/* global React */
const { useState: useStateRT, useEffect: useEffectRT } = React;

function ReactTrace() {
  const STEPS = [
    { role: "user",    label: "User",       body: <>What's the weather in Tokyo, and is it warmer than Bengaluru right now?</> },
    { role: "thought", label: "Thought",    body: <>I need two pieces of information: the temperature in Tokyo and in Bengaluru. I'll start by fetching Tokyo.</> },
    { role: "action",  label: "Action",     body: <><code>get_weather</code><pre>{`{ "city": "Tokyo", "units": "metric" }`}</pre></> },
    { role: "obs",     label: "Observation",body: <><pre>{`{ "city": "Tokyo", "temp_c": 18.2, "condition": "Cloudy" }`}</pre></> },
    { role: "thought", label: "Thought",    body: <>Got Tokyo: 18.2°C. Now I need Bengaluru.</> },
    { role: "action",  label: "Action",     body: <><code>get_weather</code><pre>{`{ "city": "Bengaluru", "units": "metric" }`}</pre></> },
    { role: "obs",     label: "Observation",body: <><pre>{`{ "city": "Bengaluru", "temp_c": 27.4, "condition": "Partly cloudy" }`}</pre></> },
    { role: "thought", label: "Thought",    body: <>Bengaluru is 27.4°C, Tokyo is 18.2°C. Bengaluru is warmer by 9.2°C. I have everything I need to answer.</> },
    { role: "final",   label: "Answer",     body: <>Tokyo is currently <strong>18.2°C</strong> and cloudy. Bengaluru is <strong>27.4°C</strong> and partly cloudy — about <strong>9°C warmer</strong> right now.</> },
  ];

  const [shown, setShown] = useStateRT(1);

  const next = () => setShown(s => Math.min(STEPS.length, s + 1));
  const prev = () => setShown(s => Math.max(1, s - 1));
  const reset = () => setShown(1);
  const all   = () => setShown(STEPS.length);

  return (
    <Diagram
      title="ReAct Trace · Step-through"
      controls={
        <>
          <button className="btn ghost" onClick={reset}>↻</button>
          <button className="btn ghost" onClick={prev} disabled={shown <= 1}>‹</button>
          <button className="btn primary" onClick={next} disabled={shown >= STEPS.length}>Next step ›</button>
          <button className="btn ghost" onClick={all}>Show all</button>
        </>
      }
    >
      <div className="trace">
        {STEPS.slice(0, shown).map((s, i) => (
          <div key={i} className={`trace-step ${s.role} visible`}>
            <div className="role">{s.label}</div>
            <div className="body">{s.body}</div>
          </div>
        ))}
      </div>
      <div className="figure-caption">
        Step {shown} of {STEPS.length} · Notice the LLM only ever sees the growing list of messages — no hidden state.
      </div>
    </Diagram>
  );
}

window.ReactTrace = ReactTrace;
