import { en } from './messages';

/**
 * Tiny i18n helper (S23).
 *
 * 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.
 *
 * Single-locale for now — `en` is the only catalog. Adding more is a
 * matter of importing them here and exposing a `setLocale` hook (or
 * reading from the browser's `navigator.language`); the call sites of
 * `t()` don't need to change.
 *
 * Usage:
 *   import { t } from '@/i18n/t';
 *   t('header.save-button')                          // → 'Save'
 *   t('toast.cart-items', { count: 3, plural: 'items' })  // simple sub
 *
 * Why not react-intl / i18next? At this scale a flat catalog plus a
 * 10-line helper covers the actual feature surface (button labels,
 * toasts, modal copy) without pulling in a dependency that has its own
 * upgrade story, message-format dialect, and bundle weight. If we hit
 * full ICU MessageFormat needs (gender, complex plurals, RTL with
 * inline number formatting), revisit the library question then.
 */

// Currently we only ship one catalog. If/when more land, this would
// become a dispatch on a runtime locale value.
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.
    return key;
  }
  if (!params) return raw;
  return raw.replace(PLACEHOLDER_RE, (match, name) => {
    const v = params[name];
    return v !== undefined ? String(v) : match;
  });
}
