import { useState, useEffect, useCallback, useRef, useMemo } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { Link, useSearchParams } from 'react-router-dom'
import { useBreadcrumb } from '../hooks/useBreadcrumb'
import { breadcrumbConfig } from '../config/breadcrumbConfig'
import {
  Star, RefreshCw, Download, EyeOff, Eye,
  ChevronDown, Play, Youtube, Tv,
  Film, Camera, Award, Sparkles, ExternalLink, Loader2,
  Video, Filter, ChevronLeft, ChevronRight,
  CheckSquare, Square, XSquare, ListVideo, Calendar,
  X, Trash2, Settings
} from 'lucide-react'
import { FilterBar } from '../components/FilterPopover'
import { api } from '../lib/api'
import { LucideIcon } from 'lucide-react'
import { formatDateOnly } from '../lib/utils'
import { notificationManager } from '../lib/notificationManager'

// Content type configurations
const CONTENT_TYPES: Record<string, { label: string; icon: LucideIcon; color: string }> = {
  interview: { label: 'Interview', icon: Tv, color: 'text-blue-500 bg-blue-500/10' },
  red_carpet: { label: 'Red Carpet', icon: Award, color: 'text-red-500 bg-red-500/10' },
  premiere: { label: 'Premiere', icon: Film, color: 'text-purple-500 bg-purple-500/10' },
  photoshoot: { label: 'Photoshoot', icon: Camera, color: 'text-pink-500 bg-pink-500/10' },
  bts: { label: 'Behind the Scenes', icon: Sparkles, color: 'text-yellow-500 bg-yellow-500/10' },
  other: { label: 'Other', icon: Video, color: 'text-gray-500 bg-gray-500/10' },
  all: { label: 'All Types', icon: Filter, color: 'text-slate-500 bg-slate-500/10' }
}

// Source type configurations
const SOURCE_TYPES: Record<string, { label: string; description: string }> = {
  youtube_channel: { label: 'YouTube Channel', description: 'Search within a specific channel' },
  youtube_search: { label: 'YouTube Search', description: 'Search all of YouTube' },
  youtube_rss: { label: 'YouTube RSS', description: 'Latest videos from channel RSS feed' }
}


interface CelebrityProfile {
  id: number
  name: string
  slug: string
  image_url: string | null
  notes: string | null
  enabled: boolean
  preset_count: number
  new_videos: number
  created_at: string
  updated_at: string
}

interface SearchPreset {
  id: number
  celebrity_id: number
  celebrity_name?: string
  name: string
  source_type: string
  source_value: string
  keywords: string[]
  content_type: string
  enabled: boolean
  last_checked: string | null
  check_frequency_hours: number
  results_count: number
  created_at: string
}

interface DiscoveredVideo {
  id: number
  preset_id: number
  preset_name: string
  celebrity_id: number
  celebrity_name: string
  video_id: string
  platform: string
  url: string
  title: string
  channel_name: string
  channel_id: string
  thumbnail: string
  duration: number
  upload_date: string | null
  view_count: number
  description: string
  content_type: string
  status: string
  discovered_at: string
  downloaded_path: string | null
  max_resolution: number | null
  max_width: number | null
  metadata: string | null
}

interface Stats {
  total_celebrities: number
  total_presets: number
  monitored_channels: number
  total_videos: number
  new_videos: number
  downloaded_videos: number
  by_content_type: Record<string, number>
  by_status: Record<string, number>
}

// Helper to format duration
const 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')}`
}

// Format view count
const formatViewCount = (count: number): string => {
  if (!count) return ''
  if (count >= 1000000) return `${(count / 1000000).toFixed(1)}M views`
  if (count >= 1000) return `${(count / 1000).toFixed(1)}K views`
  return `${count} views`
}

// Format resolution - uses shorter dimension for accurate labeling
// A 720x1280 portrait video is 720p, a 1920x1080 landscape video is 1080p
const formatResolution = (height: number | null, width?: number | null): string => {
  if (!height) return ''
  // Use the shorter dimension for resolution label (handles portrait videos correctly)
  const shortSide = width ? Math.min(width, height) : height
  if (shortSide >= 2160) return '4K'
  if (shortSide >= 1440) return '1440p'
  if (shortSide >= 1080) return '1080p'
  if (shortSide >= 720) return '720p'
  if (shortSide >= 480) return '480p'
  if (shortSide >= 360) return '360p'
  return `${shortSide}p`
}

// Get cached thumbnail URL - uses local proxy endpoint that caches thumbnails
const getCachedThumbnailUrl = (video: DiscoveredVideo): string => {
  // Use cached thumbnail endpoint which fetches and caches in DB
  return `/api/celebrity/thumbnail/${video.video_id}`
}

// Resolution sort options
const RESOLUTION_SORT_OPTIONS = [
  { value: '', label: 'Resolution' },
  { value: 'highest', label: 'Highest First' },
  { value: 'lowest', label: 'Lowest First' }
]

// Date sort options
const DATE_SORT_OPTIONS = [
  { value: '', label: 'Date' },
  { value: 'discovered_newest', label: 'Discovered: Newest' },
  { value: 'discovered_oldest', label: 'Discovered: Oldest' },
  { value: 'uploaded_newest', label: 'Upload: Newest' },
  { value: 'uploaded_oldest', label: 'Upload: Oldest' }
]

// Name sort options
const NAME_SORT_OPTIONS = [
  { value: '', label: 'Name' },
  { value: 'name_asc', label: 'Name: A-Z' },
  { value: 'name_desc', label: 'Name: Z-A' }
]

const ITEMS_PER_PAGE = 24

export default function InternetDiscovery() {
  const queryClient = useQueryClient()
  const [searchParams] = useSearchParams()
  const { setBreadcrumbs } = useBreadcrumb(breadcrumbConfig['/celebrities'])

  // Read URL parameters for initial filter values
  const initialStatusFilter = searchParams.get('status') || 'not_queued'
  const initialWatchedFilter = searchParams.get('watched') !== null ? searchParams.get('watched')! : 'unwatched'
  const initialSourceFilter = searchParams.get('channel_name') || ''

  // State - defaults: Eva Longoria (id=1), Highest Resolution, Not Queued, Unwatched
  const [selectedCelebrity, setSelectedCelebrity] = useState<number | null>(null)
  const [selectedCategory, _setSelectedCategory] = useState<string | null>(null)
  const [selectedPresetIds, _setSelectedPresetIds] = useState<number[]>([])
  const [statusFilter, setStatusFilter] = useState<string>(initialStatusFilter)
  const [watchedFilter, setWatchedFilter] = useState<string>(initialWatchedFilter)
  const [sourceFilter, setSourceFilter] = useState<string>(initialSourceFilter)
  const [platformFilter, setPlatformFilter] = useState<string>('')
  const [searchQuery, setSearchQuery] = useState<string>('')
  const [resolutionSort, setResolutionSort] = useState<string>('highest')
  const [dateSort, setDateSort] = useState<string>('')
  const [nameSort, setNameSort] = useState<string>('')
  const [showAddCelebrity, setShowAddCelebrity] = useState(false)
  const [showAddPreset, setShowAddPreset] = useState(false)
  const [newCelebrityName, setNewCelebrityName] = useState('')
  const [newCelebrityImage, setNewCelebrityImage] = useState('')

  // Pagination state
  const [currentPage, setCurrentPage] = useState(1)

  // Multi-select state
  const [selectedVideos, setSelectedVideos] = useState<Set<number>>(new Set())
  const [isDownloading, setIsDownloading] = useState(false)

  // Video preview state
  const [previewVideo, setPreviewVideo] = useState<DiscoveredVideo | null>(null)
  const [previewIndex, setPreviewIndex] = useState<number>(-1)
  const [viewedVideos, setViewedVideos] = useState<Set<number>>(new Set())  // Track videos viewed in current session
  const [previewVideos, setPreviewVideos] = useState<DiscoveredVideo[]>([])  // Snapshot of videos when preview opens

  // Video player state
  const [showMetadata, setShowMetadata] = useState(false)
  const lightboxRef = useRef<HTMLDivElement>(null)
  const thumbnailStripRef = useRef<HTMLDivElement>(null)

  // Background search job state
  const [searchJobId, setSearchJobId] = useState<string | null>(null)
  const [showSearchProgress, setShowSearchProgress] = useState(false)

  // New preset form state
  const [newPreset, setNewPreset] = useState({
    name: '',
    source_type: 'youtube_search',
    source_value: '',
    keywords: '',
    content_type: 'all'
  })

  // Update filters when URL parameters change
  useEffect(() => {
    const status = searchParams.get('status')
    const watched = searchParams.get('watched')
    const channel = searchParams.get('channel_name')

    if (status !== null) setStatusFilter(status)
    if (watched !== null) setWatchedFilter(watched)
    if (channel !== null) setSourceFilter(channel)
  }, [searchParams])

  // Fetch celebrities
  const { data: celebritiesData, refetch: refetchCelebrities } = useQuery({
    queryKey: ['celebrities'],
    queryFn: async () => {
      const response = await api.get<{ profiles: CelebrityProfile[] }>('/celebrity/profiles')
      return response.profiles || []
    }
  })
  const celebrities = celebritiesData || []

  // Fetch presets for selected celebrity/category
  const { refetch: refetchPresets } = useQuery({
    queryKey: ['celebrity-presets', selectedCelebrity, selectedCategory],
    queryFn: async () => {
      let url = '/celebrity/presets'
      const params: string[] = []
      if (selectedCelebrity) params.push(`celebrity_id=${selectedCelebrity}`)
      if (selectedCategory) params.push(`category=${selectedCategory}`)
      if (params.length > 0) url += '?' + params.join('&')
      const response = await api.get<{ presets: SearchPreset[] }>(url)
      return response.presets || []
    },
    enabled: true
  })

  // Fetch background tasks for YouTube monitor status
  const { data: backgroundTasks } = useQuery({
    queryKey: ['background-tasks'],
    queryFn: () => api.getBackgroundTasks(),
    refetchInterval: 2000,
    staleTime: 1000,
  })
  const youtubeMonitorTask = backgroundTasks?.tasks?.find((t: any) => t.task_id === 'youtube_monitor')

  // Fetch discovered videos with pagination
  const { data: videosData, refetch: refetchVideos, isLoading: loadingVideos } = useQuery({
    queryKey: ['discovered-videos', selectedCelebrity, selectedCategory, selectedPresetIds, statusFilter, watchedFilter, sourceFilter, platformFilter, resolutionSort, dateSort, nameSort, searchQuery, currentPage],
    queryFn: async () => {
      const offset = (currentPage - 1) * ITEMS_PER_PAGE
      let url = `/celebrity/videos?limit=${ITEMS_PER_PAGE}&offset=${offset}`
      if (selectedCelebrity) url += `&celebrity_id=${selectedCelebrity}`
      if (selectedCategory) url += `&category=${selectedCategory}`
      // Support multiple preset IDs for grouped presets
      if (selectedPresetIds.length > 0) {
        url += `&preset_ids=${selectedPresetIds.join(',')}`
      }
      if (statusFilter && statusFilter !== 'all') url += `&status=${statusFilter}`
      if (watchedFilter) url += `&watched=${watchedFilter}`
      if (sourceFilter) url += `&channel_name=${encodeURIComponent(sourceFilter)}`
      if (platformFilter) url += `&platform=${platformFilter}`
      if (resolutionSort) url += `&resolution_sort=${resolutionSort}`
      if (dateSort) url += `&date_sort=${dateSort}`
      if (nameSort) url += `&name_sort=${nameSort}`
      if (searchQuery) url += `&search=${encodeURIComponent(searchQuery)}`
      const response = await api.get<{ videos: DiscoveredVideo[]; total: number }>(url)
      return response
    }
  })
  const videos = videosData?.videos || []
  const totalVideos = videosData?.total || 0
  const totalPages = Math.ceil(totalVideos / ITEMS_PER_PAGE)

  // Fetch stats
  const { data: statsData } = useQuery({
    queryKey: ['celebrity-stats'],
    queryFn: async () => {
      const response = await api.get<{ stats: Stats }>('/celebrity/stats')
      return response.stats
    }
  })
  const stats = statsData

  // Fetch unique sources (channel names) for filter dropdown - filtered by current criteria
  const { data: sourcesData } = useQuery({
    queryKey: ['celebrity-sources', selectedCelebrity, selectedCategory, selectedPresetIds, statusFilter, watchedFilter, platformFilter],
    queryFn: async () => {
      const params: string[] = []
      if (selectedCelebrity) params.push(`celebrity_id=${selectedCelebrity}`)
      if (selectedCategory) params.push(`category=${selectedCategory}`)
      if (selectedPresetIds.length > 0) params.push(`preset_ids=${selectedPresetIds.join(',')}`)
      if (statusFilter && statusFilter !== 'all') params.push(`status=${statusFilter}`)
      if (watchedFilter) params.push(`watched=${watchedFilter}`)
      if (platformFilter) params.push(`platform=${platformFilter}`)
      const url = '/celebrity/sources' + (params.length > 0 ? '?' + params.join('&') : '')
      const response = await api.get<{ sources: string[] }>(url)
      return response.sources || []
    }
  })
  // Process sources to consolidate Easynews entries into TV/Movies categories
  const uniqueSources = useMemo(() => {
    const sources = sourcesData || []
    const consolidatedSources: string[] = []
    let hasEasynewsTV = false
    let hasEasynewsMovies = false

    for (const source of sources) {
      if (source.startsWith('Easynews - tv:')) {
        hasEasynewsTV = true
      } else if (source.startsWith('Easynews - movie:')) {
        hasEasynewsMovies = true
      } else {
        consolidatedSources.push(source)
      }
    }

    // Add consolidated Easynews options at the beginning
    if (hasEasynewsTV) consolidatedSources.unshift('Easynews - TV')
    if (hasEasynewsMovies) consolidatedSources.unshift('Easynews - Movies')

    return consolidatedSources
  }, [sourcesData])

  // Fetch recently viewed videos (last 10 watched, sorted by when they were watched)
  const { data: recentlyViewedData, refetch: refetchRecentlyViewed } = useQuery({
    queryKey: ['celebrity-recently-viewed', selectedCelebrity],
    queryFn: async () => {
      let url = '/celebrity/videos?limit=10&watched=watched&date_sort=watched_newest'
      if (selectedCelebrity) url += `&celebrity_id=${selectedCelebrity}`
      const response = await api.get<{ videos: DiscoveredVideo[]; total: number }>(url)
      return response.videos || []
    },
    staleTime: 0,  // Always consider data stale so it refreshes on focus/mount
    refetchOnWindowFocus: true
  })
  const recentlyViewedVideos = recentlyViewedData || []

  // Create celebrity mutation
  const createCelebrityMutation = useMutation({
    mutationFn: async (data: { name: string; image_url?: string }) => {
      return await api.post('/celebrity/profiles', data)
    },
    onSuccess: () => {
      refetchCelebrities()
      setShowAddCelebrity(false)
      setNewCelebrityName('')
      setNewCelebrityImage('')
      notificationManager.success('Success', 'Celebrity profile created')
    },
    onError: (error: any) => {
      notificationManager.error('Error', error.message || 'Failed to create profile')
    }
  })

  // Create preset mutation
  const createPresetMutation = useMutation({
    mutationFn: async (data: any) => {
      return await api.post('/celebrity/presets', data)
    },
    onSuccess: () => {
      refetchPresets()
      refetchCelebrities()
      setShowAddPreset(false)
      setNewPreset({ name: '', source_type: 'youtube_search', source_value: '', keywords: '', content_type: 'all' })
      notificationManager.success('Success', 'Search preset created')
    },
    onError: (error: any) => {
      notificationManager.error('Error', error.message || 'Failed to create preset')
    }
  })

  // Fetch search job status
  const { data: searchJobData } = useQuery({
    queryKey: ['celebrity-search-job', searchJobId],
    queryFn: async () => {
      if (!searchJobId) return null
      const response = await api.get<{ job: any }>(`/celebrity/search-jobs/${searchJobId}`)
      return response.job
    },
    enabled: !!searchJobId,
    refetchInterval: searchJobId ? 1000 : false // Poll every second while job is running
  })

  // Handle search job completion
  useEffect(() => {
    if (searchJobData?.status === 'completed') {
      refetchVideos()
      refetchPresets()
      refetchCelebrities()
      queryClient.invalidateQueries({ queryKey: ['celebrity-stats'] })
      notificationManager.success('Search Complete', `Found ${searchJobData.total_new_videos || 0} new videos across ${searchJobData.total_presets || 0} presets`)
    }
  }, [searchJobData?.status])

  // Clear source filter if currently selected source is no longer available
  useEffect(() => {
    if (sourceFilter && uniqueSources.length > 0 && !uniqueSources.includes(sourceFilter)) {
      setSourceFilter('')
    }
  }, [uniqueSources, sourceFilter])

  // Update video status mutation
  const updateVideoStatusMutation = useMutation({
    mutationFn: async ({ videoId, status }: { videoId: number; status: string }) => {
      return await api.put(`/celebrity/videos/${videoId}/status`, { status })
    },
    onSuccess: (_, variables) => {
      // Only refetch main videos list if we're not just marking as watched during preview
      // (to avoid the list changing while user is navigating)
      if (variables.status !== 'watched') {
        refetchVideos()
      }
      queryClient.invalidateQueries({ queryKey: ['celebrity-stats'] })
      // Refetch recently viewed to show newly watched videos
      refetchRecentlyViewed()
    }
  })

  // Bulk update status mutation
  const bulkUpdateStatusMutation = useMutation({
    mutationFn: async ({ videoIds, status }: { videoIds: number[]; status: string }) => {
      return await api.put('/celebrity/videos/bulk-status', { video_ids: videoIds, status })
    },
    onSuccess: (data: any) => {
      refetchVideos()
      queryClient.invalidateQueries({ queryKey: ['celebrity-stats'] })
      refetchRecentlyViewed()
      setSelectedVideos(new Set())
      notificationManager.success('Updated', `${data.updated_count || 0} videos updated`)
    }
  })

  // Delete video mutation
  const deleteVideoMutation = useMutation({
    mutationFn: async (videoId: number) => {
      return await api.delete(`/celebrity/videos/${videoId}`)
    },
    onSuccess: () => {
      refetchVideos()
      queryClient.invalidateQueries({ queryKey: ['celebrity-stats'] })
      queryClient.invalidateQueries({ queryKey: ['celebrity-categories'] })
      notificationManager.success('Deleted', 'Video removed from discovery')
    },
    onError: (error: any) => {
      notificationManager.error('Error', error.message || 'Failed to delete video')
    }
  })

  // Bulk delete videos mutation
  const bulkDeleteVideosMutation = useMutation({
    mutationFn: async (videoIds: number[]) => {
      // Delete one by one since there's no bulk endpoint
      const results = await Promise.allSettled(
        videoIds.map(id => api.delete(`/celebrity/videos/${id}`))
      )
      const deleted = results.filter(r => r.status === 'fulfilled').length
      return { deleted_count: deleted }
    },
    onSuccess: (data: any) => {
      refetchVideos()
      queryClient.invalidateQueries({ queryKey: ['celebrity-stats'] })
      queryClient.invalidateQueries({ queryKey: ['celebrity-categories'] })
      setSelectedVideos(new Set())
      notificationManager.success('Deleted', `${data.deleted_count || 0} videos removed`)
    }
  })

  // Cleanup unavailable videos mutation
  const cleanupUnavailableMutation = useMutation({
    mutationFn: async (checkAll: boolean = false) => {
      return await api.post(`/celebrity/cleanup-unavailable?limit=100&check_all=${checkAll}`)
    },
    onSuccess: () => {
      notificationManager.success('Cleanup Started', 'Checking videos for availability in background')
      // Refetch after a delay to see results
      setTimeout(() => {
        refetchVideos()
        queryClient.invalidateQueries({ queryKey: ['celebrity-stats'] })
      }, 5000)
    },
    onError: (error: any) => {
      notificationManager.error('Error', error.message || 'Failed to start cleanup')
    }
  })

  // Add to queue mutation
  const addToQueueMutation = useMutation({
    mutationFn: async (video: DiscoveredVideo) => {
      return await api.post('/celebrity/queue/add', {
        platform: video.platform,
        video_id: video.video_id,
        url: video.url,
        title: video.title,
        channel_name: video.channel_name,
        thumbnail: video.thumbnail,
        duration: video.duration,
        upload_date: video.upload_date,
        view_count: video.view_count,
        max_resolution: video.max_resolution,
        source_type: 'celebrity',
        source_id: video.celebrity_id,
        source_name: video.celebrity_name
      })
    },
    onSuccess: () => {
      notificationManager.success('Added to Queue', 'Video added to download queue')
    },
    onError: (error: any) => {
      if (error.message?.includes('already exists')) {
        notificationManager.info('Already in Queue', 'This video is already in the download queue')
      } else {
        notificationManager.error('Error', error.message || 'Failed to add to queue')
      }
    }
  })

  // Add selected videos to queue mutation
  const addSelectedToQueueMutation = useMutation({
    mutationFn: async (videoIds: number[]) => {
      const videosToAdd = videos.filter(v => videoIds.includes(v.id))
      return await api.post('/celebrity/queue/bulk-add', {
        items: videosToAdd.map(v => ({
          platform: v.platform,
          video_id: v.video_id,
          url: v.url,
          title: v.title,
          channel_name: v.channel_name,
          thumbnail: v.thumbnail,
          duration: v.duration,
          upload_date: v.upload_date,
          view_count: v.view_count,
          max_resolution: v.max_resolution,
          source_type: 'celebrity',
          source_id: v.celebrity_id,
          source_name: v.celebrity_name
        }))
      })
    },
    onSuccess: (data: any) => {
      setSelectedVideos(new Set())
      notificationManager.success('Added to Queue', `${data.added_count || 0} videos added to queue`)
    },
    onError: (error: any) => {
      notificationManager.error('Error', error.message || 'Failed to add to queue')
    }
  })

  // Easynews state
  const [easynewsStatus, setEasynewsStatus] = useState<{
    is_running: boolean
    current_search: string | null
    searches_processed: number
    total_searches: number
    results_found: number
    has_credentials: boolean
    celebrity_count: number
  }>({
    is_running: false,
    current_search: null,
    searches_processed: 0,
    total_searches: 0,
    results_found: 0,
    has_credentials: false,
    celebrity_count: 0,
  })


  // Poll for Easynews status
  useEffect(() => {
    const checkStatus = async () => {
      try {
        const data = await api.getEasynewsStatus()
        if (data.success) {
          setEasynewsStatus({
            is_running: data.status.is_running,
            current_search: data.status.current_search,
            searches_processed: data.status.searches_processed,
            total_searches: data.status.total_searches,
            results_found: data.status.results_found,
            has_credentials: data.has_credentials,
            celebrity_count: data.celebrity_count || 0,
          })
        }
      } catch (error) {
        console.error('Error checking Easynews status:', error)
      }
    }

    checkStatus()
    const interval = setInterval(checkStatus, easynewsStatus.is_running ? 2000 : 30000)
    return () => clearInterval(interval)
  }, [easynewsStatus.is_running])

  // Check Easynews mutation
  const checkEasynewsMutation = useMutation({
    mutationFn: () => api.triggerEasynewsCheck(),
    onSuccess: async () => {
      // Immediately set running state and start fast polling
      setEasynewsStatus(prev => ({ ...prev, is_running: true }))
      // Fetch actual status after a brief delay
      setTimeout(async () => {
        try {
          const data = await api.getEasynewsStatus()
          if (data.success) {
            setEasynewsStatus({
              is_running: data.status.is_running,
              current_search: data.status.current_search,
              searches_processed: data.status.searches_processed,
              total_searches: data.status.total_searches,
              results_found: data.status.results_found,
              has_credentials: data.has_credentials,
              celebrity_count: data.celebrity_count || 0,
            })
          }
        } catch (e) {
          console.error('Error fetching Easynews status:', e)
        }
      }, 500)
    },
    onError: (error: any) => {
      notificationManager.error('Error', error.message || 'Failed to start Easynews check')
    }
  })

  // Check all YouTube channels mutation
  const checkAllYouTubeChannelsMutation = useMutation({
    mutationFn: () => api.checkAllYouTubeChannels(),
    onSuccess: () => {
      notificationManager.success('Started', 'YouTube channel check started in background')
    },
    onError: (err: any) => {
      notificationManager.error('Error', err.message || 'Failed to trigger check')
    }
  })

  // Handle create celebrity
  const handleCreateCelebrity = () => {
    if (!newCelebrityName.trim()) return
    createCelebrityMutation.mutate({
      name: newCelebrityName.trim(),
      image_url: newCelebrityImage.trim() || undefined
    })
  }

  // Handle create preset
  const handleCreatePreset = () => {
    if (!selectedCelebrity || !newPreset.name.trim() || !newPreset.source_value.trim()) return
    createPresetMutation.mutate({
      celebrity_id: selectedCelebrity,
      name: newPreset.name.trim(),
      source_type: newPreset.source_type,
      source_value: newPreset.source_value.trim(),
      keywords: newPreset.keywords ? newPreset.keywords.split(',').map(k => k.trim()).filter(Boolean) : [],
      content_type: newPreset.content_type
    })
  }

  // Handle download single video
  const handleDownloadVideo = async (video: DiscoveredVideo) => {
    try {
      await api.post('/video/download', { url: video.url, platform: video.platform })
      updateVideoStatusMutation.mutate({ videoId: video.id, status: 'queued' })
      notificationManager.success('Download Started', video.title)
    } catch (error: any) {
      notificationManager.error('Download Failed', error.message || 'Failed to start download')
    }
  }

  // Handle download selected videos
  const handleDownloadSelected = async () => {
    if (selectedVideos.size === 0) return

    setIsDownloading(true)
    const videosToDownload = videos.filter(v => selectedVideos.has(v.id))
    let successCount = 0
    let failCount = 0

    for (const video of videosToDownload) {
      try {
        await api.post('/video/download', { url: video.url, platform: video.platform })
        successCount++
      } catch {
        failCount++
      }
    }

    // Update status for all selected videos
    if (successCount > 0) {
      bulkUpdateStatusMutation.mutate({
        videoIds: Array.from(selectedVideos),
        status: 'queued'
      })
    }

    setIsDownloading(false)

    if (failCount === 0) {
      notificationManager.success('Downloads Started', `${successCount} videos queued for download`)
    } else {
      notificationManager.warning('Partial Success', `${successCount} started, ${failCount} failed`)
    }
  }

  // Toggle video selection
  const toggleVideoSelection = (videoId: number) => {
    setSelectedVideos(prev => {
      const next = new Set(prev)
      if (next.has(videoId)) {
        next.delete(videoId)
      } else {
        next.add(videoId)
      }
      return next
    })
  }

  // Select all on current page
  const selectAllOnPage = () => {
    const allIds = videos.map(v => v.id)
    setSelectedVideos(new Set(allIds))
  }

  // Clear selection
  const clearSelection = () => {
    setSelectedVideos(new Set())
  }

  // Handle page change - reset selection when changing pages
  const handlePageChange = (newPage: number) => {
    setCurrentPage(newPage)
    setSelectedVideos(new Set())
  }

  // Reset page when filters change
  const handleFilterChange = (setter: (val: any) => void, value: any) => {
    setter(value)
    setCurrentPage(1)
    setSelectedVideos(new Set())
  }

  // Get selected celebrity name
  const selectedCelebrityName = celebrities.find(c => c.id === selectedCelebrity)?.name || 'All Celebrities'

  // Update breadcrumb when celebrity selection changes
  useEffect(() => {
    if (selectedCelebrity && selectedCelebrityName !== 'All Celebrities') {
      setBreadcrumbs([
        { label: 'Home', path: '/' },
        { label: 'Internet Discovery', path: '/celebrities' },
        { label: selectedCelebrityName }
      ])
    } else {
      setBreadcrumbs(breadcrumbConfig['/celebrities'])
    }
  }, [selectedCelebrity, selectedCelebrityName, setBreadcrumbs])

  // Lightbox navigation helpers - use previewVideos snapshot to avoid changes during navigation
  const navigatePreview = useCallback((direction: 'prev' | 'next') => {
    if (previewIndex === -1 || previewVideos.length === 0) return
    const newIndex = direction === 'prev' ? previewIndex - 1 : previewIndex + 1
    if (newIndex >= 0 && newIndex < previewVideos.length) {
      setPreviewIndex(newIndex)
      setPreviewVideo(previewVideos[newIndex])
    }
  }, [previewIndex, previewVideos])

  const openPreview = useCallback((video: DiscoveredVideo, index: number) => {
    // Capture current videos as snapshot so filmstrip stays stable during navigation
    setPreviewVideos([...videos])
    setPreviewVideo(video)
    setPreviewIndex(index)
  }, [videos])

  // Open preview for recently viewed videos - uses recentlyViewedVideos as the filmstrip source
  const openRecentlyViewedPreview = useCallback((video: DiscoveredVideo, index: number) => {
    setPreviewVideos([...recentlyViewedVideos])
    setPreviewVideo(video)
    setPreviewIndex(index)
  }, [recentlyViewedVideos])

  const closePreview = useCallback(() => {
    // Videos are now marked as watched immediately when viewed
    // Refetch the main videos list to reflect watched status changes
    refetchVideos()
    // Clear the tracked set and close the lightbox
    setViewedVideos(new Set())
    setPreviewVideos([])  // Clear snapshot
    setPreviewVideo(null)
    setPreviewIndex(-1)
    setShowMetadata(false)
  }, [refetchVideos])

  // Keyboard shortcuts for lightbox
  useEffect(() => {
    if (!previewVideo) return

    const handleKeyDown = (e: KeyboardEvent) => {
      switch (e.key) {
        case 'ArrowLeft':
          e.preventDefault()
          navigatePreview('prev')
          break
        case 'ArrowRight':
          e.preventDefault()
          navigatePreview('next')
          break
        case 'Escape':
          e.preventDefault()
          closePreview()
          break
        case 'i':
        case 'I':
          e.preventDefault()
          setShowMetadata(prev => !prev)
          break
      }
    }

    window.addEventListener('keydown', handleKeyDown)
    return () => window.removeEventListener('keydown', handleKeyDown)
  }, [previewVideo, navigatePreview, closePreview])

  // Scroll thumbnail into view in lightbox
  useEffect(() => {
    if (previewIndex >= 0 && thumbnailStripRef.current) {
      const thumbnail = thumbnailStripRef.current.children[previewIndex] as HTMLElement
      if (thumbnail) {
        thumbnail.scrollIntoView({ behavior: 'smooth', block: 'nearest', inline: 'center' })
      }
    }
  }, [previewIndex])

  // Track viewed videos - mark as watched immediately for proper timestamp ordering
  // Also track IDs to avoid re-marking on navigation
  useEffect(() => {
    if (previewVideo && previewVideo.status !== 'watched' && !viewedVideos.has(previewVideo.id)) {
      // Track to avoid re-marking
      setViewedVideos(prev => new Set(prev).add(previewVideo.id))
      // Mark immediately with its own timestamp
      updateVideoStatusMutation.mutate({ videoId: previewVideo.id, status: 'watched' })
    }
  }, [previewVideo?.id])  // Only trigger when the video ID changes

  // Handle closing search progress modal
  const handleCloseSearchProgress = () => {
    setShowSearchProgress(false)
    if (searchJobData?.status === 'completed') {
      setSearchJobId(null)
    }
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
        <div>
          <h1 className="text-2xl sm:text-3xl font-bold flex items-center gap-2 sm:gap-3">
            <Star className="w-8 h-8 text-yellow-500" />
            Internet Discovery
          </h1>
          <p className="text-slate-600 dark:text-slate-400 mt-1">
            Find interviews, appearances, and more from your profiles
          </p>
        </div>

        <div className="flex items-center gap-2">
          <button
            onClick={() => checkAllYouTubeChannelsMutation.mutate()}
            disabled={checkAllYouTubeChannelsMutation.isPending}
            className="flex items-center gap-2 px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors disabled:opacity-50 btn-hover-lift"
            title="Check all YouTube channels for new videos"
          >
            {checkAllYouTubeChannelsMutation.isPending ? (
              <Loader2 className="w-4 h-4 animate-spin" />
            ) : (
              <RefreshCw className="w-4 h-4" />
            )}
            <span className="hidden sm:inline">Check Channels</span>
          </button>
          {easynewsStatus.has_credentials && easynewsStatus.celebrity_count > 0 && (
            <button
              onClick={() => checkEasynewsMutation.mutate()}
              disabled={checkEasynewsMutation.isPending || easynewsStatus.is_running}
              className="flex items-center gap-2 px-4 py-2 bg-amber-600 text-white rounded-lg hover:bg-amber-700 transition-colors disabled:opacity-50 btn-hover-lift"
              title={`Check Easynews for ${easynewsStatus.celebrity_count} tracked celebrities`}
            >
              {checkEasynewsMutation.isPending || easynewsStatus.is_running ? (
                <Loader2 className="w-4 h-4 animate-spin" />
              ) : (
                <Download className="w-4 h-4" />
              )}
              <span className="hidden sm:inline">Check Easynews</span>
            </button>
          )}
          <Link
            to="/config?tab=downloads"
            className="flex items-center gap-2 px-4 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700 transition-colors btn-hover-lift"
          >
            <Settings className="w-4 h-4" />
            <span className="hidden sm:inline">Settings</span>
          </Link>
        </div>
      </div>

      {/* Easynews Progress Card */}
      {easynewsStatus.is_running && (
        <div className="card-glass rounded-xl bg-gradient-to-r from-amber-500/10 to-orange-500/10 border border-amber-500/30 p-4 glow-border">
          <div className="flex items-center justify-between mb-3">
            <div className="flex items-center gap-2">
              <div className="relative">
                <Download className="w-5 h-5 text-amber-600 dark:text-amber-400" />
                <span className="absolute -top-1 -right-1 w-2 h-2 bg-amber-500 rounded-full animate-pulse"></span>
              </div>
              <h3 className="text-sm font-semibold text-amber-900 dark:text-amber-100">
                Easynews Search
              </h3>
            </div>
            <span className="text-xs text-amber-600 dark:text-amber-400">
              {easynewsStatus.results_found} results found
            </span>
          </div>

          {easynewsStatus.current_search && (
            <div className="mb-3 px-3 py-2 bg-amber-100 dark:bg-amber-900/30 rounded-lg">
              <div className="flex items-center gap-2 text-sm text-amber-800 dark:text-amber-200">
                <span className="w-2 h-2 bg-amber-500 rounded-full animate-pulse"></span>
                <span className="truncate">Searching: {easynewsStatus.current_search}</span>
              </div>
            </div>
          )}

          {easynewsStatus.total_searches > 0 && (
            <div className="mb-2">
              <div className="flex justify-between text-xs text-amber-700 dark:text-amber-300 mb-1">
                <span>Progress</span>
                <span>{easynewsStatus.searches_processed} / {easynewsStatus.total_searches}</span>
              </div>
              <div className="w-full bg-amber-200 dark:bg-amber-800 rounded-full h-1.5">
                <div
                  className="bg-amber-600 dark:bg-amber-400 h-1.5 rounded-full transition-all duration-300"
                  style={{ width: `${((easynewsStatus.searches_processed || 0) / (easynewsStatus.total_searches || 1)) * 100}%` }}
                ></div>
              </div>
            </div>
          )}
        </div>
      )}

      {/* YouTube Monitor Progress Card */}
      {youtubeMonitorTask?.active && (
        <div className="card-glass rounded-xl bg-gradient-to-r from-red-500/10 to-rose-500/10 border border-red-500/30 p-4 glow-border">
          <div className="flex items-center justify-between mb-3">
            <div className="flex items-center gap-2">
              <div className="relative">
                <Youtube className="w-5 h-5 text-red-600 dark:text-red-400" />
                <span className="absolute -top-1 -right-1 w-2 h-2 bg-red-500 rounded-full animate-pulse"></span>
              </div>
              <h3 className="text-sm font-semibold text-red-900 dark:text-red-100">
                YouTube Channel Monitor
              </h3>
            </div>
            <span className="text-xs text-red-600 dark:text-red-400">
              {youtubeMonitorTask.extra_data?.total_channels || 0} channels
            </span>
          </div>

          {youtubeMonitorTask.detailed_status && (
            <div className="mb-3 px-3 py-2 bg-red-100 dark:bg-red-900/30 rounded-lg">
              <div className="flex items-center gap-2 text-sm text-red-800 dark:text-red-200">
                <span className="w-2 h-2 bg-red-500 rounded-full animate-pulse"></span>
                <span className="truncate">{youtubeMonitorTask.detailed_status}</span>
              </div>
            </div>
          )}

          {youtubeMonitorTask.progress && (
            <div className="mb-2">
              <div className="flex justify-between text-xs text-red-700 dark:text-red-300 mb-1">
                <span>Progress</span>
                <span>{youtubeMonitorTask.progress.current || 0}/{youtubeMonitorTask.progress.total || 0}</span>
              </div>
              <div className="w-full bg-red-200 dark:bg-red-800 rounded-full h-1.5 sm:h-2">
                <div
                  className="bg-red-600 dark:bg-red-400 h-1.5 sm:h-2 rounded-full transition-all duration-300 progress-animated"
                  style={{ width: `${youtubeMonitorTask.progress.total > 0 ? (youtubeMonitorTask.progress.current / youtubeMonitorTask.progress.total * 100) : 0}%` }}
                ></div>
              </div>
            </div>
          )}

          {(youtubeMonitorTask.extra_data?.videos_found ?? 0) > 0 && (
            <div className="flex items-center gap-1.5 text-xs text-green-700 dark:text-green-300 font-medium">
              <svg className="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
              </svg>
              <span>{youtubeMonitorTask.extra_data?.videos_found} new video{youtubeMonitorTask.extra_data?.videos_found !== 1 ? 's' : ''} queued</span>
            </div>
          )}
        </div>
      )}


      {/* Stats Bar */}
      {stats && (
        <div className="grid grid-cols-2 sm:grid-cols-5 gap-4">
          <div className="card-glass-hover rounded-xl p-4 border stat-card-purple shadow-purple-glow">
            <div className="text-2xl font-bold text-violet-600 dark:text-violet-400 animate-count-up">{stats.total_celebrities}</div>
            <div className="text-sm text-muted-foreground">Celebrities</div>
          </div>
          <div className="card-glass-hover rounded-xl p-4 border stat-card-blue shadow-blue-glow">
            <div className="text-2xl font-bold text-blue-600 dark:text-blue-400 animate-count-up">{stats.monitored_channels}</div>
            <div className="text-sm text-muted-foreground">Monitored</div>
          </div>
          <div className="card-glass-hover rounded-xl p-4 border stat-card-green shadow-green-glow">
            <div className="text-2xl font-bold text-emerald-600 dark:text-emerald-400 animate-count-up">{stats.total_videos}</div>
            <div className="text-sm text-muted-foreground">Videos Found</div>
          </div>
          <div className="card-glass-hover rounded-xl p-4 border stat-card-orange shadow-orange-glow">
            <div className="text-2xl font-bold text-amber-600 dark:text-amber-400 animate-count-up">{stats.new_videos}</div>
            <div className="text-sm text-muted-foreground">New</div>
          </div>
          <div className="card-glass-hover rounded-xl p-4 border stat-card-cyan">
            <div className="text-2xl font-bold text-cyan-600 dark:text-cyan-400 animate-count-up">{stats.downloaded_videos}</div>
            <div className="text-sm text-muted-foreground">Downloaded</div>
          </div>
        </div>
      )}

      {/* Filters */}
      <FilterBar
        searchValue={searchQuery}
        onSearchChange={setSearchQuery}
        searchPlaceholder="Search videos..."
        filterSections={[
          {
            id: 'platform',
            label: 'Platform',
            type: 'select',
            options: [
              { value: '', label: 'All Platforms' },
              { value: 'youtube', label: 'YouTube' },
              { value: 'dailymotion', label: 'Dailymotion' },
              { value: 'easynews', label: 'Easynews' }
            ],
            value: platformFilter,
            onChange: (v) => handleFilterChange(setPlatformFilter, v as string)
          },
          {
            id: 'status',
            label: 'Status',
            type: 'select',
            options: [
              { value: 'all', label: 'All Status' },
              { value: 'not_queued', label: 'Not Queued' },
              { value: 'not_downloaded', label: 'Not Downloaded' },
              { value: 'new', label: 'New' },
              { value: 'queued', label: 'Queued' },
              { value: 'downloaded', label: 'Downloaded' },
              { value: 'ignored', label: 'Ignored' }
            ],
            value: statusFilter,
            onChange: (v) => handleFilterChange(setStatusFilter, v as string)
          },
          {
            id: 'watched',
            label: 'Watched',
            type: 'select',
            options: [
              { value: '', label: 'All' },
              { value: 'watched', label: 'Watched' },
              { value: 'unwatched', label: 'Unwatched' }
            ],
            value: watchedFilter,
            onChange: (v) => handleFilterChange(setWatchedFilter, v as string)
          },
          {
            id: 'resolution',
            label: 'Sort by Resolution',
            type: 'select',
            options: RESOLUTION_SORT_OPTIONS.map(o => ({ value: o.value, label: o.label })),
            value: resolutionSort,
            onChange: (v) => {
              handleFilterChange(setResolutionSort, v as string)
              if (v) { setDateSort(''); setNameSort('') }
            }
          },
          {
            id: 'date',
            label: 'Sort by Date',
            type: 'select',
            options: DATE_SORT_OPTIONS.map(o => ({ value: o.value, label: o.label })),
            value: dateSort,
            onChange: (v) => {
              handleFilterChange(setDateSort, v as string)
              if (v) { setResolutionSort(''); setNameSort('') }
            }
          },
          {
            id: 'name',
            label: 'Sort by Name',
            type: 'select',
            options: NAME_SORT_OPTIONS.map(o => ({ value: o.value, label: o.label })),
            value: nameSort,
            onChange: (v) => {
              handleFilterChange(setNameSort, v as string)
              if (v) { setResolutionSort(''); setDateSort('') }
            }
          },
          ...(uniqueSources.length > 0 ? [{
            id: 'source',
            label: 'Source',
            type: 'select' as const,
            options: [{ value: '', label: 'All Sources' }, ...uniqueSources.map((s: string) => ({ value: s, label: s }))],
            value: sourceFilter,
            onChange: (v: string | string[]) => handleFilterChange(setSourceFilter, v as string)
          }] : [])
        ]}
        activeFilters={[
          ...(platformFilter ? [{
            id: 'platform',
            label: 'Platform',
            value: platformFilter,
            displayValue: platformFilter.charAt(0).toUpperCase() + platformFilter.slice(1),
            onRemove: () => setPlatformFilter('')
          }] : []),
          ...(statusFilter !== 'all' ? [{
            id: 'status',
            label: 'Status',
            value: statusFilter,
            displayValue: statusFilter === 'not_queued' ? 'Not Queued' : statusFilter === 'not_downloaded' ? 'Not Downloaded' : statusFilter.charAt(0).toUpperCase() + statusFilter.slice(1),
            onRemove: () => setStatusFilter('all')
          }] : []),
          ...(watchedFilter ? [{
            id: 'watched',
            label: 'Watched',
            value: watchedFilter,
            displayValue: watchedFilter === 'watched' ? 'Watched' : 'Unwatched',
            onRemove: () => setWatchedFilter('')
          }] : []),
          ...(sourceFilter ? [{
            id: 'source',
            label: 'Source',
            value: sourceFilter,
            displayValue: sourceFilter,
            onRemove: () => setSourceFilter('')
          }] : []),
          ...(resolutionSort ? [{
            id: 'resolution',
            label: 'Sort',
            value: resolutionSort,
            displayValue: resolutionSort === 'highest' ? 'Highest Resolution' : 'Lowest Resolution',
            onRemove: () => setResolutionSort('')
          }] : []),
          ...(dateSort ? [{
            id: 'date',
            label: 'Sort',
            value: dateSort,
            displayValue: DATE_SORT_OPTIONS.find(o => o.value === dateSort)?.label || dateSort,
            onRemove: () => setDateSort('')
          }] : []),
          ...(nameSort ? [{
            id: 'name',
            label: 'Sort',
            value: nameSort,
            displayValue: nameSort === 'name_asc' ? 'Name A-Z' : 'Name Z-A',
            onRemove: () => setNameSort('')
          }] : [])
        ]}
        onClearAll={() => {
          setSelectedCelebrity(null)
          setPlatformFilter('')
          setStatusFilter('all')
          setWatchedFilter('')
          setSourceFilter('')
          setSearchQuery('')
          setResolutionSort('')
          setDateSort('')
          setNameSort('')
        }}
        totalCount={totalVideos}
        countLabel="videos"
      />

      {/* Selection Actions Bar */}
      {videos.length > 0 && (
        <div className="card-glass rounded-xl p-3 flex items-center gap-4">
          <div className="flex items-center gap-2">
            <button
              onClick={selectAllOnPage}
              className="flex items-center gap-1 px-3 py-1.5 text-sm text-slate-600 dark:text-slate-300 hover:bg-slate-100 dark:hover:bg-slate-700 rounded-lg"
              title="Select all on page"
            >
              <CheckSquare className="w-4 h-4" />
              Select All
            </button>
            <button
              onClick={clearSelection}
              className="flex items-center gap-1 px-3 py-1.5 text-sm text-slate-600 dark:text-slate-300 hover:bg-slate-100 dark:hover:bg-slate-700 rounded-lg"
              title="Clear selection"
            >
              <XSquare className="w-4 h-4" />
              Clear
            </button>
            <button
              onClick={() => {
                if (confirm('Check oldest 100 videos and remove any that are no longer available?')) {
                  cleanupUnavailableMutation.mutate(true)
                }
              }}
              disabled={cleanupUnavailableMutation.isPending}
              className="flex items-center gap-1 px-3 py-1.5 text-sm text-orange-600 dark:text-orange-400 hover:bg-orange-50 dark:hover:bg-orange-900/20 rounded-lg"
              title="Remove unavailable videos"
            >
              {cleanupUnavailableMutation.isPending ? (
                <Loader2 className="w-4 h-4 animate-spin" />
              ) : (
                <Trash2 className="w-4 h-4" />
              )}
              Cleanup
            </button>
          </div>

          {selectedVideos.size > 0 && (
            <>
              <div className="text-sm text-indigo-600 dark:text-indigo-400 font-medium">
                {selectedVideos.size} selected
              </div>
              <div className="flex items-center gap-2">
                <button
                  onClick={() => addSelectedToQueueMutation.mutate(Array.from(selectedVideos))}
                  disabled={addSelectedToQueueMutation.isPending}
                  className="flex items-center gap-2 px-4 py-1.5 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 disabled:opacity-50 text-sm"
                >
                  {addSelectedToQueueMutation.isPending ? (
                    <Loader2 className="w-4 h-4 animate-spin" />
                  ) : (
                    <ListVideo className="w-4 h-4" />
                  )}
                  Add to Queue
                </button>
                <button
                  onClick={handleDownloadSelected}
                  disabled={isDownloading}
                  className="flex items-center gap-2 px-4 py-1.5 bg-green-600 text-white rounded-lg hover:bg-green-700 disabled:opacity-50 text-sm btn-hover-lift"
                >
                  {isDownloading ? (
                    <Loader2 className="w-4 h-4 animate-spin" />
                  ) : (
                    <Download className="w-4 h-4" />
                  )}
                  Download Now
                </button>
                <button
                  onClick={() => bulkUpdateStatusMutation.mutate({ videoIds: Array.from(selectedVideos), status: 'ignored' })}
                  className="flex items-center gap-2 px-4 py-1.5 bg-slate-600 text-white rounded-lg hover:bg-slate-700 text-sm"
                >
                  <EyeOff className="w-4 h-4" />
                  Ignore
                </button>
                <button
                  onClick={() => bulkUpdateStatusMutation.mutate({ videoIds: Array.from(selectedVideos), status: 'watched' })}
                  className="flex items-center gap-2 px-4 py-1.5 bg-teal-600 text-white rounded-lg hover:bg-teal-700 text-sm"
                >
                  <Eye className="w-4 h-4" />
                  Watched
                </button>
                <button
                  onClick={() => bulkUpdateStatusMutation.mutate({ videoIds: Array.from(selectedVideos), status: 'new' })}
                  className="flex items-center gap-2 px-4 py-1.5 bg-amber-600 text-white rounded-lg hover:bg-amber-700 text-sm"
                >
                  <Square className="w-4 h-4" />
                  Unwatched
                </button>
                <button
                  onClick={() => {
                    if (confirm(`Delete ${selectedVideos.size} selected videos? This cannot be undone.`)) {
                      bulkDeleteVideosMutation.mutate(Array.from(selectedVideos))
                    }
                  }}
                  className="flex items-center gap-2 px-4 py-1.5 bg-red-700 text-white rounded-lg hover:bg-red-800 text-sm"
                >
                  <Trash2 className="w-4 h-4" />
                  Delete
                </button>
              </div>
            </>
          )}

          <div className="flex-1" />

          {/* Pagination */}
          {totalPages > 1 && (
            <div className="flex items-center gap-2">
              <button
                onClick={() => handlePageChange(currentPage - 1)}
                disabled={currentPage === 1}
                className="p-2 rounded-lg hover:bg-slate-100 dark:hover:bg-slate-700 disabled:opacity-50 disabled:cursor-not-allowed"
              >
                <ChevronLeft className="w-4 h-4" />
              </button>
              <span className="text-sm text-slate-600 dark:text-slate-400">
                Page {currentPage} of {totalPages}
              </span>
              <button
                onClick={() => handlePageChange(currentPage + 1)}
                disabled={currentPage === totalPages}
                className="p-2 rounded-lg hover:bg-slate-100 dark:hover:bg-slate-700 disabled:opacity-50 disabled:cursor-not-allowed"
              >
                <ChevronRight className="w-4 h-4" />
              </button>
            </div>
          )}
        </div>
      )}

      {/* Videos Grid */}
      <div className="card-glass rounded-xl overflow-hidden">
        {loadingVideos ? (
          <div className="flex items-center justify-center p-12">
            <Loader2 className="w-8 h-8 animate-spin text-indigo-500" />
          </div>
        ) : videos.length === 0 ? (
          <div className="text-center p-12">
            <Video className="w-12 h-12 mx-auto text-slate-400 mb-4" />
            <h3 className="text-lg font-medium text-slate-900 dark:text-white mb-2">
              {searchQuery ? `No matches for "${searchQuery}"` : 'No videos found'}
            </h3>
            <p className="text-slate-600 dark:text-slate-400 mb-4">
              {searchQuery
                ? "Try a different search term."
                : celebrities.length === 0
                  ? "Add a celebrity and create search presets to discover content."
                  : "Run a search to discover new videos."}
            </p>
          </div>
        ) : (
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4 p-4">
            {videos.map(video => {
              const isSelected = selectedVideos.has(video.id)

              return (
                <div
                  key={video.id}
                  className={`bg-slate-50 dark:bg-slate-700/50 rounded-lg overflow-hidden group relative ${
                    isSelected ? 'ring-2 ring-indigo-500' : ''
                  }`}
                >
                  {/* Selection checkbox */}
                  <div
                    className="absolute top-2 left-2 z-10 cursor-pointer"
                    onClick={(e) => {
                      e.stopPropagation()
                      toggleVideoSelection(video.id)
                    }}
                  >
                    {isSelected ? (
                      <CheckSquare className="w-6 h-6 text-indigo-500 bg-white rounded" />
                    ) : (
                      <Square className="w-6 h-6 text-white/80 bg-black/30 rounded opacity-0 group-hover:opacity-100 transition-opacity" />
                    )}
                  </div>

                  {/* Thumbnail - clickable to play video */}
                  <div
                    className="relative aspect-video bg-slate-200 dark:bg-slate-600 cursor-pointer"
                    onClick={() => openPreview(video, videos.indexOf(video))}
                  >
                    {video.thumbnail ? (
                      <img
                        src={getCachedThumbnailUrl(video)}
                        alt={video.title}
                        className="w-full h-full object-cover"
                        loading="lazy"
                        onError={(e) => {
                          // Fallback to original thumbnail URL if cache fails
                          const target = e.target as HTMLImageElement
                          if (target.src !== video.thumbnail) {
                            target.src = video.thumbnail
                          }
                        }}
                      />
                    ) : (
                      <div className="flex items-center justify-center h-full">
                        <Youtube className="w-12 h-12 text-slate-400" />
                      </div>
                    )}

                    {/* Duration, Resolution, Source & Audio badges - bottom right */}
                    <div className="absolute bottom-2 right-2 flex items-center gap-1">
                      {video.max_resolution && (
                        <div className="px-1.5 py-0.5 bg-indigo-600/90 text-white text-xs rounded">
                          {video.max_resolution}p
                        </div>
                      )}
                      {(() => {
                        try {
                          const meta = video.metadata ? JSON.parse(video.metadata) : null
                          return (
                            <>
                              {meta?.source && (
                                <div className="px-1.5 py-0.5 bg-emerald-600/90 text-white text-xs rounded">
                                  {meta.source}
                                </div>
                              )}
                              {meta?.audio_codec && (
                                <div className="px-1.5 py-0.5 bg-amber-600/90 text-white text-xs rounded">
                                  {meta.audio_codec}
                                </div>
                              )}
                            </>
                          )
                        } catch { return null }
                      })()}
                      {video.duration > 0 && (
                        <div className="px-1.5 py-0.5 bg-black/80 text-white text-xs rounded">
                          {formatDuration(video.duration)}
                        </div>
                      )}
                    </div>

                    {/* Status badge - bottom left */}
                    {video.status !== 'new' && (
                      <div className={`absolute bottom-2 left-2 px-2 py-1 rounded text-xs font-medium ${
                        video.status === 'downloaded' ? 'bg-green-500 text-white' :
                        video.status === 'queued' ? 'bg-blue-500 text-white' :
                        video.status === 'ignored' ? 'bg-slate-500 text-white' :
                        'bg-yellow-500 text-white'
                      }`}>
                        {video.status}
                      </div>
                    )}

                    {/* Hover overlay with actions */}
                    <div
                      className="absolute inset-0 bg-black/60 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center gap-2"
                      onClick={(e) => e.stopPropagation()}
                    >
                      <button
                        onClick={(e) => {
                          e.stopPropagation()
                          openPreview(video, videos.indexOf(video))
                        }}
                        className="p-3 bg-red-600 hover:bg-red-700 rounded-full transition-colors"
                        title="Preview Video"
                      >
                        <Play className="w-6 h-6 text-white" />
                      </button>
                      {(video.platform === 'youtube' || video.platform === 'dailymotion') && (
                        <a
                          href={video.url}
                          target="_blank"
                          rel="noopener noreferrer"
                          onClick={(e) => e.stopPropagation()}
                          className="p-2 bg-white/20 hover:bg-white/30 rounded-full transition-colors"
                          title={video.platform === 'dailymotion' ? 'Open on Dailymotion' : 'Open on YouTube'}
                        >
                          <ExternalLink className="w-5 h-5 text-white" />
                        </a>
                      )}
                      <button
                        onClick={(e) => {
                          e.stopPropagation()
                          addToQueueMutation.mutate(video)
                        }}
                        className="p-2 bg-indigo-600 hover:bg-indigo-700 rounded-full transition-colors"
                        title="Add to Queue"
                      >
                        <ListVideo className="w-5 h-5 text-white" />
                      </button>
                      <button
                        onClick={(e) => {
                          e.stopPropagation()
                          handleDownloadVideo(video)
                        }}
                        className="p-2 bg-green-600 hover:bg-green-700 rounded-full transition-colors"
                        title="Download Now"
                      >
                        <Download className="w-5 h-5 text-white" />
                      </button>
                      <button
                        onClick={(e) => {
                          e.stopPropagation()
                          updateVideoStatusMutation.mutate({ videoId: video.id, status: 'ignored' })
                        }}
                        className="p-2 bg-slate-600 hover:bg-slate-700 rounded-full transition-colors"
                        title="Ignore"
                      >
                        <EyeOff className="w-5 h-5 text-white" />
                      </button>
                      <button
                        onClick={(e) => {
                          e.stopPropagation()
                          if (confirm('Delete this video from discovery? This cannot be undone.')) {
                            deleteVideoMutation.mutate(video.id)
                          }
                        }}
                        className="p-2 bg-red-800 hover:bg-red-900 rounded-full transition-colors"
                        title="Delete"
                      >
                        <Trash2 className="w-5 h-5 text-white" />
                      </button>
                    </div>
                  </div>

                  {/* Info */}
                  <div className="p-3">
                    <h3 className="font-medium text-sm line-clamp-2 mb-1" title={video.title}>
                      {video.title}
                    </h3>
                    <div className="text-xs text-slate-600 dark:text-slate-400 space-y-0.5">
                      <div className="flex items-center gap-1">
                        <Youtube className="w-3 h-3" />
                        {video.channel_name}
                      </div>
                      <div className="flex items-center gap-2">
                        {video.view_count > 0 && (
                          <span>{formatViewCount(video.view_count)}</span>
                        )}
                        {video.upload_date && (
                          <span className="flex items-center gap-1">
                            <Calendar className="w-3 h-3" />
                            {formatDateOnly(video.upload_date)}
                          </span>
                        )}
                      </div>
                      <div className="text-indigo-600 dark:text-indigo-400">
                        {video.celebrity_name}
                      </div>
                    </div>
                  </div>
                </div>
              )
            })}
          </div>
        )}

        {/* Bottom Pagination */}
        {totalPages > 1 && (
          <div className="flex items-center justify-center gap-2 p-4 border-t border-slate-200 dark:border-slate-700">
            <button
              onClick={() => handlePageChange(1)}
              disabled={currentPage === 1}
              className="px-3 py-1.5 rounded-lg hover:bg-slate-100 dark:hover:bg-slate-700 disabled:opacity-50 disabled:cursor-not-allowed text-sm"
            >
              First
            </button>
            <button
              onClick={() => handlePageChange(currentPage - 1)}
              disabled={currentPage === 1}
              className="p-2 rounded-lg hover:bg-slate-100 dark:hover:bg-slate-700 disabled:opacity-50 disabled:cursor-not-allowed"
            >
              <ChevronLeft className="w-4 h-4" />
            </button>

            {/* Page numbers */}
            {Array.from({ length: Math.min(5, totalPages) }, (_, i) => {
              let pageNum: number
              if (totalPages <= 5) {
                pageNum = i + 1
              } else if (currentPage <= 3) {
                pageNum = i + 1
              } else if (currentPage >= totalPages - 2) {
                pageNum = totalPages - 4 + i
              } else {
                pageNum = currentPage - 2 + i
              }
              return (
                <button
                  key={pageNum}
                  onClick={() => handlePageChange(pageNum)}
                  className={`w-8 h-8 rounded-lg text-sm ${
                    currentPage === pageNum
                      ? 'bg-indigo-600 text-white'
                      : 'hover:bg-slate-100 dark:hover:bg-slate-700'
                  }`}
                >
                  {pageNum}
                </button>
              )
            })}

            <button
              onClick={() => handlePageChange(currentPage + 1)}
              disabled={currentPage === totalPages}
              className="p-2 rounded-lg hover:bg-slate-100 dark:hover:bg-slate-700 disabled:opacity-50 disabled:cursor-not-allowed"
            >
              <ChevronRight className="w-4 h-4" />
            </button>
            <button
              onClick={() => handlePageChange(totalPages)}
              disabled={currentPage === totalPages}
              className="px-3 py-1.5 rounded-lg hover:bg-slate-100 dark:hover:bg-slate-700 disabled:opacity-50 disabled:cursor-not-allowed text-sm"
            >
              Last
            </button>
          </div>
        )}
      </div>

      {/* Recently Viewed Section */}
      {recentlyViewedVideos.length > 0 && (
        <div className="bg-white dark:bg-slate-800 rounded-lg shadow-sm overflow-hidden">
          <div className="p-4 border-b border-slate-200 dark:border-slate-700">
            <h2 className="text-lg font-semibold flex items-center gap-2">
              <Eye className="w-5 h-5 text-teal-500" />
              Recently Viewed
            </h2>
          </div>
          <div className="p-4">
            <div className="flex gap-3 overflow-x-auto pb-2 scrollbar-thin scrollbar-thumb-slate-300 dark:scrollbar-thumb-slate-600">
              {recentlyViewedVideos.map((video, index) => (
                <div
                  key={video.id}
                  className="flex-shrink-0 w-48 bg-slate-50 dark:bg-slate-700/50 rounded-lg overflow-hidden cursor-pointer group"
                  onClick={() => openRecentlyViewedPreview(video, index)}
                >
                  <div className="relative aspect-video bg-slate-200 dark:bg-slate-600">
                    {video.thumbnail ? (
                      <img
                        src={getCachedThumbnailUrl(video)}
                        alt={video.title}
                        className="w-full h-full object-cover"
                        loading="lazy"
                        onError={(e) => {
                          // Fallback to original thumbnail URL if cache fails
                          const target = e.target as HTMLImageElement
                          if (target.src !== video.thumbnail) {
                            target.src = video.thumbnail
                          }
                        }}
                      />
                    ) : (
                      <div className="flex items-center justify-center h-full">
                        <Youtube className="w-8 h-8 text-slate-400" />
                      </div>
                    )}
                    {/* Duration badge */}
                    {video.duration > 0 && (
                      <div className="absolute bottom-1 right-1 px-1 py-0.5 bg-black/80 text-white text-xs rounded">
                        {formatDuration(video.duration)}
                      </div>
                    )}
                    {/* Play overlay on hover */}
                    <div className="absolute inset-0 bg-black/40 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center">
                      <Play className="w-8 h-8 text-white" />
                    </div>
                  </div>
                  <div className="p-2">
                    <h3 className="text-xs font-medium line-clamp-2" title={video.title}>
                      {video.title}
                    </h3>
                    <div className="text-xs text-slate-500 dark:text-slate-400 mt-1 truncate">
                      {video.channel_name}
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>
      )}

      {/* Add Celebrity Modal */}
      {showAddCelebrity && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-white dark:bg-slate-800 rounded-xl shadow-xl max-w-md w-full p-6">
            <h2 className="text-xl font-bold mb-4">Add Celebrity</h2>

            <div className="space-y-4">
              <div>
                <label className="block text-sm font-medium mb-1">Name *</label>
                <input
                  type="text"
                  value={newCelebrityName}
                  onChange={(e) => setNewCelebrityName(e.target.value)}
                  placeholder="e.g., Eva Longoria"
                  className="w-full px-3 py-2 border border-slate-300 dark:border-slate-600 rounded-lg bg-white dark:bg-slate-700"
                  autoFocus
                />
              </div>

              <div>
                <label className="block text-sm font-medium mb-1">Image URL (optional)</label>
                <input
                  type="text"
                  value={newCelebrityImage}
                  onChange={(e) => setNewCelebrityImage(e.target.value)}
                  placeholder="https://..."
                  className="w-full px-3 py-2 border border-slate-300 dark:border-slate-600 rounded-lg bg-white dark:bg-slate-700"
                />
              </div>
            </div>

            <div className="flex justify-end gap-3 mt-6">
              <button
                onClick={() => {
                  setShowAddCelebrity(false)
                  setNewCelebrityName('')
                  setNewCelebrityImage('')
                }}
                className="px-4 py-2 text-slate-600 hover:bg-slate-100 dark:hover:bg-slate-700 rounded-lg"
              >
                Cancel
              </button>
              <button
                onClick={handleCreateCelebrity}
                disabled={!newCelebrityName.trim() || createCelebrityMutation.isPending}
                className="px-4 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 disabled:opacity-50"
              >
                {createCelebrityMutation.isPending ? 'Creating...' : 'Create'}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Add Preset Modal */}
      {showAddPreset && selectedCelebrity && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-white dark:bg-slate-800 rounded-xl shadow-xl max-w-lg w-full p-6">
            <h2 className="text-xl font-bold mb-4">Add Search Preset</h2>
            <p className="text-sm text-slate-600 dark:text-slate-400 mb-4">
              For: {selectedCelebrityName}
            </p>

            <div className="space-y-4">
              <div>
                <label className="block text-sm font-medium mb-1">Preset Name *</label>
                <input
                  type="text"
                  value={newPreset.name}
                  onChange={(e) => setNewPreset({ ...newPreset, name: e.target.value })}
                  placeholder="e.g., Tonight Show, Red Carpet Interviews"
                  className="w-full px-3 py-2 border border-slate-300 dark:border-slate-600 rounded-lg bg-white dark:bg-slate-700"
                />
              </div>

              <div>
                <label className="block text-sm font-medium mb-1">Source Type *</label>
                <select
                  value={newPreset.source_type}
                  onChange={(e) => setNewPreset({ ...newPreset, source_type: e.target.value })}
                  className="w-full px-3 py-2 border border-slate-300 dark:border-slate-600 rounded-lg bg-white dark:bg-slate-700"
                >
                  {Object.entries(SOURCE_TYPES).map(([key, { label }]) => (
                    <option key={key} value={key}>{label}</option>
                  ))}
                </select>
                <p className="text-xs text-slate-500 mt-1">
                  {SOURCE_TYPES[newPreset.source_type]?.description}
                </p>
              </div>

              <div>
                <label className="block text-sm font-medium mb-1">
                  {newPreset.source_type === 'youtube_search' ? 'Search Query *' :
                   newPreset.source_type === 'youtube_channel' ? 'Channel ID *' :
                   'Channel ID for RSS *'}
                </label>
                <input
                  type="text"
                  value={newPreset.source_value}
                  onChange={(e) => setNewPreset({ ...newPreset, source_value: e.target.value })}
                  placeholder={
                    newPreset.source_type === 'youtube_search'
                      ? '"Eva Longoria" interview'
                      : 'UCxxxxxxxxxxxxxxxx'
                  }
                  className="w-full px-3 py-2 border border-slate-300 dark:border-slate-600 rounded-lg bg-white dark:bg-slate-700"
                />
                {newPreset.source_type === 'youtube_search' && (
                  <p className="text-xs text-slate-500 mt-1">
                    Use quotes for exact phrases. Example: "Eva Longoria" interview Fallon
                  </p>
                )}
              </div>

              <div>
                <label className="block text-sm font-medium mb-1">Filter Keywords (optional)</label>
                <input
                  type="text"
                  value={newPreset.keywords}
                  onChange={(e) => setNewPreset({ ...newPreset, keywords: e.target.value })}
                  placeholder="interview, talks, red carpet"
                  className="w-full px-3 py-2 border border-slate-300 dark:border-slate-600 rounded-lg bg-white dark:bg-slate-700"
                />
                <p className="text-xs text-slate-500 mt-1">
                  Comma-separated. Only videos containing these keywords will be included.
                </p>
              </div>

              <div>
                <label className="block text-sm font-medium mb-1">Content Type</label>
                <select
                  value={newPreset.content_type}
                  onChange={(e) => setNewPreset({ ...newPreset, content_type: e.target.value })}
                  className="w-full px-3 py-2 border border-slate-300 dark:border-slate-600 rounded-lg bg-white dark:bg-slate-700"
                >
                  {Object.entries(CONTENT_TYPES).map(([key, { label }]) => (
                    <option key={key} value={key}>{label}</option>
                  ))}
                </select>
              </div>
            </div>

            <div className="flex justify-end gap-3 mt-6">
              <button
                onClick={() => {
                  setShowAddPreset(false)
                  setNewPreset({ name: '', source_type: 'youtube_search', source_value: '', keywords: '', content_type: 'all' })
                }}
                className="px-4 py-2 text-slate-600 hover:bg-slate-100 dark:hover:bg-slate-700 rounded-lg"
              >
                Cancel
              </button>
              <button
                onClick={handleCreatePreset}
                disabled={!newPreset.name.trim() || !newPreset.source_value.trim() || createPresetMutation.isPending}
                className="px-4 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 disabled:opacity-50"
              >
                {createPresetMutation.isPending ? 'Creating...' : 'Create Preset'}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Search Progress Modal */}
      {showSearchProgress && searchJobData && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-white dark:bg-slate-800 rounded-xl shadow-xl max-w-lg w-full p-6">
            <div className="flex items-center justify-between mb-4">
              <h2 className="text-xl font-bold flex items-center gap-2">
                <RefreshCw className={`w-5 h-5 ${searchJobData.status === 'running' ? 'animate-spin' : ''}`} />
                Search Progress
              </h2>
              <button
                onClick={handleCloseSearchProgress}
                className="p-2 hover:bg-slate-100 dark:hover:bg-slate-700 rounded-lg"
              >
                <X className="w-5 h-5" />
              </button>
            </div>

            {/* Progress Bar */}
            <div className="mb-4">
              <div className="flex justify-between text-sm mb-1">
                <span className="text-slate-600 dark:text-slate-400">
                  {searchJobData.completed_presets} of {searchJobData.total_presets} presets
                </span>
                <span className="font-medium">
                  {Math.round((searchJobData.completed_presets / searchJobData.total_presets) * 100)}%
                </span>
              </div>
              <div className="h-3 bg-slate-200 dark:bg-slate-700 rounded-full overflow-hidden">
                <div
                  className="h-full bg-gradient-to-r from-green-500 to-emerald-500 transition-all duration-300"
                  style={{ width: `${(searchJobData.completed_presets / searchJobData.total_presets) * 100}%` }}
                />
              </div>
            </div>

            {/* Current Preset */}
            {searchJobData.status === 'running' && searchJobData.current_preset && (
              <div className="mb-4 p-3 bg-slate-100 dark:bg-slate-700/50 rounded-lg">
                <div className="text-sm text-slate-600 dark:text-slate-400 mb-1">Currently searching:</div>
                <div className="font-medium truncate">{searchJobData.current_preset}</div>
              </div>
            )}

            {/* Stats */}
            <div className="grid grid-cols-2 gap-4 mb-4">
              <div className="p-3 bg-green-50 dark:bg-green-900/20 rounded-lg">
                <div className="text-2xl font-bold text-green-600">{searchJobData.total_new_videos}</div>
                <div className="text-sm text-green-700 dark:text-green-400">New Videos Found</div>
              </div>
              <div className="p-3 bg-blue-50 dark:bg-blue-900/20 rounded-lg">
                <div className="text-2xl font-bold text-blue-600">{searchJobData.completed_presets}</div>
                <div className="text-sm text-blue-700 dark:text-blue-400">Presets Searched</div>
              </div>
            </div>

            {/* Errors */}
            {searchJobData.errors && searchJobData.errors.length > 0 && (
              <div className="mb-4">
                <div className="text-sm font-medium text-red-600 mb-2">
                  {searchJobData.errors.length} error(s):
                </div>
                <div className="max-h-24 overflow-y-auto custom-scrollbar text-sm text-red-500 space-y-1">
                  {searchJobData.errors.map((err: any, i: number) => (
                    <div key={i} className="truncate">{err.preset_name}: {err.error}</div>
                  ))}
                </div>
              </div>
            )}

            {/* Status */}
            <div className="flex items-center justify-between">
              <div className={`flex items-center gap-2 ${
                searchJobData.status === 'completed' ? 'text-green-600' : 'text-blue-600'
              }`}>
                {searchJobData.status === 'running' ? (
                  <>
                    <Loader2 className="w-4 h-4 animate-spin" />
                    Searching...
                  </>
                ) : (
                  <>
                    <CheckSquare className="w-4 h-4" />
                    Complete
                  </>
                )}
              </div>
              {searchJobData.status === 'completed' && (
                <button
                  onClick={() => {
                    setShowSearchProgress(false)
                    setSearchJobId(null)
                  }}
                  className="px-4 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700"
                >
                  Done
                </button>
              )}
            </div>
          </div>
        </div>
      )}

      {/* Enhanced Video Preview Lightbox */}
      {previewVideo && (
        <div
          ref={lightboxRef}
          className="fixed inset-0 bg-black/95 z-50 flex flex-col"
          onClick={closePreview}
        >
          {/* Top Bar */}
          <div className="absolute top-0 left-0 right-0 bg-gradient-to-b from-black/80 to-transparent p-4 z-10" onClick={(e) => e.stopPropagation()}>
            <div className="flex items-center justify-between max-w-7xl mx-auto">
              {/* Title & Counter */}
              <div className="flex-1 min-w-0 text-white">
                <h3 className="text-lg font-medium truncate">{previewVideo.title}</h3>
                <p className="text-sm text-white/70">
                  {previewIndex + 1} / {previewVideos.length}
                </p>
              </div>

              {/* Close Button */}
              <button
                onClick={closePreview}
                className="p-2 hover:bg-white/20 rounded-lg transition-colors ml-4"
                title="Close (Esc)"
              >
                <X className="w-6 h-6 text-white" />
              </button>
            </div>
          </div>

          {/* Navigation Buttons */}
          <button
            onClick={(e) => {
              e.stopPropagation()
              navigatePreview('prev')
            }}
            disabled={previewIndex === 0}
            className="absolute left-4 top-1/2 -translate-y-1/2 p-3 bg-black/50 hover:bg-black/70 rounded-full text-white disabled:opacity-30 transition-colors z-10"
            title="Previous (←)"
          >
            <ChevronLeft className="w-8 h-8" />
          </button>

          <button
            onClick={(e) => {
              e.stopPropagation()
              navigatePreview('next')
            }}
            disabled={previewIndex === previewVideos.length - 1}
            className="absolute right-4 top-1/2 -translate-y-1/2 p-3 bg-black/50 hover:bg-black/70 rounded-full text-white disabled:opacity-30 transition-colors z-10"
            title="Next (→)"
          >
            <ChevronRight className="w-8 h-8" />
          </button>

          {/* Main Content Area */}
          <div className="flex-1 flex items-center justify-center p-4 pt-20 pb-32" onClick={(e) => e.stopPropagation()}>
            <div className="relative flex flex-col items-center justify-center w-full">
              {/* Video Player - Local file if downloaded, otherwise embedded */}
              {previewVideo.status === 'downloaded' && previewVideo.downloaded_path ? (
                /* Local video player for downloaded files */
                <div className="w-[90vw] max-w-6xl flex justify-center">
                  <video
                    key={`video-${previewVideo.id}`}
                    src={`/api/celebrity/videos/${previewVideo.id}/stream`}
                    className="max-w-full max-h-[60vh] rounded-xl shadow-2xl bg-black"
                    controls
                    autoPlay
                    playsInline
                    // @ts-ignore - AirPlay attributes
                    x-webkit-airplay="allow"
                    airplay="allow"
                  />
                </div>
              ) : previewVideo.video_id && (previewVideo.platform === 'youtube' || previewVideo.platform === 'dailymotion') ? (
                /* Embedded player for YouTube/Dailymotion videos */
                <div className="relative w-[90vw] max-w-6xl aspect-video bg-black rounded-xl overflow-hidden shadow-2xl">
                  <iframe
                    key={`embed-${previewVideo.id}`}
                    src={previewVideo.platform === 'dailymotion'
                      ? `https://www.dailymotion.com/embed/video/${previewVideo.video_id}?autoplay=1`
                      : `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>
              ) : previewVideo.thumbnail ? (
                /* Thumbnail preview for other platforms (e.g., Easynews) */
                <div className="relative w-[90vw] max-w-6xl aspect-video bg-black rounded-xl overflow-hidden shadow-2xl flex items-center justify-center">
                  <img
                    src={previewVideo.thumbnail}
                    alt={previewVideo.title}
                    className="max-w-full max-h-full object-contain"
                  />
                </div>
              ) : (
                /* Error state - no video ID or thumbnail */
                <div className="relative w-[92vw] max-w-6xl aspect-video bg-black rounded-xl overflow-hidden shadow-2xl flex items-center justify-center text-white/70">
                  <div className="text-center">
                    <Youtube className="w-12 h-12 mx-auto mb-2 opacity-50" />
                    <p>Preview not available</p>
                  </div>
                </div>
              )}

              {/* Video Info Bar */}
              <div className="mt-4 flex items-center gap-4 text-white/80 text-sm">
                <span className="flex items-center gap-1">
                  <Youtube className="w-4 h-4" />
                  {previewVideo.channel_name}
                </span>
                {previewVideo.view_count > 0 && (
                  <span>{formatViewCount(previewVideo.view_count)}</span>
                )}
                {previewVideo.upload_date && (
                  <span className="flex items-center gap-1">
                    <Calendar className="w-4 h-4" />
                    {formatDateOnly(previewVideo.upload_date)}
                  </span>
                )}
                {previewVideo.duration > 0 && (
                  <span>{formatDuration(previewVideo.duration)}</span>
                )}
                {previewVideo.max_resolution && (
                  <span className="flex items-center gap-1 text-emerald-400 font-medium">
                    <Film className="w-4 h-4" />
                    {formatResolution(previewVideo.max_resolution, previewVideo.max_width)}
                  </span>
                )}
                <div className="flex-1" />
                <span className="text-indigo-400 font-medium">{previewVideo.celebrity_name}</span>
              </div>
            </div>
          </div>

          {/* Metadata Toggle Button (Caret) */}
          <button
            onClick={(e) => {
              e.stopPropagation()
              setShowMetadata(!showMetadata)
            }}
            className="absolute right-4 top-24 p-3 bg-black/30 hover:bg-black/50 rounded-lg text-white transition-colors z-10 min-w-[44px] min-h-[44px] flex items-center justify-center"
            title="Toggle Metadata (I)"
          >
            {showMetadata ? (
              <ChevronRight className="w-5 h-5" />
            ) : (
              <ChevronDown className="w-5 h-5 rotate-90" />
            )}
          </button>

          {/* Metadata Panel */}
          <div
            className={`absolute right-6 top-24 bottom-48 w-80 transition-all duration-300 ease-in-out ${
              showMetadata ? 'translate-x-0 opacity-100' : 'translate-x-[110%] opacity-0'
            }`}
            onClick={(e) => e.stopPropagation()}
          >
            <div className="h-full bg-gradient-to-br from-gray-900/95 to-black/95 backdrop-blur-xl rounded-2xl border border-white/20 shadow-xl overflow-hidden">
              <div className="p-5 h-full overflow-y-auto">
                <h3 className="text-white font-semibold text-lg mb-4 pb-3 border-b border-white/20">Video Details</h3>

                <div className="space-y-4 text-sm">
                  <div>
                    <div className="text-white/60 mb-1">Title</div>
                    <div className="text-white">{previewVideo.title}</div>
                  </div>

                  <div>
                    <div className="text-white/60 mb-1">Channel</div>
                    <div className="text-white">{previewVideo.channel_name}</div>
                  </div>

                  <div>
                    <div className="text-white/60 mb-1">Celebrity</div>
                    <div className="text-indigo-400 font-medium">{previewVideo.celebrity_name}</div>
                  </div>

                  {previewVideo.upload_date && (
                    <div>
                      <div className="text-white/60 mb-1">Upload Date</div>
                      <div className="text-white">{formatDateOnly(previewVideo.upload_date)}</div>
                    </div>
                  )}

                  {previewVideo.view_count > 0 && (
                    <div>
                      <div className="text-white/60 mb-1">Views</div>
                      <div className="text-white">{previewVideo.view_count.toLocaleString()}</div>
                    </div>
                  )}

                  {previewVideo.duration > 0 && (
                    <div>
                      <div className="text-white/60 mb-1">Duration</div>
                      <div className="text-white">{formatDuration(previewVideo.duration)}</div>
                    </div>
                  )}

                  {previewVideo.max_resolution && (
                    <div>
                      <div className="text-white/60 mb-1">Max Resolution</div>
                      <div className="text-emerald-400 font-medium">{formatResolution(previewVideo.max_resolution, previewVideo.max_width)}</div>
                    </div>
                  )}

                  <div>
                    <div className="text-white/60 mb-1">Status</div>
                    <div className={`inline-flex px-2 py-1 rounded text-xs font-medium ${
                      previewVideo.status === 'new' ? 'bg-yellow-500/20 text-yellow-400' :
                      previewVideo.status === 'downloaded' ? 'bg-green-500/20 text-green-400' :
                      previewVideo.status === 'queued' ? 'bg-blue-500/20 text-blue-400' :
                      'bg-slate-500/20 text-slate-400'
                    }`}>
                      {previewVideo.status}
                    </div>
                  </div>

                  {previewVideo.description && (
                    <div>
                      <div className="text-white/60 mb-1">Description</div>
                      <div className="text-white/80 text-xs line-clamp-6">{previewVideo.description}</div>
                    </div>
                  )}
                </div>
              </div>
            </div>
          </div>

          {/* Action Buttons */}
          <div className="absolute bottom-32 left-1/2 -translate-x-1/2 flex items-center gap-3" onClick={(e) => e.stopPropagation()}>
            <button
              onClick={() => {
                addToQueueMutation.mutate(previewVideo)
              }}
              className="flex items-center gap-2 px-5 py-2.5 bg-indigo-600 hover:bg-indigo-700 text-white rounded-lg transition-colors shadow-lg"
            >
              <ListVideo className="w-5 h-5" />
              Add to Queue
            </button>
            <button
              onClick={() => {
                handleDownloadVideo(previewVideo)
              }}
              className="flex items-center gap-2 px-5 py-2.5 bg-green-600 hover:bg-green-700 text-white rounded-lg transition-colors shadow-lg btn-hover-lift"
            >
              <Download className="w-5 h-5" />
              Download
            </button>
            <button
              onClick={() => {
                updateVideoStatusMutation.mutate({ videoId: previewVideo.id, status: 'ignored' })
                navigatePreview('next')
              }}
              className="flex items-center gap-2 px-5 py-2.5 bg-slate-700 hover:bg-slate-600 text-white rounded-lg transition-colors shadow-lg"
            >
              <EyeOff className="w-5 h-5" />
              Ignore
            </button>
            <button
              onClick={() => {
                if (confirm('Delete this video from discovery? This cannot be undone.')) {
                  deleteVideoMutation.mutate(previewVideo.id)
                  navigatePreview('next')
                }
              }}
              className="flex items-center gap-2 px-5 py-2.5 bg-red-800 hover:bg-red-900 text-white rounded-lg transition-colors shadow-lg"
            >
              <Trash2 className="w-5 h-5" />
              Delete
            </button>
            <a
              href={previewVideo.url}
              target="_blank"
              rel="noopener noreferrer"
              className={`flex items-center gap-2 px-5 py-2.5 text-white rounded-lg transition-colors shadow-lg ${
                previewVideo.platform === 'dailymotion'
                  ? 'bg-cyan-600 hover:bg-cyan-700'
                  : 'bg-red-600 hover:bg-red-700'
              }`}
            >
              <ExternalLink className="w-5 h-5" />
              {previewVideo.platform === 'dailymotion' ? 'Dailymotion' : 'YouTube'}
            </a>
          </div>

          {/* Thumbnail Navigation Strip */}
          <div className="absolute bottom-0 left-0 right-0 bg-gradient-to-t from-black/90 to-transparent p-4 pt-8" onClick={(e) => e.stopPropagation()}>
            <div
              ref={thumbnailStripRef}
              className="flex gap-2 overflow-x-auto overflow-y-visible scrollbar-thin scrollbar-thumb-white/20 scrollbar-track-transparent pt-1 pb-2 px-1"
            >
              {previewVideos.map((video, index) => (
                <button
                  key={video.id}
                  onClick={() => {
                    setPreviewIndex(index)
                    setPreviewVideo(video)
                  }}
                  className={`relative flex-shrink-0 w-24 h-14 bg-slate-800 rounded-lg overflow-hidden transition-all ${
                    index === previewIndex
                      ? 'ring-2 ring-red-500 opacity-100 scale-105'
                      : 'opacity-60 hover:opacity-100'
                  }`}
                >
                  <img
                    src={getCachedThumbnailUrl(video)}
                    alt=""
                    className="w-full h-full object-cover"
                    onError={(e) => {
                      const target = e.target as HTMLImageElement
                      if (video.thumbnail && target.src !== video.thumbnail) {
                        target.src = video.thumbnail
                      }
                    }}
                  />
                  <div className="absolute inset-0 bg-black/30 flex items-center justify-center">
                    <Play className="w-4 h-4 text-white/80" />
                  </div>
                  {video.duration > 0 && (
                    <div className="absolute bottom-0.5 right-0.5 px-1 py-0.5 bg-black/80 text-white text-[10px] rounded">
                      {formatDuration(video.duration)}
                    </div>
                  )}
                </button>
              ))}
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
