var $ = jQuery;
var bulk_editor_which_btn_clicked = "search";
$(document).ready(function () {
    var is_bulk_edited = false;
    $(document).on("click", ".connect_stripe_account_modal_open", function () {
        $("#connect_stripe_account_modal_id").show();
        $("#bulk_connect_stripe_account").focus();
    });
    $(document).on("click", ".close_connect_stripe_account_modal_btn, .cancel_change_btn", function () {
        $("#connect_stripe_account_modal_id").hide();
    });

    $(document).on("click", ".apply_change_btn", function () {
        $(".sps-modal-footer .popup-loader").show();
        $(".apply_change_btn").hide();
        setTimeout(function () {

            var bulk_selected_account = $("#bulk_connect_stripe_account").val();
            $(".sspscwsca_select").val(bulk_selected_account);
            $('.select_account_btns .edit-form-ok-btn', document).trigger("click");
            $("#connect_stripe_account_modal_id").hide();
            $(".sps-modal-footer .popup-loader").hide();
            $(".apply_change_btn").show();
            is_bulk_edited = true;
        }, 1000);

    });

    window.onclick = function (event) {
        if (event.target == $("#connect_stripe_account_modal_id")[0]) {
            $("#connect_stripe_account_modal_id").hide();
        }
    }


    $(document).on("click", ".transfer_type_modal_open", function () {
        $("#account_transfer_type_modal_id").show();
        $("#bulk_transfer_type").focus();
    });
    $(document).on("click", ".close_account_transfer_type_modal_btn, .transfer_type_cancel_change_btn", function () {
        $("#account_transfer_type_modal_id").hide();
    });

    $(document).on("click", ".transfer_type_apply_change_btn", function () {
        $(".sps-modal-footer .popup-loader").show();
        $(".transfer_type_apply_change_btn").hide();
        setTimeout(function () {
            var bulk_transfer_type = $("#bulk_transfer_type").val();
            $(".bsd_spscwt_type").val(bulk_transfer_type);
            $('.prod_selected_tt_btns .edit-form-ok-btn', document).trigger("click");

            $("#connect_stripe_account_modal_id").hide();
            $(".sps-modal-footer .popup-loader").hide();
            $("#account_transfer_type_modal_id").hide();
            $(".transfer_type_apply_change_btn").show();
            is_bulk_edited = true;
        }, 1000);


    });

    window.onclick = function (event) {
        if (event.target == $("#account_transfer_type_modal_id")[0]) {
            $("#account_transfer_type_modal_id").hide();
        }
    }

    $(document).on("click", ".value_modal_open", function () {
        $("#account_transfer_value_modal_id").show();
        $("#bulk_transfer_value").focus();
    });
    $(document).on("click", ".close_account_transfer_value_modal_btn, .transfer_value_cancel_change_btn", function () {
        $("#account_transfer_value_modal_id").hide();
    });

    $(document).on("click", ".transfer_value_apply_change_btn", function () {
        $(".sps-modal-footer .popup-loader").show();
        $(".transfer_value_apply_change_btn").hide();
        setTimeout(function () {
            var bulk_transfer_value = $("#bulk_transfer_value").val();

            $(".prod_tv_td_wrapper.edit-item-parent").each(function (index, element) {


                var selected_tt_value_wrapper = $(element).children(".selected_tt_value_wrapper");
                let connected_account_index = $(selected_tt_value_wrapper).attr("data-connected_account_index");
                if ($("#bsd_spscwt_type_" + connected_account_index).length) {
                    let selected_tt = $("#bsd_spscwt_type_" + connected_account_index + " option:selected").val();
                    $(".bsd_spscwtp_input, .bsd_spscwt_amount").addClass("bsd_hidden");
                    if (selected_tt == "percentage") {

                        $("#bsd_split_pay_stripe_connect_woo_transfer_percentage_" + connected_account_index).val(bulk_transfer_value);
                        $("#bsd_split_pay_stripe_connect_woo_transfer_percentage_" + connected_account_index).removeClass("bsd_hidden");
                    } else if (selected_tt == "amount") {
                        $("#bsd_spscwt_amount_" + connected_account_index).val(bulk_transfer_value);
                        $("#bsd_spscwt_amount_" + connected_account_index).removeClass("bsd_hidden");
                    } else if (selected_tt == "") {
                        $("#bsd_split_pay_stripe_connect_woo_transfer_percentage_" + connected_account_index).val(bulk_transfer_value);
                        $("#bsd_spscwt_amount_" + connected_account_index).val(bulk_transfer_value);
                    }
                }
            });

            $(".prod_tv_td_wrapper .selected_transfer_value_wrapper").html(bulk_transfer_value);
            $('.prod_tv_btns .edit-form-ok-btn', document).trigger("click");
            $("#account_transfer_value_modal_id").hide();
            $(".sps-modal-footer .popup-loader").hide();
            $(".transfer_value_apply_change_btn").show();

            is_bulk_edited = true;
        }, 1000);

    });

    window.onclick = function (event) {
        if (event.target == $("#account_transfer_value_modal_id")[0]) {
            $("#account_transfer_value_modal_id").hide();
        }
    }

    $(document).on("click", ".shipping_transfer_type_modal_open", function () {
        $("#shipping_transfer_type_modal_id").show();
        $("#shipping_bulk_transfer_type").focus();
    });
    $(document).on("click", ".close_shipping_transfer_type_modal_btn, .shipping_transfer_type_cancel_change_btn", function () {
        $("#shipping_transfer_type_modal_id").hide();
    });

    $(document).on("click", ".shipping_transfer_type_apply_change_btn", function () {
        $(".sps-modal-footer .popup-loader").show();
        $(".shipping_transfer_type_apply_change_btn").hide();
        setTimeout(function () {
            var shipping_bulk_transfer_type = $("#shipping_bulk_transfer_type").val();


            $(".bsd_spscwt_shipping_type").val(shipping_bulk_transfer_type);
            $(".prod_selected_st_td_wrapper .selected_shipping_type_wrapper").html(shipping_bulk_transfer_type);
            $('.prod_selected_st_btns .edit-form-ok-btn', document).trigger("click");
            $("#shipping_transfer_type_modal_id").hide();
            $(".sps-modal-footer .popup-loader").hide();
            $(".shipping_transfer_type_apply_change_btn").show();
            is_bulk_edited = true;
        }, 1000);

    });

    window.onclick = function (event) {
        if (event.target == $("#shipping_transfer_type_modal_id")[0]) {
            $("#shipping_transfer_type_modal_id").hide();
        }
    }

    $(document).on("click", ".shipping_transfer_value_modal_open", function () {
        $("#shipping_transfer_value_modal_id").show();
        $("#shipping_bulk_transfer_value").focus();
    });
    $(document).on("click", ".close_shipping_transfer_value_modal_btn, .shipping_transfer_value_cancel_change_btn", function () {
        $("#shipping_transfer_value_modal_id").hide();
    });

    $(document).on("click", ".shipping_transfer_value_apply_change_btn", function () {

        $(".sps-modal-footer .popup-loader").show();
        $(".shipping_transfer_value_apply_change_btn").hide();
        setTimeout(function () {
            var shipping_bulk_transfer_value = $("#shipping_bulk_transfer_value").val();



            $(".prod_stv_td_wrapper.edit-item-parent").each(function (index, element) {


                var selected_stv_value_wrapper = $(element).children(".selected_stv_value_wrapper");
                let connected_account_index = $(selected_stv_value_wrapper).attr("data-connected_account_index");
                if ($("#bsd_spscwt_shipping_type_" + connected_account_index).length) {
                    let selected_tt = $("#bsd_spscwt_shipping_type_" + connected_account_index + " option:selected").val();
                    $(".bsd_spscwtp_shipping_input, .bsd_spscwt_shipping_amount").addClass("bsd_hidden");
                    if (selected_tt == "percentage") {

                        $("#bsd_prod_shipping_percentage_" + connected_account_index).val(shipping_bulk_transfer_value);
                        $("#bsd_prod_shipping_percentage_" + connected_account_index).removeClass("bsd_hidden");
                    } else if (selected_tt == "amount") {
                        $("#bsd_prod_shipping_amount_" + connected_account_index).val(shipping_bulk_transfer_value);
                        $("#bsd_prod_shipping_amount_" + connected_account_index).removeClass("bsd_hidden");
                    } else if (selected_tt == "") {
                        $("#bsd_prod_shipping_percentage_" + connected_account_index).val(shipping_bulk_transfer_value);
                        $("#bsd_prod_shipping_amount_" + connected_account_index).val(shipping_bulk_transfer_value);
                    }
                }
            });

            $(".prod_stv_td_wrapper .selected_shipping_digit_wrapper").html(shipping_bulk_transfer_value);
            $('.prod_stv_btns .edit-form-ok-btn', document).trigger("click");
            $("#shipping_transfer_value_modal_id").hide();
            $(".sps-modal-footer .popup-loader").hide();
            $(".shipping_transfer_value_apply_change_btn").show();
            is_bulk_edited = true;
        }, 1000);

    });

    window.onclick = function (event) {
        if (event.target == $("#shipping_transfer_value_modal_id")[0]) {
            $("#shipping_transfer_value_modal_id").hide();
        }
    }


    /* -------------------------------------------------------------------------
     * Accessibility (3.7.5 / A11Y-014): dependency-free focus-trap for the bulk
     * editor modals (.sps-modal). Each modal is shown/hidden by the handlers
     * above; this block is purely additive — it never opens or closes a modal
     * itself, it only manages keyboard focus while one is open so the dialog is
     * usable without a mouse and meets WCAG 2.4.3 (Focus Order) / 2.1.2 (No
     * Keyboard Trap, in the "you can always Escape" sense):
     *   - On open: remember the element that had focus (the trigger) and move
     *     focus to the first focusable control inside the modal.
     *   - Tab / Shift+Tab: cycle within the modal (wrap at the ends) so focus
     *     can never leave the dialog while it is open.
     *   - Escape: close the modal and return focus to the trigger.
     *   - On close by any path (X, Cancel, Apply, backdrop, Escape): restore
     *     focus to the trigger element.
     * One small reusable trap is wired to every .sps-modal; the primary dialog
     * is #connect_stripe_account_modal_id (the bulk "Connected Stripe Account"
     * editor). No external library, no markup the partial doesn't already ship.
     * --------------------------------------------------------------------- */
    // Leading semicolon: the preceding `window.onclick = function(){…}` block
    // ships without a trailing semicolon, so this guards against ASI folding
    // the IIFE into a call on that assignment's value.
    ;(function () {
        var FOCUSABLE = 'a[href], area[href], button:not([disabled]), input:not([disabled]):not([type="hidden"]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';
        var sppModalTrigger = null;

        function sppVisibleModal() {
            var $m = $('.sps-modal:visible').first();
            return $m.length ? $m : null;
        }

        function sppFocusable($modal) {
            return $modal.find(FOCUSABLE).filter(':visible');
        }

        function sppRestoreFocus() {
            if (sppModalTrigger && typeof sppModalTrigger.focus === 'function') {
                sppModalTrigger.focus();
            }
            sppModalTrigger = null;
        }

        // Remember the trigger and focus the first control when any modal opens.
        // The *_modal_open handlers above already call .show() + .focus() on a
        // specific field; we run after them (same click) to seed the trap and,
        // if that field wasn't focusable for some reason, focus the first one.
        $(document).on('click', '.connect_stripe_account_modal_open, .transfer_type_modal_open, .value_modal_open, .shipping_transfer_type_modal_open, .shipping_transfer_value_modal_open', function () {
            sppModalTrigger = this;
            // Defer to let the modal become visible, then ensure focus is inside.
            window.setTimeout(function () {
                var $modal = sppVisibleModal();
                if (!$modal) { return; }
                if (!$.contains($modal[0], document.activeElement)) {
                    var $f = sppFocusable($modal);
                    if ($f.length) { $f.first().trigger('focus'); }
                    else { $modal.trigger('focus'); }
                }
            }, 0);
        });

        // Restore focus to the trigger whenever a modal is dismissed via its
        // own close/cancel controls (the click also runs the .hide() handlers
        // above). Apply buttons hide the modal after a timeout, so restore there
        // too once it is actually hidden.
        $(document).on('click', '.close_connect_stripe_account_modal_btn, .cancel_change_btn, .close_account_transfer_type_modal_btn, .transfer_type_cancel_change_btn, .close_account_transfer_value_modal_btn, .transfer_value_cancel_change_btn, .close_shipping_transfer_type_modal_btn, .shipping_transfer_type_cancel_change_btn, .close_shipping_transfer_value_modal_btn, .shipping_transfer_value_cancel_change_btn', function () {
            sppRestoreFocus();
        });

        // Tab containment + Escape, only while a modal is open.
        $(document).on('keydown', function (e) {
            var $modal = sppVisibleModal();
            if (!$modal) { return; }

            if (e.key === 'Escape' || e.keyCode === 27) {
                $modal.hide();
                sppRestoreFocus();
                e.preventDefault();
                return;
            }

            if (e.key === 'Tab' || e.keyCode === 9) {
                var $f = sppFocusable($modal);
                if (!$f.length) {
                    // Nothing focusable inside: keep focus on the dialog itself.
                    $modal.trigger('focus');
                    e.preventDefault();
                    return;
                }
                var first = $f.first()[0];
                var last = $f.last()[0];
                var active = document.activeElement;

                if (e.shiftKey) {
                    if (active === first || !$.contains($modal[0], active)) {
                        last.focus();
                        e.preventDefault();
                    }
                } else {
                    if (active === last || !$.contains($modal[0], active)) {
                        first.focus();
                        e.preventDefault();
                    }
                }
            }
        });
    })();


    set_select2();
    /** Bulk editor js start. */
    $(document).on("click", ".edit-item", function () {
        // Close any previously opened edit-form
        $('.edit-form', document).removeClass("open-edit-item");
        // Open the clicked edit-form
        $(this).next('.edit-form').addClass("open-edit-item");
    });

    $(document).on("click", ".edit-item-parent", function (e) {
        if (
            $(e.target).hasClass("edit-item-parent") ||
            $(e.target).hasClass("selected_account_id_wrapper") ||
            $(e.target).hasClass("selecte_tt_wrapper") ||
            $(e.target).hasClass("selected_transfer_value_wrapper") ||
            $(e.target).hasClass("selected_shipping_type_wrapper") ||
            $(e.target).hasClass("selected_shipping_digit_wrapper")
        ) {
            // Close any previously opened edit-form
            $('.edit-form', document).removeClass("open-edit-item");
            // Open the clicked edit-form
            $(this).children('.edit-form').addClass("open-edit-item");
        }

    });
    $(document).on("keyup", function (e) {

        if (e.key === "Escape") {
            $('.edit-form', document).removeClass("open-edit-item");
        }
        if (e.keyCode === 13) {
            $('.open-edit-item .edit-form-ok-btn', document).trigger("click");
        }
    });
    $(document).on("click", ".edit-form-cancle-btn", function () {
        $('.edit-form', document).removeClass("open-edit-item");
    });

    /* $(document).on("focusout", "tr td select,tr td input", function (e) {
        $(this).parents("td").next("td").children(".edit-item").trigger("click");
        $('.open-edit-item select, .open-edit-item input', document).focus();
    }); */

    $(document).on("click", ".select_account_btns .edit-form-ok-btn", function () {
        let td_parent = $(this).parents(".select_account_td_wrapper");
        let selected_account = $(td_parent).find(".sspscwsca_select option:selected").val();
        $('.edit-form', document).removeClass("open-edit-item");
        $(".selected_account_id_wrapper", td_parent).html(selected_account);
        $(td_parent).addClass("edited_fields");
    });

    $(document).on("click", ".prod_selected_tt_btns .edit-form-ok-btn", function () {
        let td_parent = $(this).parents(".prod_selected_tt_td_wrapper");
        let selected_val = $(td_parent).find(".bsd_spscwt_type option:selected").val();
        $('.edit-form', document).removeClass("open-edit-item");
        let display_selected_val = "";
        if (selected_val == "percentage") {
            display_selected_val = "Percentage";
        } else if (selected_val == "amount") {
            display_selected_val = "Fixed Amount";
        }
        $(".selecte_tt_wrapper", td_parent).html(display_selected_val);
        $(td_parent).addClass("edited_fields");
    });
    $(document).on("click", ".selected_tt_value_wrapper", function () {
        let connected_account_index = $(this).attr("data-connected_account_index");
        if ($("#bsd_spscwt_type_" + connected_account_index).length) {
            let selected_tt = $("#bsd_spscwt_type_" + connected_account_index + " option:selected").val();
            $(".bsd_spscwtp_input, .bsd_spscwt_amount").addClass("bsd_hidden");
            if (selected_tt == "percentage") {
                $("#bsd_split_pay_stripe_connect_woo_transfer_percentage_" + connected_account_index).removeClass("bsd_hidden");
            } else {
                $("#bsd_spscwt_amount_" + connected_account_index).removeClass("bsd_hidden");
            }
        }
    });

    $(document).on("click", ".prod_tv_td_wrapper.edit-item-parent", function () {
        var selected_tt_value_wrapper = $(this).children(".selected_tt_value_wrapper");
        let connected_account_index = $(selected_tt_value_wrapper).attr("data-connected_account_index");
        if ($("#bsd_spscwt_type_" + connected_account_index).length) {
            let selected_tt = $("#bsd_spscwt_type_" + connected_account_index + " option:selected").val();
            $(".bsd_spscwtp_input, .bsd_spscwt_amount").addClass("bsd_hidden");
            if (selected_tt == "percentage") {
                $("#bsd_split_pay_stripe_connect_woo_transfer_percentage_" + connected_account_index).removeClass("bsd_hidden");
            } else {
                $("#bsd_spscwt_amount_" + connected_account_index).removeClass("bsd_hidden");
            }
        }
    });


    $(document).on("click", ".prod_tv_btns .edit-form-ok-btn", function () {
        let td_parent = $(this).parents(".prod_tv_td_wrapper");
        let selected_val = $(td_parent).find(".edit-form input[type=number]:not(.bsd_hidden)").val();
        $('.edit-form', document).removeClass("open-edit-item");

        $(".selected_transfer_value_wrapper", td_parent).html(selected_val);
        $(td_parent).addClass("edited_fields");
    });

    $(document).on("click", "#sync_webhooks", function () {

        var data = {
            action: "sync_webhooks",
            security: bsd_admin_plugin_vars.security
        };
        $.ajax({
            url: bsd_admin_plugin_vars.ajax_url,
            type: "post",
            data: data,
            beforeSend: function () {
                $("#sync_webhooks .bsd_loader").show();
                $("#sync_webhooks").addClass("disabled");
            },
            success: function (response) {
                if (response.success) {

                    if (response.data.error_messages.test_mode && response.data.error_messages.test_mode.length) {
                        $(".webhook_response_status_upate td .test_mode_message_wrapper").html("");
                        response.data.error_messages.test_mode.forEach(element => {
                            $(".webhook_response_status_upate td .test_mode_message_wrapper").append("❌ Test " + element + "<br/>");
                        });
                    }
                    if (response.data.error_messages.live_mode && response.data.error_messages.live_mode.length) {
                        $(".webhook_response_status_upate td .live_mode_message_wrapper").html("");
                        response.data.error_messages.live_mode.forEach(element => {
                            $(".webhook_response_status_upate td .live_mode_message_wrapper").append("❌ Live " + element + "<br/>");
                        });
                    }


                    if (response.data.successes.test_mode && response.data.successes.test_mode.length) {
                        $(".webhook_response_status_upate td .test_mode_message_wrapper").html("");
                        $(".webhook_response_status_upate td .test_mode_message_wrapper").html("✅ Test Mode Webhook Configured");
                    }
                    if (response.data.successes.live_mode && response.data.successes.live_mode.length) {
                        $(".webhook_response_status_upate td .live_mode_message_wrapper").html("");
                        $(".webhook_response_status_upate td .live_mode_message_wrapper").html("✅ Live Mode Webhook Configured");
                    }

                }

                $(".webhook_response_status_upate").removeClass("bsd_hidden");
                $("#sync_webhooks .bsd_loader").hide();
                $("#sync_webhooks").removeClass("disabled");
            }
        });

    });

    $(document).on("click", ".prod_selected_st_btns .edit-form-ok-btn", function () {
        let td_parent = $(this).parents(".prod_selected_st_td_wrapper");
        let selected_val = $(td_parent).find(".bsd_spscwt_shipping_type option:selected").val();
        $('.edit-form', document).removeClass("open-edit-item");
        let display_selected_val = "";
        if (selected_val == "percentage") {
            display_selected_val = "Percentage";
        } else if (selected_val == "amount") {
            display_selected_val = "Fixed Amount";
        }
        $(".selected_shipping_type_wrapper", td_parent).html(display_selected_val);
        $(td_parent).addClass("edited_fields");
    });

    $(document).on("click", ".prod_stv_btns .edit-form-ok-btn", function () {
        let td_parent = $(this).parents(".prod_stv_td_wrapper");
        let selected_val = $(td_parent).find(".edit-form input[type=number]:not(.bsd_hidden)").val();
        $('.edit-form', document).removeClass("open-edit-item");

        $(".selected_shipping_digit_wrapper", td_parent).html(selected_val);
        $(td_parent).addClass("edited_fields");
    });

    $(document).on("click", ".selected_stv_value_wrapper", function () {
        let connected_account_index = $(this).attr("data-connected_account_index");

        if ($("#bsd_spscwt_shipping_type_" + connected_account_index).length) {
            let selected_tt = $("#bsd_spscwt_shipping_type_" + connected_account_index + " option:selected", document).val();
            $(".bsd_spscwtp_shipping_input, .bsd_spscwt_shipping_amount ").addClass("bsd_hidden");
            if (selected_tt == "percentage") {
                $("#bsd_prod_shipping_percentage_" + connected_account_index).removeClass("bsd_hidden");
            } else {
                $("#bsd_prod_shipping_amount_" + connected_account_index).removeClass("bsd_hidden");
            }
        }
    });



    $(document).on("submit", "#bulk-editor-save", function (e) {
        $(".result-loader", document).css("display", "flex");
        e.preventDefault(); // avoid to execute the actual submit of the form.


        let account_array = [];
        $("input[name^='product_type[']").each(function (index, value) {

            const name = $(value).attr('name');
            // Use regex to extract the ID between brackets
            const match = name.match(/product_type\[(\d+)\]/);

            if (match && match[1]) {
                const id = match[1];


                account_array[id] = {};
                account_array[id]["product_id"] = id;
                account_array[id]["product_type"] = $(value).val();
                if ($("select[name^='_bsd_spscwt_product_connected_account[" + id + "]").length) {
                    account_array[id]["connected_account"] = {};
                    $("select[name^='_bsd_spscwt_product_connected_account[" + id + "]").each(function (caIndex, caValue) {

                        account_array[id]["connected_account"][caIndex] = $(caValue).val();
                    });
                }
                if ($("select[name^='_bsd_spscwt_product_type[" + id + "]").length) {
                    account_array[id]["transfer_type"] = {};
                    $("select[name^='_bsd_spscwt_product_type[" + id + "]").each(function (caIndex, caValue) {
                        account_array[id]["transfer_type"][caIndex] = $(caValue).val();
                    });
                }
                if ($("input[name^='_stripe_connect_split_pay_transfer_percentage[" + id + "]").length) {
                    account_array[id]["transfer_type_percentage"] = {};
                    $("input[name^='_stripe_connect_split_pay_transfer_percentage[" + id + "]").each(function (caIndex, caValue) {
                        account_array[id]["transfer_type_percentage"][caIndex] = $.trim($(caValue).val());
                    });
                }
                if ($("input[name^='_bsd_spscwt_product_amount[" + id + "]").length) {
                    account_array[id]["transfer_type_amount"] = {};
                    $("input[name^='_bsd_spscwt_product_amount[" + id + "]").each(function (caIndex, caValue) {
                        account_array[id]["transfer_type_amount"][caIndex] = $.trim($(caValue).val());
                    });
                }

                if ($("select[name^='bsd_spscwt_shipping_type[" + id + "]").length) {
                    account_array[id]["shipping_transfer_type"] = {};
                    $("select[name^='bsd_spscwt_shipping_type[" + id + "]").each(function (caIndex, caValue) {
                        account_array[id]["shipping_transfer_type"][caIndex] = $(caValue).val();
                    });
                }
                if ($("input[name^='bsd_prod_shipping_percentage[" + id + "]").length) {
                    account_array[id]["shipping_transfer_percentage"] = {};
                    $("input[name^='bsd_prod_shipping_percentage[" + id + "]").each(function (caIndex, caValue) {
                        account_array[id]["shipping_transfer_percentage"][caIndex] = $.trim($(caValue).val());
                    });
                }
                if ($("input[name^='bsd_prod_shipping_amount[" + id + "]").length) {
                    account_array[id]["shipping_transfer_amount"] = {};
                    $("input[name^='bsd_prod_shipping_amount[" + id + "]").each(function (caIndex, caValue) {
                        account_array[id]["shipping_transfer_amount"][caIndex] = $.trim($(caValue).val());
                    });
                }



            }


        });

        // console.log(account_array);
        let definedElements = account_array.filter(element => element !== undefined);
        const batchSize = 100;
        let batches = [];
        for (let i = 0; i < definedElements.length; i += batchSize) {
            batches.push(definedElements.slice(i, i + batchSize));
        }


        if (batches.length) {
            var batch_counter = batches.length
            batches.forEach((batch, batchIndex) => {
                batch.push({
                    "security": bsd_admin_plugin_vars.security
                });
                let jsonData = JSON.stringify(batch);
                $.ajax({
                    type: "POST",
                    url: ajaxurl + "?action=save_product_bulk_edit",
                    // async: false,
                    contentType: "application/json; charset=utf-8",
                    data: jsonData, // serializes the form's elements.
                    beforeSend: function () {
                        $(".result-loader", document).css("display", "flex");
                    },
                    success: function (data) {
                        //if (is_bulk_edited && batchIndex == batch_counter - 1) {
                        var page_num = parseInt($(".pagination .current").html());
                        fetch_bulk_editor_search_result("search", page_num);
                        is_bulk_edited = false;

                        $(".result-loader", document).hide();


                        //}
                    }
                });
            });

        }



    });

    /** Bulk editor js end. */

    window.current_page = 2;
    $("#sync_accounts_btn").on("click", function () {
        fetch_account_ajax();
        $("#sync_btn_text").hide();
        $("#sync_accounts_btn .bsd_loader").show();
        $("#sync_accounts_btn").addClass("disabled");

    });

    $("#csync_accounts_btn").on("click", function () {
        if ( ! confirm( 'Are you sure you want to clear all synced Stripe account data? This will remove all connected accounts from the plugin and cannot be undone.' ) ) {
            return;
        }
        clear_accounts_ajax();
        $("#csync_btn_text").hide();
        $("#csync_accounts_btn .bsd_loader").show();
        $("#csync_accounts_btn").addClass("disabled");

    });



    $("#_bsd_spscwt_product_type").on("change", function () {
        var selected_type = $(this).val();
        if (selected_type == "amount") {
            $(".bsd_scsptp").hide();
            $(".bsd_spscwt_product_amount").show();

        } else {
            $(".bsd_spscwt_product_amount").hide();
            $(".bsd_scsptp").show();
        }
    });

    $(document).on("change", "._bsd_spscwt_product_type", function () {
        var selected_type = $(this).val();
        if (selected_type == "amount") {
            $(this).parent().siblings(".bsd_scsptp").hide();
            $(this).parent().siblings(".bsd_spscwt_product_amount").show();

        } else {
            $(this).parent().siblings(".bsd_spscwt_product_amount").hide();
            $(this).parent().siblings(".bsd_scsptp").show();
        }
    });

    $("#vendor_onboading").on("change", function () {
        if ($(this).is(":checked")) {
            $(".show_td_cb_row").removeClass("bsd_hidden");
        } else {
            $(".show_td_cb_row").addClass("bsd_hidden");
            $(".show_td_rows").addClass("bsd_hidden");
            $("#enable_title_description").prop("checked", false);
        }
    });

    $("#enable_title_description").on("change", function () {
        if ($(this).is(":checked")) {
            $(".show_td_rows").removeClass("bsd_hidden");
        } else {
            $(".show_td_rows").addClass("bsd_hidden");
        }
    });



    /* Transfer-percentage validation (3.7.2).
     *
     * Prior versions used blocking native alert()/confirm() popups when the
     * aggregate of configured percentages crossed 97% or 100%. Dismissing
     * the confirm aborted the save, which blocked legitimate account-per-
     * product workflows (where each connected account is intentionally set
     * to 100% of its own payment routing — see customer report from Sand
     * Dragon Media, May 2026, and Shortcut sc-7166 for the 3.7.3 math fix).
     *
     * The 3.7.2 behavior:
     *   * Never block save with a popup or modal.
     *   * If a threshold is crossed, attach a hidden input describing the
     *     condition; PHP picks it up in admin_init and stashes a per-user
     *     transient that admin_notices renders once as a dismissible
     *     notice-warning (>97%) or notice-error (>100%).
     *   * Receiver: includes/admin/spp-validation-notices.php.
     */

    function bsdSppAttachValidationFlag($form, payload) {
        $form.find('input[name="bsd_spscwa_high_total_warning"]').remove();
        $form.append($('<input>', {
            type:  'hidden',
            name:  'bsd_spscwa_high_total_warning',
            value: JSON.stringify(payload)
        }));
    }

    function bsdSppSeverityFor(total) {
        if (total > 100) { return 'error'; }
        if (total > 97)  { return 'warning'; }
        return null;
    }

    /* Dashboard form: Global Shipping rows + Global Transfer rows on the
     * Split Pay settings page. Validates each bucket independently and
     * surfaces whichever threshold is more severe. */
    $("#bsd-split-pay-stripe-connect-woo-settings form").on("submit", function () {
        var $form = $(this);

        var ship_total = 0;
        $(".bsd_shipping_type").each(function (index) {
            if ($(this).val() == 'percentage') {
                ship_total += Number($("#bsd_global_shipping_percentage_" + index).val()) || 0;
            }
        });

        var prod_total = 0;
        $(".bsd_spscwt_type:not(.bsd_shipping_type)").each(function (index) {
            if ($(this).val() == 'percentage') {
                prod_total += Number($("#bsd_split_pay_stripe_connect_woo_transfer_percentage_" + index).val()) || 0;
            }
        });

        var prod_sev = bsdSppSeverityFor(prod_total);
        var ship_sev = bsdSppSeverityFor(ship_total);

        /* Prefer product-bucket payload when both fire — it's the more
         * commonly-misconfigured one. Error severity outranks warning. */
        var payload = null;
        if (prod_sev === 'error' || (prod_sev && ship_sev !== 'error')) {
            payload = { context: 'global', total: prod_total, severity: prod_sev };
        } else if (ship_sev) {
            payload = { context: 'global_shipping', total: ship_total, severity: ship_sev };
        }
        if (payload) {
            bsdSppAttachValidationFlag($form, payload);
        }

        /* Always allow save — the notice ships as a dismissible admin_notices
         * on the next page render via spp-validation-notices.php. */
        return true;
    });

    /* WC product-edit form: simple products only. Variable, grouped, and
     * external types render the per-variation table elsewhere and own
     * their own validation. */
    $(".post-type-product form#post").on("submit", function () {
        var $form        = $(this);
        var product_type = $("#product-type").val();
        if (product_type == "variable" || product_type == "grouped" || product_type == "external") {
            return true;
        }

        var pro_transfer_vals = 0;
        $(".bsd_spscwt_type").each(function () {
            if ($(this).val() != 'percentage') { return; }
            var lastword = String($(this).attr("id") || '').split("_").pop();
            pro_transfer_vals += Number($("#bsd_split_pay_stripe_connect_woo_transfer_percentage_" + lastword).val()) || 0;
        });

        var severity = bsdSppSeverityFor(pro_transfer_vals);
        if (severity) {
            bsdSppAttachValidationFlag($form, {
                context:  'product',
                total:    pro_transfer_vals,
                severity: severity
            });
        }

        /* Always allow save — see dashboard handler comment above. */
        return true;
    });




    /* Bulk editor */
    if ($(".pwbe-filter-select").length) {
        $('.pwbe-filter-select').select2();
        $(".product-fields").hide();
    }

    $(document).on("change", ".filter-name", function () {
        var filter_type = $(this).val();
        var data_id = $(this).attr("data-id");
        if (filter_type == 'categories') {
            $(".category-fields-" + data_id).show();
            $(".product-fields-" + data_id).hide();
        }
        if (filter_type == 'post_title' || filter_type == 'sku' || filter_type == 'pa') {
            $(".product-fields-" + data_id).show();
            $(".category-fields-" + data_id).hide();
        }
    });


    $(document).on("click", ".serach-btn", function () {
        fetch_bulk_editor_search_result("search");
        bulk_editor_which_btn_clicked = "search";
    });
    $(document).on("click", ".show-products-btn", function () {
        if ($(".find-minus.remove_more").length) {
            $(".find-minus.remove_more").each(function (ind, ele) {
                var data_id = $(ele).attr("data-id");
                $(".more-" + data_id).remove();
            });
        }
        $(".pro-filter-input").val("");

        $('.pwbe-filter-select').val("").trigger('change');
        fetch_bulk_editor_search_result("show-all");
        bulk_editor_which_btn_clicked = "show-all";
    });

    $(document).on("click", ".add_more", function () {
        var count_fil = $(this).attr("data-id");
        $.ajax({
            url: ajaxurl,
            type: 'post',
            dataType: 'json',
            data: {
                action: 'fetch_more_filter',
                count: count_fil
            },
            success: function (response) {
                if (response.data) {
                    var count2 = parseInt(count_fil) + 1;
                    $(".add_more").attr("data-id", count2 + 1);
                    $(".find-product-list__row-main").append(response.data);
                    $('.pwbe-filter-select').select2();
                    $("body .product-fields-" + count2).hide();
                }
            }
        });

    });

    $(document).on("click", ".remove_more", function () {
        var count = $(this).data("id");
        $(".more-" + count).remove();
    });

    /* Pagination on bulk editor */
    $(document).on("click", ".pagination a.page-numbers", function (e) {
        e.preventDefault();
        var page_num = $(this).text();
        if (!$.isNumeric($(this).text())) {
            if ($(this).hasClass("next")) {
                var page_num = parseInt($(".pagination .current").html()) + 1;
            }
            if ($(this).hasClass("prev")) {
                var page_num = parseInt($(".pagination .current").html()) - 1;
            }
        }
        if (bulk_editor_which_btn_clicked === "show-all") {
            fetch_bulk_editor_search_result("show-all", page_num);
        } else {
            fetch_bulk_editor_search_result("search", page_num);
        }

    });

    /*
     * 3.7.5 a11y (WCAG 2.1 AA, 4.1.2 Name/Role/Value): the per-row transfer-type /
     * shipping-type / connected-account <select>s use dynamic per-row ids and have no
     * adjacent <label>, so they need an aria-label to expose an accessible name. The
     * server-rendered rows are labelled in PHP; rows added at runtime by the
     * "add new account" cloners (main.js) are not, so stamp any unlabelled SPP select
     * here — on load AND whenever the DOM changes. Labels are i18n-driven when the
     * localized strings are present, with an English fallback matching the existing
     * cloner markup.
     */
    (function () {
        var L = (window.bsd_admin_plugin_vars && bsd_admin_plugin_vars.a11y_labels) || {};
        var labelFor = function (el) {
            if (el.classList.contains("bsd_shipping_type") || el.classList.contains("bsd_spscwt_shipping_type")) {
                return L.shipping_transfer_type || "Global shipping transfer type";
            }
            if (el.classList.contains("bsd_spscwt_type")) {
                return L.transfer_type || "Transfer type";
            }
            if (el.classList.contains("sspscwsca_select") || el.classList.contains("sspscwsca_prod_select")) {
                return L.connected_account || "Connected Stripe account";
            }
            if (el.classList.contains("filter-categories")) { return L.filter_categories || "Product categories"; }
            if (el.classList.contains("filter-name")) { return L.filter_field || "Filter field"; }
            if (el.classList.contains("pwbe-filter-type") || el.classList.contains("filter-cat-type") || el.classList.contains("filter-product-type")) {
                return L.filter_match_type || "Match type";
            }
            if (el.classList.contains("pro-filter-input")) { return L.filter_search_text || "Search text"; }
            return "";
        };
        var stampAll = function (root) {
            var sels = (root || document).querySelectorAll(
                "select.bsd_spscwt_type, select.bsd_shipping_type, select.bsd_spscwt_shipping_type, select.sspscwsca_select, select.sspscwsca_prod_select, select.pwbe-filter-field, input.pro-filter-input"
            );
            sels.forEach(function (el) {
                // Skip if it already has an accessible name (aria-label, aria-labelledby,
                // a wrapping/associated <label>, or the select2-hidden mirror handling it).
                if (el.getAttribute("aria-label") || el.getAttribute("aria-labelledby")) return;
                if (el.id && document.querySelector('label[for="' + el.id + '"]')) return;
                var name = labelFor(el);
                if (name) el.setAttribute("aria-label", name);
            });
        };
        stampAll(document);
        if (window.MutationObserver) {
            var mo = new MutationObserver(function (muts) {
                for (var i = 0; i < muts.length; i++) {
                    if (muts[i].addedNodes && muts[i].addedNodes.length) { stampAll(document); break; }
                }
            });
            mo.observe(document.body, { childList: true, subtree: true });
        }
    })();

});

function fetch_bulk_editor_search_result(search_type = "search", paged = 1) {

    var filter_types = [];
    var filter_contain = [];
    var filter_value = [];
    var error = 0;
    var all_variations = false;
    $("p.error").remove();
    if (search_type == "search") {
        $(".filter-name").each(function () {
            var data_id = $(this).attr("data-id");
            filter_types.push($(this).val());
            if ($(this).val() == 'categories') {
                filter_contain.push($(".filter-cat-type[data-id=" + data_id + "]").val());
                if ($.trim($(".filter-categories[data-id=" + data_id + "]").val()) == '') {
                    $(".filter-categories[data-id=" + data_id + "]").closest(".category-fields").append("<p class='error'>This field is required!</p>");
                    error = 1;
                }
                filter_value.push($(".filter-categories[data-id=" + data_id + "]").val());
            } else {
                filter_contain.push($(".filter-product-type[data-id=" + data_id + "]").val());
                if ($.trim($(".pro-filter-input[data-id=" + data_id + "]").val()) == '') {
                    $(".pro-filter-input[data-id=" + data_id + "]").closest(".product-fields").append("<p class='error'>This field is required!</p>");
                    error = 1;
                }
                filter_value.push($(".pro-filter-input[data-id=" + data_id + "]").val());
            }
        });
    }

    if ($("#all_variations").is(":checked")) {
        all_variations = true;
    }

    var page = paged;
    if (error == 0) {
        $.ajax({
            url: ajaxurl,
            type: 'post',
            dataType: 'json',
            beforeSend: function () {
                $(".filter-loader").css("display", "flex");
            },
            data: {
                action: 'fetch_search_result',
                filter_type: filter_types,
                all_variations: all_variations,
                filter_contain: filter_contain,
                filter_value: filter_value,
                paged: page,
                search_type: search_type,
                security: bsd_admin_plugin_vars.security
            },
            success: function (response) {
                if (response.data) {
                    $(".filter-loader").hide();
                    $(".product-result").html(response.data.data);
                    $(".result-coutn", document).html("");
                    $(".result-coutn", document).html(response.data.total_text);
                    set_select2();
                }
            }
        });
    }
}

function set_select2() {
    if ($(".sspscwsca_select").length) {
        $('.sspscwsca_select').select2({
            width: '100%',
            placeholder: "Select",
            allowClear: true,
            templateResult: formatOptions,
            matcher: function (params, data) {
                if ($.trim(params.term) === '') {
                    return data;
                }
                var term = params.term.toLowerCase();
                if ((data.text && data.text.toLowerCase().indexOf(term) > -1) ||
                    (data.id && data.id.toLowerCase().indexOf(term) > -1)) {
                    return data;
                }
                return null;
            },
            language: {
                noResults: function () {
                    return 'No Result Found! <button class="no-results-btn">Click to add it</button>';
                },
            },
            escapeMarkup: function (markup) {
                return markup;
            },
            templateSelection: function (data) {
                if (data.id !== "") {
                    return data.text;
                }
                return data.text;
            }

        }).on('select2-open', function () {

            // however much room you determine you need to prevent jumping
            var requireHeight = 600;
            var viewportBottom = $(window).scrollTop() + $(window).height();

            // figure out if we need to make changes
            if (viewportBottom < requireHeight) {
                // determine how much padding we should add (via marginBottom)
                var marginBottom = requireHeight - viewportBottom;

                // adding padding so we can scroll down
                $(".aLwrElmntOrCntntWrppr").css("marginBottom", marginBottom + "px");

                // animate to just above the select2, now with plenty of room below
                $('html, body').animate({
                    scrollTop: $(".sspscwsca_select").offset().top - 10
                }, 1000);
            }
        });

        $(document).on("click", ".no-results-btn", function (e) {
            e.stopImmediatePropagation();
            var no_results_btn_obj = $(this);
            // select2-results__options
            var get_select2_id = $(no_results_btn_obj).parents(".select2-results__options").attr("id");
            get_select2_id = get_select2_id.replace("select2-", "");
            get_select2_id = get_select2_id.replace("-results", "");

            var entered_id = $('.select2-search__field')[0].value;
            var target_select = $(".select2.select2-container--open").prev(".sspscwsca_select");
            var data = {
                action: "add_custom_account",
                account_id: entered_id,
                security: bsd_admin_plugin_vars.security
            };
            var option_html = '<option value="' + entered_id + '">' + entered_id + '</option>';
            $(".sspscwsca_select").prepend(option_html);
            target_select.val(entered_id).change();
            $.ajax({
                url: bsd_admin_plugin_vars.ajax_url,
                type: "post",
                data: data,
                success: function (response) {
                    if (response && response.success) {
                        var label = spp_build_account_label({
                            account_id: entered_id,
                            account_name: response.account_name || '',
                            account_email: response.account_email || ''
                        });
                        $(".sspscwsca_select option[value='" + entered_id + "']").text(label);
                    }
                }
            });
        });


    }
}



function spp_build_account_label(item) {
    var name  = (item.account_name != null && item.account_name !== '' && item.account_name !== item.account_id) ? item.account_name : '';
    var email = (item.account_email != null && item.account_email !== '') ? item.account_email : '';
    if (name && email) {
        return name + ' - ' + email;
    } else if (name) {
        return name;
    } else if (email) {
        return email;
    }
    return item.account_id;
}

function formatOptions(repo) {


    var $container = $(
        "<div class='select2-result-repository clearfix'>" +
        "<div class='select2-result-repository__meta'>" +
        "<div class='select2-result-repository__title'></div>" +
        "<div class='select2-result-repository__description'></div>" +
        "</div>" +
        "</div>"
    );

    $container.find(".select2-result-repository__title").text(repo.text);
    $container.find(".select2-result-repository__description").text(repo.id);

    return $container;
}

function fetch_account_ajax() {
    var data = {
        action: "fetch_accounts",
        page: window.current_page,
        security: bsd_admin_plugin_vars.security
    };
    $.ajax({
        url: bsd_admin_plugin_vars.ajax_url,
        type: "post",
        data: data,
        success: function (response) {
            if (!response.is_finished) {
                window.current_page = response.current_page;
                if (response.new_account_ids.length > 0) {
                    var option_html = "";
                    response.new_account_ids.forEach(function (item, index) {
                        option_html += '<option value="' + item.account_id + '">' + spp_build_account_label(item) + '</option>';
                    });
                    $(".sspscwsca_select").append(option_html);
                }
                fetch_account_ajax();
            } else {
                if ("new_account_ids" in response && response.new_account_ids.length > 0) {
                    var option_html = "";
                    response.new_account_ids.forEach(function (item, index) {
                        option_html += '<option value="' + item.account_id + '">' + spp_build_account_label(item) + '</option>';
                    });
                    $(".sspscwsca_select").append(option_html);


                }
                $("#sync_btn_text").show();
                $("#sync_accounts_btn .bsd_loader").hide();
                $("#sync_accounts_btn").removeClass("disabled");
                alert(response.message);
            }

        }
    });
}

function clear_accounts_ajax() {
    var data = {
        action: "clear_accounts",
        page: window.current_page,
        security: bsd_admin_plugin_vars.security
    };
    $.ajax({
        url: bsd_admin_plugin_vars.ajax_url,
        type: "post",
        data: data,
        success: function (response) {
            $("#csync_btn_text").show();
            $("#csync_accounts_btn .bsd_loader").hide();
            $("#csync_accounts_btn").removeClass("disabled");

            window.location.reload(true);

        }
    });
}
