/* momentumlab.jsx — MomentumTutor: two carts colliding head-on on a track. Built on
   window.BenchKit (harness) + window.BenchFields (shared field math), so this file is just
   the FIGURE. compute = window.BenchFields.momentum — the SAME function
   server/benches/momentum.js calls, so client and server fields are identical by
   construction. Mirrors the gas-laws lab: controls → BenchFields.fn(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.momentum(s);
  const COLLISIONS = ['elastic', 'inelastic'];

  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 MomentumFig({ task, setTask, tasks, report, event, done }) {
    const [m1, setM1] = useState(2);
    const [v1, setV1] = useState(3);
    const [m2, setM2] = useState(1);
    const [v2, setV2] = useState(-1);
    const [collision, setCollision] = useState("inelastic");
    const fld = useMemo(() => compute({ m1, v1, m2, v2, collision }), [m1, v1, m2, v2, collision]);
    useEffect(() => { report(fld); }, [m1, v1, m2, v2, collision]); // eslint-disable-line

    const t = tasks.find((x) => x.id === task) || tasks[0];
    // track geometry: carts sized ∝ mass, velocity arrows ∝ velocity & direction.
    const X0 = 50, X1 = 550, TY = 150, MID = 300;
    const half = (m) => 12 + (m / 10) * 22;           // half-width ∝ mass
    const h1 = half(m1), h2 = half(m2);
    const c1x = 170, c2x = 430;                       // resting cart centers
    const arrow = (v) => Math.max(-90, Math.min(90, v * 9)); // arrow length ∝ velocity
    const cartTop = TY - 26, cartBot = TY;

    const Cart = (cx, hw, vel, fill, idx) => {
      const a = arrow(vel), ax = cx + (vel >= 0 ? hw : -hw), ay = cartTop - 14;
      return (
        <g key={idx}>
          <rect x={cx - hw} y={cartTop} width={hw * 2} height={26} rx="4" fill={fill} opacity="0.9" stroke={C.line} />
          <circle cx={cx - hw + 7} cy={cartBot} r={5} fill={C.faint} />
          <circle cx={cx + hw - 7} cy={cartBot} r={5} fill={C.faint} />
          <text x={cx} y={cartTop + 17} textAnchor="middle" fill="#06251c" fontSize="11" fontFamily="monospace">m{idx}={fmt(idx === 1 ? m1 : m2)}</text>
          {Math.abs(a) > 2 && <line x1={ax} y1={ay} x2={ax + a} y2={ay} stroke={fill} strokeWidth="3" markerEnd="" />}
          {Math.abs(a) > 2 && <polygon points={`${ax + a},${ay} ${ax + a - (a >= 0 ? 8 : -8)},${ay - 4} ${ax + a - (a >= 0 ? 8 : -8)},${ay + 4}`} fill={fill} />}
          <text x={cx} y={ay - 6} textAnchor="middle" fill={fill} fontSize="11" fontFamily="monospace">v{idx}={fmt(idx === 1 ? v1 : v2)}</text>
        </g>
      );
    };

    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 }}>
          {/* track */}
          <line x1={X0} y1={cartBot + 6} x2={X1} y2={cartBot + 6} stroke={C.faint} strokeWidth="2" />
          {Cart(c1x, h1, v1, C.blue, 1)}
          {Cart(c2x, h2, v2, C.amber, 2)}
          {/* divider */}
          <line x1={MID} y1={40} x2={MID} y2={cartBot + 6} stroke={C.line} strokeWidth="1" strokeDasharray="4 4" />
          <text x={c1x} y={cartBot + 26} textAnchor="middle" fill={C.blue} fontSize="11" fontFamily="monospace">p₁ = {fmt(fld.p1)}</text>
          <text x={c2x} y={cartBot + 26} textAnchor="middle" fill={C.amber} fontSize="11" fontFamily="monospace">p₂ = {fmt(fld.p2)}</text>
          {/* after: common/COM velocity indicator */}
          <text x={MID} y={70} textAnchor="middle" fill={C.mute} fontSize="11" fontFamily="monospace">{fld.isElastic ? "elastic — KE conserved" : "inelastic — carts stick"}</text>
          <text x={MID} y={cartBot + 50} textAnchor="middle" fill={C.teal} fontSize="13" fontFamily="monospace">after: v_COM = {fmt(fld.vFinal)} m/s · p = {fmt(fld.pTotal)} kg·m/s</text>
          {/* COM velocity arrow */}
          {Math.abs(arrow(fld.vFinal)) > 2 && (
            <g>
              <line x1={MID} y1={cartBot + 64} x2={MID + arrow(fld.vFinal)} y2={cartBot + 64} stroke={C.teal} strokeWidth="3" />
              <polygon points={`${MID + arrow(fld.vFinal)},${cartBot + 64} ${MID + arrow(fld.vFinal) - (fld.vFinal >= 0 ? 8 : -8)},${cartBot + 60} ${MID + arrow(fld.vFinal) - (fld.vFinal >= 0 ? 8 : -8)},${cartBot + 68}`} fill={C.teal} />
            </g>
          )}
        </svg>
        <div style={{ marginTop: 10, padding: "8px 12px", borderRadius: 6, background: C.panel, border: `1px solid ${C.line}`, color: C.mute, fontSize: 12.5, fontFamily: "monospace" }}>
          Σp = {fmt(fld.pTotal)} kg·m/s is conserved. {fld.isElastic ? "Elastic: no kinetic energy lost." : `Inelastic: ${fmt(fld.keLost)} J of kinetic energy lost.`}
        </div>
        <Slider label="mass m₁" value={m1} set={setM1} min={0.5} max={10} step={0.5} unit="kg" color={C.blue} onUp={() => event("adjusted", `Set m₁ = ${fmt(m1)} kg`, { response: `p ${fmt(fld.pTotal)} kg·m/s` }, C.blue)} />
        <Slider label="velocity v₁" value={v1} set={setV1} min={-10} max={10} step={0.5} unit="m/s" color={C.blue} onUp={() => event("adjusted", `Set v₁ = ${fmt(v1)} m/s`, { response: `p ${fmt(fld.pTotal)} kg·m/s` }, C.blue)} />
        <Slider label="mass m₂" value={m2} set={setM2} min={0.5} max={10} step={0.5} unit="kg" color={C.amber} onUp={() => event("adjusted", `Set m₂ = ${fmt(m2)} kg`, { response: `p ${fmt(fld.pTotal)} kg·m/s` }, C.amber)} />
        <Slider label="velocity v₂" value={v2} set={setV2} min={-10} max={10} step={0.5} unit="m/s" color={C.amber} onUp={() => event("adjusted", `Set v₂ = ${fmt(v2)} m/s`, { response: `p ${fmt(fld.pTotal)} kg·m/s` }, C.amber)} />
        <div style={{ display: "flex", gap: 6, marginTop: 10 }}>
          {COLLISIONS.map((cv) => (
            <button key={cv} onClick={() => { setCollision(cv); event("selected", `Collision: ${cv}`, { response: `KE lost ${fmt(compute({ m1, v1, m2, v2, collision: cv }).keLost)} J` }, C.crimson); }}
              style={{ flex: 1, padding: "9px 8px", borderRadius: 6, cursor: "pointer", fontFamily: "monospace", fontSize: 13,
                background: collision === cv ? C.crimson : C.panel2, color: collision === cv ? "#fff" : C.mute, fontWeight: collision === cv ? 600 : 400,
                border: `1px solid ${collision === cv ? C.crimson : C.line}` }}>{cv}</button>
          ))}
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 8, marginTop: 12 }}>
          <StatMeter label="total p" v={fld.pTotal} d={2} unit="kg·m/s" color={C.teal} />
          <StatMeter label="v_COM" v={fld.vFinal} d={2} unit="m/s" color={C.blue} />
          <StatMeter label="KE lost" v={fld.keLost} d={2} unit="J" color={fld.keLost > 0.05 ? C.crimson : C.faint} />
          <StatMeter label="p₁" v={fld.p1} d={2} unit="kg·m/s" color={C.amber} />
        </div>
      </>
    );
  }

  window.MomentumTutor = K.makeTutor(MomentumFig, { moduleLabel: "Momentum bench", benchId: "momentum" });
})();
