/* eagle-agent.jsx — AI Agent · "mission control". A live investigation graph:
   Triage → Enrichment → Response agents on a spine with animated A2A edges,
   MCP tool nodes branching off enrichment, action nodes off response, a gantt
   timeline, and the assembled incident report. Theme-aware. */

const _AG = [
  { id: "triage", name: "Triage", icon: "Crosshair", role: "assess + categorise" },
  { id: "enrich", name: "Enrichment", icon: "Network", role: "MCP tool calls" },
  { id: "response", name: "Response", icon: "Zap", role: "real-world actions" },
];

function AgentNode({ def, status }) {
  const E = useE(); const c = E.agent;
  const active = status === "active", done = status === "done", on = active || done;
  return (
    <div className="flex flex-1 flex-col items-center gap-2 text-center">
      <div className="relative flex h-14 w-14 items-center justify-center rounded-2xl transition-all" style={{ background: on ? c + "1f" : E.fill, color: on ? c : E.muted, border: `1px solid ${active ? c : on ? c + "55" : E.border}`, boxShadow: active ? `0 0 22px -4px ${c}` : "none" }}>
        <window.Icon name={def.icon} size={24} />
        {active && <span className="absolute inset-0 rounded-2xl" style={{ border: `1px solid ${c}`, animation: "eagle-ping 1.5s ease-out infinite" }} />}
        {done && <span className="absolute -right-1.5 -top-1.5 flex h-5 w-5 items-center justify-center rounded-full" style={{ background: E.success, color: E.isDark ? "#04110f" : "#fff" }}><window.Icon name="Check" size={12} /></span>}
      </div>
      <div><div className="text-[12.5px] font-bold" style={{ color: on ? E.text : E.muted }}>{def.name}</div><div className="text-[10px]" style={{ color: E.muted, fontFamily: E.mono }}>{def.role}</div></div>
    </div>
  );
}

function A2AEdge({ msg }) {
  const E = useE(); const c = E.a2a;
  // "Message packet in transit": a faint dashed track between the agent icons,
  // with a little message chip that slides along it when a hand-off fires.
  // Height matches the 56px (h-14) icon box so the track centres on the icons.
  return (
    <div className="relative flex h-14 w-16 shrink-0 items-center">
      <div className="absolute inset-x-0 top-1/2 -translate-y-1/2" style={{ borderTop: `2px dashed ${msg ? c + "66" : E.border}`, transition: "border-color .3s" }} />
      {msg && (
        <span
          className="absolute top-1/2 flex h-[18px] -translate-y-1/2 items-center gap-[3px] rounded-md px-[5px]"
          style={{
            left: 2,
            background: E.isDark ? `linear-gradient(180deg, ${c}3d, ${c}26)` : `linear-gradient(180deg, ${c}1f, ${c}2e)`,
            border: `1px solid ${c}`,
            boxShadow: `0 4px 10px -4px ${c}`,
            animation: "eagle-packet 1.9s cubic-bezier(.5,0,.5,1) infinite",
          }}
        >
          <span className="block h-[3px] w-[3px] rounded-full" style={{ background: c }} />
          <span className="block h-[3px] w-[3px] rounded-full" style={{ background: c }} />
        </span>
      )}
    </div>
  );
}

function McpNode({ ev }) {
  const E = useE(); const [open, setOpen] = React.useState(false); const fn = ev.tool.split(".");
  return (
    <div className="rounded-lg a-fade-up" style={{ background: E.surface, border: `1px solid ${E.tools}33` }}>
      <button onClick={() => setOpen((v) => !v)} className="flex w-full items-center gap-2 px-2.5 py-2 text-left">
        <span className="flex h-6 w-6 shrink-0 items-center justify-center rounded-md" style={{ background: E.tools + "1f", color: E.tools }}><window.Icon name="Wrench" size={12} /></span>
        <span className="min-w-0 flex-1 truncate text-[11px]" style={{ fontFamily: E.mono, color: E.text }}><span style={{ color: E.tools }}>{fn[1]}</span>(<span style={{ color: E.app }}>{ev.args}</span>)</span>
        <window.Icon name="Check" size={12} style={{ color: E.success }} />
        <window.Icon name={open ? "ChevronDown" : "ChevronRight"} size={13} style={{ color: E.muted }} />
      </button>
      {open && <pre className="lr-scroll overflow-x-auto border-t px-2.5 py-2 text-[10px] leading-relaxed" style={{ borderColor: E.border, color: E.text2, fontFamily: E.mono }}>{ev.result}</pre>}
    </div>
  );
}

function ActionNode({ a }) {
  const E = useE(); const done = a.status === "done";
  return (
    <div className="flex items-center gap-2.5 rounded-lg px-2.5 py-2 a-fade-up" style={{ background: E.surface, border: `1px solid ${done ? E.success + "3a" : E.border}`, transition: "border-color .3s" }}>
      <span className="flex h-6 w-6 shrink-0 items-center justify-center rounded-md" style={{ background: done ? E.success + "1f" : E.fill, color: done ? E.success : E.muted }}>{done ? <window.Icon name="Check" size={13} /> : <window.Icon name="Loader" size={12} className="animate-spin" />}</span>
      <div className="min-w-0 flex-1"><div className="truncate text-[12px] font-medium" style={{ color: E.text }}>{a.label}</div><div className="truncate text-[10px]" style={{ fontFamily: E.mono, color: E.muted }}>{a.tool.split(".")[1]}()</div></div>
      {done ? <span className="inline-flex items-center gap-1 rounded-md px-1.5 py-0.5 text-[10px] font-semibold" style={{ fontFamily: E.mono, color: E.success, background: E.success + "1a" }}><window.Icon name="Link2" size={10} /> {a.chip}</span> : <span className="text-[10px] uppercase" style={{ fontFamily: E.mono, color: E.muted }}>pending</span>}
    </div>
  );
}

function GraphCanvas({ state, alert }) {
  const E = useE();
  const ag = state.agents;
  const branch = (on) => ({ width: 2, height: 18, background: on ? E.agent + "88" : E.border, margin: "0 auto" });
  return (
    <div className="rounded-xl p-4" style={{ background: E.surface, border: `1px solid ${E.border}`, backgroundImage: `radial-gradient(${E.grid} 1px, transparent 1px)`, backgroundSize: "18px 18px" }}>
      {/* agent spine */}
      <div className="flex items-start justify-center">
        <AgentNode def={_AG[0]} status={ag.triage} />
        <A2AEdge msg={state.a2a[0]} />
        <AgentNode def={_AG[1]} status={ag.enrich} />
        <A2AEdge msg={state.a2a[1]} />
        <AgentNode def={_AG[2]} status={ag.response} />
      </div>

      {/* work columns */}
      <div className="mt-1 grid grid-cols-3 gap-3">
        {/* triage */}
        <div className="flex flex-col items-center">
          <div style={branch(ag.triage)} />
          {state.agentFind.triage ? (
            <div className="w-full space-y-1.5 rounded-lg p-2.5 a-fade-up" style={{ background: E.elevated, border: `1px solid ${E.border}` }}>
              <div className="flex items-center gap-1.5"><span className="text-[10px] uppercase" style={{ color: E.muted, fontFamily: E.mono }}>severity</span><SevChip sev={state.agentFind.triage.sev} /></div>
              <div className="text-[11px]"><span className="text-[10px] uppercase" style={{ color: E.muted, fontFamily: E.mono }}>category </span><span style={{ color: E.agent, fontWeight: 600 }}>{state.agentFind.triage.cat}</span></div>
            </div>
          ) : <Pending label="awaiting triage" />}
        </div>
        {/* enrichment */}
        <div className="flex flex-col items-center">
          <div style={branch(ag.enrich)} />
          <div className="w-full space-y-2">
            {state.mcp.length === 0 && !state.mcpPending ? <Pending label="no tool calls yet" /> : null}
            {state.mcp.map((m) => <McpNode key={m._id} ev={m} />)}
            {state.mcpPending && <div className="flex items-center gap-2 rounded-lg px-2.5 py-2 text-[11px]" style={{ background: E.surface, border: `1px dashed ${E.tools}55`, color: E.muted }}><window.Icon name="Loader" size={12} className="animate-spin" style={{ color: E.tools }} /> {state.mcpPending.split(".")[1]}()…</div>}
          </div>
        </div>
        {/* response */}
        <div className="flex flex-col items-center">
          <div style={branch(ag.response)} />
          <div className="w-full space-y-2">
            {state.actions.length === 0 ? <Pending label="no actions yet" /> : state.actions.map((a) => <ActionNode key={a.id} a={a} />)}
          </div>
        </div>
      </div>
    </div>
  );
}
function Pending({ label }) {
  const E = useE();
  return <div className="w-full rounded-lg px-2.5 py-3 text-center text-[10.5px]" style={{ background: E.fill, border: `1px dashed ${E.border}`, color: E.muted, fontFamily: E.mono }}>{label}</div>;
}

function GanttTimeline({ state, alert }) {
  const E = useE(); const c = E.agent;
  const lanes = [
    { label: "Triage", start: 0, len: 18, status: state.agents.triage, ticks: state.agentFind.triage ? 1 : 0, total: 1 },
    { label: "Enrichment", start: 18, len: 52, status: state.agents.enrich, ticks: state.mcp.length, total: alert.mcp.length },
    { label: "Response", start: 70, len: 30, status: state.agents.response, ticks: state.actions.filter((a) => a.status === "done").length, total: alert.actions.length },
  ];
  return (
    <div className="rounded-xl p-4" style={{ background: E.surface, border: `1px solid ${E.border}` }}>
      <div className="mb-3 flex items-center gap-2 text-[11px] font-bold uppercase tracking-[0.14em]" style={{ color: E.muted, fontFamily: E.mono }}><window.Icon name="GanttChart" size={13} /> Investigation timeline</div>
      <div className="space-y-2.5">
        {lanes.map((ln) => {
          const done = ln.status === "done", active = ln.status === "active", on = done || active;
          const frac = ln.total ? ln.ticks / ln.total : 0;
          const fillLen = done ? ln.len : active ? Math.max(ln.len * 0.25, ln.len * frac) : 0;
          return (
            <div key={ln.label} className="flex items-center gap-3">
              <span className="w-20 shrink-0 text-[11px] font-medium" style={{ color: on ? E.text : E.muted }}>{ln.label}</span>
              <div className="relative h-6 flex-1 rounded" style={{ background: E.fill }}>
                <div className="absolute top-0 h-full rounded" style={{ left: ln.start + "%", width: fillLen + "%", background: active ? `repeating-linear-gradient(45deg, ${c}, ${c} 6px, ${c}bb 6px, ${c}bb 12px)` : c, opacity: on ? 1 : 0.2, transition: "width .6s cubic-bezier(.22,1,.36,1)" }} />
                {/* sub-step ticks */}
                {on && Array.from({ length: ln.total }).map((_, i) => (
                  <span key={i} className="absolute top-1/2 h-2 w-2 -translate-y-1/2 rounded-full" style={{ left: `calc(${ln.start}% + ${(ln.len / (ln.total + 1)) * (i + 1)}%)`, background: i < ln.ticks ? (E.isDark ? "#04110f" : "#fff") : "transparent", border: `1px solid ${i < ln.ticks ? c : E.border}` }} />
                ))}
              </div>
              <span className="w-10 shrink-0 text-right text-[10.5px] tabular-nums" style={{ fontFamily: E.mono, color: E.muted }}>{ln.total ? ln.ticks + "/" + ln.total : (done ? "✓" : "")}</span>
            </div>
          );
        })}
      </div>
      <div className="mt-3 flex justify-between text-[9.5px]" style={{ color: E.muted, fontFamily: E.mono }}><span>0s</span><span>~45s</span></div>
    </div>
  );
}

function ReportSection({ icon, ck, title, items }) {
  const E = useE(); const c = E[ck];
  return (
    <div>
      <div className="mb-1.5 flex items-center gap-1.5 text-[11px] font-bold uppercase tracking-[0.14em]" style={{ color: c, fontFamily: E.mono }}><window.Icon name={icon} size={12} /> {title}</div>
      <ul className="space-y-1.5">{items.map((it, i) => <li key={i} className="flex gap-2 text-[13px] leading-relaxed" style={{ color: E.text }}><span className="mt-1.5 h-1 w-1 shrink-0 rounded-full" style={{ background: c }} /><span><window.EInline text={it} /></span></li>)}</ul>
    </div>
  );
}
function IncidentReport({ report }) {
  const E = useE();
  const txt = () => `INCIDENT REPORT — ${report.id}\nSeverity: ${report.severity}\n${report.title}\n` +
    (report.jiraTicket ? `\nJIRA TICKET: ${report.jiraTicket} — ${report.jiraUrl}\n` : "") +
    `\nFINDINGS:\n${report.findings.map((f) => "- " + f).join("\n")}\n\nACTIONS TAKEN:\n${report.actions.map((a) => "- " + a).join("\n")}\n\nREFERENCES:\n${report.refs.map((r) => "- " + r).join("\n")}`;
  return (
    <div className="overflow-hidden rounded-xl a-fade-up" style={{ background: E.surface, border: `1px solid ${E.borderStrong}` }}>
      <div className="flex flex-wrap items-center justify-between gap-2 border-b px-4 py-3" style={{ borderColor: E.border, background: E.elevated }}>
        <span className="inline-flex items-center gap-2 text-[12px] font-bold uppercase tracking-[0.14em]" style={{ color: E.text, fontFamily: E.mono }}><window.Icon name="FileCheck2" size={15} style={{ color: E.success }} /> Incident Report · {report.id}</span>
        <div className="flex items-center gap-2">
          {report.jiraUrl && (
            <a href={report.jiraUrl} target="_blank" rel="noopener noreferrer"
              className="inline-flex items-center gap-1.5 rounded-md px-2.5 py-1.5 text-[11.5px] font-bold transition-colors hover:opacity-85"
              style={{ color: E.gateway, background: E.gateway + "14", border: `1px solid ${E.gateway}44`, fontFamily: E.mono }}>
              <window.Icon name="ExternalLink" size={13} /> Open ticket in Jira
            </a>
          )}
          <window.CopyBtn getText={txt} label="Copy report" />
        </div>
      </div>
      <div className="max-w-4xl space-y-4 px-4 py-4">
        <div className="flex items-start gap-3"><SevChip sev={report.severity} size="lg" /><p className="text-[14px] font-semibold leading-snug" style={{ color: E.text }}>{report.title}</p></div>
        <ReportSection icon="Search" ck="app" title="Findings" items={report.findings} />
        <ReportSection icon="CheckCheck" ck="success" title="Actions taken" items={report.actions} />
        <div>
          <div className="mb-1.5 flex items-center gap-1.5 text-[11px] font-bold uppercase tracking-[0.14em]" style={{ color: E.muted, fontFamily: E.mono }}><window.Icon name="BookMarked" size={12} /> References</div>
          <div className="flex flex-wrap gap-1.5">
            {report.jiraTicket && (
              <a href={report.jiraUrl} target="_blank" rel="noopener noreferrer"
                className="inline-flex items-center gap-1.5 rounded-md px-2 py-1 text-[11px] font-semibold transition-colors hover:opacity-85"
                style={{ background: E.gateway + "14", border: `1px solid ${E.gateway}44`, color: E.gateway, fontFamily: E.mono }}>
                <window.Icon name="ExternalLink" size={11} /> {report.jiraTicket}
              </a>
            )}
            {report.refs.map((r, i) => <span key={i} className="rounded-md px-2 py-1 text-[11px]" style={{ background: E.fill, border: `1px solid ${E.border}`, color: E.muted }}>{r}</span>)}
          </div>
        </div>
      </div>
    </div>
  );
}

function AgentTally({ state, alert, running }) {
  const E = useE(); const c = E.agent; const s = state.summary;
  const steps = Object.values(state.agents).filter((x) => x === "done").length;
  const cells = [
    ["Steps", s ? s.steps : steps, "GitBranch"], ["MCP calls", s ? s.mcp : state.mcp.length, "Wrench"],
    ["A2A msgs", s ? s.a2a : state.a2a.length, "ArrowLeftRight"], ["Tokens", s ? s.tokens.toLocaleString() : (state.nav.tokIn + state.nav.tokOut).toLocaleString(), "Hash"],
    ["Cost", s ? s.cost : window.eagleFmtCost(state.nav.cost), "DollarSign"], ["Time", s ? s.time : (state.nav.latency ? (state.nav.latency / 1000).toFixed(1) + "s" : "—"), "Clock"],
  ];
  return (
    <div className="grid grid-cols-3 gap-px overflow-hidden rounded-xl sm:grid-cols-6" style={{ background: E.border, border: `1px solid ${E.border}` }}>
      {cells.map(([k, v, ic], i) => <div key={i} className="px-3 py-2.5" style={{ background: E.surface }}><div className="flex items-center gap-1 text-[9.5px] uppercase tracking-[0.12em]" style={{ color: E.muted }}><window.Icon name={ic} size={10} /> {k}</div><div className="mt-0.5 text-[15px] font-bold tabular-nums" style={{ fontFamily: E.mono, color: running && i === 5 ? c : E.text }}>{v}</div></div>)}
    </div>
  );
}

function AgentPrerun({ alert }) {
  const E = useE(); const c = E.agent;
  const respTools = alert.actions.map((a) => a.tool);
  return (
    <div className="grid items-start gap-4 lg:grid-cols-3">
      <div className="rounded-xl p-5 lg:col-span-2" style={{ background: E.surface, border: `1px solid ${E.border}`, backgroundImage: `radial-gradient(${E.grid} 1px, transparent 1px)`, backgroundSize: "18px 18px" }}>
        <div className="flex items-start justify-center" style={{ opacity: 0.92 }}>
          <AgentNode def={_AG[0]} status={undefined} />
          <A2AEdge msg={null} />
          <AgentNode def={_AG[1]} status={undefined} />
          <A2AEdge msg={null} />
          <AgentNode def={_AG[2]} status={undefined} />
        </div>
        <div className="mx-auto mt-5 max-w-md rounded-lg px-4 py-3 text-center text-[12.5px] leading-relaxed" style={{ background: E.elevated, border: `1px solid ${E.border}`, color: E.muted }}>
          Idle topology — three agents collaborate over <span style={{ color: E.a2a, fontWeight: 600 }}>A2A</span>. Press <span style={{ color: c, fontWeight: 600 }}>Run investigation</span> to watch Triage → Enrichment → Response work <span style={{ color: E.text2, fontFamily: E.mono }}>#{alert.code}</span> autonomously.
        </div>
      </div>
      <div className="rounded-xl" style={{ background: E.surface, border: `1px solid ${E.border}` }}>
        <div className="border-b px-3.5 py-2.5 text-[11px] font-bold uppercase tracking-[0.16em]" style={{ color: E.muted, fontFamily: E.mono }}><window.Icon name="Wrench" size={13} style={{ display: "inline", verticalAlign: "-2px", color: E.tools }} /> Available tools</div>
        <div className="px-3 py-3">
          <div className="mb-1.5 text-[10px] font-bold uppercase tracking-[0.12em]" style={{ color: E.tools, fontFamily: E.mono }}>Enrichment · MCP</div>
          <div className="space-y-1.5">
            {alert.mcp.map((m, i) => (
              <div key={i} className="flex items-center gap-2 rounded-md px-2.5 py-1.5" style={{ background: E.elevated, border: `1px solid ${E.border}` }}>
                <window.Icon name="Wrench" size={12} style={{ color: E.tools }} />
                <span className="truncate text-[11px]" style={{ fontFamily: E.mono, color: E.text2 }}>{m.tool.split(".")[1]}</span>
              </div>
            ))}
          </div>
          <div className="mb-1.5 mt-3 text-[10px] font-bold uppercase tracking-[0.12em]" style={{ color: E.agent, fontFamily: E.mono }}>Response · actions</div>
          <div className="space-y-1.5">
            {respTools.map((t, i) => (
              <div key={i} className="flex items-center gap-2 rounded-md px-2.5 py-1.5" style={{ background: E.elevated, border: `1px solid ${E.border}` }}>
                <window.Icon name="Zap" size={12} style={{ color: E.agent }} />
                <span className="truncate text-[11px]" style={{ fontFamily: E.mono, color: E.text2 }}>{t.split(".")[1]}</span>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

function AgentScreen({ alert, onBack, onPickAlert, mode, onToggleTheme, onGo, active, autoRun }) {
  const E = useE(); const L = window.LAYERS.agent; const c = E.agent;
  const { state, running, run, reset, clearTelem } = useEagleRun(window.runAgent);
  const started = running || state.summary || Object.keys(state.agents).length > 0;
  const meters = fmtMeters(state.nav);
  const doRun = React.useCallback(() => run(alert), [alert]);
  useRunHotkey(doRun, running, active);
  // On a new Alert-Launcher selection (autoRun bumps), auto-run the investigation.
  // On any other alert change, just reset. Tab switches touch neither → run survives.
  const autoRef = React.useRef(autoRun);
  React.useEffect(() => {
    if (autoRun !== autoRef.current) { autoRef.current = autoRun; doRun(); }
    else { reset(); }
  }, [alert.id, autoRun]);

  return (
    <div className="flex h-full flex-col" style={{ background: E.bg }}>
      <EagleNav layer={L} meters={meters} running={running} onBack={onBack} mode={mode} onToggleTheme={onToggleTheme} current="agent" onGo={onGo}
        center={<span className="ml-1 inline-flex shrink-0 items-center gap-2 whitespace-nowrap rounded-lg px-2.5 py-1.5 text-[11px] font-bold uppercase tracking-[0.12em]" style={{ color: c, background: c + "14", border: `1px solid ${c}33`, fontFamily: E.mono }}><window.Icon name="Infinity" size={14} /> Autonomous loop</span>} />

      <div className="lr-scroll flex-1 overflow-y-auto px-6 py-4 lg:px-8">
        <div className="w-full space-y-4">
          <RunBar layer={L} alert={alert} running={running} started={started} onRun={doRun} onReset={reset} onPickAlert={onPickAlert} runLabel="Run investigation" />
          {started && <AgentTally state={state} alert={alert} running={running} />}

          {!started ? (
            <AgentPrerun alert={alert} />
          ) : (
            <>
              <div className="grid items-start gap-4 lg:grid-cols-3">
                {/* left 2/3: live graph, then the incident report directly below it */}
                <div className="space-y-4 lg:col-span-2">
                  <GraphCanvas state={state} alert={alert} />
                  {state.report && <IncidentReport report={state.report} />}
                </div>
                {/* right 1/3: tool & A2A telemetry */}
                <div className="h-full" style={{ minHeight: 360 }}><window.TelemetryPanel events={state.events} onClear={clearTelem} title="Tool & A2A traffic" empty="Raw tool calls and agent-to-agent messages stream here." /></div>
              </div>
              {/* full-width timeline along the bottom */}
              <GanttTimeline state={state} alert={alert} />
            </>
          )}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { AgentScreen });
