const runChat = async () => {
  const frenId =
    new URLSearchParams(document.location.search).get("fren_id") ??
    document.getElementById("fren_id").value;
  const html = await fetch(`/chat/messages?fren_id=${frenId}`).then((r) =>
    r.text(),
  );

  const { scrollTop, scrollHeight, clientTop } = document.getElementById(
    "chat-container",
  ) ?? { scrollTop: 0, scrollHeight: 0, clientTop: 0};
  const scrollTopMax = scrollHeight - clientTop;
  const isAtEdge = scrollTop > (0.92 * scrollTopMax) || scrollTop === 0;
  document.getElementById("messages").innerHTML = html;
  await new Promise((res) => setTimeout(res, 200)); // wait for html to emplace.
  const emplacedScrollTopMax = document.getElementById("chat-container").scrollHeight - document.getElementById("chat-container").clientTop;
  if (isAtEdge) {
    document.getElementById("chat-container").scrollTop = scrollTopMax;
  } else {
    // save the position.
    document.getElementById("chat-container").scrollTop = scrollTop;
  }
};

setTimeout(() => {
  if (document.location.pathname.startsWith("/chat")) {
    runChat().then(() => setInterval(runChat, 2_500));
  }
}, 200);

const form = document.getElementById("chat-form");
form.addEventListener('submit', (event) => {
  event.preventDefault();

  const message = document.getElementById("message-content").value;
  const fren_id = document.getElementById("fren-id").value;
  const params = new URLSearchParams();
  params.append("fren_id", fren_id);
  params.append("message", message);
  fetch("/chat", {
    method: "POST",
    headers: {
      "Content-Type": "application/x-www-form-urlencoded"
    },
    body: params,
  }).then(runChat);
});