/* ---- licence agreement gate ---- */
let TERMS_VERSION = "";
let termsBusy = false;
let termsRead = false;
let authBooted = false;

const SCROLL_TOLERANCE = 24;

function termsAtBottom(el) {
	if (el.scrollHeight <= el.clientHeight + 1) return true;
	return el.scrollHeight - el.scrollTop - el.clientHeight <= SCROLL_TOLERANCE;
}

function syncTermsButton() {
	const agreed = $("#termsAgree").checked;
	$("#termsAcceptBtn").disabled = !(termsRead && agreed);
	const note = $("#termsNote");
	if (!termsRead) {
		note.textContent = "Scroll to the end of the agreement to continue.";
		note.classList.remove("done");
	} else if (!agreed) {
		note.textContent = "Tick the box below to confirm you accept the agreement.";
		note.classList.remove("done");
	} else {
		note.textContent = "Ready to accept.";
		note.classList.add("done");
	}
}

function renderTerms(version, text) {
	TERMS_VERSION = version || "";
	const doc = $("#termsDoc");
	if (typeof md === "function" && text) {
		doc.innerHTML = md(text);
		doc.classList.add("md");
	} else {
		doc.textContent = text || "The licence agreement could not be loaded.";
		doc.classList.remove("md");
	}
	$("#termsVer").textContent = version ? "version " + version : "";
	doc.scrollTop = 0;
	termsRead = false;
	$("#termsAgree").checked = false;
	$("#termsErr").textContent = "";
	syncTermsButton();
	requestAnimationFrame(() => {
		if (termsAtBottom(doc)) { termsRead = true; syncTermsButton(); }
	});
}

function showTermsCard(which) {
	$("#termsGate").classList.remove("hidden");
	$("#termsMain").classList.toggle("hidden", which !== "main");
	$("#termsDeclined").classList.toggle("hidden", which !== "declined");
}

async function loadTerms() {
	const r = await fetch("/api/terms");
	const j = await r.json();
	renderTerms(j.version, j.text);
	return j;
}

async function showTermsGate() {
	if (!$("#termsGate").classList.contains("hidden")) return;
	showTermsCard("main");
	try { await loadTerms(); }
	catch { $("#termsErr").textContent = "Could not reach the server."; }
}
window.showTermsGate = showTermsGate;

$("#termsDoc").addEventListener("scroll", () => {
	if (termsRead) return;
	if (!termsAtBottom($("#termsDoc"))) return;
	termsRead = true;
	syncTermsButton();
});

$("#termsAgree").addEventListener("change", syncTermsButton);

$("#termsDecline").onclick = () => showTermsCard("declined");
$("#termsBack").onclick = () => showTermsCard("main");

$("#termsAcceptBtn").onclick = async () => {
	if (termsBusy) return;
	termsBusy = true;
	$("#termsErr").textContent = "";
	try {
		const r = await fetch("/api/terms/accept", {
			method: "POST",
			headers: { "content-type": "application/json" },
			body: JSON.stringify({ version: TERMS_VERSION }),
		});
		const j = await r.json().catch(() => ({}));
		if (!r.ok || j.ok !== true) {
			$("#termsErr").textContent = j.error === "version mismatch"
				? "The agreement was updated. Reload CloudEye and read the new version."
				: (j.error || "Could not record your acceptance.");
			return;
		}
		$("#termsGate").classList.add("hidden");
		if (!authBooted) { authBooted = true; bootAuth(); }
	} catch {
		$("#termsErr").textContent = "Could not reach the server.";
	} finally { termsBusy = false; }
};

/* ---- boot: terms first, then the auth gate ---- */
(async () => {
	let t = null;
	try { t = await loadTerms(); } catch { }
	if (t && t.accepted) {
		authBooted = true;
		bootAuth();
		return;
	}
	if (!t) {
		$("#termsErr").textContent = "Could not reach the server.";
	}
	showTermsCard("main");
})();
