/* global React, Icon */
/* ============================================================
   DetailPanel — drawer do agente
   Tabs: Visão geral · Execuções · Prompt (versionado+diff) ·
   Modelo · MCPs (teste de conexão simulado)
   ============================================================ */
const { useState: useStateP, useEffect: useEffectP, useRef: useRefP } = React;
const Icon = window.Icon;
const TraceView = window.TraceView, Badge = window.Badge;

// ---- LCS line diff ----
function lineDiff(oldT, newT) {
  const a = oldT.split("\n"), b = newT.split("\n");
  const m = a.length, n = b.length;
  const dp = Array.from({ length: m + 1 }, () => new Array(n + 1).fill(0));
  for (let i = m - 1; i >= 0; i--) for (let j = n - 1; j >= 0; j--)
    dp[i][j] = a[i] === b[j] ? dp[i + 1][j + 1] + 1 : Math.max(dp[i + 1][j], dp[i][j + 1]);
  const out = []; let i = 0, j = 0;
  while (i < m && j < n) {
    if (a[i] === b[j]) { out.push({ t: "ctx", text: a[i] }); i++; j++; }
    else if (dp[i + 1][j] >= dp[i][j + 1]) { out.push({ t: "del", text: a[i] }); i++; }
    else { out.push({ t: "add", text: b[j] }); j++; }
  }
  while (i < m) out.push({ t: "del", text: a[i++] });
  while (j < n) out.push({ t: "add", text: b[j++] });
  return out;
}
const diffCounts = (d) => ({ add: d.filter((x) => x.t === "add").length, del: d.filter((x) => x.t === "del").length });
const nowStamp = () => {
  const d = new Date();
  const p = (x) => String(x).padStart(2, "0");
  return `${p(d.getDate())}/${p(d.getMonth() + 1)}/${d.getFullYear()} ${p(d.getHours())}:${p(d.getMinutes())}`;
};

function seedVersions(agent) {
  return agent.versions.map((ver, idx) => {
    let text = agent.prompt;
    if (idx > 0) {
      const ls = agent.prompt.split("\n");
      let removed = 0;
      for (let k = ls.length - 1; k >= 0 && removed < idx; k--) { if (ls[k].trim()) { ls.splice(k, 1); removed++; } }
      text = ls.join("\n");
    }
    return { ...ver, text };
  });
}

// ---------- small UI bits ----------
function StatTile({ t, label, value, sub, icon, valueColor }) {
  return (
    <div style={{ padding: 16, borderRadius: 14, background: "rgba(255,255,255,.018)", border: "1px solid #1f1f22" }}>
      <div style={{ display: "flex", alignItems: "center", gap: 8, color: "rgba(207,207,207,.5)" }}>
        <Icon name={icon} size={15} stroke={1.7} />
        <span style={{ fontSize: 9.5, letterSpacing: ".14em", textTransform: "uppercase" }}>{label}</span>
      </div>
      <div style={{ fontSize: 26, fontWeight: 800, color: valueColor || "#fff", letterSpacing: "-.02em", marginTop: 11, lineHeight: 1 }}>{value}</div>
      {sub && <div style={{ fontSize: 11, color: "rgba(207,207,207,.4)", marginTop: 7 }}>{sub}</div>}
    </div>
  );
}

function ResultRow({ r, t }) {
  const dot = window.AgentData.STATUS[r.status].orb;
  return (
    <div style={{ display: "flex", gap: 14 }}>
      <div style={{ display: "flex", flexDirection: "column", alignItems: "center", flex: "none", paddingTop: 5 }}>
        <span style={{ width: 10, height: 10, borderRadius: "50%", flex: "none", background: dot, boxShadow: `0 0 8px ${dot}` }} />
        <span style={{ flex: 1, width: 1, background: "#1c1c20", marginTop: 6, minHeight: 14 }} />
      </div>
      <div style={{ flex: 1, minWidth: 0, paddingBottom: 20 }}>
        <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between", gap: 12 }}>
          <span style={{ fontSize: 13.5, fontWeight: 600, color: "#fff" }}>{r.title}</span>
          <span style={{ fontSize: 11, color: "rgba(207,207,207,.4)", whiteSpace: "nowrap", flex: "none" }}>{r.time}</span>
        </div>
        <p style={{ margin: "5px 0 0", fontSize: 12, color: "rgba(207,207,207,.55)", lineHeight: 1.45 }}>{r.summary}</p>
        <div style={{ display: "flex", gap: 7, marginTop: 9 }}>
          <span style={{ display: "flex", alignItems: "center", gap: 5, height: 24, padding: "0 9px", borderRadius: 7, background: "rgba(255,255,255,.03)", border: "1px solid #1f1f22", fontSize: 11, color: "rgba(207,207,207,.7)" }}><Icon name="coins" size={11} stroke={1.8} />{window.AgentData.fmtTokens(r.tokens)} tok</span>
          <span style={{ display: "flex", alignItems: "center", gap: 5, height: 24, padding: "0 9px", borderRadius: 7, background: "rgba(255,255,255,.03)", border: "1px solid #1f1f22", fontSize: 11, color: "rgba(207,207,207,.7)" }}><Icon name="clock" size={11} stroke={1.8} />{r.dur}</span>
        </div>
      </div>
    </div>
  );
}

// ---------- TABS ----------
function OverviewTab({ agent, t }) {
  const { fmtBRL, fmtTokens, fmtNum, STATUS } = window.AgentData;
  const m = agent.metrics;
  const isLocal = agent.llm === "llama";
  const sucColor = STATUS[agent.status].orb;
  return (
    <div>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
        <StatTile t={t} label="Tokens hoje" value={fmtTokens(m.tokensDay)} sub={`${fmtTokens(m.tokensMonth)} no mês`} icon="coins" />
        <StatTile t={t} label="Custo hoje" value={isLocal ? "R$ 0,00" : fmtBRL(m.cost)} sub={isLocal ? "Modelo local · sem custo de API" : `${fmtBRL(m.costMonth)} no mês`} icon="dollar-sign" />
        <StatTile t={t} label="Acion. / dia" value={fmtNum(m.calls)} sub="gatilhos automáticos + manuais" icon="zap" />
        <StatTile t={t} label="Taxa de sucesso" value={m.success + "%"} sub="execuções concluídas" icon="gauge" valueColor={sucColor} />
        <StatTile t={t} label="Latência p95" value={m.p95} sub="tempo de resposta" icon="clock" />
        <StatTile t={t} label="Tempo economizado" value={m.saved} sub="vs. processo manual" icon="trending-up" />
      </div>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", margin: "26px 0 16px" }}>
        <span style={{ fontSize: 10.5, letterSpacing: ".18em", color: "rgba(207,207,207,.5)", textTransform: "uppercase" }}>Resultados recentes</span>
        <span style={{ fontSize: 11, color: "#aecbe0", cursor: "pointer" }}>ver tudo</span>
      </div>
      <div>{agent.recent.map((r, i) => <ResultRow key={i} r={r} t={t} />)}</div>
    </div>
  );
}

function RunsTab({ agent, t, dark }) {
  const { fmtBRL, fmtTokens, TRACES } = window.AgentData;
  const [open, setOpen] = useStateP(agent.runs[0] ? agent.runs[0].id : null);
  useEffectP(() => setOpen(agent.runs[0] ? agent.runs[0].id : null), [agent.id]);
  const trace = TRACES[agent.id] || [];
  return (
    <div>
      <div style={{ fontSize: 11.5, color: t.ink2, marginBottom: 12, lineHeight: 1.5 }}>Histórico de execuções de hoje. Clique numa linha para abrir o <b style={{ color: t.ink }}>trace passo a passo</b> — cada chamada de modelo e MCP, com tokens e onde falhou.</div>
      <div style={{ display: "grid", gridTemplateColumns: "1.25fr 1.5fr 0.7fr 0.8fr 0.7fr 18px", padding: "9px 12px", fontSize: 9.5, fontWeight: 700, textTransform: "uppercase", letterSpacing: ".06em", color: t.ink3 }}>
        <span>Execução</span><span>Gatilho</span><span>Duração</span><span>Tokens</span><span>Status</span><span></span>
      </div>
      <div style={{ display: "flex", flexDirection: "column", gap: 7 }}>
        {agent.runs.map((r) => {
          const S = window.AgentData.STATUS[r.status];
          const isOpen = open === r.id;
          return (
            <div key={r.id} style={{ border: `1px solid ${isOpen ? agent.accent : t.cardBorder}`, borderRadius: 12, overflow: "hidden", background: t.cardBg }}>
              <div onClick={() => setOpen(isOpen ? null : r.id)} style={{ display: "grid", gridTemplateColumns: "1.25fr 1.5fr 0.7fr 0.8fr 0.7fr 18px", padding: "11px 12px", fontSize: 11.5, alignItems: "center", cursor: "pointer", background: isOpen ? t.trayBg : "transparent" }}>
                <span style={{ fontFamily: "var(--font-mono)", color: t.ink, fontWeight: 600 }}>{r.id}</span>
                <span style={{ color: t.ink2, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{r.trigger}</span>
                <span style={{ color: t.ink2, fontFamily: "var(--font-mono)" }}>{r.dur}</span>
                <span style={{ color: t.ink2, fontFamily: "var(--font-mono)" }}>{fmtTokens(r.tokens)}</span>
                <span><span style={{ display: "inline-flex", alignItems: "center", gap: 4, background: dark ? S.orb + "22" : S.bg, color: dark ? S.orb : S.fg, fontSize: 10, fontWeight: 600, padding: "2px 7px", borderRadius: 7 }}><span style={{ width: 6, height: 6, borderRadius: 6, background: S.orb }} />{S.label}</span></span>
                <span style={{ color: t.ink3, transform: isOpen ? "rotate(0)" : "rotate(-90deg)", transition: "transform .18s", display: "inline-flex" }}><Icon name="chevron-down" size={15} /></span>
              </div>
              {isOpen && (
                <div style={{ borderTop: `1px solid ${t.cardBorder}`, padding: "14px 14px 12px", background: t.statBg }}>
                  <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 12, fontSize: 10, color: t.ink3, fontFamily: "var(--font-mono)" }}>
                    <span>TRACE · {r.id}</span><span>custo {fmtBRL(r.cost)} · {trace.length} passos</span>
                  </div>
                  <TraceView steps={trace} t={t} dark={dark} />
                </div>
              )}
            </div>
          );
        })}
      </div>
    </div>
  );
}

function PlaygroundTab({ agent, t, dark }) {
  const { LLMS } = window.AgentData;
  const SAMPLES = {
    nf: "NF-e 35260412345678000190550010000004121000004120\nFornecedor: Distribuidora Souza LTDA\nValor total: R$ 4.218,90 · CFOP 5102 · ICMS 18%",
    concilia: "Extrato 12/04: -R$ 1.250,00 · PIX FORNECEDOR X\nLançamento ERP: NF 412 · R$ 1.250,00 · 11/04\nConta sugerida?",
    triagem: "Currículo: João Silva · 5 anos em contabilidade fiscal,\nCRC ativo, Excel avançado, experiência com SPED.\nVaga: Analista Contábil Pleno",
    contratos: "Contratar: Maria Andrade · CLT · R$ 4.200,00\nCargo: Analista Fiscal Jr · início 01/07/2026 · Campinas",
    atendimento: "Cliente: \"Meu DAS do Simples venceu ontem, o que faço agora? Tem multa?\"",
  };
  const OUT = {
    nf: '{ "tipo": "NFe", "chave": "3526…4120", "cfop": "5102",\n  "valor_total": 4218.90, "icms": 759.40,\n  "operacao": "entrada/mercadoria", "divergencias": [] }',
    concilia: '{ "match": true, "confianca": 0.94,\n  "conta": "1.1.02 · Bancos", "diferenca_dias": 1,\n  "acao": "conciliar_automatico" }',
    triagem: '{ "score": 88, "recomendacao": "avançar",\n  "fortes": ["SPED", "CRC ativo"], "lacunas": ["IFRS"],\n  "vies_detectado": false }',
    contratos: '{ "template": "CLT", "clausulas": 12, "lgpd": true,\n  "status": "minuta_para_revisao",\n  "proximo": "aprovacao_humana" }',
    atendimento: '{ "resposta": "Há multa de 0,33%/dia + juros Selic.\n  Posso emitir a guia atualizada?", "escalar": true,\n  "registro_crm": "ok" }',
  };
  const [input, setInput] = useStateP(SAMPLES[agent.id]);
  const [cmp, setCmp] = useStateP("single");
  const [phase, setPhase] = useStateP("idle");
  useEffectP(() => { setInput(SAMPLES[agent.id]); setPhase("idle"); }, [agent.id]);

  const run = () => { setPhase("running"); setTimeout(() => setPhase("done"), 1300); };
  const cur = LLMS[agent.llm], fb = LLMS[agent.fallback];

  const ResultCard = ({ model, label, variant }) => {
    const out = OUT[agent.id];
    return (
      <div style={{ background: t.cardBg, border: `1px solid ${t.cardBorder}`, borderRadius: 12, padding: 12, flex: 1, minWidth: 0 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 6, marginBottom: 9 }}>
          <span style={{ width: 7, height: 7, borderRadius: 7, background: model.color }} />
          <span style={{ fontSize: 11.5, fontWeight: 700, color: t.ink }}>{model.name}</span>
          {label && <span style={{ fontSize: 9, fontWeight: 700, color: t.ink3, textTransform: "uppercase", letterSpacing: ".06em" }}>{label}</span>}
        </div>
        <pre style={{ margin: 0, whiteSpace: "pre-wrap", fontFamily: "var(--font-mono)", fontSize: 10.5, color: t.ink2, lineHeight: 1.5, background: t.statBg, border: `1px solid ${t.chipBorder}`, borderRadius: 8, padding: "9px 10px" }}>{out}</pre>
        <div style={{ display: "flex", gap: 6, marginTop: 9, flexWrap: "wrap", fontSize: 10, color: t.ink3, fontFamily: "var(--font-mono)" }}>
          <span>{variant === "b" ? "3,4k" : "2,9k"} tok</span><span>·</span><span>{variant === "b" ? (model.costOut === 0 ? "R$ 0,00" : "R$ 0,04") : (model.costOut === 0 ? "R$ 0,00" : "R$ 0,03")}</span><span>·</span><span>{variant === "b" ? "1,8 s" : "1,1 s"}</span>
        </div>
      </div>
    );
  };

  return (
    <div>
      <div style={{ fontSize: 11.5, color: t.ink2, marginBottom: 12, lineHeight: 1.5 }}>Rode o agente com uma <b style={{ color: t.ink }}>entrada de exemplo</b> sem afetar produção. Compare versões de prompt ou modelos lado a lado antes de promover.</div>
      <div style={{ fontSize: 10.5, fontWeight: 700, textTransform: "uppercase", letterSpacing: ".09em", color: t.ink3, marginBottom: 6 }}>Entrada de exemplo</div>
      <textarea value={input} onChange={(e) => setInput(e.target.value)} spellCheck={false}
        style={{ width: "100%", minHeight: 92, resize: "vertical", borderRadius: 12, padding: "11px 12px", fontSize: 11.5, lineHeight: 1.5, fontFamily: "var(--font-mono)", color: t.ink, background: t.statBg, border: `1px solid ${t.chipBorder}`, outline: "none", boxSizing: "border-box" }} />
      <div style={{ display: "flex", gap: 7, alignItems: "center", margin: "10px 0 4px", flexWrap: "wrap" }}>
        <div className="seg" style={{ borderColor: t.chipBorder }}>
          {[["single", "Saída única"], ["versions", "Comparar versões"], ["models", "Comparar modelos"]].map(([k, l]) => (
            <button key={k} onClick={() => { setCmp(k); setPhase("idle"); }} className={cmp === k ? "on" : ""} style={{ color: cmp === k ? "#fff" : t.ink2 }}>{l}</button>
          ))}
        </div>
        <div style={{ flex: 1 }} />
        <button onClick={run} disabled={phase === "running"} className="btn-primary" style={{ background: agent.accent, opacity: phase === "running" ? .6 : 1 }}>
          <Icon name={phase === "running" ? "loader" : "play"} size={13} className={phase === "running" ? "spin" : ""} fill={phase === "running" ? "none" : "currentColor"} stroke={phase === "running" ? 2 : 0} /> {phase === "running" ? "Rodando…" : "Rodar teste"}
        </button>
      </div>

      {phase === "running" && <div style={{ marginTop: 14, fontSize: 11.5, color: t.ink2, display: "flex", alignItems: "center", gap: 8 }}><span className="spin" style={{ color: agent.accent }}><Icon name="loader" size={15} /></span> Executando em sandbox · sem efeitos colaterais…</div>}

      {phase === "done" && (
        <div style={{ marginTop: 14 }}>
          <div style={{ fontSize: 10.5, fontWeight: 700, textTransform: "uppercase", letterSpacing: ".09em", color: t.ink3, marginBottom: 8 }}>Resultado</div>
          {cmp === "single" && <ResultCard model={cur} />}
          {cmp === "versions" && (
            <div style={{ display: "flex", gap: 9 }}>
              <ResultCard model={cur} label="v atual" variant="a" />
              <ResultCard model={cur} label="v anterior" variant="b" />
            </div>
          )}
          {cmp === "models" && (
            <div style={{ display: "flex", gap: 9 }}>
              <ResultCard model={cur} label="em uso" variant="a" />
              <ResultCard model={fb} label="fallback" variant="b" />
            </div>
          )}
          {cmp !== "single" && (
            <div style={{ marginTop: 10, display: "flex", alignItems: "center", gap: 8, background: dark ? "rgba(25,179,107,.12)" : "#ecfdf3", border: `1px solid ${dark ? "transparent" : "#bbf7d0"}`, borderRadius: 10, padding: "9px 12px", fontSize: 11.5, color: "#15803d" }}>
              <Icon name="check" size={14} stroke={2.4} /> Saídas equivalentes · {cmp === "models" ? `${cur.name} 38% mais rápido e ${cur.costOut <= fb.costOut ? "mais barato" : "mais caro"}` : "v atual mantém qualidade com menos tokens"}.
            </div>
          )}
        </div>
      )}
    </div>
  );
}

function PromptTab({ agent, t, onUpdate }) {
  const [versions, setVersions] = useStateP(() => seedVersions(agent));
  const [draft, setDraft] = useStateP(versions[0].text);
  const [open, setOpen] = useStateP(null);
  const [hint, setHint] = useStateP("");
  useEffectP(() => { const v = seedVersions(agent); setVersions(v); setDraft(v[0].text); setOpen(null); setHint(""); }, [agent.id]);

  const dirty = draft !== versions[0].text;
  const liveDiff = lineDiff(versions[0].text, draft);
  const lc = diffCounts(liveDiff);

  const save = () => {
    const c = diffCounts(lineDiff(versions[0].text, draft));
    const nv = { v: versions[0].v + 1, author: "Você", date: nowStamp(), note: hint || "Edição manual do prompt", added: c.add, removed: c.del, text: draft };
    setVersions([nv, ...versions]);
    onUpdate(agent.id, { prompt: draft });
    setHint("");
  };
  const revert = (ver) => { setDraft(ver.text); setHint(`Revertido para v${ver.v} — salve para versionar`); };

  return (
    <div>
      {/* editor */}
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 7 }}>
        <span style={{ fontSize: 11, fontWeight: 700, textTransform: "uppercase", letterSpacing: ".1em", color: t.ink3 }}>System prompt</span>
        <span style={{ fontSize: 10, color: t.ink3, fontFamily: "var(--font-mono)" }}>v{versions[0].v} ativa</span>
      </div>
      <textarea value={draft} onChange={(e) => setDraft(e.target.value)} spellCheck={false}
        style={{ width: "100%", minHeight: 184, resize: "vertical", borderRadius: 12, padding: "12px 13px", fontSize: 12, lineHeight: 1.55, fontFamily: "var(--font-mono)", color: t.ink, background: t.statBg, border: `1px solid ${dirty ? agent.accent : t.chipBorder}`, outline: "none", boxSizing: "border-box" }} />
      <div style={{ display: "flex", alignItems: "center", gap: 8, marginTop: 9, flexWrap: "wrap" }}>
        {dirty && <span style={{ fontSize: 11, fontFamily: "var(--font-mono)", color: t.ink2 }}><span style={{ color: "#19b36b" }}>+{lc.add}</span> <span style={{ color: "#ef4444" }}>−{lc.del}</span> linhas</span>}
        <div style={{ flex: 1 }} />
        {dirty && <button onClick={() => { setDraft(versions[0].text); setHint(""); }} className="btn-ghost" style={{ color: t.ink2, borderColor: t.chipBorder }}>Descartar</button>}
        <button onClick={save} disabled={!dirty} className="btn-primary" style={{ opacity: dirty ? 1 : .45, background: agent.accent }}>
          <Icon name="git-commit" size={14} /> Salvar nova versão
        </button>
      </div>
      {hint && <div style={{ fontSize: 11, color: agent.accent, marginTop: 8, fontWeight: 600 }}>{hint}</div>}

      {/* history */}
      <div style={{ fontSize: 11, fontWeight: 700, textTransform: "uppercase", letterSpacing: ".1em", color: t.ink3, margin: "20px 0 8px" }}>Histórico de versões</div>
      <div style={{ display: "flex", flexDirection: "column", gap: 7 }}>
        {versions.map((ver, idx) => {
          const prev = versions[idx + 1];
          const isOpen = open === ver.v;
          const d = prev ? lineDiff(prev.text, ver.text) : null;
          return (
            <div key={ver.v} style={{ border: `1px solid ${isOpen ? agent.accent : t.cardBorder}`, borderRadius: 11, overflow: "hidden", background: t.cardBg }}>
              <div onClick={() => setOpen(isOpen ? null : ver.v)} style={{ display: "flex", alignItems: "center", gap: 10, padding: "9px 11px", cursor: "pointer" }}>
                <span style={{ fontFamily: "var(--font-mono)", fontWeight: 700, fontSize: 11, color: "#fff", background: idx === 0 ? agent.accent : t.ink3, borderRadius: 6, padding: "2px 6px" }}>v{ver.v}</span>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 12, color: t.ink, fontWeight: 600, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{ver.note}</div>
                  <div style={{ fontSize: 10, color: t.ink3, marginTop: 1 }}>{ver.author} · {ver.date}{idx === 0 ? " · atual" : ""}</div>
                </div>
                <span style={{ fontSize: 10, fontFamily: "var(--font-mono)" }}><span style={{ color: "#19b36b" }}>+{ver.added}</span> <span style={{ color: "#ef4444" }}>−{ver.removed}</span></span>
                <span style={{ color: t.ink3, transform: isOpen ? "rotate(0)" : "rotate(-90deg)", transition: "transform .18s" }}><Icon name="chevron-down" size={15} /></span>
              </div>
              {isOpen && (
                <div style={{ borderTop: `1px solid ${t.cardBorder}` }}>
                  <div style={{ maxHeight: 240, overflow: "auto", background: t.statBg, padding: "8px 0", fontFamily: "var(--font-mono)", fontSize: 11, lineHeight: 1.5 }}>
                    {(d || [{ t: "ctx", text: ver.text }]).flatMap((l, i) => l.text.split("\n").map((tx, k) => (
                      <div key={i + "-" + k} style={{ padding: "0 12px", whiteSpace: "pre-wrap", background: l.t === "add" ? "rgba(25,179,107,.13)" : l.t === "del" ? "rgba(239,68,68,.12)" : "transparent", color: l.t === "add" ? "#15803d" : l.t === "del" ? "#b91c1c" : t.ink2 }}>
                        <span style={{ userSelect: "none", opacity: .5, marginRight: 8 }}>{l.t === "add" ? "+" : l.t === "del" ? "−" : " "}</span>{tx || " "}
                      </div>
                    )))}
                  </div>
                  <div style={{ display: "flex", justifyContent: "flex-end", gap: 8, padding: "9px 11px", borderTop: `1px solid ${t.cardBorder}` }}>
                    {!prev && <span style={{ fontSize: 10.5, color: t.ink3, alignSelf: "center" }}>versão inicial</span>}
                    {idx !== 0 && <button onClick={() => revert(ver)} className="btn-ghost" style={{ color: t.ink2, borderColor: t.chipBorder }}><Icon name="rotate-ccw" size={13} /> Reverter para v{ver.v}</button>}
                  </div>
                </div>
              )}
            </div>
          );
        })}
      </div>
    </div>
  );
}

function ModelTab({ agent, t, onUpdate }) {
  const { LLMS, LLM_LIST, fmtBRL } = window.AgentData;
  const cur = agent.llm;
  return (
    <div>
      <div style={{ fontSize: 11.5, color: t.ink2, marginBottom: 14, lineHeight: 1.5 }}>Modelo que dá raciocínio a este agente. A troca recalcula custo e latência estimados e re-versiona a configuração.</div>
      <div style={{ display: "flex", flexDirection: "column", gap: 9 }}>
        {LLM_LIST.map((id) => {
          const l = LLMS[id]; const active = id === cur;
          return (
            <button key={id} onClick={() => onUpdate(agent.id, { llm: id })}
              style={{ textAlign: "left", display: "flex", alignItems: "center", gap: 12, padding: "13px 14px", borderRadius: 13, cursor: "pointer", background: active ? (t.dark ? "rgba(255,255,255,.05)" : "#fff") : t.statBg, border: `1.5px solid ${active ? agent.accent : t.chipBorder}`, boxShadow: active ? `0 0 0 3px ${agent.accent}1f` : "none" }}>
              <span style={{ width: 38, height: 38, borderRadius: 10, background: l.color + "1f", color: l.color, display: "grid", placeItems: "center", fontSize: 18, fontWeight: 700, flex: "0 0 38px" }}>{l.glyph}</span>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ display: "flex", alignItems: "center", gap: 7 }}>
                  <span style={{ fontSize: 13.5, fontWeight: 700, color: t.ink }}>{l.name}</span>
                  {active && <span style={{ fontSize: 9, fontWeight: 700, color: "#fff", background: agent.accent, padding: "1px 6px", borderRadius: 6, textTransform: "uppercase", letterSpacing: ".06em" }}>Em uso</span>}
                </div>
                <div style={{ fontSize: 10.5, color: t.ink3, marginTop: 2 }}>{l.vendor} · contexto {l.ctx} · {l.speed}</div>
              </div>
              <div style={{ textAlign: "right", fontFamily: "var(--font-mono)", fontSize: 10.5, color: t.ink2 }}>
                <div>{l.costIn === 0 ? "—" : fmtBRL(l.costIn)}<span style={{ color: t.ink3 }}> /1M in</span></div>
                <div>{l.costOut === 0 ? "local" : fmtBRL(l.costOut)}<span style={{ color: t.ink3 }}> /1M out</span></div>
              </div>
            </button>
          );
        })}
      </div>

      {/* fallback & resiliência */}
      <div style={{ marginTop: 20, paddingTop: 16, borderTop: `1px solid ${t.cardBorder}` }}>
        <div style={{ fontSize: 11, fontWeight: 700, textTransform: "uppercase", letterSpacing: ".1em", color: t.ink3, marginBottom: 4 }}>Fallback & resiliência</div>
        <div style={{ fontSize: 11, color: t.ink2, marginBottom: 11, lineHeight: 1.5 }}>Se o modelo principal falhar ou estourar o timeout, o agente tenta automaticamente o modelo reserva.</div>
        <div style={{ fontSize: 9.5, fontWeight: 700, textTransform: "uppercase", letterSpacing: ".07em", color: t.ink3, marginBottom: 7 }}>Modelo reserva</div>
        <div style={{ display: "flex", gap: 7, flexWrap: "wrap", marginBottom: 14 }}>
          {LLM_LIST.filter((id) => id !== cur).map((id) => {
            const l = LLMS[id]; const active = id === agent.fallback;
            return (
              <button key={id} onClick={() => onUpdate(agent.id, { fallback: id })} style={{ display: "inline-flex", alignItems: "center", gap: 6, padding: "7px 11px", borderRadius: 9, cursor: "pointer", fontFamily: "inherit", fontSize: 11.5, fontWeight: 600, background: active ? agent.accent : t.statBg, color: active ? "#fff" : t.ink2, border: `1px solid ${active ? agent.accent : t.chipBorder}` }}>
                <span style={{ width: 7, height: 7, borderRadius: 7, background: active ? "#fff" : l.color }} />{l.name}
              </button>
            );
          })}
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 9 }}>
          {[["Tentativas", "retries", "", 0, 5], ["Timeout", "timeout", " s", 5, 120]].map(([label, key, suffix, min, max]) => (
            <div key={key} style={{ background: t.statBg, border: `1px solid ${t.chipBorder}`, borderRadius: 12, padding: "10px 12px" }}>
              <div style={{ fontSize: 9.5, textTransform: "uppercase", letterSpacing: ".07em", color: t.ink3, fontWeight: 700, marginBottom: 6 }}>{label}</div>
              <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
                <button onClick={() => onUpdate(agent.id, { [key]: Math.max(min, agent[key] - (key === "timeout" ? 5 : 1)) })} className="step-btn" style={{ color: t.ink, borderColor: t.chipBorder }}><Icon name="minus" size={13} /></button>
                <span style={{ fontSize: 16, fontWeight: 700, color: t.ink, fontFamily: "var(--font-mono)" }}>{agent[key]}{suffix}</span>
                <button onClick={() => onUpdate(agent.id, { [key]: Math.min(max, agent[key] + (key === "timeout" ? 5 : 1)) })} className="step-btn" style={{ color: t.ink, borderColor: t.chipBorder }}><Icon name="plus" size={13} /></button>
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

function McpTab({ agent, t, onEditCreds }) {
  const [state, setState] = useStateP({});
  useEffectP(() => setState({}), [agent.id]);
  const test = (m) => {
    setState((s) => ({ ...s, [m.id]: { phase: "testing" } }));
    setTimeout(() => {
      const okBase = m.status !== "error";
      setState((s) => ({ ...s, [m.id]: { phase: "done", ok: okBase, lat: okBase ? m.latency : "timeout", warn: m.status === "warn" } }));
    }, 900 + Math.random() * 700);
  };
  const testAll = () => agent.mcps.forEach((m, i) => setTimeout(() => test(m), i * 180));
  return (
    <div>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 13 }}>
        <div style={{ fontSize: 11.5, color: t.ink2, lineHeight: 1.5, maxWidth: 250 }}>Tools (MCPs) acopladas a este agente — escopo global da esteira. Simule o handshake de conexão.</div>
        <button onClick={testAll} className="btn-primary" style={{ background: agent.accent }}><Icon name="plug" size={13} /> Testar todos</button>
      </div>
      <div style={{ display: "flex", flexDirection: "column", gap: 9 }}>
        {agent.mcps.map((m) => {
          const st = state[m.id]; const S = window.AgentData.STATUS[m.status];
          return (
            <div key={m.id} style={{ display: "flex", alignItems: "center", gap: 12, padding: "12px 13px", borderRadius: 13, background: t.statBg, border: `1px solid ${t.chipBorder}` }}>
              <span style={{ width: 38, height: 38, borderRadius: 11, background: t.cardBg, border: `1px solid ${t.chipBorder}`, display: "grid", placeItems: "center", color: S.orb, flex: "0 0 38px" }}><Icon name={m.icon} size={18} /></span>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 13, fontWeight: 700, color: t.ink }}>{m.name}</div>
                <div style={{ fontSize: 10.5, color: t.ink3, marginTop: 2, fontFamily: "var(--font-mono)" }}>
                  {st?.phase === "testing" ? "handshake…" : st?.phase === "done" ? (st.ok ? `${st.warn ? "lento" : "conectado"} · ${st.lat}` : "falha · timeout") : `latência ${m.latency}`}
                </div>
              </div>
              <button onClick={() => onEditCreds(m)} title="Editar credenciais" className="cred-btn" style={{ width: 32, height: 32, flex: "0 0 32px", color: t.ink2, borderColor: t.chipBorder, background: t.cardBg }}><Icon name="key" size={14} /></button>
              {st?.phase === "testing"
                ? <span className="spin" style={{ color: agent.accent }}><Icon name="loader" size={17} /></span>
                : st?.phase === "done"
                  ? <span style={{ display: "inline-flex", alignItems: "center", gap: 4, fontSize: 10.5, fontWeight: 700, color: st.ok ? (st.warn ? "#92400e" : "#15803d") : "#b91c1c", background: st.ok ? (st.warn ? "#fffbeb" : "#ecfdf3") : "#fef2f2", padding: "3px 8px", borderRadius: 8 }}><Icon name={st.ok ? "check" : "x"} size={12} stroke={2.5} />{st.ok ? (st.warn ? "Lento" : "OK") : "Falha"}</span>
                  : <button onClick={() => test(m)} className="btn-ghost" style={{ color: t.ink, borderColor: t.chipBorder }}>Testar</button>}
            </div>
          );
        })}
      </div>
    </div>
  );
}

// ---------- Panel shell ----------
function DetailPanel({ agent, t, dark, onClose, onUpdate, onRun, running, onEditCreds }) {
  const [tab, setTab] = useStateP("overview");
  useEffectP(() => setTab("overview"), [agent.id]);
  const S = window.AgentData.STATUS[agent.status];
  const llm = window.AgentData.LLMS[agent.llm];
  const tt = { ...t, dark };
  const TABS = [
    { id: "overview", label: "Visão geral", icon: "activity" },
    { id: "runs", label: "Execuções", icon: "history" },
    { id: "playground", label: "Testes", icon: "sparkles" },
    { id: "prompt", label: "Prompt", icon: "file-text" },
    { id: "model", label: "Modelo", icon: "cpu" },
    { id: "mcp", label: "MCPs", icon: "plug" },
  ];
  const acc = dark ? S.orb : agent.accent;
  return (
    <div className="panel" style={{ position: "relative", background: dark ? "linear-gradient(180deg,#0d0d0f,#070708)" : t.panelBg, borderLeft: `1px solid ${dark ? "#1f1f22" : t.panelBorder}`, color: t.ink }}>
      {dark && <span style={{ position: "absolute", left: 0, top: 0, bottom: 0, width: 2, background: `linear-gradient(180deg, ${acc}, transparent 60%)`, opacity: .7, pointerEvents: "none" }} />}
      {/* header */}
      <div style={{ padding: "24px 26px 18px", borderBottom: `1px solid ${dark ? "#161619" : t.cardBorder}` }}>
        <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between", gap: 14 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 11, minWidth: 0 }}>
            <span style={{ width: 34, height: 34, flex: "none", borderRadius: "50%", display: "flex", alignItems: "center", justifyContent: "center", border: `1px solid ${acc}66`, background: `radial-gradient(circle at 50% 40%, ${acc}38, transparent 70%)`, animation: "nnRingPulse 2.8s ease-in-out infinite" }}>
              <span style={{ width: 9, height: 9, borderRadius: "50%", background: acc, boxShadow: `0 0 10px ${acc}` }} />
            </span>
            <div style={{ minWidth: 0 }}>
              <div style={{ fontSize: 10, letterSpacing: ".2em", textTransform: "uppercase", color: t.ink3 }}>{agent.short}</div>
              <h2 style={{ margin: "4px 0 0", fontSize: 22, fontWeight: 700, letterSpacing: "-.02em", color: t.ink, lineHeight: 1.1 }}>{agent.name}</h2>
            </div>
          </div>
          <button onClick={onClose} style={{ flex: "none", width: 34, height: 34, borderRadius: 10, display: "flex", alignItems: "center", justifyContent: "center", background: "rgba(255,255,255,.03)", border: `1px solid ${dark ? "#242427" : t.chipBorder}`, color: "#9a9a9f", cursor: "pointer" }}><Icon name="x" size={16} /></button>
        </div>
        <div style={{ display: "flex", gap: 8, marginTop: 16, flexWrap: "wrap" }}>
          <span className="pill" style={{ background: "rgba(255,255,255,.04)", border: "1px solid #2a2a2e", color: "#e2e1df", height: 30, padding: "0 12px" }}><span style={{ width: 7, height: 7, borderRadius: 9, background: llm.color }} /><span style={{ fontWeight: 600 }}>{llm.name}</span></span>
          <span className="pill" style={{ background: S.orb + "1a", border: `1px solid ${S.orb}52`, color: S.orb, height: 30, padding: "0 12px" }}><span style={{ width: 7, height: 7, borderRadius: 6, background: S.orb, boxShadow: `0 0 7px ${S.orb}` }} /><span style={{ fontWeight: 600 }}>{S.label}</span></span>
          <span className="pill" style={{ background: "rgba(174,203,224,.07)", border: "1px solid rgba(174,203,224,.2)", color: "#aecbe0", height: 30, padding: "0 12px" }}><Icon name="plug" size={12} /><span style={{ fontWeight: 600 }}>{agent.mcps.length} MCPs</span></span>
        </div>
      </div>
      {/* tabs */}
      <div className="nn-noscroll" style={{ display: "flex", gap: 18, padding: "16px 26px 0", borderBottom: `1px solid ${dark ? "#161619" : t.cardBorder}`, overflowX: "auto", flexShrink: 0 }}>
        {TABS.map((x) => {
          const on = tab === x.id;
          return (
            <button key={x.id} onClick={() => setTab(x.id)} style={{ position: "relative", display: "flex", alignItems: "center", gap: 7, padding: "0 0 11px", border: 0, background: "transparent", cursor: "pointer", fontSize: 13, fontWeight: 600, fontFamily: "inherit", color: on ? "#fff" : "#6f6f74", whiteSpace: "nowrap", flexShrink: 0 }}>
              <Icon name={x.icon} size={15} stroke={1.8} style={{ color: on ? "#aecbe0" : "currentColor" }} /> {x.label}
              {on && <span style={{ position: "absolute", left: 0, right: 0, bottom: -1, height: 2, borderRadius: 2, background: "#aecbe0", boxShadow: "0 0 9px rgba(174,203,224,.5)" }} />}
            </button>
          );
        })}
      </div>
      {/* body */}
      <div className="panel-body" style={{ flex: 1, overflowY: "auto", padding: "22px 26px 30px" }}>
        {tab === "overview" && <OverviewTab agent={agent} t={tt} />}
        {tab === "runs" && <RunsTab agent={agent} t={tt} dark={dark} />}
        {tab === "playground" && <PlaygroundTab agent={agent} t={tt} dark={dark} />}
        {tab === "prompt" && <PromptTab agent={agent} t={tt} onUpdate={onUpdate} />}
        {tab === "model" && <ModelTab agent={agent} t={tt} onUpdate={onUpdate} />}
        {tab === "mcp" && <McpTab agent={agent} t={tt} onEditCreds={onEditCreds} />}
      </div>
      {/* footer */}
      <div style={{ padding: "18px 26px 22px", borderTop: `1px solid ${dark ? "#161619" : t.cardBorder}`, display: "flex", gap: 11, background: dark ? "linear-gradient(180deg, rgba(7,7,8,0), #070708 40%)" : t.trayBg }}>
        <button onClick={() => onRun([agent.id])} disabled={running} style={{ flex: 1, display: "flex", alignItems: "center", justifyContent: "center", gap: 9, height: 48, borderRadius: 13, background: running ? "#1a1a1d" : "#aecbe0", border: "none", color: running ? "#cfcfcf" : "#06121c", fontSize: 14, fontWeight: 700, cursor: running ? "default" : "pointer", boxShadow: running ? "none" : "0 0 24px rgba(174,203,224,.32)", fontFamily: "inherit" }}>
          <Icon name="play" size={15} fill="currentColor" stroke={0} /> {running ? "Executando…" : "Executar a partir daqui"}
        </button>
        <button style={{ flex: "none", width: 48, height: 48, borderRadius: 13, display: "flex", alignItems: "center", justifyContent: "center", background: "#101012", border: "1px solid #262629", color: "#cfcfcf", cursor: "pointer" }}><Icon name="more-horizontal" size={17} stroke={1.8} /></button>
      </div>
    </div>
  );
}

window.DetailPanel = DetailPanel;
