"use client";

import { useEffect, useState, useRef } from "react";
import { Volume2, VolumeX } from "lucide-react";

export default function SoundManager() {
  const [isPlaying, setIsPlaying] = useState(false);
  const audioCtxRef = useRef<AudioContext | null>(null);
  
  // Refs for oscillators and gain nodes to control the drone
  const droneNodesRef = useRef<{
    oscillators: OscillatorNode[];
    gains: GainNode[];
    lfo: OscillatorNode | null;
  }>({ oscillators: [], gains: [], lfo: null });

  // Web Audio Tanpura Drone Synthesizer
  const startDrone = () => {
    if (!audioCtxRef.current) {
      audioCtxRef.current = new (window.AudioContext || (window as any).webkitAudioContext)();
    }
    
    const ctx = audioCtxRef.current;
    if (ctx.state === "suspended") {
      ctx.resume();
    }

    const masterGain = ctx.createGain();
    masterGain.gain.setValueAtTime(0.08, ctx.currentTime); // Soft, unobtrusive volume
    masterGain.connect(ctx.destination);

    // Warm Lowpass filter to simulate wood resonance
    const filter = ctx.createBiquadFilter();
    filter.type = "lowpass";
    filter.frequency.setValueAtTime(350, ctx.currentTime);
    filter.connect(masterGain);

    const freqs = [65.41, 98.0, 130.81, 196.0]; // C2, G2, C3, G3 - traditional Indian scale tuning
    const oscillators: OscillatorNode[] = [];
    const gains: GainNode[] = [];

    // Create harmonically rich drone oscillators
    freqs.forEach((freq, idx) => {
      const osc = ctx.createOscillator();
      // Mix sawtooth and triangle for rich but warm string timbre
      osc.type = idx % 2 === 0 ? "triangle" : "sine";
      osc.frequency.setValueAtTime(freq, ctx.currentTime);
      
      const gain = ctx.createGain();
      // Stagger volumes
      gain.gain.setValueAtTime(idx === 0 ? 0.4 : 0.25, ctx.currentTime);

      osc.connect(gain);
      gain.connect(filter);
      
      osc.start();
      oscillators.push(osc);
      gains.push(gain);
    });

    // Create LFO (Low Frequency Oscillator) to model the rhythmic strumming (swells) of a tanpura
    const lfo = ctx.createOscillator();
    lfo.frequency.setValueAtTime(0.12, ctx.currentTime); // Very slow swell (every 8 seconds)
    
    const lfoGain = ctx.createGain();
    lfoGain.gain.setValueAtTime(0.15, ctx.currentTime);

    lfo.connect(lfoGain);
    // Connect LFO to modulate filter cutoff frequency to create organic breathing texture
    lfoGain.connect(filter.frequency);
    lfo.start();

    droneNodesRef.current = { oscillators, gains, lfo };
  };

  const stopDrone = () => {
    const { oscillators, lfo } = droneNodesRef.current;
    oscillators.forEach((osc) => {
      try { osc.stop(); } catch (e) {}
    });
    if (lfo) {
      try { lfo.stop(); } catch (e) {}
    }
    droneNodesRef.current = { oscillators: [], gains: [], lfo: null };
  };

  // Synthesize a traditional temple bell chime
  const playBellChime = () => {
    if (!audioCtxRef.current || audioCtxRef.current.state === "suspended") return;
    
    const ctx = audioCtxRef.current;
    const now = ctx.currentTime;
    
    // Bell tones consist of a fundamental frequency and inharmonic overtones
    const frequencies = [600, 770, 930, 1200, 1540]; 
    const bellGain = ctx.createGain();
    bellGain.gain.setValueAtTime(0, now);
    // Sudden attack, long delay
    bellGain.gain.linearRampToValueAtTime(0.04, now + 0.05);
    bellGain.gain.exponentialRampToValueAtTime(0.0001, now + 4.5);
    bellGain.connect(ctx.destination);

    frequencies.forEach((f, index) => {
      const osc = ctx.createOscillator();
      osc.type = "sine";
      osc.frequency.setValueAtTime(f, now);
      // Detune slightly for realistic metallic resonance
      osc.detune.setValueAtTime(index * 4, now);
      osc.connect(bellGain);
      osc.start(now);
      osc.stop(now + 5.0);
    });
  };

  const toggleSound = () => {
    if (isPlaying) {
      stopDrone();
      setIsPlaying(false);
    } else {
      startDrone();
      setIsPlaying(true);
      // Play introductory bell chime
      setTimeout(() => {
        playBellChime();
      }, 500);
    }
  };

  // Periodically ring temple bell (every 22 seconds) for ambient realism
  useEffect(() => {
    if (!isPlaying) return;
    
    const interval = setInterval(() => {
      playBellChime();
    }, 22000);

    return () => clearInterval(interval);
  }, [isPlaying]);

  // Stop sound on unmount
  useEffect(() => {
    return () => {
      stopDrone();
    };
  }, []);

  return (
    <div className="fixed bottom-6 right-6 z-[999] flex items-center gap-3">
      {/* Soundwave animation */}
      {isPlaying && (
        <div className="hidden sm:flex items-end gap-[3px] h-4 px-2">
          <div className="w-[3px] bg-maroon h-full rounded-full animate-[soundwave_1.2s_ease-in-out_infinite_alternate]" style={{ animationDelay: "0.1s" }} />
          <div className="w-[3px] bg-maroon h-2/3 rounded-full animate-[soundwave_0.8s_ease-in-out_infinite_alternate]" style={{ animationDelay: "0.4s" }} />
          <div className="w-[3px] bg-maroon h-4/5 rounded-full animate-[soundwave_1.0s_ease-in-out_infinite_alternate]" style={{ animationDelay: "0.2s" }} />
          <div className="w-[3px] bg-maroon h-1/2 rounded-full animate-[soundwave_0.7s_ease-in-out_infinite_alternate]" style={{ animationDelay: "0.6s" }} />
        </div>
      )}
      
      {/* Sound Toggle Button */}
      <button
        onClick={toggleSound}
        className="clickable w-12 h-12 rounded-full bg-white border border-maroon/20 flex items-center justify-center text-maroon hover:text-white hover:border-maroon-dark shadow-md hover:shadow-lg transition-all duration-300 relative group overflow-hidden"
        aria-label={isPlaying ? "Mute Background Music" : "Play Background Music"}
      >
        <span className="absolute inset-0 bg-maroon translate-y-full group-hover:translate-y-0 transition-transform duration-300 ease-out z-0" />
        <span className="relative z-10">
          {isPlaying ? <Volume2 size={20} className="animate-pulse" /> : <VolumeX size={20} />}
        </span>
      </button>

      {/* Tailwind Soundwave Keyframes definition embedded in a style block */}
      <style jsx global>{`
        @keyframes soundwave {
          0% { height: 4px; }
          100% { height: 16px; }
        }
      `}</style>
    </div>
  );
}
