import { mockTrees, type WishingTree } from './data'

export function getNearbyTrees(
  lng: number,
  lat: number,
  _maxDistance = 5000,
  _limit = 50
) {
  // Mock 模式：返回所有许愿树，按距离排序（不过滤距离）
  const results: (WishingTree & { distance: number; isInRange: boolean })[] = []

  for (const tree of mockTrees) {
    if (!tree.isActive) continue
    const dist = haversine(lng, lat, tree.longitude, tree.latitude)
    results.push({
      ...tree,
      distance: Math.round(dist),
      isInRange: dist <= tree.radius,
    })
  }

  results.sort((a, b) => a.distance - b.distance)
  return Promise.resolve(results)
}

export function getTreeById(id: number) {
  const tree = mockTrees.find((t) => t.id === id)
  return Promise.resolve(tree || null)
}

function haversine(lng1: number, lat1: number, lng2: number, lat2: number): number {
  const R = 6371000
  const toRad = (d: number) => (d * Math.PI) / 180
  const dLat = toRad(lat2 - lat1)
  const dLng = toRad(lng2 - lng1)
  const a = Math.sin(dLat / 2) ** 2 + Math.cos(toRad(lat1)) * Math.cos(toRad(lat2)) * Math.sin(dLng / 2) ** 2
  return R * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a))
}
