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

document.addEventListener('DOMContentLoaded', function() {
    loadDataStats();
    
    // 导出功能
    document.getElementById('exportAllBtn').addEventListener('click', () => exportData('all'));
    document.getElementById('exportPostsBtn').addEventListener('click', () => exportData('posts'));
    document.getElementById('exportCommentsBtn').addEventListener('click', () => exportData('comments'));
    
    // 清除功能
    document.getElementById('clearCacheBtn').addEventListener('click', clearCache);
    document.getElementById('clearHistoryBtn').addEventListener('click', clearHistory);
    
    // 删除账号
    document.getElementById('deleteAccountBtn').addEventListener('click', deleteAccount);
});

async function loadDataStats() {
    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('statPosts').textContent = user.post_count || 0;
            document.getElementById('statComments').textContent = user.comment_count || 0;
            document.getElementById('statFavorites').textContent = user.favorite_count || 0;
            document.getElementById('statLikes').textContent = user.like_count || 0;
        }
    } catch (error) {
        console.error('加载数据统计失败:', error);
    }
}

async function exportData(type) {
    const btnMap = {
        'all': document.getElementById('exportAllBtn'),
        'posts': document.getElementById('exportPostsBtn'),
        'comments': document.getElementById('exportCommentsBtn')
    };
    
    const btn = btnMap[type];
    btn.disabled = true;
    btn.textContent = '导出中...';
    
    try {
        const response = await fetch(BASE_URL + '/?r=mobileApi/exportData&type=' + type, {
            method: 'GET',
            credentials: 'include'
        });
        
        const result = await response.json();
        
        if (result.code === 0 && result.data) {
            // 创建下载链接
            const blob = new Blob([JSON.stringify(result.data, null, 2)], { type: 'application/json' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = `husns_data_${type}_${Date.now()}.json`;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            URL.revokeObjectURL(url);
            
            showToast('导出成功');
        } else {
            showToast(result.message || '导出失败');
        }
    } catch (error) {
        console.error('导出数据失败:', error);
        showToast('导出失败，请重试');
    }
    
    btn.disabled = false;
    btn.textContent = '导出';
}

function clearCache() {
    if (!confirm('确定要清除缓存数据吗？')) {
        return;
    }
    
    try {
        // 清除本地存储中的缓存数据
        localStorage.removeItem('privacy_settings');
        localStorage.removeItem('user_info');
        
        // 清除图片缓存（如果有）
        caches.keys().then(function(names) {
            for (let name of names) {
                caches.delete(name);
            }
        });
        
        showToast('缓存已清除');
    } catch (error) {
        console.error('清除缓存失败:', error);
        showToast('清除失败，请重试');
    }
}

function clearHistory() {
    if (!confirm('确定要清除浏览记录吗？')) {
        return;
    }
    
    try {
        localStorage.removeItem('browse_history');
        showToast('浏览记录已清除');
    } catch (error) {
        console.error('清除浏览记录失败:', error);
        showToast('清除失败，请重试');
    }
}

function deleteAccount() {
    if (!confirm('⚠️ 警告：此操作将永久删除您的账号及所有数据，且无法恢复！\n\n确定要继续吗？')) {
        return;
    }
    
    const password = prompt('请输入您的密码以确认删除账号：');
    if (!password) {
        showToast('请输入密码');
        return;
    }
    
    const btn = document.getElementById('deleteAccountBtn');
    btn.disabled = true;
    btn.textContent = '处理中...';
    
    (async function() {
        try {
            const formData = new FormData();
            formData.append('password', password);
            
            const response = await fetch(BASE_URL + '/?r=mobileApi/deleteAccount', {
                method: 'POST',
                body: formData,
                credentials: 'include'
            });
            
            const result = await response.json();
            
            if (result.code === 0) {
                showToast('账号已删除');
                setTimeout(() => {
                    window.location.href = BASE_URL;
                }, 2000);
            } else {
                showToast(result.message || '删除失败');
            }
        } catch (error) {
            console.error('删除账号失败:', error);
            showToast('删除失败，请重试');
        }
        
        btn.disabled = false;
        btn.textContent = '删除我的账号';
    })();
}

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);
}