'use client';
import { useEffect, useRef } from 'react';

interface Props {
  isActive: boolean;
  audioLevel?: number; // 0-100
  color?: string;
  barCount?: number;
}

export default function WaveAnimation({ isActive, audioLevel = 0, color = '#6366f1', barCount = 20 }: Props) {
  const barsRef = useRef<(HTMLDivElement | null)[]>([]);

  useEffect(() => {
    if (!isActive) {
      barsRef.current.forEach(bar => {
        if (bar) bar.style.transform = 'scaleY(0.15)';
      });
      return;
    }

    const interval = setInterval(() => {
      barsRef.current.forEach((bar, i) => {
        if (!bar) return;
        // Create organic wave pattern
        const base = audioLevel / 100;
        const wave = Math.sin(Date.now() / 200 + i * 0.5) * 0.3;
        const noise = Math.random() * 0.2;
        const scale = Math.max(0.15, Math.min(1, base * 0.7 + wave + noise));
        bar.style.transform = `scaleY(${scale})`;
      });
    }, 50);

    return () => clearInterval(interval);
  }, [isActive, audioLevel]);

  const gradientColors = [
    '#6366f1', '#7c3aed', '#8b5cf6', '#a855f7', '#c026d3',
    '#db2777', '#ec4899', '#db2777', '#c026d3', '#a855f7',
    '#8b5cf6', '#7c3aed', '#6366f1', '#4f46e5', '#4338ca',
    '#6366f1', '#7c3aed', '#a855f7', '#c026d3', '#6366f1',
  ];

  return (
    <div className="flex items-end justify-center gap-0.5" style={{ height: '40px' }}>
      {Array.from({ length: barCount }).map((_, i) => (
        <div
          key={i}
          ref={el => { barsRef.current[i] = el; }}
          className="wave-bar"
          style={{
            height: '40px',
            background: gradientColors[i % gradientColors.length],
            animationDelay: `${i * 0.05}s`,
            animationDuration: `${0.4 + Math.random() * 0.3}s`,
            transform: 'scaleY(0.15)',
            transition: 'transform 0.05s ease',
          }}
        />
      ))}
    </div>
  );
}
