// SignalStrip.jsx — three small panels under the stage: song body, frequency layers, dance map.
// Each canvas sits inside a dark "window" (mm-strip__canvas-wrap) on a cream card.

function SignalStrip({ ready }) {
  const waveRef = React.useRef(null);
  const barsRef = React.useRef(null);
  const onsRef  = React.useRef(null);

  React.useEffect(() => {
    const draw = () => {
      drawWave(waveRef.current);
      drawBars(barsRef.current);
      drawOnsets(onsRef.current);
    };
    draw();
    const off = window.MM?.onFrame(() => {
      drawBars(barsRef.current);
    });
    window.addEventListener('resize', draw);
    return () => { off && off(); window.removeEventListener('resize', draw); };
  }, [ready]);

  return (
    <section className="mm-strip">
      <Panel idx="01" title="Song body"        caption="Full-track pressure, post-analysis. Waveform peaks." truth="measured" truthLabel="Measured">
        <canvas ref={waveRef} />
      </Panel>
      <Panel idx="02" title="Frequency layers" caption="Bottom · middle · top, by analyser band level."      truth="measured" truthLabel="Measured">
        <canvas ref={barsRef} />
      </Panel>
      <Panel idx="03" title="Dance map"        caption="Spectral flux peaks — the visible rhythm of the song." truth="modeled" truthLabel="Modeled">
        <canvas ref={onsRef} />
      </Panel>
    </section>
  );
}

function Panel({ idx, title, caption, truth, truthLabel, children }) {
  return (
    <div className="mm-strip__panel">
      <header className="mm-strip__head">
        <h3 className="mm-strip__title"><span>{idx}</span>{title}</h3>
        <span className={"mm-truth mm-truth--" + truth}>{truthLabel}</span>
      </header>
      <div className="mm-strip__canvas-wrap">
        {children}
      </div>
      <p className="mm-strip__note">{caption}</p>
    </div>
  );
}

function fit(c) {
  if (!c) return null;
  const r = c.getBoundingClientRect();
  const d = window.devicePixelRatio || 1;
  const w = Math.max(10, Math.round(r.width * d));
  const h = Math.max(10, Math.round(r.height * d));
  if (c.width !== w || c.height !== h) { c.width = w; c.height = h; }
  return [c.getContext('2d'), w, h, d];
}

function placeholder(g, w, h, d) {
  g.fillStyle = 'rgba(214,201,182,0.55)';
  g.font = `${11*d}px Spectral, serif`;
  g.textAlign = 'center';
  g.fillText('awaiting signal', w/2, h/2);
  g.textAlign = 'start';
}

function drawWave(c) {
  const r = fit(c); if (!r) return; const [g, w, h, d] = r;
  g.clearRect(0, 0, w, h);
  const peaks = window.MM?.peaks || [];
  if (!peaks.length) return placeholder(g, w, h, d);
  g.strokeStyle = '#f8e9d7';
  g.lineWidth = 1*d;
  g.beginPath();
  const mid = h/2;
  for (let i=0; i<peaks.length; i++) {
    const x = i/(peaks.length-1)*w;
    const y = peaks[i]*h*0.42;
    g.moveTo(x, mid-y); g.lineTo(x, mid+y);
  }
  g.stroke();
}

function drawBars(c) {
  const r = fit(c); if (!r) return; const [g, w, h, d] = r;
  g.clearRect(0, 0, w, h);
  const fd = window.MM?.freqData;
  const sa = window.MM?.spectrumAvg;
  const arr = fd ? Array.from(fd).map(v => v/255) : (sa && sa.length ? sa : null);
  if (!arr) return placeholder(g, w, h, d);
  const bands = 48;
  for (let i=0; i<bands; i++) {
    let v = 0;
    const a = Math.floor(i/bands*arr.length), b = Math.floor((i+1)/bands*arr.length);
    for (let k=a; k<b; k++) v = Math.max(v, arr[k] || 0);
    const x = i/bands*w, bh = v*h*0.9;
    g.fillStyle = i < 8 ? '#ff5147' : i < 28 ? '#f8e9d7' : '#50d6ff';
    g.globalAlpha = 0.35 + v*0.65;
    g.fillRect(x, h-bh, (w/bands)-1, bh);
  }
  g.globalAlpha = 1;
}

function drawOnsets(c) {
  const r = fit(c); if (!r) return; const [g, w, h, d] = r;
  g.clearRect(0, 0, w, h);
  const onsets = window.MM?.onsets || [];
  if (!onsets.length) return placeholder(g, w, h, d);
  const mx = Math.max(...onsets, 1);
  g.strokeStyle = '#ffa950';
  for (let i=0; i<onsets.length; i++) {
    const v = onsets[i]/mx;
    if (v < 0.06) continue;
    const x = i/onsets.length*w;
    g.globalAlpha = 0.15 + v*0.85;
    g.beginPath(); g.moveTo(x, h); g.lineTo(x, h - v*h*0.95); g.stroke();
  }
  g.globalAlpha = 1;
}

Object.assign(window, { SignalStrip });
