/* TiaStore frontend - TiaSolveIt | Solutions */
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import { registerSW } from 'virtual:pwa-register'
import App from './App'
import './index.css'

/* Service worker: production only, and in dev we actively remove it.
 *
 * This is not defensive boilerplate, it is the fix for a specific and very
 * confusing failure: you build the app, serve it, and the service worker
 * precaches the built assets and starts answering every fetch from its cache.
 * Then you run `npm run dev` on the same origin. The browser still has the
 * worker from the build, it still intercepts requests for the same paths, and
 * it keeps serving the OLD app. Reload does nothing. Edit a file, HMR updates
 * the module, and the screen does not change. The symptom is "I am running the
 * dev server and nothing I do to the code appears".
 *
 * The cure is to make dev actively hostile to service workers rather than
 * merely absent of them: in development we unregister every worker this origin
 * has and clear its caches, on every load. A leftover worker from a build gets
 * removed on the next dev page load instead of silently shadowing the dev
 * server forever.
 *
 * The PWA itself is not optional. Offline is the product, so the production
 * build must keep its worker. This only changes what happens while developing.
 */
if (import.meta.env.DEV) {
  if ('serviceWorker' in navigator) {
    void navigator.serviceWorker.getRegistrations().then((registrations) => {
      registrations.forEach((registration) => {
        void registration.unregister()
      })
    })

    /* Caches the worker created are not reachable from getRegistrations, so they
     * are cleared by name pattern. Without this the unregister is only half a
     * fix: the worker is gone but its precache is still on disk. */
    if ('caches' in window) {
      void caches.keys().then((keys) => {
        keys.forEach((key) => {
          void caches.delete(key)
        })
      })
    }
  }
} else {
  registerSW({ immediate: true })
}

/* App owns the router, and only App. Two BrowserRouters nested would make every
 * <Link> a no-op relative to the inner one, which is exactly the class of bug
 * where buttons silently stop navigating. */
createRoot(document.getElementById('root')!).render(
  <StrictMode>
    <App />
  </StrictMode>,
)
