/**
 * Audio utilities for playing alert sounds
 */

let audioContext;
let gainNode;

/**
 * Initialize audio context (must be called after user interaction)
 */
export function initAudio() {
  if (!audioContext) {
    try {
      audioContext = new (window.AudioContext || window.webkitAudioContext)();
      gainNode = audioContext.createGain();
      gainNode.connect(audioContext.destination);
      gainNode.gain.value = 0.3; // Set volume to 30%
    } catch (error) {
      console.warn('Audio context not available:', error);
    }
  }
}

/**
 * Play alert sound (beep)
 */
export function playAlertSound() {
  try {
    initAudio();
    
    if (!audioContext || audioContext.state === 'closed') {
      return;
    }
    
    // Resume audio context if suspended (required by browser autoplay policies)
    if (audioContext.state === 'suspended') {
      audioContext.resume();
    }
    
    // Create a beep sound (800Hz, 200ms)
    const oscillator = audioContext.createOscillator();
    oscillator.type = 'sine';
    oscillator.frequency.setValueAtTime(800, audioContext.currentTime);
    
    const envelope = audioContext.createGain();
    envelope.gain.setValueAtTime(0.3, audioContext.currentTime);
    envelope.gain.exponentialRampToValueAtTime(0.01, audioContext.currentTime + 0.2);
    
    oscillator.connect(envelope);
    envelope.connect(gainNode);
    
    oscillator.start(audioContext.currentTime);
    oscillator.stop(audioContext.currentTime + 0.2);
  } catch (error) {
    console.warn('Error playing alert sound:', error);
  }
}

/**
 * Play a custom tone
 * @param {number} frequency - Frequency in Hz (default 800)
 * @param {number} duration - Duration in seconds (default 0.2)
 */
export function playTone(frequency = 800, duration = 0.2) {
  try {
    initAudio();
    
    if (!audioContext || audioContext.state === 'closed') {
      return;
    }
    
    if (audioContext.state === 'suspended') {
      audioContext.resume();
    }
    
    const oscillator = audioContext.createOscillator();
    oscillator.type = 'sine';
    oscillator.frequency.setValueAtTime(frequency, audioContext.currentTime);
    
    const envelope = audioContext.createGain();
    envelope.gain.setValueAtTime(0.3, audioContext.currentTime);
    envelope.gain.exponentialRampToValueAtTime(0.01, audioContext.currentTime + duration);
    
    oscillator.connect(envelope);
    envelope.connect(gainNode);
    
    oscillator.start(audioContext.currentTime);
    oscillator.stop(audioContext.currentTime + duration);
  } catch (error) {
    console.warn('Error playing tone:', error);
  }
}

