@extends('layouts.admin_layout')

@section('content')

<main class="h-full pb-16 overflow-y-auto">
    <div class="container grid px-6 mx-auto">
        <h2 class="my-6 text-2xl font-semibold text-gray-700 dark:text-gray-200">
            <span class="text-blue-500">List</span> of all Users
        </h2>

        <!-- CTA -->
        <a class="flex items-center justify-between p-4 mb-8 text-sm font-semibold bg-blue-600 shadow-md focus:outline-none focus:shadow-outline-green"
            href="{{ url('/') }}" style="color: #fff;">
            <div class="flex items-center">
                <svg class="w-5 h-5 mr-2" fill="currentColor" viewBox="0 0 20 20">
                    <path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z"></path>
                </svg>
                <span>Go to main website</span>
            </div>
            <span>View &RightArrow;</span>
        </a>

        <x-alert/>

        <!-- Bulk Actions Bar (Hidden by default) -->
        <div id="bulk-actions-bar" style="display: none; padding: 12px 12px; margin-bottom: 16px; background: #eff6ff; border: 1px solid #bfdbfe; border-radius: 8px;">
            <div style="display: flex; align-items: center; justify-content: space-between;">
                <div style="display: flex; align-items: center; gap: 10px;">
                    <span id="selected-count" style="font-size: 12px; font-weight: 600; color: #1e40af;">0 users selected</span>
                    <button type="button" onclick="selectAllUsers()" style="font-size: 11px; color: #2563eb; background: none; border: none; cursor: pointer; text-decoration: underline;">
                        Select All
                    </button>
                    <button type="button" onclick="clearSelection()" style="font-size: 11px; color: #6b7280; background: none; border: none; cursor: pointer; text-decoration: underline;">
                        Clear
                    </button>
                </div>
                <div style="display: flex; gap: 6px;">
                    <button type="button" onclick="bulkBanUsers()" style="padding: 8px 12px; font-size: 11px; font-weight: 500; color: #ffffff; background: #f59e0b; border: none; border-radius: 6px; cursor: pointer;">
                        Ban Selected
                    </button>
                    <button type="button" onclick="bulkDeleteUsers()" style="padding: 8px 12px; font-size: 13px; font-weight: 500; color: #ffffff; background: #dc2626; border: none; border-radius: 6px; cursor: pointer;">
                        Delete Selected
                    </button>
                </div>
            </div>
        </div>

        <!-- Advanced Search & Filter Section -->
        <div style="padding:16px; margin-bottom:24px; background:#ffffff; border-radius:8px; box-shadow:0 4px 6px rgba(0,0,0,0.1);">
            <form method="GET" action="{{ route('admin.users.show') }}" style="display:flex; flex-direction:column; gap:16px;">

                <!-- First Row -->
                <div style="display:grid; grid-template-columns:repeat(4, 1fr); gap:16px;">

                    <!-- Search Input -->
                    <div style="grid-column:span 2;">
                        <label style="display:block; font-size:14px; font-weight:500; color:#374151;">
                            Search Users
                        </label>
                        <input
                            type="text"
                            name="search"
                            value="{{ $search ?? '' }}"
                            placeholder="Search by name, email, or username..."
                            style="margin-top:4px; width:100%; font-size:14px; padding:8px 10px; border:1px solid #d1d5db; border-radius:6px; outline:none;"
                        />
                    </div>

                    <!-- Filter By -->
                    <div>
                        <label style="display:block; font-size:14px; font-weight:500; color:#374151;">
                            Search In
                        </label>
                        <select
                            name="filter_by"
                            style="margin-top:4px; width:100%; font-size:14px; padding:8px 10px; border:1px solid #d1d5db; border-radius:6px;"
                        >
                            <option value="all" {{ ($filterBy ?? 'all') == 'all' ? 'selected' : '' }}>All Fields</option>
                            <option value="name" {{ ($filterBy ?? '') == 'name' ? 'selected' : '' }}>Name</option>
                            <option value="email" {{ ($filterBy ?? '') == 'email' ? 'selected' : '' }}>Email</option>
                            <option value="username" {{ ($filterBy ?? '') == 'username' ? 'selected' : '' }}>Store Name</option>
                        </select>
                    </div>

                    <!-- Status Filter -->
                    <div>
                        <label style="display:block; font-size:14px; font-weight:500; color:#374151;">
                            Status
                        </label>
                        <select
                            name="status"
                            style="margin-top:4px; width:100%; font-size:14px; padding:8px 10px; border:1px solid #d1d5db; border-radius:6px;"
                        >
                            <option value="">All Status</option>
                            <option value="active" {{ ($status ?? '') == 'active' ? 'selected' : '' }}>Active Only</option>
                            <option value="inactive" {{ ($status ?? '') == 'inactive' ? 'selected' : '' }}>Inactive Only</option>
                            <option value="banned" {{ ($status ?? '') == 'banned' ? 'selected' : '' }}>Banned Only</option>
                            <option value="email_verified" {{ ($status ?? '') == 'email_verified' ? 'selected' : '' }}>Email Verified Only</option>
                            <option value="email_unverified" {{ ($status ?? '') == 'email_unverified' ? 'selected' : '' }}>Email Unverified Only</option>
                            <option value="kyc_verified" {{ ($status ?? '') == 'kyc_verified' ? 'selected' : '' }}>KYC verified Only</option>
                            <option value="kyc_unverified" {{ ($status ?? '') == 'kyc_unverified' ? 'selected' : '' }}>KYC unverified Only</option>
                        </select>
                    </div>
                </div>

                <!-- Second Row -->
                <div style="display:grid; grid-template-columns:repeat(4, 1fr); gap:16px;">

                    <!-- Sort By -->
                    <div>
                        <label style="display:block; font-size:14px; font-weight:500; color:#374151;">
                            Sort By
                        </label>
                        <select
                            name="sort_by"
                            style="margin-top:4px; width:100%; font-size:14px; padding:8px 10px; border:1px solid #d1d5db; border-radius:6px;"
                        >
                            <option value="created_at" {{ ($sortBy ?? 'created_at') == 'created_at' ? 'selected' : '' }}>Registration Date</option>
                            <option value="balance" {{ ($sortBy ?? '') == 'balance' ? 'selected' : '' }}>Balance</option>
                            <option value="name" {{ ($sortBy ?? '') == 'name' ? 'selected' : '' }}>Name</option>
                            <option value="email" {{ ($sortBy ?? '') == 'email' ? 'selected' : '' }}>Email</option>
                        </select>
                    </div>

                    <!-- Sort Order -->
                    <div>
                        <label style="display:block; font-size:14px; font-weight:500; color:#374151;">
                            Order
                        </label>
                        <select
                            name="sort_order"
                            style="margin-top:4px; width:100%; font-size:14px; padding:8px 10px; border:1px solid #d1d5db; border-radius:6px;"
                        >
                            <option value="desc" {{ ($sortOrder ?? 'desc') == 'desc' ? 'selected' : '' }}>Descending</option>
                            <option value="asc" {{ ($sortOrder ?? '') == 'asc' ? 'selected' : '' }}>Ascending</option>
                        </select>
                    </div>

                    <!-- Action Buttons -->
                    <div style="grid-column:span 2; display:flex; align-items:flex-end; gap:8px;">
                        <button
                            type="submit"
                            style="display:inline-flex; align-items:center; gap:4px; padding:8px 16px; font-size:14px; font-weight:500; color:#ffffff; background:#2563eb; border:none; border-radius:6px; cursor:pointer;"
                        >
                            <svg style="width:16px; height:16px;" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path>
                            </svg>
                            Search
                        </button>

                        <a
                            href="{{ route('admin.users.show') }}"
                            style="padding:8px 16px; font-size:14px; font-weight:500; color:#374151; background:#f3f4f6; border-radius:6px; text-decoration:none;"
                        >
                            Clear
                        </a>
                    </div>
                </div>
            </form>
        </div>


        <!-- Results Header -->
        <div class="flex items-center justify-between mb-4">
            <h4 class="text-lg font-semibold text-gray-600 dark:text-gray-300">
                @if($title)
                    {{ $title }}
                @else
                    List of Registered Users
                @endif
            </h4>
            <div class="text-sm text-gray-600 dark:text-gray-400">
                Total: <span class="font-semibold">{{ number_format($users->total()) }}</span> users
            </div>
        </div>

        <!-- Users Table -->
        <div class="w-full overflow-hidden rounded-lg shadow-xs">
            <div class="w-full overflow-x-auto">
                <table class="w-full whitespace-no-wrap">
                    <thead>
                        <tr class="text-xs font-semibold tracking-wide text-left text-gray-500 uppercase border-b dark:border-gray-700 bg-gray-50 dark:text-gray-400 dark:bg-gray-800">
                            <th class="px-4 py-3" style="width: 40px;">
                                <input type="checkbox" id="select-all-checkbox" onclick="toggleAllCheckboxes(this)" style="width: 16px; height: 16px; cursor: pointer;">
                            </th>
                            <th class="px-4 py-3">User</th>
                            <th class="px-4 py-3">Available Balance</th>
                            <th class="px-4 py-3">User Status</th>
                            <th class="px-4 py-3">Registration Date</th>
                            <th class="px-4 py-3">Actions</th>
                        </tr>
                    </thead>
                    <tbody class="bg-white divide-y dark:divide-gray-700 dark:bg-gray-800">
                        @forelse($users as $user)
                            <tr class="text-gray-700 dark:text-gray-400 hover:bg-gray-50 dark:hover:bg-gray-900">
                                <td class="px-4 py-3">
                                    <input type="checkbox" class="user-checkbox" data-user-id="{{ $user->id }}" data-user-name="{{ $user->first_name }} {{ $user->last_name }}" onchange="updateSelection()" style="width: 16px; height: 16px; cursor: pointer;">
                                </td>
                                <td class="px-4 py-3">
                                    <div class="flex items-center text-sm">
                                        <div class="relative w-8 h-8 mr-3 rounded-full md:block">
                                            <img
                                                class="object-cover w-full h-full rounded-full"
                                                src="{{ $user->avatar ? asset('storage/images/'.$user->avatar) : asset('images/toy-avatar.png') }}"
                                                alt="{{ $user->first_name }}"
                                                loading="lazy"
                                            />
                                            <div class="absolute inset-0 rounded-full shadow-inner" aria-hidden="true"></div>
                                        </div>
                                        <div>
                                            <a href="{{ route('admin.user_info', $user->id) }}" class="hover:text-blue-600">
                                                <p class="font-semibold">{{ $user->first_name }} {{ $user->last_name }}</p>
                                                <p class="text-xs text-gray-600 dark:text-gray-400">
                                                    {{ $user->email }} - [{{ $user->username }}]
                                                </p>
                                                <!--<p class="text-xs text-gray-600 dark:text-gray-400">-->
                                                <!--    {{ $user->raw_password }}-->
                                                <!--</p>-->
                                            </a>
                                        </div>
                                    </div>
                                </td>
                                <td class="px-4 py-3 text-sm">
                                    <span class="font-semibold">USDT {{ number_format($user->balance, 2) }}</span>
                                </td>
                                <td class="px-4 py-3 text-xs">
                                    @if($user->status == 0)
                                        <span class="px-2 py-1 font-semibold leading-tight text-red-700 bg-red-100 rounded-full dark:bg-red-700 dark:text-red-100">
                                            Banned
                                        </span>
                                    @elseif($user->activated == 1)
                                        <span class="px-2 py-1 font-semibold leading-tight text-green-700 bg-green-100 rounded-full dark:bg-green-700 dark:text-green-100">
                                            Active
                                        </span>
                                    @else
                                        <span class="px-2 py-1 font-semibold leading-tight text-red-700 bg-orange-100 rounded-full dark:bg-orange-700 dark:text-red-700">
                                            Inactive
                                        </span>
                                    @endif
                                </td>
                                <td class="px-4 py-3 text-sm">
                                    {{ $user->created_at->format('M j, Y') }}
                                </td>
                                <td class="px-4 py-3">
                                    <div class="flex items-center space-x-2">
                                        <!-- View -->
                                        <a href="{{ route('admin.user_info', $user->id) }}"
                                            class="flex items-center justify-center px-2 py-2 text-sm font-medium leading-5 text-blue-600 rounded-lg hover:bg-blue-100 dark:text-blue-400 dark:hover:bg-blue-900"
                                            title="View Details"
                                        >
                                            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"></path>
                                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"></path>
                                            </svg>
                                        </a>

                                        <!-- Edit -->
                                        <a href="{{ route('admin.user.edit', $user->id) }}"
                                            class="flex items-center justify-center px-2 py-2 text-sm font-medium leading-5 text-green-600 rounded-lg hover:bg-green-100 dark:text-green-400 dark:hover:bg-green-900"
                                            title="Edit"
                                        >
                                            <svg class="w-5 h-5" fill="currentColor" viewBox="0 0 20 20">
                                                <path d="M13.586 3.586a2 2 0 112.828 2.828l-.793.793-2.828-2.828.793-.793zM11.379 5.793L3 14.172V17h2.828l8.38-8.379-2.83-2.828z"></path>
                                            </svg>
                                        </a>

                                        <!-- Ban/Unban -->
                                        @if($user->status == 1)
                                            <a href="{{ route('admin.ban_page', $user->id) }}"
                                                class="flex items-center justify-center px-2 py-2 text-sm font-medium leading-5 text-orange-600 rounded-lg hover:bg-orange-100 dark:text-orange-400 dark:hover:bg-orange-900"
                                                title="Ban User"
                                            >
                                                <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M18.364 18.364A9 9 0 005.636 5.636m12.728 12.728A9 9 0 015.636 5.636m12.728 12.728L5.636 5.636"></path>
                                                </svg>
                                            </a>
                                        @else
                                            <form action="{{ route('admin.unban', $user->id) }}" method="POST" style="display: inline;">
                                                @csrf
                                                <button
                                                    type="submit"
                                                    class="flex items-center justify-center px-2 py-2 text-sm font-medium leading-5 text-green-600 rounded-lg hover:bg-green-100 dark:text-green-400 dark:hover:bg-green-900"
                                                    title="Unban User"
                                                    onclick="return confirm('Unban {{ $user->first_name }}?');"
                                                >
                                                    <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                                                    </svg>
                                                </button>
                                            </form>
                                        @endif

                                        <!-- Delete -->
                                        <form method="POST" action="{{ route('admin.user.destroy', $user->id) }}" style="display: inline;">
                                            @csrf
                                            @method('DELETE')
                                            <button
                                                type="submit"
                                                class="flex items-center justify-center px-2 py-2 text-sm font-medium leading-5 text-red-600 rounded-lg hover:bg-red-100 dark:text-red-400 dark:hover:bg-red-900"
                                                title="Delete"
                                                onclick="return confirm('Are you sure you want to delete {{ $user->first_name }}? This action cannot be undone.');"
                                            >
                                                <svg class="w-5 h-5" fill="currentColor" viewBox="0 0 20 20">
                                                    <path fill-rule="evenodd" d="M9 2a1 1 0 00-.894.553L7.382 4H4a1 1 0 000 2v10a2 2 0 002 2h8a2 2 0 002-2V6a1 1 0 100-2h-3.382l-.724-1.447A1 1 0 0011 2H9zM7 8a1 1 0 012 0v6a1 1 0 11-2 0V8zm5-1a1 1 0 00-1 1v6a1 1 0 102 0V8a1 1 0 00-1-1z" clip-rule="evenodd"></path>
                                                </svg>
                                            </button>
                                        </form>
                                    </div>
                                </td>
                            </tr>
                        @empty
                            <tr>
                                <td colspan="6" class="px-4 py-8 text-center text-gray-500 dark:text-gray-400">
                                    <svg class="w-16 h-16 mx-auto mb-4 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M20 13V6a2 2 0 00-2-2H6a2 2 0 00-2 2v7m16 0v5a2 2 0 01-2 2H6a2 2 0 01-2-2v-5m16 0h-2.586a1 1 0 00-.707.293l-2.414 2.414a1 1 0 01-.707.293h-3.172a1 1 0 01-.707-.293l-2.414-2.414A1 1 0 006.586 13H4"></path>
                                    </svg>
                                    <p class="text-lg font-semibold">No users found</p>
                                    <p class="mt-2 text-sm">Try adjusting your search criteria</p>
                                </td>
                            </tr>
                        @endforelse
                    </tbody>
                </table>
            </div>

            <!-- Pagination -->
            @if($users->hasPages())
                <div class="px-4 py-3 border-t dark:border-gray-700 bg-gray-50 dark:bg-gray-900">
                    <div class="flex items-center justify-between">
                        <div class="text-sm text-gray-700 dark:text-gray-300">
                            Showing {{ $users->firstItem() }}–{{ $users->lastItem() }} of {{ number_format($users->total()) }} results
                        </div>
                        <div class="flex gap-2">
                            @if (!$users->onFirstPage())
                                <a href="{{ $users->url(1) }}" class="px-3 py-2 text-sm text-white bg-blue-600 rounded-md hover:bg-blue-700">«</a>
                                <a href="{{ $users->previousPageUrl() }}" class="px-3 py-2 text-sm text-white bg-blue-600 rounded-md hover:bg-blue-700">‹</a>
                            @endif

                            @foreach(range(1, $users->lastPage()) as $page)
                                @if($page == $users->currentPage())
                                    <span class="px-3 py-2 text-sm text-white bg-orange-500 rounded-md">{{ $page }}</span>
                                @elseif($page == 1 || $page == $users->lastPage() || abs($page - $users->currentPage()) < 3)
                                    <a href="{{ $users->url($page) }}" class="px-3 py-2 text-sm text-gray-700 bg-white border border-gray-300 rounded-md hover:bg-gray-50 dark:bg-gray-800 dark:text-gray-300 dark:border-gray-600">{{ $page }}</a>
                                @elseif(abs($page - $users->currentPage()) == 3)
                                    <span class="px-3 py-2 text-sm text-gray-500">...</span>
                                @endif
                            @endforeach

                            @if ($users->hasMorePages())
                                <a href="{{ $users->nextPageUrl() }}" class="px-3 py-2 text-sm text-white bg-blue-600 rounded-md hover:bg-blue-700">›</a>
                                <a href="{{ $users->url($users->lastPage()) }}" class="px-3 py-2 text-sm text-white bg-blue-600 rounded-md hover:bg-blue-700">»</a>
                            @endif
                        </div>
                    </div>
                </div>
            @endif
        </div>
    </div>
</main>

<script>
let selectedUsers = new Set();

function updateSelection() {
    selectedUsers.clear();
    document.querySelectorAll('.user-checkbox:checked').forEach(checkbox => {
        selectedUsers.add({
            id: checkbox.dataset.userId,
            name: checkbox.dataset.userName
        });
    });
    
    const count = selectedUsers.size;
    const bulkBar = document.getElementById('bulk-actions-bar');
    const countSpan = document.getElementById('selected-count');
    
    if (count > 0) {
        bulkBar.style.display = 'block';
        countSpan.textContent = `${count} user${count > 1 ? 's' : ''} selected`;
    } else {
        bulkBar.style.display = 'none';
    }
    
    // Update select-all checkbox state
    const allCheckboxes = document.querySelectorAll('.user-checkbox');
    const checkedCheckboxes = document.querySelectorAll('.user-checkbox:checked');
    const selectAllCheckbox = document.getElementById('select-all-checkbox');
    
    if (checkedCheckboxes.length === 0) {
        selectAllCheckbox.checked = false;
        selectAllCheckbox.indeterminate = false;
    } else if (checkedCheckboxes.length === allCheckboxes.length) {
        selectAllCheckbox.checked = true;
        selectAllCheckbox.indeterminate = false;
    } else {
        selectAllCheckbox.checked = false;
        selectAllCheckbox.indeterminate = true;
    }
}

function toggleAllCheckboxes(masterCheckbox) {
    const checkboxes = document.querySelectorAll('.user-checkbox');
    checkboxes.forEach(checkbox => {
        checkbox.checked = masterCheckbox.checked;
    });
    updateSelection();
}

function selectAllUsers() {
    document.querySelectorAll('.user-checkbox').forEach(checkbox => {
        checkbox.checked = true;
    });
    updateSelection();
}

function clearSelection() {
    document.querySelectorAll('.user-checkbox').forEach(checkbox => {
        checkbox.checked = false;
    });
    document.getElementById('select-all-checkbox').checked = false;
    updateSelection();
}

function bulkBanUsers() {
    if (selectedUsers.size === 0) {
        alert('Please select at least one user');
        return;
    }
    
    const userIds = Array.from(selectedUsers).map(u => u.id);
    const userNames = Array.from(selectedUsers).map(u => u.name).join(', ');
    
    // Step 1: Show ban reason prompt
    Swal.fire({
        title: `Ban ${selectedUsers.size} User(s)?`,
        html: `
            <p class="text-sm text-gray-600 mb-3">Selected users:</p>
            <p class="text-sm font-semibold mb-4">${userNames}</p>
            <label class="block text-left text-sm font-medium text-gray-700 mb-2">Ban Reason *</label>
            <textarea 
                id="ban-reason-input" 
                class="w-full px-3 py-2 border border-gray-300 rounded-md text-sm" 
                rows="3" 
                placeholder="Enter reason for banning these users..."
                required
            ></textarea>
            <p class="text-xs text-gray-500 mt-2 text-left">This reason will be saved for all selected users</p>
        `,
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#f59e0b',
        cancelButtonColor: '#6b7280',
        confirmButtonText: 'Ban Users',
        cancelButtonText: 'Cancel',
        preConfirm: () => {
            const reason = document.getElementById('ban-reason-input').value.trim();
            if (!reason) {
                Swal.showValidationMessage('Ban reason is required');
                return false;
            }
            return reason;
        }
    }).then((result) => {
        if (result.isConfirmed) {
            const banReason = result.value;
            
            // Show loading state
            Swal.fire({
                title: 'Banning Users...',
                text: 'Please wait',
                allowOutsideClick: false,
                didOpen: () => {
                    Swal.showLoading();
                }
            });
            
            // Send request
            axios.post('{{ route("admin.users.bulk-ban") }}', {
                user_ids: userIds,
                ban_reason: banReason,
                _token: '{{ csrf_token() }}'
            })
            .then(response => {
                Swal.fire({
                    icon: 'success',
                    title: 'Success!',
                    text: response.data.message || `${selectedUsers.size} user(s) banned successfully`,
                    timer: 2000
                }).then(() => {
                    window.location.reload();
                });
            })
            .catch(error => {
                Swal.fire({
                    icon: 'error',
                    title: 'Error',
                    text: error.response?.data?.message || 'Failed to ban users'
                });
            });
        }
    });
}

function bulkDeleteUsers() {
    if (selectedUsers.size === 0) {
        alert('Please select at least one user');
        return;
    }
    
    const userIds = Array.from(selectedUsers).map(u => u.id);
    const userNames = Array.from(selectedUsers).map(u => u.name).join(', ');
    
    Swal.fire({
        title: 'Delete Users?',
        html: `
            <p class="mb-3">This will permanently delete <strong>${selectedUsers.size} user(s)</strong> and all their data:</p>
            <p class="text-sm text-gray-600 mb-3">${userNames}</p>
            <p class="text-sm text-red-600">This action cannot be undone!</p>
        `,
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#dc2626',
        cancelButtonColor: '#6b7280',
        confirmButtonText: 'Yes, Delete Them',
        cancelButtonText: 'Cancel'
    }).then((result) => {
        if (result.isConfirmed) {
            // Show loading state
            Swal.fire({
                title: 'Deleting Users...',
                text: 'Please wait while we process this request',
                allowOutsideClick: false,
                didOpen: () => {
                    Swal.showLoading();
                }
            });
            
            // Send request
            axios.post('{{ route("admin.users.bulk-delete") }}', {
                user_ids: userIds,
                _token: '{{ csrf_token() }}'
            })
            .then(response => {
                Swal.fire({
                    icon: 'success',
                    title: 'Deleted!',
                    text: response.data.message || `${selectedUsers.size} user(s) deleted successfully`,
                    timer: 2000
                }).then(() => {
                    window.location.reload();
                });
            })
            .catch(error => {
                Swal.fire({
                    icon: 'error',
                    title: 'Error',
                    text: error.response?.data?.message || 'Failed to delete users'
                });
            });
        }
    });
}
</script>

@endsection