import { ref } from 'vue'
import { useGameStore } from '@/stores/game'

export function useCameraControls(scene: Phaser.Scene): any {
  const gameStore = useGameStore()
  const camera = ref(scene.cameras.main)
  const isDragging = ref(false)
  let pointerDownTimer: number | null = null
  let pointerUpTimer: number | null = null

  const DRAG_DELAY = 150
  const MOVE_RESET_DELAY = 100

  function onPointerDown(pointer: Phaser.Input.Pointer) {
    if (pointer.event instanceof MouseEvent || pointer.event.altKey) {
      pointerDownTimer = setTimeout(() => {
        isDragging.value = true
        gameStore.setMovingCamera(true)
      }, DRAG_DELAY)
    }
  }

  function onPointerUp() {
    if (pointerDownTimer) {
      clearTimeout(pointerDownTimer)
      pointerDownTimer = null
    }
    isDragging.value = false

    if (pointerUpTimer) {
      clearTimeout(pointerUpTimer)
    }

    pointerUpTimer = setTimeout(() => {
      gameStore.setMovingCamera(false)
    }, MOVE_RESET_DELAY)
  }

  scene.input.on(Phaser.Input.Events.POINTER_DOWN, onPointerDown)
  scene.input.on(Phaser.Input.Events.POINTER_UP, onPointerUp)

  return {
    camera,
    isDragging
  }
}
