/* optimizationlab.jsx — OptimizationTutor: the optimization bench. Built on window.BenchKit
   (harness) + window.BenchFields (shared field math), so this file is just the FIGURE.
   computeFields = window.BenchFields.optimization — the SAME function server/benches/optimization.js
   calls, so client and server fields are identical by construction. The learner folds an open box
   from an S×S sheet by cutting a square of side c from each corner; the volume V(c) = c(S − 2c)²,
   the derivative V'(c), and an at-optimum flag (c = S/6) update live. */
(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.optimization(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 OptimizationFig({ task, setTask, tasks, report, event, done }) {
    const [S, setS] = useState(12);
    const [c, setC] = useState(1);
    const fld = useMemo(() => compute({ S, c }), [S, c]);
    useEffect(() => { report(fld); }, [S, c]); // eslint-disable-line

    // ── flat S×S sheet (left), drawn as a square with the four corner cut-squares shaded ──
    const SH0 = 30, SHT = 36, SHW = 200; // sheet box: top-left, side px
    const scale = SHW / S;               // math units → px on the sheet
    const cpx = Math.min(c, S / 2) * scale;
    const baseSide = fld.baseSide;
    // corner cut rectangles (size cpx) at the four corners of the sheet
    const corners = [
      [SH0, SHT], [SH0 + SHW - cpx, SHT], [SH0, SHT + SHW - cpx], [SH0 + SHW - cpx, SHT + SHW - cpx],
    ];

    // ── V(c) mini-plot (right) ──
    const PX0 = 300, PX1 = 560, PY0 = 36, PY1 = 250;
    const cMax = S / 2;
    const vAt = (cc) => { const b = S - 2 * cc; return cc * b * b; };
    const vPeak = fld.maxVolume || vAt(S / 6);
    const px = (cc) => PX0 + (cc / cMax) * (PX1 - PX0);
    const py = (v) => PY1 - (Math.max(0, Math.min(vPeak * 1.05, v)) / (vPeak * 1.05)) * (PY1 - PY0);
    const vpts = [];
    for (let i = 0; i <= 80; i++) { const cc = (i / 80) * cMax; vpts.push(`${px(cc).toFixed(1)},${py(vAt(cc)).toFixed(1)}`); }
    const vcurve = vpts.join(" ");
    const optCx = px(fld.optimalCut), optCy = py(vPeak);
    const curCx = px(c), curCy = py(fld.volume);

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

    return (
      <>
        <TaskStrip tasks={tasks} cur={task} setCur={setTask} done={done} goal={t && t.goal} />
        <svg viewBox="0 0 600 290" style={{ width: "100%", background: SVG_BG, border: `1px solid ${C.line}`, borderRadius: 8 }}>
          {/* flat sheet */}
          <rect x={SH0} y={SHT} width={SHW} height={SHW} fill="none" stroke={C.blue} strokeWidth="2" />
          {/* shaded corner cuts */}
          {corners.map(([rx, ry], i) => (
            <rect key={i} x={rx} y={ry} width={cpx} height={cpx} fill={C.crimson} fillOpacity="0.3" stroke={C.crimson} strokeWidth="1" />
          ))}
          {/* the base (the inner square that folds up) */}
          <rect x={SH0 + cpx} y={SHT + cpx} width={SHW - 2 * cpx} height={SHW - 2 * cpx} fill={accent} fillOpacity="0.12" stroke={accent} strokeWidth="1.5" strokeDasharray="4 3" />
          <text x={SH0 + SHW / 2} y={SHT + SHW / 2} fill={accent} fontSize="11" fontFamily="monospace" textAnchor="middle">base = {fmt(baseSide)}</text>
          <text x={SH0} y={SHT - 8} fill={C.mute} fontSize="11" fontFamily="monospace">S×S sheet · S = {fmt(S)} · cut c = {fmt(c)}</text>
          {/* V(c) mini-plot */}
          <line x1={PX0} y1={PY1} x2={PX1} y2={PY1} stroke={C.faint} strokeWidth="1" />
          <line x1={PX0} y1={PY0} x2={PX0} y2={PY1} stroke={C.faint} strokeWidth="1" />
          <text x={PX1} y={PY1 + 14} fill={C.faint} fontSize="10" fontFamily="monospace" textAnchor="end">c</text>
          <text x={PX0 + 4} y={PY0 + 12} fill={C.mute} fontSize="11" fontFamily="monospace">V(c) = c(S − 2c)²</text>
          <polyline points={vcurve} fill="none" stroke={C.blue} strokeWidth="2" />
          {/* peak marker at c = optimalCut */}
          <line x1={optCx} y1={PY0} x2={optCx} y2={PY1} stroke={C.teal} strokeWidth="1" strokeDasharray="3 4" />
          <circle cx={optCx} cy={optCy} r={4} fill={C.teal} />
          <text x={optCx + 6} y={optCy - 6} fill={C.teal} fontSize="10" fontFamily="monospace">c = S/6</text>
          {/* current point */}
          <circle cx={curCx} cy={curCy} r={5} fill={accent} stroke={C.ink} strokeWidth="1" />
          <text x={curCx + 8} y={curCy + 4} fill={accent} fontSize="11" fontFamily="monospace">V = {fmt(fld.volume)}</text>
        </svg>
        <div style={{ marginTop: 10, padding: "8px 12px", borderRadius: 6, background: C.panel, border: `1px solid ${fld.atOptimum ? C.teal : C.line}`, color: fld.atOptimum ? C.teal : C.mute, fontSize: 12.5 }}>
          V'(c) = (S − 2c)(S − 6c) = {fmt(fld.dVdc)}. {fld.atOptimum ? <>⚑ <K.T>at the optimum — V'(c) = 0, the volume is maximal.</K.T></> : (fld.dVdc > 0 ? <K.T>Volume still rising — increase the cut.</K.T> : <K.T>Past the peak — decrease the cut.</K.T>)} <K.T>Optimal cut</K.T> c = S/6 = {fmt(fld.optimalCut)}, V_max = {fmt(fld.maxVolume)}.
        </div>
        <Slider label="sheet side S" value={S} set={setS} min={6} max={20} step={1} unit="" color={C.gold} onUp={() => event("adjusted", `Set S = ${fmt(S)}`, { response: `V = ${fmt(fld.volume)}` }, C.gold)} />
        <Slider label="corner cut c" value={c} set={setC} min={0.1} max={9} step={0.1} unit="" color={C.teal} onUp={() => event("adjusted", `Set cut c = ${fmt(c)}`, { response: `V'(c) ${fmt(fld.dVdc)}` }, C.teal)} />
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 8, marginTop: 12 }}>
          <StatMeter label="volume V(c)" v={fld.volume} d={2} color={C.blue} />
          <StatMeter label="V'(c)" v={fld.dVdc} d={2} color={accent} />
          <StatMeter label="optimal cut" v={fld.optimalCut} d={2} color={C.teal} />
          <StatMeter label="base side" v={fld.baseSide} d={2} color={C.amber} />
        </div>
      </>
    );
  }

  window.OptimizationTutor = K.makeTutor(OptimizationFig, { moduleLabel: "Optimization bench", benchId: "optimization" });
})();
