<template>
  <div class="question-bank-panel">
    <PageHeader
      title="题库管理与审批"
      description="管理和维护AI生成的试题库，审核待审批题目"
    />

    <div class="toolbar">
      <div class="toolbar-main">
        <div class="search-group">
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" class="search-icon">
            <circle cx="11" cy="11" r="8"></circle>
            <line x1="21" y1="21" x2="16.65" y2="16.65"></line>
          </svg>
          <input
            v-model="searchForm.keyword"
            type="text"
            class="search-input"
            placeholder="搜索题目标题或内容..."
            @keyup.enter="handleSearch"
          />
        </div>

        <div class="filter-group">
          <div class="filter-item">
            <label class="filter-label">
              <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <polygon points="12 2 2 7 12 12 22 7 12 2"></polygon>
              </svg>
              题型
            </label>
            <select v-model="searchForm.type" class="filter-select" @change="handleSearch">
              <option value="">全部</option>
              <option v-for="opt in questionTypeOptions" :key="opt.value" :value="opt.value">{{ opt.label }}</option>
            </select>
          </div>

          <div class="filter-item">
            <label class="filter-label">
              <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <path d="M4 15s1-1 4-1 5 2 8 2 4-6 4-6V5a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V9"></path>
              </svg>
              难度
            </label>
            <select v-model="searchForm.difficulty" class="filter-select" @change="handleSearch">
              <option value="">全部</option>
              <option v-for="opt in difficultyOptions" :key="opt.value" :value="opt.value">{{ opt.label }}</option>
            </select>
          </div>

          <div class="filter-item">
            <label class="filter-label">
              <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"></path>
                <polyline points="22 4 12 14.01 9 11.01"></polyline>
              </svg>
              状态
            </label>
            <select v-model="searchForm.status" class="filter-select" @change="handleSearch">
              <option value="">全部</option>
              <option v-for="opt in statusOptions" :key="opt.value" :value="opt.value">{{ opt.label }}</option>
            </select>
          </div>

          <div class="filter-item">
            <label class="filter-label">
              <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path>
                <polyline points="14 2 14 8 20 8"></polyline>
              </svg>
              文件
            </label>
            <select v-model="searchForm.documentId" class="filter-select" @change="handleSearch">
              <option v-for="opt in fileOptions" :key="opt.value" :value="opt.value">{{ opt.label }}</option>
            </select>
          </div>

          <button class="btn btn-secondary reset-btn" @click="handleReset">
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <path d="M23 4v6h-6"></path>
              <path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"></path>
            </svg>
            重置
          </button>
        </div>
      </div>

      <div class="toolbar-footer">
        <div class="result-info">
          <span class="result-count"><strong>{{ pagination.total }}</strong> 条题目</span>
        </div>
        <div class="toolbar-actions">
          <button class="action-chip active">
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <line x1="8" y1="6" x2="21" y2="6"></line>
              <line x1="8" y1="12" x2="21" y2="12"></line>
              <line x1="8" y1="18" x2="21" y2="18"></line>
              <line x1="3" y1="6" x2="3.01" y2="6"></line>
              <line x1="3" y1="12" x2="3.01" y2="12"></line>
              <line x1="3" y1="18" x2="3.01" y2="18"></line>
            </svg>
            列表视图
          </button>
        </div>
      </div>
    </div>

    <ContentCard title="题目列表">
      <DataTable
        :dataSource="questions"
        :columns="columns"
        :loading="loading"
        :pagination="false"
        :row-key="(record) => record.id + '_' + pagination.current"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'type'">
            <span :class="['type-badge', record.type]">{{ getTypeLabel(record.type) }}</span>
          </template>
          <template v-if="column.key === 'difficulty'">
            <span :class="['difficulty-badge', `level-${record.difficulty}`]">
              {{ getDifficultyLabel(record.difficulty) }}
            </span>
          </template>
          <template v-if="column.key === 'status'">
            <span :class="['status-badge', record.status || 'pending']">{{ getStatusLabel(record.status) }}</span>
          </template>
          <template v-if="column.key === 'action'">
            <button class="btn btn-text btn-sm" @click="viewQuestion(record)">查看</button>
            <button class="btn btn-text btn-sm" @click="editQuestion(record)">编辑</button>
            <template v-if="(record.status || 'pending') === 'pending'">
              <button class="btn btn-approve-text btn-sm" @click="approveQuestion(record)" :disabled="reviewingId === record.id">通过</button>
              <button class="btn btn-reject-text btn-sm" @click="rejectQuestion(record)" :disabled="reviewingId === record.id">驳回</button>
            </template>
            <button class="btn btn-danger-text btn-sm" @click="confirmDelete(record)">删除</button>
          </template>
        </template>
      </DataTable>

      <div v-if="Number(pagination.total || 0) > 0" class="table-pagination">
        <a-pagination
          :current="pagination.current"
          :page-size="pagination.pageSize"
          :total="Number(pagination.total || 0)"
          :show-size-changer="true"
          :show-quick-jumper="true"
          size="small"
          :show-total="(total) => `共 ${total || 0} 条`"
          @change="onPageChange"
        />
      </div>
    </ContentCard>
  </div>

  <!-- 查看题目弹窗 -->
  <Teleport to="body">
    <div v-if="viewModalVisible" class="modal-overlay" @click.self="viewModalVisible = false">
      <div class="modal-dialog modal-lg">
        <div class="modal-header">
          <h3>题目详情</h3>
          <button class="close-btn" @click="viewModalVisible = false">×</button>
        </div>
        <div v-if="viewingLoading" class="modal-loading">
          <div class="loading-spinner"></div>
          <span>正在加载题目详情...</span>
        </div>
        <div v-else class="modal-body" v-if="viewingRecord">
          <div class="detail-meta-row">
            <span :class="['type-badge', viewingRecord.type]">{{ getTypeLabel(viewingRecord.type) }}</span>
            <span :class="['difficulty-badge', `level-${viewingRecord.difficulty}`]">{{ getDifficultyLabel(viewingRecord.difficulty) }}</span>
            <span class="detail-meta-id">ID: {{ viewingRecord.id }}</span>
          </div>

          <div class="detail-section">
            <label class="section-label">题干</label>
            <p class="detail-stem">{{ viewingRecord.stem || '（无题干内容）' }}</p>
          </div>

          <!-- 选择题：显示选项和正确答案 -->
          <template v-if="viewingRecord.type === 'single_choice' || viewingRecord.type === 'multiple_choice'">
            <div class="detail-section">
              <label class="section-label">选项</label>
              <div class="options-list-view">
                <div
                  v-for="(opt, idx) in parseOptions(viewingRecord)"
                  :key="idx"
                  :class="['option-item-view', { 'is-correct': opt.isCorrect }]"
                >
                  <span class="option-key-view">{{ opt.key }}</span>
                  <span class="option-text-view">{{ opt.text }}</span>
                  <span v-if="opt.isCorrect" class="correct-tag">正确答案</span>
                </div>
              </div>
            </div>
          </template>

          <!-- 判断题 -->
          <template v-if="viewingRecord.type === 'true_false'">
            <div class="detail-section">
              <label class="section-label">答案</label>
              <div class="tf-answer-display">
                <div :class="['tf-option-box', { active: normalizeTfAnswer(viewingRecord.answer) === 'T' }]">
                  ✓ 正确
                </div>
                <div :class="['tf-option-box', { active: normalizeTfAnswer(viewingRecord.answer) === 'F' }]">
                  ✗ 错误
                </div>
              </div>
            </div>
          </template>

          <!-- 填空题 -->
          <template v-if="viewingRecord.type === 'fill_blank'">
            <div class="detail-section">
              <label class="section-label">参考答案</label>
              <div class="fb-answer-view">
                <template v-if="parsedBlankAnswers(viewingRecord).length > 0">
                  <div
                    v-for="(blank, idx) in parsedBlankAnswers(viewingRecord)"
                    :key="idx"
                    class="blank-tag"
                  >
                    <span class="blank-index">{{ idx + 1 }}</span>
                    <span class="blank-text">{{ blank }}</span>
                  </div>
                </template>
                <span v-else class="fb-no-answer">未设置参考答案</span>
              </div>
            </div>
          </template>

          <!-- 简答题 -->
          <template v-if="viewingRecord.type === 'subjective'">
            <div class="detail-section">
              <label class="section-label">参考答案</label>
              <div class="fb-answer-display">
                {{ viewingRecord.answer || viewingRecord.content?.answer || '未设置参考答案' }}
              </div>
            </div>
          </template>

          <div class="detail-footer-info">
            <span>创建时间：{{ viewingRecord.createdAt || '-' }}</span>
          </div>
        </div>
      </div>
    </div>
  </Teleport>

  <!-- 编辑题目弹窗 -->
  <Teleport to="body">
    <div v-if="editModalVisible" class="modal-overlay" @click.self="editModalVisible = false">
      <div class="modal-dialog modal-lg">
        <div class="modal-header">
          <h3>编辑题目</h3>
          <button class="close-btn" @click="editModalVisible = false">×</button>
        </div>
        <div v-if="editingLoading" class="modal-loading">
          <div class="loading-spinner"></div>
          <span>正在加载题目详情...</span>
        </div>
        <div v-else class="modal-body" v-if="editingRecord">
          <div class="form-item" style="margin-bottom: 14px;">
            <label class="section-label">题干内容</label>
            <textarea v-model="editForm.stem" class="form-textarea" rows="3"></textarea>
          </div>

          <div style="display: flex; gap: 14px; margin-bottom: 14px;">
            <div class="form-item" style="flex:1; margin-bottom:0;">
              <label class="section-label">难度等级</label>
              <select v-model.number="editForm.difficulty" class="filter-select">
                <option :value="1">简单</option>
                <option :value="2">中等</option>
                <option :value="3">困难</option>
              </select>
            </div>
          </div>

          <!-- 选择题：编辑选项和正确答案 -->
          <template v-if="editingRecord.type === 'single_choice' || editingRecord.type === 'multiple_choice'">
            <div class="detail-section">
              <label class="section-label">选项与答案</label>
              <div class="options-edit-list">
                <div
                  v-for="(opt, idx) in editForm.options"
                  :key="idx"
                  class="option-edit-row"
                >
                  <span class="option-key-edit">{{ opt.key }}</span>
                  <input
                    v-model="opt.text"
                    type="text"
                    class="option-input-edit"
                    :placeholder="'选项' + opt.key + '内容'"
                  />
                  <button
                    :class="['correct-toggle', { active: opt.isCorrect }]"
                    @click="setCorrectOption(idx)"
                    title="设为正确答案"
                  >
                    {{ opt.isCorrect ? '✓ 正确' : '设为正确' }}
                  </button>
                </div>
              </div>
              <p class="edit-hint">单选题只能有一个正确答案，多选题可多个</p>
            </div>
          </template>

          <!-- 判断题 -->
          <template v-if="editingRecord.type === 'true_false'">
            <div class="detail-section">
              <label class="section-label">正确答案</label>
              <div class="tf-answer-display">
                <button
                  :class="['tf-option-box', { active: editForm.answer === 'T' }]"
                  @click="editForm.answer = 'T'"
                >✓ 正确</button>
                <button
                  :class="['tf-option-box', { active: editForm.answer === 'F' }]"
                  @click="editForm.answer = 'F'"
                >✗ 错误</button>
              </div>
            </div>
          </template>

          <!-- 填空题 -->
          <template v-if="editingRecord.type === 'fill_blank'">
            <div class="detail-section">
              <label class="section-label">参考答案</label>
              <p class="edit-hint" style="margin-bottom: 8px;">多个填空答案请用逗号 <code>,</code> 分隔，如：<code>北京,故宫,1949</code></p>
              <textarea
                v-model="editForm.answer"
                class="form-textarea"
                rows="3"
                placeholder="输入参考答案，多空用逗号分隔..."
              ></textarea>
              <div v-if="blankPreviewCount > 0" class="blank-preview">
                <span class="preview-label">已识别 {{ blankPreviewCount }} 个填空：</span>
                <span v-for="(b, i) in blankPreviewList" :key="i" class="preview-chip">{{ b }}</span>
              </div>
            </div>
          </template>

          <!-- 简答题 -->
          <template v-if="editingRecord.type === 'subjective'">
            <div class="detail-section">
              <label class="section-label">参考答案</label>
              <textarea
                v-model="editForm.answer"
                class="form-textarea"
                rows="5"
                placeholder="输入参考答案..."
              ></textarea>
            </div>
          </template>
        </div>
        <div class="modal-footer">
          <button class="btn btn-secondary btn-sm" @click="editModalVisible = false">取消</button>
          <button class="btn btn-primary btn-sm" :disabled="savingEdit" @click="saveEdit">
            {{ savingEdit ? '保存中...' : '保存修改' }}
          </button>
        </div>
      </div>
    </div>
  </Teleport>
</template>

<script setup>
import { computed, ref, reactive, onMounted } from 'vue'
import { Modal, Pagination as APagination, message } from 'ant-design-vue'
import PageHeader from '../common/PageHeader.vue'
import ContentCard from '../common/ContentCard.vue'
import DataTable from '../common/DataTable.vue'
import { useQuestionBank } from './composables/useQuestionBank.js'
import { questionAPI } from '../../api/question.js'

const {
  questions,
  loading,
  pagination,
  searchForm,
  questionTypeOptions,
  difficultyOptions,
  statusOptions,
  fileOptions,
  loadFileList,
  loadQuestions,
  handleSearch,
  handleReset,
  handleTableChange,
  handleDeleteQuestion,
  changeLocalPage
} = useQuestionBank()

onMounted(() => {
  loadQuestions()
  loadFileList()
})

const columns = [
  { title: 'ID', dataIndex: 'id', key: 'id', width: 110, customRender: ({ text, record }) => {
    if (!text) return '-'
    const s = String(text)
    const short = s.length > 12 ? s.substring(0, 8) + '…' : s
    return { children: short, props: { title: s } }
  }},
  { title: '题型', dataIndex: 'type', key: 'type', width: 100 },
  { title: '题目内容', dataIndex: 'stem', key: 'stem', ellipsis: true },
  { title: '难度', dataIndex: 'difficulty', key: 'difficulty', width: 80 },
  { title: '状态', dataIndex: 'status', key: 'status', width: 90 },
  { title: '创建时间', dataIndex: 'createdAt', key: 'createdAt', width: 160 },
  { title: '操作', key: 'action', width: 240, fixed: 'right' }
]

const paginationConfig = computed(() => ({
  current: pagination.current,
  pageSize: pagination.pageSize,
  total: pagination.total,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total) => `共 ${total} 条`
}))

const getTypeLabel = (type) => {
  const typeMap = {
    single_choice: '单选',
    multiple_choice: '多选',
    true_false: '判断',
    fill_blank: '填空',
    subjective: '简答'
  }
  return typeMap[type] || type
}

const getDifficultyLabel = (difficulty) => {
  const map = { 1: '简单', 2: '中等', 3: '困难' }
  return map[difficulty] || '未知'
}

const getStatusLabel = (status) => {
  const map = { pending: '待审核', approved: '已通过', rejected: '已驳回' }
  return map[status] || '待审核'
}

const viewModalVisible = ref(false)
const editModalVisible = ref(false)
const viewingRecord = ref(null)
const editingRecord = ref(null)
const savingEdit = ref(false)
const editForm = reactive({ stem: '', difficulty: 2, answer: '', options: [] })

const parseOptions = (record) => {
  const opts = record?.options
  if (Array.isArray(opts) && opts.length > 0) return opts

  const content = record?.content || {}
  const contentOpts = content?.options || content?.choices || content?.items || []
  if (Array.isArray(contentOpts) && contentOpts.length > 0) return contentOpts

  if (content?.body) {
    const bodyOpts = content.body.options || content.body.choices || content.body.items || []
    if (Array.isArray(bodyOpts) && bodyOpts.length > 0) return bodyOpts
  }

  if (record?.data) {
    const dataOpts = record.data.options || record.data.choices || []
    if (Array.isArray(dataOpts) && dataOpts.length > 0) return dataOpts
  }

  const keys = ['A', 'B', 'C', 'D']
  return keys.map(k => ({ key: k, text: `（未设置${k}选项）`, isCorrect: false }))
}

// Normalize true/false answer to 'T' or 'F' string
const normalizeTfAnswer = (val) => {
  if (val === null || val === undefined || val === '') return ''
  if (typeof val === 'boolean') return val ? 'T' : 'F'
  const s = String(val).trim().toUpperCase()
  if (s === 'T' || s === 'TRUE' || s === '1' || s === 'YES' || s === '对' || s === '正确') return 'T'
  if (s === 'F' || s === 'FALSE' || s === '0' || s === 'NO' || s === '错' || s === '错误') return 'F'
  return ''
}

// Parse fill-blank answers: split by , ；; newline
const splitBlankAnswers = (raw) => {
  if (raw === null || raw === undefined || raw === '') return []
  const s = String(raw).trim()
  return s.split(/[,，;；\n\r]+/).map(b => b.trim()).filter(b => b.length > 0)
}

const parsedBlankAnswers = (record) => {
  const raw = record?.answer ?? record?.content?.answer
  return splitBlankAnswers(raw)
}

// Computed properties for blank preview in edit mode
const blankPreviewCount = computed(() => splitBlankAnswers(editForm.answer).length)
const blankPreviewList = computed(() => splitBlankAnswers(editForm.answer))

const setCorrectOption = (idx) => {
  if (!editForm.options[idx]) return
  const isSingleChoice = editingRecord.value?.type === 'single_choice'
  if (isSingleChoice) {
    editForm.options.forEach((opt, i) => { opt.isCorrect = i === idx })
  } else {
    editForm.options[idx].isCorrect = !editForm.options[idx].isCorrect
  }
}

const viewingLoading = ref(false)
const editingLoading = ref(false)

const enrichDetailData = (raw) => {
  if (!raw) return null

  // Unwrap nested data wrapper: { code, data: { id, stem, options... } }
  let source = raw
  if (raw.data && (raw.data.id || raw.data.stem || raw.data.content || raw.data.options || raw.data.answer)) {
    source = raw.data
  }

  const content = source.content || source
  const rawOptions = source.options || content?.options || content?.choices ||
    content?.items || (content?.body?.options) || (content?.body?.choices) ||
    (content?.data?.options) || (content?.data?.choices) || []
  const rawAnswer = source.answer ?? content?.answer ?? content?.correct_answer ??
    source.correctAnswer ?? content?.correctAnswer ?? null

  console.log('[enrichDetailData] 原始数据字段检查:', {
    id: source.id || raw.id,
    hasRawOptions: Array.isArray(rawOptions) && rawOptions.length > 0,
    rawOptionsLen: Array.isArray(rawOptions) ? rawOptions.length : 'not-array',
    sourceTopKeys: Object.keys(source).slice(0, 12),
    rawTopKeys: Object.keys(raw).slice(0, 8),
    contentType: typeof content,
    contentKeys: typeof content === 'object' && content !== source ? Object.keys(content).slice(0, 10) : 'same-as-source',
    rawAnswer: rawAnswer,
    answerType: typeof rawAnswer
  })

  let options = []
  if (Array.isArray(rawOptions) && rawOptions.length > 0) {
    options = rawOptions.map((opt, i) => {
      if (typeof opt === 'string') {
        return { key: String.fromCharCode(65 + i), text: opt, isCorrect: false }
      }
      const key = opt.key || opt.label || String.fromCharCode(65 + i)
      const text = opt.text || opt.content || opt.value || ''
      const isCorrect = !!(opt.isCorrect || opt.is_correct || opt.correct || opt.is_right)
      return { key, text, isCorrect }
    })

    if (rawAnswer !== null && rawAnswer !== undefined && options.length > 0) {
      let answerKeys = []
      if (Array.isArray(rawAnswer)) {
        answerKeys = rawAnswer.map(a => String(a).toUpperCase().trim())
      } else {
        answerKeys = String(rawAnswer).toUpperCase().split(/[,，]/).map(s => s.trim())
      }
      options.forEach(opt => {
        opt.isCorrect = answerKeys.includes(opt.key)
      })
    }
  }

  return {
    id: source.id || raw.id,
    type: source.questionType || source.type,
    stem: content?.stem || source.stem || raw.stem || source.title || '无题干',
    difficulty: source.difficulty ?? raw.difficulty ?? undefined,
    score: source.score ?? raw.score,
    status: source.status || raw.status || 'pending',
    createdAt: source.createdAt || source.created_at || raw.createdAt || '-',
    answer: rawAnswer,
    options,
    content
  }
}

const viewQuestion = async (record) => {
  console.log('[查看] 列表原始 record:', JSON.stringify({
    id: record.id, type: record.type,
    hasOptions: Array.isArray(record.options) && record.options.length > 0,
    optionsCount: record.options?.length,
    optionsKeys: record.options?.map(o => o.key),
    answer: record.answer,
    contentKeys: record.content ? Object.keys(record.content) : 'no-content'
  }))
  viewingRecord.value = enrichDetailData(record) || record
  console.log('[查看] enrichDetailData 结果 options:', viewingRecord.value.options?.length, '条',
    viewingRecord.value.options?.map(o => o.key))
  viewModalVisible.value = true
  viewingLoading.value = true

  try {
    const res = await questionAPI.getQuestionById(record.id)
    console.log('[查看] 详情接口原始响应 topKeys:', Object.keys(res?.data || res || {}).slice(0, 12))
    const rawDetail = res?.data || res
    // Check both rawDetail and rawDetail.data for actual question data
    const hasQuestionData = rawDetail
      && (rawDetail.id || rawDetail.stem || rawDetail.content
        || (rawDetail.data && (rawDetail.data.id || rawDetail.data.stem || rawDetail.data.content || rawDetail.data.options)))
    if (hasQuestionData) {
      const enriched = enrichDetailData(rawDetail)
      console.log('[查看] 详情 enrich 结果 options:', enriched?.options?.length, '条',
        enriched?.options?.map(o => `${o.key}:${o.text?.substring(0,20)}`))
      if (enriched) {
        viewingRecord.value = enriched
      }
    }
  } catch (error) {
    console.warn('[查看] 获取详情失败，使用列表数据:', error.message?.substring(0, 100))
  } finally {
    viewingLoading.value = false
  }
}

const editQuestion = async (record) => {
  console.log('[编辑] 列表原始 record:', JSON.stringify({
    id: record.id, type: record.type,
    hasOptions: Array.isArray(record.options) && record.options.length > 0,
    optionsCount: record.options?.length,
    optionsKeys: record.options?.map(o => o.key),
    answer: record.answer
  }))
  const baseRecord = enrichDetailData(record) || record
  console.log('[编辑] baseRecord options:', baseRecord.options?.length, '条')
  editingRecord.value = baseRecord
  editForm.stem = baseRecord.stem || ''
  editForm.difficulty = baseRecord.difficulty || 2
  editForm.answer = baseRecord.type === 'true_false'
    ? normalizeTfAnswer(baseRecord.answer)
    : (baseRecord.answer ?? '')

  if (baseRecord.options && baseRecord.options.length > 0) {
    editForm.options = baseRecord.options.map(opt => ({ ...opt }))
    console.log('[编辑] 初始化 editForm.options:', editForm.options.length, '条')
  } else {
    editForm.options = []
    console.log('[编辑] ⚠️ baseRecord.options 为空！editForm 设为空数组')
  }

  editModalVisible.value = true
  editingLoading.value = true

  try {
    const res = await questionAPI.getQuestionById(record.id)
    const rawDetail = res?.data || res
    console.log('[编辑] 详情接口原始响应:', JSON.stringify(rawDetail, null, 2))
    console.log('[编辑] 详情接口原始响应 topKeys:', Object.keys(rawDetail || {}).slice(0, 12))
    const hasQuestionData = rawDetail
      && (rawDetail.id || rawDetail.stem || rawDetail.content
        || (rawDetail.data && (rawDetail.data.id || rawDetail.data.stem || rawDetail.data.content || rawDetail.data.options)))
    if (hasQuestionData) {
      const enriched = enrichDetailData(rawDetail)
      console.log('[编辑] 详情 enrich options:', enriched?.options?.length, '条',
        enriched?.options?.map(o => `${o.key}:${o.text?.substring(0,20)}`))
      if (enriched) {
        editingRecord.value = enriched
        editForm.stem = enriched.stem || ''
        editForm.difficulty = enriched.difficulty || 2
        editForm.answer = enriched.type === 'true_false'
          ? normalizeTfAnswer(enriched.answer)
          : (enriched.answer ?? '')

        if (enriched.options && enriched.options.length > 0) {
          editForm.options = enriched.options.map(opt => ({ ...opt }))
          console.log('[编辑] 详情覆盖 editForm.options:', editForm.options.length, '条')
        } else {
          console.log('[编辑] ⚠️ 详情接口返回的 options 也为空!')
        }
      }
    }
  } catch (error) {
    console.warn('[编辑] 获取详情失败，使用列表数据:', error.message?.substring(0, 100))
  } finally {
    editingLoading.value = false
  }
}

const saveEdit = async () => {
  if (!editingRecord.value) return
  savingEdit.value = true

  try {
    const rec = editingRecord.value
    const isChoice = rec.type === 'single_choice' || rec.type === 'multiple_choice'
    const correctOpts = editForm.options.filter(o => o.isCorrect).map(o => o.key)

    // 答案：所有题型统一转为字符串（与 POST /api/question 创建接口格式一致）
    // 后端读取返回数组，但写入时要求字符串
    let answerStr
    if (isChoice) {
      answerStr = correctOpts.join(',')
    } else if (rec.type === 'fill_blank') {
      // 填空题：用逗号分隔多个答案
      answerStr = splitBlankAnswers(editForm.answer).join(',')
    } else {
      answerStr = editForm.answer || ''
    }

    // 严格匹配创建接口的数据结构（参考完整curl测试手册 13.2 创建题目）
    const contentObj = {
      stem: editForm.stem,
      data: {},
      answer: answerStr
    }

    if (isChoice && editForm.options.length > 0) {
      contentObj.data.options = editForm.options.map(o => ({ key: o.key, content: o.text }))
    } else if (rec.type === 'true_false') {
      contentObj.data.options = [
        { key: 'T', content: '正确' },
        { key: 'F', content: '错误' }
      ]
    } else if (rec.type === 'fill_blank') {
      const blanks = splitBlankAnswers(editForm.answer)
      if (blanks.length > 0) contentObj.data.blank_count = blanks.length
    }

    const updateData = {
      question_type: rec.type,
      difficulty: editForm.difficulty,
      content: contentObj
    }

    // 透传创建接口中的额外字段
    if (rec.score != null) updateData.score = rec.score
    if (rec.document_name || rec.documentName) updateData.document_name = rec.document_name || rec.documentName

    console.log('[保存] 更新题目 - id:', rec.id, 'type:', rec.type)
    console.log('[保存] 发送 payload:', JSON.stringify(updateData, null, 2))
    await questionAPI.updateQuestion(rec.id, updateData)

    editingRecord.value.stem = editForm.stem
    editingRecord.value.difficulty = editForm.difficulty
    editingRecord.value.answer = answerStr
    if (editForm.options.length > 0) {
      editingRecord.value.options = [...editForm.options]
    }

    const idx = questions.value.findIndex(q => q.id === editingRecord.value.id)
    if (idx !== -1) {
      questions.value[idx] = { ...questions.value[idx], stem: editForm.stem, difficulty: editForm.difficulty, answer: answerStr }
      if (editForm.options.length > 0) questions.value[idx].options = [...editForm.options]
    }

    message.success('题目已保存')
    editModalVisible.value = false
  } catch (error) {
    const serverError = error.response?.data
    console.error('[保存] 更新题目失败:', {
      status: error.response?.status,
      statusText: error.response?.statusText,
      serverData: JSON.stringify(serverError, null, 2),
      message: error.message
    })
    const errMsg = serverError?.message || serverError?.error || error.message || '未知错误'
    message.error('保存失败: ' + errMsg)
  } finally {
    savingEdit.value = false
  }
}

const confirmDelete = (record) => {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除题目 "${(record.stem || '').substring(0, 50)}..." 吗？`,
    okText: '确认删除',
    okType: 'danger',
    cancelText: '取消',
    onOk() {
      handleDeleteQuestion(record.id)
    }
  })
}

const reviewingId = ref(null)

const reloadAndSortPendingFirst = async () => {
  pagination.current = 1
  await loadQuestions()
  questions.value.sort((a, b) => {
    const aPending = (a.status || 'pending') === 'pending' ? 0 : 1
    const bPending = (b.status || 'pending') === 'pending' ? 0 : 1
    return aPending - bPending
  })
}

const approveQuestion = async (record) => {
  const questionId = record.id
  reviewingId.value = questionId
  try {
    await questionAPI.reviewQuestion(questionId, 'approved', '')
    message.success('已通过该题目')
    await reloadAndSortPendingFirst()
  } catch (error) {
    console.error('[审批] 通过失败:', error)
    message.error('审批失败: ' + (error.message || '未知错误'))
  } finally {
    reviewingId.value = null
  }
}

const rejectQuestion = async (record) => {
  const questionId = record.id
  reviewingId.value = questionId
  try {
    await questionAPI.reviewQuestion(questionId, 'rejected', '')
    message.success('已驳回该题目')
    await reloadAndSortPendingFirst()
  } catch (error) {
    console.error('[审批] 驳回失败:', error)
    message.error('驳回失败: ' + (error.message || '未知错误'))
  } finally {
    reviewingId.value = null
  }
}

const onPageChange = async (page, pageSize) => {
  console.log(`[分页] @change 触发: page=${page}, pageSize=${pageSize}`)
  // 搜索模式走前端本地分页，正常模式走后端分页
  await changeLocalPage(page, pageSize)
  console.log(`[分页] 变更后 current=${pagination.current}, pageSize=${pagination.pageSize}, questions.length=${questions.value?.length || 0}`)
}
</script>

<style scoped>
.question-bank-panel {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 16px;
  overflow-y: auto;
  overflow-x: hidden;
  min-width: 0;
  gap: 16px;
}

/* ========== 工具栏重新设计 ========== */
.toolbar {
  background: #FFFFFF;
  border: 1px solid #E9ECEF;
  border-radius: 10px;
}

.toolbar-main {
  display: flex;
  flex-direction: column;
  gap: 14px;
  padding: 18px 20px 16px;
  border-bottom: 1px solid #F1F3F5;
}

.search-group {
  display: flex;
  align-items: center;
  gap: 10px;
  position: relative;
}

.search-icon {
  color: #ADB5BD;
  flex-shrink: 0;
  pointer-events: none;
  transition: color 0.15s ease;
}

.search-group:focus-within .search-icon {
  color: #212529;
}

.search-input {
  flex: 1;
  height: 38px;
  padding: 0 14px 0 12px;
  border: 1.5px solid #DEE2E6;
  border-radius: 8px;
  font-size: 13.5px;
  color: #212529;
  background: #FAFBFC;
  transition: all 0.2s ease;
  outline: none;
}

.search-input::placeholder {
  color: #ADB5BD;
}

.search-input:hover {
  border-color: #CED4DA;
  background: #FFFFFF;
}

.search-input:focus {
  border-color: #212529;
  background: #FFFFFF;
  box-shadow: 0 0 0 3px rgba(33, 37, 41, 0.06);
}

.filter-group {
  display: flex;
  align-items: flex-end;
  gap: 10px;
  flex-wrap: wrap;
}

.filter-item {
  display: flex;
  flex-direction: column;
  gap: 5px;
  min-width: 100px;
}

.filter-label {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  font-size: 11.5px;
  font-weight: 600;
  color: #868E96;
  text-transform: uppercase;
  letter-spacing: 0.04em;
}

.filter-label svg {
  opacity: 0.6;
}

.filter-select {
  height: 34px;
  padding: 0 28px 0 10px;
  border: 1.5px solid #DEE2E6;
  border-radius: 7px;
  font-size: 13px;
  color: #212529;
  background-color: #FFFFFF;
  background-image: url("data:image/svg+xml,%3Csvg width='10' height='6' viewBox='0 0 10 6' fill='none' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M1 1L5 5L9 1' stroke='%23868E96' stroke-width='1.5' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E");
  background-repeat: no-repeat;
  background-position: right 10px center;
  appearance: none;
  -webkit-appearance: none;
  cursor: pointer;
  transition: all 0.15s ease;
}

.filter-select:hover {
  border-color: #ADB5BD;
}

.filter-select:focus {
  outline: none;
  border-color: #212529;
  box-shadow: 0 0 0 3px rgba(33, 37, 41, 0.06);
}

.search-btn,
.reset-btn {
  height: 34px;
  padding: 0 18px;
  border-radius: 7px;
  font-size: 13px;
  font-weight: 500;
  display: inline-flex;
  align-items: center;
  gap: 6px;
  white-space: nowrap;
  cursor: pointer;
  transition: all 0.15s ease;
  border: none;
}

.search-btn {
  background: #212529;
  color: #FFFFFF;
}

.search-btn:hover:not(:disabled) {
  background: #000000;
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

.search-btn:active:not(:disabled) {
  transform: translateY(0);
}

.reset-btn {
  background: #FFFFFF;
  color: #495057;
  border: 1.5px solid #DEE2E6;
}

.reset-btn:hover:not(:disabled) {
  border-color: #ADB5BD;
  background: #F8F9FA;
  color: #212529;
}

.toolbar-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 20px;
  background: #FAFBFC;
}

.result-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.result-count {
  font-size: 13px;
  color: #6C757D;
}

.result-count strong {
  color: #212529;
  font-weight: 700;
  font-size: 15px;
}

.toolbar-actions {
  display: flex;
  align-items: center;
  gap: 4px;
}

.action-chip {
  display: inline-flex;
  align-items: center;
  gap: 5px;
  padding: 5px 12px;
  border: 1.5px solid transparent;
  border-radius: 6px;
  background: transparent;
  color: #868E96;
  font-size: 12px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.15s ease;
}

.action-chip:hover {
  background: #F1F3F5;
  color: #495057;
}

.action-chip.active {
  background: #FFFFFF;
  color: #212529;
  border-color: #DEE2E6;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.06);
}

/* 表格分页 */
.table-pagination {
  display: flex;
  justify-content: center;
  padding: 14px 0 6px;
  margin-top: 4px;
}

.table-pagination :deep(.ant-pagination) {
  display: flex;
  align-items: center;
  gap: 4px;
}

.table-pagination :deep(.ant-pagination-item) {
  border-radius: 5px;
  font-size: 13px;
  min-width: 30px;
  height: 30px;
  line-height: 30px;
  border: 1px solid #DEE2E6;
  transition: all 0.15s ease;
}

.table-pagination :deep(.ant-pagination-item:hover) {
  border-color: #ADB5BD;
}

.table-pagination :deep(.ant-pagination-item-active) {
  background: #212529;
  border-color: #212529;
}

.table-pagination :deep(.ant-pagination-item-active a) {
  color: #FFFFFF;
}

.table-pagination :deep(.ant-pagination-prev),
.table-pagination :deep(.ant-pagination-next) {
  min-width: 30px;
  height: 30px;
  line-height: 30px;
  border-radius: 5px;
  border: 1px solid #DEE2E6;
  transition: all 0.15s ease;
}

.table-pagination :deep(.ant-pagination-prev:hover),
.table-pagination :deep(.ant-pagination-next:hover) {
  border-color: #212529;
  color: #212529;
}

.table-pagination :deep(.ant-pagination-disabled) {
  opacity: 0.35;
}

.table-pagination :deep(.ant-pagination-options) {
  margin-left: 8px;
}

.table-pagination :deep(.ant-pagination-total-text) {
  font-size: 13px;
  color: #6C757D;
}

/* 基础按钮（用于表格操作和弹窗） */
.btn {
  border-radius: 6px;
  padding: 0 14px;
  height: 32px;
  font-size: 12px;
  font-weight: 500;
  transition: all 0.15s ease;
  border: none;
  cursor: pointer;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: 5px;
  box-sizing: border-box;
  white-space: nowrap;
}

.btn-primary {
  background: #212529;
  color: #FFFFFF;
}

.btn-primary:hover:not(:disabled) {
  background: #000000;
}

.btn-secondary {
  background: #FFFFFF;
  color: #495057;
  border: 1px solid #DEE2E6;
}

.btn-sm {
  height: 28px;
  padding: 0 10px;
  font-size: 11.5px;
  min-width: auto;
}

.btn-text {
  background: transparent;
  color: #1C7ED6;
  padding: 3px 8px;
  height: auto;
  box-shadow: none;
}

.btn-text:hover {
  background: #F8F9FA;
  color: #495057;
}

.btn-danger-text {
  background: transparent;
  color: #C92A2A;
  padding: 3px 8px;
  height: auto;
  box-shadow: none;
}

.btn-danger-text:hover {
  background: #FFF5F5;
}

.btn-approve-text {
  background: transparent;
  color: #2B8A3E;
  padding: 3px 8px;
  height: auto;
  box-shadow: none;
}

.btn-approve-text:hover {
  background: #EBFBEE;
  color: #1B7A2E;
}

.btn-approve-text:disabled {
  opacity: 0.45;
  cursor: not-allowed;
}

.btn-reject-text {
  background: transparent;
  color: #E67700;
  padding: 3px 8px;
  height: auto;
  box-shadow: none;
}

.btn-reject-text:hover {
  background: #FFF9DB;
  color: #C66700;
}

.btn-reject-text:disabled {
  opacity: 0.45;
  cursor: not-allowed;
}

.type-badge {
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
  background: #FFFFFF;
  color: #212529;
  border: 1px solid #DEE2E6;
  display: inline-block;
}

.difficulty-badge {
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
  display: inline-block;
}

.difficulty-badge.level-1 {
  background: #EBFBEE;
  color: #2B8A3E;
  border: 1px solid #D3F9D8;
}

.difficulty-badge.level-2 {
  background: #FFF9DB;
  color: #E67700;
  border: 1px solid #FFE066;
}

.difficulty-badge.level-3 {
  background: #FFF5F5;
  color: #C92A2A;
  border: 1px solid #FFD6D6;
}

.status-badge {
  padding: 2px 10px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
  display: inline-block;
}

.status-badge.pending {
  background: #FFF9DB;
  color: #E67700;
  border: 1px solid #FFE066;
}

.status-badge.approved {
  background: #EBFBEE;
  color: #2B8A3E;
  border: 1px solid #D3F9D8;
}

.status-badge.rejected {
  background: #FFF5F5;
  color: #C92A2A;
  border: 1px solid #FFD6D6;
}

/* 分页器增强样式 */
.question-bank-panel :deep(.ant-pagination) {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 4px;
  padding: 12px 0 4px;
  margin-top: 8px;
}

.question-bank-panel :deep(.ant-pagination-item) {
  border-radius: 5px;
  font-size: 13px;
  min-width: 30px;
  height: 30px;
  line-height: 30px;
  border: 1px solid #DEE2E6;
  transition: all 0.15s ease;
}

.question-bank-panel :deep(.ant-pagination-item:hover) {
  border-color: #ADB5BD;
}

.question-bank-panel :deep(.ant-pagination-item-active) {
  background: #212529;
  border-color: #212529;
}

.question-bank-panel :deep(.ant-pagination-item-active a) {
  color: #FFFFFF;
}

.question-bank-panel :deep(.ant-pagination-prev),
.question-bank-panel :deep(.ant-pagination-next) {
  min-width: 30px;
  height: 30px;
  line-height: 30px;
  border-radius: 5px;
  border: 1px solid #DEE2E6;
}

.question-bank-panel :deep(.ant-pagination-prev:hover),
.question-bank-panel :deep(.ant-pagination-next:hover) {
  border-color: #212529;
  color: #212529;
}

.question-bank-panel :deep(.ant-pagination-disabled) {
  opacity: 0.35;
}

.question-bank-panel :deep(.ant-pagination-options) {
  margin-left: 8px;
}

.question-bank-panel :deep(.ant-pagination-options .ant-select-selection) {
  border-radius: 5px;
  border-color: #DEE2E6;
}

.question-bank-panel :deep(.ant-pagination-total-text) {
  font-size: 13px;
  color: #6C757D;
  margin-right: 8px;
}

/* 模态弹窗 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.45);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 2000;
}

.modal-dialog {
  background: #FFFFFF;
  border-radius: 10px;
  width: 520px;
  max-width: 92vw;
  max-height: 80vh;
  display: flex;
  flex-direction: column;
  box-shadow: 0 12px 40px rgba(0, 0, 0, 0.15);
}

.modal-dialog.modal-lg {
  width: 620px;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #E9ECEF;
}

.modal-header h3 {
  margin: 0;
  font-size: 15px;
  font-weight: 600;
  color: #212529;
}

.close-btn {
  width: 28px;
  height: 28px;
  border: none;
  background: #F1F3F5;
  border-radius: 6px;
  font-size: 18px;
  cursor: pointer;
  color: #868E96;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.15s ease;
}

.close-btn:hover {
  background: #E9ECEF;
  color: #212529;
}

.modal-body {
  padding: 20px;
  overflow-y: auto;
  flex: 1;
}

.detail-row {
  margin-bottom: 12px;
  display: flex;
  align-items: flex-start;
  gap: 8px;
}

.detail-label {
  font-size: 13px;
  font-weight: 500;
  color: #6C757D;
  min-width: 60px;
  flex-shrink: 0;
}

.detail-value {
  font-size: 14px;
  color: #212529;
}

.detail-stem {
  margin: 0;
  font-size: 14px;
  line-height: 1.6;
  color: #212529;
  background: #F8F9FA;
  padding: 10px 12px;
  border-radius: 6px;
  border-left: 3px solid #212529;
}

.form-textarea {
  width: 100%;
  padding: 8px 12px;
  border: 1.5px solid #DEE2E6;
  border-radius: 6px;
  font-size: 13px;
  color: #212529;
  resize: vertical;
  line-height: 1.5;
  box-sizing: border-box;
  font-family: inherit;
}

.form-textarea:focus {
  outline: none;
  border-color: #212529;
  box-shadow: 0 0 0 3px rgba(0, 0, 0, 0.05);
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
  padding: 14px 20px;
  border-top: 1px solid #E9ECEF;
}

/* 查看弹窗 - 详细内容样式 */
.detail-meta-row {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 18px;
  padding-bottom: 14px;
  border-bottom: 1px solid #F1F3F5;
}

.detail-meta-id {
  font-size: 12px;
  color: #ADB5BD;
  margin-left: auto;
}

.section-label {
  display: block;
  font-size: 12px;
  font-weight: 600;
  color: #868E96;
  text-transform: uppercase;
  letter-spacing: 0.04em;
  margin-bottom: 8px;
}

.detail-section {
  margin-bottom: 16px;
}

.detail-stem {
  margin: 0;
  font-size: 14px;
  line-height: 1.7;
  color: #212529;
  background: #FAFBFC;
  padding: 12px 14px;
  border-radius: 7px;
  border-left: 3px solid #212529;
}

/* 选择题选项展示 */
.options-list-view {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.option-item-view {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 9px 12px;
  background: #FFFFFF;
  border: 1px solid #E9ECEF;
  border-radius: 7px;
  transition: all 0.15s ease;
}

.option-item-view.is-correct {
  background: #F0FDF4;
  border-color: #86EFAC;
  border-left: 3px solid #16A34A;
}

.option-key-view {
  width: 26px;
  height: 26px;
  background: #F1F3F5;
  border-radius: 6px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  font-weight: 700;
  color: #495057;
  flex-shrink: 0;
}

.option-item-view.is-correct .option-key-view {
  background: #16A34A;
  color: #FFFFFF;
}

.option-text-view {
  font-size: 13.5px;
  color: #343A40;
  line-height: 1.4;
  flex: 1;
}

.correct-tag {
  font-size: 11px;
  font-weight: 600;
  color: #2B8A3E;
  background: #D3F9D8;
  padding: 2px 10px;
  border-radius: 4px;
  white-space: nowrap;
  flex-shrink: 0;
}

/* 判断题答案展示 */
.tf-answer-display {
  display: flex;
  gap: 10px;
}

.tf-option-box {
  flex: 1;
  padding: 11px 16px;
  border: 1.5px solid #DEE2E6;
  border-radius: 8px;
  font-size: 13.5px;
  font-weight: 500;
  color: #495057;
  cursor: default;
  text-align: center;
  transition: all 0.15s ease;
  user-select: none;
}

.tf-option-box.active {
  background: #2B8A3E;
  border-color: #2B8A3E;
  color: #FFFFFF;
}

/* Edit mode: make TF boxes look clickable */
button.tf-option-box {
  cursor: pointer;
  background: #FFFFFF;
  border: 1.5px solid #DEE2E6;
  outline: none;
  font-family: inherit;
}
button.tf-option-box:hover:not(.active) {
  border-color: #86EFAC;
  color: #16A34A;
  background: #F0FDF4;
}
button.tf-option-box:active:not(.active) {
  transform: scale(0.98);
}

/* 填空题查看 - 空白答案标签样式 */
.fb-answer-view {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  align-items: center;
}

.fb-no-answer {
  font-size: 13px;
  color: #ADB5BD;
  font-style: italic;
}

.blank-tag {
  display: inline-flex;
  align-items: center;
  background: #FFFFFF;
  border: 1.5px solid #DEE2E6;
  border-radius: 8px;
  overflow: hidden;
}

.blank-index {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 28px;
  height: 32px;
  background: #F1F3F5;
  color: #495057;
  font-size: 11px;
  font-weight: 700;
  border-right: 1px solid #DEE2E6;
  flex-shrink: 0;
}

.blank-text {
  padding: 6px 12px;
  font-size: 13px;
  color: #212529;
  line-height: 1.4;
}

/* 填空题编辑 - 空白预览 */
.blank-preview {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 6px;
  margin-top: 10px;
  padding: 10px 12px;
  background: #F8F9FA;
  border: 1px solid #E9ECEF;
  border-radius: 7px;
  font-size: 12px;
}

.preview-label {
  color: #868E96;
  font-weight: 500;
}

.preview-chip {
  display: inline-block;
  padding: 2px 10px;
  background: #E7F5FF;
  color: #1C7ED6;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
  border: 1px solid #D0EBFF;
}

.fb-answer-display {
  padding: 12px 14px;
  background: #F8F9FA;
  border: 1px dashed #CED4DA;
  border-radius: 7px;
  font-size: 13.5px;
  line-height: 1.6;
  color: #495057;
  min-height: 40px;
}

.detail-footer-info {
  margin-top: 16px;
  padding-top: 12px;
  border-top: 1px solid #F1F3F5;
  font-size: 12px;
  color: #ADB5BD;
}

/* 编辑弹窗 - 选项编辑 */
.options-edit-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.option-edit-row {
  display: flex;
  align-items: center;
  gap: 8px;
}

.option-key-edit {
  width: 28px;
  height: 28px;
  background: #212529;
  color: #FFFFFF;
  border-radius: 6px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  font-weight: 700;
  flex-shrink: 0;
}

.option-input-edit {
  flex: 1;
  height: 36px;
  padding: 0 12px;
  border: 1.5px solid #DEE2E6;
  border-radius: 6px;
  font-size: 13px;
  color: #212529;
  outline: none;
  box-sizing: border-box;
  transition: border-color 0.15s ease;
}

.option-input-edit:focus {
  border-color: #212529;
  box-shadow: 0 0 0 3px rgba(33, 37, 41, 0.06);
}

.correct-toggle {
  height: 36px;
  padding: 0 14px;
  border: 1.5px solid #DEE2E6;
  border-radius: 6px;
  font-size: 12px;
  font-weight: 500;
  cursor: pointer;
  white-space: nowrap;
  transition: all 0.15s ease;
  background: #FFFFFF;
  color: #868E96;
  flex-shrink: 0;
  position: relative;
}

.correct-toggle:hover:not(.active) {
  border-color: #86EFAC;
  color: #16A34A;
}

.correct-toggle.active {
  background: #16A34A !important;
  border-color: #16A34A !important;
  color: #FFFFFF !important;
  font-weight: 600;
  box-shadow: 0 2px 8px rgba(22, 163, 74, 0.25);
}

.edit-hint {
  margin: 8px 0 0;
  font-size: 12px;
  color: #ADB5BD;
}
.edit-hint code {
  background: #F1F3F5;
  padding: 1px 6px;
  border-radius: 4px;
  font-size: 11px;
  color: #495057;
  border: 1px solid #DEE2E6;
}

/* 弹窗加载状态 */
.modal-loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 14px;
  padding: 48px 20px;
  min-height: 200px;
  color: #6C757D;
  font-size: 14px;
}

.loading-spinner {
  width: 32px;
  height: 32px;
  border: 3px solid #E9ECEF;
  border-top-color: #212529;
  border-radius: 50%;
  animation: spin 0.7s linear infinite;
}

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

.no-answer-hint {
  margin: 10px 0 0;
  padding: 8px 12px;
  background: #FFF8E1;
  border-left: 3px solid #F59E0B;
  border-radius: 6px;
  font-size: 12.5px;
  color: #92400E;
}
</style>
