"use client";

import { useEffect, useState } from "react";
import { Menu, X } from "lucide-react";
import { SidebarNav } from "@/components/layout/sidebar";
import { cn } from "@/lib/utils";

/**
 * Mobile-only slide-in navigation drawer. The hamburger trigger is visible
 * below `lg`; on `lg+` the static <Sidebar /> column handles navigation and
 * this component renders nothing meaningful (the trigger is hidden).
 *
 * The drawer is a simple fixed-position panel over a dimmed backdrop, driven
 * by local open state — no extra dependencies. Tapping a link, the backdrop,
 * or the X closes it.
 */
export function MobileNav({ allowed }: { allowed: string[] }) {
  const [open, setOpen] = useState(false);

  // Lock body scroll while the drawer is open.
  useEffect(() => {
    if (!open) return;
    const original = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    return () => {
      document.body.style.overflow = original;
    };
  }, [open]);

  // Close on Escape.
  useEffect(() => {
    if (!open) return;
    const onKey = (e: KeyboardEvent) => {
      if (e.key === "Escape") setOpen(false);
    };
    document.addEventListener("keydown", onKey);
    return () => document.removeEventListener("keydown", onKey);
  }, [open]);

  const close = () => setOpen(false);

  return (
    <>
      <button
        type="button"
        onClick={() => setOpen(true)}
        aria-label="Open navigation menu"
        aria-expanded={open}
        className="inline-flex size-9 items-center justify-center rounded-md text-foreground hover:bg-accent lg:hidden"
      >
        <Menu className="size-5" />
      </button>

      {/* Backdrop */}
      <div
        aria-hidden={!open}
        onClick={close}
        className={cn(
          "fixed inset-0 z-40 bg-black/50 transition-opacity lg:hidden",
          open ? "opacity-100" : "pointer-events-none opacity-0",
        )}
      />

      {/* Drawer */}
      <div
        role="dialog"
        aria-modal="true"
        aria-label="Navigation"
        className={cn(
          "fixed inset-y-0 left-0 z-50 flex w-64 max-w-[80%] flex-col bg-sidebar text-sidebar-foreground shadow-xl transition-transform duration-300 ease-in-out lg:hidden",
          open ? "translate-x-0" : "-translate-x-full",
        )}
      >
        <button
          type="button"
          onClick={close}
          aria-label="Close navigation menu"
          className="absolute right-3 top-4 z-10 inline-flex size-9 items-center justify-center rounded-md text-sidebar-foreground/80 hover:bg-sidebar-accent hover:text-sidebar-accent-foreground"
        >
          <X className="size-5" />
        </button>
        <SidebarNav allowed={allowed} onNavigate={close} />
      </div>
    </>
  );
}
