<template>
  <CreateZone v-if="zoneEditorStore.isCreateZoneModalShown" />

  <Teleport to="body">
    <Modal @modal:close="() => zoneEditorStore.toggleZoneListModal()" :is-resizable="false" :is-modal-open="true" :modal-width="300" :modal-height="360">
      <template #modalHeader>
        <h3 class="text-lg text-white">Zones</h3>
      </template>
      <template #modalBody>
        <div class="my-4 mx-auto">
          <div class="text-center mb-4 px-2 flex gap-2.5">
            <button class="btn-cyan py-1.5 min-w-[calc(50%_-_5px)]" @click="fetchZones">Refresh</button>
            <button class="btn-cyan py-1.5 min-w-[calc(50%_-_5px)]" @click="() => zoneEditorStore.toggleCreateZoneModal()">New</button>
          </div>
          <div class="relative p-2.5 cursor-pointer flex gap-y-2.5 gap-x-5 flex-wrap" v-for="(zone, index) in zoneEditorStore.zoneList" :key="zone.id">
            <div class="absolute left-0 top-0 w-full h-px bg-gray-500" v-if="index === 0"></div>
            <div class="flex gap-3 items-center w-full" @click="() => loadZone(zone.id)">
              <span>{{ zone.name }}</span>
              <span class="ml-auto gap-1 flex">
                <button class="btn-red w-11 h-11 z-50" @click.stop="() => deleteZone(zone.id)">X</button>
              </span>
            </div>
            <div class="absolute left-0 bottom-0 w-full h-px bg-gray-500"></div>
          </div>
        </div>
      </template>
    </Modal>
  </Teleport>
</template>

<script setup lang="ts">
import { onMounted } from 'vue'
import { useGameStore } from '@/stores/gameStore'
import Modal from '@/components/utilities/Modal.vue'
import type { Zone } from '@/types'
import { useZoneEditorStore } from '@/stores/zoneEditorStore'
import CreateZone from '@/components/gameMaster/zoneEditor/partials/CreateZone.vue'

const gameStore = useGameStore()
const zoneEditorStore = useZoneEditorStore()

onMounted(async () => {
  fetchZones()
})

function fetchZones() {
  gameStore.connection?.emit('gm:zone_editor:zone:list', {}, (response: Zone[]) => {
    zoneEditorStore.setZoneList(response)
  })
}

function loadZone(id: number) {
  gameStore.connection?.emit('gm:zone_editor:zone:request', { zoneId: id }, (response: Zone) => {
    zoneEditorStore.setZone(response)
  })
  zoneEditorStore.toggleZoneListModal()
}

function deleteZone(id: number) {
  gameStore.connection?.emit('gm:zone_editor:zone:delete', { zoneId: id }, () => {
    fetchZones()
  })
}
</script>
