import { type Ref } from 'vue'
import { getTile, tileToWorldXY } from '@/services/zone'
import { useGameStore } from '@/stores/game'
import config from '@/config'

export function useGamePointerHandlers(scene: Phaser.Scene, layer: Phaser.Tilemaps.TilemapLayer, waypoint: Ref<{ visible: boolean; x: number; y: number }>, camera: Ref<Phaser.Cameras.Scene2D.Camera>) {
  const gameStore = useGameStore()

  function updateWaypoint(pointer: Phaser.Input.Pointer) {
    const { x: px, y: py } = camera.value.getWorldPoint(pointer.x, pointer.y)
    const pointerTile = getTile(px, py, layer)

    waypoint.value.visible = !!pointerTile
    if (pointerTile) {
      const worldPoint = tileToWorldXY(layer, pointerTile.x, pointerTile.y)
      waypoint.value.x = worldPoint.positionX
      waypoint.value.y = worldPoint.positionY + config.tile_size.y + 15
    }
  }

  function handlePointerMove(pointer: Phaser.Input.Pointer) {
    updateWaypoint(pointer)
  }

  function clickTile(pointer: Phaser.Input.Pointer) {
    const { x: px, y: py } = camera.value.getWorldPoint(pointer.x, pointer.y)
    const pointerTile = getTile(px, py, layer)

    if (pointerTile) {
      gameStore.connection?.emit('character:move', {
        positionX: pointerTile.x,
        positionY: pointerTile.y
      })
    }
  }

  function handleZoom({ event, deltaY }: Phaser.Input.Pointer) {
    if (event instanceof WheelEvent && event.shiftKey) {
      scene.scale.setZoom(scene.scale.zoom - deltaY * 0.01)
      camera.value = scene.cameras.main
    }
  }

  const setupPointerHandlers = () => {
    scene.input.on(Phaser.Input.Events.POINTER_UP, clickTile)
    scene.input.on(Phaser.Input.Events.POINTER_MOVE, handlePointerMove)
    scene.input.on(Phaser.Input.Events.POINTER_WHEEL, handleZoom)
  }

  const cleanupPointerHandlers = () => {
    scene.input.off(Phaser.Input.Events.POINTER_UP, clickTile)
    scene.input.off(Phaser.Input.Events.POINTER_MOVE, handlePointerMove)
    scene.input.off(Phaser.Input.Events.POINTER_WHEEL, handleZoom)
  }

  return { setupPointerHandlers, cleanupPointerHandlers }
}
