import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import './styles.css'
import App from './App.jsx'

const APP_VERSION = 'mobile-20260414-04'

function ensureBootSplash() {
  if (document.getElementById('app-boot-splash')) return
  const style = document.createElement('style')
  style.id = 'app-boot-splash-style'
  style.textContent = `
    #app-boot-splash { position: fixed; inset: 0; background: #ffffff; display: flex; align-items: center; justify-content: center; z-index: 2147483647; }
    #app-boot-splash::after { content: ''; width: 32px; height: 32px; border: 4px solid rgba(0,176,155,0.25); border-top-color: #00b09b; border-radius: 50%; animation: app-boot-spin 1s linear infinite; }
    @keyframes app-boot-spin { to { transform: rotate(360deg); } }
  `
  document.head.appendChild(style)
  const splash = document.createElement('div')
  splash.id = 'app-boot-splash'
  document.body.appendChild(splash)
}

ensureBootSplash()

async function clearOldAppState() {
  const currentVersion = localStorage.getItem('dstation_app_version')
  if (currentVersion === APP_VERSION) return false

  const needsReload = Boolean(currentVersion)

  if ('caches' in window) {
    const keys = await caches.keys()
    await Promise.all(keys.filter(key => key.startsWith('dstation-b2b-')).map(key => caches.delete(key)))
  }

  if ('serviceWorker' in navigator && needsReload) {
    const registrations = await navigator.serviceWorker.getRegistrations()
    await Promise.all(registrations.map(registration => registration.unregister()))
  }

  localStorage.setItem('dstation_app_version', APP_VERSION)
  if (needsReload) {
    window.location.reload()
    return true
  }
  return false
}

function mountApp() {
  createRoot(document.getElementById('root')).render(
    <StrictMode>
      <App />
    </StrictMode>
  )
  requestAnimationFrame(() => {
    document.getElementById('app-boot-splash')?.remove()
  })
}

clearOldAppState()
  .then(reloading => { if (!reloading) mountApp() })
  .catch(error => { console.error('App refresh failed:', error); mountApp() })

if ('serviceWorker' in navigator) {
  window.addEventListener('load', () => {
    navigator.serviceWorker.register(`${import.meta.env.BASE_URL}sw.js`)
      .then(registration => registration.update())
      .catch(error => console.error('Service worker registration failed:', error))
  })
}
