<template>
  <Teleport to="body">
    <Modal v-if="isModalOpen" :isModalOpen="true" :closable="false" :modal-width="645" :modal-height="260">
      <template #modalHeader>
        <h3 class="modal-title">Tiles</h3>
      </template>
      <template #modalBody>
        <div class="container tiles">
          <div class="tiles">
            <img v-for="(tile, index) in tiles" :key="index" :src="tile" alt="Tile" @click="zoneEditorStore.setSelectedTile(tile)" :class="{ selected: zoneEditorStore.selectedTile && zoneEditorStore.selectedTile === tile }" />
          </div>
        </div>
      </template>
    </Modal>
  </Teleport>
</template>

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

const socket = useSocketStore()
const tiles = ref<string[]>([])
const isModalOpen = ref(false)
const zoneEditorStore = useZoneEditorStore()

onMounted(async () => {
  isModalOpen.value = true
  socket.connection.emit('gm:tile:list', {}, (response: string[]) => {
    tiles.value = response.map((tile) => `${config.server_endpoint}/assets/tiles/${tile}`)
  })
})
</script>

<style lang="scss">
@import '@/assets/scss/main.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 $red;
}
</style>
