/**
 * Maps language state to actual language code for API calls
 * Extracts language code from domain (e.g., "fr1.youngengineers.org" -> "fr")
 */
export function getLanguageCode(language: string | undefined, domain?: string): string | undefined {
  // 1. Explicitly requested "default" (standard English)
  if (language === "default") {
    return undefined;
  }

  // 2. Explicitly requested specific language code (e.g., "fr", "he")
  // We ignore "translated" here because it's a UI state that should be 
  // resolved to a real code before reaching this utility.
  if (language && language !== "translated" && language.length > 0) {
    return language;
  }

  // Extract language code from domain (e.g., "fr1.youngengineers.org" -> "fr")
  if (domain) {
    // The whole first label must be the code plus an optional number — anchored
    // at both ends. Matching it as a mere prefix treated every licensee
    // subdomain as a language: "denver" became "de" (German), "israel" "is",
    // "oksanatest" "ok", so ordinary sites silently requested a translation.
    const label = domain.split(".")[0];
    const match = label.match(/^([a-z]{2})\d*$/);
    if (match && match[1]) {
      const code = match[1]; // Returns "fr", "es", "de", etc.
      return code;
    }
  }

  // If no domain or domain doesn't follow pattern, return undefined (no language param)
  return undefined;
}
