/**
 * Plays a beep sound using the Web Audio API.
 * @param duration Duration in milliseconds
 * @param frequency Frequency in Hz
 * @param volume Volume (0-1)
 */
export const playBeep = (duration = 200, frequency = 440, volume = 0.5) => {
    try {
        const AudioContext = window.AudioContext || (window as any).webkitAudioContext;
        if (!AudioContext) return;

        const ctx = new AudioContext();
        const osc = ctx.createOscillator();
        const gainUrl = ctx.createGain();

        osc.connect(gainUrl);
        gainUrl.connect(ctx.destination);

        osc.type = 'sine';
        osc.frequency.value = frequency;
        gainUrl.gain.setValueAtTime(volume, ctx.currentTime);
        gainUrl.gain.exponentialRampToValueAtTime(0.01, ctx.currentTime + duration / 1000);

        osc.start(ctx.currentTime);
        osc.stop(ctx.currentTime + duration / 1000);
    } catch (e) {
        console.error('Audio playback failed', e);
    }
};

/**
 * Plays a "Time Up" signal (3 beeps)
 */
export const playTimeUpSignal = async () => {
    // 3 beeps: High-Low-High? Or just 3 Highs.
    // Let's do 3 rapid beeps.
    const now = Date.now();
    playBeep(300, 880, 0.5);
    setTimeout(() => playBeep(300, 880, 0.5), 600);
    setTimeout(() => playBeep(600, 1200, 0.5), 1200);
};
