const apiUrl = "http://localhost/kvalifikacija_html/first_page/php";

async function generateText(prompt) {
    const typingIndicator = document.createElement('div');
    typingIndicator.classList.add('chat-message', 'ai');
    typingIndicator.innerHTML = `
        <div class="typing-dots">
            <div class="dot"></div>
            <div class="dot"></div>
            <div class="dot"></div>
        </div>
    `;
    document.getElementById('messagesContainer').appendChild(typingIndicator);
    scrollToBottom();

    try {
        const response = await axios.post(
            'https://api.openai.com/v1/chat/completions',
            {
                model: 'gpt-3.5-turbo',
                messages: [{ role: 'user', content: prompt }]
            },
            {
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${openaiApiKey}`
                }
            }
        );
        const aiResponse = response.data.choices[0].message.content.trim();

        const aiMessage = document.createElement('div');
        aiMessage.classList.add('chat-message', 'ai');
        aiMessage.innerHTML = `
            <div class="message-content">
                <div class="message-bubble">${aiResponse}</div>
                <img src="images/avatar.png" alt="AI Avatar" class="avatar ai-avatar-bottom">
            </div>
        `;
        document.getElementById('messagesContainer').appendChild(aiMessage);
        scrollToBottom();
    } catch (error) {
        console.error('Error generating text:', error);
        const errorMessage = document.createElement('div');
        errorMessage.classList.add('chat-message', 'ai');
        errorMessage.innerHTML = `
            <div class="message-content">
                <div class="message-bubble">Failed to generate text. Please try again.</div>
                <img src="images/avatar.png" alt="AI Avatar" class="avatar ai-avatar-bottom">
            </div>
        `;
        document.getElementById('messagesContainer').appendChild(errorMessage);
    } finally {
        typingIndicator.remove();
        isLoading = false;
        toggleInputState(false);
    }
}


