"use client";

import { useCallback, useEffect, useRef, useState } from "react";
import Link from "next/link";
import Image from "next/image";
import { useRouter } from "next/navigation";
import { Menu, Moon, Sun, X } from "lucide-react";
import { gsap, ScrollSmoother, prefersReducedMotion } from "./gsap-setup";
import { scrollToImmersiveSection } from "./immersive-scroll";
import { rememberLandingHash } from "@/lib/landing-hash";
import type { LandingTheme } from "./useLandingTheme";

/**
 * Anchors. These ids are load-bearing beyond this page: the site header, the
 * footer link columns and lib/landing-hash all deep-link to /#product,
 * /#product-tour, /#resource, /#data-security-compliance and /#pricing, so
 * the immersive sections keep the same ids the previous landing page used.
 *
 * "Contact" is the one plain page link mixed in here — the landing page no
 * longer has its own enquiry section, so it now points straight at /contact
 * rather than an in-page anchor.
 */
const NAV = [
  { label: "Platform", href: "#product", index: "02" },
  { label: "Product tour", href: "#product-tour", index: "03" },
  { label: "Who we serve", href: "#resource", index: "04" },
  { label: "How we work", href: "#process", index: "05" },
  { label: "Security", href: "#data-security-compliance", index: "06" },
  { label: "Pricing", href: "#pricing", index: "07" },
  { label: "Contact", href: "/contact", index: "08" },
];

/** Shown in the header bar; Contact is covered by the "Book a demo" action. */
const PRIMARY_NAV = NAV.filter((item) => item.label !== "Contact");

/** Compact set for mid-width screens, where six labels would crowd the CTA. */
const COMPACT_NAV = NAV.filter((item) =>
  item.label === "Platform" || item.label === "Product tour" || item.label === "Pricing"
);

const SECONDARY = [
  { label: "About", href: "/about" },
  { label: "Articles", href: "/articles" },
  { label: "Careers", href: "/careers" },
  { label: "SME Initiative", href: "/sme-initiative" },
];

/**
 * Page chrome: a campaign strip, then a conventional sticky header.
 *
 * The SME Initiative sits in the strip so it does not compete with Book a
 * demo. The header is the professional half — logo, navigation, and the two
 * actions a visitor actually needs — and it earns its background only once
 * the page has scrolled, so the hero opens clean. The strip collapses on
 * scroll to recover the space.
 */
export default function HUD({
  visible,
  theme,
  onToggleTheme,
}: {
  visible: boolean;
  theme: LandingTheme;
  onToggleTheme: () => void;
}) {
  const router = useRouter();
  const [open, setOpen] = useState(false);
  const [scrolled, setScrolled] = useState(false);
  const rootRef = useRef<HTMLDivElement>(null);
  const menuRef = useRef<HTMLDivElement>(null);
  const closeButtonRef = useRef<HTMLButtonElement>(null);

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

  // Fade the chrome in behind the preloader rather than having it pop.
  useEffect(() => {
    if (!visible || !rootRef.current) return;
    if (prefersReducedMotion()) return;
    const ctx = gsap.context(() => {
      gsap.fromTo(
        rootRef.current,
        { opacity: 0, y: -10 },
        { opacity: 1, y: 0, duration: 0.7, ease: "power2.out", delay: 0.1 }
      );
    }, rootRef);
    return () => ctx.revert();
  }, [visible]);

  // The smoother owns the scroll position, so pausing it is how the page is
  // frozen behind the menu; `overflow: hidden` alone would not stop it.
  useEffect(() => {
    const smoother = ScrollSmoother.get();
    if (open) {
      smoother?.paused(true);
      document.body.style.overflow = "hidden";
      closeButtonRef.current?.focus();
    } else {
      smoother?.paused(false);
      document.body.style.overflow = "";
    }
    return () => {
      smoother?.paused(false);
      document.body.style.overflow = "";
    };
  }, [open]);

  useEffect(() => {
    if (!open) return;
    const onKey = (e: KeyboardEvent) => {
      if (e.key === "Escape") setOpen(false);
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [open]);

  useEffect(() => {
    if (!open || !menuRef.current || prefersReducedMotion()) return;
    const ctx = gsap.context(() => {
      gsap
        .timeline()
        .fromTo(
          menuRef.current,
          { clipPath: "inset(0 0 100% 0)" },
          { clipPath: "inset(0 0 0% 0)", duration: 0.6, ease: "expo.out" }
        )
        .fromTo(
          "[data-menu-item]",
          { yPercent: 110, opacity: 0 },
          { yPercent: 0, opacity: 1, duration: 0.55, ease: "power3.out", stagger: 0.045 },
          "-=0.3"
        );
    }, menuRef);
    return () => ctx.revert();
  }, [open]);

  /**
   * NAV entries are either in-page anchors ("#product") or, for "Contact", a
   * plain page path ("/contact") — that one is a real route now, so it's a
   * normal navigation with no smoother or remembered-hash involved.
   *
   * Anchor navigation has to go through the smoother when one exists — a
   * native hash jump would move the scroll position out from under it and the
   * transformed content would tear. On subpages (where the section does not
   * exist) the hash is remembered and the visitor is routed to the landing
   * page, which scrolls to it once its sections mount.
   */
  const goTo = useCallback((href: string) => {
    setOpen(false);
    if (!href.startsWith("#")) {
      router.push(href);
      return;
    }
    const id = href.replace(/^#/, "");
    if (scrollToImmersiveSection(id)) return;

    // Not on the landing page: push "/" without the hash. A hash in the URL
    // makes the browser jump natively on load AND the landing page scroll
    // again once its sections mount — a visible double scroll. The
    // remembered hash alone produces exactly one scroll (and the landing
    // rewrites the URL to /#id after).
    rememberLandingHash(id);
    router.push("/");
  }, [router]);

  return (
    <>
      <div
        ref={rootRef}
        className="fixed inset-x-0 top-0 z-[90]"
        style={visible ? undefined : { opacity: 0 }}
      >

        <header
          className={
            scrolled
              ? "border-b border-white/10 bg-[hsl(var(--background))]/85 backdrop-blur-xl transition-colors duration-300"
              : "border-b border-transparent bg-transparent transition-colors duration-300"
          }
        >
          <div className="mx-auto flex h-16 w-full max-w-[88rem] items-center justify-between gap-4 px-6 lg:h-[4.5rem] lg:gap-6">
            <Link href="/" aria-label="Oxyfinz home" className="flex shrink-0 items-center">
              <Image
                src="/assets/logooxy.png"
                alt="Oxyfinz"
                width={160}
                height={52}
                className="h-8 w-auto object-contain"
                priority
              />
            </Link>

            <nav className="hidden items-center gap-0.5 md:flex xl:hidden" aria-label="Primary">
              {COMPACT_NAV.map((item) => (
                <button
                  key={item.href}
                  type="button"
                  onClick={() => goTo(item.href)}
                  className="whitespace-nowrap rounded-md px-2.5 py-2 text-[13px] font-medium text-[hsl(var(--foreground))]/75 transition-colors hover:bg-white/[0.06] hover:text-[hsl(var(--foreground))]"
                >
                  {item.label === "Product tour" ? "Tour" : item.label}
                </button>
              ))}
            </nav>

            <nav className="hidden items-center gap-1 xl:flex" aria-label="Primary">
              {PRIMARY_NAV.map((item) => (
                <button
                  key={item.href}
                  type="button"
                  onClick={() => goTo(item.href)}
                  className="whitespace-nowrap rounded-md px-3 py-2 text-[13px] font-medium text-[hsl(var(--foreground))]/75 transition-colors hover:bg-white/[0.06] hover:text-[hsl(var(--foreground))]"
                >
                  {item.label}
                </button>
              ))}
            </nav>

            <div className="flex items-center gap-2">
              <button
                type="button"
                onClick={onToggleTheme}
                aria-label={
                  theme === "dark" ? "Switch to light theme" : "Switch to dark theme"
                }
                title={
                  theme === "dark" ? "Switch to light theme" : "Switch to dark theme"
                }
                className="inline-flex size-9 items-center justify-center rounded-md border border-white/12 text-[hsl(var(--foreground))]/80 transition-colors hover:border-white/30 hover:text-[hsl(var(--foreground))]"
              >
                {theme === "dark" ? (
                  <Sun className="size-4" aria-hidden />
                ) : (
                  <Moon className="size-4" aria-hidden />
                )}
              </button>
              <Link
                href="/signin_step"
                className="hidden rounded-md px-3 py-2 text-[13px] font-medium text-[hsl(var(--foreground))]/75 transition-colors hover:bg-white/[0.06] hover:text-[hsl(var(--foreground))] sm:inline-flex"
              >
                Log in
              </Link>
              <Link
                href="/contact"
                className="inline-flex items-center rounded-md bg-[hsl(var(--primary))] px-4 py-2 text-[13px] font-semibold text-[hsl(var(--primary-foreground))] transition-colors hover:bg-[hsl(var(--primary-hover))]"
              >
                Book a demo
              </Link>
              {/* Full nav is only in the bar from xl; below that the menu
                  still covers Who we serve, How we work and Security. */}
              <button
                type="button"
                onClick={() => setOpen(true)}
                aria-label="Open menu"
                aria-expanded={open}
                className="ml-1 inline-flex size-9 items-center justify-center rounded-md border border-white/12 text-[hsl(var(--foreground))]/80 transition-colors hover:border-white/30 hover:text-[hsl(var(--foreground))] xl:hidden"
              >
                <Menu className="size-4" aria-hidden />
              </button>
            </div>
          </div>
        </header>
      </div>

      {open ? (
        <div
          ref={menuRef}
          role="dialog"
          aria-modal="true"
          aria-label="Site menu"
          className="fixed inset-0 z-[110] flex flex-col bg-[hsl(var(--background))] px-6 py-5 lg:px-12 lg:py-6"
        >
          <div className="flex items-center justify-between">
            <Image
              src="/assets/logooxy.png"
              alt="Oxyfinz"
              width={160}
              height={52}
              className="h-8 w-auto object-contain"
            />
            <button
              ref={closeButtonRef}
              type="button"
              onClick={() => setOpen(false)}
              className="inline-flex items-center gap-2 rounded-md border border-white/12 px-3 py-2 transition-colors hover:border-white/30"
            >
              <span className="immersive-label">Close</span>
              <X className="size-4" aria-hidden />
            </button>
          </div>

          <nav
            className="flex flex-1 flex-col justify-center gap-0.5"
            aria-label="All sections"
          >
            {NAV.map((item) => (
              <span key={item.href} className="immersive-line-mask">
                <button
                  type="button"
                  data-menu-item
                  onClick={() => goTo(item.href)}
                  className="group flex w-full items-baseline gap-5 border-b border-white/[0.07] py-3 text-left lg:gap-8"
                >
                  <span className="immersive-label w-7 shrink-0 tabular-nums">
                    {item.index}
                  </span>
                  <span className="font-heading text-[7vw] font-medium leading-[1.15] tracking-[-0.03em] text-[hsl(var(--foreground))] transition-colors group-hover:text-[hsl(var(--primary))] lg:text-[3.25vw]">
                    {item.label}
                  </span>
                </button>
              </span>
            ))}
          </nav>

          <div className="flex flex-col gap-6 border-t border-white/10 pt-6 lg:flex-row lg:items-end lg:justify-between">
            <div className="flex flex-wrap gap-x-6 gap-y-2">
              {SECONDARY.map((item) => (
                <Link
                  key={item.href}
                  href={item.href}
                  data-menu-item
                  className="immersive-label transition-colors hover:text-[hsl(var(--primary))]"
                >
                  {item.label}
                </Link>
              ))}
            </div>
            <div className="flex gap-3">
              <Link
                href="/signin_step"
                data-menu-item
                className="rounded-md border border-white/15 px-5 py-2.5 text-[13px] font-semibold transition-colors hover:border-white/35"
              >
                Log in
              </Link>
              <Link
                href="/register"
                data-menu-item
                className="rounded-md bg-[hsl(var(--primary))] px-5 py-2.5 text-[13px] font-semibold text-[hsl(var(--primary-foreground))] transition-colors hover:bg-[hsl(var(--primary-hover))]"
              >
                Sign up
              </Link>
            </div>
          </div>
        </div>
      ) : null}
    </>
  );
}
