<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { useRoute } from 'vue-router'
import CompetitionLayout from '@/components/custom/user/CompetitionLayout.vue'
import { PublishStatus } from '@/enum/business'
import { useRouterPush } from '@/hooks/common/router'
import { fetchUpdatePublishStatus } from '@/service/api/competition'
import { fetchGetQuestionTableByActivityID } from '@/service/api/game'
import { useActivityInfoStore } from '@/store/modules/activityinfo'
import { AudioController } from '@/utils/audio'
import { filterRepeat } from '@/utils/data'

const activityInfoStore = useActivityInfoStore()
const activityInfo = computed(() => activityInfoStore.activityInfo)

const { routerPushByKey, routerBack } = useRouterPush()
const audioController = new AudioController()

interface QuestionItem {
  id: number
  moduleName: string
}

const questions = ref<QuestionItem[]>([])
const loading = ref(false)

const activityName = computed(() => activityInfo.value?.ActivityTitle || '星·辞海遨游')

// 记录已翻转的卡片索引
const flippedCards = ref<Set<number>>(new Set())

// 计算是否所有卡片都已翻转 (当前显示4张卡片)
// eslint-disable-next-line unused-imports/no-unused-vars
const isAllFlipped = computed(() => flippedCards.value.size === questions.value.length)

// 控制下一步按钮的显示（带延迟）
const showNextButton = ref(true)
// eslint-disable-next-line prefer-const, unused-imports/no-unused-vars
let timer: ReturnType<typeof setTimeout> | null = null

// 获取路由参数
const route = useRoute()
const activityId = computed(() => activityInfoStore.activityId || Number(route.query?.activityId))
const groupsId = computed(() => Number(route.query?.groupsId)) || activityInfoStore.groupId
const teamId = computed(() => activityInfoStore.teamId || Number(route.query?.teamId))
const teamIds = computed(() => route.query?.teamIds as string)

const RoundType = route.query?.RoundType || 0

async function getQuestions() {
  if (!activityId.value || !groupsId.value || !teamId.value) {
    window?.$message?.error('参数错误')
    return
  }

  loading.value = true
  try {
    const { data, error } = await fetchGetQuestionTableByActivityID(String(activityId.value), Number(RoundType))
    if (error) {
      window?.$message?.error(error.message)
      return
    }

    const list = data?.data || []

    if (list && Array.isArray(list)) {
      // 根据ActitvityQuestionName去重
      const uniqueData = filterRepeat(list as any[], 'Name')
      questions.value = uniqueData.map((item: any) => ({
        id: item.Id,
        moduleName: item.Name,
      }))
    }
  }
  finally {
    loading.value = false
  }
}
// 测试先注释掉
// watch(isAllFlipped, (val) => {
//   if (timer) {
//     clearTimeout(timer)
//     timer = null
//   }

//   if (val) {
//     timer = setTimeout(() => {
//       showNextButton.value = true
//     }, 1500)
//   }
//   else {
//     showNextButton.value = false
//   }
// })

function handleBack() {
  routerBack()
}

async function handleNext() {
  // 封面页的下一步操作，更改活动状态
  // 判断状态是否为已发布或处理中，若已发布或处理中则不能更改状态
  if (activityInfo.value?.PublishStatus === PublishStatus.Published || activityInfo.value?.PublishStatus === PublishStatus.Processing) {
    if (activityId.value) {
      try {
        await fetchUpdatePublishStatus(Number(activityId.value), PublishStatus.Processing)
      }
      catch (error) {
        console.error('更新活动状态失败', error)
      }
    }
  }

  routerPushByKey('user_rules', {
    query: {
      activityId: activityId.value,
      groupsId: groupsId.value,
      teamId: teamId.value,
      teamIds: teamIds.value,
      RoundType: Number(RoundType),
    },
  })
}

function toggleFlip(index: number) {
  if (flippedCards.value.has(index)) {
    flippedCards.value.delete(index) // 可选：如果希望再次点击翻回去，可以取消注释
  }
  else {
    flippedCards.value.add(index)
    audioController.play('flip') // 翻牌动效
  }
  // 每次点击都播放翻牌音效（无论翻开还是翻回去）
  // audioController.play('flip')
}

async function initSyncRouteParams() {
  if (route.query.activityId)
    activityInfoStore.setActivityId(Number(route.query.activityId))
  if (route.query.groupsId)
    activityInfoStore.setGroupId(Number(route.query.groupsId))
  if (route.query.teamId)
    activityInfoStore.setTeamId(Number(route.query.teamId))
  if (route.query.teamIds) {
    const ids = String(route.query.teamIds).split(',').map(Number).filter(id => !Number.isNaN(id))
    if (ids.length > 0)
      activityInfoStore.setTeamIds(ids)
  }
}

const showCards = ref(false)

// 3D 悬停效果逻辑
const cardStyles = ref<Record<number, any>>({})

function handleMouseMove(e: MouseEvent, index: number) {
  const card = e.currentTarget as HTMLElement
  const rect = card.getBoundingClientRect()
  const x = e.clientX - rect.left
  const y = e.clientY - rect.top
  const centerX = rect.width / 2
  const centerY = rect.height / 2

  // 计算旋转角度
  // 鼠标在上方(y < centerY) -> rotateX > 0 (上半部分凸起)
  // 鼠标在下方(y > centerY) -> rotateX < 0 (下半部分凸起)
  const rotateX = ((centerY - y) / centerY) * 10

  // 鼠标在左方(x < centerX) -> rotateY < 0 (左半部分凸起)
  // 鼠标在右方(x > centerX) -> rotateY > 0 (右半部分凸起)
  const rotateY = ((x - centerX) / centerX) * 10

  cardStyles.value[index] = {
    transform: `perspective(1000px) rotateX(${rotateX}deg) rotateY(${rotateY}deg) scale3d(1.02, 1.02, 1.02)`,
    transition: 'transform 0.1s ease-out', // 移动时响应要快
  }
}

function handleMouseLeave(index: number) {
  cardStyles.value[index] = {
    transform: 'perspective(1000px) rotateX(0) rotateY(0) scale3d(1, 1, 1)',
    transition: 'transform 0.5s ease', // 离开时平滑复位
  }
}

onMounted(async () => {
  await initSyncRouteParams()
  await getQuestions()
  // 页面加载 300ms 后显示卡片，开始动画
  setTimeout(() => {
    showCards.value = true
  }, 500)
})
</script>

<template>
  <CompetitionLayout
    :show-back="true" :show-next="showNextButton" next-btn-text="下一步" :title="activityName"
    :title-bg-type="2" @back="handleBack" @next="handleNext"
  >
    <div class="h-screen w-full overflow-y-auto font-sans">
      <div class="relative z-10 min-h-full w-full">
        <div class="min-h-full w-full flex flex-col items-center pb-12 pt-24">
          <!-- 卡片列表 -->
          <TransitionGroup
            tag="div" name="card-anim"
            class="perspective-container max-w-[1800px] w-full flex flex-wrap justify-center gap-4 px-4 md:gap-10 md:px-12"
          >
            <div
              v-for="(node, index) in showCards ? questions : []" :key="index"
              class="w-[44%] card-wrapper 2xl:w-[14%] lg:w-[21%] md:w-[28%] xl:w-[17%]" :style="{
                animationDelay: `${index * 0.2}s`,
                ...(cardStyles[index] || {}),
              }" @click="toggleFlip(index)" @mousemove="(e) => handleMouseMove(e, index)"
              @mouseleave="handleMouseLeave(index)"
            >
              <div class="flip-card-inner" :class="{ 'is-flipped': flippedCards.has(index) }">
                <!-- 正面 (Front) - 显示背面图案 -->
                <div class="flip-card-front card-face">
                  <!-- 这里是未翻开时的样子，即卡片背面 -->
                  <div class="card-back-design" />
                </div>

                <!-- 背面 (Back) - 显示内容 -->
                <div class="flip-card-back card-face">
                  <!-- 这里是翻开后的样子，即卡片正面内容 -->
                  <div class="card-content-design">
                    <!-- 内部装饰圈 -->
                    <div class="inner-circle-decoration">
                      <!-- 文字内容 -->
                      <div class="relative z-10 transform text-center">
                        <div
                          class="card-text text-2xl text-[#333333] font-bold leading-tight font-serif drop-shadow-sm"
                        >
                          <span class="block">{{ node.moduleName.slice(0, 2) }}</span>
                          <span class="block">{{ node.moduleName.slice(2) }}</span>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </TransitionGroup>
        </div>
      </div>
    </div>
  </CompetitionLayout>
</template>

<style scoped lang="scss">
// ... existing styles ...

// 卡片进场动画 - 增强版 3D 纵深翻转入场 (Deep Space Flip-in)
.card-anim-enter-active {
  // 增加动画时长到 1.5s，配合复杂的 3D 变换
  animation: card-enter-deep 1.5s cubic-bezier(0.2, 0.8, 0.2, 1) both;
}

@keyframes card-enter-deep {
  0% {
    opacity: 0;
    // [初始状态]
    // translateZ(-800px): 从屏幕深处(远离观众)开始
    // translateY(300px): 从下方更深处升起
    // rotateY(180deg): 背面朝上 (配合 flip-card 结构，视觉上可能是翻转状态)
    // rotateX(45deg): 稍微倾斜
    transform: translate3d(0, 300px, -800px) rotateY(180deg) rotateX(45deg) scale(0.5);
    filter: blur(20px); // 深度模糊
  }

  50% {
    opacity: 1;
    filter: blur(0); // 聚焦
  }

  70% {
    // [过冲状态]
    // 飞到眼前一点点 (Z=50px)
    // 角度稍微回弹 (rotateY -15deg)
    transform: translate3d(0, -20px, 50px) rotateY(-15deg) rotateX(-10deg) scale(1.05);
  }

  100% {
    // [最终归位]
    transform: translate3d(0, 0, 0) rotateY(0) rotateX(0) scale(1);
  }
}

.perspective-container {
  perspective: 1000px; // [3D透视] 设置观察者距离，数值越小透视感越强，产生近大远小的3D效果
}

.card-wrapper {
  position: relative;
  aspect-ratio: 3/4;
  cursor: pointer;
  transition: transform 0.3s ease;
  box-shadow: none !important;
}

.flip-card-inner {
  position: relative;
  width: 100%;
  height: 100%;
  text-align: center;
  // [动画核心]
  // 0.6s: 动画持续时间
  // cubic-bezier(...): 贝塞尔曲线，(0.175, 0.885, 0.32, 1.275) 这是一个带有"回弹"效果的曲线
  // 也就是卡片翻过去时会稍微过头一点再弹回来，增加生动感
  transition: transform 3s cubic-bezier(0.175, 0.885, 0.32, 1.275);

  transform-style: preserve-3d; // [3D空间] 确保子元素（正反面）在3D空间中渲染，而不是压平在平面上
  border-radius: 20px;
  // box-shadow: 0 10px 30px -5px rgba(0, 0, 0, 0.2); // [静态阴影] 默认状态下的投影

  &.is-flipped {
    // [翻转状态]
    // rotateY(180deg): 绕Y轴旋转180度，实现翻面
    // scale(1.05): 翻转同时放大1.05倍，产生"向观众逼近"的视觉冲击力
    transform: rotateY(180deg) scale(1.06);
    box-shadow: 0 20px 40px -5px rgba(0, 0, 0, 0.3); // [动态阴影] 翻转浮起时阴影更深、更扩散
  }
}

.card-face {
  position: absolute;
  width: 100%;
  height: 100%;
  // [背面隐藏] 关键属性！当元素背面朝向观察者时隐藏。
  // 这样保证翻转180度后，正面消失，背面显示（或者反之）
  -webkit-backface-visibility: hidden;
  backface-visibility: hidden;

  border-radius: 20px;
  overflow: hidden;
  // border: 1px solid rgba(255, 255, 255, 0.5); // 增加微妙的边框
}

// 正面（实际是卡背图案）
.flip-card-front {
  background-color: transparent;

  .card-back-design {
    width: 100%;
    height: 100%;
    background: url('@/assets/imgs/user/cover-back.webp') no-repeat center center; // 背景面
    background-size: contain; // 保持比例
    border-radius: 20px;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: filter 1s; // [滤镜动画] 1秒内变化，模拟卡片翻转时的光影变化
  }
}

// 背面（实际是内容面）
.flip-card-back {
  // background-color: #fff;
  transform: rotateY(180deg);
  // border: 4px solid #fff;

  .card-content-design {
    width: 100%;
    height: 100%;
    background: url('@/assets/imgs/user/cover-bg-active.svg') no-repeat center center;
    background-size: cover;
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;

    // 光效叠加
    &::before {
      content: '';
      position: absolute;
      top: -150%;
      left: -50%;
      width: 200%;
      height: 200%;
      background: linear-gradient(
        to bottom right,
        rgba(255, 255, 255, 0) 0%,
        rgba(255, 255, 255, 0) 40%,
        rgba(255, 255, 255, 0.6) 50%,
        rgba(255, 255, 255, 0) 60%,
        rgba(255, 255, 255, 0) 100%
      );
      transform: rotate(-30deg);
      opacity: 0;
      transition: none;
      pointer-events: none;
    }
  }

  // 翻转后的高光效果 - 扫光动画
  .is-flipped & .card-content-design::before {
    // [扫光动画触发]
    // animation-delay: 0.2s; 确保卡片翻转到一半（正对屏幕）时才开始闪光，
    // 模拟光线随着角度变化掠过卡片表面的物理效果
    animation: shine-sweep 3s ease-out forwards;
    animation-delay: 0.2s;
  }
}

.inner-circle-decoration {
  width: 98px;
  height: 98px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 2px solid $accent-color; // 使用金色
  // box-shadow: 0 0 15px rgba(212, 175, 55, 0.2);
  position: relative;

  // 祥云纹理
  &::after {
    content: '';
    position: absolute;
    top: -5px;
    left: -5px;
    right: -5px;
    bottom: -5px;
    border-radius: 50%;
    border: 1px dashed $accent-color;
    animation: spin 20s linear infinite;
  }
}

.card-text {
  font-family: 'Noto Serif SC', serif;
  color: $group-text-color;
  text-shadow: 0 1px 2px rgba(255, 255, 255, 0.8);
}

// [扫光动画关键帧]
// 模拟一道光束从左上角快速扫向右下角
@keyframes shine-sweep {
  0% {
    top: -150%;
    left: -150%;
    opacity: 0;
  }

  10% {
    // 刚进入时瞬间变亮
    opacity: 0.8;
  }

  100% {
    // 扫出视野
    top: 50%;
    left: 150%;
    opacity: 0;
  }
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }

  to {
    transform: rotate(360deg);
  }
}
</style>
