"use client";

/**
 * Landing-page header menu for narrow viewports.
 *
 * Below the tablet breakpoint the header bar has room for the brand, the theme
 * toggle and one more control, so everything else — the section links, the
 * language picker and the sign-in / account slot — moves in here.
 *
 * The account slot arrives as `children` rather than being rebuilt, so there is
 * exactly one definition of what the header shows a signed-in visitor.
 *
 * The panel stays mounted and is hidden with the `hidden` attribute instead of
 * being unmounted, so Clerk and Convex inside it are not torn down and re-run
 * every time the menu is opened.
 */

import { useEffect, useState } from "react";
import { MenuIcon, XIcon } from "lucide-react";

export function MobileMenu({
  labels,
  navItems,
  styles,
  children,
}: {
  labels: { open: string; close: string };
  navItems: { href: string; label: string }[];
  styles: Record<string, string>;
  children: React.ReactNode;
}) {
  const [open, setOpen] = useState(false);

  useEffect(() => {
    if (!open) return;

    // The panel covers the viewport; letting the page scroll behind it is the
    // classic mobile-menu bug where the reader loses their place on close.
    const previous = document.body.style.overflow;
    document.body.style.overflow = "hidden";

    const onKeyDown = (e: KeyboardEvent) => {
      if (e.key === "Escape") setOpen(false);
    };
    window.addEventListener("keydown", onKeyDown);

    return () => {
      document.body.style.overflow = previous;
      window.removeEventListener("keydown", onKeyDown);
    };
  }, [open]);

  // Anything the visitor clicks in here either jumps to a section or leaves the
  // page, and in both cases the panel should get out of the way. Caught on the
  // container so the language picker and the account chip need no wiring.
  const closeOnActivate = (e: React.MouseEvent) => {
    if ((e.target as HTMLElement).closest("a")) setOpen(false);
  };

  return (
    <>
      <button
        type="button"
        className={styles.menuButton}
        aria-expanded={open}
        aria-controls="landing-mobile-menu"
        aria-label={open ? labels.close : labels.open}
        onClick={() => setOpen((v) => !v)}
      >
        {open ? <XIcon size={20} /> : <MenuIcon size={20} />}
      </button>

      <div
        className={styles.menuScrim}
        hidden={!open}
        onClick={() => setOpen(false)}
        aria-hidden
      />

      <div
        id="landing-mobile-menu"
        className={styles.menuPanel}
        hidden={!open}
        onClick={closeOnActivate}
      >
        <nav className={styles.menuNav}>
          {navItems.map((item) => (
            <a key={item.href} href={item.href} className={styles.menuLink}>
              {item.label}
            </a>
          ))}
        </nav>
        <div className={styles.menuActions}>{children}</div>
      </div>
    </>
  );
}
