import React, { useEffect, useRef } from 'react';

interface AudioVibePlayerProps {
  isPlaying: boolean;
}

export const AudioVibePlayer: React.FC<AudioVibePlayerProps> = ({ isPlaying }) => {
  const audioCtxRef = useRef<AudioContext | null>(null);
  const oscillatorRefs = useRef<any[]>([]);
  const gainNodeRef = useRef<GainNode | null>(null);

  useEffect(() => {
    if (isPlaying) {
      try {
        const AudioContextClass = window.AudioContext || (window as any).webkitAudioContext;
        if (!AudioContextClass) return;

        const ctx = new AudioContextClass();
        audioCtxRef.current = ctx;

        // Master Gain
        const masterGain = ctx.createGain();
        masterGain.gain.setValueAtTime(0.08, ctx.currentTime);
        masterGain.connect(ctx.destination);
        gainNodeRef.current = masterGain;

        // Chords frequencies (Sunset Deep Lounge in D-Minor: D3, F3, A3, C4)
        const chordFreqs = [146.83, 174.61, 220.0, 261.63, 329.63];

        chordFreqs.forEach((freq, i) => {
          const osc = ctx.createOscillator();
          const gain = ctx.createGain();
          const panner = ctx.createStereoPanner ? ctx.createStereoPanner() : null;

          osc.type = i % 2 === 0 ? 'sine' : 'triangle';
          osc.frequency.setValueAtTime(freq, ctx.currentTime);

          // Subtle LFO modulation for ocean-like swell
          const lfo = ctx.createOscillator();
          lfo.frequency.setValueAtTime(0.15 + i * 0.05, ctx.currentTime);
          const lfoGain = ctx.createGain();
          lfoGain.gain.setValueAtTime(0.04, ctx.currentTime);
          lfo.connect(lfoGain.gain);
          lfo.start();

          gain.gain.setValueAtTime(0.03 / (i + 1), ctx.currentTime);

          if (panner) {
            panner.pan.setValueAtTime((i - 2) * 0.35, ctx.currentTime);
            osc.connect(gain);
            gain.connect(panner);
            panner.connect(masterGain);
          } else {
            osc.connect(gain);
            gain.connect(masterGain);
          }

          osc.start();
          oscillatorRefs.current.push(osc, lfo);
        });

      } catch (e) {
        console.warn("Audio synthesis error:", e);
      }
    } else {
      if (audioCtxRef.current) {
        try {
          audioCtxRef.current.close();
        } catch (e) {}
        audioCtxRef.current = null;
        oscillatorRefs.current = [];
      }
    }

    return () => {
      if (audioCtxRef.current) {
        try {
          audioCtxRef.current.close();
        } catch (e) {}
      }
    };
  }, [isPlaying]);

  return null;
};
