<template>
  <MapTiles :key="mapStore.mapId" @tileMap:create="tileMap = $event" />
  <!--  <MapObjects v-if="tileMap" :tilemap="tileMap as Phaser.Tilemaps.Tilemap" />-->
  <Characters v-if="tileMap" :tilemap="tileMap as Phaser.Tilemaps.Tilemap" />
</template>

<script setup lang="ts">
import type { MapCharacter, mapLoadData, UUID } from '@/application/types'
import Characters from '@/components/game/map/Characters.vue'
import MapTiles from '@/components/game/map/MapTiles.vue'
import MapObjects from '@/components/game/map/PlacedMapObjects.vue'
import { useGameStore } from '@/stores/gameStore'
import { useMapStore } from '@/stores/mapStore'
import { onUnmounted, shallowRef } from 'vue'

const gameStore = useGameStore()
const mapStore = useMapStore()

const tileMap = shallowRef<Phaser.Tilemaps.Tilemap>()

onUnmounted(() => {
  mapStore.reset()
  gameStore.connection?.off('map:character:teleport')
  gameStore.connection?.off('map:character:join')
  gameStore.connection?.off('map:character:leave')
  gameStore.connection?.off('map:character:move')
})

// Event listeners
gameStore.connection?.on('map:character:teleport', async (data: mapLoadData) => {
  mapStore.setMapId(data.mapId)
  mapStore.setCharacters(data.characters)
})

gameStore.connection?.on('map:character:join', async (data: MapCharacter) => {
  mapStore.addCharacter(data)
})

gameStore.connection?.on('map:character:leave', (characterId: UUID) => {
  mapStore.removeCharacter(characterId)
})

gameStore.connection?.on('map:character:move', (data: { characterId: UUID; positionX: number; positionY: number; rotation: number; isMoving: boolean }) => {
  mapStore.updateCharacterPosition(data)
})
</script>
