import { useEffect } from "react";

export function useOutsideDismiss(ref, onDismiss, enabled = true, options = {}) {
  const { returnFocusRef } = options;
  useEffect(() => {
    if (!enabled) return undefined;

    function dismiss() {
      onDismiss();
      returnFocusRef?.current?.focus?.();
    }

    function handlePointerDown(event) {
      const container = ref.current;
      if (container && !container.contains(event.target)) dismiss();
    }

    function handleKeyDown(event) {
      if (event.key !== "Escape") return;
      dismiss();
    }

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