import { useEffect } from 'react';

export function useOutsideClick(ref: any, id: string) {
  useEffect(() => {
    /**
     * Alert if clicked on outside of element
     */
    function handleClickOutside(event: any) {
      if (ref.current && !ref.current.contains(event.target)) {
        const event = new CustomEvent('clickOutside', {
          detail: {
            id,
          },
        });
        document.dispatchEvent(event);
      }
    }
    // Bind the event listener
    document.addEventListener('pointerdown', handleClickOutside);
    return () => {
      // Unbind the event listener on clean up
      document.removeEventListener('pointerdown', handleClickOutside);
    };
  }, [ref]);
}
