"use strict";
const $ = (sel) => document.querySelector(sel);
// When the server requires a token, it arrives as ?token=… on this page URL;
// forward it on every API request.
const TOKEN = new URLSearchParams(location.search).get("token");
const u = (url) =>
  TOKEN ? url + (url.includes("?") ? "&" : "?") + "token=" + encodeURIComponent(TOKEN) : url;

async function loadPages() {
  try {
    const r = await fetch(u("/api/pages"));
    $("#pages").innerHTML = await r.text();
    $("#pages").classList.remove("dim");
  } catch (e) {
    $("#pages").textContent = "failed to load pages";
  }
}

async function loadStatus() {
  try {
    const r = await fetch(u("/api/status"));
    const txt = await r.text();
    $("#status-line").textContent = (txt.split("\n").find((l) => l.includes("wiki:")) || "").trim();
  } catch (e) {
    /* ignore */
  }
}

// Page navigation (event delegation over sidebar links).
document.addEventListener("click", async (e) => {
  const link = e.target.closest("[data-path]");
  if (!link) return;
  e.preventDefault();
  const r = await fetch(u("/api/page?path=" + encodeURIComponent(link.dataset.path)));
  $("#page").innerHTML = await r.text();
  window.scrollTo(0, 0);
});

// Client-side sidebar filter (browse convenience, not ranked search).
$("#filter").addEventListener("input", (e) => {
  const q = e.target.value.toLowerCase();
  document.querySelectorAll("#pages a[data-path]").forEach((a) => {
    a.style.display = a.textContent.toLowerCase().includes(q) ? "" : "none";
  });
});

// Ask: stream progress + answer over SSE.
$("#ask-form").addEventListener("submit", (e) => {
  e.preventDefault();
  const q = $("#q").value.trim();
  if (!q) return;
  $("#progress").textContent = "";
  $("#answer").innerHTML = "";
  let url = "/api/ask?q=" + encodeURIComponent(q);
  if ($("#save").checked) url += "&save=1";
  const es = new EventSource(u(url));
  es.addEventListener("progress", (ev) => {
    $("#progress").textContent += ev.data + "\n";
  });
  es.addEventListener("answer", (ev) => {
    $("#answer").innerHTML = ev.data;
  });
  es.addEventListener("done", () => es.close());
  es.onerror = () => es.close();
});

loadPages();
loadStatus();
