import { useRef, useEffect } from "react"

/**
 * Custom hook that triggers a callback when a click is detected outside of the referenced element.
 *
 * @param callback - Function to be called when a click outside the element is detected.
 * @returns A ref to be attached to the element you want to detect outside clicks for.
 *
 */
export const useOutsideClick = (callback: () => void) => {
  const ref = useRef<HTMLDivElement>(null)

  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (ref.current && !ref.current.contains(event.target as Node)) {
        callback()
      }
    }

    document.addEventListener("mousedown", handleClickOutside)
    return () => {
      document.removeEventListener("mousedown", handleClickOutside)
    }
  }, [callback])

  return ref
}
