/**
 * FocusFeed Background Script
 * Handles context menus and badge updates.
 */

// Create Context Menu on install
chrome.runtime.onInstalled.addListener((details) => {
    // Context Menu
    chrome.contextMenus.create({
        id: "add-to-focusfeed",
        title: "Zu FocusFeed hinzufügen: '%s'",
        contexts: ["selection"]
    });

    // Open Welcome Page
    if (details.reason === "install") {
        chrome.tabs.create({
            url: chrome.runtime.getURL("welcome.html")
        });
    }
});

// Handle Context Menu click
chrome.contextMenus.onClicked.addListener((info, tab) => {
    if (info.menuItemId === "add-to-focusfeed" && info.selectionText) {
        const newKeyword = info.selectionText.trim().toLowerCase();
        
        chrome.storage.local.get(['customKeywords'], (result) => {
            const keywords = result.customKeywords || [];
            if (!keywords.includes(newKeyword)) {
                keywords.push(newKeyword);
                chrome.storage.local.set({ customKeywords: keywords }, () => {
                    // Notify the user or content script if needed
                    console.log(`Added "${newKeyword}" to FocusFeed`);
                });
            }
        });
    }
});

// Listen for block events to update badge
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
    if (message.type === 'BLOCK_EVENT' && sender.tab) {
        chrome.action.setBadgeText({
            text: message.count.toString(),
            tabId: sender.tab.id
        });
        chrome.action.setBadgeBackgroundColor({
            color: '#00f2ff',
            tabId: sender.tab.id
        });
    }
});
