jQuery(function ($) {

    //Switch Tabs
    $(".plantshop-wc-tabs-wrapper li").on("click", function (e) {

        e.preventDefault();

        const $tab = $(this);
        const target = $tab.find("a").attr("href");

        $tab.addClass("active").siblings().removeClass("active");

        $(target).removeClass("hidden").siblings(".plantshop-wc-tab-content").addClass("hidden");

    });


    //Repeater Template
    let rowIndex = {
        good_neighbors: $("#plantshop-wc_repeater_good_neighbors .plantshop-wc-repeater-row").length - 1,
        bad_neighbors: $("#plantshop-wc_repeater_bad_neighbors .plantshop-wc-repeater-row").length - 1,
    };

    $(".plantshop-wc-add-row").on("click", function (e) {

        e.preventDefault();

        const type = $(this).data("type");
        const template = wp.template("plantshop-wc-repeater-row-" + type);

        $("#plantshop-wc_repeater_" + type).append(template({index: ++rowIndex[type]}));

    });

    $(document).on("click", ".plantshop-wc-remove-row", function (e) {

        e.preventDefault();

        const type = $(this).data("type");
        --rowIndex[type];

        $(this).closest(".plantshop-wc-repeater-row").remove();

    });

});

//Neighbor Search
function plantshop_wc_hide_neighbor_container($container) {
    if ($container.is(':empty')) {
        return;
    }
    $container.html('');
    $container.css('display', 'none');
}

function plantshop_wc_get_current_post_id() {
    const url = new URL(location.href);
    return url.searchParams.has("post") ? String(url.searchParams.get("post") || '') : '';
}

function plantshop_wc_on_neighbor_click($input, $container, e) {
    const $target = jQuery(e.currentTarget);
    $input.val($target.text());
    $input.prev().val($target.data('id'));
    $container.html('').css('display', 'none');
}

function plantshop_wc_append_neighbor_item($list, $input, $container, element) {
    const $li = jQuery('<li>', {
        class: 'plantshop-wc-neighbor',
        text: element.name,
        'data-id': element.id
    });
    $li.on('click', function (e) {
        plantshop_wc_on_neighbor_click($input, $container, e);
    });
    $list.append($li);
}

function plantshop_wc_render_neighbor_response($input, $container, response) {
    const $list = jQuery('<ul></ul>');
    $input.on('focusout', function (e) {
        e.preventDefault();
    });

    if (!response.success) {
        const $li = jQuery('<li>', {
            class: 'plantshop-wc-no-neighbor',
            text: response.data
        });
        $list.append($li);
    } else {
        const elements = response.data.data;
        for (const element of elements) {
            plantshop_wc_append_neighbor_item($list, $input, $container, element);
        }
    }

    $container.append($list);
    $container.css('display', 'block');
}

function plantshop_wc_request_neighbors($input, $container, value) {
    jQuery.ajax({
        method: 'POST',
        url: window.plantshop_wc_ajax_tabs.url,
        data: {
            nonce: window.plantshop_wc_ajax_tabs.nonce,
            action: 'plantshop-wc_get_neighbors',
            title: value,
            current_id: plantshop_wc_get_current_post_id(),
        },
        success(response) {
            plantshop_wc_render_neighbor_response($input, $container, response);
        },
        error(xhr) {
            console.error(xhr);
        }
    });
}

function plantshop_wc_ajax_neighbor_search(input) {

    const $input = jQuery(input);
    const $container = $input.next();

    plantshop_wc_hide_neighbor_container($container);

    const value = $input.val();

    clearTimeout(plantshop_wc_ajax_neighbor_search.timer);

    if (value.length >= 3) {
        plantshop_wc_ajax_neighbor_search.timer = setTimeout(function () {
            plantshop_wc_request_neighbors($input, $container, value);
        }, 500);
    }
}
