<template>
  <div class="relative" ref="containerRef">
    <Button variant="ghost" size="icon" class="gap-1.5 w-auto px-2" @click="isOpen = !isOpen" :aria-label="t('nav.changeLanguage')">
      <Globe class="w-4 h-4" />
      <span class="text-sm font-medium">{{ currentLang.flag }}</span>
      <ChevronDown class="w-3 h-3 text-muted-foreground/60" />
    </Button>

    <Transition
      enter-active-class="transition duration-150 ease-out"
      enter-from-class="opacity-0 scale-95 translate-y-1"
      enter-to-class="opacity-100 scale-100 translate-y-0"
      leave-active-class="transition duration-100 ease-in"
      leave-from-class="opacity-100 scale-100 translate-y-0"
      leave-to-class="opacity-0 scale-95 translate-y-1"
    >
      <div
        v-if="isOpen"
        class="absolute right-0 top-full mt-2 w-44 bg-card border border-border rounded-xl shadow-xl z-50 overflow-hidden"
      >
        <button
          v-for="lang in languages"
          :key="lang.code"
          class="w-full flex items-center gap-2 px-4 py-2.5 text-sm hover:bg-secondary transition-colors cursor-pointer"
          @click="changeLang(lang.code)"
        >
          <span>{{ lang.flag }}</span>
          <span>{{ lang.label }}</span>
        </button>
      </div>
    </Transition>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from "vue";
import { useRouter, useRoute } from "vue-router";
import { onClickOutside } from "@vueuse/core";
import { Globe, ChevronDown } from "lucide-vue-next";
import Button from "./ui/button.vue";
import { currentLanguage } from "@/i18n";
import { useI18n } from "vue-i18n";

const { t } = useI18n();
const languages = [
  { code: "en", label: "English", flag: "🇬🇧" },
  { code: "ru", label: "Русский", flag: "🇷🇺" },
  { code: "ua", label: "Українська", flag: "🇺🇦" },
  { code: "me", label: "Crnogorski", flag: "🇲🇪" },
];

const router = useRouter();
const route = useRoute();
const isOpen = ref(false);
const containerRef = ref<HTMLElement | null>(null);
const currentLang = computed(
  () => languages.find((l) => l.code === currentLanguage()) ?? languages[0]
);

onClickOutside(containerRef, () => (isOpen.value = false));

const emit = defineEmits(["select"]);

function changeLang(code: string) {
  isOpen.value = false;
  // Push the new language to the current route
  router.push({ 
    name: route.name || undefined, 
    params: { ...route.params, lang: code },
    query: route.query,
    hash: route.hash
  });
  emit("select");
}
</script>
