/* integrallab.jsx — IntegralTutor: the definite-integral (Riemann sum) bench. Built on
   window.BenchKit (harness) + window.BenchFields (shared field math), so this file is just
   the FIGURE. computeFields = window.BenchFields.integral — the SAME function
   server/benches/integral.js calls, so client and server fields are identical by construction.
   Sliders → BenchFields.fn(state) → report + meters. */
(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.integral(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 }}>{label}</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 IntegralFig({ task, setTask, tasks, report, event, done }) {
    const [upperB, setUpperB] = useState(2);
    const [nRects, setNRects] = useState(4);
    const fld = useMemo(() => compute({ upperB, nRects }), [upperB, nRects]);
    useEffect(() => { report(fld); }, [upperB, nRects]); // eslint-disable-line

    // plot area: x ∈ [0, b] → [X0, X1]; y = f(x) = x² ∈ [0, b²] → [AY1, AY0] (y up).
    const X0 = 70, X1 = 540, AY0 = 50, AY1 = 250;
    const b = upperB, n = Math.max(1, Math.round(nRects)), dx = b / n;
    const yMax = b * b || 1e-9;
    const sx = (x) => X0 + (x / b) * (X1 - X0);
    const sy = (y) => AY1 - (y / yMax) * (AY1 - AY0);

    // the parabola f(x) = x² across [0, b].
    const curve = [];
    for (let i = 0; i <= 60; i++) { const x = (i / 60) * b; curve.push(`${sx(x)},${sy(x * x)}`); }

    // n right-endpoint rectangles filling the area under the curve.
    const rects = [];
    for (let i = 0; i < n; i++) {
      const xl = i * dx, xr = (i + 1) * dx, h = xr * xr; // height at right edge
      rects.push({ x: sx(xl), y: sy(h), w: sx(xr) - sx(xl), hh: AY1 - sy(h) });
    }

    const t = tasks.find((x) => x.id === task) || tasks[0];
    const conv = fld.converged;

    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={AY1} x2={X1 + 20} y2={AY1} stroke={C.faint} strokeWidth="1.5" />
          <line x1={X0} y1={AY1} x2={X0} y2={AY0 - 12} stroke={C.faint} strokeWidth="1.5" />
          <text x={X1 + 24} y={AY1 + 4} fill={C.mute} fontSize="11" fontFamily="monospace">x</text>
          <text x={X0 - 14} y={AY0 - 14} fill={C.mute} fontSize="11" fontFamily="monospace">y</text>
          {/* right-endpoint rectangles under the curve */}
          {rects.map((r, i) => (
            <rect key={i} x={r.x} y={r.y} width={r.w} height={r.hh} fill={C.teal} opacity="0.18" stroke={C.teal} strokeWidth="0.75" />
          ))}
          {/* the parabola f(x) = x² */}
          <polyline points={curve.join(" ")} fill="none" stroke={C.crimson} strokeWidth="2.5" />
          {/* baseline tick labels */}
          <text x={X0} y={AY1 + 16} fill={C.mute} fontSize="10" fontFamily="monospace">0</text>
          <text x={sx(b)} y={AY1 + 16} fill={C.mute} fontSize="10" fontFamily="monospace" textAnchor="middle">b = {fmt(b)}</text>
          <text x={X0 + 8} y={AY0 - 2} fill={C.mute} fontSize="11" fontFamily="monospace">f(x) = x²  ·  n = {n} rects</text>
          <text x={(X0 + sx(b)) / 2} y={AY1 - 10} textAnchor="middle" fill={C.ink} fontSize="13" fontFamily="monospace">area = {fmt(fld.area)}  ·  err = {fmt(fld.error)}</text>
        </svg>
        <div style={{ marginTop: 10, padding: "8px 12px", borderRadius: 6, background: C.panel, border: `1px solid ${conv ? C.teal : C.line}`, color: conv ? C.teal : C.mute, fontSize: 12.5 }}>
          ∫₀ᵇ x² dx = b³/3 = {fmt(fld.area)}. Right sum = {fmt(fld.riemannRight)} overshoots by {fmt(fld.error)}. {conv ? "✓ converged — the approximation is tight." : "Add rectangles (↑n) to shrink the error."}
        </div>
        <Slider label="upper limit b" value={upperB} set={setUpperB} min={0.5} max={5} step={0.5} color={C.gold} onUp={() => event("adjusted", `Set b = ${fmt(upperB)}`, { response: `area ${fmt(fld.area)} · err ${fmt(fld.error)}` }, C.gold)} />
        <Slider label="rectangles n" value={nRects} set={setNRects} min={1} max={50} step={1} color={C.blue} onUp={() => event("adjusted", `Set n = ${Math.round(nRects)}`, { response: `err ${fmt(fld.error)}` }, C.blue)} />
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 8, marginTop: 12 }}>
          <StatMeter label="exact area" v={fld.area} color={C.teal} />
          <StatMeter label="right sum" v={fld.riemannRight} color={C.amber} />
          <StatMeter label="error" v={fld.error} color={conv ? C.teal : C.crimson} />
          <StatMeter label="rectangles n" v={fld.nRects} d={0} color={C.blue} />
        </div>
      </>
    );
  }

  window.IntegralTutor = K.makeTutor(IntegralFig, { moduleLabel: "Definite integral bench", benchId: "integral" });
})();
