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

import appCss from "../styles.css?url";
import { reportLovableError } from "../lib/lovable-error-reporting";
import { site } from "@/lib/site";
import { Logo, LogoMark } from "@/components/brand/Logo";
import { CursorGlow, MonogramLoader } from "@/components/brand/Chrome";
import { MonogramWatermark } from "@/components/brand/decor";
import { Toaster } from "@/components/ui/sonner";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";

const navLinks = [
  { to: "/", label: "Home" },
  { to: "/about", label: "About" },
  { to: "/books", label: "Books" },
  { to: "/speaking", label: "Speaking & Mentorship" },
  { to: "/blog", label: "Blog" },
  { to: "/contact", label: "Contact" },
] as const;

function NotFoundComponent() {
  return (
    <div className="flex min-h-[60vh] items-center justify-center bg-background px-4">
      <div className="max-w-md text-center">
        <LogoMark className="mx-auto mb-8 h-20 w-20 text-4xl" />
        <h1 className="font-display text-6xl text-jungle">404</h1>
        <h2 className="mt-4 font-display text-xl text-foreground">This page hasn't been written yet</h2>
        <p className="mt-2 text-sm text-muted-foreground">
          The page you're looking for doesn't exist — but your next chapter does.
        </p>
        <div className="mt-6">
          <Button asChild variant="green">
            <Link to="/">Back home</Link>
          </Button>
        </div>
      </div>
    </div>
  );
}

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

  return (
    <div className="flex min-h-[60vh] items-center justify-center bg-background px-4">
      <div className="max-w-md text-center">
        <h1 className="font-display text-xl 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
            variant="green"
            onClick={() => {
              router.invalidate();
              reset();
            }}
          >
            Try again
          </Button>
          <Button asChild variant="outline-gold">
            <a href="/">Go home</a>
          </Button>
        </div>
      </div>
    </div>
  );
}

export const Route = createRootRouteWithContext<{ queryClient: QueryClient }>()({
  head: () => ({
    meta: [
      { charSet: "utf-8" },
      { name: "viewport", content: "width=device-width, initial-scale=1" },
      { title: "Eva Shii Jason — People. Purpose. Possibilities." },
      {
        name: "description",
        content:
          "Author, worship minister, gospel recording artist, vocal coach, speaker and mentor Eva Shii Jason — leading, empowering and transforming for a brighter tomorrow. Nairobi, Kenya.",
      },
      { name: "author", content: "Eva Shii Jason" },
      { property: "og:title", content: "Eva Shii Jason — People. Purpose. Possibilities." },
      {
        property: "og:description",
        content: "Books, worship, mentorship and speaking for a brighter tomorrow.",
      },
      { property: "og:type", content: "website" },
      { name: "twitter:card", content: "summary_large_image" },
    ],
    links: [
      { rel: "stylesheet", href: appCss },
      { rel: "icon", type: "image/png", href: "/favicon.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=Playfair+Display:ital,wght@0,400..900;1,400..900&family=Montserrat:wght@300..800&family=Great+Vibes&display=swap",
      },
    ],
  }),
  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 SiteHeader() {
  const [open, setOpen] = useState(false);
  const [scrolled, setScrolled] = useState(false);
  const location = useLocation();

  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 24);
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  useEffect(() => setOpen(false), [location.pathname]);

  return (
    <header
      className={cn(
        "fixed inset-x-0 top-0 z-40 transition-all duration-500",
        scrolled || open
          ? "border-b border-gold/25 bg-ivory/95 shadow-sm backdrop-blur"
          : "bg-transparent",
      )}
    >
      <div className="mx-auto flex max-w-6xl items-center justify-between px-4 py-3 sm:px-6">
        <Link to="/" aria-label="Eva Shii Jason — home" className="shrink-0">
          <Logo compact variant={scrolled || open ? "light" : "dark"} />
        </Link>
        <nav className="hidden items-center gap-7 md:flex" aria-label="Main">
          {navLinks.map((l) => (
            <Link
              key={l.to}
              to={l.to}
              className={cn(
                "link-gold eyebrow text-[0.62rem] transition-colors",
                location.pathname === l.to
                  ? scrolled || open
                    ? "text-jungle"
                    : "text-ivory"
                  : scrolled || open
                    ? "text-foreground/70 hover:text-jungle"
                    : "text-ivory/70 hover:text-ivory",
              )}
              data-active={location.pathname === l.to}
            >
              {l.label}
            </Link>
          ))}
          <Button
            asChild
            variant={scrolled || open ? "green" : "gold"}
            size="sm"
            className="rounded-full"
          >
            <Link to="/contact">Book Eva</Link>
          </Button>
        </nav>
        <button
          type="button"
          className={cn("rounded-md p-2 md:hidden", scrolled || open ? "text-jungle" : "text-ivory")}
          aria-expanded={open}
          aria-label={open ? "Close menu" : "Open menu"}
          onClick={() => setOpen((o) => !o)}
        >
          {open ? <X className="h-5 w-5" /> : <Menu className="h-5 w-5" />}
        </button>
      </div>
      {open ? (
        <nav className="border-t border-gold/20 bg-ivory px-4 pb-5 pt-2 md:hidden" aria-label="Mobile">
          {navLinks.map((l) => (
            <Link
              key={l.to}
              to={l.to}
              className="block border-b border-gold/10 py-3 font-display text-lg text-jungle"
            >
              {l.label}
            </Link>
          ))}
          <Button asChild variant="green" className="mt-4 w-full">
            <Link to="/contact">Book Eva</Link>
          </Button>
        </nav>
      ) : null}
    </header>
  );
}

function SiteFooter() {
  return (
    <footer className="relative overflow-hidden bg-jungle text-ivory">
      <div aria-hidden="true" className="leaf-glow absolute inset-0" />
      <MonogramWatermark className="absolute -bottom-16 right-4 text-[14rem] sm:-bottom-24 sm:right-10" />
      <div className="relative mx-auto max-w-6xl px-4 py-16 sm:px-6">
        <div className="grid gap-10 md:grid-cols-3">
          <div>
            <Logo variant="dark" withTagline />
            <p className="mt-5 max-w-xs text-sm leading-relaxed text-ivory/70">
              Real insights. Practical tools. Lasting impact — for a brighter tomorrow.
            </p>
          </div>
          <div>
            <p className="eyebrow text-[0.6rem] text-gold-light">Explore</p>
            <ul className="mt-4 grid gap-2.5">
              {navLinks.map((l) => (
                <li key={l.to}>
                  <Link to={l.to} className="text-sm text-ivory/80 transition-colors hover:text-gold-light">
                    {l.label}
                  </Link>
                </li>
              ))}
            </ul>
          </div>
          <div>
            <p className="eyebrow text-[0.6rem] text-gold-light">Connect</p>
            <ul className="mt-4 grid gap-2.5">
              {site.emails.map((e) => (
                <li key={e}>
                  <a href={`mailto:${e}`} className="text-sm text-ivory/80 hover:text-gold-light">
                    {e}
                  </a>
                </li>
              ))}
              {site.socials.map((s) => (
                <li key={s.label}>
                  <a href={s.href} target="_blank" rel="noreferrer" className="text-sm text-ivory/80 hover:text-gold-light">
                    {s.label}
                  </a>
                </li>
              ))}
              <li className="text-sm text-ivory/60">{site.location}</li>
            </ul>
          </div>
        </div>
        <div className="mt-12 flex flex-col items-center gap-3 border-t border-ivory/10 pt-6 text-center">
          <p className="font-script text-2xl text-gold-light">A greater tomorrow.</p>
          <p className="text-xs text-ivory/50">
            © {new Date().getFullYear()} {site.legalName}. All rights reserved. ·{" "}
            <Link to="/admin" className="text-ivory/40 hover:text-gold-light">
              Admin
            </Link>
          </p>
        </div>
      </div>
    </footer>
  );
}

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

  return (
    <QueryClientProvider client={queryClient}>
      <MonogramLoader />
      <CursorGlow />
      <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>
      <Toaster position="bottom-center" />
    </QueryClientProvider>
  );
}
