// Background script for Overleaf Document Reader Extension

let latestDocumentContent = '';
let lastUpdateTime = 0;
let openedTabs = new Set(); // Track tabs where we've already opened the sidepanel

// Listen for messages from content script
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    if (request.type === 'DOCUMENT_CONTENT_UPDATED') {
        latestDocumentContent = request.content;
        lastUpdateTime = request.timestamp;
        console.log('[Background] Document content updated, length:', request.content.length);

        // Store in local storage for persistence
        chrome.storage.local.set({
            documentContent: latestDocumentContent,
            lastUpdate: lastUpdateTime
        });

        // Notify popup if it's open
        chrome.runtime.sendMessage({
            type: 'CONTENT_UPDATE_NOTIFICATION',
            length: latestDocumentContent.length,
            timestamp: lastUpdateTime
        }).catch(() => {
            // Popup might not be open, ignore error
        });
    } else if (request.type === 'EDITOR_LINES_INSERTED') {
        // Forward line insertion event to sidepanel
        console.log('[Background] Forwarding EDITOR_LINES_INSERTED to sidepanel:', request, 'source:', request.source, 'file:', request.fileName);
        chrome.runtime.sendMessage({
            type: 'DOC_LINE_CHANGED',
            changeType: 'insert',
            lineNumber: request.lineNumber,
            count: request.count,
            insertType: request.insertType,
            prevLineNumber: request.prevLineNumber,
            currentLineNumber: request.currentLineNumber,
            source: request.source,  // 传递来源标记
            fileName: request.fileName  // 传递文件名，用于防止文件切换时的竞态条件
        }).catch(() => {
            // Sidepanel might not be open, ignore error
        });
    } else if (request.type === 'EDITOR_LINES_DELETED') {
        // Forward line deletion event to sidepanel
        console.log('[Background] Forwarding EDITOR_LINES_DELETED to sidepanel:', request, 'source:', request.source, 'file:', request.fileName);
        chrome.runtime.sendMessage({
            type: 'DOC_LINE_CHANGED',
            changeType: 'delete',
            lineNumber: request.lineNumber,
            count: request.count,
            deleteType: request.deleteType,
            mergeToLine: request.mergeToLine,
            source: request.source,  // 传递来源标记
            fileName: request.fileName  // 传递文件名，用于防止文件切换时的竞态条件
        }).catch(() => {
            // Sidepanel might not be open, ignore error
        });
    } else if (request.type === 'EDITOR_CURSOR_LINE_CHANGED') {
        // Forward cursor line change event to sidepanel
        chrome.runtime.sendMessage({
            type: 'CURSOR_LINE_CHANGED',
            lineNumber: request.lineNumber
        }).catch(() => {
            // Sidepanel might not be open, ignore error
        });
    } else if (request.type === 'FILE_CHANGED') {
        // Forward file change event to sidepanel
        console.log('[Background] Forwarding FILE_CHANGED to sidepanel:', request.fileName);
        chrome.runtime.sendMessage({
            type: 'FILE_CHANGED',
            fileName: request.fileName
        }).catch(() => {
            // Sidepanel might not be open, ignore error
        });
    } else if (request.type === 'COMPACT_VIEW_MESSAGE') {
        // Forward compact view messages to sidepanel
        console.log('[Background] Forwarding COMPACT_VIEW_MESSAGE to sidepanel:', request.action);
        chrome.runtime.sendMessage({
            type: 'COMPACT_VIEW_MESSAGE',
            action: request.action,
            content: request.content,
            lineNumber: request.lineNumber
        }).catch(() => {
            // Sidepanel might not be open, ignore error
        });
    } else if (request.type === 'AUTO_OPEN_SIDEPANEL') {
        // Content script requests auto-opening the sidepanel
        const tabId = sender.tab?.id;
        if (tabId && !openedTabs.has(tabId)) {
            chrome.sidePanel.open({ tabId: tabId })
                .then(() => {
                    openedTabs.add(tabId);
                    console.log('[Background] Auto-opened sidepanel for tab:', tabId);
                })
                .catch(err => {
                    console.log('[Background] Could not auto-open sidepanel:', err.message);
                });
        }
    } else if (request.type === 'OPEN_SIDEPANEL_FROM_BUTTON') {
        // User clicked the floating button
        const tabId = sender.tab?.id;
        if (tabId) {
            chrome.sidePanel.open({ tabId: tabId })
                .then(() => {
                    openedTabs.add(tabId);
                    console.log('[Background] Opened sidepanel from floating button for tab:', tabId);
                    // Notify content script that sidepanel is open
                    chrome.tabs.sendMessage(tabId, {
                        type: 'SIDEPANEL_STATE_CHANGED',
                        isOpen: true
                    }).catch(() => {});
                })
                .catch(err => {
                    console.error('[Background] Failed to open sidepanel from button:', err.message);
                });
        }
    } else if (request.type === 'SIDEPANEL_OPENED') {
        // Sidepanel notifies that it's opened
        const tabId = request.tabId;
        if (tabId) {
            chrome.tabs.sendMessage(tabId, {
                type: 'SIDEPANEL_STATE_CHANGED',
                isOpen: true
            }).catch(() => {});
        }
    } else if (request.type === 'SIDEPANEL_CLOSED') {
        // Sidepanel notifies that it's closing
        const tabId = request.tabId;
        if (tabId) {
            chrome.tabs.sendMessage(tabId, {
                type: 'SIDEPANEL_STATE_CHANGED',
                isOpen: false
            }).catch(() => {});
        }
    }
});

// Handle requests from popup
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    if (request.type === 'GET_STORED_CONTENT') {
        chrome.storage.local.get(['documentContent', 'lastUpdate'], (result) => {
            sendResponse({
                content: result.documentContent || '',
                lastUpdate: result.lastUpdate || 0
            });
        });
        return true; // Keep message channel open
    }
});

// Clean up tab tracking when tab is closed (don't clear storage)
chrome.tabs.onRemoved.addListener((tabId, removeInfo) => {
    openedTabs.delete(tabId);
});

// Handle extension icon click to open sidepanel
chrome.action.onClicked.addListener(async (tab) => {
    // Open the side panel for the current tab
    try {
        await chrome.sidePanel.open({ tabId: tab.id });
        console.log('[Background] Side panel opened for tab:', tab.id);
    } catch (error) {
        console.error('[Background] Failed to open side panel:', error);
    }
});

// Handle keyboard shortcuts
chrome.commands.onCommand.addListener(async (command) => {
    console.log('[Background] Command received:', command);

    const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });

    if (command === 'translate-selection') {
        try {
            // Get selected text from content script first
            chrome.tabs.sendMessage(tab.id, { type: 'GET_SELECTION' }, async (response) => {
                const selectedText = response?.selectedText || '';

                // Always try to open sidepanel
                await chrome.sidePanel.open({ tabId: tab.id });
                openedTabs.add(tab.id);
                console.log('[Background] Opened sidepanel for translation shortcut');

                // Wait a bit longer to ensure sidepanel is ready
                setTimeout(() => {
                    chrome.runtime.sendMessage({
                        type: 'TRANSLATION_SHORTCUT',
                        selectedText: selectedText
                    }).catch(() => {
                        console.log('[Background] Sidepanel not ready for translation shortcut');
                    });
                }, 300);
            });
        } catch (error) {
            console.error('[Background] Failed to open side panel:', error);
        }
    } else if (command === 'modify-selection') {
        try {
            // Get selected text from content script first
            chrome.tabs.sendMessage(tab.id, { type: 'GET_SELECTION' }, async (response) => {
                const selectedText = response?.selectedText || '';

                // Always try to open sidepanel
                await chrome.sidePanel.open({ tabId: tab.id });
                openedTabs.add(tab.id);
                console.log('[Background] Opened sidepanel for modification shortcut');

                // Wait a bit longer to ensure sidepanel is ready
                setTimeout(() => {
                    chrome.runtime.sendMessage({
                        type: 'MODIFICATION_SHORTCUT',
                        selectedText: selectedText
                    }).catch(() => {
                        console.log('[Background] Sidepanel not ready for modification shortcut');
                    });
                }, 300);
            });
        } catch (error) {
            console.error('[Background] Failed to open side panel:', error);
        }
    }
});

// Create context menus
chrome.runtime.onInstalled.addListener(() => {
    chrome.contextMenus.create({
        id: "auto-cite",
        title: "自动引用",
        contexts: ["selection"]
    });
});

// Handle context menu clicks
chrome.contextMenus.onClicked.addListener(async (info, tab) => {
    if (info.menuItemId === "auto-cite" && info.selectionText) {
        try {
            // Always try to open sidepanel first
            await chrome.sidePanel.open({ tabId: tab.id });
            openedTabs.add(tab.id);
            console.log('[Background] Opened sidepanel for context menu auto-cite');

            // Wait a bit longer to ensure sidepanel is ready, then send with selected text
            setTimeout(() => {
                chrome.runtime.sendMessage({
                    type: 'AUTO_CITE_SHORTCUT',
                    selectedText: info.selectionText
                }).catch(() => {
                    console.log('[Background] Sidepanel not ready for context menu auto-cite');
                });
            }, 300);
        } catch (error) {
            console.error('[Background] Failed to open side panel:', error);
        }
    }
});

// Show extension is loaded
console.log('[Background] Overleaf Document Reader extension loaded');