import type { QueryClient } from '@tanstack/react-query'
import { useSuspenseQuery } from '@tanstack/react-query'
import { createRootRouteWithContext, Outlet } from '@tanstack/react-router'
import { Helmet } from 'react-helmet-async'
import { ErrorState } from '~/components/error-state'
import { Shell } from '~/components/layout/shell'
import { NotFound } from '~/components/not-found'
import { globalsQuery, menusQuery } from '~/lib/queries'

export const Route = createRootRouteWithContext<{ queryClient: QueryClient }>()({
  loader: async ({ context: { queryClient } }) => {
    await Promise.all([queryClient.ensureQueryData(globalsQuery), queryClient.ensureQueryData(menusQuery)])
  },
  component: RootComponent,
  notFoundComponent: () => (
    <Shell>
      <NotFound />
    </Shell>
  ),
  errorComponent: ({ error, reset }) => (
    <Shell>
      <ErrorState error={error} reset={reset} />
    </Shell>
  ),
})

function RootComponent() {
  const { data: globals } = useSuspenseQuery(globalsQuery)
  return (
    <>
      <Helmet defaultTitle={globals.meta_title} titleTemplate={`%s — ${globals.meta_title}`}>
        <meta name="description" content={globals.meta_description} />
      </Helmet>
      <Shell>
        <Outlet />
      </Shell>
    </>
  )
}
