/* doubleintegrallab.jsx — DoubleIntegralTutor: the double integrals bench. Built on
   window.BenchKit (harness) + window.BenchFields (shared field math), so this file is just the
   FIGURE. computeFields = window.BenchFields.doubleintegral — the SAME function
   server/benches/doubleintegral.js calls, so client and server fields are identical by construction.
   The learner sets the region [0,X]×[0,Y] and the grid resolution n; an n×n grid of boxes, shaded by
   f = x² + y² at each box midpoint, makes the midpoint Riemann sum under the surface visible as it
   converges to the exact volume XY(X²+Y²)/3. */
(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.doubleintegral(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 DoubleIntegralFig({ task, setTask, tasks, report, event, done }) {
    const [X, setX] = useState(2);
    const [Y, setY] = useState(2);
    const [n, setN] = useState(2);
    const fld = useMemo(() => compute({ X, Y, n }), [X, Y, n]);
    useEffect(() => { report(fld); }, [X, Y, n]); // eslint-disable-line

    // top-down plot of the rectangle [0,X]×[0,Y] as an n×n grid of boxes.
    const X0 = 60, X1 = 360, Y0 = 30, Y1 = 270;
    const gw = X1 - X0, gh = Y1 - Y0;
    const ni = Math.max(1, Math.round(n));
    const dx = X / ni, dy = Y / ni;
    // max f over the rectangle is at the far corner (X,Y) → use to normalise shading.
    const fMax = X * X + Y * Y || 1;
    const boxes = [];
    for (let i = 0; i < ni; i++) {
      for (let j = 0; j < ni; j++) {
        const xm = (i + 0.5) * dx, ym = (j + 0.5) * dy;
        const fv = xm * xm + ym * ym;
        const t = Math.max(0, Math.min(1, fv / fMax)); // 0..1, darker/taller = larger
        // i along X (left→right), j along Y drawn top→bottom from the far edge.
        const bx = X0 + (i / ni) * gw, by = Y0 + ((ni - 1 - j) / ni) * gh;
        const opacity = (0.18 + 0.72 * t).toFixed(3);
        boxes.push(<rect key={`${i}-${j}`} x={bx.toFixed(1)} y={by.toFixed(1)} width={(gw / ni).toFixed(1)} height={(gh / ni).toFixed(1)} fill={C.blue} fillOpacity={opacity} stroke={C.line} strokeWidth="0.7" />);
      }
    }

    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 }}>
          {/* the n×n Riemann grid over [0,X]×[0,Y] */}
          {boxes}
          {/* region outline */}
          <rect x={X0} y={Y0} width={gw} height={gh} fill="none" stroke={C.faint} strokeWidth="1.5" />
          {/* axis labels for the region */}
          <text x={X0} y={Y1 + 16} fill={C.faint} fontSize="10" fontFamily="monospace">0</text>
          <text x={X1 - 4} y={Y1 + 16} fill={C.faint} fontSize="10" fontFamily="monospace" textAnchor="end">X = {fmt(X)}</text>
          <text x={X0 - 6} y={Y1} fill={C.faint} fontSize="10" fontFamily="monospace" textAnchor="end">0</text>
          <text x={X0 - 6} y={Y0 + 10} fill={C.faint} fontSize="10" fontFamily="monospace" textAnchor="end">Y = {fmt(Y)}</text>
          {/* readout panel on the right */}
          <text x={X1 + 24} y={Y0 + 24} fill={C.mute} fontSize="12" fontFamily="monospace">f = x² + y² over [0,X]×[0,Y]</text>
          <text x={X1 + 24} y={Y0 + 50} fill={C.blue} fontSize="13" fontFamily="monospace">Riemann = {fmt(fld.riemann)}</text>
          <text x={X1 + 24} y={Y0 + 72} fill={C.teal} fontSize="13" fontFamily="monospace">exact V = {fmt(fld.exactVol)}</text>
          <text x={X1 + 24} y={Y0 + 94} fill={okColor} fontSize="13" fontFamily="monospace">error = {fmt(fld.error)}</text>
          <text x={X1 + 24} y={Y0 + 116} fill={C.mute} fontSize="12" fontFamily="monospace">{ni}×{ni} = {fld.nBoxes} boxes</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 }}>
          Midpoint Riemann sum = {fmt(fld.riemann)} vs exact volume XY(X²+Y²)/3 = {fmt(fld.exactVol)}. {fld.converged ? <>⚑ <K.T>Converged — the Riemann sum has closed onto the exact volume.</K.T></> : <K.T>Not converged yet — add boxes (raise n) to shrink the error.</K.T>}
        </div>
        <Slider label="region width X" value={X} set={setX} min={0.5} max={4} step={0.5} unit="" color={C.teal} onUp={() => event("adjusted", `Set X = ${fmt(X)}`, { response: `riemann ${fmt(fld.riemann)}` }, C.teal)} />
        <Slider label="region depth Y" value={Y} set={setY} min={0.5} max={4} step={0.5} unit="" color={C.gold} onUp={() => event("adjusted", `Set Y = ${fmt(Y)}`, { response: `riemann ${fmt(fld.riemann)}` }, C.gold)} />
        <Slider label="boxes per side n" value={n} set={(v) => setN(Math.round(v))} min={1} max={20} step={1} unit="" color={C.blue} onUp={() => event("adjusted", `Set n = ${fmt(Math.round(n))}`, { response: `error ${fmt(fld.error)}` }, C.blue)} />
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 8, marginTop: 12 }}>
          <StatMeter label="Riemann sum" v={fld.riemann} d={2} color={C.blue} />
          <StatMeter label="exact volume" v={fld.exactVol} d={2} color={C.teal} />
          <StatMeter label="error" v={fld.error} d={3} color={okColor} />
          <StatMeter label="# boxes" v={fld.nBoxes} d={0} color={C.amber} />
        </div>
      </>
    );
  }

  window.DoubleIntegralTutor = K.makeTutor(DoubleIntegralFig, { moduleLabel: "Double Integrals bench", benchId: "doubleintegral" });
})();
