/* waveslab.jsx — WavesTutor: the travelling-wave-on-a-string bench. Built on window.BenchKit
   (harness) + window.BenchFields (shared field math), so this file is just the FIGURE.
   compute = window.BenchFields.waves — the SAME function server/benches/waves.js calls, so
   client and server fields are identical by construction. Follows the gas-laws TEMPLATE:
   sliders → BenchFields.fn(state) → report + meters. */
(function () {
  const { useState, useMemo, useEffect } = React;
  const K = window.BenchKit, C = K.C, fmt = K.fmt;
  const TaskStrip = K.TaskStrip, StatMeter = K.StatMeter, Scene3D = K.Scene3D;
  const compute = (s) => window.BenchFields.waves(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 WavesFig({ task, setTask, tasks, report, event, done }) {
    const [freq, setFreq] = useState(2);
    const [wavelength, setWavelength] = useState(0.5);
    const [amplitude, setAmplitude] = useState(0.05);
    const [az, setAz] = useState(40);
    const [el, setEl] = useState(22);
    const fld = useMemo(() => compute({ freq, wavelength, amplitude }), [freq, wavelength, amplitude]);
    useEffect(() => { report(fld); }, [freq, wavelength, amplitude]); // eslint-disable-line

    // world (metres): a travelling-wave RIBBON — the corrugated sheet z = A·sin(k·x), independent of
    // y, so a sinusoidal surface running along x and extruded across y. Drag to orbit; the projector
    // auto-fits via `fit`.
    const k = fld.waveNumber;          // k = 2π/λ
    const A = amplitude;               // amplitude (m)
    const span = 2.5 * wavelength;     // show ~2.5 wavelengths along x
    const Wy = wavelength * 0.6;       // strip half-width across y
    const crest0 = wavelength * 0.25;  // first crest of sin(k·x) at x = λ/4 (z = +A)
    const crest1 = crest0 + wavelength;

    // frame the strip [0,span]×[−Wy,Wy] at z=0 and z=±A
    const fit = [];
    for (const xx of [0, span]) for (const yy of [-Wy, Wy]) { fit.push([xx, yy, 0]); fit.push([xx, yy, A]); fit.push([xx, yy, -A]); }

    const build = (screen) => {
      // the wave surface z = A·sin(k·x), height-coloured + shaded
      let out = K.surfaceMesh3d(screen, (x, y) => A * Math.sin(k * x), 0, span, -Wy, Wy, { n: 36, zmin: -A, zmax: A });
      // baseline (z=0) reference along the strip centre
      out += K.seg3d(screen, [0, 0, 0], [span, 0, 0], C.faint, 0.8, "3 3");
      // mark ONE WAVELENGTH between the first two crests (z = +A)
      out += K.dot3d(screen, [crest0, 0, A], 4, C.gold);
      out += K.dot3d(screen, [crest1, 0, A], 4, C.gold);
      out += K.seg3d(screen, [crest0, 0, A], [crest1, 0, A], C.gold, 2);
      out += K.text3d(screen, [(crest0 + crest1) / 2, 0, A + Math.max(0.02, A * 0.4)], `λ = ${fmt(wavelength)} m`, C.gold, 11);
      // mark AMPLITUDE — vertical from baseline to crest at the strip's front edge
      out += K.seg3d(screen, [crest0, -Wy, 0], [crest0, -Wy, A], C.crimson, 2);
      out += K.dot3d(screen, [crest0, -Wy, A], 3, C.crimson);
      out += K.text3d(screen, [crest0, -Wy, A + Math.max(0.02, A * 0.45)], `A = ${fmt(amplitude)} m`, C.crimson, 11);
      // axis hints
      out += K.seg3d(screen, [0, 0, 0], [span * 1.04, 0, 0], C.faint, 0.8) + K.text3d(screen, [span * 1.08, 0, 0], "x", C.faint, 10);
      out += K.seg3d(screen, [0, 0, 0], [0, Wy * 1.3, 0], C.faint, 0.8) + K.text3d(screen, [0, Wy * 1.45, 0], "y", C.faint, 10);
      out += K.seg3d(screen, [0, 0, 0], [0, 0, A * 1.4], C.faint, 0.8) + K.text3d(screen, [0, 0, A * 1.55], "z", C.faint, 10);
      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: `v ${fmt(fld.speed)} m/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> · v = fλ = {fmt(fld.speed)} m/s</span>
          <span>λ = {fmt(wavelength)} m · f = {fmt(freq)} Hz</span>
        </div>
        <div style={{ marginTop: 10, padding: "8px 12px", borderRadius: 6, background: C.panel, border: `1px solid ${C.line}`, color: C.mute, fontSize: 12.5 }}>
          v = fλ = {fmt(fld.speed)} m/s · T = 1/f = {fmt(fld.period)} s · k = 2π/λ = {fmt(fld.waveNumber)} rad/m. <K.T>Trade f against λ to hold the speed; the medium sets v.</K.T>
        </div>
        <Slider label="frequency f" value={freq} set={setFreq} min={0.5} max={20} step={0.5} unit="Hz" color={C.blue} onUp={() => event("adjusted", `Set f = ${fmt(freq)} Hz`, { response: `v ${fmt(fld.speed)} m/s` }, C.blue)} />
        <Slider label="wavelength λ" value={wavelength} set={setWavelength} min={0.1} max={5} step={0.1} unit="m" color={C.gold} onUp={() => event("adjusted", `Set λ = ${fmt(wavelength)} m`, { response: `v ${fmt(fld.speed)} m/s` }, C.gold)} />
        <Slider label="amplitude A" value={amplitude} set={setAmplitude} min={0.01} max={0.5} step={0.01} unit="m" color={C.crimson} onUp={() => event("adjusted", `Set A = ${fmt(amplitude)} m`, { response: `v ${fmt(fld.speed)} m/s` }, C.crimson)} />
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 8, marginTop: 12 }}>
          <StatMeter label="speed v" v={fld.speed} d={2} unit="m/s" color={C.teal} />
          <StatMeter label="period T" v={fld.period} d={3} unit="s" color={C.amber} />
          <StatMeter label="frequency f" v={fld.freq} d={1} unit="Hz" color={C.blue} />
          <StatMeter label="wavelength λ" v={fld.wavelength} d={2} unit="m" color={C.gold} />
        </div>
      </>
    );
  }

  window.WavesTutor = K.makeTutor(WavesFig, { moduleLabel: "Waves bench", benchId: "waves" });
})();
