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

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

const NAV = [
  { to: "/", label: "Home" },
  { to: "/about", label: "About" },
  { to: "/applications", label: "Applications" },
  { to: "/products", label: "Products" },
  { to: "/solutions", label: "Solutions" },
  { to: "/projects", label: "Projects" },
  { to: "/enquiry", label: "Enquiry" },
  { to: "/contact", label: "Contact" },
  { to: "/rental", label: "Rental" },
] as const;

function TopBar() {
  return (
    <div className="w-full bg-brand-red text-white text-sm">
      <div className="container-page flex flex-wrap items-center justify-end gap-6 py-2">
        <a href="tel:+97142515596" className="inline-flex items-center gap-2 hover:opacity-80">
          <Phone className="h-3.5 w-3.5" /> +971 4 251 5596
        </a>
        <a href="tel:+971552098628" className="inline-flex items-center gap-2 hover:opacity-80">
          <Phone className="h-3.5 w-3.5" /> +971 55 209 8628
        </a>
      </div>
    </div>
  );
}

function Header() {
  const [open, setOpen] = useState(false);
  return (
    <header className="sticky top-0 z-50 bg-background/95 backdrop-blur border-b">
      <div className="container-page flex items-center justify-between h-20">
        <Link to="/" className="flex items-baseline gap-1 font-display">
          <span className="text-3xl font-black tracking-tight">
            <span className="text-brand-blue">Pro</span>
            <span className="text-brand-red">mist</span>
          </span>
          <span className="text-xs uppercase tracking-[0.2em] text-muted-foreground hidden sm:inline">
            Misting Systems
          </span>
        </Link>
        <nav className="hidden lg:flex items-center gap-7 text-sm font-medium">
          {NAV.map((n) => (
            <Link
              key={n.to}
              to={n.to}
              className="text-foreground/80 hover:text-brand-red transition-colors"
              activeProps={{ className: "text-brand-red" }}
              activeOptions={{ exact: n.to === "/" }}
            >
              {n.label}
            </Link>
          ))}
        </nav>
        <button
          onClick={() => setOpen((v) => !v)}
          className="lg:hidden inline-flex items-center justify-center h-10 w-10 rounded-md border"
          aria-label="Toggle menu"
        >
          {open ? <X className="h-5 w-5" /> : <Menu className="h-5 w-5" />}
        </button>
      </div>
      {open && (
        <div className="lg:hidden border-t">
          <div className="container-page py-4 flex flex-col gap-3">
            {NAV.map((n) => (
              <Link
                key={n.to}
                to={n.to}
                onClick={() => setOpen(false)}
                className="text-foreground/80 hover:text-brand-red"
                activeProps={{ className: "text-brand-red" }}
                activeOptions={{ exact: n.to === "/" }}
              >
                {n.label}
              </Link>
            ))}
          </div>
        </div>
      )}
    </header>
  );
}

function Footer() {
  return (
    <footer className="mt-24 border-t bg-muted/40">
      <div className="container-page py-14 grid gap-10 md:grid-cols-4">
        <div>
          <div className="font-display text-2xl font-black">
            <span className="text-brand-blue">Pro</span>
            <span className="text-brand-red">mist</span>
          </div>
          <p className="mt-3 text-sm text-muted-foreground max-w-xs">
            High-pressure misting systems for cooling, humidification and dust suppression since 1979.
          </p>
        </div>
        <div>
          <h4 className="text-xs uppercase tracking-widest text-brand-red font-semibold">Explore</h4>
          <ul className="mt-4 space-y-2 text-sm">
            {NAV.slice(1, 6).map((n) => (
              <li key={n.to}>
                <Link to={n.to} className="hover:text-brand-red">{n.label}</Link>
              </li>
            ))}
          </ul>
        </div>
        <div>
          <h4 className="text-xs uppercase tracking-widest text-brand-red font-semibold">Company</h4>
          <ul className="mt-4 space-y-2 text-sm">
            <li><Link to="/enquiry" className="hover:text-brand-red">Enquiry</Link></li>
            <li><Link to="/contact" className="hover:text-brand-red">Contact</Link></li>
            <li><Link to="/rental" className="hover:text-brand-red">Rental</Link></li>
          </ul>
        </div>
        <div>
          <h4 className="text-xs uppercase tracking-widest text-brand-red font-semibold">Contact</h4>
          <ul className="mt-4 space-y-2 text-sm text-muted-foreground">
            <li>+971 4 251 5596</li>
            <li>+971 55 209 8628</li>
            <li>Dubai, United Arab Emirates</li>
          </ul>
        </div>
      </div>
      <div className="border-t">
        <div className="container-page py-5 text-xs text-muted-foreground flex flex-wrap justify-between gap-2">
          <span>© {new Date().getFullYear()} Promist Misting Systems. All rights reserved.</span>
          <span>Humidity and Control</span>
        </div>
      </div>
    </footer>
  );
}

function NotFoundComponent() {
  return (
    <div className="flex min-h-[70vh] items-center justify-center px-4">
      <div className="max-w-md text-center">
        <h1 className="text-7xl font-black text-brand-red">404</h1>
        <h2 className="mt-4 text-xl font-semibold">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>
        <Link to="/" className="mt-6 inline-flex rounded-md bg-brand-red text-white px-5 py-2.5 text-sm font-medium hover:opacity-90">
          Go 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-[70vh] items-center justify-center px-4">
      <div className="max-w-md text-center">
        <h1 className="text-xl font-semibold">This page didn't load</h1>
        <p className="mt-2 text-sm text-muted-foreground">Something went wrong. Try again or head home.</p>
        <div className="mt-6 flex justify-center gap-2">
          <button
            onClick={() => { router.invalidate(); reset(); }}
            className="rounded-md bg-brand-red text-white px-4 py-2 text-sm font-medium"
          >Try again</button>
          <a href="/" className="rounded-md border px-4 py-2 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: "Promist Misting Systems — Humidity and Control" },
      { name: "description", content: "High-pressure misting systems for outdoor cooling, humidification, dust suppression and sanitization in the UAE since 1979." },
      { property: "og:title", content: "Promist Misting Systems" },
      { property: "og:description", content: "High-pressure misting for cooling, humidification and dust suppression." },
      { property: "og:type", content: "website" },
      { name: "twitter:card", content: "summary_large_image" },
    ],
    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=Hanken+Grotesk:wght@300;400;500;600;700;800;900&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 RootComponent() {
  const { queryClient } = Route.useRouteContext();
  return (
    <QueryClientProvider client={queryClient}>
      <TopBar />
      <Header />
      <main>
        <Outlet />
      </main>
      <Footer />
    </QueryClientProvider>
  );
}
