import type { RefObject } from "react";
import { useEffect } from "react";

interface UseOutsidePressArgs {
  referenceRef: RefObject<HTMLElement | null>;
  floatingRef: RefObject<HTMLDivElement | null>;
  enabled: boolean;
  onOutsidePress: (event: PointerEvent) => void;
}

export const useOutsidePress = ({
  referenceRef,
  floatingRef,
  enabled,
  onOutsidePress,
}: UseOutsidePressArgs): void => {
  useEffect(() => {
    if (!enabled) return;

    const handler = (event: PointerEvent) => {
      const target = event.target as Node | null;
      if (!target) return;
      if (referenceRef.current?.contains(target)) return;
      if (floatingRef.current?.contains(target)) return;
      onOutsidePress(event);
    };

    document.addEventListener("pointerdown", handler);
    return () => document.removeEventListener("pointerdown", handler);
  }, [enabled, onOutsidePress, referenceRef, floatingRef]);
};
