"use client";

import { useEffect, useId, useRef, useState } from "react";
import { SiteLink } from "@/components/site/site-link";

type Active =
  | "home"
  | "projects"
  | "experience"
  | "services"
  | "about"
  | "studio"
  | "team"
  | "journal"
  | "awards"
  | "publications"
  | "contact";

const primaryLinks: {
  href: string;
  label: string;
  shortLabel?: string;
  key: Active;
}[] = [
  { href: "/projects", label: "Projects", key: "projects" },
  { href: "/experience", label: "3D Experience", shortLabel: "3D", key: "experience" },
  { href: "/services", label: "Services", key: "services" },
  { href: "/about", label: "About", key: "about" },
  { href: "/team", label: "Team", key: "team" },
  { href: "/journal", label: "Journal", key: "journal" },
  { href: "/contact", label: "Contact", key: "contact" },
];

const moreLinks: { href: string; label: string; key: Active }[] = [
  { href: "/studio", label: "Studio", key: "studio" },
  { href: "/awards", label: "Awards", key: "awards" },
  { href: "/publications", label: "Publications", key: "publications" },
];

export function SiteHeader({
  studioName,
  active,
  tone = "light",
}: {
  studioName: string;
  active?: Active;
  tone?: "dark" | "light";
}) {
  const [scrolled, setScrolled] = useState(false);
  const [open, setOpen] = useState(false);
  const [moreOpen, setMoreOpen] = useState(false);
  const menuBtnRef = useRef<HTMLButtonElement>(null);
  const sheetRef = useRef<HTMLElement>(null);
  const moreRef = useRef<HTMLDetailsElement>(null);
  const drawerTitleId = useId();
  const moreActive = moreLinks.some((l) => l.key === active);

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

  useEffect(() => {
    if (!open) return;
    const prev = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    const sheet = sheetRef.current;
    const focusables = sheet?.querySelectorAll<HTMLElement>(
      'a[href], button:not([disabled])',
    );
    focusables?.[0]?.focus();

    const onKey = (e: KeyboardEvent) => {
      if (e.key === "Escape") {
        setOpen(false);
        menuBtnRef.current?.focus();
        return;
      }
      if (e.key !== "Tab" || !focusables?.length) return;
      const list = Array.from(focusables);
      const first = list[0];
      const last = list[list.length - 1];
      if (e.shiftKey && document.activeElement === first) {
        e.preventDefault();
        last.focus();
      } else if (!e.shiftKey && document.activeElement === last) {
        e.preventDefault();
        first.focus();
      }
    };
    window.addEventListener("keydown", onKey);
    return () => {
      document.body.style.overflow = prev;
      window.removeEventListener("keydown", onKey);
    };
  }, [open]);

  useEffect(() => {
    if (!moreOpen) return;
    const onPointer = (e: MouseEvent) => {
      if (!moreRef.current?.contains(e.target as Node)) {
        moreRef.current?.removeAttribute("open");
        setMoreOpen(false);
      }
    };
    document.addEventListener("mousedown", onPointer);
    return () => document.removeEventListener("mousedown", onPointer);
  }, [moreOpen]);

  const onDark = tone === "dark" && !scrolled && !open;
  const bar =
    scrolled || open
      ? "border-b border-[var(--archi-line)] bg-[rgba(244,241,234,0.96)] text-[var(--archi-ink)] backdrop-blur-xl"
      : onDark
        ? "border-b border-transparent bg-transparent text-white"
        : "border-b border-transparent bg-transparent text-[var(--archi-ink)]";

  const muted =
    onDark && !open
      ? "text-white/55 hover:text-white"
      : "text-[var(--archi-ink-muted)] hover:text-[var(--archi-ink)]";
  const activeCls = onDark && !open ? "text-white" : "text-[var(--archi-ink)]";
  const allMobile = [...primaryLinks, ...moreLinks];

  function closeMenu() {
    setOpen(false);
    menuBtnRef.current?.focus();
  }

  return (
    <header
      className={`studio-header fixed inset-x-0 top-0 z-50 pt-[env(safe-area-inset-top)] transition-[background,border-color,color,backdrop-filter] duration-300 ${bar}`}
    >
      <div className="studio-container flex h-14 items-center justify-between gap-3 sm:h-[4.25rem]">
        <SiteLink
          href="/"
          className="relative z-[60] min-w-0 truncate font-[family-name:var(--font-display)] text-[0.95rem] font-semibold tracking-[0.04em] sm:text-lg"
          onClick={() => setOpen(false)}
        >
          {studioName}
        </SiteLink>

        <nav
          aria-label="Primary"
          className="hidden items-center gap-4 text-[0.7rem] tracking-[0.12em] uppercase xl:gap-5 lg:flex"
        >
          {primaryLinks.map((link) => (
            <SiteLink
              key={link.href}
              href={link.href}
              aria-current={active === link.key ? "page" : undefined}
              className={
                active === link.key ? `${activeCls} font-medium` : muted
              }
            >
              {link.shortLabel ? (
                <>
                  <span className="xl:hidden">{link.shortLabel}</span>
                  <span className="hidden xl:inline">{link.label}</span>
                </>
              ) : (
                link.label
              )}
            </SiteLink>
          ))}
          <details
            ref={moreRef}
            className="relative"
            onToggle={(e) =>
              setMoreOpen((e.target as HTMLDetailsElement).open)
            }
          >
            <summary
              className={`cursor-pointer list-none ${
                moreActive ? `${activeCls} font-medium` : muted
              } [&::-webkit-details-marker]:hidden`}
              aria-current={moreActive ? "true" : undefined}
            >
              More
            </summary>
            <div className="absolute right-0 mt-3 min-w-[12rem] border border-[var(--archi-line)] bg-[var(--archi-cream)] py-2 text-[var(--archi-ink)] shadow-lg">
              {moreLinks.map((link) => (
                <SiteLink
                  key={link.href}
                  href={link.href}
                  aria-current={active === link.key ? "page" : undefined}
                  className={`block px-4 py-2.5 text-[0.72rem] tracking-[0.12em] uppercase transition hover:bg-white ${
                    active === link.key
                      ? "text-[var(--archi-ink)] font-medium"
                      : "text-[var(--archi-ink-muted)] hover:text-[var(--archi-ink)]"
                  }`}
                >
                  {link.label}
                </SiteLink>
              ))}
            </div>
          </details>
        </nav>

        <button
          ref={menuBtnRef}
          type="button"
          className={`studio-menu-btn relative z-[60] lg:hidden ${onDark ? "is-dark" : ""} ${open ? "is-open" : ""}`}
          aria-expanded={open}
          aria-controls="studio-mobile-nav"
          aria-label={open ? "Close menu" : "Open menu"}
          onClick={() => setOpen((v) => !v)}
        >
          <span />
          <span />
          <span />
        </button>
      </div>

      <div
        id="studio-mobile-nav"
        className={`studio-mobile-drawer lg:hidden ${open ? "is-open" : ""}`}
        aria-hidden={!open}
      >
        <button
          type="button"
          className="studio-mobile-backdrop"
          aria-label="Close menu"
          tabIndex={open ? 0 : -1}
          onClick={closeMenu}
        />
        <nav
          ref={sheetRef}
          className="studio-mobile-sheet"
          aria-labelledby={drawerTitleId}
          role="dialog"
          aria-modal="true"
        >
          <div className="studio-mobile-sheet-inner">
            <div className="studio-mobile-sheet-head">
              <div>
                <p
                  id={drawerTitleId}
                  className="text-[0.65rem] tracking-[0.28em] text-[var(--archi-ink-muted)] uppercase"
                >
                  Navigate
                </p>
                <p className="mt-2 max-w-[14rem] truncate font-[family-name:var(--font-display)] text-xl font-semibold tracking-tight text-[var(--archi-ink)]">
                  {studioName}
                </p>
              </div>
              <span className="studio-mobile-sheet-mark" aria-hidden />
            </div>

            <div className="studio-mobile-sheet-links">
              {allMobile.map((link, i) => {
                const isActive = active === link.key;
                return (
                  <SiteLink
                    key={link.href}
                    href={link.href}
                    aria-current={isActive ? "page" : undefined}
                    style={{
                      transitionDelay: open ? `${50 + i * 32}ms` : "0ms",
                    }}
                    className={`studio-mobile-link ${isActive ? "is-active" : ""}`}
                    onClick={() => setOpen(false)}
                  >
                    <span className="studio-mobile-link-index" aria-hidden>
                      {String(i + 1).padStart(2, "0")}
                    </span>
                    <span className="studio-mobile-link-label">{link.label}</span>
                  </SiteLink>
                );
              })}
            </div>

            <div
              className="studio-mobile-sheet-foot"
              style={{ transitionDelay: open ? "380ms" : "0ms" }}
            >
              <SiteLink
                href="/contact"
                className="studio-btn-primary w-full"
                onClick={() => setOpen(false)}
              >
                Start a project
              </SiteLink>
              <p className="mt-4 text-center text-[0.7rem] tracking-[0.14em] text-[var(--archi-ink-muted)] uppercase">
                Architecture · Design · Place
              </p>
            </div>
          </div>
        </nav>
      </div>
    </header>
  );
}
