// source --> https://lohnapood.ee/wp-content/plugins/woo-lithuaniapost-main/public/js/woo-lithuaniapost.js?ver=4.0.29 
(function ($) {
    'use strict';

    let savedTerminalId = undefined;

    function onTerminalSelect(data) {
        const terminalId = data.id;
        const terminalName = data.text;
        if (terminalId && terminalId !== savedTerminalId && !isNaN(terminalId)) {
            $.ajax({
                type: "POST",
                dataType: "json",
                url: woo_lithuaniapost.ajax_url,
                data: {
                    action: "save_selected_lpexpress_terminal",
                    terminal: terminalName,
                    terminal_id: terminalId
                }, success: function () {
                    savedTerminalId = terminalId;
                }
            });
        }
    }

    $(document).ready(function () {

        const terminalMatcher = (params, data) => {
            const originalMatcher = $.fn.select2.defaults.defaults.matcher;
            const result = originalMatcher(params, data);
            if (
                result &&
                data.children &&
                result.children &&
                data.children.length
            ) {
                if (
                    data.children.length !== result.children.length &&
                    data.text.toLowerCase().includes(params.term.toLowerCase())
                ) {
                    result.children = data.children;
                }
                return result;
            }
            return null;
        }

        const recurse = (parent) => {

            if (parent.nodeName === 'SELECT' && parent.className === 'woo_lithuaniapost_lpexpress_terminal_id') {
                const terminalsElem = $(parent);
                if(terminalsElem.width() < 250) {
                    const tdElem = $('<td colspan=\"2\">').append(terminalsElem.parent());
                    const trElem = $('<tr>').append(tdElem)
                    $('.woocommerce-shipping-totals.shipping').after(trElem);
                }

                let eventSelect = terminalsElem.select2({
                    width: 'resolve',
                    matcher(params, data) {
                        return terminalMatcher(params, data);
                    },
                });
                eventSelect.on("select2:select", function (e) { onTerminalSelect(e.params.data) });
                return;
            }
            if (parent.childNodes) {
                [...parent.childNodes].forEach(recurse);
            }
        };

        // select the target node
        var target = $('.cart-collaterals, #order_review, .wc-block-components-totals-shipping');
        let terminalIdElem = $('.woo_lithuaniapost_lpexpress_terminal_id');
        if (terminalIdElem.length > 0) {
            let eventSelect = $(terminalIdElem).select2({
                width: 'resolve',
                matcher(params, data) {
                    return terminalMatcher(params, data);
                },
            });
            eventSelect.on("select2:select", function (e) { onTerminalSelect(e.params.data) });
        }

        if (target) {
            // create an observer instance
            var observer = new MutationObserver(function (mutations) {
                //loop through the detected mutations(added controls)
                mutations.forEach(function (mutation) {
                    for (const node of mutation.addedNodes) {
                        recurse(node);
                    }
                });
            });
            let obsConfig = {
                childList: true,
                characterData: true,
                attributes: true,
                subtree: true
            };
            target.each(function () {
                observer.observe(this, obsConfig);
            });

            // later, you can stop observing
            //observer.disconnect();
        }
    });
})(jQuery);
// source --> https://lohnapood.ee/wp-content/plugins/woo-lithuaniapost-main/public/js/woo-lithuaniapost-lpexpress-terminal-block.js?ver=4.0.29 
(function ($) {
    'use strict';

    function attachTerminalDropdown() {
        let checkedShippingMethodLabel = $('.wc-block-components-shipping-rates-control .wc-block-components-radio-control__option-checked');
        if (checkedShippingMethodLabel.length > 0) {
            let input = $(checkedShippingMethodLabel).find('input');
            if (input) {
                if (input.val() && input.val().indexOf('woo_lithuaniapost_lpexpress_terminal') !== -1) {
                    let terminalLabel = $('.woo_lithuaniapost_lpexpress_terminal_label');
                    if (terminalLabel.length > 0) {
                        let terminalInput = $('#' + input.val().replace(":", "_") + '.woo_lithuaniapost_shipping_method_terminal');
                        if (terminalInput.length > 0) {
                            terminalLabel.detach();
                            terminalLabel.appendTo(checkedShippingMethodLabel);
                            $(terminalLabel).show();
                        } else {
                            $(terminalLabel).hide();
                        }
                    }
                }
            }
            return true;
        }
        return false;
    }

    function loopAttachTerminalDropdown() {
        if (!attachTerminalDropdown()) {
            setTimeout(() => {
                loopAttachTerminalDropdown()
            }, 1000);
        }
    }

    $(document).ready(function () {
        $(document).delegate('.wp-site-blocks, .wp-block-woocommerce-cart-order-summary-block, .wp-block-woocommerce-checkout-shipping-methods-block', 'change', function (e) {
            attachTerminalDropdown();
        });
        loopAttachTerminalDropdown();
    });
})(jQuery);
// source --> https://lohnapood.ee/wp-content/plugins/woo-lithuaniapost-main/public/js/woo-lithuaniapost-shipping-logo.js?ver=4.0.29 
(function ($) {
    'use strict';

    function startListeningForMutations(elements, matcher, callback) {

        const recurse = (parent) => {

            for (let match in matcher) {
                const parentValue = parent[match];
                const matcherValue = matcher[match];
                if (!parentValue || (parentValue !== matcherValue && !String(parentValue).includes(matcherValue))) {
                    if (parent.childNodes) {
                        [...parent.childNodes].forEach(recurse);
                    }
                    return;
                }
            }
            callback(parent);
        };

        // select the target node
        var target = $(elements);

        if (target) {
            // create an observer instance
            var observer = new MutationObserver(function (mutations) {
                //loop through the detected mutations(added controls)
                mutations.forEach(function (mutation) {
                    for (const node of mutation.addedNodes) {
                        recurse(node);
                    }
                });
            });
            let obsConfig = {
                childList: true,
                characterData: true,
                attributes: true,
                subtree: true
            };
            target.each(function () {
                observer.observe(this, obsConfig);
            });

            // later, you can stop observing
            //observer.disconnect();
        }
    }

    function attachShippingLogos() {
        const shippingMethods = $("input[type='radio'][value^=woo_lithuaniapost_lpexpress_terminal]");
        if (shippingMethods.length > 0) {
            $(shippingMethods).each(function (index, input) {
                attachLogo(input);
            });
            return true;
        }
        return false;
    }

    function attachLogo(shippingMethodElement) {
        const imgUrl = woo_lithuaniapost.shipping_logo_url;
        if ($(shippingMethodElement).next().filter((index, element) => $(element).prop('nodeName') === 'IMG').length === 0) {
            $(shippingMethodElement).after("<img style='max-width:45px; max-height:25px; padding-right: 0.1em;' src=" + imgUrl + ">");
        }
    }

    $(document).ready(function () {
        const elementMatcher = {
            nodeName: 'INPUT',
            type: 'radio',
            value: 'woo_lithuaniapost_lpexpress_terminal'
        };
        startListeningForMutations(document, elementMatcher, function (matchedElement) {
            attachLogo(matchedElement);
        });
        attachShippingLogos();
    });

})(jQuery);