<script>
    let mainSparePartsRowCount = 1;

    function addListenersToSpareRow(row) {
        // Delete logic
        row.querySelector(".deleteMainSparePartsRow").addEventListener("click", function() {
            if (document.querySelectorAll(".mainSparePartsRow").length > 1) {
                row.remove();
                mainSparePartsRowCount--;

                // Recalculate total after deleting
                updateTotalSpareAjaxNetAmount();
            } else {
                alert("At least one row is required!");
            }
        });

        // Bind AJAX search
        const searchInput = row.querySelector(".sparePartsSearch");
        const resultContainer = row.querySelector(".spareSearchResults");

        if (searchInput && resultContainer) {
            bindSpareSearch(searchInput, resultContainer);
        }
    }

    document.addEventListener("DOMContentLoaded", function() {
        const container = document.getElementById("mainSpareContainer");
        const addBtn = document.getElementById("addMainSparePartsRow");

        if (!window.mainSpareHandlerAttached) {
            window.mainSpareHandlerAttached = true;

            // Initial row binding
            const initialRow = container.querySelector(".mainSparePartsRow");
            if (initialRow) {
                addListenersToSpareRow(initialRow);
            }

            // Add new row
            addBtn.addEventListener("click", function() {
                if (mainSparePartsRowCount < 100) {
                    const firstRow = container.querySelector(".mainSparePartsRow");
                    const newRow = firstRow.cloneNode(true);

                    // Reset inputs
                    newRow.querySelectorAll("input").forEach(input => {
                        input.value = input.type === "text" ? "" : "0";
                    });

                    container.appendChild(newRow);
                    addListenersToSpareRow(newRow);
                    mainSparePartsRowCount++;
                } else {
                    alert("Maximum of 100 rows allowed.");
                }
            });
        }
    });
</script>