function  getCountryFromIP()  {
  fetch("https://freeipapi.com/api/json/")
    .then((response)  =>  response.json())
    .then((data)  =>  {
      const  country  =  data.countryName;
      const  countryElement  =  document.getElementById("Country");
      if  (countryElement)  {
        countryElement.value  =  country;
        console.log(`Country:  ${country}  set  based  on  IP  location`);
      }  else  {
    console.warn("No  element  found  with  ID:  Country");
  }
    });
}

function setCountryBasedOnLocation() {
  // Step 1: Prefill using Free IP API based on the IP address
  getCountryFromIP();
  // Step 2: If the user accepts, update using GPS-based location
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(
      (position) => {
        const { latitude, longitude } = position.coords;
        fetch(`https://nominatim.openstreetmap.org/reverse?lat=${latitude}&lon=${longitude}&format=jsonv2`)
          .then((response) => response.json())
          .then((data) => {
            const address = data.address;
            const country = address.country;
            const countryElement = document.getElementById("Country");
            if (countryElement) {
              countryElement.value = country;
              console.log(`Country: ${country} updated based on geolocation location`);
            } else {
              console.warn("No element found with ID: Country");
            }
          })
          .catch((error) => console.error("Error fetching country data based on GPS:", error));
      },
      (error) => {
        console.error("Geolocation error:", error.message);
      }
    );
  } else {
    console.error("Geolocation is not supported by this browser.");
  }
}

window.onload = function () {
  setCountryBasedOnLocation();
};