<template>
  <view class="matching-game-overlay" v-if="visible" @touchmove.stop.prevent>
    <view class="game-mask"></view>
    <view class="game-container">
      <view class="game-header">
        <text class="game-title">翻牌配对</text>
        <view class="game-stats">
          <text>已配对: {{ pairsFound }}</text>
          <text>剩余: {{ cards.length / 2 - pairsFound }}</text>
        </view>
      </view>

      <view class="game-grid" :style="{ gridTemplateColumns: `repeat(${gridCols}, 1fr)` }">
        <view 
          v-for="(card, index) in gameCards" 
          :key="index" 
          class="game-card"
          :class="{ flipped: card.flipped || card.matched, matched: card.matched }"
          @tap="onCardTap(index)"
        >
          <view class="card-inner">
            <view class="card-front">
              <view class="pattern"></view>
            </view>
            <view class="card-back">
              <image :src="card.image" mode="aspectFit" class="card-img" />
            </view>
          </view>
        </view>
      </view>

      <button class="submit-btn" @tap="forceSubmit" v-if="gameOver">领 取 奖 励</button>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue'

const props = defineProps({
  visible: { type: Boolean, default: false },
  cards: { type: Array, default: () => [] }, // Array of { id, image, type... }
  gameId: { type: String, default: '' }
})

const emit = defineEmits(['finish', 'close'])

const gameCards = ref([])
const pairsFound = ref(0)
const selectedIndices = ref([])
const isProcessing = ref(false)
const gameOver = ref(false)

const gridCols = computed(() => {
  const len = props.cards.length
  if (len <= 9) return 3
  if (len <= 16) return 4
  return 4
})

watch(() => props.visible, (val) => {
  if (val) initGame()
})

function initGame() {
  // Initialize game cards with state
  // Assuming props.cards is already the shuffled list of cards for the board
  let list = JSON.parse(JSON.stringify(props.cards))
  
  // If we only got types, we might need to duplicate them? 
  // User says "initializes the game session with shuffled cards". 
  // I assume the server sends the exact layout.
  
  gameCards.value = list.map(c => ({
    ...c,
    flipped: false,
    matched: false
  }))
  
  pairsFound.value = 0
  selectedIndices.value = []
  isProcessing.value = false
  gameOver.value = false
  
  // Flash all cards briefly?
  setTimeout(() => {
    gameCards.value.forEach(c => c.flipped = true)
    setTimeout(() => {
      gameCards.value.forEach(c => c.flipped = false)
    }, 2000)
  }, 500)
}

function onCardTap(index) {
  if (isProcessing.value) return
  const card = gameCards.value[index]
  if (card.flipped || card.matched) return

  // Flip card
  card.flipped = true
  selectedIndices.value.push(index)

  if (selectedIndices.value.length === 2) {
    checkMatch()
  }
}

function checkMatch() {
  isProcessing.value = true
  const [idx1, idx2] = selectedIndices.value
  const card1 = gameCards.value[idx1]
  const card2 = gameCards.value[idx2]

  // Assuming 'title' or 'id' connects them. 
  // Better use an explicit 'type' or compare 'title/image'.
  // Using image as the matcher for now if no type.
  const isMatch = (card1.type && card1.type === card2.type) || (card1.image === card2.image)

  if (isMatch) {
    setTimeout(() => {
      card1.matched = true
      card2.matched = true
      pairsFound.value++
      selectedIndices.value = []
      isProcessing.value = false
      checkGameOver()
    }, 500)
  } else {
    setTimeout(() => {
      card1.flipped = false
      card2.flipped = false
      selectedIndices.value = []
      isProcessing.value = false
    }, 1000)
  }
}

function checkGameOver() {
  // Check if all pairs found
  // Note: If odd number of cards (9), 1 will remain.
  const totalPairsPossible = Math.floor(props.cards.length / 2)
  if (pairsFound.value >= totalPairsPossible) {
    gameOver.value = true
  }
}

function forceSubmit() {
  emit('finish', {
    gameId: props.gameId,
    totalPairs: pairsFound.value
  })
}
</script>

<style lang="scss" scoped>
.matching-game-overlay {
  position: fixed; top: 0; left: 0; right: 0; bottom: 0;
  z-index: 10000;
  display: flex; align-items: center; justify-content: center;
}
.game-mask {
  position: absolute; top: 0; left: 0; width: 100%; height: 100%;
  background: rgba(0,0,0,0.85);
  backdrop-filter: blur(10px);
}
.game-container {
  position: relative; z-index: 10;
  width: 680rpx;
  background: #fff;
  border-radius: 32rpx;
  padding: 40rpx;
  box-shadow: 0 20rpx 60rpx rgba(0,0,0,0.3);
  animation: popIn 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275);
}
.game-header {
  display: flex; justify-content: space-between; align-items: center;
  margin-bottom: 40rpx;
}
.game-title {
  font-size: 40rpx; font-weight: 800; color: #333;
}
.game-stats {
  font-size: 28rpx; color: #666; font-weight: 600;
}
.game-grid {
  display: grid; gap: 20rpx;
  margin-bottom: 40rpx;
}
.game-card {
  aspect-ratio: 1;
  perspective: 1000rpx;
}
.card-inner {
  position: relative; width: 100%; height: 100%;
  transform-style: preserve-3d;
  transition: transform 0.5s;
}
.game-card.flipped .card-inner {
  transform: rotateY(180deg);
}
.game-card.matched .card-inner {
  transform: rotateY(180deg);
}
.game-card.matched {
  animation: pulse 1s infinite;
}
.card-front, .card-back {
  position: absolute; top: 0; left: 0; width: 100%; height: 100%;
  backface-visibility: hidden;
  border-radius: 16rpx;
  box-shadow: 0 4rpx 10rpx rgba(0,0,0,0.1);
}
.card-front {
  background: linear-gradient(135deg, #ff9a9e 0%, #fecfef 99%, #fecfef 100%);
  display: flex; align-items: center; justify-content: center;
}
.pattern {
  width: 60%; height: 60%;
  background: rgba(255,255,255,0.3);
  border-radius: 50%;
}
.card-back {
  background: #fff;
  transform: rotateY(180deg);
  display: flex; align-items: center; justify-content: center;
  padding: 10rpx;
}
.card-img {
  width: 80%; height: 80%;
}
.submit-btn {
  background: linear-gradient(90deg, #ff758c 0%, #ff7eb3 100%);
  color: #fff;
  font-weight: 800;
  border-radius: 50rpx;
  margin-top: 20rpx;
  box-shadow: 0 10rpx 20rpx rgba(255, 117, 140, 0.4);
}
@keyframes popIn {
  from { transform: scale(0.8); opacity: 0; }
  to { transform: scale(1); opacity: 1; }
}
@keyframes pulse {
  0% { transform: scale(1); }
  50% { transform: scale(1.05); }
  100% { transform: scale(1); }
}
</style>
