const CACHE_NAME = 'icon-cache-v1';
const ICON_URLS = [
  // Preload common remote icons
  'https://arbodev.s3.ap-south-1.amazonaws.com/icon/tess/TESSRAPP_Icon_Email.svg',
  'https://arbodev.s3.ap-south-1.amazonaws.com/icon/tess/TESSRAPP_Icon_Add.svg',
  // Add more URLs to preload
];

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

self.addEventListener('fetch', (event) => {
  if (event.request.url.includes('arbodev.s3.ap-south-1.amazonaws.com/icon/tess/')) {
    event.respondWith(
      caches.match(event.request).then((response) => {
        return response || fetch(event.request).then((fetchResponse) => {
          return caches.open(CACHE_NAME).then((cache) => {
            cache.put(event.request, fetchResponse.clone());
            return fetchResponse;
          });
        });
      })
    );
  }
});

self.addEventListener('activate', (event) => {
  event.waitUntil(
    caches.keys().then((cacheNames) => {
      return Promise.all(
        cacheNames.map((cacheName) => {
          if (cacheName !== CACHE_NAME) {
            return caches.delete(cacheName);
          }
        })
      );
    })
  );
});