<script setup lang="ts">
import { ref, onMounted, onUnmounted, computed } from 'vue'

const props = defineProps<{
  t: (key: string) => string
  theme: string
}>()

const emit = defineEmits(['close', 'unlock-nat'])

const canvas = ref<HTMLCanvasElement | null>(null)
const gameState = ref<'start' | 'playing' | 'gameOver' | 'win'>('start')
const score = ref(0)
const level = ref(1)
const TOTAL_LEVELS = 10

let ctx: CanvasRenderingContext2D | null = null
let animationId: number
let playerX = 180
const playerY = 500
const playerWidth = 40
const playerHeight = 40

// Theme-based configurations
const themeConfig = computed(() => {
  switch (props.theme) {
    case 'unicorn':
      return { 
        bg: '#fff0fb', 
        player: '🦄', 
        obstacles: { trash: '🍬', boat: '🍭', boar: '🧁' },
        waves: 'rgba(255, 105, 180, 0.3)'
      }
    case 'luxury':
      return { 
        bg: '#0a0a0a', 
        player: '👑', 
        obstacles: { trash: '💎', boat: '💍', boar: '💰' },
        waves: 'rgba(212, 175, 55, 0.4)'
      }
    case 'win95':
      return { 
        bg: '#c0c0c0', 
        player: '🖱️', 
        obstacles: { trash: '🗑️', boat: '📁', boar: '💣' },
        waves: 'rgba(0,0,0,0.1)'
      }
    case 'nat':
      return { 
        bg: '#1a2f1a', 
        player: '🐗', 
        obstacles: { trash: '🪵', boat: '🛶', boar: '🦢' },
        waves: 'rgba(255,255,255,0.1)'
      }
    default:
      return { 
        bg: '#1e3a8a', 
        player: '🦢', 
        obstacles: { trash: '🗑️', boat: '🚤', boar: '🐗' },
        waves: 'rgba(255,255,255,0.2)'
      }
  }
})

interface Obstacle {
  x: number
  y: number
  type: 'trash' | 'boat' | 'boar'
  speed: number
}

const obstacles = ref<Obstacle[]>([])
const keys = ref<Record<string, boolean>>({})

// Touch handling
const handleTouchMove = (e: TouchEvent) => {
  if (gameState.value !== 'playing') return
  const touchX = e.touches[0].clientX
  const canvasRect = canvas.value?.getBoundingClientRect()
  if (canvasRect) {
    playerX = Math.max(0, Math.min(360, (touchX - canvasRect.left) * (400 / canvasRect.width) - (playerWidth / 2)))
  }
}

const initGame = () => {
  gameState.value = 'playing'
  score.value = 0
  level.value = 1
  obstacles.value = []
  playerX = 180
  gameLoop()
}

const gameLoop = () => {
  if (gameState.value !== 'playing') return
  update()
  draw()
  animationId = requestAnimationFrame(gameLoop)
}

const update = () => {
  // Move player (Keyboard)
  const speed = 7 // Made slightly faster for easier control
  if (keys.value['ArrowLeft'] && playerX > 0) playerX -= speed
  if (keys.value['ArrowRight'] && playerX < 360) playerX += speed

  // Spawn obstacles - Adjusted frequency for better balance
  const spawnChance = 0.01 + level.value * 0.002
  if (Math.random() < spawnChance) {
    const type = level.value === TOTAL_LEVELS ? 'boar' : (Math.random() > 0.6 ? 'trash' : 'boat')
    obstacles.value.push({
      x: Math.random() * 370,
      y: -50,
      type: type,
      speed: 1.5 + level.value * 0.45 // Slightly slower for level 1 but scales up
    })
  }

  // Move and filter obstacles
  obstacles.value.forEach(obs => {
    obs.y += obs.speed
    
    // Collision detection (with a bit of buffer for better feel)
    const buffer = 10
    if (
      playerX + buffer < obs.x + 30 &&
      playerX + playerWidth - buffer > obs.x &&
      playerY + buffer < obs.y + 30 &&
      playerY + playerHeight - buffer > obs.y
    ) {
      gameState.value = 'gameOver'
    }
  })
  
  obstacles.value = obstacles.value.filter(obs => obs.y < 650)

  // Score and level up
  score.value += 1
  if (score.value % 500 === 0 && level.value < TOTAL_LEVELS) {
    level.value += 1
  }
  
  // Win condition
  if (score.value >= TOTAL_LEVELS * 500 + 500) {
    gameState.value = 'win'
    emit('unlock-nat')
  }
}

const draw = () => {
  if (!ctx) return
  ctx.clearRect(0, 0, 400, 600)

  // Draw Background
  ctx.fillStyle = themeConfig.value.bg
  ctx.fillRect(0, 0, 400, 600)
  
  // Draw Waves
  ctx.strokeStyle = themeConfig.value.waves
  ctx.lineWidth = 2
  for (let i = 0; i < 5; i++) {
    const y = (Date.now() / 20 + i * 120) % 650
    ctx.beginPath()
    ctx.moveTo(0, y)
    ctx.bezierCurveTo(100, y - 10, 300, y + 10, 400, y)
    ctx.stroke()
  }

  // Draw Player
  ctx.font = '40px Arial'
  ctx.textAlign = 'left'
  ctx.textBaseline = 'top'
  ctx.fillText(themeConfig.value.player, playerX, playerY)

  // Draw Obstacles
  obstacles.value.forEach(obs => {
    const emoji = themeConfig.value.obstacles[obs.type]
    ctx.fillText(emoji, obs.x, obs.y)
  })
}

const handleKeydown = (e: KeyboardEvent) => keys.value[e.key] = true
const handleKeyup = (e: KeyboardEvent) => keys.value[e.key] = false

onMounted(() => {
  if (canvas.value) {
    ctx = canvas.value.getContext('2d')
    window.addEventListener('keydown', handleKeydown)
    window.addEventListener('keyup', handleKeyup)
  }
})

onUnmounted(() => {
  cancelAnimationFrame(animationId)
  window.removeEventListener('keydown', handleKeydown)
  window.removeEventListener('keyup', handleKeyup)
})
</script>

<template>
  <div class="game-overlay fancy-glass">
    <div class="game-window">
      <div class="game-header">
        <span>{{ t('game.title') }}</span>
        <button @click="emit('close')">X</button>
      </div>
      
      <div class="canvas-container">
        <canvas 
          ref="canvas" 
          width="400" 
          height="600"
          @touchmove.prevent="handleTouchMove"
        ></canvas>
        
        <div v-if="gameState === 'start'" class="overlay-content">
          <h2>{{ t('game.title') }}</h2>
          <p>Weich am Schmarrn in da Donau aus!</p>
          <p style="font-size: 0.8rem; margin-top: 10px; opacity: 0.8;">Desktop: Pfeile | Mobile: Wischen</p>
          <button @click="initGame">{{ t('game.start') }}</button>
        </div>

        <div v-if="gameState === 'gameOver'" class="overlay-content">
          <h2 style="color: #ff4444; margin-bottom: 5px;">{{ t('game.gameOver') }}</h2>
          <p>Level: {{ level }} / {{ TOTAL_LEVELS }}</p>
          <p>Score: {{ score }}</p>
          <button @click="initGame">No amoi!</button>
        </div>

        <div v-if="gameState === 'win'" class="overlay-content">
          <h2 style="color: #44ff44; margin-bottom: 10px;">🏆 {{ t('game.win') }}</h2>
          <p>Du hosd an NATinator bsiegt!</p>
          <p style="color: #ffd700; font-weight: bold; margin-top: 10px;">🐗 NAT-Modus freigschaltet!</p>
          <button @click="emit('close')">Zruck zur Website</button>
        </div>

        <div v-if="gameState === 'playing'" class="game-stats">
          <div class="stats-left">
            <span class="level-badge">{{ t('game.level') }} {{ level }}/{{ TOTAL_LEVELS }}</span>
            <span v-if="level === TOTAL_LEVELS" class="boar-alert">🐗 BOAR RAIN! 🐗</span>
          </div>
          <span class="score-display">Score: {{ score }}</span>
        </div>
        
        <!-- Progress Bar -->
        <div v-if="gameState === 'playing'" class="progress-container">
          <div class="progress-bar" :style="{ width: (score / (TOTAL_LEVELS * 500 + 500)) * 100 + '%' }"></div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.game-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 2000;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(0,0,0,0.8);
}

.game-window {
  background: #c0c0c0;
  border: 3px solid;
  border-color: #ffffff #808080 #808080 #ffffff;
  padding: 4px;
  width: 420px;
}

.game-header {
  background: #000080;
  color: white;
  padding: 4px 8px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
  margin-bottom: 4px;
}

.game-header button {
  background: #c0c0c0;
  border: 2px solid;
  border-color: #ffffff #808080 #808080 #ffffff;
  padding: 0 6px;
  cursor: pointer;
  color: black;
}

.canvas-container {
  position: relative;
  border: 2px solid #000;
}

canvas {
  display: block;
  background: #1e3a8a;
}

.overlay-content {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0,0,0,0.7);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: white;
  text-align: center;
  padding: 20px;
}

.overlay-content h2 { margin-bottom: 20px; }

.overlay-content button {
  background: #c0c0c0;
  border: 3px solid;
  border-color: #ffffff #808080 #808080 #ffffff;
  padding: 10px 20px;
  font-weight: bold;
  cursor: pointer;
  margin-top: 20px;
}

.game-stats {
  position: absolute;
  top: 10px;
  left: 10px;
  right: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: white;
  font-weight: bold;
  background: rgba(0,0,0,0.6);
  padding: 8px 12px;
  pointer-events: none;
  font-size: 0.9rem;
}

.stats-left {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.level-badge {
  color: #fbbf24;
}

.boar-alert {
  color: #ff4444;
  font-size: 0.7rem;
  animation: blink 0.5s infinite;
}

@keyframes blink {
  50% { opacity: 0; }
}

.progress-container {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 4px;
  background: rgba(0,0,0,0.3);
}

.progress-bar {
  height: 100%;
  background: #4ade80;
  transition: width 0.3s;
}

@media (max-width: 450px) {
  .game-window {
    width: 95vw;
  }
  .canvas-container {
    width: 100%;
  }
  canvas {
    width: 100%;
    height: auto;
  }
}
</style>
