(function () {
    var cards = document.getElementById('niadm-cards');
    if (!cards) return;

    cards.addEventListener('change', function (e) {
        var checkbox = e.target.closest('.niadm-toggle-switch input[type="checkbox"]');
        if (!checkbox) return;

        var card = checkbox.closest('.niadm-card');
        if (!card) return;

        var set_id = card.dataset.setId;
        var enabled = checkbox.checked ? 1 : 0;
        var statusEl = card.querySelector('.niadm-card__status');

        if (enabled) {
            card.classList.remove('niadm-card--disabled');
            card.classList.add('niadm-card--enabled');
            if (statusEl) {
                statusEl.textContent = 'Enabled';
                statusEl.className = 'niadm-card__status niadm-card__status--enabled';
            }
        } else {
            card.classList.remove('niadm-card--enabled');
            card.classList.add('niadm-card--disabled');
            if (statusEl) {
                statusEl.textContent = 'Disabled';
                statusEl.className = 'niadm-card__status niadm-card__status--disabled';
            }
        }

        var formData = new FormData();
        formData.append('action', 'ninz_toggle_icon_set');
        formData.append('nonce', ninzIconsData.nonce);
        formData.append('set_id', set_id);
        formData.append('enabled', enabled);

        fetch(ninzIconsData.ajaxUrl, {
            method: 'POST',
            body: formData
        }).then(function (r) { return r.json(); }).catch(function () {
            checkbox.checked = !checkbox.checked;
        });
    });
})();
