import type { Map as MapboxMap } from 'mapbox-gl'

interface FlyThroughSpaceOptions {
  targetCenter: [number, number]
  targetZoom?: number
  totalDuration?: number
  spaceZoom?: number
}

export const useMapboxFlyAnimation = () => {
  const isAnimating = ref(false)

  const flyThroughSpace = (
    map: MapboxMap,
    options: FlyThroughSpaceOptions
  ): Promise<void> => {
    const {
      targetCenter,
      targetZoom = 6,
      totalDuration = 6000,
      spaceZoom = 1.5
    } = options

    // Stop any ongoing animation
    if (isAnimating.value) {
      map.stop()
    }
    isAnimating.value = true

    const currentCenter = map.getCenter()

    // Calculate midpoint for smoother arc
    const midLng = (currentCenter.lng + targetCenter[0]) / 2
    const midLat = (currentCenter.lat + targetCenter[1]) / 2

    return new Promise((resolve) => {
      // Phase 1: Zoom out to space
      map.flyTo({
        center: [midLng, midLat],
        zoom: spaceZoom,
        pitch: 0,
        bearing: 0,
        duration: totalDuration * 0.4,
        essential: true,
        curve: 1.2,
        easing: (t) => t * (2 - t) // easeOutQuad
      })

      // Phase 2: Fly to target after zoom out completes
      setTimeout(() => {
        map.flyTo({
          center: targetCenter,
          zoom: targetZoom,
          pitch: 45,
          bearing: -17.6,
          duration: totalDuration * 0.6,
          essential: true,
          curve: 1.42,
          easing: (t) => 1 - Math.pow(1 - t, 3) // easeOutCubic
        })

        map.once('moveend', () => {
          isAnimating.value = false
          resolve()
        })

        // Fallback timeout in case moveend doesn't fire
        setTimeout(() => {
          isAnimating.value = false
          resolve()
        }, totalDuration * 0.7)
      }, totalDuration * 0.4)
    })
  }

  const setupGlobeAtmosphere = (map: MapboxMap) => {
    map.setFog({
      color: 'rgb(186, 210, 235)',
      'high-color': 'rgb(36, 92, 223)',
      'horizon-blend': 0.02,
      'space-color': 'rgb(11, 11, 25)',
      'star-intensity': 0.6
    })
  }

  return {
    flyThroughSpace,
    setupGlobeAtmosphere,
    isAnimating
  }
}
