// location.js — AUTO geolocation with high accuracy + fallback Parung

export async function detectLocation(timeoutMs = 5000) {
  return new Promise((resolve) => {

    // fallback koordinat Parung
    const fallback = { 
      lat: -6.3940, 
      lon: 106.7330, 
      label: "Parung" 
    };

    // jika browser tidak mendukung
    if (!navigator.geolocation) {
      resolve(fallback);
      return;
    }

    let finished = false;

    navigator.geolocation.getCurrentPosition(
      async (pos) => {
        if (finished) return;
        finished = true;

        let label = "Lokasi Anda";

        try {
          // reverse geocoding (lebih akurat dari IP)
          const resp = await fetch(
            `https://nominatim.openstreetmap.org/reverse?lat=${pos.coords.latitude}&lon=${pos.coords.longitude}&format=json`
          );

          const data = await resp.json();

          label =
            data.address?.city ||
            data.address?.town ||
            data.address?.village ||
            "Lokasi Anda";
        } catch (e) {
          // ignore reverse lookup error, pakai label default
        }

        resolve({
          lat: pos.coords.latitude,
          lon: pos.coords.longitude,
          label
        });
      },

      // onError → fallback Parung
      () => {
        if (!finished) {
          finished = true;
          resolve(fallback);
        }
      },

      {
        timeout: timeoutMs,
        enableHighAccuracy: true, // 📌 mode presisi
        maximumAge: 0
      }
    );

    // jika 5 detik tidak ada jawaban → fallback Parung
    setTimeout(() => {
      if (!finished) {
        finished = true;
        resolve(fallback);
      }
    }, timeoutMs + 300);
  });
}
