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 { SiteHeader } from "@/components/site-header";
import { SiteFooter } from "@/components/site-footer";

function NotFoundComponent() {
  return (
    <div className="flex min-h-screen items-center justify-center bg-background px-4">
      <div className="max-w-md text-center">
        <p className="font-display text-sm uppercase tracking-[0.3em] text-gold">404</p>
        <h1 className="mt-4 text-4xl font-semibold text-foreground">Page not found</h1>
        <p className="mt-3 text-sm text-muted-foreground">
          The page you're looking for has moved or no longer exists.
        </p>
        <Link
          to="/"
          className="mt-8 inline-flex items-center justify-center rounded-full bg-foreground px-6 py-3 text-sm font-medium text-background transition hover:opacity-90"
        >
          Back to home
        </Link>
      </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">
          Something went wrong
        </h1>
        <p className="mt-2 text-sm text-muted-foreground">
          Please refresh or head back home.
        </p>
        <div className="mt-6 flex justify-center gap-2">
          <button
            onClick={() => { router.invalidate(); reset(); }}
            className="rounded-full bg-foreground px-5 py-2.5 text-sm font-medium text-background"
          >
            Try again
          </button>
          <a href="/" className="rounded-full border border-border px-5 py-2.5 text-sm font-medium">
            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: "Zamelect Properties — Luxury Dubai Real Estate for Sale & Investment" },
      {
        name: "description",
        content:
          "Buy, sell and invest in Dubai real estate with Zamelect Properties. Luxury apartments, villas, penthouses and off-plan projects in Marina, Downtown, Palm Jumeirah, Business Bay & more.",
      },
      { property: "og:site_name", content: "Zamelect Properties" },
      { property: "og:type", content: "website" },
      { property: "og:title", content: "Zamelect Properties — Luxury Dubai Real Estate for Sale & Investment" },
      {
        property: "og:description",
        content:
          "Buy, sell and invest in Dubai real estate with Zamelect Properties. Luxury apartments, villas, penthouses and off-plan projects in Marina, Downtown, Palm Jumeirah, Business Bay & more.",
      },
      { name: "twitter:card", content: "summary_large_image" },
      { name: "theme-color", content: "#181410" },
      { name: "twitter:title", content: "Zamelect Properties — Luxury Dubai Real Estate for Sale & Investment" },
      { name: "twitter:description", content: "Buy, sell and invest in Dubai real estate with Zamelect Properties. Luxury apartments, villas, penthouses and off-plan projects in Marina, Downtown, Palm Jumeirah, Business Bay & more." },
      { property: "og:image", content: "https://pub-bb2e103a32db4e198524a2e9ed8f35b4.r2.dev/cb685456-2c38-47f4-9f10-73309c194806/id-preview-c4cd095f--fbec5c26-c0cb-4d07-8dfe-739040574599.lovable.app-1784053026901.png" },
      { name: "twitter:image", content: "https://pub-bb2e103a32db4e198524a2e9ed8f35b4.r2.dev/cb685456-2c38-47f4-9f10-73309c194806/id-preview-c4cd095f--fbec5c26-c0cb-4d07-8dfe-739040574599.lovable.app-1784053026901.png" },
    ],
    links: [
      { rel: "stylesheet", href: appCss },
      { rel: "icon", href: "/favicon.ico", type: "image/x-icon" },
      { 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=Urbanist:wght@400;500;600;700;800&family=Epilogue:wght@400;500;600&display=swap",
      },
    ],
    scripts: [
      {
        type: "application/ld+json",
        children: JSON.stringify({
          "@context": "https://schema.org",
          "@type": "RealEstateAgent",
          name: "Zamelect Properties",
          description:
            "Dubai luxury real estate brokerage specialising in off-plan investments, ready properties and portfolio advisory.",
          areaServed: "Dubai, United Arab Emirates",
          telephone: "+971 4 000 0000",
          email: "hello@zamelectproperties.com",
          address: {
            "@type": "PostalAddress",
            addressLocality: "Dubai",
            addressCountry: "AE",
          },
        }),
      },
    ],
  }),
  shellComponent: RootShell,
  component: RootComponent,
  notFoundComponent: NotFoundComponent,
  errorComponent: ErrorComponent,
});

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

function RootComponent() {
  const { queryClient } = Route.useRouteContext();
  return (
    <QueryClientProvider client={queryClient}>
      <div className="flex min-h-screen flex-col bg-background text-foreground">
        <SiteHeader />
        <main className="flex-1">
          <Outlet />
        </main>
        <SiteFooter />
      </div>
    </QueryClientProvider>
  );
}
