(function ($) {
  let DSPILOTADMIN = {
    init: function () {
      this.bindEvents();
    },
    bindEvents: function () {
      
      // Disable pro options
      $(document).on('click', '#dspilot-form .select2-results__option', function(e){
         // Although select2 handles its own disabling, we ensure here for standard selects or initial load
      });
      // Initial check for selects
      $('#dspilot-form select option').each(function(){
         if($(this).text().indexOf('PRO Version') !== -1){
            $(this).prop('disabled', true);
         }
      });
      // If using Select2 or Chosen, we need to handle open events to disable options rendered dynamically
      $(document).on('#dspilot-form .select2:open', function(e) {
         // Wait for options to render
         setTimeout(function(){
            $('#dspilot-form .select2-results__option').each(function(){
                if($(this).text().indexOf('PRO Version') !== -1){
                   $(this).addClass('pro-disabled').attr('aria-disabled', 'true');
                   // Preventing click is harder on select2 elements directly, usually disabling in 'data' source is best but if source is HTML options, select2 respects disabled attribute.
                }
            });
         }, 0);
      });
      // Handle standard selects dynamically
      $(document).on('DOMNodeInserted', function(e){
         if($(e.target).is('select')) {
             $(e.target).find('option').each(function(){
                if($(this).text().indexOf('PRO Version') !== -1){
                    $(this).prop('disabled', true);
                }
             });
         }
      });

      // hidden fields if condition is not numeric
      $(document)
        .on(
          "click",
          "#dspilot-form .ui-accordion-header, #dspilot-form .dspilot-repeater-add",
          function (e) {
            e.preventDefault();

            let discountIndex = $(this).parent().index();
            //discountIndex = discountIndex - 1; // exclude first header

            let triggerElement = e.target;

            let newRepeaterItem = false;
            if ($(triggerElement).hasClass("dspilot-repeater-add")) {
              newRepeaterItem = true;
            }

            $(
              ".conditions-repeater .dspilot-repeater-wrapper .dspilot-repeater-item, .dspilot-field-group.products-filter .dspilot-repeater-wrapper .dspilot-repeater-item",
            ).each(function () {
              let conditionFieldWrapper = $(this).find(".condition-select");
              let selectField = $(this)
                .find(".condition-select select")
                .get(-1);
              let value = $(selectField).val().toLowerCase(); // make it case-insensitive

              //console.log("value", value);

              DSPILOTADMIN.updateFieldVisibility(
                value,
                selectField,
                newRepeaterItem,
                triggerElement,
              );

              $(selectField).change(function () {
                let value = $(this).val().toLowerCase();

                DSPILOTADMIN.updateFieldVisibility(
                  value,
                  selectField,
                  newRepeaterItem,
                  triggerElement,
                );
              });
            });

            // load variations if product is selected in BOGO Y product field
            let pid = $(".dspilot-field.bogo-y-product-select select").val();
            if (pid) DSPILOTADMIN.loadBogoYVariations(pid, discountIndex);
          },
        )
        .on(
          "change",
          ".dspilot-field.bogo-y-product-select select",
          function () {
            DSPILOTADMIN.loadBogoYVariations($(this).val());
          },
        );
    },
    updateFieldVisibility: function (
      value,
      selectField,
      newRepeaterItem,
      triggerElement,
    ) {
      const $wrapper = $(selectField).closest(".dspilot-repeater-item"); // more precise and efficient
      let $compareSelect = $wrapper.find(".compare-select select");

      if (newRepeaterItem) {
        $compareSelect = $(triggerElement)
          .parent()
          .find(
            ".dspilot-repeater-wrapper .dspilot-repeater-item:nth-last-child(1)",
          )
          .find(".compare-select select");
      }

      const $numberField = $wrapper.find(".value-number");
      const $textField = $wrapper.find(".value-text");

      const numericStrings = [
        "amount",
        "money",
        "money_spent",
        "quantity",
        "number",
        "weight",
        "subtotal",
        "subtotal of",
        "limit",
        "total",
        "maximum",
        "minimum",
        "max",
        "min",
        "height",
        "width",
        "length",
        "price",
        "stock",
      ];

      const textStrings = [
        "email",
        "user_meta",
        "product_meta",
        "coupons_applied",
        "shipping_postcode",
        "shipping_city",
      ];

      const questionsString = [
        "is_featured",
        "is_onsale",
        "is_trending",
        "is_top_seller",
        "is_top_earner",
        "is_most_viewed",
        "is_recently_viewed",
      ];

      const dependsOnFields = {
        "value-product": ["product_variations"],
        "value-products": [
          "quantity_of_products",
          "products_in_cart",
          "featured_products_in_cart",
          "onsale_products_in_cart",
          "bought_products",
          "bought_featured_products",
          "bought_onsale_products",
          "subtotal_of_products_include_tax",
          "subtotal_of_products_exclude_tax",
          "subtotal_of_onsale_products_include_tax",
          "subtotal_of_onsale_products_exclude_tax",
          "quantity_of_bought_products",
          "amount_of_bought_products",
          "products",
        ],
        "value-categories": [
          "product_categories_in_cart",
          "bought_product_categories",
          "quantity_of_bought_categories",
          "subtotal_of_categories_include_tax",
          "subtotal_of_categories_exclude_tax",
          "quantity_of_categories",
          "amount_of_bought_categories",
          "categories",
        ],
        "value-brands": [
          "product_brands_in_cart",
          "bought_product_brands",
          "quantity_of_bought_brands",
          "subtotal_of_brands_include_tax",
          "subtotal_of_brands_exclude_tax",
          "quantity_of_brands",
          "amount_of_bought_brands",
          "brands",
        ],
        "value-variations": [
          "product_variations_in_cart",
          "subtotal_of_variations_include_tax",
          "subtotal_of_variations_exclude_tax",
          "quantity_of_variations",
          "quantity_of_bought_variations",
          "amount_of_bought_variations",
          "variations",
        ],
      };

      const numericComparisonValues = [
        "equal_to",
        "less_than",
        "less_equal_to",
        "greater_than",
        "greater_equal_to",
      ];

      const questionComparisonValues = ["yes", "no"];

      const textComparisonValues = ["equal_to", "not_equal_to"];

      const isMatch = (arr) => arr.some((str) => value.includes(str));
      const isNumeric = isMatch(numericStrings);
      const isText = isMatch(textStrings);
      const isQuestion = isMatch(questionsString);

      // Reset fields
      $numberField.hide();
      $textField.hide();
      $compareSelect.find("option").hide(); // hide all first

      // Handle comparison & field display
      if (isNumeric) {
        numericComparisonValues.forEach((val) =>
          $compareSelect.find(`option[value="${val}"]`).show(),
        );
        $numberField.show();
        $compareSelect.val("greater_than");
      } else if (isQuestion) {
        $compareSelect.val("yes");
        questionComparisonValues.forEach((val) =>
          $compareSelect.find(`option[value="${val}"]`).show(),
        );
      } else if (isText) {
        textComparisonValues.forEach((val) =>
          $compareSelect.find(`option[value="${val}"]`).show(),
        );
        $textField.show();
        $compareSelect.val("equal_to");
      } else {
        $compareSelect.find("option").show(); // show all
        $numberField.hide();
        $compareSelect.val("in");
      }

      // Hide all dependent fields
      Object.keys(dependsOnFields).forEach((className) => {
        $wrapper.find(`.dspilot-field.${className}`).hide();
      });

      // Show based on matched dependency
      for (const [className, values] of Object.entries(dependsOnFields)) {
        if (values.includes(value)) {
          $wrapper.find(`.dspilot-field.${className}`).show();
        }
      }
    },
    loadBogoYVariations: function (pid, discountIndex = null) {
      const variationSelectField = $(
        ".dspilot-field.bogo-y-product-variations select",
      );

      DSPILOTADMIN.updateVariationField(
        pid,
        discountIndex,
        variationSelectField,
        function (success, data) {
          if (success && Object.keys(data).length > 0) {
            $(".dspilot-field.bogo-y-product-variations").removeClass(
              "dspilot-depend-hidden-custom",
            );
          } else {
            $(".dspilot-field.bogo-y-product-variations").addClass(
              "dspilot-depend-hidden-custom",
            );
          }
        },
      );
    },
    updateVariationField: function (
      pid,
      discountIndex,
      variationSelectField,
      callback,
    ) {
      //

      // Clear existing options
      variationSelectField.html("<option value='0'>Loading...</option>"); // clear existing options

      // get variations by ajax
      $.ajax({
        type: "post",
        url: dspilot_admin.ajax_url,
        data: {
          action: "dspilot_get_variations_by_product_ids",
          pid: pid,
          discountIndex: discountIndex,
          nonce: dspilot_admin.nonce,
        },
        success: function (response) {
          console.log("response", response);

          if (response.success) {
            const data = response.data;
            const variations = data.variations;
            const selectedValue = data.selected_variation;

            variationSelectField.empty(); // Clear existing options
            // Populate the select field
            Object.entries(variations).forEach(
              ([variationId, variationName]) => {
                variationSelectField.append(
                  // select first option as selected
                  `<option value="${variationId}" ${
                    selectedValue === variationId ? "selected" : ""
                  }>${variationName}</option>`,
                );
              },
            );

            callback && callback(response.success, variations);
          } else {
            console.warn("No variation data found");
          }
        },
      });
    },
  };

  $(document).ready(function () {
    DSPILOTADMIN.init();
  });
})(jQuery);
