/* mvtlab.jsx — MvtTutor: the Mean Value Theorem bench. Built on window.BenchKit
   (harness) + window.BenchFields (shared field math), so this file is just the FIGURE.
   computeFields = window.BenchFields.mvt — the SAME function server/benches/mvt.js calls,
   so client and server fields are identical by construction. The learner sets an interval
   [a, b] and drags a point c on f(x) = x³; a secant line spans [a, b] and a tangent line at
   c makes f'(c) = 3c² visible, turning teal when it becomes parallel to the secant. */
(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.mvt(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 MvtFig({ task, setTask, tasks, report, event, done }) {
    const [a, setA] = useState(-1);
    const [b, setB] = useState(2);
    const [c, setC] = useState(0.5);
    const fld = useMemo(() => compute({ a, b, c }), [a, b, c]);
    useEffect(() => { report(fld); }, [a, b, c]); // 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) => x * x * 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 secant from (a,a³) to (b,b³)
    const saX = sx(a), saY = sy(f(a)), sbX = sx(b), sbY = sy(f(b));
    // the tangent at c (slope = tangentAtC) spanning ±0.8 in x.
    const dxL = -0.8, dxR = 0.8;
    const txL = c + dxL, txR = c + dxR;
    const fc = f(c);
    const tyL = fc + fld.tangentAtC * dxL, tyR = fc + fld.tangentAtC * dxR;
    const px = sx(c), py = sy(fc);

    const t = tasks.find((x) => x.id === task) || tasks[0];
    const tanColor = fld.matched ? C.teal : (fld.inInterval ? C.amber : 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>
          {/* endpoint markers a, b on the x-axis */}
          {[{ v: a, lbl: "a" }, { v: b, lbl: "b" }].map((m) => (
            <g key={m.lbl}>
              <line x1={sx(m.v)} y1={Y0} x2={sx(m.v)} y2={Y1} stroke={C.line} strokeWidth="1" strokeDasharray="3 4" />
              <text x={sx(m.v)} y={sy(0) + 14} fill={C.mute} fontSize="11" fontFamily="monospace" textAnchor="middle">{m.lbl}</text>
            </g>
          ))}
          {/* the curve */}
          <polyline points={curve} fill="none" stroke={C.blue} strokeWidth="2" />
          {/* the secant line */}
          <line x1={saX} y1={saY} x2={sbX} y2={sbY} stroke={C.gold} strokeWidth="2.5" strokeDasharray="6 4" />
          <circle cx={saX} cy={saY} r={4} fill={C.gold} stroke={C.ink} strokeWidth="1" />
          <circle cx={sbX} cy={sbY} r={4} fill={C.gold} stroke={C.ink} strokeWidth="1" />
          {/* the tangent at c */}
          <line x1={sx(txL)} y1={sy(tyL)} x2={sx(txR)} y2={sy(tyR)} stroke={tanColor} strokeWidth="2.5" />
          {/* the dragged point c */}
          <circle cx={px} cy={py} r={5} fill={tanColor} stroke={C.ink} strokeWidth="1" />
          <text x={sx(c)} y={sy(0) + 14} fill={tanColor} fontSize="11" fontFamily="monospace" textAnchor="middle">c</text>
          <text x={px + 9} y={py - 8} fill={tanColor} fontSize="12" fontFamily="monospace">f'(c) = {fmt(fld.tangentAtC)}</text>
          <text x={X0 + 4} y={Y0 + 14} fill={C.mute} fontSize="11" fontFamily="monospace">f(x) = x³ · [a,b] = [{fmt(a)}, {fmt(b)}] · secant slope = {fmt(fld.secantSlope)}</text>
        </svg>
        <div style={{ marginTop: 10, padding: "8px 12px", borderRadius: 6, background: C.panel, border: `1px solid ${fld.matched ? C.teal : C.line}`, color: fld.matched ? C.teal : C.mute, fontSize: 12.5 }}>
          secant slope = {fmt(fld.secantSlope)} · f'(c) = 3c² = {fmt(fld.tangentAtC)}. {fld.matched ? <>⚑ <K.T>matched — the tangent at c is parallel to the secant (the MVT point).</K.T></> : (fld.inInterval ? <K.T>c is inside the interval; drag it until the tangent is parallel to the secant.</K.T> : <K.T>c is outside (a, b) — the MVT only guarantees a point strictly inside.</K.T>)} <K.T>Guaranteed c</K.T> = √(m/3) = {fmt(fld.cTheory)}.
        </div>
        <Slider label="left endpoint a" value={a} set={setA} min={-3} max={0} step={0.5} unit="" color={C.gold} onUp={() => event("adjusted", `Set a = ${fmt(a)}`, { response: `secant ${fmt(fld.secantSlope)}` }, C.gold)} />
        <Slider label="right endpoint b" value={b} set={setB} min={0.5} max={3} step={0.5} unit="" color={C.gold} onUp={() => event("adjusted", `Set b = ${fmt(b)}`, { response: `secant ${fmt(fld.secantSlope)}` }, C.gold)} />
        <Slider label="point c" value={c} set={setC} min={-3} max={3} step={0.05} unit="" color={C.teal} onUp={() => event("adjusted", `Dragged to c = ${fmt(c)}`, { response: `f'(c) ${fmt(fld.tangentAtC)}` }, C.teal)} />
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 8, marginTop: 12 }}>
          <StatMeter label="secant slope" v={fld.secantSlope} d={2} color={C.gold} />
          <StatMeter label="f'(c) tangent" v={fld.tangentAtC} d={2} color={tanColor} />
          <StatMeter label="c" v={fld.cValue} d={2} color={C.teal} />
          <StatMeter label="matched?" v={fld.matched ? 1 : 0} d={0} color={fld.matched ? C.teal : C.crimson} />
        </div>
      </>
    );
  }

  window.MvtTutor = K.makeTutor(MvtFig, { moduleLabel: "Mean Value Theorem bench", benchId: "mvt" });
})();
