"use client";

import { useCallback, useEffect, useRef, useState } from "react";
import { Menu, X } from "lucide-react";
import Logo from "@/components/ui/Logo";
import LanguageSwitch from "./LanguageSwitch";
import { getLenis, scrollToId } from "@/lib/motion";
import { SECTIONS, type SectionId } from "@/content/site";
import type { Dictionary, Locale } from "@/lib/i18n";

type Props = { locale: Locale; nav: Dictionary["nav"] };

const NAV_ITEMS: SectionId[] = ["overview", "about", "vision", "philosophy", "sustainability", "expertise", "inquiry"];

export default function Header({ locale, nav }: Props) {
  const [theme, setTheme] = useState<"dark" | "light">("dark");
  const [solid, setSolid] = useState(false);
  const [hidden, setHidden] = useState(false);
  const [active, setActive] = useState<SectionId | null>(null);
  const [open, setOpen] = useState(false);
  const progressRef = useRef<HTMLDivElement>(null);
  const menuRef = useRef<HTMLDivElement>(null);
  const toggleRef = useRef<HTMLButtonElement>(null);

  // Theme under the header, active section, hide-on-scroll and progress.
  useEffect(() => {
    let lastY = window.scrollY;
    let raf = 0;
    const update = () => {
      raf = 0;
      const y = window.scrollY;
      const probe = 40;
      const themed = document.querySelectorAll<HTMLElement>("[data-theme]");
      for (const el of themed) {
        const r = el.getBoundingClientRect();
        if (r.top <= probe && r.bottom > probe) {
          setTheme(el.dataset.theme === "light" ? "light" : "dark");
          break;
        }
      }
      let current: SectionId | null = null;
      for (const id of SECTIONS) {
        const el = document.getElementById(id);
        if (el && el.getBoundingClientRect().top <= window.innerHeight * 0.4) current = id;
      }
      setActive(current);
      setSolid(y > 24);
      setHidden(y > window.innerHeight * 0.8 && y > lastY + 2);
      if (y < lastY - 2) setHidden(false);
      lastY = y;
      const max = document.documentElement.scrollHeight - window.innerHeight;
      if (progressRef.current) progressRef.current.style.transform = `scaleX(${max > 0 ? y / max : 0})`;
    };
    const onScroll = () => {
      if (!raf) raf = requestAnimationFrame(update);
    };
    update();
    window.addEventListener("scroll", onScroll, { passive: true });
    window.addEventListener("resize", onScroll);
    return () => {
      window.removeEventListener("scroll", onScroll);
      window.removeEventListener("resize", onScroll);
      cancelAnimationFrame(raf);
    };
  }, []);

  const close = useCallback(() => {
    setOpen(false);
    toggleRef.current?.focus();
  }, []);

  // Mobile menu: lock scroll, Esc to close, simple focus trap.
  useEffect(() => {
    if (!open) return;
    const lenis = getLenis();
    lenis?.stop();
    document.body.style.overflow = "hidden";
    const first = menuRef.current?.querySelector<HTMLElement>("a,button");
    first?.focus();
    const onKey = (e: KeyboardEvent) => {
      if (e.key === "Escape") close();
      if (e.key === "Tab" && menuRef.current) {
        const items = Array.from(menuRef.current.querySelectorAll<HTMLElement>("a,button"));
        const [a, b] = [items[0], items[items.length - 1]];
        if (e.shiftKey && document.activeElement === a) {
          e.preventDefault();
          b.focus();
        } else if (!e.shiftKey && document.activeElement === b) {
          e.preventDefault();
          a.focus();
        }
      }
    };
    document.addEventListener("keydown", onKey);
    return () => {
      document.removeEventListener("keydown", onKey);
      document.body.style.overflow = "";
      lenis?.start();
    };
  }, [open, close]);

  const goTo = (id: SectionId) => (e: React.MouseEvent) => {
    e.preventDefault();
    setOpen(false);
    history.replaceState(null, "", `#${id}`);
    // Wait a frame so the scroll lock is released before scrolling.
    requestAnimationFrame(() => scrollToId(id));
  };

  const dark = theme === "dark" || open;

  return (
    <>
      <header
        className="site-header fixed inset-x-0 top-0 z-50"
        data-theme={dark ? "dark" : "light"}
        data-solid={solid && !open ? "true" : "false"}
        data-hidden={hidden && !open ? "true" : "false"}
        data-hero="header"
      >
        <div className="container-x flex h-[var(--header-h)] items-center justify-between gap-6">
          <a
            href={`/${locale}#top`}
            aria-label={nav.home}
            className="relative z-10 block shrink-0"
            onClick={(e) => {
              e.preventDefault();
              setOpen(false);
              const lenis = getLenis();
              if (lenis) lenis.scrollTo(0, { duration: 1.6 });
              else window.scrollTo({ top: 0, behavior: "smooth" });
            }}
          >
            <Logo tone={dark ? "reverse" : "default"} alt="" className="h-10 w-auto md:h-11" priority />
          </a>

          <nav aria-label={nav.primary} className="hidden lg:block">
            <ul className="flex items-center gap-7 xl:gap-9">
              {NAV_ITEMS.map((id) => (
                <li key={id}>
                  <a href={`#${id}`} onClick={goTo(id)} className="nav-link" aria-current={active === id ? "true" : undefined}>
                    {nav[id]}
                  </a>
                </li>
              ))}
            </ul>
          </nav>

          <div className="relative z-10 flex items-center gap-3">
            <LanguageSwitch current={locale} label={nav.language} className="hidden sm:flex" />
            <button
              ref={toggleRef}
              type="button"
              className="inline-flex h-11 w-11 items-center justify-center lg:hidden"
              aria-expanded={open}
              aria-controls="mobile-menu"
              aria-label={open ? nav.close : nav.menu}
              onClick={() => setOpen((o) => !o)}
            >
              {open ? <X size={24} strokeWidth={1.5} /> : <Menu size={24} strokeWidth={1.5} />}
            </button>
          </div>
        </div>
        <div className="absolute inset-x-0 bottom-0 h-px overflow-hidden" role="presentation">
          <div ref={progressRef} className="h-full origin-left bg-gold" style={{ transform: "scaleX(0)" }} />
        </div>
      </header>

      <div
        id="mobile-menu"
        ref={menuRef}
        role="dialog"
        aria-modal="true"
        aria-label={nav.menu}
        hidden={!open}
        className="fixed inset-0 z-40 overflow-y-auto bg-navy-ink text-white lg:hidden"
      >
        <div className="container-x flex min-h-full flex-col justify-between pb-10 pt-[calc(var(--header-h)+2rem)]">
          <ul className="space-y-1">
            {SECTIONS.map((id, i) => (
              <li key={id} className="border-b border-white/10">
                <a href={`#${id}`} onClick={goTo(id)} className="flex items-baseline gap-4 py-4">
                  <span className="numeral text-sm text-gold">{String(i + 1).padStart(2, "0")}</span>
                  <span className="display text-[2rem] leading-none">{nav[id]}</span>
                </a>
              </li>
            ))}
          </ul>
          <div className="mt-10 flex items-center justify-between">
            <LanguageSwitch current={locale} label={nav.language} />
            <Logo variant="symbol" tone="reverse" alt="" className="h-10 w-auto opacity-80" />
          </div>
        </div>
      </div>
    </>
  );
}
