<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI Chat - Live Streaming</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        body { background-color: #f8f9fa; }
        .chat-container { height: 80vh; display: flex; flex-direction: column; }
        .chat-messages { flex: 1; overflow-y: auto; padding: 20px; background-color: #f8f9fa; }
        .message { margin-bottom: 15px; padding: 12px 16px; border-radius: 18px; max-width: 75%; word-wrap: break-word; animation: fadeIn 0.3s ease-in; }
        .message.user { background-color: #007bff; color: white; margin-left: auto; text-align: right; }
        .message.ai { background-color: white; color: #333; border: 1px solid #dee2e6; margin-right: auto; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }
        .message.system { background-color: #e9ecef; color: #6c757d; text-align: center; margin: 0 auto; font-style: italic; max-width: 90%; }
        .typing-indicator { display: none; padding: 12px 16px; background-color: white; border: 1px solid #dee2e6; border-radius: 18px; margin-right: auto; max-width: 75%; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }
        .typing-indicator.show { display: block; }
        .typing-dots { display: inline-block; }
        .typing-dots span { display: inline-block; width: 8px; height: 8px; border-radius: 50%; background-color: #6c757d; margin: 0 2px; animation: typing 1.4s infinite ease-in-out; }
        .typing-dots span:nth-child(1) { animation-delay: -0.32s; }
        .typing-dots span:nth-child(2) { animation-delay: -0.16s; }
        @keyframes typing { 0%, 80%, 100% { transform: scale(0); } 40% { transform: scale(1); } }
        @keyframes fadeIn { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } }
        .chat-input { padding: 20px; background-color: white; border-top: 1px solid #dee2e6; }
        .message-time { font-size: 0.7em; opacity: 0.7; margin-top: 4px; }
        .status-indicator { position: fixed; top: 20px; right: 20px; z-index: 1000; }
        .streaming-text { border-right: 2px solid #007bff; animation: blink 1s infinite; }
        @keyframes blink { 0%, 50% { border-color: #007bff; } 51%, 100% { border-color: transparent; } }
        .model-selector { position: fixed; top: 20px; left: 20px; z-index: 1000; }
    </style>
</head>
<body>
    <div class="model-selector">
        <select class="form-select form-select-sm" id="modelSelect">
            <option value="gemma:2b">Gemma 2B (Fast)</option>
            <option value="phi3:mini">Phi-3 Mini (Better Quality)</option>
        </select>
    </div>

    <div class="status-indicator">
        <span class="badge bg-success" id="connectionStatus">
            <i class="fas fa-circle"></i> Ready
        </span>
    </div>

    <div class="container-fluid">
        <div class="row">
            <div class="col-12">
                <div class="card">
                    <div class="card-header bg-primary text-white">
                        <div class="d-flex justify-content-between align-items-center">
                            <h4 class="mb-0">
                                <i class="fas fa-robot"></i> AI Voice Agent - Live Streaming
                            </h4>
                            <div>
                                <button class="btn btn-sm btn-outline-light" id="clearChat">
                                    <i class="fas fa-trash"></i> Clear
                                </button>
                                <button class="btn btn-sm btn-outline-light" id="testConnection">
                                    <i class="fas fa-wifi"></i> Test
                                </button>
                            </div>
                        </div>
                    </div>
                    <div class="card-body p-0">
                        <div class="chat-container">
                            <div class="chat-messages" id="chatMessages">
                                <div class="message system">
                                    <i class="fas fa-robot"></i> AI Chat with Live Streaming! Type any message to start.
                                </div>
                            </div>
                            <div class="typing-indicator" id="typingIndicator">
                                <div class="typing-dots">
                                    <span></span>
                                    <span></span>
                                    <span></span>
                                </div>
                                AI is thinking...
                            </div>
                            <div class="chat-input">
                                <div class="input-group">
                                    <input type="text" class="form-control" id="messageInput" 
                                           placeholder="Type your message here..." 
                                           onkeypress="handleKeyPress(event)">
                                    <button class="btn btn-primary" type="button" id="sendButton" onclick="sendMessage()">
                                        <i class="fas fa-paper-plane"></i>
                                    </button>
                                </div>
                                <div class="mt-2">
                                    <small class="text-muted">
                                        <i class="fas fa-info-circle"></i> 
                                        Live streaming enabled - watch responses appear in real-time
                                    </small>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        let isTyping = false;
        let currentStreamingMessage = null;

        // Initialize
        document.addEventListener('DOMContentLoaded', function() {
            testConnection();
            setupEventListeners();
        });

        function setupEventListeners() {
            document.getElementById('clearChat').addEventListener('click', clearChat);
            document.getElementById('testConnection').addEventListener('click', testConnection);
            document.getElementById('modelSelect').addEventListener('change', function() {
                addMessage('system', `Model switched to: ${this.value}`);
            });
        }

        function handleKeyPress(event) {
            if (event.key === 'Enter') {
                sendMessage();
            }
        }

        function testConnection() {
            const status = document.getElementById('connectionStatus');
            status.className = 'badge bg-warning';
            status.innerHTML = '<i class="fas fa-circle"></i> Testing...';
            
            fetch('/ai-test-simple')
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    status.className = 'badge bg-success';
                    status.innerHTML = '<i class="fas fa-circle"></i> Connected';
                    addMessage('system', '✅ AI connection successful! Ready for live streaming.');
                } else {
                    status.className = 'badge bg-danger';
                    status.innerHTML = '<i class="fas fa-circle"></i> Error';
                    addMessage('system', '❌ AI connection failed: ' + (data.error || 'Unknown error'));
                }
            })
            .catch(error => {
                status.className = 'badge bg-danger';
                status.innerHTML = '<i class="fas fa-circle"></i> Error';
                addMessage('system', '❌ Connection error: ' + error.message);
            });
        }

        function sendMessage() {
            const input = document.getElementById('messageInput');
            const message = input.value.trim();
            
            if (!message || isTyping) return;

            // Add user message
            addMessage('user', message);
            input.value = '';

            // Show typing indicator
            showTypingIndicator();

            // Send to AI with streaming
            sendToAIStreaming(message);
        }

        function sendToAIStreaming(message) {
            const model = document.getElementById('modelSelect').value;
            const encodedMessage = encodeURIComponent(message);
            
            // Create streaming message container
            currentStreamingMessage = addStreamingMessage();
            
            // Simulate streaming by breaking response into chunks
            fetch(`/ai-test-response?message=${encodedMessage}&model=${model}`)
            .then(response => response.json())
            .then(data => {
                hideTypingIndicator();
                
                if (data.success) {
                    // Simulate streaming by showing text character by character
                    streamText(data.response, currentStreamingMessage);
                } else {
                    updateStreamingMessage(currentStreamingMessage, '❌ Error: ' + (data.error || 'Unknown error'));
                }
            })
            .catch(error => {
                hideTypingIndicator();
                console.error('Error:', error);
                updateStreamingMessage(currentStreamingMessage, '❌ Connection Error: ' + error.message);
            });
        }

        function addStreamingMessage() {
            const messagesContainer = document.getElementById('chatMessages');
            const messageDiv = document.createElement('div');
            messageDiv.className = 'message ai streaming-message';
            messageDiv.innerHTML = `
                <div class="streaming-text" id="streamingText"></div>
                <div class="message-time">${new Date().toLocaleTimeString()}</div>
            `;
            
            messagesContainer.appendChild(messageDiv);
            messagesContainer.scrollTop = messagesContainer.scrollHeight;
            
            return messageDiv;
        }

        function streamText(text, messageElement) {
            const textElement = messageElement.querySelector('#streamingText');
            let index = 0;
            
            const streamInterval = setInterval(() => {
                if (index < text.length) {
                    textElement.textContent += text[index];
                    index++;
                    
                    // Auto-scroll to bottom
                    const messagesContainer = document.getElementById('chatMessages');
                    messagesContainer.scrollTop = messagesContainer.scrollHeight;
                } else {
                    clearInterval(streamInterval);
                    // Remove streaming cursor
                    textElement.classList.remove('streaming-text');
                }
            }, 30); // Adjust speed here (lower = faster)
        }

        function updateStreamingMessage(messageElement, text) {
            const textElement = messageElement.querySelector('#streamingText');
            textElement.textContent = text;
            textElement.classList.remove('streaming-text');
        }

        function addMessage(type, content) {
            const messagesContainer = document.getElementById('chatMessages');
            const messageDiv = document.createElement('div');
            messageDiv.className = `message ${type}`;
            
            const time = new Date().toLocaleTimeString();
            messageDiv.innerHTML = `
                <div>${content}</div>
                <div class="message-time">${time}</div>
            `;
            
            messagesContainer.appendChild(messageDiv);
            messagesContainer.scrollTop = messagesContainer.scrollHeight;
        }

        function showTypingIndicator() {
            isTyping = true;
            document.getElementById('typingIndicator').classList.add('show');
            document.getElementById('sendButton').disabled = true;
        }

        function hideTypingIndicator() {
            isTyping = false;
            document.getElementById('typingIndicator').classList.remove('show');
            document.getElementById('sendButton').disabled = false;
        }

        function clearChat() {
            const messagesContainer = document.getElementById('chatMessages');
            messagesContainer.innerHTML = `
                <div class="message system">
                    <i class="fas fa-robot"></i> Chat cleared. Ready for live streaming!
                </div>
            `;
        }
    </script>
</body>
</html>
<?php /**PATH D:\xampp\htdocs\dizzcall-ai\resources\views/ai-chat-streaming-fixed.blade.php ENDPATH**/ ?>