<template>
  <Container>
    <!-- @TODO : Text position X must be calculated based on the character name length -->
    <Text
      :text="props.character?.name"
      :x="position.x - 40"
      :y="position.y - 80"
      :style="{
        fontFamily: 'Helvetica, Arial',
        color: '#42B883',
        fontSize: '20px',
        fontStyle: 'bold',
        strokeThickness: 8,
        stroke: '#213547'
      }"
    />
    <Sprite ref="sprite" texture="character" :x="position.x" :y="position.y" />
  </Container>
</template>

<script lang="ts" setup>
import { Container, onPostUpdate, onPreUpdate, Sprite, Text, useScene } from 'phavuer'
import { onMounted, reactive, type Ref, ref } from 'vue'
import config from '@/config'
import { useSocketStore } from '@/stores/socket'
import { type Character as CharacterT } from '@/types'

const socket = useSocketStore()

const props = defineProps({
  layer: Phaser.Tilemaps.TilemapLayer,
  character: Object as () => CharacterT
})

const scene = useScene()
const position = reactive({ x: props.character.position_x, y: props.character.position_y })
const isSelf = props.character.id === socket.character.id;

onMounted(() => {
  if (isSelf) setupSelf()

  if (!isSelf) {
  }
});

function setupSelf()
{
  scene.input.on(Phaser.Input.Events.POINTER_UP, onPointerClick)
  const pointer_tile = ref(undefined)
  function onPointerClick(pointer: Phaser.Input.Pointer) {
    if (!isSelf) return;

    const px = scene.cameras.main.worldView.x + pointer.x
    const py = scene.cameras.main.worldView.y + pointer.y

    pointer_tile.value = getTile(px, py, props.layer) as Phaser.Tilemaps.Tile
    if (pointer_tile.value) {
      const worldPoint = props.layer.tileToWorldXY(pointer_tile.value.x, pointer_tile.value.y)
      const position_x = worldPoint.x + config.tile_size.y
      const position_y = worldPoint.y
      socket.getConnection.emit('character:move', { position_x, position_y })
    }

    //Directions for player sprites + animations
    if (px < 0 && py > 0) {
      console.log('down left')
    } else if (px < 0 && py < 0) {
      console.log('top left')
    } else if (px > 0 && py > 0) {
      console.log('down right')
    } else if (px > 0 && py < 0) {
      console.log('top right')
    }
  }

  function getTile(x: number, y: number, layer: Phaser.Tilemaps.TilemapLayer): Phaser.Tilemaps.Tile | undefined {
    const tile: Phaser.Tilemaps.Tile = layer.getTileAtWorldXY(x, y)
    if (!tile) return undefined;
    return tile
  }
}

socket.getConnection.on('character:moved', (data: CharacterT) => {
  console.log('character:moved', data);
  if (data.id !== props.character.id) return; // Only update the character that moved
  position.x = data.position_x
  position.y = data.position_y
})
</script>
