"use client";

import { useEffect, useRef, useState } from "react";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { AnimatePresence, motion } from "framer-motion";
import { ChevronDown, Menu, X } from "lucide-react";
import { localizedPath, parsePublicPath, type Locale } from "@alterra/shared";
import Logo from "./Logo";
import LanguageSwitch from "./LanguageSwitch";
import { CurrencySwitch } from "./Currency";
import type { LayoutCopy, Menus } from "@/lib/site";

type MenuKey = "services" | "locations";
type NavItem = { label: string; path: string; menu?: MenuKey };

const ease = [0.22, 1, 0.36, 1] as const;

export default function Header({ lang, copy, menus }: { lang: Locale; copy: LayoutCopy; menus: Menus }) {
  const pathname = usePathname();
  const current = parsePublicPath(pathname).internalPath;
  const [scrolled, setScrolled] = useState(false);
  const [mobileOpen, setMobileOpen] = useState(false);
  const [dropdown, setDropdown] = useState<MenuKey | null>(null);
  const [accordion, setAccordion] = useState<MenuKey | null>(null);
  const closeTimer = useRef<number | undefined>(undefined);

  const to = (path: string) => localizedPath(lang, path);
  const isActive = (path: string) => current === path || current.startsWith(`${path}/`);

  const items: NavItem[] = [
    { label: copy.nav.properties, path: "/properties" },
    { label: copy.nav.services, path: "/services", menu: "services" },
    { label: copy.nav.locations, path: "/locations", menu: "locations" },
    { label: copy.nav.buying, path: "/buying-in-colombia" },
    { label: copy.nav.insights, path: "/insights" },
    { label: copy.nav.about, path: "/about" },
  ];

  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 40);
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  // Close everything after navigating.
  useEffect(() => {
    setMobileOpen(false);
    setDropdown(null);
  }, [pathname]);

  useEffect(() => {
    document.body.style.overflow = mobileOpen ? "hidden" : "";
    if (mobileOpen) window.__lenis?.stop();
    else window.__lenis?.start();
  }, [mobileOpen]);

  useEffect(() => {
    const onKey = (e: KeyboardEvent) => {
      if (e.key !== "Escape") return;
      setDropdown(null);
      setMobileOpen(false);
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, []);

  const openMenu = (key: MenuKey) => {
    window.clearTimeout(closeTimer.current);
    setDropdown(key);
  };
  const scheduleClose = () => {
    closeTimer.current = window.setTimeout(() => setDropdown(null), 140);
  };

  const solid = scrolled || mobileOpen || dropdown !== null;
  const activeMenu = dropdown ? menus[dropdown] : null;
  const activeMenuItem = items.find((i) => i.menu === dropdown);

  return (
    <header
      className={`fixed inset-x-0 top-0 z-50 text-cream transition-[background-color,padding,box-shadow] duration-500 ${
        solid ? "bg-ink/95 py-3 shadow-lg backdrop-blur" : "bg-transparent py-6"
      }`}
      onMouseLeave={scheduleClose}
    >
      <div className="mx-auto flex max-w-7xl items-center justify-between gap-6 px-5 md:px-8">
        <Link href={to("/")} className="shrink-0">
          <Logo priority className={`transition-[height] duration-500 ${solid ? "h-9 md:h-10" : "h-10 md:h-12"}`} />
        </Link>

        <nav aria-label="Main" className="hidden items-center gap-6 whitespace-nowrap xl:flex 2xl:gap-8">
          {items.map((item) =>
            item.menu ? (
              <div key={item.path} onMouseEnter={() => openMenu(item.menu!)}>
                <button
                  type="button"
                  onClick={() => setDropdown((d) => (d === item.menu ? null : item.menu!))}
                  aria-expanded={dropdown === item.menu}
                  aria-haspopup="true"
                  className={`flex items-center gap-1 py-2 text-[0.8rem] tracking-wide transition hover:text-gold-light ${
                    isActive(item.path) ? "text-gold-light" : "text-cream/80"
                  }`}
                >
                  {item.label}
                  <ChevronDown
                    size={13}
                    strokeWidth={1.6}
                    className={`transition-transform duration-300 ${dropdown === item.menu ? "rotate-180" : ""}`}
                  />
                </button>
              </div>
            ) : (
              <Link
                key={item.path}
                href={to(item.path)}
                onMouseEnter={scheduleClose}
                className={`py-2 text-[0.8rem] tracking-wide transition hover:text-gold-light ${
                  isActive(item.path) ? "text-gold-light" : "text-cream/80"
                }`}
              >
                {item.label}
              </Link>
            ),
          )}
        </nav>

        <div className="hidden items-center gap-5 xl:flex" onMouseEnter={scheduleClose}>
          <LanguageSwitch lang={lang} label={copy.nav.language} />
          <span className="h-4 w-px bg-cream/20" aria-hidden />
          <CurrencySwitch label={copy.nav.currency} />
          <Link
            href={to("/contact")}
            className="ml-1 border border-gold px-5 py-2.5 text-[0.72rem] tracking-[0.16em] whitespace-nowrap uppercase transition hover:bg-gold hover:text-ink"
          >
            {copy.nav.cta}
          </Link>
        </div>

        <button
          className="flex items-center xl:hidden"
          onClick={() => setMobileOpen((v) => !v)}
          aria-expanded={mobileOpen}
          aria-label={mobileOpen ? copy.nav.close : copy.nav.menu}
        >
          {mobileOpen ? <X size={26} strokeWidth={1.4} /> : <Menu size={26} strokeWidth={1.4} />}
        </button>
      </div>

      {/* Desktop dropdown panel */}
      <AnimatePresence>
        {activeMenu && activeMenuItem && (
          <motion.div
            key={dropdown}
            initial={{ opacity: 0, y: -8 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: -8 }}
            transition={{ duration: 0.35, ease }}
            onMouseEnter={() => openMenu(dropdown!)}
            className="absolute inset-x-0 top-full hidden border-t border-cream/10 bg-ink/97 shadow-2xl backdrop-blur xl:block"
          >
            <div className="mx-auto grid max-w-7xl grid-cols-[1fr_2.6fr] gap-12 px-8 py-10">
              <div>
                <p className="eyebrow text-gold-light">{activeMenuItem.label}</p>
                <Link
                  href={to(activeMenuItem.path)}
                  className="mt-5 inline-block border-b border-gold/60 pb-1 font-serif text-2xl transition hover:text-gold-light"
                >
                  {dropdown === "services" ? copy.nav.allServices : copy.nav.allLocations} →
                </Link>
              </div>
              <ul className="grid grid-cols-3 gap-x-8 gap-y-7">
                {activeMenu.map((entry) => (
                  <li key={entry.path}>
                    <Link href={to(entry.path)} className="group block">
                      <span
                        className={`font-serif text-xl leading-snug transition group-hover:text-gold-light ${
                          isActive(entry.path) ? "text-gold-light" : ""
                        }`}
                      >
                        {entry.name}
                      </span>
                      <span className="mt-1.5 block text-[0.8rem] leading-relaxed text-cream/70">{entry.line}</span>
                    </Link>
                  </li>
                ))}
              </ul>
            </div>
          </motion.div>
        )}
      </AnimatePresence>

      {/* Mobile menu */}
      {mobileOpen && (
        <div className="h-[calc(100dvh-60px)] overflow-y-auto bg-ink px-5 pb-12 pt-6 xl:hidden" data-lenis-prevent>
          <nav aria-label="Main" className="flex flex-col">
            {items.map((item) =>
              item.menu ? (
                <div key={item.path} className="border-b border-cream/10">
                  <button
                    type="button"
                    onClick={() => setAccordion((a) => (a === item.menu ? null : item.menu!))}
                    aria-expanded={accordion === item.menu}
                    className="flex w-full items-center justify-between py-4 font-serif text-3xl"
                  >
                    {item.label}
                    <ChevronDown
                      size={22}
                      strokeWidth={1.3}
                      className={`text-gold-ink transition-transform duration-300 ${accordion === item.menu ? "rotate-180" : ""}`}
                    />
                  </button>
                  <AnimatePresence initial={false}>
                    {accordion === item.menu && (
                      <motion.ul
                        initial={{ height: 0, opacity: 0 }}
                        animate={{ height: "auto", opacity: 1 }}
                        exit={{ height: 0, opacity: 0 }}
                        transition={{ duration: 0.35, ease }}
                        className="overflow-hidden"
                      >
                        {menus[item.menu].map((entry) => (
                          <li key={entry.path}>
                            <Link href={to(entry.path)} className="block py-2.5 pl-1 text-[0.95rem] text-cream/75">
                              {entry.name}
                            </Link>
                          </li>
                        ))}
                        <li>
                          <Link href={to(item.path)} className="eyebrow block pb-5 pt-3 pl-1 text-gold-light">
                            {item.menu === "services" ? copy.nav.allServices : copy.nav.allLocations} →
                          </Link>
                        </li>
                      </motion.ul>
                    )}
                  </AnimatePresence>
                </div>
              ) : (
                <Link key={item.path} href={to(item.path)} className="border-b border-cream/10 py-4 font-serif text-3xl">
                  {item.label}
                </Link>
              ),
            )}
            <Link href={to("/contact")} className="border-b border-cream/10 py-4 font-serif text-3xl">
              {copy.nav.contact}
            </Link>
          </nav>

          <div className="mt-8 flex items-center gap-6">
            <LanguageSwitch lang={lang} label={copy.nav.language} />
            <span className="h-4 w-px bg-cream/20" aria-hidden />
            <CurrencySwitch label={copy.nav.currency} />
          </div>
          <Link
            href={to("/contact")}
            className="mt-8 block border border-gold py-4 text-center text-[0.78rem] tracking-[0.16em] uppercase"
          >
            {copy.nav.cta}
          </Link>
        </div>
      )}
    </header>
  );
}
