const CACHE_NAME = 'cmux-remote-v3';
const STATIC_ASSETS = [
  '/',
  '/index.html',
  '/login.html',
  '/css/main.css',
  '/css/terminal.css',
  '/css/keyboard.css',
  '/css/sidebar.css',
  '/css/themes.css',
  '/js/app.js',
  '/js/auth.js',
  '/js/terminal-view.js',
  '/js/websocket-client.js',
  '/js/virtual-keyboard.js',
  '/js/sidebar.js',
  '/js/gestures.js',
  '/js/theme.js',
];

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

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

self.addEventListener('fetch', (event) => {
  // Skip API and WebSocket requests
  const url = new URL(event.request.url);
  if (url.pathname.startsWith('/api/') || event.request.headers.get('upgrade') === 'websocket') {
    return;
  }

  event.respondWith(
    fetch(event.request)
      .then((response) => {
        const clone = response.clone();
        caches.open(CACHE_NAME).then((cache) => cache.put(event.request, clone));
        return response;
      })
      .catch(() => caches.match(event.request))
  );
});
