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";
import ru from "./ru.json";
import rw from "./rw.json";
import kr from "./kr.json";

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

export type I18nKey = keyof typeof es;

export const routeTranslations = {
  news: {
    es: "noticias",
    en: "news",
    fr: "informations",
    he: "חדשות",
    uk: "noticias",
    pt: "noticias",
    ru: "новости",
    rw: "amakuru",
    kr: "nouvel",
  },
  editorial: {
    es: "editorial",
    en: "editorial",
    fr: "editorial",
    he: "מאמר",
    uk: "editorial",
    pt: "editorial",
    ru: "редакция",
    rw: "editorial",
    kr: "editorial",
  },
  formulario: {
    es: "formulario",
    en: "form",
    fr: "formulaire",
    he: "טופס",
    uk: "форма",
    pt: "formulario",
    ru: "форма",
    rw: "formulaire",
    kr: "fòm",
  },
  terminos: {
    es: "terminos",
    en: "terms",
    fr: "termes",
    he: "תנאים",
    uk: "terminos",
    pt: "termos",
    ru: "условия",
    rw: "terminos",
    kr: "tèm",
  },
} as const;

export function getRouteKeyFromSlug(slug: string): keyof typeof routeTranslations {
  for (const [key, translations] of Object.entries(routeTranslations)) {
    const values = Object.values(translations) as string[];
    if (values.includes(slug)) {
      return key as keyof typeof routeTranslations;
    }
  }
  return "news";
}

export function getLocalizedRoute(route: keyof typeof routeTranslations, locale: string | undefined): string {
  const l = (locale in routeTranslations[route] ? locale : "es") as Locale;
  return routeTranslations[route][l as keyof (typeof routeTranslations)[typeof route]] || routeTranslations[route]["en" as keyof (typeof routeTranslations)[typeof route]];
}

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);
  };
}
