/**
 * The identifiers a category page accepts for its event type — the same set
 * the backend's `ReferenceCatalog::matchers()` uses to find an existing row:
 * the catalog key, the slugs of the current and legacy English labels, and the
 * labels themselves.
 *
 * A single catalog slug is not enough. `ReferenceDataSynchronizer` keeps the
 * slug an existing row already had, so a database seeded before the catalog
 * still answers `expo-carnival` / `sport-activity` rather than
 * `exhibitions-festivals` / `sports-activities` — and a page that matched only
 * the new key showed «unavailable» for a category that exists.
 */
export const EVENT_CATEGORY_KEYS = {
  exhibitions: ["exhibitions-festivals", "exhibitions-and-festivals", "expo-carnival", "Exhibitions and festivals", "Expo & Carnival"],
  sports: ["sports-activities", "sport-activity", "Sports activities", "Sport Activity"],
  camps: ["camps", "Camps"],
  conferences: ["conferences", "conference", "Conferences", "Conference"],
} as const satisfies Record<string, readonly string[]>;

const normalize = (value: string | null | undefined) => (value ?? "").trim().toLowerCase();

/**
 * The id of the event type a category page lists, by the choice's `slug`
 * (`/choices/event_type/` carries one — see `ReferenceCatalog`), falling back to
 * the English label. Matching on English names alone broke silently when the
 * catalog renamed them («Sports Activities» → «Sports activities») or retired
 * one («Hub»): the lookup came back empty, the list went unfiltered, and every
 * event showed under the category heading.
 */
export function resolveEventTypeId(
  choices: ReadonlyArray<{ id: number | string; slug?: string | null; value_en?: string | null }> | null | undefined,
  key: string | readonly string[] | undefined
): number | string | undefined {
  if (!key || !choices) return undefined;
  const keys = (typeof key === "string" ? [key] : key).map(normalize).filter(Boolean);
  if (keys.length === 0) return undefined;
  return (
    choices.find((choice) => keys.includes(normalize(choice.slug))) ??
    choices.find((choice) => keys.includes(normalize(choice.value_en)))
  )?.id;
}

/** A category page must never fall back to the unfiltered event feed. */
export function eventCategoryState(
  key: string | readonly string[] | undefined,
  id: string | number | undefined,
  loading: boolean,
  error: boolean
): "all" | "loading" | "error" | "unavailable" | "ready" {
  if (!key || key.length === 0) return "all";
  if (loading) return "loading";
  if (error) return "error";
  return id == null ? "unavailable" : "ready";
}
