import { useEffect, useRef } from "react";

// Attach the returned ref to the menu's outermost container. Clicking
// anywhere outside that element while `open` is true calls onClose.
export function useClickOutside<T extends HTMLElement>(open: boolean, onClose: () => void) {
  const ref = useRef<T>(null);

  useEffect(() => {
    if (!open) return;
    function handleClick(e: MouseEvent) {
      if (ref.current && !ref.current.contains(e.target as Node)) {
        onClose();
      }
    }
    // Listen on the next tick — otherwise the same click that opened the
    // menu (e.g. the toggle button) would immediately bubble up and close
    // it again before the user sees anything.
    const id = setTimeout(() => document.addEventListener("mousedown", handleClick), 0);
    return () => {
      clearTimeout(id);
      document.removeEventListener("mousedown", handleClick);
    };
  }, [open, onClose]);

  return ref;
}
