/* global React, Icon, Badge, PageHead, KTile, Bar, ModulePage */
/* ============================================================
   Modules2 — Modelos · MCPs · ROI/Custo · Novo agente
   ============================================================ */
const Icon2 = window.Icon, Badge2 = window.Badge, PageHead2 = window.PageHead, KTile2 = window.KTile, Bar2 = window.Bar, ModulePage2 = window.ModulePage;
const GridFx2 = window.GridFx;
const { useState: useS2, useEffect: useE2, useRef: useR2 } = React;

// =================== PARQUE DE MODELOS — design NN.ai (Parque de Modelos.dc.html) ===================
const MODEL_FLEET = [
  { color: "#5fd0a6", glow: "rgba(95,208,166,.3)", tileBd: "rgba(95,208,166,.34)", name: "GPT-4o", spec: "OpenAI · contexto 128K", speed: "Rápido", tokens: "1,84M", pct: "59%", custo: "R$ 92,40", acion: "412", preco: "R$ 10,00",
    tags: [["a", "Processamento de Notas Fiscais"], ["r", "Conciliação Contábil"], ["r", "Triagem de Currículos"], ["r", "Geração de Contratos"], ["r", "Atendimento ao Cliente"]] },
  { color: "#e0875f", glow: "rgba(224,135,95,.3)", tileBd: "rgba(224,135,95,.34)", name: "Claude Sonnet 4", spec: "Anthropic · contexto 200K", speed: "Equilibrado", tokens: "980,0k", pct: "31%", custo: "R$ 141,30", acion: "188", preco: "R$ 15,00",
    tags: [["a", "Conciliação Contábil"], ["r", "Processamento de Notas Fiscais"]] },
  { color: "#6e9ff0", glow: "rgba(110,159,240,.3)", tileBd: "rgba(110,159,240,.34)", name: "Gemini 1.5 Pro", spec: "Google · contexto 1M", speed: "Rápido", tokens: "2,31M", pct: "74%", custo: "R$ 22,70", acion: "96", preco: "R$ 5,00",
    tags: [["a", "Triagem de Currículos"]] },
  { color: "#7d83f0", glow: "rgba(125,131,240,.3)", tileBd: "rgba(125,131,240,.34)", name: "DeepSeek V3", spec: "DeepSeek · contexto 64K", speed: "Econômico", tokens: "540,0k", pct: "17%", custo: "R$ 4,30", acion: "58", preco: "R$ 1,10",
    tags: [["a", "Geração de Contratos"]] },
  { color: "#a78bf5", glow: "rgba(167,139,245,.3)", tileBd: "rgba(167,139,245,.34)", name: "Llama 3.1 70B", spec: "Local · on-premise · contexto 128K", speed: "Privado", tokens: "3,12M", pct: "100%", custo: "local", acion: "1.287", preco: "—",
    tags: [["a", "Atendimento ao Cliente"]] },
];
function NnMetric2({ accent, icon, label, value, sub, valueSize = 44 }) {
  return (
    <div className="nn-metric" style={{ position: "relative", borderRadius: 20, padding: "22px 24px", background: "linear-gradient(180deg,rgba(20,21,23,.9),rgba(13,15,17,.92))", border: "1px solid #232327", overflow: "hidden" }}>
      <div style={{ position: "absolute", top: 0, left: 24, right: 24, height: 1, background: `linear-gradient(90deg,transparent,${accent}73,transparent)` }} />
      <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
        <span style={{ width: 32, height: 32, borderRadius: 9, background: `${accent}1a`, border: `1px solid ${accent}3a`, display: "flex", alignItems: "center", justifyContent: "center", color: accent }}>{icon}</span>
        <span style={{ fontSize: 11, letterSpacing: ".16em", color: "rgba(207,207,207,.5)" }}>{label}</span>
      </div>
      <div style={{ fontSize: valueSize, fontWeight: 800, color: "#fff", letterSpacing: "-.03em", marginTop: 14, lineHeight: 1 }}>{value}</div>
      {sub && <span style={{ display: "block", fontSize: 12.5, color: "rgba(207,207,207,.5)", marginTop: 14 }}>{sub}</span>}
    </div>
  );
}

function ModelsModule({ agents, t, dark, onSelect }) {
  const cube = <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d="M12 2.5l8 4.5v9l-8 4.5-8-4.5v-9z" /><path d="M12 12l8-4.5M12 12v9.5M12 12L4 7.5" opacity=".55" /></svg>;
  const cpuI = <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinejoin="round"><rect x="7" y="7" width="10" height="10" rx="2" /><path d="M10 3v3M14 3v3M10 18v3M14 18v3M3 10h3M3 14h3M18 10h3M18 14h3" strokeLinecap="round" /></svg>;
  const coinsI = <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="9" /><path d="M12 7v10M9.2 9.2a3 3 0 1 1 0 5.6" /></svg>;
  const dollarI = <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M12 3v18M16.5 7.5C16 5.7 14.2 4.8 12 4.8 9.4 4.8 7.5 6 7.5 8.1c0 4.6 9 2.8 9 7.5 0 2.1-1.9 3.6-4.5 3.6-2.4 0-4.2-1-4.7-3" /></svg>;

  return (
    <div className="nn-scroll" style={{ position: "absolute", inset: 0, overflowY: "auto", overflowX: "hidden", background: "radial-gradient(ellipse 900px 520px at 30% -8%, rgba(58,143,220,.08), transparent 70%), #000" }}>
      <GridFx2 dark={dark} />
      <div style={{ position: "relative", maxWidth: 1500, margin: "0 auto", padding: "42px 56px 80px" }}>

        {/* page header */}
        <div style={{ display: "flex", alignItems: "center", gap: 22 }}>
          <div style={{ position: "relative", width: 72, height: 72, flex: "none", borderRadius: "50%", background: "radial-gradient(circle at 50% 38%, #16242f, #080d11)", border: "1px solid rgba(174,203,224,.28)", display: "flex", alignItems: "center", justifyContent: "center", boxShadow: "0 0 0 6px rgba(174,203,224,.04), 0 0 60px rgba(58,143,220,.3)" }}>
            <span style={{ position: "absolute", inset: -1, borderRadius: "50%", border: "1px solid rgba(174,203,224,.18)", animation: "nnBreathe 3.4s ease-in-out infinite" }} />
            <svg width="30" height="30" viewBox="0 0 24 24" fill="none" stroke="#cfe0ec" strokeWidth="1.6" strokeLinejoin="round"><rect x="7" y="7" width="10" height="10" rx="2" /><path d="M10 3v3M14 3v3M10 18v3M14 18v3M3 10h3M3 14h3M18 10h3M18 14h3" strokeLinecap="round" /></svg>
          </div>
          <div>
            <h2 style={{ margin: 0, fontSize: 38, fontWeight: 700, letterSpacing: "-.03em", color: "#fff", lineHeight: 1 }}>Parque de Modelos</h2>
            <p style={{ margin: "11px 0 0", fontSize: 15, lineHeight: 1.45, color: "rgba(207,207,207,.62)", maxWidth: 820 }}>Quais LLMs sustentam cada agente, quanto consomem e custam. Misture nuvem e on-premise conforme a sensibilidade do dado.</p>
          </div>
        </div>

        {/* metric cards */}
        <div style={{ display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 20, marginTop: 34 }}>
          <NnMetric2 accent="#aecbe0" icon={cpuI} label="MODELOS EM USO" value="5 / 5" sub="ativos + reserva" />
          <NnMetric2 accent="#aecbe0" icon={coinsI} label="TOKENS HOJE" value="8,79M" sub="somados todos os modelos" />
          <NnMetric2 accent="#5fd0a6" icon={dollarI} label="CUSTO HOJE" value="R$ 260,70" sub="modelos locais não geram custo de API" />
        </div>

        {/* model grid */}
        <div className="rg2" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 20, alignItems: "start", marginTop: 30 }}>
          {MODEL_FLEET.map((m) => (
            <article key={m.name} className="nn-model" style={{ position: "relative", borderRadius: 20, background: "linear-gradient(180deg,#121315,#0d0f11)", border: "1px solid #202024", overflow: "hidden", boxShadow: "0 16px 36px rgba(0,0,0,.4)" }}>
              <span style={{ position: "absolute", top: 0, left: 0, right: 0, height: 3, background: `linear-gradient(90deg,${m.color},rgba(255,255,255,.04))` }} />
              <div style={{ padding: "22px 24px 24px" }}>
                <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
                  <span style={{ width: 46, height: 46, flex: "none", borderRadius: 13, background: "radial-gradient(circle at 50% 35%, #1a1d20, #101113)", border: `1px solid ${m.tileBd}`, display: "flex", alignItems: "center", justifyContent: "center", color: m.color, boxShadow: `0 0 20px ${m.glow}` }}>{cube}</span>
                  <div style={{ minWidth: 0 }}>
                    <h3 style={{ margin: 0, fontSize: 18, fontWeight: 700, color: "#fff", letterSpacing: "-.01em" }}>{m.name}</h3>
                    <p style={{ margin: "3px 0 0", fontSize: 12.5, color: "rgba(207,207,207,.5)" }}>{m.spec}</p>
                  </div>
                  <span style={{ marginLeft: "auto", display: "inline-flex", alignItems: "center", height: 24, padding: "0 11px", borderRadius: 200, background: "rgba(255,255,255,.04)", border: "1px solid #2a2a2e", fontSize: 11, fontWeight: 700, letterSpacing: ".04em", color: m.color }}>{m.speed}</span>
                </div>

                <div style={{ marginTop: 20 }}>
                  <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between" }}>
                    <span style={{ fontSize: 11.5, letterSpacing: ".06em", color: "rgba(207,207,207,.5)" }}>Tokens hoje</span>
                    <span style={{ fontSize: 14, fontWeight: 700, color: "#e8e8e6", fontFeatureSettings: "'tnum'" }}>{m.tokens}</span>
                  </div>
                  <div style={{ position: "relative", height: 8, borderRadius: 200, background: "#1c1d20", marginTop: 9, overflow: "hidden" }}>
                    <div style={{ position: "absolute", left: 0, top: 0, bottom: 0, width: m.pct, borderRadius: 200, background: `linear-gradient(90deg,rgba(255,255,255,.18),${m.color})` }} />
                  </div>
                </div>

                <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 8, marginTop: 20, paddingTop: 18, borderTop: "1px solid #1c1c1f" }}>
                  {[["CUSTO HOJE", m.custo], ["ACION.", m.acion], ["R$/1M OUT", m.preco]].map(([l, v]) => (
                    <div key={l}><div style={{ fontSize: 9.5, letterSpacing: ".13em", color: "rgba(207,207,207,.4)" }}>{l}</div><div style={{ fontSize: 17, fontWeight: 700, color: "#fff", marginTop: 5, fontFeatureSettings: "'tnum'" }}>{v}</div></div>
                  ))}
                </div>

                <div style={{ display: "flex", flexWrap: "wrap", gap: 8, marginTop: 20 }}>
                  {m.tags.map(([kind, label], i) => kind === "a" ? (
                    <span key={i} style={{ display: "inline-flex", alignItems: "center", gap: 7, height: 30, padding: "0 12px", borderRadius: 9, background: "rgba(255,255,255,.04)", border: "1px solid #2a2a2e", fontSize: 12, fontWeight: 600, color: "#eef0ee" }}>
                      <span style={{ width: 6, height: 6, borderRadius: "50%", background: m.color, boxShadow: `0 0 7px ${m.glow}` }} />{label}
                    </span>
                  ) : (
                    <span key={i} style={{ display: "inline-flex", alignItems: "center", gap: 7, height: 30, padding: "0 12px", borderRadius: 9, background: "rgba(255,255,255,.02)", border: "1px solid #222226", fontSize: 12, fontWeight: 600, color: "rgba(207,207,207,.55)" }}>
                      <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" style={{ opacity: .7 }}><circle cx="6" cy="6" r="2.4" /><circle cx="6" cy="18" r="2.4" /><circle cx="18" cy="8" r="2.4" /><path d="M6 8.4v7.2M18 10.4c0 4-3 3.6-6 5.6" /></svg>reserva de {label}
                    </span>
                  ))}
                </div>
              </div>
            </article>
          ))}
        </div>
      </div>
    </div>
  );
}

// =================== CATÁLOGO DE MCPs — design NN.ai (Catálogo de MCPs.dc.html) ===================
const MCP_ICO = {
  scan: <><path d="M4 7V5a1 1 0 0 1 1-1h2" /><path d="M4 17v2a1 1 0 0 0 1 1h2" /><path d="M20 7V5a1 1 0 0 0-1-1h-2" /><path d="M20 17v2a1 1 0 0 1-1 1h-2" /><path d="M7 12h10" /></>,
  doc: <><path d="M7 4h8l4 4v12H7z" /><path d="M14 4v5h5" /><path d="M10 13h6M10 16h4" /></>,
  db: <><ellipse cx="12" cy="6" rx="7" ry="3" /><path d="M5 6v12c0 1.7 3.1 3 7 3s7-1.3 7-3V6" /><path d="M5 12c0 1.7 3.1 3 7 3s7-1.3 7-3" /></>,
  ledger: <><path d="M5 4h14v16H5z" /><path d="M5 9h14M9 4v16" /><path d="M12 12h4M12 15h4" /></>,
  bank: <><path d="M3 21h18" /><path d="M5 21V10l7-5 7 5v11" /><path d="M9 21v-6h6v6" /></>,
  filePerson: <><path d="M7 4h8l4 4v12H7z" /><path d="M14 4v5h5" /><circle cx="11" cy="13" r="1.6" /><path d="M8.5 18c0-1.6 1.1-2.6 2.5-2.6s2.5 1 2.5 2.6" /></>,
  people: <><circle cx="9" cy="8" r="3" /><path d="M3 20c0-3.3 2.7-5.5 6-5.5" /><circle cx="17" cy="10" r="2.4" /><path d="M14.5 20c0-2.4 1.5-4 3.5-4s3.5 1.6 3.5 4" /></>,
  briefcase: <><rect x="3" y="7" width="18" height="13" rx="2" /><path d="M8 7V5a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2" /><path d="M3 12h18" /></>,
  pen: <><path d="M3 17.5 14 6.5l3.5 3.5L6.5 21H3z" /><path d="M14 6.5l3-3 3.5 3.5-3 3" /></>,
  lock: <><rect x="4" y="10" width="16" height="11" rx="2" /><path d="M8 10V7a4 4 0 0 1 8 0v3" /></>,
  chat: <><path d="M5 4h11a3 3 0 0 1 3 3v6a3 3 0 0 1-3 3H9l-4 3v-3a3 3 0 0 1-3-3V7a3 3 0 0 1 3-3Z" /><path d="M8 9h8M8 12h5" /></>,
  book: <><path d="M4 5.5C4 4.7 4.7 4 5.5 4H11v15H5.5C4.7 19 4 18.3 4 17.5z" /><path d="M20 5.5C20 4.7 19.3 4 18.5 4H13v15h5.5c.8 0 1.5-.7 1.5-1.5z" /></>,
  crm: <><circle cx="12" cy="8" r="3.2" /><path d="M5 20c0-3.6 3.1-6 7-6s7 2.4 7 6" /><path d="M19 4l1 1.5L21.5 6 20 7l-1 1.5L18 7l-1.5-1L18 5z" /></>,
  mail: <><rect x="3" y="5" width="18" height="14" rx="2" /><path d="M3 7l9 6 9-6" /></>,
  drive: <><path d="M8 4h8l4 12-4 4H8l-4-4z" /><path d="M8 4l4 12M16 4l-4 12M4 16h16" /></>,
};
const McpIco = ({ k, size = 22 }) => <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">{MCP_ICO[k] || MCP_ICO.doc}</svg>;
const MCP_ST = {
  ok:   { status: "Operacional", color: "#5fd0a6", bg: "rgba(95,208,166,.08)", bd: "rgba(95,208,166,.26)", glow: "rgba(95,208,166,.55)", connBd: "rgba(95,208,166,.4)" },
  warn: { status: "Atenção",     color: "#e3b25b", bg: "rgba(227,178,91,.08)", bd: "rgba(227,178,91,.28)", glow: "rgba(227,178,91,.55)", connBd: "rgba(227,178,91,.4)" },
  fail: { status: "Falha",       color: "#e07a82", bg: "rgba(224,122,130,.1)", bd: "rgba(224,122,130,.32)", glow: "rgba(224,122,130,.6)", connBd: "rgba(224,122,130,.45)" },
};
const MCP_AG = { P: { l: "P", c: "#7fb4e6", g: "rgba(127,180,230,.4)" }, C: { l: "C", c: "#9d97f0", g: "rgba(157,151,240,.4)" }, T: { l: "T", c: "#5fd0a6", g: "rgba(95,208,166,.4)" }, G: { l: "G", c: "#e0b07f", g: "rgba(224,176,127,.4)" }, A: { l: "A", c: "#6ec5e0", g: "rgba(110,197,224,.4)" } };
const MCP_CONNECTED = [
  ["OCR Documentos", "Documentos · 412 cham./dia · 180 ms", "ok", 4, ["P"], "scan"],
  ["SEFAZ · NF-e", "Fiscal · 412 cham./dia · 320 ms", "ok", 4, ["P"], "doc"],
  ["TOTVS Protheus", "ERP · 600 cham./dia · 225 ms", "ok", 5, ["P", "C"], "db"],
  ["Plano de Contas", "Contábil · 188 cham./dia · 90 ms", "ok", 3, ["C"], "ledger"],
  ["Open Finance", "Bancário · 188 cham./dia · 1,80 s", "warn", 4, ["C"], "bank"],
  ["Parser de CV", "RH · 96 cham./dia · 140 ms", "ok", 4, ["T"], "filePerson"],
  ["ATS · LinkedIn", "RH · 96 cham./dia · 420 ms", "ok", 4, ["T"], "people"],
  ["Banco de Vagas", "RH · 96 cham./dia · 110 ms", "ok", 3, ["T"], "briefcase"],
  ["Templates Jurídicos", "Jurídico · 58 cham./dia · 70 ms", "ok", 4, ["G"], "doc"],
  ["Assinatura Digital", "Jurídico · 58 cham./dia · 260 ms", "ok", 4, ["G"], "pen"],
  ["Cofre de Documentos", "Documentos · 58 cham./dia · 150 ms", "ok", 4, ["G"], "lock"],
  ["WhatsApp API", "Comunicação · 1.287 cham./dia · —", "fail", 4, ["A"], "chat"],
  ["Base de Conhecimento", "Conhecimento · 1.287 cham./dia · 120 ms", "ok", 3, ["A"], "book"],
  ["CRM", "CRM · 1.287 cham./dia · 300 ms", "ok", 4, ["A"], "crm"],
  ["E-mail", "Comunicação · 640 cham./dia · 180 ms", "ok", 3, ["A"], "mail"],
];
const MCP_AVAIL = [["Receita Federal", "Fiscal", "bank", 5], ["Banco Central · PIX", "Bancário", "bank", 4], ["Google Drive", "Documentos", "drive", 6], ["Slack", "Comunicação", "chat", 4]];

function McpStepIcon({ state }) {
  if (state === "done") return <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.6" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12.5l4.5 4.5L19 7.5" /></svg>;
  if (state === "fail") return <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.6" strokeLinecap="round"><path d="M6 6l12 12M18 6L6 18" /></svg>;
  if (state === "running") return <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" style={{ animation: "nnSpin .8s linear infinite" }}><path d="M12 3a9 9 0 1 0 9 9" /></svg>;
  return <span style={{ width: 6, height: 6, borderRadius: "50%", background: "currentColor", display: "block" }} />;
}

function mcpStepStyle(state) {
  if (state === "done") return { ringBg: "rgba(95,208,166,.1)", ringBd: "rgba(95,208,166,.34)", ringColor: "#5fd0a6", labelColor: "#fff", subColor: "rgba(207,207,207,.55)" };
  if (state === "fail") return { ringBg: "rgba(224,122,130,.12)", ringBd: "rgba(224,122,130,.4)", ringColor: "#f09aa1", labelColor: "#fff", subColor: "#f09aa1" };
  if (state === "running") return { ringBg: "rgba(174,203,224,.1)", ringBd: "rgba(174,203,224,.4)", ringColor: "#aecbe0", labelColor: "#fff", subColor: "#aecbe0" };
  return { ringBg: "rgba(255,255,255,.02)", ringBd: "#26262a", ringColor: "#54545a", labelColor: "rgba(207,207,207,.45)", subColor: "rgba(207,207,207,.3)" };
}

function TestConnectionModal({ mcp, onClose }) {
  const [step, setStep] = useS2(0);
  const [status, setStatus] = useS2("running");
  const timer = useR2(null);
  const fail = mcp.name === "WhatsApp API";
  const labels = ["Autenticação da chave", "Handshake com o endpoint", "Descoberta de tools", "Chamada de exemplo", "Validação da resposta"];
  const lats = ["118 ms", "174 ms", "92 ms", "236 ms", "58 ms"];

  const run = React.useCallback(() => {
    clearTimeout(timer.current);
    setStep(0);
    setStatus("running");
    const tick = (i) => {
      timer.current = setTimeout(() => {
        if (fail && i === 2) { setStep(1); setStatus("fail"); return; }
        const done = i >= labels.length;
        setStep(i);
        setStatus(done ? "done" : "running");
        if (!done) tick(i + 1);
      }, i === 1 ? 420 : 720);
    };
    tick(1);
  }, [fail, labels.length]);

  useE2(() => { run(); return () => clearTimeout(timer.current); }, [run]);

  const stateOf = (i) => {
    if (status === "fail" && i === step) return "fail";
    if (i < step) return "done";
    if (i === step && status === "running") return "running";
    return "pending";
  };
  const ok = status === "done";
  const failed = status === "fail";
  const resultColor = ok ? "#7fe0bc" : "#f09aa1";
  const IconComp = window.McpCatalogIcon;

  return (
    <div onClick={onClose} style={{ position: "fixed", inset: 0, zIndex: 50, display: "flex", alignItems: "center", justifyContent: "center", padding: 32, background: "rgba(0,0,0,.62)", backdropFilter: "blur(5px)", WebkitBackdropFilter: "blur(5px)", animation: "nnScrimIn .25s ease" }}>
      <div onClick={(e) => e.stopPropagation()} style={{ width: "100%", maxWidth: 540, maxHeight: "88vh", display: "flex", flexDirection: "column", borderRadius: 22, background: "linear-gradient(180deg,#111113,#0a0a0c)", border: "1px solid #232327", boxShadow: "0 40px 100px rgba(0,0,0,.66), inset 0 1px 0 rgba(255,255,255,.04)", overflow: "hidden", animation: "nnModalIn .4s cubic-bezier(.22,1,.36,1)" }}>
        <div style={{ flex: "none", display: "flex", alignItems: "center", gap: 14, padding: "24px 26px 20px", borderBottom: "1px solid #19191c" }}>
          <span style={{ position: "relative", width: 46, height: 46, flex: "none", borderRadius: 13, background: "radial-gradient(circle at 50% 35%, #1a1d20, #101113)", border: "1px solid rgba(174,203,224,.22)", display: "flex", alignItems: "center", justifyContent: "center", color: "#aecbe0" }}>{IconComp ? <IconComp k={mcp.icon} /> : <McpIco k={mcp.icon} />}</span>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 10, letterSpacing: ".2em", textTransform: "uppercase", color: "rgba(207,207,207,.5)" }}>Teste de conexão</div>
            <h2 style={{ margin: "4px 0 0", fontSize: 20, fontWeight: 700, letterSpacing: "-.02em", color: "#fff", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{mcp.name}</h2>
          </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 #242427", color: "#9a9a9f", cursor: "pointer" }}>
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M6 6l12 12M18 6L6 18" /></svg>
          </button>
        </div>

        <div className="nn-scroll" style={{ flex: 1, overflowY: "auto", padding: "22px 26px 24px" }}>
          {labels.map((label, i) => {
            const st = stateOf(i);
            const sty = mcpStepStyle(st);
            const sub = st === "done" ? lats[i] : st === "running" ? "..." : st === "fail" ? "timeout" : "";
            return (
              <div key={label} style={{ display: "flex", alignItems: "center", gap: 14, padding: "11px 0", animation: "nnStepIn .3s ease" }}>
                <span style={{ width: 30, height: 30, flex: "none", borderRadius: "50%", display: "flex", alignItems: "center", justifyContent: "center", background: sty.ringBg, border: `1px solid ${sty.ringBd}`, color: sty.ringColor }}><McpStepIcon state={st} /></span>
                <div style={{ flex: 1, minWidth: 0 }}><div style={{ fontSize: 13.5, fontWeight: 600, color: sty.labelColor }}>{label}</div></div>
                <span style={{ flex: "none", fontSize: 12, fontWeight: 600, color: sty.subColor, fontFamily: "var(--font-mono)" }}>{sub}</span>
              </div>
            );
          })}

          {(ok || failed) && (
            <div style={{ marginTop: 18, borderRadius: 15, background: ok ? "rgba(95,208,166,.06)" : "rgba(224,122,130,.06)", border: `1px solid ${ok ? "rgba(95,208,166,.26)" : "rgba(224,122,130,.3)"}`, padding: "18px 20px", animation: "nnStepIn .35s ease" }}>
              <div style={{ display: "flex", alignItems: "center", gap: 11 }}>
                <span style={{ width: 32, height: 32, flex: "none", borderRadius: "50%", display: "flex", alignItems: "center", justifyContent: "center", background: ok ? "rgba(95,208,166,.14)" : "rgba(224,122,130,.14)", color: resultColor }}><McpStepIcon state={ok ? "done" : "fail"} /></span>
                <div><div style={{ fontSize: 14.5, fontWeight: 700, color: resultColor }}>{ok ? "Conexão saudável" : "Falha na conexão"}</div><div style={{ fontSize: 12, color: "rgba(207,207,207,.6)", marginTop: 2 }}>{ok ? "Todos os checks passaram com sucesso." : "Endpoint não respondeu (timeout após 30 s)."}</div></div>
              </div>
              {ok && (
                <div style={{ display: "flex", gap: 10, marginTop: 16 }}>
                  <div style={{ flex: 1, padding: "11px 13px", borderRadius: 11, background: "rgba(255,255,255,.02)", border: "1px solid #1f1f22" }}><div style={{ fontSize: 9, letterSpacing: ".13em", color: "rgba(207,207,207,.42)" }}>LATÊNCIA TOTAL</div><div style={{ fontSize: 16, fontWeight: 700, color: "#fff", marginTop: 5 }}>678 ms</div></div>
                  <div style={{ flex: 1, padding: "11px 13px", borderRadius: 11, background: "rgba(255,255,255,.02)", border: "1px solid #1f1f22" }}><div style={{ fontSize: 9, letterSpacing: ".13em", color: "rgba(207,207,207,.42)" }}>TOOLS VERIFICADAS</div><div style={{ fontSize: 16, fontWeight: 700, color: "#fff", marginTop: 5 }}>{mcp.tools} / {mcp.tools}</div></div>
                </div>
              )}
              <div style={{ marginTop: 14, borderRadius: 11, background: "#08080a", border: "1px solid #1c1c1f", padding: "14px 16px", fontFamily: "var(--font-mono)", fontSize: 12, lineHeight: 1.7, color: "rgba(207,207,207,.78)", whiteSpace: "pre", overflowX: "auto" }}>{ok ? '{\n  "ok": true,\n  "tool": "ping",\n  "latency_ms": 236,\n  "result": "pong"\n}' : '{\n  "ok": false,\n  "error": "ECONNREFUSED",\n  "detail": "no response from host",\n  "retries": 3\n}'}</div>
            </div>
          )}
        </div>

        <div style={{ flex: "none", display: "flex", alignItems: "center", justifyContent: "space-between", gap: 14, padding: "16px 26px", borderTop: "1px solid #19191c", background: "#0a0a0c" }}>
          <span style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 12.5, color: ok ? "#7fe0bc" : failed ? "#f09aa1" : "rgba(207,207,207,.5)" }}>{ok || failed ? <span style={{ width: 7, height: 7, borderRadius: "50%", background: ok ? "#5fd0a6" : "#e07a82", boxShadow: `0 0 7px ${ok ? "#5fd0a6" : "#e07a82"}` }} /> : <McpStepIcon state="running" />}{ok ? "Teste concluído" : failed ? "Teste falhou" : "Executando teste..."}</span>
          <div style={{ display: "flex", gap: 10 }}>
            <button onClick={onClose} style={{ height: 42, padding: "0 18px", borderRadius: 11, background: "transparent", border: "1px solid #2a2a2e", color: "#d8d8d8", fontSize: 13, fontWeight: 600, cursor: "pointer", fontFamily: "inherit" }}>Fechar</button>
            <button onClick={run} style={{ display: "flex", alignItems: "center", gap: 8, height: 42, padding: "0 18px", borderRadius: 11, background: "rgba(174,203,224,.1)", border: "1px solid rgba(174,203,224,.28)", color: "#cfe0ec", fontSize: 13, fontWeight: 700, cursor: "pointer", fontFamily: "inherit" }}><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round" strokeLinejoin="round"><path d="M3 12a9 9 0 1 0 3-6.7L3 8" /><path d="M3 4v4h4" /></svg>Rodar novamente</button>
          </div>
        </div>
      </div>
    </div>
  );
}

function scopesForConnect(cat) {
  const map = {
    "Fiscal": ["nfe.read", "nfe.issue", "sefaz.query"],
    "Bancário": ["accounts.read", "pix.send", "transactions.read"],
    "Documentos": ["files.read", "files.write", "folders.list"],
    "Comunicação": ["messages.send", "channels.read", "users.read"],
  };
  return map[cat] || ["read", "write"];
}

function ConnectMcpModal({ item, onClose }) {
  const [phase, setPhase] = useS2("form");
  const [step, setStep] = useS2(0);
  const timer = useR2(null);
  const IconComp = window.McpCatalogIcon;
  const steps = ["Enviando credenciais", "Estabelecendo conexão segura", "Verificando permissões"];

  useE2(() => () => clearTimeout(timer.current), []);

  const doConnect = () => {
    clearTimeout(timer.current);
    setPhase("connecting");
    setStep(0);
    const tick = (i) => {
      timer.current = setTimeout(() => {
        const done = i >= steps.length;
        setStep(i);
        if (done) setPhase("done");
        else tick(i + 1);
      }, 760);
    };
    tick(1);
  };

  return (
    <div onClick={onClose} style={{ position: "fixed", inset: 0, zIndex: 50, display: "flex", alignItems: "center", justifyContent: "center", padding: 32, background: "rgba(0,0,0,.62)", backdropFilter: "blur(5px)", WebkitBackdropFilter: "blur(5px)", animation: "nnScrimIn .25s ease" }}>
      <div onClick={(e) => e.stopPropagation()} style={{ width: "100%", maxWidth: 520, maxHeight: "88vh", display: "flex", flexDirection: "column", borderRadius: 22, background: "linear-gradient(180deg,#111113,#0a0a0c)", border: "1px solid #232327", boxShadow: "0 40px 100px rgba(0,0,0,.66), inset 0 1px 0 rgba(255,255,255,.04)", overflow: "hidden", animation: "nnModalIn .4s cubic-bezier(.22,1,.36,1)" }}>
        <div style={{ flex: "none", display: "flex", alignItems: "center", gap: 14, padding: "24px 26px 20px", borderBottom: "1px solid #19191c" }}>
          <span style={{ width: 46, height: 46, flex: "none", borderRadius: 13, background: "rgba(174,203,224,.08)", border: "1px solid #232327", display: "flex", alignItems: "center", justifyContent: "center", color: "#aecbe0" }}>{IconComp ? <IconComp k={item.icon} /> : <McpIco k={item.icon} />}</span>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 10, letterSpacing: ".2em", textTransform: "uppercase", color: "rgba(207,207,207,.5)" }}>Conectar integração</div>
            <h2 style={{ margin: "4px 0 0", fontSize: 20, fontWeight: 700, letterSpacing: "-.02em", color: "#fff", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{item.name}</h2>
          </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 #242427", color: "#9a9a9f", cursor: "pointer" }}><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M6 6l12 12M18 6L6 18" /></svg></button>
        </div>

        <div className="nn-scroll" style={{ flex: 1, overflowY: "auto", padding: "24px 26px" }}>
          {phase === "form" && (
            <div style={{ animation: "nnStepIn .3s ease" }}>
              <p style={{ margin: "0 0 20px", fontSize: 13.5, lineHeight: 1.55, color: "rgba(207,207,207,.62)" }}>Informe a chave de API de <strong style={{ color: "#fff", fontWeight: 700 }}>{item.name}</strong> para autorizar a NN a acessar este serviço. Você pode revogar o acesso a qualquer momento.</p>
              <label style={{ display: "block", fontSize: 10, letterSpacing: ".16em", textTransform: "uppercase", color: "rgba(207,207,207,.45)", marginBottom: 9 }}>Chave de API</label>
              <input className="nn-cfield" placeholder="cole sua chave aqui" style={{ width: "100%", height: 46, padding: "0 14px", borderRadius: 11, background: "#0e0e10", border: "1px solid #242427", color: "#fff", fontSize: 13, fontFamily: "var(--font-mono)", marginBottom: 20 }} />
              <div style={{ fontSize: 10, letterSpacing: ".16em", textTransform: "uppercase", color: "rgba(207,207,207,.45)", marginBottom: 12 }}>Permissões solicitadas</div>
              <div style={{ display: "flex", flexDirection: "column", gap: 9 }}>
                {scopesForConnect(item.cat).map((s) => <div key={s} style={{ display: "flex", alignItems: "center", gap: 11, padding: "11px 13px", borderRadius: 11, background: "rgba(255,255,255,.02)", border: "1px solid #1f1f22" }}><svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="#5fd0a6" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12.5l4.5 4.5L19 7.5" /></svg><span style={{ fontSize: 13, color: "#e2e1df", fontFamily: "var(--font-mono)" }}>{s}</span></div>)}
              </div>
            </div>
          )}
          {phase === "connecting" && (
            <div style={{ padding: "6px 0", animation: "nnStepIn .3s ease" }}>
              {steps.map((label, i) => {
                const st = i < step ? "done" : (i === step ? "running" : "pending");
                const sty = mcpStepStyle(st);
                return <div key={label} style={{ display: "flex", alignItems: "center", gap: 14, padding: "13px 0" }}><span style={{ width: 30, height: 30, flex: "none", borderRadius: "50%", display: "flex", alignItems: "center", justifyContent: "center", background: sty.ringBg, border: `1px solid ${sty.ringBd}`, color: sty.ringColor }}><McpStepIcon state={st} /></span><div style={{ flex: 1, fontSize: 13.5, fontWeight: 600, color: sty.labelColor }}>{label}</div></div>;
              })}
            </div>
          )}
          {phase === "done" && (
            <div style={{ display: "flex", flexDirection: "column", alignItems: "center", textAlign: "center", padding: "14px 10px 6px", animation: "nnStepIn .35s ease" }}>
              <span style={{ width: 62, height: 62, borderRadius: "50%", display: "flex", alignItems: "center", justifyContent: "center", background: "rgba(95,208,166,.1)", border: "1px solid rgba(95,208,166,.34)", color: "#5fd0a6", boxShadow: "0 0 30px rgba(95,208,166,.22)" }}><McpStepIcon state="done" /></span>
              <h3 style={{ margin: "18px 0 0", fontSize: 19, fontWeight: 700, color: "#fff", letterSpacing: "-.01em" }}>{item.name} conectado</h3>
              <p style={{ margin: "8px 0 0", fontSize: 13, color: "rgba(207,207,207,.6)", lineHeight: 1.5, maxWidth: 340 }}>A integração está ativa e <strong style={{ color: "#cfe0ec" }}>{item.tools} tools</strong> já estão disponíveis para os agentes.</p>
            </div>
          )}
        </div>

        <div style={{ flex: "none", display: "flex", alignItems: "center", justifyContent: "flex-end", gap: 10, padding: "16px 26px", borderTop: "1px solid #19191c", background: "#0a0a0c" }}>
          {phase === "form" && <><button onClick={onClose} style={{ height: 44, padding: "0 18px", borderRadius: 11, background: "transparent", border: "1px solid #2a2a2e", color: "#d8d8d8", fontSize: 13, fontWeight: 600, cursor: "pointer", fontFamily: "inherit" }}>Cancelar</button><button onClick={doConnect} style={{ display: "flex", alignItems: "center", gap: 9, height: 44, padding: "0 20px", borderRadius: 11, background: "#aecbe0", border: "none", color: "#06121c", fontSize: 13, fontWeight: 700, cursor: "pointer", boxShadow: "0 0 22px rgba(174,203,224,.3)", fontFamily: "inherit" }}><svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M9 2v5M15 2v5M8 7h8v3a4 4 0 0 1-8 0V7ZM12 14v5" /></svg>Conectar</button></>}
          {phase === "connecting" && <button style={{ display: "flex", alignItems: "center", gap: 9, height: 44, padding: "0 20px", borderRadius: 11, background: "rgba(174,203,224,.16)", border: "none", color: "rgba(6,18,28,.55)", fontSize: 13, fontWeight: 700, cursor: "default", fontFamily: "inherit" }}><McpStepIcon state="running" />Conectando...</button>}
          {phase === "done" && <button onClick={onClose} style={{ display: "flex", alignItems: "center", gap: 9, height: 44, padding: "0 22px", borderRadius: 11, background: "#aecbe0", border: "none", color: "#06121c", fontSize: 13, fontWeight: 700, cursor: "pointer", boxShadow: "0 0 22px rgba(174,203,224,.3)", fontFamily: "inherit" }}>Concluir</button>}
        </div>
      </div>
    </div>
  );
}

function McpsModule({ agents, t, dark, onSelect, onEditCreds }) {
  const totalTools = MCP_CONNECTED.reduce((s, m) => s + m[3], 0);
  const fails = MCP_CONNECTED.filter((m) => m[2] === "fail").length;
  const [testMcp, setTestMcp] = useS2(null);
  const [connectMcp, setConnectMcp] = useS2(null);
  return (
    <div className="nn-scroll" style={{ position: "absolute", inset: 0, overflowY: "auto", overflowX: "hidden", background: "radial-gradient(ellipse 900px 520px at 30% -8%, rgba(58,143,220,.08), transparent 70%), #000" }}>
      <GridFx2 dark={dark} />
      <div style={{ position: "relative", maxWidth: 1500, margin: "0 auto", padding: "42px 56px 80px" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 22 }}>
          <div style={{ position: "relative", width: 72, height: 72, flex: "none", borderRadius: "50%", background: "radial-gradient(circle at 50% 38%, #16242f, #080d11)", border: "1px solid rgba(174,203,224,.28)", display: "flex", alignItems: "center", justifyContent: "center", boxShadow: "0 0 0 6px rgba(174,203,224,.04), 0 0 60px rgba(58,143,220,.3)" }}>
            <span style={{ position: "absolute", inset: -1, borderRadius: "50%", border: "1px solid rgba(174,203,224,.18)", animation: "nnBreathe 3.4s ease-in-out infinite" }} />
            <svg width="30" height="30" viewBox="0 0 24 24" fill="none" stroke="#cfe0ec" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d="M9 2v6M15 2v6M7 8h10v3a5 5 0 0 1-10 0V8ZM12 16v6" /></svg>
          </div>
          <div>
            <h2 style={{ margin: 0, fontSize: 38, fontWeight: 700, letterSpacing: "-.03em", color: "#fff", lineHeight: 1 }}>Catálogo de MCPs</h2>
            <p style={{ margin: "11px 0 0", fontSize: 15, lineHeight: 1.45, color: "rgba(207,207,207,.62)", maxWidth: 880 }}>Cada MCP é uma caixa de ferramentas: conecte uma vez e ela expõe várias tools — as ferramentas que dão poderes ao agente. Abra um MCP para ver o que tem dentro.</p>
          </div>
        </div>

        <div style={{ display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 20, marginTop: 34 }}>
          <NnMetric2 accent="#aecbe0" icon={<McpIco k="db" size={16} />} label="CAIXAS CONECTADAS" value={MCP_CONNECTED.length} sub="MCPs em escopo global" />
          <NnMetric2 accent="#aecbe0" icon={<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M14.5 5.5a3.5 3.5 0 0 0-4.9 4.9l-6.1 6.1 2.1 2.1 6.1-6.1a3.5 3.5 0 0 0 4.9-4.9l-2 2-2-2z" /></svg>} label="FERRAMENTAS (TOOLS)" value={totalTools} sub="expostas pelas caixas" />
          <div className="nn-metric" style={{ position: "relative", borderRadius: 20, padding: "22px 24px", background: "linear-gradient(180deg,rgba(22,17,18,.92),rgba(14,11,12,.94))", border: "1px solid rgba(224,122,130,.24)", overflow: "hidden", boxShadow: "0 0 40px rgba(224,122,130,.06)" }}>
            <div style={{ position: "absolute", top: 0, left: 24, right: 24, height: 1, background: "linear-gradient(90deg,transparent,rgba(224,122,130,.5),transparent)" }} />
            <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
              <span style={{ width: 32, height: 32, borderRadius: 9, background: "rgba(224,122,130,.12)", border: "1px solid rgba(224,122,130,.3)", display: "flex", alignItems: "center", justifyContent: "center", color: "#f09aa1" }}><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round" strokeLinejoin="round"><path d="M12 3l9 16H3z" /><path d="M12 9v4M12 16v.5" /></svg></span>
              <span style={{ fontSize: 11, letterSpacing: ".16em", color: "rgba(207,207,207,.5)" }}>COM FALHA</span>
            </div>
            <div style={{ fontSize: 44, fontWeight: 800, color: "#fff", letterSpacing: "-.03em", marginTop: 14, lineHeight: 1 }}>{fails}</div>
            <span style={{ display: "block", fontSize: 12.5, color: "rgba(240,154,161,.7)", marginTop: 14 }}>exige reconexão</span>
          </div>
        </div>

        <div style={{ display: "flex", alignItems: "center", gap: 12, marginTop: 44 }}>
          <h3 style={{ margin: 0, fontSize: 21, fontWeight: 700, color: "#fff", letterSpacing: "-.01em" }}>Conectadas</h3>
          <span style={{ display: "inline-flex", alignItems: "center", height: 24, padding: "0 11px", borderRadius: 200, background: "rgba(95,208,166,.08)", border: "1px solid rgba(95,208,166,.24)", fontSize: 11.5, fontWeight: 700, color: "#7fe0bc" }}>{MCP_CONNECTED.length}</span>
        </div>

        <div className="rg2" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 18, marginTop: 18 }}>
          {MCP_CONNECTED.map(([name, meta, sev, tools, ags, ic]) => {
            const S = MCP_ST[sev];
            const mcpPayload = { name, meta, status: sev, tools, icon: ic, catalogIcon: ic };
            return (
              <article key={name} className="nn-mcp" style={{ borderRadius: 18, background: "linear-gradient(180deg,#121315,#0d0f11)", border: "1px solid #202024", overflow: "hidden", boxShadow: "0 14px 32px rgba(0,0,0,.38)" }}>
                <div style={{ padding: "20px 22px" }}>
                  <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
                    <span style={{ position: "relative", width: 46, height: 46, flex: "none", borderRadius: 13, background: "radial-gradient(circle at 50% 35%, #1a1d20, #101113)", border: "1px solid rgba(174,203,224,.2)", display: "flex", alignItems: "center", justifyContent: "center", color: "#aecbe0" }}>
                      <McpIco k={ic} />
                      <span style={{ position: "absolute", right: -3, bottom: -3, width: 16, height: 16, borderRadius: "50%", background: "#0c0d0f", border: `1px solid ${S.connBd}`, display: "flex", alignItems: "center", justifyContent: "center", color: S.color }}><svg width="9" height="9" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.6" strokeLinecap="round" strokeLinejoin="round"><path d="M9 2v5M15 2v5M8 7h8v3a4 4 0 0 1-8 0V7ZM12 14v5" /></svg></span>
                    </span>
                    <div style={{ minWidth: 0, flex: 1 }}>
                      <h4 style={{ margin: 0, fontSize: 16.5, fontWeight: 700, color: "#fff", letterSpacing: "-.01em", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{name}</h4>
                      <p style={{ margin: "3px 0 0", fontSize: 12, color: "rgba(207,207,207,.5)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{meta}</p>
                    </div>
                    <div style={{ display: "flex", alignItems: "center", gap: 9, flex: "none" }}>
                      <span style={{ display: "inline-flex", alignItems: "center", gap: 7, height: 26, padding: "0 11px", borderRadius: 200, fontSize: 11.5, fontWeight: 700, color: S.color, background: S.bg, border: `1px solid ${S.bd}` }}>
                        <span style={{ width: 6, height: 6, borderRadius: "50%", background: S.color, boxShadow: `0 0 7px ${S.glow}` }} />{S.status}
                      </span>
                      <span style={{ display: "inline-flex", alignItems: "center", gap: 5, height: 26, padding: "0 9px", borderRadius: 9, background: "rgba(255,255,255,.03)", border: "1px solid #26262a", fontSize: 11.5, fontWeight: 600, color: "rgba(207,207,207,.7)" }}>
                        <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="#aecbe0" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><circle cx="8" cy="15" r="4" /><path d="M10.8 12.2 19 4M16 7l2 2M14 9l2 2" /></svg>{tools}
                        <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="#5b5b60" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><path d="M9 6l6 6-6 6" /></svg>
                      </span>
                    </div>
                  </div>
                  <div style={{ height: 1, background: "#1c1c1f", margin: "18px 0 0" }} />
                  <div style={{ display: "flex", alignItems: "center", gap: 14, marginTop: 16 }}>
                    <span style={{ fontSize: 10, letterSpacing: ".16em", color: "rgba(207,207,207,.42)" }}>USADA POR</span>
                    <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
                      {ags.map((k) => { const a = MCP_AG[k]; return <span key={k} style={{ width: 24, height: 24, borderRadius: 7, display: "flex", alignItems: "center", justifyContent: "center", fontSize: 11, fontWeight: 700, color: "#0a1016", background: a.c, boxShadow: `0 0 10px ${a.g}` }}>{a.l}</span>; })}
                    </div>
                    <div style={{ display: "flex", alignItems: "center", gap: 10, marginLeft: "auto" }}>
                      <button className="nn-btn" onClick={() => onEditCreds && onEditCreds(mcpPayload)} style={{ display: "flex", alignItems: "center", gap: 7, height: 36, padding: "0 14px", borderRadius: 10, background: "rgba(255,255,255,.02)", border: "1px solid #2a2a2e", color: "#cfcfcf", fontSize: 12.5, fontWeight: 600, cursor: "pointer", fontFamily: "inherit" }}>
                        <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><circle cx="8" cy="15" r="4" /><path d="M10.8 12.2 19 4M16 7l2 2M14 9l2 2" /></svg>Credenciais
                      </button>
                      <button className="nn-connect" onClick={() => setTestMcp(mcpPayload)} style={{ display: "flex", alignItems: "center", height: 36, padding: "0 18px", borderRadius: 10, background: "rgba(174,203,224,.08)", border: "1px solid rgba(174,203,224,.26)", color: "#cfe0ec", fontSize: 12.5, fontWeight: 700, cursor: "pointer", fontFamily: "inherit", transition: "background .3s, border-color .3s, color .3s" }}>Testar</button>
                    </div>
                  </div>
                </div>
              </article>
            );
          })}
        </div>

        <h3 style={{ margin: "48px 0 0", fontSize: 21, fontWeight: 700, color: "#fff", letterSpacing: "-.01em" }}>Disponíveis para conectar</h3>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 18, marginTop: 18 }}>
          {MCP_AVAIL.map(([name, cat, ic, tools]) => (
            <article key={name} className="nn-avail" style={{ borderRadius: 18, background: "linear-gradient(180deg,#0e0f11,#0a0b0d)", border: "1px dashed #26282c", padding: "24px 22px 20px", display: "flex", flexDirection: "column", alignItems: "center", textAlign: "center" }}>
              <span style={{ width: 48, height: 48, borderRadius: 13, background: "rgba(255,255,255,.03)", border: "1px solid #232327", display: "flex", alignItems: "center", justifyContent: "center", color: "rgba(174,203,224,.7)" }}><McpIco k={ic} /></span>
              <h4 style={{ margin: "14px 0 0", fontSize: 15.5, fontWeight: 700, color: "#fff" }}>{name}</h4>
              <p style={{ margin: "4px 0 0", fontSize: 12, color: "rgba(207,207,207,.45)" }}>{cat}</p>
              <button className="nn-connect" onClick={() => setConnectMcp({ name, cat, icon: ic, tools })} style={{ display: "flex", alignItems: "center", justifyContent: "center", gap: 8, width: "100%", height: 40, marginTop: 18, borderRadius: 11, background: "rgba(174,203,224,.05)", border: "1px solid #2a2d31", color: "#cfd6dc", fontSize: 12.5, fontWeight: 700, cursor: "pointer", fontFamily: "inherit", transition: "background .3s, border-color .3s, color .3s" }}>
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round"><path d="M12 5v14M5 12h14" /></svg>Conectar
              </button>
            </article>
          ))}
        </div>
      </div>
      {testMcp && <TestConnectionModal mcp={testMcp} onClose={() => setTestMcp(null)} />}
      {connectMcp && <ConnectMcpModal item={connectMcp} onClose={() => setConnectMcp(null)} />}
    </div>
  );
}

// =================== ROI & CUSTO — design NN.ai (ROI & Custo.dc.html) ===================
const ROI_CHIPS = [["Toda a operação", "transparent"], ["Processamento de Notas Fiscais", "#7fb4e6"], ["Conciliação Contábil", "#9d97f0"], ["Triagem de Currículos", "#5fd0a6"], ["Geração de Contratos", "#e0b07f"], ["Atendimento ao Cliente", "#6ec5e0"]];
const ROI_AGENTS = [
  { name: "Processamento de Notas Fiscais", color: "#7fb4e6", glow: "rgba(127,180,230,.5)", custo: "R$ 2.710,00", orc: "R$ 4.000,00", pct: "68%", economia: "R$ 18.705,60", bar: "#5fd0a6", barFrom: "rgba(95,208,166,.4)" },
  { name: "Conciliação Contábil", color: "#9d97f0", glow: "rgba(157,151,240,.5)", custo: "R$ 4.180,00", orc: "R$ 5.000,00", pct: "84%", economia: "R$ 12.080,70", bar: "#e3b25b", barFrom: "rgba(227,178,91,.4)" },
  { name: "Triagem de Currículos", color: "#5fd0a6", glow: "rgba(95,208,166,.5)", custo: "R$ 690,00", orc: "R$ 1.500,00", pct: "46%", economia: "R$ 10.521,90", bar: "#5fd0a6", barFrom: "rgba(95,208,166,.4)" },
  { name: "Geração de Contratos", color: "#e0b07f", glow: "rgba(224,176,127,.5)", custo: "R$ 132,00", orc: "R$ 800,00", pct: "17%", economia: "R$ 7.404,30", bar: "#5fd0a6", barFrom: "rgba(95,208,166,.4)" },
  { name: "Atendimento ao Cliente", color: "#6ec5e0", glow: "rgba(110,197,224,.5)", custo: "R$ 420,00", orc: "R$ 700,00", pct: "60%", economia: "R$ 24.161,40", bar: "#5fd0a6", barFrom: "rgba(95,208,166,.4)" },
];

function RoiModule({ agents, t, dark, onSelect }) {
  const [chartFilter, setChartFilter] = useS2("Toda a operação");
  const [threshold, setThreshold] = useS2("90%");
  const [emailOn, setEmailOn] = useS2(true);
  const [whatsOn, setWhatsOn] = useS2(false);
  const kpi = (special, accentBar, icon, label, value, sub, subColor) => (
    <div className="nn-metric" style={{ position: "relative", borderRadius: 20, padding: "20px 22px", background: special ? "linear-gradient(180deg,rgba(18,22,20,.92),rgba(12,15,13,.94))" : "linear-gradient(180deg,rgba(20,21,23,.9),rgba(13,15,17,.92))", border: `1px solid ${special ? "rgba(95,208,166,.22)" : "#232327"}`, overflow: "hidden" }}>
      <div style={{ position: "absolute", top: 0, left: 22, right: 22, height: 1, background: `linear-gradient(90deg,transparent,${accentBar},transparent)` }} />
      <div style={{ display: "flex", alignItems: "center", gap: 9 }}>{icon}<span style={{ fontSize: 10.5, letterSpacing: ".15em", color: "rgba(207,207,207,.5)" }}>{label}</span></div>
      <div style={{ fontSize: 32, fontWeight: 800, color: "#fff", letterSpacing: "-.03em", marginTop: 14, lineHeight: 1 }}>{value}</div>
      <span style={{ display: "block", fontSize: 12, color: subColor || "rgba(207,207,207,.5)", marginTop: 12 }}>{sub}</span>
    </div>
  );
  const ibox = (accent, svg) => <span style={{ width: 30, height: 30, borderRadius: 9, background: `${accent}1a`, border: `1px solid ${accent}3d`, display: "flex", alignItems: "center", justifyContent: "center", color: accent, flex: "none" }}>{svg}</span>;
  const toggle = (on, setOn) => (
    <span onClick={() => setOn((v) => !v)} style={{ width: 40, height: 23, borderRadius: 200, position: "relative", cursor: "pointer", background: on ? "rgba(174,203,224,.9)" : "#26262a", border: `1px solid ${on ? "transparent" : "#303034"}`, boxShadow: on ? "0 0 12px rgba(174,203,224,.4)" : "none", flex: "none" }}>
      <span style={{ position: "absolute", top: 2.5, [on ? "right" : "left"]: 2.5, width: 18, height: 18, borderRadius: "50%", background: on ? "#06121c" : "#6a6a70" }} />
    </span>
  );

  // ---- dados do gráfico conforme o filtro selecionado ----
  const parseBRL = (s) => Number(String(s).replace(/[^\d,]/g, "").replace(",", "."));
  const fmtBRL2 = (v) => "R$ " + v.toLocaleString("pt-BR", { minimumFractionDigits: 2, maximumFractionDigits: 2 });
  const fmtK = (v) => { if (!v) return "0"; const k = v / 1000; return (k >= 10 ? Math.round(k).toString() : k.toFixed(1).replace(/\.0$/, "")).replace(".", ",") + "k"; };
  const totalCusto = ROI_AGENTS.reduce((s, a) => s + parseBRL(a.custo), 0);
  const cd = (() => {
    let proj, orc, color;
    if (chartFilter === "Toda a operação") { proj = totalCusto; orc = 12000; color = "#72b2e6"; }
    else { const a = ROI_AGENTS.find((x) => x.name === chartFilter) || ROI_AGENTS[0]; proj = parseBRL(a.custo); orc = parseBRL(a.orc); color = a.color; }
    const gasto = proj * 0.6, saldo = orc - proj;
    const axisMax = orc / 0.857; // mantém o teto sempre em ~86% da altura
    const yMap = (v) => 250 - Math.max(0, Math.min(1.04, v / axisMax)) * 230;
    const xDay = (d) => 44 + ((d - 1) / 29) * 620;
    const solid = [1, 3, 5, 7, 9, 11, 13, 15, 17, 18].map((d) => `${xDay(d).toFixed(0)},${yMap(gasto * Math.pow((d - 1) / 17, 1.15)).toFixed(1)}`);
    const dash = [18, 21, 24, 27, 30].map((d) => `${xDay(d).toFixed(0)},${yMap(gasto + (proj - gasto) * ((d - 18) / 12)).toFixed(1)}`);
    return { color, gasto, proj, orc, saldo, axisMax,
      solidStr: solid.join(" "), areaStr: `${solid.join(" ")} 407,250 44,250`, dashStr: dash.join(" "),
      hojeY: yMap(gasto), endY: yMap(proj), pctOrc: orc ? Math.round((proj / orc) * 100) : 0 };
  })();

  return (
    <div className="nn-scroll" style={{ position: "absolute", inset: 0, overflowY: "auto", overflowX: "hidden", background: "radial-gradient(ellipse 900px 520px at 30% -8%, rgba(58,143,220,.08), transparent 70%), #000" }}>
      <GridFx2 dark={dark} />
      <div style={{ position: "relative", maxWidth: 1560, margin: "0 auto", padding: "42px 56px 80px" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 22 }}>
          <div style={{ position: "relative", width: 72, height: 72, flex: "none", borderRadius: "50%", background: "radial-gradient(circle at 50% 38%, #122319, #080d0a)", border: "1px solid rgba(95,208,166,.3)", display: "flex", alignItems: "center", justifyContent: "center", boxShadow: "0 0 0 6px rgba(95,208,166,.04), 0 0 60px rgba(95,208,166,.26)" }}>
            <span style={{ position: "absolute", inset: -1, borderRadius: "50%", border: "1px solid rgba(95,208,166,.2)", animation: "nnBreathe 3.4s ease-in-out infinite" }} />
            <svg width="30" height="30" viewBox="0 0 24 24" fill="none" stroke="#7fe0bc" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round"><path d="M3 17l5-5 4 3 6-7" /><path d="M16 8h5v5" /></svg>
          </div>
          <div>
            <h2 style={{ margin: 0, fontSize: 38, fontWeight: 700, letterSpacing: "-.03em", color: "#fff", lineHeight: 1 }}>ROI &amp; Custo</h2>
            <p style={{ margin: "11px 0 0", fontSize: 15, lineHeight: 1.45, color: "rgba(207,207,207,.62)", maxWidth: 880 }}>O business case da camada agêntica: valor gerado (tempo economizado) versus o custo de modelos e infraestrutura.</p>
          </div>
        </div>

        <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 20, marginTop: 34 }}>
          {kpi(true, "rgba(95,208,166,.5)", ibox("#7fe0bc", <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round" strokeLinejoin="round"><path d="M3 17l6-6 4 3 7-8" /><path d="M17 6h4v4" /></svg>), "ECONOMIA / MÊS", "R$ 72.873,90", "a R$ 90/h de analista")}
          {kpi(false, "rgba(224,122,130,.4)", ibox("#f09aa1", <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M12 3v18M16.5 7.5C16 5.7 14.2 4.8 12 4.8 9.4 4.8 7.5 6 7.5 8.1c0 4.6 9 2.8 9 7.5 0 2.1-1.9 3.6-4.5 3.6-2.4 0-4.2-1-4.7-3" /></svg>), "CUSTO / MÊS", "R$ 8.132,00", "API + infraestrutura")}
          {kpi(false, "rgba(174,203,224,.45)", ibox("#aecbe0", <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M12 13a7 7 0 0 1 7-7M5 13a7 7 0 0 1 2-4.9" /><circle cx="12" cy="13" r="1.6" fill="currentColor" /><path d="M12 13l4-4" /><path d="M5 18h14" /></svg>), "ROI", "9.0×", "retorno sobre o custo")}
          {kpi(false, "rgba(174,203,224,.45)", ibox("#aecbe0", <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round"><circle cx="8" cy="8" r="3" /><path d="M2 20c0-3.3 2.7-5.5 6-5.5s6 2.2 6 5.5" /><circle cx="17" cy="9" r="2.4" /><path d="M15 20c0-2.6 1.5-4.5 4-4.5" /></svg>), "EQUIVALENTE", "5.1 FTE", "187 h/sem economizadas")}
        </div>

        <div style={{ display: "flex", alignItems: "center", gap: 13, marginTop: 18, padding: "16px 22px", borderRadius: 14, background: "linear-gradient(90deg,rgba(95,208,166,.1),rgba(95,208,166,.03))", border: "1px solid rgba(95,208,166,.24)" }}>
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#7fe0bc" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" style={{ flex: "none" }}><path d="M12 3l1.8 5.2L19 10l-5.2 1.8L12 17l-1.8-5.2L5 10l5.2-1.8L12 3Z" /></svg>
          <p style={{ margin: 0, fontSize: 14, color: "rgba(207,224,214,.8)" }}><span style={{ color: "#9fecca", fontWeight: 700 }}>Valor líquido de R$ 64.741,90/mês.</span> Cada R$ 1 investido na camada agêntica devolve aproximadamente R$ 8.96 em horas de equipe.</p>
        </div>

        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginTop: 40 }}>
          <h3 style={{ margin: 0, fontSize: 20, fontWeight: 700, color: "#fff", letterSpacing: "-.01em" }}>Custo previsto vs. orçamento</h3>
          <span style={{ fontSize: 12.5, letterSpacing: ".04em", color: "rgba(207,207,207,.42)" }}>Ciclo Junho · 2026 · dia 18/30</span>
        </div>

        <div style={{ display: "grid", gridTemplateColumns: "1.62fr 1fr", gap: 20, marginTop: 18, alignItems: "start" }}>
          {/* CHART CARD */}
          <div style={{ borderRadius: 20, background: "linear-gradient(180deg,#121315,#0d0f11)", border: "1px solid #202024", padding: "22px 24px", boxShadow: "0 16px 36px rgba(0,0,0,.4)" }}>
            <div style={{ display: "flex", flexWrap: "wrap", gap: 9 }}>
              {ROI_CHIPS.map(([label, dot]) => {
                const on = label === chartFilter;
                return <span key={label} className="nn-chip" onClick={() => setChartFilter(label)} style={{ display: "inline-flex", alignItems: "center", gap: 8, height: 32, padding: "0 14px", borderRadius: 200, fontSize: 12.5, fontWeight: 600, color: on ? "#e8eff6" : "rgba(226,225,223,.8)", background: on ? "rgba(174,203,224,.12)" : "rgba(255,255,255,.02)", border: `1px solid ${on ? "rgba(174,203,224,.26)" : "#26262a"}` }}><span style={{ width: 7, height: 7, borderRadius: "50%", flex: "none", background: dot }} />{label}</span>;
              })}
            </div>
            <svg viewBox="0 0 700 285" width="100%" style={{ display: "block", marginTop: 22, overflow: "visible" }}>
              <defs>
                <linearGradient id="roiArea" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stopColor="#72b2e6" stopOpacity=".32" /><stop offset="1" stopColor="#72b2e6" stopOpacity="0" /></linearGradient>
                <linearGradient id="roiFlow" x1="0" y1="0" x2="1" y2="0"><stop offset="0" stopColor="#cfe8ff" stopOpacity="0" /><stop offset="0.5" stopColor="#cfe8ff" /><stop offset="1" stopColor="#cfe8ff" stopOpacity="0" /></linearGradient>
                <filter id="roiGlow" x="-20%" y="-60%" width="140%" height="220%"><feGaussianBlur stdDeviation="3.4" result="b" /><feMerge><feMergeNode in="b" /><feMergeNode in="SourceGraphic" /></feMerge></filter>
              </defs>
              <g stroke="#1c1d20" strokeWidth="1"><line x1="44" y1="20" x2="664" y2="20" /><line x1="44" y1="86" x2="664" y2="86" /><line x1="44" y1="137" x2="664" y2="137" /><line x1="44" y1="194" x2="664" y2="194" /><line x1="44" y1="250" x2="664" y2="250" /></g>
              <g fill="rgba(207,207,207,.4)" fontSize="10.5" fontFamily="Manrope, 'Helvetica Neue', Arial, sans-serif" textAnchor="end">{[[24, 1], [90, .714], [141, .493], [198, .243], [254, 0]].map(([yy, f]) => <text key={yy} x="36" y={yy}>{fmtK(f * cd.axisMax)}</text>)}</g>
              <g fill="rgba(207,207,207,.4)" fontSize="10.5" fontFamily="Manrope, 'Helvetica Neue', Arial, sans-serif" textAnchor="middle"><text x="44" y="268">1</text><text x="151" y="268">6</text><text x="279" y="268">12</text><text x="407" y="268">18</text><text x="536" y="268">24</text><text x="664" y="268">30</text></g>
              <line x1="44" y1="53" x2="664" y2="53" stroke="#e07a82" strokeWidth="1.4" strokeDasharray="6 5" opacity=".8" />
              <rect x="566" y="44" width="98" height="18" rx="5" fill="#1c1417" stroke="rgba(224,122,130,.55)" />
              <text x="615" y="56.5" fill="#f3aab0" fontSize="10" fontFamily="Manrope, 'Helvetica Neue', Arial, sans-serif" fontWeight="700" textAnchor="middle">{`TETO ${fmtBRL2(cd.orc)}`}</text>
              <line x1="44" y1="73" x2="580" y2="73" stroke="#e3b25b" strokeWidth="1.3" strokeDasharray="4 5" opacity=".7" />
              <line x1="407" y1="20" x2="407" y2="250" stroke="rgba(174,203,224,.35)" strokeWidth="1.2" strokeDasharray="3 4" />
              <text x="407" y="14" fill="rgba(207,207,207,.55)" fontSize="10" fontFamily="Manrope, 'Helvetica Neue', Arial, sans-serif" fontWeight="700" letterSpacing="1" textAnchor="middle">HOJE</text>
              <polygon points={cd.areaStr} fill={cd.color} fillOpacity="0.16" className="nn-area-in" />
              <polyline points={cd.solidStr} pathLength="760" fill="none" stroke={cd.color} strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round" filter="url(#roiGlow)" className="nn-draw-line" />
              <polyline points={cd.solidStr} fill="none" stroke="url(#roiFlow)" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round" strokeDasharray="22 218" className="nn-pulse-line" />
              <polyline points={cd.dashStr} fill="none" stroke={cd.color} strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" opacity=".85" className="nn-draw-proj" />
              <circle cx="407" cy={cd.hojeY} r="5" fill="#0d0f11" stroke={cd.color} strokeWidth="2.4" />
              <circle cx="407" cy={cd.hojeY} r="2" fill={cd.color} className="nn-node-spark" />
              <circle cx="664" cy={cd.endY} r="9" fill="none" stroke={cd.color} strokeOpacity=".5" className="nn-node-pulse" />
              <circle cx="664" cy={cd.endY} r="5" fill={cd.color} stroke="#0d0f11" strokeWidth="2" className="nn-node-core" />
            </svg>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 12, marginTop: 18, paddingTop: 18, borderTop: "1px solid #1c1c1f" }}>
              <div><div style={{ fontSize: 9.5, letterSpacing: ".13em", color: "rgba(207,207,207,.42)" }}>GASTO ATÉ HOJE</div><div style={{ fontSize: 21, fontWeight: 700, color: "#fff", marginTop: 6 }}>{fmtBRL2(cd.gasto)}</div><div style={{ fontSize: 11.5, color: "rgba(207,207,207,.45)", marginTop: 3 }}>dia 18 de 30</div></div>
              <div><div style={{ fontSize: 9.5, letterSpacing: ".13em", color: "rgba(207,207,207,.42)" }}>PROJEÇÃO FIM DO CICLO</div><div style={{ fontSize: 21, fontWeight: 700, color: cd.color, marginTop: 6 }}>{fmtBRL2(cd.proj)}</div><div style={{ fontSize: 11.5, color: "rgba(207,207,207,.45)", marginTop: 3 }}>{cd.pctOrc}% do orçamento</div></div>
              <div><div style={{ fontSize: 9.5, letterSpacing: ".13em", color: "rgba(207,207,207,.42)" }}>SALDO DO ORÇAMENTO</div><div style={{ fontSize: 21, fontWeight: 700, color: cd.saldo >= 0 ? "#7fe0bc" : "#f09aa1", marginTop: 6 }}>{fmtBRL2(cd.saldo)}</div><div style={{ fontSize: 11.5, color: "rgba(207,207,207,.45)", marginTop: 3 }}>{cd.saldo >= 0 ? "folga prevista" : "acima do orçamento"}</div></div>
            </div>
          </div>

          {/* ALERTS CARD */}
          <div style={{ borderRadius: 20, background: "linear-gradient(180deg,#121315,#0d0f11)", border: "1px solid #202024", padding: "22px 24px", boxShadow: "0 16px 36px rgba(0,0,0,.4)" }}>
            <div style={{ display: "flex", alignItems: "center", gap: 13 }}>
              <span style={{ width: 40, height: 40, flex: "none", borderRadius: 11, background: "rgba(227,178,91,.1)", border: "1px solid rgba(227,178,91,.26)", display: "flex", alignItems: "center", justifyContent: "center", color: "#e3b25b" }}><svg width="19" height="19" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round"><path d="M6 9a6 6 0 0 1 12 0c0 5 2 6 2 6H4s2-1 2-6Z" /><path d="M10 19a2 2 0 0 0 4 0" /></svg></span>
              <div><h4 style={{ margin: 0, fontSize: 16, fontWeight: 700, color: "#fff" }}>Alertas de orçamento</h4><p style={{ margin: "3px 0 0", fontSize: 12, color: "rgba(207,207,207,.5)", lineHeight: 1.4 }}>Aviso automático quando a projeção atinge o limite.</p></div>
            </div>
            <div style={{ fontSize: 10, letterSpacing: ".15em", color: "rgba(207,207,207,.42)", marginTop: 22 }}>DISPARAR EM</div>
            <div style={{ display: "flex", padding: 4, gap: 3, borderRadius: 11, background: "#0c0c0e", border: "1px solid #1f1f22", marginTop: 9 }}>
              {["75%", "90%", "100%"].map((th) => { const on = th === threshold; return <span key={th} onClick={() => setThreshold(th)} style={{ flex: 1, display: "flex", alignItems: "center", justifyContent: "center", height: 34, borderRadius: 8, fontSize: 12.5, fontWeight: on ? 700 : 600, color: on ? "#e8eff6" : "#76767c", background: on ? "rgba(174,203,224,.12)" : "transparent", border: `1px solid ${on ? "rgba(174,203,224,.24)" : "transparent"}`, cursor: "pointer" }}>{th}</span>; })}
            </div>
            <div style={{ fontSize: 10, letterSpacing: ".15em", color: "rgba(207,207,207,.42)", marginTop: 22 }}>NOTIFICAR POR</div>
            <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginTop: 13 }}>
              <span style={{ display: "inline-flex", alignItems: "center", gap: 10, fontSize: 13.5, color: "#dcdcda" }}><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="rgba(207,207,207,.6)" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="5" width="18" height="14" rx="2" /><path d="M3 7l9 6 9-6" /></svg>E-mail do responsável</span>
              {toggle(emailOn, setEmailOn)}
            </div>
            <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginTop: 15 }}>
              <span style={{ display: "inline-flex", alignItems: "center", gap: 10, fontSize: 13.5, color: "#dcdcda" }}><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="rgba(207,207,207,.6)" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round"><path d="M5 5h11a3 3 0 0 1 3 3v5a3 3 0 0 1-3 3H9l-4 3v-3a3 3 0 0 1-3-3V8a3 3 0 0 1 3-3Z" /></svg>WhatsApp · gestor</span>
              {toggle(whatsOn, setWhatsOn)}
            </div>
            <div style={{ height: 1, background: "#1c1c1f", margin: "22px 0 0" }} />
            <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginTop: 16 }}>
              <span style={{ fontSize: 10, letterSpacing: ".15em", color: "rgba(207,207,207,.42)" }}>NO LIMITE (90%)</span>
              <span style={{ fontSize: 12.5, fontWeight: 700, color: "#7fe0bc" }}>0 agentes</span>
            </div>
            <div style={{ display: "flex", alignItems: "center", gap: 10, marginTop: 12, padding: "13px 15px", borderRadius: 12, background: "rgba(95,208,166,.07)", border: "1px solid rgba(95,208,166,.22)" }}>
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#7fe0bc" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" style={{ flex: "none" }}><path d="M12 3l8 3v5c0 5-3.5 8.5-8 10-4.5-1.5-8-5-8-10V6z" /><path d="M9 12l2 2 4-4" /></svg>
              <span style={{ fontSize: 13, color: "#9fecca" }}>Nenhum agente acima de 90% do orçamento.</span>
            </div>
          </div>
        </div>

        <h3 style={{ margin: "44px 0 0", fontSize: 20, fontWeight: 700, color: "#fff", letterSpacing: "-.01em" }}>Orçamento por agente</h3>
        <div className="nn-roitable nn-noscroll" style={{ marginTop: 18, borderRadius: 20, background: "linear-gradient(180deg,#121315,#0d0f11)", border: "1px solid #202024", overflow: "hidden", boxShadow: "0 16px 36px rgba(0,0,0,.4)" }}>
          <div style={{ display: "grid", gridTemplateColumns: "2fr 1.1fr 1.1fr 1.8fr 1.3fr", gap: 16, padding: "16px 26px", borderBottom: "1px solid #1c1c1f", fontSize: 10, letterSpacing: ".14em", color: "rgba(207,207,207,.42)" }}>
            <span>AGENTE</span><span>CUSTO / MÊS</span><span>ORÇAMENTO</span><span>CONSUMO</span><span style={{ textAlign: "right" }}>ECONOMIA</span>
          </div>
          {ROI_AGENTS.map((a) => (
            <div key={a.name} className="nn-trow" style={{ display: "grid", gridTemplateColumns: "2fr 1.1fr 1.1fr 1.8fr 1.3fr", gap: 16, alignItems: "center", padding: "18px 26px", borderBottom: "1px solid #161618" }}>
              <span style={{ display: "inline-flex", alignItems: "center", gap: 11, fontSize: 14.5, fontWeight: 700, color: "#f1f1ef" }}><span style={{ width: 9, height: 9, borderRadius: "50%", flex: "none", background: a.color, boxShadow: `0 0 8px ${a.glow}` }} />{a.name}</span>
              <span style={{ fontSize: 14, color: "#dcdcda", fontFeatureSettings: "'tnum'" }}>{a.custo}</span>
              <span style={{ fontSize: 14, color: "rgba(207,207,207,.55)", fontFeatureSettings: "'tnum'" }}>{a.orc}</span>
              <span style={{ display: "flex", alignItems: "center", gap: 12 }}>
                <span style={{ flex: 1, height: 7, borderRadius: 200, background: "#1d1d20", overflow: "hidden" }}><span style={{ display: "block", height: "100%", width: a.pct, borderRadius: 200, background: `linear-gradient(90deg,${a.barFrom},${a.bar})` }} /></span>
                <span style={{ fontSize: 13, fontWeight: 700, color: a.bar, width: 34, fontFeatureSettings: "'tnum'" }}>{a.pct}</span>
              </span>
              <span style={{ fontSize: 14, fontWeight: 700, color: "#7fe0bc", textAlign: "right", fontFeatureSettings: "'tnum'" }}>{a.economia}</span>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

// =================== NOVO AGENTE (modal) — design NN.ai ===================
const NA_TEMPLATES = [
  { name: "Classificação de Documentos", desc: "OCR + extração e categorização de qualquer documento recebido.", d: "M4 8V6a2 2 0 0 1 2-2h2M16 4h2a2 2 0 0 1 2 2v2M20 16v2a2 2 0 0 1-2 2h-2M8 20H6a2 2 0 0 1-2-2v-2M7 12h10" },
  { name: "Cobrança & Inadimplência", desc: "Detecta atrasos, gera régua de cobrança e dispara lembretes.", d: "M12 2v20M16.5 6.5A4 4 0 0 0 12 4.5h-.8a3.2 3.2 0 0 0 0 6.4h1.6a3.2 3.2 0 0 1 0 6.4H11A4 4 0 0 1 7 16" },
  { name: "Onboarding de Clientes", desc: "Coleta documentos, valida cadastro e abre a conta do cliente.", d: "M9 8a3 3 0 1 0 0-.01M3 20c0-3.3 2.7-5.5 6-5.5s6 2.2 6 5.5M16 4.5a3 3 0 0 1 0 5.8M21 20c0-2.4-1.4-4.2-3.5-5" },
  { name: "Análise de Contratos", desc: "Lê contratos, extrai cláusulas de risco e resume obrigações.", d: "M7 3h7l4 4v14H7zM13 3v5h5M10 13h5M10 16.5h5" },
  { name: "Relatórios Gerenciais", desc: "Consolida dados e gera relatórios executivos sob demanda.", d: "M3 13h3l2.5 6 4-15 2.5 9H21" },
  { name: "Agente em branco", desc: "Comece do zero e componha as tools manualmente.", d: "M12 5v14M5 12h14", dashed: true },
];
function NewAgentModal({ t, dark, onClose, onCreate }) {
  const [tpl, setTpl] = useS2(null);
  const hasPick = tpl !== null;
  return (
    <div onClick={onClose} style={{ position: "fixed", inset: 0, zIndex: 80, display: "flex", alignItems: "center", justifyContent: "center", padding: 32, background: "rgba(0,0,0,.62)", backdropFilter: "blur(5px)" }}>
      <div onClick={(e) => e.stopPropagation()} style={{ width: "100%", maxWidth: 920, maxHeight: "88vh", display: "flex", flexDirection: "column", borderRadius: 22, background: "linear-gradient(180deg,#111113,#0a0a0c)", border: "1px solid #232327", boxShadow: "0 40px 100px rgba(0,0,0,.66), inset 0 1px 0 rgba(255,255,255,.04)", overflow: "hidden" }}>
        <div style={{ flex: "none", display: "flex", alignItems: "flex-start", justifyContent: "space-between", gap: 16, padding: "26px 28px 22px", borderBottom: "1px solid #19191c" }}>
          <div style={{ display: "flex", alignItems: "center", gap: 15 }}>
            <span style={{ width: 50, height: 50, flex: "none", borderRadius: 15, display: "flex", alignItems: "center", justifyContent: "center", background: "linear-gradient(150deg,#1d2b36,#0c1318)", border: "1px solid rgba(174,203,224,.28)", boxShadow: "0 0 26px rgba(58,143,220,.26)" }}>
              <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#cfe0ec" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d="M12 3l1.8 5.2L19 10l-5.2 1.8L12 17l-1.8-5.2L7 10l5.2-1.8L12 3Z" /><path d="M19 15l.7 2 2 .7-2 .7-.7 2-.7-2-2-.7 2-.7.7-2Z" /></svg>
            </span>
            <div><h2 style={{ margin: 0, fontSize: 24, fontWeight: 700, letterSpacing: "-.02em", color: "#fff" }}>Novo agente</h2><p style={{ margin: "5px 0 0", fontSize: 13.5, color: "rgba(207,207,207,.55)" }}>Comece a partir de um template ou do zero.</p></div>
          </div>
          <button onClick={onClose} style={{ flex: "none", width: 36, height: 36, borderRadius: 11, display: "flex", alignItems: "center", justifyContent: "center", background: "rgba(255,255,255,.03)", border: "1px solid #242427", color: "#9a9a9f", cursor: "pointer" }}><svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M6 6l12 12M18 6L6 18" /></svg></button>
        </div>
        <div className="nn-scroll" style={{ flex: 1, overflowY: "auto", padding: "22px 28px" }}>
          <div style={{ fontSize: 10, letterSpacing: ".18em", textTransform: "uppercase", color: "rgba(207,207,207,.45)", marginBottom: 15 }}>Escolha um ponto de partida</div>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 14 }}>
            {NA_TEMPLATES.map((x, i) => {
              const on = tpl === i;
              return (
                <div key={i} onClick={() => setTpl(i)} className="nn-tpl" style={{ position: "relative", padding: 20, borderRadius: 16, background: "rgba(255,255,255,.018)", border: `1px solid ${on ? "rgba(174,203,224,.55)" : "#1f1f22"}`, boxShadow: on ? "0 0 0 1px rgba(174,203,224,.35), 0 18px 44px rgba(0,0,0,.5), 0 0 34px rgba(58,143,220,.14)" : "none", cursor: "pointer" }}>
                  {on && <span style={{ position: "absolute", top: 14, right: 14, width: 22, height: 22, borderRadius: "50%", background: "#aecbe0", display: "flex", alignItems: "center", justifyContent: "center", boxShadow: "0 0 12px rgba(174,203,224,.5)" }}><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="#06121c" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12.5l4.5 4.5L19 7.5" /></svg></span>}
                  <span style={{ width: 44, height: 44, borderRadius: 12, display: "flex", alignItems: "center", justifyContent: "center", background: "rgba(174,203,224,.07)", border: `1px ${x.dashed ? "dashed #34343a" : "solid #232327"}`, color: "#aecbe0" }}><svg width="21" height="21" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round"><path d={x.d} /></svg></span>
                  <h3 style={{ margin: "15px 0 0", fontSize: 16, fontWeight: 700, color: "#fff", letterSpacing: "-.01em" }}>{x.name}</h3>
                  <p style={{ margin: "7px 0 0", fontSize: 12.5, lineHeight: 1.5, color: "rgba(207,207,207,.55)" }}>{x.desc}</p>
                </div>
              );
            })}
          </div>
        </div>
        <div style={{ flex: "none", display: "flex", alignItems: "center", justifyContent: "space-between", gap: 16, padding: "18px 28px", borderTop: "1px solid #19191c", background: "#0a0a0c" }}>
          <span style={{ fontSize: 12.5, color: "rgba(207,207,207,.45)" }}>{hasPick ? `Template selecionado · ${NA_TEMPLATES[tpl].name}` : "Selecione um ponto de partida"}</span>
          <div style={{ display: "flex", alignItems: "center", gap: 11 }}>
            <button onClick={onClose} style={{ height: 44, padding: "0 20px", borderRadius: 12, background: "transparent", border: "1px solid #2a2a2e", color: "#d8d8d8", fontSize: 13.5, fontWeight: 600, cursor: "pointer", fontFamily: "inherit" }}>Cancelar</button>
            <button onClick={() => hasPick && (onCreate ? onCreate(NA_TEMPLATES[tpl]) : onClose())} disabled={!hasPick} style={{ display: "flex", alignItems: "center", gap: 9, height: 44, padding: "0 22px", borderRadius: 12, background: hasPick ? "#aecbe0" : "rgba(174,203,224,.22)", border: "none", color: hasPick ? "#06121c" : "rgba(6,18,28,.5)", fontSize: 13.5, fontWeight: 700, cursor: hasPick ? "pointer" : "default", boxShadow: hasPick ? "0 0 22px rgba(174,203,224,.32)" : "none", fontFamily: "inherit" }}><svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round"><path d="M12 5v14M5 12h14" /></svg>Criar agente</button>
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { ModelsModule, McpsModule, RoiModule, NewAgentModal, McpCatalogIcon: McpIco });
