import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { createElement as _createElement } from "react";
import { forwardRef, useContext, useEffect, useRef, useState, useMemo, useCallback, useLayoutEffect } from 'react';
import { useAfterInitialEffect, useConsolidatedRef, useI18n, useItemIntersection, useLiveLog } from '../../hooks';
import Progress from '../Progress';
import EmptyState from '../EmptyState';
import Popover from '../Popover';
import MenuContext from './Menu.context';
import MenuItem from './MenuItem';
import { StyledLoadingItem, StyledMenuList, StyledFlyoutMenuListContainer } from './Menu.styles';
import { resizeRootEl } from './NavItemsList';
import helpers from './helpers';
import MenuGroup from './MenuGroup';
import { isParentMenuItem } from './Menu.utils';
const FlyoutMenuList = forwardRef(function FlyoutMenuListFunction({ items, parent, menuRole }, ref) {
    const t = useI18n();
    const selfRef = useConsolidatedRef(ref);
    const ulRef = useRef(null);
    const menuListWrapperRef = useRef(null);
    const returnFocusRef = useRef(null);
    const [expandedItem, setExpandedItem] = useState();
    const { componentId, loadMore, loading, scrollAt, emptyText, onItemExpand, pushFlyoutId, flyOutActiveIdStack, updateActiveDescendants, updateParentDescendantStack } = useContext(MenuContext);
    const { announcePolite } = useLiveLog();
    useItemIntersection(ulRef, items.length - 1, () => {
        loadMore?.(parent?.item?.id);
    }, ':scope > li');
    useAfterInitialEffect(() => {
        if (expandedItem) {
            const foundItem = items.find(item => item.id === expandedItem.id);
            if (foundItem && isParentMenuItem(foundItem)) {
                setExpandedItem(foundItem);
            }
            else {
                setExpandedItem(undefined);
            }
        }
    }, [expandedItem, items]);
    useEffect(() => {
        const hasExpanded = items.some(item => {
            return flyOutActiveIdStack.includes(item.id);
        });
        if (!hasExpanded) {
            returnFocusRef.current = null;
            setExpandedItem(undefined);
        }
    }, [flyOutActiveIdStack]);
    useEffect(() => {
        if (items.length === 0 && !loading) {
            announcePolite({ message: emptyText ?? t('no_items') });
        }
    }, [items.length, loading]);
    const listContent = useMemo(() => {
        if (items.length) {
            return items.map(item => {
                return helpers.isItem(item) ? (_createElement(MenuItem, { ...item, key: item.id, "aria-haspopup": !!item.items, "aria-expanded": item.items ? item.id === expandedItem?.id : undefined, role: menuRole === 'listbox' ? 'option' : 'menuitem', onExpand: (id, e) => {
                        if (item.items) {
                            returnFocusRef.current = e.currentTarget;
                            setExpandedItem(isParentMenuItem(item) ? item : undefined);
                            item?.onExpand?.(id, e);
                            onItemExpand?.(id, e);
                            pushFlyoutId(item.id || componentId);
                            updateActiveDescendants();
                            if (updateParentDescendantStack) {
                                updateParentDescendantStack(returnFocusRef.current.closest('li'));
                            }
                        }
                        else {
                            returnFocusRef.current = null;
                            setExpandedItem(undefined);
                        }
                    } })) : (_createElement(MenuGroup, { ...item, key: item.id, itemRole: menuRole === 'listbox' ? 'option' : 'menuitem' }));
            });
        }
        if (!loading) {
            return _jsx(EmptyState, { message: emptyText, forwardedAs: 'li' });
        }
        return null;
    }, [items, loading, emptyText, expandedItem, flyOutActiveIdStack]);
    const list = (_jsxs(StyledMenuList, { ref: ulRef, role: menuRole, children: [listContent, loading && !expandedItem && (_jsx(StyledLoadingItem, { children: _jsx(Progress, { placement: 'local' }) }))] }));
    useLayoutEffect(() => {
        setExpandedItem(undefined);
        if (selfRef.current) {
            menuListWrapperRef.current = selfRef.current.parentElement;
            resizeRootEl(selfRef.current, selfRef.current, items.length, scrollAt);
        }
    }, [items]);
    const handleMenuListScroll = useCallback(() => {
        if (expandedItem) {
            setExpandedItem(undefined);
        }
    }, [expandedItem]);
    return (_jsxs(_Fragment, { children: [_jsx(StyledFlyoutMenuListContainer, { ref: selfRef, onScroll: handleMenuListScroll, "data-flyout-menu-parent-id": componentId, "data-flyout-menu-id": parent?.item.id || componentId, children: list }), expandedItem && selfRef.current && (_jsx(Popover, { target: returnFocusRef.current, show: true, strategy: 'fixed', placement: 'right-start', portal: false, children: _jsx(FlyoutMenuList, { items: expandedItem.items, parent: {
                        el: selfRef.current,
                        item: expandedItem,
                        siblingItems: items,
                        setExpandedItem,
                        returnFocusRef
                    }, menuRole: menuRole }) }))] }));
});
export default FlyoutMenuList;
//# sourceMappingURL=FlyoutMenuList.js.map