<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <title>User Management - Ryll Store</title>
    <link rel="icon" type="image/webp" href="{{ asset('images/ryll.webp') }}">
    
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js" defer></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Orbitron:wght@400;700;900&display=swap" rel="stylesheet">
    
    <style>
        .font-orbitron { font-family: 'Orbitron', sans-serif; }
        
        [x-cloak] { display: none !important; }
        
        ::-webkit-scrollbar { width: 8px; }
        ::-webkit-scrollbar-track { background: #1f2937; }
        ::-webkit-scrollbar-thumb { background: #06b6d4; border-radius: 4px; }

        /* Mobile responsive */
        @media (max-width: 768px) {
            .desktop-table { display: none; }
            .mobile-cards { display: block; }
        }
        
        @media (min-width: 769px) {
            .desktop-table { display: table; }
            .mobile-cards { display: none; }
        }
    </style>
</head>
<body class="bg-gray-950 text-white" x-data="userManager()">

<!-- NAVBAR COMPONENT -->
@include('components.admin-navbar')

<!-- MAIN CONTENT -->
<div class="max-w-7xl mx-auto px-4 py-8">
    
    <!-- Header -->
    <div class="flex flex-col md:flex-row items-start md:items-center justify-between mb-6 gap-4">
        <div>
            <h1 class="text-2xl md:text-3xl font-bold font-orbitron text-cyan-400 mb-2">
                <i class="fas fa-users mr-3"></i>USER MANAGEMENT
            </h1>
            <p class="text-sm md:text-base text-gray-400">Manage users, roles, and permissions</p>
        </div>
        
        <button @click="openAddModal()" 
                class="w-full md:w-auto px-6 py-3 bg-gradient-to-r from-cyan-500 to-blue-600 hover:opacity-90 rounded-lg font-bold transition shadow-lg">
            <i class="fas fa-user-plus mr-2"></i>Add New User
        </button>
    </div>
    
    <!-- ✅ ENHANCED STATS (3 → 6 Cards) -->
    <div class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-3 md:gap-6 mb-6">
        <div class="bg-gray-900 rounded-xl p-4 md:p-6 border border-cyan-500/20">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-400 text-[10px] md:text-sm mb-1">Total Users</p>
                    <p class="text-2xl md:text-3xl font-bold text-white">{{ $totalUsers }}</p>
                </div>
                <div class="w-10 h-10 md:w-14 md:h-14 bg-blue-500/20 rounded-xl flex items-center justify-center">
                    <i class="fas fa-users text-blue-400 text-lg md:text-2xl"></i>
                </div>
            </div>
        </div>
        
        <div class="bg-gray-900 rounded-xl p-4 md:p-6 border border-cyan-500/20">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-400 text-[10px] md:text-sm mb-1">Active</p>
                    <p class="text-2xl md:text-3xl font-bold text-green-400">{{ $activeUsers }}</p>
                </div>
                <div class="w-10 h-10 md:w-14 md:h-14 bg-green-500/20 rounded-xl flex items-center justify-center">
                    <i class="fas fa-user-check text-green-400 text-lg md:text-2xl"></i>
                </div>
            </div>
        </div>
        
        <div class="bg-gray-900 rounded-xl p-4 md:p-6 border border-cyan-500/20">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-400 text-[10px] md:text-sm mb-1">Admins</p>
                    <p class="text-2xl md:text-3xl font-bold text-purple-400">{{ $adminUsers }}</p>
                </div>
                <div class="w-10 h-10 md:w-14 md:h-14 bg-purple-500/20 rounded-xl flex items-center justify-center">
                    <i class="fas fa-user-shield text-purple-400 text-lg md:text-2xl"></i>
                </div>
            </div>
        </div>

        <!-- ✅ NEW: Inactive Users -->
        <div class="bg-gray-900 rounded-xl p-4 md:p-6 border border-cyan-500/20">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-400 text-[10px] md:text-sm mb-1">Inactive</p>
                    <p class="text-2xl md:text-3xl font-bold text-red-400">{{ $totalUsers - $activeUsers }}</p>
                </div>
                <div class="w-10 h-10 md:w-14 md:h-14 bg-red-500/20 rounded-xl flex items-center justify-center">
                    <i class="fas fa-user-times text-red-400 text-lg md:text-2xl"></i>
                </div>
            </div>
        </div>

        <!-- ✅ NEW: New Today -->
        <div class="bg-gray-900 rounded-xl p-4 md:p-6 border border-cyan-500/20">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-400 text-[10px] md:text-sm mb-1">New Today</p>
                    @php
                        $newToday = DB::table('users')->whereDate('created_at', today())->count();
                    @endphp
                    <p class="text-2xl md:text-3xl font-bold text-cyan-400">{{ $newToday }}</p>
                </div>
                <div class="w-10 h-10 md:w-14 md:h-14 bg-cyan-500/20 rounded-xl flex items-center justify-center">
                    <i class="fas fa-user-plus text-cyan-400 text-lg md:text-2xl"></i>
                </div>
            </div>
        </div>

        <!-- ✅ NEW: Online Now -->
        <div class="bg-gray-900 rounded-xl p-4 md:p-6 border border-cyan-500/20">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-400 text-[10px] md:text-sm mb-1">Online</p>
                    @php
                        $onlineNow = DB::table('users')
                            ->where('last_login', '>=', now()->subMinutes(15))
                            ->count();
                    @endphp
                    <p class="text-2xl md:text-3xl font-bold text-yellow-400">{{ $onlineNow }}</p>
                </div>
                <div class="w-10 h-10 md:w-14 md:h-14 bg-yellow-500/20 rounded-xl flex items-center justify-center">
                    <i class="fas fa-circle text-yellow-400 text-lg md:text-2xl animate-pulse"></i>
                </div>
            </div>
        </div>
    </div>
    
    <!-- ✅ ENHANCED FILTERS -->
    <div class="bg-gray-900 rounded-xl p-4 md:p-6 mb-6 border border-cyan-500/20">
        <form method="GET" class="space-y-4">
            <!-- First Row: Search + Filters -->
            <div class="grid grid-cols-1 md:grid-cols-4 gap-3 md:gap-4">
                <!-- Search -->
                <div class="md:col-span-2">
                    <label class="block text-xs md:text-sm font-bold text-gray-400 mb-2">
                        <i class="fas fa-search text-cyan-400 mr-2"></i>Search
                    </label>
                    <div class="relative">
                        <i class="fas fa-search absolute left-4 top-1/2 -translate-y-1/2 text-gray-500"></i>
                        <input type="text" 
                               name="search" 
                               value="{{ $search ?? '' }}" 
                               placeholder="Name, email, or ID..." 
                               class="w-full pl-12 pr-4 py-2 md:py-3 bg-gray-800 border border-gray-700 rounded-lg text-white text-sm focus:border-cyan-500 focus:outline-none focus:ring-2 focus:ring-cyan-500/50">
                    </div>
                </div>
                
                <!-- Role Filter -->
                <div>
                    <label class="block text-xs md:text-sm font-bold text-gray-400 mb-2">
                        <i class="fas fa-user-tag text-cyan-400 mr-2"></i>Role
                    </label>
                    <select name="role" class="w-full px-4 py-2 md:py-3 bg-gray-800 border border-gray-700 rounded-lg text-white text-sm focus:border-cyan-500 focus:outline-none">
                        <option value="">All Roles</option>
                        <option value="admin" {{ ($roleFilter ?? '') === 'admin' ? 'selected' : '' }}>Admin</option>
                        <option value="staff" {{ ($roleFilter ?? '') === 'staff' ? 'selected' : '' }}>Staff</option>
                        <option value="user" {{ ($roleFilter ?? '') === 'user' ? 'selected' : '' }}>User</option>
                    </select>
                </div>
                
                <!-- Status Filter -->
                <div>
                    <label class="block text-xs md:text-sm font-bold text-gray-400 mb-2">
                        <i class="fas fa-toggle-on text-cyan-400 mr-2"></i>Status
                    </label>
                    <select name="status" class="w-full px-4 py-2 md:py-3 bg-gray-800 border border-gray-700 rounded-lg text-white text-sm focus:border-cyan-500 focus:outline-none">
                        <option value="">All Status</option>
                        <option value="1" {{ ($statusFilter ?? '') === '1' ? 'selected' : '' }}>Active</option>
                        <option value="0" {{ ($statusFilter ?? '') === '0' ? 'selected' : '' }}>Inactive</option>
                    </select>
                </div>
            </div>

            <!-- Second Row: Quick Filters + Actions -->
            <div class="flex flex-wrap items-center gap-2">
                <button type="submit" class="px-4 py-2 bg-cyan-600 hover:bg-cyan-700 rounded-lg font-bold transition text-sm">
                    <i class="fas fa-filter mr-2"></i>Apply Filters
                </button>
                <a href="{{ route('account.users.index') }}" class="px-4 py-2 bg-gray-700 hover:bg-gray-600 rounded-lg font-bold transition text-sm">
                    <i class="fas fa-redo mr-2"></i>Clear
                </a>

                <span class="ml-auto text-sm text-gray-400">
                    Showing {{ $users->count() }} of {{ $users->total() }}
                </span>
            </div>
        </form>
    </div>

    <!-- ✅ BULK ACTIONS BAR -->
    <div x-show="selectedUsers.length > 0" 
         x-cloak
         class="bg-blue-500/10 border border-blue-500/30 rounded-xl p-4 mb-6 flex flex-wrap items-center gap-3">
        <span class="text-sm font-bold text-blue-400">
            <i class="fas fa-check-square mr-2"></i>
            <span x-text="selectedUsers.length"></span> selected
        </span>
        
        <button @click="bulkActivate()" class="px-4 py-2 bg-green-500/20 text-green-400 rounded-lg hover:bg-green-500 hover:text-white transition text-sm font-bold">
            <i class="fas fa-check mr-2"></i>Bulk Activate
        </button>
        
        <button @click="bulkDeactivate()" class="px-4 py-2 bg-orange-500/20 text-orange-400 rounded-lg hover:bg-orange-500 hover:text-white transition text-sm font-bold">
            <i class="fas fa-pause mr-2"></i>Bulk Deactivate
        </button>
        
        <button @click="bulkDelete()" class="px-4 py-2 bg-red-500/20 text-red-400 rounded-lg hover:bg-red-500 hover:text-white transition text-sm font-bold">
            <i class="fas fa-trash mr-2"></i>Bulk Delete
        </button>

        <button @click="selectedUsers = []" class="ml-auto px-4 py-2 bg-gray-700 hover:bg-gray-600 rounded-lg transition text-sm">
            Clear Selection
        </button>
    </div>
    
    <!-- Users Table/Cards -->
    <div class="bg-gray-900 rounded-xl border border-cyan-500/20 overflow-hidden">
        
        <!-- ✅ DESKTOP TABLE -->
        <div class="overflow-x-auto desktop-table">
            <table class="w-full">
                <thead class="bg-gray-800 border-b border-gray-700">
                    <tr>
                        <th class="px-4 md:px-6 py-4">
                            <input type="checkbox" 
                                   @change="toggleSelectAll($event)"
                                   :checked="selectedUsers.length === allUserIds.length && allUserIds.length > 0"
                                   class="w-4 h-4 rounded bg-gray-700 border-gray-600 text-cyan-500">
                        </th>
                        <th class="px-4 md:px-6 py-4 text-left text-xs md:text-sm font-bold text-cyan-400">ID</th>
                        <th class="px-4 md:px-6 py-4 text-left text-xs md:text-sm font-bold text-cyan-400">User</th>
                        <th class="px-4 md:px-6 py-4 text-left text-xs md:text-sm font-bold text-cyan-400">Email</th>
                        <th class="px-4 md:px-6 py-4 text-left text-xs md:text-sm font-bold text-cyan-400">Role</th>
                        <th class="px-4 md:px-6 py-4 text-left text-xs md:text-sm font-bold text-cyan-400">Status</th>
                        <th class="px-4 md:px-6 py-4 text-left text-xs md:text-sm font-bold text-cyan-400">Last Login</th>
                        <th class="px-4 md:px-6 py-4 text-left text-xs md:text-sm font-bold text-cyan-400">Actions</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-gray-800">
                    @forelse($users as $user)
                    <tr class="hover:bg-gray-800 transition">
                        <td class="px-4 md:px-6 py-4">
                            <input type="checkbox" 
                                   value="{{ $user->id }}"
                                   @change="toggleSelect({{ $user->id }})"
                                   :checked="selectedUsers.includes({{ $user->id }})"
                                   {{ $user->id == auth()->id() ? 'disabled' : '' }}
                                   class="w-4 h-4 rounded bg-gray-700 border-gray-600 text-cyan-500">
                        </td>
                        <td class="px-4 md:px-6 py-4 text-xs md:text-sm text-gray-400">#{{ $user->id }}</td>
                        <td class="px-4 md:px-6 py-4">
                            <div class="flex items-center gap-3">
                                <div class="w-8 h-8 md:w-10 md:h-10 bg-gradient-to-br from-cyan-400 to-blue-600 rounded-full flex items-center justify-center relative">
                                    <span class="text-white font-bold text-xs md:text-sm">{{ strtoupper(substr($user->name, 0, 1)) }}</span>
                                    @if($user->last_login && \Carbon\Carbon::parse($user->last_login)->gt(now()->subMinutes(15)))
                                    <span class="absolute -bottom-0.5 -right-0.5 w-3 h-3 bg-green-500 border-2 border-gray-900 rounded-full"></span>
                                    @endif
                                </div>
                                <div>
                                    <span class="text-white font-bold text-sm md:text-base">{{ $user->name }}</span>
                                    @if($user->id == auth()->id())
                                    <span class="ml-2 px-2 py-0.5 bg-cyan-500/20 text-cyan-400 rounded text-xs">You</span>
                                    @endif
                                </div>
                            </div>
                        </td>
                        <td class="px-4 md:px-6 py-4 text-xs md:text-sm text-gray-400">{{ $user->email }}</td>
                        <td class="px-4 md:px-6 py-4">
                            @if($user->role === 'admin')
                                <span class="px-2 md:px-3 py-1 bg-purple-500/20 text-purple-400 rounded-full text-xs font-bold">
                                    <i class="fas fa-shield-alt"></i> Admin
                                </span>
                            @elseif($user->role === 'staff')
                                <span class="px-2 md:px-3 py-1 bg-blue-500/20 text-blue-400 rounded-full text-xs font-bold">
                                    <i class="fas fa-user-tie"></i> Staff
                                </span>
                            @else
                                <span class="px-2 md:px-3 py-1 bg-gray-500/20 text-gray-400 rounded-full text-xs font-bold">
                                    <i class="fas fa-user"></i> User
                                </span>
                            @endif
                        </td>
                        <td class="px-4 md:px-6 py-4">
                            @if($user->is_active)
                                <span class="px-2 md:px-3 py-1 bg-green-500/20 text-green-400 rounded-full text-xs font-bold">
                                    <i class="fas fa-check-circle"></i> Active
                                </span>
                            @else
                                <span class="px-2 md:px-3 py-1 bg-red-500/20 text-red-400 rounded-full text-xs font-bold">
                                    <i class="fas fa-times-circle"></i> Inactive
                                </span>
                            @endif
                        </td>
                        <td class="px-4 md:px-6 py-4">
                            @if($user->last_login)
                            <div class="text-xs md:text-sm">
                                <p class="text-gray-400">{{ \Carbon\Carbon::parse($user->last_login)->diffForHumans() }}</p>
                                <p class="text-gray-600 text-xs">{{ \Carbon\Carbon::parse($user->last_login)->format('d M Y, H:i') }}</p>
                            </div>
                            @else
                            <span class="text-xs md:text-sm text-gray-500">Never</span>
                            @endif
                        </td>
                        <td class="px-4 md:px-6 py-4">
                            <div class="flex items-center gap-2">
                                <button @click="editUser({{ $user->id }})" 
                                        class="px-2 md:px-3 py-1 bg-blue-600 hover:bg-blue-700 rounded text-xs font-bold transition">
                                    <i class="fas fa-edit"></i>
                                </button>
                                
                                <button @click="toggleStatus({{ $user->id }})" 
                                        class="px-2 md:px-3 py-1 {{ $user->is_active ? 'bg-orange-600 hover:bg-orange-700' : 'bg-green-600 hover:bg-green-700' }} rounded text-xs font-bold transition"
                                        title="{{ $user->is_active ? 'Deactivate' : 'Activate' }}">
                                    <i class="fas fa-power-off"></i>
                                </button>
                                
                                @if($user->id != auth()->id())
                                <button @click="deleteUser({{ $user->id }})" 
                                        class="px-2 md:px-3 py-1 bg-red-600 hover:bg-red-700 rounded text-xs font-bold transition">
                                    <i class="fas fa-trash"></i>
                                </button>
                                @endif
                            </div>
                        </td>
                    </tr>
                    @empty
                    <tr>
                        <td colspan="8" class="px-6 py-12 text-center">
                            <i class="fas fa-users text-5xl text-gray-700 mb-4"></i>
                            <p class="text-gray-400 text-lg">No users found</p>
                        </td>
                    </tr>
                    @endforelse
                </tbody>
            </table>
        </div>

        <!-- ✅ MOBILE CARDS -->
        <div class="mobile-cards p-4 space-y-4">
            @forelse($users as $user)
            <div class="bg-gray-800/50 border border-gray-700 rounded-xl p-4">
                <!-- Header -->
                <div class="flex items-start gap-3 mb-3">
                    <input type="checkbox" 
                           value="{{ $user->id }}"
                           @change="toggleSelect({{ $user->id }})"
                           :checked="selectedUsers.includes({{ $user->id }})"
                           {{ $user->id == auth()->id() ? 'disabled' : '' }}
                           class="mt-1 w-4 h-4 rounded bg-gray-700 border-gray-600 text-cyan-500">
                    
                    <div class="w-12 h-12 bg-gradient-to-br from-cyan-400 to-blue-600 rounded-full flex items-center justify-center relative">
                        <span class="text-white font-bold">{{ strtoupper(substr($user->name, 0, 1)) }}</span>
                        @if($user->last_login && \Carbon\Carbon::parse($user->last_login)->gt(now()->subMinutes(15)))
                        <span class="absolute -bottom-0.5 -right-0.5 w-3 h-3 bg-green-500 border-2 border-gray-900 rounded-full"></span>
                        @endif
                    </div>
                    
                    <div class="flex-1">
                        <div class="flex items-center gap-2 mb-1">
                            <span class="font-bold text-white">{{ $user->name }}</span>
                            @if($user->id == auth()->id())
                            <span class="px-2 py-0.5 bg-cyan-500/20 text-cyan-400 rounded text-xs">You</span>
                            @endif
                        </div>
                        <p class="text-xs text-gray-400 mb-2">{{ $user->email }}</p>
                        
                        <!-- Role & Status -->
                        <div class="flex gap-2">
                            @if($user->role === 'admin')
                                <span class="px-2 py-1 bg-purple-500/20 text-purple-400 rounded-full text-xs font-bold">
                                    <i class="fas fa-shield-alt"></i> Admin
                                </span>
                            @elseif($user->role === 'staff')
                                <span class="px-2 py-1 bg-blue-500/20 text-blue-400 rounded-full text-xs font-bold">
                                    <i class="fas fa-user-tie"></i> Staff
                                </span>
                            @else
                                <span class="px-2 py-1 bg-gray-500/20 text-gray-400 rounded-full text-xs font-bold">
                                    <i class="fas fa-user"></i> User
                                </span>
                            @endif

                            @if($user->is_active)
                                <span class="px-2 py-1 bg-green-500/20 text-green-400 rounded-full text-xs font-bold">
                                    <i class="fas fa-check-circle"></i> Active
                                </span>
                            @else
                                <span class="px-2 py-1 bg-red-500/20 text-red-400 rounded-full text-xs font-bold">
                                    <i class="fas fa-times-circle"></i> Inactive
                                </span>
                            @endif
                        </div>
                    </div>
                </div>

                <!-- Last Login -->
                <div class="bg-gray-900/50 rounded-lg p-2 mb-3">
                    <p class="text-xs text-gray-500 mb-1">Last Login:</p>
                    @if($user->last_login)
                    <p class="text-sm text-gray-300">{{ \Carbon\Carbon::parse($user->last_login)->diffForHumans() }}</p>
                    @else
                    <p class="text-sm text-gray-500">Never</p>
                    @endif
                </div>

                <!-- Actions -->
                <div class="flex gap-2">
                    <button @click="editUser({{ $user->id }})" 
                            class="flex-1 px-3 py-2 bg-blue-600 hover:bg-blue-700 rounded text-xs font-bold transition">
                        <i class="fas fa-edit mr-1"></i>Edit
                    </button>
                    
                    <button @click="toggleStatus({{ $user->id }})" 
                            class="px-3 py-2 {{ $user->is_active ? 'bg-orange-600 hover:bg-orange-700' : 'bg-green-600 hover:bg-green-700' }} rounded text-xs font-bold transition">
                        <i class="fas fa-power-off"></i>
                    </button>
                    
                    @if($user->id != auth()->id())
                    <button @click="deleteUser({{ $user->id }})" 
                            class="px-3 py-2 bg-red-600 hover:bg-red-700 rounded text-xs font-bold transition">
                        <i class="fas fa-trash"></i>
                    </button>
                    @endif
                </div>
            </div>
            @empty
            <div class="text-center py-12">
                <i class="fas fa-users text-5xl text-gray-700 mb-4"></i>
                <p class="text-gray-400">No users found</p>
            </div>
            @endforelse
        </div>
        
        <!-- Pagination -->
        @if($users->hasPages())
        <div class="px-4 md:px-6 py-4 bg-gray-800 border-t border-gray-700">
            {{ $users->appends(request()->query())->links() }}
        </div>
        @endif
    </div>
</div>

<!-- ✅ ADD/EDIT MODAL -->
<div x-show="showModal" 
     x-cloak
     class="fixed inset-0 z-50 flex items-center justify-center bg-black/80 backdrop-blur-sm p-4"
     @click.self="closeModal()">
    <div class="bg-gray-900 rounded-3xl w-full max-w-md border border-cyan-500/30 shadow-2xl" 
         @click.stop
         x-transition:enter="transition ease-out duration-300"
         x-transition:enter-start="opacity-0 scale-90"
         x-transition:enter-end="opacity-100 scale-100">
        
        <!-- Header -->
        <div class="bg-gradient-to-r from-cyan-500 to-blue-600 p-4 md:p-6 rounded-t-3xl">
            <div class="flex items-center justify-between">
                <h3 class="text-xl md:text-2xl font-bold font-orbitron" x-text="modalMode === 'add' ? 'Add New User' : 'Edit User'"></h3>
                <button @click="closeModal()" class="w-10 h-10 rounded-full bg-white/20 hover:bg-white/30 transition flex items-center justify-center">
                    <i class="fas fa-times text-xl"></i>
                </button>
            </div>
        </div>
        
        <!-- Form -->
        <form @submit.prevent="submitForm()" class="p-4 md:p-6 space-y-4">
            <!-- Name -->
            <div>
                <label class="block text-xs md:text-sm font-bold text-gray-400 mb-2">
                    <i class="fas fa-user text-cyan-400 mr-2"></i>Full Name *
                </label>
                <input type="text" x-model="formData.name" required
                       class="w-full px-4 py-2 md:py-3 bg-gray-800 border border-gray-700 rounded-lg text-white text-sm focus:border-cyan-500 focus:outline-none focus:ring-2 focus:ring-cyan-500/50">
            </div>
            
            <!-- Email -->
            <div>
                <label class="block text-xs md:text-sm font-bold text-gray-400 mb-2">
                    <i class="fas fa-envelope text-cyan-400 mr-2"></i>Email Address *
                </label>
                <input type="email" x-model="formData.email" required
                       class="w-full px-4 py-2 md:py-3 bg-gray-800 border border-gray-700 rounded-lg text-white text-sm focus:border-cyan-500 focus:outline-none focus:ring-2 focus:ring-cyan-500/50">
            </div>
            
            <!-- Role -->
            <div>
                <label class="block text-xs md:text-sm font-bold text-gray-400 mb-2">
                    <i class="fas fa-user-tag text-cyan-400 mr-2"></i>Role *
                </label>
                <select x-model="formData.role" required
                        class="w-full px-4 py-2 md:py-3 bg-gray-800 border border-gray-700 rounded-lg text-white text-sm focus:border-cyan-500 focus:outline-none focus:ring-2 focus:ring-cyan-500/50">
                    <option value="user">User</option>
                    <option value="staff">Staff</option>
                    <option value="admin">Admin</option>
                </select>
            </div>
            
            <!-- Password -->
            <div>
                <label class="block text-xs md:text-sm font-bold text-gray-400 mb-2">
                    <i class="fas fa-lock text-cyan-400 mr-2"></i>Password <span x-text="modalMode === 'add' ? '*' : '(Leave blank to keep current)'"></span>
                </label>
                <input type="password" x-model="formData.password"
                       :required="modalMode === 'add'"
                       class="w-full px-4 py-2 md:py-3 bg-gray-800 border border-gray-700 rounded-lg text-white text-sm focus:border-cyan-500 focus:outline-none focus:ring-2 focus:ring-cyan-500/50">
            </div>
            
            <!-- Buttons -->
            <div class="flex gap-3 pt-4">
                <button type="button" @click="closeModal()" 
                        class="flex-1 px-4 md:px-6 py-2 md:py-3 bg-gray-700 hover:bg-gray-600 rounded-lg font-bold transition text-sm">
                    <i class="fas fa-times mr-2"></i>Cancel
                </button>
                <button type="submit" 
                        :disabled="loading"
                        class="flex-1 px-4 md:px-6 py-2 md:py-3 bg-gradient-to-r from-cyan-500 to-blue-600 hover:opacity-90 rounded-lg font-bold transition text-sm disabled:opacity-50">
                    <span x-show="!loading">
                        <i class="fas fa-save mr-2"></i>Save
                    </span>
                    <span x-show="loading">
                        <i class="fas fa-spinner fa-spin mr-2"></i>Saving...
                    </span>
                </button>
            </div>
        </form>
    </div>
</div>

<script>
function userManager() {
    return {
        showModal: false,
        modalMode: 'add',
        loading: false,
        selectedUsers: [],
        allUserIds: @json($users->pluck('id')),
        formData: {
            id: null,
            name: '',
            email: '',
            role: 'user',
            password: ''
        },

        openAddModal() {
            this.modalMode = 'add';
            this.formData = {
                id: null,
                name: '',
                email: '',
                role: 'user',
                password: ''
            };
            this.showModal = true;
        },

        closeModal() {
            this.showModal = false;
            this.formData = {
                id: null,
                name: '',
                email: '',
                role: 'user',
                password: ''
            };
        },

        async editUser(id) {
            try {
                const response = await fetch(`/account/users/${id}`);
                const data = await response.json();
                
                if (data.success) {
                    this.modalMode = 'edit';
                    this.formData = {
                        id: data.data.id,
                        name: data.data.name,
                        email: data.data.email,
                        role: data.data.role,
                        password: ''
                    };
                    this.showModal = true;
                }
            } catch (error) {
                alert('❌ Error loading user data');
                console.error(error);
            }
        },

        async submitForm() {
            this.loading = true;
            
            const isEdit = this.modalMode === 'edit';
            const url = isEdit ? `/account/users/${this.formData.id}` : '/account/users';
            
            const payload = {
                name: this.formData.name,
                email: this.formData.email,
                role: this.formData.role,
                password: this.formData.password
            };

            if (isEdit) {
                payload._method = 'PUT';
            }
            
            try {
                const response = await fetch(url, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Accept': 'application/json',
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
                    },
                    body: JSON.stringify(payload)
                });
                
                const data = await response.json();
                
                if (data.success) {
                    alert('✅ ' + data.message);
                    window.location.reload();
                } else {
                    alert('❌ ' + (data.message || 'Error saving user'));
                }
            } catch (error) {
                alert('❌ Failed to save user');
                console.error(error);
            } finally {
                this.loading = false;
            }
        },

        async toggleStatus(id) {
            if (!confirm('Toggle user status?')) return;
            
            try {
                const response = await fetch(`/account/users/${id}/toggle-status`, {
                    method: 'POST',
                    headers: {
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
                    }
                });
                
                const data = await response.json();
                
                if (data.success) {
                    window.location.reload();
                } else {
                    alert(data.message);
                }
            } catch (error) {
                alert('❌ Error toggling status');
                console.error(error);
            }
        },

        async deleteUser(id) {
            if (!confirm('⚠️ Delete this user permanently?\n\nThis action cannot be undone!')) return;
            
            try {
                const response = await fetch(`/account/users/${id}`, {
                    method: 'DELETE',
                    headers: {
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
                    }
                });
                
                const data = await response.json();
                
                if (data.success) {
                    alert('✅ ' + data.message);
                    window.location.reload();
                } else {
                    alert('❌ ' + data.message);
                }
            } catch (error) {
                alert('❌ Error deleting user');
                console.error(error);
            }
        },

        toggleSelect(id) {
            const index = this.selectedUsers.indexOf(id);
            if (index > -1) {
                this.selectedUsers.splice(index, 1);
            } else {
                this.selectedUsers.push(id);
            }
        },

        toggleSelectAll(event) {
            if (event.target.checked) {
                // Don't select current user
                this.selectedUsers = this.allUserIds.filter(id => id !== {{ auth()->id() }});
            } else {
                this.selectedUsers = [];
            }
        },

        async bulkActivate() {
            if (this.selectedUsers.length === 0) return;
            
            if (!confirm(`Activate ${this.selectedUsers.length} users?`)) return;

            try {
                const response = await fetch('/account/users/bulk-activate', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
                    },
                    body: JSON.stringify({ user_ids: this.selectedUsers })
                });

                const data = await response.json();
                if (data.success) {
                    alert('✅ ' + data.message);
                    window.location.reload();
                }
            } catch (error) {
                alert('❌ Failed to activate users');
            }
        },

        async bulkDeactivate() {
            if (this.selectedUsers.length === 0) return;
            
            if (!confirm(`Deactivate ${this.selectedUsers.length} users?`)) return;

            try {
                const response = await fetch('/account/users/bulk-deactivate', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
                    },
                    body: JSON.stringify({ user_ids: this.selectedUsers })
                });

                const data = await response.json();
                if (data.success) {
                    alert('✅ ' + data.message);
                    window.location.reload();
                }
            } catch (error) {
                alert('❌ Failed to deactivate users');
            }
        },

        async bulkDelete() {
            if (this.selectedUsers.length === 0) return;
            
            if (!confirm(`⚠️ Delete ${this.selectedUsers.length} users permanently?\n\nThis action cannot be undone!`)) return;

            try {
                const response = await fetch('/account/users/bulk-delete', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
                    },
                    body: JSON.stringify({ user_ids: this.selectedUsers })
                });

                const data = await response.json();
                if (data.success) {
                    alert('✅ ' + data.message);
                    window.location.reload();
                }
            } catch (error) {
                alert('❌ Failed to delete users');
            }
        }
    }
}
</script>

</body>
</html>