<template>
  <div class="ebookDetail">
    <van-nav-bar :title="ebook?.title || '电子书'" left-arrow @click-left="$router.back()" />
    <div v-if="loading" class="loadingWrap">
      <van-loading size="24px" />
    </div>
    <template v-else-if="ebook">
      <div class="coverWrap">
        <div class="cover">
          <img v-if="ebook.cover" :src="ebook.cover" alt="" class="cover__img" />
        </div>
        <p class="desc">{{ ebook.description }}</p>
      </div>
      <div class="chapterList">
        <h3 class="listTitle">目录</h3>
        <div
          v-for="(chapter, index) in chapters"
          :key="chapter.id"
          class="chapterItem"
          :class="{ locked: !canViewChapter(chapter) }"
          @click="openChapter(chapter)"
        >
          <span class="index">{{ index + 1 }}</span>
          <span class="title">{{ chapter.title }}</span>
          <div class="chapterMeta">
            <van-tag :type="getTagType(chapter)" size="small">{{ getLabel(chapter) }}</van-tag>
            <van-icon :name="canViewChapter(chapter) ? 'arrow' : 'lock'" class="arrow" />
          </div>
        </div>
      </div>
    </template>
    <VipGate
      :show="showVipGate"
      :level="gateLevel"
      :logged-in="!!user"
      @close="showVipGate = false"
      @go-login="goLogin"
      @go-upgrade="goPurchase"
    />
  </div>
</template>

<script setup>
import { computed, onMounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import VipGate from '@/components/VipGate.vue'
import { useAuth } from '@/composables/useAuth.js'
import { usePageRobots } from '@/composables/usePageRobots.js'
import { fetchEbookChapters } from '@/composables/useKnowledge.js'
import { mockEbooks } from '@/data/mockData.js'
import {
  ACCESS_LEVEL,
  canAccessLevel,
  getAccessLabel,
  getAccessTagType,
  normalizeAccessLevel,
  shouldNoindexLevel,
} from '@/utils/access.js'

const route = useRoute()
const router = useRouter()
const { user, isSvip } = useAuth()

const ebookId = route.params.id
const ebook = ref(null)
const chapters = ref([])
const loading = ref(true)
const showVipGate = ref(false)
const gateLevel = ref(ACCESS_LEVEL.VIP)

const robotsContent = computed(() => (
  chapters.value.some((chapter) => shouldNoindexLevel(chapter))
    ? 'noindex,nofollow,noarchive'
    : 'index,follow,max-image-preview:large'
))

usePageRobots(robotsContent)

function getLabel(chapter) {
  return getAccessLabel(chapter)
}

function getTagType(chapter) {
  return getAccessTagType(chapter)
}

function canViewChapter(chapter) {
  return canAccessLevel(chapter, {
    user: user.value,
    isSvip: isSvip.value,
  })
}

function openChapter(chapter) {
  if (!canViewChapter(chapter)) {
    gateLevel.value = normalizeAccessLevel(chapter)
    showVipGate.value = true
    return
  }

  router.push(`/ebook/${ebookId}/chapter/${chapter.id}`)
}

function goPurchase() {
  router.push({
    path: '/vip',
    query: { redirect: route.fullPath, source: 'ebook-detail' },
  })
}

function goLogin() {
  router.push('/login')
}

onMounted(async () => {
  ebook.value = mockEbooks.find((item) => String(item.id) === String(ebookId)) || {
    id: ebookId,
    title: '电子书',
    cover: '',
    description: '',
  }
  chapters.value = await fetchEbookChapters(ebookId)
  loading.value = false
})
</script>

<style scoped lang="less">
.ebookDetail {
  min-height: 100vh;
  background: var(--bg-primary);
  padding-bottom: env(safe-area-inset-bottom);
}

.loadingWrap {
  padding: 60px;
  text-align: center;
}

.coverWrap {
  padding: var(--page-padding);

  .cover {
    width: 100%;
    max-width: 200px;
    aspect-ratio: 3 / 4;
    margin: 0 auto 16px;
    border-radius: var(--radius-md);
    background-color: var(--color-bg-muted);
    box-shadow: var(--shadow-md);
    position: relative;
    overflow: hidden;

    @media (min-width: 768px) {
      max-width: 240px;
    }

    &__img {
      width: 100%;
      height: 100%;
      object-fit: cover;
      display: block;
      border-radius: inherit;
    }
  }

  .desc {
    margin: 0;
    font-size: 14px;
    line-height: 1.7;
    color: var(--text-secondary);
  }
}

.chapterList {
  padding: 0 var(--page-padding) 24px;

  @media (min-width: 768px) {
    padding: 0 var(--page-padding) 40px;
    max-width: 640px;
    margin: 0 auto;
  }

  .listTitle {
    margin: 0 0 12px;
    font-size: 16px;
    font-weight: 600;
    color: var(--text-primary);
  }
}

.chapterItem {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 14px 16px;
  background: var(--bg-card);
  border-radius: var(--radius-sm);
  margin-bottom: 8px;
  border: 1px solid var(--border-color);
  cursor: pointer;
  transition: transform 0.15s ease;

  &:active {
    transform: scale(0.99);
  }

  @media (min-width: 768px) {
    &:hover {
      transform: translateX(4px);
    }
  }

  &.locked .title {
    color: var(--text-secondary);
  }

  .index {
    width: 24px;
    height: 24px;
    display: flex;
    align-items: center;
    justify-content: center;
    background: var(--primary-color);
    color: #fff;
    border-radius: 50%;
    font-size: 12px;
    flex-shrink: 0;
  }

  .title {
    flex: 1;
    font-size: 15px;
    color: var(--text-primary);
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  .chapterMeta {
    display: flex;
    align-items: center;
    gap: 8px;
  }

  .arrow {
    color: var(--text-placeholder);
    font-size: 16px;
  }
}
</style>
