/* accumulationlab.jsx — AccumulationTutor: the accumulation (FTC) bench. Built on window.BenchKit
   (harness) + window.BenchFields (shared field math), so this file is just the FIGURE.
   computeFields = window.BenchFields.accumulation — the SAME function server/benches/accumulation.js
   calls, so client and server fields are identical by construction. The learner drags the upper limit
   x of F(x) = ∫₀ˣ (t − shift) dt; the signed area from 0 to x is shaded so accumulation is 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.accumulation(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 AccumulationFig({ task, setTask, tasks, report, event, done }) {
    const [xUpper, setXUpper] = useState(3);
    const [shift, setShift] = useState(2);
    const fld = useMemo(() => compute({ xUpper, shift }), [xUpper, shift]);
    useEffect(() => { report(fld); }, [xUpper, shift]); // eslint-disable-line

    // plot window: t ∈ [0,6], y auto-clamped; map math coords → svg px.
    const X0 = 60, X1 = 560, Y0 = 30, Y1 = 270;
    const XMIN = 0, XMAX = 6, YMIN = -4, YMAX = 4;
    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 f = (t) => t - shift;            // integrand f(t) = t − shift = F'(t)
    const y0 = sy(0);

    // sample the integrand line across t.
    const linePts = [];
    for (let i = 0; i <= 120; i++) { const t = XMIN + (i / 120) * (XMAX - XMIN); linePts.push(`${sx(t).toFixed(1)},${sy(f(t)).toFixed(1)}`); }
    const line = linePts.join(" ");

    // shade the signed area from 0 to x: split into positive (above axis) and negative (below).
    // build a filled region bounded by the integrand, the axis, and the vertical at x.
    const N = 80;
    const posPath = []; const negPath = [];
    for (let i = 0; i <= N; i++) {
      const t = XMIN + (i / N) * (Math.max(XMIN, Math.min(XMAX, xUpper)) - XMIN);
      const yv = f(t);
      const X = sx(t).toFixed(1);
      if (yv >= 0) { posPath.push(`${X},${y0.toFixed(1)}`, `${X},${sy(yv).toFixed(1)}`); }
      else { negPath.push(`${X},${y0.toFixed(1)}`, `${X},${sy(yv).toFixed(1)}`); }
    }
    // turn the strip points into a polygon (down the value, back along the axis).
    const stripPoly = (pairs) => {
      if (!pairs.length) return null;
      const tops = []; const bots = [];
      for (let i = 0; i < pairs.length; i += 2) { bots.push(pairs[i]); tops.push(pairs[i + 1]); }
      return tops.join(" ") + " " + bots.reverse().join(" ");
    };
    const posPoly = stripPoly(posPath), negPoly = stripPoly(negPath);

    const xpx = sx(Math.max(XMIN, Math.min(XMAX, xUpper)));

    const t = tasks.find((x) => x.id === task) || tasks[0];
    const areaColor = fld.areaPositive ? C.teal : C.crimson;
    const fColor = fld.atMin ? C.amber : (fld.isIncreasing ? C.teal : C.crimson);

    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 }}>
          {/* shaded signed area 0→x */}
          {negPoly && <polygon points={negPoly} fill={C.crimson} fillOpacity="0.28" stroke="none" />}
          {posPoly && <polygon points={posPoly} fill={C.teal} fillOpacity="0.28" stroke="none" />}
          {/* axes */}
          <line x1={X0} y1={y0} x2={X1} y2={y0} 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={y0 - 5} fill={C.faint} fontSize="10" fontFamily="monospace" textAnchor="end">t</text>
          {/* minimum marker at t = shift (f crosses zero) */}
          <line x1={sx(shift)} y1={Y0} x2={sx(shift)} y2={Y1} stroke={C.line} strokeWidth="1" strokeDasharray="3 4" />
          {/* the integrand line f(t) = t − shift */}
          <polyline points={line} fill="none" stroke={C.blue} strokeWidth="2" />
          {/* vertical line at the current upper limit x */}
          <line x1={xpx} y1={Y0} x2={xpx} y2={Y1} stroke={areaColor} strokeWidth="2" />
          <circle cx={xpx} cy={sy(fld.fx)} r={5} fill={fColor} stroke={C.ink} strokeWidth="1" />
          <text x={xpx + 9} y={sy(fld.fx) - 8} fill={fColor} fontSize="12" fontFamily="monospace">f(x) = F'(x) = {fmt(fld.fx)}</text>
          <text x={X0 + 4} y={Y0 + 14} fill={C.mute} fontSize="11" fontFamily="monospace">F(x) = ∫₀ˣ(t − {fmt(shift)})dt · x = {fmt(xUpper)} · area = {fmt(fld.accumArea)}</text>
        </svg>
        <div style={{ marginTop: 10, padding: "8px 12px", borderRadius: 6, background: C.panel, border: `1px solid ${fld.atMin ? C.amber : C.line}`, color: fld.atMin ? C.amber : C.mute, fontSize: 12.5 }}>
          F(x) = x²/2 − {fmt(shift)}·x = {fmt(fld.accumArea)}. {fld.atMin ? <>⚑ <K.T>minimum of F — the integrand f(x) = 0 here.</K.T></> : (fld.isIncreasing ? <K.T>Accumulated area is increasing (f &gt; 0).</K.T> : <K.T>Accumulated area is decreasing (f &lt; 0).</K.T>)} {fld.areaPositive ? <><K.T>Net area positive</K.T> (F &gt; 0).</> : <><K.T>Net area negative</K.T> (F &lt; 0).</>}
        </div>
        <Slider label="upper limit x" value={xUpper} set={setXUpper} min={0} max={6} step={0.1} unit="" color={C.teal} onUp={() => event("adjusted", `Dragged upper limit to x = ${fmt(xUpper)}`, { response: `F(x) ${fmt(fld.accumArea)}` }, C.teal)} />
        <Slider label="integrand shift" value={shift} set={setShift} min={0} max={4} step={0.5} unit="" color={C.gold} onUp={() => event("adjusted", `Set shift = ${fmt(shift)}`, { response: `F(x) ${fmt(fld.accumArea)}` }, C.gold)} />
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 8, marginTop: 12 }}>
          <StatMeter label="area F(x)" v={fld.accumArea} d={2} color={areaColor} />
          <StatMeter label="f(x) = F'(x)" v={fld.fx} d={2} color={fColor} />
          <StatMeter label="upper limit x" v={fld.xValue} d={2} color={C.blue} />
          <StatMeter label="net area positive?" v={fld.areaPositive ? 1 : 0} d={0} color={fld.areaPositive ? C.teal : C.crimson} />
        </div>
      </>
    );
  }

  window.AccumulationTutor = K.makeTutor(AccumulationFig, { moduleLabel: "Accumulation (FTC) bench", benchId: "accumulation" });
})();
