// Auto-Cite module for Overleaf Chrome Extension
// 自动引用功能

// 选中的论文列表
let selectedPapers = [];

// 重置自动引用页面
function resetAutoCitePage() {
    document.getElementById('autocite-loading').style.display = 'block';
    document.getElementById('autocite-selection').style.display = 'none';
    document.getElementById('autocite-bibtex-display').style.display = 'none';
    document.getElementById('autocite-keywords').textContent = '';
    document.getElementById('autocite-keywords-display').textContent = '';
    document.getElementById('paper-list').innerHTML = '';
    document.getElementById('selected-count').textContent = '0';
    document.getElementById('autocite-bibtex-content').textContent = '';
    document.getElementById('autocite-citation-keys').innerHTML = '';
    selectedPapers = [];
}

// 显示 BibTeX（当无法自动添加时）
function showBibTeXDisplay(citationKeys, bibEntries) {
    // 隐藏论文选择，显示 BibTeX
    document.getElementById('autocite-selection').style.display = 'none';
    document.getElementById('autocite-bibtex-display').style.display = 'block';

    // 显示 BibTeX 内容
    const bibContent = bibEntries.join('\n\n');
    document.getElementById('autocite-bibtex-content').textContent = bibContent;

    // 显示引用键
    const keysContainer = document.getElementById('autocite-citation-keys');
    keysContainer.innerHTML = '';
    for (const key of citationKeys) {
        const keyTag = document.createElement('span');
        keyTag.className = 'px-3 py-1.5 bg-primary-100 text-primary-700 text-sm rounded-lg font-mono cursor-pointer hover:bg-primary-200 transition-colors';
        keyTag.textContent = `\\cite{${key}}`;
        keyTag.title = '点击复制';
        keyTag.addEventListener('click', async () => {
            try {
                await navigator.clipboard.writeText(`\\cite{${key}}`);
                showSuccess('已复制引用键！');
            } catch (err) {
                console.error('复制失败:', err);
            }
        });
        keysContainer.appendChild(keyTag);
    }
}

// Toggle paper selection
function togglePaperSelection(paperItem, isSelected) {
    if (isSelected) {
        paperItem.classList.add('selected');
        selectedPapers.push(paperItem.paperData);
    } else {
        paperItem.classList.remove('selected');
        const index = selectedPapers.findIndex(p => p.doi === paperItem.paperData.doi);
        if (index > -1) {
            selectedPapers.splice(index, 1);
        }
    }

    // Update count
    document.getElementById('selected-count').textContent = selectedPapers.length;
}

// Handle auto-cite confirm
async function handleAutoCiteConfirm() {
    if (selectedPapers.length === 0) {
        showError('请至少选择一篇论文');
        return;
    }

    console.log('[Sidepanel] Adding citations for', selectedPapers.length, 'papers');

    // Show loading
    showSuccess(`正在添加 ${selectedPapers.length} 篇引用...`, true);

    const citationKeys = [];
    const bibEntries = [];

    // Generate citation keys and BibTeX entries
    for (const paper of selectedPapers) {
        const firstAuthor = paper.authors[0] || 'Unknown';
        const lastName = firstAuthor.split(' ').pop();
        const citationKey = `${lastName}${paper.year}`.replace(/[^a-zA-Z0-9]/g, '');

        const bibEntry = `@article{${citationKey},
  title={${paper.title}},
  author={${paper.authors.join(' and ')}},
  journal={${paper.journal}},
  year={${paper.year}},
  doi={${paper.doi}}
}`;

        citationKeys.push(citationKey);
        bibEntries.push(bibEntry);
    }

    console.log('[Sidepanel] Citation keys:', citationKeys);

    try {
        // Send all citations at once
        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });

        await new Promise((resolve, reject) => {
            chrome.tabs.sendMessage(tab.id, {
                type: 'ADD_MULTIPLE_CITATIONS',
                citationKeys: citationKeys,
                bibEntries: bibEntries
            }, (response) => {
                if (chrome.runtime.lastError) {
                    reject(new Error(chrome.runtime.lastError.message));
                } else if (response && response.success) {
                    resolve();
                } else {
                    reject(new Error(response?.error || '添加引用失败'));
                }
            });
        });

        showSuccess(`成功添加 ${citationKeys.length} 篇引用！`);
        setTimeout(() => {
            goToHomePage();
        }, 2000);

    } catch (error) {
        console.error('[Sidepanel] Error adding citations:', error);

        // 检查是否是找不到 bib 文件的错误
        const errorMessage = error.message.toLowerCase();
        if (errorMessage.includes('bib') || errorMessage.includes('找不到') || errorMessage.includes('not found')) {
            // 显示 BibTeX 供用户手动复制
            showBibTeXDisplay(citationKeys, bibEntries);
            showSuccess('请手动复制 BibTeX 到您的参考文献文件');
        } else {
            // 其他错误也显示 BibTeX，方便用户
            showBibTeXDisplay(citationKeys, bibEntries);
            showError('自动添加失败，请手动复制');
        }
    }
}

// Handle paper selection (legacy - keeping for backward compatibility)
async function handlePaperSelection(paper) {
    console.log('[Sidepanel] Paper selected:', paper.title);

    // Show loading
    showSuccess('正在添加引用...', true);

    try {
        // Generate citation key from first author last name and year
        const firstAuthor = paper.authors[0] || 'Unknown';
        const lastName = firstAuthor.split(' ').pop();
        const citationKey = `${lastName}${paper.year}`.replace(/[^a-zA-Z0-9]/g, '');

        // Format BibTeX entry
        const bibEntry = `@article{${citationKey},
  title={${paper.title}},
  author={${paper.authors.join(' and ')}},
  journal={${paper.journal}},
  year={${paper.year}},
  doi={${paper.doi}}
}`;

        console.log('[Sidepanel] Sending ADD_CITATION_TO_BIB message with key:', citationKey);

        // Send message to content script to add citation
        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });

        chrome.tabs.sendMessage(tab.id, {
            type: 'ADD_CITATION_TO_BIB',
            citationKey: citationKey,
            bibEntry: bibEntry
        }, (response) => {
            console.log('[Sidepanel] ADD_CITATION_TO_BIB response:', response);

            if (chrome.runtime.lastError) {
                console.error('[Sidepanel] Error adding citation:', chrome.runtime.lastError);
                showError('添加引用失败: ' + chrome.runtime.lastError.message);
            } else if (response && response.success) {
                showSuccess(`引用已添加！引用键: ${citationKey}`);
                setTimeout(() => {
                    goToHomePage();
                }, 2000);
            } else {
                showError(response?.error || '添加引用失败，请检查是否存在references.bib文件');
            }
        });
    } catch (error) {
        console.error('[Sidepanel] Error in handlePaperSelection:', error);
        showError('添加引用失败: ' + error.message);
    }
}

// 初始化自动引用页面事件处理器
function initAutoCiteEventHandlers() {
    // Auto-cite back button
    document.getElementById('autocite-back-btn').addEventListener('click', () => {
        goToHomePage();
    });

    // Auto-cite cancel button
    document.getElementById('autocite-cancel-btn').addEventListener('click', () => {
        goToHomePage();
    });

    // Auto-cite confirm button
    document.getElementById('autocite-confirm-btn').addEventListener('click', handleAutoCiteConfirm);

    // BibTeX copy button
    document.getElementById('autocite-copy-btn').addEventListener('click', async () => {
        const bibContent = document.getElementById('autocite-bibtex-content').textContent;
        try {
            await navigator.clipboard.writeText(bibContent);
            showSuccess('BibTeX 已复制到剪贴板！');
        } catch (err) {
            console.error('复制失败:', err);
            showError('复制失败，请手动选择复制');
        }
    });

    // BibTeX done button
    document.getElementById('autocite-done-btn').addEventListener('click', () => {
        goToHomePage();
    });
}
