import { useEffect, useRef } from 'react';

const BAR_COUNT = 24;

export function VoiceWaveform({
  analyser,
  active,
}: {
  analyser: AnalyserNode | null;
  active: boolean;
}) {
  const barsRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (!analyser || !active || !barsRef.current) return undefined;

    const bars = Array.from(barsRef.current.children) as HTMLElement[];
    const data = new Uint8Array(analyser.frequencyBinCount);
    let frame = 0;

    const tick = () => {
      analyser.getByteFrequencyData(data);
      const step = Math.max(1, Math.floor(data.length / BAR_COUNT));
      for (let i = 0; i < BAR_COUNT; i += 1) {
        const sample = data[i * step] ?? 0;
        const height = Math.max(12, Math.round((sample / 255) * 100));
        bars[i]?.style.setProperty('--voice-bar-height', `${height}%`);
      }
      frame = window.requestAnimationFrame(tick);
    };

    tick();
    return () => window.cancelAnimationFrame(frame);
  }, [analyser, active]);

  return (
    <div
      className={`voice-waveform${active ? ' voice-waveform-active' : ''}${active && !analyser ? ' voice-waveform-idle' : ''}`}
      aria-hidden="true"
      ref={barsRef}
    >
      {Array.from({ length: BAR_COUNT }, (_, index) => (
        <span key={index} className="voice-waveform-bar" />
      ))}
    </div>
  );
}
