@extends('FrontUser.layouts.app')

@section('title', 'AI Voice Agent Dashboard')

@section('content')
<div class="container-fluid">
    <!-- Header Section -->
    <div class="row mb-4">
        <div class="col-12">
            <div class="d-flex justify-content-between align-items-center">
                <div>
                    <h2 class="mb-1">🤖 AI Voice Agent Dashboard</h2>
                    <p class="text-muted mb-0">Manage your AI conversations and voice interactions</p>
                </div>
                <div>
                    <button class="btn btn-primary me-2" id="startNewConversation">
                        <i class="fas fa-plus"></i> New Conversation
                    </button>
                    <button class="btn btn-outline-secondary" id="testAIConnection">
                        <i class="fas fa-wifi"></i> Test AI
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- AI Status Cards -->
    <div class="row mb-4">
        <div class="col-md-3">
            <div class="card bg-primary text-white">
                <div class="card-body">
                    <div class="d-flex justify-content-between">
                        <div>
                            <h4 class="mb-0" id="totalConversations">0</h4>
                            <p class="mb-0">Total Conversations</p>
                        </div>
                        <div class="align-self-center">
                            <i class="fas fa-comments fa-2x"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card bg-success text-white">
                <div class="card-body">
                    <div class="d-flex justify-content-between">
                        <div>
                            <h4 class="mb-0" id="activeConversations">0</h4>
                            <p class="mb-0">Active Now</p>
                        </div>
                        <div class="align-self-center">
                            <i class="fas fa-play-circle fa-2x"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card bg-info text-white">
                <div class="card-body">
                    <div class="d-flex justify-content-between">
                        <div>
                            <h4 class="mb-0" id="aiResponseTime">0ms</h4>
                            <p class="mb-0">Avg Response Time</p>
                        </div>
                        <div class="align-self-center">
                            <i class="fas fa-tachometer-alt fa-2x"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card bg-warning text-white">
                <div class="card-body">
                    <div class="d-flex justify-content-between">
                        <div>
                            <h4 class="mb-0" id="satisfactionScore">0%</h4>
                            <p class="mb-0">Satisfaction</p>
                        </div>
                        <div class="align-self-center">
                            <i class="fas fa-star fa-2x"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Main Content -->
    <div class="row">
        <!-- Chat Interface -->
        <div class="col-md-8">
            <div class="card h-100">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h5 class="mb-0">AI Voice Agent</h5>
                    <div class="btn-group" role="group">
                        <button type="button" class="btn btn-sm btn-outline-primary" id="voiceToggle">
                            <i class="fas fa-microphone"></i> Voice
                        </button>
                        <button type="button" class="btn btn-sm btn-outline-secondary" id="settingsToggle">
                            <i class="fas fa-cog"></i> Settings
                        </button>
                    </div>
                </div>
                <div class="card-body d-flex flex-column">
                    <!-- Chat Messages -->
                    <div id="chatMessages" class="flex-grow-1 overflow-auto mb-3" style="height: 500px; background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%); border-radius: 10px; padding: 20px;">
                        <div class="text-center text-muted py-5">
                            <i class="fas fa-robot fa-3x mb-3" style="color: #007bff;"></i>
                            <h4>Welcome to DizzCall AI!</h4>
                            <p>Start a conversation with your AI voice agent</p>
                            <button class="btn btn-primary me-2" id="startChatBtn">
                                <i class="fas fa-play"></i> Start Chat
                            </button>
                            <button class="btn btn-outline-primary" id="testAIDirect">
                                <i class="fas fa-wifi"></i> Test AI Direct
                            </button>
                        </div>
                    </div>

                    <!-- Message Input -->
                    <div class="input-group">
                        <input type="text" class="form-control" id="messageInput" placeholder="Type your message or speak..." disabled>
                        <button class="btn btn-primary" type="button" id="sendMessage" disabled>
                            <i class="fas fa-paper-plane"></i>
                        </button>
                        <button class="btn btn-outline-secondary" type="button" id="voiceInput">
                            <i class="fas fa-microphone"></i>
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <!-- Sidebar -->
        <div class="col-md-4">
            <!-- Quick Actions -->
            <div class="card mb-3">
                <div class="card-header">
                    <h6 class="mb-0">Quick Actions</h6>
                </div>
                <div class="card-body">
                    <div class="d-grid gap-2">
                        <button class="btn btn-outline-primary btn-sm" onclick="startQuickChat('sales')">
                            <i class="fas fa-handshake"></i> Sales Call
                        </button>
                        <button class="btn btn-outline-success btn-sm" onclick="startQuickChat('support')">
                            <i class="fas fa-headset"></i> Customer Support
                        </button>
                        <button class="btn btn-outline-info btn-sm" onclick="startQuickChat('demo')">
                            <i class="fas fa-presentation"></i> Product Demo
                        </button>
                        <button class="btn btn-outline-warning btn-sm" onclick="startQuickChat('follow_up')">
                            <i class="fas fa-phone"></i> Follow Up
                        </button>
                    </div>
                </div>
            </div>

            <!-- AI Status -->
            <div class="card mb-3">
                <div class="card-header">
                    <h6 class="mb-0">AI Status</h6>
                </div>
                <div class="card-body">
                    <div class="d-flex align-items-center">
                        <div class="me-3">
                            <div id="aiStatusIndicator" class="status-indicator bg-secondary"></div>
                        </div>
                        <div>
                            <div class="fw-bold" id="aiStatusText">Checking...</div>
                            <small class="text-muted" id="aiStatusDetails">Connecting to AI service</small>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Recent Conversations -->
            <div class="card">
                <div class="card-header">
                    <h6 class="mb-0">Recent Conversations</h6>
                </div>
                <div class="card-body p-0">
                    <div id="conversationsList" class="list-group list-group-flush">
                        <div class="list-group-item text-center text-muted">
                            <i class="fas fa-comments fa-2x mb-2"></i>
                            <p>No conversations yet</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- AI Insights Panel -->
    <div class="row mt-4">
        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0">AI Insights & Analytics</h5>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-6">
                            <h6>Sentiment Analysis</h6>
                            <div id="sentimentChart" style="height: 200px;">
                                <div class="text-center text-muted py-5">
                                    <i class="fas fa-chart-pie fa-2x mb-2"></i>
                                    <p>No sentiment data available</p>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <h6>Conversation Types</h6>
                            <div id="conversationTypesChart" style="height: 200px;">
                                <div class="text-center text-muted py-5">
                                    <i class="fas fa-chart-bar fa-2x mb-2"></i>
                                    <p>No conversation data available</p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- New Conversation Modal -->
<div class="modal fade" id="newConversationModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Start New AI Conversation</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="newConversationForm">
                    <div class="mb-3">
                        <label for="conversationType" class="form-label">Conversation Type</label>
                        <select class="form-select" id="conversationType" name="type" required>
                            <option value="sales">Sales Call</option>
                            <option value="support">Customer Support</option>
                            <option value="follow_up">Follow Up</option>
                            <option value="qualification">Lead Qualification</option>
                            <option value="demo">Product Demo</option>
                            <option value="general">General Chat</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label for="contextNotes" class="form-label">Context Notes</label>
                        <textarea class="form-control" id="contextNotes" name="context" rows="3" placeholder="Any specific context or goals for this conversation..."></textarea>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-primary" id="createConversation">Start Conversation</button>
            </div>
        </div>
    </div>
</div>
@endsection

@push('styles')
<style>
.chat-message {
    margin-bottom: 1rem;
    padding: 1rem;
    border-radius: 15px;
    max-width: 80%;
    word-wrap: break-word;
    box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}

.chat-message.user {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    margin-left: auto;
    margin-right: 0;
}

.chat-message.assistant {
    background: white;
    color: #333;
    margin-left: 0;
    margin-right: auto;
    border: 1px solid #e9ecef;
}

.chat-message .message-header {
    font-size: 0.8rem;
    opacity: 0.8;
    margin-bottom: 0.5rem;
    font-weight: 500;
}

.chat-message .message-content {
    line-height: 1.5;
}

.typing-indicator {
    display: none;
    color: #666;
    font-style: italic;
    padding: 1rem;
    background: white;
    border-radius: 15px;
    margin-bottom: 1rem;
    box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}

.typing-indicator.show {
    display: block;
}

.status-indicator {
    width: 12px;
    height: 12px;
    border-radius: 50%;
    display: inline-block;
}

.status-indicator.bg-success {
    background-color: #28a745 !important;
    box-shadow: 0 0 10px rgba(40, 167, 69, 0.5);
}

.status-indicator.bg-danger {
    background-color: #dc3545 !important;
    box-shadow: 0 0 10px rgba(220, 53, 69, 0.5);
}

.status-indicator.bg-secondary {
    background-color: #6c757d !important;
}

@keyframes blink {
    0%, 50% { border-color: #007bff; }
    51%, 100% { border-color: transparent; }
}

.streaming-text {
    border-right: 2px solid #007bff;
    animation: blink 1s infinite;
}

.btn {
    border-radius: 8px;
    font-weight: 500;
}

.card {
    border: none;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
    border-radius: 15px;
}

.card-header {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    border-radius: 15px 15px 0 0 !important;
    border: none;
}

.list-group-item {
    border: none;
    border-bottom: 1px solid #f8f9fa;
}

.list-group-item:last-child {
    border-bottom: none;
}

.list-group-item:hover {
    background-color: #f8f9fa;
}

.modal-content {
    border-radius: 15px;
    border: none;
    box-shadow: 0 10px 30px rgba(0,0,0,0.3);
}

.modal-header {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    border-radius: 15px 15px 0 0;
    border: none;
}

.btn-close {
    filter: invert(1);
}
</style>
@endpush

@push('scripts')
<script>
let currentConversationId = null;
let isVoiceEnabled = false;
let recognition = null;
let conversationCount = 0;

// Initialize the dashboard
document.addEventListener('DOMContentLoaded', function() {
    initializeDashboard();
    setupEventListeners();
    testAIConnection();
});

function initializeDashboard() {
    // Initialize voice recognition if supported
    if ('webkitSpeechRecognition' in window || 'SpeechRecognition' in window) {
        const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
        recognition = new SpeechRecognition();
        recognition.continuous = false;
        recognition.interimResults = false;
        recognition.lang = 'en-US';
        
        recognition.onresult = function(event) {
            const transcript = event.results[0][0].transcript;
            document.getElementById('messageInput').value = transcript;
        };
        
        recognition.onerror = function(event) {
            console.error('Speech recognition error:', event.error);
        };
    }
}

function setupEventListeners() {
    // New conversation button
    document.getElementById('startNewConversation').addEventListener('click', function() {
        new bootstrap.Modal(document.getElementById('newConversationModal')).show();
    });
    
    // Create conversation
    document.getElementById('createConversation').addEventListener('click', function() {
        createNewConversation();
    });
    
    // Start chat button
    document.getElementById('startChatBtn').addEventListener('click', function() {
        startQuickChat('general');
    });
    
    // Send message
    document.getElementById('sendMessage').addEventListener('click', function() {
        sendMessage();
    });
    
    // Enter key to send message
    document.getElementById('messageInput').addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            sendMessage();
        }
    });
    
    // Voice input
    document.getElementById('voiceInput').addEventListener('click', function() {
        if (recognition) {
            recognition.start();
            this.innerHTML = '<i class="fas fa-stop"></i>';
        }
    });
    
    // Voice toggle
    document.getElementById('voiceToggle').addEventListener('click', function() {
        isVoiceEnabled = !isVoiceEnabled;
        this.classList.toggle('btn-primary', isVoiceEnabled);
        this.classList.toggle('btn-outline-primary', !isVoiceEnabled);
    });
    
    // Settings toggle
    document.getElementById('settingsToggle').addEventListener('click', function() {
        alert('Settings panel coming soon!');
    });
    
    // Test AI connection
    document.getElementById('testAIConnection').addEventListener('click', function() {
        testAIConnection();
    });
    
    // Test AI direct button
    document.getElementById('testAIDirect').addEventListener('click', function() {
        testAIConnection();
    });
}

function startQuickChat(type) {
    // Enable input immediately
    document.getElementById('messageInput').disabled = false;
    document.getElementById('sendMessage').disabled = false;
    
    // Clear chat and show welcome message
    const chatMessages = document.getElementById('chatMessages');
    chatMessages.innerHTML = '';
    
    // Add welcome message
    addMessageToChat('assistant', `Hello! I'm your DizzCall AI assistant. I'm ready to help you with ${type.replace('_', ' ')}. How can I assist you today?`, new Date().toISOString());
    
    // Update conversation count
    conversationCount++;
    document.getElementById('totalConversations').textContent = conversationCount;
    document.getElementById('activeConversations').textContent = '1';
    
    // Add to conversations list
    addToConversationsList(type);
}

function createNewConversation() {
    const form = document.getElementById('newConversationForm');
    const formData = new FormData(form);
    const type = formData.get('type');
    
    // Close modal
    bootstrap.Modal.getInstance(document.getElementById('newConversationModal')).hide();
    
    // Start conversation
    startQuickChat(type);
    
    // Reset form
    form.reset();
}

function addMessageToChat(role, content, timestamp) {
    const chatMessages = document.getElementById('chatMessages');
    const messageDiv = document.createElement('div');
    messageDiv.className = `chat-message ${role}`;
    
    const time = new Date(timestamp).toLocaleTimeString();
    messageDiv.innerHTML = `
        <div class="message-header">${role === 'user' ? 'You' : 'AI Assistant'} • ${time}</div>
        <div class="message-content">${content}</div>
    `;
    
    chatMessages.appendChild(messageDiv);
    chatMessages.scrollTop = chatMessages.scrollHeight;
}

function sendMessage() {
    const messageInput = document.getElementById('messageInput');
    const message = messageInput.value.trim();
    
    if (!message) {
        alert('Please enter a message');
        return;
    }
    
    // Add user message to chat
    addMessageToChat('user', message, new Date().toISOString());
    
    // Show typing indicator
    showTypingIndicator();
    
    // Create streaming message container
    const streamingMessage = addStreamingMessage();
    
    // Send to AI
    fetch(`/dizzcall-ai/public/ai-test-dashboard?message=${encodeURIComponent(message)}`, {
        method: 'GET',
        headers: {
            'Content-Type': 'application/json'
        }
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('HTTP ' + response.status);
        }
        return response.json();
    })
    .then(data => {
        hideTypingIndicator();
        
        if (data.success) {
            // Stream the AI response
            if (data.data && data.data.ai_message) {
                streamText(data.data.ai_message.content, streamingMessage);
            } else if (data.details && data.details.response) {
                streamText(data.details.response, streamingMessage);
            } else {
                updateStreamingMessage(streamingMessage, '❌ No response received');
            }
        } else {
            updateStreamingMessage(streamingMessage, '❌ Error: ' + (data.message || 'Unknown error'));
        }
    })
    .catch(error => {
        hideTypingIndicator();
        console.error('Error:', error);
        updateStreamingMessage(streamingMessage, '❌ Connection Error: ' + error.message);
    });
    
    messageInput.value = '';
}

function showTypingIndicator() {
    const chatMessages = document.getElementById('chatMessages');
    const typingDiv = document.createElement('div');
    typingDiv.className = 'typing-indicator show';
    typingDiv.innerHTML = '<i class="fas fa-robot"></i> AI is typing...';
    chatMessages.appendChild(typingDiv);
    chatMessages.scrollTop = chatMessages.scrollHeight;
}

function hideTypingIndicator() {
    const typingIndicator = document.querySelector('.typing-indicator');
    if (typingIndicator) {
        typingIndicator.remove();
    }
}

function addStreamingMessage() {
    const chatMessages = document.getElementById('chatMessages');
    const messageDiv = document.createElement('div');
    messageDiv.className = 'chat-message assistant streaming-message';
    messageDiv.innerHTML = `
        <div class="message-header">AI Assistant • ${new Date().toLocaleTimeString()}</div>
        <div class="message-content streaming-text" id="streamingText" style="border-right: 2px solid #007bff; animation: blink 1s infinite;"></div>
    `;
    
    chatMessages.appendChild(messageDiv);
    chatMessages.scrollTop = chatMessages.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 chatMessages = document.getElementById('chatMessages');
            chatMessages.scrollTop = chatMessages.scrollHeight;
        } else {
            clearInterval(streamInterval);
            // Remove streaming cursor
            textElement.style.borderRight = 'none';
            textElement.style.animation = 'none';
        }
    }, 30); // Adjust speed here (lower = faster)
}

function updateStreamingMessage(messageElement, text) {
    const textElement = messageElement.querySelector('#streamingText');
    textElement.textContent = text;
    textElement.style.borderRight = 'none';
    textElement.style.animation = 'none';
}

function testAIConnection() {
    const button = document.getElementById('testAIConnection');
    const statusIndicator = document.getElementById('aiStatusIndicator');
    const statusText = document.getElementById('aiStatusText');
    const statusDetails = document.getElementById('aiStatusDetails');
    
    button.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Testing...';
    button.disabled = true;
    
    statusText.textContent = 'Testing...';
    statusDetails.textContent = 'Connecting to AI service';
    
    fetch('/dizzcall-ai/public/ai-test-dashboard', {
        method: 'GET',
        headers: {
            'Content-Type': 'application/json'
        }
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('HTTP ' + response.status);
        }
        return response.json();
    })
    .then(data => {
        if (data.success) {
            button.innerHTML = '<i class="fas fa-check"></i> AI Connected';
            button.className = 'btn btn-success';
            
            statusIndicator.className = 'status-indicator bg-success';
            statusText.textContent = 'Connected';
            statusDetails.textContent = 'AI service is ready';
            
            // Show success message in chat
            addMessageToChat('assistant', '✅ AI connection successful! Ready for live streaming.', new Date().toISOString());
        } else {
            button.innerHTML = '<i class="fas fa-times"></i> AI Disconnected';
            button.className = 'btn btn-danger';
            
            statusIndicator.className = 'status-indicator bg-danger';
            statusText.textContent = 'Disconnected';
            statusDetails.textContent = 'AI service unavailable';
            
            // Show error message in chat
            addMessageToChat('assistant', '❌ AI connection failed: ' + (data.message || 'Unknown error'), new Date().toISOString());
        }
        
        setTimeout(() => {
            button.innerHTML = '<i class="fas fa-wifi"></i> Test AI';
            button.className = 'btn btn-outline-secondary';
            button.disabled = false;
        }, 3000);
    })
    .catch(error => {
        console.error('Error testing AI connection:', error);
        button.innerHTML = '<i class="fas fa-times"></i> Connection Error';
        button.className = 'btn btn-danger';
        
        statusIndicator.className = 'status-indicator bg-danger';
        statusText.textContent = 'Error';
        statusDetails.textContent = 'Connection failed';
        
        // Show error message in chat
        addMessageToChat('assistant', '❌ Connection error: ' + error.message, new Date().toISOString());
        
        setTimeout(() => {
            button.innerHTML = '<i class="fas fa-wifi"></i> Test AI';
            button.className = 'btn btn-outline-secondary';
            button.disabled = false;
        }, 3000);
    });
}

function addToConversationsList(type) {
    const conversationsList = document.getElementById('conversationsList');
    
    // Clear the "no conversations" message
    if (conversationsList.querySelector('.text-center')) {
        conversationsList.innerHTML = '';
    }
    
    const conversationDiv = document.createElement('div');
    conversationDiv.className = 'list-group-item list-group-item-action';
    conversationDiv.innerHTML = `
        <div class="d-flex w-100 justify-content-between">
            <h6 class="mb-1">${type.replace('_', ' ').toUpperCase()}</h6>
            <small>${new Date().toLocaleTimeString()}</small>
        </div>
        <p class="mb-1">Active conversation</p>
        <small>Status: <span class="badge bg-success">Active</span></small>
    `;
    
    conversationsList.insertBefore(conversationDiv, conversationsList.firstChild);
}
</script>
@endpush