/**
 * Service Worker для офлайн-режима админ-панели (NFR-016, PWA).
 * Кэширует статические ресурсы; при офлайне возвращает заглушку.
 */
const CACHE_NAME = 'cascad360-admin-v1';
const STATIC_ASSETS = [
  '/static/css/bootstrap.min.css',
  '/static/css/bootstrap-icons.css',
  '/static/css/style.css',
  '/static/js/bootstrap.bundle.min.js',
  '/static/js/menu.js',
  '/static/js/i18n.js',
  '/static/lang/ru.json',
  '/static/lang/en.json'
];

self.addEventListener('install', function(event) {
  const origin = self.location.origin;
  const urls = STATIC_ASSETS.map(function(p) { return origin + p; });
  event.waitUntil(
    caches.open(CACHE_NAME).then(function(cache) {
      return cache.addAll(urls).catch(function() {});
    }).then(function() {
      return self.skipWaiting();
    })
  );
});

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

self.addEventListener('fetch', function(event) {
  if (event.request.method !== 'GET') return;
  if (event.request.mode === 'navigate') {
    event.respondWith(
      fetch(event.request).catch(function() {
        return caches.match(event.request.url).then(function(cached) {
          if (cached) return cached;
          return new Response(
            '<!DOCTYPE html><html lang="ru"><head><meta charset="UTF-8"><title>Офлайн</title></head><body><p>Нет соединения. Проверьте сеть и обновите страницу.</p></body></html>',
            { headers: { 'Content-Type': 'text/html; charset=utf-8' } }
          );
        });
      })
    );
    return;
  }
  if (!event.request.url.startsWith(self.location.origin + '/static/')) return;
  event.respondWith(
    caches.match(event.request).then(function(cached) {
      return cached || fetch(event.request).then(function(response) {
        if (response && response.status === 200) {
          const clone = response.clone();
          caches.open(CACHE_NAME).then(function(cache) {
            cache.put(event.request, clone);
          });
        }
        return response;
      }).catch(function() {
        return caches.match(event.request);
      });
    })
  );
});
