"use client";

import {
  Briefcase,
  Building2,
  ClipboardCheck,
  ClipboardList,
  LogOut,
  ShieldCheck,
  User,
} from "lucide-react";
import { useEffect, useState } from "react";
import { useQuery } from "@tanstack/react-query";
import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";

import { ADMIN_HOME, EMPLOYEE_HOME } from "@/constants/business-routes";
import { getCompanySummary } from "@/services/admin-approvals/admin-approvals.client";
import { InitialsAvatar, MyBizBadge, RoleLink } from "./business-chrome";
import { useBusinessSession } from "@/components/employee-requests/use-session";
import {
  clearBusinessTokens,
  getBusinessAccessToken,
  getBusinessRefreshToken,
  nameFromEmail,
} from "@/lib/business-session";
import {
  getBusinessProfile,
  signOutBusiness,
} from "@/services/employee-login/employee-login.client";

import { BurgerIcon, LoginIcon, SigninIcon } from "./chrome-icons";

/**
 * Site header, ported from leisure-ui.com's HeaderV3.
 *
 * Two headers render, exactly as in leisure-ui: a compact one below 1226px and
 * the full nav at 1226px and up. That 1225px cut-off is not a Bootstrap
 * breakpoint — it is a bespoke one in home-v3.css — so it is defined as the
 * `nav:` variant in globals.css rather than being rounded to `xl:`.
 *
 * The Login button and "Login or signup" menu item link to /employee-login —
 * the Business-mode work-email OTP sign-in flow (components/employee-login/).
 * corp is Business-mode only (no Personal/Business toggle here), so that's
 * the one login destination regardless of which header button is used.
 *
 * Session awareness is a cheap, local check (lib/business-session.ts reads
 * the stored access token's own `exp` claim, no network call) — enough to
 * swap the Login button for "Signed in as <email>" / Sign out once a
 * business session exists (set by employee-signup's Done step or a normal
 * employee-login sign-in), without the header needing to hit the API on
 * every page load. Everything else that would need a session is still
 * marked TODO(auth) below.
 *
 * Both headers carry Bootstrap's `fixed-top` class alongside their Tailwind
 * positioning. It is not styling — on /srp the ported FlightSearchStickyBar
 * measures `document.querySelectorAll("header.fixed-top")` to decide where to
 * pin itself and publishes `--flight-header-h` / `--flight-chrome-h` from it.
 * Without the class that query returns nothing, the bar falls back to a
 * hardcoded 62px that does not match corp's header, and a gap opens between
 * the two. The class is inert off /srp (Bootstrap only loads there), and on
 * /srp it is in the `leisure-vendor` layer, below these Tailwind utilities, so
 * it cannot change how the header actually positions.
 *
 * The ids and the account-menu class are prefixed `corp*`/`corp-` on purpose.
 * /srp routes load leisure-ui's Bootstrap stylesheets, and home-v3.css styles
 * `#mobileHeader`, `#desktopHeader`, `.user-menu` and `.user-dropdown`. An id
 * selector outranks a Tailwind utility class, so reusing those names would let
 * that sheet override this header's responsive show/hide on the SRP only.
 *
 * Two faithful-to-the-original quirks worth knowing before you "fix" them:
 *
 *  - leisure-ui's Events nav link carries an inline `style={{display:'none'}}`,
 *    but its class list includes Bootstrap's `d-flex`, which is
 *    `display:flex !important`. An important author rule beats a non-important
 *    inline style, so the link has always been visible. It is visible here too.
 *  - leisure-ui's mobile header contains a search box that can never appear:
 *    `.header-search` is `display:block` by default but `display:none` at
 *    <=1225px, and the mobile header itself only exists at <=1225px. It is
 *    omitted here rather than ported as permanently hidden markup.
 */

/** Bootstrap's `.dropdown-item` as leisure-ui styles it in the account menu. */
const DROPDOWN_ITEM =
  "flex w-full items-center gap-2 rounded-[0.5rem] border-0 bg-transparent p-2 text-left text-base font-medium text-lx-second";

export default function SiteHeader() {
  const router = useRouter();
  // Not read directly — calling it still subscribes this component to route
  // changes, which is what makes `useBusinessSession()` below re-check on
  // every navigation (see its own comment): `setBusinessTokens` doesn't fire
  // a same-tab 'storage' event, so without some reactive dependency on the
  // route this header would never notice employee-login/employee-signup
  // having just written a fresh session right before routing here.
  usePathname();
  const [menuOpen, setMenuOpen] = useState(false);
  const [openUserMenu, setOpenUserMenu] = useState<"mobile" | "desktop" | null>(null);
  // useSyncExternalStore under the hood (see use-session.ts), not a
  // useState+useEffect read of getActiveBusinessSession() — that version
  // always rendered the signed-out Login button first, on every single
  // mount, then swapped to the signed-in header once the effect ran. On a
  // client-side mount (which is every navigation, since this header lives
  // in the root layout and never actually remounts — see below) that's a
  // guaranteed, measured layout shift (confirmed via the PerformanceObserver
  // layout-shift API): the Login button is wider than the signed-in avatar
  // button, so its removal visibly shifts the whole nav row. This hook
  // resolves synchronously during render instead, so a signed-in admin
  // reloading or restoring a backgrounded tab sees the correct header from
  // the first paint, not a flash of "Login" first.
  const session = useBusinessSession();
  const sessionEmail = session?.email ?? null;
  const isAdmin = session?.role === "ADMIN";
  const [sessionName, setSessionName] = useState<string | null>(null);

  /**
   * The number on the admin's Approval queue link.
   *
   * Only for admins, and deliberately not refetched on a timer: the header is
   * on every page, and a poll here would be a request per interval for the
   * whole session. The approval queue itself polls every 15s while it is open,
   * which is where an admin actually watches this number move; here it is
   * orientation, so a value up to two minutes old is fine and a stale one is
   * never wrong in a way that costs anything.
   */
  const pending = useQuery({
    queryKey: ["admin-summary", "header"],
    queryFn: async () => {
      const token = getBusinessAccessToken();
      const res = await getCompanySummary(token ?? "");
      if (!res.success) throw new Error(res.message ?? "Could not load the approval summary.");
      return res.data ?? null;
    },
    enabled: Boolean(sessionEmail) && isAdmin,
    staleTime: 2 * 60_000,
    refetchOnWindowFocus: false,
    retry: false,
  });

  /** My requests for an employee, the approval queue for the admin. */
  const roleLink = isAdmin
    ? {
        href: "/admin/flight-approvals",
        label: "Approval queue",
        icon: <ClipboardCheck size={18} aria-hidden="true" />,
        count: pending.data?.awaitingApproval.count,
      }
    : {
        href: "/employee-requests",
        label: "My requests",
        icon: <ClipboardList size={18} aria-hidden="true" />,
        count: undefined,
      };

  // Re-resolved whenever `session` changes — which includes every route
  // change, since the header stays mounted across client-side navigations
  // within this layout and `pathname` changing is itself enough to make
  // React re-read the external store, so this still catches the session
  // that employee-login/employee-signup just wrote right before routing
  // here. Only the display *name* needs this effect at all — `sessionEmail`
  // above is already correct without one.
  useEffect(() => {
    queueMicrotask(async () => {
      if (!session) {
        setSessionName(null);
        return;
      }
      // Same token the session above already validated locally — this one
      // extra call just resolves the name to greet them by (falls back to
      // deriving one from the email if the profile call fails or the
      // profile hasn't been filled in, e.g. an admin who skipped it).
      const token = getBusinessAccessToken();
      const res = token ? await getBusinessProfile(token) : null;
      const first = res?.data?.firstName;
      const last = res?.data?.lastName;
      setSessionName([first, last].filter(Boolean).join(" ") || nameFromEmail(session.email));
    });
  }, [session]);

  // Same outside-click close as leisure-ui: anything not inside a
  // .corp-user-menu closes the account dropdown. (Must be the prefixed
  // class, not leisure-ui's own .user-menu — see the file header comment on
  // why the account-menu class is prefixed. It previously wasn't actually
  // applied to the wrapper div below, so this selector matched nothing and
  // every click anywhere — including on the dropdown's own items — was
  // treated as "outside", racing against whatever that click was supposed
  // to do.)
  useEffect(() => {
    const onDocClick = (e: MouseEvent) => {
      if (!(e.target as Element).closest?.(".corp-user-menu")) setOpenUserMenu(null);
    };
    document.addEventListener("click", onDocClick);
    return () => document.removeEventListener("click", onDocClick);
  }, []);

  // Body scroll lock while the mobile drawer is open — leisure-ui leans on
  // Bootstrap's offcanvas for this; without a lock the page behind scrolls.
  useEffect(() => {
    if (!menuOpen) return;
    const previous = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    return () => {
      document.body.style.overflow = previous;
    };
  }, [menuOpen]);

  useEffect(() => {
    if (!menuOpen) return;
    const onKey = (e: KeyboardEvent) => e.key === "Escape" && setMenuOpen(false);
    document.addEventListener("keydown", onKey);
    return () => document.removeEventListener("keydown", onKey);
  }, [menuOpen]);

  const closeMenus = () => {
    setOpenUserMenu(null);
    setMenuOpen(false);
  };

  const handleSignOut = async () => {
    closeMenus();
    const refreshToken = getBusinessRefreshToken();
    if (refreshToken) await signOutBusiness(refreshToken);
    clearBusinessTokens();
    // No setSessionEmail here — it's derived from useBusinessSession now.
    // clearBusinessTokens already removed the token before this point, and
    // this setSessionName call forces the re-render that re-reads it, so
    // `sessionEmail` resolves to null on the very same tick regardless of
    // whether `router.push` below ends up changing the pathname.
    setSessionName(null);
    router.push(EMPLOYEE_HOME);
  };

  /** The logo's destination: the signed-in user's own home page. */
  const homeHref = isAdmin ? ADMIN_HOME : EMPLOYEE_HOME;

  const accountDropdown = (
    <div
      className="corp-user-dropdown bg-lx-white absolute top-[calc(100%+10px)] right-0 z-[1060] w-[220px] overflow-hidden rounded-[0.5rem] p-2 shadow-[0_0_80px_rgba(0,0,0,0.24)] xl:top-[calc(100%+20px)]"
      role="menu"
    >
      {sessionEmail ? (
        <>
          <div className="text-lx-dark truncate px-2 py-1 text-base font-semibold">
            Hi {sessionName}
          </div>
          <Link
            href="/employee-profile"
            onClick={closeMenus}
            className={DROPDOWN_ITEM}
            role="menuitem"
          >
            <User size={18} />
            Profile
          </Link>
          {/* The employee's own travel requests (PRD §6.2). Employees only
              (LEIS-1046): an admin books directly on the company card and never
              files a request, so the page would always be empty for them. Their
              equivalent is Approvals below, and the header's own role link. */}
          {!isAdmin && (
            <Link
              href="/employee-requests"
              onClick={closeMenus}
              className={DROPDOWN_ITEM}
              role="menuitem"
            >
              <ClipboardList size={18} />
              My requests
            </Link>
          )}
          {/* Booked/cancelled trips (LEIS-1022) — an internal route now, not
              the external leisure.com personal-mode link this used to be. A
              business portal's own "My Trips" linking a traveller out to a
              different site's personal account was the actual bug. */}
          <Link href="/my-trips" onClick={closeMenus} className={DROPDOWN_ITEM} role="menuitem">
            <Briefcase size={18} />
            My Trips
          </Link>
          {/* The only way into the approval queue used to be typing the URL
              by hand — there was no link anywhere in the chrome. Shown only
              for admins: an employee has no use for a queue they cannot
              act on, and the page itself still enforces this server-side
              regardless of what this link does or doesn't show. */}
          {session?.role === "ADMIN" && (
            <>
              <Link
                href="/admin/flight-approvals"
                onClick={closeMenus}
                className={DROPDOWN_ITEM}
                role="menuitem"
              >
                <ShieldCheck size={18} />
                Approvals
              </Link>
            </>
          )}
          <button
            type="button"
            onClick={handleSignOut}
            className={`${DROPDOWN_ITEM} text-red-600`}
            role="menuitem"
          >
            <LogOut size={18} />
            Logout
          </button>
        </>
      ) : (
        <>
          <Link
            href="/employee-login"
            onClick={closeMenus}
            className={DROPDOWN_ITEM}
            role="menuitem"
          >
            <SigninIcon />
            Login or signup
          </Link>
          {/* LEIS-942's own entry point for A3 (admin company sign-up) is a
              "Setting up your company? Sign up" link on the employee-login
              page itself — this is the same destination, reachable straight
              from the header instead of via employee-login first. */}
          <Link
            href="/company-signup"
            onClick={closeMenus}
            className={DROPDOWN_ITEM}
            role="menuitem"
          >
            <Building2 size={18} />
            Sign up your company
          </Link>
        </>
      )}
    </div>
  );

  const loginButton = sessionEmail ? null : (
    <Link
      href="/employee-login"
      onClick={closeMenus}
      className="bg-lx-second text-lx-white-same flex items-center gap-1 rounded-[0.5rem] border-0 px-2 py-2 text-base max-[480px]:text-xs md:gap-2 md:px-3"
    >
      <LoginIcon />
      Login
    </Link>
  );

  return (
    <div className="lx-chrome">
      {/* ---------------- Mobile header (below 1226px) ---------------- */}
      <header
        id="corpMobileHeader"
        className="fixed-top bg-lx-white nav:hidden fixed inset-x-0 top-0 z-[1030] px-3 py-2"
      >
        <div className="flex items-center justify-between">
          <Link href={homeHref} className="flex items-center gap-[8px]">
            {/* eslint-disable-next-line @next/next/no-img-element */}
            <img src="/images/v3/logo.svg" alt="Leisure" className="w-[112px]" />
            <MyBizBadge />
          </Link>

          <ul className="m-0 flex list-none items-center gap-2 p-0 md:gap-3">
            {/* The toggle is in the drawer below this width — two pills plus a
                role link plus an avatar does not fit a phone header. */}
            {sessionEmail && (
              <li className="hidden sm:block">
                <RoleLink {...roleLink} onClick={closeMenus} />
              </li>
            )}
            {loginButton && <li>{loginButton}</li>}
            <li>
              <div
                className={`corp-user-menu relative ml-auto${openUserMenu === "mobile" ? "active" : ""}`}
              >
                <button
                  type="button"
                  aria-label="Account menu"
                  aria-expanded={openUserMenu === "mobile"}
                  onClick={(e) => {
                    e.stopPropagation();
                    setOpenUserMenu((p) => (p === "mobile" ? null : "mobile"));
                  }}
                  className="flex items-center rounded-[10px] border-0 bg-transparent p-0 shadow-none outline-none"
                >
                  <InitialsAvatar name={sessionName} email={sessionEmail} />
                </button>
                {openUserMenu === "mobile" && accountDropdown}
              </div>
            </li>
            <li>
              <button
                type="button"
                aria-label="Open menu"
                className="m-0 border-0 bg-transparent p-0 shadow-none outline-none"
                onClick={() => setMenuOpen(true)}
              >
                <BurgerIcon />
              </button>
            </li>
          </ul>
        </div>
      </header>

      {/* ---------------- Mobile slide-in menu ---------------- */}
      <div
        className={`bg-lx-white nav:hidden fixed inset-y-0 z-[9999] flex w-[300px] flex-col shadow-[0_0_80px_rgba(0,0,0,0.24)] transition-[right,opacity] duration-300 ease-in-out ${
          menuOpen
            ? "visible right-0 opacity-100"
            : "pointer-events-none invisible right-[-100%] opacity-0"
        }`}
        aria-hidden={!menuOpen}
      >
        <div className="flex h-[60px] items-center justify-between border-b border-white px-3">
          <Link
            href={homeHref}
            onClick={() => setMenuOpen(false)}
            className="flex items-center gap-[8px]"
          >
            {/* eslint-disable-next-line @next/next/no-img-element */}
            <img src="/images/v3/logo.svg" alt="Leisure" className="w-[112px]" />
            <MyBizBadge />
          </Link>
          <button
            type="button"
            aria-label="Close menu"
            className="m-0 inline-flex items-center border-0 bg-transparent p-0 shadow-none outline-none"
            onClick={() => setMenuOpen(false)}
          >
            <svg width="24" height="24" viewBox="0 0 24 24" fill="none" aria-hidden="true">
              <path
                d="M18 6L6 18M6 6l12 12"
                stroke="#000"
                strokeWidth="2"
                strokeLinecap="round"
                strokeLinejoin="round"
              />
            </svg>
          </button>
        </div>

        <div className="relative flex-1 overflow-y-auto">
          <ul className="mt-3 list-none ps-3">
            {sessionEmail && (
              <li className="mb-4">
                <Link
                  href={roleLink.href}
                  className="text-lx-dark flex gap-2 p-0"
                  onClick={() => setMenuOpen(false)}
                >
                  <span className="flex items-center">
                    {isAdmin ? <ShieldCheck size={20} /> : <ClipboardList size={20} />}
                  </span>
                  <span className="text-base font-medium">{roleLink.label}</span>
                  {typeof roleLink.count === "number" && roleLink.count > 0 && (
                    <span
                      className="ms-1 inline-flex min-w-[20px] items-center justify-center rounded-[6px] px-[5px] py-[2px] text-[11px] leading-none font-bold text-white"
                      style={{ backgroundColor: "var(--fra-coral)" }}
                    >
                      {roleLink.count > 99 ? "99+" : roleLink.count}
                    </span>
                  )}
                </Link>
              </li>
            )}
          </ul>
        </div>
      </div>

      {/* ---------------- Desktop header (1226px and up) ---------------- */}
      <header
        id="corpDesktopHeader"
        className="fixed-top bg-lx-white nav:block fixed inset-x-0 top-0 z-[1030] hidden"
      >
        <nav className="py-2">
          <div className="lx-container flex items-center justify-between gap-3">
            <Link href={homeHref} className="flex items-center gap-[10px] font-bold">
              {/* eslint-disable-next-line @next/next/no-img-element */}
              <img src="/images/v3/logo.svg" alt="Leisure" className="block h-auto w-[150px]" />
              <MyBizBadge />
            </Link>

            {/*
             * The four consumer links — Hotels, Flights, Cruises, Events —
             * used to sit here. LEIS-1014 replaced them: this is the Business
             * header on every Business page, and it carries the one role link
             * and the profile menu. Hotels
             * and Flights are the search itself on the home page now, so a nav
             * link to them was a second, worse route to the same place; Cruises
             * and Events are not part of Business mode at all.
             */}
            <ul className="m-0 flex list-none items-center gap-3 p-0">
              {sessionEmail && (
                <li>
                  <RoleLink {...roleLink} onClick={closeMenus} />
                </li>
              )}
              {loginButton && <li>{loginButton}</li>}
              <li>
                <div
                  className={`corp-user-menu relative ml-auto${openUserMenu === "desktop" ? "active" : ""}`}
                >
                  <button
                    type="button"
                    aria-label="Account menu"
                    aria-expanded={openUserMenu === "desktop"}
                    onClick={(e) => {
                      e.stopPropagation();
                      setOpenUserMenu((p) => (p === "desktop" ? null : "desktop"));
                    }}
                    className="flex items-center rounded-[10px] border-0 bg-transparent p-0 shadow-none outline-none"
                  >
                    <InitialsAvatar name={sessionName} email={sessionEmail} />
                  </button>
                  {openUserMenu === "desktop" && accountDropdown}
                </div>
              </li>
            </ul>
          </div>
        </nav>
      </header>
    </div>
  );
}
