/* ProofWarden — live console (progressive enhancement for the Running view).
 *
 * With JS on, the live log streams over SSE (real-time, Pause, auto-scroll, and a
 * per-run selector) instead of the 3-second full-page <meta refresh> — which we
 * remove here so it can't reload the page mid-stream. With JS off, that
 * meta-refresh stays and none of this runs: the view degrades to exactly today's
 * behavior. Telemetry only — authority state (the lease cards) stays the warden's.
 */
(function () {
  "use strict";
  var box = document.getElementById("pw-live");
  if (!box || typeof EventSource === "undefined") return;

  // PE: this view drives its own log now — drop the whole-page auto-refresh.
  var meta = document.querySelector('meta[http-equiv="refresh"]');
  if (meta && meta.parentNode) meta.parentNode.removeChild(meta);

  var consoleEl = box.querySelector(".console");
  if (!consoleEl) return;
  var slug = box.getAttribute("data-slug");
  var pauseBtn = document.getElementById("pw-pause");
  var selectEl = document.getElementById("pw-run-select");
  var countEl = document.getElementById("pw-ev-count");

  var runId = box.getAttribute("data-run");
  var since = parseInt(box.getAttribute("data-seq") || "0", 10) || 0;
  var count = parseInt((countEl && countEl.textContent) || "0", 10) || 0;
  var paused = false;
  var es = null;

  // reveal JS-only controls (hidden by default so JS-off shows nothing broken)
  if (pauseBtn) pauseBtn.hidden = false;
  if (selectEl) selectEl.hidden = false;

  function nearBottom() {
    return consoleEl.scrollHeight - consoleEl.scrollTop - consoleEl.clientHeight < 48;
  }
  function cell(cls, text) {
    var s = document.createElement("span");
    s.className = cls;
    s.textContent = text; // text is test output — never innerHTML
    return s;
  }
  function append(line) {
    var stick = nearBottom();
    var row = document.createElement("div");
    row.className = "console__line";
    row.appendChild(cell("console__seq", "#" + line.seq));
    row.appendChild(cell("console__ts", line.ts));
    row.appendChild(cell("console__kind kind--" + line.kind_class, line.kind));
    row.appendChild(cell("console__text", line.text));
    consoleEl.appendChild(row);
    count += 1;
    if (countEl) countEl.textContent = String(count);
    if (!paused && stick) consoleEl.scrollTop = consoleEl.scrollHeight;
  }
  function ended() {
    var row = document.createElement("div");
    row.className = "console__line console__line--end";
    row.appendChild(cell("console__text", "· run ended ·"));
    consoleEl.appendChild(row);
    if (!paused) consoleEl.scrollTop = consoleEl.scrollHeight;
    // reload once so the lease cards reflect the finished run (as the meta-refresh did)
    setTimeout(function () { window.location.reload(); }, 1400);
  }
  function connect(rid, fromSeq) {
    if (es) es.close();
    if (!rid) return;
    es = new EventSource("/p/" + slug + "/stream/" + encodeURIComponent(rid) + "?since=" + fromSeq);
    es.onmessage = function (ev) {
      try { append(JSON.parse(ev.data)); } catch (e) { /* skip a partial frame */ }
    };
    es.addEventListener("end", function () { if (es) es.close(); ended(); });
    // onerror: EventSource auto-reconnects — nothing to do.
  }

  if (pauseBtn) {
    pauseBtn.addEventListener("click", function () {
      paused = !paused;
      pauseBtn.textContent = paused ? "Resume" : "Pause";
      pauseBtn.setAttribute("aria-pressed", paused ? "true" : "false");
      if (!paused) consoleEl.scrollTop = consoleEl.scrollHeight;
    });
  }
  if (selectEl) {
    selectEl.addEventListener("change", function () {
      runId = selectEl.value;
      count = 0;
      if (countEl) countEl.textContent = "0";
      while (consoleEl.firstChild) consoleEl.removeChild(consoleEl.firstChild);
      connect(runId, 0); // switch run — stream from the start
    });
  }

  connect(runId, since);
})();
