(function () {
  function updateCounter(form) {
    var counter = document.getElementById('permissionCounter');
    if (!counter || !form) return;
    counter.textContent = form.querySelectorAll('input[type="checkbox"]:checked').length;
  }

  document.addEventListener('DOMContentLoaded', function () {
    var roleSearch = document.getElementById('roleMatrixSearch');
    if (roleSearch) {
      roleSearch.addEventListener('input', function () {
        var term = this.value.toLowerCase();
        document.querySelectorAll('[data-role-card]').forEach(function (card) {
          card.style.display = card.getAttribute('data-role-name').indexOf(term) !== -1 ? '' : 'none';
        });
      });
    }

    var form = document.getElementById('ngbvdPermissionForm');
    if (!form) return;

    form.addEventListener('change', function (e) {
      if (e.target && e.target.type === 'checkbox') updateCounter(form);
    });

    document.querySelectorAll('[data-permission-action="select"]').forEach(function (btn) {
      btn.addEventListener('click', function () {
        form.querySelectorAll('input[type="checkbox"]').forEach(function (i) { i.checked = true; });
        updateCounter(form);
      });
    });

    document.querySelectorAll('[data-permission-action="clear"]').forEach(function (btn) {
      btn.addEventListener('click', function () {
        form.querySelectorAll('input[type="checkbox"]').forEach(function (i) { i.checked = false; });
        updateCounter(form);
      });
    });

    document.querySelectorAll('[data-module-select]').forEach(function (btn) {
      btn.addEventListener('click', function () {
        var box = document.querySelector(this.getAttribute('data-module-select'));
        if (!box) return;
        box.querySelectorAll('input[type="checkbox"]').forEach(function (i) { i.checked = true; });
        updateCounter(form);
      });
    });

    document.querySelectorAll('[data-module-clear]').forEach(function (btn) {
      btn.addEventListener('click', function () {
        var box = document.querySelector(this.getAttribute('data-module-clear'));
        if (!box) return;
        box.querySelectorAll('input[type="checkbox"]').forEach(function (i) { i.checked = false; });
        updateCounter(form);
      });
    });

    var search = document.getElementById('permissionSearch');
    if (search) {
      search.addEventListener('input', function () {
        var term = this.value.toLowerCase();
        document.querySelectorAll('[data-permission-option]').forEach(function (opt) {
          opt.style.display = opt.getAttribute('data-permission-text').indexOf(term) !== -1 ? '' : 'none';
        });
      });
    }

    updateCounter(form);
  });
})();
