export function haversineKm(lat1, lon1, lat2, lon2) {
  const R = 6371;
  const toRad = (deg) => (deg * Math.PI) / 180;
  const dLat = toRad(lat2 - lat1);
  const dLon = toRad(lon2 - lon1);
  const a =
    Math.sin(dLat / 2) * Math.sin(dLat / 2) +
    Math.cos(toRad(lat1)) *
      Math.cos(toRad(lat2)) *
      Math.sin(dLon / 2) *
      Math.sin(dLon / 2);
  const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
  return R * c;
}

export function getViewFromMap(map) {
  const bounds = map.getBounds();
  const center = bounds.getCenter();
  const ne = bounds.getNorthEast();

  let radiusKm = haversineKm(center.lat, center.lng, ne.lat, ne.lng);

  if (!Number.isFinite(radiusKm) || radiusKm <= 0) {
    radiusKm = 750;
  }

  radiusKm = Math.min(Math.max(radiusKm, 25), 1000);

  return {
    center: [center.lng, center.lat],
    radiusKm,
  };
}

export function getCoords(post) {
  const lat =
    post.lat ??
    post.latitude ??
    post.location?.lat ??
    (Array.isArray(post.coords) ? post.coords[1] : null);

  const lon =
    post.lon ??
    post.lng ??
    post.location?.lng ??
    (Array.isArray(post.coords) ? post.coords[0] : null);

  if (typeof lat === "number" && typeof lon === "number") return [lon, lat];
  return null;
}
