var WordformGlobalApp = WordformGlobalApp || {}; // Create or use existing namespace

/**
 * Find overall min and max length allowed in regex expression
 * @param pattern - Regex Pattern
 * try/catch ensures malformed regex input won’t crash the function
 * Fallback: always returns { min: 6, max: 14 } when nothing valid is found
 * @returns object - {min,max}
 */
function getOverallMinMax(pattern) {
  const regex = /\{(\d+)(?:,(\d+))?\}/g;
  let match;
  let totalMin = 0;
  let totalMax = 0;

  while ((match = regex.exec(pattern)) !== null) {
    const min = parseInt(match[1], 10);
    const max = match[2] ? parseInt(match[2], 10) : min; // if no max, same as min
    totalMin += min;
    totalMax += max;
  }

  return { min: totalMin, max: totalMax };
}


/**
 * Show WordForm jQuery Dialog
 * @param {string} message - The message text to display inside the modal.
 * @param {string} title - Optional title for the dialog.
 */
function showWordformDialog(elementType) {
    let $wrapper = jQuery('.wordform-fullscreen-wrapper');
    let $dialog = jQuery('#wordform-generic-dialog');

    // Create dialog inside wrapper if missing
    if ($dialog.length === 0) {
        $wrapper.append(`
            <div id="wordform-generic-dialog" title="" style="display:none;">
                <p class="wordform-dialog-message"></p>
            </div>
        `);
        $dialog = jQuery('#wordform-generic-dialog');
    }

    // Define title, icon & message
    let iconHtml = '';
    let title = 'Notice';
    let message = '';

    if (typeof elementType === 'object' && elementType !== null) {
        iconHtml = elementType.iconHtml || '';
        title = elementType.title || title;
        message = elementType.message || message;
    } else if (elementType === 'captcha') {
        iconHtml = '<i class="fa-solid fa-shield"></i>';
        title = 'Numeric Captcha';
        message = 'Numeric Captcha should use once with any Form!';
    } else if (elementType === 'gcaptcha') {
        iconHtml = '<i class="fa-brands fa-google"></i>';
        title = 'Google reCaptcha';
        message = 'Google reCaptcha should use once with any Form!';
    } else if (elementType === 'hcaptcha') {
        iconHtml = '<i class="fa-solid fa-shield-halved"></i>';
        title = 'hCaptcha';
        message = 'hCaptcha should use once with any Form!';
    } else {
        message = 'This element is already added once with your Form!';
    }

    // Destroy any existing dialog safely
    if ($dialog.hasClass('ui-dialog-content')) {
        try { $dialog.dialog('destroy'); } catch (e) {}
    }

    // Slight delay to avoid drag DOM timing issue
    setTimeout(() => {
        $dialog.find('.wordform-dialog-message').html(message);

        $dialog.dialog({
            appendTo: '.wordform-fullscreen-wrapper',
            modal: true,
            width: 400,
            dialogClass: 'wordform-admin-dialog',
            create: function () {
                // Allow HTML in title
                jQuery(this)
                    .closest('.ui-dialog')
                    .find('.ui-dialog-title')
                    .html(`${iconHtml} ${title}`);
            },
            buttons: {
                OK: function () {
                    jQuery(this).dialog('close');
                }
            },
            open: function () {
                jQuery('.ui-widget-overlay').addClass('wordform-dialog-overlay');
            },
            // ✅ When dialog completely closes (via OK or ✖)
            close: function () {
                $dialog.hide();
                // Trigger form name element click AFTER modal fully closed
                jQuery('.wordform-input-element-div-wrapper-form-name').trigger('click');
            }
        });
    }, 50);
}

function wordformBuilderHasMixedCaptchaConflict(elementName = '') {
    const hasGoogleRecaptcha = jQuery('.wordform-dropzone-div-wrapper').find('[data-input-element-type="gcaptcha"]').length > 0;
    const hasHCaptcha = jQuery('.wordform-dropzone-div-wrapper').find('[data-input-element-type="hcaptcha"]').length > 0;

    if (elementName === 'gcaptcha' && hasHCaptcha) {
        return {
            iconHtml: '<i class="fa-brands fa-google"></i>',
            title: 'Google reCaptcha',
            message: 'Google reCaptcha and hCaptcha should not be added together in the same form. Use only one verification provider at a time.'
        };
    }

    if (elementName === 'hcaptcha' && hasGoogleRecaptcha) {
        return {
            iconHtml: '<i class="fa-solid fa-shield-halved"></i>',
            title: 'hCaptcha',
            message: 'hCaptcha and Google reCaptcha should not be added together in the same form. Use only one verification provider at a time.'
        };
    }

    if (!elementName && hasGoogleRecaptcha && hasHCaptcha) {
        return {
            iconHtml: '<i class="fa-solid fa-shield"></i>',
            title: 'Captcha Conflict',
            message: 'Google reCaptcha and hCaptcha cannot be used together in the same form. Remove one of them before saving.'
        };
    }

    return null;
}



jQuery(document).ready(function($) {				
	// console.log('Localized WordForm Data');	
	// console.log( sc_wordform_metabox_script_obj );	
	//console.log('jQuery Version: '+ $().jquery );
	let wordformBuilderReconstructionInProgress = false;

	function wordformIsGatewayBuilderElement(elementName) {
		return ['stripe', 'paypal', 'square', 'authorizenet'].indexOf(elementName) !== -1;
	}

	function wordformBuilderHasPaymentMethodElement() {
		return is_element_added_into_dropzone('payment_method');
	}

	function wordformBuilderGatewayElementCount() {
		return $('.wordform-dropzone-div-wrapper [data-input-element-type="stripe"], .wordform-dropzone-div-wrapper [data-input-element-type="paypal"], .wordform-dropzone-div-wrapper [data-input-element-type="square"], .wordform-dropzone-div-wrapper [data-input-element-type="authorizenet"]').length;
	}

	function wordformBuilderHasDuplicateGatewayElement(elementName) {
		return wordformIsGatewayBuilderElement(elementName) && is_element_added_into_dropzone(elementName);
	}

	function wordformShowPaymentGatewayRuleDialog() {
		showWordformDialog({
			iconHtml: '<i class="fa-solid fa-credit-card"></i>',
			title: 'Payment Gateway Rule',
			message: 'To offer multiple payment gateways in one form, first add the Payment Method element. Without Payment Method, keep only one individual gateway element in the form.'
		});
	}

	function wordformShowPageBreakRuleDialog(message) {
		showWordformDialog({
			iconHtml: '<i class="fa-solid fa-forward-step"></i>',
			title: 'Page Break Rule',
			message: message
		});
	}

	function wordformBuilderHasInvalidGatewayConfiguration(nextGatewayElementName = '') {
		const gatewayCount = wordformBuilderGatewayElementCount();
		const hasPaymentMethod = wordformBuilderHasPaymentMethodElement();
		const nextGatewayCount = wordformIsGatewayBuilderElement(nextGatewayElementName) ? 1 : 0;

		if (hasPaymentMethod) {
			return false;
		}

		return (gatewayCount + nextGatewayCount) > 1;
	}

	function wordformGetPageBreakLayoutValidation() {
		const elementTypes = $('.wordform-dropzone-div-wrapper .wordform-input-element-div-wrapper').map(function() {
			return $(this).data('input-element-type');
		}).get();
		const pageBreakIndexes = [];

		elementTypes.forEach(function(type, index) {
			if (type === 'pagebreak') {
				pageBreakIndexes.push(index);
			}
		});

		if (!pageBreakIndexes.length) {
			return { valid: true };
		}

		if (pageBreakIndexes[0] === 0) {
			return { valid: false, message: 'Page Break cannot be the first builder element. Add at least one field before it.' };
		}

		if (pageBreakIndexes[pageBreakIndexes.length - 1] === (elementTypes.length - 1)) {
			return { valid: false, message: 'Page Break cannot be the last builder element. Keep at least one field in the final step.' };
		}

		for (let i = 1; i < pageBreakIndexes.length; i++) {
			if (pageBreakIndexes[i] === pageBreakIndexes[i - 1] + 1) {
				return { valid: false, message: 'Two Page Break elements cannot stay beside each other. Add at least one field between steps.' };
			}
		}

		const finalPageBreakIndex = pageBreakIndexes[pageBreakIndexes.length - 1];
		const finalStepRestrictedTypes = ['captcha', 'gcaptcha', 'hcaptcha', 'stripe', 'paypal', 'square', 'authorizenet'];

		for (let i = 0; i < finalPageBreakIndex; i++) {
			if (finalStepRestrictedTypes.indexOf(elementTypes[i]) !== -1) {
				return { valid: false, message: 'Captcha and payment gateway elements should stay in the final step. Move them below the last Page Break.' };
			}
		}

		return { valid: true };
	}

	function wordformElementSupportsAdminLabel(elementType) {
		return [
			'text',
			'firstlastname',
			'number',
			'textarea',
			'richeditor',
			'range',
			'url',
			'date',
			'time',
			'datetime',
			'tel',
			'email',
			'address',
			'maskinput',
			'rating',
			'signature',
			'hidden',
			'radio',
			'checkbox',
			'select',
			'upload',
			'terms',
			'gdpr',
			'likert',
			'payment_item',
			'payment_coupon',
			'payment_method',
			'payment_custom_amount',
			'payment_quantity',
			'payment_summary',
			'stripe',
			'paypal',
			'square',
			'authorizenet'
		].indexOf(elementType) !== -1;
	}

	function wordformSlugifyAdminLabel(value, fallback = 'field') {
		let normalizedValue = String(value || '')
			.toLowerCase()
			.replace(/&/g, ' and ')
			.replace(/[^a-z0-9]+/g, '_')
			.replace(/^_+|_+$/g, '');

		if (!normalizedValue.length) {
			normalizedValue = fallback;
		}

		return normalizedValue;
	}

	function wordformDefaultAdminLabelBase(elementType, elementIndex, publicLabel = '', variant = '') {
		const fallbackMap = {
			text: 'text',
			firstlastname: variant === 'last' ? 'last_name' : 'first_name',
			number: 'number',
			textarea: 'textarea',
			richeditor: 'richeditor',
			range: 'range',
			url: 'url',
			date: 'date',
			time: 'time',
			datetime: 'datetime',
			tel: 'phone',
			email: 'email',
			address: 'address',
			maskinput: 'masked_input',
			rating: 'rating',
			likert: 'likert',
			signature: 'signature',
			hidden: 'hidden_field',
			radio: 'multiple_choice',
			checkbox: 'checkboxes',
			select: 'dropdown',
			upload: 'upload',
			pagebreak: 'pagebreak',
			terms: 'terms',
			gdpr: 'gdpr_consent',
			payment_item: 'payment_item',
			payment_coupon: 'payment_coupon',
			payment_method: 'payment_method',
			payment_custom_amount: 'custom_amount',
			payment_quantity: 'quantity',
			payment_summary: 'payment_summary',
			stripe: 'stripe_payment',
			paypal: 'paypal_payment',
			square: 'square_payment',
			authorizenet: 'authorizenet_payment'
		};

		return wordformSlugifyAdminLabel(
			publicLabel,
			fallbackMap[elementType] || (variant ? `${variant}_field` : 'field')
		) + '_' + elementIndex;
	}

	function wordformGetOptionsWrapperType($wrapper) {
		return $wrapper.data('wrapper-element-type') || '';
	}

	function wordformAppendAdminLabelControls($optionsWrapper, elementType, elementIndex) {
		if (!$optionsWrapper.length || !wordformElementSupportsAdminLabel(elementType) || $optionsWrapper.find('.wordform-admin-label-options-group').length) {
			return;
		}

		const commonHelpText = '<small><em>( Used internally in reports, exports, and integrations. Keep it unique. )</em></small>';

		if (elementType === 'firstlastname') {
			$optionsWrapper.append(
				'<hr/>' +
				'<div class="wordform-admin-label-options-group">' +
					'<h4>First Name Admin Label:</h4>' +
					'<ul class="wordform-admin-label-list">' +
						'<li><input class="wordform-admin-label-first-input" data-wordform-admin-label-mode="auto" type="text" placeholder="' + wordformDefaultAdminLabelBase(elementType, elementIndex, 'First Name', 'first') + '" /></li>' +
						'<li>' + commonHelpText + '</li>' +
					'</ul>' +
					'<h4>Last Name Admin Label:</h4>' +
					'<ul class="wordform-admin-label-list">' +
						'<li><input class="wordform-admin-label-last-input" data-wordform-admin-label-mode="auto" type="text" placeholder="' + wordformDefaultAdminLabelBase(elementType, elementIndex, 'Last Name', 'last') + '" /></li>' +
						'<li>' + commonHelpText + '</li>' +
					'</ul>' +
				'</div>'
			);
			return;
		}

		$optionsWrapper.append(
			'<hr/>' +
			'<div class="wordform-admin-label-options-group">' +
				'<h4>Admin Label:</h4>' +
				'<ul class="wordform-admin-label-list">' +
					'<li><input class="wordform-admin-label-input" data-wordform-admin-label-mode="auto" type="text" placeholder="' + wordformDefaultAdminLabelBase(elementType, elementIndex) + '" /></li>' +
					'<li>' + commonHelpText + '</li>' +
				'</ul>' +
			'</div>'
		);
	}

	function wordformSetAdminLabelField($field, value, mode = 'auto') {
		if (!$field.length) {
			return;
		}

		$field.val(value).attr('value', value).attr('data-wordform-admin-label-mode', mode);
	}

	function wordformGetPublicLabelValueForAdminSync($wrapper, variant = '') {
		const elementType = wordformGetOptionsWrapperType($wrapper);

		switch (elementType) {
			case 'text':
				return $wrapper.find('.wordform-text-label-name').val() || 'Name';
			case 'firstlastname':
				if (variant === 'last') {
					return $wrapper.find('.wordform-lastname-label-name').val() || 'Last Name';
				}
				return $wrapper.find('.wordform-firstname-label-name').val() || 'First Name';
			case 'number':
				return $wrapper.find('.wordform-number-label-name').val() || 'Number';
			case 'textarea':
				return $wrapper.find('.wordform-textarea-label-name').val() || 'Description';
			case 'richeditor':
				return $wrapper.find('.wordform-richeditor-label-name').val() || 'Rich Text Editor';
			case 'range':
				return $wrapper.find('.wordform-range-label-name').val() || 'Range';
			case 'url':
				return $wrapper.find('.wordform-url-label-name').val() || 'URL';
			case 'date':
				return $wrapper.find('.wordform-date-label-name').val() || 'Date';
			case 'time':
				return $wrapper.find('.wordform-time-label-name').val() || 'Time';
			case 'datetime':
				return $wrapper.find('.wordform-datetime-label-name').val() || 'DateTime';
			case 'tel':
				return $wrapper.find('.wordform-tel-label-name').val() || 'Tel';
			case 'email':
				return $wrapper.find('.wordform-email-label-name').val() || 'Email';
			case 'address':
				return $wrapper.find('.wordform-address-label-name').val() || 'Address';
			case 'maskinput':
				return $wrapper.find('.wordform-maskinput-label-name').val() || 'Masked Input';
			case 'rating':
				return $wrapper.find('.wordform-rating-label-name').val() || 'Rating';
			case 'likert':
				return $wrapper.find('.wordform-likert-label-name').val() || 'Likert Scale';
			case 'signature':
				return $wrapper.find('.wordform-signature-label-name').val() || 'Signature';
			case 'hidden':
				return $wrapper.find('.wordform-hidden-label-name').val() || 'Hidden Field';
			case 'radio':
				return $wrapper.find('.wordform-radio-label-name').val() || 'Multiple Choice';
			case 'checkbox':
				return $wrapper.find('.wordform-checkbox-label-name').val() || 'Checkboxes';
			case 'select':
				return $wrapper.find('.wordform-select-label-name').val() || 'Dropdown Options';
			case 'upload':
				return $wrapper.find('.wordform-upload-label-name').val() || 'Upload';
			case 'terms':
				return $wrapper.find('.wordform-terms-label-name').val() || 'Terms';
			case 'gdpr':
				return $wrapper.find('.wordform-gdpr-label-name').val() || 'GDPR Consent';
			case 'payment_item':
				return $wrapper.find('.wordform-payment-item-label-name').val() || 'Payment Item';
			case 'payment_coupon':
				return $wrapper.find('.wordform-payment-coupon-label-name').val() || 'Coupon Code';
			case 'payment_method':
				return $wrapper.find('.wordform-payment-method-label-name').val() || 'Payment Method';
			case 'payment_custom_amount':
				return $wrapper.find('.wordform-payment-custom-amount-label-name').val() || 'Custom Amount';
			case 'payment_quantity':
				return $wrapper.find('.wordform-payment-quantity-label-name').val() || 'Quantity';
			case 'payment_summary':
				return $wrapper.find('.wordform-payment-summary-label-name').val() || 'Payment Summary';
			case 'stripe':
				return $wrapper.find('.wordform-stripe-label-name').val() || 'Stripe Payment';
			case 'paypal':
				return $wrapper.find('.wordform-paypal-label-name').val() || 'PayPal Payment';
			case 'square':
				return $wrapper.find('.wordform-square-label-name').val() || 'Square Payment';
			case 'authorizenet':
				return $wrapper.find('.wordform-authorizenet-label-name').val() || 'Authorize.Net Payment';
			default:
				return '';
		}
	}

	function wordformEnsureInitialAdminLabelValues($optionsWrapper, elementType, elementIndex, savedElement = null) {
		if (!$optionsWrapper.length || !wordformElementSupportsAdminLabel(elementType)) {
			return;
		}

		if (elementType === 'firstlastname') {
			wordformSetAdminLabelField(
				$optionsWrapper.find('.wordform-admin-label-first-input'),
				(savedElement && savedElement.adminLabelFirst) ? savedElement.adminLabelFirst : wordformDefaultAdminLabelBase(elementType, elementIndex, wordformGetPublicLabelValueForAdminSync($optionsWrapper, 'first'), 'first'),
				(savedElement && savedElement.adminLabelFirst) ? 'manual' : 'auto'
			);
			wordformSetAdminLabelField(
				$optionsWrapper.find('.wordform-admin-label-last-input'),
				(savedElement && savedElement.adminLabelLast) ? savedElement.adminLabelLast : wordformDefaultAdminLabelBase(elementType, elementIndex, wordformGetPublicLabelValueForAdminSync($optionsWrapper, 'last'), 'last'),
				(savedElement && savedElement.adminLabelLast) ? 'manual' : 'auto'
			);
			return;
		}

		wordformSetAdminLabelField(
			$optionsWrapper.find('.wordform-admin-label-input'),
			(savedElement && savedElement.adminLabel) ? savedElement.adminLabel : wordformDefaultAdminLabelBase(elementType, elementIndex, wordformGetPublicLabelValueForAdminSync($optionsWrapper)),
			(savedElement && savedElement.adminLabel) ? 'manual' : 'auto'
		);
	}

	function wordformSyncAdminLabelFromPublicLabel($sourceField, variant = '') {
		const $optionsWrapper = $sourceField.closest('.show-hide-common-class-all-options-wrapper-element');
		const elementType = wordformGetOptionsWrapperType($optionsWrapper);
		const elementIndex = (($optionsWrapper.prop('id') || '').split('-')[1]) || '';

		if (!wordformElementSupportsAdminLabel(elementType) || !elementIndex) {
			return;
		}

		let $adminLabelField = $optionsWrapper.find('.wordform-admin-label-input');
		if (elementType === 'firstlastname') {
			$adminLabelField = (variant === 'last') ? $optionsWrapper.find('.wordform-admin-label-last-input') : $optionsWrapper.find('.wordform-admin-label-first-input');
		}

		if (!$adminLabelField.length) {
			return;
		}

		const currentMode = $adminLabelField.attr('data-wordform-admin-label-mode') || 'auto';
		if (currentMode === 'manual' && ($adminLabelField.val() || '').trim().length) {
			return;
		}

		wordformSetAdminLabelField(
			$adminLabelField,
			wordformDefaultAdminLabelBase(elementType, elementIndex, $sourceField.val(), variant),
			'auto'
		);
	}

	function wordformNormalizeUniqueAdminLabel(value, fallbackValue, usedLabels) {
		const baseLabel = wordformSlugifyAdminLabel(value, fallbackValue);
		let normalizedLabel = baseLabel;
		let suffixCounter = 2;

		while (usedLabels[normalizedLabel]) {
			normalizedLabel = baseLabel + '_' + suffixCounter;
			suffixCounter++;
		}

		usedLabels[normalizedLabel] = true;
		return normalizedLabel;
	}

	function wordformNormalizeAdminLabelsBeforeSave(inputElementArr) {
		const usedLabels = {};

		inputElementArr.forEach(function(element) {
			if (!element || !wordformElementSupportsAdminLabel(element.type)) {
				return;
			}

			const elementIndex = element.elementIndex || '';
			const $optionsWrapper = $('#wordformElementOptions-' + elementIndex);

			if (element.type === 'firstlastname') {
				element.adminLabelFirst = wordformNormalizeUniqueAdminLabel(
					element.adminLabelFirst,
					wordformDefaultAdminLabelBase(element.type, elementIndex, element.labelFirst || 'First Name', 'first'),
					usedLabels
				);
				element.adminLabelLast = wordformNormalizeUniqueAdminLabel(
					element.adminLabelLast,
					wordformDefaultAdminLabelBase(element.type, elementIndex, element.labelLast || 'Last Name', 'last'),
					usedLabels
				);

				wordformSetAdminLabelField($optionsWrapper.find('.wordform-admin-label-first-input'), element.adminLabelFirst, 'manual');
				wordformSetAdminLabelField($optionsWrapper.find('.wordform-admin-label-last-input'), element.adminLabelLast, 'manual');
				return;
			}

			element.adminLabel = wordformNormalizeUniqueAdminLabel(
				element.adminLabel,
				wordformDefaultAdminLabelBase(element.type, elementIndex, element.label || ''),
				usedLabels
			);
			wordformSetAdminLabelField($optionsWrapper.find('.wordform-admin-label-input'), element.adminLabel, 'manual');
		});

		return inputElementArr;
	}

	function wordformReadAdminLabelValue($optionsWrapper, elementType, elementIndex, variant = '') {
		if (!wordformElementSupportsAdminLabel(elementType)) {
			return '';
		}

		if (elementType === 'firstlastname') {
			const $field = variant === 'last' ? $optionsWrapper.find('.wordform-admin-label-last-input') : $optionsWrapper.find('.wordform-admin-label-first-input');
			const fallbackLabel = wordformGetPublicLabelValueForAdminSync($optionsWrapper, variant === 'last' ? 'last' : 'first');
			return ($field.val() || '').trim().length
				? $field.val()
				: wordformDefaultAdminLabelBase(elementType, elementIndex, fallbackLabel, variant === 'last' ? 'last' : 'first');
		}

		const $field = $optionsWrapper.find('.wordform-admin-label-input');
		return ($field.val() || '').trim().length
			? $field.val()
			: wordformDefaultAdminLabelBase(elementType, elementIndex, wordformGetPublicLabelValueForAdminSync($optionsWrapper));
	}

	function wordformElementSupportsSharedHelpText(elementType) {
		return [
			'text',
			'firstlastname',
			'number',
			'textarea',
			'richeditor',
			'range',
			'url',
			'date',
			'time',
			'datetime',
			'tel',
			'email',
			'address',
			'maskinput',
			'rating',
			'signature',
			'radio',
			'checkbox',
			'select',
			'upload'
			,
			'gdpr',
			'payment_coupon'
		].indexOf(elementType) !== -1;
	}

	function wordformAppendSharedHelpTextControl($optionsWrapper, elementType) {
		if (!$optionsWrapper.length || !wordformElementSupportsSharedHelpText(elementType) || $optionsWrapper.find('.wordform-shared-help-text-options-group').length) {
			return;
		}

		$optionsWrapper.append(
			'<hr/>' +
			'<div class="wordform-shared-help-text-options-group">' +
				'<h4>Description / Help Text:</h4>' +
				'<ul class="wordform-help-text-list">' +
					'<li><input class="wordform-shared-help-text-input" type="text" placeholder="Add a short instruction for users" /></li>' +
					'<li><small><em>( Optional. Shown on the frontend below the field label. )</em></small></li>' +
				'</ul>' +
			'</div>'
		);
	}

	function wordformSetBuilderHelpTextPreview($builderElement, helpText) {
		if (!$builderElement || !$builderElement.length || !wordformElementSupportsSharedHelpText($builderElement.data('input-element-type'))) {
			return;
		}

		const normalizedText = String(helpText || '').trim();
		let $helpPreview = $builderElement.children('.wordform-builder-help-text-preview');

		if (!normalizedText.length) {
			$helpPreview.remove();
			return;
		}

		if (!$helpPreview.length) {
			$helpPreview = $('<div class="wordform-builder-help-text-preview"></div>');
			const $directDiv = $builderElement.children('div').first();
			if ($directDiv.length) {
				$helpPreview.insertAfter($directDiv);
			} else {
				const $directList = $builderElement.children('ul').first();
				if ($directList.length) {
					$helpPreview.insertBefore($directList);
				} else {
					$builderElement.append($helpPreview);
				}
			}
		}

		$helpPreview.text(normalizedText);
	}

	function wordformEnsureInitialSharedHelpTextValue($optionsWrapper, $builderElement, elementType, savedElement = null) {
		if (!$optionsWrapper.length || !wordformElementSupportsSharedHelpText(elementType)) {
			return;
		}

		const helpTextValue = savedElement && savedElement.helpText ? savedElement.helpText : '';
		setWordformFieldValue($optionsWrapper.find('.wordform-shared-help-text-input'), helpTextValue, null);
		wordformSetBuilderHelpTextPreview($builderElement, helpTextValue);
	}

	function wordformElementSupportsSharedFieldWidth(elementType) {
		return [
			'text',
			'firstlastname',
			'number',
			'textarea',
			'richeditor',
			'range',
			'url',
			'date',
			'time',
			'datetime',
			'tel',
			'email',
			'address',
			'sectionhtml',
			'maskinput',
			'rating',
			'signature',
			'radio',
			'checkbox',
			'select',
			'upload',
			'terms',
			'gdpr',
			'payment_item',
			'payment_coupon',
			'payment_custom_amount',
			'payment_quantity'
		].indexOf(elementType) !== -1;
	}

	function wordformAppendSharedFieldWidthControl($optionsWrapper, elementType) {
		if (!$optionsWrapper.length || !wordformElementSupportsSharedFieldWidth(elementType) || $optionsWrapper.find('.wordform-shared-field-width-options-group').length) {
			return;
		}

		$optionsWrapper.append(
			'<hr/>' +
			'<div class="wordform-shared-field-width-options-group">' +
				'<h4>Field Width:</h4>' +
				'<ul class="wordform-shared-field-width-list">' +
					'<li>' +
						'<select class="wordform-shared-field-width-select">' +
							'<option value="full">Full Width</option>' +
							'<option value="half">Half Width</option>' +
							'<option value="third">One Third</option>' +
						'</select>' +
					'</li>' +
					'<li><small><em>( Controls the frontend field layout. Smaller widths stack automatically on mobile. )</em></small></li>' +
				'</ul>' +
			'</div>'
		);
	}

	function wordformReadSharedFieldWidthValue($optionsWrapper, elementType) {
		if (!wordformElementSupportsSharedFieldWidth(elementType)) {
			return 'full';
		}

		const selectedValue = ($optionsWrapper.find('.wordform-shared-field-width-select').val() || 'full').trim();
		return ['full', 'half', 'third'].indexOf(selectedValue) !== -1 ? selectedValue : 'full';
	}

	function wordformEnsureInitialSharedFieldWidthValue($optionsWrapper, elementType, savedElement = null) {
		if (!$optionsWrapper.length || !wordformElementSupportsSharedFieldWidth(elementType)) {
			return;
		}

		const initialValue = savedElement && savedElement.fieldWidth ? savedElement.fieldWidth : 'full';
		setWordformFieldValue(
			$optionsWrapper.find('.wordform-shared-field-width-select'),
			['full', 'half', 'third'].indexOf(initialValue) !== -1 ? initialValue : 'full',
			'change'
		);
	}

	function wordformSetBuilderFieldWidthPreview($builderElement, elementType, fieldWidth) {
		if (!$builderElement || !$builderElement.length || !wordformElementSupportsSharedFieldWidth(elementType)) {
			return;
		}

		const normalizedWidth = ['full', 'half', 'third'].indexOf(fieldWidth) !== -1 ? fieldWidth : 'full';
		$builderElement
			.removeClass('wordform-builder-field-width-full wordform-builder-field-width-half wordform-builder-field-width-third')
			.addClass('wordform-builder-field-width-' + normalizedWidth)
			.attr('data-wordform-builder-field-width', normalizedWidth);
		wordformSyncSelectedBuilderWidthBadge($builderElement, elementType, normalizedWidth);
	}

	function wordformGetBuilderFieldWidthBadgeLabel(fieldWidth) {
		switch (fieldWidth) {
			case 'half':
				return 'Half';
			case 'third':
				return '1/3';
			default:
				return 'Full';
		}
	}

	function wordformSyncSelectedBuilderWidthBadge($builderElement, elementType, fieldWidth) {
		if (!$builderElement || !$builderElement.length) {
			return;
		}

		if (!$builderElement.hasClass('wordform-selected-dropped-element-background-color')) {
			return;
		}

		if (!wordformElementSupportsSharedFieldWidth(elementType)) {
			$builderElement.removeAttr('data-wordform-active-width-label');
			return;
		}

		$builderElement.attr('data-wordform-active-width-label', wordformGetBuilderFieldWidthBadgeLabel(fieldWidth));
	}

	function wordformElementSupportsSharedCustomClass(elementType) {
		return wordformElementSupportsSharedFieldWidth(elementType);
	}

	function wordformAppendSharedCustomClassControl($optionsWrapper, elementType) {
		if (!$optionsWrapper.length || !wordformElementSupportsSharedCustomClass(elementType) || $optionsWrapper.find('.wordform-shared-custom-class-options-group').length) {
			return;
		}

		$optionsWrapper.append(
			'<hr/>' +
			'<div class="wordform-shared-custom-class-options-group">' +
				'<h4>Custom CSS Class:</h4>' +
				'<ul class="wordform-shared-custom-class-list">' +
					'<li><input class="wordform-shared-custom-class-input" type="text" placeholder="custom-field highlight-row" /></li>' +
					'<li><small><em>( Optional. Applied to the frontend field wrapper for custom styling. )</em></small></li>' +
				'</ul>' +
			'</div>'
		);
	}

	function wordformReadSharedCustomClassValue($optionsWrapper, elementType) {
		if (!wordformElementSupportsSharedCustomClass(elementType)) {
			return '';
		}

		return ($optionsWrapper.find('.wordform-shared-custom-class-input').val() || '').trim();
	}

	function wordformEnsureInitialSharedCustomClassValue($optionsWrapper, elementType, savedElement = null) {
		if (!$optionsWrapper.length || !wordformElementSupportsSharedCustomClass(elementType)) {
			return;
		}

		setWordformFieldValue($optionsWrapper.find('.wordform-shared-custom-class-input'), (savedElement && savedElement.customCssClass) ? savedElement.customCssClass : '', null);
	}

	function wordformElementSupportsSharedDefaultValue(elementType) {
		return [
			'text',
			'number',
			'textarea',
			'url',
			'tel',
			'email',
			'maskinput'
		].indexOf(elementType) !== -1;
	}

	function wordformAppendSharedDefaultValueControl($optionsWrapper, elementType) {
		if (!$optionsWrapper.length || !wordformElementSupportsSharedDefaultValue(elementType) || $optionsWrapper.find('.wordform-shared-default-value-options-group').length) {
			return;
		}

		$optionsWrapper.append(
			'<hr/>' +
			'<div class="wordform-shared-default-value-options-group">' +
				'<h4>Default Value:</h4>' +
				'<ul class="wordform-shared-default-value-list">' +
					'<li><input class="wordform-shared-default-value-input" type="text" placeholder="Prefill this field value" /></li>' +
					'<li><small><em>( Optional. Prefills the field on the frontend until the user changes it. )</em></small></li>' +
				'</ul>' +
			'</div>'
		);
	}

	function wordformReadSharedDefaultValue($optionsWrapper, elementType) {
		if (!wordformElementSupportsSharedDefaultValue(elementType)) {
			return '';
		}

		return ($optionsWrapper.find('.wordform-shared-default-value-input').val() || '').trim();
	}

	function wordformSetBuilderSharedDefaultValuePreview($builderElement, elementType, defaultValue) {
		if (!$builderElement || !$builderElement.length || !wordformElementSupportsSharedDefaultValue(elementType)) {
			return;
		}

		const normalizedValue = String(defaultValue || '');
		switch (elementType) {
			case 'text':
				$builderElement.find('.wordform-dropped-text-name').val(normalizedValue).attr('value', normalizedValue);
				break;
			case 'number':
				$builderElement.find('.wordform-dropped-number-name').val(normalizedValue).attr('value', normalizedValue);
				break;
			case 'textarea':
				$builderElement.find('.wordform-dropped-textarea-name').val(normalizedValue).text(normalizedValue);
				break;
			case 'richeditor':
				$builderElement.find('.wordform-richeditor-builder-content').text(normalizedValue);
				break;
			case 'url':
				$builderElement.find('.wordform-dropped-url-name').val(normalizedValue).attr('value', normalizedValue);
				break;
			case 'tel':
				$builderElement.find('.wordform-dropped-tel-name').val(normalizedValue).attr('value', normalizedValue);
				break;
			case 'email':
				$builderElement.find('.wordform-dropped-email-name').val(normalizedValue).attr('value', normalizedValue);
				break;
			case 'maskinput':
				$builderElement.find('.wordform-dropped-maskinput-name').val(normalizedValue).attr('value', normalizedValue);
				break;
		}
	}

	function wordformEnsureInitialSharedDefaultValue($optionsWrapper, $builderElement, elementType, savedElement = null) {
		if (!$optionsWrapper.length || !wordformElementSupportsSharedDefaultValue(elementType)) {
			return;
		}

		const defaultValue = savedElement && savedElement.defaultValue ? savedElement.defaultValue : '';
		setWordformFieldValue($optionsWrapper.find('.wordform-shared-default-value-input'), defaultValue, null);
		wordformSetBuilderSharedDefaultValuePreview($builderElement, elementType, defaultValue);
	}

	let wordformSharedColorPicker = null;
	let wordformSharedColorPickerTarget = null;

	function wordformEnsureSharedColorPickerModal() {
		if ($('#wordform-shared-color-picker-modal').length) {
			return;
		}

		$('body').append(
			'<div id="wordform-shared-color-picker-modal" class="wordform-color-picker-modal" aria-hidden="true">' +
				'<div class="wordform-color-picker-modal-backdrop"></div>' +
				'<div class="wordform-color-picker-modal-dialog" role="dialog" aria-modal="true" aria-label="Color Picker">' +
					'<div class="wordform-color-picker-modal-header">' +
						'<div class="wordform-color-picker-modal-title">Select Color</div>' +
						'<button type="button" class="wordform-color-picker-modal-close" aria-label="Close">&times;</button>' +
					'</div>' +
					'<div class="wordform-color-picker-modal-body">' +
						'<div id="wordform-shared-color-picker-root"></div>' +
						'<div class="wordform-color-picker-current-value">#2563EB</div>' +
					'</div>' +
				'</div>' +
			'</div>'
		);

		if (typeof iro !== 'undefined') {
			wordformSharedColorPicker = new iro.ColorPicker('#wordform-shared-color-picker-root', {
				width: 280,
				color: '#2563eb',
				layout: [
					{ component: iro.ui.Wheel },
					{ component: iro.ui.Slider, options: { sliderType: 'value' } },
					{ component: iro.ui.Slider, options: { sliderType: 'alpha' } }
				]
			});

			wordformSharedColorPicker.on('color:change', function(color) {
				if (!wordformSharedColorPickerTarget || !wordformSharedColorPickerTarget.length) {
					return;
				}

				const hex = color.hexString.toUpperCase();
				wordformSharedColorPickerTarget.val(hex).trigger('change');
				wordformSyncEnhancedColorPickerDisplay(wordformSharedColorPickerTarget);
				$('#wordform-shared-color-picker-modal .wordform-color-picker-current-value').text(hex);
			});
		}
	}

	function wordformOpenSharedColorPicker($input) {
		wordformEnsureSharedColorPickerModal();
		if (!$input || !$input.length) {
			return;
		}

		wordformSharedColorPickerTarget = $input;
		const currentValue = String($input.val() || '#2563eb').toUpperCase();
		$('#wordform-shared-color-picker-modal').addClass('is-open').attr('aria-hidden', 'false');
		$('.wordform-color-picker-trigger').removeClass('is-active');
		$input.siblings('.wordform-color-picker-trigger').addClass('is-active');
		$('#wordform-shared-color-picker-modal .wordform-color-picker-current-value').text(currentValue);

		if (wordformSharedColorPicker) {
			wordformSharedColorPicker.color.hexString = currentValue;
		}
	}

	function wordformCloseSharedColorPicker() {
		$('#wordform-shared-color-picker-modal').removeClass('is-open').attr('aria-hidden', 'true');
		$('.wordform-color-picker-trigger').removeClass('is-active');
		wordformSharedColorPickerTarget = null;
	}

	function wordformSyncEnhancedColorPickerDisplay($input) {
		if (!$input || !$input.length) {
			return;
		}

		const colorValue = String($input.val() || '#2563eb').toUpperCase();
		const $trigger = $input.siblings('.wordform-color-picker-trigger');
		if (!$trigger.length) {
			return;
		}

		$trigger.find('.wordform-color-picker-trigger-swatch').css('background-color', colorValue);
		$trigger.find('.wordform-color-picker-trigger-text').text(colorValue);
	}

	function wordformEnhanceColorInputs($context) {
		const $scope = ($context && $context.length) ? $context : $(document.body);
		wordformEnsureSharedColorPickerModal();

		$scope.find('input[type="color"]').each(function() {
			const $input = $(this);
			if ($input.hasClass('wordform-enhanced-color-input')) {
				wordformSyncEnhancedColorPickerDisplay($input);
				return;
			}

			const colorValue = String($input.val() || '#2563eb').toUpperCase();
			$input.addClass('wordform-enhanced-color-input');
			$input.after(
				'<button type="button" class="wordform-color-picker-trigger">' +
					'<span class="wordform-color-picker-trigger-swatch" style="background-color:' + wordformEscapeAttribute(colorValue) + ';"></span>' +
					'<span class="wordform-color-picker-trigger-text">' + wordformEscapeHtml(colorValue) + '</span>' +
				'</button>'
			);
		});
	}
	
    // Tooltip Init
	// $( document ).tooltip();
		
	// Drag: Draggable Config - Draggable
	$('.draggable-element').draggable({
		scope: "wordforms",
		// revert: "invalid", // snaps back if not dropped in droppable
		revert: function( dropped ) {
			// If 'dropped' is false, it means the draggable was not dropped on a droppable
			// or was dropped on a droppable that didn't accept it.
			if ( !dropped ) {
				return true; // Revert the helper to its original position
			} else {
				// Access attributes of the dragged element
				// var classAttr = $(this).attr("class");
				// var elementName = $(this).data("wordform-element-name")
				// console.log("Dragged element Class: ", classAttr );
				// console.log("Dragged element data attribute wordform-element-name: ", elementName );

				return false; // Don't revert, the drop was successful
			}
		},		
		connectToSortable: "#wordform-sortable",		
		// connectWith: "#wordform-sortable",
		// helper: "clone",				
		helper: function( event ) {
			console.log('Helper() Callback');
			// console.log(event);
			// console.log( $(event.result) );
			let elementName = $(event.currentTarget).data("wordform-element-name");
			console.log(elementName);
			//return '<div>Helper return element DIV</div>';			
			// return $(this);						
			return generateTargetElement( elementName );
		},
		cursor: "crosshair",
		cancel: false,		

		// containment: "window",				
		over: function(event, ui) {
		},
		drag: function( event, ui) {
		},
		start: function(event, ui) {   						      			
			console.log('Dragging STARTED');			
			let elementName = $(event.currentTarget).data("wordform-element-name");
			console.log(elementName);

			if (wordformBuilderHasDuplicateGatewayElement(elementName)) {
				setTimeout(() => {
					showWordformDialog(elementName);
				}, 10);

				event.preventDefault();
				jQuery(this).draggable("option", "revert", true);
				return false;
			}

			if (wordformBuilderHasInvalidGatewayConfiguration(elementName)) {
				setTimeout(() => {
					wordformShowPaymentGatewayRuleDialog();
				}, 10);

				event.preventDefault();
				jQuery(this).draggable("option", "revert", true);
				return false;
			}

			// Check duplicates first — before helper is even created
			if (
				(elementName === "captcha" && is_element_added_into_dropzone("captcha")) ||
				(elementName === "gcaptcha" && is_element_added_into_dropzone("gcaptcha")) ||
				(elementName === "hcaptcha" && is_element_added_into_dropzone("hcaptcha"))
			) {
				// Show message in modal (use timeout to ensure DOM stability)
				setTimeout(() => {
					showWordformDialog(elementName);										
				}, 10);

				// Stop this drag immediately (no helper, no ghost)
				event.preventDefault();
				jQuery(this).draggable("option", "revert", true);				
				// $('.draggable-element').draggable("option", "revert", true);				
				return false; // cancel drag creation
			}
		},		
		stop: function( event, ui ) {
			console.log('Dragging STOPPED');			
			let elementName = $(event.target).data("wordform-element-name");
			console.log(elementName);

			let draggedElementId = '#' + ui.helper.attr('id');
			let inputFieldOptionsWrapperId = '#wordformElementOptions-' + ui.helper.data('element-index');
			$droppedElement = $( draggedElementId );
			$dropzoneElement = $('.wordform-dropzone-div-wrapper');			

			// console.log('Dragged Element ID: '+ draggedElementId );		
			// console.log('Dragged Element Index Data Attribute Value: '+ ui.helper.data('element-index') );	
			// console.log( isDroppedInside( $droppedElement, $dropzoneElement ) );
			
			if ( ! isDroppedInside( $droppedElement, $dropzoneElement ) ) {
				// Hide Conector Line Arrow between Elements - Hide connector line if dragged elements dropped outside droppable area
				hideWordformConnector();
				// Check if the input element options wrapper exist then remove - we do not need input customization options which element dropped outside droppable zone
				$( inputFieldOptionsWrapperId ).remove(); 	
			}
			else {
				// Dragged element dropped inside droppable zone

				// Remove DropZone text if already exist							
				toggleDropzoneText( $(".wordform-dropzone-div-wrapper") );

			}
						
			// $('#wordform-sortable').sortable( "refresh" );			
		}		
	});
   
	
	// Drop: Add Form Elements on Drop - Droppable
	$( ".wordform-dropzone-div-wrapper" ).droppable({	 	
	   accept: '.draggable-element',
	// tolerance: "touch",
	   tolerance: "pointer",
	   scope: "wordforms",

	   over: function( event, ui ) {	
		console.log('Element Over Droppable.');		
		// Method 1
		// let parentWidth = $("#wordform-sortable").width();
		// console.log( "Droppable Over(): #wordform-sortable Width: "+ parentWidth ); // outerWidth() includes padding and border, while width() only includes the content area
		// parentWidth = ( parentWidth - 80 ); // css ref: .wordform-input-element-div-wrapper: 20px margin + 20px padding		
		// $(ui.helper).css({ 'width': parentWidth	});

		// Method 2
		// let targetWidthPercentage = $("#wordform-sortable").width() * 0.90; // For 90% of the reference element's width
		// $(ui.helper).css('width', targetWidthPercentage );		

		// Method 2 (Updated) - When element over droppable then set width 90% of wrapper
		// $(ui.helper).css('width', setInputElementWidthBasedOnWrapper() );				
		
	  },	
	  drop: function( event, ui ) {
		console.log('DROPPED');			         
	  }, 
	  out: function( event, ui ) {
		console.log('Outside droppable');
	  }	  
		
	});	

	// Sort: Drag Drop Sortable Elements - Sortable
	$('#wordform-sortable').sortable({
		start: function( event, ui ) {
			// console.log('Sort Start');
			// $(ui.helper).addClass("wordform-input-element-div-wrapper-dragging");
		},
		stop: function( event, ui ) {			
			console.log('Sort Stopped.');
			// $(ui.helper).addClass("wordform-input-element-div-wrapper-dragging");			
			// When elements sorting stopped inside sortable area - while element dragging-sorting then style attributes set including width by jQuery sort API to keep the consistency
			ui.item.css('width', ''); // Reset to original CSS						

			// let sortedElementID = '#' + ui.item.attr('id');
			// console.log('Sort(Stop) Element ID: '+ sortedElementID );			
			// Remove earlier Arrow Connector and show the only selected one
			// $droppedElement = $( sortedElementID ); // wordformElement-3			
			// console.log('Sortable Stop(): ' );
			// console.log( $droppedElement );
			// hideWordformConnector().then(() => showWordformConnector( $droppedElement ) );				
			// $('#wordform-sortable').sortable( "refresh" );
		},

		placeholder: "sortable-wordform-placeholder"
	});

	

	// Drag Elements Click: Add Form Elements on Click into dropzone
	$('body').on("click", ".wordform-drag-elements-button", function() {
		// Remove Dropzone text
		// removeDropZoneLabel(); 		
		let elementName	=	$(this).data('wordform-element-name');		

		if (wordformIsBuilderElementBlocked(elementName)) {
			wordformOpenUpgradeUrl();
			return false;
		}

		if (wordformBuilderHasDuplicateGatewayElement(elementName)) {
			setTimeout(() => {
				showWordformDialog(elementName);
			}, 10);
			return false;
		}

		if (wordformBuilderHasInvalidGatewayConfiguration(elementName)) {
			setTimeout(() => {
				wordformShowPaymentGatewayRuleDialog();
			}, 10);
			return false;
		}

		// Check duplicates first — before helper is even created
		if (
			(elementName === "captcha" && is_element_added_into_dropzone("captcha")) ||
			(elementName === "gcaptcha" && is_element_added_into_dropzone("gcaptcha")) ||
			(elementName === "hcaptcha" && is_element_added_into_dropzone("hcaptcha"))
		) {
			// Show message in modal (use timeout to ensure DOM stability)
			setTimeout(() => {
				showWordformDialog(elementName);
			}, 10);
		}
		else if (elementName === "pagebreak" && $('.wordform-dropzone-div-wrapper .wordform-input-element-div-wrapper').length === 0) {
			setTimeout(() => {
				wordformShowPageBreakRuleDialog('Page Break cannot be the first builder element. Add at least one field before it.');
			}, 10);
		}
		else {
			return generateTargetElement( elementName, appendElement = true );	
		}


		// return generateTargetElement( elementName, appendElement = true );
	});

	// Common: Check droppedElement inside DropZone area - return boolean true | false
	function isDroppedInside($droppedElement, $dropzone) {
		if (!$droppedElement.length || !$dropzone.length) return false;
		return $.contains($dropzone[0], $droppedElement[0]);
	}

	// DropZone Text: Show-Hide DropZone Text //	
	function toggleDropzoneText($dropzone) {
		if ($dropzone.children().length > 0) {
			$dropzone.addClass("has-items");
		} else {
			$dropzone.removeClass("has-items");
		}
	}
	$(".wordform-dropzone-div-wrapper").each(function() {
		const $dropzone = $(this);

		// Initial check
		toggleDropzoneText($dropzone);

		// Observe child changes
		const observer = new MutationObserver(function() {
			toggleDropzoneText($dropzone);
		});
		observer.observe(this, { childList: true });
	});

	// Global: Add element on dragged or clicked the element
	function generateTargetElement( elementName, appendElement = false) {		
		switch (elementName) {
			case 'singletext':
				return createSingleLineText( appendElement );
				break;
			case 'firstlastname':
				return createFirstLastName( appendElement );
				break;
			case 'singlenumber':
				return createInputNumber( appendElement );
				break;
			case 'multitext':
				return createTextarea( appendElement );
				break;				
			case 'richeditor':
				return createRichEditorElement( appendElement );
				break;
			case 'select':
				return createDropdownSelect( appendElement );
				break;
			case 'checkbox':
				return createInputCheckbox( appendElement );
				break;
			case 'radio':
				return createInputRadio( appendElement );
				break;
			case 'range':
				return createInputRange( appendElement );
				break;	
			case 'url':
				return createInputUrl( appendElement );
				break;	
			case 'date':
				return createInputDate( appendElement );
				break;	
			case 'time':
				return createInputTime( appendElement );
				break;
			case 'datetime':
				return createInputDatetime( appendElement );
				break;	
			case 'tel':
				return createInputTel( appendElement );
				break;	
			case 'email':
				return createInputEmail( appendElement );
				break;
			case 'address':
				return createInputAddress( appendElement );
				break;
			case 'sectionhtml':
				return createSectionHtmlElement( appendElement );
				break;
			case 'maskinput':
				return createMaskInputElement( appendElement );
				break;
			case 'hidden':
				return createHiddenFieldElement( appendElement );
				break;
			case 'captcha':
				return createInputCaptcha( appendElement );
				break;		
			case 'gcaptcha':
				return createInputGoogleCaptcha( appendElement );						
				break;
			case 'hcaptcha':
				return createInputHCaptcha( appendElement );
				break;
			case 'upload':
				return createInputUpload( appendElement );
				break;				
			case 'rating':
				return createRatingElement( appendElement );
				break;
			case 'likert':
				return createLikertElement( appendElement );
				break;
			case 'signature':
				return createSignatureElement( appendElement );
				break;
			case 'pagebreak':
				return createPageBreakElement( appendElement );
				break;
			case 'terms':
				return createInputTerms( appendElement );
				break;					
			case 'gdpr':
				return createInputGdpr( appendElement );
				break;
			case 'payment_method':
				return createPaymentMethod( appendElement );
				break;
			case 'payment_item':
				return createPaymentItem( appendElement );
				break;
			case 'payment_coupon':
				return createPaymentCoupon( appendElement );
				break;
			case 'payment_custom_amount':
				return createPaymentCustomAmount( appendElement );
				break;
			case 'payment_quantity':
				return createPaymentQuantity( appendElement );
				break;
			case 'payment_summary':
				return createPaymentSummary( appendElement );
				break;
			case 'stripe':
				return createStripeElement( appendElement );
				break;
			case 'paypal':
				return createPayPalElement( appendElement );
				break;
			case 'square':
				return createSquareElement( appendElement );
				break;
			case 'authorizenet':
				return createAuthorizeNetElement( appendElement );
				break;
			default:
				console.log('Element not supported yet.');
				return '';
				break;
				
		} // switch		
	}

	// Remove DropZone Label Text
	function removeDropZoneLabel() {
		$('.sc-wordform-dropzone-watermark-text').remove(); 
	}
	
	// Global: Create Element Index Number
	function createElementNumber() {
		let WordFormBuilderElementNum	= parseInt( $('.wordform-form-builder-element-number').val() );
		let elementNumber				= 0;
		if ( $.trim( WordFormBuilderElementNum ).length != 0 ) {
			elementNumber               = parseInt( WordFormBuilderElementNum+1 );
			$('.wordform-form-builder-element-number').val( elementNumber );
		}
		else {
			elementNumber				= DroppabaleElementWrapper.children().length;
			elementNumber				= parseInt(elementNumber+1);
			$('.wordform-form-builder-element-number').val(elementNumber);
		}
		return elementNumber;
	}
		
	
	/*** Create Standard Elements ***/
	
	// Text: Create Input Text - Single Line Text
	function createSingleLineText( appendElement ) {
		let DroppabaleElementWrapper	= $('.wordform-dropzone-div-wrapper');
		let elementNumber				= createElementNumber();		
		let AttrID						= 'wordformElement-'+ elementNumber;
		let elementOptionsWrapperID		= 'wordformElementOptions-'+ elementNumber;
		renderElementOptions('text', elementOptionsWrapperID, elementNumber );		
		if ( appendElement == true ) {
			let generatedElement = '<div id="'+AttrID+'" class="wordform-input-element-div-wrapper wordform-build-input-field-moveable" data-input-element-type="text" data-element-index="'+elementNumber+'"> <span class="wordform-element-delete dashicons dashicons-trash" title="Remove"></span> <div class="wordform-dropped-text-label">Name</div> <ul class="wordform-dropped-element-text-field-options"><li><input class="wordform-dropped-text-name" name="wordform-dropped-text-name" type="text" placeholder="Your Name" readonly /> </li></ul>  </div>';
			DroppabaleElementWrapper.append( generatedElement );						
			focusGeneratedElement( generatedElement );
		}
		else {
			return '<div id="'+AttrID+'" class="wordform-input-element-div-wrapper wordform-build-input-field-moveable" data-input-element-type="text" data-element-index="'+elementNumber+'"> <span class="wordform-element-delete dashicons dashicons-trash" title="Remove"></span> <div class="wordform-dropped-text-label">Name</div> <ul class="wordform-dropped-element-text-field-options"><li><input class="wordform-dropped-text-name" name="wordform-dropped-text-name" type="text" placeholder="Your Name" readonly /> </li></ul>  </div>';		   						
		}		
	}


	// First Last Name: Create Input Text - First Last Name
	function createFirstLastName( appendElement ) {
		let DroppabaleElementWrapper	= $('.wordform-dropzone-div-wrapper');
		let elementNumber				= createElementNumber();		
		let AttrID						= 'wordformElement-'+ elementNumber;
		let elementOptionsWrapperID		= 'wordformElementOptions-'+ elementNumber;
		renderElementOptions('firstlastname', elementOptionsWrapperID, elementNumber );				
		let generatedElement = `
		<div id="${AttrID}" class="wordform-input-element-div-wrapper wordform-build-input-field-moveable" 
			data-input-element-type="firstlastname" data-element-index="${elementNumber}">
			
			<span class="wordform-element-delete dashicons dashicons-trash" title="Remove"></span>

			<ul class="wordform-dropped-element-firstlastname-field-options">
				<li class="wordform-dropped-firstlastname-name-row">

					<!-- First Name -->
					<div class="wordform-dropped-text-first-name-wrapper">
						<label class="wordform-dropped-text-first-name-label">First Name</label>
						<input class="wordform-dropped-text-first-name" 
							name="wordform-dropped-text-first-name" 
							type="text" placeholder="First Name" readonly>
					</div>

					<!-- Last Name -->
					<div class="wordform-dropped-text-last-name-wrapper">
						<label class="wordform-dropped-text-last-name-label">Last Name</label>
						<input class="wordform-dropped-text-last-name" 
							name="wordform-dropped-text-last-name" 
							type="text" placeholder="Last Name" readonly>
					</div>

				</li>
			</ul>
		</div>
		`;			
		if ( appendElement == true ) {
			DroppabaleElementWrapper.append( generatedElement );						
			focusGeneratedElement( generatedElement );
		}
		else {
			return generatedElement;			
		}		
	}

	// Address: Create compound address field
	function createInputAddress( appendElement ) {
		let DroppabaleElementWrapper	= $('.wordform-dropzone-div-wrapper');
		let elementNumber				= createElementNumber();
		let AttrID						= 'wordformElement-'+ elementNumber;
		let elementOptionsWrapperID		= 'wordformElementOptions-'+ elementNumber;
		renderElementOptions('address', elementOptionsWrapperID, elementNumber );
		let generatedElement = `
		<div id="${AttrID}" class="wordform-input-element-div-wrapper wordform-build-input-field-moveable wordform-address-builder-element" data-input-element-type="address" data-element-index="${elementNumber}">
			<span class="wordform-element-delete dashicons dashicons-trash" title="Remove"></span>
			<div class="wordform-dropped-address-label">Address</div>
			<div class="wordform-address-builder-grid">
				<input class="wordform-dropped-address-street" type="text" placeholder="Street Address" readonly />
				<div class="wordform-address-builder-grid-inner">
					<input class="wordform-dropped-address-city" type="text" placeholder="City" readonly />
					<input class="wordform-dropped-address-state" type="text" placeholder="State / Region" readonly />
				</div>
				<div class="wordform-address-builder-grid-inner">
					<input class="wordform-dropped-address-zip" type="text" placeholder="ZIP / Postal Code" readonly />
					<input class="wordform-dropped-address-country" type="text" placeholder="Country" readonly />
				</div>
			</div>
		</div>`;

		if ( appendElement == true ) {
			DroppabaleElementWrapper.append( generatedElement );
			focusGeneratedElement( generatedElement );
		}
		else {
			return generatedElement;
		}
	}

	// Section / HTML: Create static content block
	function createSectionHtmlElement( appendElement ) {
		let DroppabaleElementWrapper	= $('.wordform-dropzone-div-wrapper');
		let elementNumber				= createElementNumber();
		let AttrID						= 'wordformElement-'+ elementNumber;
		let elementOptionsWrapperID		= 'wordformElementOptions-'+ elementNumber;
		renderElementOptions('sectionhtml', elementOptionsWrapperID, elementNumber );
		let generatedElement = `
		<div id="${AttrID}" class="wordform-input-element-div-wrapper wordform-build-input-field-moveable wordform-sectionhtml-builder-element" data-input-element-type="sectionhtml" data-element-index="${elementNumber}">
			<span class="wordform-element-delete dashicons dashicons-trash" title="Remove"></span>
			<div class="wordform-sectionhtml-builder-card">
				<div class="wordform-sectionhtml-builder-badge"><i class="fa-regular fa-rectangle-list"></i><span>Section / HTML</span></div>
				<div class="wordform-sectionhtml-builder-title">Section Title</div>
				<div class="wordform-sectionhtml-builder-content">Add instructions, notes, or custom HTML content.</div>
			</div>
		</div>`;

		if ( appendElement == true ) {
			DroppabaleElementWrapper.append( generatedElement );
			focusGeneratedElement( generatedElement );
		}
		else {
			return generatedElement;
		}
	}

	// Mask Input: Create formatted text field
	function createMaskInputElement( appendElement ) {
		let DroppabaleElementWrapper	= $('.wordform-dropzone-div-wrapper');
		let elementNumber				= createElementNumber();
		let AttrID						= 'wordformElement-'+ elementNumber;
		let elementOptionsWrapperID		= 'wordformElementOptions-'+ elementNumber;
		renderElementOptions('maskinput', elementOptionsWrapperID, elementNumber );
		let generatedElement = `
		<div id="${AttrID}" class="wordform-input-element-div-wrapper wordform-build-input-field-moveable" data-input-element-type="maskinput" data-element-index="${elementNumber}">
			<span class="wordform-element-delete dashicons dashicons-trash" title="Remove"></span>
			<div class="wordform-dropped-maskinput-label">Masked Input</div>
			<ul class="wordform-dropped-element-maskinput-field-options">
				<li><input class="wordform-dropped-maskinput-name" name="wordform-dropped-maskinput-name" type="text" placeholder="AB-12345" readonly /></li>
				<li class="wordform-maskinput-builder-pattern">Pattern: <code>^[A-Z]{2}-[0-9]{5}$</code></li>
			</ul>
		</div>`;

		if ( appendElement == true ) {
			DroppabaleElementWrapper.append( generatedElement );
			focusGeneratedElement( generatedElement );
		}
		else {
			return generatedElement;
		}
	}

	// Hidden: Create hidden-value helper field
	function createHiddenFieldElement( appendElement ) {
		let DroppabaleElementWrapper	= $('.wordform-dropzone-div-wrapper');
		let elementNumber				= createElementNumber();
		let AttrID						= 'wordformElement-'+ elementNumber;
		let elementOptionsWrapperID		= 'wordformElementOptions-'+ elementNumber;
		renderElementOptions('hidden', elementOptionsWrapperID, elementNumber );
		let generatedElement = `
		<div id="${AttrID}" class="wordform-input-element-div-wrapper wordform-build-input-field-moveable wordform-hidden-builder-element" data-input-element-type="hidden" data-element-index="${elementNumber}">
			<span class="wordform-element-delete dashicons dashicons-trash" title="Remove"></span>
			<div class="wordform-hidden-builder-card">
				<div class="wordform-hidden-builder-badge"><i class="fa-regular fa-eye-slash"></i><span>Hidden Field</span></div>
				<div class="wordform-hidden-builder-title">Hidden Field</div>
				<div class="wordform-hidden-builder-value">Value: utm_source</div>
			</div>
		</div>`;

		if ( appendElement == true ) {
			DroppabaleElementWrapper.append( generatedElement );
			focusGeneratedElement( generatedElement );
		}
		else {
			return generatedElement;
		}
	}

	// Signature: Create drawable signature field
	function wordformBuildRatingBuilderStars(scaleValue) {
		let markup = '';
		const normalizedScale = Math.min(Math.max(parseInt(scaleValue, 10) || 5, 3), 10);

		for (let index = 1; index <= normalizedScale; index++) {
			markup += '<span class="wordform-rating-builder-star"><i class="fa-solid fa-star"></i></span>';
		}

		return markup;
	}

	function wordformEscapeHtml(value) {
		return String(value || '')
			.replace(/&/g, '&amp;')
			.replace(/</g, '&lt;')
			.replace(/>/g, '&gt;')
			.replace(/"/g, '&quot;')
			.replace(/'/g, '&#39;');
	}

	function wordformEscapeAttribute(value) {
		return wordformEscapeHtml(value);
	}

	function wordformGetLikertDefaultRows() {
		return ['Quality', 'Speed', 'Support'];
	}

	function wordformGetLikertDefaultColumns() {
		return ['Strongly Disagree', 'Disagree', 'Neutral', 'Agree', 'Strongly Agree'];
	}

	function wordformNormalizeLikertOptions(values, fallbackValues) {
		const normalizedValues = Array.isArray(values)
			? values.map(function(value) {
				return String(value || '').trim();
			}).filter(function(value) {
				return value.length > 0;
			})
			: [];

		return normalizedValues.length ? normalizedValues : fallbackValues.slice();
	}

	function wordformBuildLikertBuilderPreview(rowValues, columnValues) {
		const rows = wordformNormalizeLikertOptions(rowValues, wordformGetLikertDefaultRows()).slice(0, 4);
		const columns = wordformNormalizeLikertOptions(columnValues, wordformGetLikertDefaultColumns());
		const columnCount = Math.max(columns.length, 2);
		let headerMarkup = '<div class="wordform-likert-builder-header-cell is-corner"></div>';
		let bodyMarkup = '';

		columns.forEach(function(columnLabel) {
			headerMarkup += '<div class="wordform-likert-builder-header-cell">' + wordformEscapeHtml(columnLabel) + '</div>';
		});

		rows.forEach(function(rowLabel) {
			let rowMarkup = '<div class="wordform-likert-builder-row-label">' + wordformEscapeHtml(rowLabel) + '</div>';
			columns.forEach(function() {
				rowMarkup += '<div class="wordform-likert-builder-row-choice"><span></span></div>';
			});
			bodyMarkup += '<div class="wordform-likert-builder-row">' + rowMarkup + '</div>';
		});

		return '<div class="wordform-likert-builder-matrix-scroll" style="--wordform-likert-builder-column-count:' + columnCount + '"><div class="wordform-likert-builder-matrix-head">' + headerMarkup + '</div><div class="wordform-likert-builder-matrix-body">' + bodyMarkup + '</div></div>';
	}

	function wordformRenderLikertOptionListMarkup(optionType, values) {
		const normalizedValues = wordformNormalizeLikertOptions(
			values,
			optionType === 'row' ? wordformGetLikertDefaultRows() : wordformGetLikertDefaultColumns()
		);
		const inputClass = optionType === 'row' ? 'wordform-input-likert-row-label-name' : 'wordform-input-likert-column-label-name';
		const removeClass = optionType === 'row' ? 'wordform-likert-row-field-remove' : 'wordform-likert-column-field-remove';
		const addClass = optionType === 'row' ? 'wordform-add-likert-row-option' : 'wordform-add-likert-column-option';
		const placeholder = optionType === 'row' ? 'Statement text' : 'Column text';
		const addTitle = optionType === 'row' ? 'Add Row' : 'Add Column';
		let markup = '';

		normalizedValues.forEach(function(value) {
			markup += '<li><input class="' + inputClass + '" type="text" placeholder="' + placeholder + '" value="' + wordformEscapeAttribute(value) + '" /><span class="' + removeClass + ' dashicons dashicons-no" title="Remove"></span></li>';
		});

		markup += '<li><span class="' + addClass + ' dashicons dashicons-plus" title="' + addTitle + '"></span></li>';
		return markup;
	}

	function wordformCreateLikertOptionItem(optionType, value) {
		const inputClass = optionType === 'row' ? 'wordform-input-likert-row-label-name' : 'wordform-input-likert-column-label-name';
		const removeClass = optionType === 'row' ? 'wordform-likert-row-field-remove' : 'wordform-likert-column-field-remove';
		const placeholder = optionType === 'row' ? 'Statement text' : 'Column text';
		return $('<li><input type="text" /><span title="Remove"></span></li>')
			.find('input')
				.addClass(inputClass)
				.attr('placeholder', placeholder)
				.val(value || '')
				.attr('value', value || '')
				.end()
			.find('span')
				.addClass(removeClass + ' dashicons dashicons-no')
				.end();
	}

	function wordformSetLikertOptionListValues($wrapper, optionType, values) {
		const normalizedValues = wordformNormalizeLikertOptions(
			values,
			optionType === 'row' ? wordformGetLikertDefaultRows() : wordformGetLikertDefaultColumns()
		);
		const listSelector = optionType === 'row' ? '.wordform-likert-row-options' : '.wordform-likert-column-options';
		const addClass = optionType === 'row' ? 'wordform-add-likert-row-option' : 'wordform-add-likert-column-option';
		const addTitle = optionType === 'row' ? 'Add Row' : 'Add Column';
		const $list = $wrapper.find(listSelector);

		if (!$list.length) {
			return;
		}

		$list.empty();

		normalizedValues.forEach(function(value) {
			$list.append(wordformCreateLikertOptionItem(optionType, value));
		});

		$list.append('<li><span class="' + addClass + ' dashicons dashicons-plus" title="' + addTitle + '"></span></li>');
	}

	function wordformCollectLikertOptionValues($wrapper, optionType) {
		const selector = optionType === 'row' ? '.wordform-input-likert-row-label-name' : '.wordform-input-likert-column-label-name';
		return $wrapper.find(selector).map(function() {
			return ($(this).val() || '').trim();
		}).get().filter(function(value) {
			return value.length > 0;
		});
	}

	function wordformSetLikertBuilderPreview(elementIndex, rowValues, columnValues) {
		$('#wordformElement-' + elementIndex + ' .wordform-likert-builder-matrix').html(wordformBuildLikertBuilderPreview(rowValues, columnValues));
	}

	function wordformRefreshLikertBuilderPreviewFromOptions($wrapper) {
		if (!$wrapper || !$wrapper.length) {
			return;
		}

		const elementIndex = ($wrapper.prop('id') || '').split('-')[1];
		wordformSetLikertBuilderPreview(
			elementIndex,
			wordformCollectLikertOptionValues($wrapper, 'row'),
			wordformCollectLikertOptionValues($wrapper, 'column')
		);
	}

	// Rating: Create star rating field
	function createRatingElement( appendElement ) {
		let DroppabaleElementWrapper	= $('.wordform-dropzone-div-wrapper');
		let elementNumber				= createElementNumber();
		let AttrID						= 'wordformElement-'+ elementNumber;
		let elementOptionsWrapperID		= 'wordformElementOptions-'+ elementNumber;
		renderElementOptions('rating', elementOptionsWrapperID, elementNumber );
		let generatedElement = `
		<div id="${AttrID}" class="wordform-input-element-div-wrapper wordform-build-input-field-moveable wordform-rating-builder-element" data-input-element-type="rating" data-element-index="${elementNumber}">
			<span class="wordform-element-delete dashicons dashicons-trash" title="Remove"></span>
			<div class="wordform-rating-builder-card">
				<div class="wordform-rating-builder-badge"><i class="fa-solid fa-star"></i><span>Rating</span></div>
				<div class="wordform-rating-builder-title">Rating</div>
				<div class="wordform-rating-builder-stars">${wordformBuildRatingBuilderStars(5)}</div>
				<div class="wordform-rating-builder-scale-labels"><span class="wordform-rating-builder-low">Poor</span><span class="wordform-rating-builder-high">Excellent</span></div>
			</div>
		</div>`;

		if ( appendElement == true ) {
			DroppabaleElementWrapper.append( generatedElement );
			focusGeneratedElement( generatedElement );
		}
		else {
			return generatedElement;
		}
	}

	function createRichEditorElement( appendElement ) {
		let DroppabaleElementWrapper	= $('.wordform-dropzone-div-wrapper');
		let elementNumber				= createElementNumber();
		let AttrID						= 'wordformElement-'+ elementNumber;
		let elementOptionsWrapperID		= 'wordformElementOptions-'+ elementNumber;
		renderElementOptions('richeditor', elementOptionsWrapperID, elementNumber );
		let generatedElement = `
		<div id="${AttrID}" class="wordform-input-element-div-wrapper wordform-build-input-field-moveable wordform-richeditor-builder-element" data-input-element-type="richeditor" data-element-index="${elementNumber}">
			<span class="wordform-element-delete dashicons dashicons-trash" title="Remove"></span>
			<div class="wordform-richeditor-builder-card">
				<div class="wordform-richeditor-builder-badge"><i class="fa-solid fa-pen-to-square"></i><span>Rich Text Editor</span></div>
				<div class="wordform-richeditor-builder-title">Rich Text Editor</div>
				<div class="wordform-richeditor-builder-toolbar">
					<span><i class="fa-solid fa-bold"></i></span>
					<span><i class="fa-solid fa-italic"></i></span>
					<span><i class="fa-solid fa-list-ul"></i></span>
					<span><i class="fa-solid fa-link"></i></span>
				</div>
				<div class="wordform-richeditor-builder-surface" style="min-height:180px;">
					<div class="wordform-richeditor-builder-placeholder">Write your response...</div>
				</div>
			</div>
		</div>`;

		if ( appendElement == true ) {
			DroppabaleElementWrapper.append( generatedElement );
			focusGeneratedElement( generatedElement );
		}
		else {
			return generatedElement;
		}
	}

	function createLikertElement( appendElement ) {
		let DroppabaleElementWrapper	= $('.wordform-dropzone-div-wrapper');
		let elementNumber				= createElementNumber();
		let AttrID						= 'wordformElement-'+ elementNumber;
		let elementOptionsWrapperID		= 'wordformElementOptions-'+ elementNumber;
		renderElementOptions('likert', elementOptionsWrapperID, elementNumber );
		let generatedElement = `
		<div id="${AttrID}" class="wordform-input-element-div-wrapper wordform-build-input-field-moveable wordform-likert-builder-element" data-input-element-type="likert" data-element-index="${elementNumber}">
			<span class="wordform-element-delete dashicons dashicons-trash" title="Remove"></span>
			<div class="wordform-likert-builder-card">
				<div class="wordform-likert-builder-badge"><i class="fa-solid fa-table-list"></i><span>Likert / Matrix</span></div>
				<div class="wordform-likert-builder-title">Likert Scale</div>
				<div class="wordform-likert-builder-matrix">${wordformBuildLikertBuilderPreview(wordformGetLikertDefaultRows(), wordformGetLikertDefaultColumns())}</div>
			</div>
		</div>`;

		if ( appendElement == true ) {
			DroppabaleElementWrapper.append( generatedElement );
			focusGeneratedElement( generatedElement );
		}
		else {
			return generatedElement;
		}
	}

	// Signature: Create drawable signature field
	function createSignatureElement( appendElement ) {
		let DroppabaleElementWrapper	= $('.wordform-dropzone-div-wrapper');
		let elementNumber				= createElementNumber();
		let AttrID						= 'wordformElement-'+ elementNumber;
		let elementOptionsWrapperID		= 'wordformElementOptions-'+ elementNumber;
		renderElementOptions('signature', elementOptionsWrapperID, elementNumber );
		let generatedElement = `
		<div id="${AttrID}" class="wordform-input-element-div-wrapper wordform-build-input-field-moveable wordform-signature-builder-element" data-input-element-type="signature" data-element-index="${elementNumber}">
			<span class="wordform-element-delete dashicons dashicons-trash" title="Remove"></span>
			<div class="wordform-signature-builder-card">
				<div class="wordform-signature-builder-badge"><i class="fa-solid fa-signature"></i><span>Signature</span></div>
				<div class="wordform-signature-builder-title">Signature</div>
				<div class="wordform-signature-builder-canvas" style="height:180px;">
					<div class="wordform-signature-builder-line"></div>
					<div class="wordform-signature-builder-placeholder">Sign here</div>
				</div>
				<div class="wordform-signature-builder-actions">
					<span class="wordform-signature-builder-clear">Clear Signature</span>
				</div>
			</div>
		</div>`;

		if ( appendElement == true ) {
			DroppabaleElementWrapper.append( generatedElement );
			focusGeneratedElement( generatedElement );
		}
		else {
			return generatedElement;
		}
	}
		
	// Number: Create Input Number
	function createInputNumber( appendElement ) {
		let DroppabaleElementWrapper	= $('.wordform-dropzone-div-wrapper');
		let elementNumber				= createElementNumber();		
		let AttrID						= 'wordformElement-'+ elementNumber;
		let elementOptionsWrapperID		= 'wordformElementOptions-'+ elementNumber;
		renderElementOptions('number', elementOptionsWrapperID, elementNumber );   						
		if ( appendElement == true ) {
			let generatedElement = '<div id="'+AttrID+'" class="wordform-input-element-div-wrapper wordform-build-input-field-moveable" data-input-element-type="number" data-element-index="'+elementNumber+'"> <span class="wordform-element-delete dashicons dashicons-trash" title="Remove"></span> <div class="wordform-dropped-number-label">Number</div> <ul class="wordform-dropped-element-number-field-options"><li><input class="wordform-dropped-number-name" name="wordform-dropped-number-name" type="number" placeholder="Enter Number" readonly /> </li></ul>  </div>';
			DroppabaleElementWrapper.append( generatedElement );		
			focusGeneratedElement( generatedElement );
		}
		else {
			return '<div id="'+AttrID+'" class="wordform-input-element-div-wrapper wordform-build-input-field-moveable" data-input-element-type="number" data-element-index="'+elementNumber+'"> <span class="wordform-element-delete dashicons dashicons-trash" title="Remove"></span> <div class="wordform-dropped-number-label">Number</div> <ul class="wordform-dropped-element-number-field-options"><li><input class="wordform-dropped-number-name" name="wordform-dropped-number-name" type="number" placeholder="Enter Number" readonly /> </li></ul>  </div>';
		}
	}
	
	
	// Textarea: Create Input Textarea - Multi Line Text
	function createTextarea( appendElement ) {
		let DroppabaleElementWrapper	= $('.wordform-dropzone-div-wrapper');
		let elementNumber				=	createElementNumber();		
		let AttrID						= 'wordformElement-'+ elementNumber;
		let elementOptionsWrapperID		= 'wordformElementOptions-'+ elementNumber;
		renderElementOptions('textarea', elementOptionsWrapperID, elementNumber );   						
		if ( appendElement == true ) {
			let generatedElement = '<div id="'+AttrID+'" class="wordform-input-element-div-wrapper wordform-build-input-field-moveable" data-input-element-type="textarea" data-element-index="'+elementNumber+'"> <span class="wordform-element-delete dashicons dashicons-trash" title="Remove"></span> <div class="wordform-dropped-textarea-label">Description</div> <ul class="wordform-dropped-element-textarea-field-options"><li> <textarea class="wordform-dropped-textarea-name" name="wordform-dropped-textarea-name" placeholder="Tell us about yourself..." readonly></textarea> </li></ul>  </div>';
			DroppabaleElementWrapper.append( generatedElement );
			focusGeneratedElement( generatedElement );
		}
		else {
			return '<div id="'+AttrID+'" class="wordform-input-element-div-wrapper wordform-build-input-field-moveable" data-input-element-type="textarea" data-element-index="'+elementNumber+'"> <span class="wordform-element-delete dashicons dashicons-trash" title="Remove"></span> <div class="wordform-dropped-textarea-label">Description</div> <ul class="wordform-dropped-element-textarea-field-options"><li> <textarea class="wordform-dropped-textarea-name" name="wordform-dropped-textarea-name" placeholder="Tell us about yourself..." readonly></textarea> </li></ul>  </div>';
		}
	}
	
	
	// Radio: Create Input Radio
	function createInputRadio( appendElement ) {
		let DroppabaleElementWrapper	= $('.wordform-dropzone-div-wrapper');
		let elementNumber				= createElementNumber();		
		let AttrID						= 'wordformElement-'+ elementNumber;
		let elementOptionsWrapperID		= 'wordformElementOptions-'+ elementNumber;
		renderElementOptions('radio', elementOptionsWrapperID, elementNumber );   				
		if ( appendElement == true ) {
			let generatedElement = '<div id="'+AttrID+'" class="wordform-input-element-div-wrapper wordform-build-input-field-moveable" data-input-element-type="radio" data-element-index="'+elementNumber+'"> <span class="wordform-element-delete dashicons dashicons-trash" title="Remove"></span> <div class="wordform-dropped-radio-label">Multiple Choice</div> <ul class="wordform-dropped-element-radio-field-options"><li><input class="wordform-dropped-radio-name" name="wordform-dropped-radio-name-'+elementNumber+'" type="radio" readonly /><span>Option Text</span> </li></ul>  </div>';
			DroppabaleElementWrapper.append( generatedElement );
			focusGeneratedElement( generatedElement );
		}	
		else {
			return '<div id="'+AttrID+'" class="wordform-input-element-div-wrapper wordform-build-input-field-moveable" data-input-element-type="radio" data-element-index="'+elementNumber+'"> <span class="wordform-element-delete dashicons dashicons-trash" title="Remove"></span> <div class="wordform-dropped-radio-label">Multiple Choice</div> <ul class="wordform-dropped-element-radio-field-options"><li><input class="wordform-dropped-radio-name" name="wordform-dropped-radio-name-'+elementNumber+'" type="radio" readonly /><span>Option Text</span> </li></ul>  </div>';
		}
	}
	
	// Select: Create Dropdown Select
	function createDropdownSelect( appendElement ) {
		let DroppabaleElementWrapper	= $('.wordform-dropzone-div-wrapper');
		let elementNumber				= createElementNumber();		
		let AttrID						= 'wordformElement-'+ elementNumber;
		let elementOptionsWrapperID		= 'wordformElementOptions-'+ elementNumber;
		renderElementOptions('select', elementOptionsWrapperID, elementNumber );   				
		if ( appendElement == true ) {
			let generatedElement = '<div id="'+AttrID+'" class="wordform-input-element-div-wrapper wordform-build-input-field-moveable" data-input-element-type="select" data-element-index="'+elementNumber+'"> <span class="wordform-element-delete dashicons dashicons-trash" title="Remove"></span> <div class="wordform-dropped-select-label">Dropdown</div> <ul class="wordform-dropped-element-select-field-options"><li> <select class="wordform-dropped-select-name" name="wordform-dropped-select-name" readonly ><option value="Select Text">Select Text</option></select> </li></ul>  </div>';
			DroppabaleElementWrapper.append( generatedElement );
			focusGeneratedElement( generatedElement );
		}
		else {
			return '<div id="'+AttrID+'" class="wordform-input-element-div-wrapper wordform-build-input-field-moveable" data-input-element-type="select" data-element-index="'+elementNumber+'"> <span class="wordform-element-delete dashicons dashicons-trash" title="Remove"></span> <div class="wordform-dropped-select-label">Dropdown</div> <ul class="wordform-dropped-element-select-field-options"><li> <select class="wordform-dropped-select-name" name="wordform-dropped-select-name" readonly ><option value="Select Text">Select Text</option></select> </li></ul>  </div>';
		}
	}
	
	// Time: Create Input Time
	function createInputTime( appendElement ) {
		let DroppabaleElementWrapper	= $('.wordform-dropzone-div-wrapper');
		let elementNumber				= createElementNumber();		
		let AttrID						= 'wordformElement-'+ elementNumber;
		let elementOptionsWrapperID		= 'wordformElementOptions-'+ elementNumber;
		renderElementOptions('time', elementOptionsWrapperID, elementNumber );   				
		if ( appendElement == true ) {
			let generatedElement = '<div id="'+AttrID+'" class="wordform-input-element-div-wrapper wordform-build-input-field-moveable" data-input-element-type="time" data-element-index="'+elementNumber+'"> <span class="wordform-element-delete dashicons dashicons-trash" title="Remove"></span> <div class="wordform-dropped-time-label">Time</div> <ul class="wordform-dropped-element-time-field-options"><li><input class="wordform-dropped-time-name" name="wordform-dropped-time-name" type="text" placeholder="Select time" readonly /> </li></ul>  </div>';
			DroppabaleElementWrapper.append( generatedElement );
			focusGeneratedElement( generatedElement );
		}
		else {
			return '<div id="'+AttrID+'" class="wordform-input-element-div-wrapper wordform-build-input-field-moveable" data-input-element-type="time" data-element-index="'+elementNumber+'"> <span class="wordform-element-delete dashicons dashicons-trash" title="Remove"></span> <div class="wordform-dropped-time-label">Time</div> <ul class="wordform-dropped-element-time-field-options"><li><input class="wordform-dropped-time-name" name="wordform-dropped-time-name" type="text" placeholder="Select time" readonly /> </li></ul>  </div>';
		}
	}

	// Checkbox: Create Input Checkbox
	function createInputCheckbox( appendElement ) {
		let DroppabaleElementWrapper	= $('.wordform-dropzone-div-wrapper');
		let elementNumber				= createElementNumber();		
		let AttrID						= 'wordformElement-'+ elementNumber;
		let elementOptionsWrapperID		= 'wordformElementOptions-'+ elementNumber;
		renderElementOptions('checkbox', elementOptionsWrapperID, elementNumber );   				
		if ( appendElement == true ) {
			let generatedElement = '<div id="'+AttrID+'" class="wordform-input-element-div-wrapper wordform-build-input-field-moveable" data-input-element-type="checkbox" data-element-index="'+elementNumber+'"> <span class="wordform-element-delete dashicons dashicons-trash" title="Remove"></span> <div class="wordform-dropped-checkbox-label">Checkboxes</div> <ul class="wordform-dropped-element-checkbox-field-options"><li><input class="wordform-dropped-checkbox-name" name="wordform-dropped-checkbox-name" type="checkbox" disabled="disabled" /><span>Checkbox Text</span> </li></ul>  </div>';
			DroppabaleElementWrapper.append( generatedElement );
			focusGeneratedElement( generatedElement );
		}
		else {
			return '<div id="'+AttrID+'" class="wordform-input-element-div-wrapper wordform-build-input-field-moveable" data-input-element-type="checkbox" data-element-index="'+elementNumber+'"> <span class="wordform-element-delete dashicons dashicons-trash" title="Remove"></span> <div class="wordform-dropped-checkbox-label">Checkboxes</div> <ul class="wordform-dropped-element-checkbox-field-options"><li><input class="wordform-dropped-checkbox-name" name="wordform-dropped-checkbox-name" type="checkbox" disabled="disabled" /><span>Checkbox Text</span> </li></ul>  </div>';
		}
	}
	
    // Range: Create Input Range
	function createInputRange( appendElement ) {
		let DroppabaleElementWrapper	= $('.wordform-dropzone-div-wrapper');
		let elementNumber				= createElementNumber();		
		let AttrID						= 'wordformElement-'+ elementNumber;
		let elementOptionsWrapperID		= 'wordformElementOptions-'+ elementNumber;
		renderElementOptions('range', elementOptionsWrapperID, elementNumber );   				
		if ( appendElement == true ) {
			let generatedElement = '<div id="'+AttrID+'" class="wordform-input-element-div-wrapper wordform-build-input-field-moveable" data-input-element-type="range" data-element-index="'+elementNumber+'"> <span class="wordform-element-delete dashicons dashicons-trash" title="Remove"></span> <div class="wordform-dropped-range-label">Range Label</div> <ul class="wordform-dropped-element-range-field-options"><li><input class="wordform-dropped-range-name" name="wordform-dropped-range-name" type="range" min="0" max="100" value="50" step="5" disabled /> </li></ul></div>';
			DroppabaleElementWrapper.append( generatedElement );
			focusGeneratedElement( generatedElement );
		}
		else {
			return '<div id="'+AttrID+'" class="wordform-input-element-div-wrapper wordform-build-input-field-moveable" data-input-element-type="range" data-element-index="'+elementNumber+'"> <span class="wordform-element-delete dashicons dashicons-trash" title="Remove"></span> <div class="wordform-dropped-range-label">Range Label</div> <ul class="wordform-dropped-element-range-field-options"><li><input class="wordform-dropped-range-name" name="wordform-dropped-range-name" type="range" min="0" max="100" value="50" step="5" disabled /> </li></ul></div>';
		}
	}

    // Url: Create Input Url
	function createInputUrl( appendElement ) {
		let DroppabaleElementWrapper	= $('.wordform-dropzone-div-wrapper');
		let elementNumber				= createElementNumber();		
		let AttrID						= 'wordformElement-'+ elementNumber;
		let elementOptionsWrapperID		= 'wordformElementOptions-'+ elementNumber;
		renderElementOptions('url', elementOptionsWrapperID, elementNumber );   				
		if ( appendElement == true ) {
			let generatedElement = '<div id="'+AttrID+'" class="wordform-input-element-div-wrapper wordform-build-input-field-moveable" data-input-element-type="url" data-element-index="'+elementNumber+'"> <span class="wordform-element-delete dashicons dashicons-trash" title="Remove"></span> <div class="wordform-dropped-url-label">URL Label</div> <ul class="wordform-dropped-element-url-field-options"><li><input class="wordform-dropped-url-name" name="wordform-dropped-url-name" type="url" placeholder="https://example.com" readonly /> </li></ul></div>';
			DroppabaleElementWrapper.append( generatedElement );
			focusGeneratedElement( generatedElement );
		}
		else {
			return '<div id="'+AttrID+'" class="wordform-input-element-div-wrapper wordform-build-input-field-moveable" data-input-element-type="url" data-element-index="'+elementNumber+'"> <span class="wordform-element-delete dashicons dashicons-trash" title="Remove"></span> <div class="wordform-dropped-url-label">URL Label</div> <ul class="wordform-dropped-element-url-field-options"><li><input class="wordform-dropped-url-name" name="wordform-dropped-url-name" type="url" placeholder="https://example.com"  readonly /> </li></ul></div>';
		}
	}

    // Date: Create Input Date
	function createInputDate( appendElement ) {
		let DroppabaleElementWrapper	= $('.wordform-dropzone-div-wrapper');
		let elementNumber				= createElementNumber();		
		let AttrID						= 'wordformElement-'+ elementNumber;
		let elementOptionsWrapperID		= 'wordformElementOptions-'+ elementNumber;
		renderElementOptions('date', elementOptionsWrapperID, elementNumber );   				
		const today = new Date();
		let Today = today.toLocaleDateString('en-CA').split('T')[0];
		let PreviousYear = new Date(today.getFullYear() - 1, today.getMonth(), today.getDate()).toLocaleDateString('en-CA').split('T')[0];
		let NextYear = new Date(today.getFullYear() + 1, today.getMonth(), today.getDate('en-CA')).toLocaleDateString('en-CA').split('T')[0];		
		if ( appendElement == true ) {
			let generatedElement = '<div id="'+AttrID+'" class="wordform-input-element-div-wrapper wordform-build-input-field-moveable" data-input-element-type="date" data-element-index="'+elementNumber+'"> <span class="wordform-element-delete dashicons dashicons-trash" title="Remove"></span> <div class="wordform-dropped-date-label">Date Label</div> <ul class="wordform-dropped-element-date-field-options"><li><input class="wordform-dropped-date-name" name="wordform-dropped-date-name" type="text" placeholder="Pick a date from calendar" readonly /> </li></ul></div>'
			DroppabaleElementWrapper.append( generatedElement );
			focusGeneratedElement( generatedElement );
		}
		else {
			return '<div id="'+AttrID+'" class="wordform-input-element-div-wrapper wordform-build-input-field-moveable" data-input-element-type="date" data-element-index="'+elementNumber+'"> <span class="wordform-element-delete dashicons dashicons-trash" title="Remove"></span> <div class="wordform-dropped-date-label">Date Label</div> <ul class="wordform-dropped-element-date-field-options"><li><input class="wordform-dropped-date-name" name="wordform-dropped-date-name" type="text" placeholder="Pick a date from calendar" readonly /> </li></ul></div>';
		}
	}
	
    // Datetime: Create Input Datetime
	function createInputDatetime( appendElement ) {
		let DroppabaleElementWrapper	= $('.wordform-dropzone-div-wrapper');
		let elementNumber				= createElementNumber();		
		let AttrID						= 'wordformElement-'+ elementNumber;
		let elementOptionsWrapperID		= 'wordformElementOptions-'+ elementNumber;
		renderElementOptions('datetime', elementOptionsWrapperID, elementNumber );   				
		const today = new Date();
		let Today = today.toLocaleDateString('en-CA').split('T')[0];
		let PreviousYear = new Date(today.getFullYear() - 1, today.getMonth(), today.getDate()).toLocaleDateString('en-CA').split('T')[0];
		let NextYear = new Date(today.getFullYear() + 1, today.getMonth(), today.getDate('en-CA')).toLocaleDateString('en-CA').split('T')[0];		

		let generatedElement = 
		'<div id="'+AttrID+'" class="wordform-input-element-div-wrapper wordform-build-input-field-moveable" data-input-element-type="datetime" data-element-index="'+elementNumber+'">' +
			'<span class="wordform-element-delete dashicons dashicons-trash" title="Remove"></span>' +
			'<div class="wordform-dropped-datetime-label">Datetime Label</div>' +
			'<ul class="wordform-dropped-element-datetime-field-options">' +
				'<li>' +
					'<input class="wordform-dropped-datetime-name" name="wordform-dropped-datetime-name" type="text" placeholder="Select date & time" readonly />' +
				'</li>' +
			'</ul>' +
		'</div>';
		
		if ( appendElement == true ) {			
			DroppabaleElementWrapper.append( generatedElement );
			focusGeneratedElement( generatedElement );
		}
		else {			
			return generatedElement;
		}
	}

    // Tel: Create Input Tel
	function createInputTel( appendElement ) {
		let DroppabaleElementWrapper	= $('.wordform-dropzone-div-wrapper');
		let elementNumber				= createElementNumber();		
		let AttrID						= 'wordformElement-'+ elementNumber;
		let elementOptionsWrapperID		= 'wordformElementOptions-'+ elementNumber;
		renderElementOptions('tel', elementOptionsWrapperID, elementNumber );   				
		if ( appendElement == true ) {
			let generatedElement = '<div id="'+AttrID+'" class="wordform-input-element-div-wrapper wordform-build-input-field-moveable" data-input-element-type="tel" data-element-index="'+elementNumber+'"> <span class="wordform-element-delete dashicons dashicons-trash" title="Remove"></span> <div class="wordform-dropped-tel-label">Tel Label</div> <ul class="wordform-dropped-element-tel-field-options"><li><input class="wordform-dropped-tel-name" name="wordform-dropped-tel-name" type="tel" placeholder="Enter Your Phone Number" readonly /> </li></ul></div>'
			DroppabaleElementWrapper.append( generatedElement );
			focusGeneratedElement( generatedElement );
		}
		else {
			return '<div id="'+AttrID+'" class="wordform-input-element-div-wrapper wordform-build-input-field-moveable" data-input-element-type="tel" data-element-index="'+elementNumber+'"> <span class="wordform-element-delete dashicons dashicons-trash" title="Remove"></span> <div class="wordform-dropped-tel-label">Tel Label</div> <ul class="wordform-dropped-element-tel-field-options"><li><input class="wordform-dropped-tel-name" name="wordform-dropped-tel-name" type="tel" placeholder="Enter Your Phone Number" readonly /> </li></ul></div>';
		}
	}


	// Email: Create Input Email
	function createInputEmail( appendElement ) {
		let DroppabaleElementWrapper	= $('.wordform-dropzone-div-wrapper');
		let elementNumber				=	createElementNumber();		
		let AttrID						= 'wordformElement-'+ elementNumber;
		let elementOptionsWrapperID		= 'wordformElementOptions-'+ elementNumber;
		renderElementOptions('email', elementOptionsWrapperID, elementNumber );   						
		if ( appendElement == true ) {
			let generatedElement = '<div id="'+AttrID+'" class="wordform-input-element-div-wrapper wordform-build-input-field-moveable" data-input-element-type="email" data-element-index="'+elementNumber+'"> <span class="wordform-element-delete dashicons dashicons-trash" title="Remove"></span> <div class="wordform-dropped-email-label">Email</div> <ul class="wordform-dropped-element-email-field-options"><li><input class="wordform-dropped-email-name" name="wordform-dropped-email-name" type="email" placeholder="Write Your Email" readonly /> </li></ul>  </div>';
			DroppabaleElementWrapper.append( generatedElement );
			focusGeneratedElement( generatedElement );
		}
		else {
			return '<div id="'+AttrID+'" class="wordform-input-element-div-wrapper wordform-build-input-field-moveable" data-input-element-type="email" data-element-index="'+elementNumber+'"> <span class="wordform-element-delete dashicons dashicons-trash" title="Remove"></span> <div class="wordform-dropped-email-label">Email</div> <ul class="wordform-dropped-element-email-field-options"><li><input class="wordform-dropped-email-name" name="wordform-dropped-email-name" type="email" placeholder="Write Your Email" readonly /> </li></ul>  </div>';
		}
	}
	
	// Captcha: Create Input Captcha - should be added once with Form
	function createInputCaptcha( appendElement ) {
		// if ( is_element_added_into_dropzone('captcha') ) {
		// 	alert('Captcha already added once with your Form!');
		// } 
		let DroppabaleElementWrapper	= $('.wordform-dropzone-div-wrapper');
		let elementNumber				=	createElementNumber();		
		let AttrID						= 'wordformElement-'+ elementNumber;
		let elementOptionsWrapperID		= 'wordformElementOptions-'+ elementNumber;
		let randomNumber                = wordformGenerateCaptchaPreviewDigits(4);
		renderElementOptions('captcha', elementOptionsWrapperID, elementNumber );   								
		if ( appendElement == true ) {
			let generatedElement = '<div id="'+AttrID+'" class="wordform-input-element-div-wrapper wordform-build-input-field-moveable" data-input-element-type="captcha" data-element-index="'+elementNumber+'"> <span class="wordform-element-delete dashicons dashicons-trash" title="Remove"></span> <div class="wordform-dropped-captcha-label">Captcha Label</div> <ul class="wordform-dropped-element-captcha-field-options"><li><input class="wordform-dropped-captcha-name" name="wordform-dropped-captcha-name" type="text" placeholder="Type Captcha Here" readonly /></li> <li class="wordform-input-element-div-wrapper-captcha-template"><div class="wordform-dropped-captcha-placeholder"><span class="wordform-overlay-captcha-value">'+randomNumber+'</span><img src="' + sc_wordform_metabox_script_obj.wordform_default_template_url + '" alt="Captcha Image" /></div></li> </ul>  </div>';
			DroppabaleElementWrapper.append( generatedElement );
			focusGeneratedElement( generatedElement );
		}
		else {
			return '<div id="'+AttrID+'" class="wordform-input-element-div-wrapper wordform-build-input-field-moveable" data-input-element-type="captcha" data-element-index="'+elementNumber+'"> <span class="wordform-element-delete dashicons dashicons-trash" title="Remove"></span> <div class="wordform-dropped-captcha-label">Captcha Label</div> <ul class="wordform-dropped-element-captcha-field-options"><li><input class="wordform-dropped-captcha-name" name="wordform-dropped-captcha-name" type="text" placeholder="Type Captcha Here" readonly /></li> <li class="wordform-input-element-div-wrapper-captcha-template"><div class="wordform-dropped-captcha-placeholder"><span class="wordform-overlay-captcha-value">'+randomNumber+'</span><img src="' + sc_wordform_metabox_script_obj.wordform_default_template_url + '" alt="Captcha Image" /></div></li> </ul>  </div>';
		}		
	}
	
	// Google Captcha: Create Input Google re-captcha - should be added once with Form
	function createInputGoogleCaptcha( appendElement ) {
		const mixedCaptchaConflict = wordformBuilderHasMixedCaptchaConflict('gcaptcha');
		if ( mixedCaptchaConflict ) {
			setTimeout(() => {
				showWordformDialog(mixedCaptchaConflict);
			}, 10);
			return false;
		}
		// if ( is_element_added_into_dropzone('gcaptcha') ) {
		// 	alert('Google reCaptcha already added once with your Form!');
		// } 
		let DroppabaleElementWrapper	= $('.wordform-dropzone-div-wrapper');
		let elementNumber				=	createElementNumber();		
		let AttrID						= 'wordformElement-'+ elementNumber;
		let elementOptionsWrapperID		= 'wordformElementOptions-'+ elementNumber;
		// let randomNumber                = Math.random().toString().substr(2, 4).split('').join(' ');
		renderElementOptions('gcaptcha', elementOptionsWrapperID, elementNumber );   								
		if ( appendElement == true ) {
			let generatedElement = '<div id="'+AttrID+'" class="wordform-input-element-div-wrapper wordform-build-input-field-moveable" data-input-element-type="gcaptcha" data-element-index="'+elementNumber+'"> <span class="wordform-element-delete dashicons dashicons-trash" title="Remove"></span> <div class="wordform-dropped-gcaptcha-label">Google reCaptcha</div> <ul class="wordform-dropped-element-gcaptcha-field-options"><li><input class="wordform-dropped-gcaptcha-name" name="wordform-dropped-gcaptcha-name" type="text" readonly /></li> <li><div class="wordform-dropped-gcaptcha-placeholder"></div></li> </ul>  </div>';
			DroppabaleElementWrapper.append( generatedElement );
			focusGeneratedElement( generatedElement );
		}
		else {
			return '<div id="'+AttrID+'" class="wordform-input-element-div-wrapper wordform-build-input-field-moveable" data-input-element-type="gcaptcha" data-element-index="'+elementNumber+'"> <span class="wordform-element-delete dashicons dashicons-trash" title="Remove"></span> <div class="wordform-dropped-gcaptcha-label">Google reCaptcha</div> <ul class="wordform-dropped-element-gcaptcha-field-options"><li><input class="wordform-dropped-gcaptcha-name" name="wordform-dropped-gcaptcha-name" type="text" readonly /></li> <li><div class="wordform-dropped-gcaptcha-placeholder"></div></li> </ul>  </div>';
		}

	}

	function createInputHCaptcha( appendElement ) {
		const mixedCaptchaConflict = wordformBuilderHasMixedCaptchaConflict('hcaptcha');
		if ( mixedCaptchaConflict ) {
			setTimeout(() => {
				showWordformDialog(mixedCaptchaConflict);
			}, 10);
			return false;
		}
		let DroppabaleElementWrapper	= $('.wordform-dropzone-div-wrapper');
		let elementNumber				=	createElementNumber();		
		let AttrID						= 'wordformElement-'+ elementNumber;
		let elementOptionsWrapperID		= 'wordformElementOptions-'+ elementNumber;
		renderElementOptions('hcaptcha', elementOptionsWrapperID, elementNumber );
		if ( appendElement == true ) {
			let generatedElement = '<div id="'+AttrID+'" class="wordform-input-element-div-wrapper wordform-build-input-field-moveable" data-input-element-type="hcaptcha" data-element-index="'+elementNumber+'"> <span class="wordform-element-delete dashicons dashicons-trash" title="Remove"></span> <div class="wordform-dropped-hcaptcha-label">hCaptcha</div> <ul class="wordform-dropped-element-hcaptcha-field-options"><li><input class="wordform-dropped-hcaptcha-name" name="wordform-dropped-hcaptcha-name" type="text" readonly /></li> <li><div class="wordform-dropped-hcaptcha-placeholder"></div></li> </ul>  </div>';
			DroppabaleElementWrapper.append( generatedElement );
			focusGeneratedElement( generatedElement );
		}
		else {
			return '<div id="'+AttrID+'" class="wordform-input-element-div-wrapper wordform-build-input-field-moveable" data-input-element-type="hcaptcha" data-element-index="'+elementNumber+'"> <span class="wordform-element-delete dashicons dashicons-trash" title="Remove"></span> <div class="wordform-dropped-hcaptcha-label">hCaptcha</div> <ul class="wordform-dropped-element-hcaptcha-field-options"><li><input class="wordform-dropped-hcaptcha-name" name="wordform-dropped-hcaptcha-name" type="text" readonly /></li> <li><div class="wordform-dropped-hcaptcha-placeholder"></div></li> </ul>  </div>';
		}
	}

	// Captcha: Create Input Upload
	function createInputUpload( appendElement ) {
		let DroppabaleElementWrapper	= $('.wordform-dropzone-div-wrapper');
		let elementNumber				=	createElementNumber();		
		let AttrID						= 'wordformElement-'+ elementNumber;
		let elementOptionsWrapperID		= 'wordformElementOptions-'+ elementNumber;		
		renderElementOptions('upload', elementOptionsWrapperID, elementNumber );   								
		if ( appendElement == true ) {
			let generatedElement = '<div id="'+AttrID+'" class="wordform-input-element-div-wrapper wordform-build-input-field-moveable" data-input-element-type="upload" data-element-index="'+elementNumber+'"> <span class="wordform-element-delete dashicons dashicons-trash" title="Remove"></span> <div class="wordform-dropped-upload-label">Upload</div> <ul class="wordform-dropped-element-upload-field-options"><li><input id="wordformFileUpload" class="wordform-dropped-upload-name" name="wordform-dropped-upload-name" type="file" disabled /><label for="wordformFileUpload"><i class="fa-solid fa-upload wordform-dropped-fileupload-icon"></i> <span class="wordform-dropped-upload-select-file-label">Select File</span></label></li> </ul></div>';
			DroppabaleElementWrapper.append( generatedElement );
			focusGeneratedElement( generatedElement );
		}
		else {
			return '<div id="'+AttrID+'" class="wordform-input-element-div-wrapper wordform-build-input-field-moveable" data-input-element-type="upload" data-element-index="'+elementNumber+'"> <span class="wordform-element-delete dashicons dashicons-trash" title="Remove"></span> <div class="wordform-dropped-upload-label">Upload</div> <ul class="wordform-dropped-element-upload-field-options"><li><input id="wordformFileUpload" class="wordform-dropped-upload-name" name="wordform-dropped-upload-name" type="file" disabled /><label for="wordformFileUpload"><i class="fa-solid fa-upload wordform-dropped-fileupload-icon"></i> <span class="wordform-dropped-upload-select-file-label">Select File</span></label></li> </ul></div>';
		}
	}

	// Page Break: Create structural step divider
	function createPageBreakElement( appendElement ) {
		let DroppabaleElementWrapper = $('.wordform-dropzone-div-wrapper');
		let elementNumber = createElementNumber();
		let AttrID = 'wordformElement-' + elementNumber;
		let elementOptionsWrapperID = 'wordformElementOptions-' + elementNumber;
		renderElementOptions('pagebreak', elementOptionsWrapperID, elementNumber);
		let generatedElement = '<div id="' + AttrID + '" class="wordform-input-element-div-wrapper wordform-build-input-field-moveable wordform-pagebreak-builder-element" data-input-element-type="pagebreak" data-element-index="' + elementNumber + '"> <span class="wordform-element-delete dashicons dashicons-trash" title="Remove"></span> <div class="wordform-pagebreak-builder-card"><div class="wordform-pagebreak-builder-topline"><i class="fa-solid fa-forward-step"></i><span class="wordform-pagebreak-builder-badge">Page Break</span></div><div class="wordform-pagebreak-builder-title">Next Step</div><div class="wordform-pagebreak-builder-actions align-prev-left align-next-right"><span class="wordform-pagebreak-builder-action is-secondary">Back</span><span class="wordform-pagebreak-builder-divider"></span><span class="wordform-pagebreak-builder-action is-primary">Next</span></div></div></div>';

		if ( appendElement == true ) {
			DroppabaleElementWrapper.append( generatedElement );
			focusGeneratedElement( generatedElement );
		}
		else {
			return generatedElement;
		}
	}

	// Terms: Create Input Terms & Conditions
	function createInputTerms( appendElement ) {
		let DroppabaleElementWrapper	= $('.wordform-dropzone-div-wrapper');
		let elementNumber				= createElementNumber();		
		let AttrID						= 'wordformElement-'+ elementNumber;
		let elementOptionsWrapperID		= 'wordformElementOptions-'+ elementNumber;
		renderElementOptions('terms', elementOptionsWrapperID, elementNumber );		
		let generatedElement = `
		<div id="${AttrID}" class="wordform-input-element-div-wrapper wordform-build-input-field-moveable" data-input-element-type="terms" data-element-index="${elementNumber}">
		<span class="wordform-element-delete dashicons dashicons-trash" title="Remove"></span>
		<div class="wordform-dropped-terms-label">Terms & Conditions</div>
		<ul class="wordform-dropped-element-terms-field-options">
			<li>
			<input id="wordform-dropped-terms-${elementNumber}" class="wordform-dropped-terms-checkbox" name="wordform-dropped-terms-checkbox" type="checkbox" disabled />
			<label for="wordform-dropped-terms-${elementNumber}">
				<a href="javascript:void(0)" target="_blank" class="wordform-terms-text-clickable-link-text">I agree to the Terms & Conditions</a>.
			</label>
			</li>
		</ul>
		</div>`;

		if ( appendElement == true ) {			
			DroppabaleElementWrapper.append( generatedElement );						
			focusGeneratedElement( generatedElement );
		}
		else {			
			return generatedElement;
		}		
	}

	function createInputGdpr( appendElement ) {
		let DroppabaleElementWrapper	= $('.wordform-dropzone-div-wrapper');
		let elementNumber				= createElementNumber();
		let AttrID						= 'wordformElement-'+ elementNumber;
		let elementOptionsWrapperID		= 'wordformElementOptions-'+ elementNumber;
		renderElementOptions('gdpr', elementOptionsWrapperID, elementNumber );
		let generatedElement = `
		<div id="${AttrID}" class="wordform-input-element-div-wrapper wordform-build-input-field-moveable" data-input-element-type="gdpr" data-element-index="${elementNumber}">
		<span class="wordform-element-delete dashicons dashicons-trash" title="Remove"></span>
		<div class="wordform-dropped-gdpr-label">GDPR Consent</div>
		<ul class="wordform-dropped-element-gdpr-field-options">
			<li>
			<input id="wordform-dropped-gdpr-${elementNumber}" class="wordform-dropped-gdpr-checkbox" name="wordform-dropped-gdpr-checkbox" type="checkbox" disabled />
			<label for="wordform-dropped-gdpr-${elementNumber}">
				<a href="javascript:void(0)" target="_blank" class="wordform-gdpr-text-clickable-link-text">I agree to the privacy policy and consent to data processing.</a>
			</label>
			</li>
		</ul>
		</div>`;

		if ( appendElement == true ) {
			DroppabaleElementWrapper.append( generatedElement );
			focusGeneratedElement( generatedElement );
		}
		else {
			return generatedElement;
		}
	}

	// Payment Item: Create fixed payment item element
	function createPaymentMethod( appendElement ) {
		let DroppabaleElementWrapper = $('.wordform-dropzone-div-wrapper');
		let elementNumber = createElementNumber();
		let AttrID = 'wordformElement-' + elementNumber;
		let elementOptionsWrapperID = 'wordformElementOptions-' + elementNumber;
		renderElementOptions('payment_method', elementOptionsWrapperID, elementNumber);
		let generatedElement =
		'<div id="' + AttrID + '" class="wordform-input-element-div-wrapper wordform-build-input-field-moveable wordform-payment-builder-element" data-input-element-type="payment_method" data-element-index="' + elementNumber + '">' +
			'<span class="wordform-element-delete dashicons dashicons-trash" title="Remove"></span>' +
			'<div class="wordform-payment-method-builder-card">' +
				'<div class="wordform-payment-method-builder-title">Payment Method</div>' +
				'<div class="wordform-payment-method-builder-helper-text">Choose how you want to pay</div>' +
				'<div class="wordform-payment-method-builder-options">' +
					'<label class="wordform-payment-method-builder-option is-active" data-gateway="stripe">' +
						'<input class="wordform-payment-method-builder-option-input" type="radio" checked="checked" disabled />' +
						'<span class="wordform-payment-method-builder-option-card"><i class="fa-brands fa-stripe"></i><span class="wordform-payment-method-builder-option-text">Stripe</span></span>' +
					'</label>' +
					'<label class="wordform-payment-method-builder-option" data-gateway="paypal">' +
						'<input class="wordform-payment-method-builder-option-input" type="radio" disabled />' +
						'<span class="wordform-payment-method-builder-option-card"><i class="fa-brands fa-paypal"></i><span class="wordform-payment-method-builder-option-text">PayPal</span></span>' +
					'</label>' +
					'<label class="wordform-payment-method-builder-option" data-gateway="square">' +
						'<input class="wordform-payment-method-builder-option-input" type="radio" disabled />' +
						'<span class="wordform-payment-method-builder-option-card"><i class="fa-solid fa-square"></i><span class="wordform-payment-method-builder-option-text">Square</span></span>' +
					'</label>' +
					'<label class="wordform-payment-method-builder-option" data-gateway="authorizenet">' +
						'<input class="wordform-payment-method-builder-option-input" type="radio" disabled />' +
						'<span class="wordform-payment-method-builder-option-card"><i class="fa-solid fa-building-columns"></i><span class="wordform-payment-method-builder-option-text">Authorize.Net</span></span>' +
					'</label>' +
				'</div>' +
			'</div>' +
		'</div>';

		if ( appendElement === true ) {
			DroppabaleElementWrapper.append( generatedElement );
			focusGeneratedElement( generatedElement );
		} else {
			return generatedElement;
		}
	}

	// Payment Item: Create fixed payment item element
	function createPaymentItem( appendElement ) {
		let DroppabaleElementWrapper = $('.wordform-dropzone-div-wrapper');
		let elementNumber = createElementNumber();
		let AttrID = 'wordformElement-' + elementNumber;
		let elementOptionsWrapperID = 'wordformElementOptions-' + elementNumber;
		renderElementOptions('payment_item', elementOptionsWrapperID, elementNumber);
		let generatedElement =
		'<div id="' + AttrID + '" class="wordform-input-element-div-wrapper wordform-build-input-field-moveable wordform-payment-builder-element" data-input-element-type="payment_item" data-element-index="' + elementNumber + '">' +
			'<span class="wordform-element-delete dashicons dashicons-trash" title="Remove"></span>' +
			'<div class="wordform-payment-builder-card">' +
				'<div class="wordform-payment-builder-card-header">' +
					'<div class="wordform-payment-item-label">Payment Item</div>' +
					'<div class="wordform-payment-item-amount">$0.00</div>' +
				'</div>' +
				'<div class="wordform-payment-item-description">Fixed price item</div>' +
			'</div>' +
		'</div>';

		if ( appendElement === true ) {
			DroppabaleElementWrapper.append( generatedElement );
			focusGeneratedElement( generatedElement );
			wordformRefreshBuilderPaymentSummary();
		} else {
			return generatedElement;
		}
	}

	// Custom Amount: Create amount input element
	function createPaymentCustomAmount( appendElement ) {
		let DroppabaleElementWrapper = $('.wordform-dropzone-div-wrapper');
		let elementNumber = createElementNumber();
		let AttrID = 'wordformElement-' + elementNumber;
		let elementOptionsWrapperID = 'wordformElementOptions-' + elementNumber;
		renderElementOptions('payment_custom_amount', elementOptionsWrapperID, elementNumber);
		let generatedElement =
		'<div id="' + AttrID + '" class="wordform-input-element-div-wrapper wordform-build-input-field-moveable wordform-payment-builder-element" data-input-element-type="payment_custom_amount" data-element-index="' + elementNumber + '">' +
			'<span class="wordform-element-delete dashicons dashicons-trash" title="Remove"></span>' +
			'<div class="wordform-dropped-payment-custom-amount-label">Custom Amount</div>' +
			'<ul class="wordform-dropped-element-payment-custom-amount-field-options">' +
				'<li class="wordform-payment-amount-input-row"><span class="wordform-payment-currency-prefix">$</span><input class="wordform-dropped-payment-custom-amount-name" name="wordform-dropped-payment-custom-amount-name" type="number" min="0" step="0.01" placeholder="Enter amount" readonly /></li>' +
			'</ul>' +
		'</div>';

		if ( appendElement === true ) {
			DroppabaleElementWrapper.append( generatedElement );
			focusGeneratedElement( generatedElement );
			wordformRefreshBuilderPaymentSummary();
		} else {
			return generatedElement;
		}
	}

	// Quantity: Create quantity field element
	function createPaymentQuantity( appendElement ) {
		let DroppabaleElementWrapper = $('.wordform-dropzone-div-wrapper');
		let elementNumber = createElementNumber();
		let AttrID = 'wordformElement-' + elementNumber;
		let elementOptionsWrapperID = 'wordformElementOptions-' + elementNumber;
		renderElementOptions('payment_quantity', elementOptionsWrapperID, elementNumber);
		let generatedElement =
		'<div id="' + AttrID + '" class="wordform-input-element-div-wrapper wordform-build-input-field-moveable wordform-payment-builder-element" data-input-element-type="payment_quantity" data-element-index="' + elementNumber + '">' +
			'<span class="wordform-element-delete dashicons dashicons-trash" title="Remove"></span>' +
			'<div class="wordform-dropped-payment-quantity-label">Quantity</div>' +
			'<ul class="wordform-dropped-element-payment-quantity-field-options">' +
				'<li><input class="wordform-dropped-payment-quantity-name" name="wordform-dropped-payment-quantity-name" type="number" min="1" step="1" value="1" readonly /></li>' +
			'</ul>' +
		'</div>';

		if ( appendElement === true ) {
			DroppabaleElementWrapper.append( generatedElement );
			focusGeneratedElement( generatedElement );
			wordformRefreshBuilderPaymentSummary();
		} else {
			return generatedElement;
		}
	}

	// Payment Summary: Create summary card element
	function createPaymentSummary( appendElement ) {
		let DroppabaleElementWrapper = $('.wordform-dropzone-div-wrapper');
		let elementNumber = createElementNumber();
		let AttrID = 'wordformElement-' + elementNumber;
		let elementOptionsWrapperID = 'wordformElementOptions-' + elementNumber;
		renderElementOptions('payment_summary', elementOptionsWrapperID, elementNumber);
		let generatedElement =
		'<div id="' + AttrID + '" class="wordform-input-element-div-wrapper wordform-build-input-field-moveable wordform-payment-builder-element" data-input-element-type="payment_summary" data-element-index="' + elementNumber + '">' +
			'<span class="wordform-element-delete dashicons dashicons-trash" title="Remove"></span>' +
			'<div class="wordform-payment-summary-card">' +
				'<div class="wordform-payment-summary-title">Payment Summary</div>' +
				'<div class="wordform-payment-summary-row"><span>Subtotal</span><strong>$0.00</strong></div>' +
				'<div class="wordform-payment-summary-row wordform-payment-summary-row-discount" style="display:none;"><span>Discount</span><strong>-$0.00</strong></div>' +
				'<div class="wordform-payment-summary-row"><span>Total</span><strong>$0.00</strong></div>' +
				'<div class="wordform-payment-summary-empty-text" data-empty-text="Amounts will appear here">Amounts will appear here</div>' +
			'</div>' +
		'</div>';

		if ( appendElement === true ) {
			DroppabaleElementWrapper.append( generatedElement );
			focusGeneratedElement( generatedElement );
			wordformRefreshBuilderPaymentSummary();
		} else {
			return generatedElement;
		}
	}

	// Coupon: Create coupon input element
	function createPaymentCoupon( appendElement ) {
		let DroppabaleElementWrapper = $('.wordform-dropzone-div-wrapper');
		let elementNumber = createElementNumber();
		let AttrID = 'wordformElement-' + elementNumber;
		let elementOptionsWrapperID = 'wordformElementOptions-' + elementNumber;
		renderElementOptions('payment_coupon', elementOptionsWrapperID, elementNumber);
		let generatedElement =
		'<div id="' + AttrID + '" class="wordform-input-element-div-wrapper wordform-build-input-field-moveable wordform-payment-builder-element" data-input-element-type="payment_coupon" data-element-index="' + elementNumber + '">' +
			'<span class="wordform-element-delete dashicons dashicons-trash" title="Remove"></span>' +
			'<div class="wordform-payment-coupon-builder-card">' +
				'<div class="wordform-payment-coupon-builder-title">Coupon Code</div>' +
				'<div class="wordform-payment-coupon-builder-input-row">' +
					'<input class="wordform-payment-coupon-builder-input" type="text" placeholder="Enter coupon code" readonly />' +
					'<button class="button button-secondary wordform-payment-coupon-builder-button" type="button" disabled><i class="fa-solid fa-ticket"></i><span class="wordform-payment-coupon-builder-button-text">Apply Coupon</span></button>' +
				'</div>' +
				'<div class="wordform-payment-coupon-builder-message">Applied coupon feedback will appear here.</div>' +
			'</div>' +
		'</div>';

		if ( appendElement === true ) {
			DroppabaleElementWrapper.append( generatedElement );
			focusGeneratedElement( generatedElement );
			wordformRefreshBuilderPaymentSummary();
		} else {
			return generatedElement;
		}
	}

	// Stripe: Create Stripe gateway placeholder
	function createStripeElement( appendElement ) {
		let DroppabaleElementWrapper = $('.wordform-dropzone-div-wrapper');
		let elementNumber = createElementNumber();
		let AttrID = 'wordformElement-' + elementNumber;
		let elementOptionsWrapperID = 'wordformElementOptions-' + elementNumber;
		renderElementOptions('stripe', elementOptionsWrapperID, elementNumber);
		let generatedElement =
		'<div id="' + AttrID + '" class="wordform-input-element-div-wrapper wordform-build-input-field-moveable wordform-payment-builder-element" data-input-element-type="stripe" data-element-index="' + elementNumber + '">' +
			'<span class="wordform-element-delete dashicons dashicons-trash" title="Remove"></span>' +
			'<div class="wordform-payment-gateway-card wordform-payment-gateway-card-stripe">' +
				'<div class="wordform-payment-gateway-title"><i class="fa-brands fa-stripe"></i> <span class="wordform-dropped-stripe-label">Stripe Payment</span></div>' +
				'<div class="wordform-payment-gateway-description wordform-dropped-stripe-description">Secure card payment via Stripe</div>' +
				'<button class="button button-secondary wordform-payment-gateway-preview-button" type="button" disabled><span class="wordform-dropped-stripe-button-text">Pay with Card</span></button>' +
			'</div>' +
		'</div>';

		if ( appendElement === true ) {
			DroppabaleElementWrapper.append( generatedElement );
			focusGeneratedElement( generatedElement );
		} else {
			return generatedElement;
		}
	}

	// PayPal: Create PayPal gateway placeholder
	function createPayPalElement( appendElement ) {
		let DroppabaleElementWrapper = $('.wordform-dropzone-div-wrapper');
		let elementNumber = createElementNumber();
		let AttrID = 'wordformElement-' + elementNumber;
		let elementOptionsWrapperID = 'wordformElementOptions-' + elementNumber;
		renderElementOptions('paypal', elementOptionsWrapperID, elementNumber);
		let generatedElement =
		'<div id="' + AttrID + '" class="wordform-input-element-div-wrapper wordform-build-input-field-moveable wordform-payment-builder-element" data-input-element-type="paypal" data-element-index="' + elementNumber + '">' +
			'<span class="wordform-element-delete dashicons dashicons-trash" title="Remove"></span>' +
			'<div class="wordform-payment-gateway-card wordform-payment-gateway-card-paypal">' +
				'<div class="wordform-payment-gateway-title"><i class="fa-brands fa-paypal"></i> <span class="wordform-dropped-paypal-label">PayPal Payment</span></div>' +
				'<div class="wordform-payment-gateway-description wordform-dropped-paypal-description">Checkout with your PayPal account</div>' +
				'<button class="button button-secondary wordform-payment-gateway-preview-button" type="button" disabled><span class="wordform-dropped-paypal-button-text">Pay with PayPal</span></button>' +
			'</div>' +
		'</div>';

		if ( appendElement === true ) {
			DroppabaleElementWrapper.append( generatedElement );
			focusGeneratedElement( generatedElement );
		} else {
			return generatedElement;
		}
	}

	// Square: Create Square gateway placeholder
	function createSquareElement( appendElement ) {
		let DroppabaleElementWrapper = $('.wordform-dropzone-div-wrapper');
		let elementNumber = createElementNumber();
		let AttrID = 'wordformElement-' + elementNumber;
		let elementOptionsWrapperID = 'wordformElementOptions-' + elementNumber;
		renderElementOptions('square', elementOptionsWrapperID, elementNumber);
		let generatedElement =
		'<div id="' + AttrID + '" class="wordform-input-element-div-wrapper wordform-build-input-field-moveable wordform-payment-builder-element" data-input-element-type="square" data-element-index="' + elementNumber + '">' +
			'<span class="wordform-element-delete dashicons dashicons-trash" title="Remove"></span>' +
			'<div class="wordform-payment-gateway-card wordform-payment-gateway-card-square">' +
				'<div class="wordform-payment-gateway-title"><i class="fa-solid fa-square"></i> <span class="wordform-dropped-square-label">Square Payment</span></div>' +
				'<div class="wordform-payment-gateway-description wordform-dropped-square-description">Secure card payment via Square</div>' +
				'<button class="button button-secondary wordform-payment-gateway-preview-button" type="button" disabled><span class="wordform-dropped-square-button-text">Pay with Square</span></button>' +
			'</div>' +
		'</div>';

		if ( appendElement === true ) {
			DroppabaleElementWrapper.append( generatedElement );
			focusGeneratedElement( generatedElement );
		} else {
			return generatedElement;
		}
	}

	// Authorize.Net: Create gateway placeholder
	function createAuthorizeNetElement( appendElement ) {
		let DroppabaleElementWrapper = $('.wordform-dropzone-div-wrapper');
		let elementNumber = createElementNumber();
		let AttrID = 'wordformElement-' + elementNumber;
		let elementOptionsWrapperID = 'wordformElementOptions-' + elementNumber;
		renderElementOptions('authorizenet', elementOptionsWrapperID, elementNumber);
		let generatedElement =
		'<div id="' + AttrID + '" class="wordform-input-element-div-wrapper wordform-build-input-field-moveable wordform-payment-builder-element" data-input-element-type="authorizenet" data-element-index="' + elementNumber + '">' +
			'<span class="wordform-element-delete dashicons dashicons-trash" title="Remove"></span>' +
			'<div class="wordform-payment-gateway-card wordform-payment-gateway-card-authorizenet">' +
				'<div class="wordform-payment-gateway-title"><i class="fa-solid fa-building-columns"></i> <span class="wordform-dropped-authorizenet-label">Authorize.Net Payment</span></div>' +
				'<div class="wordform-payment-gateway-description wordform-dropped-authorizenet-description">Secure card payment via Authorize.Net</div>' +
				'<button class="button button-secondary wordform-payment-gateway-preview-button" type="button" disabled><span class="wordform-dropped-authorizenet-button-text">Pay with Authorize.Net</span></button>' +
			'</div>' +
		'</div>';

		if ( appendElement === true ) {
			DroppabaleElementWrapper.append( generatedElement );
			focusGeneratedElement( generatedElement );
		} else {
			return generatedElement;
		}
	}

	function wordformBuilderParsePaymentAmount(value) {
		const parsed = parseFloat(value);
		return Number.isFinite(parsed) ? parsed : 0;
	}

	function wordformBuilderFormatPaymentAmount(amount) {
		return '$' + wordformBuilderParsePaymentAmount(amount).toFixed(2);
	}

	function wordformRefreshBuilderPaymentSummary() {
		let fixedItemsSubtotal = 0;
		let customAmountTotal = 0;
		let quantityMultiplier = 1;
		let hasCouponField = $('.wordform-dropzone-div-wrapper [data-input-element-type="payment_coupon"]').length > 0;

		$('.wordform-dropzone-div-wrapper [data-input-element-type="payment_item"]').each(function() {
			const amountText = $(this).find('.wordform-payment-item-amount').text().replace(/[^0-9.\-]/g, '');
			fixedItemsSubtotal += wordformBuilderParsePaymentAmount(amountText);
		});

		const $quantityElement = $('.wordform-dropzone-div-wrapper [data-input-element-type="payment_quantity"]').first();
		if ($quantityElement.length) {
			const quantityValue = $quantityElement.find('.wordform-dropped-payment-quantity-name').val() || $quantityElement.find('.wordform-dropped-payment-quantity-name').attr('value');
			quantityMultiplier = Math.max(1, Math.round(wordformBuilderParsePaymentAmount(quantityValue || 1)));
		}

		$('.wordform-dropzone-div-wrapper [data-input-element-type="payment_custom_amount"]').each(function() {
			const amountValue = $(this).find('.wordform-dropped-payment-custom-amount-name').val() || $(this).find('.wordform-dropped-payment-custom-amount-name').attr('value');
			customAmountTotal += wordformBuilderParsePaymentAmount(amountValue);
		});

		const subtotal = (fixedItemsSubtotal * quantityMultiplier) + customAmountTotal;
		const formattedSubtotal = wordformBuilderFormatPaymentAmount(subtotal);
		const hasAmount = subtotal > 0;

		$('.wordform-dropzone-div-wrapper [data-input-element-type="payment_summary"]').each(function() {
			const $summaryCard = $(this).find('.wordform-payment-summary-card');
			const $rows = $summaryCard.find('.wordform-payment-summary-row strong');
			const $discountRow = $summaryCard.find('.wordform-payment-summary-row-discount');
			const emptyText = $summaryCard.find('.wordform-payment-summary-empty-text').data('empty-text') || 'Amounts will appear here';

			$rows.eq(0).text(formattedSubtotal);
			$rows.eq(1).text('-$0.00');
			$rows.eq(2).text(formattedSubtotal);
			$discountRow.toggle(hasCouponField);

			if (hasAmount) {
				$summaryCard.find('.wordform-payment-summary-empty-text').hide();
				$summaryCard.find('.wordform-payment-summary-row').css('display', 'flex');
			} else {
				$summaryCard.find('.wordform-payment-summary-empty-text').text(emptyText).show();
				$summaryCard.find('.wordform-payment-summary-row').css('display', 'flex');
			}
		});
	}

	function wordformSetBuilderPaymentMethodPreview(elementIndex, gatewaySlug) {
		const $wrapper = $('#wordformElement-' + elementIndex + ' .wordform-payment-method-builder-options');
		if (!$wrapper.length) {
			return;
		}

		$wrapper.find('.wordform-payment-method-builder-option').removeClass('is-active');
		$wrapper.find('.wordform-payment-method-builder-option-input').prop('checked', false).attr('checked', false);
		$wrapper.find('.wordform-payment-method-builder-option[data-gateway="' + gatewaySlug + '"]').addClass('is-active')
			.find('.wordform-payment-method-builder-option-input').prop('checked', true).attr('checked', true);
	}


	/** All Common ***/

	// All: Focus appened generated Form element : when added by click on Element
	function focusGeneratedElement( newElement ) {
		if (wordformBuilderReconstructionInProgress) {
			return;
		}

		// $el = $('#wordform-sortable');
		// let dropZoneScrollHeight = $el.get(0).scrollHeight;
		// $el.animate({ scrollTop: dropZoneScrollHeight }, 'fast');					

		let totalChildrenHeight = 0;
				
		// Sum all children heights (including margins)
		$('.wordform-input-element-div-wrapper').each(function () {
			totalChildrenHeight += $(this).outerHeight(true);
		});

		// Get the parent container
		let $parent = $('.wordform-dropzone-div-wrapper');
		let parentHeight = $parent.outerHeight();

		console.log("Total children height:", totalChildrenHeight);
		console.log("Parent container height:", parentHeight);

		// If children overflow the parent, scroll to bottom
		if (totalChildrenHeight > parentHeight) {
			console.log('Scroll To Bottom');
			let scrollSelector = '.wordform-fullscreen-wrapper';
			scrollToBottom( scrollSelector );
		}
	}
    // All: scroll to Bottom
	function scrollToBottom( scrollSelector ) {
		let $fullscreen = $( scrollSelector );

		if ($fullscreen.length && $fullscreen.get(0).scrollHeight > $fullscreen.height()) {
			// Fullscreen mode → scroll the wrapper
			$fullscreen.stop().animate({
				scrollTop: $fullscreen.get(0).scrollHeight - $fullscreen.height()
			}, 1000, 'swing');
		} else {
			// Standard page scroll
			$('html, body').stop().animate({
				scrollTop: $(document).height() - $(window).height()
			}, 1000, 'swing');
		}
	}

	function initWordformBuilderAccordion() {
		const $builderSidebar = $('.wordform-draggable-elements-div-wrapper');

		if (!$builderSidebar.length) {
			return;
		}

		$builderSidebar.find('.wordform-builder-section-toggle').each(function() {
			const $toggle = $(this);
			const target = $toggle.attr('data-wordform-builder-target');
			const $group = $builderSidebar.find('[data-wordform-builder-group="' + target + '"]');

			if (!$group.length) {
				return;
			}

			if ($toggle.hasClass('is-open')) {
				$group.addClass('open').show();
			} else {
				$group.removeClass('open').hide();
			}
		});
	}

	$('body').off('click.wordformBuilderAccordion').on('click.wordformBuilderAccordion', '.wordform-builder-section-toggle', function(e) {
		e.preventDefault();
		e.stopPropagation();

		const $toggle = $(this);
		const target = $toggle.attr('data-wordform-builder-target');
		const $group = $('.wordform-draggable-elements-div-wrapper').find('[data-wordform-builder-group="' + target + '"]');
		const shouldOpen = !$toggle.hasClass('is-open');

		if (!$group.length) {
			return;
		}

		if (shouldOpen) {
			$toggle.addClass('is-open');
			$group.stop(true, true).removeAttr('style').hide().addClass('open').slideDown(180);
		} else {
			$toggle.removeClass('is-open');
			$group.stop(true, true).slideUp(180, function() {
				$group.removeClass('open').removeAttr('style');
			});
		}
	});

	initWordformBuilderAccordion();


	// All: Check same element added into dropzone
	function is_element_added_into_dropzone( elementName = '' ) {
		if ( $('.wordform-dropzone-div-wrapper').find('[data-input-element-type="'+elementName+'"]').length > 0 ) {
			return true;
		}
		return false;
	}
	
	// All: Render element options update template
	function renderElementOptions( elementType, elementOptionsWrapperID, elementIndex ) {
		let actionName			= 'sc_wordform_render_element_options_type_'+elementType;
		//console.log(actionName);
		let jsonData			= '';
		$.ajax({
		  type : "POST",		  
		  url  : sc_wordform_metabox_script_obj.adminajax_url,
		  data : {			    
				action 	 			: actionName,
				security 			: sc_wordform_metabox_script_obj.nonce,
			    elementWrapperID 	: elementOptionsWrapperID
				},		  
		  success: function(data) { 
			 //console.log(data); 
			 jsonData	= JSON.parse( data );			 
			 const appendOptionsMarkup = function() {
				$('.wordform-builder-form-options-div-wrapper').append(jsonData.fieldEditOptionsHtml);
				wordformAppendSharedHelpTextControl($('#' + elementOptionsWrapperID), elementType);
				wordformEnsureInitialSharedHelpTextValue($('#' + elementOptionsWrapperID), $('#wordformElement-' + elementIndex), elementType);
				wordformAppendSharedFieldWidthControl($('#' + elementOptionsWrapperID), elementType);
				wordformEnsureInitialSharedFieldWidthValue($('#' + elementOptionsWrapperID), elementType);
				wordformSetBuilderFieldWidthPreview($('#wordformElement-' + elementIndex), elementType, wordformReadSharedFieldWidthValue($('#' + elementOptionsWrapperID), elementType));
				wordformAppendSharedCustomClassControl($('#' + elementOptionsWrapperID), elementType);
				wordformEnsureInitialSharedCustomClassValue($('#' + elementOptionsWrapperID), elementType);
				wordformAppendSharedDefaultValueControl($('#' + elementOptionsWrapperID), elementType);
				wordformEnsureInitialSharedDefaultValue($('#' + elementOptionsWrapperID), $('#wordformElement-' + elementIndex), elementType);
				wordformAppendAdminLabelControls($('#' + elementOptionsWrapperID), elementType, elementIndex);
				wordformEnsureInitialAdminLabelValues($('#' + elementOptionsWrapperID), elementType, elementIndex);
				wordformEnhanceColorInputs($('#' + elementOptionsWrapperID));
			 };
			 const appendAndMaybeActivate = function(showHideCallback) {
				appendOptionsMarkup();
				if (!wordformBuilderReconstructionInProgress) {
					showHideCallback( elementOptionsWrapperID );
					setSelectedDroppedElementBackground( elementIndex );
				}
			 };
			 //console.log(jsonData ); 
			 switch( elementType ) {
				 case 'radio':
					 appendAndMaybeActivate( showHideRadioOptions );
					 break;
				 case 'checkbox':
					 appendAndMaybeActivate( showHideCheckboxOptions );
					 break;					 
				 case 'select':
					 appendAndMaybeActivate( showHideSelectOptions );
					 break;					 
				 case 'text':
					 appendAndMaybeActivate( showHideTextOptions );
					 break;
				 case 'firstlastname':
					 appendAndMaybeActivate( showHideFirstLastNameOptions );
					 break;
				 case 'number':
					 appendAndMaybeActivate( showHideNumberOptions );
					 break;					 
				 case 'textarea':
					 appendAndMaybeActivate( showHideTextareaOptions );
					 break;
				case 'range':
					appendAndMaybeActivate( showHideRangeOptions );
					break;   
				case 'url':
					appendAndMaybeActivate( showHideUrlOptions );
					break;   
				case 'date':
					appendAndMaybeActivate( showHideDateOptions );
					break;   
				case 'time':
					appendAndMaybeActivate( showHideTimeOptions );
					break;   
				case 'datetime':
					appendAndMaybeActivate( showHideDatetimeOptions );
					break;   
				case 'tel':
					appendAndMaybeActivate( showHideTelOptions );
					break;   
				 case 'email':
					 appendAndMaybeActivate( showHideEmailOptions );
					 break;			
				 case 'address':
					 appendAndMaybeActivate( showHideAddressOptions );
					 break;
				 case 'sectionhtml':
					 appendAndMaybeActivate( showHideSectionHtmlOptions );
					 break;
				 case 'maskinput':
					 appendAndMaybeActivate( showHideMaskInputOptions );
					 break;
				 case 'hidden':
					 appendAndMaybeActivate( showHideHiddenOptions );
					 break;
				 case 'captcha':
					 appendAndMaybeActivate( showHideCaptchaOptions );
					 break;		
				case 'gcaptcha':
					appendAndMaybeActivate( showHideGoogleCaptchaOptions );
					break;
				case 'hcaptcha':
					appendAndMaybeActivate( showHideHCaptchaOptions );
					break;
				 case 'upload':
					 appendAndMaybeActivate( showHideUploadOptions );
					 break;			   
				 case 'rating':
					 appendAndMaybeActivate( showHideRatingOptions );
					 break;
				 case 'richeditor':
					 appendAndMaybeActivate( showHideRichEditorOptions );
					 break;
				 case 'likert':
					 appendAndMaybeActivate( showHideLikertOptions );
					 break;
				 case 'signature':
					 appendAndMaybeActivate( showHideSignatureOptions );
					 break;
				 case 'pagebreak':
					 appendAndMaybeActivate( showHidePageBreakOptions );
					 break;
				 case 'terms':
					 appendAndMaybeActivate( showHideTermsOptions );
					 break;
				 case 'gdpr':
					 appendAndMaybeActivate( showHideGdprOptions );
					 break;
				 case 'payment_item':
					 appendAndMaybeActivate( showHidePaymentItemOptions );
					 break;
				 case 'payment_coupon':
					 appendAndMaybeActivate( showHidePaymentCouponOptions );
					 break;
				 case 'payment_method':
					 appendAndMaybeActivate( showHidePaymentMethodOptions );
					 break;
				 case 'payment_custom_amount':
					 appendAndMaybeActivate( showHidePaymentCustomAmountOptions );
					 break;
				 case 'payment_quantity':
					 appendAndMaybeActivate( showHidePaymentQuantityOptions );
					 break;
				 case 'payment_summary':
					 appendAndMaybeActivate( showHidePaymentSummaryOptions );
					 break;
				 case 'stripe':
					 appendAndMaybeActivate( showHideStripeOptions );
					 break;
				 case 'paypal':
					 appendAndMaybeActivate( showHidePaypalOptions );
					 break;
				 case 'square':
					 appendAndMaybeActivate( showHideSquareOptions );
					 break;
				 case 'authorizenet':
					 appendAndMaybeActivate( showHideAuthorizeNetOptions );
					 break;
				 default:
					 console.log('Rendering element not supported yet.');
					 break;
			 } 
			},
		  error: function( xhr, status, error ) { 
			 console.log(xhr); 
			 console.log(status); 
			 console.log(error); 				 
			}
		});								
	}
	
	// All: set Checkbox attr on change
	$('body').on('change', 'input[type="checkbox"]', function() {
		if ( $(this).is(":checked") ) {
			$(this).attr('checked', true );			
		}
		else {
			$(this).attr('checked', false );		
		}
	});
	
	// All: set all type Text / Number / Email input field attr on change
	$('body').on('input', 'input[type="text"], input[type="number"], input[type="email"]', function() {
		$(this).attr('value', $(this).val() );
	});

	$('body').on('input', '.wordform-admin-label-input', function() {
		$(this).attr('data-wordform-admin-label-mode', 'manual');
		$(this).attr('value', $(this).val());
	});

	$('body').on('input', '.wordform-admin-label-first-input, .wordform-admin-label-last-input', function() {
		$(this).attr('data-wordform-admin-label-mode', 'manual');
		$(this).attr('value', $(this).val());
	});

	$('body').on('blur change', '.wordform-admin-label-input, .wordform-admin-label-first-input, .wordform-admin-label-last-input', function() {
		const elementType = wordformGetOptionsWrapperType($(this).closest('.show-hide-common-class-all-options-wrapper-element'));
		const elementIndex = (($(this).closest('.show-hide-common-class-all-options-wrapper-element').prop('id') || '').split('-')[1]) || '';
		const variant = $(this).hasClass('wordform-admin-label-last-input') ? 'last' : ($(this).hasClass('wordform-admin-label-first-input') ? 'first' : '');
		const normalizedValue = wordformSlugifyAdminLabel($(this).val(), wordformDefaultAdminLabelBase(elementType, elementIndex, '', variant));
		$(this).val(normalizedValue).attr('value', normalizedValue);
	});

	$('body').on('input', '.wordform-shared-help-text-input', function() {
		const $optionsWrapper = $(this).closest('.show-hide-common-class-all-options-wrapper-element');
		const elementIndex = (($optionsWrapper.prop('id') || '').split('-')[1]) || '';
		wordformSetBuilderHelpTextPreview($('#wordformElement-' + elementIndex), $(this).val());
		$(this).attr('value', $(this).val());
	});

	$('body').on('input', '.wordform-shared-default-value-input', function() {
		const $optionsWrapper = $(this).closest('.show-hide-common-class-all-options-wrapper-element');
		const elementType = wordformGetOptionsWrapperType($optionsWrapper);
		const elementIndex = (($optionsWrapper.prop('id') || '').split('-')[1]) || '';
		wordformSetBuilderSharedDefaultValuePreview($('#wordformElement-' + elementIndex), elementType, $(this).val());
		$(this).attr('value', $(this).val());
	});

	$('body').on('change', '.wordform-shared-field-width-select', function() {
		const $optionsWrapper = $(this).closest('.show-hide-common-class-all-options-wrapper-element');
		const elementType = wordformGetOptionsWrapperType($optionsWrapper);
		const elementIndex = (($optionsWrapper.prop('id') || '').split('-')[1]) || '';
		wordformSetBuilderFieldWidthPreview($('#wordformElement-' + elementIndex), elementType, $(this).val());
	});

	// All: Set width in percentage of dragged elements while inside droppable area
	function setInputElementWidthBasedOnWrapper() {
		let targetWidthPercentage = $("#wordform-sortable").width() * 0.90; // For 90% of the reference element's width
		// $(ui.helper).css('width', targetWidthPercentage );		
		return targetWidthPercentage;
	}
	
	// All: set all selected element backgorund
	function setSelectedDroppedElementBackground( elementIndex ) {
		console.log('setSelectedDroppedElementBackground() elementIndex: '+elementIndex);
		$inputElement = $('.wordform-input-element-div-wrapper');
		$inputOptionsCustomizationPanelElement = $('.wordform-builder-form-options-div-wrapper');		

	// Remove earlier selected background color from elements
	$inputElement.removeClass('wordform-selected-dropped-element-background-color'); 
	$inputElement.removeAttr('data-wordform-active-label');
	$inputElement.removeAttr('data-wordform-active-width-label');
	// Drpped Element 		
	$droppedElement = $('#wordformElement-'+elementIndex);
	// console.log( 'setSelectedDroppedElementBackground(): ' );
	// console.log( $droppedElement );
	updateWordformActiveElementHeader($droppedElement);
	if ($droppedElement.length) {
		const elementMeta = getWordformActiveElementMeta($droppedElement.data('input-element-type'));
		$droppedElement.attr('data-wordform-active-label', elementMeta.title);
		if (wordformElementSupportsSharedFieldWidth($droppedElement.data('input-element-type'))) {
			const widthValue = $droppedElement.attr('data-wordform-builder-field-width') || 'full';
			$droppedElement.attr('data-wordform-active-width-label', wordformGetBuilderFieldWidthBadgeLabel(widthValue));
		}
	}

	// Add selected element background color
	$inputElement.promise().done(function() {			
			$droppedElement.addClass('wordform-selected-dropped-element-background-color');			
		});		

		// Remove earlier Arrow Connector and show the only selected one
		hideWordformConnector().then(() => showWordformConnector( $droppedElement ) );		
	}		
	
	// All: On Click / Select Dropped Element - Show-Hide corresponding edit options data
	$('body').on("click", ".wordform-input-element-div-wrapper:not(.wordform-input-element-div-wrapper-submit-button):not(.wordform-input-element-div-wrapper-form-name)", function() {
		let elementIndex				= $(this).data('element-index');
		let elementType					= $(this).data('input-element-type');
		let elementOptionsWrapperID		= 'wordformElementOptions-'+elementIndex;
		switch ( elementType ) {
			case 'radio':
				showHideRadioOptions( elementOptionsWrapperID );
				break;
			case 'checkbox':
				showHideCheckboxOptions( elementOptionsWrapperID );
				break;				
			case 'text':
				showHideTextOptions( elementOptionsWrapperID );
				break;
			case 'firstlastname':
				showHideFirstLastNameOptions( elementOptionsWrapperID );
				break;
			case 'number':
				showHideNumberOptions( elementOptionsWrapperID );
				break;				
			case 'number':
				showHideNumberOptions( elementOptionsWrapperID );
				break;				
			case 'range':
				showHideRangeOptions( elementOptionsWrapperID );
				break;					
			case 'richeditor':
				showHideRichEditorOptions( elementOptionsWrapperID );
				break;
			case 'url':
				showHideUrlOptions( elementOptionsWrapperID );
				break;					
			case 'date':
				showHideDateOptions( elementOptionsWrapperID );
				break;					
			case 'time':
				showHideTimeOptions( elementOptionsWrapperID );
				break;					
			case 'datetime':
				showHideDatetimeOptions( elementOptionsWrapperID );
				break;					
			case 'tel':
				showHideTelOptions( elementOptionsWrapperID );
				break;					
			case 'textarea':
				showHideTextareaOptions( elementOptionsWrapperID );
				break;
			case 'address':
				showHideAddressOptions( elementOptionsWrapperID );
				break;
			case 'sectionhtml':
				showHideSectionHtmlOptions( elementOptionsWrapperID );
				break;
			case 'maskinput':
				showHideMaskInputOptions( elementOptionsWrapperID );
				break;
			case 'hidden':
				showHideHiddenOptions( elementOptionsWrapperID );
				break;
			case 'select':
				showHideSelectOptions( elementOptionsWrapperID );
				break;				
			case 'email':
				showHideEmailOptions( elementOptionsWrapperID );
				break;		
			case 'captcha':
				showHideCaptchaOptions( elementOptionsWrapperID );
				break;		
			case 'gcaptcha':
				showHideGoogleCaptchaOptions( elementOptionsWrapperID );
				break;
			case 'hcaptcha':
				showHideHCaptchaOptions( elementOptionsWrapperID );
				break;
			case 'upload':
				showHideUploadOptions( elementOptionsWrapperID );
				break;			
			case 'rating':
				showHideRatingOptions( elementOptionsWrapperID );
				break;
			case 'likert':
				showHideLikertOptions( elementOptionsWrapperID );
				break;
			case 'signature':
				showHideSignatureOptions( elementOptionsWrapperID );
				break;
			case 'pagebreak':
				showHidePageBreakOptions( elementOptionsWrapperID );
				break;
			case 'terms':
				showHideTermsOptions( elementOptionsWrapperID );
				break;
			case 'gdpr':
				showHideGdprOptions( elementOptionsWrapperID );
				break;
			case 'payment_item':
				showHidePaymentItemOptions( elementOptionsWrapperID );
				break;
			case 'payment_coupon':
				showHidePaymentCouponOptions( elementOptionsWrapperID );
				break;
			case 'payment_method':
				showHidePaymentMethodOptions( elementOptionsWrapperID );
				break;
			case 'payment_custom_amount':
				showHidePaymentCustomAmountOptions( elementOptionsWrapperID );
				break;
			case 'payment_quantity':
				showHidePaymentQuantityOptions( elementOptionsWrapperID );
				break;
			case 'payment_summary':
				showHidePaymentSummaryOptions( elementOptionsWrapperID );
				break;
			case 'stripe':
				showHideStripeOptions( elementOptionsWrapperID );
				break;
			case 'paypal':
				showHidePaypalOptions( elementOptionsWrapperID );
				break;
			case 'square':
				showHideSquareOptions( elementOptionsWrapperID );
				break;
			case 'authorizenet':
				showHideAuthorizeNetOptions( elementOptionsWrapperID );
				break;
		}
		// All: Common on click select dropped element
		setSelectedDroppedElementBackground(elementIndex);		
	});
	
	
	// All: Remove Dropped Input Element inside DropZone

	// $('body').on("click", ".wordform-element-delete", function() {
	// 	let confirmMsg	= confirm('Are you sure you want to delete this element?');
	// 	if ( confirmMsg ) {			
	// 		let elementIndex	= $(this).parent().prop("id").split("-")[1];
	// 		$('#wordformElementOptions-'+elementIndex).remove();
	// 		$(this).parent().remove();
	// 	}
	// });		
		
	$('body').on('click', '.wordform-element-delete', function(e) {
		e.preventDefault();

		var $trigger     = $(this);
		var $wrapper     = $trigger.closest('.wordform-input-element-div-wrapper');
		var elementIndex = $wrapper.prop('id').split('-').pop();

		// Highlight the wrapper
		$wrapper.addClass('highlight-delete');

		// Choose container: fullscreen wrapper (class) or body
		var $fullscreen  = $('.wordform-fullscreen-wrapper');
		var $container   = $fullscreen.length ? $fullscreen : $('body');

		// Remove any existing dialog
		$container.find('#wordform-delete-dialog').remove();

		// Build dialog and append to correct container
		var $dialog = $(
		'<div id="wordform-delete-dialog" title="Confirm Deletion">' +
			'<p>Are you sure you want to delete this element?</p>' +
		'</div>'
		).appendTo($container);

		// Compute position relative to the wrapper
		var off        = $wrapper.offset(),
			wrapH      = $wrapper.outerHeight(),
			winH       = $(window).height(),
			scrollTop  = $(window).scrollTop(),
			dlgH       = 120,  // approximate dialog height
			spaceBelow = scrollTop + winH - (off.top + wrapH + dlgH + 20);

		var positionOpt = spaceBelow >= 0
		? { my: 'center top',    at: 'center bottom+20', of: $wrapper }
		: { my: 'center bottom', at: 'center top-20',    of: $wrapper };

		// Initialize and open the dialog
		$dialog.dialog({
		modal:      true,
		resizable:  false,
		draggable:  false,
		width:      400,
		appendTo:   $container,
		position:   positionOpt,
		zIndex:     100000,
		dialogClass: 'wordform-admin-dialog',
		buttons: {
			Delete: function() {
			$('#wordformElementOptions-' + elementIndex).remove();
			$wrapper.remove();
			$(document).trigger('wordform:elementDeleted', { index: elementIndex });
			setTimeout(function() {
				syncWordformInitialSelectedElement('.wordform-input-element-div-wrapper-form-name');
			}, 0);
			$(this).dialog('close');
			},
			Cancel: function() {
			$(this).dialog('close');
			}
		},
		close: function() {
			$wrapper.removeClass('highlight-delete');
			$(this).remove();
		}
		});
	});


	
	/*** Text ***/

	$('body').on('input', '.wordform-text-label-name, .wordform-number-label-name, .wordform-textarea-label-name, .wordform-range-label-name, .wordform-url-label-name, .wordform-date-label-name, .wordform-time-label-name, .wordform-datetime-label-name, .wordform-tel-label-name, .wordform-email-label-name, .wordform-radio-label-name, .wordform-checkbox-label-name, .wordform-select-label-name, .wordform-upload-label-name, .wordform-rating-label-name, .wordform-likert-label-name, .wordform-signature-label-name, .wordform-terms-label-name, .wordform-payment-item-label-name, .wordform-payment-coupon-label-name, .wordform-payment-method-label-name, .wordform-payment-custom-amount-label-name, .wordform-payment-quantity-label-name, .wordform-payment-summary-label-name, .wordform-stripe-label-name, .wordform-paypal-label-name, .wordform-square-label-name, .wordform-authorizenet-label-name', function() {
		wordformSyncAdminLabelFromPublicLabel($(this));
	});

	$('body').on('input', '.wordform-firstname-label-name', function() {
		wordformSyncAdminLabelFromPublicLabel($(this), 'first');
	});

	$('body').on('input', '.wordform-lastname-label-name', function() {
		wordformSyncAdminLabelFromPublicLabel($(this), 'last');
	});
	
	// Text: Hide all text options wrapper - then show only the working one
	function showHideTextOptions( elementOptionsWrapperID ) {
		 $('.show-hide-common-class-all-options-wrapper-element').css('display', 'none');
		 $('.show-hide-common-class-all-options-wrapper-element').promise().done(function() {			 
			 $('#'+elementOptionsWrapperID).fadeIn();
		 }); 		
	}
	
	// Text: EditText Label Text
	$('body').on("input", ".wordform-text-label-name", function() {
		let labelName		= $(this).val();
		let elementIndex	= $(this).closest('.wordform-text-field-options-wrapper').prop("id").split("-")[1];														
		$('#wordformElement-'+elementIndex+' .wordform-dropped-text-label').html(labelName);		
	});

   // Text: EditText Placeholder Text
   $('body').on("input", ".wordform-text-placeholder-text-input", function() {
	   let placeholderText		= $(this).val();
	   let elementIndex	= $(this).closest('.wordform-text-field-options-wrapper').prop("id").split("-")[1];														
	   $('#wordformElement-'+elementIndex+' .wordform-dropped-text-name').attr("placeholder", placeholderText );		
   });

	/*** First Last Name ***/
	
	// First Last Name: Hide all firstlastname options wrapper - then show only the working one
	function showHideFirstLastNameOptions( elementOptionsWrapperID ) {
		 $('.show-hide-common-class-all-options-wrapper-element').css('display', 'none');
		 $('.show-hide-common-class-all-options-wrapper-element').promise().done(function() {			 
			 $('#'+elementOptionsWrapperID).fadeIn();
		 }); 		
	}
	
	// First Last Name: EditText Label First Name
	$('body').on("input", ".wordform-firstname-label-name", function() {
		let labelName		= $(this).val();
		let elementIndex	= $(this).closest('.wordform-firstlastname-field-options-wrapper').prop("id").split("-")[1];														
		$('#wordformElement-'+elementIndex+' .wordform-dropped-text-first-name-label').html(labelName);		
	});

	// First Last Name: EditText Label Last Name
	$('body').on("input", ".wordform-lastname-label-name", function() {
		let labelName		= $(this).val();
		let elementIndex	= $(this).closest('.wordform-firstlastname-field-options-wrapper').prop("id").split("-")[1];														
		$('#wordformElement-'+elementIndex+' .wordform-dropped-text-last-name-label').html(labelName);		
	});

   // First Last Name: EditText Placeholder First Name
   $('body').on("input", ".wordform-firstlastname-placeholder-firstname-input", function() {
	   let placeholderText		= $(this).val();
	   let elementIndex	= $(this).closest('.wordform-firstlastname-field-options-wrapper').prop("id").split("-")[1];														
	   $('#wordformElement-'+elementIndex+' .wordform-dropped-text-first-name').attr("placeholder", placeholderText );		
   });

   // First Last Name: EditText Placeholder Last Name      
   $('body').on("input", ".wordform-firstlastname-placeholder-lastname-input", function() {
	   let placeholderText		= $(this).val();
	   let elementIndex	= $(this).closest('.wordform-firstlastname-field-options-wrapper').prop("id").split("-")[1];														
	   $('#wordformElement-'+elementIndex+' .wordform-dropped-text-last-name').attr("placeholder", placeholderText );		
   });
   
   
	/*** Number ***/
	
	// Number: Hide all number options wrapper - then show only the working one
	function showHideNumberOptions( elementOptionsWrapperID ) {
		 $('.show-hide-common-class-all-options-wrapper-element').css('display', 'none');
		 $('.show-hide-common-class-all-options-wrapper-element').promise().done(function() {			 
			 $('#'+elementOptionsWrapperID).fadeIn();
		 }); 		
	}
	
	// Number: Edit Number Label Text
	$('body').on("input", ".wordform-number-label-name", function() {
		let labelName		= $(this).val();
		let elementIndex	= $(this).closest('.wordform-number-field-options-wrapper').prop("id").split("-")[1];														
		$('#wordformElement-'+elementIndex+' .wordform-dropped-number-label').html(labelName);		
	});

   // Number: EditText Placeholder Text
   $('body').on("input", ".wordform-number-placeholder-text-input", function() {
	   let placeholderText		= $(this).val();
	   let elementIndex	= $(this).closest('.wordform-number-field-options-wrapper').prop("id").split("-")[1];														
	   $('#wordformElement-'+elementIndex+' .wordform-dropped-number-name').attr("placeholder", placeholderText );		
   });

	
		
	
	/*** Textarea ***/

	// Textarea: Hide all textarea options wrapper - then show only the working one
	function showHideTextareaOptions( elementOptionsWrapperID ) {
		 $('.show-hide-common-class-all-options-wrapper-element').css('display', 'none');
		 $('.show-hide-common-class-all-options-wrapper-element').promise().done(function() {			 
			 $('#'+elementOptionsWrapperID).fadeIn();
		 }); 		
	}
	
	// Textarea: EdiText Label Text
	$('body').on("input", ".wordform-textarea-label-name", function() {
		let labelName		= $(this).val();
		let elementIndex	= $(this).closest('.wordform-textarea-field-options-wrapper').prop("id").split("-")[1];														
		$('#wordformElement-'+elementIndex+' .wordform-dropped-textarea-label').html(labelName);		
	});

   // Textarea: EditText Placeholder Text
   $('body').on("input", ".wordform-textarea-placeholder-text-input", function() {
	   let placeholderText		= $(this).val();
	   let elementIndex	= $(this).closest('.wordform-textarea-field-options-wrapper').prop("id").split("-")[1];														
	   $('#wordformElement-'+elementIndex+' .wordform-dropped-textarea-name').attr("placeholder", placeholderText );		
   });

	
	/*** Range ***/
	
	// Range: Hide all text options wrapper - then show only the working one
	function showHideRangeOptions( elementOptionsWrapperID ) {
		$('.show-hide-common-class-all-options-wrapper-element').css('display', 'none');
		$('.show-hide-common-class-all-options-wrapper-element').promise().done(function() {			 
			$('#'+elementOptionsWrapperID).fadeIn();
		}); 		
   }
   
   // Range: EditText Label Text
   $('body').on("input", ".wordform-range-label-name", function() {
	   let labelName		= $(this).val();
	   let elementIndex	= $(this).closest('.wordform-range-field-options-wrapper').prop("id").split("-")[1];														
	   $('#wordformElement-'+elementIndex+' .wordform-dropped-range-label').html(labelName);		
   });

	$('body').on("input change", ".wordform-range-min-value, .wordform-range-max-value, .wordform-range-default-value, .wordform-range-step-value", function() {
		const $wrapper = $(this).closest('.wordform-range-field-options-wrapper');
		const elementIndex = $wrapper.prop("id").split("-")[1];
		const $rangeInput = $('#wordformElement-' + elementIndex + ' .wordform-dropped-range-name');
		$rangeInput.attr('min', $wrapper.find('.wordform-range-min-value').val() || 0);
		$rangeInput.attr('max', $wrapper.find('.wordform-range-max-value').val() || 100);
		$rangeInput.attr('value', $wrapper.find('.wordform-range-default-value').val() || 50);
		$rangeInput.attr('step', $wrapper.find('.wordform-range-step-value').val() || 5);
	});


	/*** Url ***/
	
	// Url: Hide all text options wrapper - then show only the working one
	function showHideUrlOptions( elementOptionsWrapperID ) {
		$('.show-hide-common-class-all-options-wrapper-element').css('display', 'none');
		$('.show-hide-common-class-all-options-wrapper-element').promise().done(function() {			 
			$('#'+elementOptionsWrapperID).fadeIn();
		}); 		
    }
   
   // Url: EditText Label Text
   $('body').on("input", ".wordform-url-label-name", function() {
	   let labelName		= $(this).val();
	   let elementIndex	= $(this).closest('.wordform-url-field-options-wrapper').prop("id").split("-")[1];														
	   $('#wordformElement-'+elementIndex+' .wordform-dropped-url-label').html(labelName);		
   });

   // Url: EditText Placeholder Text
   $('body').on("input", ".wordform-url-placeholder-text-input", function() {
	   let placeholderText		= $(this).val();
	   let elementIndex	= $(this).closest('.wordform-url-field-options-wrapper').prop("id").split("-")[1];														
	   $('#wordformElement-'+elementIndex+' .wordform-dropped-url-name').attr("placeholder", placeholderText );		
   });

   
	/*** Date ***/
	
	// Date: Hide all text options wrapper - then show only the working one
	function showHideDateOptions( elementOptionsWrapperID ) {
		$('.show-hide-common-class-all-options-wrapper-element').css('display', 'none');
		$('.show-hide-common-class-all-options-wrapper-element').promise().done(function() {			 
			$('#'+elementOptionsWrapperID).fadeIn();
		}); 		
    }
   
	// Date: EditText Label Text
	$('body').on("input", ".wordform-date-label-name", function() {
		let labelName		= $(this).val();
		let elementIndex	= $(this).closest('.wordform-date-field-options-wrapper').prop("id").split("-")[1];														
		$('#wordformElement-'+elementIndex+' .wordform-dropped-date-label').html(labelName);		
	});

	// Date: EditText Placeholder Text
   $('body').on("input", ".wordform-date-placeholder-text-input", function() {
	   let placeholderText		= $(this).val();
	   let elementIndex	= $(this).closest('.wordform-date-field-options-wrapper').prop("id").split("-")[1];														
	   console.log('Element Index:' + elementIndex );
	   $('#wordformElement-'+elementIndex+' .wordform-dropped-date-name').attr("placeholder", placeholderText );		
   });

	function initWordformAdminDatePickerInput($input) {
		if (!$input || !$input.length) {
			return;
		}

		if ($input.hasClass('hasDatepicker')) {
			return;
		}

		$input.datepicker({
			dateFormat: 'yy-mm-dd',
			changeMonth: true,
			changeYear: true,
			onSelect: function(dateText) {
				$(this).val(dateText).trigger('input').trigger('change');
			},
			onClose: function(dateText) {
				if (dateText) {
					$(this).val(dateText).trigger('change');
				}
			}
		});
	}

	$('body').on('focus click', '.wordform-date-default-value, .wordform-date-min-date-value, .wordform-date-max-date-value', function() {
		const $input = $(this);
		initWordformAdminDatePickerInput($input);
		try { $input.datepicker('show'); } catch (e) {}
	});

	$('body').on('input change blur', '.wordform-date-default-value', function() {
		const $wrapper = $(this).closest('.wordform-date-field-options-wrapper');
		const elementIndex = $wrapper.prop("id").split("-")[1];
		const defaultDate = $(this).val();
		$wrapper.find('.wordform-date-hidden-raw-format-default-value').val(defaultDate);

		if ($wrapper.find('.date-default-value-show-checkbox').is(':checked')) {
			$('#wordformElement-'+elementIndex+' .wordform-dropped-date-name')
				.val(defaultDate)
				.attr('value', defaultDate)
				.attr('placeholder', defaultDate || 'Pick a date from calendar');
		}
	});

	/*** Time ***/

	function wordformGetTimeModeFormat(targetMode) {
		return String(targetMode) === '12h' ? 'hh:mm TT' : 'HH:mm';
	}

	function wordformFormatAdminTimeValue(rawValue, targetMode) {
		const normalizedRaw = normalizeSpaces(rawValue || '');
		if (!normalizedRaw.length) {
			return '';
		}

		try {
			const parsed = $.datepicker.parseTime('HH:mm', normalizedRaw);
			return $.datepicker.formatTime(
				wordformGetTimeModeFormat(targetMode),
				{ hour: parsed.hour ?? 0, minute: parsed.minute ?? 0, second: parsed.second ?? 0 },
				{ ampm: String(targetMode) === '12h' }
			);
		} catch (e) {
			return normalizedRaw;
		}
	}

	function wordformNormalizeAdminTimeRaw(value, targetMode) {
		const normalizedValue = normalizeSpaces(value || '');
		if (!normalizedValue.length) {
			return '';
		}

		const formatsToTry = [wordformGetTimeModeFormat(targetMode), 'HH:mm', 'hh:mm TT'];
		for (let i = 0; i < formatsToTry.length; i++) {
			try {
				const parsed = $.datepicker.parseTime(formatsToTry[i], normalizedValue);
				return ('0' + (parsed.hour ?? 0)).slice(-2) + ':' + ('0' + (parsed.minute ?? 0)).slice(-2);
			} catch (e) {}
		}

		return normalizedValue;
	}

	function wordformSyncTimePreview($wrapper) {
		if (!$wrapper || !$wrapper.length) {
			return;
		}

		const elementIndex = $wrapper.prop("id").split("-")[1];
		const targetMode = ($wrapper.find('.wordform-time-display-mode').val() === '12h') ? '12h' : '24h';
		const placeholderText = $wrapper.find('.wordform-time-placeholder-text-input').val() || 'Select time';
		const shouldShowPlaceholder = $wrapper.find('.time-placeholder-show-checkbox').is(':checked');
		const rawValue = normalizeSpaces($wrapper.find('.wordform-time-hidden-raw-default-value').val() || '');
		const visibleValue = wordformFormatAdminTimeValue(rawValue, targetMode);
		const $previewInput = $('#wordformElement-'+elementIndex+' .wordform-dropped-time-name');

		$previewInput
			.val(visibleValue)
			.attr('value', visibleValue)
			.attr('placeholder', visibleValue.length ? visibleValue : (shouldShowPlaceholder ? placeholderText : ''));
	}

	function initWordformAdminTimePickerInput($input) {
		if (!$input || !$input.length || typeof $input.timepicker !== 'function') {
			return;
		}

		const $wrapper = $input.closest('.wordform-time-field-options-wrapper');
		const timeFmt = wordformGetTimeModeFormat($wrapper.find('.wordform-time-display-mode').val() === '12h' ? '12h' : '24h');
		const opts = {
			controlType: 'select',
			oneLine: true,
			showSecond: false,
			stepMinute: 1,
			timeFormat: timeFmt,
			ampm: /t/i.test(timeFmt),
			onSelect: function(timeText) {
				$(this).val(timeText).trigger('input').trigger('change');
			},
			onClose: function(timeText) {
				if (typeof timeText !== 'undefined') {
					$(this).val(timeText).trigger('change');
				}
			}
		};

		if (!$input.hasClass('has-timepicker')) {
			$input.timepicker(opts);
			$input.addClass('has-timepicker');
			return;
		}

		$input.timepicker('option', opts);
	}

	function showHideTimeOptions( elementOptionsWrapperID ) {
		$('.show-hide-common-class-all-options-wrapper-element').css('display', 'none');
		$('.show-hide-common-class-all-options-wrapper-element').promise().done(function() {
			$('#'+elementOptionsWrapperID).fadeIn();
		});
	}

	$('body').on("input", ".wordform-time-label-name", function() {
		let labelName		= $(this).val();
		let elementIndex	= $(this).closest('.wordform-time-field-options-wrapper').prop("id").split("-")[1];
		$('#wordformElement-'+elementIndex+' .wordform-dropped-time-label').html(labelName || 'Time');
	});

	$('body').on("change", ".time-placeholder-show-checkbox", function() {
		let $wrapper		= $(this).closest('.wordform-time-field-options-wrapper');
		let elementIndex	= $wrapper.prop("id").split("-")[1];
		let placeholderText	= $wrapper.find('.wordform-time-placeholder-text-input').val() || 'Select time';
		const hasVisibleValue = normalizeSpaces($('#wordformElement-'+elementIndex+' .wordform-dropped-time-name').val() || '').length > 0;
		if (!hasVisibleValue) {
			$('#wordformElement-'+elementIndex+' .wordform-dropped-time-name').attr("placeholder", $(this).is(':checked') ? placeholderText : '');
		}
	});

	$('body').on("input", ".wordform-time-placeholder-text-input", function() {
		let placeholderText	= $(this).val();
		let $wrapper		= $(this).closest('.wordform-time-field-options-wrapper');
		let elementIndex	= $wrapper.prop("id").split("-")[1];
		let shouldShow		= $wrapper.find('.time-placeholder-show-checkbox').is(':checked');
		const hasVisibleValue = normalizeSpaces($('#wordformElement-'+elementIndex+' .wordform-dropped-time-name').val() || '').length > 0;
		if (!hasVisibleValue) {
			$('#wordformElement-'+elementIndex+' .wordform-dropped-time-name').attr("placeholder", shouldShow ? placeholderText : '');
		}
	});

	$('body').on("input change", ".wordform-time-default-value", function() {
		let $wrapper		= $(this).closest('.wordform-time-field-options-wrapper');
		let targetMode      = $wrapper.find('.wordform-time-display-mode').val() === '12h' ? '12h' : '24h';
		let rawTime         = wordformNormalizeAdminTimeRaw($(this).val(), targetMode);
		let visibleTime     = wordformFormatAdminTimeValue(rawTime, targetMode);
		$wrapper.find('.wordform-time-hidden-raw-default-value').val(rawTime);
		$(this).val(visibleTime).attr('value', visibleTime);
		wordformSyncTimePreview($wrapper);
	});

	$('body').on('change', '.wordform-time-display-mode', function() {
		const $wrapper = $(this).closest('.wordform-time-field-options-wrapper');
		const rawTime = normalizeSpaces($wrapper.find('.wordform-time-hidden-raw-default-value').val() || '');
		$wrapper.find('.wordform-time-default-value')
			.val(wordformFormatAdminTimeValue(rawTime, $(this).val()))
			.attr('value', wordformFormatAdminTimeValue(rawTime, $(this).val()));
		initWordformAdminTimePickerInput($wrapper.find('.wordform-time-default-value'));
		wordformSyncTimePreview($wrapper);
	});

	$('body').on('focus click', '.wordform-time-default-value', function() {
		const $input = $(this);
		initWordformAdminTimePickerInput($input);
		try { $input.timepicker('show'); } catch (e) {}
	});


	/*** Datetime ***/
	
	// Datetime: Hide all text options wrapper - then show only the working one
	function showHideDatetimeOptions( elementOptionsWrapperID ) {
		$('.show-hide-common-class-all-options-wrapper-element').css('display', 'none');
		$('.show-hide-common-class-all-options-wrapper-element').promise().done(function() {			 
			$('#'+elementOptionsWrapperID).fadeIn();
		}); 		
	}
   
	// Datetime: EditText Label Text
	$('body').on("input", ".wordform-datetime-label-name", function() {
		let labelName		= $(this).val();
		let elementIndex	= $(this).closest('.wordform-datetime-field-options-wrapper').prop("id").split("-")[1];														
		$('#wordformElement-'+elementIndex+' .wordform-dropped-datetime-label').html(labelName);		
	});
	


		/**
		 * Datetime: WordForm Pro — Datetime Field System
		 * - Wrapper: .wordform-datetime-field-options-wrapper
		 * - Preview parent: #wordformElement-{index}
		 * - jQuery UI Timepicker Addon required
		 */

		/* ------------------------------
		* 1) Helpers: normalization
		* ----------------------------*/

		/** Normalize whitespace (incl. NBSP) and collapse multiples */
		function normalizeSpaces(str) {
		return String(str || '').replace(/\u00A0/g, ' ').replace(/\s+/g, ' ').trim();
		}

		/** True if a time format is 12-hour (AM/PM) */
		function is12hFormat(timeFmt) {
		// If the time part contains t/tt/TT, treat as 12h
		return /t/i.test(timeFmt);
		}

		// Very loose date-format validator: only tokens ymdMD and separators (space, comma, dot, slash, dash)
		function isLikelyValidDateFmt(fmt) {
			const f = normalizeSpaces(fmt);
			if (!f) return false;
			// allow letters y m d M and separators , . / - space
			if (!/^[ymdM,\.\-\/\s]+$/.test(f)) return false;
			// require at least one year, one month (m or M), and one day
			if (!/[y]/i.test(f)) return false;
			if (!/[mM]/.test(f)) return false;
			if (!/[d]/i.test(f)) return false;
			return true;
		}

		// Very loose time-format validator: allow H/h, mm, optional :ss, optional AM/PM
		function isLikelyValidTimeFmt(fmt) {
			const f = normalizeSpaces(fmt);
			if (!f) return false;
			// Must contain H or h and "mm"
			if (!/[Hh]/.test(f)) return false;
			if (!/m{2}/.test(f)) return false;
			// Basic token check (allow :, space, and TT/tt)
			if (!/^[Hh:\smTt]+$/.test(f)) return false;
			return true;
		}

		/**
		 * Split a combined format like "mm/dd/yy hh:mm TT" into date & time parts.
		 * This version is permissive and does NOT force fallback if tokens are valid-looking.
		 */
		function splitCombinedFormat(combined) {
		const normalized = normalizeSpaces(combined);

		// Time pattern AT THE END: H/h + :mm (optional :ss) and optional AM/PM
		const timePatternAtEnd = /([Hh]{1,2}:[m]{2}(?::[s]{2})?(?:\s?[Tt]{1,2})?)$/;
		const match = normalized.match(timePatternAtEnd);

		let dateFmt = normalized, timeFmt = 'HH:mm';
		if (match) {
			timeFmt = match[1].trim();
			dateFmt = normalized.slice(0, match.index).trim().replace(/,$/, ''); // drop trailing comma
		}

		// keep user intent unless truly malformed
		const dateOk = /y/i.test(dateFmt) && /d/i.test(dateFmt) && /[mM]/.test(dateFmt);
		const timeOk = /[Hh]/.test(timeFmt) && /m{2}/.test(timeFmt);

		if (!dateOk) dateFmt = 'yy-mm-dd';
		if (!timeOk) timeFmt = 'HH:mm';

		return { dateFmt, timeFmt };
		}



		/** Get the active combined format and parse the field's current value into a Date() */
		function getDateFromField($input) {
		const combined = $input.attr('data-datetime-format') || 'yy-mm-dd HH:mm';
		const { dateFmt, timeFmt } = splitCombinedFormat(combined);
		const raw = normalizeSpaces($input.attr('data-datetime-value') || $input.val() || '');
		return parseDateTime(dateFmt, timeFmt, raw) || new Date();
		}

		/**
		 * Seed the datetimepicker UI with the field's current value so the hour/minute
		 * selects reflect the actual selection. Also normalizes the text in the input.
		 */
		function seedPickerFromCurrent($input) {
		try {
			const combined = $input.attr('data-datetime-format') || 'yy-mm-dd HH:mm';
			const { dateFmt, timeFmt } = splitCombinedFormat(combined);

			const dateObj = getDateFromField($input);

			// 1) Set the widget date (includes time)
			$input.datetimepicker('setDate', dateObj);

			// 2) Sync the internal timepicker UI (hour/min dropdowns)
			const inst = $input.data('datetimepicker') || $input.data('datepicker');
			if (inst && inst.timepicker) {
			const tp = inst.timepicker;
			if (typeof tp._setTime === 'function') {
				tp._setTime(dateObj);
			} else {
				tp.hour   = dateObj.getHours();
				tp.minute = dateObj.getMinutes();
				tp.second = dateObj.getSeconds();
				tp._onTimeChange();
			}
			tp._updateTimepicker();
			}

			// 3) Normalize field text to the active format (keeps UI + text consistent)
			const normalizedText = formatDateTime(dateFmt, timeFmt, dateObj);
			if (normalizedText) {
			$input.val(normalizedText).attr('data-datetime-value', normalizedText);
			}
		} catch (e) {
			// OK to ignore
		}
		}



	/* ------------------------------
	* 2) Parsing & formatting
	* ----------------------------*/
	/**
	 * Parse a user-visible datetime string into a Date() using the active formats.
	 * Robust time extraction (doesn't confuse AM/PM as part of the date).
	 */
	function parseDateTime(dateFmt, timeFmt, text) {
		const txt = normalizeSpaces(text);
		if (!txt) return null;

		// Time at the END (HH:mm[:ss][ AM/PM]) so date part stays clean
		const timeAtEnd = /([01]?\d|2[0-3]):[0-5]\d(?::[0-5]\d)?(?:\s?[APap][Mm])?$/;
		const m = txt.match(timeAtEnd);

		let dateText = txt, timeText = '';
		if (m) {
			timeText = m[0].trim();
			dateText = txt.slice(0, m.index).trim();
			if (dateText.endsWith(',')) dateText = dateText.slice(0, -1).trim(); // e.g., "Oct 13, 2025"
		}

		// Parse date
		let dateObj;
		try {
			dateObj = $.datepicker.parseDate(dateFmt, dateText);
		} catch (e) {
			return null;
		}

		// Parse time
		let hour = 0, minute = 0, second = 0;
		if (timeText) {
			try {
			const t = $.datepicker.parseTime(timeFmt, timeText);
			hour = t.hour ?? 0;
			minute = t.minute ?? 0;
			second = t.second ?? 0;
			} catch (e) {
			// keep 00:00 if time couldn't be parsed
			}
		}

		return new Date(
			dateObj.getFullYear(),
			dateObj.getMonth(),
			dateObj.getDate(),
			hour, minute, second
		);
	}


	function formatDateTime(dateFmt, timeFmt, dateObj) {
		if (!dateObj || isNaN(dateObj.getTime())) return '';
		const dateStr = $.datepicker.formatDate(dateFmt, dateObj);
		const timeStr = $.datepicker.formatTime(
		timeFmt,
		{ hour: dateObj.getHours(), minute: dateObj.getMinutes(), second: dateObj.getSeconds() },
		{ ampm: is12hFormat(timeFmt) } // <-- critical for AM/PM
		);
		return (dateStr + ' ' + timeStr).trim();
	}

		function exampleFromFormat(combinedFmt) {
		const { dateFmt, timeFmt } = splitCombinedFormat(combinedFmt);
		return formatDateTime(dateFmt, timeFmt, new Date()) || combinedFmt;
		}

		function wordformInferTimeDisplayMode(combinedFmt) {
		const parts = splitCombinedFormat(combinedFmt || '');
		return is12hFormat(parts.timeFmt) ? '12h' : '24h';
		}

		function wordformConvertCombinedFormatTimeMode(combinedFmt, targetMode) {
		const safeCombined = normalizeSpaces(combinedFmt || 'yy-mm-dd HH:mm');
		const parts = splitCombinedFormat(safeCombined);
		const dateFmt = parts.dateFmt || 'yy-mm-dd';
		const nextTimeFmt = String(targetMode) === '12h' ? 'hh:mm TT' : 'HH:mm';
		return (dateFmt + ' ' + nextTimeFmt).trim();
		}

		const wordformDateTimeDateLayoutOptions = [
			{ dateFmt: 'yy-mm-dd', label: 'YYYY-MM-DD' },
			{ dateFmt: 'yy/mm/dd', label: 'YYYY/MM/DD' },
			{ dateFmt: 'dd/mm/yy', label: 'DD/MM/YYYY' },
			{ dateFmt: 'mm/dd/yy', label: 'MM/DD/YYYY' },
			{ dateFmt: 'dd-mm-yy', label: 'DD-MM-YYYY' },
			{ dateFmt: 'dd.mm.yy', label: 'DD.MM.YYYY' },
			{ dateFmt: 'yy.mm.dd', label: 'YYYY.MM.DD' },
			{ dateFmt: 'M d, yy', label: 'Mon D, YYYY' },
			{ dateFmt: 'MM d, yy', label: 'Month D, YYYY' },
			{ dateFmt: 'd M yy', label: 'D Mon YYYY' },
			{ dateFmt: 'd MM yy', label: 'D Month YYYY' },
			{ dateFmt: 'yy M d', label: 'YYYY Mon D' },
			{ dateFmt: 'yy MM d', label: 'YYYY Month D' }
		];

		function wordformGetTimeModeMeta(targetMode) {
			return String(targetMode) === '12h'
				? { timeFmt: 'hh:mm TT', labelSuffix: ' hh:mm AM/PM (12h)' }
				: { timeFmt: 'HH:mm', labelSuffix: ' HH:mm (24h)' };
		}

		function wordformBuildDateTimeLayoutOptions(targetMode) {
			const meta = wordformGetTimeModeMeta(targetMode);
			return wordformDateTimeDateLayoutOptions.map(function(option) {
				return {
					value: normalizeSpaces(option.dateFmt + ' ' + meta.timeFmt),
					label: option.label + meta.labelSuffix
				};
			});
		}

		function wordformRefreshDateTimeFormatOptions($select, targetMode, selectedCombined) {
			if (!$select || !$select.length) {
				return normalizeSpaces(selectedCombined || '');
			}

			const safeMode = String(targetMode) === '12h' ? '12h' : '24h';
			const currentCombined = normalizeSpaces(selectedCombined || $select.val() || 'yy-mm-dd HH:mm');
			const currentParts = splitCombinedFormat(currentCombined);
			const desiredValue = normalizeSpaces(wordformConvertCombinedFormatTimeMode(currentCombined, safeMode));
			const options = wordformBuildDateTimeLayoutOptions(safeMode);
			let resolvedValue = '';

			$select.empty();

			options.forEach(function(option, index) {
				const shouldSelect = option.value === desiredValue || (!resolvedValue && option.value === normalizeSpaces(currentParts.dateFmt + ' ' + wordformGetTimeModeMeta(safeMode).timeFmt));
				const $option = $('<option></option>').val(option.value).text(option.label);
				if (shouldSelect || (!resolvedValue && index === 0 && !desiredValue.length)) {
					$option.prop('selected', true).attr('selected', 'selected');
					resolvedValue = option.value;
				}
				$select.append($option);
			});

			if (!resolvedValue && options.length) {
				resolvedValue = options[0].value;
				$select.find('option').first().prop('selected', true).attr('selected', 'selected');
			}

			if (resolvedValue) {
				$select.val(resolvedValue);
			}

			return resolvedValue;
		}

	/* ------------------------------
	* 3) Picker init/update
	* ----------------------------*/

	/**
	 * Initialize or update the jQuery UI DateTimePicker widget.
	 * - Rebuilds the widget when switching 12h <-> 24h so hours list is correct.
	 * - Preserves the current selected time (e.g., 07:24) in the dropdowns.
	 * - Uses stepMinute: 1 for accurate minute selection.
	 */
	function ensurePicker($input, dateFmt, timeFmt) {
	const ampmNew  = is12hFormat(timeFmt);
	const ampmPrev = $input.data('wfAmpm');

	// Prevent re-entrancy during beforeShow
	let insideBeforeShow = false;

	const opts = {
		controlType: 'select',
		oneLine: true,
		showSecond: false,
		stepMinute: 1,
		dateFormat: dateFmt,
		timeFormat: timeFmt,
		ampm: ampmNew,

		// Seed right before opening (ensures lists + selection are correct)
		beforeShow: function () {
		if (insideBeforeShow) return;
		insideBeforeShow = true;
		try {
			$input.datetimepicker('option', { dateFormat: dateFmt, timeFormat: timeFmt, ampm: ampmNew });
			seedPickerFromCurrent($input);
		} catch (e) {}
		insideBeforeShow = false;
		},

		// When user picks (date or time), always reformat and sync
		onSelect: function () {
		if ($input.data('wordformSyncingDatetimePreview')) return;
		const d = $input.datetimepicker('getDate');
		if (!d) return;
		const txt = formatDateTime(dateFmt, timeFmt, d);
		const scope = getScopeFromChild($input);
		if (scope) {
			scope.$wrapper.find('.datetime-default-value-show-radio').prop('checked', false).attr('checked', false);
			scope.$wrapper.find('.datetime-default-value-show-radio[value="setDateTime"]').prop('checked', true).attr('checked', true);
		}
		$input.val(txt).attr('data-datetime-value', txt);
		// push to preview/builder
		syncToPreviewFromBuilder($input, txt);
		},

		onClose: function () {
		if ($input.data('wordformSyncingDatetimePreview')) return;
		const d = $input.datetimepicker('getDate');
		if (!d) return;
		const txt = formatDateTime(dateFmt, timeFmt, d);
		const scope = getScopeFromChild($input);
		if (scope) {
			scope.$wrapper.find('.datetime-default-value-show-radio').prop('checked', false).attr('checked', false);
			scope.$wrapper.find('.datetime-default-value-show-radio[value="setDateTime"]').prop('checked', true).attr('checked', true);
		}
		$input.val(txt).attr('data-datetime-value', txt);
		syncToPreviewFromBuilder($input, txt);
		}
	};

	// 1) First-time init
	if (!$input.hasClass('has-datetimepicker')) {
		$input.datetimepicker(opts);
		$input.addClass('has-datetimepicker');
		$input.data('wfAmpm', ampmNew);
		// Seed once so field shows exactly what picker will use
		seedPickerFromCurrent($input);
		return;
	}

	// 2) Mode changed (12h <-> 24h): hard rebuild to refresh hour list
	if (ampmPrev !== ampmNew) {
		const preserved = getDateFromField($input);
		try { $input.datetimepicker('destroy'); } catch (e) {}
		$input.removeClass('has-datetimepicker');
		$input.datetimepicker(opts);
		$input.addClass('has-datetimepicker');
		$input.data('wfAmpm', ampmNew);
		$input.datetimepicker('setDate', preserved);
		seedPickerFromCurrent($input);
		return;
	}

	// 3) Same mode: soft update + reseed
	$input.datetimepicker('option', opts);
	$input.data('wfAmpm', ampmNew);
	seedPickerFromCurrent($input);
	}


	/* ------------------------------
	* 4) Scoping to the right element
	* ----------------------------*/

	function getScopeFromChild($child) {
		const $wrapper = $child.closest('.wordform-datetime-field-options-wrapper');
		if (!$wrapper.length) return null;

		// ID like: wordform-datetime-field-options-wrapper-3 → index = 3
		const wrapperId = $wrapper.prop('id') || '';
		const parts = wrapperId.split('-');
		const elementIndex = parts[parts.length - 1];
		if (!elementIndex) return null;

		const $element = $('#wordformElement-' + elementIndex);
		if (!$element.length) return null;

		return {
		elementIndex,
		$wrapper,
		$element,
		$builderInput: $wrapper.find('.wordform-datetime-default-value'),
		$datetimeHiddenInput: $wrapper.find('.wordform-datetime-hidden-raw-format-default-value'),
		$previewInput: $element.find('.wordform-dropped-datetime-name'),
		$formatSelect: $wrapper.find('.wordform-default-datetime-display-format'),
		$timeModeSelect: $wrapper.find('.wordform-datetime-time-display-mode')
		};
	}

	/* ------------------------------
	* 5) Sync logic (builder ↔ preview)
	* ----------------------------*/

	function syncPreview($scope, text) {
		const fmt = normalizeSpaces($scope.$builderInput.attr('data-datetime-format') || 'yy-mm-dd HH:mm');
		$scope.$builderInput.attr('data-wordform-custom-default-datetime', text);
		$scope.$builderInput.attr('data-datetime-value', text);
		$scope.$datetimeHiddenInput.val(text);
		const example = exampleFromFormat(fmt);
		$scope.$builderInput.attr('placeholder', example);
		$scope.$previewInput.attr('placeholder', example);
		wordformSyncDatetimePreviewByMode($scope);
	}

	function wordformApplyDatetimeVisibleValue($input, visibleValue, combined) {
		if (!$input || !$input.length) {
			return;
		}

		const normalizedVisibleValue = normalizeSpaces(visibleValue || '');
		$input.val(normalizedVisibleValue)
			.attr('value', normalizedVisibleValue)
			.attr('data-datetime-value', normalizedVisibleValue);
	}

	function wordformGetAdminSiteCurrentDateTime() {
		const raw = normalizeSpaces((window.sc_wordform_metabox_script_obj && sc_wordform_metabox_script_obj.wordform_current_site_datetime) || '');
		if (!raw.length) {
			return new Date();
		}

		return parseDateTime('yy-mm-dd', 'HH:mm', raw) || new Date();
	}

	function wordformSyncDatetimePreviewByMode($scope) {
		if (!$scope || !$scope.$previewInput || !$scope.$previewInput.length || !$scope.$builderInput || !$scope.$builderInput.length) {
			return;
		}

		const combined = normalizeSpaces($scope.$builderInput.attr('data-datetime-format') || 'yy-mm-dd HH:mm');
		const parts = splitCombinedFormat(combined);
		const selectedMode = $scope.$wrapper.find('.datetime-default-value-show-radio:checked').val() || 'none';
		const placeholderShow = $scope.$wrapper.find('.datetime-placeholder-show-checkbox').is(':checked');
		const placeholderText = normalizeSpaces($scope.$wrapper.find('.wordform-datetime-placeholder-text-input').val() || 'Select date & time');
		const placeholder = (selectedMode === 'none' && placeholderShow) ? placeholderText : exampleFromFormat(combined);
		let visibleValue = '';

		if (selectedMode === 'currentDateTime') {
			visibleValue = formatDateTime(parts.dateFmt, parts.timeFmt, wordformGetAdminSiteCurrentDateTime());
		} else if (selectedMode === 'setDateTime') {
			const savedValue = normalizeSpaces(
				$scope.$builderInput.attr('data-wordform-custom-default-datetime')
				|| $scope.$datetimeHiddenInput.val()
				|| $scope.$builderInput.attr('data-datetime-value')
				|| $scope.$builderInput.val()
				|| ''
			);
			const dateObj = parseDateTime(parts.dateFmt, parts.timeFmt, savedValue) || parseDateTime('yy-mm-dd', 'HH:mm', savedValue);
			visibleValue = dateObj ? formatDateTime(parts.dateFmt, parts.timeFmt, dateObj) : '';
		}

		wordformApplyDatetimeVisibleValue($scope.$builderInput, visibleValue, combined);
		$scope.$builderInput.attr('placeholder', placeholder);
		$scope.$previewInput.val(visibleValue).attr('data-datetime-value', visibleValue).attr('placeholder', placeholder);
		if (visibleValue.length) {
			$scope.$builderInput.attr('value', visibleValue);
			$scope.$previewInput.attr('value', visibleValue);
		} else {
			$scope.$builderInput.attr('value', '');
			$scope.$previewInput.attr('value', '');
		}
	}

	function syncToPreviewFromBuilder($builderInput, dtText) {
		const scope = getScopeFromChild($builderInput);
		if (!scope) return;
		syncPreview(scope, dtText);
	}

	function applyFormatChange($scope, combinedFmt) {
		const safeCombined = normalizeSpaces(combinedFmt);
		const { dateFmt, timeFmt } = splitCombinedFormat(safeCombined);

		// 1) Persist combined format on both inputs
		$scope.$builderInput.attr('data-datetime-format', `${dateFmt} ${timeFmt}`);
		$scope.$previewInput.attr('data-datetime-format', `${dateFmt} ${timeFmt}`);

		// 2) Update picker options (also flips AM/PM)
		ensurePicker($scope.$builderInput, dateFmt, timeFmt);

		// 3) Re-parse current displayed value using PREV format first, then reformat into NEW format
		const prevCombined = normalizeSpaces($scope.$builderInput.attr('data-datetime-format-prev') || 'yy-mm-dd HH:mm');
		const prevParts = splitCombinedFormat(prevCombined);
		const currentText = normalizeSpaces($scope.$builderInput.attr('data-datetime-value') || $scope.$builderInput.val() || '');

		let dateObj = parseDateTime(prevParts.dateFmt, prevParts.timeFmt, currentText)
				|| parseDateTime(dateFmt, timeFmt, currentText);

		const newText = dateObj ? formatDateTime(dateFmt, timeFmt, dateObj) : '';
		$scope.$builderInput.attr('data-datetime-format-prev', `${dateFmt} ${timeFmt}`);

		// 4) Push to both inputs immediately
		syncPreview($scope, newText);
	}

	// When user changes the DateTime dropdown display format
	$('body').on('change', '.wordform-default-datetime-display-format', function () {
		const scope = getScopeFromChild($(this));
		if (!scope) return;

		const chosen = normalizeSpaces($(this).val() || 'yy-mm-dd HH:mm');
		const { dateFmt, timeFmt } = splitCombinedFormat(chosen);

		$(this).find('option').removeAttr('selected').prop('selected', false);
		$(this).find('option').filter(function() {
			return normalizeSpaces($(this).val()) === chosen;
		}).first().attr('selected', 'selected').prop('selected', true);

		applyFormatChange(scope, `${dateFmt} ${timeFmt}`);
		if (scope.$timeModeSelect.length) {
			scope.$timeModeSelect.val(wordformInferTimeDisplayMode(`${dateFmt} ${timeFmt}`));
		}
	});

	$('body').on('change', '.wordform-datetime-time-display-mode', function () {
		const scope = getScopeFromChild($(this));
		if (!scope) return;

		const targetMode = $(this).val() === '12h' ? '12h' : '24h';
		const currentCombined = normalizeSpaces(scope.$builderInput.attr('data-datetime-format') || scope.$formatSelect.val() || 'yy-mm-dd HH:mm');
		const nextCombined = wordformRefreshDateTimeFormatOptions(scope.$formatSelect, targetMode, currentCombined) || wordformConvertCombinedFormatTimeMode(currentCombined, targetMode);
		scope.$timeModeSelect.val(targetMode);
		applyFormatChange(scope, nextCombined);
	});


	// Builder input: manual edit or programmatic update
	$('body').on('change blur input', '.wordform-datetime-default-value', function (event) {
	const scope = getScopeFromChild($(this));
	if (!scope) return;

	const combined = normalizeSpaces(scope.$builderInput.attr('data-datetime-format') || 'yy-mm-dd HH:mm');
	const { dateFmt, timeFmt } = splitCombinedFormat(combined);

	const typed = normalizeSpaces(scope.$builderInput.val());
	const dateObj = parseDateTime(dateFmt, timeFmt, typed);
	const normalized = dateObj ? formatDateTime(dateFmt, timeFmt, dateObj) : typed;

	if (normalized.length && !wordformBuilderReconstructionInProgress && event && event.originalEvent) {
		scope.$wrapper.find('.datetime-default-value-show-radio').prop('checked', false).attr('checked', false);
		scope.$wrapper.find('.datetime-default-value-show-radio[value="setDateTime"]').prop('checked', true).attr('checked', true);
	}

	// put back normalized (so picker + text match) and sync preview
	scope.$builderInput.val(normalized).attr('data-datetime-value', normalized);
	syncPreview(scope, normalized);
	});

	/* ------------------------------
	* 7) Initialization (existing + dynamic)
	* ----------------------------*/

	function initWrapper($wrapper) {
		const scope = getScopeFromChild($wrapper);
		if (!scope) return;

		const initialCombined = normalizeSpaces(scope.$formatSelect.val() || 'yy-mm-dd HH:mm');
		const initialMode = wordformInferTimeDisplayMode(initialCombined);
		const normalizedCombined = wordformRefreshDateTimeFormatOptions(scope.$formatSelect, initialMode, initialCombined) || 'yy-mm-dd HH:mm';
		const { dateFmt, timeFmt } = splitCombinedFormat(normalizedCombined);
		if (scope.$timeModeSelect.length) {
			scope.$timeModeSelect.val(initialMode);
		}

		// persist both combined and previous formats
		scope.$builderInput
		.attr('data-datetime-format', `${dateFmt} ${timeFmt}`)
		.attr('data-datetime-format-prev', `${dateFmt} ${timeFmt}`);
		scope.$previewInput.attr('data-datetime-format', `${dateFmt} ${timeFmt}`);

		// init widget
		ensurePicker(scope.$builderInput, dateFmt, timeFmt);

		// show example placeholders
		const example = exampleFromFormat(`${dateFmt} ${timeFmt}`);
		scope.$builderInput.attr('placeholder', example);
		scope.$previewInput.attr('placeholder', example);

		// normalize any saved value into current format
		const saved = normalizeSpaces(scope.$builderInput.attr('data-datetime-value') || scope.$builderInput.val() || '');
		if (saved) {
		const dateObj = parseDateTime(dateFmt, timeFmt, saved)
					|| parseDateTime('yy-mm-dd', 'HH:mm', saved); // safe fallback
		const normalized = dateObj ? formatDateTime(dateFmt, timeFmt, dateObj) : saved;
		syncPreview(scope, normalized);
		} else {
			wordformSyncDatetimePreviewByMode(scope);
		}
	}

	// Init present wrappers
	$('.wordform-datetime-field-options-wrapper').each(function () { initWrapper($(this)); });

	// Init dynamically added wrappers
	const observer = new MutationObserver((mutations) => {
		mutations.forEach(m => {
		m.addedNodes.forEach(node => {
			const $n = $(node);
			if ($n.hasClass('wordform-datetime-field-options-wrapper')) {
			initWrapper($n);
			}
			$n.find('.wordform-datetime-field-options-wrapper').each(function () {
			initWrapper($(this));
			});
		});
		});
	});
	const target = document.querySelector('#wordformBuilderArea') || document.body;
	if (target) observer.observe(target, { childList: true, subtree: true });


	// Datetime: On check DateTime Default Radio Options - Handle datetime default-value radio changes	
	$('body').on('change', '.datetime-default-value-show-radio', function () {
		// Find the current options wrapper
		const $wrapper = $(this).closest('.wordform-datetime-field-options-wrapper');

		// Uncheck all radios within this wrapper
		$wrapper.find('.datetime-default-value-show-radio')
		.prop('checked', false)       // update visual/DOM state
		.attr('checked', false);      // sync HTML attribute

		// Check only the clicked radio
		$(this)
		.prop('checked', true)        // update visual/DOM state
		.attr('checked', true);       // sync HTML attribute

		const scope = getScopeFromChild($wrapper);
		if (scope) {
			wordformSyncDatetimePreviewByMode(scope);
		}
	});



	/*** Tel ***/
	
	// Tel: Hide all text options wrapper - then show only the working one
	function showHideTelOptions( elementOptionsWrapperID ) {
		$('.show-hide-common-class-all-options-wrapper-element').css('display', 'none');
		$('.show-hide-common-class-all-options-wrapper-element').promise().done(function() {			 
			$('#'+elementOptionsWrapperID).fadeIn();
		}); 		
   }
   
   // Tel: EditText Label Text
   $('body').on("input", ".wordform-tel-label-name", function() {
	   let labelName		= $(this).val();
	   let elementIndex	= $(this).closest('.wordform-tel-field-options-wrapper').prop("id").split("-")[1];														
	   $('#wordformElement-'+elementIndex+' .wordform-dropped-tel-label').html(labelName);		
   });

   // Tel: EditText Placeholder Text
   $('body').on("input", ".wordform-tel-placeholder-text-input", function() {
	   let placeholderText		= $(this).val();
	   let elementIndex	= $(this).closest('.wordform-tel-field-options-wrapper').prop("id").split("-")[1];														
	   $('#wordformElement-'+elementIndex+' .wordform-dropped-tel-name').attr("placeholder", placeholderText );		
   });

   // Tel: Get Regex Pattern value immediately when a radio button in Pattern list is selected        
	$('body').on( "change", 'input[name="phonePattern"]', function() {			
		// Remove 'checked' attribute from all radios in the same group
		$('input[name="phonePattern"]').attr('checked', false);			

		const selectedPatternDisplayInputElement = $('.wordform-input-tel-selected-pattern-regex-value');
		const selectedPatternExampleHintsInputElement = $('.wordform-input-tel-selected-pattern-regex-example-phone-numbers');
        const selectedPatternValue = $(this).val();			
		const selectedPatternHintsNumbers = $(this).parent().find('em').text();			
		// console.log('Ex Numbers: ' + selectedPatternHintsNumbers );
		// console.log(selectedPatternValue);

		// Assign selected Regex Pattern into Selected Pattern Input Field Value
		selectedPatternDisplayInputElement.attr("value", selectedPatternValue );            
		// Assign selected Regex Pattern Example numbers into Selected Pattern example number Input Field Value
		selectedPatternExampleHintsInputElement.attr("value", selectedPatternHintsNumbers );
		 // Set 'checked' attribute on the currently selected radio
    	$(this).attr('checked', true);
    }); 
	
	// Tel: On Change Tel Min & Max Length Value
	// $('body').on("change", '.wordform-tel-min-length, .wordform-tel-max-length', function() {
	// 	const changedValue = $(this).val();
	// 	const droppedTelName  = $('.wordform-dropped-tel-name');
	// 	const TellengthFieldName = $(this).data("tel-length-field");
	// 	console.log( TellengthFieldName );
	// 	if ( TellengthFieldName == 'min' ) {
	// 		droppedTelName.attr("minlength", changedValue );	
	// 	}
	// 	else if ( TellengthFieldName == 'max' ) {
	// 		droppedTelName.attr("maxlength", changedValue );	
	// 	}
	// 	else {
	// 		console.log('Something went wrong.');
	// 	}
	// });

	
	/*** Radio ***/
	
	// Radio: Hide Radio element options wrapper - then show only the working one
	function showHideRadioOptions( elementOptionsWrapperID ) {
		 $('.show-hide-common-class-all-options-wrapper-element').css('display', 'none');
		 $('.show-hide-common-class-all-options-wrapper-element').promise().done(function() {			 
			 $('#'+elementOptionsWrapperID).fadeIn();
		 }); 		
	}
			
	// Radio: Add more Radio Option
	$('body').on("click", ".wordform-add-radio-option", function() {
		let elementIndex	= $(this).closest('.wordform-radio-field-options-wrapper').prop("id").split("-")[1];												
		
		// Add to field options
		$(this).parent().prev().after('<li> <input class="wordform-edit-radio-name" name="wordform-edit-radio-name-'+elementIndex+'" type="radio" /><input class="wordform-input-radio-label-name" type="text" placeholder="Option Text" /> <span class="wordform-radio-field-remove dashicons dashicons-no" title="Remove"></span> </li> ');
				
		// Add to dropped zone element		
		$('#wordformElement-'+elementIndex+ ' .wordform-dropped-element-radio-field-options').append('<li><input class="wordform-dropped-radio-name" name="wordform-dropped-radio-name-'+elementIndex+'" type="radio" disabled="disabled" /><span>Option Text</span> </li>');		
	});
	
	// Radio: On change/ Edit update radio options label text
	$('body').on("input", ".wordform-input-radio-label-name", function() {
		let elementIndex	= $(this).closest('.wordform-radio-field-options-wrapper').prop("id").split("-")[1];				
		let liElementnth	= $(this).parent().index();
		let labelName		= $(this).val();		
		//$('.wordform-dropped-element-radio-field-options li:eq('+liElementnth+') span').html(labelName);
		$('#wordformElement-'+elementIndex+' li:eq('+liElementnth+') span').html(labelName);
	});
	
	// Radio: Remove Radio Option Field
	$('body').on("click", ".wordform-radio-field-remove", function() {
		let parentULLength		= $(this).closest('.wordform-field-options').find('li').length;		
		if ( parentULLength == 2 ) {
			alert('Minimum 1 Option Required!');
		}
		else {		
			let liElementnth	= $(this).parent().index();		
			$('.wordform-dropped-element-radio-field-options li:eq('+liElementnth+')').remove();
			$(this).parent().remove();
		}
	})
	
	// Radio: Click/Select radio box
	$('body').on("click", ".wordform-edit-radio-name", function() {
		let liElementnth	= $(this).parent().index();
		let elementIndex	= $(this).closest('.wordform-radio-field-options-wrapper').prop("id").split("-")[1];
		
		// Find Radio group name by name attribute
		let editOptionsGroupName		= $(this).prop('name');
		let droppedElementGroupName		= $('#wordformElement-'+elementIndex+' .wordform-dropped-element-radio-field-options li input').prop('name');				
		// Element options
		$('input[name="'+ editOptionsGroupName +'"]').each(function(index, elem ) {			
			if ( $(this).is(":checked") ) {
				$(this).attr('checked', true);
				$('#wordformElement-'+elementIndex+' .wordform-dropped-element-radio-field-options li:eq('+liElementnth+') input').attr("checked", true );
			}
			else {
				$(this).attr('checked', false );
			}
		});
		// Dropped Radio element options
		$('input[name="'+ droppedElementGroupName +'"]').each(function(index, elem ) {
			if ( $(this).is(":checked") ) {
				$(this).attr('checked', true);
			}						
			else {
				$(this).attr('checked', false);
			}
		});
		
		//if ( $(this).is(":checked") ) {
			//$('#wordformElement-'+elementIndex+' .wordform-dropped-element-radio-field-options li:eq('+liElementnth+') input').prop("checked", true );
			//$('#wordformElement-'+elementIndex+' .wordform-dropped-element-radio-field-options li:eq('+liElementnth+') input').attr("checked", true );
		//}
	});
	
	// Radio: Edit Radio Label Text
	$('body').on("input", ".wordform-radio-label-name", function() {
		let labelName		= $(this).val();
		let elementIndex	= $(this).closest('.wordform-radio-field-options-wrapper').prop("id").split("-")[1];														
		$('#wordformElement-'+elementIndex+' .wordform-dropped-radio-label').html(labelName);		
	});
	
	
	/*** Checkbox ***/
	
	// Checkbox: Hide Checkbox element options wrapper - then show only the working one
	function showHideCheckboxOptions( elementOptionsWrapperID ) {
		 $('.show-hide-common-class-all-options-wrapper-element').css('display', 'none');
		 $('.show-hide-common-class-all-options-wrapper-element').promise().done(function() {			 
			 $('#'+elementOptionsWrapperID).fadeIn();
		 }); 		
	}
	
	// Checkbox: Edit Checkbox Label Text
	$('body').on("input", ".wordform-checkbox-label-name", function() {
		let labelName		= $(this).val();
		let elementIndex	= $(this).closest('.wordform-checkbox-field-options-wrapper').prop("id").split("-")[1];														
		$('#wordformElement-'+elementIndex+' .wordform-dropped-checkbox-label').html(labelName);		
	});
	
	// Checkbox: On change/ Edit update checkbox options label text
	$('body').on("input", ".wordform-input-checkbox-label-name", function() {
		let elementIndex	= $(this).closest('.wordform-checkbox-field-options-wrapper').prop("id").split("-")[1];				
		let liElementnth	= $(this).parent().index();
		let labelName		= $(this).val();		
		//$('.wordform-dropped-element-radio-field-options li:eq('+liElementnth+') span').html(labelName);
		$('#wordformElement-'+elementIndex+' li:eq('+liElementnth+') span').html(labelName);
	});
	
	// Checkbox: Clicked/Checked checkbox
	$('body').on("click", ".wordform-edit-checkbox-name", function() {
		let liElementnth	= $(this).parent().index();
		let elementIndex	= $(this).closest('.wordform-checkbox-field-options-wrapper').prop("id").split("-")[1];
		if ( $(this).is(":checked") ) {
			$(this).attr('checked', true );
			//$('#wordformElement-'+elementIndex+' .wordform-dropped-element-checkbox-field-options li:eq('+liElementnth+') input').prop("checked", true );
			$('#wordformElement-'+elementIndex+' .wordform-dropped-element-checkbox-field-options li:eq('+liElementnth+') input').attr("checked", true );
		}
		else {
			$(this).attr('checked', false );
			//$('#wordformElement-'+elementIndex+' .wordform-dropped-element-checkbox-field-options li:eq('+liElementnth+') input').prop("checked", false );
			$('#wordformElement-'+elementIndex+' .wordform-dropped-element-checkbox-field-options li:eq('+liElementnth+') input').attr("checked", false );
		}
	});
	
	// Checkbox: Remove Checkbox Option Field
	$('body').on("click", ".wordform-checkbox-field-remove", function() {		
		let parentULLength		= $(this).closest('.wordform-field-options').find('li').length;		
		if ( parentULLength == 2 ) {
			alert('Minimum 1 Option Required!');
		}
		else {
			let liElementnth	= $(this).parent().index();		
			$('.wordform-dropped-element-checkbox-field-options li:eq('+liElementnth+')').remove();
			$(this).parent().remove();
		}
	})
	
	// Checkbox: Add more Checkbox Option
	$('body').on("click", ".wordform-add-checkbox-option", function() {
		// Add to field options
		$(this).parent().prev().after('<li> <input class="wordform-edit-checkbox-name" name="wordform-edit-checkbox-name" type="checkbox" /><input class="wordform-input-checkbox-label-name" type="text" placeholder="Checkbox Text" /> <span class="wordform-checkbox-field-remove dashicons dashicons-no" title="Remove"></span> </li> ');
				
		// Add to dropped zone element
		let elementIndex	= $(this).closest('.wordform-checkbox-field-options-wrapper').prop("id").split("-")[1];												
		$('#wordformElement-'+elementIndex+ ' .wordform-dropped-element-checkbox-field-options').append('<li><input class="wordform-dropped-checkbox-name" name="wordform-dropped-checkbox-name" type="checkbox" disabled="disabled" /><span>Checkbox Text</span> </li>');		
	});
	
	
	/*** Select ***/
	
	// Select: Hide all select options wrapper - then show only the working one
	function showHideSelectOptions( elementOptionsWrapperID ) {
		 $('.show-hide-common-class-all-options-wrapper-element').css('display', 'none');
		 $('.show-hide-common-class-all-options-wrapper-element').promise().done(function() {			 
			 $('#'+elementOptionsWrapperID).fadeIn();
		 }); 		
	}
	
	// Select: EdiT Dropdown Label Text
	$('body').on("input", ".wordform-select-label-name", function() {
		let labelName		= $(this).val();
		let elementIndex	= $(this).closest('.wordform-select-field-options-wrapper').prop("id").split("-")[1];														
		$('#wordformElement-'+elementIndex+' .wordform-dropped-select-label').html(labelName);		
	});
		
	// Select: On change/ Edit update Select options text
	$('body').on("input", ".wordform-input-select-label-name", function() {
		let elementIndex	= $(this).closest('.wordform-select-field-options-wrapper').prop("id").split("-")[1];				
		let liElementnth	= $(this).parent().index();
		let selectText		= $(this).val();				
		$('#wordformElement-'+elementIndex+' option:eq('+liElementnth+')' ).html(selectText);
		$('#wordformElement-'+elementIndex+' option:eq('+liElementnth+')' ).val(selectText);
	});

	// Select: On Click Select option texts to set as default selected in dropdown
	$('body').on("click", ".wordform-edit-select-name", function() {		
		let elementIndex	= $(this).closest('.wordform-select-field-options-wrapper').prop("id").split("-")[1];						
		let selectText		= $(this).next().val();							
		//$('#wordformElement-'+elementIndex+' .wordform-dropped-select-name' ).val(selectText);
		
		// Find Select checkbox options group name by name attribute
		let editSelectCheckboxOptionsGroupName		= $(this).prop('name');						
		// Element options
		$('input[name="'+ editSelectCheckboxOptionsGroupName +'"]').each(function(index, elem ) {			
			if ( $(this).is(":checked") ) {
				$(this).attr('checked', true);
				$('#wordformElement-'+elementIndex+' .wordform-dropped-select-name option' ).attr('selected', false ).promise().done(function() {
					$('#wordformElement-'+elementIndex+' .wordform-dropped-select-name option[value="'+selectText+'"]' ).attr('selected', true );	
				});				
			}
			else {
				$(this).attr('checked', false );
			}
		});		
				
	});
		
	
	// Select: Add more Select Option
	$('body').on("click", ".wordform-add-select-option", function() {
		let elementIndex	= $(this).closest('.wordform-select-field-options-wrapper').prop("id").split("-")[1];												
		
		// Add to field options
		$(this).parent().prev().after('<li> <input class="wordform-edit-select-name" name="wordform-edit-select-name-'+elementIndex+'" type="radio" /><input class="wordform-input-select-label-name" type="text" placeholder="Select Text" /> <span class="wordform-select-field-remove dashicons dashicons-no" title="Remove"></span> </li> ');
				
		// Add to dropped zone element
		//let elementIndex	= $(this).closest('.wordform-select-field-options-wrapper').prop("id").split("-")[1];												
		$('#wordformElement-'+elementIndex+ ' .wordform-dropped-select-name').append('<option value="Select Text">Select Text</option>');		
	});
	
	// Select: Remove Select Text Field
	$('body').on("click", ".wordform-select-field-remove", function() {
		let parentULLength		= $(this).closest('.wordform-field-options').find('li').length;		
		if ( parentULLength == 2 ) {
			alert('Minimum 1 Option Required!');
		}
		else {		
			let liElementnth	= $(this).parent().index();		
			$('.wordform-dropped-element-select-field-options .wordform-dropped-select-name option:eq('+liElementnth+')').remove();
			$(this).parent().remove();
		}
	})
	
	/*** Email ***/

	// Email: Hide all email options wrapper - then show only the working one
	function showHideEmailOptions( elementOptionsWrapperID ) {
		 $('.show-hide-common-class-all-options-wrapper-element').css('display', 'none');
		 $('.show-hide-common-class-all-options-wrapper-element').promise().done(function() {			 
			 $('#'+elementOptionsWrapperID).fadeIn();
		 }); 		
	}
	
	// Email: EdiEmail Label Text
	$('body').on("input", ".wordform-email-label-name", function() {
		let labelName		= $(this).val();
		let elementIndex	= $(this).closest('.wordform-email-field-options-wrapper').prop("id").split("-")[1];														
		$('#wordformElement-'+elementIndex+' .wordform-dropped-email-label').html(labelName);		
	});

   // Email: EditText Placeholder Text
   $('body').on("input", ".wordform-email-placeholder-text-input", function() {
	   let placeholderText		= $(this).val();
	   let elementIndex	= $(this).closest('.wordform-email-field-options-wrapper').prop("id").split("-")[1];														
	   $('#wordformElement-'+elementIndex+' .wordform-dropped-email-name').attr("placeholder", placeholderText );		
   });

	/*** Address ***/

	function showHideAddressOptions( elementOptionsWrapperID ) {
		 $('.show-hide-common-class-all-options-wrapper-element').css('display', 'none');
		 $('.show-hide-common-class-all-options-wrapper-element').promise().done(function() {
			 $('#'+elementOptionsWrapperID).fadeIn();
		 });
	}

	$('body').on("input", ".wordform-address-label-name", function() {
		let labelName = $(this).val();
		let elementIndex = $(this).closest('.wordform-address-field-options-wrapper').prop("id").split("-")[1];
		$('#wordformElement-'+elementIndex+' .wordform-dropped-address-label').html(labelName || 'Address');
	});

	$('body').on("change", ".address-placeholder-show-checkbox", function() {
		let $wrapper = $(this).closest('.wordform-address-field-options-wrapper');
		let elementIndex = $wrapper.prop("id").split("-")[1];
		let showPlaceholders = $(this).is(':checked');
		$('#wordformElement-'+elementIndex).find('input[type="text"]').each(function() {
			let storedPlaceholder = $(this).data('wordform-placeholder') || $(this).attr('placeholder') || '';
			$(this).attr('placeholder', showPlaceholders ? storedPlaceholder : '');
		});
	});

	$('body').on("input", ".wordform-address-placeholder-street-input, .wordform-address-placeholder-city-input, .wordform-address-placeholder-state-input, .wordform-address-placeholder-zip-input, .wordform-address-placeholder-country-input", function() {
		let $wrapper = $(this).closest('.wordform-address-field-options-wrapper');
		let elementIndex = $wrapper.prop("id").split("-")[1];
		let showPlaceholders = $wrapper.find('.address-placeholder-show-checkbox').is(':checked');
		let placeholderMap = {
			'wordform-address-placeholder-street-input': '.wordform-dropped-address-street',
			'wordform-address-placeholder-city-input': '.wordform-dropped-address-city',
			'wordform-address-placeholder-state-input': '.wordform-dropped-address-state',
			'wordform-address-placeholder-zip-input': '.wordform-dropped-address-zip',
			'wordform-address-placeholder-country-input': '.wordform-dropped-address-country'
		};
		let currentClass = $(this).attr('class').split(' ').find((className) => placeholderMap[className]);
		if (!currentClass) {
			return;
		}

		let $target = $('#wordformElement-'+elementIndex+' ' + placeholderMap[currentClass]);
		let placeholderText = $(this).val();
		$target.data('wordform-placeholder', placeholderText);
		$target.attr('placeholder', showPlaceholders ? placeholderText : '');
	});

	/*** Section / HTML ***/

	function showHideSectionHtmlOptions( elementOptionsWrapperID ) {
		 $('.show-hide-common-class-all-options-wrapper-element').css('display', 'none');
		 $('.show-hide-common-class-all-options-wrapper-element').promise().done(function() {
			 $('#'+elementOptionsWrapperID).fadeIn();
		 });
	}

	$('body').on("input", ".wordform-sectionhtml-title-input", function() {
		let titleText = $(this).val();
		let elementIndex = $(this).closest('.wordform-sectionhtml-field-options-wrapper').prop("id").split("-")[1];
		$('#wordformElement-'+elementIndex+' .wordform-sectionhtml-builder-title').html(titleText || 'Section Title');
	});

	$('body').on("input", ".wordform-sectionhtml-content-input", function() {
		let contentText = $.trim($(this).val());
		let elementIndex = $(this).closest('.wordform-sectionhtml-field-options-wrapper').prop("id").split("-")[1];
		$('#wordformElement-'+elementIndex+' .wordform-sectionhtml-builder-content').text(contentText || 'Add instructions, notes, or custom HTML content.');
	});

	/*** Mask Input ***/

	function showHideMaskInputOptions( elementOptionsWrapperID ) {
		 $('.show-hide-common-class-all-options-wrapper-element').css('display', 'none');
		 $('.show-hide-common-class-all-options-wrapper-element').promise().done(function() {
			 $('#'+elementOptionsWrapperID).fadeIn();
		 });
	}

	$('body').on("input", ".wordform-maskinput-label-name", function() {
		let labelName = $(this).val();
		let elementIndex = $(this).closest('.wordform-maskinput-field-options-wrapper').prop("id").split("-")[1];
		$('#wordformElement-'+elementIndex+' .wordform-dropped-maskinput-label').html(labelName || 'Masked Input');
	});

	$('body').on("change", ".maskinput-placeholder-show-checkbox", function() {
		let $wrapper = $(this).closest('.wordform-maskinput-field-options-wrapper');
		let elementIndex = $wrapper.prop("id").split("-")[1];
		let $input = $('#wordformElement-'+elementIndex+' .wordform-dropped-maskinput-name');
		let placeholderText = $input.data('wordform-placeholder') || 'AB-12345';
		$input.attr('placeholder', $(this).is(':checked') ? placeholderText : '');
	});

	$('body').on("input", ".wordform-maskinput-placeholder-text-input", function() {
		let $wrapper = $(this).closest('.wordform-maskinput-field-options-wrapper');
		let elementIndex = $wrapper.prop("id").split("-")[1];
		let placeholderText = $(this).val();
		let showPlaceholder = $wrapper.find('.maskinput-placeholder-show-checkbox').is(':checked');
		let $input = $('#wordformElement-'+elementIndex+' .wordform-dropped-maskinput-name');
		$input.data('wordform-placeholder', placeholderText);
		$input.attr('placeholder', showPlaceholder ? placeholderText : '');
	});

	$('body').on("input", ".wordform-maskinput-pattern-input", function() {
		let patternText = $(this).val();
		let elementIndex = $(this).closest('.wordform-maskinput-field-options-wrapper').prop("id").split("-")[1];
		$('#wordformElement-'+elementIndex+' .wordform-maskinput-builder-pattern code').text(patternText || '^[A-Z]{2}-[0-9]{5}$');
	});

	/*** Hidden ***/

	function showHideHiddenOptions( elementOptionsWrapperID ) {
		 $('.show-hide-common-class-all-options-wrapper-element').css('display', 'none');
		 $('.show-hide-common-class-all-options-wrapper-element').promise().done(function() {
			 $('#'+elementOptionsWrapperID).fadeIn();
		 });
	}

	$('body').on("input", ".wordform-hidden-label-name", function() {
		let labelName = $(this).val();
		let elementIndex = $(this).closest('.wordform-hidden-field-options-wrapper').prop("id").split("-")[1];
		$('#wordformElement-'+elementIndex+' .wordform-hidden-builder-title').html(labelName || 'Hidden Field');
	});

	$('body').on("input", ".wordform-hidden-field-value-input", function() {
		let hiddenValue = $(this).val();
		let elementIndex = $(this).closest('.wordform-hidden-field-options-wrapper').prop("id").split("-")[1];
		$('#wordformElement-'+elementIndex+' .wordform-hidden-builder-value').text('Value: ' + (hiddenValue || 'utm_source'));
	});

	
	/*** Captcha ***/
	
	// Captcha: Hide all captcha options wrapper - then show only the working one
	function showHideCaptchaOptions( elementOptionsWrapperID ) {
		 $('.show-hide-common-class-all-options-wrapper-element').css('display', 'none');
		 $('.show-hide-common-class-all-options-wrapper-element').promise().done(function() {
			 const $wrapper = $('#'+elementOptionsWrapperID);
			 $wrapper.fadeIn();
			 wordformToggleCaptchaStyleModeGroups($wrapper);
			 wordformRefreshCaptchaBuilderPreview($wrapper);
		 }); 		
	}

	function wordformGetCaptchaTemplatePreviewUrl($wrapper) {
		const $selectedTemplate = $wrapper.find('.wordform-captcha-template-radio:checked').first();
		if (!$selectedTemplate.length) {
			return sc_wordform_metabox_script_obj.wordform_default_template_url;
		}

		if (($selectedTemplate.val() || '') === 'all') {
			return sc_wordform_metabox_script_obj.wordform_default_template_url;
		}

		return $selectedTemplate.closest('label').find('img').attr('src')
			|| $selectedTemplate.siblings('img').attr('src')
			|| sc_wordform_metabox_script_obj.wordform_default_template_url;
	}

	function wordformToggleCaptchaStyleModeGroups($wrapper) {
		const styleMode = $wrapper.find('.wordform-captcha-style-mode-radio:checked').val() || 'template';
		$wrapper.find('.wordform-captcha-template-settings-group').toggle(styleMode === 'template');
		$wrapper.find('.wordform-captcha-dynamic-colors-group').toggle(styleMode === 'dynamic');
	}

	function wordformRefreshCaptchaBuilderPreview($wrapper) {
		if (!$wrapper || !$wrapper.length) {
			return;
		}

		const elementIndex = ($wrapper.prop('id') || '').split('-')[1];
		const $builderElement = $('#wordformElement-' + elementIndex);
		if (!$builderElement.length) {
			return;
		}

		const styleMode = $wrapper.find('.wordform-captcha-style-mode-radio:checked').val() || 'template';
		const backgroundColor = $wrapper.find('.wordform-captcha-background-color-input').val() || '#eef2ff';
		const textColor = $wrapper.find('.wordform-captcha-text-color-input').val() || '#111827';
		const noiseColor = $wrapper.find('.wordform-captcha-noise-color-input').val() || '#cbd5e1';
		const digitLength = Math.max(3, Math.min(8, parseInt($wrapper.find('.wordform-captcha-digit-length-select').val(), 10) || 4));
		const fontStyle = $wrapper.find('.wordform-captcha-font-style-select').val() || 'blackopsone';
		const templateImageUrl = wordformGetCaptchaTemplatePreviewUrl($wrapper);
		const $preview = $builderElement.find('.wordform-dropped-captcha-placeholder');
		const $image = $preview.find('img');
		const $overlay = $preview.find('.wordform-overlay-captcha-value');
		const previewWidth = wordformGetCaptchaPreviewWidth(digitLength);
		const previewHeight = 84;
		const previewValue = wordformGenerateCaptchaPreviewDigits(digitLength);

		$preview.css({
			width: previewWidth + 'px',
			height: previewHeight + 'px'
		});
		$overlay
			.text(previewValue)
			.css({
				'font-family': wordformResolveCaptchaPreviewFontFamily(fontStyle),
				'font-size': wordformGetCaptchaPreviewFontSize(digitLength, fontStyle) + 'px'
			});

		if (styleMode === 'dynamic') {
			$preview
				.addClass('wordform-captcha-preview-dynamic')
				.css({
					'background-color': backgroundColor,
					'border-color': noiseColor
				});
			$image.hide();
			$overlay.css('color', textColor);
		} else {
			$preview
				.removeClass('wordform-captcha-preview-dynamic')
				.css({
					'background-color': '',
					'border-color': ''
				});
			$image.attr('src', templateImageUrl).show();
			$overlay.css('color', '');
		}
	}

	function initWordformAdminDateTimeLimitPicker($input) {
		if (!$input || !$input.length) {
			return;
		}

		const dateFmt = 'yy-mm-dd';
		const timeFmt = 'HH:mm';

		const opts = {
			controlType: 'select',
			oneLine: true,
			showSecond: false,
			stepMinute: 1,
			dateFormat: dateFmt,
			timeFormat: timeFmt,
			ampm: false,
			beforeShow: function() {
				try {
					const currentValue = normalizeSpaces($input.val() || '');
					const currentDate = parseDateTime(dateFmt, timeFmt, currentValue);
					if (currentDate) {
						$input.datetimepicker('setDate', currentDate);
					}
				} catch (e) {}
			},
			onSelect: function() {
				const d = $input.datetimepicker('getDate');
				if (!d) return;
				$input.val(formatDateTime(dateFmt, timeFmt, d)).trigger('input').trigger('change');
			},
			onClose: function() {
				const d = $input.datetimepicker('getDate');
				if (!d) return;
				$input.val(formatDateTime(dateFmt, timeFmt, d)).trigger('change');
			}
		};

		if (!$input.hasClass('has-datetimepicker')) {
			$input.datetimepicker(opts);
			$input.addClass('has-datetimepicker');
			return;
		}

		$input.datetimepicker('option', opts);
	}

	$('body').on('focus click', '.wordform-datetime-min-datetime-value, .wordform-datetime-max-datetime-value', function() {
		const $input = $(this);
		initWordformAdminDateTimeLimitPicker($input);
		try { $input.datetimepicker('show'); } catch (e) {}
	});

	function wordformGenerateCaptchaPreviewDigits(length) {
		const normalizedLength = Math.max(3, Math.min(8, parseInt(length, 10) || 4));
		const digits = [];
		for (let i = 0; i < normalizedLength; i++) {
			digits.push(Math.floor(Math.random() * 10));
		}
		return digits.join(' ');
	}

	function wordformResolveCaptchaPreviewFontFamily(fontStyle) {
		const fontMap = {
			blackopsone: 'GoogleBlackOpsOne',
			kalam: 'Kalam',
			rubikmoonrocks: 'RubikMoonrocks',
			fasterone: 'FasterOne',
			code: 'Code'
		};
		return fontMap[fontStyle] || 'GoogleBlackOpsOne';
	}

	function wordformGetCaptchaPreviewWidth(length) {
		const normalizedLength = Math.max(3, Math.min(8, parseInt(length, 10) || 4));
		return Math.max(220, 120 + (normalizedLength * 20));
	}

	function wordformGetCaptchaPreviewFontSize(length, fontStyle) {
		const normalizedLength = Math.max(3, Math.min(8, parseInt(length, 10) || 4));
		let fontSize = 25 - Math.max(0, (normalizedLength - 4) * 2);
		if (fontStyle === 'rubikmoonrocks') {
			fontSize -= 2;
		} else if (fontStyle === 'fasterone') {
			fontSize -= 1;
		}
		return Math.max(14, fontSize);
	}
	
	// Captcha: EditText Label Text
	$('body').on("input", ".wordform-captcha-label-name", function() {
		let labelName		= $(this).val();
		let elementIndex	= $(this).closest('.wordform-captcha-field-options-wrapper').prop("id").split("-")[1];														
		$('#wordformElement-'+elementIndex+' .wordform-dropped-captcha-label').html(labelName);		
	});

   // Captcha: EditText Placeholder Text
   $('body').on("input", ".wordform-captcha-placeholder-text-input", function() {
	   let placeholderText		= $(this).val();
	   let elementIndex	= $(this).closest('.wordform-captcha-field-options-wrapper').prop("id").split("-")[1];														
	   $('#wordformElement-'+elementIndex+' .wordform-dropped-captcha-name').attr("placeholder", placeholderText );		
   });
	
	// Captcha: Background Template Selection
	$('body').on("change", ".wordform-captcha-template-radio", function() {
		const $wrapper = $(this).closest('.wordform-captcha-field-options-wrapper');
		wordformRefreshCaptchaBuilderPreview($wrapper);
	});

	$('body').on("change", ".wordform-captcha-style-mode-radio", function() {
		const $wrapper = $(this).closest('.wordform-captcha-field-options-wrapper');
		wordformToggleCaptchaStyleModeGroups($wrapper);
		wordformRefreshCaptchaBuilderPreview($wrapper);
	});

	$('body').on("input change", ".wordform-captcha-background-color-input, .wordform-captcha-text-color-input, .wordform-captcha-noise-color-input", function() {
		const $wrapper = $(this).closest('.wordform-captcha-field-options-wrapper');
		wordformSyncEnhancedColorPickerDisplay($(this));
		wordformRefreshCaptchaBuilderPreview($wrapper);
	});

	$('body').on('change', '.wordform-date-calendar-accent-color, .wordform-date-calendar-surface-color, .wordform-date-calendar-text-color, .wordform-datetime-calendar-accent-color, .wordform-datetime-calendar-surface-color, .wordform-datetime-calendar-text-color', function() {
		wordformSyncEnhancedColorPickerDisplay($(this));
	});

	$('body').on('click', '.wordform-color-picker-trigger', function(e) {
		e.preventDefault();
		const $input = $(this).siblings('input[type="color"]').first();
		wordformOpenSharedColorPicker($input);
	});

	$('body').on('click', '.wordform-color-picker-modal-backdrop, .wordform-color-picker-modal-close', function() {
		wordformCloseSharedColorPicker();
	});

	$(document).on('keydown', function(e) {
		if (e.key === 'Escape' && $('#wordform-shared-color-picker-modal').hasClass('is-open')) {
			wordformCloseSharedColorPicker();
		}
	});

	$('body').on("change", ".wordform-captcha-digit-length-select, .wordform-captcha-font-style-select", function() {
		const $wrapper = $(this).closest('.wordform-captcha-field-options-wrapper');
		wordformRefreshCaptchaBuilderPreview($wrapper);
	});
	
	// Captcha: Captcha Template Alignment
	$('body').on("change", ".wordform-build-captcha-template-align-input", function() {	
		$('.wordform-build-captcha-template-align-input').attr('checked', false);
		let captchaImageAlignVal = $(this).val();
		let elementIndex = $(this).closest('.wordform-captcha-field-options-wrapper').prop("id").split("-")[1];
		$('#wordformElement-'+elementIndex+' .wordform-input-element-div-wrapper-captcha-template').removeClass('left right center');
		$('#wordformElement-'+elementIndex+' .wordform-input-element-div-wrapper-captcha-template').addClass(captchaImageAlignVal );
		$(this).attr('checked', true);		
	});

	
	/*** Google Captcha ***/

	// Google Captcha: Hide all captcha options wrapper - then show only the working one
	function showHideGoogleCaptchaOptions( elementOptionsWrapperID ) {
		$('.show-hide-common-class-all-options-wrapper-element').css('display', 'none');
		$('.show-hide-common-class-all-options-wrapper-element').promise().done(function() {			 
			$('#'+elementOptionsWrapperID).fadeIn();
		}); 		
   }
   
   // Google Captcha: EditText Label Text
   $('body').on("input", ".wordform-gcaptcha-label-name", function() {
	   let labelName	= $(this).val();
	   let elementIndex	= $(this).closest('.wordform-gcaptcha-field-options-wrapper').prop("id").split("-")[1];														
	   $('#wordformElement-'+elementIndex+' .wordform-dropped-gcaptcha-label').html(labelName);		
   });

	$('body').on("change", ".recaptcha-label-checkbox", function() {
		const elementIndex = $(this).closest('.wordform-gcaptcha-field-options-wrapper').prop("id").split("-")[1];
		const $label = $('#wordformElement-' + elementIndex + ' .wordform-dropped-gcaptcha-label');
		if ($(this).is(':checked')) {
			$label.show();
		} else {
			$label.hide();
		}
	});

	/*** hCaptcha ***/

	function showHideHCaptchaOptions( elementOptionsWrapperID ) {
		$('.show-hide-common-class-all-options-wrapper-element').css('display', 'none');
		$('.show-hide-common-class-all-options-wrapper-element').promise().done(function() {
			$('#' + elementOptionsWrapperID).fadeIn();
		});
	}

	$('body').on("input", ".wordform-hcaptcha-label-name", function() {
		let labelName = $(this).val();
		let elementIndex = $(this).closest('.wordform-hcaptcha-field-options-wrapper').prop("id").split("-")[1];
		$('#wordformElement-' + elementIndex + ' .wordform-dropped-hcaptcha-label').html(labelName);
	});

	$('body').on("change", ".hcaptcha-label-checkbox", function() {
		const elementIndex = $(this).closest('.wordform-hcaptcha-field-options-wrapper').prop("id").split("-")[1];
		const $label = $('#wordformElement-' + elementIndex + ' .wordform-dropped-hcaptcha-label');
		if ($(this).is(':checked')) {
			$label.show();
		} else {
			$label.hide();
		}
	});
	

	/*** Upload ***/
	
	// Upload: Hide all options wrapper - then show only the working one
	function showHideUploadOptions( elementOptionsWrapperID ) {
		$('.show-hide-common-class-all-options-wrapper-element').css('display', 'none');
		$('.show-hide-common-class-all-options-wrapper-element').promise().done(function() {			 
			$('#'+elementOptionsWrapperID).fadeIn();
		}); 		
   }
   
   // Upload: EditText Label Text
   $('body').on("input", ".wordform-upload-label-name", function() {
	   let labelName	= $(this).val();
	   let elementIndex	= $(this).closest('.wordform-upload-field-options-wrapper').prop("id").split("-")[1];														
	   $('#wordformElement-'+elementIndex+' .wordform-dropped-upload-label').html(labelName);		
   });
   
   // Upload: EditText Select File Label Text
   $('body').on("input", ".wordform-upload-select-file-label-name", function() {
		let labelName	= $(this).val();
		let elementIndex	= $(this).closest('.wordform-upload-field-options-wrapper').prop("id").split("-")[1];														
		$('#wordformElement-'+elementIndex+' .wordform-dropped-upload-select-file-label').html(labelName);		
		$(this).attr("value", labelName );
	});

	/*** Signature ***/

	function showHideRatingOptions( elementOptionsWrapperID ) {
		$('.show-hide-common-class-all-options-wrapper-element').css('display', 'none');
		$('.show-hide-common-class-all-options-wrapper-element').promise().done(function() {
			$('#' + elementOptionsWrapperID).fadeIn();
		});
	}

	function showHideRichEditorOptions( elementOptionsWrapperID ) {
		$('.show-hide-common-class-all-options-wrapper-element').css('display', 'none');
		$('.show-hide-common-class-all-options-wrapper-element').promise().done(function() {
			$('#' + elementOptionsWrapperID).fadeIn();
		});
	}

	$('body').on("input", ".wordform-richeditor-label-name", function() {
		let labelName = $(this).val();
		let elementIndex = $(this).closest('.wordform-richeditor-field-options-wrapper').prop("id").split("-")[1];
		$('#wordformElement-' + elementIndex + ' .wordform-richeditor-builder-title').html(labelName || 'Rich Text Editor');
		$(this).attr("value", labelName );
	});

	$('body').on("change", ".richeditor-placeholder-show-checkbox", function() {
		let elementIndex = $(this).closest('.wordform-richeditor-field-options-wrapper').prop("id").split("-")[1];
		let placeholderText = $(this).closest('.wordform-richeditor-field-options-wrapper').find('.wordform-richeditor-placeholder-text-input').val() || 'Write your response...';
		$('#wordformElement-' + elementIndex + ' .wordform-richeditor-builder-placeholder')
			.text(placeholderText)
			.toggle($(this).is(':checked'));
	});

	$('body').on("input", ".wordform-richeditor-placeholder-text-input", function() {
		let placeholderText = $(this).val();
		let $wrapper = $(this).closest('.wordform-richeditor-field-options-wrapper');
		let elementIndex = $wrapper.prop("id").split("-")[1];
		let showPlaceholder = $wrapper.find('.richeditor-placeholder-show-checkbox').is(':checked');
		$('#wordformElement-' + elementIndex + ' .wordform-richeditor-builder-placeholder')
			.text(placeholderText || 'Write your response...')
			.toggle(showPlaceholder);
		$(this).attr("value", placeholderText );
	});

	$('body').on("input change", ".wordform-richeditor-min-height-input", function() {
		let minHeight = parseInt($(this).val(), 10);
		let elementIndex = $(this).closest('.wordform-richeditor-field-options-wrapper').prop("id").split("-")[1];
		if (!Number.isFinite(minHeight) || minHeight < 140) {
			minHeight = 180;
		}
		minHeight = Math.min(minHeight, 420);
		$('#wordformElement-' + elementIndex + ' .wordform-richeditor-builder-surface').css('min-height', minHeight + 'px');
		$(this).val(minHeight).attr("value", minHeight );
	});

	$('body').on("input", ".wordform-rating-label-name", function() {
		let labelName = $(this).val();
		let elementIndex = $(this).closest('.wordform-rating-field-options-wrapper').prop("id").split("-")[1];
		$('#wordformElement-' + elementIndex + ' .wordform-rating-builder-title').html(labelName || 'Rating');
		$(this).attr("value", labelName );
	});

	$('body').on("input change", ".wordform-rating-scale-input", function() {
		let ratingScale = parseInt($(this).val(), 10);
		let elementIndex = $(this).closest('.wordform-rating-field-options-wrapper').prop("id").split("-")[1];
		if (!Number.isFinite(ratingScale) || ratingScale < 3) {
			ratingScale = 5;
		}
		ratingScale = Math.min(ratingScale, 10);
		$('#wordformElement-' + elementIndex + ' .wordform-rating-builder-stars').html(wordformBuildRatingBuilderStars(ratingScale));
		$(this).val(ratingScale).attr("value", ratingScale );
	});

	$('body').on("input", ".wordform-rating-low-text-input", function() {
		let ratingText = $(this).val();
		let elementIndex = $(this).closest('.wordform-rating-field-options-wrapper').prop("id").split("-")[1];
		$('#wordformElement-' + elementIndex + ' .wordform-rating-builder-low').html(ratingText || 'Poor');
		$(this).attr("value", ratingText );
	});

	$('body').on("input", ".wordform-rating-high-text-input", function() {
		let ratingText = $(this).val();
		let elementIndex = $(this).closest('.wordform-rating-field-options-wrapper').prop("id").split("-")[1];
		$('#wordformElement-' + elementIndex + ' .wordform-rating-builder-high').html(ratingText || 'Excellent');
		$(this).attr("value", ratingText );
	});

	function showHideLikertOptions( elementOptionsWrapperID ) {
		$('.show-hide-common-class-all-options-wrapper-element').css('display', 'none');
		$('.show-hide-common-class-all-options-wrapper-element').promise().done(function() {
			$('#' + elementOptionsWrapperID).fadeIn();
		});
	}

	$('body').on("input", ".wordform-likert-label-name", function() {
		let labelName = $(this).val();
		let elementIndex = $(this).closest('.wordform-likert-field-options-wrapper').prop("id").split("-")[1];
		$('#wordformElement-' + elementIndex + ' .wordform-likert-builder-title').html(labelName || 'Likert Scale');
		$(this).attr("value", labelName );
	});

	$('body').on("input", ".wordform-input-likert-row-label-name, .wordform-input-likert-column-label-name", function() {
		wordformRefreshLikertBuilderPreviewFromOptions($(this).closest('.wordform-likert-field-options-wrapper'));
	});

	$('body').on("click", ".wordform-add-likert-row-option", function() {
		const $wrapper = $(this).closest('.wordform-likert-field-options-wrapper');
		const $newItem = wordformCreateLikertOptionItem('row', '');
		$(this).closest('li').before($newItem);
		$newItem.find('input').trigger('focus');
		wordformRefreshLikertBuilderPreviewFromOptions($wrapper);
	});

	$('body').on("click", ".wordform-add-likert-column-option", function() {
		const $wrapper = $(this).closest('.wordform-likert-field-options-wrapper');
		const $newItem = wordformCreateLikertOptionItem('column', '');
		$(this).closest('li').before($newItem);
		$newItem.find('input').trigger('focus');
		wordformRefreshLikertBuilderPreviewFromOptions($wrapper);
	});

	$('body').on("click", ".wordform-likert-row-field-remove", function() {
		const $wrapper = $(this).closest('.wordform-likert-field-options-wrapper');
		const $list = $(this).closest('.wordform-likert-row-options');
		if ($list.find('.wordform-input-likert-row-label-name').length <= 2) {
			return;
		}
		$(this).closest('li').remove();
		wordformRefreshLikertBuilderPreviewFromOptions($wrapper);
	});

	$('body').on("click", ".wordform-likert-column-field-remove", function() {
		const $wrapper = $(this).closest('.wordform-likert-field-options-wrapper');
		const $list = $(this).closest('.wordform-likert-column-options');
		if ($list.find('.wordform-input-likert-column-label-name').length <= 2) {
			return;
		}
		$(this).closest('li').remove();
		wordformRefreshLikertBuilderPreviewFromOptions($wrapper);
	});

	function showHideSignatureOptions( elementOptionsWrapperID ) {
		$('.show-hide-common-class-all-options-wrapper-element').css('display', 'none');
		$('.show-hide-common-class-all-options-wrapper-element').promise().done(function() {
			$('#' + elementOptionsWrapperID).fadeIn();
		});
	}

	$('body').on("input", ".wordform-signature-label-name", function() {
		let labelName = $(this).val();
		let elementIndex = $(this).closest('.wordform-signature-field-options-wrapper').prop("id").split("-")[1];
		$('#wordformElement-' + elementIndex + ' .wordform-signature-builder-title').html(labelName || 'Signature');
		$(this).attr("value", labelName );
	});

	$('body').on("input", ".wordform-signature-clear-button-text-input", function() {
		let buttonText = $(this).val();
		let elementIndex = $(this).closest('.wordform-signature-field-options-wrapper').prop("id").split("-")[1];
		$('#wordformElement-' + elementIndex + ' .wordform-signature-builder-clear').html(buttonText || 'Clear Signature');
		$(this).attr("value", buttonText );
	});

	$('body').on("input change", ".wordform-signature-canvas-height-input", function() {
		let canvasHeight = parseInt($(this).val(), 10);
		let elementIndex = $(this).closest('.wordform-signature-field-options-wrapper').prop("id").split("-")[1];
		if (!Number.isFinite(canvasHeight) || canvasHeight < 120) {
			canvasHeight = 180;
		}
		canvasHeight = Math.min(canvasHeight, 360);
		$('#wordformElement-' + elementIndex + ' .wordform-signature-builder-canvas').css('height', canvasHeight + 'px');
		$(this).val(canvasHeight).attr("value", canvasHeight );
	});

	// Page Break: Hide all options wrapper - then show only the working one
	function showHidePageBreakOptions( elementOptionsWrapperID ) {
		$('.show-hide-common-class-all-options-wrapper-element').css('display', 'none');
		$('.show-hide-common-class-all-options-wrapper-element').promise().done(function() {
			$('#'+elementOptionsWrapperID).fadeIn();
		});
	}

	function updatePageBreakBuilderLayout( elementIndex ) {
		let $builderElement = $('#wordformElement-' + elementIndex);
		if (!$builderElement.length) {
			return;
		}

		let $optionsWrapper = $('#wordformElementOptions-' + elementIndex);
		let nextAlign = $optionsWrapper.find('.wordform-pagebreak-next-button-align-input:checked').val() || 'right';
		let previousAlign = $optionsWrapper.find('.wordform-pagebreak-previous-button-align-input:checked').val() || 'left';
		let $actions = $builderElement.find('.wordform-pagebreak-builder-actions');

		$actions.removeClass('align-next-left align-next-center align-next-right align-prev-left align-prev-center align-prev-right is-stacked');
		$actions.addClass('align-next-' + nextAlign + ' align-prev-' + previousAlign);

		if (nextAlign === previousAlign) {
			$actions.addClass('is-stacked');
		}
	}

	// Page Break: Edit next step title
	$('body').on("input", ".wordform-pagebreak-step-title-input", function() {
		let labelName = $(this).val();
		let elementIndex = $(this).closest('.wordform-pagebreak-field-options-wrapper').prop("id").split("-")[1];
		$('#wordformElement-'+elementIndex+' .wordform-pagebreak-builder-title').html(labelName || 'Next Step');
		$(this).attr("value", labelName );
	});

	// Page Break: Edit next button text
	$('body').on("input", ".wordform-pagebreak-next-button-text-input", function() {
		let buttonText = $(this).val();
		let elementIndex = $(this).closest('.wordform-pagebreak-field-options-wrapper').prop("id").split("-")[1];
		$('#wordformElement-'+elementIndex+' .wordform-pagebreak-builder-action.is-primary').html(buttonText || 'Next');
		$(this).attr("value", buttonText );
	});

	// Page Break: Edit previous button text
	$('body').on("input", ".wordform-pagebreak-previous-button-text-input", function() {
		let buttonText = $(this).val();
		let elementIndex = $(this).closest('.wordform-pagebreak-field-options-wrapper').prop("id").split("-")[1];
		$('#wordformElement-'+elementIndex+' .wordform-pagebreak-builder-action.is-secondary').html(buttonText || 'Back');
		$(this).attr("value", buttonText );
	});

	$('body').on("change", ".wordform-pagebreak-next-button-align-input, .wordform-pagebreak-previous-button-align-input", function() {
		let elementIndex = $(this).closest('.wordform-pagebreak-field-options-wrapper').prop("id").split("-")[1];
		updatePageBreakBuilderLayout(elementIndex);
	});

	// Terms: Hide all options wrapper - then show only the working one
	function showHideTermsOptions( elementOptionsWrapperID ) {
		$('.show-hide-common-class-all-options-wrapper-element').css('display', 'none');
		$('.show-hide-common-class-all-options-wrapper-element').promise().done(function() {			 
			$('#'+elementOptionsWrapperID).fadeIn();
		}); 		
   }
   
   // Terms: Edit 'Terms & Conditions' Label Name
   $('body').on("input", ".wordform-terms-label-name", function() {
	   let labelName	= $(this).val();
	   let elementIndex	= $(this).closest('.wordform-terms-field-options-wrapper').prop("id").split("-")[1];														
	   $('#wordformElement-'+elementIndex+' .wordform-dropped-terms-label').html(labelName);		
   });

   // Terms: Edit 'I agree to the Terms & Conditions' Text
	jQuery('body').on('input change', '.wordform-terms-text', function () {
		let termsText = jQuery(this).val().trim();
		let elementIndex = jQuery(this)
			.closest('.wordform-terms-field-options-wrapper')
			.prop('id')
			.split('-')[1];

		// Scope to specific parent wrapper
		let $wrapper = jQuery('#wordformElement-' + elementIndex);

		// Find the label and link under this specific element only
		let $label = $wrapper.find('.wordform-dropped-terms-checkbox').closest('li').find('label');
		let $link = $label.find('a');

		// Update text dynamically inside <a> or as plain label if no <a> exists
		if ($link.length) {
			$link.text(termsText !== '' ? termsText : 'I agree to the Terms & Conditions.');
		} else {
			$label.text(termsText !== '' ? termsText : 'I agree to the Terms & Conditions.');
		}
	});

    // Terms: Make <a> clickable only when checkbox is checked
	jQuery(document).on('change', '.clickable-term-conditions-text-checkbox', function () {
		let elementIndex = $(this).closest('.wordform-terms-field-options-wrapper').prop("id").split("-")[1];
		let $wrapper = jQuery('#wordformElement-' + elementIndex);
		let isChecked = jQuery(this).is(':checked');

		// Find label and current text within this specific wrapper
		var $label = $wrapper.find('.wordform-dropped-terms-checkbox').closest('li').find('label');
		var currentText = $label.find('a').length ? $label.find('a').text() : $label.text().trim();

		if (isChecked) {
			// ✅ Make text clickable (wrap with <a>)
			if (!$label.find('a').length) {
				$label.html('<a href="#" target="_blank">' + currentText + '</a>');
			}
		} else {
			// 🚫 Make text non-clickable (remove <a>)
			if ($label.find('a').length) {
				$label.text(currentText );
			}
		}
	});

	jQuery('body').on('input change', '.wordform-terms-conditions-url-input', function () {
		let elementIndex = jQuery(this).closest('.wordform-terms-field-options-wrapper').prop("id").split("-")[1];
		let $wrapper = jQuery('#wordformElement-' + elementIndex);
		let url = jQuery(this).val().trim();
		let $link = $wrapper.find('.wordform-dropped-terms-checkbox').closest('li').find('label a');

		if ($link.length) {
			$link.attr('href', url || '#');
		}
	});

	function showHideGdprOptions( elementOptionsWrapperID ) {
		$('.show-hide-common-class-all-options-wrapper-element').css('display', 'none');
		$('.show-hide-common-class-all-options-wrapper-element').promise().done(function() {
			$('#'+elementOptionsWrapperID).fadeIn();
		});
	}

	$('body').on("input", ".wordform-gdpr-label-name", function() {
		let labelName = $(this).val();
		let elementIndex = $(this).closest('.wordform-gdpr-field-options-wrapper').prop("id").split("-")[1];
		$('#wordformElement-'+elementIndex+' .wordform-dropped-gdpr-label').html(labelName);
	});

	jQuery('body').on('input change', '.wordform-gdpr-text', function () {
		let gdprText = jQuery(this).val().trim();
		let elementIndex = jQuery(this).closest('.wordform-gdpr-field-options-wrapper').prop('id').split('-')[1];
		let $wrapper = jQuery('#wordformElement-' + elementIndex);
		let $label = $wrapper.find('.wordform-dropped-gdpr-checkbox').closest('li').find('label');
		let $link = $label.find('a');

		if ($link.length) {
			$link.text(gdprText !== '' ? gdprText : 'I agree to the privacy policy and consent to data processing.');
		} else {
			$label.text(gdprText !== '' ? gdprText : 'I agree to the privacy policy and consent to data processing.');
		}
	});

	jQuery(document).on('change', '.clickable-gdpr-text-checkbox', function () {
		let elementIndex = $(this).closest('.wordform-gdpr-field-options-wrapper').prop("id").split("-")[1];
		let $wrapper = jQuery('#wordformElement-' + elementIndex);
		let isChecked = jQuery(this).is(':checked');
		let $label = $wrapper.find('.wordform-dropped-gdpr-checkbox').closest('li').find('label');
		let currentText = $label.find('a').length ? $label.find('a').text() : $label.text().trim();

		if (isChecked) {
			if (!$label.find('a').length) {
				$label.html('<a href="#" target="_blank">' + currentText + '</a>');
			}
		} else {
			if ($label.find('a').length) {
				$label.text(currentText);
			}
		}
	});

	jQuery('body').on('input change', '.wordform-gdpr-policy-url-input', function () {
		let elementIndex = jQuery(this).closest('.wordform-gdpr-field-options-wrapper').prop("id").split("-")[1];
		let $wrapper = jQuery('#wordformElement-' + elementIndex);
		let url = jQuery(this).val().trim();
		let $link = $wrapper.find('.wordform-dropped-gdpr-checkbox').closest('li').find('label a');

		if ($link.length) {
			$link.attr('href', url || '#');
		}
	});

	/*** Payment Elements ***/

	function showHidePaymentItemOptions( elementOptionsWrapperID ) {
		$('.show-hide-common-class-all-options-wrapper-element').css('display', 'none');
		$('.show-hide-common-class-all-options-wrapper-element').promise().done(function() {
			$('#' + elementOptionsWrapperID).fadeIn();
		});
	}

	function showHidePaymentCouponOptions( elementOptionsWrapperID ) {
		$('.show-hide-common-class-all-options-wrapper-element').css('display', 'none');
		$('.show-hide-common-class-all-options-wrapper-element').promise().done(function() {
			$('#' + elementOptionsWrapperID).fadeIn();
		});
	}

	function showHidePaymentMethodOptions( elementOptionsWrapperID ) {
		$('.show-hide-common-class-all-options-wrapper-element').css('display', 'none');
		$('.show-hide-common-class-all-options-wrapper-element').promise().done(function() {
			$('#' + elementOptionsWrapperID).fadeIn();
		});
	}

	$('body').on('input', '.wordform-payment-method-label-name', function() {
		let labelName = $(this).val();
		let elementIndex = $(this).closest('.wordform-payment-method-field-options-wrapper').prop('id').split('-')[1];
		$('#wordformElement-' + elementIndex + ' .wordform-payment-method-builder-title').html(labelName || 'Payment Method');
	});

	$('body').on('input', '.wordform-payment-method-helper-text-input', function() {
		let helperText = $(this).val();
		let elementIndex = $(this).closest('.wordform-payment-method-field-options-wrapper').prop('id').split('-')[1];
		$('#wordformElement-' + elementIndex + ' .wordform-payment-method-builder-helper-text').html(helperText || 'Choose how you want to pay');
	});

	$('body').on('change', '.wordform-payment-method-default-gateway-radio', function() {
		let gatewaySlug = $(this).val() || 'stripe';
		let elementIndex = $(this).closest('.wordform-payment-method-field-options-wrapper').prop('id').split('-')[1];
		$(this).closest('.wordform-payment-method-field-options-wrapper').find('.wordform-payment-method-default-gateway-radio').attr('checked', false);
		$(this).attr('checked', true);
		wordformSetBuilderPaymentMethodPreview(elementIndex, gatewaySlug);
	});

	$('body').on('input', '.wordform-payment-item-label-name', function() {
		let labelName = $(this).val();
		let elementIndex = $(this).closest('.wordform-payment-item-field-options-wrapper').prop('id').split('-')[1];
		$('#wordformElement-' + elementIndex + ' .wordform-payment-item-label').html(labelName || 'Payment Item');
	});

	$('body').on('input', '.wordform-payment-item-amount', function() {
		let amount = $(this).val();
		let elementIndex = $(this).closest('.wordform-payment-item-field-options-wrapper').prop('id').split('-')[1];
		let formattedAmount = (amount && !isNaN(parseFloat(amount))) ? '$' + parseFloat(amount).toFixed(2) : '$0.00';
		$('#wordformElement-' + elementIndex + ' .wordform-payment-item-amount').html(formattedAmount);
		wordformRefreshBuilderPaymentSummary();
	});

	$('body').on('input', '.wordform-payment-item-description', function() {
		let description = $(this).val();
		let elementIndex = $(this).closest('.wordform-payment-item-field-options-wrapper').prop('id').split('-')[1];
		$('#wordformElement-' + elementIndex + ' .wordform-payment-item-description').html(description || 'Fixed price item');
	});

	$('body').on('input', '.wordform-payment-coupon-label-name', function() {
		let labelName = $(this).val();
		let elementIndex = $(this).closest('.wordform-payment-coupon-field-options-wrapper').prop('id').split('-')[1];
		$('#wordformElement-' + elementIndex + ' .wordform-payment-coupon-builder-title').html(labelName || 'Coupon Code');
	});

	$('body').on('input', '.wordform-payment-coupon-placeholder-text-input', function() {
		let placeholderText = $(this).val();
		let elementIndex = $(this).closest('.wordform-payment-coupon-field-options-wrapper').prop('id').split('-')[1];
		$('#wordformElement-' + elementIndex + ' .wordform-payment-coupon-builder-input').attr('placeholder', placeholderText || 'Enter coupon code');
	});

	$('body').on('input', '.wordform-payment-coupon-apply-button-text-input', function() {
		let buttonText = $(this).val();
		let elementIndex = $(this).closest('.wordform-payment-coupon-field-options-wrapper').prop('id').split('-')[1];
		$('#wordformElement-' + elementIndex + ' .wordform-payment-coupon-builder-button').html(buttonText || 'Apply Coupon');
	});

	$('body').on('input', '.wordform-payment-coupon-applied-message-input, .wordform-payment-coupon-invalid-message-input', function() {
		let $wrapper = $(this).closest('.wordform-payment-coupon-field-options-wrapper');
		let elementIndex = $wrapper.prop('id').split('-')[1];
		let previewText = $wrapper.find('.wordform-payment-coupon-applied-message-input').val() || 'Applied coupon feedback will appear here.';
		$('#wordformElement-' + elementIndex + ' .wordform-payment-coupon-builder-message').html(previewText);
	});

	function showHidePaymentCustomAmountOptions( elementOptionsWrapperID ) {
		$('.show-hide-common-class-all-options-wrapper-element').css('display', 'none');
		$('.show-hide-common-class-all-options-wrapper-element').promise().done(function() {
			$('#' + elementOptionsWrapperID).fadeIn();
		});
	}

	$('body').on('input', '.wordform-payment-custom-amount-label-name', function() {
		let labelName = $(this).val();
		let elementIndex = $(this).closest('.wordform-payment-custom-amount-field-options-wrapper').prop('id').split('-')[1];
		$('#wordformElement-' + elementIndex + ' .wordform-dropped-payment-custom-amount-label').html(labelName || 'Custom Amount');
	});

	$('body').on('input', '.wordform-payment-custom-amount-placeholder-text-input', function() {
		let placeholderText = $(this).val();
		let elementIndex = $(this).closest('.wordform-payment-custom-amount-field-options-wrapper').prop('id').split('-')[1];
		$('#wordformElement-' + elementIndex + ' .wordform-dropped-payment-custom-amount-name').attr('placeholder', placeholderText || 'Enter amount');
	});

	$('body').on('input', '.wordform-payment-custom-amount-default', function() {
		let defaultAmount = $(this).val();
		let elementIndex = $(this).closest('.wordform-payment-custom-amount-field-options-wrapper').prop('id').split('-')[1];
		$('#wordformElement-' + elementIndex + ' .wordform-dropped-payment-custom-amount-name').attr('value', defaultAmount || '').val(defaultAmount || '');
		wordformRefreshBuilderPaymentSummary();
	});

	$('body').on('input', '.wordform-payment-custom-amount-min', function() {
		let minAmount = $(this).val();
		let elementIndex = $(this).closest('.wordform-payment-custom-amount-field-options-wrapper').prop('id').split('-')[1];
		$('#wordformElement-' + elementIndex + ' .wordform-dropped-payment-custom-amount-name').attr('min', minAmount || '0');
	});

	function showHidePaymentQuantityOptions( elementOptionsWrapperID ) {
		$('.show-hide-common-class-all-options-wrapper-element').css('display', 'none');
		$('.show-hide-common-class-all-options-wrapper-element').promise().done(function() {
			$('#' + elementOptionsWrapperID).fadeIn();
		});
	}

	$('body').on('input', '.wordform-payment-quantity-label-name', function() {
		let labelName = $(this).val();
		let elementIndex = $(this).closest('.wordform-payment-quantity-field-options-wrapper').prop('id').split('-')[1];
		$('#wordformElement-' + elementIndex + ' .wordform-dropped-payment-quantity-label').html(labelName || 'Quantity');
	});

	$('body').on('input', '.wordform-payment-quantity-default-input', function() {
		let quantityValue = $(this).val();
		let elementIndex = $(this).closest('.wordform-payment-quantity-field-options-wrapper').prop('id').split('-')[1];
		$('#wordformElement-' + elementIndex + ' .wordform-dropped-payment-quantity-name').attr('value', quantityValue || '1').val(quantityValue || '1');
		wordformRefreshBuilderPaymentSummary();
	});

	$('body').on('input', '.wordform-payment-quantity-min-input', function() {
		let quantityValue = $(this).val();
		let elementIndex = $(this).closest('.wordform-payment-quantity-field-options-wrapper').prop('id').split('-')[1];
		$('#wordformElement-' + elementIndex + ' .wordform-dropped-payment-quantity-name').attr('min', quantityValue || '1');
	});

	$('body').on('input', '.wordform-payment-quantity-max-input', function() {
		let quantityValue = $(this).val();
		let elementIndex = $(this).closest('.wordform-payment-quantity-field-options-wrapper').prop('id').split('-')[1];
		$('#wordformElement-' + elementIndex + ' .wordform-dropped-payment-quantity-name').attr('max', quantityValue || '');
	});

	function showHidePaymentSummaryOptions( elementOptionsWrapperID ) {
		$('.show-hide-common-class-all-options-wrapper-element').css('display', 'none');
		$('.show-hide-common-class-all-options-wrapper-element').promise().done(function() {
			$('#' + elementOptionsWrapperID).fadeIn();
		});
	}

	$('body').on('input', '.wordform-payment-summary-label-name', function() {
		let labelName = $(this).val();
		let elementIndex = $(this).closest('.wordform-payment-summary-field-options-wrapper').prop('id').split('-')[1];
		$('#wordformElement-' + elementIndex + ' .wordform-payment-summary-title').html(labelName || 'Payment Summary');
	});

	$('body').on('input', '.wordform-payment-summary-empty-text-input', function() {
		let text = $(this).val();
		let elementIndex = $(this).closest('.wordform-payment-summary-field-options-wrapper').prop('id').split('-')[1];
		$('#wordformElement-' + elementIndex + ' .wordform-payment-summary-empty-text').data('empty-text', text || 'Amounts will appear here').html(text || 'Amounts will appear here');
	});

	function showHideStripeOptions( elementOptionsWrapperID ) {
		$('.show-hide-common-class-all-options-wrapper-element').css('display', 'none');
		$('.show-hide-common-class-all-options-wrapper-element').promise().done(function() {
			$('#' + elementOptionsWrapperID).fadeIn();
		});
	}

	$('body').on('input', '.wordform-stripe-label-name', function() {
		let labelName = $(this).val();
		let elementIndex = $(this).closest('.wordform-stripe-field-options-wrapper').prop('id').split('-')[1];
		$('#wordformElement-' + elementIndex + ' .wordform-dropped-stripe-label').html(labelName || 'Stripe Payment');
	});

	$('body').on('input', '.wordform-stripe-button-text-input', function() {
		let buttonText = $(this).val();
		let elementIndex = $(this).closest('.wordform-stripe-field-options-wrapper').prop('id').split('-')[1];
		$('#wordformElement-' + elementIndex + ' .wordform-dropped-stripe-button-text').html(buttonText || 'Pay with Card');
	});

	$('body').on('input', '.wordform-stripe-description-input', function() {
		let description = $(this).val();
		let elementIndex = $(this).closest('.wordform-stripe-field-options-wrapper').prop('id').split('-')[1];
		$('#wordformElement-' + elementIndex + ' .wordform-dropped-stripe-description').html(description || 'Secure card payment via Stripe');
	});

	function showHidePaypalOptions( elementOptionsWrapperID ) {
		$('.show-hide-common-class-all-options-wrapper-element').css('display', 'none');
		$('.show-hide-common-class-all-options-wrapper-element').promise().done(function() {
			$('#' + elementOptionsWrapperID).fadeIn();
		});
	}

	$('body').on('input', '.wordform-paypal-label-name', function() {
		let labelName = $(this).val();
		let elementIndex = $(this).closest('.wordform-paypal-field-options-wrapper').prop('id').split('-')[1];
		$('#wordformElement-' + elementIndex + ' .wordform-dropped-paypal-label').html(labelName || 'PayPal Payment');
	});

	$('body').on('input', '.wordform-paypal-button-text-input', function() {
		let buttonText = $(this).val();
		let elementIndex = $(this).closest('.wordform-paypal-field-options-wrapper').prop('id').split('-')[1];
		$('#wordformElement-' + elementIndex + ' .wordform-dropped-paypal-button-text').html(buttonText || 'Pay with PayPal');
	});

	$('body').on('input', '.wordform-paypal-description-input', function() {
		let description = $(this).val();
		let elementIndex = $(this).closest('.wordform-paypal-field-options-wrapper').prop('id').split('-')[1];
		$('#wordformElement-' + elementIndex + ' .wordform-dropped-paypal-description').html(description || 'Checkout with your PayPal account');
	});

	function showHideSquareOptions( elementOptionsWrapperID ) {
		$('.show-hide-common-class-all-options-wrapper-element').css('display', 'none');
		$('.show-hide-common-class-all-options-wrapper-element').promise().done(function() {
			$('#' + elementOptionsWrapperID).fadeIn();
		});
	}

	$('body').on('input', '.wordform-square-label-name', function() {
		let labelName = $(this).val();
		let elementIndex = $(this).closest('.wordform-square-field-options-wrapper').prop('id').split('-')[1];
		$('#wordformElement-' + elementIndex + ' .wordform-dropped-square-label').html(labelName || 'Square Payment');
	});

	$('body').on('input', '.wordform-square-button-text-input', function() {
		let buttonText = $(this).val();
		let elementIndex = $(this).closest('.wordform-square-field-options-wrapper').prop('id').split('-')[1];
		$('#wordformElement-' + elementIndex + ' .wordform-dropped-square-button-text').html(buttonText || 'Pay with Square');
	});

	$('body').on('input', '.wordform-square-description-input', function() {
		let description = $(this).val();
		let elementIndex = $(this).closest('.wordform-square-field-options-wrapper').prop('id').split('-')[1];
		$('#wordformElement-' + elementIndex + ' .wordform-dropped-square-description').html(description || 'Secure card payment via Square');
	});

	function showHideAuthorizeNetOptions( elementOptionsWrapperID ) {
		$('.show-hide-common-class-all-options-wrapper-element').css('display', 'none');
		$('.show-hide-common-class-all-options-wrapper-element').promise().done(function() {
			$('#' + elementOptionsWrapperID).fadeIn();
		});
	}

	$('body').on('input', '.wordform-authorizenet-label-name', function() {
		let labelName = $(this).val();
		let elementIndex = $(this).closest('.wordform-authorizenet-field-options-wrapper').prop('id').split('-')[1];
		$('#wordformElement-' + elementIndex + ' .wordform-dropped-authorizenet-label').html(labelName || 'Authorize.Net Payment');
	});

	$('body').on('input', '.wordform-authorizenet-button-text-input', function() {
		let buttonText = $(this).val();
		let elementIndex = $(this).closest('.wordform-authorizenet-field-options-wrapper').prop('id').split('-')[1];
		$('#wordformElement-' + elementIndex + ' .wordform-dropped-authorizenet-button-text').html(buttonText || 'Pay with Authorize.Net');
	});

	$('body').on('input', '.wordform-authorizenet-description-input', function() {
		let description = $(this).val();
		let elementIndex = $(this).closest('.wordform-authorizenet-field-options-wrapper').prop('id').split('-')[1];
		$('#wordformElement-' + elementIndex + ' .wordform-dropped-authorizenet-description').html(description || 'Secure card payment via Authorize.Net');
	});


	/*** Submit-button Element ***/
	
	// Submit-button: Hide all options wrapper - then show only the working one
	function showHideSubmitButtonOptions( elementOptionsWrapperID ) {
		 $('.show-hide-common-class-all-options-wrapper-element').css('display', 'none');
		 $('.show-hide-common-class-all-options-wrapper-element').promise().done(function() {			 
			 $('#'+elementOptionsWrapperID).fadeIn();
		 }); 		
	}
	
	// Submit-button: Wordform create form submit button element options display
	$('body').on("click", ".wordform-input-element-div-wrapper-submit-button", function() {		
		let elementID					= $(this).prop("id");
		let elementIndex				= elementID.split("-")[1];		
		let elementOptionsWrapperID		= 'wordformElementOptions-'+ elementIndex;
		showHideSubmitButtonOptions( elementOptionsWrapperID );	
		setSelectedDroppedElementBackground( elementIndex );				
	});
	
	// Submit-button: Submit button Label Text
	$('body').on("input", ".wordform-submit-button-label-input", function() {
		let labelName		= $(this).val();
		let elementIndex	= $(this).closest('.wordform-submit-button-field-options-wrapper').prop("id").split("-")[1];														
		$('#wordformElement-'+elementIndex+' button').text(labelName);		
	});
	
	// Submit-button: Submit button Align
	$('body').on("change", ".wordform-build-submit-button-align-input", function() {	
		$('.wordform-build-submit-button-align-input').attr('checked', false );	
		let submitAlignVal		= $(this).val();				
		let elementIndex	= $(this).closest('.wordform-submit-button-field-options-wrapper').prop("id").split("-")[1];																		
		// $('.wordform-input-element-div-wrapper-submit-button').css('text-align', submitAlignVal );
		$('.wordform-input-element-div-wrapper-submit-button').removeClass('left right center');
		$('.wordform-input-element-div-wrapper-submit-button').addClass(submitAlignVal );
		$(this).attr('checked', true );
	});

	// Submit-button: Make full width button -  Detect change on the full width checkbox
	$(document).on('change', '.wordform-submit-button-full-width-input-checkbox', function() {
		// Target the submit button
		let $button = $('.wordform-admin-create-form-submit-button');

		if ($(this).is(':checked')) {
			$(this).attr('checked', true );
			$button.addClass('wordform-button-full-width');
		} else {
			$(this).attr('checked', false );
			$button.removeClass('wordform-button-full-width');
		}
	});	
	
	/*** Form-Name Element ***/
	
	// Form-name: Hide all options wrapper - then show only the working one
	function showHideFormNameOptions( elementOptionsWrapperID ) {
		 $('.show-hide-common-class-all-options-wrapper-element').css('display', 'none');
		 $('.show-hide-common-class-all-options-wrapper-element').promise().done(function() {			 
			 $('#'+elementOptionsWrapperID).fadeIn();
		 }); 		
	}
	
	// Form-name: Wordform create form form name element options display
	$('body').on("click", ".wordform-input-element-div-wrapper-form-name", function() {		
		let elementID					= $(this).prop("id");
		let elementIndex				= elementID.split("-")[1];		
		let elementOptionsWrapperID		= 'wordformElementOptions-'+ elementIndex;
		showHideFormNameOptions( elementOptionsWrapperID );	
		setSelectedDroppedElementBackground( elementIndex );				
	});
	
	// Form-name: Form Name Label Text
	$('body').on("input", ".wordform-form-name-label-input", function() {
		let labelName		= $(this).val();		
		let elementIndex	= $(this).closest('.wordform-form-name-field-options-wrapper').prop("id").split("-")[1];														
		$('#wordformElement-'+elementIndex+' span').html(labelName);	
	});

	// Form-Name: Form Name Label Align
	$('body').on("change", ".wordform-build-form-name-align-input", function() {	
		$('.wordform-build-form-name-align-input').attr('checked', false);		
		let formNameAlignVal		= $(this).val();				
		let elementIndex	= $(this).closest('.wordform-form-name-field-options-wrapper').prop("id").split("-")[1];																		
		// $('.wordform-input-element-div-wrapper-form-name').css('text-align', formNameAlignVal );
		$('.wordform-input-element-div-wrapper-form-name').removeClass('left right center');
		$('.wordform-input-element-div-wrapper-form-name').addClass(formNameAlignVal );
		$(this).attr('checked', true);		
	});

	function getWordformActiveElementMeta(elementType) {
		const metaMap = {
			'form-name': { icon: 'fa-solid fa-heading', title: 'Form Name', subtitle: 'Form-level settings', hint: 'Set a clear form title so users and reports can identify the form quickly.' },
			'submit-button': { icon: 'fa-solid fa-paper-plane', title: 'Submit Button', subtitle: 'Button text and alignment', hint: 'Keep the button label action-focused, especially for payment or multi-step forms.' },
			'text': { icon: 'fa-regular fa-user', title: 'Single Name', subtitle: 'Field settings', hint: 'Use concise labels and placeholders so users can complete the field quickly.' },
			'firstlastname': { icon: 'fa-regular fa-address-card', title: 'First & Last Name', subtitle: 'Field settings', hint: 'Use this when you need first and last names stored separately for reports or integrations.' },
			'address': { icon: 'fa-solid fa-location-dot', title: 'Address', subtitle: 'Field settings', hint: 'Use Address instead of separate text fields when location details need consistent structure.' },
			'number': { icon: 'fa-solid fa-arrow-up-1-9', title: 'Number', subtitle: 'Field settings', hint: 'Use clear min/max guidance when only certain numeric values are valid.' },
			'textarea': { icon: 'fa-solid fa-text-width', title: 'Description', subtitle: 'Field settings', hint: 'Long-answer fields work best with a descriptive label or help text so users know what detail is expected.' },
			'sectionhtml': { icon: 'fa-solid fa-rectangle-list', title: 'Section / HTML', subtitle: 'Content block settings', hint: 'Use this for headings, instructions, or content blocks that should not collect submission data.' },
			'select': { icon: 'fa-solid fa-square-caret-down', title: 'Dropdown Options', subtitle: 'Choice settings', hint: 'Use dropdowns when the option list is long and only one value should be selected.' },
			'checkbox': { icon: 'fa-solid fa-square-check', title: 'Checkboxes', subtitle: 'Choice settings', hint: 'Use checkboxes when users should be allowed to select more than one option.' },
			'radio': { icon: 'fa-regular fa-circle-dot', title: 'Multiple Choice', subtitle: 'Choice settings', hint: 'Use multiple choice when users should select exactly one option from a short list.' },
			'range': { icon: 'fa-solid fa-sliders', title: 'Range Slider', subtitle: 'Field settings', hint: 'Range sliders work best for quick scoring or rating inputs where exact typing is not needed.' },
			'url': { icon: 'fa-solid fa-link', title: 'URL', subtitle: 'Field settings', hint: 'Use this field when you want to collect websites, profile links, or resource URLs.' },
			'date': { icon: 'fa-solid fa-calendar', title: 'Date', subtitle: 'Field settings', hint: 'Use Date when time is not required. Min/Max Date are fixed limits. Disable Past/Future works relative to today and is useful when the allowed window should move automatically over time.' },
			'time': { icon: 'fa-regular fa-clock', title: 'Time', subtitle: 'Field settings', hint: 'Use Time for appointments, delivery windows, or schedules where only time input is needed.' },
			'datetime': { icon: 'fa-regular fa-clock', title: 'Datetime', subtitle: 'Field settings', hint: 'Use Datetime for bookings, schedules, or records that require both date and time. Min/Max Datetime are fixed limits. Disable Past/Future works relative to the current date and time when availability should move automatically.' },
			'tel': { icon: 'fa-solid fa-phone', title: 'Tel', subtitle: 'Field settings', hint: 'Use Tel with a clear format or mask when you need consistent phone numbers.' },
			'email': { icon: 'fa-solid fa-at', title: 'Email', subtitle: 'Field settings', hint: 'Use Email when submissions or integrations depend on a valid email address.' },
			'richeditor': { icon: 'fa-solid fa-pen-to-square', title: 'Rich Text Editor', subtitle: 'Formatted content field settings', hint: 'Use this when users need richer responses with formatting such as paragraphs, lists, emphasis, or links.' },
			'upload': { icon: 'fa-solid fa-upload', title: 'Upload', subtitle: 'Upload field settings', hint: 'Set allowed file types and size limits clearly so users know what can be uploaded.' },
			'maskinput': { icon: 'fa-regular fa-keyboard', title: 'Mask Input', subtitle: 'Field settings', hint: 'Use a clear pattern for IDs, policy numbers, phone formats, or other strict text formats.' },
			'rating': { icon: 'fa-solid fa-star', title: 'Rating', subtitle: 'Rating field settings', hint: 'Use Rating for quick satisfaction, review, or score-based feedback where users should select a star value.' },
			'likert': { icon: 'fa-solid fa-table-list', title: 'Likert / Matrix', subtitle: 'Matrix field settings', hint: 'Use this for surveys where each row should receive one answer from the same response scale.' },
			'signature': { icon: 'fa-solid fa-signature', title: 'Signature', subtitle: 'Signature field settings', hint: 'Use this for approvals, consent, deliveries, or acknowledgements that need a handwritten signature area.' },
			'hidden': { icon: 'fa-solid fa-eye-slash', title: 'Hidden Field', subtitle: 'Hidden field settings', hint: 'Use hidden fields for internal values, tracking, or page context that should submit silently.' },
			'pagebreak': { icon: 'fa-solid fa-forward-step', title: 'Page Break', subtitle: 'Step navigation settings', hint: 'Place page breaks between real fields only. Keep captcha and payment gateways on the final step with the submit button.' },
			'captcha': { icon: 'fa-solid fa-shield', title: 'Numeric Captcha', subtitle: 'Security settings', hint: 'Use one captcha approach per form for a cleaner user flow.' },
			'gcaptcha': { icon: 'fa-brands fa-google', title: 'Google reCaptcha', subtitle: 'Security settings', hint: 'Use one captcha provider per form. Avoid combining Google reCaptcha and hCaptcha in the same form.' },
			'hcaptcha': { icon: 'fa-solid fa-shield-halved', title: 'hCaptcha', subtitle: 'Security settings', hint: 'Use one captcha provider per form. Avoid combining hCaptcha and Google reCaptcha in the same form.' },
			'terms': { icon: 'fa-regular fa-file-lines', title: 'Terms & Conditions', subtitle: 'Consent settings', hint: 'Place this near the end of the form so users can review and accept terms before submission.' },
			'gdpr': { icon: 'fa-solid fa-shield-heart', title: 'GDPR Consent', subtitle: 'Consent settings', hint: 'Use this for privacy policy and data-processing consent. Place it near the end of the form before submission.' },
			'payment_method': { icon: 'fa-solid fa-credit-card', title: 'Payment Method', subtitle: 'Gateway selector settings', hint: 'This element is a payment selector/controller. Add at least one payment gateway like Stripe, PayPal, Square, or Authorize.Net for it to control.' },
			'payment_item': { icon: 'fa-solid fa-tag', title: 'Payment Item', subtitle: 'Item pricing settings', hint: 'Use fixed item pricing here. Combine with Quantity, Coupon, and Payment Summary for a complete checkout flow.' },
			'payment_custom_amount': { icon: 'fa-solid fa-money-bill-wave', title: 'Custom Amount', subtitle: 'Payment field settings', hint: 'Use this for donation-style or flexible-amount forms where users enter their own amount.' },
			'payment_quantity': { icon: 'fa-solid fa-hashtag', title: 'Quantity', subtitle: 'Payment field settings', hint: 'Quantity works best when paired with a fixed Payment Item and Payment Summary.' },
			'payment_summary': { icon: 'fa-solid fa-receipt', title: 'Payment Summary', subtitle: 'Summary display settings', hint: 'Keep Payment Summary near coupon and gateway fields so users can review the final amount before paying.' },
			'payment_coupon': { icon: 'fa-solid fa-ticket', title: 'Coupon', subtitle: 'Discount field settings', hint: 'Coupons validate against codes created in Settings > Coupons and update the total before checkout.' },
			'stripe': { icon: 'fa-brands fa-stripe', title: 'Stripe', subtitle: 'Gateway settings', hint: 'Place payment gateways on the final step. For multiple gateways, add Payment Method so users can choose one gateway.' },
			'paypal': { icon: 'fa-brands fa-paypal', title: 'PayPal', subtitle: 'Gateway settings', hint: 'Place payment gateways on the final step. For multiple gateways, add Payment Method so users can choose one gateway.' },
			'square': { icon: 'fa-solid fa-square', title: 'Square', subtitle: 'Gateway settings', hint: 'Place payment gateways on the final step. For multiple gateways, add Payment Method so users can choose one gateway.' },
			'authorizenet': { icon: 'fa-solid fa-lock', title: 'Authorize.Net', subtitle: 'Gateway settings', hint: 'Place payment gateways on the final step. For multiple gateways, add Payment Method so users can choose one gateway.' }
		};

		const baseMeta = metaMap[elementType] || {
			icon: 'fa-solid fa-sliders',
			title: 'Field Settings',
			subtitle: 'Selected field settings',
			hint: ''
		};

		if (wordformElementSupportsSharedFieldWidth(elementType)) {
			const widthHint = ' Field Width: Half and One Third widths can sit beside other fields on larger screens and stack automatically on smaller screens.';
			baseMeta.hint = (baseMeta.hint || '') + widthHint;
		}

		if (elementType === 'date' || elementType === 'datetime') {
			const siteTimezone = String((window.sc_wordform_metabox_script_obj && (sc_wordform_metabox_script_obj.wordform_site_timezone_label || sc_wordform_metabox_script_obj.wordform_site_timezone_name)) || 'UTC').trim();
			const currentSiteDate = String((window.sc_wordform_metabox_script_obj && sc_wordform_metabox_script_obj.wordform_current_site_date) || '').trim();
			const currentSiteDateTime = String((window.sc_wordform_metabox_script_obj && sc_wordform_metabox_script_obj.wordform_current_site_datetime) || '').trim();
			if (elementType === 'date' && currentSiteDate.length) {
				baseMeta.hint = (baseMeta.hint || '') + ' Uses WordPress site timezone: ' + siteTimezone + '. Current site date: ' + currentSiteDate + '.';
			}
			if (elementType === 'datetime' && currentSiteDateTime.length) {
				baseMeta.hint = (baseMeta.hint || '') + ' Uses WordPress site timezone: ' + siteTimezone + '. Current site datetime: ' + currentSiteDateTime + '.';
			}
		}

		return baseMeta;
	}

	function updateWordformActiveElementHeader($element) {
		const $header = $('.wordform-builder-active-element-header');
		if (!$header.length || !$element || !$element.length) {
			return;
		}

		const meta = getWordformActiveElementMeta($element.data('input-element-type'));
		$header.find('.wordform-builder-active-element-icon').html('<i class="' + meta.icon + '" aria-hidden="true"></i>');
		$header.find('.wordform-builder-active-element-title').text(meta.title);
		$header.find('.wordform-builder-active-element-subtitle').text(meta.subtitle);
		const $hint = $header.find('.wordform-builder-active-element-hint');
		$header.find('.wordform-builder-active-element-hint-text').text(meta.hint || '');
		$hint.toggleClass('is-hidden', !(meta.hint && meta.hint.length));
	}

	function showWordformOptionsForElement($element) {
		if (!$element || !$element.length) {
			return;
		}

		const elementIndex = $element.data('element-index') || (($element.prop('id') || '').split('-')[1]);
		const elementType = $element.data('input-element-type');
		const elementOptionsWrapperID = 'wordformElementOptions-' + elementIndex;

		switch (elementType) {
			case 'text':
				showHideTextOptions(elementOptionsWrapperID);
				break;
			case 'firstlastname':
				showHideFirstLastNameOptions(elementOptionsWrapperID);
				break;
			case 'number':
				showHideNumberOptions(elementOptionsWrapperID);
				break;
			case 'textarea':
				showHideTextareaOptions(elementOptionsWrapperID);
				break;
			case 'range':
				showHideRangeOptions(elementOptionsWrapperID);
				break;
			case 'url':
				showHideUrlOptions(elementOptionsWrapperID);
				break;
			case 'date':
				showHideDateOptions(elementOptionsWrapperID);
				break;
			case 'time':
				showHideTimeOptions(elementOptionsWrapperID);
				break;
			case 'datetime':
				showHideDatetimeOptions(elementOptionsWrapperID);
				break;
			case 'tel':
				showHideTelOptions(elementOptionsWrapperID);
				break;
			case 'radio':
				showHideRadioOptions(elementOptionsWrapperID);
				break;
			case 'checkbox':
				showHideCheckboxOptions(elementOptionsWrapperID);
				break;
			case 'select':
				showHideSelectOptions(elementOptionsWrapperID);
				break;
			case 'email':
				showHideEmailOptions(elementOptionsWrapperID);
				break;
			case 'address':
				showHideAddressOptions(elementOptionsWrapperID);
				break;
			case 'sectionhtml':
				showHideSectionHtmlOptions(elementOptionsWrapperID);
				break;
			case 'maskinput':
				showHideMaskInputOptions(elementOptionsWrapperID);
				break;
			case 'hidden':
				showHideHiddenOptions(elementOptionsWrapperID);
				break;
			case 'captcha':
				showHideCaptchaOptions(elementOptionsWrapperID);
				break;
			case 'gcaptcha':
				showHideGoogleCaptchaOptions(elementOptionsWrapperID);
				break;
			case 'hcaptcha':
				showHideHCaptchaOptions(elementOptionsWrapperID);
				break;
			case 'upload':
				showHideUploadOptions(elementOptionsWrapperID);
				break;
			case 'rating':
				showHideRatingOptions(elementOptionsWrapperID);
				break;
			case 'richeditor':
				showHideRichEditorOptions(elementOptionsWrapperID);
				break;
			case 'likert':
				showHideLikertOptions(elementOptionsWrapperID);
				break;
			case 'signature':
				showHideSignatureOptions(elementOptionsWrapperID);
				break;
			case 'pagebreak':
				showHidePageBreakOptions(elementOptionsWrapperID);
				break;
			case 'terms':
				showHideTermsOptions(elementOptionsWrapperID);
				break;
			case 'gdpr':
				showHideGdprOptions(elementOptionsWrapperID);
				break;
			case 'payment_item':
				showHidePaymentItemOptions(elementOptionsWrapperID);
				break;
			case 'payment_coupon':
				showHidePaymentCouponOptions(elementOptionsWrapperID);
				break;
			case 'payment_method':
				showHidePaymentMethodOptions(elementOptionsWrapperID);
				break;
			case 'payment_custom_amount':
				showHidePaymentCustomAmountOptions(elementOptionsWrapperID);
				break;
			case 'payment_quantity':
				showHidePaymentQuantityOptions(elementOptionsWrapperID);
				break;
			case 'payment_summary':
				showHidePaymentSummaryOptions(elementOptionsWrapperID);
				break;
			case 'stripe':
				showHideStripeOptions(elementOptionsWrapperID);
				break;
			case 'paypal':
				showHidePaypalOptions(elementOptionsWrapperID);
				break;
			case 'square':
				showHideSquareOptions(elementOptionsWrapperID);
				break;
			case 'authorizenet':
				showHideAuthorizeNetOptions(elementOptionsWrapperID);
				break;
			case 'submit-button':
				showHideSubmitButtonOptions(elementOptionsWrapperID);
				break;
			case 'form-name':
				showHideFormNameOptions(elementOptionsWrapperID);
				break;
			default:
				return;
		}

		updateWordformActiveElementHeader($element);
		setSelectedDroppedElementBackground(elementIndex);
	}

	function syncWordformInitialSelectedElement(preferredSelector = '') {
		let $selectedElement = preferredSelector ? $(preferredSelector).first() : $();

		if (!$selectedElement.length) {
			$selectedElement = $('.wordform-input-element-div-wrapper.wordform-selected-dropped-element-background-color').first();
		}

		if (!$selectedElement.length) {
			const $visibleOptions = $('.show-hide-common-class-all-options-wrapper-element:visible').first();
			if ($visibleOptions.length) {
				const optionIndex = (($visibleOptions.prop('id') || '').split('-')[1]) || '';
				if (optionIndex) {
					$selectedElement = $('#wordformElement-' + optionIndex);
				}
			}
		}

		if (!$selectedElement.length) {
			$selectedElement = $('.wordform-input-element-div-wrapper-form-name').first();
		}

		if (!$selectedElement.length) {
			$selectedElement = $('.wordform-input-element-div-wrapper').first();
		}

		showWordformOptionsForElement($selectedElement);
	}

	/**
	 * Builder reconstruction
	 * Rebuild edit canvas from the saved structured form definition so edit mode
	 * stays aligned with the current builder templates and logic.
	 */
	function parseWordformBoolean(value) {
		return value === true || value === 'true' || value === 1 || value === '1';
	}

	function normalizeWordformOptionValue(value, fallback = '') {
		if (typeof value === 'undefined' || value === null) {
			return fallback;
		}
		return String(value).trim();
	}

	function getWordformMatchingRadioByValue($scope, selector, value, fallbackValue = '') {
		const normalizedValue = normalizeWordformOptionValue(value, fallbackValue);
		let $match = $scope.find(`${selector}[value="${normalizedValue}"]`);

		if ($match.length) {
			return $match;
		}

		const normalizedLower = normalizedValue.toLowerCase();
		$match = $scope.find(selector).filter(function () {
			return normalizeWordformOptionValue($(this).val()).toLowerCase() === normalizedLower;
		}).first();

		if ($match.length) {
			return $match;
		}

		return fallbackValue ? $scope.find(`${selector}[value="${fallbackValue}"]`).first() : $();
	}

	function setWordformFieldValue($field, value, triggerName = 'input') {
		if (!$field.length) {
			return;
		}
		$field.val(value);
		if ($field.is('input[type="text"], input[type="number"], input[type="email"], input[type="hidden"], textarea')) {
			$field.attr('value', value);
		}
		if (triggerName) {
			$field.trigger(triggerName);
		}
	}

	function scrollWordformBuilderToTop() {
		let $fullscreen = $('.wordform-fullscreen-wrapper');

		if ($fullscreen.length && $fullscreen.get(0).scrollHeight > $fullscreen.height()) {
			$fullscreen.stop().animate({ scrollTop: 0 }, 250);
			return;
		}

		$('html, body').stop().animate({ scrollTop: 0 }, 250);
	}

	function setWordformCheckboxState($field, isChecked, triggerName = 'change') {
		if (!$field.length) {
			return;
		}
		$field.prop('checked', !!isChecked);
		if (isChecked) {
			$field.attr('checked', 'checked');
		} else {
			$field.removeAttr('checked');
		}
		if (triggerName) {
			$field.trigger(triggerName);
		}
	}

	function waitForWordformElement(selector, timeoutMs = 5000) {
		return new Promise((resolve, reject) => {
			const startedAt = Date.now();
			const timer = setInterval(() => {
				const $element = $(selector);
				if ($element.length) {
					clearInterval(timer);
					resolve($element);
					return;
				}

				if (Date.now() - startedAt >= timeoutMs) {
					clearInterval(timer);
					reject(new Error(`Timed out waiting for ${selector}`));
				}
			}, 30);
		});
	}

	function getWordformBuilderReconstructionPayload() {
		const $dataField = $('.wordform-builder-reconstruction-data');
		if (!$dataField.length) {
			return null;
		}

		try {
			const formData = JSON.parse($dataField.val() || '[]');
			if (!Array.isArray(formData)) {
				return null;
			}

			return {
				formData,
				formId: $('.wordform-builder-reconstruction-form-id').val() || '',
				previewUrl: $('.wordform-builder-reconstruction-preview-url').val() || '#',
				builderSchemaVersion: parseInt($('.wordform-builder-schema-version').val() || '1', 10)
			};
		} catch (error) {
			console.error('WordForm builder reconstruction payload parse failed.', error);
			return null;
		}
	}

	function getWordformBuilderTemplatesRegistry() {
		const $templateDataField = $('.wordform-builder-templates-registry');

		if (!$templateDataField.length) {
			return [];
		}

		try {
			const templates = JSON.parse($templateDataField.val() || '[]');
			return Array.isArray(templates) ? templates : [];
		} catch (error) {
			console.error('WordForm templates registry parse failed.', error);
			return [];
		}
	}

	function escapeWordformHtml(text) {
		return $('<div></div>').text(text || '').html();
	}

	function resetWordformBuilderCanvas(options = {}) {
		const preservedFormId = typeof options.formId !== 'undefined' ? options.formId : ($('.wordform-created-form-id').val() || '');

		$('.wordform-dropzone-div-wrapper').empty();
		$('.wordform-builder-form-options-div-wrapper')
			.find('.show-hide-common-class-all-options-wrapper-element')
			.not('#wordformElementOptions-1, #wordformElementOptions-2')
			.remove();

		$('.wordform-input-element-div-wrapper').removeClass('wordform-selected-dropped-element-background-color');
		$('.show-hide-common-class-all-options-wrapper-element').hide();
		$('.wordform-form-builder-element-number').val(2);
		$('.wordform-form-saved').val('false');
		$('.wordform-created-form-id').val(preservedFormId);
		$('.wordform-message-info').empty();

		setWordformCheckboxState($('.wordform-form-name-display-checkbox'), false, null);
		setWordformFieldValue($('.wordform-form-name-label-input'), 'New Form');
		setWordformFieldValue($('.wordform-form-name-class-names-input'), '', null);
		setWordformCheckboxState(getWordformMatchingRadioByValue($(document), '.wordform-build-form-name-align-input', 'center', 'center'), true, 'change');

		setWordformFieldValue($('.wordform-submit-button-label-input'), 'Submit');
		setWordformCheckboxState($('.wordform-submit-button-full-width-input-checkbox'), false, 'change');
		setWordformCheckboxState(getWordformMatchingRadioByValue($(document), '.wordform-build-submit-button-align-input', 'left', 'left'), true, 'change');

		if (options.disablePreview) {
			$('.wordform-preview-btn').prop('href', '#').addClass('disabled');
		}
	}

	async function loadWordformStructuredBuilderPayload(payload, options = {}) {
		if (!payload || !Array.isArray(payload.formData) || !payload.formData.length) {
			return;
		}

		wordformBuilderReconstructionInProgress = true;

		try {
			resetWordformBuilderCanvas({
				formId: typeof options.formId !== 'undefined' ? options.formId : (payload.formId || ''),
				disablePreview: !!options.disablePreview
			});

			const formMetaElements = payload.formData.filter((element) => element.type === 'form-name' || element.type === 'submit-button');
			const builderElements = payload.formData.filter((element) => element.type !== 'form-name' && element.type !== 'submit-button');

			formMetaElements.forEach((element) => applyWordformFormMeta(element));

			if (!options.disablePreview && payload.previewUrl) {
				$('.wordform-preview-btn').prop('href', payload.previewUrl).removeClass('disabled');
			}

			for (const element of builderElements) {
				if (wordformIsBuilderElementBlocked(element.type)) {
					continue;
				}

				createWordformBuilderElementFromSavedType(element.type);
				const $builderElement = $('.wordform-dropzone-div-wrapper .wordform-input-element-div-wrapper:last');
				const elementIndex = $builderElement.data('element-index');
				if (!elementIndex) {
					continue;
				}

				const $optionsWrapper = await waitForWordformElement(`#wordformElementOptions-${elementIndex}`);
				applyWordformElementState($builderElement, $optionsWrapper, element);
			}

			$('.wordform-datetime-field-options-wrapper').each(function () {
				initWrapper($(this));
			});
		} finally {
			wordformBuilderReconstructionInProgress = false;
		}

		syncWordformInitialSelectedElement('.wordform-input-element-div-wrapper-form-name');
		scrollWordformBuilderToTop();
	}

	function createWordformBuilderElementFromSavedType(type) {
		if (wordformIsBuilderElementBlocked(type)) {
			return null;
		}

		const typeMap = {
			text: 'singletext',
			firstlastname: 'firstlastname',
			number: 'singlenumber',
			textarea: 'multitext',
			address: 'address',
			sectionhtml: 'sectionhtml',
			maskinput: 'maskinput',
			hidden: 'hidden',
			select: 'select',
			checkbox: 'checkbox',
			radio: 'radio',
			range: 'range',
			url: 'url',
			date: 'date',
			time: 'time',
			datetime: 'datetime',
			tel: 'tel',
			email: 'email',
			address: 'address',
			sectionhtml: 'sectionhtml',
			maskinput: 'maskinput',
			hidden: 'hidden',
			captcha: 'captcha',
			gcaptcha: 'gcaptcha',
			hcaptcha: 'hcaptcha',
			upload: 'upload',
			rating: 'rating',
			likert: 'likert',
			richeditor: 'richeditor',
			signature: 'signature',
			pagebreak: 'pagebreak',
			terms: 'terms',
			gdpr: 'gdpr',
			payment_item: 'payment_item',
			payment_coupon: 'payment_coupon',
			payment_method: 'payment_method',
			payment_custom_amount: 'payment_custom_amount',
			payment_quantity: 'payment_quantity',
			payment_summary: 'payment_summary',
			stripe: 'stripe',
			paypal: 'paypal',
			square: 'square',
			authorizenet: 'authorizenet'
		};

		if (!typeMap[type]) {
			return null;
		}

		return generateTargetElement(typeMap[type], true);
	}

	let wordformHiddenBuilderElementsCache = null;

	function wordformGetHiddenBuilderElements() {
		if (wordformHiddenBuilderElementsCache !== null) {
			return wordformHiddenBuilderElementsCache;
		}

		const rawValue = $('.wordform-tier-hidden-builder-elements').first().val() || '[]';

		try {
			const parsed = JSON.parse(rawValue);
			wordformHiddenBuilderElementsCache = Array.isArray(parsed) ? parsed.map(String) : [];
		} catch (e) {
			wordformHiddenBuilderElementsCache = [];
		}

		return wordformHiddenBuilderElementsCache;
	}

	function wordformGetUpgradeUrl() {
		const rawUrl = $('.wordform-upgrade-url').first().val() || 'https://softcoy.com/products/wordform-pro/checkout';
		return String(rawUrl);
	}

	function wordformOpenUpgradeUrl() {
		const upgradeUrl = wordformGetUpgradeUrl();
		if (!upgradeUrl) {
			return;
		}
		window.open(upgradeUrl, '_blank', 'noopener');
	}

	function wordformIsBuilderElementBlocked(type) {
		if (!type) {
			return false;
		}

		return wordformGetHiddenBuilderElements().includes(String(type));
	}

	function wordformApplyTierBuilderRestrictions() {
		const blockedElements = wordformGetHiddenBuilderElements();
		if (!blockedElements.length) {
			return;
		}

		blockedElements.forEach(function(type) {
			const $button = $('.wordform-drag-elements-button[data-wordform-element-name="' + type + '"]');
			const $wrapper = $button.closest('.draggable-form-element-wrapper');

			if (!$button.length || !$wrapper.length) {
				return;
			}

			$wrapper.addClass('wordform-pro-locked-builder-element');
			$button
				.addClass('wordform-pro-locked-trigger')
				.attr('aria-disabled', 'true')
				.attr('aria-label', 'Get Pro')
				.attr('data-wordform-locked-tooltip', 'Get Pro')
				.removeAttr('title');

			if ($button.hasClass('ui-draggable')) {
				$button.draggable('disable');
			}
		});
	}

	function ensureWordformOptionItems($wrapper, addSelector, targetCount) {
		const currentOptionCount = Math.max(0, $wrapper.find('.wordform-field-options li').length - 1);
		for (let i = currentOptionCount; i < targetCount; i++) {
			$wrapper.find(addSelector).trigger('click');
		}
	}

	function applyWordformCommonFlags($wrapper, element) {
		if (Object.prototype.hasOwnProperty.call(element, 'required')) {
			setWordformCheckboxState($wrapper.find('.required-checkbox'), parseWordformBoolean(element.required), null);
		}
	}

	function applyWordformAdminLabelState($wrapper, element) {
		const elementType = wordformGetOptionsWrapperType($wrapper);
		const elementIndex = (($wrapper.prop('id') || '').split('-')[1]) || '';

		if (!wordformElementSupportsAdminLabel(elementType) || !elementIndex) {
			return;
		}

		wordformEnsureInitialAdminLabelValues($wrapper, elementType, elementIndex, element);
	}

	function applyWordformSharedHelpTextState($builderElement, $wrapper, element) {
		const elementType = wordformGetOptionsWrapperType($wrapper);

		if (!wordformElementSupportsSharedHelpText(elementType)) {
			return;
		}

		wordformEnsureInitialSharedHelpTextValue($wrapper, $builderElement, elementType, element);
	}

	function applyWordformSharedFieldWidthState($wrapper, element) {
		const elementType = wordformGetOptionsWrapperType($wrapper);

		if (!wordformElementSupportsSharedFieldWidth(elementType)) {
			return;
		}

		wordformEnsureInitialSharedFieldWidthValue($wrapper, elementType, element);
		wordformSetBuilderFieldWidthPreview(
			$('#wordformElement-' + ((($wrapper.prop('id') || '').split('-')[1]) || '')),
			elementType,
			(element && element.fieldWidth) ? element.fieldWidth : 'full'
		);
	}

	function applyWordformSharedCustomClassState($wrapper, element) {
		const elementType = wordformGetOptionsWrapperType($wrapper);

		if (!wordformElementSupportsSharedCustomClass(elementType)) {
			return;
		}

		wordformEnsureInitialSharedCustomClassValue($wrapper, elementType, element);
	}

	function applyWordformSharedDefaultValueState($builderElement, $wrapper, element) {
		const elementType = wordformGetOptionsWrapperType($wrapper);

		if (!wordformElementSupportsSharedDefaultValue(elementType)) {
			return;
		}

		wordformEnsureInitialSharedDefaultValue($wrapper, $builderElement, elementType, element);
	}

	function applyWordformFormMeta(element) {
		if (element.type === 'form-name') {
			setWordformFieldValue($('.wordform-form-name-label-input'), element.label || 'New Form');
			setWordformFieldValue($('.wordform-form-name-class-names-input'), element.formClasses || '', null);
			setWordformCheckboxState($('.wordform-form-name-display-checkbox'), parseWordformBoolean(element.hide), null);
			if (element.align) {
				const $align = $(`.wordform-build-form-name-align-input[value="${element.align}"]`);
				setWordformCheckboxState($align, true, 'change');
			}
			return;
		}

		if (element.type === 'submit-button') {
			setWordformFieldValue($('.wordform-submit-button-label-input'), element.label || 'Submit');
			setWordformCheckboxState($('.wordform-submit-button-full-width-input-checkbox'), parseWordformBoolean(element.buttonFullWidth));
			if (element.align) {
				const $align = $(`.wordform-build-submit-button-align-input[value="${element.align}"]`);
				setWordformCheckboxState($align, true, 'change');
			}
		}
	}

	function applyWordformPreviewOnlyState($builderElement, element) {
		switch (element.type) {
			case 'address':
				$builderElement.find('.wordform-dropped-address-label').text(element.label || 'Address');
				$builderElement.find('.wordform-dropped-address-street')
					.data('wordform-placeholder', element.placeholderStreet || 'Street Address')
					.attr('placeholder', parseWordformBoolean(element.placeholderShow) ? (element.placeholderStreet || 'Street Address') : '');
				$builderElement.find('.wordform-dropped-address-city')
					.data('wordform-placeholder', element.placeholderCity || 'City')
					.attr('placeholder', parseWordformBoolean(element.placeholderShow) ? (element.placeholderCity || 'City') : '');
				$builderElement.find('.wordform-dropped-address-state')
					.data('wordform-placeholder', element.placeholderState || 'State / Region')
					.attr('placeholder', parseWordformBoolean(element.placeholderShow) ? (element.placeholderState || 'State / Region') : '');
				$builderElement.find('.wordform-dropped-address-zip')
					.data('wordform-placeholder', element.placeholderZip || 'ZIP / Postal Code')
					.attr('placeholder', parseWordformBoolean(element.placeholderShow) ? (element.placeholderZip || 'ZIP / Postal Code') : '');
				$builderElement.find('.wordform-dropped-address-country')
					.data('wordform-placeholder', element.placeholderCountry || 'Country')
					.attr('placeholder', parseWordformBoolean(element.placeholderShow) ? (element.placeholderCountry || 'Country') : '');
				break;
			case 'sectionhtml':
				$builderElement.find('.wordform-sectionhtml-builder-title').text(element.label || 'Section Title');
				$builderElement.find('.wordform-sectionhtml-builder-content').text(element.content || 'Add instructions, notes, or custom HTML content.');
				break;
			case 'richeditor':
				$builderElement.find('.wordform-richeditor-builder-title').text(element.label || 'Rich Text Editor');
				$builderElement.find('.wordform-richeditor-builder-surface').css('min-height', (element.minHeight || 180) + 'px');
				$builderElement.find('.wordform-richeditor-builder-placeholder')
					.text(element.placeholderText || 'Write your response...')
					.toggle(parseWordformBoolean(typeof element.placeholderShow === 'undefined' ? true : element.placeholderShow));
				break;
			case 'time':
				const timePreviewMode = (element.timeDisplayMode === '12h') ? '12h' : '24h';
				const timeRawValue = element.defaultTime || '';
				$builderElement.find('.wordform-dropped-time-label').text(element.label || 'Time');
				$builderElement.find('.wordform-dropped-time-name')
					.attr('placeholder', parseWordformBoolean(element.placeholderShow) ? (element.placeholderText || 'Select time') : '')
					.val(wordformFormatAdminTimeValue(timeRawValue, timePreviewMode))
					.attr('value', wordformFormatAdminTimeValue(timeRawValue, timePreviewMode));
				break;
			case 'maskinput':
				$builderElement.find('.wordform-dropped-maskinput-label').text(element.label || 'Masked Input');
				$builderElement.find('.wordform-dropped-maskinput-name')
					.data('wordform-placeholder', element.placeholderText || 'AB-12345')
					.attr('placeholder', parseWordformBoolean(element.placeholderShow) ? (element.placeholderText || 'AB-12345') : '');
				$builderElement.find('.wordform-maskinput-builder-pattern code').text(element.pattern || '^[A-Z]{2}-[0-9]{5}$');
				break;
			case 'rating':
				$builderElement.find('.wordform-rating-builder-title').text(element.label || 'Rating');
				$builderElement.find('.wordform-rating-builder-stars').html(wordformBuildRatingBuilderStars(element.scale || 5));
				$builderElement.find('.wordform-rating-builder-low').text(element.lowText || 'Poor');
				$builderElement.find('.wordform-rating-builder-high').text(element.highText || 'Excellent');
				break;
			case 'likert':
				$builderElement.find('.wordform-likert-builder-title').text(element.label || 'Likert Scale');
				$builderElement.find('.wordform-likert-builder-matrix').html(
					wordformBuildLikertBuilderPreview(
						Array.isArray(element.rowLabels) ? element.rowLabels : wordformGetLikertDefaultRows(),
						Array.isArray(element.columnLabels) ? element.columnLabels : wordformGetLikertDefaultColumns()
					)
				);
				break;
			case 'signature':
				$builderElement.find('.wordform-signature-builder-title').text(element.label || 'Signature');
				$builderElement.find('.wordform-signature-builder-clear').text(element.clearButtonText || 'Clear Signature');
				$builderElement.find('.wordform-signature-builder-canvas').css('height', (element.canvasHeight || 180) + 'px');
				break;
			case 'hidden':
				$builderElement.find('.wordform-hidden-builder-title').text(element.label || 'Hidden Field');
				$builderElement.find('.wordform-hidden-builder-value').text('Value: ' + (element.defaultValue || 'utm_source'));
				break;
			case 'payment_method':
				$builderElement.find('.wordform-payment-method-builder-title').text(element.label || 'Payment Method');
				$builderElement.find('.wordform-payment-method-builder-helper-text').text(element.helperText || 'Choose how you want to pay');
				wordformSetBuilderPaymentMethodPreview($builderElement.data('element-index'), element.defaultGateway || 'stripe');
				break;
			case 'payment_item':
				$builderElement.find('.wordform-payment-item-label').text(element.label || 'Payment Item');
				$builderElement.find('.wordform-payment-item-amount').text(wordformBuilderFormatPaymentAmount(element.amount || 0));
				$builderElement.find('.wordform-payment-item-description').text(element.description || 'Fixed price item');
				break;
			case 'payment_coupon':
				$builderElement.find('.wordform-payment-coupon-builder-title').text(element.label || 'Coupon Code');
				$builderElement.find('.wordform-payment-coupon-builder-input').attr('placeholder', element.placeholderText || 'Enter coupon code');
				$builderElement.find('.wordform-payment-coupon-builder-button').text(element.applyButtonText || 'Apply Coupon');
				$builderElement.find('.wordform-payment-coupon-builder-message').text(element.appliedMessage || 'Applied coupon feedback will appear here.');
				break;
			case 'payment_custom_amount':
				$builderElement.find('.wordform-dropped-payment-custom-amount-label').text(element.label || 'Custom Amount');
				$builderElement.find('.wordform-dropped-payment-custom-amount-name')
					.attr('placeholder', element.placeholderText || 'Enter amount')
					.attr('value', element.defaultAmount || '')
					.val(element.defaultAmount || '')
					.attr('min', element.minAmount || '0');
				break;
			case 'payment_quantity':
				$builderElement.find('.wordform-dropped-payment-quantity-label').text(element.label || 'Quantity');
				$builderElement.find('.wordform-dropped-payment-quantity-name')
					.attr('value', element.defaultQuantity || 1)
					.val(element.defaultQuantity || 1)
					.attr('min', element.minQuantity || 1)
					.attr('max', element.maxQuantity || '');
				break;
			case 'payment_summary':
				$builderElement.find('.wordform-payment-summary-title').text(element.label || 'Payment Summary');
				$builderElement.find('.wordform-payment-summary-empty-text')
					.data('empty-text', element.emptyText || 'Amounts will appear here')
					.text(element.emptyText || 'Amounts will appear here');
				break;
			case 'stripe':
				$builderElement.find('.wordform-dropped-stripe-label').text(element.label || 'Stripe Payment');
				$builderElement.find('.wordform-dropped-stripe-button-text').text(element.buttonText || 'Pay with Card');
				$builderElement.find('.wordform-dropped-stripe-description').text(element.description || 'Secure card payment via Stripe');
				break;
			case 'paypal':
				$builderElement.find('.wordform-dropped-paypal-label').text(element.label || 'PayPal Payment');
				$builderElement.find('.wordform-dropped-paypal-button-text').text(element.buttonText || 'Pay with PayPal');
				$builderElement.find('.wordform-dropped-paypal-description').text(element.description || 'Checkout with your PayPal account');
				break;
			case 'square':
				$builderElement.find('.wordform-dropped-square-label').text(element.label || 'Square Payment');
				$builderElement.find('.wordform-dropped-square-button-text').text(element.buttonText || 'Pay with Square');
				$builderElement.find('.wordform-dropped-square-description').text(element.description || 'Secure card payment via Square');
				break;
			case 'authorizenet':
				$builderElement.find('.wordform-dropped-authorizenet-label').text(element.label || 'Authorize.Net Payment');
				$builderElement.find('.wordform-dropped-authorizenet-button-text').text(element.buttonText || 'Pay with Authorize.Net');
				$builderElement.find('.wordform-dropped-authorizenet-description').text(element.description || 'Secure card payment via Authorize.Net');
				break;
			case 'pagebreak':
				$builderElement.find('.wordform-pagebreak-builder-title').text(element.stepTitle || 'Next Step');
				$builderElement.find('.wordform-pagebreak-builder-action.is-primary').text(element.nextButtonText || 'Next');
				$builderElement.find('.wordform-pagebreak-builder-action.is-secondary').text(element.previousButtonText || 'Back');
				updatePageBreakBuilderLayout($builderElement.data('element-index'));
				break;
			case 'range':
				$builderElement.find('.wordform-dropped-range-name')
					.attr('min', element.min || 0)
					.attr('max', element.max || 100)
					.attr('value', element.default || 50)
					.attr('step', element.step || 5);
				break;
			case 'date':
				if (parseWordformBoolean(element.showDefaultDate) && element.defaultDate) {
					$builderElement.find('.wordform-dropped-date-name')
						.attr('value', element.defaultDate)
						.attr('placeholder', element.defaultDate);
				}
				break;
			case 'datetime':
				if (element.defaultDateTimeSetting === 'currentDateTime') {
					$builderElement.find('.wordform-dropped-datetime-name')
						.attr('value', '')
						.attr('placeholder', element.placeholderText || 'Select date & time');
				} else if (element.defaultDateTimeSetting && element.defaultDateTimeSetting !== 'none' && element.defaultDateTime) {
					$builderElement.find('.wordform-dropped-datetime-name')
						.attr('value', element.defaultDateTime)
						.attr('placeholder', element.defaultDateTime);
				} else {
					$builderElement.find('.wordform-dropped-datetime-name')
						.attr('value', '')
						.attr('placeholder', element.placeholderText || 'Select date & time');
				}
				break;
			case 'tel':
				$builderElement.find('.wordform-dropped-tel-name')
					.attr('minlength', element.minlength || 6)
					.attr('maxlength', element.maxlength || 14)
					.attr('pattern', element.pattern || '^\\+?[0-9]{6,14}$');
				break;
			case 'terms': {
				const $link = $builderElement.find('.wordform-dropped-terms-checkbox').closest('li').find('label a');
				const $label = $builderElement.find('.wordform-dropped-terms-checkbox').closest('li').find('label');
				if (element.termsConditionsUrl) {
					$link.attr('href', element.termsConditionsUrl);
				}
				if (!parseWordformBoolean(element.termsConditionsTextClickable) && $link.length) {
					$label.text($link.text());
				}
				break;
			}
			case 'gdpr': {
				const $link = $builderElement.find('.wordform-dropped-gdpr-checkbox').closest('li').find('label a');
				const $label = $builderElement.find('.wordform-dropped-gdpr-checkbox').closest('li').find('label');
				$builderElement.find('.wordform-dropped-gdpr-label').text(element.label || 'GDPR Consent');
				if ($link.length) {
					$link.text(element.gdprConsentText || 'I agree to the privacy policy and consent to data processing.');
				} else {
					$label.text(element.gdprConsentText || 'I agree to the privacy policy and consent to data processing.');
				}
				if (element.gdprPolicyUrl) {
					$link.attr('href', element.gdprPolicyUrl);
				}
				if (!parseWordformBoolean(element.gdprConsentTextClickable) && $link.length) {
					$label.text($link.text());
				}
				break;
			}
			case 'gcaptcha':
				if (!parseWordformBoolean(element.labelshow)) {
					$builderElement.find('.wordform-dropped-gcaptcha-label').hide();
				}
				break;
			case 'hcaptcha':
				if (!parseWordformBoolean(element.labelshow)) {
					$builderElement.find('.wordform-dropped-hcaptcha-label').hide();
				}
				break;
		}

		if (['payment_item', 'payment_coupon', 'payment_custom_amount', 'payment_quantity', 'payment_summary'].includes(element.type)) {
			wordformRefreshBuilderPaymentSummary();
		}
	}

	function applyWordformElementState($builderElement, $optionsWrapper, element) {
		applyWordformCommonFlags($optionsWrapper, element);

		switch (element.type) {
			case 'text':
				setWordformFieldValue($optionsWrapper.find('.wordform-text-label-name'), element.label || 'Name');
				setWordformCheckboxState($optionsWrapper.find('.text-placeholder-show-checkbox'), parseWordformBoolean(element.placeholderShow), null);
				setWordformFieldValue($optionsWrapper.find('.wordform-text-placeholder-text-input'), element.placeholderText || 'Your Name');
				break;
			case 'firstlastname':
				setWordformFieldValue($optionsWrapper.find('.wordform-firstname-label-name'), element.labelFirst || 'First Name');
				setWordformFieldValue($optionsWrapper.find('.wordform-lastname-label-name'), element.labelLast || 'Last Name');
				setWordformCheckboxState($optionsWrapper.find('.wordform-firstlastname-placeholder-show-checkbox'), parseWordformBoolean(element.placeholderShow), null);
				setWordformFieldValue($optionsWrapper.find('.wordform-firstlastname-placeholder-firstname-input'), element.placeholderTextFirst || 'First Name');
				setWordformFieldValue($optionsWrapper.find('.wordform-firstlastname-placeholder-lastname-input'), element.placeholderTextLast || 'Last Name');
				break;
			case 'number':
				setWordformFieldValue($optionsWrapper.find('.wordform-number-label-name'), element.label || 'Number');
				setWordformCheckboxState($optionsWrapper.find('.number-placeholder-show-checkbox'), parseWordformBoolean(element.placeholderShow), null);
				setWordformFieldValue($optionsWrapper.find('.wordform-number-placeholder-text-input'), element.placeholderText || 'Enter Number');
				break;
			case 'textarea':
				setWordformFieldValue($optionsWrapper.find('.wordform-textarea-label-name'), element.label || 'Description');
				setWordformCheckboxState($optionsWrapper.find('.textarea-placeholder-show-checkbox'), parseWordformBoolean(element.placeholderShow), null);
				setWordformFieldValue($optionsWrapper.find('.wordform-textarea-placeholder-text-input'), element.placeholderText || 'Tell us about yourself...');
				break;
			case 'richeditor':
				setWordformFieldValue($optionsWrapper.find('.wordform-richeditor-label-name'), element.label || 'Rich Text Editor');
				setWordformCheckboxState($optionsWrapper.find('.richeditor-placeholder-show-checkbox'), typeof element.placeholderShow === 'undefined' ? true : parseWordformBoolean(element.placeholderShow), null);
				setWordformFieldValue($optionsWrapper.find('.wordform-richeditor-placeholder-text-input'), element.placeholderText || 'Write your response...');
				setWordformFieldValue($optionsWrapper.find('.wordform-richeditor-min-height-input'), element.minHeight || 180, 'input');
				break;
			case 'range':
				setWordformFieldValue($optionsWrapper.find('.wordform-range-label-name'), element.label || 'Range');
				setWordformFieldValue($optionsWrapper.find('.wordform-range-min-value'), element.min || 0, null);
				setWordformFieldValue($optionsWrapper.find('.wordform-range-max-value'), element.max || 100, null);
				setWordformFieldValue($optionsWrapper.find('.wordform-range-default-value'), element.default || 50, null);
				setWordformFieldValue($optionsWrapper.find('.wordform-range-step-value'), element.step || 5, null);
				break;
			case 'url':
				setWordformFieldValue($optionsWrapper.find('.wordform-url-label-name'), element.label || 'URL');
				setWordformCheckboxState($optionsWrapper.find('.url-placeholder-show-checkbox'), parseWordformBoolean(element.placeholderShow), null);
				setWordformFieldValue($optionsWrapper.find('.wordform-url-placeholder-text-input'), element.placeholderText || 'https://example.com');
				break;
			case 'date':
				setWordformFieldValue($optionsWrapper.find('.wordform-date-label-name'), element.label || 'Date');
				setWordformCheckboxState($optionsWrapper.find('.date-placeholder-show-checkbox'), parseWordformBoolean(element.placeholderShow), null);
				setWordformFieldValue($optionsWrapper.find('.wordform-date-placeholder-text-input'), element.placeholderText || 'Pick a date from calendar');
				setWordformFieldValue($optionsWrapper.find('.wordform-default-date-display-format'), element.defaultDateFormat || 'yy-mm-dd', 'change');
				setWordformFieldValue($optionsWrapper.find('.wordform-date-default-value'), element.defaultDate || '', null);
				setWordformFieldValue($optionsWrapper.find('.wordform-date-hidden-raw-format-default-value'), element.defaultDate || '', null);
				setWordformCheckboxState($optionsWrapper.find('.date-default-value-show-checkbox'), parseWordformBoolean(element.showDefaultDate), null);
				setWordformFieldValue($optionsWrapper.find('.wordform-date-min-date-value'), element.minDate || '', null);
				setWordformFieldValue($optionsWrapper.find('.wordform-date-max-date-value'), element.maxDate || '', null);
				setWordformCheckboxState($optionsWrapper.find('.wordform-date-disable-past-checkbox'), parseWordformBoolean(element.disablePastDates), null);
				setWordformCheckboxState($optionsWrapper.find('.wordform-date-disable-future-checkbox'), parseWordformBoolean(element.disableFutureDates), null);
				setWordformFieldValue($optionsWrapper.find('.wordform-date-calendar-accent-color'), element.calendarAccentColor || '#2563eb', 'change');
				setWordformFieldValue($optionsWrapper.find('.wordform-date-calendar-surface-color'), element.calendarSurfaceColor || '#ffffff', 'change');
				setWordformFieldValue($optionsWrapper.find('.wordform-date-calendar-text-color'), element.calendarTextColor || '#0f172a', 'change');
				break;
			case 'time':
				setWordformFieldValue($optionsWrapper.find('.wordform-time-label-name'), element.label || 'Time');
				setWordformCheckboxState($optionsWrapper.find('.time-placeholder-show-checkbox'), typeof element.placeholderShow === 'undefined' ? true : parseWordformBoolean(element.placeholderShow), null);
				setWordformFieldValue($optionsWrapper.find('.wordform-time-placeholder-text-input'), element.placeholderText || 'Select time');
				setWordformFieldValue($optionsWrapper.find('.wordform-time-display-mode'), element.timeDisplayMode || '24h', null);
				setWordformFieldValue($optionsWrapper.find('.wordform-time-hidden-raw-default-value'), element.defaultTime || '', null);
				setWordformFieldValue($optionsWrapper.find('.wordform-time-default-value'), wordformFormatAdminTimeValue(element.defaultTime || '', element.timeDisplayMode || '24h'), null);
				wordformSyncTimePreview($optionsWrapper);
				break;
			case 'datetime': {
				setWordformFieldValue($optionsWrapper.find('.wordform-datetime-label-name'), element.label || 'DateTime');
				setWordformCheckboxState($optionsWrapper.find('.datetime-placeholder-show-checkbox'), parseWordformBoolean(element.placeholderShow), null);
				setWordformFieldValue($optionsWrapper.find('.wordform-datetime-placeholder-text-input'), element.placeholderText || 'Select date & time');
				setWordformCheckboxState($optionsWrapper.find('.wordform-datetime-display-format-hint-show-checkbox'), parseWordformBoolean(element.displayFormatHint), null);
				setWordformFieldValue($optionsWrapper.find('.wordform-datetime-time-display-mode'), element.timeDisplayMode || wordformInferTimeDisplayMode(element.defaultDateTimeFormat || 'yy-mm-dd HH:mm'), null);
				setWordformFieldValue($optionsWrapper.find('.wordform-default-datetime-display-format'), element.defaultDateTimeFormat || 'yy-mm-dd HH:mm', 'change');
				setWordformFieldValue($optionsWrapper.find('.wordform-datetime-default-value'), element.defaultDateTime || '', 'input');
				setWordformFieldValue($optionsWrapper.find('.wordform-datetime-hidden-raw-format-default-value'), element.defaultDateTime || '', null);
				setWordformFieldValue($optionsWrapper.find('.wordform-datetime-min-datetime-value'), element.minDateTime || '', null);
				setWordformFieldValue($optionsWrapper.find('.wordform-datetime-max-datetime-value'), element.maxDateTime || '', null);
				setWordformCheckboxState($optionsWrapper.find('.wordform-datetime-disable-past-checkbox'), parseWordformBoolean(element.disablePastDates), null);
				setWordformCheckboxState($optionsWrapper.find('.wordform-datetime-disable-future-checkbox'), parseWordformBoolean(element.disableFutureDates), null);
				setWordformFieldValue($optionsWrapper.find('.wordform-datetime-calendar-accent-color'), element.calendarAccentColor || '#2563eb', 'change');
				setWordformFieldValue($optionsWrapper.find('.wordform-datetime-calendar-surface-color'), element.calendarSurfaceColor || '#ffffff', 'change');
				setWordformFieldValue($optionsWrapper.find('.wordform-datetime-calendar-text-color'), element.calendarTextColor || '#0f172a', 'change');
				const $selectedRadio = getWordformMatchingRadioByValue(
					$optionsWrapper,
					'.datetime-default-value-show-radio',
					element.defaultDateTimeSetting,
					'currentDateTime'
				);
				setWordformCheckboxState($selectedRadio, true, 'change');
				break;
			}
			case 'tel':
				setWordformFieldValue($optionsWrapper.find('.wordform-tel-label-name'), element.label || 'Tel');
				setWordformCheckboxState($optionsWrapper.find('.tel-placeholder-show-checkbox'), parseWordformBoolean(element.placeholderShow), null);
				setWordformFieldValue($optionsWrapper.find('.wordform-tel-placeholder-text-input'), element.placeholderText || 'Enter Your Phone Number');
				setWordformFieldValue($optionsWrapper.find('.wordform-tel-min-length'), element.minlength || 6, null);
				setWordformFieldValue($optionsWrapper.find('.wordform-tel-max-length'), element.maxlength || 14, null);
				setWordformCheckboxState($optionsWrapper.find('.telhints-checkbox'), parseWordformBoolean(element.telhints), null);
				setWordformFieldValue($optionsWrapper.find('.wordform-input-tel-selected-pattern-regex-value'), element.pattern || '^\\+?[0-9]{6,14}$', null);
				setWordformFieldValue($optionsWrapper.find('.wordform-input-tel-selected-pattern-regex-example-phone-numbers'), element.telhintsNumber || 'Ex: +33123456789, 49891234567', null);
				break;
			case 'email':
				setWordformFieldValue($optionsWrapper.find('.wordform-email-label-name'), element.label || 'Email');
				setWordformCheckboxState($optionsWrapper.find('.email-placeholder-show-checkbox'), parseWordformBoolean(element.placeholderShow), null);
				setWordformFieldValue($optionsWrapper.find('.wordform-email-placeholder-text-input'), element.placeholderText || 'Write Your Email');
				break;
			case 'address':
				setWordformCheckboxState($optionsWrapper.find('.required-checkbox'), parseWordformBoolean(element.required), null);
				setWordformFieldValue($optionsWrapper.find('.wordform-address-label-name'), element.label || 'Address');
				setWordformCheckboxState($optionsWrapper.find('.address-placeholder-show-checkbox'), typeof element.placeholderShow === 'undefined' ? true : parseWordformBoolean(element.placeholderShow), null);
				setWordformFieldValue($optionsWrapper.find('.wordform-address-placeholder-street-input'), element.placeholderStreet || 'Street Address');
				setWordformFieldValue($optionsWrapper.find('.wordform-address-placeholder-city-input'), element.placeholderCity || 'City');
				setWordformFieldValue($optionsWrapper.find('.wordform-address-placeholder-state-input'), element.placeholderState || 'State / Region');
				setWordformFieldValue($optionsWrapper.find('.wordform-address-placeholder-zip-input'), element.placeholderZip || 'ZIP / Postal Code');
				setWordformFieldValue($optionsWrapper.find('.wordform-address-placeholder-country-input'), element.placeholderCountry || 'Country');
				break;
			case 'sectionhtml':
				setWordformFieldValue($optionsWrapper.find('.wordform-sectionhtml-title-input'), element.label || 'Section Title');
				setWordformFieldValue($optionsWrapper.find('.wordform-sectionhtml-content-input'), element.content || 'Add instructions, notes, or custom HTML content.');
				break;
			case 'maskinput':
				setWordformCheckboxState($optionsWrapper.find('.required-checkbox'), parseWordformBoolean(element.required), null);
				setWordformFieldValue($optionsWrapper.find('.wordform-maskinput-label-name'), element.label || 'Masked Input');
				setWordformCheckboxState($optionsWrapper.find('.maskinput-placeholder-show-checkbox'), typeof element.placeholderShow === 'undefined' ? true : parseWordformBoolean(element.placeholderShow), null);
				setWordformFieldValue($optionsWrapper.find('.wordform-maskinput-placeholder-text-input'), element.placeholderText || 'AB-12345');
				setWordformFieldValue($optionsWrapper.find('.wordform-maskinput-pattern-input'), element.pattern || '^[A-Z]{2}-[0-9]{5}$');
				break;
			case 'rating':
				setWordformFieldValue($optionsWrapper.find('.wordform-rating-label-name'), element.label || 'Rating');
				setWordformFieldValue($optionsWrapper.find('.wordform-rating-scale-input'), element.scale || 5, 'input');
				setWordformFieldValue($optionsWrapper.find('.wordform-rating-low-text-input'), element.lowText || 'Poor');
				setWordformFieldValue($optionsWrapper.find('.wordform-rating-high-text-input'), element.highText || 'Excellent');
				break;
			case 'likert':
				setWordformFieldValue($optionsWrapper.find('.wordform-likert-label-name'), element.label || 'Likert Scale');
				wordformSetLikertOptionListValues($optionsWrapper, 'row', Array.isArray(element.rowLabels) ? element.rowLabels : wordformGetLikertDefaultRows());
				wordformSetLikertOptionListValues($optionsWrapper, 'column', Array.isArray(element.columnLabels) ? element.columnLabels : wordformGetLikertDefaultColumns());
				wordformRefreshLikertBuilderPreviewFromOptions($optionsWrapper);
				break;
			case 'hidden':
				setWordformFieldValue($optionsWrapper.find('.wordform-hidden-label-name'), element.label || 'Hidden Field');
				setWordformFieldValue($optionsWrapper.find('.wordform-hidden-field-value-input'), element.defaultValue || 'utm_source');
				break;
			case 'captcha':
				setWordformFieldValue($optionsWrapper.find('.wordform-captcha-label-name'), element.label || 'Captcha');
				setWordformCheckboxState($optionsWrapper.find('.required-checkbox'), parseWordformBoolean(element.required), null);
				setWordformCheckboxState($optionsWrapper.find('.captcha-placeholder-show-checkbox'), parseWordformBoolean(element.placeholderShow), null);
				setWordformFieldValue($optionsWrapper.find('.wordform-captcha-placeholder-text-input'), element.placeholderText || 'Type Captcha Here');
				setWordformFieldValue($optionsWrapper.find('.wordform-captcha-digit-length-select'), element.digitLength || 4, 'change');
				setWordformFieldValue($optionsWrapper.find('.wordform-captcha-font-style-select'), element.fontStyle || 'blackopsone', 'change');
				setWordformCheckboxState($optionsWrapper.find(`.wordform-captcha-style-mode-radio[value="${element.styleMode || 'template'}"]`), true, null);
				setWordformFieldValue($optionsWrapper.find('.wordform-captcha-background-color-input'), element.backgroundColor || '#eef2ff', 'change');
				setWordformFieldValue($optionsWrapper.find('.wordform-captcha-text-color-input'), element.textColor || '#111827', 'change');
				setWordformFieldValue($optionsWrapper.find('.wordform-captcha-noise-color-input'), element.noiseColor || '#cbd5e1', 'change');
				if (element.align) {
					const $align = $optionsWrapper.find(`.wordform-build-captcha-template-align-input[value="${element.align}"]`);
					setWordformCheckboxState($align, true, 'change');
				}
				if (element.templateName) {
					const $template = $optionsWrapper.find(`.wordform-captcha-template-radio[value="${element.templateName}"]`);
					if ($template.length) {
						setWordformCheckboxState($template, true, 'change');
					}
				}
				wordformToggleCaptchaStyleModeGroups($optionsWrapper);
				wordformRefreshCaptchaBuilderPreview($optionsWrapper);
				break;
			case 'gcaptcha':
				setWordformFieldValue($optionsWrapper.find('.wordform-gcaptcha-label-name'), element.label || 'Google reCaptcha');
				setWordformCheckboxState($optionsWrapper.find('.recaptcha-label-checkbox'), parseWordformBoolean(element.labelshow), 'change');
				break;
			case 'hcaptcha':
				setWordformFieldValue($optionsWrapper.find('.wordform-hcaptcha-label-name'), element.label || 'hCaptcha');
				setWordformCheckboxState($optionsWrapper.find('.hcaptcha-label-checkbox'), parseWordformBoolean(element.labelshow), 'change');
				break;
			case 'radio': {
				setWordformFieldValue($optionsWrapper.find('.wordform-radio-label-name'), element.label || 'Multiple Choice');
				const options = Array.isArray(element.multiOption) && element.multiOption.length ? element.multiOption : [{ checkStatus: false, optionText: 'Option Text' }];
				ensureWordformOptionItems($optionsWrapper, '.wordform-add-radio-option', options.length);
				$optionsWrapper.find('.wordform-field-options li').slice(0, options.length).each(function (index) {
					const option = options[index] || {};
					const $row = $(this);
					setWordformFieldValue($row.find('.wordform-input-radio-label-name'), option.optionText || 'Option Text');
					setWordformCheckboxState($row.find('.wordform-edit-radio-name'), parseWordformBoolean(option.checkStatus), null);
					const $previewInput = $builderElement.find('.wordform-dropped-element-radio-field-options li').eq(index).find('input');
					if (parseWordformBoolean(option.checkStatus)) {
						$builderElement.find('.wordform-dropped-element-radio-field-options input').removeAttr('checked');
						$previewInput.attr('checked', 'checked');
					} else {
						$previewInput.removeAttr('checked');
					}
				});
				break;
			}
			case 'checkbox': {
				setWordformFieldValue($optionsWrapper.find('.wordform-checkbox-label-name'), element.label || 'Checkboxes');
				const options = Array.isArray(element.multiOption) && element.multiOption.length ? element.multiOption : [{ checkStatus: false, optionText: 'Checkbox Text' }];
				ensureWordformOptionItems($optionsWrapper, '.wordform-add-checkbox-option', options.length);
				$optionsWrapper.find('.wordform-field-options li').slice(0, options.length).each(function (index) {
					const option = options[index] || {};
					const $row = $(this);
					setWordformFieldValue($row.find('.wordform-input-checkbox-label-name'), option.optionText || 'Checkbox Text');
					setWordformCheckboxState($row.find('.wordform-edit-checkbox-name'), parseWordformBoolean(option.checkStatus), null);
					const $previewInput = $builderElement.find('.wordform-dropped-element-checkbox-field-options li').eq(index).find('input');
					if (parseWordformBoolean(option.checkStatus)) {
						$previewInput.attr('checked', 'checked');
					} else {
						$previewInput.removeAttr('checked');
					}
				});
				break;
			}
			case 'select': {
				setWordformFieldValue($optionsWrapper.find('.wordform-select-label-name'), element.label || 'Dropdown Options');
				const options = Array.isArray(element.multiOption) && element.multiOption.length ? element.multiOption : [{ checkStatus: false, optionText: 'Select Text' }];
				ensureWordformOptionItems($optionsWrapper, '.wordform-add-select-option', options.length);
				$optionsWrapper.find('.wordform-field-options li').slice(0, options.length).each(function (index) {
					const option = options[index] || {};
					const $row = $(this);
					setWordformFieldValue($row.find('.wordform-input-select-label-name'), option.optionText || 'Select Text');
					setWordformCheckboxState($row.find('.wordform-edit-select-name'), parseWordformBoolean(option.checkStatus), null);
					const $previewOption = $builderElement.find('.wordform-dropped-select-name option').eq(index);
					if (parseWordformBoolean(option.checkStatus)) {
						$builderElement.find('.wordform-dropped-select-name option').removeAttr('selected');
						$previewOption.attr('selected', 'selected');
					}
				});
				break;
			}
			case 'upload': {
				setWordformFieldValue($optionsWrapper.find('.wordform-upload-label-name'), element.label || 'Upload');
				setWordformFieldValue($optionsWrapper.find('.wordform-upload-select-file-label-name'), element.selectFileLabel || 'Select File');
				setWordformCheckboxState($optionsWrapper.find('.multiple-checkbox'), parseWordformBoolean(element.multiple), null);
				if (Array.isArray(element.multiOption)) {
					element.multiOption.forEach((option) => {
						const selector = `.wordform-upload-allow-file-type-name-checkbox[value="${option.fileTypeValue}"]`;
						setWordformCheckboxState($optionsWrapper.find(selector), parseWordformBoolean(option.checkStatus), null);
					});
				}
				break;
			}
			case 'signature':
				setWordformFieldValue($optionsWrapper.find('.wordform-signature-label-name'), element.label || 'Signature');
				setWordformFieldValue($optionsWrapper.find('.wordform-signature-clear-button-text-input'), element.clearButtonText || 'Clear Signature');
				setWordformFieldValue($optionsWrapper.find('.wordform-signature-canvas-height-input'), element.canvasHeight || 180, 'input');
				break;
			case 'pagebreak':
				setWordformFieldValue($optionsWrapper.find('.wordform-pagebreak-step-title-input'), element.stepTitle || 'Next Step');
				setWordformFieldValue($optionsWrapper.find('.wordform-pagebreak-next-button-text-input'), element.nextButtonText || 'Next');
				setWordformFieldValue($optionsWrapper.find('.wordform-pagebreak-previous-button-text-input'), element.previousButtonText || 'Back');
				setWordformCheckboxState(getWordformMatchingRadioByValue($optionsWrapper, '.wordform-pagebreak-next-button-align-input', element.nextButtonAlign || 'right', 'right'), true, 'change');
				setWordformCheckboxState(getWordformMatchingRadioByValue($optionsWrapper, '.wordform-pagebreak-previous-button-align-input', element.previousButtonAlign || 'left', 'left'), true, 'change');
				break;
			case 'payment_method':
				setWordformFieldValue($optionsWrapper.find('.wordform-payment-method-label-name'), element.label || 'Payment Method');
				setWordformFieldValue($optionsWrapper.find('.wordform-payment-method-helper-text-input'), element.helperText || 'Choose how you want to pay');
				setWordformCheckboxState(getWordformMatchingRadioByValue($optionsWrapper, '.wordform-payment-method-default-gateway-radio', element.defaultGateway || 'stripe', 'stripe'), true, 'change');
				break;
			case 'payment_item':
				setWordformFieldValue($optionsWrapper.find('.wordform-payment-item-label-name'), element.label || 'Payment Item');
				setWordformFieldValue($optionsWrapper.find('.wordform-payment-item-amount'), element.amount || '', 'input');
				setWordformFieldValue($optionsWrapper.find('.wordform-payment-item-description'), element.description || 'Fixed price item');
				break;
			case 'payment_coupon':
				setWordformFieldValue($optionsWrapper.find('.wordform-payment-coupon-label-name'), element.label || 'Coupon Code');
				setWordformFieldValue($optionsWrapper.find('.wordform-payment-coupon-placeholder-text-input'), element.placeholderText || 'Enter coupon code');
				setWordformFieldValue($optionsWrapper.find('.wordform-payment-coupon-apply-button-text-input'), element.applyButtonText || 'Apply Coupon');
				setWordformFieldValue($optionsWrapper.find('.wordform-payment-coupon-remove-button-text-input'), element.removeButtonText || 'Remove Coupon');
				setWordformFieldValue($optionsWrapper.find('.wordform-payment-coupon-invalid-message-input'), element.invalidMessage || 'Coupon code is not valid.');
				setWordformFieldValue($optionsWrapper.find('.wordform-payment-coupon-applied-message-input'), element.appliedMessage || 'Coupon applied successfully.');
				break;
			case 'payment_custom_amount':
				setWordformCheckboxState($optionsWrapper.find('.required-checkbox'), parseWordformBoolean(element.required), null);
				setWordformFieldValue($optionsWrapper.find('.wordform-payment-custom-amount-label-name'), element.label || 'Custom Amount');
				setWordformFieldValue($optionsWrapper.find('.wordform-payment-custom-amount-placeholder-text-input'), element.placeholderText || 'Enter amount');
				setWordformFieldValue($optionsWrapper.find('.wordform-payment-custom-amount-default'), element.defaultAmount || '', 'input');
				setWordformFieldValue($optionsWrapper.find('.wordform-payment-custom-amount-min'), element.minAmount || '', 'input');
				break;
			case 'payment_quantity':
				setWordformCheckboxState($optionsWrapper.find('.required-checkbox'), parseWordformBoolean(element.required), null);
				setWordformFieldValue($optionsWrapper.find('.wordform-payment-quantity-label-name'), element.label || 'Quantity');
				setWordformFieldValue($optionsWrapper.find('.wordform-payment-quantity-default-input'), element.defaultQuantity || 1, 'input');
				setWordformFieldValue($optionsWrapper.find('.wordform-payment-quantity-min-input'), element.minQuantity || 1, 'input');
				setWordformFieldValue($optionsWrapper.find('.wordform-payment-quantity-max-input'), element.maxQuantity || '', 'input');
				break;
			case 'payment_summary':
				setWordformFieldValue($optionsWrapper.find('.wordform-payment-summary-label-name'), element.label || 'Payment Summary');
				setWordformFieldValue($optionsWrapper.find('.wordform-payment-summary-empty-text-input'), element.emptyText || 'Amounts will appear here');
				break;
			case 'stripe':
				setWordformFieldValue($optionsWrapper.find('.wordform-stripe-label-name'), element.label || 'Stripe Payment');
				setWordformFieldValue($optionsWrapper.find('.wordform-stripe-button-text-input'), element.buttonText || 'Pay with Card');
				setWordformFieldValue($optionsWrapper.find('.wordform-stripe-description-input'), element.description || 'Secure card payment via Stripe');
				break;
			case 'paypal':
				setWordformFieldValue($optionsWrapper.find('.wordform-paypal-label-name'), element.label || 'PayPal Payment');
				setWordformFieldValue($optionsWrapper.find('.wordform-paypal-button-text-input'), element.buttonText || 'Pay with PayPal');
				setWordformFieldValue($optionsWrapper.find('.wordform-paypal-description-input'), element.description || 'Checkout with your PayPal account');
				break;
			case 'square':
				setWordformFieldValue($optionsWrapper.find('.wordform-square-label-name'), element.label || 'Square Payment');
				setWordformFieldValue($optionsWrapper.find('.wordform-square-button-text-input'), element.buttonText || 'Pay with Square');
				setWordformFieldValue($optionsWrapper.find('.wordform-square-description-input'), element.description || 'Secure card payment via Square');
				break;
			case 'authorizenet':
				setWordformFieldValue($optionsWrapper.find('.wordform-authorizenet-label-name'), element.label || 'Authorize.Net Payment');
				setWordformFieldValue($optionsWrapper.find('.wordform-authorizenet-button-text-input'), element.buttonText || 'Pay with Authorize.Net');
				setWordformFieldValue($optionsWrapper.find('.wordform-authorizenet-description-input'), element.description || 'Secure card payment via Authorize.Net');
				break;
			case 'terms':
				setWordformFieldValue($optionsWrapper.find('.wordform-terms-label-name'), element.label || 'Terms & Conditions');
				setWordformFieldValue($optionsWrapper.find('.wordform-terms-text'), element.termsConditionsText || 'I agree to the Terms & Conditions.');
				setWordformFieldValue($optionsWrapper.find('.wordform-terms-conditions-url-input'), element.termsConditionsUrl || '', null);
				setWordformCheckboxState($optionsWrapper.find('.clickable-term-conditions-text-checkbox'), parseWordformBoolean(element.termsConditionsTextClickable), 'change');
				break;
			case 'gdpr':
				setWordformFieldValue($optionsWrapper.find('.wordform-gdpr-label-name'), element.label || 'GDPR Consent');
				setWordformFieldValue($optionsWrapper.find('.wordform-gdpr-text'), element.gdprConsentText || 'I agree to the privacy policy and consent to data processing.');
				setWordformFieldValue($optionsWrapper.find('.wordform-gdpr-policy-url-input'), element.gdprPolicyUrl || '', null);
				setWordformCheckboxState($optionsWrapper.find('.clickable-gdpr-text-checkbox'), parseWordformBoolean(element.gdprConsentTextClickable), 'change');
				break;
		}

		applyWordformAdminLabelState($optionsWrapper, element);
		applyWordformSharedHelpTextState($builderElement, $optionsWrapper, element);
		applyWordformSharedFieldWidthState($optionsWrapper, element);
		applyWordformSharedCustomClassState($optionsWrapper, element);
		applyWordformSharedDefaultValueState($builderElement, $optionsWrapper, element);
		applyWordformPreviewOnlyState($builderElement, element);
	}

	async function rebuildWordformEditCanvasFromStructuredData() {
		const payload = getWordformBuilderReconstructionPayload();
		if (!payload || !payload.formData.length) {
			return;
		}

		await loadWordformStructuredBuilderPayload(payload, {
			formId: payload.formId,
			disablePreview: false
		});
		$('.wordform-form-saved').val(true);
	}

	setTimeout(() => {
		rebuildWordformEditCanvasFromStructuredData().catch((error) => {
			console.error('WordForm builder reconstruction failed.', error);
		});
	}, 50);

	setTimeout(() => {
		if ($('.wordform-input-element-div-wrapper').length) {
			syncWordformInitialSelectedElement();
		}
	}, 350);

	const wordformTemplateModalState = {
		activeCategory: 'all'
	};

	function wordformBuilderNeedsTemplateReplacementConfirmation() {
		const hasDynamicElements = $('.wordform-dropzone-div-wrapper .wordform-input-element-div-wrapper').length > 0;
		const hasSavedFormId = $.trim($('.wordform-created-form-id').val() || '').length > 0;
		const currentFormName = $.trim($('.wordform-form-name-label-input').val() || '');
		const currentSubmitText = $.trim($('.wordform-submit-button-label-input').val() || '');

		return hasDynamicElements || hasSavedFormId || currentFormName !== 'New Form' || currentSubmitText !== 'Submit';
	}

	function renderWordformTemplateCards() {
		const templates = getWordformBuilderTemplatesRegistry();
		const $grid = $('.wordform-templates-grid');
		const $emptyState = $('.wordform-templates-empty-state');
		const searchTerm = $.trim($('#WordFormTemplateSearch').val() || '').toLowerCase();
		const activeCategory = wordformTemplateModalState.activeCategory || 'all';

		if (!$grid.length) {
			return;
		}

		const filteredTemplates = templates.filter((template) => {
			const matchesCategory = activeCategory === 'all' || template.category === activeCategory;
			const haystack = [
				template.name || '',
				template.description || '',
				Array.isArray(template.tags) ? template.tags.join(' ') : '',
				template.form_name || ''
			].join(' ').toLowerCase();

			return matchesCategory && (searchTerm.length === 0 || haystack.indexOf(searchTerm) !== -1);
		});

		if (!filteredTemplates.length) {
			$grid.empty();
			$emptyState.show();
			return;
		}

		$emptyState.hide();
		$grid.html(
			filteredTemplates.map((template) => {
				const tags = Array.isArray(template.tags) ? template.tags : [];
				return `
					<div class="wordform-template-card" data-template-id="${escapeWordformHtml(template.template_id)}">
						<div class="wordform-template-card-topline">
							<span class="wordform-template-card-category">${escapeWordformHtml(template.category_label || template.category)}</span>
						</div>
						<h4>${escapeWordformHtml(template.name)}</h4>
						<p>${escapeWordformHtml(template.description)}</p>
						<div class="wordform-template-card-tags">
							${tags.map((tag) => `<span class="wordform-template-card-tag">${escapeWordformHtml(tag)}</span>`).join('')}
						</div>
						<div class="wordform-template-card-actions">
							<button type="button" class="button button-primary wordform-template-use-btn" data-template-id="${escapeWordformHtml(template.template_id)}">Use Template</button>
						</div>
					</div>
				`;
			}).join('')
		);
	}

	function initWordformTemplatesDialog() {
		const $modal = $('#WordFormTemplatesModal');

		if (!$modal.length) {
			return null;
		}

		if ($modal.data('wordform-templates-dialog-ready')) {
			return $modal;
		}

		const viewportWidth = Math.max(960, Math.round($(window).width() * 0.8));
		const viewportHeight = Math.max(620, Math.round($(window).height() * 0.82));

		$modal.dialog({
			autoOpen: false,
			minWidth: viewportWidth,
			minHeight: viewportHeight,
			modal: true,
			dialogClass: 'wordform-admin-dialog wordform-form-templates-dialog',
			open: function() {
				$('body').addClass('wordform-hide-builder-connector');
			},
			close: function() {
				$('body').removeClass('wordform-hide-builder-connector');
				syncWordformInitialSelectedElement();
			},
			buttons: {
				Close: function() {
					$modal.dialog('close');
				}
			}
		});

		$modal.data('wordform-templates-dialog-ready', true);
		return $modal;
	}

	$('body').on('click', '.wordform-form-templates-btn', function() {
		const $modal = initWordformTemplatesDialog();
		if (!$modal) {
			return;
		}

		wordformTemplateModalState.activeCategory = 'all';
		$('#WordFormTemplateSearch').val('');
		$('.wordform-template-category-item').removeClass('is-active');
		$('.wordform-template-category-item[data-template-category="all"]').addClass('is-active');
		renderWordformTemplateCards();
		$modal.dialog('open');
	});

	$('body').on('input', '#WordFormTemplateSearch', function() {
		renderWordformTemplateCards();
	});

	$('body').on('click', '.wordform-template-category-item', function() {
		wordformTemplateModalState.activeCategory = $(this).data('template-category') || 'all';
		$('.wordform-template-category-item').removeClass('is-active');
		$(this).addClass('is-active');
		renderWordformTemplateCards();
	});

	$('body').on('click', '.wordform-template-use-btn', async function() {
		const templateId = $(this).data('template-id');
		const templates = getWordformBuilderTemplatesRegistry();
		const selectedTemplate = templates.find((template) => template.template_id === templateId);

		if (!selectedTemplate || !Array.isArray(selectedTemplate.form_definition)) {
			return;
		}

		if (wordformBuilderNeedsTemplateReplacementConfirmation()) {
			const shouldReplace = window.confirm('Replace the current builder contents with this template? Unsaved changes will be lost.');
			if (!shouldReplace) {
				return;
			}
		}

		$('#WordFormTemplatesModal').dialog('close');

		await loadWordformStructuredBuilderPayload(
			{
				formData: selectedTemplate.form_definition
			},
			{
				formId: $('.wordform-created-form-id').val() || '',
				disablePreview: true
			}
		);

		$('.wordform-message-info').html('<span class="dashicons dashicons-yes-alt"></span> Template loaded into the builder. Review the fields and save the form.');
	});

	wordformApplyTierBuilderRestrictions();
	
	
	// Input Field Label Name
	$('body').on("input", ".wordform-input-label-name", function() {
		let labelName	=	$(this).val();		
		let parentID	= $(this).closest('.wordform-input-element-div-wrapper').prop("id");		
		$('#'+parentID+ ' .input-label').text(labelName);
	});
	
	
	// Save: Wordform Save Button - Save created form to use later
	$('body').on("click", ".wordform-save-btn", function() {
		let duplicateGatewayExists = false;
		['stripe', 'paypal', 'square', 'authorizenet'].forEach(function(gatewaySlug) {
			if ($('.wordform-dropzone-div-wrapper [data-input-element-type="' + gatewaySlug + '"]').length > 1) {
				duplicateGatewayExists = gatewaySlug;
			}
		});

		if (duplicateGatewayExists) {
			showWordformDialog(duplicateGatewayExists);
			return false;
		}

		let duplicateCaptchaExists = false;
		['captcha', 'gcaptcha', 'hcaptcha'].forEach(function(captchaSlug) {
			if ($('.wordform-dropzone-div-wrapper [data-input-element-type="' + captchaSlug + '"]').length > 1) {
				duplicateCaptchaExists = captchaSlug;
			}
		});

		if (duplicateCaptchaExists) {
			showWordformDialog(duplicateCaptchaExists);
			return false;
		}

		const mixedCaptchaConflict = wordformBuilderHasMixedCaptchaConflict();
		if (mixedCaptchaConflict) {
			showWordformDialog(mixedCaptchaConflict);
			return false;
		}

		if (wordformBuilderHasInvalidGatewayConfiguration()) {
			wordformShowPaymentGatewayRuleDialog();
			return false;
		}

		const pageBreakLayoutValidation = wordformGetPageBreakLayoutValidation();
		if (!pageBreakLayoutValidation.valid) {
			wordformShowPageBreakRuleDialog(pageBreakLayoutValidation.message);
			return false;
		}

		let inputElementArr				=	[];
		let formSaveMeta				= 	{};
		formSaveMeta.formSaved			=   $('.wordform-form-saved').val();
		formSaveMeta.createdFormID		=   $('.wordform-created-form-id').val();
		formSaveMeta.formName			=   $('.wordform-form-name-label-input').val();		
		let messageWrapper				=   $('.wordform-message-info');			
		
		$('.wordform-input-element-div-wrapper').each(function() {
			let elementObj				=	{};
			let multipleOptions			= 	[];
			let options					=	{};
			let elementIndex			=	$(this).prop("id").split('-')[1];
			let elementType				=   $(this).data('input-element-type');
			let optionsWrapperID		=   '#wordformElementOptions-'+elementIndex;
			// console.log( elementType );			
			// console.log(elementIndex);
			switch ( elementType ) {
				case 'text':
					elementObj					=	{};
					elementObj.type				=   elementType;
					elementObj.required			=   ( $(optionsWrapperID).find('.required-checkbox').is(':checked') )? true : false;
					elementObj.label			=   ( $(optionsWrapperID).find('.wordform-text-label-name').val()?.length == 0 )? 'Name' : $(optionsWrapperID).find('.wordform-text-label-name').val();
					elementObj.placeholderShow	=   ( $(optionsWrapperID).find('.text-placeholder-show-checkbox').is(':checked') )? true : false;					
					elementObj.placeholderText	=   ( $(optionsWrapperID).find('.wordform-text-placeholder-text-input').val()?.length == 0 )? 'Your Name' : $(optionsWrapperID).find('.wordform-text-placeholder-text-input').val();

					elementObj.charLimit		=   '';					
					elementObj.elementIndex		=   elementIndex;
					inputElementArr.push( elementObj);
					break;

				case 'firstlastname':
					elementObj					=	{};
					elementObj.type				=   elementType;
					elementObj.required			=   ( $(optionsWrapperID).find('.required-checkbox').is(':checked') )? true : false;
					elementObj.labelFirst		=   ( $(optionsWrapperID).find('.wordform-firstname-label-name').val()?.length == 0 )? 'First Name' : $(optionsWrapperID).find('.wordform-firstname-label-name').val();
					elementObj.labelLast		=   ( $(optionsWrapperID).find('.wordform-lastname-label-name').val()?.length == 0 )? 'Last Name' : $(optionsWrapperID).find('.wordform-lastname-label-name').val();
					elementObj.placeholderShow	=   ( $(optionsWrapperID).find('.wordform-firstlastname-placeholder-show-checkbox').is(':checked') )? true : false;					
					elementObj.placeholderTextFirst	=  ( $(optionsWrapperID).find('.wordform-firstlastname-placeholder-firstname-input').val()?.length == 0 )? 'First Name' : $(optionsWrapperID).find('.wordform-firstlastname-placeholder-firstname-input').val();
					elementObj.placeholderTextLast	=  ( $(optionsWrapperID).find('.wordform-firstlastname-placeholder-lastname-input').val()?.length == 0 )? 'Last Name' : $(optionsWrapperID).find('.wordform-firstlastname-placeholder-lastname-input').val();

					elementObj.charLimit		=   '';					
					elementObj.elementIndex		=   elementIndex;
					inputElementArr.push( elementObj);
					break;
					
				case 'number':
					elementObj					=	{};
					elementObj.type				=   elementType;
					elementObj.required			=   ( $(optionsWrapperID).find('.required-checkbox').is(':checked') )? true : false;
					elementObj.label			=   ( $(optionsWrapperID).find('.wordform-number-label-name').val()?.length == 0 )? 'Number' : $(optionsWrapperID).find('.wordform-number-label-name').val();	
					elementObj.placeholderShow	=   ( $(optionsWrapperID).find('.number-placeholder-show-checkbox').is(':checked') )? true : false;					
					elementObj.placeholderText	=   ( $(optionsWrapperID).find('.wordform-number-placeholder-text-input').val()?.length == 0 )? 'Enter Number' : $(optionsWrapperID).find('.wordform-number-placeholder-text-input').val();

					elementObj.elementIndex		=   elementIndex;
					inputElementArr.push( elementObj);
					break;
					
				case 'textarea':
					elementObj					=	{};
					elementObj.type				=   elementType;
					elementObj.required			=   ( $(optionsWrapperID).find('.required-checkbox').is(':checked') )? true : false;
					elementObj.label			=   ( $(optionsWrapperID).find('.wordform-textarea-label-name').val()?.length == 0 )? 'Description' : $(optionsWrapperID).find('.wordform-textarea-label-name').val();	
					elementObj.placeholderShow	=   ( $(optionsWrapperID).find('.textarea-placeholder-show-checkbox').is(':checked') )? true : false;					
					elementObj.placeholderText	=   ( $(optionsWrapperID).find('.wordform-textarea-placeholder-text-input').val()?.length == 0 )? 'Tell us about yourself...' : $(optionsWrapperID).find('.wordform-textarea-placeholder-text-input').val();

					elementObj.elementIndex		=   elementIndex;
					inputElementArr.push( elementObj);
					break;
					
				case 'richeditor':
					elementObj					=	{};
					elementObj.type				=   elementType;
					elementObj.required			=   ( $(optionsWrapperID).find('.required-checkbox').is(':checked') )? true : false;
					elementObj.label			=   ( $(optionsWrapperID).find('.wordform-richeditor-label-name').val()?.length == 0 )? 'Rich Text Editor' : $(optionsWrapperID).find('.wordform-richeditor-label-name').val();
					elementObj.placeholderShow	=   ( $(optionsWrapperID).find('.richeditor-placeholder-show-checkbox').is(':checked') )? true : false;
					elementObj.placeholderText	=   ( $(optionsWrapperID).find('.wordform-richeditor-placeholder-text-input').val()?.length == 0 )? 'Write your response...' : $(optionsWrapperID).find('.wordform-richeditor-placeholder-text-input').val();
					elementObj.minHeight		=   ( $(optionsWrapperID).find('.wordform-richeditor-min-height-input').val()?.length == 0 )? '180' : $(optionsWrapperID).find('.wordform-richeditor-min-height-input').val();
					elementObj.elementIndex		=   elementIndex;
					inputElementArr.push( elementObj);
					break;
					
				case 'range':
					elementObj					=	{};
					elementObj.type				=   elementType;
					elementObj.required			=   ( $(optionsWrapperID).find('.required-checkbox').is(':checked') )? true : false;
					elementObj.label			=   ( $(optionsWrapperID).find('.wordform-range-label-name').val()?.length == 0 )? 'Range' : $(optionsWrapperID).find('.wordform-range-label-name').val();
					elementObj.min				=   $(optionsWrapperID).find('.wordform-range-min-value').val();
					elementObj.max				=   $(optionsWrapperID).find('.wordform-range-max-value').val();
					elementObj.default			=   $(optionsWrapperID).find('.wordform-range-default-value').val();
					elementObj.step				=   $(optionsWrapperID).find('.wordform-range-step-value').val();						
					elementObj.elementIndex		=   elementIndex;
					inputElementArr.push( elementObj);
					break;

				case 'url':
					elementObj					=	{};
					elementObj.type				=   elementType;
					elementObj.required			=   ( $(optionsWrapperID).find('.required-checkbox').is(':checked') )? true : false;					
					elementObj.label			=   ( $(optionsWrapperID).find('.wordform-url-label-name').val()?.length == 0 )? 'URL' : $(optionsWrapperID).find('.wordform-url-label-name').val();
					elementObj.placeholderShow	=   ( $(optionsWrapperID).find('.url-placeholder-show-checkbox').is(':checked') )? true : false;					
					elementObj.placeholderText	=   ( $(optionsWrapperID).find('.wordform-url-placeholder-text-input').val()?.length == 0 )? 'URL' : $(optionsWrapperID).find('.wordform-url-placeholder-text-input').val();

					elementObj.elementIndex		=   elementIndex;
					inputElementArr.push( elementObj);
					break;

				case 'date':
					elementObj					=	{};
					elementObj.type				=   elementType;
					elementObj.required			=   ( $(optionsWrapperID).find('.required-checkbox').is(':checked') )? true : false;
					elementObj.label			=   ( $(optionsWrapperID).find('.wordform-date-label-name').val()?.length == 0 )? 'Date' : $(optionsWrapperID).find('.wordform-date-label-name').val();
					elementObj.placeholderShow	=   ( $(optionsWrapperID).find('.date-placeholder-show-checkbox').is(':checked') )? true : false;					
					elementObj.placeholderText	=   ( $(optionsWrapperID).find('.wordform-date-placeholder-text-input').val()?.length == 0 )? 'Pick a date from calendar' : $(optionsWrapperID).find('.wordform-date-placeholder-text-input').val();
					
					elementObj.showDefaultDate	=   ( $(optionsWrapperID).find('.date-default-value-show-checkbox').is(':checked') )? true : false;					
					elementObj.defaultDate	    =   ( $(optionsWrapperID).find('.wordform-date-default-value').val()?.length == 0 )? 'Pick a date from calendar' : $(optionsWrapperID).find('.wordform-date-default-value').val();
					elementObj.defaultDateFormat=   ( $(optionsWrapperID).find('.wordform-default-date-display-format').val()?.length == 0 )? 'Month D, YYYY' : $(optionsWrapperID).find('.wordform-default-date-display-format').val();										
					elementObj.minDate          =   ( $(optionsWrapperID).find('.wordform-date-min-date-value').val()?.length == 0 ) ? '' : $(optionsWrapperID).find('.wordform-date-min-date-value').val();
					elementObj.maxDate          =   ( $(optionsWrapperID).find('.wordform-date-max-date-value').val()?.length == 0 ) ? '' : $(optionsWrapperID).find('.wordform-date-max-date-value').val();
					elementObj.disablePastDates =   ( $(optionsWrapperID).find('.wordform-date-disable-past-checkbox').is(':checked') ) ? true : false;
					elementObj.disableFutureDates = ( $(optionsWrapperID).find('.wordform-date-disable-future-checkbox').is(':checked') ) ? true : false;
					elementObj.calendarAccentColor = ( $(optionsWrapperID).find('.wordform-date-calendar-accent-color').val()?.length == 0 ) ? '#2563eb' : $(optionsWrapperID).find('.wordform-date-calendar-accent-color').val();
					elementObj.calendarSurfaceColor = ( $(optionsWrapperID).find('.wordform-date-calendar-surface-color').val()?.length == 0 ) ? '#ffffff' : $(optionsWrapperID).find('.wordform-date-calendar-surface-color').val();
					elementObj.calendarTextColor = ( $(optionsWrapperID).find('.wordform-date-calendar-text-color').val()?.length == 0 ) ? '#0f172a' : $(optionsWrapperID).find('.wordform-date-calendar-text-color').val();

					elementObj.elementIndex		=   elementIndex;
					inputElementArr.push( elementObj);

					// Before storing - Remove datepicker assigned dynamic Id attribute and class 'hasDatepicker' to make the datepicker reloads and work okay when contents loaded in edit form page
					$(optionsWrapperID).find('.wordform-date-default-value, .wordform-date-min-date-value, .wordform-date-max-date-value').removeAttr('id').removeClass('hasDatepicker');
					break;

				case 'time':
					elementObj					=	{};
					elementObj.type				=   elementType;
					elementObj.required			=   ( $(optionsWrapperID).find('.required-checkbox').is(':checked') )? true : false;
					elementObj.label			=   ( $(optionsWrapperID).find('.wordform-time-label-name').val()?.length == 0 )? 'Time' : $(optionsWrapperID).find('.wordform-time-label-name').val();
					elementObj.placeholderShow	=   ( $(optionsWrapperID).find('.time-placeholder-show-checkbox').is(':checked') )? true : false;
					elementObj.placeholderText	=   ( $(optionsWrapperID).find('.wordform-time-placeholder-text-input').val()?.length == 0 )? 'Select time' : $(optionsWrapperID).find('.wordform-time-placeholder-text-input').val();
					elementObj.defaultTime		=   ( $(optionsWrapperID).find('.wordform-time-hidden-raw-default-value').val()?.length == 0 )? '' : $(optionsWrapperID).find('.wordform-time-hidden-raw-default-value').val();
					elementObj.timeDisplayMode  =   ( $(optionsWrapperID).find('.wordform-time-display-mode').val()?.length == 0 ) ? '24h' : $(optionsWrapperID).find('.wordform-time-display-mode').val();
					elementObj.elementIndex		=   elementIndex;
					inputElementArr.push( elementObj);
					break;

				case 'datetime':
					elementObj					=	{};
					elementObj.type				=   elementType;
					elementObj.required			=   ( $(optionsWrapperID).find('.required-checkbox').is(':checked') )? true : false;
					elementObj.label			=   ( $(optionsWrapperID).find('.wordform-datetime-label-name').val()?.length == 0 )? 'DateTime' : $(optionsWrapperID).find('.wordform-datetime-label-name').val();
					elementObj.placeholderShow	=   ( $(optionsWrapperID).find('.datetime-placeholder-show-checkbox').is(':checked') )? true : false;					
					elementObj.placeholderText	=   ( $(optionsWrapperID).find('.wordform-datetime-placeholder-text-input').val()?.length == 0 )? 'Select date & time' : $(optionsWrapperID).find('.wordform-datetime-placeholder-text-input').val();
					
					elementObj.displayFormatHint	  = ( $(optionsWrapperID).find('.wordform-datetime-display-format-hint-show-checkbox').is(':checked') )? true : false;					
					// elementObj.defaultDateTime	  = ( $(optionsWrapperID).find('.wordform-datetime-default-value').data('datetime-value')?.length == 0 )? '' : $(optionsWrapperID).find('.wordform-datetime-default-value').data('datetime-value');
					elementObj.defaultDateTime	      = ( $(optionsWrapperID).find('.wordform-datetime-hidden-raw-format-default-value').val()?.length == 0 )? '' : $(optionsWrapperID).find('.wordform-datetime-hidden-raw-format-default-value').val();
					
					elementObj.defaultDateTimeSetting = ($(optionsWrapperID).find('.datetime-default-value-show-radio:checked').length === 0)? 'currentDateTime' : $(optionsWrapperID).find('.datetime-default-value-show-radio:checked').val();
					elementObj.timeDisplayMode        = ( $(optionsWrapperID).find('.wordform-datetime-time-display-mode').val()?.length == 0 ) ? '24h' : $(optionsWrapperID).find('.wordform-datetime-time-display-mode').val();
					elementObj.defaultDateTimeFormat  = ( $(optionsWrapperID).find('.wordform-default-datetime-display-format').val()?.length == 0 ) ? 'yy-mm-dd HH:mm' : $(optionsWrapperID).find('.wordform-default-datetime-display-format').val();
					elementObj.minDateTime           = ( $(optionsWrapperID).find('.wordform-datetime-min-datetime-value').val()?.length == 0 ) ? '' : $(optionsWrapperID).find('.wordform-datetime-min-datetime-value').val();
					elementObj.maxDateTime           = ( $(optionsWrapperID).find('.wordform-datetime-max-datetime-value').val()?.length == 0 ) ? '' : $(optionsWrapperID).find('.wordform-datetime-max-datetime-value').val();
					elementObj.disablePastDates      = ( $(optionsWrapperID).find('.wordform-datetime-disable-past-checkbox').is(':checked') ) ? true : false;
					elementObj.disableFutureDates    = ( $(optionsWrapperID).find('.wordform-datetime-disable-future-checkbox').is(':checked') ) ? true : false;
					elementObj.calendarAccentColor = ( $(optionsWrapperID).find('.wordform-datetime-calendar-accent-color').val()?.length == 0 ) ? '#2563eb' : $(optionsWrapperID).find('.wordform-datetime-calendar-accent-color').val();
					elementObj.calendarSurfaceColor = ( $(optionsWrapperID).find('.wordform-datetime-calendar-surface-color').val()?.length == 0 ) ? '#ffffff' : $(optionsWrapperID).find('.wordform-datetime-calendar-surface-color').val();
					elementObj.calendarTextColor = ( $(optionsWrapperID).find('.wordform-datetime-calendar-text-color').val()?.length == 0 ) ? '#0f172a' : $(optionsWrapperID).find('.wordform-datetime-calendar-text-color').val();
															
					elementObj.elementIndex		=   elementIndex;
					console.log('elementObj.defaultDateTime :' + elementObj.defaultDateTime);
					inputElementArr.push( elementObj);

					// Before saiving: Remove 'hasDatepicker has-datetimepicker' assigned with dynamic Id attribute and classes 'hasDatepicker has-datetimepicker' to make the datepicker & timepicker reloads to work properly when contents loaded in edit form page
					// After Saving: Add again 'hasDatepicker has-datetimepicker' classes to make the datepicker & timepicker reloads to work properly when contents loaded in edit form page without reloadng the page
					$(optionsWrapperID).find('.wordform-datetime-default-value, .wordform-datetime-min-datetime-value, .wordform-datetime-max-datetime-value').removeAttr('id').removeClass('hasDatepicker has-datetimepicker');
					break;

				case 'tel':
					elementObj					=	{};
					elementObj.type				=   elementType;
					elementObj.required			=   ( $(optionsWrapperID).find('.required-checkbox').is(':checked') )? true : false;
					elementObj.telhints			=   ( $(optionsWrapperID).find('.telhints-checkbox').is(':checked') )? true : false;
					elementObj.label			=   ( $(optionsWrapperID).find('.wordform-tel-label-name').val()?.length == 0 )? 'Tel' : $(optionsWrapperID).find('.wordform-tel-label-name').val();
					elementObj.placeholderShow	=   ( $(optionsWrapperID).find('.tel-placeholder-show-checkbox').is(':checked') )? true : false;					
					elementObj.placeholderText	=   ( $(optionsWrapperID).find('.wordform-tel-placeholder-text-input').val()?.length == 0 )? 'Enter Your Phone Number' : $(optionsWrapperID).find('.wordform-tel-placeholder-text-input').val();

					elementObj.minlength		=   $(optionsWrapperID).find('.wordform-tel-min-length').val();
					elementObj.maxlength		=   $(optionsWrapperID).find('.wordform-tel-max-length').val();					
					elementObj.pattern			=   $(optionsWrapperID).find('.wordform-input-tel-selected-pattern-regex-value').val();		
					elementObj.telhintsNumber	=   $(optionsWrapperID).find('.wordform-input-tel-selected-pattern-regex-example-phone-numbers').val();					
					elementObj.elementIndex		=   elementIndex;
					inputElementArr.push( elementObj);
					break;

	
				case 'email':
					elementObj					=	{};
					elementObj.type				=   elementType;
					elementObj.required			=   ( $(optionsWrapperID).find('.required-checkbox').is(':checked') )? true : false;
					elementObj.label			=   ( $(optionsWrapperID).find('.wordform-email-label-name').val()?.length == 0 )? 'Email' : $(optionsWrapperID).find('.wordform-email-label-name').val();	
					elementObj.placeholderShow	=   ( $(optionsWrapperID).find('.email-placeholder-show-checkbox').is(':checked') )? true : false;					
					elementObj.placeholderText	=   ( $(optionsWrapperID).find('.wordform-email-placeholder-text-input').val()?.length == 0 )? 'Write Your Email' : $(optionsWrapperID).find('.wordform-email-placeholder-text-input').val();

					elementObj.elementIndex		=   elementIndex;
					inputElementArr.push( elementObj);
					break;

				case 'address':
					elementObj					 =	{};
					elementObj.type				 =   elementType;
					elementObj.required			 =   ( $(optionsWrapperID).find('.required-checkbox').is(':checked') )? true : false;
					elementObj.label			 =   ( $(optionsWrapperID).find('.wordform-address-label-name').val()?.length == 0 )? 'Address' : $(optionsWrapperID).find('.wordform-address-label-name').val();
					elementObj.placeholderShow	 =   ( $(optionsWrapperID).find('.address-placeholder-show-checkbox').is(':checked') )? true : false;
					elementObj.placeholderStreet =   ( $(optionsWrapperID).find('.wordform-address-placeholder-street-input').val()?.length == 0 )? 'Street Address' : $(optionsWrapperID).find('.wordform-address-placeholder-street-input').val();
					elementObj.placeholderCity	 =   ( $(optionsWrapperID).find('.wordform-address-placeholder-city-input').val()?.length == 0 )? 'City' : $(optionsWrapperID).find('.wordform-address-placeholder-city-input').val();
					elementObj.placeholderState	 =   ( $(optionsWrapperID).find('.wordform-address-placeholder-state-input').val()?.length == 0 )? 'State / Region' : $(optionsWrapperID).find('.wordform-address-placeholder-state-input').val();
					elementObj.placeholderZip	 =   ( $(optionsWrapperID).find('.wordform-address-placeholder-zip-input').val()?.length == 0 )? 'ZIP / Postal Code' : $(optionsWrapperID).find('.wordform-address-placeholder-zip-input').val();
					elementObj.placeholderCountry =  ( $(optionsWrapperID).find('.wordform-address-placeholder-country-input').val()?.length == 0 )? 'Country' : $(optionsWrapperID).find('.wordform-address-placeholder-country-input').val();
					elementObj.elementIndex		 =   elementIndex;
					inputElementArr.push( elementObj);
					break;

				case 'sectionhtml':
					elementObj					=	{};
					elementObj.type				=   elementType;
					elementObj.label			=   ( $(optionsWrapperID).find('.wordform-sectionhtml-title-input').val()?.length == 0 )? 'Section Title' : $(optionsWrapperID).find('.wordform-sectionhtml-title-input').val();
					elementObj.content			=   ( $(optionsWrapperID).find('.wordform-sectionhtml-content-input').val()?.length == 0 )? 'Add instructions, notes, or custom HTML content.' : $(optionsWrapperID).find('.wordform-sectionhtml-content-input').val();
					elementObj.elementIndex		=   elementIndex;
					inputElementArr.push( elementObj);
					break;

				case 'maskinput':
					elementObj					=	{};
					elementObj.type				=   elementType;
					elementObj.required			=   ( $(optionsWrapperID).find('.required-checkbox').is(':checked') )? true : false;
					elementObj.label			=   ( $(optionsWrapperID).find('.wordform-maskinput-label-name').val()?.length == 0 )? 'Masked Input' : $(optionsWrapperID).find('.wordform-maskinput-label-name').val();
					elementObj.placeholderShow	=   ( $(optionsWrapperID).find('.maskinput-placeholder-show-checkbox').is(':checked') )? true : false;
					elementObj.placeholderText	=   ( $(optionsWrapperID).find('.wordform-maskinput-placeholder-text-input').val()?.length == 0 )? 'AB-12345' : $(optionsWrapperID).find('.wordform-maskinput-placeholder-text-input').val();
					elementObj.pattern			=   ( $(optionsWrapperID).find('.wordform-maskinput-pattern-input').val()?.length == 0 )? '^[A-Z]{2}-[0-9]{5}$' : $(optionsWrapperID).find('.wordform-maskinput-pattern-input').val();
					elementObj.elementIndex		=   elementIndex;
					inputElementArr.push( elementObj);
					break;

				case 'rating':
					elementObj					=	{};
					elementObj.type				=   elementType;
					elementObj.required			=   ( $(optionsWrapperID).find('.required-checkbox').is(':checked') )? true : false;
					elementObj.label			=   ( $(optionsWrapperID).find('.wordform-rating-label-name').val()?.length == 0 )? 'Rating' : $(optionsWrapperID).find('.wordform-rating-label-name').val();
					elementObj.scale			=   ( $(optionsWrapperID).find('.wordform-rating-scale-input').val()?.length == 0 )? '5' : $(optionsWrapperID).find('.wordform-rating-scale-input').val();
					elementObj.lowText			=   ( $(optionsWrapperID).find('.wordform-rating-low-text-input').val()?.length == 0 )? 'Poor' : $(optionsWrapperID).find('.wordform-rating-low-text-input').val();
					elementObj.highText			=   ( $(optionsWrapperID).find('.wordform-rating-high-text-input').val()?.length == 0 )? 'Excellent' : $(optionsWrapperID).find('.wordform-rating-high-text-input').val();
					elementObj.elementIndex		=   elementIndex;
					inputElementArr.push( elementObj);
					break;

				case 'likert':
					elementObj					=	{};
					elementObj.type				=   elementType;
					elementObj.required			=   ( $(optionsWrapperID).find('.required-checkbox').is(':checked') )? true : false;
					elementObj.label			=   ( $(optionsWrapperID).find('.wordform-likert-label-name').val()?.length == 0 )? 'Likert Scale' : $(optionsWrapperID).find('.wordform-likert-label-name').val();
					elementObj.rowLabels		=   wordformCollectLikertOptionValues($(optionsWrapperID), 'row');
					elementObj.columnLabels		=   wordformCollectLikertOptionValues($(optionsWrapperID), 'column');
					if (elementObj.rowLabels.length === 0) {
						elementObj.rowLabels = wordformGetLikertDefaultRows();
					}
					if (elementObj.columnLabels.length < 2) {
						elementObj.columnLabels = wordformGetLikertDefaultColumns();
					}
					elementObj.elementIndex		=   elementIndex;
					inputElementArr.push( elementObj );
					break;

				case 'hidden':
					elementObj					=	{};
					elementObj.type				=   elementType;
					elementObj.label			=   ( $(optionsWrapperID).find('.wordform-hidden-label-name').val()?.length == 0 )? 'Hidden Field' : $(optionsWrapperID).find('.wordform-hidden-label-name').val();
					elementObj.defaultValue		=   ( $(optionsWrapperID).find('.wordform-hidden-field-value-input').val()?.length == 0 )? 'utm_source' : $(optionsWrapperID).find('.wordform-hidden-field-value-input').val();
					elementObj.elementIndex		=   elementIndex;
					inputElementArr.push( elementObj);
					break;
					
				case 'captcha':
					elementObj					=	{};
					elementObj.type				=   elementType;
					elementObj.required			=   ( $(optionsWrapperID).find('.required-checkbox').is(':checked') ) ? true : false;
					elementObj.label			=   ( $(optionsWrapperID).find('.wordform-captcha-label-name').val()?.length == 0 )? 'Captcha' : $(optionsWrapperID).find('.wordform-captcha-label-name').val();					
					elementObj.placeholderShow	=   ( $(optionsWrapperID).find('.captcha-placeholder-show-checkbox').is(':checked') )? true : false;					
					elementObj.placeholderText	=   ( $(optionsWrapperID).find('.wordform-captcha-placeholder-text-input').val()?.length == 0 )? 'Type Captcha Here' : $(optionsWrapperID).find('.wordform-captcha-placeholder-text-input').val();
					elementObj.digitLength      =   ( $(optionsWrapperID).find('.wordform-captcha-digit-length-select').val()?.length == 0 ) ? 4 : $(optionsWrapperID).find('.wordform-captcha-digit-length-select').val();
					elementObj.fontStyle        =   ( $(optionsWrapperID).find('.wordform-captcha-font-style-select').val()?.length == 0 ) ? 'blackopsone' : $(optionsWrapperID).find('.wordform-captcha-font-style-select').val();
					elementObj.align			=   ( $(optionsWrapperID).find('.wordform-build-captcha-template-align-input').val()?.length == 0 )? 'left' : $(optionsWrapperID).find('input[name="wordform-build-captcha-template-align-input"]:checked').val();
					elementObj.styleMode		=   ( $(optionsWrapperID).find('.wordform-captcha-style-mode-radio:checked').length === 0 ) ? 'template' : $(optionsWrapperID).find('.wordform-captcha-style-mode-radio:checked').val();
					elementObj.backgroundColor	=   ( $(optionsWrapperID).find('.wordform-captcha-background-color-input').val()?.length == 0 )? '#eef2ff' : $(optionsWrapperID).find('.wordform-captcha-background-color-input').val();
					elementObj.textColor		=   ( $(optionsWrapperID).find('.wordform-captcha-text-color-input').val()?.length == 0 )? '#111827' : $(optionsWrapperID).find('.wordform-captcha-text-color-input').val();
					elementObj.noiseColor		=   ( $(optionsWrapperID).find('.wordform-captcha-noise-color-input').val()?.length == 0 )? '#cbd5e1' : $(optionsWrapperID).find('.wordform-captcha-noise-color-input').val();
					elementObj.elementIndex		=   elementIndex;
					elementObj.templateName     =   ($(optionsWrapperID).find('.wordform-captcha-template-radio:checked').length === 0)
						? 'all'
						: $(optionsWrapperID).find('.wordform-captcha-template-radio:checked').val();
					elementObj.elementIndex		=   elementIndex;
					
					inputElementArr.push( elementObj);
					break;					
					
				case 'gcaptcha':
					elementObj					=	{};
					elementObj.type				=   elementType;
					elementObj.required			=   true; // Captcha required protection always true
					elementObj.label			=   ( $(optionsWrapperID).find('.wordform-gcaptcha-label-name').val()?.length == 0 )? 'Google reCaptcha' : $(optionsWrapperID).find('.wordform-gcaptcha-label-name').val();
					elementObj.labelshow		=   ( $(optionsWrapperID).find('.recaptcha-label-checkbox').is(':checked') )? true : false;					
					elementObj.elementIndex		=   elementIndex;
					inputElementArr.push( elementObj);
					break;	

				case 'hcaptcha':
					elementObj					=	{};
					elementObj.type				=   elementType;
					elementObj.required			=   true;
					elementObj.label			=   ( $(optionsWrapperID).find('.wordform-hcaptcha-label-name').val()?.length == 0 )? 'hCaptcha' : $(optionsWrapperID).find('.wordform-hcaptcha-label-name').val();
					elementObj.labelshow		=   ( $(optionsWrapperID).find('.hcaptcha-label-checkbox').is(':checked') )? true : false;
					elementObj.elementIndex		=   elementIndex;
					inputElementArr.push( elementObj);
					break;

				case 'radio':
					elementObj					=	{};
					elementObj.type				=   elementType;
					elementObj.required			=   ( $(optionsWrapperID).find('.required-checkbox').is(':checked') )? true : false;
					elementObj.label			=   ( $(optionsWrapperID).find('.wordform-radio-label-name').val()?.length == 0 )? 'Multiple Choice' : $(optionsWrapperID).find('.wordform-radio-label-name').val();	
					elementObj.elementIndex		=   elementIndex;
					
					
					multipleOptions				= 	[];
					$(optionsWrapperID).find('.wordform-field-options input[type="radio"]').each(function() {						
						options					=	{};		
						options.checkStatus		=	( $(this).is(':checked') )? true : false;
						options.optionText		=	( $(this).next().val()?.length == 0 )? 'Option Text' : $(this).next().val();
						multipleOptions.push( options );						
					});					
					elementObj.multiOption		= multipleOptions;
					
					inputElementArr.push( elementObj);
					break;
					
				case 'checkbox':
					elementObj					=	{};
					elementObj.type				=   elementType;
					elementObj.required			=   ( $(optionsWrapperID).find('.required-checkbox').is(':checked') )? true : false;
					elementObj.label			=   ( $(optionsWrapperID).find('.wordform-checkbox-label-name').val()?.length == 0 )? 'Checkboxes' : $(optionsWrapperID).find('.wordform-checkbox-label-name').val();	
					elementObj.elementIndex		=   elementIndex;
					
					
					multipleOptions				= 	[];
					$(optionsWrapperID).find('.wordform-field-options input[type="checkbox"]').each(function() {						
						options					=	{};		
						options.checkStatus		=	( $(this).is(':checked') )? true : false;
						options.optionText		=	( $(this).next().val().length == 0 )? 'Checkbox Text' : $(this).next().val();
						multipleOptions.push( options );						
					});					
					elementObj.multiOption		= multipleOptions;					
					
					inputElementArr.push( elementObj);
					break;
					
				case 'select':
					elementObj					=	{};
					elementObj.type				=   elementType;
					elementObj.required			=   ( $(optionsWrapperID).find('.required-checkbox').is(':checked') )? true : false;
					elementObj.label			=   ( $(optionsWrapperID).find('.wordform-select-label-name').val()?.length == 0 )? 'Dropdown Options' : $(optionsWrapperID).find('.wordform-select-label-name').val();	
					elementObj.elementIndex		=   elementIndex;
					
					
					multipleOptions				= 	[];
					$(optionsWrapperID).find('.wordform-field-options input[type="radio"]').each(function() {						
						options					=	{};		
						options.checkStatus		=	( $(this).is(':checked') )? true : false;
						options.optionText		=	( $(this).next().val().length == 0 )? 'Select Text' : $(this).next().val();
						multipleOptions.push( options );						
					});					
					elementObj.multiOption		= multipleOptions;					
					
					inputElementArr.push( elementObj);
					break;		
					
				case 'upload':
					elementObj					=	{};
					elementObj.type				=   elementType;
					elementObj.required			=   ( $(optionsWrapperID).find('.required-checkbox').is(':checked') )? true : false;
					elementObj.multiple			=   ( $(optionsWrapperID).find('.multiple-checkbox').is(':checked') )? true : false;
					elementObj.label			=   ( $(optionsWrapperID).find('.wordform-upload-label-name').val()?.length == 0 )? 'Upload' : $(optionsWrapperID).find('.wordform-upload-label-name').val();	
					elementObj.selectFileLabel	=   ( $(optionsWrapperID).find('.wordform-upload-select-file-label-name').val()?.length == 0 )? 'Select File' : $(optionsWrapperID).find('.wordform-upload-select-file-label-name').val();	
					elementObj.elementIndex		=   elementIndex;
										
					multipleOptions				= 	[];
					$(optionsWrapperID).find('.wordform-field-options input[type="checkbox"]').each(function() {						
						options					=	{};		
						options.checkStatus		=	( $(this).is(':checked') )? true : false;						
						options.fileTypeValue	=	$(this).val();
						options.fileTypeText	=	$(this).next().text();
						multipleOptions.push( options );						
					});					
					elementObj.multiOption		= multipleOptions;					
					
					inputElementArr.push( elementObj );
					break;

				case 'signature':
					elementObj					=	{};
					elementObj.type				=   elementType;
					elementObj.required			=   ( $(optionsWrapperID).find('.required-checkbox').is(':checked') )? true : false;
					elementObj.label			=   ( $(optionsWrapperID).find('.wordform-signature-label-name').val()?.length == 0 )? 'Signature' : $(optionsWrapperID).find('.wordform-signature-label-name').val();
					elementObj.clearButtonText	=   ( $(optionsWrapperID).find('.wordform-signature-clear-button-text-input').val()?.length == 0 )? 'Clear Signature' : $(optionsWrapperID).find('.wordform-signature-clear-button-text-input').val();
					elementObj.canvasHeight		=   ( $(optionsWrapperID).find('.wordform-signature-canvas-height-input').val()?.length == 0 )? '180' : $(optionsWrapperID).find('.wordform-signature-canvas-height-input').val();
					elementObj.elementIndex		=   elementIndex;
					inputElementArr.push( elementObj );
					break;

				case 'pagebreak':
					elementObj                    =   {};
					elementObj.type               =   elementType;
					elementObj.stepTitle          =   ( $(optionsWrapperID).find('.wordform-pagebreak-step-title-input').val()?.length == 0 ) ? 'Next Step' : $(optionsWrapperID).find('.wordform-pagebreak-step-title-input').val();
					elementObj.nextButtonText     =   ( $(optionsWrapperID).find('.wordform-pagebreak-next-button-text-input').val()?.length == 0 ) ? 'Next' : $(optionsWrapperID).find('.wordform-pagebreak-next-button-text-input').val();
					elementObj.previousButtonText =   ( $(optionsWrapperID).find('.wordform-pagebreak-previous-button-text-input').val()?.length == 0 ) ? 'Back' : $(optionsWrapperID).find('.wordform-pagebreak-previous-button-text-input').val();
					elementObj.nextButtonAlign    =   $(optionsWrapperID).find('.wordform-pagebreak-next-button-align-input:checked').val() || 'right';
					elementObj.previousButtonAlign =  $(optionsWrapperID).find('.wordform-pagebreak-previous-button-align-input:checked').val() || 'left';
					elementObj.elementIndex       =   elementIndex;
					inputElementArr.push( elementObj );
					break;

				case 'payment_item':
					elementObj					=	{};
					elementObj.type				=   elementType;
					elementObj.label			=   ( $(optionsWrapperID).find('.wordform-payment-item-label-name').val()?.length == 0 ) ? 'Payment Item' : $(optionsWrapperID).find('.wordform-payment-item-label-name').val();
					elementObj.amount			=   ( $(optionsWrapperID).find('.wordform-payment-item-amount').val()?.length == 0 ) ? '0.00' : $(optionsWrapperID).find('.wordform-payment-item-amount').val();
					elementObj.description		=   ( $(optionsWrapperID).find('.wordform-payment-item-description').val()?.length == 0 ) ? 'Fixed price item' : $(optionsWrapperID).find('.wordform-payment-item-description').val();
					elementObj.elementIndex		=   elementIndex;
					inputElementArr.push( elementObj );
					break;

				case 'payment_coupon':
					elementObj					=	{};
					elementObj.type				=   elementType;
					elementObj.label			=   ( $(optionsWrapperID).find('.wordform-payment-coupon-label-name').val()?.length == 0 ) ? 'Coupon Code' : $(optionsWrapperID).find('.wordform-payment-coupon-label-name').val();
					elementObj.placeholderText	=   ( $(optionsWrapperID).find('.wordform-payment-coupon-placeholder-text-input').val()?.length == 0 ) ? 'Enter coupon code' : $(optionsWrapperID).find('.wordform-payment-coupon-placeholder-text-input').val();
					elementObj.applyButtonText	=   ( $(optionsWrapperID).find('.wordform-payment-coupon-apply-button-text-input').val()?.length == 0 ) ? 'Apply Coupon' : $(optionsWrapperID).find('.wordform-payment-coupon-apply-button-text-input').val();
					elementObj.removeButtonText	=   ( $(optionsWrapperID).find('.wordform-payment-coupon-remove-button-text-input').val()?.length == 0 ) ? 'Remove Coupon' : $(optionsWrapperID).find('.wordform-payment-coupon-remove-button-text-input').val();
					elementObj.invalidMessage	=   ( $(optionsWrapperID).find('.wordform-payment-coupon-invalid-message-input').val()?.length == 0 ) ? 'Coupon code is not valid.' : $(optionsWrapperID).find('.wordform-payment-coupon-invalid-message-input').val();
					elementObj.appliedMessage	=   ( $(optionsWrapperID).find('.wordform-payment-coupon-applied-message-input').val()?.length == 0 ) ? 'Coupon applied successfully.' : $(optionsWrapperID).find('.wordform-payment-coupon-applied-message-input').val();
					elementObj.elementIndex		=   elementIndex;
					inputElementArr.push( elementObj );
					break;

				case 'payment_custom_amount':
					elementObj					=	{};
					elementObj.type				=   elementType;
					elementObj.required			=   ( $(optionsWrapperID).find('.required-checkbox').is(':checked') ) ? true : false;
					elementObj.label			=   ( $(optionsWrapperID).find('.wordform-payment-custom-amount-label-name').val()?.length == 0 ) ? 'Custom Amount' : $(optionsWrapperID).find('.wordform-payment-custom-amount-label-name').val();
					elementObj.placeholderText	=   ( $(optionsWrapperID).find('.wordform-payment-custom-amount-placeholder-text-input').val()?.length == 0 ) ? 'Enter amount' : $(optionsWrapperID).find('.wordform-payment-custom-amount-placeholder-text-input').val();
					elementObj.defaultAmount	=   ( $(optionsWrapperID).find('.wordform-payment-custom-amount-default').val()?.length == 0 ) ? '' : $(optionsWrapperID).find('.wordform-payment-custom-amount-default').val();
					elementObj.minAmount		=   ( $(optionsWrapperID).find('.wordform-payment-custom-amount-min').val()?.length == 0 ) ? '' : $(optionsWrapperID).find('.wordform-payment-custom-amount-min').val();
					elementObj.elementIndex		=   elementIndex;
					inputElementArr.push( elementObj );
					break;

				case 'payment_quantity':
					elementObj					=	{};
					elementObj.type				=   elementType;
					elementObj.required			=   ( $(optionsWrapperID).find('.required-checkbox').is(':checked') ) ? true : false;
					elementObj.label			=   ( $(optionsWrapperID).find('.wordform-payment-quantity-label-name').val()?.length == 0 ) ? 'Quantity' : $(optionsWrapperID).find('.wordform-payment-quantity-label-name').val();
					elementObj.defaultQuantity	=   ( $(optionsWrapperID).find('.wordform-payment-quantity-default-input').val()?.length == 0 ) ? '1' : $(optionsWrapperID).find('.wordform-payment-quantity-default-input').val();
					elementObj.minQuantity		=   ( $(optionsWrapperID).find('.wordform-payment-quantity-min-input').val()?.length == 0 ) ? '1' : $(optionsWrapperID).find('.wordform-payment-quantity-min-input').val();
					elementObj.maxQuantity		=   ( $(optionsWrapperID).find('.wordform-payment-quantity-max-input').val()?.length == 0 ) ? '' : $(optionsWrapperID).find('.wordform-payment-quantity-max-input').val();
					elementObj.elementIndex		=   elementIndex;
					inputElementArr.push( elementObj );
					break;

				case 'payment_summary':
					elementObj					=	{};
					elementObj.type				=   elementType;
					elementObj.label			=   ( $(optionsWrapperID).find('.wordform-payment-summary-label-name').val()?.length == 0 ) ? 'Payment Summary' : $(optionsWrapperID).find('.wordform-payment-summary-label-name').val();
					elementObj.emptyText		=   ( $(optionsWrapperID).find('.wordform-payment-summary-empty-text-input').val()?.length == 0 ) ? 'Amounts will appear here' : $(optionsWrapperID).find('.wordform-payment-summary-empty-text-input').val();
					elementObj.elementIndex		=   elementIndex;
					inputElementArr.push( elementObj );
					break;

				case 'payment_method':
					elementObj					=	{};
					elementObj.type				=   elementType;
					elementObj.label			=   ( $(optionsWrapperID).find('.wordform-payment-method-label-name').val()?.length == 0 ) ? 'Payment Method' : $(optionsWrapperID).find('.wordform-payment-method-label-name').val();
					elementObj.helperText		=   ( $(optionsWrapperID).find('.wordform-payment-method-helper-text-input').val()?.length == 0 ) ? 'Choose how you want to pay' : $(optionsWrapperID).find('.wordform-payment-method-helper-text-input').val();
					elementObj.defaultGateway	=   ( $(optionsWrapperID).find('.wordform-payment-method-default-gateway-radio:checked').val()?.length == 0 ) ? 'stripe' : $(optionsWrapperID).find('.wordform-payment-method-default-gateway-radio:checked').val();
					elementObj.elementIndex		=   elementIndex;
					inputElementArr.push( elementObj );
					break;

				case 'stripe':
					elementObj					=	{};
					elementObj.type				=   elementType;
					elementObj.label			=   ( $(optionsWrapperID).find('.wordform-stripe-label-name').val()?.length == 0 ) ? 'Stripe Payment' : $(optionsWrapperID).find('.wordform-stripe-label-name').val();
					elementObj.buttonText		=   ( $(optionsWrapperID).find('.wordform-stripe-button-text-input').val()?.length == 0 ) ? 'Pay with Card' : $(optionsWrapperID).find('.wordform-stripe-button-text-input').val();
					elementObj.description		=   ( $(optionsWrapperID).find('.wordform-stripe-description-input').val()?.length == 0 ) ? 'Secure card payment via Stripe' : $(optionsWrapperID).find('.wordform-stripe-description-input').val();
					elementObj.elementIndex		=   elementIndex;
					inputElementArr.push( elementObj );
					break;

				case 'paypal':
					elementObj					=	{};
					elementObj.type				=   elementType;
					elementObj.label			=   ( $(optionsWrapperID).find('.wordform-paypal-label-name').val()?.length == 0 ) ? 'PayPal Payment' : $(optionsWrapperID).find('.wordform-paypal-label-name').val();
					elementObj.buttonText		=   ( $(optionsWrapperID).find('.wordform-paypal-button-text-input').val()?.length == 0 ) ? 'Pay with PayPal' : $(optionsWrapperID).find('.wordform-paypal-button-text-input').val();
					elementObj.description		=   ( $(optionsWrapperID).find('.wordform-paypal-description-input').val()?.length == 0 ) ? 'Checkout with your PayPal account' : $(optionsWrapperID).find('.wordform-paypal-description-input').val();
					elementObj.elementIndex		=   elementIndex;
					inputElementArr.push( elementObj );
					break;

				case 'square':
					elementObj					=	{};
					elementObj.type				=   elementType;
					elementObj.label			=   ( $(optionsWrapperID).find('.wordform-square-label-name').val()?.length == 0 ) ? 'Square Payment' : $(optionsWrapperID).find('.wordform-square-label-name').val();
					elementObj.buttonText		=   ( $(optionsWrapperID).find('.wordform-square-button-text-input').val()?.length == 0 ) ? 'Pay with Square' : $(optionsWrapperID).find('.wordform-square-button-text-input').val();
					elementObj.description		=   ( $(optionsWrapperID).find('.wordform-square-description-input').val()?.length == 0 ) ? 'Secure card payment via Square' : $(optionsWrapperID).find('.wordform-square-description-input').val();
					elementObj.elementIndex		=   elementIndex;
					inputElementArr.push( elementObj );
					break;

				case 'authorizenet':
					elementObj					=	{};
					elementObj.type				=   elementType;
					elementObj.label			=   ( $(optionsWrapperID).find('.wordform-authorizenet-label-name').val()?.length == 0 ) ? 'Authorize.Net Payment' : $(optionsWrapperID).find('.wordform-authorizenet-label-name').val();
					elementObj.buttonText		=   ( $(optionsWrapperID).find('.wordform-authorizenet-button-text-input').val()?.length == 0 ) ? 'Pay with Authorize.Net' : $(optionsWrapperID).find('.wordform-authorizenet-button-text-input').val();
					elementObj.description		=   ( $(optionsWrapperID).find('.wordform-authorizenet-description-input').val()?.length == 0 ) ? 'Secure card payment via Authorize.Net' : $(optionsWrapperID).find('.wordform-authorizenet-description-input').val();
					elementObj.elementIndex		=   elementIndex;
					inputElementArr.push( elementObj );
					break;

				case 'terms':
					elementObj					=	{};
					elementObj.type				=   elementType;
					elementObj.required			=   ( $(optionsWrapperID).find('.required-checkbox').is(':checked') )? true : false;					
					elementObj.label            = ( $(optionsWrapperID).find('.wordform-terms-label-name').val()?.length == 0 )? '' : $(optionsWrapperID).find('.wordform-terms-label-name').val();
					elementObj.termsConditionsText = ( $(optionsWrapperID).find('.wordform-terms-text').val()?.length == 0 )? 'I agree to the terms and conditions.' : $(optionsWrapperID).find('.wordform-terms-text').val();
					elementObj.termsConditionsUrl  = ( $(optionsWrapperID).find('.wordform-terms-conditions-url-input').val()?.length == 0 )? '' : $(optionsWrapperID).find('.wordform-terms-conditions-url-input').val();
					elementObj.termsConditionsTextClickable = ( $(optionsWrapperID).find('.clickable-term-conditions-text-checkbox').is(':checked') )? true : false;
					
					elementObj.charLimit		=   '';					
					elementObj.elementIndex		=   elementIndex;
					inputElementArr.push( elementObj);
					break;

				case 'gdpr':
					elementObj					=	{};
					elementObj.type				=   elementType;
					elementObj.required			=   ( $(optionsWrapperID).find('.required-checkbox').is(':checked') )? true : false;
					elementObj.label            = ( $(optionsWrapperID).find('.wordform-gdpr-label-name').val()?.length == 0 )? 'GDPR Consent' : $(optionsWrapperID).find('.wordform-gdpr-label-name').val();
					elementObj.gdprConsentText  = ( $(optionsWrapperID).find('.wordform-gdpr-text').val()?.length == 0 )? 'I agree to the privacy policy and consent to data processing.' : $(optionsWrapperID).find('.wordform-gdpr-text').val();
					elementObj.gdprPolicyUrl    = ( $(optionsWrapperID).find('.wordform-gdpr-policy-url-input').val()?.length == 0 )? '' : $(optionsWrapperID).find('.wordform-gdpr-policy-url-input').val();
					elementObj.gdprConsentTextClickable = ( $(optionsWrapperID).find('.clickable-gdpr-text-checkbox').is(':checked') )? true : false;
					elementObj.elementIndex		=   elementIndex;
					inputElementArr.push( elementObj);
					break;
						
				case 'form-name':
					elementObj					=	{};
					elementObj.type				=   elementType;
					elementObj.hide				=   ( $(optionsWrapperID).find('.wordform-form-name-display-checkbox').is(':checked') )? true : false;
					elementObj.label			=   ( $(optionsWrapperID).find('.wordform-form-name-label-input').val()?.length == 0 )? 'New Form' : $(optionsWrapperID).find('.wordform-form-name-label-input').val();	
					elementObj.formClasses	    =   ( $(optionsWrapperID).find('.wordform-form-name-class-names-input').val()?.length == 0 )? '' : $(optionsWrapperID).find('.wordform-form-name-class-names-input').val();						
					elementObj.align			=   ( $(optionsWrapperID).find('.wordform-build-form-name-align-input').val()?.length == 0 )? sc_wordform_metabox_script_obj.sc_wordform_submit_align : $(optionsWrapperID).find('input[name="wordform-build-form-name-align-input"]:checked').val();
					elementObj.elementIndex		=   elementIndex;
					inputElementArr.push( elementObj);
					break;
					
				case 'submit-button':
					elementObj					=	{};
					elementObj.type				=   elementType;										
					elementObj.label			=   ( $(optionsWrapperID).find('.wordform-submit-button-label-input').val()?.length == 0 )? sc_wordform_metabox_script_obj.sc_wordform_submit_text : $(optionsWrapperID).find('.wordform-submit-button-label-input').val();
					elementObj.align			=   ( $(optionsWrapperID).find('.wordform-build-submit-button-align-input').val()?.length == 0 )? sc_wordform_metabox_script_obj.sc_wordform_submit_align : $(optionsWrapperID).find('input[name="wordform-build-submit-button-align-input"]:checked').val();
					elementObj.buttonFullWidth	=   ( $(optionsWrapperID).find('.wordform-submit-button-full-width-input-checkbox').is(':checked') )? true : false;
					elementObj.elementIndex		=   elementIndex;
					inputElementArr.push( elementObj);
					break;
					
										
			} // switch			

			if (elementObj && elementObj.type && wordformElementSupportsAdminLabel(elementObj.type)) {
				const $currentOptionsWrapper = $(optionsWrapperID);
				if (elementObj.type === 'firstlastname') {
					elementObj.adminLabelFirst = wordformReadAdminLabelValue($currentOptionsWrapper, elementObj.type, elementIndex, 'first');
					elementObj.adminLabelLast = wordformReadAdminLabelValue($currentOptionsWrapper, elementObj.type, elementIndex, 'last');
				} else {
					elementObj.adminLabel = wordformReadAdminLabelValue($currentOptionsWrapper, elementObj.type, elementIndex);
				}
			}

			if (elementObj && elementObj.type && wordformElementSupportsSharedHelpText(elementObj.type)) {
				elementObj.helpText = ($(optionsWrapperID).find('.wordform-shared-help-text-input').val() || '').trim();
			}

			if (elementObj && elementObj.type && wordformElementSupportsSharedFieldWidth(elementObj.type)) {
				elementObj.fieldWidth = wordformReadSharedFieldWidthValue($(optionsWrapperID), elementObj.type);
			}

			if (elementObj && elementObj.type && wordformElementSupportsSharedCustomClass(elementObj.type)) {
				elementObj.customCssClass = wordformReadSharedCustomClassValue($(optionsWrapperID), elementObj.type);
			}

			if (elementObj && elementObj.type && wordformElementSupportsSharedDefaultValue(elementObj.type)) {
				elementObj.defaultValue = wordformReadSharedDefaultValue($(optionsWrapperID), elementObj.type);
			}
			
		}); // each(function)		

		inputElementArr = wordformNormalizeAdminLabelsBeforeSave(inputElementArr);
		messageWrapper.html('');
		messageWrapper.removeClass('text-error text-success text-info text-warning show');
		let scWordFormName	= $('.wordform-form-name-label-input').val();	
		
		// If no element dropped yet!
		let scWordFormDroppedElementLength  = $('.wordform-dropzone-div-wrapper').children().length;		
		if ( scWordFormDroppedElementLength > 0 ) {
			// messageWrapper.html('<i class="fa-solid fa-file-circle-check fa-spin"></i>').addClass('text-info');
			// showWordformMessage('text-info', '<i class="fa-solid fa-file-circle-check fa-spin"></i>' );
			
			$.ajax({
			  type:"POST",		  
			  url: sc_wordform_metabox_script_obj.adminajax_url,
			  data : {			    
					action 	 : 'sc_wordform_save',
					security : sc_wordform_metabox_script_obj.nonce,				
					params   : inputElementArr,
					saveMeta : formSaveMeta			    
					},		  
			  success: function(data) { 
				//  console.log(data); 
				 let jsonData	= JSON.parse( data );
				  if ( jsonData.status == 'success' ) {
					  $('.wordform-form-saved').val(jsonData.formSaved);
					  $('.wordform-created-form-id').val(jsonData.savedFormID);
					//   messageWrapper.html(jsonData.reason ).removeClass('text-info').addClass('text-success');
					  showWordformMessage('text-success', jsonData.reason );

					  $('.wordform-preview-btn').prop( 'href', jsonData.previewURL );
					  $('.wordform-preview-btn').removeClass('disabled');

					  if ( jsonData.savedFormID ) {
						  let builtFormMeta					=  {};
						  builtFormMeta.builtForm			=  $('.wordform-builder-div-wrapper').clone().html();					  
						  builtFormMeta.builtFormOptions	=  $('.wordform-builder-form-options-div-wrapper').clone().html();						  
						  builtFormMeta.formID				=  jsonData.savedFormID;
						  builtFormMeta.builderSchemaVersion = 2;

						  // Save edit form elements html data
						  wordFormBuiltDataStore( builtFormMeta );

						// Init DateTime present wrappers without page reload - after save contents - during saving we remove hasDatepicker has-datetimepicker
						$('.wordform-date-field-options-wrapper').each(function () {
							const $wrapper = $(this);
							initWordformAdminDatePickerInput($wrapper.find('.wordform-date-default-value'));
							initWordformAdminDatePickerInput($wrapper.find('.wordform-date-min-date-value'));
							initWordformAdminDatePickerInput($wrapper.find('.wordform-date-max-date-value'));
						});
						$('.wordform-datetime-field-options-wrapper').each(function () {
							initWrapper($(this));
							const $wrapper = $(this);
							initWordformAdminDateTimeLimitPicker($wrapper.find('.wordform-datetime-min-datetime-value'));
							initWordformAdminDateTimeLimitPicker($wrapper.find('.wordform-datetime-max-datetime-value'));
						});

					  }
				  }
				  else if ( jsonData.status == 'fail' ) {					  
					//   messageWrapper.html(jsonData.reason ).removeClass('text-info').addClass('text-error');
					  showWordformMessage('text-error', jsonData.reason );
				  }
				  else {
					// messageWrapper.html( 'Something went wrong.' ).removeClass('text-info').addClass('text-error');
					   showWordformMessage('text-error', 'Something went wrong. Try again.' );
				  }
				},
			  error: function( xhr, status, error ) { 
				 console.log(xhr); 
				 console.log(status); 
				 console.log(error); 				 
				}
			});
		}
		// No element dropped yet!
		else {
			// messageWrapper.html(sc_wordform_metabox_script_obj.noElementDroppedMsg).addClass('text-info');
			showWordformMessage('text-info', sc_wordform_metabox_script_obj.noElementDroppedMsg );
		}		
	});

	// Save: Auto-hide after 7 seconds displayed messages	
	// showWordformMessage('text-success', 'Form saved successfully!');
	// showWordformMessage('text-error', 'Failed to save settings. Please try again.');
	// showWordformMessage('text-info', 'Refreshing form data...');
	(function ($) {
		let hideTimeout;

		window.showWordformMessage = function (type, text) {
			const $msg = $('.wordform-message-info');

			// clear previous hide timers
			clearTimeout(hideTimeout);

			// reset and apply new message
			$msg
				.stop(true, true)
				.removeClass('text-success text-error text-info text-warning show')
				.html(text)
				.addClass(type);

			// Force browser reflow so transition restarts cleanly
			void $msg[0].offsetWidth;

			// Show with transition
			$msg.addClass('show');

			// Different hide delays by type (better UX)
			const delay = type === 'text-error' ? 5000 : 3000;

			hideTimeout = setTimeout(() => {
				$msg.removeClass('show');
			}, delay);
		};
	})(jQuery);
			
	
	// Save: Store partial built form data
	function wordFormBuiltDataStore( builtFormMeta ) {
		//console.log(builtFormMeta);
		$.ajax({
		  type:"POST",		  
		  url: sc_wordform_metabox_script_obj.adminajax_url,
		  data : {			    
				action 	 : 'sc_wordform_built_form_data_save',
				security : sc_wordform_metabox_script_obj.nonce,				
			    params   : builtFormMeta			    		    
				},		  
		  success: function(data) { 
			 //console.log(data); 
			 let jsonData	= JSON.parse( data );
			  if ( jsonData.status == 'success' ) {
			  }
			  else if ( jsonData.status == 'fail' ) {					  				  
			  }
			  else {				  
			  }
			},
		  error: function( xhr, status, error ) { 
			 console.log(xhr); 
			 console.log(status); 
			 console.log(error); 				 
			}
		});		
	}
				
	// Settings: Validation tab
	$('body').on('submit', '#scWordformSettingsValidationTabForm', function() {		
		let formData			= $(this).serialize();
		let scWordformMsgInfo	= $('.sc-wordform-validation-message-settings-info');
		let $form				= $(this);
		let $buttons			= $form.find('button');
				
		scWordformMsgInfo.removeClass('msg-success msg-error').text('');
		$buttons.attr('disabled', true );
		$.ajax({
		  type:"POST",		  
		  url: sc_wordform_metabox_script_obj.adminajax_url,
		  data : {			    
				action 	 : 'sc_wordform_settings_menu_validation_tab_data_save',
				security : sc_wordform_metabox_script_obj.nonce,				
			    formData :formData			    		    
				},		  
		  success: function(data) { 
			 //console.log(data); 
			 let jsonData	= JSON.parse( data );
			  if ( jsonData.status == 'success' ) {
				  scWordformMsgInfo.html(jsonData.Msg ).addClass('msg-success');
			  }
			  else if ( jsonData.status == 'fail' ) {		
				  scWordformMsgInfo.html(jsonData.Msg ).addClass('msg-error');
			  }
			  
			  $buttons.removeAttr('disabled');
			},
		  error: function( xhr, status, error ) { 
			 console.log(xhr); 
			 console.log(status); 
			 console.log(error); 				 
			 $buttons.removeAttr('disabled'); 
			}
		});			
				
		return false;
	});

	$('body').on('click', '.sc-wordform-validation-reset-btn', function() {
		let $form							= $('#scWordformSettingsValidationTabForm');
		let scWordformMsgInfo				= $('.sc-wordform-validation-message-settings-info');
		let scWordformValidationMsgDisplayTbl	= $('.sc-wordform-validation-messages-display-table tbody');
		let formID							= $('.sc-wordform-validation-tab-selected-form-id').val() || 'all_form';
		let formName						= $('.sc-wordform-validation-tab-selected-form-name').val() || 'All Forms';
		let $buttons						= $form.find('button');

		scWordformMsgInfo.removeClass('msg-success msg-error').text('');
		$buttons.attr('disabled', true);
		scWordformValidationMsgDisplayTbl.css('opacity', 0.30);

		$.ajax({
		  type:"POST",
		  url: sc_wordform_metabox_script_obj.adminajax_url,
		  data : {
				action    : 'sc_wordform_settings_menu_validation_tab_data_reset',
				security  : sc_wordform_metabox_script_obj.nonce,
				form_id   : formID,
				form_name : formName
				},
		  success: function(data) {
			 let jsonData = JSON.parse( data );
			  if ( jsonData.status == 'success' ) {
				  scWordformValidationMsgDisplayTbl.html(jsonData.htmlTemplate).css('opacity', 1);
				  scWordformMsgInfo.html(jsonData.Msg).addClass('msg-success');
			  }
			  else if ( jsonData.status == 'fail' ) {
				  scWordformValidationMsgDisplayTbl.css('opacity', 1);
				  scWordformMsgInfo.html(jsonData.Msg).addClass('msg-error');
			  }

			  $buttons.removeAttr('disabled');
			},
		  error: function( xhr, status, error ) {
			 console.log(xhr);
			 console.log(status);
			 console.log(error);
			 scWordformValidationMsgDisplayTbl.css('opacity', 1);
			 $buttons.removeAttr('disabled');
			}
		});
	});
	
	
	// Settings: Validation Tab - On Select Form
	$('body').on('change', '#scWordformSelectValidationMsgsFor', function() {
		let scSelectWordformName				= $(this).find('option:selected').text();
		let scSelectWordformID					= $(this).val();
		let scWordformValidationMsgDisplayTbl	= $('.sc-wordform-validation-messages-display-table tbody');
		let scWordformMsgInfo					= $('.sc-wordform-validation-message-settings-info');
		scWordformMsgInfo.removeClass('msg-success msg-error').html('');				
		$('.sc-wordform-validation-tab-selected-form-name').val(scSelectWordformName);
		$('.sc-wordform-validation-tab-selected-form-id').val(scSelectWordformID);
		
		let params						= {};
		params.FormName					= scSelectWordformName;
		params.FormID					= scSelectWordformID;
		scWordformValidationMsgDisplayTbl.css('opacity', 0.30 );
		$.ajax({
		  type:"POST",		  
		  url: sc_wordform_metabox_script_obj.adminajax_url,
		  data : {			    
				action 	  : 'sc_wordform_settings_menu_validation_tab_selected_form_data_save',
				security  : sc_wordform_metabox_script_obj.nonce,				
			    params 	  : params
				},		  
		  success: function(data) { 
			 //console.log(data); 
			 let jsonData	= JSON.parse( data );
			  if ( jsonData.status == 'success' ) {
				  scWordformValidationMsgDisplayTbl.html(jsonData.htmlTemplate).css('opacity', 1 );				  
			  }
			  else if ( jsonData.status == 'fail' ) {		
				  scWordformValidationMsgDisplayTbl.css('opacity', 1 );
			  }
			  
			  
			},
		  error: function( xhr, status, error ) { 
			 console.log(xhr); 
			 console.log(status); 
			 console.log(error); 				 
			 scWordformValidationMsgDisplayTbl.css('opacity', 1 );
			}
		});			
		
	});
	
	
	
	// All Forms Page: Delete form - using browser native alert window
	// $('body').on('click', '.sc-wordform-delete-btn', function() {
	// 	let scWordFormID	= $(this).data('sc-wordform-id');
	// 	let scWordFormName	= $(this).data('sc-wordform-name');		
	// 	let scWordFormTR	= $(this).closest('tr');				
	// 	let params			= {};
	// 	params.wordformID	= scWordFormID;
	// 	params.wordformName	= scWordFormName;		
	// 	let confirmMsg		= confirm('Do you want to delete '+ scWordFormName +' [ '+ scWordFormID +' ] permanently?\n\n[ will be deleted all related data associated with this form like users submission data! ]');
	// 	if ( confirmMsg ) {
	// 		scWordFormTR.css('background-color', 'darksalmon');
	// 		$.ajax({
	// 		  type:"POST",		  
	// 		  url: sc_wordform_metabox_script_obj.adminajax_url,
	// 		  data : {			    
	// 				action 	    : 'sc_wordform_all_forms_page_delete_form',
	// 				security    : sc_wordform_metabox_script_obj.nonce,				
	// 				params 		: params
	// 				},		  
	// 		  success: function(data) { 
	// 			 //console.log(data); 
	// 			 let jsonData	= JSON.parse( data );
	// 			  if ( jsonData.status == 'success' ) {
	// 				  scWordFormTR.fadeOut(300);
	// 			  }
	// 			  else if ( jsonData.status == 'fail' ) {		
	// 				  scWordFormTR.css('background-color', '');
	// 				  alert('Something went wrong, failed to delete. Please try again.')
	// 			  }

	// 			},
	// 		  error: function( xhr, status, error ) { 
	// 			 console.log(xhr); 
	// 			 console.log(status); 
	// 			 console.log(error); 				 

	// 			}
	// 		});	
	// 	}
		
	// });
	
    // All Forms Page: Delete form - using WordPress default dialog window
    $('body').on('click', '.sc-wordform-delete-btn', function(e) {
        e.preventDefault();

        let $btn          = $(this); // the clicked trash icon
        let scWordFormID   = $btn.data('sc-wordform-id');
        let scWordFormName = $btn.data('sc-wordform-name');      
        let scWordFormTR   = $btn.closest('tr');                
        let params         = { wordformID: scWordFormID, wordformName: scWordFormName };

        let $dialog = $('<div></div>').appendTo('body');

        $dialog.html(
            '<p>Do you want to delete <strong>' + scWordFormName + '</strong> [ ' + scWordFormID + ' ] permanently?</p>' +
            '<p><em>All related data associated with this form, including users’ submission data, will also be deleted.</em></p>'
        );

        $dialog.dialog({
            modal: true,
            title: 'Confirm Delete',
            // dialogClass: 'wp-dialog',
			dialogClass: 'wordform-admin-dialog',
            draggable: false,
            resizable: false,
            width: 400,
            show: { effect: "fade", duration: 200 },
            hide: { effect: "fade", duration: 200 },
            buttons: [
                {
                    text: 'Delete',
                    class: 'button button-secondary button-delete',
                    click: function() {
                        scWordFormTR.css('background-color', 'darksalmon');
                        $.ajax({
                            type: "POST",
                            url: sc_wordform_metabox_script_obj.adminajax_url,
                            data: { 
                                action: 'sc_wordform_all_forms_page_delete_form',
                                security: sc_wordform_metabox_script_obj.nonce,
                                params: params
                            },
                            success: function(data) { 
                                let jsonData = JSON.parse(data);
                                if (jsonData.status === 'success') {
                                    scWordFormTR.fadeOut(300);
                                } else {
                                    scWordFormTR.css('background-color', '');
                                    alert('Something went wrong, failed to delete. Please try again.');
                                }
                            },
                            error: function(xhr, status, error) { 
                                console.log(xhr, status, error);                 
                            }
                        });
                        $(this).dialog("close");
                    }
                },
                {
                    text: 'Cancel',
                    class: 'button',
                    click: function() {
                        $(this).dialog("close");
                    }
                }
            ],
            close: function() {
                $dialog.dialog("destroy").remove();
                $btn.blur(); // 🔑 remove focus from trash icon
            }
        });

        // Style delete button in red
        $('.button-delete').css({
            'background': '#d63638',
            'border-color': '#b32d2e',
            'color': '#fff'
        }).hover(
            function() { $(this).css('background', '#b32d2e'); },
            function() { $(this).css('background', '#d63638'); }
        );

    });	
	
	
	// Settings: General Tab
	$('#scWordformSettingsGeneralTabForm').on('submit', function() {
		let updateInfoEle = $('.sc-wordform-general-tab-update-info');
		let postData = $(this).serialize();
		let params = { formData: postData };
		updateInfoEle.html('').removeClass('text-success text-error');

		$.ajax({
			type: "POST",
			url: sc_wordform_metabox_script_obj.adminajax_url,
			data: {
				action: 'sc_wordform_settings_general_tab_form',
				security: sc_wordform_metabox_script_obj.nonce,
				params: params
			},
			success: function(data) {
				console.log(data); // data is already a JS object (not a string)

				if (data.status === 'success') {
					updateInfoEle.html(data.successMsg).addClass('text-success');
				} else if (data.status === 'fail') {
					updateInfoEle.html(data.failMsg).addClass('text-error');
				}
			},
			error: function(xhr, status, error) {
				console.log(xhr);
				console.log(status);
				console.log(error);
			}
		});

		return false;
	});

		

	
	// Settings: Google reCaptcha Tab
	$('#scWordformSettingsgCaptchaTabForm').on('submit', function() {
		let updateInfoEle	= $('.sc-wordform-gcaptcha-message-settings-info');
		let postData		= $(this).serialize();
		//console.log(postData);
		let params			= {};
		params.formData		= postData;
		updateInfoEle.html('').removeClass('text-success text-error');
		$.ajax({
		  type:"POST",		  
		  url: sc_wordform_metabox_script_obj.adminajax_url,
		  data : {			    
				action 	    : 'sc_wordform_settings_google_recaptcha_tab_form',
				security    : sc_wordform_metabox_script_obj.nonce,				
				params 		: params
				},		  
		  success: function(data) { 
			 //console.log(data); 
			 let jsonData	= JSON.parse( data );
			  if ( jsonData.status == 'success' ) {		
				  updateInfoEle.html(jsonData.successMsg).addClass('text-success');
			  }
			  else if ( jsonData.status == 'fail' ) {			
				  updateInfoEle.html(jsonData.failMsg).addClass('text-error');
			  }

			},
		  error: function( xhr, status, error ) { 
			 console.log(xhr); 
			 console.log(status); 
			 console.log(error); 				 

			}
		});			
	
	return false;
   });

	// Settings: hCaptcha Tab
	$('#scWordformSettingshCaptchaTabForm').on('submit', function() {
		let updateInfoEle = $('.sc-wordform-hcaptcha-message-settings-info');
		let postData = $(this).serialize();
		let params = {};
		params.formData = postData;
		updateInfoEle.html('').removeClass('text-success text-error');
		$.ajax({
		  type:"POST",
		  url: sc_wordform_metabox_script_obj.adminajax_url,
		  data : {
				action      : 'sc_wordform_settings_hcaptcha_tab_form',
				security    : sc_wordform_metabox_script_obj.nonce,
				params      : params
				},
		  success: function(data) {
			 let jsonData = JSON.parse( data );
			  if ( jsonData.status == 'success' ) {
				  updateInfoEle.html(jsonData.successMsg).addClass('text-success');
			  }
			  else if ( jsonData.status == 'fail' ) {
				  updateInfoEle.html(jsonData.failMsg).addClass('text-error');
			  }

			},
		  error: function( xhr, status, error ) {
			 console.log(xhr);
			 console.log(status);
			 console.log(error);

			}
		});

	return false;
   });


	// Toggle: Draggable Input Elements Buttons Collapse - Expand
	
	// document.addEventListener("DOMContentLoaded", function () {
	// 	const headers = document.querySelectorAll(
	// 		".wordform-draggable-elements-div-wrapper h4"
	// 	);

	// 	headers.forEach((header) => {
	// 		header.addEventListener("click", function () {
	// 			const nextDiv = header.nextElementSibling;
	// 			header.classList.toggle("active");
	// 			nextDiv.classList.toggle("open");
	// 		});
	// 	});
	// });

	document.addEventListener("DOMContentLoaded", function () {
		const headers = document.querySelectorAll(
			".wordform-draggable-elements-div-wrapper h4"
		);

		headers.forEach((header) => {
			const contentDiv = header.nextElementSibling;

			// Expand by default
			header.classList.add("active");
			contentDiv.style.height = contentDiv.scrollHeight + "px";
			contentDiv.classList.add("open");

			header.addEventListener("click", function () {
				header.classList.toggle("active");

				if (contentDiv.classList.contains("open")) {
					// Collapse
					contentDiv.style.height = contentDiv.scrollHeight + "px"; // set current height
					requestAnimationFrame(() => {
						contentDiv.style.height = "0px";
					});
				} else {
					// Expand
					contentDiv.style.height = contentDiv.scrollHeight + "px";
				}

				contentDiv.classList.toggle("open");
			});

			// Optional: reset height to auto after transition for dynamic content
			contentDiv.addEventListener("transitionend", function () {
				if (contentDiv.classList.contains("open")) {
					contentDiv.style.height = "auto";
				}
			});
		});
	});

	
	// Selected tooltips
	const getWordformTooltipContainer = () => {
		const fsElement = document.fullscreenElement
			|| document.webkitFullscreenElement
			|| document.mozFullScreenElement
			|| document.msFullscreenElement;

		if (fsElement) {
			if (fsElement.classList?.contains('wordform-fullscreen-wrapper')) {
				return fsElement;
			}

			const wrapperAncestor = fsElement.closest?.('.wordform-fullscreen-wrapper');
			if (wrapperAncestor) {
				return wrapperAncestor;
			}
		}

		return document.body;
	};

	$("body").tooltip({
		selector: ".wordform-add-select-option, .wordform-add-radio-option, .wordform-add-checkbox-option",
		tooltipClass: "wordform-add-options-tooltip-wrapper",
		appendTo: getWordformTooltipContainer(),
		open: function (event, ui) {
			const container = getWordformTooltipContainer();
			if (container && ui.tooltip[0].parentNode !== container) {
				ui.tooltip.appendTo(container);
			}
			ui.tooltip.css('z-index', 2147483647);
		}
	});
	

}(jQuery));




