"use client";

import Link from "next/link";
import { useEffect } from "react";
import { createPortal } from "react-dom";
import { AnimatePresence, motion } from "framer-motion";
import { X } from "lucide-react";
import { siloDepartments } from "@/data/silo-catalog";
import { cn } from "@/lib/cn";
import { SiloWordmark } from "@/components/silo/SiloMark";

type MobileNavDrawerProps = {
  open: boolean;
  brand: string;
  logoUrl?: string;
  onClose: () => void;
};

const linkClass =
  "rounded-xl px-3 py-3 text-[15px] font-medium text-foreground transition active:bg-card hover:bg-card";

/** Mobile nav drawer — portaled to body so sticky/blur header cannot clip it. */
export function MobileNavDrawer({
  open,
  onClose,
}: MobileNavDrawerProps) {
  useEffect(() => {
    if (!open) return;
    const prevOverflow = document.body.style.overflow;
    const prevTouch = document.body.style.touchAction;
    document.body.style.overflow = "hidden";
    document.body.style.touchAction = "none";
    const onKey = (event: KeyboardEvent) => {
      if (event.key === "Escape") onClose();
    };
    window.addEventListener("keydown", onKey);
    return () => {
      document.body.style.overflow = prevOverflow;
      document.body.style.touchAction = prevTouch;
      window.removeEventListener("keydown", onKey);
    };
  }, [open, onClose]);

  if (typeof document === "undefined") return null;

  return createPortal(
    <AnimatePresence>
      {open ? (
        <motion.div
          key="mobile-nav"
          className="fixed inset-0 z-[90] lg:hidden"
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          exit={{ opacity: 0 }}
          transition={{ duration: 0.18, ease: "easeOut" }}
        >
          <button
            type="button"
            aria-label="Close menu"
            className="absolute inset-0 bg-black/50"
            onClick={onClose}
          />

          <motion.aside
            id="mobile-nav-drawer"
            role="dialog"
            aria-modal="true"
            aria-label="Product categories"
            initial={{ x: "-105%" }}
            animate={{ x: 0 }}
            exit={{ x: "-105%" }}
            transition={{ type: "spring", stiffness: 420, damping: 38, mass: 0.85 }}
            className={cn(
              "absolute left-0 top-0 flex h-[100dvh] max-h-[100dvh] w-[min(20rem,86vw)] flex-col",
              "bg-background text-foreground shadow-[8px_0_40px_rgba(0,0,0,0.28)]",
              "pt-[env(safe-area-inset-top)] pb-[env(safe-area-inset-bottom)]",
            )}
            onClick={(event) => event.stopPropagation()}
          >
            <div className="flex shrink-0 items-center justify-between border-b border-border px-4 py-3.5">
              <SiloWordmark />
              <button
                type="button"
                onClick={onClose}
                className="btn-bin btn-bin-outline btn-bin-icon"
                aria-label="Close"
              >
                <X className="h-4 w-4" />
              </button>
            </div>

            <nav className="flex min-h-0 flex-1 flex-col gap-0.5 overflow-y-auto overscroll-contain px-3 py-3 [-webkit-overflow-scrolling:touch]">
              <p className="px-3 pb-1 pt-1 text-[11px] font-bold uppercase tracking-[0.16em] text-[var(--straw)]">
                Categories
              </p>
              {siloDepartments.map((category) => (
                <Link
                  key={category.slug}
                  href={`/categories/${category.slug}`}
                  onClick={onClose}
                  className={linkClass}
                >
                  {category.name}
                </Link>
              ))}
              <div className="my-2 border-t border-border" />
              <Link href="/shop" onClick={onClose} className={linkClass}>
                Shop the crib
              </Link>
              <Link href="/weekly" onClick={onClose} className={linkClass}>
                Weekly Crib
              </Link>
              <Link href="/drops" onClick={onClose} className={linkClass}>
                Bin Cuts
              </Link>
              <Link href="/finds" onClick={onClose} className={linkClass}>
                Silo Drops
              </Link>
              <Link href="/diet" onClick={onClose} className={linkClass}>
                Shop by Plate
              </Link>
              <Link href="/recipes" onClick={onClose} className={linkClass}>
                Recipes
              </Link>
              <div className="my-2 border-t border-border" />
              <Link href="/about" onClick={onClose} className={linkClass}>
                About
              </Link>
              <Link href="/contact" onClick={onClose} className={linkClass}>
                Help
              </Link>
              <Link href="/login" onClick={onClose} className={linkClass}>
                Sign in
              </Link>
            </nav>
          </motion.aside>
        </motion.div>
      ) : null}
    </AnimatePresence>,
    document.body,
  );
}
