{% extends 'formie/_formfields/field' %}

{% set id = 'formie-repeater-' ~ random() %}

{% block field %}

{% namespace field.handle %}
    <div id="{{ id }}" class="fui-repeater-rows" data-repeater-rows>
        {% for row in value %}
            {% include 'formie/_formfields/repeater/fields' with {
                index: loop.index0,
                value: row,
            } %}
        {% endfor %}
    </div>

    {% set buttonAttributes = {
        class: 'btn add icon',
        type: 'button',
        data: {
            'min-rows': field.minRows,
            'max-rows': field.maxRows,
            'add-repeater-row': field.handle,
        }
    } %}

    <button {{ attr(buttonAttributes) }}>
        {{ field.addLabel }}
    </button>

    <script type="text/template" data-repeater-template="{{ field.handle }}">
        {% include 'formie/_formfields/repeater/fields' %}
    </script>
{% endnamespace %}

{% endblock %}

{# Ensure we initialize any JS in repeater blocks, like element fields. Only for the CP. #}
{% if footHtml is defined %}
    {% js %}

    var $repeaterRows = document.querySelector('#fields-{{ field.handle }}-{{ id }}');

    if ($repeaterRows) {
        var $repeaterField = $repeaterRows.parentNode;

        if ($repeaterField) {
            $repeaterField.addEventListener('append', function(e) {
                var id = 'new' + e.detail.repeater.getNumRows();
                var js = '{{ footHtml | e('js') }}'.replace(/__ROW__/g, id);
                
                Craft.appendFootHtml(js);
                Craft.initUiElements($repeaterField);
            });
        }
    }

    {% endjs %}
{% endif %}
