// page-admin.jsx — Super Admin views

const { useState: usA } = React;

function PageAdmin({ route, setRoute }) {
  if (route === 'admin') return <AdminOverview setRoute={setRoute} />;
  if (route === 'admin-tenants') return <AdminTenants />;
  if (route === 'admin-plans') return <AdminPlans />;
  return null;
}

function AdminOverview({ setRoute }) {
  const totalExecs = TENANTS.reduce((a,t) => a + t.execs, 0);
  return (
    <div className="fade-up">
      <div className="page-head">
        <div>
          <div className="row gap-sm" style={{ marginBottom: 4 }}>
            <span className="tag tag-accent">Console Admin</span>
            <span className="tag tag-ok tag-dot">All systems normal</span>
          </div>
          <h1 className="page-title">Visão geral da plataforma</h1>
          <p className="page-sub">Saúde global do SyncBridge, MRR e tenants em alerta.</p>
        </div>
        <div className="page-actions">
          <button className="btn"><iconify-icon icon="lucide:user-cog" />Impersonar tenant</button>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 'var(--gap)', marginBottom: 'var(--gap)' }}>
        <KpiCard k={{ label: 'Tenants ativos', value: 32, delta: 9.2, foot: 'meta: 50 (M6)', icon: 'lucide:building-2', color: 'var(--accent)' }} />
        <KpiCard k={{ label: 'MRR (R$)', value: 4280, delta: 18.5, foot: 'meta: 5.000', icon: 'lucide:trending-up', color: 'var(--green)' }} />
        <KpiCard k={{ label: 'Execuções 24h', value: totalExecs, delta: 4.1, foot: 'em todos tenants', icon: 'lucide:zap', color: 'var(--cyan)' }} />
        <KpiCard k={{ label: 'Uptime 30d', value: 99.81, delta: 0.04, foot: 'SLA: 99,5%', icon: 'lucide:activity', color: 'var(--pink)' }} />
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr', gap: 'var(--gap)', marginBottom: 'var(--gap)' }}>
        <PlatformHealth />
        <AlertsCard setRoute={setRoute} />
      </div>

      <div className="card" style={{ padding: 0 }}>
        <div className="row" style={{ padding: 'var(--card-pad)', justifyContent: 'space-between' }}>
          <div style={{ fontSize: 14, fontWeight: 700 }}>Tenants — visão consolidada</div>
          <button className="btn btn-sm" onClick={() => setRoute('admin-tenants')}>Ver todos →</button>
        </div>
        <TenantsTable rows={TENANTS} compact />
      </div>
    </div>
  );
}

function PlatformHealth() {
  return (
    <div className="card">
      <div className="row" style={{ justifyContent: 'space-between', marginBottom: 16 }}>
        <div>
          <div style={{ fontSize: 14, fontWeight: 700 }}>Throughput global por função</div>
          <div className="muted" style={{ fontSize: 11 }}>Execuções/hora — últimas 24h</div>
        </div>
      </div>
      <div style={{ display: 'grid', gap: 10 }}>
        {[
          { fn: 'fn-webhook-router', val: 4820, color: 'var(--accent)' },
          { fn: 'fn-abandoned-carts', val: 2140, color: 'var(--cyan)' },
          { fn: 'fn-sync-leads', val: 880, color: 'var(--green)' },
          { fn: 'fn-sync-catalog', val: 320, color: 'var(--pink)' },
          { fn: 'fn-sync-orders', val: 92, color: 'var(--warn)' },
        ].map(r => (
          <div key={r.fn}>
            <div className="row" style={{ justifyContent: 'space-between', marginBottom: 4, fontSize: 12 }}>
              <span className="strong mono">{r.fn}</span>
              <span className="mono">{r.val.toLocaleString('pt-BR')}/h</span>
            </div>
            <div className="progress"><div className="progress-bar" style={{ width: (r.val / 5000 * 100) + '%', background: r.color }} /></div>
          </div>
        ))}
      </div>
    </div>
  );
}

function AlertsCard({ setRoute }) {
  const alerts = TENANTS.filter(t => t.status === 'warn' || t.status === 'err');
  return (
    <div className="card">
      <div className="row" style={{ justifyContent: 'space-between', marginBottom: 12 }}>
        <div style={{ fontSize: 14, fontWeight: 700 }}>Tenants em alerta</div>
        <span className="tag tag-warn">{alerts.length}</span>
      </div>
      <div style={{ display: 'grid', gap: 8 }}>
        {alerts.map(t => (
          <div key={t.id} className="row gap-sm" style={{ padding: 10, background: 'var(--bg-base)', borderRadius: 'var(--r-md)' }}>
            <span style={{
              width: 8, height: 8, borderRadius: '50%',
              background: t.status === 'err' ? 'var(--err)' : 'var(--warn)',
            }} />
            <div style={{ flex: 1 }}>
              <div className="strong" style={{ fontSize: 13 }}>{t.name}</div>
              <div className="muted" style={{ fontSize: 11 }}>{t.success}% sucesso · {t.execs.toLocaleString('pt-BR')} execs</div>
            </div>
            <button className="btn btn-sm">Inspecionar</button>
          </div>
        ))}
      </div>
    </div>
  );
}

function AdminTenants() {
  const [q, setQ] = usA('');
  const filtered = TENANTS.filter(t => t.name.toLowerCase().includes(q.toLowerCase()) || t.id.includes(q));
  return (
    <div className="fade-up">
      <div className="page-head">
        <div>
          <h1 className="page-title">Tenants</h1>
          <p className="page-sub">{TENANTS.length} contas no total · 32 ativas no mês</p>
        </div>
        <div className="page-actions">
          <button className="btn"><iconify-icon icon="lucide:download" />Exportar</button>
          <button className="btn btn-primary"><iconify-icon icon="lucide:plus" />Novo tenant</button>
        </div>
      </div>
      <div className="card" style={{ padding: 12, marginBottom: 'var(--gap)' }}>
        <div style={{ position: 'relative' }}>
          <iconify-icon icon="lucide:search" style={{ position: 'absolute', left: 12, top: '50%', transform: 'translateY(-50%)', color: 'var(--text-muted)' }} />
          <input className="input" style={{ paddingLeft: 36 }}
            placeholder="Buscar por nome ou ID…" value={q} onChange={e => setQ(e.target.value)} />
        </div>
      </div>
      <div className="card" style={{ padding: 0, overflow: 'hidden' }}>
        <TenantsTable rows={filtered} />
      </div>
    </div>
  );
}

function TenantsTable({ rows, compact }) {
  return (
    <table className="tbl">
      <thead><tr>
        <th>Tenant</th>
        {!compact && <th>ID</th>}
        <th>Plano</th>
        <th>Execuções (mês)</th>
        <th>Sucesso</th>
        <th>Status</th>
        <th>Último acesso</th>
        <th></th>
      </tr></thead>
      <tbody>
        {rows.map(t => (
          <tr key={t.id}>
            <td className="strong">{t.name}</td>
            {!compact && <td className="muted mono" style={{ fontSize: 11 }}>{t.id}</td>}
            <td><span className="tag">{t.plan}</span></td>
            <td className="mono strong">{t.execs.toLocaleString('pt-BR')}</td>
            <td>
              <div className="row gap-sm">
                <span className="mono">{t.success}%</span>
                <div className="progress" style={{ width: 60 }}>
                  <div className={'progress-bar ' + (t.success < 90 ? 'err' : t.success < 97 ? 'warn' : '')} style={{ width: t.success + '%' }} />
                </div>
              </div>
            </td>
            <td>
              {t.status === 'healthy' && <span className="tag tag-ok tag-dot">healthy</span>}
              {t.status === 'warn' && <span className="tag tag-warn tag-dot">warning</span>}
              {t.status === 'err' && <span className="tag tag-err tag-dot">errors</span>}
              {t.status === 'offline' && <span className="tag tag-dot" style={{color:'var(--text-muted)'}}>offline</span>}
            </td>
            <td className="muted">há {t.lastSeen}</td>
            <td style={{ textAlign: 'right' }}>
              <button className="btn btn-sm btn-ghost" title="Impersonar"><iconify-icon icon="lucide:log-in" /></button>
              <button className="btn btn-sm btn-ghost"><iconify-icon icon="lucide:more-horizontal" /></button>
            </td>
          </tr>
        ))}
      </tbody>
    </table>
  );
}

function AdminPlans() {
  return (
    <div className="fade-up">
      <div className="page-head">
        <div>
          <h1 className="page-title">Planos</h1>
          <p className="page-sub">Configure preços, limites de execuções e disponibilidade.</p>
        </div>
        <div className="page-actions">
          <button className="btn btn-primary"><iconify-icon icon="lucide:plus" />Novo plano</button>
        </div>
      </div>

      <div className="card" style={{ padding: 0, overflow: 'hidden' }}>
        <table className="tbl">
          <thead><tr>
            <th>Nome</th><th>Preço (R$)</th><th>Lojas</th><th>Execuções/mês</th><th>Tenants ativos</th><th>Status</th><th></th>
          </tr></thead>
          <tbody>
            {PLANS.map(p => (
              <tr key={p.id}>
                <td className="strong">{p.name} {p.popular && <span className="tag tag-accent" style={{marginLeft:6}}>popular</span>}</td>
                <td className="mono strong">{p.price},00</td>
                <td className="mono">{p.max_stores}</td>
                <td className="mono">{p.monthly_executions.toLocaleString('pt-BR')}</td>
                <td className="mono">{p.id === 'starter' ? 14 : p.id === 'growth' ? 16 : 2}</td>
                <td><span className="tag tag-ok tag-dot">ativo</span></td>
                <td style={{textAlign:'right'}}>
                  <button className="btn btn-sm"><iconify-icon icon="lucide:edit-3" />Editar</button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

Object.assign(window, { PageAdmin });
