// ==================== USER MANAGEMENT ====================
// Global variables (assume userObj and serverURL are defined elsewhere)
// serverURL = "https://demo2.bsl.co.ke/api/v1/"

allUsers();
// Main function to load and display all users
function allUsers(filter = 'all') {
    $(".crud_section").html("");

    // Modern loading skeleton (same as device version)
    var loadingHTML = `
        <div class="users-container" style="padding: 24px; background: #ffffff; min-height: 100vh;">
            <div class="loading-skeleton">
                <div style="height: 60px; background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%); background-size: 200% 100%; animation: loading 1.5s infinite; border-radius: 12px; margin-bottom: 20px;"></div>
                <div style="display: grid; grid-template-columns: repeat(4, 1fr); gap: 20px; margin-bottom: 24px;">
                    ${Array(4).fill().map(() => '<div style="height: 100px; background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%); background-size: 200% 100%; animation: loading 1.5s infinite; border-radius: 16px;"></div>').join('')}
                </div>
                <div style="height: 400px; background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%); background-size: 200% 100%; animation: loading 1.5s infinite; border-radius: 16px;"></div>
            </div>
        </div>
        <style>
            @keyframes loading {
                0% { background-position: 200% 0; }
                100% { background-position: -200% 0; }
            }
        </style>
    `;

    $(".crud_section").html(loadingHTML);

    let url = serverURL + "users/userAllList?pageNo=0&pageSize=1000";

    $.ajax({
        url: url,
        type: 'GET',
        dataType: "json",
        headers: {
            Authorization: "Bearer " + userObj.accessToken,
            "Content-Type": "application/json",
        },
        async: true,
        success: function(res) {
            let data = res || [];
            
            // Apply filter if needed
            if (filter === 'locked') {
                data = data.filter(u => u.locked === true);
            } else if (filter === 'unlocked') {
                data = data.filter(u => u.locked === false);
            } else if (filter === 'admins') {
                data = data.filter(u => u.roles && u.roles.includes('ADMIN'));
            } else if (filter === 'agents') {
                data = data.filter(u => u.roles && u.roles.includes('AGENT'));
            } else if (filter === 'drivers') {
                data = data.filter(u => u.roles && u.roles.includes('DRIVER'));
            }
            
            // Calculate statistics
            const totalUsers = data.length;
            const lockedUsers = data.filter(u => u.locked === true).length;
            const unlockedUsers = totalUsers - lockedUsers;
            const expiredUsers = data.filter(u => u.expired === true).length;
            const subAdmins = data.filter(u => u.subAdmin === true).length;
            const admins = data.filter(u => u.roles && u.roles.includes('ADMIN')).length;
            const agents = data.filter(u => u.roles && u.roles.includes('AGENT')).length;
            const drivers = data.filter(u => u.roles && u.roles.includes('DRIVER')).length;

            var html = `
            <div class="users-container" style="padding: 24px; background: #ffffff; min-height: 100vh; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;">
                
                <!-- Header Section -->
                <div style="background: #ffffff; border-radius: 16px; padding: 24px; margin-bottom: 24px; box-shadow: 0 2px 8px rgba(0,0,0,0.04); border: 1px solid #eaeef2;">
                    <div style="display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 16px;">
                        <div style="display: flex; align-items: center; gap: 16px;">
                            <h1 style="margin: 0; font-size: 28px; font-weight: 600; color: #1a1f36; display: flex; align-items: center; gap: 12px;">
                                <i class="fas fa-users" style="color: #000;"></i>
                                User Management
                            </h1>
                            <span style="background: #f0f2f5; color: #1a1f36; padding: 6px 14px; border-radius: 40px; font-size: 14px; font-weight: 500;">
                                ${totalUsers} Total
                            </span>
                        </div>
                        <div style="display: flex; gap: 12px;">
                            <button onclick="addNewUser()" style="display: flex; align-items: center; gap: 8px; padding: 10px 20px; background: #000; color: white; border: none; border-radius: 10px; font-weight: 500; cursor: pointer; transition: all 0.2s;">
                                <i class="fas fa-plus"></i> Add User
                            </button>
                            <button onclick="exportUsers()" style="display: flex; align-items: center; gap: 8px; padding: 10px 20px; background: #ffffff; color: #1a1f36; border: 1px solid #d0d5dd; border-radius: 10px; font-weight: 500; cursor: pointer; transition: all 0.2s;">
                                <i class="fas fa-download"></i> Export
                            </button>
                        </div>
                    </div>
                </div>

                <!-- Statistics Cards - Single Responsive Row -->
                <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(140px, 1fr)); gap: 16px; margin-bottom: 24px;">
                    
                    <!-- Total Card -->
                    <div style="background: #ffffff; border-radius: 16px; padding: 16px; box-shadow: 0 2px 8px rgba(0,0,0,0.04); border: 1px solid #eaeef2; text-align: center;">
                        <div style="width: 40px; height: 40px; background: #f0f2f5; border-radius: 10px; display: flex; align-items: center; justify-content: center; margin: 0 auto 8px;">
                            <i class="fas fa-users" style="font-size: 20px; color: #000;"></i>
                        </div>
                        <div style="font-size: 20px; font-weight: 700; color: #1a1f36;" id="stat-total">${totalUsers}</div>
                        <div style="font-size: 12px; color: #5b677c;">Total</div>
                    </div>

                    <!-- Locked Card -->
                    <div style="background: #ffffff; border-radius: 16px; padding: 16px; box-shadow: 0 2px 8px rgba(0,0,0,0.04); border: 1px solid #eaeef2; text-align: center; cursor: pointer;" onclick="allUsers('locked')">
                        <div style="width: 40px; height: 40px; background: #fee2e2; border-radius: 10px; display: flex; align-items: center; justify-content: center; margin: 0 auto 8px;">
                            <i class="fas fa-lock" style="font-size: 20px; color: #dc2626;"></i>
                        </div>
                        <div style="font-size: 20px; font-weight: 700; color: #dc2626;" id="stat-locked">${lockedUsers}</div>
                        <div style="font-size: 12px; color: #5b677c;">Locked</div>
                    </div>

                    <!-- Unlocked Card -->
                    <div style="background: #ffffff; border-radius: 16px; padding: 16px; box-shadow: 0 2px 8px rgba(0,0,0,0.04); border: 1px solid #eaeef2; text-align: center; cursor: pointer;" onclick="allUsers('unlocked')">
                        <div style="width: 40px; height: 40px; background: #e3f2fd; border-radius: 10px; display: flex; align-items: center; justify-content: center; margin: 0 auto 8px;">
                            <i class="fas fa-lock-open" style="font-size: 20px; color: #1976d2;"></i>
                        </div>
                        <div style="font-size: 20px; font-weight: 700; color: #1976d2;" id="stat-unlocked">${unlockedUsers}</div>
                        <div style="font-size: 12px; color: #5b677c;">Unlocked</div>
                    </div>

                    <!-- Expired Card -->
                    <div style="background: #ffffff; border-radius: 16px; padding: 16px; box-shadow: 0 2px 8px rgba(0,0,0,0.04); border: 1px solid #eaeef2; text-align: center;">
                        <div style="width: 40px; height: 40px; background: #fff3e0; border-radius: 10px; display: flex; align-items: center; justify-content: center; margin: 0 auto 8px;">
                            <i class="fas fa-clock" style="font-size: 20px; color: #ed6c02;"></i>
                        </div>
                        <div style="font-size: 20px; font-weight: 700; color: #ed6c02;" id="stat-expired">${expiredUsers}</div>
                        <div style="font-size: 12px; color: #5b677c;">Expired</div>
                    </div>

                    <!-- Admin Card -->
                    <div style="background: #ffffff; border-radius: 16px; padding: 16px; box-shadow: 0 2px 8px rgba(0,0,0,0.04); border: 1px solid #eaeef2; text-align: center; cursor: pointer;" onclick="allUsers('admins')">
                        <div style="width: 40px; height: 40px; background: #f3e5f5; border-radius: 10px; display: flex; align-items: center; justify-content: center; margin: 0 auto 8px;">
                            <i class="fas fa-user-shield" style="font-size: 20px; color: #9c27b0;"></i>
                        </div>
                        <div style="font-size: 20px; font-weight: 700; color: #9c27b0;" id="stat-admins">${admins}</div>
                        <div style="font-size: 12px; color: #5b677c;">Admins</div>
                    </div>

                    <!-- Agent Card -->
                    <div style="background: #ffffff; border-radius: 16px; padding: 16px; box-shadow: 0 2px 8px rgba(0,0,0,0.04); border: 1px solid #eaeef2; text-align: center; cursor: pointer;" onclick="allUsers('agents')">
                        <div style="width: 40px; height: 40px; background: #e8f5e9; border-radius: 10px; display: flex; align-items: center; justify-content: center; margin: 0 auto 8px;">
                            <i class="fas fa-user-tie" style="font-size: 20px; color: #2e7d32;"></i>
                        </div>
                        <div style="font-size: 20px; font-weight: 700; color: #2e7d32;" id="stat-agents">${agents}</div>
                        <div style="font-size: 12px; color: #5b677c;">Agents</div>
                    </div>

                    <!-- Driver Card -->
                    <div style="background: #ffffff; border-radius: 16px; padding: 16px; box-shadow: 0 2px 8px rgba(0,0,0,0.04); border: 1px solid #eaeef2; text-align: center; cursor: pointer;" onclick="allUsers('drivers')">
                        <div style="width: 40px; height: 40px; background: #e1f5fe; border-radius: 10px; display: flex; align-items: center; justify-content: center; margin: 0 auto 8px;">
                            <i class="fas fa-truck" style="font-size: 20px; color: #0288d1;"></i>
                        </div>
                        <div style="font-size: 20px; font-weight: 700; color: #0288d1;" id="stat-drivers">${drivers}</div>
                        <div style="font-size: 12px; color: #5b677c;">Drivers</div>
                    </div>
                </div>

                <!-- Filter Chips -->
                <div style="background: #ffffff; border-radius: 12px; padding: 16px; margin-bottom: 20px; border: 1px solid #eaeef2; display: flex; gap: 8px; flex-wrap: wrap;">
                    <!-- ... (unchanged) ... -->
                    <button class="filter-chip ${filter === 'all' ? 'active' : ''}" data-filter="all" onclick="allUsers('all')" style="padding: 8px 16px; border: 1px solid #eaeef2; border-radius: 40px; background: ${filter === 'all' ? '#000' : 'white'}; color: ${filter === 'all' ? 'white' : '#1a1f36'}; cursor: pointer; font-size: 14px; display: inline-flex; align-items: center; gap: 6px; transition: all 0.2s;">
                        <i class="fas fa-list"></i> All Users
                    </button>
                    <button class="filter-chip ${filter === 'locked' ? 'active' : ''}" data-filter="locked" onclick="allUsers('locked')" style="padding: 8px 16px; border: 1px solid #eaeef2; border-radius: 40px; background: ${filter === 'locked' ? '#dc2626' : 'white'}; color: ${filter === 'locked' ? 'white' : '#1a1f36'}; cursor: pointer; font-size: 14px; display: inline-flex; align-items: center; gap: 6px;">
                        <i class="fas fa-lock"></i> Locked
                    </button>
                    <button class="filter-chip ${filter === 'unlocked' ? 'active' : ''}" data-filter="unlocked" onclick="allUsers('unlocked')" style="padding: 8px 16px; border: 1px solid #eaeef2; border-radius: 40px; background: ${filter === 'unlocked' ? '#1976d2' : 'white'}; color: ${filter === 'unlocked' ? 'white' : '#1a1f36'}; cursor: pointer; font-size: 14px; display: inline-flex; align-items: center; gap: 6px;">
                        <i class="fas fa-lock-open"></i> Unlocked
                    </button>
                    <button class="filter-chip ${filter === 'admins' ? 'active' : ''}" data-filter="admins" onclick="allUsers('admins')" style="padding: 8px 16px; border: 1px solid #eaeef2; border-radius: 40px; background: ${filter === 'admins' ? '#9c27b0' : 'white'}; color: ${filter === 'admins' ? 'white' : '#1a1f36'}; cursor: pointer; font-size: 14px;">
                        <i class="fas fa-user-shield"></i> Admins
                    </button>
                    <button class="filter-chip ${filter === 'agents' ? 'active' : ''}" data-filter="agents" onclick="allUsers('agents')" style="padding: 8px 16px; border: 1px solid #eaeef2; border-radius: 40px; background: ${filter === 'agents' ? '#2e7d32' : 'white'}; color: ${filter === 'agents' ? 'white' : '#1a1f36'}; cursor: pointer; font-size: 14px;">
                        <i class="fas fa-user-tie"></i> Agents
                    </button>
                    <button class="filter-chip ${filter === 'drivers' ? 'active' : ''}" data-filter="drivers" onclick="allUsers('drivers')" style="padding: 8px 16px; border: 1px solid #eaeef2; border-radius: 40px; background: ${filter === 'drivers' ? '#0288d1' : 'white'}; color: ${filter === 'drivers' ? 'white' : '#1a1f36'}; cursor: pointer; font-size: 14px;">
                        <i class="fas fa-truck"></i> Drivers
                    </button>
                </div>

                <!-- Search and Controls (unchanged) -->
                <div style="background: #ffffff; border-radius: 12px; padding: 16px; margin-bottom: 20px; border: 1px solid #eaeef2; display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 16px;">
                    <div style="position: relative; flex: 1; max-width: 400px;">
                        <i class="fas fa-search" style="position: absolute; left: 12px; top: 50%; transform: translateY(-50%); color: #94a3b8;"></i>
                        <input type="text" id="userSearch" placeholder="Search by name, email, phone..." style="width: 100%; padding: 12px 12px 12px 40px; border: 1px solid #eaeef2; border-radius: 40px; font-size: 14px; outline: none;">
                    </div>
                    <div style="display: flex; gap: 12px;">
                        <select id="pageSize" style="padding: 8px 16px; border: 1px solid #eaeef2; border-radius: 40px; background: white; font-size: 14px;">
                            <option value="10">10 per page</option>
                            <option value="25">25 per page</option>
                            <option value="50">50 per page</option>
                            <option value="100">100 per page</option>
                        </select>
                        <button onclick="allUsers('${filter}')" style="width: 40px; height: 40px; border: 1px solid #eaeef2; border-radius: 50%; background: white; cursor: pointer;">
                            <i class="fas fa-sync-alt"></i>
                        </button>
                    </div>
                </div>

                <!-- Users Table (unchanged) -->
                <div style="background: #ffffff; border-radius: 16px; border: 1px solid #eaeef2; overflow: inherit; box-shadow: 0 2px 8px rgba(0,0,0,0.04);">
                    <table class="users-table" id="usertableview" style="width: 100%; border-collapse: collapse; min-width: 1200px;">
                        <thead>
                            <tr style="background: #f8fafc; border-bottom: 2px solid #eaeef2;">
                                <th style="padding: 16px; text-align: left; font-weight: 600; color: #1a1f36; width: 40px;">
                                    <input type="checkbox" id="selectAll" style="width: 18px; height: 18px; cursor: pointer;">
                                </th>
                                <th style="padding: 16px; text-align: left; font-weight: 600; color: #1a1f36;">#</th>
                                <th style="padding: 16px; text-align: left; font-weight: 600; color: #1a1f36;">User</th>
                                <th style="padding: 16px; text-align: left; font-weight: 600; color: #1a1f36;">Contact</th>
                                <th style="padding: 16px; text-align: left; font-weight: 600; color: #1a1f36;">Status</th>
                                <th style="padding: 16px; text-align: left; font-weight: 600; color: #1a1f36;">Roles</th>
                                <th style="padding: 16px; text-align: left; font-weight: 600; color: #1a1f36;">Last Login</th>
                                <th style="padding: 16px; text-align: center; font-weight: 600; color: #1a1f36;">Actions</th>
                            </tr>
                        </thead>
                        <tbody id="userTableBody">
            `;

            // Table rows generation (unchanged)
            data.forEach((user, i) => {
                const userId = user.userId;
                const fullName = [user.firstName, user.otherNames, user.lastName].filter(Boolean).join(' ') || 'N/A';
                const roles = user.roles ? user.roles.join(', ') : 'N/A';
                const lastLogin = user.lastLogin ? new Date(user.lastLogin).toLocaleString() : 'Never';
                
                html += `
                <tr data-user-id="${userId}" data-username="${user.username}" style="border-bottom: 1px solid #eaeef2;">
                    <td style="padding: 16px;">
                        <input type="checkbox" class="row-checkbox" data-id="${userId}" style="width: 18px; height: 18px; cursor: pointer;">
                    </td>
                    <td style="padding: 16px; color: #5b677c;">${i + 1}</td>
                    <td style="padding: 16px;">
                        <div style="display: flex; align-items: center; gap: 12px;">
                            <div style="width: 40px; height: 40px; background: #f0f2f5; border-radius: 10px; display: flex; align-items: center; justify-content: center;">
                                <i class="fas fa-user-circle" style="color: #000; font-size: 24px;"></i>
                            </div>
                            <div>
                                <div style="font-weight: 600; color: #1a1f36;">${fullName}</div>
                                <div style="font-size: 12px; color: #5b677c;">@${user.username || ''}</div>
                                <div style="font-size: 11px; color: #94a3b8;">ID: ${userId}</div>
                            </div>
                        </div>
                    </td>
                    <td style="padding: 16px;">
                        <div>
                            <div><i class="fas fa-envelope" style="width: 16px; color: #5b677c;"></i> ${user.email || 'N/A'}</div>
                            <div style="margin-top: 4px;"><i class="fas fa-phone" style="width: 16px; color: #5b677c;"></i> ${user.phoneNo || 'N/A'}</div>
                            <div style="margin-top: 4px;"><i class="fas fa-id-card" style="width: 16px; color: #5b677c;"></i> ${user.nationalIDNo || 'N/A'}</div>
                        </div>
                    </td>
                    <td style="padding: 16px;">
                        <div style="display: flex; flex-direction: column; gap: 6px;">
                            <span style="display: inline-flex; align-items: center; gap: 6px; padding: 4px 10px; background: ${user.locked ? '#fee2e2' : '#e3f2fd'}; border-radius: 40px; font-size: 12px; font-weight: 500; color: ${user.locked ? '#dc2626' : '#1976d2'}; width: fit-content;">
                                <i class="fas ${user.locked ? 'fa-lock' : 'fa-lock-open'}"></i>
                                ${user.locked ? 'Locked' : 'Unlocked'}
                            </span>
                            <span style="display: inline-flex; align-items: center; gap: 6px; padding: 4px 10px; background: ${user.expired ? '#fee2e2' : '#e8f5e9'}; border-radius: 40px; font-size: 12px; font-weight: 500; color: ${user.expired ? '#dc2626' : '#2e7d32'}; width: fit-content;">
                                <i class="fas ${user.expired ? 'fa-hourglass-end' : 'fa-hourglass-start'}"></i>
                                ${user.expired ? 'Expired' : 'Not Expired'}
                            </span>
                            ${user.subAdmin ? '<span style="display: inline-flex; align-items: center; gap: 6px; padding: 4px 10px; background: #fff3e0; border-radius: 40px; font-size: 12px; font-weight: 500; color: #ed6c02;"><i class="fas fa-user-cog"></i> Sub-Admin</span>' : ''}
                        </div>
                    </td>
                    <td style="padding: 16px;">
                        <div style="display: flex; flex-wrap: wrap; gap: 6px;">
                            ${user.roles ? user.roles.map(role => 
                                `<span style="background: #f0f2f5; padding: 4px 10px; border-radius: 40px; font-size: 12px; font-weight: 500; color: #1a1f36;">${role}</span>`
                            ).join('') : 'N/A'}
                        </div>
                    </td>
                    <td style="padding: 16px; color: #5b677c; font-size: 13px;">${lastLogin}</td>
                    <td style="padding: 16px; text-align: center;">
                        <div class="action-dropdown" style="position: relative; display: inline-block;">
                            <button onclick="toggleUserActionMenu(${userId})" style="width: 36px; height: 36px; border: 1px solid #eaeef2; border-radius: 8px; background: white; cursor: pointer;">
                                <i class="fas fa-ellipsis-v" style="color: #5b677c;"></i>
                            </button>
                            <div id="user_menu_${userId}" style="display: none; position: absolute; right: 0; top: 45px; width: 240px; background: white; border-radius: 12px; box-shadow: 0 4px 20px rgba(0,0,0,0.1); border: 1px solid #eaeef2; z-index: 1000;">
                                <div style="padding: 12px; border-bottom: 1px solid #eaeef2;">
                                    <span style="font-weight: 600; color: #1a1f36;">User Actions</span>
                                </div>
                                <div style="padding: 8px;">
                                    <button onclick='viewUserDetails(${userId})' style="width: 100%; padding: 10px; text-align: left; background: none; border: none; border-radius: 8px; cursor: pointer; display: flex; align-items: center; gap: 8px; color: #1a1f36;">
                                        <i class="fas fa-eye"></i> View Details
                                    </button>
                                    <button onclick='editUser(${userId})' style="width: 100%; padding: 10px; text-align: left; background: none; border: none; border-radius: 8px; cursor: pointer; display: flex; align-items: center; gap: 8px; color: #1a1f36;">
                                        <i class="fas fa-edit"></i> Edit User
                                    </button>
                                    <button onclick='toggleUserLock(${userId}, ${user.locked})' style="width: 100%; padding: 10px; text-align: left; background: none; border: none; border-radius: 8px; cursor: pointer; display: flex; align-items: center; gap: 8px; color: ${user.locked ? '#1976d2' : '#dc2626'};">
                                        <i class="fas ${user.locked ? 'fa-lock-open' : 'fa-lock'}"></i> 
                                        ${user.locked ? 'Unlock User' : 'Lock User'}
                                    </button>
                                    <div style="height: 1px; background: #eaeef2; margin: 8px 0;"></div>
                                    <button onclick='resetUserPassword(${userId})' style="width: 100%; padding: 10px; text-align: left; background: none; border: none; border-radius: 8px; cursor: pointer; display: flex; align-items: center; gap: 8px; color: #f97316;">
                                        <i class="fas fa-key"></i> Reset Password
                                    </button>
                                    <button onclick='deleteUser(${userId}, "${user.firstName} ${user.lastName}")' style="width: 100%; padding: 10px; text-align: left; background: none; border: none; border-radius: 8px; cursor: pointer; display: flex; align-items: center; gap: 8px; color: #dc2626;">
                                        <i class="fas fa-trash"></i> Delete User
                                    </button>
                                </div>
                            </div>
                        </div>
                    </td>
                </tr>
                `;
            });

            html += `
                        </tbody>
                    </table>
                </div>

                <!-- Table Footer (unchanged) -->
                <div style="background: #ffffff; border-radius: 12px; padding: 16px; margin-top: 20px; border: 1px solid #eaeef2; display: flex; justify-content: space-between; align-items: center;">
                    <div style="color: #5b677c;">
                        <span id="selectedCount">0</span> items selected
                    </div>
                    <div class="table-pagination" id="tablePagination"></div>
                </div>

                <style>
                    .filter-chip.active { background: #000 !important; color: white !important; border-color: #000 !important; }
                    .users-table tbody tr:hover { background: #f8fafc; cursor: pointer; }
                    .action-dropdown button:hover { background: #f0f2f5; }
                </style>
            </div>
            `;

            $(".crud_section").html(html);

            // Initialize DataTable (unchanged)
            const table = $('#usertableview').DataTable({
                dom: 'rtip',
                pageLength: 10,
                lengthMenu: [[10, 25, 50, 100], [10, 25, 50, 100]],
                order: [[1, 'asc']],
                columnDefs: [
                    { orderable: false, targets: [0, 7] }
                ]
            });

            $('#userSearch').off('keyup').on('keyup', function() {
                table.search(this.value).draw();
            });

            $('#pageSize').off('change').on('change', function() {
                table.page.len(this.value).draw();
            });

            $("#selectAll").off("click").on("click", function() {
                $(".row-checkbox").prop("checked", this.checked);
                updateSelectedCount();
            });

            $(document).off("change", ".row-checkbox").on("change", ".row-checkbox", function() {
                updateSelectedCount();
                const total = $(".row-checkbox").length;
                const checked = $(".row-checkbox:checked").length;
                $("#selectAll").prop("checked", total === checked);
            });

            function updateSelectedCount() {
                $("#selectedCount").text($(".row-checkbox:checked").length);
            }
        },
        error: function(xhr, status, error) {
            console.error("Error loading users:", error);
            $(".crud_section").html(`
                <div style="padding: 40px; text-align: center; background: white; border-radius: 16px; margin: 24px;">
                    <i class="fas fa-exclamation-triangle" style="font-size: 48px; color: #dc2626;"></i>
                    <h3 style="color: #1a1f36;">Failed to load users</h3>
                    <p style="color: #5b677c;">${error}</p>
                    <button onclick="allUsers()" style="padding: 10px 24px; background: #000; color: white; border: none; border-radius: 10px;">
                        <i class="fas fa-sync-alt"></i> Retry
                    </button>
                </div>
            `);
        }
    });
}

// Toggle action menu for users
function toggleUserActionMenu(userId) {
    $('[id^="user_menu_"]').hide();
    $(`#user_menu_${userId}`).toggle();
}

function addNewUser() {
    Swal.fire({
        title: 'Add New User',
        html: `
            <div style="text-align: left; max-height: 500px; overflow-y: auto; padding: 10px;">
                <!-- Email -->
                <div style="margin-bottom: 15px;">
                    <label style="display: block; margin-bottom: 5px; font-weight: 500; color: #1a1f36;">Email <span style="color: #db2828;">*</span></label>
                    <div style="position: relative; width: 100%;">
                        <i class="fas fa-envelope" style="position: absolute; left: 12px; top: 50%; transform: translateY(-50%); color: #999; z-index: 1;"></i>
                        <input id="userEmail" type="email" placeholder="user@example.com" style="width: 100%; padding: 12px 12px 12px 40px; border: 1px solid rgba(34,36,38,.15); border-radius: 4px; font-size: 14px; box-sizing: border-box;">
                    </div>
                </div>

                <!-- Password -->
                <div style="margin-bottom: 15px;">
                    <label style="display: block; margin-bottom: 5px; font-weight: 500; color: #1a1f36;">Password <span style="color: #db2828;">*</span></label>
                    <div style="position: relative; width: 100%;">
                        <i class="fas fa-lock" style="position: absolute; left: 12px; top: 50%; transform: translateY(-50%); color: #999; z-index: 1;"></i>
                        <input id="password" type="password" placeholder="Password" style="width: 100%; padding: 12px 12px 12px 40px; border: 1px solid rgba(34,36,38,.15); border-radius: 4px; font-size: 14px; box-sizing: border-box;">
                    </div>
                </div>

                <!-- First Name & Other Names -->
                <div style="display: flex; gap: 10px; margin-bottom: 15px;">
                    <div style="flex: 1;">
                        <label style="display: block; margin-bottom: 5px; font-weight: 500; color: #1a1f36;">First Name <span style="color: #db2828;">*</span></label>
                        <div style="position: relative; width: 100%;">
                            <i class="fas fa-user" style="position: absolute; left: 12px; top: 50%; transform: translateY(-50%); color: #999; z-index: 1;"></i>
                            <input id="firstName" type="text" placeholder="First" style="width: 100%; padding: 12px 12px 12px 40px; border: 1px solid rgba(34,36,38,.15); border-radius: 4px; font-size: 14px; box-sizing: border-box;">
                        </div>
                    </div>
                    <div style="flex: 1;">
                        <label style="display: block; margin-bottom: 5px; font-weight: 500; color: #1a1f36;">Other Names</label>
                        <div style="position: relative; width: 100%;">
                            <i class="fas fa-user-plus" style="position: absolute; left: 12px; top: 50%; transform: translateY(-50%); color: #999; z-index: 1;"></i>
                            <input id="otherNames" type="text" placeholder="Other" style="width: 100%; padding: 12px 12px 12px 40px; border: 1px solid rgba(34,36,38,.15); border-radius: 4px; font-size: 14px; box-sizing: border-box;">
                        </div>
                    </div>
                </div>

                <!-- Last Name & Phone No -->
                <div style="display: flex; gap: 10px; margin-bottom: 15px;">
                    <div style="flex: 1;">
                        <label style="display: block; margin-bottom: 5px; font-weight: 500; color: #1a1f36;">Last Name <span style="color: #db2828;">*</span></label>
                        <div style="position: relative; width: 100%;">
                            <i class="fas fa-user" style="position: absolute; left: 12px; top: 50%; transform: translateY(-50%); color: #999; z-index: 1;"></i>
                            <input id="lastName" type="text" placeholder="Last" style="width: 100%; padding: 12px 12px 12px 40px; border: 1px solid rgba(34,36,38,.15); border-radius: 4px; font-size: 14px; box-sizing: border-box;">
                        </div>
                    </div>
                    <div style="flex: 1;">
                        <label style="display: block; margin-bottom: 5px; font-weight: 500; color: #1a1f36;">Phone No <span style="color: #db2828;">*</span></label>
                        <div style="position: relative; width: 100%;">
                            <i class="fas fa-phone" style="position: absolute; left: 12px; top: 50%; transform: translateY(-50%); color: #999; z-index: 1;"></i>
                            <input id="phoneNo" type="text" placeholder="+254..." style="width: 100%; padding: 12px 12px 12px 40px; border: 1px solid rgba(34,36,38,.15); border-radius: 4px; font-size: 14px; box-sizing: border-box;">
                        </div>
                    </div>
                </div>

                <!-- National ID -->
                <div style="margin-bottom: 15px;">
                    <label style="display: block; margin-bottom: 5px; font-weight: 500; color: #1a1f36;">National ID No</label>
                    <div style="position: relative; width: 100%;">
                        <i class="fas fa-id-card" style="position: absolute; left: 12px; top: 50%; transform: translateY(-50%); color: #999; z-index: 1;"></i>
                        <input id="nationalIDNo" type="text" placeholder="ID Number" style="width: 100%; padding: 12px 12px 12px 40px; border: 1px solid rgba(34,36,38,.15); border-radius: 4px; font-size: 14px; box-sizing: border-box;">
                    </div>
                </div>

                <!-- Roles (multi‑select with Semantic UI for usability) -->
                <div style="margin-bottom: 15px;">
                    <label style="display: block; margin-bottom: 5px; font-weight: 500; color: #1a1f36;">Roles <span style="color: #db2828;">*</span></label>
                    <div style="position: relative; width: 100%;">
                        <i class="fas fa-tags" style="position: absolute; left: 12px; top: 18px; color: #999; z-index: 1;"></i>
                        <select id="roleSelect" multiple class="ui fluid dropdown" style="width: 100%; padding: 12px 12px 12px 40px; border: 1px solid rgba(34,36,38,.15); border-radius: 4px; font-size: 14px; background: white; appearance: none;">
                            <option value="ADMIN">Admin</option>
                            <option value="AGENT">Agent</option>
                            <option value="DRIVER">Driver</option>
                        </select>
                    </div>
                    <small style="color: #64748b; display: block; margin-top: 4px;">Hold Ctrl/Cmd to select multiple</small>
                </div>
            </div>

            <style>
                /* Override Semantic UI dropdown to match device form */
                .ui.dropdown {
                    border: 1px solid rgba(34,36,38,.15) !important;
                    border-radius: 4px !important;
                    padding: 12px 12px 12px 40px !important;
                    min-height: auto !important;
                    font-size: 14px !important;
                    background: white !important;
                }
                .ui.dropdown .menu {
                    border-radius: 4px !important;
                    margin-top: 2px !important;
                    border: 1px solid rgba(34,36,38,.15) !important;
                    box-shadow: 0 2px 8px rgba(0,0,0,0.04) !important;
                }
                .ui.dropdown .menu > .item {
                    padding: 10px 16px !important;
                    font-size: 14px !important;
                }
                .ui.dropdown .menu > .item.selected {
                    background: #f0f2f5 !important;
                }
                .ui.dropdown .menu > .item.active {
                    background: #e3f2fd !important;
                    color: #1976d2 !important;
                }
                /* Focus style matching device form */
                input:focus, .ui.dropdown:focus, .ui.dropdown.active {
                    border-color: #85b7d9 !important;
                    outline: 0 !important;
                    box-shadow: 0 0 0 2px rgba(33,133,208,.2) !important;
                }
                /* Make the dropdown arrow consistent */
                .ui.dropdown > .dropdown.icon {
                    top: 50% !important;
                    transform: translateY(-50%) !important;
                    right: 12px !important;
                    color: #999 !important;
                }
                /* Adjust icon position for select wrapper */
                .fa-tags {
                    top: 50% !important;
                    transform: translateY(-50%);
                }
            </style>
        `,
        showCancelButton: true,
        confirmButtonText: 'Create User',
        confirmButtonColor: '#000',
        cancelButtonColor: '#64748b',
        background: '#ffffff',
        color: '#1a1f36',
        width: '700px',
        didOpen: () => {
            // Initialize Semantic UI dropdown
            if ($.fn.dropdown) {
                $('#roleSelect').dropdown({
                    allowAdditions: false,
                    fullTextSearch: true,
                    forceSelection: false,
                    selectOnKeydown: false
                });
            }
        },
        preConfirm: () => {
            const email = $('#userEmail').val();
            const password = $('#password').val();
            const firstName = $('#firstName').val();
            const lastName = $('#lastName').val();
            const phoneNo = $('#phoneNo').val();
            const roleSelect = $('#roleSelect').val(); // array

            if (!email || !password || !firstName || !lastName || !phoneNo) {
                Swal.showValidationMessage('Please fill all required fields');
                return false;
            }
            if (!roleSelect || roleSelect.length === 0) {
                Swal.showValidationMessage('Select at least one role');
                return false;
            }

            return {
                userEmail: email.trim(),
                password: password,
                firstName: firstName.trim(),
                otherNames: $('#otherNames').val() ? $('#otherNames').val().trim() : null,
                lastName: lastName.trim(),
                phoneNo: phoneNo.trim(),
                nationalIDNo: $('#nationalIDNo').val() ? $('#nationalIDNo').val().trim() : null,
                roleName: roleSelect
            };
        }
    }).then((result) => {
        if (result.isConfirmed) {
            createUser(result.value);
        }
    });
}

// Create user API call
function createUser(userData) {
    Swal.fire({
        title: 'Creating User',
        html: 'Please wait...',
        allowOutsideClick: false,
        didOpen: () => Swal.showLoading()
    });

    $.ajax({
        url: serverURL + 'auth/register',
        type: 'POST',
        contentType: 'application/json',
        headers: { Authorization: 'Bearer ' + userObj.accessToken },
        data: JSON.stringify(userData),
        success: function(res) {
            Swal.fire({
                title: 'Success!',
                text: 'User created successfully',
                icon: 'success',
                confirmButtonColor: '#000'
            }).then(() => allUsers());
        },
        error: function(xhr) {
            let msg = 'Failed to create user';
            try { msg = JSON.parse(xhr.responseText).message || msg; } catch(e) {}
            Swal.fire({ title: 'Error', text: msg, icon: 'error', confirmButtonColor: '#000' });
        }
    });
}

// Edit user (fetch details first)
function editUser(userId) {
    // First fetch user details (assuming GET /users/{userId})
    Swal.fire({ title: 'Loading...', allowOutsideClick: false, didOpen: () => Swal.showLoading() });

    $.ajax({
        url: serverURL + 'users/' + userId,
        type: 'GET',
        headers: { Authorization: 'Bearer ' + userObj.accessToken },
        success: function(user) {
            Swal.close();
            showEditUserModal(user);
        },
        error: function() {
            Swal.fire({ title: 'Error', text: 'Could not load user details', icon: 'error' });
        }
    });
}

function showEditUserModal(user) {
    // Pre-select roles
    const roleOptions = ['ADMIN', 'AGENT', 'DRIVER'].map(role => 
        `<option value="${role}" ${user.roles && user.roles.includes(role) ? 'selected' : ''}>${role}</option>`
    ).join('');

    Swal.fire({
        title: 'Edit User',
        html: `
            <div style="text-align: left; max-height: 500px; overflow-y: auto; padding: 10px;">
                <div style="margin-bottom: 15px;">
                    <label>Email <span style="color: #db2828;">*</span></label>
                    <input id="editUserEmail" type="email" class="swal2-input" value="${user.email || ''}">
                </div>
                <div style="display: flex; gap: 10px;">
                    <div style="flex:1;">
                        <label>First Name</label>
                        <input id="editFirstName" class="swal2-input" value="${user.firstName || ''}">
                    </div>
                    <div style="flex:1;">
                        <label>Other Names</label>
                        <input id="editOtherNames" class="swal2-input" value="${user.otherNames || ''}">
                    </div>
                </div>
                <div style="display: flex; gap: 10px;">
                    <div style="flex:1;">
                        <label>Last Name</label>
                        <input id="editLastName" class="swal2-input" value="${user.lastName || ''}">
                    </div>
                    <div style="flex:1;">
                        <label>Phone No</label>
                        <input id="editPhoneNo" class="swal2-input" value="${user.phoneNo || ''}">
                    </div>
                </div>
                <div style="margin-bottom: 15px;">
                    <label>National ID No</label>
                    <input id="editNationalIDNo" class="swal2-input" value="${user.nationalIDNo || ''}">
                </div>
                <div style="margin-bottom: 15px;">
                    <label>Roles</label>
                    <select id="editRoleSelect" multiple class="swal2-input" style="height: auto;">${roleOptions}</select>
                </div>
                <div style="margin-bottom: 15px;">
                    <label style="display: flex; align-items: center; gap: 10px;">
                        <input type="checkbox" id="editLocked" ${user.locked ? 'checked' : ''}> Locked
                    </label>
                    <label style="display: flex; align-items: center; gap: 10px;">
                        <input type="checkbox" id="editExpired" ${user.expired ? 'checked' : ''}> Expired
                    </label>
                    <label style="display: flex; align-items: center; gap: 10px;">
                        <input type="checkbox" id="editSubAdmin" ${user.subAdmin ? 'checked' : ''}> Sub-Admin
                    </label>
                </div>
            </div>
        `,
        showCancelButton: true,
        confirmButtonText: 'Update User',
        confirmButtonColor: '#000',
        preConfirm: () => {
            const email = $('#editUserEmail').val();
            const firstName = $('#editFirstName').val();
            const lastName = $('#editLastName').val();
            const phoneNo = $('#editPhoneNo').val();
            const roleSelect = $('#editRoleSelect').val() || [];

            if (!email || !firstName || !lastName || !phoneNo) {
                Swal.showValidationMessage('Required fields missing');
                return false;
            }

            return {
                userEmail: email,
                firstName: firstName,
                otherNames: $('#editOtherNames').val() || null,
                lastName: lastName,
                phoneNo: phoneNo,
                nationalIDNo: $('#editNationalIDNo').val() || null,
                roleName: roleSelect,
                locked: $('#editLocked').is(':checked'),
                expired: $('#editExpired').is(':checked'),
                subAdmin: $('#editSubAdmin').is(':checked')
                // Password not updated here; use reset password separately
            };
        }
    }).then((result) => {
        if (result.isConfirmed) {
            updateUser(user.userId, result.value);
        }
    });
}

// Update user (PUT /users/{userId})
function updateUser(userId, userData) {
    Swal.fire({ title: 'Updating...', allowOutsideClick: false, didOpen: () => Swal.showLoading() });

    $.ajax({
        url: serverURL + 'users/' + userId,
        type: 'PUT',
        contentType: 'application/json',
        headers: { Authorization: 'Bearer ' + userObj.accessToken },
        data: JSON.stringify(userData),
        success: function() {
            Swal.fire({ title: 'Success!', text: 'User updated', icon: 'success', confirmButtonColor: '#000' })
                .then(() => allUsers());
        },
        error: function(xhr) {
            let msg = 'Update failed';
            try { msg = JSON.parse(xhr.responseText).message || msg; } catch(e) {}
            Swal.fire({ title: 'Error', text: msg, icon: 'error' });
        }
    });
}

// Delete user
// Delete user using the provided deleteUser endpoint
function deleteUser(userId, userName) {
    Swal.fire({
        title: 'Delete User?',
        html: `Are you sure you want to delete <strong>${userName || 'this user'}</strong>?<br><br>This action cannot be undone.`,
        icon: 'warning',
        input: 'textarea',
        inputLabel: 'Reason for deletion (required)',
        inputPlaceholder: 'Please provide a reason...',
        inputAttributes: {
            'aria-label': 'Reason for deletion'
        },
        showCancelButton: true,
        confirmButtonColor: '#dc2626',
        cancelButtonColor: '#6b7280',
        confirmButtonText: 'Yes, delete user',
        cancelButtonText: 'Cancel',
        background: '#ffffff',
        color: '#1a1f36',
        preConfirm: (reason) => {
            if (!reason) {
                Swal.showValidationMessage('Reason is required to delete a user');
                return false;
            }
            return reason;
        }
    }).then((result) => {
        if (result.isConfirmed) {
            performUserDeletion(userId, result.value);
        }
    });
}

// Perform the actual API call to delete the user
function performUserDeletion(userId, reason) {
    // Show loading state
    Swal.fire({
        title: 'Deleting User...',
        html: 'Please wait',
        allowOutsideClick: false,
        didOpen: () => {
            Swal.showLoading();
        }
    });

    // Construct the URL with query parameters
    const url = `${serverURL}users/deleteUser?users_id=${userId}&reason=${encodeURIComponent(reason)}`;

    $.ajax({
        url: url,
        type: 'POST', // Assuming GET based on the URL structure - adjust if your backend expects POST/DELETE
        headers: {
            Authorization: 'Bearer ' + userObj.accessToken,
            'Content-Type': 'application/json',
        },
        success: function(response) {
            Swal.fire({
                title: 'Deleted!',
                text: 'User has been deleted successfully.',
                icon: 'success',
                confirmButtonColor: '#000',
                background: '#ffffff',
                color: '#1a1f36'
            }).then(() => {
                allUsers(); // Refresh the user list
                // Close any open action menu for this user
                $(`#user_menu_${userId}`).hide();
            });
        },
        error: function(xhr, status, error) {
            console.error("Error deleting user:", error);
            
            let errorMsg = 'Failed to delete user';
            try {
                const errorData = JSON.parse(xhr.responseText);
                errorMsg = errorData.message || errorMsg;
            } catch (e) {
                errorMsg = xhr.statusText || errorMsg;
            }
            
            Swal.fire({
                title: 'Error!',
                text: errorMsg,
                icon: 'error',
                confirmButtonColor: '#000',
                background: '#ffffff',
                color: '#1a1f36'
            });
        }
    });
}

// Toggle lock/unlock
// Toggle lock/unlock using the provided unlock endpoint
function toggleUserUnLock(userId, currentlyLocked) {
    const action = currentlyLocked ? 'unlock' : 'lock';
    // Note: There's no explicit "lock" endpoint in your example, only unlock.
    // If you need to lock, you might have a different endpoint.
    
    Swal.fire({
        title: `${currentlyLocked ? 'Unlock' : 'Lock'} User?`,
        text: `Are you sure you want to ${action} this user?`,
        icon: 'question',
        input: 'text',
        inputLabel: 'Reason (required for unlock)',
        inputPlaceholder: 'Enter reason...',
        showCancelButton: true,
        confirmButtonColor: '#000',
        confirmButtonText: 'Yes',
        preConfirm: (reason) => {
            if (currentlyLocked && !reason) {
                Swal.showValidationMessage('Reason is required to unlock');
                return false;
            }
            return reason;
        }
    }).then((result) => {
        if (result.isConfirmed) {
            Swal.fire({ title: 'Processing...', allowOutsideClick: false, didOpen: () => Swal.showLoading() });

            // Build URL with query parameters
            let url = `${serverURL}users/unlockUser?users_id=${userId}`;
            if (currentlyLocked && result.value) {
                url += `&reason=${encodeURIComponent(result.value)}`;
            }

            $.ajax({
                url: url,
                type: 'POST', // or 'POST' - adjust based on actual API requirement
                headers: { Authorization: 'Bearer ' + userObj.accessToken },
                success: function(response) {
                    Swal.fire({
                        title: 'Success!',
                        text: `User ${currentlyLocked ? 'unlocked' : 'locked'} successfully`,
                        icon: 'success',
                        confirmButtonColor: '#000'
                    }).then(() => allUsers());
                },
                error: function(xhr) {
                    let msg = 'Operation failed';
                    try { msg = JSON.parse(xhr.responseText).message || msg; } catch(e) {}
                    Swal.fire({ title: 'Error', text: msg, icon: 'error' });
                }
            });
        }
    });
}

// Reset password (optional - need endpoint)
function resetUserPassword(userId) {
    Swal.fire({
        title: 'Reset Password',
        input: 'password',
        inputLabel: 'New Password',
        inputPlaceholder: 'Enter new password',
        showCancelButton: true,
        confirmButtonText: 'Reset',
        confirmButtonColor: '#000'
    }).then((result) => {
        if (result.isConfirmed && result.value) {
            // Assuming endpoint PUT /users/{userId}/password or similar
            Swal.fire({ title: 'Processing...', allowOutsideClick: false, didOpen: () => Swal.showLoading() });

            $.ajax({
                url: serverURL + 'users/' + userId + '/password', // adjust as needed
                type: 'PUT',
                contentType: 'application/json',
                headers: { Authorization: 'Bearer ' + userObj.accessToken },
                data: JSON.stringify({ password: result.value }),
                success: function() {
                    Swal.fire({ title: 'Success', text: 'Password updated', icon: 'success' });
                },
                error: function() {
                    Swal.fire({ title: 'Error', text: 'Password reset failed', icon: 'error' });
                }
            });
        }
    });
}

// View user details (simple modal)
function viewUserDetails(userId) {
    // Show loading state
    Swal.fire({
        title: 'Loading User Details',
        html: 'Please wait...',
        allowOutsideClick: false,
        didOpen: () => Swal.showLoading()
    });

    const url = `${serverURL}users/getUserByID?users_id=${userId}`;

    $.ajax({
        url: url,
        type: 'GET',
        headers: { Authorization: 'Bearer ' + userObj.accessToken },
        success: function(user) {
            // Format last login date
            const lastLogin = user.lastLogin ? new Date(user.lastLogin).toLocaleString() : 'Never';

            // Build status badges
            const lockedBadge = user.locked 
                ? '<span class="status-badge locked"><i class="fas fa-lock"></i> Locked</span>' 
                : '<span class="status-badge unlocked"><i class="fas fa-lock-open"></i> Unlocked</span>';
            
            const expiredBadge = user.expired 
                ? '<span class="status-badge expired"><i class="fas fa-hourglass-end"></i> Expired</span>' 
                : '<span class="status-badge active"><i class="fas fa-check-circle"></i> Not Expired</span>';
            
            const subAdminBadge = user.subAdmin 
                ? '<span class="status-badge subadmin"><i class="fas fa-user-cog"></i> Sub-Admin</span>' 
                : '';

            // Format roles as badges
            const roleBadges = user.roles && user.roles.length > 0 
                ? user.roles.map(role => `<span class="role-badge">${role}</span>`).join('') 
                : '<span class="no-data">No roles assigned</span>';

            // Build the HTML content
            const html = `
                <div class="user-details-container">
                    <!-- Header with avatar and basic info -->
                    <div class="details-header">
                        <div class="user-avatar">
                            <i class="fas fa-user-circle"></i>
                        </div>
                        <div class="user-title">
                            <h2>${user.firstName || ''} ${user.lastName || ''}</h2>
                            <div class="user-username">@${user.username || ''}</div>
                        </div>
                        <div class="header-badges">
                            ${lockedBadge} ${expiredBadge} ${subAdminBadge}
                        </div>
                    </div>

                    <!-- Personal Information Card -->
                    <div class="info-card">
                        <h3><i class="fas fa-user"></i> Personal Information</h3>
                        <div class="info-grid">
                            <div class="info-item">
                                <span class="info-label">First Name</span>
                                <span class="info-value">${user.firstName || 'N/A'}</span>
                            </div>
                            <div class="info-item">
                                <span class="info-label">Other Names</span>
                                <span class="info-value">${user.otherNames || 'N/A'}</span>
                            </div>
                            <div class="info-item">
                                <span class="info-label">Last Name</span>
                                <span class="info-value">${user.lastName || 'N/A'}</span>
                            </div>
                            <div class="info-item">
                                <span class="info-label">National ID</span>
                                <span class="info-value">${user.nationalIDNo || 'N/A'}</span>
                            </div>
                        </div>
                    </div>

                    <!-- Contact Information Card -->
                    <div class="info-card">
                        <h3><i class="fas fa-envelope"></i> Contact</h3>
                        <div class="info-grid">
                            <div class="info-item">
                                <span class="info-label">Email</span>
                                <span class="info-value">${user.email || 'N/A'}</span>
                            </div>
                            <div class="info-item">
                                <span class="info-label">Phone</span>
                                <span class="info-value">${user.phoneNo || 'N/A'}</span>
                            </div>
                        </div>
                    </div>

                    <!-- Roles Card -->
                    <div class="info-card">
                        <h3><i class="fas fa-tags"></i> Roles</h3>
                        <div class="roles-container">
                            ${roleBadges}
                        </div>
                    </div>

                    <!-- System Info Card -->
                    <div class="info-card">
                        <h3><i class="fas fa-cog"></i> System Information</h3>
                        <div class="info-grid">
                            <div class="info-item">
                                <span class="info-label">User ID</span>
                                <span class="info-value">${user.userId}</span>
                            </div>
                            <div class="info-item">
                                <span class="info-label">Last Login</span>
                                <span class="info-value">${lastLogin}</span>
                            </div>
                            <div class="info-item">
                                <span class="info-label">Account Status</span>
                                <span class="info-value">
                                    ${user.locked ? 'Locked' : 'Unlocked'} 
                                    ${user.expired ? '· Expired' : ''} 
                                    ${user.subAdmin ? '· Sub-Admin' : ''}
                                </span>
                            </div>
                        </div>
                    </div>
                </div>

                <style>
                    .user-details-container {
                        text-align: left;
                        font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
                        max-height: 70vh;
                        overflow-y: auto;
                        padding: 5px;
                    }
                    .details-header {
                        display: flex;
                        align-items: center;
                        gap: 20px;
                        background: linear-gradient(135deg, #4b6af3 0%, #4b6af3 100%);
                        margin: -20px -20px 20px -20px;
                        padding: 25px 30px;
                        border-radius: 20px 20px 0 0;
                        color: white;
                        flex-wrap: wrap;
                    }
                    .user-avatar {
                        font-size: 60px;
                        color: rgba(255,255,255,0.8);
                    }
                    .user-title h2 {
                        margin: 0;
                        font-size: 24px;
                        font-weight: 600;
                    }
                    .user-username {
                        font-size: 14px;
                        opacity: 0.9;
                        margin-top: 4px;
                    }
                    .header-badges {
                        margin-left: auto;
                        display: flex;
                        gap: 8px;
                        flex-wrap: wrap;
                    }
                    .status-badge {
                        display: inline-flex;
                        align-items: center;
                        gap: 6px;
                        padding: 6px 14px;
                        border-radius: 30px;
                        font-size: 13px;
                        font-weight: 500;
                        background: rgba(255,255,255,0.2);
                        backdrop-filter: blur(5px);
                        border: 1px solid rgba(255,255,255,0.3);
                    }
                    .status-badge.locked { background: #ef4444; color: white; }
                    .status-badge.unlocked { background: #10b981; color: white; }
                    .status-badge.expired { background: #f59e0b; color: white; }
                    .status-badge.active { background: #10b981; color: white; }
                    .status-badge.subadmin { background: #8b5cf6; color: white; }
                    .info-card {
                        background: #f8fafc;
                        border-radius: 16px;
                        padding: 20px;
                        margin-bottom: 20px;
                        border: 1px solid #e2e8f0;
                    }
                    .info-card h3 {
                        margin: 0 0 15px 0;
                        font-size: 16px;
                        font-weight: 600;
                        color: #1e293b;
                        display: flex;
                        align-items: center;
                        gap: 8px;
                    }
                    .info-card h3 i {
                        color: #3b82f6;
                    }
                    .info-grid {
                        display: grid;
                        grid-template-columns: repeat(2, 1fr);
                        gap: 16px;
                    }
                    .info-item {
                        display: flex;
                        flex-direction: column;
                    }
                    .info-label {
                        font-size: 12px;
                        color: #64748b;
                        margin-bottom: 4px;
                    }
                    .info-value {
                        font-size: 15px;
                        font-weight: 500;
                        color: #1e293b;
                        word-break: break-word;
                    }
                    .roles-container {
                        display: flex;
                        flex-wrap: wrap;
                        gap: 8px;
                    }
                    .role-badge {
                        background: #3b82f6;
                        color: white;
                        padding: 6px 16px;
                        border-radius: 30px;
                        font-size: 13px;
                        font-weight: 500;
                        display: inline-block;
                    }
                    .no-data {
                        color: #94a3b8;
                        font-style: italic;
                        font-size: 14px;
                    }
                    @media (max-width: 600px) {
                        .info-grid { grid-template-columns: 1fr; }
                        .details-header { flex-direction: column; text-align: center; }
                        .header-badges { margin-left: 0; }
                    }
                </style>
            `;

            Swal.fire({
                title: null,
                html: html,
                showCloseButton: true,
                showConfirmButton: false,
                background: '#ffffff',
                color: '#1a1f36',
                width: '700px',
                customClass: {
                    popup: 'user-details-popup'
                }
            });
        },
        error: function(xhr) {
            let errorMsg = 'Could not fetch user details';
            try {
                const res = JSON.parse(xhr.responseText);
                errorMsg = res.message || errorMsg;
            } catch (e) {
                errorMsg = xhr.statusText || errorMsg;
            }
            Swal.fire({
                title: 'Error',
                text: errorMsg,
                icon: 'error',
                confirmButtonColor: '#000'
            });
        }
    });
}

// Export users
function exportUsers() {
    // Similar to device export
    Swal.fire({
        title: 'Export Users',
        text: 'Choose format',
        icon: 'question',
        showCancelButton: true,
        confirmButtonText: 'CSV',
        cancelButtonText: 'JSON',
        confirmButtonColor: '#000'
    }).then((result) => {
        if (result.isConfirmed) {
            // CSV export placeholder
            alert('CSV export coming soon!');
        } else if (result.dismiss === Swal.DismissReason.cancel) {
            const table = $('#usertableview').DataTable();
            const data = table.data().toArray();
            const jsonStr = JSON.stringify(data, null, 2);
            const blob = new Blob([jsonStr], { type: 'application/json' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = `users_export_${new Date().toISOString().slice(0,10)}.json`;
            a.click();
            URL.revokeObjectURL(url);
        }
    });
}

// Initialize on document ready (if needed)
$(document).ready(function() {
    // Load users initially
    allUsers();

    // Close dropdowns when clicking outside
    $(document).on('click', function(e) {
        if (!$(e.target).closest('.action-dropdown').length) {
            $('[id^="user_menu_"]').hide();
        }
    });
});