const CACHE_NAME = 'singgih-eka-v' + new Date().getTime();

const urlsToCache = [
  './',
  './index.php',
  './riwayat.php',
  './ringkasan.php',
  './ai.php',
  './pengingat.php',
  './pengaturan.php',
  './manifest.json'
];

// Install event - cache files
self.addEventListener('install', (event) => {
  event.waitUntil(
    caches.open(CACHE_NAME)
      .then((cache) => {
        console.log('Cache opened');
        return cache.addAll(urlsToCache);
      })
      .catch((err) => {
        console.log('Cache failed:', err);
      })
  );
});

self.addEventListener('fetch', (event) => {
  // Jika API request, gunakan network-first strategy
  if (event.request.url.includes('/api/') || event.request.url.includes('.php?')) {
    event.respondWith(
      fetch(event.request)
        .then((response) => {
          // Cache jika berhasil
          if (response.status === 200) {
            const responseClone = response.clone();
            caches.open(CACHE_NAME).then((cache) => {
              cache.put(event.request, responseClone);
            });
          }
          return response;
        })
        .catch(() => {
          // Jika offline, gunakan cache
          return caches.match(event.request);
        })
    );
  } else {
    // Untuk file statis, gunakan cache-first
    event.respondWith(
      caches.match(event.request)
        .then((response) => {
          return response || fetch(event.request);
        })
    );
  }
});


// Activate event - clean up old caches
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);
          }
        })
      );
    })
  );
});
