const CACHE_NAME = 'laundry-offline-v1';
const OFFLINE_URL = 'offline.html'; // Pastikan file offline.html ada di folder yang sama

// Install Service Worker dan simpan halaman offline ke cache
self.addEventListener('install', (event) => {
    event.waitUntil(
        caches.open(CACHE_NAME).then((cache) => {
            console.log('Service Worker: Caching offline page');
            return cache.add(OFFLINE_URL);
        })
    );
    // Paksa service worker aktif segera
    self.skipWaiting();
});

// Aktifkan Service Worker
self.addEventListener('activate', (event) => {
    event.waitUntil(self.clients.claim());
});

// Intercept request jaringan
self.addEventListener('fetch', (event) => {
    // Hanya tangani request navigasi (halaman utama), biarkan asset (css/js/img) lewat biasa
    if (event.request.mode === 'navigate') {
        event.respondWith(
            fetch(event.request).catch(() => {
                // Jika fetch gagal (offline), ambil dari cache
                return caches.open(CACHE_NAME).then((cache) => {
                    return cache.match(OFFLINE_URL);
                });
            })
        );
    }
});