const BASE_URL = window.location.origin;

document.addEventListener('DOMContentLoaded', function() {
    loadPrivacySettings();
    document.getElementById('savePrivacySettings').addEventListener('click', savePrivacySettings);
});

/**
 * 从表单获取当前隐私设置
 */
function getFormSettings() {
    return {
        profile_visibility: document.getElementById('profileVisibility').value,
        show_online_status: document.getElementById('showOnlineStatus').checked ? 1 : 0,
        allow_stranger_messages: document.getElementById('allowStrangerMessages').checked ? 1 : 0,
        comment_visibility: document.getElementById('commentVisibility').value,
        repost_visibility: document.getElementById('repostVisibility').value,
        allow_search: document.getElementById('allowSearch').checked ? 1 : 0,
        notify_likes: document.getElementById('notificationsLikes').checked ? 1 : 0,
        notify_comments: document.getElementById('notificationsComments').checked ? 1 : 0,
        notify_follows: document.getElementById('notificationsFollows').checked ? 1 : 0,
        notify_system: document.getElementById('notificationsSystem').checked ? 1 : 0
    };
}

/**
 * 将设置应用到表单
 */
function applySettingsToForm(settings) {
    if (settings.profile_visibility) {
        document.getElementById('profileVisibility').value = settings.profile_visibility;
    }
    if (settings.show_online_status !== undefined) {
        document.getElementById('showOnlineStatus').checked = settings.show_online_status == 1;
    }
    if (settings.allow_stranger_messages !== undefined) {
        document.getElementById('allowStrangerMessages').checked = settings.allow_stranger_messages == 1;
    }
    if (settings.comment_visibility) {
        document.getElementById('commentVisibility').value = settings.comment_visibility;
    }
    if (settings.repost_visibility) {
        document.getElementById('repostVisibility').value = settings.repost_visibility;
    }
    if (settings.allow_search !== undefined) {
        document.getElementById('allowSearch').checked = settings.allow_search == 1;
    }
    if (settings.notify_likes !== undefined) {
        document.getElementById('notificationsLikes').checked = settings.notify_likes == 1;
    }
    if (settings.notify_comments !== undefined) {
        document.getElementById('notificationsComments').checked = settings.notify_comments == 1;
    }
    if (settings.notify_follows !== undefined) {
        document.getElementById('notificationsFollows').checked = settings.notify_follows == 1;
    }
    if (settings.notify_system !== undefined) {
        document.getElementById('notificationsSystem').checked = settings.notify_system == 1;
    }
}

async function loadPrivacySettings() {
    try {
        // 1. 首先尝试从后端 API 获取（优先）
        try {
            const response = await fetch(BASE_URL + '/?r=mobileApi/getPrivacySettings');
            const result = await response.json();
            
            if (result.code === 0 && result.data && result.data.settings) {
                const settings = result.data.settings;
                // 应用到表单
                applySettingsToForm(settings);
                // 同步到本地缓存
                localStorage.setItem('privacy_settings', JSON.stringify(settings));
                return;
            }
        } catch (apiError) {
            console.warn('从API加载隐私设置失败，使用本地缓存:', apiError);
        }
        
        // 2. 备用：尝试从 userInfo API 获取
        try {
            const userResponse = await fetch(BASE_URL + '/?r=mobileApi/userInfo');
            const userResult = await userResponse.json();
            
            if (userResult.code === 0 && userResult.data && userResult.data.user) {
                const user = userResult.data.user;
                
                // 检查 user 对象是否有隐私设置字段
                if (user.profile_visibility || user.show_online_status !== undefined) {
                    const settings = {
                        profile_visibility: user.profile_visibility || 'public',
                        show_online_status: user.show_online_status !== undefined ? user.show_online_status : 1,
                        allow_stranger_messages: user.allow_stranger_messages !== undefined ? user.allow_stranger_messages : 1,
                        comment_visibility: user.comment_visibility || 'public',
                        repost_visibility: user.repost_visibility || 'public',
                        allow_search: user.allow_search !== undefined ? user.allow_search : 1,
                        notify_likes: user.notify_likes !== undefined ? user.notify_likes : 1,
                        notify_comments: user.notify_comments !== undefined ? user.notify_comments : 1,
                        notify_follows: user.notify_follows !== undefined ? user.notify_follows : 1,
                        notify_system: user.notify_system !== undefined ? user.notify_system : 1
                    };
                    applySettingsToForm(settings);
                    localStorage.setItem('privacy_settings', JSON.stringify(settings));
                    return;
                }
            }
        } catch (userError) {
            console.warn('从userInfo加载隐私设置失败，使用本地缓存:', userError);
        }
        
        // 3. 最后备用：从本地缓存获取
        const localSettings = localStorage.getItem('privacy_settings');
        if (localSettings) {
            const settings = JSON.parse(localSettings);
            applySettingsToForm(settings);
        }
    } catch (error) {
        console.error('加载隐私设置失败:', error);
        // 尝试使用本地缓存
        const localSettings = localStorage.getItem('privacy_settings');
        if (localSettings) {
            applySettingsToForm(JSON.parse(localSettings));
        }
    }
}

async function savePrivacySettings() {
    const settings = getFormSettings();
    
    const btn = document.getElementById('savePrivacySettings');
    btn.disabled = true;
    btn.textContent = '保存中...';
    
    try {
        // 1. 保存到本地缓存（立即生效）
        localStorage.setItem('privacy_settings', JSON.stringify(settings));
        
        // 2. 发送到后端 API（异步，不阻塞）
        try {
            const formData = new FormData();
            for (const [key, value] of Object.entries(settings)) {
                formData.append(key, value);
            }
            
            const response = await fetch(BASE_URL + '/?r=mobileApi/savePrivacySettings', {
                method: 'POST',
                body: formData,
                credentials: 'include'
            });
            
            const result = await response.json();
            
            if (result.code === 0) {
                showToast('保存成功');
            } else {
                showToast('部分保存成功（本地已保存）');
            }
        } catch (apiError) {
            console.warn('保存到服务器失败，已保存到本地:', apiError);
            showToast('已保存到本地，网络异常请稍后重试');
        }
        
        btn.disabled = false;
        btn.textContent = '保存设置';
    } catch (error) {
        console.error('保存失败:', error);
        showToast('保存失败，请重试');
        btn.disabled = false;
        btn.textContent = '保存设置';
    }
}
