import { RefObject, useEffect } from 'react';

export function useClickOutsideElement(
  ref: RefObject<HTMLElement>,
  onClick: () => void,
): void {
  useEffect(() => {
    function handleClickOutside(event: MouseEvent): void {
      if (
        ref.current &&
        event.currentTarget &&
        !ref.current.contains(event.target as Node)
      ) {
        onClick();
      }
    }

    document.addEventListener('mousedown', handleClickOutside);

    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, [ref, onClick]);
}
