<template>
  <div class="dropdown select-language-dropdown">
    <a
      v-if="selectedLang?.length"
      :title="$t(selectedLang)"
      class="nav-link"
      :class="$attrs.toggleClass"
      href="#"
      role="button"
      data-toggle="dropdown"
      aria-haspopup="true"
      aria-expanded="false"
      data-bs-toggle="dropdown"
      
    >
      <!-- <svg class="icon icon-Component-240--1"><use xlink:href="#icon-Component-240--1"></use></svg> -->
      <span> {{ $t(selectedLang) }} </span>
    </a>

    <div
      class="dropdown-menu text-right"
      aria-labelledby="selected-language-dropdown"
    >
      <button
        :title="$t('Fa')"
        class="dropdown-item"
        type="button"
        @click.prevent="changeLanguage('fa')"
      >
        {{ $t("Fa") }}
      </button>
      <button
        :title="$t('En')"
        class="dropdown-item"
        type="button"
        @click.prevent="changeLanguage('en')"
      >
        {{ $t("En") }}
      </button>
      <button
        :title="$t('Ar')"
        class="dropdown-item"
        type="button"
        @click.prevent="changeLanguage('ar')"
      >
        {{ $t("Ar") }}
      </button>
    </div>
  </div>
</template>

<script>
import { mapActions, mapState } from "pinia";
import { useCommonStore } from "~/stores/commonStore";
import { useAuthStore } from "~/stores/authStore";

// import i18next from "i18next";
// import I18NextVue from "i18next-vue";

export default {
  data() {
    return {
      selectedLang: "",
    };
  },
  mounted() {
    this.selectedLang = this.upperCaseFirstLetter(this.langGetter ?? "fa");

    this.langSetter(this.langGetter ?? "fa");
    // i18next.changeLanguage(this.langGetter ?? "fa");

    // i18next.changeLanguage("de", (err, t) => {
    //   if (err) return console.log("Something went wrong loading", err);
    //   t("key"); // Use the translation function
    // });
  },
  computed: {
    ...mapState(useCommonStore, ["langGetter"]),
  },
  methods: {
    ...mapActions(useCommonStore, ["langSetter"]),
    changeLanguage(selectedLang) {
      const { setLocale } = useI18n()
      const dir = selectedLang == "en" ? "ltr" : "rtl";

      document.getElementsByTagName("html")[0].dir = dir;
      document.getElementsByTagName("html")[0].lang = selectedLang;

      this.selectedLang = this.upperCaseFirstLetter(selectedLang);
      this.langSetter(selectedLang);
      setLocale(selectedLang)
      // i18next.changeLanguage(selectedLang);
    },
    upperCaseFirstLetter(selectedLang) {
      return selectedLang.charAt(0).toUpperCase() + selectedLang.slice(1);
    },
  },
};
</script>

<style scoped lang="scss"></style>
