// src/lib/sites/options.ts — option lists for the add-site comboboxes.
// Derived from the canonical Google Ads geo/language data. Languages and
// countries are INDEPENDENT axes (language_id != location_id): a language
// carries NO flag — only countries do.
import {
  countryByCode,
  GOOGLE_ADS_COUNTRIES,
  GOOGLE_ADS_LANGUAGES,
  normalizeLanguageCode,
} from "@/lib/geo/google-ads";

export interface ComboOption {
  value: string;
  label: string;
}

const byName = (a: { name: string }, b: { name: string }) =>
  a.name.localeCompare(b.name);

/**
 * All 51 Google Ads languages. value = Google Ads language code (e.g. "fr",
 * "zh_CN"), label = English name. NO flag — a language is not a country.
 */
export const LANGUAGE_OPTIONS: ComboOption[] = [...GOOGLE_ADS_LANGUAGES]
  .sort(byName)
  .map((l) => ({ value: l.code, label: l.name }));

/**
 * All 250 Google Ads countries. value = ISO 3166-1 alpha-2, label = name only.
 * The flag is derived from `value` by consumers via `<Flag code={value} />` —
 * never baked into the label (which flows into inputs, chips and aria-labels).
 */
export const COUNTRY_OPTIONS: ComboOption[] = [...GOOGLE_ADS_COUNTRIES]
  .sort(byName)
  .map((c) => ({ value: c.code, label: c.name }));

/** Display label for a stored language code (handles legacy "zh"). */
export function languageLabel(code: string): string {
  const canonical = normalizeLanguageCode(code);
  return canonical
    ? (GOOGLE_ADS_LANGUAGES.find((l) => l.code === canonical)?.name ?? code)
    : code;
}

/** Display name (WITHOUT flag) for a stored alpha-2 country code. */
export function countryLabel(code: string): string {
  const c = countryByCode.get(code.trim().toUpperCase());
  return c ? c.name : code;
}

/**
 * Options de langue du SITE : langue principale + additionnelles, dédupées,
 * principale en tête. value = code, label = languageLabel(code). Pas de drapeau
 * (une langue n'est pas un pays). `primaryLanguage` existe toujours → au moins
 * une option.
 */
export function siteLanguageOptions(site: {
  primaryLanguage: string;
  languages?: string[] | null;
}): ComboOption[] {
  const codes: string[] = [];
  for (const c of [site.primaryLanguage, ...(site.languages ?? [])]) {
    if (c && !codes.includes(c)) codes.push(c);
  }
  return codes.map((c) => ({ value: c, label: languageLabel(c) }));
}

/**
 * Options de pays du SITE : `targetCountries` mappés (value = alpha-2,
 * label = countryLabel = nom seul, drapeau via le combobox `withFlag`).
 * Repli sur l'univers (COUNTRY_OPTIONS) si `targetCountries` vide/absent, pour
 * ne pas bloquer la saisie sur un site pas encore configuré.
 */
export function siteCountryOptions(site: {
  targetCountries?: string[] | null;
}): ComboOption[] {
  const codes = site.targetCountries ?? [];
  if (codes.length === 0) return COUNTRY_OPTIONS;
  return codes.map((c) => ({ value: c, label: countryLabel(c) }));
}
