document.addEventListener('DOMContentLoaded', () => {
    const permissionsContainer = document.getElementById('permissionsContainer');
  
  let permissions;

    async function loadAllPermissions() {
        try {
          const response = await fetch('/api/permission/all');
          if (!response.ok) {
            throw new Error('Failed to fetch permissions');
          }
           permissions = await response.json();
      
          console.log('Permissions:', permissions['NEW_TRANSACTION']);
          renderPermissions(permissions);
          return permissions;
        } catch (error) {
          console.error('Error loading permissions:', error);
        }
      }
    
      loadAllPermissions();


    // Render permissions categorized by groups
    const renderPermissions = (permissionsCategories) => {
      Object.keys(permissionsCategories).forEach((categoryKey) => {
        const category = permissionsCategories[categoryKey];
  
        // Create category container
        const categoryDiv = document.createElement('div');
        categoryDiv.classList.add('permissions-category');
  
        const categoryTitle = document.createElement('h4');
        categoryTitle.textContent = category.name;
        categoryDiv.appendChild(categoryTitle);
  
        // Render each permission under the category
        const permissionsGrid = document.createElement('div');
        permissionsGrid.classList.add('permissions-grid');
  
        Object.keys(category.permissions).forEach((permissionKey) => {
          const permissionDiv = document.createElement('div');
          permissionDiv.classList.add('permission-item');
  
          const toggleLabel = document.createElement('label');
          toggleLabel.classList.add('switch');
  
          const checkbox = document.createElement('input');
          checkbox.type = 'checkbox';
          checkbox.id = `perm-${permissionKey}`;
          checkbox.value = permissionKey;
  
          const slider = document.createElement('span');
          slider.classList.add('slider');
  
          const permissionName = document.createElement('span');
          permissionName.classList.add('permission-name');
          permissionName.textContent = category.permissions[permissionKey];
  
          toggleLabel.appendChild(checkbox);
          toggleLabel.appendChild(slider);
  
          permissionDiv.appendChild(toggleLabel);
          permissionDiv.appendChild(permissionName);
          permissionsGrid.appendChild(permissionDiv);
        });
  
        categoryDiv.appendChild(permissionsGrid);
        permissionsContainer.appendChild(categoryDiv);
      });
    };
  
    // Render permissions from the defined categories
 
  
    // 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.trim();
      if (!roleName) {
        alert('Role name is required.');
        return;
      }
  
      // 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 {
       
        // Send POST request to create role
        const response = await fetch('/api/role', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify(payload),
        });
 
        if (!response.ok) {
          throw new Error('Failed to create role');
        }
     
        const result = await response.json();
        alert(`Role created successfully`);
        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;
  });
});

  });
  