export function buildTree(items) {
	const nodes = items
		.map((i) => ({
			...i,
			parent: Number(i.parent || 0),
			menu_order: Number(i.menu_order || 0),
			children: [],
		}))
		.sort((a, b) => a.menu_order - b.menu_order);

	const map = new Map(nodes.map((n) => [n.id, n]));
	const roots = [];

	for (const n of map.values()) {
		if (n.parent && map.has(n.parent)) map.get(n.parent).children.push(n);
		else roots.push(n);
	}
	return roots;
}

export function flattenWithOrder(tree) {
	const out = [];
	let order = 1;

	const walk = (nodes, parent = 0) => {
		for (const n of nodes) {
			out.push({id: n.id, parent, menu_order: order++});
			if (n.children?.length) walk(n.children, n.id);
		}
	};

	walk(tree, 0);
	return out;
}
