const form = document.getElementById("submissionForm");
const statusEl = document.getElementById("submitStatus");
const entitySlugs = document.getElementById("entitySlugs");

function setStatus(message, kind = "") {
  statusEl.textContent = message;
  statusEl.className = `status-bar${kind ? ` ${kind}` : ""}`;
}

async function loadEntityOptions() {
  const response = await fetch("/api/public/catalog");
  const payload = await response.json();
  const slugs = [
    ...(payload.characters || []).map((row) => row.slug),
    ...(payload.stages || []).map((row) => row.slug),
    ...(payload.mechanics || []).map((row) => row.slug),
  ];
  entitySlugs.innerHTML = [...new Set(slugs)]
    .sort()
    .map((slug) => `<option value="${slug}"></option>`)
    .join("");
}

form.addEventListener("submit", async (event) => {
  event.preventDefault();
  setStatus("Sending submission...");
  try {
    const formData = new FormData(form);
    const response = await fetch("/api/public/submissions", {
      method: "POST",
      body: formData,
    });
    const payload = await response.json();
    if (!response.ok || payload.ok === false) {
      throw new Error(payload.error || "Submission failed.");
    }
    form.reset();
    setStatus("Submission received and queued for review.", "success");
  } catch (error) {
    setStatus(error.message, "error");
  }
});

loadEntityOptions().catch((error) => {
  setStatus(error.message, "error");
});
