<script setup lang="ts">
import { computed, type ComputedRef } from 'vue'
import type { FieldSize } from '@/scripts/interfaces/FieldSize.ts'

defineEmits(['clickOnGameField'])
const props = defineProps<{ gameState: number[][] }>()
let currentSelectionIndex = defineModel<number | null>('currentSelectionIndex', {
  required: true,
})

const gameFieldSize: ComputedRef<FieldSize> = computed(() => ({
  x: props.gameState[0]?.length || 7,
  y: props.gameState.length || 6,
}))

function translateNumberToImage(num: number): string {
  switch (num) {
    case 1:
      return '/Game/Gamefield_Red.svg'
    case 2:
      return '/Game/Gamefield_Yellow.svg'
    default:
      return '/Game/Gamefield_Empty.svg'
  }
}

function selectionUpdate(index: number, active: boolean) {
  const newValue = active ? index : null

  if (
    (active && currentSelectionIndex.value !== index) ||
    (!active && currentSelectionIndex.value === index)
  ) {
    currentSelectionIndex.value = newValue
  }
}
</script>

<template>
  <div class="game-container">
    <div
      id="gameField"
      class="d-flex flex-column"
      style="gap: 0"
      @click="$emit('clickOnGameField')"
    >
      <div id="selectors" class="d-flex flex-row" style="gap: 0">
        <v-img
          v-for="index in gameFieldSize.x"
          :key="index"
          :src="
            index - 1 == currentSelectionIndex ? '/Arrow/Arrow_Red.svg' : '/Arrow/Arrow_White.svg'
          "
          class="game-cell"
          :aspect-ratio="1"
          cover
          @mouseenter="selectionUpdate(index - 1, true)"
          @mouseleave="selectionUpdate(index - 1, false)"
        />
      </div>
      <div v-for="row in props.gameState" class="d-flex flex-row" style="gap: 0">
        <v-img
          v-for="(field, index) in row"
          :key="index"
          :src="translateNumberToImage(field)"
          class="game-cell"
          :aspect-ratio="1"
          cover
          @mouseenter="selectionUpdate(index, true)"
          @mouseleave="selectionUpdate(index, false)"
        />
      </div>
    </div>
  </div>
</template>

<style scoped>
.game-container {
  height: calc(100dvh - var(--v-layout-top));
  width: 100%;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
}

.game-cell {
  --cols: v-bind('gameFieldSize.x || 7');
  --rows: v-bind('gameFieldSize.y || 6');
  width: min(calc(85vw / var(--cols)), calc((100dvh - var(--v-layout-top)) * 0.85 / var(--rows)));
  height: min(calc(85vw / var(--cols)), calc((100dvh - var(--v-layout-top)) * 0.85 / var(--rows)));
  flex: 0 0 auto;
  user-select: none;
}

#gameField {
  cursor: cell;
}
</style>