// export const flattenCategories = (categories, prefix = "") => {
//   let result = [];

//   if (!Array.isArray(categories)) return result;

//   categories.forEach((cat) => {
//     const path = prefix ? `${prefix} > ${cat.name}` : cat.name;

//     result.push({
//       value: cat._id,   // ✅ ID stored
//       label: path,      // ✅ Path shown
//     });

//     if (cat.children?.length) {
//       result = result.concat(
//         flattenCategories(cat.children, path)
//       );
//     }
//   });

//   return result;
// };




export const flattenCategories = (categories, prefix = "") => {
  let result = [];

  if (!Array.isArray(categories)) return result;

  categories.forEach((cat) => {
    const path = prefix ? `${prefix} > ${cat.name}` : cat.name;
    
    // ✅ Handle multiple ID field names
    const categoryId = cat.id || cat._id || cat.categoryId;
    
    if (!categoryId) {
      console.error("❌ Category missing ID:", cat);
      return; // Skip this category
    }

    result.push({
      value: categoryId,   // ✅ Store ID
      label: path,         // ✅ Display path
    });

    if (cat.children?.length) {
      result = result.concat(
        flattenCategories(cat.children, path)
      );
    }
  });

  return result;
};