<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Voice Chat - RonnieGPT</title>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <style>
        body {
            margin: 0;
            padding: 0;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            height: 100vh;
            display: flex;
        }

        .sidebar {
            width: 260px;
            background-color: #f7f7f8;
            border-right: 1px solid #e5e7eb;
            display: flex;
            flex-direction: column;
            padding: 1rem;
        }

        .main-content {
            flex: 1;
            display: flex;
            flex-direction: column;
            height: 100vh;
            position: relative;
            background-color: white;
        }

        .chat-area {
            flex: 1;
            overflow-y: auto;
            padding: 2rem;
            display: flex;
            flex-direction: column;
            gap: 1rem;
        }

        .message {
            display: flex;
            max-width: 80%;
            padding: 1rem;
            border-radius: 0.8rem;
            line-height: 1.5;
        }

        .message.user {
            margin-left: auto;
            background-color: #2563eb;
            color: white;
        }

        .message.assistant {
            margin-right: auto;
            background-color: #f3f4f6;
            color: #1f2937;
        }

        .voice-controls {
            position: fixed;
            bottom: 2rem;
            left: 50%;
            transform: translateX(-50%);
            display: flex;
            align-items: center;
            gap: 1.5rem;
            padding: 1rem 2rem;
            background: white;
            border-radius: 50px;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
            z-index: 1000;
        }

        .mic-button {
            width: 60px;
            height: 60px;
            border-radius: 50%;
            border: none;
            background: #2563eb;
            color: white;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.3s ease;
        }

        .mic-button.recording {
            background: #dc2626;
            animation: pulse 1.5s infinite;
        }

        .voice-status {
            font-size: 0.9rem;
            color: #666;
            min-width: 200px;
            text-align: center;
        }

        .audio-player {
            display: flex;
            align-items: center;
            gap: 0.5rem;
            margin-top: 0.5rem;
        }

        .play-button {
            background: #2563eb;
            color: white;
            border: none;
            padding: 0.5rem 1rem;
            border-radius: 20px;
            cursor: pointer;
            display: flex;
            align-items: center;
            gap: 0.5rem;
            font-size: 0.9rem;
        }

        .switch-interface {
            position: absolute;
            top: 1rem;
            right: 1rem;
            padding: 0.5rem 1rem;
            background: white;
            border: 1px solid #e5e7eb;
            border-radius: 20px;
            cursor: pointer;
            display: flex;
            align-items: center;
            gap: 0.5rem;
            transition: all 0.2s;
        }

        @keyframes pulse {
            0% { transform: scale(1); }
            50% { transform: scale(1.05); }
            100% { transform: scale(1); }
        }

        .message-text {
            margin-bottom: 0.5rem;
            white-space: pre-wrap;
            word-break: break-word;
        }

        .play-button:hover {
            background: #1d4ed8;
        }

        .play-button:disabled {
            background: #93c5fd;
            cursor: not-allowed;
        }

        .message.assistant {
            background: #f3f4f6;
            color: #1f2937;
            padding: 1rem;
            border-radius: 0.8rem;
            margin-bottom: 1rem;
        }

        .message.user {
            background: #2563eb;
            color: white;
            padding: 1rem;
            border-radius: 0.8rem;
            margin-bottom: 1rem;
            align-self: flex-end;
        }
    </style>
</head>
<body>
    <div class="sidebar">
        <h2>Chat History</h2>
        <div class="chat-history">
            {% for chat in chats %}
            <div class="chat-item">{{ chat.title }}</div>
            {% endfor %}
        </div>
    </div>

    <div class="main-content">
        <button class="switch-interface" onclick="window.location.href='/chat'">
            <svg width="20" height="20" viewBox="0 0 24 24">
                <path fill="currentColor" d="M20,2H4A2,2 0 0,0 2,4V22L6,18H20A2,2 0 0,0 22,16V4A2,2 0 0,0 20,2M6,9H18V11H6M14,14H6V12H14M18,8H6V6H18"/>
            </svg>
            Switch to Text Chat
        </button>

        <div class="chat-area" id="messages"></div>

        <div class="voice-controls">
            <div class="voice-status">Click the microphone to start speaking</div>
            <button class="mic-button" id="micButton" onclick="toggleRecording()">
                <svg width="24" height="24" viewBox="0 0 24 24">
                    <path fill="currentColor" d="M12,2A3,3 0 0,1 15,5V11A3,3 0 0,1 12,14A3,3 0 0,1 9,11V5A3,3 0 0,1 12,2M19,11C19,14.53 16.39,17.44 13,17.93V21H11V17.93C7.61,17.44 5,14.53 5,11H7A5,5 0 0,0 12,16A5,5 0 0,0 17,11H19Z"/>
                </svg>
            </button>
        </div>
    </div>

    <script>
        let mediaRecorder;
        let audioChunks = [];
        let isRecording = false;

        async function sendAudioToServer(audioBlob) {
            const statusDiv = document.querySelector('.voice-status');
            try {
                const formData = new FormData();
                formData.append('audio', audioBlob, 'recording.webm');
                statusDiv.textContent = 'Processing your message...';

                const response = await axios.post('/chat/voice', formData, {
                    headers: {
                        'Content-Type': 'multipart/form-data'
                    }
                });

                if (response.data.success) {
                    // Add user's transcribed message to chat
                    if (response.data.transcript) {
                        const userMessage = document.createElement('div');
                        userMessage.className = 'message user';
                        userMessage.textContent = response.data.transcript;
                        document.getElementById('messages').appendChild(userMessage);
                    }
                    
                    // Add assistant's response to chat and auto-play
                    if (response.data.response) {
                        const assistantMessage = document.createElement('div');
                        assistantMessage.className = 'message assistant';
                        assistantMessage.textContent = response.data.response;
                        document.getElementById('messages').appendChild(assistantMessage);
                        
                        // Auto-play the audio response
                        const audio = new Audio(response.data.audio_url);
                        audio.play().catch(error => {
                            console.error('Audio playback error:', error);
                        });
                    }
                    
                    // Scroll to bottom
                    const messagesDiv = document.getElementById('messages');
                    messagesDiv.scrollTop = messagesDiv.scrollHeight;
                    
                    statusDiv.textContent = 'Click the microphone to start speaking';
                } else {
                    throw new Error(response.data.error || 'Unknown error occurred');
                }
            } catch (error) {
                console.error('Error sending audio:', error);
                statusDiv.textContent = 'Error processing audio';
                const errorMessage = document.createElement('div');
                errorMessage.className = 'message assistant';
                errorMessage.textContent = 'Sorry, there was an error processing your message. Please try again.';
                document.getElementById('messages').appendChild(errorMessage);
            }
        }

        async function toggleRecording() {
            const micButton = document.getElementById('micButton');
            const statusDiv = document.querySelector('.voice-status');

            if (!isRecording) {
                try {
                    const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
                    mediaRecorder = new MediaRecorder(stream);
                    audioChunks = [];

                    mediaRecorder.ondataavailable = (event) => {
                        audioChunks.push(event.data);
                    };

                    mediaRecorder.onstop = async () => {
                        const audioBlob = new Blob(audioChunks, { type: 'audio/webm' });
                        await sendAudioToServer(audioBlob);
                    };

                    mediaRecorder.start();
                    isRecording = true;
                    micButton.classList.add('recording');
                    statusDiv.textContent = 'Recording... Click to stop';
                } catch (err) {
                    console.error('Error accessing microphone:', err);
                    statusDiv.textContent = 'Error accessing microphone';
                }
            } else {
                mediaRecorder.stop();
                isRecording = false;
                micButton.classList.remove('recording');
                statusDiv.textContent = 'Processing...';
            }
        }
    </script>
</body>
</html> 