<template>
  <div
		  :class="{
		'd-sm-block d-none': !mobileArea,
		'd-sm-none d-block': mobileArea
	}"
		  class="offcanvas__select language my-3 pointer"
  >
    <div class="offcanvas__lang d-flex align-items-center justify-content-as-locale">
      <div class="offcanvas__lang-img" :class="{
        'mr-15': !hideLabel
      }">
        <img :src="localeServices.selectedLanguageFlag" alt="language-flag" class="language-flag"
             @click="toggleDropdown()" />
      </div>
      <div class="offcanvas__lang-wrapper ">
        <span
            v-if="!hideLabel"
		        id="tp-offcanvas-lang-toggle"
		        :class="{
					    'opened': isToggleActive === 'lang',
		        }"
		        class="offcanvas__lang-selected-lang tp-lang-toggle"
		        @click="toggleDropdown()"
        >
          {{ localeServices.selectedLanguageName() }}
        </span>
        <ul
		        :class="`border offcanvas__lang-list tp-lang-list ${isToggleActive === 'lang' ? 'tp-lang-list-open' : ''} ${top ? 'tp-lang-list-top' : ''}`"
        >
          <li
		          v-for="(language) in localeServices.locales()"
		          :key="language.code"
		          :class="{
						'border-0 disabled': language.code === localeServices.selectedLanguage(),
						'd-none': hideLabel && language.code === localeServices.selectedLanguage()
          }"
		          class="btn "
		          @click="changeLocale(language.code, $event)"
          >
            {{ language.name }}
          </li>
        </ul>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import {ref} from 'vue';
import {useLocaleStore} from "@/pinia/useLocaleStore";

const localeServices = useLocaleStore();
const isToggleActive = ref<string>('');
const props = withDefaults(defineProps<{
  mobileArea?: boolean
  hideLabel?: boolean
  top?: boolean
}>(), {
	mobileArea: false,
  hideLabel: false,
  top: false,
});
const toggleDropdown = () => {
	isToggleActive.value = 'lang' === isToggleActive.value ? '' : 'lang';
};

const changeLocale = (language: string, event) => {
	if (language === localeServices.selectedLanguage()) {
		if (event) {
			event.preventDefault();
			return false;
		}
	}
	localeServices.changeLanguage(language);
	toggleDropdown();

  if (process.client) {
    // window && window.location && window.location.reload();
    reloadNuxtApp({force: true});
  }
};
</script>

<style lang="scss">
@use "sass:selector";

@mixin rtl {
	[dir=rtl] & {
		@content;
	}
}

.language-flag {
	width: 24px;
}

.offcanvas__select.language {
	direction: ltr;
}

.justify-content-as-locale {
	justify-content: start;

	@include rtl {
		justify-content: end !important;
	}
}

.tp-lang-list-open.tp-lang-list-top {
  bottom: auto;
  top: 112%;
  height: fit-content;
}
.tp-lang-list-open:not(.tp-lang-list-top) {
  bottom: 112%;
  top: auto;
}

</style>