const CACHE_NAME = 'rtku-pwa-cache-v1';
const urlsToCache = [
  'manifest.json',
  'assets/css/bootstrap.min.css',
  'assets/js/jquery-3.7.0.min.js',
  'assets/js/bootstrap.bundle.min.js',
  'assets/img/icon-192.png',
  'assets/img/icon-512.png'
];

// Install Event
self.addEventListener('install', event => {
  event.waitUntil(
    caches.open(CACHE_NAME)
      .then(cache => {
        return cache.addAll(urlsToCache);
      })
  );
});

// Fetch Event - Network First untuk HTML (Navigate), Cache First untuk aset statis
self.addEventListener('fetch', event => {
  // Hanya proses request GET
  if (event.request.method !== 'GET') return;

if (event.request.mode === 'navigate') {
  event.respondWith(
    fetch(event.request).catch(() => {
      return caches.match(event.request).then(cached => {
        // Kalau ada di cache, return. Kalau tidak, return response offline sederhana
        return cached || new Response(
          '<h2>Anda sedang offline</h2><p>Silakan cek koneksi internet Anda.</p>',
          { headers: { 'Content-Type': 'text/html; charset=utf-8' } }
        );
      });
    })
  );
  return;
}

  // Untuk request lainnya (CSS, JS, Image), gunakan Cache First
  event.respondWith(
    caches.match(event.request)
      .then(response => {
        // Return cache jika ada
        if (response) {
          return response;
        }

        // Jika tidak ada di cache, fetch dari network
        return fetch(event.request).then(
          function(networkResponse) {
            // Cek jika response valid
            if(!networkResponse || networkResponse.status !== 200 || networkResponse.type !== 'basic') {
              return networkResponse;
            }

            // Simpan ke cache untuk request berikutnya (Cache on the fly)
            const clone = networkResponse.clone();
            const url = new URL(event.request.url);
            
            if (url.origin === location.origin && (url.pathname.startsWith('/assets/') || url.pathname.endsWith('.js') || url.pathname.endsWith('.css'))) {
                caches.open(CACHE_NAME).then(function(cache) {
                    cache.put(event.request, clone);
                });
            }

            return networkResponse;
          }
        ).catch(error => {
          console.log('Offline / Gagal ambil aset: ', error);
        });
      })
  );
});

// Activate Event - Clean up old caches
self.addEventListener('activate', event => {
  const cacheWhitelist = [CACHE_NAME];
  event.waitUntil(
    caches.keys().then(cacheNames => {
      return Promise.all(
        cacheNames.map(cacheName => {
          if (cacheWhitelist.indexOf(cacheName) === -1) {
            return caches.delete(cacheName);
          }
        })
      );
    })
  );
});
