"use client";

import { useEffect, useRef, useState } from "react";
import { usePathname } from "next/navigation";
import {
  ChevronDown,
  Globe,
  Grid3x3,
  Heart,
  Menu,
  MessageSquare,
  X,
} from "lucide-react";
import { ContactModal } from "@/components/ContactModal";
import { destinationHref } from "@/data/destinations";
import { filterDestinations } from "@/data/home";

const links = [
  { label: "About us", href: "/about-us" },
  { label: "Destination", href: "/destinations", dropdown: true },
  { label: "Cruise", href: "/cruise-tours" },
  { label: "News", href: "/news" },
] as const;

const overlayPaths = new Set(["/"]);

export function Header() {
  const pathname = usePathname();
  const [scrolled, setScrolled] = useState(false);
  const [open, setOpen] = useState(false);
  const [destOpen, setDestOpen] = useState(false);
  const [contactOpen, setContactOpen] = useState(false);
  const destRef = useRef<HTMLDivElement>(null);

  const canOverlay = overlayPaths.has(pathname || "/");
  const solid = !canOverlay || scrolled || open;

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

  useEffect(() => {
    setOpen(false);
    setDestOpen(false);
    setScrolled(window.scrollY > 12);
  }, [pathname]);

  useEffect(() => {
    const onOpenContact = () => {
      setContactOpen(true);
      setOpen(false);
    };
    window.addEventListener("vnsails:open-contact", onOpenContact);
    return () => window.removeEventListener("vnsails:open-contact", onOpenContact);
  }, []);

  useEffect(() => {
    if (!destOpen) return;
    const onPointerDown = (e: MouseEvent) => {
      if (destRef.current && !destRef.current.contains(e.target as Node)) {
        setDestOpen(false);
      }
    };
    const onKeyDown = (e: KeyboardEvent) => {
      if (e.key === "Escape") setDestOpen(false);
    };
    document.addEventListener("mousedown", onPointerDown);
    document.addEventListener("keydown", onKeyDown);
    return () => {
      document.removeEventListener("mousedown", onPointerDown);
      document.removeEventListener("keydown", onKeyDown);
    };
  }, [destOpen]);

  const navText = solid ? "text-[#1c2b33] hover:text-[#111827]" : "";
  const iconText = solid ? "text-[#1c2b33]/75 hover:text-[#111827]" : "";
  const ctaClass = solid
    ? "ml-2 inline-flex items-center gap-2 rounded-full border border-[#d7dee2] bg-[#f3f5f6] px-4 py-2 text-[13px] font-bold text-[#1c2b33] transition hover:border-accent/40 hover:bg-[#eef6f9]"
    : "ml-2 inline-flex items-center gap-2 rounded-full border border-white/45 bg-white/15 px-4 py-2 text-[13px] font-bold backdrop-blur-sm transition hover:bg-white/25";

  return (
    <header
      className={`fixed inset-x-0 top-0 z-50 transition-[background-color,box-shadow,backdrop-filter] duration-300 ${
        solid
          ? "bg-white shadow-[0_4px_20px_rgba(23,98,122,0.08)]"
          : "site-header--overlay bg-transparent shadow-none"
      }`}
    >
      <div className="site-header__bar mx-auto flex h-[92px] w-[min(1240px,calc(100%-2rem))] items-center justify-between gap-3">
        <a href="/" className="shrink-0">
          <img
            src="/img/logo.png"
            alt="VNSAILS — Vietnam Yachting & Cruises"
            className={`h-[80px] w-auto object-contain transition ${
              solid ? "" : "drop-shadow-[0_4px_14px_rgba(0,0,0,0.45)]"
            }`}
          />
        </a>

        <div className="hidden flex-1 items-center justify-end gap-5 xl:gap-7 lg:flex">
          <nav className="flex items-center gap-5 xl:gap-6">
            {links.map((link) =>
              "dropdown" in link && link.dropdown ? (
                <div key={link.label} className="relative" ref={destRef}>
                  <button
                    type="button"
                    aria-expanded={destOpen}
                    aria-haspopup="menu"
                    onClick={() => setDestOpen((v) => !v)}
                    className={`inline-flex items-center gap-1 text-[14px] font-bold transition ${navText}`}
                  >
                    {link.label}
                    <ChevronDown
                      className={`h-3.5 w-3.5 transition ${destOpen ? "rotate-180" : ""}`}
                      strokeWidth={2.4}
                    />
                  </button>
                  {destOpen && (
                    <div
                      role="menu"
                      className="absolute top-full left-0 z-50 mt-2 max-h-[70vh] w-[260px] overflow-auto rounded-xl border border-[var(--line)] bg-white p-2 shadow-xl"
                    >
                      {filterDestinations.map((item) => (
                        <a
                          key={item.name}
                          role="menuitem"
                          href={destinationHref(item.name)}
                          className="block rounded-lg px-3 py-2.5 text-sm font-semibold text-[#1c2b33] hover:bg-[#e8f5f9]"
                          onClick={() => setDestOpen(false)}
                        >
                          {item.name}
                        </a>
                      ))}
                    </div>
                  )}
                </div>
              ) : (
                <a
                  key={link.label}
                  href={link.href}
                  className={`text-[14px] font-bold transition ${navText}`}
                >
                  {link.label}
                </a>
              ),
            )}
          </nav>

          <div className="flex items-center gap-0.5">
            <button
              type="button"
              className={`grid h-9 w-9 place-items-center transition ${iconText}`}
              aria-label="Apps"
            >
              <Grid3x3 className="h-[18px] w-[18px]" strokeWidth={1.8} />
            </button>
            <button
              type="button"
              className={`grid h-9 w-9 place-items-center transition ${iconText}`}
              aria-label="Language"
            >
              <Globe className="h-[18px] w-[18px]" strokeWidth={1.8} />
            </button>
            <button
              type="button"
              className={`inline-flex h-9 items-center gap-1.5 px-2 text-[13px] font-semibold transition ${iconText}`}
              aria-label="Wishlist"
            >
              <Heart className="h-[18px] w-[18px]" strokeWidth={1.8} />
              <span>Wishlist</span>
            </button>
            <button
              type="button"
              onClick={() => setContactOpen(true)}
              className={ctaClass}
            >
              Let’s trip
              <MessageSquare className="h-4 w-4" strokeWidth={2} />
            </button>
          </div>
        </div>

        <button
          type="button"
          className={`grid h-10 w-10 place-items-center rounded-full transition lg:hidden ${
            solid ? "text-[#1c2b33]" : ""
          }`}
          aria-label="Menu"
          onClick={() => setOpen((v) => !v)}
        >
          {open ? <X className="h-6 w-6" strokeWidth={2} /> : <Menu className="h-6 w-6" strokeWidth={2} />}
        </button>
      </div>

      {open && (
        <div className="border-t border-[var(--line)] bg-white px-4 py-4 lg:hidden">
          <div className="mx-auto flex w-full flex-col gap-2">
            {links.map((link) => (
              <a
                key={link.label}
                href={link.href}
                className="rounded-xl px-3 py-2.5 text-sm font-semibold text-[#1c2b33] hover:bg-[#e8f5f9]"
                onClick={() => setOpen(false)}
              >
                {link.label}
              </a>
            ))}
            <button
              type="button"
              onClick={() => {
                setOpen(false);
                setContactOpen(true);
              }}
              className="mt-2 inline-flex items-center justify-center gap-2 rounded-full border border-[#d7dee2] bg-[#f3f5f6] px-5 py-3 text-sm font-bold text-[#1c2b33]"
            >
              Let’s trip
              <MessageSquare className="h-4 w-4" strokeWidth={2} />
            </button>
          </div>
        </div>
      )}

      <ContactModal open={contactOpen} onClose={() => setContactOpen(false)} />
    </header>
  );
}
