<x-app-layout>
    <div class="flex h-[90vh]">
        <div class="w-1/3 border-r p-4 overflow-y-auto bg-white">
            <h2 class="font-bold mb-2">
                {{ Auth::user()->hasRole('GuruBK') ? 'Daftar Siswa' : 'Daftar GuruBK' }}
            </h2>

            @role('GuruBK')
            <div class="p-4">
                <input type="text" id="searchUser" placeholder="Cari siswa..."
                    class="w-full px-3 py-2 border rounded focus:outline-none focus:ring focus:border-blue-300">
            </div>
            @endrole

            <div id="userList" class="space-y-1">
                @foreach($users as $user)
                <a href="{{ route('chat.index', $user->id) }}"
                    class="flex items-center gap-3 px-4 py-2 rounded hover:bg-gray-200 {{ $receiver && $receiver->id === $user->id ? 'bg-purple-100' : '' }}">
                    <div class="w-8 h-8 flex items-center justify-center rounded-full bg-purple-500 text-white font-semibold">
                        {{ strtoupper(substr($user->name, 0, 1)) }}
                    </div>
                    <span class="user-name">{{ $user->name }}</span>
                </a>
                <hr>
                @endforeach
            </div>
        </div>

        <div class="w-2/3 p-4">
            @if ($receiver)
            @include('partials.chat-box', ['chats' => $chats, 'receiver' => $receiver])
            @else
            <div class="text-center text-gray-500 mt-20">
                <p>
                    <!-- Pilih {{ Auth::user()->role === 'spesialis' ? 'siswa' : 'spesialis' }} untuk memulai percakapan. -->
                    Pilih {{ Auth::user()->hasRole('GuruBK') ? 'Siswa / Spesialis' : (Auth::user()->hasRole('Spesialis') ? 'GuruBK' : 'GuruBK') }} untuk memulai percakapan.
                </p>
            </div>
            @endif
        </div>
    </div>
</x-app-layout>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        const searchInput = document.getElementById('searchUser');
        const userList = document.getElementById('userList');

        if (searchInput && userList) {
            searchInput.addEventListener('input', function() {
                const query = this.value.toLowerCase();
                const items = userList.querySelectorAll('a');

                items.forEach(item => {
                    const name = item.querySelector('.user-name').textContent.toLowerCase();
                    item.style.display = name.includes(query) ? 'flex' : 'none';
                });
            });
        }
    });
</script>