// Pidgey Assist — Background Service Worker
// Opens the side panel when the extension icon is clicked

chrome.sidePanel.setPanelBehavior({ openPanelOnActionClick: true });

// Track active tab URL and send to side panel
chrome.tabs.onActivated.addListener(async (activeInfo) => {
    try {
        const tab = await chrome.tabs.get(activeInfo.tabId);
        if (tab.url) {
            chrome.storage.local.set({ currentUrl: tab.url });
        }
    } catch { }
});

chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
    if (changeInfo.url) {
        chrome.storage.local.set({ currentUrl: changeInfo.url });
    }
});

// Setup Context Menu for "Right-Click Strike"
chrome.runtime.onInstalled.addListener(() => {
    chrome.runtime.setUninstallURL('https://pidgeyassist.com/uninstall.html');

    // Parent Menu
    chrome.contextMenus.create({
        id: 'pidgey-parent',
        title: 'Ask Pidgey...',
        contexts: ['selection']
    });

    // Sub-items
    chrome.contextMenus.create({
        id: 'pidgey-summarize',
        parentId: 'pidgey-parent',
        title: '📝 Summarize with Pidgey',
        contexts: ['selection']
    });
    
    chrome.contextMenus.create({
        id: 'pidgey-crm',
        parentId: 'pidgey-parent',
        title: '🚀 Add to CRM (Growth Persona)',
        contexts: ['selection']
    });
    
    chrome.contextMenus.create({
        id: 'pidgey-chart',
        parentId: 'pidgey-parent',
        title: '📈 Analyze (Trader Persona)',
        contexts: ['selection']
    });
});

chrome.contextMenus.onClicked.addListener((info, tab) => {
    const selectedText = info.selectionText;
    if (!selectedText) return;

    // Open side panel if closed
    chrome.sidePanel.open({ tabId: tab.id });

    const sanitizedText = selectedText.replace(/</g, "&lt;").replace(/>/g, "&gt;");
    let command = '';
    let personaTarget = '';

    if (info.menuItemId === 'pidgey-summarize') {
        command = `Hey Pidgey, I just highlighted this: "${sanitizedText}". Can you give me a bulleted summary?`;
        personaTarget = 'assist';
    } else if (info.menuItemId === 'pidgey-crm') {
        command = `I found a new lead: "${sanitizedText}". Please add this to my CRM.`;
        personaTarget = 'growth';
    } else if (info.menuItemId === 'pidgey-chart') {
        command = `Traders watch: "${sanitizedText}". Analyze this asset/data and give me a read on it.`;
        personaTarget = 'trader';
    } else {
        return; // Clicked the parent or unknown item
    }

    chrome.storage.local.set({
        pidgeyStrikeCommand: command,
        pidgeyForcePersona: personaTarget
    });
});
