<template>
  <Image texture="waypoint" :x="waypoint.x" :y="waypoint.y" :visible="waypoint.visible" />
</template>
<script setup lang="ts">
import { Image, useScene } from 'phavuer'
import { ref } from 'vue'
import config from '@/config'

const scene = useScene()
const pointer_tile = ref(undefined)
const props = defineProps({
  layer: Phaser.Tilemaps.TilemapLayer
})
const waypoint = ref({
  visible: false,
  x: 0,
  y: 0
})

function onPointerMove(pointer: Phaser.Input.Pointer) {
  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)
  if (pointer_tile.value) {
    waypoint.value.visible = true

    // Convert tile coordinates to world coordinates
    const worldPoint = props.layer.tileToWorldXY(pointer_tile.value.x, pointer_tile.value.y)
    waypoint.value.x = worldPoint.x + config.tile_size.y
    waypoint.value.y = worldPoint.y + config.tile_size.y
  } else {
    waypoint.value.visible = false
  }
}

scene.input.on(Phaser.Input.Events.POINTER_MOVE, onPointerMove)

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

  // console.log(x,y);
  // console.log('tile', tile);

  if (!tile) {
    return undefined
  }

  return tile
}

function getTileAt(iX: number, iY: number, layer: Phaser.Tilemaps.TilemapLayer): Phaser.Tilemaps.Tile | undefined {
  const tile: Phaser.Tilemaps.Tile = layer.getTileAt(iX, iY)
  if (tile) return tile
  else return undefined
}

function getDepth(tile: Phaser.Tilemaps.Tile): number {
  return 32
}
</script>
