/* eulerlab.jsx — EulerTutor: the Euler's-method bench. Built on window.BenchKit (harness) +
   window.BenchFields (shared field math), so this file is just the FIGURE.
   computeFields = window.BenchFields.euler — the SAME function server/benches/euler.js calls, so
   client and server fields are identical by construction. The learner sets the initial value y0,
   the endpoint X and the number of steps n; a polygonal staircase of n Euler steps along the slope
   field dy/dx = y is drawn lagging below the exact exponential y(x) = y0·eˣ, making the step error
   visible as it converges. */
(function () {
  const { useState, useMemo, useEffect } = React;
  const K = window.BenchKit, C = K.C, SVG_BG = K.SVG_BG, fmt = K.fmt;
  const TaskStrip = K.TaskStrip, StatMeter = K.StatMeter;
  const compute = (s) => window.BenchFields.euler(s);

  function Slider({ label, value, set, min, max, step, unit, color, onUp }) {
    return (
      <div style={{ display: "flex", alignItems: "center", gap: 10, marginTop: 9 }}>
        <span style={{ fontSize: 12, color: C.mute, width: 116 }}><K.T>{label}</K.T></span>
        <input type="range" min={min} max={max} step={step} value={value} onChange={(e) => set(parseFloat(e.target.value))} onPointerUp={onUp} style={{ flex: 1 }} />
        <span style={{ color: color || C.amber, width: 64, textAlign: "right" }}>{value}{unit ? ` ${unit}` : ""}</span>
      </div>
    );
  }

  function EulerFig({ task, setTask, tasks, report, event, done }) {
    const [y0, setY0] = useState(1);
    const [X, setX] = useState(1.5);
    const [n, setN] = useState(4);
    const fld = useMemo(() => compute({ y0, X, n }), [y0, X, n]);
    useEffect(() => { report(fld); }, [y0, X, n]); // eslint-disable-line

    // plot the exact curve y = y0·eˣ over [0,X] and the Euler staircase (recomputed inline) lagging below.
    const X0 = 60, X1 = 380, baseY = 250, plotW = X1 - X0, plotH = 190;
    const xx = Math.max(0.5, X);
    const ni = Math.max(1, Math.round(n));
    const h = xx / ni;
    const yMax = Math.max(y0 * Math.exp(xx), 0.1);
    const sx = (x) => X0 + (x / xx) * plotW;
    const sy = (y) => baseY - (y / yMax) * plotH;

    // exact exponential curve
    let curve = `M ${sx(0).toFixed(1)} ${sy(y0).toFixed(1)}`;
    const SEG = 40;
    for (let i = 1; i <= SEG; i++) { const x = (xx * i) / SEG; curve += ` L ${sx(x).toFixed(1)} ${sy(y0 * Math.exp(x)).toFixed(1)}`; }

    // Euler polygonal staircase: y ← y + h·y
    let stair = `M ${sx(0).toFixed(1)} ${sy(y0).toFixed(1)}`;
    let ey = y0, ex = 0;
    for (let i = 0; i < ni; i++) { ey = ey + h * ey; ex = ex + h; stair += ` L ${sx(ex).toFixed(1)} ${sy(ey).toFixed(1)}`; }

    const t = tasks.find((x) => x.id === task) || tasks[0];
    const okColor = fld.converged ? C.teal : C.amber;

    return (
      <>
        <TaskStrip tasks={tasks} cur={task} setCur={setTask} done={done} goal={t && t.goal} />
        <svg viewBox="0 0 600 300" style={{ width: "100%", background: SVG_BG, border: `1px solid ${C.line}`, borderRadius: 8 }}>
          {/* axes */}
          <line x1={X0} y1={baseY} x2={X1 + 4} y2={baseY} stroke={C.faint} strokeWidth="1.2" />
          <line x1={X0} y1={baseY} x2={X0} y2={baseY - plotH - 4} stroke={C.faint} strokeWidth="1.2" />
          {/* exact exponential */}
          <path d={curve} fill="none" stroke={C.teal} strokeWidth="2.2" />
          {/* Euler staircase (lags below) */}
          <path d={stair} fill="none" stroke={C.gold} strokeWidth="2" />
          {/* the step error at X */}
          <line x1={sx(xx)} y1={sy(ey)} x2={sx(xx)} y2={sy(y0 * Math.exp(xx))} stroke={okColor} strokeWidth="1.4" strokeDasharray="3 2" />
          {/* labels */}
          <text x={X0} y={baseY + 16} fill={C.faint} fontSize="10" fontFamily="monospace" textAnchor="middle">0</text>
          <text x={sx(xx)} y={baseY + 16} fill={C.faint} fontSize="10" fontFamily="monospace" textAnchor="middle">X = {fmt(xx)}</text>
          {/* readout panel on the right */}
          <text x={X1 + 36} y={40} fill={C.mute} fontSize="12" fontFamily="monospace">dy/dx = y, y(0) = {fmt(y0)}</text>
          <text x={X1 + 36} y={66} fill={C.gold} fontSize="13" fontFamily="monospace">Euler y(X) = {fmt(fld.yEuler)}</text>
          <text x={X1 + 36} y={88} fill={C.teal} fontSize="13" fontFamily="monospace">exact y(X) = {fmt(fld.yExact)}</text>
          <text x={X1 + 36} y={110} fill={okColor} fontSize="13" fontFamily="monospace">error = {fmt(fld.error)}</text>
          <text x={X1 + 36} y={132} fill={C.mute} fontSize="12" fontFamily="monospace">{fld.steps} steps · h = {fmt(fld.stepH)}</text>
        </svg>
        <div style={{ marginTop: 10, padding: "8px 12px", borderRadius: 6, background: C.panel, border: `1px solid ${fld.converged ? C.teal : C.line}`, color: fld.converged ? C.teal : C.mute, fontSize: 12.5 }}>
          Euler estimate y(X) = {fmt(fld.yEuler)} vs exact y0·eˣ = {fmt(fld.yExact)}. {fld.converged ? <>⚑ <K.T>Converged — the staircase has closed onto the exponential.</K.T></> : <K.T>Not converged yet — add steps (raise n) to shrink the error.</K.T>}
        </div>
        <Slider label="initial y(0)" value={y0} set={setY0} min={0.5} max={3} step={0.5} unit="" color={C.teal} onUp={() => event("adjusted", `Set y0 = ${fmt(y0)}`, { response: `exact ${fmt(fld.yExact)}` }, C.teal)} />
        <Slider label="endpoint X" value={X} set={setX} min={0.5} max={3} step={0.5} unit="" color={C.blue} onUp={() => event("adjusted", `Set X = ${fmt(X)}`, { response: `exact ${fmt(fld.yExact)}` }, C.blue)} />
        <Slider label="steps n" value={n} set={(v) => setN(Math.round(v))} min={1} max={100} step={1} unit="" color={C.gold} onUp={() => event("adjusted", `Set n = ${fmt(Math.round(n))}`, { response: `error ${fmt(fld.error)}` }, C.gold)} />
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 8, marginTop: 12 }}>
          <StatMeter label="Euler y(X)" v={fld.yEuler} d={2} color={C.gold} />
          <StatMeter label="exact y(X)" v={fld.yExact} d={2} color={C.teal} />
          <StatMeter label="error" v={fld.error} d={3} color={okColor} />
          <StatMeter label="# steps" v={fld.steps} d={0} color={C.amber} />
        </div>
      </>
    );
  }

  window.EulerTutor = K.makeTutor(EulerFig, { moduleLabel: "Euler's Method bench", benchId: "euler" });
})();
