<template>
  <CreateZone v-if="zoneEditorStore.isCreateZoneModalShown" />
  <Modal :is-modal-open="zoneEditorStore.isZoneListModalShown" @modal:close="() => zoneEditorStore.toggleZoneListModal()" :is-resizable="false" :modal-width="300" :modal-height="360" :bg-style="'none'">
    <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-7 h-7 z-50 flex items-center justify-center" @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>
</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>
