import { HeadContent, Outlet, Scripts, createRootRoute, useLocation } from '@tanstack/react-router'
import { RootDocument } from '@/lib/root-document'
import { NotFoundTitle } from '@/components/NotFoundTitle'
import { metadataToHead } from '@/lib/head'
import {
  DEFAULT_OG_IMAGE,
  DEFAULT_SITE_DESCRIPTION,
  DEFAULT_SITE_TITLE,
  SITE_NAME,
  SITE_URL,
  getAbsoluteUrl,
} from '@/lib/seo'
import { getResolvedLocale } from '@/lib/request-routing'

const rootMetadata = {
  metadataBase: new URL(SITE_URL),
  applicationName: SITE_NAME,
  title: DEFAULT_SITE_TITLE,
  description: DEFAULT_SITE_DESCRIPTION,
  manifest: '/site.webmanifest',
  icons: {
    icon: [
      { url: '/favicon.ico' },
      { url: '/favicon-16x16.png', sizes: '16x16', type: 'image/png' },
      { url: '/favicon-32x32.png', sizes: '32x32', type: 'image/png' },
    ],
    apple: [{ url: '/apple-touch-icon.png', sizes: '180x180' }],
  },
  openGraph: {
    title: DEFAULT_SITE_TITLE,
    description: DEFAULT_SITE_DESCRIPTION,
    url: SITE_URL,
    siteName: SITE_NAME,
    type: 'website',
    images: [{ url: getAbsoluteUrl(DEFAULT_OG_IMAGE), alt: SITE_NAME }],
  },
  twitter: {
    card: 'summary_large_image',
    title: DEFAULT_SITE_TITLE,
    description: DEFAULT_SITE_DESCRIPTION,
    images: [getAbsoluteUrl(DEFAULT_OG_IMAGE)],
  },
}

export const Route = createRootRoute({
  head: () => metadataToHead(rootMetadata),
  notFoundComponent: NotFoundTitle,
  component: RootComponent,
})

function RootComponent() {
  const pathname = useLocation({ select: (location) => location.pathname })
  const lang = getResolvedLocale(pathname)
  const initialTheme =
    typeof document === 'undefined'
      ? 'light'
      : ((document.cookie
          .split(';')
          .map((part) => part.trim())
          .find((part) => part.startsWith('mantine-color-scheme='))
          ?.split('=')[1] ?? 'light') as 'light' | 'dark' | 'auto')

  return (
    <RootDocument
      lang={lang}
      initialTheme={initialTheme}
      gaId={import.meta.env.VITE_GA_ID ?? import.meta.env.GA_ID}
      headContent={<HeadContent />}
      bodyEnd={<Scripts />}
    >
      <Outlet />
    </RootDocument>
  )
}
