<script setup lang="ts">
import { ref, onMounted, watch, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { NTag, NCard, NGrid, NGridItem, NSkeleton, NInput, NPagination, useMessage } from 'naive-ui'
import { api } from '../../api/client'
import { trackAction } from '../../composables/useAnalytics'

const message = useMessage()

const router = useRouter()
const journals = ref<any[]>([])
const loading = ref(true)
const search = ref('')
const selectedTier = ref<string|null>(null)
const selectedIssn = ref<string|null>(null)
const journalArticles = ref<any[]>([])
const journalLoading = ref(false)
const total = ref(0)
const page = ref(1)
const pageSize = ref(20)
const tierCounts = ref<Record<string, number>>({})

async function load() {
  loading.value = true
  try {
    const params: Record<string, any> = { page: page.value, page_size: pageSize.value }
    if (selectedTier.value) params.tier = selectedTier.value
    if (search.value) params.q = search.value
    const { data } = await api.get('/public/journals', { params })
    journals.value = data.journals || []
    total.value = data.total || 0
    tierCounts.value = data.tier_counts || {}
    trackAction('browse_journals', 'journal')
  } catch (e: any) {
    message.error(e?.response?.data?.detail || '加载期刊失败')
  } finally {
    loading.value = false
  }
}

onMounted(load)

function selectTier(tier: string) {
  selectedTier.value = selectedTier.value === tier ? null : tier
  page.value = 1
  load()
}

async function onSearch() {
  page.value = 1
  await nextTick()
  load()
}

watch(page, load)

function selectJournal(j: any) {
  selectedIssn.value = j.issn
  journalLoading.value = true
  api.get(`/public/journals/${j.issn}`).then(({ data }) => {
    journalArticles.value = data.items || []
  }).catch(e => message.error(e?.response?.data?.detail || '加载期刊文章失败'))
  .finally(() => { journalLoading.value = false })
}

function goJournalDetail(issn: string) {
  router.push(`/app/journals/${issn}`)
}

const tierInfo: Record<string, { label: string; color: string; desc: string }> = {
  '1': { label: '四大综合', color: '#d03050', desc: 'NEJM / Lancet / JAMA / BMJ' },
  '2': { label: '肿瘤顶刊', color: '#f0a020', desc: 'JCO / Lancet Oncol / JAMA Oncol / Cancer Discov' },
  '3': { label: '专科顶刊', color: '#18a058', desc: 'Ann Oncol / CCR / JNCI / Cancer Cell' },
  '4': { label: '其他SCI', color: '#999', desc: '其他肿瘤相关SCI期刊' },
}
</script>

<template>
  <div style="max-width:1200px;margin:0 auto;padding:32px 24px 80px">
    <div style="text-align:center;margin-bottom:32px">
      <h1 style="font-size:28px;margin-bottom:8px">📰 肿瘤学期刊导航</h1>
      <p style="color:var(--text-secondary)">
        浏览 <strong>{{ total }}</strong> 本肿瘤学期刊 · 查看最新文献
        <span v-if="selectedTier" style="margin-left:8px;font-size:13px;color:var(--text-muted)">（当前筛选：{{ tierInfo[selectedTier]?.label }}）</span>
      </p>
    </div>

    <!-- 期刊等级说明 -->
    <n-grid :cols="4" :x-gap="12" responsive="screen" style="margin-bottom:24px">
      <n-grid-item v-for="(info, tier) in tierInfo" :key="tier">
        <n-card size="small"
                :style="{ cursor:'pointer', textAlign:'center', border: selectedTier===tier ? '2px solid ' + info.color : '1px solid var(--border-color)' }"
                @click="selectTier(tier)">
          <div style="font-size:14px;font-weight:600">{{ info.label }}</div>
          <div style="font-size:12px;color:var(--text-muted);margin-top:4px">{{ info.desc }}</div>
          <div style="font-size:20px;font-weight:700;margin-top:6px;color:var(--text-primary)">
            {{ tierCounts[tier] ?? '—' }}
          </div>
        </n-card>
      </n-grid-item>
    </n-grid>

    <div style="display:flex;gap:24px;flex-wrap:wrap;align-items:flex-start">
      <!-- 左侧期刊列表 -->
      <div style="flex:1;min-width:280px">
        <div style="display:flex;gap:8px;margin-bottom:12px">
          <NInput v-model:value="search" placeholder="搜索期刊..." size="small" clearable
                  @keyup.enter="onSearch" @clear="onSearch" style="flex:1" />
        </div>
        <NSkeleton v-if="loading" text :repeat="8" />
        <div v-for="j in journals" :key="j.id"
                class="journal-item"
                :class="{ active: selectedIssn === j.issn }"
                @click="selectJournal(j)">
          <div style="display:flex;justify-content:space-between;align-items:center;font-size:14px">
            <span style="flex:1;font-weight:500">{{ j.name }}</span>
            <span style="width:50px;text-align:right;font-weight:700;color:#1a5276" v-if="j.impact_factor">IF {{ j.impact_factor }}</span>
            <NTag size="tiny" :bordered="false" style="margin-left:8px">{{ j.article_count }}篇</NTag>
          </div>
          <div style="text-align:right;margin-top:4px">
            <span style="font-size:11px;color:#1890ff;cursor:pointer" @click.stop="goJournalDetail(j.issn)">详情 →</span>
          </div>
        </div>
        <!-- 分页 -->
        <div v-if="total > 0" style="display:flex;justify-content:center;margin:16px 0">
          <NPagination v-model:page="page" :page-count="Math.ceil(total / pageSize)" :page-size="pageSize" />
        </div>
      </div>

      <!-- 右侧期刊文献 -->
      <div style="flex:2;min-width:400px">
        <div v-if="!selectedIssn" style="text-align:center;padding:80px 0;color:var(--text-muted)">
          <div style="font-size:48px;margin-bottom:12px">📰</div>
          <div>选择左侧期刊查看最新文献</div>
        </div>
        <div v-else>
          <h3 style="margin-bottom:16px">{{ journals.find((j:any)=>j.issn===selectedIssn)?.name }} · {{ journalArticles.length }} 篇</h3>
          <NSkeleton v-if="journalLoading" text :repeat="5" />
          <n-card v-for="item in journalArticles" :key="item.id" size="small" style="margin-bottom:4px;cursor:pointer"
                  @click="router.push(`/literature/${item.pmid}`)">
            <div style="font-size:14px;font-weight:500">{{ item.title }}</div>
            <div style="font-size:12px;color:var(--text-muted);margin-top:4px">
              {{ item.first_author }} et al. · {{ (item.article_date || item.pub_date)?.slice(0,10) }}
              <NTag v-for="t in (item.tags||[]).slice(0,3)" :key="t.id" size="tiny" style="margin-left:4px">{{ t.name_zh }}</NTag>
            </div>
          </n-card>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.journal-item {
  padding: 8px 12px;
  margin-bottom: 4px;
  border-radius: 6px;
  cursor: pointer;
  border: 1px solid var(--border-color);
  border-left: 3px solid transparent;
  background: var(--bg-card);
  transition: box-shadow .15s;
}
.journal-item:hover {
  box-shadow: 0 1px 6px var(--shadow);
}
.journal-item.active {
  border-left-color: #1a5276;
  background: var(--bg-hover);
}
</style>
