'use client';

/**
 * useHybridAudioAnalysis - Audio frequency analysis for hybrid player.
 *
 * Simplified version of useAudioAnalysis that works directly with AnalyserNode
 * instead of SharedWebAudioContext.
 */

import { useCallback, useEffect, useRef, useState } from 'react';

import type { AudioLevels } from '../effects';

export function useHybridAudioAnalysis(
  analyser: AnalyserNode | null,
  isPlaying: boolean
): AudioLevels {
  const [levels, setLevels] = useState<AudioLevels>({ bass: 0, mid: 0, high: 0, overall: 0 });
  const animationRef = useRef<number | null>(null);
  const dataArrayRef = useRef<Uint8Array<ArrayBuffer> | null>(null);

  const cleanup = useCallback(() => {
    if (animationRef.current) {
      cancelAnimationFrame(animationRef.current);
      animationRef.current = null;
    }
  }, []);

  // Initialize data array when analyser is available
  useEffect(() => {
    if (analyser && !dataArrayRef.current) {
      dataArrayRef.current = new Uint8Array(analyser.frequencyBinCount) as Uint8Array<ArrayBuffer>;
    }
  }, [analyser]);

  // Animation loop
  useEffect(() => {
    if (!isPlaying || !analyser || !dataArrayRef.current) {
      cleanup();
      // Smooth fade out when stopped
      setLevels((prev) => ({
        bass: prev.bass * 0.95 < 0.01 ? 0 : prev.bass * 0.95,
        mid: prev.mid * 0.95 < 0.01 ? 0 : prev.mid * 0.95,
        high: prev.high * 0.95 < 0.01 ? 0 : prev.high * 0.95,
        overall: prev.overall * 0.95 < 0.01 ? 0 : prev.overall * 0.95,
      }));
      return;
    }

    const dataArray = dataArrayRef.current;

    const animate = () => {
      analyser.getByteFrequencyData(dataArray);
      const binCount = dataArray.length;

      // Bass (0-15% of frequency range)
      const bassEnd = Math.floor(binCount * 0.15);
      let bassSum = 0;
      for (let i = 0; i < bassEnd; i++) bassSum += dataArray[i];
      const bass = bassSum / bassEnd / 255;

      // Mids (15-50% of frequency range)
      const midStart = bassEnd;
      const midEnd = Math.floor(binCount * 0.5);
      let midSum = 0;
      for (let i = midStart; i < midEnd; i++) midSum += dataArray[i];
      const mid = midSum / (midEnd - midStart) / 255;

      // Highs (50-100% of frequency range)
      const highStart = midEnd;
      let highSum = 0;
      for (let i = highStart; i < binCount; i++) highSum += dataArray[i];
      const high = highSum / (binCount - highStart) / 255;

      // Overall
      let totalSum = 0;
      for (let i = 0; i < binCount; i++) totalSum += dataArray[i];
      const overall = totalSum / binCount / 255;

      // Smooth with lerp for natural feel
      setLevels((prev) => ({
        bass: prev.bass * 0.7 + bass * 0.3,
        mid: prev.mid * 0.7 + mid * 0.3,
        high: prev.high * 0.7 + high * 0.3,
        overall: prev.overall * 0.7 + overall * 0.3,
      }));

      animationRef.current = requestAnimationFrame(animate);
    };

    animationRef.current = requestAnimationFrame(animate);
    return cleanup;
  }, [analyser, isPlaying, cleanup]);

  return levels;
}
