// buildMenuTree.ts

export interface MenuItem {
  id: string;
  label: string;
  uri: string;
  parentId?: string | null;
  children?: MenuItem[];
}

export function buildMenuTree(items: MenuItem[]): MenuItem[] {
  const map: Record<string, MenuItem> = {};
  const tree: MenuItem[] = [];

  // 1️⃣ Create lookup map
  items.forEach((item) => {
    map[item.id] = {
      ...item,
      children: [],
    };
  });

  // 2️⃣ Assign children using parentId
  items.forEach((item) => {
    if (item.parentId && map[item.parentId]) {
      map[item.parentId].children!.push(map[item.id]);
    } else {
      tree.push(map[item.id]);
    }
  });

  return tree;
}
