 
// Check valid URL    
function isValidUrl(string) {
  try {
    new URL(string);
    return true;
  } catch (err) {
    return false;
  }
}
// Copy Text - Google oAuth Create Help
function copyText(clickedElement) {
  // const text = document.getElementById("copyTarget").innerText;
  const text = clickedElement.previousElementSibling.innerText;
  navigator.clipboard.writeText(text);
 alert("Copied: " + text);
//   alert("Copied");
}

function initConfigureApplicationSearch($) {
  const $applicationSearch = $('#WordFormConfigureApplicationSearch');
  const $applicationRows = $('.wordform-connect-application-row');
  const $applicationCards = $('.wordform-connect-application-card');
  const $applicationGroups = $('.wordform-connect-application-group');
  const $emptyState = $('#WordFormConfigureApplicationSearchEmptyState');
  const $categoryFilters = $('.wordform-connect-category-filter');
  let activeCategoryFilter = 'all';

  if (!$applicationSearch.length || !$applicationCards.length) {
    return;
  }

  function applyConfigureApplicationFilters() {
    const normalizedSearchTerm = $.trim($applicationSearch.val()).toLowerCase();
    let visibleCards = 0;

    $applicationCards.each(function() {
      const $card = $(this);
      const applicationName = ($card.data('application-name') || '').toString().toLowerCase();
      const applicationSlug = ($card.data('application-slug') || '').toString().toLowerCase();
      const applicationCategory = ($card.data('application-category') || '').toString().toLowerCase();
      const matchesSearch = normalizedSearchTerm.length === 0 || applicationName.indexOf(normalizedSearchTerm) !== -1 || applicationSlug.indexOf(normalizedSearchTerm) !== -1;
      const matchesCategory = activeCategoryFilter === 'all' || applicationCategory === activeCategoryFilter;
      const isMatch = matchesSearch && matchesCategory;

      $card.toggle(isMatch);

      if (isMatch) {
        visibleCards++;
      }
    });

    $applicationRows.each(function() {
      const hasVisibleCards = $(this).find('.wordform-connect-application-card').filter(function() {
        return $(this).css('display') !== 'none';
      }).length > 0;
      $(this).toggle(hasVisibleCards);
    });

    $applicationGroups.each(function() {
      const hasVisibleGroupCards = $(this).find('.wordform-connect-application-card').filter(function() {
        return $(this).css('display') !== 'none';
      }).length > 0;
      $(this).toggle(hasVisibleGroupCards);
    });

    $emptyState.toggle(visibleCards === 0);
  }

  $applicationSearch.on('input', function() {
    applyConfigureApplicationFilters();
  });

  $categoryFilters.on('click', function() {
    activeCategoryFilter = ($(this).data('category-filter') || 'all').toString().toLowerCase();
    $categoryFilters.removeClass('is-active');
    $(this).addClass('is-active');
    applyConfigureApplicationFilters();
  });

  applyConfigureApplicationFilters();
}

function populateIntegrationResourceSelect($select, resources, emptyLabel, selectedValue) {
  if (!$select.length) {
    return;
  }

  $select.empty().append(
    jQuery('<option>', {
      value: '',
      text: emptyLabel || 'Select'
    })
  );

  if (Array.isArray(resources)) {
    resources.forEach(function(resource) {
      const value = resource && resource.value ? resource.value.toString() : '';
      const label = resource && resource.label ? resource.label.toString() : value;
      if (!value) {
        return;
      }

      $select.append(
        jQuery('<option>', {
          value: value,
          text: label
        })
      );
    });
  }

  if (selectedValue && selectedValue.toString().length) {
    $select.val(selectedValue.toString());
  }
}

function scrollConnectFeedbackIntoView(feedbackSelector) {
  if (!feedbackSelector) {
    return;
  }

  const $feedback = jQuery(feedbackSelector).first();
  if (!$feedback.length) {
    return;
  }

  const $modalContent = $feedback.closest('.ui-dialog-content');
  if ($modalContent.length) {
    const modalNode = $modalContent.get(0);
    const feedbackNode = $feedback.get(0);
    if (modalNode && feedbackNode) {
      const targetTop = Math.max(0, feedbackNode.offsetTop - 24);
      $modalContent.stop(true).animate({ scrollTop: targetTop }, 220);
    }
  }

  const feedbackNode = $feedback.get(0);
  if (feedbackNode && typeof feedbackNode.scrollIntoView === 'function') {
    feedbackNode.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
  }
}

function openWordFormUpgradeUrl(upgradeUrl) {
  const targetUrl = (upgradeUrl || '').toString();
  if (!targetUrl.length) {
    return;
  }
  window.open(targetUrl, '_blank', 'noopener');
}


jQuery(document).ready(function($) {					
	// console.log('wordform-connects-page-script Loaded...');
	// console.log(wordform_admin_view_connects_page_script_obj);
    initConfigureApplicationSearch($);

    const connectionAppRegistry = {
        googlesheet: {
            connectAction: 'wordform_connect_create_googlesheet_with_form_fields',
            reconnectAction: 'wordform_connect_reconnect_googlesheet_with_form_fields'
        },
        googlecalendar: {
            connectAction: 'wordform_connect_create_googlecalendar_with_form_fields',
            reconnectAction: 'wordform_connect_create_googlecalendar_with_form_fields'
        },
        zapier: {
            connectAction: 'wordform_connect_create_zapier_with_form_fields',
            reconnectAction: 'wordform_connect_create_zapier_with_form_fields'
        },
        customwebhook: {
            connectAction: 'wordform_connect_create_custom_webhook_with_form_fields',
            reconnectAction: 'wordform_connect_create_custom_webhook_with_form_fields'
        },
        slack: {
            connectAction: 'wordform_connect_create_slack_with_form_fields',
            reconnectAction: 'wordform_connect_create_slack_with_form_fields'
        },
        mailchimp: {
            connectAction: 'wordform_connect_create_mailchimp_with_form_fields',
            reconnectAction: 'wordform_connect_create_mailchimp_with_form_fields'
        },
        mailerlite: {
            connectAction: 'wordform_connect_create_mailerlite_with_form_fields',
            reconnectAction: 'wordform_connect_create_mailerlite_with_form_fields'
        },
        airtable: {
            connectAction: 'wordform_connect_create_airtable_with_form_fields',
            reconnectAction: 'wordform_connect_create_airtable_with_form_fields'
        },
        brevo: {
            connectAction: 'wordform_connect_create_brevo_with_form_fields',
            reconnectAction: 'wordform_connect_create_brevo_with_form_fields'
        },
        hubspot: {
            connectAction: 'wordform_connect_create_hubspot_with_form_fields',
            reconnectAction: 'wordform_connect_create_hubspot_with_form_fields'
        },
        make: {
            connectAction: 'wordform_connect_create_make_with_form_fields',
            reconnectAction: 'wordform_connect_create_make_with_form_fields'
        },
        activecampaign: {
            connectAction: 'wordform_connect_create_activecampaign_with_form_fields',
            reconnectAction: 'wordform_connect_create_activecampaign_with_form_fields'
        },
        salesforce: {
            connectAction: 'wordform_connect_create_salesforce_with_form_fields',
            reconnectAction: 'wordform_connect_create_salesforce_with_form_fields'
        },
        zohocrm: {
            connectAction: 'wordform_connect_create_zohocrm_with_form_fields',
            reconnectAction: 'wordform_connect_create_zohocrm_with_form_fields'
        }
    };

    function getConnectionAppConfig(applicationSlug) {
        return connectionAppRegistry[applicationSlug] || null;
    }

    function scrollToConnectionCreatePanel() {
        const $panel = $('#WordFormConnectionCreatePanel');
        if (!$panel.length) {
            return;
        }

        $('html, body').stop(true).animate({
            scrollTop: Math.max(0, $panel.offset().top - 36)
        }, 220);

        $panel.addClass('wordform-connection-create-panel-highlight');
        setTimeout(function() {
            $panel.removeClass('wordform-connection-create-panel-highlight');
        }, 1600);
    }

    function upsertConfiguredApplicationOption(applicationData) {
        const $applicationSelect = $('#WordFormSelectConnectionName');
        if (!$applicationSelect.length || !applicationData || !applicationData.id || !applicationData.applicationSlug) {
            return;
        }

        let $existingOption = $applicationSelect.find('option[value="' + applicationData.id + '"]');
        if (!$existingOption.length) {
            $existingOption = $('<option>');
            $applicationSelect.append($existingOption);
        }

        $existingOption
            .val(applicationData.id)
            .attr('data-application-slug', applicationData.applicationSlug)
            .text(applicationData.applicationName || applicationData.applicationSlug);
    }

    function buildPostSaveConnectMarkup(applicationData) {
        const formOptionsHtml = $('#WordFormConnectSelectForm option').map(function() {
            const optionValue = $(this).val();
            const optionText = $(this).text();
            if (!optionValue) {
                return '';
            }
            return '<option value="' + optionValue + '">' + optionText + '</option>';
        }).get().join('');

        if (!formOptionsHtml.length) {
            return '';
        }

        return `
            <div class="wordform-connect-post-save-cta" data-application-id="${applicationData.id}" data-application-slug="${applicationData.applicationSlug}">
                <div class="wordform-connect-post-save-cta-copy">
                    <h4>Configuration saved</h4>
                    <p>${applicationData.applicationName} is ready. Choose a form and continue directly to the connection step.</p>
                </div>
                <div class="wordform-connect-post-save-cta-actions">
                    <select class="wordform-connect-post-save-form-select">
                        <option value="">Select Form</option>
                        ${formOptionsHtml}
                    </select>
                    <button type="button" class="button button-primary wordform-connect-post-save-connect-btn">Connect This App</button>
                </div>
            </div>
        `;
    }

    function escapeHtml(value) {
        return $('<div>').text(value == null ? '' : value.toString()).html();
    }

    function escapeAttribute(value) {
        return (value == null ? '' : value.toString())
            .replace(/&/g, '&amp;')
            .replace(/"/g, '&quot;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;');
    }

    const integrationHelpRegistry = {
        activecampaign: {
            url: 'https://help.activecampaign.com/hc/en-us/articles/221317447-Where-can-I-find-my-API-URL-and-key-',
            label: 'ActiveCampaign API Help'
        },
        airtable: {
            url: 'https://support.airtable.com/docs/creating-personal-access-tokens',
            label: 'Airtable Access Token Help'
        },
        brevo: {
            url: 'https://help.brevo.com/hc/en-us/articles/209467485-Create-and-manage-your-API-keys',
            label: 'Brevo API Key Help'
        },
        googlecalendar: {
            url: 'https://developers.google.com/identity/protocols/oauth2/web-server',
            label: 'Google OAuth Setup Guide'
        },
        googlesheet: {
            url: 'https://developers.google.com/identity/protocols/oauth2/web-server',
            label: 'Google OAuth Setup Guide'
        },
        hubspot: {
            url: 'https://developers.hubspot.com/docs/api/private-apps',
            label: 'HubSpot Private Apps Help'
        },
        mailchimp: {
            url: 'https://mailchimp.com/help/about-api-keys/',
            label: 'Mailchimp API Key Help'
        },
        mailerlite: {
            url: 'https://developers.mailerlite.com/docs/',
            label: 'MailerLite API Token Help'
        },
        salesforce: {
            url: 'https://help.salesforce.com/s/articleView?id=sf.connected_app_create.htm&type=5',
            label: 'Salesforce Connected App Help'
        },
        zohocrm: {
            url: 'https://www.zoho.com/accounts/protocol/oauth-setup.html',
            label: 'Zoho OAuth Setup Help'
        }
    };

    function inferIntegrationSlugFromAction(actionName) {
        const normalizedAction = (actionName || '').toString().toLowerCase();
        const knownSlugs = [
            'googlecalendar',
            'googlesheet',
            'activecampaign',
            'mailchimp',
            'mailerlite',
            'airtable',
            'hubspot',
            'salesforce',
            'zohocrm',
            'customwebhook',
            'brevo',
            'slack',
            'zapier',
            'make'
        ];

        for (let index = 0; index < knownSlugs.length; index++) {
            if (normalizedAction.indexOf(knownSlugs[index]) !== -1) {
                return knownSlugs[index];
            }
        }

        if (normalizedAction.indexOf('custom_webhook') !== -1) {
            return 'customwebhook';
        }

        return '';
    }

    function buildIntegrationFeedbackHtml(payload, actionName, explicitSlug) {
        const jsonData = payload || {};
        const providerSlug = (explicitSlug || jsonData.providerSlug || inferIntegrationSlugFromAction(actionName || '')).toString().toLowerCase();
        const providerHelp = integrationHelpRegistry[providerSlug] || {};
        const commentText = (jsonData.comment || '').toString();
        const fixTip = (jsonData.fixTip || jsonData.fix_tip || '').toString();
        const providerHelpUrl = (jsonData.providerHelpUrl || providerHelp.url || '').toString();
        const providerHelpLabel = (jsonData.providerHelpLabel || providerHelp.label || 'Official Help').toString();

        let html = '<div class="wordform-connect-feedback-copy">' + escapeHtml(commentText) + '</div>';

        if (fixTip.length) {
            html += '<div class="wordform-connect-feedback-detail"><strong>Fix tip:</strong> ' + escapeHtml(fixTip) + '</div>';
        }

        if (providerHelpUrl.length) {
            html += '<div class="wordform-connect-feedback-link"><a href="' + escapeAttribute(providerHelpUrl) + '" target="_blank" rel="noopener">' + escapeHtml(providerHelpLabel) + '</a></div>';
        }

        return html;
    }

    function removeConfiguredApplicationOption(applicationSlug) {
        const $applicationSelect = $('#WordFormSelectConnectionName');
        if (!$applicationSelect.length || !applicationSlug) {
            return;
        }

        const $option = $applicationSelect.find('option[data-application-slug="' + applicationSlug + '"]');
        if ($option.length) {
            if (($applicationSelect.val() || '') === ($option.val() || '')) {
                $applicationSelect.val('');
            }
            $option.remove();
        }
    }

    function renderIntegrationCardState(applicationSlug, cardState) {
        if (!applicationSlug) {
            return;
        }

        const $card = $('.wordform-connect-application-card[data-application-slug="' + applicationSlug + '"]').first();
        if (!$card.length) {
            return;
        }

        const applicationName = cardState && cardState.applicationName ? cardState.applicationName.toString() : $.trim($card.find('h2').first().text());
        const isConfigured = !!(cardState && cardState.isConfigured);
        const isActive = !!(cardState && cardState.isActive);
        const configuredApplication = cardState && cardState.configuredApplication ? cardState.configuredApplication : null;
        const isConnectionReady = !!(isConfigured && isActive && configuredApplication && configuredApplication.id);
        let actionsHtml = '';

        const summaryHtml = `
            <div class="wordform-connect-card-health-row">
                <span class="wordform-connect-card-health-label">Setup</span>
                <span class="wordform-connect-card-health-value ${isConfigured ? 'is-good' : 'is-warning'}">
                    <i class="fa-solid ${isConfigured ? 'fa-circle-check' : 'fa-wrench'}"></i>
                    ${isConfigured ? 'Ready' : 'Needs Setup'}
                </span>
            </div>
            <div class="wordform-connect-card-health-row">
                <span class="wordform-connect-card-health-label">Status</span>
                <span class="wordform-connect-card-health-value ${isActive ? 'is-good' : (isConfigured ? 'is-muted' : 'is-warning')}">
                    <i class="fa-solid ${isActive ? 'fa-bolt' : (isConfigured ? 'fa-pause-circle' : 'fa-circle-minus')}"></i>
                    ${isActive ? 'Active' : (isConfigured ? 'Inactive' : 'Not Ready')}
                </span>
            </div>
            <div class="wordform-connect-card-health-row">
                <span class="wordform-connect-card-health-label">Connection</span>
                <span class="wordform-connect-card-health-value ${isConnectionReady ? 'is-good' : 'is-muted'}">
                    <i class="fa-solid ${isConnectionReady ? 'fa-diagram-project' : 'fa-arrow-right'}"></i>
                    ${isConnectionReady ? 'Connection Ready' : 'Configure First'}
                </span>
            </div>
        `;

        if (isConfigured) {
            if (isActive) {
                if (configuredApplication && configuredApplication.id) {
                    actionsHtml += `
                        <button class="button button-primary wordform-use-configured-application-btn"
                            data-application-id="${escapeHtml(configuredApplication.id)}"
                            data-application-name="${escapeHtml(configuredApplication.applicationName || applicationName)}"
                            data-application-slug="${escapeHtml(applicationSlug)}">
                            <i class="fa-solid fa-arrow-up-right-from-square"></i> Use in Create Connection
                        </button>
                    `;
                }

                actionsHtml += `
                    <button class="button button-secondary wordform-activate-deactivate-sending-forms-data"
                        data-activate-deactivate-application-slug="${escapeHtml(applicationSlug)}"
                        data-application-name="${escapeHtml(applicationName)}"
                        data-application-status-change-to="inactive">
                        <i class="fa-solid fa-link-slash"></i> Deactivate
                    </button>
                `;
            } else {
                actionsHtml += `
                    <button class="button button-secondary wordform-activate-deactivate-sending-forms-data"
                        data-activate-deactivate-application-slug="${escapeHtml(applicationSlug)}"
                        data-application-name="${escapeHtml(applicationName)}"
                        data-application-status-change-to="active">
                        <i class="fa-solid fa-link"></i> Activate
                    </button>
                `;
            }
        }

        $card.attr('data-configured-application-id', configuredApplication && configuredApplication.id ? configuredApplication.id : '');
        $card.find('.wordform-connect-card-health-summary').html(summaryHtml);
        $card.find('.wordform-connect-card-actions').html(actionsHtml);
    }

    function syncConfiguredApplicationUi(applicationData, stateOverrides) {
        if (!applicationData || !applicationData.applicationSlug) {
            return;
        }

        const applicationSlug = applicationData.applicationSlug.toString();
        const cardState = $.extend({
            applicationName: applicationData.applicationName || '',
            isConfigured: true,
            isActive: true,
            configuredApplication: applicationData
        }, stateOverrides || {});

        if (cardState.isActive) {
            upsertConfiguredApplicationOption(applicationData);
        } else {
            removeConfiguredApplicationOption(applicationSlug);
        }

        renderIntegrationCardState(applicationSlug, cardState);
    }

    // Init Modal Config
    function initWordFormModalDialogConfig( connectApplicationModalId, connectProgramName ) {
        return new Promise( ( resolve ) => {        
        // console.log('Inside Promise');    
        // console.log( connectApplicationModalId );    

        var viewportWidth = Math.round( $(window).width() / 2 ) ;
        var viewportHeight = Math.round( $(window).height() * 2 / 3 ); // Two-Third of total viewport Height + 50px not to conflict/hide dialog title with topbar of the page
        // console.log('viewportWidth: '+ viewportWidth );
        // console.log('viewportHeight: '+ viewportHeight );        
        // Init Modal Config
        connectApplicationModalId.dialog({
            autoOpen: false,
            minHeight: viewportHeight,
            minWidth: viewportWidth,
            modal: true,
            dialogClass: 'wordform-admin-dialog wordform-configure-app-dialog',
            // if the calculated topOffset is less than the desiredTop. If it is, the dialog's top CSS property is set to the desiredTop value, effectively pushing it down from the top of the window.
            position: {
                my: "center top",
                at: "center top",
                of: window,
                using: function(pos) {
                    var topOffset = $(this).css(pos).offset().top;
                    var desiredTop = 50; // Desired top margin
                    if (topOffset < desiredTop) {
                        $(this).css("top", desiredTop);
                    }
                }
            },            
            buttons: {
              /*"Configure": function() { 
                switch ( connectProgramName ) {
                    case 'GoogleSheetAPI':
                        ConnectGoogleSheetAPI();
                        break;
                    case 'ZapierAPI':
                        ConnectZapierAPI();
                        break;    
                }                
              },*/
              Close: function() {
                connectApplicationModalId.dialog( "close" );
              }
            },
            close: function() {
              const shouldSkipReload = connectApplicationModalId.data('wordform-skip-reload') === true;
              connectApplicationModalId.data('wordform-skip-reload', false);
              if ( shouldSkipReload ) {
                return;
              }
            }
          });
       
          form = connectApplicationModalId.find( "form" ).on( "submit", function( event ) {
            event.preventDefault();
            // addUser();
          });

        resolve(connectApplicationModalId);
        });          
    }
         
   // On Click on Third-Party Application Name - Open the corresponding Modal Window
    $( ".third-party-connect-library" ).on( "click", function() {
        const featureAvailable = ($(this).data('feature-available') || 'yes').toString().toLowerCase();
        if (featureAvailable !== 'yes') {
            openWordFormUpgradeUrl($(this).data('upgrade-url'));
            return false;
        }

        let connectProgramName = '';        
        // connectProgramName = $(this).prop('id');
        connectProgramName = $(this).data('thirdparty-program-name');
        console.log( connectProgramName );
        let connectApplicationModalId = $('#' + connectProgramName + 'Modal'); // Generate Id of clicked Application to make the connection from WordForm
        initWordFormModalDialogConfig( connectApplicationModalId, connectProgramName ).then( (result) => {            
            console.log(result);
            let connectApplicationModalId = result;
            // Open Modal Window  
            console.log('After Promise inside then chaining');
            console.log(connectApplicationModalId);
            connectApplicationModalId.dialog("open");
        });
    });    


    // Create Connect or Icon Click: On Click Create Connection Or Icon Link
    $('body').on('click', '.wordform-connection-create-icon', function() {        
        let selectedFormId = $('#WordFormConnectSelectForm').val();
        let selectedFormName = $("#WordFormConnectSelectForm option:selected").text();
        let selectedApplicationID = $('#WordFormSelectConnectionName').val();
        let selectedApplicationName = $("#WordFormSelectConnectionName option:selected").text();
        let WordFormConnectionModalId = $('#WordFormConnectionModal');
        WordFormConnectionModalId.dialog({
            autoOpen: false,
            minHeight: 300,
            minWidth: 600,
            modal: true,
            title: 'Connect WordForm to ' + selectedApplicationName,
            dialogClass: 'wordform-admin-dialog wordform-connection-create-dialog',
            buttons: {
              /*"Connect": function() { 
                console.log('Connect...Testing');
              },*/
              Close: function() {
                WordFormConnectionModalId.dialog( "close" );
              }
            },
            close: function() {
            }
          });
          // When Form or Application not selected
          if ( $.trim(selectedFormId).length == 0 || $.trim( selectedApplicationID ).length == 0 ) {
                WordFormConnectionModalId.dialog('option', 'title', 'Create Connection');
                WordFormConnectionModalId.html(`
                <div class="wordform-connection-empty-state-modal">
                    <div class="wordform-connection-empty-state-hero">
                        <span class="dashicons dashicons-warning"></span>
                        <h3>Select Form and Application First</h3>
                        <p>Please complete both selections before creating a connection.</p>
                    </div>
                    <div class="wordform-connection-empty-state-grid">
                        <div class="wordform-connection-empty-state-card ${$.trim(selectedFormId).length !== 0 ? 'is-ready' : 'is-missing'}">
                            <h4>Form</h4>
                            <p>${$.trim(selectedFormId).length !== 0 ? selectedFormName + ' (' + selectedFormId + ')' : 'No form selected yet.'}</p>
                        </div>
                        <div class="wordform-connection-empty-state-card ${$.trim(selectedApplicationID).length !== 0 ? 'is-ready' : 'is-missing'}">
                            <h4>Application</h4>
                            <p>${$.trim(selectedApplicationID).length !== 0 ? selectedApplicationName : 'No application selected yet.'}</p>
                        </div>
                    </div>
                <div class="wordform-connection-empty-state-help">
                        <p><span class="dashicons dashicons-info-outline"></span> Select a WordForm from the left dropdown.</p>
                        <p><span class="dashicons dashicons-info-outline"></span> Select a configured application from the right dropdown.</p>
                        <p><span class="dashicons dashicons-info-outline"></span> If the application is missing, configure it first from the cards below.</p>
                        <p><button type="button" class="button button-secondary wordform-scroll-to-configure-apps-btn"><i class="fa-solid fa-gears"></i> Browse Configure Applications</button></p>
                    </div>
                </div>
                `);
          }
          else {                             
            DisplayConnectModalWindow( WordFormConnectionModalId );            
          }
          WordFormConnectionModalId.dialog("open");
    })

    // Collect parameters data
    function wordFormConnectParamsData() {
        let params = {};          
        let selectedFormId = $('#WordFormConnectSelectForm').val();
        let selectedFormName = $('#WordFormConnectSelectForm option:selected').text();
        params.wordFormID = selectedFormId;     
        params.wordFormName = selectedFormName;   
        let selectedApplicationID = $('#WordFormSelectConnectionName').val();
        let selectedApplicationName = $('#WordFormSelectConnectionName option:selected').text();
        let selectedApplicationSlug =  $('#WordFormSelectConnectionName option:selected').data('application-slug');
        params.applicationID = selectedApplicationID;
        params.applicationSlug = selectedApplicationSlug;
        params.applicationName = selectedApplicationName;
        console.log('WordForm ID: '+selectedFormId);
        console.log('WordForm Name: '+selectedFormName);
        console.log('Application ID: ' + selectedApplicationID );
        console.log('Application Name: ' + selectedApplicationName );
        return params;         
    }
    // Display Connect / Reconnect Button Modal Window: Display Connection Modal window based on Wordform & selected Application
    function DisplayConnectModalWindow( WordFormConnectionModalId = '' ) {
         let selectedApplicationSlug =  $('#WordFormSelectConnectionName option:selected').data('application-slug');
         let connectButtonHtmlContents = '';
         let appConfig = getConnectionAppConfig( selectedApplicationSlug );
         console.log('Selected Application: '+ selectedApplicationSlug );
         if ( appConfig ) {
            connectButtonHtmlContents = `
                <div class="wordform-connection-modal-shell">
                    <div class="wordform-connection-modal-summary">
                        <div class="wordform-connection-modal-summary-card">
                            <span class="wordform-connection-modal-summary-label">Form</span>
                            <strong class="wordform-connection-modal-summary-value"></strong>
                        </div>
                        <div class="wordform-connection-modal-summary-card">
                            <span class="wordform-connection-modal-summary-label">Application</span>
                            <strong class="wordform-connection-modal-summary-value wordform-connection-modal-summary-application"></strong>
                        </div>
                    </div>
                    <div class="connect-modal-dynamic-contents"></div>
                    <h4 class="wordform-connecting-msg"></h4>
                    <div class="wordform-modal-connection-app-action-btn" data-application-slug="` + selectedApplicationSlug + `" data-connect-mode="connect">
                        <button class="button button-primary button-large">
                            <i class="fa-solid fa-plug-circle-check"></i>
                            <span>Connect</span>
                        </button>
                    </div>
                </div>`;
         }
         else {
            connectButtonHtmlContents = '<div class="notice notice-error is-dismissible"><p><strong>This application is not yet wired into the connection workflow.</strong></p></div>';
         }
          // Display Connect button in the opened Modal
          WordFormConnectionModalId.html( connectButtonHtmlContents );        
          let params = {};          
          params = wordFormConnectParamsData(); 
          WordFormConnectionModalId.find('.wordform-connection-modal-summary-value').first().text(params.wordFormName + ' (' + params.wordFormID + ')');
          WordFormConnectionModalId.find('.wordform-connection-modal-summary-application').text(params.applicationName);
          console.log('Modal Window Display: Return params data: ');
          console.log(params);
          var wordFormConnectFormFields = '';     
          let showDynamicWordFormConnectMsg =  $('.connect-modal-dynamic-contents');       
          showDynamicWordFormConnectMsg.html('<div class="wordform-connection-modal-loading"><i class="fa-solid fa-spinner fa-spin-pulse"></i><span>Loading form fields...</span></div>');    
          // Ftech Form fileds information    
          $.ajax({
              type:"POST",		  
              url: wordform_admin_view_connects_page_script_obj.adminajax_url,
              data : {			    			
                      action    : 'wordform_connect_form_n_display_form_fields',
                      security  : wordform_admin_view_connects_page_script_obj.nonce,				
                      params 	: params
                      },		  
              success: function(data) {                   
                  // console.log(data); 
                  let jsonData	= JSON.parse( data );
                  console.log( jsonData );                  

                  if ( jsonData.status == 'success' ) {		

                    // If Wordform already connected with the same selected application then Show Reconnect Button
                    if ( jsonData.isConnected == true ) {
                        WordFormConnectionModalId.find('.wordform-modal-connection-app-action-btn').attr('data-connect-mode', 'reconnect');
                        WordFormConnectionModalId.find('.wordform-modal-connection-app-action-btn button span').text('ReConnect');
                    }

                    // Organize form fields
                    for( i in jsonData.formFields ) {
                        console.log( jsonData.formFields[ i ] );
                        wordFormConnectFormFields += '<li><span class="dashicons dashicons-yes-alt"></span><span>'+ jsonData.formFields[ i ] +'</span></li>';   
                    }
                    showDynamicWordFormConnectMsg.html(
                        '<div class="wordform-connection-modal-fields-card">' +
                            '<div class="wordform-connection-modal-fields-head">' +
                                '<h4>Form Fields</h4>' +
                                '<span class="wordform-connection-modal-fields-count">' + jsonData.formFields.length + ' fields</span>' +
                            '</div>' +
                            '<p class="wordform-connection-modal-fields-help">These form fields will be used for this connection.</p>' +
                            '<ul class="wordform-connection-modal-fields-list">'+ wordFormConnectFormFields +'</ul>' +
                        '</div>'
                    );                    
                  }
                  else if ( jsonData.status == 'warning' ) {			
                  }
                  else if ( jsonData.status == 'fail' ) {			
                      showDynamicWordFormConnectMsg.html( jsonData.comment );
                  }
      
                  },
              error: function( xhr, status, error ) { 
                  console.log(xhr); 
                  console.log(status); 
                  console.log(error); 				 
      
                  }
              }); // $.ajax			                   
    } // DisplayConnectModalWindow

    // Generic Connect/ReConnect Button Click: Start connecting between Form & Application
    $('body').on("click", ".wordform-modal-connection-app-action-btn", function() {
        let params = wordFormConnectParamsData();
        let applicationSlug = $(this).data('application-slug');
        let connectMode = $(this).attr('data-connect-mode') || 'connect';
        let appConfig = getConnectionAppConfig( applicationSlug );
        if ( ! appConfig ) {
            return;
        }

        let actionName = connectMode === 'reconnect' ? appConfig.reconnectAction : appConfig.connectAction;
        let actionLabel = connectMode === 'reconnect' ? 'ReConnecting' : 'Connecting';
        let showDynamicWordFormConnectMsg = $('.connect-modal-dynamic-contents');
        let wordformModalConnectButton = $(this).find('button');
        let wordformConnectingMsgShowElement = $('.wordform-connecting-msg');

        wordformConnectingMsgShowElement.html("").removeClass('text-warning text-error');
        wordformModalConnectButton.prop( 'disabled', true );
        wordformConnectingMsgShowElement.html( '<span class="dashicons dashicons-update spin"></span> Please wait... ' + actionLabel + ' ' + params.applicationName ).addClass('text-warning');

        $.ajax({
            type:"POST",
            url: wordform_admin_view_connects_page_script_obj.adminajax_url,
            data : {
                    action    : actionName,
                    security  : wordform_admin_view_connects_page_script_obj.nonce,
                    params 	  : params
                    },
            success: function(data) {
                wordformConnectingMsgShowElement.html("").removeClass('text-warning text-error');
                let jsonData = JSON.parse( data );
                console.log( jsonData );
                if ( jsonData.status == 'success' ) {
                    let successLabel = connectMode === 'reconnect' ? 'WordForm reconnected to ' + params.applicationName + '.' : 'WordForm connected to ' + params.applicationName + '.';
                    showDynamicWordFormConnectMsg.html(
                        '<div class="wordform-connection-modal-result wordform-connection-modal-result-success">' +
                            '<span class="dashicons dashicons-yes-alt"></span>' +
                            '<div><h4>' + successLabel + '</h4><p>You can now submit this form and WordForm will send the data to ' + params.applicationName + '.</p></div>' +
                        '</div>'
                    ).addClass('text-success');
                }
                else if ( jsonData.status == 'warning' ) {
                }
                else if ( jsonData.status == 'fail' ) {
                    wordformModalConnectButton.prop( 'disabled', false );
                    showDynamicWordFormConnectMsg.html(
                        '<div class="wordform-connection-modal-result wordform-connection-modal-result-fail">' +
                            '<span class="dashicons dashicons-warning"></span>' +
                            '<div><h4>Connection failed</h4><p>' + jsonData.comment + '</p></div>' +
                        '</div>'
                    ).addClass('text-error');
                }
            },
            error: function( xhr, status, error ) {
                wordformModalConnectButton.prop( 'disabled', false );
                console.log(xhr);
                console.log(status);
                console.log(error);
            }
        }); // $.ajax
    }); // $('body').on("click", ".wordform-modal-connection-app-action-btn", function())


    // Configure Google Authentication - When Click on Modal Configure/Reconfigure Button
    $('body').on("click", ".wordform-configure-google-credentials-save-authentication-btn", function() {
        let gCredentialsId = $('.google-auth-client-id').val();
        let gCredentialsSecret = $('.google-auth-client-secret').val();
        let gRedirectUrl = $('.google-auth-redirect-url').val();
        let credentialsfeedbackMsg = $('.wordform-google-sheet-credentials-feedback-msg');
        let feedbackSelector = '.wordform-google-sheet-credentials-feedback-msg';
        credentialsfeedbackMsg.html('').removeClass('msg-error');
        if ( $.trim(gCredentialsId).length !==0 && $.trim( gCredentialsSecret).length !== 0 && $.trim( gRedirectUrl ).length !== 0 ) {
          let params = {};
          params.googleClientId = gCredentialsId;
          params.googleClientSecret = gCredentialsSecret;
          params.googleRedirectUrl = gRedirectUrl;
          $.ajax({
              type:"POST",		  
              url: wordform_admin_view_connects_page_script_obj.adminajax_url,
              data : {			    			
                      action      : 'wordform_save_google_auth_credentials_with_authentication',
                      security    : wordform_admin_view_connects_page_script_obj.nonce,				
                      params 		: params
                      },		  
              success: function(data) { 
                  // console.log(data); 
                  let jsonData	= JSON.parse( data );
                  console.log( jsonData );
                  if ( jsonData.status == 'success' ) {		
                      credentialsfeedbackMsg.html(jsonData.comment).addClass('text-success');
                      scrollConnectFeedbackIntoView(feedbackSelector);
                      setTimeout( function() { window.location.href = jsonData.googleAuthCodeURI; }, 3000 );
                  }
                  else if ( jsonData.status == 'warning' ) {			
                      credentialsfeedbackMsg.html(jsonData.comment).addClass('text-success');
                      scrollConnectFeedbackIntoView(feedbackSelector);
                      setTimeout( function() { window.location.href = jsonData.googleAuthCodeURI; }, 3000 );
                  }
                  else if ( jsonData.status == 'fail' ) {			
                      credentialsfeedbackMsg.html(jsonData.comment).addClass('text-error');
                      scrollConnectFeedbackIntoView(feedbackSelector);
                  }
      
                  },
              error: function( xhr, status, error ) { 
                  console.log(xhr); 
                  console.log(status); 
                  console.log(error); 				 
      
                  }
              });			    
        }
        // When Google client ID or Client Secret or Redirect Url empty
        else {
            credentialsfeedbackMsg.html('<i class="fa-solid fa-circle-info"></i> Please enter both Google Client ID and Secret.').addClass('msg-error');
            scrollConnectFeedbackIntoView(feedbackSelector);
        }

    });

    // Managed OAuth quick-connect button.
    $('body').on('click', '.wordform-start-managed-oauth-authentication-btn', function() {
        let authUrl = $(this).data('auth-url');
        if ( authUrl && $.trim(authUrl).length !== 0 ) {
            window.location.href = authUrl;
        }
    });

    // Connection Status tab: toolbar filters reload while keeping the same tab active.
    function reloadConnectionStatusTabWithFilters() {
        let selectedFormId = $('#WordFormConnectionStatusSelectForm').val();
        let selectedApplicationSlug = $('#WordFormConnectionStatusSelectApplication').val();
        let targetUrl = new URL(wordform_admin_view_connects_page_script_obj.wordform_connect_page_url, window.location.origin);

        if ( selectedFormId && $.trim(selectedFormId).length !== 0 ) {
            targetUrl.searchParams.set('connection_status_form_id', selectedFormId);
        } else {
            targetUrl.searchParams.delete('connection_status_form_id');
        }

        if ( selectedApplicationSlug && $.trim(selectedApplicationSlug).length !== 0 ) {
            targetUrl.searchParams.set('connection_status_application_slug', selectedApplicationSlug);
        } else {
            targetUrl.searchParams.delete('connection_status_application_slug');
        }

        targetUrl.hash = 'scWordFormConnectionStatus';
        window.location.href = targetUrl.toString();
    }

    $('body').on('change', '#WordFormConnectionStatusSelectForm, #WordFormConnectionStatusSelectApplication', function() {
        reloadConnectionStatusTabWithFilters();
    });

    // Connection Status tab: initialize DataTable only when the tab is visible.
    function initConnectionStatusDataTable() {
        let $statusTable = $('#wordformConnectionStatusTable');
        if ( ! $statusTable.length || ! $.fn.DataTable ) {
            return null;
        }

        if ( $.fn.DataTable.isDataTable( $statusTable ) ) {
            let existingTable = $statusTable.DataTable();
            existingTable.columns.adjust().draw(false);
            return existingTable;
        }

        return $statusTable.DataTable({
            order: [[0, 'asc'], [2, 'asc']],
            pageLength: 25,
            autoWidth: false,
            language: {
                search: 'Filter results:',
                searchPlaceholder: 'Type form, app, or status'
            }
        });
    }

    if ( $('#scWordFormConnectionStatus').is(':visible') ) {
        initConnectionStatusDataTable();
    }

    $(document).on('tabsactivate', '#tabs', function(event, ui) {
        if ( ui && ui.newPanel && ui.newPanel.attr('id') === 'scWordFormConnectionStatus' ) {
            initConnectionStatusDataTable();
        }
    });

    // Connection Status tab: failure detail modal.
    $('body').on('click', '.wordform-open-connection-fail-detail-modal', function() {
        let detailRaw = $(this).attr('data-failure-detail') || '';
        let detail = {};
        let modal = $('#WordFormConnectionStatusFailDetailModal');
        let docsHtml = '';
        let exceptionHtml = '';

        if ( ! detailRaw || ! modal.length ) {
            return;
        }

        try {
            detail = JSON.parse(detailRaw);
        } catch (error) {
            console.log(error);
            return;
        }

        if ( detail.docsUrl && detail.docsLabel ) {
            docsHtml = '<p><strong>Official help:</strong> <a href="' + detail.docsUrl + '" target="_blank" rel="noopener">' + detail.docsLabel + '</a></p>';
        }

        if ( detail.exceptionType || detail.exceptionMsg ) {
            exceptionHtml = '<div class="wordform-connection-fail-detail-block">';
            if ( detail.exceptionType ) {
                exceptionHtml += '<p><strong>Exception Type:</strong> ' + detail.exceptionType + '</p>';
            }
            if ( detail.exceptionMsg ) {
                exceptionHtml += '<p><strong>Exception Message:</strong> ' + detail.exceptionMsg + '</p>';
            }
            exceptionHtml += '</div>';
        }

        modal.html(
            '<div class="wordform-connection-fail-detail-wrapper">' +
                '<p><strong>Form:</strong> ' + (detail.formName || '') + '</p>' +
                '<p><strong>Application:</strong> ' + (detail.applicationName || '') + '</p>' +
                '<p><strong>Reason:</strong> ' + (detail.reason || 'Not available.') + '</p>' +
                '<p><strong>Details:</strong> ' + (detail.comment || 'Not available.') + '</p>' +
                '<p><strong>Suggestion:</strong> ' + (detail.suggestion || 'Please review the app configuration and try again.') + '</p>' +
                docsHtml +
                exceptionHtml +
            '</div>'
        );

        modal.dialog({
            autoOpen: true,
            minHeight: 240,
            minWidth: 520,
            modal: true,
            dialogClass: 'wordform-admin-dialog',
            buttons: {
                Close: function() {
                    modal.dialog('close');
                }
            }
        }).dialog('open');
    });


    // Wordform Configure Result Message Modal - Display Modal while available modal wrapper div generated based on condition
    if ( $('div').hasClass('WordFormConnectionConfigureModal') ) {
        let WordFormConfigureModalId = $('#WordFormConnectionConfigureModal');
        WordFormConfigureModalId.dialog({
            autoOpen: true,
            minHeight: 200,
            minWidth: 450,
            modal: true,
            dialogClass: 'wordform-admin-dialog',
            buttons: {
              /*"Connect": function() { 
                console.log('Connect...Testing');
              },*/
              Close: function() {
                WordFormConfigureModalId.dialog( "close" );
              }
            },
            close: function() {
              // On closing Modal dialog - Redirect into wordform connect base page             
              window.location.href = wordform_admin_view_connects_page_script_obj.wordform_connect_page_url;
            }
          });
          WordFormConfigureModalId.dialog("open");
    }

    // Generic save handler for webhook-style apps.
    $('body').on("click", ".wordform-connect-save-update-webhook-like-app-button", function() {
        let $button = $(this);
        let urlSelector = $button.data('url-selector');
        let feedbackSelector = $button.data('feedback-selector');
        let saveAction = $button.data('save-action');
        let urlParamKey = $button.data('url-param-key');
        let invalidMsg = $button.data('invalid-msg');
        let webhookUrl = $(urlSelector).val();
        let feedbackMsg = $(feedbackSelector);
        let params = {};

        feedbackMsg.html('').removeClass('msg-error');
        if ( $.trim( webhookUrl ).length !== 0 && isValidUrl( webhookUrl ) ) {
            params[ urlParamKey ] = webhookUrl;
            $.ajax({
                type:"POST",
                url: wordform_admin_view_connects_page_script_obj.adminajax_url,
                data : {
                        action    : saveAction,
                        security  : wordform_admin_view_connects_page_script_obj.nonce,
                        params 	: params
                        },
                success: function(data) {
                    console.log(data);
                    let jsonData = JSON.parse( data );
                    console.log( jsonData );
                if ( jsonData.status == 'success' ) {
                    feedbackMsg.html(buildIntegrationFeedbackHtml(jsonData, saveAction, $button.data('application-slug'))).addClass('text-success');
                    if ( jsonData.configuredApplication ) {
                        syncConfiguredApplicationUi(jsonData.configuredApplication);
                        let $modalBody = $button.closest('.ui-dialog-content, [id$="APIModal"]');
                        $modalBody.find('.wordform-connect-post-save-cta').remove();
                        const postSaveMarkup = buildPostSaveConnectMarkup(jsonData.configuredApplication);
                        if ( postSaveMarkup ) {
                            $modalBody.find(feedbackSelector).after(postSaveMarkup);
                        }
                    }
                }
                else if ( jsonData.status == 'warning' ) {
                    feedbackMsg.html(buildIntegrationFeedbackHtml(jsonData, saveAction, $button.data('application-slug'))).addClass('text-success');
                    if ( jsonData.configuredApplication ) {
                        syncConfiguredApplicationUi(jsonData.configuredApplication);
                        let $modalBody = $button.closest('.ui-dialog-content, [id$="APIModal"]');
                        $modalBody.find('.wordform-connect-post-save-cta').remove();
                        const postSaveMarkup = buildPostSaveConnectMarkup(jsonData.configuredApplication);
                        if ( postSaveMarkup ) {
                            $modalBody.find(feedbackSelector).after(postSaveMarkup);
                        }
                    }
                }
                    else if ( jsonData.status == 'fail' ) {
                        feedbackMsg.html(buildIntegrationFeedbackHtml(jsonData, saveAction, $button.data('application-slug'))).addClass('text-error');
                    }
                },
                error: function( xhr, status, error ) {
                    console.log(xhr);
                    console.log(status);
                    console.log(error);
                }
            }); // $.ajax
        }
        else {
            feedbackMsg.html('<i class="fa-solid fa-circle-info"></i> ' + invalidMsg).addClass('msg-error');
        }
    });

    // Generic save handler for app configuration forms with multiple required fields.
    $('body').on("click", ".wordform-connect-save-update-app-fields-button", function() {
        let $button = $(this);
        let saveAction = $(this).data('save-action');
        let feedbackSelector = $(this).data('feedback-selector');
        let fieldsConfigRaw = $(this).attr('data-fields-config');
        let feedbackMsg = $(feedbackSelector);
        let params = {};
        let fieldsConfig = [];
        let hasValidationError = false;

        feedbackMsg.html('').removeClass('msg-error text-error text-warning text-success');

        try {
            fieldsConfig = JSON.parse(fieldsConfigRaw);
        } catch (error) {
            console.log(error);
            feedbackMsg.html('Configuration fields data is invalid.').addClass('text-error');
            return;
        }

        if ( ! Array.isArray(fieldsConfig) || fieldsConfig.length === 0 ) {
            feedbackMsg.html('Configuration fields data is missing.').addClass('text-error');
            return;
        }

        fieldsConfig.forEach(function(fieldConfig) {
            let fieldValue = $(fieldConfig.selector).val();
            fieldValue = typeof fieldValue === 'string' ? fieldValue.trim() : fieldValue;

            if ( fieldConfig.validation === 'optional' ) {
                params[fieldConfig.paramKey] = fieldValue || '';
                return;
            }

            if ( fieldConfig.validation === 'url' && ! isValidUrl(fieldValue) ) {
                hasValidationError = true;
                feedbackMsg.html(fieldConfig.invalidMessage || 'Please enter valid value.').addClass('msg-error');
                return;
            }

            if ( ! fieldValue || $.trim(fieldValue).length === 0 ) {
                hasValidationError = true;
                feedbackMsg.html(fieldConfig.invalidMessage || 'Please enter required value.').addClass('msg-error');
                return;
            }

            params[fieldConfig.paramKey] = fieldValue;
        });

        if ( hasValidationError ) {
            scrollConnectFeedbackIntoView(feedbackSelector);
            return;
        }

        $.ajax({
            type:"POST",
            url: wordform_admin_view_connects_page_script_obj.adminajax_url,
            data : {
                    action    : saveAction,
                    security  : wordform_admin_view_connects_page_script_obj.nonce,
                    params 	: params
                    },
            success: function(data) {
                console.log(data);
                    let jsonData = JSON.parse( data );
                    console.log( jsonData );
                if ( jsonData.status == 'success' ) {
                    feedbackMsg.html(buildIntegrationFeedbackHtml(jsonData, saveAction, $button.data('application-slug'))).addClass('text-success');
                    scrollConnectFeedbackIntoView(feedbackSelector);
                    if ( jsonData.configuredApplication ) {
                        upsertConfiguredApplicationOption(jsonData.configuredApplication);
                        let $modalBody = $button.closest('.ui-dialog-content, [id$="APIModal"]');
                        $modalBody.find('.wordform-connect-post-save-cta').remove();
                        const postSaveMarkup = buildPostSaveConnectMarkup(jsonData.configuredApplication);
                        if ( postSaveMarkup ) {
                            $modalBody.find(feedbackSelector).after(postSaveMarkup);
                        }
                    }
                    if ( jsonData.authRedirectUri ) {
                        setTimeout(function() { window.location.href = jsonData.authRedirectUri; }, 2000);
                    }
                }
                else if ( jsonData.status == 'warning' ) {
                    feedbackMsg.html(buildIntegrationFeedbackHtml(jsonData, saveAction, $button.data('application-slug'))).addClass('text-success');
                    scrollConnectFeedbackIntoView(feedbackSelector);
                    if ( jsonData.configuredApplication ) {
                        upsertConfiguredApplicationOption(jsonData.configuredApplication);
                        let $modalBody = $button.closest('.ui-dialog-content, [id$="APIModal"]');
                        $modalBody.find('.wordform-connect-post-save-cta').remove();
                        const postSaveMarkup = buildPostSaveConnectMarkup(jsonData.configuredApplication);
                        if ( postSaveMarkup ) {
                            $modalBody.find(feedbackSelector).after(postSaveMarkup);
                        }
                    }
                    if ( jsonData.authRedirectUri ) {
                        setTimeout(function() { window.location.href = jsonData.authRedirectUri; }, 2000);
                    }
                }
                else if ( jsonData.status == 'fail' ) {
                    feedbackMsg.html(buildIntegrationFeedbackHtml(jsonData, saveAction, $button.data('application-slug'))).addClass('text-error');
                    scrollConnectFeedbackIntoView(feedbackSelector);
                }
            },
            error: function( xhr, status, error ) {
                console.log(xhr);
                console.log(status);
                console.log(error);
            }
        }); // $.ajax
    });

    $('body').on('click', '.wordform-connect-fetch-app-resource-button', function() {
        let $button = $(this);
        let saveAction = $button.data('fetch-action');
        let feedbackSelector = $button.data('feedback-selector');
        let fieldsConfigRaw = $button.attr('data-fields-config');
        let targetSelectSelector = $button.data('target-select');
        let targetInputSelector = $button.data('target-input');
        let targetLabelInputSelector = $button.data('target-label-input');
        let emptyLabel = $button.data('empty-label') || 'Select';
        let feedbackMsg = $(feedbackSelector);
        let $targetSelect = $(targetSelectSelector);
        let $targetInput = $(targetInputSelector);
        let params = {};
        let fieldsConfig = [];
        let hasValidationError = false;

        feedbackMsg.html('').removeClass('msg-error text-error text-warning text-success');

        try {
            fieldsConfig = JSON.parse(fieldsConfigRaw);
        } catch (error) {
            console.log(error);
            feedbackMsg.html('Configuration fields data is invalid.').addClass('text-error');
            return;
        }

        fieldsConfig.forEach(function(fieldConfig) {
            let fieldValue = $(fieldConfig.selector).val();
            fieldValue = typeof fieldValue === 'string' ? fieldValue.trim() : fieldValue;

            if ( fieldConfig.validation === 'url' && ! isValidUrl(fieldValue) ) {
                hasValidationError = true;
                feedbackMsg.html(fieldConfig.invalidMessage || 'Please enter valid value.').addClass('msg-error');
                return;
            }

            if ( !fieldValue || $.trim(fieldValue).length === 0 ) {
                hasValidationError = true;
                feedbackMsg.html(fieldConfig.invalidMessage || 'Please enter required value.').addClass('msg-error');
                return;
            }

            params[fieldConfig.paramKey] = fieldValue;
        });

        if ( hasValidationError ) {
            return;
        }

        $button.prop('disabled', true);
        feedbackMsg.html('<i class="fa-solid fa-spinner fa-spin-pulse"></i> Verifying and loading resources...').addClass('text-warning');

        $.ajax({
            type: "POST",
            url: wordform_admin_view_connects_page_script_obj.adminajax_url,
            data: {
                action: saveAction,
                security: wordform_admin_view_connects_page_script_obj.nonce,
                params: params
            },
            success: function(data) {
                let jsonData = JSON.parse(data);
                console.log(jsonData);

                if ( jsonData.status === 'success' && Array.isArray(jsonData.resources) ) {
                    let currentValue = $targetInput.val();
                    populateIntegrationResourceSelect($targetSelect, jsonData.resources, emptyLabel, currentValue);
                    if ( !currentValue && jsonData.resources.length ) {
                        $targetSelect.val(jsonData.resources[0].value);
                    }
                    $targetSelect.trigger('change');
                    feedbackMsg.html(buildIntegrationFeedbackHtml(jsonData, saveAction, $button.data('application-slug'))).removeClass('text-error').addClass('text-success');
                } else if ( jsonData.status === 'warning' ) {
                    feedbackMsg.html(buildIntegrationFeedbackHtml(jsonData, saveAction, $button.data('application-slug'))).removeClass('text-error').addClass('text-warning');
                } else {
                    feedbackMsg.html(buildIntegrationFeedbackHtml($.extend({ comment: jsonData.comment || 'Resources could not be loaded.' }, jsonData), saveAction, $button.data('application-slug'))).removeClass('text-success').addClass('text-error');
                }
            },
            error: function(xhr, status, error) {
                console.log(xhr);
                console.log(status);
                console.log(error);
                feedbackMsg.html('Resources could not be loaded right now.').removeClass('text-success').addClass('text-error');
            },
            complete: function() {
                $button.prop('disabled', false);
            }
        });
    });

    $('body').on('click', '.wordform-connect-post-save-connect-btn', function() {
        const $cta = $(this).closest('.wordform-connect-post-save-cta');
        const formId = $cta.find('.wordform-connect-post-save-form-select').val();
        const applicationId = $cta.data('application-id');

        if (!formId || !applicationId) {
            return;
        }

        $('#WordFormConnectSelectForm').val(formId);
        $('#WordFormSelectConnectionName').val(applicationId.toString());

        const $modal = $cta.closest('.ui-dialog-content, [id$="APIModal"]');
        if ($modal.length && $modal.hasClass('ui-dialog-content')) {
            $modal.data('wordform-skip-reload', true).dialog('close');
        } else if ($modal.length) {
            $modal.data('wordform-skip-reload', true);
        }

        setTimeout(function() {
            $('.wordform-connection-create-icon').trigger('click');
        }, 180);
    });

    $('body').on('click', '.wordform-use-configured-application-btn', function() {
        const applicationId = ($(this).data('application-id') || '').toString();

        if (!applicationId.length) {
            return;
        }

        $('#WordFormSelectConnectionName').val(applicationId);
        scrollToConnectionCreatePanel();
    });

    $('body').on('click', '.wordform-scroll-to-configure-apps-btn', function() {
        const $configureToolbar = $('.wordform-connect-configure-toolbar').first();
        if (!$configureToolbar.length) {
            return;
        }

        $('html, body').stop(true).animate({
            scrollTop: Math.max(0, $configureToolbar.offset().top - 36)
        }, 220);
    });

    $('body').on('change', '.wordform-connect-resource-select', function() {
        let $select = $(this);
        let selectedValue = $select.val() || '';
        let selectedLabel = $select.find('option:selected').text() || '';
        let modalRoot = $select.closest('.ui-dialog-content, [id$="APIModal"]');

        if ($select.attr('id') === 'MailchimpAudienceSelect') {
            modalRoot.find('.mailchimp-audience-id').val(selectedValue);
            modalRoot.find('.mailchimp-audience-label').val(selectedValue ? selectedLabel : '');
        } else if ($select.attr('id') === 'BrevoListSelect') {
            modalRoot.find('.brevo-list-id').val(selectedValue);
            modalRoot.find('.brevo-list-label').val(selectedValue ? selectedLabel : '');
        } else if ($select.attr('id') === 'ActivecampaignListSelect') {
            modalRoot.find('.activecampaign-list-id').val(selectedValue);
            modalRoot.find('.activecampaign-list-label').val(selectedValue ? selectedLabel : '');
        } else if ($select.attr('id') === 'AirtableTableSelect') {
            modalRoot.find('.airtable-table-name').val(selectedValue);
        }
    });

    $('body').on('click', '.wordform-connect-check-webhook-endpoint-button', function() {
        let $button = $(this);
        let urlSelector = $button.data('url-selector');
        let feedbackSelector = $button.data('feedback-selector');
        let checkAction = $button.data('check-action');
        let applicationSlug = ($button.data('application-slug') || '').toString();
        let invalidMsg = $button.data('invalid-msg') || 'Please enter a valid webhook URL.';
        let webhookUrl = $(urlSelector).val();
        let feedbackMsg = $(feedbackSelector);

        feedbackMsg.html('').removeClass('msg-error text-error text-warning text-success');

        if ( $.trim( webhookUrl ).length === 0 || ! isValidUrl( webhookUrl ) ) {
            feedbackMsg.html('<i class="fa-solid fa-circle-info"></i> ' + invalidMsg).addClass('msg-error');
            return;
        }

        $button.prop('disabled', true);
        feedbackMsg.html('<i class="fa-solid fa-spinner fa-spin-pulse"></i> Checking endpoint reachability...').addClass('text-warning');

        $.ajax({
            type: "POST",
            url: wordform_admin_view_connects_page_script_obj.adminajax_url,
            data : {
                action   : checkAction,
                security : wordform_admin_view_connects_page_script_obj.nonce,
                params   : {
                    webhookUrl: webhookUrl,
                    applicationSlug: applicationSlug
                }
            },
            success: function(data) {
                console.log(data);
                let jsonData = JSON.parse(data);
                feedbackMsg.removeClass('msg-error text-error text-warning text-success');

                if ( jsonData.status == 'success' ) {
                    feedbackMsg.html(buildIntegrationFeedbackHtml(jsonData, checkAction, applicationSlug)).addClass('text-success');
                }
                else if ( jsonData.status == 'warning' ) {
                    feedbackMsg.html(buildIntegrationFeedbackHtml(jsonData, checkAction, applicationSlug)).addClass('text-warning');
                }
                else {
                    feedbackMsg.html(buildIntegrationFeedbackHtml($.extend({ comment: jsonData.comment || 'Endpoint could not be checked.' }, jsonData), checkAction, applicationSlug)).addClass('text-error');
                }
            },
            error: function(xhr, status, error) {
                console.log(xhr);
                console.log(status);
                console.log(error);
                feedbackMsg.removeClass('msg-error text-warning text-success').html('Endpoint could not be checked right now.').addClass('text-error');
            },
            complete: function() {
                $button.prop('disabled', false);
            }
        });
    });

    // Sending off Forms data into connected application based on 'deactivate' button click
    $('body').on('click', '.wordform-activate-deactivate-sending-forms-data', function() {
        let applicationSlug = $(this).data('activate-deactivate-application-slug');
        let applicationName = $(this).data('application-name');
        let WordFormSendingDataStatusChangeTo = $(this).data('application-status-change-to');        
        console.log( applicationSlug );
        console.log(WordFormSendingDataStatusChangeTo);
        let dialogMsg = '';
        let dialogMsgAppendDiv = '<div class="wordform-sending-data-activating-deactivating-status"></div>';
        if ( WordFormSendingDataStatusChangeTo == 'inactive' ) {
            dialogMsg = 'Do you want to de-activate ' + applicationName + ' to send WordForm users submitted data?' + dialogMsgAppendDiv;
        }
        else {
            dialogMsg = 'Do you want to Activate ' + applicationName + ' to send WordForm users submitted data?' + dialogMsgAppendDiv;
        }
        let WordFormApplicationActiveInactiveAskModalId = $('#WordFormApplicationActivateDeactivateConfirmModal');
        WordFormApplicationActiveInactiveAskModalId.dialog({
            autoOpen: true,
            minHeight: 200,
            minWidth: 450,
            modal: true,
            dialogClass: 'wordform-admin-dialog',
            buttons: {
              /*"Connect": function() { 
                console.log('Connect...Testing');
              },*/
              "Confirm": function() {
                console.log('Confirmed!');
                WordFormFormsSendingDataIntoApplicationActiveInactive( applicationSlug, WordFormSendingDataStatusChangeTo );
              },
              Close: function() {
                WordFormApplicationActiveInactiveAskModalId.dialog( "close" );
              }
            },
            close: function() {
              // On closing Modal dialog - Redirect into wordform connect base page             
            //   window.location.href = wordform_admin_view_connects_page_script_obj.wordform_connect_page_url;
            }
          });
          WordFormApplicationActiveInactiveAskModalId.html(dialogMsg).dialog("open");
    });

    // WordForm Forms Data sending activate - deactivate into Third-Party Application Ajax
    function WordFormFormsSendingDataIntoApplicationActiveInactive( applicationSlug = '', WordFormSendingDataStatusChangeTo = '' ) {
        let WordFormSendingDataStatusChangeMsg = $('.wordform-sending-data-activating-deactivating-status');
        // let WordFormSendingDataStatusChangeTo = $('.wordform-activate-deactivate-sending-forms-data').data('application-status-change-to');        
        console.log('Before Ajax Call Application Slug: '+ applicationSlug );
        console.log(WordFormSendingDataStatusChangeTo);
        let params = {};
        params.applicationSlug = applicationSlug;
        params.statusChangeTo = WordFormSendingDataStatusChangeTo;
        WordFormSendingDataStatusChangeMsg.html('<i class="fa-solid fa-spinner fa-spin-pulse fa-xl"></i>');
        $.ajax({
            type:"POST",		  
            url: wordform_admin_view_connects_page_script_obj.adminajax_url,
            data : {			    			
                    action    : 'wordform_forms_data_send_activate_deactivate',
                    security  : wordform_admin_view_connects_page_script_obj.nonce,				
                    params 	  : params
                    },		  
            success: function(data) {    
                // wordformConnectingMsgShowElement.html("").removeClass('text-warning text-error'); // Remove if earlier connecting messages shown
                // wordformModalConnectButton.prop( 'disabled', false );             
                // console.log(data); 
                let jsonData = JSON.parse( data );
                console.log( jsonData );
                if ( jsonData.status == 'success' ) {		
                    if ( params.statusChangeTo && params.statusChangeTo == 'inactive' ) {
                        WordFormSendingDataStatusChangeMsg.html("<h4>Deactivated Successfully.</h4>").addClass('text-success');                                        
                    }
                    if ( params.statusChangeTo && params.statusChangeTo == 'active' ) {
                        WordFormSendingDataStatusChangeMsg.html("<h4>Activated Successfully.</h4>").addClass('text-success');                                        
                    }
                    if ( jsonData.configuredApplication ) {
                        syncConfiguredApplicationUi(
                            jsonData.configuredApplication,
                            {
                                isConfigured: true,
                                isActive: params.statusChangeTo === 'active'
                            }
                        );
                    } else if ( params.statusChangeTo === 'inactive' ) {
                        removeConfiguredApplicationOption(applicationSlug);
                        renderIntegrationCardState(applicationSlug, {
                            applicationName: applicationName,
                            isConfigured: true,
                            isActive: false,
                            configuredApplication: null
                        });
                    }
                    setTimeout( function() {
                        $('#WordFormApplicationActivateDeactivateConfirmModal').dialog('close');
                    }, 900 );
                }
                else if ( jsonData.status == 'warning' ) {			
                }
                else if ( jsonData.status == 'fail' ) {			
                    WordFormSendingDataStatusChangeMsg.html('<h4>'+ jsonData.comment +'</h4>').addClass('text-error');
                }
    
                },
            error: function( xhr, status, error ) { 
                console.log(xhr); 
                console.log(status); 
                console.log(error); 				 
                }
            }); // $.ajax	    
    }

    
}); // jQuery(document).ready(function($)
