// Service Worker za go4.video PWA
const CACHE_NAME = 'go4-video-v1';
const urlsToCache = [
  '/',
  '/manifest.json',
  '/api/favicon',
  '/api/favicon?size=192',
  '/api/favicon?size=512'
];

// Instalacija service worker-ja
self.addEventListener('install', (event) => {
  event.waitUntil(
    caches.open(CACHE_NAME)
      .then((cache) => {
        console.log('PWA cache opened');
        return cache.addAll(urlsToCache);
      })
  );
});

// Aktivacija service worker-ja
self.addEventListener('activate', (event) => {
  event.waitUntil(
    caches.keys().then((cacheNames) => {
      return Promise.all(
        cacheNames.map((cacheName) => {
          if (cacheName !== CACHE_NAME) {
            console.log('Deleting old cache:', cacheName);
            return caches.delete(cacheName);
          }
        })
      );
    })
  );
});

// Prestrezanje omrežnih zahtev
self.addEventListener('fetch', (event) => {
  event.respondWith(
    caches.match(event.request)
      .then((response) => {
        // Vrni iz cache-a, če obstaja
        if (response) {
          return response;
        }
        
        // Sicer povleči iz omrežja
        return fetch(event.request).then((response) => {
          // Preveri ali je veljaven odgovor
          if (!response || response.status !== 200 || response.type !== 'basic') {
            return response;
          }

          // Kloniraj odgovor
          const responseToCache = response.clone();

          caches.open(CACHE_NAME)
            .then((cache) => {
              cache.put(event.request, responseToCache);
            });

          return response;
        });
      })
  );
});