<template>
  <div class="switcher" ref="switcherRef">
    <div
        @click="setSwitcherVisible(!isSwitcherVisible)"
        class="switcher__button"
        :class="[{ active: isSwitcherVisible }]"
    >
      <img
          v-if="currentLocale"
          :src="currentLocale.flag"
          :alt="currentLocale.code"
      >
      <language-switcher-skeleton v-else />
    </div>
    <div
        class="switcher__menu"
        :class="[{active: isSwitcherVisible}]"
    >
      <img
        class="switcher__menu-button"
        v-for="locale of locales"
        :key="locale.code"
        @click="switchLanguage(locale.code)"
        :src="locale.flag"
        :alt="locale.code"
      />
    </div>
  </div>
</template>

<script setup>
import {computed, ref} from "vue";
import {onClickOutside} from "@vueuse/core";
import {useLanguageStore} from "@/stores/languages.js";
import {useLanguageSwitch} from "@/composables/languages/index.js";
import LanguageSwitcherSkeleton from "@/components/skeletons/ui/language-switcher-skeleton.vue";

const languageStore = useLanguageStore()

const locales = computed(() => languageStore.languages)
const currentLocale = computed(() => languageStore.currentLocale)

const isSwitcherVisible = ref(false)
const setSwitcherVisible = (state) => {
  isSwitcherVisible.value = state
}

const switcherRef = ref(null)
onClickOutside(switcherRef, () => isSwitcherVisible.value = false)

const { switchLanguage } = useLanguageSwitch()
</script>

<style lang="scss" scoped>
.switcher {
  position: relative;
  z-index: 1;
  width: 52px;
  flex-shrink: 0;

  &__button {
      width: 100%;
    cursor: pointer;
    display: flex;
    gap: 5px;
    border: 1px solid $accent;
    background-color: #ddd9ef;
    padding: 5px;
    border-radius: $default_border_radius;
    transition: 0.2s;

    @include hover {
      background-color: $accent;
    }

    &.active {
      background-color: $accent;
    }

    & img {
      width: 100%;
    }
  }

  &__menu {
    position: absolute;
    z-index: 3;
    top: 110%;
    left: 50%;
    transform: translateX(-50%);
    border: 0 solid $accent;
    display: flex;
    flex-direction: column;
    width: 100%;
    max-height: 0;
    overflow: hidden;
    transition: 0.3s;
    border-radius: $default_border_radius;

    &.active {
      max-height: 1000px;
      border: 1px solid $accent;
    }

    &-button {
      width: 100%;
      cursor: pointer;
      padding: 5px 8px;
      background-color: #ddd9ef;
      transition: 0.1s;

      &:first-child {
        padding-top: 10px;
      }
      &:last-child {
        padding-bottom: 10px;
      }

      &:hover {
        background-color: $accent;
      }
    }
  }
}
</style>