<template>
  <div>
    <canvas ref="tileCanvas" :width="tileWidth" :height="tileHeight" style="display: none;"></canvas>
    <div class="tiles">
      <img
        v-for="(tile, index) in tiles"
        :key="index"
        :src="tile"
        alt="Tile"
        @click="selectTile(index)"
        :class="{ selected: selectedTile === index }"
      />
    </div>
  </div>
</template>

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

const tileWidth = 64;
const tileHeight = 32;
const tiles = ref([]);
const selectedTile = ref(null);
const tileCanvas = ref(null);

// Hardcoded image path
const imagePath = '/assets/tiles/default.png';

const loadImage = (src) => {
  return new Promise((resolve) => {
    const img = new Image();
    img.onload = () => resolve(img);
    img.src = src;
  });
};

const splitTiles = (img) => {
  const canvas = tileCanvas.value;
  const ctx = canvas.getContext('2d');

  const tilesetWidth = img.width;
  const tilesetHeight = img.height;
  const columns = Math.floor(tilesetWidth / tileWidth);
  const rows = Math.floor(tilesetHeight / tileHeight);

  tiles.value = [];
  selectedTile.value = null;

  for (let row = 0; row < rows; row++) {
    for (let col = 0; col < columns; col++) {
      const x = col * tileWidth;
      const y = row * tileHeight;

      ctx.clearRect(0, 0, tileWidth, tileHeight);
      ctx.drawImage(img, x, y, tileWidth, tileHeight, 0, 0, tileWidth, tileHeight);

      const tileDataURL = canvas.toDataURL();
      tiles.value.push(tileDataURL);
    }
  }
};

const selectTile = (index) => {
  selectedTile.value = index;
};

onMounted(async () => {
  const img = await loadImage(imagePath);
  splitTiles(img);
});

/**
 * Resources:
 * https://codepen.io/Xymota/pen/gOOyxWB
 * https://www.dynetisgames.com/2022/06/09/update-how-to-manage-big-isometric-maps-with-phaser-3-5/
 * https://stackoverflow.com/questions/11533606/javascript-splitting-a-tileset-image-to-be-stored-in-2d-image-array
 */
</script>

<style lang="scss">
.tiles {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.tiles img {
  width: 64px;
  height: 32px;
  cursor: pointer;
  border: 2px solid transparent;
  transition: border 0.3s ease;
}

.tiles img.selected {
  border: 2px solid #ff0000;
}
</style>