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

{% block extra_head %}
<style>
  .chat-bubble {
    max-width: 70%;
    padding: 12px 16px;
    border-radius: 20px;
    margin-bottom: 8px;
    word-wrap: break-word;
  }

  .user-bubble {
    background-color: #007bff;
    color: white;
    align-self: flex-end;
    margin-left: auto;
  }

  .ai-bubble {
    background-color: #374151; /* gray-700 */
    color: white;
    align-self: flex-start;
    margin-right: auto;
  }
</style>
{% endblock %}

{% block content %}
<div class="flex h-screen bg-gray-900 text-white">
  <!-- Sidebar -->
  <div class="w-1/4 bg-gray-800 border-r border-gray-700">
    <div class="p-4 border-b border-gray-700">
      <h2 class="text-xl font-bold">Conversations</h2>
    </div>
    <div class="p-4">
      <!-- Conversation list will go here -->
      <p class="text-gray-400">No conversations yet.</p>
    </div>
  </div>

  <!-- Chat Area -->
  <div class="flex flex-col w-3/4">
    <!-- Header -->
    <div class="bg-gray-800 p-4 border-b border-gray-700">
      <h2 class="text-2xl font-bold">BotAI</h2>
    </div>

    <!-- Messages -->
    <div id="chat-messages" class="flex-1 p-4 overflow-y-auto" style="max-height: 50vh;">
      {% for message in messages %}
        <div class="chat-bubble {% if message.is_user %}user-bubble{% else %}ai-bubble{% endif %}">
          {{ message.message|linebreaksbr }}
        </div>
      {% endfor %}
    </div>

    <!-- Input -->
    <div class="bg-gray-800 p-4">
      <form id="chat-form" class="flex items-center">
        {% csrf_token %}
        <input type="text" id="message" name="message" class="w-full bg-gray-700 text-white rounded-full py-3 px-6 focus:outline-none focus:ring-2 focus:ring-blue-500" placeholder="Type your message...">
        <button type="submit" class="ml-4 bg-blue-500 hover:bg-blue-600 text-white rounded-full p-3">
          <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 userBubble = document.createElement('div');
      userBubble.classList.add('chat-bubble', 'user-bubble');
      userBubble.textContent = messageText;
      chatMessages.appendChild(userBubble);
      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 aiBubble = document.createElement('div');
          aiBubble.classList.add('chat-bubble', 'ai-bubble');
          aiBubble.textContent = `Error: ${data.error}`;
          chatMessages.appendChild(aiBubble);
        } else if (data.reply) {
          const aiBubble = document.createElement('div');
          aiBubble.classList.add('chat-bubble', 'ai-bubble');
          aiBubble.textContent = data.reply;
          chatMessages.appendChild(aiBubble);
        } else if (data.commands) {
          data.commands.forEach(command => {
            executeCommand(command);
          });
        chatMessages.scrollTop = chatMessages.scrollHeight;
      })
      .catch(error => {
        console.error('Fetch error:', error);
        const aiBubble = document.createElement('div');
        aiBubble.classList.add('chat-bubble', 'ai-bubble');
        aiBubble.textContent = 'Sorry, something went wrong.';
        chatMessages.appendChild(aiBubble);
        chatMessages.scrollTop = chatMessages.scrollHeight;
      });
    });
  });
</script>
{% endblock %}