<script>
    let mainLubricantRowCount = 1;

    function addListenersToRow(row) {
        // Delete logic
        row.querySelector(".deleteMainLubricantRow").addEventListener("click", function() {
            if (document.querySelectorAll(".mainlubricantRow").length > 1) {
                row.remove();
                mainLubricantRowCount--;

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

        // Bind AJAX search
        const searchInput = row.querySelector(".lubricantSearch");
        const resultContainer = row.querySelector(".lubricantSearchResults");
        if (searchInput && resultContainer) {
            bindLubricantSearch(searchInput, resultContainer);
        }
    }


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

        // Avoid attaching multiple times
        if (!window.mainLubricantHandlerAttached) {
            window.mainLubricantHandlerAttached = true;

            // Initial row
            const initialRow = container.querySelector(".mainlubricantRow");
            if (initialRow) {
                addListenersToRow(initialRow);
            }

            addBtn.addEventListener("click", function() {
                if (mainLubricantRowCount < 100) {
                    const firstRow = container.querySelector(".mainlubricantRow");
                    const newRow = firstRow.cloneNode(true);

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

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