import es from "./es.json";
import en from "./en.json";
import fr from "./fr.json";
import he from "./he.json";
import uk from "./uk.json";
import pt from "./pt.json";

const dictionaries = { es, en, fr, he, uk, pt } as const;
export type Locale = keyof typeof dictionaries;

// Optional: type-safe keys from the default dictionary
export type I18nKey = keyof typeof es;

export function t(
  locale: string | undefined,
  key: I18nKey,
  vars?: Record<string, string | number>
) {
  const l = (locale in dictionaries ? locale : "es") as Locale;

  // fallback chain: requested locale -> default locale -> key itself
  const template =
    dictionaries[l][key] ??
    dictionaries.es[key] ??
    String(key);

  if (!vars) return template;

  // simple interpolation: "Hello {name}"
  return template.replace(/\{(\w+)\}/g, (_, name) =>
    vars[name] === undefined ? `{${name}}` : String(vars[name])
  );
}

export function createTranslator(locale: string | undefined) {
  return function tl(key: I18nKey, vars?: Record<string, string | number>) {
    return t(locale, key, vars);
  };
}