'use client';

import { useState, useEffect, useCallback } from 'react';
import {
  Lock, Users, CreditCard, BarChart3, TrendingUp, Brain,
  Search, ChevronDown, ChevronUp, ArrowLeft, RefreshCw,
  AlertTriangle, Loader2, Send, Eye, Download,
} from 'lucide-react';

// ── Types ──────────────────────────────────────────────────────────────────

interface Overview {
  users: { total_users: string; paid_users: string; new_last_7d: string; new_last_30d: string };
  generations: { total_generations: string; total_credits_consumed: string; gens_last_7d: string; gens_last_30d: string; unique_users_generated: string };
  payments: { total_topups: string; total_revenue_usd: string; total_credits_sold: string; revenue_last_30d: string };
  nfc: { total_nfc_orders: string; pending_nfc: string };
  trend: { day: string; count: string }[];
  typeBreakdown: { type: string; count: string }[];
}

interface User {
  id: string; email: string; name: string | null; plan: string;
  credits: number; gen_count: number; credits_consumed: number;
  total_spent_usd: string; created_at: string; last_generation: string | null;
}

interface Payment {
  id: string; email: string; name: string | null; credits: number;
  amount_usd: string; payment_ref: string; status: string; created_at: string; plan: string;
}

// ── Constants ──────────────────────────────────────────────────────────────

const API = '/api/super-admin';
const TOKEN_KEY = 'super_admin_token';

function getToken() { return typeof window !== 'undefined' ? sessionStorage.getItem(TOKEN_KEY) : null; }
function setToken(t: string) { sessionStorage.setItem(TOKEN_KEY, t); }
function clearToken() { sessionStorage.removeItem(TOKEN_KEY); }

function authHeaders() { return { 'x-super-admin-token': getToken() || '', 'Content-Type': 'application/json' }; }

function fmt(n: string | number, decimals = 0) {
  const num = typeof n === 'string' ? parseFloat(n) : n;
  if (isNaN(num)) return '0';
  return num.toFixed(decimals).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}

function fmtDate(iso: string | null) {
  if (!iso) return '—';
  return new Date(iso).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' });
}

// ── Login Gate ─────────────────────────────────────────────────────────────

function LoginGate({ onAuth }: { onAuth: () => void }) {
  const [password, setPassword] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');

  async function handleLogin(e: React.FormEvent) {
    e.preventDefault();
    setLoading(true); setError('');
    try {
      const r = await fetch(`${API}/auth`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ password }) });
      const d = await r.json();
      if (!r.ok) { setError(d.error || 'Invalid password'); return; }
      setToken(d.token);
      onAuth();
    } catch { setError('Network error'); }
    finally { setLoading(false); }
  }

  return (
    <div className="flex items-center justify-center min-h-[60vh]">
      <div className="w-full max-w-sm">
        <div className="bg-slate-800/60 border border-slate-700/50 rounded-2xl p-8 space-y-6">
          <div className="text-center">
            <div className="w-12 h-12 bg-amber-500/20 rounded-full flex items-center justify-center mx-auto mb-3">
              <Lock className="w-5 h-5 text-amber-400" />
            </div>
            <h2 className="text-lg font-bold text-white">Super Admin Access</h2>
            <p className="text-sm text-slate-400 mt-1">Platform-wide user & usage management</p>
          </div>
          <form onSubmit={handleLogin} className="space-y-4">
            <input
              type="password"
              value={password}
              onChange={e => setPassword(e.target.value)}
              placeholder="Admin password"
              className="w-full bg-slate-900/60 border border-slate-700/50 rounded-xl px-4 py-3 text-sm text-white placeholder-slate-500 focus:outline-none focus:border-amber-500/50"
              autoFocus
            />
            {error && <p className="text-red-400 text-xs">{error}</p>}
            <button
              type="submit"
              disabled={loading || !password}
              className="w-full py-3 bg-amber-600 hover:bg-amber-500 disabled:opacity-40 text-white rounded-xl text-sm font-semibold transition-colors flex items-center justify-center gap-2"
            >
              {loading ? <Loader2 className="w-4 h-4 animate-spin" /> : <Lock className="w-4 h-4" />}
              Authenticate
            </button>
          </form>
        </div>
      </div>
    </div>
  );
}

// ── Overview Tab ───────────────────────────────────────────────────────────

function OverviewTab() {
  const [data, setData] = useState<Overview | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');

  const load = useCallback(async () => {
    setLoading(true); setError('');
    try {
      const r = await fetch(`${API}/overview`, { headers: authHeaders() });
      if (!r.ok) throw new Error((await r.json()).error);
      setData(await r.json());
    } catch (e: unknown) { setError(e instanceof Error ? e.message : 'Failed to load'); }
    finally { setLoading(false); }
  }, []);

  useEffect(() => { load(); }, [load]);

  if (loading) return <div className="flex items-center justify-center h-48"><Loader2 className="w-6 h-6 animate-spin text-slate-400" /></div>;
  if (error) return <div className="text-red-400 text-sm p-4">{error}</div>;
  if (!data) return null;

  const maxTrend = Math.max(...data.trend.map(t => parseInt(t.count)), 1);

  return (
    <div className="space-y-6">
      {/* KPI Cards */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
        {[
          { label: 'Total Users', value: fmt(data.users.total_users), sub: `${fmt(data.users.paid_users)} paid`, color: 'text-blue-400', bg: 'bg-blue-500/10 border-blue-500/20' },
          { label: 'Total Generations', value: fmt(data.generations.total_generations), sub: `${fmt(data.generations.gens_last_7d)} this week`, color: 'text-purple-400', bg: 'bg-purple-500/10 border-purple-500/20' },
          { label: 'Total Revenue', value: `$${fmt(data.payments.total_revenue_usd, 2)}`, sub: `$${fmt(data.payments.revenue_last_30d, 2)} last 30d`, color: 'text-emerald-400', bg: 'bg-emerald-500/10 border-emerald-500/20' },
          { label: 'Credits Consumed', value: fmt(data.generations.total_credits_consumed), sub: `${fmt(data.payments.total_credits_sold)} sold`, color: 'text-amber-400', bg: 'bg-amber-500/10 border-amber-500/20' },
        ].map(c => (
          <div key={c.label} className={`${c.bg} border rounded-xl p-4`}>
            <p className="text-xs text-slate-400">{c.label}</p>
            <p className={`text-2xl font-bold ${c.color} mt-1`}>{c.value}</p>
            <p className="text-xs text-slate-500 mt-0.5">{c.sub}</p>
          </div>
        ))}
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
        {/* Generation Trend */}
        <div className="bg-slate-800/60 border border-slate-700/50 rounded-xl p-5">
          <h3 className="text-sm font-semibold text-white mb-4">Daily Generation Trend (14 days)</h3>
          {data.trend.length === 0 ? (
            <p className="text-slate-500 text-sm">No data yet</p>
          ) : (
            <div className="flex items-end gap-1 h-32">
              {data.trend.map(t => (
                <div key={t.day} className="flex-1 flex flex-col items-center gap-1 group relative">
                  <div
                    className="w-full bg-purple-500/60 hover:bg-purple-400/80 rounded-sm transition-colors"
                    style={{ height: `${(parseInt(t.count) / maxTrend) * 100}%`, minHeight: '2px' }}
                  />
                  <div className="absolute -top-6 left-1/2 -translate-x-1/2 bg-slate-700 text-white text-[10px] px-1.5 py-0.5 rounded opacity-0 group-hover:opacity-100 transition-opacity whitespace-nowrap">
                    {t.count} gens
                  </div>
                </div>
              ))}
            </div>
          )}
          <div className="flex justify-between text-[10px] text-slate-500 mt-2">
            <span>{data.trend[0]?.day?.slice(5) || ''}</span>
            <span>{data.trend[data.trend.length - 1]?.day?.slice(5) || ''}</span>
          </div>
        </div>

        {/* Type Breakdown + NFC */}
        <div className="space-y-4">
          <div className="bg-slate-800/60 border border-slate-700/50 rounded-xl p-5">
            <h3 className="text-sm font-semibold text-white mb-3">Generation Types</h3>
            <div className="space-y-2">
              {data.typeBreakdown.map(t => {
                const total = data.typeBreakdown.reduce((s, x) => s + parseInt(x.count), 0);
                const pct = total ? Math.round(parseInt(t.count) / total * 100) : 0;
                return (
                  <div key={t.type}>
                    <div className="flex justify-between text-xs text-slate-400 mb-1">
                      <span className="capitalize">{t.type}</span>
                      <span>{fmt(t.count)} ({pct}%)</span>
                    </div>
                    <div className="h-1.5 bg-slate-700 rounded-full">
                      <div className="h-full bg-blue-500/70 rounded-full" style={{ width: `${pct}%` }} />
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
          <div className="grid grid-cols-2 gap-3">
            <div className="bg-slate-800/60 border border-slate-700/50 rounded-xl p-4">
              <p className="text-xs text-slate-400">New Users (7d)</p>
              <p className="text-xl font-bold text-white mt-1">{fmt(data.users.new_last_7d)}</p>
            </div>
            <div className="bg-slate-800/60 border border-slate-700/50 rounded-xl p-4">
              <p className="text-xs text-slate-400">NFC Orders</p>
              <p className="text-xl font-bold text-white mt-1">{fmt(data.nfc.total_nfc_orders)}</p>
              <p className="text-xs text-slate-500">{data.nfc.pending_nfc} pending</p>
            </div>
          </div>
        </div>
      </div>

      <button onClick={load} className="flex items-center gap-1.5 text-xs text-slate-400 hover:text-white transition-colors">
        <RefreshCw className="w-3 h-3" /> Refresh
      </button>
    </div>
  );
}

// ── Users Tab ──────────────────────────────────────────────────────────────

function UsersTab() {
  const [users, setUsers] = useState<User[]>([]);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState('');
  const [plan, setPlan] = useState('');
  const [sort, setSort] = useState('created_at');
  const [order, setOrder] = useState<'asc' | 'desc'>('desc');
  const [offset, setOffset] = useState(0);
  const [selectedUser, setSelectedUser] = useState<string | null>(null);
  const LIMIT = 20;

  const load = useCallback(async () => {
    setLoading(true);
    try {
      const q = new URLSearchParams({ search, plan, sort, order, limit: String(LIMIT), offset: String(offset) });
      const r = await fetch(`${API}/users?${q}`, { headers: authHeaders() });
      const d = await r.json();
      setUsers(d.users || []);
      setTotal(d.total || 0);
    } catch { /* ignore */ }
    finally { setLoading(false); }
  }, [search, plan, sort, order, offset]);

  useEffect(() => { load(); }, [load]);

  function toggleSort(col: string) {
    if (sort === col) setOrder(o => o === 'asc' ? 'desc' : 'asc');
    else { setSort(col); setOrder('desc'); }
    setOffset(0);
  }

  function SortIcon({ col }: { col: string }) {
    if (sort !== col) return null;
    return order === 'asc' ? <ChevronUp className="w-3 h-3" /> : <ChevronDown className="w-3 h-3" />;
  }

  const planColors: Record<string, string> = {
    free: 'bg-slate-700/60 text-slate-300',
    starter: 'bg-blue-500/20 text-blue-300',
    popular: 'bg-purple-500/20 text-purple-300',
    business: 'bg-amber-500/20 text-amber-300',
    enterprise: 'bg-emerald-500/20 text-emerald-300',
  };

  if (selectedUser) return <UserDetailPanel userId={selectedUser} onBack={() => setSelectedUser(null)} />;

  return (
    <div className="space-y-4">
      {/* Filters */}
      <div className="flex flex-wrap gap-3">
        <div className="relative flex-1 min-w-48">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-slate-400" />
          <input
            value={search}
            onChange={e => { setSearch(e.target.value); setOffset(0); }}
            placeholder="Search email or name..."
            className="w-full bg-slate-800/60 border border-slate-700/50 rounded-xl pl-9 pr-4 py-2 text-sm text-white placeholder-slate-500 focus:outline-none focus:border-purple-500/50"
          />
        </div>
        <select
          value={plan}
          onChange={e => { setPlan(e.target.value); setOffset(0); }}
          className="bg-slate-800/60 border border-slate-700/50 rounded-xl px-3 py-2 text-sm text-white focus:outline-none"
        >
          <option value="">All plans</option>
          <option value="free">Free</option>
          <option value="starter">Starter</option>
          <option value="popular">Popular</option>
          <option value="business">Business</option>
          <option value="enterprise">Enterprise</option>
        </select>
        <button onClick={load} className="px-3 py-2 bg-slate-800/60 border border-slate-700/50 rounded-xl text-slate-400 hover:text-white transition-colors">
          <RefreshCw className="w-3.5 h-3.5" />
        </button>
      </div>

      {/* Table */}
      <div className="bg-slate-800/60 border border-slate-700/50 rounded-xl overflow-hidden">
        <div className="overflow-x-auto">
          <table className="w-full text-sm">
            <thead>
              <tr className="border-b border-slate-700/50">
                {[
                  { label: 'User', col: 'email' },
                  { label: 'Plan', col: 'plan' },
                  { label: 'Credits', col: 'credits' },
                  { label: 'Generations', col: 'gen_count' },
                  { label: 'Spent', col: null },
                  { label: 'Joined', col: 'created_at' },
                  { label: '', col: null },
                ].map(h => (
                  <th
                    key={h.label}
                    onClick={() => h.col && toggleSort(h.col)}
                    className={`text-left px-4 py-3 text-xs font-medium text-slate-400 ${h.col ? 'cursor-pointer hover:text-white' : ''}`}
                  >
                    <span className="flex items-center gap-1">{h.label}{h.col && <SortIcon col={h.col} />}</span>
                  </th>
                ))}
              </tr>
            </thead>
            <tbody>
              {loading ? (
                <tr><td colSpan={7} className="text-center py-8 text-slate-500"><Loader2 className="w-5 h-5 animate-spin mx-auto" /></td></tr>
              ) : users.length === 0 ? (
                <tr><td colSpan={7} className="text-center py-8 text-slate-500">No users found</td></tr>
              ) : users.map(u => (
                <tr key={u.id} className="border-b border-slate-700/30 hover:bg-white/[0.02] transition-colors">
                  <td className="px-4 py-3">
                    <div className="font-medium text-white">{u.email}</div>
                    {u.name && <div className="text-xs text-slate-400">{u.name}</div>}
                  </td>
                  <td className="px-4 py-3">
                    <span className={`text-xs px-2 py-0.5 rounded-full font-medium ${planColors[u.plan] || planColors.free}`}>
                      {u.plan}
                    </span>
                  </td>
                  <td className="px-4 py-3 text-white">{fmt(u.credits)}</td>
                  <td className="px-4 py-3">
                    <div className="text-white">{fmt(u.gen_count)}</div>
                    <div className="text-xs text-slate-500">{fmt(u.credits_consumed)} credits</div>
                  </td>
                  <td className="px-4 py-3 text-emerald-400">{u.total_spent_usd > '0' ? `$${fmt(u.total_spent_usd, 2)}` : '—'}</td>
                  <td className="px-4 py-3 text-slate-400 text-xs">{fmtDate(u.created_at)}</td>
                  <td className="px-4 py-3">
                    <button
                      onClick={() => setSelectedUser(u.id)}
                      className="p-1.5 rounded-lg text-slate-400 hover:text-white hover:bg-white/[0.05] transition-colors"
                    >
                      <Eye className="w-3.5 h-3.5" />
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
        {/* Pagination */}
        <div className="px-4 py-3 border-t border-slate-700/30 flex items-center justify-between text-xs text-slate-400">
          <span>{total} total users</span>
          <div className="flex gap-2">
            <button disabled={offset === 0} onClick={() => setOffset(Math.max(0, offset - LIMIT))} className="px-3 py-1 rounded-lg border border-slate-700/50 disabled:opacity-40 hover:text-white transition-colors">Prev</button>
            <span className="px-2 py-1">{Math.floor(offset / LIMIT) + 1} / {Math.ceil(total / LIMIT) || 1}</span>
            <button disabled={offset + LIMIT >= total} onClick={() => setOffset(offset + LIMIT)} className="px-3 py-1 rounded-lg border border-slate-700/50 disabled:opacity-40 hover:text-white transition-colors">Next</button>
          </div>
        </div>
      </div>
    </div>
  );
}

// ── User Detail Panel ──────────────────────────────────────────────────────

function UserDetailPanel({ userId, onBack }: { userId: string; onBack: () => void }) {
  const [data, setData] = useState<{
    user: User & { free_gens_today: number; free_reset_date: string; updated_at: string };
    usage: { id: string; type: string; content: string; credits_used: number; created_at: string }[];
    payments: { id: string; credits: number; amount_usd: string; payment_ref: string; status: string; created_at: string }[];
    stats: { typeBreakdown: { type: string; count: number; credits: number }[]; dailyUsage: { day: string; count: number }[] };
  } | null>(null);
  const [loading, setLoading] = useState(true);
  const [subTab, setSubTab] = useState<'overview' | 'usage' | 'payments'>('overview');

  useEffect(() => {
    (async () => {
      setLoading(true);
      try {
        const r = await fetch(`${API}/users/${userId}`, { headers: authHeaders() });
        setData(await r.json());
      } catch { /* ignore */ }
      finally { setLoading(false); }
    })();
  }, [userId]);

  if (loading) return <div className="flex items-center justify-center h-48"><Loader2 className="w-6 h-6 animate-spin text-slate-400" /></div>;
  if (!data) return <div className="text-red-400 text-sm">Failed to load user</div>;

  const { user, usage, payments, stats } = data;
  const maxDaily = Math.max(...stats.dailyUsage.map(d => d.count), 1);

  return (
    <div className="space-y-4">
      <button onClick={onBack} className="flex items-center gap-1.5 text-sm text-slate-400 hover:text-white transition-colors">
        <ArrowLeft className="w-4 h-4" /> Back to users
      </button>

      {/* User header */}
      <div className="bg-slate-800/60 border border-slate-700/50 rounded-xl p-5">
        <div className="flex items-start justify-between flex-wrap gap-3">
          <div>
            <h3 className="text-lg font-bold text-white">{user.email}</h3>
            {user.name && <p className="text-slate-400 text-sm">{user.name}</p>}
          </div>
          <span className={`text-sm px-3 py-1 rounded-full font-semibold ${user.plan === 'free' ? 'bg-slate-700 text-slate-300' : 'bg-amber-500/20 text-amber-300'}`}>
            {user.plan}
          </span>
        </div>
        <div className="grid grid-cols-2 sm:grid-cols-4 gap-4 mt-4">
          {[
            { label: 'Credits Remaining', value: fmt(user.credits), color: 'text-blue-400' },
            { label: 'Total Generations', value: fmt(user.gen_count), color: 'text-purple-400' },
            { label: 'Total Spent', value: user.total_spent_usd > '0' ? `$${fmt(user.total_spent_usd, 2)}` : '$0', color: 'text-emerald-400' },
            { label: 'Member Since', value: fmtDate(user.created_at), color: 'text-slate-300' },
          ].map(s => (
            <div key={s.label}>
              <p className="text-xs text-slate-500">{s.label}</p>
              <p className={`text-base font-semibold ${s.color} mt-0.5`}>{s.value}</p>
            </div>
          ))}
        </div>
      </div>

      {/* Sub-tabs */}
      <div className="flex gap-1 border-b border-slate-700/50">
        {(['overview', 'usage', 'payments'] as const).map(t => (
          <button
            key={t}
            onClick={() => setSubTab(t)}
            className={`px-4 py-2 text-sm font-medium capitalize border-b-2 transition-colors ${subTab === t ? 'border-amber-500 text-amber-400' : 'border-transparent text-slate-400 hover:text-white'}`}
          >
            {t}
          </button>
        ))}
      </div>

      {subTab === 'overview' && (
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          {/* Daily usage chart */}
          <div className="bg-slate-800/60 border border-slate-700/50 rounded-xl p-4">
            <h4 className="text-xs font-semibold text-slate-400 mb-3">Daily Activity (30d)</h4>
            {stats.dailyUsage.length === 0 ? <p className="text-slate-500 text-xs">No activity</p> : (
              <div className="flex items-end gap-0.5 h-20">
                {stats.dailyUsage.map(d => (
                  <div key={d.day} className="flex-1" style={{ height: `${(d.count / maxDaily) * 100}%`, minHeight: '2px', background: 'rgba(168,85,247,0.6)', borderRadius: '2px' }} title={`${d.day}: ${d.count}`} />
                ))}
              </div>
            )}
          </div>
          {/* Type breakdown */}
          <div className="bg-slate-800/60 border border-slate-700/50 rounded-xl p-4">
            <h4 className="text-xs font-semibold text-slate-400 mb-3">Usage by Type</h4>
            <div className="space-y-2">
              {stats.typeBreakdown.map(t => (
                <div key={t.type} className="flex justify-between text-xs">
                  <span className="text-slate-300 capitalize">{t.type}</span>
                  <span className="text-slate-400">{t.count} gens · {t.credits} credits</span>
                </div>
              ))}
              {stats.typeBreakdown.length === 0 && <p className="text-slate-500 text-xs">No data</p>}
            </div>
          </div>
        </div>
      )}

      {subTab === 'usage' && (
        <div className="bg-slate-800/60 border border-slate-700/50 rounded-xl overflow-hidden">
          <div className="overflow-x-auto">
            <table className="w-full text-xs">
              <thead><tr className="border-b border-slate-700/50">
                <th className="text-left px-4 py-2.5 text-slate-400 font-medium">Type</th>
                <th className="text-left px-4 py-2.5 text-slate-400 font-medium">Content</th>
                <th className="text-left px-4 py-2.5 text-slate-400 font-medium">Credits</th>
                <th className="text-left px-4 py-2.5 text-slate-400 font-medium">Date</th>
              </tr></thead>
              <tbody>
                {usage.map(g => (
                  <tr key={g.id} className="border-b border-slate-700/20 hover:bg-white/[0.02]">
                    <td className="px-4 py-2.5 capitalize text-slate-300">{g.type}</td>
                    <td className="px-4 py-2.5 text-slate-400 max-w-xs truncate">{g.content}</td>
                    <td className="px-4 py-2.5 text-slate-300">{g.credits_used}</td>
                    <td className="px-4 py-2.5 text-slate-400">{fmtDate(g.created_at)}</td>
                  </tr>
                ))}
                {usage.length === 0 && <tr><td colSpan={4} className="text-center py-6 text-slate-500">No usage history</td></tr>}
              </tbody>
            </table>
          </div>
        </div>
      )}

      {subTab === 'payments' && (
        <div className="space-y-2">
          {payments.length === 0 && <p className="text-slate-500 text-sm">No payments on record</p>}
          {payments.map(p => (
            <div key={p.id} className="bg-slate-800/60 border border-slate-700/50 rounded-xl px-4 py-3 flex items-center justify-between">
              <div>
                <p className="text-sm text-white font-medium">{p.credits} credits for <span className="text-emerald-400">${fmt(p.amount_usd, 2)}</span></p>
                <p className="text-xs text-slate-500 mt-0.5">Ref: {p.payment_ref} · {fmtDate(p.created_at)}</p>
              </div>
              <span className={`text-xs px-2 py-0.5 rounded-full ${p.status === 'completed' ? 'bg-emerald-500/20 text-emerald-300' : 'bg-amber-500/20 text-amber-300'}`}>
                {p.status}
              </span>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

// ── Payments Tab ───────────────────────────────────────────────────────────

function PaymentsTab() {
  const [payments, setPayments] = useState<Payment[]>([]);
  const [total, setTotal] = useState(0);
  const [totalRevenue, setTotalRevenue] = useState('0');
  const [loading, setLoading] = useState(true);
  const [offset, setOffset] = useState(0);
  const LIMIT = 25;

  const load = useCallback(async () => {
    setLoading(true);
    try {
      const r = await fetch(`${API}/payments?limit=${LIMIT}&offset=${offset}`, { headers: authHeaders() });
      const d = await r.json();
      setPayments(d.payments || []);
      setTotal(d.total || 0);
      setTotalRevenue(d.totalRevenue || '0');
    } catch { /* ignore */ }
    finally { setLoading(false); }
  }, [offset]);

  useEffect(() => { load(); }, [load]);

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <div>
          <p className="text-sm text-slate-400">Total Revenue</p>
          <p className="text-2xl font-bold text-emerald-400">${fmt(totalRevenue, 2)}</p>
        </div>
        <button onClick={load} className="p-2 rounded-xl bg-slate-800/60 border border-slate-700/50 text-slate-400 hover:text-white transition-colors">
          <RefreshCw className="w-4 h-4" />
        </button>
      </div>

      <div className="bg-slate-800/60 border border-slate-700/50 rounded-xl overflow-hidden">
        <div className="overflow-x-auto">
          <table className="w-full text-sm">
            <thead><tr className="border-b border-slate-700/50">
              {['User', 'Plan', 'Credits', 'Amount', 'Ref', 'Status', 'Date'].map(h => (
                <th key={h} className="text-left px-4 py-3 text-xs font-medium text-slate-400">{h}</th>
              ))}
            </tr></thead>
            <tbody>
              {loading ? (
                <tr><td colSpan={7} className="text-center py-8"><Loader2 className="w-5 h-5 animate-spin mx-auto text-slate-400" /></td></tr>
              ) : payments.map(p => (
                <tr key={p.id} className="border-b border-slate-700/20 hover:bg-white/[0.02]">
                  <td className="px-4 py-3">
                    <div className="text-white">{p.email}</div>
                    {p.name && <div className="text-xs text-slate-500">{p.name}</div>}
                  </td>
                  <td className="px-4 py-3 text-slate-400 text-xs">{p.plan}</td>
                  <td className="px-4 py-3 text-white">{fmt(p.credits)}</td>
                  <td className="px-4 py-3 text-emerald-400 font-medium">${fmt(p.amount_usd, 2)}</td>
                  <td className="px-4 py-3 text-slate-500 text-xs font-mono">{p.payment_ref}</td>
                  <td className="px-4 py-3">
                    <span className={`text-xs px-2 py-0.5 rounded-full ${p.status === 'completed' ? 'bg-emerald-500/20 text-emerald-300' : 'bg-amber-500/20 text-amber-300'}`}>
                      {p.status}
                    </span>
                  </td>
                  <td className="px-4 py-3 text-slate-400 text-xs">{fmtDate(p.created_at)}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
        <div className="px-4 py-3 border-t border-slate-700/30 flex items-center justify-between text-xs text-slate-400">
          <span>{total} transactions</span>
          <div className="flex gap-2">
            <button disabled={offset === 0} onClick={() => setOffset(Math.max(0, offset - LIMIT))} className="px-3 py-1 rounded-lg border border-slate-700/50 disabled:opacity-40 hover:text-white">Prev</button>
            <span className="px-2 py-1">{Math.floor(offset / LIMIT) + 1} / {Math.ceil(total / LIMIT) || 1}</span>
            <button disabled={offset + LIMIT >= total} onClick={() => setOffset(offset + LIMIT)} className="px-3 py-1 rounded-lg border border-slate-700/50 disabled:opacity-40 hover:text-white">Next</button>
          </div>
        </div>
      </div>
    </div>
  );
}

// ── AI Insights Tab ────────────────────────────────────────────────────────

const AI_PROMPTS = [
  'Who are the top 5 highest-value users and what makes them high-value?',
  'What usage patterns suggest churn risk?',
  'Which user segments should we target for upsell?',
  'What features drive the most credit consumption?',
  'Summarize platform health and recommend 3 growth actions',
  'Are there any anomalies or suspicious usage patterns?',
];

function AIInsightsTab() {
  const [question, setQuestion] = useState('');
  const [answer, setAnswer] = useState('');
  const [snapshot, setSnapshot] = useState<Record<string, unknown> | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');

  async function ask(q?: string) {
    const query = q || question;
    if (!query.trim()) return;
    setLoading(true); setAnswer(''); setError('');
    try {
      const r = await fetch(`${API}/ai-insights`, {
        method: 'POST',
        headers: authHeaders(),
        body: JSON.stringify({ question: query }),
      });
      const d = await r.json();
      if (!r.ok) throw new Error(d.error);
      setAnswer(d.answer);
      setSnapshot(d.dataSnapshot);
      if (q) setQuestion(q);
    } catch (e: unknown) { setError(e instanceof Error ? e.message : 'Failed'); }
    finally { setLoading(false); }
  }

  return (
    <div className="space-y-5">
      <div className="bg-amber-500/10 border border-amber-500/20 rounded-xl p-4 flex gap-3">
        <Brain className="w-4 h-4 text-amber-400 shrink-0 mt-0.5" />
        <div className="text-xs text-amber-200/80">
          AI analyzes live platform data and provides actionable business insights using DeepSeek Reasoner. Data is fetched fresh for each query.
        </div>
      </div>

      {/* Suggestion chips */}
      <div>
        <p className="text-xs text-slate-400 mb-2">Quick insights</p>
        <div className="flex flex-wrap gap-2">
          {AI_PROMPTS.map(p => (
            <button
              key={p}
              onClick={() => ask(p)}
              disabled={loading}
              className="text-xs px-3 py-1.5 rounded-full border border-slate-700/50 bg-slate-800/60 text-slate-400 hover:text-white hover:border-amber-500/40 transition-colors disabled:opacity-40"
            >
              {p}
            </button>
          ))}
        </div>
      </div>

      {/* Custom question */}
      <div className="flex gap-3">
        <input
          value={question}
          onChange={e => setQuestion(e.target.value)}
          onKeyDown={e => e.key === 'Enter' && ask()}
          placeholder="Ask anything about your users, usage, or revenue..."
          className="flex-1 bg-slate-800/60 border border-slate-700/50 rounded-xl px-4 py-2.5 text-sm text-white placeholder-slate-500 focus:outline-none focus:border-amber-500/50"
        />
        <button
          onClick={() => ask()}
          disabled={loading || !question.trim()}
          className="px-4 py-2.5 bg-amber-600 hover:bg-amber-500 disabled:opacity-40 text-white rounded-xl text-sm font-medium transition-colors flex items-center gap-1.5"
        >
          {loading ? <Loader2 className="w-4 h-4 animate-spin" /> : <Send className="w-4 h-4" />}
        </button>
      </div>

      {error && (
        <div className="flex items-center gap-2 text-red-400 text-sm">
          <AlertTriangle className="w-4 h-4" /> {error}
        </div>
      )}

      {answer && (
        <div className="bg-slate-800/60 border border-slate-700/50 rounded-xl p-5 space-y-3">
          <div className="flex items-center gap-2 text-xs text-slate-400">
            <Brain className="w-3.5 h-3.5 text-amber-400" />
            AI Analysis
            {snapshot && <span className="ml-auto">Data as of {new Date((snapshot as {generatedAt?: string}).generatedAt || '').toLocaleTimeString()}</span>}
          </div>
          <div className="text-sm text-slate-200 leading-relaxed whitespace-pre-wrap">{answer}</div>
        </div>
      )}
    </div>
  );
}

// ── Main Component ─────────────────────────────────────────────────────────

export default function SuperAdminDashboard() {
  const [authed, setAuthed] = useState(false);
  const [activeTab, setActiveTab] = useState<'overview' | 'users' | 'payments' | 'ai'>('overview');

  useEffect(() => {
    if (getToken()) setAuthed(true);
  }, []);

  function logout() { clearToken(); setAuthed(false); }

  if (!authed) return <LoginGate onAuth={() => setAuthed(true)} />;

  const tabs = [
    { id: 'overview' as const, label: 'Overview', icon: BarChart3 },
    { id: 'users' as const, label: 'Users', icon: Users },
    { id: 'payments' as const, label: 'Payments', icon: CreditCard },
    { id: 'ai' as const, label: 'AI Insights', icon: Brain },
  ];

  return (
    <div className="space-y-5">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-lg font-bold text-white flex items-center gap-2">
            <Lock className="w-4 h-4 text-amber-400" />
            Super Admin
          </h2>
          <p className="text-xs text-slate-400 mt-0.5">Platform-wide accounts, usage & revenue</p>
        </div>
        <button onClick={logout} className="text-xs text-slate-400 hover:text-white px-3 py-1.5 rounded-lg border border-slate-700/50 hover:border-slate-500 transition-colors">
          Sign out
        </button>
      </div>

      {/* Sub-tabs */}
      <div className="flex gap-1 border-b border-slate-700/50">
        {tabs.map(t => {
          const Icon = t.icon;
          return (
            <button
              key={t.id}
              onClick={() => setActiveTab(t.id)}
              className={`flex items-center gap-1.5 px-4 py-2.5 text-sm font-medium border-b-2 transition-colors ${activeTab === t.id ? 'border-amber-500 text-amber-400' : 'border-transparent text-slate-400 hover:text-white hover:border-slate-600'}`}
            >
              <Icon className="w-3.5 h-3.5" />
              {t.label}
            </button>
          );
        })}
      </div>

      {/* Content */}
      <div>
        {activeTab === 'overview' && <OverviewTab />}
        {activeTab === 'users' && <UsersTab />}
        {activeTab === 'payments' && <PaymentsTab />}
        {activeTab === 'ai' && <AIInsightsTab />}
      </div>
    </div>
  );
}
