import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
import { useContext, useEffect, useRef, useState } from 'react';
import styled, { css } from 'styled-components';
import { useDirection, useEscape, useOuterEvent } from '../../hooks';
import Text from '../Text';
import Tooltip from '../Tooltip';
import Popover from '../Popover';
import Menu from '../Menu';
import { StyledMenu, StyledMenuListContainer, StyledMenuListWrapper } from '../Menu/Menu.styles';
import { defaultThemeProp } from '../../theme';
import { calculateFontSize } from '../../styles';
import AppShellContext from './AppShellContext';
import { navContrastColors } from './style-utils';
const StyledNavigationPopover = styled.div(({ theme }) => {
    const navBg = theme.components['app-shell'].nav['background-color'];
    const { hoverBg, foreground } = navContrastColors(theme);
    const headingFontSize = calculateFontSize(theme.base['font-size'], theme.base['font-scale']).s;
    return css `
    display: flex;
    background-color: ${navBg};

    ${StyledMenu} {
      display: flex;
      flex-direction: column;
    }

    ${StyledMenuListWrapper} {
      overflow: auto;
    }

    &,
    ${StyledMenuListContainer} {
      background-color: ${navBg};

      header {
        color: ${foreground};
        border-bottom: none;
        opacity: 0.7;

        h2 {
          font-weight: ${theme.base['font-weight']['semi-bold']};
          font-size: ${headingFontSize};
        }
      }
    }

    ${StyledMenuListContainer} li {
      color: ${foreground};
      background-color: transparent;

      &:hover,
      &[data-current='true'] {
        background-color: ${hoverBg};
      }
    }
  `;
});
StyledNavigationPopover.defaultProps = defaultThemeProp;
const ListItemWrapper = props => {
    const { children, childElementRef, label, tooltipLabel, items = [], content, onMenuToggle } = props;
    const { navOpen, collapsedHoverMenus, headerEl } = useContext(AppShellContext);
    const popoverRef = useRef(null);
    const [popoverOpen, setPopoverOpen] = useState(false);
    const { end } = useDirection();
    const mousedOverMenu = useRef(false);
    const hidePopoverTimeout = useRef();
    const closePopover = (focusChildEl = true) => {
        if (popoverOpen) {
            setPopoverOpen(false);
            if (focusChildEl) {
                childElementRef.current?.focus();
            }
            if (hidePopoverTimeout.current) {
                clearTimeout(hidePopoverTimeout.current);
                hidePopoverTimeout.current = null;
            }
        }
    };
    const onMouseEnterContent = () => {
        if (collapsedHoverMenus) {
            mousedOverMenu.current = true;
        }
    };
    const onMouseLeaveContent = () => {
        if (mousedOverMenu.current && collapsedHoverMenus) {
            mousedOverMenu.current = false;
            closePopover();
        }
    };
    useOuterEvent('click', [popoverRef], () => closePopover());
    useEffect(() => {
        const onClick = (e) => {
            if (items.length || content) {
                if (!navOpen) {
                    e.stopPropagation();
                    e.preventDefault();
                }
                if (!navOpen && !popoverOpen)
                    setPopoverOpen(true);
                else {
                    setTimeout(() => {
                        closePopover(false);
                    }, 0);
                }
            }
        };
        const onKeyDown = (e) => {
            if (e.key === 'Tab' && !content) {
                setPopoverOpen(false);
            }
        };
        const onMouseOut = (e) => {
            if (hidePopoverTimeout.current) {
                clearTimeout(hidePopoverTimeout.current);
                hidePopoverTimeout.current = null;
            }
            const tag = e.relatedTarget?.tagName.toLowerCase();
            // If the mouse is mousing out from this nav item onto another nav item
            if (tag && ['a', 'button', 'form'].includes(tag)) {
                closePopover(false);
            }
            else {
                hidePopoverTimeout.current = window.setTimeout(() => {
                    if (!mousedOverMenu.current) {
                        closePopover(false);
                    }
                }, 1000);
            }
        };
        childElementRef.current?.addEventListener('click', onClick);
        childElementRef.current?.addEventListener('blur', () => closePopover(false));
        childElementRef.current?.addEventListener('keydown', onKeyDown);
        if (collapsedHoverMenus) {
            childElementRef.current?.addEventListener('mouseenter', onClick);
            childElementRef.current?.addEventListener('mouseleave', onMouseOut);
        }
        return () => {
            childElementRef.current?.removeEventListener('click', onClick);
            childElementRef.current?.removeEventListener('keydown', onKeyDown);
            if (collapsedHoverMenus) {
                childElementRef.current?.removeEventListener('mouseenter', onClick);
                childElementRef.current?.removeEventListener('mouseleave', onMouseOut);
            }
            if (hidePopoverTimeout.current) {
                clearTimeout(hidePopoverTimeout.current);
                hidePopoverTimeout.current = null;
            }
        };
    }, [items, content, navOpen, closePopover, collapsedHoverMenus]);
    useEffect(() => {
        onMenuToggle?.(popoverOpen ? 'open' : 'close');
    }, [popoverOpen]);
    useEscape(() => closePopover(), childElementRef, [childElementRef]);
    useEscape(() => closePopover(), popoverRef, [popoverRef]);
    return (_jsxs(_Fragment, { children: [children, !navOpen && (_jsxs(_Fragment, { children: [!popoverOpen && (_jsx(Tooltip, { target: childElementRef.current, placement: end, showDelay: 'none', hideDelay: 'none', children: tooltipLabel })), popoverOpen && (items.length || content) && (_jsx(Popover, { target: childElementRef.current, placement: `${end}-start`, ref: popoverRef, as: StyledNavigationPopover, arrow: true, modifiers: headerEl
                            ? [
                                {
                                    name: 'preventOverflow',
                                    options: {
                                        padding: {
                                            top: headerEl.offsetHeight + 8,
                                            right: 8,
                                            bottom: 8,
                                            left: 8
                                        }
                                    }
                                }
                            ]
                            : undefined, onClick: (e) => {
                            e.stopPropagation();
                        }, children: content ? (_jsx("div", { onMouseEnter: onMouseEnterContent, onMouseLeave: onMouseLeaveContent, children: content })) : (_jsx(Menu, { mode: 'action', variant: 'flyout', focusControlEl: childElementRef.current ?? undefined, scrollAt: 99, items: items.map(item => {
                                return {
                                    id: (item.primary || item.text),
                                    primary: (item.primary || item.text),
                                    href: item.href,
                                    onClick: (_, e) => {
                                        e.stopPropagation();
                                        item.onClick?.(e);
                                        setPopoverOpen(false);
                                    }
                                };
                            }), header: _jsx(Text, { variant: 'h2', children: label }), onMouseEnter: onMouseEnterContent, onMouseLeave: onMouseLeaveContent })) }))] }))] }));
};
export default ListItemWrapper;
//# sourceMappingURL=NavigationListItemWrapper.js.map