(function ($) {
  "use strict";

  var HorizontalSearchHandler = function ($scope, $) {
    var map_api_key = felan_template_vars.map_api_key,
      map_type = felan_template_vars.map_type,
      search_form = $scope.find(".felan-form-location"),
      input = search_form.find(".input-search-location"),
      field_select = search_form.find(".felan-select2");

    if (!search_form.length) {
      return;
    }

    $("body").on(
      "mousedown",
      ".felan-form-location .icon-arrow i",
      function (e) {
        e.preventDefault();
        var select2_container = search_form.find(".select2.select2-container");
        if (select2_container.hasClass("select2-container--open")) {
          field_select.select2("close");
        } else {
          field_select.val(null).trigger("change");
          field_select.select2("open");
        }
      }
    );

    field_select.on("select2:select", function (e) {
      var data = e.params.data;
      input.val(data.text).trigger("change");
    });

    // Geo Location
    var locationBtn = search_form.find(".icon-location svg");
    if (!locationBtn.length) {
      return;
    }

    locationBtn.on("click", () => {
      // Check if geolocation is supported by the browser
      if ("geolocation" in navigator) {
        navigator.geolocation.getCurrentPosition(
          (position) => {
            // Get the latitude and longitude from the position object
            var latitude = position.coords.latitude;
            var longitude = position.coords.longitude;
            var url;

            if (map_type === "google_map") {
              url = `https://maps.googleapis.com/maps/api/geocode/json?latlng=${latitude},${longitude}&key=${map_api_key}`;
            } else if (map_type === "mapbox") {
              url = `https://api.mapbox.com/geocoding/v5/mapbox.places/${longitude},${latitude}.json?access_token=${map_api_key}`;
            } else if (map_type === "openstreetmap") {
              url = `https://nominatim.openstreetmap.org/reverse?lat=${latitude}&lon=${longitude}&format=jsonv2`;
            } else {
              console.error("Invalid map_type: ", map_type);
              return;
            }

            $.ajax({
              url: url,
              type: "GET",
              success: (result) => {
                var address = "";

                if (map_type === "google_map") {
                  if (result && result.status === "OK" && result.results && Array.isArray(result.results) && result.results.length > 0) {
                    address = result.results[0].formatted_address;
                  } else {
                    console.error("Google Maps error: ", result ? result.status : "No response");
                    return;
                  }
                } else if (map_type === "mapbox") {
                  if (result && result.features && Array.isArray(result.features) && result.features.length > 0) {
                    address = result.features[0].place_name ||
                      (result.features[0].context && Array.isArray(result.features[0].context) && result.features[0].context.length > 2
                        ? result.features[0].context[2].text
                        : result.features[0].text);
                  } else {
                    console.error("Mapbox error: No features found");
                    return;
                  }
                } else if (map_type === "openstreetmap") {
                  if (result && result.display_name) {
                    address = result.display_name;
                  } else {
                    console.error("OpenStreetMap error: No display_name found");
                    return;
                  }
                }

                if (address) {
                  input.val(address).trigger("change");
                }
              },
              error: (xhr, status, error) => {
                console.error("AJAX error details:", {
                  status: xhr.status,
                  statusText: xhr.statusText,
                  responseText: xhr.responseText,
                  error: error
                });

                // Thông báo lỗi cụ thể hơn
                if (xhr.status === 0) {
                  alert("Unable to connect to server. Please check your network connection.");
                } else if (xhr.status === 403) {
                  alert("API key is invalid or expired.");
                } else if (xhr.status === 429) {
                  alert("API rate limit exceeded. Please try again later.");
                } else {
                  alert("Unable to retrieve location. Please try again.");
                }
              },
            });
          },
          (error) => {
            console.error("Geolocation error: ", error.message, error.code);
            if (error.code === error.PERMISSION_DENIED) {
              alert("Please allow location access to use this feature.");
            } else if (error.code === error.POSITION_UNAVAILABLE) {
              alert("Location information is unavailable.");
            } else if (error.code === error.TIMEOUT) {
              alert("The request to get user location timed out.");
            } else {
              alert("An unknown error occurred while retrieving location.");
            }
          },
          {
            enableHighAccuracy: true,
            timeout: 15000,
            maximumAge: 300000, 
          }
        );
      } else {
        alert("Geolocation is not supported by your browser");
      }
    });
  };

  $(window).on("elementor/frontend/init", function () {
    elementorFrontend.hooks.addAction(
      "frontend/element_ready/felan-search-horizontal.default",
      HorizontalSearchHandler
    );
    elementorFrontend.hooks.addAction(
      "frontend/element_ready/felan-search-vertical.default",
      HorizontalSearchHandler
    );
  });
})(jQuery);
