/* global React, Icon */
/* ============================================================
   ui.jsx — blocos compartilhados entre painel e módulos
   ============================================================ */
const IconU = window.Icon;

function statusChip(status, dark) {
  const S = window.AgentData.STATUS[status] || window.AgentData.STATUS.ok;
  return dark
    ? { bg: S.orb + "22", fg: S.orb, border: "transparent", orb: S.orb, label: S.label }
    : { bg: S.bg, fg: S.fg, border: S.ring, orb: S.orb, label: S.label };
}

function Badge({ t, dark, tone, children, icon }) {
  // tone = {bg,fg,orb} or status key
  const c = typeof tone === "string" ? statusChip(tone, dark) : tone;
  return (
    <span style={{ display: "inline-flex", alignItems: "center", gap: 5, background: c.bg, color: c.fg, border: `1px solid ${c.border || "transparent"}`, borderRadius: 999, padding: "3px 9px", fontSize: 10.5, fontWeight: 600, whiteSpace: "nowrap" }}>
      {c.orb && !icon && <span style={{ width: 6, height: 6, borderRadius: 6, background: c.orb }} />}
      {icon && <IconU name={icon} size={11} stroke={2.3} />}
      {children}
    </span>
  );
}

function PageHead({ t, dark, icon, accent = "var(--brand-teal-600)", title, subtitle, right }) {
  return (
    <div style={{ display: "flex", alignItems: "flex-start", gap: 14, marginBottom: 20 }}>
      <span style={{ width: 46, height: 46, borderRadius: 13, background: dark ? "rgba(174,203,224,.12)" : "#e6f4f5", color: accent, display: "grid", placeItems: "center", flex: "0 0 46px" }}><IconU name={icon} size={23} /></span>
      <div style={{ flex: 1, minWidth: 0 }}>
        <h1 style={{ margin: 0, fontSize: 38, fontWeight: 700, letterSpacing: "-.02em", color: t.ink, fontFamily: "var(--font-brand)", lineHeight: 1.05 }}>{title}</h1>
        <div style={{ fontSize: 12.5, color: t.ink2, marginTop: 3, lineHeight: 1.45, textWrap: "pretty", maxWidth: 640 }}>{subtitle}</div>
      </div>
      {right && <div style={{ display: "flex", alignItems: "center", gap: 9, flexShrink: 0 }}>{right}</div>}
    </div>
  );
}

function KTile({ t, dark, label, value, sub, icon, accent = "var(--brand-teal-600)", big, viz }) {
  return (
    <div style={{ background: dark ? "transparent" : t.cardBg, border: `1px solid ${t.cardBorder}`, borderRadius: 16, padding: viz ? "16px 18px" : (big ? "18px 20px" : "15px 17px"), boxShadow: dark ? "none" : t.cardShadow, display: viz ? "flex" : "block", alignItems: "center", justifyContent: "space-between", gap: 12 }}>
      <div style={{ minWidth: 0 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: viz ? 12 : 9, color: accent }}>
          <IconU name={icon} size={15} stroke={2} />
          <span style={{ fontSize: viz ? 10.5 : 9.5, textTransform: "uppercase", letterSpacing: viz ? ".16em" : ".08em", fontWeight: 700, color: t.ink3, whiteSpace: "nowrap" }}>{label}</span>
        </div>
        <div style={{ fontSize: viz ? 42 : (big ? 30 : 23), fontWeight: viz ? 800 : 700, color: t.ink, fontFamily: "var(--font-mono)", lineHeight: 1, letterSpacing: "-.02em" }}>{value}</div>
        {sub && <div style={{ fontSize: 11, color: t.ink3, marginTop: 6, lineHeight: 1.4 }}>{sub}</div>}
      </div>
      {viz && <div style={{ flex: "0 0 auto" }}>{viz}</div>}
    </div>
  );
}

function Bar({ pct, color, t, height = 8 }) {
  const p = Math.max(0, Math.min(100, pct));
  return (
    <div style={{ height, borderRadius: 999, background: t.statBg, border: `1px solid ${t.chipBorder}`, overflow: "hidden", width: "100%" }}>
      <div style={{ height: "100%", width: p + "%", background: color, borderRadius: 999, transition: "width .5s cubic-bezier(.22,1,.36,1)" }} />
    </div>
  );
}

// ---------- TRACE inspector (timeline passo a passo) ----------
const TRACE_TYPE = {
  trigger: { icon: "zap", c: "#8fb3d4", label: "Gatilho" },
  tool: { icon: "plug", c: "#7ea3cc", label: "Tool / MCP" },
  llm: { icon: "cpu", c: "#7c3aed", label: "Modelo" },
  decision: { icon: "git-branch", c: "#b8860b", label: "Decisão" },
  output: { icon: "check", c: "#15803d", label: "Saída" },
  blocked: { icon: "minus", c: "#8a9394", label: "Bloqueado" },
};

function TraceStep({ s, t, dark, last }) {
  const ty = TRACE_TYPE[s.t] || TRACE_TYPE.tool;
  const sc = s.status === "error" ? "#ef4444" : s.status === "warn" ? "#e0a800" : s.status === "blocked" ? "#8a9394" : ty.c;
  const llm = s.model ? window.AgentData.LLMS[s.model] : null;
  const faded = s.status === "blocked";
  return (
    <div style={{ display: "flex", gap: 12, opacity: faded ? .55 : 1 }}>
      <div style={{ display: "flex", flexDirection: "column", alignItems: "center", flex: "0 0 28px" }}>
        <span style={{ width: 28, height: 28, borderRadius: 9, background: sc + (dark ? "33" : "1a"), color: sc, display: "grid", placeItems: "center", border: `1px solid ${sc}55` }}><IconU name={ty.icon} size={14} stroke={2.2} /></span>
        {!last && <span style={{ flex: 1, width: 2, background: t.cardBorder, margin: "3px 0", minHeight: 14 }} />}
      </div>
      <div style={{ flex: 1, minWidth: 0, paddingBottom: last ? 0 : 14 }}>
        <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between", gap: 8 }}>
          <span style={{ fontSize: 12.5, fontWeight: 700, color: t.ink }}>{s.label}</span>
          <span style={{ fontSize: 10, color: t.ink3, fontFamily: "var(--font-mono)", whiteSpace: "nowrap" }}>{s.dur}</span>
        </div>
        <div style={{ fontSize: 11, color: t.ink2, marginTop: 2, lineHeight: 1.45 }}>{s.detail}</div>
        {s.io && <div style={{ fontSize: 10.5, color: s.status === "error" ? "#b91c1c" : t.ink3, marginTop: 5, fontFamily: "var(--font-mono)", background: t.statBg, border: `1px solid ${t.chipBorder}`, borderRadius: 8, padding: "6px 9px", lineHeight: 1.4 }}>{s.io}</div>}
        <div style={{ display: "flex", gap: 6, marginTop: 7, flexWrap: "wrap" }}>
          {llm && <Badge t={t} dark={dark} tone={{ bg: t.chipBg, fg: t.ink2, border: t.chipBorder }}><span style={{ width: 6, height: 6, borderRadius: 6, background: llm.color }} />{llm.name}</Badge>}
          {s.mcp && <Badge t={t} dark={dark} tone={{ bg: t.chipBg, fg: t.ink2, border: t.chipBorder }} icon="plug">{s.mcp}</Badge>}
          {(s.tokIn != null) && <Badge t={t} dark={dark} tone={{ bg: t.chipBg, fg: t.ink2, border: t.chipBorder }} icon="coins">{window.AgentData.fmtTokens(s.tokIn)} in · {window.AgentData.fmtTokens(s.tokOut)} out</Badge>}
          {s.status !== "ok" && <Badge t={t} dark={dark} tone={s.status === "blocked" ? { bg: t.chipBg, fg: t.ink3, border: t.chipBorder } : s.status}>{s.status === "error" ? "Falhou" : s.status === "warn" ? "Atenção" : "Pulado"}</Badge>}
        </div>
      </div>
    </div>
  );
}

function TraceView({ steps, t, dark }) {
  return (
    <div style={{ paddingTop: 4 }}>
      {steps.map((s, i) => <TraceStep key={i} s={s} t={t} dark={dark} last={i === steps.length - 1} />)}
    </div>
  );
}

// GridFx — fundo de bolinhas + spotlight azul que segue o mouse.
// Coloque como camada (irmã anterior ao conteúdo posicionado) dentro de um
// container posicionado; o conteúdo `position: relative` pinta por cima.
function GridFx({ dark }) {
  const rootRef = React.useRef(null);
  const glowRef = React.useRef(null);
  React.useEffect(() => {
    const onMove = (e) => {
      const root = rootRef.current, glow = glowRef.current;
      if (!root || !glow) return;
      const r = root.getBoundingClientRect();
      const mx = e.clientX - r.left, my = e.clientY - r.top;
      if (mx < 0 || my < 0 || mx > r.width || my > r.height) { glow.style.opacity = "0"; return; }
      const mask = `radial-gradient(circle 150px at ${mx}px ${my}px, #000 0%, rgba(0,0,0,.45) 50%, transparent 76%)`;
      glow.style.webkitMaskImage = mask;
      glow.style.maskImage = mask;
      glow.style.opacity = "1";
    };
    window.addEventListener("mousemove", onMove);
    return () => window.removeEventListener("mousemove", onMove);
  }, []);
  const base = dark ? "rgba(174,203,224,.14)" : "rgba(13,56,59,.11)";
  const blue = dark ? "rgba(114,178,230,.95)" : "rgba(58,143,220,.85)";
  return (
    <div ref={rootRef} aria-hidden style={{ position: "absolute", inset: 0, pointerEvents: "none", overflow: "hidden" }}>
      <div style={{ position: "absolute", inset: 0, backgroundImage: `radial-gradient(circle at 1px 1px, ${base} 1px, transparent 1.6px)`, backgroundSize: "28px 28px" }} />
      <div ref={glowRef} style={{ position: "absolute", inset: 0, opacity: 0, transition: "opacity .3s ease", backgroundImage: `radial-gradient(circle at 1px 1px, ${blue} 1.5px, transparent 2px)`, backgroundSize: "28px 28px" }} />
    </div>
  );
}

Object.assign(window, { statusChip, Badge, PageHead, KTile, Bar, TraceView, GridFx });
