{% load static i18n %}
<table id="table-{{ widget.attrs.id }}">
    <thead>
    <tr>
        <th>{% blocktrans %}key{% endblocktrans %}</th>
        <th>{% blocktrans %}value{% endblocktrans %}</th>
    </tr>
    </thead>
    <tbody id="json-fields-{{ widget.attrs.id }}">
    {% for key, value in widget.value.items %}
        <tr data-row-index="{{ forloop.counter }}">
            <td><label>
                <input type="text" name="{{ widget.name }}_key" value="{{ key }}">
            </label></td>
            <td>
                {% if value is list %}
                    <label>
                        <input type="text" name="{{ widget.name }}_value" value="{{ value|join:', ' }}">
                    </label>
                {% else %}
                    <label>
                        <input type="text" name="{{ widget.name }}_value" value="{{ value }}">
                    </label>
                {% endif %}
            </td>
        </tr>
    {% endfor %}
    <tr data-row-index="{{ widget.value.items|length|default:0|add:1 }}">
        <td><label>
            <input type="text" name="{{ widget.name }}_key">
        </label></td>
        <td><label>
            <input type="text" name="{{ widget.name }}_value">
        </label></td>
    </tr>
    </tbody>
</table>

<button type="button" class="add-row-button" data-table-id="json-fields-{{ widget.attrs.id }}">
    {% blocktrans %}Add Row{% endblocktrans %}
</button>

<script>
    document.addEventListener("DOMContentLoaded", function () {
        document.querySelectorAll(".add-row-button").forEach(function (button) {
            button.removeEventListener("click", addRow);
            button.addEventListener("click", addRow);
        });
    });

    function addRow(event) {
        let tableId = event.target.getAttribute("data-table-id");
        let table = document.getElementById(tableId);

        if (table) {
            let lastRow = table.querySelector("tr:last-child");
            let rowIndex = (parseInt(lastRow.getAttribute("data-row-index"), 10) + 1).toString();

            let row = table.insertRow();
            row.setAttribute("data-row-index", rowIndex);

            let keyCell = row.insertCell(0);
            let valueCell = row.insertCell(1);

            let namePrefix = tableId.replace("json-fields-", "");

            keyCell.innerHTML = `<input type="text" name="${namePrefix}_key_${rowIndex}">`;
            valueCell.innerHTML = `<input type="text" name="${namePrefix}_value_${rowIndex}">`;
        }
    }
</script>
