import i18n from "i18next";
import { initReactI18next } from "react-i18next";
import en from "./locales/en.json";
import ru from "./locales/ru.json";

export type AppLocale = "ru" | "en";

function langFromSearch(): AppLocale | null {
  const raw = new URLSearchParams(window.location.search).get("lang");
  const v = raw?.trim().toLowerCase();
  if (v === "ru" || v === "en") return v;
  return null;
}

function initialLng(): AppLocale {
  return langFromSearch() ?? "en";
}

i18n.use(initReactI18next).init({
  resources: {
    ru: { translation: ru },
    en: { translation: en },
  },
  lng: initialLng(),
  fallbackLng: "en",
  interpolation: { escapeValue: false },
});

export { i18n };
