<template>
  <MapTiles :key="mapStore.mapId" @tileMap:create="tileMap = $event" />
  <PlacedMapObjects v-if="tileMap" :key="mapStore.mapId" :tilemap="tileMap" />
  <Characters v-if="tileMap && mapStore.characters" :tilemap="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 PlacedMapObjects 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>()

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

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')
})
</script>
