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

const STORAGE_KEY = "dailymeals.lang";

function detectLanguage(): string {
  const stored = localStorage.getItem(STORAGE_KEY);
  if (stored === "en" || stored === "pl") {
    return stored;
  }
  return navigator.language.toLowerCase().startsWith("pl") ? "pl" : "en";
}

const initialLanguage = detectLanguage();
document.documentElement.lang = initialLanguage;

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

i18n.on("languageChanged", (lng) => {
  localStorage.setItem(STORAGE_KEY, lng);
  document.documentElement.lang = lng;
});

export default i18n;
