// InsightFlow Chrome Extension - Popup Script

document.addEventListener('DOMContentLoaded', async () => {
    // 获取当前标签页信息
    const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
    
    // 更新页面信息
    document.getElementById('pageTitle').textContent = tab.title || '未知标题';
    document.getElementById('pageUrl').textContent = tab.url || '';
    
    // 获取页面统计
    updateStats();
    
    // 加载最近的剪辑
    loadRecentClips();
    
    // 绑定按钮事件
    document.getElementById('clipPageBtn').addEventListener('click', clipPage);
    document.getElementById('clipSelectionBtn').addEventListener('click', clipSelection);
    document.getElementById('openOptions').addEventListener('click', openOptions);
});

// 更新统计信息
async function updateStats() {
    const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
    
    // 获取字数统计
    try {
        const response = await chrome.tabs.sendMessage(tab.id, { action: 'extractContent' });
        if (response.success) {
            document.getElementById('wordCount').textContent = response.data.wordCount || 0;
        }
    } catch (error) {
        console.log('Content script not available');
    }
    
    // 获取待同步数量
    const result = await chrome.storage.local.get(['clips']);
    const clips = result.clips || [];
    const pendingCount = clips.filter(c => !c.synced).length;
    document.getElementById('pendingCount').textContent = pendingCount;
}

// 保存整个页面
async function clipPage() {
    setLoading(true);
    
    try {
        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
        
        // 发送消息给 background script
        const response = await chrome.runtime.sendMessage({ action: 'clipPage' });
        
        if (response.success) {
            showStatus('页面已保存！', 'success');
            loadRecentClips();
            updateStats();
        } else {
            showStatus(response.error || '保存失败', 'error');
        }
    } catch (error) {
        showStatus('保存失败: ' + error.message, 'error');
    } finally {
        setLoading(false);
    }
}

// 保存选中内容
async function clipSelection() {
    setLoading(true);
    
    try {
        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
        
        const response = await chrome.runtime.sendMessage({ action: 'clipSelection' });
        
        if (response.success) {
            showStatus('选中内容已保存！', 'success');
            loadRecentClips();
            updateStats();
        } else {
            showStatus(response.error || '保存失败', 'error');
        }
    } catch (error) {
        showStatus('保存失败: ' + error.message, 'error');
    } finally {
        setLoading(false);
    }
}

// 加载最近的剪辑
async function loadRecentClips() {
    const result = await chrome.storage.local.get(['clips']);
    const clips = result.clips || [];
    
    const clipsList = document.getElementById('clipsList');
    clipsList.innerHTML = '';
    
    // 只显示最近5条
    const recentClips = clips.slice(0, 5);
    
    for (const clip of recentClips) {
        const clipEl = document.createElement('div');
        clipEl.className = 'clip-item';
        
        const title = clip.title || '未命名';
        const time = new Date(clip.extractedAt).toLocaleString('zh-CN');
        const statusClass = clip.synced ? 'synced' : 'pending';
        const statusText = clip.synced ? '已同步' : '待同步';
        
        clipEl.innerHTML = `
            <div class="clip-title">${escapeHtml(title)}</div>
            <div class="clip-time">${time}</div>
            <span class="clip-status ${statusClass}">${statusText}</span>
        `;
        
        clipsList.appendChild(clipEl);
    }
}

// 打开设置页面
function openOptions(e) {
    e.preventDefault();
    chrome.runtime.openOptionsPage();
}

// 显示状态消息
function showStatus(message, type) {
    const statusEl = document.getElementById('status');
    statusEl.textContent = message;
    statusEl.className = 'status ' + type;
    
    setTimeout(() => {
        statusEl.textContent = '';
        statusEl.className = 'status';
    }, 3000);
}

// 设置加载状态
function setLoading(loading) {
    const loadingEl = document.getElementById('loading');
    if (loading) {
        loadingEl.classList.add('active');
    } else {
        loadingEl.classList.remove('active');
    }
}

// HTML 转义
function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}