import { useEffect, useRef, useState } from "preact/hooks";

/**
 * @typedef {{ name: string; href: string }} MenuLink
 * @param {{ links: MenuLink[] }} props
 */
export default function MobileMenu({ links = [] }) {
  const [open, setOpen] = useState(false);
  const menuRef = useRef(null);
  const btnRef = useRef(null);

  const close = () => setOpen(false);
  const toggle = (e) => {
    e?.stopPropagation?.(); 
    setOpen((o) => !o);
  };

  useEffect(() => {
    const onKey = (e) => e.key === "Escape" && close();
    document.addEventListener("keydown", onKey);
    return () => document.removeEventListener("keydown", onKey);
  }, []);

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

    const onDocClick = (e) => {
      const menuEl = menuRef.current;
      const btnEl = btnRef.current;

      if (menuEl && menuEl.contains(e.target)) return;
      if (btnEl && btnEl.contains(e.target)) return;

      close();
    };

    document.addEventListener("mousedown", onDocClick);
    document.addEventListener("touchstart", onDocClick, { passive: true });

    return () => {
      document.removeEventListener("mousedown", onDocClick);
      document.removeEventListener("touchstart", onDocClick);
    };
  }, [open]);

  return (
    <>
      <button
        ref={btnRef}
        onClick={toggle}
        class="f-mobile-toggle md:hidden"
        aria-label="Menu mobilne"
        aria-expanded={open}
        aria-controls="mobile-menu"
      >
        {open ? "✖" : "☰"}
      </button>

      <div
        class={`f-mobile-backdrop ${open ? "open" : ""}`}
        onClick={close}
        aria-hidden="true"
      />

      <div
        id="mobile-menu"
        ref={menuRef}
        class={`f-mobile-menu ${open ? "open" : ""}`}
        onClick={(e) => e.stopPropagation()}
      >
        {links.map((link) => (
          <a href={link.href} class="f-mobile-link" onClick={close}>
            {link.name}
          </a>
        ))}
      </div>
    </>
  );
}
