// ============================================================
// Super Admin — Dashboard de Créditos (visão interna Octale)
// MOSTRA custo Jusbrasil, margem e markup — esta é a visão do
// dono da plataforma, não do cliente. 1 crédito = R$1.
// ============================================================

// ─── Helpers de formatação (pt-BR) ────────────────────────────
const scMoney = (v) =>
  'R$ ' + (Number(v) || 0).toLocaleString('pt-BR', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
const scCred = (v) =>
  (Number(v) || 0).toLocaleString('pt-BR', { minimumFractionDigits: 0, maximumFractionDigits: 2 }) + ' créditos';
const scNum = (v) => (Number(v) || 0).toLocaleString('pt-BR');
const scPct = (v) => (Number(v) || 0).toLocaleString('pt-BR', { minimumFractionDigits: 0, maximumFractionDigits: 1 }) + '%';
const scDate = (d) => { try { return d ? new Date(d).toLocaleDateString('pt-BR') : '—'; } catch (e) { return '—'; } };
const scDateTime = (d) => { try { return d ? new Date(d).toLocaleString('pt-BR') : '—'; } catch (e) { return '—'; } };

const SC_SERVICE_LABELS = {
  download_autos: 'Download de autos',
  busca_ativa_oab: 'Busca ativa por OAB',
  consulta_cnj_tribunal: 'Consulta CNJ (Tribunal)',
  consulta_cnj_jus: 'Consulta CNJ (Jus)',
  monitoramento_diarios: 'Monitoramento de diários',
  distribuicao_processos: 'Distribuição de novos processos',
};
const scServiceLabel = (s) => SC_SERVICE_LABELS[s] || s || '—';

const SC_TX_TYPE = { purchase: 'Recarga', debit: 'Débito', refund: 'Estorno', bonus: 'Bônus', expiration: 'Expiração' };
const SC_TX_STATUS = { completed: 'Concluído', cancelled: 'Estornado', pending: 'Pendente' };
const scTxType = (t) => SC_TX_TYPE[t] || t || '—';
const scTxStatus = (s) => SC_TX_STATUS[s] || s || '—';

const SC_PLAN_LABELS = {
  essencial: 'Essencial', starter: 'Starter', pro: 'Pro', business: 'Business',
  trial: 'Trial', enterprise: 'Enterprise',
};
const scPlanLabel = (p) => SC_PLAN_LABELS[p] || p || '—';

const SC_STATUS_COLORS = {
  trial: '#D49A1A', active: '#1F9D55', suspended: '#C2253E', cancelled: '#888',
};
const SC_STATUS_LABELS = {
  trial: 'Trial', active: 'Ativa', suspended: 'Suspensa', cancelled: 'Cancelada',
};

// markup interno = (preço − custo) / custo * 100
const scMarkup = (credits, cost) => {
  const c = Number(cost) || 0;
  const p = Number(credits) || 0;
  if (c <= 0) return '—';
  return Math.round(((p - c) / c) * 100) + '%';
};

// ─── Componentes visuais reutilizáveis ─────────────────────────
const ScCard = ({ children, style }) => (
  <div style={{
    background: '#fff', border: '1px solid var(--border)', borderRadius: 12,
    padding: 18, ...style,
  }}>{children}</div>
);

const ScKpi = ({ label, value, sub, accent, tag }) => (
  <div style={{
    background: '#fff', border: '1px solid var(--border)', borderRadius: 12, padding: 18,
  }}>
    <div style={{
      fontSize: 10.5, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '.07em',
      color: 'var(--fg-muted)', marginBottom: 10, display: 'flex', alignItems: 'center', gap: 6,
    }}>
      {label}
      {tag && (
        <span style={{
          fontSize: 9, fontWeight: 800, padding: '1px 6px', borderRadius: 999,
          background: 'rgba(212,154,26,.15)', color: '#8a6410', letterSpacing: '.04em',
        }}>{tag}</span>
      )}
    </div>
    <div style={{ fontSize: 22, fontWeight: 800, color: accent || 'var(--octale-black)' }}>{value}</div>
    {sub && <div style={{ fontSize: 11, color: 'var(--fg-muted)', marginTop: 4 }}>{sub}</div>}
  </div>
);

const ScSpinner = ({ label = 'Carregando…' }) => (
  <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', height: 180, gap: 12, color: 'var(--fg-muted)', fontSize: 13 }}>
    <div className="spinner" /> {label}
  </div>
);

const ScEmpty = ({ children = 'Sem dados.' }) => (
  <div style={{ textAlign: 'center', padding: '40px 24px', color: 'var(--fg-muted)', fontSize: 13 }}>
    {children}
  </div>
);

const ScSectionTitle = ({ children, style }) => (
  <div style={{ fontSize: 13, fontWeight: 800, color: 'var(--octale-black)', marginBottom: 12, ...style }}>{children}</div>
);

const ScBadge = ({ children, bg = '#888', color = '#fff' }) => (
  <span style={{ fontSize: 10, fontWeight: 700, padding: '2px 8px', borderRadius: 999, background: bg, color }}>{children}</span>
);

// barra de progresso simples
const ScProgress = ({ pct, color = 'var(--octale-neon)', height = 10 }) => {
  const p = Math.max(0, Math.min(100, Number(pct) || 0));
  return (
    <div style={{ background: 'var(--octale-off-white)', borderRadius: 999, height, overflow: 'hidden', width: '100%' }}>
      <div style={{ width: p + '%', height: '100%', background: color, borderRadius: 999, transition: 'width .3s' }} />
    </div>
  );
};

const scGridStyle = { display: 'grid', gap: 14, gridTemplateColumns: 'repeat(auto-fill, minmax(210px, 1fr))' };

// ════════════════════════════════════════════════════════════
// §6.1 — VISÃO GERAL
// ════════════════════════════════════════════════════════════
const ScVisaoGeral = () => {
  const [data, setData] = React.useState(null);
  const [loading, setLoading] = React.useState(true);
  const [err, setErr] = React.useState('');

  React.useEffect(() => {
    let alive = true;
    setLoading(true);
    (async () => {
      try {
        const d = await window.OctaleApi.creditsAdmin.home();
        if (alive) setData(d || {});
      } catch (e) {
        if (alive) setErr(e.message || 'Erro ao carregar visão geral.');
      } finally {
        if (alive) setLoading(false);
      }
    })();
    return () => { alive = false; };
  }, []);

  if (loading) return <ScSpinner />;
  if (err) return <ScEmpty>{err}</ScEmpty>;
  const d = data || {};
  const criticos = Array.isArray(d.criticalTenants) ? d.criticalTenants : [];
  const semRecarga = Array.isArray(d.noRechargeTenants) ? d.noRechargeTenants : [];

  return (
    <div>
      <div style={scGridStyle}>
        <ScKpi label="MRR total" value={scMoney(d.mrr)} sub="Receita recorrente mensal" />
        <ScKpi label="Receita de créditos (mês)" value={scMoney(d.creditRevenue)} />
        <ScKpi label="Custo Jusbrasil (mês)" value={scMoney(d.jusbrasilCost)} accent="#C2253E" sub="Custo de API externo" />
        <ScKpi label="Margem consolidada" value={scMoney(d.margin)} accent="#1F9D55" sub={`Receita total ${scMoney(d.totalRevenue)}`} />
        <ScKpi label="Créditos em circulação" value={scCred(d.creditsInCirculation)} tag="passivo" sub="Saldo não consumido" />
        <ScKpi label="Tenants ativos" value={scNum(d.activeTenants)} />
        <ScKpi label="Estornos" value={scMoney(d.refunds)} accent="#C2253E" />
      </div>

      <div style={{ display: 'grid', gap: 16, gridTemplateColumns: 'repeat(auto-fit, minmax(300px, 1fr))', marginTop: 20 }}>
        <ScCard>
          <ScSectionTitle style={{ color: '#C2253E' }}>Saldo crítico (&lt;20)</ScSectionTitle>
          {criticos.length === 0 ? <ScEmpty>Nenhum tenant em saldo crítico.</ScEmpty> : (
            <div style={{ display: 'grid', gap: 6 }}>
              {criticos.map(t => (
                <div key={t.id} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '8px 12px', borderRadius: 8, background: 'rgba(194,37,62,.06)' }}>
                  <span style={{ fontSize: 13, fontWeight: 600, color: 'var(--octale-black)' }}>{t.name}</span>
                  <span style={{ fontSize: 13, fontWeight: 800, color: '#C2253E' }}>{scCred(t.balance)}</span>
                </div>
              ))}
            </div>
          )}
        </ScCard>

        <ScCard>
          <ScSectionTitle>Sem recarga 60+ dias</ScSectionTitle>
          {semRecarga.length === 0 ? <ScEmpty>Nenhum tenant sem recarga.</ScEmpty> : (
            <div style={{ display: 'grid', gap: 6 }}>
              {semRecarga.map(t => (
                <div key={t.id} style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '8px 12px', borderRadius: 8, background: 'var(--octale-off-white)' }}>
                  <Icon name="bell" size={14} />
                  <span style={{ fontSize: 13, fontWeight: 600, color: 'var(--octale-black)' }}>{t.name}</span>
                </div>
              ))}
            </div>
          )}
        </ScCard>
      </div>
    </div>
  );
};

// ════════════════════════════════════════════════════════════
// §6.2 — POR TENANT
// ════════════════════════════════════════════════════════════
const ScTenantTransactions = ({ tenantId }) => {
  const [state, setState] = React.useState({ rows: [], total: 0, page: 1, hasMore: false, loading: true });

  const load = React.useCallback((page) => {
    setState(s => ({ ...s, loading: true }));
    (async () => {
      try {
        const r = await window.OctaleApi.creditsAdmin.tenantTransactions(tenantId, { page, limit: 20 });
        setState({
          rows: Array.isArray(r?.data) ? r.data : [],
          total: r?.total || 0,
          page: r?.page || page,
          hasMore: !!r?.hasMore,
          loading: false,
        });
      } catch (e) {
        setState({ rows: [], total: 0, page, hasMore: false, loading: false });
      }
    })();
  }, [tenantId]);

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

  if (state.loading && state.rows.length === 0) return <ScSpinner label="Carregando transações…" />;
  if (state.rows.length === 0) return <ScEmpty>Nenhuma transação registrada.</ScEmpty>;

  return (
    <div>
      <div style={{ overflowX: 'auto' }}>
        <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 12 }}>
          <thead>
            <tr>
              {['Data', 'Tipo', 'Serviço', 'Valor', 'Saldo', 'Status'].map(h => (
                <th key={h} style={{ textAlign: 'left', fontSize: 10, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '.05em', color: 'var(--fg-muted)', padding: '7px 8px', borderBottom: '1px solid var(--border)', whiteSpace: 'nowrap' }}>{h}</th>
              ))}
            </tr>
          </thead>
          <tbody>
            {state.rows.map((tx, i) => (
              <tr key={i}>
                <td style={{ padding: '7px 8px', borderBottom: '1px solid var(--border)', whiteSpace: 'nowrap', color: 'var(--fg-muted)' }}>{scDateTime(tx.created_at)}</td>
                <td style={{ padding: '7px 8px', borderBottom: '1px solid var(--border)' }}>{scTxType(tx.type)}</td>
                <td style={{ padding: '7px 8px', borderBottom: '1px solid var(--border)' }}>{tx.service ? scServiceLabel(tx.service) : '—'}</td>
                <td style={{ padding: '7px 8px', borderBottom: '1px solid var(--border)', textAlign: 'right', fontWeight: 700, color: (Number(tx.amount) || 0) < 0 ? '#C2253E' : '#1F9D55', whiteSpace: 'nowrap' }}>
                  {(Number(tx.amount) || 0) > 0 ? '+' : ''}{scCred(tx.amount)}
                </td>
                <td style={{ padding: '7px 8px', borderBottom: '1px solid var(--border)', textAlign: 'right', whiteSpace: 'nowrap' }}>{scCred(tx.balance_after)}</td>
                <td style={{ padding: '7px 8px', borderBottom: '1px solid var(--border)' }}>{scTxStatus(tx.status)}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: 10 }}>
        <span style={{ fontSize: 11.5, color: 'var(--fg-muted)' }}>
          Página {state.page} · {scNum(state.total)} transaç{state.total === 1 ? 'ão' : 'ões'}
        </span>
        <div style={{ display: 'flex', gap: 6 }}>
          <button className="btn ghost sm" disabled={state.page <= 1 || state.loading} onClick={() => load(state.page - 1)}>Anterior</button>
          <button className="btn ghost sm" disabled={!state.hasMore || state.loading} onClick={() => load(state.page + 1)}>Próxima</button>
        </div>
      </div>
    </div>
  );
};

const ScTenantDetail = ({ tenantId }) => {
  const [data, setData] = React.useState(null);
  const [loading, setLoading] = React.useState(true);
  const [err, setErr] = React.useState('');

  React.useEffect(() => {
    let alive = true;
    setLoading(true); setErr('');
    (async () => {
      try {
        const d = await window.OctaleApi.creditsAdmin.tenant(tenantId);
        if (alive) setData(d || {});
      } catch (e) {
        if (alive) setErr(e.message || 'Erro ao carregar tenant.');
      } finally {
        if (alive) setLoading(false);
      }
    })();
    return () => { alive = false; };
  }, [tenantId]);

  if (loading) return <ScSpinner label="Carregando tenant…" />;
  if (err) return <ScEmpty>{err}</ScEmpty>;
  const d = data || {};
  const org = d.organization || {};
  const wallet = d.wallet || {};
  const quotas = Array.isArray(d.quotas) ? d.quotas : [];

  return (
    <div style={{ display: 'grid', gap: 16 }}>
      <ScCard>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexWrap: 'wrap', gap: 8 }}>
          <div>
            <div style={{ fontSize: 16, fontWeight: 800, color: 'var(--octale-black)' }}>{org.name || 'Tenant'}</div>
            <div style={{ fontSize: 12, color: 'var(--fg-muted)', marginTop: 2 }}>
              Plano {scPlanLabel(org.plan)}
              {org.renews_at && <> · renova {scDate(org.renews_at)}</>}
              {org.renewal && <> · renova {scDate(org.renewal)}</>}
            </div>
          </div>
          <div style={{ textAlign: 'right' }}>
            <div style={{ fontSize: 10.5, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '.06em', color: 'var(--fg-muted)' }}>Saldo</div>
            <div style={{ fontSize: 20, fontWeight: 800, color: 'var(--octale-black)' }}>{scCred(wallet.balance)}</div>
          </div>
        </div>
      </ScCard>

      <div style={scGridStyle}>
        <ScKpi label="Créditos debitados (mês)" value={scCred(d.creditsDebited)} />
        <ScKpi label="Custo Jusbrasil" value={scMoney(d.jusbrasilCost)} accent="#C2253E" />
        <ScKpi label="Receita" value={scMoney(d.revenue)} />
        <ScKpi label="Margem" value={scMoney(d.margin)} accent="#1F9D55" />
      </div>

      <ScCard>
        <ScSectionTitle>Consumo por serviço (quota)</ScSectionTitle>
        {quotas.length === 0 ? <ScEmpty>Sem quotas configuradas.</ScEmpty> : (
          <div style={{ display: 'grid', gap: 12 }}>
            {quotas.map((q, i) => {
              const limit = Number(q.quota_limit) || 0;
              const used = Number(q.consumed) || 0;
              const pct = limit > 0 ? (used / limit) * 100 : 0;
              const over = limit > 0 && used > limit;
              return (
                <div key={i}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12, marginBottom: 4 }}>
                    <span style={{ fontWeight: 600, color: 'var(--octale-black)' }}>{scServiceLabel(q.service)}</span>
                    <span style={{ color: over ? '#C2253E' : 'var(--fg-muted)', fontWeight: over ? 700 : 400 }}>
                      {scNum(used)} / {limit > 0 ? scNum(limit) : '∞'}
                    </span>
                  </div>
                  <ScProgress pct={pct} color={over ? '#C2253E' : 'var(--octale-neon)'} height={8} />
                </div>
              );
            })}
          </div>
        )}
      </ScCard>

      <ScCard>
        <ScSectionTitle>Transações recentes</ScSectionTitle>
        <ScTenantTransactions tenantId={tenantId} />
      </ScCard>
    </div>
  );
};

const ScPorTenant = () => {
  const [tenants, setTenants] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [err, setErr] = React.useState('');
  const [selected, setSelected] = React.useState(null);
  const [q, setQ] = React.useState('');

  React.useEffect(() => {
    let alive = true;
    setLoading(true);
    (async () => {
      try {
        const list = await window.OctaleApi.creditsAdmin.tenants();
        if (alive) setTenants(Array.isArray(list) ? list : []);
      } catch (e) {
        if (alive) setErr(e.message || 'Erro ao carregar tenants.');
      } finally {
        if (alive) setLoading(false);
      }
    })();
    return () => { alive = false; };
  }, []);

  const filtered = q.trim()
    ? tenants.filter(t => (t.name || '').toLowerCase().includes(q.trim().toLowerCase()))
    : tenants;

  return (
    <div style={{ display: 'grid', gridTemplateColumns: '320px 1fr', gap: 16, alignItems: 'start' }}>
      <ScCard style={{ padding: 14 }}>
        <div style={{ position: 'relative', marginBottom: 12 }}>
          <span style={{ position: 'absolute', left: 10, top: '50%', transform: 'translateY(-50%)', color: 'var(--fg-muted)', display: 'flex' }}>
            <Icon name="search" size={14} />
          </span>
          <input
            value={q}
            onChange={e => setQ(e.target.value)}
            placeholder="Buscar tenant…"
            style={{ width: '100%', boxSizing: 'border-box', padding: '8px 10px 8px 30px', borderRadius: 8, border: '1px solid var(--border)', fontSize: 13 }}
          />
        </div>
        {loading ? <ScSpinner label="Carregando…" /> : err ? <ScEmpty>{err}</ScEmpty> : filtered.length === 0 ? <ScEmpty>Nenhum tenant.</ScEmpty> : (
          <div style={{ display: 'grid', gap: 6, maxHeight: 620, overflowY: 'auto' }}>
            {filtered.map(t => {
              const active = selected === t.id;
              return (
                <button
                  key={t.id}
                  onClick={() => setSelected(t.id)}
                  style={{
                    textAlign: 'left', cursor: 'pointer', border: '1px solid ' + (active ? 'var(--octale-navy)' : 'var(--border)'),
                    background: active ? 'var(--octale-off-white)' : '#fff', borderRadius: 10, padding: '10px 12px',
                    display: 'flex', flexDirection: 'column', gap: 4,
                  }}
                >
                  <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8 }}>
                    <span style={{ fontWeight: 700, fontSize: 13, color: 'var(--octale-black)' }}>{t.name}</span>
                    <ScBadge bg={SC_STATUS_COLORS[t.status] || '#888'}>{SC_STATUS_LABELS[t.status] || t.status}</ScBadge>
                  </div>
                  <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', fontSize: 11.5, color: 'var(--fg-muted)' }}>
                    <span>{scPlanLabel(t.plan)}</span>
                    <span style={{ fontWeight: 700, color: (Number(t.balance) || 0) < 20 ? '#C2253E' : 'var(--octale-black)' }}>{scCred(t.balance)}</span>
                  </div>
                </button>
              );
            })}
          </div>
        )}
      </ScCard>

      <div>
        {selected ? <ScTenantDetail tenantId={selected} /> : (
          <ScCard><ScEmpty>Selecione um tenant à esquerda para ver os detalhes.</ScEmpty></ScCard>
        )}
      </div>
    </div>
  );
};

// ════════════════════════════════════════════════════════════
// §6.3 — POR SERVIÇO
// ════════════════════════════════════════════════════════════
const ScPorServico = () => {
  const [data, setData] = React.useState(null);
  const [loading, setLoading] = React.useState(true);
  const [err, setErr] = React.useState('');
  const [sort, setSort] = React.useState({ key: null, dir: 1 });

  React.useEffect(() => {
    let alive = true;
    setLoading(true);
    (async () => {
      try {
        const d = await window.OctaleApi.creditsAdmin.byService();
        if (alive) setData(d || {});
      } catch (e) {
        if (alive) setErr(e.message || 'Erro ao carregar serviços.');
      } finally {
        if (alive) setLoading(false);
      }
    })();
    return () => { alive = false; };
  }, []);

  if (loading) return <ScSpinner />;
  if (err) return <ScEmpty>{err}</ScEmpty>;
  const d = data || {};
  const services = Array.isArray(d.services) ? d.services.slice() : [];

  if (sort.key) {
    services.sort((a, b) => {
      const va = a[sort.key], vb = b[sort.key];
      if (typeof va === 'number' || typeof vb === 'number') return ((Number(va) || 0) - (Number(vb) || 0)) * sort.dir;
      return String(va || '').localeCompare(String(vb || '')) * sort.dir;
    });
  }

  const toggleSort = (key) => setSort(s => s.key === key ? { key, dir: -s.dir } : { key, dir: 1 });

  const cols = [
    { key: 'service', label: 'Serviço', align: 'left', render: (r) => scServiceLabel(r.service) },
    { key: 'calls', label: 'Chamadas', align: 'right', render: (r) => scNum(r.calls) },
    { key: 'revenue', label: 'Receita (créditos)', align: 'right', render: (r) => scCred(r.revenue) },
    { key: 'cost', label: 'Custo Jusbrasil', align: 'right', render: (r) => scMoney(r.cost) },
    { key: 'margin', label: 'Margem', align: 'right', render: (r) => scMoney(r.margin) },
    { key: 'excess', label: 'Excedente', align: 'right', render: (r) => scNum(r.excess) },
    { key: 'failureRate', label: 'Taxa de falha', align: 'right', render: (r) => scPct(r.failureRate) },
  ];

  const svcByKey = (k) => (d.services || []).find(s => s.service === k) || null;

  const callout = (title, item, valFn, color) => (
    <ScCard style={{ padding: 14 }}>
      <div style={{ fontSize: 10.5, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '.06em', color: 'var(--fg-muted)', marginBottom: 6 }}>{title}</div>
      {item ? (
        <>
          <div style={{ fontSize: 14, fontWeight: 800, color: 'var(--octale-black)' }}>{scServiceLabel(item.service)}</div>
          <div style={{ fontSize: 12, fontWeight: 700, color: color || 'var(--fg-muted)', marginTop: 2 }}>{valFn(item)}</div>
        </>
      ) : <div style={{ fontSize: 12, color: 'var(--fg-muted)' }}>—</div>}
    </ScCard>
  );

  return (
    <div>
      <div style={{ display: 'grid', gap: 14, gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))', marginBottom: 18 }}>
        {callout('Maior volume', svcByKey(d.topByVolume), (i) => scNum(i.calls) + ' chamadas', 'var(--octale-black)')}
        {callout('Maior excedente', svcByKey(d.topByExcess), (i) => scNum(i.excess) + ' excedentes', '#D49A1A')}
        {callout('Maior taxa de falha', svcByKey(d.topByFailure), (i) => scPct(i.failureRate), '#C2253E')}
      </div>

      <ScCard style={{ padding: 0, overflow: 'hidden' }}>
        {services.length === 0 ? <ScEmpty>Nenhum serviço com dados.</ScEmpty> : (
          <div style={{ overflowX: 'auto' }}>
            <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 12.5 }}>
              <thead>
                <tr>
                  {cols.map(c => (
                    <th key={c.key} onClick={() => toggleSort(c.key)} style={{
                      textAlign: c.align, fontSize: 10, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '.05em',
                      color: 'var(--fg-muted)', padding: '10px 12px', borderBottom: '1px solid var(--border)', whiteSpace: 'nowrap', cursor: 'pointer', userSelect: 'none',
                    }}>
                      {c.label}{sort.key === c.key ? (sort.dir === 1 ? ' ▲' : ' ▼') : ''}
                    </th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {services.map((r, i) => (
                  <tr key={r.service || i}>
                    {cols.map(c => (
                      <td key={c.key} style={{
                        textAlign: c.align, padding: '9px 12px', borderBottom: '1px solid var(--border)', whiteSpace: 'nowrap',
                        fontWeight: c.key === 'service' ? 600 : 400,
                        color: c.key === 'margin' ? '#1F9D55' : c.key === 'cost' ? '#C2253E' : c.key === 'failureRate' && (Number(r.failureRate) || 0) >= 10 ? '#C2253E' : 'var(--octale-black)',
                      }}>{c.render(r)}</td>
                    ))}
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </ScCard>
    </div>
  );
};

// ════════════════════════════════════════════════════════════
// §6.4 — FINANCEIRO
// ════════════════════════════════════════════════════════════
const ScFinanceiro = () => {
  const [data, setData] = React.useState(null);
  const [loading, setLoading] = React.useState(true);
  const [err, setErr] = React.useState('');

  React.useEffect(() => {
    let alive = true;
    setLoading(true);
    (async () => {
      try {
        const d = await window.OctaleApi.creditsAdmin.financial();
        if (alive) setData(d || {});
      } catch (e) {
        if (alive) setErr(e.message || 'Erro ao carregar financeiro.');
      } finally {
        if (alive) setLoading(false);
      }
    })();
    return () => { alive = false; };
  }, []);

  if (loading) return <ScSpinner />;
  if (err) return <ScEmpty>{err}</ScEmpty>;
  const d = data || {};
  const topPkg = d.topPackage;
  const topPkgLabel = topPkg ? (typeof topPkg === 'string' ? topPkg : (topPkg.label || topPkg.id || '—')) : '—';

  return (
    <div style={scGridStyle}>
      <ScKpi label="Créditos vendidos" value={scCred(d.creditsSold)} />
      <ScKpi label="Receita de recargas" value={scMoney(d.revenueSold)} accent="#1F9D55" />
      <ScKpi label="Créditos debitados" value={scCred(d.creditsDebited)} />
      <ScKpi label="Créditos em saldo" value={scCred(d.creditsInBalance)} tag="passivo" />
      <ScKpi label="Ticket médio" value={scMoney(d.avgTicket)} />
      <ScKpi label="Pacote mais vendido" value={topPkgLabel} sub={topPkg && topPkg.amount_brl ? scMoney(topPkg.amount_brl) : undefined} />
      <ScKpi label="ARPU" value={scMoney(d.arpu)} sub="Receita média por tenant" />
      <ScKpi label="Conversão franquia → crédito" value={scPct(d.conversionRate)} />
      <ScKpi label="Estornos" value={scMoney(d.refunds)} accent="#C2253E" />
    </div>
  );
};

// ════════════════════════════════════════════════════════════
// §6.5 — SAÚDE API
// ════════════════════════════════════════════════════════════
const ScSaudeApi = () => {
  const [data, setData] = React.useState(null);
  const [loading, setLoading] = React.useState(true);
  const [err, setErr] = React.useState('');

  React.useEffect(() => {
    let alive = true;
    setLoading(true);
    (async () => {
      try {
        const d = await window.OctaleApi.creditsAdmin.apiHealth();
        if (alive) setData(d || {});
      } catch (e) {
        if (alive) setErr(e.message || 'Erro ao carregar saúde da API.');
      } finally {
        if (alive) setLoading(false);
      }
    })();
    return () => { alive = false; };
  }, []);

  if (loading) return <ScSpinner />;
  if (err) return <ScEmpty>{err}</ScEmpty>;
  const d = data || {};
  const nearTier2 = Array.isArray(d.nearTier2) ? d.nearTier2 : [];
  const successRate = Number(d.successRate) || 0;

  return (
    <div style={{ display: 'grid', gap: 16 }}>
      <div style={scGridStyle}>
        <ScKpi label="Taxa de sucesso" value={scPct(d.successRate)} accent={successRate >= 95 ? '#1F9D55' : successRate >= 85 ? '#D49A1A' : '#C2253E'} sub={`${scNum(d.total)} chamadas totais`} />
        <ScKpi label="Chamadas com erro" value={scNum((Number(d.errors) || 0) + (Number(d.timeouts) || 0))} accent="#C2253E" sub={`${scNum(d.errors)} erros · ${scNum(d.timeouts)} timeouts`} />
        <ScKpi label="Estornos" value={scMoney(d.refunds)} accent="#C2253E" />
        <ScKpi label="Latência média" value={scNum(d.avgLatency) + ' ms'} />
      </div>

      <ScCard>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 10, flexWrap: 'wrap', gap: 8 }}>
          <ScSectionTitle style={{ margin: 0 }}>Faturamento mínimo Jusbrasil (R$ 1.000)</ScSectionTitle>
          <span style={{ fontSize: 12, color: 'var(--fg-muted)' }}>
            {scMoney(d.jusbrasilSpend)} de {scMoney(d.jusbrasilMinimum || 1000)}
          </span>
        </div>
        <ScProgress pct={d.jusbrasilMinimumProgress} color={(Number(d.jusbrasilMinimumProgress) || 0) >= 100 ? '#1F9D55' : 'var(--octale-neon)'} />
        <div style={{ fontSize: 11.5, color: 'var(--fg-muted)', marginTop: 6 }}>{scPct(d.jusbrasilMinimumProgress)} do mínimo atingido</div>
      </ScCard>

      <ScCard>
        <ScSectionTitle>Aproximação da 2ª faixa</ScSectionTitle>
        {nearTier2.length === 0 ? <ScEmpty>Nenhum serviço próximo da 2ª faixa.</ScEmpty> : (
          <div style={{ display: 'grid', gap: 8 }}>
            {nearTier2.map((s, i) => {
              const vol = Number(s.volume) || 0;
              const warn = vol >= 1800;
              return (
                <div key={i} style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '9px 12px', borderRadius: 8, background: warn ? 'rgba(212,154,26,.1)' : 'var(--octale-off-white)' }}>
                  <span style={{ fontSize: 13, fontWeight: 600, color: 'var(--octale-black)', display: 'flex', alignItems: 'center', gap: 8 }}>
                    {warn && <Icon name="bell" size={14} />}
                    {scServiceLabel(s.service)}
                  </span>
                  <span style={{ fontSize: 13, fontWeight: 700, color: warn ? '#8a6410' : 'var(--fg-muted)' }}>{scNum(vol)} chamadas</span>
                </div>
              );
            })}
          </div>
        )}
      </ScCard>
    </div>
  );
};

// ════════════════════════════════════════════════════════════
// §6.6 — CONFIG & EXPORTAÇÕES
// ════════════════════════════════════════════════════════════
const ScPriceRow = ({ price, onSaved }) => {
  const [credits, setCredits] = React.useState(String(price.credits_per_unit ?? ''));
  const [cost, setCost] = React.useState(String(price.jusbrasil_cost ?? ''));
  const [active, setActive] = React.useState(!!price.active);
  const [saving, setSaving] = React.useState(false);
  const [msg, setMsg] = React.useState('');

  const dirty =
    String(price.credits_per_unit ?? '') !== credits ||
    String(price.jusbrasil_cost ?? '') !== cost ||
    !!price.active !== active;

  const save = async () => {
    setSaving(true); setMsg('');
    try {
      await window.OctaleApi.creditsAdmin.updatePrice(price.service, {
        credits_per_unit: Number(credits) || 0,
        jusbrasil_cost: Number(cost) || 0,
        active,
      });
      setMsg('ok');
      if (onSaved) onSaved(price.service, { credits_per_unit: Number(credits) || 0, jusbrasil_cost: Number(cost) || 0, active });
      setTimeout(() => setMsg(''), 2500);
    } catch (e) {
      setMsg('err');
    } finally {
      setSaving(false);
    }
  };

  const inputStyle = { width: 90, boxSizing: 'border-box', padding: '5px 8px', borderRadius: 6, border: '1px solid var(--border)', fontSize: 12.5, textAlign: 'right' };

  return (
    <tr>
      <td style={{ padding: '9px 12px', borderBottom: '1px solid var(--border)', fontWeight: 600, color: 'var(--octale-black)' }}>{price.label || scServiceLabel(price.service)}</td>
      <td style={{ padding: '9px 12px', borderBottom: '1px solid var(--border)', color: 'var(--fg-muted)', fontSize: 12 }}>{price.unit_label || '—'}</td>
      <td style={{ padding: '9px 12px', borderBottom: '1px solid var(--border)', textAlign: 'right' }}>
        <input type="number" min="0" step="0.01" value={credits} onChange={e => setCredits(e.target.value)} style={inputStyle} />
      </td>
      <td style={{ padding: '9px 12px', borderBottom: '1px solid var(--border)', textAlign: 'right' }}>
        <input type="number" min="0" step="0.01" value={cost} onChange={e => setCost(e.target.value)} style={inputStyle} />
      </td>
      <td style={{ padding: '9px 12px', borderBottom: '1px solid var(--border)', textAlign: 'right', fontWeight: 700, color: 'var(--octale-black)' }}>
        {scMarkup(credits, cost)}
      </td>
      <td style={{ padding: '9px 12px', borderBottom: '1px solid var(--border)', textAlign: 'center' }}>
        <button
          type="button"
          onClick={() => setActive(a => !a)}
          title={active ? 'Ativo' : 'Inativo'}
          style={{ width: 34, height: 18, borderRadius: 9, border: 'none', cursor: 'pointer', position: 'relative', background: active ? 'var(--octale-navy)' : '#d1d5db' }}
        >
          <span style={{ position: 'absolute', top: 2, left: active ? 18 : 2, width: 14, height: 14, borderRadius: '50%', background: '#fff', transition: 'left .2s' }} />
        </button>
      </td>
      <td style={{ padding: '9px 12px', borderBottom: '1px solid var(--border)', textAlign: 'right', whiteSpace: 'nowrap' }}>
        <button className="btn sm" disabled={saving || !dirty} onClick={save}>
          {saving ? 'Salvando…' : 'Salvar'}
        </button>
        {msg === 'ok' && <span style={{ marginLeft: 8, color: '#1F9D55', display: 'inline-flex', verticalAlign: 'middle' }}><Icon name="check" size={14} /></span>}
        {msg === 'err' && <span style={{ marginLeft: 8, color: '#C2253E', fontSize: 11 }}>erro</span>}
      </td>
    </tr>
  );
};

const ScConfig = () => {
  const [data, setData] = React.useState(null);
  const [loading, setLoading] = React.useState(true);
  const [err, setErr] = React.useState('');

  React.useEffect(() => {
    let alive = true;
    setLoading(true);
    (async () => {
      try {
        const d = await window.OctaleApi.creditsAdmin.config();
        if (alive) setData(d || {});
      } catch (e) {
        if (alive) setErr(e.message || 'Erro ao carregar configuração.');
      } finally {
        if (alive) setLoading(false);
      }
    })();
    return () => { alive = false; };
  }, []);

  const exportTypes = [
    { type: 'consumption-by-tenant', label: 'Consumo por tenant' },
    { type: 'api-calls', label: 'Log de chamadas API' },
    { type: 'refunds', label: 'Estornos' },
    { type: 'open-balance', label: 'Saldo em aberto' },
  ];

  const doExport = (type, format) => {
    try {
      const url = window.OctaleApi.creditsAdmin.exportUrl(type, format);
      if (url) window.open(url, '_blank');
    } catch (e) { /* silencioso */ }
  };

  if (loading) return <ScSpinner />;
  if (err) return <ScEmpty>{err}</ScEmpty>;
  const d = data || {};
  const prices = Array.isArray(d.prices) ? d.prices : [];
  const packages = Array.isArray(d.packages) ? d.packages : [];
  const plans = Array.isArray(d.plans) ? d.plans : [];

  const th = { textAlign: 'left', fontSize: 10, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '.05em', color: 'var(--fg-muted)', padding: '10px 12px', borderBottom: '1px solid var(--border)', whiteSpace: 'nowrap' };

  return (
    <div style={{ display: 'grid', gap: 20 }}>
      <ScCard style={{ padding: 0, overflow: 'hidden' }}>
        <div style={{ padding: '14px 18px', borderBottom: '1px solid var(--border)' }}>
          <ScSectionTitle style={{ margin: 0 }}>Preços por serviço</ScSectionTitle>
          <div style={{ fontSize: 11.5, color: 'var(--fg-muted)', marginTop: 2 }}>Markup = (preço − custo) / custo. Visão interna.</div>
        </div>
        {prices.length === 0 ? <ScEmpty>Nenhum preço configurado.</ScEmpty> : (
          <div style={{ overflowX: 'auto' }}>
            <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 12.5 }}>
              <thead>
                <tr>
                  <th style={th}>Serviço</th>
                  <th style={th}>Unidade</th>
                  <th style={{ ...th, textAlign: 'right' }}>Créditos/unid.</th>
                  <th style={{ ...th, textAlign: 'right' }}>Custo Jusbrasil</th>
                  <th style={{ ...th, textAlign: 'right' }}>Markup</th>
                  <th style={{ ...th, textAlign: 'center' }}>Ativo</th>
                  <th style={{ ...th, textAlign: 'right' }}></th>
                </tr>
              </thead>
              <tbody>
                {prices.map((p, i) => <ScPriceRow key={p.service || i} price={p} />)}
              </tbody>
            </table>
          </div>
        )}
      </ScCard>

      <ScCard>
        <ScSectionTitle>Pacotes de crédito</ScSectionTitle>
        {packages.length === 0 ? <ScEmpty>Nenhum pacote.</ScEmpty> : (
          <div style={{ display: 'grid', gap: 10, gridTemplateColumns: 'repeat(auto-fill, minmax(200px, 1fr))' }}>
            {packages.map((pk, i) => (
              <div key={pk.id || i} style={{ border: '1px solid var(--border)', borderRadius: 10, padding: 14 }}>
                <div style={{ fontWeight: 800, fontSize: 14, color: 'var(--octale-black)' }}>{pk.label || pk.id}</div>
                <div style={{ fontSize: 12, color: 'var(--fg-muted)', marginTop: 4 }}>
                  {scCred(pk.credits)}{pk.bonus ? ` + ${scNum(pk.bonus)} bônus` : ''}
                </div>
                <div style={{ fontSize: 16, fontWeight: 800, color: 'var(--octale-navy)', marginTop: 6 }}>{scMoney(pk.amount_brl)}</div>
              </div>
            ))}
          </div>
        )}
      </ScCard>

      <ScCard style={{ padding: 0, overflow: 'hidden' }}>
        <div style={{ padding: '14px 18px', borderBottom: '1px solid var(--border)' }}>
          <ScSectionTitle style={{ margin: 0 }}>Planos</ScSectionTitle>
        </div>
        {plans.length === 0 ? <ScEmpty>Nenhum plano.</ScEmpty> : (
          <div style={{ overflowX: 'auto' }}>
            <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 12.5 }}>
              <thead>
                <tr>
                  <th style={th}>Plano</th>
                  <th style={{ ...th, textAlign: 'right' }}>Preço</th>
                  <th style={{ ...th, textAlign: 'right' }}>Usuários</th>
                  <th style={th}>Quotas</th>
                </tr>
              </thead>
              <tbody>
                {plans.map((pl, i) => (
                  <tr key={pl.plan_id || i}>
                    <td style={{ padding: '9px 12px', borderBottom: '1px solid var(--border)', fontWeight: 600, color: 'var(--octale-black)' }}>{pl.label || scPlanLabel(pl.plan_id)}</td>
                    <td style={{ padding: '9px 12px', borderBottom: '1px solid var(--border)', textAlign: 'right' }}>{scMoney(pl.price_brl)}</td>
                    <td style={{ padding: '9px 12px', borderBottom: '1px solid var(--border)', textAlign: 'right' }}>{pl.users_limit != null ? scNum(pl.users_limit) : '∞'}</td>
                    <td style={{ padding: '9px 12px', borderBottom: '1px solid var(--border)', color: 'var(--fg-muted)', fontSize: 11.5 }}>
                      {pl.quotas && typeof pl.quotas === 'object'
                        ? Object.entries(pl.quotas).map(([k, v]) => `${scServiceLabel(k)}: ${scNum(v)}`).join(' · ')
                        : '—'}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </ScCard>

      <ScCard>
        <ScSectionTitle>Exportações</ScSectionTitle>
        <div style={{ display: 'grid', gap: 10 }}>
          {exportTypes.map(ex => (
            <div key={ex.type} style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexWrap: 'wrap', gap: 8, padding: '10px 12px', borderRadius: 8, background: 'var(--octale-off-white)' }}>
              <span style={{ fontSize: 13, fontWeight: 600, color: 'var(--octale-black)', display: 'flex', alignItems: 'center', gap: 8 }}>
                <Icon name="fileText" size={15} /> {ex.label}
              </span>
              <div style={{ display: 'flex', gap: 6 }}>
                <button className="btn ghost sm" onClick={() => doExport(ex.type, 'csv')}>CSV</button>
                <button className="btn ghost sm" onClick={() => doExport(ex.type, 'xlsx')}>XLSX</button>
              </div>
            </div>
          ))}
        </div>
      </ScCard>
    </div>
  );
};

// ════════════════════════════════════════════════════════════
// RAIZ — SuperAdminCredits (nav de sub-abas)
// ════════════════════════════════════════════════════════════
const SC_SUBTABS = [
  { id: 'overview', label: 'Visão Geral', icon: 'trendingUp' },
  { id: 'tenant', label: 'Por Tenant', icon: 'building' },
  { id: 'service', label: 'Por Serviço', icon: 'coins' },
  { id: 'financial', label: 'Financeiro', icon: 'creditCard' },
  { id: 'health', label: 'Saúde API', icon: 'bell' },
  { id: 'config', label: 'Config & Exportações', icon: 'settings' },
];

const SuperAdminCredits = () => {
  const [sub, setSub] = React.useState('overview');

  const renderSub = () => {
    switch (sub) {
      case 'overview': return <ScVisaoGeral />;
      case 'tenant': return <ScPorTenant />;
      case 'service': return <ScPorServico />;
      case 'financial': return <ScFinanceiro />;
      case 'health': return <ScSaudeApi />;
      case 'config': return <ScConfig />;
      default: return <ScVisaoGeral />;
    }
  };

  return (
    <div>
      <div style={{
        display: 'flex', gap: 2, background: 'var(--octale-off-white)', borderRadius: 10, padding: 4,
        marginBottom: 24, width: 'fit-content', maxWidth: '100%', flexWrap: 'wrap',
      }}>
        {SC_SUBTABS.map(t => {
          const active = sub === t.id;
          return (
            <button
              key={t.id}
              onClick={() => setSub(t.id)}
              style={{
                display: 'flex', alignItems: 'center', gap: 6, padding: '7px 14px', borderRadius: 7, border: 'none',
                background: active ? '#fff' : 'transparent', color: active ? 'var(--octale-navy)' : 'var(--fg-muted)',
                fontSize: 12.5, fontWeight: active ? 700 : 500, cursor: 'pointer', whiteSpace: 'nowrap',
                boxShadow: active ? '0 1px 4px rgba(0,0,0,.08)' : 'none',
              }}
            >
              <Icon name={t.icon} size={14} /> {t.label}
            </button>
          );
        })}
      </div>

      {renderSub()}
    </div>
  );
};

window.SuperAdminCredits = SuperAdminCredits;
