import { useEffect, useRef } from 'react';

interface Props {
  bars?: number;
  color?: string;
  className?: string;
}

export default function Waveform({
  bars = 64,
  color = 'var(--color-cyan)',
  className = '',
}: Props) {
  const ref = useRef<SVGSVGElement>(null);
  const barRefs = useRef<(SVGRectElement | null)[]>([]);

  useEffect(() => {
    if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) return;

    let rafId: number;
    const start = performance.now();

    const tick = (now: number) => {
      const t = (now - start) / 1000;
      barRefs.current.forEach((bar, i) => {
        if (!bar) return;
        // Multi-sine combination → pulse organique
        const x = i / bars;
        const amp =
          0.5 +
          0.25 * Math.sin(t * 1.7 + x * 8) +
          0.15 * Math.sin(t * 3.1 + x * 16) +
          0.1 * Math.sin(t * 0.8 + x * 4);
        const h = Math.max(0.08, Math.min(1, amp));
        bar.setAttribute('transform', `scale(1, ${h})`);
      });
      rafId = requestAnimationFrame(tick);
    };
    rafId = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(rafId);
  }, [bars]);

  const barWidth = 100 / bars;
  const gap = barWidth * 0.3;
  const rectWidth = barWidth - gap;

  return (
    <svg
      ref={ref}
      viewBox="0 0 100 20"
      preserveAspectRatio="none"
      className={className}
      aria-hidden="true"
    >
      {Array.from({ length: bars }).map((_, i) => (
        <g key={i} transform={`translate(${i * barWidth + gap / 2}, 10)`}>
          <rect
            ref={(el) => {
              barRefs.current[i] = el;
            }}
            x={0}
            y={-10}
            width={rectWidth}
            height={20}
            fill={color}
            style={{
              transformBox: 'fill-box',
              transformOrigin: 'center',
            }}
          />
        </g>
      ))}
    </svg>
  );
}
