<template>
  <Image texture="waypoint" :x="waypoint.x" :y="waypoint.y" :visible="waypoint.visible" />
</template>

<script setup lang="ts">
import { Image, useScene } from 'phavuer'
import { onBeforeUnmount, ref, watch } from 'vue'
import config from '@/config'
import { getTile, tileToWorldXY } from '@/services/zone'
import { useZoneStore } from '@/stores/zone'
import { useZoneEditorStore } from '@/stores/zoneEditor'

const zoneStore = useZoneStore();
const zoneEditorStore = useZoneEditorStore();
const scene = useScene()
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

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

  waypoint.value.visible = true

  // Convert tile coordinates to world coordinates
  const worldPoint = tileToWorldXY(props.layer, pointer_tile.x, pointer_tile.y)
  waypoint.value.x = worldPoint.position_x
  waypoint.value.y = worldPoint.position_y + config.tile_size.y + 15
}

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

// Zone camera system
function dragZone (pointer: Phaser.Input.Pointer) {
  if (!pointer.isDown) return
  cam.scrollX -= (pointer.x - pointer.prevPosition.x) / cam.zoom
  cam.scrollY -= (pointer.y - pointer.prevPosition.y) / cam.zoom
}
let cam = scene.cameras.main
scene.input.on(Phaser.Input.Events.POINTER_MOVE, dragZone)

watch(
  () => zoneEditorStore.tool, () => {
    // @TODO : change to zone for when loading other maps
   if (zoneEditorStore.tool === 'move') {
     scene.input.on(Phaser.Input.Events.POINTER_MOVE, dragZone)
   } else {
     scene.input.off(Phaser.Input.Events.POINTER_MOVE, dragZone)
   }
  }, { deep: true }
)

// Unload funcs
onBeforeUnmount(() => {
  scene.input.off(Phaser.Input.Events.POINTER_MOVE, onPointerMove)
  scene.input.off(Phaser.Input.Events.POINTER_MOVE, dragZone)
})
</script>
