import { useEffect } from "react"

export default function useClickOutside(
  ref: React.RefObject<HTMLElement | null>,
  isOpen: boolean,
  callback: () => void
) {
  useEffect(() => {
    function handleClickOutside(evt: Event) {
      const target = evt.target as HTMLElement
      if (ref.current && target && !ref.current.contains(target) && isOpen) {
        callback()
      }
    }

    if (isOpen) {
      document.addEventListener("click", handleClickOutside)
    }

    return () => {
      document.removeEventListener("click", handleClickOutside)
    }
  }, [ref, isOpen, callback])
}
