'use strict';

const CACHE_NAME = 'ctm-mobile-shell-v69';
const SHELL_ASSETS = [
  '/m/',
  '/m/index.html',
  '/m/claim.html',
  '/m/app.css',
  '/m/app.js',
  '/js/session-search-utils.js',
  '/js/message-renderer.js',
  '/js/document-review-links.js',
  '/icon-32.png',
  '/icon-180.png',
  '/manifest.json',
];

self.addEventListener('install', (event) => {
  event.waitUntil(
    caches.open(CACHE_NAME)
      .then((cache) => cache.addAll(SHELL_ASSETS))
      .then(() => self.skipWaiting()),
  );
});

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

self.addEventListener('message', (event) => {
  if (event.data && event.data.type === 'CTM_SKIP_WAITING') {
    event.waitUntil(self.skipWaiting());
  }
});

// Network-first for app shell (HTML/CSS/JS) so code changes reach the phone
// on next reload instead of being trapped behind the old cache. Cache is only
// a fallback for offline use. Other assets (icons, manifest) stay cache-first.
self.addEventListener('fetch', (event) => {
  const url = new URL(event.request.url);
  if (url.origin !== location.origin) return;
  if (url.pathname.startsWith('/api/') || url.pathname === '/ws') return;
  if (event.request.method !== 'GET') return;

  const isAppShell =
    url.pathname === '/m/' ||
    url.pathname === '/m/index.html' ||
    url.pathname === '/m/app.css' ||
    url.pathname === '/m/app.js' ||
    url.pathname === '/m/claim.html' ||
    url.pathname.startsWith('/js/');

  if (isAppShell) {
    event.respondWith(
      fetch(new Request(event.request, { cache: 'reload' }))
        .then((response) => {
          if (response.ok) {
            const clone = response.clone();
            caches.open(CACHE_NAME).then((cache) => cache.put(event.request, clone));
          }
          return response;
        })
        .catch(() => caches.match(event.request).then((cached) => cached || Response.error())),
    );
    return;
  }

  event.respondWith(
    caches.match(event.request).then((cached) => {
      if (cached) return cached;
      return fetch(event.request).then((response) => {
        if (response.ok && url.pathname.startsWith('/m/')) {
          const clone = response.clone();
          caches.open(CACHE_NAME).then((cache) => cache.put(event.request, clone));
        }
        return response;
      });
    }),
  );
});

self.addEventListener('push', (event) => {
  let payload = {};
  try { payload = event.data ? event.data.json() : {}; } catch { payload = {}; }
  const title = payload.title || 'CTM update';
  const options = {
    body: payload.body || 'Open CTM on your phone for details.',
    tag: payload.tag || payload.id || 'ctm-mobile',
    renotify: !!payload.renotify,
    timestamp: payload.timestamp || Date.now(),
    icon: '/icon-180.png',
    badge: '/icon-32.png',
    data: payload.data || {},
  };
  event.waitUntil((async () => {
    if (navigator.setAppBadge && payload.badgeCount) {
      try { await navigator.setAppBadge(payload.badgeCount); } catch {}
    }
    await self.registration.showNotification(title, options);
  })());
});

self.addEventListener('notificationclick', (event) => {
  event.notification.close();
  const deepLink = event.notification?.data?.deepLink || '/m/';
  let target = new URL('/m/', self.location.origin).toString();
  try {
    const parsed = new URL(deepLink, self.location.origin);
    if (parsed.origin === self.location.origin && parsed.pathname.startsWith('/m/')) {
      target = parsed.toString();
    }
  } catch {}
  event.waitUntil((async () => {
    const clientList = await self.clients.matchAll({ type: 'window', includeUncontrolled: true });
    for (const client of clientList) {
      if (client.url.startsWith(self.location.origin) && 'focus' in client) {
        if ('navigate' in client) await client.navigate(target);
        return client.focus();
      }
    }
    return self.clients.openWindow(target);
  })());
});
