(function ($) {
    $( document ).ready(
        function () {

            console.log( "Inpost: order-metabox ready" );

            const { __, _x, _n, sprintf } = window.wp.i18n;
            const log_file_warning  = __( 'Also you can check log file', 'inpost-international' );
            const log_file_warning_order  = __( 'Check log file for order # ', 'inpost-international' );
            const server_warning  = __( 'Unexpected response from server.', 'inpost-international' );

            if (typeof inpost_intl_order_metabox === 'undefined' || inpost_intl_order_metabox === null) {
                return false;
            }

            let inpost_intl_geowidget_modal;
            let inpost_global_geowidget_api = null;
            let geowidget_countries         = inpost_intl_order_metabox.shipping_country;
            let coords                      = null;

            let token   = inpost_intl_order_metabox.geowidget_token;
            let config  = 'parcelCollect';
            let content = 'Inpost Global Geowidget';

            let inpost_international_ometabox = {
                init_modal: function () {

                    inpost_intl_geowidget_modal = document.createElement( 'div' );

                    content = '<inpost-geowidget ' +
                        'id="inpost-global-geowidget" ' +
                        'country="' + geowidget_countries + '" ' +
                        'onpoint="inpost_international_onpoint_select_callback" ' +
                        'token="' + token + '" ' +
                        'language="pl" ' +
                        'config="' + config + '"></inpost-geowidget>';

                    let modal_html = '<div ' +
                        'class="inpost_intl_geowidget_modal"' +
                        ' id="inpost_intl_geowidget_modal_dynamic">' +
                        '<div class="inpost_intl_geowidget_modal_inner">' +
                        '<span id="inpost_international_close_modal_cross">&times;</span>' +
                        '<div class="inpost_intl_geowidget_modal_inner_content">' + content + '</div>' +
                        '</div>' +
                        '</div>';

                    inpost_intl_geowidget_modal.innerHTML = modal_html;

                    document.body.appendChild( inpost_intl_geowidget_modal );

                    const geowidget = document.getElementById( 'inpost-global-geowidget' );

                    geowidget.addEventListener(
                        'inpost.geowidget.init',
                        function (event) {
                            inpost_global_geowidget_api = event.detail.api;
                        }
                    );
                },

                set_map_config: function (map_config) {
                    let modal_inner_content = $( '.inpost_intl_geowidget_modal_inner_content' );
                    if (typeof modal_inner_content != 'undefined' && modal_inner_content !== null) {
                        $( '#inpost-global-geowidget' ).attr( 'config', map_config );
                    }
                },

                set_geowidget_position: function (coords, zoom = 12 ) {
                    if (typeof inpost_global_geowidget_api != 'undefined' && inpost_global_geowidget_api !== null) {
                        try {
                            inpost_global_geowidget_api.changePosition( coords, zoom );
                        } catch (error) {
                            console.error( "An error occurred: " + error.message );
                        }
                        console.log("current_lang: ");
                        console.log(inpost_intl_order_metabox.current_lang);

                        /*try {
                            let current_lang = inpost_intl_order_metabox.current_lang;
                            current_lang = current_lang.toLowerCase();
                            const arr = ['pt', 'pl', 'es', 'nl', 'it', 'fr'];
                            if (arr.indexOf(current_lang) !== -1) {
                                console.log('Translation exists for this language');
                            } else {
                                current_lang = 'en';
                            }
                            inpost_global_geowidget_api.changeLanguage( current_lang );
                        } catch (error) {
                            console.error( "An error occurred when we try to cahnge map language: " + error.message );
                        }*/
                    }
                },

                wait_for_element: function (selector) {
                    return new Promise(
                        function (resolve) {
                            if (document.querySelector( selector )) {
                                return resolve( document.querySelector( selector ) );
                            }
                            let observer = new MutationObserver(
                                function (mutations) {
                                    if (document.querySelector( selector )) {
                                        resolve( document.querySelector( selector ) );
                                        observer.disconnect();
                                    }
                                }
                            );
                            observer.observe(
                                document.body,
                                {
                                    childList: true,
                                    subtree: true
                                }
                            );
                        }
                    );
                },



                reference_field_counter: function ( point ) {
                    let maxChars = 100;
                    let textLength = 0;
                    let comment = "";
                    let outOfChars = 'Osiągnąłeś limit znaków: ' + maxChars;
                    let order_note = "<?php echo esc_html( $is_order_note_exists ); ?>";

                    let char_counter = $('.inpost-intl-charcount').val();
                    if (typeof char_counter != 'undefined' && char_counter !== null) {
                        textLength = char_counter.length;
                        let count = maxChars - textLength;
                        if (count >= maxChars) {
                            $('#inp-intl-char-num').text(outOfChars);
                            $('.inpost-intl-charcount-label').addClass('limit');
                            if (order_note) {
                                $('.inp-intl-charcount-limit-exceeded').addClass('show');
                            }
                        } else {
                            $('#inp-intl-char-num').text(count + ' znaków do końca. Maksimum 100 znaków.');
                            $('.inpost-intl-charcount-label').removeClass('limit');
                            $('.inp-intl-charcount-limit-exceeded').removeClass('show');
                        }

                        /* fix val so it counts carriage returns */
                        $.valHooks.textarea = {
                            get: function (e) {
                                return e.value.replace(/\r?\n/g, "\r\n");
                            }
                        };
                    }

                    $('.inpost-intl-charcount').keyup(function() {
                        checkCount();
                        comment = $(this).val();
                    });

                    function checkCount() {
                        textLength = $('.inpost-intl-charcount').val().length;
                        if (textLength >= maxChars) {
                            $('#inp-intl-char-num').text(outOfChars);
                            $('.inpost-intl-charcount-label').addClass('limit');
                        }
                        else {
                            count = maxChars - textLength;
                            $('#inp-intl-char-num').text(count + ' znaków do końca. Maksimum 100 znaków.');
                            $('.inpost-intl-charcount-label').removeClass('limit');
                        }
                    }

                },

                callback_on_locker_point_select: function ( point ) {

                },





                get_map_config_based_on_instance_id: function (instance_id, method) {
                    let map_config     = 'parcelCollect';
                    let selected_method = inpost_intl_order_metabox.shipping_method;

                    if (typeof instance_id != 'undefined' && instance_id !== undefined && instance_id !== null && instance_id !== '') {
                        if (typeof selected_method != 'undefined' && selected_method !== null) {
                            let method_id = selected_method.inpost_title;
                            if (method_id === 'easypack_parcel_machines_cod') {
                                map_config = 'parcelCollectPayment';
                            }
                            if (method_id === 'easypack_shipping_courier_c2c') {
                                map_config = 'parcelSend';
                            }
                            if (method_id === 'easypack_parcel_machines_weekend' || method_id === 'easypack_parcel_machines_weekend_cod') {
                                map_config = 'parcelCollect247';
                            }
                        }

                    } else {
                        if (method === 'easypack_parcel_machines_cod') {
                            map_config = 'parcelCollectPayment';
                        }
                        if (method === 'easypack_shipping_courier_c2c') {
                            map_config = 'parcelSend';
                        }
                        if (method === 'easypack_parcel_machines_weekend' || method === 'easypack_parcel_machines_weekend_cod') {
                            map_config = 'parcelCollect247';
                        }
                    }

                    return map_config;
                },

                open_map_modal: function () {
                    let map_modal = document.getElementById( 'inpost_intl_geowidget_modal_dynamic' );
                    if (typeof map_modal != 'undefined' && map_modal !== null) {
                        map_modal.style.display = 'flex';
                    }
                },
                block_scroll: function () {
                    const scrollTop  = window.pageYOffset || document.documentElement.scrollTop;
                    const scrollLeft = window.pageXOffset || document.documentElement.scrollLeft;
                    window.onscroll  = function () {
                        window.scrollTo( scrollLeft, scrollTop );
                    };
                },
                unblock_scroll: function () {
                    window.onscroll = function () {};
                },
                set_initial_geowidget_position: function () {
                    let country_code = inpost_intl_order_metabox.shipping_country;
                    if ('PL' === country_code) {
                        coords = {longitude: 20.318968, latitude: 49.731131};
                    }
                    if ('BE' === country_code) {
                        // 50.8518425654914, 4.351724313951752
                        coords = {longitude: 4.351724, latitude: 50.851842};
                    }
                    if ('IT' === country_code) {
                        // 41.896154821545316, 12.496158445220988
                        coords = {longitude: 12.496158, latitude: 41.896154};
                    }
                    if ('FR' === country_code) {
                        // 48.85747020725999, 2.3576749096813567
                        coords = {longitude: 2.357674, latitude: 48.857470};
                    }
                    if ('LU' === country_code) {
                        // 49.612793733267004, 6.141375112248663
                        coords = {longitude: 6.141375, latitude: 49.612793};
                    }
                    if ('PT' === country_code) {
                        // 38.73202335039995, -8.871431250019862
                        coords = {longitude: -8.871431, latitude: 38.732023};
                    }
                    if ('ES' === country_code) {
                        // 40.47738373459267, -3.7204805103180743
                        coords = {longitude: -3.720480, latitude: 40.4773837};
                    }
                    if ('NL' === country_code) {
                        // 52.36841126990683, 5.106379478772352
                        coords = {longitude: 5.106379, latitude: 52.368411};
                    }
                    inpost_international_ometabox.set_geowidget_position( coords );
                }

            };

            inpost_international_ometabox.init_modal();
            inpost_international_ometabox.reference_field_counter();


            if (typeof inpost_intl_order_metabox != 'undefined' && inpost_intl_order_metabox !== null) {
                config = inpost_international_ometabox.get_map_config_based_on_instance_id( inpost_intl_order_metabox.instance_id, inpost_intl_order_metabox.method );
            }

            $( '#inpost_intl_locker_id' ).on(
                'click',
                function () {
                    if ( typeof inpost_intl_geowidget_modal != 'undefined' && inpost_intl_geowidget_modal !== null ) {

                        if ( ! coords ) {
                            inpost_international_ometabox.set_initial_geowidget_position();
                        }
                        inpost_international_ometabox.block_scroll();
                        inpost_international_ometabox.open_map_modal();
                    }
                }
            );

            $( '#inpost_international_close_modal_cross' ).on(
                'click',
                function () {
                    inpost_international_ometabox.unblock_scroll();
                    let map_modal = document.getElementById( 'inpost_intl_geowidget_modal_dynamic' );
                    if (typeof map_modal != 'undefined' && map_modal !== null) {
                        map_modal.style.display = 'none';
                    }
                }
            );

            $( '.inpost_intl_dimensions' ).on(
                'change',
                function () {
                    if ($('#inpost_intl_package_size_dimensions option[value="custom"]').length === 0) {
                        // Append the new option.
                        $('#inpost_intl_package_size_dimensions').append(
                            $('<option>', {
                                value: 'custom',
                                text: 'Custom template'
                            })
                        );
                    }
                    $('#inpost_intl_package_size_dimensions').val('custom');
                    $( '#inpost_intl_used_template' ).val('custom');
                }
            );

            let selected_shipment_template = $( '#inpost_intl_package_size_dimensions' ).find(':selected').text();
            $( '#inpost_intl_used_template' ).val( selected_shipment_template );


            $( '#inpost_intl_package_size_dimensions' ).on(
                'change',
                function () {
                    if ($(this).find('option[value="custom"]').length !== 0) {
                        // Remove the "custom" option
                        $(this).find('option[value="custom"]').remove();
                    }

                    let length = '';
                    let width = '';
                    let height = '';
                    let weight = '';
                    let selected_template = [];
                    let selected_template_ind = $(this).val();
                    let saved_templates = inpost_intl_order_metabox.templates;

                    if (typeof saved_templates != 'undefined' && saved_templates !== null) {
                        selected_template = saved_templates[selected_template_ind];
                        //console.log( selected_template );
                        length = selected_template.length;
                        width = selected_template.width;
                        height = selected_template.height;
                        weight = selected_template.weight;
                    }

                    $('#inpost_intl_length').val(length);
                    $('#inpost_intl_width').val(width);
                    $('#inpost_intl_height').val(height);
                    $('#inpost_intl_weight').val(weight);

                    if( 'default' === $(this).val() ) {
                        $( '#inpost_intl_used_template' ).val('default');
                    } else {
                        $( '#inpost_intl_used_template' ).val($(this).find(':selected').text());
                    }

                    console.log( $(this).find(':selected').text() );


                }
            );


            const inputs = document.querySelectorAll('.inpost_intl_validated_input');
            const tooltip = document.createElement('div');
            tooltip.className = 'inpost-intl-tooltip';
            document.body.appendChild(tooltip);
            if ( typeof inputs != 'undefined' && inputs !== null ) {
                let validationTimeout;

                inputs.forEach(function(input) {
                    input.addEventListener('input', function(e) {
                        clearTimeout(validationTimeout);  // Clear any existing timeout

                        validationTimeout = setTimeout(function() {
                            const value = parseFloat(this.value);
                            const min = parseFloat(this.min);
                            const max = parseFloat(this.max);
                            const step = parseFloat(this.step) || 1;

                            if (isNaN(value)) {
                                hideTooltip(this);
                                return;
                            }
                            // Exit if the input is not a number.

                            if (value < min) {
                                showTooltip(this, `Min value ${min} is allowed only`);
                                this.value = min;
                            } else if (value > max) {
                                showTooltip(this, `Max value ${max} is allowed only`);
                                this.value = max;
                            } else {
                                hideTooltip(this);
                                // Round to nearest step
                                const roundedValue = Math.round(value / step) * step;
                                if (roundedValue !== value) {
                                    this.value = roundedValue.toFixed(getDecimalPlaces(step));
                                }
                            }
                        }.bind(this), 1500);  // 1500ms delay, adjust as needed
                    });
                });
            }

            function getDecimalPlaces(num) {
                if (Math.floor(num) === num) return 0;
                return num.toString().split(".")[1].length || 0;
            }

            function showTooltip(input, message) {
                // Remove any existing tooltip
                const existingTooltip = input.parentNode.querySelector('.inpost-intl-tooltip');
                if (existingTooltip) {
                    existingTooltip.remove();
                }

                // Create new tooltip
                const tooltip = document.createElement('div');
                tooltip.className = 'inpost-intl-tooltip';
                tooltip.textContent = message;

                // Style the tooltip
                tooltip.style.position = 'absolute';
                tooltip.style.backgroundColor = '#FCC905';
                tooltip.style.color = '#fff';
                tooltip.style.padding = '5px 10px';
                tooltip.style.borderRadius = '4px';
                tooltip.style.fontSize = '14px';
                tooltip.style.zIndex = '1000';
                tooltip.style.whiteSpace = 'nowrap';

                // Position the tooltip.
                const inputRect = input.getBoundingClientRect();
                tooltip.style.bottom = `${inputRect.height}px`;
                tooltip.style.left = '0';
                tooltip.style.transform = 'translateY(-5px)';
                // Move it 5px up.


                // Ensure the input's parent has a relative position.
                if (getComputedStyle(input.parentNode).position === 'static') {
                    input.parentNode.style.position = 'relative';
                }

                // Append the tooltip to the input's parent.
                input.parentNode.appendChild(tooltip);

                // Remove the tooltip after 3 seconds.
                setTimeout(function() {
                    tooltip.remove();
                }, 3000);
            }

            function hideTooltip(input) {
                const existingTooltip = input.parentNode.querySelector('.inpost-intl-tooltip');
                if (existingTooltip) {
                    existingTooltip.remove();
                }
            }


            /*function objectToString(obj) {
                return Object.entries(obj)
                    .map(([key, value]) => `${key} - ${value}`)
                    .join(', ');
            }*/

            function objectToString(obj) {
                return Object.entries(obj)
                    .map(function(entry) {
                        var key = entry[0];
                        var value = entry[1];
                        return key + ' - ' + value;
                    })
                    .join(', ');
            }


            function process_unknown_variable(variable) {
                if (typeof variable === 'object' && variable !== null && !Array.isArray(variable)) {
                    return objectToString(variable);
                }
                if (typeof variable === 'string') {
                    try {
                        const parsedJSON = JSON.parse(variable);
                        if (typeof parsedJSON === 'object' && parsedJSON !== null) {
                            return objectToString(parsedJSON);
                        }
                    } catch (e) {

                    }
                }

                return variable;
            }


            function process_events(events) {
                // Sort events by timestamp, newest first.
                events.sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp));

                // Create HTML table for events
                let table_html = `
                    <div class="tracking-events-container">
                    <table class="tracking-events">
                        <thead>
                            <tr>
                                <th>Data i czas</th>
                                <th>Kod</th>
                                <th>Tytuł</th>
                                <th>Opis</th>
                            </tr>
                        </thead>
                        <tbody>
                `;

                events.forEach(event => {
                    const date = new Date(event.timestamp);
                    const formatted_date = `${date.getDate().toString().padStart(2, '0')}.${(date.getMonth() + 1).toString().padStart(2, '0')}.${date.getFullYear()}`;
                    const formatted_time = date.toTimeString().split(' ')[0];

                    table_html += `
                        <tr>
                            <td>${formatted_date} ${formatted_time}</td>
                            <td>${event.eventCode}</td>
                            <td>${event.eventTitle}</td>
                            <td>${event.eventDescription}</td>
                        </tr>
                    `;
                });

                table_html += `
                        </tbody>
                    </table></div>
                `;

                return table_html;
            }



            // open modal with map.
            document.addEventListener(
                'click',
                function (e) {
                    e          = e || window.event;
                    let target = e.target || e.srcElement;

                    if (target.hasAttribute( 'id' ) && target.getAttribute( 'id' ) === 'inpost_intl_get_label_order') {

                        e.preventDefault();

                        let order_id = $('#inpost_international_order_id').val();
                        let uuid = $('#inpost_international_uuid').val();

                        let data = {
                            action: 'inpost_international',
                            inpost_intl_action: 'inpost_international_get_label',
                            security: inpost_intl_order_metabox.nonce,
                            order_id: order_id,
                            uuid: uuid,
                        };

                        $.ajax({
                            type: 'POST',
                            dataType: 'json',
                            //dataType: 'blob',
                            url: inpost_intl_order_metabox.ajaxurl,
                            data: data,
                            beforeSend: function(jqXHR) {
                                jqXHR.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');

                                $( '.inpost_intl_error_response' ).each(
                                    function (i) {
                                        $(this).remove();
                                    })
                                $('#inpost_intl_create_package_order').prop('disabled', true );
                                $('#inpost_international_order_metabox').css({ 'opacity': '0.6', 'cursor': 'wait' });
                                $('.inpost_intl_preloader').show();
                            },
                            success: function( response ) {
                                console.log( response );

                                let woo_logs_section_url = ' <a target="blank_" href="' + inpost_intl_order_metabox.log_path + '">here</a>';

                                if (response.pdf) {

                                    let filename = 'inpost_int_zamowenie_' + order_id + '.pdf';

                                    // Decode the base64 string.
                                    let binaryString = window.atob(response.pdf);
                                    let binaryLen = binaryString.length;
                                    let bytes = new Uint8Array(binaryLen);
                                    for (let i = 0; i < binaryLen; i++) {
                                        bytes[i] = binaryString.charCodeAt(i);
                                    }

                                    // download file.
                                    let blob = new Blob([bytes], {type: 'application/pdf'});
                                    let link = document.createElement('a');
                                    link.href = window.URL.createObjectURL(blob);
                                    link.download = filename;
                                    document.body.appendChild(link);
                                    link.click();
                                    document.body.removeChild(link);

                                } else if (response.error) {
                                    let error = '';
                                    if (response.error_connection) {
                                        error = "<span class='inpost_intl_error_response' style='font-weight:bold; color:#ff0000'>" +
                                            "Error:<br> " + response.error_connection + "</span>";
                                    } else
                                    if (response.error_details) {
                                        // Handle error.
                                        error = "<span class='inpost_intl_error_response' style='font-weight:bold; color:#ff0000'>" +
                                            "Error:<br> " + response.error_details + ".<br>" +
                                            "Or " + log_file_warning_order + order_id + woo_logs_section_url + "</span>";
                                    } else {
                                        // Unexpected JSON response.
                                        error = "<span class='inpost_intl_error_response' style='font-weight:bold; color:#ff0000'>" +
                                            "Error:<br>" + server_warning + "<br>" + log_file_warning_order + order_id + woo_logs_section_url + "</span>";
                                    }
                                    $('#inpost_intl_error').append(error);
                                } else {
                                    let unknown_response = process_unknown_variable( response );
                                    error = "<span class='inpost_intl_error_response' style='font-weight:bold; color:#ff0000'>" +
                                        "Error:<br> " + unknown_response + ".<br>" + log_file_warning_order + order_id + woo_logs_section_url + "</span>";
                                    $('#inpost_intl_error').append(error);
                                }





                            },
                            error: function (jqXHR, textStatus, errorThrown) {

                                let response = jqXHR.responseText;
                                let cleanResponse = response.replace(/<!--[\s\S]*?-->/g, '');
                                try {
                                    let jsonResponse = JSON.parse(cleanResponse);
                                    if (jsonResponse.pdf) {
                                        console.log('Error, but - yes, PDF');

                                        let filename = 'inpost_int_zamowenie_' + order_id + '.pdf';

                                        // Decode the base64 string
                                        let binaryString = window.atob(jsonResponse.pdf);
                                        let binaryLen = binaryString.length;
                                        let bytes = new Uint8Array(binaryLen);
                                        for (let i = 0; i < binaryLen; i++) {
                                            bytes[i] = binaryString.charCodeAt(i);
                                        }

                                        // download file.
                                        let blob = new Blob([bytes], {type: 'application/pdf'});
                                        let link = document.createElement('a');
                                        link.href = window.URL.createObjectURL(blob);
                                        link.download = filename;
                                        document.body.appendChild(link);
                                        link.click();
                                        document.body.removeChild(link);
                                    }

                                } catch (e) {
                                    console.error("Error during JSON parse:", e);

                                    let color = "#e03636";
                                    let error = "<span class='inpost_intl_error_response' style='font-weight:bold; color: " + color + "'>Error:<br> " + errorThrown + ', ' + e + ' ' + jqXHR.responseText + "</span>";
                                    $('#inpost_intl_error').append(error);
                                    console.log( "error response" );
                                    console.log( 'Error: ' + errorThrown + ' ' + jqXHR.responseText );

                                }



                            },
                            complete: function(response) {
                                console.log( "complete response" );
                                $('.inpost_intl_preloader').hide();
                                $('#inpost_international_order_metabox').css({ 'opacity': '1', 'cursor': 'unset' });
                                $('#inpost_intl_create_package_order').prop('disabled', false );
                            }
                        });
                    }

                    if (target.hasAttribute( 'id' ) && target.getAttribute( 'id' ) === 'inpost_international_close_modal_cross') {
                        inpost_international_ometabox.unblock_scroll();
                        let map_modal = document.getElementById( 'inpost_intl_geowidget_modal_dynamic' );
                        if (typeof map_modal != 'undefined' && map_modal !== null) {
                            map_modal.style.display = 'none';
                        }
                    }

                    if (target.hasAttribute( 'id' ) && target.getAttribute( 'id' ) === 'inpost_intl_order_metabox_locker_id') {

                        e.preventDefault();
                        if ( typeof inpost_intl_geowidget_modal != 'undefined' && inpost_intl_geowidget_modal !== null ) {

                            if ( ! coords ) {
                                inpost_international_ometabox.set_initial_geowidget_position();
                            }
                            inpost_international_ometabox.block_scroll();
                            inpost_international_ometabox.open_map_modal();
                        }
                    }


                    if (target.hasAttribute( 'id' ) && target.getAttribute( 'id' ) === 'inpost_intl_metabox_tracking_number') {

                        e.preventDefault();
                        //$('#inpost_intl_status_modal').addClass('active');
                        let tracking_number = target.getAttribute( 'data-id' );
                        console.log( tracking_number );

                        let order_id = $('#inpost_international_order_id').val();

                        let data = {
                            action: 'inpost_international',
                            inpost_intl_action: 'inpost_international_get_status',
                            security: inpost_intl_order_metabox.nonce,
                            tracking_number: tracking_number,
                            order_id: order_id,
                        };

                        $.ajax({
                            type: 'POST',
                            dataType: 'json',
                            //dataType: 'blob',
                            url: inpost_intl_order_metabox.ajaxurl,
                            data: data,
                            beforeSend: function(jqXHR) {
                                jqXHR.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');

                                $( '.inpost_intl_error_response' ).each(
                                    function (i) {
                                        $(this).remove();
                                    })
                                $('#inpost_intl_create_package_order').prop('disabled', true );
                                $('#inpost_international_order_metabox').css({ 'opacity': '0.6', 'cursor': 'wait' });
                                $('.inpost_intl_preloader').show();
                            },
                            success: function( response ) {
                                let woo_logs_section_url = ' <a target="blank_" href="' + inpost_intl_order_metabox.log_path + '">here</a>';

                                const tracking_data = response[0];
                                if (typeof tracking_data != 'undefined' && tracking_data !== null) {
                                    let events = tracking_data.events;
                                    if (typeof events != 'undefined' && events !== null) {
                                        let modal_header = '';
                                        let modal_subheader = '';

                                        const events_html = process_events( events );

                                        const destination = tracking_data.destination;
                                        if (typeof destination != 'undefined' && destination !== null) {
                                            modal_header = `${destination.locationType} ${destination.name}`;
                                            modal_subheader = [
                                                destination.countryCode,
                                                destination.postalCode,
                                                destination.province,
                                                destination.city,
                                                destination.street,
                                                destination.building,
                                                destination.flat
                                            ].filter(Boolean).join(', ');
                                        }


                                        $( '.inpost_intl_temp_data' ).each(
                                            function (i) {
                                                $(this).remove();
                                            })
                                        $('.inpost_intl_status_modal_text').html( events_html );
                                        $('.inpost_intl_status_modal_tracking').text( tracking_number );
                                        $('.inpost_intl_status_modal_title').append( '<h3 class="inpost_intl_temp_data">' + modal_header + '</h3>' );
                                        $('.inpost_intl_status_modal_title').append( '<h4 class="inpost_intl_temp_data">' + modal_subheader + '</h4>' );
                                        $('#inpost_intl_status_modal').addClass('active');

                                    }

                                } else {
                                    if (response.error) {
                                        let error = '';
                                        if (response.error_connection) {
                                            error = "<span class='inpost_intl_error_response' style='font-weight:bold; color:#ff0000'>" +
                                                "Error:<br> " + response.error_connection + "</span>";
                                        } else
                                        if (response.error_details) {
                                            // Handle error.
                                            error = "<span class='inpost_intl_error_response' style='font-weight:bold; color:#ff0000'>" +
                                                "Error:<br> " + response.error_details + ".<br>" +
                                                "Or " + log_file_warning_order + order_id + woo_logs_section_url + "</span>";
                                        } else {
                                            // Unexpected JSON response.
                                            error = "<span class='inpost_intl_error_response' style='font-weight:bold; color:#ff0000'>" +
                                                "Error:<br>" + server_warning + "<br>" + log_file_warning_order + order_id + woo_logs_section_url + "</span>";
                                        }
                                        console.log(error);
                                        $('#inpost_intl_status_error').append(error);
                                    }
                                }

                            },
                            error: function (jqXHR, textStatus, errorThrown) {
                                let response = jqXHR.responseText;
                                console.error("Error response:");
                                console.error(response);

                                let cleanResponse = response.replace(/<!--[\s\S]*?-->/g, '');
                                try {
                                    let jsonResponse = JSON.parse(cleanResponse);

                                    if (jsonResponse.error) {
                                        let error = '';
                                        if (jsonResponse.error_connection) {
                                            error = "<span class='inpost_intl_error_response' style='font-weight:bold; color:#ff0000'>" +
                                                "Error:<br> " + jsonResponse.error_connection + "</span>";
                                        } else
                                        if (jsonResponse.error_details) {
                                            // Handle error.
                                            error = "<span class='inpost_intl_error_response' style='font-weight:bold; color:#ff0000'>" +
                                                "Error:<br> " + jsonResponse.error_details + ".<br>" +
                                                "Or " + log_file_warning_order + order_id + woo_logs_section_url + "</span>";
                                        } else {
                                            // Unexpected JSON response.
                                            error = "<span class='inpost_intl_error_response' style='font-weight:bold; color:#ff0000'>" +
                                                "Error:<br>" + server_warning + "<br>" + log_file_warning_order + order_id + woo_logs_section_url + "</span>";
                                        }

                                        $('#inpost_intl_status_error').append(error);
                                    } else {

                                        let tracking_data = jsonResponse[0];
                                        if (typeof tracking_data != 'undefined' && tracking_data !== null) {
                                            let events = tracking_data.events;
                                            if (typeof events != 'undefined' && events !== null) {
                                                let modal_header = '';
                                                let modal_subheader = '';

                                                const events_html = process_events( events );

                                                const destination = tracking_data.destination;
                                                if (typeof destination != 'undefined' && destination !== null) {
                                                    modal_header = `${destination.locationType} ${destination.name}`;
                                                    modal_subheader = [
                                                        destination.countryCode,
                                                        destination.postalCode,
                                                        destination.province,
                                                        destination.city,
                                                        destination.street,
                                                        destination.building,
                                                        destination.flat
                                                    ].filter(Boolean).join(', ');
                                                }

                                                $( '.inpost_intl_temp_data' ).each(
                                                    function (i) {
                                                        $(this).remove();
                                                    })
                                                $('.inpost_intl_status_modal_text').html( events_html );
                                                $('.inpost_intl_status_modal_tracking').text( tracking_number );
                                                $('.inpost_intl_status_modal_title').append( '<h3 class="inpost_intl_temp_data">' + modal_header + '</h3>' );
                                                $('.inpost_intl_status_modal_title').append( '<h4 class="inpost_intl_temp_data">' + modal_subheader + '</h4>' );
                                                $('#inpost_intl_status_modal').addClass('active');

                                            }
                                        }
                                    }

                                } catch (e) {
                                    console.error("Error during JSON parse:", e);

                                    let color = "#e03636";
                                    let error = "<span class='inpost_intl_error_response' style='font-weight:bold; color: " + color + "'>Error:<br> " + errorThrown + ', ' + e + ' ' + jqXHR.responseText + "</span>";
                                    $('#inpost_intl_status_error').append(error);
                                    console.log( "error response" );
                                    console.log( 'Error: ' + errorThrown + ' ' + jqXHR.responseText );

                                }
                            },
                            complete: function(response) {
                                console.log( "complete response" );
                                $('.inpost_intl_preloader').hide();
                                $('#inpost_international_order_metabox').css({ 'opacity': '1', 'cursor': 'unset' });
                                $('#inpost_intl_create_package_order').prop('disabled', false );
                            }
                        });
                    }


                    if (target.hasAttribute( 'id' ) && target.getAttribute( 'id' ) === 'inpost_intl_status_modal_close_button') {

                        e.preventDefault();
                        $('#inpost_intl_status_modal').removeClass('active');
                    }

                    if (target.hasAttribute( 'id' ) && target.getAttribute( 'id' ) === 'inpost_intl_create_package_order') {
                        e.preventDefault();

                        let order_id = $('#inpost_international_order_id').val();
                        let insurance_amounts = $('#inpost_intl_insurance_amount').val();
                        //let size = $('#inpost_intl_package_size').val();

                        let data = {
                            action: 'inpost_international',
                            inpost_intl_action: 'inpost_international_create_package',
                            security: inpost_intl_order_metabox.nonce,
                            order_id: order_id,
                            locker_id: $('#inpost_intl_order_metabox_locker_id').val(),
                            parcel: {
                                length: $('#inpost_intl_length').val(),
                                width: $('#inpost_intl_width').val(),
                                height: $('#inpost_intl_height').val(),
                                weight: $('#inpost_intl_weight').val(),
                            },
                            send_method: $('#inpost_intl_send_method').val(),
                            insurance_amounts: insurance_amounts,
                            label_reference: $('#inpost_intl_reference_number').val(),
                            used_template: $('#inpost_intl_used_template').val()
                        };

                        $.ajax({
                            type: 'POST',
                            dataType: 'text',
                            url: inpost_intl_order_metabox.ajaxurl,
                            data: data,
                            beforeSend: function() {
                                $( '.inpost_intl_error_response' ).each(
                                    function (i) {
                                        $(this).remove();
                                    })
                                $('#inpost_intl_create_package_order').prop('disabled', true );
                                $('#inpost_international_order_metabox').css({ 'opacity': '0.6', 'cursor': 'wait' });
                                $('.inpost_intl_preloader').show();
                            },
                            success: function(response) {
                                console.log( "success response" );
                                console.log( response );

                                let woo_logs_section_url = ' <a target="blank_" href="' + inpost_intl_order_metabox.log_path + '">here</a>';

                                try {
                                    // Try to parse the response as JSON.
                                    let response_cleared = response.replace(/<!--[\s\S]*?-->/g, '');
                                    let maybe_json = JSON.parse(response_cleared);

                                    // If parsing succeeds, it's likely an error response.
                                    if (maybe_json.error) {
                                        let error = '';
                                        if (maybe_json.error_connection) {
                                            error = "<span class='inpost_intl_error_response' style='font-weight:bold; color:#ff0000'>" +
                                                "Error:<br>" + maybe_json.error_connection + "</span>";
                                        } else
                                        if (maybe_json.error_details) {
                                            // Handle error.
                                            error = "<span class='inpost_intl_error_response' style='font-weight:bold; color:#ff0000'>" +
                                                "Error:<br>" + maybe_json.error_details + "<br>" + log_file_warning +
                                                " 'inpost-international-order-" + order_id + "-request-response'"  + woo_logs_section_url + "</span>";
                                        } else {
                                            // Unexpected JSON response.
                                            error = "<span class='inpost_intl_error_response' style='font-weight:bold; color:#ff0000'>" +
                                                "Error:<br>" + server_warning + "<br>" + log_file_warning_order + order_id + woo_logs_section_url + "</span>";
                                        }
                                        $('#inpost_intl_error').append(error);

                                    }
                                } catch (e) {
                                    // If parsing fails, it's likely HTML.
                                    let inpost_metabox = $('#inpost_international_order_metabox').find('.inside');

                                    if (typeof response != 'undefined' && response !== null && '' !== response ) {
                                        $(inpost_metabox).replaceWith('<div class="inside">' + response + '</div>');
                                    } else {
                                        error = "<span class='inpost_intl_error_response' style='font-weight:bold; color:#ff0000'>" +
                                            "Error:<br>Response is empty<br>" + log_file_warning_order + order_id + woo_logs_section_url + "</span>";
                                        $('#inpost_intl_error').append(error);
                                    }
                                }

                            },
                            error: function (jqXHR, textStatus, errorThrown) {

                                let color = "#e03636";
                                let error = "<span class='inpost_intl_error_response' style='font-weight:bold; color: " + color + "'>Error: " + errorThrown + ' ' + jqXHR.responseText + "</span>";
                                $('#inpost_intl_error').append(error);
                                console.log( "error response" );
                                console.log( 'Error: ' + errorThrown + ' ' + jqXHR.responseText );

                            },
                            complete: function(response) {
                                console.log( "complete response" );
                                $('.inpost_intl_preloader').hide();
                                $('#inpost_international_order_metabox').css({ 'opacity': '1', 'cursor': 'unset' });
                                $('#inpost_intl_create_package_order').prop('disabled', false );
                            }
                        });

                    }
                }
            );

            document.addEventListener(
                'inpost_international_onpoint_select_callback',
                function (point) {
                    console.log( point.detail );
                    $( '#inpost_intl_order_metabox_locker_id' ).val( point.detail.name );
                    window.onscroll = function () {};
                    let map_modal = document.getElementById( 'inpost_intl_geowidget_modal_dynamic' );
                    if (typeof map_modal != 'undefined' && map_modal !== null) {
                        map_modal.style.display = 'none';
                    }
                }
            );
        }
    );

})( jQuery );

