const audioSystem = {
    ctx: null,
    muted: false,

    // Lazy initialization of AudioContext
    getContext() {
        if (!this.ctx) {
            try {
                const AudioContext = window.AudioContext || window.webkitAudioContext;
                this.ctx = new AudioContext();
                
                // Listener para depurar cambios de estado
                this.ctx.onstatechange = () => {
                    console.log('[AUDIO] State changed to:', this.ctx.state);
                };

                console.log('[AUDIO] AudioContext created. State:', this.ctx.state);
            } catch (e) {
                console.error('[AUDIO] API not supported', e);
            }
        }
        return this.ctx;
    },

    // Method to resume AudioContext (must be called from a user gesture)
    resume() {
        const ctx = this.getContext();
        if (!ctx) return;

        console.log('[AUDIO] resume() called. Current state:', ctx.state);

        if (ctx.state === 'suspended') {
            ctx.resume().then(() => {
                console.log('[AUDIO] Context resumed successfully. State:', ctx.state);
            }).catch(e => {
                console.error('[AUDIO] Resume failed:', e);
            });
        }
    },

    playTone(freq, type, duration, startTime = 0, vol = 0.1) {
        if (this.muted) return;
        
        const ctx = this.getContext();
        if (!ctx) return;

        // Intentar reanudar si está suspendido (fallback)
        if (ctx.state === 'suspended') {
            console.warn('[AUDIO] Trying to play tone while suspended. Calling resume()...');
            this.resume();
        }

        try {
            const osc = ctx.createOscillator();
            const gain = ctx.createGain();

            osc.type = type;
            
            // Programar ligeramente en el futuro
            const t = ctx.currentTime + 0.05;
            
            // Debug: verificar si el tiempo avanza
            // console.log(`[AUDIO] Playing tone. Freq: ${freq}, Time: ${ctx.currentTime.toFixed(2)} -> ${t.toFixed(2)}`);

            osc.frequency.setValueAtTime(freq, t);
            
            // Envelope ADSR simplificado
            gain.gain.setValueAtTime(0, t);
            gain.gain.linearRampToValueAtTime(vol, t + 0.05); // Attack
            gain.gain.linearRampToValueAtTime(0.001, t + duration); // Decay

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

            osc.start(t);
            osc.stop(t + duration + 0.1); 
        } catch (e) {
            console.warn('[AUDIO] Play tone error', e);
        }
    },

    playClick() {
        this.playTone(800, 'sine', 0.1, 0, 0.1);
    },

    playBuy() {
        this.playTone(1200, 'square', 0.1, 0, 0.05);
        this.playTone(1600, 'square', 0.1, 0.1, 0.05);
    },

    playError() {
        this.playTone(150, 'sawtooth', 0.2, 0, 0.1);
    },
    
    playUnlock() {
        this.playTone(440, 'sine', 0.3, 0, 0.1);
        this.playTone(554, 'sine', 0.3, 0.1, 0.1);
        this.playTone(659, 'sine', 0.5, 0.2, 0.1);
    },

    toggleMute() {
        this.resume();
        this.muted = !this.muted;
        return this.muted;
    }
};

// Global toggle function bound to the button
function toggleAudio() {
    const isMuted = audioSystem.toggleMute();
    const btn = document.getElementById('audio-toggle');
    if (btn) {
        btn.textContent = isMuted ? '🔇' : '🔊';
        if (!isMuted) audioSystem.playClick();
    }
    // Actualizar icono en menú móvil si existe la función
    if (typeof updateMobileAudioIcon === 'function') {
        updateMobileAudioIcon();
    }
}