import languageMapping from "./language-mapping.json";

export interface LanguageInfo {
  countryCode: string;
  name: string;
}

export const LANGUAGE_MAPPING: Record<string, LanguageInfo> = languageMapping as Record<string, LanguageInfo>;

/**
 * Gets the flag URL for a given language code using flagcdn.com.
 * Fallbacks to GB flag if the code is not found.
 */
export function getFlagByLanguageCode(code: string | null | undefined): string {
  if (!code || code === "default" || code === "en") {
    return `https://flagcdn.com/w80/gb.png`;
  }
  
  const normalizedCode = code.toLowerCase();
  const info = LANGUAGE_MAPPING[normalizedCode];
  
  if (info) {
    return `https://flagcdn.com/w80/${info.countryCode.toLowerCase()}.png`;
  }
  
  // If not in mapping, try using the code itself as country code as a last resort
  // but only if it's 2 characters
  if (normalizedCode.length === 2) {
    return `https://flagcdn.com/w80/${normalizedCode}.png`;
  }

  return `https://flagcdn.com/w80/gb.png`;
}

/**
 * Gets the display name for a given language code.
 */
export function getLanguageName(code: string | null | undefined): string {
  if (!code || code === "default" || code === "en") {
    return LANGUAGE_MAPPING["en"].name;
  }
  
  const normalizedCode = code.toLowerCase();
  return LANGUAGE_MAPPING[normalizedCode]?.name || "Translated";
}
