<template>
  <Container>
    <Rectangle :x="tileToWorldX(layer, props.character?.position_x, props.character?.position_y)" :y="tileToWorldY(layer, props.character?.position_x, props.character?.position_y)" :origin-x="0.5" :origin-y="16" :fillColor="0xffffff" :width="74" :height="8">
      <Rectangle :x="tileToWorldX(layer, props.character?.position_x, props.character?.position_y)" :y="tileToWorldY(layer, props.character?.position_x, props.character?.position_y)" :origin-x="0.5" :origin-y="31.5" :fillColor="0x09ad19" :width="70" :height="4" />
    </Rectangle>
    <Text
      @create="createText"
      :text="props.character?.name"
      :x="tileToWorldX(layer, props.character?.position_x, props.character?.position_y)"
      :y="tileToWorldY(layer, props.character?.position_x, props.character?.position_y)"
      :origin-x="0.5"
      :origin-y="7.5"
      :style="{
        fontFamily: 'Helvetica, Arial',
        color: '#FFF',
        fontSize: '14px'
      }"
    />
    <Sprite ref="sprite" :x="tileToWorldX(layer, props.character?.position_x, props.character?.position_y)" :y="tileToWorldY(layer, props.character?.position_x, props.character?.position_y)" :origin-y="1" play="walk" />
  </Container>
</template>

<script lang="ts" setup>
import { Container, Rectangle, Sprite, Text, useScene } from 'phavuer'
import { onBeforeMount, onBeforeUnmount, onMounted, ref } from 'vue'
import { useGameStore } from '@/stores/game'
import { type Character as CharacterT } from '@/types'
import { getTile, tileToWorldX, tileToWorldXY, tileToWorldY } from '@/services/zone'

const gameStore = useGameStore()

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

const scene = useScene()
const isSelf = props.character?.id === gameStore.character?.id

const createText = (text: Phaser.GameObjects.Text) => {
  text.setLetterSpacing(1.5)
}

onBeforeMount(() => {
  if (isSelf) setupSelf()
})

function setupSelf() {
  scene.input.on(Phaser.Input.Events.POINTER_UP, onPointerClick)
}

function onPointerClick(pointer: Phaser.Input.Pointer) {
  if (!isSelf || gameStore.isMovingCamera) return

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

  const pointer_tile = getTile(px, py, props.layer) as Phaser.Tilemaps.Tile
  if (!pointer_tile) {
    return
  }

  gameStore.connection?.emit('character:move', { position_x: pointer_tile.x, position_y: pointer_tile.y })

  // Directions for player sprite + 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')
  }
}

onBeforeUnmount(() => {
  if (!isSelf) return
  scene.input.off(Phaser.Input.Events.POINTER_UP, onPointerClick)
})
</script>
