import { useEffect, useRef } from 'react';
import { Progress } from '@mantine/core';

interface VUMeterProps {
  analyser: AnalyserNode | null;
  color?: string;
  id?: string;
}

/**
 * 🎚️ Componente VUmetro visual
 * Mide energía RMS del audio en tiempo real desde un AnalyserNode.
 */
export function VUMeter({ analyser, color = 'green', id }: VUMeterProps) {
  const valueRef = useRef(0);
  const barRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (!analyser) return;

    const dataArray = new Uint8Array(analyser.fftSize);
    const update = () => {
      analyser.getByteTimeDomainData(dataArray);
      const rms =
        Math.sqrt(
          dataArray.reduce((acc, val) => acc + (val - 128) ** 2, 0) /
            dataArray.length
        ) / 128;

      // Escala sensible y suavizada
      const level = Math.min(rms * 180, 100);
      valueRef.current = level;

      if (barRef.current) {
        barRef.current.style.width = `${level}%`;
        barRef.current.style.backgroundColor =
          level < 30 ? '#4caf50' : level < 70 ? '#ffeb3b' : '#f44336';
      }

      requestAnimationFrame(update);
    };

    update();
  }, [analyser]);

  return (
    <div
      style={{
        width: '100%',
        height: '8px',
        background: '#222',
        borderRadius: '4px',
        overflow: 'hidden',
        position: 'relative',
      }}
    >
      <div
        ref={barRef}
        style={{
          height: '100%',
          width: '0%',
          transition: 'width 0.1s linear',
          background: color,
        }}
      />
    </div>
  );
}
