<div id="main-panel" class="col-12 col-md-9 d-flex flex-column mc-chat-panel">
  <div class="card mc-panel flex-grow-1 d-flex flex-column min-h-0">

    <div class="card-header mc-panel-header d-flex justify-content-between align-items-center">
      <span class="d-flex align-items-center gap-2">
        {% if agent %}
          <span class="status-dot {{ 'green' if agent.status == 'idle' else 'amber' }}"></span>
        {% endif %}
        // AGENT INTERFACE
        <span id="agent-status" class="ms-2" style="font-size: 0.75rem; color: #888;">
          <span class="htmx-indicator">checking...</span>
        </span>
      </span>
      <button class="mc-btn-clear"
              hx-delete="/agents/default/history"
              hx-target="#chat-log"
              hx-swap="innerHTML"
              hx-confirm="Clear conversation history?">CLEAR</button>
    </div>

    <div id="current-task-banner" class="current-task-banner" style="display: none; background: #1a1a2e; padding: 8px 12px; border-bottom: 1px solid #333;">
      <small style="color: #00ff88;">&#9679; WORKING:</small>
      <span id="current-task-title" style="color: #fff;"></span>
    </div>

    <div class="chat-log flex-grow-1 overflow-auto p-3" id="chat-log"
         hx-get="/agents/default/history"
         hx-trigger="load"
         hx-swap="innerHTML"
         hx-on::after-settle="scrollChat()"></div>

    <div class="card-footer mc-chat-footer">
      <form hx-post="/agents/default/chat"
            hx-target="#chat-log"
            hx-swap="beforeend"
            hx-indicator="#send-indicator"
            hx-sync="this:drop"
            hx-disabled-elt="find button"
            hx-on::after-settle="scrollChat()"
            hx-on::after-request="handleAfterRequest(event)"
            class="d-flex gap-2"
            id="agent-chat-form">
        <input type="text"
               name="message"
               class="form-control mc-input"
               placeholder="send a message..."
               autocomplete="off"
               autocorrect="off"
               autocapitalize="none"
               spellcheck="false"
               enterkeyhint="send"
               required
               id="agent-chat-input" />
        <button type="submit" class="btn mc-btn-send">
          SEND
          <span id="send-indicator" class="htmx-indicator">&#x25FC;</span>
        </button>
        <button type="button"
                class="btn mc-btn-grok"
                onclick="askGrok()"
                title="Send directly to Grok (xAI)">
          GROK
        </button>
      </form>
    </div>

  </div>
</div>

<script>
  scrollChat();

  function handleAfterRequest(event) {
    var detail = event.detail;
    if (detail.successful) {
      document.getElementById('agent-chat-form').querySelector('[name=message]').value = '';
    } else if (detail.failed) {
      // Show error message in chat log
      var chatLog = document.getElementById('chat-log');
      var div = document.createElement('div');
      div.className = 'chat-message error-msg';
      var meta = document.createElement('div');
      meta.className = 'msg-meta';
      var now = new Date();
      meta.textContent = 'SYSTEM // ' + now.toTimeString().slice(0, 8);
      var body = document.createElement('div');
      body.className = 'msg-body';
      body.textContent = 'Request timed out or failed. Try breaking the task into smaller steps.';
      div.appendChild(meta);
      div.appendChild(body);
      chatLog.appendChild(div);
      chatLog.scrollTop = chatLog.scrollHeight;
    }
  }

  function askGrok() {
    var input = document.getElementById('agent-chat-input');
    if (!input || !input.value.trim()) return;
    var form = document.getElementById('agent-chat-form');
    // Temporarily redirect form to Grok endpoint
    var originalAction = form.getAttribute('hx-post');
    form.setAttribute('hx-post', '/grok/chat');
    htmx.process(form);
    htmx.trigger(form, 'submit');
    // Restore original action after submission
    setTimeout(function() {
      form.setAttribute('hx-post', originalAction);
      htmx.process(form);
    }, 100);
  }

  // Poll for queue status (fallback) + WebSocket for real-time
(function() {
  var statusEl = document.getElementById('agent-status');
  var banner = document.getElementById('current-task-banner');
  var taskTitle = document.getElementById('current-task-title');
  var protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
  var ws;
  var chatLog = document.getElementById('chat-log');

  function updateFromData(data) {
    if (data.is_working && data.current_task) {
      statusEl.textContent = 'working...';
      statusEl.style.color = '#ffaa00';
      banner.style.display = 'block';
      taskTitle.textContent = data.current_task.title;
    } else if (data.tasks_ahead > 0) {
      statusEl.textContent = 'queue: ' + data.tasks_ahead + ' ahead';
      statusEl.style.color = '#888';
      banner.style.display = 'none';
    } else {
      statusEl.textContent = 'ready';
      statusEl.style.color = '#00ff88';
      banner.style.display = 'none';
    }
  }

  function fetchStatus() {
    fetch('/api/queue/status?assigned_to=default')
      .then(r => r.json())
      .then(updateFromData)
      .catch(() => {});
  }

  function appendMessage(role, content, timestamp, taskId) {
    // If this is a response for a queued task, replace the placeholder
    if (taskId) {
      var placeholder = chatLog.querySelector('.chat-message.agent[data-task-id="' + taskId + '"]');
      if (placeholder) {
        placeholder.removeAttribute('data-task-id');
        var body = placeholder.querySelector('.msg-body');
        if (body) {
          body.textContent = content;
          body.className = 'msg-body agent-md';
          if (typeof marked !== 'undefined' && typeof DOMPurify !== 'undefined') {
            body.innerHTML = DOMPurify.sanitize(marked.parse(body.textContent));
            if (typeof hljs !== 'undefined') {
              body.querySelectorAll('pre code').forEach(function(block) { hljs.highlightElement(block); });
            }
          }
        }
        placeholder.querySelector('.msg-meta').textContent = 'AGENT // ' + timestamp;
        // Remove queue-status indicator if present
        var qs = placeholder.nextElementSibling;
        if (qs && qs.classList.contains('queue-status')) qs.remove();
        chatLog.scrollTop = chatLog.scrollHeight;
        return;
      }
    }
    var div = document.createElement('div');
    div.className = 'chat-message ' + role;
    var meta = document.createElement('div');
    meta.className = 'msg-meta';
    meta.textContent = (role === 'user' ? 'YOU' : 'AGENT') + ' // ' + timestamp;
    var body = document.createElement('div');
    body.className = 'msg-body agent-md';
    body.textContent = content;
    div.appendChild(meta);
    div.appendChild(body);
    chatLog.appendChild(div);
    // Render markdown if available
    if (typeof marked !== 'undefined' && typeof DOMPurify !== 'undefined') {
      body.innerHTML = DOMPurify.sanitize(marked.parse(body.textContent));
      if (typeof hljs !== 'undefined') {
        body.querySelectorAll('pre code').forEach(function(block) { hljs.highlightElement(block); });
      }
    }
    // Scroll to bottom
    chatLog.scrollTop = chatLog.scrollHeight;
  }

  function connectWs() {
    try {
      ws = new WebSocket(protocol + '//' + window.location.host + '/swarm/live');
      ws.onmessage = function(event) {
        try {
          var msg = JSON.parse(event.data);
          // Refresh on task events
          if (msg.type === 'task_event') {
            fetchStatus();
          } else if (msg.type === 'agent_thought') {
            // Agent thought - could show in UI
          } else if (msg.event === 'task_created' || msg.event === 'task_completed' ||
                     msg.event === 'task_approved') {
            fetchStatus();
          } else if (msg.event === 'agent_response' && msg.data) {
            // Agent pushed a response via task processor
            var now = new Date();
            var ts = now.getHours().toString().padStart(2,'0') + ':' + now.getMinutes().toString().padStart(2,'0') + ':' + now.getSeconds().toString().padStart(2,'0');
            appendMessage('agent', msg.data.response, ts, msg.data.task_id);
            fetchStatus();
          }
        } catch(e) {}
      };
      ws.onclose = function() {
        setTimeout(connectWs, 5000);
      };
    } catch(e) {}
  }

  // Initial fetch + start WebSocket
  fetchStatus();
  connectWs();

  // Also poll periodically as fallback (every 10s)
  setInterval(fetchStatus, 10000);
})();
</script>
