@extends('FrontUser.layouts.app')

@section('title', 'CRM 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">📊 CRM Dashboard</h2>
                    <p class="text-muted mb-0">Manage your contacts, conversations, and AI insights</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>

    <!-- CRM Stats Cards -->
    <div class="row mb-4">
        <div class="col-md-2">
            <div class="card bg-primary text-white">
                <div class="card-body">
                    <div class="d-flex justify-content-between">
                        <div>
                            <h4 class="mb-0" id="totalContacts">{{ $stats['total_contacts'] ?? 0 }}</h4>
                            <p class="mb-0">Total Contacts</p>
                        </div>
                        <div class="align-self-center">
                            <i class="fas fa-users fa-2x"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-2">
            <div class="card bg-success text-white">
                <div class="card-body">
                    <div class="d-flex justify-content-between">
                        <div>
                            <h4 class="mb-0" id="totalConversations">{{ $stats['total_conversations'] ?? 0 }}</h4>
                            <p class="mb-0">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-2">
            <div class="card bg-info text-white">
                <div class="card-body">
                    <div class="d-flex justify-content-between">
                        <div>
                            <h4 class="mb-0" id="activeConversations">{{ $stats['active_conversations'] ?? 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-2">
            <div class="card bg-warning text-white">
                <div class="card-body">
                    <div class="d-flex justify-content-between">
                        <div>
                            <h4 class="mb-0" id="conversionRate">{{ $stats['conversion_rate'] ?? 0 }}%</h4>
                            <p class="mb-0">Conversion Rate</p>
                        </div>
                        <div class="align-self-center">
                            <i class="fas fa-chart-line fa-2x"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-2">
            <div class="card bg-secondary text-white">
                <div class="card-body">
                    <div class="d-flex justify-content-between">
                        <div>
                            <h4 class="mb-0" id="avgSatisfaction">{{ round(($stats['avg_satisfaction'] ?? 0) * 100, 1) }}%</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 class="col-md-2">
            <div class="card bg-dark text-white">
                <div class="card-body">
                    <div class="d-flex justify-content-between">
                        <div>
                            <h4 class="mb-0" id="completedConversations">{{ $stats['completed_conversations'] ?? 0 }}</h4>
                            <p class="mb-0">Completed</p>
                        </div>
                        <div class="align-self-center">
                            <i class="fas fa-check-circle fa-2x"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Main Content -->
    <div class="row">
        <!-- Recent Contacts -->
        <div class="col-md-4">
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0">Recent Contacts</h5>
                </div>
                <div class="card-body p-0">
                    <div id="contactsList" class="list-group list-group-flush">
                        @forelse($recentContacts as $contact)
                        <div class="list-group-item list-group-item-action">
                            <div class="d-flex w-100 justify-content-between">
                                <h6 class="mb-1">{{ $contact->name }}</h6>
                                <small>{{ $contact->created_at->diffForHumans() }}</small>
                            </div>
                            <p class="mb-1">{{ $contact->email }}</p>
                            <small>{{ $contact->company_name ?? 'No company' }}</small>
                        </div>
                        @empty
                        <div class="list-group-item text-center text-muted">
                            <i class="fas fa-users fa-2x mb-2"></i>
                            <p>No contacts yet</p>
                        </div>
                        @endforelse
                    </div>
                </div>
            </div>
        </div>

        <!-- Recent Conversations -->
        <div class="col-md-4">
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0">Recent Conversations</h5>
                </div>
                <div class="card-body p-0">
                    <div id="conversationsList" class="list-group list-group-flush">
                        @forelse($recentConversations as $conversation)
                        <div class="list-group-item list-group-item-action" onclick="loadConversation({{ $conversation->id }})">
                            <div class="d-flex w-100 justify-content-between">
                                <h6 class="mb-1">{{ $conversation->type_label }}</h6>
                                <small>{{ $conversation->created_at->diffForHumans() }}</small>
                            </div>
                            <p class="mb-1">{{ $conversation->contact->name ?? 'No contact' }}</p>
                            <small>Status: <span class="badge {{ $conversation->status_badge }}">{{ $conversation->status }}</span></small>
                        </div>
                        @empty
                        <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>
                        @endforelse
                    </div>
                </div>
            </div>
        </div>

        <!-- AI Chat Interface -->
        <div class="col-md-4">
            <div class="card h-100">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h5 class="mb-0">AI Assistant</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: 300px;">
                        <div class="text-center text-muted py-5">
                            <i class="fas fa-robot fa-3x mb-3"></i>
                            <p>Start a conversation with your AI assistant</p>
                            <button class="btn btn-primary me-2" id="startChatBtn">Start Chat</button>
                            <button class="btn btn-outline-primary" id="testAIDirect">Test AI Direct</button>
                        </div>
                    </div>

                    <!-- Message Input -->
                    <div class="input-group">
                        <input type="text" class="form-control" id="messageInput" placeholder="Type your message..." disabled>
                        <button class="btn btn-primary" type="button" id="sendMessage" disabled>
                            <i class="fas fa-paper-plane"></i>
                        </button>
                    </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="contactId" class="form-label">Contact (Optional)</label>
                        <select class="form-select" id="contactId" name="contact_id">
                            <option value="">No specific contact</option>
                            @foreach($recentContacts as $contact)
                            <option value="{{ $contact->id }}">{{ $contact->name }} ({{ $contact->email }})</option>
                            @endforeach
                        </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: 0.75rem;
    border-radius: 0.5rem;
}

.chat-message.user {
    background-color: #e3f2fd;
    margin-left: 2rem;
}

.chat-message.assistant {
    background-color: #f5f5f5;
    margin-right: 2rem;
}

.chat-message .message-header {
    font-size: 0.8rem;
    color: #666;
    margin-bottom: 0.25rem;
}

.typing-indicator {
    display: none;
    color: #666;
    font-style: italic;
}

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

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

.streaming-text {
    border-right: 2px solid #007bff;
    animation: blink 1s infinite;
}
</style>
@endpush

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

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

function initializeDashboard() {
    // Initialize any dashboard-specific functionality
}

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() {
        new bootstrap.Modal(document.getElementById('newConversationModal')).show();
    });
    
    // 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();
        }
    });
    
    // Test AI connection
    document.getElementById('testAIConnection').addEventListener('click', function() {
        testAIConnection();
    });
    
    // Test AI direct button
    document.getElementById('testAIDirect').addEventListener('click', function() {
        testAIConnection();
    });
}

function createNewConversation() {
    const form = document.getElementById('newConversationForm');
    const formData = new FormData(form);
    
    fetch('/dizzcall-ai/public/user/crm/conversations/start', {
        method: 'POST',
        headers: {
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            type: formData.get('type'),
            contact_id: formData.get('contact_id') || null,
            context: formData.get('context') ? { notes: formData.get('context') } : {}
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            currentConversationId = data.conversation.id;
            loadConversation(data.conversation.id);
            bootstrap.Modal.getInstance(document.getElementById('newConversationModal')).hide();
            form.reset();
        } else {
            alert('Error: ' + data.message);
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('Failed to create conversation');
    });
}

function loadConversation(conversationId) {
    fetch(`/dizzcall-ai/public/user/crm/conversations/${conversationId}`)
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            displayConversation(data.data);
        }
    })
    .catch(error => {
        console.error('Error loading conversation:', error);
    });
}

function displayConversation(data) {
    const chatMessages = document.getElementById('chatMessages');
    chatMessages.innerHTML = '';
    
    // Enable input
    document.getElementById('messageInput').disabled = false;
    document.getElementById('sendMessage').disabled = false;
    
    // Display messages
    data.messages.forEach(message => {
        addMessageToChat(message.role, message.content, message.timestamp);
    });
}

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;
    }
    
    if (!currentConversationId) {
        alert('Please start a conversation first by clicking "New Conversation"');
        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/user/crm/conversations/${currentConversationId}/message`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
        },
        body: JSON.stringify({
            message: message,
            metadata: { timestamp: new Date().toISOString() }
        })
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('HTTP ' + response.status);
        }
        return response.json();
    })
    .then(data => {
        hideTypingIndicator();
        
        if (data.success) {
            // Stream the AI response
            streamText(data.data.ai_message.content, streamingMessage);
        } 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');
    button.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Testing...';
    button.disabled = true;
    
    fetch('/dizzcall-ai/public/user/crm/test-connection', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
        }
    })
    .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';
            // 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';
            // 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';
        // 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);
    });
}
</script>
@endpush
