// 音效管理器类
class SoundEffectManager {
    constructor() {
        this.audioContext = null;
        this.enabled = ConfigManager.getBoolConfig('soundEffectsEnabled', true); // 默认开启
        this.volume = ConfigManager.getConfig('soundEffectsVolume', 0.8); // 默认音量 80%
        this.soundEffects = []; // 存储音效列表
        this.selectedSound = 'ciallo.ogg'; // 当前选中的音效
        this.soundEffectsLoaded = false; // 音效列表是否已加载
    }

    // 初始化音频上下文（需要用户交互）
    initAudioContext() {
        if (!this.audioContext) {
            try {
                this.audioContext = new (window.AudioContext || window.webkitAudioContext)();
                console.log('音频上下文初始化成功');
                return true;
            } catch (error) {
                console.warn('音频上下文初始化失败:', error);
                return false;
            }
        }
        return true;
    }

    // 预加载音效
    async preloadSound(soundName, soundUrl) {
        try {
            // 使用getSoundUrl函数确保音效URL正确
            // 音效文件现在存储在resource/audio目录中
            let actualUrl = soundUrl;
            if (!soundUrl.startsWith(window.location.origin)) {
                actualUrl = getSoundUrl(soundName);
            }

            // 简单预加载，不使用缓存
            const audio = new Audio(actualUrl);
            return new Promise((resolve, reject) => {
                audio.oncanplaythrough = () => {
                    resolve(true);
                };
                audio.onerror = () => {
                    reject(new Error(`音效预加载失败 ${soundName}`));
                };
                // 设置超时
                setTimeout(() => {
                    reject(new Error(`音效预加载超时 ${soundName}`));
                }, 8000);
                audio.load();
            });
        } catch (error) {
            console.warn(`预加载音效 ${soundName} 失败:`, error);
            return false;
        }
    }

    // 加载音效列表
    async loadSoundEffects() {
        try {
            const response = await fetch(getApiUrl('/data/audio.json'));
            const data = await response.json();
            this.soundEffects = data.soundEffects || [];
            this.soundEffectsLoaded = true;
            
            // 从配置中恢复选中的音效
            const savedSound = ConfigManager.getConfig('selectedSoundEffect', 'ciallo.ogg');
            if (this.soundEffects.some(effect => effect.file === savedSound)) {
                this.selectedSound = savedSound;
            }
            
            console.log('音效列表加载成功:', this.soundEffects);
            return true;
        } catch (error) {
            console.error('音效列表加载失败:', error);
            return false;
        }
    }

    // 获取音效列表
    getSoundEffects() {
        return this.soundEffects;
    }

    // 设置选中的音效
    setSelectedSound(soundFile) {
        this.selectedSound = soundFile;
        ConfigManager.setConfig('selectedSoundEffect', soundFile);
        console.log(`选中音效已更新为: ${soundFile}`);
    }

    // 获取选中的音效
    getSelectedSound() {
        return this.selectedSound;
    }

    // 播放音效
    async playSound(soundName, soundUrl, volume = null) {
        if (!this.enabled) return false;

        // 如果没有指定音量，使用管理器设置的音量
        const finalVolume = volume !== null ? volume : this.volume;

        try {
            // 检查是否是特殊音效，使用选中的音效
            if (soundName === 'click' && soundUrl.includes('click.mp3')) {
                if (this.soundEffectsLoaded && this.selectedSound) {
                    // 使用getSoundUrl函数获取正确的音效路径
                    soundUrl = getSoundUrl(this.selectedSound);
                } else {
                    soundUrl = getSoundUrl('ciallo.ogg');
                }
                console.log(`播放特殊音效: ${soundUrl}`);
            }
            
            const audio = new Audio(soundUrl);
            audio.volume = finalVolume;
            await audio.play();
            return true;
        } catch (error) {
            console.warn(`音效播放失败 ${soundName}:`, error);
            return false;
        }
    }

    // 设置是否启用音效
    setEnabled(enabled) {
        this.enabled = enabled;
        ConfigManager.setBoolConfig('soundEffectsEnabled', enabled);
    }

    // 设置音效音量
    setVolume(volume) {
        // 确保音量在0-1 范围内
        this.volume = Math.max(0, Math.min(1, volume));
        ConfigManager.setConfig('soundEffectsVolume', this.volume);
        console.log('音效音量已设置为:', this.volume);
    }

    // 获取当前音量
    getVolume() {
        return this.volume;
    }
}