import { HeadContent, Outlet, Scripts } from '@tanstack/react-router'

import { lazy, Suspense } from 'react'
import { Toaster } from 'sonner'

import { APP_CONFIG } from '@lib/config'

const LazyDevtools = lazy(() =>
  Promise.all([
    import('@tanstack/react-devtools'),
    import('@tanstack/react-query-devtools'),
    import('@tanstack/react-router-devtools'),
  ]).then(([{ TanStackDevtools }, { ReactQueryDevtoolsPanel }, { TanStackRouterDevtoolsPanel }]) => ({
    default: () => (
      <TanStackDevtools
        config={{ position: 'bottom-left' }}
        plugins={[
          {
            name: 'TanStack Query',
            render: <ReactQueryDevtoolsPanel />,
          },
          {
            name: 'TanStack Router',
            render: <TanStackRouterDevtoolsPanel />,
          },
        ]}
      />
    ),
  })),
)

export const RootDocument = () => {
  return (
    <>
      {/* html header content */}
      <HeadContent />

      {/* page layout */}
      <div className="flex flex-col min-h-screen w-full">
        <Outlet />
      </div>

      {/* sonner toasts */}
      <Toaster
        richColors
        position="bottom-right"
        toastOptions={{
          style: {
            borderRadius: 'var(--radius)',
          },
        }}
      />

      {APP_CONFIG.enableDevTools && (
        <Suspense>
          <LazyDevtools />
        </Suspense>
      )}
      <Scripts />
    </>
  )
}
