<template>
  <button class="icon-btn mx-2" @click="toggleShowLocales">
    <carbon-language class="inline-block text-gray-900 dark:text-white" />
  </button>
  <div v-if="showLocalesSelector" :class="`select !normal max-w-xs ${selWidth} float-right`">
    <select v-model="currentLocale" class="dark:text-white dark:bg-gray-800 !outline-none">
      <option
        v-for="(itm: string) in listLocales"
        :key="itm"
        :selected="itm === currentLocale"
        :value="itm"
      >
        {{ localeLabel(itm) }}
      </option>
    </select>
  </div>
</template>
<script setup lang="ts">
//  <vue:window on:keydown={cleanOverlay} />
import {
  computed,
  PropType,
} from 'vue'

import { useI18n } from 'vue-i18n'
import {LocalesLabelModes}  from '~/typs'

const props = defineProps({
  labelMode: {
    type: String as PropType<LocalesLabelModes>,
    //default: LocalesLabelModes.translation,
    required: false,
  },
  includeCurrent: {
    type: Boolean,
    default: false,
    required: false,
  },
})
const i18n = useI18n()

const showLocalesSelector = ref(false)

const emit = defineEmits(['onLocale'])
const currentLocale = computed({
  get: (): string => i18n.locale.value,
  set: (val: string) => {
    if (i18n.availableLocales.includes(val)) {
      // console.log(`change to ${val} from ${i18n.locale.value}`)
      i18n.locale.value = val
			emit('onLocale', val)
      showLocalesSelector.value = false
    }
  },
})
const locales = computed(() => i18n.availableLocales)
const listLocales = computed(() =>
  props.includeCurrent ? locales.value : locales.value.filter(lcl => lcl !== currentLocale.value))
const toggleShowLocales = () => {
  showLocalesSelector.value = !showLocalesSelector.value
  // change to some real logic
  //  i18n.locale.value = i18n.availableLocales[(i18n.availableLocales.indexOf(i18n.locale.value) + 1) % i18n.availableLocales.length]
}
const localeLabel = (value: string): string => {
  let label = ''
  switch (props.labelMode) {
    case LocalesLabelModes.auto:
    case LocalesLabelModes.translation:
      label = i18n.t(value, value)
      break
    case LocalesLabelModes.value:
      label = value
      break
  }
  return label
}
const selWidth = computed(() => {
  let width = ''
  switch (props.labelMode) {
    case LocalesLabelModes.auto:
      width = 'w-auto'
      break
    case LocalesLabelModes.translation:
      width = 'w-28'
      break
    case LocalesLabelModes.value:
      width = 'w-24'
      break
  }
  return width
})
</script>
