/**
 * invoiceFields.js
 *
 * @author     alfiopiccione <alfio.piccione@gmail.com>
 * @copyright  Copyright (c) 2018, alfiopiccione
 * @license    http://opensource.org/licenses/gpl-2.0.php GPL v2
 *
 * Copyright (C) 2018 alfiopiccione <alfio.piccione@gmail.com>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */

;(
    function ($, wc_el_inv_invoice) {

        /**
         * Scripts init
         */
        function init()
        {
            console.log('[POP-WC] user level:', wc_el_inv_invoice.user_level);
            const wcBlockCheckout = window.wcSettings?.isCheckoutBlock || document.querySelector('.wc-block-checkout');

            /**
             * setCompanyLabel
             *
             * @since 6.3.2
             */
            function setCompanyLabel()
            {
                const companyBlock = document.getElementById('billing-company');
                // Replace companyBlock label
                if (wcBlockCheckout && companyBlock) {
                    var companyBlockLabel = companyBlock.nextElementSibling;
                    companyBlockLabel.innerText = wc_el_inv_invoice.company_label
                }
            }

            /**
             * Init Select2
             *
             * @since 1.0.0
             *
             * @returns {boolean}
             */
            function initSelect2()
            {
                if (wcBlockCheckout) {
                    return false;
                }

                var invoiceType = document.getElementById('billing_invoice_type');
                if (!invoiceType) {
                    return false;
                }

                if ($(invoiceType).data('select2')) {
                    return false;
                }

                if (typeof $(invoiceType).select2 !== "undefined") {
                    $(invoiceType).select2(
                        {
                            minimumResultsForSearch: 3
                        }
                    );
                }

                var choiceType = document.getElementById('billing_choice_type');
                if (!choiceType) {
                    return false;
                }

                if ($(choiceType).data('select2')) {
                    return false;
                }

                if (typeof $(choiceType).select2 !== "undefined") {
                    $(choiceType).select2(
                        {
                            minimumResultsForSearch: 3
                        }
                    );
                }
            }

            /**
             * Clone Vat in tax code for only company
             * @returns {boolean}
             */
            function cloneValueVat()
            {
                if (wcBlockCheckout) {
                    return false;
                }

                var invoiceType = document.getElementById('billing_invoice_type');
                var country = document.getElementById('billing_country');
                var invoiceVat = document.getElementById('billing_vat_number');
                var invoiceTax = document.getElementById('billing_tax_code');

                // Return if tax code is disabled
                if ('on' === wc_el_inv_invoice.disable_cf) {
                    return false;
                }

                if (!invoiceVat && !invoiceTax) {
                    return false;
                }

                if (invoiceVat) {
                    invoiceVat.addEventListener('keyup', function (evt) {
                        if (invoiceType && 'company' !== invoiceType.value) {
                            return false;
                        }
                        invoiceTax.value = this.value;
                    })
                }
            }

            /**
             * Set Required
             *
             * @since 1.0.0
             *
             * @returns {boolean}
             */
            function clearTaxCodeValidationState(taxCode)
            {
                if (!taxCode) {
                    return;
                }

                taxCode.setCustomValidity('');

                var cfMessage = taxCode.nextElementSibling;
                if (cfMessage && cfMessage.classList.contains('no-valid-cf')) {
                    cfMessage.remove();
                }
            }

            function setRequired()
            {
                if (wcBlockCheckout) {
                    const interval = setInterval(() => {
                        var invoiceType = document.getElementById('billing_invoice_type');
                        var country = document.getElementById('billing-country');

                        if (!invoiceType) {
                            invoiceType = document.querySelectorAll('#billing_invoice_type_field.form-radio_fields input[type=radio]');
                        }

                        if (!invoiceType || !country) {
                            return false;
                        }

                        if ('SELECT' === invoiceType.tagName) {
                            invoiceType.addEventListener('change', changeInvoiceTypeEventHandler);
                        } else {
                            invoiceType.forEach(function (radio) {
                                radio.addEventListener('click', function (evt) {
                                    changeInvoiceTypeEventHandler(evt)
                                })
                            })
                        }

                        country.addEventListener('change', changeCountryEventHandler);

                        clearInterval(interval);
                    }, 300);
                } else {
                    var invoiceType = document.getElementById('billing_invoice_type');
                    var country = document.getElementById('billing_country');
                    if (!invoiceType) {
                        invoiceType = document.querySelectorAll('#billing_invoice_type_field.form-radio_fields input[type=radio]');
                    }

                    if (!invoiceType || !country) {
                        return false;
                    }

                    if ('SELECT' === invoiceType.tagName) {
                        document.addEventListener('DOMContentLoaded', function () {
                            invoiceType.onchange = changeInvoiceTypeEventHandler;
                        }, false);
                    } else {
                        invoiceType.forEach(function (radio) {
                            radio.addEventListener('click', function (evt) {
                                changeInvoiceTypeEventHandler(evt)
                            })
                        })
                    }

                    document.addEventListener('DOMContentLoaded', function () {
                        country.onchange = changeCountryEventHandler;
                    }, false);
                }
            }

            /**
             * Change Country Handler
             *
             * @since 1.0.0
             *
             * @param event
             */
            function changeCountryEventHandler(event)
            {
                var country = event.target.value;
                var invoiceTypeSelect = document.getElementById('billing_invoice_type');
                var invoiceTypeRadios = document.querySelectorAll('#billing_invoice_type_field.form-radio_fields input[type=radio]');
                var choiceTypeSelect = document.getElementById('billing_choice_type');
                var choiceTypeRadios = document.querySelectorAll('#billing_choice_type_field.form-radio_fields input[type=radio]');

                // Toggle fields based on choice type (handle select or radios safely)
                if (choiceTypeSelect) {
                    toggleFieldsDisplay(choiceTypeSelect.value || '', event);
                } else if (choiceTypeRadios.length) {
                    var currentChoiceTypeValue = null;
                    choiceTypeRadios.forEach(function (radio) {
                        if (radio.checked) {
                            currentChoiceTypeValue = radio.value;
                        }
                    });
                    if (currentChoiceTypeValue) {
                        toggleFieldsDisplay(currentChoiceTypeValue, event);
                    }
                }

                // Work out current invoice type value
                var invoiceTypeValue = null;
                if (invoiceTypeSelect) {
                    invoiceTypeValue = invoiceTypeSelect.value;
                } else if (invoiceTypeRadios.length) {
                    invoiceTypeRadios.forEach(function (radio) {
                        if (radio.checked) {
                            invoiceTypeValue = radio.value;
                        }
                    });
                }

                if (!invoiceTypeValue) {
                    console.log('[POP-WC] changeCountryEventHandler: missing invoice type value, aborting.');
                    return false;
                }

                if ('IT' !== country) {
                    switchTypeNoIT(invoiceTypeValue, event);
                } else {
                    switchType(invoiceTypeValue, event);
                }
            }

            /**
             * Change Invoice Type Handler
             *
             * @since 1.0.0
             *
             * @param event
             */
            function changeInvoiceTypeEventHandler(event)
            {
                var country = document.getElementById('billing_country');
                if (wcBlockCheckout) {
                    country = document.getElementById('billing-country');
                }

                var type = event.target.value;

                // IT country and not required fields and country is in UE
                if (country && 'IT' === country.value &&
                    -1 !== wc_el_inv_invoice.eu_vat_country.indexOf(country.value)
                ) {
                    switchType(type, event);
                } else {
                    switchTypeNoIT(type, event)
                }
            }

            /**
             * Switch Country
             *
             * @param country
             * @param type
             * @param event
             */
            function switchCountry(country, type, event)
            {
                if ('IT' !== country) {
                    switchTypeNoIT(type, event);
                } else {
                    switchType(type, event);
                }
            }

            /**
             * Switch No IT type
             * @param type
             * @param ev
             */
            function switchTypeNoIT(type, ev)
            {
                var country = document.getElementById('billing_country');
                if (wcBlockCheckout) {
                    country = document.getElementById('billing-country');
                }

                var choiceTypeField = document.getElementById('billing_choice_type_field');
                var invoiceTypeField = document.getElementById('billing_invoice_type_field');
                var choiceTypeFieldLabel = document.querySelector('#billing_choice_type_field label[for*="billing_choice_type"]');
                var invoiceTypeFieldLabel = document.querySelector('#billing_invoice_type_field label[for*="billing_invoice_type"]');

                if (wcBlockCheckout) {
                    if (choiceTypeField) {
                        choiceTypeFieldLabel = choiceTypeField.querySelector('.components-base-control__label');
                    }
                    invoiceTypeFieldLabel = invoiceTypeField.querySelector('.components-base-control__label');
                }

                var sdi = document.getElementById('billing_sdi_type');
                var sdiField = document.getElementById('billing_sdi_type_field');
                var sdiLabel = document.querySelector('#billing_sdi_type_field label[for*="billing_sdi_type"]');
                if (sdiLabel) {
                    var sdiAbbr = sdiLabel.firstElementChild;
                }

                if (wcBlockCheckout) {
                    if (sdiField) {
                        sdiLabel = sdiField.querySelector('.components-base-control__label');
                    }
                    sdiAbbr = false;
                }

                var vat = document.getElementById('billing_vat_number');
                var vatField = document.getElementById('billing_vat_number_field');
                var vatLabel = document.querySelector('#billing_vat_number_field label[for="billing_vat_number"]');
                if (vatLabel) {
                    var vatAbbr = vatLabel.firstElementChild;
                }

                if (wcBlockCheckout) {
                    vatLabel = vatField.querySelector('.components-base-control__label');
                    vatAbbr = false;
                }

                var taxCode = document.getElementById('billing_tax_code');
                var taxCodeField = document.getElementById('billing_tax_code_field');
                var taxCodeLabel = document.querySelector('#billing_tax_code_field label[for="billing_tax_code"]');
                if (taxCode) {
                    if (taxCodeLabel) {
                        var taxCodeAbbr = taxCodeLabel.firstElementChild;
                    }

                    if (wcBlockCheckout) {
                        if (taxCodeField) {
                            taxCodeLabel = taxCodeField.querySelector('.components-base-control__label');
                        }
                        taxCodeAbbr = false;
                    }

                    clearTaxCodeValidationState(taxCode);
                }

                var choiceType = document.getElementById('billing_choice_type');
                var currentChoiceTypeValue = null;
                if (!choiceType) {
                    var choiceTypeRadio = document.querySelectorAll('#billing_choice_type_field.form-radio_fields input[type=radio]');
                    choiceTypeRadio.forEach(function (radio) {
                        if (radio.checked) {
                            currentChoiceTypeValue = radio.value;
                        }
                    })
                }

                // Sdi not required for no IT country
                if (sdiField) {
                    // SDI
                    sdiField.style.display = 'none';
                    sdiField.classList.remove('validate-required');
                    if (sdiAbbr) {
                        sdiAbbr.classList.remove('required');
                        sdiAbbr.classList.add('optional');
                        sdiAbbr.innerText = '(' + wc_el_inv_invoice.not_required_text + ')';
                        sdiAbbr.outerHTML = sdiAbbr.outerHTML.replace(/abbr/g, "span");
                    }
                    sdi.removeAttribute('required');
                    sdi.value = '';
                }

                // Reset value on change
                if ('change' === ev.type) {
                    if (sdi) {
                        sdi.value = '';
                    }
                    if (vat) {
                        vat.value = '';
                    }
                    if (taxCode) {
                        taxCode.value = '';
                    }
                }

                // No UE not required VAT and TAX
                if (country &&
                    'show' !== wc_el_inv_invoice.hide_outside_ue &&
                    -1 === wc_el_inv_invoice.eu_vat_country.indexOf(country.value)
                ) {
                    // Remove required billing_company
                    toggleBillingCompany('private');

                    if (choiceTypeField) {
                        choiceTypeField.style.display = 'none';
                        if (choiceTypeFieldLabel && choiceTypeFieldLabel.firstElementChild) {
                            choiceTypeFieldLabel.firstElementChild.remove();
                        }
                    }
                    if (invoiceTypeField) {
                        invoiceTypeField.style.display = 'none';
                        if (invoiceTypeFieldLabel && invoiceTypeFieldLabel.firstElementChild) {
                            invoiceTypeFieldLabel.firstElementChild.remove();
                        }
                    }

                    // TAX
                    if (taxCodeField) {
                        taxCodeField.style.display = 'none';
                        taxCode.value = ''; // reset value
                        if (taxCodeAbbr) {
                            taxCodeAbbr.classList.remove('required');
                        }
                        taxCodeField.classList.remove('validate-required');
                        taxCode.removeAttribute('required');
                    }

                    // VAT
                    if (vatField) {
                        vatField.style.display = 'none';
                        vat.value = ''; // reset value
                        if (vatAbbr) {
                            vatAbbr.classList.remove('required');
                        }
                        vatField.classList.remove('validate-required');
                        vat.removeAttribute('required');
                    }
                    return;
                } else {
                    if (choiceTypeField) {
                        if (choiceTypeFieldLabel && choiceTypeFieldLabel.firstElementChild) {
                            choiceTypeFieldLabel.firstElementChild.remove();
                        }
                        choiceTypeField.style.display = 'block';
                    }
                    if (invoiceTypeField) {
                        if (invoiceTypeFieldLabel && invoiceTypeFieldLabel.firstElementChild) {
                            invoiceTypeFieldLabel.firstElementChild.remove();
                        }
                        invoiceTypeField.style.display = 'block';
                    }
                }

                if ('1' === wc_el_inv_invoice.invoice_required) {
                    // Initialize display fields
                    if (choiceTypeField) {
                        choiceTypeField.style.display = 'block';
                        if (choiceTypeFieldLabel && choiceTypeFieldLabel.firstElementChild &&
                            'ABBR' !== choiceTypeFieldLabel.firstElementChild.nodeName &&
                            !choiceTypeFieldLabel.querySelector('.required')
                        ) {
                            $(choiceTypeFieldLabel).append('<abbr class="required">*</abbr>');
                        } else {
                            if (choiceTypeFieldLabel && null === choiceTypeFieldLabel.firstElementChild) {
                                $(choiceTypeFieldLabel).append('<abbr class="required">*</abbr>');
                            }
                        }
                    }
                    if (invoiceTypeField) {
                        invoiceTypeField.style.display = 'block';
                        if (invoiceTypeFieldLabel && invoiceTypeFieldLabel.firstElementChild &&
                            'ABBR' !== invoiceTypeFieldLabel.firstElementChild.nodeName &&
                            !invoiceTypeFieldLabel.querySelector('.required')
                        ) {
                            $(invoiceTypeFieldLabel).append('<abbr class="required">*</abbr>');
                        } else {
                            if (invoiceTypeFieldLabel && null === invoiceTypeFieldLabel.firstElementChild) {
                                $(invoiceTypeFieldLabel).append('<abbr class="required">*</abbr>');
                            }
                        }
                    }

                    // TAX
                    if (taxCodeField) {
                        taxCodeField.style.display = 'block';
                        taxCodeField.classList.add('validate-required');
                        if (taxCodeAbbr) {
                            taxCodeAbbr.classList.remove('optional');
                            taxCodeAbbr.classList.add('required');
                            taxCodeAbbr.innerText = '*';
                            taxCodeAbbr.setAttribute('title', wc_el_inv_invoice.required_text);
                            taxCodeAbbr.outerHTML = taxCodeAbbr.outerHTML.replace(/span/g, "abbr");
                        }
                        if (taxCode) {
                            taxCode.setAttribute('required', 'required');
                        }
                    }

                    // VAT
                    if (vatField) {
                        vatField.style.display = 'block';
                        vatField.classList.add('validate-required');
                        if (vatAbbr) {
                            vatAbbr.classList.remove('optional');
                            vatAbbr.classList.add('required');
                            vatAbbr.innerText = '*';
                            vatAbbr.setAttribute('title', wc_el_inv_invoice.required_text);
                            vatAbbr.outerHTML = vatAbbr.outerHTML.replace(/span/g, "abbr");
                        }
                        if (vat) {
                            vat.setAttribute('required', 'required');
                        }
                    }
                } else {

                    // TAX
                    if (taxCodeField) {
                        taxCodeField.classList.remove('validate-required');
                        if (taxCodeAbbr) {
                            taxCodeAbbr.classList.remove('required');
                            taxCodeAbbr.classList.add('optional');
                            taxCodeAbbr.innerText = '(' + wc_el_inv_invoice.not_required_text + ')';
                            taxCodeAbbr.outerHTML = taxCodeAbbr.outerHTML.replace(/abbr/g, "span");
                        }
                        if (taxCode) {
                            taxCode.removeAttribute('required');
                        }
                    }

                    // VAT
                    if (vatField) {
                        vatField.classList.remove('validate-required');
                        if (vatAbbr) {
                            vatAbbr.classList.remove('required');
                            vatAbbr.classList.add('optional');
                            vatAbbr.innerText = '(' + wc_el_inv_invoice.not_required_text + ')';
                            vatAbbr.outerHTML = vatAbbr.outerHTML.replace(/abbr/g, "span");
                        }
                        if (vat) {
                            vat.removeAttribute('required');
                        }
                    }
                }

                if (invoiceTypeField) {
                    invoiceTypeField.style.display = 'block';
                }

                if (currentChoiceTypeValue && 'receipt' === currentChoiceTypeValue) {
                    invoiceTypeField.style.display = 'none';
                }

                if (choiceType && 'receipt' === choiceType.value) {
                    invoiceTypeField.style.display = 'none';
                }

                if (currentChoiceTypeValue && 'receipt' === currentChoiceTypeValue ||
                    choiceType && 'receipt' === choiceType.value) {
                    type = '';
                }

                switch (type) {
                    default:
                    case 'private':
                        if (vat) {
                            // VAT
                            vatField.style.display = 'none';
                            if (vatAbbr) {
                                vatAbbr.classList.remove('required');
                                vatAbbr.classList.add('optional');
                            }
                            vatField.classList.remove('validate-required');
                            if (vatAbbr) {
                                vatAbbr.innerText = '(' + wc_el_inv_invoice.not_required_text + ')';
                                vatAbbr.innerHTML = vatAbbr.outerHTML.replace(/abbr/g, "span");
                            }
                            vat.removeAttribute('required');
                        }
                        if (taxCode) {
                            taxCodeField.style.display = 'block';
                        }
                        break;
                    case 'company':
                    case 'freelance':
                        if (vat) {
                            vatField.style.display = 'block';
                        }
                        if (taxCode && 'on' === wc_el_inv_invoice.disable_cf) {
                            // TAX
                            if (taxCodeField) {
                                taxCodeField.style.display = 'none';
                            }
                            if (taxCodeAbbr) {
                                taxCodeAbbr.classList.remove('required');
                                taxCodeAbbr.classList.add('optional');
                            }
                            if (taxCodeField) {
                                taxCodeField.classList.remove('validate-required');
                            }
                            if (taxCodeAbbr) {
                                taxCodeAbbr.innerText = '(' + wc_el_inv_invoice.not_required_text + ')';
                            }
                            if (vatAbbr && taxCodeAbbr) {
                                taxCodeAbbr.innerText = vatAbbr.outerHTML.replace(/abbr/g, "span");
                            }
                            if (taxCode) {
                                taxCode.removeAttribute('required');
                            }
                        }
                        break;
                    case '':
                        if (taxCodeField) {
                            taxCodeField.style.display = 'none';
                        }
                        if (sdiField) {
                            sdiField.style.display = 'none';
                        }
                        if (vatField) {
                            vatField.style.display = 'none';
                        }
                        break;
                }

                if (taxCode && type !== 'private' && type !== 'company' && type !== 'freelance') {
                    clearTaxCodeValidationState(taxCode);
                }

                // Toggle billing company by custom type
                toggleBillingCompany(type);
            }

            /**
             * toggleBillingCompany
             * Toggle billing company by custom type
             *
             * @since 4.4.0
             */
            function toggleBillingCompany(type)
            {
                var companyFiled = document.getElementById('billing_company');
                if (wcBlockCheckout) {
                    companyFiled = document.getElementById('billing-company');
                }

                if (companyFiled) {
                    console.log('[POP-WC] toggleBillingCompany');
                    var companyFieldWrap = companyFiled.closest('p');
                    var companyLabel = null;
                    var companySpan = null;
                    var abbrCompany = null;
                    if (companyFieldWrap) {
                        companyLabel = companyFieldWrap.querySelector('label');
                        if (companyLabel) {
                            abbrCompany = companyLabel.querySelector('.required');
                            companySpan = companyFieldWrap.querySelector('label .optional');
                        }

                        if ('company' === type) {
                            companyFiled.setAttribute('required', 'required');
                            companyFieldWrap.classList.add('validate-required');
                            if (companySpan) {
                                companySpan.style.display = 'none';
                            }
                            if (!abbrCompany && companyLabel) {
                                companyLabel.insertAdjacentHTML('beforeend', '<abbr class="required">*</abbr>');
                            }
                        } else {
                            companyFiled.removeAttribute('required');
                            companyFieldWrap.classList.remove('validate-required');
                            if (companySpan) {
                                companySpan.style.display = 'inline';
                            }
                            if (abbrCompany) {
                                abbrCompany.remove();
                            }
                        }
                    }
                }
            }

            /**
             * Switch Type and set args in input
             *
             * @since 1.0.0
             *
             * @param type
             * @param ev
             */
            function switchType(type, ev)
            {
                var country = document.getElementById('billing_country');
                if (wcBlockCheckout) {
                    country = document.getElementById('billing-country');
                }

                var choiceTypeField = document.getElementById('billing_choice_type_field');
                var invoiceTypeField = document.getElementById('billing_invoice_type_field');
                var choiceTypeFieldLabel = document.querySelector('#billing_choice_type_field label[for*="billing_choice_type"]');
                var invoiceTypeFieldLabel = document.querySelector('#billing_invoice_type_field label[for*="billing_invoice_type"]');
                if (wcBlockCheckout) {
                    if (choiceTypeField) {
                        choiceTypeFieldLabel = choiceTypeField.querySelector('.components-base-control__label');
                    }
                    invoiceTypeFieldLabel = invoiceTypeField.querySelector('.components-base-control__label');
                }

                var choiceType = document.getElementById('billing_choice_type');
                if (!choiceType) {
                    var choiceType = document.querySelectorAll('#billing_choice_type_field.form-radio_fields input[type=radio]');
                }
                var sdi = document.getElementById('billing_sdi_type');
                var sdiField = document.getElementById('billing_sdi_type_field');
                var sdiInput = document.getElementById('billing_sdi_type');
                var sdiLabel = document.querySelector('#billing_sdi_type_field label[for="billing_sdi_type"]');
                var sdiDesc = document.querySelector('#billing_sdi_type_field #billing_sdi_type-description');
                if (sdi && sdiLabel) {
                    var sdiAbbr = sdiLabel.firstElementChild;
                }

                if (wcBlockCheckout) {
                    if (sdiField) {
                        sdiLabel = sdiField.querySelector('.components-base-control__label');
                    }
                    sdiAbbr = false;
                }

                var vat = document.getElementById('billing_vat_number');
                var vatField = document.getElementById('billing_vat_number_field');
                var vatLabel = document.querySelector('#billing_vat_number_field label[for="billing_vat_number"]');
                if (vatLabel) {
                    var vatAbbr = vatLabel.firstElementChild;
                }

                if (wcBlockCheckout) {
                    vatLabel = vatField.querySelector('.components-base-control__label');
                    vatAbbr = false;
                }

                var taxCode = document.getElementById('billing_tax_code');
                var taxCodeField = document.getElementById('billing_tax_code_field');
                var taxCodeLabel = document.querySelector('#billing_tax_code_field label[for="billing_tax_code"]');

                if (taxCode && taxCodeLabel) {
                    var taxCodeAbbr = taxCodeLabel.firstElementChild;
                }

                if (wcBlockCheckout) {
                    if (taxCodeField) {
                        taxCodeLabel = taxCodeField.querySelector('.components-base-control__label');
                    }
                    taxCodeAbbr = false;
                }

                // No UE check
                if (-1 === wc_el_inv_invoice.eu_vat_country.indexOf(country.value)) {
                    return;
                }

                // No IT check
                if ('IT' !== country.value) {
                    return;
                }

                // Reset value on change
                if ('change' === ev.type) {
                    if (sdi) {
                        sdi.value = '';
                    }
                    if (vat) {
                        vat.value = '';
                    }
                    if (taxCode) {
                        taxCode.value = '';
                    }
                }

                // Initialize display fields
                if (choiceTypeField) {
                    choiceTypeField.style.display = 'block';
                    if (choiceTypeFieldLabel && choiceTypeFieldLabel.firstElementChild &&
                        'ABBR' !== choiceTypeFieldLabel.firstElementChild.nodeName &&
                        !choiceTypeFieldLabel.querySelector('.required')
                    ) {
                        $(choiceTypeFieldLabel).append('<abbr class="required">*</abbr>');
                    } else {
                        if (choiceTypeFieldLabel && null === choiceTypeFieldLabel.firstElementChild) {
                            $(choiceTypeFieldLabel).append('<abbr class="required">*</abbr>');
                        }
                    }
                }

                if (invoiceTypeField) {
                    invoiceTypeField.style.display = 'block';
                    if (invoiceTypeFieldLabel && invoiceTypeFieldLabel.firstElementChild &&
                        'ABBR' !== invoiceTypeFieldLabel.firstElementChild.nodeName &&
                        !invoiceTypeFieldLabel.querySelector('.required')
                    ) {
                        $(invoiceTypeFieldLabel).append('<abbr class="required">*</abbr>');
                    } else {
                        if (invoiceTypeFieldLabel && null === invoiceTypeFieldLabel.firstElementChild) {
                            $(invoiceTypeFieldLabel).append('<abbr class="required">*</abbr>');
                        }
                    }
                }

                if (taxCodeField) {
                    taxCodeField.style.display = 'block';
                }
                if (vatField) {
                    vatField.style.display = 'block';
                }

                switch (type) {
                    default:
                    case 'private':
                        // TAX-CODE
                        if (taxCode) {
                            if (country &&
                                'IT' === country.value &&
                                taxCode &&
                                'on' === wc_el_inv_invoice.active_js_cf_check
                            ) {
                                cfCheck();
                                taxCode.dispatchEvent(new Event('change'));
                            }

                            taxCodeField.style.display = 'block';
                            if (taxCodeAbbr) {
                                taxCodeAbbr.classList.remove('optional');
                                taxCodeAbbr.classList.add('required');
                            }
                            taxCodeField.classList.add('validate-required');
                            if (taxCodeAbbr) {
                                taxCodeAbbr.innerText = '*';
                                taxCodeAbbr.outerHTML = taxCodeAbbr.outerHTML.replace(/span/g, "abbr");
                            }
                            taxCode.setAttribute('required', 'required');
                        }
                        // SDI check
                        if (sdiField) {
                            // SDI
                            sdiField.style.display = 'none';
                            sdiField.classList.remove('validate-required');
                            sdi.removeAttribute('required');
                            sdi.value = ''; // reset value
                            if (sdiAbbr) {
                                sdiAbbr.classList.remove('required');
                                sdiAbbr.classList.add('optional');
                                sdiAbbr.innerText = '(' + wc_el_inv_invoice.not_required_text + ')';
                                sdiAbbr.outerHTML = sdiAbbr.outerHTML.replace(/abbr/g, "span");
                            }
                        }

                        // VAT
                        if (vatField) {
                            vatField.style.display = 'none';
                            vatField.classList.remove('validate-required');
                            if (vatAbbr) {
                                vatAbbr.classList.remove('required');
                                vatAbbr.classList.add('optional');
                                vatAbbr.innerText = '(' + wc_el_inv_invoice.not_required_text + ')';
                                vatAbbr.outerHTML = vatAbbr.outerHTML.replace(/abbr/g, "span");
                            }
                            if (vat) {
                                vat.removeAttribute('required');
                            }
                        }

                        break;
                    case 'company':
                    case 'freelance':
                        // SDI check
                        if (sdiField) {
                            if ('on' !== wc_el_inv_invoice.disable_pec_sdi) {
                                // SDI
                                sdiField.style.display = 'block';
                                sdiField.classList.add('validate-required');
                                if (sdiAbbr) {
                                    sdiAbbr.classList.remove('optional');
                                    sdiAbbr.classList.add('required');
                                    sdiAbbr.innerText = '*';
                                    sdiAbbr.setAttribute('title', wc_el_inv_invoice.required_text);
                                    sdiAbbr.outerHTML = sdiAbbr.outerHTML.replace(/span/g, "abbr");
                                }
                                sdi.setAttribute('required', 'required');
                                if (sdiDesc) {
                                    sdiDesc.innerText = wc_el_inv_invoice.sdi_description;
                                }
                                sdiInput.placeholder = wc_el_inv_invoice.sdi_placeholder;
                            } else {
                                sdiField.style.display = 'none';
                                sdi.removeAttribute('required');
                            }
                        }

                        // VAT
                        if (vatField) {
                            vatField.style.display = 'block';
                            vatField.classList.add('validate-required');
                            if (vatAbbr) {
                                vatAbbr.classList.remove('optional');
                                vatAbbr.classList.add('required');
                                vatAbbr.innerText = '*';
                                vatAbbr.setAttribute('title', wc_el_inv_invoice.required_text);
                                vatAbbr.outerHTML = vatAbbr.outerHTML.replace(/span/g, "abbr");
                            }
                            if (vat) {
                                vat.setAttribute('required', 'required');
                            }
                        }

                        // TAX-CODE
                        if (taxCode && 'on' !== wc_el_inv_invoice.disable_cf) {
                            taxCodeField.style.display = 'block';
                            taxCodeField.classList.add('validate-required');

                            if (taxCodeAbbr) {
                                taxCodeAbbr.classList.remove('optional');
                                taxCodeAbbr.classList.add('required');
                                taxCodeAbbr.innerText = '*';
                                taxCodeAbbr.setAttribute('title', wc_el_inv_invoice.required_text);
                                taxCodeAbbr.outerHTML = taxCodeAbbr.outerHTML.replace(/span/g, "abbr");
                            }
                            taxCode.setAttribute('required', 'required');
                        } else if (taxCode && 'on' === wc_el_inv_invoice.disable_cf) {
                            if (taxCodeField) {
                                taxCodeField.style.display = 'none';
                                taxCode.removeAttribute('required');
                            }
                            clearTaxCodeValidationState(taxCode);
                        }

                        if (taxCode) {
                            clearTaxCodeValidationState(taxCode);
                        }
                        break;
                    case '':
                        if (taxCodeField) {
                            taxCodeField.style.display = 'none';
                        }
                        if (sdiField) {
                            sdiField.style.display = 'none';
                        }
                        if (vatField) {
                            vatField.style.display = 'none';
                        }
                        break;
                }

                if (taxCode && type !== 'private' && type !== 'company' && type !== 'freelance') {
                    clearTaxCodeValidationState(taxCode);
                }

                // Logic for displaying the fields if set to "receipt" at the change of state.
                if ('SELECT' === choiceType.tagName) {
                    var currentChoiceType = choiceType.options[choiceType.selectedIndex];
                    if (currentChoiceType && 'receipt' === currentChoiceType.value) {
                        toggleFieldsDisplay(currentChoiceType.value, ev);
                    }
                } else {
                    if (choiceType && choiceType.length) {
                        var currentChoiceTypeValue = null;
                        choiceType.forEach(function (radio) {
                            if (radio.checked) {
                                currentChoiceTypeValue = radio.value;
                            }
                        })
                        if (currentChoiceTypeValue && 'receipt' === currentChoiceTypeValue) {
                            toggleFieldsDisplay(currentChoiceTypeValue, ev);
                        }
                    }
                }

                // Toggle billing company by custom type
                toggleBillingCompany(type);
            }

            /**
             * Choice type
             * @param ev
             */
            function choiceType(ev)
            {
                var editAddress = document.querySelector('body.woocommerce-edit-address');
                var choiceType = document.getElementById('billing_choice_type');
                var choiceTypeRadio = document.querySelectorAll('#billing_choice_type_field.form-radio_fields input[type=radio]');

                // billing_choice_type radio
                if (!choiceType && choiceTypeRadio) {
                    // load
                    var choiceTypeRadioValue = '';
                    choiceTypeRadio.forEach(function (radio) {
                        if (radio.checked) {
                            choiceTypeRadioValue = radio.value;
                        }
                    })
                    console.log('[POP-WC] RADIO > choiceTypeRadioValue', choiceTypeRadioValue);
                    toggleFieldsDisplay(choiceTypeRadioValue, ev);
                    // Change
                    choiceTypeRadio.forEach(function (radio) {
                        radio.addEventListener('change', function (evt) {
                            toggleFieldsDisplay(this.value, evt);
                        })
                    })
                }

                initSelect2();

                // Remove optional text
                var choiceTypeLabel = document.querySelector('#billing_choice_type_field label[for="billing_choice_type"] span.optional');
                if (choiceTypeLabel) {
                    choiceTypeLabel.remove();
                }

                if (choiceType && 'load' === ev.type && !editAddress) {
                    toggleFieldsDisplay(choiceType.options[choiceType.selectedIndex].value, ev);
                }

                if (choiceType) {
                    $(choiceType).on('change', function (evt) {
                        toggleFieldsDisplay(this.value, evt);
                    });
                }

                if (editAddress) {
                    toggleFieldsDisplay('edit-address', ev);
                }
            }

            /**
             * Toggle Display fields
             *
             * @param type
             * @param ev
             */
            function toggleFieldsDisplay(type, ev)
            {
                var invoiceType = document.getElementById('billing_invoice_type');
                if (!invoiceType) {
                    invoiceType = document.querySelectorAll('#billing_invoice_type_field.form-radio_fields input[type=radio]');
                }
                var invoiceTypeField = document.getElementById('billing_invoice_type_field');
                var sdiField = document.getElementById('billing_sdi_type_field');
                var vatField = document.getElementById('billing_vat_number_field');
                var taxCodeField = document.getElementById('billing_tax_code_field');
                var sdi = document.getElementById('billing_sdi_type');
                var vat = document.getElementById('billing_vat_number');
                var taxCode = document.getElementById('billing_tax_code');

                console.log('[POP-WC] toggle:', type, 'event:', ev.type);

                switch (type) {
                    case'invoice':
                        var country = document.getElementById('billing_country');
                        if (wcBlockCheckout) {
                            country = document.getElementById('billing-country');
                        }

                        if ('SELECT' === invoiceType.tagName) {
                            // Check condition for display fields based on country and invoice type selected
                            if ('' === invoiceType.options[invoiceType.selectedIndex].value) {
                                invoiceTypeField.style.display = 'block';
                            } else {
                                invoiceTypeField.style.display = 'block';

                                if ('private' === invoiceType.options[invoiceType.selectedIndex].value) {
                                    if (taxCodeField) {
                                        taxCodeField.style.display = 'block';
                                    }
                                    if (type === 'load' || taxCode.value === 'XXXXXX00L00L000X') {
                                        taxCode.value = '';
                                    }

                                } else if ('company' === invoiceType.options[invoiceType.selectedIndex].value ||
                                           'freelance' === invoiceType.options[invoiceType.selectedIndex].value
                                ) {
                                    // Display and reset value
                                    if (vat) {
                                        vatField.style.display = 'block';
                                        if ('load' !== ev.type) {
                                            vat.value = '';
                                        }
                                    }
                                    // Display Only IT
                                    if ('IT' === country.value) {
                                        if (sdi) {
                                            sdiField.style.display = 'block';
                                            if ('load' !== ev.type) {
                                                sdi.value = '';
                                            }
                                        }
                                    }
                                    if (taxCode) {
                                        taxCodeField.style.display = 'block';
                                        if ('load' !== ev.type) {
                                            taxCode.value = '';
                                        }
                                    }
                                }

                                switchType(invoiceType.options[invoiceType.selectedIndex].value, ev);
                            }
                        } else {
                            if (!invoiceType.length) {
                                console.log('[POP-WC] toggleFieldsDisplay: invoiceType radios empty, aborting.');
                                return false;
                            }
                            var invoiceTypeValue = invoiceType[0].value;
                            invoiceType.forEach(function (radio) {
                                if (radio.checked) {
                                    invoiceTypeValue = radio.value;
                                }
                            })
                            console.log('[POP-WC] RADIO > invoiceTypeValue', invoiceTypeValue);
                            // Check condition for display fields based on country and invoice type selected
                            if ('' === invoiceTypeValue) {
                                invoiceTypeField.style.display = 'block';
                            } else {
                                invoiceTypeField.style.display = 'block';

                                if ('private' === invoiceTypeValue) {
                                    if (taxCodeField) {
                                        taxCodeField.style.display = 'block';
                                    }
                                    if (type === 'load' || taxCode.value === 'XXXXXX00L00L000X') {
                                        taxCode.value = '';
                                    }

                                } else if ('company' === invoiceTypeValue ||
                                           'freelance' === invoiceTypeValue
                                ) {
                                    // Display and reset value
                                    if (vat) {
                                        vatField.style.display = 'block';
                                        if ('load' !== ev.type) {
                                            vat.value = '';
                                        }
                                    }
                                    // Display Only IT
                                    if ('IT' === country.value) {
                                        if (sdi) {
                                            sdiField.style.display = 'block';
                                            if ('load' !== ev.type) {
                                                sdi.value = '';
                                            }
                                        }
                                    }
                                    if (taxCode) {
                                        taxCodeField.style.display = 'block';
                                        if ('load' !== ev.type) {
                                            taxCode.value = '';
                                        }
                                    }
                                }

                                switchType(invoiceTypeValue, ev);
                            }
                        }
                        break;
                    case'receipt':
                        // Reset billing company required
                        toggleBillingCompany(null);
                        // It serves as a discriminant to generate the receipt
                        // fake data to validate the fields
                        if (vat) {
                            vat.value = '11111111111';
                            vatField.style.display = 'none';
                        }
                        if (sdi) {
                            sdi.value = '1111111';
                            sdiField.style.display = 'none';
                        }
                        if (taxCode) {
                            taxCode.value = 'XXXXXX00L00L000X';
                            taxCodeField.style.display = 'none';
                            clearTaxCodeValidationState(taxCode);
                        }
                        invoiceTypeField.style.display = 'none';
                        break;
                    // Reset fields
                    case'reset':
                        // Reset billing company required
                        toggleBillingCompany(null);
                        if (vat) {
                            vat.value = '';
                        }
                        if (sdi) {
                            sdi.value = '';
                        }
                        if (taxCode) {
                            taxCode.value = '';
                            clearTaxCodeValidationState(taxCode);
                        }
                        break;
                    case 'edit-address':
                        // Support other plugin save fields
                        if (taxCode.value !== '') {
                            taxCodeField.style.display = 'block';
                        }
                        if (vat.value !== '') {
                            vatField.style.display = 'block';
                        }
                        if (sdi.value !== '') {
                            sdiField.style.display = 'block';
                        }
                        break
                    default:
                        break;
                }
            }

            /**
             * Vies check via ajax for default checkout
             */
            function viesCheckActions()
            {
                if (wcBlockCheckout) {
                    // Use block vies check function
                    return false
                }

                /**
                 * callViesCheck
                 * @param vatNumber
                 * @param taxCode
                 * @param invoiceType
                 * @param choiceType
                 * @param country
                 */
                function callViesCheck(vatNumber, taxCode, invoiceType, choiceType, country)
                {
                    console.log('[POP-WC] callViesCheck fetch:', country, choiceType, invoiceType, vatNumber, taxCode);
                    fetch(wc_el_inv_invoice.ajax_url, {
                        method: 'POST',
                        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                        body: new URLSearchParams({
                            action: 'popCheckoutViesCheck',
                            vat_number: vatNumber,
                            tax_code: taxCode,
                            invoice_type: invoiceType,
                            choice_type: choiceType,
                            country: country,
                        })
                    })
                        .then(response => response.json())
                        .then(data => {
                            console.log("[POP-WC] VIES response:", data);
                            var vatField = $('#billing_vat_number_field label');
                            var valid = $('#billing_vat_number_field label .valid_vies');
                            var notValid = $('#billing_vat_number_field label .not_valid_vies');
                            var viesTrigger = $('.order-total #wc_el_inv_vies_trigger');
                            if (viesTrigger.length !== 0) {
                                viesTrigger.remove();
                            }

                            if (valid.length !== 0) {
                                valid.remove();
                            }
                            if (notValid.length !== 0) {
                                notValid.remove();
                            }

                            if ('not_necessary' === data.data.vies) {
                                return;
                            }

                            if (data.success) {
                                vatField.append(' <small style="color:green;" class="valid_vies">' + data.data.message + '</small>');
                            } else {
                                vatField.append(' <small style="color:red;" class="not_valid_vies">' + data.data.message + '</small>');
                            }

                            $('body').trigger('update_checkout');
                        })
                        .catch(err => {
                            console.error("VIES fetch error:", err);
                        });
                }

                var viesDebounce;

                function triggerViesCheck()
                {
                    clearTimeout(viesDebounce);
                    viesDebounce = setTimeout(() => {
                        const vatNumber = $('#billing_vat_number').val()?.trim();
                        const taxCode = $('#billing_tax_code').val()?.trim();
                        const invoiceType = $('#billing_invoice_type').val()?.trim();
                        const choiceType = $('#billing_choice_type').val()?.trim();
                        const country = $('#billing_country').val()?.trim();

                        callViesCheck(vatNumber, taxCode, invoiceType, choiceType, country);
                    }, 300);
                }

                $('#billing_choice_type, #billing_invoice_type, #billing_country, #billing_vat_number, #billing_tax_code')
                    .on('change', triggerViesCheck);

                triggerViesCheck();
            }

            /**
             * Vies check via ajax for checkout block
             */
            function viesCheckCheckoutBlock()
            {
                if (!wcBlockCheckout) {
                    return;
                }

                (function ($) {
                    var debounceTimer;

                    // If requests are made too close together, the totals in the frontend are not guaranteed to be updated.
                    // However, on the server side, taxes will only be removed if necessary.
                    /**
                     * updateTotalsAfterVies
                     * @param viesData
                     * @returns {Promise<void>}
                     */
                    async function updateTotalsAfterVies(evt, viesData, vatNumber, country)
                    {
                        // Invalidate resolutions
                        wp.data.dispatch('wc/store/cart').invalidateResolution('getCartTotals');
                        wp.data.dispatch('wc/store/checkout').invalidateResolution('getCheckoutStatus');
                        // Wait for the store to recalculate the totals
                        const totals = await wp.data.resolveSelect('wc/store/cart').getCartTotals();
                        const checkoutStatus = await wp.data.resolveSelect('wc/store/checkout').getCheckoutStatus();

                        // Message
                        const label = $('#billing_vat_number_field label.components-base-control__label');
                        const message = $('<small class="message_vies" style="margin-left:10px;"></small>');
                        message.addClass(viesData.success ? 'valid' : 'not_valid');
                        message.text(viesData.data.message);
                        message.css('color', viesData.success ? 'green' : 'red');
                        label.append(message);

                        // Reset billing_tax_code to force totals to change in checkout
                        if (viesData.data.update_totals) {
                            const additionalFields = wp.data.select('wc/store/checkout').getAdditionalFields() || {};
                            wp.data.dispatch('wc/store/checkout').setAdditionalFields({
                                ...additionalFields,
                                billing_tax_code: ''
                            });
                        }

                        if ('dev' === wc_el_inv_invoice.mode) {
                            console.log('[POP-WC block] forceBatchRequest?', evt && evt.target && evt.target.id !== 'billing-country')
                        }
                        if (evt && evt.target && evt.target.id !== 'billing-country') {
                            forceBatchRequest();
                        }
                    }

                    function forceBatchRequest()
                    {
                        // Invalida cache dei resolver
                        wp.data.dispatch('wc/store/cart').invalidateResolution('getCartData');
                        wp.data.dispatch('wc/store/cart').invalidateResolution('getCartTotals');
                        wp.data.dispatch('wc/store/checkout').invalidateResolution('getCheckoutStatus');

                        // Force resolution → trigger fetch wc/store/v1/batch?_locale=site
                        return Promise.all([
                            wp.data.resolveSelect('wc/store/cart').getCartData(),
                            wp.data.resolveSelect('wc/store/cart').getCartTotals(),
                            wp.data.resolveSelect('wc/store/checkout').getCheckoutStatus()
                        ]).then(([cartData, cartTotals, checkoutStatus]) => {
                            if ('dev' === wc_el_inv_invoice.mode) {
                            console.log('[POP-WC block] Batch refresh completato:', {
                                    cartData,
                                    cartTotals,
                                    checkoutStatus
                                });
                            }
                            return {cartData, cartTotals, checkoutStatus};
                        }).catch(err => {
                            if ('dev' === wc_el_inv_invoice.mode) {
                                console.error('[POP block] Errore nel forzare batch request:', err);
                            }
                        });
                    }

                    /**
                     * callViesCheck
                     * @param vatNumber
                     * @param taxCode
                     * @param invoiceType
                     * @param choiceType
                     * @param country
                     */
                    function callViesCheck(evt, vatNumber, taxCode, invoiceType, choiceType, country)
                    {
                        if ('dev' === wc_el_inv_invoice.mode) {
                            console.log('[POP-WC block] vies fetch:', country, choiceType, invoiceType, vatNumber, taxCode);
                        }

                        fetch(wc_el_inv_invoice.ajax_url, {
                            method: 'POST',
                            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                            body: new URLSearchParams({
                                action: 'popCheckoutViesCheck',
                                vat_number: vatNumber,
                                tax_code: taxCode,
                                invoice_type: invoiceType,
                                choice_type: choiceType,
                                country: country,
                            })
                        })
                            .then(response => response.json())
                            .then(data => {
                                if ('dev' === wc_el_inv_invoice.mode) {
                                    console.log("[POP-WC block] vies response:", data);
                                }
                                const label = $('#billing_vat_number_field label.components-base-control__label');
                                const viesSpan = label.find('.message_vies');
                                if (viesSpan.length) {
                                    viesSpan.remove();
                                }

                                updateTotalsAfterVies(evt, data, vatNumber, country);
                            })
                            .catch(err => {
                                console.error("VIES fetch error:", err);
                            });
                    }

                    var viesDebounce;

                    function triggerViesCheck(evt)
                    {
                        clearTimeout(viesDebounce);
                        viesDebounce = setTimeout(() => {
                            const vatNumber = $('#billing_vat_number').val()?.trim();
                            const taxCode = $('#billing_tax_code').val()?.trim();
                            const invoiceType = $('#billing_invoice_type').val()?.trim();
                            const choiceType = $('#billing_choice_type').val()?.trim();
                            const country = $('#billing-country').val()?.trim();

                            callViesCheck(evt, vatNumber, taxCode, invoiceType, choiceType, country);
                        }, 300);
                    }

                    $('#billing_choice_type, #billing_invoice_type, #billing-country, #billing_vat_number, #billing_tax_code')
                        .on('change blur', triggerViesCheck);

                    triggerViesCheck();
                })(jQuery);
            }

            /**
             * CF check
             */
            function cfCheck()
            {
                var name = document.getElementById('billing_first_name');
                var lastName = document.getElementById('billing_last_name');
                if (wcBlockCheckout) {
                    name = document.getElementById('billing-first_name');
                    lastName = document.getElementById('billing-last_name');
                }

                var taxCode = document.getElementById('billing_tax_code');
                var invoiceType = document.getElementById('billing_invoice_type');
                var checkCodeFinal = false;
                var computeInverse = {};

                // Reset on change name and last name
                $(name).on('change', function () {
                    taxCode.value = ''
                });
                $(lastName).on('change', function () {
                    taxCode.value = ''
                });

                // Tax code change
                $(taxCode).on('change', function () {
                    taxCode.setCustomValidity("");
                    taxCode.setCustomValidity("");
                    var CF = this.value.toUpperCase();
                    var checkCode = CodiceFiscale.check(CF);

                    if ('private' === invoiceType.options[invoiceType.selectedIndex].value) {
                        // Final check
                        if (this.value.length <= 16 && true === checkCode) {
                            computeInverse = CodiceFiscale.computeInverse(CF);
                            var args = {
                                name: name.value,
                                surname: lastName.value,
                                gender: computeInverse.gender,
                                birthday: computeInverse.birthday,
                                birthplace: computeInverse.birthplace
                            };
                            var cfDataFinal = new CodiceFiscale(args);
                            console.log('[POP-WC] CodiceFiscale di ' + args.name + ' ' + args.surname, cfDataFinal);
                            checkCodeFinal = (0 === cfDataFinal.code.indexOf(computeInverse.surname + computeInverse.name));
                        } else {
                            checkCodeFinal = false;
                        }
                        console.log('[POP-WC] Check CF:', checkCodeFinal);
                        if (!checkCodeFinal) {
                            setTimeout(function () {
                                var cfMessage = taxCode.nextElementSibling;
                                if (cfMessage) {
                                    cfMessage.remove();
                                }

                                //taxCode.value = '';
                                taxCode.insertAdjacentHTML('afterend',
                                    "<p class='no-valid-cf'><small>(*) <b>" + CF + "</b> " + wc_el_inv_invoice.invalid_tax_code + "</small></p>"
                                );
                                taxCode.setCustomValidity(wc_el_inv_invoice.pop_invalid_tax_code);
                            }, 200);
                            return false;
                        } else {
                            clearTaxCodeValidationState(taxCode);
                            return true;
                        }
                    } else {
                        clearTaxCodeValidationState(taxCode);
                    }
                })
            }

            /**
             * initializedScripts
             * @param ev
             * @returns {boolean}
             */
            function initializedScripts(ev)
            {
                // Default
                var invoiceType = document.getElementById('billing_invoice_type');
                var country = document.getElementById('billing_country');
                if (wcBlockCheckout) {
                    country = document.getElementById('billing-country');
                }

                var taxCode = document.getElementById('billing_tax_code');

                if (!invoiceType) {
                    invoiceType = document.querySelectorAll('#billing_invoice_type_field.form-radio_fields input[type=radio]');
                }

                if (!invoiceType) {
                    return false;
                }

                if (!country) {
                    return false;
                }

                if (country) {
                    var readOnly = country.getAttribute('readonly');
                    if (readOnly && 'readonly' === readOnly) {
                        country.closest('#billing_country_field').style.display = 'none';
                    }
                }

                // Remove optional label
                var invoiceTypeLabelOption = document.querySelector('label[for="billing_invoice_type"] .optional');
                if (invoiceTypeLabelOption) {
                    invoiceTypeLabelOption.remove();
                }

                // Required and in not UE country
                if ('SELECT' === invoiceType.tagName) {
                    if (country &&
                        'IT' === country.value &&
                        -1 !== wc_el_inv_invoice.eu_vat_country.indexOf(country.value)
                    ) {
                        if (invoiceType.tagName.toLowerCase() === 'select') {
                            switchType(invoiceType.options[invoiceType.selectedIndex].value, ev);
                        } else if (invoiceType.tagName.toLowerCase() === 'input') {
                            switchType(invoiceType.value, ev);
                        }
                    } else {
                        if (invoiceType.tagName.toLowerCase() === 'select') {
                            switchTypeNoIT(invoiceType.options[invoiceType.selectedIndex].value, ev);
                        } else if (invoiceType.tagName.toLowerCase() === 'input') {
                            switchTypeNoIT(invoiceType.value, ev);
                        }
                    }

                    // Switch country
                    if (country) {
                        switchCountry(country.value, invoiceType.value, ev);
                    }

                } else {
                    if (!invoiceType || !invoiceType.length || !invoiceType[0]) {
                        return false;
                    }
                    if (country &&
                        'IT' === country.value &&
                        -1 !== wc_el_inv_invoice.eu_vat_country.indexOf(country.value)
                    ) {
                        switchType(invoiceType[0].value, ev);
                    } else {
                        switchTypeNoIT(invoiceType[0].value, ev);
                    }

                    // Switch country
                    if (country) {
                        switchCountry(country.value, invoiceType[0].value, ev);
                    }
                }

                choiceType(ev);
                initSelect2();
                cloneValueVat();
                if ('free' !== wc_el_inv_invoice.user_level) {
                    viesCheckActions();
                    viesCheckCheckoutBlock();
                }
                setCompanyLabel();

                // By activating the control of the Fiscal Code only for the "Private" customer type, the value
                // of the fiscal code will be validated through a correspondence
                // between the Fiscal Code and the Name and Surname fields
                if (country &&
                    'IT' === country.value &&
                    taxCode &&
                    'on' === wc_el_inv_invoice.active_js_cf_check
                ) {
                    cfCheck();
                    taxCode.dispatchEvent(new Event('change'));
                }
            }

            /**
             * loadEvent
             */
            function loadEvent(ev)
            {
                if (wcBlockCheckout) {
                    const interval = setInterval(() => {
                        initializedScripts(ev)
                        // Set required fields
                        setRequired();
                        clearInterval(interval);
                    }, 300);
                } else {
                    initializedScripts(ev);
                }
            }

            if (!wcBlockCheckout) {
                // Set required fields
                setRequired();
            }

            // Load listener
            window.addEventListener('load', loadEvent);
        }

        if (document.querySelector('.wc-block-checkout')) {
            document.addEventListener('DOMContentLoaded', () => {
                // Watch the DOM until .wc-block-checkout appears
                const observer = new MutationObserver(function (mutations, obs) {
                    if (document.querySelector('.pop-checkout-fields')) {
                        obs.disconnect();
                        init();
                    }
                });
                observer.observe(document.body, {childList: true, subtree: true});
            });
        } else {
            // classic checkout: run init immediately
            init();
        }

    }(jQuery, window.wc_el_inv_invoice)
);
