import { QueryClientProvider } from '@tanstack/react-query'
import { RouterProvider } from '@tanstack/react-router'
import { lazy, StrictMode, Suspense } from 'react'
import { createRoot } from 'react-dom/client'
import { getCurrentUserProfile, refreshAuthSession } from '@/api'
import { AppBootResourceGate } from '@/components/app-boot-resource-gate'
import { AppNotificationAlert } from '@/components/ui/notification-alert'
import { APP_ROOT_ELEMENT_ID } from '@/constants'
import { GlobalAudioController } from '@/features/game/audio/global-audio-controller'
import '@/i18n'
import { prefetchAuthToken } from '@/lib/api/api-client'
import {
  initializeAuthSession,
  registerCurrentUserInitializer,
  registerRefreshSessionHandler,
} from '@/lib/auth/auth-session'
import { queryClient } from '@/lib/query/query-client'
import { router } from '@/router'
import './style/index.css'

const rootElement = document.getElementById(APP_ROOT_ELEMENT_ID)
const shouldShowQueryDevtools =
  import.meta.env.VITE_APP_ENV === 'development' &&
  import.meta.env.VITE_ENABLE_QUERY_DEVTOOLS === 'true'
const QueryDevtools = shouldShowQueryDevtools
  ? lazy(async () => {
      const { ReactQueryDevtools } = await import(
        '@tanstack/react-query-devtools'
      )

      return { default: ReactQueryDevtools }
    })
  : null

if (!rootElement) {
  throw new Error('Root element not found')
}

registerCurrentUserInitializer(getCurrentUserProfile)
registerRefreshSessionHandler(refreshAuthSession)

void initializeAuthSession().then(async () => {
  try {
    await prefetchAuthToken()
  } catch (error) {
    console.error('Failed to prefetch auth token', error)
  }
})

createRoot(rootElement).render(
  <StrictMode>
    <QueryClientProvider client={queryClient}>
      <AppBootResourceGate>
        <GlobalAudioController />
        <RouterProvider router={router} />
        <AppNotificationAlert />
        {QueryDevtools && (
          <Suspense fallback={null}>
            <QueryDevtools initialIsOpen={false} />
          </Suspense>
        )}
      </AppBootResourceGate>
    </QueryClientProvider>
  </StrictMode>,
)
