// Background script for ArticleBin extension

chrome.runtime.onInstalled.addListener(() => {
    chrome.contextMenus.create({
        id: "save-to-articlebin",
        title: "Save to ArticleBin",
        contexts: ["page", "link"]
    });
});

chrome.contextMenus.onClicked.addListener(async (info, tab) => {
    if (info.menuItemId === "save-to-articlebin") {
        const url = info.linkUrl || info.pageUrl || tab.url;
        await saveToArticleBin(url);
    }
});

async function saveToArticleBin(url) {
    const { apiBase, apiToken } = await chrome.storage.sync.get(['apiBase', 'apiToken']);

    if (!apiBase || !apiToken) {
        // We can't easily show an alert from background in MV3
        // But we can trigger a notification
        chrome.notifications.create({
            type: 'basic',
            iconUrl: 'icons/icon128.png',
            title: 'ArticleBin Error',
            message: 'Please configure API settings in the extension popup.'
        });
        return;
    }

    try {
        const response = await fetch(`${apiBase}/api/articles`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${apiToken}`
            },
            body: JSON.stringify({ url })
        });

        const data = await response.json();
        if (data.success) {
            chrome.notifications.create({
                type: 'basic',
                iconUrl: 'icons/icon128.png',
                title: 'ArticleBin',
                message: 'Saved successfully!'
            });
        } else {
            chrome.notifications.create({
                type: 'basic',
                iconUrl: 'icons/icon128.png',
                title: 'ArticleBin Error',
                message: 'Error: ' + (data.error || 'Unknown error')
            });
        }
    } catch (error) {
        chrome.notifications.create({
            type: 'basic',
            iconUrl: 'icons/icon128.png',
            title: 'ArticleBin Error',
            message: 'Network error: ' + error.message
        });
    }
}
