var a = {

    \u0440: "a",

    \u010D: "c",

    \u0119: "e",

    \u0117: "e",

    \u012F: "i",

    \u0161: "s",

    \u0173: "u",

    \u016B: "u",

    \u017E: "z"

};



function transliterate(word) {

    return word.split('').map(function (char) {

        return a[char] || char;

    }).join("");

}

var timeout;
var timeout2;
var radio_control = 0;
function timedCount(){
    jQuery(function($) {
        setTimeout(function() {
            if ($(".wp-block-woocommerce-checkout-fields-block")[0]) {
                timeout = setTimeout(
                    function()
                    {
                        // $('.wc-block-components-checkbox__input').on('click', function() {
                        //     setTimeout(function() {
                        //         $.ajax({
                        //             url: '/wp-admin/admin-ajax.php',
                        //             type: 'post',
                        //             data: {
                        //                 action: 'checkout_blocks_hide_inputs_for_terminal'
                        //             },
                        //             success: function (response) {
                        //                 if(response == '1') {
                        //                     $('.wp-block-woocommerce-checkout-billing-address-block .wc-block-components-address-form__address_1').hide();
                        //                     $('.wp-block-woocommerce-checkout-billing-address-block .wc-block-components-address-form__address_2').hide();
                        //                     $('.wp-block-woocommerce-checkout-billing-address-block .wc-block-components-address-form__city').hide();
                        //                     $('.wp-block-woocommerce-checkout-billing-address-block .wc-block-components-address-form__state').hide();
                        //                     $('.wp-block-woocommerce-checkout-billing-address-block .wc-block-components-address-form__postcode').hide();
                        //                 }
                        //             },
                        //             error: function (error) {
                        //                 console.error('Error loading additional block:', error);
                        //             },
                        //         });
                        //     }, 2000);
                        //
                        //
                        // });
                        var selected_value = $(".wc-block-components-shipping-rates-control__package input[name=radio-control-0]:checked").val();

                        $('#mp-wc-pickup-point-shipping-block').hide();


                        $.ajax({
                            url: '/wp-admin/admin-ajax.php',
                            type: 'post',
                            data: {
                                action: 'load_additional_block'

                            },
                            success: function (response) {
                                // // Append the received content to a specific container or location
                                $('body .wc-block-components-shipping-rates-control__package').append(response);
                            },
                            error: function (error) {
                                console.error('Error loading additional block:', error);
                            },
                        });

                        // $.ajax({
                        //     url: '/wp-admin/admin-ajax.php',
                        //     type: 'post',
                        //     data: {
                        //         action: 'checkout_blocks_hide_inputs_for_terminal'
                        //     },
                        //     success: function (response) {
                        //         if(response == '1') {
                        //             $('.wp-block-woocommerce-checkout-shipping-address-block .wc-block-components-address-form__address_1').hide();
                        //             $('.wp-block-woocommerce-checkout-shipping-address-block .wc-block-components-address-form__address_2').hide();
                        //             $('.wp-block-woocommerce-checkout-shipping-address-block .wc-block-components-address-form__city').hide();
                        //             $('.wp-block-woocommerce-checkout-shipping-address-block .wc-block-components-address-form__state').hide();
                        //             $('.wp-block-woocommerce-checkout-shipping-address-block .wc-block-components-address-form__postcode').hide();
                        //         }
                        //     },
                        //     error: function (error) {
                        //         console.error('Error loading additional block:', error);
                        //     },
                        // });

                        $('.wc-block-components-shipping-rates-control__package .wc-block-components-radio-control__input').on('click', function(e) {
                            // var selected_value2 = $(".wc-block-components-shipping-rates-control__package input[name=radio-control-" + radio_control + "]:checked").val();
                            let selected_value2 = $(".wc-block-components-shipping-rates-control__package input[type=radio]:checked").val();

                            setTimeout(function() {
                                $.ajax({
                                    url: '/wp-admin/admin-ajax.php',
                                    type: 'post',
                                    data: {
                                        action: 'checkout_blocks_hide_inputs_for_terminal',
                                        selected_value : selected_value2
                                    },
                                    success: function (response) {

                                        if(response == 1) {
                                            // $('.wc-block-components-address-form .wc-block-components-address-form__address_1').hide();
                                            // $('.wc-block-components-address-form .wc-block-components-address-form__address_2').hide();
                                            // $('.wc-block-components-address-form .wc-block-components-address-form__city').hide();
                                            // $('.wc-block-components-address-form .wc-block-components-address-form__state').hide();
                                            // $('.wc-block-components-address-form .wc-block-components-address-form__postcode').hide();
                                            $('#shipping .wc-block-components-address-form__address_1').remove();
                                            $('#shipping .wc-block-components-address-form__address_2').remove();
                                            $('#shipping .wc-block-components-address-form__city').remove();
                                            $('#shipping .wc-block-components-address-form__state').remove();
                                            $('#shipping .wc-block-components-address-form__postcode').remove();
                                        }else {
                                            $('.wc-block-components-address-form .wc-block-components-address-form__address_1').show();
                                            $('.wc-block-components-address-form .wc-block-components-address-form__address_2').show();
                                            $('.wc-block-components-address-form .wc-block-components-address-form__city').show();
                                            $('.wc-block-components-address-form .wc-block-components-address-form__state').show();
                                            $('.wc-block-components-address-form .wc-block-components-address-form__postcode').show();
                                        }
                                    },
                                    error: function (error) {
                                        console.error('Error loading additional block:', error);
                                    },
                                });
                            }, 2000);

                            // if (selected_value2.indexOf("post_lt") == -1 && selected_value2.indexOf("courier") == -1 && selected_value2 != 'free_shipping:1' && selected_value2.indexOf("siuntos_autobusais") != 13) {
                            const $select = $('#mp-wc-pickup-point-shipping-select-block');

                            if (selected_value2.indexOf('terminal')>0 || selected_value2.indexOf('pickup_point')>0 || selected_value2.indexOf('post_lv_post')>0) {
                                let currentRequest = null;
                                $('#mp-wc-pickup-point-shipping-block').show();
                                $select.show().empty();

                                // Inicializuojame globalius kintamuosius
                                window.multiparcels_selected_location = window.multiparcels_selected_location || '';
                                window.multiparcels_selected_option = window.multiparcels_selected_option || null;

                                $select.select2({
                                    placeholder: multiparcels.text.please_select_pickup_point_location,
                                    width: '100%',
                                    minimumInputLength: 0,
                                    ajax: {
                                        url: '/wp-admin/admin-ajax.php',
                                        type: 'POST',
                                        dataType: 'json',
                                        delay: 250,
                                        transport: function(params, success, failure) {
                                            // Abort previous request
                                            if (currentRequest) {
                                                currentRequest.abort();
                                            }

                                            // New request
                                            currentRequest = $.ajax(params);

                                            currentRequest.then(success);
                                            currentRequest.fail(function(jqXHR, textStatus) {
                                                // Ignore if request was aborted
                                                if (textStatus !== 'abort') {
                                                    failure();
                                                }
                                            });

                                            return currentRequest;
                                        },
                                        data: function (params) {
                                            return {
                                                action: 'multiparcels_checkout_get_pickup_points_blocks',
                                                selected_value: selected_value2,
                                                q: params.term || '',
                                                page: params.page || 1
                                            };
                                        },
                                        success: function(data) {
                                            const selectedOption = data.results.find(item => item.id == window.multiparcels_selected_location);
                                            if (selectedOption) {
                                                // įdedame pasirinktą elementą į select, kad select2 galėtų jį parodyti
                                                const option = new Option(selectedOption.text, selectedOption.id, true, true);
                                                $select.append(option).trigger('change');
                                            }
                                        },
                                        processResults: function (data, params) {
                                            params.page = params.page || 1;
                                            return {
                                                results: data.results,   // ← vietoj data.items
                                                pagination: data.pagination // ← vietoj skaičiavimo
                                            };
                                        },
                                        cache: true
                                    }
                                });

                                // console.log(window.multiparcels_selected_location);
                                //
                                // // ---- Initial selection if exists ----
                                // if (window.multiparcels_selected_location) {
                                //
                                //     console.log('testing1234');
                                //     $.ajax({
                                //         url: '/wp-admin/admin-ajax.php',
                                //         type: 'POST',
                                //         dataType: 'json',
                                //         data: {
                                //             action: 'multiparcels_checkout_get_pickup_points_blocks',
                                //             selected_value: selected_value2,
                                //             q: window.multiparcels_selected_location
                                //         },
                                //         success: function(data) {
                                //             const selectedOption = data.results.find(item => item.id == window.multiparcels_selected_location);
                                //             if (selectedOption) {
                                //                 window.multiparcels_selected_option = {
                                //                     id: selectedOption.id,
                                //                     text: selectedOption.text
                                //                 };
                                //
                                //                 // Tik pridėti, jei dar nėra
                                //                 if (!$select.find(`option[value='${selectedOption.id}']`).length) {
                                //                     const option = new Option(selectedOption.text, selectedOption.id, true, true);
                                //                     $select.append(option).trigger('change'); // triggers document-level change
                                //                 }
                                //             }
                                //         }
                                //     });
                                // }

                                $select.off('change').on('change', function() {
                                    const selectedData = $(this).select2('data')[0];
                                    if (!selectedData) return;

                                    // Pažymėti <option selected>
                                    $select.find('option').prop('selected', false);
                                    let $option = $select.find(`option[value='${selectedData.id}']`);
                                    if ($option.length === 0) {
                                        $option = new Option(selectedData.text, selectedData.id, true, true);
                                        $select.append($option);
                                    }
                                    $option.prop('selected', true);

                                    // Atnaujinti globalią kintamąją
                                    window.multiparcels_selected_option = {
                                        id: selectedData.id,
                                        text: selectedData.text
                                    };

                                    console.log(window.multiparcels_selected_option);

                                    // Siųsti AJAX
                                    sendPickupAjax(selectedData.id);
                                });

                                // $.ajax({
                                //     url: '/wp-admin/admin-ajax.php',
                                //     type: 'post',
                                //     data: {
                                //         action: 'multiparcels_checkout_get_pickup_points_blocks',
                                //         selected_value : selected_value2
                                //     },
                                //     dataType: 'json',
                                //     success: function (points) {
                                //
                                //         var pointsNew = points.by_identifier;
                                //
                                //         window.multiparcels_select_points_by_identifier = points.by_identifier;
                                //
                                //         $('#mp-wc-pickup-point-shipping-block').show();
                                //
                                //         $('#mp-wc-pickup-point-shipping-select-block').select2();
                                //
                                //         $('#mp-wc-pickup-point-shipping-select-block').html("");
                                //
                                //         if (typeof jQuery.fn.selectWoo === "function") {
                                //
                                //             console.log('testing');
                                //
                                //             $('#mp-wc-pickup-point-shipping-select-block').selectWoo({
                                //
                                //                 data: points.all,
                                //
                                //                 placeholderOption: 'first',
                                //
                                //                 width: '100%',
                                //
                                //                 language: {
                                //
                                //                     noResults: function () {
                                //
                                //                         return multiparcels.text.pickup_location_not_found;
                                //
                                //                     }
                                //
                                //                 },
                                //
                                //                 templateResult: function (option) {
                                //
                                //                     if (typeof option.first_line == 'string') {
                                //
                                //                         return $(
                                //
                                //                             '<span>' + option.first_line + ' <small>' + option.second_line + '</small></span>'
                                //
                                //                         );
                                //
                                //                     }
                                //
                                //                     return $('<span>' + option.text + '</span>');
                                //
                                //                 },
                                //
                                //                 templateSelection: function (data, container) {
                                //
                                //                     if (typeof data.second_line != 'undefined' && data.second_line) {
                                //
                                //                         return data.first_line + ' (' + data.second_line + ')';
                                //
                                //                     }
                                //
                                //                     return data.first_line;
                                //
                                //                 }
                                //
                                //             })
                                //                 // add search placeholder
                                //
                                //                 .data('select2')
                                //
                                //                 .$dropdown
                                //
                                //                 .find(':input.select2-search__field')
                                //
                                //                 .attr('placeholder', multiparcels.placeholder_text);
                                //
                                //         } else {
                                //
                                //             var items = '';
                                //
                                //             $.each(points.all, function (key, value) {
                                //
                                //                 if (typeof value.children === 'object') {
                                //
                                //                     items += "<optgroup label='" + value.text + "'>";
                                //
                                //                     $.each(value.children, function (key2, value2) {
                                //
                                //                         items += '<option value=' + value2.id + '>' + value2.text + '</option>';
                                //
                                //                     });
                                //
                                //                     items += "</optgroup>";
                                //
                                //                 } else {
                                //
                                //                     items += '<option value=' + value.id + '>' + value.text + '</option>';
                                //
                                //                 }
                                //
                                //             });
                                //
                                //             $('#mp-wc-pickup-point-shipping-select-block').html(items);
                                //
                                //         }
                                //
                                //         if (typeof window.multiparcels_selected_location != 'undefined' && window.multiparcels_selected_location) {
                                //
                                //             // check if it actually exists
                                //
                                //             if ($('#mp-wc-pickup-point-shipping-select-block').find("option[value='" + window.multiparcels_selected_location + "']").length) {
                                //
                                //                 $('#mp-wc-pickup-point-shipping-select-block').val(window.multiparcels_selected_location).trigger('change');
                                //
                                //             }
                                //
                                //         }
                                //
                                //     },
                                //     error: function (error) {
                                //         console.error('Error loading additional block:', error);
                                //     },
                                // });
                            }else if(selected_value2.indexOf("siuntos_autobusais") > 0){

                                $.ajax({
                                    url: '/wp-admin/admin-ajax.php',
                                    type: 'post',
                                    data: {
                                        action: 'multiparcels_checkout_get_pickup_points_siuntos_autobusais_blocks',
                                        selected_value : selected_value2

                                    },
                                    dataType: 'json',
                                    success: function (points) {

                                        var pointsNew = points.all;

                                        window.multiparcels_select_points_by_identifier = points.all;

                                        $('#mp-wc-pickup-point-shipping-block').show();

                                        $('#mp-wc-pickup-point-shipping-select-block').select2();

                                        $('#mp-wc-pickup-point-shipping-select-block').html("");

                                        var items = '';

                                        $.each(points.all, function (key, value) {

                                            items += '<option value=' + value.id + '>' + value.text + '</option>';

                                        });

                                        $('#mp-wc-pickup-point-shipping-select-block').html(items);

                                        attachPickupPointChangeHandler();
                                    },
                                    error: function (error) {
                                        console.error('Error loading additional block:', error);
                                    },
                                });
                            } else {
                                $('#mp-wc-pickup-point-shipping-block').hide();
                            }


                        });


                    }, 1200);

                setTimeout(function() {
                    $(".wc-block-components-shipping-rates-control__package input[name=radio-control-"+radio_control+"]:checked").click();
                }, 2500);
            }
        }, 1000);

    });

}

function stopCount(){
    clearTimeout(timeout);
    clearTimeout(timeout2);
}

function attachPickupPointChangeHandler() {

    jQuery(function($) {

        const selector = '#mp-wc-pickup-point-shipping-select-block';

        // Ensure Select2 is initialized
        const $select = $(selector);

        if ($select.length) {
            // Avoid duplicate bindings
            $select.off('select2:select');

            // Bind to Select2 event
            $select.on('select2:select', function (e) {
                const multiparcels_pickup_location_value = $(this).val();

                console.log('Value' + multiparcels_pickup_location_value);

                sendPickupAjax(multiparcels_pickup_location_value);
            });

            // 🔁 Trigger AJAX manually if there's a selected value
            const preselected = $select.val();

            if (preselected) {
                sendPickupAjax(preselected);
            }
        }
    });

}

function sendPickupAjax(multiparcels_pickup_location_value) {
    jQuery(function($) {
        $.ajax({
            url: '/wp-admin/admin-ajax.php',
            type: 'post',
            data: {
                action: 'multiparcels_store_pickup_selection',
                multiparcels_pickup_location_value: multiparcels_pickup_location_value
            },
            success: function (response) {
                console.log('Pickup point selection stored:', multiparcels_pickup_location_value);
            },
            error: function (error) {
                console.error('Error storing pickup selection:', error);
            },
        });
    });

}



(function ($) {
    $( document ).ready(function() {
        
        // var checkoutRenderInitInterval = setInterval(() => {
        //     var checkoutRenderInitEvent = new CustomEvent( 'checkout_render_init' , { detail: {message:'checkout render init: halo'}});
        //     if ($(".wp-block-woocommerce-checkout-fields-block")[0]) {
        //         document.dispatchEvent(checkoutRenderInitEvent);
        //         clearInterval(checkoutRenderInitInterval);
        //     }
        // },500);

        document.addEventListener('checkout_render_init', function (e){
            if ($(".wp-block-woocommerce-checkout-fields-block")[0]) {
                setTimeout(
                    function()
                    {
                        $('#shipping-method-1').on('click', function(){
                            radio_control = radio_control + 2;
                            timedCount();
                        });

                        $('#shipping-method-2').on('click', function(){
                            var selected_value2 = 'local_pickup';
                            // var selected_value2 = $(".wc-block-components-shipping-rates-control__package input[name=radio-control-" + radio_control + "]:checked").val();
                            stopCount();

                            $.ajax({
                                url: '/wp-admin/admin-ajax.php',
                                type: 'post',
                                data: {
                                    action: 'checkout_blocks_hide_inputs_for_terminal',
                                    selected_value : selected_value2
                                },
                                success: function (response) {

                                    if(response == 1) {
                                        $('.wc-block-components-address-form .wc-block-components-address-form__address_1').hide();
                                        $('.wc-block-components-address-form .wc-block-components-address-form__address_1 #shipping-address_1').removeAttr('required');
                                        $('.wc-block-components-address-form .wc-block-components-address-form__address_2').hide();
                                        $('.wc-block-components-address-form .wc-block-components-address-form__city').hide();
                                        $('.wc-block-components-address-form .wc-block-components-address-form__state').hide();
                                        $('.wc-block-components-address-form .wc-block-components-address-form__postcode').hide();
                                    }else {
                                        $('.wc-block-components-address-form .wc-block-components-address-form__address_1').show();
                                        $('.wc-block-components-address-form .wc-block-components-address-form__address_2').show();
                                        $('.wc-block-components-address-form .wc-block-components-address-form__city').show();
                                        $('.wc-block-components-address-form .wc-block-components-address-form__state').show();
                                        $('.wc-block-components-address-form .wc-block-components-address-form__postcode').show();
                                    }
                                },
                                error: function (error) {
                                    console.error('Error loading additional block:', error);
                                },
                            });

                        });

                        // $('#shipping-postcode').on('change', function() {
                        //     radio_control = 0;
                        //     timedCount();
                        // });


                    }, 1100);
            }
        });
        // if ($(".wp-block-woocommerce-checkout-fields-block")[0]) {
        //     setTimeout(
        //         function()
        //         {
        //             $('#shipping-method-1').on('click', function(){
        //                 radio_control = radio_control + 2;
        //                 timedCount();
        //             });
        //
        //             $('#shipping-method-2').on('click', function(){
        //                 var selected_value2 = 'local_pickup';
        //                 // var selected_value2 = $(".wc-block-components-shipping-rates-control__package input[name=radio-control-" + radio_control + "]:checked").val();
        //                 stopCount();
        //
        //                 $.ajax({
        //                     url: '/wp-admin/admin-ajax.php',
        //                     type: 'post',
        //                     data: {
        //                         action: 'checkout_blocks_hide_inputs_for_terminal',
        //                         selected_value : selected_value2
        //                     },
        //                     success: function (response) {
        //
        //                         if(response == 1) {
        //                             $('.wc-block-components-address-form .wc-block-components-address-form__address_1').hide();
        //                             $('.wc-block-components-address-form .wc-block-components-address-form__address_1 #shipping-address_1').removeAttr('required');
        //                             $('.wc-block-components-address-form .wc-block-components-address-form__address_2').hide();
        //                             $('.wc-block-components-address-form .wc-block-components-address-form__city').hide();
        //                             $('.wc-block-components-address-form .wc-block-components-address-form__state').hide();
        //                             $('.wc-block-components-address-form .wc-block-components-address-form__postcode').hide();
        //                         }else {
        //                             $('.wc-block-components-address-form .wc-block-components-address-form__address_1').show();
        //                             $('.wc-block-components-address-form .wc-block-components-address-form__address_2').show();
        //                             $('.wc-block-components-address-form .wc-block-components-address-form__city').show();
        //                             $('.wc-block-components-address-form .wc-block-components-address-form__state').show();
        //                             $('.wc-block-components-address-form .wc-block-components-address-form__postcode').show();
        //                         }
        //                     },
        //                     error: function (error) {
        //                         console.error('Error loading additional block:', error);
        //                     },
        //                 });
        //
        //             });
        //
        //
        //         }, 1100);
        // }
        


        setTimeout(function() {
            if ($(".wp-block-woocommerce-checkout-fields-block")[0]) {
                timedCount();
            }

            $('#shipping-country').on('change', function() {
                // Read current checkout shipping fields
                const country = $('#shipping-country').val() || '';
                const state   = $('#shipping-state').val() || 'Vilnius';
                const postcode = $('#shipping-postcode').val() || '';
                const city    = $('#shipping-city').val() || '';

                // Only send if at least country is selected
                if (!country) return;

                const shippingAddress = {
                    country: country,
                    state: state,
                    postcode: postcode,
                    city: city
                };

                $.ajax({
                    // url: '/wp-json/wc/store/v1/batch',
                    url: '/index.php?rest_route=/wc/store/v1/batch',
                    method: 'POST',
                    contentType: 'application/json',
                    // headers: {
                    //     'X-WP-Nonce': 'dee34b149e' // your nonce here
                    // },
                    data: JSON.stringify({
                        requests: [
                            {
                                body: {
                                    billing_address: {
                                        first_name: "",
                                        last_name: "",
                                        company: "",
                                        address_1: "",
                                        address_2: "",
                                        city: "",
                                        state: "",
                                        postcode: "",
                                        country: country,
                                        email: "",
                                        phone: ""
                                    },
                                    shipping_address: {
                                        first_name: "",
                                        last_name: "",
                                        company: "",
                                        address_1: "",
                                        address_2: "",
                                        city: "",
                                        state: "",
                                        postcode: "",
                                        country: country,
                                        phone: ""
                                    }
                                },
                                cache: 'no-store',
                                data: {
                                    billing_address: {
                                        first_name: "",
                                        last_name: "",
                                        company: "",
                                        address_1: "",
                                        address_2: "",
                                        city: "",
                                        state: "",
                                        postcode: "",
                                        country: country,
                                        email: "",
                                        phone: ""
                                    },
                                    shipping_address: {
                                        first_name: "",
                                        last_name: "",
                                        company: "",
                                        address_1: "",
                                        address_2: "",
                                        city: "",
                                        state: "",
                                        postcode: "",
                                        country: country,
                                        phone: ""
                                    }
                                },
                                headers: {
                                    'Nonce': multiparcels.nonce // your nonce here
                                },
                                method: "POST",
                                path: "/wc/store/v1/cart/update-customer",
                            }
                        ]
                    }),
                    success: function(response) {

                        const shippingRates = response.responses[0].body.shipping_rates[0].shipping_rates;
                        $('.wc-block-components-shipping-rates-control__package .wc-block-components-radio-control').html("");
                        $('#dpd-wc-pickup-point-shipping-block').hide();

                        var html = '';
                        shippingRates.forEach((method, index) => {

                            let price = method.price/100;

                            if (index === 0) {
                                html += '<label class="wc-block-components-radio-control__option wc-block-components-radio-control__option-checked wc-block-components-radio-control__option--checked-option-highlighted" for="radio-control-0-' + method.rate_id +'">';
                                html += '<input id="radio-control-0-'+ method.rate_id +'" class="wc-block-components-radio-control__input" type="radio" name="radio-control-0" aria-describedby="radio-control-0-'+ method.rate_id +'__secondary-label" aria-disabled="false" value="' + method.rate_id +'" checked="">';
                            } else {
                                html += '<label class="wc-block-components-radio-control__option" for="radio-control-0-' + method.rate_id +'">';
                                html += '<input id="radio-control-0-'+ method.rate_id +'" class="wc-block-components-radio-control__input" type="radio" name="radio-control-0" aria-describedby="radio-control-0-' + method.rate_id +'__secondary-label" aria-disabled="false" value="'+ method.rate_id + '">';
                            }
                            html += '<div class="wc-block-components-radio-control__option-layout">';
                            html += '<div class="wc-block-components-radio-control__label-group"><span id="radio-control-0-' + method.rate_id +'__label" class="wc-block-components-radio-control__label">' + method.name +'</span><span id="radio-control-0-'+ method.rate_id +'__secondary-label" class="wc-block-components-radio-control__secondary-label"><span class="wc-block-formatted-money-amount wc-block-components-formatted-money-amount">'+ price +' €</span></span></div>';
                            html += '</div>';
                            html += '</label>';

                        });
                        $('.wc-block-components-shipping-rates-control__package .wc-block-components-radio-control').append(html);

                        // rebind click to new inputs
                        // $('.wc-block-components-shipping-rates-control__package .wc-block-components-radio-control__input').off('click').on('click', function() {
                        //     timedCount();
                        // });
                        //
                        // find the checked input
                        const firstChecked = $('.wc-block-components-shipping-rates-control__package .wc-block-components-radio-control__input:checked');

                        // run your logic manually
                        if (firstChecked.length) {
                            //firstChecked.trigger('click'); // or trigger('change')
                            timedCount();
                        }

                        // timedCount();
                    },
                    error: function(xhr, status, error) {
                        console.error('Error updating customer via batch:', error, xhr.responseText);
                    }
                });
            });

            $('#shipping-city').on('change', function() {
                timedCount();
                setTimeout(function() {
                    $('.wc-block-components-shipping-rates-control__package .wc-block-components-radio-control__input:checked').click();
                }, 4000);
            });

            $('#shipping-state').on('change', function() {
                timedCount();
                setTimeout(function() {
                    $('.wc-block-components-shipping-rates-control__package .wc-block-components-radio-control__input:checked').click();
                }, 4000);
            });

            $('#shipping-postcode').on('change', function() {
                timedCount();
                setTimeout(function() {
                    $('.wc-block-components-shipping-rates-control__package .wc-block-components-radio-control__input:checked').click();
                }, 4000);
            });
        }, 1000);

        // setTimeout(function() {
        //     attachPickupPointChangeHandler();
        // }, 5000);

    });



    $(document).on('updated_checkout cfw_updated_checkout', function (e, data) {
        $('#mp-wc-pickup-point-shipping').hide();

        let placeholder_classic = multiparcels.text.please_select_pickup_point_location;

        var shipping_methods = {};

        $('select.shipping_method, input[name^="shipping_method"][type="radio"]:checked, input[name^="shipping_method"][type="hidden"]').each(function () {

            shipping_methods[$(this).data('index')] = $(this).val();

        });



        var show_title = false;



        if (multiparcels.display_pickup_location_title == 'yes') {

            show_title = true;

        }



        var rey_theme = $('body').hasClass('theme-rey') && $('.rey-checkout-shipping').length && $('.rey-checkout-shipping').is(":visible");



        if (!show_title) {

            $("#mp-wc-pickup-point-shipping .mp-please-select-location").hide();

        }



        $("#preferred_delivery_time_field").hide();



        $('.multiparcels-door-code').addClass('multiparcels-door-code-invisible').removeClass('multiparcels-door-code-visible');



        if (rey_theme && $('.multiparcels-rey-theme-modified-step').length) {

            var originalText = $('.multiparcels-rey-theme-modified-step').attr('data-original-text');



            $(".multiparcels-rey-theme-modified-step")

                .removeClass('multiparcels-rey-theme-modified-step')

                .attr('href', '#')

                .text(originalText)

                .addClass('__step-fwd');

        }



        if (Object.keys(shipping_methods).length > 0) {



            var shipping_methods_keys = Object.keys(shipping_methods);

            var shipping_method = $.trim(shipping_methods[shipping_methods_keys[0]]);

            $('#mp-wc-pickup-point-shipping').addClass('multiparcels-loading');



            var terminal_shipping_fields = $("");

            if (multiparcels.hide_not_required_terminal_fields === 'yes') {

                terminal_shipping_fields = $("#billing_address_1_field, #billing_address_2_field, #billing_city_field, #billing_postcode_field, #shipping_address_1_field, #shipping_address_2_field, #shipping_city_field, #shipping_postcode_field");

                terminal_shipping_fields.show();

            }





            var local_pickup_shipping_fields = $("");

            if (multiparcels.hide_not_required_local_pickup_fields === 'yes') {

                local_pickup_shipping_fields = $("#billing_address_1_field, #billing_address_2_field, #billing_city_field, #billing_postcode_field, #shipping_address_1_field, #shipping_address_2_field, #shipping_city_field, #shipping_postcode_field");

                local_pickup_shipping_fields.show();

            }





            // is MultiParcels and pickup location

            if (
                (shipping_method.indexOf("_siuntos_autobusais_courier") !== -1) ||
                (shipping_method.substr(0, 12) === 'multiparcels' && shipping_method.indexOf("_bus_station") !== -1) ||
                (shipping_method.substr(0, 12) === 'multiparcels' && shipping_method.indexOf("_pickup_point") !== -1) ||

                (shipping_method.substr(0, 12) === 'multiparcels' && shipping_method.indexOf("_terminal") !== -1) ||

                (shipping_method.substr(0, 12) === 'multiparcels' && shipping_method.indexOf("post_lv_pickup_point") !== -1 && shipping_method.split(':')[0].endsWith('_post')) ||

                (shipping_method.substr(0, 12) === 'multiparcels' && shipping_method.indexOf("multiparcels_post_lv_post") !== -1 && shipping_method.split(':')[0].endsWith('_post'))) {



                // Reset selected

                $("#mp-selected-pickup-point-info-wrapper").hide();

                $("#mp-map-preview").hide();

                $("#mp-wc-pickup-point-shipping-select").html('');

                $(".mp-selected-pickup-point-info").html('');

                var latvian_post = false;



                if (shipping_method.indexOf("post_lv") !== -1) {

                    latvian_post = true;

                }



                if (!latvian_post) {

                    terminal_shipping_fields.hide();

                }



                if (rey_theme && $('.rey-checkoutPage-form .__step[data-step="shipping"]').is(':visible')) {

                    var step = $('.rey-checkoutPage-form .__step[data-step="shipping"]')

                        .find('.__step-footer .btn-primary');

                    var originalText = step.text();

                    step.attr('data-original-text', originalText);



                    $('.rey-checkoutPage-form .__step[data-step="shipping"]')

                        .find('.__step-footer .btn-primary')

                        .removeClass('__step-fwd')

                        .addClass('multiparcels-rey-theme-modified-step')

                        .attr('href', 'javascript:;')

                        .text(multiparcels.text.please_select_pickup_point_location);

                }



                $('#mp-wc-pickup-point-shipping').show();

                $.ajax({

                    type: 'POST',

                    url: multiparcels.ajax_url,

                    data: {

                        'action': 'multiparcels_checkout_get_pickup_points'

                    },

                    dataType: 'json',

                    success: function (points) {

                        window.multiparcels_select_points_by_identifier = points.by_identifier;



                        $('#mp-wc-pickup-point-shipping').removeClass('multiparcels-loading');



                        $('#mp-wc-pickup-point-shipping-select').html("");

                        // Add an empty <option> for placeholder
                        // $('#mp-wc-pickup-point-shipping-select').html('<option></option>');



                        if (typeof jQuery.fn.selectWoo === "function") {

                            let currentRequest = null;

                            $('#mp-wc-pickup-point-shipping-select').selectWoo({
                                placeholder: multiparcels.placeholder_text || 'Please select pickup point',
                                allowClear: true,
                                allowClear: true,
                                width: '100%',
                                minimumInputLength: 0,
                                ajax: {
                                    url: multiparcels.ajax_url,
                                    type: 'POST',
                                    dataType: 'json',
                                    delay: 250,
                                    transport: function(params, success, failure) {
                                        // Abort previous request
                                        if (currentRequest) {
                                            currentRequest.abort();
                                        }

                                        // New request
                                        currentRequest = $.ajax(params);

                                        currentRequest.then(success);
                                        currentRequest.fail(function(jqXHR, textStatus) {
                                            // Ignore if request was aborted
                                            if (textStatus !== 'abort') {
                                                failure();
                                            }
                                        });

                                        return currentRequest;
                                    },
                                    data: function(params) {
                                        return {
                                            action: 'multiparcels_checkout_get_pickup_points_classic',
                                            q: params.term || '',
                                            page: params.page || 1
                                        };
                                    },
                                    processResults: function(data, params) {
                                        params.page = params.page || 1;
                                        // return {
                                        //     results: data.items.map(function(item) {
                                        //         return {
                                        //             id: item.id,
                                        //             text: item.first_line + (item.second_line ? ' (' + item.second_line + ')' : ''),
                                        //             first_line: item.first_line,
                                        //             second_line: item.second_line
                                        //         };
                                        //     }),
                                        //     pagination: { more: (params.page * 20) < data.total_count }
                                        // };
                                        let results = data.items.map(function(item) {
                                            return {
                                                id: item.id,
                                                text: item.first_line + (item.second_line ? ' (' + item.second_line + ')' : ''),
                                                first_line: item.first_line,
                                                second_line: item.second_line
                                            };
                                        });

                                        return { results: results, pagination: { more: (params.page * 20) < data.total_count } };
                                    },
                                    cache: true
                                },
                                language: {
                                    noResults: function() {
                                        return multiparcels.text.pickup_location_not_found;
                                    }
                                },
                                templateResult: function(option) {
                                    if (option.first_line) {
                                        return $('<span>' + option.first_line + ' <small>' + option.second_line + '</small></span>');
                                    }
                                    return $('<span>' + option.text + '</span>');
                                },
                                templateSelection: function(data) {
                                    if (!data.id) { // empty value, show placeholder
                                        return multiparcels.placeholder_text || 'Please select pickup point';
                                    }
                                    // return data.second_line ? data.first_line + ' (' + data.second_line + ')' : data.first_line;
                                    return data.second_line ? data.first_line + ' (' + data.second_line + ')' : data.first_line;
                                }
                            });

                            // select first element by default
                            // $('#mp-wc-pickup-point-shipping-select').click();
                            // $('#mp-wc-pickup-point-shipping-select').selectWoo({
                            //
                            //     data: points.all,
                            //
                            //     placeholderOption: 'first',
                            //
                            //     width: '100%',
                            //
                            //     language: {
                            //
                            //         noResults: function () {
                            //
                            //             return multiparcels.text.pickup_location_not_found;
                            //
                            //         }
                            //
                            //     },
                            //
                            //     templateResult: function (option) {
                            //
                            //         if (typeof option.first_line == 'string') {
                            //
                            //             return $(
                            //
                            //                 '<span>' + option.first_line + ' <small>' + option.second_line + '</small></span>'
                            //
                            //             );
                            //
                            //         }
                            //
                            //
                            //
                            //         return $('<span>' + option.text + '</span>');
                            //
                            //     },
                            //
                            //     templateSelection: function (data, container) {
                            //
                            //         if (typeof data.second_line != 'undefined' && data.second_line) {
                            //
                            //             return data.first_line + ' (' + data.second_line + ')';
                            //
                            //         }
                            //
                            //
                            //
                            //         return data.first_line;
                            //
                            //     }
                            //
                            // })
                            //
                            //     // add search placeholder
                            //
                            //     .data('select2')
                            //
                            //     .$dropdown
                            //
                            //     .find(':input.select2-search__field')
                            //
                            //     .attr('placeholder', multiparcels.placeholder_text);

                        } else {

                            var items = '';



                            $.each(points.all, function (key, value) {

                                if (typeof value.children === 'object') {

                                    items += "<optgroup label='" + value.text + "'>";

                                    $.each(value.children, function (key2, value2) {

                                        items += '<option value=' + value2.id + '>' + value2.text + '</option>';

                                    });

                                    items += "</optgroup>";

                                } else {

                                    items += '<option value=' + value.id + '>' + value.text + '</option>';

                                }

                            });



                            $('#mp-wc-pickup-point-shipping-select').html(items);

                        }



                        // if (typeof window.multiparcels_selected_location != 'undefined' && window.multiparcels_selected_location) {
                        //
                        //     // check if it actually exists
                        //
                        //     if ($('#mp-wc-pickup-point-shipping-select').find("option[value='" + window.multiparcels_selected_location + "']").length) {
                        //
                        //         $('#mp-wc-pickup-point-shipping-select').val(window.multiparcels_selected_location).trigger('change');
                        //
                        //     }
                        //
                        // }

                    }

                });

            } else if (shipping_method.substr(0, 12) === 'multiparcels') {

                if (shipping_method.indexOf("venipak") !== -1) {

                    var cities = multiparcels.preferred_delivery_time_cities;

                    var city = transliterate($("#billing_city").val().toLowerCase());

                    var is_big_city = cities.indexOf(city) != -1;



                    if (is_big_city) {

                        $.ajax({

                            type: 'POST',

                            url: multiparcels.ajax_url,

                            data: {

                                'action': 'multiparcels_is_preferred_delivery_time_available'

                            },

                            dataType: 'json',

                            success: function (response) {

                                if (response.success == true) {

                                    var options = '';



                                    response.times.forEach(function (value, key) {

                                        options += "<option value='" + key + "'>" + value + "</option>";

                                    });



                                    $("#preferred_delivery_time_field select").html(options);

                                    $("#preferred_delivery_time_field").show();



                                    if (typeof jQuery.fn.selectWoo === "function") {

                                        $("#preferred_delivery_time").selectWoo();

                                    }



                                    if (typeof window.multiparcels_selected_delivery_time != 'undefined' && window.multiparcels_selected_delivery_time) {

                                        $('#preferred_delivery_time').val(window.multiparcels_selected_delivery_time).trigger('change');

                                    }

                                }

                            }

                        });

                    }



                    $.ajax({

                        type: 'POST',

                        url: multiparcels.ajax_url,

                        data: {

                            'action': 'multiparcels_venipak_door_code'

                        },

                        dataType: 'json',

                        success: function (response) {

                            if (response.success) {

                                $('.multiparcels-door-code').addClass('multiparcels-door-code-visible').removeClass('multiparcels-door-code-invisible');

                            }

                        }

                    });



                    // Reset any previous selection

                    $('#mp-wc-pickup-point-shipping-select').val('');

                }

            } else if(shipping_method.split(':')[0] == 'local_pickup') {

                local_pickup_shipping_fields.hide();



                // Reset any previous selection

                $('#mp-wc-pickup-point-shipping-select').val('');

            } else {

                // Reset any previous selection

                $('#mp-wc-pickup-point-shipping-select').val('');

            }

        }

    });



    $(document).on('change', '#mp-wc-pickup-point-shipping-select', function () {

        var val = $('#mp-wc-pickup-point-shipping-select').val();

        if (jQuery('body').hasClass('theme-Divi')) {

            $.ajax({
                url: '/wp-admin/admin-ajax.php',
                type: 'POST',
                data: {
                    action: 'multiparcels_set_terminal_value',
                    selected_value: val,
                },
                dataType: 'json',
                success: function(response) {
                },
                error: function(error) {
                    console.error('AJAX Error:', error);
                }
            });

        }



        $("#mp-selected-pickup-point-info-wrapper").hide();

        $("#mp-map-preview").hide();



        var show_information = false;



        if (multiparcels.display_selected_pickup_location_information == 'yes') {

            show_information = true;

        }



        // remember selected location

        window.multiparcels_selected_location = val;



        if (val == '' || !show_information) {

            $(".mp-selected-pickup-point-info").html('');

        } else {

            var location = window.multiparcels_select_points_by_identifier[val];



            // to prevent selecting location from a different carrier when switching between

            // shipping methods

            if (location) {

                $("#mp-selected-pickup-point-info-wrapper").show();



                var rey_theme = $('body').hasClass('theme-rey') && $('.rey-checkout-shipping').length && $('.rey-checkout-shipping').is(":visible");



                if (rey_theme && $('.multiparcels-rey-theme-modified-step').length) {

                    var originalText = $('.multiparcels-rey-theme-modified-step').attr('data-original-text');



                    $(".multiparcels-rey-theme-modified-step")

                        .removeClass('multiparcels-rey-theme-modified-step')

                        .attr('href', '#')

                        .text(originalText)

                        .addClass('__step-fwd');

                }



                var html = location['second_line'] + "<br/>";



                if (location.location.working_hours) {

                    html += multiparcels.text.working_hours + ": <strong>" + location.location.working_hours + "</strong><br/>";

                }



                if (location.location.comment) {

                    html += "<small>" + location.location.comment + "</small><br/>";

                }



                $(".mp-selected-pickup-point-info").html(html);



                if (typeof google === "object" && google.maps && location.location.latitude && location.location.longitude) {

                    $("#mp-map-preview").show();



                    var position = {

                        lat: parseFloat(location.location.latitude),

                        lng: parseFloat(location.location.longitude)

                    };



                    var map = new google.maps.Map(document.getElementById('mp-gmap'), {

                        center: position,

                        zoom: 15

                    });



                    new google.maps.Marker({

                        position: position,

                        map: map

                    });

                }

            }

        }

    });

    // $(document).on('change', '#mp-wc-pickup-point-shipping-select-block', function () {
    //
    //
    //
    //     let val = $('#mp-wc-pickup-point-shipping-select').val();
    //
    //     // if (!val) {
    //     //     const selectedData = $('#mp-wc-pickup-point-shipping-select-block').select2('data')[0];
    //     //     if (!selectedData.id) {
    //     //         console.log("No selection or id is null/undefined/empty");
    //     //         return;
    //     //     }else {
    //     //         val = selectedData.id;
    //     //     }
    //     //     // val = window.multiparcels_selected_location;
    //     // }
    //
    //
    //
    //     $("#mp-selected-pickup-point-info-wrapper").hide();
    //
    //     $("#mp-map-preview").hide();
    //
    //
    //
    //     var show_information = false;
    //
    //
    //
    //     if (multiparcels.display_selected_pickup_location_information == 'yes') {
    //
    //         show_information = true;
    //
    //     }
    //
    //
    //
    //     // remember selected location
    //
    //     window.multiparcels_selected_location = val;
    //
    //
    //
    //     if (val == '' || !show_information) {
    //
    //         $(".mp-selected-pickup-point-info").html('');
    //
    //     } else {
    //
    //         var location = window.multiparcels_select_points_by_identifier[val];
    //
    //
    //
    //         // to prevent selecting location from a different carrier when switching between
    //
    //         // shipping methods
    //
    //         if (location) {
    //
    //             $("#mp-selected-pickup-point-info-wrapper").show();
    //
    //
    //
    //             var rey_theme = $('body').hasClass('theme-rey') && $('.rey-checkout-shipping').length && $('.rey-checkout-shipping').is(":visible");
    //
    //
    //
    //             if (rey_theme && $('.multiparcels-rey-theme-modified-step').length) {
    //
    //                 var originalText = $('.multiparcels-rey-theme-modified-step').attr('data-original-text');
    //
    //
    //
    //                 $(".multiparcels-rey-theme-modified-step")
    //
    //                     .removeClass('multiparcels-rey-theme-modified-step')
    //
    //                     .attr('href', '#')
    //
    //                     .text(originalText)
    //
    //                     .addClass('__step-fwd');
    //
    //             }
    //
    //
    //
    //             var html = location['second_line'] + "<br/>";
    //
    //
    //
    //             if (location.location.working_hours) {
    //
    //                 html += multiparcels.text.working_hours + ": <strong>" + location.location.working_hours + "</strong><br/>";
    //
    //             }
    //
    //
    //
    //             if (location.location.comment) {
    //
    //                 html += "<small>" + location.location.comment + "</small><br/>";
    //
    //             }
    //
    //
    //
    //             $(".mp-selected-pickup-point-info").html(html);
    //
    //
    //
    //             if (typeof google === "object" && google.maps && location.location.latitude && location.location.longitude) {
    //
    //                 $("#mp-map-preview").show();
    //
    //
    //
    //                 var position = {
    //
    //                     lat: parseFloat(location.location.latitude),
    //
    //                     lng: parseFloat(location.location.longitude)
    //
    //                 };
    //
    //
    //
    //                 var map = new google.maps.Map(document.getElementById('mp-gmap'), {
    //
    //                     center: position,
    //
    //                     zoom: 15
    //
    //                 });
    //
    //
    //
    //                 new google.maps.Marker({
    //
    //                     position: position,
    //
    //                     map: map
    //
    //                 });
    //
    //             }
    //
    //         }
    //
    //     }
    //
    // });



    /**

     * Remember selected delivery time

     */

    $(document).on('change', '#preferred_delivery_time', function () {

        window.multiparcels_selected_delivery_time = $(this).val();

    });



    /**

     * AeroCheckout

     */

    $(document).on('change', '.wfacp_shipping_radio input', function () {

        $(document).trigger('updated_checkout');

    });

}(jQuery));

