<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI Chat Assistant</title>
    <link rel="stylesheet" href="styles.css">
    <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;500&display=swap" rel="stylesheet">
</head>
<body>
    <div class="chat-container">
        <div class="welcome-container" id="welcomeContainer">
            <div class="welcome-content">
                <div class="welcome-icon">💬</div>
                <h1>Hi, I'm DeepSeekR1</h1>
                <p>How can I help you today?</p>
            </div>
        </div>

        <div class="chat-messages" id="chatMessages"></div>
        
        <div class="typing-indicator" id="typingIndicator">
            <span class="typing-dot dot1"></span>
            <span class="typing-dot dot2"></span>
            <span class="typing-dot dot3"></span>
        </div>
        
        <div class="input-container">
            <textarea class="input-field" id="userInput" placeholder="Type your message..." rows="1"></textarea>
            <button class="send-button" id="sendButton">Send</button>
        </div>
    </div>

    <script>
        function generateUsername() {
            const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
            let username = '';
            for (let i = 0; i < 12; i++) {
                username += chars.charAt(Math.floor(Math.random() * chars.length));
            }
            return username;
        }

        let userName = generateUsername();
        const chatMessages = document.getElementById('chatMessages');
        const userInput = document.getElementById('userInput');
        const sendButton = document.getElementById('sendButton');
        const typingIndicator = document.getElementById('typingIndicator');
        const welcomeContainer = document.getElementById('welcomeContainer');
        let isGenerating = false;
        let welcomeVisible = true;

        function adjustTextareaHeight() {
            userInput.style.height = 'auto';
            const maxHeight = window.innerWidth > 480 ? 150 : 100;
            const newHeight = Math.min(userInput.scrollHeight, maxHeight);
            userInput.style.height = newHeight + 'px';
            
            // Automatically scroll to bottom when typing
            if (userInput.scrollHeight > maxHeight) {
                userInput.scrollTop = userInput.scrollHeight;
            }
        }

        function hideWelcomeMessage() {
            if (welcomeVisible) {
                welcomeContainer.style.opacity = '0';
                setTimeout(() => {
                    welcomeContainer.style.display = 'none';
                }, 300);
                welcomeVisible = false;
            }
        }

        async function sendMessage() {
            const message = userInput.value.trim();
            if (!message || isGenerating) return;

            hideWelcomeMessage();

            const userMessage = document.createElement('div');
            userMessage.className = 'message user-message';
            userMessage.innerHTML = message.replace(/\n/g, '<br>');
            chatMessages.appendChild(userMessage);
            
            chatMessages.scrollTop = chatMessages.scrollHeight;
            userInput.value = '';
            userInput.style.height = 'auto';
            isGenerating = true;
            typingIndicator.style.display = 'flex';
            
            try {
                const response = await fetch('https://whole-bug-aware.ngrok-free.app/inference', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        user: userName,
                        prompt: message
                    })
                });

                typingIndicator.style.display = 'none';
                
                const botMessage = document.createElement('div');
                botMessage.className = 'message bot-message';
                chatMessages.appendChild(botMessage);
                
                const reader = response.body.getReader();
                const decoder = new TextDecoder();
                
                while (true) {
                    const { done, value } = await reader.read();
                    if (done) break;
                    const chunk = decoder.decode(value);
                    
                    const parts = chunk.split(/(<think>|<\/think>)/g);
                    const processedParts = parts.map(part => {
                        if (part === '<think>') {
                            return '<strong>Thinking...</strong><br>';
                        } else if (part === '</think>') {
                            return '<br><strong>Final Response:</strong>';
                        } else {
                            return part.replace(/\*\*/g, '') // Remove **
                                    .replace(/&/g, '&amp;')
                                    .replace(/</g, '&lt;')
                                    .replace(/>/g, '&gt;')
                                    .replace(/"/g, '&quot;')
                                    .replace(/'/g, '&#039;');
                        }
                    });
                    
                    botMessage.innerHTML += processedParts.join('');
                    chatMessages.scrollTop = chatMessages.scrollHeight;
                }

            } catch (error) {
                console.error('Error:', error);
                typingIndicator.style.display = 'none';
                const errorMessage = document.createElement('div');
                errorMessage.className = 'message bot-message';
                errorMessage.textContent = 'Error: Could not get response';
                errorMessage.style.color = '#dc3545';
                chatMessages.appendChild(errorMessage);
            }
            
            chatMessages.scrollTop = chatMessages.scrollHeight;
            isGenerating = false;
        }

        sendButton.addEventListener('click', sendMessage);
        userInput.addEventListener('input', adjustTextareaHeight);
        userInput.addEventListener('keydown', (e) => {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                sendMessage();
            }
        });
    </script>
</body>
</html>
