<script lang="ts">
export default { name: 'PreviewView' }
</script>
<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">
      <loading-outlined class="loading-icon" spin />
      <div class="loading-text">加载中…</div>
    </div>

    <!-- 加载失败 -->
    <div v-else-if="error" class="error-state">
      <frown-outlined class="error-icon" />
      <div class="error-title">加载失败</div>
      <div class="error-msg">{{ error }}</div>
      <button class="btn-primary error-btn" @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" :alt="pageBadge" />
          <div v-else class="page-image placeholder-img">
            <picture-outlined />
          </div>
        </div>

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

        <!-- 3. 翻页 -->
        <div class="nav-row">
          <button class="nav-btn" :class="{ invisible: idx <= 0 }" @click="prev" aria-label="上一页">
            <left-outlined />
          </button>
          <span class="page-counter">{{ idx + 1 }} / {{ pages.length }}</span>
          <button class="nav-btn" :class="{ invisible: idx >= pages.length - 1 }" @click="next" aria-label="下一页">
            <right-outlined />
          </button>
        </div>

        <!-- 4. 缩略图横向胶卷 -->
        <div class="thumb-strip" ref="thumbStrip">
          <div v-for="(p, i) in pages" :key="i" class="thumb-item" :class="{ active: i === idx }" @click="idx = i">
            <img v-if="p.imageUrl" :src="p.imageUrl" class="thumb-img" />
            <div v-else class="thumb-placeholder">
              <picture-outlined />
            </div>
            <div class="thumb-num">{{ i === 0 ? '封面' : i }}</div>
          </div>
        </div>
      </div>

      <!-- 底部按钮 -->
      <div class="page-bottom">
        <button class="btn-primary next-btn" @click="goEditInfo">
          <span>下一步：编辑绘本信息</span>
          <arrow-right-outlined />
        </button>
      </div>
    </template>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onActivated, nextTick } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import {
  LoadingOutlined,
  FrownOutlined,
  PictureOutlined,
  LeftOutlined,
  RightOutlined,
  ArrowRightOutlined,
} from '@ant-design/icons-vue'
import { getWorkDetail } from '@/api/aicreate'
import { useAicreateStore } from '@/stores/aicreate'
import { STATUS, getRouteByStatus } from '@/utils/aicreate/status'

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

const loading = ref(true)
const error = ref('')
const pages = ref<any[]>([])
const idx = ref(0)
const thumbStrip = ref<HTMLElement | null>(null)

// 触屏滑动翻页
let touchX = 0
const onTouchStart = (e: TouchEvent) => { touchX = e.touches[0].clientX }
const onTouchEnd = (e: TouchEvent) => {
  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(() => idx.value === 0 ? '封面' : `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: number) {
  nextTick(() => {
    const el = thumbStrip.value?.children[i] as HTMLElement | undefined
    if (el) el.scrollIntoView({ behavior: 'smooth', inline: 'center', block: 'nearest' })
  })
}

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

async function loadWork() {
  loading.value = true
  error.value = ''

  if (!workId.value) {
    error.value = '缺少作品信息'
    loading.value = false
    return
  }

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

    pages.value = work.pageList || [];

  } catch (e: any) {
    error.value = e.message || '加载失败'
  } finally {
    loading.value = false
  }
}

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

onActivated(loadWork)
</script>

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

/* ---------- 顶部 ---------- */
.top-bar {
  background: var(--ai-gradient);
  padding: 22px 22px 18px;
  color: #fff;
  text-align: center;
  box-shadow: 0 6px 20px rgba(99, 102, 241, 0.18);
}

.top-title {
  font-size: 20px;
  font-weight: 800;
  letter-spacing: 1px;
}

.top-sub {
  font-size: 13px;
  opacity: 0.92;
  margin-top: 4px;
  font-weight: 500;
}

/* ---------- 加载/错误状态 ---------- */
.loading-state,
.error-state {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 24px;
}

.loading-icon {
  font-size: 44px;
  color: var(--ai-primary);
  margin-bottom: 14px;
}

.loading-text {
  color: var(--ai-text-sub);
  font-size: 14px;
}

.error-icon {
  font-size: 48px;
  color: var(--ai-text-sub);
  margin-bottom: 14px;
}

.error-title {
  font-size: 16px;
  font-weight: 700;
  color: var(--ai-text);
  margin-bottom: 6px;
}

.error-msg {
  color: var(--ai-text-sub);
  font-size: 13px;
  margin-bottom: 18px;
  text-align: center;
  max-width: 280px;
}

.error-btn {
  width: auto !important;
  padding: 10px 32px !important;
  font-size: 14px !important;
}

/* ---------- 主内容 ---------- */
.content {
  padding: 16px 16px 14px;
  flex: 1;
  overflow-y: auto;
}

/* 图片区 */
.image-section {
  position: relative;
  border-radius: 18px;
  overflow: hidden;
  background: #1e1b4b;
  /* 深紫黑底，电影画幅感 */
  box-shadow: 0 8px 28px rgba(99, 102, 241, 0.2);
}

.page-image {
  width: 100%;
  display: block;
  object-fit: contain;
  aspect-ratio: 16 / 9;
  background: #1e1b4b;
}

.placeholder-img {
  aspect-ratio: 16 / 9;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 56px;
  color: rgba(255, 255, 255, 0.3);
  background: #1e1b4b;
}

.page-badge {
  position: absolute;
  top: 12px;
  left: 12px;
  background: var(--ai-gradient);
  color: #fff;
  font-size: 11px;
  font-weight: 700;
  padding: 4px 14px;
  border-radius: 20px;
  z-index: 2;
  box-shadow: 0 4px 12px rgba(99, 102, 241, 0.4);
  letter-spacing: 0.5px;
}

/* 故事文字区 */
.text-section {
  background: #fff;
  border: 1px solid rgba(99, 102, 241, 0.08);
  border-top: none;
  border-radius: 0 0 18px 18px;
  margin-top: -8px;
  padding: 18px 22px 16px;
  position: relative;
  box-shadow: 0 4px 16px rgba(99, 102, 241, 0.06);
  min-height: 64px;
}

.story-text {
  font-size: 15px;
  line-height: 1.8;
  color: var(--ai-text);
  font-weight: 500;
}

/* 翻页 */
.nav-row {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 22px;
  margin-top: 18px;
}

.nav-btn {
  width: 38px;
  height: 38px;
  border-radius: 50%;
  border: 1px solid rgba(99, 102, 241, 0.18);
  background: #fff;
  box-shadow: 0 2px 10px rgba(99, 102, 241, 0.1);
  font-size: 16px;
  color: var(--ai-primary);
  cursor: pointer;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s;

  &:hover {
    border-color: var(--ai-primary);
    background: rgba(99, 102, 241, 0.04);
  }

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

  &.invisible {
    opacity: 0;
    pointer-events: none;
  }
}

.page-counter {
  font-size: 12px;
  color: var(--ai-text-sub);
  font-weight: 600;
  letter-spacing: 0.5px;
}

/* ---------- 横向胶卷缩略图 ---------- */
.thumb-strip {
  display: flex;
  gap: 10px;
  padding: 18px 4px 8px;
  overflow-x: auto;
  overflow-y: hidden;
  scroll-snap-type: x proximity;
  scroll-padding: 0 50%;

  /* 隐藏滚动条 */
  scrollbar-width: none;
  -ms-overflow-style: none;

  &::-webkit-scrollbar {
    display: none;
  }
}

.thumb-item {
  position: relative;
  flex-shrink: 0;
  width: 88px;
  aspect-ratio: 16 / 9;
  border-radius: 10px;
  overflow: hidden;
  cursor: pointer;
  border: 2px solid transparent;
  background: #1e1b4b;
  box-shadow: 0 2px 10px rgba(99, 102, 241, 0.08);
  transition: all 0.25s ease;
  scroll-snap-align: center;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 14px rgba(99, 102, 241, 0.18);
  }

  &.active {
    border-color: var(--ai-primary);
    transform: translateY(-3px) scale(1.06);
    box-shadow: 0 8px 22px rgba(99, 102, 241, 0.36);
    z-index: 1;
  }
}

.thumb-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  display: block;
}

.thumb-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 22px;
  color: rgba(255, 255, 255, 0.3);
}

.thumb-num {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 8px 4px 3px;
  background: linear-gradient(to top, rgba(15, 12, 41, 0.85), transparent);
  color: #fff;
  font-size: 10px;
  font-weight: 700;
  text-align: center;
  letter-spacing: 0.5px;
  line-height: 1;
}

/* ---------- 底部按钮 ---------- */
.next-btn {
  display: flex !important;
  align-items: center;
  justify-content: center;
  gap: 8px;
  font-size: 16px !important;
  padding: 14px 0 !important;
  border-radius: 28px !important;

  :deep(.anticon) {
    font-size: 16px;
  }
}
</style>
