<script lang="ts">
export default { name: 'BookReaderView' }
</script>
<template>
  <div class="reader-page page-fullscreen" @touchstart="onTouchStart" @touchend="onTouchEnd">
    <!-- 顶栏 -->
    <div class="reader-top">
      <div v-if="fromWorks" class="back-btn" @click="handleBack">
        <left-outlined />
      </div>
      <div class="top-title">{{ title }}</div>
    </div>

    <!-- 书本区域 -->
    <div class="book-area page-content">
      <div
        class="book"
        :class="{ 'flip-left': flipDir === -1, 'flip-right': flipDir === 1 }"
        :style="{ background: pageBg }"
      >
        <div class="book-spine" />

        <!-- 封面 -->
        <div v-if="isCover" class="page-cover">
          <div class="cover-image">
            <img v-if="coverImageUrl" :src="coverImageUrl" class="cover-real-img" />
            <picture-outlined v-else class="cover-placeholder" />
          </div>
          <div class="cover-title">{{ currentPage.text }}</div>
          <div class="cover-divider" />
          <div class="cover-brand">{{ brandName }} · AI 绘本创作</div>
          <div v-if="authorDisplay" class="cover-author">
            <user-outlined />
            <span>{{ authorDisplay }}</span>
          </div>
        </div>

        <!-- 正文页 -->
        <div v-else-if="isContent" class="book-content-page">
          <div class="content-image">
            <img v-if="currentPage.imageUrl" :src="currentPage.imageUrl" class="content-real-img" />
            <picture-outlined v-else class="content-placeholder" />
            <div class="page-num">P{{ idx }}</div>
          </div>
          <div class="content-text">{{ currentPage.text }}</div>
        </div>

        <!-- 封底 -->
        <div v-else-if="isBack" class="page-back">
          <heart-filled class="back-icon" />
          <div class="back-title">故事讲完了</div>
          <div class="back-divider" />
          <div class="back-desc">你的画作<br />变成了一个精彩的故事</div>
          <div v-if="workTags.length" class="book-tags">
            <span v-for="tag in workTags" :key="tag" class="book-tag">{{ tag }}</span>
          </div>
          <div class="back-replay" @click="jumpTo(0)">
            <reload-outlined />
            <span>重新阅读</span>
          </div>
          <div class="back-brand">{{ brandName }} · AI 绘本创作</div>
        </div>
      </div>

      <!-- 翻页导航 -->
      <div class="nav-row">
        <div class="nav-btn prev" :class="{ disabled: idx <= 0 }" @click="go(-1)">
          <left-outlined />
        </div>
        <div class="nav-label">
          {{ isCover ? '封面' : isBack ? '— 完 —' : `${idx} / ${totalContent}` }}
        </div>
        <div class="nav-btn next" :class="{ disabled: idx >= pages.length - 1 }" @click="go(1)">
          <right-outlined />
        </div>
      </div>

      <!-- 进度条 -->
      <div class="progress-bar-wrap">
        <div class="progress-bar-fill" :style="{ width: progressPct + '%' }" />
      </div>
    </div>

    <!-- 底部：再次创作（仅创作流程入口显示，作品库入口不显示） -->
    <div v-if="!fromWorks" class="reader-bottom page-bottom">
      <button class="btn-primary again-btn" @click="goHome">
        <plus-outlined />
        <span>再创作一本</span>
      </button>
      <div class="bottom-hint">本作品可在「作品库」继续查看</div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onActivated } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import {
  LeftOutlined,
  RightOutlined,
  PictureOutlined,
  UserOutlined,
  HeartFilled,
  ReloadOutlined,
  PlusOutlined,
} from '@ant-design/icons-vue'
import { useAicreateStore } from '@/stores/aicreate'
import { getWorkDetail } from '@/api/aicreate'

const route = useRoute()
const router = useRouter()
const store = useAicreateStore()

const fromWorks = new URLSearchParams(window.location.search).get('from') === 'works'
  || sessionStorage.getItem('le_from') === 'works'

const brandName = '智创未来'

function handleBack() {
  if (fromWorks) {
    router.push('/p/works')
  } else {
    router.back()
  }
}

const idx = ref(0)
const flipDir = ref(0)

const title = ref('我的绘本')
const coverImageUrl = ref('')
const authorDisplay = ref('')
const workTags = ref<string[]>([])
const pages = ref<any[]>([
  { pageNum: 0, text: '我的绘本', type: 'cover' },
  { pageNum: 99, text: '', type: 'backcover' },
])

const currentPage = computed(() => pages.value[idx.value])
const isCover = computed(() => idx.value === 0)
const isBack = computed(() => currentPage.value?.type === 'backcover')
const isContent = computed(() => !isCover.value && !isBack.value)
const totalContent = computed(() => pages.value.length - 2)
const progressPct = computed(() => ((idx.value) / (pages.value.length - 1)) * 100)

const pageBg = computed(() => {
  if (isCover.value) return 'linear-gradient(135deg, #6366f1 0%, #8b5cf6 50%, #ec4899 100%)'
  if (isBack.value) return 'linear-gradient(135deg, #8b5cf6 0%, #a78bfa 50%, #f472b6 100%)'
  return '#ffffff'
})

const go = (dir: number) => {
  const next = idx.value + dir
  if (next < 0 || next >= pages.value.length) return
  flipDir.value = dir
  setTimeout(() => { idx.value = next; flipDir.value = 0 }, 250)
}

const jumpTo = (i: number) => { idx.value = i; flipDir.value = 0 }

// 触摸滑动翻页
let touchStartX = 0
let touchStartY = 0
const onTouchStart = (e: TouchEvent) => {
  touchStartX = e.touches[0].clientX
  touchStartY = e.touches[0].clientY
}
const onTouchEnd = (e: TouchEvent) => {
  const dx = e.changedTouches[0].clientX - touchStartX
  const dy = e.changedTouches[0].clientY - touchStartY
  if (Math.abs(dx) > 50 && Math.abs(dx) > Math.abs(dy) * 1.5) {
    go(dx < 0 ? 1 : -1)
  }
}

const goHome = () => {
  store.reset()
  router.push('/p/create')
}

function applyWork(work: any) {
  title.value = work.title || '我的绘本'
  const list: any[] = [{ pageNum: 0, text: work.title || '我的绘本', type: 'cover' }]
  ;(work.pageList || []).forEach((p: any) => {
    if (p.pageNum > 0) list.push({ pageNum: p.pageNum, text: p.text, imageUrl: p.imageUrl })
  })
  if (work.pageList?.[0]?.imageUrl) coverImageUrl.value = work.pageList[0].imageUrl
  if (work.author) authorDisplay.value = work.author
  if (Array.isArray(work.tags) && work.tags.length > 0) workTags.value = work.tags
  list.push({ pageNum: 99, text: '', type: 'backcover' })
  pages.value = list
}

async function loadReader() {
  idx.value = 0
  const workId = route.params.workId

  if (!workId) return
  try {
    let work
    const shareToken = new URLSearchParams(window.location.search).get('st') || ''
    if (store.sessionToken) {
      const res = await getWorkDetail(workId)
      work = res
    } else if (shareToken) {
      const leaiBase = import.meta.env.VITE_LEAI_API_URL || ''
      const resp = await fetch(`${leaiBase}/api/v1/query/work/${workId}?shareToken=${encodeURIComponent(shareToken)}`)
      const json = await resp.json()
      work = json.data
    } else {
      return
    }
    if (work) applyWork(work)
  } catch { /* use default */ }
}

onActivated(loadReader)
</script>

<style lang="scss" scoped>
.reader-page {
  background: var(--ai-bg);
  user-select: none;
  -webkit-user-select: none;
}

/* ---------- 顶栏 ---------- */
.reader-top {
  flex-shrink: 0;
  padding: 12px 16px;
  display: flex;
  align-items: center;
  background: rgba(255, 255, 255, 0.92);
  backdrop-filter: blur(12px);
  border-bottom: 1px solid rgba(99, 102, 241, 0.08);
  position: relative;
}
.back-btn {
  position: absolute;
  left: 12px;
  width: 32px;
  height: 32px;
  cursor: pointer;
  background: rgba(99, 102, 241, 0.08);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: var(--ai-primary);

  :deep(.anticon) { font-size: 16px; }
}
.top-title {
  font-size: 15px;
  font-weight: 700;
  color: var(--ai-text);
  flex: 1;
  text-align: center;
  letter-spacing: 0.5px;
}

/* ---------- 书本区域 ---------- */
.book-area {
  display: flex !important;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 14px 16px 16px;
}

.book {
  width: 100%;
  max-width: 320px;
  aspect-ratio: 3 / 4;
  border-radius: 4px 16px 16px 4px;
  position: relative;
  overflow: hidden;
  box-shadow:
    inset -4px 0 8px rgba(0, 0, 0, 0.04),
    4px 0 12px rgba(99, 102, 241, 0.14),
    0 14px 36px rgba(99, 102, 241, 0.2);
  transition: transform 0.25s ease;

  &.flip-left { transform: perspective(800px) rotateY(8deg); }
  &.flip-right { transform: perspective(800px) rotateY(-8deg); }
}

.book-spine {
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  width: 6px;
  background: linear-gradient(180deg, rgba(0, 0, 0, 0.12), rgba(0, 0, 0, 0.02), rgba(0, 0, 0, 0.12));
  z-index: 1;
}

/* ---------- 封面 ---------- */
.page-cover {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 24px 26px;
  text-align: center;
  position: relative;
}
.cover-image {
  width: 100%;
  aspect-ratio: 16 / 9;
  border-radius: 14px;
  background: rgba(255, 255, 255, 0.18);
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 18px;
  overflow: hidden;
  backdrop-filter: blur(8px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.18);
}
.cover-real-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
.cover-placeholder {
  font-size: 56px;
  color: rgba(255, 255, 255, 0.5);
}
.cover-title {
  font-size: 22px;
  font-weight: 900;
  color: #fff;
  text-shadow: 0 2px 10px rgba(0, 0, 0, 0.18);
  line-height: 1.3;
  letter-spacing: 1.5px;
}
.cover-divider {
  width: 50px;
  height: 2px;
  background: rgba(255, 255, 255, 0.55);
  border-radius: 2px;
  margin: 14px 0 12px;
}
.cover-brand {
  font-size: 12px;
  color: rgba(255, 255, 255, 0.88);
  font-weight: 500;
  letter-spacing: 0.5px;
}
.cover-author {
  margin-top: 12px;
  display: inline-flex;
  align-items: center;
  gap: 5px;
  font-size: 11px;
  color: #fff;
  background: rgba(255, 255, 255, 0.18);
  border: 1px solid rgba(255, 255, 255, 0.28);
  border-radius: 12px;
  padding: 4px 12px;
  backdrop-filter: blur(4px);

  :deep(.anticon) { font-size: 11px; }
}

/* ---------- 正文页 ---------- */
.book-content-page {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
}
.content-image {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 14px;
  position: relative;
  background: #1e1b4b;
}
.content-real-img {
  width: 100%;
  height: 100%;
  object-fit: contain;
  border-radius: 10px;
}
.content-placeholder {
  font-size: 48px;
  color: rgba(255, 255, 255, 0.3);
}
.page-num {
  position: absolute;
  top: 14px;
  left: 14px;
  background: rgba(15, 12, 41, 0.6);
  backdrop-filter: blur(4px);
  border-radius: 8px;
  padding: 3px 10px;
  font-size: 11px;
  font-weight: 700;
  color: #fff;
  letter-spacing: 0.5px;
}
.content-text {
  padding: 14px 22px 18px;
  text-align: center;
  background: #fff;
  border-top: 1px solid rgba(99, 102, 241, 0.08);
  font-size: 14px;
  font-weight: 500;
  line-height: 1.7;
  color: var(--ai-text);
  letter-spacing: 0.3px;
}

/* ---------- 封底 ---------- */
.page-back {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 32px 28px;
  text-align: center;
}
.back-icon {
  font-size: 44px;
  color: #fff;
  margin-bottom: 16px;
  filter: drop-shadow(0 2px 8px rgba(0, 0, 0, 0.18));
}
.back-title {
  font-size: 20px;
  font-weight: 900;
  color: #fff;
  text-shadow: 0 2px 8px rgba(0, 0, 0, 0.18);
  letter-spacing: 1px;
}
.back-divider {
  width: 36px;
  height: 2px;
  background: rgba(255, 255, 255, 0.55);
  border-radius: 2px;
  margin: 12px 0;
}
.back-desc {
  font-size: 13px;
  color: rgba(255, 255, 255, 0.92);
  line-height: 1.7;
  font-weight: 500;
}

.book-tags {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  gap: 6px;
  margin-top: 14px;
  padding: 0 16px;
}
.book-tag {
  display: inline-block;
  padding: 4px 12px;
  border-radius: 14px;
  font-size: 11px;
  font-weight: 600;
  color: #fff;
  background: rgba(255, 255, 255, 0.2);
  border: 1px solid rgba(255, 255, 255, 0.32);
  backdrop-filter: blur(4px);
}

.back-replay {
  margin-top: 22px;
  display: inline-flex;
  align-items: center;
  gap: 6px;
  background: #fff;
  color: var(--ai-primary);
  font-size: 14px;
  font-weight: 700;
  padding: 11px 26px;
  border-radius: 24px;
  cursor: pointer;
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.18);
  transition: transform 0.2s;

  :deep(.anticon) { font-size: 13px; }

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

.back-brand {
  margin-top: 18px;
  font-size: 11px;
  color: rgba(255, 255, 255, 0.85);
  letter-spacing: 0.5px;
  font-weight: 500;
}

/* ---------- 翻页导航 ---------- */
.nav-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  max-width: 320px;
  margin-top: 16px;
  padding: 0 4px;
}
.nav-btn {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.2s;

  :deep(.anticon) { font-size: 16px; }

  &.prev {
    background: #fff;
    color: var(--ai-primary);
    border: 1px solid rgba(99, 102, 241, 0.2);
    box-shadow: 0 2px 10px rgba(99, 102, 241, 0.08);

    &:hover { border-color: var(--ai-primary); }
  }
  &.next {
    background: var(--ai-gradient);
    color: #fff;
    box-shadow: 0 4px 14px rgba(99, 102, 241, 0.32);

    &:hover { transform: scale(1.05); }
  }
  &.disabled {
    opacity: 0;
    pointer-events: none;
  }
}
.nav-label {
  font-size: 12px;
  color: var(--ai-text-sub);
  font-weight: 600;
  letter-spacing: 0.5px;
}

/* ---------- 进度条 ---------- */
.progress-bar-wrap {
  width: 100%;
  max-width: 320px;
  height: 3px;
  background: rgba(99, 102, 241, 0.12);
  border-radius: 2px;
  margin-top: 12px;
  overflow: hidden;
}
.progress-bar-fill {
  height: 100%;
  background: var(--ai-gradient);
  border-radius: 2px;
  transition: width 0.4s ease;
}

/* ---------- 底部 ---------- */
.reader-bottom {
  display: flex;
  flex-direction: column;
  align-items: center;
  background: #fff;
  border-top: 1px solid rgba(99, 102, 241, 0.08);
}
.again-btn {
  display: flex !important;
  align-items: center;
  justify-content: center;
  gap: 8px;
  width: 100%;
  font-size: 16px !important;
  padding: 14px 0 !important;
  border-radius: 28px !important;

  :deep(.anticon) { font-size: 16px; }
}
.bottom-hint {
  margin-top: 8px;
  font-size: 12px;
  color: var(--ai-text-sub);
  text-align: center;
}
</style>
