<x-admin-layout>
    <x-slot name="header">
        <h2 class="font-semibold text-xl text-gray-800 leading-tight">
            Customer Chat
            @if($unreadCount > 0)
                <span class="ml-2 inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-red-100 text-red-800">
                    {{ $unreadCount }} unread
                </span>
            @endif
        </h2>
    </x-slot>

    <div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
        <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
            <!-- Chat Sessions List -->
            <div class="lg:col-span-1">
                <div class="bg-white shadow-sm rounded-lg">
                    <div class="p-4 border-b">
                        <div class="flex items-center justify-between">
                            <h3 class="text-lg font-medium text-gray-900">Active Chats</h3>
                            <button onclick="refreshChatList()" class="text-gray-400 hover:text-gray-600">
                                <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"></path>
                                </svg>
                            </button>
                        </div>
                    </div>
                    <div class="overflow-y-auto max-h-96">
                        @foreach($sessions as $session)
                            <a href="{{ route('admin.chat.show', $session->id) }}" 
                               class="block p-4 hover:bg-gray-50 border-b {{ request()->route('admin.chat.show') == route('admin.chat.show', $session->id) ? 'bg-blue-50' : '' }}">
                                <div class="flex items-center">
                                    <div class="flex-shrink-0">
                                        <div class="h-10 w-10 rounded-full bg-blue-500 flex items-center justify-center">
                                            <span class="text-white font-medium">
                                                {{ $session->tenant ? substr($session->tenant->name ?? 'Unknown', 0, 1) : '?' }}
                                            </span>
                                        </div>
                                    </div>
                                    <div class="ml-3 flex-1">
                                        <div class="flex items-center justify-between">
                                            <p class="text-sm font-medium text-gray-900">{{ $session->tenant->name ?? 'Unknown Tenant' }}</p>
                                            @if($session->latestMessage)
                                                <span class="text-xs text-gray-500">
                                                    {{ $session->latestMessage->created_at->diffForHumans() }}
                                                </span>
                                            @endif
                                        </div>
                                        <p class="text-sm text-gray-500 truncate">
                                            {{ $session->latestMessage->message ?? 'No messages yet' }}
                                        </p>
                                    </div>
                                </div>
                            </a>
                        @endforeach
                    </div>
                </div>

                <!-- Start New Chat -->
                <div class="bg-white shadow-sm rounded-lg mt-6">
                    <div class="p-4">
                        <h3 class="text-lg font-medium text-gray-900 mb-4">Start New Chat</h3>
                        <form id="startChatForm">
                            <div class="mb-3">
                                <label class="block text-sm font-medium text-gray-700 mb-1">Search Tenant</label>
                                <input type="text" id="tenantSearch" placeholder="Type to search tenants..." 
                                       class="w-full rounded-md border-gray-300 shadow-sm focus:border-green-500 focus:ring focus:ring-green-200 focus:ring-opacity-50">
                                <div id="tenantSearchResults" class="mt-2 max-h-32 overflow-y-auto hidden"></div>
                            </div>
                            <button type="submit" class="w-full bg-blue-600 text-white px-4 py-2 rounded-md hover:bg-blue-700">
                                Start Chat
                            </button>
                        </form>
                    </div>
                </div>
            </div>

            <!-- Chat Area -->
            <div class="lg:col-span-2">
                <div class="bg-white shadow-sm rounded-lg h-full">
                    <div class="flex flex-col h-full">
                        <!-- Chat Header -->
                        <div class="p-4 border-b">
                            <div class="flex items-center justify-between">
                                <div>
                                    <h3 class="text-lg font-medium text-gray-900">Select a chat</h3>
                                    <p class="text-sm text-gray-500">Choose a conversation from the list</p>
                                </div>
                            </div>
                        </div>

                        <!-- Messages Area -->
                        <div class="flex-1 p-4 overflow-y-auto">
                            <div class="flex items-center justify-center h-full">
                                <div class="text-center">
                                    <svg class="mx-auto h-12 w-12 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z"></path>
                                    </svg>
                                    <h3 class="mt-2 text-sm font-medium text-gray-900">No chat selected</h3>
                                    <p class="mt-1 text-sm text-gray-500">Select a conversation to start messaging</p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        let selectedTenant = null;

        // Tenant search
        document.getElementById('tenantSearch').addEventListener('input', function(e) {
            const query = e.target.value;
            if (query.length < 2) {
                document.getElementById('tenantSearchResults').classList.add('hidden');
                return;
            }

            fetch(`{{ route('admin.chat.search-tenants') }}?q=${encodeURIComponent(query)}`)
                .then(response => response.json())
                .then(data => {
                    const resultsDiv = document.getElementById('tenantSearchResults');
                    resultsDiv.innerHTML = '';
                    
                    if (data.length > 0) {
                        data.forEach(tenant => {
                            const div = document.createElement('div');
                            div.className = 'p-2 hover:bg-gray-100 cursor-pointer border rounded';
                            div.innerHTML = `
                                <div class="font-medium">${tenant.name}</div>
                                <div class="text-sm text-gray-500">${tenant.domain}</div>
                            `;
                            div.onclick = () => selectTenant(tenant);
                            resultsDiv.appendChild(div);
                        });
                        resultsDiv.classList.remove('hidden');
                    } else {
                        resultsDiv.innerHTML = '<div class="p-2 text-gray-500">No tenants found</div>';
                        resultsDiv.classList.remove('hidden');
                    }
                });
        });

        function selectTenant(tenant) {
            selectedTenant = tenant;
            document.getElementById('tenantSearch').value = tenant.name;
            document.getElementById('tenantSearchResults').classList.add('hidden');
        }

        // Start chat form
        document.getElementById('startChatForm').addEventListener('submit', function(e) {
            e.preventDefault();
            
            if (!selectedTenant) {
                alert('Please select a tenant first');
                return;
            }

            const form = document.createElement('form');
            form.method = 'POST';
            form.action = '{{ route('admin.chat.start') }}';
            
            const csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
            const csrfInput = document.createElement('input');
            csrfInput.type = 'hidden';
            csrfInput.name = '_token';
            csrfInput.value = csrfToken;
            form.appendChild(csrfInput);
            
            const tenantInput = document.createElement('input');
            tenantInput.type = 'hidden';
            tenantInput.name = 'tenant_id';
            tenantInput.value = selectedTenant.id;
            form.appendChild(tenantInput);
            
            document.body.appendChild(form);
            form.submit();
        });

        // Refresh chat list
        function refreshChatList() {
            window.location.reload();
        }

        // Auto-refresh unread count
        setInterval(() => {
            fetch('{{ route('admin.chat.unread-count') }}')
                .then(response => response.json())
                .then(data => {
                    if (data.count > 0) {
                        // Update unread count badge if it exists
                        const badge = document.querySelector('.bg-red-100');
                        if (badge) {
                            badge.textContent = data.count + ' unread';
                        }
                    }
                });
        }, 30000); // Refresh every 30 seconds
    </script>
</x-admin-layout>
