const CACHE_NAME = 'easy-erp-v20260702_fix28';
const STATIC_ASSETS = [
    './index.html',
    './hr.html',
    './ready_mix.html',
    './style.css',
    './db.js',
    './app.js',
    './app_final_v12.js',
    './hr.js',
    './ready_mix.js'
];

// Install event - cache static assets
self.addEventListener('install', event => {
    event.waitUntil(
        caches.open(CACHE_NAME).then(cache => {
            return Promise.allSettled(
                STATIC_ASSETS.map(url => cache.add(url).catch(err => console.warn('Cache add failed for', url, err)))
            );
        }).then(() => self.skipWaiting())
    );
});

// Activate event - cleanup old caches
self.addEventListener('activate', event => {
    event.waitUntil(
        caches.keys().then(keys => {
            return Promise.all(
                keys.filter(key => key !== CACHE_NAME).map(key => caches.delete(key))
            );
        }).then(() => self.clients.claim())
    );
});

// Fetch event - NETWORK FIRST for everything
// Always try to get the latest from the server, fall back to cache only if offline
self.addEventListener('fetch', event => {
    event.respondWith(
        fetch(event.request).then(networkResponse => {
            // Update cache with latest version
            if (networkResponse && networkResponse.status === 200) {
                const responseClone = networkResponse.clone();
                caches.open(CACHE_NAME).then(cache => {
                    cache.put(event.request, responseClone);
                });
            }
            return networkResponse;
        }).catch(() => {
            // Network failed, fall back to cache (offline mode)
            return caches.match(event.request);
        })
    );
});
