// Obtener baseURL dinámicamente a partir de la ubicación del SW
//const baseUrl = self.location.pathname.replace(/\/[^\/]+$/, ''); 
const baseUrl = self.location.pathname
  .split('/')
  .slice(0, -2)
  .join('/');

const CACHE_NAME = 'appquadrata-cache-v1.0';

const FILES_TO_CACHE = [
  `${baseUrl}/`,
  `${baseUrl}/index.php`,
  `${baseUrl}/dist/css/style_app.css`,
  `${baseUrl}/dist/js/app.js`,
  `${baseUrl}/pwa/icon-192x192.png`,
  `${baseUrl}/pwa/icon-512x512.png`
];

console.log('[SW] baseUrl detectado:', baseUrl);
console.log('[SW] Archivos a cachear:', FILES_TO_CACHE);

// INSTALACIÓN
self.addEventListener('install', event => {
  console.log('[SW] Instalando y precacheando desde:', baseUrl);
  event.waitUntil(
    caches.open(CACHE_NAME).then(cache => {
      return cache.addAll(FILES_TO_CACHE);
    })
  );
  self.skipWaiting();
});

// ACTIVACIÓN
self.addEventListener('activate', event => {
  console.log('[SW] Activando y limpiando cachés viejos');
  event.waitUntil(
    caches.keys().then(keys =>
      Promise.all(
        keys.map(key => {
          if (key !== CACHE_NAME) {
            console.log('[SW] Eliminando caché:', key);
            return caches.delete(key);
          }
        })
      )
    )
  );
  self.clients.claim();
});

// FETCH: Cache first, luego red
self.addEventListener('fetch', event => {
  if (event.request.method !== 'GET') return;

  event.respondWith(
    caches.match(event.request).then(cached => {
      return cached || fetch(event.request).then(response => {
        return caches.open(CACHE_NAME).then(cache => {
          cache.put(event.request, response.clone());
          return response;
        });
      }).catch(() => {
        // Puedes retornar una página offline aquí si quieres
      });
    })
  );
});
