<script lang="ts">
export default { name: 'WelcomeView' }
</script>
<template>
  <div class="welcome-page">
    <!-- Hero -->
    <section class="hero">
      <div class="hero-deco">
        <thunderbolt-outlined class="deco deco-1" />
        <star-outlined class="deco deco-2" />
        <star-outlined class="deco deco-3" />
      </div>
      <div class="hero-icon">
        <book-outlined />
      </div>
      <h1 class="hero-title">AI 绘本创作</h1>
      <p class="hero-sub">把你的画变成会讲故事的绘本</p>
    </section>

    <!-- 创作流程 -->
    <section class="card steps-card">
      <h2 class="card-title">创作流程</h2>
      <div class="steps">
        <div class="step">
          <div class="step-left">
            <div class="step-num">1</div>
            <div class="step-line" />
          </div>
          <div class="step-right">
            <div class="step-head">
              <camera-outlined class="step-icon" />
              <span class="step-title">拍照上传</span>
            </div>
            <div class="step-desc">拍下你的画作</div>
          </div>
        </div>
        <div class="step">
          <div class="step-left">
            <div class="step-num">2</div>
            <div class="step-line" />
          </div>
          <div class="step-right">
            <div class="step-head">
              <smile-outlined class="step-icon" />
              <span class="step-title">角色提取</span>
            </div>
            <div class="step-desc">AI 智能识别画中角色</div>
          </div>
        </div>
        <div class="step">
          <div class="step-left">
            <div class="step-num">3</div>
            <div class="step-line" />
          </div>
          <div class="step-right">
            <div class="step-head">
              <edit-outlined class="step-icon" />
              <span class="step-title">编排故事</span>
            </div>
            <div class="step-desc">起书名、定主角、填故事要素</div>
          </div>
        </div>
        <div class="step">
          <div class="step-left">
            <div class="step-num">4</div>
            <div class="step-line" />
          </div>
          <div class="step-right">
            <div class="step-head">
              <bg-colors-outlined class="step-icon" />
              <span class="step-title">选择画风</span>
            </div>
            <div class="step-desc">水墨、3D 等多种风格</div>
          </div>
        </div>
        <div class="step">
          <div class="step-left">
            <div class="step-num">5</div>
            <div class="step-line" />
          </div>
          <div class="step-right">
            <div class="step-head">
              <thunderbolt-outlined class="step-icon" />
              <span class="step-title">AI 生成</span>
            </div>
            <div class="step-desc">一键生成完整绘本</div>
          </div>
        </div>
        <div class="step">
          <div class="step-left">
            <div class="step-num">6</div>
            <div class="step-line" />
          </div>
          <div class="step-right">
            <div class="step-head">
              <eye-outlined class="step-icon" />
              <span class="step-title">预览编目</span>
            </div>
            <div class="step-desc">浏览成果，补充作者署名</div>
          </div>
        </div>
        <div class="step">
          <div class="step-left">
            <div class="step-num">7</div>
          </div>
          <div class="step-right">
            <div class="step-head">
              <sound-outlined class="step-icon" />
              <span class="step-title">配音发布</span>
              <span class="step-tag">可选</span>
            </div>
            <div class="step-desc">AI 配音或亲自录音</div>
          </div>
        </div>
      </div>
    </section>

    <!-- 底部固定 CTA -->
    <div class="cta-fab">
      <button class="cta-btn" @click="handleStart">
        <rocket-outlined />
        <span>开始创作</span>
      </button>
      <p class="slogan">你的画作，会讲故事</p>
    </div>
  </div>
</template>

<script setup lang="ts">
import { createVNode, onMounted, onActivated, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import {
  CameraOutlined,
  SmileOutlined,
  BgColorsOutlined,
  EditOutlined,
  ThunderboltOutlined,
  EyeOutlined,
  SoundOutlined,
  BookOutlined,
  RocketOutlined,
  StarOutlined,
  ExclamationCircleOutlined,
} from '@ant-design/icons-vue'
import { Modal } from 'ant-design-vue'
import { useAicreateStore } from '@/stores/aicreate'
import { loadExtractDraft } from '@/utils/aicreate/extractDraft'
import { resumeLeaiWorkFromApi } from '@/utils/aicreate/resumeLeaiWork'

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

/** 作品库「编辑」传入的 resumeWorkId（query 可能已解码，容错二次 decode） */
function parseResumeWorkIdFromQuery(raw: string): string {
  const t = String(raw || '').trim()
  if (!t) return ''
  try {
    return decodeURIComponent(t)
  } catch {
    return t
  }
}

function getResumeWorkIdFromRoute(): string {
  const qResume = route.query.resumeWorkId
  const resumeFromQuery =
    typeof qResume === 'string'
      ? qResume
      : Array.isArray(qResume) && qResume[0]
        ? qResume[0]
        : ''
  return resumeFromQuery ? String(resumeFromQuery) : ''
}

/** 欢迎页恢复逻辑：与 keep-alive 配合，onMounted 仅首次；再次进入需 onActivated + watch */
let welcomeResumeRunning = false

async function runWelcomeEntry() {
  if (route.name !== 'PublicCreateWelcome') return
  if (welcomeResumeRunning) return
  welcomeResumeRunning = true

  try {
    const resumeFromQuery = getResumeWorkIdFromRoute()

    // 1) 作品库 ?resumeWorkId= 优先于短会话 recovery，避免错跳；无 token 时等待壳层/ watch 再试
    if (resumeFromQuery) {
      if (!store.sessionToken) {
        return
      }
      const decoded = parseResumeWorkIdFromQuery(resumeFromQuery)
      if (!decoded) {
        await router.replace({ name: 'PublicCreateWelcome', query: {} })
      } else {
        const ok = await resumeLeaiWorkFromApi(decoded, router, store)
        if (ok) return
        await router.replace({ name: 'PublicCreateWelcome', query: {} })
      }
    }

    // 2) 短会话恢复（Tab 切换等）
    const recovery = store.restoreRecoveryState()
    if (recovery && recovery.path && recovery.path !== '/') {
      const newPath = '/p/create' + recovery.path
      router.push(newPath)
      return
    }

    // 3) 本地 le_workId：乐读派已生成作品，按状态继续
    const storedWid = localStorage.getItem('le_workId')
    if (storedWid && store.sessionToken) {
      const ok = await resumeLeaiWorkFromApi(storedWid, router, store)
      if (ok) return
    }

    // 4) 角色提取草稿（10 天内）：继续到选角页
    const draft = loadExtractDraft()
    if (draft && store.sessionToken) {
      store.imageUrl = draft.imageUrl
      store.extractId = draft.extractId
      store.characters = draft.characters
      store.selectedCharacter = null
      store.storyData = null
      store.selectedStyle = ''
      store.workId = ''
      store.workDetail = null
      localStorage.removeItem('le_workId')
      router.replace('/p/create/characters')
    }
  } finally {
    welcomeResumeRunning = false
  }
}

onMounted(() => {
  void runWelcomeEntry()
})

onActivated(() => {
  void runWelcomeEntry()
})

watch(
  () => [store.sessionToken, route.query.resumeWorkId] as const,
  () => {
    void runWelcomeEntry()
  },
)

const handleStart = () => {
  if (!store.sessionToken) return
  store.reset()

  // Modal.warning 为单按钮提示，不展示取消；需双按钮时用 confirm + 警告图标
  Modal.confirm({
    title: '温馨提示',
    icon: createVNode(ExclamationCircleOutlined),
    content:
      '本次 AI 绘本创作体验功能，仅面向 “智创未来” 广东省 AI 绘本创作活动参与者开放，每个手机号可使用两次。',
    okText: '我知道了',
    cancelText: '取消',
    centered: true,
    wrapClassName: 'welcome-tip-modal',
    onOk() {
      router.push('/p/create/upload')
    },
  })
}
</script>

<style lang="scss" scoped>
$primary: #6366f1;
$accent: #ec4899;
$text-strong: #1e1b4b;
$text: #4b5563;
$text-muted: #9ca3af;
$gradient: linear-gradient(135deg, #6366f1 0%, #8b5cf6 50%, #ec4899 100%);

.welcome-page {
  padding: 16px 16px 140px; // 底部留位给浮动 CTA
  display: flex;
  flex-direction: column;
  gap: 16px;
}

/* ---------- Hero ---------- */
.hero {
  position: relative;
  padding: 28px 24px;
  border-radius: 20px;
  background: $gradient;
  color: #fff;
  text-align: center;
  overflow: hidden;
  box-shadow: 0 12px 32px rgba(99, 102, 241, 0.22);
}

.hero-deco {
  position: absolute;
  inset: 0;
  pointer-events: none;

  .deco {
    position: absolute;
    color: rgba(255, 255, 255, 0.4);
  }

  .deco-1 {
    top: 14px;
    right: 18px;
    font-size: 22px;
  }

  .deco-2 {
    top: 18px;
    left: 22px;
    font-size: 14px;
  }

  .deco-3 {
    bottom: 18px;
    right: 30%;
    font-size: 12px;
  }
}

.hero-icon {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 56px;
  height: 56px;
  border-radius: 16px;
  background: rgba(255, 255, 255, 0.22);
  backdrop-filter: blur(8px);
  font-size: 28px;
  color: #fff;
  margin-bottom: 12px;
}

.hero-title {
  margin: 0;
  font-size: 24px;
  font-weight: 800;
  letter-spacing: 2px;
}

.hero-sub {
  margin: 6px 0 0;
  font-size: 13px;
  opacity: 0.92;
  font-weight: 500;
}

/* ---------- 通用卡片 ---------- */
.card {
  background: #fff;
  border-radius: 16px;
  padding: 18px;
  border: 1px solid rgba(99, 102, 241, 0.06);
  box-shadow: 0 2px 12px rgba(99, 102, 241, 0.05);
}

.card-title {
  margin: 0 0 14px;
  font-size: 15px;
  font-weight: 700;
  color: $text-strong;
}

/* ---------- 创作流程 ---------- */
.steps {
  display: flex;
  flex-direction: column;
}

.step {
  display: flex;
  gap: 12px;
}

.step-left {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 28px;
  flex-shrink: 0;
}

.step-num {
  width: 28px;
  height: 28px;
  border-radius: 50%;
  background: $gradient;
  color: #fff;
  font-size: 13px;
  font-weight: 700;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4px 10px rgba(99, 102, 241, 0.25);
}

.step-line {
  flex: 1;
  width: 2px;
  min-height: 14px;
  background: linear-gradient(180deg, rgba(99, 102, 241, 0.35), rgba(236, 72, 153, 0.18));
  margin: 4px 0;
}

.step-right {
  flex: 1;
  padding-bottom: 14px;
}

.step:last-child .step-right {
  padding-bottom: 0;
}

.step-head {
  display: flex;
  align-items: center;
  gap: 6px;
  flex-wrap: wrap;
}

.step-icon {
  color: $primary;
  font-size: 15px;
}

.step-title {
  font-size: 14px;
  font-weight: 700;
  color: $text-strong;
}

.step-tag {
  font-size: 10px;
  font-weight: 600;
  color: $primary;
  background: rgba(99, 102, 241, 0.1);
  border-radius: 8px;
  padding: 1px 6px;
  letter-spacing: 0.5px;
}

.step-desc {
  font-size: 12px;
  color: $text-muted;
  margin-top: 2px;
}

/* ---------- 浮动 CTA ---------- */
.cta-fab {
  position: fixed;
  left: 50%;
  transform: translateX(-50%);
  width: calc(100% - 32px);
  max-width: 398px;
  z-index: 50;
  text-align: center;
  pointer-events: none; // 让蒙版区域不挡内容滚动

  // 移动端：tabbar 上方
  bottom: calc(64px + env(safe-area-inset-bottom));

  // 桌面端：tabbar 隐藏，离底 24px
  @media (min-width: 768px) {
    bottom: 24px;
  }
}

.cta-btn {
  pointer-events: auto;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  width: 100%;
  padding: 14px 0;
  border: none;
  border-radius: 28px;
  background: $gradient;
  color: #fff;
  font-size: 16px;
  font-weight: 700;
  letter-spacing: 2px;
  cursor: pointer;
  box-shadow: 0 8px 24px rgba(99, 102, 241, 0.38);
  transition: all 0.2s;

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

  &:hover {
    transform: translateY(-1px);
    box-shadow: 0 10px 28px rgba(99, 102, 241, 0.44);
  }

  &:active {
    transform: scale(0.98);
    opacity: 0.95;
  }

  &--disabled {
    background: #e5e7eb;
    color: #9ca3af;
    box-shadow: none;
    cursor: not-allowed;

    &:hover {
      transform: none;
      box-shadow: none;
    }
  }
}

.slogan {
  pointer-events: auto;
  margin: 8px 0 0;
  font-size: 12px;
  color: $primary;
  font-weight: 600;
  letter-spacing: 1px;
  text-shadow: 0 1px 4px rgba(248, 247, 252, 0.9);
}
</style>

<style lang="scss">
/* Modal.confirm 挂载在 body，需非 scoped */
.welcome-tip-modal {
  // .ant-modal-confirm-body-wrapper {
  //   display: flex;
  //   flex-direction: column;
  //   align-items: center; 
  // }

  // .ant-modal-confirm-body {
  //   display: flex;
  //   flex-direction: column;
  //   align-items: center;
  //   text-align: center;
  // }

  // .ant-modal-confirm-body > .anticon {
  //   margin-inline-end: 0 !important;
  //   margin-bottom: 4px;
  //   font-size: 22px;
  // }

  .ant-modal-confirm-title {
    display: block;
    width: 100%;
  }

  .ant-modal-confirm-content {
    margin-top: 8px;
  }

  .ant-modal-confirm-btns {
    display: flex;
    justify-content: center;
    width: 100%;
    margin-top: 8px;
  }
}
</style>
