/**
 * TechShop Perú - Service Worker (PWA)
 */

const CACHE_NAME = 'techshop-v2';
const ASSETS_TO_CACHE = [
  './',
  './index.php',
  './assets/css/styles.css',
  './assets/js/main.js',
  './assets/images/favicon.svg',
  './assets/images/placeholder-product.svg'
];

// Instalar Service Worker y guardar assets básicos
self.addEventListener('install', function (e) {
  e.waitUntil(
    caches.open(CACHE_NAME).then(function (cache) {
      return cache.addAll(ASSETS_TO_CACHE);
    })
  );
  self.skipWaiting();
});

// Activar y limpiar cachés antiguas
self.addEventListener('activate', function (e) {
  e.waitUntil(
    caches.keys().then(function (keys) {
      return Promise.all(
        keys.map(function (key) {
          if (key !== CACHE_NAME) {
            return caches.delete(key);
          }
        })
      );
    })
  );
  self.clients.claim();
});

// Estrategia de red primero, fallback a caché
self.addEventListener('fetch', function (e) {
  if (e.request.method !== 'GET') return;
  
  e.respondWith(
    fetch(e.request).catch(function () {
      return caches.match(e.request);
    })
  );
});
