"use client";

import { useEffect, useRef, useState } from "react";

import Link from "next/link";
import { usePathname } from "next/navigation";

import Image from "next/image";
import { ArrowRight, X } from "@phosphor-icons/react";

import { SITE } from "@/lib/site";

import { useLenis } from "@/components/LenisProvider";

const LINKS = [
  { href: "/solutions", label: "Solutions" },
  { href: "/products", label: "Products" },
  { href: "/projects", label: "Projects" },
  { href: "/about", label: "About" },
  { href: "/contact", label: "Contact" },
];

export default function Nav() {
  const pathname = usePathname();
  const { lenis } = useLenis();
  const [scrolled, setScrolled] = useState(false);
  const [open, setOpen] = useState(false);

  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 8);
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  // Body scroll lock + lenis stop while the overlay is open.
  useEffect(() => {
    if (!open) return;
    lenis?.stop();
    document.body.style.overflow = "hidden";
    return () => {
      lenis?.start();
      document.body.style.overflow = "";
    };
  }, [open, lenis]);

  // Close on Escape, on route change, and on any hash navigation.
  useEffect(() => {
    // eslint-disable-next-line react-hooks/set-state-in-effect -- sync overlay to route change
    setOpen(false);
  }, [pathname]);

  useEffect(() => {
    if (!open) return;
    const onKey = (e: KeyboardEvent) => {
      if (e.key === "Escape") setOpen(false);
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [open]);

  // Move focus into the overlay when it opens, back to the toggle when closed.
  const overlayFirstRef = useRef<HTMLAnchorElement | null>(null);
  const toggleRef = useRef<HTMLButtonElement | null>(null);
  const firstRun = useRef(true);
  useEffect(() => {
    if (firstRun.current) {
      firstRun.current = false;
      return;
    }
    if (open) overlayFirstRef.current?.focus();
    else toggleRef.current?.focus();
  }, [open]);

  const handleNavClick = () => {
    setOpen(false);
    lenis?.scrollTo(0, { immediate: true });
  };

  return (
    <>
      <header
        className={`fixed inset-x-0 top-0 z-50 transition-transform duration-300 ${
          open ? "-translate-y-full" : "translate-y-0"
        }`}
      >
        <nav
          aria-label="Primary"
          className={`border-b border-line backdrop-blur-md transition-all duration-300 ${
            scrolled
              ? "bg-white/95 shadow-[0_8px_30px_rgba(11,27,51,0.08)]"
              : "bg-white/90"
          }`}
        >
          <div className="container-gv flex h-16 items-center justify-between gap-8">
            <Link
              href="/"
              className="flex shrink-0 items-center gap-2.5"
              aria-label={`${SITE.shortName} - home`}
            >
              <Image
                src="/images/brand/gv-logo-horizontal.png"
                alt=""
                width={948}
                height={125}
                priority={false}
                className="h-8 w-auto shrink-0"
              />
            </Link>

            <div className="hidden items-center gap-7 md:flex">
              {LINKS.map((l) => (
                <Link
                  key={l.href}
                  href={l.href}
                  aria-current={pathname === l.href ? "page" : undefined}
                  className={`text-sm font-medium transition-colors hover:text-accent ${
                    pathname === l.href ? "text-ink" : "text-ink-soft"
                  }`}
                >
                  {l.label}
                </Link>
              ))}
            </div>

            <div className="flex items-center gap-3">
              <Link
                href="/contact"
                className="btn btn-primary btn-sm hidden! lg:inline-flex!"
              >
                Get in Touch
                <span className="btn-arrow" aria-hidden="true">
                  <ArrowRight className="ph" weight="bold" />
                </span>
              </Link>

              <button
                ref={toggleRef}
                type="button"
                className="flex h-10 w-10 items-center justify-center rounded-full border border-line text-ink transition-colors hover:bg-sky md:hidden"
                aria-expanded={open}
                aria-label={open ? "Close menu" : "Open menu"}
                onClick={() => setOpen((v) => !v)}
              >
                <span className="relative block h-3 w-4">
                  <span
                    className={`absolute left-0 top-0 h-[2px] w-full rounded-full bg-current transition-transform duration-300 ${
                      open ? "translate-y-[5px] rotate-45" : ""
                    }`}
                  />
                  <span
                    className={`absolute bottom-0 left-0 h-[2px] w-full rounded-full bg-current transition-transform duration-300 ${
                      open ? "-translate-y-[5px] -rotate-45" : ""
                    }`}
                  />
                </span>
              </button>
            </div>
          </div>
        </nav>
      </header>

      {/* Full-screen overlay menu */}
      <div
        inert={!open}
        className={`fixed inset-0 z-40 flex flex-col bg-white/95 backdrop-blur-xl transition-opacity duration-300 md:hidden ${
          open ? "opacity-100" : "pointer-events-none opacity-0"
        }`}
        aria-hidden={!open}
      >
        <div className="flex flex-1 flex-col justify-center gap-2 px-8 pt-20">
          {[{ href: "/", label: "Home" }, ...LINKS].map((l, i) => (
            <Link
              key={l.href}
              ref={i === 0 ? overlayFirstRef : undefined}
              href={l.href}
              className={`border-b border-line py-5 font-display text-3xl font-semibold tracking-tight text-ink transition-all duration-500 ${
                open ? "translate-y-0 opacity-100" : "translate-y-4 opacity-0"
              }`}
              style={{ transitionDelay: open ? `${i * 60}ms` : "0ms" }}
              onClick={handleNavClick}
            >
              {l.label}
            </Link>
          ))}
          <Link
            href="/contact"
            className="btn btn-primary mt-8 self-start"
            onClick={handleNavClick}
          >
            Get in Touch
            <span className="btn-arrow" aria-hidden="true">
              <ArrowRight className="ph" weight="bold" />
            </span>
          </Link>
        </div>
        <button
          type="button"
          className="absolute right-4 top-6 flex h-11 w-11 items-center justify-center rounded-full text-ink transition-colors hover:bg-sky"
          aria-label="Close menu"
          onClick={() => setOpen(false)}
        >
          <X size={22} weight="light" />
        </button>
      </div>
    </>
  );
}
