<template>
  <div class="topic-discussion-preview">
    <!-- Ready 阶段：极简首页（参照 enspeak 布局） -->
    <div v-if="dialogueState === 'ready'" class="ready-stage">
      <div class="ready-header">
        <h1 class="ready-title">
          <span class="ready-title-icon">💬</span>
          Topic Discussion
        </h1>
        <p class="ready-subtitle">话题讨论 · 与 AI 伙伴练习英语对话</p>
      </div>

      <div class="ready-body">
        <span class="topic-emoji">🐼</span>
        <h3 class="topic-name">{{ speakingStore.config.topic || topic }}</h3>
      </div>

      <div class="ready-footer">
        <button class="start-btn" @click="startDialogue">
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor"
            stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <path d="M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z" />
            <path d="M19 10v2a7 7 0 0 1-14 0v-2" />
            <line x1="12" y1="19" x2="12" y2="23" />
            <line x1="8" y1="23" x2="16" y2="23" />
          </svg>
          开始对话
        </button>
      </div>
    </div>

    <!-- Chatting 阶段：直接渲染 DialogueChatView -->
    <DialogueChatView
      v-else-if="dialogueState === 'chatting'"
      :topic="speakingStore.config.topic || topic"
      :keywords="speakingStore.config.learningGoals.vocabulary.length ? speakingStore.config.learningGoals.vocabulary : keywords"
      :ai-name="mockRole.name"
      :ai-avatar="mockRole.avatar"
      :total-rounds="speakingStore.config.practice.rounds || totalRounds"
      :mode="mode"
      @complete="handleDialogueComplete"
    />

    <!-- Completed 阶段：直接渲染报告 -->
    <div v-else class="report-stage">
      <div class="report-scroll">
        <OverallReport
          :evaluation="displayEvaluation"
          :role="mockRole"
          :scoreDisplayMode="'numeric'"
          @restart="resetPreview"
          @complete="resetPreview"
        />
        <div class="report-divider" />
        <DetailedReport :sentenceEvaluations="displayEvaluation.sentenceEvaluations" />
      </div>
    </div>

  </div>
</template>

<script lang="ts" setup>
import { ref, computed, watch, onMounted, onUnmounted } from 'vue'
import type { DialogueReport, OverallEvaluation, PreviewAIRole, PreviewDialogueState } from '@/types/englishSpeaking'
import { useSpeakingStore } from '@/store/speaking'
import { getSpeakingConfig } from '@/services/speaking'

import DialogueChatView from './DialogueChatView.vue'
import OverallReport from './OverallReport.vue'
import DetailedReport from './DetailedReport.vue'

interface Props {
  mode?: 'preview' | 'real'
  topic?: string
  keywords?: string[]
  totalRounds?: number
  /** 配置 id（由 FrameElement 从 elementInfo.url 传入） */
  configId?: string
}

const props = withDefaults(defineProps<Props>(), {
  mode: 'real',
  topic: '我最喜欢的动物',
  keywords: () => ['favorite', 'adorable', 'bamboo', 'habitat', 'wildlife', 'endangered'],
  totalRounds: 3,
  configId: '',
})

const dialogueState = ref<PreviewDialogueState>('ready')

const mockRole: PreviewAIRole = {
  id: 'tom',
  name: 'Tom',
  avatar: '😊',
  identity: 'Friendly Teacher',
  personality: 'Patient and encouraging',
  speakingStyle: 'casual',
  speed: 'normal',
  isCustom: false,
  isRecommended: true,
}

const mockEvaluation: OverallEvaluation = {
  overallScore: 85,
  scoreLevel: 'good',
  percentile: 78,
  dimensions: {
    fluency: 82,
    interaction: 88,
    vocabulary: 76,
    grammar: 90,
  },
  aiComment: 'Great job! You showed good understanding of the topic. Your pronunciation was clear and your responses were relevant. Keep practicing to improve your fluency and try using more advanced vocabulary!',
  highlights: [
    'Clear pronunciation of key words',
    'Good use of complete sentences',
    'Natural conversation flow',
  ],
  improvements: [
    'Try using more descriptive adjectives',
    'Practice linking words for smoother speech',
    'Expand vocabulary range for the topic',
  ],
  nextChallenge: {
    difficulty: 'Medium',
    unlockedTopic: 'My Dream Job',
    suggestedMode: 'Free Talk',
  },
  statistics: {
    totalRounds: 3,
    averageScore: 83,
    highestScore: 92,
    highestRound: 2,
    grammarErrors: 2,
    excellentExpressions: 4,
    totalDuration: 180,
  },
  sentenceEvaluations: [
    {
      id: 'se-1', round: 1, role: 'ai',
      content: "Hi! What's your favorite animal?",
      audioDuration: 3,
    },
    {
      id: 'se-2', round: 1, role: 'student',
      content: 'I like pandas. They are very cute!',
      audioDuration: 4, score: 88,
      pronunciation: { accuracy: 90, intonation: 85, stress: 82, fluency: 88 },
      feedback: {
        highlights: ['Good pronunciation of "pandas"', 'Natural intonation'],
        corrections: [],
        suggestions: ['Try: "I really love pandas because they\'re incredibly cute!"'],
      },
    },
    {
      id: 'se-3', round: 2, role: 'ai',
      content: 'Pandas are adorable! Have you seen them at the zoo?',
      audioDuration: 4,
    },
    {
      id: 'se-4', round: 2, role: 'student',
      content: 'Yes, I went to the zoo last month.',
      audioDuration: 3, score: 92,
      pronunciation: { accuracy: 95, intonation: 90, stress: 88, fluency: 92 },
      feedback: {
        highlights: ['Excellent fluency', 'Clear past tense usage'],
        corrections: [],
        suggestions: ['Add more details: "I visited the Beijing Zoo last month and saw giant pandas there."'],
      },
    },
    {
      id: 'se-5', round: 3, role: 'ai',
      content: "That's great! What do pandas like to eat?",
      audioDuration: 3,
    },
    {
      id: 'se-6', round: 3, role: 'student',
      content: 'They like to eat bamboo.',
      audioDuration: 3, score: 78,
      pronunciation: { accuracy: 80, intonation: 75, stress: 76, fluency: 82 },
      feedback: {
        highlights: ['Correct answer'],
        corrections: [{ original: 'like to eat', corrected: 'mainly feed on', explanation: '"feed on" is more natural for describing animal diets' }],
        suggestions: ['Expand: "Pandas mainly feed on bamboo, but they also eat fruits and vegetables."'],
      },
    },
  ],
}

const realEvaluation = ref<OverallEvaluation | null>(null)

const displayEvaluation = computed<OverallEvaluation>(() => {
  const real = realEvaluation.value
  if (real && real.sentenceEvaluations.length > 0) return real
  return mockEvaluation
})

function startDialogue() {
  dialogueState.value = 'chatting'
}

function handleDialogueComplete(report: DialogueReport | null) {
  realEvaluation.value = report?.evaluation ?? null
  dialogueState.value = 'completed'
}

function resetPreview() {
  dialogueState.value = 'ready'
  realEvaluation.value = null
}

// ── Sync with speakingStore (让 CanvasTool 可以驱动"重置预览") ──
const speakingStore = useSpeakingStore()

watch(dialogueState, (s) => { speakingStore.setPreviewState(s) }, { immediate: true })

watch(
  () => speakingStore.resetSignal,
  (val, old) => {
    if (val !== old) resetPreview()
  },
)

// ── 根据 configId 从后端拉回配置注入 store ──
async function loadConfigFromBackend(id: string) {
  if (!id) return
  try {
    const { config } = await getSpeakingConfig(id)
    speakingStore.$patch({ config })
  } catch (err) {
    console.error('[speaking] load config failed:', err)
  }
}

watch(() => props.configId, (id) => { loadConfigFromBackend(id) })

onMounted(() => {
  speakingStore.setPreviewState(dialogueState.value)
  loadConfigFromBackend(props.configId)
})
onUnmounted(() => { speakingStore.setPreviewState('ready') })
</script>

<style lang="scss" scoped>
.topic-discussion-preview {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  background: #fff;
  position: relative;
  overflow: hidden;

  // flex 嵌套 overflow 生效的前提：flex 子默认 min-height: auto 会被内容撑大，
  // 让 ready-stage / report-stage / DialogueChatView 根节点能 shrink 到父高度
  > * {
    min-height: 0;
  }
}

// ─── Ready 阶段 ───
.ready-stage {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: #fff;
}
.ready-header {
  padding: 20px 24px 12px;
  text-align: center;
  border-bottom: 1px solid #f9fafb;
}
.ready-title {
  font-size: 20px;
  font-weight: 600;
  color: #111827;
  margin: 0;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}
.ready-title-icon { font-size: 22px; }
.ready-subtitle {
  font-size: 13px;
  color: #9ca3af;
  margin: 4px 0 0;
}
.ready-body {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 16px;
  padding: 24px;
}
.topic-emoji { font-size: 56px; line-height: 1; }
.topic-name {
  font-size: 18px;
  font-weight: 600;
  color: #1f2937;
  margin: 0;
}
.ready-footer {
  padding: 16px 24px 20px;
  border-top: 1px solid #f9fafb;
  background: #fafbfc;
  display: flex;
  justify-content: center;
}
.start-btn {
  display: inline-flex;
  align-items: center;
  gap: 8px;
  padding: 9px 28px;
  border-radius: 999px;
  background: #f97316;
  color: #fff;
  border: none;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  box-shadow: 0 4px 12px rgba(249, 115, 22, 0.25);
  transition: background 0.2s, transform 0.15s;
  &:hover { background: #ea580c; }
  &:active { transform: scale(0.97); }
}

// ─── Completed 阶段 ───
.report-stage {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  background: #fff;
}
.report-scroll {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
  display: flex;
  flex-direction: column;
  gap: 24px;
}
.report-divider {
  height: 1px;
  background: #e5e7eb;
  margin: 0;
}

</style>
