/**
 * background.js (Service Worker)
 * Handles events and message passing for Grain of Salt.
 */

// Listen for messages from the web app (if applicable) or other parts of the extension
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    if (request.action === 'LOGIN_SUCCESS') {
        // Forward to side panel or popup if necessary
        // Since side panel shares storage, it might poll or react to storage changes.
        // However, we can also actively notify if the side panel is open.
        chrome.runtime.sendMessage({ action: 'REFRESH_AUTH_STATE' }).catch(() => {
            // Ignore error if no receiver (side panel closed)
        });
    }
});

// Cookie change listener to detect login/logout on the main site
chrome.cookies.onChanged.addListener((changeInfo) => {
    if (
        changeInfo.cookie.domain.includes('localhost') ||
        changeInfo.cookie.domain.includes('grainofsaltai') ||
        changeInfo.cookie.domain.includes('grainofsalt') ||
        changeInfo.cookie.domain.includes('vercel.app')
    ) {
        // Check for Supabase Auth Token (fuzzy match)
        if (
            (changeInfo.cookie.name.startsWith('sb-') && changeInfo.cookie.name.endsWith('-auth-token')) ||
            changeInfo.cookie.name === 'supabase-auth-token'
        ) {
            // Notify views to refresh auth state
            chrome.runtime.sendMessage({ action: 'REFRESH_AUTH_STATE' }).catch(() => {
                // Ignore error
            });
        }
    }
});

// Setup side panel behavior
chrome.sidePanel.setPanelBehavior({ openPanelOnActionClick: true })
    .catch((error) => console.error(error));

console.log('Grain of Salt Background Service Worker Active');
