// Admin Panel — gerenciamento de usuários, créditos, bans.

const { useState, useEffect, useCallback, useRef } = React;

// ── Admin Route — verifica cookie real no servidor a cada montagem ────────
function AdminRoute({ navigate }) {
  const [checked, setChecked] = useState(false);
  const [isAdmin, setIsAdmin] = useState(false);

  useEffect(() => {
    window.DB.checkAdmin().then(ok => {
      setIsAdmin(!!ok);
      setChecked(true);
    });
  }, []);

  if (!checked) return (
    <div style={{ minHeight: '100dvh', background: 'var(--bg)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
      <div style={{ color: 'var(--ink-3)', fontSize: 14 }}>Verificando acesso...</div>
    </div>
  );

  if (!isAdmin) return (
    <AdminLoginGate onSuccess={() => setIsAdmin(true)} />
  );

  return <AdminPanel navigate={navigate} />;
}


function AdminLoginGate({ onSuccess }) {
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(false);

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!username.trim() || !password) return;
    setLoading(true);
    setError('');
    try {
      await window.DB.adminLogin(username.trim(), password);
      onSuccess();
    } catch (err) {
      setError(err.message || 'Credenciais inválidas.');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div style={{
      minHeight: '100dvh', background: 'var(--bg)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      padding: 24,
    }}>
      <div style={{
        background: 'var(--paper)', border: '1px solid var(--line)',
        borderRadius: 20, padding: '40px 36px', width: '100%', maxWidth: 400,
        boxShadow: 'var(--shadow-lg)',
      }}>
        <div style={{
          width: 48, height: 48, borderRadius: 12, marginBottom: 20,
          background: 'linear-gradient(135deg, var(--accent), #8B5A3C)',
          boxShadow: '0 8px 20px -8px rgba(201,100,66,.45)',
        }}/>
        <h1 className="serif" style={{ fontSize: 28, margin: '0 0 6px', letterSpacing: '-0.01em' }}>Aftershot Admin</h1>
        <p style={{ fontSize: 14, color: 'var(--ink-3)', margin: '0 0 28px' }}>Acesso restrito — apenas administradores.</p>

        {error && (
          <div style={{
            marginBottom: 16, padding: '10px 14px', borderRadius: 10,
            background: '#FDECE7', border: '1px solid #E8B7A5',
            color: '#7A2E18', fontSize: 13,
          }}>{error}</div>
        )}

        <form onSubmit={handleSubmit}>
          <div style={{ marginBottom: 14 }}>
            <div style={{ fontSize: 12, fontWeight: 600, color: 'var(--ink-3)', marginBottom: 6, textTransform: 'uppercase', letterSpacing: '.05em' }}>Usuário</div>
            <input
              autoFocus
              value={username}
              onChange={e => setUsername(e.target.value)}
              placeholder="darlidonizete"
              style={{
                width: '100%', fontSize: 15, padding: '11px 14px',
                borderRadius: 8, border: '1px solid var(--line-2)',
                background: 'var(--paper)', color: 'var(--ink)', outline: 'none',
              }}
            />
          </div>
          <div style={{ marginBottom: 24 }}>
            <div style={{ fontSize: 12, fontWeight: 600, color: 'var(--ink-3)', marginBottom: 6, textTransform: 'uppercase', letterSpacing: '.05em' }}>Senha</div>
            <input
              type="password"
              value={password}
              onChange={e => setPassword(e.target.value)}
              placeholder="••••••••"
              style={{
                width: '100%', fontSize: 15, padding: '11px 14px',
                borderRadius: 8, border: '1px solid var(--line-2)',
                background: 'var(--paper)', color: 'var(--ink)', outline: 'none',
              }}
            />
          </div>
          <button
            type="submit"
            disabled={loading || !username || !password}
            style={{
              width: '100%', padding: '13px 0', borderRadius: 12,
              background: 'var(--accent)', color: '#fff',
              fontSize: 15, fontWeight: 600, cursor: 'pointer',
              opacity: loading ? .6 : 1, transition: 'opacity .15s',
              border: 'none',
            }}
          >
            {loading ? 'Entrando...' : 'Entrar no painel'}
          </button>
        </form>
      </div>
    </div>
  );
}

// ── API helpers ─────────────────────────────────────────────────────────
async function adminFetch(path, opts = {}) {
  const res = await fetch(path, {
    ...opts,
    credentials: 'include',
    headers: opts.body ? { 'Content-Type': 'application/json' } : {},
    body: opts.body ? JSON.stringify(opts.body) : undefined,
  });
  const json = await res.json();
  if (!res.ok) throw new Error(json.error || `HTTP ${res.status}`);
  return json;
}

// ── Stat Card ───────────────────────────────────────────────────────────
function StatCard({ label, value, icon, color }) {
  return (
    <div style={adminS.statCard}>
      <div style={{ ...adminS.statIcon, background: color || 'var(--accent-soft)', color: 'var(--accent-deep)' }}>
        {icon}
      </div>
      <div>
        <div style={{ fontSize: 11, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: '.06em', marginBottom: 2 }}>{label}</div>
        <div className="serif" style={{ fontSize: 28, lineHeight: 1.1 }}>{value}</div>
      </div>
    </div>
  );
}

// ── User Row ────────────────────────────────────────────────────────────
function UserRow({ user, onSelect }) {
  const available = Math.max(0, (user.creditsTotal || 0) - (user.creditsUsed || 0));
  const pct = user.creditsTotal ? Math.min(100, (user.creditsUsed / user.creditsTotal) * 100) : 0;
  return (
    <tr style={{ cursor: 'pointer', transition: 'background .12s' }}
        onClick={() => onSelect(user)}
        onMouseEnter={e => e.currentTarget.style.background = 'var(--bg-deep)'}
        onMouseLeave={e => e.currentTarget.style.background = ''}>
      <td style={adminS.td}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <div style={adminS.miniAvatar}>{(user.name || 'U').slice(0, 2).toUpperCase()}</div>
          <div>
            <div style={{ fontWeight: 600, fontSize: 14 }}>{user.name}</div>
            <div style={{ fontSize: 12, color: 'var(--ink-3)' }}>{user.email}</div>
          </div>
        </div>
      </td>
      <td style={adminS.td}>
        <Pill tone={user.planName === 'Gratuito' ? 'default' : 'accent'}>{user.planName || 'Gratuito'}</Pill>
      </td>
      <td style={adminS.td}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <div style={{ width: 48, height: 4, background: 'var(--line)', borderRadius: 2, overflow: 'hidden' }}>
            <div style={{ width: `${pct}%`, height: '100%', background: 'var(--accent)' }} />
          </div>
          <span className="mono" style={{ fontSize: 12, color: 'var(--ink-3)' }}>{available}/{user.creditsTotal || 0}</span>
        </div>
      </td>
      <td style={adminS.td}>
        {user.banned
          ? <Pill tone="ink">Banido</Pill>
          : <span style={{ fontSize: 12, color: 'var(--olive)', fontWeight: 500 }}>Ativo</span>}
      </td>
      <td style={{ ...adminS.td, fontSize: 12, color: 'var(--ink-4)' }}>
        {user.createdAt ? new Date(Number(user.createdAt)).toLocaleDateString('pt-BR') : '—'}
      </td>
    </tr>
  );
}

// ── User Detail Modal ───────────────────────────────────────────────────
function UserDetailModal({ userId, onClose, onRefresh }) {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [creditsAmount, setCreditsAmount] = useState('');
  const [creditsReason, setCreditsReason] = useState('');
  const [actionLoading, setActionLoading] = useState('');
  const [toast, setToast] = useState('');

  const load = useCallback(async () => {
    try {
      setLoading(true);
      const [d, termsData] = await Promise.all([
        adminFetch(`/api/admin/users/${userId}`),
        adminFetch(`/api/admin/users/${userId}/terms`).catch(() => ({ terms: [] }))
      ]);
      setData({ ...d, terms: termsData.terms || [] });
    } catch (e) { console.error(e); }
    finally { setLoading(false); }
  }, [userId]);

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

  const showToast = (msg) => { setToast(msg); setTimeout(() => setToast(''), 2500); };

  const handleCredits = async () => {
    const amt = parseInt(creditsAmount, 10);
    if (!amt || isNaN(amt)) return;
    setActionLoading('credits');
    try {
      await adminFetch(`/api/admin/users/${userId}/credits`, { method: 'POST', body: { amount: amt, reason: creditsReason } });
      showToast(`${amt > 0 ? '+' : ''}${amt} créditos aplicados`);
      setCreditsAmount(''); setCreditsReason('');
      await load(); onRefresh();
    } catch (e) { showToast('Erro: ' + e.message); }
    finally { setActionLoading(''); }
  };

  const handleBan = async (ban) => {
    setActionLoading('ban');
    try {
      await adminFetch(`/api/admin/users/${userId}/ban`, { method: 'POST', body: { banned: ban } });
      showToast(ban ? 'Usuário banido' : 'Usuário desbanido');
      await load(); onRefresh();
    } catch (e) { showToast('Erro: ' + e.message); }
    finally { setActionLoading(''); }
  };

  const u = data?.user;

  return (
    <div style={adminS.overlay} onClick={onClose}>
      <div style={adminS.modal} onClick={e => e.stopPropagation()}>
        {/* Close */}
        <button onClick={onClose} style={adminS.modalClose}><Icons.X size={20} /></button>

        {loading || !u ? (
          <div style={{ padding: 40, textAlign: 'center', color: 'var(--ink-3)' }}>Carregando...</div>
        ) : (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 0 }}>
            {/* Header */}
            <div style={{ padding: '28px 32px 20px', borderBottom: '1px solid var(--line)' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
                <div style={{ ...adminS.miniAvatar, width: 48, height: 48, fontSize: 16 }}>{(u.name || 'U').slice(0, 2).toUpperCase()}</div>
                <div>
                  <div style={{ fontSize: 20, fontWeight: 600 }}>{u.name}</div>
                  <div style={{ fontSize: 13, color: 'var(--ink-3)' }}>{u.email}</div>
                </div>
                <div style={{ marginLeft: 'auto', display: 'flex', gap: 8 }}>
                  {u.banned ? <Pill tone="ink">Banido</Pill> : <Pill tone="accent">Ativo</Pill>}
                  {u.googleLinked && <Pill>Google</Pill>}
                </div>
              </div>
            </div>

            {/* Stats row */}
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 0, borderBottom: '1px solid var(--line)' }}>
              {[
                { label: 'Plano', value: u.planName || 'Gratuito' },
                { label: 'Créditos totais', value: u.creditsTotal },
                { label: 'Usados', value: u.creditsUsed },
                { label: 'Disponíveis', value: Math.max(0, u.creditsTotal - u.creditsUsed) },
              ].map((s, i) => (
                <div key={i} style={{ padding: '16px 24px', borderRight: i < 3 ? '1px solid var(--line)' : 'none' }}>
                  <div style={{ fontSize: 11, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: '.05em' }}>{s.label}</div>
                  <div className="serif" style={{ fontSize: 22, marginTop: 2 }}>{s.value}</div>
                </div>
              ))}
            </div>

            {/* Actions */}
            <div style={{ padding: '20px 32px', borderBottom: '1px solid var(--line)' }}>
              <div style={{ fontSize: 13, fontWeight: 600, marginBottom: 12, color: 'var(--ink-2)' }}>Adicionar / Remover Créditos</div>
              <div style={{ display: 'flex', gap: 10, alignItems: 'flex-end' }}>
                <div style={{ flex: '0 0 100px' }}>
                  <div style={{ fontSize: 11, color: 'var(--ink-4)', marginBottom: 4 }}>Quantidade</div>
                  <input type="number" value={creditsAmount} onChange={e => setCreditsAmount(e.target.value)}
                    placeholder="+10 ou -5" style={{ ...adminS.input, width: '100%' }} />
                </div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 11, color: 'var(--ink-4)', marginBottom: 4 }}>Motivo (opcional)</div>
                  <input value={creditsReason} onChange={e => setCreditsReason(e.target.value)}
                    placeholder="Motivo da alteração" style={{ ...adminS.input, width: '100%' }} />
                </div>
                <Button variant="accent" size="sm" onClick={handleCredits}
                  disabled={actionLoading === 'credits' || !creditsAmount}>
                  {actionLoading === 'credits' ? 'Salvando...' : 'Aplicar'}
                </Button>
              </div>
            </div>

            {/* Ban / Unban */}
            <div style={{ padding: '16px 32px', borderBottom: '1px solid var(--line)', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
              <div>
                <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--ink-2)' }}>Status da conta</div>
                <div style={{ fontSize: 12, color: 'var(--ink-4)' }}>
                  {u.banned ? 'Este usuário está banido e não consegue acessar a plataforma.' : 'Conta ativa. O usuário pode acessar normalmente.'}
                </div>
              </div>
              {u.banned ? (
                <Button variant="primary" size="sm" onClick={() => handleBan(false)}
                  disabled={actionLoading === 'ban'}>
                  {actionLoading === 'ban' ? '...' : 'Desbanir'}
                </Button>
              ) : (
                <button onClick={() => handleBan(true)} disabled={actionLoading === 'ban'}
                  style={{ padding: '7px 14px', borderRadius: 8, fontSize: 13, fontWeight: 500, background: '#FDECE7', color: '#7A2E18', border: '1px solid #EAC1B4', cursor: 'pointer' }}>
                  {actionLoading === 'ban' ? '...' : 'Banir usuário'}
                </button>
              )}
            </div>

            {/* Purchases */}
            <div style={{ padding: '20px 32px', maxHeight: 220, overflow: 'auto' }}>
              <div style={{ fontSize: 13, fontWeight: 600, marginBottom: 10, color: 'var(--ink-2)' }}>
                Compras ({data.purchases?.length || 0})
              </div>
              {data.purchases?.length > 0 ? (
              <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
                <thead><tr style={{ borderBottom: '1px solid var(--line)' }}>
                  {['Plano', 'Créditos', 'Valor', 'Método', 'Status', 'Data', 'Código / Recibo'].map(h =>
                    <th key={h} style={{ textAlign: 'left', padding: '6px 8px', fontSize: 11, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: '.05em' }}>{h}</th>
                  )}
                </tr></thead>
                <tbody>{data.purchases.map((p, i) => (
                  <tr key={i} style={{ borderBottom: '1px solid var(--line)' }}>
                    <td style={{ padding: '8px 8px' }}>{p.planName}</td>
                    <td style={{ padding: '8px 8px' }}>{p.credits}</td>
                    <td style={{ padding: '8px 8px' }}>R$ {Number(p.amount).toFixed(2).replace('.', ',')}</td>
                    <td style={{ padding: '8px 8px' }}>{p.method === 'pix' ? 'PIX' : 'Cartão'}</td>
                    <td style={{ padding: '8px 8px' }}>
                      <span style={{ color: p.status === 'paid' ? 'var(--olive)' : '#C96442', fontWeight: 500 }}>
                        {p.status === 'paid' ? 'Pago' : p.status}
                      </span>
                    </td>
                    <td style={{ padding: '8px 8px', color: 'var(--ink-4)' }}>
                      {p.createdAt ? new Date(Number(p.createdAt)).toLocaleDateString('pt-BR') : '—'}
                    </td>
                    <td style={{ padding: '8px 8px' }}>
                      {p.receiptCode ? (
                        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                          <span className="mono" style={{ fontSize: 12, background: 'var(--bg-deep)', padding: '2px 6px', borderRadius: 4 }}>{p.receiptCode}</span>
                          {p.status === 'paid' && (
                            <a href={`/api/checkout/receipt/${p.receiptCode}.html`} target="_blank" rel="noopener"
                              style={{ fontSize: 12, color: 'var(--accent)', textDecoration: 'underline' }}>Recibo</a>
                          )}
                        </div>
                      ) : <span style={{ color: 'var(--ink-4)' }}>—</span>}
                    </td>
                  </tr>
                ))}</tbody>
              </table>
              ) : (
                <div style={{ fontSize: 13, color: 'var(--ink-4)' }}>Nenhuma compra registrada.</div>
              )}
            </div>

            {/* Terms Signatures */}
            <div style={{ padding: '20px 32px 32px', maxHeight: 220, overflow: 'auto' }}>
              <div style={{ fontSize: 13, fontWeight: 600, marginBottom: 10, color: 'var(--ink-2)' }}>
                Assinaturas de Termos ({data.terms?.length || 0})
              </div>
              {data.terms?.length > 0 ? (
                <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
                  <thead><tr style={{ borderBottom: '1px solid var(--line)' }}>
                    {['Data', 'Hash', 'IP', 'Versão'].map(h =>
                      <th key={h} style={{ textAlign: 'left', padding: '6px 8px', fontSize: 11, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: '.05em' }}>{h}</th>
                    )}
                  </tr></thead>
                  <tbody>{data.terms.map((t, i) => (
                    <tr key={i} style={{ borderBottom: '1px solid var(--line)' }}>
                      <td style={{ padding: '8px 8px' }}>
                        {t.acceptedAt ? new Date(Number(t.acceptedAt)).toLocaleString('pt-BR') : '—'}
                      </td>
                      <td style={{ padding: '8px 8px' }}>
                        <span className="mono" title={t.signatureHash} style={{ fontSize: 11, background: 'var(--bg-deep)', padding: '2px 6px', borderRadius: 4 }}>
                          {t.id}
                        </span>
                      </td>
                      <td style={{ padding: '8px 8px', color: 'var(--ink-4)' }}>{t.ipAddress}</td>
                      <td style={{ padding: '8px 8px' }}>{t.version}</td>
                    </tr>
                  ))}</tbody>
                </table>
              ) : (
                <div style={{ fontSize: 13, color: 'var(--ink-4)' }}>Nenhum aceite registrado.</div>
              )}
            </div>
          </div>
        )}

        {/* Toast */}
        {toast && (
          <div style={adminS.toast}>{toast}</div>
        )}
      </div>
    </div>
  );
}

// ── Re-edições Metrics Section ─────────────────────────────────────────
const PERIODS = [
  { id: '7d',  label: '7 dias' },
  { id: '30d', label: '30 dias' },
  { id: '90d', label: '90 dias' },
];

function periodDates(id) {
  const days = id === '7d' ? 7 : id === '90d' ? 90 : 30;
  const to = new Date();
  const from = new Date(Date.now() - days * 86400000);
  const fmt = d => d.toISOString().slice(0, 10);
  return { from: fmt(from), to: fmt(to) };
}

function ReeditsSection() {
  const RC = window.Recharts || {};
  const { LineChart, Line, BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer } = RC;

  const [period, setPeriod] = useState('30d');
  const [data, setData] = useState(null);
  const [topUsers, setTopUsers] = useState([]);
  const [loading, setLoading] = useState(true);

  const load = useCallback(async (pid) => {
    setLoading(true);
    try {
      const { from, to } = periodDates(pid);
      const qs = `from=${from}&to=${to}`;
      const [m, t] = await Promise.all([
        adminFetch(`/api/admin/metrics/reedits?${qs}`),
        adminFetch(`/api/admin/metrics/reedits/top-users?${qs}&limit=20`),
      ]);
      setData(m);
      setTopUsers(t.users || []);
    } catch (e) { console.error(e); }
    finally { setLoading(false); }
  }, []);

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

  const fmtPct = v => `${v}%`;
  const fmtBrl = v => `R$ ${Number(v).toFixed(2).replace('.', ',')}`;
  const fmtDate = s => s ? s.slice(5) : '';

  if (loading) return (
    <div style={{ padding: 60, textAlign: 'center', color: 'var(--ink-3)' }}>Carregando métricas...</div>
  );
  if (!data) return (
    <div style={{ padding: 60, textAlign: 'center', color: 'var(--ink-3)' }}>Sem dados.</div>
  );

  const pkgLabels = { '15': 'Pacote 15', '30': 'Pacote 30', '50': 'Pacote 50' };
  const byPkgData = Object.entries(data.reeditRateByPackage || {}).map(([k, v]) => ({
    name: pkgLabels[k] || `Pacote ${k}`, rate: v,
  }));

  return (
    <div style={{ padding: '28px 40px 60px' }}>
      {/* Alert banner */}
      {data.alert7dRate > 40 && (
        <div style={{
          marginBottom: 24, padding: '14px 20px', borderRadius: 12,
          background: '#FDECE7', border: '1px solid #E8B7A5', color: '#7A2E18',
          display: 'flex', alignItems: 'center', gap: 12, fontWeight: 500,
        }}>
          ⚠️ Taxa de re-edição dos últimos 7 dias está em <strong>{data.alert7dRate}%</strong> — acima do limite de 40%!
        </div>
      )}

      {/* Period selector */}
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 24 }}>
        <div className="serif" style={{ fontSize: 22 }}>Métricas de Re-edições</div>
        <div style={{ display: 'flex', gap: 4, background: 'var(--bg-deep)', borderRadius: 10, padding: 3 }}>
          {PERIODS.map(p => (
            <button key={p.id} onClick={() => setPeriod(p.id)} style={{
              padding: '7px 14px', borderRadius: 8, fontSize: 13, fontWeight: 500,
              background: period === p.id ? 'var(--paper)' : 'transparent',
              color: period === p.id ? 'var(--ink)' : 'var(--ink-3)',
              boxShadow: period === p.id ? 'var(--shadow-sm)' : 'none',
              transition: 'all .15s',
            }}>{p.label}</button>
          ))}
        </div>
      </div>

      {/* 4 stat cards */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 16, marginBottom: 32 }}>
        <StatCard label="Taxa Global" value={fmtPct(data.reeditRateGlobal)} color="#F3E0E0" icon={<Icons.Star size={20}/>}/>
        <StatCard label="Custo Extra" value={fmtBrl(data.reeditExtraCost)} color="#FDECE7" icon={<Icons.Zap size={20}/>}/>
        <StatCard label="Custo Extra %" value={fmtPct(data.reeditExtraCostPct)} color="#DDE6ED" icon={<Icons.Grid size={20}/>}/>
        <StatCard label="Re-edições totais" value={data.totalReedits} color="#E7EADE" icon={<Icons.Plus size={20}/>}/>
      </div>

      {/* Charts row */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 20, marginBottom: 32 }}>
        {/* LineChart - série diária */}
        <div style={{ background: 'var(--paper)', border: '1px solid var(--line)', borderRadius: 14, padding: '20px 16px 12px' }}>
          <div style={{ fontSize: 13, fontWeight: 600, marginBottom: 16, color: 'var(--ink-2)' }}>Taxa diária de re-edição (%)</div>
          {LineChart ? (
            <ResponsiveContainer width="100%" height={200}>
              <LineChart data={data.dailySeries || []}>
                <CartesianGrid strokeDasharray="3 3" stroke="var(--line)"/>
                <XAxis dataKey="date" tickFormatter={fmtDate} tick={{ fontSize: 10, fill: 'var(--ink-4)' }}/>
                <YAxis tick={{ fontSize: 10, fill: 'var(--ink-4)' }} tickFormatter={v => `${v}%`}/>
                <Tooltip formatter={v => [`${v}%`, 'Taxa']} labelFormatter={l => `Dia: ${l}`}/>
                <Line type="monotone" dataKey="rate" stroke="var(--accent)" strokeWidth={2} dot={false}/>
              </LineChart>
            </ResponsiveContainer>
          ) : <div style={{ color: 'var(--ink-3)', fontSize: 13, padding: 20 }}>Recharts não carregado.</div>}
        </div>

        {/* BarChart - por pacote */}
        <div style={{ background: 'var(--paper)', border: '1px solid var(--line)', borderRadius: 14, padding: '20px 16px 12px' }}>
          <div style={{ fontSize: 13, fontWeight: 600, marginBottom: 16, color: 'var(--ink-2)' }}>Taxa por pacote (%)</div>
          {BarChart && byPkgData.length > 0 ? (
            <ResponsiveContainer width="100%" height={200}>
              <BarChart data={byPkgData}>
                <CartesianGrid strokeDasharray="3 3" stroke="var(--line)"/>
                <XAxis dataKey="name" tick={{ fontSize: 11, fill: 'var(--ink-4)' }}/>
                <YAxis tick={{ fontSize: 10, fill: 'var(--ink-4)' }} tickFormatter={v => `${v}%`}/>
                <Tooltip formatter={v => [`${v}%`, 'Taxa']}/>
                <Bar dataKey="rate" fill="var(--accent)" radius={[6,6,0,0]}/>
              </BarChart>
            </ResponsiveContainer>
          ) : <div style={{ color: 'var(--ink-3)', fontSize: 13, padding: 20 }}>Sem dados de pacote ainda.</div>}
        </div>
      </div>

      {/* By-user stats */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 16, marginBottom: 32 }}>
        {[
          { label: 'Taxa média / usuário', value: fmtPct(data.reeditRateByUser?.mean || 0) },
          { label: 'Mediana / usuário', value: fmtPct(data.reeditRateByUser?.median || 0) },
          { label: 'P90 / usuário', value: fmtPct(data.reeditRateByUser?.p90 || 0) },
        ].map((s, i) => <StatCard key={i} label={s.label} value={s.value} color="var(--accent-soft)" icon={<Icons.Grid size={20}/>}/>)}
      </div>

      {/* Top-20 users table */}
      <div style={{ background: 'var(--paper)', border: '1px solid var(--line)', borderRadius: 14, overflow: 'hidden' }}>
        <div style={{ padding: '16px 20px', borderBottom: '1px solid var(--line)', fontSize: 13, fontWeight: 600, color: 'var(--ink-2)' }}>
          Top usuários por taxa de re-edição (mín. 5 gerações)
        </div>
        {topUsers.length === 0 ? (
          <div style={{ padding: 32, textAlign: 'center', color: 'var(--ink-3)', fontSize: 13 }}>Sem dados suficientes no período.</div>
        ) : (
          <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
            <thead>
              <tr style={{ borderBottom: '1px solid var(--line)', background: 'var(--bg-warm)' }}>
                {['Usuário', 'Email', 'Originais', 'Re-edições', 'Taxa'].map(h => (
                  <th key={h} style={adminS.th}>{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {topUsers.map((u, i) => (
                <tr key={i} style={{ borderBottom: '1px solid var(--line)' }}>
                  <td style={adminS.td}>{u.name}</td>
                  <td style={{ ...adminS.td, color: 'var(--ink-3)' }}>{u.email}</td>
                  <td style={adminS.td}>{u.originals}</td>
                  <td style={adminS.td}>{u.reedits}</td>
                  <td style={adminS.td}>
                    <span style={{ fontWeight: 600, color: u.reeditRate > 40 ? '#C96442' : 'var(--olive)' }}>
                      {u.reeditRate}%
                    </span>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>
    </div>
  );
}

// ── Main Admin Panel ────────────────────────────────────────────────────
function AdminPanel({ navigate }) {
  const [tab, setTab] = useState('users');
  const [stats, setStats] = useState(null);
  const [users, setUsers] = useState([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [search, setSearch] = useState('');
  const [filter, setFilter] = useState('all');
  const [selectedUserId, setSelectedUserId] = useState(null);
  const [loading, setLoading] = useState(true);
  const searchRef = useRef(null);
  const debounceRef = useRef(null);

  const loadStats = async () => {
    try { const s = await adminFetch('/api/admin/stats'); setStats(s); }
    catch (e) { console.error(e); }
  };

  const loadUsers = useCallback(async (p = page, s = search, f = filter) => {
    try {
      setLoading(true);
      const q = new URLSearchParams({ page: p, limit: 20, search: s, filter: f });
      const d = await adminFetch(`/api/admin/users?${q}`);
      setUsers(d.users); setTotal(d.total); setPage(d.page); setTotalPages(d.totalPages);
    } catch (e) { console.error(e); }
    finally { setLoading(false); }
  }, []);

  useEffect(() => { loadStats(); loadUsers(1, '', 'all'); }, []);

  const onSearchChange = (val) => {
    setSearch(val);
    clearTimeout(debounceRef.current);
    debounceRef.current = setTimeout(() => loadUsers(1, val, filter), 350);
  };

  const onFilterChange = (f) => { setFilter(f); loadUsers(1, search, f); };

  const filters = [
    { id: 'all', label: 'Todos' },
    { id: 'active', label: 'Ativos' },
    { id: 'banned', label: 'Banidos' },
  ];

  const tabs = [
    { id: 'users', label: 'Usuários' },
    { id: 'reedits', label: 'Re-edições' },
  ];

  return (
    <AppShell route="#/admin" navigate={navigate} title="Administração" subtitle="Gerencie usuários, créditos e acessos">
      {/* Tab bar + logout */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 4, padding: '16px 40px 0', borderBottom: '1px solid var(--line)', background: 'var(--bg-warm)' }}>
        {tabs.map(t => (
          <button key={t.id} onClick={() => setTab(t.id)} style={{
            padding: '10px 18px', fontSize: 14, fontWeight: 500, borderRadius: '8px 8px 0 0',
            background: tab === t.id ? 'var(--paper)' : 'transparent',
            color: tab === t.id ? 'var(--ink)' : 'var(--ink-3)',
            borderBottom: tab === t.id ? '2px solid var(--accent)' : '2px solid transparent',
            transition: 'all .15s',
          }}>{t.label}</button>
        ))}
        <button
          onClick={async () => { await window.DB.adminLogout(); window.location.reload(); }}
          style={{
            marginLeft: 'auto', padding: '7px 14px', borderRadius: 8,
            fontSize: 13, color: 'var(--ink-3)', border: '1px solid var(--line)',
            background: 'transparent', cursor: 'pointer',
          }}
        >Sair →</button>
      </div>
      {tab === 'reedits' ? <ReeditsSection /> : (
      <div style={{ padding: '28px 40px 40px' }}>
        {/* Stats Grid */}
        {stats && (
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 16, marginBottom: 32 }}>
            <StatCard label="Total de Usuários" value={stats.totalUsers} color="var(--accent-soft)"
              icon={<Icons.Grid size={20} />} />
            <StatCard label="Cadastros (7 dias)" value={stats.recentSignups} color="#E7EADE"
              icon={<Icons.Plus size={20} />} />
            <StatCard label="Créditos em uso" value={`${stats.totalCreditsUsed}/${stats.totalCreditsIssued}`} color="#DDE6ED"
              icon={<Icons.Zap size={20} />} />
            <StatCard label="Receita Total" value={`R$ ${Number(stats.totalRevenue).toFixed(2).replace('.', ',')}`} color="#F3E0E0"
              icon={<Icons.Star size={20} />} />
          </div>
        )}

        {/* Search + Filters */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 20 }}>
          <div style={{ position: 'relative', flex: 1, maxWidth: 380 }}>
            <Icons.Search size={16} style={{ position: 'absolute', left: 12, top: '50%', transform: 'translateY(-50%)', color: 'var(--ink-4)' }} />
            <input ref={searchRef} value={search} onChange={e => onSearchChange(e.target.value)}
              placeholder="Buscar por nome, email ou ID..."
              style={{ ...adminS.input, width: '100%', paddingLeft: 36 }} />
          </div>
          <div style={{ display: 'flex', gap: 4, background: 'var(--bg-deep)', borderRadius: 10, padding: 3 }}>
            {filters.map(f => (
              <button key={f.id} onClick={() => onFilterChange(f.id)}
                style={{
                  padding: '7px 14px', borderRadius: 8, fontSize: 13, fontWeight: 500,
                  background: filter === f.id ? 'var(--paper)' : 'transparent',
                  color: filter === f.id ? 'var(--ink)' : 'var(--ink-3)',
                  boxShadow: filter === f.id ? 'var(--shadow-sm)' : 'none',
                  transition: 'all .15s',
                }}>
                {f.label}
              </button>
            ))}
          </div>
          <div style={{ marginLeft: 'auto', fontSize: 13, color: 'var(--ink-3)' }}>
            {total} usuário{total !== 1 ? 's' : ''}
          </div>
        </div>

        {/* Table */}
        <div style={{ background: 'var(--paper)', border: '1px solid var(--line)', borderRadius: 14, overflow: 'hidden' }}>
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <thead>
              <tr style={{ borderBottom: '1px solid var(--line)', background: 'var(--bg-warm)' }}>
                {['Usuário', 'Plano', 'Créditos', 'Status', 'Cadastro'].map(h => (
                  <th key={h} style={adminS.th}>{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {loading && users.length === 0 ? (
                <tr><td colSpan={5} style={{ padding: 40, textAlign: 'center', color: 'var(--ink-3)' }}>Carregando...</td></tr>
              ) : users.length === 0 ? (
                <tr><td colSpan={5} style={{ padding: 40, textAlign: 'center', color: 'var(--ink-3)' }}>Nenhum usuário encontrado.</td></tr>
              ) : (
                users.map(u => <UserRow key={u.id} user={u} onSelect={() => setSelectedUserId(u.id)} />)
              )}
            </tbody>
          </table>
        </div>

        {/* Pagination */}
        {totalPages > 1 && (
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8, marginTop: 20 }}>
            <Button variant="ghost" size="sm" disabled={page <= 1} onClick={() => loadUsers(page - 1, search, filter)}>
              ← Anterior
            </Button>
            <span className="mono" style={{ fontSize: 13, color: 'var(--ink-3)' }}>
              {page} / {totalPages}
            </span>
            <Button variant="ghost" size="sm" disabled={page >= totalPages} onClick={() => loadUsers(page + 1, search, filter)}>
              Próxima →
            </Button>
          </div>
        )}
      </div>
      )}

      {/* Detail Modal */}
      {selectedUserId && (
        <UserDetailModal userId={selectedUserId}
          onClose={() => setSelectedUserId(null)}
          onRefresh={() => { loadUsers(page, search, filter); loadStats(); }} />
      )}
    </AppShell>
  );
}

// ── Styles ──────────────────────────────────────────────────────────────
const adminS = {
  statCard: {
    display: 'flex', alignItems: 'center', gap: 14,
    padding: '18px 20px', background: 'var(--paper)',
    border: '1px solid var(--line)', borderRadius: 14,
  },
  statIcon: {
    width: 42, height: 42, borderRadius: 12,
    display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
  },
  th: {
    textAlign: 'left', padding: '12px 16px', fontSize: 11,
    color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: '.06em', fontWeight: 600,
  },
  td: { padding: '12px 16px', borderBottom: '1px solid var(--line)' },
  miniAvatar: {
    width: 34, height: 34, borderRadius: 8,
    background: 'var(--accent)', color: 'white',
    display: 'flex', alignItems: 'center', justifyContent: 'center',
    fontSize: 12, fontWeight: 600, flexShrink: 0,
  },
  input: {
    padding: '9px 12px', borderRadius: 8,
    border: '1px solid var(--line-2)', background: 'var(--paper)',
    fontSize: 13, color: 'var(--ink)', outline: 'none',
  },
  overlay: {
    position: 'fixed', inset: 0, background: 'rgba(31,26,21,.45)',
    display: 'flex', alignItems: 'center', justifyContent: 'center',
    zIndex: 1000, backdropFilter: 'blur(4px)',
  },
  modal: {
    background: 'var(--paper)', borderRadius: 18, width: '90%', maxWidth: 720,
    maxHeight: '88vh', overflow: 'auto', position: 'relative',
    boxShadow: '0 30px 80px -20px rgba(31,26,21,.35)',
    border: '1px solid var(--line)',
  },
  modalClose: {
    position: 'absolute', top: 16, right: 16, padding: 8,
    borderRadius: 8, color: 'var(--ink-3)', zIndex: 10,
  },
  toast: {
    position: 'absolute', bottom: 16, left: '50%', transform: 'translateX(-50%)',
    background: 'var(--ink)', color: 'var(--bg-warm)', padding: '10px 20px',
    borderRadius: 10, fontSize: 13, fontWeight: 500,
    boxShadow: '0 8px 24px -8px rgba(31,26,21,.3)',
    animation: 'fadeIn .2s ease',
  },
};

Object.assign(window, { AdminPanel, AdminRoute });
