/**
 * Enriched state data for Eagle Action.
 *
 * Provides slug-addressable state metadata for the states index and detail pages.
 * The canonical list of 50 states comes from usStates.ts; this module adds slugs
 * and a lookup map. Chapter and event data is joined at the page level, this
 * module only owns state identity.
 */

import { US_STATES } from "./usStates";
import type { StateInfo } from "./types";

function toSlug(name: string): string {
  return name.toLowerCase().replace(/\s+/g, "-");
}

export const STATES: StateInfo[] = US_STATES.map((s) => ({
  name: s.name,
  abbr: s.abbr,
  slug: toSlug(s.name),
}));

const SLUG_INDEX = new Map(STATES.map((s) => [s.slug, s]));
const ABBR_INDEX = new Map(STATES.map((s) => [s.abbr, s]));
const CODE_INDEX = new Map(STATES.map((s) => [s.abbr.toLowerCase(), s]));

/**
 * Set of valid lowercase 2-letter state codes (e.g. "fl", "tx").
 * Use to validate user-supplied chapter URL segments before any
 * database lookup, keeps invalid codes from ever reaching DynamoDB.
 */
export const STATE_CODES: ReadonlySet<string> = new Set(CODE_INDEX.keys());

export function getStateBySlug(slug: string): StateInfo | undefined {
  return SLUG_INDEX.get(slug);
}

export function getStateByAbbr(abbr: string): StateInfo | undefined {
  return ABBR_INDEX.get(abbr);
}

/**
 * Resolve a state by its lowercase 2-letter code (the URL form used
 * in /chapters/<code>/<slug>). Returns undefined for unknown codes
 * so callers can render notFound() rather than guessing.
 */
export function getStateByCode(code: string): StateInfo | undefined {
  return CODE_INDEX.get(code.toLowerCase());
}

export function getStateSlug(nameOrAbbr: string): string {
  const byAbbr = ABBR_INDEX.get(nameOrAbbr);
  if (byAbbr) return byAbbr.slug;
  return toSlug(nameOrAbbr);
}
