/**
 * Country → flag emoji helpers.
 *
 * Flag emojis are built from two "regional indicator" characters derived from a
 * country's ISO 3166-1 alpha-2 code (e.g. IT -> 🇮🇹). No images are used.
 *
 * Note: on most platforms (iOS, Android, macOS) these render as real flags.
 * Some Windows browsers don't ship flag glyphs and will show the two-letter
 * code instead — that's a platform font limitation, not a bug here.
 */

// Uppercase country name (and common aliases) -> ISO 3166-1 alpha-2 code.
const COUNTRY_TO_ISO: Record<string, string> = {
  "UNITED STATES": "US",
  "UNITED STATES OF AMERICA": "US",
  USA: "US",
  "U.S.A.": "US",
  US: "US",
  AMERICA: "US",
  "UNITED KINGDOM": "GB",
  UK: "GB",
  "U.K.": "GB",
  "GREAT BRITAIN": "GB",
  ENGLAND: "GB",
  SCOTLAND: "GB",
  WALES: "GB",
  "UNITED ARAB EMIRATES": "AE",
  UAE: "AE",
  CANADA: "CA",
  AUSTRALIA: "AU",
  "NEW ZEALAND": "NZ",
  IRELAND: "IE",
  ITALY: "IT",
  SPAIN: "ES",
  FRANCE: "FR",
  GERMANY: "DE",
  PORTUGAL: "PT",
  NETHERLANDS: "NL",
  HOLLAND: "NL",
  BELGIUM: "BE",
  SWITZERLAND: "CH",
  AUSTRIA: "AT",
  GREECE: "GR",
  CYPRUS: "CY",
  MALTA: "MT",
  POLAND: "PL",
  CZECHIA: "CZ",
  "CZECH REPUBLIC": "CZ",
  SLOVAKIA: "SK",
  HUNGARY: "HU",
  ROMANIA: "RO",
  BULGARIA: "BG",
  CROATIA: "HR",
  SERBIA: "RS",
  SLOVENIA: "SI",
  SWEDEN: "SE",
  NORWAY: "NO",
  DENMARK: "DK",
  FINLAND: "FI",
  ICELAND: "IS",
  ESTONIA: "EE",
  LATVIA: "LV",
  LITHUANIA: "LT",
  UKRAINE: "UA",
  RUSSIA: "RU",
  TURKEY: "TR",
  TÜRKIYE: "TR",
  ISRAEL: "IL",
  "SAUDI ARABIA": "SA",
  QATAR: "QA",
  KUWAIT: "KW",
  BAHRAIN: "BH",
  OMAN: "OM",
  JORDAN: "JO",
  LEBANON: "LB",
  EGYPT: "EG",
  MOROCCO: "MA",
  TUNISIA: "TN",
  ALGERIA: "DZ",
  "SOUTH AFRICA": "ZA",
  NIGERIA: "NG",
  KENYA: "KE",
  GHANA: "GH",
  INDIA: "IN",
  PAKISTAN: "PK",
  BANGLADESH: "BD",
  "SRI LANKA": "LK",
  NEPAL: "NP",
  CHINA: "CN",
  "HONG KONG": "HK",
  TAIWAN: "TW",
  JAPAN: "JP",
  "SOUTH KOREA": "KR",
  KOREA: "KR",
  SINGAPORE: "SG",
  MALAYSIA: "MY",
  INDONESIA: "ID",
  THAILAND: "TH",
  VIETNAM: "VN",
  PHILIPPINES: "PH",
  MEXICO: "MX",
  BRAZIL: "BR",
  ARGENTINA: "AR",
  CHILE: "CL",
  COLOMBIA: "CO",
  PERU: "PE",
  URUGUAY: "UY",
  ECUADOR: "EC",
  "COSTA RICA": "CR",
  PANAMA: "PA",
};

/**
 * Extract the country portion from an author string like "NAME, COUNTRY".
 * Falls back to the whole trimmed string when there is no comma.
 */
export function extractCountry(author: string | undefined | null): string {
  if (!author) return "";
  const parts = author.split(",");
  return parts[parts.length - 1].trim();
}

/** Convert an ISO 3166-1 alpha-2 code (e.g. "IT") to a flag emoji. */
function isoToFlag(iso: string): string {
  if (!/^[A-Za-z]{2}$/.test(iso)) return "";
  const base = 0x1f1e6; // regional indicator "A"
  return iso
    .toUpperCase()
    .split("")
    .map((c) => String.fromCodePoint(base + (c.charCodeAt(0) - 65)))
    .join("");
}

/** Resolve a country name (or 2-letter ISO code) to its ISO 3166-1 alpha-2 code. */
export function getIsoCode(country: string | undefined | null): string {
  if (!country) return "";
  const name = country.trim().toUpperCase();
  if (!name) return "";
  // Direct match, or a 2-letter ISO code passed straight in.
  return COUNTRY_TO_ISO[name] || (/^[A-Z]{2}$/.test(name) ? name : "");
}

/**
 * Get the flag emoji for a country name (or a "NAME, COUNTRY" author string).
 * Returns "" when the country can't be matched.
 */
export function getFlagEmoji(country: string | undefined | null): string {
  const iso = getIsoCode(country);
  return iso ? isoToFlag(iso) : "";
}

/**
 * Get a flagcdn.com image URL for a country name (or a "NAME, COUNTRY" string),
 * matching the pattern already used in the app (getFlagByLanguageCode).
 * Renders as a real flag on every platform, including Windows. Returns "" when
 * the country can't be matched.
 */
export function getFlagUrl(
  country: string | undefined | null,
  width: "w20" | "w40" | "w80" = "w40"
): string {
  const iso = getIsoCode(country);
  return iso ? `https://flagcdn.com/${width}/${iso.toLowerCase()}.png` : "";
}
