import { useState, useEffect } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { useBreadcrumb } from '../hooks/useBreadcrumb'
import { breadcrumbConfig } from '../config/breadcrumbConfig'
import {
  ListVideo, Download, Trash2, Pause, RefreshCw, Play, StopCircle,
  Edit2, Calendar, Youtube, ExternalLink, Loader2, Video,
  ChevronLeft, ChevronRight, ChevronDown, CheckSquare, Square, XSquare,
  AlertCircle, Clock, Check, X, Film,
  type LucideIcon,
} from 'lucide-react'
import { api } from '../lib/api'
import { formatDateOnly } from '../lib/utils'
import { notificationManager } from '../lib/notificationManager'
import { FilterBar, FilterSection, ActiveFilter } from '../components/FilterPopover'

interface ProcessorStatus {
  is_running: boolean
  is_paused: boolean
  current_item_id: number | null
  current_video_id: string | null
  current_title: string | null
  processed_count: number
  failed_count: number
  started_at: string | null
  pending_count: number
}

interface QueueItem {
  id: number
  platform: string
  video_id: string
  url: string
  title: string
  custom_title: string | null
  channel_name: string | null
  thumbnail: string | null
  duration: number | null
  upload_date: string | null
  custom_date: string | null
  view_count: number | null
  max_resolution: number | null
  max_width: number | null
  source_type: string | null
  source_name: string | null
  priority: number
  status: string
  progress: number
  error_message: string | null
  file_path: string | null
  added_at: string
}

interface QueueStats {
  total: number
  pending: number
  downloading: number
  completed: number
  failed: number
  paused: number
}

const STATUS_CONFIG: Record<string, { label: string; color: string; icon: LucideIcon }> = {
  pending: { label: 'Pending', color: 'bg-yellow-500/10 text-yellow-600', icon: Clock },
  downloading: { label: 'Downloading', color: 'bg-blue-500/10 text-blue-600', icon: Download },
  completed: { label: 'Completed', color: 'bg-green-500/10 text-green-600', icon: Check },
  failed: { label: 'Failed', color: 'bg-red-500/10 text-red-600', icon: AlertCircle },
  paused: { label: 'Paused', color: 'bg-slate-500/10 text-slate-600', icon: Pause }
}

const formatDuration = (seconds: number | null): 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 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 - proxies through backend to cache YouTube thumbnails
const getCachedThumbnailUrl = (item: { platform: string; video_id: string; thumbnail?: string | null }): string => {
  if (!item.video_id || !item.platform) {
    return item.thumbnail || ''
  }
  // Security: Auth via httpOnly cookie only - no token in URL
  return `/api/video/thumbnail/${item.platform}/${item.video_id}?source=queue`
}

const ITEMS_PER_PAGE = 20

export default function DownloadQueue() {
  useBreadcrumb(breadcrumbConfig['/queue'])
  const queryClient = useQueryClient()

  // State
  const [statusFilter, setStatusFilter] = useState<string>('pending')
  const [sortOrder, setSortOrder] = useState<'download_order' | 'recently_added'>('download_order')
  const [searchQuery, setSearchQuery] = useState('')
  const [currentPage, setCurrentPage] = useState(1)
  const [selectedItems, setSelectedItems] = useState<Set<number>>(new Set())
  const [editingItem, setEditingItem] = useState<QueueItem | null>(null)
  const [editForm, setEditForm] = useState({ title: '', date: '' })
  const [previewVideo, setPreviewVideo] = useState<QueueItem | null>(null)
  const [previewIndex, setPreviewIndex] = useState<number>(-1)
  const [showMetadata, setShowMetadata] = useState(false)

  // Fetch queue items
  const { data: queueData, isLoading, refetch } = useQuery({
    queryKey: ['download-queue', statusFilter, sortOrder, currentPage, searchQuery],
    queryFn: async () => {
      const offset = (currentPage - 1) * ITEMS_PER_PAGE
      let url = `/video-queue?limit=${ITEMS_PER_PAGE}&offset=${offset}&sort=${sortOrder}`
      if (statusFilter && statusFilter !== 'all') url += `&status=${statusFilter}`
      if (searchQuery) url += `&search=${encodeURIComponent(searchQuery)}`
      const response = await api.get<{ items: QueueItem[]; total: number; stats: QueueStats }>(url)
      return response
    },
    refetchInterval: 5000 // Refresh every 5 seconds for download progress
  })
  const items = queueData?.items || []
  const total = queueData?.total || 0
  const stats = queueData?.stats
  const totalPages = Math.ceil(total / ITEMS_PER_PAGE)

  // Navigate preview
  const navigatePreview = (direction: 'prev' | 'next') => {
    if (previewIndex === -1) return
    const newIndex = direction === 'prev' ? previewIndex - 1 : previewIndex + 1
    if (newIndex >= 0 && newIndex < items.length) {
      setPreviewIndex(newIndex)
      setPreviewVideo(items[newIndex])
    }
  }

  // Open preview
  const openPreview = (item: QueueItem, index: number) => {
    setPreviewVideo(item)
    setPreviewIndex(index)
  }

  // Keyboard handler for video player
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (!previewVideo) return
      if (e.key === 'Escape') {
        setPreviewVideo(null)
        setPreviewIndex(-1)
      } else if (e.key === 'ArrowLeft') {
        navigatePreview('prev')
      } else if (e.key === 'ArrowRight') {
        navigatePreview('next')
      } else if (e.key === 'i' || e.key === 'I') {
        setShowMetadata(prev => !prev)
      }
    }
    window.addEventListener('keydown', handleKeyDown)
    return () => window.removeEventListener('keydown', handleKeyDown)
  }, [previewVideo, previewIndex, items])

  const closePreview = () => {
    setPreviewVideo(null)
    setPreviewIndex(-1)
    setShowMetadata(false)
  }

  // Update item mutation
  const updateItemMutation = useMutation({
    mutationFn: async ({ id, data }: { id: number; data: any }) => {
      return await api.patch(`/video-queue/${id}`, data)
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['download-queue'] })
      setEditingItem(null)
      notificationManager.success('Updated', 'Queue item updated successfully')
    },
    onError: (error: any) => {
      notificationManager.error('Error', error.message || 'Failed to update item')
    }
  })

  // Delete item mutation
  const deleteItemMutation = useMutation({
    mutationFn: async (id: number) => {
      return await api.delete(`/video-queue/${id}`)
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['download-queue'] })
      notificationManager.success('Removed', 'Item removed from queue')
    }
  })

  // Bulk action mutation
  const bulkActionMutation = useMutation({
    mutationFn: async ({ ids, action }: { ids: number[]; action: string }) => {
      return await api.post('/video-queue/bulk-action', { ids, action })
    },
    onSuccess: (data: any) => {
      queryClient.invalidateQueries({ queryKey: ['download-queue'] })
      setSelectedItems(new Set())
      notificationManager.success('Done', `${data.updated_count || 0} items updated`)
    }
  })

  // Clear completed mutation
  const clearCompletedMutation = useMutation({
    mutationFn: async () => {
      return await api.post('/video-queue/clear-completed', {})
    },
    onSuccess: (data: any) => {
      queryClient.invalidateQueries({ queryKey: ['download-queue'] })
      notificationManager.success('Cleared', `${data.deleted_count || 0} completed items removed`)
    }
  })

  // Clear failed mutation
  const clearFailedMutation = useMutation({
    mutationFn: async () => {
      return await api.post('/video-queue/clear-failed', {})
    },
    onSuccess: (data: any) => {
      queryClient.invalidateQueries({ queryKey: ['download-queue'] })
      notificationManager.success('Cleared', `${data.deleted_count || 0} failed items removed`)
    }
  })

  // Fetch processor status
  const { data: processorData } = useQuery({
    queryKey: ['queue-processor-status'],
    queryFn: async () => {
      const response = await api.get<{ success: boolean; processor: ProcessorStatus }>('/video-queue/processor/status')
      return response.processor
    },
    refetchInterval: 2000 // Check status every 2 seconds
  })
  const processorStatus = processorData

  // Download selected mutation
  const downloadSelectedMutation = useMutation({
    mutationFn: async (ids: number[]) => {
      return await api.post('/video-queue/processor/start-selected', { ids })
    },
    onSuccess: (data: any) => {
      queryClient.invalidateQueries({ queryKey: ['queue-processor-status'] })
      queryClient.invalidateQueries({ queryKey: ['download-queue'] })
      setSelectedItems(new Set())
      notificationManager.success('Started', data.message || 'Downloading selected items')
    },
    onError: (error: any) => {
      notificationManager.error('Error', error.message || 'Failed to start download')
    }
  })

  // Start processor mutation
  const startProcessorMutation = useMutation({
    mutationFn: async () => {
      return await api.post('/video-queue/processor/start', {})
    },
    onSuccess: (data: any) => {
      queryClient.invalidateQueries({ queryKey: ['queue-processor-status'] })
      notificationManager.success('Started', data.message || 'Queue processor started')
    },
    onError: (error: any) => {
      notificationManager.error('Error', error.message || 'Failed to start processor')
    }
  })

  // Pause processor mutation
  const pauseProcessorMutation = useMutation({
    mutationFn: async () => {
      return await api.post('/video-queue/processor/pause', {})
    },
    onSuccess: (data: any) => {
      queryClient.invalidateQueries({ queryKey: ['queue-processor-status'] })
      notificationManager.success('Paused', data.message || 'Queue processor paused')
    },
    onError: (error: any) => {
      notificationManager.error('Error', error.message || 'Failed to pause processor')
    }
  })

  // Stop processor mutation
  const stopProcessorMutation = useMutation({
    mutationFn: async () => {
      return await api.post('/video-queue/processor/stop', {})
    },
    onSuccess: (data: any) => {
      queryClient.invalidateQueries({ queryKey: ['queue-processor-status'] })
      notificationManager.success('Stopped', data.message || 'Queue processor stopped')
    },
    onError: (error: any) => {
      notificationManager.error('Error', error.message || 'Failed to stop processor')
    }
  })

  // Handle edit save
  const handleSaveEdit = () => {
    if (!editingItem) return
    const updates: any = {}
    if (editForm.title && editForm.title !== editingItem.title) {
      updates.custom_title = editForm.title
    }
    if (editForm.date) {
      updates.custom_date = editForm.date
    }
    if (Object.keys(updates).length > 0) {
      updateItemMutation.mutate({ id: editingItem.id, data: updates })
    } else {
      setEditingItem(null)
    }
  }

  // Open edit modal
  const openEditModal = (item: QueueItem) => {
    setEditingItem(item)
    setEditForm({
      title: item.custom_title || item.title,
      date: item.custom_date || item.upload_date || ''
    })
  }

  // Selection handlers
  const toggleSelection = (id: number) => {
    setSelectedItems(prev => {
      const next = new Set(prev)
      if (next.has(id)) next.delete(id)
      else next.add(id)
      return next
    })
  }

  const selectAll = () => {
    setSelectedItems(new Set(items.map(i => i.id)))
  }

  const clearSelection = () => {
    setSelectedItems(new Set())
  }

  // Page change
  const handlePageChange = (page: number) => {
    setCurrentPage(page)
    setSelectedItems(new Set())
  }

  // Filter change
  const handleFilterChange = (filter: string) => {
    setStatusFilter(filter)
    setCurrentPage(1)
    setSelectedItems(new Set())
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex flex-col gap-4">
        <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">
              <ListVideo className="w-6 h-6 sm:w-8 sm:h-8 text-indigo-500" />
              Download Queue
            </h1>
            <p className="text-sm sm:text-base text-slate-600 dark:text-slate-400 mt-1">
              Manage pending and completed downloads
            </p>
          </div>

          {/* Processor Controls - Primary actions */}
          <div className="flex items-center gap-2">
            {processorStatus?.is_running && !processorStatus?.is_paused ? (
              <button
                onClick={() => pauseProcessorMutation.mutate()}
                disabled={pauseProcessorMutation.isPending}
                className="flex items-center justify-center gap-2 px-3 sm:px-4 py-2.5 bg-yellow-600 text-white rounded-lg hover:bg-yellow-700 transition-colors disabled:opacity-50 min-h-[44px]"
              >
                <Pause className="w-4 h-4" />
                <span>Pause</span>
              </button>
            ) : processorStatus?.is_paused ? (
              <>
                <button
                  onClick={() => startProcessorMutation.mutate()}
                  disabled={startProcessorMutation.isPending}
                  className="flex items-center justify-center gap-2 px-3 sm:px-4 py-2.5 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors disabled:opacity-50 min-h-[44px] btn-hover-lift"
                >
                  <Play className="w-4 h-4" />
                  <span>Resume</span>
                </button>
                <button
                  onClick={() => stopProcessorMutation.mutate()}
                  disabled={stopProcessorMutation.isPending}
                  className="flex items-center justify-center gap-2 px-3 sm:px-4 py-2.5 bg-red-600 text-white rounded-lg hover:bg-red-700 transition-colors disabled:opacity-50 min-h-[44px]"
                >
                  <StopCircle className="w-4 h-4" />
                  <span className="hidden sm:inline">Stop</span>
                </button>
              </>
            ) : (
              <button
                onClick={() => startProcessorMutation.mutate()}
                disabled={startProcessorMutation.isPending || (processorStatus?.pending_count === 0)}
                className="flex items-center justify-center gap-2 px-3 sm:px-4 py-2.5 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors disabled:opacity-50 min-h-[44px] btn-hover-lift"
              >
                {startProcessorMutation.isPending ? (
                  <Loader2 className="w-4 h-4 animate-spin" />
                ) : (
                  <Play className="w-4 h-4" />
                )}
                <span className="hidden xs:inline">Start</span>
                <span className="hidden sm:inline"> Downloads</span>
              </button>
            )}

            <button
              onClick={() => refetch()}
              className="flex items-center justify-center gap-2 p-2.5 sm:px-4 sm:py-2.5 text-slate-600 dark:text-slate-300 hover:bg-slate-100 dark:hover:bg-slate-700 rounded-lg transition-colors min-h-[44px]"
              title="Refresh"
            >
              <RefreshCw className="w-4 h-4" />
              <span className="hidden sm:inline">Refresh</span>
            </button>
          </div>
        </div>

        {/* Secondary actions - Clear buttons */}
        {stats && (stats.completed > 0 || stats.failed > 0) && (
          <div className="flex flex-wrap items-center gap-2">
            {stats.completed > 0 && (
              <button
                onClick={() => clearCompletedMutation.mutate()}
                disabled={clearCompletedMutation.isPending}
                className="flex items-center gap-2 px-3 py-2 text-sm bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors disabled:opacity-50 min-h-[44px] btn-hover-lift"
              >
                <Check className="w-4 h-4" />
                Clear Completed ({stats.completed})
              </button>
            )}
            {stats.failed > 0 && (
              <button
                onClick={() => clearFailedMutation.mutate()}
                disabled={clearFailedMutation.isPending}
                className="flex items-center gap-2 px-3 py-2 text-sm bg-red-600 text-white rounded-lg hover:bg-red-700 transition-colors disabled:opacity-50 min-h-[44px]"
              >
                <X className="w-4 h-4" />
                Clear Failed ({stats.failed})
              </button>
            )}
          </div>
        )}
      </div>

      {/* Processor Status Banner */}
      {processorStatus?.is_running && (
        <div className={`rounded-lg p-4 shadow-sm ${processorStatus.is_paused ? 'bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800' : 'bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800'}`}>
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-3">
              {processorStatus.is_paused ? (
                <Pause className="w-5 h-5 text-yellow-600" />
              ) : (
                <Loader2 className="w-5 h-5 text-blue-600 animate-spin" />
              )}
              <div>
                <div className="font-medium text-slate-800 dark:text-slate-200">
                  {processorStatus.is_paused ? 'Queue Paused' : 'Processing Queue'}
                </div>
                {processorStatus.current_title && (
                  <div className="text-sm text-slate-600 dark:text-slate-400">
                    {processorStatus.is_paused ? 'Paused at: ' : 'Downloading: '}
                    {processorStatus.current_title.substring(0, 60)}{processorStatus.current_title.length > 60 ? '...' : ''}
                  </div>
                )}
              </div>
            </div>
            <div className="flex items-center gap-4 text-sm">
              <span className="text-green-600">
                <Check className="w-4 h-4 inline mr-1" />
                {processorStatus.processed_count} completed
              </span>
              {processorStatus.failed_count > 0 && (
                <span className="text-red-600">
                  <X className="w-4 h-4 inline mr-1" />
                  {processorStatus.failed_count} failed
                </span>
              )}
              <span className="text-slate-500">
                {processorStatus.pending_count} remaining
              </span>
            </div>
          </div>
        </div>
      )}

      {/* Stats Bar */}
      {stats && (
        <div className="grid grid-cols-3 sm:grid-cols-6 gap-2 sm:gap-4">
          <div className="card-glass-hover rounded-xl p-2.5 sm:p-4 border stat-card-blue shadow-blue-glow">
            <div className="text-lg sm:text-2xl font-bold text-foreground animate-count-up">{stats.total}</div>
            <div className="text-xs sm:text-sm text-muted-foreground">Total</div>
          </div>
          <div className="card-glass-hover rounded-xl p-2.5 sm:p-4 border stat-card-orange shadow-orange-glow">
            <div className="text-lg sm:text-2xl font-bold text-amber-600 dark:text-amber-400 animate-count-up">{stats.pending}</div>
            <div className="text-xs sm:text-sm text-muted-foreground">Pending</div>
          </div>
          <div className="card-glass-hover rounded-xl p-2.5 sm:p-4 border stat-card-cyan">
            <div className="text-lg sm:text-2xl font-bold text-cyan-600 dark:text-cyan-400 animate-count-up">{stats.downloading}</div>
            <div className="text-xs sm:text-sm text-muted-foreground">Active</div>
          </div>
          <div className="card-glass-hover rounded-xl p-2.5 sm:p-4 border stat-card-green shadow-green-glow">
            <div className="text-lg sm:text-2xl font-bold text-emerald-600 dark:text-emerald-400 animate-count-up">{stats.completed}</div>
            <div className="text-xs sm:text-sm text-muted-foreground">Done</div>
          </div>
          <div className="card-glass-hover rounded-xl p-2.5 sm:p-4 border stat-card-red shadow-red-glow">
            <div className="text-lg sm:text-2xl font-bold text-red-600 dark:text-red-400 animate-count-up">{stats.failed}</div>
            <div className="text-xs sm:text-sm text-muted-foreground">Failed</div>
          </div>
          <div className="card-glass-hover rounded-xl p-2.5 sm:p-4 border bg-gradient-to-br from-slate-500/10 via-slate-500/5 to-gray-500/10 border-slate-500/20">
            <div className="text-lg sm:text-2xl font-bold text-slate-600 dark:text-slate-400 animate-count-up">{stats.paused}</div>
            <div className="text-xs sm:text-sm text-muted-foreground">Paused</div>
          </div>
        </div>
      )}

      {/* Filters */}
      <div className="card-glass-hover rounded-xl p-4 relative z-30">
        <FilterBar
          searchValue={searchQuery}
          onSearchChange={(value) => {
            setSearchQuery(value)
            setCurrentPage(1)
          }}
          searchPlaceholder="Search by title..."
          filterSections={[
            {
              id: 'status',
              label: 'Status',
              type: 'select',
              options: [
                { value: 'all', label: 'All Status' },
                { value: 'pending', label: 'Pending' },
                { value: 'completed', label: 'Completed' },
                { value: 'failed', label: 'Failed' },
                { value: 'paused', label: 'Paused' },
              ],
              value: statusFilter,
              onChange: (value) => handleFilterChange(value as string),
            },
            {
              id: 'sort',
              label: 'Sort By',
              type: 'select',
              options: [
                { value: 'download_order', label: 'Download Order' },
                { value: 'recently_added', label: 'Recently Added' },
              ],
              value: sortOrder,
              onChange: (value) => {
                setSortOrder(value as 'download_order' | 'recently_added')
                setCurrentPage(1)
              },
            },
          ] as FilterSection[]}
          activeFilters={[
            ...(statusFilter !== 'all' ? [{
              id: 'status',
              label: 'Status',
              value: statusFilter,
              displayValue: statusFilter.charAt(0).toUpperCase() + statusFilter.slice(1),
              onRemove: () => setStatusFilter('all'),
            }] : []),
            ...(searchQuery ? [{
              id: 'search',
              label: 'Search',
              value: searchQuery,
              displayValue: `"${searchQuery}"`,
              onRemove: () => setSearchQuery(''),
            }] : []),
          ] as ActiveFilter[]}
          onClearAll={() => {
            setStatusFilter('all')
            setSearchQuery('')
          }}
          totalCount={total}
          countLabel="items"
        />
      </div>

      {/* Selection Actions */}
      {items.length > 0 && (
        <div className="card-glass rounded-xl p-2 sm:p-3">
          <div className="flex flex-wrap items-center gap-2 sm:gap-4">
            {/* Selection buttons */}
            <div className="flex items-center gap-1 sm:gap-2">
              <button
                onClick={selectAll}
                className="flex items-center gap-1 px-2 sm:px-3 py-2 text-xs sm:text-sm hover:bg-slate-100 dark:hover:bg-slate-700 rounded-lg min-h-[44px]"
              >
                <CheckSquare className="w-4 h-4" />
                <span className="hidden xs:inline">Select</span> All
              </button>
              <button
                onClick={clearSelection}
                className="flex items-center gap-1 px-2 sm:px-3 py-2 text-xs sm:text-sm hover:bg-slate-100 dark:hover:bg-slate-700 rounded-lg min-h-[44px]"
              >
                <XSquare className="w-4 h-4" />
                Clear
              </button>
            </div>

            {selectedItems.size > 0 && (
              <>
                <div className="text-xs sm:text-sm text-indigo-600 dark:text-indigo-400 font-medium">
                  {selectedItems.size} selected
                </div>
                <div className="flex items-center gap-1 sm:gap-2">
                  <button
                    onClick={() => downloadSelectedMutation.mutate(Array.from(selectedItems))}
                    disabled={downloadSelectedMutation.isPending || processorStatus?.is_running}
                    className="flex items-center justify-center gap-1 sm:gap-2 px-2 sm:px-3 py-1.5 bg-green-600 text-white rounded-lg hover:bg-green-700 text-xs sm:text-sm min-h-[44px] min-w-[44px] disabled:opacity-50 btn-hover-lift"
                    title="Download selected"
                  >
                    {downloadSelectedMutation.isPending ? (
                      <Loader2 className="w-4 h-4 animate-spin" />
                    ) : (
                      <Download className="w-4 h-4" />
                    )}
                    <span className="hidden sm:inline">Download</span>
                  </button>
                  <button
                    onClick={() => bulkActionMutation.mutate({ ids: Array.from(selectedItems), action: 'retry' })}
                    className="flex items-center justify-center gap-1 sm:gap-2 px-2 sm:px-3 py-1.5 bg-blue-600 text-white rounded-lg hover:bg-blue-700 text-xs sm:text-sm min-h-[44px] min-w-[44px] btn-hover-lift"
                    title="Retry selected"
                  >
                    <RefreshCw className="w-4 h-4" />
                    <span className="hidden sm:inline">Retry</span>
                  </button>
                  <button
                    onClick={() => bulkActionMutation.mutate({ ids: Array.from(selectedItems), action: 'pause' })}
                    className="flex items-center justify-center gap-1 sm:gap-2 px-2 sm:px-3 py-1.5 bg-slate-600 text-white rounded-lg hover:bg-slate-700 text-xs sm:text-sm min-h-[44px] min-w-[44px]"
                    title="Pause selected"
                  >
                    <Pause className="w-4 h-4" />
                    <span className="hidden sm:inline">Pause</span>
                  </button>
                  <button
                    onClick={() => bulkActionMutation.mutate({ ids: Array.from(selectedItems), action: 'delete' })}
                    className="flex items-center justify-center gap-1 sm:gap-2 px-2 sm:px-3 py-1.5 bg-red-600 text-white rounded-lg hover:bg-red-700 text-xs sm:text-sm min-h-[44px] min-w-[44px]"
                    title="Remove selected"
                  >
                    <Trash2 className="w-4 h-4" />
                    <span className="hidden sm:inline">Remove</span>
                  </button>
                </div>
              </>
            )}

            <div className="flex-1" />

            {/* Pagination */}
            {totalPages > 1 && (
              <div className="flex items-center gap-1 sm: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 min-w-[44px] min-h-[44px] flex items-center justify-center"
                >
                  <ChevronLeft className="w-4 h-4" />
                </button>
                <span className="text-xs sm:text-sm whitespace-nowrap">
                  {currentPage}/{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 min-w-[44px] min-h-[44px] flex items-center justify-center"
                >
                  <ChevronRight className="w-4 h-4" />
                </button>
              </div>
            )}
          </div>
        </div>
      )}

      {/* Queue List */}
      <div className="card-glass rounded-xl overflow-hidden">
        {isLoading ? (
          <div className="flex items-center justify-center p-12">
            <Loader2 className="w-8 h-8 animate-spin text-indigo-500" />
          </div>
        ) : items.length === 0 ? (
          <div className="text-center p-12">
            <ListVideo className="w-12 h-12 mx-auto text-slate-400 mb-4" />
            <h3 className="text-lg font-medium mb-2">Queue is empty</h3>
            <p className="text-slate-600 dark:text-slate-400">
              Add videos from Internet Discovery or Video Downloader
            </p>
          </div>
        ) : (
          <div className="divide-y divide-slate-200 dark:divide-slate-700">
            {items.map((item, index) => {
              const statusConfig = STATUS_CONFIG[item.status] || STATUS_CONFIG.pending
              const StatusIcon = statusConfig.icon
              const isSelected = selectedItems.has(item.id)
              const displayTitle = item.custom_title || item.title
              const displayDate = item.custom_date || item.upload_date

              return (
                <div
                  key={item.id}
                  className={`p-3 sm:p-4 hover:bg-slate-50 dark:hover:bg-slate-700/50 ${
                    isSelected ? 'bg-indigo-50 dark:bg-indigo-900/20' : ''
                  }`}
                >
                  {/* Mobile Layout */}
                  <div className="flex gap-3 sm:hidden">
                    {/* Selection + Thumbnail */}
                    <div className="flex flex-col items-center gap-2">
                      <div
                        className="cursor-pointer p-1 min-w-[44px] min-h-[44px] flex items-center justify-center"
                        onClick={() => toggleSelection(item.id)}
                      >
                        {isSelected ? (
                          <CheckSquare className="w-5 h-5 text-indigo-500" />
                        ) : (
                          <Square className="w-5 h-5 text-slate-400" />
                        )}
                      </div>
                      <button
                        onClick={() => openPreview(item, index)}
                        className="w-24 h-14 flex-shrink-0 bg-slate-100 dark:bg-slate-700 rounded overflow-hidden relative block group cursor-pointer"
                      >
                        {item.video_id ? (
                          <img
                            src={getCachedThumbnailUrl(item)}
                            alt={displayTitle}
                            className="w-full h-full object-cover"
                            onError={(e) => {
                              // Fallback to original thumbnail URL if cache fails
                              const target = e.target as HTMLImageElement
                              if (item.thumbnail && target.src !== item.thumbnail) {
                                target.src = item.thumbnail
                              }
                            }}
                          />
                        ) : (
                          <div className="flex items-center justify-center h-full">
                            <Youtube className="w-6 h-6 text-slate-400" />
                          </div>
                        )}
                        {item.max_resolution && (
                          <div className="absolute bottom-0.5 right-0.5 px-1 py-0.5 bg-black/70 text-white text-[10px] font-medium rounded">
                            {formatResolution(item.max_resolution, item.max_width)}
                          </div>
                        )}
                      </button>
                    </div>

                    {/* Info */}
                    <div className="flex-1 min-w-0">
                      <h3 className="font-medium text-sm line-clamp-2" title={displayTitle}>
                        {displayTitle}
                      </h3>
                      <div className="flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-slate-500 mt-1">
                        {item.channel_name && (
                          <span className="flex items-center gap-1">
                            <Youtube className="w-3 h-3" />
                            {item.channel_name}
                          </span>
                        )}
                        {displayDate && (
                          <span>{formatDateOnly(displayDate)}</span>
                        )}
                        {item.duration && (
                          <span>{formatDuration(item.duration)}</span>
                        )}
                      </div>

                      {/* Status + Progress on mobile */}
                      <div className="flex items-center gap-2 mt-2">
                        <div className={`flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium ${statusConfig.color}`}>
                          <StatusIcon className="w-3 h-3" />
                          {statusConfig.label}
                        </div>
                        {item.status === 'downloading' && item.progress > 0 && (
                          <div className="flex-1 flex items-center gap-2">
                            <div className="flex-1 h-1.5 bg-slate-200 dark:bg-slate-600 rounded-full overflow-hidden">
                              <div
                                className="h-full bg-blue-500 transition-all progress-animated"
                                style={{ width: `${item.progress}%` }}
                              />
                            </div>
                            <span className="text-xs text-slate-500">{item.progress}%</span>
                          </div>
                        )}
                      </div>

                      {item.error_message && item.status === 'failed' && (
                        <div className="text-xs text-red-600 mt-1 line-clamp-1" title={item.error_message}>
                          {item.error_message}
                        </div>
                      )}

                      {/* Actions on mobile */}
                      <div className="flex items-center gap-1 mt-2">
                        <button
                          onClick={() => openEditModal(item)}
                          className="p-2 hover:bg-slate-100 dark:hover:bg-slate-600 rounded-lg transition-colors min-w-[44px] min-h-[44px] flex items-center justify-center"
                          title="Edit"
                        >
                          <Edit2 className="w-4 h-4 text-slate-500" />
                        </button>
                        <a
                          href={item.url}
                          target="_blank"
                          rel="noopener noreferrer"
                          className="p-2 hover:bg-slate-100 dark:hover:bg-slate-600 rounded-lg transition-colors min-w-[44px] min-h-[44px] flex items-center justify-center"
                          title="Open in YouTube"
                        >
                          <ExternalLink className="w-4 h-4 text-slate-500" />
                        </a>
                        {item.status === 'failed' && (
                          <button
                            onClick={() => updateItemMutation.mutate({ id: item.id, data: { status: 'pending' } })}
                            className="p-2 hover:bg-blue-100 dark:hover:bg-blue-900/30 rounded-lg transition-colors min-w-[44px] min-h-[44px] flex items-center justify-center"
                            title="Retry"
                          >
                            <RefreshCw className="w-4 h-4 text-blue-500" />
                          </button>
                        )}
                        <button
                          onClick={() => {
                            if (confirm('Remove this item from queue?')) {
                              deleteItemMutation.mutate(item.id)
                            }
                          }}
                          className="p-2 hover:bg-red-100 dark:hover:bg-red-900/30 rounded-lg transition-colors min-w-[44px] min-h-[44px] flex items-center justify-center"
                          title="Remove"
                        >
                          <Trash2 className="w-4 h-4 text-red-500" />
                        </button>
                      </div>
                    </div>
                  </div>

                  {/* Desktop Layout */}
                  <div className="hidden sm:flex items-center gap-4">
                    {/* Selection */}
                    <div
                      className="cursor-pointer"
                      onClick={() => toggleSelection(item.id)}
                    >
                      {isSelected ? (
                        <CheckSquare className="w-5 h-5 text-indigo-500" />
                      ) : (
                        <Square className="w-5 h-5 text-slate-400" />
                      )}
                    </div>

                    {/* Thumbnail */}
                    <button
                      onClick={() => openPreview(item, index)}
                      className="w-32 h-20 flex-shrink-0 bg-slate-100 dark:bg-slate-700 rounded overflow-hidden relative block group cursor-pointer"
                    >
                      {item.video_id ? (
                        <img
                          src={getCachedThumbnailUrl(item)}
                          alt={displayTitle}
                          className="w-full h-full object-cover group-hover:opacity-80 transition-opacity"
                          onError={(e) => {
                            const target = e.target as HTMLImageElement
                            if (item.thumbnail && target.src !== item.thumbnail) {
                              target.src = item.thumbnail
                            }
                          }}
                        />
                      ) : (
                        <div className="flex items-center justify-center h-full">
                          <Youtube className="w-8 h-8 text-slate-400" />
                        </div>
                      )}
                      {item.max_resolution && (
                        <div className="absolute bottom-1 right-1 px-1.5 py-0.5 bg-black/70 text-white text-xs font-medium rounded">
                          {formatResolution(item.max_resolution, item.max_width)}
                        </div>
                      )}
                      <div className="absolute inset-0 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity bg-black/30">
                        <Play className="w-8 h-8 text-white" />
                      </div>
                    </button>

                    {/* Info */}
                    <div className="flex-1 min-w-0">
                      <h3 className="font-medium truncate" title={displayTitle}>
                        {displayTitle}
                      </h3>
                      <div className="flex items-center gap-3 text-sm text-slate-500 mt-1">
                        {item.channel_name && (
                          <span className="flex items-center gap-1">
                            <Youtube className="w-3 h-3" />
                            {item.channel_name}
                          </span>
                        )}
                        {displayDate && (
                          <span className="flex items-center gap-1">
                            <Calendar className="w-3 h-3" />
                            {formatDateOnly(displayDate)}
                          </span>
                        )}
                        {item.duration && (
                          <span>{formatDuration(item.duration)}</span>
                        )}
                      </div>
                      {item.source_name && (
                        <div className="text-xs text-indigo-600 dark:text-indigo-400 mt-1">
                          Source: {item.source_name}
                        </div>
                      )}
                      {item.error_message && item.status === 'failed' && (
                        <div className="text-xs text-red-600 mt-1 truncate" title={item.error_message}>
                          Error: {item.error_message}
                        </div>
                      )}
                    </div>

                    {/* Progress (for downloading) */}
                    {item.status === 'downloading' && item.progress > 0 && (
                      <div className="w-24">
                        <div className="h-2 bg-slate-200 dark:bg-slate-600 rounded-full overflow-hidden">
                          <div
                            className="h-full bg-blue-500 transition-all"
                            style={{ width: `${item.progress}%` }}
                          />
                        </div>
                        <div className="text-xs text-center mt-1 text-slate-500">
                          {item.progress}%
                        </div>
                      </div>
                    )}

                    {/* Status */}
                    <div className={`flex items-center gap-1 px-2.5 py-1 rounded-full text-xs font-medium ${statusConfig.color}`}>
                      <StatusIcon className="w-3 h-3" />
                      {statusConfig.label}
                    </div>

                    {/* Actions */}
                    <div className="flex items-center gap-1">
                      <button
                        onClick={() => openEditModal(item)}
                        className="p-2 hover:bg-slate-100 dark:hover:bg-slate-600 rounded-lg transition-colors"
                        title="Edit"
                      >
                        <Edit2 className="w-4 h-4 text-slate-500" />
                      </button>
                      <a
                        href={item.url}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="p-2 hover:bg-slate-100 dark:hover:bg-slate-600 rounded-lg transition-colors"
                        title="Open in YouTube"
                      >
                        <ExternalLink className="w-4 h-4 text-slate-500" />
                      </a>
                      {item.status === 'failed' && (
                        <button
                          onClick={() => updateItemMutation.mutate({ id: item.id, data: { status: 'pending' } })}
                          className="p-2 hover:bg-blue-100 dark:hover:bg-blue-900/30 rounded-lg transition-colors"
                          title="Retry"
                        >
                          <RefreshCw className="w-4 h-4 text-blue-500" />
                        </button>
                      )}
                      <button
                        onClick={() => {
                          if (confirm('Remove this item from queue?')) {
                            deleteItemMutation.mutate(item.id)
                          }
                        }}
                        className="p-2 hover:bg-red-100 dark:hover:bg-red-900/30 rounded-lg transition-colors"
                        title="Remove"
                      >
                        <Trash2 className="w-4 h-4 text-red-500" />
                      </button>
                    </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 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"
            >
              <ChevronLeft className="w-4 h-4" />
            </button>

            {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"
            >
              <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 text-sm"
            >
              Last
            </button>
          </div>
        )}
      </div>

      {/* Edit Modal */}
      {editingItem && (
        <div className="fixed inset-0 bg-black/50 backdrop-blur-sm flex items-end sm:items-center justify-center z-50 p-0 sm:p-4 pt-[env(safe-area-inset-top)]">
          <div className="bg-card border border-border rounded-t-xl sm:rounded-xl shadow-2xl w-full sm:max-w-lg p-4 sm:p-6 max-h-[85vh] sm:max-h-[90vh] overflow-y-auto custom-scrollbar pb-[calc(1rem+env(safe-area-inset-bottom))]">
            <h2 className="text-lg sm:text-xl font-bold mb-4">Edit Queue Item</h2>

            <div className="space-y-4">
              <div>
                <label className="block text-sm font-medium mb-1">Title (for filename)</label>
                <input
                  type="text"
                  value={editForm.title}
                  onChange={(e) => setEditForm({ ...editForm, title: e.target.value })}
                  className="w-full px-3 py-2.5 border border-border rounded-lg bg-background text-foreground min-h-[44px]"
                />
                <p className="text-xs text-muted-foreground mt-1">
                  This will be used as the filename when downloading
                </p>
              </div>

              <div>
                <label className="block text-sm font-medium mb-1">Upload Date</label>
                <input
                  type="date"
                  value={editForm.date ? editForm.date.split('T')[0] : ''}
                  onChange={(e) => setEditForm({ ...editForm, date: e.target.value })}
                  className="w-full px-3 py-2.5 border border-border rounded-lg bg-background text-foreground min-h-[44px]"
                />
                <p className="text-xs text-muted-foreground mt-1">
                  Override the video's upload date
                </p>
              </div>
            </div>

            <div className="flex flex-col-reverse sm:flex-row justify-end gap-2 sm:gap-3 mt-6">
              <button
                onClick={() => setEditingItem(null)}
                className="px-4 py-2.5 text-slate-600 hover:bg-slate-100 dark:hover:bg-slate-700 rounded-lg min-h-[44px]"
              >
                Cancel
              </button>
              <button
                onClick={handleSaveEdit}
                disabled={updateItemMutation.isPending}
                className="px-4 py-2.5 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 disabled:opacity-50 min-h-[44px]"
              >
                {updateItemMutation.isPending ? 'Saving...' : 'Save Changes'}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Video Player Modal */}
      {previewVideo && (
        <div
          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-2 sm:p-4 z-10 safe-area-top" onClick={(e) => e.stopPropagation()}>
            <div className="flex items-center justify-between max-w-7xl mx-auto gap-2">
              <div className="flex-1 min-w-0 text-white">
                <h3 className="text-sm sm:text-lg font-medium truncate">{previewVideo.custom_title || previewVideo.title}</h3>
                <p className="text-xs sm:text-sm text-white/70">
                  {previewIndex + 1} / {items.length}
                </p>
              </div>

              {/* Close Button */}
              <button
                onClick={closePreview}
                className="p-2 hover:bg-white/20 rounded-lg transition-colors min-w-[44px] min-h-[44px] flex items-center justify-center"
                title="Close (Esc)"
              >
                <X className="w-6 h-6 text-white" />
              </button>
            </div>
          </div>

          {/* Navigation Buttons - Hidden on mobile, use swipe instead */}
          <button
            onClick={(e) => { e.stopPropagation(); navigatePreview('prev'); }}
            disabled={previewIndex === 0}
            className="hidden sm:flex absolute left-2 sm:left-4 top-1/2 -translate-y-1/2 p-2 sm:p-3 bg-black/50 hover:bg-black/70 rounded-full text-white disabled:opacity-30 transition-colors z-10 min-w-[44px] min-h-[44px] items-center justify-center"
            title="Previous (←)"
          >
            <ChevronLeft className="w-6 h-6 sm:w-8 sm:h-8" />
          </button>

          <button
            onClick={(e) => { e.stopPropagation(); navigatePreview('next'); }}
            disabled={previewIndex === items.length - 1}
            className="hidden sm:flex absolute right-2 sm:right-4 top-1/2 -translate-y-1/2 p-2 sm:p-3 bg-black/50 hover:bg-black/70 rounded-full text-white disabled:opacity-30 transition-colors z-10 min-w-[44px] min-h-[44px] items-center justify-center"
            title="Next (→)"
          >
            <ChevronRight className="w-6 h-6 sm:w-8 sm:h-8" />
          </button>

          {/* Main Content Area */}
          <div className="flex-1 flex items-center justify-center p-2 sm:p-4 pt-16 sm:pt-20 pb-28 sm: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 === 'completed' && previewVideo.file_path ? (
                /* Local video player for downloaded files */
                <div className="w-[90vw] max-w-6xl flex justify-center">
                  <video
                    src={`/api/video-queue/${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>
              ) : (
                /* Embedded player for non-downloaded videos */
                <div className="relative w-[90vw] max-w-6xl aspect-video bg-black rounded-xl overflow-hidden shadow-2xl">
                  <iframe
                    src={previewVideo.platform === 'dailymotion'
                      ? `https://www.dailymotion.com/embed/video/${previewVideo.video_id}?autoplay=1`
                      : `https://www.youtube-nocookie.com/embed/${previewVideo.video_id}?autoplay=1&rel=0&modestbranding=1`
                    }
                    title={previewVideo.title}
                    className="absolute inset-0 w-full h-full z-10"
                    allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
                    allowFullScreen
                  />
                </div>
              )}

              {/* Video Info Bar */}
              <div className="mt-2 sm:mt-4 flex flex-wrap items-center gap-2 sm:gap-4 text-white/80 text-xs sm:text-sm">
                <span className="flex items-center gap-1">
                  {previewVideo.platform === 'dailymotion' ? (
                    <Video className="w-3 h-3 sm:w-4 sm:h-4" />
                  ) : (
                    <Youtube className="w-3 h-3 sm:w-4 sm:h-4" />
                  )}
                  {previewVideo.channel_name || 'Unknown'}
                </span>
                {previewVideo.upload_date && (
                  <span className="flex items-center gap-1">
                    <Calendar className="w-3 h-3 sm:w-4 sm:h-4" />
                    {formatDateOnly(previewVideo.upload_date)}
                  </span>
                )}
                {previewVideo.duration && (
                  <span>{formatDuration(previewVideo.duration)}</span>
                )}
                {previewVideo.max_resolution && (
                  <span className="flex items-center gap-1 text-emerald-400 font-medium">
                    <Film className="w-3 h-3 sm:w-4 sm:h-4" />
                    {formatResolution(previewVideo.max_resolution, previewVideo.max_width)}
                  </span>
                )}
                <div className="hidden sm:block flex-1" />
                {previewVideo.source_name && (
                  <span className="text-indigo-400 font-medium">{previewVideo.source_name}</span>
                )}
              </div>
            </div>
          </div>

          {/* Metadata Toggle Button - Hidden on mobile */}
          <button
            onClick={(e) => { e.stopPropagation(); setShowMetadata(!showMetadata); }}
            className="hidden sm:flex 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] items-center justify-center"
            title="Toggle Metadata (I)"
          >
            <ChevronDown className={`w-5 h-5 transition-transform duration-200 ${showMetadata ? '-rotate-90' : 'rotate-90'}`} />
          </button>

          {/* Metadata Panel - Hidden on mobile */}
          <div
            className={`hidden sm:block 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.custom_title || previewVideo.title}</div>
                  </div>
                  {previewVideo.channel_name && (
                    <div>
                      <div className="text-white/60 mb-1">Channel</div>
                      <div className="text-white">{previewVideo.channel_name}</div>
                    </div>
                  )}
                  {previewVideo.source_name && (
                    <div>
                      <div className="text-white/60 mb-1">Source</div>
                      <div className="text-indigo-400 font-medium">{previewVideo.source_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 && 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 && 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">Queue Status</div>
                    <div className={`inline-flex px-2 py-1 rounded text-xs font-medium ${
                      previewVideo.status === 'pending' ? 'bg-yellow-500/20 text-yellow-400' :
                      previewVideo.status === 'completed' ? 'bg-green-500/20 text-green-400' :
                      previewVideo.status === 'downloading' ? 'bg-blue-500/20 text-blue-400' :
                      previewVideo.status === 'failed' ? 'bg-red-500/20 text-red-400' :
                      'bg-slate-500/20 text-slate-400'
                    }`}>
                      {previewVideo.status}
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          {/* Action Buttons */}
          <div className="absolute bottom-24 sm:bottom-32 left-1/2 -translate-x-1/2 flex items-center gap-3" onClick={(e) => e.stopPropagation()}>
            {previewVideo.status === 'pending' && (
              <button
                onClick={() => {
                  updateItemMutation.mutate({ id: previewVideo.id, data: { status: 'downloading' } })
                  notificationManager.success('Starting', 'Download started')
                }}
                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>
            )}
            {previewVideo.status === 'failed' && (
              <button
                onClick={() => {
                  updateItemMutation.mutate({ id: previewVideo.id, data: { status: 'pending' } })
                  notificationManager.success('Retrying', 'Added back to queue')
                }}
                className="flex items-center gap-2 px-5 py-2.5 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-colors shadow-lg btn-hover-lift"
              >
                <RefreshCw className="w-5 h-5" />
                Retry
              </button>
            )}
            <button
              onClick={() => {
                deleteItemMutation.mutate(previewVideo.id)
                navigatePreview('next')
              }}
              className="flex items-center gap-2 px-5 py-2.5 bg-red-600 hover:bg-red-700 text-white rounded-lg transition-colors shadow-lg"
            >
              <Trash2 className="w-5 h-5" />
              Remove
            </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-2 sm:p-4 pt-6 sm:pt-8 safe-area-bottom" onClick={(e) => e.stopPropagation()}>
            <div className="flex gap-1.5 sm:gap-2 overflow-x-auto overflow-y-visible scrollbar-thin scrollbar-thumb-white/20 scrollbar-track-transparent pt-1 pb-1 sm:pb-2 px-1">
              {items.map((video, idx) => (
                <button
                  key={video.id}
                  onClick={() => openPreview(video, idx)}
                  className={`relative flex-shrink-0 w-16 h-10 sm:w-24 sm:h-14 bg-slate-800 rounded-lg overflow-hidden transition-all ${
                    idx === previewIndex
                      ? 'ring-2 ring-red-500 opacity-100 scale-105'
                      : 'opacity-60 hover:opacity-100'
                  }`}
                >
                  {video.video_id ? (
                    <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="w-full h-full bg-slate-700 flex items-center justify-center">
                      <Youtube className="w-3 h-3 sm:w-4 sm:h-4 text-slate-500" />
                    </div>
                  )}
                  <div className="absolute inset-0 bg-black/30 flex items-center justify-center">
                    <Play className="w-3 h-3 sm:w-4 sm:h-4 text-white/80" />
                  </div>
                  {video.duration && video.duration > 0 && (
                    <div className="absolute bottom-0.5 right-0.5 px-0.5 sm:px-1 py-0.5 bg-black/80 text-white text-[8px] sm:text-[10px] rounded">
                      {formatDuration(video.duration)}
                    </div>
                  )}
                </button>
              ))}
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
