// Service Worker Unregister - Forces cache clear
if ("serviceWorker" in navigator) {
  navigator.serviceWorker.getRegistrations().then(function (registrations) {
    for (let registration of registrations) {
      registration.unregister();
      console.log("Service Worker unregistered");
    }
  });
}

// Clear all caches
if ("caches" in window) {
  caches.keys().then(function (cacheNames) {
    cacheNames.forEach(function (cacheName) {
      caches.delete(cacheName);
      console.log("Cache deleted:", cacheName);
    });
  });
}

// Force reload with cache bypass
const APP_VERSION = "v2025.12.15.2319";
const storedVersion = localStorage.getItem("app_version");

if (storedVersion !== APP_VERSION) {
  console.log("New version detected, clearing cache...");
  localStorage.setItem("app_version", APP_VERSION);

  // Clear localStorage except version
  const keysToKeep = ["app_version", "selected_profile_id"];
  const allKeys = Object.keys(localStorage);
  allKeys.forEach((key) => {
    if (!keysToKeep.includes(key)) {
      localStorage.removeItem(key);
    }
  });

  // Hard reload
  window.location.reload(true);
}
