export function buildNestedMenu(menuItems: any) {
    // Create a map for quick lookup by menu_item_id
    const itemsMap = new Map();
    const rootItems: any = [];

    // First pass: add all items to the map and initialize items array
    menuItems.forEach((item: any) => {
        // Ensure we don't mutate the original object by creating a new one with items array
        itemsMap.set(item.menu_item_id, {
            ...item,
            items: []
        });
    });

    // Second pass: build the hierarchy
    menuItems.forEach((item: any) => {
        const menuItem = itemsMap.get(item.menu_item_id);
        const parentId = item.parent_menu_item_id;

        if (parentId === "0") {
            // This is a root-level item
            rootItems.push(menuItem);
        } else {
            // This is a child item
            const parentItem = itemsMap.get(parentId);
            if (parentItem) {
                parentItem.items.push(menuItem);
            } else {
                // Orphaned item - add to root as fallback
                rootItems.push(menuItem);
            }
        }
    });

    return rootItems;
}