import { useEffect, useRef } from "react";

export default function useOutsideDismiss<TElement extends HTMLElement = HTMLDivElement>(
  active: boolean,
  onDismiss: () => void,
) {
  const rootRef = useRef<TElement | null>(null);

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

    function handlePointerDown(event: PointerEvent) {
      if (!rootRef.current || rootRef.current.contains(event.target as Node)) return;
      onDismiss();
    }

    function handleKeyDown(event: KeyboardEvent) {
      if (event.key === "Escape") onDismiss();
    }

    document.addEventListener("pointerdown", handlePointerDown);
    document.addEventListener("keydown", handleKeyDown);
    return () => {
      document.removeEventListener("pointerdown", handlePointerDown);
      document.removeEventListener("keydown", handleKeyDown);
    };
  }, [active, onDismiss]);

  return rootRef;
}
