(() => {
  const ping = () => {
    try {
      fetch('/__ping?ts=' + Date.now(), { cache: 'no-store', credentials: 'same-origin' }).catch(() => {});
    } catch (_) {}
  };

  const clearOldCaches = async () => {
    try {
      if ('serviceWorker' in navigator) {
        const regs = await navigator.serviceWorker.getRegistrations();
        await Promise.all(regs.map((reg) => reg.unregister().catch(() => {})));
      }
      if ('caches' in window) {
        const keys = await caches.keys();
        await Promise.all(keys.map((key) => caches.delete(key).catch(() => {})));
      }
    } catch (_) {}
  };

  clearOldCaches();
  ping();
  setInterval(ping, 5000);
  const bye = () => {
    try { navigator.sendBeacon('/__bye', 'bye'); } catch (_) {}
  };
  window.addEventListener('beforeunload', bye);
  window.addEventListener('pagehide', bye);
  document.addEventListener('visibilitychange', () => { if (!document.hidden) ping(); });
  window.__ELLOS_DESKTOP__ = true;
})();
