<template>
  <Image :depth="2" 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 { storeToRefs } from 'pinia'
import config from '@/config'
import { getTile, tileToWorldXY } from '@/services/zone'
import { useZoneEditorStore } from '@/stores/zoneEditor'

const props = defineProps<{
  layer: Phaser.Tilemaps.TilemapLayer
}>()

const scene = useScene()
const zoneEditorStore = useZoneEditorStore()
const { tool } = storeToRefs(zoneEditorStore)

const waypoint = ref({
  visible: false,
  x: 0,
  y: 0
})

const cam = ref(scene.cameras.main)

function updateWaypoint(pointer: Phaser.Input.Pointer) {
  const { x: px, y: py } = scene.cameras.main.getWorldPoint(pointer.x, pointer.y)
  const pointerTile = getTile(px, py, props.layer) as Phaser.Tilemaps.Tile

  if (!pointerTile) {
    waypoint.value.visible = false
    return
  }

  const worldPoint = tileToWorldXY(props.layer, pointerTile.x, pointerTile.y)
  waypoint.value = {
    visible: true,
    x: worldPoint.position_x,
    y: worldPoint.position_y + config.tile_size.y + 15
  }
}

function dragZone(pointer: Phaser.Input.Pointer) {
  if (!pointer.isDown) return
  const { x, y, prevPosition } = pointer
  cam.value.scrollX -= (x - prevPosition.x) / cam.value.zoom
  cam.value.scrollY -= (y - prevPosition.y) / cam.value.zoom
}

function handleZoom(pointer: Phaser.Input.Pointer, _: any, __: any, deltaY: number) {
  if (pointer.event.altKey) {
    scene.scale.setZoom(scene.scale.zoom - deltaY * 0.01)
    cam.value = scene.cameras.main
  }
}

function setupEventListeners() {
  scene.input.on(Phaser.Input.Events.POINTER_MOVE, updateWaypoint)
  scene.input.on(Phaser.Input.Events.POINTER_WHEEL, handleZoom)

  scene.input.on(Phaser.Input.Events.POINTER_DOWN, (pointer: Phaser.Input.Pointer) => {
    if (pointer.event.altKey || tool.value === 'move') {
      scene.input.on(Phaser.Input.Events.POINTER_MOVE, dragZone)
    }
  })

  scene.input.on(Phaser.Input.Events.POINTER_UP, () => {
    scene.input.off(Phaser.Input.Events.POINTER_MOVE, dragZone)
  })
}

function cleanupEventListeners() {
  scene.input.off(Phaser.Input.Events.POINTER_MOVE, updateWaypoint)
  scene.input.off(Phaser.Input.Events.POINTER_MOVE, dragZone)
  scene.input.off(Phaser.Input.Events.POINTER_DOWN)
  scene.input.off(Phaser.Input.Events.POINTER_UP)
  scene.input.off(Phaser.Input.Events.POINTER_WHEEL, handleZoom)
}

setupEventListeners()

watch(tool, (newTool) => {
  if (newTool === 'move') {
    scene.input.on(Phaser.Input.Events.POINTER_MOVE, dragZone)
  } else {
    scene.input.off(Phaser.Input.Events.POINTER_MOVE, dragZone)
  }
})

onBeforeUnmount(cleanupEventListeners)
</script>
