(function (ns) {
  'use strict';

  const radians = value => value * Math.PI / 180;
  const degrees = value => value * 180 / Math.PI;
  const normalizeDegrees = value => (value % 360 + 360) % 360;

  ns.Distance = {
    meters(a, b) {
      const dLat = radians(b.lat - a.lat);
      const dLon = radians(b.lon - a.lon);
      const h = Math.sin(dLat / 2) ** 2
        + Math.cos(radians(a.lat)) * Math.cos(radians(b.lat)) * Math.sin(dLon / 2) ** 2;
      return 2 * 6371000 * Math.asin(Math.sqrt(h));
    },

    bearing(a, b) {
      const lat1 = radians(a.lat);
      const lat2 = radians(b.lat);
      const dLon = radians(b.lon - a.lon);
      const y = Math.sin(dLon) * Math.cos(lat2);
      const x = Math.cos(lat1) * Math.sin(lat2)
        - Math.sin(lat1) * Math.cos(lat2) * Math.cos(dLon);
      return normalizeDegrees(degrees(Math.atan2(y, x)));
    },

    normalizeDegrees,

    format(meters) {
      return meters < 1000 ? `${Math.round(meters)} m` : `${(meters / 1000).toFixed(1)} km`;
    }
  };
}(globalThis.Wegwichtel));
