<template>
  <Teleport to="body">
    <Transition name="cg-overlay">
      <div
        v-if="activityStore.showCgGuide || activityStore.showCommonGuide"
        class="fixed inset-0 z-[10000] flex items-center justify-center bg-black/90"
      >
        <!-- 阶段1: 播放CG动画 -->
        <div
          v-if="phase === 'video' && activityStore.showCgGuide"
          class="relative w-full h-full flex flex-col items-center justify-center"
        >
          <!-- CG视频区域 -->
          <div
            class="relative w-full max-w-4xl aspect-video rounded-2xl overflow-hidden shadow-2xl mx-4"
          >
            <video
              ref="videoRef"
              class="w-full h-full object-cover"
              :src="cgVideoUrl"
              playsinline
              preload="metadata"
              @ended="onVideoEnd"
              @error="onVideoEnd"
              @play="isPlaying = true"
              @pause="isPlaying = false"
            />
            <!-- 自定义播放按钮：未播放时显示，点击后开始播放 -->
            <button
              v-if="!isPlaying"
              type="button"
              class="absolute inset-0 flex items-center justify-center bg-black/30 hover:bg-black/40 transition-colors cursor-pointer"
              @click="playVideo"
            >
              <span
                class="w-16 h-16 sm:w-20 sm:h-20 rounded-full bg-white/20 hover:bg-white/30 flex items-center justify-center text-white/90"
              >
                <svg class="w-8 h-8 sm:w-10 sm:h-10 ml-1" viewBox="0 0 24 24" fill="currentColor">
                  <path d="M8 5v14l11-7z" />
                </svg>
              </span>
            </button>
            <!-- 控制栏：播放 / 暂停 + 时间 + 进度条 -->
            <div
              class="absolute bottom-4 left-3 right-3 flex items-center gap-3 text-white pointer-events-none"
            >
              <!-- 播放 / 暂停按钮 -->
              <button
                type="button"
                class="w-9 h-9 sm:w-10 sm:h-10 rounded-full bg-black/50 hover:bg-black/80 flex items-center justify-center text-white shadow-md border border-white/20 cursor-pointer transition-colors pointer-events-auto"
                @click="isPlaying ? pauseVideo() : playVideo()"
              >
                <svg
                  v-if="!isPlaying"
                  class="w-4 h-4 sm:w-5 sm:h-5 ml-0.5"
                  viewBox="0 0 24 24"
                  fill="currentColor"
                >
                  <path d="M8 5v14l11-7z" />
                </svg>
                <svg v-else class="w-4 h-4 sm:w-5 sm:h-5" viewBox="0 0 24 24" fill="currentColor">
                  <path d="M6 4h4v16H6V4zm8 0h4v16h-4V4z" />
                </svg>
              </button>

              <!-- 时间 + 进度条 -->
              <div
                class="flex-1 flex flex-col gap-1 rounded-lg bg-black/50 backdrop-blur-sm px-3 py-2 pointer-events-auto"
              >
                <div class="flex items-center justify-end text-[11px] sm:text-xs font-mono">
                  <span class="text-white/90">{{ formattedCurrentTime }}</span>
                  <span class="text-white/60 mx-1">/</span>
                  <span class="text-white/80">{{ formattedDuration }}</span>
                </div>
                <div class="h-1.5 rounded-full bg-white/15 overflow-hidden">
                  <div
                    class="h-full bg-gradient-to-r from-indigo-300 via-indigo-400 to-purple-400 transition-all duration-300"
                    :style="{ width: `${videoProgress}%` }"
                  />
                </div>
              </div>
            </div>
          </div>
          <!-- 跳过按钮：视频播放满 1 分钟后才显示 -->
          <button
            v-if="canSkip"
            class="absolute top-6 right-6 px-5 py-2 rounded-full bg-white/15 hover:bg-white/25 text-white/80 hover:text-white text-sm border border-white/20 transition-all duration-200 cursor-pointer"
            @click="skipVideo"
          >
            跳过
          </button>
        </div>

        <!-- 阶段2: 奖励动画 -->
        <div
          v-else-if="phase === 'reward' && activityStore.showCgGuide"
          class="flex flex-col items-center gap-6"
        >
          <div class="text-white/60 text-sm mb-2">恭喜获得观看奖励</div>
          <!-- 奖励卡片 -->
          <div class="flex gap-6">
            <div class="reward-card reward-card-1">
              <div
                class="flex flex-col items-center gap-3 px-8 py-6 rounded-2xl bg-gradient-to-br from-indigo-500/90 to-purple-600/90 border border-white/20 shadow-[0_8px_32px_rgba(99,102,241,0.4)]"
              >
                <span class="text-4xl">🧩</span>
                <span class="text-white text-2xl font-bold">碎片 +1</span>
              </div>
            </div>
            <div class="reward-card reward-card-2">
              <div
                class="flex flex-col items-center gap-3 px-8 py-6 rounded-2xl bg-gradient-to-br from-amber-400/90 to-orange-500/90 border border-white/20 shadow-[0_8px_32px_rgba(245,158,11,0.4)]"
              >
                <span class="text-4xl">💰</span>
                <span class="text-white text-2xl font-bold">亚币 +2</span>
              </div>
            </div>
          </div>
          <!-- 光效 -->
          <div class="absolute inset-0 pointer-events-none overflow-hidden">
            <div
              class="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-96 h-96 rounded-full bg-amber-400/10 blur-3xl animate-pulse"
            />
          </div>
        </div>

        <!-- 阶段3: 指引按钮 -->
        <div
          v-else-if="phase === 'guide' && activityStore.showCommonGuide"
          class="flex flex-col items-center gap-8"
        >
          <div class="text-center">
            <h2 class="text-white text-2xl font-bold mb-2">欢迎来到 YAYA 文化岛 🏝️</h2>
            <p class="text-white/60 text-sm">选择你接下来想要探索的内容</p>
          </div>
          <div class="flex gap-5">
            <button
              class="group flex flex-col items-center gap-3 px-8 py-6 rounded-2xl bg-gradient-to-br from-indigo-500 to-purple-600 hover:from-indigo-400 hover:to-purple-500 shadow-lg hover:shadow-[0_8px_32px_rgba(99,102,241,0.5)] border border-white/20 transition-all duration-300 hover:-translate-y-1 cursor-pointer"
              @click="goToActivity"
            >
              <span class="text-3xl group-hover:scale-110 transition-transform duration-300"
                >🎯</span
              >
              <span class="text-white font-semibold text-base">直达活动页面</span>
              <span class="text-white/60 text-xs">查看精选推文</span>
            </button>
            <button
              class="group flex flex-col items-center gap-3 px-8 py-6 rounded-2xl bg-white/10 hover:bg-white/20 shadow-lg hover:shadow-[0_8px_32px_rgba(255,255,255,0.15)] border border-white/20 transition-all duration-300 hover:-translate-y-1 cursor-pointer"
              @click="goHome"
            >
              <span class="text-3xl group-hover:scale-110 transition-transform duration-300"
                >🏠</span
              >
              <span class="text-white font-semibold text-base">返回首页</span>
              <span class="text-white/60 text-xs">开始自由浏览</span>
            </button>
          </div>
        </div>
      </div>
    </Transition>
  </Teleport>
</template>

<script setup lang="ts">
import { useActivityStore } from '@/stores'
import { useYaBiStore } from '@/stores/yabi'
const yabiStore = useYaBiStore()
const activityStore = useActivityStore()
const router = useRouter()
type Phase = 'video' | 'reward' | 'guide'
const phase = ref<Phase>('video')

const videoRef = ref<HTMLVideoElement>()
const videoProgress = ref(0)
const videoCurrentTime = ref(0)
const videoDuration = ref(0)
const isPlaying = ref(false)
// 是否允许跳过：视频播放满 60s 后变为 true
const canSkip = ref(false)

const cgVideoUrl = ref(
  'https://soundasia.oss-cn-shenzhen.aliyuncs.com/OA/readName/mp4/2026/03/10/Common/1773129191249.mp4',
)

const formatTime = (seconds: number) => {
  if (Number.isNaN(seconds) || seconds < 0) return '0:00'
  const m = Math.floor(seconds / 60)
  const s = Math.floor(seconds % 60)
  return `${m}:${s.toString().padStart(2, '0')}`
}

const formattedCurrentTime = computed(() => formatTime(videoCurrentTime.value))
const formattedDuration = computed(() => formatTime(videoDuration.value))

let progressTimer: ReturnType<typeof setInterval> | null = null

const startTimers = () => {
  progressTimer = setInterval(() => {
    if (videoRef.value) {
      const { currentTime, duration } = videoRef.value
      videoCurrentTime.value = currentTime
      videoDuration.value = duration
      if (duration && Number.isFinite(duration)) {
        videoProgress.value = (currentTime / duration) * 100
        if (!canSkip.value && currentTime >= 60) canSkip.value = true
      }
    }
  }, 200)
}

const playVideo = () => {
  videoRef.value?.play()
}

const pauseVideo = () => {
  videoRef.value?.pause()
}

const clearTimers = () => {
  if (progressTimer) clearInterval(progressTimer)
}

const onVideoEnd = () => {
  clearTimers()
  transitionToReward()
}

const skipVideo = () => {
  if (videoRef.value) videoRef.value.pause()
  clearTimers()
  transitionToReward()
}

const transitionToReward = async () => {
  phase.value = 'reward'
  // 标记用户已经观看过cg动画
  await activityStore.markUserGuideWatched('isView')
  // 并且需要加YA币
  yabiStore.fetchYaBiData()
  setTimeout(() => {
    // 第二天上线打开这个 去掉下一行注释
    // phase.value = 'guide'
    close()
  }, 2500)
}

const close = () => {
  activityStore.showCgGuide = false
  activityStore.showCommonGuide = false
  phase.value = 'video'
  videoProgress.value = 0
  videoCurrentTime.value = 0
  videoDuration.value = 0
  isPlaying.value = false
  canSkip.value = false
}

const goToActivity = async () => {
  await activityStore.markUserGuideWatched('isViewGuide')
  close()
  router.push('/articleDetail/289')
}

const goHome = async () => {
  activityStore.markUserGuideWatched('isViewGuide')
  close()
  router.push('/homePage/homeTab')
}

watch(
  () => [activityStore.showCgGuide, activityStore.showCommonGuide],
  (val) => {
    if (val[0]) {
      phase.value = 'video'
      nextTick(() => startTimers())
    } else if (val[1]) {
      // 第二天上线打开这个 去掉下一行注释
      // phase.value = 'guide'
      close()
    } else {
      clearTimers()
    }
  },
)

onUnmounted(() => {
  clearTimers()
})
</script>

<style scoped>
.cg-overlay-enter-active {
  transition: opacity 0.5s ease;
}
.cg-overlay-leave-active {
  transition: opacity 0.4s ease;
}
.cg-overlay-enter-from,
.cg-overlay-leave-to {
  opacity: 0;
}

.reward-card {
  opacity: 0;
  animation: rewardPop 0.7s cubic-bezier(0.34, 1.56, 0.64, 1) forwards;
}
.reward-card-1 {
  animation-delay: 0.2s;
}
.reward-card-2 {
  animation-delay: 0.5s;
}

@keyframes rewardPop {
  0% {
    opacity: 0;
    transform: scale(0.5) translateY(20px);
  }
  60% {
    opacity: 1;
    transform: scale(1.08) translateY(-5px);
  }
  100% {
    opacity: 1;
    transform: scale(1) translateY(0);
  }
}
</style>
