<template>
  <Tiles @tilemap:create="tileMap = $event" />
  <Objects v-if="tileMap" :tilemap="tileMap as Phaser.Tilemaps.Tilemap" />
  <EventTiles v-if="tileMap" :tilemap="tileMap as Phaser.Tilemaps.Tilemap" />

  <Toolbar @save="save" />

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

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

<script setup lang="ts">
import { onBeforeMount, onUnmounted, ref } from 'vue'
import { useScene } from 'phavuer'
import { useGameStore } from '@/stores/gameStore'
import { useZoneEditorStore } from '@/stores/zoneEditorStore'
import { loadAssets } from '@/composables/zoneComposable'
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 Tiles from '@/components/gameMaster/zoneEditor/Tiles.vue'
import Objects from '@/components/gameMaster/zoneEditor/Objects.vue'
import EventTiles from '@/components/gameMaster/zoneEditor/EventTiles.vue'

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

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

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)
  })
}

onBeforeMount(async () => {
  await gameStore.fetchAllZoneAssets()
  await loadAssets(scene)
})

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