function setText(id, text) {
  const el = document.getElementById(id);
  if (el) el.textContent = text;
}

function showManualAddressTip(message) {
  const tip = document.querySelector("[data-manual-address-tip]");
  const addressInput = document.querySelector("[data-manual-address]") || document.getElementById("id_address");
  if (tip) {
    tip.hidden = false;
  }
  if (message) {
    setText("form-location-status", message);
  }
  if (addressInput) {
    addressInput.focus({ preventScroll: true });
    addressInput.scrollIntoView({ behavior: "smooth", block: "center" });
  }
}

function requestLocation(callback, statusId, unavailableCallback) {
  if (!navigator.geolocation) {
    setText(statusId, "Location is not supported by this browser. You can type or paste the address instead.");
    if (unavailableCallback) unavailableCallback();
    return;
  }
  setText(statusId, "Requesting location…");
  navigator.geolocation.getCurrentPosition(
    (pos) => {
      const lat = pos.coords.latitude.toFixed(6);
      const lng = pos.coords.longitude.toFixed(6);
      setText(statusId, `Captured ${lat}, ${lng}`);
      callback(lat, lng);
    },
    () => {
      setText(statusId, "Location permission was denied or unavailable. Type or paste the address instead.");
      if (unavailableCallback) unavailableCallback();
    },
    { enableHighAccuracy: true, timeout: 10000 }
  );
}

document.addEventListener("click", (event) => {
  const action = event.target?.dataset?.action;
  if (action === "request-location") {
    requestLocation(() => {}, "location-status");
  }
  if (action === "request-notifications") {
    if (!window.Notification) {
      setText("notification-status", "Notifications are not supported here.");
      return;
    }
    Notification.requestPermission().then((permission) => {
      setText("notification-status", `Notification permission: ${permission}`);
    });
  }
  if (action === "manual-address") {
    showManualAddressTip("Manual address mode: paste or type the property address below.");
  }
  if (action === "fill-current-location") {
    requestLocation((lat, lng) => {
      const latInput = document.getElementById("id_latitude");
      const lngInput = document.getElementById("id_longitude");
      if (latInput) latInput.value = lat;
      if (lngInput) lngInput.value = lng;
    }, "form-location-status", () => {
      showManualAddressTip();
    });
  }
  if (action === "use-location-for-list") {
    requestLocation((lat, lng) => {
      document.querySelector("[data-user-lat]").value = lat;
      document.querySelector("[data-user-lng]").value = lng;
      const sort = document.getElementById("sort");
      if (sort) sort.value = "distance";
      const form = document.querySelector("[data-distance-form]");
      if (form) form.submit();
    }, "list-location-status");
  }
});
