"use strict";

// --- Headerbar (eingeloggt?) ---
let loggedIn = false;

async function refreshHeader() {
  const h = await api.get("/auth/headerbar");
  loggedIn = !!h.loggedin;

  document.getElementById("auth-box").hidden = loggedIn;
  document.getElementById("compose").hidden = !loggedIn;

  const bar = document.getElementById("headerbar");
  if (loggedIn) {
    const me = await api.get("/user/info");
    const user = encodeURIComponent(me.username);
    bar.innerHTML = `<a class="button" href="/u/${user}">mein Profil</a> <button id="logout-btn">Logout</button>`;
    document.getElementById("logout-btn").addEventListener("click", async () => {
      await api.get("/auth/logout");
      await refreshHeader();
    });
  } else {
    bar.innerHTML = "";
    showAuth("login");
  }
}

// --- Login / Registrierung ---
const loginForm = document.getElementById("login-form");
const registerForm = document.getElementById("register-form");
const authMsg = document.getElementById("auth-msg");

function showAuth(which) {
  loginForm.hidden = which !== "login";
  registerForm.hidden = which !== "register";
  authMsg.textContent = "";
}

document.getElementById("show-register").addEventListener("click", (e) => {
  e.preventDefault();
  showAuth("register");
});
document.getElementById("show-login").addEventListener("click", (e) => {
  e.preventDefault();
  showAuth("login");
});

loginForm.addEventListener("submit", async (e) => {
  e.preventDefault();
  const res = await api.post("/auth/login", new FormData(e.target));
  if (res.ok) {
    await refreshHeader();
  } else {
    authMsg.textContent = res.data.error || "Login fehlgeschlagen.";
  }
});

registerForm.addEventListener("submit", async (e) => {
  e.preventDefault();
  const data = new FormData(e.target);
  const res = await api.post("/auth/newuser", data);
  if (!res.ok) {
    // newuser liefert eine Fehlerliste ({"errors": [...]}).
    const errors = res.data.errors || [res.data.error || "Registrierung fehlgeschlagen."];
    authMsg.textContent = errors.join(" ");
    return;
  }
  // Direkt mit denselben Daten einloggen, damit der Nutzer gleich drin ist.
  const login = new FormData();
  login.append("user", data.get("user"));
  login.append("pass", data.get("pass1"));
  login.append("timeout", "86400");
  await api.post("/auth/login", login);
  await refreshHeader();
});

// --- Feed ---
const feed = createFeed(
  document.getElementById("feed"),
  document.getElementById("sentinel"),
  (page) => `/entry/feed/${page}`
);

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

// --- Start ---
refreshHeader();
