@extends('admin.layouts.app')

@section('content')
<div x-data="membersPage()" class="space-y-6">
    <div class="dark-card">
        <div class="px-6 py-4 flex items-center justify-between border-b border-gray-700">
            <div>
                <h1 class="text-2xl font-bold text-white">{{ trans('members.manage_members') }}</h1>
                <p class="text-gray-400 mt-1">Manage user accounts and balances</p>
            </div>

            <div class="flex items-center space-x-4">
                <div class="relative">
                    <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                        <i class="fas fa-search text-gray-400"></i>
                    </div>
                    <input x-model.debounce.300="query" @input="search()" id="search" type="text" class="pl-10 pr-4 py-2 w-64" placeholder="{{ trans('members.fields.search.placeholder') }}">
                </div>

        <div class="p-6">
            <template x-if="users.length">
                <div class="overflow-x-auto">
                    <table class="min-w-full">
                        <thead>
                            <tr>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-300 uppercase tracking-wider">{{ trans('members.table.id') }}</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-300 uppercase tracking-wider">{{ trans('members.table.name') }}</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-300 uppercase tracking-wider">{{ trans('members.table.balance') }}</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-300 uppercase tracking-wider">{{ trans('members.table.role') }}</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-300 uppercase tracking-wider">{{ trans('members.table.actions') }}</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-gray-700">
                            <template x-for="user in users" :key="user.ID">
                                <tr class="hover:bg-gray-700/50 transition-colors">
                                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-300" x-text="user.ID"></td>
                                    <td class="px-6 py-4 whitespace-nowrap">
                                        <div class="flex items-center">
                                            <div class="w-10 h-10 rounded-lg flex items-center justify-center mr-3" style="background: linear-gradient(135deg, #6366f1, #8b5cf6);">
                                                <i class="fas fa-user text-white text-sm"></i>
                                            </div>
                                            <div>
                                                <div class="text-sm font-medium text-white" x-text="user.name"></div>
                                                <div class="text-sm text-gray-400">ID: <span x-text="user.ID"></span></div>
                                    </td>
                                    <td class="px-6 py-4 whitespace-nowrap">
                                        <span class="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium bg-green-100 text-green-700">
                                            <i class="fas fa-coins mr-1"></i><span x-text="user.money_formatted"></span>
                                        </span>
                                    </td>
                                    <td class="px-6 py-4 whitespace-nowrap">
                                        <span class="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium bg-indigo-100 text-indigo-700" x-text="user.role"></span>
                                    </td>
                                    <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                                        <button @click.prevent="openModal(user)" class="inline-flex items-center px-3 py-1 rounded-md bg-indigo-600 text-white">
                                            <i class="fas fa-plus mr-2"></i> {{ trans('members.actions.give', ['currency' => settings('currency_name')]) }}
                                        </button>
                                    </td>
                                </tr>
                            </template>
                        </tbody>
                    </table>
                </div>
            </template>

            <template x-if="!users.length">
                <div class="text-center py-12 text-gray-400">
                    <div class="w-24 h-24 mx-auto mb-6 bg-gray-700 rounded-full flex items-center justify-center">
                        <i class="fas fa-users text-4xl"></i>
                    </div>
                    <h3 class="text-xl font-semibold text-white mb-2">No members found</h3>
                    <p>No user accounts match your search.</p>
                </div>
            </template>

            <!-- Pagination: keep server-side pagination links (works when not searching) -->
            <div class="mt-6" x-show="!query">
                {!! $users->links() !!}
            </div>

    <!-- Balance Modal -->
    <div x-show="modalOpen" x-cloak class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
        <div class="dark-card max-w-md w-full mx-4" @click.away="closeModal()">
            <div class="px-6 py-4 border-b border-gray-700 flex items-center justify-between">
                <h3 class="text-lg font-semibold text-white" x-text="modalTitle">Add Balance</h3>
                <button @click="closeModal()" class="text-gray-400 hover:text-white"><i class="fas fa-times"></i></button>
            </div>
            <form :action="balanceAction" method="post" class="p-6">
                {!! csrf_field() !!}
                <div class="mb-6">
                    <label for="amount" class="block text-sm font-medium text-gray-300 mb-2">{{ trans('members.fields.amount.label') }}</label>
                    <input name="amount" type="number" step="0.01" class="w-full" id="amount" placeholder="Enter amount..." required>
                </div>
                <div class="flex justify-end space-x-3">
                    <button type="button" @click="closeModal()" class="px-3 py-2 rounded-md bg-gray-600 text-white">{{ trans('members.modal.close') }}</button>
                    <button type="submit" class="px-3 py-2 rounded-md bg-indigo-600 text-white">{{ trans('members.modal.submit') }}</button>
                </div>
            </form>
        </div>

@push('scripts')
<script>
function membersPage() {
    return {
        query: '',
        users: @json($users->map(function($u){ return ['ID'=>$u->ID,'name'=>$u->name,'money'=>$u->money,'money_formatted'=>number_format($u->money),'role'=>$u->role]; })->values()),
        modalOpen: false,
        modalTitle: '',
        balanceAction: '',
        searchTimer: null,
        openModal(user) {
            this.modalTitle = `Add {{ settings('currency_name') }} to ${user.name}`;
            this.balanceAction = `{{ url('admin/members/balance') }}/${user.ID}`;
            this.modalOpen = true;
        },
        closeModal() {
            this.modalOpen = false;
            document.getElementById('amount') && (document.getElementById('amount').value = '');
        },
        search() {
            // Debounce already handled by x-model.debounce; keep small guard and do fetch
            if (this.query.length === 0) {
                // restore initial page set
                this.users = @json($users->map(function($u){ return ['ID'=>$u->ID,'name'=>$u->name,'money'=>$u->money,'money_formatted'=>number_format($u->money),'role'=>$u->role]; })->values());
                return;
            }

            // Use server search endpoint for large datasets for accurate results
            fetch('{{ url('admin/members/search') }}', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': '{{ csrf_token() }}' },
                body: JSON.stringify({ search_query: this.query })
            })
            .then(r => r.json())
            .then(data => {
                this.users = data.map(u => ({
                    ID: u.ID,
                    name: u.name,
                    money: u.money,
                    money_formatted: Number(u.money).toLocaleString(),
                    role: u.role
                }));
            })
            .catch(err => console.error(err));
        }
    }
}
</script>
@endpush

@endsection