"use client";

import Link from "next/link";
import { usePathname } from "next/navigation";
import { useState, useRef, useEffect } from "react";
import ThemeToggle from "./ThemeToggle";

// CUSTOMIZATION HOOK — MOTION: 스마트 스티키 튜닝
const SCROLL_DELTA  = 6;    // px — 방향 전환 인식 최소 이동량(지터 방지)
const HIDE_AFTER    = 140;  // px — 이 지점 이전에는 숨기지 않음(실측 데스크톱 헤더 높이 122.8px + 여유)
const NAV_SETTLE_MS = 300;  // ms — 라우트 전환 직후 방향 판정 유예 구간

// CUSTOMIZATION HOOK: edit nav labels / routes here.
const navItems = [
  { href: "/", en: "Home", no: "01" },
  { href: "/members", en: "Members", no: "02" },
  { href: "/publications", en: "Publications", no: "03" },
  { href: "/lectures", en: "Lectures", no: "04" },
  { href: "/standardization", en: "Standardization", no: "05" },
];

export default function Header() {
  const [open, setOpen] = useState(false);
  const [hidden, setHidden] = useState(false);
  const pathname = usePathname();

  const lastY       = useRef(0);
  const ticking     = useRef(false);
  const navSettling = useRef(false);
  const openRef     = useRef(open);
  openRef.current   = open;

  useEffect(() => {
    // (A) 모션 줄임 사용자는 자동 숨김 자체를 비활성화 — DESIGN.md 접근성 원칙
    if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) return;

    lastY.current = window.scrollY;

    const update = () => {
      ticking.current = false;
      const y = window.scrollY;

      // (B) 최상단 + iOS 러버밴드(음수) 구간 → 항상 표시
      if (y <= 0) {
        setHidden(false);
        lastY.current = 0;
        return;
      }

      // (F-2) 라우트 전환 정착 구간: 전환이 유발한 스크롤 점프는 방향 판정에서 제외.
      //       기준점만 따라가고 hidden은 건드리지 않는다.
      if (navSettling.current) {
        lastY.current = y;
        return;
      }

      // (C) 모바일 메뉴가 열려 있으면 숨기지 않되, lastY는 계속 추적
      //     (추적하지 않으면 메뉴를 닫는 순간 헤더가 튀며 사라짐)
      if (openRef.current) {
        setHidden(false);
        lastY.current = y;
        return;
      }

      const delta = y - lastY.current;

      // (D) 미세 이동 무시. 이때 lastY를 갱신하지 않고 보존
      if (Math.abs(delta) < SCROLL_DELTA) return;

      if (delta > 0 && y > HIDE_AFTER) {
        setHidden(true); // 아래로 → 숨김
      } else if (delta < 0) {
        setHidden(false); // 위로 → 복귀
      }

      lastY.current = y;
    };

    const onScroll = () => {
      if (ticking.current) return;
      ticking.current = true;
      requestAnimationFrame(update); // 프레임당 1회로 제한
    };

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

  // (F) 라우트 전환 대응 — persistent layout이라 hidden이 페이지를 넘어 생존한다.
  //     스크롤 이벤트 발화 여부와 무관하게 표시 상태를 보장한다.
  useEffect(() => {
    setHidden(false);
    lastY.current = window.scrollY; // 현재 실제 위치로 동기화
    setOpen(false); // 뒤로/앞으로 이동 시 모바일 메뉴 잔존 방지
    navSettling.current = true;
    const id = window.setTimeout(() => {
      navSettling.current = false;
    }, NAV_SETTLE_MS);
    return () => window.clearTimeout(id);
  }, [pathname]);

  const isActive = (href: string) =>
    pathname
      ? href === "/"
        ? pathname === "/"
        : pathname === href || pathname.startsWith(`${href}/`)
      : false;

  return (
    <header
      data-smart-sticky
      onFocusCapture={() => setHidden(false)}
      className={`flow-root sticky top-0 z-50 border-b border-ink bg-ivory/85 backdrop-blur transition-transform duration-300 ease-out ${
        hidden ? "-translate-y-full" : "translate-y-0"
      }`}
    >
      {/* Journal issue strip — magazine masthead feel. */}
      <div className="hidden border-b border-line desktop:block">
        <div className="container-content flex items-center justify-between py-1.5">
          <span className="kicker">KNU/CSE/ANL</span>
          {/* CUSTOMIZATION HOOK: masthead tagline */}
          <span className="kicker text-ink-mute">
            Kyungpook National University · School of Computer Science &amp; Engineering
          </span>
          <span className="kicker">Daegu / South Korea</span>
        </div>
      </div>

      <div className="container-content flex h-[4.25rem] items-center justify-between gap-4 my-2 sm:my-3">
        {/* Brand logo */}
        <Link
          href="/"
          className="group flex items-center gap-3 shrink-0"
          onClick={() => setOpen(false)}
        >
          <div className="relative flex items-center justify-center w-9 h-9 sm:w-10 sm:h-10 rounded-xl overflow-hidden shadow-sm ring-1 ring-ink/10 group-hover:ring-cobalt/40 group-hover:shadow-md group-hover:scale-105 transition-all duration-300 shrink-0">
            <svg viewBox="0 0 32 32" className="w-full h-full" aria-hidden="true">
              <defs>
                <linearGradient id="headerLogoGrad" x1="0%" y1="0%" x2="100%" y2="100%">
                  <stop offset="0%" stopColor="#4E77FF"/>
                  <stop offset="100%" stopColor="#2B4CDE"/>
                </linearGradient>
                <radialGradient id="nodeGlow" cx="50%" cy="50%" r="50%">
                  <stop offset="0%" stopColor="#FFD666" stopOpacity="1"/>
                  <stop offset="100%" stopColor="#FF9C1A" stopOpacity="0.8"/>
                </radialGradient>
              </defs>
              <rect width="32" height="32" rx="7" fill="url(#headerLogoGrad)"/>
              {/* Network Graph Edges */}
              <path d="M16 9 L9 22 M16 9 L23 22 M9 22 L23 22 M16 9 L16 17 M9 22 L16 17 M23 22 L16 17" 
                    stroke="#FFFFFF" strokeWidth="1.2" strokeOpacity="0.85" strokeLinecap="round"/>
              {/* Network Agent Outer Nodes */}
              <circle cx="16" cy="9" r="2.5" fill="#FFFFFF"/>
              <circle cx="9" cy="22" r="2.5" fill="#FFFFFF"/>
              <circle cx="23" cy="22" r="2.5" fill="#FFFFFF"/>
              {/* Central Coordinating Hub Node */}
              <circle cx="16" cy="17" r="2.2" fill="url(#nodeGlow)" className="animate-pulse"/>
            </svg>
          </div>

          <div className="flex flex-col leading-none">
            <span className="headline-ko text-lg text-ink sm:text-xl font-bold tracking-tight group-hover:text-cobalt-dark transition-colors">
              ANL
            </span>
            <span className="kicker mt-1 transition-colors group-hover:text-cobalt-dark">
              AI Agent Networking LAB
            </span>
          </div>
        </Link>

        {/* Desktop nav — small caps, wide tracking (visible at >= 1240px) */}
        <div className="hidden items-center gap-4 desktop:flex">
          <nav className="flex items-center gap-2" aria-label="Main Navigation">
            {navItems.map((item) => {
              const active = isActive(item.href);
              return (
                <Link
                  key={item.href}
                  href={item.href}
                  aria-current={active ? "page" : undefined}
                  className={`group relative flex items-baseline gap-1.5 text-[0.78rem] font-semibold uppercase tracking-[0.18em] transition-all px-3 py-1.5 rounded-md ${
                    active
                      ? "bg-cobalt-dark text-white dark:text-ivory shadow-sm font-bold"
                      : "text-ink hover:text-cobalt-dark hover:bg-paper/60"
                  }`}
                >
                  <span
                    className={`font-display text-[0.62rem] ${
                      active ? "text-white dark:text-ivory" : "text-ink-mute"
                    }`}
                  >
                    {item.no}
                  </span>
                  <span>{item.en}</span>
                </Link>
              );
            })}
          </nav>
          <div className="h-4 w-px bg-line" aria-hidden="true" />
          <ThemeToggle />
        </div>

        {/* Mobile controls (visible under 1240px) */}
        <div className="flex items-center gap-2 desktop:hidden">
          <ThemeToggle />
          <button
            type="button"
            className="inline-flex items-center justify-center border border-ink p-2 text-ink transition hover:bg-ink hover:text-ivory"
            aria-label={open ? "Close menu" : "Open menu"}
            aria-expanded={open}
            aria-controls="mobile-menu"
            onClick={() => setOpen((v) => !v)}
          >
            <svg className="h-5 w-5" fill="none" viewBox="0 0 24 24" strokeWidth={1.8} stroke="currentColor">
              {open ? (
                <path strokeLinecap="round" strokeLinejoin="round" d="M6 18 18 6M6 6l12 12" />
              ) : (
                <path strokeLinecap="round" strokeLinejoin="round" d="M3.75 6.75h16.5M3.75 12h16.5M3.75 17.25h16.5" />
              )}
            </svg>
          </button>
        </div>
      </div>

      {/* Mobile menu panel */}
      {open && (
        <nav
          id="mobile-menu"
          className="mobile-menu-panel border-t border-ink bg-ivory desktop:hidden"
          aria-label="Mobile Navigation"
        >
          <ul className="container-content flex flex-col py-2">
            {navItems.map((item) => {
              const active = isActive(item.href);
              return (
                <li key={item.href}>
                  <Link
                    href={item.href}
                    onClick={() => setOpen(false)}
                    aria-current={active ? "page" : undefined}
                    className={`flex items-baseline justify-between px-4 py-3.5 transition-colors rounded-md my-1 ${
                      active
                        ? "bg-cobalt-dark text-white dark:text-ivory font-bold shadow-sm"
                        : "text-ink hover:bg-paper/60"
                    }`}
                  >
                    <span className="flex items-baseline gap-3">
                      <span
                        className={`font-display text-xs ${
                          active ? "text-white dark:text-ivory" : "text-ink-mute"
                        }`}
                      >
                        {item.no}
                      </span>
                      <span className="font-sans text-base">{item.en}</span>
                    </span>
                    <span
                      aria-hidden="true"
                      className={`text-xs font-mono ${
                        active ? "text-white/80 dark:text-ivory/80" : "text-ink-mute"
                      }`}
                    >
                      →
                    </span>
                  </Link>
                </li>
              );
            })}
          </ul>
        </nav>
      )}
    </header>
  );
}
