/* AIWine CRM — Backup & admin: system status, exports, audit log, go-live */
function Admin() {
  const store = window.UI.useStore();
  const { Badge, Ic, rel, fmtDate, KV, toast } = window.UI;
  const counts = ['wineries', 'contacts', 'consumers', 'wines', 'campaigns', 'tickets', 'tasks', 'uploads', 'notes'].map((t) => [t, store.t(t).length]);
  const totalRecords = counts.reduce((s, [, n]) => s + n, 0);
  const audit = store.t('audit').slice(0, 40);

  return (
    <div>
      <div className="page-head">
        <div>
          <div className="label" style={{ marginBottom: 6 }}>System · backups · audit</div>
          <h1 className="page-title">Backup & admin</h1>
        </div>
      </div>

      <div className="grid-2" style={{ marginBottom: 16 }}>
        <div className="card card-pad">
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 16 }}>
            <h3 className="card-title" style={{ margin: 0 }}>System status</h3>
            {store.mode === 'demo'
              ? <span className="badge badge-brass"><span className="dot pulse"></span>Demo · browser only</span>
              : <span className="badge badge-green"><span className="dot"></span>Live · Supabase</span>}
          </div>
          <KV rows={[
            ['Backend', store.mode === 'demo' ? 'localStorage (sample data)' : 'Supabase PostgreSQL'],
            ['Records', totalRecords.toLocaleString()],
            ['Email', store.mode === 'demo' ? 'Simulated' : 'Resend via /api/send-campaign'],
            ['Signed in', store.user ? store.user.email : '—'],
            ['Markets', 'aiwine.co.nz · aiwine.com.au'],
          ]} />
          <div style={{ borderTop: '1px solid var(--line-soft)', marginTop: 16, paddingTop: 14, display: 'flex', gap: 10, flexWrap: 'wrap' }}>
            <button className="btn btn-primary" onClick={() => { store.exportEverything(); toast('Backup downloaded'); }}><Ic name="download" w={15} /> Export everything</button>
            {store.mode === 'demo' && <button className="btn btn-ghost" title="Generates INSERT statements from the data exactly as it is right now — every edit included. Paste into Supabase SQL Editor at go-live." onClick={() => { store.exportSQL(); toast('Go-live SQL downloaded'); }}><Ic name="database" w={15} /> Export SQL for go-live</button>}
            {store.mode === 'demo' && <button className="btn btn-ghost" onClick={() => { if (confirm('Reset local data back to the imported winery list? Any notes, tasks and edits made since will be lost.')) { store.resetDemo(); toast('Local data reset'); } }}>Reset local data</button>}
          </div>
          <div style={{ fontSize: 12, color: 'var(--muted)', marginTop: 10 }}>
            Exports a dated JSON snapshot of every table — keep a copy in Google Drive or OneDrive as your tertiary backup. In live mode, Supabase also takes automatic daily database backups.
          </div>
        </div>

        <div className="card card-pad">
          <h3 className="card-title" style={{ marginTop: 0, marginBottom: 16 }}>Export tables (CSV)</h3>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 8 }}>
            {counts.map(([t, n]) => (
              <button key={t} className="btn btn-ghost btn-sm" style={{ justifyContent: 'space-between' }} onClick={() => { store.exportTableCSV(t); toast(t + '.csv downloaded'); }}>
                <span style={{ textTransform: 'capitalize' }}>{t}</span>
                <span className="mono" style={{ fontSize: 10, color: 'var(--muted)' }}>{n}</span>
              </button>
            ))}
          </div>
          <div style={{ borderTop: '1px solid var(--line-soft)', marginTop: 16, paddingTop: 14 }}>
            <h3 className="card-title" style={{ marginTop: 0, marginBottom: 8 }}>Going live</h3>
            <ol style={{ margin: 0, paddingLeft: 18, fontSize: 12.5, color: 'var(--ink-soft)', lineHeight: 1.9 }}>
              <li>Create the Supabase project & run <span className="mono" style={{ fontSize: 11 }}>supabase/schema.sql</span></li>
              <li>Paste keys into <span className="mono" style={{ fontSize: 11 }}>config.js</span></li>
              <li>Deploy to Vercel · point <span className="mono" style={{ fontSize: 11 }}>crm.aiwine.co.nz</span> at it in Cloudflare</li>
              <li>Verify both domains in Resend</li>
            </ol>
            <div style={{ fontSize: 12, color: 'var(--muted)', marginTop: 8 }}>Full walkthrough: <span className="mono" style={{ fontSize: 11 }}>DEPLOYMENT.md</span> in the crm folder.</div>
          </div>
        </div>
      </div>

      <div className="card">
        <div className="card-head"><h3 className="card-title">Audit log</h3><span className="label" style={{ fontSize: 9 }}>Recent changes</span></div>
        <div className="tbl-wrap" style={{ border: 'none' }}>
          <table className="tbl">
            <thead><tr><th>When</th><th>Who</th><th>Action</th><th>Entity</th></tr></thead>
            <tbody>
              {audit.map((a) => (
                <tr key={a.id}>
                  <td className="num">{rel(a.at)}</td>
                  <td style={{ fontSize: 12.5 }}>{a.user}</td>
                  <td style={{ fontSize: 12.5, fontWeight: 600 }}>{a.action}</td>
                  <td><span className="badge">{a.entity}</span></td>
                </tr>
              ))}
              {audit.length === 0 && <tr><td colSpan="4"><window.UI.Empty msg="No audit entries yet" /></td></tr>}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}
window.Admin = Admin;
