import {createRoot} from 'react-dom/client';
import {registerSW} from 'virtual:pwa-register';
import App from './App.tsx';
import './index.css';

createRoot(document.getElementById('root')!).render(<App />);

// ---------------------------------------------------------------------------
// PWA update handling.
//
// Workbox precaches `index.html` and serves it through a NavigationRoute, so an
// already-open tab keeps executing the bundle it was loaded with — even after a
// new build is deployed and the service worker has been replaced. That is how a
// tab can keep talking to the API with stale client code (e.g. missing auth
// headers) for days. Reloading once when the new worker takes control keeps
// every tab on the freshest build.
// ---------------------------------------------------------------------------
if ('serviceWorker' in navigator) {
  let reloading = false;
  // On a first visit the worker claims the page and fires `controllerchange`
  // too — nothing is stale then, so only reload when replacing an old worker.
  const hadController = Boolean(navigator.serviceWorker.controller);

  navigator.serviceWorker.addEventListener('controllerchange', () => {
    if (!hadController || reloading) return;
    reloading = true;
    window.location.reload();
  });

  registerSW({
    immediate: true,
    onRegisteredSW(_swUrl: string, registration?: ServiceWorkerRegistration) {
      if (!registration) return;

      const checkForUpdate = () => {
        if (!navigator.onLine) return;
        registration.update().catch(() => {
          // Offline or transient network failure: the next check retries.
        });
      };

      window.setInterval(checkForUpdate, 10 * 60 * 1000);
      document.addEventListener('visibilitychange', () => {
        if (document.visibilityState === 'visible') checkForUpdate();
      });
      window.addEventListener('focus', checkForUpdate);
    },
  });
}
