/**
 * The counted noun, in the form the number actually requires.
 *
 * Arabic does not have one plural. «منهج» after a number changes with the number, and getting it wrong
 * is the first thing a reader notices:
 *
 *     1   منهج واحد        one
 *     2   منهجين           two      (a dual form, which English does not have at all)
 *     3-10 مناهج           few      (the broken plural)
 *     11+ منهجاً            many     (singular again, in the accusative)
 *
 * English needs two forms and would be fine with a bolted-on «s»; Arabic would not, and a site that
 * prints «4 منهج» on its own front page reads as one nobody proofread. `Intl.PluralRules` knows these
 * categories for every language, so the rule is not written here — only the words are, and they come
 * from the CMS so an editor can set them per noun.
 *
 * A form left empty falls back to the next most general one that is filled, ending at `other`. So an
 * editor who fills only «مناهج» gets that everywhere rather than an empty space, and English, which
 * only ever asks for `one` and `other`, needs no Arabic-shaped thinking at all.
 */

export type CountForms = {
  one?: string | null
  two?: string | null
  few?: string | null
  many?: string | null
  other?: string | null
}

/** The order to fall back through, per category, most specific first. */
const FALLBACK: Record<Intl.LDMLPluralRule, (keyof CountForms)[]> = {
  zero: ['other', 'many', 'few', 'one'],
  one: ['one', 'other', 'few', 'many'],
  two: ['two', 'few', 'other', 'many', 'one'],
  few: ['few', 'other', 'many', 'two', 'one'],
  many: ['many', 'other', 'few', 'one'],
  other: ['other', 'few', 'many', 'one'],
}

export function countWord(n: number, forms: CountForms, locale: 'ar' | 'en'): string {
  let category: Intl.LDMLPluralRule = 'other'
  try {
    category = new Intl.PluralRules(locale === 'ar' ? 'ar-EG' : 'en-GB').select(n)
  } catch {
    // An environment with no full ICU answers «other» for everything; the fallback chain still
    // finds a word, so the page prints something sensible rather than nothing.
  }
  for (const key of FALLBACK[category]) {
    const v = forms[key]
    if (v && v.trim()) return v.trim()
  }
  return ''
}

/** «4 مناهج» / «1 course» — the figure and its word, ready to print. */
export function counted(n: number, forms: CountForms, locale: 'ar' | 'en'): string {
  const w = countWord(n, forms, locale)
  return w ? `${n} ${w}` : String(n)
}
