import { useEffect } from "react";

export function useOutsideClick(ref, callback, excludeRef = []) {
  useEffect(() => {
    function handleClickOutside(event) {
      const excludeIsElement = excludeRef?.every((ref) => !ref?.current);
      const isExcluded = excludeRef?.find((ref) =>
        excludeIsElement
          ? ref.contains(event.target)
          : ref?.current?.contains(event.target)
      );

      if (isExcluded) return;

      if (ref.current && !ref.current.contains(event.target)) {
        callback();
      }
    }
    // Bind the event listener
    document.addEventListener("mousedown", handleClickOutside);
    return () => {
      // Unbind the event listener on clean up
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, [callback, ref, excludeRef]);
}
