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

{% block extra_head %}
{% endblock %}

{% block content %}
<div class="chat-container glass-card">

  <!-- Chat Area (Adjusted for new layout) -->
  <div class="flex flex-col flex-1">
    <!-- Header -->
    <div class="chat-header">
      <h2 class="text-2xl font-bold">BotAI</h2>
    </div>

    <!-- Messages -->
    <div id="chat-messages" class="chat-box">
      {% for message in messages %}
        <div class="chat-message {% if message.is_user %}user-message{% else %}ai-message{% endif %}">
          <div class="message-content">
            {{ message.message|linebreaksbr }}
          </div>
        </div>
      {% endfor %}
    </div>

    <!-- Input -->
    <div class="chat-input-area">
      <form id="chat-form" class="flex items-center">
        {% csrf_token %}
        <input type="text" id="message" name="message" class="chat-input" placeholder="Type your message...">
        <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>
{% endblock %}

{% block extra_scripts %}
<script>
    function executeCommand(command) {
      console.log('Executing command:', command);
      switch (command.action) {
        case 'navigate':
          if (command.url) {
            window.open(command.url, '_blank');
          }
          break;
        case 'fill':
          if (command.selector && command.value) {
            const element = document.querySelector(command.selector);
            if (element) {
              element.value = command.value;
            } else {
              console.warn('Element not found for fill command:', command.selector);
            }
          }
          break;
        case 'click':
          if (command.selector) {
            const element = document.querySelector(command.selector);
            if (element) {
              element.click();
            } else {
              console.warn('Element not found for click command:', command.selector);
            }
          }
          break;
        default:
          console.warn('Unknown command type:', command.type);
      }
    }

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

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

      const messageText = messageInput.value.trim();
      if (messageText === '') {
        return;
      }

      // Display user message
      const userMessageDiv = document.createElement('div');
      userMessageDiv.classList.add('chat-message', 'user-message');
      const userMessageContent = document.createElement('div');
      userMessageContent.classList.add('message-content');
      userMessageContent.textContent = messageText;
      userMessageDiv.appendChild(userMessageContent);
      chatMessages.appendChild(userMessageDiv);
      chatMessages.scrollTop = chatMessages.scrollHeight;

      messageInput.value = '';

      // Send message to server
      fetch('{% url "ai_chat_new" %}', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
          'X-CSRFToken': '{{ csrf_token }}'
        },
        body: new URLSearchParams({
          'message': messageText
        })
      })
      .then(response => response.json())
      .then(data => {
        if (data.error) {
          console.error('Error:', data.error);
          const aiMessageDiv = document.createElement('div');
          aiMessageDiv.classList.add('chat-message', 'ai-message');
          const aiMessageContent = document.createElement('div');
          aiMessageContent.classList.add('message-content');
          aiMessageContent.textContent = `Error: ${data.error}`;
          aiMessageDiv.appendChild(aiMessageContent);
          chatMessages.appendChild(aiMessageDiv);
        } else if (data.reply) {
          const aiMessageDiv = document.createElement('div');
          aiMessageDiv.classList.add('chat-message', 'ai-message');
          const aiMessageContent = document.createElement('div');
          aiMessageContent.classList.add('message-content');
          aiMessageContent.textContent = data.reply;
          aiMessageDiv.appendChild(aiMessageContent);
          chatMessages.appendChild(aiMessageDiv);
        } else if (data.commands) {
          data.commands.forEach(command => {
            executeCommand(command);
          });
        chatMessages.scrollTop = chatMessages.scrollHeight;
      })
      .catch(error => {
        console.error('Fetch error:', error);
        const aiMessageDiv = document.createElement('div');
        aiMessageDiv.classList.add('chat-message', 'ai-message');
        const aiMessageContent = document.createElement('div');
        aiMessageContent.classList.add('message-content');
        aiMessageContent.textContent = 'Sorry, something went wrong.';
        aiMessageDiv.appendChild(aiMessageContent);
        chatMessages.appendChild(aiMessageDiv);
        chatMessages.scrollTop = chatMessages.scrollHeight;
      });
    });
  });
</script>
{% endblock %}