import type { Metadata, Viewport } from "next";
import Link from "next/link";
import Script from "next/script";
import { headers } from "next/headers";
import { redirect } from "next/navigation";
import { Geist, Geist_Mono } from "next/font/google";
import { getCurrentUser } from "@/lib/auth";
import { logoutAction } from "@/app/login/actions";
import { MobileNav } from "@/components/MobileNav";
import { NavLink } from "@/components/NavLink";
import { isSetupComplete } from "@/lib/setup";
import "./globals.css";

// Resolves theme="SYSTEM" (or a logged-out visitor, who has no stored
// preference at all) to a concrete data-theme before paint, from
// prefers-color-scheme - only acts if the server hasn't already resolved
// LIGHT/DARK onto <html> below. Must stay inlined here (not imported from a
// separate component) - Next's beforeInteractive strategy is only
// recognized when it's declared directly in the root layout.
const THEME_INIT_SCRIPT = `
(function () {
  try {
    var root = document.documentElement;
    if (root.getAttribute("data-theme")) return;
    var dark = window.matchMedia("(prefers-color-scheme: dark)").matches;
    root.setAttribute("data-theme", dark ? "dark" : "light");
  } catch (e) {}
})();
`;

type NavItem = { href: string; label: string; icon: string };

function initials(name: string): string {
  const parts = name.trim().split(/\s+/);
  return ((parts[0]?.[0] ?? "") + (parts[1]?.[0] ?? "")).toUpperCase() || "?";
}

const geistSans = Geist({
  variable: "--font-geist-sans",
  subsets: ["latin"],
});

const geistMono = Geist_Mono({
  variable: "--font-geist-mono",
  subsets: ["latin"],
});

export const metadata: Metadata = {
  title: "Horse Records",
  description: "Horse profiles, genetics, and pedigree records",
  manifest: "/manifest.json",
  appleWebApp: {
    capable: true,
    statusBarStyle: "default",
    title: "Horse Records",
  },
};

export const viewport: Viewport = {
  width: "device-width",
  initialScale: 1,
  themeColor: "#171717",
};

export default async function RootLayout({ children }: LayoutProps<"/">) {
  // First-run gate: every route redirects to the setup wizard until it's
  // complete, except /setup itself (which would otherwise redirect-loop -
  // the pathname comes from proxy.ts, since a shared layout has no other way
  // to know the current URL). The wizard page re-checks this same condition
  // itself too, so this holds even if that header were ever missing.
  const pathname = (await headers()).get("x-pathname") ?? "";
  const setupComplete = await isSetupComplete();
  if (!pathname.startsWith("/setup") && !setupComplete) {
    redirect("/setup");
  }

  // Before setup completes there are no tables yet at all (migrations
  // haven't run), so getCurrentUser()'s session lookup would itself throw -
  // skip it rather than querying a database that doesn't exist yet.
  const user = setupComplete ? await getCurrentUser() : null;
  const isAdmin = user?.role === "ADMIN";

  // LIGHT/DARK resolve to a concrete attribute server-side (no flash, even on
  // first paint); SYSTEM is left unset here and resolved client-side by
  // ThemeScript from prefers-color-scheme, since the server can't know that.
  const themeAttr = user?.theme === "LIGHT" ? "light" : user?.theme === "DARK" ? "dark" : undefined;

  const primaryItems: NavItem[] = [
    { href: "/horses", label: "Horses", icon: "🐴" },
    ...(user
      ? ([
          { href: "/dashboard", label: "Dashboard", icon: "📊" },
          { href: "/buyers", label: "Buyers", icon: "🤝" },
          { href: "/calendar", label: "Calendar", icon: "📅" },
          { href: "/foals", label: "Foal Flow", icon: "🐣" },
          { href: "/daybook", label: "Day Book", icon: "📓" },
          { href: "/transfers", label: "Transfers", icon: "🔄" },
        ] satisfies NavItem[])
      : []),
  ];
  const adminItems: NavItem[] = isAdmin
    ? [
        { href: "/backup", label: "Backup", icon: "💾" },
        { href: "/admin/users", label: "Users", icon: "👥" },
      ]
    : [];

  const desktopLinkCls = "rounded-md px-2.5 py-1.5 text-neutral-600 dark:text-neutral-400 transition-colors hover:bg-neutral-100 hover:dark:bg-neutral-900 hover:text-neutral-900 hover:dark:text-neutral-200";
  const desktopActiveCls = "bg-neutral-100 dark:bg-neutral-900 font-semibold text-neutral-900 dark:text-neutral-200";
  const mobileLinkCls = "flex items-center gap-3 rounded-md px-3 py-3 text-neutral-900 dark:text-neutral-200 hover:bg-neutral-50 hover:dark:bg-neutral-950";
  const mobileActiveCls = "bg-neutral-100 dark:bg-neutral-900 font-semibold";

  return (
    <html
      lang="en"
      data-theme={themeAttr}
      className={`${geistSans.variable} ${geistMono.variable} h-full antialiased`}
      suppressHydrationWarning
    >
      <head>
        <Script id="theme-init" strategy="beforeInteractive">
          {THEME_INIT_SCRIPT}
        </Script>
      </head>
      <body
        className="min-h-full flex flex-col bg-neutral-50 dark:bg-neutral-950 text-neutral-900 dark:text-neutral-200"
        suppressHydrationWarning
      >
        <header className="sticky top-0 z-30 border-b border-neutral-200 dark:border-neutral-700 bg-white dark:bg-neutral-900">
          <div className="mx-auto flex max-w-6xl items-center justify-between px-4 py-4 sm:px-6">
            <Link href="/horses" className="text-lg font-semibold tracking-tight">
              🐴 Horse Records
            </Link>

            <nav className="hidden items-center gap-1 text-sm md:flex">
              {primaryItems.map((item) => (
                <NavLink key={item.href} href={item.href} className={desktopLinkCls} activeClassName={desktopActiveCls}>
                  {item.label}
                </NavLink>
              ))}
              {adminItems.length > 0 && (
                <div className="ml-1 flex items-center gap-1 border-l border-neutral-200 dark:border-neutral-700 pl-2">
                  {adminItems.map((item) => (
                    <NavLink key={item.href} href={item.href} className={desktopLinkCls} activeClassName={desktopActiveCls}>
                      {item.label}
                    </NavLink>
                  ))}
                </div>
              )}
              {user ? (
                <div className="ml-2 flex items-center gap-3 border-l border-neutral-200 dark:border-neutral-700 pl-3">
                  <Link href="/account" className="text-neutral-600 dark:text-neutral-400 transition-colors hover:text-neutral-900 hover:dark:text-neutral-200">
                    {user.name}
                  </Link>
                  <form action={logoutAction}>
                    <button type="submit" className="text-neutral-600 dark:text-neutral-400 transition-colors hover:text-neutral-900 hover:dark:text-neutral-200">
                      Log out
                    </button>
                  </form>
                </div>
              ) : (
                <Link href="/login" className={`ml-2 ${desktopLinkCls}`}>Log in</Link>
              )}
            </nav>

            <MobileNav>
              <div className="flex flex-col gap-0.5">
                {primaryItems.map((item) => (
                  <NavLink key={item.href} href={item.href} className={mobileLinkCls} activeClassName={mobileActiveCls}>
                    <span className="text-base">{item.icon}</span>
                    {item.label}
                  </NavLink>
                ))}
              </div>

              {adminItems.length > 0 && (
                <div className="mt-2 border-t border-neutral-100 dark:border-neutral-800 pt-2">
                  <p className="px-3 pb-1 text-xs font-semibold uppercase tracking-wide text-neutral-500 dark:text-neutral-400">Admin</p>
                  <div className="flex flex-col gap-0.5">
                    {adminItems.map((item) => (
                      <NavLink key={item.href} href={item.href} className={mobileLinkCls} activeClassName={mobileActiveCls}>
                        <span className="text-base">{item.icon}</span>
                        {item.label}
                      </NavLink>
                    ))}
                  </div>
                </div>
              )}

              <div className="mt-2 border-t border-neutral-100 dark:border-neutral-800 pt-2">
                {user ? (
                  <>
                    <Link href="/account" className="flex items-center gap-3 rounded-md px-3 py-3 hover:bg-neutral-50 hover:dark:bg-neutral-950">
                      <span className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-neutral-900 dark:bg-neutral-100 dark:text-neutral-900 text-xs font-semibold text-white">
                        {initials(user.name)}
                      </span>
                      <span>
                        <span className="block font-medium text-neutral-900 dark:text-neutral-200">{user.name}</span>
                        <span className="block text-xs text-neutral-500 dark:text-neutral-400">Account settings</span>
                      </span>
                    </Link>
                    <form action={logoutAction}>
                      <button type="submit" className="block w-full rounded-md px-3 py-3 text-left text-neutral-700 dark:text-neutral-300 hover:bg-neutral-50 hover:dark:bg-neutral-950">
                        Log out
                      </button>
                    </form>
                  </>
                ) : (
                  <Link href="/login" className="block rounded-md px-3 py-3 text-neutral-900 dark:text-neutral-200 hover:bg-neutral-50 hover:dark:bg-neutral-950">Log in</Link>
                )}
              </div>
            </MobileNav>
          </div>
        </header>
        <main className="mx-auto w-full max-w-6xl flex-1 px-4 py-6 sm:px-6 sm:py-8">{children}</main>
      </body>
    </html>
  );
}
