/**
 * pickLang — read the locale-preferred field with EN fallback.
 *
 * The bureau stores every narrative as a pair: `field` (EN) and
 * `field_pt_br` (Brazilian Portuguese). UI components call this helper to
 * surface the correct one based on the request locale.
 *
 *  - locale "pt-br" or "pt"  → prefer PT-BR, fall back to EN
 *  - locale "en"              → prefer EN, fall back to PT-BR
 *
 * Empty / whitespace-only strings are treated as missing so a partial row
 * still surfaces the language that has content.
 */

export type Locale = "pt-br" | "pt" | "en" | string | null | undefined;

function isPt(locale: Locale): boolean {
  return locale === "pt-br" || locale === "pt";
}

function nonEmpty(s: string | null | undefined): string | null {
  if (typeof s !== "string") return null;
  const t = s.trim();
  return t.length > 0 ? s : null;
}

export function pickLang(
  en: string | null | undefined,
  pt_br: string | null | undefined,
  locale: Locale,
): string | null {
  const enValid = nonEmpty(en);
  const ptValid = nonEmpty(pt_br);
  if (isPt(locale)) return ptValid ?? enValid;
  return enValid ?? ptValid;
}
