/* =========================================================
   ENGINE
   ========================================================= */
const $ = (s, el=document) => el.querySelector(s);
const $$ = (s, el=document) => [...el.querySelectorAll(s)];

const rawFetch = window.fetch.bind(window);
window.fetch = async (input, init) => {
	const r = await rawFetch(input, init);
	const u = typeof input === "string" ? input : (input && input.url) || "";
	const guarded = u.startsWith("/api/") && !u.startsWith("/api/auth/") && !u.startsWith("/api/terms");
	if (guarded && r.status === 401 && typeof window.showSignIn === "function") window.showSignIn();
	if (guarded && r.status === 403 && typeof window.showTermsGate === "function") {
		const j = await r.clone().json().catch(() => null);
		if (j && j.error === "terms not accepted") window.showTermsGate();
	}
	return r;
};
let ENV = "prod";
let CFG = null;
let LIVE = null, liveDrawerNode = null;
let mapSource = "curated";
const wsCurated = () => {
	if (!CFG || CFG.workspace === undefined) return true;
	return !!CFG.workspace && CFG.workspace.curated === true;
};
const wsZero = () => !!CFG && CFG.workspace !== undefined && !CFG.workspace && Array.isArray(CFG.workspaces) && !CFG.workspaces.length;
const wsName = () => CFG?.workspace?.name || (CFG && CFG.workspace !== undefined ? "CloudEye" : "Fairground");
const wsKey = (base) => base + ":" + (CFG?.activeWorkspace || "none");
function wsGet(store, base) {
	const key = wsKey(base);
	let v = store.getItem(key);
	if (v === null && CFG?.workspace?.curated === true) {
		const legacy = store.getItem(base);
		if (legacy !== null) { store.setItem(key, legacy); v = legacy; }
	}
	return v;
}
const escHtml = (s) => String(s ?? "").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/"/g, "&quot;");
const envName = (str) => {
	const e = CFG?.envs?.find((x) => x.key === ENV);
	return str.replaceAll("<env>", ENV)
		.replaceAll("<profile>", LIVE?.profile || e?.profiles?.at(-1) || ENV)
		.replaceAll("<acct>", e?.account || "");
};

/* ---- console urls ---- */
const envCfg = () => CFG?.envs?.find((x) => x.key === ENV) || {};
function awsConsoleUrl(kind, arg) {
	const e = envCfg();
	const region = e.region || "eu-west-2";
	const c = `https://${region}.console.aws.amazon.com`;
	if (kind === "ecs") return `${c}/ecs/v2/clusters/${e.cluster || ""}/services/${e.service || ""}/health?region=${region}`;
	if (kind === "logGroup") {
		const g = arg || e.logGroup || "";
		return `${c}/cloudwatch/home?region=${region}#logsV2:log-groups/log-group/${encodeURIComponent(encodeURIComponent(g)).replace(/%/g, "$")}`;
	}
	if (kind === "lambda") return `${c}/lambda/home?region=${region}#/functions/${arg || ""}`;
	if (kind === "alarm") return `${c}/cloudwatch/home?region=${region}#alarmsV2:` + (arg ? `alarm/${encodeURIComponent(arg)}` : "");
	if (kind === "sqs") return `${c}/sqs/v3/home?region=${region}#/queues`;
	if (kind === "cost") return "https://console.aws.amazon.com/costmanagement/home#/cost-explorer";
	if (kind === "trail") return `${c}/cloudtrailv2/home?region=${region}#/events` + (arg ? `?EventName=${encodeURIComponent(arg)}` : "");
	if (kind === "guardduty") return `${c}/guardduty/home?region=${region}#/findings`;
	if (kind === "iam") return "https://console.aws.amazon.com/iam/home#/users";
	if (kind === "sg") return `${c}/ec2/home?region=${region}#SecurityGroups:`;
	return "";
}
const extLink = (url, label) => url ? `<a class="xl" href="${url}" target="_blank" rel="noopener">${label ? label + " " : ""}↗</a>` : "";

/* ---- tabs ---- */
$$(".tab").forEach(b => b.onclick = () => {
	$$(".tab").forEach(x => x.classList.toggle("active", x === b));
	$$(".view").forEach(v => v.classList.toggle("active", v.id === b.dataset.view));
	if (typeof loadForTab === "function") loadForTab(b.dataset.view);
});
$("#themeBtn").onclick = () => {
	const d = document.body.dataset.theme === "dark";
	document.body.dataset.theme = d ? "light" : "dark";
	drawEdges();
};


