<script>
    let mainLabourRowCount = 1;

    function addListenersToLabourRow(row) {
        // Delete button logic
        row.querySelector(".deleteMainLabourRow").addEventListener("click", function() {
            if (document.querySelectorAll(".mainLabourRow").length > 1) {
                row.remove();
                mainLabourRowCount--;
                updateTotalLabourAjaxNetAmount();
            } else {
                alert("At least one row is required!");
            }
        });

        // Bind AJAX search for this row
        const searchInput = row.querySelector(".labourCodeSearch");
        const resultContainer = row.querySelector(".labourSearchResults");

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

    document.addEventListener("DOMContentLoaded", function() {
        const container = document.querySelector(".mainLabourContainer");
        const addBtn = document.getElementById("addMainLabourRow");

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

            // Bind existing first row
            const initialRow = container.querySelector(".mainLabourRow");
            if (initialRow) {
                addListenersToLabourRow(initialRow);
            }

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

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

                    // Clear any search results in new row
                    const resultBox = newRow.querySelector(".labourSearchResults");
                    if (resultBox) {
                        resultBox.innerHTML = "";
                        resultBox.style.display = "none";
                    }

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