"use strict";

// pid aus dem Pfad /e/<pid>.
const pid = location.pathname.split("/")[2] || "";

document.getElementById("reply-form").addEventListener("submit", async (e) => {
  e.preventDefault();
  const fd = new FormData(e.target);
  fd.append("reply_to", pid);
  const res = await api.post("/entry/create", fd);
  if (res.ok) {
    e.target.reset();
    document.getElementById("reply-msg").textContent = "";
    load();
  } else {
    document.getElementById("reply-msg").textContent =
      res.data.error || "Antwort fehlgeschlagen.";
  }
});

async function load() {
  const data = await api.get(`/entry/${pid}/thread`);

  const focus = document.getElementById("focus");
  if (data.error) {
    focus.textContent = "Beitrag nicht gefunden";
    return;
  }

  // Ahnenkette (Root zuerst), dann der fokussierte Beitrag.
  const ancestors = document.getElementById("ancestors");
  ancestors.innerHTML = "";
  data.ancestors.forEach((a) => ancestors.appendChild(renderEntry(a)));

  focus.innerHTML = "";
  focus.appendChild(renderEntry(data.entry));

  // Eingeloggt? Reply-Box zeigen; eigener, nicht gelöschter Beitrag -> Bearbeiten/Löschen.
  const me = await api.get("/user/info");
  document.getElementById("reply-box").hidden = !me.uid;
  if (me.uid === data.entry.uid && !data.entry.deleted) {
    const editBtn = document.createElement("button");
    editBtn.textContent = "Bearbeiten";
    editBtn.addEventListener("click", () => {
      editBtn.disabled = true;
      const form = document.createElement("form");
      form.innerHTML = `
        <textarea name="content" rows="4" maxlength="1000"></textarea>
        <button type="submit">Speichern</button>
        <button type="button" class="cancel">Abbrechen</button>
        <p class="msg"></p>`;
      form.querySelector("textarea").value = data.entry.content;
      form.addEventListener("submit", async (ev) => {
        ev.preventDefault();
        const res = await api.post(`/entry/${pid}/edit`, new FormData(form));
        if (res.ok) load();
        else form.querySelector(".msg").textContent =
          res.data.error || "Bearbeiten fehlgeschlagen.";
      });
      form.querySelector(".cancel").addEventListener("click", load);
      focus.appendChild(form);
    });

    const delBtn = document.createElement("button");
    delBtn.textContent = "Löschen";
    delBtn.addEventListener("click", async () => {
      if (!confirm("Beitrag wirklich löschen?")) return;
      const res = await api.post(`/entry/${pid}/delete`, new FormData());
      if (res.ok) load();
      else alert(res.data.error || "Löschen fehlgeschlagen.");
    });

    focus.appendChild(editBtn);
    focus.appendChild(delBtn);
  }

  // Direkte Antworten.
  const replies = document.getElementById("replies");
  replies.innerHTML = "";
  if (!data.replies.length) {
    const p = document.createElement("p");
    p.className = "muted";
    p.textContent = "Noch keine Antworten.";
    replies.appendChild(p);
  } else {
    data.replies.forEach((e) => replies.appendChild(renderEntry(e)));
  }
}

load();
