const { ajaxurl } = multi_inventory;

let loader = '<div class="wcmlim-chase-wrapper">';
loader += '<div class="wcmlim-chase">';
loader += '<div class="wcmlim-chase-dot"></div>';
loader += '<div class="wcmlim-chase-dot"></div>';
loader += '<div class="wcmlim-chase-dot"></div>';
loader += '<div class="wcmlim-chase-dot"></div>';
loader += '<div class="wcmlim-chase-dot"></div>';
loader += '<div class="wcmlim-chase-dot"></div>';
loader += "</div>";
loader += "</div>";

jQuery(".currentLoc").click(() => {
  DetectLocationCloudflare();

  $(".elementIdGlobal, #elementIdGlobal").on("click", function () {
    $(".wclimlocsearch").show();
  });
});

var DetectLocationCloudflare = (function () {

  var showLocationFromCloudflare = function () {
    // Use Cloudflare IP detection AJAX call
    jQuery.ajax({
      url: ajaxurl,
      type: "post", 
      data: {
        action: "wcmlim_cloudflare_ip_location",
        nonce: multi_inventory.security,
      },
      dataType: "json",
      success: function(response) {
        if (jQuery.trim(response.status) === "true") {
          var latitude = response.user_lat || response.detected_lat;
          var longitude = response.user_lng || response.detected_lng;
          
          if (latitude && longitude) {
            wcmlim_nearby_location = latitude + "," + longitude;
            
            setcookie("autodetect_independent_wcmlim_nearby_location", wcmlim_nearby_location, 1);
            setcookie("wcmlim_selected_location", response.loc_key);
            setcookie("wcmlim_selected_location_termid", response.loc_term_id);
            setcookie("wcmlim_user_lat", latitude);
            setcookie("wcmlim_user_lng", longitude);
            setcookie("wcmlim_selected_location_regid", response.secgrouploc);

            // sorted_by_proximity contain the array of location id sorted by proximity
            if (response.sorted_by_proximity) {
              setcookie("wcmlim_location_priority_order_by_user_loc", response.sorted_by_proximity);
            }
            
            jQuery(
              'select[name="wcmlim_change_sl_to"] option[value="' +
                response.secgrouploc +
                '"]'
            ).attr("selected", "selected");
            jQuery('select[name="wcmlim_change_sl_to"]').trigger("change");

            var dunit = response.loc_dis_unit;
            if (dunit !== null) {
              var spu = dunit.split(" ");
              var n = spu[0];
            }
            if (response.locServiceRadius != "") {
              if (response.locServiceRadius <= n || !n) {
                if (response.cookie != "") {
                  Swal.fire({
                    title: "Oops...!",
                    text: "We are not serving this area...",
                    icon: "info",
                    timer: 2000,
                    showConfirmButton: false,
                  }).then(function () {
                    jQuery("#lc-switch-form").submit();
                  });
                } else {
                  jQuery(".postcode-checker-response").html();
                }
              }
            } else {
              jQuery(".postcode-checker-change").show();
              jQuery(".postcode-checker-div")
                .removeClass("postcode-checker-div-show")
                .addClass("postcode-checker-div-hide");
              if (wcmlim_nearby_location) {
                var wcmlim_nearby_location_str = wcmlim_nearby_location.replace(
                  /%20/g,
                  " "
                );
                jQuery(".postcode-checker-response").html(
                  `<i class="fa fa-search"></i> ${wcmlim_nearby_location_str}`
                );
              } else {
                var wcmlim_nearby_location_str = wcmlim_nearby_location.replace(
                  /%20/g,
                  " "
                );

                jQuery(".postcode-checker-response").html(
                  `<i class="fa fa-search"></i> ${wcmlim_nearby_location_str}`
                );
              }
              const locationCookie = getCookie("wcmlim_selected_location");

              if (locationCookie == null) {
                /* do cookie doesn't exist stuff; */
                var gLocation = response.loc_key;
                jQuery("#wcmlim-change-lc-select")
                  .find(":selected")
                  .removeAttr("selected");
                jQuery(".rselect_location input[name=select_location]").prop(
                  "checked",
                  false
                );
                jQuery(".rlist_location input[name=wcmlim_change_lc_to]").prop(
                  "checked",
                  false
                );
                jQuery("#select_location")
                  .find(":selected")
                  .removeAttr("selected");
                jQuery("#wcmlim-change-lc-select")
                  .find(`option[value="${gLocation}"]`)
                  .prop("selected", true);
                jQuery(`#select_location option[value='${gLocation}']`).prop(
                  "selected",
                  true
                );
                jQuery(
                  ".rselect_location input[name=select_location][value=" +
                    gLocation +
                    "]"
                ).prop("checked", true);
                jQuery(
                  ".rlist_location input[name=wcmlim_change_lc_to][value=" +
                    gLocation +
                    "]"
                ).prop("checked", true);
                setcookie("wcmlim_selected_location", gLocation);
                jQuery("#lc-switch-form").submit();
              } else {
                // if(locationCookie != jQuery.trim(response.location)){
                var gLocation = response.loc_key;
                jQuery("#wcmlim-change-lc-select")
                  .find(":selected")
                  .removeAttr("selected");
                jQuery("#select_location")
                  .find(":selected")
                  .removeAttr("selected");
                jQuery(".rselect_location input[name=select_location]").prop(
                  "checked",
                  false
                );
                jQuery(".rlist_location input[name=wcmlim_change_lc_to]").prop(
                  "checked",
                  false
                );
                jQuery("#wcmlim-change-lc-select")
                  .find(`option[value="${gLocation}"]`)
                  .prop("selected", true);
                jQuery(`#select_location option[value='${gLocation}']`).prop(
                  "selected",
                  true
                );
                jQuery(
                  ".rselect_location input[name=select_location][value=" +
                    gLocation +
                    "]"
                ).prop("checked", true);
                jQuery(
                  ".rlist_location input[name=wcmlim_change_lc_to][value=" +
                    gLocation +
                    "]"
                ).prop("checked", true);
              }
            }
          }
          jQuery(".wclimlocsearch").hide();

          // Only reload if the location has actually changed
          const currentSelectedLocation = getCookie("wcmlim_selected_location");
          if (currentSelectedLocation !== response.loc_key) {
            window.location.reload();
          }
        } else {
          console.error("Cloudflare IP location detection failed:", response.message);
        }
      },
      error: function (data, textStatus, errorThrown) {
        console.error("Cloudflare IP detection error:", errorThrown);
        jQuery(".postcode-checker-response").empty();
      }
    });
  };

  return function () {
    showLocationFromCloudflare();
  };
})();

var autodetect_wcmlim_nearby_location = getCookie(
  "autodetect_independent_wcmlim_nearby_location"
);

var selected_location = getCookie("wcmlim_selected_location_termid");
var user_lat = getCookie("wcmlim_user_lat");
var user_lng = getCookie("wcmlim_user_lng");

// Only trigger autodetect if we don't have both coordinates and a selected location
if ((user_lat == "" || user_lng == "") && selected_location == "") {
    DetectLocationCloudflare();
}

function getCookie(cname) {
  let name = cname + "=";
  let ca = document.cookie.split(";");
  for (let i = 0; i < ca.length; i++) {
    let c = ca[i];
    while (c.charAt(0) == " ") {
      c = c.substring(1);
    }
    if (c.indexOf(name) == 0) {
      return c.substring(name.length, c.length);
    }
  }
  return "";
}

function setcookie(name, value, days) {
  let date = new Date();
  if (days) {
    date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
    var expires = `; expires=${date.toUTCString()}`;
  } else {
    date.setTime(date.getTime() + 1 * 24 * 60 * 60 * 1000);
    var expires = `; expires=${date.toUTCString()}`;
  }
  document.cookie = `${name}=${value}${expires};path=/`;
}