<template>
  <div class="overall-report">
    <!-- 完成提示（enspeak OverallReport.tsx:178-184） -->
    <div class="completion-header">
      <div class="completion-emoji">🎉</div>
      <h2 class="completion-title">{{ lang.ssArticleReportDone }}</h2>
      <p class="completion-subtitle">{{ subtitle }}</p>
    </div>

    <template v-if="overall">
      <!-- 综合评分：五星紧凑横排 + 两列维度星级（scoreLayout="compactStars"） -->
      <div class="score-card">
        <div class="score-card__head">
          <div class="score-card__summary">
            <span class="score-card__label">{{ lang.ssArticleOverallScore }}</span>
            <ArticleStarRating :score="overall.overallScore" size="lg" step="half" />
            <span class="score-card__value">{{ overallStars }} {{ lang.ssArticlePointsUnit }}</span>
          </div>
          <span class="score-card__praise">{{ praise }}</span>
        </div>

        <div class="score-card__dims">
          <div v-for="dim in dimRows" :key="dim.key" class="score-card__dim">
            <span class="score-card__dim-label">{{ dim.label }}</span>
            <ArticleStarRating :score="dim.score" size="sm" step="half" />
          </div>
        </div>
      </div>

      <!-- AI 点评 -->
      <div class="comment-card">
        <div class="comment-card__inner">
          <div class="comment-card__avatar">👨‍🏫</div>
          <div class="comment-card__body">
            <div class="comment-card__name">{{ lang.ssArticleTeacherSays }}</div>
            <p class="comment-card__text">{{ overall.aiComment }}</p>
          </div>
        </div>
      </div>

      <!-- 亮点与建议 -->
      <div class="notes-grid">
        <div class="note-card">
          <div class="note-card__head">
            <span class="note-card__icon note-card__icon--good">✓</span>
            {{ lang.ssArticleHighlights }}
          </div>
          <div class="note-card__list">
            <div v-for="(item, index) in overall.highlights.slice(0, 3)" :key="`h-${index}`" class="note-card__item">
              • {{ item }}
            </div>
          </div>
        </div>

        <div class="note-card">
          <div class="note-card__head">
            <span class="note-card__icon note-card__icon--warn">→</span>
            {{ lang.ssArticleSuggestions }}
          </div>
          <div class="note-card__list">
            <div v-for="(item, index) in overall.suggestions.slice(0, 3)" :key="`s-${index}`" class="note-card__item">
              • {{ item }}
            </div>
          </div>
        </div>
      </div>
    </template>

    <!-- 软失败 / 无总评：不挡住逐段结果（spec §4.1 边界 5） -->
    <div v-else class="report-notice">
      {{ report.overallStatus === 'failed' ? lang.ssArticleOverallFailed : lang.ssArticleOverallMissing }}
    </div>

    <!-- 再来一次（enspeak OverallReport.tsx:301-309；老师端看学生报告时不给这个出口） -->
    <div v-if="showRestart" class="report-actions">
      <button class="restart-btn" @click="emit('restart')">
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
          <polyline points="23 4 23 10 17 10" />
          <path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10" />
        </svg>
        {{ lang.ssArticleTryAgain }}
      </button>
    </div>
  </div>
</template>

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

const props = withDefaults(defineProps<{
  report: ArticleReadingReport
  /** 学生自己的报告页给「再来一次」；老师端 StudentReportModal 不给。 */
  showRestart?: boolean
}>(), { showRestart: false })

const emit = defineEmits<{ restart: [] }>()

const overall = computed(() => props.report.overall)

const overallStars = computed(() => Math.round(scoreToStars(overall.value?.overallScore ?? null) * 2) / 2)

// 星级 → 鼓励文案（enspeak scoreToPraise）
const praise = computed(() => {
  const stars = overallStars.value
  if (stars >= 5) return lang.ssArticlePraiseExcellent as string
  if (stars >= 4) return lang.ssArticlePraiseGreat as string
  if (stars >= 3) return lang.ssArticlePraiseGood as string
  return lang.ssArticlePraiseKeepGoing as string
})

const dimRows = computed(() => {
  const dims = overall.value?.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 },
  ]
})

const readCount = computed(() =>
  props.report.paragraphs.filter(paragraph => paragraph.status === 'completed').length,
)

// 原型副标题是「与 X 对话 N 轮 · 时长」，朗读没有轮次，换成同位置的篇名 + 已读段数 + 时长
const subtitle = computed(() => {
  const parts: string[] = []
  if (props.report.title) parts.push(props.report.title)
  parts.push(`${lang.ssArticleReadCount}：${readCount.value} / ${props.report.paragraphs.length} ${lang.ssArticleParagraphsUnit}`)
  if (props.report.totalDurationSeconds !== null) {
    parts.push(`${lang.ssArticleTotalDuration}：${formatDuration(props.report.totalDurationSeconds)}`)
  }
  return parts.join(' · ')
})

function formatDuration(seconds: number): string {
  const mm = Math.floor(seconds / 60)
  const ss = seconds % 60
  return mm > 0 ? `${mm} ${lang.ssMinute} ${ss} ${lang.ssArticleSecondsUnit}` : `${ss} ${lang.ssArticleSecondsUnit}`
}
</script>

<style lang="scss" scoped>
// 原型是 max-w-md mx-auto space-y-3 的窄栏，报告页外层已限宽，这里只保留纵向节奏
.overall-report {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

// ---- 完成提示 ----
.completion-header {
  text-align: center;
}

.completion-emoji {
  font-size: 30px;
  line-height: 1.2;
  margin-bottom: 4px;
}

.completion-title {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #111827;
}

.completion-subtitle {
  margin: 2px 0 0;
  font-size: 12px;
  line-height: 1.5;
  color: #6b7280;
}

// ---- 综合评分卡 ----
.score-card {
  border: 1px solid #f3f4f6;
  border-radius: 12px;
  background: #fff;
  overflow: hidden;
}

.score-card__head {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
  padding: 14px 16px;
  border-bottom: 1px solid #f3f4f6;
  background: linear-gradient(to right, #fff7ed, #fffdf9);
}

.score-card__summary {
  display: flex;
  align-items: center;
  gap: 10px;
}

.score-card__label {
  font-size: 12px;
  color: #6b7280;
}

.score-card__value {
  font-size: 12px;
  font-weight: 600;
  color: #f59e0b;
  font-variant-numeric: tabular-nums;
}

.score-card__praise {
  font-size: 12px;
  font-weight: 600;
  color: #f59e0b;
}

.score-card__dims {
  display: grid;
  grid-template-columns: 1fr 1fr;
  column-gap: 16px;
  row-gap: 10px;
  padding: 12px 16px;
}

.score-card__dim {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 8px;
}

.score-card__dim-label {
  font-size: 12px;
  color: #4b5563;
}

// ---- AI 点评 ----
.comment-card {
  padding: 12px;
  border: 1px solid #f3f4f6;
  border-radius: 12px;
  background: #fff;
}

.comment-card__inner {
  display: flex;
  gap: 10px;
}

.comment-card__avatar {
  flex-shrink: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
  border-radius: 50%;
  background: #fff7ed;
  font-size: 16px;
}

.comment-card__body {
  flex: 1;
  min-width: 0;
}

.comment-card__name {
  margin-bottom: 4px;
  font-size: 12px;
  color: #9ca3af;
}

.comment-card__text {
  margin: 0;
  font-size: 12px;
  line-height: 1.65;
  color: #374151;
}

// ---- 亮点与建议 ----
.notes-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 8px;
}

.note-card {
  padding: 10px;
  border: 1px solid #f3f4f6;
  border-radius: 12px;
  background: #fff;
}

.note-card__head {
  display: flex;
  align-items: center;
  gap: 4px;
  margin-bottom: 6px;
  font-size: 12px;
  color: #6b7280;
}

.note-card__icon--good { color: #22c55e; }
.note-card__icon--warn { color: #f59e0b; }

.note-card__list {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.note-card__item {
  font-size: 10px;
  line-height: 1.5;
  color: #4b5563;
}

// ---- 软失败提示 ----
.report-notice {
  padding: 12px 16px;
  border: 1px solid #fed7aa;
  border-radius: 12px;
  background: #fff7ed;
  font-size: 12px;
  color: #c2410c;
}

// ---- 再来一次 ----
.report-actions {
  display: flex;
  align-items: center;
  justify-content: center;
  padding-top: 4px;
}

.restart-btn {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  padding: 10px 24px;
  border: none;
  border-radius: 8px;
  background: #f97316;
  color: #fff;
  font-size: 12px;
  font-weight: 500;
  cursor: pointer;
  transition: background 0.2s;

  &:hover { background: #ea580c; }
}
</style>
