const CACHE_VERSION = 'ss-v2';

const STATIC_ASSETS = [
  '/',
  '/index.html',
  '/service.html',
  '/contact.html',
  '/abouts.html',
  '/whyus.html',
  '/signal_scale_styles.css',
  '/components.js',
  '/favicon.svg',
  '/images/Adaeze.webp',
  '/images/Gemini_Generated_Image_zia2bzzia2bzzia2.webp',
  '/images/Geo.webp',
  '/images/Geo-Intelligence.webp',
  '/images/geo-layer.webp',
  '/images/James.webp',
  '/images/Mia.webp',
  '/images/moats-hero.webp',
  '/images/Predictive.webp',
  '/images/Sofia.webp',
  '/images/Synthetic.webp',
  '/images/Synthetic-Content-Networks.webp',
];

// Install: cache all static assets
self.addEventListener('install', event => {
  event.waitUntil(
    caches.open(CACHE_VERSION).then(cache => cache.addAll(STATIC_ASSETS))
  );
  self.skipWaiting();
});

// Activate: delete old caches
self.addEventListener('activate', event => {
  event.waitUntil(
    caches.keys().then(keys =>
      Promise.all(keys.filter(k => k !== CACHE_VERSION).map(k => caches.delete(k)))
    )
  );
  self.clients.claim();
});

// Fetch: cache-first for assets, network-first for HTML
self.addEventListener('fetch', event => {
  const { request } = event;
  const url = new URL(request.url);

  // Only handle same-origin and Google Fonts
  if (url.origin !== location.origin && !url.hostname.includes('fonts.g')) return;

  // Google Fonts: stale-while-revalidate
  if (url.hostname.includes('fonts.g')) {
    event.respondWith(staleWhileRevalidate(request));
    return;
  }

  // HTML pages: network-first (stay fresh)
  if (request.headers.get('accept')?.includes('text/html')) {
    event.respondWith(networkFirst(request));
    return;
  }

  // Everything else (CSS, JS, images, fonts): cache-first
  event.respondWith(cacheFirst(request));
});

async function cacheFirst(request) {
  const cached = await caches.match(request);
  if (cached) return cached;
  const response = await fetch(request);
  if (response.ok) {
    const cache = await caches.open(CACHE_VERSION);
    cache.put(request, response.clone());
  }
  return response;
}

async function networkFirst(request) {
  const cache = await caches.open(CACHE_VERSION);
  try {
    const response = await fetch(request);
    if (response.ok) cache.put(request, response.clone());
    return response;
  } catch {
    const cached = await cache.match(request);
    return cached || cache.match('/index.html');
  }
}

async function staleWhileRevalidate(request) {
  const cache = await caches.open(CACHE_VERSION);
  const cached = await cache.match(request);
  const fetchPromise = fetch(request).then(response => {
    if (response.ok) cache.put(request, response.clone());
    return response;
  });
  return cached || fetchPromise;
}
