<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>DizzCall AI - Client Test Dashboard</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <style>
        .gradient-bg {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        }
        .card-hover {
            transition: transform 0.3s ease, box-shadow 0.3s ease;
        }
        .card-hover:hover {
            transform: translateY(-5px);
            box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
        }
        .typing-indicator {
            display: inline-block;
            width: 8px;
            height: 8px;
            border-radius: 50%;
            background-color: #667eea;
            animation: typing 1.4s infinite ease-in-out;
        }
        .typing-indicator:nth-child(1) { animation-delay: -0.32s; }
        .typing-indicator:nth-child(2) { animation-delay: -0.16s; }
        @keyframes typing {
            0%, 80%, 100% { transform: scale(0); }
            40% { transform: scale(1); }
        }
    </style>
</head>
<body class="bg-gray-100 min-h-screen">
    <!-- Header -->
    <div class="gradient-bg text-white py-6">
        <div class="container mx-auto px-4">
            <h1 class="text-3xl font-bold text-center">🤖 DizzCall AI - Client Test Dashboard</h1>
            <p class="text-center mt-2 text-blue-100">Test your AI phone system before going live</p>
        </div>
    </div>

    <div class="container mx-auto px-4 py-8">
        <!-- Status Cards -->
        <div class="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
            <div class="bg-white rounded-lg shadow-lg p-6 card-hover">
                <div class="flex items-center">
                    <div class="p-3 rounded-full bg-green-100 text-green-600">
                        <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                        </svg>
                    </div>
                    <div class="ml-4">
                        <h3 class="text-lg font-semibold text-gray-900">System Status</h3>
                        <p id="system-status" class="text-gray-600">Checking...</p>
                    </div>
                </div>
            </div>

            <div class="bg-white rounded-lg shadow-lg p-6 card-hover">
                <div class="flex items-center">
                    <div class="p-3 rounded-full bg-blue-100 text-blue-600">
                        <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z"></path>
                        </svg>
                    </div>
                    <div class="ml-4">
                        <h3 class="text-lg font-semibold text-gray-900">Response Time</h3>
                        <p id="response-time" class="text-gray-600">Testing...</p>
                    </div>
                </div>
            </div>

            <div class="bg-white rounded-lg shadow-lg p-6 card-hover">
                <div class="flex items-center">
                    <div class="p-3 rounded-full bg-purple-100 text-purple-600">
                        <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z"></path>
                        </svg>
                    </div>
                    <div class="ml-4">
                        <h3 class="text-lg font-semibold text-gray-900">Success Rate</h3>
                        <p id="success-rate" class="text-gray-600">Calculating...</p>
                    </div>
                </div>
            </div>
        </div>

        <!-- Main Testing Area -->
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-8">
            <!-- Phone Call Simulator -->
            <div class="bg-white rounded-lg shadow-lg p-6">
                <h2 class="text-2xl font-bold text-gray-900 mb-6">📞 Phone Call Simulator</h2>
                <p class="text-gray-600 mb-6">Simulate what happens when someone calls your Twilio number</p>
                
                <form id="phone-simulator-form" class="space-y-4">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">Caller Phone Number</label>
                        <input type="text" id="caller-phone" name="caller_phone" 
                               value="+1234567890" 
                               class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">What the caller says</label>
                        <textarea id="caller-message" name="message" rows="3" 
                                  placeholder="Hello, I'm interested in your services..."
                                  class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"></textarea>
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">Conversation Type</label>
                        <select id="conversation-type" name="conversation_type" 
                                class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                            <option value="general">General Inquiry</option>
                            <option value="sales">Sales</option>
                            <option value="support">Support</option>
                            <option value="technical">Technical</option>
                        </select>
                    </div>
                    
                    <button type="submit" 
                            class="w-full bg-blue-600 text-white py-2 px-4 rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500">
                        🚀 Simulate Phone Call
                    </button>
                </form>
                
                <div id="phone-result" class="mt-6 hidden">
                    <h3 class="text-lg font-semibold text-gray-900 mb-3">AI Response:</h3>
                    <div class="bg-gray-50 p-4 rounded-md">
                        <p id="phone-ai-response" class="text-gray-800"></p>
                        <div class="mt-2 text-sm text-gray-600">
                            <span id="phone-response-time"></span> | 
                            <span id="phone-model-used"></span>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Quick Test Messages -->
            <div class="bg-white rounded-lg shadow-lg p-6">
                <h2 class="text-2xl font-bold text-gray-900 mb-6">⚡ Quick Test Messages</h2>
                <p class="text-gray-600 mb-6">Test common customer scenarios</p>
                
                <div class="grid grid-cols-1 gap-3">
                    <button onclick="testMessage('Hello, I need help with your services')" 
                            class="text-left p-3 bg-gray-50 hover:bg-gray-100 rounded-md border border-gray-200">
                        <strong>Greeting:</strong> "Hello, I need help with your services"
                    </button>
                    
                    <button onclick="testMessage('What are your prices for software development?')" 
                            class="text-left p-3 bg-gray-50 hover:bg-gray-100 rounded-md border border-gray-200">
                        <strong>Pricing:</strong> "What are your prices for software development?"
                    </button>
                    
                    <button onclick="testMessage('I need technical support for my project')" 
                            class="text-left p-3 bg-gray-50 hover:bg-gray-100 rounded-md border border-gray-200">
                        <strong>Support:</strong> "I need technical support for my project"
                    </button>
                    
                    <button onclick="testMessage('Can I schedule a meeting with your team?')" 
                            class="text-left p-3 bg-gray-50 hover:bg-gray-100 rounded-md border border-gray-200">
                        <strong>Scheduling:</strong> "Can I schedule a meeting with your team?"
                    </button>
                    
                    <button onclick="testMessage('Do you work with React and Laravel?')" 
                            class="text-left p-3 bg-gray-50 hover:bg-gray-100 rounded-md border border-gray-200">
                        <strong>Technical:</strong> "Do you work with React and Laravel?"
                    </button>
                </div>
                
                <div id="quick-test-result" class="mt-6 hidden">
                    <h3 class="text-lg font-semibold text-gray-900 mb-3">AI Response:</h3>
                    <div class="bg-gray-50 p-4 rounded-md">
                        <p id="quick-ai-response" class="text-gray-800"></p>
                        <div class="mt-2 text-sm text-gray-600">
                            <span id="quick-response-time"></span> | 
                            <span id="quick-model-used"></span>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Advanced Testing -->
        <div class="mt-8 bg-white rounded-lg shadow-lg p-6">
            <h2 class="text-2xl font-bold text-gray-900 mb-6">🔬 Advanced Testing</h2>
            
            <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                <button onclick="testConnection()" 
                        class="p-4 bg-green-50 hover:bg-green-100 rounded-lg border border-green-200 text-center">
                    <div class="text-green-600 text-2xl mb-2">🔌</div>
                    <h3 class="font-semibold text-green-800">Test Connection</h3>
                    <p class="text-sm text-green-600">Check AI system status</p>
                </button>
                
                <button onclick="testScenarios()" 
                        class="p-4 bg-blue-50 hover:bg-blue-100 rounded-lg border border-blue-200 text-center">
                    <div class="text-blue-600 text-2xl mb-2">🎭</div>
                    <h3 class="font-semibold text-blue-800">Test Scenarios</h3>
                    <p class="text-sm text-blue-600">Run all test scenarios</p>
                </button>
                
                <button onclick="getPerformance()" 
                        class="p-4 bg-purple-50 hover:bg-purple-100 rounded-lg border border-purple-200 text-center">
                    <div class="text-purple-600 text-2xl mb-2">📊</div>
                    <h3 class="font-semibold text-purple-800">Performance</h3>
                    <p class="text-sm text-purple-600">Get system metrics</p>
                </button>
            </div>
        </div>

        <!-- Results Log -->
        <div class="mt-8 bg-white rounded-lg shadow-lg p-6">
            <h2 class="text-2xl font-bold text-gray-900 mb-6">📋 Test Results Log</h2>
            <div id="results-log" class="space-y-3 max-h-96 overflow-y-auto">
                <p class="text-gray-500 text-center py-4">No tests run yet. Start testing above!</p>
            </div>
        </div>
    </div>

    <script>
        const API_BASE = '/api/client-test';
        
        // Initialize dashboard
        document.addEventListener('DOMContentLoaded', function() {
            testConnection();
            getPerformance();
        });

        // Test connection
        async function testConnection() {
            try {
                const response = await axios.get(`${API_BASE}/connection`);
                const data = response.data;
                
                document.getElementById('system-status').textContent = 
                    data.success ? '✅ Operational' : '❌ Offline';
                document.getElementById('system-status').className = 
                    data.success ? 'text-green-600' : 'text-red-600';
                
                addToLog('Connection Test', data.success ? 'SUCCESS' : 'FAILED', data.message);
            } catch (error) {
                document.getElementById('system-status').textContent = '❌ Error';
                document.getElementById('system-status').className = 'text-red-600';
                addToLog('Connection Test', 'ERROR', error.message);
            }
        }

        // Test performance
        async function getPerformance() {
            try {
                const response = await axios.get(`${API_BASE}/performance`);
                const data = response.data;
                
                if (data.success) {
                    document.getElementById('response-time').textContent = 
                        `${data.data.ai_response_time_ms}ms`;
                    document.getElementById('success-rate').textContent = 
                        `${data.data.success_rate}%`;
                }
            } catch (error) {
                console.error('Performance test failed:', error);
            }
        }

        // Test scenarios
        async function testScenarios() {
            try {
                showLoading('Testing all scenarios...');
                const response = await axios.get(`${API_BASE}/scenarios`);
                const data = response.data;
                
                if (data.success) {
                    addToLog('Scenario Test', 'SUCCESS', 
                        `Tested ${data.data.total_scenarios} scenarios`);
                    
                    // Show results in a modal or expandable section
                    showScenarioResults(data.data.results);
                } else {
                    addToLog('Scenario Test', 'FAILED', data.message);
                }
            } catch (error) {
                addToLog('Scenario Test', 'ERROR', error.message);
            } finally {
                hideLoading();
            }
        }

        // Phone simulator form
        document.getElementById('phone-simulator-form').addEventListener('submit', async function(e) {
            e.preventDefault();
            
            const formData = new FormData(e.target);
            const data = Object.fromEntries(formData);
            
            try {
                showLoading('Simulating phone call...');
                const response = await axios.post(`${API_BASE}/simulate-call`, data);
                const result = response.data;
                
                if (result.success) {
                    document.getElementById('phone-ai-response').textContent = result.data.ai_response;
                    document.getElementById('phone-response-time').textContent = 
                        `Response time: ${result.data.response_time_ms}ms`;
                    document.getElementById('phone-model-used').textContent = 
                        `Model: ${result.data.model_used}`;
                    document.getElementById('phone-result').classList.remove('hidden');
                    
                    addToLog('Phone Simulation', 'SUCCESS', 
                        `Caller: ${result.data.caller_phone} | Response: ${result.data.ai_response.substring(0, 50)}...`);
                } else {
                    addToLog('Phone Simulation', 'FAILED', result.message);
                }
            } catch (error) {
                addToLog('Phone Simulation', 'ERROR', error.message);
            } finally {
                hideLoading();
            }
        });

        // Quick test message
        async function testMessage(message) {
            try {
                showLoading('Testing message...');
                const response = await axios.post(`${API_BASE}/simulate-call`, {
                    caller_phone: '+1234567890',
                    message: message,
                    conversation_type: 'general'
                });
                const result = response.data;
                
                if (result.success) {
                    document.getElementById('quick-ai-response').textContent = result.data.ai_response;
                    document.getElementById('quick-response-time').textContent = 
                        `Response time: ${result.data.response_time_ms}ms`;
                    document.getElementById('quick-model-used').textContent = 
                        `Model: ${result.data.model_used}`;
                    document.getElementById('quick-test-result').classList.remove('hidden');
                    
                    addToLog('Quick Test', 'SUCCESS', 
                        `Message: "${message}" | Response: ${result.data.ai_response.substring(0, 50)}...`);
                } else {
                    addToLog('Quick Test', 'FAILED', result.message);
                }
            } catch (error) {
                addToLog('Quick Test', 'ERROR', error.message);
            } finally {
                hideLoading();
            }
        }

        // Show scenario results
        function showScenarioResults(results) {
            const log = document.getElementById('results-log');
            const scenarioDiv = document.createElement('div');
            scenarioDiv.className = 'bg-blue-50 p-4 rounded-md mb-4';
            scenarioDiv.innerHTML = `
                <h4 class="font-semibold text-blue-800 mb-2">Scenario Test Results:</h4>
                <div class="space-y-2">
                    ${results.map(r => `
                        <div class="text-sm">
                            <strong>${r.scenario}:</strong> ${r.ai_response.substring(0, 100)}...
                            <span class="text-gray-500">(${r.response_time_ms}ms)</span>
                        </div>
                    `).join('')}
                </div>
            `;
            log.insertBefore(scenarioDiv, log.firstChild);
        }

        // Add to log
        function addToLog(test, status, message) {
            const log = document.getElementById('results-log');
            const logEntry = document.createElement('div');
            logEntry.className = `p-3 rounded-md border-l-4 ${
                status === 'SUCCESS' ? 'bg-green-50 border-green-400' :
                status === 'FAILED' ? 'bg-red-50 border-red-400' :
                'bg-yellow-50 border-yellow-400'
            }`;
            
            const timestamp = new Date().toLocaleTimeString();
            logEntry.innerHTML = `
                <div class="flex justify-between items-start">
                    <div>
                        <span class="font-semibold">${test}</span>
                        <span class="ml-2 px-2 py-1 text-xs rounded ${
                            status === 'SUCCESS' ? 'bg-green-200 text-green-800' :
                            status === 'FAILED' ? 'bg-red-200 text-red-800' :
                            'bg-yellow-200 text-yellow-800'
                        }">${status}</span>
                    </div>
                    <span class="text-xs text-gray-500">${timestamp}</span>
                </div>
                <p class="text-sm text-gray-700 mt-1">${message}</p>
            `;
            
            // Remove "No tests run yet" message
            const noTestsMsg = log.querySelector('p.text-gray-500.text-center');
            if (noTestsMsg) {
                noTestsMsg.remove();
            }
            
            log.insertBefore(logEntry, log.firstChild);
        }

        // Loading indicator
        function showLoading(message) {
            const loadingDiv = document.createElement('div');
            loadingDiv.id = 'loading-indicator';
            loadingDiv.className = 'fixed top-4 right-4 bg-blue-600 text-white px-4 py-2 rounded-md shadow-lg z-50';
            loadingDiv.innerHTML = `
                <div class="flex items-center">
                    <div class="typing-indicator mr-2"></div>
                    <div class="typing-indicator mr-2"></div>
                    <div class="typing-indicator mr-2"></div>
                    <span>${message}</span>
                </div>
            `;
            document.body.appendChild(loadingDiv);
        }

        function hideLoading() {
            const loadingDiv = document.getElementById('loading-indicator');
            if (loadingDiv) {
                loadingDiv.remove();
            }
        }
    </script>
</body>
</html>
