<script setup>
import { ref } from 'vue'

const dropdownVisible = ref(false);

const toggleDropdown = () => {
    dropdownVisible.value = !dropdownVisible.value;
}

const menuContainer = ref(null);

const handleClickOutside = (e) => {
    if (menuContainer.value && !menuContainer.value.contains(e.target)) {
    dropdownVisible.value = false
  }
}

onMounted(() => {
  document.addEventListener('click', handleClickOutside)
})

onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside)
})


// i18n
const { locales, setLocale, locale } = useI18n()

const changeLocale = (lang) => {
  setLocale(lang.code);
  dropdownVisible.value = false
}
</script>

<template>
<div class="menu-container" ref="menuContainer">
  <button class="menu-button" @click="toggleDropdown">{{ $t("site_options.language_selector.dropdown") }} ▾</button>

  <Transition name="dropdown">
    <div class="dropdown" v-show="dropdownVisible">
      <div class="section">
        <div :class="{'menu-item': true, 'active': locale === loc.code}"
         v-for="loc in locales" @click="changeLocale(loc)">
          {{ $t('locales.' + loc.code) }}
        </div>
      </div>
    </div>
  </Transition>
</div>
</template>

<style lang="scss" scoped>
.menu-button {
  background: var(--color-background-fore);
  color: var(--color-text);
  font-size: 1em;
border: 1px solid var(--color-border-color);
   padding: 8px 12px;
   border-radius: 0;
   cursor: pointer;
   margin-right: 15px;

  &.active {
    background-color: var(--color-selected);
  }
}
/* Dropdown transitions */
.dropdown-enter-active, .dropdown-leave-active {
  transition: opacity 0.2s ease, transform 0.2s ease;
}
.dropdown-enter-from, .dropdown-leave-to {
  opacity: 0;
  transform: translateY(-8px);
}

.dropdown {
 z-index: 10;
  position: absolute;
  top: 50px;
  right: 110px;
  margin-right: 10px;
  background: var(--color-background-fore);
border: 1px solid var(--color-border-color);
   border-radius: 0;
   padding: 8px 0;
   box-shadow: 4px -4px 0px 0px rgba(0,0,0,0.3);
   border-left: 2px solid var(--color-border-color);

   &::before {
     content: "▸";
     display: block;
     position: absolute;
     left: -16px;
     top: -2px;
     font-size: 14px;
     color: var(--color-border-color);
   }
}

/* Items */
.menu-item {
  padding: 8px 16px;
  color: var(--color-text);
  cursor: pointer;
  display: flex;
  gap: 10px;
  align-items: center;

  &.active {
    background: var(--color-selected);
  }
}

.menu-item:hover {
  background: var(--color-hover);
}
</style>