<div class="relative pt-5 text-gray-900 dark:text-white xl:max-w-[95%] 2xl:max-w-[90%]"
    x-data="{
        showConfirm: false,
        confirmAction: null,
        confirmTitle: '',
        confirmMessage: '',
        confirmButtonClass: '',
        confirmCallback: null,
        openConfirm(title, message, buttonClass, callback) {
            this.confirmTitle = title;
            this.confirmMessage = message;
            this.confirmButtonClass = buttonClass;
            this.confirmCallback = callback;
            this.showConfirm = true;
        },
        executeConfirm() {
            if (this.confirmCallback) this.confirmCallback();
            this.showConfirm = false;
        }
    }"
    x-on:notify.window="
        $dispatch('toast', { type: $event.detail.type, message: $event.detail.message })
    ">

    {{-- Notifications --}}
    <div x-data="{ toasts: [] }"
        x-on:toast.window="
            const id = Date.now();
            toasts.push({ id, type: $event.detail.type, message: $event.detail.message });
            setTimeout(() => { toasts = toasts.filter(t => t.id !== id) }, 4000);
        "
        class="fixed top-4 right-4 z-[100] space-y-2 w-80"
    >
        <template x-for="toast in toasts" :key="toast.id">
            <div x-show="true"
                x-transition:enter="transition ease-out duration-300"
                x-transition:enter-start="translate-x-full opacity-0"
                x-transition:enter-end="translate-x-0 opacity-100"
                x-transition:leave="transition ease-in duration-200"
                x-transition:leave-start="translate-x-0 opacity-100"
                x-transition:leave-end="translate-x-full opacity-0"
                :class="toast.type === 'success' ? 'bg-green-600' : 'bg-red-600'"
                class="rounded-lg px-4 py-3 text-white text-sm shadow-lg flex items-center justify-between"
            >
                <span x-text="toast.message"></span>
                <button @click="toasts = toasts.filter(t => t.id !== toast.id)" class="ml-2 text-white/80 hover:text-white">&times;</button>
            </div>
        </template>
    </div>

    {{-- Confirmation Modal --}}
    <div x-show="showConfirm"
        x-transition:enter="transition ease-out duration-200"
        x-transition:enter-start="opacity-0"
        x-transition:enter-end="opacity-100"
        x-transition:leave="transition ease-in duration-150"
        x-transition:leave-start="opacity-100"
        x-transition:leave-end="opacity-0"
        class="fixed inset-0 z-[90] flex items-center justify-center bg-black/60"
        x-cloak
    >
        <div x-show="showConfirm"
            x-transition:enter="transition ease-out duration-200"
            x-transition:enter-start="scale-95 opacity-0"
            x-transition:enter-end="scale-100 opacity-100"
            x-transition:leave="transition ease-in duration-150"
            x-transition:leave-start="scale-100 opacity-100"
            x-transition:leave-end="scale-95 opacity-0"
            @click.away="showConfirm = false"
            class="bg-white dark:bg-neutral-800 rounded-xl shadow-2xl max-w-md w-full mx-4 p-6 border border-gray-200 dark:border-neutral-700"
        >
            <div class="mb-4">
                <h3 class="text-lg font-semibold text-gray-900 dark:text-white" x-text="confirmTitle"></h3>
                <p class="mt-2 text-sm text-gray-600 dark:text-gray-300" x-text="confirmMessage"></p>
            </div>
            <div class="flex justify-end gap-3">
                <button @click="showConfirm = false"
                    class="px-4 py-2 text-sm font-medium text-gray-700 bg-gray-200 rounded-lg hover:bg-gray-300 dark:bg-neutral-700 dark:text-gray-200 dark:hover:bg-neutral-600 transition">
                    Cancel
                </button>
                <button @click="executeConfirm()"
                    :class="confirmButtonClass || 'bg-red-600 hover:bg-red-700'"
                    class="px-4 py-2 text-sm font-medium text-white rounded-lg transition">
                    Confirm
                </button>
            </div>
        </div>
    </div>

    {{-- User Detail Modal --}}
    @if($showUserModal && $modalUser)
    <div class="fixed inset-0 z-[80] flex items-center justify-center bg-black/60"
        x-data="{}"
        wire:key="user-modal-{{ $modalUser->id }}"
    >
        <div class="bg-white dark:bg-neutral-800 rounded-xl shadow-2xl max-w-2xl w-full mx-4 max-h-[85vh] overflow-y-auto border border-gray-200 dark:border-neutral-700"
            @click.away="$wire.closeModal()"
        >
            {{-- Modal Header --}}
            <div class="sticky top-0 bg-white dark:bg-neutral-800 border-b border-gray-200 dark:border-neutral-700 px-6 py-4 flex items-center justify-between z-10 rounded-t-xl">
                <h2 class="text-xl font-bold text-gray-900 dark:text-white flex items-center gap-3">
                    <img src="{{ $modalUser->getAvatar() }}" alt="{{ $modalUser->name }}" class="w-10 h-10 rounded-full object-cover">
                    {{ $modalUser->name }}
                </h2>
                <button wire:click="closeModal" class="text-gray-400 hover:text-gray-600 dark:hover:text-white transition">
                    <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/></svg>
                </button>
            </div>

            {{-- Modal Body --}}
            <div class="px-6 py-4 space-y-6">
                {{-- User Info Grid --}}
                <div class="grid grid-cols-2 gap-4">
                    <div>
                        <dt class="text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">User ID</dt>
                        <dd class="mt-1 text-sm text-gray-900 dark:text-white font-mono">#{{ $modalUser->id }}</dd>
                    </div>
                    <div>
                        <dt class="text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">Email</dt>
                        <dd class="mt-1 text-sm text-gray-900 dark:text-white">{{ $modalUser->email ?? 'n/a' }}</dd>
                    </div>
                    <div>
                        <dt class="text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">Discord ID</dt>
                        <dd class="mt-1 text-sm text-gray-900 dark:text-white font-mono">{{ $modalUser->discord_id ?? 'n/a' }}</dd>
                    </div>
                    <div>
                        <dt class="text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">Registered</dt>
                        <dd class="mt-1 text-sm text-gray-900 dark:text-white">{{ $modalUser->created_at->format('Y-m-d H:i') }}</dd>
                    </div>
                    <div>
                        <dt class="text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">Last Updated</dt>
                        <dd class="mt-1 text-sm text-gray-900 dark:text-white">{{ $modalUser->updated_at->format('Y-m-d H:i') }}</dd>
                    </div>
                    <div>
                        <dt class="text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">Comments</dt>
                        <dd class="mt-1 text-sm text-gray-900 dark:text-white">{{ $modalUser->commentCount() }}</dd>
                    </div>
                </div>

                {{-- Roles --}}
                <div>
                    <dt class="text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider mb-2">Roles</dt>
                    <dd class="flex flex-wrap gap-2">
                        @php $roleLabels = [
                            \App\Enums\UserRole::ADMINISTRATOR->value => ['bg-purple-600 text-white', 'Admin'],
                            \App\Enums\UserRole::MODERATOR->value => ['bg-blue-600 text-white', 'Moderator'],
                            \App\Enums\UserRole::SUPPORTER->value => ['bg-pink-600 text-white', 'Patreon'],
                            \App\Enums\UserRole::BANNED->value => ['bg-red-600 text-white', 'Banned'],
                        ]; @endphp
                        @foreach($roleLabels as $role => $classes)
                            @if($modalUser->hasRole(\App\Enums\UserRole::from($role)))
                                <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium {{ $classes[0] }}">{{ $classes[1] }}</span>
                            @endif
                        @endforeach
                        @if(empty($modalUser->roles))
                            <span class="text-sm text-gray-400 dark:text-gray-500">No special roles</span>
                        @endif
                    </dd>
                </div>

                {{-- Modal Actions --}}
                <div class="flex flex-wrap gap-2 pt-2 border-t border-gray-200 dark:border-neutral-700">
                    @if($modalUser->hasRole(\App\Enums\UserRole::BANNED))
                        <button wire:click="unbanUser({{ $modalUser->id }})"
                            class="px-3 py-1.5 text-xs font-medium bg-green-600 text-white rounded-lg hover:bg-green-700 transition">
                            Unban User
                        </button>
                    @else
                        <button wire:click="banUser({{ $modalUser->id }})"
                            class="px-3 py-1.5 text-xs font-medium bg-rose-600 text-white rounded-lg hover:bg-rose-700 transition">
                            Ban User
                        </button>
                    @endif

                    @if($modalUser->hasRole(\App\Enums\UserRole::MODERATOR))
                        <button wire:click="revokeModerator({{ $modalUser->id }})"
                            class="px-3 py-1.5 text-xs font-medium bg-amber-600 text-white rounded-lg hover:bg-amber-700 transition">
                            Revoke Moderator
                        </button>
                    @else
                        <button wire:click="grantModerator({{ $modalUser->id }})"
                            class="px-3 py-1.5 text-xs font-medium bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition">
                            Grant Moderator
                        </button>
                    @endif

                    <button wire:click="deleteUserComments({{ $modalUser->id }})"
                        class="px-3 py-1.5 text-xs font-medium bg-red-600 text-white rounded-lg hover:bg-red-700 transition">
                        Delete All Comments
                    </button>
                </div>

                {{-- Recent Comments --}}
                @if($modalUserComments->isNotEmpty())
                <div class="pt-2 border-t border-gray-200 dark:border-neutral-700">
                    <h4 class="text-sm font-semibold text-gray-900 dark:text-white mb-3">Recent Comments (last {{ $modalUserComments->count() }})</h4>
                    <div class="space-y-2 max-h-48 overflow-y-auto">
                        @foreach($modalUserComments as $comment)
                            <div class="bg-gray-50 dark:bg-neutral-900 rounded-lg px-3 py-2 text-sm text-gray-700 dark:text-gray-300">
                                <p class="line-clamp-2">{{ $comment->body }}</p>
                                <span class="text-xs text-gray-400 dark:text-gray-500 mt-1 block">{{ $comment->created_at->diffForHumans() }}</span>
                            </div>
                        @endforeach
                    </div>
                </div>
                @endif
            </div>

            {{-- Modal Footer --}}
            <div class="sticky bottom-0 bg-gray-50 dark:bg-neutral-900 border-t border-gray-200 dark:border-neutral-700 px-6 py-3 rounded-b-xl flex justify-end">
                <button wire:click="closeModal"
                    class="px-4 py-2 text-sm font-medium text-gray-700 bg-gray-200 rounded-lg hover:bg-gray-300 dark:bg-neutral-700 dark:text-gray-200 dark:hover:bg-neutral-600 transition">
                    Close
                </button>
            </div>
        </div>
    </div>
    @endif

    {{-- Main Table Area --}}
    <div class="flex justify-center">
        <div class="w-full xl:max-w-[95%] 2xl:max-w-[90%]">
            {{-- Filter Bar --}}
            <div class="bg-white dark:bg-neutral-800 rounded-lg border border-gray-200 dark:border-neutral-700 p-4 mb-4">
                <div class="grid grid-cols-1 md:grid-cols-3 lg:grid-cols-5 gap-3 mb-3">
                    <div>
                        <label class="block text-xs font-medium text-gray-500 dark:text-gray-400 uppercase mb-1">Username</label>
                        <input wire:model.live.debounce.400ms="search" type="search"
                            class="w-full h-9 text-sm text-gray-900 border border-gray-300 rounded-lg bg-gray-50 focus:ring-rose-500 focus:border-rose-600 dark:bg-neutral-900 dark:border-neutral-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-rose-500 dark:focus:border-rose-600 px-3"
                            placeholder="Search username...">
                    </div>
                    <div>
                        <label class="block text-xs font-medium text-gray-500 dark:text-gray-400 uppercase mb-1">Discord ID</label>
                        <input wire:model.live.debounce.400ms="discordId" type="search"
                            class="w-full h-9 text-sm text-gray-900 border border-gray-300 rounded-lg bg-gray-50 focus:ring-rose-500 focus:border-rose-600 dark:bg-neutral-900 dark:border-neutral-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-rose-500 dark:focus:border-rose-600 px-3"
                            placeholder="Discord ID...">
                    </div>
                    <div>
                        <label class="block text-xs font-medium text-gray-500 dark:text-gray-400 uppercase mb-1">Email</label>
                        <input wire:model.live.debounce.400ms="email" type="search"
                            class="w-full h-9 text-sm text-gray-900 border border-gray-300 rounded-lg bg-gray-50 focus:ring-rose-500 focus:border-rose-600 dark:bg-neutral-900 dark:border-neutral-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-rose-500 dark:focus:border-rose-600 px-3"
                            placeholder="Search email...">
                    </div>
                    <div>
                        <label class="block text-xs font-medium text-gray-500 dark:text-gray-400 uppercase mb-1">Role Filter</label>
                        <div class="flex flex-wrap gap-1.5">
                            @foreach([
                                'admin' => 'Admin',
                                'moderator' => 'Moderator',
                                'supporter' => 'Supporter',
                                'banned' => 'Banned',
                            ] as $val => $label)
                                <label class="inline-flex items-center gap-1 text-xs cursor-pointer">
                                    <input type="checkbox" wire:model.live="roleFilter" value="{{ $val }}"
                                        class="w-3.5 h-3.5 text-rose-600 bg-gray-100 border-gray-300 rounded focus:ring-rose-500 dark:bg-gray-700 dark:border-gray-600">
                                    <span class="text-gray-700 dark:text-gray-300">{{ $label }}</span>
                                </label>
                            @endforeach
                        </div>
                    </div>
                    <div class="flex items-end gap-2">
                        <button wire:click="clearFilters"
                            class="h-9 px-3 text-xs font-medium text-gray-600 bg-gray-200 rounded-lg hover:bg-gray-300 dark:bg-neutral-700 dark:text-gray-200 dark:hover:bg-neutral-600 transition">
                            Clear Filters
                        </button>
                    </div>
                </div>

                {{-- Per-page and bulk actions bar --}}
                <div class="flex items-center justify-between flex-wrap gap-2">
                    <div class="flex items-center gap-2">
                        <label class="text-xs text-gray-500 dark:text-gray-400">Show</label>
                        <select wire:model.live="perPage"
                            class="h-8 text-xs border border-gray-300 rounded-lg bg-gray-50 focus:ring-rose-500 focus:border-rose-600 dark:bg-neutral-900 dark:border-neutral-600 dark:text-white px-2">
                            <option value="10">10</option>
                            <option value="20">20</option>
                            <option value="50">50</option>
                            <option value="100">100</option>
                        </select>
                        <span class="text-xs text-gray-500 dark:text-gray-400">per page</span>
                    </div>

                    {{-- Bulk Actions --}}
                    @if(count($selected) > 0)
                    <div class="flex items-center gap-2">
                        <span class="text-xs text-gray-500 dark:text-gray-400">{{ count($selected) }} selected</span>
                        <button @click="openConfirm('Ban Selected Users', 'Are you sure you want to ban ' + {{ count($selected) }} + ' user(s)?', 'bg-rose-600 hover:bg-rose-700', () => $wire.bulkBan())"
                            class="h-8 px-3 text-xs font-medium bg-rose-600 text-white rounded-lg hover:bg-rose-700 transition">
                            Ban Selected
                        </button>
                        <button @click="openConfirm('Unban Selected Users', 'Are you sure you want to unban ' + {{ count($selected) }} + ' user(s)?', 'bg-green-600 hover:bg-green-700', () => $wire.bulkUnban())"
                            class="h-8 px-3 text-xs font-medium bg-green-600 text-white rounded-lg hover:bg-green-700 transition">
                            Unban Selected
                        </button>
                        <button @click="openConfirm('Delete Comments', 'Are you sure you want to delete ALL comments from ' + {{ count($selected) }} + ' user(s)? This cannot be undone.', 'bg-red-600 hover:bg-red-700', () => $wire.bulkDeleteComments())"
                            class="h-8 px-3 text-xs font-medium bg-red-600 text-white rounded-lg hover:bg-red-700 transition">
                            Delete Selected Comments
                        </button>
                    </div>
                    @endif
                </div>
            </div>

            {{-- Table --}}
            <div class="relative overflow-x-auto rounded-lg border border-gray-200 dark:border-neutral-700">
                <table class="w-full text-sm text-left rtl:text-right text-gray-500 dark:text-white">
                    <thead class="text-xs text-gray-700 uppercase bg-gray-50 dark:bg-pink-700 dark:text-neutral-200">
                        <tr>
                            <th scope="col" class="px-4 py-3 w-10">
                                <input type="checkbox" wire:model.live="selectPage"
                                    class="w-4 h-4 text-rose-600 bg-gray-100 border-gray-300 rounded focus:ring-rose-500 dark:bg-gray-700 dark:border-gray-600">
                            </th>
                            @foreach([
                                'id' => 'ID',
                                'discord_id' => 'Discord ID',
                                'name' => 'Username',
                                'email' => 'Email',
                                'created_at' => 'Registered',
                                'updated_at' => 'Updated',
                            ] as $field => $label)
                                <th scope="col" class="px-4 py-3 cursor-pointer select-none hover:bg-pink-800/50 transition"
                                    wire:click="sortBy('{{ $field }}')">
                                    <div class="flex items-center gap-1 whitespace-nowrap">
                                        {{ $label }}
                                        @if($sortField === $field)
                                            <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                @if($sortDirection === 'asc')
                                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 15l7-7 7 7"/>
                                                @else
                                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"/>
                                                @endif
                                            </svg>
                                        @endif
                                    </div>
                                </th>
                            @endforeach
                            <th scope="col" class="px-4 py-3">Roles</th>
                            <th scope="col" class="px-4 py-3">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        @forelse($users as $user)
                        <tr wire:key="user-{{ $user->id }}"
                            class="bg-white border-t dark:bg-neutral-800 dark:border-pink-700 hover:bg-gray-50 dark:hover:bg-neutral-750 transition">
                            <td class="px-4 py-3">
                                <input type="checkbox" wire:model.live="selected" value="{{ $user->id }}"
                                    class="w-4 h-4 text-rose-600 bg-gray-100 border-gray-300 rounded focus:ring-rose-500 dark:bg-gray-700 dark:border-gray-600">
                            </td>
                            <td class="px-4 py-3 font-mono text-xs">{{ $user->id }}</td>
                            <td class="px-4 py-3 font-mono text-xs">{{ $user->discord_id ?? 'n/a' }}</td>
                            <td class="px-4 py-3">
                                <button wire:click="viewUser({{ $user->id }})"
                                    class="font-medium text-blue-600 dark:text-blue-400 hover:underline flex items-center gap-2">
                                    <img src="{{ $user->getAvatar() }}" alt="" class="w-6 h-6 rounded-full object-cover">
                                    {{ $user->name }}
                                </button>
                            </td>
                            <td class="px-4 py-3 text-xs">{{ $user->email ?? 'n/a' }}</td>
                            <td class="px-4 py-3 text-xs whitespace-nowrap">{{ $user->created_at->format('Y-m-d') }}</td>
                            <td class="px-4 py-3 text-xs whitespace-nowrap">{{ $user->updated_at->format('Y-m-d') }}</td>
                            <td class="px-4 py-3">
                                <div class="flex flex-wrap gap-1">
                                    @if($user->hasRole(\App\Enums\UserRole::ADMINISTRATOR))
                                        <span class="inline-flex items-center px-1.5 py-0.5 rounded text-[10px] font-medium bg-purple-600 text-white">Admin</span>
                                    @endif
                                    @if($user->hasRole(\App\Enums\UserRole::MODERATOR))
                                        <span class="inline-flex items-center px-1.5 py-0.5 rounded text-[10px] font-medium bg-blue-600 text-white">Mod</span>
                                    @endif
                                    @if($user->hasRole(\App\Enums\UserRole::SUPPORTER))
                                        <span class="inline-flex items-center px-1.5 py-0.5 rounded text-[10px] font-medium bg-pink-600 text-white">Supp.</span>
                                    @endif
                                    @if($user->hasRole(\App\Enums\UserRole::BANNED))
                                        <span class="inline-flex items-center px-1.5 py-0.5 rounded text-[10px] font-medium bg-red-600 text-white">Banned</span>
                                    @endif
                                </div>
                            </td>
                            <td class="px-4 py-3">
                                <div class="flex flex-wrap gap-1">
                                    @if($user->hasRole(\App\Enums\UserRole::BANNED))
                                        <button wire:click="unbanUser({{ $user->id }})"
                                            class="inline-block rounded bg-green-600 px-2 py-1 text-[10px] font-medium uppercase leading-normal text-white hover:bg-green-700 transition">
                                            Unban
                                        </button>
                                    @else
                                        <button wire:click="banUser({{ $user->id }})"
                                            class="inline-block rounded bg-rose-600 px-2 py-1 text-[10px] font-medium uppercase leading-normal text-white hover:bg-rose-700 transition">
                                            Ban
                                        </button>
                                    @endif

                                    @if($user->hasRole(\App\Enums\UserRole::MODERATOR))
                                        <button @click="openConfirm('Revoke Moderator', 'Are you sure you want to revoke moderator role from {{ addslashes($user->name) }}?', 'bg-amber-600 hover:bg-amber-700', () => $wire.revokeModerator({{ $user->id }}))"
                                            class="inline-block rounded bg-amber-600 px-2 py-1 text-[10px] font-medium uppercase leading-normal text-white hover:bg-amber-700 transition">
                                            Revoke Mod
                                        </button>
                                    @else
                                        <button wire:click="grantModerator({{ $user->id }})"
                                            class="inline-block rounded bg-blue-600 px-2 py-1 text-[10px] font-medium uppercase leading-normal text-white hover:bg-blue-700 transition">
                                            Grant Mod
                                        </button>
                                    @endif

                                    <button @click="openConfirm('Delete Comments', 'Are you sure you want to delete ALL comments from {{ addslashes($user->name) }}? This cannot be undone.', 'bg-red-600 hover:bg-red-700', () => $wire.deleteUserComments({{ $user->id }}))"
                                        class="inline-block rounded bg-red-600 px-2 py-1 text-[10px] font-medium uppercase leading-normal text-white hover:bg-red-700 transition">
                                        Del Comments
                                    </button>
                                </div>
                            </td>
                        </tr>
                        @empty
                        <tr class="bg-white dark:bg-neutral-800">
                            <td colspan="9" class="px-6 py-12 text-center text-gray-500 dark:text-gray-400">
                                <svg class="w-12 h-12 mx-auto mb-3 text-gray-300 dark:text-gray-600" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"/></svg>
                                <p class="text-sm">No users found matching your filters.</p>
                            </td>
                        </tr>
                        @endforelse
                    </tbody>
                </table>
            </div>

            {{-- Pagination --}}
            <div class="mt-4 flex items-center justify-between">
                <div class="text-xs text-gray-500 dark:text-gray-400">
                    @if($users->total() > 0)
                        Showing {{ $users->firstItem() }} to {{ $users->lastItem() }} of {{ $users->total() }} users
                    @endif
                </div>
                <div class="flex items-center gap-1">
                    {{ $users->links('pagination::tailwind') }}
                </div>
            </div>
        </div>
    </div>
</div>