// 使用模板中定义的 BASE_URL，避免重复声明
document.addEventListener('DOMContentLoaded', function() {
    loadUserProfile();
    
    document.querySelectorAll('.js-disabled').forEach(link => {
        link.addEventListener('click', function(e) {
            e.preventDefault();
            const tip = this.dataset.tip || '功能开发中';
            showToast(tip);
        });
    });
});

async function loadUserProfile() {
    try {
        const response = await fetch(BASE_URL + '/?r=mobileApi/userInfo');
        const result = await response.json();
        
        if (result.code === 0 && result.data) {
            const user = result.data.user || {};
            const stats = result.data.stats || {};
            
            const avatarEl = document.getElementById('profileAvatar');
            const validAvatar = user.avatar && 
                                 user.avatar.trim() !== '' && 
                                 user.avatar !== 'null' && 
                                 user.avatar.startsWith('http');
            if (validAvatar) {
                avatarEl.innerHTML = `<img src="${user.avatar}" alt="">`;
            } else {
                avatarEl.innerHTML = `<img src="/templates/mobile/images/avatar_default.png" alt="">`;
            }
            
            document.getElementById('profileUsername').textContent = user.username || '用户';
            document.getElementById('profileBio').textContent = user.bio || '这个人很懒，什么都没写';
            
            document.getElementById('statPosts').textContent = stats.post_count || 0;
            document.getElementById('statFollows').textContent = stats.following || 0;
            document.getElementById('statFans').textContent = stats.followers || 0;
            document.getElementById('statFavorites').textContent = stats.favorites || 0;
        }
    } catch (error) {
        console.error('加载用户信息失败:', error);
        document.getElementById('profileUsername').textContent = '加载失败';
    }
}

function initLogout() {
    var logoutBtn = document.getElementById('logoutBtn');
    if (logoutBtn) {
        logoutBtn.addEventListener('click', function(e) {
            e.preventDefault();
            // 使用美化的确认对话框
            if (window.HuSNS_Dialog && window.HuSNS_Dialog.confirm) {
                window.HuSNS_Dialog.confirm('确定要退出登录吗？', {
                    title: '退出登录',
                    confirmText: '退出',
                    confirmCallback: function() {
                        handleLogout();
                    }
                });
            } else {
                // 回退到原生 confirm
                if (confirm('确定要退出登录吗？')) {
                    handleLogout();
                }
            }
        });
    }
}

function handleLogout() {
    fetch(BASE_URL + '/?r=mobileApi/logout', {
        method: 'POST',
        credentials: 'include',
        headers: {
            'Content-Type': 'application/json'
        }
    })
    .then(function(response) {
        return response.json();
    })
    .then(function(data) {
        localStorage.clear();
        sessionStorage.clear();
        // 退出登录后返回首页（个人中心需要登录，会被重定向）
        window.location.href = BASE_URL + '/?r=mobile/index';
    })
    .catch(function() {
        localStorage.clear();
        sessionStorage.clear();
        // 退出登录后返回首页（个人中心需要登录，会被重定向）
        window.location.href = BASE_URL + '/?r=mobile/index';
    });
}

document.addEventListener('DOMContentLoaded', initLogout);