<template>
  <div class="preview-page page-fullscreen">
    <!-- 顶部 -->
    <div class="top-bar">
      <div class="top-title">绘本预览</div>
      <div class="top-sub">你的绘本已生成!</div>
    </div>

    <!-- 加载中 -->
    <div v-if="loading" class="loading-state">
      <div class="loading-icon">📖</div>
      <div class="loading-text">加载中...</div>
    </div>

    <!-- 加载失败 -->
    <div v-else-if="error" class="error-state card">
      <div style="font-size:36px;margin-bottom:12px">😥</div>
      <div style="font-weight:600;margin-bottom:8px">加载失败</div>
      <div style="color:var(--text-sub);font-size:13px;margin-bottom:16px">{{ error }}</div>
      <button class="btn-primary" style="width:auto;padding:10px 32px" @click="loadWork">重试</button>
    </div>

    <!-- 主内容 -->
    <template v-else-if="pages.length">
      <div class="content page-content" @touchstart="onTouchStart" @touchend="onTouchEnd">
        <!-- 1. 图片区：16:9 完整展示，不裁切 -->
        <div class="image-section">
          <div class="page-badge">{{ pageBadge }}</div>
          <img v-if="currentPage.imageUrl" :src="currentPage.imageUrl" class="page-image" />
          <div v-else class="page-image placeholder-img">📖</div>
        </div>

        <!-- 2. 故事文字区 -->
        <div class="text-section">
          <div class="text-deco">"</div>
          <div class="story-text">{{ currentPage.text || '' }}</div>
        </div>

        <!-- 3. 翻页 -->
        <div class="nav-row">
          <button class="nav-btn" :class="{ invisible: idx <= 0 }" @click="prev">‹</button>
          <span class="page-counter">{{ idx + 1 }} / {{ pages.length }}</span>
          <button class="nav-btn" :class="{ invisible: idx >= pages.length - 1 }" @click="next">›</button>
        </div>

        <!-- 4. 横版卡片网格（2列） -->
        <div class="thumb-grid">
          <div v-for="(p, i) in pages" :key="i"
            class="thumb-card" :class="{ active: i === idx }"
            @click="idx = i">
            <div class="thumb-card-img-wrap">
              <img v-if="p.imageUrl" :src="p.imageUrl" class="thumb-card-img" />
              <div v-else class="thumb-card-placeholder">📖</div>
              <div class="thumb-card-badge">{{ i === 0 ? '封面' : 'P' + i }}</div>
            </div>
            <div class="thumb-card-text">{{ p.text ? (p.text.length > 16 ? p.text.slice(0,16) + '...' : p.text) : '' }}</div>
          </div>
        </div>
      </div>

      <!-- 底部按钮 -->
      <div class="page-bottom">
        <button class="btn-primary" @click="goEditInfo">下一步: 编辑绘本信息 →</button>
      </div>
    </template>
  </div>
</template>

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

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

const loading = ref(true)
const error = ref('')
const pages = ref([])
const idx = ref(0)
const thumbStrip = ref(null)

// Touch swipe
let touchX = 0
const onTouchStart = (e) => { touchX = e.touches[0].clientX }
const onTouchEnd = (e) => {
  const dx = e.changedTouches[0].clientX - touchX
  if (Math.abs(dx) > 50) dx > 0 ? prev() : next()
}

const currentPage = computed(() => pages.value[idx.value] || {})
const pageBadge = computed(() => {
  if (idx.value === 0) return '封面'
  return `P${idx.value}`
})

function prev() { if (idx.value > 0) { idx.value--; scrollThumbIntoView(idx.value) } }
function next() { if (idx.value < pages.value.length - 1) { idx.value++; scrollThumbIntoView(idx.value) } }

function scrollThumbIntoView(i) {
  nextTick(() => {
    const el = thumbStrip.value?.children[i]
    if (el) el.scrollIntoView({ behavior: 'smooth', inline: 'center', block: 'nearest' })
  })
}

const workId = computed(() => route.params.workId || store.workId)

async function loadWork() {
  loading.value = true
  error.value = ''
  try {
    const res = await getWorkDetail(workId.value)
    const work = res.data
    store.workDetail = work
    store.workId = work.workId

    // 如果作品状态已超过 COMPLETED，重定向到对应页面
    if (work.status > STATUS.COMPLETED) {
      const route = getRouteByStatus(work.status, work.workId)
      if (route) { router.replace(route); return }
    }

    pages.value = (work.pageList || []).map(p => ({
      pageNum: p.pageNum,
      text: p.text,
      imageUrl: p.imageUrl,
      audioUrl: p.audioUrl
    }))
  } catch (e) {
    error.value = e.message || '加载失败'
  } finally {
    loading.value = false
  }
}

function goEditInfo() {
  router.push(`/edit-info/${workId.value}`)
}

onMounted(loadWork)
</script>

<style lang="scss" scoped>
.preview-page {
  background: var(--bg);
}

.top-bar {
  background: var(--gradient);
  padding: 20px 20px 16px;
  color: #fff;
}
.top-title { font-size: 20px; font-weight: 800; }
.top-sub { font-size: 13px; opacity: 0.85; margin-top: 4px; }

.loading-state, .error-state {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px;
}
.loading-icon { font-size: 48px; animation: pulse 1.5s ease infinite; }
.loading-text { margin-top: 12px; color: var(--text-sub); }

.content {
  padding: 10px 14px 14px;
}

/* 1. 图片区：16:9 完整展示 */
.image-section {
  position: relative;
  border-radius: 18px;
  overflow: hidden;
  background: #1A1A1A;
  box-shadow: 0 6px 24px rgba(0,0,0,0.12);
}
.page-image {
  width: 100%;
  display: block;
  object-fit: contain; /* 16:9 横图完整显示，不裁切 */
  aspect-ratio: 16 / 9;
  background: #1A1A1A; /* 上下留黑，像电影画幅 */
}
.placeholder-img {
  aspect-ratio: 16 / 9;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 48px;
  background: #F5F3EE;
}
.page-badge {
  position: absolute;
  top: 10px;
  left: 10px;
  background: linear-gradient(135deg, rgba(255,107,53,0.9), rgba(255,140,66,0.9));
  color: #fff;
  font-size: 11px;
  font-weight: 700;
  padding: 4px 14px;
  border-radius: 20px;
  z-index: 2;
  box-shadow: 0 2px 8px rgba(255,107,53,0.3);
}

/* 2. 故事文字区 */
.text-section {
  background: rgba(255,255,255,0.92);
  border-radius: 0 0 18px 18px;
  margin-top: -8px; /* 与图片无缝衔接 */
  padding: 18px 22px 16px;
  position: relative;
  box-shadow: 0 4px 16px rgba(0,0,0,0.05);
  min-height: 60px;
}
.text-deco {
  position: absolute;
  top: 4px; left: 14px;
  font-size: 36px; color: #FFD166; opacity: 0.25;
  font-family: Georgia, serif; font-weight: 900; line-height: 1;
}
.story-text {
  font-size: 16px;
  line-height: 1.8;
  color: #3D2E1E;
  font-weight: 500;
  padding-left: 4px;
}

/* 3. 翻页行 */

.nav-row {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 20px;
}
.nav-btn {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  border: none;
  background: var(--card);
  box-shadow: 0 2px 8px rgba(0,0,0,0.06);
  font-size: 18px;
  font-weight: 700;
  color: var(--primary);
  cursor: pointer;

  &:active { transform: scale(0.9); }
  &.invisible { opacity: 0; pointer-events: none; }
}
.page-counter {
  font-size: 12px;
  color: var(--text-sub);
  font-weight: 500;
}

/* 4. 横版卡片网格 */
.thumb-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 10px;
  padding: 4px 0;
}
.thumb-card {
  border-radius: 14px;
  overflow: hidden;
  background: rgba(255,255,255,0.9);
  box-shadow: 0 2px 10px rgba(0,0,0,0.06);
  cursor: pointer;
  transition: all 0.2s;
  border: 2.5px solid transparent;

  &.active {
    border-color: var(--primary);
    box-shadow: 0 3px 14px rgba(255,107,53,0.25);
    transform: scale(1.02);
  }
}
.thumb-card-img-wrap {
  position: relative;
  aspect-ratio: 16 / 9;
  overflow: hidden;
  background: #F0EDE8;
}
.thumb-card-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
.thumb-card-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
}
.thumb-card-badge {
  position: absolute;
  top: 4px; left: 4px;
  background: rgba(0,0,0,0.5);
  color: #fff;
  font-size: 9px;
  font-weight: 700;
  padding: 2px 8px;
  border-radius: 10px;
}
.thumb-card-text {
  padding: 6px 8px;
  font-size: 11px;
  color: #64748B;
  line-height: 1.4;
  min-height: 20px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}


@keyframes pulse {
  0%, 100% { transform: scale(1); }
  50% { transform: scale(1.08); }
}
</style>
