import { useContext, useEffect, useRef } from 'react';
import { DashboardContext } from '../../DashboardContext';
import { dashboardLayoutHeaderClassnames } from '../../DashboardLayout/Header';
import { dashboardLayoutMainClassnames } from '../../DashboardLayout/Main';
import { DashboardSidebarContext } from '../../DashboardSidebarProvider';
import { useTheme } from '../../theme/hooks/useTheme';
import { useViewportType } from '../../useViewportType';
import { classNames } from '../../utils/classNames';
import { dashboardSidebarClassnames } from '../constants';
import { useCloseSidebarOnMobile } from './hooks';
export const useLogic = (props) => {
    const { className, menu, header, isLoading } = props;
    const { onToggleSidebar, isPinned, onTogglePin, collapsedIn, setIsPopupOpen, } = useContext(DashboardSidebarContext);
    const { alertHeight, isLoading: isDashboardLoading, hasMenuOrganizationRef, hasProfileRef, mobileHeaderPriorityFeature, } = useContext(DashboardContext);
    const { isMobile } = useViewportType();
    useCloseSidebarOnMobile();
    const hoverTimerRef = useRef(null);
    const theme = useTheme();
    const onMouseEnter = () => {
        if (isMobile) {
            return;
        }
        if (hoverTimerRef.current) {
            clearTimeout(hoverTimerRef.current);
        }
        //Задержка 200ms
        hoverTimerRef.current = window.setTimeout(() => {
            onToggleSidebar(true);
        }, theme.transitions.duration.shorter);
    };
    const onMouseLeave = () => {
        if (isMobile) {
            return;
        }
        if (hoverTimerRef.current) {
            clearTimeout(hoverTimerRef.current);
            hoverTimerRef.current = null;
        }
        onToggleSidebar(false);
        setIsPopupOpen(false);
    };
    useEffect(() => {
        return () => {
            if (hoverTimerRef.current) {
                clearTimeout(hoverTimerRef.current);
            }
        };
    }, []);
    /**
     * Функция закрытия sidebar
     * Для избежания ситуации, когда sidebar не закреплен, но курсор увели за пределы его контейнера и
     * событие onMouseLeave на элементе sidebar не выполнилось
     */
    useEffect(() => {
        //Не подписываемся на изменения если мобильное устройство, если sidebar закреплен или свернут
        if (isMobile || isPinned || (!collapsedIn && !isPinned)) {
            return;
        }
        const handleMouseEnter = () => onToggleSidebar(false);
        //Основные элементы DashboardLayout
        const mainElement = document.querySelector(`.${dashboardLayoutMainClassnames.main}`);
        const pageAlertElement = document.querySelector(`.${dashboardLayoutMainClassnames.alert}`);
        const headerElement = document.querySelector(`.${dashboardLayoutHeaderClassnames.root}`);
        if (mainElement) {
            mainElement.addEventListener('mouseenter', handleMouseEnter);
        }
        if (pageAlertElement) {
            pageAlertElement.addEventListener('mouseenter', handleMouseEnter);
        }
        if (headerElement) {
            headerElement.addEventListener('mouseenter', handleMouseEnter);
        }
        return () => {
            if (mainElement) {
                mainElement.removeEventListener('mouseenter', handleMouseEnter);
            }
            if (pageAlertElement) {
                pageAlertElement.removeEventListener('mouseenter', handleMouseEnter);
            }
            if (headerElement) {
                headerElement.removeEventListener('mouseenter', handleMouseEnter);
            }
        };
    }, [collapsedIn, isPinned]);
    const classnames = classNames(className, dashboardSidebarClassnames.root);
    return {
        isPinned,
        isMobile,
        collapsedIn,
        onTogglePin,
        onMouseEnter,
        onMouseLeave,
        alertHeight,
        menu,
        header,
        isLoading: isLoading || isDashboardLoading,
        classnames,
        hasMenuOrganization: hasMenuOrganizationRef.current &&
            mobileHeaderPriorityFeature === 'profile',
        hasProfile: hasProfileRef.current && mobileHeaderPriorityFeature === 'menuOrg',
    };
};
