let isRegisterMode = false;

document.getElementById('authSwitchBtn').onclick = () => {
    isRegisterMode = !isRegisterMode;
    document.getElementById('authTitle').innerText = isRegisterMode ? "加入视界 AI" : "欢迎回来";
    document.getElementById('authSub').innerText = isRegisterMode ? "注册并开启创作" : "请登录以开启 AI 创作之旅";
    document.getElementById('authSubmitBtn').querySelector('span').innerText = isRegisterMode ? "立即注册" : "立即登录";
    document.getElementById('authSwitchBtn').innerText = isRegisterMode ? "已有账号？返回登录" : "没有账号？立即注册";
    document.getElementById('smsGroup').classList.toggle('hidden', !isRegisterMode);
};

document.getElementById('sendSmsBtn').onclick = async () => {
    const phone = document.getElementById('authPhone').value;
    const btn = document.getElementById('sendSmsBtn');
    
    if(!phone) return showToast('请输入手机号', 'warning');
    
    btn.disabled = true;
    const originalText = btn.innerText;
    
    const r = await fetch('/api/auth/send_code', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({ phone })
    });
    const d = await r.json();
    
    if(d.error) {
        showToast(d.error, 'error');
        btn.disabled = false;
    } else {
        showToast(d.message, 'success');
        let countdown = 60;
        const timer = setInterval(() => {
            btn.innerText = `${countdown}秒后重试`;
            countdown--;
            if(countdown < 0) {
                clearInterval(timer);
                btn.innerText = originalText;
                btn.disabled = false;
            }
        }, 1000);
    }
};

document.getElementById('authSubmitBtn').onclick = async () => {
    const phone = document.getElementById('authPhone').value;
    const password = document.getElementById('authPass').value;
    const code = document.getElementById('authCode').value;

    const url = isRegisterMode ? '/api/auth/register' : '/api/auth/login';
    const body = isRegisterMode ? { phone, password, code } : { phone, password };

    const r = await fetch(url, {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify(body)
    });
    const d = await r.json();
    if(d.error) {
        showToast(d.error, 'error');
    } else {
        showToast(d.message, 'success');
        if(isRegisterMode) {
            isRegisterMode = true;
            document.getElementById('authSwitchBtn').click();
        } else {
            // 获取来源页面路径
            const urlParams = new URLSearchParams(window.location.search);
            const nextUrl = urlParams.get('next') || '/';
            window.location.href = nextUrl;
        }
    }
};