const CACHE_NAME = 'cix-orbit-academy-v2';
const OFFLINE_URLS = [
    '/',
    '/public/assets/css/style.css',
    '/public/assets/js/app.js',
    '/public/assets/images/icon-192.png',
    '/public/assets/images/icon-512.png',
    '/public/assets/images/maskable-icon.png'
];

self.addEventListener('install', event => {
    event.waitUntil(
        caches.open(CACHE_NAME).then(cache => cache.addAll(OFFLINE_URLS))
    );
    self.skipWaiting();
});

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

self.addEventListener('fetch', event => {
    if (event.request.url.includes('/api/') || event.request.url.includes('/student/submit-test')) {
        return;
    }
    
    event.respondWith(
        fetch(event.request).then(response => {
            if (response && response.status === 200) {
                const responseClone = response.clone();
                caches.open(CACHE_NAME).then(cache => cache.put(event.request, responseClone));
            }
            return response;
        }).catch(() => {
            return caches.match(event.request).then(cached => {
                return cached || caches.match('/public/offline.html');
            });
        })
    );
});
