// Neutral colors that pair well with anything
const NEUTRALS = new Set(["white", "cream", "beige", "grey", "gray", "black", "off-white", "ivory", "nude"]);

export function colorsCompatible(a: string[], b: string[]): boolean {
  if (!a.length || !b.length) return true; // no color info → assume compatible
  const hasNeutral = (arr: string[]) => arr.some(c => NEUTRALS.has(c.toLowerCase()));
  if (hasNeutral(a) || hasNeutral(b)) return true;
  // Same hue family → monochromatic, fine
  const normalize = (c: string) => c.toLowerCase().replace(/light |dark |pale |deep /, "");
  const aHues = a.map(normalize);
  const bHues = b.map(normalize);
  return aHues.some(h => bHues.includes(h));
}

export interface GarmentRow {
  id: string;
  name: string | null;
  category: string;
  sizeLabel: string;
  colors: string[];
  seasons: string[];
  occasionTags: string[];
  thumbKey: string;
  imageKey: string;
}

export interface OutfitSuggestion {
  items: GarmentRow[];
  label: string;
}

export function buildOutfits(garments: GarmentRow[], max = 3): OutfitSuggestion[] {
  const tops = garments.filter(g => g.category === "top");
  const bottoms = garments.filter(g => g.category === "bottom");
  const dresses = garments.filter(g => g.category === "dress");
  const onesies = garments.filter(g => g.category === "onesie");

  const results: OutfitSuggestion[] = [];

  // Dresses and onesies are standalone complete outfits
  for (const item of [...dresses, ...onesies]) {
    if (results.length >= max) break;
    results.push({ items: [item], label: item.category === "dress" ? "Dress" : "Onesie" });
  }

  // Pair tops + bottoms
  for (const top of tops) {
    if (results.length >= max) break;
    for (const bottom of bottoms) {
      if (results.length >= max) break;
      if (colorsCompatible(top.colors, bottom.colors)) {
        results.push({ items: [top, bottom], label: "Top + Bottom" });
        break; // one bottom per top
      }
    }
  }

  // If not enough pairs, add mismatched ones anyway
  if (results.length < max) {
    for (const top of tops) {
      if (results.length >= max) break;
      for (const bottom of bottoms) {
        if (results.length >= max) break;
        const alreadyAdded = results.some(r => r.items.some(i => i.id === top.id || i.id === bottom.id));
        if (!alreadyAdded) {
          results.push({ items: [top, bottom], label: "Top + Bottom" });
          break;
        }
      }
    }
  }

  return results;
}
