/* partialslab.jsx — PartialsTutor: the partial derivatives bench, in TRUE 3-D. Built on
   window.BenchKit (harness + 3-D SVG toolkit) + window.BenchFields (shared field math), so this file is
   just the FIGURE. computeFields = window.BenchFields.partials — the SAME function
   server/benches/partials.js calls, so client and server fields are identical by construction. The learner
   moves a point (x, y) over the surface z = x² + y² − c·x and tilts it with c; the two partial-derivative
   slices (∂z/∂x in teal, ∂z/∂y in blue) ride the surface and the gradient arrow points steepest-uphill on
   the base plane. Drag to orbit. 3-D method: docs/samples/triple-integral-svg.html. */
(function () {
  const { useState, useMemo, useEffect } = React;
  const K = window.BenchKit, C = K.C, fmt = K.fmt;
  const TaskStrip = K.TaskStrip, StatMeter = K.StatMeter, Scene3D = K.Scene3D;
  const compute = (s) => window.BenchFields.partials(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 PartialsFig({ task, setTask, tasks, report, event, done }) {
    const [x, setX] = useState(1);
    const [y, setY] = useState(1);
    const [c, setC] = useState(0);
    const [az, setAz] = useState(42);
    const [el, setEl] = useState(24);
    const fld = useMemo(() => compute({ x, y, c }), [x, y, c]);
    useEffect(() => { report(fld); }, [x, y, c]); // eslint-disable-line

    const zAt = (X, Y) => X * X + Y * Y - c * X;     // the surface
    const pz = zAt(x, y);
    const ptColor = fld.atCritical ? C.teal : C.amber;

    // frame the surface over [-3,3]² plus the base plane and the point
    const fit = [];
    for (const xx of [-3, 3]) for (const yy of [-3, 3]) { fit.push([xx, yy, zAt(xx, yy)]); fit.push([xx, yy, 0]); }
    fit.push([x, y, pz], [c / 2, 0, zAt(c / 2, 0)]);

    const build = (screen) => {
      // base plane + axes (drawn first, behind the surface)
      let out = K.poly3d(screen, [[-3, -3, 0], [3, -3, 0], [3, 3, 0], [-3, 3, 0]], "rgba(108,182,255,0.05)", C.line, 0.7);
      out += K.seg3d(screen, [-3, 0, 0], [3.2, 0, 0], C.faint, 0.8) + K.text3d(screen, [3.5, 0, 0], "x", C.faint);
      out += K.seg3d(screen, [0, -3, 0], [0, 3.2, 0], C.faint, 0.8) + K.text3d(screen, [0, 3.5, 0], "y", C.faint);
      // the surface mesh z = x²+y²−c·x, height-coloured + Lambert-shaded
      out += K.surfaceMesh3d(screen, zAt, -3, 3, -3, 3, { n: 24 });
      // vertical drop from the surface point down to the base
      out += K.seg3d(screen, [x, y, 0], [x, y, pz], C.faint, 1, "3 3");
      out += K.dot3d(screen, [x, y, 0], 2.5, C.faint);
      // the two partial-derivative slices on the surface: slope fx in x, fy in y
      const d = 0.95;
      out += K.seg3d(screen, [x - d, y, pz - fld.fx * d], [x + d, y, pz + fld.fx * d], C.teal, 2.6);
      out += K.seg3d(screen, [x, y - d, pz - fld.fy * d], [x, y + d, pz + fld.fy * d], C.blue, 2.6);
      // gradient arrow on the base plane (direction of steepest ascent)
      const g = fld.gradMag || 1;
      if (fld.gradMag > 0.05) { const L = Math.min(2.4, 0.5 + fld.gradMag * 0.4); out += K.vec3d(screen, [x, y, 0], [x + (fld.fx / g) * L, y + (fld.fy / g) * L, 0], C.crimson, 2.5); }
      // the critical point (c/2, 0) — where ∇z = 0
      out += K.dot3d(screen, [c / 2, 0, zAt(c / 2, 0)], 4.5, "none", C.teal);
      // the moved point on the surface
      out += K.dot3d(screen, [x, y, pz], 5, ptColor, C.ink);
      return out;
    };

    const t = tasks.find((q) => q.id === task) || tasks[0];

    return (
      <>
        <TaskStrip tasks={tasks} cur={task} setCur={setTask} done={done} goal={t && t.goal} />
        <Scene3D az={az} el={el} setAz={setAz} setEl={setEl} fit={fit} width={600} height={320} build={build}
          onUp={() => event("rotated", `View az ${Math.round(az)}° · el ${Math.round(el)}°`, { response: `∇z ‖${fmt(fld.gradMag)}‖` }, C.blue)} />
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginTop: 8, fontSize: 11.5, color: C.faint, fontFamily: "monospace" }}>
          <span><K.T>drag the surface to orbit</K.T> · z = x² + y² − {fmt(c)}·x · z = {fmt(fld.zValue)}</span>
          <span><span style={{ color: C.teal }}>∂z/∂x = {fmt(fld.fx)}</span> · <span style={{ color: C.blue }}>∂z/∂y = {fmt(fld.fy)}</span></span>
        </div>
        <div style={{ marginTop: 10, padding: "8px 12px", borderRadius: 6, background: C.panel, border: `1px solid ${fld.atCritical ? C.teal : C.line}`, color: fld.atCritical ? C.teal : C.mute, fontSize: 12.5 }}>
          ∂z/∂x = 2x − {fmt(c)} = {fmt(fld.fx)}, ∂z/∂y = 2y = {fmt(fld.fy)}. {fld.atCritical ? <>⚑ <K.T>critical point — the gradient is zero.</K.T></> : <><K.T>Gradient magnitude</K.T> ‖∇z‖ = {fmt(fld.gradMag)} <K.T>pointing</K.T> {fmt(fld.steepDir)}°.</>}
        </div>
        <Slider label="point x" value={x} set={setX} min={-3} max={3} step={0.1} unit="" color={C.teal} onUp={() => event("adjusted", `Moved to x = ${fmt(x)}`, { response: `∂z/∂x ${fmt(fld.fx)}` }, C.teal)} />
        <Slider label="point y" value={y} set={setY} min={-3} max={3} step={0.1} unit="" color={C.blue} onUp={() => event("adjusted", `Moved to y = ${fmt(y)}`, { response: `∂z/∂y ${fmt(fld.fy)}` }, C.blue)} />
        <Slider label="x-tilt c" value={c} set={setC} min={-4} max={4} step={0.5} unit="" color={C.gold} onUp={() => event("adjusted", `Set c = ${fmt(c)}`, { response: `∇z ‖${fmt(fld.gradMag)}‖` }, C.gold)} />
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 8, marginTop: 12 }}>
          <StatMeter label="∂z/∂x" v={fld.fx} d={2} color={C.teal} />
          <StatMeter label="∂z/∂y" v={fld.fy} d={2} color={C.blue} />
          <StatMeter label="‖∇z‖" v={fld.gradMag} d={2} color={C.crimson} />
          <StatMeter label="z" v={fld.zValue} d={2} color={C.amber} />
        </div>
      </>
    );
  }

  window.PartialsTutor = K.makeTutor(PartialsFig, { moduleLabel: "Partial Derivatives bench", benchId: "partials" });
})();
