/* ---- deploy tab ---- */
const pipeListEl = $("#pipeList");
PIPELINES.forEach((p, i) => {
	const b = document.createElement("button");
	b.className = "pipe-item" + (i === 0 ? " active" : "");
	b.innerHTML = `${p.name}<small>${p.meta.split("·")[0]}</small>`;
	b.onclick = () => { $$(".pipe-item").forEach(x => x.classList.toggle("active", x === b)); renderPipe(p); };
	pipeListEl.appendChild(b);
});
function renderPipe(p) {
	let h = `<h2>${p.name}</h2><p class="meta">${p.meta}</p>`;
	p.steps.forEach(([t, d, cmd], i) => {
		h += `<div class="pstep on"><div class="num">${i + 1}</div><div class="txt"><h5>${t}</h5><p>${envName(d).replace(/</g, "&lt;").replace(/&lt;(b|\/b|code|\/code|br)&gt;/g, "<$1>")}</p>` +
			(cmd ? `<div class="cmd">${envName(cmd)}<button class="copy">copy</button></div>` : "") + `</div></div>`;
	});
	if (p.callout) h += `<div class="callout ${p.callout[0] === "crit" ? "crit" : ""}">${p.callout[1]}</div>`;
	$("#pipeDetail").innerHTML = h;
	bindCopies($("#pipeDetail"));
}
renderPipe(PIPELINES[0]);

/* ---- logs tab ---- */
function renderLogs() {
	const tb = $("#logTable tbody");
	tb.innerHTML = LOGS.map(([c, g, r, cmd]) =>
		`<tr><td><b>${c}</b></td><td style="font-family:ui-monospace,Menlo,monospace;font-size:11.5px">${envName(g)}</td><td class="ret">${r}</td><td><div class="cmd">${envName(cmd + " --profile <profile> --region " + (envCfg().region || "eu-west-2"))}<button class="copy">copy</button></div></td></tr>`).join("");
	bindCopies(tb);
}
let RUNBOOKS = RUNBOOK.map(([sev, t, body]) => ({ sev, t, body, html: true }));
let runbooksFromServer = false;
let rbEditing = -1;
function renderRunbooks() {
	$("#runbook").innerHTML = RUNBOOKS.length ? RUNBOOKS.map((r, i) =>
		`<details class="acc"><summary><span class="sev ${r.sev}">${r.sev.toUpperCase()}</span> ${r.t}<span class="rb-acts"><button class="btn" data-rbe="${i}">edit</button><button class="btn" data-rbd="${i}">delete</button></span></summary><div class="acc-body">${r.html ? r.body : md(r.body)}</div></details>`).join("")
		: `<p class="cfg-note">No runbooks yet. Add the first fix procedure for this workspace.</p>`;
	bindCopies($("#runbook"));
	$$("[data-rbe]").forEach((b) => b.onclick = (e) => { e.preventDefault(); e.stopPropagation(); openRbForm(+b.dataset.rbe); });
	$$("[data-rbd]").forEach((b) => b.onclick = (e) => {
		e.preventDefault(); e.stopPropagation();
		RUNBOOKS.splice(+b.dataset.rbd, 1);
		saveRunbooks(); renderRunbooks();
	});
}
function openRbForm(i) {
	rbEditing = i;
	$("#rbForm").style.display = "block";
	$("#rbTitle").value = i >= 0 ? RUNBOOKS[i].t : "";
	$("#rbSev").value = i >= 0 ? RUNBOOKS[i].sev : "p2";
	$("#rbBody").value = i >= 0 ? (RUNBOOKS[i].html ? RUNBOOKS[i].body.replace(/<[^>]+>/g, "") : RUNBOOKS[i].body) : "";
	$("#rbTitle").focus();
}
async function saveRunbooks() {
	runbooksFromServer = true;
	try { await fetch("/api/runbooks", { method: "POST", body: JSON.stringify({ items: RUNBOOKS }) }); } catch { }
}
$("#rbAdd").onclick = () => openRbForm(-1);
$("#rbCancel").onclick = () => { $("#rbForm").style.display = "none"; };
$("#rbSave").onclick = () => {
	const t = $("#rbTitle").value.trim();
	if (!t) { $("#rbMsg").textContent = "title required"; return; }
	const item = { sev: $("#rbSev").value, t, body: $("#rbBody").value, html: false };
	if (rbEditing >= 0) RUNBOOKS[rbEditing] = item; else RUNBOOKS.unshift(item);
	$("#rbForm").style.display = "none";
	saveRunbooks(); renderRunbooks();
};
async function loadRunbooks() {
	try {
		const r = await fetch("/api/runbooks");
		const d = await r.json();
		if (Array.isArray(d.items) && d.items.length) { RUNBOOKS = d.items; runbooksFromServer = true; }
		else if (!wsCurated()) RUNBOOKS = [];
	} catch { }
	renderRunbooks();
}
loadRunbooks();
bindCopies($("#viewLogs"));
renderLogs();



