/* global React, Icon, AgentNode */
/* ============================================================
   PipelineView — visão de esteiras (design NN.ai 2.0)
   ============================================================ */
const IconP = window.Icon;

const ESTEIRA_META = {
  "Esteira Fiscal": { icon: "landmark", desc: "Captura fiscal e fechamento contábil — do recebimento da nota ao lançamento conciliado." },
  "Esteira de Pessoas": { icon: "users", desc: "Recrutamento e contratação — da triagem de currículos à geração do contrato assinado." },
  "Esteira de Relacionamento": { icon: "message-circle", desc: "Atendimento e suporte — da dúvida do cliente à abertura e resolução do chamado." },
};

// ---- card de agente da esteira (estilo template do protótipo) ----
function PipeAgentCard({ a, t, dark, selected, onSelect }) {
  const { fmtTokens, fmtNum, STATUS, LLMS } = window.AgentData;
  const S = STATUS[a.status], llm = LLMS[a.llm];
  const barColor = dark ? S.orb : a.accent;
  const sparkColor = a.status === "error" ? "#e07a82" : "#72b2e6";
  const max = Math.max(...a.spark);
  const pts = a.spark.map((v, i) => `${(i / (a.spark.length - 1)) * 264},${44 - (v / max) * 40}`).join(" ");
  const sucColor = S.orb;
  return (
    <article onClick={() => onSelect(a.id)} className="nn-pcard" style={{ flex: 1, minWidth: 0, position: "relative", borderRadius: 18, background: dark ? "linear-gradient(180deg,#141416,#0f0f11)" : t.cardBg, border: `1px solid ${selected ? barColor : (dark ? "#242427" : t.cardBorder)}`, boxShadow: "0 18px 40px rgba(0,0,0,.45)", overflow: "hidden", cursor: "pointer" }}>
      <div style={{ height: 3, background: `linear-gradient(90deg, ${barColor}, transparent)` }} />
      <div style={{ padding: "18px 20px 20px" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 7, fontSize: 10, letterSpacing: ".18em", color: t.ink3, textTransform: "uppercase" }}><span style={{ width: 7, height: 7, borderRadius: "50%", background: S.orb, boxShadow: `0 0 8px ${S.orb}` }} />{a.short}</div>
        <h3 style={{ margin: "9px 0 0", fontSize: 16.5, fontWeight: 700, color: t.ink, letterSpacing: "-.01em" }}>{a.name}</h3>
        <p style={{ margin: "7px 0 0", fontSize: 12, lineHeight: 1.5, color: t.ink2 }}>{a.role}</p>
        <div style={{ display: "flex", gap: 7, marginTop: 13, flexWrap: "wrap" }}>
          <span style={{ display: "flex", alignItems: "center", gap: 6, height: 26, padding: "0 10px", borderRadius: 200, whiteSpace: "nowrap", background: "rgba(255,255,255,.04)", border: "1px solid #2a2a2e", fontSize: 11.5, fontWeight: 600, color: "#e2e1df" }}><span style={{ width: 6, height: 6, borderRadius: "50%", background: llm.color }} />{llm.name}</span>
          <span style={{ display: "flex", alignItems: "center", gap: 6, height: 26, padding: "0 10px", borderRadius: 200, whiteSpace: "nowrap", background: S.orb + "1a", border: `1px solid ${S.orb}52`, fontSize: 11.5, fontWeight: 600, color: S.orb }}><span style={{ width: 6, height: 6, borderRadius: "50%", background: S.orb, boxShadow: `0 0 6px ${S.orb}` }} />{S.label}</span>
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", marginTop: 16, border: `1px solid ${dark ? "#1f1f22" : t.chipBorder}`, borderRadius: 12, overflow: "hidden" }}>
          {[["TOKENS HOJE", fmtTokens(a.metrics.tokensDay), t.ink], ["ACION./DIA", fmtNum(a.metrics.calls), t.ink], ["SUCESSO", a.metrics.success + "%", sucColor]].map(([l, v, c], i) => (
            <div key={l} style={{ padding: "10px 11px", borderLeft: i ? `1px solid ${dark ? "#1f1f22" : t.chipBorder}` : "none" }}>
              <div style={{ fontSize: 8.5, letterSpacing: ".13em", color: t.ink3 }}>{l}</div>
              <div style={{ fontSize: 15, fontWeight: 700, color: c, marginTop: 4 }}>{v}</div>
            </div>
          ))}
        </div>
        <svg width="100%" height="40" viewBox="0 0 264 44" preserveAspectRatio="none" style={{ marginTop: 12, display: "block" }}>
          <polygon points={`${pts} 264,44 0,44`} fill={sparkColor} fillOpacity="0.12" />
          <polyline points={pts} fill="none" stroke={sparkColor} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" />
        </svg>
        <div style={{ height: 1, background: dark ? "#1d1d20" : t.cardBorder, margin: "16px 0 13px" }} />
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}><span style={{ fontSize: 9, letterSpacing: ".16em", color: t.ink3 }}>MCPS ACOPLADOS</span><span style={{ fontSize: 9.5, color: t.ink3 }}>{a.mcps.length} tools</span></div>
        <div style={{ display: "flex", flexWrap: "wrap", gap: 7, marginTop: 11 }}>
          {a.mcps.map((m) => (
            <span key={m.id} style={{ display: "flex", alignItems: "center", gap: 7, height: 32, padding: "0 11px 0 8px", borderRadius: 9, background: "rgba(255,255,255,.03)", border: `1px solid ${dark ? "#232326" : t.chipBorder}`, fontSize: 11.5, color: t.ink }}><span style={{ width: 20, height: 20, borderRadius: 6, flex: "none", background: "rgba(174,203,224,.1)", display: "flex", alignItems: "center", justifyContent: "center", color: "#aecbe0" }}><IconP name={m.icon} size={12} stroke={1.8} /></span>{m.name}</span>
          ))}
        </div>
      </div>
    </article>
  );
}

function Lane({ name, laneAgents, edges, t, dark, selectedId, onSelect, running, onRun }) {
  const { fmtTokens, fmtBRL, fmtNum, STATUS } = window.AgentData;
  const meta = ESTEIRA_META[name] || { icon: "git-branch", desc: "" };
  const ids = laneAgents.map((a) => a.id);
  const tokens = laneAgents.reduce((s, a) => s + a.metrics.tokensDay, 0);
  const custo = laneAgents.reduce((s, a) => s + a.metrics.cost, 0);
  const calls = laneAgents.reduce((s, a) => s + a.metrics.calls, 0);
  const health = { ok: 0, warn: 0, error: 0 };
  laneAgents.forEach((a) => health[a.status]++);
  const entries = laneAgents.filter((a) => !edges.some((e) => e.to === a.id && ids.includes(e.from)));
  const edgeLabel = (fromId, toId) => (edges.find((e) => e.from === fromId && e.to === toId) || {}).label;

  return (
    <div style={{ borderRadius: 22, background: dark ? "linear-gradient(180deg, rgba(255,255,255,.02), rgba(255,255,255,.004))" : t.cardBg, border: `1px solid ${dark ? "#1c1c20" : t.cardBorder}`, padding: "24px 24px 26px", boxShadow: dark ? "none" : t.cardShadow }}>
      {/* lane header */}
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 24, flexWrap: "wrap" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 15, minWidth: 0 }}>
          <span style={{ width: 52, height: 52, flex: "none", borderRadius: 15, display: "flex", alignItems: "center", justifyContent: "center", background: dark ? "linear-gradient(150deg,#16242f,#0b1217)" : "#e6f4f5", border: "1px solid rgba(174,203,224,.2)", color: "#aecbe0", boxShadow: dark ? "0 0 22px rgba(58,143,220,.16)" : "none" }}><IconP name={meta.icon} size={24} /></span>
          <div style={{ minWidth: 0 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 11 }}>
              <h2 style={{ margin: 0, fontSize: 21, fontWeight: 700, letterSpacing: "-.02em", color: t.ink, whiteSpace: "nowrap" }}>{name}</h2>
              <span style={{ fontSize: 12.5, color: t.ink3, fontWeight: 600, whiteSpace: "nowrap" }}>{laneAgents.length} {laneAgents.length === 1 ? "agente" : "agentes"}</span>
            </div>
            <p style={{ margin: "4px 0 0", fontSize: 13, color: t.ink2, lineHeight: 1.4 }}>{meta.desc}</p>
          </div>
        </div>
        <div style={{ display: "flex", alignItems: "center", gap: 28 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
            {["ok", "warn", "error"].filter((k) => health[k] > 0).map((k) => (
              <span key={k} style={{ display: "flex", alignItems: "center", gap: 6, fontSize: 15, fontWeight: 700, color: t.ink }}><span style={{ width: 8, height: 8, borderRadius: "50%", background: STATUS[k].orb, boxShadow: `0 0 8px ${STATUS[k].orb}` }} />{health[k]}</span>
            ))}
          </div>
          {[[fmtTokens(tokens), "TOKENS"], [fmtBRL(custo), "CUSTO"], [fmtNum(calls), "ACION."]].map(([v, l]) => (
            <div key={l} style={{ display: "flex", flexDirection: "column", alignItems: "flex-end" }}><span style={{ fontSize: 16, fontWeight: 700, color: t.ink, letterSpacing: "-.01em" }}>{v}</span><span style={{ fontSize: 9, letterSpacing: ".16em", color: t.ink3 }}>{l}</span></div>
          ))}
          <button onClick={() => onRun(entries.map((a) => a.id))} disabled={running} style={{ display: "flex", alignItems: "center", gap: 8, height: 40, padding: "0 17px", borderRadius: 11, background: "rgba(174,203,224,.1)", border: "1px solid rgba(174,203,224,.26)", color: "#cfe0ec", fontSize: 13, fontWeight: 700, cursor: running ? "default" : "pointer", fontFamily: "inherit", opacity: running ? .5 : 1, whiteSpace: "nowrap" }}><IconP name="play" size={13} fill="currentColor" stroke={0} /> Executar esteira</button>
        </div>
      </div>

      {/* agents row */}
      <div style={{ display: "flex", alignItems: "stretch", gap: 20, marginTop: 24, overflowX: "auto" }}>
        {laneAgents.map((a, i) => (
          <React.Fragment key={a.id}>
            {i > 0 && (() => {
              const lbl = edgeLabel(laneAgents[i - 1].id, a.id);
              const accent = dark ? "#72b2e6" : "#3a8fdc";
              const gid = `pgrad-${laneAgents[i - 1].id}-${a.id}`;
              const d = "M 3 24 C 60 24, 84 40, 141 40";
              return (
              <div style={{ flex: "none", alignSelf: "center", margin: "0 -21px", zIndex: 1, display: "flex", flexDirection: "column", alignItems: "center", gap: 10 }}>
                {lbl && <span style={{ display: "flex", alignItems: "center", height: 24, padding: "0 11px", borderRadius: 200, background: dark ? "#0d0f12" : t.statBg, border: `1px solid ${dark ? "#23262b" : t.chipBorder}`, fontSize: 10.5, letterSpacing: ".03em", color: t.ink2, whiteSpace: "nowrap" }}>{lbl}</span>}
                <svg width="144" height="64" viewBox="0 0 144 64" fill="none" style={{ overflow: "visible" }}>
                  <defs>
                    <linearGradient id={gid} x1="0" y1="0" x2="1" y2="0">
                      <stop offset="0" stopColor={accent} stopOpacity="0" />
                      <stop offset="0.5" stopColor={accent} />
                      <stop offset="1" stopColor={accent} stopOpacity="0" />
                    </linearGradient>
                  </defs>
                  <path d={d} stroke={dark ? "#2a2f37" : t.cardBorder} strokeWidth="2" strokeLinecap="round" />
                  <path d={d} stroke={accent} strokeWidth="1.8" strokeDasharray="2 9" strokeLinecap="round" className="edge-flow" style={{ opacity: .9 }} />
                  {dark && <path d={d} stroke={`url(#${gid})`} strokeWidth="2.2" strokeLinecap="round" strokeDasharray="14 226" className="nn-flow" />}
                  <circle cx="3" cy="24" r="3.1" fill={dark ? "#3a8fdc" : t.cardBorder} />
                  <circle cx="141" cy="40" r="3.4" fill={accent} style={{ filter: `drop-shadow(0 0 5px ${accent}88)` }} />
                </svg>
              </div>
              );
            })()}
            <PipeAgentCard a={a} t={t} dark={dark} selected={selectedId === a.id} onSelect={onSelect} />
          </React.Fragment>
        ))}
      </div>
    </div>
  );
}

function PipelineView({ agents, edges, t, dark, nodeRun, selectedId, onSelect, running, onRun }) {
  const order = [];
  const groups = {};
  agents.forEach((a) => { if (!groups[a.short]) { groups[a.short] = []; order.push(a.short); } groups[a.short].push(a); });

  const wrapRef = React.useRef(null);
  const glowRef = React.useRef(null);
  const onGridMove = (e) => {
    const el = glowRef.current;
    if (!el || !wrapRef.current) return;
    const rect = wrapRef.current.getBoundingClientRect();
    const mx = e.clientX - rect.left, my = e.clientY - rect.top;
    const mask = `radial-gradient(circle 150px at ${mx}px ${my}px, #000 0%, rgba(0,0,0,.45) 50%, transparent 76%)`;
    el.style.webkitMaskImage = mask;
    el.style.maskImage = mask;
    el.style.opacity = "1";
  };
  const onGridLeave = () => { if (glowRef.current) glowRef.current.style.opacity = "0"; };

  return (
    <div ref={wrapRef} onMouseMove={onGridMove} onMouseLeave={onGridLeave}
      style={{ position: "absolute", inset: 0, overflow: "hidden", background: dark ? "#000" : t.pageBg, backgroundImage: `radial-gradient(circle at 1px 1px, ${t.gridDot} 1px, transparent 1.6px)`, backgroundSize: "28px 28px" }}>
      <div ref={glowRef} aria-hidden style={{
        position: "absolute", inset: 0, pointerEvents: "none", opacity: 0, transition: "opacity .3s ease",
        backgroundImage: `radial-gradient(circle at 1px 1px, ${dark ? "rgba(114,178,230,.95)" : "rgba(58,143,220,.85)"} 1.5px, transparent 2px)`,
        backgroundSize: "28px 28px",
      }} />
      <div className="nn-scroll" style={{ position: "absolute", inset: 0, overflowY: "auto" }}>
      <div style={{ maxWidth: 1500, margin: "0 auto", padding: "26px 36px 64px" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 11, marginBottom: 24, fontSize: 14, color: "rgba(226,225,223,.72)" }}>
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#aecbe0" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d="M3 6l9-3 9 3-9 3-9-3ZM3 12l9 3 9-3M3 18l9 3 9-3" /></svg>
          <span>Cada faixa é uma <strong style={{ color: t.ink, fontWeight: 700 }}>esteira</strong> — um pipeline de agentes que processam uma jornada de ponta a ponta. Clique num agente para abrir.</span>
        </div>
        <div style={{ display: "flex", flexDirection: "column", gap: 22 }}>
          {order.map((name) => (
            <Lane key={name} name={name} laneAgents={groups[name]} edges={edges} t={t} dark={dark}
              selectedId={selectedId} onSelect={onSelect} running={running} onRun={onRun} />
          ))}
        </div>
      </div>
      </div>
    </div>
  );
}

window.PipelineView = PipelineView;
