<template>
  <div class="welcome-page">
    <!-- Hero（紧凑版） -->
    <div class="hero-compact">
      <div class="hero-bg-deco d1">⭐</div>
      <div class="hero-bg-deco d2">🌈</div>
      <div class="hero-bg-deco d3">✨</div>
      <div class="hero-row">
        <div class="hero-books">
          <span v-for="(b, i) in ['📕','📗','📘','📙']" :key="i" class="book-icon">{{ b }}</span>
        </div>
        <div class="hero-text">
          <div class="hero-title">{{ brandTitle }}</div>
          <div class="hero-sub">{{ brandSubtitle }}</div>
        </div>
      </div>
      <div class="hero-tag">✨ 拍一张画，AI帮你变成绘本</div>
    </div>

    <!-- 主内容区（flex:1 撑满中间） -->
    <div class="main-area">
      <!-- 流程步骤（垂直时间线） -->
      <div class="steps-card">
        <div class="steps-header">🎯 创作流程</div>
        <div class="steps-timeline">
          <div v-for="(s, i) in steps" :key="i" class="step-item">
            <div class="step-left">
              <div class="step-num" :style="{ background: s.color }">{{ i + 1 }}</div>
              <div v-if="i < steps.length - 1" class="step-line" :style="{ background: s.color + '40' }" />
            </div>
            <div class="step-right">
              <div class="step-head">
                <span class="step-emoji">{{ s.emoji }}</span>
                <span class="step-title">{{ s.title }}</span>
              </div>
              <div class="step-desc">{{ s.desc }}</div>
            </div>
          </div>
        </div>
      </div>

      <!-- 特色标签 -->
      <div class="features-row">
        <div class="feature-tag">🎨 AI绘画</div>
        <div class="feature-tag">📖 自动排版</div>
        <div class="feature-tag">🔊 语音配音</div>
        <div class="feature-tag">🎤 人工配音</div>
      </div>

      <!-- 亮点描述 -->
      <div class="highlights">
        <div class="hl-item">
          <span class="hl-icon">🖌️</span>
          <span class="hl-text">上传孩子的画作，AI 自动识别角色</span>
        </div>
        <div class="hl-item">
          <span class="hl-icon">📖</span>
          <span class="hl-text">一键生成多页精美绘本故事</span>
        </div>
        <div class="hl-item">
          <span class="hl-icon">🔊</span>
          <span class="hl-text">AI 配音或亲自录音，让故事活起来</span>
        </div>
      </div>
    </div>

    <!-- 底部（固定） -->
    <div class="bottom-area safe-bottom">
      <!-- Token模式无token时 -->
      <template v-if="isTokenMode && !store.sessionToken">
        <div class="auth-prompt" style="text-align:center;padding:20px;">
          <p style="font-size:16px;color:#666;margin-bottom:8px;">本应用需要通过企业入口访问</p>
          <p style="font-size:14px;color:#999;margin-bottom:20px;">请联系您的管理员获取访问链接</p>
          <button v-if="store.authRedirectUrl" class="btn-primary start-btn" @click="goToEnterprise">
            <span class="btn-icon">🔑</span> 前往企业认证
          </button>
        </div>
      </template>
      <!-- 有token或HMAC模式 -->
      <template v-else>
        <button class="btn-primary start-btn" @click="handleStart">
          <span class="btn-icon">🚀</span> 开始创作
        </button>
      </template>
      <div class="slogan">让每个孩子都是小画家 ✨</div>
    </div>
  </div>
</template>

<script setup>
import { onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { store } from '@/utils/store'
import config from '@/utils/config'
import bridge from '@/utils/bridge'
import { getOrgConfig } from '@/api/index'

const router = useRouter()

const steps = [
  { emoji: '📸', title: '拍照上传', desc: '拍下孩子的画作', color: '#FF6B35' },
  { emoji: '🎭', title: '角色提取', desc: 'AI智能识别角色', color: '#6C63FF' },
  { emoji: '✏️', title: '编排故事', desc: '选画风填要素', color: '#2EC4B6' },
  { emoji: '📖', title: '绘本创作', desc: 'AI生成完整绘本', color: '#FFD166' },
]

// 从 URL 读取会话令牌（企业重定向入口: ?token=sess_xxx&phone=138xxx&orgId=ORG001）
onMounted(async () => {
  // 双来源参数解析：search（iframe src）+ hash（hash路由）
  const searchParams = new URLSearchParams(window.location.search)
  const hashQuery = window.location.hash.split('?')[1] || ''
  const hashParams = new URLSearchParams(hashQuery)
  const urlToken = searchParams.get('token') || hashParams.get('token')
  const urlOrgId = searchParams.get('orgId') || hashParams.get('orgId')
  const urlPhone = searchParams.get('phone') || hashParams.get('phone')
  const urlReturnPath = searchParams.get('returnPath') || hashParams.get('returnPath')

  if (urlToken) {
    if (!urlOrgId) {
      console.error('[Welcome] URL缺少orgId参数')
      alert('入口链接缺少机构信息(orgId)，请联系管理员')
      return
    }
    store.setSession(urlOrgId, urlToken)
    if (urlPhone) store.setPhone(urlPhone)
    // 清理URL中的token参数（安全）
    window.history.replaceState({}, '', window.location.pathname + '#/')

    // 检查恢复状态
    const recovery = store.restoreRecoveryState()
    const targetPath = urlReturnPath || (recovery ? recovery.path : null)
    if (targetPath && targetPath !== '/') {
      router.push(targetPath)
      return
    }
  } else {
    // 清理URL参数（即使没有token也清理）
    if (hashQuery) {
      window.history.replaceState({}, '', window.location.pathname + '#/')
    }
  }

  // Token模式下无token：尝试获取企业认证URL
  if (config.isTokenMode && !store.sessionToken) {
    // iframe 模式：请求父页面提供 token
    if (bridge.isEmbedded) {
      try {
        const data = await bridge.requestTokenRefresh()
        if (data?.token) {
          store.setSession(data.orgId || '', data.token)
          if (data.phone) store.setPhone(data.phone)
          router.push('/upload')
          return
        }
      } catch { /* 超时：继续显示提示 */ }
    }
    // standalone模式或iframe超时：获取企业认证URL
    const savedOrgId = sessionStorage.getItem('le_orgId') || urlOrgId
    if (savedOrgId) {
      try {
        const res = await getOrgConfig(savedOrgId)
        if (res?.data?.authRedirectUrl) {
          store.authRedirectUrl = res.data.authRedirectUrl
        }
      } catch { /* ignore - will show text-only prompt */ }
    }
  }
})

const handleStart = () => {
  if (config.isTokenMode) {
    if (!store.sessionToken) return
  } else {
    if (!store.phone && config.dev?.phone) store.setPhone(config.dev.phone)
    if (!store.sessionToken && !store.appSecret && config.dev) {
      store.setOrg(config.dev.orgId, config.dev.appSecret)
    }
  }
  store.reset()
  router.push('/upload')
}

const goToEnterprise = () => {
  window.location.href = store.authRedirectUrl
}

const brandTitle = config.brand.title || '乐读派'
const brandSubtitle = config.brand.subtitle || 'AI智能儿童绘本创作'

// expose config to template for v-if usage
const isTokenMode = config.isTokenMode
</script>

<style lang="scss" scoped>
.welcome-page {
  height: 100vh;
  background: linear-gradient(180deg, #FFF8E7 0%, #FFF3E0 30%, #FFF0F0 60%, #FFFDF7 100%);
  display: flex;
  flex-direction: column;
  position: relative;
  overflow: hidden;
}

/* ---- Hero 紧凑版 ---- */
.hero-compact {
  background: linear-gradient(135deg, #FF6B35 0%, #FF8F65 40%, #FFB088 70%, #FFCBA4 100%);
  border-radius: 0 0 32px 32px;
  padding: 40px 20px 18px;
  text-align: center;
  position: relative;
  overflow: hidden;
  flex-shrink: 0;
}
.hero-bg-deco {
  position: absolute;
  opacity: 0.18;
  pointer-events: none;
  animation: twinkle 3s ease-in-out infinite;
  &.d1 { top: 10px; left: 16px; font-size: 20px; }
  &.d2 { top: 16px; right: 20px; font-size: 18px; animation-delay: 0.8s; }
  &.d3 { bottom: 10px; right: 30%; font-size: 16px; animation-delay: 1.5s; }
}
@keyframes twinkle {
  0%, 100% { transform: scale(1) rotate(0deg); opacity: 0.18; }
  50% { transform: scale(1.15) rotate(8deg); opacity: 0.35; }
}
.hero-row {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 14px;
}
.hero-books {
  display: flex;
  gap: 4px;
}
.book-icon {
  font-size: 26px;
  filter: drop-shadow(0 2px 4px rgba(0,0,0,0.15));
  animation: bookBounce 2.5s ease-in-out infinite;
  &:nth-child(2) { animation-delay: 0.3s; }
  &:nth-child(3) { animation-delay: 0.6s; }
  &:nth-child(4) { animation-delay: 0.9s; }
}
@keyframes bookBounce {
  0%, 100% { transform: translateY(0); }
  50% { transform: translateY(-5px); }
}
.hero-text { text-align: left; }
.hero-title {
  font-size: 28px;
  font-weight: 900;
  color: #fff;
  letter-spacing: 3px;
  text-shadow: 0 2px 8px rgba(0,0,0,0.18);
}
.hero-sub {
  font-size: 13px;
  color: rgba(255,255,255,0.9);
  margin-top: 2px;
  letter-spacing: 1.5px;
  font-weight: 500;
}
.hero-tag {
  margin-top: 10px;
  display: inline-flex;
  align-items: center;
  gap: 4px;
  background: rgba(255,255,255,0.22);
  border-radius: 20px;
  padding: 5px 16px;
  font-size: 12px;
  color: #fff;
  backdrop-filter: blur(8px);
  font-weight: 600;
}

/* ---- 主内容区 ---- */
.main-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-evenly;
  padding: 10px 16px 0;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
}

/* 流程步骤（垂直时间线） */
.steps-card {
  background: rgba(255,255,255,0.92);
  border-radius: 16px;
  padding: 12px 14px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.05);
}
.steps-header {
  font-size: 15px;
  font-weight: 800;
  color: #333;
  margin-bottom: 8px;
}
.steps-timeline { display: flex; flex-direction: column; }
.step-item {
  display: flex;
  align-items: flex-start;
  gap: 12px;
}
.step-left {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 32px;
  flex-shrink: 0;
}
.step-num {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  font-size: 13px;
  font-weight: 800;
  box-shadow: 0 2px 8px rgba(0,0,0,0.15);
}
.step-line {
  width: 3px;
  height: 12px;
  border-radius: 2px;
  margin: 3px 0;
}
.step-right { padding-top: 4px; }
.step-head {
  display: flex;
  align-items: center;
  gap: 6px;
}
.step-emoji { font-size: 18px; }
.step-title { font-size: 14px; font-weight: 800; color: #333; }
.step-desc { font-size: 11px; color: #999; margin-top: 1px; padding-left: 24px; }

/* 特色标签 */
.features-row {
  display: flex;
  gap: 6px;
  justify-content: center;
  margin-bottom: 12px;
  flex-wrap: nowrap;
}
.feature-tag {
  background: rgba(255,255,255,0.85);
  border: 1.5px solid #FFE4D0;
  border-radius: 20px;
  padding: 4px 10px;
  font-size: 11px;
  font-weight: 600;
  color: var(--primary, #FF6B35);
  white-space: nowrap;
}

/* 亮点描述 */
.highlights {
  background: rgba(255,255,255,0.88);
  border-radius: 16px;
  padding: 12px 14px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.04);
}
.hl-item {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 6px 0;
  &:not(:last-child) { border-bottom: 1px dashed #FFE4D0; }
}
.hl-icon { font-size: 20px; flex-shrink: 0; }
.hl-text {
  font-size: 13px;
  color: #555;
  font-weight: 500;
  line-height: 1.4;
}

/* ---- 底部固定区 ---- */
.bottom-area {
  flex-shrink: 0;
  padding: 12px 16px 8px;
}
.start-btn {
  display: flex !important;
  align-items: center;
  justify-content: center;
  gap: 8px;
  width: 100%;
  padding: 16px 0 !important;
  font-size: 18px !important;
  border-radius: 28px !important;
  background: linear-gradient(135deg, #FF8C42, #FF6B35, #FF5722) !important;
  box-shadow: 0 6px 24px rgba(255,107,53,0.35) !important;
  letter-spacing: 2px;
  border: none;
  color: #fff;
  font-weight: 700;
  cursor: pointer;
  &:active { transform: scale(0.98); opacity: 0.9; }
}
.btn-icon { font-size: 20px; }
.slogan {
  text-align: center;
  font-size: 12px;
  color: var(--primary, #FF6B35);
  font-weight: 600;
  margin-top: 8px;
  letter-spacing: 1px;
}
</style>
