/* vectorslab.jsx — VectorsTutor: the two-vectors bench. Built on window.BenchKit
   (harness) + window.BenchFields (shared field math), so this file is just the FIGURE.
   compute = window.BenchFields.vectors — the SAME function server/benches/vectors.js
   calls, so client and server fields are identical by construction. Two 2-D vectors are
   added tip-to-tail; sliders → BenchFields.vectors(state) → report + meters. */
(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.vectors(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 VectorsFig({ task, setTask, tasks, report, event, done }) {
    const [ax, setAx] = useState(3);
    const [ay, setAy] = useState(0);
    const [bx, setBx] = useState(0);
    const [by, setBy] = useState(4);
    const fld = useMemo(() => compute({ ax, ay, bx, by }), [ax, ay, bx, by]);
    useEffect(() => { report(fld); }, [ax, ay, bx, by]); // eslint-disable-line

    // axes through the centre; 1 unit = SCALE px. y grows upward (SVG y is flipped).
    const CX = 300, CY = 155, SCALE = 11, AXR = 270, AYR = 130;
    const px = (vx) => CX + vx * SCALE;
    const py = (vy) => CY - vy * SCALE;

    // tip-to-tail: a from origin, b from tip of a, r from origin to final tip.
    const aTip = { x: px(ax), y: py(ay) };
    const bTip = { x: px(ax + bx), y: py(ay + by) };
    const O = { x: px(0), y: py(0) };

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

    return (
      <>
        <TaskStrip tasks={tasks} cur={task} setCur={setTask} done={done} goal={t && t.goal} />
        <svg viewBox="0 0 600 310" style={{ width: "100%", background: SVG_BG, border: `1px solid ${C.line}`, borderRadius: 8 }}>
          <defs>
            <marker id="vah-a" markerWidth="9" markerHeight="9" refX="6" refY="3" orient="auto"><path d="M0,0 L6,3 L0,6 z" fill={C.blue} /></marker>
            <marker id="vah-b" markerWidth="9" markerHeight="9" refX="6" refY="3" orient="auto"><path d="M0,0 L6,3 L0,6 z" fill={C.gold} /></marker>
            <marker id="vah-r" markerWidth="10" markerHeight="10" refX="6" refY="3" orient="auto"><path d="M0,0 L6,3 L0,6 z" fill={C.crimson} /></marker>
          </defs>
          {/* axes */}
          <line x1={CX - AXR} y1={CY} x2={CX + AXR} y2={CY} stroke={C.faint} strokeWidth="1.5" />
          <line x1={CX} y1={CY - AYR} x2={CX} y2={CY + AYR} stroke={C.faint} strokeWidth="1.5" />
          <text x={CX + AXR - 4} y={CY - 6} fill={C.mute} fontSize="11" fontFamily="monospace" textAnchor="end">x</text>
          <text x={CX + 6} y={CY - AYR + 10} fill={C.mute} fontSize="11" fontFamily="monospace">y</text>
          {/* vector a (origin → tip) */}
          <line x1={O.x} y1={O.y} x2={aTip.x} y2={aTip.y} stroke={C.blue} strokeWidth="3" markerEnd="url(#vah-a)" />
          <text x={(O.x + aTip.x) / 2} y={(O.y + aTip.y) / 2 - 6} fill={C.blue} fontSize="12" fontFamily="monospace">a</text>
          {/* vector b (tip of a → final tip), tip-to-tail */}
          <line x1={aTip.x} y1={aTip.y} x2={bTip.x} y2={bTip.y} stroke={C.gold} strokeWidth="3" markerEnd="url(#vah-b)" />
          <text x={(aTip.x + bTip.x) / 2 + 6} y={(aTip.y + bTip.y) / 2} fill={C.gold} fontSize="12" fontFamily="monospace">b</text>
          {/* resultant r (origin → final tip) */}
          <line x1={O.x} y1={O.y} x2={bTip.x} y2={bTip.y} stroke={C.crimson} strokeWidth="3" markerEnd="url(#vah-r)" />
          <text x={(O.x + bTip.x) / 2 - 10} y={(O.y + bTip.y) / 2 + 14} fill={C.crimson} fontSize="12" fontFamily="monospace">r</text>
          <text x={12} y={20} fill={C.ink} fontSize="12" fontFamily="monospace">a = ({fmt(ax)}, {fmt(ay)}) · b = ({fmt(bx)}, {fmt(by)})</text>
          <text x={12} y={300} fill={C.crimson} fontSize="12" fontFamily="monospace">|r| = {fmt(fld.resultMag)} · θ = {fmt(fld.resultAngle)}°{fld.isPerpendicular ? " · a ⊥ b" : ""}</text>
        </svg>
        <div style={{ marginTop: 10, padding: "8px 12px", borderRadius: 6, background: C.panel, border: `1px solid ${fld.isPerpendicular ? C.teal : C.line}`, color: fld.isPerpendicular ? C.teal : C.mute, fontSize: 12.5 }}>
          r = a + b = ({fmt(fld.rx)}, {fmt(fld.ry)}) · a·b = {fmt(fld.dotProduct)}. {fld.isPerpendicular ? "✓ a·b = 0 — the vectors are perpendicular." : "Tip-to-tail: b starts where a ends; r runs from the origin to the final tip."}
        </div>
        <Slider label="a · x" value={ax} set={setAx} min={-10} max={10} step={1} color={C.blue} onUp={() => event("adjusted", `Set aₓ = ${fmt(ax)}`, { response: `|r| ${fmt(fld.resultMag)}` }, C.blue)} />
        <Slider label="a · y" value={ay} set={setAy} min={-10} max={10} step={1} color={C.blue} onUp={() => event("adjusted", `Set a_y = ${fmt(ay)}`, { response: `|r| ${fmt(fld.resultMag)}` }, C.blue)} />
        <Slider label="b · x" value={bx} set={setBx} min={-10} max={10} step={1} color={C.gold} onUp={() => event("adjusted", `Set bₓ = ${fmt(bx)}`, { response: `|r| ${fmt(fld.resultMag)}` }, C.gold)} />
        <Slider label="b · y" value={by} set={setBy} min={-10} max={10} step={1} color={C.gold} onUp={() => event("adjusted", `Set b_y = ${fmt(by)}`, { response: `|r| ${fmt(fld.resultMag)}` }, C.gold)} />
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 8, marginTop: 12 }}>
          <StatMeter label="|r|" v={fld.resultMag} d={2} color={C.crimson} />
          <StatMeter label="direction θ" v={fld.resultAngle} d={1} unit="°" color={C.amber} />
          <StatMeter label="a·b" v={fld.dotProduct} d={2} color={fld.isPerpendicular ? C.teal : C.blue} />
          <StatMeter label="rₓ" v={fld.rx} d={2} color={C.teal} />
        </div>
      </>
    );
  }

  window.VectorsTutor = K.makeTutor(VectorsFig, { moduleLabel: "Vectors bench", benchId: "vectors" });
})();
