<script setup lang="ts">
import { computed } from "vue";
import Button from "./ui/Button.vue";
import DropdownMenu from "./ui/DropdownMenu.vue";
import DropdownMenuTrigger from "./ui/DropdownMenuTrigger.vue";
import DropdownMenuContent from "./ui/DropdownMenuContent.vue";
import DropdownMenuItem from "./ui/DropdownMenuItem.vue";
import type { Language } from "../types";

export type { Language };

const props = defineProps<{
  currentLocale: string | null;
  languages: Language[];
  onSwitch?: (code: string) => void;
}>();

const currentLabel = computed(() => {
  const found = props.languages.find((l) => l.code === props.currentLocale);
  return found?.name ?? props.currentLocale ?? "";
});
</script>

<template>
  <DropdownMenu>
    <DropdownMenuTrigger as-child>
      <Button type="button" variant="outline">
        {{ currentLabel }}
        <svg
          class="ml-1 h-3.5 w-3.5 opacity-60"
          fill="none"
          viewBox="0 0 24 24"
          stroke="currentColor"
        >
          <path
            stroke-linecap="round"
            stroke-linejoin="round"
            stroke-width="2"
            d="M19 9l-7 7-7-7"
          />
        </svg>
      </Button>
    </DropdownMenuTrigger>
    <DropdownMenuContent align="end">
      <DropdownMenuItem
        v-for="lang in languages"
        :key="lang.code"
        :class="[
          lang.code === currentLocale ? 'font-medium' : '',
          !lang.is_active ? 'opacity-60' : '',
        ]"
        @click="props.onSwitch?.(lang.code)"
      >
        {{ lang.name }}{{ !lang.is_active ? " (inactive)" : "" }}
      </DropdownMenuItem>
    </DropdownMenuContent>
  </DropdownMenu>
</template>
