import "./../style.scss";

(function ($) {
  'use strict';

  const applyReload = () => {
    $.ajax({
      method: 'POST',
      url: repetito.ajax_url,
      accepts: "application/json",
      data: {
        nonce: repetito.nonce,
        action: 'repetito_apply_reload',
      },
      success: function (result) {
        let repetitoDiv = $('#repetito, div[class*="repetito-fee"]');
        if (result.data.show == 0) {
          repetitoDiv.hide();
        } else {
          repetitoDiv.show();
        }
      },
    });
  }

  // Watch for the input to appear in the DOM
  const observer = new MutationObserver((mutations) => {
    // Disconnect observer to prevent recursive calls
    observer.disconnect();

    mutations.forEach((mutation) => {
      if (mutation.addedNodes.length) {
        const inputs = $(mutation.addedNodes).find('input[data-name="repetito_fee"]');
        inputs.each(function(index, input) {
          const div = wc.wcSettings.getSetting('repetito/div', '').replace('{NAME}', repetito_l10n.name).replace('{DESC}', repetito_l10n.desc).replace('{DESC_LONG}', repetito_l10n.desc_long);
          $(input).parent().after(div)
        });
      }
    });

    // Reconnect observer after changes are done
    observer.observe(document.body, {
      childList: true,
      subtree: true
    });
  });

  // Start observing the document
  observer.observe(document.body, {
    childList: true,
    subtree: true
  });

  // Initial load
  if (repetito.ajax_url) {
    applyReload();
  }

  // Handle changes to the input
  $(document).on('change', 'input[data-name="repetito_fee"], input[name="repetito_fee"]', function() {
    const fee = $(this).prop('checked') === true ? 1 : 0;

    $.ajax({
      method: 'POST',
      url: repetito.ajax_url,
      accepts: "application/json",
      data: {
        nonce: repetito.nonce,
        action: 'repetito_apply_fee',
        applyFee: fee,
      },
      success: function (result) {
        $('body').trigger('update_checkout');
        wp.data.dispatch('wc/store/cart').invalidateResolutionForStore();
      },
    });
  });

  // Handle checkout updates
  $(document).on('updated_checkout', function () {
    applyReload();
  });

})(jQuery);