<template>
  <Teleport to="body">
    <Modal v-if="isModalOpen" @modal:close="() => zoneEditorStore.setTool('move')" :isModalOpen="true" :modal-width="645" :modal-height="260">
      <template #modalHeader>
        <h3 class="m-0 font-medium shrink-0">Tiles</h3>
        <div class="flex">
          <div class="w-full flex gap-1.5 flex-row">
            <div>
              <label class="mb-1.5 font-titles hidden" for="search">Search...</label>
              <input @mousedown.stop class="input-cyan" type="text" name="search" placeholder="Search" />
            </div>
          </div>
        </div>
      </template>
      <template #modalBody>
        <div class="m-[15px]">
          <div class="flex flex-wrap gap-2.5">
            <img
              class="w-[64px] h-[32px] cursor-pointer border-2 border-solid border-transparent transition ease duration-300"
              src="/assets/zone/blank_tile.png"
              alt="Blank tile"
              @click="zoneEditorStore.setSelectedTile('blank_tile')"
              :class="{ 'border-2 border-solid border-red': zoneEditorStore.selectedTile && zoneEditorStore.selectedTile === 'blank_tile' }"
            />
            <img
              class="w-[64px] h-[32px] cursor-pointer border-2 border-solid border-transparent transition ease duration-300"
              v-for="(tile, index) in zoneEditorStore.tileList"
              :key="index"
              :src="`${config.server_endpoint}/assets/tiles/${tile}.png`"
              alt="Tile"
              @click="zoneEditorStore.setSelectedTile(tile)"
              :class="{ 'border-2 border-solid border-red': 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 isModalOpen = ref(false)
const zoneEditorStore = useZoneEditorStore()

onMounted(async () => {
  isModalOpen.value = true
  socket.connection.emit('gm:tile:list', {}, (response: string[]) => {
    zoneEditorStore.tileList = response
  })
})
</script>
