import { createRootRoute, Outlet } from '@tanstack/react-router'
import { Toaster } from 'sonner'
import { useEffect } from 'react'

export const Route = createRootRoute({
  component: RootLayout,
})

function RootLayout() {
  useEffect(() => {
    fetch('/v1/store/branding')
      .then((r) => r.ok ? r.json() : null)
      .then((data: { name: string | null; hasLogo: boolean } | null) => {
        if (!data) return
        if (data.name) document.title = data.name
        if (data.hasLogo) {
          const link = document.querySelector<HTMLLinkElement>('link[rel="icon"]')
            ?? document.createElement('link')
          link.rel = 'icon'
          link.href = '/v1/store/logo'
          document.head.appendChild(link)
        }
      })
      .catch(() => {})
  }, [])

  return (
    <>
      <Outlet />
      <Toaster position="bottom-right" />
    </>
  )
}
