/**
 * Helpers for the `translation_family` payloads returned by the admin API.
 *
 * A family holds one row per available language. A row whose language has no
 * publishable content of its own falls back to the global copy (usually global
 * English), so more than one row can end up describing the same language code.
 * Keying such a family by language blindly lets the fallback row overwrite the
 * row that really belongs to that language — which is how a franchise edit
 * (e.g. age range "6-11") disappeared behind the global value ("6-10").
 */

export const translationRowLanguage = (item, fallback = "en") =>
  item?.language || fallback;

/**
 * Higher rank wins. A row carrying content authored in its own language beats a
 * fallback row, and a franchise copy beats the global copy it was adopted from.
 */
export const rankTranslationRow = (item) => {
  if (!item) return -1;

  const code = String(translationRowLanguage(item)).toLowerCase();
  const displayed = String(item.displayed_language || code).toLowerCase();

  let rank = 0;
  if (displayed === code) rank += 2;
  if (item.franchise_translation_exists) rank += 1;
  return rank;
};

/**
 * Keep a single, most authoritative row per language code, preserving order.
 */
export const dedupeTranslationFamily = (family) => {
  const byCode = new Map();

  (Array.isArray(family) ? family : []).forEach((item) => {
    if (!item) return;
    const code = translationRowLanguage(item);
    const existing = byCode.get(code);
    if (existing && rankTranslationRow(existing) >= rankTranslationRow(item)) return;
    byCode.set(code, item);
  });

  return Array.from(byCode.values());
};
