// Scope.jsx — the oscilloscope. A neon waveform on a canvas that reacts to
// transport (livelier when playing). Capped, reduced-motion aware.
function Scope({ playing }) {
  const ref = React.useRef(null);
  const playRef = React.useRef(playing);
  playRef.current = playing;
  React.useEffect(() => {
    const canvas = ref.current;
    const ctx = canvas.getContext('2d');
    let raf, t = 0, running = true;
    const reduce = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
    function resize() {
      const dpr = Math.min(window.devicePixelRatio || 1, 2);
      canvas.width = canvas.offsetWidth * dpr;
      canvas.height = canvas.offsetHeight * dpr;
      ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
    }
    resize();
    window.addEventListener('resize', resize);
    function draw() {
      const w = canvas.offsetWidth, h = canvas.offsetHeight, mid = h / 2;
      ctx.clearRect(0, 0, w, h);
      // baseline grid
      ctx.strokeStyle = 'rgba(255,255,255,0.05)';
      ctx.lineWidth = 1;
      for (let x = 0; x <= w; x += 28) { ctx.beginPath(); ctx.moveTo(x, 0); ctx.lineTo(x, h); ctx.stroke(); }
      ctx.beginPath(); ctx.moveTo(0, mid); ctx.lineTo(w, mid); ctx.stroke();
      const amp = playRef.current ? h * 0.32 : h * 0.06;
      const drawWave = (col, freq, phase, blur) => {
        ctx.beginPath();
        for (let x = 0; x <= w; x++) {
          const env = Math.sin((x / w) * Math.PI);
          const y = mid + Math.sin(x * freq + t * 0.05 + phase) * amp * env
                        + Math.sin(x * freq * 2.3 + t * 0.08) * amp * 0.25 * env;
          x === 0 ? ctx.moveTo(x, y) : ctx.lineTo(x, y);
        }
        ctx.strokeStyle = col; ctx.lineWidth = 2; ctx.shadowColor = col; ctx.shadowBlur = blur;
        ctx.stroke(); ctx.shadowBlur = 0;
      };
      drawWave('rgba(0,255,255,0.9)', 0.045, 0, 12);
      drawWave('rgba(255,0,170,0.6)', 0.03, 1.6, 10);
      if (!reduce) t += playRef.current ? 1.6 : 0.4;
    }
    function loop() { if (running) { draw(); raf = requestAnimationFrame(loop); } }
    loop();
    const onVis = () => { running = !document.hidden; if (running) loop(); else cancelAnimationFrame(raf); };
    document.addEventListener('visibilitychange', onVis);
    return () => { cancelAnimationFrame(raf); window.removeEventListener('resize', resize); document.removeEventListener('visibilitychange', onVis); };
  }, []);
  return (
    <div className="scope">
      <div className="scope-label t-eyebrow">// scope {playing ? '· ● live' : '· idle'}</div>
      <canvas ref={ref} className="scope-canvas" aria-hidden="true" />
    </div>
  );
}
window.Scope = Scope;
