"use client";

import { useEffect, useRef, useState } from "react";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { AnimatePresence, motion, useMotionValueEvent, useReducedMotion, useScroll } from "motion/react";
import Icon from "@/components/ui/Icon";
import { accountLinks, navItems, type NavItem } from "@/data/navigation";
import { useAuth } from "@/store/auth";

const ease = [0.2, 0.7, 0.2, 1] as const;
const cine = [0.77, 0, 0.175, 1] as const;

/** Home intro delay so the navbar lands after the hero media reveal. */
const HOME_INTRO_DELAY = 0.9;

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

/**
 * Transparent over the home hero, solid cream everywhere else (and on home once the
 * content sheet reaches it). Items with columns open a mega panel; on touch they live
 * in the full-screen menu as accordions.
 */
export default function Navbar() {
  const reduce = useReducedMotion();
  const pathname = usePathname();
  const isHome = pathname === "/";
  const user = useAuth((s) => s.user);
  const initAuth = useAuth((s) => s.init);
  // The navbar is on every page, so it restores the session once per visit.
  useEffect(() => {
    void initAuth();
  }, [initAuth]);
  const account = user ? { label: user.first_name || user.name.split(" ")[0], href: "/account" } : accountLinks.login;
  const { scrollY } = useScroll();
  const [scrolled, setScrolled] = useState(false);
  const [menu, setMenu] = useState(false);
  const [panel, setPanel] = useState<string | null>(null);
  const [accordion, setAccordion] = useState<string | null>(null);
  const headerRef = useRef<HTMLElement>(null);

  useMotionValueEvent(scrollY, "change", (y) => setScrolled(y > window.innerHeight - 110));

  const solid = !isHome || scrolled || panel !== null;
  const activeItem = navItems.find((n) => n.label === panel);

  // Close everything after navigating.
  useEffect(() => {
    setPanel(null);
    setMenu(false);
  }, [pathname]);

  useEffect(() => {
    document.documentElement.style.overflow = menu ? "hidden" : "";
    return () => {
      document.documentElement.style.overflow = "";
    };
  }, [menu]);

  useEffect(() => {
    if (!panel) return;
    const onKey = (e: KeyboardEvent) => {
      if (e.key !== "Escape") return;
      setPanel(null);
      headerRef.current?.querySelector<HTMLElement>("[aria-expanded=true]")?.focus();
    };
    document.addEventListener("keydown", onKey);
    return () => document.removeEventListener("keydown", onKey);
  }, [panel]);

  const dur = reduce ? 0 : 0.22;

  return (
    <>
      <motion.header
        ref={headerRef}
        className="nav"
        data-solid={solid}
        data-menu={menu}
        data-panel={panel !== null}
        initial={reduce || !isHome ? false : { opacity: 0, y: -24 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.8, delay: isHome ? HOME_INTRO_DELAY : 0, ease }}
        onPointerLeave={(e) => e.pointerType === "mouse" && setPanel(null)}
        onBlur={(e) => {
          if (!e.currentTarget.contains(e.relatedTarget)) setPanel(null);
        }}
      >
        <div className="wrap nav-inner">
          <Link className="brand" href="/" aria-label="Syria, home">
            <span className="brand-en">Syria</span>
            <span className="brand-ar" lang="ar">سوريا</span>
          </Link>

          <nav className="nav-links" aria-label="Primary">
            {navItems.map((n) =>
              n.columns ? (
                <button
                  key={n.label}
                  type="button"
                  className="nav-trigger"
                  aria-expanded={panel === n.label}
                  aria-controls="mega-panel"
                  data-current={isActive(pathname, n.href)}
                  onClick={() => setPanel((p) => (p === n.label ? null : n.label))}
                  onPointerEnter={(e) => e.pointerType === "mouse" && setPanel(n.label)}
                >
                  {n.label}
                  <Icon name="expand_more" />
                </button>
              ) : (
                <Link
                  key={n.label}
                  href={n.href}
                  aria-current={isActive(pathname, n.href) ? "page" : undefined}
                  onPointerEnter={(e) => e.pointerType === "mouse" && setPanel(null)}
                >
                  {n.label}
                </Link>
              ),
            )}
          </nav>

          <div className="nav-actions">
            <button type="button" className="nav-icon-btn" aria-label="Search"><Icon name="search" /></button>
            <Link className="nav-icon-btn" href={accountLinks.favourites.href} aria-label="Favourites">
              <Icon name="favorite" />
            </Link>
            <button type="button" className="nav-lang" lang="ar"><Icon name="language" />العربية</button>
            <Link className="btn btn-plum btn-sm" href={account.href}>
              <Icon name="person" />
              {account.label}
            </Link>
            <button
              type="button"
              className="nav-icon-btn nav-burger"
              aria-label={menu ? "Close menu" : "Open menu"}
              aria-expanded={menu}
              onClick={() => setMenu((o) => !o)}
            >
              <Icon name={menu ? "close" : "menu"} />
            </button>
          </div>
        </div>

        <AnimatePresence>
          {activeItem?.columns && (
            <motion.div
              key={activeItem.label}
              id="mega-panel"
              className="mega"
              initial={{ opacity: 0, y: -8 }}
              animate={{ opacity: 1, y: 0, transition: { duration: dur, ease } }}
              exit={{ opacity: 0, transition: { duration: dur / 2 } }}
            >
              <MegaPanel item={activeItem} pathname={pathname} />
            </motion.div>
          )}
        </AnimatePresence>
      </motion.header>

      <AnimatePresence>
        {menu && (
          <motion.div
            className="sheet-menu"
            data-lenis-prevent
            initial={{ clipPath: "inset(0 0 100% 0)" }}
            animate={{ clipPath: "inset(0 0 0% 0)" }}
            exit={{ clipPath: "inset(0 0 100% 0)", transition: { duration: 0.3, ease: cine } }}
            transition={{ duration: 0.5, ease: cine }}
          >
            <nav aria-label="Mobile">
              {navItems.map((n, i) => (
                <motion.div
                  key={n.label}
                  className="sheet-item"
                  initial={{ opacity: 0, y: 20 }}
                  animate={{ opacity: 1, y: 0, transition: { delay: 0.18 + i * 0.05, duration: 0.5, ease } }}
                >
                  {n.columns ? (
                    <>
                      <button
                        type="button"
                        className="sheet-row"
                        aria-expanded={accordion === n.label}
                        onClick={() => setAccordion((a) => (a === n.label ? null : n.label))}
                      >
                        {n.label}
                        <Icon name="expand_more" className="sheet-chevron" />
                      </button>
                      <div className="sheet-sub" data-open={accordion === n.label}>
                        <div>
                          {n.columns.map((c, ci) => (
                            <div key={c.title ?? ci} className="sheet-col">
                              {c.title &&
                                (c.href ? (
                                  <Link className="sheet-col-title" href={c.href} tabIndex={accordion === n.label ? 0 : -1}>
                                    {c.title}
                                  </Link>
                                ) : (
                                  <span className="sheet-col-title">{c.title}</span>
                                ))}
                              {c.links.map((l) => (
                                <Link key={l.href} href={l.href} tabIndex={accordion === n.label ? 0 : -1}>
                                  {l.label}
                                </Link>
                              ))}
                            </div>
                          ))}
                        </div>
                      </div>
                    </>
                  ) : (
                    <Link className="sheet-row" href={n.href}>
                      {n.label}
                      <Icon name="arrow_forward" />
                    </Link>
                  )}
                </motion.div>
              ))}
            </nav>
            <div className="sheet-foot">
              <Link className="btn btn-rose" href={account.href}>
                <Icon name="person" />
                {account.label}
              </Link>
              <Link className="btn btn-ghost-light" href={accountLinks.favourites.href}>
                <Icon name="favorite" />
                {accountLinks.favourites.label}
              </Link>
              <button type="button" className="btn btn-ghost-light" lang="ar"><Icon name="language" />العربية</button>
            </div>
          </motion.div>
        )}
      </AnimatePresence>
    </>
  );
}

function MegaPanel({ item, pathname }: { item: NavItem; pathname: string }) {
  return (
    <div className="wrap mega-inner">
      <Link className="mega-lead" href={item.href}>
        <span>{item.label}</span>
        <span className="mega-lead-go">
          Overview <Icon name="arrow_forward" />
        </span>
      </Link>
      <div className="mega-cols">
        {item.columns!.map((c, i) => (
          <div key={c.title ?? i} className="mega-col">
            {c.title &&
              (c.href ? (
                <Link className="mega-title" href={c.href}>{c.title}</Link>
              ) : (
                <span className="mega-title">{c.title}</span>
              ))}
            <ul>
              {c.links.map((l) => (
                <li key={l.href}>
                  <Link href={l.href} aria-current={isActive(pathname, l.href) ? "page" : undefined}>
                    {l.label}
                    <Icon name="arrow_forward" />
                  </Link>
                </li>
              ))}
            </ul>
          </div>
        ))}
      </div>
    </div>
  );
}
