import { AuthProvider, useAuth } from '@context-providers/auth-context-provider'
import { ThemeProvider } from '@context-providers/theme-context-provider'
import { QueryClientProvider } from '@tanstack/react-query'
import { RouterProvider } from '@tanstack/react-router'

import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'

import { useFontsLoaded } from '@hooks/useFontsLoaded'
import { APP_CONFIG } from '@lib/config'
import { queryClient } from '@lib/query-client'
import { router } from '@lib/router'
import { createTrpcClient, TRPCProvider } from '@lib/trpc'

function AppRouter() {
  const auth = useAuth()

  return <RouterProvider router={router} context={{ auth }} />
}

function App() {
  const trpcClient = createTrpcClient({ apiUrl: APP_CONFIG.apiURL })

  // required for snapshot testing
  const fontsLoaded = useFontsLoaded()

  if (!trpcClient || !fontsLoaded) {
    return
  }

  return (
    <QueryClientProvider client={queryClient}>
      <TRPCProvider trpcClient={trpcClient} queryClient={queryClient}>
        <AuthProvider>
          <ThemeProvider>
            <AppRouter />
          </ThemeProvider>
        </AuthProvider>
      </TRPCProvider>
    </QueryClientProvider>
  )
}

createRoot(document.getElementById('root')!).render(
  <StrictMode>
    <App />
  </StrictMode>,
)
