/* global React */
const { useState: useStateAE, useEffect: useEffectAE } = React;

// AgentExecutor internals - shows the message list growing each step
function AgentExecutorViz() {
  const STAGES = [
    {
      label: "T=0 · Initial",
      desc: "Just the system prompt and the user's question.",
      msgs: [
        { role: "system", text: "You are a helpful assistant with tools: get_weather, search_web." },
        { role: "user", text: "What should I wear in Tokyo today?" },
      ],
    },
    {
      label: "T=1 · LLM call #1",
      desc: "Model decides to call get_weather. Returns an AIMessage with empty content + tool_calls.",
      msgs: [
        { role: "system", text: "You are a helpful assistant with tools: get_weather, search_web." },
        { role: "user", text: "What should I wear in Tokyo today?" },
        { role: "assistant", text: "(empty content)", tc: { name: "get_weather", args: { city: "Tokyo" } } },
      ],
    },
    {
      label: "T=2 · Tool executed",
      desc: "Executor runs the function locally, appends a ToolMessage with the result.",
      msgs: [
        { role: "system", text: "You are a helpful assistant with tools: get_weather, search_web." },
        { role: "user", text: "What should I wear in Tokyo today?" },
        { role: "assistant", text: "(empty content)", tc: { name: "get_weather", args: { city: "Tokyo" } } },
        { role: "tool", text: '{"city": "Tokyo", "temp_c": 14.1, "condition": "Light rain"}', name: "get_weather" },
      ],
    },
    {
      label: "T=3 · LLM call #2",
      desc: "Model sees the tool result. No more tool calls — emits final answer.",
      msgs: [
        { role: "system", text: "You are a helpful assistant with tools: get_weather, search_web." },
        { role: "user", text: "What should I wear in Tokyo today?" },
        { role: "assistant", text: "(empty content)", tc: { name: "get_weather", args: { city: "Tokyo" } } },
        { role: "tool", text: '{"city": "Tokyo", "temp_c": 14.1, "condition": "Light rain"}', name: "get_weather" },
        { role: "assistant", text: "It's 14°C and raining lightly in Tokyo. Wear a warm jacket and bring an umbrella." },
      ],
    },
    {
      label: "T=4 · Stop",
      desc: "No tool_calls in the last AIMessage → executor exits and returns the final content.",
      msgs: [
        { role: "system", text: "You are a helpful assistant with tools: get_weather, search_web." },
        { role: "user", text: "What should I wear in Tokyo today?" },
        { role: "assistant", text: "(empty content)", tc: { name: "get_weather", args: { city: "Tokyo" } } },
        { role: "tool", text: '{"city": "Tokyo", "temp_c": 14.1, "condition": "Light rain"}', name: "get_weather" },
        { role: "assistant", text: "It's 14°C and raining lightly in Tokyo. Wear a warm jacket and bring an umbrella.", final: true },
      ],
    },
  ];

  const [t, setT] = useStateAE(0);

  const roleColor = {
    system:    { bg: "#eceef2", fg: "var(--ink-3)" },
    user:      { bg: "#fff3f6", fg: "var(--rose)" },
    assistant: { bg: "rgba(47,91,255,0.08)", fg: "var(--electric)" },
    tool:      { bg: "#f5ffe6", fg: "#5a8a00" },
  };

  return (
    <Diagram
      title="AgentExecutor · message list over time"
      controls={
        <>
          <button className="btn ghost" onClick={() => setT(0)}>↻</button>
          <button className="btn ghost" onClick={() => setT(s => Math.max(0, s - 1))} disabled={t === 0}>‹</button>
          <button className="btn primary" onClick={() => setT(s => Math.min(STAGES.length - 1, s + 1))} disabled={t === STAGES.length - 1}>Step ›</button>
        </>
      }
    >
      <div style={{ background: "var(--bg-elev)", borderRadius: 8 }}>
        <div style={{ display: "flex", gap: 6, marginBottom: 12, flexWrap: "wrap" }}>
          {STAGES.map((s, i) => (
            <span key={i} className={`tag ${i === t ? "electric" : ""}`}
                  style={{ opacity: i <= t ? 1 : 0.4, cursor: "pointer" }}
                  onClick={() => setT(i)}>
              {s.label}
            </span>
          ))}
        </div>
        <p style={{ fontSize: 14, color: "var(--ink-2)", margin: "0 0 10px" }}>{STAGES[t].desc}</p>
        <div style={{ display: "flex", flexDirection: "column", gap: 6, padding: 10, background: "var(--bg-sunk)", borderRadius: 8 }}>
          {STAGES[t].msgs.map((m, i) => {
            const c = roleColor[m.role] || roleColor.assistant;
            return (
              <div key={i} style={{
                background: c.bg, borderLeft: `3px solid ${c.fg}`,
                padding: "8px 12px", borderRadius: 4,
                fontSize: 13, lineHeight: 1.5,
                animation: i === STAGES[t].msgs.length - 1 ? "fadeUp 280ms ease both" : "none",
              }}>
                <div style={{ fontFamily: "var(--mono)", fontSize: 10.5, color: c.fg, letterSpacing: "0.08em", marginBottom: 2, textTransform: "uppercase", fontWeight: 600 }}>
                  {m.role}{m.name ? ` · ${m.name}` : ""}{m.final ? " · FINAL" : ""}
                </div>
                <div style={{ color: "var(--ink-2)" }}>{m.text}</div>
                {m.tc && (
                  <div style={{ marginTop: 4, fontFamily: "var(--mono)", fontSize: 12, color: "var(--electric)" }}>
                    tool_calls: [{m.tc.name}({JSON.stringify(m.tc.args)})]
                  </div>
                )}
              </div>
            );
          })}
        </div>
      </div>
    </Diagram>
  );
}

window.AgentExecutorViz = AgentExecutorViz;
