const BASE_URL = window.HuSNS_Index?.apiUrls?.base || '/';

document.addEventListener('DOMContentLoaded', function() {
    loadUserInfo();
    loadDevices();
    
    // 修改密码
    document.getElementById('changePasswordBtn').addEventListener('click', changePassword);
    
    // 绑定手机
    document.getElementById('bindMobileBtn').addEventListener('click', showBindMobileModal);
    
    // 绑定邮箱
    document.getElementById('bindEmailBtn').addEventListener('click', showBindEmailModal);
});

async function loadUserInfo() {
    try {
        const response = await fetch(BASE_URL + '/?r=mobileApi/userInfo');
        const result = await response.json();
        
        if (result.code === 0 && result.data && result.data.user) {
            const user = result.data.user;
            document.getElementById('mobileValue').textContent = user.mobile ? maskPhone(user.mobile) : '未绑定';
            document.getElementById('emailValue').textContent = user.email ? maskEmail(user.email) : '未绑定';
        }
    } catch (error) {
        console.error('加载用户信息失败:', error);
    }
}

function maskPhone(phone) {
    if (!phone) return phone;
    return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
}

function maskEmail(email) {
    if (!email) return email;
    const parts = email.split('@');
    if (parts[0].length > 2) {
        return parts[0].slice(0, 2) + '****@' + parts[1];
    }
    return email;
}

async function loadDevices() {
    const deviceList = document.getElementById('deviceList');
    const emptyState = document.getElementById('deviceEmptyState');
    
    try {
        const response = await fetch(BASE_URL + '/?r=mobileApi/getDevices');
        const result = await response.json();
        
        if (result.code === 0 && result.data && result.data.list) {
            renderDevices(result.data.list);
            emptyState.style.display = result.data.list.length === 0 ? 'block' : 'none';
        } else {
            deviceList.innerHTML = '<div class="error-tip">加载失败，请重试</div>';
        }
    } catch (error) {
        console.error('加载设备列表失败:', error);
        deviceList.innerHTML = '<div class="error-tip">网络异常，请稍后重试</div>';
    }
}

function renderDevices(list) {
    const deviceList = document.getElementById('deviceList');
    
    if (list.length === 0) {
        deviceList.innerHTML = '';
        return;
    }
    
    const items = list.map((item, index) => `
        <div class="device-item" data-device-id="${item.id}">
            <div class="device-info">
                <div class="device-icon">${index === 0 ? '✅' : '📱'}</div>
                <div class="device-detail">
                    <div class="device-name">${item.device_name || '未知设备'}</div>
                    <div class="device-info-text">${item.ip_address || '未知IP'} - ${item.login_time || '未知时间'}</div>
                </div>
            </div>
            ${index !== 0 ? '<button class="device-logout" onclick="logoutDevice(' + item.id + ')">退出登录</button>' : '<span class="device-current">当前设备</span>'}
        </div>
    `).join('');
    
    deviceList.innerHTML = items;
}

async function changePassword() {
    const currentPassword = document.getElementById('currentPassword').value.trim();
    const newPassword = document.getElementById('newPassword').value.trim();
    const confirmPassword = document.getElementById('confirmPassword').value.trim();
    
    // 验证
    if (!currentPassword) {
        showToast('请输入当前密码');
        return;
    }
    if (!newPassword) {
        showToast('请输入新密码');
        return;
    }
    if (newPassword.length < 6) {
        showToast('新密码至少需要6位');
        return;
    }
    if (newPassword !== confirmPassword) {
        showToast('两次输入的密码不一致');
        return;
    }
    
    const btn = document.getElementById('changePasswordBtn');
    btn.disabled = true;
    btn.textContent = '修改中...';
    
    try {
        const formData = new FormData();
        formData.append('old_password', currentPassword);
        formData.append('new_password', newPassword);
        
        const response = await fetch(BASE_URL + '/?r=mobileApi/changePassword', {
            method: 'POST',
            body: formData,
            credentials: 'include'
        });
        
        const result = await response.json();
        
        if (result.code === 0) {
            showToast('密码修改成功，请重新登录');
            // 清空表单
            document.getElementById('currentPassword').value = '';
            document.getElementById('newPassword').value = '';
            document.getElementById('confirmPassword').value = '';
            // 延迟退出登录
            setTimeout(() => {
                window.location.href = BASE_URL + '/?r=mobile/logout';
            }, 2000);
        } else {
            showToast(result.message || '修改失败');
        }
    } catch (error) {
        console.error('修改密码失败:', error);
        showToast('修改失败，请重试');
    }
    
    btn.disabled = false;
    btn.textContent = '修改密码';
}

function showBindMobileModal() {
    alert('绑定手机功能开发中...');
}

function showBindEmailModal() {
    alert('绑定邮箱功能开发中...');
}

async function logoutDevice(deviceId) {
    if (!confirm('确定要退出该设备的登录吗？')) {
        return;
    }
    
    try {
        const formData = new FormData();
        formData.append('device_id', deviceId);
        
        const response = await fetch(BASE_URL + '/?r=mobileApi/logoutDevice', {
            method: 'POST',
            body: formData,
            credentials: 'include'
        });
        
        const result = await response.json();
        
        if (result.code === 0) {
            showToast('已退出该设备');
            loadDevices();
        } else {
            showToast(result.message || '操作失败');
        }
    } catch (error) {
        console.error('退出设备失败:', error);
        showToast('操作失败，请重试');
    }
}

function showToast(message) {
    const toast = document.createElement('div');
    toast.className = 'toast';
    toast.textContent = message;
    document.body.appendChild(toast);
    
    setTimeout(() => {
        toast.classList.add('show');
    }, 10);
    
    setTimeout(() => {
        toast.classList.remove('show');
        setTimeout(() => {
            document.body.removeChild(toast);
        }, 300);
    }, 2000);
}