import i18n, { type i18n as I18nInstance } from "i18next";
import { initReactI18next } from "react-i18next";

import en from "@/locales/en.json";
import ar from "@/locales/ar.json";

export * from "./constants";
import { DEFAULT_LANG } from "./constants";

export const resources = {
    ar: { translation: ar },
    en: { translation: en },
};

const baseOptions = {
    fallbackLng: DEFAULT_LANG,
    interpolation: { escapeValue: false },
    resources,
    initAsync: false, // تهيئة متزامنة: الترجمة جاهزة في أول تصيير على الخادم
    initImmediate: false,
    react: { useSuspense: false },
} as const;

/**
 * الخادم: نسخة مستقلة لكل طلب حتى لا تتسرّب لغة مستخدم إلى آخر.
 * المتصفح: النسخة العامة الافتراضية نفسها التي يعتمد عليها الكود الأصلي
 * (مثل services/ivoryProductsService.ts الذي يقرأ i18n.language مباشرة).
 */
export function getI18n(lng: string): I18nInstance {
    if (typeof window === "undefined") {
        const instance = i18n.createInstance();
        instance.use(initReactI18next).init({ ...baseOptions, lng });
        return instance;
    }
    if (!i18n.isInitialized) {
        i18n.use(initReactI18next).init({ ...baseOptions, lng });
    } else if (i18n.language !== lng) {
        i18n.changeLanguage(lng);
    }
    return i18n;
}

export default i18n;
