<x-tenant-layout>
    <x-slot name="header">
        <h2 class="font-semibold text-xl text-gray-800 leading-tight">
            Customer Support Chat
        </h2>
    </x-slot>

    <div class="max-w-4xl mx-auto sm:px-6 lg:px-8">
        <div class="bg-white shadow-sm rounded-lg">
            <div class="flex flex-col h-screen max-h-screen">
                <!-- Chat Header -->
                <div class="p-4 border-b bg-gray-50">
                    <div class="flex items-center justify-between">
                        <div class="flex items-center">
                            <div class="flex-shrink-0">
                                <div class="h-10 w-10 rounded-full bg-green-500 flex items-center justify-center">
                                    <svg class="w-6 h-6 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"></path>
                                    </svg>
                                </div>
                            </div>
                            <div class="ml-3">
                                <h3 class="text-lg font-medium text-gray-900">Support Team</h3>
                                <p class="text-sm text-gray-500">
                                    @if($session->admin_id)
                                        Admin is online
                                    @else
                                        Support team will respond shortly
                                    @endif
                                </p>
                            </div>
                        </div>
                        <div class="flex items-center space-x-2">
                            @if($session->messages && $session->messages->where('sender_type', 'admin')->where('is_read', false)->count() > 0)
                                <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800">
                                    {{ $session->messages->where('sender_type', 'admin')->where('is_read', false)->count() }} new messages
                                </span>
                            @endif
                            <button onclick="refreshMessages()" 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>

                <!-- Messages Area -->
                <div id="messagesContainer" class="flex-1 overflow-y-auto p-4 space-y-4">
                    @if($session->messages && $session->messages->count() > 0)
                        @foreach($session->messages as $message)
                            <div class="flex {{ $message->sender_type === 'tenant' ? 'justify-end' : 'justify-start' }}">
                                <div class="max-w-xs lg:max-w-md">
                                    <div class="{{ $message->sender_type === 'tenant' ? 'bg-blue-600 text-white' : 'bg-gray-200 text-gray-900' }} rounded-lg px-4 py-2">
                                        <p class="text-sm">{{ $message->message }}</p>
                                    </div>
                                    <p class="text-xs text-gray-500 mt-1 {{ $message->sender_type === 'tenant' ? 'text-right' : 'text-left' }}">
                                        {{ $message->created_at->format('h:i A') }}
                                        @if($message->sender_type === 'tenant')
                                            @if($message->is_read)
                                                <span class="text-green-500">✓✓</span>
                                            @else
                                                <span class="text-gray-400">✓</span>
                                            @endif
                                        @endif
                                    </p>
                                </div>
                            </div>
                        @endforeach
                    @else
                        <div class="text-center py-8">
                            <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">Start a conversation</h3>
                            <p class="mt-1 text-sm text-gray-500">Send a message to connect with our support team</p>
                        </div>
                    @endif
                </div>

                <!-- Message Input -->
                <div class="p-4 border-t bg-gray-50">
                    <form id="messageForm" class="flex space-x-2">
                        @csrf
                        <input type="hidden" name="session_id" value="{{ $session->id }}">
                        <input type="text" id="messageInput" 
                               name="message"
                               placeholder="Type your message..." 
                               maxlength="1000"
                               class="flex-1 rounded-md border-gray-300 shadow-sm focus:border-green-500 focus:ring focus:ring-green-200 focus:ring-opacity-50">
                        <button type="submit" 
                                class="bg-blue-600 text-white px-4 py-2 rounded-md hover:bg-blue-700 flex items-center">
                            <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="M12 19l9 2-9-18-9 18 9-2zm0 0v-8"></path>
                            </svg>
                            <span class="ml-2">Send</span>
                        </button>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <script>
        let sessionId = '{{ $session->id }}';
        let isTyping = false;

        // Auto-scroll to bottom
        function scrollToBottom() {
            const container = document.getElementById('messagesContainer');
            container.scrollTop = container.scrollHeight;
        }

        // Scroll to bottom on page load
        window.addEventListener('load', scrollToBottom);

        // Send message
        document.getElementById('messageForm').addEventListener('submit', function(e) {
            e.preventDefault();
            
            const input = document.getElementById('messageInput');
            const message = input.value.trim();
            
            if (!message) return;
            
            // Disable form while sending
            const submitButton = e.target.querySelector('button[type="submit"]');
            submitButton.disabled = true;
            submitButton.innerHTML = '<svg class="w-5 h-5 animate-spin" 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> Sending...';
            
            const formData = new FormData(this);
            
            fetch('{{ route('tenant.chat.send') }}', {
                method: 'POST',
                body: formData,
                headers: {
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    input.value = '';
                    refreshMessages();
                } else {
                    alert('Failed to send message: ' + (data.message || 'Unknown error'));
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('Failed to send message. Please try again.');
            })
            .finally(() => {
                // Re-enable form
                submitButton.disabled = false;
                submitButton.innerHTML = `
                    <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="M12 19l9 2-9-18-9 18 9-2zm0 0v-8"></path>
                    </svg>
                    <span class="ml-2">Send</span>
                `;
            });
        });

        function addMessageToUI(message) {
            const container = document.getElementById('messagesContainer');
            const messageDiv = document.createElement('div');
            messageDiv.className = `flex ${message.sender_type === 'tenant' ? 'justify-end' : 'justify-start'} mb-4`;
            messageDiv.setAttribute('data-message-id', message.id);
            
            const readStatus = message.sender_type === 'tenant' 
                ? (message.is_read ? '<span class="text-green-500">✓✓</span>' : '<span class="text-gray-400">✓</span>')
                : '';
            
            messageDiv.innerHTML = `
                <div class="max-w-xs lg:max-w-md">
                    <div class="${message.sender_type === 'tenant' ? 'bg-blue-600 text-white' : 'bg-gray-200 text-gray-900'} rounded-lg px-4 py-2 shadow-sm">
                        <p class="text-sm">${message.message}</p>
                    </div>
                    <div class="flex items-center justify-between mt-2">
                        <p class="text-xs text-gray-500 ${message.sender_type === 'tenant' ? 'text-right' : 'text-left'}">
                            ${message.formatted_time}
                            ${readStatus}
                        </p>
                        <div class="flex items-center ml-2">
                            <p class="text-xs text-gray-400 mr-2">
                                ${message.sender_name}
                            </p>
                            <p class="text-xs text-gray-300">
                                ${message.formatted_date}
                            </p>
                        </div>
                    </div>
                </div>
            `;
            
            container.appendChild(messageDiv);
            scrollToBottom();
        }

        function removeTemporaryMessage() {
            const tempMessage = document.querySelector('[data-message-id^="temp-"]');
            if (tempMessage) {
                tempMessage.remove();
            }
        }

        // Refresh messages
        function refreshMessages() {
            fetch('{{ route('tenant.chat.messages') }}')
                .then(response => response.json())
                .then(data => {
                    const container = document.getElementById('messagesContainer');
                    
                    // Clear existing messages
                    container.innerHTML = '';
                    
                    if (data.length === 0) {
                        container.innerHTML = `
                            <div class="text-center text-gray-500 py-8">
                                <svg class="w-12 h-12 mx-auto mb-2" 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>
                                <p class="text-sm">No messages yet. Start the conversation!</p>
                            </div>
                        `;
                    } else {
                        // Group messages by sender and time to create conversational flow
                        const groupedMessages = groupMessagesByConversation(data);
                        
                        groupedMessages.forEach(group => {
                            group.forEach(message => {
                                addMessageToUI(message);
                            });
                        });
                    }
                });
        }

        // Group messages to create conversational flow
        function groupMessagesByConversation(messages) {
            const groups = [];
            let currentGroup = [];
            let lastSenderType = null;
            let lastTimestamp = null;
            const TIME_GAP = 30000; // 30 seconds gap between messages from same sender
            
            messages.forEach(message => {
                const messageTimestamp = message.timestamp * 1000; // Convert to milliseconds
                const timeDiff = lastTimestamp ? messageTimestamp - lastTimestamp : 0;
                
                // Start new group if sender changes or time gap is too large
                if (lastSenderType !== message.sender_type || timeDiff > TIME_GAP) {
                    if (currentGroup.length > 0) {
                        groups.push(currentGroup);
                    }
                    currentGroup = [message];
                } else {
                    currentGroup.push(message);
                }
                
                lastSenderType = message.sender_type;
                lastTimestamp = messageTimestamp;
            });
            
            if (currentGroup.length > 0) {
                groups.push(currentGroup);
            }
            
            return groups;
        }

        // Real-time updates using polling (more reliable than SSE)
        let lastMessageId = 0;
        let pollingInterval;
        
        function startRealTimeUpdates() {
            // Clear any existing interval
            if (pollingInterval) {
                clearInterval(pollingInterval);
            }
            
            // Poll for new messages every 2 seconds
            pollingInterval = setInterval(() => {
                checkForNewMessages();
            }, 2000);
            
            // Initial check
            checkForNewMessages();
        }
        
        function checkForNewMessages() {
            fetch('{{ route('tenant.chat.stream') }}?last_id=' + lastMessageId)
                .then(response => response.json())
                .then(data => {
                    if (data.error) {
                        console.error('Error:', data.error);
                        return;
                    }
                    
                    if (data.messages && data.messages.length > 0) {
                        data.messages.forEach(message => {
                            addMessageToUI(message);
                            if (message.id > lastMessageId) {
                                lastMessageId = message.id;
                            }
                        });
                    }
                })
                .catch(error => {
                    console.error('Polling error:', error);
                    // Don't show error to user, just log it
                });
        }
        
        function showTypingIndicator(sender) {
            // Implement typing indicator if needed
            console.log(sender + ' is typing...');
        }
        
        function updateReadStatus(messageId) {
            const messageElement = document.querySelector(`[data-message-id="${messageId}"]`);
            if (messageElement) {
                const readStatusElement = messageElement.querySelector('.text-gray-400');
                if (readStatusElement) {
                    readStatusElement.className = 'text-green-500';
                    readStatusElement.textContent = '✓✓';
                }
            }
        }
        
        function sendTypingIndicator() {
            fetch('{{ route('tenant.chat.typing') }}', {
                method: 'POST',
                headers: {
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    typing: true,
                    sender_type: 'tenant'
                })
            }).catch(error => {
                // Silently ignore typing indicator errors
            });
        }

        // Auto-refresh messages every 5 seconds (fallback)
        setInterval(refreshMessages, 5000);

        // Handle typing indicator
        document.getElementById('messageInput').addEventListener('input', function() {
            if (!isTyping) {
                isTyping = true;
                // Send typing indicator
                sendTypingIndicator();
                // Could send typing indicator here
            }
            
            clearTimeout(typingTimeout);
            typingTimeout = setTimeout(() => {
                isTyping = false;
                // Could stop typing indicator here
            }, 1000);
        });
    </script>
</x-tenant-layout>
