<template>
  <div v-if="langs.length" class="vm-data-i18n-lang">
    <DropdownMenu :modal="false">
      <DropdownMenuTrigger as-child>
        <button
          type="button"
          class="vm-crud-toolbar__btn is-ghost vm-data-i18n-lang__btn"
          :disabled="switching"
          :title="
            crudFormat(
              crudLabel('dataI18nTargetLang', crud.dict.label),
              targetCurrent?.name || targetCode,
            )
          "
        >
          <span class="vm-data-i18n-lang__flag" aria-hidden="true">
            {{ targetCurrent?.flag || '🏳️' }}
          </span>
          {{ crudLabel('dataI18nSwitch', crud.dict.label) }}
        </button>
      </DropdownMenuTrigger>
      <DropdownMenuContent align="start" class="vm-data-i18n-lang__menu">
        <DropdownMenuItem
          v-for="lang in langs"
          :key="lang.value"
          class="vm-data-i18n-lang__item"
          :class="{ 'is-active': targetCode === lang.value }"
          :disabled="switching"
          @click="switchTarget(lang.value)"
        >
          <span class="vm-data-i18n-lang__flag" aria-hidden="true">
            {{ lang.flag || '🏳️' }}
          </span>
          <span class="vm-data-i18n-lang__label">{{ lang.name || lang.label }}</span>
        </DropdownMenuItem>
      </DropdownMenuContent>
    </DropdownMenu>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue'
import { useVome } from '../hooks/useVome'
import { useCrud } from './useCrud'
import { crudFormat, crudLabel } from './style'
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from '../components/ui/dropdown-menu'
import {
  loadEnabledLangOptions,
  type DataI18nLangOption,
} from './data-i18n'

defineOptions({ name: 'vm-data-i18n-lang' })

const crud = useCrud()
const { service } = useVome()
const langs = ref<DataI18nLangOption[]>([])
const switching = ref(false)

const targetCode = computed({
  get: () => crud.dataI18nLangCode?.value || '',
  set: (v: string) => {
    if (crud.dataI18nLangCode) crud.dataI18nLangCode.value = v
  },
})

const targetCurrent = computed(
  () =>
    langs.value.find((l) => l.value === targetCode.value) ||
    langs.value[0],
)

async function loadLangs() {
  langs.value = await loadEnabledLangOptions(service)
  ensureLangs()
  if (crud.trashMode.value === 'dataI18n') {
    await crud.refresh()
  }
}

function ensureLangs() {
  if (!langs.value.length) return
  if (
    !targetCode.value ||
    !langs.value.some((o) => o.value === targetCode.value)
  ) {
    targetCode.value = langs.value[0]!.value
  }
}

async function switchTarget(code: string) {
  if (switching.value || !code || code === targetCode.value) return
  switching.value = true
  try {
    targetCode.value = code
    crud.pagination.value = { ...crud.pagination.value, page: 1 }
    await crud.refresh()
  } finally {
    switching.value = false
  }
}

watch(
  () => crud.trashMode.value,
  (mode) => {
    if (mode === 'dataI18n') void loadLangs()
  },
)

onMounted(() => {
  if (crud.trashMode.value === 'dataI18n') void loadLangs()
})
</script>

<style lang="scss" scoped>
.vm-data-i18n-lang {
  display: inline-flex;
  align-items: center;
}

.vm-crud-toolbar__btn {
  display: inline-flex;
  height: 36px;
  align-items: center;
  gap: 4px;
  padding: 0 14px;
  border: none;
  border-radius: 12px;
  font-size: 13px;
  font-weight: 600;
  cursor: pointer;
  background: var(--muted);
  color: var(--foreground);
  transition: background 0.15s ease, opacity 0.15s ease;

  &:disabled {
    cursor: not-allowed;
    opacity: 0.45;
  }

  &:hover:not(:disabled) {
    background: color-mix(in srgb, var(--muted) 70%, var(--foreground) 8%);
  }
}

.vm-data-i18n-lang__flag {
  font-size: 16px;
  line-height: 1;
}

.vm-data-i18n-lang__menu {
  min-width: 140px;
}

.vm-data-i18n-lang__item {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;

  &.is-active {
    background: color-mix(in srgb, var(--brand) 12%, transparent);
    color: var(--brand);
  }
}

.vm-data-i18n-lang__label {
  font-size: 13px;
}
</style>
