import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import {
  Outlet,
  createRootRouteWithContext,
  useRouter,
  HeadContent,
  Scripts,
  Link,
} 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";
import { Toaster } from "@/components/ui/sonner";
import { GatavaseChat } from "@/components/gatavase-chat";

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: "Gatavase Corporation — Intelligent Systems for a Connected Africa" },
      { name: "author", content: "Gatavase Corporation" },
      { property: "og:type", content: "website" },
      { property: "og:site_name", content: "Gatavase Corporation" },
      { name: "twitter:card", content: "summary_large_image" },
      { property: "og:title", content: "Gatavase Corporation — Intelligent Systems for a Connected Africa" },
      { name: "twitter:title", content: "Gatavase Corporation — Intelligent Systems for a Connected Africa" },
      { name: "description", content: "Gatavase Corporation builds AI platforms, mobile apps, enterprise software and digital experiences for businesses across Africa and beyond. Kampala · Doha." },
      { property: "og:description", content: "Gatavase Corporation builds AI platforms, mobile apps, enterprise software and digital experiences for businesses across Africa and beyond. Kampala · Doha." },
      { name: "twitter:description", content: "Gatavase Corporation builds AI platforms, mobile apps, enterprise software and digital experiences for businesses across Africa and beyond. Kampala · Doha." },
      { property: "og:image", content: "https://storage.googleapis.com/gpt-engineer-file-uploads/attachments/og-images/07bb4b7e-ae68-49d2-a13f-4b13a127d323" },
      { name: "twitter:image", content: "https://storage.googleapis.com/gpt-engineer-file-uploads/attachments/og-images/07bb4b7e-ae68-49d2-a13f-4b13a127d323" },
    ],
    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=Space+Grotesk:wght@500;600;700&family=DM+Sans:wght@400;500;600&display=swap",
      },
      { rel: "icon", href: "/favicon.png", type: "image/png" },
      { rel: "apple-touch-icon", href: "/favicon.png" },
    ],
    scripts: [
      {
        type: "application/ld+json",
        children: JSON.stringify({
          "@context": "https://schema.org",
          "@type": "Organization",
          name: "Gatavase Corporation",
          alternateName: "Gatavase",
          url: "/",
          logo: "/favicon.png",
          email: "gazmanadvancedtechnologies@gmail.com",
          telephone: ["+256773231138", "+97433201668"],
          foundingLocation: "Kampala, Uganda",
          areaServed: ["UG", "QA", "Africa", "Middle East"],
          address: [
            {
              "@type": "PostalAddress",
              streetAddress: "Muyenga-Bukasa, Plot 68",
              addressLocality: "Kampala",
              addressCountry: "UG",
            },
            {
              "@type": "PostalAddress",
              streetAddress: "Abu Nakhla, Al Rayyan",
              addressLocality: "Doha",
              addressCountry: "QA",
            },
          ],
          contactPoint: [
            {
              "@type": "ContactPoint",
              contactType: "sales",
              email: "gazmanadvancedtechnologies@gmail.com",
              telephone: "+256773231138",
              areaServed: ["UG", "QA"],
              availableLanguage: ["en"],
            },
          ],
        }),
      },
      {
        type: "application/ld+json",
        children: JSON.stringify({
          "@context": "https://schema.org",
          "@type": "WebSite",
          name: "Gatavase Corporation",
          url: "/",
          inLanguage: "en",
          publisher: { "@type": "Organization", name: "Gatavase Corporation" },
          potentialAction: {
            "@type": "SearchAction",
            target: "/blog?q={search_term_string}",
            "query-input": "required name=search_term_string",
          },
        }),
      },
    ],
  }),

  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">
        <SiteHeader />
        <main className="flex-1">
          {/* Required: nested routes render here. Removing <Outlet /> breaks all child routes. */}
          <Outlet />
        </main>
        <SiteFooter />
      </div>
      <GatavaseChat />
      <Toaster />
    </QueryClientProvider>
  );
}
