import { defineStore } from 'pinia'
import { ref } from 'vue'
import { getUserLocation } from '@/utils/geo'

type LocationFn = () => Promise<{ lng: number; lat: number }>

export const useLocationStore = defineStore('location', () => {
  const lng = ref<number | null>(null)
  const lat = ref<number | null>(null)
  const located = ref(false)
  let timer: ReturnType<typeof setInterval> | null = null
  let overriddenFn: LocationFn | null = null

  function setLocationFn(fn: LocationFn) {
    overriddenFn = fn
  }

  function setLocation(longitude: number, latitude: number) {
    lng.value = longitude
    lat.value = latitude
    located.value = true
  }

  async function refreshLocation() {
    try {
      const fn = overriddenFn || getUserLocation
      const pos = await fn()
      setLocation(pos.lng, pos.lat)
    } catch {
      // 保留上次位置
    }
  }

  function startWatch(intervalMs = 5000) {
    stopWatch()
    refreshLocation()
    timer = setInterval(refreshLocation, intervalMs)
  }

  function stopWatch() {
    if (timer) {
      clearInterval(timer)
      timer = null
    }
  }

  return { lng, lat, located, setLocation, setLocationFn, refreshLocation, startWatch, stopWatch }
})
