const CACHE = 'snh-accounts-v4';

// Install — skip waiting immediately, cache assets on first use instead
self.addEventListener('install', e => {
    e.waitUntil(self.skipWaiting());
});

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

// Fetch — network first, fall back to cache
// PHP pages always go to network (live data); only static assets use cache
self.addEventListener('fetch', e => {
    const url = new URL(e.request.url);

    // Only handle same-origin requests
    if (url.origin !== self.location.origin) return;

    // For static assets (css, js, images, fonts) — cache first, network fallback
    if (/\.(css|js|png|jpg|jpeg|gif|svg|ico|woff2?)$/i.test(url.pathname)) {
        e.respondWith(
            caches.match(e.request).then(cached => {
                if (cached) return cached;
                return fetch(e.request).then(res => {
                    if (res.ok) {
                        const clone = res.clone();
                        caches.open(CACHE).then(c => c.put(e.request, clone));
                    }
                    return res;
                });
            }).catch(() => fetch(e.request))
        );
        return;
    }

    // For PHP pages — network first, show offline page on failure
    e.respondWith(
        fetch(e.request).catch(() => {
            return new Response(
                `<!DOCTYPE html><html><head><meta charset="utf-8">
                <meta name="viewport" content="width=device-width,initial-scale=1">
                <title>Offline</title>
                <style>
                    body{font-family:Arial,sans-serif;display:flex;align-items:center;
                    justify-content:center;min-height:100vh;margin:0;background:#0f172a;color:#fff;}
                    .box{text-align:center;padding:40px;}
                    .icon{font-size:64px;margin-bottom:16px;}
                    h2{margin:0 0 8px;}p{color:#94a3b8;margin:0 0 24px;}
                    button{padding:10px 24px;background:#2563eb;color:#fff;border:none;
                    border-radius:8px;font-size:15px;cursor:pointer;}
                </style></head>
                <body><div class="box">
                    <div class="icon">📡</div>
                    <h2>You are offline</h2>
                    <p>Please check your internet connection and try again.</p>
                    <button onclick="location.reload()">Retry</button>
                </div></body></html>`,
                { headers: { 'Content-Type': 'text/html' } }
            );
        })
    );
});
