import { computed, type Ref, watch } from 'vue'
import { useZoneEditorStore } from '@/stores/zoneEditor'
import { useGamePointerHandlers } from '@/composables/pointerHandlers/useGamePointerHandlers'
import { useZoneEditorPointerHandlers } from '@/composables/pointerHandlers/useZoneEditorPointerHandlers'
import { useGameStore } from '@/stores/game'

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

  const gameHandlers = useGamePointerHandlers(scene, layer, waypoint, camera, isDragging)
  const zoneEditorHandlers = useZoneEditorPointerHandlers(scene, layer, waypoint, camera, isDragging)

  let currentHandlers = computed(() => zoneEditorStore.active ? zoneEditorHandlers : gameHandlers)

  const setupPointerHandlers = () => {
    currentHandlers.value.setupPointerHandlers()
  }

  const cleanupPointerHandlers = () => {
    currentHandlers.value.cleanupPointerHandlers()
  }

  watch(() => zoneEditorStore.active, (newValue, oldValue) => {
    if (newValue !== oldValue) {
      cleanupPointerHandlers()
      setupPointerHandlers()
    }
  })

  return { setupPointerHandlers, cleanupPointerHandlers }
}