<template>
  <div class="char-page page-fullscreen">
    <PageHeader title="选择主角" subtitle="AI已识别画中角色，请选择绘本主角" :step="1" />

    <div class="content page-content">
      <!-- 加载中 -->
      <div v-if="loading" class="loading-state">
        <div class="loading-emojis">
          <span class="loading-emoji e1">🔍</span>
          <span class="loading-emoji e2">🎨</span>
          <span class="loading-emoji e3">✨</span>
        </div>
        <div class="loading-title">AI正在识别角色...</div>
        <div class="loading-sub">通常需要 10-20 秒</div>
        <div class="progress-bar"><div class="progress-fill" /></div>
      </div>

      <!-- 错误状态 -->
      <template v-else-if="error">
        <div class="error-state">
          <div class="error-emoji">😔</div>
          <div class="error-text">{{ error }}</div>
          <button class="btn-ghost" style="max-width:200px;margin-top:20px" @click="$router.back()">返回重新上传</button>
        </div>
      </template>

      <template v-else>
        <div class="result-tip">
          <span class="result-icon">🎉</span>
          <span>发现 <strong>{{ characters.length }}</strong> 个角色！点击选择绘本主角</span>
        </div>

        <div class="char-list">
          <div
            v-for="c in characters"
            :key="c.charId"
            class="char-card"
            :class="{ selected: selected === c.charId }"
            @click="selected = c.charId"
          >
            <!-- 选中星星装饰 -->
            <div v-if="selected === c.charId" class="selected-stars">
              <span class="star s1">⭐</span>
              <span class="star s2">✨</span>
              <span class="star s3">⭐</span>
            </div>

            <div class="char-avatar" @click.stop="c.originalCropUrl && (previewImg = c.originalCropUrl)">
              <img v-if="c.originalCropUrl" :src="c.originalCropUrl" class="char-img" />
              <div v-else class="char-placeholder">🎭</div>
            </div>
            <div class="char-info">
              <div class="char-name-row">
                <span class="char-name">{{ c.name }}</span>
                <span v-if="c.type === 'HERO'" class="hero-badge">⭐ 推荐主角</span>
              </div>
              <div class="char-hint">点击头像可放大查看</div>
            </div>
            <div class="check-badge" :class="{ checked: selected === c.charId }">
              <span v-if="selected === c.charId">✓</span>
            </div>
          </div>
        </div>

        <!-- 图片预览 -->
        <Transition name="fade">
          <div v-if="previewImg" class="preview-overlay" @click="previewImg = ''">
            <img :src="previewImg" class="preview-full-img" />
          </div>
        </Transition>

      </template>
    </div>
    <div class="page-bottom">
      <button class="btn-primary next-btn" :disabled="!selected" @click="goNext">
        确定主角，选画风 →
      </button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import PageHeader from '@/components/PageHeader.vue'
import { store } from '@/utils/store'
import { extractCharacters } from '@/api'

const router = useRouter()
const loading = ref(true)
const selected = ref(null)
const characters = ref([])
const error = ref('')
const previewImg = ref('')

onMounted(async () => {
  if (store.characters && store.characters.length > 0) {
    characters.value = store.characters
    // 自动选中推荐主角
    const hero = characters.value.find(c => c.type === 'HERO')
    if (hero) selected.value = hero.charId
    loading.value = false
    return
  }

  if (!store.imageUrl) {
    error.value = '未上传图片，请返回上传'
    loading.value = false
    return
  }
  try {
    const res = await extractCharacters(store.imageUrl)
    const data = res.data || {}
    characters.value = (data.characters || []).map(c => ({
      ...c,
      type: c.charType || c.type || 'SIDEKICK'
    }))
    if (characters.value.length === 0) {
      error.value = 'AI未识别到角色，请更换图片重试'
    }
    store.extractId = data.extractId || ''
    store.characters = characters.value
    const hero = characters.value.find(c => c.type === 'HERO')
    if (hero) selected.value = hero.charId
  } catch (e) {
    error.value = '角色识别失败：' + (e.message || '请检查网络')
  } finally {
    loading.value = false
  }
})

const goNext = () => {
  store.selectedCharacter = characters.value.find(c => c.charId === selected.value)
  router.push('/style')
}
</script>

<style lang="scss" scoped>
.char-page {
  min-height: 100vh;
  background: linear-gradient(180deg, #F0F4FF 0%, #F5F0FF 40%, #FFF5F8 70%, #FFFDF7 100%);
  display: flex;
  flex-direction: column;
}
.content { flex: 1; padding: 16px 20px; display: flex; flex-direction: column; }

// Loading
.loading-state {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}
.loading-emojis {
  display: flex;
  gap: 16px;
  margin-bottom: 16px;
}
.loading-emoji {
  font-size: 40px;
  display: inline-block;
  animation: emojiPop 1.8s ease-in-out infinite;
  &.e1 { animation-delay: 0s; }
  &.e2 { animation-delay: 0.4s; }
  &.e3 { animation-delay: 0.8s; }
}
@keyframes emojiPop {
  0%, 100% { transform: scale(1) rotate(0deg); opacity: 0.5; }
  50% { transform: scale(1.3) rotate(10deg); opacity: 1; }
}
.loading-title { font-size: 18px; font-weight: 700; margin-top: 4px; color: var(--text); }
.loading-sub { font-size: 14px; color: var(--text-sub); margin-top: 8px; }
.progress-bar { width: 220px; height: 6px; background: rgba(108,99,255,0.15); border-radius: 3px; margin-top: 20px; overflow: hidden; }
.progress-fill { width: 100%; height: 100%; background: linear-gradient(90deg, #6C63FF, #9B93FF); border-radius: 3px; animation: loading 2s ease-in-out infinite; }
@keyframes loading { 0%{transform:translateX(-100%)} 100%{transform:translateX(200%)} }

// Error
.error-state {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}
.error-emoji { font-size: 56px; }
.error-text { font-size: 16px; font-weight: 600; margin-top: 16px; color: var(--text); text-align: center; }

// Result tip
.result-tip {
  background: linear-gradient(135deg, #E8F5E9, #F1F8E9);
  border: 1.5px solid #C8E6C9;
  border-radius: 18px;
  padding: 14px 18px;
  margin-bottom: 16px;
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 15px;
  color: #2E7D32;
  font-weight: 600;
}
.result-icon { font-size: 22px; }

// Character list
.char-list {
  display: flex;
  flex-direction: column;
  gap: 14px;
}

.char-card {
  background: rgba(255,255,255,0.95);
  border-radius: 20px;
  padding: 16px 18px;
  display: flex;
  align-items: center;
  gap: 16px;
  border: 3px solid transparent;
  transition: all 0.3s ease;
  cursor: pointer;
  box-shadow: 0 4px 16px rgba(0,0,0,0.05);
  position: relative;
  overflow: visible;

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

  &.selected {
    border-color: var(--primary);
    background: linear-gradient(135deg, #FFF5F0 0%, #FFFAF7 50%, #FFF0F5 100%);
    box-shadow: 0 6px 24px rgba(255, 107, 53, 0.2);
    transform: scale(1.02);
  }
}

// 选中星星装饰
.selected-stars {
  position: absolute;
  top: -8px;
  right: -4px;
  display: flex;
  gap: 2px;
  pointer-events: none;
}
.star {
  font-size: 14px;
  animation: starPop 1.5s ease-in-out infinite;
  &.s1 { animation-delay: 0s; }
  &.s2 { animation-delay: 0.3s; font-size: 12px; }
  &.s3 { animation-delay: 0.6s; }
}
@keyframes starPop {
  0%, 100% { transform: scale(1); opacity: 0.6; }
  50% { transform: scale(1.3); opacity: 1; }
}

.char-avatar {
  width: 88px;
  height: 88px;
  border-radius: 20px;
  overflow: hidden;
  background: linear-gradient(135deg, #FFF5F0, #FFE8D6);
  flex-shrink: 0;
  box-shadow: 0 4px 12px rgba(0,0,0,0.08);
  cursor: zoom-in;
  transition: transform 0.2s;

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

.char-img {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.char-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 36px;
}

.char-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.char-name-row {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}

.char-name {
  font-size: 18px;
  font-weight: 800;
  color: var(--text);
}

.char-hint {
  font-size: 12px;
  color: var(--text-sub);
}

// Check badge (right side)
.check-badge {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  border: 2.5px solid #E2E8F0;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
  color: #fff;
  flex-shrink: 0;
  transition: all 0.3s;

  &.checked {
    background: linear-gradient(135deg, #FF8C42, #FF6B35);
    border-color: var(--primary);
    box-shadow: 0 3px 10px rgba(255, 107, 53, 0.4);
    transform: scale(1.1);
  }
}

.hero-badge {
  font-size: 11px;
  background: linear-gradient(135deg, #FFD166, #FFBE4A);
  color: #fff;
  padding: 3px 10px;
  border-radius: 12px;
  font-weight: 700;
  box-shadow: 0 2px 6px rgba(255,209,102,0.3);
}

.bottom-area { margin-top: auto; padding-top: 20px; }

.next-btn {
  font-size: 17px !important;
  padding: 16px 0 !important;
  border-radius: 28px !important;
  background: linear-gradient(135deg, #FF8C42, #FF6B35) !important;
  box-shadow: 0 6px 24px rgba(255,107,53,0.3) !important;
}

// 图片预览
.preview-overlay {
  position: fixed;
  inset: 0;
  z-index: 999;
  background: rgba(0,0,0,0.85);
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: zoom-out;
}
.preview-full-img {
  max-width: 90%;
  max-height: 80vh;
  object-fit: contain;
  border-radius: 16px;
  box-shadow: 0 8px 40px rgba(0,0,0,0.3);
}
.fade-enter-active, .fade-leave-active { transition: opacity 0.2s; }
.fade-enter-from, .fade-leave-to { opacity: 0; }
</style>
