import { Suspense, lazy } from 'react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { BrowserRouter, useLocation } from 'react-router-dom'
import { ErrorBoundary } from './components/ErrorBoundary'
import { PlatformAuthProvider } from './auth/platform-auth'
import { isSuperTokensConfigured } from './auth/supertokens-runtime'
import { AppRouteTree } from './router/AppRouteTree'
import { AuthShellBackdropSync } from './router/AuthShellBackdropSync'
import { ROUTER_FUTURE_FLAGS } from './router/router-future'
import 'performative-ui'
import './styles/global.css'

const LazySuperTokensRouteWrapper = lazy(async () => ({
  default: (await import('./auth/SuperTokensRouteWrapper')).SuperTokensRouteWrapper,
}))

const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      staleTime: 60_000,
      retry: 1,
      refetchOnWindowFocus: false,
    },
  },
})

function routeRequiresAuthShell(pathname: string) {
  return pathname.startsWith('/app')
    || pathname === '/login'
    || pathname.startsWith('/login/')
    || pathname === '/register'
    || pathname.startsWith('/register/')
    || pathname.startsWith('/auth/')
}

function hasStoredPlatformUser() {
  if (typeof window === 'undefined') return false
  try {
    return Boolean(window.localStorage.getItem('hypertwist.platform.user.v1'))
  } catch {
    return false
  }
}

function MaybeSuperTokensWrapper({ children }: { children: React.ReactNode }) {
  const location = useLocation()

  if (!isSuperTokensConfigured()) {
    return <>{children}</>
  }

  const needsWrapper = routeRequiresAuthShell(location.pathname) || hasStoredPlatformUser()
  if (!needsWrapper) {
    return <>{children}</>
  }

  return (
    <Suspense fallback={<>{children}</>}>
      <LazySuperTokensRouteWrapper>{children}</LazySuperTokensRouteWrapper>
    </Suspense>
  )
}

export default function App() {
  return (
    <QueryClientProvider client={queryClient}>
      <BrowserRouter future={ROUTER_FUTURE_FLAGS}>
        <AuthShellBackdropSync />
        <MaybeSuperTokensWrapper>
          <PlatformAuthProvider>
            <ErrorBoundary>
              <AppRouteTree />
            </ErrorBoundary>
          </PlatformAuthProvider>
        </MaybeSuperTokensWrapper>
      </BrowserRouter>
    </QueryClientProvider>
  )
}
