<template>
  <div class="i18n-editor">
    <ElTabs v-model="activeTab" type="card">
      <ElTabPane name="zh-CN" :label="t('dictionary.i18n.zh')">
        <ElInput
          v-model="localValue['zh-CN']"
          :disabled="disabled"
          :placeholder="resolvedPlaceholderZh"
          @input="emitChange"
          clearable
        />
      </ElTabPane>
      <ElTabPane name="en" :label="t('dictionary.i18n.en')">
        <ElInput
          v-model="localValue.en"
          :disabled="disabled"
          :placeholder="resolvedPlaceholderEn"
          @input="emitChange"
          clearable
        />
      </ElTabPane>
    </ElTabs>
    <div v-if="hintVisible" class="i18n-hint">
      {{ t('dictionary.i18n.hint') }}
    </div>
  </div>
</template>

<script setup lang="ts">
  import { computed, reactive, ref, watch } from 'vue'
  import { useI18n } from 'vue-i18n'

  defineOptions({ name: 'I18nValueEditor' })

  interface Props {
    modelValue?: Record<string, string>
    disabled?: boolean
    placeholderZh?: string
    placeholderEn?: string
    showHint?: boolean
  }

  const props = withDefaults(defineProps<Props>(), {
    modelValue: () => ({}),
    disabled: false,
    placeholderZh: '',
    placeholderEn: '',
    showHint: true
  })

  const emit = defineEmits<{
    (event: 'update:modelValue', value: Record<string, string>): void
    (event: 'change', value: Record<string, string>): void
  }>()

  const activeTab = ref('zh-CN')
  const localValue = reactive<Record<string, string>>({ ...props.modelValue })
  const { t } = useI18n()
  const resolvedPlaceholderZh = computed(
    () => props.placeholderZh || t('dictionary.i18n.zhPlaceholder')
  )
  const resolvedPlaceholderEn = computed(
    () => props.placeholderEn || t('dictionary.i18n.enPlaceholder')
  )
  const hintVisible = computed(() => {
    if (!props.showHint) return false
    return !Object.values(localValue).some((value) => value?.trim())
  })

  watch(
    () => props.modelValue,
    (value) => {
      Object.keys(localValue).forEach((key) => delete localValue[key])
      Object.assign(localValue, value || {})
    },
    { deep: true }
  )

  const emitChange = () => {
    const payload = { ...localValue }
    emit('update:modelValue', payload)
    emit('change', payload)
  }
</script>

<style scoped>
  .i18n-editor {
    display: flex;
    flex-direction: column;
    gap: 8px;
  }

  .i18n-hint {
    font-size: 12px;
    color: #909399;
  }
</style>
