/**
 * RecentItemsCard - Dashboard card showing recent items with thumbnails
 *
 * Displays recent items from Media, Review, or Internet Discovery with:
 * - Clickable thumbnails that open lightboxes
 * - Hover overlays with action buttons matching source pages
 * - Dismiss functionality with localStorage persistence
 * - Buffer system for smooth item removal animations
 */

import { useState } from 'react'
import { Link } from 'react-router-dom'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import {
  X,
  Play,
  Eye,
  Check,
  Trash2,
  UserPlus,
  ExternalLink,
  ListVideo,
  EyeOff,
  LucideIcon
} from 'lucide-react'
import { api } from '../lib/api'
import { notificationManager } from '../lib/notificationManager'
import { isVideoFile } from '../lib/utils'
import EnhancedLightbox from './EnhancedLightbox'
import ThrottledImage from './ThrottledImage'
import { invalidateAllFileCaches } from '../lib/cacheInvalidation'

// Types for items from each location
export interface MediaItem {
  id: number
  file_path: string
  filename: string
  source: string
  platform: string
  media_type: string
  file_size: number
  added_at: string
  width: number | null
  height: number | null
}

export interface ReviewItem extends MediaItem {
  face_recognition: {
    scanned: boolean
    matched: boolean
    confidence: number | null
    matched_person: string | null
  } | null
}

export interface DiscoveryItem {
  id: number
  video_id: string
  title: string
  thumbnail: string
  channel_name: string
  platform: string
  duration: number
  max_resolution: number | null
  status: string
  discovered_at: string
  url: string
  view_count: number
  upload_date: string | null
  celebrity_name: string
}

type RecentItem = MediaItem | ReviewItem | DiscoveryItem

interface RecentItemsCardProps {
  title: string
  icon: LucideIcon
  items: RecentItem[]
  allItems: RecentItem[] // Full buffer for lightbox navigation
  totalCount: number
  location: 'media' | 'review' | 'internet_discovery'
  viewAllLink: string
  onDismiss: () => void
  onItemAction: (itemId: number | string) => void
  gradientFrom: string
  gradientTo: string
  borderColor: string
  iconColor: string
}

// Helper to check if item is a discovery item
function isDiscoveryItem(item: RecentItem): item is DiscoveryItem {
  return 'video_id' in item
}

// Helper to check if media/review item is video
function isMediaVideo(item: MediaItem | ReviewItem): boolean {
  return item.media_type === 'video' || isVideoFile(item.filename)
}

// Format duration for videos
function formatDuration(seconds: number): string {
  if (!seconds) return ''
  const h = Math.floor(seconds / 3600)
  const m = Math.floor((seconds % 3600) / 60)
  const s = seconds % 60
  if (h > 0) return `${h}:${m.toString().padStart(2, '0')}:${s.toString().padStart(2, '0')}`
  return `${m}:${s.toString().padStart(2, '0')}`
}

export function RecentItemsCard({
  title,
  icon: Icon,
  items,
  allItems,
  totalCount,
  location,
  viewAllLink,
  onDismiss,
  onItemAction,
  gradientFrom,
  gradientTo,
  borderColor,
  iconColor
}: RecentItemsCardProps) {
  const queryClient = useQueryClient()

  // Lightbox state for media/review
  const [lightboxOpen, setLightboxOpen] = useState(false)
  const [lightboxIndex, setLightboxIndex] = useState(0)

  // Video preview state for internet discovery
  const [previewVideo, setPreviewVideo] = useState<DiscoveryItem | null>(null)

  // Add face reference modal state
  const [showAddRefModal, setShowAddRefModal] = useState(false)
  const [addRefFile, setAddRefFile] = useState<string | null>(null)
  const [addRefPersonName, setAddRefPersonName] = useState('')

  // ===================
  // MUTATIONS
  // ===================

  // Media: Delete
  const deleteMediaMutation = useMutation({
    mutationFn: (filePath: string) => api.batchDeleteMedia([filePath]),
    onSuccess: () => {
      invalidateAllFileCaches(queryClient)
      // Notification handled by websocket batch_delete_completed in App.tsx
    },
    onError: (err) => notificationManager.deleteError('item', err)
  })

  // Media: Move to Review
  const moveToReviewMutation = useMutation({
    mutationFn: (filePath: string) => api.moveToReview([filePath]),
    onSuccess: () => {
      invalidateAllFileCaches(queryClient)
      notificationManager.movedToReview(1)
    },
    onError: (err) => notificationManager.moveError('item', err)
  })

  // Review: Keep (move to media)
  const keepMutation = useMutation({
    mutationFn: (filePath: string) => api.reviewKeep(filePath, ''),
    onSuccess: () => {
      invalidateAllFileCaches(queryClient)
      notificationManager.kept('Image')
    },
    onError: (err) => notificationManager.moveError('item', err)
  })

  // Review: Delete
  const deleteReviewMutation = useMutation({
    mutationFn: (filePath: string) => api.reviewDelete(filePath),
    onSuccess: () => {
      invalidateAllFileCaches(queryClient)
      // Notification handled by websocket in App.tsx
    },
    onError: (err) => notificationManager.deleteError('item', err)
  })

  // Add face reference (works for both media and review)
  const addReferenceMutation = useMutation({
    mutationFn: ({ filePath, personName }: { filePath: string; personName: string }) =>
      api.addFaceReference(filePath, personName),
    onSuccess: (_, variables) => {
      invalidateAllFileCaches(queryClient)
      notificationManager.faceReferenceAdded(variables.personName)
      setShowAddRefModal(false)
      setAddRefFile(null)
      setAddRefPersonName('')
    },
    onError: (err) => notificationManager.faceReferenceError(err)
  })

  // Quick add face reference (automatic, no modal)
  const quickAddFaceMutation = useMutation({
    mutationFn: (filePath: string) => api.addFaceReference(filePath, undefined, true),
    onSuccess: (data) => {
      invalidateAllFileCaches(queryClient)
      notificationManager.info('Processing', data.message, '⏳')
    },
    onError: (err: any) => {
      const errorMessage = err?.response?.data?.detail || err?.message || 'Failed to add face reference'
      notificationManager.error('Add Reference Failed', errorMessage, '❌')
    }
  })

  // Internet Discovery: Add to queue
  const addToQueueMutation = useMutation({
    mutationFn: (video: DiscoveryItem) => api.post('/celebrity/queue/add', {
      platform: video.platform,
      video_id: video.video_id,
      url: video.url,
      title: video.title,
      thumbnail: video.thumbnail,
      duration: video.duration,
      channel_name: video.channel_name,
      celebrity_name: video.celebrity_name
    }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['dashboard-recent-items'] })
      queryClient.invalidateQueries({ queryKey: ['video-queue'] })
      notificationManager.success('Added to Queue', 'Video added to download queue')
    },
    onError: (err) => notificationManager.apiError('Add to Queue', err)
  })

  // Internet Discovery: Update status (ignore)
  const updateStatusMutation = useMutation({
    mutationFn: ({ videoId, status }: { videoId: number; status: string }) =>
      api.put(`/celebrity/videos/${videoId}/status`, { status }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['dashboard-recent-items'] })
      notificationManager.success('Status Updated', 'Video marked as ignored')
    },
    onError: (err) => notificationManager.apiError('Update Status', err)
  })

  // ===================
  // ACTION HANDLERS
  // ===================

  const handleMediaDelete = (item: MediaItem) => {
    if (confirm(`Delete "${item.filename}"?`)) {
      onItemAction(item.id)
      deleteMediaMutation.mutate(item.file_path)
    }
  }

  const handleMoveToReview = (item: MediaItem) => {
    onItemAction(item.id)
    moveToReviewMutation.mutate(item.file_path)
  }

  const handleReviewKeep = (item: ReviewItem) => {
    onItemAction(item.id)
    keepMutation.mutate(item.file_path)
  }

  const handleReviewDelete = (item: ReviewItem) => {
    if (confirm(`Delete "${item.filename}"?`)) {
      onItemAction(item.id)
      deleteReviewMutation.mutate(item.file_path)
    }
  }

  const handleAddReference = (filePath: string) => {
    setAddRefFile(filePath)
    setShowAddRefModal(true)
  }

  const handleDiscoveryAddToQueue = (item: DiscoveryItem) => {
    onItemAction(item.id)
    addToQueueMutation.mutate(item)
  }

  const handleDiscoveryIgnore = (item: DiscoveryItem) => {
    onItemAction(item.id)
    updateStatusMutation.mutate({ videoId: item.id, status: 'ignored' })
  }

  // ===================
  // LIGHTBOX HELPERS
  // ===================

  const openLightbox = (index: number) => {
    setLightboxIndex(index)
    setLightboxOpen(true)
  }

  const getLightboxItems = () => {
    // Use allItems (buffer) for lightbox navigation
    return allItems.filter(item => !isDiscoveryItem(item)) as (MediaItem | ReviewItem)[]
  }

  // ===================
  // RENDER THUMBNAIL
  // ===================

  const renderThumbnail = (item: RecentItem, index: number) => {
    if (isDiscoveryItem(item)) {
      // Internet Discovery thumbnail
      return (
        <div
          key={item.id}
          className="group relative w-28 h-20 flex-shrink-0 rounded-lg overflow-hidden cursor-pointer hover:ring-2 hover:ring-red-500 transition-all"
          onClick={() => setPreviewVideo(item)}
        >
          {/* Thumbnail */}
          {item.thumbnail ? (
            <img
              src={`/api/celebrity/thumbnail/${item.video_id}`}
              alt={item.title}
              className="w-full h-full object-cover"
              loading="lazy"
              onError={(e) => {
                const target = e.target as HTMLImageElement
                if (target.src !== item.thumbnail) {
                  target.src = item.thumbnail
                }
              }}
            />
          ) : (
            <div className="w-full h-full bg-slate-700 flex items-center justify-center">
              <Play className="w-6 h-6 text-slate-400" />
            </div>
          )}

          {/* Play icon overlay */}
          <div className="absolute inset-0 flex items-center justify-center">
            <div className="bg-black/50 rounded-full p-1.5">
              <Play className="w-4 h-4 text-white fill-white" />
            </div>
          </div>

          {/* Duration badge */}
          {item.duration > 0 && (
            <div className="absolute bottom-1 right-1 px-1 py-0.5 bg-black/80 text-white text-[10px] rounded">
              {formatDuration(item.duration)}
            </div>
          )}

          {/* Hover overlay with actions */}
          <div className="absolute inset-0 bg-black/70 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center gap-1">
            <button
              onClick={(e) => { e.stopPropagation(); setPreviewVideo(item) }}
              className="p-1.5 bg-red-600 hover:bg-red-700 rounded-full"
              title="Preview"
            >
              <Play className="w-3 h-3 text-white fill-white" />
            </button>
            {item.platform === 'youtube' && (
              <a
                href={item.url}
                target="_blank"
                rel="noopener noreferrer"
                onClick={(e) => e.stopPropagation()}
                className="p-1.5 bg-white/20 hover:bg-white/30 rounded-full"
                title="Open on YouTube"
              >
                <ExternalLink className="w-3 h-3 text-white" />
              </a>
            )}
            <button
              onClick={(e) => { e.stopPropagation(); handleDiscoveryAddToQueue(item) }}
              className="p-1.5 bg-indigo-600 hover:bg-indigo-700 rounded-full"
              title="Add to Queue"
            >
              <ListVideo className="w-3 h-3 text-white" />
            </button>
            <button
              onClick={(e) => { e.stopPropagation(); handleDiscoveryIgnore(item) }}
              className="p-1.5 bg-slate-600 hover:bg-slate-700 rounded-full"
              title="Ignore"
            >
              <EyeOff className="w-3 h-3 text-white" />
            </button>
          </div>

          {/* Source label */}
          <div className="absolute bottom-0 left-0 right-0 bg-gradient-to-t from-black/80 to-transparent p-1 opacity-0 group-hover:opacity-0">
            <p className="text-white text-[10px] truncate">{item.channel_name}</p>
          </div>
        </div>
      )
    }

    // Media or Review thumbnail
    const mediaItem = item as MediaItem | ReviewItem
    const isVideo = isMediaVideo(mediaItem)
    const isReview = location === 'review'

    return (
      <div
        key={mediaItem.id}
        className={`group relative w-20 h-20 flex-shrink-0 rounded-lg overflow-hidden cursor-pointer hover:ring-2 transition-all ${
          isReview ? 'hover:ring-orange-500' : 'hover:ring-blue-500'
        }`}
        onClick={() => openLightbox(index)}
      >
        {/* Thumbnail */}
        <ThrottledImage
          src={api.getMediaThumbnailUrl(mediaItem.file_path, mediaItem.media_type as 'image' | 'video')}
          alt={mediaItem.filename}
          className="w-full h-full object-cover"
          showErrorPlaceholder={true}
          priority={index < 5}
        />

        {/* Video indicator */}
        {isVideo && (
          <div className="absolute top-1 right-1 bg-black/70 rounded-full p-0.5">
            <Play className="w-2.5 h-2.5 text-white fill-white" />
          </div>
        )}

        {/* Hover overlay with actions */}
        <div className="absolute inset-0 bg-black/70 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center gap-1 p-1">
          {isReview ? (
            // Review actions
            <>
              <button
                onClick={(e) => { e.stopPropagation(); handleReviewKeep(mediaItem as ReviewItem) }}
                className="p-1.5 bg-green-600 hover:bg-green-700 rounded-full"
                title="Keep"
              >
                <Check className="w-3 h-3 text-white" />
              </button>
              <button
                onClick={(e) => { e.stopPropagation(); handleAddReference(mediaItem.file_path) }}
                className="p-1.5 bg-blue-600 hover:bg-blue-700 rounded-full"
                title="Add Reference"
              >
                <UserPlus className="w-3 h-3 text-white" />
              </button>
              <button
                onClick={(e) => { e.stopPropagation(); handleReviewDelete(mediaItem as ReviewItem) }}
                className="p-1.5 bg-red-600 hover:bg-red-700 rounded-full"
                title="Delete"
              >
                <Trash2 className="w-3 h-3 text-white" />
              </button>
            </>
          ) : (
            // Media actions
            <>
              <button
                onClick={(e) => { e.stopPropagation(); handleMoveToReview(mediaItem) }}
                className="p-1.5 bg-orange-600 hover:bg-orange-700 rounded-full"
                title="Move to Review"
              >
                <Eye className="w-3 h-3 text-white" />
              </button>
              <button
                onClick={(e) => { e.stopPropagation(); handleAddReference(mediaItem.file_path) }}
                className="p-1.5 bg-blue-600 hover:bg-blue-700 rounded-full"
                title="Add Reference"
              >
                <UserPlus className="w-3 h-3 text-white" />
              </button>
              <button
                onClick={(e) => { e.stopPropagation(); handleMediaDelete(mediaItem) }}
                className="p-1.5 bg-red-600 hover:bg-red-700 rounded-full"
                title="Delete"
              >
                <Trash2 className="w-3 h-3 text-white" />
              </button>
            </>
          )}
        </div>

        {/* Source label on hover */}
        <div className="absolute bottom-0 left-0 right-0 bg-gradient-to-t from-black/80 to-transparent p-1 opacity-0 group-hover:opacity-100 transition-opacity">
          <p className="text-white text-[9px] truncate">{mediaItem.source}</p>
        </div>
      </div>
    )
  }

  // ===================
  // RENDER
  // ===================

  if (items.length === 0) return null

  return (
    <>
      <div className={`card-glass rounded-xl bg-gradient-to-r ${gradientFrom} ${gradientTo} border ${borderColor} p-4`}>
        {/* Header */}
        <div className="flex items-center justify-between mb-3">
          <div className="flex items-center gap-3">
            <Icon className={`w-5 h-5 ${iconColor}`} />
            <h3 className="font-semibold text-foreground">{title}</h3>
            <span className="px-2 py-0.5 bg-white/20 dark:bg-black/20 rounded-full text-xs font-medium">
              {totalCount} new
            </span>
          </div>
          <div className="flex items-center gap-2">
            <Link
              to={viewAllLink}
              className="text-sm text-muted-foreground hover:text-foreground hover:underline transition-colors"
            >
              View All →
            </Link>
            <button
              onClick={onDismiss}
              className="p-1.5 text-muted-foreground hover:text-foreground hover:bg-white/20 dark:hover:bg-black/20 rounded-md transition-colors"
              title="Dismiss"
            >
              <X className="w-4 h-4" />
            </button>
          </div>
        </div>

        {/* Thumbnail Grid */}
        <div className="flex gap-3 overflow-x-auto p-1 -m-1 scrollbar-thin scrollbar-thumb-white/20 scrollbar-track-transparent">
          {items.map((item, index) => renderThumbnail(item, index))}
        </div>
      </div>

      {/* Enhanced Lightbox for Media/Review */}
      {lightboxOpen && location !== 'internet_discovery' && (
        <EnhancedLightbox
          items={getLightboxItems()}
          currentIndex={lightboxIndex}
          onClose={() => setLightboxOpen(false)}
          onNavigate={setLightboxIndex}
          onDelete={(item) => {
            const mediaItem = item as MediaItem | ReviewItem
            onItemAction(mediaItem.id)
            if (location === 'review') {
              deleteReviewMutation.mutate(mediaItem.file_path)
            } else {
              deleteMediaMutation.mutate(mediaItem.file_path)
            }
          }}
          getPreviewUrl={(item) => api.getMediaPreviewUrl((item as MediaItem).file_path)}
          getThumbnailUrl={(item) => api.getMediaThumbnailUrl((item as MediaItem).file_path, (item as MediaItem).media_type as 'image' | 'video')}
          isVideo={(item) => isMediaVideo(item as MediaItem)}
          renderActions={(item) => {
            const mediaItem = item as MediaItem | ReviewItem
            if (location === 'review') {
              return (
                <>
                  <button
                    onClick={() => { handleReviewKeep(mediaItem as ReviewItem); setLightboxOpen(false) }}
                    className="flex items-center gap-2 px-3 py-1.5 md:px-4 md:py-2 bg-green-600 hover:bg-green-700 text-white text-sm md:text-base rounded-lg transition-colors"
                  >
                    <Check className="w-4 h-4" />
                    <span className="hidden sm:inline">Keep</span>
                  </button>
                  <button
                    onClick={() => handleAddReference(mediaItem.file_path)}
                    className="flex items-center gap-2 px-3 py-1.5 md:px-4 md:py-2 bg-blue-600 hover:bg-blue-700 text-white text-sm md:text-base rounded-lg transition-colors"
                  >
                    <UserPlus className="w-4 h-4" />
                    <span className="hidden sm:inline">Add Ref</span>
                  </button>
                  <button
                    onClick={() => quickAddFaceMutation.mutate(mediaItem.file_path)}
                    disabled={quickAddFaceMutation.isPending}
                    className="flex items-center gap-2 px-3 py-1.5 md:px-4 md:py-2 bg-purple-600 hover:bg-purple-700 text-white text-sm md:text-base rounded-lg transition-colors disabled:opacity-50"
                  >
                    <UserPlus className="w-4 h-4" />
                    <span className="hidden sm:inline">{quickAddFaceMutation.isPending ? 'Adding...' : 'Quick Add'}</span>
                  </button>
                  <button
                    onClick={() => { handleReviewDelete(mediaItem as ReviewItem); setLightboxOpen(false) }}
                    className="flex items-center gap-2 px-3 py-1.5 md:px-4 md:py-2 bg-red-600 hover:bg-red-700 text-white text-sm md:text-base rounded-lg transition-colors"
                  >
                    <Trash2 className="w-4 h-4" />
                    <span className="hidden sm:inline">Delete</span>
                  </button>
                </>
              )
            } else {
              return (
                <>
                  <button
                    onClick={() => { handleMoveToReview(mediaItem); setLightboxOpen(false) }}
                    className="flex items-center gap-2 px-3 py-1.5 md:px-4 md:py-2 bg-orange-600 hover:bg-orange-700 text-white text-sm md:text-base rounded-lg transition-colors"
                  >
                    <Eye className="w-4 h-4" />
                    <span className="hidden sm:inline">Review</span>
                  </button>
                  <button
                    onClick={() => handleAddReference(mediaItem.file_path)}
                    className="flex items-center gap-2 px-3 py-1.5 md:px-4 md:py-2 bg-blue-600 hover:bg-blue-700 text-white text-sm md:text-base rounded-lg transition-colors"
                  >
                    <UserPlus className="w-4 h-4" />
                    <span className="hidden sm:inline">Add Ref</span>
                  </button>
                  <button
                    onClick={() => quickAddFaceMutation.mutate(mediaItem.file_path)}
                    disabled={quickAddFaceMutation.isPending}
                    className="flex items-center gap-2 px-3 py-1.5 md:px-4 md:py-2 bg-purple-600 hover:bg-purple-700 text-white text-sm md:text-base rounded-lg transition-colors disabled:opacity-50"
                  >
                    <UserPlus className="w-4 h-4" />
                    <span className="hidden sm:inline">{quickAddFaceMutation.isPending ? 'Adding...' : 'Quick Add'}</span>
                  </button>
                  <button
                    onClick={() => { handleMediaDelete(mediaItem); setLightboxOpen(false) }}
                    className="flex items-center gap-2 px-3 py-1.5 md:px-4 md:py-2 bg-red-600 hover:bg-red-700 text-white text-sm md:text-base rounded-lg transition-colors"
                  >
                    <Trash2 className="w-4 h-4" />
                    <span className="hidden sm:inline">Delete</span>
                  </button>
                </>
              )
            }
          }}
        />
      )}

      {/* Video Preview Modal for Internet Discovery */}
      {previewVideo && (
        <div
          className="fixed inset-0 bg-black/95 z-50 flex items-center justify-center"
          onClick={() => setPreviewVideo(null)}
        >
          <div className="relative w-full max-w-4xl mx-4" onClick={(e) => e.stopPropagation()}>
            {/* Close button */}
            <button
              onClick={() => setPreviewVideo(null)}
              className="absolute -top-12 right-0 p-2 text-white/70 hover:text-white transition-colors"
            >
              <X className="w-6 h-6" />
            </button>

            {/* Video title */}
            <h3 className="absolute -top-12 left-0 text-white font-medium truncate max-w-[80%]">
              {previewVideo.title}
            </h3>

            {/* Video preview */}
            <div className="relative aspect-video bg-black rounded-xl overflow-hidden">
              {previewVideo.platform === 'youtube' ? (
                <iframe
                  src={`https://www.youtube.com/embed/${previewVideo.video_id}?autoplay=1&rel=0`}
                  title={previewVideo.title}
                  className="absolute inset-0 w-full h-full"
                  allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
                  allowFullScreen
                />
              ) : (
                <div className="absolute inset-0 flex items-center justify-center">
                  <img
                    src={previewVideo.thumbnail}
                    alt={previewVideo.title}
                    className="max-w-full max-h-full object-contain"
                  />
                </div>
              )}
            </div>

            {/* Video info */}
            <div className="mt-4 flex items-center justify-between text-white/70 text-sm">
              <div className="flex items-center gap-4">
                <span>{previewVideo.channel_name}</span>
                {previewVideo.duration > 0 && <span>{formatDuration(previewVideo.duration)}</span>}
                {previewVideo.max_resolution && <span className="text-emerald-400">{previewVideo.max_resolution}p</span>}
              </div>
              <span className="text-indigo-400 font-medium">{previewVideo.celebrity_name}</span>
            </div>

            {/* Action buttons */}
            <div className="mt-4 flex items-center justify-center gap-3">
              {previewVideo.platform === 'youtube' && (
                <a
                  href={previewVideo.url}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="flex items-center gap-2 px-4 py-2 bg-white/10 hover:bg-white/20 text-white rounded-lg transition-colors"
                >
                  <ExternalLink className="w-4 h-4" />
                  <span>Open on YouTube</span>
                </a>
              )}
              <button
                onClick={() => { handleDiscoveryAddToQueue(previewVideo); setPreviewVideo(null) }}
                className="flex items-center gap-2 px-4 py-2 bg-indigo-600 hover:bg-indigo-700 text-white rounded-lg transition-colors"
              >
                <ListVideo className="w-4 h-4" />
                <span>Add to Queue</span>
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Add Face Reference Modal */}
      {showAddRefModal && (
        <div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4" onClick={() => setShowAddRefModal(false)}>
          <div className="bg-card rounded-xl p-6 max-w-md w-full" onClick={(e) => e.stopPropagation()}>
            <h3 className="text-lg font-semibold mb-4">Add Face Reference</h3>
            <input
              type="text"
              value={addRefPersonName}
              onChange={(e) => setAddRefPersonName(e.target.value)}
              placeholder="Person name..."
              className="w-full px-4 py-2 bg-secondary rounded-lg border border-border focus:outline-none focus:ring-2 focus:ring-primary mb-4"
              autoFocus
            />
            <div className="flex justify-end gap-3">
              <button
                onClick={() => { setShowAddRefModal(false); setAddRefPersonName('') }}
                className="px-4 py-2 text-muted-foreground hover:text-foreground transition-colors"
              >
                Cancel
              </button>
              <button
                onClick={() => {
                  if (addRefFile && addRefPersonName.trim()) {
                    addReferenceMutation.mutate({ filePath: addRefFile, personName: addRefPersonName.trim() })
                  }
                }}
                disabled={!addRefPersonName.trim() || addReferenceMutation.isPending}
                className="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg disabled:opacity-50 transition-colors"
              >
                {addReferenceMutation.isPending ? 'Adding...' : 'Add Reference'}
              </button>
            </div>
          </div>
        </div>
      )}
    </>
  )
}
