(function ($) {
    "use strict";
    var WidgetFormHandler = function ($scope, $) {
        var container = $scope[0].querySelector('.tpaep-form-container');
        var form = container.querySelector('.tpaep-form');

        var formdata = container.dataset.formdata ? JSON.parse(container.dataset.formdata) : {};
        var requiredMask = formdata.Required_mask;
        var integrationData = container?.dataset?.integration ? JSON.parse(container.dataset.integration) : {};

        const requiredAsterisks = container.querySelectorAll('.tpaep-required-asterisk');
        requiredAsterisks.forEach(asterisk => {
            asterisk.style.display = requiredMask === 'hide-asterisks' ? 'none' : 'inline';
        });

        var messages = {
            invalidForm: formdata.invalid_form || "Invalid form submission.",
            successMessage: formdata.success_message || "Your message has been sent successfully.",
            formError: formdata.form_error || "There was an error with the form submission.",
            requiredFieldsError: formdata.required_fields || "Please fill in the required fields.",
            emailFormatError : formdata.email_format_error || "Please enter a valid email address.",
            serverError: formdata.server_error || "Server error, please try again later."
        };

        var isSubmitting = false;

        var emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
    
        var turnstileWidget = container.querySelector('.cf-turnstile');
        var widgetId = null;
        var turnstileInitialized = false;
        
        var isTurnstileLoaded = function() {
            return typeof turnstile !== 'undefined' && typeof turnstile.render === 'function';
        };
    
        var currentFormData = {};
        var currentFormFields = [];
        
        var initializeTurnstile = function() {
            if (turnstileWidget && isTurnstileLoaded() && !turnstileInitialized) {
                try {
                    widgetId = turnstile.render(turnstileWidget, {
                        sitekey: formdata.cf_site_key || '',
                        size: turnstileWidget.getAttribute('data-size') || 'invisible',
                        callback: function (token) {
                            currentTurnstileToken = token;
                        },
                        'error-callback': function () {
                            displayMessage(messages.formError.replace('%error%', 'Turnstile error occurred.'), 'error');
                            currentTurnstileToken = null;
                        }
                    });
                    turnstileInitialized = true;
                } catch (error) {
                    console.error('Turnstile initialization error:', error);
                    currentTurnstileToken = null;
                }
            }
        };

        var currentTurnstileToken = null;
        if (turnstileWidget && isTurnstileLoaded()) {
            initializeTurnstile();
        }

        var currentRecaptchaToken = null;
        var googleSiteKey = formdata.google_site_key;
        var isUsingRecaptcha = isRecaptchaEnabled();
        
        if (isUsingRecaptcha && typeof grecaptcha.execute === 'function') {
            grecaptcha.ready(function () {
                grecaptcha.execute(googleSiteKey, { action: 'load' }).then(function (recaptchaToken) {
                    currentRecaptchaToken = recaptchaToken;
                });
            });
        }

        form.addEventListener('submit', function (e) {
            e.preventDefault();
            if (isSubmitting) return;

            isSubmitting = true;
            clearMessages();

            var isValid = true;
            currentFormData = {};
            currentFormFields = [];
            const checkboxGroups = new Set();

            form.querySelectorAll('.tpaep-form-field').forEach(field => {
                const inputs = field.querySelectorAll('input, textarea, select');
                if (!inputs.length) return;

                const label = field.querySelector('label') ? field.querySelector('label').textContent.trim() : '';
                const inputType = inputs[0].type;
                const inputName = inputs[0].name;

                if ((inputType === 'checkbox' || inputType === 'radio') && inputName) {
                    if (checkboxGroups.has(inputName)) return;
                    checkboxGroups.add(inputName);

                    const allGroupInputs = form.querySelectorAll(`input[name="${inputName}"]`);
                    let selected = [];
                    let isRequired = false;

                    allGroupInputs.forEach(input => {
                        if (input.required) isRequired = true;
                        if (input.checked) selected.push(input.value);
                    });

                    if (isRequired && selected.length === 0) {
                        isValid = false;
                        showFieldError(allGroupInputs[0], messages.requiredFieldsError.replace('%field%', label));
                    }

                    if (inputType === 'email' && inputValue !== '') {
                        if (!emailRegex.test(inputValue)) {
                            isValid = false;
                            showFieldError(input, emailFormatError);
                        }
                    }

                    if (inputType === 'checkbox') {
                        if (inputName === 'agree_to_terms') {
                            currentFormData[inputName] = selected.length > 0 ? 'yes' : 'no';
                        } else {
                            currentFormData[inputName] = selected;
                        }
                    } else if (inputType === 'radio' && selected.length > 0) {
                        currentFormData[inputName] = selected[0];
                    }
                    return;
                }

                inputs.forEach(input => {
                    const inputValue = input.value.trim();
                    const inputID = input.getAttribute('id') || '';
                    const inputName = input.getAttribute('name') || '';

                    if (!inputName) return;

                    if (inputName === 'g-recaptcha-response' || inputName === 'cf-turnstile-response') {
                        return;
                    }

                    currentFormData[inputName] = inputValue;

                    currentFormFields.push({
                        field_id: inputID,
                        field_name: inputName,
                        field_value: inputValue
                    });

                    if (input.required && inputValue === '') {
                        isValid = false;
                        const fieldLabel = label || inputName || 'This field';
                        showFieldError(input, messages.requiredFieldsError.replace('%field%', fieldLabel));
                    }

                    if (input.type === 'email' && inputValue !== '') {
                        if (!emailRegex.test(inputValue)) {
                            isValid = false;
                            showFieldError(input, messages.emailFormatError);
                        }
                    }
                });
            });

            if (!isValid) {
                isSubmitting = false;
                return;
            }
    
            var isUsingRecaptcha = typeof grecaptcha !== 'undefined' && googleSiteKey;
            var isUsingTurnstile = turnstileWidget && isTurnstileLoaded() && formdata.cf_site_key;
    
            if (isUsingRecaptcha && typeof grecaptcha.execute === 'function') {
                if (currentRecaptchaToken) {
                    var formSecurity = { 'g-recaptcha-response': currentRecaptchaToken };
                    submitForm(currentFormData, currentFormFields, formSecurity);
                } else {
                    grecaptcha.ready(function () {
                        grecaptcha.execute(googleSiteKey, { action: 'submit' }).then(function (recaptchaToken) {
                            var formSecurity = { 'g-recaptcha-response': recaptchaToken };
                            submitForm(currentFormData, currentFormFields, formSecurity);
                        });
                    });
                }
            } else if (isUsingTurnstile) {
                if (currentTurnstileToken) {
                    var formSecurity = { 'cf-turnstile-response': currentTurnstileToken };
                    submitForm(currentFormData, currentFormFields, formSecurity);
                } else {
                    if (widgetId && isTurnstileLoaded()) {
                        try {
                            if (widgetId && typeof turnstile.execute === 'function') {
                                turnstile.execute(widgetId, { action: 'submit' });
                            } else {
                                submitForm(currentFormData, currentFormFields, {});
                            }
                        } catch (error) {
                            console.error('Turnstile execution error:', error);
                            submitForm(currentFormData, currentFormFields, {});
                        }
                    } else {
                        submitForm(currentFormData, currentFormFields, {});
                    }
                }
            } else {
                submitForm(currentFormData, currentFormFields, {});
            }
        });

        var submitForm = function (formData, formFields, formSecurity) {
            var submitBtn = form.querySelector('.tpaep-form-submit');
            var btnText = submitBtn.querySelector('.tpaep-button-text');
            var btnLoader = submitBtn.querySelector('.tpaep-button-loader');
        
            submitBtn.disabled = true;
            if (btnText) {
                btnText.style.display = 'none';
            }
            if (btnLoader) {
                btnLoader.style.display = 'inline-flex';
            }

            $.ajax({
                url: theplus_ajax_url,
                type: 'POST',
                data: {
                    action: 'tpaep_form_submission',
                    form_data: JSON.stringify(formData),
                    form_security: JSON.stringify(formSecurity),
                    integration: integrationData,
                    form_fields: JSON.stringify(formFields),
                    page_url: window.location.href,
                },
                success: function (response) {
                    if (response?.success) {
                        displayMessage(messages.successMessage, 'success');
                        form.reset();
                        
                        if (isTurnstileEnabled() && widgetId && isTurnstileLoaded()) {
                            try {
                                if (typeof turnstile.reset === 'function') {
                                    turnstile.reset(widgetId);
                                    currentTurnstileToken = null;
                                    prewarmTurnstileToken();
                                }
                            } catch (error) {
                                console.error('Turnstile reset error:', error);
                            }
                        }                        
                        
                        if (isRecaptchaEnabled() && typeof grecaptcha !== 'undefined') {
                            try {
                                if (typeof grecaptcha.reset === 'function') {
                                    grecaptcha.reset();
                                    currentRecaptchaToken = null;
                                }
                            } catch (error) {
                                console.error('reCAPTCHA reset error:', error);
                            }
                        }
                        
                        var redirection = response?.data?.redirection || response.data?.redirect_sent;
                        if (redirection && redirection.url) {
                            if (redirection.is_external) {
                                window.open(redirection.url, '_blank', 'noopener,noreferrer');
                            } else {
                                window.location.href = redirection.url;
                            }
                        }
                    } else {
                        displayMessage(messages.formError.replace('%error%', response?.data?.message || ''), 'error');
                    }
                },
                error: function (xhr, status, error) {
                    displayMessage(messages.serverError.replace('%error%', error), 'error');
                    
                    if (isTurnstileEnabled() && widgetId && isTurnstileLoaded()) {
                        try {
                            if (typeof turnstile.reset === 'function') {
                                turnstile.reset(widgetId);
                                currentTurnstileToken = null;
                            }
                        } catch (resetError) {
                            console.error('Turnstile reset error:', resetError);
                        }
                    }
                    
                    if (isUsingRecaptcha && typeof grecaptcha !== 'undefined') {
                        try {
                            if (typeof grecaptcha.reset === 'function') {
                                grecaptcha.reset();
                                currentRecaptchaToken = null;
                            }
                        } catch (resetError) {
                            console.error('reCAPTCHA reset error:', resetError);
                        }
                    }
                },
                complete: function () {
                    isSubmitting = false;
                    if (btnLoader) {
                        btnLoader.style.display = 'none';
                    }
                    if (btnText) {
                        btnText.style.display = 'inline-block';
                    }
                    submitBtn.disabled = false;
                }
            });
        };

        function isTurnstileEnabled() {
            return !!(turnstileWidget && isTurnstileLoaded() && formdata.cf_site_key);
        }
        
        function isRecaptchaEnabled() {
            return typeof grecaptcha !== 'undefined' && !!googleSiteKey;
        }
        

        var showFieldError = function (input, message) {
            clearFieldError(input);
        
            var errorSpan = document.createElement('span');
            errorSpan.className = 'tpaep-field-error';
            errorSpan.style.color = '#FF0000';
            errorSpan.style.fontSize = '14px';
            errorSpan.style.marginTop = '5px';
            errorSpan.style.display = 'block';
            errorSpan.textContent = message;
        
            var fieldset = input.closest('.tpaep-radio-checkbox');
            var fieldWrapper = input.closest('.tpaep-form-field');
            
            if (fieldset && fieldWrapper) {
                fieldWrapper.appendChild(errorSpan);
            } else {
                input.parentElement.appendChild(errorSpan);
            }
            
            input.style.borderColor = '#FF0000';
            input.style.borderWidth = '2px';
            
            input.addEventListener('input', function() {
                clearFieldError(input);
                input.style.borderColor = '';
                input.style.borderWidth = '';
            }, { once: true });
        };

        var clearFieldError = function (input) {
            var fieldWrapper = input.closest('.tpaep-form-field');
            var existingError = fieldWrapper ? fieldWrapper.querySelector('.tpaep-field-error') : input.parentElement.querySelector('.tpaep-field-error');
            if (existingError) existingError.remove();
        };

        var clearMessages = function () {
            form.querySelectorAll('.tpaep-form-message').forEach(el => el.remove());
        };

        var messageTimeout;
        var displayMessage = function (message, type) {
            clearMessages();

            var messageDiv = document.createElement('div');
            messageDiv.className = 'tpaep-form-message ' + type;
            messageDiv.textContent = message;

            form.appendChild(messageDiv);

            clearTimeout(messageTimeout);
            messageTimeout = setTimeout(() => {
                messageDiv.remove();
            }, 5000);
        };

        var countryCodes = [
            { code: "+44", name: "UK (+44)", country_name: "UK" },
            { code: "+1", name: "USA (+1)", country_name: "USA" },
            { code: "+1", name: "Canada (+1)", country_name: "Canada" },
            { code: "+213", name: "Algeria (+213)", country_name: "Algeria" },
            { code: "+376", name: "Andorra (+376)", country_name: "Andorra" },
            { code: "+244", name: "Angola (+244)", country_name: "Angola" },
            { code: "+1264", name: "Anguilla (+1264)", country_name: "Anguilla" },
            { code: "+1268", name: "Antigua & Barbuda (+1268)", country_name: "Antigua & Barbuda" },
            { code: "+54", name: "Argentina (+54)", country_name: "Argentina" },
            { code: "+374", name: "Armenia (+374)", country_name: "Armenia" },
            { code: "+297", name: "Aruba (+297)", country_name: "Aruba" },
            { code: "+61", name: "Australia (+61)", country_name: "Australia" },
            { code: "+43", name: "Austria (+43)", country_name: "Austria" },
            { code: "+994", name: "Azerbaijan (+994)", country_name: "Azerbaijan" },
            { code: "+1242", name: "Bahamas (+1242)", country_name: "Bahamas" },
            { code: "+973", name: "Bahrain (+973)", country_name: "Bahrain" },
            { code: "+880", name: "Bangladesh (+880)", country_name: "Bangladesh" },
            { code: "+1246", name: "Barbados (+1246)", country_name: "Barbados" },
            { code: "+375", name: "Belarus (+375)", country_name: "Belarus" },
            { code: "+32", name: "Belgium (+32)", country_name: "Belgium" },
            { code: "+501", name: "Belize (+501)", country_name: "Belize" },
            { code: "+229", name: "Benin (+229)", country_name: "Benin" },
            { code: "+1441", name: "Bermuda (+1441)", country_name: "Bermuda" },
            { code: "+975", name: "Bhutan (+975)", country_name: "Bhutan" },
            { code: "+591", name: "Bolivia (+591)", country_name: "Bolivia" },
            { code: "+387", name: "Bosnia Herzegovina (+387)", country_name: "Bosnia Herzegovina" },
            { code: "+267", name: "Botswana (+267)", country_name: "Botswana" },
            { code: "+55", name: "Brazil (+55)", country_name: "Brazil" },
            { code: "+673", name: "Brunei (+673)", country_name: "Brunei" },
            { code: "+359", name: "Bulgaria (+359)", country_name: "Bulgaria" },
            { code: "+226", name: "Burkina Faso (+226)", country_name: "Burkina Faso" },
            { code: "+257", name: "Burundi (+257)", country_name: "Burundi" },
            { code: "+855", name: "Cambodia (+855)", country_name: "Cambodia" },
            { code: "+237", name: "Cameroon (+237)", country_name: "Cameroon" },
            { code: "+238", name: "Cape Verde Islands (+238)", country_name: "Cape Verde Islands" },
            { code: "+1345", name: "Cayman Islands (+1345)", country_name: "Cayman Islands" },
            { code: "+236", name: "Central African Republic (+236)", country_name: "Central African Republic" },
            { code: "+56", name: "Chile (+56)", country_name: "Chile" },
            { code: "+86", name: "China (+86)", country_name: "China" },
            { code: "+57", name: "Colombia (+57)", country_name: "Colombia" },
            { code: "+269", name: "Comoros (+269)", country_name: "Comoros" },
            { code: "+242", name: "Congo (+242)", country_name: "Congo" },
            { code: "+682", name: "Cook Islands (+682)", country_name: "Cook Islands" },
            { code: "+506", name: "Costa Rica (+506)", country_name: "Costa Rica" },
            { code: "+385", name: "Croatia (+385)", country_name: "Croatia" },
            { code: "+53", name: "Cuba (+53)", country_name: "Cuba" },
            { code: "+90392", name: "Cyprus North (+90392)", country_name: "Cyprus North" },
            { code: "+357", name: "Cyprus South (+357)", country_name: "Cyprus South" },
            { code: "+42", name: "Czech Republic (+42)", country_name: "Czech Republic" },
            { code: "+45", name: "Denmark (+45)", country_name: "Denmark" },
            { code: "+253", name: "Djibouti (+253)", country_name: "Djibouti" },
            { code: "+1809", name: "Dominican Republic (+1809)", country_name: "Dominican Republic" },
            { code: "+593", name: "Ecuador (+593)", country_name: "Ecuador" },
            { code: "+20", name: "Egypt (+20)", country_name: "Egypt" },
            { code: "+503", name: "El Salvador (+503)", country_name: "El Salvador" },
            { code: "+240", name: "Equatorial Guinea (+240)", country_name: "Equatorial Guinea" },
            { code: "+291", name: "Eritrea (+291)", country_name: "Eritrea" },
            { code: "+372", name: "Estonia (+372)", country_name: "Estonia" },
            { code: "+251", name: "Ethiopia (+251)", country_name: "Ethiopia" },
            { code: "+500", name: "Falkland Islands (+500)", country_name: "Falkland Islands" },
            { code: "+298", name: "Faroe Islands (+298)", country_name: "Faroe Islands" },
            { code: "+679", name: "Fiji (+679)", country_name: "Fiji" },
            { code: "+358", name: "Finland (+358)", country_name: "Finland" },
            { code: "+33", name: "France (+33)", country_name: "France" },
            { code: "+594", name: "French Guiana (+594)", country_name: "French Guiana" },
            { code: "+689", name: "French Polynesia (+689)", country_name: "French Polynesia" },
            { code: "+241", name: "Gabon (+241)", country_name: "Gabon" },
            { code: "+220", name: "Gambia (+220)", country_name: "Gambia" },
            { code: "+7880", name: "Georgia (+7880)", country_name: "Georgia" },
            { code: "+49", name: "Germany (+49)", country_name: "Germany" },
            { code: "+233", name: "Ghana (+233)", country_name: "Ghana" },
            { code: "+350", name: "Gibraltar (+350)", country_name: "Gibraltar" },
            { code: "+30", name: "Greece (+30)", country_name: "Greece" },
            { code: "+299", name: "Greenland (+299)", country_name: "Greenland" },
            { code: "+1473", name: "Grenada (+1473)", country_name: "Grenada" },
            { code: "+590", name: "Guadeloupe (+590)", country_name: "Guadeloupe" },
            { code: "+671", name: "Guam (+671)", country_name: "Guam" },
            { code: "+502", name: "Guatemala (+502)", country_name: "Guatemala" },
            { code: "+224", name: "Guinea (+224)", country_name: "Guinea" },
            { code: "+245", name: "Guinea - Bissau (+245)", country_name: "Guinea - Bissau" },
            { code: "+592", name: "Guyana (+592)", country_name: "Guyana" },
            { code: "+509", name: "Haiti (+509)", country_name: "Haiti" },
            { code: "+504", name: "Honduras (+504)", country_name: "Honduras" },
            { code: "+852", name: "Hong Kong (+852)", country_name: "Hong Kong" },
            { code: "+36", name: "Hungary (+36)", country_name: "Hungary" },
            { code: "+354", name: "Iceland (+354)", country_name: "Iceland" },
            { code: "+91", name: "India (+91)", country_name: "India" },
            { code: "+62", name: "Indonesia (+62)", country_name: "Indonesia" },
            { code: "+98", name: "Iran (+98)", country_name: "Iran" },
            { code: "+964", name: "Iraq (+964)", country_name: "Iraq" },
            { code: "+353", name: "Ireland (+353)", country_name: "Ireland" },
            { code: "+972", name: "Israel (+972)", country_name: "Israel" },
            { code: "+39", name: "Italy (+39)", country_name: "Italy" },
            { code: "+1876", name: "Jamaica (+1876)", country_name: "Jamaica" },
            { code: "+81", name: "Japan (+81)", country_name: "Japan" },
            { code: "+962", name: "Jordan (+962)", country_name: "Jordan" },
            { code: "+7", name: "Kazakhstan (+7)", country_name: "Kazakhstan" },
            { code: "+254", name: "Kenya (+254)", country_name: "Kenya" },
            { code: "+686", name: "Kiribati (+686)", country_name: "Kiribati" },
            { code: "+850", name: "Korea North (+850)", country_name: "Korea North" },
            { code: "+82", name: "Korea South (+82)", country_name: "Korea South" },
            { code: "+965", name: "Kuwait (+965)", country_name: "Kuwait" },
            { code: "+996", name: "Kyrgyzstan (+996)", country_name: "Kyrgyzstan" },
            { code: "+856", name: "Laos (+856)", country_name: "Laos" },
            { code: "+371", name: "Latvia (+371)", country_name: "Latvia" },
            { code: "+961", name: "Lebanon (+961)", country_name: "Lebanon" },
            { code: "+266", name: "Lesotho (+266)", country_name: "Lesotho" },
            { code: "+231", name: "Liberia (+231)", country_name: "Liberia" },
            { code: "+218", name: "Libya (+218)", country_name: "Libya" },
            { code: "+417", name: "Liechtenstein (+417)", country_name: "Liechtenstein" },
            { code: "+370", name: "Lithuania (+370)", country_name: "Lithuania" },
            { code: "+352", name: "Luxembourg (+352)", country_name: "Luxembourg" },
            { code: "+853", name: "Macao (+853)", country_name: "Macao" },
            { code: "+389", name: "Macedonia (+389)", country_name: "Macedonia" },
            { code: "+261", name: "Madagascar (+261)", country_name: "Madagascar" },
            { code: "+265", name: "Malawi (+265)", country_name: "Malawi" },
            { code: "+60", name: "Malaysia (+60)", country_name: "Malaysia" },
            { code: "+960", name: "Maldives (+960)", country_name: "Maldives" },
            { code: "+223", name: "Mali (+223)", country_name: "Mali" },
            { code: "+356", name: "Malta (+356)", country_name: "Malta" },
            { code: "+692", name: "Marshall Islands (+692)", country_name: "Marshall Islands" },
            { code: "+596", name: "Martinique (+596)", country_name: "Martinique" },
            { code: "+222", name: "Mauritania (+222)", country_name: "Mauritania" },
            { code: "+269", name: "Mayotte (+269)", country_name: "Mayotte" },
            { code: "+52", name: "Mexico (+52)", country_name: "Mexico" },
            { code: "+691", name: "Micronesia (+691)", country_name: "Micronesia" },
            { code: "+373", name: "Moldova (+373)", country_name: "Moldova" },
            { code: "+377", name: "Monaco (+377)", country_name: "Monaco" },
            { code: "+976", name: "Mongolia (+976)", country_name: "Mongolia" },
            { code: "+1664", name: "Montserrat (+1664)", country_name: "Montserrat" },
            { code: "+212", name: "Morocco (+212)", country_name: "Morocco" },
            { code: "+258", name: "Mozambique (+258)", country_name: "Mozambique" },
            { code: "+95", name: "Myanmar (+95)", country_name: "Myanmar" },
            { code: "+264", name: "Namibia (+264)", country_name: "Namibia" },
            { code: "+674", name: "Nauru (+674)", country_name: "Nauru" },
            { code: "+977", name: "Nepal (+977)", country_name: "Nepal" },
            { code: "+31", name: "Netherlands (+31)", country_name: "Netherlands" },
            { code: "+687", name: "New Caledonia (+687)", country_name: "New Caledonia" },
            { code: "+64", name: "New Zealand (+64)", country_name: "New Zealand" },
            { code: "+505", name: "Nicaragua (+505)", country_name: "Nicaragua" },
            { code: "+227", name: "Niger (+227)", country_name: "Niger" },
            { code: "+234", name: "Nigeria (+234)", country_name: "Nigeria" },
            { code: "+683", name: "Niue (+683)", country_name: "Niue" },
            { code: "+672", name: "Norfolk Islands (+672)", country_name: "Norfolk Islands" },
            { code: "+670", name: "Northern Marianas (+670)", country_name: "Northern Marianas" },
            { code: "+47", name: "Norway (+47)", country_name: "Norway" },
            { code: "+968", name: "Oman (+968)", country_name: "Oman" },
            { code: "+92", name: "Pakistan (+92)", country_name: "Pakistan" },
            { code: "+680", name: "Palau (+680)", country_name: "Palau" },
            { code: "+507", name: "Panama (+507)", country_name: "Panama" },
            { code: "+675", name: "Papua New Guinea (+675)", country_name: "Papua New Guinea" },
            { code: "+595", name: "Paraguay (+595)", country_name: "Paraguay" },
            { code: "+51", name: "Peru (+51)", country_name: "Peru" },
            { code: "+63", name: "Philippines (+63)", country_name: "Philippines" },
            { code: "+48", name: "Poland (+48)", country_name: "Poland" },
            { code: "+351", name: "Portugal (+351)", country_name: "Portugal" },
            { code: "+1787", name: "Puerto Rico (+1787)", country_name: "Puerto Rico" },
            { code: "+974", name: "Qatar (+974)", country_name: "Qatar" },
            { code: "+262", name: "Reunion (+262)", country_name: "Reunion" },
            { code: "+40", name: "Romania (+40)", country_name: "Romania" },
            { code: "+7", name: "Russia (+7)", country_name: "Russia" },
            { code: "+250", name: "Rwanda (+250)", country_name: "Rwanda" },
            { code: "+378", name: "San Marino (+378)", country_name: "San Marino" },
            { code: "+239", name: "Sao Tome & Principe (+239)", country_name: "Sao Tome & Principe" },
            { code: "+966", name: "Saudi Arabia (+966)", country_name: "Saudi Arabia" },
            { code: "+221", name: "Senegal (+221)", country_name: "Senegal" },
            { code: "+381", name: "Serbia (+381)", country_name: "Serbia" },
            { code: "+248", name: "Seychelles (+248)", country_name: "Seychelles" },
            { code: "+232", name: "Sierra Leone (+232)", country_name: "Sierra Leone" },
            { code: "+65", name: "Singapore (+65)", country_name: "Singapore" },
            { code: "+421", name: "Slovak Republic (+421)", country_name: "Slovak Republic" },
            { code: "+386", name: "Slovenia (+386)", country_name: "Slovenia" },
            { code: "+677", name: "Solomon Islands (+677)", country_name: "Solomon Islands" },
            { code: "+252", name: "Somalia (+252)", country_name: "Somalia" },
            { code: "+27", name: "South Africa (+27)", country_name: "South Africa" },
            { code: "+34", name: "Spain (+34)", country_name: "Spain" },
            { code: "+94", name: "Sri Lanka (+94)", country_name: "Sri Lanka" },
            { code: "+290", name: "St. Helena (+290)", country_name: "St. Helena" },
            { code: "+1869", name: "St. Kitts (+1869)", country_name: "St. Kitts" },
            { code: "+1758", name: "St. Lucia (+1758)", country_name: "St. Lucia" },
            { code: "+249", name: "Sudan (+249)", country_name: "Sudan" },
            { code: "+597", name: "Suriname (+597)", country_name: "Suriname" },
            { code: "+268", name: "Swaziland (+268)", country_name: "Swaziland" },
            { code: "+46", name: "Sweden (+46)", country_name: "Sweden" },
            { code: "+41", name: "Switzerland (+41)", country_name: "Switzerland" },
            { code: "+963", name: "Syria (+963)", country_name: "Syria" },
            { code: "+886", name: "Taiwan (+886)", country_name: "Taiwan" },
            { code: "+7", name: "Tajikstan (+7)", country_name: "Tajikstan" },
            { code: "+66", name: "Thailand (+66)", country_name: "Thailand" },
            { code: "+228", name: "Togo (+228)", country_name: "Togo" },
            { code: "+676", name: "Tonga (+676)", country_name: "Tonga" },
            { code: "+1868", name: "Trinidad & Tobago (+1868)", country_name: "Trinidad & Tobago" },
            { code: "+216", name: "Tunisia (+216)", country_name: "Tunisia" },
            { code: "+90", name: "Turkey (+90)", country_name: "Turkey" },
            { code: "+7", name: "Turkmenistan (+7)", country_name: "Turkmenistan" },
            { code: "+993", name: "Turkmenistan (+993)", country_name: "Turkmenistan" },
            { code: "+1649", name: "Turks & Caicos Islands (+1649)", country_name: "Turks & Caicos Islands" },
            { code: "+688", name: "Tuvalu (+688)", country_name: "Tuvalu" },
            { code: "+256", name: "Uganda (+256)", country_name: "Uganda" },
            { code: "+380", name: "Ukraine (+380)", country_name: "Ukraine" },
            { code: "+971", name: "United Arab Emirates (+971)", country_name: "United Arab Emirates" },
            { code: "+598", name: "Uruguay (+598)", country_name: "Uruguay" },
            { code: "+7", name: "Uzbekistan (+7)", country_name: "Uzbekistan" },
            { code: "+678", name: "Vanuatu (+678)", country_name: "Vanuatu" },
            { code: "+379", name: "Vatican City (+379)", country_name: "Vatican City" },
            { code: "+58", name: "Venezuela (+58)", country_name: "Venezuela" },
            { code: "+84", name: "Vietnam (+84)", country_name: "Vietnam" },
            { code: "+84", name: "Virgin Islands - British (+1284)", country_name: "Virgin Islands - British" },
            { code: "+84", name: "Virgin Islands - US (+1340)", country_name: "Virgin Islands - US" },
            { code: "+681", name: "Wallis & Futuna (+681)", country_name: "Wallis & Futuna" },
            { code: "+969", name: "Yemen (North)(+969)", country_name: "Yemen (North)" },
            { code: "+967", name: "Yemen (South)(+967)", country_name: "Yemen (South)" },
            { code: "+260", name: "Zambia (+260)", country_name: "Zambia" },
            { code: "+263", name: "Zimbabwe (+263)", country_name: "Zimbabwe" },
        ];
    
        const $select = $('.tpaep-phone-country-code');
    
        countryCodes.forEach(function (country) {
            const $option = $('<option></option>')
            .val(country.code)
            .text(country.name);
            $select.append($option);
        });

        // Handle country code detection for each phone field
        $('.tpaep-phone-wrapper').each(function() {
            var $phoneWrapper = $(this);
            var $select = $phoneWrapper.find('.tpaep-phone-country-code');
            var detectionType = $phoneWrapper.data('country-detection');
            var defaultCountry = $phoneWrapper.data('default-country');
            
            if (detectionType === 'default' && defaultCountry) {
                $select.val(defaultCountry);
            } else if (detectionType === 'ip') {
                $.ajax({
                    url: theplus_ajax_url,
                    type: 'POST',
                    data: {
                        action: 'tpaep_get_country_code'
                    },
                    success: function (response) {
                        if (response && response.success && response.data && response.data.phone_code) {
                            var phoneCode = response.data.phone_code;
                            $select.val(phoneCode);
                        }
                    },
                    error: function () {
                        console.log('Country detection failed, using default');
                    }
                });
            }
        });

        function prewarmTurnstileToken() {
            if (turnstileWidget && isTurnstileLoaded() && widgetId && typeof turnstile.execute === 'function') {
                    turnstile.execute(widgetId, { action: 'prefetch' });
            }
        }

        function setFormFieldWidth() {
            var formFields = container.querySelectorAll(".tpaep-form-field");
                formFields.forEach(el => {
                    let tabletWidth = el.getAttribute("data-tablet-width"),
                        mobileWidth = el.getAttribute("data-mobile-width"),
                        desktopWidth = el.getAttribute("data-width");

                    if (window.innerWidth < 768) {
                        el.style.width = mobileWidth + "%";
                    } else if (window.innerWidth <= 1024) {
                        el.style.width = tabletWidth + "%";
                    } else {
                        el.style.width = desktopWidth + "%";
                    }
                });
        }

        setFormFieldWidth();
        window.addEventListener('resize', setFormFieldWidth);

    };

    window.addEventListener('elementor/frontend/init', function () {
        elementorFrontend.hooks.addAction('frontend/element_ready/tp-plus-form.default', WidgetFormHandler);
    });

})(jQuery);
