/**
 * Resolve a GSC country dimension value (typically a 3-letter ISO 3166-1 alpha-3
 * code like "usa", "rus", "fra") to a human-readable country name.
 *
 * Intl.DisplayNames expects ISO 3166-1 alpha-2 region codes, so we first map the
 * incoming alpha-3 code to alpha-2 via a lookup table, then resolve. If the code
 * is already a 2-letter code, or resolution fails, we fall back to the uppercased
 * raw code so the UI never shows a blank cell.
 *
 * (File named `region` rather than `country` to avoid a developer-global gitignore
 * pattern that excludes country-named files.)
 */

// ISO 3166-1 alpha-3 → alpha-2. GSC emits alpha-3 country codes.
const ALPHA3_TO_ALPHA2: Record<string, string> = {
  abw: 'AW', afg: 'AF', ago: 'AO', aia: 'AI', ala: 'AX', alb: 'AL', and: 'AD',
  are: 'AE', arg: 'AR', arm: 'AM', asm: 'AS', ata: 'AQ', atf: 'TF', atg: 'AG',
  aus: 'AU', aut: 'AT', aze: 'AZ', bdi: 'BI', bel: 'BE', ben: 'BJ', bes: 'BQ',
  bfa: 'BF', bgd: 'BD', bgr: 'BG', bhr: 'BH', bhs: 'BS', bih: 'BA', blm: 'BL',
  blr: 'BY', blz: 'BZ', bmu: 'BM', bol: 'BO', bra: 'BR', brb: 'BB', brn: 'BN',
  btn: 'BT', bvt: 'BV', bwa: 'BW', caf: 'CF', can: 'CA', cck: 'CC', che: 'CH',
  chl: 'CL', chn: 'CN', civ: 'CI', cmr: 'CM', cod: 'CD', cog: 'CG', cok: 'CK',
  col: 'CO', com: 'KM', cpv: 'CV', cri: 'CR', cub: 'CU', cuw: 'CW', cxr: 'CX',
  cym: 'KY', cyp: 'CY', cze: 'CZ', deu: 'DE', dji: 'DJ', dma: 'DM', dnk: 'DK',
  dom: 'DO', dza: 'DZ', ecu: 'EC', egy: 'EG', eri: 'ER', esh: 'EH', esp: 'ES',
  est: 'EE', eth: 'ET', fin: 'FI', fji: 'FJ', flk: 'FK', fra: 'FR', fro: 'FO',
  fsm: 'FM', gab: 'GA', gbr: 'GB', geo: 'GE', ggy: 'GG', gha: 'GH', gib: 'GI',
  gin: 'GN', glp: 'GP', gmb: 'GM', gnb: 'GW', gnq: 'GQ', grc: 'GR', grd: 'GD',
  grl: 'GL', gtm: 'GT', guf: 'GF', gum: 'GU', guy: 'GY', hkg: 'HK', hmd: 'HM',
  hnd: 'HN', hrv: 'HR', hti: 'HT', hun: 'HU', idn: 'ID', imn: 'IM', ind: 'IN',
  iot: 'IO', irl: 'IE', irn: 'IR', irq: 'IQ', isl: 'IS', isr: 'IL', ita: 'IT',
  jam: 'JM', jey: 'JE', jor: 'JO', jpn: 'JP', kaz: 'KZ', ken: 'KE', kgz: 'KG',
  khm: 'KH', kir: 'KI', kna: 'KN', kor: 'KR', kwt: 'KW', lao: 'LA', lbn: 'LB',
  lbr: 'LR', lby: 'LY', lca: 'LC', lie: 'LI', lka: 'LK', lso: 'LS', ltu: 'LT',
  lux: 'LU', lva: 'LV', mac: 'MO', maf: 'MF', mar: 'MA', mco: 'MC', mda: 'MD',
  mdg: 'MG', mdv: 'MV', mex: 'MX', mhl: 'MH', mkd: 'MK', mli: 'ML', mlt: 'MT',
  mmr: 'MM', mne: 'ME', mng: 'MN', mnp: 'MP', moz: 'MZ', mrt: 'MR', msr: 'MS',
  mtq: 'MQ', mus: 'MU', mwi: 'MW', mys: 'MY', myt: 'YT', nam: 'NA', ncl: 'NC',
  ner: 'NE', nfk: 'NF', nga: 'NG', nic: 'NI', niu: 'NU', nld: 'NL', nor: 'NO',
  npl: 'NP', nru: 'NR', nzl: 'NZ', omn: 'OM', pak: 'PK', pan: 'PA', pcn: 'PN',
  per: 'PE', phl: 'PH', plw: 'PW', png: 'PG', pol: 'PL', pri: 'PR', prk: 'KP',
  prt: 'PT', pry: 'PY', pse: 'PS', pyf: 'PF', qat: 'QA', reu: 'RE', rou: 'RO',
  rus: 'RU', rwa: 'RW', sau: 'SA', sdn: 'SD', sen: 'SN', sgp: 'SG', sgs: 'GS',
  shn: 'SH', sjm: 'SJ', slb: 'SB', sle: 'SL', slv: 'SV', smr: 'SM', som: 'SO',
  spm: 'PM', srb: 'RS', ssd: 'SS', stp: 'ST', sur: 'SR', svk: 'SK', svn: 'SI',
  swe: 'SE', swz: 'SZ', sxm: 'SX', syc: 'SC', syr: 'SY', tca: 'TC', tcd: 'TD',
  tgo: 'TG', tha: 'TH', tjk: 'TJ', tkl: 'TK', tkm: 'TM', tls: 'TL', ton: 'TO',
  tto: 'TT', tun: 'TN', tur: 'TR', tuv: 'TV', twn: 'TW', tza: 'TZ', uga: 'UG',
  ukr: 'UA', umi: 'UM', ury: 'UY', usa: 'US', uzb: 'UZ', vat: 'VA', vct: 'VC',
  ven: 'VE', vgb: 'VG', vir: 'VI', vnm: 'VN', vut: 'VU', wlf: 'WF', wsm: 'WS',
  yem: 'YE', zaf: 'ZA', zmb: 'ZM', zwe: 'ZW',
};

let displayNames: Intl.DisplayNames | null | undefined;

function getDisplayNames(): Intl.DisplayNames | null {
  if (displayNames !== undefined) {
    return displayNames;
  }
  try {
    displayNames = new Intl.DisplayNames(['en'], { type: 'region' });
  } catch {
    displayNames = null;
  }
  return displayNames;
}

/**
 * Resolve an ISO country code (alpha-3 or alpha-2, any case) to its English
 * display name. Falls back to the uppercased raw code when the code is unknown
 * or Intl.DisplayNames is unavailable.
 */
export function countryName(code: string): string {
  if (!code) {
    return '';
  }

  const normalized = code.trim().toLowerCase();
  const upperRaw = code.trim().toUpperCase();
  const alpha2 =
    normalized.length === 3 ? ALPHA3_TO_ALPHA2[normalized] : normalized.toUpperCase();

  if (!alpha2 || alpha2.length !== 2) {
    return upperRaw;
  }

  const names = getDisplayNames();
  if (!names) {
    return upperRaw;
  }

  try {
    const resolved = names.of(alpha2);
    // Intl returns the input back unchanged for unknown regions in some engines.
    if (resolved && resolved.toUpperCase() !== alpha2) {
      return resolved;
    }
    return upperRaw;
  } catch {
    return upperRaw;
  }
}
