import { useEffect, useState } from 'react';
import { notifyClassnames } from '../../../../constants';
const isInteractiveTarget = (element) => Boolean(element.closest('button, a[href], [role="button"], input, textarea, select'));
/**
 * Определяет, является ли стек уведомлений раскрытым на мобильном устройстве.
 */
export const useTouchStackExpand = ({ stackContainerElement, enabled, hasOpenNotify, }) => {
    const [isTouchExpanded, setTouchExpanded] = useState(false);
    useEffect(() => {
        if (!enabled || !hasOpenNotify) {
            setTouchExpanded(false);
        }
    }, [enabled, hasOpenNotify]);
    useEffect(() => {
        if (!enabled || !hasOpenNotify || !stackContainerElement) {
            return undefined;
        }
        const toggleStack = (event) => {
            const { target } = event;
            if (!(target instanceof Element) || isInteractiveTarget(target)) {
                return;
            }
            setTouchExpanded((prev) => !prev);
        };
        stackContainerElement.addEventListener('pointerdown', toggleStack);
        return () => {
            stackContainerElement.removeEventListener('pointerdown', toggleStack);
        };
    }, [enabled, hasOpenNotify, stackContainerElement]);
    useEffect(() => {
        const collapseIfOutside = (event) => {
            const { target } = event;
            if (!(target instanceof Node) || !stackContainerElement) {
                return;
            }
            const stackHost = stackContainerElement.closest(`.${notifyClassnames.stackHost}`);
            const insideUi = stackHost?.parentElement ?? stackContainerElement;
            if (!insideUi.contains(target)) {
                setTouchExpanded(false);
            }
        };
        document.addEventListener('pointerdown', collapseIfOutside, true);
        if (!enabled ||
            !hasOpenNotify ||
            !isTouchExpanded ||
            !stackContainerElement) {
            document.removeEventListener('pointerdown', collapseIfOutside, true);
        }
        return () => {
            document.removeEventListener('pointerdown', collapseIfOutside, true);
        };
    }, [enabled, hasOpenNotify, isTouchExpanded, stackContainerElement]);
    return isTouchExpanded;
};
