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

export const LOCALE_KEY = "locale";
const stored =
  typeof localStorage !== "undefined" ? localStorage.getItem(LOCALE_KEY) : null;
const fallback = "en";

void i18n.use(initReactI18next).init({
  resources: { en: { translation: en }, sv: { translation: sv } },
  lng: stored ?? fallback,
  fallbackLng: fallback,
  interpolation: { escapeValue: false },
});

function syncHtmlLang(lng: string) {
  if (typeof document !== "undefined") {
    document.documentElement.lang = lng.startsWith("sv") ? "sv" : "en";
  }
}

i18n.on("languageChanged", syncHtmlLang);
syncHtmlLang(i18n.language);

export default i18n;
