/* 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;
  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 }}>{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 PendulumFig({ task, setTask, tasks, report, event, done }) {
    const [length, setLength] = useState(1);
    const [gravity, setGravity] = useState(9.81);
    const [amplitudeDeg, setAmplitudeDeg] = useState(10);
    const fld = useMemo(() => compute({ length, gravity, amplitudeDeg }), [length, gravity, amplitudeDeg]);
    useEffect(() => { report(fld); }, [length, gravity, amplitudeDeg]); // eslint-disable-line

    // geometry: pivot at top-center; string length ∝ L (0.1..5 m → pixels); drawn at the
    // amplitude angle θ₀ to one side (static figure at max displacement). An arc traces the swing.
    const PX = 300, PY = 50;
    const strLen = 50 + (length / 5) * 200; // px, 0.1..5 m
    const th = (amplitudeDeg * Math.PI) / 180; // radians from vertical
    const bobX = PX + strLen * Math.sin(th);
    const bobY = PY + strLen * Math.cos(th);
    const vertX = PX, vertY = PY + strLen; // rest position (straight down)
    // mirror bob to show the full swing arc from -θ₀ to +θ₀
    const mirX = PX - strLen * Math.sin(th), mirY = bobY;
    const arc = `M ${fmt(mirX)} ${fmt(mirY)} A ${fmt(strLen)} ${fmt(strLen)} 0 0 1 ${fmt(bobX)} ${fmt(bobY)}`;
    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 320" style={{ width: "100%", background: SVG_BG, border: `1px solid ${C.line}`, borderRadius: 8 }}>
          {/* ceiling / pivot mount */}
          <line x1={PX - 60} y1={PY} x2={PX + 60} y2={PY} stroke={C.faint} strokeWidth="3" />
          <circle cx={PX} cy={PY} r={4} fill={C.faint} />
          {/* rest (vertical) reference */}
          <line x1={PX} y1={PY} x2={vertX} y2={vertY} stroke={C.line} strokeWidth="1.5" strokeDasharray="4 4" />
          {/* swing arc (amplitude) */}
          <path d={arc} fill="none" stroke={C.gold} strokeWidth="1.5" strokeDasharray="3 4" opacity="0.8" />
          {/* string at max displacement */}
          <line x1={PX} y1={PY} x2={bobX} y2={bobY} stroke={C.blue} strokeWidth="2" />
          {/* mirrored string (far side of swing) */}
          <line x1={PX} y1={PY} x2={mirX} y2={mirY} stroke={C.blue} strokeWidth="1" opacity="0.35" />
          {/* bob */}
          <circle cx={bobX} cy={bobY} r={14} fill={C.teal} opacity="0.9" />
          <circle cx={mirX} cy={mirY} r={11} fill={C.teal} opacity="0.22" />
          {/* amplitude label */}
          <text x={PX + 10} y={PY + 34} fill={C.gold} fontSize="11" fontFamily="monospace">θ₀ = {Math.round(amplitudeDeg)}°</text>
          <text x={PX + 6} y={PY - 10} fill={C.mute} fontSize="11" fontFamily="monospace">L = {fmt(length)} m · g = {fmt(gravity)} m/s²</text>
          <text x={300} y={300} textAnchor="middle" fill={C.ink} fontSize="13" fontFamily="monospace">T = {fmt(fld.period)} s · f = {fmt(fld.freq)} Hz</text>
        </svg>
        <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 ? "🐢 a slow, long-period swing." : "Lengthen (↑L) or weaken gravity (↓g) to slow it down."}
        </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" });
})();
