import { BrowserRouter, Routes, Route, Link, useLocation, Navigate, useNavigate } from 'react-router-dom'
import { useEffect, useState, useRef, lazy, Suspense, useMemo } from 'react'
import { LayoutDashboard, FolderDown, Settings, ScrollText, Menu, Moon, Sun, CalendarClock, GalleryHorizontalEnd, HeartPulse, BarChart3, LogOut, User, ChevronDown, FileText, BellRing, ClipboardList, Trash2, ScanFace, Gauge, Clapperboard, FolderInput, Compass, Bot, Star, ListVideo, Wrench, Layers, Video, Gem, Users, Plus, Bell, ListOrdered, Lock, MessageCircle, Clock, Newspaper } from 'lucide-react'
import { useEnabledFeatures } from './hooks/useEnabledFeatures'

// Lazy load pages for better initial load performance
const Dashboard = lazy(() => import('./pages/Dashboard'))
const Downloads = lazy(() => import('./pages/Downloads'))
const Gallery = lazy(() => import('./pages/Gallery'))
const Review = lazy(() => import('./pages/Review'))
const Platforms = lazy(() => import('./pages/Platforms'))
const Scheduler = lazy(() => import('./pages/Scheduler'))
const Configuration = lazy(() => import('./pages/Configuration'))
const Logs = lazy(() => import('./pages/Logs'))
const Health = lazy(() => import('./pages/Health'))
const Analytics = lazy(() => import('./pages/Analytics'))
const Login = lazy(() => import('./pages/Login'))
const TwoFactorAuth = lazy(() => import('./pages/TwoFactorAuth'))
const Changelog = lazy(() => import('./pages/Changelog'))
const Notifications = lazy(() => import('./pages/Notifications'))
const RecycleBin = lazy(() => import('./pages/RecycleBin'))
const FaceRecognitionDashboard = lazy(() => import('./pages/FaceRecognitionDashboard'))
const Monitoring = lazy(() => import('./pages/Monitoring'))
const ScrapingMonitor = lazy(() => import('./pages/ScrapingMonitor'))
const VideoDownloader = lazy(() => import('./pages/VideoDownloader'))
const ManualImport = lazy(() => import('./pages/ManualImport'))
const Discovery = lazy(() => import('./pages/Discovery'))
const Scrapers = lazy(() => import('./pages/Scrapers'))
const InternetDiscovery = lazy(() => import('./pages/InternetDiscovery'))
const DownloadQueue = lazy(() => import('./pages/DownloadQueue'))
const ChannelMonitors = lazy(() => import('./pages/ChannelMonitors'))
const Appearances = lazy(() => import('./pages/Appearances'))
const Press = lazy(() => import('./pages/Press'))

// Paid Content pages
const PaidContentDashboard = lazy(() => import('./pages/paid-content/Dashboard'))
const PaidContentFeed = lazy(() => import('./pages/paid-content/Feed'))
const PaidContentCreators = lazy(() => import('./pages/paid-content/Creators'))
const PaidContentAddContent = lazy(() => import('./pages/paid-content/AddContent'))
const PaidContentQueue = lazy(() => import('./pages/paid-content/Queue'))
const PaidContentNotifications = lazy(() => import('./pages/paid-content/Notifications'))
const PaidContentSettings = lazy(() => import('./pages/paid-content/Settings'))
const PaidContentMessages = lazy(() => import('./pages/paid-content/Messages'))
const PaidContentAnalytics = lazy(() => import('./pages/paid-content/Analytics'))
const PaidContentWatchLater = lazy(() => import('./pages/paid-content/WatchLater'))
const PaidContentBulkDelete = lazy(() => import('./pages/paid-content/BulkDelete'))
const PaidContentGallery = lazy(() => import('./pages/paid-content/Gallery'))

// Private Gallery pages
const PrivateGalleryUnlock = lazy(() => import('./pages/private-gallery/Unlock'))
const PrivateGallery = lazy(() => import('./pages/private-gallery/Gallery'))
const PrivateGalleryConfig = lazy(() => import('./pages/private-gallery/Config'))

import { wsClient, api } from './lib/api'
import { notificationManager } from './lib/notificationManager'
import NotificationToast, { ToastNotification } from './components/NotificationToast'
import ErrorBoundary from './components/ErrorBoundary'
import { BreadcrumbProvider } from './contexts/BreadcrumbContext'
import Breadcrumb from './components/Breadcrumb'
import { PrivateGalleryProvider, RequirePrivateGalleryAuth } from './components/private-gallery/PrivateGalleryProvider'

// Route tracker - saves current route to localStorage for PWA persistence
function RouteTracker() {
  const location = useLocation()

  useEffect(() => {
    // Don't save login/2fa routes
    if (location.pathname !== '/login' && location.pathname !== '/2fa') {
      try {
        localStorage.setItem('lastRoute', location.pathname)
      } catch (e) {
        // localStorage not available
      }
    }
  }, [location.pathname])

  return null
}

// Protected Route Component
function ProtectedRoute({ children }: { children: React.ReactNode }) {
  // Handle Duo callback before auth check — the redirect lands on "/" which is
  // protected, so we must store the token synchronously before isAuthenticated()
  // runs, otherwise ProtectedRoute redirects to /login and loses the params.
  const params = new URLSearchParams(window.location.search)
  const duoAuth = params.get('duo_auth')
  if (duoAuth === 'success') {
    const token = params.get('token')
    const sessionId = params.get('sessionId')
    const username = params.get('username')
    if (token && sessionId && username) {
      const user = { username, role: 'admin', email: `${username}@localhost` }
      api.setAuthToken(token, user, sessionId)
      window.history.replaceState({}, '', '/')
    }
  }

  const isAuthenticated = api.isAuthenticated()

  if (!isAuthenticated) {
    return <Navigate to="/login" replace />
  }

  return <>{children}</>
}

function Navigation({ darkMode, setDarkMode }: { darkMode: boolean; setDarkMode: (value: boolean) => void }) {
  const location = useLocation()
  const [systemMenuOpen, setSystemMenuOpen] = useState(false)
  const [userMenuOpen, setUserMenuOpen] = useState(false)
  const [mobileMenuOpen, setMobileMenuOpen] = useState(false)
  const [videoMenuOpen, setVideoMenuOpen] = useState(false)
  const [toolsMenuOpen, setToolsMenuOpen] = useState(false)
  const [analyticsMenuOpen, setAnalyticsMenuOpen] = useState(false)
  const [paidContentMenuOpen, setPaidContentMenuOpen] = useState(false)
  const systemMenuRef = useRef<HTMLDivElement>(null)
  const userMenuRef = useRef<HTMLDivElement>(null)
  const videoMenuRef = useRef<HTMLDivElement>(null)
  const toolsMenuRef = useRef<HTMLDivElement>(null)
  const analyticsMenuRef = useRef<HTMLDivElement>(null)
  const paidContentMenuRef = useRef<HTMLDivElement>(null)

  // Get enabled features to filter menu items and their order
  const { isFeatureEnabled, sortByOrder, getFeatureLabel, isLoading: featuresLoading } = useEnabledFeatures()
  const navigate = useNavigate()

  // Route protection - redirect if accessing disabled feature
  useEffect(() => {
    if (featuresLoading) return // Don't check while loading

    const currentPath = location.pathname
    // Skip protected routes and special pages
    if (currentPath === '/' || currentPath === '/login' || currentPath === '/2fa' ||
        currentPath === '/config' || currentPath.startsWith('/config')) {
      return
    }

    // Find the base feature path for the current route
    const featurePath = '/' + currentPath.split('/').filter(Boolean)[0]
    // Also check the full path for nested routes like /paid-content/feed
    const fullFeaturePath = currentPath

    // Check if feature is disabled
    if (!isFeatureEnabled(featurePath) && !isFeatureEnabled(fullFeaturePath)) {
      navigate('/', { replace: true })
    }
  }, [location.pathname, isFeatureEnabled, featuresLoading, navigate])

  // Close dropdowns when clicking outside
  useEffect(() => {
    function handleClickOutside(event: MouseEvent) {
      if (systemMenuRef.current && !systemMenuRef.current.contains(event.target as Node)) {
        setSystemMenuOpen(false)
      }
      if (userMenuRef.current && !userMenuRef.current.contains(event.target as Node)) {
        setUserMenuOpen(false)
      }
      if (videoMenuRef.current && !videoMenuRef.current.contains(event.target as Node)) {
        setVideoMenuOpen(false)
      }
      if (toolsMenuRef.current && !toolsMenuRef.current.contains(event.target as Node)) {
        setToolsMenuOpen(false)
      }
      if (analyticsMenuRef.current && !analyticsMenuRef.current.contains(event.target as Node)) {
        setAnalyticsMenuOpen(false)
      }
      if (paidContentMenuRef.current && !paidContentMenuRef.current.contains(event.target as Node)) {
        setPaidContentMenuOpen(false)
      }
    }
    document.addEventListener('mousedown', handleClickOutside)
    return () => document.removeEventListener('mousedown', handleClickOutside)
  }, [])

  // Primary nav items (always visible)
  const primaryNavItems = [
    { path: '/', label: 'Dashboard', icon: LayoutDashboard },
    { path: '/downloads', label: 'Downloads', icon: FolderDown },
    { path: '/gallery', label: 'Gallery', icon: GalleryHorizontalEnd },
    { path: '/review', label: 'Review', icon: ClipboardList },
  ]

  // Video dropdown items (video downloading features)
  const videoMenuItems = [
    { path: '/videos', label: 'Video Downloader', icon: Clapperboard },
    { path: '/celebrities', label: 'Internet Discovery', icon: Star },
    { path: '/queue', label: 'Download Queue', icon: ListVideo },
    { path: '/video/channel-monitors', label: 'Channel Monitors', icon: Video },
  ]

  // Tools dropdown items (actions & features)
  const toolsMenuItems = [
    { path: '/import', label: 'Manual Import', icon: FolderInput },
    { path: '/faces', label: 'Face Recognition', icon: ScanFace },
    { path: '/scheduler', label: 'Scheduler', icon: CalendarClock },
    { path: '/appearances', label: 'Appearances', icon: User },
    { path: '/press', label: 'Press', icon: Newspaper },
    { path: '/discovery', label: 'Discovery', icon: Compass },
    { path: '/recycle-bin', label: 'Recycle Bin', icon: Trash2 },
  ]

  // Analytics dropdown items
  const analyticsMenuItems = [
    { path: '/analytics', label: 'Analytics', icon: BarChart3 },
    { path: '/health', label: 'System Health', icon: HeartPulse },
    { path: '/monitoring', label: 'Monitoring', icon: Gauge },
    { path: '/notifications', label: 'Notifications', icon: BellRing },
  ]

  // Paid Content dropdown items
  const paidContentMenuItems = [
    { path: '/paid-content', label: 'Dashboard', icon: LayoutDashboard },
    { path: '/paid-content/feed', label: 'Feed', icon: ScrollText },
    { path: '/paid-content/gallery', label: 'Gallery', icon: GalleryHorizontalEnd },
    { path: '/paid-content/messages', label: 'Messages', icon: MessageCircle },
    { path: '/paid-content/creators', label: 'Creators', icon: Users },
    { path: '/paid-content/add', label: 'Add Content', icon: Plus },
    { path: '/paid-content/queue', label: 'Download Queue', icon: ListOrdered },
    { path: '/paid-content/watch-later', label: 'Watch Later', icon: Clock },
    { path: '/paid-content/analytics', label: 'Analytics', icon: BarChart3 },
    { path: '/paid-content/notifications', label: 'Notifications', icon: Bell },
    { path: '/paid-content/settings', label: 'Configuration', icon: Settings },
  ]

  // Private Gallery dropdown items (only shown when gallery is unlocked)
  const privateGalleryMenuItems = [
    { path: '/private-gallery', label: 'Gallery', icon: GalleryHorizontalEnd },
    { path: '/private-gallery/config', label: 'Settings', icon: Settings },
  ]

  const systemMenuItems = [
    { path: '/config', label: 'Configuration', icon: Settings },
    { path: '/platforms', label: 'Platforms', icon: Layers },
    { path: '/scrapers', label: 'Scrapers', icon: Bot },
    { path: '/logs', label: 'Logs', icon: ScrollText },
    { path: '/changelog', label: 'Change Log', icon: FileText },
  ]

  // Filter and sort menu items based on enabled features and their order
  const filteredPrimaryNavItems = useMemo(() => {
    // Dashboard (/) is always first and not part of any feature group
    const dashboard = primaryNavItems.filter(item => item.path === '/')
    const rest = sortByOrder(
      primaryNavItems.filter(item => item.path !== '/' && isFeatureEnabled(item.path)),
      'media'
    )
    return [...dashboard, ...rest]
  }, [isFeatureEnabled, sortByOrder]
  )
  const filteredVideoMenuItems = useMemo(() =>
    sortByOrder(
      videoMenuItems.filter(item => isFeatureEnabled(item.path)),
      'video'
    ),
    [isFeatureEnabled, sortByOrder]
  )
  const filteredToolsMenuItems = useMemo(() =>
    sortByOrder(
      toolsMenuItems.filter(item => isFeatureEnabled(item.path)),
      'tools'
    ),
    [isFeatureEnabled, sortByOrder]
  )
  const filteredAnalyticsMenuItems = useMemo(() =>
    sortByOrder(
      analyticsMenuItems.filter(item => isFeatureEnabled(item.path)),
      'analytics'
    ),
    [isFeatureEnabled, sortByOrder]
  )
  const filteredPaidContentMenuItems = useMemo(() =>
    sortByOrder(
      paidContentMenuItems.filter(item => isFeatureEnabled(item.path)),
      'paid-content'
    ),
    [isFeatureEnabled, sortByOrder]
  )
  const filteredSystemMenuItems = useMemo(() =>
    sortByOrder(
      systemMenuItems.filter(item => isFeatureEnabled(item.path)),
      'system'
    ),
    [isFeatureEnabled, sortByOrder]
  )
  const filteredPrivateGalleryMenuItems = useMemo(() =>
    sortByOrder(
      privateGalleryMenuItems.filter(item => isFeatureEnabled(item.path)),
      'private-gallery'
    ),
    [isFeatureEnabled, sortByOrder]
  )

  return (
    <>
    <nav className="bg-card/95 backdrop-blur-md border-b border-border shadow-soft sticky top-0 z-40" style={{ paddingTop: 'env(safe-area-inset-top)', paddingLeft: 'env(safe-area-inset-left)', paddingRight: 'env(safe-area-inset-right)' }}>
      <div className="container mx-auto px-4">
        <div className="flex items-center justify-between h-14">
          <div className="flex items-center space-x-4">
            {/* Mobile Menu Button */}
            <button
              onClick={() => setMobileMenuOpen(!mobileMenuOpen)}
              className="lg:hidden p-3 rounded-lg text-muted-foreground hover:text-foreground hover:bg-secondary min-w-[44px] min-h-[44px] flex items-center justify-center transition-colors"
              aria-label="Open menu"
            >
              <Menu className="w-6 h-6" />
            </button>

            <h1 className="text-xl font-bold text-foreground whitespace-nowrap tracking-tight">
              Media Downloader
            </h1>
            <div className="hidden lg:flex items-center space-x-1">
              {/* Primary nav items */}
              {filteredPrimaryNavItems.map((item) => {
                const Icon = item.icon
                const isActive = location.pathname === item.path
                return (
                  <Link
                    key={item.path}
                    to={item.path}
                    className={`flex items-center space-x-2 px-3 py-2 rounded-lg text-sm font-medium transition-all duration-200 ${
                      isActive
                        ? 'bg-primary text-primary-foreground shadow-sm'
                        : 'text-muted-foreground hover:text-foreground hover:bg-secondary'
                    }`}
                  >
                    <Icon className="w-4 h-4" />
                    <span>{getFeatureLabel(item.path, item.label)}</span>
                  </Link>
                )
              })}

              {/* Video Dropdown - hidden if all items are disabled */}
              {filteredVideoMenuItems.length > 0 && (
              <div className="relative" ref={videoMenuRef}>
                <button
                  onClick={() => {
                    setVideoMenuOpen(!videoMenuOpen)
                    setToolsMenuOpen(false)
                    setAnalyticsMenuOpen(false)
                    setPaidContentMenuOpen(false)
                  }}
                  className={`flex items-center space-x-1 px-3 py-2 rounded-lg text-sm font-medium transition-all duration-200 ${
                    filteredVideoMenuItems.some(item => location.pathname === item.path)
                      ? 'bg-primary text-primary-foreground shadow-sm'
                      : 'text-muted-foreground hover:text-foreground hover:bg-secondary'
                  }`}
                >
                  <Video className="w-4 h-4" />
                  <span>Video</span>
                  <ChevronDown className={`w-3 h-3 transition-transform duration-200 ${videoMenuOpen ? 'rotate-180' : ''}`} />
                </button>

                {videoMenuOpen && (
                  <div className="absolute left-0 mt-2 w-48 bg-popover rounded-xl shadow-soft-md border border-border py-1.5 z-50 animate-fade-in">
                    {filteredVideoMenuItems.map((item) => {
                      const Icon = item.icon
                      const isActive = location.pathname === item.path
                      return (
                        <Link
                          key={item.path}
                          to={item.path}
                          onClick={() => setVideoMenuOpen(false)}
                          className={`flex items-center space-x-2 px-4 py-2.5 mx-1.5 rounded-lg text-sm transition-all duration-200 ${
                            isActive
                              ? 'bg-primary/10 text-primary font-medium'
                              : 'text-muted-foreground hover:text-foreground hover:bg-secondary'
                          }`}
                        >
                          <Icon className="w-4 h-4" />
                          <span>{getFeatureLabel(item.path, item.label)}</span>
                        </Link>
                      )
                    })}
                  </div>
                )}
              </div>
              )}

              {/* Tools Dropdown - hidden if all items are disabled */}
              {filteredToolsMenuItems.length > 0 && (
              <div className="relative" ref={toolsMenuRef}>
                <button
                  onClick={() => {
                    setToolsMenuOpen(!toolsMenuOpen)
                    setVideoMenuOpen(false)
                    setAnalyticsMenuOpen(false)
                    setPaidContentMenuOpen(false)
                  }}
                  className={`flex items-center space-x-1 px-3 py-2 rounded-lg text-sm font-medium transition-all duration-200 ${
                    filteredToolsMenuItems.some(item => location.pathname === item.path)
                      ? 'bg-primary text-primary-foreground shadow-sm'
                      : 'text-muted-foreground hover:text-foreground hover:bg-secondary'
                  }`}
                >
                  <Wrench className="w-4 h-4" />
                  <span>Tools</span>
                  <ChevronDown className={`w-3 h-3 transition-transform duration-200 ${toolsMenuOpen ? 'rotate-180' : ''}`} />
                </button>

                {toolsMenuOpen && (
                  <div className="absolute left-0 mt-2 w-48 bg-popover rounded-xl shadow-soft-md border border-border py-1.5 z-50 animate-fade-in">
                    {filteredToolsMenuItems.map((item) => {
                      const Icon = item.icon
                      const isActive = location.pathname === item.path
                      return (
                        <Link
                          key={item.path}
                          to={item.path}
                          onClick={() => setToolsMenuOpen(false)}
                          className={`flex items-center space-x-2 px-4 py-2.5 mx-1.5 rounded-lg text-sm transition-all duration-200 ${
                            isActive
                              ? 'bg-primary/10 text-primary font-medium'
                              : 'text-muted-foreground hover:text-foreground hover:bg-secondary'
                          }`}
                        >
                          <Icon className="w-4 h-4" />
                          <span>{getFeatureLabel(item.path, item.label)}</span>
                        </Link>
                      )
                    })}
                  </div>
                )}
              </div>
              )}

              {/* Analytics Dropdown - hidden if all items are disabled */}
              {filteredAnalyticsMenuItems.length > 0 && (
              <div className="relative" ref={analyticsMenuRef}>
                <button
                  onClick={() => {
                    setAnalyticsMenuOpen(!analyticsMenuOpen)
                    setVideoMenuOpen(false)
                    setToolsMenuOpen(false)
                    setPaidContentMenuOpen(false)
                  }}
                  className={`flex items-center space-x-1 px-3 py-2 rounded-lg text-sm font-medium transition-all duration-200 ${
                    filteredAnalyticsMenuItems.some(item => location.pathname === item.path)
                      ? 'bg-primary text-primary-foreground shadow-sm'
                      : 'text-muted-foreground hover:text-foreground hover:bg-secondary'
                  }`}
                >
                  <BarChart3 className="w-4 h-4" />
                  <span>Insights</span>
                  <ChevronDown className={`w-3 h-3 transition-transform duration-200 ${analyticsMenuOpen ? 'rotate-180' : ''}`} />
                </button>

                {analyticsMenuOpen && (
                  <div className="absolute left-0 mt-2 w-48 bg-popover rounded-xl shadow-soft-md border border-border py-1.5 z-50 animate-fade-in">
                    {filteredAnalyticsMenuItems.map((item) => {
                      const Icon = item.icon
                      const isActive = location.pathname === item.path
                      return (
                        <Link
                          key={item.path}
                          to={item.path}
                          onClick={() => setAnalyticsMenuOpen(false)}
                          className={`flex items-center space-x-2 px-4 py-2.5 mx-1.5 rounded-lg text-sm transition-all duration-200 ${
                            isActive
                              ? 'bg-primary/10 text-primary font-medium'
                              : 'text-muted-foreground hover:text-foreground hover:bg-secondary'
                          }`}
                        >
                          <Icon className="w-4 h-4" />
                          <span>{getFeatureLabel(item.path, item.label)}</span>
                        </Link>
                      )
                    })}
                  </div>
                )}
              </div>
              )}

              {/* Paid Content Dropdown - hidden if all items are disabled */}
              {filteredPaidContentMenuItems.length > 0 && (
              <div className="relative" ref={paidContentMenuRef}>
                <button
                  onClick={() => {
                    setPaidContentMenuOpen(!paidContentMenuOpen)
                    setVideoMenuOpen(false)
                    setToolsMenuOpen(false)
                    setAnalyticsMenuOpen(false)
                  }}
                  className={`flex items-center space-x-1 px-3 py-2 rounded-lg text-sm font-medium transition-all duration-200 ${
                    filteredPaidContentMenuItems.some(item => location.pathname === item.path)
                      ? 'bg-primary text-primary-foreground shadow-sm'
                      : 'text-muted-foreground hover:text-foreground hover:bg-secondary'
                  }`}
                >
                  <Gem className="w-4 h-4" />
                  <span>Paid Content</span>
                  <ChevronDown className={`w-3 h-3 transition-transform duration-200 ${paidContentMenuOpen ? 'rotate-180' : ''}`} />
                </button>

                {paidContentMenuOpen && (
                  <div className="absolute left-0 mt-2 w-48 bg-popover rounded-xl shadow-soft-md border border-border py-1.5 z-50 animate-fade-in">
                    {filteredPaidContentMenuItems.map((item) => {
                      const Icon = item.icon
                      const isActive = location.pathname === item.path
                      return (
                        <Link
                          key={item.path}
                          to={item.path}
                          onClick={() => setPaidContentMenuOpen(false)}
                          className={`flex items-center space-x-2 px-4 py-2.5 mx-1.5 rounded-lg text-sm transition-all duration-200 ${
                            isActive
                              ? 'bg-primary/10 text-primary font-medium'
                              : 'text-muted-foreground hover:text-foreground hover:bg-secondary'
                          }`}
                        >
                          <Icon className="w-4 h-4" />
                          <span>{getFeatureLabel(item.path, item.label)}</span>
                        </Link>
                      )
                    })}
                  </div>
                )}
              </div>
              )}


            </div>
          </div>

          <div className="hidden lg:flex items-center space-x-2">
            {/* System Menu Dropdown */}
            <div className="relative" ref={systemMenuRef}>
              <button
                onClick={() => {
                  setSystemMenuOpen(!systemMenuOpen)
                  setVideoMenuOpen(false)
                  setToolsMenuOpen(false)
                  setAnalyticsMenuOpen(false)
                  setPaidContentMenuOpen(false)

                }}
                className={`flex items-center space-x-1 px-3 py-2 rounded-lg text-sm font-medium transition-all duration-200 ${
                  filteredSystemMenuItems.some(item => location.pathname === item.path) ||
                  filteredPrivateGalleryMenuItems.some(item => location.pathname === item.path) ||
                  location.pathname === '/private-gallery/unlock'
                    ? 'bg-primary text-primary-foreground shadow-sm'
                    : 'text-muted-foreground hover:text-foreground hover:bg-secondary'
                }`}
              >
                <Settings className="w-4 h-4" />
                <span>System</span>
                <ChevronDown className={`w-3 h-3 transition-transform duration-200 ${systemMenuOpen ? 'rotate-180' : ''}`} />
              </button>

              {systemMenuOpen && (
                <div className="absolute right-0 mt-2 w-48 bg-popover rounded-xl shadow-soft-md border border-border py-1.5 z-50 animate-fade-in">
                  {filteredSystemMenuItems.map((item) => {
                    const Icon = item.icon
                    const isActive = location.pathname === item.path
                    return (
                      <Link
                        key={item.path}
                        to={item.path}
                        onClick={() => setSystemMenuOpen(false)}
                        className={`flex items-center space-x-2 px-4 py-2.5 mx-1.5 rounded-lg text-sm transition-all duration-200 ${
                          isActive
                            ? 'bg-primary/10 text-primary font-medium'
                            : 'text-muted-foreground hover:text-foreground hover:bg-secondary'
                        }`}
                      >
                        <Icon className="w-4 h-4" />
                        <span>{getFeatureLabel(item.path, item.label)}</span>
                      </Link>
                    )
                  })}
                  {/* Private Gallery divider and items */}
                  {filteredPrivateGalleryMenuItems.length > 0 && (
                    <>
                      <div className="my-1.5 mx-3 border-t border-border" />
                      <div className="px-4 py-1.5 text-xs font-semibold text-muted-foreground uppercase tracking-wider flex items-center gap-1.5">
                        <Lock className="w-3 h-3" />
                        Private
                      </div>
                      {filteredPrivateGalleryMenuItems.map((item) => {
                        const Icon = item.icon
                        const isActive = location.pathname === item.path
                        return (
                          <Link
                            key={item.path}
                            to={item.path}
                            onClick={() => setSystemMenuOpen(false)}
                            className={`flex items-center space-x-2 px-4 py-2.5 mx-1.5 rounded-lg text-sm transition-all duration-200 ${
                              isActive
                                ? 'bg-primary/10 text-primary font-medium'
                                : 'text-muted-foreground hover:text-foreground hover:bg-secondary'
                            }`}
                          >
                            <Icon className="w-4 h-4" />
                            <span>{getFeatureLabel(item.path, item.label)}</span>
                          </Link>
                        )
                      })}
                    </>
                  )}
                </div>
              )}
            </div>

            {/* User Menu Dropdown */}
            <div className="relative" ref={userMenuRef}>
              <button
                onClick={() => {
                  setUserMenuOpen(!userMenuOpen)
                  setSystemMenuOpen(false)
                  setVideoMenuOpen(false)
                  setToolsMenuOpen(false)
                  setAnalyticsMenuOpen(false)
                  setPaidContentMenuOpen(false)

                }}
                className="flex items-center space-x-2 px-2.5 py-2 rounded-lg text-muted-foreground hover:text-foreground hover:bg-secondary transition-all duration-200"
              >
                <div className="w-8 h-8 rounded-full bg-primary/10 flex items-center justify-center">
                  <User className="w-4 h-4 text-primary" />
                </div>
                <ChevronDown className={`w-3 h-3 transition-transform duration-200 ${userMenuOpen ? 'rotate-180' : ''}`} />
              </button>

              {userMenuOpen && (
                <div className="absolute right-0 mt-2 w-56 bg-popover rounded-xl shadow-soft-md border border-border py-1.5 z-50 animate-fade-in">
                  <div className="px-4 py-3 border-b border-border">
                    <p className="text-xs text-muted-foreground">Signed in as</p>
                    <p className="text-sm font-semibold text-foreground">
                      {api.getAuthUser()?.username || 'admin'}
                    </p>
                  </div>

                  <div className="py-1.5">
                    <button
                      onClick={() => {
                        setDarkMode(!darkMode)
                        setUserMenuOpen(false)
                      }}
                      className="w-full flex items-center space-x-2 px-4 py-2.5 mx-1.5 rounded-lg text-sm text-muted-foreground hover:text-foreground hover:bg-secondary transition-all duration-200"
                      style={{ width: 'calc(100% - 12px)' }}
                    >
                      {darkMode ? <Sun className="w-4 h-4" /> : <Moon className="w-4 h-4" />}
                      <span>{darkMode ? 'Light' : 'Dark'} Mode</span>
                    </button>
                  </div>

                  <div className="border-t border-border py-1.5">
                    <button
                      onClick={() => api.logout()}
                      className="w-full flex items-center space-x-2 px-4 py-2.5 mx-1.5 rounded-lg text-sm text-destructive hover:bg-destructive/10 transition-all duration-200"
                      style={{ width: 'calc(100% - 12px)' }}
                    >
                      <LogOut className="w-4 h-4" />
                      <span>Logout</span>
                    </button>
                  </div>

                  <div className="border-t border-border px-4 py-2.5">
                    <p className="text-xs text-muted-foreground">v13.13.1</p>
                  </div>
                </div>
              )}
            </div>
          </div>
        </div>
      </div>
    </nav>

    {/* Mobile Menu Overlay */}
    {mobileMenuOpen && (
      <div
        className="fixed inset-0 bg-background/80 backdrop-blur-sm z-40 lg:hidden animate-fade-in"
        onClick={() => setMobileMenuOpen(false)}
      />
    )}

    {/* Mobile Menu Drawer */}
    <div
      className={`fixed top-0 left-0 h-full w-72 bg-card shadow-soft-lg z-50 transform transition-transform duration-300 ease-out lg:hidden ${
        mobileMenuOpen ? 'translate-x-0' : '-translate-x-full'
      }`}
      style={{ paddingTop: 'env(safe-area-inset-top)', paddingLeft: 'env(safe-area-inset-left)' }}
    >
      <div className="p-4 border-b border-border">
        <h2 className="text-lg font-bold text-foreground">Menu</h2>
      </div>

      <div className="overflow-y-auto h-full pb-20 custom-scrollbar">
        {/* Main Navigation */}
        <div className="p-3">
          <p className="px-3 py-2 text-xs font-semibold text-muted-foreground uppercase tracking-wider">
            Main
          </p>
          {filteredPrimaryNavItems.map((item) => {
            const Icon = item.icon
            const isActive = location.pathname === item.path
            return (
              <Link
                key={item.path}
                to={item.path}
                onClick={() => setMobileMenuOpen(false)}
                className={`flex items-center space-x-3 px-4 py-3 rounded-xl text-base font-medium transition-all duration-200 min-h-[48px] ${
                  isActive
                    ? 'bg-primary text-primary-foreground shadow-sm'
                    : 'text-muted-foreground hover:text-foreground hover:bg-secondary'
                }`}
              >
                <Icon className="w-5 h-5" />
                <span>{getFeatureLabel(item.path, item.label)}</span>
              </Link>
            )
          })}
        </div>

        {/* Video */}
        <div className="p-3 pt-0">
          <p className="px-3 py-2 text-xs font-semibold text-muted-foreground uppercase tracking-wider">
            Video
          </p>
          {filteredVideoMenuItems.map((item) => {
            const Icon = item.icon
            const isActive = location.pathname === item.path
            return (
              <Link
                key={item.path}
                to={item.path}
                onClick={() => setMobileMenuOpen(false)}
                className={`flex items-center space-x-3 px-4 py-3 rounded-xl text-base font-medium transition-all duration-200 min-h-[48px] ${
                  isActive
                    ? 'bg-primary text-primary-foreground shadow-sm'
                    : 'text-muted-foreground hover:text-foreground hover:bg-secondary'
                }`}
              >
                <Icon className="w-5 h-5" />
                <span>{getFeatureLabel(item.path, item.label)}</span>
              </Link>
            )
          })}
        </div>

        {/* Tools */}
        <div className="p-3 pt-0">
          <p className="px-3 py-2 text-xs font-semibold text-muted-foreground uppercase tracking-wider">
            Tools
          </p>
          {filteredToolsMenuItems.map((item) => {
            const Icon = item.icon
            const isActive = location.pathname === item.path
            return (
              <Link
                key={item.path}
                to={item.path}
                onClick={() => setMobileMenuOpen(false)}
                className={`flex items-center space-x-3 px-4 py-3 rounded-xl text-base font-medium transition-all duration-200 min-h-[48px] ${
                  isActive
                    ? 'bg-primary text-primary-foreground shadow-sm'
                    : 'text-muted-foreground hover:text-foreground hover:bg-secondary'
                }`}
              >
                <Icon className="w-5 h-5" />
                <span>{getFeatureLabel(item.path, item.label)}</span>
              </Link>
            )
          })}
        </div>

        {/* Insights */}
        <div className="p-3 pt-0">
          <p className="px-3 py-2 text-xs font-semibold text-muted-foreground uppercase tracking-wider">
            Insights
          </p>
          {filteredAnalyticsMenuItems.map((item) => {
            const Icon = item.icon
            const isActive = location.pathname === item.path
            return (
              <Link
                key={item.path}
                to={item.path}
                onClick={() => setMobileMenuOpen(false)}
                className={`flex items-center space-x-3 px-4 py-3 rounded-xl text-base font-medium transition-all duration-200 min-h-[48px] ${
                  isActive
                    ? 'bg-primary text-primary-foreground shadow-sm'
                    : 'text-muted-foreground hover:text-foreground hover:bg-secondary'
                }`}
              >
                <Icon className="w-5 h-5" />
                <span>{getFeatureLabel(item.path, item.label)}</span>
              </Link>
            )
          })}
        </div>

        {/* Paid Content */}
        <div className="p-3 pt-0">
          <p className="px-3 py-2 text-xs font-semibold text-muted-foreground uppercase tracking-wider flex items-center space-x-2">
            <Gem className="w-4 h-4" />
            <span>Paid Content</span>
          </p>
          {filteredPaidContentMenuItems.map((item) => {
            const Icon = item.icon
            const isActive = location.pathname === item.path
            return (
              <Link
                key={item.path}
                to={item.path}
                onClick={() => setMobileMenuOpen(false)}
                className={`flex items-center space-x-3 px-4 py-3 rounded-xl text-base font-medium transition-all duration-200 min-h-[48px] ${
                  isActive
                    ? 'bg-primary text-primary-foreground shadow-sm'
                    : 'text-muted-foreground hover:text-foreground hover:bg-secondary'
                }`}
              >
                <Icon className="w-5 h-5" />
                <span>{getFeatureLabel(item.path, item.label)}</span>
              </Link>
            )
          })}
        </div>

        {/* System Menu */}
        <div className="p-3 pt-0">
          <p className="px-3 py-2 text-xs font-semibold text-muted-foreground uppercase tracking-wider">
            System
          </p>
          {filteredSystemMenuItems.map((item) => {
            const Icon = item.icon
            const isActive = location.pathname === item.path
            return (
              <Link
                key={item.path}
                to={item.path}
                onClick={() => setMobileMenuOpen(false)}
                className={`flex items-center space-x-3 px-4 py-3 rounded-xl text-base font-medium transition-all duration-200 min-h-[48px] ${
                  isActive
                    ? 'bg-primary text-primary-foreground shadow-sm'
                    : 'text-muted-foreground hover:text-foreground hover:bg-secondary'
                }`}
              >
                <Icon className="w-5 h-5" />
                <span>{getFeatureLabel(item.path, item.label)}</span>
              </Link>
            )
          })}
          {/* Private Gallery under System */}
          {filteredPrivateGalleryMenuItems.length > 0 && (
            <>
              <div className="my-2 mx-3 border-t border-border" />
              <p className="px-3 py-2 text-xs font-semibold text-muted-foreground uppercase tracking-wider flex items-center space-x-2">
                <Lock className="w-3.5 h-3.5" />
                <span>Private</span>
              </p>
              {filteredPrivateGalleryMenuItems.map((item) => {
                const Icon = item.icon
                const isActive = location.pathname === item.path
                return (
                  <Link
                    key={item.path}
                    to={item.path}
                    onClick={() => setMobileMenuOpen(false)}
                    className={`flex items-center space-x-3 px-4 py-3 rounded-xl text-base font-medium transition-all duration-200 min-h-[48px] ${
                      isActive
                        ? 'bg-primary text-primary-foreground shadow-sm'
                        : 'text-muted-foreground hover:text-foreground hover:bg-secondary'
                    }`}
                  >
                    <Icon className="w-5 h-5" />
                    <span>{getFeatureLabel(item.path, item.label)}</span>
                  </Link>
                )
              })}
            </>
          )}
        </div>

        {/* Settings */}
        <div className="p-3 mt-2 border-t border-border">
          <p className="px-3 py-2 text-xs font-semibold text-muted-foreground uppercase tracking-wider">
            Settings
          </p>
          <button
            onClick={() => {
              setDarkMode(!darkMode)
              setMobileMenuOpen(false)
            }}
            className="w-full flex items-center space-x-3 px-4 py-3 rounded-xl text-base text-muted-foreground hover:text-foreground hover:bg-secondary transition-all duration-200 min-h-[48px]"
          >
            {darkMode ? <Sun className="w-5 h-5" /> : <Moon className="w-5 h-5" />}
            <span>{darkMode ? 'Light' : 'Dark'} Mode</span>
          </button>

          <button
            onClick={() => {
              api.logout()
              setMobileMenuOpen(false)
            }}
            className="w-full flex items-center space-x-3 px-4 py-3 rounded-xl text-base text-destructive hover:bg-destructive/10 transition-all duration-200 mt-1 min-h-[48px]"
          >
            <LogOut className="w-5 h-5" />
            <span>Logout</span>
          </button>
        </div>

        <div className="p-3 mt-2 border-t border-border">
          <p className="px-3 py-1 text-xs text-muted-foreground">
            Signed in as <span className="font-semibold text-foreground">{api.getAuthUser()?.username || 'admin'}</span>
          </p>
          <p className="px-3 py-1 text-xs text-muted-foreground">v13.13.1</p>
        </div>
      </div>
    </div>
    </>
  )
}

function App() {
  const [darkMode, setDarkMode] = useState(() => {
    // First check if user has a saved theme preference in their profile
    const user = api.getAuthUser()
    if (user?.preferences?.theme) {
      return user.preferences.theme === 'dark'
    }

    // Check localStorage
    const saved = localStorage.getItem('darkMode')
    if (saved !== null) {
      try {
        return JSON.parse(saved)
      } catch {
        // Invalid JSON, ignore and continue to auto-detect
        localStorage.removeItem('darkMode')
      }
    }

    // Auto-detect system preference as fallback
    if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
      return true
    }

    return false
  })

  // Notification state
  const [notifications, setNotifications] = useState<ToastNotification[]>([])

  useEffect(() => {
    // Subscribe to notification manager
    const unsubscribe = notificationManager.subscribe((newNotifications) => {
      setNotifications(newNotifications)
    })

    return unsubscribe
  }, [])

  useEffect(() => {
    // Connect WebSocket on mount
    wsClient.connect()

    // Set up WebSocket listeners for in-app notifications (always enabled)
    const unsubscribeStarted = wsClient.on('download_started', (data) => {
      notificationManager.downloadStarted(
        data.platform || 'Unknown',
        data.username || 'unknown'
      )
    })

    const unsubscribeComplete = wsClient.on('download_completed', (data) => {
      // Only show notification for scheduled downloads, not manual platform runs
      if (!data.from_platform_page) {
        notificationManager.downloadCompleted(
          data.platform || 'Unknown',
          data.filename || 'File',
          data.username
        )
      }
    })

    const unsubscribeError = wsClient.on('download_error', (data) => {
      notificationManager.downloadError(
        data.platform || 'Unknown',
        data.error || 'Download failed'
      )
    })

    const unsubscribeScheduler = wsClient.on('scheduler_update', (data) => {
      notificationManager.info('Scheduler Update', data.message || 'Scheduler updated', '📅')
    })

    const unsubscribeBatchDelete = wsClient.on('batch_delete_completed', (data) => {
      const success = data.deleted_count > 0
      const icon = success ? '✅' : '❌'
      const isBatch = data.deleted_count > 1
      const title = isBatch ? 'Batch Delete' : 'Media Deleted'
      const message = `${data.deleted_count} item${data.deleted_count !== 1 ? 's' : ''} ${success ? 'deleted' : 'failed'}`
      if (success) {
        notificationManager.success(title, message, icon)
      } else {
        notificationManager.error(title, message, icon)
      }
    })

    const unsubscribeBatchMove = wsClient.on('batch_move_completed', (data) => {
      const success = data.moved_count > 0
      const icon = success ? '✅' : '❌'
      const message = `${data.moved_count} item${data.moved_count !== 1 ? 's' : ''} ${success ? 'moved' : 'failed'}`
      if (success) {
        notificationManager.success('Batch Move', message, icon)
      } else {
        notificationManager.error('Batch Move', message, icon)
      }
    })

    // Real-time error alerts from backend
    const unsubscribeErrorAlert = wsClient.on('error_alert', (data) => {
      if (data.error) {
        const module = data.error.module || 'System'
        const message = data.error.message || 'An error occurred'
        notificationManager.error(`Error: ${module}`, message, '🚨')
      }
    })

    // Database notifications (from pushover_notifier.py) - show as toast when created
    const unsubscribeNotificationCreated = wsClient.on('notification_created', (data) => {
      if (data.notification && data.notification.status === 'sent') {
        const notif = data.notification
        const count = notif.download_count || 1
        const itemText = count === 1 ? 'item' : 'items'
        const filename = `${count} ${itemText}`

        // Use the centralized downloadCompleted helper
        notificationManager.downloadCompleted(
          notif.platform || 'Download',
          filename,
          notif.source
        )
      }
    })

    return () => {
      unsubscribeStarted()
      unsubscribeComplete()
      unsubscribeError()
      unsubscribeScheduler()
      unsubscribeBatchDelete()
      unsubscribeBatchMove()
      unsubscribeErrorAlert()
      unsubscribeNotificationCreated()
      wsClient.disconnect()
    }
  }, [])

  // Listen for system theme changes
  useEffect(() => {
    if (!window.matchMedia) return

    const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)')

    const handleChange = (e: MediaQueryListEvent) => {
      // Only auto-update if user hasn't manually set a preference
      const saved = localStorage.getItem('darkMode')
      if (saved === null) {
        setDarkMode(e.matches)
      }
    }

    mediaQuery.addEventListener('change', handleChange)
    return () => mediaQuery.removeEventListener('change', handleChange)
  }, [])

  useEffect(() => {
    // Handle Duo callback
    const params = new URLSearchParams(window.location.search)
    const duoAuth = params.get('duo_auth')

    if (duoAuth === 'success') {
      const token = params.get('token')
      const sessionId = params.get('sessionId')
      const username = params.get('username')

      if (token && sessionId && username) {
        // Store auth data
        const user = { username, role: 'admin', email: `${username}@localhost` }
        api.setAuthToken(token, user, sessionId)

        // Clear URL parameters and reload to the dashboard
        window.history.replaceState({}, '', '/')
        window.location.reload()
      }
    } else if (duoAuth === 'failed') {
      // Clear URL and show error
      window.history.replaceState({}, '', '/login')
      window.location.reload()
    }
  }, [])

  useEffect(() => {
    // Apply dark mode class to document
    if (darkMode) {
      document.documentElement.classList.add('dark')
    } else {
      document.documentElement.classList.remove('dark')
    }

    // Save preference to localStorage
    localStorage.setItem('darkMode', JSON.stringify(darkMode))

    // Save to database if logged in (silently fail if not)
    const token = localStorage.getItem('auth_token')
    if (token) {
      api.updatePreferences({ theme: darkMode ? 'dark' : 'light' }).catch(() => {
        // Silently ignore errors (user might not be logged in anymore)
      })
    }
  }, [darkMode])

  return (
    <ErrorBoundary>
      <BrowserRouter
        future={{ v7_startTransition: true, v7_relativeSplatPath: true }}
      >
        <RouteTracker />
        <Routes>
          <Route path="/login" element={<Suspense fallback={<div className="min-h-screen flex items-center justify-center bg-background"><div className="animate-spin rounded-full h-8 w-8 border-2 border-primary border-t-transparent"></div></div>}><Login /></Suspense>} />
          <Route path="/2fa" element={<Suspense fallback={<div className="min-h-screen flex items-center justify-center bg-background"><div className="animate-spin rounded-full h-8 w-8 border-2 border-primary border-t-transparent"></div></div>}><TwoFactorAuth /></Suspense>} />
          <Route
            path="/*"
            element={
              <ProtectedRoute>
                <PrivateGalleryProvider>
                  <BreadcrumbProvider>
                    <div className="min-h-screen bg-background theme-transition">
                      <Navigation darkMode={darkMode} setDarkMode={setDarkMode} />
                      <main className="container mx-auto px-3 md:px-4 py-4 md:py-6" style={{ paddingLeft: 'calc(0.75rem + env(safe-area-inset-left))', paddingRight: 'calc(0.75rem + env(safe-area-inset-right))' }}>
                        <Breadcrumb />
                        <ErrorBoundary>
                          <Suspense fallback={
                          <div className="flex items-center justify-center h-64">
                            <div className="animate-spin rounded-full h-8 w-8 border-2 border-primary border-t-transparent"></div>
                          </div>
                        }>
                          <Routes>
                            <Route path="/" element={<Dashboard />} />
                            <Route path="/downloads" element={<Downloads />} />
                            <Route path="/gallery" element={<Gallery />} />
                            <Route path="/media" element={<Navigate to="/gallery" replace />} />
                            <Route path="/review" element={<Review />} />
                            <Route path="/videos" element={<VideoDownloader />} />
                            <Route path="/celebrities" element={<InternetDiscovery />} />
                            <Route path="/queue" element={<DownloadQueue />} />
                            <Route path="/video/channel-monitors" element={<ChannelMonitors />} />
                            <Route path="/import" element={<ManualImport />} />
                            <Route path="/discovery" element={<Discovery />} />
                            <Route path="/appearances" element={<Appearances />} />
                            <Route path="/press" element={<Press />} />
                            <Route path="/analytics" element={<Analytics />} />
                            <Route path="/faces" element={<FaceRecognitionDashboard />} />
                            <Route path="/platforms" element={<Platforms />} />
                            <Route path="/scheduler" element={<Scheduler />} />
                            <Route path="/health" element={<Health />} />
                            <Route path="/scrapers" element={<Scrapers />} />
                            <Route path="/monitoring" element={<Monitoring />} />
                            <Route path="/scraping-monitor" element={<ScrapingMonitor />} />
                            <Route path="/logs" element={<Logs />} />
                            <Route path="/recycle-bin" element={<RecycleBin />} />
                            <Route path="/config" element={<Configuration />} />
                            <Route path="/notifications" element={<Notifications />} />
                            <Route path="/changelog" element={<Changelog />} />
                            {/* Paid Content Routes */}
                            <Route path="/paid-content" element={<PaidContentDashboard />} />
                            <Route path="/paid-content/feed" element={<PaidContentFeed />} />
                            <Route path="/paid-content/creators" element={<PaidContentCreators />} />
                            <Route path="/paid-content/add" element={<PaidContentAddContent />} />
                            <Route path="/paid-content/queue" element={<PaidContentQueue />} />
                            <Route path="/paid-content/notifications" element={<PaidContentNotifications />} />
                            <Route path="/paid-content/settings" element={<PaidContentSettings />} />
                            <Route path="/paid-content/messages" element={<PaidContentMessages />} />
                            <Route path="/paid-content/messages/:creatorId" element={<PaidContentMessages />} />
                            <Route path="/paid-content/analytics" element={<PaidContentAnalytics />} />
                            <Route path="/paid-content/watch-later" element={<PaidContentWatchLater />} />
                            <Route path="/paid-content/bulk-delete" element={<PaidContentBulkDelete />} />
                            <Route path="/paid-content/gallery" element={<PaidContentGallery />} />
                            {/* Private Gallery Routes */}
                            <Route path="/private-gallery" element={<RequirePrivateGalleryAuth><PrivateGallery /></RequirePrivateGalleryAuth>} />
                            <Route path="/private-gallery/unlock" element={<PrivateGalleryUnlock />} />
                            <Route path="/private-gallery/config" element={<RequirePrivateGalleryAuth><PrivateGalleryConfig /></RequirePrivateGalleryAuth>} />
                          </Routes>
                        </Suspense>
                        </ErrorBoundary>
                      </main>
                      {/* In-app notification toasts */}
                      <NotificationToast
                        notifications={notifications}
                        onDismiss={(id) => notificationManager.dismiss(id)}
                      />
                    </div>
                  </BreadcrumbProvider>
                </PrivateGalleryProvider>
              </ProtectedRoute>
            }
          />
        </Routes>
      </BrowserRouter>
    </ErrorBoundary>
  )
}

export default App
