// All the JS the page needs. Three responsibilities:
//   1. On load, fetch the current list of messages and render it.
//   2. When the user clicks Post, send a fetch() with the form fields
//      as JSON, then render the response.
//   3. Render = wipe the <ul> and rebuild its <li> children.

const nameElement = document.getElementById("name");
const messageElement = document.getElementById("message");

function render(messages) {
  const ul = document.getElementById("messages");
  ul.innerHTML = "";  // clear out previous contents
  if (messages.length === 0) {
    const li = document.createElement("li");
    li.innerHTML = "<em>No messages yet.</em>";
    ul.appendChild(li);
    return;
  }
  for (const m of messages) {
    const li = document.createElement("li");
    const strong = document.createElement("strong");
    strong.textContent = m.name;             // textContent, not innerHTML: see XSS aside in the guide
    li.appendChild(strong);
    li.appendChild(document.createTextNode(": " + m.message));
    ul.appendChild(li);
  }
}

async function loadMessages() {
  const response = await fetch("/api/messages");
  const messages = await response.json();
  render(messages);
}

async function doPost() {
  const name = nameElement.value;
  const message = messageElement.value;
  const response = await fetch("/api/messages", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ name, message }),
  });
  const messages = await response.json();
  render(messages);
  // Clear the inputs so the user can type the next one.
  nameElement.value = "";
  messageElement.value = "";
}

// Kick off the initial load as soon as the script runs.
loadMessages();
