<div class="chat chat-end">
  <div class="chat-bubble markdown-content" data-content="{{ user_message.content|escape }}">
    {{ user_message.content|escape }}
  </div>
</div>
<div class="chat chat-start">
  <div hx-ext="sse" sse-connect="/chat/response-stream?message_id={{user_message.id}}" sse-close="close_stream"
    hx-swap="beforeend">
    <div class="chat-bubble">
      <span class="loading loading-dots loading-sm loading-id-{{user_message.id}}"></span>
      <div class="markdown-content" id="ai-message-content-{{user_message.id}}" sse-swap="chat_message"></div>
    </div>
    <div sse-swap="references"></div>
  </div>
</div>

<script>
  window.markdownBuffer = window.markdownBuffer || {};
  document.body.addEventListener('htmx:sseBeforeMessage', function (e) {
    const msgId = '{{ user_message.id }}';
    const spinner = document.querySelector('.loading-id-' + msgId);
    if (spinner) spinner.style.display = 'none';
    const el = document.getElementById('ai-message-content-' + msgId);
    if (e.detail.elt !== el) return;
    e.preventDefault();
    window.markdownBuffer[msgId] = (window.markdownBuffer[msgId] || '') + (e.detail.data || '');
    el.innerHTML = marked.parse(window.markdownBuffer[msgId].replace(/\\n/g, '\n'));
    if (typeof window.scrollChatToBottom === "function") window.scrollChatToBottom();
  });
  document.body.addEventListener('htmx:sseClose', function () {
    const msgId = '{{ user_message.id }}';
    const el = document.getElementById('ai-message-content-' + msgId);
    if (el && window.markdownBuffer[msgId]) {
      el.innerHTML = marked.parse(window.markdownBuffer[msgId].replace(/\\n/g, '\n'));
      delete window.markdownBuffer[msgId];
      if (typeof window.scrollChatToBottom === "function") window.scrollChatToBottom();
    }
  });
</script>
