<template>
  <div class="reader-page" @touchstart="onTouchStart" @touchend="onTouchEnd">
    <!-- 顶栏 -->
    <div class="reader-top">
      <div v-if="fromWorks" class="back-btn" @click="handleBack">
        <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2.5" stroke-linecap="round"><path d="M15 18l-6-6 6-6"/></svg>
      </div>
      <div class="top-title">{{ title }}</div>
    </div>

    <!-- 书本区域 -->
    <div class="book-area">
      <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-deco star">⭐</div>
          <div class="cover-image" v-if="coverImageUrl">
            <img :src="coverImageUrl" class="cover-real-img" />
          </div>
          <div class="cover-image" v-else>📖</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">✍️ {{ authorDisplay }}</div>
        </div>

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

        <!-- 封底 -->
        <div v-else-if="isBack" class="page-back">
          <div class="back-emoji">🎉</div>
          <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)">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><path d="M1 4v6h6"/><path d="M3.51 15a9 9 0 105.64-8.36L1 10"/></svg>
            重新阅读
          </div>
          <div class="back-brand">{{ brandName }} AI 绘本 · {{ brandSlogan }}</div>
        </div>
      </div>

      <!-- 翻页导航 -->
      <div class="nav-row">
        <div class="nav-btn prev" :class="{ disabled: idx <= 0 }" @click="go(-1)">
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><path d="M15 18l-6-6 6-6"/></svg>
        </div>
        <div class="nav-label">{{ isCover ? '封面' : isBack ? '— 完 —' : `${idx} / ${totalContent}` }}</div>
        <div class="nav-btn next" :class="{ disabled: idx >= pages.length - 1 }" @click="go(1)">
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><path d="M9 18l6-6-6-6"/></svg>
        </div>
      </div>

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

    <!-- 底部：再次创作（仅创作流程入口显示，作品列表入口不显示） -->
    <div v-if="!fromWorks" class="reader-bottom safe-bottom">
      <button class="btn-primary" @click="goHome">再次创作 →</button>
      <div class="bottom-hint">本作品可在作品板块中查看</div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { store } from '@/utils/store'
import { getWorkDetail } from '@/api'
import config from '@/utils/config'

const route = useRoute()
const router = useRouter()
const fromWorks = new URLSearchParams(window.location.search).get('from') === 'works'
  || sessionStorage.getItem('le_from') === 'works'
import bridge from '@/utils/bridge'

function handleBack() {
  if (bridge.isEmbedded) {
    bridge.send('NAVIGATE_BACK')
  } else {
    router.back()
  }
}

const brandName = config.brand.title || '乐读派'
const brandSlogan = config.brand.slogan || '让想象力飞翔'

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

const title = ref('我的绘本')
const coverImageUrl = ref('')
const authorDisplay = ref('')
const workTags = ref([])
const pages = ref([
  { 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 bgColors = ['#FFF5EB', '#E8F4FD', '#F0F9EC', '#FFF8E1', '#F3E8FF', '#E0F7F4', '#FFF9E6', '#FCE4EC']
const emojis = ['📖', '🌅', '🐦', '🗣️', '🍄', '🏠', '❤️', '🌟']
const pageEmoji = computed(() => emojis[idx.value % emojis.length])

const pageBg = computed(() => {
  if (isCover.value) return 'linear-gradient(135deg, #FF8F65 0%, #FF6B35 40%, #E85D26 100%)'
  if (isBack.value) return 'linear-gradient(135deg, #FFD4A8 0%, #FFB874 50%, #FF9F43 100%)'
  return `linear-gradient(180deg, ${bgColors[idx.value % bgColors.length]} 0%, #FFFFFF 100%)`
})

const go = (dir) => {
  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) => { idx.value = i; flipDir.value = 0 }

// 触摸滑动翻页
let touchStartX = 0
let touchStartY = 0

const onTouchStart = (e) => {
  touchStartX = e.touches[0].clientX
  touchStartY = e.touches[0].clientY
}

const onTouchEnd = (e) => {
  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('/')
}

onMounted(async () => {
  const workId = route.params.workId
  if (!workId) return
  try {
    let work
    const shareToken = new URLSearchParams(window.location.search).get('st') || ''
    if (store.sessionToken || store.appSecret) {
      // 认证用户: 用 axios 实例（自动加 HMAC/Bearer 头）
      const res = await getWorkDetail(workId)
      work = res.data
    } else if (shareToken) {
      // 分享链接: 无认证，用 shareToken
      const resp = await fetch(`/api/v1/query/work/${workId}?shareToken=${encodeURIComponent(shareToken)}`)
      const json = await resp.json()
      work = json.data
    } else {
      error.value = '请从创作流程或分享链接进入'
      return
    }
    if (work) {
      title.value = work.title || '我的绘本'
      const list = [{ pageNum: 0, text: work.title || '我的绘本', type: 'cover' }]
      ;(work.pageList || []).forEach(p => {
        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
    }
  } catch { /* use default */ }
})
</script>

<style lang="scss" scoped>
.reader-page {
  min-height: 100vh;
  background: #F5F0E8;
  display: flex;
  flex-direction: column;
  user-select: none;
  -webkit-user-select: none;
}

// 顶栏
.reader-top {
  padding: 14px 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: rgba(255,255,255,0.85);
  backdrop-filter: blur(10px);
}
.back-btn { padding: 4px; cursor: pointer; background: rgba(0,0,0,0.2); border-radius: 50%; display: flex; align-items: center; justify-content: center; }
.top-title { font-size: 15px; font-weight: 700; color: var(--text); flex: 1; text-align: center; }

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

.book {
  width: 100%;
  max-width: 360px;
  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(0,0,0,0.08), 0 8px 32px rgba(0,0,0,0.12);
  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.08), rgba(0,0,0,0.02), rgba(0,0,0,0.08));
  z-index: 1;
}

// 封面
.page-cover {
  width: 100%; height: 100%;
  display: flex; flex-direction: column;
  align-items: center; justify-content: center;
  padding: 32px; text-align: center;
}
.cover-deco { position: absolute; opacity: 0.4; &.star { top: 20px; right: 24px; font-size: 24px; } }
.cover-image {
  width: calc(100% - 32px); aspect-ratio: 4/3; border-radius: 16px;
  background: rgba(255,255,255,0.2);
  display: flex; align-items: center; justify-content: center;
  font-size: 72px; margin-bottom: 20px; overflow: hidden;
}
.cover-real-img { width: 100%; height: 100%; object-fit: cover; border-radius: 16px; }
.cover-title {
  font-size: 24px; font-weight: 900; color: #fff;
  text-shadow: 0 2px 8px rgba(0,0,0,0.2);
  line-height: 1.4; letter-spacing: 2px;
}
.cover-divider { width: 60px; height: 3px; background: rgba(255,255,255,0.5); border-radius: 2px; margin: 16px 0; }
.cover-brand { font-size: 13px; color: rgba(255,255,255,0.8); }
.cover-author {
  margin-top: 8px; font-size: 12px; color: rgba(255,255,255,0.7);
  background: rgba(255,255,255,0.15); border-radius: 12px; padding: 4px 14px;
}

// 正文页
.page-content { width: 100%; height: 100%; display: flex; flex-direction: column; }
.content-image {
  flex: 1; display: flex; align-items: center; justify-content: center;
  padding: 16px; position: relative;
}
.content-emoji { font-size: 64px; }
.content-real-img { width: 100%; height: 100%; object-fit: contain; border-radius: 12px; }
.page-num {
  position: absolute; top: 20px; left: 20px;
  background: rgba(0,0,0,0.4); border-radius: 8px; padding: 2px 10px;
  font-size: 11px; font-weight: 600; color: #fff;
}
.content-text {
  padding: 12px 24px 20px; text-align: center;
  background: rgba(255,255,255,0.6); border-top: 1px solid rgba(0,0,0,0.04);
  font-size: 16px; font-weight: 500; line-height: 1.8; letter-spacing: 0.5px;
}

// 封底
.page-back {
  width: 100%; height: 100%;
  display: flex; flex-direction: column;
  align-items: center; justify-content: center;
  padding: 40px; text-align: center;
}
.back-emoji { font-size: 56px; margin-bottom: 20px; }
.back-title { font-size: 22px; font-weight: 900; color: #fff; text-shadow: 0 2px 6px rgba(0,0,0,0.15); }
.back-divider { width: 40px; height: 3px; background: rgba(255,255,255,0.5); border-radius: 2px; margin: 14px 0; }
.back-desc { font-size: 14px; color: rgba(255,255,255,0.8); line-height: 1.8; }
.back-replay {
  margin-top: 24px;
  display: inline-flex;
  align-items: center;
  gap: 6px;
  background: rgba(255,255,255,0.95);
  color: var(--primary);
  font-size: 15px;
  font-weight: 700;
  padding: 12px 32px;
  border-radius: 28px;
  cursor: pointer;
  box-shadow: 0 4px 16px rgba(0,0,0,0.1);
  transition: transform 0.2s;
  &:active { transform: scale(0.95); }
}
.back-brand {
  margin-top: 20px;
  font-size: 12px; color: rgba(255,255,255,0.7);
}
.book-tags {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  gap: 8px;
  margin-top: 16px;
  padding: 0 20px;
}
.book-tag {
  display: inline-block;
  padding: 4px 14px;
  border-radius: 20px;
  font-size: 12px;
  font-weight: 500;
  color: #E11D48;
  background: linear-gradient(135deg, #FFF1F2, #FFE4E6);
  border: 1px solid #FECDD3;
}

// 翻页导航
.nav-row {
  display: flex; align-items: center; justify-content: space-between;
  width: 100%; max-width: 360px; margin-top: 16px; padding: 0 4px;
}
.nav-btn {
  width: 44px; height: 44px; border-radius: 50%;
  display: flex; align-items: center; justify-content: center;
  cursor: pointer; transition: all 0.2s;
  &.prev { background: var(--card); box-shadow: var(--shadow-soft); color: var(--text); }
  &.next { background: var(--gradient); box-shadow: var(--shadow); color: #fff; }
  &.disabled { opacity: 0; pointer-events: none; }
}
.nav-label { font-size: 13px; color: var(--text-sub); font-weight: 500; }

// 进度条
.progress-bar-wrap {
  width: 100%; max-width: 360px; height: 3px;
  background: #E2DDD4; border-radius: 2px; margin-top: 12px; overflow: hidden;
}
.progress-bar-fill {
  height: 100%; background: var(--primary); border-radius: 2px;
  transition: width 0.3s ease;
}

// 底部
.reader-bottom {
  padding: 12px 20px 24px;
  display: flex;
  flex-direction: column;
  align-items: center;
  background: rgba(255,255,255,0.85);
  backdrop-filter: blur(10px);
  button { width: 100%; }
}
.bottom-hint {
  margin-top: 8px;
  font-size: 12px;
  color: #9E9E9E;
  text-align: center;
}
</style>
