import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { useEffect, useRef, useState } from 'react'
import { Link } from 'react-router-dom'
import {
  Download,
  Activity,
  Database,
  TrendingUp,
  Instagram,
  Video,
  MessageCircle,
  Globe,
  Play,
  Calendar,
  CalendarClock,
  SkipForward,
  StopCircle,
  UserPlus,
  Image,
  Eye,
  Trash2,
  LayoutDashboard,
  Search,
  Loader2,
  Pause,
  Check,
  X,
  Youtube,
  Twitter,
  Film,
  FolderInput,
  ImageIcon,
  FolderDown,
  ClipboardList,
  RefreshCw,
  HardDrive,
  Cloud,
  type LucideIcon,
} from 'lucide-react'
import { api, wsClient, PaidContentActiveTask } from '../lib/api'
import { formatBytes, formatRelativeTime, formatPlatformName, isVideoFile } from '../lib/utils'
import { notificationManager } from '../lib/notificationManager'
import EnhancedLightbox from '../components/EnhancedLightbox'
import { FlareSolverrStatus } from '../components/FlareSolverrStatus'
import { ErrorBanner } from '../components/ErrorBanner'
import { CookieHealthBanner } from '../components/CookieHealthBanner'
import UpcomingAppearancesCard from '../components/UpcomingAppearancesCard'
import { RecentItemsCard, MediaItem, ReviewItem, DiscoveryItem } from '../components/RecentItemsCard'
import { useBreadcrumb } from '../hooks/useBreadcrumb'
import { breadcrumbConfig } from '../config/breadcrumbConfig'

// Helper to get formatted task info from task_id
function getTaskInfo(taskId: string): { platform: string; account: string | null } {
  const [platformPart, accountPart] = taskId.split(':')

  // Platform name mappings
  const platformNames: Record<string, string> = {
    instagram: 'Instagram',
    instagram_unified: 'Instagram',
    fastdl: 'Instagram',
    imginn: 'Instagram',
    imginn_api: 'Instagram',
    instagram_client: 'Instagram',
    toolzu: 'Instagram',
    snapchat: 'Snapchat',
    snapchat_client: 'Snapchat',
    tiktok: 'TikTok',
    forum: 'Forums',
    monitor: 'Forum Monitor',
    appearances: 'Appearances',
    paid_content: 'Paid Content',
    youtube_channel_monitor: 'YouTube Monitor',
    youtube_monitor: 'YouTube Monitor',
    easynews_monitor: 'Easynews',
    reddit_monitor: 'Reddit Monitor',
    press_monitor: 'Press',
  }

  const platform = platformNames[platformPart.toLowerCase()] || formatPlatformName(platformPart)

  // Tasks that don't have real accounts (system tasks)
  const systemTasks = ['paid_content', 'youtube_monitor', 'youtube_channel_monitor', 'easynews_monitor', 'reddit_monitor', 'appearances', 'press_monitor']

  // For system tasks, the second part is a task type, not an account
  if (systemTasks.includes(platformPart)) {
    // Map task types to friendly names
    const taskTypeNames: Record<string, string> = {
      sync: 'All Creators',
      tmdb_sync: 'TMDb Sync',
      reminders: 'Daily Reminders',
    }
    const taskType = accountPart ? (taskTypeNames[accountPart] || null) : null
    return { platform, account: taskType }
  }

  // For regular platforms, the second part is the account name
  return { platform, account: accountPart || null }
}

function StatCard({
  title,
  value,
  icon: Icon,
  subtitle,
  color = 'blue',
}: {
  title: string
  value: string | number
  icon: LucideIcon
  subtitle?: string
  color?: string
}) {
  const colorStyles = {
    blue: {
      card: 'stat-card-blue shadow-blue-glow',
      icon: 'bg-blue-500/20 text-blue-600 dark:text-blue-400',
    },
    green: {
      card: 'stat-card-green shadow-green-glow',
      icon: 'bg-emerald-500/20 text-emerald-600 dark:text-emerald-400',
    },
    purple: {
      card: 'stat-card-purple shadow-purple-glow',
      icon: 'bg-violet-500/20 text-violet-600 dark:text-violet-400',
    },
    orange: {
      card: 'stat-card-orange shadow-orange-glow',
      icon: 'bg-amber-500/20 text-amber-600 dark:text-amber-400',
    },
    cyan: {
      card: 'stat-card-cyan',
      icon: 'bg-cyan-500/20 text-cyan-600 dark:text-cyan-400',
    },
    red: {
      card: 'stat-card-red shadow-red-glow',
      icon: 'bg-red-500/20 text-red-600 dark:text-red-400',
    },
  }

  const styles = colorStyles[color as keyof typeof colorStyles] || colorStyles.blue

  return (
    <div className={`card-glass-hover rounded-xl p-4 md:p-6 border ${styles.card}`}>
      <div className="flex items-center justify-between">
        <div className="flex-1 min-w-0">
          <p className="text-sm font-medium text-muted-foreground">{title}</p>
          <p className="mt-2 text-2xl md:text-3xl font-bold text-foreground animate-count-up">{value}</p>
          {subtitle && (
            <p className="mt-1 text-sm text-muted-foreground">{subtitle}</p>
          )}
        </div>
        <div className={`p-2.5 md:p-3 rounded-xl flex-shrink-0 ${styles.icon}`}>
          <Icon className="w-5 h-5 md:w-6 md:h-6" />
        </div>
      </div>
    </div>
  )
}

function PlatformIcon({ platform }: { platform: string }) {
  const icons: Record<string, any> = {
    instagram: Instagram,
    instagram_unified: Instagram,
    fastdl: Instagram,
    imginn: Instagram,
    toolzu: Instagram,
    snapchat: MessageCircle,
    snapchat_client: MessageCircle,
    tiktok: Video,
    forum: Globe,
    forums: Globe,
    youtube: Youtube,
    youtube_monitor: Youtube,
    youtube_channel_monitor: Youtube,
    coppermine: ImageIcon,
    appearances: Film,
    tmdb: Film,
    tvdb: Film,
    imdb: Film,
    twitter: Twitter,
    reddit: Globe,
    manual_import: FolderInput,
  }

  const Icon = icons[platform?.toLowerCase()] || Download
  return <Icon className="w-4 h-4" />
}

function PaidContentActiveTaskCard({ task }: { task: PaidContentActiveTask }) {
  const getPhaseIcon = () => {
    switch (task.phase) {
      case 'fetching':
        return <RefreshCw className="w-4 h-4 animate-spin text-blue-500" />
      case 'processing':
        return <Loader2 className="w-4 h-4 animate-spin text-amber-500" />
      case 'downloading':
        return <Download className="w-4 h-4 animate-pulse text-emerald-500" />
      default:
        return <Loader2 className="w-4 h-4 animate-spin text-primary" />
    }
  }

  const getPhaseLabel = () => {
    switch (task.phase) {
      case 'fetching': return 'Fetching posts'
      case 'processing': return 'Processing'
      case 'downloading': return 'Downloading'
      default: return 'Working'
    }
  }

  const progressPercent = task.total_files
    ? Math.round(((task.downloaded || 0) / task.total_files) * 100)
    : 0

  return (
    <div className="p-4 bg-secondary/50 rounded-lg border border-border">
      <div className="flex items-center justify-between mb-3">
        <div className="flex items-center space-x-3">
          <div className="p-2 rounded-lg bg-primary/10">
            {getPhaseIcon()}
          </div>
          <div>
            <p className="font-semibold text-foreground">{task.username}</p>
            <p className="text-xs text-muted-foreground">
              {formatPlatformName(task.platform)} • {formatPlatformName(task.service)}
            </p>
          </div>
        </div>
        <span className="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-primary/10 text-primary">
          {getPhaseLabel()}
        </span>
      </div>

      <p className="text-sm text-foreground mb-2">{task.status}</p>

      {task.phase === 'downloading' && task.total_files && (
        <div className="bg-background/50 rounded-lg p-3 space-y-2">
          <div className="flex justify-between items-center mb-1">
            <span className="text-xs font-medium text-foreground">Progress</span>
            <span className="text-xs text-muted-foreground">
              {task.downloaded || 0} / {task.total_files} ({progressPercent}%)
            </span>
          </div>
          <div className="h-2 bg-secondary rounded-full overflow-hidden">
            <div
              className="h-full bg-gradient-to-r from-primary to-emerald-500 rounded-full transition-all duration-300"
              style={{ width: `${progressPercent}%` }}
            />
          </div>

          {task.active_downloads && task.active_downloads.length > 0 && (
            <div className="pt-2 border-t border-border/50 space-y-1.5">
              <span className="text-xs text-muted-foreground">
                Downloading ({task.active_count || task.active_downloads.length}):
              </span>
              {task.active_downloads.slice(0, 2).map((dl, idx) => (
                <div key={idx} className="text-xs">
                  <div className="flex justify-between items-center mb-0.5">
                    <span className="text-foreground truncate flex-1 mr-2" title={dl.name}>
                      {dl.name.length > 30 ? dl.name.slice(0, 30) + '...' : dl.name}
                    </span>
                    <span className="text-muted-foreground whitespace-nowrap">
                      {formatBytes(dl.progress)}{dl.size ? ` / ${formatBytes(dl.size)}` : ''}
                    </span>
                  </div>
                  {dl.size && (
                    <div className="h-1 bg-secondary rounded-full overflow-hidden">
                      <div
                        className="h-full bg-blue-500 rounded-full transition-all duration-200"
                        style={{ width: `${dl.size > 0 ? Math.min(100, (dl.progress / dl.size) * 100) : 0}%` }}
                      />
                    </div>
                  )}
                </div>
              ))}
              {task.active_downloads.length > 2 && (
                <span className="text-xs text-muted-foreground">
                  +{task.active_downloads.length - 2} more...
                </span>
              )}
            </div>
          )}
        </div>
      )}

      {task.phase === 'fetching' && task.posts_fetched !== undefined && (
        <div className="bg-background/50 rounded-lg p-3">
          <p className="text-xs text-muted-foreground">
            <span className="font-medium text-foreground">{task.posts_fetched}</span> posts fetched
          </p>
        </div>
      )}
    </div>
  )
}

export default function Dashboard() {
  // Breadcrumb - just Home for Dashboard
  useBreadcrumb(breadcrumbConfig['/'])

  const queryClient = useQueryClient()
  const [selectedMedia, setSelectedMedia] = useState<any | null>(null)
  const [showAddModal, setShowAddModal] = useState(false)
  const [addPersonName, setAddPersonName] = useState('')
  const [actioningFile, setActioningFile] = useState<string | null>(null)
  const [triggering, setTriggering] = useState(false)

  // Date edit modal state
  const [showDateModal, setShowDateModal] = useState(false)
  const [editingItemId, setEditingItemId] = useState<number | null>(null)
  const [newDate, setNewDate] = useState('')
  const [updateFileTimestamps, setUpdateFileTimestamps] = useState(true)
  const [skipping, setSkipping] = useState(false)
  const [pausing, setPausing] = useState(false)
  const [stopping, setStopping] = useState(false)
  const [startingScheduler, setStartingScheduler] = useState(false)
  const [currentTime, setCurrentTime] = useState(new Date())
  const [schedulerDisabledCount, setSchedulerDisabledCount] = useState(0)

  // Appearances sync progress state
  const [appearancesSyncProgress, setAppearancesSyncProgress] = useState<{
    is_running: boolean
    current_celebrity: string | null
    celebrities_processed: number
    total_celebrities: number
    new_appearances: number
    phase: 'fetching_movies' | 'fetching_tv' | 'fetching_podcasts' | 'fetching_podcasts_taddy' | 'fetching' | 'saving' | 'complete' | null
    current_show?: string | null
    shows_processed?: number
    total_shows?: number
    current_podcast?: string | null
    podcasts_processed?: number
    total_podcasts?: number
  }>({
    is_running: false,
    current_celebrity: null,
    celebrities_processed: 0,
    total_celebrities: 0,
    new_appearances: 0,
    phase: null,
    current_show: null,
    shows_processed: 0,
    total_shows: 0,
    current_podcast: null,
    podcasts_processed: 0,
    total_podcasts: 0,
  })
  const [matchingPlex, setMatchingPlex] = useState(false)

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

  // Recent items cards state - track when user dismissed each card (synced to server)
  const { data: dismissedCards = { media: null, review: null, internet_discovery: null } } = useQuery({
    queryKey: ['dashboard-dismissed-cards'],
    queryFn: () => api.getDismissedCards(),
    staleTime: Infinity, // Don't auto-refresh, only update when we mutate
  })

  // Mutation for updating dismissed cards
  const dismissCardsMutation = useMutation({
    mutationFn: (data: { media: number | null; review: number | null; internet_discovery: number | null }) =>
      api.setDismissedCards(data),
    onMutate: async (newData) => {
      // Cancel any outgoing refetches
      await queryClient.cancelQueries({ queryKey: ['dashboard-dismissed-cards'] })
      // Snapshot the previous value
      const previousData = queryClient.getQueryData(['dashboard-dismissed-cards'])
      // Optimistically update to the new value
      queryClient.setQueryData(['dashboard-dismissed-cards'], newData)
      // Return a context with the previous value
      return { previousData }
    },
    onError: (_err, _newData, context) => {
      // Roll back to the previous value on error
      if (context?.previousData) {
        queryClient.setQueryData(['dashboard-dismissed-cards'], context.previousData)
      }
    },
    onSettled: () => {
      // Refetch to ensure we have the latest from server
      queryClient.invalidateQueries({ queryKey: ['dashboard-dismissed-cards'] })
    }
  })

  // Session-based actioned items (resets on page refresh)
  const [actionedItems, setActionedItems] = useState<Set<number | string>>(new Set())

  // Fetch initial stats - optimized polling intervals
  const { data: stats, refetch: refetchStats } = useQuery({
    queryKey: ['stats'],
    queryFn: () => api.getStats(),
    refetchInterval: 60000, // Refresh every minute (stats don't change frequently)
    staleTime: 30000, // Consider fresh for 30 seconds
  })

  const { data: systemHealth } = useQuery({
    queryKey: ['system-health'],
    queryFn: () => api.getSystemHealth(),
    refetchInterval: 60000,
    staleTime: 30000,
  })

  // Cloud backup status
  const { data: cloudBackupStatus } = useQuery<{
    configured: boolean; enabled: boolean; service_status: string;
    syncing: boolean; last_sync: string | null; state: string;
    storage_used: number | null; cooldown_remaining: number;
    error_count: number; last_error: string | null;
    active_job: {
      current_dir: string | null; dirs_synced: number; dirs_total: number;
      current_file: string | null; phase: string | null;
      transfer_stats: {
        bytes_done: string; bytes_total: string; pct: number; speed: string;
        eta?: string; files_done?: number; files_total?: number;
        checks_done?: number; checks_total?: number;
      } | null;
    } | null;
  }>({
    queryKey: ['cloud-backup-status'],
    queryFn: () => api.get('/cloud-backup/status'),
    refetchInterval: (query) => query.state.data?.syncing ? 3000 : 60000,
    staleTime: 2000,
  })

  // Fetch recent items for dashboard cards
  const { data: recentItems } = useQuery({
    queryKey: ['dashboard-recent-items'],
    queryFn: () => api.getDashboardRecentItems(),
    refetchInterval: 60000, // Refresh every minute
    staleTime: 30000,
  })

  const { data: status, refetch: refetchStatus } = useQuery({
    queryKey: ['status'],
    queryFn: () => api.getStatus(),
    refetchInterval: 60000, // Refresh every minute
    staleTime: 30000,
  })

  const { data: downloads, refetch: refetchDownloads } = useQuery({
    queryKey: ['recent-downloads'],
    queryFn: () => api.searchDownloads({ limit: 6, sortBy: 'download_date', sortOrder: 'desc' }),
    refetchInterval: 30000, // Refresh every 30 seconds (WebSocket handles real-time)
    staleTime: 15000,
  })

  const { data: currentActivity, refetch: refetchActivity } = useQuery({
    queryKey: ['current-activity'],
    queryFn: () => api.getCurrentActivity(),
    refetchInterval: 5000, // Poll every 5 seconds (reduced from 2s)
    staleTime: 3000,
  })

  const { data: schedulerStatus } = useQuery({
    queryKey: ['scheduler-status'],
    queryFn: () => api.getSchedulerStatus(),
    refetchInterval: 15000, // Poll every 15 seconds
    staleTime: 10000,
  })

  const { data: appConfig } = useQuery({
    queryKey: ['config'],
    queryFn: () => api.getConfig(),
    staleTime: 30000,
  })
  const hiddenModules = (appConfig?.hidden_modules || []) as string[]

  const { data: dashboardStats } = useQuery({
    queryKey: ['dashboard-stats'],
    queryFn: () => api.getDashboardStats(),
    refetchInterval: 120000, // Refresh every 2 minutes (expensive query)
    staleTime: 60000,
  })

  // Background tasks (YouTube monitor, etc.) - poll when there's an active task
  const { data: backgroundTasks } = useQuery({
    queryKey: ['background-tasks'],
    queryFn: () => api.getBackgroundTasks(),
    refetchInterval: 2000, // Poll every 2 seconds for real-time updates
    staleTime: 1000,
  })

  // Paid content active syncs
  const { data: paidContentActiveSyncs } = useQuery({
    queryKey: ['paid-content-active-syncs'],
    queryFn: () => api.paidContent.getActiveSyncs(),
    refetchInterval: 2000,
    staleTime: 1000,
  })

  // Video queue processor status
  const { data: processorStatus } = useQuery({
    queryKey: ['queue-processor-status'],
    queryFn: async () => {
      const response = await api.get<{ success: boolean; processor: {
        is_running: boolean
        is_paused: boolean
        current_title: string | null
        processed_count: number
        failed_count: number
        pending_count: number
      } }>('/video-queue/processor/status')
      return response.processor
    },
    refetchInterval: 2000, // Check status every 2 seconds
  })

  // Manual platform runs - poll for active manual downloads
  const { data: runningPlatforms, refetch: refetchRunningPlatforms } = useQuery({
    queryKey: ['running-platforms'],
    queryFn: () => api.getRunningPlatforms(),
    refetchInterval: 2000, // Poll every 2 seconds for real-time updates
    staleTime: 1000,
  })

  // Active scraper sessions for progress data
  const { data: activeSessions } = useQuery({
    queryKey: ['active-sessions'],
    queryFn: () => api.getActiveScraperSessions(),
    refetchInterval: 2000, // Poll every 2 seconds
    staleTime: 1000,
  })

  // Upcoming celebrity appearances
  const { data: upcomingAppearances, refetch: refetchAppearances } = useQuery({
    queryKey: ['upcoming-appearances'],
    queryFn: () => api.getUpcomingAppearances({ limit: 5, days_ahead: 30 }),
    refetchInterval: 300000, // Refresh every 5 minutes
    staleTime: 180000, // Consider fresh for 3 minutes
  })

  // Get YouTube monitor task if active
  const youtubeMonitorTask = backgroundTasks?.tasks?.find(t => t.task_id === 'youtube_monitor')

  // Get celebrity search task if active
  const celebritySearchTask = backgroundTasks?.tasks?.find(t => t.task_id === 'celebrity_search')

  // Recent downloads array (handle new API response structure)
  const recentDownloads = downloads?.results || []

  // Track scheduler disabled state with debounce to prevent flicker
  // But on initial load, trust the first response immediately
  const [hasInitialized, setHasInitialized] = useState(false)

  useEffect(() => {
    if (currentActivity?.scheduler_running === false && !currentActivity?.active) {
      // If this is the first load and scheduler is disabled, set count high immediately
      if (!hasInitialized) {
        setSchedulerDisabledCount(10)
        setHasInitialized(true)
      } else {
        setSchedulerDisabledCount(prev => prev + 1)
      }
    } else {
      setSchedulerDisabledCount(0)
      if (!hasInitialized && currentActivity) {
        setHasInitialized(true)
      }
    }
  }, [currentActivity, hasInitialized])

  // Only consider scheduler truly disabled after 3 consecutive polls (6 seconds)
  // But on initial load, we set count to 10 immediately if disabled
  const isSchedulerDisabled = schedulerDisabledCount >= 3

  // Helper function to advance to next/previous item after delete/move
  const advanceToNextItem = () => {
    if (!selectedMedia || !recentDownloads.length) return

    const currentIndex = recentDownloads.findIndex((d: any) => d.id === selectedMedia.id)
    if (currentIndex === -1) {
      setSelectedMedia(null)
      return
    }

    // Try next item first
    if (currentIndex + 1 < recentDownloads.length) {
      setSelectedMedia(recentDownloads[currentIndex + 1])

    }
    // If no next item, try previous
    else if (currentIndex - 1 >= 0) {
      setSelectedMedia(recentDownloads[currentIndex - 1])

    }
    // If no items left, close lightbox
    else {
      setSelectedMedia(null)
    }
  }

  const addFaceReferenceMutation = useMutation({
    mutationFn: (file_path: string) => api.addFaceReference(file_path, undefined, true), // background = true
    onSuccess: (data) => {
      setSelectedMedia(null) // Close lightbox immediately
      setActioningFile(null)
      notificationManager.processing(data.message)
    },
    onError: (err: unknown) => {
      setActioningFile(null)
      notificationManager.faceReferenceError(err)
    },
  })

  const addReferenceMutation = useMutation({
    mutationFn: ({ filePath, personName }: { filePath: string; personName: string }) =>
      api.addFaceReference(filePath, personName, false),
    onSuccess: (data) => {
      setShowAddModal(false)
      setActioningFile(null)
      setSelectedMedia(null)
      notificationManager.faceReferenceAdded(data.person_name)
      api.triggerImmichScan().catch(() => {})
    },
    onError: (err: unknown) => {
      setActioningFile(null)
      notificationManager.faceReferenceError(err)
    },
  })

  const moveToReviewMutation = useMutation({
    mutationFn: (filePaths: string[]) => api.moveToReview(filePaths),
    onSuccess: (data) => {
      // If lightbox is open, advance to next item
      if (selectedMedia) {
        advanceToNextItem()
      }
      notificationManager.movedToReview(data.moved_count)
      api.triggerImmichScan().catch(() => {})
    },
    onError: (err: unknown) => {
      notificationManager.moveError('item', err)
    },
  })

  const batchDeleteMutation = useMutation({
    mutationFn: (filePaths: string[]) => api.batchDeleteMedia(filePaths),
    onSuccess: () => {
      // If lightbox is open, advance to next item
      if (selectedMedia) {
        advanceToNextItem()
      }
      api.triggerImmichScan().catch(() => {})
    },
    onError: (err: unknown) => {
      notificationManager.deleteError('media', err)
    },
  })

  const updateDateMutation = useMutation({
    mutationFn: ({ ids, newDate, updateFile }: { ids: number[]; newDate: string; updateFile: boolean }) =>
      api.updateMediaDate(ids, newDate, updateFile, 'post_date'),
    onSuccess: (data) => {
      refetchDownloads()
      setShowDateModal(false)
      setNewDate('')
      setEditingItemId(null)
      notificationManager.dateUpdated(`${data.success_count} file${data.success_count !== 1 ? 's' : ''}`)
    },
    onError: (err: unknown) => {
      notificationManager.dateUpdateError(err)
    },
  })

  const markWatchedMutation = useMutation({
    mutationFn: (appearanceId: number) => api.updateAppearanceStatus(appearanceId, 'watched'),
    onSuccess: () => {
      notificationManager.success('Success', 'Marked as watched')
      refetchAppearances()
    },
    onError: (err: unknown) => {
      notificationManager.apiError('Error', err)
    },
  })

  // Match Plex mutation
  const matchPlexMutation = useMutation({
    mutationFn: () => api.matchAppearancesToPlex(),
    onSuccess: () => {
      setMatchingPlex(true)
      // Poll for completion
      const pollInterval = setInterval(async () => {
        refetchAppearances()
        queryClient.invalidateQueries({ queryKey: ['plex-stats'] })
      }, 3000)
      setTimeout(() => {
        clearInterval(pollInterval)
        setMatchingPlex(false)
        refetchAppearances()
        queryClient.invalidateQueries({ queryKey: ['plex-stats'] })
      }, 120000)
    },
    onError: (error: any) => {
      setMatchingPlex(false)
      notificationManager.error('Error', error?.response?.data?.detail || error?.message, '❌')
    },
  })

  // Refs for values used inside polling interval (avoids unstable deps causing re-renders)
  const appearancesSyncRef = useRef(appearancesSyncProgress)
  appearancesSyncRef.current = appearancesSyncProgress
  const matchingPlexRef = useRef(matchingPlex)
  matchingPlexRef.current = matchingPlex
  const matchPlexMutationRef = useRef(matchPlexMutation)
  matchPlexMutationRef.current = matchPlexMutation

  // Poll for appearances sync status - always poll to detect when sync starts/stops
  useEffect(() => {
    const pollInterval = setInterval(async () => {
      try {
        const status = await api.getAppearanceSyncStatus()

        // Refresh data and trigger Plex sync when sync completes
        if (!status.is_running && appearancesSyncRef.current.is_running) {
          queryClient.invalidateQueries({ queryKey: ['upcoming-appearances'] })
          // Automatically run Plex sync after appearances sync completes
          if (!matchingPlexRef.current && !matchPlexMutationRef.current.isPending) {
            matchPlexMutationRef.current.mutate()
          }
        }

        setAppearancesSyncProgress(status)
      } catch (error) {
        console.error('Error polling sync status:', error)
      }
    }, appearancesSyncRef.current.is_running ? 2000 : 10000) // Poll faster when running

    // Initial check
    api.getAppearanceSyncStatus().then(setAppearancesSyncProgress).catch(console.error)

    return () => clearInterval(pollInterval)
  }, [queryClient])

  // Poll for Easynews sync status
  useEffect(() => {
    const pollInterval = setInterval(async () => {
      try {
        const statusData = await api.getEasynewsStatus()
        if (statusData.success) {
          setEasynewsStatus({
            ...statusData.status,
            enabled: statusData.enabled,
            has_credentials: statusData.has_credentials,
            last_check: statusData.last_check,
          })
        }
      } catch (error) {
        console.error('Error polling Easynews status:', error)
      }
    }, easynewsStatus.is_running ? 2000 : 30000) // Poll faster when running

    // Initial check
    api.getEasynewsStatus().then((data) => {
      if (data.success) {
        setEasynewsStatus({
          ...data.status,
          enabled: data.enabled,
          has_credentials: data.has_credentials,
          last_check: data.last_check,
        })
      }
    }).catch(console.error)

    return () => clearInterval(pollInterval)
  }, [easynewsStatus.is_running])

  // Update current time periodically for relative time updates
  useEffect(() => {
    const interval = setInterval(() => {
      setCurrentTime(new Date())
    }, 30000)

    return () => clearInterval(interval)
  }, [])

  // Use currentTime to force re-renders for relative time updates
  void currentTime

  // Listen for WebSocket updates
  useEffect(() => {
    const unsubscribe = wsClient.on('*', (data) => {
      if (data.type === 'download_completed') {
        refetchStats()
        refetchStatus()
        refetchActivity()
        refetchDownloads()
      }
    })

    return unsubscribe
  }, [refetchStats, refetchStatus, refetchActivity, refetchDownloads])

  // ===================
  // Recent Items Cards Helpers
  // ===================

  const handleDismissCard = (location: 'media' | 'review' | 'internet_discovery') => {
    // Store the newest item's ID as the dismiss marker.
    // IDs are monotonically increasing and reflect insertion order,
    // unlike timestamps which can interleave across batch downloads.
    const items = location === 'media' ? recentItems?.media?.items
      : location === 'review' ? recentItems?.review?.items
      : recentItems?.internet_discovery?.items
    const newestItem = items?.[0] as Record<string, any> | undefined
    const dismissId = newestItem?.id ?? null
    const newDismissed = {
      ...dismissedCards,
      [location]: dismissId
    }
    dismissCardsMutation.mutate(newDismissed)
  }

  const handleItemAction = (itemId: number | string) => {
    setActionedItems(prev => new Set([...prev, itemId]))
  }

  // Card should show if:
  // 1. Has items AND
  // 2. Either not dismissed OR has items with id > dismissed id
  const shouldShowCard = (
    _location: 'media' | 'review' | 'internet_discovery',
    items: Array<{ id: number | string }> | undefined,
    dismissedId: number | string | null
  ) => {
    if (!items || items.length === 0) return false
    if (dismissedId == null) return true

    // Items are ordered by id DESC, so first item has the highest id
    const newestItem = items[0]
    return Number(newestItem.id) > Number(dismissedId)
  }

  // Filter items by removing actioned ones and items with id <= dismissed id
  const getVisibleItems = <T extends { id: number | string }>(
    items: T[] | undefined,
    maxItems: number = 10,
    dismissedId: number | string | null = null
  ): T[] => {
    if (!items) return []
    return items
      .filter(item => !actionedItems.has(item.id))
      .filter(item => {
        if (dismissedId == null) return true
        return Number(item.id) > Number(dismissedId)
      })
      .slice(0, maxItems)
  }

  // Get all items for lightbox buffer
  const getAllItems = <T extends { id: number | string }>(items: T[] | undefined): T[] => {
    if (!items) return []
    return items.filter(item => !actionedItems.has(item.id))
  }

  // Handle Run Now button
  const handleRunNow = async (platform: string, account: string) => {
    try {
      setTriggering(true)
      await api.triggerDownload(platform, account)
      // Refetch to show the task is now running
      setTimeout(() => {
        refetchActivity()
      }, 1000)
    } catch (error) {
      console.error('Failed to trigger download:', error)
    } finally {
      setTriggering(false)
    }
  }

  // Handle Skip Run button
  const handleSkipRun = async (taskId: string) => {
    try {
      setSkipping(true)
      await api.skipNextRun(taskId)
      // Refetch scheduler status to show updated next run time
      setTimeout(() => {
        refetchActivity()
      }, 500)
    } catch (error) {
      console.error('Failed to skip run:', error)
    } finally {
      setSkipping(false)
    }
  }

  // Handle Stop Scheduler button
  const handleStopScheduler = async () => {
    try {
      setPausing(true)
      await api.stopSchedulerService()
      notificationManager.schedulerStopped()
      // Force scheduler disabled state immediately (skip debounce)
      setSchedulerDisabledCount(10)
      // Invalidate and refetch immediately
      queryClient.invalidateQueries({ queryKey: ['status'] })
      queryClient.invalidateQueries({ queryKey: ['current-activity'] })
      refetchActivity()
      refetchStatus()
      // Refetch again after systemctl has time to fully update
      setTimeout(() => {
        refetchActivity()
        refetchStatus()
      }, 2000)
    } catch (error: unknown) {
      console.error('Failed to stop scheduler:', error)
      notificationManager.schedulerError('Stop', error)
    } finally {
      setPausing(false)
    }
  }

  // Handle Stop button for scheduler service
  const handleStopActivity = async () => {
    try {
      setStopping(true)
      await api.stopSchedulerService()
      notificationManager.schedulerStopped()
      // Force scheduler disabled state immediately (skip debounce)
      setSchedulerDisabledCount(10)
      // Invalidate and refetch immediately, then again after service fully stops
      queryClient.invalidateQueries({ queryKey: ['status'] })
      queryClient.invalidateQueries({ queryKey: ['current-activity'] })
      refetchActivity()
      refetchStatus()
      // Refetch again after systemctl has time to fully update
      setTimeout(() => {
        refetchActivity()
        refetchStatus()
        refetchStats()
      }, 2000)
    } catch (error: unknown) {
      console.error('Failed to stop scheduler:', error)
      notificationManager.schedulerError('Stop', error)
    } finally {
      setStopping(false)
    }
  }

  // Handle Start Scheduler button
  const handleStartScheduler = async () => {
    try {
      setStartingScheduler(true)
      await api.startSchedulerService()
      notificationManager.schedulerStarted()
      // Reset scheduler disabled counter immediately (allow debounce to work fresh)
      setSchedulerDisabledCount(0)
      // Invalidate and refetch immediately
      queryClient.invalidateQueries({ queryKey: ['status'] })
      queryClient.invalidateQueries({ queryKey: ['current-activity'] })
      refetchActivity()
      refetchStatus()
      // Refetch again after systemctl has time to fully start
      setTimeout(() => {
        refetchActivity()
        refetchStatus()
      }, 2000)
    } catch (error: unknown) {
      console.error('Failed to start scheduler:', error)
      notificationManager.schedulerError('Start', error)
    } finally {
      setStartingScheduler(false)
    }
  }

  // Handle stop manual platform run
  const handleStopManualRun = async (platform: string) => {
    try {
      await api.stopPlatformDownload(platform)
      notificationManager.downloadStopped(platform)
      // Refetch to update UI
      refetchRunningPlatforms()
    } catch (error: unknown) {
      console.error('Failed to stop platform download:', error)
      notificationManager.schedulerError('Stop', error)
    }
  }


  // Handle single item move to review
  const handleSingleMoveToReview = (filePath: string) => {
    if (confirm('Move this item to review queue?')) {
      moveToReviewMutation.mutate([filePath])
    }
  }

  // Handle add reference with person name
  const handleAddReference = (media: any) => {
    setActioningFile(media.file_path)
    setShowAddModal(true)
  }

  // Handle delete
  const handleDelete = (media: any) => {
    if (confirm(`Delete "${media.filename}"?`)) {
      setActioningFile(media.file_path)
      batchDeleteMutation.mutate([media.file_path])
    }
  }

  // Confirm add reference
  const confirmAddReference = () => {
    if (!addPersonName.trim() || !actioningFile) return
    addReferenceMutation.mutate({ filePath: actioningFile, personName: addPersonName })
  }

  // Date editing handlers
  const handleSingleChangeDate = (media: any) => {
    setEditingItemId(media.id)
    // Pre-fill with current post_date if available
    if (media.post_date) {
      const date = new Date(media.post_date)
      const localDateTime = new Date(date.getTime() - date.getTimezoneOffset() * 60000)
        .toISOString()
        .slice(0, 16)
      setNewDate(localDateTime)
    } else {
      setNewDate('')
    }
    setShowDateModal(true)
  }

  const confirmDateChange = () => {
    if (!newDate || !editingItemId) return
    const isoDate = new Date(newDate).toISOString()
    updateDateMutation.mutate({ ids: [editingItemId], newDate: isoDate, updateFile: updateFileTimestamps })
  }

  // Group platforms by type for cleaner display
  // Note: Database now stores all Instagram methods as platform='instagram' (not fastdl/imginn/toolzu)
  const platformGroups: Record<string, { platforms: string[], icon: any, color: string }> = {
    'Instagram': {
      platforms: ['instagram', 'instagram_unified', 'fastdl', 'imginn', 'toolzu'],
      icon: Instagram,
      color: 'bg-gradient-to-br from-purple-500 to-pink-500'
    },
    'Snapchat': {
      platforms: ['snapchat'],
      icon: MessageCircle,
      color: 'bg-gradient-to-br from-yellow-400 to-yellow-500'
    },
    'TikTok': {
      platforms: ['tiktok'],
      icon: Video,
      color: 'bg-gradient-to-br from-black to-gray-800'
    },
    'YouTube': {
      platforms: ['youtube', 'youtube_monitor', 'youtube_channel_monitor'],
      icon: Youtube,
      color: 'bg-gradient-to-br from-red-500 to-red-600'
    },
    'Forums': {
      platforms: ['forum', 'forums', 'monitor'],
      icon: Globe,
      color: 'bg-gradient-to-br from-blue-500 to-indigo-600'
    },
    'Coppermine': {
      platforms: ['coppermine'],
      icon: ImageIcon,
      color: 'bg-gradient-to-br from-green-500 to-emerald-600'
    },
    'Appearances': {
      platforms: ['appearances', 'tmdb', 'tvdb', 'imdb', 'plex'],
      icon: Film,
      color: 'bg-gradient-to-br from-amber-500 to-orange-600'
    },
    'Twitter/X': {
      platforms: ['twitter'],
      icon: Twitter,
      color: 'bg-gradient-to-br from-sky-400 to-sky-600'
    },
    'Reddit': {
      platforms: ['reddit'],
      icon: Globe,
      color: 'bg-gradient-to-br from-orange-500 to-orange-600'
    },
    'Manual Import': {
      platforms: ['manual_import', 'manual'],
      icon: FolderInput,
      color: 'bg-gradient-to-br from-slate-500 to-slate-600'
    },
    'Other': {
      platforms: ['other'],
      icon: Download,
      color: 'bg-gradient-to-br from-gray-500 to-gray-600'
    }
  }

  // Aggregate downloads by platform group
  const groupedData = Object.entries(platformGroups).map(([groupName, groupInfo]) => {
    const total = groupInfo.platforms.reduce((sum, platform) => {
      return sum + (stats?.by_platform?.[platform] || 0)
    }, 0)

    return {
      name: groupName,
      count: total,
      icon: groupInfo.icon,
      color: groupInfo.color,
      platforms: groupInfo.platforms
        .map(p => ({ name: p, count: stats?.by_platform?.[p] || 0 }))
        .filter(p => p.count > 0)
    }
  }).filter(group => group.count > 0)
    .sort((a, b) => b.count - a.count) // Sort by count descending


  // Helper to get current index for lightbox
  const getCurrentLightboxIndex = () => {
    if (!selectedMedia || !recentDownloads.length) return -1
    return recentDownloads.findIndex((d: any) => d.id === selectedMedia.id)
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
        <div className="flex-1">
          <div className="flex items-center gap-3 mb-2">
            <h1 className="text-2xl sm:text-3xl font-bold flex items-center gap-2 sm:gap-3">
              <LayoutDashboard className="w-8 h-8 text-blue-500" />
              Dashboard
            </h1>
          </div>
          <p className="text-slate-600 dark:text-slate-400">
            Overview of your media downloader system
          </p>
        </div>
        {/* FlareSolverr Status */}
        <FlareSolverrStatus />
      </div>

      {/* Error Banner - shows when there are new errors since last visit */}
      <ErrorBanner />

      {/* Cookie Health Banner - shows when cookies/sessions have issues */}
      <CookieHealthBanner />

      {/* Stats Grid */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 md:gap-6">
        <StatCard
          title="Total Downloads"
          value={stats?.total_downloads.toLocaleString() || '0'}
          icon={Download}
          subtitle={stats?.review_queue_count ? `${stats.review_queue_count} in review` : "All time"}
          color="blue"
        />
        <StatCard
          title="Last 24 Hours"
          value={stats?.recent_24h || '0'}
          icon={Activity}
          subtitle="Recent activity"
          color="green"
        />
        <StatCard
          title="Total Size"
          value={stats?.total_size ? formatBytes(stats.total_size) : '0 B'}
          icon={Database}
          subtitle="Disk space used"
          color="purple"
        />
        <StatCard
          title="Duplicates Prevented"
          value={stats?.duplicates_prevented || '0'}
          icon={TrendingUp}
          subtitle="Hash + perceptual"
          color="orange"
        />
      </div>

      {/* Disk Space Cards */}
      {systemHealth?.system?.disks && systemHealth.system.disks.length > 0 && (
        <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-5 gap-3 md:gap-4">
          {systemHealth.system.disks.map((disk) => {
            const color = disk.percent > 85 ? 'red' : disk.percent > 70 ? 'orange' : 'cyan'
            const cardClass = color === 'red' ? 'stat-card-red shadow-red-glow' :
              color === 'orange' ? 'stat-card-orange shadow-orange-glow' : 'stat-card-cyan'
            const iconClass = color === 'red' ? 'bg-red-500/20 text-red-600 dark:text-red-400' :
              color === 'orange' ? 'bg-amber-500/20 text-amber-600 dark:text-amber-400' :
              'bg-cyan-500/20 text-cyan-600 dark:text-cyan-400'
            const label = disk.mountpoint === '/' ? 'System' : disk.mountpoint.replace('/media/', '').replace('/opt/', '')
            return (
              <div key={disk.mountpoint} className={`card-glass-hover rounded-xl p-3 md:p-4 border ${cardClass}`}>
                <div className="flex items-center justify-between">
                  <div className="flex-1 min-w-0">
                    <p className="text-xs font-medium text-muted-foreground truncate">{label}</p>
                    <p className="mt-1 text-lg md:text-xl font-bold text-foreground">{formatBytes(disk.free)} free</p>
                    <p className="text-xs text-muted-foreground">{formatBytes(disk.used)} / {formatBytes(disk.total)}</p>
                  </div>
                  <div className={`p-2 rounded-lg flex-shrink-0 ${iconClass}`}>
                    <HardDrive className="w-4 h-4" />
                  </div>
                </div>
              </div>
            )
          })}

        </div>
      )}

      {/* Cloud Backup Status Card — always below disk cards */}
      {cloudBackupStatus?.configured && (
        <Link to="/config?tab=cloud_backup" className="block">
          <div className={`card-glass-hover rounded-xl border overflow-hidden transition-all duration-300 ${
            cloudBackupStatus.syncing
              ? 'bg-gradient-to-r from-blue-500/10 to-cyan-500/10 border-blue-500/30 p-4 md:p-6 glow-border'
              : cloudBackupStatus.state === 'error'
              ? 'stat-card-red shadow-red-glow p-4 md:p-6'
              : 'stat-card-cyan p-4 md:p-6'
          }`}>
            {cloudBackupStatus.syncing ? (
              <div className="flex items-start md:items-center space-x-3 md:space-x-4">
                <div className="relative flex-shrink-0 mt-1 md:mt-0">
                  <Cloud className="w-7 h-7 md:w-8 md:h-8 text-blue-600 dark:text-blue-400 animate-pulse" />
                  <span className="absolute -top-1 -right-1 live-dot"></span>
                </div>
                <div className="flex-1 min-w-0">
                  <div className="flex items-center justify-between">
                    <h3 className="text-base md:text-lg font-semibold text-blue-900 dark:text-blue-100">
                      Cloud Backup
                    </h3>
                    {cloudBackupStatus.active_job?.transfer_stats && (
                      <span className="text-sm font-mono font-medium text-blue-600 dark:text-blue-400">
                        {cloudBackupStatus.active_job.transfer_stats.speed}
                      </span>
                    )}
                  </div>
                  <div className="flex flex-col sm:flex-row sm:items-center sm:flex-wrap gap-x-2 gap-y-0.5 mt-1">
                    <span className="text-sm text-blue-700 dark:text-blue-300">
                      {cloudBackupStatus.active_job?.current_dir
                        ? <>Syncing: <span className="font-medium">{cloudBackupStatus.active_job.current_dir}</span>
                            {cloudBackupStatus.active_job.phase === 'checking' && (
                              <span className="text-yellow-600 dark:text-yellow-400 ml-1">
                                (comparing{cloudBackupStatus.active_job.transfer_stats?.checks_done != null
                                  ? ` ${cloudBackupStatus.active_job.transfer_stats.checks_done.toLocaleString()}${cloudBackupStatus.active_job.transfer_stats.checks_total ? ` / ${cloudBackupStatus.active_job.transfer_stats.checks_total.toLocaleString()}` : ''} files`
                                  : '...'})
                              </span>
                            )}
                          </>
                        : 'Preparing...'}
                    </span>
                    {(cloudBackupStatus.active_job?.dirs_total ?? 0) > 0 && (
                      <>
                        <span className="hidden sm:inline text-blue-400 dark:text-blue-600">&bull;</span>
                        <span className="text-sm text-blue-600 dark:text-blue-400">
                          Dir {(cloudBackupStatus.active_job?.dirs_synced ?? 0) + 1}/{cloudBackupStatus.active_job?.dirs_total ?? 0}
                        </span>
                      </>
                    )}
                    {cloudBackupStatus.active_job?.transfer_stats?.files_done != null && (
                      <>
                        <span className="hidden sm:inline text-blue-400 dark:text-blue-600">&bull;</span>
                        <span className="text-sm text-blue-600 dark:text-blue-400">
                          {cloudBackupStatus.active_job.transfer_stats.files_done}/{cloudBackupStatus.active_job.transfer_stats.files_total} files
                        </span>
                      </>
                    )}
                    {cloudBackupStatus.active_job?.transfer_stats?.eta && (
                      <>
                        <span className="hidden sm:inline text-blue-400 dark:text-blue-600">&bull;</span>
                        <span className="text-sm text-blue-600 dark:text-blue-400">
                          ETA {cloudBackupStatus.active_job.transfer_stats.eta}
                        </span>
                      </>
                    )}
                  </div>

                  {/* Transfer progress bar — only when actually transferring */}
                  {cloudBackupStatus.active_job?.transfer_stats?.bytes_done && (
                    <div className="mt-2 w-full">
                      <div className="flex justify-between text-xs text-blue-700 dark:text-blue-300 mb-1">
                        <span>{cloudBackupStatus.active_job.transfer_stats.bytes_done} / {cloudBackupStatus.active_job.transfer_stats.bytes_total}</span>
                        <span>{cloudBackupStatus.active_job.transfer_stats.pct}%</span>
                      </div>
                      <div className="w-full bg-blue-200 dark:bg-blue-800 rounded-full h-1.5">
                        <div
                          className="bg-blue-600 dark:bg-blue-400 h-1.5 rounded-full transition-all duration-300 progress-animated"
                          style={{ width: `${Math.max(1, cloudBackupStatus.active_job.transfer_stats.pct)}%` }}
                        ></div>
                      </div>
                    </div>
                  )}
                  {/* Show indeterminate bar only during preparing phase (no stats yet) */}
                  {cloudBackupStatus.active_job && cloudBackupStatus.active_job.phase === 'preparing' && (
                    <div className="mt-2 w-full">
                      <div className="w-full bg-blue-200 dark:bg-blue-800 rounded-full h-1.5">
                        <div className="bg-blue-600 dark:bg-blue-400 h-1.5 rounded-full w-full animate-pulse"></div>
                      </div>
                    </div>
                  )}

                  {/* Current file being transferred */}
                  {cloudBackupStatus.active_job?.current_file && (
                    <p className="mt-1.5 text-xs text-blue-600/70 dark:text-blue-400/70 truncate font-mono">
                      {cloudBackupStatus.active_job.current_file}
                    </p>
                  )}
                </div>
              </div>
            ) : (
              <div className="flex items-center justify-between">
                <div className="flex items-center space-x-3 md:space-x-4 flex-1 min-w-0">
                  <div className={`p-2.5 md:p-3 rounded-xl flex-shrink-0 ${
                    cloudBackupStatus.state === 'error' ? 'bg-red-500/20 text-red-600 dark:text-red-400' :
                    'bg-cyan-500/20 text-cyan-600 dark:text-cyan-400'
                  }`}>
                    <Cloud className="w-5 h-5 md:w-6 md:h-6" />
                  </div>
                  <div className="flex-1 min-w-0">
                    <p className="text-sm font-medium text-muted-foreground">Cloud Backup</p>
                    <p className="mt-1 text-xl md:text-2xl font-bold text-foreground">
                      {cloudBackupStatus.storage_used != null
                        ? `${(cloudBackupStatus.storage_used / 1e12).toFixed(1)} TB synced`
                        : 'Ready'}
                    </p>
                  </div>
                </div>
                <div className="text-right flex-shrink-0">
                  <p className="text-sm font-medium text-foreground">
                    {cloudBackupStatus.state === 'error' ? 'Error' : 'Idle'}
                  </p>
                  <p className="text-xs text-muted-foreground mt-0.5">
                    {cloudBackupStatus.last_sync
                      ? `Last sync ${formatRelativeTime(cloudBackupStatus.last_sync)}`
                      : 'No syncs yet'}
                  </p>
                </div>
              </div>
            )}
          </div>
        </Link>
      )}

      {/* Upcoming Appearances Card */}
      {upcomingAppearances && upcomingAppearances.length > 0 && (
        <UpcomingAppearancesCard
          appearances={upcomingAppearances}
          onMarkWatched={(id) => markWatchedMutation.mutate(id)}
        />
      )}

      {/* Recent Items Cards */}
      <div className="space-y-4">
        {/* New in Downloads */}
        {shouldShowCard('media', recentItems?.media?.items, dismissedCards.media) && (
          <RecentItemsCard
            title="New in Downloads"
            icon={FolderDown}
            items={getVisibleItems(recentItems?.media?.items as MediaItem[], 15, dismissedCards.media)}
            allItems={getAllItems(recentItems?.media?.items as MediaItem[])}
            totalCount={getVisibleItems(recentItems?.media?.items as MediaItem[], 999, dismissedCards.media).length}
            location="media"
            viewAllLink="/downloads"
            onDismiss={() => handleDismissCard('media')}
            onItemAction={handleItemAction}
            gradientFrom="from-blue-500/10"
            gradientTo="to-indigo-500/10"
            borderColor="border-blue-500/30"
            iconColor="text-blue-500"
          />
        )}

        {/* New in Review */}
        {shouldShowCard('review', recentItems?.review?.items, dismissedCards.review) && (
          <RecentItemsCard
            title="New in Review"
            icon={ClipboardList}
            items={getVisibleItems(recentItems?.review?.items as ReviewItem[], 15, dismissedCards.review)}
            allItems={getAllItems(recentItems?.review?.items as ReviewItem[])}
            totalCount={getVisibleItems(recentItems?.review?.items as ReviewItem[], 999, dismissedCards.review).length}
            location="review"
            viewAllLink="/review"
            onDismiss={() => handleDismissCard('review')}
            onItemAction={handleItemAction}
            gradientFrom="from-orange-500/10"
            gradientTo="to-amber-500/10"
            borderColor="border-orange-500/30"
            iconColor="text-orange-500"
          />
        )}

        {/* New in Internet Discovery */}
        {shouldShowCard('internet_discovery', recentItems?.internet_discovery?.items, dismissedCards.internet_discovery) && (
          <RecentItemsCard
            title="New in Internet Discovery"
            icon={Globe}
            items={getVisibleItems(recentItems?.internet_discovery?.items as DiscoveryItem[], 11, dismissedCards.internet_discovery)}
            allItems={getAllItems(recentItems?.internet_discovery?.items as DiscoveryItem[])}
            totalCount={getVisibleItems(recentItems?.internet_discovery?.items as DiscoveryItem[], 999, dismissedCards.internet_discovery).length}
            location="internet_discovery"
            viewAllLink="/celebrities"
            onDismiss={() => handleDismissCard('internet_discovery')}
            onItemAction={handleItemAction}
            gradientFrom="from-red-500/10"
            gradientTo="to-pink-500/10"
            borderColor="border-red-500/30"
            iconColor="text-red-500"
          />
        )}
      </div>

      {/* Current Activity or Next Scheduled Run */}
      {currentActivity?.active ? (
        <div className="card-glass rounded-xl bg-gradient-to-r from-blue-500/10 to-indigo-500/10 border border-blue-500/30 p-4 md:p-6 glow-border">
          <div className="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
            <div className="flex items-start md:items-center space-x-3 md:space-x-4 flex-1">
              <div className="relative flex-shrink-0 mt-1 md:mt-0">
                <Activity className="w-7 h-7 md:w-8 md:h-8 text-blue-600 dark:text-blue-400 animate-pulse" />
                <span className="absolute -top-1 -right-1 live-dot"></span>
              </div>
              <div className="flex-1 min-w-0">
                <h3 className="text-base md:text-lg font-semibold text-blue-900 dark:text-blue-100">
                  Currently Scraping
                </h3>
                <div className="flex flex-col sm:flex-row sm:items-center sm:space-x-2 mt-1 gap-1 sm:gap-0">
                  <span className="text-sm text-blue-700 dark:text-blue-300">
                    Platform: <span className="font-medium">{getTaskInfo(currentActivity.platform + (currentActivity.account ? ':' + currentActivity.account : '')).platform}</span>
                  </span>
                  {currentActivity.account && !['paid_content', 'youtube_monitor', 'youtube_channel_monitor', 'youtube', 'easynews_monitor', 'easynews', 'reddit_monitor', 'appearances'].includes((currentActivity.platform || '').toLowerCase().replace(/\s+/g, '_')) && (
                    <>
                      <span className="hidden sm:inline text-blue-400 dark:text-blue-600">•</span>
                      <span className="text-sm text-blue-700 dark:text-blue-300">
                        Account: <span className="font-medium">{currentActivity.account}</span>
                      </span>
                    </>
                  )}
                  <span className="hidden sm:inline text-blue-400 dark:text-blue-600">•</span>
                  <span className="text-sm text-blue-600 dark:text-blue-400 font-medium">
                    {currentActivity.start_time ? formatRelativeTime(currentActivity.start_time) : 'Just started'}
                  </span>
                </div>
                {currentActivity.detailed_status && (
                  <div className="mt-2 px-3 py-2 bg-blue-100 dark:bg-blue-900/30 rounded-lg border border-blue-200 dark:border-blue-800 w-[95%] overflow-hidden">
                    <div className="text-sm text-blue-800 dark:text-blue-200 font-medium">
                      <div className="flex items-center">
                        <span className="inline-block w-2 h-2 bg-blue-500 rounded-full mr-2 flex-shrink-0 animate-pulse"></span>
                        <span>{currentActivity.detailed_status.split(':')[0]}</span>
                      </div>
                      {currentActivity.detailed_status.includes(':') && (
                        <div className="mt-1 pl-4 text-xs truncate text-blue-700 dark:text-blue-300">
                          {currentActivity.detailed_status.split(':').slice(1).join(':').trim()}
                        </div>
                      )}
                    </div>
                    {currentActivity.progress && (
                      <div className="mt-2">
                        <div className="flex justify-between text-xs text-blue-700 dark:text-blue-300 mb-1">
                          <span>Progress</span>
                          <span>{currentActivity.progress.current || 0}/{currentActivity.progress.total || 0}</span>
                        </div>
                        <div className="w-full bg-blue-200 dark:bg-blue-800 rounded-full h-1.5">
                          <div
                            className="bg-blue-600 dark:bg-blue-400 h-1.5 rounded-full transition-all duration-300 progress-animated"
                            style={{ width: `${currentActivity.progress.total > 0 ? (currentActivity.progress.current / currentActivity.progress.total * 100) : 0}%` }}
                          ></div>
                        </div>
                      </div>
                    )}
                    {currentActivity.account_progress && currentActivity.account_progress.total > 0 && (
                      <div className="mt-2">
                        <div className="flex justify-between text-xs text-blue-700 dark:text-blue-300 mb-1">
                          <span>Account {currentActivity.account_progress.current} of {currentActivity.account_progress.total}</span>
                          <span>{currentActivity.account_progress.total - currentActivity.account_progress.current} remaining</span>
                        </div>
                        <div className="w-full bg-blue-200 dark:bg-blue-800 rounded-full h-2">
                          <div
                            className="bg-indigo-500 dark:bg-indigo-400 h-2 rounded-full transition-all duration-500 progress-animated"
                            style={{ width: `${(currentActivity.account_progress.current / currentActivity.account_progress.total * 100)}%` }}
                          ></div>
                        </div>
                      </div>
                    )}
                  </div>
                )}
              </div>
            </div>
            <div className="flex items-center justify-end md:justify-start">
              <button
                onClick={handleStopActivity}
                disabled={stopping}
                className="flex items-center space-x-2 px-4 py-2.5 bg-red-600 hover:bg-red-700 disabled:bg-red-400 text-white rounded-lg transition-colors text-sm font-medium min-h-[44px]"
              >
                <StopCircle className="w-5 h-5" />
                <span>{stopping ? 'Stopping...' : 'Stop'}</span>
              </button>
            </div>
          </div>
        </div>
      ) : (() => {
          // Check if scheduler is disabled - use debounced state to prevent flicker
          if (isSchedulerDisabled) {
            return (
              <div className="card-glass rounded-xl bg-gradient-to-r from-slate-500/10 to-gray-500/10 border border-slate-500/30 p-4 md:p-6 min-h-[140px] flex items-center">
                <div className="flex items-center space-x-3 md:space-x-4 w-full">
                  <div className="relative flex-shrink-0">
                    <StopCircle className="w-7 h-7 md:w-8 md:h-8 text-slate-500 dark:text-slate-400" />
                  </div>
                  <div className="flex-1">
                    <h3 className="text-base md:text-lg font-semibold text-slate-900 dark:text-slate-100">
                      Scheduler Disabled
                    </h3>
                    <p className="text-sm text-slate-600 dark:text-slate-400 mt-1">
                      The scheduler service is currently stopped
                    </p>
                  </div>
                  <button
                    onClick={handleStartScheduler}
                    disabled={startingScheduler}
                    className="flex items-center space-x-2 px-4 py-2.5 bg-green-600 hover:bg-green-700 disabled:bg-slate-400 text-white rounded-lg transition-colors min-h-[44px] flex-shrink-0"
                  >
                    <Play className="w-5 h-5" />
                    <span className="hidden sm:inline">{startingScheduler ? 'Starting...' : 'Start Scheduler'}</span>
                    <span className="sm:hidden">{startingScheduler ? 'Start' : 'Start'}</span>
                  </button>
                </div>
              </div>
            );
          }

          // Show next scheduled run if available
          if (!schedulerStatus || !schedulerStatus.tasks || schedulerStatus.tasks.length === 0) return null;

          // Calculate the next task to run (only future times)
          const now = new Date();
          const nextTask = schedulerStatus.tasks
            .filter((t: any) => {
              if (t.status !== 'active' || !t.next_run) return false;
              const [platformKey] = t.task_id.split(':');
              if (hiddenModules.includes(platformKey)) return false;
              const nextRunTime = new Date(t.next_run);
              return nextRunTime > now; // Only include future times
            })
            .sort((a: any, b: any) => new Date(a.next_run).getTime() - new Date(b.next_run).getTime())[0];

          if (!nextTask || !nextTask.next_run) return null;

          const taskInfo = getTaskInfo(nextTask.task_id);
          const [platformRaw, accountRaw] = nextTask.task_id.split(':');

          return (
            <div className="card-glass rounded-xl bg-gradient-to-r from-slate-500/5 to-gray-500/5 border border-border p-4 md:p-6 min-h-[140px] flex items-center">
              <div className="flex flex-col md:flex-row md:items-center md:justify-between w-full gap-4">
                <div className="flex items-start md:items-center space-x-3 md:space-x-4 flex-1">
                  <div className="relative flex-shrink-0 mt-1 md:mt-0">
                    <Activity className="w-7 h-7 md:w-8 md:h-8 text-muted-foreground" />
                  </div>
                  <div className="flex-1 min-w-0">
                    <h3 className="text-base md:text-lg font-semibold text-foreground">
                      Next Scheduled Run
                    </h3>
                    <div className="flex flex-col sm:flex-row sm:items-center sm:space-x-2 mt-1 gap-1 sm:gap-0">
                      <span className="text-sm text-slate-700 dark:text-slate-300">
                        Platform: <span className="font-medium">{taskInfo.platform}</span>
                      </span>
                      {taskInfo.account && (
                        <>
                          <span className="hidden sm:inline text-slate-400 dark:text-slate-600">•</span>
                          <span className="text-sm text-slate-700 dark:text-slate-300">
                            Account: <span className="font-medium">{taskInfo.account}</span>
                          </span>
                        </>
                      )}
                      <span className="hidden sm:inline text-slate-400 dark:text-slate-600">•</span>
                      <span className="text-sm text-slate-600 dark:text-slate-400 font-medium">
                        {formatRelativeTime(nextTask.next_run)}
                      </span>
                    </div>
                  </div>
                </div>
                <div className="flex flex-wrap items-center gap-2">
                  <button
                    onClick={() => handleRunNow(platformRaw, accountRaw)}
                    disabled={triggering || skipping || pausing}
                    className="flex items-center space-x-2 px-4 py-2.5 bg-blue-600 hover:bg-blue-700 disabled:bg-blue-400 text-white rounded-lg transition-colors text-sm font-medium min-h-[44px]"
                  >
                    <Play className="w-5 h-5" />
                    <span className="hidden sm:inline">{triggering ? 'Starting...' : 'Run Now'}</span>
                    <span className="sm:hidden">{triggering ? 'Start' : 'Run'}</span>
                  </button>
                  <button
                    onClick={() => handleSkipRun(nextTask.task_id)}
                    disabled={triggering || skipping || pausing}
                    className="flex items-center space-x-2 px-4 py-2.5 bg-amber-600 hover:bg-amber-700 disabled:bg-amber-400 text-white rounded-lg transition-colors text-sm font-medium min-h-[44px]"
                  >
                    <SkipForward className="w-5 h-5" />
                    <span className="hidden sm:inline">{skipping ? 'Skipping...' : 'Skip Run'}</span>
                    <span className="sm:hidden">{skipping ? 'Skip' : 'Skip'}</span>
                  </button>
                  <button
                    onClick={handleStopScheduler}
                    disabled={triggering || skipping || pausing}
                    className="flex items-center space-x-2 px-4 py-2.5 bg-red-600 hover:bg-red-700 disabled:bg-red-400 text-white rounded-lg transition-colors text-sm font-medium min-h-[44px]"
                    title="Stop the scheduler service"
                  >
                    <StopCircle className="w-5 h-5" />
                    <span className="hidden sm:inline">{pausing ? 'Stopping...' : 'Stop Scheduler'}</span>
                    <span className="sm:hidden">{pausing ? 'Stop' : 'Stop'}</span>
                  </button>
                  <Link
                    to="/scheduler"
                    className="flex items-center space-x-2 px-4 py-2.5 bg-slate-200 hover:bg-slate-300 dark:bg-slate-700 dark:hover:bg-slate-600 text-slate-700 dark:text-slate-200 rounded-lg transition-colors text-sm font-medium min-h-[44px]"
                  >
                    <Calendar className="w-5 h-5" />
                    <span className="hidden sm:inline">View Schedule</span>
                    <span className="sm:hidden">Schedule</span>
                  </Link>
                </div>
              </div>
            </div>
          );
        })()}

      {/* Video Queue Processing Card */}
      {processorStatus?.is_running && (
        <Link
          to="/queue"
          className={`block card-glass rounded-xl p-4 transition-all hover:scale-[1.01] ${
            processorStatus.is_paused
              ? 'bg-gradient-to-r from-yellow-500/10 to-amber-500/10 border border-yellow-500/30'
              : 'bg-gradient-to-r from-blue-500/10 to-indigo-500/10 border border-blue-500/30'
          }`}
        >
          <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 Video 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, 50)}{processorStatus.current_title.length > 50 ? '...' : ''}
                  </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}
              </span>
              {processorStatus.failed_count > 0 && (
                <span className="text-red-600">
                  <X className="w-4 h-4 inline mr-1" />
                  {processorStatus.failed_count}
                </span>
              )}
              <span className="text-slate-500">
                {processorStatus.pending_count} left
              </span>
            </div>
          </div>
        </Link>
      )}

      {/* Manual Platform Runs Card - EXACT COPY of scheduled card with green colors */}
      {runningPlatforms && runningPlatforms.platforms && runningPlatforms.platforms.length > 0 && (() => {
        const runningPlatform = runningPlatforms.platforms[0]
        const matchingSession = activeSessions?.sessions?.find(
          (s: any) => s.session_id === runningPlatform.session_id
        )

        if (!matchingSession) return null

        return (
          <div className="card-glass rounded-xl bg-gradient-to-r from-green-500/10 to-emerald-500/10 border border-green-500/30 p-4 md:p-6 glow-border">
            <div className="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
              <div className="flex items-start md:items-center space-x-3 md:space-x-4 flex-1">
                <div className="relative flex-shrink-0 mt-1 md:mt-0">
                  <Download className="w-7 h-7 md:w-8 md:h-8 text-green-600 dark:text-green-400 animate-pulse" />
                  <span className="absolute -top-1 -right-1 live-dot"></span>
                </div>
                <div className="flex-1 min-w-0">
                  <h3 className="text-base md:text-lg font-semibold text-green-900 dark:text-green-100">
                    Manual Platform Run
                  </h3>
                  <div className="flex flex-col sm:flex-row sm:items-center sm:space-x-2 mt-1 gap-1 sm:gap-0">
                    <span className="text-sm text-green-700 dark:text-green-300">
                      Platform: <span className="font-medium">{getTaskInfo(matchingSession.platform + (matchingSession.account ? ':' + matchingSession.account : '')).platform}</span>
                    </span>
                    {matchingSession.account && !['paid_content', 'youtube_monitor', 'youtube_channel_monitor', 'easynews_monitor', 'reddit_monitor', 'appearances'].includes(matchingSession.platform || '') && (
                      <>
                        <span className="hidden sm:inline text-green-400 dark:text-green-600">•</span>
                        <span className="text-sm text-green-700 dark:text-green-300">
                          Account: <span className="font-medium">{matchingSession.account}</span>
                        </span>
                      </>
                    )}
                    <span className="hidden sm:inline text-green-400 dark:text-green-600">•</span>
                    <span className="text-sm text-green-600 dark:text-green-400 font-medium">
                      {matchingSession.start_time ? formatRelativeTime(matchingSession.start_time) : 'Just started'}
                    </span>
                  </div>
                  {matchingSession.detailed_status && (
                    <div className="mt-2 px-3 py-2 bg-green-100 dark:bg-green-900/30 rounded-lg border border-green-200 dark:border-green-800 w-[95%] overflow-hidden">
                      <div className="text-sm text-green-800 dark:text-green-200 font-medium">
                        <div className="flex items-center">
                          <span className="inline-block w-2 h-2 bg-green-500 rounded-full mr-2 flex-shrink-0 animate-pulse"></span>
                          <span>{matchingSession.detailed_status.split(':')[0]}</span>
                        </div>
                        {matchingSession.detailed_status.includes(':') && (
                          <div className="mt-1 pl-4 text-xs truncate text-green-700 dark:text-green-300">
                            {matchingSession.detailed_status.split(':').slice(1).join(':').trim()}
                          </div>
                        )}
                      </div>
                      {matchingSession.progress && (
                        <div className="mt-2">
                          <div className="flex justify-between text-xs text-green-700 dark:text-green-300 mb-1">
                            <span>Progress</span>
                            <span>{matchingSession.progress.current || 0}/{matchingSession.progress.total || 0}</span>
                          </div>
                          <div className="w-full bg-green-200 dark:bg-green-800 rounded-full h-1.5">
                            <div
                              className="bg-green-600 dark:bg-green-400 h-1.5 rounded-full transition-all duration-300 progress-animated"
                              style={{ width: `${matchingSession.progress.total > 0 ? (matchingSession.progress.current / matchingSession.progress.total * 100) : 0}%` }}
                            ></div>
                          </div>
                        </div>
                      )}
                    </div>
                  )}
                </div>
              </div>
              <div className="flex items-center justify-end md:justify-start">
                <button
                  onClick={() => handleStopManualRun(runningPlatform.platform)}
                  className="flex items-center space-x-2 px-4 py-2.5 bg-red-600 hover:bg-red-700 text-white rounded-lg transition-colors text-sm font-medium min-h-[44px]"
                >
                  <StopCircle className="w-5 h-5" />
                  <span>Stop</span>
                </button>
              </div>
            </div>
          </div>
        )
      })()}

      {/* YouTube Monitor Background Task 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 md:p-6 glow-border">
          <div className="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
            <div className="flex items-start md:items-center space-x-3 md:space-x-4 flex-1">
              <div className="relative flex-shrink-0 mt-1 md:mt-0">
                <Video className="w-7 h-7 md:w-8 md:h-8 text-red-600 dark:text-red-400" />
                <span className="absolute -top-1 -right-1 live-dot-red"></span>
              </div>
              <div className="flex-1 min-w-0">
                <h3 className="text-base md:text-lg font-semibold text-red-900 dark:text-red-100">
                  YouTube Channel Monitor
                </h3>
                <div className="flex flex-col sm:flex-row sm:items-center sm:space-x-2 mt-1 gap-1 sm:gap-0">
                  <span className="text-sm text-red-700 dark:text-red-300">
                    Checking: <span className="font-medium">{youtubeMonitorTask.extra_data?.total_channels || 0} channels</span>
                  </span>
                  <span className="hidden sm:inline text-red-400 dark:text-red-600">•</span>
                  <span className="text-sm text-red-600 dark:text-red-400 font-medium">
                    {youtubeMonitorTask.start_time ? formatRelativeTime(youtubeMonitorTask.start_time) : 'Just started'}
                  </span>
                </div>
                {youtubeMonitorTask.detailed_status && (
                  <div className="mt-2 px-3 py-2 bg-red-100 dark:bg-red-900/30 rounded-lg border border-red-200 dark:border-red-800 w-[95%] overflow-hidden">
                    <div className="text-sm text-red-800 dark:text-red-200 font-medium">
                      <div className={`flex items-center ${youtubeMonitorTask.detailed_status.startsWith('Found ') ? 'text-green-700 dark:text-green-300' : ''}`}>
                        <span className={`inline-block w-2 h-2 ${youtubeMonitorTask.detailed_status.startsWith('Found ') ? 'bg-green-500' : 'bg-red-500'} rounded-full mr-2 flex-shrink-0 animate-pulse`}></span>
                        <span className="truncate">{youtubeMonitorTask.detailed_status}</span>
                      </div>
                    </div>
                    {youtubeMonitorTask.progress && (
                      <div className="mt-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">
                          <div
                            className="bg-red-600 dark:bg-red-400 h-1.5 rounded-full transition-all duration-300"
                            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="mt-2 flex items-center space-x-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>
                )}
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Celebrity Search Background Task Card */}
      {celebritySearchTask?.active && (
        <div className="card-glass rounded-xl bg-gradient-to-r from-purple-500/10 to-indigo-500/10 border border-purple-500/30 p-4 md:p-6">
          <div className="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
            <div className="flex items-start md:items-center space-x-3 md:space-x-4 flex-1">
              <div className="relative flex-shrink-0 mt-1 md:mt-0">
                <Search className="w-7 h-7 md:w-8 md:h-8 text-purple-600 dark:text-purple-400" />
                <div className="absolute -top-1 -right-1 w-3 h-3 bg-purple-500 rounded-full animate-pulse"></div>
              </div>
              <div className="min-w-0 flex-1">
                <h3 className="text-base md:text-lg font-semibold text-purple-900 dark:text-purple-100">
                  {celebritySearchTask.display_name || 'Celebrity Search'}
                </h3>
                <div className="flex flex-col sm:flex-row sm:items-center sm:space-x-2 mt-1 gap-1 sm:gap-0">
                  <span className="text-sm text-purple-700 dark:text-purple-300">
                    {celebritySearchTask.extra_data?.total_presets ? (
                      <>Scanning: <span className="font-medium">{celebritySearchTask.extra_data.total_presets} presets</span></>
                    ) : (
                      <span className="font-medium">{celebritySearchTask.status || 'Running'}</span>
                    )}
                  </span>
                  <span className="hidden sm:inline text-purple-400 dark:text-purple-600">•</span>
                  <span className="text-sm text-purple-600 dark:text-purple-400 font-medium">
                    {celebritySearchTask.start_time ? formatRelativeTime(celebritySearchTask.start_time) : 'Just started'}
                  </span>
                </div>
                {celebritySearchTask.detailed_status && (
                  <div className="mt-2 px-3 py-2 bg-purple-100 dark:bg-purple-900/30 rounded-lg border border-purple-200 dark:border-purple-800 w-[95%] overflow-hidden">
                    <div className="text-sm text-purple-800 dark:text-purple-200 font-medium">
                      <div className="flex items-center">
                        <span className="inline-block w-2 h-2 bg-purple-500 rounded-full mr-2 flex-shrink-0 animate-pulse"></span>
                        <span className="truncate">{celebritySearchTask.detailed_status}</span>
                      </div>
                    </div>
                    {celebritySearchTask.progress && (
                      <div className="mt-2">
                        <div className="flex justify-between text-xs text-purple-700 dark:text-purple-300 mb-1">
                          <span>Progress</span>
                          <span>{celebritySearchTask.progress.current || 0}/{celebritySearchTask.progress.total || 0}</span>
                        </div>
                        <div className="w-full bg-purple-200 dark:bg-purple-800 rounded-full h-1.5">
                          <div
                            className="bg-purple-600 dark:bg-purple-400 h-1.5 rounded-full transition-all duration-300"
                            style={{ width: `${celebritySearchTask.progress.total > 0 ? (celebritySearchTask.progress.current / celebritySearchTask.progress.total * 100) : 0}%` }}
                          ></div>
                        </div>
                      </div>
                    )}
                    {(celebritySearchTask.extra_data?.videos_found ?? 0) > 0 && (
                      <div className="mt-2 flex items-center space-x-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>{celebritySearchTask.extra_data?.videos_found} new video{celebritySearchTask.extra_data?.videos_found !== 1 ? 's' : ''} found</span>
                      </div>
                    )}
                  </div>
                )}
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Paid Content Active Tasks */}
      {paidContentActiveSyncs && paidContentActiveSyncs.length > 0 && (
        <div className="bg-card rounded-xl border border-primary/30 p-4 shadow-glow">
          <div className="flex items-center space-x-2 mb-3">
            <Loader2 className="w-4 h-4 text-primary animate-spin" />
            <h2 className="font-semibold text-foreground">
              Paid Content — Active Tasks ({paidContentActiveSyncs.length})
            </h2>
          </div>
          <div className="space-y-3">
            {paidContentActiveSyncs.map((task) => (
              <PaidContentActiveTaskCard key={task.creator_id} task={task} />
            ))}
          </div>
        </div>
      )}

      {/* Celebrity Appearances Sync Status Card */}
      {appearancesSyncProgress.is_running && (
        <div className="card-glass rounded-xl bg-gradient-to-r from-cyan-500/10 to-blue-500/10 border border-cyan-500/30 p-4 md:p-6 glow-border">
          <div className="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
            <div className="flex items-start md:items-center space-x-3 md:space-x-4 flex-1">
              <div className="relative flex-shrink-0 mt-1 md:mt-0">
                <Calendar className="w-7 h-7 md:w-8 md:h-8 text-cyan-600 dark:text-cyan-400 animate-pulse" />
                <span className="absolute -top-1 -right-1 live-dot"></span>
              </div>
              <div className="flex-1 min-w-0">
                <h3 className="text-base md:text-lg font-semibold text-cyan-900 dark:text-cyan-100">
                  Celebrity Appearances
                </h3>
                <div className="flex flex-col sm:flex-row sm:items-center sm:space-x-2 mt-1 gap-1 sm:gap-0">
                  <span className="text-sm text-cyan-700 dark:text-cyan-300">
                    Celebrity: <span className="font-medium">{appearancesSyncProgress.current_celebrity || 'Starting...'}</span>
                  </span>
                  <span className="hidden sm:inline text-cyan-400 dark:text-cyan-600">•</span>
                  <span className="text-sm text-cyan-600 dark:text-cyan-400 font-medium">
                    {appearancesSyncProgress.celebrities_processed || 0} of {appearancesSyncProgress.total_celebrities || 0}
                  </span>
                </div>

                {/* Detailed status box */}
                {appearancesSyncProgress.current_celebrity && (
                  <div className="mt-2 px-3 py-2 bg-cyan-100 dark:bg-cyan-900/30 rounded-lg border border-cyan-200 dark:border-cyan-800 w-[95%] overflow-hidden">
                    <div className="text-sm text-cyan-800 dark:text-cyan-200 font-medium">
                      <div className="flex items-center">
                        <span className="inline-block w-2 h-2 bg-cyan-500 rounded-full mr-2 flex-shrink-0 animate-pulse"></span>
                        <span>
                          {appearancesSyncProgress.phase === 'fetching_movies' && 'Fetching movies'}
                          {appearancesSyncProgress.phase === 'fetching_tv' && 'Fetching TV shows'}
                          {appearancesSyncProgress.phase === 'fetching_podcasts' && 'Fetching podcasts (Podchaser)'}
                          {appearancesSyncProgress.phase === 'fetching_podcasts_taddy' && 'Fetching podcasts (Taddy)'}
                          {appearancesSyncProgress.phase === 'fetching' && 'Fetching data'}
                          {appearancesSyncProgress.phase === 'saving' && 'Saving to database'}
                          {!appearancesSyncProgress.phase && 'Processing'}
                        </span>
                      </div>
                      {/* Show current item being processed */}
                      {appearancesSyncProgress.phase === 'fetching_tv' && appearancesSyncProgress.current_show && (
                        <div className="mt-1 pl-4 text-xs text-cyan-700 dark:text-cyan-300 truncate">
                          {appearancesSyncProgress.current_show}
                        </div>
                      )}
                      {(appearancesSyncProgress.phase === 'fetching_podcasts' || appearancesSyncProgress.phase === 'fetching_podcasts_taddy') && appearancesSyncProgress.current_podcast && (
                        <div className="mt-1 pl-4 text-xs text-cyan-700 dark:text-cyan-300 truncate">
                          {appearancesSyncProgress.current_podcast}
                        </div>
                      )}
                    </div>

                    {/* Phase-specific progress bar */}
                    {appearancesSyncProgress.phase === 'fetching_tv' && (appearancesSyncProgress.total_shows || 0) > 0 && (
                      <div className="mt-2">
                        <div className="flex justify-between text-xs text-cyan-700 dark:text-cyan-300 mb-1">
                          <span>TV Shows</span>
                          <span>{appearancesSyncProgress.shows_processed || 0}/{appearancesSyncProgress.total_shows || 0}</span>
                        </div>
                        <div className="w-full bg-cyan-200 dark:bg-cyan-800 rounded-full h-1.5">
                          <div
                            className="bg-cyan-600 dark:bg-cyan-400 h-1.5 rounded-full transition-all duration-300 progress-animated"
                            style={{ width: `${((appearancesSyncProgress.shows_processed || 0) / (appearancesSyncProgress.total_shows || 1)) * 100}%` }}
                          ></div>
                        </div>
                      </div>
                    )}
                    {(appearancesSyncProgress.phase === 'fetching_podcasts' || appearancesSyncProgress.phase === 'fetching_podcasts_taddy') && (appearancesSyncProgress.total_podcasts || 0) > 0 && (
                      <div className="mt-2">
                        <div className="flex justify-between text-xs text-green-700 dark:text-green-300 mb-1">
                          <span>Podcasts</span>
                          <span>{appearancesSyncProgress.podcasts_processed || 0}/{appearancesSyncProgress.total_podcasts || 0}</span>
                        </div>
                        <div className="w-full bg-green-200 dark:bg-green-800 rounded-full h-1.5">
                          <div
                            className="bg-green-600 dark:bg-green-400 h-1.5 rounded-full transition-all duration-300 progress-animated"
                            style={{ width: `${((appearancesSyncProgress.podcasts_processed || 0) / (appearancesSyncProgress.total_podcasts || 1)) * 100}%` }}
                          ></div>
                        </div>
                      </div>
                    )}

                    {/* New appearances found */}
                    {appearancesSyncProgress.new_appearances > 0 && (
                      <div className="mt-2 flex items-center gap-1.5 text-xs text-green-700 dark:text-green-300 font-medium">
                        <Check className="w-3.5 h-3.5" />
                        <span>Found {appearancesSyncProgress.new_appearances} new appearance{appearancesSyncProgress.new_appearances !== 1 ? 's' : ''}</span>
                      </div>
                    )}
                  </div>
                )}
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Easynews Sync Status 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 md:p-6 glow-border">
          <div className="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
            <div className="flex items-start md:items-center space-x-3 md:space-x-4 flex-1">
              <div className="relative flex-shrink-0 mt-1 md:mt-0">
                <Download className="w-7 h-7 md:w-8 md:h-8 text-amber-600 dark:text-amber-400" />
                <span className="absolute -top-1 -right-1 w-2.5 h-2.5 bg-amber-500 rounded-full animate-pulse"></span>
              </div>
              <div className="flex-1 min-w-0">
                <h3 className="text-base md:text-lg font-semibold text-amber-900 dark:text-amber-100">
                  Easynews
                </h3>
                <div className="flex flex-col sm:flex-row sm:items-center sm:space-x-2 mt-1 gap-1 sm:gap-0">
                  <span className="text-sm text-amber-700 dark:text-amber-300">
                    Checking: <span className="font-medium">{easynewsStatus.current_search || 'Starting...'}</span>
                  </span>
                  <span className="hidden sm:inline text-amber-400 dark:text-amber-600">•</span>
                  <span className="text-sm text-amber-600 dark:text-amber-400">
                    {easynewsStatus.searches_processed || 0}/{easynewsStatus.total_searches || 0} searches
                  </span>
                </div>
                {easynewsStatus.total_searches > 0 && (
                  <div className="mt-2 px-3 py-2 bg-amber-100 dark:bg-amber-900/30 rounded-lg border border-amber-200 dark:border-amber-800 w-[95%] overflow-hidden">
                    <div className="flex justify-between text-xs text-amber-700 dark:text-amber-300 mb-1">
                      <span>Progress</span>
                      <span>{easynewsStatus.searches_processed || 0}/{easynewsStatus.total_searches || 0}</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>
                    {easynewsStatus.results_found > 0 && (
                      <div className="mt-2 flex items-center space-x-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>{easynewsStatus.results_found} result{easynewsStatus.results_found !== 1 ? 's' : ''} found</span>
                      </div>
                    )}
                  </div>
                )}
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Charts Row */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6 items-stretch">
        {/* Platform Distribution */}
        <div className="card-glass-hover rounded-xl p-4 sm:p-6 h-full flex flex-col">
          <div className="flex items-center justify-between mb-4">
            <h3 className="text-lg font-semibold text-slate-900 dark:text-slate-100">
              Downloads by Platform
            </h3>
            <span className="text-xs text-slate-500 dark:text-slate-400 bg-slate-100 dark:bg-slate-800 px-2 py-1 rounded">
              {groupedData.length} platforms
            </span>
          </div>
          <div className="space-y-2 sm:space-y-3 flex-1 flex flex-col justify-center">
            {groupedData.length > 0 ? (
              groupedData.map((group) => {
                const Icon = group.icon
                const percentage = stats?.total_downloads ? ((group.count / stats.total_downloads) * 100).toFixed(1) : '0'

                return (
                  <div key={group.name} className="relative py-1">
                    <div className="flex items-center justify-between mb-1.5">
                      <div className="flex items-center space-x-2 sm:space-x-3 min-w-0 flex-1">
                        <div className={`w-7 h-7 sm:w-8 sm:h-8 rounded-md ${group.color} flex items-center justify-center shadow flex-shrink-0`}>
                          <Icon className="w-3.5 h-3.5 sm:w-4 sm:h-4 text-white" />
                        </div>
                        <div className="min-w-0 flex-1">
                          <p className="text-sm font-medium text-slate-900 dark:text-slate-100 truncate">
                            {group.name}
                          </p>
                        </div>
                      </div>
                      <div className="text-right flex-shrink-0 ml-2">
                        <p className="text-base sm:text-lg font-bold text-slate-900 dark:text-slate-100">
                          {group.count.toLocaleString()}
                        </p>
                        <p className="text-xs text-slate-500 dark:text-slate-400">
                          {percentage}%
                        </p>
                      </div>
                    </div>
                    {/* Progress bar */}
                    <div className="h-1.5 sm:h-2 bg-slate-100 dark:bg-slate-800 rounded-full overflow-hidden">
                      <div
                        className={`h-full ${group.color} transition-all duration-500`}
                        style={{ width: `${percentage}%` }}
                      />
                    </div>
                  </div>
                )
              })
            ) : (
              <div className="flex flex-col items-center justify-center flex-1 text-slate-500 dark:text-slate-400">
                <Download className="w-12 h-12 mb-3 opacity-50" />
                <p className="text-sm">No downloads yet</p>
              </div>
            )}
          </div>
        </div>

        {/* Recent Activity */}
        <div className="card-glass-hover rounded-xl p-6 h-full flex flex-col">
          <h3 className="text-lg font-semibold text-slate-900 dark:text-slate-100 mb-4">
            Recent Downloads
          </h3>
          <div className="space-y-3 flex-1 overflow-y-auto custom-scrollbar">
            {recentDownloads && recentDownloads.length > 0 ? (
              recentDownloads.map((download) => {
                const isVideo = isVideoFile(download.filename)
                const mediaType = isVideo ? 'video' : 'image'

                return (
                <div
                  key={download.id}
                  className="flex items-center justify-between p-3 bg-secondary/50 rounded-xl transition-all duration-200 hover:bg-secondary group"
                >
                  <div className="flex items-center space-x-3 min-w-0 flex-1">
                    {download.file_path ? (
                      <img
                        src={api.getMediaThumbnailUrl(download.file_path, mediaType, download.file_token)}
                        alt={download.filename || ''}
                        className="w-12 h-12 object-cover rounded-lg flex-shrink-0 cursor-pointer ring-1 ring-border transition-all duration-200 hover:ring-2 hover:ring-primary hover:scale-105"
                        loading="lazy"
                        onClick={() => setSelectedMedia({ ...download, media_type: mediaType })}
                      />
                    ) : (
                      <div className="flex-shrink-0 w-12 h-12 bg-card rounded-lg flex items-center justify-center ring-1 ring-border">
                        <PlatformIcon platform={download.platform} />
                      </div>
                    )}
                    <div className="min-w-0 flex-1">
                      <p className="text-sm font-medium text-foreground truncate" title={download.filename || 'Unknown'}>
                        {download.filename ? (
                          download.filename.length > 45
                            ? download.filename.substring(0, 42) + '...' + download.filename.slice(-8)
                            : download.filename.replace('_old_post_', '')
                        ) : 'Unknown'}
                      </p>
                      <p className="text-xs text-muted-foreground">
                        {formatPlatformName(download.platform)} • {download.source}
                      </p>
                    </div>
                  </div>
                  <div className="flex-shrink-0 text-xs text-muted-foreground">
                    {formatRelativeTime(download.download_date)}
                  </div>
                </div>
                )
              })
            ) : (
              <div className="text-center text-slate-500 dark:text-slate-400 py-8">
                No recent downloads
              </div>
            )}
          </div>
        </div>
      </div>

      {/* Analytics Widgets */}
      {dashboardStats && (
        <>
          {/* Download Trends */}
          {dashboardStats.downloads_per_day && dashboardStats.downloads_per_day.length > 0 && (
            <div className="card-glass-hover rounded-xl p-6">
              <h3 className="text-lg font-semibold text-slate-900 dark:text-slate-100 mb-4">
                Download Trends (Last 30 Days)
              </h3>
              <div className="space-y-2">
                {dashboardStats.downloads_per_day.slice(-14).map((day, index) => {
                  const maxDownloads = Math.max(...dashboardStats.downloads_per_day.map(d => d.count))
                  const width = maxDownloads > 0 ? (day.count / maxDownloads) * 100 : 0
                  return (
                    <div key={index} className="flex items-center">
                      <div className="w-20 text-xs text-slate-600 dark:text-slate-400">
                        {new Date(day.date).toLocaleDateString('en-US', { month: 'short', day: 'numeric' })}
                      </div>
                      <div className="flex-1 ml-4">
                        <div className="flex items-center">
                          <div className="w-full bg-slate-200 dark:bg-slate-700 rounded-full h-6 relative">
                            <div
                              className="bg-blue-600 dark:bg-blue-500 h-6 rounded-full flex items-center justify-end pr-2"
                              style={{ width: `${width}%`, minWidth: day.count > 0 ? '40px' : '0' }}
                            >
                              {day.count > 0 && (
                                <span className="text-xs font-medium text-white">
                                  {day.count}
                                </span>
                              )}
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                  )
                })}
              </div>
            </div>
          )}

          {/* Storage & Content Grid */}
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
            {/* Storage by Platform */}
            {dashboardStats.storage_by_platform && dashboardStats.storage_by_platform.length > 0 && (
              <div className="card-glass-hover rounded-xl p-6">
                <h3 className="text-lg font-semibold text-slate-900 dark:text-slate-100 mb-4">
                  Storage by Platform
                </h3>
                <div className="space-y-2 sm:space-y-3">
                  {dashboardStats.storage_by_platform
                    .sort((a, b) => b.size_bytes - a.size_bytes)
                    .map((item) => {
                      const totalStorage = dashboardStats.storage_by_platform.reduce((sum, p) => sum + p.size_bytes, 0)
                      const percentage = totalStorage > 0 ? (item.size_bytes / totalStorage) * 100 : 0

                      // Get platform icon and color
                      const getPlatformStyle = (platform: string) => {
                        const styles: Record<string, { icon: any, color: string }> = {
                          instagram: { icon: Instagram, color: 'bg-gradient-to-br from-purple-500 to-pink-500' },
                          snapchat: { icon: MessageCircle, color: 'bg-gradient-to-br from-yellow-400 to-yellow-500' },
                          tiktok: { icon: Video, color: 'bg-gradient-to-br from-black to-gray-800' },
                          youtube: { icon: Youtube, color: 'bg-gradient-to-br from-red-500 to-red-600' },
                          forum: { icon: Globe, color: 'bg-gradient-to-br from-blue-500 to-indigo-600' },
                          forums: { icon: Globe, color: 'bg-gradient-to-br from-blue-500 to-indigo-600' },
                          coppermine: { icon: ImageIcon, color: 'bg-gradient-to-br from-green-500 to-emerald-600' },
                          appearances: { icon: Film, color: 'bg-gradient-to-br from-amber-500 to-orange-600' },
                          tmdb: { icon: Film, color: 'bg-gradient-to-br from-amber-500 to-orange-600' },
                          twitter: { icon: Twitter, color: 'bg-gradient-to-br from-sky-400 to-sky-600' },
                          reddit: { icon: Globe, color: 'bg-gradient-to-br from-orange-500 to-orange-600' },
                          manual_import: { icon: FolderInput, color: 'bg-gradient-to-br from-slate-500 to-slate-600' },
                        }
                        return styles[platform.toLowerCase()] || { icon: Download, color: 'bg-gradient-to-br from-gray-500 to-gray-600' }
                      }

                      const { icon: Icon, color } = getPlatformStyle(item.platform)

                      return (
                        <div key={item.platform} className="py-1">
                          <div className="flex items-center justify-between mb-1.5">
                            <div className="flex items-center space-x-2 sm:space-x-3">
                              <div className={`w-7 h-7 sm:w-8 sm:h-8 rounded-md ${color} flex items-center justify-center shadow flex-shrink-0`}>
                                <Icon className="w-3.5 h-3.5 sm:w-4 sm:h-4 text-white" />
                              </div>
                              <span className="text-sm font-medium text-slate-700 dark:text-slate-300">
                                {formatPlatformName(item.platform)}
                              </span>
                            </div>
                            <span className="text-sm text-slate-600 dark:text-slate-400">
                              {formatBytes(item.size_bytes)} ({percentage.toFixed(1)}%)
                            </span>
                          </div>
                          <div className="w-full bg-slate-200 dark:bg-slate-700 rounded-full h-1.5 sm:h-2">
                            <div
                              className={`${color} h-full rounded-full`}
                              style={{ width: `${percentage}%` }}
                            ></div>
                          </div>
                        </div>
                      )
                    })}
                </div>
              </div>
            )}

            {/* Content Types */}
            {dashboardStats.content_types && Object.keys(dashboardStats.content_types).length > 0 && (
              <div className="card-glass-hover rounded-xl p-6">
                <h3 className="text-lg font-semibold text-slate-900 dark:text-slate-100 mb-4">
                  Content Types
                </h3>
                <div className="space-y-2 sm:space-y-3">
                  {Object.entries(dashboardStats.content_types)
                    .sort(([, a], [, b]) => b - a)
                    .map(([type, count]) => {
                      const total = Object.values(dashboardStats.content_types).reduce((a, b) => a + b, 0)
                      const percentage = total > 0 ? (count / total) * 100 : 0

                      // Get content type icon and color
                      const getContentTypeStyle = (contentType: string) => {
                        const t = contentType.toLowerCase()
                        const styles: Record<string, { icon: any, color: string, label: string }> = {
                          // Instagram content types
                          post: { icon: Instagram, color: 'bg-gradient-to-br from-purple-500 to-pink-500', label: 'Posts' },
                          posts: { icon: Instagram, color: 'bg-gradient-to-br from-purple-500 to-pink-500', label: 'Posts' },
                          stories: { icon: Instagram, color: 'bg-gradient-to-br from-orange-500 to-pink-500', label: 'Stories' },
                          story: { icon: Instagram, color: 'bg-gradient-to-br from-orange-500 to-pink-500', label: 'Stories' },
                          reels: { icon: Video, color: 'bg-gradient-to-br from-purple-600 to-pink-600', label: 'Reels' },
                          reel: { icon: Video, color: 'bg-gradient-to-br from-purple-600 to-pink-600', label: 'Reels' },
                          tagged: { icon: Instagram, color: 'bg-gradient-to-br from-blue-500 to-purple-500', label: 'Tagged' },
                          // Snapchat content types
                          spotlight: { icon: MessageCircle, color: 'bg-gradient-to-br from-yellow-400 to-yellow-500', label: 'Spotlight' },
                          // Generic content types
                          image: { icon: Image, color: 'bg-gradient-to-br from-blue-500 to-blue-600', label: 'Images' },
                          images: { icon: Image, color: 'bg-gradient-to-br from-blue-500 to-blue-600', label: 'Images' },
                          photo: { icon: Image, color: 'bg-gradient-to-br from-blue-400 to-blue-500', label: 'Photos' },
                          photos: { icon: Image, color: 'bg-gradient-to-br from-blue-400 to-blue-500', label: 'Photos' },
                          video: { icon: Video, color: 'bg-gradient-to-br from-green-500 to-green-600', label: 'Videos' },
                          videos: { icon: Video, color: 'bg-gradient-to-br from-green-500 to-green-600', label: 'Videos' },
                        }

                        if (styles[t]) return styles[t]
                        // Fallback - capitalize first letter
                        return { icon: Download, color: 'bg-gradient-to-br from-gray-500 to-gray-600', label: contentType.charAt(0).toUpperCase() + contentType.slice(1) }
                      }

                      const { icon: Icon, color, label } = getContentTypeStyle(type)

                      return (
                        <div key={type} className="py-1">
                          <div className="flex items-center justify-between mb-1.5">
                            <div className="flex items-center space-x-2 sm:space-x-3">
                              <div className={`w-7 h-7 sm:w-8 sm:h-8 rounded-md ${color} flex items-center justify-center shadow flex-shrink-0`}>
                                <Icon className="w-3.5 h-3.5 sm:w-4 sm:h-4 text-white" />
                              </div>
                              <span className="text-sm font-medium text-slate-700 dark:text-slate-300">
                                {label}
                              </span>
                            </div>
                            <span className="text-sm text-slate-600 dark:text-slate-400">
                              {count.toLocaleString()} ({percentage.toFixed(1)}%)
                            </span>
                          </div>
                          <div className="w-full bg-slate-200 dark:bg-slate-700 rounded-full h-1.5 sm:h-2">
                            <div
                              className={`${color} h-full rounded-full`}
                              style={{ width: `${percentage}%` }}
                            ></div>
                          </div>
                        </div>
                      )
                    })}
                </div>
              </div>
            )}
          </div>

          {/* Top Sources */}
          {dashboardStats.top_sources && dashboardStats.top_sources.length > 0 && (
            <div className="card-glass-hover rounded-xl p-6">
              <h3 className="text-lg font-semibold text-slate-900 dark:text-slate-100 mb-4">
                Top Sources
              </h3>
              <div className="space-y-2 sm:space-y-3">
                {dashboardStats.top_sources.slice(0, 10).map((source, index) => {
                  const maxCount = dashboardStats.top_sources[0]?.count || 1
                  const percentage = (source.count / maxCount) * 100

                  // Get platform icon and color
                  const getPlatformStyle = (platform: string) => {
                    const p = platform.toLowerCase()
                    const styles: Record<string, { icon: any, color: string }> = {
                      instagram: { icon: Instagram, color: 'bg-gradient-to-br from-purple-500 to-pink-500' },
                      snapchat: { icon: MessageCircle, color: 'bg-gradient-to-br from-yellow-400 to-yellow-500' },
                      tiktok: { icon: Video, color: 'bg-gradient-to-br from-black to-gray-800' },
                      youtube: { icon: Youtube, color: 'bg-gradient-to-br from-red-500 to-red-600' },
                      forum: { icon: Globe, color: 'bg-gradient-to-br from-blue-500 to-indigo-600' },
                      forums: { icon: Globe, color: 'bg-gradient-to-br from-blue-500 to-indigo-600' },
                      coppermine: { icon: ImageIcon, color: 'bg-gradient-to-br from-green-500 to-emerald-600' },
                      twitter: { icon: Twitter, color: 'bg-gradient-to-br from-sky-400 to-sky-600' },
                      reddit: { icon: Globe, color: 'bg-gradient-to-br from-orange-500 to-orange-600' },
                      dailymotion: { icon: Video, color: 'bg-gradient-to-br from-blue-400 to-blue-600' },
                      bilibili: { icon: Video, color: 'bg-gradient-to-br from-pink-400 to-cyan-400' },
                    }
                    return styles[p] || { icon: Download, color: 'bg-gradient-to-br from-gray-500 to-gray-600' }
                  }

                  const { icon: Icon, color } = getPlatformStyle(source.platform)

                  return (
                    <div key={index} className="py-1">
                      <div className="flex items-center justify-between mb-1.5">
                        <div className="flex items-center space-x-2 sm:space-x-3 min-w-0 flex-1">
                          <div className={`w-7 h-7 sm:w-8 sm:h-8 rounded-md ${color} flex items-center justify-center shadow flex-shrink-0`}>
                            <Icon className="w-3.5 h-3.5 sm:w-4 sm:h-4 text-white" />
                          </div>
                          <span className="text-sm font-medium text-slate-900 dark:text-slate-100 truncate">
                            {source.source}
                          </span>
                        </div>
                        <span className="text-sm text-slate-600 dark:text-slate-400 ml-2 flex-shrink-0">
                          {source.count.toLocaleString()}
                        </span>
                      </div>
                      <div className="w-full bg-slate-200 dark:bg-slate-700 rounded-full h-1.5 sm:h-2">
                        <div
                          className={`${color} h-full rounded-full`}
                          style={{ width: `${percentage}%` }}
                        ></div>
                      </div>
                    </div>
                  )
                })}
              </div>
            </div>
          )}
        </>
      )}

      {/* System Status */}
      <div className="card-glass-hover rounded-xl p-6">
        <h3 className="text-lg font-semibold text-foreground mb-4">
          System Status
        </h3>
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          <div className="flex items-center justify-between p-4 bg-secondary/50 rounded-xl transition-all duration-200 hover:bg-secondary">
            <span className="text-sm text-slate-600 dark:text-slate-400">Scheduler</span>
            <span
              className={`px-3 py-1 text-xs font-medium rounded-full ${
                status?.scheduler_running
                  ? 'bg-emerald-100 text-emerald-700 dark:bg-emerald-500/20 dark:text-emerald-400'
                  : 'bg-slate-200 text-slate-700 dark:bg-slate-700 dark:text-slate-300'
              }`}
            >
              {status?.scheduler_running ? 'Running' : 'Stopped'}
            </span>
          </div>
          <div className="flex items-center justify-between p-4 bg-secondary/50 rounded-xl transition-all duration-200 hover:bg-secondary">
            <span className="text-sm text-muted-foreground">Active Connections</span>
            <span className="text-sm font-medium text-foreground">
              {status?.active_websockets || 0}
            </span>
          </div>
          <div className="flex items-center justify-between p-4 bg-secondary/50 rounded-xl transition-all duration-200 hover:bg-secondary">
            <span className="text-sm text-muted-foreground">Last Update</span>
            <span className="text-sm font-medium text-foreground">
              {status?.timestamp ? formatRelativeTime(status.timestamp) : 'Never'}
            </span>
          </div>
        </div>
      </div>

      {/* Lightbox */}
      {selectedMedia && getCurrentLightboxIndex() >= 0 && recentDownloads.length > 0 && (
        <EnhancedLightbox
          items={recentDownloads}
          currentIndex={getCurrentLightboxIndex()}
          onClose={() => { setSelectedMedia(null) }}
          onNavigate={(index) => { setSelectedMedia(recentDownloads[index]) }}
          onDelete={handleDelete}
          onEditDate={handleSingleChangeDate}
          getPreviewUrl={(item) => api.getMediaPreviewUrl(item.file_path, item.file_token)}
          getThumbnailUrl={(item) => api.getMediaThumbnailUrl(item.file_path, isVideoFile(item.filename) ? 'video' : 'image', item.file_token)}
          isVideo={(item) => isVideoFile(item.filename)}
          renderActions={(item) => (
            <>
              <button
                onClick={() => handleSingleMoveToReview(item.file_path)}
                disabled={moveToReviewMutation.isPending || actioningFile === item.file_path}
                className="px-6 py-3 bg-orange-600 text-white rounded-lg hover:bg-orange-700 disabled:opacity-50 flex items-center space-x-2 transition-colors"
              >
                <Eye className="w-5 h-5" />
                <span>{moveToReviewMutation.isPending ? 'Moving...' : 'Move to Review'}</span>
              </button>
              <button
                onClick={() => handleAddReference(item)}
                disabled={actioningFile === item.file_path}
                className="px-3 py-1.5 md:px-6 md:py-3 bg-blue-600 text-white text-sm md:text-base rounded-lg hover:bg-blue-700 disabled:opacity-50 flex items-center space-x-1.5 md:space-x-2 transition-colors"
              >
                <UserPlus className="w-4 h-4 md:w-5 md:h-5" />
                <span>Add Reference</span>
              </button>
              <button
                onClick={() => {
                  setActioningFile(item.file_path)
                  addFaceReferenceMutation.mutate(item.file_path)
                }}
                disabled={addFaceReferenceMutation.isPending}
                className="px-3 py-1.5 md:px-6 md:py-3 bg-purple-600 text-white text-sm md:text-base rounded-lg hover:bg-purple-700 disabled:opacity-50 flex items-center space-x-1.5 md:space-x-2 transition-colors"
              >
                <UserPlus className="w-4 h-4 md:w-5 md:h-5" />
                <span>{addFaceReferenceMutation.isPending ? 'Adding...' : 'Quick Add Face'}</span>
              </button>
              <button
                onClick={() => handleDelete(item)}
                disabled={actioningFile === item.file_path}
                className="px-3 py-1.5 md:px-6 md:py-3 bg-red-600 text-white text-sm md:text-base rounded-lg hover:bg-red-700 disabled:opacity-50 flex items-center space-x-1.5 md:space-x-2 transition-colors"
              >
                <Trash2 className="w-4 h-4 md:w-5 md:h-5" />
                <span>Delete</span>
              </button>
            </>
          )}
        />
      )}

      {/* Add Reference Modal */}
      {showAddModal && (
        <div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4">
          <div className="bg-white dark:bg-slate-800 rounded-lg p-6 max-w-md w-full">
            <h3 className="text-lg font-semibold text-slate-900 dark:text-slate-100 mb-4">
              Add as Face Reference
            </h3>
            <p className="text-sm text-slate-600 dark:text-slate-400 mb-4">
              This will add the face in this image as a reference for future matching.
            </p>
            <div>
              <label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-2">
                Person Name
              </label>
              <input
                type="text"
                value={addPersonName}
                onChange={(e) => setAddPersonName(e.target.value)}
                placeholder="Enter person name"
                className="w-full px-3 py-2 border border-slate-300 dark:border-slate-600 rounded-lg bg-white dark:bg-slate-900 text-slate-900 dark:text-slate-100"
                autoFocus
                onKeyDown={(e) => {
                  if (e.key === 'Enter' && addPersonName.trim()) {
                    confirmAddReference()
                  }
                }}
              />
            </div>
            <div className="flex justify-end space-x-2 mt-4">
              <button
                onClick={() => {
                  setShowAddModal(false)
                  setActioningFile(null)
                }}
                className="px-4 py-2.5 text-slate-700 dark:text-slate-300 hover:bg-slate-100 dark:hover:bg-slate-700 rounded-lg transition-colors min-h-[44px]"
              >
                Cancel
              </button>
              <button
                onClick={confirmAddReference}
                disabled={!addPersonName.trim() || addReferenceMutation.isPending}
                className="px-4 py-2.5 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50 transition-colors min-h-[44px]"
              >
                {addReferenceMutation.isPending ? 'Adding...' : 'Add Reference'}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Date Edit Modal */}
      {showDateModal && (
        <div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4">
          <div className="bg-white dark:bg-slate-800 rounded-lg p-6 max-w-md w-full">
            <h3 className="text-lg font-semibold text-slate-900 dark:text-slate-100 mb-4 flex items-center space-x-2">
              <CalendarClock className="w-5 h-5 text-amber-500" />
              <span>Edit Post Date</span>
            </h3>
            <p className="text-sm text-slate-600 dark:text-slate-400 mb-4">
              Change the post date for this file. This will update the database and optionally update file timestamps.
            </p>
            <div className="space-y-4">
              <div>
                <label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-2">
                  New Date and Time
                </label>
                <input
                  type="datetime-local"
                  value={newDate}
                  onChange={(e) => setNewDate(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-900 text-slate-900 dark:text-slate-100"
                  autoFocus
                />
              </div>
              <div className="flex items-center space-x-2">
                <input
                  type="checkbox"
                  id="updateFileTimestampsDashboard"
                  checked={updateFileTimestamps}
                  onChange={(e) => setUpdateFileTimestamps(e.target.checked)}
                  className="w-4 h-4 text-amber-600 border-slate-300 rounded focus:ring-amber-500"
                />
                <label htmlFor="updateFileTimestampsDashboard" className="text-sm text-slate-700 dark:text-slate-300">
                  Update file timestamps (EXIF/metadata and filesystem)
                </label>
              </div>
            </div>
            <div className="flex justify-end space-x-2 mt-6">
              <button
                onClick={() => {
                  setShowDateModal(false)
                  setNewDate('')
                  setEditingItemId(null)
                }}
                className="px-4 py-2.5 text-slate-700 dark:text-slate-300 hover:bg-slate-100 dark:hover:bg-slate-700 rounded-lg transition-colors min-h-[44px]"
              >
                Cancel
              </button>
              <button
                onClick={confirmDateChange}
                disabled={!newDate || updateDateMutation.isPending}
                className="px-4 py-2.5 bg-amber-600 text-white rounded-lg hover:bg-amber-700 disabled:opacity-50 disabled:cursor-not-allowed flex items-center space-x-2 transition-colors min-h-[44px]"
              >
                {updateDateMutation.isPending ? (
                  <>
                    <span className="animate-spin">⏳</span>
                    <span>Updating...</span>
                  </>
                ) : (
                  <span>Apply</span>
                )}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
