// Live waveform — responds to real mic input via AudioEngine.getLiveLevel().
// Flat/static when mic is silent; animates only when sound is detected.

function Waveform({ bars = 48, height = 48, color = '#E75002', color2 = '#3FA890', speed = 1 }) {
  const containerRef = React.useRef(null);

  React.useEffect(() => {
    let rafId, t = 0;

    function update() {
      const AE = window.AudioEngine;
      const level = AE && AE.getLiveLevel ? AE.getLiveLevel() : 0;
      t++;

      if (containerRef.current) {
        const divs = containerRef.current.children;
        const tNorm = t / 10;
        const silent = level < 0.08;

        for (let i = 0; i < divs.length; i++) {
          let h;
          if (silent) {
            h = height * 0.05;
          } else {
            const a = Math.sin(tNorm * speed + i * 0.35) * 0.5 + 0.5;
            const b = Math.sin(tNorm * speed * 1.7 + i * 0.12) * 0.5 + 0.5;
            const c = Math.sin(tNorm * speed * 0.6 + i * 0.7) * 0.5 + 0.5;
            const v = (a * 0.5 + b * 0.3 + c * 0.2) * level * 3;
            h = Math.max(height * 0.05, Math.min(height, v * height));
          }
          divs[i].style.height = h + 'px';
          divs[i].style.opacity = 0.35 + (h / height) * 0.65;
        }
      }

      rafId = requestAnimationFrame(update);
    }

    rafId = requestAnimationFrame(update);
    return () => cancelAnimationFrame(rafId);
  }, [bars, height, speed]);

  return (
    <div ref={containerRef} style={{ display: 'flex', alignItems: 'center', gap: 2, height, width: '100%' }}>
      {Array.from({ length: bars }).map((_, i) => (
        <div key={i} style={{
          flex: 1,
          height: height * 0.05,
          minWidth: 2,
          background: `linear-gradient(180deg, ${color}, ${color2})`,
          borderRadius: 2,
          opacity: 0.35,
        }} />
      ))}
    </div>
  );
}

window.Waveform = Waveform;
