export interface Category {
  id: number;
  name: string;
  parentId?: number | null;
}

export interface FlatCategory {
  id: number;
  name: string;
  level: number;
  parentId: number | null;
  label: string; // Para mostrar en el select con indentación
}

interface CategoryNode extends Category {
  children: CategoryNode[];
}

/**
 * Construye el árbol y luego lo aplana ordenadamente con niveles
 */
export const processCategoriesForSelect = (rawCategories: Category[]): FlatCategory[] => {
  const map = new Map<number, CategoryNode>();
  const roots: CategoryNode[] = [];

  // 1. Mapear categorías
  rawCategories.forEach(cat => {
    map.set(cat.id, { ...cat, children: [] });
  });

  // 2. Tree
  rawCategories.forEach(cat => {
    const node = map.get(cat.id);
    if (node) {
      if (cat.parentId && map.has(cat.parentId)) {
        map.get(cat.parentId)!.children.push(node);
      } else {
        roots.push(node);
      }
    }
  });

  // 3. Flatten Recursive
  const flatten = (nodes: CategoryNode[], level = 0): FlatCategory[] => {
    let result: FlatCategory[] = [];
    // Ordenar alfabéticamente
    const sorted = nodes.sort((a, b) => a.name.localeCompare(b.name));

    for (const node of sorted) {
      // Creamos el label visual con espacios
      // Usamos caracteres unicode especiales para que se note la jerarquía
      const prefix = level === 0 ? '' : '\u00A0\u00A0'.repeat(level) + '↳ ';

      result.push({
        id: node.id,
        name: node.name,
        parentId: node.parentId || null,
        level: level,
        label: prefix + node.name
      });

      if (node.children.length > 0) {
        result = [...result, ...flatten(node.children, level + 1)];
      }
    }
    return result;
  };

  return flatten(roots);
};