import React from 'react'
import { createRoot } from 'react-dom/client'
import App from './App'
import { I18nProvider } from './i18n'
import './styles/index.css'

createRoot(document.getElementById('root')).render(
  <React.StrictMode>
    <I18nProvider>
      <App />
    </I18nProvider>
  </React.StrictMode>
)

// Service worker registration with friendlier in-app update banner

if ('serviceWorker' in navigator) {
  window.addEventListener('load', () => {
    const swUrl = `${import.meta.env.BASE_URL || './'}sw.js`
    navigator.serviceWorker.register(swUrl).then(registration => {
      console.log('ServiceWorker registered with scope:', registration.scope)

      // If there's an already-waiting worker, dispatch event to App
      if (registration.waiting) {
        window.dispatchEvent(new CustomEvent('swUpdate', { detail: registration }))
      }

      // Listen for new installing worker
      registration.addEventListener('updatefound', () => {
        const newWorker = registration.installing
        if (!newWorker) return
        newWorker.addEventListener('statechange', () => {
          if (newWorker.state === 'installed') {
            if (navigator.serviceWorker.controller) {
              // New content is available, dispatch event to App
              window.dispatchEvent(new CustomEvent('swUpdate', { detail: registration }))
            } else {
              console.log('Content cached for offline use.')
            }
          }
        })
      })
    }).catch(err => {
      console.warn('ServiceWorker registration failed:', err)
    })

    // Reload the page when the new service worker takes control
    navigator.serviceWorker.addEventListener('controllerchange', () => {
      window.location.reload()
    })
  })
}
