// InsightFlow Chrome Extension - Options Script

document.addEventListener('DOMContentLoaded', () => {
    // 加载保存的设置
    loadSettings();
    
    // 绑定事件
    document.getElementById('saveBtn').addEventListener('click', saveSettings);
    document.getElementById('testBtn').addEventListener('click', testConnection);
});

// 加载设置
async function loadSettings() {
    const settings = await chrome.storage.sync.get([
        'serverUrl',
        'apiKey',
        'showFloatingButton',
        'autoSync'
    ]);
    
    document.getElementById('serverUrl').value = settings.serverUrl || '';
    document.getElementById('apiKey').value = settings.apiKey || '';
    document.getElementById('showFloatingButton').checked = settings.showFloatingButton !== false;
    document.getElementById('autoSync').checked = settings.autoSync !== false;
}

// 保存设置
async function saveSettings() {
    const serverUrl = document.getElementById('serverUrl').value.trim();
    const apiKey = document.getElementById('apiKey').value.trim();
    const showFloatingButton = document.getElementById('showFloatingButton').checked;
    const autoSync = document.getElementById('autoSync').checked;
    
    // 验证
    if (!serverUrl) {
        showStatus('请输入服务器地址', 'error');
        return;
    }
    
    if (!apiKey) {
        showStatus('请输入 API 令牌', 'error');
        return;
    }
    
    // 确保 URL 格式正确
    let formattedUrl = serverUrl;
    if (!formattedUrl.startsWith('http://') && !formattedUrl.startsWith('https://')) {
        formattedUrl = 'https://' + formattedUrl;
    }
    
    // 移除末尾的斜杠
    formattedUrl = formattedUrl.replace(/\/$/, '');
    
    // 保存
    await chrome.storage.sync.set({
        serverUrl: formattedUrl,
        apiKey: apiKey,
        showFloatingButton: showFloatingButton,
        autoSync: autoSync
    });
    
    showStatus('设置已保存！', 'success');
}

// 测试连接
async function testConnection() {
    const serverUrl = document.getElementById('serverUrl').value.trim();
    const apiKey = document.getElementById('apiKey').value.trim();
    
    if (!serverUrl || !apiKey) {
        showStatus('请先填写服务器地址和 API 令牌', 'error');
        return;
    }
    
    showStatus('正在测试连接...', '');
    
    try {
        const response = await fetch(`${serverUrl}/api/v1/health`, {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json'
            }
        });
        
        if (response.ok) {
            const data = await response.json();
            showStatus(`连接成功！服务器版本: ${data.version || 'unknown'}`, 'success');
        } else {
            showStatus('连接失败：服务器返回错误', 'error');
        }
    } catch (error) {
        showStatus('连接失败：' + error.message, 'error');
    }
}

// 显示状态
function showStatus(message, type) {
    const statusEl = document.getElementById('status');
    statusEl.textContent = message;
    statusEl.className = 'status';
    
    if (type) {
        statusEl.classList.add(type);
    }
}