/* global React */
// TempoPreview.jsx — Feature 5: BPM slider + animated taal beat preview

const { useState: useStateT, useEffect: useEffectT, useRef: useRefT } = React;

function TempoPreview({ bpm, setBpm, taal, taals }) {
  const [playing, setPlaying] = useStateT(false);
  const [activeBeat, setActiveBeat] = useStateT(-1);
  const ctxRef = useRefT(null);
  const timerRef = useRefT(null);
  const beatRef = useRefT(0);

  const taalDef = taals.find((t) => t.name === taal) || taals[0];
  const totalBeats = taalDef.beats;
  // Build flat beat list with vibhag boundaries
  const beats = [];
  let bIdx = 0;
  taalDef.vibhags.forEach((vSize, vi) => {
    const v = [];
    for (let i = 0; i < vSize; i++) {
      v.push({
        idx: bIdx,
        isSam: bIdx === taalDef.sam,
        isKhali: bIdx === taalDef.khali,
        isVibhagStart: i === 0,
      });
      bIdx++;
    }
    beats.push(v);
  });

  useEffectT(() => {
    if (!playing) {
      if (timerRef.current) clearInterval(timerRef.current);
      setActiveBeat(-1);
      return;
    }
    // Web audio for click
    if (!ctxRef.current) {
      try { ctxRef.current = new (window.AudioContext || window.webkitAudioContext)(); }
      catch (e) { ctxRef.current = null; }
    }
    const ctx = ctxRef.current;
    const tick = (i) => {
      if (!ctx) return;
      const isSam = i === taalDef.sam;
      const isKhali = i === taalDef.khali;
      const o = ctx.createOscillator();
      const g = ctx.createGain();
      o.frequency.value = isSam ? 880 : isKhali ? 380 : 620;
      g.gain.value = isSam ? 0.18 : 0.10;
      o.connect(g); g.connect(ctx.destination);
      const now = ctx.currentTime;
      o.start(now);
      g.gain.exponentialRampToValueAtTime(0.001, now + 0.08);
      o.stop(now + 0.09);
    };
    beatRef.current = 0;
    const interval = 60000 / bpm;
    setActiveBeat(0); tick(0);
    timerRef.current = setInterval(() => {
      beatRef.current = (beatRef.current + 1) % totalBeats;
      setActiveBeat(beatRef.current);
      tick(beatRef.current);
    }, interval);
    return () => clearInterval(timerRef.current);
  }, [playing, bpm, taal]);

  return (
    <div className="tempo">
      <div className="tempo-row">
        <div className="num">{bpm}<span className="unit">BPM</span></div>
        <div className="slider">
          <input type="range" min={40} max={200} value={bpm}
                 onChange={(e) => setBpm(parseInt(e.target.value))} />
        </div>
        <button className={`preview-btn${playing ? ' on' : ''}`}
                onClick={() => setPlaying((p) => !p)}
                title={playing ? 'Stop preview' : 'Preview tempo + taal'}>
          {playing ? (
            <svg width="12" height="12" viewBox="0 0 12 12" fill="currentColor">
              <rect x="3" y="2.5" width="2.2" height="7" rx=".4"/><rect x="6.8" y="2.5" width="2.2" height="7" rx=".4"/>
            </svg>
          ) : (
            <svg width="12" height="12" viewBox="0 0 12 12" fill="currentColor">
              <path d="M3.5 2.5v7a.4.4 0 00.62.33l5.5-3.5a.4.4 0 000-.66l-5.5-3.5A.4.4 0 003.5 2.5z"/>
            </svg>
          )}
        </button>
      </div>

      <div className="beat-grid">
        {beats.map((vibhag, vi) => (
          <div className="vibhag" key={vi}>
            {vibhag.map((b) => (
              <div key={b.idx}
                   className={[
                     'beat',
                     b.isSam ? 'sam' : '',
                     b.isKhali ? 'khali' : '',
                     activeBeat === b.idx ? 'active' : '',
                   ].join(' ').trim()}>
                {b.isSam ? 'X' : b.isKhali ? '0' : (b.idx + 1)}
              </div>
            ))}
          </div>
        ))}
      </div>

      <div className="taal-info">
        <span><b>{taalDef.name}</b></span>
        <span>{taalDef.beats} beats · {taalDef.vibhags.join('+')}</span>
        <span style={{marginLeft: 'auto'}}>X = sam · 0 = khali</span>
      </div>
    </div>
  );
}

window.TempoPreview = TempoPreview;
