import { Fragment, jsx } from "react/jsx-runtime";
import { createContext, useCallback, useContext, useRef } from "react";
import lodash from "lodash";
const GetMenuItemContext = /*#__PURE__*/ createContext(null);
GetMenuItemContext.displayName = 'GetMenuItemContext';
const GetMenuItemsContext = /*#__PURE__*/ createContext(null);
GetMenuItemsContext.displayName = 'GetMenuItemsContext';
const useCollectMenuItem = ()=>useContext(GetMenuItemContext) || {};
const useCollectMenuItems = ()=>useContext(GetMenuItemsContext) || {};
const useMenuItem = ()=>{
    const list = useRef([]);
    const renderItems = useRef(null);
    const shouldRerender = useRef(false);
    const Component = useCallback((param)=>{
        let { limitCount } = param;
        if (!shouldRerender.current) return null;
        shouldRerender.current = false;
        if (renderItems.current) return renderItems.current();
        if (limitCount && list.current.length > limitCount) return /*#__PURE__*/ jsx(Fragment, {
            children: list.current.slice(0, limitCount).map((Com, index)=>/*#__PURE__*/ jsx(Com, {}, index))
        });
        return /*#__PURE__*/ jsx(Fragment, {
            children: list.current.map((Com, index)=>/*#__PURE__*/ jsx(Com, {}, index))
        });
    }, []);
    const getMenuItems = useCallback((Com)=>{
        const items = [];
        const pushMenuItem = (item)=>{
            items.push(item);
            items.sort((a, b)=>(a.order || 0) - (b.order || 0));
        };
        shouldRerender.current = true;
        renderItems.current = ()=>{
            const notDeleteItems = items.filter((item)=>item.notdelete).map((item)=>lodash.omit(item, 'notdelete'));
            items.length = 0;
            items.push(...notDeleteItems);
            return /*#__PURE__*/ jsx(GetMenuItemsContext.Provider, {
                value: {
                    pushMenuItem
                },
                children: Com()
            });
        };
        return items;
    }, []);
    const getMenuItem = useCallback((Com)=>{
        const item = {};
        const collectMenuItem = (menuItem)=>{
            Object.assign(item, menuItem);
        };
        shouldRerender.current = true;
        list.current.push(()=>/*#__PURE__*/ jsx(GetMenuItemContext.Provider, {
                value: {
                    collectMenuItem
                },
                children: Com()
            }));
        return item;
    }, []);
    const clean = useCallback(()=>{
        list.current = [];
    }, []);
    return {
        Component,
        getMenuItems,
        getMenuItem,
        clean
    };
};
export { GetMenuItemContext, GetMenuItemsContext, useCollectMenuItem, useCollectMenuItems, useMenuItem };
