/**
 * Repeatable "Attribute / Value" rows for the asset Technical Information
 * fieldset.
 *
 * Progressive enhancement only: the form renders a handful of empty rows
 * server-side, which already work as plain named array inputs
 * (`spec_key[]` / `spec_value[]`) with JavaScript disabled. This script adds
 * the convenience of inserting more rows or removing one — it does not create
 * the baseline capability, which already exists without it.
 */

const CONTAINER_SELECTOR = '[data-specs-container]';
const ROW_SELECTOR = '[data-specs-row]';
const ADD_SELECTOR = '[data-specs-add]';
const REMOVE_SELECTOR = '[data-specs-remove]';

function clearRowInputs(row) {
    row.querySelectorAll('input').forEach((input) => {
        input.value = '';
    });
}

function addRow(container) {
    const rows = container.querySelectorAll(ROW_SELECTOR);
    const lastRow = rows[rows.length - 1];

    if (!lastRow) {
        return;
    }

    const clone = lastRow.cloneNode(true);
    clearRowInputs(clone);
    lastRow.insertAdjacentElement('afterend', clone);
}

function removeRow(row, container) {
    // Always leave at least one row so the fieldset never disappears entirely.
    const rows = container.querySelectorAll(ROW_SELECTOR);

    if (rows.length <= 1) {
        clearRowInputs(row);

        return;
    }

    row.remove();
}

document.addEventListener('click', (event) => {
    const addButton = event.target.closest(ADD_SELECTOR);

    if (addButton) {
        const container = addButton.closest(CONTAINER_SELECTOR);

        if (container) {
            addRow(container);
        }

        return;
    }

    const removeButton = event.target.closest(REMOVE_SELECTOR);

    if (removeButton) {
        const row = removeButton.closest(ROW_SELECTOR);
        const container = removeButton.closest(CONTAINER_SELECTOR);

        if (row && container) {
            removeRow(row, container);
        }
    }
});
