/* trigwavelab.jsx — TrigWaveTutor: the sinusoidal functions bench. Built on window.BenchKit
   (harness) + window.BenchFields (shared field math), so this file is just the FIGURE.
   computeFields = window.BenchFields.trigWave — the SAME function server/benches/trigwave.js
   calls, so client and server fields are identical by construction. Mirrors 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.trigWave(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 TrigWaveFig({ task, setTask, tasks, report, event, done }) {
    const [amplitudeA, setAmplitudeA] = useState(2);
    const [B, setB] = useState(1);
    const [phaseC, setPhaseC] = useState(0);
    const [midlineD, setMidlineD] = useState(1);
    const fld = useMemo(() => compute({ amplitudeA, B, phaseC, midlineD }), [amplitudeA, B, phaseC, midlineD]);
    useEffect(() => { report(fld); }, [amplitudeA, B, phaseC, midlineD]); // eslint-disable-line

    // plot area: x in [0, 4π] across the panel; y in [-10, 10] mapped to a fixed pixel scale.
    const X0 = 60, X1 = 560, AY0 = 30, AY1 = 270;
    const XMAX = 4 * Math.PI, YSPAN = 10; // y range ±10 around 0
    const midY = (AY0 + AY1) / 2;
    const yScale = (AY1 - AY0) / (2 * YSPAN); // px per unit
    const xPix = (x) => X0 + (x / XMAX) * (X1 - X0);
    const yPix = (y) => midY - y * yScale;
    const yOf = (x) => amplitudeA * Math.sin(B * x + phaseC) + midlineD;

    const N = 240;
    let path = "";
    for (let i = 0; i <= N; i++) {
      const x = (i / N) * XMAX;
      path += (i === 0 ? "M" : "L") + xPix(x).toFixed(1) + " " + yPix(yOf(x)).toFixed(1) + " ";
    }

    const amp = fld.amplitude, period = fld.period, mid = fld.midline;
    // one-period span starting at x = 0; amplitude span drawn at the left edge.
    const periodEndX = Math.min(XMAX, period);
    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 300" style={{ width: "100%", background: SVG_BG, border: `1px solid ${C.line}`, borderRadius: 8 }}>
          {/* axes */}
          <line x1={X0} y1={AY0} x2={X0} y2={AY1} stroke={C.faint} strokeWidth="1.5" />
          <line x1={X0} y1={yPix(0)} x2={X1} y2={yPix(0)} stroke={C.faint} strokeWidth="1.5" />
          <text x={X0 - 6} y={yPix(0) - 4} textAnchor="end" fill={C.mute} fontSize="10" fontFamily="monospace">0</text>
          {/* midline (dashed) */}
          <line x1={X0} y1={yPix(mid)} x2={X1} y2={yPix(mid)} stroke={C.gold} strokeWidth="1.5" strokeDasharray="5 4" opacity="0.85" />
          <text x={X1} y={yPix(mid) - 4} textAnchor="end" fill={C.gold} fontSize="10" fontFamily="monospace">midline y = {fmt(mid)}</text>
          {/* the sinusoid */}
          <path d={path} fill="none" stroke={C.teal} strokeWidth="2.5" />
          {/* amplitude span at left: from midline up to peak */}
          <line x1={X0 + 18} y1={yPix(mid)} x2={X0 + 18} y2={yPix(mid + amp)} stroke={C.crimson} strokeWidth="2" />
          <line x1={X0 + 13} y1={yPix(mid + amp)} x2={X0 + 23} y2={yPix(mid + amp)} stroke={C.crimson} strokeWidth="2" />
          <text x={X0 + 26} y={yPix(mid + amp / 2) + 3} fill={C.crimson} fontSize="10" fontFamily="monospace">|A| = {fmt(amp)}</text>
          {/* one-period span along the midline */}
          <line x1={xPix(0)} y1={yPix(mid) + 14} x2={xPix(periodEndX)} y2={yPix(mid) + 14} stroke={C.blue} strokeWidth="2" />
          <line x1={xPix(0)} y1={yPix(mid) + 9} x2={xPix(0)} y2={yPix(mid) + 19} stroke={C.blue} strokeWidth="2" />
          <line x1={xPix(periodEndX)} y1={yPix(mid) + 9} x2={xPix(periodEndX)} y2={yPix(mid) + 19} stroke={C.blue} strokeWidth="2" />
          <text x={(xPix(0) + xPix(periodEndX)) / 2} y={yPix(mid) + 30} textAnchor="middle" fill={C.blue} fontSize="10" fontFamily="monospace">period = {fmt(period)}</text>
          <text x={X0 + 6} y={AY0 + 4} fill={C.mute} fontSize="11" fontFamily="monospace">y = {fmt(amplitudeA)}·sin({fmt(B)}x + {fmt(phaseC)}) + {fmt(midlineD)}</text>
        </svg>
        <div style={{ marginTop: 10, padding: "8px 12px", borderRadius: 6, background: C.panel, border: `1px solid ${C.line}`, color: C.mute, fontSize: 12.5 }}>
          y = A·sin(Bx + C) + D · amplitude = |A| = {fmt(amp)}, period = 2π/|B| = {fmt(period)}, midline = {fmt(mid)}. Stretch A, raise B, slide with C, lift with D.
        </div>
        <Slider label="amplitude A" value={amplitudeA} set={setAmplitudeA} min={-5} max={5} step={0.5} color={C.crimson} onUp={() => event("adjusted", `Set A = ${fmt(amplitudeA)}`, { response: `amp ${fmt(fld.amplitude)}` }, C.crimson)} />
        <Slider label="ang. freq B" value={B} set={setB} min={0.25} max={5} step={0.25} color={C.blue} onUp={() => event("adjusted", `Set B = ${fmt(B)}`, { response: `period ${fmt(fld.period)}` }, C.blue)} />
        <Slider label="phase C" value={phaseC} set={setPhaseC} min={-3.14} max={3.14} step={0.1} color={C.teal} onUp={() => event("adjusted", `Set C = ${fmt(phaseC)}`, { response: `shift ${fmt(fld.phaseShift)}` }, C.teal)} />
        <Slider label="midline D" value={midlineD} set={setMidlineD} min={-5} max={5} step={0.5} color={C.gold} onUp={() => event("adjusted", `Set D = ${fmt(midlineD)}`, { response: `midline ${fmt(fld.midline)}` }, C.gold)} />
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 8, marginTop: 12 }}>
          <StatMeter label="amplitude" v={fld.amplitude} color={C.crimson} />
          <StatMeter label="period" v={fld.period} color={C.blue} />
          <StatMeter label="phase shift" v={fld.phaseShift} color={C.teal} />
          <StatMeter label="midline" v={fld.midline} color={C.gold} />
        </div>
      </>
    );
  }

  window.TrigWaveTutor = K.makeTutor(TrigWaveFig, { moduleLabel: "Sinusoidal functions bench", benchId: "trigwave" });
})();
