// 认证相关 JavaScript

// 检查是否已登录
async function checkAuth() {
    try {
        const token = getCookie('token');
        if (!token) {
            return false;
        }
        
        const response = await fetch('/admin/me', {
            headers: {
                'Authorization': `Bearer ${token}`
            }
        });
        
        if (response.ok) {
            const data = await response.json();
            // 已登录，跳转到管理页面
            window.location.href = '/admin';
            return true;
        }
    } catch (error) {
        console.error('Auth check error:', error);
    }
    return false;
}

// 获取 Cookie
function getCookie(name) {
    const value = `; ${document.cookie}`;
    const parts = value.split(`; ${name}=`);
    if (parts.length === 2) return parts.pop().split(';').shift();
    return null;
}

// API 请求封装
async function apiRequest(url, options = {}) {
    const token = getCookie('token');
    const headers = {
        'Content-Type': 'application/json',
        ...options.headers
    };
    
    if (token) {
        headers['Authorization'] = `Bearer ${token}`;
    }
    
    const response = await fetch(url, {
        ...options,
        headers
    });
    
    if (!response.ok) {
        const error = await response.json().catch(() => ({ error: '请求失败' }));
        throw new Error(error.error || '请求失败');
    }
    
    return await response.json();
}

// 显示错误消息
function showError(message) {
    const errorEl = document.getElementById('auth-error');
    if (errorEl) {
        errorEl.textContent = message;
        errorEl.classList.add('show');
        setTimeout(() => {
            errorEl.classList.remove('show');
        }, 5000);
    }
}

// 登录表单处理
const loginForm = document.getElementById('login-form');
if (loginForm) {
    loginForm.addEventListener('submit', async (e) => {
        e.preventDefault();
        
        const formData = new FormData(loginForm);
        const data = {
            username: formData.get('username'),
            password: formData.get('password')
        };
        
        const submitBtn = loginForm.querySelector('button[type="submit"]');
        const originalText = submitBtn.innerHTML;
        submitBtn.disabled = true;
        submitBtn.innerHTML = '<span>登录中...</span>';
        
        try {
            const result = await apiRequest('/admin/login', {
                method: 'POST',
                body: JSON.stringify(data)
            });
            
            // 设置 token cookie
            document.cookie = `token=${result.token}; path=/; max-age=86400; SameSite=Lax`;
            
            // 跳转到管理页面
            window.location.href = '/admin';
        } catch (error) {
            showError(error.message || '登录失败');
            submitBtn.disabled = false;
            submitBtn.innerHTML = originalText;
        }
    });
}

// 注册表单处理
const registerForm = document.getElementById('register-form');
if (registerForm) {
    // 密码强度检测
    const passwordInput = document.getElementById('password');
    const passwordStrength = document.getElementById('password-strength');
    
    if (passwordInput && passwordStrength) {
        passwordInput.addEventListener('input', (e) => {
            const password = e.target.value;
            let strength = 'weak';
            
            if (password.length >= 8) {
                const hasUpper = /[A-Z]/.test(password);
                const hasLower = /[a-z]/.test(password);
                const hasNumber = /[0-9]/.test(password);
                const hasSpecial = /[^A-Za-z0-9]/.test(password);
                
                const score = [hasUpper, hasLower, hasNumber, hasSpecial].filter(Boolean).length;
                
                if (score >= 3) {
                    strength = 'strong';
                } else if (score >= 2) {
                    strength = 'medium';
                }
            }
            
            passwordStrength.className = `password-strength ${strength}`;
        });
    }
    
    registerForm.addEventListener('submit', async (e) => {
        e.preventDefault();
        
        const password = document.getElementById('password').value;
        const confirmPassword = document.getElementById('confirm-password').value;
        
        if (password !== confirmPassword) {
            showError('两次输入的密码不一致');
            return;
        }
        
        const formData = new FormData(registerForm);
        const data = {
            username: formData.get('username'),
            email: formData.get('email'),
            password: password
        };
        
        const submitBtn = registerForm.querySelector('button[type="submit"]');
        const originalText = submitBtn.innerHTML;
        submitBtn.disabled = true;
        submitBtn.innerHTML = '<span>注册中...</span>';
        
        try {
            const result = await apiRequest('/admin/register', {
                method: 'POST',
                body: JSON.stringify(data)
            });
            
            // 设置 token cookie
            document.cookie = `token=${result.token}; path=/; max-age=86400; SameSite=Lax`;
            
            // 跳转到管理页面
            window.location.href = '/admin';
        } catch (error) {
            showError(error.message || '注册失败');
            submitBtn.disabled = false;
            submitBtn.innerHTML = originalText;
        }
    });
}

// 页面加载时检查认证状态
document.addEventListener('DOMContentLoaded', () => {
    // 如果已经在登录/注册页面，不需要检查
    if (window.location.pathname.includes('/admin/login') || 
        window.location.pathname.includes('/admin/register')) {
        return;
    }
    
    // 检查是否已登录
    checkAuth();
});
