<template>
  <div class="paragraph-card">
    <!-- 段落原文 -->
    <p class="paragraph-card__text" :class="{ 'paragraph-card__text--muted': !isCompleted }">
      {{ paragraph.text }}
    </p>

    <!-- 星级 / 状态 + 操作按钮（enspeak ArticleDetailedReport.tsx:108-169） -->
    <div class="paragraph-card__meta">
      <div class="paragraph-card__status">
        <template v-if="isCompleted">
          <ArticleStarRating :score="paragraph.overallScore" size="md" step="full" />
          <span class="status-tag status-tag--done">
            <svg width="12" height="12" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true">
              <path fill-rule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clip-rule="evenodd" />
            </svg>
            {{ lang.ssArticleRecordedTag }}
          </span>
        </template>

        <span v-else-if="paragraph.status === 'generating'" class="status-tag status-tag--generating">
          <span class="status-spinner"></span>
          {{ lang.ssArticleProcessing }}
        </span>

        <span v-else-if="paragraph.status === 'failed'" class="status-tag status-tag--failed">
          {{ lang.ssArticleEvalFailed }}
        </span>
      </div>

      <div class="paragraph-card__actions" :class="{ 'paragraph-card__actions--locked': !interactive }">
        <!-- 系统朗读示范：任何状态都可听（后端按 reference_text 合成） -->
        <button
          class="act-btn act-btn--demo"
          :class="{ playing: demoAudioPlaying }"
          :disabled="demoAudioLoading"
          :tabindex="interactive ? undefined : -1"
          :aria-pressed="demoAudioPlaying"
          :title="lang.ssArticleDemoAudio as string"
          @click.stop="emit('play-demo')"
        >
          <span v-if="demoAudioLoading" class="act-btn__spinner"></span>
          <svg v-else width="14" height="14" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true">
            <path d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zM7 8a1 1 0 012 0v4a1 1 0 11-2 0V8zm5-1a1 1 0 00-1 1v4a1 1 0 102 0V8a1 1 0 00-1-1z" />
          </svg>
          {{ lang.ssArticleDemoAudio }}
        </button>

        <!-- 我的录音回放：仅已录 -->
        <button
          v-if="ownAudioAvailable"
          class="act-btn act-btn--own"
          :class="{ playing: ownAudioPlaying }"
          :disabled="ownAudioLoading"
          :tabindex="interactive ? undefined : -1"
          :aria-pressed="ownAudioPlaying"
          :title="lang.ssArticleMyAudio as string"
          @click.stop="emit('play-own')"
        >
          <span v-if="ownAudioLoading" class="act-btn__spinner"></span>
          <svg v-else width="14" height="14" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true">
            <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM9.555 7.168A1 1 0 008 8v4a1 1 0 001.555.832l3-2a1 1 0 000-1.664l-3-2z" clip-rule="evenodd" />
          </svg>
          {{ lang.ssArticleMyAudio }}
        </button>

        <!-- 展开评价：容器负责状态，这里只是开关 -->
        <button
          v-if="isCompleted"
          class="expand-btn"
          :class="{ open: expanded }"
          :tabindex="interactive ? undefined : -1"
          :title="lang.ssArticleViewEval as string"
          @click.stop="emit('toggle')"
        >
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <path stroke-linecap="round" stroke-linejoin="round" d="M6 9l6 6 6-6" />
          </svg>
        </button>
      </div>
    </div>

    <!-- 展开的评价区 -->
    <div v-if="expanded && isCompleted" class="paragraph-card__evaluation">
      <!-- 段落总评：四维横排五星 -->
      <div class="evaluation-block">
        <p class="evaluation-block__title">
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true">
            <path stroke-linecap="round" stroke-linejoin="round" d="M8 10h.01M12 10h.01M16 10h.01M9 16H5a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v8a2 2 0 01-2 2h-5l-5 5v-5z" />
          </svg>
          {{ lang.ssArticleParagraphSummary }}
        </p>
        <div class="dims-row">
          <template v-for="(dim, index) in dimRows" :key="dim.key">
            <span v-if="index > 0" class="dims-row__sep">|</span>
            <span class="dims-row__item">
              <span class="dims-row__label">{{ dim.label }}</span>
              <ArticleStarRating :score="dim.score" size="sm" step="full" />
            </span>
          </template>
        </div>
      </div>

      <!-- 整段反馈：一条连续词流，不分句 -->
      <div class="evaluation-block">
        <p class="evaluation-block__title">
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true">
            <path stroke-linecap="round" stroke-linejoin="round" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
          </svg>
          {{ lang.ssArticleWordFeedback }}
        </p>
        <p class="word-stream"><span
          v-for="(token, index) in words"
          :key="`${index}-${token.word}`"
          class="article-word"
          :class="`article-word--${token.status}`"
        ><template v-if="token.status === 'omission'">[{{ token.word }}]</template><template v-else>{{ token.word }}</template>{{ ' ' }}</span></p>

        <!-- 词级统计栏：每一项自带该类词的视觉标记 -->
        <div class="word-legend">
          <span class="article-word article-word--good">word {{ lang.ssArticleWordCorrect }} {{ counts.good }} {{ lang.ssArticleWordsUnit }}</span>
          <span class="word-legend__sep">|</span>
          <span class="article-word article-word--misread">word {{ lang.ssArticleWordMisread }} {{ counts.misread }} {{ lang.ssArticleWordsUnit }}</span>
          <span class="word-legend__sep">|</span>
          <span class="article-word article-word--omission">[word] {{ lang.ssArticleWordOmission }} {{ counts.omission }} {{ lang.ssArticleWordsUnit }}</span>
          <span class="word-legend__sep">|</span>
          <span class="article-word article-word--insertion">word {{ lang.ssArticleWordInsertion }} {{ counts.insertion }} {{ lang.ssArticleWordsUnit }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { computed } from 'vue'
import { lang } from '@/main'
import ArticleStarRating from './ArticleStarRating.vue'
import type { ArticleParagraphResult } from '@/types/articleReading'

const props = withDefaults(defineProps<{
  paragraph: ArticleParagraphResult
  expanded: boolean
  demoAudioLoading: boolean
  demoAudioPlaying: boolean
  ownAudioLoading: boolean
  ownAudioPlaying: boolean
  ownAudioAvailable: boolean
  /**
   * 卡内按钮是否接管点击。练习页只有**选中的那一段**是 true —— 其余段落整张卡
   * 只做一件事：把自己选中。报告页没有「当前段」的概念，全部可点。
   */
  interactive?: boolean
}>(), { interactive: true })

const emit = defineEmits<{
  (event: 'toggle'): void
  (event: 'play-demo'): void
  (event: 'play-own'): void
}>()

const isCompleted = computed(() => props.paragraph.status === 'completed')

// 后端给的就是段内扁平词级（spec §6），不再有句层可展平。
const words = computed(() => props.paragraph.words)

/**
 * 统计栏只数「自带标记」的四类：正确（绿）/ 错读（波浪线）/ 漏读（[]）/ 多读（删除线）。
 * warn / bad 在词流里照常着色，但它们没有独立标记，原型的统计栏也不含这两档。
 */
const counts = computed(() => {
  const tally = { good: 0, misread: 0, omission: 0, insertion: 0 }
  for (const token of words.value) {
    if (token.status in tally) tally[token.status as keyof typeof tally] += 1
  }
  return tally
})

const dimRows = computed(() => {
  const dims = props.paragraph.dims
  return [
    { key: 'accuracy', label: lang.ssAccuracy as string, score: dims?.accuracy ?? null },
    { key: 'fluency', label: lang.ssFluency as string, score: dims?.fluency ?? null },
    { key: 'completeness', label: lang.ssCompleteness as string, score: dims?.completeness ?? null },
    { key: 'prosody', label: lang.ssRhythm as string, score: dims?.prosody ?? null },
  ]
})
</script>

<style lang="scss" scoped>
.paragraph-card__text {
  margin: 0;
  font-size: 14px;
  line-height: 1.7;
  color: #1f2937;

  &--muted { color: #9ca3af; }
}

.paragraph-card__meta {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 8px;
  margin-top: 12px;
  flex-wrap: wrap;
}

.paragraph-card__status {
  display: flex;
  align-items: center;
  gap: 8px;
}

.paragraph-card__actions {
  display: flex;
  align-items: center;
  gap: 6px;

  // 未选中的段落：这一下点击是「我要练这一段」，别让按钮把它吃掉。
  // pointer-events 而不是 disabled —— 事件要能冒泡到外层的段落壳去选中，
  // 而且 disabled 的半透明叠在整卡已有的 opacity 上会糊成一团。
  &--locked {
    pointer-events: none;
  }
}

// ---- 状态药丸 ----
.status-tag {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  padding: 3px 8px;
  border-radius: 999px;
  font-size: 12px;
  font-weight: 500;
  white-space: nowrap;

  &--done {
    background: #ecfdf5;
    color: #059669;
  }

  &--generating {
    background: #fff7ed;
    color: #ea580c;
  }

  &--failed {
    background: #fef2f2;
    color: #dc2626;
  }
}

// ---- 操作按钮 ----
.act-btn {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  padding: 5px 10px;
  border-radius: 8px;
  font-size: 10px;
  font-weight: 500;
  cursor: pointer;
  transition: background 0.2s, border-color 0.2s;

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

  &--demo {
    border: 1px solid #fed7aa;
    background: #fff7ed;
    color: #ea580c;

    &:hover:not(:disabled) { background: #ffedd5; }
    &.playing { background: #ffedd5; border-color: #fdba74; }
  }

  &--own {
    border: 1px solid #bfdbfe;
    background: #eff6ff;
    color: #2563eb;

    &:hover:not(:disabled) { background: #dbeafe; }
    &.playing { background: #dbeafe; border-color: #93c5fd; }
  }
}

.act-btn__spinner,
.status-spinner {
  width: 10px;
  height: 10px;
  border-radius: 50%;
  border: 1.5px solid currentColor;
  border-top-color: transparent;
  animation: article-card-spin 0.7s linear infinite;
}

@keyframes article-card-spin {
  to { transform: rotate(360deg); }
}

.expand-btn {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 24px;
  height: 24px;
  border: none;
  border-radius: 6px;
  background: transparent;
  color: #f97316;
  cursor: pointer;
  transition: background 0.2s, transform 0.2s;

  &:hover { background: #ffedd5; }
  &.open { transform: rotate(180deg); }
}

// ---- 展开的评价区 ----
.paragraph-card__evaluation {
  margin-top: 12px;
  padding-top: 12px;
  border-top: 1px solid #e5e7eb;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.evaluation-block__title {
  display: flex;
  align-items: center;
  gap: 4px;
  margin: 0 0 8px;
  font-size: 12px;
  font-weight: 500;
  color: #9ca3af;

  svg {
    color: #fb923c;
    opacity: 0.6;
    flex-shrink: 0;
  }
}

// 四维横排，维度之间用浅灰竖线分隔
.dims-row {
  display: flex;
  align-items: center;
  gap: 12px;
  flex-wrap: wrap;
  font-size: 11px;
  color: #6b7280;
}

.dims-row__item {
  display: inline-flex;
  align-items: center;
  gap: 6px;
}

.dims-row__sep {
  color: #e5e7eb;
}

.word-stream {
  margin: 0;
  font-size: 14px;
  line-height: 1.75;
  color: #374151;
}

.article-word {
  font-weight: 500;
}

.article-word--good { color: #047857; }
.article-word--warn { color: #d97706; }
.article-word--bad { color: #dc2626; }

.article-word--misread {
  color: #dc2626;
  text-decoration-line: underline;
  text-decoration-style: wavy;
  text-decoration-color: #f87171;
}

.article-word--omission { color: #dc2626; }

.article-word--insertion {
  color: #dc2626;
  text-decoration: line-through;
  text-decoration-color: #f87171;
}

.word-legend {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
  margin-top: 8px;
  font-size: 11px;
}

.word-legend__sep {
  color: #d1d5db;
}
</style>
