// static/js/shared.js
const App = {
    init: function () {
        this.bindMenuToggle();
        this.bindGlobalClick();
        this.initHistoryPanel();
        this.initAdvancedOptions();
        this.checkLoginStatus();
        this.loadSettings();
    },

    // 菜单切换功能
    bindMenuToggle: function () {
        document.querySelectorAll('.menu-button').forEach(button => {
            button.addEventListener('click', (e) => {
                e.stopPropagation();
                const menu = e.currentTarget.closest('.menu').querySelector('.menu-dropdown');
                menu.classList.toggle('active');
            });
        });
    },

    // 全局点击处理
    bindGlobalClick: function () {
        document.addEventListener('click', (e) => {
            // 关闭所有菜单
            document.querySelectorAll('.menu-dropdown.active').forEach(menu => {
                if (!menu.contains(e.target)) {
                    menu.classList.remove('active');
                }
            });

            // 关闭高级选项
            const advancedPanel = document.getElementById('advancedOptions');
            if (advancedPanel &&
                !e.target.closest('.advanced-options') &&
                !e.target.closest('.advanced-toggle')) {
                advancedPanel.classList.remove('active');
                const toggleImg = document.querySelector('.advanced-toggle img');
                if (toggleImg) toggleImg.style.transform = 'rotate(0deg)';
            }
        });
    },

    // 历史记录面板
    initHistoryPanel: function () {
        const historyButton = document.querySelector('.history-button');
        const historyPanel = document.getElementById('historyPanel');

        if (historyButton && historyPanel) {
            historyButton.addEventListener('click', () => {
                historyPanel.classList.toggle('active');
            });

            // 触摸滑动处理
            let touchStartY = 0;
            historyPanel.addEventListener('touchstart', e => {
                touchStartY = e.touches[0].clientY;
            }, false);

            historyPanel.addEventListener('touchmove', e => {
                const touchY = e.touches[0].clientY;
                if (touchY - touchStartY > 50) {
                    historyPanel.classList.remove('active');
                }
            }, false);
        }
    },

    // 高级选项功能
    initAdvancedOptions: function () {
        const toggleButton = document.querySelector('.advanced-toggle');
        if (toggleButton) {
            toggleButton.addEventListener('click', () => {
                const optionsPanel = document.getElementById('advancedOptions');
                optionsPanel.classList.toggle('active');
                const img = toggleButton.querySelector('img');
                img.style.transform = optionsPanel.classList.contains('active') ?
                    'rotate(180deg)' : 'rotate(0deg)';
            });
        }
    },

    // 登录状态检查
    checkLoginStatus: function () {
        const loginItem = document.getElementById('loginItem');
        if (loginItem) {
            // 实际应通过API检查登录状态
            const isLoggedIn = false;
            if (isLoggedIn) {
                loginItem.textContent = 'Profile';
                loginItem.href = '/profile';
            }
        }
    },

    // 设置管理
    loadSettings: function () {
        if (document.querySelector('[name="voice"]')) {
            const settings = JSON.parse(localStorage.getItem('userSettings')) || {};
            document.querySelector('[name="voice"]').value = settings.voice || 'male';
            document.querySelector('[name="style"]').value = settings.style || 'news';
            document.querySelector('[name="experimental"]').checked = settings.experimental || false;
        }
    },

    saveSettings: function () {
        if (document.querySelector('[name="voice"]')) {
            const settings = {
                voice: document.querySelector('[name="voice"]').value,
                style: document.querySelector('[name="style"]').value,
                experimental: document.querySelector('[name="experimental"]').checked
            };
            localStorage.setItem('userSettings', JSON.stringify(settings));
        }
    },

    // 通用表单验证
    validateRegistration: function (form) {
        const password = form.querySelector('#password').value;
        const confirmPassword = form.querySelector('#confirmPassword').value;

        if (password !== confirmPassword) {
            alert('Passwords do not match!');
            return false;
        }
        return true;
    },

    // 播放器控制
    initAudioPlayer: function () {
        const audio = document.getElementById('audioPlayer');
        if (!audio) return;

        // 设置有效音频源
        if (window.audioSource) {
            audio.src = window.audioSource;
        }

        const progress = document.querySelector('.progress-fill');
        const playButton = document.getElementById('playButton');

        // 安全更新播放按钮状态
        const updatePlayButton = () => {
            if (!audio.paused && !isFinite(audio.duration)) {
                return; // 防止无效状态
            }
            const iconPath = audio.paused ? 'play.png' : 'pause.png';
            playButton.querySelector('img').src =
                `${window.prefix}/static/icons/${iconPath}`;
        };

        // 音频元数据加载完成后再启用控制
        audio.addEventListener('loadedmetadata', () => {
            // 初始化进度条
            progress.style.width = '0%';

            // 绑定控制事件
            document.querySelectorAll('#playButton').forEach(btn => {
                btn.addEventListener('click', () => {
                    audio.paused ? audio.play().catch(console.error) : audio.pause();
                });
            });

            document.querySelectorAll('.jump-back').forEach(btn => {
                btn.addEventListener('click', () => this.jumpAudio(-15, audio));
            });

            document.querySelectorAll('.jump-forward').forEach(btn => {
                btn.addEventListener('click', () => this.jumpAudio(15, audio));
            });
        });

        // 错误处理
        audio.addEventListener('error', (e) => {
            console.error('Audio error:', e.target.error);
            alert('Error loading audio file');
        });

    },

    jumpAudio: function (seconds, audio) {
        try {
            if (!isFinite(audio.duration) || audio.readyState < 2) {
                console.warn('Audio not ready');
                return;
            }

            const newTime = Math.max(0, Math.min(
                audio.currentTime + seconds,
                audio.duration
            ));

            audio.currentTime = newTime;

        } catch (error) {
            console.error('Jump error:', error);
        }
    }
};

// 初始化应用
document.addEventListener('DOMContentLoaded', () => {
    App.init();
    App.initAudioPlayer();

    // 注册表单验证
    const regForm = document.querySelector('.auth-form');
    if (regForm) {
        regForm.addEventListener('submit', (e) => {
            if (!App.validateRegistration(regForm)) {
                e.preventDefault();
            }
        });
    }
});