const CACHE_NAME = 'codePwa-v1';
const HTML_FALLBACK = '/index.html';

self.addEventListener('install', (event) => {
  // console.log('[SW] Installed');
  self.skipWaiting(); // Activate SW immediately
});

self.addEventListener('activate', (event) => {
  // console.log('[SW] Activated');
  event.waitUntil(
    caches.keys().then((cacheNames) =>
      Promise.all(
        cacheNames
          .filter((name) => name !== CACHE_NAME)
          .map((name) => caches.delete(name))
      )
    )
  );
  self.clients.claim(); // Control pages immediately
});

self.addEventListener('fetch', (event) => {
  const req = event.request;
  const url = new URL(req.url);

   // ❌ Skip non-GET and API requests
  if (req.method !== 'GET' || url.pathname.startsWith('/api/')) return;

  // Handle navigation requests (e.g., /home, /dashboard)
  if (req.mode === 'navigate') {
    event.respondWith(
      fetch(req)
        .then((response) => {
          return caches.open(CACHE_NAME).then((cache) => {
            cache.put(req, response.clone());
            return response;
          });
        })
        .catch((error) => {
          if (!navigator.onLine) {
            self.clients.matchAll().then((clients) => {
              clients.forEach((client) => {
                client.postMessage({ type: 'SET_OFFLINE' });
              });
            });

            return caches.match(req).then((res) => res || caches.match(HTML_FALLBACK));
          }

          // If online, ignore fetch error and do not affect UI
          return;
        })
    );
    return;
  }

  // Handle static files (JS, CSS, etc.)
  event.respondWith(
    caches.match(req).then((cachedResponse) => {
      if (cachedResponse) return cachedResponse;

      return fetch(req).then((networkResponse) => {
        return caches.open(CACHE_NAME).then((cache) => {
          cache.put(req, networkResponse.clone());
          return networkResponse;
        });
      });
    }).catch((error) => {
      if (!navigator.onLine) {
        self.clients.matchAll().then((clients) => {
          clients.forEach((client) => {
            client.postMessage({ type: 'SET_OFFLINE' });
          });
        });

        if (req.destination === 'image') {
          return caches.match('/fallback-image.png');
        }
      }

      // If online, ignore fetch error and do not affect UI
      return;
    })
  );
});

// Support skipWaiting message
self.addEventListener('message', (event) => {
  if (event.data && event.data.type === 'SKIP_WAITING') {
    self.skipWaiting();
  }
});
