/**
 * 登录/注册弹窗逻辑
 */

(function() {
    'use strict';

    /**
     * 切换到登录弹窗
     */
    window.switchToLogin = function() {
        closeModal('registerModal');
        setTimeout(() => {
            openModal('loginModal');
        }, 300);
    };

    /**
     * 切换到注册弹窗
     */
    window.switchToRegister = function() {
        closeModal('loginModal');
        setTimeout(() => {
            openModal('registerModal');
        }, 300);
    };

    /**
     * 处理弹窗登录表单提交
     */
    let isLoggingIn = false; // 防止重复提交
    
    window.handleModalLogin = async function(event) {
        event.preventDefault();
        
        // 防止重复提交
        if (isLoggingIn) {
            return;
        }
        
        const form = document.getElementById('modalLoginForm');
        if (!form) return;

        const submitBtn = document.getElementById('loginSubmitBtn');
        const btnText = submitBtn?.querySelector('.btn-text');
        const btnLoading = submitBtn?.querySelector('.btn-loading');

        // 显示加载状态
        if (btnText) btnText.style.display = 'none';
        if (btnLoading) btnLoading.style.display = 'inline';
        if (submitBtn) submitBtn.disabled = true;
        isLoggingIn = true;

        try {
            const formData = new FormData(form);
            const data = {
                username: formData.get('username'),
                password: formData.get('password')
            };

            const baseUrl = window.BASE_URL || window.location.origin;
            const response = await fetch(`${baseUrl}/?r=mobileApi/login`, {
                method: 'POST',
                credentials: 'include',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(data)
            });

            const result = await response.json();

            if (result.code === 0) {
                // 更新全局登录状态
                window.LOGGED_IN = true;
                window.USER_ID = result.data?.user_id || null;
                
                showToast('登录成功');
                closeModal('loginModal');
                // 刷新页面
                setTimeout(() => {
                    window.location.reload();
                }, 1500);
            } else {
                showToast(result.message || '登录失败');
            }
        } catch (error) {
            showToast('网络错误，请稍后重试');
            console.error('Login error:', error);
        } finally {
            // 恢复按钮状态
            if (btnText) btnText.style.display = 'inline';
            if (btnLoading) btnLoading.style.display = 'none';
            if (submitBtn) submitBtn.disabled = false;
            isLoggingIn = false;
        }
    };

    /**
     * 处理弹窗注册表单提交
     */
    let isRegistering = false; // 防止重复提交
    
    window.handleModalRegister = async function(event) {
        event.preventDefault();
        
        // 防止重复提交
        if (isRegistering) {
            return;
        }
        
        const form = document.getElementById('modalRegisterForm');
        if (!form) return;

        const submitBtn = document.getElementById('registerSubmitBtn');
        const btnText = submitBtn?.querySelector('.btn-text');
        const btnLoading = submitBtn?.querySelector('.btn-loading');

        // 显示加载状态
        if (btnText) btnText.style.display = 'none';
        if (btnLoading) btnLoading.style.display = 'inline';
        if (submitBtn) submitBtn.disabled = true;
        isRegistering = true;

        try {
            const formData = new FormData(form);
            const data = {
                username: formData.get('username'),
                password: formData.get('password')
            };

            // 验证数据
            if (!data.username || data.username.length < 3) {
                showToast('用户名至少需要3个字符');
                return;
            }

            if (!data.password || data.password.length < 6) {
                showToast('密码至少需要6个字符');
                return;
            }

            const baseUrl = window.BASE_URL || window.location.origin;
            const response = await fetch(`${baseUrl}/?r=mobileApi/register`, {
                method: 'POST',
                credentials: 'include',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(data)
            });

            const result = await response.json();

            if (result.code === 0) {
                showToast('注册成功，请登录');
                switchToLogin();
                // 重置表单
                form.reset();
            } else {
                showToast(result.message || '注册失败');
            }
        } catch (error) {
            showToast('网络错误，请稍后重试');
            console.error('Register error:', error);
        } finally {
            // 恢复按钮状态
            if (btnText) btnText.style.display = 'inline';
            if (btnLoading) btnLoading.style.display = 'none';
            if (submitBtn) submitBtn.disabled = false;
            isRegistering = false;
        }
    };

    /**
     * 发送弹窗邮箱验证码
     */
    window.sendModalEmailCode = async function(button) {
        const form = document.getElementById('modalRegisterForm');
        if (!form) return;

        const emailInput = form.querySelector('input[name="email"]');
        const email = emailInput?.value;

        if (!email) {
            showToast('请先输入邮箱');
            return;
        }

        // 验证邮箱格式
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        if (!emailRegex.test(email)) {
            showToast('请输入正确的邮箱格式');
            return;
        }

        // 禁用按钮并显示倒计时
        button.disabled = true;
        let countdown = 60;
        button.textContent = `${countdown}秒`;

        const countdownInterval = setInterval(() => {
            countdown--;
            button.textContent = `${countdown}秒`;
            
            if (countdown <= 0) {
                clearInterval(countdownInterval);
                button.disabled = false;
                button.textContent = '获取验证码';
            }
        }, 1000);

        try {
            const baseUrl = window.BASE_URL || window.location.origin;
            const response = await fetch(`${baseUrl}/?r=mobileApi/sendEmailCode`, {
                method: 'POST',
                credentials: 'include',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ email })
            });

            const result = await response.json();

            if (result.code !== 0) {
                showToast(result.message || '发送失败');
                // 重置按钮
                clearInterval(countdownInterval);
                button.disabled = false;
                button.textContent = '获取验证码';
            } else {
                showToast('验证码已发送');
            }
        } catch (error) {
            showToast('网络错误，请稍后重试');
            console.error('Send email code error:', error);
            // 重置按钮
            clearInterval(countdownInterval);
            button.disabled = false;
            button.textContent = '获取验证码';
        }
    };

    /**
     * 切换密码可见性
     */
    window.toggleModalPassword = function(inputId, button) {
        const input = document.getElementById(inputId);
        if (!input) return;

        const isPassword = input.type === 'password';
        input.type = isPassword ? 'text' : 'password';

        // 找到按钮并更新图标
        let toggleBtn = button;
        if (!toggleBtn) {
            const allToggles = document.querySelectorAll('.password-toggle-btn');
            for (let btn of allToggles) {
                const onclickAttr = btn.getAttribute('onclick');
                if (onclickAttr && onclickAttr.includes(inputId)) {
                    toggleBtn = btn;
                    break;
                }
            }
        }

        if (toggleBtn) {
            const icon = toggleBtn.querySelector('.iconify');
            if (icon) {
                icon.setAttribute('data-icon', isPassword ? 'mdi:eye-off' : 'mdi:eye');
            }
        }
    };

    /**
     * 初始化登录/注册弹窗
     */
    function initAuthModals() {
        // 添加表单提交事件
        const loginForm = document.getElementById('modalLoginForm');
        if (loginForm) {
            loginForm.addEventListener('submit', handleModalLogin);
        }

        const registerForm = document.getElementById('modalRegisterForm');
        if (registerForm) {
            registerForm.addEventListener('submit', handleModalRegister);
        }

        // 添加密码切换按钮事件
        const passwordToggles = document.querySelectorAll('.password-toggle-btn');
        passwordToggles.forEach(toggle => {
            toggle.addEventListener('click', function(e) {
                e.preventDefault();
                const inputId = this.getAttribute('onclick')?.match(/'([^']+)'/)?.[1];
                if (inputId) {
                    toggleModalPassword(inputId, this);
                }
            });
        });

        // 添加切换链接事件
        const switchToRegisterLink = document.querySelector('.auth-link[onclick="switchToRegister()"]');
        if (switchToRegisterLink) {
            switchToRegisterLink.addEventListener('click', switchToRegister);
        }

        const switchToLoginLink = document.querySelector('.auth-link[onclick="switchToLogin()"]');
        if (switchToLoginLink) {
            switchToLoginLink.addEventListener('click', switchToLogin);
        }

        // 添加邮箱验证码发送按钮事件
        const sendCodeBtn = document.querySelector('.send-code-btn');
        if (sendCodeBtn) {
            sendCodeBtn.addEventListener('click', function() {
                sendModalEmailCode(this);
            });
        }
    }

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