{% extends 'body_base.html' %}

{% block title %}Minne - Chat{% endblock %}

{% block head %}
<script src="/assets/htmx-ext-sse.js" defer></script>
{% endblock %}

{% block main %}
<div class="flex grow relative justify-center mt-2 sm:mt-4">
  <div class="container">
    <section class="mb-3">
      <div class="nb-panel p-3 flex items-center justify-between">
        <h1 class="text-xl font-extrabold tracking-tight">Chat</h1>
        <div class="text-xs opacity-70">Converse with your knowledge</div>
      </div>
    </section>
    <div id="chat-scroll-container" class="overflow-auto hide-scrollbar">
      {% include "chat/history.html" %}
      {% include "chat/new_message_form.html" %}
    </div>
  </div>
</div>

<script>
  function scrollChatToBottom() {
    requestAnimationFrame(() => {
      const mainScroll = document.querySelector('main');
      if (mainScroll) mainScroll.scrollTop = mainScroll.scrollHeight;

      const chatScroll = document.getElementById('chat-scroll-container');
      if (chatScroll) chatScroll.scrollTop = chatScroll.scrollHeight;

      const chatContainer = document.getElementById('chat_container');
      if (chatContainer) chatContainer.scrollTop = chatContainer.scrollHeight;

      window.scrollTo(0, document.body.scrollHeight);
    });
  }

  window.scrollChatToBottom = scrollChatToBottom;

  document.addEventListener('DOMContentLoaded', scrollChatToBottom);

  document.body.addEventListener('htmx:afterSwap', scrollChatToBottom);
  document.body.addEventListener('htmx:afterSettle', scrollChatToBottom);
</script>
{% endblock %}
