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 { ThemeProvider } from "../lib/theme";
import { Header } from "../components/site/Header";
import { Footer } from "../components/site/Footer";
import { BackgroundFX } from "../components/site/BackgroundFX";
import { Cursor } from "../components/site/Cursor";
import { PageTransition, RouteProgressBar } from "../components/site/PageTransition";
import { SeoCanonical } from "../components/site/SeoCanonical";
import { BackToTop } from "../components/site/BackToTop";

function NotFoundComponent() {
  return (
    <div className="flex min-h-screen items-center justify-center px-4">
      <div className="max-w-md text-center">
        <h1 className="text-8xl font-black text-gradient">404</h1>
        <h2 className="mt-4 text-xl font-semibold">Signal lost.</h2>
        <p className="mt-2 text-sm text-muted-foreground">
          The page you're looking for drifted off the grid.
        </p>
        <div className="mt-6">
          <Link
            to="/"
            className="inline-flex items-center justify-center rounded-full bg-primary px-5 py-2.5 text-sm font-medium text-primary-foreground glow-ring hover:brightness-110"
          >
            Back 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 px-4">
      <div className="max-w-md text-center glass-strong rounded-3xl p-8">
        <h1 className="text-xl font-semibold">This page didn't load</h1>
        <p className="mt-2 text-sm text-muted-foreground">
          Something glitched. Try again or head back home.
        </p>
        <div className="mt-6 flex flex-wrap justify-center gap-2">
          <button
            onClick={() => { router.invalidate(); reset(); }}
            className="rounded-full bg-primary px-4 py-2 text-sm text-primary-foreground glow-ring"
          >
            Try again
          </button>
          <a href="/" className="rounded-full border border-border px-4 py-2 text-sm hover:bg-accent">
            Go home
          </a>
        </div>
      </div>
    </div>
  );
}

const themeInit = `
try {
  var t = localStorage.getItem('cist-theme') || 'dark';
  if (t === 'dark') document.documentElement.classList.add('dark');
  else document.documentElement.classList.remove('dark');
} catch (e) { document.documentElement.classList.add('dark'); }
`;

export const Route = createRootRouteWithContext<{ queryClient: QueryClient }>()({
  head: () => ({
    meta: [
      { charSet: "utf-8" },
      { name: "viewport", content: "width=device-width, initial-scale=1" },
      { title: "Create it Simple Technologies Pvt Ltd — Simple and Effective Digital Growth" },
      { name: "description", content: "Website development, brand identity, SEO optimization and website maintenance from Raipur, India. Fast, secure and custom websites that drive business growth." },
      { name: "author", content: "Create it Simple Technologies Pvt Ltd" },
      { property: "og:title", content: "Create it Simple Technologies Pvt Ltd — Simple and Effective Digital Growth" },
      { property: "og:description", content: "Create it Simple Technologies Pvt Ltd builds fast, secure and custom websites, mobile apps and software for businesses in India and worldwide." },
      { property: "og:type", content: "website" },
      { property: "og:site_name", content: "Create it Simple Technologies Pvt Ltd" },
      { name: "twitter:card", content: "summary_large_image" },
    ],
    links: [
      { rel: "canonical", href: "https://createitsimple.com/" },
      { rel: "stylesheet", href: appCss },
      { rel: "icon", href: "/favicon.webp", type: "image/webp" },
      { rel: "icon", href: "/favicon.png", type: "image/png" },
      { 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@400;500;600;700&family=Plus+Jakarta+Sans:wght@400;500;600;700;800&family=Outfit:wght@400;500;600;700;800;900&display=swap",
      },
    ],
    scripts: [
      { children: themeInit },
      {
        type: "application/ld+json",
        children: JSON.stringify({
          "@context": "https://schema.org",
          "@type": "Organization",
          name: "Create it Simple Technologies Pvt Ltd",
          url: "https://createitsimple.com/",
          logo: "https://createitsimple.com/favicon.png",
          description:
            "Website development, brand identity, SEO optimization and website maintenance from Raipur, India.",
          email: "hello@createitsimple.com",
          telephone: "+91-9644-511-551",
          address: {
            "@type": "PostalAddress",
            streetAddress: "LIG-58, Galaxy Green, Vidhan Sabha Chowk",
            addressLocality: "Raipur",
            addressRegion: "Chhattisgarh",
            addressCountry: "IN",
          },
          sameAs: [
            "https://www.instagram.com/wecreateitsimple",
            "https://www.linkedin.com/company/create-it-simple",
          ],
        }),
      },
    ],
  }),
  shellComponent: RootShell,
  component: RootComponent,
  notFoundComponent: NotFoundComponent,
  errorComponent: ErrorComponent,
});

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

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

  return (
    <QueryClientProvider client={queryClient}>
      <ThemeProvider>
        <SeoCanonical />
        <BackgroundFX />
        <Cursor />
        <RouteProgressBar />
        <Header />
        <main className="relative">
          <PageTransition />
        </main>
        <Footer />
        <BackToTop />
      </ThemeProvider>
    </QueryClientProvider>
  );
}
