import { HeadContent, Scripts, createRootRoute } from '@tanstack/react-router'
import { TanStackRouterDevtoolsPanel } from '@tanstack/react-router-devtools'
import { TanStackDevtools } from '@tanstack/react-devtools'

import appCss from '../styles.css?url'

export const Route = createRootRoute({
  notFoundComponent: NotFound,
  errorComponent: RootError,
  head: () => ({
    meta: [
      {
        charSet: 'utf-8',
      },
      {
        name: 'viewport',
        content: 'width=device-width, initial-scale=1',
      },
      {
        title: 'Signal-Learn | Feedback kelas secara real-time',
      },
    ],
    links: [
      {
        rel: 'stylesheet',
        href: appCss,
      },
    ],
  }),
  shellComponent: RootDocument,
})

function NotFound() {
  return (
    <main className="flex min-h-screen items-center justify-center bg-cream p-6 text-center">
      <div>
        <p className="text-sm font-semibold text-clay">404</p>
        <h1 className="mt-2 text-2xl font-bold text-ink">Halaman tidak ditemukan</h1>
        <p className="mt-2 text-sm text-body">URL yang Anda buka tidak tersedia.</p>
        <a className="mt-5 inline-block text-sm font-semibold text-clay hover:text-indigo-700" href="/">Kembali ke beranda</a>
      </div>
    </main>
  )
}

function RootError({ error }: { error: Error }) {
  return (
    <main className="flex min-h-screen items-center justify-center bg-cream p-6 text-center">
      <div>
        <p className="text-sm font-semibold text-red">Terjadi kesalahan</p>
        <h1 className="mt-2 text-2xl font-bold text-ink">Halaman gagal dimuat</h1>
        <p className="mt-2 max-w-md text-sm text-body">{error.message || 'Silakan coba lagi.'}</p>
        <button className="mt-5 rounded-lg bg-gray-900 px-4 py-2 text-sm font-semibold text-white" onClick={() => window.location.reload()}>Coba lagi</button>
      </div>
    </main>
  )
}

function RootDocument({ children }: { children: React.ReactNode }) {
  return (
    <html lang="id">
      <head>
        <HeadContent />
      </head>
      <body>
        {children}
        <TanStackDevtools
          config={{
            position: 'bottom-right',
          }}
          plugins={[
            {
              name: 'Tanstack Router',
              render: <TanStackRouterDevtoolsPanel />,
            },
          ]}
        />
        <Scripts />
      </body>
    </html>
  )
}
