"use client";

import type { ReactNode } from "react";
import { useCallback, useEffect, useRef, useState } from "react";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { AnimatePresence, motion } from "motion/react";
import { Menu, X } from "lucide-react";
import { products } from "@/lib/site-config";

const topLinks = [
  { href: "/", label: "Home" },
  { href: "/about", label: "About" },
  { href: "/blog", label: "Blog" },
  { href: "/news", label: "News" },
  { href: "/studies", label: "Studies" },
  { href: "/contact", label: "Contact" },
];

export function MobileNav({ authSlot }: { authSlot?: ReactNode } = {}) {
  const [open, setOpen] = useState(false);
  const pathname = usePathname();
  const firstLinkRef = useRef<HTMLAnchorElement | null>(null);
  const closeButtonRef = useRef<HTMLButtonElement | null>(null);

  const close = useCallback(() => setOpen(false), []);

  // Close on route change
  useEffect(() => {
    setOpen(false);
  }, [pathname]);

  // Lock body scroll when open
  useEffect(() => {
    if (!open) return;
    const previous = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    return () => {
      document.body.style.overflow = previous;
    };
  }, [open]);

  // Close on Escape + focus trap on first link
  useEffect(() => {
    if (!open) return;
    const onKey = (e: KeyboardEvent) => {
      if (e.key === "Escape") {
        e.preventDefault();
        close();
        closeButtonRef.current?.focus();
      }
    };
    document.addEventListener("keydown", onKey);
    // Focus the first link when opened
    const t = window.setTimeout(() => {
      firstLinkRef.current?.focus();
    }, 50);
    return () => {
      document.removeEventListener("keydown", onKey);
      window.clearTimeout(t);
    };
  }, [open, close]);

  return (
    <div className="md:hidden">
      <button
        type="button"
        ref={closeButtonRef}
        aria-label={open ? "Close menu" : "Open menu"}
        aria-expanded={open}
        aria-controls="mobile-nav-drawer"
        onClick={() => setOpen((v) => !v)}
        className="inline-flex h-11 w-11 items-center justify-center rounded-md border border-[var(--color-line)] bg-white text-[var(--color-ink)] transition-colors hover:border-[var(--color-blue)] hover:text-[var(--color-blue)]"
      >
        <span className="sr-only">{open ? "Close menu" : "Open menu"}</span>
        {open ? (
          <X size={20} strokeWidth={1.75} aria-hidden="true" />
        ) : (
          <Menu size={20} strokeWidth={1.75} aria-hidden="true" />
        )}
      </button>

      <AnimatePresence>
        {open && (
          <>
            <motion.div
              key="backdrop"
              className="fixed inset-0 z-[60] bg-[rgba(11,18,32,0.45)] backdrop-blur-[2px]"
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              transition={{ duration: 0.2, ease: "easeOut" }}
              onClick={close}
              aria-hidden="true"
            />
            <motion.aside
              key="drawer"
              id="mobile-nav-drawer"
              role="dialog"
              aria-modal="true"
              aria-label="Site navigation"
              className="fixed right-0 top-0 z-[61] flex h-dvh w-[86%] max-w-sm flex-col overflow-y-auto border-l border-[var(--color-line)] bg-white shadow-2xl"
              initial={{ x: "100%" }}
              animate={{ x: 0 }}
              exit={{ x: "100%" }}
              transition={{ type: "tween", duration: 0.28, ease: [0.2, 0.8, 0.2, 1] }}
            >
              <div className="flex items-center justify-between border-b border-[var(--color-line)] px-6 py-5">
                <div className="font-display text-[18px] font-extrabold tracking-tight text-[var(--color-ink)]">
                  Menu
                </div>
                <button
                  type="button"
                  onClick={close}
                  className="inline-flex h-10 w-10 items-center justify-center rounded-md border border-[var(--color-line)] text-[var(--color-ink)] hover:border-[var(--color-blue)] hover:text-[var(--color-blue)]"
                  aria-label="Close menu"
                >
                  <X size={18} strokeWidth={1.75} aria-hidden="true" />
                </button>
              </div>

              <nav className="flex-1 px-2 py-4">
                <ul className="space-y-0.5">
                  {topLinks.map((link, i) => (
                    <li key={link.href}>
                      <Link
                        ref={i === 0 ? firstLinkRef : undefined}
                        href={link.href}
                        className="block rounded-md px-4 py-3 text-[15px] font-semibold text-[var(--color-ink)] hover:bg-[#f4f6fc] hover:text-[var(--color-blue)]"
                      >
                        {link.label}
                      </Link>
                    </li>
                  ))}
                </ul>

                <div className="mt-6 px-4">
                  <div className="mb-3 border-t border-[var(--color-line)] pt-5 text-[11px] font-bold uppercase tracking-wider text-[var(--color-slate)]">
                    Initiatives
                  </div>
                </div>
                <ul className="space-y-0.5">
                  {products.map((p) => (
                    <li key={p.slug}>
                      <Link
                        href={p.href}
                        className="block rounded-md px-4 py-3 hover:bg-[#f4f6fc]"
                      >
                        <div className="text-[14px] font-semibold text-[var(--color-ink)]">
                          {p.name}
                        </div>
                        <div className="mt-0.5 text-[12px] leading-snug text-[var(--color-slate)]">
                          {p.tagline}
                        </div>
                      </Link>
                    </li>
                  ))}
                </ul>
                {authSlot}
              </nav>
            </motion.aside>
          </>
        )}
      </AnimatePresence>
    </div>
  );
}
