/* geocode.jsx — REAL Bulgarian address / place search via the keyless Photon (Komoot) geocoder,
   biased to Sofia. Powers the Search screen. Returns [{ name, sub, at:[lat,lng], d }].
   Handles Cyrillic natively (Photon's default response uses local names). */

const PHOTON = 'https://photon.komoot.io/api/';
const SOFIA = { lat: 42.6977, lon: 23.3219, bbox: '23.18,42.60,23.46,42.78' };

function gcHav(a, b) {
  const R = 6371000, toR = (x) => x * Math.PI / 180;
  const dLat = toR(b[0] - a[0]), dLng = toR(b[1] - a[1]);
  const s = Math.sin(dLat / 2) ** 2 + Math.cos(toR(a[0])) * Math.cos(toR(b[0])) * Math.sin(dLng / 2) ** 2;
  return 2 * R * Math.asin(Math.sqrt(s));
}
const gcKm = (m) => (m / 1000).toFixed(1).replace('.', ',') + ' км';

function labelOf(p) {
  const street = p.street ? (p.housenumber ? `${p.street} ${p.housenumber}` : p.street) : null;
  const name = p.name || street || p.city || 'Без име';
  const parts = [];
  if (street && street !== name) parts.push(street);
  if (p.district) parts.push(p.district);
  else if (p.city && p.city !== name) parts.push(p.city);
  return { name, sub: parts.join(' · ') || p.city || 'София' };
}

// Current location via the browser Geolocation API (works on https:// and localhost).
window.getMyLocation = function () {
  return new Promise((resolve, reject) => {
    if (!navigator.geolocation) return reject(new Error('geolocation unavailable'));
    navigator.geolocation.getCurrentPosition(
      (pos) => resolve([pos.coords.latitude, pos.coords.longitude]),
      (err) => reject(err),
      // small maximumAge so the "you are here" dot reflects a FRESH GPS fix, not a stale cached one
      { enableHighAccuracy: true, timeout: 9000, maximumAge: 5000 }
    );
  });
};

// Reverse-geocode a coordinate to a Bulgarian place label via Photon's /reverse endpoint.
// Best-effort: returns '' on any failure so callers can fall back to raw coords.
window.reverseGeocode = async function (lat, lng) {
  try {
    const res = await fetch(`${PHOTON}reverse?lat=${lat}&lon=${lng}&limit=1`);
    if (!res.ok) return '';
    const j = await res.json();
    const f = (j.features || [])[0];
    if (!f) return '';
    const { name, sub } = labelOf(f.properties || {});
    return sub && sub !== name ? `${name} · ${sub}` : name;
  } catch (e) { return ''; }
};

window.geocodeSearch = async function (q) {
  const query = (q || '').trim();
  if (query.length < 2) return [];
  const start = (window.VR_ENDPOINTS && window.VR_ENDPOINTS.start) || [SOFIA.lat, SOFIA.lon];
  const url = `${PHOTON}?q=${encodeURIComponent(query)}&lat=${SOFIA.lat}&lon=${SOFIA.lon}`
    + `&bbox=${SOFIA.bbox}&limit=6`;
  const res = await fetch(url);
  if (!res.ok) throw new Error('photon http ' + res.status);
  const j = await res.json();
  return (j.features || []).map((f) => {
    const c = f.geometry && f.geometry.coordinates;
    if (!c) return null;
    const at = [c[1], c[0]];
    const { name, sub } = labelOf(f.properties || {});
    return { name, sub, at, d: gcKm(gcHav(start, at)) };
  }).filter(Boolean);
};
