import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import { BrowserRouter } from 'react-router-dom'
import './index.css'
import App from './App.tsx'

const PWA_UPDATE_EVENT = 'badminton-scoreboard:pwa-update-ready'

createRoot(document.getElementById('root')!).render(
  <StrictMode>
    <BrowserRouter>
      <App />
    </BrowserRouter>
  </StrictMode>,
)

if (import.meta.env.PROD && 'serviceWorker' in navigator) {
  window.addEventListener('load', () => {
    let refreshing = false

    const notifyUpdateReady = () => {
      window.dispatchEvent(new CustomEvent(PWA_UPDATE_EVENT))
    }

    const trackWorker = (worker: ServiceWorker | null) => {
      if (!worker) {
        return
      }

      worker.addEventListener('statechange', () => {
        if (worker.state === 'installed' && navigator.serviceWorker.controller) {
          notifyUpdateReady()
        }
      })
    }

    navigator.serviceWorker.addEventListener('controllerchange', () => {
      if (refreshing) {
        return
      }

      refreshing = true
      window.location.reload()
    })

    void navigator.serviceWorker
      .register('/sw.js', {
        updateViaCache: 'none',
      })
      .then((registration) => {
      if (registration.waiting) {
        notifyUpdateReady()
      }

      trackWorker(registration.installing)
      registration.addEventListener('updatefound', () => {
        trackWorker(registration.installing)
      })
      void registration.update()
    })
  })
}
