import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import {
  Outlet,
  Link,
  createRootRouteWithContext,
  useRouter,
  useRouterState,
  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 { AppShell } from "@/components/app/AppShell";
import { RequireAuth } from "@/components/app/RequireAuth";
import { Toaster } from "@/components/ui/sonner";

function NotFoundComponent() {
  return (
    <div className="flex min-h-dvh 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>
  );
}

const STALE_MODULE_RELOAD_KEY = "kv:stale-module-reload";

/** A dynamic import that fails to fetch means this tab is holding module URLs from a build that no
 * longer exists — after a deploy, or after the dev server restarted. The code is fine; the URLs
 * are stale, and a reload picks up the current ones. */
const isStaleModuleError = (error: Error) =>
  /failed to fetch dynamically imported module|error loading dynamically imported module|importing a module script failed/i.test(
    error.message,
  );

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

  // Recover from a stale chunk without making the operator work out that "refresh" is the answer.
  // Reloads at most once per session-storage flag, so a module that is genuinely broken shows the
  // error instead of trapping the tab in a reload loop.
  useEffect(() => {
    if (!isStaleModuleError(error)) return;
    try {
      if (sessionStorage.getItem(STALE_MODULE_RELOAD_KEY)) return;
      sessionStorage.setItem(STALE_MODULE_RELOAD_KEY, "1");
    } catch {
      return; // storage blocked — leave the manual "Try again" button as the way out
    }
    window.location.reload();
  }, [error]);

  const stale = isStaleModuleError(error);

  return (
    <div className="flex min-h-dvh 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">
          {stale
            ? "This tab was running an older version of the app. Reloading picks up the current one."
            : "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={() => {
              // Re-running the loaders cannot fetch a module that is no longer being served, so a
              // stale chunk needs a real page load rather than a router retry.
              if (stale) {
                window.location.reload();
                return;
              }
              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"
          >
            {stale ? "Reload page" : "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: "KareVoyage Operations" },
      {
        name: "description",
        content:
          "Every journey. Every traveller. Every detail. The operations command centre behind KareVoyage.",
      },
      { name: "robots", content: "noindex, nofollow" },
      { property: "og:type", content: "website" },
      { name: "twitter:card", content: "summary_large_image" },
    ],
    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=Fraunces:opsz,wght@9..144,400;9..144,500;9..144,600&family=Plus+Jakarta+Sans:wght@400;500;600;700&display=swap",
      },
      /** SVG first so the tab icon stays crisp at any zoom; the .ico is the legacy fallback and
       * is also what a browser finds when it probes /favicon.ico on its own. */
      { rel: "icon", href: "/favicon.svg", type: "image/svg+xml" },
      { rel: "icon", href: "/favicon.ico", sizes: "64x64" },
      { rel: "apple-touch-icon", href: "/favicon.svg" },
    ],
  }),
  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();
  const pathname = useRouterState({ select: (s) => s.location.pathname });
  const isLoginRoute = pathname === "/login";

  // Rendering at all means the modules loaded, so re-arm the one-shot stale-chunk reload.
  useEffect(() => {
    try {
      sessionStorage.removeItem(STALE_MODULE_RELOAD_KEY);
    } catch {
      /* storage blocked — nothing to clear */
    }
  }, []);

  return (
    <QueryClientProvider client={queryClient}>
      {isLoginRoute ? (
        <Outlet />
      ) : (
        <RequireAuth>
          <AppShell>
            {/* Required: nested routes render here. Removing <Outlet /> breaks all child routes. */}
            <Outlet />
          </AppShell>
        </RequireAuth>
      )}
      <Toaster position="bottom-right" />
    </QueryClientProvider>
  );
}
