jQuery(document).ready(function($) {

  function idfInitializeTippy() {
    // Initialize Tippy for each tooltip element
    tippy('.idf-tooltip', {
      trigger: 'mouseenter', // Trigger the tooltip on mouse enter
      allowHTML: true, // Allow HTML tags in the tooltip content
      interactive: true, // Keep the tooltip open when hovering over the tooltip content
      interactiveBorder: 20, // Adds a small buffer to prevent the tooltip from closing when quickly moving to the content
      delay: [100, 300] // Optional: add delay on showing and hiding the tooltip (show delay, hide delay)
    });
  }

  $(document).on('idfInitializeTippy', function () {
    idfInitializeTippy();
  });

  idfInitializeTippy();

  idfInitializeSelect2();

  function idfInitializeSelect2() {
    // Target all select fields in your plugin
    $('select').each(function () {
      // Check if the select element already has select2 initialized
      if (!$(this).hasClass('select2-hidden-accessible') && !$(this).hasClass('idf-disable-select2') ) {
        $(this).select2({
          placeholder: $(this).attr('placeholder') || 'Select an option', // Use the placeholder if available
          allowClear: true, // Allow clearing selections
          dropdownCssClass: 'select2-dropdown-always-below', // Custom CSS class
          width: '280px',
          theme: "classic"
        });
        $(this).trigger('change');
      }
    });
  }

  // Open modal when gear icon is clicked
  $('.idf-modal-trigger').on('click', function () {
    const modalRoute = $(this).data('modal');
    // Launch modal and load settings via AJAX
    $.ajax({
      url: idf_ajax_object.ajax_url,
      method: 'POST',
      data: {
        action: 'load_feature_settings',
        feature_key: modalRoute,
        _wpnonce: idf_ajax_object.ajax_nonce,
      },
      beforeSend: function () {
        // Optionally show a loader or placeholder before loading the content
        $('#idf-settings-modal').html('<div class="loader">Loading...</div>');
      },
      success: function (response) {
        if (response.success) {
          // Insert the response (modal content) into the modal container
          $('#idf-settings-modal').html(response.data.content);

          // Trigger specific events based on the loaded modal
          switch (modalRoute) {
            case 'paypal_settings':
              $(document).trigger('paypalSettingsModalLoaded');
              break;
            case 'stripe_legacy_settings':
            case 'stripe_checkout_settings':
              $(document).trigger('stripeSettingsModalLoaded');
              $(document).trigger('stripeConnectSettingsModalLoaded');
              break;
            case 'square_settings':
              $(document).trigger('squareSettingsModalLoaded');
              break;
            default:
              break;
          }

          $(document).trigger('idfSettingsModalLoaded', modalRoute);

          // Display the modal
          $('.idf-modal-background').css('display', 'flex');

          // Initialize tooltips in the modal
          tippy('.idf-tooltip', {
            allowHTML: true, // Allow HTML tags in the tooltip content
          });

          idfInitializeSelect2();
        } else {
          // Handle errors by displaying an error message
          $('#idf-settings-modal').html('<p class="error-message">Unable to load settings. Please try again.</p>');
        }
      },
      error: function () {
        // Handle AJAX errors gracefully
        $('#idf-settings-modal').html('<p class="error-message">An error occurred while loading the settings.</p>');
      },
    });
  });

  // Close modal functionality
  $(document).on('click', '.idf-modal-background', function (e) {
    if ($(e.target).hasClass('idf-modal-background')) {
      $(this).css('display', 'none');
      $('#idf-settings-modal').empty(); // Clear modal content on close
    }
  });



  // Close modal when "Cancel" button is clicked
  $(document).on('click', '#cancelBtn',function () {
    $('.idf-modal-background').hide();
  });

  // Optionally, close modal when "Save & Close" is clicked and perform saving action
  $(document).on('click', '#saveCloseBtn',function () {
    $('.idf-modal-background').hide();
  });


  // Close modal when clicking outside of it
  $(window).on('click', function(e) {
    var modal = $('#idf-settings-modal');
    if ($(e.target).is('.idf-modal-background')) {
      $('.idf-modal-background').hide();
    }
  });

  $('#select_purchase_pageurls').change(function() {
    var selectedValue = $(this).val();

    if (selectedValue == 'external_url') {
      $('#purchase_url_cont').show();
      $('#purchase_posts').hide();
    } else if (selectedValue == 'page_or_post') {
      $('#purchase_posts').show();
      $('#purchase_url_cont').hide();
    } else if (selectedValue == 'current_page') {
      $('#purchase_posts').hide();
      $('#purchase_url_cont').hide();
    }
  });

  function validateCreditCardGatewaysOptions() {
    // Retrieve gateway keys from localized object
    const gatewayCheckboxes = idf_ajax_object.idc_cc_gateways.map((key) => `input[name="${key}"]`);

    // Stripe Legacy and Stripe Checkout related fields
    const stripeLegacyFields = [
      'input[name="enable_stripe_legacy_for_creators"]',
      'input[name="stripe_legacy_enable_fee_mods"]',
      'span[data-modal="stripe_legacy_settings"]'
    ];

    const stripeCheckoutFields = [
      'input[name="enable_stripe_checkout_for_creators"]',
      'input[name="stripe_checkout_enable_fee_mods"]',
      'span[data-modal="stripe_checkout_settings"]'
    ];

    const coinPaymentsFields = [
      'input[name="enable_coin_payments_for_creators"]',
      'input[name="coin_payments_enable_fee_mods"]'
    ];

    // Function to handle dependent fields
    function handleDependentFields() {
      // Paypal for creator
      if ($('input[name="enable_paypal"]').is(':checked')) {
        $('input[name="enable_paypal_for_creators"]').prop('disabled', false);
      } else {
        $('input[name="enable_paypal_for_creators"]').prop('disabled', true).prop('checked', false);
      }

      // Stripe Legacy Fee Mods
      if ($('input[name="enable_stripe_legacy_for_creators"]').is(':checked')) {
        $('input[name="stripe_legacy_enable_fee_mods"]').prop('disabled', false);
      } else {
        $('input[name="stripe_legacy_enable_fee_mods"]').prop('disabled', true).prop('checked', false);
      }

      // Stripe Checkout Fee Mods
      if ($('input[name="enable_stripe_checkout_for_creators"]').is(':checked')) {
        $('input[name="stripe_checkout_enable_fee_mods"]').prop('disabled', false);
      } else {
        $('input[name="stripe_checkout_enable_fee_mods"]').prop('disabled', true).prop('checked', false);
      }

      // Handle Coin Payments for creator field.
      if ($('input[name="enable_coin_payments"]').is(':checked')) {
        $('input[name="enable_coin_payments_for_creators"]').prop('disabled', false);
      } else {
        $('input[name="enable_coin_payments_for_creators"]').prop('disabled', true).prop('checked', false);
      }

      // Coin Payments Fee Mods
      if ($('input[name="enable_coin_payments_for_creators"]').is(':checked')) {
        $('input[name="coin_payments_enable_fee_mods"]').prop('disabled', false);
      } else {
        $('input[name="coin_payments_enable_fee_mods"]').prop('disabled', true).prop('checked', false);
      }
    }

    // Function to handle state based on current selections
    function handleInitialState() {
      const checkedGateway = $(gatewayCheckboxes.join(', ')).filter(':checked');
      if (checkedGateway.length) {
        // If any checkbox is already checked, disable the others
        $(gatewayCheckboxes.join(', ')).not(checkedGateway).prop('disabled', true);
      }

      // Handle Stripe Legacy related fields
      if ($('input[name="enable_stripe"]').is(':checked')) {
        $(stripeLegacyFields.join(', ')).prop('disabled', false);
      } else {
        $(stripeLegacyFields.join(', ')).prop('disabled', true).prop('checked', false);
      }

      // Handle Stripe Checkout related fields
      if ($('input[name="enable_stripe_checkout"]').is(':checked')) {
        $(stripeCheckoutFields.join(', ')).prop('disabled', false);
      } else {
        $(stripeCheckoutFields.join(', ')).prop('disabled', true).prop('checked', false);
      }

      // Handle Coin Payments related fields
      if ($('input[name="enable_coin_payments"]').is(':checked')) {
        console.log("here");
        $(coinPaymentsFields.join(', ')).prop('disabled', false);
      } else {
        $(coinPaymentsFields.join(', ')).prop('disabled', true).prop('checked', false);
      }

      // Handle Coin Payments related fields
      handleDependentFields();
    }

    // Add change event listener to each checkbox
    $(gatewayCheckboxes.join(', ')).on('change', function () {
      if ($(this).is(':checked')) {
        // Disable and uncheck all other checkboxes
        $(gatewayCheckboxes.join(', ')).not(this).prop('checked', false).prop('disabled', true);
      } else {
        // Enable all checkboxes if none is selected
        $(gatewayCheckboxes.join(', ')).prop('disabled', false);
      }

      // Handle Stripe Legacy related fields
      if ($('input[name="enable_stripe"]').is(':checked')) {
        $(stripeLegacyFields.join(', ')).prop('disabled', false);
      } else {
        $(stripeLegacyFields.join(', ')).prop('disabled', true).prop('checked', false);
      }

      // Handle Stripe Checkout related fields
      if ($('input[name="enable_stripe_checkout"]').is(':checked')) {
        $(stripeCheckoutFields.join(', ')).prop('disabled', false);
      } else {
        $(stripeCheckoutFields.join(', ')).prop('disabled', true).prop('checked', false);
      }

      handleDependentFields();
    });

    // Add change event listener for dependent fields
    $([
      'input[name="enable_stripe_legacy_for_creators"]',
      'input[name="enable_stripe_checkout_for_creators"]',
      'input[name="enable_coin_payments_for_creators"]',
      'input[name="enable_coin_payments"]',
      'input[name="enable_paypal"]',
    ].join(', ')).on('change', handleDependentFields);

    // Handle the initial page load
    handleInitialState();
  }

  // Initialize the function
  validateCreditCardGatewaysOptions();


  // Target all checkboxes on the page
  $('input[type="checkbox"]').each(function () {
    if ($(this).is(':disabled')) {
      // If the checkbox is disabled, uncheck it
      $(this).prop('checked', false);
    }
  });

});


