(function () {
    'use strict';

    function boot() {
        var body = document.querySelector('[data-component-rows]');
        var template = document.querySelector('[data-component-template]');
        var addButton = document.querySelector('[data-component-add]');
        var emptyState = document.querySelector('[data-component-empty]');

        if (!body || !template || !addButton) {
            return;
        }

        var nextIndex = body.querySelectorAll('[data-component-row]').length;

        function toggleEmptyState() {
            if (!emptyState) {
                return;
            }
            var hasRows = body.querySelectorAll('[data-component-row]').length > 0;
            emptyState.style.display = hasRows ? 'none' : '';
        }

        function addRow() {
            var html = template.innerHTML.replace(/__INDEX__/g, String(nextIndex));
            nextIndex += 1;
            body.insertAdjacentHTML('beforeend', html);
            toggleEmptyState();
        }

        addButton.addEventListener('click', addRow);

        body.addEventListener('click', function (event) {
            var trigger = event.target.closest('[data-component-remove]');
            if (!trigger) {
                return;
            }
            var row = trigger.closest('[data-component-row]');
            if (row) {
                row.remove();
                toggleEmptyState();
            }
        });

        toggleEmptyState();
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', boot);
    } else {
        boot();
    }
})();
