// Sistema de audio sintetizado con Web Audio API.
// Tonos generados con osciladores, sin archivos.
const audioSystem = {
    ctx: null,
    muted: false,

    getContext() {
        if (!this.ctx) {
            try {
                const AudioContext = window.AudioContext || window.webkitAudioContext;
                if (AudioContext) this.ctx = new AudioContext();
            } catch (e) {}
        }
        return this.ctx;
    },

    resume() {
        const ctx = this.getContext();
        if (!ctx) return;
        if (ctx.state === 'suspended') {
            ctx.resume().catch(() => {});
        }
    },

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

        try {
            const osc = ctx.createOscillator();
            const gain = ctx.createGain();
            osc.type = type;
            const t = ctx.currentTime + 0.05 + startTime;
            osc.frequency.setValueAtTime(freq, t);
            gain.gain.setValueAtTime(0, t);
            gain.gain.linearRampToValueAtTime(vol, t + 0.05);
            gain.gain.linearRampToValueAtTime(0.001, t + duration);
            osc.connect(gain);
            gain.connect(ctx.destination);
            osc.start(t);
            osc.stop(t + duration + 0.1);
        } catch (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);
    },

    playAdvance() {
        this.playTone(660, 'triangle', 0.12, 0, 0.08);
        this.playTone(550, 'triangle', 0.12, 0.08, 0.08);
        this.playTone(440, 'triangle', 0.18, 0.16, 0.08);
    },

    playWin() {
        this.playTone(523, 'sine', 0.2, 0, 0.1);
        this.playTone(659, 'sine', 0.2, 0.12, 0.1);
        this.playTone(784, 'sine', 0.2, 0.24, 0.1);
        this.playTone(1046, 'sine', 0.5, 0.36, 0.1);
    },

    playAlert() {
        this.playTone(880, 'triangle', 0.1, 0, 0.08);
        this.playTone(1108, 'triangle', 0.12, 0.1, 0.08);
    },

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

    setMuted(muted) {
        this.muted = !!muted;
    }
};
