/**
 * Live counter for the advanced robots directives panel.
 *
 * PHP renders the badge with the count it knows at page load. Without this the
 * number would only follow a save + reload, so ticking a box inside a collapsed
 * panel appeared to do nothing. Everything else stays server-rendered; this only
 * keeps the summary honest while the panel is being edited.
 */
(function () {
    'use strict';

    /**
     * Fill one placeholder without letting the value expand.
     *
     * Copy of the canonical helper in assets/js/tamrank-onboarding.js; read the
     * docblock there for why String.replace() with a STRING replacement mangles
     * any value carrying $&, $`, $' or $$, and why this is a copy instead of a
     * shared global. `token` may be a string or a RegExp; a FUNCTION replacement
     * is exempt from that expansion in both cases. Keep the body identical.
     */
    function fillPlaceholder(tpl, token, value) {
        var literal = String(value);
        return String(tpl).replace(token, function () { return literal; });
    }

    /**
     * Count the fields inside the panel body that hold a value.
     *
     * Scoped to __body on purpose: noindex and nofollow sit outside the panel
     * and must not be counted.
     *
     * @param {HTMLElement} panel The <details> element.
     * @return {number} Number of directives that are set.
     */
    function activeCount(panel) {
        var fields = panel.querySelectorAll('.tr-robots-adv__body input, .tr-robots-adv__body select');
        var count = 0;
        var i;

        for (i = 0; i < fields.length; i++) {
            if (fields[i].type === 'checkbox') {
                if (fields[i].checked) {
                    count++;
                }
            } else if (fields[i].value !== '') {
                count++;
            }
        }

        return count;
    }

    /**
     * Write the current count into the badge, hiding it at zero.
     *
     * @param {HTMLElement} panel The <details> element.
     * @return {void}
     */
    function sync(panel) {
        var badge = panel.querySelector('.tr-robots-adv__count');
        var count;

        if (!badge) {
            return;
        }

        count = activeCount(panel);

        if (count === 0) {
            badge.hidden = true;
            return;
        }

        badge.textContent = fillPlaceholder(panel.getAttribute('data-tr-count-label') || '%d', '%d', count);
        badge.hidden = false;
    }

    function init() {
        var panels = document.querySelectorAll('.tr-robots-adv');
        var i;

        for (i = 0; i < panels.length; i++) {
            (function (panel) {
                var update = function () {
                    sync(panel);
                };

                // 'change' covers checkboxes and the select, 'input' the number
                // fields while typing.
                panel.addEventListener('change', update);
                panel.addEventListener('input', update);
                sync(panel);
            }(panels[i]));
        }
    }

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