/**
 * Attention Capture - admin repeaters.
 *
 * Adds/removes dynamic cards on the Attention Capture settings page. Each new
 * card is cloned from a hidden <template>, with the `__INDEX__` placeholder in
 * field names replaced by a unique index so arrays round-trip through PHP.
 *
 * No jQuery dependency.
 */

(function () {
    'use strict';

    var REPEATERS = [
        {
            key: 'conditional-rules',
            templateId: 'niwa-conditional-rule-template',
            titlePrefix: 'Rule #'
        },
        {
            key: 'ignore-pages',
            templateId: 'niwa-ignore-page-template',
            titlePrefix: 'Ignored page #'
        },
        {
            key: 'hide-niwa-pages',
            templateId: 'niwa-hide-niwa-page-template',
            titlePrefix: 'Custom page #'
        }
    ];

    function getContainer(key) {
        return document.querySelector('[data-niwa-repeater="' + key + '"]');
    }

    function getTemplate(config) {
        return document.getElementById(config.templateId);
    }

    function renumber(container, config) {
        var cards = container.querySelectorAll('.niwa-rule');
        for (var i = 0; i < cards.length; i++) {
            var titleEl = cards[i].querySelector('.niwa-rule__title');
            if (titleEl) {
                titleEl.textContent = config.titlePrefix + (i + 1);
            }
        }
    }

    function syncAllProductsState(card) {
        var checkbox = card.querySelector('.niwa-rule__all-products');
        if (!checkbox) return;
        if (checkbox.checked) {
            card.classList.add('is-all-products');
        } else {
            card.classList.remove('is-all-products');
        }
    }

    function addRule(container, template, counterRef, config) {
        var empty = container.querySelector('.niwa-repeater__empty');
        if (empty) {
            empty.parentNode.removeChild(empty);
        }

        var index = counterRef.value++;
        var html = template.innerHTML.replace(/__INDEX__/g, String(index));

        var wrapper = document.createElement('div');
        wrapper.innerHTML = html.trim();

        var card = wrapper.querySelector('.niwa-rule');
        if (!card) return;

        // The template card carries a marker attribute - drop it on the live clone.
        card.removeAttribute('data-niwa-rule-template');

        container.appendChild(card);
        syncAllProductsState(card);
        renumber(container, config);

        var firstInput = card.querySelector('input, textarea, select');
        if (firstInput && typeof firstInput.focus === 'function') {
            firstInput.focus();
        }
    }

    function initRepeater(config) {
        var container = getContainer(config.key);
        var template = getTemplate(config);
        if (!container || !template) {
            return;
        }

        var counterRef = { value: container.querySelectorAll('.niwa-rule').length };

        var addButtons = document.querySelectorAll('[data-niwa-repeater-add="' + config.key + '"]');
        for (var i = 0; i < addButtons.length; i++) {
            addButtons[i].addEventListener('click', function (e) {
                e.preventDefault();
                addRule(container, template, counterRef, config);
            });
        }

        container.addEventListener('click', function (e) {
            var removeBtn = e.target.closest('.niwa-rule__remove');
            if (!removeBtn) return;
            e.preventDefault();
            var card = removeBtn.closest('.niwa-rule');
            if (card && card.parentNode) {
                card.parentNode.removeChild(card);
                renumber(container, config);
            }
        });

        container.addEventListener('change', function (e) {
            if (e.target && e.target.classList.contains('niwa-rule__all-products')) {
                var card = e.target.closest('.niwa-rule');
                if (card) {
                    syncAllProductsState(card);
                }
            }
        });

        var cards = container.querySelectorAll('.niwa-rule');
        for (var j = 0; j < cards.length; j++) {
            syncAllProductsState(cards[j]);
        }
        renumber(container, config);
    }

    function init() {
        for (var i = 0; i < REPEATERS.length; i++) {
            initRepeater(REPEATERS[i]);
        }
    }

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