{% extends 'base.html' %}

{% block content %}
<div class="container mx-auto p-4">
    <h1 class="text-2xl font-bold mb-4">AI Chat</h1>
    <div id="chat-box" class="border p-4 h-64 overflow-y-scroll mb-4"></div>
    <form id="chat-form">
        {% csrf_token %}
        <div class="flex">
            <input type="text" id="message" name="message" class="flex-grow border p-2" placeholder="Type your message...">
            <button type="submit" class="bg-blue-500 text-white p-2">Send</button>
        </div>
    </form>
</div>

<script>
    document.getElementById('chat-form').addEventListener('submit', function(e) {
        e.preventDefault();
        const messageInput = document.getElementById('message');
        const message = messageInput.value;
        const chatBox = document.getElementById('chat-box');

        if (message.trim() === '') return;

        // Display user message
        chatBox.innerHTML += `<div class="text-right"><strong>You:</strong> ${message}</div>`;
        messageInput.value = '';

        // Send message to server
        fetch('{% url "ai_chat" %}', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'X-CSRFToken': '{{ csrf_token }}'
            },
            body: `message=${encodeURIComponent(message)}`
        })
        .then(response => response.json())
        .then(data => {
            if (data.reply) {
                chatBox.innerHTML += `<div><strong>AI:</strong> ${data.reply}</div>`;
            } else if (data.error) {
                chatBox.innerHTML += `<div class="text-red-500"><strong>Error:</strong> ${data.error}</div>`;
            }
            chatBox.scrollTop = chatBox.scrollHeight;
        })
        .catch(error => {
            chatBox.innerHTML += `<div class="text-red-500"><strong>Error:</strong> ${error}</div>`;
            chatBox.scrollTop = chatBox.scrollHeight;
        });
    });
</script>
{% endblock %}