// Painel SUPERADMIN — visível só pra usuários role=SUPERADMIN.
// Gerencia tipos de perícia (bancária, veicular, tributária, cartão RMC, etc.)
// e versiona prompts/templates/fórmulas.

function AdminPanel() {
  const [types, setTypes] = useState([]);
  const [loading, setLoading] = useState(true);
  const [err, setErr] = useState(null);
  const [selectedTypeId, setSelectedTypeId] = useState(null);
  const [showNewType, setShowNewType] = useState(false);

  const reloadTypes = async () => {
    setLoading(true);
    setErr(null);
    try {
      const res = await window.apiFetch('/admin/pericia-types');
      if (!res.ok) throw new Error(`HTTP ${res.status}`);
      setTypes(await res.json());
    } catch (e) {
      setErr(`Não foi possível carregar tipos de perícia: ${e.message}`);
    } finally {
      setLoading(false);
    }
  };

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

  return (
    <div className="px-4 sm:px-8 py-5 sm:py-7 max-w-[1280px] mx-auto">
      <div className="flex flex-wrap items-end justify-between gap-4 mb-5">
        <div>
          <h1 className="text-[22px] font-bold text-ink-900 tracking-tightish">Painel administrativo</h1>
          <p className="mt-1 text-[13px] text-ink-500">
            Gerencie tipos de perícia e versione prompts, planilhas e fórmulas da metodologia.
          </p>
        </div>
        <Button onClick={() => setShowNewType(true)}><Icon.Plus /> Nova perícia</Button>
      </div>

      {err && (
        <div className="mb-4 rounded-md border border-danger-200 bg-danger-50 px-3 py-2.5 text-[13px] text-danger-700 flex items-start gap-2">
          <span className="mt-0.5"><Icon.Alert /></span>
          <span>{err}</span>
        </div>
      )}

      {selectedTypeId ? (
        <PericiaTypeDetail
          typeId={selectedTypeId}
          onBack={() => { setSelectedTypeId(null); reloadTypes(); }}
        />
      ) : (
        <PericiaTypesList
          types={types}
          loading={loading}
          onOpen={setSelectedTypeId}
        />
      )}

      <NewPericiaTypeModal
        open={showNewType}
        onClose={() => setShowNewType(false)}
        onCreated={() => { setShowNewType(false); reloadTypes(); }}
      />
    </div>
  );
}

// ─── Lista de tipos ───────────────────────────────────────────────────────────
function PericiaTypesList({ types, loading, onOpen }) {
  if (loading) {
    return (
      <div className="bg-white rounded-lg border border-ink-200 shadow-card px-6 py-14 text-center text-ink-500 text-[13px]">
        <Spinner /> Carregando tipos de perícia…
      </div>
    );
  }
  if (!types.length) {
    return (
      <div className="bg-white rounded-lg border border-dashed border-ink-300 px-6 py-14 text-center">
        <div className="text-[14px] text-ink-700 font-medium mb-1">Nenhum tipo de perícia cadastrado.</div>
        <div className="text-[12.5px] text-ink-500">Clique em "Nova perícia" pra criar o primeiro (ex.: bancária, tributária, cartão RMC).</div>
      </div>
    );
  }
  return (
    <>
      {/* Mobile: cards stackados */}
      <div className="sm:hidden bg-white rounded-lg border border-ink-200 shadow-card divide-y divide-ink-100">
        {types.map((t) => (
          <button
            key={t.id}
            onClick={() => onOpen(t.id)}
            className="w-full text-left px-4 py-3 flex items-start gap-3 active:bg-ink-50"
          >
            <div className="flex-1 min-w-0">
              <div className="flex items-center justify-between gap-2 mb-1">
                <div className="text-[14px] text-ink-900 font-semibold truncate">{t.label}</div>
                <span className={`inline-flex items-center rounded-full border px-1.5 py-0 text-[10.5px] font-medium shrink-0 ${
                  t.status === 'ACTIVE' ? 'bg-ok-50 text-ok-700 border-ok-200' : 'bg-ink-100 text-ink-700 border-ink-200'
                }`}>{t.status}</span>
              </div>
              <div className="flex flex-wrap items-center gap-x-2 gap-y-0.5 text-[11.5px] text-ink-500">
                <span className="font-mono text-ink-700">{t.code}</span>
                <span className="text-ink-300">·</span>
                {t.active_version_label
                  ? <span className="font-mono text-ink-700">{t.active_version_label}</span>
                  : <span className="text-ink-400">sem versão ativa</span>}
                <span className="text-ink-300">·</span>
                <span className="tabular">{fmtDate.format(new Date(t.created_at))}</span>
              </div>
            </div>
            <span className="text-ink-400 mt-1 shrink-0"><Icon.ArrowR /></span>
          </button>
        ))}
      </div>

      {/* Desktop: tabela completa */}
      <div className="hidden sm:block bg-white rounded-lg border border-ink-200 overflow-hidden shadow-card">
        <table className="w-full text-[13px]">
          <thead className="bg-ink-50 border-b border-ink-200">
            <tr className="text-left text-[11.5px] uppercase tracking-tracker text-ink-500 font-medium">
              <th className="px-5 py-2.5">Code</th>
              <th className="px-5 py-2.5">Label</th>
              <th className="px-5 py-2.5">Versão ativa</th>
              <th className="px-5 py-2.5">Status</th>
              <th className="px-5 py-2.5">Criada em</th>
              <th className="px-5 py-2.5 w-0"></th>
            </tr>
          </thead>
          <tbody>
            {types.map((t) => (
              <tr
                key={t.id}
                onClick={() => onOpen(t.id)}
                className="border-b border-ink-100 last:border-0 hover:bg-ink-50 cursor-pointer transition-colors"
              >
                <td className="px-5 py-3 font-mono text-ink-700">{t.code}</td>
                <td className="px-5 py-3 text-ink-900 font-medium">{t.label}</td>
                <td className="px-5 py-3">
                  {t.active_version_label
                    ? <span className="font-mono text-[12px] text-ink-700">{t.active_version_label}</span>
                    : <span className="text-ink-400 text-[12px]">(nenhuma ativa)</span>}
                </td>
                <td className="px-5 py-3">
                  <span className={`inline-flex items-center gap-1.5 rounded-full border px-2 py-0.5 text-[11.5px] font-medium ${
                    t.status === 'ACTIVE' ? 'bg-ok-50 text-ok-700 border-ok-200' : 'bg-ink-100 text-ink-700 border-ink-200'
                  }`}>{t.status}</span>
                </td>
                <td className="px-5 py-3 text-ink-500 tabular">{fmtDate.format(new Date(t.created_at))}</td>
                <td className="px-5 py-3 text-ink-400"><Icon.ArrowR /></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </>
  );
}

// ─── Modal: criar tipo de perícia ─────────────────────────────────────────────
function NewPericiaTypeModal({ open, onClose, onCreated }) {
  const [code, setCode] = useState('');
  const [label, setLabel] = useState('');
  const [description, setDescription] = useState('');
  const [submitting, setSubmitting] = useState(false);
  const [err, setErr] = useState(null);

  useEffect(() => {
    if (open) { setCode(''); setLabel(''); setDescription(''); setErr(null); }
  }, [open]);

  const submit = async (e) => {
    e.preventDefault();
    if (!code.match(/^[a-z][a-z0-9_]*$/)) {
      setErr('Code precisa começar com letra minúscula e usar só letras, números e _');
      return;
    }
    if (!label.trim()) { setErr('Informe um label.'); return; }
    setSubmitting(true);
    setErr(null);
    try {
      const res = await window.apiFetch('/admin/pericia-types', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ code: code.trim(), label: label.trim(), description: description.trim() || null }),
      });
      if (!res.ok) {
        const body = await res.json().catch(() => ({}));
        throw new Error(body.detail || `HTTP ${res.status}`);
      }
      onCreated();
    } catch (e2) {
      setErr(e2.message);
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <Modal open={open} onClose={onClose} width="max-w-lg" label="Nova perícia">
      <form onSubmit={submit}>
        <ModalHeader title="Nova perícia" subtitle="Crie o tipo (sem versões). Suba a primeira versão depois na tela de detalhe." onClose={onClose} />
        <div className="px-6 py-5 space-y-4">
          <Field label="Code" hint="Identificador interno em snake_case (ex.: bancaria, veicular, cartao_rmc, tributaria).">
            <TextInput
              value={code}
              onChange={(e) => setCode(e.target.value.toLowerCase())}
              placeholder="ex.: cartao_rmc"
              className="font-mono"
              autoFocus
            />
          </Field>
          <Field label="Label" hint="Nome exibido pros clientes.">
            <TextInput
              value={label}
              onChange={(e) => setLabel(e.target.value)}
              placeholder="ex.: Revisional de Cartão RMC (Reserva de Margem Consignável)"
            />
          </Field>
          <Field label="Descrição (opcional)">
            <textarea
              value={description}
              onChange={(e) => setDescription(e.target.value)}
              rows={3}
              className="w-full px-3 py-2 rounded-md border border-ink-200 bg-white text-[14px] text-ink-900 focus:border-navy-800 focus:ring-2 focus:ring-navy-800/15 transition-colors leading-snug"
              placeholder="Cenários cobertos, base legal aplicável…"
            />
          </Field>
          {err && (
            <div className="text-[12.5px] text-danger-700 bg-danger-50 border border-danger-200 rounded-md px-3 py-2 flex items-start gap-2">
              <span className="mt-0.5"><Icon.Alert /></span>
              <span>{err}</span>
            </div>
          )}
        </div>
        <div className="px-6 py-4 border-t border-ink-200 flex justify-end gap-2 bg-ink-50/60">
          <Button variant="ghost" type="button" onClick={onClose}>Cancelar</Button>
          <Button type="submit" disabled={submitting}>{submitting ? 'Criando…' : 'Criar perícia'}</Button>
        </div>
      </form>
    </Modal>
  );
}

// ─── Detalhe do tipo: lista versões + upload ──────────────────────────────────
function PericiaTypeDetail({ typeId, onBack }) {
  const [versions, setVersions] = useState([]);
  const [type, setType] = useState(null);
  const [loading, setLoading] = useState(true);
  const [err, setErr] = useState(null);
  const [showUpload, setShowUpload] = useState(false);
  const [showVersion, setShowVersion] = useState(null);

  const reload = async () => {
    setLoading(true);
    setErr(null);
    try {
      const types = await (await window.apiFetch('/admin/pericia-types')).json();
      setType(types.find((t) => t.id === typeId) || null);
      const v = await (await window.apiFetch(`/admin/pericia-types/${typeId}/versions`)).json();
      setVersions(v);
    } catch (e) {
      setErr(`Falha ao carregar: ${e.message}`);
    } finally { setLoading(false); }
  };

  useEffect(() => { reload(); }, [typeId]);

  const activate = async (vid) => {
    if (!confirm('Ativar esta versão? A versão atualmente ativa será deprecada automaticamente.')) return;
    try {
      const res = await window.apiFetch(`/admin/pericia-types/${typeId}/versions/${vid}/activate`, { method: 'POST' });
      if (!res.ok) throw new Error(`HTTP ${res.status}`);
      reload();
    } catch (e) { alert(`Falha: ${e.message}`); }
  };

  const deprecate = async (vid) => {
    if (!confirm('Deprecar esta versão? Análises futuras não a usarão mais.')) return;
    try {
      const res = await window.apiFetch(`/admin/pericia-types/${typeId}/versions/${vid}/deprecate`, { method: 'POST' });
      if (!res.ok) throw new Error(`HTTP ${res.status}`);
      reload();
    } catch (e) { alert(`Falha: ${e.message}`); }
  };

  if (loading) {
    return (
      <div className="bg-white rounded-lg border border-ink-200 shadow-card px-6 py-14 text-center text-ink-500 text-[13px]">
        <Spinner /> Carregando…
      </div>
    );
  }

  return (
    <div>
      <div className="mb-4 flex flex-wrap items-end justify-between gap-3">
        <div>
          <button onClick={onBack} className="text-[12.5px] text-ink-500 hover:text-ink-900 mb-2 inline-flex items-center gap-1">
            <span style={{transform:'rotate(180deg)'}}><Icon.ArrowR /></span> Voltar
          </button>
          <h2 className="text-[18px] font-bold text-ink-900 tracking-tightish">{type?.label || typeId}</h2>
          <div className="mt-0.5 text-[12.5px] text-ink-500 font-mono">{type?.code}</div>
          {type?.description && <p className="mt-1.5 text-[12.5px] text-ink-700 max-w-2xl">{type.description}</p>}
        </div>
        <Button onClick={() => setShowUpload(true)}><Icon.Plus /> Nova versão</Button>
      </div>

      {err && (
        <div className="mb-4 rounded-md border border-danger-200 bg-danger-50 px-3 py-2.5 text-[13px] text-danger-700">{err}</div>
      )}

      {/* Mobile: cards stackados */}
      <div className="sm:hidden bg-white rounded-lg border border-ink-200 shadow-card divide-y divide-ink-100">
        {versions.length === 0 && (
          <div className="px-4 py-12 text-center text-ink-500 text-[13px]">
            Nenhuma versão. Suba a primeira clicando em "Nova versão".
          </div>
        )}
        {versions.map((v) => (
          <div key={v.id} className="px-4 py-3">
            <div className="flex items-center justify-between gap-2 mb-1">
              <div className="font-mono text-[14px] text-ink-900 font-semibold">{v.version_label}</div>
              <span className={`inline-flex items-center rounded-full border px-1.5 py-0 text-[10.5px] font-medium shrink-0 ${
                v.status === 'ACTIVE'    ? 'bg-ok-50 text-ok-700 border-ok-200'
              : v.status === 'DRAFT'     ? 'bg-warn-50 text-warn-700 border-warn-200'
                                         : 'bg-ink-100 text-ink-700 border-ink-200'
              }`}>{v.status}</span>
            </div>
            <div className="text-[11.5px] text-ink-500 tabular">
              {v.activated_at
                ? <>Ativada {fmtDateTime.format(new Date(v.activated_at))}</>
                : <>Criada {fmtDateTime.format(new Date(v.created_at))}</>}
            </div>
            <div className="mt-2 flex items-center gap-3 text-[12.5px] font-medium">
              <button onClick={() => setShowVersion(v.id)} className="text-navy-800 active:underline">Inspecionar</button>
              {v.status !== 'ACTIVE' && (
                <button onClick={() => activate(v.id)} className="text-ok-700 active:underline">Ativar</button>
              )}
              {v.status === 'ACTIVE' && (
                <button onClick={() => deprecate(v.id)} className="text-danger-700 active:underline">Deprecar</button>
              )}
            </div>
          </div>
        ))}
      </div>

      {/* Desktop: tabela */}
      <div className="hidden sm:block bg-white rounded-lg border border-ink-200 overflow-hidden shadow-card">
        <table className="w-full text-[13px]">
          <thead className="bg-ink-50 border-b border-ink-200">
            <tr className="text-left text-[11.5px] uppercase tracking-tracker text-ink-500 font-medium">
              <th className="px-5 py-2.5">Versão</th>
              <th className="px-5 py-2.5">Status</th>
              <th className="px-5 py-2.5">Ativada em</th>
              <th className="px-5 py-2.5">Criada em</th>
              <th className="px-5 py-2.5 text-right">Ações</th>
            </tr>
          </thead>
          <tbody>
            {versions.length === 0 && (
              <tr><td colSpan="5" className="px-5 py-12 text-center text-ink-500 text-[13px]">
                Nenhuma versão. Suba a primeira clicando em "Nova versão".
              </td></tr>
            )}
            {versions.map((v) => (
              <tr key={v.id} className="border-b border-ink-100 last:border-0 hover:bg-ink-50">
                <td className="px-5 py-3 font-mono text-ink-900">{v.version_label}</td>
                <td className="px-5 py-3">
                  <span className={`inline-flex items-center gap-1.5 rounded-full border px-2 py-0.5 text-[11.5px] font-medium ${
                    v.status === 'ACTIVE'    ? 'bg-ok-50 text-ok-700 border-ok-200'
                  : v.status === 'DRAFT'     ? 'bg-warn-50 text-warn-700 border-warn-200'
                                             : 'bg-ink-100 text-ink-700 border-ink-200'
                  }`}>{v.status}</span>
                </td>
                <td className="px-5 py-3 text-ink-700 tabular">{v.activated_at ? fmtDateTime.format(new Date(v.activated_at)) : <span className="text-ink-400">—</span>}</td>
                <td className="px-5 py-3 text-ink-500 tabular">{fmtDateTime.format(new Date(v.created_at))}</td>
                <td className="px-5 py-3 text-right space-x-2 whitespace-nowrap">
                  <button onClick={() => setShowVersion(v.id)} className="text-[12.5px] text-navy-800 hover:underline font-medium">Inspecionar</button>
                  {v.status !== 'ACTIVE' && (
                    <button onClick={() => activate(v.id)} className="text-[12.5px] text-ok-700 hover:underline font-medium">Ativar</button>
                  )}
                  {v.status === 'ACTIVE' && (
                    <button onClick={() => deprecate(v.id)} className="text-[12.5px] text-danger-700 hover:underline font-medium">Deprecar</button>
                  )}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      <UploadVersionModal
        open={showUpload}
        typeId={typeId}
        onClose={() => setShowUpload(false)}
        onUploaded={() => { setShowUpload(false); reload(); }}
      />
      <InspectVersionModal
        versionId={showVersion}
        typeId={typeId}
        onClose={() => setShowVersion(null)}
      />
    </div>
  );
}

// ─── Modal: upload nova versão ────────────────────────────────────────────────
function UploadVersionModal({ open, typeId, onClose, onUploaded }) {
  const [versionLabel, setVersionLabel] = useState('');
  const [notes, setNotes] = useState('');
  const [files, setFiles] = useState({
    prompt: null,
    extraction_tools: null,
    opinion_template: null,
    calculation: null,
    spreadsheet: null,
  });
  const [submitting, setSubmitting] = useState(false);
  const [err, setErr] = useState(null);

  useEffect(() => {
    if (open) {
      setVersionLabel(''); setNotes(''); setErr(null);
      setFiles({ prompt: null, extraction_tools: null, opinion_template: null, calculation: null, spreadsheet: null });
    }
  }, [open]);

  const slots = [
    { key: 'prompt',           label: 'prompt.md',             hint: 'System prompt da metodologia (texto em Markdown).' },
    { key: 'extraction_tools', label: 'extraction_tools.json', hint: 'JSONSchema da tool de extração que o Claude vai chamar.' },
    { key: 'opinion_template', label: 'opinion_template.md',   hint: 'Template Jinja2 do texto de considerações no painel PDF.' },
    { key: 'calculation',      label: 'calculation.yaml',      hint: 'Espelho declarativo das fórmulas (referência/audit).' },
    { key: 'spreadsheet',      label: 'spreadsheet.xlsx',      hint: 'Planilha-modelo (com 11+ inputs editáveis e fórmulas preservadas).' },
  ];

  const allFilesIn = slots.every((s) => files[s.key]);

  const submit = async (e) => {
    e.preventDefault();
    if (!versionLabel.trim()) { setErr('Informe a versão (ex.: v1.0.0).'); return; }
    if (!allFilesIn) { setErr('Anexe os 5 arquivos pra subir a versão.'); return; }
    setSubmitting(true);
    setErr(null);
    try {
      const fd = new FormData();
      fd.append('version_label', versionLabel.trim());
      if (notes.trim()) fd.append('notes', notes.trim());
      for (const s of slots) fd.append(s.key, files[s.key]);
      const res = await window.apiFetch(`/admin/pericia-types/${typeId}/versions`, {
        method: 'POST',
        body: fd,
      });
      if (!res.ok) {
        const body = await res.json().catch(() => ({}));
        throw new Error(body.detail || `HTTP ${res.status}`);
      }
      onUploaded();
    } catch (e2) {
      setErr(e2.message);
    } finally { setSubmitting(false); }
  };

  return (
    <Modal open={open} onClose={onClose} width="max-w-2xl" label="Nova versão">
      <form onSubmit={submit}>
        <ModalHeader title="Nova versão da metodologia" subtitle="Sobe como DRAFT. Ative quando estiver pronta — análises antigas seguem amarradas à versão original (audit trail forense)." onClose={onClose} />
        <div className="px-6 py-5 space-y-4 max-h-[60vh] overflow-y-auto">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <Field label="Versão" hint="Use semver (v1.0.0, v1.1.0…) ou rótulo livre.">
              <TextInput
                value={versionLabel}
                onChange={(e) => setVersionLabel(e.target.value)}
                placeholder="v1.0.0"
                className="font-mono"
                autoFocus
              />
            </Field>
            <Field label="Notas (opcional)" hint="O que mudou em relação à versão anterior.">
              <TextInput
                value={notes}
                onChange={(e) => setNotes(e.target.value)}
                placeholder="ex.: ajuste em B.9 + atualização Bacen 2026-05"
              />
            </Field>
          </div>

          <div className="border-t border-ink-100 pt-4">
            <div className="text-[12px] uppercase tracking-tracker text-ink-500 font-medium mb-2.5">Arquivos da metodologia</div>
            <div className="space-y-2.5">
              {slots.map((s) => (
                <div key={s.key} className="grid grid-cols-1 md:grid-cols-[180px_1fr] gap-3 items-center">
                  <div>
                    <div className="text-[13px] font-mono text-ink-900">{s.label}</div>
                    <div className="text-[11.5px] text-ink-500 leading-snug">{s.hint}</div>
                  </div>
                  <div className="flex items-center gap-2">
                    <input
                      type="file"
                      onChange={(e) => setFiles((p) => ({ ...p, [s.key]: e.target.files[0] || null }))}
                      className="block w-full text-[12.5px] text-ink-700 file:mr-3 file:px-3 file:py-1.5 file:rounded-md file:border-0 file:bg-ink-100 file:text-ink-700 file:font-medium hover:file:bg-ink-200"
                    />
                    {files[s.key] && (
                      <span className="text-[11.5px] text-ok-700 whitespace-nowrap">✓ {files[s.key].name.slice(0, 24)}{files[s.key].name.length > 24 ? '…' : ''}</span>
                    )}
                  </div>
                </div>
              ))}
            </div>
          </div>

          {err && (
            <div className="text-[12.5px] text-danger-700 bg-danger-50 border border-danger-200 rounded-md px-3 py-2 flex items-start gap-2">
              <span className="mt-0.5"><Icon.Alert /></span>
              <span>{err}</span>
            </div>
          )}
        </div>
        <div className="px-6 py-4 border-t border-ink-200 flex justify-end gap-2 bg-ink-50/60">
          <Button variant="ghost" type="button" onClick={onClose}>Cancelar</Button>
          <Button type="submit" disabled={submitting || !allFilesIn}>
            {submitting ? 'Enviando…' : 'Subir versão (como DRAFT)'}
          </Button>
        </div>
      </form>
    </Modal>
  );
}

// ─── Modal: inspecionar versão ───────────────────────────────────────────────
function InspectVersionModal({ versionId, typeId, onClose }) {
  const [data, setData] = useState(null);
  const [tab, setTab] = useState('prompt');
  const [err, setErr] = useState(null);

  useEffect(() => {
    if (!versionId) { setData(null); return; }
    (async () => {
      setErr(null);
      try {
        const res = await window.apiFetch(`/admin/pericia-types/${typeId}/versions/${versionId}`);
        if (!res.ok) throw new Error(`HTTP ${res.status}`);
        setData(await res.json());
      } catch (e) { setErr(e.message); }
    })();
  }, [versionId, typeId]);

  const open = !!versionId;
  const tabs = [
    { id: 'prompt',     label: 'prompt.md' },
    { id: 'tools',      label: 'extraction_tools.json' },
    { id: 'opinion',    label: 'opinion_template.md' },
    { id: 'calc',       label: 'calculation.yaml' },
  ];
  let body = '';
  if (data) {
    body = tab === 'prompt'  ? data.system_prompt_md
         : tab === 'tools'   ? JSON.stringify(data.extraction_tools, null, 2)
         : tab === 'opinion' ? data.opinion_template_md
         : tab === 'calc'    ? data.calculation_yaml
         : '';
  }

  return (
    <Modal open={open} onClose={onClose} width="max-w-4xl" label="Inspecionar versão">
      <ModalHeader
        title={data ? `${data.pericia_type_code} · ${data.version_label}` : 'Carregando…'}
        subtitle={data ? `Status: ${data.status} · criada por ${data.created_by || '—'}` : null}
        onClose={onClose}
      />
      <div className="px-4 sm:px-6 pt-3 border-b border-ink-200">
        <nav className="flex gap-1 overflow-x-auto -mb-px" style={{ scrollbarWidth: 'none' }}>
          {tabs.map((t) => (
            <button
              key={t.id}
              onClick={() => setTab(t.id)}
              className={`px-3 py-2 text-[12.5px] font-medium border-b-2 transition-colors whitespace-nowrap shrink-0 ${
                tab === t.id ? 'border-navy-800 text-navy-800' : 'border-transparent text-ink-500 hover:text-ink-900'
              }`}
            >{t.label}</button>
          ))}
        </nav>
      </div>
      <div className="px-6 py-4 max-h-[60vh] overflow-y-auto">
        {err && <div className="text-[12.5px] text-danger-700">{err}</div>}
        {!data && !err && <div className="text-ink-500 text-[13px]"><Spinner /> Carregando…</div>}
        {data && (
          <pre className="bg-ink-50 border border-ink-200 rounded-md p-4 text-[11.5px] text-ink-900 font-mono whitespace-pre-wrap leading-relaxed">{body}</pre>
        )}
      </div>
      <div className="px-6 py-4 border-t border-ink-200 flex justify-end bg-ink-50/60">
        <Button onClick={onClose}>Fechar</Button>
      </div>
    </Modal>
  );
}

window.AdminPanel = AdminPanel;
