<template>
  <ZoneTiles @tileMap:create="tileMap = $event" />
  <ZoneObjects v-if="tileMap" :tilemap="tileMap as Phaser.Tilemaps.Tilemap" />
  <ZoneEventTiles v-if="tileMap" :tilemap="tileMap as Phaser.Tilemaps.Tilemap" />

  <Toolbar @save="save" @clear="clear" />

  <ZoneList />
  <TileList />
  <ObjectList />

  <ZoneSettings />
  <TeleportModal />
</template>

<script setup lang="ts">
import { onUnmounted, ref } from 'vue'
import { useGameStore } from '@/stores/gameStore'
import { useZoneEditorStore } from '@/stores/zoneEditorStore'
import { type Zone } from '@/types'
// Components
import Toolbar from '@/components/gameMaster/zoneEditor/partials/Toolbar.vue'
import TileList from '@/components/gameMaster/zoneEditor/partials/TileList.vue'
import ObjectList from '@/components/gameMaster/zoneEditor/partials/ObjectList.vue'
import ZoneSettings from '@/components/gameMaster/zoneEditor/partials/ZoneSettings.vue'
import ZoneList from '@/components/gameMaster/zoneEditor/partials/ZoneList.vue'
import TeleportModal from '@/components/gameMaster/zoneEditor/partials/TeleportModal.vue'
import ZoneTiles from '@/components/gameMaster/zoneEditor/zonePartials/ZoneTiles.vue'
import ZoneObjects from '@/components/gameMaster/zoneEditor/zonePartials/ZoneObjects.vue'
import ZoneEventTiles from '@/components/gameMaster/zoneEditor/zonePartials/ZoneEventTiles.vue'

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

const tileMap = ref(null as Phaser.Tilemaps.Tilemap | null)

function clear() {
  if (!zoneEditorStore.zone) return

  // Clear objects, event tiles and tiles
  zoneEditorStore.zone.zoneObjects = []
  zoneEditorStore.zone.zoneEventTiles = []
  zoneEditorStore.triggerClearTiles()
}

function save() {
  if (!zoneEditorStore.zone) return

  const data = {
    zoneId: zoneEditorStore.zone.id,
    name: zoneEditorStore.zoneSettings.name,
    width: zoneEditorStore.zoneSettings.width,
    height: zoneEditorStore.zoneSettings.height,
    tiles: zoneEditorStore.zone.tiles,
    pvp: zoneEditorStore.zone.pvp,
    zoneEffects: zoneEditorStore.zone.zoneEffects.map(({ id, zoneId, effect, strength }) => ({ id, zoneId, effect, strength })),
    zoneEventTiles: zoneEditorStore.zone.zoneEventTiles.map(({ id, zoneId, type, positionX, positionY, teleport }) => ({ id, zoneId, type, positionX, positionY, teleport })),
    zoneObjects: zoneEditorStore.zone.zoneObjects.map(({ id, zoneId, objectId, depth, isRotated, positionX, positionY }) => ({ id, zoneId, objectId, depth, isRotated, positionX, positionY }))
  }

  if (zoneEditorStore.isSettingsModalShown) {
    zoneEditorStore.toggleSettingsModal()
  }

  gameStore.connection?.emit('gm:zone_editor:zone:update', data, (response: Zone) => {
    zoneEditorStore.setZone(response)
  })
}

onUnmounted(() => {
  zoneEditorStore.reset()
})
</script>
