// StudyTrack Service Worker v2 — Web Push + Background Sync
const CACHE_NAME = 'studytrack-v2';
const SITE_URL   = 'https://studytrack.edurx.icu/studytrack';

self.addEventListener('install',  e => self.skipWaiting());
self.addEventListener('activate', e => e.waitUntil(clients.claim()));

// ── Push handler ─────────────────────────────────────────────────────
self.addEventListener('push', function(event) {
    let data = {};
    try {
        if (event.data) {
            const text = event.data.text();
            // Try JSON first, fall back to plain ping
            try { data = JSON.parse(text); } catch(e) { data = {}; }
        }
    } catch(e) { data = {}; }

    // If we got an empty push (ping), fetch latest notification from API
    if (!data.title) {
        event.waitUntil(
            fetch(SITE_URL + '/api/notifications.php', {
                headers: { 'X-Requested-With': 'XMLHttpRequest' }
            })
            .then(r => r.json())
            .then(list => {
                const unread = list.filter(n => !n.is_read);
                if (unread.length === 0) return;
                const n = unread[0];
                return self.registration.showNotification('📚 ' + (n.title || 'StudyTrack'), {
                    body:    n.message || 'You have a new notification.',
                    icon:    SITE_URL + '/images/studytrack.png',
                    badge:   SITE_URL + '/images/studytrack.png',
                    tag:     'notif-' + n.id,
                    data:    { url: SITE_URL + '/notifications' },
                    vibrate: [200, 100, 200],
                    requireInteraction: false,
                });
            })
            .catch(() => {
                // Silent fail — don't show error notification
            })
        );
        return;
    }

    const title   = data.title;
    const options = {
        body:    data.body || data.message || 'You have a new notification.',
        icon:    data.icon  || SITE_URL + '/images/studytrack.png',
        badge:   data.badge || SITE_URL + '/images/studytrack.png',
        tag:     data.tag   || 'studytrack-' + Date.now(),
        data:    { url: data.url || SITE_URL + '/notifications' },
        vibrate: [200, 100, 200],
        requireInteraction: false,
        actions: [
            { action: 'view',    title: '👁️ View' },
            { action: 'dismiss', title: '✕ Dismiss' },
        ],
    };

    event.waitUntil(self.registration.showNotification(title, options));
});

// ── Notification click ───────────────────────────────────────────────
self.addEventListener('notificationclick', function(event) {
    event.notification.close();
    if (event.action === 'dismiss') return;

    const url = (event.notification.data && event.notification.data.url)
        ? event.notification.data.url
        : SITE_URL + '/notifications';

    event.waitUntil(
        clients.matchAll({ type: 'window', includeUncontrolled: true }).then(list => {
            for (const c of list) {
                if (c.url.includes('studytrack') && 'focus' in c) {
                    c.focus();
                    return c.navigate(url);
                }
            }
            return clients.openWindow(url);
        })
    );
});