/**
 * Country Flags Utilities
 * Converte country code in flag emoji
 */

/**
 * Converte country code ISO 3166-1 alpha-2 in flag emoji
 * Es: "IT" => "🇮🇹", "US" => "🇺🇸"
 */
export function getFlagEmoji(countryCode: string | null | undefined): string {
  if (!countryCode || countryCode.length !== 2) {
    return '🏳️'; // Flag bianca per unknown
  }
  
  const codePoints = countryCode
    .toUpperCase()
    .split('')
    .map(char => 127397 + char.charCodeAt(0));
  
  return String.fromCodePoint(...codePoints);
}

/**
 * Mappa nomi paesi comuni (fallback se API non ritorna country code)
 */
export const COUNTRY_CODE_MAP: Record<string, string> = {
  'Italy': 'IT',
  'United States': 'US',
  'Russia': 'RU',
  'China': 'CN',
  'Germany': 'DE',
  'France': 'FR',
  'United Kingdom': 'GB',
  'Spain': 'ES',
  'Brazil': 'BR',
  'Japan': 'JP',
  'India': 'IN',
  'Canada': 'CA',
  'Australia': 'AU',
  'Netherlands': 'NL',
  'Switzerland': 'CH',
  'Sweden': 'SE',
  'Poland': 'PL',
  'Ukraine': 'UA',
  'Romania': 'RO',
  'Belgium': 'BE',
};

/**
 * Ottieni flag da nome paese o country code
 */
export function getFlag(country: string | null | undefined, countryCode?: string | null): string {
  if (countryCode) {
    return getFlagEmoji(countryCode);
  }
  
  if (country && COUNTRY_CODE_MAP[country]) {
    return getFlagEmoji(COUNTRY_CODE_MAP[country]);
  }
  
  return '🏳️';
}
