import { useEffect } from 'react';
const resolveNode = (item) => {
    if (!item) {
        return null;
    }
    return item instanceof Node ? item : item.current;
};
/**
 * хук позволяющий подписаться на клик вне указанного рефа,
 * подойдет для использования в кастомных попперах
 */
export const useClickAwayEffect = ({ ref, onClickAway, preventBubbling, isActive, excludeNodes, }) => {
    useEffect(() => {
        const node = ref?.current;
        if (!isActive || !node) {
            return;
        }
        const onClick = (event) => {
            const target = event.target;
            const isClickInside = node.contains(target);
            const isClickOnExcluded = excludeNodes?.some((item) => resolveNode(item)?.contains(target));
            const isClickAway = !isClickInside && !isClickOnExcluded;
            if (preventBubbling) {
                event.stopPropagation();
                event.stopImmediatePropagation();
            }
            if (isClickAway) {
                onClickAway(event, 'clickAway');
            }
        };
        window.addEventListener('pointerdown', onClick);
        return () => {
            window.removeEventListener('pointerdown', onClick);
        };
    }, [isActive, ref, excludeNodes, onClickAway, preventBubbling]);
};
