/**
 * Builds grouped accounting codes for the SearchableSelect component.
 * Only returns leaf items (no children), grouped by sub-category.
 */
export function buildAccountGroups(
  leafAccounts: {
    id: string;
    code: string;
    name: string;
    parent: { name: string; code: string; parent: { name: string; code: string } | null } | null;
  }[]
) {
  const map = new Map<string, { id: string; code: string; name: string }[]>();
  for (const a of leafAccounts) {
    const subLabel = a.parent ? `${a.parent.code} — ${a.parent.name}` : "Uncategorised";
    const topLabel = a.parent?.parent ? `${a.parent.parent.name} › ` : "";
    const key = `${topLabel}${subLabel}`;
    if (!map.has(key)) map.set(key, []);
    map.get(key)!.push({ id: a.id, code: a.code, name: a.name });
  }
  return Array.from(map.entries()).map(([group, items]) => ({ group, items }));
}
