<script setup lang="ts">
import { ref } from 'vue'
import TranslateResultPanel from '../components/TranslateResultPanel.vue'
import { api, type TranslateResult } from '../api/request'

const input = ref('')
const result = ref<TranslateResult | null>(null)
const message = ref('')
const messageType = ref<'success' | 'error'>('success')
const loading = ref(false)
const adding = ref(false)

async function handleTranslate() {
  if (!input.value.trim()) return
  loading.value = true
  message.value = ''
  result.value = null
  try {
    const { data } = await api.translate(input.value.trim())
    result.value = data
  } catch (e: unknown) {
    const err = e as { response?: { data?: { detail?: string } } }
    message.value = err.response?.data?.detail || '翻译失败'
    messageType.value = 'error'
  } finally {
    loading.value = false
  }
}

async function addToLibrary() {
  if (!result.value || adding.value || !result.value.target_text.trim()) return
  adding.value = true
  message.value = ''
  try {
    await api.createWord({
      source_text: result.value.source_text,
      target_text: result.value.target_text.trim(),
      source_lang: result.value.source_lang,
      target_lang: result.value.target_lang,
      phonetic: result.value.phonetic,
      example_en: result.value.example_en,
      example_cn: result.value.example_cn,
    })
    message.value = '已加入单词库 ✅'
    messageType.value = 'success'
  } catch (e: unknown) {
    const err = e as { response?: { data?: { detail?: string } } }
    message.value = err.response?.data?.detail || '添加失败'
    messageType.value = 'error'
  } finally {
    adding.value = false
  }
}
</script>

<template>
  <div class="page">
    <h1 class="page-title">翻译</h1>
    <textarea
      v-model="input"
      class="input translate-input"
      rows="3"
      placeholder="输入中文或英文，例如：苹果 或 apple"
    />
    <button class="btn btn-primary" style="margin-top: 12px" :disabled="loading" @click="handleTranslate">
      {{ loading ? '翻译中...' : '翻译' }}
    </button>

    <div v-if="message" :class="['message', messageType]">{{ message }}</div>

    <div v-if="result" class="card result-card">
      <TranslateResultPanel v-model="result" :adding="adding" @add="addToLibrary" />
    </div>
  </div>
</template>

<style scoped>
.translate-input {
  resize: vertical;
  min-height: 80px;
  font-family: inherit;
}
.result-card {
  margin-top: 16px;
}
</style>
