'use client'

import { useEffect, useState } from 'react'
import { useRouter } from 'next/navigation'
import { useStore } from '@/lib/store'
import { api } from '@/lib/api'
import { EarningsTab } from '@/components/admin/EarningsTab'
import { ZonesTab } from '@/components/admin/ZonesTab'
import { PremiumTable, Badge, TableActionButton, StatCard } from '@/components/PremiumTable'
import {
  Users,
  Mail,
  TrendingUp,
  Shield,
  RefreshCw,
  Search,
  Crown,
  Zap,
  Activity,
  BarChart3,
  Globe,
  Bell,
  AlertCircle,
  Check,
  Loader2,
  Trash2,
  Eye,
  Gavel,
  CheckCircle,
  XCircle,
  Download,
  Send,
  History,
  X,
  BookOpen,
  Plus,
  Edit2,
  ExternalLink,
  Database,
  Tag,
  Target,
  Wallet,
  Link,
  DollarSign,
  ChevronLeft,
  ChevronRight,
  LogOut,
  LayoutDashboard,
  Menu,
  Settings,
} from 'lucide-react'
import clsx from 'clsx'
import NextLink from 'next/link'
import Image from 'next/image'

// ============================================================================
// TYPES
// ============================================================================

type TabType = 'overview' | 'earnings' | 'telemetry' | 'users' | 'alerts' | 'newsletter' | 'tld' | 'auctions' | 'blog' | 'system' | 'activity' | 'zones'

interface AdminStats {
  users: { total: number; active: number; verified: number; new_this_week: number }
  subscriptions: Record<string, number>
  domains: { watched: number; portfolio: number }
  tld_data: { unique_tlds: number; price_records: number }
  newsletter_subscribers: number
  auctions: number
  price_alerts: number
}

interface AdminUser {
  id: number
  email: string
  name: string | null
  is_active: boolean
  is_verified: boolean
  is_admin: boolean
  created_at: string
  last_login: string | null
  domain_count: number
  subscription: { tier: string; tier_name: string; status: string | null; domain_limit: number }
}

// ============================================================================
// TAB CONFIG
// ============================================================================

const TABS: Array<{ id: TabType; label: string; icon: any; shortLabel?: string }> = [
  { id: 'overview', label: 'Overview', icon: Activity, shortLabel: 'Overview' },
  { id: 'earnings', label: 'Earnings', icon: DollarSign, shortLabel: 'Earnings' },
  { id: 'telemetry', label: 'Telemetry', icon: BarChart3, shortLabel: 'KPIs' },
  { id: 'zones', label: 'Zone Sync', icon: RefreshCw, shortLabel: 'Zones' },
  { id: 'users', label: 'Users', icon: Users, shortLabel: 'Users' },
  { id: 'newsletter', label: 'Newsletter', icon: Mail, shortLabel: 'News' },
  { id: 'tld', label: 'TLD Data', icon: Globe, shortLabel: 'TLD' },
  { id: 'auctions', label: 'Auctions', icon: Gavel, shortLabel: 'Auctions' },
  { id: 'system', label: 'System', icon: Database, shortLabel: 'System' },
  { id: 'activity', label: 'Activity', icon: History, shortLabel: 'Log' },
]

// ============================================================================
// MAIN PAGE
// ============================================================================

export default function AdminPage() {
  const router = useRouter()
  const { user, isAuthenticated, isLoading, checkAuth, logout } = useStore()
  
  const [activeTab, setActiveTab] = useState<TabType>('overview')
  const [sidebarCollapsed, setSidebarCollapsed] = useState(false)
  const [mobileMenuOpen, setMobileMenuOpen] = useState(false)
  
  // Data states
  const [stats, setStats] = useState<AdminStats | null>(null)
  const [telemetryDays, setTelemetryDays] = useState(30)
  const [telemetry, setTelemetry] = useState<any>(null)
  const [referrals, setReferrals] = useState<any>(null)
  const [users, setUsers] = useState<AdminUser[]>([])
  const [usersTotal, setUsersTotal] = useState(0)
  const [newsletter, setNewsletter] = useState<any[]>([])
  const [newsletterTotal, setNewsletterTotal] = useState(0)
  const [priceAlerts, setPriceAlerts] = useState<any[]>([])
  const [priceAlertsTotal, setPriceAlertsTotal] = useState(0)
  const [activityLog, setActivityLog] = useState<any[]>([])
  const [activityLogTotal, setActivityLogTotal] = useState(0)
  const [blogPosts, setBlogPosts] = useState<any[]>([])
  const [blogPostsTotal, setBlogPostsTotal] = useState(0)
  const [schedulerStatus, setSchedulerStatus] = useState<any>(null)
  const [systemHealth, setSystemHealth] = useState<any>(null)
  const [backups, setBackups] = useState<any[]>([])
  
  // UI states
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [success, setSuccess] = useState<string | null>(null)
  const [searchQuery, setSearchQuery] = useState('')
  
  // Action states
  const [scraping, setScraping] = useState(false)
  const [auctionScraping, setAuctionScraping] = useState(false)
  const [domainChecking, setDomainChecking] = useState(false)
  const [sendingEmail, setSendingEmail] = useState(false)
  const [backingUp, setBackingUp] = useState(false)
  const [runningOpsAlerts, setRunningOpsAlerts] = useState(false)
  const [opsAlertsHistory, setOpsAlertsHistory] = useState<any[]>([])

  // Auth check
  useEffect(() => {
    checkAuth()
  }, [checkAuth])

  useEffect(() => {
    if (!isLoading && !isAuthenticated) {
      router.push('/login')
    }
  }, [isLoading, isAuthenticated, router])

  useEffect(() => {
    const saved = localStorage.getItem('admin-sidebar-collapsed')
    if (saved) setSidebarCollapsed(saved === 'true')
  }, [])

  // Load data when tab changes
  useEffect(() => {
    if (!user?.is_admin) return
      loadAdminData()
  }, [activeTab, user?.is_admin])

  const toggleSidebar = () => {
    const newState = !sidebarCollapsed
    setSidebarCollapsed(newState)
    localStorage.setItem('admin-sidebar-collapsed', String(newState))
  }

  const loadAdminData = async () => {
    setLoading(true)
    setError(null)
    
    try {
      if (activeTab === 'overview') {
        const statsData = await api.getAdminStats()
        setStats(statsData)
      } else if (activeTab === 'telemetry') {
        const [kpis, refKpis] = await Promise.all([
          api.getTelemetryKpis(telemetryDays),
          api.getReferralKpis(telemetryDays).catch(() => null),
        ])
        setTelemetry(kpis)
        setReferrals(refKpis)
      } else if (activeTab === 'users') {
        const usersData = await api.getAdminUsers(50, 0, searchQuery || undefined)
        setUsers(usersData.users)
        setUsersTotal(usersData.total)
      } else if (activeTab === 'alerts') {
        const alertsData = await api.getAdminPriceAlerts(100, 0)
        setPriceAlerts(alertsData.alerts)
        setPriceAlertsTotal(alertsData.total)
      } else if (activeTab === 'newsletter') {
        const nlData = await api.getAdminNewsletter(100, 0)
        setNewsletter(nlData.subscribers)
        setNewsletterTotal(nlData.total)
      } else if (activeTab === 'system') {
          const [healthData, schedulerData] = await Promise.all([
          api.getSystemHealth().catch(() => null),
          api.getSchedulerStatus().catch(() => null),
          ])
          setSystemHealth(healthData)
          setSchedulerStatus(schedulerData)
        const backupData = await api.listDbBackups(20).catch(() => ({ backups: [] }))
        setBackups(backupData.backups || [])
        const opsHistory = await api.getOpsAlertsHistory(50).catch(() => ({ events: [] }))
        setOpsAlertsHistory(opsHistory.events || [])
      } else if (activeTab === 'activity') {
        const logData = await api.getActivityLog(50, 0).catch(() => ({ logs: [], total: 0 }))
          setActivityLog(logData.logs)
          setActivityLogTotal(logData.total)
      } else if (activeTab === 'blog') {
        const blogData = await api.getAdminBlogPosts(50, 0).catch(() => ({ posts: [], total: 0 }))
          setBlogPosts(blogData.posts)
          setBlogPostsTotal(blogData.total)
      }
    } catch (err) {
        setError(err instanceof Error ? err.message : 'Failed to load admin data')
    } finally {
      setLoading(false)
    }
  }

  // Actions
  const handleTriggerScrape = async () => {
    setScraping(true)
    try {
      const result = await api.triggerTldScrape()
      setSuccess(`Scrape completed: ${result.tlds_scraped} TLDs`)
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Scrape failed')
    } finally {
      setScraping(false)
    }
  }

  const handleTriggerAuctionScrape = async () => {
    setAuctionScraping(true)
    try {
      const result = await api.triggerAuctionScrape()
      setSuccess(`Auction scrape completed: ${result.total_auctions || 0} auctions`)
      loadAdminData()
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Auction scrape failed')
    } finally {
      setAuctionScraping(false)
    }
  }

  const handleTriggerDomainChecks = async () => {
    setDomainChecking(true)
    try {
      const result = await api.triggerDomainChecks()
      setSuccess(`Domain checks started: ${result.domains_queued} queued`)
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Domain check failed')
    } finally {
      setDomainChecking(false)
    }
  }

  const handleSendTestEmail = async () => {
    setSendingEmail(true)
    try {
      const result = await api.sendTestEmail()
      setSuccess(`Test email sent to ${result.sent_to}`)
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Email test failed')
    } finally {
      setSendingEmail(false)
    }
  }

  const handleCreateBackup = async () => {
    setBackingUp(true)
    try {
      const result = await api.createDbBackup(true)
      setSuccess(`Backup created (${Math.round((result.backup.size_bytes || 0) / 1024 / 1024)} MB)`)
      const backupData = await api.listDbBackups(20).catch(() => ({ backups: [] }))
      setBackups(backupData.backups || [])
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Backup failed')
    } finally {
      setBackingUp(false)
    }
  }

  const handleRunOpsAlerts = async () => {
    setRunningOpsAlerts(true)
    try {
      const res = await api.runOpsAlertsNow()
      const findings = Array.isArray(res?.findings) ? res.findings.length : 0
      const sent = res?.send?.sent ?? 0
      setSuccess(`Ops alert check done: ${findings} finding(s), emails sent: ${sent}`)
      const opsHistory = await api.getOpsAlertsHistory(50).catch(() => ({ events: [] }))
      setOpsAlertsHistory(opsHistory.events || [])
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Ops alert check failed')
    } finally {
      setRunningOpsAlerts(false)
    }
  }

  const handleUpgradeUser = async (userId: number, tier: string) => {
    try {
      await api.upgradeUser(userId, tier)
      setSuccess(`User upgraded to ${tier}`)
      loadAdminData()
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Upgrade failed')
    }
  }

  const handleToggleAdmin = async (userId: number, isAdmin: boolean) => {
    try {
      await api.updateAdminUser(userId, { is_admin: !isAdmin })
      setSuccess(isAdmin ? 'Admin removed' : 'Admin granted')
      loadAdminData()
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Update failed')
    }
  }

  const handleDeleteUser = async (userId: number, email: string) => {
    if (!confirm(`Delete user "${email}"? This cannot be undone.`)) return
    try {
      await api.deleteAdminUser(userId)
      setSuccess(`User ${email} deleted`)
      loadAdminData()
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Delete failed')
    }
  }

  const handleExportUsers = async () => {
    try {
      const result = await api.exportUsersCSV()
      const blob = new Blob([result.csv], { type: 'text/csv' })
      const url = URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = `users-${new Date().toISOString().split('T')[0]}.csv`
      a.click()
      setSuccess(`Exported ${result.count} users`)
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Export failed')
    }
  }

  // Loading state
  if (isLoading) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-[#020202]">
        <div className="flex flex-col items-center gap-4">
          <Loader2 className="w-8 h-8 text-red-400 animate-spin" />
          <p className="text-white/40 text-sm font-mono">Loading...</p>
        </div>
      </div>
    )
  }

  // Access denied
  if (!isAuthenticated || !user?.is_admin) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-[#020202]">
        <div className="text-center">
          <Shield className="w-16 h-16 text-red-400 mx-auto mb-4" />
          <h1 className="text-xl font-bold text-white mb-2">Access Denied</h1>
          <p className="text-white/40 mb-6 font-mono">Admin privileges required</p>
          <button
            onClick={() => router.push('/terminal/hunt')}
            className="px-6 py-3 bg-red-500 text-white font-bold uppercase tracking-wider hover:bg-red-400 transition-colors"
          >
            Go to Dashboard
          </button>
        </div>
      </div>
    )
  }

  return (
    <div className="min-h-screen bg-[#020202]">
      {/* Background Effects */}
      <div className="fixed inset-0 pointer-events-none">
        <div className="absolute top-[-30%] left-[-10%] w-[800px] h-[800px] bg-red-500/[0.02] rounded-full blur-[120px]" />
        <div className="absolute bottom-[-20%] right-[-10%] w-[600px] h-[600px] bg-accent/[0.02] rounded-full blur-[100px]" />
      </div>

      {/* Mobile Menu Button */}
      <button
        onClick={() => setMobileMenuOpen(true)}
        className="lg:hidden fixed top-4 left-4 z-50 w-10 h-10 bg-[#020202] border border-red-500/20 flex items-center justify-center text-white/60 hover:text-white"
      >
        <Menu className="w-5 h-5" />
      </button>

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

      {/* Sidebar */}
      <aside className={clsx(
        "fixed left-0 top-0 bottom-0 z-50 flex flex-col bg-[#020202] border-r border-red-500/20 transition-all duration-300",
        // Desktop
        "lg:translate-x-0",
        sidebarCollapsed ? "lg:w-[72px]" : "lg:w-[260px]",
        // Mobile
        mobileMenuOpen ? "translate-x-0 w-[280px]" : "-translate-x-full w-[280px]"
      )}>
        {/* Mobile Close */}
        <button
          onClick={() => setMobileMenuOpen(false)}
          className="lg:hidden absolute top-4 right-4 w-8 h-8 flex items-center justify-center text-white/40 hover:text-white"
        >
          <X className="w-5 h-5" />
        </button>

        {/* Logo */}
        <div className={clsx(
          "h-20 flex items-center border-b border-red-500/20",
          sidebarCollapsed ? "justify-center px-2" : "px-5"
        )}>
          <NextLink href="/admin" className="flex items-center gap-3 group">
            <div className={clsx(
              "relative flex items-center justify-center",
              sidebarCollapsed ? "w-10 h-10" : "w-11 h-11"
            )}>
              <div className="absolute inset-0 bg-red-500/20 blur-xl rounded-full scale-150 opacity-50 group-hover:opacity-80 transition-opacity" />
              <div className="relative w-full h-full bg-gradient-to-br from-red-500 to-red-600 flex items-center justify-center shadow-lg shadow-red-500/20">
                <Shield className="w-5 h-5 text-white" />
              </div>
            </div>
            {!sidebarCollapsed && (
              <div>
                <span className="text-lg font-bold tracking-wide text-white">Admin</span>
                <span className="block text-[10px] text-red-400 uppercase tracking-wider font-mono">Control Panel</span>
              </div>
            )}
          </NextLink>
        </div>

        {/* Navigation */}
        <nav className="flex-1 py-6 px-3 space-y-1 overflow-y-auto">
          {!sidebarCollapsed && (
            <p className="px-3 mb-3 text-[10px] font-bold text-white/30 uppercase tracking-[0.15em] font-mono">
              Management
            </p>
          )}
          
          {TABS.map((tab) => {
            const isActive = activeTab === tab.id
            
            return (
              <button
                key={tab.id}
                onClick={() => {
                  setActiveTab(tab.id)
                  setMobileMenuOpen(false)
                }}
                className={clsx(
                  "w-full group relative flex items-center gap-3 px-3 py-3 transition-all duration-200",
                  isActive
                    ? "bg-red-500/10 text-white border-l-2 border-red-500"
                    : "text-white/50 hover:text-white hover:bg-white/[0.03] border-l-2 border-transparent"
                )}
                title={sidebarCollapsed ? tab.label : undefined}
              >
                <tab.icon className={clsx(
                  "w-5 h-5 transition-colors",
                  isActive ? "text-red-400" : "group-hover:text-white"
                )} />
                
                {!sidebarCollapsed && (
                  <span className="flex-1 text-left text-sm font-medium">{tab.label}</span>
                )}
              </button>
            )
          })}
        </nav>

        {/* Bottom Section */}
        <div className="border-t border-red-500/20 py-4 px-3 space-y-2">
          {/* Back to Dashboard */}
          <NextLink
            href="/terminal/hunt"
            className={clsx(
              "flex items-center gap-3 px-3 py-3 transition-all duration-200",
              "text-accent hover:bg-accent/10"
            )}
            title={sidebarCollapsed ? "Back to Dashboard" : undefined}
          >
            <LayoutDashboard className="w-5 h-5" />
            {!sidebarCollapsed && (
              <span className="flex-1 text-sm font-medium">User Dashboard</span>
            )}
          </NextLink>

          {/* User Info */}
          {!sidebarCollapsed && (
            <div className="p-4 bg-red-500/5 border border-red-500/20">
              <div className="flex items-center gap-3">
                <div className="w-9 h-9 bg-red-500/20 flex items-center justify-center">
                  <Shield className="w-4 h-4 text-red-400" />
                </div>
                <div className="flex-1 min-w-0">
                  <p className="text-sm font-medium text-white truncate">{user?.name || user?.email?.split('@')[0]}</p>
                  <p className="text-xs text-red-400 font-mono">Administrator</p>
                </div>
              </div>
            </div>
          )}

          {/* Logout */}
          <button
            onClick={logout}
            className={clsx(
              "w-full flex items-center gap-3 px-3 py-3 transition-all duration-200",
              "text-white/40 hover:text-white hover:bg-white/[0.03]"
            )}
            title={sidebarCollapsed ? "Sign out" : undefined}
          >
            <LogOut className="w-5 h-5" />
            {!sidebarCollapsed && <span className="text-sm font-medium">Sign out</span>}
          </button>
        </div>

        {/* Collapse Toggle (Desktop) */}
        <button
          onClick={toggleSidebar}
          className={clsx(
            "hidden lg:flex absolute -right-3 top-24 w-6 h-6 bg-[#020202] border border-red-500/20",
            "items-center justify-center text-white/40 hover:text-white hover:border-red-500/40 transition-all z-50"
          )}
        >
          {sidebarCollapsed ? <ChevronRight className="w-3.5 h-3.5" /> : <ChevronLeft className="w-3.5 h-3.5" />}
        </button>
      </aside>

      {/* Main Content */}
      <div className={clsx(
        "relative min-h-screen transition-all duration-300",
        "lg:ml-[260px]",
        sidebarCollapsed && "lg:ml-[72px]",
        "ml-0 pt-16 lg:pt-0"
      )}>
        {/* Header */}
        <header className="sticky top-0 z-30 bg-[#020202]/90 backdrop-blur-xl border-b border-white/[0.08]">
          <div className="px-4 sm:px-6 lg:px-8 py-5 flex items-center justify-between">
            <div className="ml-10 lg:ml-0">
              <div className="flex items-center gap-2 mb-1">
                <div className="w-1.5 h-1.5 bg-red-500 animate-pulse" />
                <span className="text-[10px] font-mono tracking-[0.2em] text-red-400 uppercase">Admin Panel</span>
              </div>
              <h1 className="text-xl sm:text-2xl font-bold tracking-tight text-white">
                {TABS.find(t => t.id === activeTab)?.label || 'Admin'}
              </h1>
            </div>
          </div>
        </header>

        {/* Page Content */}
        <main className="px-4 sm:px-6 lg:px-8 py-6">
          {/* Messages */}
        {error && (
            <div className="mb-6 p-4 bg-red-500/10 border border-red-500/20 flex items-center gap-3">
            <AlertCircle className="w-5 h-5 text-red-400 shrink-0" />
              <p className="text-sm text-red-400 flex-1 font-mono">{error}</p>
              <button onClick={() => setError(null)} className="text-red-400 hover:text-red-300">
                <X className="w-4 h-4" />
              </button>
            </div>
          )}

          {success && (
            <div className="mb-6 p-4 bg-accent/10 border border-accent/20 flex items-center gap-3">
              <Check className="w-5 h-5 text-accent shrink-0" />
              <p className="text-sm text-accent flex-1 font-mono">{success}</p>
              <button onClick={() => setSuccess(null)} className="text-accent hover:text-white">
                <X className="w-4 h-4" />
              </button>
            </div>
          )}

          {/* Tab Content */}
          {loading && activeTab !== 'earnings' ? (
            <div className="flex items-center justify-center py-20">
            <Loader2 className="w-6 h-6 text-red-400 animate-spin" />
            </div>
          ) : (
            <>
              {/* Overview Tab */}
              {activeTab === 'overview' && stats && (
              <div className="space-y-6">
                <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
                    <StatCard title="Total Users" value={stats.users.total} subtitle={`${stats.users.new_this_week} new this week`} icon={Users} />
                  <StatCard title="Domains" value={stats.domains.watched} subtitle={`${stats.domains.portfolio} in portfolios`} icon={Eye} />
                  <StatCard title="TLDs" value={stats.tld_data.unique_tlds} subtitle={`${stats.tld_data.price_records.toLocaleString()} prices`} icon={Globe} />
                  <StatCard title="Newsletter" value={stats.newsletter_subscribers} icon={Mail} accent />
                  </div>

                <div className="grid lg:grid-cols-3 gap-4">
                  {[
                      { tier: 'scout', icon: Zap, color: 'text-white/40', bg: 'bg-white/5', border: 'border-white/10' },
                      { tier: 'trader', icon: TrendingUp, color: 'text-accent', bg: 'bg-accent/10', border: 'border-accent/20' },
                      { tier: 'tycoon', icon: Crown, color: 'text-amber-400', bg: 'bg-amber-500/10', border: 'border-amber-500/20' },
                    ].map(({ tier, icon: Icon, color, bg, border }) => (
                      <div key={tier} className={clsx("p-6 border", bg, border)}>
                      <div className="flex items-center gap-3 mb-3">
                        <Icon className={clsx("w-5 h-5", color)} />
                          <span className="text-sm font-medium text-white/60 capitalize">{tier}</span>
                        </div>
                        <p className="text-4xl font-bold text-white font-mono">{stats.subscriptions[tier] || 0}</p>
                      </div>
                  ))}
                  </div>

                <div className="grid lg:grid-cols-2 gap-4">
                    <div className="p-6 border border-white/10 bg-white/[0.02]">
                      <h3 className="text-lg font-bold text-white mb-2">Active Auctions</h3>
                      <p className="text-4xl font-bold text-white font-mono">{stats.auctions.toLocaleString()}</p>
                    </div>
                    <div className="p-6 border border-white/10 bg-white/[0.02]">
                      <h3 className="text-lg font-bold text-white mb-2">Price Alerts</h3>
                      <p className="text-4xl font-bold text-white font-mono">{stats.price_alerts.toLocaleString()}</p>
                    </div>
                  </div>
                </div>
              )}

              {/* Earnings Tab */}
              {activeTab === 'earnings' && <EarningsTab />}

              {/* Zones Tab */}
              {activeTab === 'zones' && <ZonesTab />}

              {/* Telemetry Tab */}
              {activeTab === 'telemetry' && telemetry && (
                <div className="space-y-6">
                  <div className="flex flex-wrap items-center justify-between gap-3">
                    <div className="flex items-center gap-2">
                      <BarChart3 className="w-4 h-4 text-red-400" />
                      <span className="text-sm text-white/60 font-mono">Window</span>
                      <select
                        value={telemetryDays}
                        onChange={(e) => setTelemetryDays(Number(e.target.value))}
                        className="px-2 py-1.5 bg-white/5 border border-white/10 text-white text-xs font-mono"
                      >
                        <option value={7}>7 days</option>
                        <option value={30}>30 days</option>
                        <option value={90}>90 days</option>
                      </select>
                      <button
                        onClick={loadAdminData}
                        className="flex items-center gap-2 px-3 py-1.5 bg-white/5 border border-white/10 text-xs hover:bg-white/10"
                      >
                        <RefreshCw className="w-3 h-3" /> Refresh
                      </button>
                    </div>
                  </div>

                  <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
                    <StatCard title="Listing Views" value={telemetry.deal?.listing_views || 0} icon={Eye} />
                    <StatCard title="Inquiries" value={telemetry.deal?.inquiries_created || 0} icon={Mail} />
                    <StatCard
                      title="Reply Rate"
                      value={`${Math.round(((telemetry.deal?.inquiry_reply_rate || 0) * 100))}%`}
                      subtitle={`${telemetry.deal?.seller_replied_inquiries || 0} replied`}
                      icon={Send}
                      accent
                    />
                    <StatCard
                      title="Inquiry→Sold"
                      value={`${Math.round(((telemetry.deal?.inquiry_to_sold_listing_rate || 0) * 100))}%`}
                      subtitle={`${telemetry.deal?.listings_sold || 0} sold`}
                      icon={Tag}
                    />
                  </div>

                  <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
                    <StatCard title="Yield Connected" value={telemetry.yield?.connected_domains || 0} icon={Link} />
                    <StatCard title="Yield Clicks" value={telemetry.yield?.clicks || 0} icon={Activity} />
                    <StatCard
                      title="Yield Conv. Rate"
                      value={`${Math.round(((telemetry.yield?.conversion_rate || 0) * 100))}%`}
                      subtitle={`${telemetry.yield?.conversions || 0} conversions`}
                      icon={Target}
                      accent
                    />
                    <StatCard
                      title="Payouts Paid"
                      value={telemetry.yield?.payouts_paid || 0}
                      subtitle={`${(telemetry.yield?.payouts_paid_amount_total || 0).toFixed(2)} total`}
                      icon={Wallet}
                    />
                  </div>
                </div>
              )}

              {/* Users Tab */}
              {activeTab === 'users' && (
              <div className="space-y-6">
                  <div className="flex flex-wrap items-center gap-4">
                    <div className="relative flex-1 max-w-md">
                      <Search className="absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 text-white/30" />
                      <input
                        type="text"
                        value={searchQuery}
                        onChange={(e) => setSearchQuery(e.target.value)}
                        onKeyDown={(e) => e.key === 'Enter' && loadAdminData()}
                        placeholder="Search users..."
                        className="w-full pl-11 pr-4 py-3 bg-white/5 border border-white/10 text-white text-sm font-mono placeholder:text-white/30 focus:border-red-500/50 focus:outline-none"
                      />
                    </div>
                    <button onClick={handleExportUsers} className="flex items-center gap-2 px-5 py-3 bg-white/5 border border-white/10 text-white text-sm hover:bg-white/10">
                    <Download className="w-4 h-4" /> Export CSV
                    </button>
                  </div>

                <PremiumTable
                  data={users}
                  keyExtractor={(u) => u.id}
                  columns={[
                    {
                      key: 'user',
                      header: 'User',
                      render: (u) => (
                        <div>
                            <p className="font-medium text-white">{u.email}</p>
                            <p className="text-xs text-white/40">{u.name || 'No name'}</p>
                      </div>
                      ),
                    },
                    {
                      key: 'status',
                      header: 'Status',
                      hideOnMobile: true,
                      render: (u) => (
                        <div className="flex items-center gap-1.5 flex-wrap">
                          {u.is_admin && <Badge variant="accent" size="xs">Admin</Badge>}
                          {u.is_verified && <Badge variant="success" size="xs">Verified</Badge>}
                          {!u.is_active && <Badge variant="error" size="xs">Inactive</Badge>}
                    </div>
                      ),
                    },
                    {
                      key: 'tier',
                      header: 'Tier',
                      render: (u) => (
                        <Badge variant={u.subscription.tier === 'tycoon' ? 'warning' : u.subscription.tier === 'trader' ? 'accent' : 'default'} size="sm">
                                  {u.subscription.tier_name}
                        </Badge>
                      ),
                    },
                    {
                      key: 'domains',
                      header: 'Domains',
                      hideOnMobile: true,
                        render: (u) => <span className="text-white/60 font-mono">{u.domain_count}</span>,
                    },
                    {
                      key: 'actions',
                      header: 'Actions',
                      align: 'right',
                      render: (u) => (
                                <div className="flex items-center justify-end gap-2">
                                  <select
                                    value={u.subscription.tier}
                                    onChange={(e) => handleUpgradeUser(u.id, e.target.value)}
                              className="px-2 py-1.5 bg-white/5 border border-white/10 text-white text-xs font-mono"
                                  >
                                    <option value="scout">Scout</option>
                                    <option value="trader">Trader</option>
                                    <option value="tycoon">Tycoon</option>
                                  </select>
                          <TableActionButton icon={Shield} onClick={() => handleToggleAdmin(u.id, u.is_admin)} variant={u.is_admin ? 'accent' : 'default'} title={u.is_admin ? 'Remove admin' : 'Make admin'} />
                          <TableActionButton icon={Trash2} onClick={() => handleDeleteUser(u.id, u.email)} variant="danger" disabled={u.is_admin} title="Delete user" />
                                </div>
                      ),
                    },
                  ]}
                    emptyIcon={<Users className="w-12 h-12 text-white/10" />}
                  emptyTitle="No users found"
                />
                  <p className="text-sm text-white/40 font-mono">Showing {users.length} of {usersTotal} users</p>
                </div>
              )}

              {/* Newsletter Tab */}
              {activeTab === 'newsletter' && (
              <div className="space-y-6">
                  <div className="flex items-center justify-between">
                    <p className="text-sm text-white/60 font-mono">{newsletterTotal} subscribers</p>
                    <button
                      onClick={async () => {
                          const data = await api.exportNewsletterEmails()
                          const blob = new Blob([data.emails.join('\n')], { type: 'text/plain' })
                          const a = document.createElement('a')
                      a.href = URL.createObjectURL(blob)
                          a.download = 'newsletter-emails.txt'
                          a.click()
                      }}
                      className="px-5 py-2.5 bg-red-500 text-white font-bold uppercase tracking-wider text-sm hover:bg-red-400"
                    >
                      Export Emails
                    </button>
                  </div>
                <PremiumTable
                  data={newsletter}
                  keyExtractor={(s) => s.id}
                  columns={[
                      { key: 'email', header: 'Email', render: (s) => <span className="text-white font-mono">{s.email}</span> },
                    { key: 'status', header: 'Status', render: (s) => <Badge variant={s.is_active ? 'success' : 'error'} dot>{s.is_active ? 'Active' : 'Unsubscribed'}</Badge> },
                      { key: 'subscribed', header: 'Subscribed', render: (s) => <span className="text-white/60 font-mono text-sm">{new Date(s.subscribed_at).toLocaleDateString()}</span> },
                  ]}
                />
                </div>
              )}

              {/* System Tab */}
              {activeTab === 'system' && (
              <div className="space-y-6">
                  <div className="border border-white/10 bg-[#0a0a0a]">
                    <div className="px-6 py-4 border-b border-white/10">
                      <h3 className="text-sm font-bold text-white uppercase tracking-wider">System Status</h3>
                    </div>
                    <div className="divide-y divide-white/[0.06]">
                    {[
                      { label: 'Database', ok: systemHealth?.database === 'healthy', text: systemHealth?.database || 'Unknown' },
                      { label: 'Email (SMTP)', ok: systemHealth?.email_configured, text: systemHealth?.email_configured ? 'Configured' : 'Not configured' },
                      { label: 'Stripe', ok: systemHealth?.stripe_configured, text: systemHealth?.stripe_configured ? 'Configured' : 'Not configured' },
                      { label: 'Scheduler', ok: schedulerStatus?.scheduler_running, text: schedulerStatus?.scheduler_running ? 'Running' : 'Stopped' },
                    ].map((item) => (
                        <div key={item.label} className="px-6 py-4 flex items-center justify-between">
                          <span className="text-white/60 font-mono">{item.label}</span>
                        <span className="flex items-center gap-2">
                          {item.ok ? <CheckCircle className="w-4 h-4 text-accent" /> : <XCircle className="w-4 h-4 text-amber-400" />}
                            <span className={clsx("font-mono text-sm", item.ok ? 'text-accent' : 'text-amber-400')}>{item.text}</span>
                              </span>
                          </div>
                        ))}
                  </div>
                </div>

                <div className="grid lg:grid-cols-2 gap-6">
                    <div className="border border-white/10 bg-[#0a0a0a]">
                      <div className="px-6 py-4 border-b border-white/10">
                        <h3 className="text-sm font-bold text-white uppercase tracking-wider">Manual Triggers</h3>
                      </div>
                      <div className="p-6 space-y-3">
                        <button onClick={handleTriggerDomainChecks} disabled={domainChecking} className="w-full flex items-center justify-center gap-2 px-5 py-3 bg-red-500 text-white font-bold uppercase tracking-wider disabled:opacity-50 hover:bg-red-400">
                          {domainChecking ? <Loader2 className="w-4 h-4 animate-spin" /> : <RefreshCw className="w-4 h-4" />}
                          {domainChecking ? 'Checking...' : 'Check All Domains'}
                        </button>
                        <button onClick={handleSendTestEmail} disabled={sendingEmail} className="w-full flex items-center justify-center gap-2 px-5 py-3 bg-white/5 border border-white/10 text-white font-medium disabled:opacity-50 hover:bg-white/10">
                          {sendingEmail ? <Loader2 className="w-4 h-4 animate-spin" /> : <Send className="w-4 h-4" />}
                          {sendingEmail ? 'Sending...' : 'Send Test Email'}
                        </button>
                        <button onClick={handleCreateBackup} disabled={backingUp} className="w-full flex items-center justify-center gap-2 px-5 py-3 bg-white/5 border border-white/10 text-white font-medium disabled:opacity-50 hover:bg-white/10">
                          {backingUp ? <Loader2 className="w-4 h-4 animate-spin" /> : <Database className="w-4 h-4" />}
                          {backingUp ? 'Backing up...' : 'Create DB Backup'}
                        </button>
                        <button onClick={handleRunOpsAlerts} disabled={runningOpsAlerts} className="w-full flex items-center justify-center gap-2 px-5 py-3 bg-white/5 border border-white/10 text-white font-medium disabled:opacity-50 hover:bg-white/10">
                          {runningOpsAlerts ? <Loader2 className="w-4 h-4 animate-spin" /> : <Bell className="w-4 h-4" />}
                          {runningOpsAlerts ? 'Running...' : 'Run Ops Alerts'}
                        </button>
                        <button onClick={handleTriggerScrape} disabled={scraping} className="w-full flex items-center justify-center gap-2 px-5 py-3 bg-white/5 border border-white/10 text-white font-medium disabled:opacity-50 hover:bg-white/10">
                        {scraping ? <Loader2 className="w-4 h-4 animate-spin" /> : <Globe className="w-4 h-4" />}
                        {scraping ? 'Scraping...' : 'Scrape TLD Prices'}
                      </button>
                        <button onClick={handleTriggerAuctionScrape} disabled={auctionScraping} className="w-full flex items-center justify-center gap-2 px-5 py-3 bg-white/5 border border-white/10 text-white font-medium disabled:opacity-50 hover:bg-white/10">
                        {auctionScraping ? <Loader2 className="w-4 h-4 animate-spin" /> : <Gavel className="w-4 h-4" />}
                        {auctionScraping ? 'Scraping...' : 'Scrape Auctions'}
                      </button>
                        </div>
                        </div>

                    <div className="border border-white/10 bg-[#0a0a0a]">
                      <div className="px-6 py-4 border-b border-white/10">
                        <h3 className="text-sm font-bold text-white uppercase tracking-wider">Recent Backups</h3>
                      </div>
                      <div className="p-6">
                        {!backups?.length ? (
                          <p className="text-sm text-white/40 font-mono">No backups found.</p>
                        ) : (
                          <div className="space-y-2">
                            {backups.slice(0, 5).map((b: any) => (
                              <div key={b.path} className="flex items-center justify-between p-3 bg-white/[0.02] border border-white/[0.06]">
                                <div className="min-w-0">
                                  <p className="text-sm text-white font-mono truncate">{b.name}</p>
                                  <p className="text-xs text-white/40 font-mono">{new Date(b.modified_at).toLocaleString()}</p>
                    </div>
                                <div className="text-xs text-white/40 font-mono">
                                  {Math.round((b.size_bytes || 0) / 1024 / 1024)} MB
                    </div>
                  </div>
                            ))}
                </div>
              )}
                        </div>
                  </div>
                      </div>
                    </div>
                  )}

              {/* TLD Tab */}
              {activeTab === 'tld' && stats && (
              <div className="space-y-6">
                <div className="grid sm:grid-cols-2 lg:grid-cols-4 gap-4">
                    <StatCard title="Unique TLDs" value={stats.tld_data?.unique_tlds || 0} icon={Globe} />
                    <StatCard title="Price Records" value={stats.tld_data?.price_records?.toLocaleString() || '0'} icon={Database} accent />
                    <StatCard title="Active Alerts" value={stats.price_alerts || 0} icon={Bell} />
                    <StatCard title="Renewal Traps" value="~40%" subtitle="Have >2x renewal" icon={AlertCircle} />
                  </div>

                  <div className="border border-white/10 bg-[#0a0a0a] p-6">
                    <h3 className="text-sm font-bold text-white uppercase tracking-wider mb-4">TLD Price Management</h3>
                  <div className="flex flex-wrap gap-3">
                                  <button
                      onClick={handleTriggerScrape} 
                      disabled={scraping}
                        className="flex items-center gap-2 px-5 py-3 bg-red-500 text-white font-bold uppercase tracking-wider disabled:opacity-50 hover:bg-red-400"
                    >
                      {scraping ? <Loader2 className="w-4 h-4 animate-spin" /> : <Globe className="w-4 h-4" />}
                      {scraping ? 'Scraping...' : 'Scrape All Registrars'}
                                  </button>
                                </div>
                    </div>
                    </div>
              )}

              {/* Auctions Tab */}
              {activeTab === 'auctions' && stats && (
                <div className="space-y-6">
                  <div className="grid sm:grid-cols-2 lg:grid-cols-4 gap-4">
                    <StatCard title="Total Auctions" value={stats.auctions?.toLocaleString() || '0'} icon={Gavel} />
                    <StatCard title="Platforms" value="4" subtitle="GoDaddy, Sedo, NameJet, DropCatch" icon={Globe} accent />
                    <StatCard title="Clean Domains" value={Math.round((stats.auctions || 0) * 0.4).toLocaleString()} subtitle="~40% pass filter" icon={CheckCircle} />
            </div>

                  <div className="border border-white/10 bg-[#0a0a0a] p-6">
                    <h3 className="text-sm font-bold text-white uppercase tracking-wider mb-4">Auction Management</h3>
                    <button
                      onClick={handleTriggerAuctionScrape}
                      disabled={auctionScraping}
                      className="flex items-center gap-2 px-5 py-3 bg-red-500 text-white font-bold uppercase tracking-wider disabled:opacity-50 hover:bg-red-400"
                    >
                      {auctionScraping ? <Loader2 className="w-4 h-4 animate-spin" /> : <Gavel className="w-4 h-4" />}
                      {auctionScraping ? 'Scraping...' : 'Scrape All Platforms'}
                    </button>
          </div>
        </div>
      )}

              {/* Activity Tab */}
              {activeTab === 'activity' && (
                <PremiumTable
                  data={activityLog}
                  keyExtractor={(l) => l.id}
                  emptyIcon={<History className="w-12 h-12 text-white/10" />}
                  emptyTitle="No activity logged"
                  columns={[
                    { key: 'action', header: 'Action', render: (l) => <Badge>{l.action}</Badge> },
                    { key: 'details', header: 'Details', render: (l) => <span className="text-white/60 font-mono text-sm">{l.details}</span> },
                    { key: 'admin', header: 'Admin', render: (l) => <span className="text-white/60 font-mono text-sm">{l.admin.email}</span> },
                    { key: 'time', header: 'Time', hideOnMobile: true, render: (l) => <span className="text-white/40 font-mono text-sm">{new Date(l.created_at).toLocaleString()}</span> },
                  ]}
                />
      )}
          </>
        )}
        </main>
      </div>
    </div>
  )
}
