jQuery(document).ready(function ($) {
    'use strict';

    let userRef = '';

    if (typeof wacvParams === 'undefined') {
        return;
    }

    const wacvCookie = {
        get(cname) {
            let cookie_arr = document.cookie.split(";");
            $.each(cookie_arr, function (key, val) {
                if (val) {
                    if (val.indexOf('ppviewtimer') === 1 || val.indexOf('ppviewtimer') === 0) {
                        cookie_arr.splice(key, 1);
                    }
                }
            });
            let name = cname + "=",
                decodedCookie = cookie_arr.join(';'),
                ca = decodedCookie.split(';');
            for (let i = 0; i < ca.length; i++) {
                let c = ca[i];
                while (c.charAt(0) == ' ') {
                    c = c.substring(1);
                }
                if (c.indexOf(name) == 0) {
                    return c.substring(name.length, c.length);
                }
            }
            return "";
        },

        set(cname, cvalue, exdays = 86400) {
            var d = new Date();
            d.setTime(d.getTime() + (exdays * 1000));//* 24 * 60 * 60
            var expires = "expires=" + d.toUTCString();
            document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
        }
    };

    const wacvFbCheckBox = {

        checkedStt: false,
        cbRender: false,
        fbCbRequire: !!(parseInt(wacvParams.fbCbRequire)),

        init() {
            this.checkAjaxSend = false;
            this.confirmOptin();
            this.requireCheckbox();
        },

        getUserRef(atcButton) {
            let _this = this;
            $.ajax({
                url: wacvParams.ajaxUrl,
                type: 'post',
                data: {action: 'wacv_get_info', user_ref: userRef, nonce: wacvParams.nonce},
                success(res) {
                    _this.checkAjaxSend = true;
                    atcButton.trigger('click');
                }
            });
        },

        confirmOptin() {
            let _this = this;
            $('form.cart button[type=submit], .single_add_to_cart_button, .ajax_add_to_cart').on('click', function (e) {
                if (_this.checkedStt && !_this.checkAjaxSend) {
                    let thisAtcButton = $(this);
                    e.preventDefault();
                    e.stopImmediatePropagation();

                    _this.getUserRef(thisAtcButton);
                }
            });
        },

        requireCheckbox() {
            let _this = this;
            $('form.cart button[type=submit], .single_add_to_cart_button, .ajax_add_to_cart, .wacv-add-to-cart-btn').on('click', function (e) {
                if (!_this.fbCbRequire) return;
                if (!_this.checkedStt && _this.cbRender) {
                    e.stopImmediatePropagation();
                    e.preventDefault();
                }
            });
        }
    };

    wacvFbCheckBox.init();

    const wacvGetEmail = {
        atcButton: '',
        redirectAfterATC: '',
        popup: '',

        init() {
            this.popup = $('#wacv-modal');
            this.showPopup();
            this.chooseAction();
            this.afterAjaxATC();
        },

        showPopup: function () {
            if (!this.popup.length) return;
            $('#wacv-modal').trigger('renderReCaptcha');
            let _this = this;

            $('form.cart button[type=submit], .single_add_to_cart_button, .ajax_add_to_cart, .add_to_cart_button, .fw-pricing .fw-button-row a.button,.wacv-open-popup, #tribe-tickets__tickets-form #tribe-tickets__tickets-buy, .wpem-ticket-register-button button.wpem-theme-button').on('mousedown', function (e) {
                if (wacvParams.hasOwnProperty('exclude_atc') && wacvParams.exclude_atc !== '') {
                    let is_exclude_button_class = 0, btn_element = $(this);
                    const exclude_atc_class = wacvParams.exclude_atc.split(",");
                    $.each(exclude_atc_class, function(exc_i, exc_v) {
                        if (btn_element.hasClass(exc_v)) {
                            is_exclude_button_class = 1;
                        }
                    });
                    if (is_exclude_button_class === 1) {
                        return;
                    }
                }

                if ($(this).hasClass('disabled')) {
                    return;
                }
                $('[tabindex="-1"]').removeAttr('tabindex');
                if (wacvCookie.get('wacv_get_email')) return;
                e.stopImmediatePropagation();
                e.preventDefault();
                _this.atcButton = $(this);

                if (!_this.atcButton.hasClass('ajax_add_to_cart') && wacvParams.redirect) {
                    _this.atcButton.after(`<input type="hidden" name="wacv_redirect" value="${wacvParams.redirect}">`);
                } else {
                    _this.redirectAfterATC = true;
                }

                _this.popup.fadeIn(300);

            });

            if (wacvParams.immediate_cart_popup) {
                if (!wacvCookie.get('wacv_get_email')) {
                    _this.popup.fadeIn(300);
                }
            }
        },

        chooseAction() {
            let _this = this;
            $('.wacv-add-to-cart-btn').on('click', function () {
                $('.wacv-email-invalid-notice, .wacv-phone-number-invalid-notice').hide();

                let email = $('.wacv-popup-input-email').val(),
                    phone = $('.wacv-popup-input-phone-number').val(),
                    gdprCb = $('.wacv-gdpr-checkbox'),
                    g_validate_response = $('.wacv-recaptcha-field .wacv-g-validate-response').val(),
                    error = false;
                phone = _this.formatPhoneNumber(phone);

                if (wacvParams.recaptcha === '1' && typeof grecaptcha !== 'undefined' && wacvParams.recaptcha_key && !g_validate_response) {
                    $('.wacv-recaptcha-field .wacv-recaptcha >div').addClass('wacv-recaptcha-error').focus();

                    error = true;
                } else {
                    $('.wacv-recaptcha-field .wacv-recaptcha >div').removeClass('wacv-recaptcha-error');
                }

                if (parseInt(wacvParams.gdprField)) {
                    gdprCb.removeClass('wacv-error');
                    let checkChecked = $('.wacv-gdpr-checkbox:checked').length;
                    if (checkChecked === 0) {
                        gdprCb.addClass('wacv-error');
                        error = true;
                    }
                }

                if (!_this.emailValidation(email) && parseInt(wacvParams.emailField)) {
                    $('.wacv-email-invalid-notice').show();
                    error = true;
                }

                if (!_this.phoneValidation(phone) && parseInt(wacvParams.phoneField) && wacvParams.style === 'template-1') {
                    $('.wacv-phone-number-invalid-notice').show();
                    error = true;
                }

                if (!error) _this.importInfo();

            });

            $('.wacv-close-popup').on('click', function () { //, .wacv-modal-get-email
                wacvCookie.set('wacv_get_email', true, wacvParams.dismissDelay);//wacvParams.dismissDelay
                _this.popup.fadeOut(300);
                let events = $._data(_this.atcButton.get(0), 'events');
                let hasClick = events && events.click && events.click.length > 0 ? true : false;

                if (!wacvParams.immediate_cart_popup) {
                    if (_this.atcButton.is('a') && !hasClick) {
                        window.location.href = _this.atcButton.attr('href');
                    } else {
                        _this.atcButton.trigger('click');
                    }
                }
            });
        },

        emailValidation(email) {
            if (email === '' && wacvParams.info_require === '0') {
                return true;
            }
            email = email ? email.trim() : email;
            return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)
        },

        phoneValidation(phone) {
            if (phone === '' && wacvParams.phone_require === '0') {
                return true;
            }
            return /^\d{8,11}$/im.test(phone);
            // return /^[\+]?[(]?[0-9]{3}[)]?[-\s\.]?[0-9]{3}[-\s\.]?[0-9]{4,6}$/im.test(phone)
        },

        formatPhoneNumber(phone) {
            if (phone) {
                phone = phone.replace(/\(|\)|-|\.|\s|\+/gi, '');
                let firstChar = phone.slice(0, 1);
                phone = parseInt(firstChar) === 0 ? phone.slice(1) : phone;
            }

            return phone;
        },

        importInfo() {
            let _this = this;
            this.popup.fadeOut(200);

            let email = $('.wacv-popup-input-email').val(),
                countryCallingCode = $('.wacv-country-calling-code').val(),
                phone = _this.formatPhoneNumber($('.wacv-popup-input-phone-number').val()),
                phone_short = phone;

            phone = countryCallingCode + phone;

            let data = {
                action: 'wacv_get_info',
                nonce: wacvParams.nonce,
                billing_email: email,
                billing_phone: phone || '',
                billing_phone_short: phone_short || '',
                status: 'subscribe'
            };

            if (wacvFbCheckBox.checkedStt) data.user_ref = userRef;

            $.ajax({
                url: wacvParams.ajaxUrl,
                data: data,
                type: "post",
                xhrFields: {withCredentials: true},
                beforeSend: function () {
                    $('.wacv-add-to-cart-btn').addClass('loading');
                },
                success: function (res) {
                    wacvCookie.set('wacv_get_email', true);

                    let events = $._data(_this.atcButton.get(0), 'events');
                    let hasClick = events && events.click && events.click.length > 0 ? true : false;

                    if (!wacvParams.immediate_cart_popup) {
                        if (_this.atcButton.is('a') && !hasClick) {
                            window.location.href = _this.atcButton.attr('href');
                        } else {
                            _this.atcButton.trigger('click');
                        }
                    }
                },
                error: function (res) {
                    // console.log(res);
                }
            });
        },

        afterAjaxATC() {
            $(document).ajaxComplete(function (event, xhr, settings) {
                if (settings.url === "/?wc-ajax=add_to_cart" && wacvGetEmail.redirectAfterATC === true && wacvParams.redirect) {
                    window.location.replace(wacvParams.redirect);
                } else {
                    wacvGetEmail.showPopup();
                }
            });
        },

    };

    wacvGetEmail.init();
    if (wacvParams.immediate_cart_popup) {
        $('#wacv-modal').trigger('renderReCaptcha');
    }
});