import { useMapEditorComposable } from '@/composables/useMapEditorComposable'
import { computed, type Ref } from 'vue'
import { useBaseControlsComposable } from './useBaseControlsComposable'

export function useMapEditorControlsComposable(scene: Phaser.Scene, layer: Phaser.Tilemaps.TilemapLayer, waypoint: Ref<{ visible: boolean; x: number; y: number }>, camera: Phaser.Cameras.Scene2D.Camera) {
  const mapEditor = useMapEditorComposable()
  const baseHandlers = useBaseControlsComposable(scene, layer, waypoint, camera)
  const isMoveTool = computed(() => mapEditor.tool.value === 'move')

  function handlePointerDown(pointer: Phaser.Input.Pointer) {
    if (isMoveTool.value || pointer.event.shiftKey) {
      baseHandlers.startDragging(pointer)
    }
  }

  function handlePointerMove(pointer: Phaser.Input.Pointer) {
    if (isMoveTool.value || pointer.event.shiftKey) {
      baseHandlers.handleDragMap(pointer)
    }
    baseHandlers.updateWaypoint(pointer.worldX, pointer.worldY)
  }

  function handlePointerUp(pointer: Phaser.Input.Pointer) {
    baseHandlers.stopDragging()
  }

  const setupControls = () => {
    scene.input.on(Phaser.Input.Events.POINTER_DOWN, handlePointerDown)
    scene.input.on(Phaser.Input.Events.POINTER_MOVE, handlePointerMove)
    scene.input.on(Phaser.Input.Events.POINTER_UP, handlePointerUp)
    scene.input.on(Phaser.Input.Events.POINTER_WHEEL, baseHandlers.handleZoom)
  }

  const cleanupControls = () => {
    scene.input.off(Phaser.Input.Events.POINTER_DOWN, handlePointerDown)
    scene.input.off(Phaser.Input.Events.POINTER_MOVE, handlePointerMove)
    scene.input.off(Phaser.Input.Events.POINTER_UP, handlePointerUp)
    scene.input.off(Phaser.Input.Events.POINTER_WHEEL, baseHandlers.handleZoom)
  }

  return { setupControls, cleanupControls }
}
