(function () {
    const container = document.getElementById('tax-group-rows');
    const addBtn = document.getElementById('btn-add-tax-row');
    const template = document.getElementById('tax-group-row-template');
    if (!container || !addBtn || !template) return;

    function renumberRows() {
        container.querySelectorAll('.billing-tax-group-row').forEach((row, i) => {
            const label = row.querySelector('.form-label');
            if (label) label.textContent = 'Tax ' + (i + 1);
            row.dataset.rowIndex = String(i);
        });
    }

    function bindRemove(btn) {
        btn.addEventListener('click', () => {
            const row = btn.closest('.billing-tax-group-row');
            if (row && container.querySelectorAll('.billing-tax-group-row').length > 1) {
                row.remove();
                renumberRows();
            }
        });
    }

    container.querySelectorAll('.billing-tax-group-row__remove').forEach(bindRemove);

    addBtn.addEventListener('click', () => {
        const index = container.querySelectorAll('.billing-tax-group-row').length;
        let html = template.innerHTML.replace(/__INDEX__/g, String(index)).replace(/__NUM__/g, String(index + 1));
        const wrap = document.createElement('div');
        wrap.innerHTML = html.trim();
        const row = wrap.firstElementChild;
        container.appendChild(row);
        const removeBtn = row.querySelector('.billing-tax-group-row__remove');
        if (removeBtn) bindRemove(removeBtn);
        renumberRows();
    });
})();
