/* ============================================================
   ADMIN — review interest registrations, approve → Clerk invite.
   Reached at <site>/#admin. Gated server-side by /api/admin (ADMIN_EMAILS);
   this UI reflects 401 (sign in) / 403 (not an admin).
   ============================================================ */
const Admin = ({ setRoute }) => {
  const auth = useClerkAuth();
  const [data, setData] = React.useState(null);
  const [status, setStatus] = React.useState('loading'); // loading | ok | unauth | forbidden | error
  const [busy, setBusy] = React.useState(null);

  const authedFetch = async (opts = {}) => {
    const token = (window.Clerk && window.Clerk.session) ? await window.Clerk.session.getToken() : null;
    return fetch('/api/admin', {
      ...opts,
      headers: { 'Content-Type': 'application/json', ...(opts.headers || {}), ...(token ? { Authorization: 'Bearer ' + token } : {}) },
    });
  };

  const load = React.useCallback(async () => {
    if (!auth.ready) return;
    if (!auth.signedIn) { setStatus('unauth'); return; }
    setStatus('loading');
    try {
      const res = await authedFetch();
      if (res.status === 401) return setStatus('unauth');
      if (res.status === 403) return setStatus('forbidden');
      if (!res.ok) return setStatus('error');
      setData(await res.json());
      setStatus('ok');
    } catch (e) { setStatus('error'); }
  }, [auth.ready, auth.signedIn]);

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

  const act = async (id, action, kind) => {
    if (action === 'approve' && !window.confirm(`Approve as ${kind}? This sends a real invitation email.`)) return;
    setBusy(id);
    try {
      const res = await authedFetch({ method: 'POST', body: JSON.stringify({ id, action, kind }) });
      const j = await res.json().catch(() => ({}));
      if (!res.ok) window.alert(j.error || 'Action failed.');
      await load();
    } catch (e) { window.alert('Action failed.'); }
    finally { setBusy(null); }
  };

  const Shell = ({ children }) => (
    <section className="section first"><div className="site-wrap" style={{ maxWidth: 1080 }}>
      <div className="mono-eyebrow" style={{ marginBottom: 18 }}>Kestrel · Admin</div>
      {children}
    </div></section>
  );

  if (status === 'loading') return <Shell><p style={{ color: 'var(--ink-2)' }}>Loading…</p></Shell>;
  if (status === 'unauth') return (
    <Shell>
      <h1 className="spade-h" style={{ fontSize: 30 }}>Admin sign-in</h1>
      <p style={{ marginTop: 12, color: 'var(--ink-2)' }}>Sign in with an admin account to review registrations.</p>
      <button className="btn btn-lime" style={{ marginTop: 20, fontFamily: 'var(--mono)' }} onClick={() => (typeof openClerkSignIn === 'function') && openClerkSignIn()}>Sign in</button>
    </Shell>
  );
  if (status === 'forbidden') return (
    <Shell>
      <h1 className="spade-h" style={{ fontSize: 30 }}>Admin access required</h1>
      <p style={{ marginTop: 12, color: 'var(--ink-2)' }}>This account isn’t on the admin allowlist (ADMIN_EMAILS).</p>
      <button className="btn" style={{ marginTop: 20, fontFamily: 'var(--mono)' }} onClick={() => setRoute({ page: 'home' })}>Back to site</button>
    </Shell>
  );
  if (status === 'error') return (
    <Shell><p style={{ color: 'var(--ink-2)' }}>Couldn’t load registrations. <button className="btn" style={{ marginLeft: 8 }} onClick={load}>Retry</button></p></Shell>
  );

  const regs = (data && data.registrations) || [];
  const pending = regs.filter((r) => r.status === 'new').length;
  const th = { padding: '8px 10px', fontWeight: 600, color: 'var(--ink-2)', whiteSpace: 'nowrap', fontSize: 11, textTransform: 'uppercase', letterSpacing: '0.06em', fontFamily: 'var(--mono)' };
  const td = { padding: '8px 10px', verticalAlign: 'top', fontSize: 13.5 };
  const sm = { height: 28, padding: '0 10px', fontSize: 11.5, fontFamily: 'var(--mono)' };
  return (
    <Shell>
      <h1 className="spade-h" style={{ fontSize: 30 }}>Interest registrations</h1>
      <p style={{ marginTop: 10, color: 'var(--ink-3)', fontFamily: 'var(--mono)', fontSize: 13 }}>{regs.length} total · {pending} awaiting review</p>
      {regs.length === 0 ? (
        <p style={{ marginTop: 20, color: 'var(--ink-2)' }}>No registrations yet.</p>
      ) : (
        <table style={{ width: '100%', marginTop: 22, borderCollapse: 'collapse' }}>
          <thead>
            <tr style={{ textAlign: 'left', borderBottom: '1px solid var(--line)' }}>
              <th style={th}>When</th><th style={th}>Name / role</th><th style={th}>Email</th><th style={th}>Company</th><th style={th}>Use</th><th style={th}>Status</th><th style={th}>Actions</th>
            </tr>
          </thead>
          <tbody>
            {regs.map((r) => (
              <tr key={r.id} style={{ borderBottom: '1px solid var(--line)' }}>
                <td style={{ ...td, color: 'var(--ink-3)', whiteSpace: 'nowrap' }}>{new Date(r.created_at).toLocaleDateString()}</td>
                <td style={td}>{r.name}{r.role ? <span style={{ color: 'var(--ink-3)' }}> · {r.role}</span> : null}</td>
                <td style={td}>{r.email}</td>
                <td style={td}>{r.company || '—'}</td>
                <td style={{ ...td, maxWidth: 240, color: 'var(--ink-2)' }}>{r.use_case || '—'}</td>
                <td style={td}>{r.status}</td>
                <td style={td}>
                  {r.status === 'new' ? (
                    <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
                      <button className="btn btn-lime" style={sm} disabled={busy === r.id} onClick={() => act(r.id, 'approve', 'individual')}>Approve · individual</button>
                      <button className="btn btn-lime" style={sm} disabled={busy === r.id} onClick={() => act(r.id, 'approve', 'company')}>Approve · company</button>
                      <button className="btn" style={sm} disabled={busy === r.id} onClick={() => act(r.id, 'decline')}>Decline</button>
                    </div>
                  ) : (
                    <span style={{ color: 'var(--ink-3)', fontSize: 12 }}>
                      {r.status === 'invited' ? `invited${r.org_id ? ' · org' : ''}` : r.status}{r.reviewed_by ? ` · ${r.reviewed_by}` : ''}
                    </span>
                  )}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      )}
    </Shell>
  );
};
window.Admin = Admin;
