<?php
$users = is_array($users ?? null) ? $users : [];
$roles = is_array($roles ?? null) ? $roles : [];
$branches = is_array($branches ?? null) ? $branches : [];
$permissionsCatalog = is_array($permissionsCatalog ?? null) ? $permissionsCatalog : [];
$rolePermissionMap = is_array($rolePermissionMap ?? null) ? $rolePermissionMap : [];

$permissionsByModule = [];
foreach ($permissionsCatalog as $permission) {
    $module = trim((string) ($permission['modulo'] ?? 'general'));
    $module = $module !== '' ? $module : 'general';
    if (!isset($permissionsByModule[$module])) {
        $permissionsByModule[$module] = [];
    }
    $permissionsByModule[$module][] = $permission;
}
ksort($permissionsByModule);

$totalUsers = count($users);
$activeUsers = 0;
$assignedBranchUsers = 0;
foreach ($users as $item) {
    if ((int) ($item['activo'] ?? 0) === 1) {
        $activeUsers++;
    }
    if ((int) ($item['sucursal_id'] ?? 0) > 0) {
        $assignedBranchUsers++;
    }
}
$inactiveUsers = max(0, $totalUsers - $activeUsers);

$roleLookupByName = [];
foreach ($roles as $role) {
    $key = strtolower(trim((string) ($role['nombre'] ?? '')));
    if ($key === '') {
        continue;
    }
    $roleLookupByName[$key] = (int) ($role['id'] ?? 0);
}
?>

<div class="row g-3 mb-3">
    <div class="col-sm-6 col-xl-3">
        <div class="card border-0 shadow-sm vx-users-metric-card">
            <div class="card-body">
                <small class="vx-users-metric-label">Usuarios</small>
                <p class="vx-users-metric-value mb-0"><?= e((string) $totalUsers) ?></p>
            </div>
        </div>
    </div>
    <div class="col-sm-6 col-xl-3">
        <div class="card border-0 shadow-sm vx-users-metric-card">
            <div class="card-body">
                <small class="vx-users-metric-label">Activos</small>
                <p class="vx-users-metric-value mb-0"><?= e((string) $activeUsers) ?></p>
            </div>
        </div>
    </div>
    <div class="col-sm-6 col-xl-3">
        <div class="card border-0 shadow-sm vx-users-metric-card">
            <div class="card-body">
                <small class="vx-users-metric-label">Inactivos</small>
                <p class="vx-users-metric-value mb-0"><?= e((string) $inactiveUsers) ?></p>
            </div>
        </div>
    </div>
    <div class="col-sm-6 col-xl-3">
        <div class="card border-0 shadow-sm vx-users-metric-card">
            <div class="card-body">
                <small class="vx-users-metric-label">Con Sucursal</small>
                <p class="vx-users-metric-value mb-0"><?= e((string) $assignedBranchUsers) ?></p>
            </div>
        </div>
    </div>
</div>

<div class="row g-3">
    <div class="col-xl-4">
        <div class="card border-0 shadow-sm h-100">
            <div class="card-body">
                <div class="d-flex align-items-center gap-2 mb-3">
                    <span class="vx-auth-icon"><i class="bx bx-user-plus"></i></span>
                    <div>
                        <h2 class="h6 mb-0">Nuevo usuario</h2>
                        <small class="text-muted">Acceso y rol en un solo paso</small>
                    </div>
                </div>

                <form action="<?= e(url('usuarios')) ?>" method="post">
                    <?= csrf_field() ?>
                    <div class="row g-2">
                        <div class="col-12">
                            <label class="form-label">Nombre</label>
                            <input class="form-control" name="nombre" value="<?= e(old('nombre', '')) ?>" required>
                        </div>
                        <div class="col-12">
                            <label class="form-label">Correo</label>
                            <input type="email" class="form-control" name="email" value="<?= e(old('email', '')) ?>" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Rol</label>
                            <select class="form-select" name="rol_id" required>
                                <option value="">Seleccione...</option>
                                <?php foreach ($roles as $role): ?>
                                    <option value="<?= e((string) ($role['id'] ?? 0)) ?>" <?= (int) old('rol_id', '0') === (int) ($role['id'] ?? 0) ? 'selected' : '' ?>>
                                        <?= e((string) ($role['nombre'] ?? '')) ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Sucursal</label>
                            <select class="form-select" name="sucursal_id">
                                <option value="0">Sin asignar</option>
                                <?php foreach ($branches as $branch): ?>
                                    <option value="<?= e((string) ($branch['id'] ?? 0)) ?>" <?= (int) old('sucursal_id', '0') === (int) ($branch['id'] ?? 0) ? 'selected' : '' ?>>
                                        <?= e((string) ($branch['nombre'] ?? '')) ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-12">
                            <label class="form-label">Contraseña</label>
                            <div class="input-group">
                                <input type="password" class="form-control" name="password" id="vxUserPasswordInput" minlength="8" required>
                                <button class="btn btn-outline-secondary" type="button" id="vxUserPasswordToggle" aria-label="Mostrar u ocultar contraseña">
                                    <i class="bx bx-show"></i>
                                </button>
                            </div>
                            <small class="text-muted">Mínimo 8 caracteres.</small>
                        </div>
                    </div>

                    <button class="btn btn-primary w-100 mt-3" type="submit">
                        <i class="bx bx-save me-1"></i>Guardar usuario
                    </button>
                </form>
            </div>
        </div>
    </div>

    <div class="col-xl-8">
        <div class="card border-0 shadow-sm h-100">
            <div class="card-body">
                <div class="d-flex flex-wrap align-items-start justify-content-between gap-2 mb-3">
                    <div>
                        <h1 class="h5 mb-0">Usuarios</h1>
                        <small class="text-muted" id="vxUsersVisibleCounter">Mostrando <?= e((string) $totalUsers) ?> de <?= e((string) $totalUsers) ?></small>
                    </div>
                    <button type="button" class="btn btn-sm btn-light border" id="vxUsersClearFilters">
                        <i class="bx bx-eraser me-1"></i>Limpiar filtros
                    </button>
                </div>

                <div class="vx-users-filters mb-3">
                    <div class="input-group input-group-sm vx-users-search">
                        <span class="input-group-text"><i class="bx bx-search"></i></span>
                        <input type="search" class="form-control" id="vxUsersSearch" placeholder="Buscar por nombre, email, rol o sucursal...">
                    </div>
                    <select class="form-select form-select-sm vx-users-filter" id="vxUsersRoleFilter">
                        <option value="">Rol: todos</option>
                        <?php foreach ($roles as $role): ?>
                            <option value="<?= e((string) ($role['id'] ?? 0)) ?>"><?= e((string) ($role['nombre'] ?? '')) ?></option>
                        <?php endforeach; ?>
                    </select>
                    <select class="form-select form-select-sm vx-users-filter" id="vxUsersStatusFilter">
                        <option value="">Estado: todos</option>
                        <option value="activo">Activos</option>
                        <option value="inactivo">Inactivos</option>
                    </select>
                    <select class="form-select form-select-sm vx-users-filter" id="vxUsersBranchFilter">
                        <option value="">Sucursal: todas</option>
                        <option value="0">Sin asignar</option>
                        <?php foreach ($branches as $branch): ?>
                            <option value="<?= e((string) ($branch['id'] ?? 0)) ?>"><?= e((string) ($branch['nombre'] ?? '')) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="table-responsive">
                    <table class="table table-hover align-middle vx-users-table">
                        <thead>
                        <tr>
                            <th>Usuario</th>
                            <th>Rol</th>
                            <th>Sucursal</th>
                            <th>Estado</th>
                        </tr>
                        </thead>
                        <tbody id="vxUsersTableBody">
                        <?php if ($users === []): ?>
                            <tr>
                                <td colspan="4" class="text-center text-muted py-4">No hay usuarios registrados.</td>
                            </tr>
                        <?php endif; ?>
                        <?php foreach ($users as $item): ?>
                            <?php
                            $userName = trim((string) ($item['nombre'] ?? ''));
                            $userEmail = trim((string) ($item['email'] ?? ''));
                            $userRole = trim((string) ($item['rol'] ?? 'Sin rol'));
                            $userRoleKey = strtolower($userRole);
                            $userRoleId = (int) ($roleLookupByName[$userRoleKey] ?? 0);
                            $userBranchName = trim((string) (($item['sucursal'] ?? '') !== '' ? $item['sucursal'] : 'Sin asignar'));
                            $userBranchId = (int) ($item['sucursal_id'] ?? 0);
                            $isActive = (int) ($item['activo'] ?? 0) === 1;
                            $userStatus = $isActive ? 'activo' : 'inactivo';
                            $searchIndex = strtolower(trim($userName . ' ' . $userEmail . ' ' . $userRole . ' ' . $userBranchName));
                            ?>
                            <tr
                                class="vx-user-row"
                                data-search="<?= e($searchIndex) ?>"
                                data-role-id="<?= e((string) $userRoleId) ?>"
                                data-status="<?= e($userStatus) ?>"
                                data-branch-id="<?= e((string) $userBranchId) ?>"
                            >
                                <td>
                                    <div class="d-flex flex-column">
                                        <strong><?= e($userName) ?></strong>
                                        <small class="text-muted"><?= e($userEmail) ?></small>
                                    </div>
                                </td>
                                <td>
                                    <span class="badge text-bg-light border"><?= e($userRole) ?></span>
                                </td>
                                <td><?= e($userBranchName) ?></td>
                                <td>
                                    <span class="badge <?= $isActive ? 'text-bg-success' : 'text-bg-secondary' ?>">
                                        <?= $isActive ? 'Activo' : 'Inactivo' ?>
                                    </span>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="card border-0 shadow-sm mt-3">
    <div class="card-body">
        <div class="d-flex flex-wrap align-items-center justify-content-between gap-2 mb-3">
            <div>
                <h2 class="h6 mb-0">Permisos por rol</h2>
                <small class="text-muted">Interfaz simplificada para asignar permisos rápidamente</small>
            </div>
            <span class="badge text-bg-light border"><?= e((string) count($permissionsCatalog)) ?> permisos en catálogo</span>
        </div>

        <?php if (!has_permission('roles.gestionar')): ?>
            <p class="text-muted mb-0">No tienes permiso para editar roles.</p>
        <?php elseif ($roles === []): ?>
            <p class="text-muted mb-0">No hay roles activos para configurar.</p>
        <?php else: ?>
            <div class="vx-role-tabs mb-3" id="vxRoleTabs">
                <?php foreach ($roles as $roleIndex => $role): ?>
                    <?php
                    $roleId = (int) ($role['id'] ?? 0);
                    $selectedPermissionIds = $rolePermissionMap[$roleId] ?? [];
                    $isActiveRole = $roleIndex === 0;
                    ?>
                    <button
                        type="button"
                        class="vx-role-tab <?= $isActiveRole ? 'is-active' : '' ?>"
                        data-role-tab
                        data-role-target="vxRolePanel<?= e((string) $roleId) ?>"
                    >
                        <span class="vx-role-tab-name"><?= e((string) ($role['nombre'] ?? 'Rol')) ?></span>
                        <span class="vx-role-tab-count" data-role-tab-count="<?= e((string) $roleId) ?>"><?= e((string) count($selectedPermissionIds)) ?></span>
                    </button>
                <?php endforeach; ?>
            </div>

            <div class="vx-role-panels">
                <?php foreach ($roles as $roleIndex => $role): ?>
                    <?php
                    $roleId = (int) ($role['id'] ?? 0);
                    $selectedPermissionIds = $rolePermissionMap[$roleId] ?? [];
                    $isActiveRole = $roleIndex === 0;
                    $accordionId = 'vxRolePermAccordion' . $roleId;
                    ?>
                    <form
                        action="<?= e(url('usuarios/roles/permisos')) ?>"
                        method="post"
                        class="vx-role-panel <?= $isActiveRole ? 'is-active' : '' ?>"
                        id="vxRolePanel<?= e((string) $roleId) ?>"
                        data-role-panel
                        data-role-id="<?= e((string) $roleId) ?>"
                    >
                        <?= csrf_field() ?>
                        <input type="hidden" name="rol_id" value="<?= e((string) $roleId) ?>">

                        <div class="vx-role-panel-toolbar">
                            <div class="input-group input-group-sm vx-role-search">
                                <span class="input-group-text"><i class="bx bx-search"></i></span>
                                <input type="search" class="form-control" data-role-search placeholder="Buscar permiso por nombre o código...">
                            </div>
                            <button type="button" class="btn btn-sm btn-light border" data-role-select-all>
                                <i class="bx bx-check-square me-1"></i>Seleccionar todo
                            </button>
                            <button type="button" class="btn btn-sm btn-light border" data-role-clear-all>
                                <i class="bx bx-x-square me-1"></i>Limpiar
                            </button>
                            <span class="badge text-bg-info" data-role-selected-count><?= e((string) count($selectedPermissionIds)) ?> seleccionados</span>
                            <button class="btn btn-sm btn-primary" type="submit">
                                <i class="bx bx-save me-1"></i>Guardar
                            </button>
                        </div>

                        <div class="accordion vx-role-perm-accordion" id="<?= e($accordionId) ?>">
                            <?php foreach ($permissionsByModule as $module => $permissions): ?>
                                <?php
                                $moduleKeyRaw = strtolower(trim((string) $module));
                                $moduleKeySafe = preg_replace('/[^a-z0-9_-]/', '-', $moduleKeyRaw) ?: 'modulo';
                                $moduleLabel = ucwords(str_replace('_', ' ', $moduleKeyRaw));
                                $moduleSelected = 0;
                                foreach ($permissions as $permission) {
                                    $permissionId = (int) ($permission['id'] ?? 0);
                                    if (in_array($permissionId, $selectedPermissionIds, true)) {
                                        $moduleSelected++;
                                    }
                                }
                                $collapseId = 'vxRole' . $roleId . 'Module' . $moduleKeySafe;
                                $headingId = 'vxRole' . $roleId . 'Heading' . $moduleKeySafe;
                                ?>
                                <div class="accordion-item vx-perm-module" data-module-wrapper>
                                    <h2 class="accordion-header" id="<?= e($headingId) ?>">
                                        <button
                                            class="accordion-button collapsed"
                                            type="button"
                                            data-bs-toggle="collapse"
                                            data-bs-target="#<?= e($collapseId) ?>"
                                            aria-expanded="false"
                                            aria-controls="<?= e($collapseId) ?>"
                                        >
                                            <span class="vx-perm-module-title"><?= e($moduleLabel) ?></span>
                                            <span class="badge text-bg-light border ms-2">
                                                <span data-module-selected-count><?= e((string) $moduleSelected) ?></span>/<?= e((string) count($permissions)) ?>
                                            </span>
                                        </button>
                                    </h2>
                                    <div id="<?= e($collapseId) ?>" class="accordion-collapse collapse" aria-labelledby="<?= e($headingId) ?>" data-bs-parent="#<?= e($accordionId) ?>">
                                        <div class="accordion-body">
                                            <div class="d-flex align-items-center justify-content-between flex-wrap gap-2 mb-2">
                                                <small class="text-muted"><?= e((string) count($permissions)) ?> permisos en este módulo</small>
                                                <button type="button" class="btn btn-sm btn-outline-secondary" data-module-toggle>
                                                    Marcar módulo
                                                </button>
                                            </div>
                                            <div class="vx-perm-grid">
                                                <?php foreach ($permissions as $permission): ?>
                                                    <?php
                                                    $permissionId = (int) ($permission['id'] ?? 0);
                                                    $permissionName = trim((string) ($permission['nombre'] ?? $permission['codigo'] ?? 'Permiso'));
                                                    $permissionCode = trim((string) ($permission['codigo'] ?? ''));
                                                    $permissionSearch = strtolower(trim($permissionName . ' ' . $permissionCode));
                                                    $permissionInputId = 'perm_' . $roleId . '_' . $permissionId;
                                                    ?>
                                                    <label class="vx-perm-chip" data-permission-item data-permission-search="<?= e($permissionSearch) ?>">
                                                        <input
                                                            class="form-check-input vx-perm-check"
                                                            type="checkbox"
                                                            name="permisos[]"
                                                            id="<?= e($permissionInputId) ?>"
                                                            value="<?= e((string) $permissionId) ?>"
                                                            <?= in_array($permissionId, $selectedPermissionIds, true) ? 'checked' : '' ?>
                                                        >
                                                        <span class="vx-perm-chip-text">
                                                            <span class="vx-perm-chip-name"><?= e($permissionName) ?></span>
                                                            <small class="vx-perm-chip-code"><?= e($permissionCode) ?></small>
                                                        </span>
                                                    </label>
                                                <?php endforeach; ?>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    </form>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </div>
</div>

<script>
window.addEventListener('DOMContentLoaded', () => {
    const normalize = (value) => String(value || '')
        .normalize('NFD')
        .replace(/[\u0300-\u036f]/g, '')
        .toLowerCase()
        .trim();

    const passwordInput = document.getElementById('vxUserPasswordInput');
    const passwordToggle = document.getElementById('vxUserPasswordToggle');
    if (passwordInput instanceof HTMLInputElement && passwordToggle instanceof HTMLButtonElement) {
        passwordToggle.addEventListener('click', () => {
            const reveal = passwordInput.type === 'password';
            passwordInput.type = reveal ? 'text' : 'password';
            passwordToggle.innerHTML = reveal ? '<i class="bx bx-hide"></i>' : '<i class="bx bx-show"></i>';
        });
    }

    const usersTableBody = document.getElementById('vxUsersTableBody');
    const usersRows = Array.from(document.querySelectorAll('.vx-user-row'));
    const usersSearch = document.getElementById('vxUsersSearch');
    const roleFilter = document.getElementById('vxUsersRoleFilter');
    const statusFilter = document.getElementById('vxUsersStatusFilter');
    const branchFilter = document.getElementById('vxUsersBranchFilter');
    const clearFilters = document.getElementById('vxUsersClearFilters');
    const visibleCounter = document.getElementById('vxUsersVisibleCounter');

    const updateUsersCounter = (visible, total) => {
        if (!(visibleCounter instanceof HTMLElement)) {
            return;
        }
        visibleCounter.textContent = 'Mostrando ' + visible + ' de ' + total;
    };

    const filterUsers = () => {
        if (
            !(usersSearch instanceof HTMLInputElement) ||
            !(roleFilter instanceof HTMLSelectElement) ||
            !(statusFilter instanceof HTMLSelectElement) ||
            !(branchFilter instanceof HTMLSelectElement)
        ) {
            return;
        }

        const term = normalize(usersSearch.value);
        const roleValue = roleFilter.value;
        const statusValue = statusFilter.value;
        const branchValue = branchFilter.value;
        let visibleCount = 0;

        usersRows.forEach((row) => {
            const haystack = normalize(row.getAttribute('data-search'));
            const rowRoleId = String(row.getAttribute('data-role-id') || '');
            const rowStatus = String(row.getAttribute('data-status') || '');
            const rowBranchId = String(row.getAttribute('data-branch-id') || '');

            const matchesSearch = term === '' || haystack.includes(term);
            const matchesRole = roleValue === '' || rowRoleId === roleValue;
            const matchesStatus = statusValue === '' || rowStatus === statusValue;
            const matchesBranch = branchValue === '' || rowBranchId === branchValue;
            const visible = matchesSearch && matchesRole && matchesStatus && matchesBranch;

            row.classList.toggle('d-none', !visible);
            if (visible) {
                visibleCount++;
            }
        });

        updateUsersCounter(visibleCount, usersRows.length);
    };

    if (usersRows.length > 0) {
        filterUsers();

        if (usersSearch instanceof HTMLInputElement) {
            usersSearch.addEventListener('input', filterUsers);
        }
        if (roleFilter instanceof HTMLSelectElement) {
            roleFilter.addEventListener('change', filterUsers);
        }
        if (statusFilter instanceof HTMLSelectElement) {
            statusFilter.addEventListener('change', filterUsers);
        }
        if (branchFilter instanceof HTMLSelectElement) {
            branchFilter.addEventListener('change', filterUsers);
        }
        if (clearFilters instanceof HTMLButtonElement) {
            clearFilters.addEventListener('click', () => {
                if (usersSearch instanceof HTMLInputElement) {
                    usersSearch.value = '';
                }
                if (roleFilter instanceof HTMLSelectElement) {
                    roleFilter.value = '';
                }
                if (statusFilter instanceof HTMLSelectElement) {
                    statusFilter.value = '';
                }
                if (branchFilter instanceof HTMLSelectElement) {
                    branchFilter.value = '';
                }
                filterUsers();
            });
        }
    } else if (usersTableBody instanceof HTMLElement) {
        updateUsersCounter(0, 0);
    }

    const roleTabs = Array.from(document.querySelectorAll('[data-role-tab]'));
    const rolePanels = Array.from(document.querySelectorAll('[data-role-panel]'));

    const setActiveRole = (targetId) => {
        roleTabs.forEach((tab) => {
            const isActive = tab.getAttribute('data-role-target') === targetId;
            tab.classList.toggle('is-active', isActive);
        });
        rolePanels.forEach((panel) => {
            const isActive = panel.id === targetId;
            panel.classList.toggle('is-active', isActive);
        });
    };

    roleTabs.forEach((tab) => {
        tab.addEventListener('click', () => {
            const targetId = tab.getAttribute('data-role-target') || '';
            if (targetId !== '') {
                setActiveRole(targetId);
            }
        });
    });

    const updateRolePanelCount = (panel) => {
        const roleId = panel.getAttribute('data-role-id') || '';
        const checks = Array.from(panel.querySelectorAll('.vx-perm-check'));
        const selected = checks.filter((check) => check.checked).length;
        const roleCountBadge = panel.querySelector('[data-role-selected-count]');
        if (roleCountBadge instanceof HTMLElement) {
            roleCountBadge.textContent = selected + ' seleccionados';
        }

        const tabCount = document.querySelector('[data-role-tab-count="' + roleId + '"]');
        if (tabCount instanceof HTMLElement) {
            tabCount.textContent = String(selected);
        }

        const modules = Array.from(panel.querySelectorAll('[data-module-wrapper]'));
        modules.forEach((module) => {
            const moduleChecks = Array.from(module.querySelectorAll('.vx-perm-check'));
            const moduleSelected = moduleChecks.filter((check) => check.checked).length;
            const moduleCount = module.querySelector('[data-module-selected-count]');
            if (moduleCount instanceof HTMLElement) {
                moduleCount.textContent = String(moduleSelected);
            }
        });
    };

    const filterRolePermissions = (panel) => {
        const searchInput = panel.querySelector('[data-role-search]');
        if (!(searchInput instanceof HTMLInputElement)) {
            return;
        }

        const term = normalize(searchInput.value);
        const modules = Array.from(panel.querySelectorAll('[data-module-wrapper]'));

        modules.forEach((module) => {
            const items = Array.from(module.querySelectorAll('[data-permission-item]'));
            let visibleInModule = 0;

            items.forEach((item) => {
                const search = normalize(item.getAttribute('data-permission-search'));
                const visible = term === '' || search.includes(term);
                item.classList.toggle('d-none', !visible);
                if (visible) {
                    visibleInModule++;
                }
            });

            module.classList.toggle('d-none', visibleInModule === 0);
        });
    };

    rolePanels.forEach((panel) => {
        const checks = Array.from(panel.querySelectorAll('.vx-perm-check'));
        checks.forEach((check) => {
            check.addEventListener('change', () => updateRolePanelCount(panel));
        });

        const searchInput = panel.querySelector('[data-role-search]');
        if (searchInput instanceof HTMLInputElement) {
            searchInput.addEventListener('input', () => filterRolePermissions(panel));
        }

        const selectAllBtn = panel.querySelector('[data-role-select-all]');
        if (selectAllBtn instanceof HTMLButtonElement) {
            selectAllBtn.addEventListener('click', () => {
                checks.forEach((check) => {
                    check.checked = true;
                });
                updateRolePanelCount(panel);
            });
        }

        const clearBtn = panel.querySelector('[data-role-clear-all]');
        if (clearBtn instanceof HTMLButtonElement) {
            clearBtn.addEventListener('click', () => {
                checks.forEach((check) => {
                    check.checked = false;
                });
                updateRolePanelCount(panel);
            });
        }

        const moduleButtons = Array.from(panel.querySelectorAll('[data-module-toggle]'));
        moduleButtons.forEach((button) => {
            button.addEventListener('click', () => {
                const module = button.closest('[data-module-wrapper]');
                if (!module) {
                    return;
                }
                const moduleChecks = Array.from(module.querySelectorAll('.vx-perm-check'));
                const shouldCheck = moduleChecks.some((check) => !check.checked);
                moduleChecks.forEach((check) => {
                    check.checked = shouldCheck;
                });
                updateRolePanelCount(panel);
            });
        });

        filterRolePermissions(panel);
        updateRolePanelCount(panel);
    });
});
</script>
