"use client";

import Link from "next/link";
import { useCallback, useEffect, useRef, useState, type MouseEvent } from "react";
import { createPortal } from "react-dom";
import { usePageRoot } from "./SitePage";

type NavLink = { href: string; label: string };
type NavGroup = NavLink & { menuLabel: string; items: NavLink[] };

const NAV: (NavGroup | NavLink)[] = [
  {
    href: "/about",
    label: "About",
    menuLabel: "About submenu",
    items: [
      { href: "/about", label: "About Us" },
      { href: "/partners", label: "Our Partners & Clients" },
      { href: "/why-choose-us", label: "Why Choose Us" },
      { href: "/careers", label: "Career & Opportunities" },
      { href: "/global-strategy", label: "Unionists Group Global Strategy Division" },
      { href: "/awards", label: "Awards & Recognition" },
      { href: "/testimonials", label: "Testimonials & Strategy Division" },
      { href: "/partner-with-us", label: "Partner with Us" },
    ],
  },
  {
    href: "/product-services",
    label: "Product & Services",
    menuLabel: "Product & Services submenu",
    items: [
      { href: "/product-services", label: "Product & Services" },
      { href: "/global-agriculture", label: "Global Agriculture & Food Ingredients" },
      { href: "/services", label: "Services" },
      { href: "/industries-we-serve", label: "Industries We Serve" },
    ],
  },
  {
    href: "/sustainability-esg",
    label: "Sustainability & Responsibility",
    menuLabel: "Sustainability submenu",
    items: [
      { href: "/sustainability-esg", label: "Sustainability & ESG" },
      { href: "/social-responsibility", label: "Social Responsibility & Charity" },
    ],
  },
  {
    href: "/roadmap",
    label: "Innovations & AI",
    menuLabel: "Innovations & AI submenu",
    items: [
      { href: "/roadmap", label: "Roadmap" },
      { href: "/thought-leadership-articles", label: "Thought Leadership & Articles" },
      { href: "/ai-innovation-lab", label: "AI & Innovation Lab" },
    ],
  },
  {
    href: "/media-insights",
    label: "Media & Insights",
    menuLabel: "Media & Insights submenu",
    items: [
      { href: "/media-insights", label: "Media & Insights" },
      { href: "/unionists-magazine", label: "Unionists Group Magazine" },
    ],
  },
  { href: "/global-presence", label: "Global Presence" },
  { href: "/donations", label: "Donations" },
  { href: "/contact", label: "Contact" },
];

const MOBILE = "(max-width: 1180px)";
const cx = (...c: (string | false | undefined)[]) => c.filter(Boolean).join(" ");

const Chevron = () => (
  <svg className="nav-dropdown-chevron w-[9px] h-[9px] text-white/60" viewBox="0 0 12 8" aria-hidden="true">
    <path d="M1 1.5 6 6.5 11 1.5" stroke="currentColor" strokeWidth="1.6" fill="none" strokeLinecap="round" strokeLinejoin="round" />
  </svg>
);

/**
 * Site header (same markup as the static pages). Behaviour ported from
 * script.js: mobile menu (moved to the end of the page on ≤1180px so it is not
 * clipped by the header), hover / tap dropdowns, and the shadow on scroll.
 *
 * @param transparent see-through until scrolled (over the home hero); defaults to `home`
 * @param active      href of the highlighted top-level item
 * @param activeItem  href of the highlighted dropdown item
 */
export function SiteHeader({
  home = false,
  transparent = home,
  active,
  activeItem,
  accountCurrent = false,
}: {
  home?: boolean;
  transparent?: boolean;
  active?: string;
  activeItem?: string;
  accountCurrent?: boolean;
}) {
  const pageRoot = usePageRoot();
  const headerRef = useRef<HTMLElement>(null);
  const [mobile, setMobile] = useState(false);
  const [navOpen, setNavOpen] = useState(false);
  const [openIdx, setOpenIdx] = useState<number | null>(null);
  const [scrolled, setScrolled] = useState(false);
  const closeTimer = useRef<ReturnType<typeof setTimeout>>(undefined);

  const reset = useCallback(() => {
    setNavOpen(false);
    setOpenIdx(null);
  }, []);

  // Breakpoint, header height (used by the mobile menu's CSS) and resets.
  useEffect(() => {
    const mq = window.matchMedia(MOBILE);
    const setHeight = () => {
      const h = headerRef.current;
      if (h) document.documentElement.style.setProperty("--header-height", `${h.getBoundingClientRect().height}px`);
    };
    const sync = () => {
      setMobile(mq.matches);
      setHeight();
      if (!mq.matches) reset();
    };
    const onMq = () => setOpenIdx(null);
    sync();
    window.addEventListener("resize", sync);
    window.addEventListener("pageshow", reset);
    mq.addEventListener("change", onMq);
    return () => {
      window.removeEventListener("resize", sync);
      window.removeEventListener("pageshow", reset);
      mq.removeEventListener("change", onMq);
    };
  }, [reset]);

  // Next keeps a visited page mounted (hidden) for back/forward; start closed when it returns.
  useEffect(() => () => reset(), [reset]);

  // body.nav-open locks scrolling while the mobile menu is open.
  useEffect(() => {
    document.body.classList.toggle("nav-open", navOpen);
    return () => document.body.classList.remove("nav-open");
  }, [navOpen]);

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

  // Mobile: tapping outside a dropdown closes it.
  useEffect(() => {
    if (!mobile) return;
    const onDoc = (e: globalThis.MouseEvent) => {
      if (!(e.target as Element | null)?.closest?.(".nav-dropdown")) setOpenIdx(null);
    };
    document.addEventListener("click", onDoc);
    return () => document.removeEventListener("click", onDoc);
  }, [mobile]);

  const onToggleClick = (i: number) => (e: MouseEvent) => {
    if (!mobile) {
      setNavOpen(false);
      return;
    }
    e.preventDefault();
    e.stopPropagation();
    setOpenIdx((cur) => (cur === i ? null : i));
  };
  const onEnter = (i: number) => () => {
    if (mobile) return;
    clearTimeout(closeTimer.current);
    setOpenIdx(i);
  };
  const onLeave = (i: number) => () => {
    if (mobile) return;
    closeTimer.current = setTimeout(() => setOpenIdx((cur) => (cur === i ? null : cur)), 120);
  };
  const closeNav = () => setNavOpen(false);

  const linkCls = (isActive: boolean, toggle: boolean) =>
    cx(
      toggle && "nav-dropdown-toggle",
      isActive && "nav-link-active",
      "inline-flex items-center",
      toggle && "gap-1",
      "text-[13.5px] font-medium",
      isActive ? "text-white" : "text-white/85",
      "py-2 whitespace-nowrap hover:text-white transition-colors",
    );

  const nav = (
    <nav className={cx("main-nav min-w-0", navOpen && "is-open")} id="main-nav" aria-label="Primary">
      <ul className="flex items-center gap-[19px] flex-wrap">
        {NAV.map((n, i) =>
          "items" in n ? (
            <li key={n.href + i} className={cx("nav-dropdown", openIdx === i && "is-open")} onMouseEnter={onEnter(i)} onMouseLeave={onLeave(i)}>
              <Link href={n.href} className={linkCls(active === n.href, true)} onClick={onToggleClick(i)}>
                {n.label}
                <Chevron />
              </Link>
              <ul className="nav-dropdown-menu" role="menu" aria-label={n.menuLabel}>
                {n.items.map((it) => (
                  <li key={it.href} role="none">
                    <Link href={it.href} className={activeItem === it.href ? "is-active" : undefined} role="menuitem" onClick={closeNav}>
                      {it.label}
                    </Link>
                  </li>
                ))}
              </ul>
            </li>
          ) : (
            <li key={n.href}>
              <Link href={n.href} className={linkCls(active === n.href, false)} onClick={closeNav}>
                {n.label}
              </Link>
            </li>
          ),
        )}
      </ul>
    </nav>
  );

  return (
    <>
      <header
        ref={headerRef}
        className={cx("site-header", transparent && "site-header--home", "sticky top-0 z-50", transparent && scrolled && "is-scrolled")}
        style={scrolled ? { boxShadow: "0 4px 24px rgba(0,0,0,.22)" } : undefined}
      >
        <div className="max-w-[1400px] mx-auto px-5 py-4 flex items-center justify-between gap-[18px]">
          {home ? (
            <a href="#" className="text-[19px] font-extrabold text-white tracking-[0.01em] shrink-0">
              Unionists
            </a>
          ) : (
            <Link href="/" className="text-[19px] font-extrabold text-white tracking-[0.01em] shrink-0">
              Unionists
            </Link>
          )}

          {!(mobile && pageRoot) && nav}

          <div className="flex items-center gap-3 shrink-0">
            <Link href="/login" className="nav-account-btn" aria-label="Account" aria-current={accountCurrent ? "page" : undefined}>
              <img src="/assets/images/nav-account-icon.png" alt="" width="44" height="40" decoding="async" />
            </Link>
            <button
              className="menu-toggle hidden flex-col justify-center gap-[5px] w-[38px] h-[38px] bg-transparent border-0 cursor-pointer p-0"
              id="menu-toggle"
              aria-label="Toggle menu"
              aria-expanded={navOpen}
              aria-controls="main-nav"
              onClick={() => setNavOpen((o) => !o)}
            >
              <span className="block w-[22px] h-0.5 bg-white transition-[transform,opacity] duration-200"></span>
              <span className="block w-[22px] h-0.5 bg-white transition-[transform,opacity] duration-200"></span>
              <span className="block w-[22px] h-0.5 bg-white transition-[transform,opacity] duration-200"></span>
            </button>
          </div>
        </div>
      </header>
      {mobile && pageRoot && createPortal(nav, pageRoot)}
    </>
  );
}
