// studio-app.jsx — composes the sequencer surface + drives the playhead clock.
// The playhead now triggers real Web Audio (audio.js) per active lane.
function StudioApp() {
  const [grid, setGrid] = React.useState(() => JSON.parse(JSON.stringify(STUDIO_SEED)));
  const [playing, setPlaying] = React.useState(false);
  const [step, setStep] = React.useState(0);
  const [bpm, setBpm] = React.useState(124);
  const [swing, setSwing] = React.useState(18);
  const gridRef = React.useRef(grid);
  gridRef.current = grid;

  React.useEffect(() => {
    if (!playing) return;
    if (window.STUDIO_AUDIO) STUDIO_AUDIO.ensure();
    const fire = (s) => {
      if (!window.STUDIO_AUDIO) return;
      const g = gridRef.current;
      STUDIO_LANES.forEach(l => { if (g[l.id] && g[l.id][s]) STUDIO_AUDIO.trigger(l.id); });
    };
    let raf, last = performance.now(), acc = 0, cur = step;
    fire(cur); // sound the step we start on
    const tick = () => {
      const now = performance.now();
      const dt = now - last; last = now;
      const base = 60000 / bpm / 4; // 16th-note ms
      const swung = (cur % 2 === 0) ? base * (1 + swing / 200) : base * (1 - swing / 200);
      acc += dt;
      if (acc >= swung) { acc -= swung; cur = (cur + 1) % STEPS; setStep(cur); fire(cur); }
      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [playing, bpm, swing]);

  const stop = () => { setPlaying(false); setStep(0); };

  return (
    <div className="st-root">
      <Transport playing={playing} onToggle={() => setPlaying(p => !p)} onStop={stop}
        bpm={bpm} setBpm={setBpm} swing={swing} setSwing={setSwing} />
      <div className="st-body">
        <div className="st-main">
          <Scope playing={playing} />
          <Sequencer grid={grid} setGrid={setGrid} step={step} playing={playing} />
          <div className="st-hint t-mono">
            Tipp die Zellen, bau dir einen Beat. ▶ startet den Floor (mit Ton). 🌀 ist das freaky Instrument.
          </div>
        </div>
        <Mixer playing={playing} step={step} grid={grid} />
      </div>
    </div>
  );
}
ReactDOM.createRoot(document.getElementById('root')).render(<StudioApp />);
