

<?php $__env->startSection('title', 'AI Voice Agent Dashboard'); ?>

<?php $__env->startSection('content'); ?>
<meta name="csrf-token" content="<?php echo e(csrf_token()); ?>">
<div class="container-fluid">
    <div class="row justify-content-center">
        <div class="col-md-10">
            <div class="card" style="border-radius: 20px; box-shadow: 0 20px 40px rgba(0,0,0,0.1);">
                <!-- Header -->
                <div class="card-header" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; border-radius: 20px 20px 0 0; border: none;">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <h4 class="mb-1"><i class="fas fa-robot"></i> AI Voice Agent Dashboard</h4>
                            <small>Your intelligent business assistant with live streaming</small>
                        </div>
                        <div>
                            <span id="statusIndicator" class="badge bg-warning">Connecting...</span>
                            <button class="btn btn-outline-light btn-sm ms-2" id="testConnection">
                                <i class="fas fa-wifi"></i> Test
                            </button>
                            <small class="text-light ms-2" id="connectionInfo">Click Test to check connection</small>
                            <button class="btn btn-outline-light btn-sm ms-1" id="turboMode" title="Turbo Mode - Faster Responses">
                                <i class="fas fa-bolt"></i> Turbo
                            </button>
                            <button class="btn btn-outline-light btn-sm ms-1" id="voiceMode" title="Voice Mode - Speak & Listen">
                                <i class="fas fa-microphone"></i> Voice
                            </button>
                            <button class="btn btn-outline-light btn-sm ms-1" id="voiceSettings" title="Voice Settings">
                                <i class="fas fa-cog"></i>
                            </button>
                            <button class="btn btn-outline-light btn-sm ms-1" id="continuousVoice" title="Continuous Voice Mode - Just Talk">
                                <i class="fas fa-microphone-alt"></i> Talk
                            </button>
                            <button class="btn btn-outline-light btn-sm ms-1" id="phoneMode" title="Phone Call Mode">
                                <i class="fas fa-phone"></i> Call
                            </button>
                        </div>
                    </div>
                </div>
                
                <!-- Chat Messages -->
                <div class="card-body p-0">
                    <div id="chatMessages" style="height: 60vh; overflow-y: auto; padding: 20px; background: #f8f9fa;">
                        <div class="text-center text-muted py-5">
                            <i class="fas fa-robot fa-3x mb-3" style="color: #667eea;"></i>
                            <h5>Welcome to DizzCall AI Voice Agent!</h5>
                            <p>I'm your intelligent business assistant with live streaming capabilities. How can I help you today?</p>
                            <div class="mt-3">
                                <span class="badge bg-primary me-2">Live Streaming</span>
                                <span class="badge bg-success me-2">Real-time AI</span>
                                <span class="badge bg-info">Voice Ready</span>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Typing Indicator -->
                    <div id="typingIndicator" class="text-center p-3" style="display: none; background: white; border-top: 1px solid #e9ecef;">
                        <i class="fas fa-robot text-primary"></i> AI is typing...
                    </div>
                </div>
                
                <!-- Input -->
                <div class="card-footer" style="background: white; border-top: 1px solid #e9ecef; border-radius: 0 0 20px 20px;">
                        <div class="input-group">
                            <input type="text" class="form-control" id="messageInput" placeholder="Type your message or speak..." style="border-radius: 25px; border: 2px solid #e9ecef; padding: 12px 20px;">
                            <button class="btn btn-primary" id="sendButton" style="border-radius: 25px; margin-left: 10px; padding: 12px 25px;">
                                <i class="fas fa-paper-plane"></i> Send
                            </button>
                            <button class="btn btn-outline-secondary" id="voiceInput" style="border-radius: 25px; margin-left: 5px; padding: 12px 15px;">
                                <i class="fas fa-microphone"></i>
                            </button>
                        </div>
                        <div class="mt-2 text-center">
                            <small class="text-muted" id="voiceStatus">Click microphone to speak</small>
                        </div>
                        
                        <!-- Voice Settings Panel -->
                        <div id="voiceSettingsPanel" class="mt-3 p-3" style="background: #f8f9fa; border-radius: 10px; display: none;">
                            <h6 class="mb-3">🎤 Voice Settings</h6>
                            <div class="row">
                                <div class="col-md-6">
                                    <label class="form-label">Voice Speed</label>
                                    <input type="range" class="form-range" id="voiceSpeed" min="0.5" max="4.0" step="0.1" value="3.0">
                                    <small class="text-muted">Current: <span id="speedValue">3.0x</span></small>
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">Voice Pitch</label>
                                    <input type="range" class="form-range" id="voicePitch" min="0.5" max="2.0" step="0.1" value="1.1">
                                    <small class="text-muted">Current: <span id="pitchValue">1.1</span></small>
                                </div>
                            </div>
                            <div class="row mt-2">
                                <div class="col-md-6">
                                    <label class="form-label">Voice Volume</label>
                                    <input type="range" class="form-range" id="voiceVolume" min="0.1" max="1.0" step="0.1" value="0.9">
                                    <small class="text-muted">Current: <span id="volumeValue">90%</span></small>
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">Voice Quality</label>
                                    <select class="form-select form-select-sm" id="voiceQuality">
                                        <option value="auto">Auto (Best Available)</option>
                                        <option value="premium">Premium Voices</option>
                                        <option value="natural">Natural Voices</option>
                                        <option value="fast">Fast Voices</option>
                                    </select>
                                </div>
                            </div>
                            <div class="mt-3">
                                <button class="btn btn-sm btn-outline-primary" id="testVoice">Test Voice</button>
                                <button class="btn btn-sm btn-outline-secondary" id="closeVoiceSettings">Close</button>
                            </div>
                        </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Phone Call Interface -->
<div id="phoneInterface" class="phone-interface" style="display: none;">
    <div class="phone-panel">
        <div class="phone-header">
            <h5><i class="fas fa-phone"></i> Phone Call Interface</h5>
            <button class="btn-close" id="closePhoneInterface">&times;</button>
        </div>
        <div class="phone-body">
            <div class="form-group mb-3">
                <label for="phoneNumber">Phone Number:</label>
                <input type="tel" id="phoneNumber" class="form-control" placeholder="+1234567890" required>
            </div>
            <div class="form-group mb-3">
                <label for="callMessage">Message (Optional):</label>
                <textarea id="callMessage" class="form-control" rows="3" placeholder="Enter a message for the call..."></textarea>
            </div>
            <div class="form-group mb-3">
                <div class="form-check">
                    <input class="form-check-input" type="checkbox" id="testMode" checked>
                    <label class="form-check-label" for="testMode">
                        Test Mode (No Trial Message)
                    </label>
                </div>
            </div>
            <div class="phone-actions">
                <button class="btn btn-success" id="makeCallBtn">
                    <i class="fas fa-phone"></i> Make Call
                </button>
                <button class="btn btn-secondary" id="cancelCallBtn" style="display: none;">
                    <i class="fas fa-phone-slash"></i> Cancel Call
                </button>
            </div>
            <div id="callStatus" class="call-status mt-3"></div>
        </div>
    </div>
</div>

<style>
.message {
    margin-bottom: 15px;
    display: flex;
    align-items: flex-start;
}

.message.user {
    justify-content: flex-end;
}

.message-content {
    max-width: 70%;
    padding: 12px 18px;
    border-radius: 18px;
    word-wrap: break-word;
}

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

.message.assistant .message-content {
    background: white;
    color: #333;
    border: 1px solid #e9ecef;
    box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}

.message-header {
    font-size: 0.8rem;
    opacity: 0.7;
    margin-bottom: 5px;
}

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

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

.btn-primary {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border: none;
}

.btn-primary:hover {
    transform: translateY(-2px);
    box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
}

.phone-interface {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0,0,0,0.5);
    z-index: 1001;
    display: flex;
    align-items: center;
    justify-content: center;
}

.phone-panel {
    background: white;
    border-radius: 15px;
    box-shadow: 0 10px 30px rgba(0,0,0,0.3);
    max-width: 400px;
    width: 90%;
    max-height: 80vh;
    overflow-y: auto;
}

.phone-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px;
    border-bottom: 1px solid #eee;
}

.phone-header h5 {
    margin: 0;
    color: #333;
}

.phone-body {
    padding: 20px;
}

.phone-actions {
    display: flex;
    gap: 10px;
    justify-content: center;
}

.call-status {
    text-align: center;
    padding: 10px;
    border-radius: 5px;
    font-weight: 500;
}

.call-status.success {
    background: #d4edda;
    color: #155724;
    border: 1px solid #c3e6cb;
}

.call-status.error {
    background: #f8d7da;
    color: #721c24;
    border: 1px solid #f5c6cb;
}

.call-status.info {
    background: #d1ecf1;
    color: #0c5460;
    border: 1px solid #bee5eb;
}
</style>

<script>
let isConnected = false;
let turboMode = false;
let voiceMode = false;
let continuousVoiceMode = false;
let recognition = null;
let synthesis = null;
let isListening = false;
let continuousListening = false;
let voiceSettings = {
    speed: 3.0, // Maximum possible speed for instant speech
    pitch: 1.1, // Adjusted pitch as requested
    volume: 0.9,
    quality: 'auto'
};
let selectedVoice = null;

document.addEventListener('DOMContentLoaded', function() {
    initializeVoice();
    setupEventListeners();
    
    // Show initial status
    const statusIndicator = document.getElementById('statusIndicator');
    const connectionInfo = document.getElementById('connectionInfo');
    statusIndicator.className = 'badge bg-info';
    statusIndicator.textContent = 'Ready';
    connectionInfo.textContent = 'Click Test to check AI connection';
    
    // Delay initial connection test to ensure page is fully loaded
    setTimeout(() => {
        testConnection();
    }, 1000);
});

function setupEventListeners() {
    document.getElementById('sendButton').addEventListener('click', sendMessage);
    document.getElementById('messageInput').addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            sendMessage();
        }
    });
    document.getElementById('testConnection').addEventListener('click', testConnection);
    document.getElementById('turboMode').addEventListener('click', toggleTurboMode);
    document.getElementById('voiceMode').addEventListener('click', toggleVoiceMode);
    document.getElementById('voiceInput').addEventListener('click', toggleVoiceInput);
    document.getElementById('voiceSettings').addEventListener('click', toggleVoiceSettings);
    document.getElementById('closeVoiceSettings').addEventListener('click', closeVoiceSettings);
    document.getElementById('testVoice').addEventListener('click', testVoice);
    document.getElementById('continuousVoice').addEventListener('click', toggleContinuousVoice);
    document.getElementById('phoneMode').addEventListener('click', togglePhoneInterface);
    document.getElementById('closePhoneInterface').addEventListener('click', closePhoneInterface);
    document.getElementById('makeCallBtn').addEventListener('click', makePhoneCall);
    document.getElementById('cancelCallBtn').addEventListener('click', cancelPhoneCall);
    
    // Voice settings controls
    document.getElementById('voiceSpeed').addEventListener('input', updateVoiceSpeed);
    document.getElementById('voicePitch').addEventListener('input', updateVoicePitch);
    document.getElementById('voiceVolume').addEventListener('input', updateVoiceVolume);
    document.getElementById('voiceQuality').addEventListener('change', updateVoiceQuality);
}

function testConnection() {
    const statusIndicator = document.getElementById('statusIndicator');
    const testButton = document.getElementById('testConnection');
    const connectionInfo = document.getElementById('connectionInfo');
    
    statusIndicator.className = 'badge bg-warning';
    statusIndicator.textContent = 'Testing...';
    testButton.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Testing...';
    testButton.disabled = true;
    connectionInfo.textContent = 'Testing AI connection...';
    
    fetch('/dizzcall-ai/public/ai-test-dashboard', {
        method: 'GET',
        headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json'
        }
    })
    .then(response => {
        console.log('Connection test response status:', response.status);
        console.log('Connection test response headers:', response.headers);
        if (!response.ok) {
            throw new Error('HTTP ' + response.status + ' - ' + response.statusText);
        }
        return response.json();
    })
    .then(data => {
        console.log('Connection test response:', data);
        if (data.success) {
            statusIndicator.className = 'badge bg-success';
            statusIndicator.textContent = 'Connected';
            isConnected = true;
            connectionInfo.textContent = `AI connected (${data.response_time_ms || 0}ms)`;
            addMessage('assistant', '✅ Connection successful! I\'m ready to help you.');
        } else {
            throw new Error(data.message || 'Connection failed');
        }
    })
    .catch(error => {
        console.error('Connection test error:', error);
        statusIndicator.className = 'badge bg-danger';
        statusIndicator.textContent = 'Disconnected';
        isConnected = false;
        connectionInfo.textContent = 'Connection failed - Click Test to retry';
        addMessage('assistant', '❌ Connection failed: ' + error.message);
        
        // Try alternative connection test
        setTimeout(() => {
            testAlternativeConnection();
        }, 2000);
    })
    .finally(() => {
        testButton.innerHTML = '<i class="fas fa-wifi"></i> Test';
        testButton.disabled = false;
    });
}

function testAlternativeConnection() {
    console.log('Trying alternative connection test...');
    const statusIndicator = document.getElementById('statusIndicator');
    const connectionInfo = document.getElementById('connectionInfo');
    
    // Try the original test route
    fetch('/dizzcall-ai/public/ai-test-dashboard', {
        method: 'GET',
        headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json'
        }
    })
    .then(response => {
        console.log('Alternative test response status:', response.status);
        if (!response.ok) {
            throw new Error('HTTP ' + response.status);
        }
        return response.json();
    })
    .then(data => {
        console.log('Alternative test response:', data);
        if (data.success) {
            statusIndicator.className = 'badge bg-success';
            statusIndicator.textContent = 'Connected';
            isConnected = true;
            connectionInfo.textContent = `AI connected (${data.response_time_ms || 0}ms)`;
            addMessage('assistant', '✅ Connection restored! AI is ready.');
        } else {
            throw new Error(data.message || 'Alternative connection failed');
        }
    })
    .catch(error => {
        console.error('Alternative connection test failed:', error);
        // Try ultra-simple test as final fallback
        setTimeout(() => {
            testUltraSimpleConnection();
        }, 1000);
    });
}

function testUltraSimpleConnection() {
    console.log('Trying ultra-simple connection test...');
    const statusIndicator = document.getElementById('statusIndicator');
    const connectionInfo = document.getElementById('connectionInfo');
    
    // Try the ultra-simple test route
    fetch('/dizzcall-ai/public/ai-test-dashboard', {
        method: 'GET',
        headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json'
        }
    })
    .then(response => {
        console.log('Ultra-simple test response status:', response.status);
        if (!response.ok) {
            throw new Error('HTTP ' + response.status);
        }
        return response.json();
    })
    .then(data => {
        console.log('Ultra-simple test response:', data);
        if (data.success) {
            statusIndicator.className = 'badge bg-success';
            statusIndicator.textContent = 'Connected';
            isConnected = true;
            connectionInfo.textContent = `AI connected (${data.response_time_ms || 1}ms)`;
            addMessage('assistant', '✅ Connection established! AI is ready.');
        } else {
            throw new Error(data.message || 'Ultra-simple connection failed');
        }
    })
    .catch(error => {
        console.error('Ultra-simple connection test failed:', error);
        // Final fallback - assume connected if all tests fail
        statusIndicator.className = 'badge bg-warning';
        statusIndicator.textContent = 'Limited';
        isConnected = true;
        connectionInfo.textContent = 'Limited connection - AI may work';
        addMessage('assistant', '⚠️ Limited connection. AI may still work for basic functions.');
    });
}

function sendMessage() {
    const messageInput = document.getElementById('messageInput');
    const message = messageInput.value.trim();
    
    if (!message) {
        return;
    }
    
    // Add user message immediately
    addMessage('user', message);
    messageInput.value = ''; // Clear input immediately
    
    // Show typing indicator for 10ms only
    showTypingIndicator();
    setTimeout(hideTypingIndicator, 10);
    
    // Send to AI with word streaming
    fetch(`/dizzcall-ai/public/ai-stream-words?message=${encodeURIComponent(message)}`, {
        method: 'GET',
        headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json'
        }
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('HTTP ' + response.status);
        }
        return response.json();
    })
    .then(data => {
        console.log('AI Response:', data);
        
        if (data.success) {
            const words = data.words || [];
            const fullText = data.full_text || '';
            
            // Start streaming words immediately
            streamWordsRealtime(words);
            
            // Start speaking immediately
            if (voiceMode) {
                speakText(fullText);
            }
        } else {
            addMessage('assistant', '❌ Error: ' + (data.error || 'Unknown error'));
        }
    })
    .catch(error => {
        console.error('Error:', error);
        addMessage('assistant', '❌ Connection Error: ' + error.message);
    });
}

function addMessage(role, content) {
    const chatMessages = document.getElementById('chatMessages');
    
    // Clear welcome message if it exists
    if (chatMessages.querySelector('.text-center')) {
        chatMessages.innerHTML = '';
    }
    
    const messageDiv = document.createElement('div');
    messageDiv.className = `message ${role}`;
    
    const time = new Date().toLocaleTimeString();
    
    messageDiv.innerHTML = `
        <div>
            <div class="message-header">${role === 'user' ? 'You' : 'AI Assistant'} • ${time}</div>
            <div class="message-content">${content}</div>
        </div>
    `;
    
    chatMessages.appendChild(messageDiv);
    chatMessages.scrollTop = chatMessages.scrollHeight;
}

// Real-time word streaming with ZERO delays
function streamWordsRealtime(words) {
    const chatMessages = document.getElementById('chatMessages');
    const messageDiv = document.createElement('div');
    messageDiv.className = 'message assistant';
    
    const time = new Date().toLocaleTimeString();
    
    messageDiv.innerHTML = `
        <div>
            <div class="message-header">AI Assistant • ${time}</div>
            <div class="message-content streaming-text" id="streamingText"></div>
        </div>
    `;
    
    chatMessages.appendChild(messageDiv);
    
    const textElement = messageDiv.querySelector('#streamingText');
    let wordIndex = 0;
    
    // INSTANT word streaming - no delays
    const streamWords = () => {
        if (wordIndex < words.length) {
            // Add the next word immediately
            if (wordIndex > 0) {
                textElement.textContent += ' ';
            }
            textElement.textContent += words[wordIndex];
            wordIndex++;
            
            // Auto-scroll to bottom
            chatMessages.scrollTop = chatMessages.scrollHeight;
            
            // Continue immediately (no delay)
            requestAnimationFrame(streamWords);
        } else {
            textElement.classList.remove('streaming-text');
        }
    };
    
    // Start streaming immediately
    streamWords();
}

function streamMessage(role, content) {
    const chatMessages = document.getElementById('chatMessages');
    const messageDiv = document.createElement('div');
    messageDiv.className = `message ${role}`;
    
    const time = new Date().toLocaleTimeString();
    
    
    messageDiv.innerHTML = `
        <div>
            <div class="message-header">${role === 'user' ? 'You' : 'AI Assistant'} • ${time}</div>
            <div class="message-content streaming-text" id="streamingText"></div>
        </div>
    `;
    
    chatMessages.appendChild(messageDiv);
    
    // Stream the text word by word for better readability
    const textElement = messageDiv.querySelector('#streamingText');
    const words = content.split(' ');
    let wordIndex = 0;
    
    const streamInterval = setInterval(() => {
        if (wordIndex < words.length) {
            // Add the next word
            if (wordIndex > 0) {
                textElement.textContent += ' ';
            }
            textElement.textContent += words[wordIndex];
            wordIndex++;
            
            // Auto-scroll to bottom
            chatMessages.scrollTop = chatMessages.scrollHeight;
        } else {
            clearInterval(streamInterval);
            textElement.classList.remove('streaming-text');
        }
    }, turboMode ? 10 : 20); // Ultra-fast: 10ms per word, Fast: 20ms per word
}

function showTypingIndicator() {
    document.getElementById('typingIndicator').style.display = 'block';
}

function hideTypingIndicator() {
    document.getElementById('typingIndicator').style.display = 'none';
}

function initializeVoice() {
    // Initialize Speech Recognition
    if ('webkitSpeechRecognition' in window || 'SpeechRecognition' in window) {
        const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
        recognition = new SpeechRecognition();
        recognition.continuous = true; // Enable continuous listening
        recognition.interimResults = false;
        recognition.lang = 'en-US';
        
        recognition.onstart = function() {
            isListening = true;
            if (continuousVoiceMode) {
                updateVoiceStatus('Continuous listening active - Just talk!', 'text-success');
            } else {
                updateVoiceStatus('Listening... Speak now!', 'text-primary');
            }
            document.getElementById('voiceInput').innerHTML = '<i class="fas fa-stop"></i>';
            document.getElementById('voiceInput').classList.add('btn-danger');
        };
        
        recognition.onresult = function(event) {
            const transcript = event.results[event.results.length - 1][0].transcript;
            
            if (continuousVoiceMode) {
                // In continuous mode, automatically send the message
                document.getElementById('messageInput').value = transcript;
                sendMessage();
                updateVoiceStatus('Message sent! Continue talking...', 'text-success');
            } else {
                // In manual mode, just fill the input
                document.getElementById('messageInput').value = transcript;
                updateVoiceStatus('Speech recognized! Click Send or speak again.', 'text-success');
            }
        };
        
        recognition.onerror = function(event) {
            console.error('Speech recognition error:', event.error);
            updateVoiceStatus('Speech recognition error: ' + event.error, 'text-danger');
        };
        
        recognition.onend = function() {
            isListening = false;
            document.getElementById('voiceInput').innerHTML = '<i class="fas fa-microphone"></i>';
            document.getElementById('voiceInput').classList.remove('btn-danger');
            
            if (continuousVoiceMode && continuousListening) {
                // Restart continuous listening
                setTimeout(() => {
                    if (continuousListening) {
                        recognition.start();
                    }
                }, 100);
            } else if (!voiceMode) {
                updateVoiceStatus('Click microphone to speak', 'text-muted');
            }
        };
    } else {
        updateVoiceStatus('Speech recognition not supported in this browser', 'text-warning');
    }
    
    // Initialize Speech Synthesis
    if ('speechSynthesis' in window) {
        synthesis = window.speechSynthesis;
        
        // Load voices and select the best one
        loadVoices();
        
        // Some browsers load voices asynchronously
        if (synthesis.onvoiceschanged !== undefined) {
            synthesis.onvoiceschanged = loadVoices;
        }
    } else {
        console.warn('Speech synthesis not supported');
    }
}

function toggleVoiceMode() {
    voiceMode = !voiceMode;
    const voiceButton = document.getElementById('voiceMode');
    
    if (voiceMode) {
        voiceButton.classList.remove('btn-outline-light');
        voiceButton.classList.add('btn-success');
        voiceButton.innerHTML = '<i class="fas fa-volume-up"></i> Voice ON';
        addMessage('assistant', '🎤 Enhanced voice mode activated! I will speak with realistic, fast speech.');
        updateVoiceStatus(`Voice mode ON - ${selectedVoice ? selectedVoice.name : 'Default voice'}`, 'text-success');
    } else {
        voiceButton.classList.remove('btn-success');
        voiceButton.classList.add('btn-outline-light');
        voiceButton.innerHTML = '<i class="fas fa-microphone"></i> Voice';
        addMessage('assistant', '🔇 Voice mode deactivated. Text responses only.');
        updateVoiceStatus('Click microphone to speak', 'text-muted');
    }
}

function toggleVoiceInput() {
    if (!recognition) {
        updateVoiceStatus('Speech recognition not available', 'text-danger');
        return;
    }
    
    if (continuousVoiceMode) {
        // In continuous mode, toggle the continuous listening
        if (continuousListening) {
            continuousListening = false;
            recognition.stop();
            updateVoiceStatus('Continuous listening paused', 'text-warning');
        } else {
            continuousListening = true;
            recognition.start();
            updateVoiceStatus('Continuous listening resumed', 'text-success');
        }
    } else {
        // In manual mode, toggle single listening
        if (isListening) {
            recognition.stop();
        } else {
            recognition.start();
        }
    }
}

function loadVoices() {
    if (!synthesis) return;
    
    const voices = synthesis.getVoices();
    console.log('Available voices:', voices.length);
    
    // Select the best voice based on quality setting
    selectedVoice = selectBestVoice(voices, voiceSettings.quality);
    
    if (selectedVoice) {
        console.log('Selected voice:', selectedVoice.name, selectedVoice.lang);
        updateVoiceStatus(`Voice: ${selectedVoice.name}`, 'text-success');
    }
}

function selectBestVoice(voices, quality) {
    const englishVoices = voices.filter(voice => 
        voice.lang.startsWith('en') && !voice.localService
    );
    
    if (englishVoices.length === 0) {
        return voices.find(voice => voice.lang.startsWith('en')) || voices[0];
    }
    
    switch (quality) {
        case 'premium':
            return englishVoices.find(voice => 
                voice.name.includes('Google') || 
                voice.name.includes('Microsoft') ||
                voice.name.includes('Amazon') ||
                voice.name.includes('Neural')
            ) || englishVoices[0];
            
        case 'natural':
            return englishVoices.find(voice => 
                voice.name.includes('Natural') ||
                voice.name.includes('Enhanced') ||
                voice.name.includes('Premium')
            ) || englishVoices[0];
            
        case 'fast':
            return englishVoices.find(voice => 
                voice.name.includes('Fast') ||
                voice.name.includes('Rapid')
            ) || englishVoices[0];
            
        default: // auto
            return englishVoices.find(voice => 
                voice.name.includes('Google') || 
                voice.name.includes('Microsoft') ||
                voice.name.includes('Neural')
            ) || englishVoices[0];
    }
}

function speakText(text) {
    if (!synthesis || !voiceMode) return;
    
    // Stop any current speech
    synthesis.cancel();
    
    const utterance = new SpeechSynthesisUtterance(text);
    
    // Apply voice settings
    utterance.rate = voiceSettings.speed;
    utterance.pitch = voiceSettings.pitch;
    utterance.volume = voiceSettings.volume;
    
    // Use selected voice
    if (selectedVoice) {
        utterance.voice = selectedVoice;
    }
    
    utterance.onstart = function() {
        updateVoiceStatus('Speaking...', 'text-info');
    };
    
    utterance.onend = function() {
        updateVoiceStatus(voiceMode ? 'Ready to listen' : 'Click microphone to speak', 'text-muted');
    };
    
    utterance.onerror = function(event) {
        console.error('Speech synthesis error:', event.error);
        updateVoiceStatus('Voice error: ' + event.error, 'text-danger');
    };
    
    synthesis.speak(utterance);
}

function updateVoiceStatus(message, className) {
    const statusElement = document.getElementById('voiceStatus');
    statusElement.textContent = message;
    statusElement.className = `text-muted ${className}`;
}

function toggleVoiceSettings() {
    const panel = document.getElementById('voiceSettingsPanel');
    panel.style.display = panel.style.display === 'none' ? 'block' : 'none';
}

function closeVoiceSettings() {
    document.getElementById('voiceSettingsPanel').style.display = 'none';
}

function updateVoiceSpeed() {
    const speed = parseFloat(document.getElementById('voiceSpeed').value);
    voiceSettings.speed = speed;
    document.getElementById('speedValue').textContent = speed.toFixed(1) + 'x';
}

function updateVoicePitch() {
    const pitch = parseFloat(document.getElementById('voicePitch').value);
    voiceSettings.pitch = pitch;
    document.getElementById('pitchValue').textContent = pitch.toFixed(1);
}

function updateVoiceVolume() {
    const volume = parseFloat(document.getElementById('voiceVolume').value);
    voiceSettings.volume = volume;
    document.getElementById('volumeValue').textContent = Math.round(volume * 100) + '%';
}

function updateVoiceQuality() {
    const quality = document.getElementById('voiceQuality').value;
    voiceSettings.quality = quality;
    
    // Reload voices with new quality setting
    if (synthesis) {
        const voices = synthesis.getVoices();
        selectedVoice = selectBestVoice(voices, quality);
        if (selectedVoice) {
            updateVoiceStatus(`Voice: ${selectedVoice.name}`, 'text-success');
        }
    }
}

function testVoice() {
    const testText = "Hello! This is a test of the enhanced voice system. I can speak faster and more naturally now.";
    speakText(testText);
}

function toggleContinuousVoice() {
    continuousVoiceMode = !continuousVoiceMode;
    const continuousButton = document.getElementById('continuousVoice');
    
    if (continuousVoiceMode) {
        continuousButton.classList.remove('btn-outline-light');
        continuousButton.classList.add('btn-info');
        continuousButton.innerHTML = '<i class="fas fa-microphone-alt"></i> Talk ON';
        
        // Enable voice mode automatically
        if (!voiceMode) {
            voiceMode = true;
            document.getElementById('voiceMode').classList.remove('btn-outline-light');
            document.getElementById('voiceMode').classList.add('btn-success');
            document.getElementById('voiceMode').innerHTML = '<i class="fas fa-volume-up"></i> Voice ON';
        }
        
        // Start continuous listening
        continuousListening = true;
        if (recognition && !isListening) {
            recognition.start();
        }
        
        addMessage('assistant', '🎤 Continuous voice mode activated! Just talk naturally - I\'ll respond automatically.');
        updateVoiceStatus('Continuous listening active - Just talk!', 'text-success');
    } else {
        continuousButton.classList.remove('btn-info');
        continuousButton.classList.add('btn-outline-light');
        continuousButton.innerHTML = '<i class="fas fa-microphone-alt"></i> Talk';
        
        // Stop continuous listening
        continuousListening = false;
        if (recognition && isListening) {
            recognition.stop();
        }
        
        addMessage('assistant', '🔇 Continuous voice mode deactivated. Use manual voice or chat.');
        updateVoiceStatus('Click microphone to speak', 'text-muted');
    }
}

function toggleTurboMode() {
    turboMode = !turboMode;
    const turboButton = document.getElementById('turboMode');
    
    if (turboMode) {
        turboButton.classList.remove('btn-outline-light');
        turboButton.classList.add('btn-warning');
        turboButton.innerHTML = '<i class="fas fa-bolt"></i> Turbo ON';
        addMessage('assistant', '⚡ Turbo mode activated! Responses will be much faster.');
    } else {
        turboButton.classList.remove('btn-warning');
        turboButton.classList.add('btn-outline-light');
        turboButton.innerHTML = '<i class="fas fa-bolt"></i> Turbo';
        addMessage('assistant', '🐌 Turbo mode deactivated. Back to normal speed.');
    }
}

// Phone Interface Functions
function togglePhoneInterface() {
    const phoneInterface = document.getElementById('phoneInterface');
    phoneInterface.style.display = phoneInterface.style.display === 'none' ? 'flex' : 'none';
}

function closePhoneInterface() {
    document.getElementById('phoneInterface').style.display = 'none';
}

async function makePhoneCall() {
    const phoneNumber = document.getElementById('phoneNumber').value.trim();
    const callMessage = document.getElementById('callMessage').value.trim();
    const testMode = document.getElementById('testMode').checked;
    const makeCallBtn = document.getElementById('makeCallBtn');
    const cancelCallBtn = document.getElementById('cancelCallBtn');
    const callStatus = document.getElementById('callStatus');
    
    if (!phoneNumber) {
        callStatus.innerHTML = 'Please enter a phone number';
        callStatus.className = 'call-status error';
        return;
    }
    
    // Update UI
    makeCallBtn.disabled = true;
    makeCallBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Calling...';
    cancelCallBtn.style.display = 'inline-block';
    callStatus.innerHTML = 'Initiating call...';
    callStatus.className = 'call-status info';
    
    try {
        const response = await fetch('/dizzcall-ai/public/test-make-call', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                to: phoneNumber,
                message: callMessage || 'Hello! This is DizzCall AI calling you.',
                test_mode: testMode
            })
        });
        
        // Check if response is ok
        if (!response.ok) {
            throw new Error(`HTTP ${response.status}: ${response.statusText}`);
        }
        
        // Check if response is JSON
        const contentType = response.headers.get('content-type');
        if (!contentType || !contentType.includes('application/json')) {
            const text = await response.text();
            throw new Error(`Expected JSON but got: ${text.substring(0, 100)}...`);
        }
        
        const data = await response.json();
        
        if (data.success) {
            let statusMessage = `✅ ${data.message}<br>Call ID: ${data.call_sid || 'N/A'}`;
            
            if (data.test_mode) {
                statusMessage += '<br><small class="text-info">Test Mode: No actual call made</small>';
            } else if (data.trial_message) {
                statusMessage += '<br><small class="text-warning">Trial Account: Upgrade message will play</small>';
            }
            
            callStatus.innerHTML = statusMessage;
            callStatus.className = 'call-status success';
            
            // Start monitoring call status if call_sid exists and not in test mode
            if (data.call_sid && !data.test_mode) {
                monitorCallStatus(data.call_sid);
            }
        } else {
            callStatus.innerHTML = `❌ Call failed: ${data.error || 'Unknown error'}`;
            callStatus.className = 'call-status error';
        }
    } catch (error) {
        callStatus.innerHTML = `❌ Error: ${error.message}`;
        callStatus.className = 'call-status error';
        console.error('Phone call error:', error);
    } finally {
        makeCallBtn.disabled = false;
        makeCallBtn.innerHTML = '<i class="fas fa-phone"></i> Make Call';
        cancelCallBtn.style.display = 'none';
    }
}

function cancelPhoneCall() {
    const makeCallBtn = document.getElementById('makeCallBtn');
    const cancelCallBtn = document.getElementById('cancelCallBtn');
    const callStatus = document.getElementById('callStatus');
    
    makeCallBtn.disabled = false;
    makeCallBtn.innerHTML = '<i class="fas fa-phone"></i> Make Call';
    cancelCallBtn.style.display = 'none';
    callStatus.innerHTML = 'Call cancelled';
    callStatus.className = 'call-status info';
}

async function monitorCallStatus(callSid) {
    const callStatus = document.getElementById('callStatus');
    
    try {
        const response = await fetch(`/api/twilio/call-status?call_sid=${callSid}`, {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json'
            }
        });
        
        const data = await response.json();
        
        if (data.success) {
            let statusText = '';
            let statusClass = 'info';
            
            switch (data.status) {
                case 'queued':
                    statusText = 'Call is queued...';
                    break;
                case 'ringing':
                    statusText = 'Call is ringing...';
                    break;
                case 'in-progress':
                    statusText = 'Call is in progress...';
                    statusClass = 'success';
                    break;
                case 'completed':
                    statusText = `Call completed! Duration: ${data.duration || 0} seconds`;
                    statusClass = 'success';
                    break;
                case 'busy':
                    statusText = 'Line is busy';
                    statusClass = 'error';
                    break;
                case 'no-answer':
                    statusText = 'No answer';
                    statusClass = 'error';
                    break;
                case 'failed':
                    statusText = 'Call failed';
                    statusClass = 'error';
                    break;
                default:
                    statusText = `Call status: ${data.status}`;
            }
            
            callStatus.innerHTML = statusText;
            callStatus.className = `call-status ${statusClass}`;
            
            // Continue monitoring if call is still active
            if (['queued', 'ringing', 'in-progress'].includes(data.status)) {
                setTimeout(() => monitorCallStatus(callSid), 2000);
            }
        }
    } catch (error) {
        console.error('Error monitoring call status:', error);
    }
}
</script>
<?php $__env->stopSection(); ?>

<?php echo $__env->make('FrontUser.layouts.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH D:\xampp\htdocs\dizzcall-ai\resources\views/FrontUser/ai/simple-chat.blade.php ENDPATH**/ ?>