/* global React */
/* ============================================================
   Credentials.jsx — drawer de credenciais do MCP (design NN.ai)
   ============================================================ */
const { useState: useSC, useEffect: useEC, useRef: useRC } = React;

const CRED_ST = {
  ok:   { label: "Operacional", color: "#5fd0a6", bg: "rgba(95,208,166,.08)", bd: "rgba(95,208,166,.26)" },
  warn: { label: "Atenção", color: "#e3b25b", bg: "rgba(227,178,91,.08)", bd: "rgba(227,178,91,.28)" },
  fail: { label: "Falha", color: "#e07a82", bg: "rgba(224,122,130,.1)", bd: "rgba(224,122,130,.32)" },
};

function slugCred(name) {
  return String(name || "mcp")
    .toLowerCase()
    .normalize("NFD")
    .replace(/[\u0300-\u036f]/g, "")
    .replace(/[^a-z0-9]+/g, "-")
    .replace(/^-|-$/g, "");
}

function hashCred(name) {
  let h = 0;
  const s = String(name || "mcp");
  for (let i = 0; i < s.length; i++) h = (h * 31 + s.charCodeAt(i)) >>> 0;
  return h.toString(16).padStart(8, "0").slice(0, 4);
}

function scopesForCred(name, meta) {
  const cat = String(meta || "").split("·")[0].trim();
  const map = {
    "Documentos": ["documents.read", "documents.write", "ocr.run"],
    "Fiscal": ["nfe.read", "nfe.issue", "sefaz.query"],
    "ERP": ["erp.read", "erp.write", "inventory.sync"],
    "Contábil": ["ledger.read", "ledger.post", "accounts.map"],
    "Bancário": ["accounts.read", "transactions.read", "reconcile.run"],
    "RH": ["candidates.read", "candidates.write", "jobs.read"],
    "Jurídico": ["contracts.read", "contracts.generate", "sign.request"],
    "Comunicação": ["messages.send", "templates.read", "contacts.read"],
    "Conhecimento": ["kb.read", "kb.search"],
    "CRM": ["contacts.read", "contacts.write", "deals.read"],
  };
  return map[cat] || ["read", "write"];
}

function authForCred(name, cfg) {
  const cert = ["SEFAZ · NF-e"];
  const oauth = ["WhatsApp API", "Open Finance", "CRM", "ATS · LinkedIn", "E-mail"];
  if (cert.includes(name)) return "Certificado A1";
  if (oauth.includes(name)) return "OAuth 2.0";
  return cfg?.type || "API Key";
}

function McpCredentialsModal({ mcp, onClose }) {
  const cfg = window.AgentData.credsFor(mcp);
  const [env, setEnv] = useSC("prod");
  const [reveal, setReveal] = useSC(false);
  const [copiedKey, setCopiedKey] = useSC(false);
  const [copiedEp, setCopiedEp] = useSC(false);
  const [rotated, setRotated] = useSC(false);
  const timers = useRC({});

  useEC(() => () => Object.values(timers.current).forEach(clearTimeout), []);

  const sev = mcp.status === "error" ? "fail" : (mcp.status || (mcp.name === "WhatsApp API" ? "fail" : "ok"));
  const S = CRED_ST[sev] || CRED_ST.ok;
  const IconComp = window.McpCatalogIcon;
  const iconKey = mcp.catalogIcon || mcp.iconKey || mcp.icon || "doc";
  const tools = mcp.tools || cfg.fields.length;
  const auth = authForCred(mcp.name, cfg);
  const h = hashCred(mcp.name);
  const envKey = env === "prod" ? "live" : "test";
  const fullKey = `nn_${envKey}_sk_${h}9c4e2a17b0d6f3${h}`;
  const maskKey = `nn_${envKey}_sk_${h}....................`;
  const endpoint = `https://mcp.nn.ai/v1/${slugCred(mcp.name)}`;
  const scopes = scopesForCred(mcp.name, mcp.meta);

  const copy = (kind, value) => {
    try { navigator.clipboard && navigator.clipboard.writeText(value); } catch (e) {}
    if (kind === "key") {
      setCopiedKey(true);
      clearTimeout(timers.current.key);
      timers.current.key = setTimeout(() => setCopiedKey(false), 1600);
    } else {
      setCopiedEp(true);
      clearTimeout(timers.current.ep);
      timers.current.ep = setTimeout(() => setCopiedEp(false), 1600);
    }
  };

  const icon = (d, attrs = {}) => <svg width={attrs.width || 15} height={attrs.height || 15} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={attrs.strokeWidth || 1.9} strokeLinecap="round" strokeLinejoin="round" style={attrs.style}><path d={d} /></svg>;

  return (
    <>
      <div onClick={onClose} style={{ position: "fixed", inset: 0, zIndex: 40, background: "rgba(0,0,0,.55)", backdropFilter: "blur(3px)", WebkitBackdropFilter: "blur(3px)", animation: "nnScrimIn .25s ease" }} />
      <aside style={{ position: "fixed", top: 0, right: 0, bottom: 0, zIndex: 41, width: 480, maxWidth: "92vw", display: "flex", flexDirection: "column", background: "linear-gradient(180deg,#0d0d0f,#070708)", borderLeft: "1px solid #1f1f22", boxShadow: "-40px 0 90px rgba(0,0,0,.6), inset 1px 0 0 rgba(174,203,224,.06)", animation: "nnDrawerIn .42s cubic-bezier(.22,1,.36,1)" }}>
        <span style={{ position: "absolute", left: 0, top: 0, bottom: 0, width: 2, background: `linear-gradient(180deg,${S.color},transparent 60%)`, opacity: .7 }} />

        <header style={{ flex: "none", padding: "24px 26px 20px", borderBottom: "1px solid #161619" }}>
          <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between", gap: 14 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 13, minWidth: 0 }}>
              <span style={{ position: "relative", width: 44, height: 44, 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={iconKey} /> : icon("M9 2v6M15 2v6M7 8h10v3a5 5 0 0 1-10 0V8ZM12 16v6")}
              </span>
              <div style={{ minWidth: 0 }}>
                <div style={{ fontSize: 10, letterSpacing: ".2em", textTransform: "uppercase", color: "rgba(207,207,207,.5)" }}>Credenciais do MCP</div>
                <h2 style={{ margin: "4px 0 0", fontSize: 21, fontWeight: 700, letterSpacing: "-.02em", color: "#fff", lineHeight: 1.1, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{mcp.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 #242427", color: "#9a9a9f", cursor: "pointer" }}>
              {icon("M6 6l12 12M18 6L6 18", { width: 16, height: 16, strokeWidth: 2 })}
            </button>
          </div>
          <div style={{ display: "flex", flexWrap: "wrap", gap: 8, marginTop: 16 }}>
            <span style={{ display: "flex", alignItems: "center", gap: 7, height: 30, padding: "0 12px", borderRadius: 200, whiteSpace: "nowrap", background: S.bg, border: `1px solid ${S.bd}`, fontSize: 12, fontWeight: 600, color: S.color }}><span style={{ width: 7, height: 7, borderRadius: "50%", background: S.color, boxShadow: `0 0 7px ${S.color}` }} />{S.label}</span>
            <span style={{ display: "flex", alignItems: "center", gap: 7, height: 30, padding: "0 12px", borderRadius: 200, whiteSpace: "nowrap", background: "rgba(174,203,224,.07)", border: "1px solid rgba(174,203,224,.2)", fontSize: 12, fontWeight: 600, color: "#aecbe0" }}>{icon("M8 10V7a4 4 0 0 1 8 0v3", { width: 13, height: 13 })}<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" style={{ marginLeft: -20 }}><rect x="4" y="10" width="16" height="11" rx="2" /></svg>{auth}</span>
            <span style={{ display: "flex", alignItems: "center", gap: 7, height: 30, padding: "0 12px", borderRadius: 200, whiteSpace: "nowrap", background: "rgba(255,255,255,.04)", border: "1px solid #2a2a2e", fontSize: 12, fontWeight: 600, color: "#e2e1df" }}>{icon("M10.8 12.2 19 4M16 7l2 2M14 9l2 2", { width: 13, height: 13 })}{tools} tools</span>
          </div>
        </header>

        <div className="nn-scroll" style={{ flex: 1, overflowY: "auto", padding: "22px 26px 28px" }}>
          <div style={{ fontSize: 10, letterSpacing: ".18em", textTransform: "uppercase", color: "rgba(207,207,207,.45)", marginBottom: 13 }}>Conexão</div>
          <label style={{ display: "block", fontSize: 11, color: "rgba(207,207,207,.5)", marginBottom: 8 }}>Endpoint base</label>
          <div className="nn-crow" style={{ display: "flex", alignItems: "center", gap: 10, height: 46, padding: "0 8px 0 14px", borderRadius: 11, background: "#0e0e10", border: "1px solid #242427", transition: "border-color .2s", marginBottom: 16 }}>
            <span style={{ flex: 1, minWidth: 0, fontSize: 13, color: "#e2e1df", fontFamily: "var(--font-mono)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{endpoint}</span>
            <button onClick={() => copy("ep", endpoint)} style={{ flex: "none", display: "flex", alignItems: "center", gap: 6, height: 32, padding: "0 11px", borderRadius: 8, background: "rgba(255,255,255,.03)", border: "1px solid #2a2a2e", color: "#cfcfcf", fontSize: 11.5, fontWeight: 600, cursor: "pointer", fontFamily: "inherit" }}>{icon("M5 15V5a2 2 0 0 1 2-2h8", { width: 13, height: 13 })}<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" style={{ marginLeft: -19 }}><rect x="9" y="9" width="11" height="11" rx="2" /></svg>{copiedEp ? "Copiado" : "Copiar"}</button>
          </div>

          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 16, marginBottom: 22 }}>
            <div><div style={{ fontSize: 13.5, fontWeight: 600, color: "#fff" }}>Ambiente</div><div style={{ fontSize: 11.5, color: "rgba(207,207,207,.45)", marginTop: 2 }}>Define qual base de credenciais usar.</div></div>
            <div style={{ display: "flex", padding: 4, gap: 3, borderRadius: 11, background: "#0c0c0e", border: "1px solid #1f1f22" }}>
              {[["prod", "Produção"], ["sandbox", "Sandbox"]].map(([v, label]) => {
                const on = env === v;
                return <span key={v} onClick={() => { setEnv(v); setReveal(false); }} style={{ display: "flex", alignItems: "center", justifyContent: "center", height: 32, padding: "0 15px", borderRadius: 8, fontSize: 12, 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", whiteSpace: "nowrap" }}>{label}</span>;
              })}
            </div>
          </div>

          <div style={{ fontSize: 10, letterSpacing: ".18em", textTransform: "uppercase", color: "rgba(207,207,207,.45)", marginBottom: 13 }}>Autenticação</div>
          <label style={{ display: "block", fontSize: 11, color: "rgba(207,207,207,.5)", marginBottom: 8 }}>Chave de API</label>
          <div className="nn-crow" style={{ display: "flex", alignItems: "center", gap: 8, height: 46, padding: "0 8px 0 14px", borderRadius: 11, background: "#0e0e10", border: "1px solid #242427", transition: "border-color .2s", marginBottom: 13 }}>
            <span style={{ flex: 1, minWidth: 0, fontSize: 13, color: "#e2e1df", fontFamily: "var(--font-mono)", letterSpacing: ".04em", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{reveal ? fullKey : maskKey}</span>
            <button onClick={() => setReveal((v) => !v)} style={{ flex: "none", width: 32, height: 32, borderRadius: 8, display: "flex", alignItems: "center", justifyContent: "center", background: "rgba(255,255,255,.03)", border: "1px solid #2a2a2e", color: "#aecbe0", cursor: "pointer" }}>
              {reveal ? <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7-10-7-10-7Z" /><circle cx="12" cy="12" r="3" /><path d="M3 3l18 18" /></svg> : <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7-10-7-10-7Z" /><circle cx="12" cy="12" r="3" /></svg>}
            </button>
            <button onClick={() => copy("key", fullKey)} style={{ flex: "none", display: "flex", alignItems: "center", gap: 6, height: 32, padding: "0 11px", borderRadius: 8, background: "rgba(255,255,255,.03)", border: "1px solid #2a2a2e", color: "#cfcfcf", fontSize: 11.5, fontWeight: 600, cursor: "pointer", fontFamily: "inherit" }}>{icon("M5 15V5a2 2 0 0 1 2-2h8", { width: 13, height: 13 })}<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" style={{ marginLeft: -19 }}><rect x="9" y="9" width="11" height="11" rx="2" /></svg>{copiedKey ? "Copiado" : "Copiar"}</button>
          </div>
          <label style={{ display: "block", fontSize: 11, color: "rgba(207,207,207,.5)", margin: "0 0 8px" }}>Segredo do cliente</label>
          <div className="nn-crow" style={{ display: "flex", alignItems: "center", gap: 10, height: 46, padding: "0 14px", borderRadius: 11, background: "#0e0e10", border: "1px solid #242427", transition: "border-color .2s", marginBottom: 22 }}>
            <span style={{ flex: 1, minWidth: 0, fontSize: 13, color: "rgba(207,207,207,.55)", fontFamily: "var(--font-mono)", letterSpacing: ".18em" }}>••••••••••••••••</span>
            <span style={{ flex: "none", display: "flex", alignItems: "center", gap: 6, fontSize: 11, color: "#7fe0bc" }}><span style={{ width: 6, height: 6, borderRadius: "50%", background: "#5fd0a6", boxShadow: "0 0 6px #5fd0a6" }} />Criptografado</span>
          </div>

          <div style={{ fontSize: 10, letterSpacing: ".18em", textTransform: "uppercase", color: "rgba(207,207,207,.45)", marginBottom: 13 }}>Permissões concedidas</div>
          <div style={{ display: "flex", flexWrap: "wrap", gap: 8, marginBottom: 22 }}>
            {scopes.map((s) => <span key={s} style={{ display: "flex", alignItems: "center", gap: 7, height: 30, padding: "0 12px", borderRadius: 9, background: "rgba(255,255,255,.03)", border: "1px solid #232326", fontSize: 12, color: "#d8d8d8" }}>{icon("M5 12.5l4.5 4.5L19 7.5", { width: 12, height: 12, strokeWidth: 2.4, style: { color: "#5fd0a6" } })}{s}</span>)}
          </div>

          <div style={{ fontSize: 10, letterSpacing: ".18em", textTransform: "uppercase", color: "rgba(207,207,207,.45)", marginBottom: 13 }}>Atividade</div>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
            <div style={{ padding: "14px 16px", borderRadius: 13, background: "rgba(255,255,255,.018)", border: "1px solid #1f1f22" }}><div style={{ fontSize: 9.5, letterSpacing: ".13em", color: "rgba(207,207,207,.42)" }}>ÚLTIMA ROTAÇÃO</div><div style={{ fontSize: 14.5, fontWeight: 700, color: "#fff", marginTop: 7 }}>{rotated ? "agora mesmo" : (cfg.rotated || "14 abr 2026")}</div></div>
            <div style={{ padding: "14px 16px", borderRadius: 13, background: "rgba(255,255,255,.018)", border: "1px solid #1f1f22" }}><div style={{ fontSize: 9.5, letterSpacing: ".13em", color: "rgba(207,207,207,.42)" }}>CONECTADA POR</div><div style={{ fontSize: 14.5, fontWeight: 700, color: "#fff", marginTop: 7 }}>Felipe Costa</div></div>
          </div>
        </div>

        <footer style={{ flex: "none", padding: "18px 26px 22px", borderTop: "1px solid #161619", background: "linear-gradient(180deg,rgba(7,7,8,0),#070708 40%)" }}>
          <div style={{ display: "flex", gap: 11 }}>
            <button onClick={() => { setRotated(true); setReveal(false); }} style={{ flex: 1, display: "flex", alignItems: "center", justifyContent: "center", gap: 9, height: 48, borderRadius: 13, background: "rgba(255,255,255,.02)", border: "1px solid #2a2a2e", color: "#cfcfcf", fontSize: 13.5, fontWeight: 700, cursor: "pointer", fontFamily: "inherit" }}>{icon("M3 12a9 9 0 1 0 3-6.7L3 8M3 4v4h4")}{rotated ? "Rotacionada" : "Rotacionar chave"}</button>
            <button onClick={onClose} style={{ flex: 1, display: "flex", alignItems: "center", justifyContent: "center", gap: 9, height: 48, borderRadius: 13, background: "#aecbe0", border: "none", color: "#06121c", fontSize: 13.5, fontWeight: 700, cursor: "pointer", boxShadow: "0 0 24px rgba(174,203,224,.32)", fontFamily: "inherit" }}>{icon("M5 12.5l4.5 4.5L19 7.5", { strokeWidth: 2.4 })}Concluído</button>
          </div>
        </footer>
      </aside>
    </>
  );
}

window.McpCredentialsModal = McpCredentialsModal;
