<template>
  <Teleport to="body">
    <Modal v-if="isModalOpen" :isModalOpen="true" :closable="false" :modal-width="645" :modal-height="260">
      <template #modalHeader>
        <h3 class="modal-title">Walls</h3>
      </template>
      <template #modalBody>
        <canvas ref="canvas" :width="wallWidth" :height="wallHeight" style="display: none"></canvas>
        <div class="walls">
          <img v-for="(wall, index) in walls" :key="index" :src="wall" alt="Wall" @click="zoneEditorStore.setSelectedWall(index)" :class="{ selected: zoneEditorStore.selectedWall && zoneEditorStore.selectedWall === index }" />
        </div>
      </template>
    </Modal>
  </Teleport>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick } from 'vue'
import config from '@/config'
import Modal from '@/components/utilities/Modal.vue'
import { useZoneEditorStore } from '@/stores/zoneEditor'

const wallWidth = config.wall_size.x
const wallHeight = config.wall_size.y
const walls = ref<string[]>([])
const selectedWall = ref<number | null>(null)
const canvas = ref<HTMLCanvasElement | null>(null)
const isModalOpen = ref(false)
const zoneEditorStore = useZoneEditorStore()

// Hardcoded image path
const imagePath = '/assets/zone/walls.png'

const loadImage = (src: string): Promise<HTMLImageElement> => {
  return new Promise((resolve) => {
    const img = new Image()
    img.onload = () => resolve(img)
    img.src = src
  })
}

const splitWalls = (img: HTMLImageElement) => {
  if (!canvas.value) {
    console.error('Canvas not found')
    return
  }
  const ctx = canvas.value.getContext('2d')
  if (!ctx) {
    console.error('Failed to get canvas context')
    return
  }

  const wallsetWidth = img.width
  const wallsetHeight = img.height
  const columns = Math.floor(wallsetWidth / wallWidth)
  const rows = Math.floor(wallsetHeight / wallHeight)

  walls.value = []
  selectedWall.value = null

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

      ctx.clearRect(0, 0, wallWidth, wallHeight)
      ctx.drawImage(img, x, y, wallWidth, wallHeight, 0, 0, wallWidth, wallHeight)

      const wallDataURL = canvas.value.toDataURL()
      walls.value.push(wallDataURL)
    }
  }
}

const selectWall = (index: number) => {
  selectedWall.value = index
}

onMounted(async () => {
  isModalOpen.value = true
  const img = await loadImage(imagePath)
  await nextTick()
  splitWalls(img)
})
</script>

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

.walls img {
  width: 30px;
  height: 130px;
  cursor: pointer;
  border: 2px solid transparent;
  transition: border 0.3s ease;
}

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