'use client'

import { useEffect, useState } from 'react'
import { AdminLayout } from '@/components/AdminLayout'
import { PremiumTable, Badge, TableActionButton, StatCard, PageContainer } from '@/components/PremiumTable'
import { api } from '@/lib/api'
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,
} from 'lucide-react'
import clsx from 'clsx'

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

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 }
}

export default function AdminPage() {
  const [activeTab, setActiveTab] = useState<TabType>('overview')
  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)
  // Selection removed - PremiumTable doesn't support it
  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[]>([])
  const [backingUp, setBackingUp] = useState(false)
  const [runningOpsAlerts, setRunningOpsAlerts] = useState(false)
  const [opsAlertsHistory, setOpsAlertsHistory] = useState<any[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [success, setSuccess] = useState<string | null>(null)
  const [searchQuery, setSearchQuery] = useState('')
  const [scraping, setScraping] = useState(false)
  const [auctionScraping, setAuctionScraping] = useState(false)
  const [domainChecking, setDomainChecking] = useState(false)
  const [sendingEmail, setSendingEmail] = useState(false)
  const [bulkTier, setBulkTier] = useState('trader')

  useEffect(() => {
      loadAdminData()
  }, [activeTab])

  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)
    }
  }

  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')
    }
  }

    return (
    <AdminLayout
      title={activeTab === 'overview' ? 'Overview' : 
             activeTab === 'telemetry' ? 'Telemetry' :
             activeTab === 'users' ? 'User Management' :
             activeTab === 'alerts' ? 'Price Alerts' :
             activeTab === 'newsletter' ? 'Newsletter' :
             activeTab === 'tld' ? 'TLD Pricing' :
             activeTab === 'auctions' ? 'Auctions' :
             activeTab === 'blog' ? 'Blog Management' :
             activeTab === 'system' ? 'System Status' :
             'Activity Log'}
      subtitle="Admin Control Panel"
      activeTab={activeTab}
      onTabChange={(tab) => setActiveTab(tab as TabType)}
    >
      <PageContainer>
          {/* Messages */}
        {error && (
          <div className="p-4 bg-red-500/10 border border-red-500/20 rounded-xl 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">{error}</p>
            <button onClick={() => setError(null)} className="text-red-400"><X className="w-4 h-4" /></button>
            </div>
          )}

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

          {loading ? (
            <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-foreground-muted' },
                    { tier: 'trader', icon: TrendingUp, color: 'text-accent' },
                    { tier: 'tycoon', icon: Crown, color: 'text-amber-400' },
                  ].map(({ tier, icon: Icon, color }) => (
                    <div key={tier} className="p-6 bg-gradient-to-br from-background-secondary/50 to-background-secondary/20 border border-border/30 rounded-2xl">
                      <div className="flex items-center gap-3 mb-3">
                        <Icon className={clsx("w-5 h-5", color)} />
                        <span className="text-sm font-medium text-foreground-muted capitalize">{tier}</span>
                        </div>
                      <p className="text-3xl font-display text-foreground">{stats.subscriptions[tier] || 0}</p>
                      </div>
                  ))}
                  </div>

                <div className="grid lg:grid-cols-2 gap-4">
                  <div className="p-6 bg-gradient-to-br from-background-secondary/50 to-background-secondary/20 border border-border/30 rounded-2xl">
                    <h3 className="text-lg font-medium text-foreground mb-2">Active Auctions</h3>
                    <p className="text-4xl font-display text-foreground">{stats.auctions.toLocaleString()}</p>
                    </div>
                  <div className="p-6 bg-gradient-to-br from-background-secondary/50 to-background-secondary/20 border border-border/30 rounded-2xl">
                    <h3 className="text-lg font-medium text-foreground mb-2">Price Alerts</h3>
                    <p className="text-4xl font-display text-foreground">{stats.price_alerts.toLocaleString()}</p>
                    </div>
                  </div>
                </div>
              )}

              {/* 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-accent" />
                      <span className="text-sm text-foreground-muted">Window</span>
                      <select
                        value={telemetryDays}
                        onChange={(e) => setTelemetryDays(Number(e.target.value))}
                        className="px-2 py-1.5 bg-background-secondary border border-border/30 rounded-lg text-xs"
                      >
                        <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-foreground/10 border border-border/30 rounded-lg text-xs hover:bg-foreground/5"
                      >
                        <RefreshCw className="w-3 h-3" /> Refresh
                      </button>
                    </div>
                    <div className="text-xs text-foreground-subtle font-mono">
                      {telemetry.window?.start ? new Date(telemetry.window.start).toLocaleDateString() : '—'} →{' '}
                      {telemetry.window?.end ? new Date(telemetry.window.end).toLocaleDateString() : '—'}
                    </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>

                  {referrals ? (
                    <div className="space-y-4">
                      <div className="flex items-center justify-between gap-3">
                        <div>
                          <p className="text-xs text-foreground-subtle font-mono uppercase tracking-wider mb-1">Viral Loop</p>
                          <p className="text-lg font-medium text-foreground">Referrals</p>
                        </div>
                        <div className="text-xs text-foreground-subtle font-mono">
                          {referrals.window?.start ? new Date(referrals.window.start).toLocaleDateString() : '—'} →{' '}
                          {referrals.window?.end ? new Date(referrals.window.end).toLocaleDateString() : '—'}
                        </div>
                      </div>

                      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
                        <StatCard title="Invite users" value={referrals.totals?.referrers_with_invite_code || 0} icon={Users} />
                        <StatCard title="Link views" value={referrals.totals?.referral_link_views_window || 0} icon={Eye} />
                        <StatCard title="Referred signups" value={referrals.totals?.referred_users_window || 0} icon={TrendingUp} accent />
                        <StatCard title="All-time referred" value={referrals.totals?.referred_users_total || 0} icon={Activity} />
                      </div>

                      <PremiumTable
                        data={referrals.referrers || []}
                        keyExtractor={(r: any) => r.user_id}
                        compact
                        columns={[
                          {
                            key: 'email',
                            header: 'Referrer',
                            render: (r: any) => (
                              <div className="space-y-0.5">
                                <div className="font-medium text-foreground truncate">{r.email}</div>
                                <div className="text-[11px] text-foreground-subtle font-mono truncate">{r.invite_code || '—'}</div>
                              </div>
                            ),
                          },
                          {
                            key: 'referred_users_window',
                            header: `Signups (${telemetryDays}d)`,
                            align: 'right',
                            render: (r: any) => <span className="font-mono text-sm text-foreground">{r.referred_users_window || 0}</span>,
                          },
                          {
                            key: 'referred_users_total',
                            header: 'All-time',
                            align: 'right',
                            render: (r: any) => <span className="font-mono text-sm text-foreground">{r.referred_users_total || 0}</span>,
                          },
                          {
                            key: 'referral_link_views_window',
                            header: 'Link views',
                            align: 'right',
                            hideOnMobile: true,
                            render: (r: any) => (
                              <span className="font-mono text-sm text-foreground">{r.referral_link_views_window || 0}</span>
                            ),
                          },
                        ]}
                        emptyTitle="No referral data"
                        emptyDescription="Invite codes exist, but no signups were attributed in this window."
                      />
                    </div>
                  ) : null}

                  <div className="p-6 bg-gradient-to-br from-background-secondary/50 to-background-secondary/20 border border-border/30 rounded-2xl">
                    <h3 className="text-lg font-medium text-foreground mb-4">Latency (Median)</h3>
                    <div className="grid sm:grid-cols-2 gap-4">
                      <div className="p-4 bg-background/50 rounded-xl border border-border/20">
                        <p className="text-xs text-foreground-subtle font-mono uppercase tracking-wider mb-1">Inquiry → Seller Reply</p>
                        <p className="text-2xl font-display text-foreground">
                          {telemetry.deal?.median_reply_seconds ? `${Math.round(telemetry.deal.median_reply_seconds / 60)}m` : '—'}
                        </p>
                      </div>
                      <div className="p-4 bg-background/50 rounded-xl border border-border/20">
                        <p className="text-xs text-foreground-subtle font-mono uppercase tracking-wider mb-1">Inquiry → Sold</p>
                        <p className="text-2xl font-display text-foreground">
                          {telemetry.deal?.median_time_to_sold_seconds ? `${Math.round(telemetry.deal.median_time_to_sold_seconds / 3600)}h` : '—'}
                        </p>
                      </div>
                    </div>
                  </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-foreground-subtle" />
                      <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-background-secondary/50 border border-border/30 rounded-xl text-sm"
                      />
                    </div>
                  <button onClick={handleExportUsers} className="flex items-center gap-2 px-5 py-3 bg-background-secondary/50 border border-border/30 rounded-xl text-sm hover:bg-foreground/5">
                    <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-foreground">{u.email}</p>
                          <p className="text-xs text-foreground-subtle">{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-foreground-muted">{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-background-secondary border border-border/30 rounded-lg text-xs"
                                  >
                                    <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-foreground-subtle" />}
                  emptyTitle="No users found"
                />
                <p className="text-sm text-foreground-subtle">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-foreground-muted">{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 rounded-xl text-sm font-medium hover:bg-red-600"
                    >
                      Export Emails
                    </button>
                  </div>
                <PremiumTable
                  data={newsletter}
                  keyExtractor={(s) => s.id}
                  columns={[
                    { key: 'email', header: 'Email', render: (s) => <span className="text-foreground">{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) => new Date(s.subscribed_at).toLocaleDateString() },
                  ]}
                />
                </div>
              )}

              {/* System Tab */}
              {activeTab === 'system' && (
              <div className="space-y-6">
                <div className="p-6 bg-gradient-to-br from-background-secondary/50 to-background-secondary/20 border border-border/30 rounded-2xl">
                    <h3 className="text-lg font-medium text-foreground mb-4">System Status</h3>
                  <div className="space-y-4">
                    {[
                      { 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="flex items-center justify-between py-3 border-b border-border/30 last:border-0">
                        <span className="text-foreground-muted">{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={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="p-6 bg-gradient-to-br from-background-secondary/50 to-background-secondary/20 border border-border/30 rounded-2xl">
                      <h3 className="text-lg font-medium text-foreground mb-4">Manual Triggers</h3>
                      <div className="space-y-3">
                      <button onClick={handleTriggerDomainChecks} disabled={domainChecking} className="w-full flex items-center justify-center gap-2 px-5 py-3 bg-foreground text-background rounded-xl font-medium disabled:opacity-50">
                          {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-foreground/10 border border-border/30 rounded-xl font-medium disabled:opacity-50">
                          {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-foreground/10 border border-border/30 rounded-xl font-medium disabled:opacity-50">
                        {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-foreground/10 border border-border/30 rounded-xl font-medium disabled:opacity-50">
                        {runningOpsAlerts ? <Loader2 className="w-4 h-4 animate-spin" /> : <Bell className="w-4 h-4" />}
                        {runningOpsAlerts ? 'Running...' : 'Run Ops Alerts Now'}
                      </button>
                      <button onClick={handleTriggerScrape} disabled={scraping} className="w-full flex items-center justify-center gap-2 px-5 py-3 bg-foreground/10 border border-border/30 rounded-xl font-medium disabled:opacity-50">
                        {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-foreground/10 border border-border/30 rounded-xl font-medium disabled:opacity-50">
                        {auctionScraping ? <Loader2 className="w-4 h-4 animate-spin" /> : <Gavel className="w-4 h-4" />}
                        {auctionScraping ? 'Scraping...' : 'Scrape Auctions'}
                      </button>
                        </div>
                        </div>

                  <div className="p-6 bg-gradient-to-br from-background-secondary/50 to-background-secondary/20 border border-border/30 rounded-2xl">
                    <h3 className="text-lg font-medium text-foreground mb-4">Backups</h3>
                    {!backups?.length ? (
                      <p className="text-sm text-foreground-subtle">No backups found.</p>
                    ) : (
                      <div className="space-y-2">
                        {backups.slice(0, 6).map((b: any) => (
                          <div key={b.path} className="flex items-center justify-between p-3 bg-background/50 rounded-xl border border-border/20">
                            <div className="min-w-0">
                              <p className="text-sm text-foreground font-mono truncate">{b.name}</p>
                              <p className="text-xs text-foreground-subtle">{new Date(b.modified_at).toLocaleString()}</p>
                            </div>
                            <div className="text-xs text-foreground-subtle font-mono">
                              {Math.round((b.size_bytes || 0) / 1024 / 1024)} MB
                            </div>
                          </div>
                        ))}
                      </div>
                    )}
                    <p className="text-[11px] text-foreground-subtle mt-3">
                      Backups run daily if enabled on server. Manual backup requires ENABLE_DB_BACKUPS=true.
                    </p>
                  </div>

                  <div className="p-6 bg-gradient-to-br from-background-secondary/50 to-background-secondary/20 border border-border/30 rounded-2xl">
                    <h3 className="text-lg font-medium text-foreground mb-4">Ops Alerts History</h3>
                    {!opsAlertsHistory?.length ? (
                      <p className="text-sm text-foreground-subtle">No ops alert events yet.</p>
                    ) : (
                      <div className="space-y-2">
                        {opsAlertsHistory.slice(0, 8).map((e: any) => (
                          <div key={e.id} className="p-3 bg-background/50 rounded-xl border border-border/20">
                            <div className="flex items-center justify-between gap-3">
                              <div className="min-w-0">
                                <p className="text-sm text-foreground truncate">{e.title}</p>
                                <p className="text-xs text-foreground-subtle font-mono truncate">
                                  {e.alert_key} · {e.status}{e.send_reason ? ` (${e.send_reason})` : ''}
                                </p>
                              </div>
                              <div className="text-xs text-foreground-subtle">
                                {new Date(e.created_at).toLocaleString()}
                              </div>
                            </div>
                            {e.detail ? (
                              <p className="mt-2 text-[11px] text-foreground-subtle font-mono break-words">{e.detail}</p>
                            ) : null}
                          </div>
                        ))}
                      </div>
                    )}
                    <p className="text-[11px] text-foreground-subtle mt-3">
                      Enable OPS_ALERTS_ENABLED=true and set OPS_ALERT_RECIPIENTS for email delivery.
                    </p>
                  </div>

                  {schedulerStatus && (
                    <div className="p-6 bg-gradient-to-br from-background-secondary/50 to-background-secondary/20 border border-border/30 rounded-2xl">
                      <h3 className="text-lg font-medium text-foreground mb-4">Scheduled Jobs</h3>
                      <div className="space-y-3">
                        {schedulerStatus.jobs?.slice(0, 5).map((job: any) => (
                          <div key={job.id} className="flex items-center justify-between text-sm">
                            <span className="text-foreground truncate">{job.name}</span>
                            <span className="text-foreground-subtle text-xs">{job.trigger}</span>
                      </div>
                        ))}
                    </div>
                    </div>
                        )}
                  </div>
                </div>
              )}

              {/* Auctions Tab */}
              {activeTab === 'auctions' && (
              <div className="space-y-6">
                {/* Auction Stats */}
                <div className="grid sm:grid-cols-2 lg:grid-cols-4 gap-4">
                  <div className="p-5 bg-gradient-to-br from-background-secondary/50 to-background-secondary/20 border border-border/30 rounded-2xl">
                    <p className="text-sm text-foreground-muted mb-1">Total Auctions</p>
                    <p className="text-3xl font-display text-foreground">{stats?.auctions.toLocaleString() || 0}</p>
                        </div>
                  <div className="p-5 bg-gradient-to-br from-accent/10 to-accent/5 border border-accent/20 rounded-2xl">
                    <p className="text-sm text-foreground-muted mb-1">Platforms</p>
                    <p className="text-3xl font-display text-accent">4</p>
                    <p className="text-xs text-foreground-subtle mt-1">GoDaddy, Sedo, NameJet, DropCatch</p>
                  </div>
                  <div className="p-5 bg-gradient-to-br from-background-secondary/50 to-background-secondary/20 border border-border/30 rounded-2xl">
                    <p className="text-sm text-foreground-muted mb-1">Clean Domains</p>
                    <p className="text-3xl font-display text-foreground">
                      {stats?.auctions ? Math.round(stats.auctions * 0.4).toLocaleString() : 0}
                    </p>
                    <p className="text-xs text-foreground-subtle mt-1">~40% pass vanity filter</p>
                  </div>
                  <div className="p-5 bg-gradient-to-br from-background-secondary/50 to-background-secondary/20 border border-border/30 rounded-2xl">
                    <p className="text-sm text-foreground-muted mb-1">Last Scraped</p>
                    <p className="text-xl font-medium text-foreground">
                      {schedulerStatus?.jobs?.find((j: any) => j.name.includes('auction'))?.next_run_time 
                        ? 'Recently' 
                        : 'Unknown'}
                    </p>
                      </div>
                    </div>

                {/* Auction Scraping Actions */}
                <div className="p-6 bg-gradient-to-br from-background-secondary/50 to-background-secondary/20 border border-border/30 rounded-2xl">
                  <h3 className="text-lg font-medium text-foreground mb-4">Auction Management</h3>
                  <div className="flex flex-wrap gap-3">
                      <button
                        onClick={handleTriggerAuctionScrape}
                        disabled={auctionScraping}
                      className="flex items-center gap-2 px-5 py-3 bg-foreground text-background rounded-xl font-medium disabled:opacity-50"
                      >
                      {auctionScraping ? <Loader2 className="w-4 h-4 animate-spin" /> : <Gavel className="w-4 h-4" />}
                      {auctionScraping ? 'Scraping...' : 'Scrape All Platforms'}
                    </button>
                    <button className="flex items-center gap-2 px-5 py-3 bg-foreground/10 border border-border/30 rounded-xl font-medium">
                      <Download className="w-4 h-4" />
                      Export Auctions
                      </button>
                    </div>
                  </div>

                {/* Platform Status */}
                <div className="p-6 bg-gradient-to-br from-background-secondary/50 to-background-secondary/20 border border-border/30 rounded-2xl">
                  <h3 className="text-lg font-medium text-foreground mb-4">Platform Status</h3>
                  <div className="grid sm:grid-cols-2 lg:grid-cols-4 gap-4">
                      {['GoDaddy', 'Sedo', 'NameJet', 'DropCatch'].map((platform) => (
                      <div key={platform} className="flex items-center justify-between p-4 bg-background/50 rounded-xl border border-border/20">
                        <div className="flex items-center gap-3">
                          <div className="w-8 h-8 rounded-lg bg-accent/10 flex items-center justify-center">
                            <Gavel className="w-4 h-4 text-accent" />
                          </div>
                          <span className="font-medium text-foreground">{platform}</span>
                        </div>
                        <div className="flex items-center gap-2">
                          <span className="w-2 h-2 rounded-full bg-accent animate-pulse" />
                          <span className="text-xs text-accent">Active</span>
                    </div>
                  </div>
                    ))}
                    </div>
                  </div>

                {/* Vanity Filter Info */}
                <div className="p-6 bg-gradient-to-br from-amber-500/10 to-amber-500/5 border border-amber-500/20 rounded-2xl">
                  <h3 className="text-lg font-medium text-foreground mb-2">Vanity Filter (Public Page)</h3>
                  <p className="text-sm text-foreground-muted mb-4">
                    Non-authenticated users only see &quot;clean&quot; domains that pass these rules:
                  </p>
                  <div className="grid sm:grid-cols-2 lg:grid-cols-4 gap-4">
                    {[
                      { rule: 'No Hyphens', desc: 'domain-name.com ❌' },
                      { rule: 'No Numbers', desc: 'domain123.com ❌ (unless ≤4 chars)' },
                      { rule: 'Max 12 Chars', desc: 'verylongdomainname.com ❌' },
                      { rule: 'Premium TLDs', desc: '.com .io .ai .co .net .org .app .dev .ch .de ✅' },
                    ].map((item) => (
                      <div key={item.rule} className="p-3 bg-background/50 rounded-lg">
                        <p className="font-medium text-foreground text-sm">{item.rule}</p>
                        <p className="text-xs text-foreground-subtle mt-1">{item.desc}</p>
                          </div>
                        ))}
                      </div>
                      </div>
                    </div>
                  )}

            {/* Alerts Tab */}
            {activeTab === 'alerts' && (
              <PremiumTable
                data={priceAlerts}
                keyExtractor={(a) => a.id}
                emptyIcon={<Bell className="w-12 h-12 text-foreground-subtle" />}
                emptyTitle="No active price alerts"
                columns={[
                  { key: 'tld', header: 'TLD', render: (a) => <span className="font-mono text-accent">.{a.tld}</span> },
                  { key: 'target', header: 'Target', render: (a) => a.target_price ? `$${a.target_price.toFixed(2)}` : '—' },
                  { key: 'type', header: 'Type', render: (a) => <Badge>{a.alert_type}</Badge> },
                  { key: 'user', header: 'User', render: (a) => a.user.email },
                  { key: 'created', header: 'Created', hideOnMobile: true, render: (a) => new Date(a.created_at).toLocaleDateString() },
                ]}
              />
                  )}

              {activeTab === 'activity' && (
              <PremiumTable
                data={activityLog}
                keyExtractor={(l) => l.id}
                emptyIcon={<History className="w-12 h-12 text-foreground-subtle" />}
                emptyTitle="No activity logged"
                columns={[
                  { key: 'action', header: 'Action', render: (l) => <Badge>{l.action}</Badge> },
                  { key: 'details', header: 'Details', render: (l) => <span className="text-foreground-muted">{l.details}</span> },
                  { key: 'admin', header: 'Admin', render: (l) => l.admin.email },
                  { key: 'time', header: 'Time', hideOnMobile: true, render: (l) => new Date(l.created_at).toLocaleString() },
                ]}
              />
            )}

            {/* TLD Pricing Tab */}
            {activeTab === 'tld' && (
              <div className="space-y-6">
                {/* TLD Stats */}
                <div className="grid sm:grid-cols-2 lg:grid-cols-4 gap-4">
                  <div className="p-5 bg-gradient-to-br from-background-secondary/50 to-background-secondary/20 border border-border/30 rounded-2xl">
                    <p className="text-sm text-foreground-muted mb-1">Unique TLDs</p>
                    <p className="text-3xl font-display text-foreground">{stats?.tld_data?.unique_tlds?.toLocaleString() || 0}</p>
                      </div>
                  <div className="p-5 bg-gradient-to-br from-accent/10 to-accent/5 border border-accent/20 rounded-2xl">
                    <p className="text-sm text-foreground-muted mb-1">Price Records</p>
                    <p className="text-3xl font-display text-accent">{stats?.tld_data?.price_records?.toLocaleString() || 0}</p>
                    </div>
                  <div className="p-5 bg-gradient-to-br from-background-secondary/50 to-background-secondary/20 border border-border/30 rounded-2xl">
                    <p className="text-sm text-foreground-muted mb-1">Active Price Alerts</p>
                    <p className="text-3xl font-display text-foreground">{stats?.price_alerts || 0}</p>
                  </div>
                  <div className="p-5 bg-gradient-to-br from-amber-500/10 to-amber-500/5 border border-amber-500/20 rounded-2xl">
                    <p className="text-sm text-foreground-muted mb-1">Renewal Traps</p>
                    <p className="text-3xl font-display text-amber-400">~40%</p>
                    <p className="text-xs text-foreground-subtle mt-1">Have &gt;2x renewal</p>
                </div>
                  </div>

                {/* TLD Scraping Actions */}
                <div className="p-6 bg-gradient-to-br from-background-secondary/50 to-background-secondary/20 border border-border/30 rounded-2xl">
                  <h3 className="text-lg font-medium text-foreground 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-foreground text-background rounded-xl font-medium disabled:opacity-50"
                    >
                      {scraping ? <Loader2 className="w-4 h-4 animate-spin" /> : <Globe className="w-4 h-4" />}
                      {scraping ? 'Scraping...' : 'Scrape All Registrars'}
                                  </button>
                    <button className="flex items-center gap-2 px-5 py-3 bg-foreground/10 border border-border/30 rounded-xl font-medium">
                      <Download className="w-4 h-4" />
                      Export Price Data
                                  </button>
                                </div>
                    </div>

                {/* New Features from analysis_4.md */}
                <div className="p-6 bg-gradient-to-br from-accent/10 to-accent/5 border border-accent/20 rounded-2xl">
                  <h3 className="text-lg font-medium text-foreground mb-2">New TLD Pricing Features</h3>
                  <p className="text-sm text-foreground-muted mb-4">
                    Implemented from analysis_4.md &quot;Inflation Monitor&quot; concept:
                  </p>
                  <div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-4">
                    {[
                      { feature: 'Renewal Trap Detection', status: '✅', desc: 'Warns when renewal &gt;2x registration' },
                      { feature: '1y/3y Trend Tracking', status: '✅', desc: 'Shows price changes over time' },
                      { feature: 'Risk Level Badges', status: '✅', desc: 'Low, Medium, High indicators' },
                      { feature: 'Category Tabs', status: '✅', desc: 'Tech, Geo, Budget, Premium' },
                      { feature: 'Sparkline Charts', status: '✅', desc: 'Visual trend indicators' },
                      { feature: 'Blur for Free Users', status: '✅', desc: 'First 5 rows visible' },
                    ].map((item) => (
                      <div key={item.feature} className="p-3 bg-background/50 rounded-lg">
                        <div className="flex items-center gap-2 mb-1">
                          <span>{item.status}</span>
                          <span className="font-medium text-foreground text-sm">{item.feature}</span>
                    </div>
                        <p className="text-xs text-foreground-subtle">{item.desc}</p>
                      </div>
                    ))}
                    </div>
                </div>

                {/* Data Sources */}
                <div className="p-6 bg-gradient-to-br from-background-secondary/50 to-background-secondary/20 border border-border/30 rounded-2xl">
                  <h3 className="text-lg font-medium text-foreground mb-4">Data Sources</h3>
                  <div className="grid sm:grid-cols-2 lg:grid-cols-4 gap-4">
                    {['Cloudflare', 'Namecheap', 'Porkbun', 'GoDaddy', 'Google Domains', 'Dynadot'].map((registrar) => (
                      <div key={registrar} className="flex items-center justify-between p-4 bg-background/50 rounded-xl border border-border/20">
                        <div className="flex items-center gap-3">
                          <div className="w-8 h-8 rounded-lg bg-accent/10 flex items-center justify-center">
                            <Globe className="w-4 h-4 text-accent" />
            </div>
                          <span className="font-medium text-foreground">{registrar}</span>
              </div>
                        <div className="flex items-center gap-2">
                          <span className="w-2 h-2 rounded-full bg-accent animate-pulse" />
                          <span className="text-xs text-accent">Active</span>
              </div>
                  </div>
                    ))}
                </div>
          </div>
        </div>
      )}

            {activeTab === 'blog' && (
              <div className="space-y-6">
                <div className="flex items-center justify-between">
                  <p className="text-sm text-foreground-muted">{blogPostsTotal} posts</p>
                  <button className="flex items-center gap-2 px-5 py-2.5 bg-red-500 text-white rounded-xl text-sm font-medium">
                    <Plus className="w-4 h-4" /> New Post
              </button>
            </div>
                <PremiumTable
                  data={blogPosts}
                  keyExtractor={(p) => p.id}
                  emptyIcon={<BookOpen className="w-12 h-12 text-foreground-subtle" />}
                  emptyTitle="No blog posts"
                  columns={[
                    { key: 'title', header: 'Title', render: (p) => <div><p className="font-medium text-foreground">{p.title}</p><p className="text-xs text-foreground-subtle">{p.slug}</p></div> },
                    { key: 'category', header: 'Category', hideOnMobile: true, render: (p) => p.category ? <Badge>{p.category}</Badge> : '—' },
                    { key: 'status', header: 'Status', render: (p) => <Badge variant={p.is_published ? 'success' : 'warning'}>{p.is_published ? 'Published' : 'Draft'}</Badge> },
                    { key: 'views', header: 'Views', hideOnMobile: true, render: (p) => p.view_count },
                    { key: 'actions', header: '', align: 'right', render: (p) => (
                      <div className="flex items-center justify-end gap-2">
                        <TableActionButton icon={ExternalLink} onClick={() => window.open(`/blog/${p.slug}`, '_blank')} />
                        <TableActionButton icon={Edit2} />
                        <TableActionButton icon={Trash2} variant="danger" />
              </div>
                    ) },
                  ]}
                />
        </div>
      )}
          </>
        )}
      </PageContainer>
    </AdminLayout>
  )
}
