import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import {
  Outlet,
  Link,
  createRootRouteWithContext,
  useRouter,
  HeadContent,
  Scripts,
} from "@tanstack/react-router";
import { useEffect, type ReactNode } from "react";

import appCss from "../styles.css?url";
import { reportLovableError } from "../lib/lovable-error-reporting";
import { I18nProvider } from "../lib/i18n";

function NotFoundComponent() {
  return (
    <div className="flex min-h-screen items-center justify-center bg-background px-4">
      <div className="max-w-md text-center">
        <h1 className="text-7xl font-bold text-foreground">404</h1>
        <h2 className="mt-4 text-xl font-semibold text-foreground">Page not found</h2>
        <p className="mt-2 text-sm text-muted-foreground">
          The page you're looking for doesn't exist or has been moved.
        </p>
        <div className="mt-6">
          <Link
            to="/"
            className="inline-flex items-center justify-center rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground transition-colors hover:bg-primary/90"
          >
            Go home
          </Link>
        </div>
      </div>
    </div>
  );
}

function ErrorComponent({ error, reset }: { error: Error; reset: () => void }) {
  console.error(error);
  const router = useRouter();
  useEffect(() => {
    reportLovableError(error, { boundary: "tanstack_root_error_component" });
  }, [error]);

  return (
    <div className="flex min-h-screen items-center justify-center bg-background px-4">
      <div className="max-w-md text-center">
        <h1 className="text-xl font-semibold tracking-tight text-foreground">
          This page didn't load
        </h1>
        <p className="mt-2 text-sm text-muted-foreground">
          Something went wrong on our end. You can try refreshing or head back home.
        </p>
        <div className="mt-6 flex flex-wrap justify-center gap-2">
          <button
            onClick={() => {
              router.invalidate();
              reset();
            }}
            className="inline-flex items-center justify-center rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground transition-colors hover:bg-primary/90"
          >
            Try again
          </button>
          <a
            href="/"
            className="inline-flex items-center justify-center rounded-md border border-input bg-background px-4 py-2 text-sm font-medium text-foreground transition-colors hover:bg-accent"
          >
            Go home
          </a>
        </div>
      </div>
    </div>
  );
}

export const Route = createRootRouteWithContext<{ queryClient: QueryClient }>()({
  head: () => ({
    meta: [
      { charSet: "utf-8" },
      { name: "viewport", content: "width=device-width, initial-scale=1" },
      { title: "کارخانه سیگل | نبات زعفرانی، زعفران ایرانی و شیرینی سنتی — Seagol Factory" },
      { name: "description", content: "کارخانه سیگل، تولیدکننده تخصصی نبات زعفرانی، زعفران ایرانی و شیرینی سنتی با کیفیت صادراتی به بیش از ۲۸ کشور. Premium Iranian saffron rock candy (Nabat), saffron and traditional confectionery for global export, private label & OEM partners." },
      { name: "keywords", content: "نبات, نبات زعفرانی, زعفران, زعفران ایرانی, شیرینی, شیرینی سنتی, آبنبات, نبات چوبی, صادرات نبات, کارخانه سیگل, Seagol, saffron, Persian rock candy, Iranian saffron, nabat" },
      { name: "author", content: "Seagol Factory — کارخانه سیگل" },
      { property: "og:title", content: "کارخانه سیگل | نبات زعفرانی و زعفران ایرانی — Seagol Factory" },
      { property: "og:description", content: "تولیدکننده نبات زعفرانی، زعفران ایرانی و شیرینی سنتی برای بازارهای جهانی. Premium Persian saffron nabat & confectionery for global export." },
      { property: "og:type", content: "website" },
      { property: "og:site_name", content: "Seagol Factory — کارخانه سیگل" },
      { property: "og:locale", content: "fa_IR" },
      { name: "twitter:card", content: "summary_large_image" },
      { name: "twitter:title", content: "کارخانه سیگل — نبات زعفرانی و زعفران ایرانی" },
      { name: "twitter:description", content: "تولیدکننده نبات زعفرانی، زعفران ایرانی و شیرینی سنتی صادراتی." },
      { property: "og:image", content: "https://pub-bb2e103a32db4e198524a2e9ed8f35b4.r2.dev/b91ded03-11bf-42a5-88b5-932c9d9ed3b9/id-preview-c1a2915f--aa031a1e-bb43-48d2-aac0-fbf64418c44e.lovable.app-1781265946222.png" },
      { name: "twitter:image", content: "https://pub-bb2e103a32db4e198524a2e9ed8f35b4.r2.dev/b91ded03-11bf-42a5-88b5-932c9d9ed3b9/id-preview-c1a2915f--aa031a1e-bb43-48d2-aac0-fbf64418c44e.lovable.app-1781265946222.png" },
    ],
    links: [
      { rel: "stylesheet", href: appCss },
      { rel: "preconnect", href: "https://fonts.googleapis.com" },
      { rel: "preconnect", href: "https://fonts.gstatic.com", crossOrigin: "anonymous" },
      {
        rel: "stylesheet",
        href: "https://fonts.googleapis.com/css2?family=Playfair+Display:wght@500;600;700;800&family=Inter:wght@400;500;600;700&family=Vazirmatn:wght@400;500;600;700;800&display=swap",
      },
    ],
  }),
  shellComponent: RootShell,
  component: RootComponent,
  notFoundComponent: NotFoundComponent,
  errorComponent: ErrorComponent,
});

function RootShell({ children }: { children: ReactNode }) {
  return (
    <html lang="fa" dir="rtl">
      <head>
        <HeadContent />
      </head>
      <body>
        {children}
        <Scripts />
      </body>
    </html>
  );
}

function RootComponent() {
  const { queryClient } = Route.useRouteContext();

  return (
    <QueryClientProvider client={queryClient}>
      <I18nProvider>
        <Outlet />
      </I18nProvider>
    </QueryClientProvider>
  );
}

