/*
 * Audio - sons et musique du jeu
 */

const AudioManager = (function () {
    'use strict';

    let isInitialized = false;
    let audioContext = null;

    // sons
    const sounds = {
        bgm: null,
        drop: null,
        alert: null,
        break: null
    };

    // par défaut
    let settings = {
        masterVolume: 0.8,
        sfxVolume: 1.0,
        musicVolume: 0.6,
        sfxEnabled: true,
        musicEnabled: true
    };

    // init
    function init(audioElements = {}) {
        // Charger les paramètres depuis le storage
        if (typeof IceBreakerStorage !== 'undefined') {
            settings = { ...settings, ...IceBreakerStorage.getSettings() };
        }

        // Assigner les éléments audio
        sounds.bgm = audioElements.bgm || document.getElementById('background-audio');
        sounds.drop = audioElements.drop || document.getElementById('sfx-drop');
        sounds.alert = audioElements.alert || document.getElementById('sfx-alert');
        sounds.break = audioElements.break || document.getElementById('sfx-break');

        // Appliquer les volumes initiaux
        applyVolumes();

        // Créer le contexte audio pour le préchargement
        try {
            audioContext = new (window.AudioContext || window.webkitAudioContext)();
        } catch (e) {
            console.warn('AudioContext non supporté');
        }

        isInitialized = true;
    }

    // précharger les sons
    function preload() {
        if (!isInitialized) return;

        Object.entries(sounds).forEach(([name, audio]) => {
            if (audio && name !== 'bgm') {
                audio.volume = 0;
                audio.play().then(() => {
                    audio.pause();
                    audio.currentTime = 0;
                    applyVolumes();
                }).catch(() => { });
            }
        });
    }

    // mettre à jour les volumes
    function applyVolumes() {
        const master = settings.masterVolume;

        if (sounds.bgm) {
            sounds.bgm.volume = settings.musicEnabled ? master * settings.musicVolume : 0;
        }

        ['drop', 'alert', 'break'].forEach(name => {
            if (sounds[name]) {
                sounds[name].volume = settings.sfxEnabled ? master * settings.sfxVolume : 0;
            }
        });
    }

    // jouer un son
    function playSfx(name, volumeMultiplier = 1.0) {
        if (!settings.sfxEnabled || !sounds[name]) return;

        const audio = sounds[name];
        audio.currentTime = 0;
        audio.volume = settings.masterVolume * settings.sfxVolume * volumeMultiplier;
        audio.play().catch(() => { });
    }

    // musique de fond
    function playMusic() {
        if (!settings.musicEnabled || !sounds.bgm) return Promise.resolve();

        sounds.bgm.volume = settings.masterVolume * settings.musicVolume;
        return sounds.bgm.play().catch(e => {
            console.warn('Impossible de jouer la musique:', e);
        });
    }

    // stop musique
    function stopMusic() {
        if (sounds.bgm) {
            sounds.bgm.pause();
            sounds.bgm.currentTime = 0;
        }
    }

    // pause
    function pauseMusic() {
        if (sounds.bgm) {
            sounds.bgm.pause();
        }
    }

    // changer un param
    function setSetting(key, value) {
        if (key in settings) {
            settings[key] = value;
            applyVolumes();

            // Sauvegarder
            if (typeof IceBreakerStorage !== 'undefined') {
                IceBreakerStorage.saveSettings(settings);
            }
        }
    }

    // plusieurs params d'un coup
    function setSettings(newSettings) {
        settings = { ...settings, ...newSettings };
        applyVolumes();

        if (typeof IceBreakerStorage !== 'undefined') {
            IceBreakerStorage.saveSettings(settings);
        }
    }

    // lire params
    function getSettings() {
        return { ...settings };
    }

    // volume principal
    function getMasterVolume() {
        return settings.masterVolume;
    }

    // modifier volume
    function setMasterVolume(value) {
        setSetting('masterVolume', Math.max(0, Math.min(1, value)));
    }

    // on/off musique
    function toggleMusic() {
        settings.musicEnabled = !settings.musicEnabled;
        applyVolumes();

        if (settings.musicEnabled && sounds.bgm) {
            sounds.bgm.play().catch(() => { });
        } else if (sounds.bgm) {
            sounds.bgm.pause();
        }

        if (typeof IceBreakerStorage !== 'undefined') {
            IceBreakerStorage.saveSettings(settings);
        }

        return settings.musicEnabled;
    }

    // on/off sfx
    function toggleSfx() {
        settings.sfxEnabled = !settings.sfxEnabled;
        applyVolumes();

        if (typeof IceBreakerStorage !== 'undefined') {
            IceBreakerStorage.saveSettings(settings);
        }

        return settings.sfxEnabled;
    }

    return {
        init,
        preload,
        playSfx,
        playMusic,
        stopMusic,
        pauseMusic,
        setSetting,
        setSettings,
        getSettings,
        getMasterVolume,
        setMasterVolume,
        toggleMusic,
        toggleSfx
    };
})();

if (typeof module !== 'undefined' && module.exports) {
    module.exports = AudioManager;
}
