// Translations for the TypeScript side. index.php inlines the active
// language's dictionary (translations/<language>.json, chosen by
// translations/translations.php) as two globals before any app script runs,
// so t() is usable at load time — module-level defaults like exportSettings
// depend on that.
declare const LANGUAGE: string;
declare const TRANSLATIONS: { [key: string]: string };
// For the few keys that are editable defaults: their value in every language.
declare const TRANSLATED_DEFAULTS: { [key: string]: string[] };

type TranslationVars = { [name: string]: string | number };

// The locale for dates and numbers in the page's language (Intl), in one
// place for every formatter (projects.ts, share.ts).
const appLocale = (): string => (LANGUAGE === "sv" ? "sv-SE" : "en-GB");

// Looks up a string and fills its {placeholders}. The key type
// (translationKeys.d.ts, derived from en.json) makes an unknown key a
// compile error; tests/translations covers sv/en parity and the PHP side.
// Should a key still be missing at runtime it comes back as itself, so the
// gap shows on the page rather than failing silently.
const t = (key: TranslationKey, vars?: TranslationVars): string => {
  let text = TRANSLATIONS[key];
  if (text === undefined) {
    console.warn(`translations: missing key "${key}" for language ${LANGUAGE}`);
    return key;
  }
  if (vars) {
    for (const name of Object.keys(vars)) {
      text = text.split("{" + name + "}").join(String(vars[name]));
    }
  }
  return text;
};

// Plural forms: "<key>.one" for exactly one, "<key>.other" otherwise, with
// {count} filled in. Enough for Swedish and English.
const tCount = (key: PluralTranslationKey, count: number, vars?: TranslationVars): string => {
  const form: TranslationKey = count === 1 ? `${key}.one` : `${key}.other`;
  return t(form, { count, ...vars });
};

// Some translations are starting values of inputs the user may edit (the
// export header title, say) and are saved with the arrangement. After a
// language switch, a saved value that still equals the default in any
// language becomes the current language's default; anything else is the
// user's own text and stays. The per-language values come from
// translations.php (TRANSLATED_DEFAULT_KEYS).
const translatedDefault = (key: TranslationKey, saved: string): string =>
  (TRANSLATED_DEFAULTS[key] ?? []).includes(saved) ? t(key) : saved;
