import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import { Capacitor } from '@capacitor/core'
import './index.css'
import './App.css'
import App from './App.tsx'
import { InputProvider } from './input.tsx'
import { DualScreenBottomDisplay, DualScreenProvider, DualScreenStartupPrompt } from './dualScreen.tsx'
import { Iwt2BottomDisplay } from './modes/iwt2/Iwt2BottomDisplay.tsx'

const displayMode = new URLSearchParams(window.location.search).get('display')

createRoot(document.getElementById('root')!).render(
  <StrictMode>
    {displayMode === 'iwt2-bottom' ? (
      <InputProvider>
        <Iwt2BottomDisplay />
      </InputProvider>
    ) : displayMode === 'bottom' ? (
      <InputProvider>
        <DualScreenBottomDisplay />
      </InputProvider>
    ) : (
      <DualScreenProvider>
        <DualScreenStartupPrompt />
        <InputProvider>
          <App />
        </InputProvider>
      </DualScreenProvider>
    )}
  </StrictMode>,
)

const isNativeApp = Capacitor.isNativePlatform()

if (import.meta.env.PROD && isNativeApp && 'serviceWorker' in navigator) {
  navigator.serviceWorker.getRegistrations()
    .then((registrations) => Promise.all(registrations.map((registration) => registration.unregister())))
    .then(() => caches.keys())
    .then((keys) => Promise.all(keys.filter((key) => key.startsWith('chronicle-')).map((key) => caches.delete(key))))
    .catch(() => {
      // Native app assets should come directly from the APK when cache cleanup is unavailable.
    })
}

if (import.meta.env.PROD && !isNativeApp && 'serviceWorker' in navigator) {
  window.addEventListener('load', () => {
    navigator.serviceWorker.register('/service-worker.js').catch(() => {
      // Offline launch remains optional when registration is unavailable.
    })
  })
}
