import { useRef, useEffect } from 'react';

/**
 * Custom hook that handles clicks outside of the specified element
 * @param ref The reference to the element to detect clicks outside of
 * @param handler The callback function to execute when a click outside is detected
 */
const useClickOutside = (ref, handler) => {
    const handlerRef = useRef(handler);
    handlerRef.current = handler;
    useEffect(() => {
        const listener = (event) => {
            const el = ref.current;
            if (!el || el.contains(event.target)) {
                return;
            }
            handlerRef.current(event);
        };
        document.addEventListener('mousedown', listener);
        document.addEventListener('touchstart', listener);
        return () => {
            document.removeEventListener('mousedown', listener);
            document.removeEventListener('touchstart', listener);
        };
    }, [ref]);
};

export { useClickOutside };
