import {
  lazy,
  Suspense,
  StrictMode,
} from 'react'
import ReactDOM from 'react-dom'

import * as Sentry from '@sentry/react'
import { BrowserTracing } from '@sentry/react'

import { isIOS } from 'config/userAgent'
// import { makeServer } from 'utilits/mirage/Mirage'

import * as serviceWorker from './serviceWorker'

if (process.env.NODE_ENV !== 'development') {
  Sentry.init({
    dsn: 'https://bbe0cdfb954644ebaf3be16bb472cc3d@sentry.insports.tv/21',
    environment: process.env.REACT_APP_ENV,
    integrations: [new BrowserTracing()],
    tracesSampleRate: 1.0,
  })
}

export const App = process.env.REACT_APP_TYPE === 'auth-service'
  ? lazy(() => import('features/AuthServiceApp'))
  : lazy(() => import('features/App'))

// если раскоментить, то включится miragejs
// process.env.NODE_ENV === 'development' && makeServer({ environment: 'development' })

ReactDOM.render(
  <StrictMode>
    <Suspense fallback={null}>
      <App />
    </Suspense>
  </StrictMode>,
  document.getElementById('root'),
)

if (isIOS) {
  serviceWorker.register({
    onUpdate: (registration) => {
      const waitingServiceWorker = registration.waiting
      if (waitingServiceWorker) {
        waitingServiceWorker.addEventListener('statechange', (event) => {
          // @ts-expect-error
          if (event.target?.state === 'activated') {
            window.location.reload()
          }
        })
        waitingServiceWorker.postMessage({ type: 'SKIP_WAITING' })
      }
    },
  })
} else {
  serviceWorker.unregister()
}
