self.addEventListener('install', (event) => {
  event.waitUntil(
    caches.open('addwin-cache-v2').then((cache) => {
      return cache.addAll([
        '/',
        '/main.dart.js',
        '/flutter_bootstrap.js',
        '/assets/fonts/IRANSansXFaNum-Regular.woff2',
        '/assets/fonts/IRANSansXFaNum-Bold.woff2',
        '/assets/images/logo.webp',
        '/assets/images/favicon.png',

        '/assets/images/Icon-192.png',
        '/assets/styles.css',
        '/manifest.json',
        'https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.6.2/cropper.min.js',
        'https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.6.2/cropper.css'
      ]).catch((error) => {
        console.error('Cache addAll failed:', error);
      });
    })
  );
});

self.addEventListener('fetch', (event) => {
  event.respondWith(
    caches.match(event.request).then((response) => {
      if (response) {
        return response;
      }
      return fetch(event.request).then((networkResponse) => {
        if (!networkResponse || networkResponse.status !== 200 || networkResponse.type !== 'basic') {
          return networkResponse;
        }
        const responseToCache = networkResponse.clone();
        caches.open('addwin-cache-v2').then((cache) => {
          cache.put(event.request, responseToCache);
        });
        return networkResponse;
      }).catch((error) => {
        console.error('Fetch failed:', error);
        throw error;
      });
    })
  );
});

self.addEventListener('activate', (event) => {
  const cacheWhitelist = ['addwin-cache-v2'];
  event.waitUntil(
    caches.keys().then((cacheNames) => {
      return Promise.all(
        cacheNames.map((cacheName) => {
          if (!cacheWhitelist.includes(cacheName)) {
            return caches.delete(cacheName);
          }
        })
      );
    })
  );
});