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

    const App = {
        init() {
            if (
                '1' === wacv_localize.enable_gdpr &&
                !$('#wacv_checkout_gdpr_block').length
            ) {
                $('input#billing_email').after(
                    "<span id='wacv_checkout_gdpr_block'> <span style='font-size: x-small'> " +
                    wacv_localize.checkout_gdpr_message +
                    " <a style='cursor: pointer' id='wacv_checkout_gdpr_cancel'> " +
                    wacv_localize.checkout_gdpr_cancel +
                    ' </a></span></span>'
                );
            }
            $('#wacv_checkout_gdpr_cancel').on('click', function () {
                App.set_cookie();
            });

            if (wacv_localize.direct_trigger) {
                $('input#billing_email').on('change', function () {
                    var pattern = /^(([^<>()[\]\\.,;:\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,}))$/;

                    if (pattern.test($(this).val())) {
                        wacv_send_get_guest_info();
                    }
                });

                $('input#billing_phone').on('change', function () {
                    wacv_send_get_guest_info();
                });
            } else {
                $(document).on('change', 'input#billing_email, input#email', function () {
                    var pattern = /^(([^<>()[\]\\.,;:\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,}))$/;
                    if (pattern.test($(this).val())) {
                        wacv_send_get_guest_info();
                    }
                });

                $(document).on('change', 'input#billing_phone, input#shipping-phone', function () {
                    wacv_send_get_guest_info();
                });
            }

            function wacv_send_get_guest_info() {
                let data = $('form.wc-block-components-form').serialize();
                if (data !== '') {
                    let $form = $('form.wc-block-components-form');
                    data = {
                        action: 'wacv_get_info',
                        billing_email: $form.find('input#email').val(),
                        shipping_first_name: $form.find('input#shipping-first_name').val(),
                        shipping_last_name: $form.find('input#shipping-last_name').val(),
                        shipping_address_1: $form.find('input#shipping-address_1').val(),
                        shipping_country: $form.find('#shipping-country input').val(),
                        shipping_city: $form.find('input#shipping-city').val(),
                        shipping_state: $form.find('#shipping-state input').val(),
                        shipping_postcode: $form.find('input#shipping-postcode').val(),
                        nonce: wacv_localize.nonce,
                    };
                    if ($('.wc-block-checkout__billing-fields').length) {
                        let billing = {
                            billing_first_name: $form.find('input#billing-first_name').val(),
                            billing_last_name: $form.find('input#billing-last_name').val(),
                            billing_address_1: $form.find('input#billing-address_1').val(),
                            billing_phone: $form.find('input#shipping-phone').val(),
                            billing_country: $form.find('#billing-country input').val(),
                            billing_city: $form.find('input#billing-city').val(),
                            billing_state: $form.find('#billing-state input').val(),
                            billing_postcode: $form.find('input#billing-postcode').val(),
                        };
                        $.extend(data, billing);
                    }
                } else {
                    data = $('form.woocommerce-checkout').serialize() + '&nonce=' + wacv_localize.nonce + '&action=wacv_get_info';
                }
                $.ajax({
                    url: wacv_localize.ajax_url,
                    data: data,
                    type: 'POST',
                    xhrFields: {
                        withCredentials: true
                    },
                    success: function (res) {
                    }
                });
            }

        },
        wait_element(selector) {
            return new Promise((resolve) => {
                if (document.querySelector(selector)) {
                    return resolve(document.querySelector(selector));
                }

                const observer = new MutationObserver(mutations => {
                    if (document.querySelector(selector)) {
                        observer.disconnect();
                        resolve(document.querySelector(selector));
                    }
                });

                observer.observe(document.body, {
                    childList: true,
                    subtree: true
                });
            });
        },
        load_guest_info() {
            if (typeof wc == 'object') {
                let checkout_form = $('form.wc-block-checkout__form');
                if (checkout_form.length && wacv_localize.guest_info) {
                    const guest = wacv_localize.guest_info;
                    const input_fields = ['email', 'first_name', 'last_name', 'address_1', 'address_2', 'city', 'postcode', 'phone'];
                    const select_fields = ['country', 'state'];
                    for (let field of input_fields) {
                        this.wait_element(`.wc-block-components-address-form__${field}`).then(element => {
                            setTimeout(() => {
                                let value = '';
                                if (field === 'email' || field === 'phone') {
                                    value = guest[`billing_${field}`] ? guest[`billing_${field}`] : '';
                                } else {
                                    value = guest[`shipping_${field}`] ? guest[`shipping_${field}`] : '';
                                }
                                if (!!value) {
                                    $(element).addClass('is-active');
                                    let input = element.querySelector('input');
                                    Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value").set.call(input, value);
                                    input.dispatchEvent(new Event("input", {bubbles: true}));
                                }
                            });
                        })
                    }
                    for (let field of select_fields) {
                        this.wait_element(`.wc-block-components-address-form__${field}`).then(element => {
                            let value = guest[`shipping_${field}`] ? guest[`shipping_${field}`] : '';
                            if (!!value) {
                                $(element).find('select').val(value);
                            }
                        });
                    }
                }
            }
        },
        set_cookie() {
            let data = 'nonce=' + wacv_localize.nonce + '&action=wacv_update_gdpr';

            jQuery.post(wacv_localize.ajax_url, data, function (response) {
                if (response.success) {
                    $('#wacv_checkout_gdpr_block').empty();
                }
            });
        }
    };

    App.init();
    App.load_guest_info();

    $(document).ajaxComplete(function (event, xhr, settings) {
        if (settings.url === "/?wc-ajax=viwcaio_get_checkout_form") {
            App.init();
        }
    });


});