import { en } from './messages';

/**
 * Tiny i18n helper for the host application.
 *
 * Looks up `key` in the active catalog and substitutes any `{name}`
 * placeholders with values from `params`. Returns the key itself if
 * no entry exists, so missing translations are visible in the UI
 * rather than silently rendering empty strings.
 *
 * Mirrors the same helper inside the goods-editor module — kept as a
 * separate file (rather than re-exported from the module) so the host
 * can evolve its i18n independently. If the host ever needs different
 * placeholder syntax, plural rules, or a different message format,
 * it can change here without touching the module.
 *
 * Usage
 * ─────
 *   import { t } from './i18n/t';
 *   t('header.save')                                  // \u2192 'Save'
 *   t('header.logo-home-aria', { app: 'Pawfectly Yours' })
 *
 * Why no library
 * ──────────────
 * react-intl / i18next solve problems we don\u2019t have yet: complex
 * plural rules, gender, number/date formatting, lazy-loaded locale
 * bundles, message extraction tooling. For an en-only catalog with
 * ~25 keys, a 10-line helper is the right size. When we need ICU
 * MessageFormat (e.g. for Polish/Arabic plural rules) or DateTime
 * formatting, we revisit the library question then.
 */

// Single-locale for now. When more land, this becomes a runtime
// dispatch on a locale value \u2014 see the docblock in messages.js for
// the rough shape of that evolution.
const ACTIVE_CATALOG = en;

const PLACEHOLDER_RE = /\{(\w+)\}/g;

export function t(key, params) {
  const raw = ACTIVE_CATALOG[key];
  if (raw === undefined) {
    // Surface the missing key directly so it stands out in the UI
    // ('header.save-button' is obviously not English) rather than
    // silently rendering empty strings that look like a CSS issue.
    return key;
  }
  if (!params) return raw;
  return raw.replace(PLACEHOLDER_RE, (match, name) => {
    const v = params[name];
    return v !== undefined ? String(v) : match;
  });
}
