jQuery( document ).ready(
	function ($) {
		// A flag to track if the initial delay period is over
		let canShowPopup = (wawpPopupSettings.popupInitialDelay === 0);

		// If a delay is set, use a timer to update the flag
		if ( ! canShowPopup) {
			setTimeout(
				function () {
					canShowPopup = true;
					// After the delay, trigger the initial popup check
					showPopup( false );
				},
				wawpPopupSettings.popupInitialDelay * 1000
			);
		}

		var popup               = $( '#pnp-popup' );
		var closeButtons        = $( '.pnp-close, #pnp-close-success' );
		var savePhoneButton     = $( '#pnp-save-phone' );
		var phoneNumberInput    = $( '#billing_phone_popup' );
		var errorMessageDisplay = $( '#pnp-error-message' );
		var successState        = $( '.pnp-success-state' );
		var popupBody           = $( '.pnp-popup-body' );

		// Verification variables and states
		var transientKey        = '';
		var verificationMethod  = wawpPopupSettings.verificationMethod || 'none';
		var otpState            = $( '.pnp-otp-state' );
		var listPendingState    = $( '.pnp-list-pending-state' );
		var backToInputButtons  = $( '.pnp-back-to-input' );
		var verifyOtpButton     = $( '#pnp-verify-otp' );
		var otpCodeInput        = $( '#pnp-otp-code' );
		var otpErrorDisplay     = $( '#pnp-otp-error-message' );
		var listErrorDisplay    = $( '#pnp-list-error-message' );
		var resendOtpButton     = $( '#pnp-resend-otp' );
		var resendListButton    = $( '#pnp-resend-list' );
		var otpCooldownSpan     = $( '#pnp-otp-cooldown' );
		var listCooldownSpan    = $( '#pnp-list-cooldown' );
		var firebaseLoading     = false;
		var confirmationResult  = null;
		var pollingInterval     = null;
		var cooldownTimer       = null;
		var currentPhone        = '';

		// Helper functions for cookies
		function getCookie(name) {
			var match = document.cookie.match( new RegExp( '(^| )' + name + '=([^;]+)' ) );
			return match ? match[2] : null;
		}

		function setCookie(name, value, seconds) {
			var expires = "";
			if (seconds) {
				var date = new Date();
				date.setTime( date.getTime() + (seconds * 1000) );
				expires = "; expires=" + date.toUTCString();
			}
			document.cookie = name + "=" + value + expires + "; path=/";
		}

		// FIX: Check both cookie names for consistency with PHP logic
		var visitorPhone     = getCookie( 'visitor_phone' ) || getCookie( 'New_phone' );
		var popupClosedUntil = getCookie( 'popup_closed_until' );
		var showCount        = parseInt( getCookie( 'pnp_popup_show_count' ) || '0' );
		var currentTime      = Date.now();

		sessionStorage.removeItem( 'phone_entered' );

		function shouldShowPopup() {
			if (visitorPhone) {
				return false;
			}
			if ( ! wawpPopupSettings.enablePopup) {
				return false;
			}
			if (popupClosedUntil && Number( popupClosedUntil ) > currentTime) {
				return false;
			}

			// Frequency Logic
			var freq = wawpPopupSettings.popupFrequency || 'once';
			if (freq === 'once' && showCount > 0) {
				return false;
			}
			if (freq === 'limit' && showCount >= (wawpPopupSettings.popupFrequencyLimit || 1)) {
				return false;
			}

			var isUserLoggedIn = $( 'body' ).hasClass( 'logged-in' );
			if (wawpPopupSettings.popupDisplay === 'logged_in' && ! isUserLoggedIn) {
				return false;
			}
			if (wawpPopupSettings.popupDisplay === 'guest' && isUserLoggedIn) {
				return false;
			}
			if (wawpPopupSettings.popupDisplay === 'disabled') {
				return false;
			}

			if (wawpPopupSettings.popupWhere === 'exclude') {
				var currentPageId = $( 'body' ).attr( 'class' ).match( /page-id-(\d+)/ );
				if (currentPageId && wawpPopupSettings.popupExcludePages.includes( parseInt( currentPageId[1] ) )) {
					return false;
				}
			}
			return true;
		}

		function incrementShowCount() {
			showCount++;
			setCookie( 'pnp_popup_show_count', showCount, 30 * 24 * 60 * 60 ); // 30 days
		}

		function applyPopupStyles() {
			// Apply CSS Variables for dynamic styling.
			popup.css('--wawp-ac-btn-bg', wawpPopupSettings.btnColor);
			popup.css('--wawp-ac-btn-text', wawpPopupSettings.btnTextColor);
			popup.css('--wawp-ac-btn-bg-hover', wawpPopupSettings.btnHoverColor);
			popup.css('--wawp-ac-card-bg', wawpPopupSettings.cardColor);
			popup.css('--wawp-ac-card-bg-hover', wawpPopupSettings.cardHoverColor);
			popup.css('--wawp-ac-title-color', wawpPopupSettings.titleColor);
			popup.css('--wawp-ac-title-hover', wawpPopupSettings.titleHoverColor);
			popup.css('--wawp-ac-desc-color', wawpPopupSettings.descColor);
			popup.css('--wawp-ac-desc-hover', wawpPopupSettings.descHoverColor);

			// Handle inline image alignment.
			if (wawpPopupSettings.imageType === 'inline' && wawpPopupSettings.imageUrl) {
				var alignmentMap = {
					'left': 'flex-start',
					'center': 'center',
					'right': 'flex-end'
				};
				var alignValue = alignmentMap[wawpPopupSettings.imageAlignment] || 'center';
				popup.find('.pnp-popup-inline-image').css('justify-content', alignValue);
			}

			// Inject custom CSS if provided.
			if (wawpPopupSettings.customCss) {
				var existingStyle = $( '#wawp-popup-custom-css' );
				if ( existingStyle.length === 0 ) {
					$( '<style id="wawp-popup-custom-css">' + wawpPopupSettings.customCss + '</style>' ).appendTo( 'head' );
				} else {
					existingStyle.text( wawpPopupSettings.customCss );
				}
			}
		}

		function showPopup(force) {
			force = force || false;

			// Check if the delay period is over before showing
			if ( ! canShowPopup) {
				return;
			}

			// Device Targeting
			if (wawpPopupSettings.popupDevices) {
				var isMobile = window.matchMedia("only screen and (max-width: 768px)").matches;
				if (wawpPopupSettings.popupDevices === 'desktop' && isMobile) {
					return;
				}
				if (wawpPopupSettings.popupDevices === 'mobile' && !isMobile) {
					return;
				}
			}

			// Cart Value Condition
			if (wawpPopupSettings.minCartValue > 0) {
				if (wawpPopupSettings.cartTotal < wawpPopupSettings.minCartValue) {
					return;
				}
			}

			if (force) {
				if (visitorPhone || (popupClosedUntil && Number( popupClosedUntil ) > currentTime)) {
					return;
				}

				// For forced triggers (cart/exit), we still respect "once" and "limit"
				var freq = wawpPopupSettings.popupFrequency || 'once';
				if (freq === 'once' && showCount > 0) {
					return;
				}
				if (freq === 'limit' && showCount >= (wawpPopupSettings.popupFrequencyLimit || 1)) {
					return;
				}

				applyPopupStyles();
				popup.addClass( 'show' ).css( 'display', 'flex' );
				incrementShowCount();
			} else {
				if (shouldShowPopup()) {
					applyPopupStyles();
					popup.addClass( 'show' ).css( 'display', 'flex' );
					incrementShowCount();
				}
			}
		}

		// On window load, show popup if no delay is configured
		$( window ).on(
			'load',
			function () {
				if (canShowPopup) {
					showPopup( false );
				}
			}
		);

		function cleanUpVerification() {
			if ( pollingInterval ) {
				clearInterval( pollingInterval );
				pollingInterval = null;
			}
			if ( cooldownTimer ) {
				clearInterval( cooldownTimer );
				cooldownTimer = null;
			}
		}

		closeButtons.on(
			'click',
			function (e) {
				e.preventDefault();
				cleanUpVerification();
				popup.removeClass( 'show' ).hide();
				setCookie( 'popup_closed_until', currentTime + (wawpPopupSettings.closeHideDuration * 1000), wawpPopupSettings.closeHideDuration );
			}
		);

		$( document ).on(
			'click',
			function (e) {
				if (popup.hasClass( 'show' ) && ! $( e.target ).closest( '.pnp-popup-content' ).length) {
					cleanUpVerification();
					popup.removeClass( 'show' ).hide();
					setCookie( 'popup_closed_until', currentTime + (wawpPopupSettings.closeHideDuration * 1000), wawpPopupSettings.closeHideDuration );
				}
			}
		);

		if (wawpPopupSettings.triggerExit) {
			// Primary: mouse leaves browser viewport from the top
			$( document ).on(
				'mouseleave',
				function (e) {
					if (e.clientY < 0) {
						showPopup( true );
					}
				}
			);
			// Fallback: capture tab close / navigation away intent
			window.addEventListener(
				'beforeunload',
				function () {
					if ( ! visitorPhone) {
						showPopup( true );
					}
				}
			);
		}

		if (wawpPopupSettings.triggerCart) {
			$( document.body ).on(
				'added_to_cart',
				function () {
					showPopup( true );
				}
			);
		}

		function sanitizePhone(raw) {
			return (raw || '').replace( /[^\d]/g, '' );
		}

		function isValidPhone(digitsOnly) {
			return digitsOnly.length >= 7 && digitsOnly.length <= 15;
		}

		// Back buttons behavior
		backToInputButtons.on( 'click', function( e ) {
			e.preventDefault();
			cleanUpVerification();
			
			// Switch back to input state
			otpState.addClass( 'wawp-hide' );
			listPendingState.addClass( 'wawp-hide' );
			popupBody.removeClass( 'wawp-hide' );
			errorMessageDisplay.hide();
		});

		// Dynamic Firebase loading and initialization
		function ensureFirebase() {
			if ( typeof firebase !== 'undefined' && firebase.auth ) {
				if ( ! window.recaptchaVerifierPopup ) {
					return initFirebaseVerifier();
				}
				return Promise.resolve( true );
			}

			if ( firebaseLoading ) {
				return new Promise( function( resolve ) {
					var i = setInterval( function() {
						if ( typeof firebase !== 'undefined' && firebase.auth ) {
							clearInterval( i );
							resolve( true );
						}
					}, 100 );
				});
			}
			firebaseLoading = true;

			var scripts = [
				'https://www.gstatic.com/firebasejs/9.1.1/firebase-app-compat.js',
				'https://www.gstatic.com/firebasejs/9.1.1/firebase-auth-compat.js'
			];

			return new Promise( function( resolve, reject ) {
				var loadScript = function( index ) {
					if ( index >= scripts.length ) {
						initFirebaseVerifier().then( function() {
							resolve( true );
						} ).catch( reject );
						return;
					}
					var s = document.createElement( 'script' );
					s.src = scripts[ index ];
					s.onload = function() {
						loadScript( index + 1 );
					};
					s.onerror = function() {
						reject( new Error( 'Failed to load Firebase script: ' + scripts[ index ] ) );
					};
					document.head.appendChild( s );
				};
				loadScript( 0 );
			} );
		}

		function initFirebaseVerifier() {
			var config = wawpPopupSettings.firebaseConfig;
			if ( ! config ) {
				console.error( 'Firebase config missing' );
				return Promise.reject( new Error( 'Firebase config missing' ) );
			}

			if ( ! config.apiKey && config.api_key ) {
				config.apiKey = config.api_key;
			}
			if ( ! config.apiKey ) {
				console.error( 'Firebase API Key missing' );
				return Promise.reject( new Error( 'Firebase API Key missing' ) );
			}

			var app = null;
			try {
				app = firebase.app( 'wawp_popup_app' );
			} catch ( e ) {
				app = firebase.initializeApp( config, 'wawp_popup_app' );
			}

			if ( ! window.recaptchaVerifierPopup ) {
				try {
					window.recaptchaVerifierPopup = new firebase.auth.RecaptchaVerifier( 'wawp-firebase-recaptcha-popup', {
						'size': 'invisible',
						'callback': function( response ) { }
					}, app );
					return window.recaptchaVerifierPopup.render().then( function() {
						return true;
					} );
				} catch ( e ) {
					console.warn( 'Recaptcha init error', e );
					return Promise.reject( e );
				}
			}
			return Promise.resolve( true );
		}

		// Cooldown Countdown Timer
		function startCooldown( type ) {
			var btn = ( type === 'list' ) ? resendListButton : resendOtpButton;
			var span = ( type === 'list' ) ? listCooldownSpan : otpCooldownSpan;
			var duration = 30;

			if ( cooldownTimer ) {
				clearInterval( cooldownTimer );
			}

			btn.prop( 'disabled', true );
			span.text( duration );

			cooldownTimer = setInterval( function() {
				duration--;
				span.text( duration );
				if ( duration <= 0 ) {
					clearInterval( cooldownTimer );
					cooldownTimer = null;
					btn.prop( 'disabled', false );
				}
			}, 1000 );
		}

		// Resend Handlers
		resendOtpButton.on( 'click', function( e ) {
			e.preventDefault();
			sendChallenge( currentPhone, true );
		});

		resendListButton.on( 'click', function( e ) {
			e.preventDefault();
			sendChallenge( currentPhone, true );
		});

		// Send Verification Challenge
		function sendChallenge( phoneNumber, isResend ) {
			isResend = isResend || false;
			errorMessageDisplay.hide();
			otpErrorDisplay.addClass( 'wawp-hide' );
			listErrorDisplay.addClass( 'wawp-hide' );

			if ( verificationMethod === 'firebase' ) {
				ensureFirebase().then( function() {
					var phoneWithPlus = phoneNumber;
					if ( ! phoneWithPlus.startsWith( '+' ) ) {
						phoneWithPlus = '+' + phoneWithPlus;
					}

					var app = firebase.app( 'wawp_popup_app' );
					app.auth().signInWithPhoneNumber( phoneWithPlus, window.recaptchaVerifierPopup )
						.then( function( result ) {
							confirmationResult = result;
							
							popupBody.addClass( 'wawp-hide' );
							listPendingState.addClass( 'wawp-hide' );
							otpState.removeClass( 'wawp-hide' );

							startCooldown( 'otp' );

							savePhoneButton.prop( 'disabled', false );
							savePhoneButton.find( '.loading-spinner' ).addClass( 'wawp-hide' );
							savePhoneButton.find( '.button-text' ).removeClass( 'wawp-hide' );
						} )
						.catch( function( error ) {
							console.error( 'Firebase error', error );
							if ( isResend ) {
								otpErrorDisplay.text( error.message ).removeClass( 'wawp-hide' );
							} else {
								savePhoneButton.prop( 'disabled', false );
								savePhoneButton.find( '.loading-spinner' ).addClass( 'wawp-hide' );
								savePhoneButton.find( '.button-text' ).removeClass( 'wawp-hide' );
								errorMessageDisplay.text( error.message ).css( 'color', 'red' ).show();
							}
						} );
				} ).catch( function( err ) {
					savePhoneButton.prop( 'disabled', false );
					savePhoneButton.find( '.loading-spinner' ).addClass( 'wawp-hide' );
					savePhoneButton.find( '.button-text' ).removeClass( 'wawp-hide' );
					errorMessageDisplay.text( 'Failed to initialize verification system.' ).css( 'color', 'red' ).show();
				} );
			} else {
				$.ajax({
					url: pnpPopupData.rest_url + '/send-otp',
					type: 'POST',
					data: {
						phone: phoneNumber
					},
					success: function( response ) {
						if ( response.success ) {
							transientKey = response.transient_key;
							var authType = response.auth_type || 'otp';

							if ( authType === 'list' ) {
								popupBody.addClass( 'wawp-hide' );
								otpState.addClass( 'wawp-hide' );
								listPendingState.removeClass( 'wawp-hide' );

								startCooldown( 'list' );
								startPolling( transientKey );
							} else {
								popupBody.addClass( 'wawp-hide' );
								listPendingState.addClass( 'wawp-hide' );
								otpState.removeClass( 'wawp-hide' );

								startCooldown( 'otp' );
							}

							savePhoneButton.prop( 'disabled', false );
							savePhoneButton.find( '.loading-spinner' ).addClass( 'wawp-hide' );
							savePhoneButton.find( '.button-text' ).removeClass( 'wawp-hide' );
						} else {
							var errMsg = response.message || response.data || 'Failed to send verification.';
							if ( isResend ) {
								if ( authType === 'list' ) {
									listErrorDisplay.text( errMsg ).removeClass( 'wawp-hide' );
								} else {
									otpErrorDisplay.text( errMsg ).removeClass( 'wawp-hide' );
								}
							} else {
								savePhoneButton.prop( 'disabled', false );
								savePhoneButton.find( '.loading-spinner' ).addClass( 'wawp-hide' );
								savePhoneButton.find( '.button-text' ).removeClass( 'wawp-hide' );
								errorMessageDisplay.text( errMsg ).css( 'color', 'red' ).show();
							}
						}
					},
					error: function( xhr, status, error ) {
						var errText = 'Failed to communicate with verification server.';
						if ( isResend ) {
							otpErrorDisplay.text( errText ).removeClass( 'wawp-hide' );
						} else {
							savePhoneButton.prop( 'disabled', false );
							savePhoneButton.find( '.loading-spinner' ).addClass( 'wawp-hide' );
							savePhoneButton.find( '.button-text' ).removeClass( 'wawp-hide' );
							errorMessageDisplay.text( errText ).css( 'color', 'red' ).show();
						}
					}
				});
			}
		}

		// Polling for WhatsApp list approval
		function startPolling( transientKey ) {
			if ( pollingInterval ) {
				clearInterval( pollingInterval );
			}

			pollingInterval = setInterval( function() {
				$.ajax({
					url: pnpPopupData.rest_url + '/verify-otp',
					type: 'POST',
					data: {
						transient_key: transientKey
					},
					success: function( response ) {
						if ( response.success ) {
							clearInterval( pollingInterval );
							pollingInterval = null;

							setCookie( 'visitor_phone', currentPhone, 30 * 24 * 60 * 60 );
							visitorPhone = currentPhone;

							if ( wawpPopupSettings.autofillFrontend ) {
								autofillFields( currentPhone );
							}

							showSuccessState();
						} else if ( response.status === 'rejected' ) {
							clearInterval( pollingInterval );
							pollingInterval = null;
							listErrorDisplay.text( 'Request was rejected on WhatsApp.' ).removeClass( 'wawp-hide' );
						}
					},
					error: function() {
						// Silent fail during polling is fine
					}
				});
			}, 3000 );
		}

		// Verify OTP challenge code
		function verifyChallengeCode() {
			var code = otpCodeInput.val();
			if ( ! code || code.length < 6 ) {
				otpErrorDisplay.text( 'Please enter a 6-digit code.' ).removeClass( 'wawp-hide' );
				return;
			}

			otpErrorDisplay.addClass( 'wawp-hide' );
			verifyOtpButton.prop( 'disabled', true );
			verifyOtpButton.find( '.loading-spinner' ).removeClass( 'wawp-hide' );
			verifyOtpButton.find( '.button-text' ).addClass( 'wawp-hide' );

			if ( verificationMethod === 'firebase' && confirmationResult ) {
				confirmationResult.confirm( code )
					.then( function( result ) {
						result.user.getIdToken().then( function( idToken ) {
							verifyWithServer({
								idToken: idToken,
								billing_phone: currentPhone
							});
						} );
					} )
					.catch( function( error ) {
						verifyOtpButton.prop( 'disabled', false );
						verifyOtpButton.find( '.loading-spinner' ).addClass( 'wawp-hide' );
						verifyOtpButton.find( '.button-text' ).removeClass( 'wawp-hide' );

						if ( error.code === 'auth/invalid-verification-code' ) {
							otpErrorDisplay.text( 'OTP code is incorrect. Please try again.' ).removeClass( 'wawp-hide' );
						} else {
							otpErrorDisplay.text( error.message ).removeClass( 'wawp-hide' );
						}
					} );
			} else {
				verifyWithServer({
					transient_key: transientKey,
					code: code,
					billing_phone: currentPhone
				});
			}
		}

		verifyOtpButton.on( 'click', function( e ) {
			e.preventDefault();
			verifyChallengeCode();
		} );

		otpCodeInput.on( 'keypress', function( e ) {
			if ( e.which === 13 ) {
				e.preventDefault();
				verifyChallengeCode();
			}
		} );

		function verifyWithServer( data ) {
			$.ajax({
				url: pnpPopupData.rest_url + '/verify-otp',
				type: 'POST',
				data: data,
				success: function( response ) {
					if ( response.success ) {
						setCookie( 'visitor_phone', currentPhone, 30 * 24 * 60 * 60 );
						visitorPhone = currentPhone;

						if ( wawpPopupSettings.autofillFrontend ) {
							autofillFields( currentPhone );
						}

						showSuccessState();
					} else {
						verifyOtpButton.prop( 'disabled', false );
						verifyOtpButton.find( '.loading-spinner' ).addClass( 'wawp-hide' );
						verifyOtpButton.find( '.button-text' ).removeClass( 'wawp-hide' );
						otpErrorDisplay.text( response.message || response.data || 'Verification failed.' ).removeClass( 'wawp-hide' );
					}
				},
				error: function( xhr, status, error ) {
					verifyOtpButton.prop( 'disabled', false );
					verifyOtpButton.find( '.loading-spinner' ).addClass( 'wawp-hide' );
					verifyOtpButton.find( '.button-text' ).removeClass( 'wawp-hide' );
					otpErrorDisplay.text( 'Communication error. Please try again.' ).removeClass( 'wawp-hide' );
				}
			});
		}

		// Switch to success state screen
		function showSuccessState() {
			cleanUpVerification();

			popupBody.addClass( 'wawp-hide' );
			otpState.addClass( 'wawp-hide' );
			listPendingState.addClass( 'wawp-hide' );
			successState.removeClass( 'wawp-hide' );

			successState.find( '#pnp-close-success' ).on( 'click', function( e ) {
				e.preventDefault();
				popup.removeClass( 'show' ).hide();
			} );
		}

		// Autofill helper
		function autofillFields( phoneNumber ) {
			var allFieldSelectors = [
				'#billing_phone', '#billing-phone',
				'#wawp_whatsapp', '#wawp_phone', '#wawp_user_phone'
			];
			if (window.wawpIntlTelSettings && Array.isArray( wawpIntlTelSettings.phoneFields )) {
				wawpIntlTelSettings.phoneFields.forEach(
					function (f) {
						if (f && f.enabled === '1' && f.id) {
							allFieldSelectors.push( f.id );
						}
					}
				);
			}
			allFieldSelectors = allFieldSelectors.filter(
				function (v, i, a) {
					return a.indexOf( v ) === i;
				}
			);

			allFieldSelectors.forEach(
				function (selector) {
					var el = document.querySelector( selector );
					if ( ! el || el.value) {
						return;
					}
					var itiInst = (window.intlTelInputGlobals && window.intlTelInputGlobals.getInstance)
					? window.intlTelInputGlobals.getInstance( el ) : null;
					if (itiInst && typeof itiInst.setNumber === 'function') {
						try {
							itiInst.setNumber( '+' + phoneNumber );
							var stripped   = (el.value || '').replace( /^\+/, '' );
							var nativeProp = Object.getOwnPropertyDescriptor( HTMLInputElement.prototype, 'value' );
							if (nativeProp && nativeProp.set) {
								nativeProp.set.call( el, stripped );
							} else {
								el.value = stripped;
							}
						} catch (_) {
							var nativePropFb = Object.getOwnPropertyDescriptor( HTMLInputElement.prototype, 'value' );
							if (nativePropFb && nativePropFb.set) {
								nativePropFb.set.call( el, phoneNumber );
							} else {
								el.value = phoneNumber;
							}
						}
					} else {
						var nativeInputProp = Object.getOwnPropertyDescriptor( HTMLInputElement.prototype, 'value' );
						if (nativeInputProp && nativeInputProp.set) {
							nativeInputProp.set.call( el, phoneNumber );
						} else {
							el.value = phoneNumber;
						}
					}
					el.dispatchEvent( new Event( 'input', { bubbles: true } ) );
					el.dispatchEvent( new Event( 'change', { bubbles: true } ) );
				}
			);

			if (window.wawpIntlTelSettings) {
				wawpIntlTelSettings.savedPhone = phoneNumber;
			}
		}

		// Save phone button click handler
		savePhoneButton.on(
			'click',
			function (e) {
				e.stopPropagation();
				errorMessageDisplay.hide();

				var inputElement = phoneNumberInput[0];
				var rawInput     = phoneNumberInput.val();
				var phoneDigits  = sanitizePhone( rawInput );

				var itiInst = (window.intlTelInputGlobals && window.intlTelInputGlobals.getInstance)
				? window.intlTelInputGlobals.getInstance( inputElement ) : null;

				var isValid = false;
				if (itiInst && typeof itiInst.isValidNumber === 'function') {
					isValid = itiInst.isValidNumber();
				} else {
					isValid = isValidPhone( phoneDigits );
				}

				if (isValid) {
					var phoneNumber = (itiInst && typeof itiInst.getNumber === 'function') ? sanitizePhone( itiInst.getNumber() ) : phoneDigits;
					currentPhone = phoneNumber;

					// Disable button and show loading state
					savePhoneButton.prop( 'disabled', true );
					savePhoneButton.find( '.loading-spinner' ).removeClass( 'wawp-hide' );
					savePhoneButton.find( '.button-text' ).addClass( 'wawp-hide' );

					if ( verificationMethod === 'none' ) {
						$.ajax({
							url: pnpPopupData.rest_url + '/capture-fields',
							type: 'POST',
							data: {
								billing_phone: phoneNumber
							},
							success: function (response) {
								if (response.success) {
									if (response.data.status === 'exists') {
										savePhoneButton.prop( 'disabled', false );
										savePhoneButton.find( '.loading-spinner' ).addClass( 'wawp-hide' );
										savePhoneButton.find( '.button-text' ).removeClass( 'wawp-hide' );
										errorMessageDisplay.text( response.data.message ).css( 'color', 'orange' ).show();
									} else {
										setCookie( 'visitor_phone', phoneNumber, 30 * 24 * 60 * 60 );
										visitorPhone = phoneNumber;

										if (wawpPopupSettings.autofillFrontend) {
											autofillFields( phoneNumber );
										}

										showSuccessState();
									}
								} else {
									savePhoneButton.prop( 'disabled', false );
									savePhoneButton.find( '.loading-spinner' ).addClass( 'wawp-hide' );
									savePhoneButton.find( '.button-text' ).removeClass( 'wawp-hide' );
									errorMessageDisplay.text( response.data.message ).css( 'color', 'red' ).show();
								}
							},
							error: function (xhr, status, error) {
								savePhoneButton.prop( 'disabled', false );
								savePhoneButton.find( '.loading-spinner' ).addClass( 'wawp-hide' );
								savePhoneButton.find( '.button-text' ).removeClass( 'wawp-hide' );
								errorMessageDisplay.text( 'Error saving phone number. Please try again.' ).css( 'color', 'red' ).show();
							}
						});
					} else {
						sendChallenge( phoneNumber );
					}
				} else {
					var errorMsg = (typeof pnpPopupData !== 'undefined' && pnpPopupData.invalidPhoneMsg) ? pnpPopupData.invalidPhoneMsg : 'Please enter a valid phone number.';
					errorMessageDisplay.text( errorMsg ).css( 'color', 'red' ).show();
				}
			}
		);

		if (visitorPhone) {
			phoneNumberInput.val( visitorPhone );
		}

		// Prefill billing phone fields on checkout/forms if a phone was previously saved.
		// Handles both classic WooCommerce (#billing_phone) and Gutenberg blocks (#billing-phone).
		// Always work with digits-only (strip any leading + that may appear from session/cookie data).
		// Only runs if admin has enabled 'Auto Fill Number on Frontend'.
		if (wawpPopupSettings.autofillFrontend) {
			var savedPhoneToFill = (window.wawpIntlTelSettings && wawpIntlTelSettings.savedPhone)
			? wawpIntlTelSettings.savedPhone
			: (pnpPopupData.billing_phone || visitorPhone || '');
			// Strip leading + just in case the server-side stored it with a + prefix
			savedPhoneToFill = (savedPhoneToFill || '').replace( /^\+/, '' ).replace( /[^\d]/g, '' );

			if (savedPhoneToFill) {
				function prefillPhoneFields() {
					var allSelectors = [
					'#billing_phone', '#billing-phone',
					'#wawp_whatsapp', '#wawp_phone', '#wawp_user_phone'
					];
					// Include all configured Target Phone Fields
					if (window.wawpIntlTelSettings && Array.isArray( wawpIntlTelSettings.phoneFields )) {
						wawpIntlTelSettings.phoneFields.forEach(
							function (f) {
								if (f && f.enabled === '1' && f.id) {
									allSelectors.push( f.id );
								}
							}
						);
					}
					allSelectors = allSelectors.filter(
						function (v, i, a) {
							return a.indexOf( v ) === i; }
					);

					allSelectors.forEach(
						function (selector) {
							var el = document.querySelector( selector );
							if ( ! el) {
								return;
							}
							var currentVal = (el.value || '').replace( /[^\d]/g, '' );
							if (currentVal) {
								return; // Skip if field already has digits
							}

							// If this field has an ITI instance, use setNumber for correct flag + strip leading +
							var itiInst = (window.intlTelInputGlobals && window.intlTelInputGlobals.getInstance)
							? window.intlTelInputGlobals.getInstance( el ) : null;
							if (itiInst && typeof itiInst.setNumber === 'function') {
								try {
									itiInst.setNumber( '+' + savedPhoneToFill );
									// Strip leading + from whatever ITI put in the input
									var stripped      = (el.value || '').replace( /^\+/, '' );
									var nativePropIti = Object.getOwnPropertyDescriptor( HTMLInputElement.prototype, 'value' );
									if (nativePropIti && nativePropIti.set) {
										nativePropIti.set.call( el, stripped ); } else {
																el.value = stripped; }
										el.dispatchEvent( new Event( 'input', { bubbles: true } ) );
										el.dispatchEvent( new Event( 'change', { bubbles: true } ) );
										return;
								} catch (_) {
									/* fall through to plain fill */ }
							}

							var nativeProp = Object.getOwnPropertyDescriptor( HTMLInputElement.prototype, 'value' );
							if (nativeProp && nativeProp.set) {
								nativeProp.set.call( el, savedPhoneToFill );
							} else {
								el.value = savedPhoneToFill;
							}
							el.dispatchEvent( new Event( 'input', { bubbles: true } ) );
							el.dispatchEvent( new Event( 'change', { bubbles: true } ) );
						}
					);
				}

				// Try immediately and retry for Gutenberg async-rendered fields
				prefillPhoneFields();
				setTimeout( prefillPhoneFields, 500 );
				setTimeout( prefillPhoneFields, 1200 );
				setTimeout( prefillPhoneFields, 2500 );
			}
		}
	}
);
