/**
 * @file serviceWorker.js
 * @description Background service worker för StatusNotifier Extension
 * 
 * Author: Linus Olofsson - Iver 
 * Date: 2025-07-08 
 * Last modified: Linus Olofsson (2026-02-24) - Spark API integration via token scraping
 * 
 * @purpose Hantera bakgrundsprocesser som behöver köras även när popupen är stängd
 * @note Använder offscreen document för att hålla service worker aktiv
 * @note Kombinerar chrome.alarms API med offscreen documents för maximal tillförlitlighet
 * @note Hämtar Spark token från spark.iver.com localStorage via content script — INGA nya flikar
 */

import { getSparkToken, hasValidSparkToken, saveSparkToken, clearSparkToken, makeAuthenticatedRequest, getLoggedInUserId, SPARK_API_BASE } from '../api/auth.js';
import { getTicketTimeSheets, getTicketsFromView, getSavedViews, getExpectedArticleGuid, getArticleNameByGuid, OVERTIME_ARTICLE_GUIDS } from '../api/ticketApi.js';

// Timer-variabler
let timerActive = false;
let timerInterval = null;
let timerEndTime = null;
let timerDuration = 0; // i millisekunder

// Offscreen document-variabler
let offscreenDocumentCreated = false;
let lastHeartbeat = Date.now();
let offscreenReconnectAttempts = 0;
const MAX_RECONNECT_ATTEMPTS = 3;
const HEARTBEAT_INTERVAL = 25000; // 25 sekunder
const HEARTBEAT_TIMEOUT = 35000; // 35 sekunder

// Lyssna efter meddelanden från popup och offscreen document
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    console.log('Service worker received message:', request);
    
    // Hantera offscreen document-meddelanden
    if (request.action === 'offscreenLoaded') {
        console.log('Offscreen document loaded at', new Date(request.timestamp).toISOString());
        offscreenDocumentCreated = true;
        lastHeartbeat = Date.now();
        offscreenReconnectAttempts = 0;
        sendResponse({ status: 'acknowledged' });
        return true;
    }
    
    if (request.action === 'offscreenHeartbeat') {
        console.log('Received heartbeat from offscreen document');
        lastHeartbeat = Date.now();
        sendResponse({ status: 'acknowledged' });
        return true;
    }
    
    // Hantera timer-kommandon
    if (request.action === 'startTimer') {
        console.log('Received startTimer request with duration:', request.duration);
        
        // Använd lokala variabler för att undvika problem med undefined
        const duration = request.duration;
        
        // Starta timer och skicka svar
        startTimer(duration)
            .then(() => {
                console.log('Timer started successfully');
                sendResponse({ 
                    success: true, 
                    endTime: timerEndTime,
                    message: 'Timer started successfully' 
                });
            })
            .catch(error => {
                console.error('Error starting timer:', error);
                sendResponse({ 
                    success: false, 
                    error: error.message || 'Unknown error',
                    message: 'Failed to start timer' 
                });
            });
        
        return true; // Indikera att vi kommer att skicka ett asynkront svar
    }
    
    if (request.action === 'stopTimer') {
        stopTimer()
            .then(() => {
                sendResponse({ success: true, message: 'Timer stopped' });
            })
            .catch(error => {
                console.error('Error stopping timer:', error);
                sendResponse({ success: false, error: error.message });
            });
        
        return true;
    }
    
    if (request.action === 'getTimerStatus') {
        // Hämta aktuell timer-status från storage för att säkerställa att vi har senaste värdena
        chrome.storage.local.get(['timerActive', 'timerEndTime', 'timerDuration'], result => {
            const localTimerActive = result.timerActive !== undefined ? result.timerActive : timerActive;
            const localTimerEndTime = result.timerEndTime !== undefined ? result.timerEndTime : timerEndTime;
            const localTimerDuration = result.timerDuration !== undefined ? result.timerDuration : timerDuration;
            
            console.log('Timer status request:', { 
                active: localTimerActive, 
                endTime: localTimerEndTime ? new Date(localTimerEndTime).toISOString() : null,
                timeLeft: localTimerEndTime ? Math.max(0, localTimerEndTime - Date.now()) : 0
            });
            
            sendResponse({
                active: localTimerActive,
                endTime: localTimerEndTime,
                timeLeft: localTimerEndTime ? Math.max(0, localTimerEndTime - Date.now()) : 0,
                duration: localTimerDuration
            });
        });
        
        return true;
    }
    
    if (request.action === 'checkItems') {
        fetchAndUpdateTicketsFromAPI()
            .then(updateResult => {
                sendResponse({ status: 'Items check completed', result: updateResult });
            })
            .catch(error => {
                console.error('Error in checkItems:', error);
                sendResponse({ status: 'Items check failed', error: error.message });
            });
        return true;
    }
    
    if (request.action === 'testNotification') {
        testNotification();
        sendResponse({ status: 'Test notification triggered' });
    }
    
    if (request.action === 'getTicketAuditLogs') {
        const ticketGuid = request.ticketGuid;
        const customerId = request.customerId;
        const auditUrl = customerId
            ? `${SPARK_API_BASE}/Tickets/${ticketGuid}/${customerId}/AuditLogs?getAll=false`
            : `${SPARK_API_BASE}/Tickets/${ticketGuid}/AuditLogs`;
        makeAuthenticatedRequest(auditUrl, { method: 'GET' })
            .then(logs => sendResponse({ success: true, data: logs || [] }))
            .catch(err => {
                console.warn('Error fetching audit logs:', err.message);
                sendResponse({ success: false, data: [] });
            });
        return true;
    }

    if (request.action === 'getTicketPosts') {
        const ticketGuid = request.ticketGuid;
        makeAuthenticatedRequest(`${SPARK_API_BASE}/Tickets/${ticketGuid}/Posts`, { method: 'GET' })
            .then(posts => sendResponse({ success: true, data: posts || [] }))
            .catch(err => {
                console.warn('Error fetching ticket posts:', err.message);
                sendResponse({ success: false, data: [] });
            });
        return true;
    }

    if (request.action === 'getTicketTexts') {
        const ticketGuid = request.ticketGuid;
        makeAuthenticatedRequest(`${SPARK_API_BASE}/Tickets/${ticketGuid}/Texts`, { method: 'GET' })
            .then(texts => sendResponse({ success: true, data: texts || {} }))
            .catch(err => {
                console.warn('Error fetching ticket texts:', err.message);
                sendResponse({ success: false, data: {} });
            });
        return true;
    }

    if (request.action === 'getTicketFullEmail') {
        const emailId = request.emailId;
        makeAuthenticatedRequest(`${SPARK_API_BASE}/TicketEmails/FullEmail/${emailId}`, { method: 'GET' })
            .then(email => sendResponse({ success: true, data: email || {} }))
            .catch(err => {
                console.warn('Error fetching ticket email:', err.message);
                sendResponse({ success: false, data: {} });
            });
        return true;
    }

    // Hantera meddelanden från content scripts
    if (request.action === 'contentScriptReady') {
        console.log('Content script ready from URL:', request.url);
        sendResponse({ status: 'acknowledged' });
        return true;
    }
    
    if (request.action === 'sparkTokenReaderReady') {
        console.log('Spark token reader ready');
        // Sätt upp alarm för token refresh
        chrome.alarms.create('refreshToken', {
            when: Date.now() + 60 * 60 * 1000, // 1 timme
            periodInMinutes: 60 // Uppdatera varje timme
        });
        sendResponse({ status: 'acknowledged' });
        return true;
    }
    
    if (request.action === 'getSavedViews') {
        getSavedViews().then(views => {
            sendResponse({ success: true, views });
        }).catch(err => {
            console.error('Error fetching saved views via bridge:', err);
            sendResponse({ success: false, error: err.message, views: [] });
        });
        return true;
    }

    if (request.action === 'ticketDataExtracted') {
        console.log('Ticket data extracted:', request.data);
        // Spara ticket data temporärt för popup om den öppnas
        chrome.storage.local.set({ lastExtractedTicket: request.data });
        sendResponse({ status: 'acknowledged' });
        return true;
    }
    
    return true; // Håll anslutningen öppen för async svar
});

// Feature-detection: Edge stödjer inte chrome.offscreen
const OFFSCREEN_SUPPORTED = typeof chrome.offscreen !== 'undefined';

// Skapa offscreen document för att hålla service worker vid liv
async function createOffscreenDocument() {
    if (!OFFSCREEN_SUPPORTED) {
        console.log('Offscreen API not supported (Edge?), skipping offscreen document');
        return;
    }
    
    console.log('Attempting to create offscreen document...');
    
    try {
        // Kontrollera först om offscreen document redan finns
        if (typeof chrome.runtime.getContexts === 'function') {
            const existingContexts = await chrome.runtime.getContexts({
                contextTypes: ['OFFSCREEN_DOCUMENT']
            });
            
            if (existingContexts.length > 0) {
                console.log('Offscreen document already exists, skipping creation');
                offscreenDocumentCreated = true;
                lastHeartbeat = Date.now();
                return;
            }
        }
        
        // Om inget offscreen document finns, skapa ett nytt
        await chrome.offscreen.createDocument({
            url: chrome.runtime.getURL('html/offscreen.html'),
            reasons: ['BLOBS'],
            justification: 'Keep service worker alive'
        });
        
        console.log('Offscreen document created successfully');
        offscreenDocumentCreated = true;
    } catch (error) {
        // Hantera fel om dokumentet redan finns (fallback för äldre Chrome-versioner)
        if (error.message && error.message.includes('already exists')) {
            console.log('Offscreen document already exists (from error)');
            offscreenDocumentCreated = true;
            lastHeartbeat = Date.now();
        } else {
            console.error('Error creating offscreen document:', error);
        }
    }
    
    console.log('Offscreen document creation completed');
    lastHeartbeat = Date.now();
}

// Kontrollera offscreen document status och återskapa om nödvändigt
async function checkOffscreenDocument() {
    // Om vi inte har ett offscreen document, skapa ett
    if (!offscreenDocumentCreated) {
        await createOffscreenDocument();
        return;
    }
    
    // Om det har gått för lång tid sedan senaste heartbeat, återskapa dokumentet
    const timeSinceLastHeartbeat = Date.now() - lastHeartbeat;
    if (timeSinceLastHeartbeat > HEARTBEAT_TIMEOUT) {
        console.warn(`No heartbeat received in ${timeSinceLastHeartbeat}ms, recreating offscreen document`);
        
        // Försök att stänga befintligt dokument om det finns
        if (OFFSCREEN_SUPPORTED) {
            try {
                await chrome.offscreen.closeDocument();
            } catch (error) {
                console.error('Error closing offscreen document:', error);
            }
        }
        
        offscreenDocumentCreated = false;
        
        // Försök återskapa dokumentet om vi inte har överskridit max antal försök
        if (offscreenReconnectAttempts < MAX_RECONNECT_ATTEMPTS) {
            offscreenReconnectAttempts++;
            await createOffscreenDocument();
        } else {
            console.error('Max reconnect attempts reached, giving up on offscreen document');
        }
    } else {
        // Skicka keep-alive meddelande till offscreen document
        try {
            await chrome.runtime.sendMessage({
                action: 'keepAlive',
                interval: HEARTBEAT_INTERVAL
            });
        } catch (error) {
            console.error('Error sending keepAlive message:', error);
            // Om vi inte kan skicka meddelande, anta att dokumentet är borta
            offscreenDocumentCreated = false;
            await createOffscreenDocument();
        }
    }
}

// Starta timern med angiven duration
async function startTimer(duration) {
    try {
        console.log(`Starting timer with duration: ${duration}ms`);
        
        // Säkerställ att vi har ett offscreen document
        if (!offscreenDocumentCreated) {
            await createOffscreenDocument();
        }
        
        // Beräkna sluttid
        const endTime = Date.now() + duration;
        
        // Spara timer-status i storage
        await chrome.storage.local.set({
            timerActive: true,
            timerEndTime: endTime,
            timerDuration: duration
        });
        
        // Uppdatera lokala variabler
        timerActive = true;
        timerEndTime = endTime;
        timerDuration = duration;
        
        // Skapa alarm för när timern löper ut
        await chrome.alarms.create('timerAlarm', {
            when: endTime
        });
        
        console.log(`Timer started, will expire at ${new Date(endTime).toLocaleTimeString()}`);
        
        return { success: true, endTime };
    } catch (error) {
        console.error('Error starting timer:', error);
        return { success: false, error: error.message };
    }
}

// Stoppa timern
async function stopTimer() {
    console.log('Stopping timer');
    
    if (timerInterval) {
        clearInterval(timerInterval);
        timerInterval = null;
    }
    
    timerActive = false;
    timerEndTime = null;
    timerDuration = 0;
    
    // Ta bort alarm
    await chrome.alarms.clear('timerAlarm');
    
    // Uppdatera storage
    chrome.storage.local.set({
        timerActive: false,
        timerEndTime: null,
        timerDuration: 0
    });
    
    // Meddela popup om den är öppen
    chrome.runtime.sendMessage({ 
        action: 'timerUpdate', 
        remaining: 0,
        active: false
    }).catch(err => {
        console.log('Error sending timer update message:', err);
        // Ignorera fel om popup inte är öppen
    });
}

// ===== KONFIGURATION =====
// Statusar som VISAS som standard (resten exkluderas)
const DEFAULT_SHOWN_STATUS_IDS = new Set([
    '3efc9f1f-0000-0000-486b-0f2700000000', // New
    '3efc9f1f-0000-0000-5b4f-1b3b00000000', // Received
    '3efc9f1f-0000-0000-a7df-4a0b00000000', // Waiting for customer
    '3efc9f1f-0000-0000-3d0a-f00800000000', // Updated by customer
    '3efc9f1f-0000-0000-962a-a53d00000000', // Planned
    '3efc9f1f-0000-0000-6e33-270f00000000', // Pågående
]);

// Alla kända status-ID:n
const ALL_STATUS_IDS = [
    '3efc9f1f-0000-0000-486b-0f2700000000', '3efc9f1f-0000-0000-5b4f-1b3b00000000',
    '3efc9f1f-0000-0000-6e33-270f00000000', '3efc9f1f-0000-0000-8117-332300000000',
    '3efc9f1f-0000-0000-a7df-4a0b00000000', '3efc9f1f-0000-0000-bac3-561f00000000',
    '3efc9f1f-0000-0000-8346-992900000000', '3efc9f1f-0000-0000-962a-a53d00000000',
    '3efc9f1f-0000-0000-a90e-b11100000000', '3efc9f1f-0000-0000-bcf2-bc2500000000',
    '3efc9f1f-0000-0000-e2ba-d40d00000000', '3efc9f1f-0000-0000-f59e-e02100000000',
    '3efc9f1f-0000-0000-0883-ec3500000000', '3efc9f1f-0000-0000-1b67-f80900000000',
    '3efc9f1f-0000-0000-877e-9d1e00000000', '3efc9f1f-0000-0000-0cbb-f02a00000000',
    '3efc9f1f-0000-0000-1f9f-fc3e00000000', '3efc9f1f-0000-0000-3d0a-f00800000000',
    '3efc9f1f-0000-0000-b17e-b93b00000000', '3efc9f1f-0000-0000-5fad-e70700000000',
    '3efc9f1f-0000-0000-dc8c-163600000000', '3efc9f1f-0000-0000-ef70-220a00000000',
    '3efc9f1f-0000-0000-8791-812a00000000', '3efc9f1f-0000-0000-c03d-a52600000000',
    '3efc9f1f-0000-0000-d321-b13a00000000', '3efc9f1f-0000-0000-e605-bd0e00000000',
    '3efc9f1f-0000-0000-0cce-d43600000000', '3efc9f1f-0000-0000-1fb2-e00a00000000',
    '3efc9f1f-0000-0000-457a-f83200000000', '3efc9f1f-0000-0000-585e-040700000000',
    '3efc9f1f-0000-0000-6b42-101b00000000', '3efc9f1f-0000-0000-7e26-1c2f00000000',
    '3efc9f1f-0000-0000-910a-280300000000', '3efc9f1f-0000-0000-a4ee-331700000000',
    '3efc9f1f-0000-0000-b7d2-3f2b00000000', '3efc9f1f-0000-0000-cab6-4b3f00000000',
    '3efc9f1f-0000-0000-dd9a-571300000000',
];

// Standard exkluderade = alla som INTE är i DEFAULT_SHOWN_STATUS_IDS
const DEFAULT_EXCLUDED_STATUS_IDS = ALL_STATUS_IDS.filter(id => !DEFAULT_SHOWN_STATUS_IDS.has(id));

// Hämta användarens konfigurerade exkluderade statusar (eller default)
async function getExcludedStatusIds() {
    try {
        const result = await chrome.storage.local.get(['configExcludedStatusIds']);
        if (result.configExcludedStatusIds && Array.isArray(result.configExcludedStatusIds)) {
            return result.configExcludedStatusIds;
        }
    } catch (e) {
        console.warn('Could not load config excluded statuses:', e);
    }
    return [...DEFAULT_EXCLUDED_STATUS_IDS];
}

/**
 * Kontrollera tidsartiklar för ALLA ärenden oavsett status (senaste 7 dagar).
 * Kör oberoende av det statusfiltrerade ticket-flödet.
 * Skapar notifikationer med Ignore/Fix-knappar vid mismatch.
 * @param {string} userId - Inloggad användares ID (JWT sub)
 * @param {string|null} userTitle - Användarens titel (t.ex. "IT Specialist")
 * @param {boolean} notificationsEnabled - Om notifikationer är aktiverade
 * @returns {number} Antal unika ärenden med artikelmismatch
 */
async function checkArticleTimesheets(userId, userTitle, notificationsEnabled) {
    // Guard: kontrollera config
    const timereportNoticeConfig = await chrome.storage.local.get(['configTimereportNotice']);
    const timereportNoticeEnabled = timereportNoticeConfig.configTimereportNotice !== false;

    // Title override: om användaren har valt en titel i config, använd den istället för JWT-titeln
    const titleOverrideConfig = await chrome.storage.local.get(['configTitleOverride']);
    const effectiveTitle = titleOverrideConfig.configTitleOverride || userTitle;

    const expectedGuid = effectiveTitle ? getExpectedArticleGuid(effectiveTitle) : null;

    if (!timereportNoticeEnabled) return 0;
    if (!expectedGuid) return 0;
    if (!userId) return 0;

    // Hämta ALLA ärenden tilldelade användaren senaste 7 dagar (ingen status-exkludering)
    const sevenDaysAgo = new Date();
    sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7);

    const searchBody = {
        filter: [
            ['assignedTo.id', '=', userId],
            'and',
            ['changedDate', '>=', sevenDaysAgo.toISOString()]
        ],
        sort: [{ selector: 'changedDate', desc: true }],
        getAll: true,
        getAllLimit: 200,
        escape: true,
        isTemplateFilter: false,
        statusIsActive: null,
        searchOperation: 'contains',
        searchValue: null,
        fullTextSearch: null,
        assignedToIdFilter: null,
        assignedDepartmentIdFilter: null,
        isOwnershipExternalFilter: null,
        supportGroupIdFilter: null,
        group: [],
        userData: {}
    };

    const apiUrl = `${SPARK_API_BASE}/Tickets/Search`;

    let allTickets = [];
    try {
        const token = await getSparkToken();
        const headers = {
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json',
            'Accept': 'application/json, text/plain, */*'
        };
        const response = await fetch(apiUrl, {
            method: 'POST',
            headers,
            credentials: 'include',
            body: JSON.stringify(searchBody)
        });

        if (!response.ok) {
            console.error(`[ARTICLE-CHECK] Tickets/Search failed: HTTP ${response.status}`);
            return 0;
        }

        const responseData = await response.json();
        allTickets = responseData.data || responseData;
    } catch (fetchErr) {
        console.error('Article check: failed to fetch tickets:', fetchErr.message);
        return 0;
    }

    if (!allTickets || allTickets.length === 0) return 0;

    // Hämta ignorerade ärenden från storage
    const ignoredData = await chrome.storage.local.get(['articleMismatchIgnored']);
    const ignoredTickets = new Set(ignoredData.articleMismatchIgnored || []);

    const mismatchTickets = [];

    for (const ticket of allTickets) {
        const ticketDisplayId = ticket.ticketId || ticket.id;

        // Hoppa över ignorerade ärenden
        if (ignoredTickets.has(ticketDisplayId) || ignoredTickets.has(ticket.id)) continue;

        try {
            const timesheetsResult = await getTicketTimeSheets(ticket.id);
            const timesheets = Array.isArray(timesheetsResult) ? timesheetsResult : timesheetsResult?.data || [];

            // Filtrera timesheets senaste 7 dagarna
            const recentTimesheets = timesheets.filter(ts => {
                const perfDate = ts.performedDate ? new Date(ts.performedDate) : null;
                return perfDate && perfDate >= sevenDaysAgo;
            });

            const userTimesheets = recentTimesheets.filter(ts => ts.performedBy?.id === userId);

            for (const ts of userTimesheets) {
                if (!ts.articleId) continue;
                if (OVERTIME_ARTICLE_GUIDS.has(ts.articleId)) continue;
                if (ts.articleId === expectedGuid) continue;
                mismatchTickets.push({
                    ticketId: ticketDisplayId,
                    ticketGuid: ticket.id,
                    timesheetId: ts.timeSheetId || ts.id,
                    actualArticleId: ts.articleId,
                    expectedArticleId: expectedGuid
                });
            }
        } catch (tsErr) {
            console.warn(`Article check: could not check timesheets for ticket ${ticketDisplayId}:`, tsErr.message);
        }
    }

    // Deduplera: max 1 notifikation per ärende
    const mismatchByTicket = new Map();
    for (const m of mismatchTickets) {
        if (!mismatchByTicket.has(m.ticketId)) {
            mismatchByTicket.set(m.ticketId, m);
        }
    }
    const articleMismatchCount = mismatchByTicket.size;

    if (mismatchByTicket.size > 0 && notificationsEnabled) {
        const expectedRoleName = getArticleNameByGuid(expectedGuid) || userTitle;

        for (const [ticketId, m] of mismatchByTicket) {
            const wrongRoleName = getArticleNameByGuid(m.actualArticleId) || 'okänd roll';
            try {
                await chrome.notifications.create(`articleMismatch_${ticketId}_${m.ticketGuid}`, {
                    type: 'basic',
                    iconUrl: '/icons/Untitled-1 - 18-02-2026 23-08-51(2).png',
                    title: 'Spark + Felaktig artikel',
                    message: `Ärende #${ticketId}: Rapporterad som "${wrongRoleName}" — förväntat "${expectedRoleName}".`,
                    buttons: [
                        { title: 'Ignorera' },
                        { title: 'Fixa' }
                    ],
                    priority: 2,
                    requireInteraction: true
                });
            } catch (notifErr) {
                console.error('Article check: error creating notification:', notifErr);
            }
        }
    }

    return articleMismatchCount;
}

// Funktion för att hämta alla tickets från Spark API och uppdatera listan
// ÖPPNAR ALDRIG nya flikar — allt sker via fetch() i bakgrunden
async function fetchAndUpdateTicketsFromAPI() {
    try {
        const timestamp = new Date().toLocaleTimeString('sv-SE');
        console.log(`Fetching tickets from Spark API... ${timestamp}`);
        
        const result = await chrome.storage.local.get(['notificationsEnabled', 'scrapedItems']);
        const notificationsEnabled = result.notificationsEnabled !== false;
        const previousItems = result.scrapedItems || [];
        
        try {
            // Hämta Spark token (från öppen Spark-flik via content script, INGA nya flikar)
            let token;
            try {
                token = await getSparkToken();
                console.log('Got Spark token:', token ? `${token.substring(0, 30)}... (${token.length} chars)` : 'NULL');
            } catch (tokenError) {
                console.warn('Could not get Spark token:', tokenError.message);
                
                // Visa notifikation att användaren behöver logga in
                if (notificationsEnabled && tokenError.message?.includes('SPARK_TOKEN_MISSING')) {
                    try {
                        await chrome.notifications.create('tokenMissing', {
                            type: 'basic',
                            iconUrl: '/icons/Untitled-1 - 18-02-2026 23-08-51(2).png',
                            title: 'Spark +',
                            message: 'Öppna spark.iver.com och logga in för att aktivera automatiska uppdateringar.',
                            buttons: [{ title: 'Öppna Spark' }],
                            priority: 1,
                            requireInteraction: true
                        });
                    } catch (notifError) {
                        console.error('Error creating token missing notification:', notifError);
                    }
                }
                
                return { changedStatusCount: 0, updatedItemsFound: false };
            }
            
            // Hämta inloggad användares ID dynamiskt från JWT
            const userId = await getLoggedInUserId();
            if (!userId) {
                console.error('Could not determine logged-in user ID from token');
                return { changedStatusCount: 0, updatedItemsFound: false };
            }
            console.log('Fetching tickets for user:', userId);

            // Hämta användarens konfigurerade exkluderade statusar
            const EXCLUDED_STATUS_IDS = await getExcludedStatusIds();
            console.log(`Using ${EXCLUDED_STATUS_IDS.length} excluded status IDs from config`);

            // --- Custom Queue: kolla om användaren har valt egna köer ---
            const customQueueConfig = await chrome.storage.local.get(['configCustomQueueEnabled', 'configCustomQueueViewIds']);
            const customQueueEnabled = customQueueConfig.configCustomQueueEnabled === true;
            const customQueueViewIds = customQueueConfig.configCustomQueueViewIds || [];

            let apiTickets = [];

            if (customQueueEnabled && customQueueViewIds.length > 0) {
                // === CUSTOM QUEUE MODE: hämta tickets från valda vyer ===
                console.log(`Custom Queue mode active — fetching from ${customQueueViewIds.length} view(s)`);
                const seenTicketIds = new Set();

                for (const viewId of customQueueViewIds) {
                    try {
                        const viewTickets = await getTicketsFromView(viewId);
                        for (const ticket of viewTickets) {
                            const tid = ticket.id || ticket.ticketId;
                            if (!seenTicketIds.has(tid)) {
                                seenTicketIds.add(tid);
                                apiTickets.push(ticket);
                            }
                        }
                    } catch (viewErr) {
                        console.error(`Error fetching tickets from custom queue view ${viewId}:`, viewErr.message);
                    }
                }
                console.log(`Custom Queue: fetched ${apiTickets.length} unique tickets from ${customQueueViewIds.length} view(s)`);
            } else {
                // === DEFAULT MODE: hämta "My Tickets" via Tickets/Search ===
                const excludeFilter = EXCLUDED_STATUS_IDS.reduce((acc, id, i) => {
                    if (i > 0) acc.push('or');
                    acc.push(['status.id', '=', id]);
                    return acc;
                }, []);

                const searchBody = {
                    filter: [
                        ['!', excludeFilter],
                        'and',
                        ['assignedTo.id', '=', userId]
                    ],
                    sort: [{ selector: 'changedDate', desc: true }],
                    getAll: true,
                    getAllLimit: 200,
                    escape: true,
                    isTemplateFilter: false,
                    statusIsActive: true,
                    searchOperation: 'contains',
                    searchValue: null,
                    fullTextSearch: null,
                    assignedToIdFilter: null,
                    assignedDepartmentIdFilter: null,
                    isOwnershipExternalFilter: null,
                    supportGroupIdFilter: null,
                    group: [],
                    userData: {}
                };

                const apiUrl = `${SPARK_API_BASE}/Tickets/Search`;
                console.log('Fetching from:', apiUrl);
                
                const response = await fetch(apiUrl, {
                    method: 'POST',
                    headers: {
                        'Authorization': `Bearer ${token}`,
                        'Content-Type': 'application/json',
                        'Accept': 'application/json, text/plain, */*'
                    },
                    body: JSON.stringify(searchBody),
                    credentials: 'include'
                });
                
                console.log(`Spark API response: ${response.status} ${response.statusText}`);
                
                // Hantera 401 — rensa token och meddela
                if (response.status === 401) {
                    console.warn('Spark API returned 401, token expired');
                    await clearSparkToken();
                    
                    if (notificationsEnabled) {
                        try {
                            await chrome.notifications.create('tokenExpired', {
                                type: 'basic',
                                iconUrl: '/icons/Untitled-1 - 18-02-2026 23-08-51(2).png',
                                title: 'Spark +',
                                message: 'Spark-sessionen har gått ut. Öppna spark.iver.com för att förnya.',
                                buttons: [{ title: 'Öppna Spark' }],
                                priority: 1,
                                requireInteraction: true
                            });
                        } catch (notifError) {
                            console.error('Error creating token expired notification:', notifError);
                        }
                    }
                    
                    return { changedStatusCount: 0, updatedItemsFound: false };
                }
                
                if (!response.ok) {
                    throw new Error(`Spark API HTTP ${response.status}: ${response.statusText}`);
                }
                
                const responseData = await response.json();
                apiTickets = responseData.data || responseData;
                console.log(`Successfully fetched ${apiTickets?.length || 0} tickets from Spark API (totalCount: ${responseData.totalCount || 'N/A'})`);
            }
            
            // Backup-filter: filtrera bort exkluderade statusar via ID
            apiTickets = apiTickets.filter(ticket => {
                const statusId = ticket.status?.id || '';
                return !EXCLUDED_STATUS_IDS.includes(statusId);
            });
            
            console.log(`After status filter: ${apiTickets.length} tickets`);
            
            if (!apiTickets || apiTickets.length === 0) {
                console.log('No tickets found after filtering');
                
                // Rensa listan i storage så att popup visar en tom lista
                await chrome.storage.local.set({ scrapedItems: [] });
                
                if (notificationsEnabled) {
                    try {
                        await chrome.notifications.create('noItems', {
                            type: 'basic',
                            iconUrl: '/icons/Untitled-1 - 18-02-2026 23-08-51(2).png',
                            title: 'Spark +',
                            message: 'Inga aktiva ärenden tilldelade dig just nu.',
                            priority: 1,
                            requireInteraction: false
                        });
                    } catch (notifError) {
                        console.error('Error creating empty list notification:', notifError);
                    }
                }
                
                return { changedStatusCount: 0, updatedItemsFound: false };
            }
            
            // Konvertera API-tickets till vårt interna format
            const newItems = apiTickets.map(ticket => {
                const ticketId = ticket.ticketId || ticket.id;
                const previousItem = previousItems.find(item => item.id === ticketId);
                
                return {
                    id: ticketId,
                    ticketGuid: ticket.id || null,
                    displayName: ticket.displayName || null,
                    title: ticket.description || ticket.displayName || `Ticket ${ticketId}`,
                    status: ticket.status?.description || 'Okänd status',
                    statusColor: ticket.status?.color || null,
                    previousStatus: previousItem?.status || null,
                    timestamp: new Date().toISOString(),
                    lastChecked: new Date().toISOString(),
                    url: `https://spark.iver.com/tickets/detail/${ticket.id}`,
                    assignee: ticket.assignedTo?.displayName || ticket.assignedTo?.name || 'Ej tilldelad',
                    priority: ticket.ticketPriority?.description || 'Normal',
                    ticketType: ticket.ticketKind?.description || 'Unknown',
                    ticketKindId: ticket.ticketKind?.ticketKindId || '',
                    customerId: ticket.customer?.id || null,
                    customer: ticket.customer?.companyName || ticket.customer?.description || 'Okänd kund',
                    customerService: ticket.customerService?.description || '',
                    statusChanged: false,
                    description: ticket.description || '',
                    urgency: ticket.urgency?.description || null,
                    impact: ticket.impact?.description || null,
                    completeDueDate: previousItem?.completeDueDate || ticket.completeDueDate || null,
                    createdDate: previousItem?.createdDate || ticket.createdDate || null,
                    changedDate: ticket.changedDate || null,
                    slaLevel: ticket.slaLevel?.description || null,
                    serviceLevel: ticket.serviceLevel || null,
                    responsible: ticket.responsible?.displayName || null,
                    contact: ticket.contact?.name || null
                };
            });
            
            // Jämför med tidigare status för att hitta ändringar
            let changedStatusCount = 0;
            const changedItems = [];
            
            newItems.forEach(newItem => {
                const previousItem = previousItems.find(item => item.id === newItem.id);
                
                if (previousItem && previousItem.status !== newItem.status) {
                    console.log(`✓ Status changed for ticket ${newItem.id}: "${previousItem.status}" -> "${newItem.status}"`);
                    newItem.statusChanged = true;
                    newItem.previousStatus = previousItem.status;
                    changedStatusCount++;
                    changedItems.push(newItem);
                } else if (!previousItem) {
                    console.log(`New ticket found: ${newItem.id}`);
                }
            });
            
            // Sortera: ändrade ärenden först
            newItems.sort((a, b) => {
                if (a.statusChanged && !b.statusChanged) return -1;
                if (!a.statusChanged && b.statusChanged) return 1;
                return 0;
            });
            
            // Spara uppdaterade items
            await chrome.storage.local.set({ scrapedItems: newItems });
            
            console.log(`Changed status count: ${changedStatusCount}`);
            
            // --- Hämta användarinfo via full ticket-data (Search ger ej assignedTo.title) ---
            let userTitle = null;
            let userDisplayName = null;

            try {
                // Kolla om vi redan har cachad info
                const cachedInfo = await chrome.storage.local.get(['sparkUserTitle', 'sparkUserDisplayName']);
                userTitle = cachedInfo.sparkUserTitle || null;
                userDisplayName = cachedInfo.sparkUserDisplayName || null;

                // Om inte cachad, hämta full ticket-data för första ticketen
                if (!userTitle && apiTickets.length > 0) {
                    const firstTicketId = apiTickets[0].id;
                    console.log(`Fetching full ticket data for ${firstTicketId} to get assignedTo.title...`);
                    const fullTicket = await makeAuthenticatedRequest(`${SPARK_API_BASE}/Tickets/${firstTicketId}`, { method: 'GET' });
                    
                    if (fullTicket?.assignedTo) {
                        userTitle = fullTicket.assignedTo.title || null;
                        userDisplayName = fullTicket.assignedTo.displayName || fullTicket.assignedTo.name || null;
                        
                        if (userTitle || userDisplayName) {
                            await chrome.storage.local.set({
                                sparkUserTitle: userTitle,
                                sparkUserDisplayName: userDisplayName
                            });
                            console.log(`Cached user info — name: "${userDisplayName}", title: "${userTitle}"`);
                        }
                    }
                }
            } catch (userInfoErr) {
                console.warn('Could not fetch user title from full ticket data:', userInfoErr.message);
            }

            // --- Artikelkontroll körs separat (alla ärenden oavsett status, senaste 7 dagar) ---
            let articleMismatchCount = 0;
            try {
                articleMismatchCount = await checkArticleTimesheets(userId, userTitle, notificationsEnabled);
            } catch (articleErr) {
                console.error('[ARTICLE-CHECK] Error in checkArticleTimesheets:', articleErr);
            }
            
            // Skicka notifikation
            if (notificationsEnabled) {
                if (changedStatusCount > 0) {
                    // Skapa en notifikation per ärende med direktlänk
                    for (const item of changedItems) {
                        try {
                            await chrome.notifications.create(`statusChange_${item.id}_${item.ticketGuid}`, {
                                type: 'basic',
                                iconUrl: '/icons/Untitled-1 - 18-02-2026 23-08-51(2).png',
                                title: 'Spark + Statusändring',
                                message: `Ärende #${item.id}: "${item.previousStatus}" → "${item.status}"`,
                                buttons: [{ title: 'Öppna ärende' }],
                                priority: 2,
                                requireInteraction: true
                            });
                        } catch (notifError) {
                            console.error(`Error creating status change notification for ticket ${item.id}:`, notifError);
                        }
                    }
                    
                    try {
                        await chrome.action.setBadgeText({ text: '!' });
                        await chrome.action.setBadgeBackgroundColor({ color: '#FF0000' });
                        await chrome.storage.local.set({ hasUnreadUpdates: true });
                    } catch (badgeError) {
                        console.error('Error setting badge:', badgeError);
                    }
                } else {
                    try {
                        await chrome.notifications.create('noChanges', {
                            type: 'basic',
                            iconUrl: '/icons/Untitled-1 - 18-02-2026 23-08-51(2).png',
                            title: 'Spark +',
                            message: 'Inga nya uppdateringar',
                            priority: 1,
                            requireInteraction: false
                        });
                    } catch (notifError) {
                        console.error('Error creating no news notification:', notifError);
                    }
                }
            }
            
            return { 
                changedStatusCount, 
                updatedItemsFound: changedStatusCount > 0,
                articleMismatchCount
            };
            
        } catch (apiError) {
            console.error('Error fetching tickets from API:', apiError);
            console.error('Error name:', apiError.name);
            console.error('Error message:', apiError.message);
            console.error('Error stack:', apiError.stack);
            
            if (notificationsEnabled) {
                try {
                    const msg = apiError.message || '';
                    const isTokenIssue = msg.includes('SPARK_TOKEN') 
                        || msg.includes('Unexpected token')
                        || msg.includes('unexpected token')
                        || msg.includes('JSON')
                        || msg.includes('401');
                    const errorMsg = isTokenIssue
                        ? 'Öppna Spark för att verifiera ditt token.'
                        : `Fel: ${msg.substring(0, 100) || 'Okänt fel'}`;
                    await chrome.notifications.create('apiError', {
                        type: 'basic',
                        iconUrl: '/icons/Untitled-1 - 18-02-2026 23-08-51(2).png',
                        title: 'Spark + API Error',
                        message: errorMsg,
                        buttons: [{ title: 'Öppna Spark' }],
                        priority: 2,
                        requireInteraction: true
                    });
                } catch (notifError) {
                    console.error('Error creating error notification:', notifError);
                }
            }
            
            return { changedStatusCount: 0, updatedItemsFound: false };
        }
        
    } catch (error) {
        console.error('Error in fetchAndUpdateTicketsFromAPI:', error);
        return { changedStatusCount: 0, updatedItemsFound: false };
    }
}

// Skapa en keepAlive-funktion för att hålla service worker aktiv
function createKeepAlive() {
    return new Promise(resolve => {
        // Skapa en keepAlive-interval som körs var 5:e sekund i 30 sekunder
        let counter = 0;
        const maxTries = 6; // 6 * 5s = 30s
        
        const keepAliveInterval = setInterval(() => {
            counter++;
            console.log(`KeepAlive ping ${counter}/${maxTries}`);
            
            // Skicka ett ping till storage för att hålla service worker aktiv
            chrome.storage.local.get('keepAlive', () => {});
            
            if (counter >= maxTries) {
                clearInterval(keepAliveInterval);
                resolve();
            }
        }, 5000);
    });
}

// Lyssna på alarm-events
chrome.alarms.onAlarm.addListener(async (alarm) => {
    console.log('Alarm fired:', alarm.name);
    
    if (alarm.name === 'timerAlarm') {
        console.log('Timer alarm triggered at', new Date().toLocaleTimeString());
        
        try {
            // Skapa offscreen document om det inte finns för att säkerställa att service worker förblir aktiv
            await createOffscreenDocument();
            
            // Sätt en flagga för att indikera att timern har löpt ut medan popup var stängd
            await chrome.storage.local.set({
                timerExpiredWhileClosed: true,
                timerExpiredTime: Date.now()
            });
            
            console.log('Timer expired, running fetchAndUpdateTicketsFromAPI()...');
            
            // Uppdatera items när timern löper ut - kör med await för att säkerställa att det slutförs
            try {
                const updateResult = await fetchAndUpdateTicketsFromAPI();
                console.log('Items update completed:', updateResult);
            } catch (error) {
                console.error('Error during items update:', error);
            }
            
            // Använd lokala variabler istället för globala för att undvika problem med 'this'
            // Återställ timer-status
            const localTimerActive = false;
            const localTimerEndTime = null;
            
            // Uppdatera storage
            await chrome.storage.local.set({
                timerActive: localTimerActive,
                timerEndTime: localTimerEndTime,
                timerDuration: 0
            });
            
            // Uppdatera globala variabler
            timerActive = localTimerActive;
            timerEndTime = localTimerEndTime;
            timerDuration = 0;
            
            // Kontrollera om vi har en återkommande timer
            const storageResult = await chrome.storage.local.get(['timerSettings']);
            
            if (storageResult.timerSettings) {
                const { hours, minutes } = storageResult.timerSettings;
                if (hours > 0 || minutes > 0) {
                    console.log(`Setting up next recurring timer: ${hours}h ${minutes}m`);
                    
                    // Beräkna totala millisekunder
                    const totalMilliseconds = ((hours * 60 * 60) + (minutes * 60)) * 1000;
                    
                    // Starta en ny timer med samma duration
                    await startTimer(totalMilliseconds);
                    
                    // Spara att vi har en återkommande timer
                    await chrome.storage.local.set({
                        recurringTimer: true,
                        recurringDuration: totalMilliseconds
                    });
                }
            }
        } catch (error) {
            console.error('Error handling timer alarm:', error);
        }
    } else if (alarm.name === 'refreshToken') {
        console.log('Token refresh alarm triggered, refreshing Spark token...');
        try {
            // Försök hämta ny token från öppen Spark-flik (INGA nya flikar)
            const hasToken = await hasValidSparkToken();
            if (hasToken) {
                console.log('Spark token refreshed successfully');
            } else {
                console.log('No valid Spark token available, user needs to open spark.iver.com');
            }
        } catch (error) {
            console.error('Error refreshing Spark token:', error);
        }
    } else if (alarm.name === 'offscreenCheck') {
        console.log('Checking offscreen document status');
        await checkOffscreenDocument();
    } else if (alarm.name === 'wakeupAlarm') {
        console.log('Wakeup alarm triggered, keeping service worker alive');
        // Gör inget, detta alarm finns bara för att hålla service worker aktiv
    }
});

// Återställ timer vid uppstart om den var aktiv tidigare
chrome.storage.local.get(['timerActive', 'timerEndTime', 'timerDuration'], (result) => {
    if (result.timerActive && result.timerEndTime) {
        const now = Date.now();
        const remaining = result.timerEndTime - now;
        
        if (remaining > 0) {
            console.log('Restoring timer from previous session');
            startTimer(remaining);
        } else {
            console.log('Previous timer expired, fetching tickets from API');
            fetchAndUpdateTicketsFromAPI();
            
            // Återställ timer-status
            chrome.storage.local.set({
                timerActive: false,
                timerEndTime: null
            });
        }
    }
});

// Öppna popup-fönstret och markera att en bakgrundsuppdatering har skett
async function openPopup() {
    try {
        // Markera att en bakgrundsuppdatering har skett så att popup kan visa detta
        await chrome.storage.local.set({ 
            backgroundUpdateOccurred: true, 
            lastBackgroundUpdate: new Date().toISOString() 
        });
        
        console.log('Background update flag set, popup will show updated data when opened');
        console.log('Opening popup window automatically...');
        
        // Hämta extension URL för popup
        const url = chrome.runtime.getURL('html/PopupUI.html');
        console.log('Popup URL:', url);
        
        // Hämta extensionens namn från manifest för korrekt fönsteridentifiering
        const manifest = chrome.runtime.getManifest();
        const extensionName = manifest.name; // "Spark +" enligt manifest
        console.log('Extension name from manifest:', extensionName);
        
        // Kontrollera om popup-fönstret redan är öppet
        console.log('Checking for existing popup windows...');
        const windows = await chrome.windows.getAll();
        console.log('All windows:', windows.length);
        
        // Mer flexibel sökning efter popup-fönster
        const existingPopup = windows.find(win => {
            console.log('Checking window:', win.id, win.type, win.title);
            // Kontrollera om det är ett popup-fönster och om titeln innehåller extensionens namn
            // eller om det är ett popup-fönster som öppnats från vår extension
            return win.type === 'popup' && 
                  (win.title && (
                      win.title.includes(extensionName) || 
                      win.title.includes('Spark') || 
                      win.title.includes('PopupUI.html')
                  ));
        });
        
        if (existingPopup) {
            console.log('Popup already open, focusing window...', existingPopup.id);
            await chrome.windows.update(existingPopup.id, { focused: true });
            return;
        }
        
        // Skapa ett nytt popup-fönster
        console.log('Creating new popup window...');
        try {
            const popupWindow = await chrome.windows.create({
                url: url,
                type: 'popup',
                width: 400,
                height: 600,
                focused: true
            });
            
            console.log('Popup window opened:', popupWindow.id);
        } catch (windowError) {
            console.error('Failed to create popup window:', windowError);
            throw windowError; // Re-throw for outer catch block
        }
    } catch (error) {
        console.error('Error opening popup window:', error);
        
        // Om popup inte kan öppnas, visa en notifikation som användaren kan klicka på
        console.log('Showing fallback notification instead...');
        try {
            await chrome.notifications.create('backgroundUpdate', {
                type: 'basic',
                iconUrl: '/icons/Untitled-1 - 18-02-2026 23-08-51(2).png',
                title: 'Spark +',
                message: 'Listan har uppdaterats i bakgrunden. Klicka här för att öppna.',
                buttons: [{ title: 'Visa ärenden' }],
                priority: 2,
                requireInteraction: true
            });
            console.log('Fallback notification created');
        } catch (notifError) {
            console.error('Failed to create fallback notification:', notifError);
        }
    }
}

// Testfunktion för att verifiera att notifikationer fungerar
async function testNotification() {
    console.log('Testing notification system...');
    try {
        const notificationId = await chrome.notifications.create('testNotification', {
            type: 'basic',
            iconUrl: '/icons/Untitled-1 - 18-02-2026 23-08-51(2).png',
            title: 'Spark + Test',
            message: 'Om du ser detta fungerar notifikationer!',
            priority: 2,
            requireInteraction: true
        });
        console.log('Test notification created with ID:', notificationId);
        
        // Ta bort testnotifikationen efter 5 sekunder
        setTimeout(() => {
            chrome.notifications.clear(notificationId);
        }, 5000);
    } catch (error) {
        console.error('Failed to create test notification:', error);
    }
}

// Lyssnare för notifikationsklick (klick på notifikationskroppen)
chrome.notifications.onClicked.addListener((notificationId) => {
    // Token/API-relaterade: öppna Spark
    if (['tokenMissing', 'tokenExpired', 'apiError'].includes(notificationId)) {
        chrome.tabs.create({ url: 'https://spark.iver.com', active: true });
        chrome.notifications.clear(notificationId);
        return;
    }

    // Statusändring per ärende: öppna ärendet direkt
    if (notificationId.startsWith('statusChange_')) {
        const parts = notificationId.replace('statusChange_', '').split('_');
        const ticketGuid = parts.slice(1).join('_');
        if (ticketGuid) {
            chrome.tabs.create({ url: `https://spark.iver.com/tickets/detail/${ticketGuid}`, active: true });
        }
        chrome.notifications.clear(notificationId);
        return;
    }

    // Artikelmismatch: öppna ärendet direkt
    if (notificationId.startsWith('articleMismatch_')) {
        const parts = notificationId.replace('articleMismatch_', '').split('_');
        const ticketGuid = parts.slice(1).join('_');
        if (ticketGuid) {
            chrome.tabs.create({ url: `https://spark.iver.com/tickets/detail/${ticketGuid}`, active: true });
        }
        chrome.notifications.clear(notificationId);
        return;
    }

    // Övriga (noChanges, noItems, backgroundUpdate): öppna popup
    if (['noChanges', 'noItems', 'backgroundUpdate'].includes(notificationId)) {
        openPopup();
        chrome.notifications.clear(notificationId);
    }
});

// Hantera knappklick på alla notifikationstyper
chrome.notifications.onButtonClicked.addListener(async (notificationId, buttonIndex) => {
    // === Artikelmismatch: Ignorera (0) / Fixa (1) ===
    if (notificationId.startsWith('articleMismatch_')) {
        const parts = notificationId.replace('articleMismatch_', '').split('_');
        const ticketId = parts[0];
        const ticketGuid = parts.slice(1).join('_');

        if (buttonIndex === 0) {
            // Ignorera — spara ticketId i storage
            try {
                const data = await chrome.storage.local.get(['articleMismatchIgnored']);
                const ignored = data.articleMismatchIgnored || [];
                if (!ignored.includes(ticketId)) {
                    ignored.push(ticketId);
                    await chrome.storage.local.set({ articleMismatchIgnored: ignored });
                }
            } catch (err) {
                console.error('Error saving article ignore:', err);
            }
        } else if (buttonIndex === 1) {
            // Fixa — öppna ärendet
            const ticketUrl = `https://spark.iver.com/tickets/detail/${ticketGuid}`;
            try {
                await chrome.tabs.create({ url: ticketUrl, active: true });
            } catch (err) {
                console.error('Error opening ticket URL:', err);
            }
        }
        chrome.notifications.clear(notificationId);
        return;
    }

    // === Statusändring per ärende: Öppna ärende (0) ===
    if (notificationId.startsWith('statusChange_')) {
        if (buttonIndex === 0) {
            const parts = notificationId.replace('statusChange_', '').split('_');
            const ticketGuid = parts.slice(1).join('_');
            const ticketUrl = `https://spark.iver.com/tickets/detail/${ticketGuid}`;
            try {
                await chrome.tabs.create({ url: ticketUrl, active: true });
            } catch (err) {
                console.error('Error opening ticket URL:', err);
            }
        }
        chrome.notifications.clear(notificationId);
        return;
    }

    // === Token/API-notifikationer: Öppna Spark (0) ===
    if (['tokenMissing', 'tokenExpired', 'apiError'].includes(notificationId)) {
        if (buttonIndex === 0) {
            try {
                await chrome.tabs.create({ url: 'https://spark.iver.com', active: true });
            } catch (err) {
                console.error('Error opening Spark:', err);
            }
        }
        chrome.notifications.clear(notificationId);
        return;
    }

    // === Bakgrundsuppdatering: Visa ärenden (0) ===
    if (notificationId === 'backgroundUpdate') {
        if (buttonIndex === 0) {
            openPopup();
        }
        chrome.notifications.clear(notificationId);
        return;
    }
});

// Initiera extension när service worker startar
chrome.runtime.onInstalled.addListener(async () => {
    console.log('Extension installed/updated');
    
    // Sätt upp token refresh alarm (var 50:e minut, token lever 60 min)
    chrome.alarms.create('refreshToken', {
        delayInMinutes: 50,
        periodInMinutes: 50
    });
    console.log('Token refresh alarm set (every 50 min)');
    
    // Auto-start timer med sparade inställningar (eller default 30 min)
    try {
        const result = await chrome.storage.local.get(['timerActive', 'timerSettings']);
        if (!result.timerActive) {
            const settings = result.timerSettings || { hours: 0, minutes: 30 };
            const hours = settings.hours || 0;
            const minutes = settings.minutes || 30;
            const totalMs = ((hours * 60 * 60) + (minutes * 60)) * 1000;
            
            console.log(`Auto-starting timer: ${hours}h ${minutes}m (${totalMs}ms)`);
            await startTimer(totalMs);
            
            // Spara timerSettings om de inte redan fanns
            if (!result.timerSettings) {
                await chrome.storage.local.set({ timerSettings: settings });
            }
            await chrome.storage.local.set({ recurringTimer: true, recurringDuration: totalMs });
            console.log('Timer auto-started successfully');
        } else {
            console.log('Timer already active, skipping auto-start');
        }
    } catch (error) {
        console.error('Error auto-starting timer:', error);
    }
});

// Starta offscreen document när service worker startar (endast en gång)
createOffscreenDocument();

// Säkerställ att token refresh alarm alltid finns (även efter service worker restart)
chrome.alarms.get('refreshToken', (alarm) => {
    if (!alarm) {
        chrome.alarms.create('refreshToken', {
            delayInMinutes: 50,
            periodInMinutes: 50
        });
        console.log('Token refresh alarm created on startup');
    }
});

console.log('Service worker initialized (Spark API mode)');
