// Puzzle Balls service worker
// Provides an offline-capable app shell and satisfies the installability
// requirement for PWA install prompts (Add to Home Screen / desktop install).

var CACHE_NAME = 'ballconnect-cache-v1';
var APP_SHELL = [
  './',
  './index.html',
  './manifest.json',
  './icon-192.png',
  './icon-512.png'
];

self.addEventListener('install', function(event){
  event.waitUntil(
    caches.open(CACHE_NAME)
      .then(function(cache){ return cache.addAll(APP_SHELL); })
      .catch(function(){ /* non-fatal: game still works without precache */ })
  );
  self.skipWaiting();
});

self.addEventListener('activate', function(event){
  event.waitUntil(
    caches.keys().then(function(keys){
      return Promise.all(
        keys.filter(function(key){ return key !== CACHE_NAME; })
            .map(function(key){ return caches.delete(key); })
      );
    })
  );
  self.clients.claim();
});

// Network-first for navigation requests (so players always get the latest
// build when online), falling back to the cached shell when offline.
// Cache-first for static assets (fonts, icons) for speed.
self.addEventListener('fetch', function(event){
  if(event.request.method !== 'GET') return;

  var isNavigation = event.request.mode === 'navigate';

  if(isNavigation){
    event.respondWith(
      fetch(event.request)
        .then(function(response){
          var clone = response.clone();
          caches.open(CACHE_NAME).then(function(cache){ cache.put(event.request, clone); });
          return response;
        })
        .catch(function(){ return caches.match('./index.html'); })
    );
    return;
  }

  event.respondWith(
    caches.match(event.request).then(function(cached){
      if(cached) return cached;
      return fetch(event.request).then(function(response){
        if(response && response.status === 200){
          var clone = response.clone();
          caches.open(CACHE_NAME).then(function(cache){ cache.put(event.request, clone); });
        }
        return response;
      }).catch(function(){ /* offline and not cached: let it fail naturally */ });
    })
  );
});
