(() => {
  const root = document.querySelector("[data-permission-bulk]");
  if (!root) return;

  const selectAll = root.querySelector("[data-permission-select-all]");
  const bulkLevel = root.querySelector("[data-permission-bulk-level]");
  const apply = root.querySelector("[data-permission-apply]");
  const rows = Array.from(document.querySelectorAll(".permission-user-row"));

  const checkedRows = () => rows.filter((row) => row.querySelector("[data-permission-user]")?.checked);

  const updateSelectAll = () => {
    const selected = checkedRows().length;
    selectAll.checked = selected > 0 && selected === rows.length;
    selectAll.indeterminate = selected > 0 && selected < rows.length;
  };

  selectAll?.addEventListener("change", () => {
    rows.forEach((row) => {
      const checkbox = row.querySelector("[data-permission-user]");
      if (checkbox) checkbox.checked = selectAll.checked;
    });
    updateSelectAll();
  });

  rows.forEach((row) => {
    row.querySelector("[data-permission-user]")?.addEventListener("change", updateSelectAll);
  });

  apply?.addEventListener("click", () => {
    checkedRows().forEach((row) => {
      const select = row.querySelector("[data-permission-select]");
      if (select) select.value = bulkLevel.value;
    });
  });
})();
