<script setup lang="ts">
import type { Word } from '../api/request'
import { formatTrainSeconds } from '../composables/useQuizTimer'

defineProps<{
  word: Word
  selectable?: boolean
  selected?: boolean
}>()

defineEmits<{
  delete: [id: number]
  'toggle-select': [id: number]
}>()

const statusMap: Record<string, string> = {
  new: '新词',
  learning: '学习中',
  mastered: '已掌握',
  weak: '易错词',
}

function enText(word: Word) {
  return word.source_lang === 'en' ? word.source_text : word.target_text
}

function zhText(word: Word) {
  return word.source_lang === 'zh' ? word.source_text : word.target_text
}

function formatEnteredAt(iso: string) {
  if (!iso) return '—'
  const d = iso.replace('T', ' ').replace('Z', '')
  return d.length >= 16 ? d.slice(0, 16) : d.slice(0, 10)
}
</script>

<template>
  <div class="card word-card" :class="{ 'word-card-selected': selected }">
    <label v-if="selectable" class="word-select" @click.stop>
      <input
        type="checkbox"
        :checked="selected"
        @change="$emit('toggle-select', word.id)"
      />
    </label>
    <div class="word-body">
      <div class="word-header">
        <div>
          <div class="word-pair">{{ enText(word) }} — {{ zhText(word) }}</div>
          <span :class="['badge', `badge-${word.status}`]">{{ statusMap[word.status] || word.status }}</span>
        </div>
        <button type="button" class="btn btn-danger" @click="$emit('delete', word.id)">删除</button>
      </div>
    <div class="word-meta">
      <span>训练 {{ word.train_count ?? 0 }} 次</span>
      <span>答对 {{ word.correct_count }}</span>
      <span>答错 {{ word.wrong_count }}</span>
      <span>连续 {{ word.consecutive_correct_count }}</span>
      <span>掌握率 {{ word.mastery_score }}%</span>
      <span v-if="word.total_train_seconds">用时 {{ formatTrainSeconds(word.total_train_seconds) }}</span>
    </div>
    <div class="word-entered">进入词库：{{ formatEnteredAt(word.entered_at || word.created_at) }}</div>
      <div v-if="word.review_due_date" class="word-due">下次复习：{{ word.review_due_date }}</div>
    </div>
  </div>
</template>

<style scoped>
.word-card {
  display: flex;
  align-items: flex-start;
  gap: 10px;
}
.word-card-selected {
  border-color: rgba(79, 110, 247, 0.45);
  box-shadow: 0 0 0 2px rgba(79, 110, 247, 0.12);
}
.word-select {
  flex-shrink: 0;
  padding-top: 4px;
  cursor: pointer;
}
.word-select input {
  width: 18px;
  height: 18px;
  accent-color: var(--primary);
  cursor: pointer;
}
.word-body {
  flex: 1;
  min-width: 0;
}
.word-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 8px;
}
.word-pair {
  font-size: 17px;
  font-weight: 600;
  margin-bottom: 6px;
}
.word-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  font-size: 12px;
  color: var(--muted);
  margin-top: 10px;
}
.word-entered {
  font-size: 12px;
  color: var(--muted);
  margin-top: 8px;
}
.word-due {
  font-size: 12px;
  color: var(--primary);
  margin-top: 4px;
}
</style>
