import i18next, { type i18n } from "i18next"; import LanguageDetector from "i18next-browser-languagedetector"; import { initReactI18next } from "react-i18next"; let hasInit = false; export const initI18Next = () => { if (hasInit) return i18next; i18next .use(LanguageDetector) .use(initReactI18next) .init({ detection: { order: ["navigator"] }, debug: false, fallbackLng: "es", interpolation: { escapeValue: false }, }); hasInit = true; return i18next; }; /** * Registra dinámicamente traducciones de un módulo. * * Cada módulo tendrá su propio namespace. * * idempotente: si el bundle ya existe, no se vuelve a añadir. */ export const registerTranslations = ( moduleName: string, locale: string, resources: Record ): void => { if (!hasInit) { throw new Error("i18n not initialized. Call initI18Next() first."); } const ns = moduleName; const alreadyExists = i18next.hasResourceBundle(locale, ns); if (!alreadyExists) { i18next.addResourceBundle(locale, ns, resources, true, true); } }; /** * Acceso al `t()` global por si se necesita en librerías de backend. */ export const t = (...args: Parameters) => { if (!hasInit) { throw new Error("i18n not initialized. Call initI18Next() first."); } return i18next.t(...args); };