(function () {
    'use strict';

    function rows(group) {
        return group.querySelector('[data-niwa-wa-access-rows]');
    }

    function template(group) {
        return group.querySelector('[data-niwa-wa-access-template]');
    }

    function sync(group) {
        var list = rows(group);
        if (!list) return;

        var items = list.querySelectorAll('[data-niwa-wa-access-row]');
        var count = group.querySelector('[data-niwa-wa-access-count]');
        var empty = group.querySelector('[data-niwa-wa-access-empty]');

        if (count) {
            count.textContent = String(items.length);
        }
        if (empty) {
            empty.hidden = items.length > 0;
        }
    }

    function nextIndex(group) {
        var list = rows(group);
        if (!list) return 0;

        var max = -1;
        var inputs = list.querySelectorAll('input[name]');
        for (var i = 0; i < inputs.length; i++) {
            var match = inputs[i].name.match(/\[(\d+)\]\[(label|phone|jid)\]$/);
            if (match) {
                max = Math.max(max, parseInt(match[1], 10));
            }
        }
        return max + 1;
    }

    function addRow(group) {
        var list = rows(group);
        var tpl = template(group);
        if (!list || !tpl) return;

        var html = tpl.innerHTML.replace(/__INDEX__/g, String(nextIndex(group)));
        var wrapper = document.createElement('div');
        wrapper.innerHTML = html.trim();

        var row = wrapper.querySelector('[data-niwa-wa-access-row]');
        if (!row) return;

        list.appendChild(row);
        sync(group);

        var first = row.querySelector('input');
        if (first && typeof first.focus === 'function') {
            first.focus();
        }
    }

    function initGroup(group) {
        sync(group);

        var add = group.querySelector('[data-niwa-wa-access-add]');
        if (add) {
            add.addEventListener('click', function (event) {
                event.preventDefault();
                addRow(group);
            });
        }

        group.addEventListener('click', function (event) {
            var remove = event.target.closest('[data-niwa-wa-access-remove]');
            if (!remove) return;

            event.preventDefault();
            var row = remove.closest('[data-niwa-wa-access-row]');
            if (row && row.parentNode) {
                row.parentNode.removeChild(row);
                sync(group);
            }
        });
    }

    function init() {
        var groups = document.querySelectorAll('[data-niwa-wa-access-group]');
        for (var i = 0; i < groups.length; i++) {
            initGroup(groups[i]);
        }
    }

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