/* EduTrack Teacher Portal — Service Worker */
const CACHE_VER  = 'tp-v1';
const STATIC_CACHE = [
    './index.php',
    './offline.html',
    './assets/tp.css',
    'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css',
];

// ── Install: pre-cache static shell ───────────────────────────
self.addEventListener('install', e => {
    e.waitUntil(
        caches.open(CACHE_VER).then(c => c.addAll(STATIC_CACHE)).then(() => self.skipWaiting())
    );
});

// ── Activate: purge old caches ─────────────────────────────────
self.addEventListener('activate', e => {
    e.waitUntil(
        caches.keys().then(keys =>
            Promise.all(keys.filter(k => k !== CACHE_VER).map(k => caches.delete(k)))
        ).then(() => self.clients.claim())
    );
});

// ── Fetch strategy ──────────────────────────────────────────────
self.addEventListener('fetch', e => {
    const url = new URL(e.request.url);

    // AJAX calls: network-first, no cache
    if (url.pathname.includes('/ajax/')) {
        e.respondWith(
            fetch(e.request).catch(() =>
                new Response(JSON.stringify({
                    success: false,
                    message: 'You are offline. Please reconnect.',
                    data: null,
                }), { headers: { 'Content-Type': 'application/json' } })
            )
        );
        return;
    }

    // Static assets & shell: stale-while-revalidate
    e.respondWith(
        caches.match(e.request).then(cached => {
            const network = fetch(e.request).then(res => {
                if (res.ok) {
                    const clone = res.clone();
                    caches.open(CACHE_VER).then(c => c.put(e.request, clone));
                }
                return res;
            }).catch(() => null);
            return cached || network || caches.match('./offline.html');
        })
    );
});
