jQuery(document).ready(function() {
    var params = window.location.search.replace('?', '').split('&').reduce(
        function(p, e) {
            var a = e.split('=');
            p[decodeURIComponent(a[0])] = decodeURIComponent(a[1]);
            return p;
        }, {}
    );
    var lang;
    var initForms = document.querySelectorAll('[data-form="registrationForm"]');
    var currentEmail = '';
    var iti = [];
    var API = localStorage.getItem('api_registration_form') || window.location.origin;

    if (initForms.length) {
        const url_params = new URLSearchParams(location.search);
        let _tokenUrl = `${API}/api/user/auth/geo-data`;
        const request = new XMLHttpRequest();

        url_params.get('ip') ? _tokenUrl += '?ip=' + url_params.get('ip') : null;

        request.open("GET", _tokenUrl, true);
        request.send();

        request.addEventListener("readystatechange", () => {
            if (request.readyState === 4) {
                if (request.status === 200) {
                    const _geoDataResponse = JSON.parse(request.response);
                    localStorage.setItem('phone_code', _geoDataResponse['phone_code']); // TODO remove, should get phone_code from intlTelInput
                    localStorage.setItem('iso_code', _geoDataResponse['iso_code']);
                    localStorage.setItem('ip', _geoDataResponse['ip']);

                    initForms.forEach((form, formIndex) => {
                        iti[formIndex] = window.intlTelInput(form.querySelector('#form-phone_number'), {
                            initialCountry: _geoDataResponse['iso_code'],
                            autoPlaceholder: 'aggressive',
                            utilsScript: "/wp-content/themes/hello-elementor/utils.min.js",
                            separateDialCode: true,
                            excludeCountries: ['us','il' ]    
                        });
                        form.addEventListener('change', (event) => {
                            for (var i = 0; i < initForms.length; i++) {
                                initForms[i].querySelector(`#${event.target.id}`).value = event.target
                                .value;
                            }
                        });
                        form.addEventListener("countrychange", (event) => {
                            iti.forEach((telInput, itiIndex) => {
                                if (formIndex !== itiIndex) {
                                    telInput.setCountry(iti[formIndex].getSelectedCountryData()['iso2']);
                                }
                            })
                        });
            
                        var initInputs = form.querySelectorAll('[data-input]');
                        if (params.firstname) {
                            form.querySelector('[data-input="firstname"]').value = params.firstname;
                            form.querySelector('[data-input="firstname"]').dataset.valid = 'true';
                        }
                        if (params.email) {
                            form.querySelector('[data-input="email"]').value = params.email;
                            form.querySelector('[data-input="email"]').dataset.valid = 'true';
                            checkCorrectEmail(
                                form.querySelector('[data-input="email"]').parentElement,
                                form.querySelector('[data-input="email"]').value);
                        }
                        if (initInputs) {
                            initInputs.forEach((input) => {
                                input.addEventListener('blur', inputValidator);
                            })
                        }
            
                        form.querySelector('#form-btn').addEventListener('click', (event) => {
                            event.preventDefault();
            
                            if (!checkFormValid(form)) {
                                return false;
                            }
            
                            var request = new XMLHttpRequest();
                            var urlParams = parseUrlQueryString(location.search.slice(1));
                            var url = `${API}/api/split-registration`;
                            var dataParams = {};
            
                            document.querySelectorAll('.submit-overlay').forEach((wrapper) => wrapper.style.display = 'flex');
                            request.open("POST", url, true);
                            request.setRequestHeader("Content-type", "application/json");
            
                            var initInputs = form.querySelectorAll('[data-input]');
                            if (initInputs) {
                                initInputs.forEach((input) => {
                                    dataParams[input.name] = input.value;
                                })
                            }
            
                            if (location.search) {
                                Object.keys(urlParams).forEach((key) => {
                                    if (key !== 'email' && key !== 'firstname' && key !==
                                        'lastname') {
                                        dataParams[key] = urlParams[key];
                                    }
                                })
            
                                if (urlParams['lang']) {
                                    lang = urlParams['lang'];
                                }
                                if (urlParams['ip']) {
                                    dataParams['registration_ip'] = urlParams['ip'];
                                }
                            }
            
                            if (lang) {
                                request.setRequestHeader("X-Language", lang);
                            }
            
                            dataParams['phone_code'] = '+' + iti[0].getSelectedCountryData()['dialCode'];
                            dataParams['country_iso'] = iti[0].getSelectedCountryData()['iso2'];
                            dataParams['sync'] = 1;
            
                            request.send(JSON.stringify(dataParams));
                            request.addEventListener("readystatechange", () => {
                                document.querySelectorAll('.submit-overlay').forEach(
                                    (wrapper) => {
                                        wrapper.style.opacity = 1;
                                        jQuery(wrapper).animate({
                                            opacity: 0
                                        }, 1000, function() {
                                            wrapper.style.display = 'none';
                                            wrapper.style.opacity = '';
                                        })
                                });
            
                                if (request.readyState === 4) {
                                    if (request.status === 200) {
                                        var response = JSON.parse(request.responseText);
                                        if (!!response.redirect_url && urlParams[
                                            'disableRedirect'] !== '1') {
                                            window.location.replace(response
                                                .redirect_url);
                                        }
                                        if (!response.sblock) {
                                            fillSendlaneForm(form);
                                        }
                                    } else if (request.status === 422) {
                                        showValidationErrors(JSON.parse(request.responseText));
                                    } else if (request.status === 404) {
                                        var response = JSON.parse(request.responseText);
                                        if (response.message) {
                                            form.querySelector('[data-modal="error"]').innerHTML =
                                                response.message;
                                            form.querySelector('[data-modal="error"]').style
                                                .display = 'flex';
                                        }
                                    }
                                }
                            });
                        })
                    })
                }
            }

        });
    }

    function inputValidator(event) {
        var dataType, value, formGroup, errorMessage;

        if (event.type === 'blur') {
            dataType = event.target.dataset.input;
            value = event.target.value;
            formGroup = event.target.parentElement;
            errorMessage = formGroup.querySelector('.error-message');
        } else {
            dataType = event.dataset.input;
            value = event.value;
            formGroup = event.parentElement;
            errorMessage = formGroup.querySelector('.error-message');
        }

        switch (dataType) {
            case 'firstname':
                if (value.length === 0) {
                    switchValidatorStatus(formGroup, false, 'Please enter your First name');
                } else if (value.length < 1) {
                    switchValidatorStatus(formGroup, false, 'First name is too short (at least 2 char)');
                } else if (value.length > 50) {
                    switchValidatorStatus(formGroup, false, 'First name is too long (at most 50 char)');
                } else {
                    switchValidatorStatus(formGroup, true);
                }
                break;

            case 'lastname':
                if (value.length === 0) {
                    switchValidatorStatus(formGroup, false, 'Please enter your Last name');
                } else if (value.length < 1) {
                    switchValidatorStatus(formGroup, false, 'Last name is too short (at least 2 char)');
                } else if (value.length > 50) {
                    switchValidatorStatus(formGroup, false, 'Last name is too long (at most 50 char)');
                } else {
                    switchValidatorStatus(formGroup, true);
                }
                break;

            case 'email':
                var regEmail =
                    /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
                var resultEmail = regEmail.test(String(value).toLowerCase());
                if (value.length === 0) {
                    switchValidatorStatus(formGroup, false, 'Please enter your Email address');
                } else if (!resultEmail) {
                    switchValidatorStatus(formGroup, false,
                        'Please enter a valid email address (example@email.com)');
                    checkCorrectEmail(formGroup, value);
                } else {
                    switchValidatorStatus(formGroup, true);
                    checkCorrectEmail(formGroup, value);
                }
                break;

            case 'phone_number':
                var regPhone = /^[\d ()+-]+$/;
                var resultPhone = regPhone.test(value);
                var plcholder = formGroup.querySelector('[data-input="phone_number"]').placeholder;
                var errorMessageContainer = formGroup.parentElement.querySelector('.error-message');

                if (value.length === 0) {
                    switchValidatorStatus(formGroup.parentElement, false,
                        'Please enter your Phone number. Example:');
                } else if (!resultPhone || value.length < 6 || value.length > 16) {
                    switchValidatorStatus(formGroup.parentElement, false,
                        'Phone number contains invalid characters, please provide a valid phone. Example:');
                } else {
                    switchValidatorStatus(formGroup.parentElement, true);
                }

                if (errorMessageContainer) {
                    errorMessageContainer.innerText += ' ' + plcholder;
                } else {
                    formGroup.parentElement.querySelector(
                        '.error-message').innerText += ' ' + plcholder;
                }
                break;

            default:
                break;
        }
    }

    function switchValidatorStatus(formGroup, valid = false, message = '') {
        var errorMessage = formGroup.querySelector('.error-message');
        var input = formGroup.querySelector('[data-input]');

        if (errorMessage) {
            errorMessage.innerText = message;
        }
        if (input) {
            input.setAttribute('data-valid', valid);
        }

        if (valid) {
            formGroup.classList.remove('error');
            formGroup.classList.add('success');
        } else {
            formGroup.classList.remove('success');
            formGroup.classList.add('error');
        }
    }

    function checkCorrectEmail(formGroup, e) {
        if (Mailcheck) {
            Mailcheck.run({
                email: e,
                suggested: (suggestion) => {
                    currentEmail = suggestion.full;
                    formGroup.classList.add('info');
                    formGroup.querySelector('.form-group__emailValid-info').style.display = 'block';
                    formGroup.querySelector('.form-group__emailValid-info b').innerText = suggestion
                        .full;
                },
                empty: (data) => {
                    currentEmail = '';
                    formGroup.querySelector('.form-group__emailValid-info').style.display = 'none';
                    formGroup.classList.remove('info');
                    formGroup.querySelector('.form-group__emailValid-info b').innerText = '';
                }
            });
        }
    }

    document.querySelectorAll('.form-group__emailValid-btn').forEach((btn, btnIndex) => {
        btn.addEventListener('click', function() {
            var formInput = document.querySelectorAll('.regFormEmail'),
                formGroup,
                emailValid,
                emailWrapper;
            [].forEach.call(formInput, (item) => {
                item.value = currentEmail;
                formGroup = item.parentElement;
                emailValid = formGroup.querySelector('.form-group__emailValid-info')
                emailWrapper = formGroup.querySelector('.form-group__emailValid-info b')
                formGroup.classList.remove('info');
                emailValid.style.display = 'none';
                formGroup.classList.remove('error');
                emailWrapper.innerText = '';
                switchValidatorStatus(formGroup, true);
                localStorage.setItem('disableSendlaneSending', 0);
            });
        });
    });

    function checkFormValid(form) {
        var inputs = form.querySelectorAll('[data-valid]');
        var inputsArr = Array.prototype.slice.call(inputs); // Array.from() not supported IE
        if (inputsArr && inputsArr.every((input) => input.dataset.valid === 'true')) {
            return true;

        } else {
            inputsArr.forEach((input) => inputValidator(input));
            return false;
        }
    }

    function generateFormPostData(form) {
        var initInputs = form.querySelectorAll('[data-input]');
        var params = '';

        if (initInputs) {
            initInputs.forEach((input) => {
                params += `${input.name}=${input.value}&`;
            })
        }

        return params;
    }

    function parseUrlQueryString(query) {
        var vars = query.split("&");
        var query_string = {};
        for (var i = 0; i < vars.length; i++) {
            var pair = vars[i].split("=");
            var key = decodeURIComponent(pair[0]);
            var value = decodeURIComponent(pair[1]);
            // If first entry with this name
            if (typeof query_string[key] === "undefined") {
                query_string[key] = decodeURIComponent(value);
                // If second entry with this name
            } else if (typeof query_string[key] === "string") {
                var arr = [query_string[key], decodeURIComponent(value)];
                query_string[key] = arr;
                // If third or later entry with this name
            } else {
                query_string[key].push(decodeURIComponent(value));
            }
        }
        return query_string;
    }

    function showValidationErrors(errors) {
        var forms = document.querySelectorAll('[data-form="registrationForm"]');

        errors.forEach((error) => {

            forms.forEach((form) => {
                var input = form.querySelector(`[data-input="${error.field}"]`);

                if (input) {
                    var formGroup;
                    if (error.field === 'phone_number') {
                        formGroup = input.parentElement.parentElement
                    } else {
                        formGroup = input.parentElement
                    }

                    var errorMessage = formGroup.querySelector('.error-message');
                    formGroup.classList.remove('success');
                    formGroup.classList.add('error');

                    if (errorMessage) {
                        errorMessage.innerText = error['message'];
                    }
                    if (input) {
                        input.setAttribute('data-valid', 'false');
                    }
                }
            })
        })
    }

    function fillSendlaneForm(regForm) {
        var inputs = regForm.querySelectorAll('[data-input]'),
            sendlaneForms = document.querySelectorAll(
            '[data-hiddenform="cdpapp"]'); // TODO data-hiddenform="sendlane"

        inputs.forEach((input) => {
            switch (input.dataset.input) {
                case 'firstname':
                    fillForm('c152', input.value);
                    break;
                case 'lastname':
                    fillForm('c153', input.value);
                    break;
                case 'email':
                    fillForm('email', input.value);
                    break;
                default:
                    break;
            }
        })

        function fillForm(selector, val) {
            sendlaneForms.forEach((form) => {
                form.querySelector('[name="' + selector + '"]').value = val;
            });
        }

        if (!+localStorage.getItem('disableSendlaneSending')) {
            sendlaneForms.forEach((form) => {
                form.submit();
            });
        }
    }
});