<x-app-layout>
<x-module-hero title="Agent Dashboard" description="Manage your assigned conversations and availability" icon="fa-headset">
    <x-slot name="tabs">
        @can('view chats')
        <a href="{{ route('chat.index') }}"
           class="module-hero-tab opacity-70 hover:opacity-100 inline-flex items-center gap-2 px-4 py-3 text-[#1e293b] text-sm font-medium transition">
            <i class="fas fa-tachometer-alt"></i> Dashboard
        </a>
        @endcan
        @can('handle chats')
        <a href="{{ route('chat.conversations') }}"
           class="module-hero-tab opacity-70 hover:opacity-100 inline-flex items-center gap-2 px-4 py-3 text-[#1e293b] text-sm font-medium transition">
            <i class="fas fa-comments"></i> Conversations
        </a>
        @endcan
        @can('handle chats')
        <a href="{{ route('chat.agent-dashboard') }}"
           class="module-hero-tab border-b-2 border-[#1e293b] inline-flex items-center gap-2 px-4 py-3 text-[#1e293b] text-sm font-medium transition">
            <i class="fas fa-headset"></i> Agent Dashboard
        </a>
        @endcan
        @can('appoint chat agents')
        <a href="{{ route('chat.agents') }}"
           class="module-hero-tab opacity-70 hover:opacity-100 inline-flex items-center gap-2 px-4 py-3 text-[#1e293b] text-sm font-medium transition">
            <i class="fas fa-user-tie"></i> Agents
        </a>
        @endcan
        @can('manage chat categories')
        <a href="{{ route('chat.categories') }}"
           class="module-hero-tab opacity-70 hover:opacity-100 inline-flex items-center gap-2 px-4 py-3 text-[#1e293b] text-sm font-medium transition">
            <i class="fas fa-th-large"></i> Categories
        </a>
        @endcan
    </x-slot>
</x-module-hero>

<div class="p-6"
     x-data="{
         agentStatus: '{{ $agent->status ?? 'online' }}',
         statusLoading: false,
         setStatus(status) {
             this.statusLoading = true;
             fetch('{{ route('chat.update-status') }}', {
                 method: 'POST',
                 headers: {
                     'Content-Type': 'application/json',
                     'X-CSRF-TOKEN': document.querySelector('meta[name=csrf-token]').content
                 },
                 body: JSON.stringify({ status: status })
             })
             .then(r => r.json())
             .then(data => {
                 this.statusLoading = false;
                 if (data.success) this.agentStatus = status;
             })
             .catch(() => { this.statusLoading = false; });
         }
     }">

    @if(session('success'))
        <div class="mb-4 p-4 bg-green-100 border border-green-400 text-green-700 rounded-lg flex items-center gap-2">
            <i class="fas fa-check-circle"></i> {{ session('success') }}
        </div>
    @endif

    {{-- Stats Row --}}
    <div class="grid grid-cols-2 md:grid-cols-4 gap-4 mb-6">
        <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-4">
            <p class="text-xs text-gray-500 font-medium">Active Chats</p>
            <p class="text-2xl font-bold text-green-700">{{ $agentConversations->whereIn('status', ['active', 'waiting'])->count() }}</p>
        </div>
        <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-4">
            <p class="text-xs text-gray-500 font-medium">Resolved Today</p>
            <p class="text-2xl font-bold text-blue-700">{{ $resolvedToday ?? 0 }}</p>
        </div>
        <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-4">
            <p class="text-xs text-gray-500 font-medium">Total Handled</p>
            <p class="text-2xl font-bold text-purple-700">{{ $agent->total_conversations ?? 0 }}</p>
        </div>
        <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-4">
            <p class="text-xs text-gray-500 font-medium">Max Concurrent</p>
            <p class="text-2xl font-bold text-gray-700">{{ $agent->max_concurrent_chats ?? 5 }}</p>
        </div>
    </div>

    <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {{-- Left: Status + Conversations --}}
        <div class="lg:col-span-2 space-y-6">

            {{-- Agent Status Toggle --}}
            <div class="bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden">
                <div class="px-6 py-4 border-b border-gray-100 bg-gray-50">
                    <h3 class="font-semibold text-gray-800 flex items-center gap-2">
                        <i class="fas fa-circle text-green-500" style="font-size:10px"></i>
                        Agent Availability
                    </h3>
                </div>
                <div class="p-5">
                    <p class="text-sm text-gray-600 mb-4">Set your current availability. Visitors can only be connected to online agents.</p>
                    <div class="flex flex-wrap gap-3">
                        <button @click="setStatus('online')"
                                :disabled="statusLoading || agentStatus === 'online'"
                                :class="agentStatus === 'online' ? 'bg-green-600 text-white ring-2 ring-green-300' : 'bg-gray-100 text-gray-700 hover:bg-green-50'"
                                class="px-4 py-2 rounded-lg font-medium text-sm transition disabled:cursor-not-allowed flex items-center gap-2">
                            <span class="w-2 h-2 rounded-full bg-green-400"></span> Online
                        </button>
                        <button @click="setStatus('away')"
                                :disabled="statusLoading || agentStatus === 'away'"
                                :class="agentStatus === 'away' ? 'bg-yellow-500 text-white ring-2 ring-yellow-300' : 'bg-gray-100 text-gray-700 hover:bg-yellow-50'"
                                class="px-4 py-2 rounded-lg font-medium text-sm transition disabled:cursor-not-allowed flex items-center gap-2">
                            <span class="w-2 h-2 rounded-full bg-yellow-400"></span> Away
                        </button>
                        <button @click="setStatus('busy')"
                                :disabled="statusLoading || agentStatus === 'busy'"
                                :class="agentStatus === 'busy' ? 'bg-orange-500 text-white ring-2 ring-orange-300' : 'bg-gray-100 text-gray-700 hover:bg-orange-50'"
                                class="px-4 py-2 rounded-lg font-medium text-sm transition disabled:cursor-not-allowed flex items-center gap-2">
                            <span class="w-2 h-2 rounded-full bg-orange-400"></span> Busy
                        </button>
                        <button @click="setStatus('offline')"
                                :disabled="statusLoading || agentStatus === 'offline'"
                                :class="agentStatus === 'offline' ? 'bg-gray-600 text-white ring-2 ring-gray-300' : 'bg-gray-100 text-gray-700 hover:bg-gray-200'"
                                class="px-4 py-2 rounded-lg font-medium text-sm transition disabled:cursor-not-allowed flex items-center gap-2">
                            <span class="w-2 h-2 rounded-full bg-gray-400"></span> Offline
                        </button>
                        <i x-show="statusLoading" class="fas fa-spinner fa-spin text-gray-400 self-center ml-2"></i>
                    </div>
                </div>
            </div>

            {{-- Assigned Conversations --}}
            <div class="bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden">
                <div class="px-6 py-4 border-b border-gray-100 bg-gray-50 flex items-center justify-between">
                    <h3 class="font-semibold text-gray-800 flex items-center gap-2">
                        <i class="fas fa-comments text-green-600"></i> Assigned Conversations
                    </h3>
                    <span class="text-xs text-gray-500">{{ $agentConversations->count() }} total</span>
                </div>
                <div class="divide-y divide-gray-100">
                    @forelse($agentConversations as $conversation)
                        <a href="{{ route('chat.conversation.show', $conversation) }}"
                           class="flex items-start p-4 hover:bg-gray-50 transition">
                            <div class="w-9 h-9 rounded-full bg-gradient-to-br from-green-400 to-teal-500 flex items-center justify-center text-white font-bold text-sm mr-3 flex-shrink-0">
                                {{ strtoupper(substr($conversation->visitor_name ?? 'G', 0, 1)) }}
                            </div>
                            <div class="flex-1 min-w-0">
                                <div class="flex items-center justify-between mb-0.5">
                                    <span class="font-medium text-gray-800 text-sm truncate">
                                        {{ $conversation->visitor_name ?? 'Guest Visitor' }}
                                    </span>
                                    <span class="text-xs text-gray-400 ml-2 flex-shrink-0">
                                        {{ $conversation->last_message_at?->diffForHumans() ?? $conversation->updated_at->diffForHumans() }}
                                    </span>
                                </div>
                                <p class="text-xs text-gray-500">{{ $conversation->category->name ?? 'General' }}</p>
                            </div>
                            <div class="ml-3 flex-shrink-0">
                                @php
                                    $sc = ['active' => 'bg-green-100 text-green-700', 'waiting' => 'bg-yellow-100 text-yellow-700', 'resolved' => 'bg-gray-100 text-gray-600', 'closed' => 'bg-red-100 text-red-700'][$conversation->status] ?? 'bg-gray-100 text-gray-600';
                                @endphp
                                <span class="px-2 py-0.5 rounded-full text-xs font-medium {{ $sc }}">
                                    {{ ucfirst($conversation->status) }}
                                </span>
                            </div>
                        </a>
                    @empty
                        <div class="p-8 text-center text-gray-500">
                            <i class="fas fa-comments text-4xl mb-3 block opacity-40"></i>
                            <p class="text-sm">No conversations assigned to you yet.</p>
                        </div>
                    @endforelse
                </div>
            </div>
        </div>

        {{-- Right: Quick Reply + Profile --}}
        <div class="space-y-6">
            {{-- Quick Reply --}}
            @if(isset($latestConversation) && $latestConversation)
                <div class="bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden">
                    <div class="px-5 py-4 border-b border-gray-100 bg-gray-50">
                        <h3 class="font-semibold text-gray-800 flex items-center gap-2">
                            <i class="fas fa-reply text-green-600"></i> Quick Reply
                        </h3>
                        <p class="text-xs text-gray-500 mt-0.5">{{ $latestConversation->visitor_name ?? 'Latest conversation' }}</p>
                    </div>
                    <div class="p-4">
                        <form method="POST" action="{{ route('chat.conversation.message', $latestConversation) }}">
                            @csrf
                            <textarea name="message" rows="4" required
                                placeholder="Type your reply..."
                                class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-green-500 resize-none"></textarea>
                            <div class="flex gap-2 mt-3">
                                <button type="submit"
                                    class="flex-1 py-2 bg-[#1a4731] text-white text-sm font-medium rounded-lg hover:bg-[#276749] transition">
                                    <i class="fas fa-paper-plane mr-1"></i> Send
                                </button>
                                <a href="{{ route('chat.conversation.show', $latestConversation) }}"
                                   class="flex-1 py-2 bg-gray-100 text-gray-700 text-sm font-medium rounded-lg hover:bg-gray-200 transition text-center">
                                    <i class="fas fa-expand mr-1"></i> Open
                                </a>
                            </div>
                        </form>
                    </div>
                </div>
            @endif

            {{-- Agent Profile --}}
            <div class="bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden">
                <div class="px-5 py-4 border-b border-gray-100 bg-gray-50">
                    <h3 class="font-semibold text-gray-800">My Agent Profile</h3>
                </div>
                <div class="p-5 space-y-3 text-sm">
                    <div class="flex justify-between">
                        <span class="text-gray-500">Status</span>
                        <span x-text="agentStatus" class="font-medium capitalize text-green-700"></span>
                    </div>
                    <div class="flex justify-between">
                        <span class="text-gray-500">Max Chats</span>
                        <span class="font-medium">{{ $agent->max_concurrent_chats ?? 5 }}</span>
                    </div>
                    <div class="flex justify-between">
                        <span class="text-gray-500">Active Now</span>
                        <span class="font-medium">{{ $agentConversations->whereIn('status', ['active', 'waiting'])->count() }}</span>
                    </div>
                    @if($agent && $agent->satisfaction_rating > 0)
                        <div class="flex justify-between items-center">
                            <span class="text-gray-500">Rating</span>
                            <div class="flex items-center gap-1">
                                @for($i = 1; $i <= 5; $i++)
                                    <i class="fas fa-star text-xs {{ $i <= $agent->satisfaction_rating ? 'text-yellow-400' : 'text-gray-300' }}"></i>
                                @endfor
                            </div>
                        </div>
                    @endif
                </div>
            </div>
        </div>
    </div>
</div>
</x-app-layout>
