"use client";

import Link from "next/link";
import { usePathname } from "next/navigation";
import { useEffect, useRef, useState } from "react";
import { AnimatePresence, motion, useReducedMotion } from "framer-motion";
import BrandMark from "./BrandMark";

const LINKS = [
  { href: "/services", label: "Services" },
  { href: "/work", label: "Work" },
  { href: "/products", label: "Products" },
  { href: "/hosting", label: "Hosting" },
  { href: "/shop", label: "Shop" },
  { href: "/about", label: "About" },
  { href: "/contact", label: "Contact" },
];

export default function Nav() {
  const pathname = usePathname();
  const [scrolled, setScrolled] = useState(false);
  const [hidden, setHidden] = useState(false);
  const [open, setOpen] = useState(false);
  const lastY = useRef(0);
  const panelRef = useRef<HTMLDivElement>(null);
  const toggleRef = useRef<HTMLButtonElement>(null);
  const reduced = useReducedMotion();

  useEffect(() => {
    const onScroll = () => {
      const y = window.scrollY;
      setScrolled(y > 40);
      setHidden(y > 320 && y > lastY.current && !open);
      lastY.current = y;
    };
    window.addEventListener("scroll", onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener("scroll", onScroll);
  }, [open]);

  // close menu on route change
  useEffect(() => setOpen(false), [pathname]);

  // close menu when crossing the desktop breakpoint
  useEffect(() => {
    const mq = window.matchMedia("(min-width: 1024px)");
    const onChange = () => mq.matches && setOpen(false);
    mq.addEventListener("change", onChange);
    return () => mq.removeEventListener("change", onChange);
  }, []);

  // scroll lock + Escape + focus containment while menu is open
  useEffect(() => {
    if (!open) return;
    const scrollY = window.scrollY;
    const { style } = document.body;
    style.position = "fixed";
    style.top = `-${scrollY}px`;
    style.width = "100%";

    const panel = panelRef.current;
    const focusables = () =>
      Array.from(
        panel?.querySelectorAll<HTMLElement>("a, button, [tabindex]:not([tabindex='-1'])") ?? []
      );
    focusables()[0]?.focus();

    const onKey = (e: KeyboardEvent) => {
      if (e.key === "Escape") {
        setOpen(false);
        toggleRef.current?.focus();
      }
      if (e.key === "Tab") {
        const f = focusables();
        if (!f.length) return;
        const first = f[0];
        const last = f[f.length - 1];
        const active = document.activeElement as HTMLElement;
        if (!panel?.contains(active)) {
          e.preventDefault();
          first.focus();
        } else if (e.shiftKey && active === first) {
          e.preventDefault();
          last.focus();
        } else if (!e.shiftKey && active === last) {
          e.preventDefault();
          first.focus();
        }
      }
    };
    document.addEventListener("keydown", onKey);
    return () => {
      document.removeEventListener("keydown", onKey);
      style.position = "";
      style.top = "";
      style.width = "";
      window.scrollTo({ top: scrollY, behavior: "instant" as ScrollBehavior });
    };
  }, [open]);

  return (
    <>
      <a
        href="#main"
        className="fixed -top-24 left-4 z-[300] rounded-md bg-azure px-4 py-2.5 font-semibold text-[#04122B] transition-[top] focus:top-4"
      >
        Skip to content
      </a>

      <header
        className={`fixed inset-x-0 top-0 z-[200] border-b transition-all duration-500 ${
          scrolled
            ? "border-white/10 bg-ink/85 backdrop-blur-xl"
            : "border-transparent bg-transparent"
        } ${hidden ? "-translate-y-full" : "translate-y-0"}`}
      >
        <div className="mx-auto flex h-[76px] w-full max-w-[1280px] items-center justify-between gap-8 px-5 md:px-10">
          <Link href="/" aria-label="Vira.sa Technology — home" className="flex items-center gap-2.5 text-thi">
            <BrandMark className="h-[34px] w-[34px]" />
            <span className="flex flex-col leading-none">
              <span className="font-[family-name:var(--font-display)] text-[1.45rem] font-bold tracking-tight">
                Vira<span className="font-medium text-azure-bright">.sa</span>
              </span>
              <span className="mt-[3px] font-[family-name:var(--font-mono)] text-[0.52rem] font-medium uppercase tracking-[0.4em] text-tmid">
                Technology
              </span>
            </span>
          </Link>

          <nav aria-label="Primary" className="hidden items-center gap-7 lg:flex">
            {LINKS.map((l) => {
              const active = pathname === l.href || pathname.startsWith(l.href + "/");
              return (
                <Link
                  key={l.href}
                  href={l.href}
                  aria-current={active ? "page" : undefined}
                  className={`group relative py-1.5 text-[0.95rem] font-medium transition-colors ${
                    active ? "text-thi" : "text-tmid hover:text-thi"
                  }`}
                >
                  {l.label}
                  <span
                    className={`absolute bottom-0 left-0 h-[1.5px] w-full origin-right scale-x-0 bg-ice transition-transform duration-400 ease-[cubic-bezier(0.55,0,0.1,1)] group-hover:origin-left group-hover:scale-x-100 ${
                      active ? "origin-left scale-x-100" : ""
                    }`}
                    aria-hidden
                  />
                </Link>
              );
            })}
            <Link href="/login" className="btn btn-ghost-dark btn-sm">
              Client login
            </Link>
            <Link href="/contact" className="btn btn-primary btn-sm">
              Start a project <span className="arrow" aria-hidden>→</span>
            </Link>
          </nav>

          <button
            ref={toggleRef}
            className="relative z-[260] flex h-11 w-11 flex-col items-center justify-center gap-[6px] lg:hidden"
            aria-expanded={open}
            aria-controls="mobile-menu"
            aria-label={open ? "Close menu" : "Open menu"}
            onClick={() => setOpen(!open)}
          >
            <span
              className={`h-0.5 w-6 bg-thi transition-transform duration-300 ${open ? "translate-y-[8px] rotate-45" : ""}`}
            />
            <span className={`h-0.5 w-6 bg-thi transition-opacity duration-200 ${open ? "opacity-0" : ""}`} />
            <span
              className={`h-0.5 w-6 bg-thi transition-transform duration-300 ${open ? "-translate-y-[8px] -rotate-45" : ""}`}
            />
          </button>
        </div>
      </header>

      <AnimatePresence>
        {open && (
          <motion.div
            id="mobile-menu"
            ref={panelRef}
            role="dialog"
            aria-modal="true"
            aria-label="Menu"
            className="weave-dark fixed inset-0 z-[250] flex flex-col justify-center px-6 lg:hidden"
            initial={reduced ? { opacity: 1 } : { opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            transition={{ duration: 0.35 }}
          >
            <nav aria-label="Mobile" className="flex flex-col">
              {[...LINKS, { href: "/login", label: "Client login" }].map((l, i) => (
                <motion.div
                  key={l.href}
                  initial={reduced ? undefined : { opacity: 0, y: 22 }}
                  animate={{ opacity: 1, y: 0 }}
                  transition={{ delay: 0.08 + i * 0.055, duration: 0.45, ease: [0.22, 1, 0.36, 1] }}
                >
                  <Link
                    href={l.href}
                    className="flex items-baseline gap-4 py-2.5 font-[family-name:var(--font-display)] text-4xl font-semibold text-thi transition-colors hover:text-ice"
                  >
                    <span className="font-[family-name:var(--font-mono)] text-sm font-normal text-azure">
                      {String(i + 1).padStart(2, "0")}
                    </span>
                    {l.label}
                  </Link>
                </motion.div>
              ))}
            </nav>
            <motion.p
              className="mt-10 text-sm text-tlo"
              initial={reduced ? undefined : { opacity: 0 }}
              animate={{ opacity: 1 }}
              transition={{ delay: 0.5 }}
            >
              hello@vira.sa · Makkah · Jeddah · Riyadh · Dammam
              <br />
              <span className="ar text-ice" lang="ar">
                فيرا لتقنية المعلومات
              </span>
            </motion.p>
          </motion.div>
        )}
      </AnimatePresence>
    </>
  );
}
