// 初始化低复杂度模块
// 全局变量
// accessLogger 已在 index.html 中声明
// cialloEffectManager 已在initManager中声明为全局变量
// lastBackground变量已在index.html中声明

// 初始化低复杂度模块
function initLowComplexityModules() {
    // 初始化日志系统
    accessLogger = new AccessLogger();

    // Ciallo 特效管理器将在initManager中初始化

    // 恢复用户保存的背景 - 已移至initManager中处理

    // 初始化鼠标跟随背景
    initMouseFollowBackground();

    // 初始化音效管理器
    initializeSoundEffects();
}

// 初始化音效系统
function initializeSoundEffects() {
    // 检查是否已初始化
    if (window.soundEffectManager) {
        console.log('音效管理器已初始化，跳过重复初始化');
        return;
    }

    // 创建全局音效管理器实例
    window.soundEffectManager = new SoundEffectManager();

    // 加载音效列表并预加载所有音效
    window.soundEffectManager.loadSoundEffects()
        .then(async success => {
            if (success) {
                const soundEffects = window.soundEffectManager.getSoundEffects();
                // 预加载所有音效
                for (const effect of soundEffects) {
                    try {
                        await window.soundEffectManager.preloadSound(effect.file, getSoundUrl(effect.file));
                        console.log(`音效 ${effect.name} 预加载成功`);
                    } catch (error) {
                        console.warn(`音效 ${effect.name} 预加载失败:`, error);
                    }
                }
                console.log('所有音效预加载完成');
            } else {
                console.warn('音效列表加载失败，使用默认音效');
                // 降级处理：预加载默认音效
                window.soundEffectManager.preloadSound('click', getSoundUrl('ciallo.ogg'))
                    .catch(error => {
                        console.error('默认音效预加载错误:', error);
                    });
            }
        })
        .catch(error => {
            console.error('音效列表加载错误:', error);
            // 降级处理：预加载默认音效
            window.soundEffectManager.preloadSound('click', getSoundUrl('ciallo.ogg'))
                .catch(error => {
                    console.error('默认音效预加载错误:', error);
                });
        });

    // 添加全局点击事件监听
    document.addEventListener('click', function(event) {
        // 检查点击的是否是特效相关的按钮，如果是则不播放音效和特效（避免重复播放）
        const clickedElement = event.target;

        // 排除点击效果相关的按钮和控件
        if (clickedElement.id === 'soundToggle' ||
            clickedElement.id === 'cialloToggle' ||
            clickedElement.id === 'soundVolumeSlider' ||
            clickedElement.onclick && clickedElement.onclick.toString().includes('toggleSoundEffects') ||
            clickedElement.onclick && clickedElement.onclick.toString().includes('toggleCialloEffect') ||
            clickedElement.onclick && clickedElement.onclick.toString().includes('preloadSoundEffects') ||
            clickedElement.onclick && clickedElement.onclick.toString().includes('clearSoundCache') ||
            clickedElement.oninput && clickedElement.oninput.toString().includes('updateSoundVolume')) {
            return;
        }

        // 排除点击效果按钮的父容器
        const soundControls = document.getElementById('soundControls');
        if (soundControls && soundControls.contains(clickedElement)) {
            return;
        }

        // 播放点击音效
        const selectedSound = window.soundEffectManager.getSelectedSound();
        if (selectedSound) {
            window.soundEffectManager.playSound('click', getSoundUrl(selectedSound));
        } else {
            window.soundEffectManager.playSound('click', getSoundUrl('ciallo.ogg'));
        }

        // 显示 Ciallo 特效
        if (window.cialloEffectManager && window.cialloEffectManager.isEnabled()) {
            window.cialloEffectManager.handleClick(event);
        }
    }, { passive: true });
}

// 切换音效开关
window.toggleSoundEffects = function() {
    if (!window.soundEffectManager) return;

    const enabled = !window.soundEffectManager.enabled;
    window.soundEffectManager.setEnabled(enabled);

    updateSoundToggleUI();
    updateSoundStatus();

    // 如果开启，播放测试音效
    if (enabled) {
        setTimeout(() => {
            const selectedSound = window.soundEffectManager.getSelectedSound();
            if (selectedSound) {
                window.soundEffectManager.playSound('click', getSoundUrl(selectedSound));
            } else {
                window.soundEffectManager.playSound('click', getSoundUrl('ciallo.ogg'));
            }
        }, 100);
    }
};

// 切换 Ciallo 特效开关
window.toggleCialloEffect = function() {
    if (!cialloEffectManager) return;
    
    cialloEffectManager.toggleEnabled();
    
    // 更新UI
    const cialloToggle = document.getElementById('cialloToggle');
    if (cialloToggle) {
        cialloToggle.textContent = cialloEffectManager.isEnabled() ? '关闭特效' : '开启特效';
        cialloToggle.style.backgroundColor = cialloEffectManager.isEnabled() ? '#ff6b6b' : '#4ecdc4';
    }
    
    // 如果开启，播放测试特效
    if (cialloEffectManager.isEnabled()) {
        setTimeout(() => {
            cialloEffectManager.triggerCialloEffect();
        }, 100);
    }
};

// 更新音效开关UI
function updateSoundToggleUI() {
    const toggle = document.getElementById('soundToggle');
    if (!toggle || !window.soundEffectManager) return;

    if (window.soundEffectManager.enabled) {
        toggle.style.background = 'linear-gradient(135deg, #00b09b, #96c93d)';
        toggle.style.color = 'white';
        toggle.style.borderColor = 'transparent';
        toggle.textContent = '已开启';
    } else {
        toggle.style.background = 'rgba(40, 40, 40, 0.8)';
        toggle.style.color = 'rgba(255, 255, 255, 0.7)';
        toggle.style.borderColor = 'rgba(255, 255, 255, 0.2)';
        toggle.textContent = '已关闭';
    }
}

// 更新音效状态显示
window.updateSoundStatus = async function() {
    const statusDiv = document.getElementById('soundStatus');
    if (!statusDiv || !window.soundEffectManager) return;

    statusDiv.textContent = '音效系统已启用';
    statusDiv.style.color = 'rgba(76, 175, 80, 0.8)';
};

// 切换 Ciallo 特效开关
window.toggleCialloEffect = function() {
    if (!cialloEffectManager) return;

    const enabled = !cialloEffectManager.enabled;
    cialloEffectManager.setEnabled(enabled);

    updateCialloToggleUI();
    updateCialloStatus();

    // 如果开启，显示测试特效
    if (enabled) {
        setTimeout(() => {
            // 在屏幕中央显示测试特效
            const centerX = window.innerWidth / 2;
            const centerY = window.innerHeight / 2;
            cialloEffectManager.createEffect(centerX, centerY);
        }, 100);
    }
};

// 更新 Ciallo 特效开关UI
function updateCialloToggleUI() {
    const toggle = document.getElementById('cialloToggle');
    if (!toggle || !cialloEffectManager) return;

    if (cialloEffectManager.enabled) {
        toggle.style.background = 'linear-gradient(135deg, #00b09b, #96c93d)';
        toggle.style.color = 'white';
        toggle.style.borderColor = 'transparent';
        toggle.textContent = '已开启';
    } else {
        toggle.style.background = 'rgba(40, 40, 40, 0.8)';
        toggle.style.color = 'rgba(255, 255, 255, 0.7)';
        toggle.style.borderColor = 'rgba(255, 255, 255, 0.2)';
        toggle.textContent = '已关闭';
    }
}

// 更新 Ciallo 特效状态显示
function updateCialloStatus() {
    const statusDiv = document.getElementById('cialloStatus');
    if (!statusDiv || !cialloEffectManager) return;

    if (cialloEffectManager.enabled) {
        statusDiv.textContent = '点击时显示 Ciallo～(∠・ω< )⌒★';
        statusDiv.style.color = 'rgba(76, 175, 80, 0.8)';
    } else {
        statusDiv.textContent = 'Ciallo 特效已关闭';
        statusDiv.style.color = 'rgba(255, 255, 255, 0.6)';
    }
}

// 更新音效音量
window.updateSoundVolume = function(value) {
    if (!window.soundEffectManager) return;

    const volume = value / 100; // 转换为 0-1 范围
    window.soundEffectManager.setVolume(volume);

    // 更新显示的百分比
    const volumeValue = document.getElementById('volumeValue');
    if (volumeValue) {
        volumeValue.textContent = `${value}%`;
    }

    console.log('音效音量已调整为:', `${value}% (${volume})`);
};

// 测试音效音量
window.testSoundVolume = function() {
    if (!window.soundEffectManager || !window.soundEffectManager.enabled) return;

    // 播放测试音效
    const selectedSound = window.soundEffectManager.getSelectedSound();
    if (selectedSound) {
        window.soundEffectManager.playSound('click', getSoundUrl(selectedSound));
    } else {
        window.soundEffectManager.playSound('click', getSoundUrl('ciallo.ogg'));
    }
};

// 初始化音量滑块
function initializeSoundVolumeSlider() {
    const slider = document.getElementById('soundVolumeSlider');
    const volumeValue = document.getElementById('volumeValue');

    if (!slider || !volumeValue || !window.soundEffectManager) return;

    // 获取当前音量设置
    const currentVolume = window.soundEffectManager.getVolume();
    const percentage = Math.round(currentVolume * 100);

    // 设置滑块和显示值
    slider.value = percentage;
    volumeValue.textContent = `${percentage}%`;

    console.log('音量滑块已初始化，当前音量:', `${percentage}%`);
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    initLowComplexityModules();
});
