// Slot-based idea selection used by the legacy plan path

export interface TaggedIdea {
  id: string;
  content: string;
  category: string;
  timeSlot: string;
  estimatedMinutes: number;
  searchQuery: string;
  searchType: string;
  costLevel: string | null;
  intensity: string | null;
  needsBooking: boolean | null;
}

export const SLOT_CATEGORY_MAP: Record<string, string[]> = {
  morning: ["outdoor", "nature", "sports", "culture"],
  lunch: ["dining"],
  afternoon: ["entertainment", "shopping", "relaxation", "outdoor", "culture", "experience"],
  dinner: ["dining"],
  evening: ["entertainment", "relaxation", "experience"],
};

export const SLOT_TIME_MAP: Record<string, string[]> = {
  morning: ["morning", "flexible"],
  lunch: ["flexible"],
  afternoon: ["afternoon", "flexible"],
  dinner: ["evening", "flexible"],
  evening: ["evening", "flexible"],
};

export function matchesSlot(idea: TaggedIdea, slot: string): boolean {
  if (idea.timeSlot === "all_day") return true;
  const validTimes = SLOT_TIME_MAP[slot];
  return validTimes ? validTimes.includes(idea.timeSlot) : false;
}

export function selectIdeasForSlots(ideas: TaggedIdea[], availableHours: number): TaggedIdea[] {
  const slots: string[] = [];
  if (availableHours >= 10) {
    slots.push("morning", "lunch", "afternoon", "dinner", "evening");
  } else if (availableHours >= 7) {
    slots.push("morning", "lunch", "afternoon", "evening");
  } else if (availableHours >= 5) {
    slots.push("lunch", "afternoon", "evening");
  } else {
    slots.push("afternoon", "evening");
  }

  const selected: TaggedIdea[] = [];
  const usedIds = new Set<string>();

  function pickRandom(pool: TaggedIdea[]): TaggedIdea | null {
    if (pool.length === 0) return null;
    return pool[Math.floor(Math.random() * pool.length)];
  }

  for (const slot of slots) {
    const remaining = ideas.filter((i) => !usedIds.has(i.id));
    const preferredCategories = SLOT_CATEGORY_MAP[slot] || [];

    const p1 = remaining.filter(
      (i) => matchesSlot(i, slot) && preferredCategories.includes(i.category),
    );
    let picked = pickRandom(p1);

    if (!picked) {
      for (const cat of preferredCategories) {
        const pool = remaining.filter((i) => i.category === cat);
        picked = pickRandom(pool);
        if (picked) break;
      }
    }

    if (!picked) {
      const p3 = remaining.filter((i) => matchesSlot(i, slot));
      picked = pickRandom(p3);
    }

    if (!picked) {
      picked = pickRandom(remaining);
    }

    if (picked) {
      selected.push(picked);
      usedIds.add(picked.id);
    }
  }

  return selected;
}
