<x-filament-panels::page>
    @php
        $chats = $this->chats;
        $activeChat = $this->activeChat;
    @endphp

    <div class="w-full bg-gray-950/90 rounded-3xl border border-gray-800/80 shadow-2xl overflow-hidden p-2 sm:p-3 h-[calc(100vh-9.5rem)] min-h-[640px] text-sm">
        <div class="flex flex-col lg:flex-row h-full w-full gap-3 overflow-hidden">

            <!-- COLUMNA IZQUIERDA: LISTA DE MENSAJES (ESTILO REFERENCE DESIGN) -->
            <div class="w-full lg:w-96 flex flex-col bg-gray-900/90 rounded-2xl border border-gray-800/80 overflow-hidden flex-shrink-0">
                
                <!-- Buscador de Chats (Pill Shape) -->
                <div class="p-4 border-b border-gray-800/80 space-y-3 bg-gray-900/60">
                    <div class="relative">
                        <div class="absolute inset-y-0 left-0 pl-3.5 flex items-center pointer-events-none text-gray-500">
                            🔍
                        </div>
                        <input 
                            type="text" 
                            wire:model.live.debounce.300ms="searchQuery" 
                            placeholder="Buscar cliente, correo o tel..." 
                            class="w-full bg-gray-950/90 border border-gray-800 text-gray-200 placeholder-gray-500 text-xs rounded-full pl-9 pr-4 py-2.5 focus:outline-none focus:border-amber-500/50 transition-all shadow-inner"
                        />
                    </div>

                    <!-- Título & Filtros -->
                    <div class="flex items-center justify-between pt-1">
                        <h2 class="font-black text-gray-100 text-base tracking-tight flex items-center gap-2">
                            Conversaciones
                        </h2>
                        <div class="flex items-center gap-1 bg-gray-950 p-1 rounded-full border border-gray-800 text-[11px]">
                            <button 
                                wire:click="setFilterStatus('all')" 
                                class="px-2.5 py-0.5 rounded-full font-bold transition-all {{ $filterStatus === 'all' ? 'bg-amber-500/20 text-amber-300 border border-amber-500/30' : 'text-gray-400 hover:text-gray-200' }}"
                            >
                                Todos
                            </button>
                            <button 
                                wire:click="setFilterStatus('open')" 
                                class="px-2.5 py-0.5 rounded-full font-bold transition-all {{ $filterStatus === 'open' ? 'bg-emerald-500/20 text-emerald-300 border border-emerald-500/30' : 'text-gray-400 hover:text-gray-200' }}"
                            >
                                🟢
                            </button>
                            <button 
                                wire:click="setFilterStatus('closed')" 
                                class="px-2.5 py-0.5 rounded-full font-bold transition-all {{ $filterStatus === 'closed' ? 'bg-gray-800 text-gray-300' : 'text-gray-400 hover:text-gray-200' }}"
                            >
                                ⚪
                            </button>
                        </div>
                    </div>
                </div>

                <!-- Hilo de Conversaciones -->
                <div class="flex-1 overflow-y-auto p-2 space-y-1.5 custom-scrollbar">
                    @forelse($chats as $c)
                        @php
                            $isSelected = $selectedChatId === $c->id;
                            $unread = $c->unread_count;
                            $latest = $c->latestMessage;
                        @endphp
                        <div 
                            wire:click="selectChat({{ $c->id }})" 
                            class="p-3 rounded-2xl cursor-pointer transition-all flex items-center gap-3 border {{ $isSelected ? 'bg-gray-800/90 border-amber-500/40 shadow-lg' : 'bg-gray-950/40 hover:bg-gray-800/40 border-transparent' }}"
                        >
                            <!-- Avatar con punto verde -->
                            <div class="relative flex-shrink-0">
                                <div class="w-11 h-11 rounded-full bg-gradient-to-br from-amber-500/20 to-yellow-600/30 text-amber-300 font-black flex items-center justify-center border border-amber-500/30 text-sm shadow-md">
                                    {{ strtoupper(substr($c->user->name ?? 'U', 0, 1)) }}
                                </div>
                                <span class="absolute bottom-0 right-0 w-3 h-3 rounded-full border-2 border-gray-900 {{ $c->status === 'open' ? 'bg-emerald-500' : 'bg-gray-500' }}"></span>
                            </div>

                            <!-- Info Nombre & Mensaje -->
                            <div class="flex-1 min-w-0">
                                <div class="flex items-center justify-between mb-0.5">
                                    <h3 class="font-bold text-gray-100 truncate text-xs">
                                        {{ $c->user->name ?? 'Usuario Desconocido' }}
                                    </h3>
                                    <span class="text-[10px] text-gray-400 flex-shrink-0 ml-1">
                                        {{ $c->last_message_at ? $c->last_message_at->format('H:i') : '' }}
                                    </span>
                                </div>
                                
                                <p class="text-[11px] {{ $unread > 0 ? 'text-amber-300 font-semibold' : 'text-gray-400' }} truncate">
                                    {{ $latest ? $latest->message : 'Sin mensajes aún' }}
                                </p>
                            </div>

                            <!-- Unread Pill -->
                            @if($unread > 0)
                                <span class="px-2 py-0.5 text-[10px] font-black bg-amber-500 text-gray-950 rounded-full flex-shrink-0 shadow-md animate-pulse">
                                    {{ $unread }}
                                </span>
                            @endif
                        </div>
                    @empty
                        <div class="p-8 text-center text-gray-500 text-xs">
                            Sin chats registrados en esta vista.
                        </div>
                    @endforelse
                </div>
            </div>

            <!-- COLUMNA DERECHA: HILO DE CHAT ACTIVO -->
            <div class="flex-1 flex flex-col bg-gray-900/90 rounded-2xl border border-gray-800/80 overflow-hidden">
                @if($activeChat)
                    <!-- Header Superior del Chat -->
                    <div class="p-3.5 px-5 border-b border-gray-800 flex items-center justify-between bg-gray-950/70 flex-shrink-0">
                        <div class="flex items-center gap-3">
                            <div class="relative">
                                <div class="w-11 h-11 rounded-full bg-gradient-to-br from-amber-500/20 to-yellow-600/30 text-amber-300 font-black flex items-center justify-center border border-amber-500/40 text-base shadow-md">
                                    {{ strtoupper(substr($activeChat->user->name ?? 'U', 0, 1)) }}
                                </div>
                                <span class="absolute bottom-0 right-0 w-3 h-3 rounded-full border-2 border-gray-900 {{ $activeChat->status === 'open' ? 'bg-emerald-500' : 'bg-gray-500' }}"></span>
                            </div>
                            <div>
                                <h3 class="font-extrabold text-gray-100 text-sm flex items-center gap-2">
                                    {{ $activeChat->user->name ?? 'Cliente' }}
                                </h3>
                                <div class="flex items-center gap-2 text-xs text-gray-400">
                                    <span class="text-emerald-400 font-semibold flex items-center gap-1 text-[11px]">
                                        ● En Línea
                                    </span>
                                    <span>•</span>
                                    <span class="text-gray-400 text-[11px]">{{ $activeChat->user->email }}</span>
                                    @if($activeChat->user->phone)
                                        <span>•</span>
                                        <span class="text-gray-400 text-[11px]">📞 {{ $activeChat->user->phone }}</span>
                                    @endif
                                </div>
                            </div>
                        </div>

                        <!-- Botón de Estado -->
                        <button 
                            wire:click="toggleChatStatus" 
                            class="px-4 py-2 rounded-full text-xs font-bold border transition-all shadow-md flex items-center gap-1.5 {{ $activeChat->status === 'open' ? 'bg-red-500/10 text-red-400 border-red-500/30 hover:bg-red-500/20' : 'bg-emerald-500/10 text-emerald-400 border-emerald-500/30 hover:bg-emerald-500/20' }}"
                        >
                            @if($activeChat->status === 'open')
                                🔒 Cerrar Chat
                            @else
                                🔓 Reabrir Chat
                            @endif
                        </button>
                    </div>

                    <!-- Tarjeta Informativa del Cliente (Estilo Widget Referencia) -->
                    <div class="px-5 py-2.5 bg-gray-950/60 border-b border-gray-800/80 flex items-center justify-between text-xs flex-shrink-0">
                        <div class="flex items-center gap-4 text-gray-300">
                            <div>
                                <span class="text-gray-500 text-[10px] block uppercase font-bold">Cédula</span>
                                <span class="font-semibold text-gray-200">{{ $activeChat->user->cedula ?? 'No registrada' }}</span>
                            </div>
                            <div class="h-6 w-[1px] bg-gray-800"></div>
                            <div>
                                <span class="text-gray-500 text-[10px] block uppercase font-bold">Saldo Billetera</span>
                                <span class="font-black text-amber-400">₡{{ number_format($activeChat->user->wallet_balance ?? 0, 0, ',', '.') }}</span>
                            </div>
                        </div>
                        <div class="text-right">
                            <span class="text-gray-500 text-[10px] block uppercase font-bold">ID Cliente</span>
                            <span class="font-mono text-gray-400">#{{ $activeChat->user->id }}</span>
                        </div>
                    </div>

                    <!-- Hilo de Mensajes con Burbujas Modernas -->
                    <div 
                        wire:poll.4s 
                        id="chat-messages-body" 
                        class="flex-1 overflow-y-auto p-5 space-y-4 bg-gray-950/80 custom-scrollbar"
                    >
                        @forelse($activeChat->messages as $msg)
                            @php
                                $isUser = $msg->sender_type === 'user';
                                $isBot = $msg->sender_type === 'bot';
                            @endphp

                            @if($isBot)
                                <!-- Mensaje Bot -->
                                <div class="flex justify-center my-3">
                                    <div class="bg-gray-900 border border-gray-800 text-amber-400 text-xs py-2 px-4 rounded-full flex items-center gap-2 shadow-md">
                                        <span>🤖</span>
                                        <span class="font-medium">{{ $msg->message }}</span>
                                        <span class="text-[10px] text-gray-500 ml-1">{{ $msg->created_at->format('H:i') }}</span>
                                    </div>
                                </div>
                            @elseif($isUser)
                                <!-- Mensaje Cliente (Izquierda - Tarjeta Oscura) -->
                                <div class="flex flex-col items-start max-w-[80%] space-y-1">
                                    <div class="flex items-center gap-2 px-1">
                                        <span class="text-[11px] font-bold text-gray-300">{{ $activeChat->user->name ?? 'Cliente' }}</span>
                                    </div>
                                    <div class="bg-slate-900 text-slate-100 p-4 rounded-3xl rounded-tl-xs text-sm border border-slate-800 leading-relaxed shadow-xl">
                                        {!! nl2br(e($msg->message)) !!}
                                    </div>
                                    <span class="text-[10px] text-gray-500 px-2">{{ $msg->created_at->format('H:i') }}</span>
                                </div>
                            @else
                                <!-- Mensaje Agente de Soporte (Derecha - Tarjeta Gradiente Dorado/Borgoña) -->
                                <div class="flex flex-col items-end max-w-[80%] ml-auto space-y-1">
                                    <div class="flex items-center gap-2 px-1">
                                        <span class="text-[11px] font-bold text-amber-400">Soporte Wincar 🛡️</span>
                                    </div>
                                    <div class="bg-gradient-to-r from-amber-600/30 via-yellow-600/20 to-amber-700/30 text-amber-100 p-4 rounded-3xl rounded-tr-xs text-sm border border-amber-500/40 leading-relaxed shadow-xl">
                                        {!! nl2br(e($msg->message)) !!}
                                    </div>
                                    <div class="flex items-center gap-2 px-2">
                                        @if($msg->sender)
                                            <span class="text-[10px] text-gray-500">Agente: {{ $msg->sender->name }}</span>
                                            <span class="text-gray-700">•</span>
                                        @endif
                                        <span class="text-[10px] text-gray-500">{{ $msg->created_at->format('H:i') }}</span>
                                    </div>
                                </div>
                            @endif
                        @empty
                            <div class="py-16 text-center text-gray-500 text-xs">
                                💬 Esta conversación aún no contiene mensajes.
                            </div>
                        @endforelse
                    </div>

                    <!-- Barra de Respuestas Rápidas -->
                    <div class="px-4 py-2 bg-gray-950 border-t border-gray-800/80 flex items-center gap-2 overflow-x-auto text-xs flex-shrink-0">
                        <span class="text-[11px] font-bold text-gray-400 flex-shrink-0 uppercase tracking-wider">Plantillas:</span>
                        <button 
                            type="button" 
                            wire:click="insertCannedResponse('💳 Puedes recargar tu billetera Wincar con tarjeta de crédito/débito o transferencia SINPE Móvil directa en la sección Mi Billetera.')" 
                            class="px-3 py-1 rounded-full bg-gray-900 hover:bg-gray-800 text-gray-300 border border-gray-800 whitespace-nowrap transition-all text-xs"
                        >
                            💳 Recargas
                        </button>
                        <button 
                            type="button" 
                            wire:click="insertCannedResponse('🏎️ ¡Hola! Tus participaciones están confirmadas en el sistema. Puedes consultar tus boletos en el detalle del sorteo.')" 
                            class="px-3 py-1 rounded-full bg-gray-900 hover:bg-gray-800 text-gray-300 border border-gray-800 whitespace-nowrap transition-all text-xs"
                        >
                            🏎️ Boletos Confirmados
                        </button>
                        <button 
                            type="button" 
                            wire:click="insertCannedResponse('✅ Excelente. Tu pago ha sido verificado y los fondos ya se encuentran acreditados en tu cuenta.')" 
                            class="px-3 py-1 rounded-full bg-gray-900 hover:bg-gray-800 text-gray-300 border border-gray-800 whitespace-nowrap transition-all text-xs"
                        >
                            ✅ Pago Aprobado
                        </button>
                    </div>

                    <!-- Input Flotante Estilo Pill (Matching Reference Design) -->
                    <div class="p-3 px-4 bg-gray-950 border-t border-gray-800 flex items-center gap-2 flex-shrink-0">
                        <div class="flex-1 flex items-center bg-gray-900 border border-gray-800 rounded-full px-4 py-1.5 shadow-inner focus-within:border-amber-500/50 transition-all">
                            <input 
                                type="text" 
                                wire:model="replyMessage" 
                                wire:keydown.enter.prevent="sendMessage" 
                                placeholder="Escribe tu mensaje aquí..." 
                                class="w-full bg-transparent border-0 text-gray-100 placeholder-gray-500 text-sm focus:outline-none focus:ring-0"
                            />
                        </div>

                        <button 
                            wire:click="sendMessage" 
                            class="w-11 h-11 rounded-full bg-gradient-to-r from-amber-500 to-yellow-600 hover:from-amber-400 hover:to-yellow-500 text-gray-950 font-black shadow-lg hover:scale-105 active:scale-95 transition-all flex items-center justify-center flex-shrink-0 text-base"
                            title="Enviar Mensaje"
                        >
                            ➔
                        </button>
                    </div>
                @else
                    <!-- Estado Vacío -->
                    <div class="flex-1 flex flex-col items-center justify-center p-8 text-center text-gray-500">
                        <div class="w-20 h-20 rounded-full bg-gray-950 border border-gray-800 flex items-center justify-center text-3xl mb-4 shadow-xl">
                            💬
                        </div>
                        <h3 class="text-lg font-black text-gray-200 mb-1">Selecciona una Conversación</h3>
                        <p class="text-xs text-gray-500 max-w-sm">
                            Haz clic sobre cualquier cliente en la lista de la izquierda para desplegar el chat interactivo en vivo.
                        </p>
                    </div>
                @endif
            </div>

        </div>
    </div>

    <!-- Scroll Automático JS -->
    <script>
        function scrollChatToBottom() {
            const container = document.getElementById('chat-messages-body');
            if (container) {
                container.scrollTop = container.scrollHeight;
            }
        }

        document.addEventListener('livewire:initialized', () => {
            scrollChatToBottom();
            Livewire.on('scroll-chat-to-bottom', () => {
                setTimeout(scrollChatToBottom, 100);
            });
        });
    </script>
</x-filament-panels::page>
