@extends('layouts.app')

@section('title', 'Usuarios | Veltrix v2')
@section('page_title', 'Usuarios')
@section('page_subtitle', 'Gestion operativa en tiempo real')
@section('page_icon', 'bx bxs-group')

@section('content')
    @php
        $usersRows = $usuarios instanceof \Illuminate\Support\Collection ? $usuarios : collect($usuarios ?? []);
        $rolesRows = $roles instanceof \Illuminate\Support\Collection ? $roles : collect($roles ?? []);
        $sucursalesRows = $sucursales instanceof \Illuminate\Support\Collection ? $sucursales : collect($sucursales ?? []);
        $permissionsRows = $permissionsCatalog instanceof \Illuminate\Support\Collection ? $permissionsCatalog : collect($permissionsCatalog ?? []);
        $rolePermissionMapValue = is_array($rolePermissionMap ?? null) ? $rolePermissionMap : [];

        $permissionsByModule = $permissionsRows
            ->groupBy(static function ($permission): string {
                $module = trim((string) ($permission->modulo ?? 'general'));
                return $module !== '' ? $module : 'general';
            })
            ->sortKeys();

        $totalUsers = $usersRows->count();
        $activeUsers = $usersRows->where('activo', true)->count();
        $inactiveUsers = max(0, $totalUsers - $activeUsers);
        $assignedBranchUsers = $usersRows->filter(static fn ($user): bool => (int) ($user->sucursal_id ?? 0) > 0)->count();

        $oldRoleId = (int) old('rol_id', 0);
        $oldSucursalId = (int) old('sucursal_id', 0);
    @endphp

    @if ($errors->any())
        <div class="alert alert-danger mb-3">
            {{ $errors->first() }}
        </div>
    @endif

    <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">{{ $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">{{ $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">{{ $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">{{ $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>

                    @if (has_permission('usuarios.crear'))
                        <form action="{{ route('usuarios.store') }}" method="post">
                            @csrf
                            <div class="row g-2">
                                <div class="col-12">
                                    <label class="form-label">Nombre</label>
                                    <input class="form-control" name="nombre" value="{{ old('nombre', '') }}" required>
                                </div>
                                <div class="col-12">
                                    <label class="form-label">Correo</label>
                                    <input type="email" class="form-control" name="email" value="{{ 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>
                                        @foreach ($rolesRows as $role)
                                            @php $roleId = (int) ($role->id ?? 0); @endphp
                                            <option value="{{ $roleId }}" {{ $oldRoleId === $roleId ? 'selected' : '' }}>
                                                {{ (string) ($role->nombre ?? '') }}
                                            </option>
                                        @endforeach
                                    </select>
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">Sucursal</label>
                                    <select class="form-select" name="sucursal_id">
                                        <option value="0" {{ $oldSucursalId === 0 ? 'selected' : '' }}>Sin asignar</option>
                                        @foreach ($sucursalesRows as $sucursal)
                                            @php $sucursalId = (int) ($sucursal->id ?? 0); @endphp
                                            <option value="{{ $sucursalId }}" {{ $oldSucursalId === $sucursalId ? 'selected' : '' }}>
                                                {{ (string) ($sucursal->nombre ?? '') }}
                                            </option>
                                        @endforeach
                                    </select>
                                </div>
                                <div class="col-12">
                                    <label class="form-label">Contrasena</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 contrasena">
                                            <i class="bx bx-show"></i>
                                        </button>
                                    </div>
                                    <small class="text-muted">Minimo 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>
                    @else
                        <p class="text-muted mb-0">No tienes permiso para crear usuarios.</p>
                    @endif
                </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 {{ $totalUsers }} de {{ $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>
                            @foreach ($rolesRows as $role)
                                <option value="{{ (int) ($role->id ?? 0) }}">{{ (string) ($role->nombre ?? '') }}</option>
                            @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>
                            @foreach ($sucursalesRows as $sucursal)
                                <option value="{{ (int) ($sucursal->id ?? 0) }}">{{ (string) ($sucursal->nombre ?? '') }}</option>
                            @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">
                                @if ($usersRows->isEmpty())
                                    <tr>
                                        <td colspan="4" class="text-center text-muted py-4">No hay usuarios registrados.</td>
                                    </tr>
                                @endif
                                @foreach ($usersRows as $item)
                                    @php
                                        $userName = trim((string) ($item->nombre ?? ''));
                                        $userEmail = trim((string) ($item->email ?? ''));
                                        $userRole = trim((string) ($item->rol->nombre ?? 'Sin rol'));
                                        $userRoleId = (int) ($item->rol_id ?? 0);
                                        $userBranchName = trim((string) (($item->sucursal->nombre ?? '') !== '' ? $item->sucursal->nombre : 'Sin asignar'));
                                        $userBranchId = (int) ($item->sucursal_id ?? 0);
                                        $isActive = (bool) ($item->activo ?? false);
                                        $userStatus = $isActive ? 'activo' : 'inactivo';
                                        $searchIndex = strtolower(trim($userName.' '.$userEmail.' '.$userRole.' '.$userBranchName));
                                    @endphp
                                    <tr
                                        class="vx-user-row"
                                        data-search="{{ $searchIndex }}"
                                        data-role-id="{{ $userRoleId }}"
                                        data-status="{{ $userStatus }}"
                                        data-branch-id="{{ $userBranchId }}"
                                    >
                                        <td>
                                            <div class="d-flex flex-column">
                                                <strong>{{ $userName }}</strong>
                                                <small class="text-muted">{{ $userEmail }}</small>
                                            </div>
                                        </td>
                                        <td>
                                            <span class="badge text-bg-light border">{{ $userRole }}</span>
                                        </td>
                                        <td>{{ $userBranchName }}</td>
                                        <td>
                                            <span class="badge {{ $isActive ? 'text-bg-success' : 'text-bg-secondary' }}">
                                                {{ $isActive ? 'Activo' : 'Inactivo' }}
                                            </span>
                                        </td>
                                    </tr>
                                @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 rapidamente</small>
                </div>
                <span class="badge text-bg-light border">{{ $permissionsRows->count() }} permisos en catalogo</span>
            </div>

            @if (! has_permission('roles.gestionar'))
                <p class="text-muted mb-0">No tienes permiso para editar roles.</p>
            @elseif ($rolesRows->isEmpty())
                <p class="text-muted mb-0">No hay roles activos para configurar.</p>
            @else
                <div class="vx-role-tabs mb-3" id="vxRoleTabs">
                    @foreach ($rolesRows as $role)
                        @php
                            $roleId = (int) ($role->id ?? 0);
                            $selectedPermissionIds = collect($rolePermissionMapValue[$roleId] ?? [])->map(static fn ($id): int => (int) $id)->all();
                        @endphp
                        <button
                            type="button"
                            class="vx-role-tab {{ $loop->first ? 'is-active' : '' }}"
                            data-role-tab
                            data-role-target="vxRolePanel{{ $roleId }}"
                        >
                            <span class="vx-role-tab-name">{{ (string) ($role->nombre ?? 'Rol') }}</span>
                            <span class="vx-role-tab-count" data-role-tab-count="{{ $roleId }}">{{ count($selectedPermissionIds) }}</span>
                        </button>
                    @endforeach
                </div>

                <div class="vx-role-panels">
                    @foreach ($rolesRows as $role)
                        @php
                            $roleId = (int) ($role->id ?? 0);
                            $selectedPermissionIds = collect($rolePermissionMapValue[$roleId] ?? [])->map(static fn ($id): int => (int) $id)->all();
                            $accordionId = 'vxRolePermAccordion'.$roleId;
                        @endphp

                        <form
                            action="{{ route('usuarios.roles.permissions.update') }}"
                            method="post"
                            class="vx-role-panel {{ $loop->first ? 'is-active' : '' }}"
                            id="vxRolePanel{{ $roleId }}"
                            data-role-panel
                            data-role-id="{{ $roleId }}"
                        >
                            @csrf
                            <input type="hidden" name="rol_id" value="{{ $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 codigo...">
                                </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>{{ 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="{{ $accordionId }}">
                                @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;
                                    @endphp

                                    <div class="accordion-item vx-perm-module" data-module-wrapper>
                                        <h2 class="accordion-header" id="{{ $headingId }}">
                                            <button
                                                class="accordion-button collapsed"
                                                type="button"
                                                data-bs-toggle="collapse"
                                                data-bs-target="#{{ $collapseId }}"
                                                aria-expanded="false"
                                                aria-controls="{{ $collapseId }}"
                                            >
                                                <span class="vx-perm-module-title">{{ $moduleLabel }}</span>
                                                <span class="badge text-bg-light border ms-2">
                                                    <span data-module-selected-count>{{ $moduleSelected }}</span>/{{ $permissions->count() }}
                                                </span>
                                            </button>
                                        </h2>

                                        <div id="{{ $collapseId }}" class="accordion-collapse collapse" aria-labelledby="{{ $headingId }}" data-bs-parent="#{{ $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">{{ $permissions->count() }} permisos en este modulo</small>
                                                    <button type="button" class="btn btn-sm btn-outline-secondary" data-module-toggle>
                                                        Marcar modulo
                                                    </button>
                                                </div>

                                                <div class="vx-perm-grid">
                                                    @foreach ($permissions as $permission)
                                                        @php
                                                            $permissionId = (int) ($permission->id ?? 0);
                                                            $permissionName = trim((string) (($permission->nombre ?? '') !== '' ? $permission->nombre : ($permission->codigo ?? 'Permiso')));
                                                            $permissionCode = trim((string) ($permission->codigo ?? ''));
                                                            $permissionSearch = strtolower(trim($permissionName.' '.$permissionCode));
                                                            $permissionInputId = 'perm_'.$roleId.'_'.$permissionId;
                                                        @endphp

                                                        <label class="vx-perm-chip" data-permission-item data-permission-search="{{ $permissionSearch }}">
                                                            <input
                                                                class="form-check-input vx-perm-check"
                                                                type="checkbox"
                                                                name="permisos[]"
                                                                id="{{ $permissionInputId }}"
                                                                value="{{ $permissionId }}"
                                                                {{ in_array($permissionId, $selectedPermissionIds, true) ? 'checked' : '' }}
                                                            >
                                                            <span class="vx-perm-chip-text">
                                                                <span class="vx-perm-chip-name">{{ $permissionName }}</span>
                                                                <small class="vx-perm-chip-code">{{ $permissionCode }}</small>
                                                            </span>
                                                        </label>
                                                    @endforeach
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                @endforeach
                            </div>
                        </form>
                    @endforeach
                </div>
            @endif
        </div>
    </div>
@endsection

@push('scripts')
    <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>
@endpush
