// Content script for ArticleBin extension
// Listens for token sync messages from the web app

(function () {
    // Listen for messages from the web page
    window.addEventListener('message', async (event) => {
        // Only accept messages from the same origin
        if (event.source !== window) return;

        // Check for our specific message type
        if (event.data && event.data.type === 'ARTICLEBIN_TOKEN_SYNC') {
            const { apiBase, apiToken } = event.data;

            if (!apiBase || !apiToken) {
                window.postMessage({
                    type: 'ARTICLEBIN_TOKEN_SYNC_RESPONSE',
                    success: false,
                    error: 'Missing apiBase or apiToken'
                }, '*');
                return;
            }

            try {
                // Save to chrome storage
                await chrome.storage.sync.set({ apiBase, apiToken });

                // Send success response back to the page
                window.postMessage({
                    type: 'ARTICLEBIN_TOKEN_SYNC_RESPONSE',
                    success: true
                }, '*');
            } catch (error) {
                window.postMessage({
                    type: 'ARTICLEBIN_TOKEN_SYNC_RESPONSE',
                    success: false,
                    error: error.message
                }, '*');
            }
        }
    });

    // Notify the page that the extension is available
    window.postMessage({
        type: 'ARTICLEBIN_EXTENSION_READY'
    }, '*');
})();
