// 主JS文件 - 包含登录和注册功能
document.addEventListener('DOMContentLoaded', function() {
    // 主题切换
    const themeToggle = document.getElementById('theme-toggle');
    if (themeToggle) {
        const body = document.body;

        themeToggle.addEventListener('click', function() {
            body.classList.toggle('dark-mode');
            const isDarkMode = body.classList.contains('dark-mode');
            localStorage.setItem('dark-mode', isDarkMode);
            themeToggle.innerHTML = isDarkMode ? '🌙' : '☀️';
        });

        // 从本地存储中加载主题首选项
        const savedDarkMode = localStorage.getItem('dark-mode') === 'true';
        if (savedDarkMode) {
            body.classList.add('dark-mode');
            themeToggle.innerHTML = '🌙';
        }
    }

    // 密码可见性切换
    const passwordToggle = document.getElementById('password-toggle');
    if (passwordToggle) {
        const passwordInput = document.getElementById('password');
        passwordToggle.addEventListener('click', function() {
            const type = passwordInput.getAttribute('type') === 'password' ? 'text' : 'password';
            passwordInput.setAttribute('type', type);
            passwordToggle.innerHTML = type === 'password' ? '👁️' : '👁️‍🗨️';
        });
    }

    // 登录表单验证
    const loginForm = document.getElementById('login-form');
    if (loginForm) {
        const usernameInput = document.getElementById('username');
        const passwordInput = document.getElementById('password');
        const usernameError = document.getElementById('username-error');
        const passwordError = document.getElementById('password-error');
        const loginButton = document.getElementById('login-button');

        if (usernameInput && usernameError) {
            usernameInput.addEventListener('input', function() {
                if (usernameInput.value.trim() === '') {
                    usernameError.textContent = '用户名不能为空';
                    usernameError.classList.add('show');
                } else {
                    usernameError.classList.remove('show');
                }
            });
        }

        if (passwordInput && passwordError) {
            passwordInput.addEventListener('input', function() {
                if (passwordInput.value.trim() === '') {
                    passwordError.textContent = '密码不能为空';
                    passwordError.classList.add('show');
                } else if (passwordInput.value.length < 6) {
                    passwordError.textContent = '密码长度至少6位';
                    passwordError.classList.add('show');
                } else {
                    passwordError.classList.remove('show');
                }
            });
        }

        loginForm.addEventListener('submit', function(e) {
            let isValid = true;

            // 验证用户名
            if (usernameInput.value.trim() === '') {
                usernameError.textContent = '用户名不能为空';
                usernameError.classList.add('show');
                isValid = false;
            }

            // 验证密码
            if (passwordInput.value.trim() === '') {
                passwordError.textContent = '密码不能为空';
                passwordError.classList.add('show');
                isValid = false;
            } else if (passwordInput.value.length < 6) {
                passwordError.textContent = '密码长度至少6位';
                passwordError.classList.add('show');
                isValid = false;
            }

            if (!isValid) {
                e.preventDefault();
            } else if (loginButton) {
                loginButton.classList.add('loading-state');
            }
        });
    }
    // 注册表单验证
    const registerForm = document.getElementById('register-form');
    if (registerForm) {
        const usernameInput = document.getElementById('username');
        const emailInput = document.getElementById('email');
        const passwordInput = document.getElementById('password');
        const confirmPasswordInput = document.getElementById('confirm_password');
        const verificationCodeInput = document.getElementById('verification_code');

        const usernameError = document.getElementById('username-error');
        const emailError = document.getElementById('email-error');
        const passwordError = document.getElementById('password-error');
        const confirmPasswordError = document.getElementById('confirm-password-error');
        const verificationCodeError = document.getElementById('verification-code-error');

        const registerButton = document.getElementById('register-button');
        const sendCodeBtn = document.getElementById('send-code-btn');

        // 用户名验证
        if (usernameInput && usernameError) {
            usernameInput.addEventListener('input', function() {
                if (usernameInput.value.trim() === '') {
                    usernameError.textContent = '用户名不能为空';
                    usernameError.classList.add('show');
                } else if (usernameInput.value.length < 3) {
                    usernameError.textContent = '用户名至少3个字符';
                    usernameError.classList.add('show');
                } else {
                    usernameError.classList.remove('show');
                }
            });
        }

        // 邮箱验证
        if (emailInput && emailError) {
            emailInput.addEventListener('input', function() {
                const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
                if (emailInput.value.trim() === '') {
                    emailError.textContent = '邮箱不能为空';
                    emailError.classList.add('show');
                } else if (!emailRegex.test(emailInput.value)) {
                    emailError.textContent = '请输入有效的邮箱地址';
                    emailError.classList.add('show');
                } else {
                    emailError.classList.remove('show');
                }
            });
        }

        // 密码验证
        if (passwordInput && passwordError) {
            passwordInput.addEventListener('input', function() {
                if (passwordInput.value.trim() === '') {
                    passwordError.textContent = '密码不能为空';
                    passwordError.classList.add('show');
                } else if (passwordInput.value.length < 6) {
                    passwordError.textContent = '密码长度至少6位';
                    passwordError.classList.add('show');
                } else {
                    passwordError.classList.remove('show');
                }

                // 检查确认密码是否匹配
                if (confirmPasswordInput && confirmPasswordInput.value) {
                    if (confirmPasswordInput.value !== passwordInput.value) {
                        confirmPasswordError.textContent = '两次输入的密码不匹配';
                        confirmPasswordError.classList.add('show');
                    } else {
                        confirmPasswordError.classList.remove('show');
                    }
                }
            });
        }

        // 确认密码验证
        if (confirmPasswordInput && confirmPasswordError) {
            confirmPasswordInput.addEventListener('input', function() {
                if (confirmPasswordInput.value.trim() === '') {
                    confirmPasswordError.textContent = '请确认密码';
                    confirmPasswordError.classList.add('show');
                } else if (confirmPasswordInput.value !== passwordInput.value) {
                    confirmPasswordError.textContent = '两次输入的密码不匹配';
                    confirmPasswordError.classList.add('show');
                } else {
                    confirmPasswordError.classList.remove('show');
                }
            });
        }

        // 发送验证码按钮
        if (sendCodeBtn) {
            sendCodeBtn.addEventListener('click', function() {
                const email = emailInput.value.trim();
                const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

                if (!email) {
                    emailError.textContent = '请输入邮箱地址';
                    emailError.classList.add('show');
                    return;
                } else if (!emailRegex.test(email)) {
                    emailError.textContent = '请输入有效的邮箱地址';
                    emailError.classList.add('show');
                    return;
                }

                // 禁用按钮并显示倒计时
                let countdown = 60;
                sendCodeBtn.disabled = true;
                const originalText = sendCodeBtn.textContent;
                sendCodeBtn.textContent = `${countdown}秒后重试`;

                const timer = setInterval(() => {
                    countdown--;
                    sendCodeBtn.textContent = `${countdown}秒后重试`;

                    if (countdown <= 0) {
                        clearInterval(timer);
                        sendCodeBtn.disabled = false;
                        sendCodeBtn.textContent = originalText;
                    }
                }, 1000);

                // 发送请求获取验证码
                fetch('/user/send_verification_code', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ email: email }),
                })
                .then(response => response.json())
                .then(data => {
                    console.log("验证码发送响应:", data);  // 添加调试日志
                    if (data.success) {
                        showMessage('验证码已发送', '请检查您的邮箱', 'success');
                    } else {
                        showMessage('发送失败', data.message || '请稍后重试', 'error');
                        clearInterval(timer);
                        sendCodeBtn.disabled = false;
                        sendCodeBtn.textContent = originalText;
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    showMessage('发送失败', '网络错误，请稍后重试', 'error');
                    clearInterval(timer);
                    sendCodeBtn.disabled = false;
                    sendCodeBtn.textContent = originalText;
                });
            });
        }

        // 表单提交验证
        registerForm.addEventListener('submit', function(e) {
            let isValid = true;

            // 验证用户名
            if (usernameInput.value.trim() === '') {
                usernameError.textContent = '用户名不能为空';
                usernameError.classList.add('show');
                isValid = false;
            } else if (usernameInput.value.length < 3) {
                usernameError.textContent = '用户名至少3个字符';
                usernameError.classList.add('show');
                isValid = false;
            }

            // 验证邮箱
            const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
            if (emailInput.value.trim() === '') {
                emailError.textContent = '邮箱不能为空';
                emailError.classList.add('show');
                isValid = false;
            } else if (!emailRegex.test(emailInput.value)) {
                emailError.textContent = '请输入有效的邮箱地址';
                emailError.classList.add('show');
                isValid = false;
            }

            // 验证密码
            if (passwordInput.value.trim() === '') {
                passwordError.textContent = '密码不能为空';
                passwordError.classList.add('show');
                isValid = false;
            } else if (passwordInput.value.length < 6) {
                passwordError.textContent = '密码长度至少6位';
                passwordError.classList.add('show');
                isValid = false;
            }

            // 验证确认密码
            if (confirmPasswordInput.value.trim() === '') {
                confirmPasswordError.textContent = '请确认密码';
                confirmPasswordError.classList.add('show');
                isValid = false;
            } else if (confirmPasswordInput.value !== passwordInput.value) {
                confirmPasswordError.textContent = '两次输入的密码不匹配';
                confirmPasswordError.classList.add('show');
                isValid = false;
            }

            // 验证验证码
            if (verificationCodeInput.value.trim() === '') {
                verificationCodeError.textContent = '请输入验证码';
                verificationCodeError.classList.add('show');
                isValid = false;
            }

            if (!isValid) {
                e.preventDefault();
            } else if (registerButton) {
                registerButton.classList.add('loading-state');
            }
        });
    }

    // 通知消息显示函数
    function showMessage(title, message, type) {
        const notification = document.createElement('div');
        notification.className = `notification ${type}`;

        const icon = type === 'success' ? '✓' : '✗';

        notification.innerHTML = `
            <div class="notification-icon">${icon}</div>
            <div class="notification-content">
                <h3>${title}</h3>
                <p>${message}</p>
            </div>
        `;

        document.body.appendChild(notification);

        setTimeout(() => {
            notification.classList.add('show');
        }, 10);

        setTimeout(() => {
            notification.classList.remove('show');
            setTimeout(() => {
                document.body.removeChild(notification);
            }, 300);
        }, 3000);
    }
});