<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 #30363d;
  padding: 8px 12px;
  border-radius: 6px;
  cursor: pointer;
  margin-right: 15px;

  &.active {
    background-color: #30363d;
  }
}
/* 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 #30363d;
  border-radius: 8px;
  padding: 8px 0;
  box-shadow: 0 8px 24px rgba(0,0,0,0.6);
}

/* 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>