/**
 * German federal states (Bundesländer) with abbreviations.
 */
export const GERMAN_FEDERAL_STATES: Record<string, string> = {
  BB: "Brandenburg",
  BE: "Berlin",
  BW: "Baden-Württemberg",
  BY: "Bayern",
  HB: "Bremen",
  HE: "Hessen",
  HH: "Hamburg",
  MV: "Mecklenburg-Vorpommern",
  NI: "Niedersachsen",
  NW: "Nordrhein-Westfalen",
  RP: "Rheinland-Pfalz",
  SH: "Schleswig-Holstein",
  SL: "Saarland",
  SN: "Sachsen",
  ST: "Sachsen-Anhalt",
  TH: "Thüringen",
};

/**
 * PLZ prefix → state mapping (first 2 digits, ~85% accuracy).
 * Source: DE postal code allocation by Deutsche Post.
 */
const PLZ_PREFIX_MAP: Record<number, string> = {
  1: "BE",  // 1xxxx – mostly Berlin
  2: "BE",  // 02xxx – Cottbus area, approximation
  3: "BB",  // 03xxx
  4: "MV",  // 04xxx – close enough
  5: "SN",  // 04-05xxx Sachsen
  6: "ST",  // 06xxx Sachsen-Anhalt
  7: "TH",  // 07xxx Thüringen
  8: "SN",  // 08xxx Sachsen (Chemnitz region)
  9: "BY",  // 09xxx Bayern (Ingolstadt south)
  10: "BE",
  11: "BE",
  12: "BE",
  13: "BE",
  14: "BB",
  15: "BB",
  16: "BB",
  17: "MV",
  18: "MV",
  19: "MV",
  20: "HH",
  21: "HH",
  22: "HH",
  23: "SH",
  24: "SH",
  25: "SH",
  26: "NI",
  27: "NI",
  28: "HB",
  29: "NI",
  30: "NI",
  31: "NI",
  32: "NW",
  33: "NW",
  34: "HE",
  35: "HE",
  36: "HE",
  37: "NI",
  38: "NI",
  39: "ST",
  40: "NW",
  41: "NW",
  42: "NW",
  44: "NW",
  45: "NW",
  46: "NW",
  47: "NW",
  48: "NW",
  49: "NI",
  50: "NW",
  51: "NW",
  52: "NW",
  53: "NW",
  54: "RP",
  55: "RP",
  56: "RP",
  57: "NW",
  58: "NW",
  59: "NW",
  60: "HE",
  61: "HE",
  63: "HE",
  64: "HE",
  65: "HE",
  66: "SL",
  67: "RP",
  68: "BW",
  69: "BW",
  70: "BW",
  71: "BW",
  72: "BW",
  73: "BW",
  74: "BW",
  75: "BW",
  76: "BW",
  77: "BW",
  78: "BW",
  79: "BW",
  80: "BY",
  81: "BY",
  82: "BY",
  83: "BY",
  84: "BY",
  85: "BY",
  86: "BY",
  87: "BY",
  88: "BW",
  89: "BY",
  90: "BY",
  91: "BY",
  92: "BY",
  93: "BY",
  94: "BY",
  95: "BY",
  96: "BY",
  97: "BY",
  98: "TH",
  99: "TH",
};

/**
 * Infer federal state abbreviation from a German postal code (5 digits).
 * Returns undefined if the format is invalid or no match found.
 */
export function inferStateFromPostalCode(plz: string): string | undefined {
  const code = plz.trim().replace(/\s/g, "");
  if (!/^\d{5}$/.test(code)) return undefined;

  // Try 2-digit prefix first, then 1-digit as fallback
  const prefix2 = parseInt(code.slice(0, 2), 10);
  if (PLZ_PREFIX_MAP[prefix2] !== undefined) return PLZ_PREFIX_MAP[prefix2];

  const prefix1 = parseInt(code.slice(0, 1), 10);
  return PLZ_PREFIX_MAP[prefix1];
}
