import { useSuspenseQuery } from '@tanstack/react-query'
import { createFileRoute, notFound } from '@tanstack/react-router'
import { Helmet } from 'react-helmet-async'
import { NotFound } from '~/components/not-found'
import { PageView } from '~/components/page-view'
import { pageBySlugQuery } from '~/lib/queries'

export const Route = createFileRoute('/$slug')({
  loader: async ({ context: { queryClient }, params: { slug } }) => {
    const page = await queryClient.ensureQueryData(pageBySlugQuery(slug))
    if (!page) throw notFound()
  },
  component: CmsPage,
  notFoundComponent: () => <NotFound />,
})

function CmsPage() {
  const { slug } = Route.useParams()
  const { data: page } = useSuspenseQuery(pageBySlugQuery(slug))
  if (!page) return null

  return (
    <>
      {page.title && (
        <Helmet>
          <title>{page.title}</title>
        </Helmet>
      )}
      <PageView title={page.title} content={page.content} />
    </>
  )
}
