/* derivativelab.jsx — DerivativeTutor: the derivatives bench. Built on window.BenchKit
   (harness) + window.BenchFields (shared field math), so this file is just the FIGURE.
   computeFields = window.BenchFields.derivative — the SAME function server/benches/derivative.js
   calls, so client and server fields are identical by construction. The learner drags a point x
   along f(x) = k(x³ − 3x); a tangent line through the point makes the slope f'(x) 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.derivative(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 DerivativeFig({ task, setTask, tasks, report, event, done }) {
    const [xEval, setXEval] = useState(2);
    const [k, setK] = useState(1);
    const fld = useMemo(() => compute({ xEval, k }), [xEval, k]);
    useEffect(() => { report(fld); }, [xEval, k]); // eslint-disable-line

    // plot window: x ∈ [-3,3], y auto-clamped; map math coords → svg px.
    const X0 = 60, X1 = 560, Y0 = 30, Y1 = 270;
    const XMIN = -3, XMAX = 3, YMIN = -10, YMAX = 10;
    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 = (x) => k * (x * x * x - 3 * x);

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

    // the dragged point + tangent segment (slope = fpx) spanning ±0.8 in x.
    const px = sx(xEval), py = sy(fld.fx);
    const dxL = -0.8, dxR = 0.8;
    const txL = xEval + dxL, txR = xEval + dxR;
    const tyL = fld.fx + fld.fpx * dxL, tyR = fld.fx + fld.fpx * dxR;

    const t = tasks.find((x) => x.id === task) || tasks[0];
    const slopeColor = fld.atCriticalPoint ? 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 }}>
          {/* axes */}
          <line x1={X0} y1={sy(0)} x2={X1} y2={sy(0)} 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={sy(0) - 5} fill={C.faint} fontSize="10" fontFamily="monospace" textAnchor="end">x</text>
          {/* critical-point markers x = ±1 */}
          {[-1, 1].map((cx) => <line key={cx} x1={sx(cx)} y1={Y0} x2={sx(cx)} y2={Y1} stroke={C.line} strokeWidth="1" strokeDasharray="3 4" />)}
          {/* the curve */}
          <polyline points={curve} fill="none" stroke={C.blue} strokeWidth="2" />
          {/* tangent segment */}
          <line x1={sx(txL)} y1={sy(tyL)} x2={sx(txR)} y2={sy(tyR)} stroke={slopeColor} strokeWidth="2.5" />
          {/* dragged point */}
          <circle cx={px} cy={py} r={5} fill={slopeColor} stroke={C.ink} strokeWidth="1" />
          <text x={px + 9} y={py - 8} fill={slopeColor} fontSize="12" fontFamily="monospace">slope f'(x) = {fmt(fld.fpx)}</text>
          <text x={X0 + 4} y={Y0 + 14} fill={C.mute} fontSize="11" fontFamily="monospace">f(x) = {fmt(k)}(x³ − 3x) · x = {fmt(xEval)} · f(x) = {fmt(fld.fx)}</text>
        </svg>
        <div style={{ marginTop: 10, padding: "8px 12px", borderRadius: 6, background: C.panel, border: `1px solid ${fld.atCriticalPoint ? C.amber : C.line}`, color: fld.atCriticalPoint ? C.amber : C.mute, fontSize: 12.5 }}>
          f'(x) = {fmt(k)}(3x² − 3) = {fmt(fld.fpx)}. {fld.atCriticalPoint ? "⚑ critical point — the tangent is flat." : (fld.isIncreasing ? "Function is increasing here." : "Function is decreasing here.")} {fld.isConcaveUp ? "Concave up (f'' > 0)." : "Concave down (f'' < 0)."}
        </div>
        <Slider label="point x" value={xEval} set={setXEval} min={-3} max={3} step={0.05} unit="" color={C.teal} onUp={() => event("adjusted", `Dragged to x = ${fmt(xEval)}`, { response: `f'(x) ${fmt(fld.fpx)}` }, C.teal)} />
        <Slider label="scale k" value={k} set={setK} min={0.2} max={3} step={0.1} unit="" color={C.gold} onUp={() => event("adjusted", `Set k = ${fmt(k)}`, { response: `f'(x) ${fmt(fld.fpx)}` }, C.gold)} />
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 8, marginTop: 12 }}>
          <StatMeter label="f(x)" v={fld.fx} d={2} color={C.blue} />
          <StatMeter label="f'(x) slope" v={fld.fpx} d={2} color={slopeColor} />
          <StatMeter label="f''(x)" v={fld.secondDeriv} d={2} color={C.amber} />
          <StatMeter label="concave up?" v={fld.isConcaveUp ? 1 : 0} d={0} color={fld.isConcaveUp ? C.teal : C.crimson} />
        </div>
      </>
    );
  }

  window.DerivativeTutor = K.makeTutor(DerivativeFig, { moduleLabel: "Derivatives bench", benchId: "derivative" });
})();
