<script setup lang="ts">
import { computed, reactive, ref } from 'vue'
import { useRoute } from 'vue-router'
import { NTag, NButton, NSkeleton, NTabs, NTabPane, NSpace, NAlert, NInput, NDropdown, NIcon, NModal, NCard, NEmpty } from 'naive-ui'
import Table1Viewer from '../../components/literature/Table1Viewer.vue'
import { useLiteratureDetail } from '../../composables/useLiteratureDetail'
import { useLiteratureNotes } from '../../composables/useLiteratureNotes'
import { usePersonalTags } from '../../composables/usePersonalTags'
import { useAiSummary } from '../../composables/useAiSummary'
import { useHighlights } from '../../composables/useHighlights'
import { toBeijingDate } from '../../utils/date'
import NoteEditModal from '../../components/notes/NoteEditModal.vue'
import { api } from '../../api/client'
import { useToast } from '../../composables/useToast'
import { AddOutline, BookmarkOutline, CloseOutline, DownloadOutline, KeyOutline, PeopleOutline, SaveOutline } from '@vicons/ionicons5'

const toast = useToast()

const route = useRoute()
const pmid = computed(() => {
  const raw = route.params.pmid
  const n = Number(raw)
  return Number.isNaN(n) || !/^\d+$/.test(String(raw)) ? 0 : n
})

const { lit, loading, saving, saved, rating, readingStatus,
  studyTypes, tables, field_labels, isUpdated,
  notes, personalTags, relatedItems, relatedSource, relatedLoading,
  formatDate, goBack, copyPmid, copyDoi, openPubMed, openDOI,
  exportFormats, handleExport, copyCitation,
  handleSave, handleRate, updateReadingStatus,
  READING_STATUS_OPTIONS,
} = useLiteratureDetail(pmid.value)

const { noteContent, noteSaving, handleAddNote, handleDeleteNote, showEditModal, editingContent, editIsPrivate, editSaving, handleOpenEdit, handleSaveEdit } = useLiteratureNotes(pmid.value, notes)

// ── 搜索关键词高亮 ──
const searchQuery = computed(() => (route.query.q as string) || '')

function highlightText(text: string): string {
  const q = searchQuery.value
  if (!q || !text) return text || ''
  const escaped = q.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
  const terms = escaped.split(/\s+/).filter(Boolean)
  let result = text
  for (const term of terms) {
    result = result.replace(new RegExp(`(${term})`, 'gi'), '<mark class="search-highlight">$1</mark>')
  }
  return result
}

const noteExpandMap = reactive<Record<string, boolean>>({})
function toggleNoteExpand(id: string) {
  noteExpandMap[id] = !noteExpandMap[id]
}
const { newTag, handleAddTag, handleRemoveTag } = usePersonalTags(pmid.value, personalTags)
const { aiLoading, aiSummary, aiMode, generateAI } = useAiSummary(pmid.value)
const { highlights, hlsLoading, showHlForm, hlText, hlNote, hlType, hlColor,
        hlToolbarVisible, hlToolbarPos, handleCreateHighlight, handleDeleteHighlight,
        onAbstractMouseup, useSelectedText } = useHighlights(pmid.value)

// ── 分享到科室 ──
const showShareModal = ref(false)
const sharedFolders = ref<any[]>([])
const shareLoading = ref(false)
async function openShareModal() {
  showShareModal.value = true
  if (sharedFolders.value.length) return
  shareLoading.value = true
  try {
    const { data } = await api.get('/teams/shared-folders')
    sharedFolders.value = data.folders || []
  } catch (e) { /* 静默 */ }
  finally { shareLoading.value = false }
}
async function shareToFolder(folderId: string) {
  shareLoading.value = true
  try {
    await api.post(`/literature/${pmid.value}/save`, { folder_id: folderId })
    if (!saved.value) saved.value = true
    showShareModal.value = false
    toast.success('已分享到科室收藏夹')
  } catch (e) { toast.apiError(e, '分享失败') }
  finally { shareLoading.value = false }
}
</script>

<template>
  <div class="detail" style="max-width:1400px;margin:0 auto;padding:24px">
    <NSkeleton v-if="loading" text :repeat="8" />
    <NEmpty v-else-if="!pmid" style="padding:48px 0" description="无效的文献 ID" />
    <template v-else-if="lit">
      <!-- 返回按钮 -->
      <div class="back-bar">
        <span class="back-btn" @click="goBack">← 返回</span>
      </div>

      <!-- 更新提示 -->
      <div v-if="isUpdated" class="update-notice">🔄 该文献内容已于 {{ formatDate(lit.updated_at) }} 更新</div>

      <!-- 撤稿警示 -->
      <NAlert v-if="lit.retracted" type="error" :bordered="true" closable style="margin:12px 0">
        <template #header>
          <strong>⚠ 本文献已被撤稿</strong>
        </template>
        <div v-if="lit.retraction_details">
          撤稿来源：{{ lit.retraction_details?.ref_source || '未知' }}
          <span v-if="lit.retraction_details?.ref_pmid">
            · PMID: {{ lit.retraction_details?.ref_pmid }}
          </span>
        </div>
      </NAlert>

      <!-- 阴性结果提示 -->
      <NAlert v-if="lit.is_negative_result && !lit.retracted" type="warning" :bordered="true" closable style="margin:12px 0">
        <template #header>
          <strong>📊 本研究报告阴性结果</strong>
        </template>
        <div>研究未发现干预措施在主要终点上具有统计学显著差异</div>
      </NAlert>

      <!-- 标题 -->
      <h2>{{ lit.title }}</h2>

      <!-- 研究类型徽章 -->
      <div v-if="studyTypes.length" class="detail-type-row">
        <NTag v-for="st in studyTypes" :type="st.type" size="tiny" :bordered="false">{{ st.label }}</NTag>
      </div>

      <!-- 元信息 -->
      <p class="meta">
        {{ lit.authors?.map((a:any)=>a.family).slice(0,4).join(', ') }}
        <span v-if="(lit.authors||[]).length > 4">et al.</span>
        | <strong>{{ lit.journal }}</strong>
        <span v-if="lit.pub_date"> | {{ (lit.article_date || lit.pub_date).slice(0,10) }}</span>
        <span v-if="lit.pub_year"> ({{ lit.pub_year }})</span>
        <span v-if="lit.volume">; {{ lit.volume }}{{ lit.issue ? `(${lit.issue})` : '' }}{{ lit.pages ? `:${lit.pages}` : '' }}</span>
      </p>

      <!-- PMID / DOI / PMC / OA / 引用 -->
      <div class="detail-ids">
        <template v-if="lit.pmid">
          <span class="id-label">PMID:</span>
          <span class="id-value">{{ lit.pmid }}</span>
          <span class="copy-btn" @click="copyPmid" title="复制 PMID">📋</span>
        </template>
        <template v-if="lit.doi">
          <span class="id-sep">|</span>
          <span class="id-label">DOI:</span>
          <span class="id-value">{{ lit.doi }}</span>
          <span class="copy-btn" @click="copyDoi" title="复制 DOI">📋</span>
        </template>
        <template v-if="lit.pmc_id">
          <span class="id-sep">|</span>
          <span class="id-label">PMCID:</span>
          <span class="id-value">{{ lit.pmc_id }}</span>
          <NTag v-if="lit.is_oa" type="success" size="tiny" :bordered="false">🔓 免费全文</NTag>
          <NTag v-if="lit.license_info?.type" size="tiny" :bordered="false" style="margin-left:4px">
            📄 {{ lit.license_info?.type }}
          </NTag>
        </template>
        <template v-if="lit.cited_by_count">
          <span class="id-sep">|</span>
          <span class="cited-count">📊 被引 {{ lit.cited_by_count }} 次</span>
        </template>
      </div>

      <!-- 标签 -->
      <div class="tags" style="margin:12px 0">
        <NTag v-for="tag in lit.tags" :key="tag.id" size="small" :bordered="false" :type="tag.is_major ? 'success' : 'info'">
          {{ tag.name_zh || tag.name_en }}
          <template v-if="tag.is_major"> ★</template>
        </NTag>
      </div>

      <!-- 关键词 -->
      <div v-if="lit.keywords?.length" class="detail-section">
        <div class="section-title">关键词</div>
        <div class="kw-row">
          <span v-for="kw in lit.keywords" :key="kw" class="kw-pill">{{ kw }}</span>
        </div>
      </div>

      <!-- 研究设计分类 -->
      <div v-if="lit.study_design" class="detail-section">
        <div class="section-title">研究设计</div>
        <div style="display:flex;gap:6px;align-items:center;flex-wrap:wrap">
          <NTag size="small" type="info" :bordered="false">{{ lit.study_design?.label_zh || '' }}</NTag>
          <span v-if="lit.study_design?.primary" style="font-size:12px;color:var(--text-secondary)">
            {{ lit.study_design?.primary }} / {{ lit.study_design?.sub }}
          </span>
        </div>
      </div>

      <!-- 临床试验注册 -->
      <div v-if="lit.trial_reg" class="detail-section">
        <div class="section-title">临床试验注册</div>
        <div style="font-size:13px;display:flex;gap:12px;flex-wrap:wrap">
          <a v-if="lit.trial_reg?.nct" :href="'https://clinicaltrials.gov/study/' + lit.trial_reg?.nct" target="_blank" rel="noopener" style="color:#c0392b">
            🔗 {{ lit.trial_reg?.nct }}
          </a>
          <span v-if="lit.trial_reg?.eudract" style="color:var(--text-secondary)">EU-CTR: {{ lit.trial_reg?.eudract }}</span>
          <span v-if="lit.trial_reg?.chictr" style="color:var(--text-secondary)">ChiCTR: {{ lit.trial_reg?.chictr }}</span>
        </div>
      </div>

      <!-- PICO -->
      <div v-if="lit.pico" class="detail-section">
        <div class="section-title">PICO 要素</div>
        <div class="pico-grid">
          <div v-if="lit.pico?.population" class="pico-item">
            <span class="pico-key">Population</span>
            <span class="pico-val">{{ lit.pico?.population }}</span>
          </div>
          <div v-if="lit.pico?.intervention" class="pico-item">
            <span class="pico-key">Intervention</span>
            <span class="pico-val">{{ lit.pico?.intervention }}</span>
          </div>
          <div v-if="lit.pico?.comparator" class="pico-item">
            <span class="pico-key">Comparator</span>
            <span class="pico-val">{{ lit.pico?.comparator }}</span>
          </div>
          <div v-if="lit.pico?.outcome" class="pico-item">
            <span class="pico-key">Outcome</span>
            <span class="pico-val">{{ lit.pico?.outcome }}</span>
          </div>
          <div v-if="lit.pico?.sample_size" class="pico-item">
            <span class="pico-key">样本量</span>
            <span class="pico-val">{{ lit.pico?.sample_size }}</span>
          </div>
          <div v-if="lit.pico?.effect_size" class="pico-item">
            <span class="pico-key">效应量</span>
            <span class="pico-val">{{ JSON.stringify(lit.pico?.effect_size) }}</span>
          </div>
        </div>
      </div>

      <!-- 基线特征预提取 -->
      <div v-if="lit.pre_extracted_data?.extracted_fields" class="detail-section">
        <div class="section-title">📋 {{ lit.pre_extracted_data?.table1_caption || '基线特征' }}</div>
        <div v-if="lit.pre_extracted_data?.arms?.length" style="font-size:12px;color:var(--text-secondary);margin-bottom:6px">
          研究组：{{ lit.pre_extracted_data?.arms?.join(' / ') }}
        </div>
        <div class="baseline-grid">
          <div v-for="(vals, field) in lit.pre_extracted_data?.extracted_fields" :key="field" class="baseline-item">
            <span class="baseline-key">{{ field_labels[field as string] || field }}</span>
            <div class="baseline-vals">
              <span v-for="(v, arm) in vals" :key="arm" class="baseline-val">
                <span class="baseline-arm">{{ arm }}:</span> {{ v }}
              </span>
            </div>
          </div>
        </div>
      </div>

      <!-- 基金 -->
      <div v-if="lit.grants?.length" class="detail-section">
        <div class="section-title">基金资助</div>
        <div v-for="(g, i) in lit.grants" :key="i" class="grant-row">
          <span v-if="g.agency">{{ g.agency }}</span>
          <span v-if="g.grant_id"> ({{ g.grant_id }})</span>
        </div>
      </div>

      <!-- 化合物列表（ChemicalList） -->
      <div v-if="lit.chemical_list?.length" class="detail-section">
        <div class="section-title">🧪 化合物</div>
        <div style="display:flex;flex-wrap:wrap;gap:6px">
          <div v-for="(ch, i) in lit.chemical_list" :key="i"
               style="background:var(--bg-card);padding:4px 10px;border-radius:6px;font-size:12px;border:1px solid var(--border-color)">
            <strong>{{ ch.name }}</strong>
            <span v-if="ch.registry_number" style="color:var(--text-muted);margin-left:4px">CAS {{ ch.registry_number }}</span>
            <span v-if="ch.mesh_ui" style="color:var(--text-muted);margin-left:4px;font-size:11px">({{ ch.mesh_ui }})</span>
          </div>
        </div>
      </div>

      <!-- 基因符号（GeneSymbolList） -->
      <div v-if="lit.gene_symbols?.length" class="detail-section">
        <div class="section-title">🧬 基因</div>
        <div style="display:flex;flex-wrap:wrap;gap:6px">
          <span v-for="gs in lit.gene_symbols" :key="gs"
                style="background:var(--bg-card);padding:2px 10px;border-radius:10px;font-size:12px;font-weight:600;border:1px solid var(--border-color)">
            {{ gs }}
          </span>
        </div>
      </div>

      <!-- 引用数 + 出版状态 + 电子出版日期 -->
      <div v-if="lit.num_refs != null || lit.publication_status || lit.article_date" class="detail-section">
        <div class="section-title">文献元数据</div>
        <div style="display:flex;gap:16px;flex-wrap:wrap;font-size:12px;color:var(--text-secondary)">
          <span v-if="lit.num_refs != null">📚 参考文献数：{{ lit.num_refs }}</span>
          <span v-if="lit.publication_status">
            📄 出版状态：{{ {epublish:'电子出版', ppublish:'印刷出版', aheadofprint:'提前在线'}[lit.publication_status] || lit.publication_status }}
          </span>
          <span v-if="lit.article_date">📅 电子出版：{{ lit.article_date?.slice(0,10) }}</span>
        </div>
      </div>

      <!-- 数据库引用（DataBankList） -->
      <div v-if="lit.databank_list?.length" class="detail-section">
        <div class="section-title">🗄️ 数据库引用</div>
        <div v-for="(db, i) in lit.databank_list" :key="i" style="margin-bottom:4px;font-size:12px;color:var(--text-secondary)">
          <span style="font-weight:600">{{ db.databank_name }}:</span>
          <span v-for="(acc, j) in db.accession_numbers" :key="j" style="margin-left:4px">
            <span v-if="db.databank_name === 'GEO'">
              <a :href="'https://www.ncbi.nlm.nih.gov/geo/query/acc.cgi?acc=' + acc" target="_blank" rel="noopener" style="color:var(--primary-color)">{{ acc }}</a>
            </span>
            <span v-else-if="db.databank_name === 'SRA'">
              <a :href="'https://www.ncbi.nlm.nih.gov/sra/' + acc" target="_blank" rel="noopener" style="color:var(--primary-color)">{{ acc }}</a>
            </span>
            <span v-else-if="db.databank_name === 'GenBank'">
              <a :href="'https://www.ncbi.nlm.nih.gov/nuccore/' + acc" target="_blank" rel="noopener" style="color:var(--primary-color)">{{ acc }}</a>
            </span>
            <span v-else>{{ acc }}</span>
            <span v-if="j < (db.accession_numbers?.length || 0) - 1">, </span>
          </span>
        </div>
      </div>

      <!-- 补充 MeSH（SupplMeshList） -->
      <div v-if="lit.suppl_mesh_list?.length" class="detail-section">
        <div class="section-title">🏷️ 补充 MeSH</div>
        <div style="display:flex;flex-wrap:wrap;gap:6px">
          <span v-for="(sm, i) in lit.suppl_mesh_list" :key="i"
                style="background:var(--bg-card);padding:2px 10px;border-radius:10px;font-size:12px;border:1px solid var(--border-color)">
            {{ sm.descriptor }}
            <span v-if="sm.type" style="color:var(--text-muted);margin-left:4px;font-size:11px">({{ {Disease:'疾病', Organism:'生物', Pharmacological:'药理'}[sm.type] || sm.type }})</span>
          </span>
        </div>
      </div>

      <!-- Tab: 摘要 / 笔记 / 标注 / AI -->
      <NTabs type="line" default-value="abstract" style="margin-top:12px">
        <NTabPane name="abstract" tab="📋 摘要">
          <div class="abstract-text" @mouseup="onAbstractMouseup" v-html="highlightText(lit.abstract || '（摘要不可用）')"></div>
        </NTabPane>
        <NTabPane name="notes" tab="💬 笔记">
          <div class="notes-section" style="margin-top:8px">
            <NInput v-model:value="noteContent" type="textarea" placeholder="写阅读笔记..."
                    :autosize="{ minRows: 3, maxRows: 6 }" />
            <NButton size="small" type="primary" :loading="noteSaving"
                     :disabled="!noteContent.trim()" @click="handleAddNote" style="margin-top:8px" class="sky-btn">
              <template #icon><NIcon size="14"><SaveOutline /></NIcon></template>保存笔记
            </NButton>
            <div v-for="n in notes" :key="n.id" class="note-item">
              <div v-if="n.author_name" class="note-author">{{ n.author_name }}</div>
              <div v-if="noteExpandMap[n.id]" key="exp" class="note-content">{{ n.content }}</div>
              <div v-else key="col" class="note-content clamp-3">{{ n.content }}</div>
              <div v-if="n.content && n.content.length > 60" class="expand-toggle" @click="toggleNoteExpand(n.id)">
                {{ noteExpandMap[n.id] ? '收起' : '展开全部' }}
              </div>
              <div style="display:flex;justify-content:space-between;align-items:center;margin-top:6px">
                <span style="font-size:11px;color:var(--text-muted)">
                  {{ formatDate(n.created_at) }}
                  <span v-if="n.updated_at && n.updated_at !== n.created_at"> · 编辑于 {{ formatDate(n.updated_at) }}</span>
                </span>
                <div style="display:flex;gap:8px">
                  <NButton size="tiny" text @click="handleOpenEdit(n)">编辑</NButton>
                  <NButton size="tiny" text type="error" @click="handleDeleteNote(n.id)">删除</NButton>
                </div>
              </div>
            </div>

            <!-- Edit modal -->
            <!-- Edit modal -->
            <NoteEditModal
              :show="showEditModal"
              :content="editingContent"
              :is-private="editIsPrivate"
              :saving="editSaving"
              @update:show="(v: boolean) => showEditModal = v"
              @update:content="(v: string) => editingContent = v"
              @update:is-private="(v: boolean) => editIsPrivate = v"
              @save="handleSaveEdit"
            />
          </div>
        </NTabPane>
        <NTabPane name="highlights" tab="🖍️ 标注">
          <div class="highlights-section">
            <!-- 浮动工具栏 -->
            <div v-if="hlToolbarVisible" class="hl-toolbar" :style="{ left: hlToolbarPos.x + 'px', top: (hlToolbarPos.y - 40) + 'px' }">
              <button class="hl-tb-btn" title="高亮" @click="hlType='highlight';useSelectedText()">🖍️</button>
              <button class="hl-tb-btn" title="下划线" @click="hlType='underline';useSelectedText()">➖</button>
              <button class="hl-tb-btn" title="删除线" @click="hlType='strikethrough';useSelectedText()">~~</button>
              <button class="hl-tb-btn" title="注释" @click="hlType='free_text';useSelectedText()">💬</button>
            </div>
            <!-- 新建标注表单 -->
            <div v-if="showHlForm" class="hl-form" style="margin-bottom:16px">
              <div style="font-size:13px;font-weight:600;margin-bottom:8px">新建标注</div>
              <div class="hl-field">
                <label>摘录文字</label>
                <textarea v-model="hlText" class="hl-input" rows="2" placeholder="选中文献中的文字，或手动输入..." />
              </div>
              <div class="hl-field">
                <label>标注类型</label>
                <select v-model="hlType" class="hl-select">
                  <option value="highlight">高亮</option>
                  <option value="underline">下划线</option>
                  <option value="strikethrough">删除线</option>
                  <option value="free_text">自由注释</option>
                </select>
              </div>
              <div class="hl-field">
                <label>颜色</label>
                <div style="display:flex;gap:6px;align-items:center">
                  <input v-model="hlColor" type="color" style="width:36px;height:28px;padding:0;border:none;cursor:pointer" />
                  <span style="font-size:11px;color:var(--text-muted)">{{ hlColor }}</span>
                </div>
              </div>
              <div class="hl-field">
                <label>备注</label>
                <input v-model="hlNote" class="hl-input" placeholder="可选备注..." />
              </div>
              <div style="display:flex;gap:8px;margin-top:8px">
                <NButton size="small" type="primary" @click="handleCreateHighlight" class="sky-btn"><template #icon><NIcon size="14"><SaveOutline /></NIcon></template>保存标注</NButton>
                <NButton size="small" @click="showHlForm=false;hlToolbarVisible=false" class="sky-btn"><template #icon><NIcon size="14"><CloseOutline /></NIcon></template>取消</NButton>
              </div>
            </div>
            <!-- 已有标注列表 -->
            <div v-if="hlsLoading" style="padding:16px;text-align:center;color:var(--text-muted)">加载中...</div>
            <div v-else-if="!highlights.length" style="color:var(--text-muted);font-size:13px;text-align:center;padding:24px">
              暂无标注。选中摘要中的文字可添加标注，或点击下方按钮手动创建。
              <div style="margin-top:12px">
                <NButton size="small" @click="showHlForm=true" class="sky-btn"><template #icon><NIcon size="14"><AddOutline /></NIcon></template>✚ 新建标注</NButton>
              </div>
            </div>
            <div v-else>
              <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:12px">
                <span style="font-size:13px;color:var(--text-secondary)">共 {{ highlights.length }} 条标注</span>
                <NButton size="tiny" @click="showHlForm=true" class="sky-btn">✚ 新建</NButton>
              </div>
              <div v-for="h in highlights" :key="h.id" class="hl-item">
                <div class="hl-item-header">
                  <span class="hl-type-badge" :class="h.type">{{ {highlight:'高亮', underline:'下划线', strikethrough:'删除线', free_text:'注释'}[h.type] || h.type }}</span>
                  <span class="hl-color-dot" :style="{ background: h.color }" />
                  <span style="font-size:11px;color:var(--text-muted);margin-left:auto">{{ toBeijingDate(h.created_at) }}</span>
                </div>
                <div v-if="h.text" class="hl-text">{{ h.text }}</div>
                <div v-if="h.note" class="hl-note">📝 {{ h.note }}</div>
                <NButton size="tiny" text type="error" @click="handleDeleteHighlight(h.id)" style="margin-top:6px">删除</NButton>
              </div>
            </div>
          </div>
        </NTabPane>
        <NTabPane name="tables" tab="📊 表格">
          <Table1Viewer :tables="tables" />
        </NTabPane>
        <NTabPane name="ai" tab="🤖 AI 解读">
          <div style="margin-top:8px">
            <n-space style="margin-bottom:12px">
              <n-button size="small" class="sky-btn" :type="aiMode==='one_liner'?'primary':'default'" :loading="aiLoading && aiMode==='one_liner'" @click="generateAI('one_liner')"><template #icon><NIcon size="14"><KeyOutline /></NIcon></template>一句话总结</n-button>
              <n-button size="small" class="sky-btn" :type="aiMode==='structured'?'primary':'default'" :loading="aiLoading && aiMode==='structured'" @click="generateAI('structured')"><template #icon><NIcon size="14"><KeyOutline /></NIcon></template>结构化摘要</n-button>
              <n-button size="small" class="sky-btn" :type="aiMode==='implication'?'primary':'default'" :loading="aiLoading && aiMode==='implication'" @click="generateAI('implication')"><template #icon><NIcon size="14"><KeyOutline /></NIcon></template>临床意义</n-button>
            </n-space>
            <n-alert v-if="aiLoading" type="info" title="AI 正在生成..." />
            <div v-else-if="aiSummary" class="ai-summary-box">
              {{ aiSummary }}
            </div>
            <div v-else style="color:var(--text-muted);font-size:13px;text-align:center;padding:24px">
              点击上方按钮，AI 将自动生成中文解读<br/>
              <span style="font-size:11px">（需要 Pro 及以上方案）</span>
            </div>
          </div>
        </NTabPane>
      </NTabs>

      <!-- 操作栏 -->
      <div style="margin-top:20px;display:flex;gap:8px;flex-wrap:wrap;align-items:center">
        <NButton type="primary" :loading="saving" @click="handleSave" class="sky-btn"><template #icon><NIcon size="14"><BookmarkOutline /></NIcon></template>
          {{ saved ? '⭐ 已收藏' : '☆ 收藏' }}
        </NButton>
        <!-- 阅读状态 -->
        <div v-if="saved" style="display:inline-flex;align-items:center;gap:4px;font-size:13px">
          <span style="color:var(--text-muted)">阅读：</span>
          <span v-for="opt in READING_STATUS_OPTIONS" :key="opt.value"
                style="cursor:pointer;padding:2px 8px;border-radius:4px;font-size:12px;transition:all .15s"
                :style="{
                  background: readingStatus === opt.value ? opt.color : 'transparent',
                  color: readingStatus === opt.value ? '#fff' : 'var(--text-secondary)',
                  border: readingStatus === opt.value ? 'none' : '1px solid var(--border-color)',
                }"
                @click="updateReadingStatus(opt.value)">{{ opt.label }}</span>
        </div>
        <NButton @click="openPubMed(lit.pmid)" class="sky-btn">🔗 PubMed原文</NButton>
        <NButton v-if="lit.doi" @click="openDOI(lit.doi)" class="sky-btn">📄 DOI全文</NButton>
        <span style="margin-left:16px;font-size:13px;color:var(--text-secondary)">评分：</span>
        <span v-for="s in 5" :key="s" style="cursor:pointer;font-size:20px;margin:0 1px"
              @click="handleRate(s)">{{ s <= rating ? '⭐' : '☆' }}</span>
        <NButton size="small" @click="copyCitation" class="sky-btn">📋 复制引用</NButton>
        <NDropdown :options="exportFormats" @select="handleExport" style="margin-left:8px">
          <NButton size="small" class="sky-btn"><template #icon><NIcon size="14"><DownloadOutline /></NIcon></template>导出引用 ▼</NButton>
        </NDropdown>
        <NButton size="small" class="sky-btn" @click="openShareModal"><template #icon><NIcon size="14"><PeopleOutline /></NIcon></template>分享到科室</NButton>
      </div>

      <!-- 个人标签 -->
      <div style="margin-top:12px;display:flex;align-items:center;gap:6px;flex-wrap:wrap">
        <span style="font-size:12px;color:var(--text-muted)">🏷️ 个人标签：</span>
        <NTag v-for="t in personalTags" :key="t.name" size="tiny" closable @close="handleRemoveTag(t.name)">
          {{ t.name }}
        </NTag>
        <NInput v-model:value="newTag" size="tiny" placeholder="添加标签..." style="width:100px"
               @keyup.enter="handleAddTag" />
        <NButton size="tiny" @click="handleAddTag" class="sky-btn"><template #icon><NIcon size="14"><AddOutline /></NIcon></template></NButton>
      </div>

      <!-- 相关文献推荐 -->
      <div v-if="!loading && (relatedItems.length || !relatedLoading)" class="detail-section" style="margin-top:24px">
        <div class="section-title" style="font-size:15px">
          📎 相关文献推荐
          <span v-if="relatedSource === 'tags'" style="font-size:11px;color:var(--text-muted);font-weight:400;margin-left:6px">基于共同标签</span>
          <span v-else-if="relatedSource === 'journal'" style="font-size:11px;color:var(--text-muted);font-weight:400;margin-left:6px">基于同期刊</span>
        </div>
        <NSkeleton v-if="relatedLoading" text :repeat="3" />
        <div v-else-if="!relatedItems.length" style="font-size:13px;color:var(--text-muted);padding:8px 0">暂无相关文献推荐</div>
        <div v-else style="display:flex;flex-direction:column;gap:6px;margin-top:8px">
          <div
            v-for="(item, idx) in relatedItems.slice(0, 5)"
            :key="item.pmid"
            class="related-item"
          >
            <span style="font-size:11px;color:var(--text-muted);font-weight:700;min-width:18px;text-align:center;margin-top:2px">{{ idx + 1 }}</span>
            <div style="flex:1;min-width:0">
              <a
                :href="`/literature/${item.pmid}`" target="_blank"
                style="font-size:13px;font-weight:600;color:#1a5276;text-decoration:none;line-height:1.4"
              >{{ item.title }}</a>
              <div style="font-size:11px;color:var(--text-secondary);margin-top:3px">
                <span>{{ item.first_author }} · </span>
                <span>{{ item.journal }}</span>
                <span v-if="item.pub_date"> · {{ (item.article_date || item.pub_date)?.slice(0, 10) }}</span>
              </div>
              <div style="display:flex;gap:8px;font-size:11px;color:var(--text-muted);margin-top:3px;flex-wrap:wrap">
                <span>📄 PMID: {{ item.pmid }}</span>
                <span v-if="item.cited_by_count">📊 {{ item.cited_by_count }} 次引用</span>
                <span v-if="item.overlap_tags" style="color:#1a5276">🏷️ 共用 {{ item.overlap_tags }} 个标签</span>
                <span style="color:#e67e22">⭐ 相关度 {{ item.relevance_score }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    <!-- 分享到科室 Modal -->
    <NModal v-model:show="showShareModal" title="分享到科室收藏夹" preset="card" style="width:420px">
      <NSkeleton v-if="shareLoading && !sharedFolders.length" text :repeat="4" />
      <NEmpty v-else-if="!sharedFolders.length" description="暂无共享收藏夹，请先在科室团队创建" style="padding:24px 0" />
      <div v-else class="share-folder-list">
        <NCard v-for="f in sharedFolders" :key="f.id" size="small"
                class="share-folder-item"
                :style="`border-left:4px solid ${f.color};cursor:pointer;margin-bottom:6px`"
                @click="shareToFolder(f.id)">
          <div style="display:flex;justify-content:space-between;align-items:center">
            <div>
              <div style="font-weight:600;font-size:14px">{{ f.name }}</div>
              <div v-if="f.article_count != null" style="font-size:12px;color:var(--text-muted)">{{ f.article_count }} 篇文献</div>
            </div>
            <NButton size="tiny" class="sky-btn">分享</NButton>
          </div>
        </NCard>
      </div>
    </NModal>
    </template>
  </div>
</template>

<style scoped>
.back-bar { margin-bottom: 4px; }
.back-btn { font-size: 13px; color: #1a5276; cursor: pointer; user-select: none; }
.back-btn:hover { text-decoration: underline; }
.detail h2 { font-size:22px; font-weight:700; line-height:1.4; }
.detail-type-row { display: flex; gap: 4px; flex-wrap: wrap; margin-bottom: 8px; }
.meta { font-size:13px; color:var(--text-secondary); margin:12px 0; line-height:1.6; }
.detail-ids { font-size: 13px; color: var(--text-secondary); margin-bottom: 8px; display: flex; align-items: center; flex-wrap: wrap; gap: 4px; }
.id-label { color: var(--text-muted); }
.id-value { color: var(--text-secondary); }
.copy-btn { cursor: pointer; font-size: 12px; }
.copy-btn:hover { opacity: .7; }
.id-sep { color: var(--border-color); margin: 0 2px; }
.cited-count { color: var(--text-muted); }
.tags { display:flex; gap:6px; flex-wrap:wrap; }
.detail-section { margin: 14px 0; }
.section-title { font-size: 13px; font-weight: 600; color: var(--text-secondary); margin-bottom: 6px; }
.kw-row { display: flex; flex-wrap: wrap; gap: 4px; }
.kw-pill { font-size: 12px; background: var(--kw-pill-bg); color: var(--kw-pill-color); padding: 2px 10px; border-radius: 10px; }
.grant-row { font-size: 12px; color: var(--text-secondary); margin-bottom: 2px; }
.pico-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; }
.pico-item { background: var(--bg-card); padding: 8px 10px; border-radius: 6px; border-left: 3px solid #1a5276; }
.related-item { display:flex; align-items:flex-start; gap:10px; padding:8px 10px; background:var(--bg-card); border-radius:6px; border-left:3px solid var(--primary-color, #1a5276); }
.pico-key { display: block; font-size: 11px; color: var(--text-muted); font-weight: 600; margin-bottom: 2px; text-transform: uppercase; }
.pico-val { font-size: 13px; color: var(--text-primary); line-height: 1.5; }
.baseline-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; }
.baseline-item { background: var(--bg-card); padding: 8px 10px; border-radius: 6px; border-left: 3px solid #27ae60; }
.ai-summary-box { background:var(--bg-card); padding:12px 16px; border-radius:6px; font-size:14px; line-height:1.8; border:1px solid var(--border-color); }
.baseline-key { display: block; font-size: 11px; color: var(--text-muted); font-weight: 600; margin-bottom: 4px; }
.baseline-vals { display: flex; flex-direction: column; gap: 2px; }
.baseline-val { font-size: 13px; color: var(--text-primary); }
.baseline-arm { font-weight: 500; color: var(--text-secondary); }
.abstract-text { line-height:1.8; white-space:pre-wrap; font-size:14px; }
.abstract-text :deep(.search-highlight) { background: #ffd700; color: #333; padding: 0 2px; border-radius: 2px; }
html.dark .abstract-text :deep(.search-highlight) { background: #b8860b; color: #fff; }
.note-item { margin-top:12px; padding:12px; background: var(--bg-card); border-radius:6px; border:1px solid var(--border-color); }
.note-author { font-size:11px; color:var(--text-muted); margin-bottom:4px; }
.note-content { color: var(--text-primary) !important; line-height: 1.6; }
.note-content.clamp-3 { overflow:hidden; max-height:72px; }
.expand-toggle { font-size:12px; color:var(--primary-color, #3a7bc8); cursor:pointer; margin-top:2px; }
.expand-toggle:hover { text-decoration:underline; }
.highlights-section { margin-top:8px; position:relative; }
.hl-toolbar { position:fixed; z-index:1000; display:flex; gap:2px; background:var(--hl-toolbar-bg, #333); border-radius:6px; padding:4px; }
.hl-tb-btn { background:none; border:none; color:var(--hl-tb-btn-color, #fff); font-size:14px; cursor:pointer; padding:2px 6px; border-radius:4px; }
.hl-tb-btn:hover { background:var(--hl-tb-btn-hover, #555); }
.hl-form { background:var(--bg-card); border:1px solid var(--border-color); border-radius:6px; padding:12px; }
.hl-field { margin-bottom:8px; }
.hl-field label { display:block; font-size:11px; color:var(--text-muted); margin-bottom:2px; }
.hl-input { width:100%; padding:6px 8px; border:1px solid var(--border-color); border-radius:4px; font-size:13px; background:var(--bg-color); color:var(--text-color); box-sizing:border-box; }
.hl-select { padding:4px 8px; border:1px solid var(--border-color); border-radius:4px; font-size:12px; background:var(--bg-color); color:var(--text-color); }
.hl-item { background:var(--bg-card); border:1px solid var(--border-color); border-radius:6px; padding:12px; margin-bottom:8px; }
.hl-item-header { display:flex; align-items:center; gap:6px; margin-bottom:6px; }
.hl-type-badge { font-size:10px; padding:1px 6px; border-radius:3px; background:var(--border-color); color:var(--text-secondary); }
.hl-type-badge.highlight { background:var(--badge-warning-bg, #fff3cd); color:var(--badge-warning-text, #856404); }
.hl-type-badge.underline { background:var(--badge-info-bg, #cce5ff); color:var(--badge-info-text, #004085); }
.hl-type-badge.strikethrough { background:var(--badge-error-bg, #f8d7da); color:var(--badge-error-text, #721c24); }
.hl-type-badge.free_text { background:var(--badge-success-bg, #d4edda); color:var(--badge-success-text, #155724); }
.hl-color-dot { width:14px; height:14px; border-radius:50%; border:1px solid var(--border-color); flex-shrink:0; }
.hl-text { font-size:13px; color:var(--text-color); line-height:1.5; margin-bottom:4px; padding:6px 8px; background:var(--bg-color); border-radius:4px; border-left:3px solid var(--border-color); }
.hl-note { font-size:12px; color:var(--text-secondary); margin-top:4px; }
.update-notice { font-size:12px; color:var(--text-color); background:var(--bg-card); padding:6px 12px; border-radius:6px; margin-bottom:12px; border-left:3px solid var(--accent-border, #e8c080); }

@media (max-width: 768px) {
  .detail { padding: 12px !important; }
  .detail h2 { font-size: 18px; }
  .pico-grid { grid-template-columns: 1fr; }
  .baseline-grid { grid-template-columns: 1fr; }
}
</style>
