<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="10.5" :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="20.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="4.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)" play="walk" />
  </Container>
</template>

<script lang="ts" setup>
import { Container, Rectangle, Sprite, Text, useScene } from 'phavuer'
import { onBeforeMount, 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) 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 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')
  }
}

/**
 * Resources:
 * https://www.youtube.com/watch?v=9sWrGohw9qo
 * https://jsfiddle.net/juwalbose/pu0gt7nc/
 *
 */
</script>
