/* relatedrateslab.jsx — RelatedRatesTutor: the related-rates bench. Built on window.BenchKit
   (harness) + window.BenchFields (shared field math), so this file is just the FIGURE.
   computeFields = window.BenchFields.relatedrates — the SAME function server/benches/relatedrates.js
   calls, so client and server fields are identical by construction. The learner sets the ladder
   length L, the foot distance x and the foot slide rate dx/dt; a right triangle (wall, floor,
   ladder) makes the constraint x² + y² = L² visible and the top races as the foot nears the wall. */
(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.relatedrates(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 RelatedRatesFig({ task, setTask, tasks, report, event, done }) {
    const [L, setL] = useState(10);
    const [x, setX] = useState(6);
    const [dxdt, setDxdt] = useState(1);
    const fld = useMemo(() => compute({ L, x, dxdt }), [L, x, dxdt]);
    useEffect(() => { report(fld); }, [L, x, dxdt]); // eslint-disable-line

    // scene window: math coords (x along floor, y up the wall) → svg px. The wall sits at the
    // left, the floor along the bottom; scale by the largest possible ladder length.
    const X0 = 80, X1 = 560, Y0 = 30, Y1 = 270;
    const SPAN = 13.5; // a touch above max L so the longest ladder still fits
    const sx = (xm) => X0 + (xm / SPAN) * (X1 - X0);
    const sy = (ym) => Y1 - (ym / SPAN) * (Y1 - Y0);

    const y = fld.wallHeight;
    const footPx = sx(x), footPy = sy(0);
    const topPx = sx(0), topPy = sy(y);

    const t = tasks.find((q) => q.id === task) || tasks[0];
    const ladderColor = fld.topFalling ? C.crimson : C.teal;

    // right-angle marker at the wall/floor corner (origin)
    const m = 12;
    const cornerX = sx(0), cornerY = sy(0);

    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 }}>
          {/* wall (vertical) + floor (horizontal) */}
          <line x1={sx(0)} y1={Y0} x2={sx(0)} y2={Y1} stroke={C.faint} strokeWidth="2" />
          <line x1={sx(0)} y1={sy(0)} x2={X1} y2={sy(0)} stroke={C.faint} strokeWidth="2" />
          {/* right-angle marker at the corner */}
          <path d={`M ${cornerX + m} ${cornerY} L ${cornerX + m} ${cornerY - m} L ${cornerX} ${cornerY - m}`} fill="none" stroke={C.line} strokeWidth="1" />
          {/* the ladder (hypotenuse) */}
          <line x1={footPx} y1={footPy} x2={topPx} y2={topPy} stroke={ladderColor} strokeWidth="3" />
          {/* foot + top markers */}
          <circle cx={footPx} cy={footPy} r={5} fill={ladderColor} stroke={C.ink} strokeWidth="1" />
          <circle cx={topPx} cy={topPy} r={5} fill={ladderColor} stroke={C.ink} strokeWidth="1" />
          {/* labels */}
          <text x={(footPx + cornerX) / 2} y={footPy + 16} fill={C.mute} fontSize="11" fontFamily="monospace" textAnchor="middle">x = {fmt(x)}</text>
          <text x={topPx - 6} y={(topPy + cornerY) / 2} fill={C.mute} fontSize="11" fontFamily="monospace" textAnchor="end">y = {fmt(y)}</text>
          <text x={(footPx + topPx) / 2 + 6} y={(footPy + topPy) / 2 - 6} fill={ladderColor} fontSize="12" fontFamily="monospace">L = {fmt(L)} · {fmt(fld.ladderAngle)}°</text>
          <text x={X0 + 4} y={Y0 + 14} fill={C.mute} fontSize="11" fontFamily="monospace">x² + y² = L² · dy/dt = −(x/y)·dx/dt = {fmt(fld.dydt)}</text>
        </svg>
        <div style={{ marginTop: 10, padding: "8px 12px", borderRadius: 6, background: C.panel, border: `1px solid ${fld.topFalling ? C.crimson : C.teal}`, color: fld.topFalling ? C.crimson : C.teal, fontSize: 12.5 }}>
          dy/dt = {fmt(fld.dydt)} — {fld.topFalling ? <K.T>the top is falling.</K.T> : <K.T>the top is rising.</K.T>} <span style={{ color: C.mute }}><K.T>foot speed</K.T> {fmt(fld.footSpeed)} · <K.T>top speed</K.T> {fmt(fld.topSpeed)}.</span>
        </div>
        <Slider label="ladder length L" value={L} set={setL} min={6} max={13} step={0.5} unit="" color={C.gold} onUp={() => event("adjusted", `Set L = ${fmt(L)}`, { response: `dy/dt ${fmt(fld.dydt)}` }, C.gold)} />
        <Slider label="foot distance x" value={x} set={setX} min={0.5} max={12} step={0.5} unit="" color={C.blue} onUp={() => event("adjusted", `Set x = ${fmt(x)}`, { response: `dy/dt ${fmt(fld.dydt)}` }, C.blue)} />
        <Slider label="slide rate dx/dt" value={dxdt} set={setDxdt} min={-3} max={3} step={0.1} unit="" color={C.teal} onUp={() => event("adjusted", `Set dx/dt = ${fmt(dxdt)}`, { response: `top speed ${fmt(fld.topSpeed)}` }, C.teal)} />
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 8, marginTop: 12 }}>
          <StatMeter label="wall height y" v={fld.wallHeight} d={2} color={C.blue} />
          <StatMeter label="dy/dt" v={fld.dydt} d={2} color={ladderColor} />
          <StatMeter label="top speed" v={fld.topSpeed} d={2} color={C.amber} />
          <StatMeter label="angle°" v={fld.ladderAngle} d={1} color={C.teal} />
        </div>
      </>
    );
  }

  window.RelatedRatesTutor = K.makeTutor(RelatedRatesFig, { moduleLabel: "Related Rates bench", benchId: "relatedrates" });
})();
