import { createSlice, PayloadAction } from "@reduxjs/toolkit";
import i18next from "i18next";
import { initReactI18next } from "react-i18next";
import HttpApi from "i18next-http-backend";
import cookies from "js-cookie";
import LanguageDetector from "i18next-browser-languagedetector";

i18next
  .use(HttpApi)
  .use(LanguageDetector)
  .use(initReactI18next)
  .init({
    supportedLngs: ["en", "ru"],
    fallbackLng: "en",
    debug: false,
    // Options for language detector
    detection: {
      order: ["cookie", "navigator"],
      caches: ["cookie"],
    },
    // react: { useSuspense: false },
    backend: {
      loadPath: "/assets/locales/{{lng}}/translation.json",
    },
  });



interface LanguageState {
  currentLang: string;
}

const initialState: LanguageState = {
  currentLang: '',
};

export const languageSlice = createSlice({
  name: "language",
  initialState,
  reducers: {
    handleChangeLanguage(state, action: PayloadAction<string>) {
      i18next.changeLanguage(action.payload)
      state.currentLang = action.payload
    },
  },
});


export default languageSlice.reducer;

