const CACHE_VERSION = 'melonlite-pwa-v33-20260628';
const APP_SHELL = [
  './offline.php',
  './manifest.json',
  './assets/css/style.css',
  './assets/js/sidebar.js',
  './assets/js/playlist.js',
  './assets/js/tags.js',
  './assets/js/notes.js',
  './assets/js/search.js',
  './assets/js/player.js',
  './assets/js/app-navigation.js',
  './assets/js/pwa.js',
  './assets/img/default-cover.svg',
  './assets/img/icons/icon-192.png',
  './assets/img/icons/icon-512.png'
];

const NEVER_CACHE_PATTERNS = [
  /\/stream\.php/i,
  /\/cover\.php/i,
  /\/api\//i,
  /\/ajax\//i,
  /\/admin\//i,
  /\/login\.php/i,
  /\/logout\.php/i,
  /\/auto_playlist_save\.php/i,
  /\/scan\.php/i,
  /\/settings_save\.php/i,
  /\/backup(_|\.)/i,
  /\/restore\.php/i,
  /\/import\.php/i,
  /\/export\.php/i,
  /\/backup_download\.php/i,
  /\/admin\/backup/i,
  /\/admin\/export/i,
  /\/admin\/import/i,
  /\/admin\/restore/i,
  /\/admin\/settings_import/i,
  /\/admin\/metadata_action/i
];

const DYNAMIC_NO_CACHE_PATTERNS = [
  /\/search\.php/i,
  /\/recommend\.php/i,
  /\/auto_playlist\.php/i,
  /\/auto_playlists\.php/i,
  /\/index\.php/i,
  /\/playlist_view\.php/i
];

function shouldNeverCache(url) {
  return NEVER_CACHE_PATTERNS.some((pattern) => pattern.test(url.pathname));
}

function shouldSkipRuntimeCache(url) {
  if (url.searchParams.has('partial') || url.searchParams.has('ajax')) return true;
  if (url.searchParams.has('q') || url.searchParams.has('search')) return true;
  return DYNAMIC_NO_CACHE_PATTERNS.some((pattern) => pattern.test(url.pathname));
}

self.addEventListener('install', (event) => {
  event.waitUntil(
    caches.open(CACHE_VERSION)
      .then((cache) => cache.addAll(APP_SHELL))
      .catch(() => undefined)
  );
  self.skipWaiting();
});

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

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

self.addEventListener('fetch', (event) => {
  const request = event.request;
  if (request.method !== 'GET') return;

  const url = new URL(request.url);
  if (shouldNeverCache(url)) return;

  if (request.mode === 'navigate') {
    event.respondWith(
      fetch(request).catch(() => caches.match('./offline.php'))
    );
    return;
  }

  if (shouldSkipRuntimeCache(url)) return;

  event.respondWith(
    caches.match(request).then((cached) => {
      if (cached) return cached;
      return fetch(request).then((response) => {
        if (!response || response.status !== 200 || response.type === 'opaque') return response;
        const cacheControl = response.headers.get('Cache-Control') || '';
        if (/no-store|private/i.test(cacheControl)) return response;
        const pathname = url.pathname;
        const cacheable = pathname.endsWith('.css')
          || pathname.endsWith('.js')
          || pathname.endsWith('.png')
          || pathname.endsWith('.svg')
          || pathname.endsWith('manifest.json')
          || pathname.endsWith('offline.php');
        if (cacheable) {
          const responseClone = response.clone();
          caches.open(CACHE_VERSION).then((cache) => cache.put(request, responseClone));
        }
        return response;
      });
    }).catch(() => {
      if (request.destination === 'document') return caches.match('./offline.php');
      return Response.error();
    })
  );
});
