<template>
  <Tiles :key="zoneStore.zone?.id ?? 0" @tilemap:create="tileMap = $event" />
  <Objects />
  <Characters v-if="tileMap" :tilemap="tileMap as Phaser.Tilemaps.Tilemap" />
</template>

<script setup lang="ts">
import { useGameStore } from '@/stores/game'
import { useZoneStore } from '@/stores/zone'
import { onBeforeMount, onBeforeUnmount, ref, watch } from 'vue'
import type { Character as CharacterT, Zone as ZoneT, ExtendedCharacter as ExtendedCharacterT } from '@/types'
import Tiles from '@/components/zone/Tiles.vue'
import Objects from '@/components/zone/Objects.vue'
import Characters from '@/components/zone/Characters.vue'

const gameStore = useGameStore()
const zoneStore = useZoneStore()

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

type zoneLoadData = {
  zone: ZoneT
  characters: CharacterT[]
}

gameStore.connection?.emit('zone:characterJoin', { zoneId: gameStore.character?.zoneId }, (response: zoneLoadData) => {
  zoneStore.setZone(response.zone)
  zoneStore.setCharacters(response.characters)
})

// Event listeners
gameStore.connection?.on('zone:teleport', (data: zoneLoadData) => {
  if (zoneStore.zone?.id === data.zone.id) return
  tileMap.value = null;
  zoneStore.setZone(data.zone)
  zoneStore.setCharacters(data.characters)
})

gameStore.connection?.on('zone:character:join', (data: ExtendedCharacterT) => {
  zoneStore.addCharacter(data)
})

gameStore.connection?.on('zone:character:leave', (character_id: number) => {
  zoneStore.removeCharacter(character_id)
})

gameStore.connection?.on('character:move', (data: ExtendedCharacterT) => {
  zoneStore.updateCharacter(data)
})

watch(() => zoneStore.zone, (newZone) => {
  console.log('Zone changed:', newZone)
}, { deep: true })

onBeforeMount(() => {

});

onBeforeUnmount(() => {
  gameStore.connection?.off('zone:teleport')
  gameStore.connection?.off('zone:character:join')
  gameStore.connection?.off('zone:character:leave')
  gameStore.connection?.off('character:move')
});
</script>
