<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI Chat - DizzCall AI CRM</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">
    <meta name="csrf-token" content="<?php echo e(csrf_token()); ?>">
    <style>
        .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: 10px 15px;
            border-radius: 18px;
            max-width: 70%;
            word-wrap: break-word;
        }
        .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;
        }
        .message.system {
            background-color: #e9ecef;
            color: #6c757d;
            text-align: center;
            margin: 0 auto;
            font-style: italic;
        }
        .typing-indicator {
            display: none;
            padding: 10px 15px;
            background-color: white;
            border: 1px solid #dee2e6;
            border-radius: 18px;
            margin-right: auto;
            max-width: 70%;
        }
        .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); }
        }
        .chat-input {
            padding: 20px;
            background-color: white;
            border-top: 1px solid #dee2e6;
        }
        .insight-badge {
            display: inline-block;
            padding: 2px 8px;
            margin: 2px;
            border-radius: 12px;
            font-size: 0.75rem;
            background-color: #e3f2fd;
            color: #1976d2;
        }
    </style>
</head>
<body>
    <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 Chat
                            </h4>
                            <div>
                                <span class="badge bg-success" id="connectionStatus">
                                    <i class="fas fa-circle"></i> Connected
                                </span>
                                <button class="btn btn-sm btn-outline-light ms-2" id="clearChat">
                                    <i class="fas fa-trash"></i> Clear
                                </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> Welcome to DizzCall AI Voice Agent! How can I help you today?
                                </div>
                            </div>
                            <div class="typing-indicator" id="typingIndicator">
                                <div class="typing-dots">
                                    <span></span>
                                    <span></span>
                                    <span></span>
                                </div>
                                AI is typing...
                            </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> 
                                        This AI can help with sales, support, and general questions about DizzCall AI CRM.
                                    </small>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        let currentConversationId = null;
        let isTyping = false;

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

        function setupEventListeners() {
            document.getElementById('clearChat').addEventListener('click', clearChat);
        }

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

        function testConnection() {
            fetch('/api/ai/test-connection', {
                method: 'POST',
                headers: {
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
                    'Content-Type': 'application/json'
                }
            })
            .then(response => response.json())
            .then(data => {
                const status = document.getElementById('connectionStatus');
                if (data.success) {
                    status.className = 'badge bg-success';
                    status.innerHTML = '<i class="fas fa-circle"></i> Connected';
                } else {
                    status.className = 'badge bg-danger';
                    status.innerHTML = '<i class="fas fa-circle"></i> Disconnected';
                }
            })
            .catch(error => {
                const status = document.getElementById('connectionStatus');
                status.className = 'badge bg-warning';
                status.innerHTML = '<i class="fas fa-circle"></i> Testing...';
            });
        }

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

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

            // Show typing indicator
            showTypingIndicator();

            // Send to AI
            sendToAI(message);
        }

        function sendToAI(message) {
            const url = currentConversationId 
                ? `/api/ai/conversations/${currentConversationId}/message`
                : '/api/ai/conversations/start';

            const payload = currentConversationId 
                ? { message: message }
                : { 
                    type: 'general', 
                    context: { source: 'web_chat' },
                    message: message 
                  };

            fetch(url, {
                method: 'POST',
                headers: {
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(payload)
            })
            .then(response => response.json())
            .then(data => {
                hideTypingIndicator();
                
                if (data.success) {
                    if (!currentConversationId && data.conversation) {
                        currentConversationId = data.conversation.id;
                    }
                    
                    // Add AI response
                    if (data.data && data.data.ai_message) {
                        addMessage('ai', data.data.ai_message.content);
                        
                        // Show insights if available
                        if (data.data.insights && data.data.insights.length > 0) {
                            showInsights(data.data.insights);
                        }
                    } else if (data.response) {
                        addMessage('ai', data.response);
                    }
                } else {
                    addMessage('ai', 'Sorry, I encountered an error. Please try again.');
                }
            })
            .catch(error => {
                hideTypingIndicator();
                console.error('Error:', error);
                addMessage('ai', 'Sorry, I encountered an error. Please try again.');
            });
        }

        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>
                <small class="text-muted" style="font-size: 0.7em;">${time}</small>
            `;
            
            messagesContainer.appendChild(messageDiv);
            messagesContainer.scrollTop = messagesContainer.scrollHeight;
        }

        function showInsights(insights) {
            const messagesContainer = document.getElementById('chatMessages');
            const insightDiv = document.createElement('div');
            insightDiv.className = 'message system';
            insightDiv.style.marginTop = '5px';
            
            let insightHtml = '<small><i class="fas fa-lightbulb"></i> AI Insights: ';
            insights.forEach(insight => {
                insightHtml += `<span class="insight-badge">${insight.type}: ${insight.content}</span>`;
            });
            insightHtml += '</small>';
            
            insightDiv.innerHTML = insightHtml;
            messagesContainer.appendChild(insightDiv);
            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. How can I help you today?
                </div>
            `;
            currentConversationId = null;
        }
    </script>
</body>
</html>
<?php /**PATH D:\xampp\htdocs\dizzcall-ai\resources\views/ai-chat.blade.php ENDPATH**/ ?>