import i18n from 'i18next'
import { initReactI18next } from 'react-i18next'
import { en } from './locales/en'
import { ru } from './locales/ru'

const resources = {
  ru: { translation: ru },
  en: { translation: en },
}

const STORAGE_KEY = 'tw-lang'
const stored = typeof localStorage !== 'undefined' ? localStorage.getItem(STORAGE_KEY) : null

void i18n.use(initReactI18next).init({
  resources,
  lng: stored ?? 'ru',
  fallbackLng: 'ru',
  interpolation: { escapeValue: false },
})

export function setLanguage(lng: string) {
  localStorage.setItem(STORAGE_KEY, lng)
  void i18n.changeLanguage(lng)
}

export default i18n
