/* slopefieldlab.jsx — SlopeFieldTutor: the slope fields & ODEs bench. Built on window.BenchKit
   (harness) + window.BenchFields (shared field math), so this file is just the FIGURE.
   computeFields = window.BenchFields.slopefield — the SAME function server/benches/slopefield.js
   calls, so client and server fields are identical by construction. The learner sets the rate k,
   the initial value y0 and a target x on the separable ODE dy/dx = k·y; a slope field of short
   segments and the closed-form solution y = y0·e^{kx} make the field and its solution visible. */
(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.slopefield(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 SlopeFieldFig({ task, setTask, tasks, report, event, done }) {
    const [k, setK] = useState(0.5);
    const [y0, setY0] = useState(1);
    const [xT, setXT] = useState(2);
    const fld = useMemo(() => compute({ k, y0, xT }), [k, y0, xT]);
    useEffect(() => { report(fld); }, [k, y0, xT]); // eslint-disable-line

    // plot window: x ∈ [0,4], y ∈ [0,10]; map math coords → svg px.
    const X0 = 60, X1 = 560, Y0 = 30, Y1 = 270;
    const XMIN = 0, XMAX = 4, YMIN = 0, YMAX = 10;
    const sx = (x) => X0 + ((x - XMIN) / (XMAX - XMIN)) * (X1 - X0);
    const sy = (y) => Y1 - ((Math.max(YMIN, Math.min(YMAX, y)) - YMIN) / (YMAX - YMIN)) * (Y1 - Y0);
    const y = (x) => y0 * Math.exp(k * x);

    // slope field: a grid of short segments with slope k·y at each sample point.
    const seg = [];
    const NX = 11, NY = 9, half = 0.16; // half-length of each segment in x-units
    for (let i = 0; i < NX; i++) {
      const gx = XMIN + (i / (NX - 1)) * (XMAX - XMIN);
      for (let j = 0; j < NY; j++) {
        const gy = YMIN + ((j + 0.5) / NY) * (YMAX - YMIN);
        const slope = k * gy;
        // normalize the drawn segment so steep slopes don't run off-grid
        const len = half / Math.sqrt(1 + slope * slope);
        const x1 = gx - len, x2 = gx + len;
        const y1 = gy - slope * len, y2 = gy + slope * len;
        seg.push({ key: `${i}-${j}`, x1: sx(x1), y1: sy(y1), x2: sx(x2), y2: sy(y2) });
      }
    }

    // the solution curve y = y0·e^{kx} from x=0 to the window edge.
    const pts = [];
    for (let i = 0; i <= 120; i++) { const x = XMIN + (i / 120) * (XMAX - XMIN); pts.push(`${sx(x).toFixed(1)},${sy(y(x)).toFixed(1)}`); }
    const curve = pts.join(" ");

    const t = tasks.find((x) => x.id === task) || tasks[0];
    const tone = fld.isGrowth ? 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={sy(0)} x2={X1} y2={sy(0)} stroke={C.faint} strokeWidth="1" />
          <line x1={sx(0)} y1={Y0} x2={sx(0)} y2={Y1} stroke={C.faint} strokeWidth="1" />
          <text x={X1 - 6} y={sy(0) - 5} fill={C.faint} fontSize="10" fontFamily="monospace" textAnchor="end">x</text>
          {/* target line at y = 4 */}
          <line x1={X0} y1={sy(4)} x2={X1} y2={sy(4)} stroke={C.gold} strokeWidth="1" strokeDasharray="4 4" />
          <text x={X1 - 6} y={sy(4) - 5} fill={C.gold} fontSize="10" fontFamily="monospace" textAnchor="end">y = 4</text>
          {/* the slope field */}
          {seg.map((s) => <line key={s.key} x1={s.x1} y1={s.y1} x2={s.x2} y2={s.y2} stroke={C.faint} strokeWidth="1.4" />)}
          {/* the solution curve */}
          <polyline points={curve} fill="none" stroke={tone} strokeWidth="2.5" />
          {/* initial point (0, y0) */}
          <circle cx={sx(0)} cy={sy(y0)} r={5} fill={C.blue} stroke={C.ink} strokeWidth="1" />
          <text x={sx(0) + 9} y={sy(y0) - 8} fill={C.blue} fontSize="11" fontFamily="monospace">(0, {fmt(y0)})</text>
          {/* point at xT */}
          <circle cx={sx(xT)} cy={sy(fld.solutionY)} r={5} fill={tone} stroke={C.ink} strokeWidth="1" />
          <text x={sx(xT) - 6} y={sy(fld.solutionY) - 8} fill={tone} fontSize="12" fontFamily="monospace" textAnchor="end">y({fmt(xT)}) = {fmt(fld.solutionY)}</text>
          <text x={X0 + 4} y={Y0 + 14} fill={C.mute} fontSize="11" fontFamily="monospace">dy/dx = {fmt(k)}·y · y = {fmt(y0)}·e^({fmt(k)}x)</text>
        </svg>
        <div style={{ marginTop: 10, padding: "8px 12px", borderRadius: 6, background: C.panel, border: `1px solid ${tone}`, color: tone, fontSize: 12.5 }}>
          y = {fmt(y0)}·e^({fmt(k)}x). {fld.isGrowth ? <K.T>Growth — the field flows upward.</K.T> : <K.T>Decay — the field flows downward.</K.T>} {fld.isGrowth ? <><K.T>Doubling time</K.T> ln2/k = {fmt(fld.doublingX)} in x.</> : <><K.T>k ≤ 0: the quantity is not doubling.</K.T></>} {fld.crossedTarget ? <><K.T>Solution reaches the target line</K.T> (y = 4).</> : null}
        </div>
        <Slider label="rate k" value={k} set={setK} min={-1} max={1} step={0.1} unit="" color={C.teal} onUp={() => event("adjusted", `Set k = ${fmt(k)}`, { response: `y(${fmt(xT)}) ${fmt(fld.solutionY)}` }, C.teal)} />
        <Slider label="initial y(0)" value={y0} set={setY0} min={0.2} max={5} step={0.2} unit="" color={C.blue} onUp={() => event("adjusted", `Set y0 = ${fmt(y0)}`, { response: `y(${fmt(xT)}) ${fmt(fld.solutionY)}` }, C.blue)} />
        <Slider label="target x" value={xT} set={setXT} min={0} max={4} step={0.2} unit="" color={C.gold} onUp={() => event("adjusted", `Set target x = ${fmt(xT)}`, { response: `y ${fmt(fld.solutionY)}` }, C.gold)} />
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 8, marginTop: 12 }}>
          <StatMeter label="y at target" v={fld.solutionY} d={2} color={tone} />
          <StatMeter label="doubling time" v={fld.doublingX} d={2} color={C.gold} />
          <StatMeter label="value ratio" v={fld.valueRatio} d={2} color={C.blue} />
          <StatMeter label="slope at init" v={fld.slopeAtInit} d={2} color={C.amber} />
        </div>
      </>
    );
  }

  window.SlopeFieldTutor = K.makeTutor(SlopeFieldFig, { moduleLabel: "Slope Fields & ODEs bench", benchId: "slopefield" });
})();
