/* ============================================================================
   GamesJi Top War — Service Worker
   Cache-first offline support for a fully self-contained PWA.
   Bump CACHE_VERSION whenever shipped files change so clients pick up updates.
   ============================================================================ */
const CACHE_VERSION = "topwar-cache-v1";
const PRECACHE_URLS = [
  "./",
  "index.html",
  "style.css",
  "script.js",
  "manifest.json",
  "assets/fonts/LiberationSans-Bold.ttf",
  "assets/fonts/LiberationSans-Regular.ttf",
  "assets/fonts/OFL-LICENSE.txt",
  "assets/icons/apple-touch-icon.png",
  "assets/icons/favicon-16.png",
  "assets/icons/favicon-32.png",
  "assets/icons/favicon.ico",
  "assets/icons/fx_merge_glow.png",
  "assets/icons/icon-192.png",
  "assets/icons/icon-512.png",
  "assets/icons/icon-maskable-512.png",
  "assets/icons/ui_arrow.png",
  "assets/icons/ui_calendar.png",
  "assets/icons/ui_check.png",
  "assets/icons/ui_chest.png",
  "assets/icons/ui_close.png",
  "assets/icons/ui_home.png",
  "assets/icons/ui_lock.png",
  "assets/icons/ui_music.png",
  "assets/icons/ui_pause.png",
  "assets/icons/ui_play.png",
  "assets/icons/ui_settings.png",
  "assets/icons/ui_shop.png",
  "assets/icons/ui_sound_off.png",
  "assets/icons/ui_sound_on.png",
  "assets/icons/ui_star.png",
  "assets/icons/ui_star_empty.png",
  "assets/icons/ui_trophy.png",
  "assets/images/bg_battle.jpg",
  "assets/images/bg_menu.jpg",
  "assets/images/building_airport.png",
  "assets/images/building_barracks.png",
  "assets/images/building_factory.png",
  "assets/images/building_garage.png",
  "assets/images/building_hospital.png",
  "assets/images/building_hq.png",
  "assets/images/building_power_plant.png",
  "assets/images/building_radar.png",
  "assets/images/building_research_lab.png",
  "assets/images/building_warehouse.png",
  "assets/images/logo_mark.png",
  "assets/images/og_share.jpg",
  "assets/images/resource_coins.png",
  "assets/images/resource_diamonds.png",
  "assets/images/resource_energy.png",
  "assets/images/resource_fuel.png",
  "assets/images/resource_steel.png",
  "assets/images/unit_drone.png",
  "assets/images/unit_heavy_soldier.png",
  "assets/images/unit_heavy_tank.png",
  "assets/images/unit_helicopter.png",
  "assets/images/unit_infantry.png",
  "assets/images/unit_missile_helicopter.png",
  "assets/images/unit_rocket_tank.png",
  "assets/images/unit_sniper.png",
  "assets/images/unit_tank.png",
  "assets/music/theme_battle.mp3",
  "assets/music/theme_menu.mp3",
  "assets/music/theme_victory.mp3",
  "assets/sounds/build.mp3",
  "assets/sounds/chest_open.mp3",
  "assets/sounds/click.mp3",
  "assets/sounds/click_back.mp3",
  "assets/sounds/coin.mp3",
  "assets/sounds/defeat.mp3",
  "assets/sounds/explosion.mp3",
  "assets/sounds/gunshot.mp3",
  "assets/sounds/level_up.mp3",
  "assets/sounds/merge.mp3",
  "assets/sounds/notification.mp3",
  "assets/sounds/rocket.mp3",
  "assets/sounds/ui_tap.mp3",
  "assets/sounds/upgrade.mp3",
  "assets/sounds/victory.mp3",
  "favicon.ico"
];

self.addEventListener("install", (event) => {
  event.waitUntil(
    caches.open(CACHE_VERSION)
      .then((cache) => cache.addAll(PRECACHE_URLS))
      .catch((err) => console.warn("[sw] precache failed:", err))
  );
  self.skipWaiting();
});

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

self.addEventListener("fetch", (event) => {
  const req = event.request;
  if (req.method !== "GET") return;
  const url = new URL(req.url);
  if (url.origin !== self.location.origin) return; // no external assets in this project

  // Navigation requests: try network first (fresh HTML), fall back to cache, then to index.html.
  if (req.mode === "navigate") {
    event.respondWith(
      fetch(req)
        .then((res) => {
          const clone = res.clone();
          caches.open(CACHE_VERSION).then((cache) => cache.put(req, clone));
          return res;
        })
        .catch(() => caches.match(req).then((cached) => cached || caches.match("index.html")))
    );
    return;
  }

  // Static assets: cache-first, then network, caching the fresh copy for next time.
  event.respondWith(
    caches.match(req).then((cached) => {
      if (cached) return cached;
      return fetch(req)
        .then((res) => {
          if (res && res.status === 200) {
            const clone = res.clone();
            caches.open(CACHE_VERSION).then((cache) => cache.put(req, clone));
          }
          return res;
        })
        .catch(() => cached);
    })
  );
});
