document.addEventListener('DOMContentLoaded', async () => {
    const permissionsContainer = document.getElementById('permissionsContainer');
  
    // Fetch permissions from the backend
    const fetchPermissions = async () => {
      try {
        const response = await fetch('/api/role/permission'); // Existing API endpoint
        if (!response.ok) {
          throw new Error('Failed to fetch permissions');
        }
        return await response.json(); // Assume flat array of permissions
      } catch (error) {
        console.error('Error fetching permissions:', error);
        alert('Could not load permissions. Please try again later.');
        return [];
      }
    };
  
    // Render permissions as checkboxes
    const renderPermissions = (permissions) => {
      permissions.forEach((permission) => {
        const permissionDiv = document.createElement('div');
        permissionDiv.classList.add('permission-item');
  
        const checkbox = document.createElement('input');
        checkbox.type = 'checkbox';
        checkbox.id = `perm-${permission.name}`;
        checkbox.value = permission.name;
  
        const label = document.createElement('label');
        label.htmlFor = `perm-${permission.name}`;
        label.textContent = permission.description || permission.name;
  
        permissionDiv.appendChild(checkbox);
        permissionDiv.appendChild(label);
        permissionsContainer.appendChild(permissionDiv);
      });
    };
  
    // Load and render permissions
    const permissions = await fetchPermissions();
    renderPermissions(permissions);
  
    // Handle form submission
    const createRoleForm = document.getElementById('createRoleForm');
    createRoleForm.addEventListener('submit', async (e) => {
      e.preventDefault(); // Prevent default form submission
  
      // Get role name
      const roleName = document.getElementById('roleName').value;
  
      // Get selected permissions
      const selectedPermissions = Array.from(
        document.querySelectorAll('#permissionsContainer input[type="checkbox"]:checked')
      ).map((checkbox) => checkbox.value);
  
      if (!selectedPermissions.length) {
        alert('Please select at least one permission.');
        return;
      }
  
      // Prepare payload
      const payload = {
        roleName,
        permissionNames: selectedPermissions,
      };
  
      try {
        alert(0)
        // Send POST request to create role
        const response = await fetch('/api/role', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify(payload),
        });
  alert(1)
        if (!response.ok) {
          throw new Error('Failed to create role');
        }
  alert(2)
        const result = await response.json();
        alert(`Role created successfully: ${result.role.name}`);
        createRoleForm.reset(); // Reset form after successful submission
      } catch (error) {
        console.error('Error creating role:', error);
        alert('Could not create role. Please try again later.');
      }
    });

// Add "Select All" functionality
const selectAllCheckbox = document.getElementById('selectAllPermissions');
selectAllCheckbox.addEventListener('change', (e) => {
  const allCheckboxes = document.querySelectorAll('#permissionsContainer input[type="checkbox"]');
  allCheckboxes.forEach((checkbox) => {
    checkbox.checked = e.target.checked;
  });
});


  });
  