{% extends 'base.html' %}
{% load static %}

{% block content %}
<div class="chat-container glass-card">
  <div class="chat-header">
    <h2 class="font-poppins">BotAI</h2>
  </div>

  <div class="chat-box" id="chat-messages">
    <!-- Messages will be appended here -->
  </div>

  <div class="chat-input-area">
    <form id="chat-form" class="d-flex align-items-center">
      {% csrf_token %}
      <input type="text" id="message" name="message" class="chat-input" placeholder="Ask the AI to do something...">
      <button type="submit" class="send-button">
        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-send"><line x1="22" y1="2" x2="11" y2="13"></line><polygon points="22 2 15 22 11 13 2 9 22 2"></polygon></svg>
      </button>
    </form>
  </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const chatForm = document.getElementById('chat-form');
    const chatMessages = document.getElementById('chat-messages');
    const messageInput = document.getElementById('message');

    // Function to append a message to the chat box
    function appendMessage(sender, message, type) {
        const messageWrapper = document.createElement('div');
        messageWrapper.classList.add('chat-message', type === 'user' ? 'user-message' : 'ai-message');

        const messageContent = document.createElement('div');
        messageContent.classList.add('message-content');
        
        // Use a <p> tag to ensure proper styling and spacing
        const p = document.createElement('p');
        p.textContent = message;
        messageContent.appendChild(p);
        
        messageWrapper.appendChild(messageContent);
        chatMessages.appendChild(messageWrapper);

        // Scroll to the bottom
        chatMessages.scrollTop = chatMessages.scrollHeight;
    }

    chatForm.addEventListener('submit', function(e) {
        e.preventDefault();

        const message = messageInput.value.trim();
        if (message === '') return;

        // Display user's message immediately
        appendMessage('You', message, 'user');

        // Clear the input and disable it while waiting for response
        messageInput.value = '';
        messageInput.disabled = true;

        fetch('{% url "ai_chat" %}', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value
            },
            body: `message=${encodeURIComponent(message)}`
        })
        .then(response => response.json())
        .then(data => {
            if (data.commands) {
                // For now, we'll just log any commands to the console
                console.log('Received commands:', data.commands);
                appendMessage('AI', JSON.stringify(data.commands, null, 2), 'ai');
            } else if (data.reply) {
                appendMessage('AI', data.reply, 'ai');
            } else {
                appendMessage('AI', 'Sorry, I received an unexpected response.', 'ai');
            }
        })
        .catch(error => {
            console.error("Fetch Error:", error);
            appendMessage('AI', 'Error communicating with the server.', 'ai');
        })
        .finally(() => {
            // Re-enable the input
            messageInput.disabled = false;
            messageInput.focus();
        });
    });
});
</script>
{% endblock %}