jQuery(document).ready(function($) {
    function write_log(msg) {
        if (IS_WP_DEBUG === undefined || IS_WP_DEBUG === '1') {
            console.log(msg);
        }
    }
    // neleShowLoader();
    // hide the shipping methods until they are rendered in 1 page
    $('ul.subsubsub li a').each(function() {
        const href = $(this).attr('href');
        if (href && href.indexOf('section=nele_shipping_method_') !== -1) {
            $(this).closest('li').hide();
        }
    });

    let parentDiv = $("<div id='tabs' class='nele-tabs'></div>");
    const ul = $("<ul></ul>");
    parentDiv.append(ul);
    for (const smKey in neleShippingMethods) {
        const smData = neleShippingMethods[smKey];
        const smTitle = smData["title"];
        const smClass = smData["class"];
        const smOpts = smData["opts"];
        const tab = $("<li><a href='#"+smKey+"'>"+smTitle+"</a></li>");
        ul.append(tab);
        const tabCanvas = $("<div id='"+smKey+"'></div>");
        parentDiv.append(tabCanvas);
        const headerElem = $('h3.' + smClass.join('.')).first();
        const contentElem = headerElem.next('table.form-table').first();

        let innerDiv = $("<div id='tabs-" + smKey + "' class='nele-tabs'></div>");
        const innerUl = $("<ul></ul>");
        innerDiv.append(innerUl);
        for (const deliveryKey in smOpts) {
            const deliveryData = smOpts[deliveryKey];
            const deliveryTitle = deliveryData["title"];
            const deliveryClass = deliveryData["class"];
            const innerHeaderElem = $('h3.'+deliveryClass.join('.')).first();
            const innerContentElem = innerHeaderElem.next('table.form-table').first();
            const innerTab = $("<li><a href='#" + smKey + "_" + deliveryKey + "'>" + deliveryTitle + "</a></li>");
            innerUl.append(innerTab);
            const innerCanvas = $("<div id='" + smKey + "_" + deliveryKey + "'></div>");
            innerDiv.append(innerCanvas);
            innerCanvas.append(innerHeaderElem).append(innerContentElem);
        }
        tabCanvas.append(headerElem).append(contentElem).append(innerDiv);
    }

    const sectionGeneral = $("#woocommerce_nele_shipping_method_section_general");
    sectionGeneral.next('table.form-table').first().after(parentDiv);

    $( function() {
        $( ".nele-tabs" ).tabs();
    } );

    jQuery('ul.tabs').each(function(){
        // For each set of tabs, we want to keep track of
        // which tab is active and it's associated content
        var $active, $content, $links = jQuery(this).find('a');

        // If the location.hash matches one of the links, use that as the active tab.
        // If no match is found, use the first link as the initial active tab.
        $active = jQuery($links.filter('[href="'+location.hash+'"]')[0] || $links[0]);
        $active.addClass('active');

        $content = $($active[0].hash);

        // Hide the remaining content
        $links.not($active).each(function () {
            jQuery(this.hash).hide();
        });

        // Bind the click event handler
        jQuery(this).on('click', 'a', function(e){
            // Make the old tab inactive.
            $active.removeClass('active');
            $content.hide();

            // Update the variables with the new link and content
            $active = jQuery(this);
            $content = jQuery(this.hash);

            // Make the tab active.
            $active.addClass('active');
            $content.show();

            // Prevent the anchor's default click action
            e.preventDefault();
        });
    });
    // neleShowLoader(false);

    const checkbox = $("#woocommerce_nele_shipping_method_enabled");
    const formTable = $("#woocommerce_nele_shipping_method_section_general + .form-table");
    const tabs = $("#tabs");

    if (!checkbox.prop("checked")) {
        hideElements();
    } else {
        showElements();
    }

    checkbox.change(function() {
        if (!$(this).prop("checked")) {
            hideElements();
        } else {
            showElements();
        }
    });

    function hideElements() {
        sectionGeneral.hide();
        formTable.hide();
        tabs.hide();
    }

    function showElements() {
        sectionGeneral.show();
        formTable.show();
        tabs.show();
    }

    let $input = $('#woocommerce_nele_shipping_method_refresh_button');
    const $button = $('<button>', {
        id: $input.attr('id'),
        class: $input.attr('class'),
        name: $input.attr('name'),
        html: 'Refresh'
    });
    $input.replaceWith($button);
    $button.show();
    $button.after($('<span id="nele_refresh_message" style="display:none;"></span>'))

    $button.click(function(e) {
        e.preventDefault();
        $(this).hide();
        setTimeout(function() {
            const data = {
                action: 'nele_refresh_table_data'
            };
            $.post(ajaxurl, data)
                .done(function(response) {
                    $('#nele_refresh_message').html('Data refresh was scheduled.').css('color', 'green').show();
                })
                .fail(function(xhr, status, error) {
                    $('#nele_refresh_message').html('Error occurred during data refresh scheduling: ' + error).css('color', 'red').show();
                });
        }, 500); // Simulate 0.5 seconds delay for data refresh process
    });

    // jQuery(function($) {
    //     function refreshLogInfo() {
    //         $.ajax({
    //             url: ajaxurl,
    //             type: 'GET',
    //             data: {
    //                 action: 'get_log_entries'
    //             },
    //             success: function(response) {
    //                 const logField = $('#log_info');
    //                 logField.val(response);
    //                 // Scroll to the bottom of the textarea
    //                 logField.scrollTop(logField[0].scrollHeight);
    //             },
    //             error: function(xhr, status, error) {
    //                 console.error(error);
    //             }
    //         });
    //     }
    //
    //     function clearLogInfo() {
    //         $.ajax({
    //             url: ajaxurl,
    //             type: 'POST',
    //             data: {
    //                 action: 'clear_log_entries'
    //             },
    //             success: function(response) {
    //                 $('#log_info').val('');
    //                 alert(response);
    //             },
    //             error: function(xhr, status, error) {
    //                 console.error(error);
    //             }
    //         });
    //     }
    //
    //     $('#clear_log_info').click(function() {
    //         clearLogInfo();
    //     });
    //     refreshLogInfo();
    //     setInterval(refreshLogInfo, 5000);
    // });
});
