// Service Worker for Services Homepage PWA
const CACHE_NAME = 'services-homepage-v1';
const ASSETS_TO_CACHE = [
  '/',
  '/index.html',
  '/styles.css',
  '/manifest.json',
  '/js/galaxy-background.js',
  '/js/services-loader.js',
  '/js/search.js',
  '/js/keyboard-nav.js',
  '/js/readme-loader.js',
  '/js/drag-drop.js',
  '/js/collapsible-groups.js',
  '/js/themes.js',
  '/js/export-import.js',
  '/js/widgets.js',
  '/FAQ.md',
  'https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js',
  'https://cdnjs.cloudflare.com/ajax/libs/simplex-noise/2.4.0/simplex-noise.min.js',
  'https://cdn.jsdelivr.net/npm/marked/marked.min.js'
];

// Install event - cache assets
self.addEventListener('install', (event) => {
  console.log('Service Worker installing...');
  event.waitUntil(
    caches.open(CACHE_NAME)
      .then((cache) => {
        console.log('Caching app assets');
        return cache.addAll(ASSETS_TO_CACHE);
      })
      .catch((error) => {
        console.error('Failed to cache assets:', error);
      })
  );
  self.skipWaiting();
});

// Activate event - clean up old caches
self.addEventListener('activate', (event) => {
  console.log('Service Worker activating...');
  event.waitUntil(
    caches.keys().then((cacheNames) => {
      return Promise.all(
        cacheNames.map((cacheName) => {
          if (cacheName !== CACHE_NAME) {
            console.log('Deleting old cache:', cacheName);
            return caches.delete(cacheName);
          }
        })
      );
    })
  );
  self.clients.claim();
});

// Fetch event - serve from cache, fallback to network
self.addEventListener('fetch', (event) => {
  const url = new URL(event.request.url);
  
  // Skip cross-origin requests, API calls, health checks, and dynamic content
  // Always let these go directly to the network
  if (url.origin !== self.location.origin ||
      event.request.url.includes('/api/') || 
      event.request.url.includes('/healthcheck') ||
      event.request.url.includes('services.xml')) {
    // Let it pass through to the network without intervention
    return;
  }

  event.respondWith(
    caches.match(event.request)
      .then((response) => {
        // Return cached version or fetch from network
        return response || fetch(event.request).then((fetchResponse) => {
          // Cache successful responses
          if (fetchResponse && fetchResponse.status === 200) {
            const responseClone = fetchResponse.clone();
            caches.open(CACHE_NAME).then((cache) => {
              cache.put(event.request, responseClone);
            });
          }
          return fetchResponse;
        });
      })
      .catch(() => {
        // Offline fallback
        if (event.request.destination === 'document') {
          return caches.match('/index.html');
        }
      })
  );
});

// Background sync for offline order saves (future enhancement)
self.addEventListener('sync', (event) => {
  if (event.tag === 'sync-order') {
    event.waitUntil(syncOrderData());
  }
});

async function syncOrderData() {
  // Future: sync any pending order changes when back online
  console.log('Syncing order data...');
}
