/* ---- lazy tab loading ---- */
function loadForTab(v) {
	if (v === "viewLambdas" && !LAMBDAS) fetchLambdas();
	if (v === "viewLive") {
		if (!$("#logGroup").options.length) fetchLogGroups().then(applyDefaultLogGroup);
		else applyDefaultLogGroup();
	}
	if (v === "viewOverview") { fetchCost(); fetchActivity(); }
	if (v === "viewDeploy" && !GH) fetchGithub();
	if (v === "viewMap") setTimeout(() => { drawEdges(); renderGroupBoxes(); if (!mapFitDone) { fitAll(); mapFitDone = true; } }, 30);
	if (v === "viewSettings") renderSettings();
	if (v === "viewActions" && !actionsLoaded) { actionsLoaded = true; runActions(false); }
	if (v === "viewSecurity" && typeof loadSecurityTab === "function") loadSecurityTab();
	if (typeof timelineTabChanged === "function") timelineTabChanged(v);
}

/* ---- authentication ---- */
let appStarted = false;
let authBusy = false;
const EMAIL_SHAPE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

function startApp() {
	if (appStarted) return;
	appStarted = true;
	renderNodes();
	drawEdges();
	renderQuickLinks();
	applyLayer();
	fetchConfig().then(() => {
		if (SETTINGS.defaultEnv && CFG?.envs?.some((e) => e.key === SETTINGS.defaultEnv) && SETTINGS.defaultEnv !== ENV) {
			setEnvKey(SETTINGS.defaultEnv);
		} else {
			fetchLive(); fetchLambdas(); fetchLogGroups(); fetchCost(); fetchActivity();
		}
		schedule();
		loadSavedMap();
		$("#autoSec").value = SETTINGS.autoSecLast || SETTINGS.autoSec || 30;
		applyAuto();
	});
	setTimeout(fetchGithub, 1500);
	applyDetails();
	window.addEventListener("resize", drawEdges);
}

function setAccount(email) {
	$("#acctBox").style.display = email ? "flex" : "none";
	$("#acctEmail").textContent = email || "";
	$("#acctEmail").title = email || "";
}

function showAuthCard(which) {
	$("#authGate").classList.remove("hidden");
	$("#setupForm").style.display = which === "setup" ? "flex" : "none";
	$("#loginForm").style.display = which === "login" ? "flex" : "none";
	$("#authSub").textContent = which === "setup" ? "set up the account for this console" : "sign in to continue";
	setTimeout(() => $(which === "setup" ? "#suEmail" : "#liEmail")?.focus(), 80);
}

function showSignIn() {
	$("#liErr").textContent = "";
	$("#liPw").value = "";
	showAuthCard("login");
}
window.showSignIn = showSignIn;

function enterApp(email) {
	$("#authGate").classList.add("hidden");
	setAccount(email);
	if (appStarted) return;
	if (sessionStorage.getItem("me-skip-home") === "1") sessionStorage.removeItem("me-skip-home");
	else $("#homeScreen").classList.remove("hidden");
	startApp();
}

function markErr(inp) {
	inp.classList.remove("err"); void inp.offsetWidth; inp.classList.add("err");
	inp.focus();
}

async function postAuth(path, body) {
	const r = await fetch(path, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) });
	const j = await r.json().catch(() => ({}));
	return { ok: r.ok && j.ok === true, j };
}

$("#setupForm").addEventListener("submit", async (e) => {
	e.preventDefault();
	if (authBusy) return;
	const err = $("#suErr");
	const email = $("#suEmail").value.trim();
	const pw = $("#suPw").value;
	err.textContent = "";
	if (!EMAIL_SHAPE.test(email)) { err.textContent = "Enter a valid email address."; return markErr($("#suEmail")); }
	if (pw.length < 8) { err.textContent = "Password must be at least 8 characters."; return markErr($("#suPw")); }
	if (pw !== $("#suPw2").value) { err.textContent = "Passwords do not match."; return markErr($("#suPw2")); }
	authBusy = true;
	try {
		const { ok, j } = await postAuth("/api/auth/setup", { email, password: pw });
		if (ok) return enterApp(j.email);
		err.textContent = j.error || "Setup failed.";
	} catch {
		err.textContent = "Could not reach the server.";
	} finally { authBusy = false; }
});

$("#loginForm").addEventListener("submit", async (e) => {
	e.preventDefault();
	if (authBusy) return;
	const err = $("#liErr");
	const email = $("#liEmail").value.trim();
	const pw = $("#liPw").value;
	err.textContent = "";
	if (!email || !pw) { err.textContent = "Email and password are required."; return markErr(!email ? $("#liEmail") : $("#liPw")); }
	authBusy = true;
	try {
		const { ok, j } = await postAuth("/api/auth/login", { email, password: pw });
		if (ok) { $("#liPw").value = ""; return enterApp(j.email); }
		err.textContent = j.error || "Sign in failed.";
		markErr($("#liPw"));
	} catch {
		err.textContent = "Could not reach the server.";
	} finally { authBusy = false; }
});

$("#signOutBtn").onclick = async () => {
	try { await fetch("/api/auth/logout", { method: "POST" }); } catch { }
	setAccount("");
	showSignIn();
};

$("#wsFairground").onclick = () => $("#homeScreen").classList.add("hidden");
$("#backHome").onclick = () => $("#homeScreen").classList.remove("hidden");

localStorage.removeItem("me-syschat");
/* ---- boot ---- */
async function bootAuth() {
	let st = null;
	try { st = await (await fetch("/api/auth/status")).json(); } catch { }
	if (st && st.authed) enterApp(st.email);
	else if (st && st.setup) showAuthCard("login");
	else showAuthCard("setup");
}
window.bootAuth = bootAuth;
