/* ---- AI analyst tab ---- */
async function runActions(fresh) {
	const box = $("#actBox");
	box.innerHTML = `<div class="ai-box thinking">Reading the live state and writing your action list…</div>`;
	try {
		const r = await fetch(`/api/ai/actions?env=${ENV}${fresh ? "&fresh=1" : ""}`);
		const d = await r.json();
		if (!d.ok) { box.innerHTML = `<div class="ai-box">${d.detail || "unavailable"}</div>`; return; }
		const sevCls = { critical: "crit-a", warning: "warn-a", routine: "rout-a" };
		box.innerHTML = d.actions.map((a, i) => {
			const txt = `${a.title} ${a.why} ${a.command || ""}`;
			const links = [["ECS service", awsConsoleUrl("ecs")], ["Backend logs", awsConsoleUrl("logGroup")]];
			(LAMBDAS?.functions || []).forEach((f) => { if (txt.includes(f.name)) links.push([f.name, awsConsoleUrl("lambda", f.name)]); });
			if ((LIVE?.sections?.queues || []).some((q) => txt.includes(q.name))) links.push(["SQS queues", awsConsoleUrl("sqs")]);
			return `
			<div class="axn${i === 0 ? " open" : ""}">
				<div class="axn-head"><span class="sev ${sevCls[a.sev]}">${a.sev.toUpperCase()}</span><b>${a.title}</b><span class="chev">▸</span></div>
				<div class="axn-body">${a.why}${a.command ? `<div class="cmd">${a.command.replace(/&/g, "&amp;").replace(/</g, "&lt;")}<button class="copy">copy</button></div>` : ""}<div class="axn-links">${links.map(([t, u]) => extLink(u, t)).join("")}</div></div>
			</div>`;
		}).join("");
		bindCopies(box);
		$$(".axn", box).forEach((c) => $(".axn-head", c).onclick = () => c.classList.toggle("open"));
		$("#actMeta").textContent = `generated ${agoTxt(d.fetchedAt)}`;
	} catch { box.innerHTML = `<div class="ai-box">unavailable — is the sync server running?</div>`; }
}
let actionsLoaded = false;
$("#actRegen").onclick = () => runActions(true);

$("#aiRun").onclick = async () => {
	const out = $("#aiOut");
	out.className = "ai-box thinking";
	out.textContent = "Analyzing live snapshot, alarms, queues and recent error logs…";
	try {
		const r = await fetch(`/api/ai/analyze?env=${encodeURIComponent(ENV)}`);
		const d = await r.json();
		out.className = "ai-box";
		if (d.ok) { out.innerHTML = md(d.analysis); bindCopies(out); $("#aiMeta").textContent = `${d.model.split(".").pop()} · ${agoTxt(d.fetchedAt)} · cached 5 min`; }
		else out.textContent = d.detail || "AI unavailable";
	} catch { out.className = "ai-box"; out.textContent = "AI unavailable — is the sync server running?"; }
};

/* ---- copy status report ---- */
$("#copyReport").onclick = () => {
	const s = LIVE?.sections || {};
	const mem = s.memory?.at(-1), issues = deriveIssues();
	const lines = [
		`*${wsName()} ${ENV} status · ${new Date().toLocaleString("en-GB")}*`,
		s.ecs ? `• tasks: ${s.ecs.running}/${s.ecs.desired} (${s.ecs.rollout}, ${s.ecs.taskDef})` : "",
		mem ? `• memory: ${mem.max}% max · cpu: ${s.cpu?.at(-1)?.max ?? "?"}%` : "",
		s.targets ? `• targets: ${s.targets.healthy}/${s.targets.total} healthy` : "",
		s.pings?.api ? `• api health: ${s.pings.api.status} in ${s.pings.api.ms}ms` : "",
		`• alarms firing: ${firingAlarms().length}`,
		issues.length ? `\n*Issues:*\n` + issues.map((i) => `• [${i.sev}] ${i.tx.replace(/<[^>]+>/g, "")}`).join("\n") : "\n✓ no issues detected",
	].filter(Boolean);
	navigator.clipboard.writeText(lines.join("\n"));
	$("#copyReport").textContent = "✓ copied";
	setTimeout(() => $("#copyReport").textContent = "Copy status report", 1200);
};

/* ---- shortcuts help ---- */
$("#helpBtn").onclick = () => {
	const g = document.createElement("div");
	g.className = "gate";
	g.style.background = "rgba(0,0,0,0.5)";
	g.innerHTML = `<div class="gate-card" style="text-align:left;width:420px">
		<h2 style="text-align:center;margin-bottom:14px">Shortcuts</h2>
		${[["⌘K", "search everything"], ["1–8", "switch tabs"], ["f", "fit map"], ["← →", "walkthrough steps"], ["esc", "close panels"], ["double-click node", "zoom to it"], ["double-click empty map", "sticky note"], ["drag empty map", "pan"], ["⌘/ctrl + scroll", "zoom"]].map(([k, v]) => `<div class="kbd-row"><span>${v}</span><kbd>${k}</kbd></div>`).join("")}
	</div>`;
	g.onclick = () => g.remove();
	document.body.appendChild(g);
};

