import ReactDOM from 'react-dom/client'
import { RouterProvider } from '@tanstack/react-router'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { useEffect, useRef } from 'react'
import { AuthProvider, useAuth } from '#/features/auth'
import { ThemeProvider } from '#/shared/components/theme-provider'
import { getRouter } from './app/router'
import { TooltipProvider } from '#/shared/ui/tooltip'
import { Spinner } from '#/shared/ui/spinner'

const queryClient = new QueryClient()
const router = getRouter()

function InnerApp() {
  const auth = useAuth()
  const initialMount = useRef(true)

  // Invalidate router AFTER React commits the new auth state so that
  // beforeLoad receives the up-to-date context (e.g. isAuthenticated:false
  // after logout/session-expired/multi-tab sync).
  // Skip the initial mount — RouterProvider already runs beforeLoad on first
  // render with the correct auth state.
  useEffect(() => {
    if (initialMount.current) {
      initialMount.current = false
      return
    }
    router.invalidate()
  }, [auth.isAuthenticated])

  // Defer router mount until auth is resolved — ensures beforeLoad never
  // receives isLoading:true.
  if (auth.isLoading) {
    return (
      <div className="flex min-h-svh items-center justify-center">
        <Spinner className="size-8" />
      </div>
    )
  }

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

const rootElement = document.getElementById('app')!

if (!rootElement.innerHTML) {
  const root = ReactDOM.createRoot(rootElement)
  root.render(
    <QueryClientProvider client={queryClient}>
      <ThemeProvider defaultTheme="light" storageKey="vite-ui-theme">
        <TooltipProvider>
          <AuthProvider>
            <InnerApp />
          </AuthProvider>
        </TooltipProvider>
      </ThemeProvider>
    </QueryClientProvider>,
  )
}
