/* ---- system chatbot ---- */
let SYSCHAT = [];
let SC_SID = null;
let scSidPromise = null;
function loadChatState() {
	SYSCHAT = [];
	SC_SID = wsGet(sessionStorage, "me-syschat-sid") || null;
	scLoadHistory();
}
function scEnsureSession() {
	if (SC_SID) return Promise.resolve(SC_SID);
	if (!scSidPromise) {
		scSidPromise = fetch("/api/chat/session", { method: "POST" })
			.then((r) => r.json())
			.then((d) => {
				if (d.id) { SC_SID = d.id; sessionStorage.setItem(wsKey("me-syschat-sid"), SC_SID); }
				return SC_SID;
			})
			.catch(() => null)
			.finally(() => { scSidPromise = null; });
	}
	return scSidPromise;
}
function scStore(role, content) {
	scEnsureSession().then((sid) => {
		if (!sid) return;
		fetch("/api/chat/message", { method: "POST", body: JSON.stringify({ sessionId: sid, role, content }) }).catch(() => {});
	});
}
async function scLoadHistory() {
	if (!SC_SID) return;
	try {
		const r = await fetch(`/api/chat/session?id=${encodeURIComponent(SC_SID)}`);
		const d = await r.json();
		if (!d.id) { SC_SID = null; sessionStorage.removeItem(wsKey("me-syschat-sid")); return; }
		const hist = [];
		for (const msg of d.messages || []) {
			if (msg.role === "user") hist.push({ q: msg.content, a: "", t: msg.ts });
			else if (hist.length && hist[hist.length - 1].a === "") { hist[hist.length - 1].a = msg.content; hist[hist.length - 1].t = msg.ts; }
			else hist.push({ q: "", a: msg.content, t: msg.ts });
		}
		SYSCHAT = hist;
		scRender();
	} catch {}
}
const SC_AV = `<svg class="lc-av" viewBox="0 0 1024 1024"><rect x="64" y="64" width="896" height="896" rx="184" fill="#0e172b"/><circle cx="512" cy="554" r="210" fill="#fff"/><circle cx="316" cy="604" r="132" fill="#fff"/><circle cx="712" cy="600" r="144" fill="#fff"/><rect x="300" y="576" width="428" height="160" rx="60" fill="#fff"/><circle cx="512" cy="554" r="118" fill="#3b82f6"/><circle cx="512" cy="554" r="58" fill="#0a1224"/><circle cx="548" cy="516" r="22" fill="#f2f5fa"/></svg>`;
const SC_SUGGEST = ["How is memory right now?", "What shipped today?", "Which lambdas are failing?", "Is it safe to release to prod?"];
function scRender() {
	const m = $("#scMsgs");
	m.innerHTML = SYSCHAT.length
		? SYSCHAT.map((h) => `<div class="lc-q">${h.q.replace(/&/g, "&amp;").replace(/</g, "&lt;")}</div><div class="lc-row">${SC_AV}<div class="lc-a ai-box">${md(h.a)}</div></div>`).join("")
		: `<div class="lc-row">${SC_AV}<div class="lc-a ai-box">I can see your live system right now — metrics, deploys, errors, cost. Ask me anything.<div class="sc-chips">${SC_SUGGEST.map((q) => `<button class="sc-chip">${q}</button>`).join("")}</div></div></div>`;
	$$(".sc-chip", m).forEach((c) => c.onclick = () => { $("#scQ").value = c.textContent; scSend(); });
	bindCopies(m);
	m.scrollTop = m.scrollHeight;
}
function scToggle(open) {
	const c = $("#sysChat");
	c.classList.toggle("open", open ?? !c.classList.contains("open"));
	if (c.classList.contains("open")) { scRender(); $("#scQ").focus(); }
}
$("#chatFab").onclick = () => scToggle();
$("#scClose").onclick = () => scToggle(false);
$("#scMax").onclick = () => {
	const max = $("#sysChat").classList.toggle("max");
	$("#scMax").textContent = max ? "⤡" : "⤢";
	localStorage.setItem("me-chat-max", max ? "1" : "0");
	$("#scQ").focus();
};
if (localStorage.getItem("me-chat-max") === "1") { $("#sysChat").classList.add("max"); $("#scMax").textContent = "⤡"; }
$("#scClear").onclick = () => {
	SYSCHAT = [];
	if (SC_SID) fetch(`/api/chat/session?id=${encodeURIComponent(SC_SID)}`, { method: "DELETE" }).catch(() => {});
	SC_SID = null;
	sessionStorage.removeItem(wsKey("me-syschat-sid"));
	scRender();
};
async function typewrite(el, text) {
	el.classList.add("typing");
	el.textContent = "";
	const scroller = el.closest(".lc-msgs") || el.parentElement;
	const words = text.replace(/[#*`|]|^-{3,}$/gm, "").split(/(\s+)/);
	for (let i = 0; i < words.length; i += 3) {
		el.textContent += words.slice(i, i + 3).join("");
		scroller.scrollTop = scroller.scrollHeight;
		await new Promise((r) => setTimeout(r, 24));
	}
	el.classList.remove("typing");
	el.innerHTML = md(text);
	bindCopies(el);
	scroller.scrollTop = scroller.scrollHeight;
}
async function scSend() {
	const q = $("#scQ").value.trim();
	if (!q) return;
	$("#scQ").value = "";
	const m = $("#scMsgs");
	if (!SYSCHAT.length) m.innerHTML = "";
	m.insertAdjacentHTML("beforeend", `<div class="lc-q">${q.replace(/&/g, "&amp;").replace(/</g, "&lt;")}</div>`);
	scStore("user", q);
	const row = document.createElement("div");
	row.className = "lc-row";
	row.innerHTML = SC_AV;
	const a = document.createElement("div");
	a.className = "lc-a ai-box typing";
	a.textContent = "checking the live system";
	row.appendChild(a);
	m.appendChild(row);
	m.scrollTop = m.scrollHeight;
	try {
		const r = await fetch(`/api/ai/chat?env=${ENV}`, { method: "POST", body: JSON.stringify({ question: q, scope: "system", history: SYSCHAT.slice(-4) }) });
		const d = await r.json();
		if (!d.ok) { a.classList.remove("typing"); a.textContent = d.detail || "unavailable"; return; }
		await typewrite(a, d.answer);
		SYSCHAT.push({ q, a: d.answer, t: Date.now() });
		SYSCHAT = SYSCHAT.slice(-20);
		scStore("assistant", d.answer);
	} catch { a.classList.remove("typing"); a.textContent = "unavailable — is the sync server running?"; }
}
$("#scSend").onclick = scSend;
$("#scQ").addEventListener("keydown", (e) => { if (e.key === "Enter") scSend(); });

