<script setup lang="ts">
import {
  computed,
  onActivated,
  onBeforeUnmount,
  onDeactivated,
  onMounted,
  ref,
} from 'vue'
import { useRoute, useRouter } from 'vue-router'

import { taskMgrService } from '#/api/service/question-bank/task-mgr'
import PaperQuestionItem from '#/components/paper-question-item/index.vue'
import hud from '#/utils/hud'

import ViewStudents from './components/viewStudents.vue'

const route = useRoute()
const router = useRouter()
const { classId, resourceId } = route.query as any

// ======================== 试卷详情 ========================
const paperReleaseDetail = ref<any>({})
const paperDetail = ref<any[]>([])
const answerStatisticsList = ref<any[]>([])
const loading = ref(false)

async function loadPaperReleaseDetail() {
  const res = await taskMgrService.getpaperReleaseRecordDetail(resourceId)
  paperReleaseDetail.value = res || {}
}

async function loadPaperDetail() {
  if (!paperReleaseDetail.value?.paperId) return
  const res = await taskMgrService.getPaperDetail(
    paperReleaseDetail.value.paperId,
  )
  paperDetail.value = res?.schoolPaperTitleVoList ?? []
}

async function loadAnswerStatistics() {
  const res = await taskMgrService.getListRecord(resourceId, classId)
  const data = res || {}
  answerStatisticsList.value = data?.answerStatisticsList ?? []
}

function mergeStatistics() {
  const rows = answerStatisticsList.value.map((item: any) => {
    const total = Number(item?.totalNum ?? 0)
    const correct = Number(item?.correctNum ?? 0)
    const error = Number(item?.errorNum ?? 0)
    const rate = Number(item?.correctRate ?? 0)
    const unSubmit = Math.max(total - correct - error, 0)
    return {
      sort: item?.sort ?? '',
      titleId: item?.titleId ?? '',
      correctNum: correct,
      errorNum: error,
      correctRateText: `${(rate * 100).toFixed(0)}%`,
      unSubmitNum: unSubmit,
    }
  })

  paperDetail.value.forEach((item: any) => {
    const titleKey =
      item?.xkwTitle?.titleId ?? item?.titleId ?? item?.xkwTitle?.id ?? item?.id
    const matched = rows.find(
      (stat: any) => String(stat.titleId) === String(titleKey),
    )
    item.answerStatus = matched || {}
  })
}

async function initPageData() {
  loading.value = true
  try {
    await loadPaperReleaseDetail()
    await Promise.all([loadPaperDetail(), loadAnswerStatistics()])
    mergeStatistics()
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  initPageData()
})

onActivated(() => {
  stopQuestionExplainHeartbeat()
  phase.value = 'detail'
  countdown.value = 3
  currentIndex.value = 0
  clearCountdownTimer()
  initPageData()
})

// ======================== 倒计时 ========================
type ExplainPhase = 'countdown' | 'detail' | 'explaining'
const phase = ref<ExplainPhase>('detail')
const countdown = ref(3)
let countdownTimer: null | ReturnType<typeof setInterval> = null
const QUESTION_EXPLAIN_HEARTBEAT_INTERVAL = 60 * 1000
let questionExplainHeartbeatTimer: ReturnType<typeof setInterval> | undefined

function startCountdown() {
  document.documentElement.requestFullscreen?.().catch(() => {})
  countdown.value = 3
  phase.value = 'countdown'
  countdownTimer = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      clearCountdownTimer()
      enterExplaining()
    }
  }, 1000)
}

function cancelCountdown() {
  clearCountdownTimer()
  document.exitFullscreen?.().catch(() => {})
  phase.value = 'detail'
}

function clearCountdownTimer() {
  if (countdownTimer) {
    clearInterval(countdownTimer)
    countdownTimer = null
  }
}

onBeforeUnmount(() => {
  clearCountdownTimer()
  stopQuestionExplainHeartbeat()
})

onDeactivated(() => {
  stopQuestionExplainHeartbeat()
})

// ======================== 拖动分隔条 ========================
const leftWidth = ref(0)
let resizing = false

function initLeftWidth() {
  leftWidth.value = Math.round(window.innerWidth * 0.6)
}

function onResizeStart(e: MouseEvent) {
  e.preventDefault()
  resizing = true
  const startX = e.clientX
  const startWidth = leftWidth.value
  const minLeft = 300
  const minRight = 300
  const maxLeft = window.innerWidth - 32 - minRight

  function onMouseMove(ev: MouseEvent) {
    if (!resizing) return
    const delta = ev.clientX - startX
    leftWidth.value = Math.min(maxLeft, Math.max(minLeft, startWidth + delta))
  }

  function onMouseUp() {
    resizing = false
    document.removeEventListener('mousemove', onMouseMove)
    document.removeEventListener('mouseup', onMouseUp)
  }

  document.addEventListener('mousemove', onMouseMove)
  document.addEventListener('mouseup', onMouseUp)
}

// ======================== 讲解区缩放 ========================
const MIN_ZOOM_SCALE = 0.7
const MAX_ZOOM_SCALE = 2.5
const zoomScale = ref(1)
const zoomPercent = computed(() => Math.round(zoomScale.value * 100))
let pinchStartDistance = 0
let pinchStartScale = 1

function clampZoomScale(scale: number) {
  return Math.min(MAX_ZOOM_SCALE, Math.max(MIN_ZOOM_SCALE, scale))
}

function getTouchDistance(touches: TouchList) {
  const first = touches[0]
  const second = touches[1]
  if (!first || !second) return 0
  return Math.hypot(
    first.clientX - second.clientX,
    first.clientY - second.clientY,
  )
}

function onZoomTouchStart(e: TouchEvent) {
  if (e.touches.length !== 2) return
  pinchStartDistance = getTouchDistance(e.touches)
  pinchStartScale = zoomScale.value
}

function onZoomTouchMove(e: TouchEvent) {
  if (e.touches.length !== 2 || !pinchStartDistance) return
  e.preventDefault()
  const distance = getTouchDistance(e.touches)
  zoomScale.value = clampZoomScale(
    pinchStartScale * (distance / pinchStartDistance),
  )
}

function onZoomTouchEnd(e: TouchEvent) {
  if (e.touches.length >= 2) return
  pinchStartDistance = 0
}

function onZoomWheel(e: WheelEvent) {
  if (!e.ctrlKey && !e.metaKey) return
  e.preventDefault()
  const delta = e.deltaY > 0 ? -0.08 : 0.08
  zoomScale.value = clampZoomScale(zoomScale.value + delta)
}

function resetZoom() {
  zoomScale.value = 1
}

// ======================== 讲解模式 ========================
const currentIndex = ref(0)
const answerExpanded = ref(false)
const explanationExpanded = ref(false)
const answerPanelCollapsed = ref(false)

const currentQuestion = computed(() => {
  return paperDetail.value[currentIndex.value] || null
})

const hasAnswer = computed(() =>
  Boolean(currentQuestion.value?.xkwTitle?.answer),
)
const hasExplanation = computed(() =>
  Boolean(currentQuestion.value?.xkwTitle?.explanation),
)
const leftPanelStyle = computed(() => {
  return answerPanelCollapsed.value
    ? { flex: '1 1 auto' }
    : { flex: `0 0 ${leftWidth.value}px` }
})

function getTitleKey(item: any) {
  return (
    item?.xkwTitle?.titleId ?? item?.titleId ?? item?.xkwTitle?.id ?? item?.id
  )
}

function collapseAnswerAnalysis() {
  answerExpanded.value = false
  explanationExpanded.value = false
}

function toggleAnswer() {
  answerExpanded.value = !answerExpanded.value
}

function toggleExplanation() {
  explanationExpanded.value = !explanationExpanded.value
}

function toggleAnswerPanel() {
  answerPanelCollapsed.value = !answerPanelCollapsed.value
}

async function enterExplaining() {
  initLeftWidth()
  resetZoom()
  collapseAnswerAnalysis()
  phase.value = 'explaining'
  currentIndex.value = 0
  const started = await callExplainApi(1)
  if (started) {
    startQuestionExplainHeartbeat()
  }
}

function startQuestionExplainHeartbeat() {
  if (questionExplainHeartbeatTimer) return
  questionExplainHeartbeatTimer = setInterval(() => {
    if (phase.value !== 'explaining' || !classId) {
      stopQuestionExplainHeartbeat()
      return
    }
    void taskMgrService
      .questionExplainHeartbeat(classId)
      .catch(() => undefined)
  }, QUESTION_EXPLAIN_HEARTBEAT_INTERVAL)
}

function stopQuestionExplainHeartbeat() {
  if (!questionExplainHeartbeatTimer) return
  clearInterval(questionExplainHeartbeatTimer)
  questionExplainHeartbeatTimer = undefined
}

async function callExplainApi(status: number, overrideQuestionId?: string) {
  const questionId = overrideQuestionId || getTitleKey(currentQuestion.value)
  if (!questionId) return false
  const recordId = resourceId
  try {
    await taskMgrService.questionExplainShare({
      classId,
      questionId,
      recordId,
      status,
    })
    return true
  } catch {
    hud.error(status === 1 ? '开始讲解失败' : '结束讲解失败')
    return false
  }
}

function prevQuestion() {
  if (currentIndex.value > 0) {
    currentIndex.value--
    collapseAnswerAnalysis()
    callExplainApi(1)
  }
}

function nextQuestion() {
  if (currentIndex.value < paperDetail.value.length - 1) {
    currentIndex.value++
    collapseAnswerAnalysis()
    callExplainApi(1)
  }
}

function goToQuestion(idx: number) {
  currentIndex.value = idx
  collapseAnswerAnalysis()
  callExplainApi(1)
}

function endExplaining() {
  hud.confirm({
    content: '确定要结束讲解吗？',
    title: '提示',
    zIndex: 999_999,
    onConfirm: async () => {
      stopQuestionExplainHeartbeat()
      const lastQuestion = paperDetail.value[paperDetail.value.length - 1]
      const lastQuestionId = getTitleKey(lastQuestion)
      await callExplainApi(0, lastQuestionId)
      document.exitFullscreen?.().catch(() => {})
      hud.success('讲解已结束')
      router.back()
    },
  })
}

// ======================== 查看学生详情 ========================
const studentDialogVisible = ref(false)
const studentList = ref<any[]>([])
const studentTitle = ref('查看')

async function getTitleStudentInfo(titleId: string, markType: number) {
  const recordId = resourceId
  const res = await taskMgrService.getListTitleStudentInfo(
    recordId,
    titleId,
    markType,
  )
  if (markType === 1) {
    studentTitle.value = '满分学生'
  } else if (markType === 2) {
    studentTitle.value = '非满分学生'
  } else {
    studentTitle.value = '未作答学生'
  }
  const list = Array.isArray(res) ? res : (res?.rows ?? res?.data ?? [])
  studentList.value = list as any[]
  studentDialogVisible.value = true
}
</script>

<template>
  <!-- ==================== 试卷详情阶段 ==================== -->
  <div v-if="phase === 'detail'" v-loading="loading" class="explain-detail">
    <el-card shadow="never">
      <el-descriptions :column="3" border>
        <el-descriptions-item label="学校名称">
          {{ paperReleaseDetail?.schoolName || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="作业名称">
          {{ paperReleaseDetail?.name || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="开始时间">
          {{ paperReleaseDetail?.startTime || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="截止时间">
          {{ paperReleaseDetail?.endTime || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="学生人数">
          {{ paperReleaseDetail?.number ?? '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="完成人数">
          {{ paperReleaseDetail?.completeNumber ?? '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="作业摘要" :span="3">
          {{ paperReleaseDetail?.remark || '-' }}
        </el-descriptions-item>
      </el-descriptions>
    </el-card>

    <div class="paper-preview">
      <h3 class="section-title">试卷内容预览</h3>
      <div
        v-for="(item, idx) in paperDetail"
        :key="getTitleKey(item)"
        class="question-block"
      >
        <template
          v-if="
            Array.isArray(item.xkwTitle?.questionList) &&
            item.xkwTitle.questionList.length
          "
        >
          <PaperQuestionItem
            v-for="question in item.xkwTitle.questionList"
            :key="question.id"
            :index="item.sort ?? idx + 1"
            :question="{ ...question, score: item.score }"
            :preview="true"
          />
        </template>
        <template v-else>
          <PaperQuestionItem
            :index="item.sort ?? idx + 1"
            :question="{ ...item.xkwTitle, score: item.score }"
            :preview="true"
          />
        </template>
      </div>
    </div>

    <div class="start-btn-wrap">
      <el-button type="primary" size="large" @click="startCountdown">
        开始讲解
      </el-button>
    </div>
  </div>

  <!-- ==================== 倒计时阶段 ==================== -->
  <div v-else-if="phase === 'countdown'" class="countdown-overlay">
    <div class="countdown-content">
      <div class="countdown-number">{{ countdown }}</div>
      <p class="countdown-text">讲解即将开始...</p>
      <el-button type="danger" size="large" @click="cancelCountdown">
        取消
      </el-button>
    </div>
  </div>

  <!-- ==================== 全屏讲解阶段 ==================== -->
  <div v-else-if="phase === 'explaining'" class="explain-fullscreen">
    <div
      v-if="currentQuestion"
      class="explain-main"
      :style="{ '--explain-zoom-scale': zoomScale }"
      @touchstart="onZoomTouchStart"
      @touchmove="onZoomTouchMove"
      @touchend="onZoomTouchEnd"
      @touchcancel="onZoomTouchEnd"
      @wheel="onZoomWheel"
    >
      <!-- 左侧：题目 -->
      <div class="explain-left" :style="leftPanelStyle">
        <div class="explain-panel-header">
          <span class="panel-title">第 {{ currentIndex + 1 }} 题</span>
        </div>
        <div class="explain-panel-body question-panel-body">
          <div class="question-zoom-layer">
            <template
              v-if="
                Array.isArray(currentQuestion.xkwTitle?.questionList) &&
                currentQuestion.xkwTitle.questionList.length
              "
            >
              <PaperQuestionItem
                v-for="question in currentQuestion.xkwTitle.questionList"
                :key="question.id"
                :index="currentQuestion.sort ?? currentIndex + 1"
                :question="{ ...question, score: currentQuestion.score }"
                :preview="true"
              />
            </template>
            <template v-else>
              <PaperQuestionItem
                :index="currentQuestion.sort ?? currentIndex + 1"
                :question="{
                  ...currentQuestion.xkwTitle,
                  score: currentQuestion.score,
                }"
                :preview="true"
              />
            </template>
          </div>
        </div>
      </div>

      <!-- 拖动分隔条 -->
      <div
        class="resize-handle"
        :class="{ collapsed: answerPanelCollapsed }"
        @mousedown="!answerPanelCollapsed && onResizeStart($event)"
      >
        <button
          type="button"
          class="answer-panel-toggle"
          :aria-label="answerPanelCollapsed ? '展开答案解析' : '收起答案解析'"
          :title="answerPanelCollapsed ? '展开答案解析' : '收起答案解析'"
          @mousedown.stop
          @click.stop="toggleAnswerPanel"
        >
          <span class="toggle-arrow">
            {{ answerPanelCollapsed ? '<' : '>' }}
          </span>
          <span class="toggle-text">
            {{ answerPanelCollapsed ? '展开' : '收起' }}
          </span>
        </button>
      </div>

      <!-- 右侧：答案、解析、统计 -->
      <div
        v-show="!answerPanelCollapsed"
        class="explain-right"
        style="flex: 1; width: 0"
      >
        <div class="explain-panel-header">
          <span class="panel-title">答案与解析</span>
        </div>
        <div class="explain-panel-body">
          <div class="answer-zoom-layer">
            <!-- 答案 -->
            <div class="answer-analysis-section">
              <div class="answer-analysis-header">
                <span class="answer-analysis-title">【答案】</span>
              </div>
              <div v-if="answerExpanded && hasAnswer" class="info-content">
                <latex-text :text="currentQuestion.xkwTitle.answer" />
              </div>
              <div v-else class="answer-analysis-collapsed">
                {{
                  hasAnswer ? '答案已收起，点击底部“展开答案”查看' : '暂无答案'
                }}
              </div>
            </div>

            <!-- 解析 -->
            <div class="answer-analysis-section">
              <div class="answer-analysis-header">
                <span class="answer-analysis-title">【解析】</span>
              </div>
              <div
                v-if="explanationExpanded && hasExplanation"
                class="info-content"
              >
                <latex-text :text="currentQuestion.xkwTitle.explanation" />
              </div>
              <div v-else class="answer-analysis-collapsed">
                {{
                  hasExplanation
                    ? '解析已收起，点击底部“展开解析”查看'
                    : '暂无解析'
                }}
              </div>
            </div>

            <!-- 统计数据 -->
            <div class="stats-section">
              <div class="stats-grid">
                <div
                  class="stat-card stat-success"
                  @click="getTitleStudentInfo(getTitleKey(currentQuestion), 1)"
                >
                  <div class="stat-value">
                    {{ currentQuestion.answerStatus?.correctNum ?? 0 }}
                  </div>
                  <div class="stat-label">满分人数</div>
                </div>
                <div
                  class="stat-card stat-danger"
                  @click="getTitleStudentInfo(getTitleKey(currentQuestion), 2)"
                >
                  <div class="stat-value">
                    {{ currentQuestion.answerStatus?.errorNum ?? 0 }}
                  </div>
                  <div class="stat-label">非满分人数</div>
                </div>
                <div class="stat-card stat-primary">
                  <div class="stat-value">
                    {{ currentQuestion.answerStatus?.correctRateText ?? '0%' }}
                  </div>
                  <div class="stat-label">得分率</div>
                </div>
                <div
                  class="stat-card stat-warning"
                  @click="getTitleStudentInfo(getTitleKey(currentQuestion), 3)"
                >
                  <div class="stat-value">
                    {{ currentQuestion.answerStatus?.unSubmitNum ?? 0 }}
                  </div>
                  <div class="stat-label">未作答人数</div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 底部操作栏 -->
    <div class="explain-footer">
      <div class="footer-left">
        <el-button :disabled="currentIndex <= 0" @click="prevQuestion">
          上一题
        </el-button>
        <el-button
          :disabled="currentIndex >= paperDetail.length - 1"
          @click="nextQuestion"
        >
          下一题
        </el-button>
      </div>
      <div class="footer-center">
        <div class="question-nav">
          <span
            v-for="(_, idx) in paperDetail"
            :key="idx"
            class="nav-dot"
            :class="{ active: idx === currentIndex }"
            @click="goToQuestion(idx)"
          >
            {{ idx + 1 }}
          </span>
        </div>
      </div>
      <div class="footer-right">
        <el-button :disabled="!hasAnswer" @click="toggleAnswer">
          {{ answerExpanded ? '收起答案' : '展开答案' }}
        </el-button>
        <el-button :disabled="!hasExplanation" @click="toggleExplanation">
          {{ explanationExpanded ? '收起解析' : '展开解析' }}
        </el-button>
        <el-button @click="resetZoom">重置缩放 {{ zoomPercent }}%</el-button>
        <el-button type="danger" @click="endExplaining">结束讲解</el-button>
      </div>
    </div>

    <ViewStudents
      v-model="studentDialogVisible"
      :title="studentTitle"
      :students="studentList"
    />
  </div>
</template>

<style scoped>
@keyframes pulse {
  0%,
  100% {
    opacity: 1;
    transform: scale(1);
  }

  50% {
    opacity: 0.8;
    transform: scale(1.15);
  }
}

.explain-detail {
  padding: 20px 20px 80px;
  background-color: #fff;
}

.paper-preview {
  margin-top: 24px;
}

.section-title {
  margin-bottom: 16px;
  font-size: 18px;
  font-weight: 600;
  color: #1f2328;
}

.question-block {
  position: relative;
  padding: 16px 20px;
  margin: 16px 0;
  overflow: hidden;
  background-color: #fff;
  border: 1px solid #e6e8eb;
  border-radius: 10px;
  box-shadow: 0 4px 12px rgb(31 35 40 / 6%);
}

.question-block::before {
  position: absolute;
  top: 0;
  left: 0;
  width: 4px;
  height: 100%;
  content: '';
  background: #246cff;
}

.start-btn-wrap {
  position: fixed;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: 10;
  display: flex;
  justify-content: center;
  padding: 16px 0;
  background: #fff;
  border-top: 1px solid #ebeef5;
  box-shadow: 0 -2px 8px rgb(0 0 0 / 6%);
}

:deep(.paper-question-item .preview-toolbar) {
  display: none !important;
}

/* ==================== 倒计时阶段 ==================== */
.countdown-overlay {
  position: fixed;
  inset: 0;
  z-index: 99999;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgb(0 0 0 / 75%);
}

.countdown-content {
  display: flex;
  flex-direction: column;
  gap: 24px;
  align-items: center;
}

.countdown-number {
  font-size: 120px;
  font-weight: 700;
  line-height: 1;
  color: #fff;
  animation: pulse 1s ease-in-out infinite;
}

.countdown-text {
  font-size: 24px;
  color: rgb(255 255 255 / 80%);
}

/* ==================== 全屏讲解阶段 ==================== */
.explain-fullscreen {
  position: fixed;
  inset: 0;
  z-index: 99998;
  display: flex;
  flex-direction: column;
  background: #f0f2f5;
}

.explain-main {
  display: flex;
  flex: 1;
  padding: 16px;
  overflow: hidden;
  touch-action: pan-x pan-y;
  user-select: none;
}

.explain-left,
.explain-right {
  display: flex;
  flex-direction: column;
  overflow: hidden;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgb(0 0 0 / 8%);
}

.resize-handle {
  position: relative;
  display: flex;
  flex-shrink: 0;
  align-items: center;
  justify-content: center;
  width: 28px;
  cursor: col-resize;
  background: transparent;
  transition: background 0.2s;
}

.resize-handle:hover,
.resize-handle:active {
  background: #ecf5ff;
}

.resize-handle::before {
  width: 2px;
  height: 100%;
  content: '';
  background: #dcdfe6;
  border-radius: 2px;
  transition: background 0.2s;
}

.resize-handle:hover::before,
.resize-handle:active::before {
  background: #409eff;
}

.resize-handle.collapsed {
  cursor: default;
}

.answer-panel-toggle {
  position: absolute;
  top: 50%;
  left: 50%;
  z-index: 2;
  display: inline-flex;
  flex-direction: column;
  gap: 2px;
  align-items: center;
  justify-content: center;
  width: 42px;
  height: 72px;
  padding: 0;
  font-size: 13px;
  font-weight: 500;
  color: #409eff;
  cursor: pointer;
  background: #fff;
  border: 1px solid #d9ecff;
  border-radius: 21px;
  box-shadow: 0 2px 10px rgb(64 158 255 / 18%);
  transform: translate(-50%, -50%);
  transition:
    color 0.2s,
    background 0.2s,
    border-color 0.2s,
    box-shadow 0.2s;
}

.answer-panel-toggle:hover,
.answer-panel-toggle:focus-visible {
  color: #fff;
  background: #409eff;
  border-color: #409eff;
  box-shadow: 0 4px 14px rgb(64 158 255 / 28%);
  outline: none;
}

.toggle-arrow {
  font-size: 18px;
  line-height: 1;
}

.toggle-text {
  line-height: 1.2;
}

.explain-panel-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 14px 20px;
  border-bottom: 1px solid #ebeef5;
}

.panel-title {
  font-size: 16px;
  font-weight: 600;
  color: #1f2328;
}

.explain-panel-body {
  flex: 1;
  padding: 20px;
  overflow: hidden auto;
}

.question-panel-body {
  overflow: auto;
}

.question-zoom-layer {
  width: 100%;
  transform: scale(var(--explain-zoom-scale));
  transform-origin: left top;
}

.answer-zoom-layer {
  zoom: var(--explain-zoom-scale);
}

@supports not (zoom: 1) {
  .answer-zoom-layer {
    width: calc(100% / var(--explain-zoom-scale));
    transform: scale(var(--explain-zoom-scale));
    transform-origin: left top;
  }
}

.info-section {
  display: flex;
  align-items: flex-start;
  min-width: 0;
  padding: 12px 0;
  overflow: hidden;
  border-bottom: 1px dashed #ebeef5;
}

.answer-analysis-section {
  padding: 12px 0;
  border-bottom: 1px dashed #ebeef5;
}

.answer-analysis-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 10px;
}

.answer-analysis-title {
  font-weight: 600;
  color: #246cff;
}

.answer-analysis-collapsed {
  padding: 18px 16px;
  font-size: 14px;
  color: #909399;
  text-align: center;
  background: #f7f8fa;
  border: 1px dashed #dcdfe6;
  border-radius: 8px;
}

.info-label {
  min-width: 60px;
  font-weight: 600;
  color: #246cff;
  white-space: nowrap;
}

.info-content {
  flex: 1;
  min-width: 0;
  overflow: hidden;
  line-height: 1.8;
  word-break: break-all;
  overflow-wrap: break-word;
}

.info-content :deep(img) {
  max-width: 100%;
  height: auto;
}

.info-content :deep(*) {
  max-width: 100%;
  overflow-wrap: break-word;
}

.stats-section {
  margin-top: 20px;
}

.stats-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 12px;
}

.stat-card {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 16px 12px;
  cursor: pointer;
  border-radius: 10px;
  transition: transform 0.2s;
}

.stat-card:hover {
  transform: translateY(-2px);
}

.stat-card.stat-success {
  background: #f0f9eb;
  border: 1px solid #e1f3d8;
}

.stat-card.stat-danger {
  background: #fef0f0;
  border: 1px solid #fde2e2;
}

.stat-card.stat-primary {
  cursor: default;
  background: #ecf5ff;
  border: 1px solid #d9ecff;
}

.stat-card.stat-primary:hover {
  transform: none;
}

.stat-card.stat-warning {
  background: #fdf6ec;
  border: 1px solid #faecd8;
}

.stat-value {
  font-size: 28px;
  font-weight: 700;
  line-height: 1.2;
}

.stat-success .stat-value {
  color: #67c23a;
}

.stat-danger .stat-value {
  color: #f56c6c;
}

.stat-primary .stat-value {
  color: #409eff;
}

.stat-warning .stat-value {
  color: #e6a23c;
}

.stat-label {
  margin-top: 6px;
  font-size: 13px;
  color: #909399;
}

/* ==================== 底部操作栏 ==================== */
.explain-footer {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 60px;
  padding: 0 24px;
  background: #fff;
  border-top: 1px solid #ebeef5;
  box-shadow: 0 -2px 8px rgb(0 0 0 / 6%);
}

.footer-left,
.footer-right {
  display: flex;
  gap: 8px;
  align-items: center;
}

.footer-center {
  display: flex;
  flex: 1;
  min-width: 0;
  margin: 0 16px;
  overflow-x: auto;
  overflow-y: hidden;
}

.question-nav {
  display: flex;
  flex-wrap: nowrap;
  gap: 6px;
  width: max-content;
  min-width: max-content;
  margin: 0 auto;
}

.nav-dot {
  display: inline-flex;
  flex: 0 0 auto;
  align-items: center;
  justify-content: center;
  min-width: 32px;
  height: 32px;
  padding: 0 4px;
  font-size: 13px;
  font-weight: 500;
  color: #606266;
  cursor: pointer;
  background: #f2f3f5;
  border-radius: 6px;
  transition: all 0.2s;
}

.nav-dot:hover {
  color: #409eff;
  background: #ecf5ff;
}

.nav-dot.active {
  color: #fff;
  background: #409eff;
}

/* ==================== 详情阶段 ==================== */
</style>
