import {useEffect, useRef} from "@wordpress/element";

export default function useClickOutside(refs, callback) {
    const callbackRef = useRef(null);
    callbackRef.current = callback;

    const handleClickOutside = (e) => {
        const isOutside = refs.every(ref => !ref.current?.contains(e.target))
        if (isOutside && typeof callbackRef.current === 'function') {
            callbackRef.current();
        }
    }

    useEffect(() => {
        // Events
        document.addEventListener('click', handleClickOutside);

        return () => document.removeEventListener('click', handleClickOutside);
    }, [refs, callback]);
}