/* pendulumlab.jsx — PendulumTutor: the simple-pendulum bench. Built on window.BenchKit
   (harness) + window.BenchFields (shared field math), so this file is just the FIGURE.
   computeFields = window.BenchFields.pendulum — the SAME function server/benches/pendulum.js
   calls, so client and server fields are identical by construction. Follows the single-figure
   lab TEMPLATE (public/gaslawslab.jsx): sliders → 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, Scene3D = K.Scene3D;
  const compute = (s) => window.BenchFields.pendulum(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 PendulumFig({ task, setTask, tasks, report, event, done }) {
    const [length, setLength] = useState(1);
    const [gravity, setGravity] = useState(9.81);
    const [amplitudeDeg, setAmplitudeDeg] = useState(10);
    const [az, setAz] = useState(24);
    const [el, setEl] = useState(14);
    const fld = useMemo(() => compute({ length, gravity, amplitudeDeg }), [length, gravity, amplitudeDeg]);
    useEffect(() => { report(fld); }, [length, gravity, amplitudeDeg]); // eslint-disable-line

    // world: z is UP; the pivot sits at the origin on the ceiling (z=0) and the bob hangs
    // DOWN, swinging in the x–z plane. amp is the release angle from vertical.
    const Lw = Math.max(1.5, Math.min(3.5, length * 0.7)); // string length in world units
    const amp = (amplitudeDeg * Math.PI) / 180;
    const B = [Lw * Math.sin(amp), 0, -Lw * Math.cos(amp)]; // bob at the rightmost swing extreme

    const fit = [
      [0, 0, 0],
      [Lw * Math.sin(amp), 0, -Lw * Math.cos(amp)],
      [-Lw * Math.sin(amp), 0, -Lw * Math.cos(amp)],
      [0, 0, -Lw],
      [-0.9, -0.9, 0], [0.9, -0.9, 0], [0.9, 0.9, 0], [-0.9, 0.9, 0],
    ];

    const build = (screen) => {
      let out = "";
      // ceiling square around the pivot at z=0 with a couple of hatch strokes
      out += K.poly3d(screen, [[-0.9, -0.9, 0], [0.9, -0.9, 0], [0.9, 0.9, 0], [-0.9, 0.9, 0]], "rgba(159,182,198,0.10)", C.faint, 1);
      for (let i = -0.6; i <= 0.6; i += 0.4) out += K.seg3d(screen, [i, -0.9, 0], [i - 0.22, -0.9, 0.3], C.faint, 0.8);
      // vertical dashed reference straight down
      out += K.seg3d(screen, [0, 0, 0], [0, 0, -Lw], C.faint, 0.8, "3 3");
      // swing arc: the path the bob traces from −amp..+amp
      const N = 40, pts = [];
      for (let i = 0; i <= N; i++) { const a = -amp + (i / N) * (2 * amp); pts.push(screen([Lw * Math.sin(a), 0, -Lw * Math.cos(a)])); }
      out += `<polyline points="${pts.map((p) => `${p.x.toFixed(1)},${p.y.toFixed(1)}`).join(" ")}" fill="none" stroke="${C.teal}" stroke-width="1.6" stroke-linejoin="round" stroke-linecap="round" opacity="0.7"/>`;
      // the string (rod) at the current amplitude
      out += K.seg3d(screen, [0, 0, 0], B, C.mute, 2);
      // pivot dot and bob
      out += K.dot3d(screen, [0, 0, 0], 4, C.faint);
      out += K.dot3d(screen, B, 7, C.gold);
      // angle label near the pivot
      out += K.text3d(screen, [0.25, 0, -0.5], `θ = ${Math.round(amplitudeDeg)}°`, C.gold, 11);
      return out;
    };

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

    return (
      <>
        <TaskStrip tasks={tasks} cur={task} setCur={setTask} done={done} goal={t && t.goal} />
        <Scene3D az={az} el={el} setAz={setAz} setEl={setEl} fit={fit} width={600} height={320} build={build}
          onUp={() => event("rotated", `View az ${Math.round(az)}° · el ${Math.round(el)}°`, { response: `T ${fmt(fld.period)} s` }, C.blue)} />
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginTop: 8, fontSize: 11.5, color: C.faint, fontFamily: "monospace" }}>
          <span><K.T>drag to orbit</K.T> · L = {fmt(length)} m · g = {fmt(gravity)} m/s²</span>
          <span>T = 2π√(L/g) = {fmt(fld.period)} s</span>
        </div>
        <div style={{ marginTop: 10, padding: "8px 12px", borderRadius: 6, background: C.panel, border: `1px solid ${fld.longPeriod ? C.amber : C.line}`, color: fld.longPeriod ? C.amber : C.mute, fontSize: 12.5 }}>
          T = 2π√(L/g) = {fmt(fld.period)} s. {fld.longPeriod ? <>🐢 <K.T>a slow, long-period swing.</K.T></> : <K.T>Lengthen (↑L) or weaken gravity (↓g) to slow it down.</K.T>}
        </div>
        <Slider label="length L" value={length} set={setLength} min={0.1} max={5} step={0.1} unit="m" color={C.blue} onUp={() => event("adjusted", `Set L = ${fmt(length)} m`, { response: `T ${fmt(fld.period)} s` }, C.blue)} />
        <Slider label="gravity g" value={gravity} set={setGravity} min={1.6} max={25} step={0.1} unit="m/s²" color={C.crimson} onUp={() => event("adjusted", `Set g = ${fmt(gravity)} m/s²`, { response: `T ${fmt(fld.period)} s` }, C.crimson)} />
        <Slider label="amplitude θ₀" value={amplitudeDeg} set={setAmplitudeDeg} min={1} max={30} step={1} unit="°" color={C.gold} onUp={() => event("adjusted", `Set θ₀ = ${Math.round(amplitudeDeg)}°`, { response: `T ${fmt(fld.period)} s` }, C.gold)} />
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 8, marginTop: 12 }}>
          <StatMeter label="period T" v={fld.period} d={2} unit="s" color={fld.longPeriod ? C.amber : C.teal} />
          <StatMeter label="frequency f" v={fld.freq} d={2} unit="Hz" color={C.blue} />
          <StatMeter label="max speed" v={fld.maxSpeed} d={2} unit="m/s" color={C.crimson} />
          <StatMeter label="ω" v={fld.omega} d={2} unit="rad/s" color={C.gold} />
        </div>
      </>
    );
  }

  window.PendulumTutor = K.makeTutor(PendulumFig, { moduleLabel: "Pendulum bench", benchId: "pendulum" });
})();
