import { __name, log } from "./chunk-AGHRB4JF.js";
import { common_default, getConfig, hasKatex, renderKatexSanitized, sanitizeText } from "./chunk-ABZYJK2D.js";
import select_default from "../../../../d3-selection/src/select.js";
import "../../../../d3/src/index.js";
import { decodeEntities } from "./chunk-S3R3BYOJ.js";
import { stringToIcon } from "../../../../@iconify/utils/lib/icon/name.js";
import { getIconData } from "../../../../@iconify/utils/lib/icon-set/get-icon.js";
import { iconToSVG } from "../../../../@iconify/utils/lib/svg/build.js";
import { replaceIDs } from "../../../../@iconify/utils/lib/svg/id.js";
import { iconToHTML } from "../../../../@iconify/utils/lib/svg/html.js";
import { k } from "../../../../marked/lib/marked.esm.js";
import { dedent } from "../../../../ts-dedent/esm/index.js";
var unknownIcon = {
	body: "<g><rect width=\"80\" height=\"80\" style=\"fill: #087ebf; stroke-width: 0px;\"/><text transform=\"translate(21.16 64.67)\" style=\"fill: #fff; font-family: ArialMT, Arial; font-size: 67.75px;\"><tspan x=\"0\" y=\"0\">?</tspan></text></g>",
	height: 80,
	width: 80
}, iconsStore = /* @__PURE__ */ new Map(), loaderStore = /* @__PURE__ */ new Map(), registerIconPacks = /* @__PURE__ */ __name((i) => {
	for (let T of i) {
		if (!T.name) throw Error("Invalid icon loader. Must have a \"name\" property with non-empty string value.");
		if (log.debug("Registering icon pack:", T.name), "loader" in T) loaderStore.set(T.name, T.loader);
		else if ("icons" in T) iconsStore.set(T.name, T.icons);
		else throw log.error("Invalid icon loader:", T), Error("Invalid icon loader. Must have either \"icons\" or \"loader\" property.");
	}
}, "registerIconPacks"), getRegisteredIconData = /* @__PURE__ */ __name(async (i, T) => {
	let E = stringToIcon(i, !0, T !== void 0);
	if (!E) throw Error(`Invalid icon name: ${i}`);
	let D = E.prefix || T;
	if (!D) throw Error(`Icon name must contain a prefix: ${i}`);
	let O = iconsStore.get(D);
	if (!O) {
		let i = loaderStore.get(D);
		if (!i) throw Error(`Icon set not found: ${E.prefix}`);
		try {
			O = {
				...await i(),
				prefix: D
			}, iconsStore.set(D, O);
		} catch (i) {
			throw log.error(i), Error(`Failed to load icon set: ${E.prefix}`);
		}
	}
	let A = getIconData(O, E.name);
	if (!A) throw Error(`Icon not found: ${i}`);
	return A;
}, "getRegisteredIconData"), isIconAvailable = /* @__PURE__ */ __name(async (i) => {
	try {
		return await getRegisteredIconData(i), !0;
	} catch {
		return !1;
	}
}, "isIconAvailable"), getIconSVG = /* @__PURE__ */ __name(async (i, T, D) => {
	let O;
	try {
		O = await getRegisteredIconData(i, T?.fallbackPrefix);
	} catch (i) {
		log.error(i), O = unknownIcon;
	}
	let j = iconToSVG(O, T);
	return sanitizeText(iconToHTML(replaceIDs(j.body), {
		...j.attributes,
		...D
	}), getConfig());
}, "getIconSVG");
function preprocessMarkdown(i, { markdownAutoWrap: w }) {
	let T = dedent(i.replace(/<br\/>/g, "\n").replace(/\n{2,}/g, "\n"));
	return w === !1 ? T.replace(/ /g, "&nbsp;") : T;
}
__name(preprocessMarkdown, "preprocessMarkdown");
function markdownToLines(w, T = {}) {
	let E = preprocessMarkdown(w, T), D = k.lexer(E), O = [[]], A = 0;
	function j(i, w = "normal") {
		i.type === "text" ? i.text.split("\n").forEach((i, T) => {
			T !== 0 && (A++, O.push([])), i.split(" ").forEach((i) => {
				i = i.replace(/&#39;/g, "'"), i && O[A].push({
					content: i,
					type: w
				});
			});
		}) : i.type === "strong" || i.type === "em" ? i.tokens.forEach((w) => {
			j(w, i.type);
		}) : i.type === "html" && O[A].push({
			content: i.text,
			type: "normal"
		});
	}
	return __name(j, "processNode"), D.forEach((i) => {
		i.type === "paragraph" ? i.tokens?.forEach((i) => {
			j(i);
		}) : i.type === "html" ? O[A].push({
			content: i.text,
			type: "normal"
		}) : O[A].push({
			content: i.raw,
			type: "normal"
		});
	}), O;
}
__name(markdownToLines, "markdownToLines");
function markdownToHTML(T, { markdownAutoWrap: E } = {}) {
	let D = k.lexer(T);
	function O(i) {
		return i.type === "text" ? E === !1 ? i.text.replace(/\n */g, "<br/>").replace(/ /g, "&nbsp;") : i.text.replace(/\n */g, "<br/>") : i.type === "strong" ? `<strong>${i.tokens?.map(O).join("")}</strong>` : i.type === "em" ? `<em>${i.tokens?.map(O).join("")}</em>` : i.type === "paragraph" ? `<p>${i.tokens?.map(O).join("")}</p>` : i.type === "space" ? "" : i.type === "html" ? `${i.text}` : i.type === "escape" ? i.text : (log.warn(`Unsupported markdown: ${i.type}`), i.raw);
	}
	return __name(O, "output"), D.map(O).join("");
}
__name(markdownToHTML, "markdownToHTML");
function splitTextToChars(i) {
	return Intl.Segmenter ? [...new Intl.Segmenter().segment(i)].map((i) => i.segment) : [...i];
}
__name(splitTextToChars, "splitTextToChars");
function splitWordToFitWidth(i, w) {
	return splitWordToFitWidthRecursion(i, [], splitTextToChars(w.content), w.type);
}
__name(splitWordToFitWidth, "splitWordToFitWidth");
function splitWordToFitWidthRecursion(i, w, T, E) {
	if (T.length === 0) return [{
		content: w.join(""),
		type: E
	}, {
		content: "",
		type: E
	}];
	let [D, ...O] = T, A = [...w, D];
	return i([{
		content: A.join(""),
		type: E
	}]) ? splitWordToFitWidthRecursion(i, A, O, E) : (w.length === 0 && D && (w.push(D), T.shift()), [{
		content: w.join(""),
		type: E
	}, {
		content: T.join(""),
		type: E
	}]);
}
__name(splitWordToFitWidthRecursion, "splitWordToFitWidthRecursion");
function splitLineToFitWidth(i, w) {
	if (i.some(({ content: i }) => i.includes("\n"))) throw Error("splitLineToFitWidth does not support newlines in the line");
	return splitLineToFitWidthRecursion(i, w);
}
__name(splitLineToFitWidth, "splitLineToFitWidth");
function splitLineToFitWidthRecursion(i, w, T = [], E = []) {
	if (i.length === 0) return E.length > 0 && T.push(E), T.length > 0 ? T : [];
	let D = "";
	i[0].content === " " && (D = " ", i.shift());
	let O = i.shift() ?? {
		content: " ",
		type: "normal"
	}, A = [...E];
	if (D !== "" && A.push({
		content: D,
		type: "normal"
	}), A.push(O), w(A)) return splitLineToFitWidthRecursion(i, w, T, A);
	if (E.length > 0) T.push(E), i.unshift(O);
	else if (O.content) {
		let [E, D] = splitWordToFitWidth(w, O);
		T.push([E]), D.content && i.unshift(D);
	}
	return splitLineToFitWidthRecursion(i, w, T);
}
__name(splitLineToFitWidthRecursion, "splitLineToFitWidthRecursion");
function applyStyle(i, w) {
	w && i.attr("style", w);
}
__name(applyStyle, "applyStyle");
async function addHtmlSpan(i, w, j, M, N = !1, P = getConfig()) {
	let F = i.append("foreignObject");
	F.attr("width", `${10 * j}px`), F.attr("height", `${10 * j}px`);
	let I = F.append("xhtml:div"), L = hasKatex(w.label) ? await renderKatexSanitized(w.label.replace(common_default.lineBreakRegex, "\n"), P) : sanitizeText(w.label, P), R = w.isNode ? "nodeLabel" : "edgeLabel", z = I.append("span");
	z.html(L), applyStyle(z, w.labelStyle), z.attr("class", `${R} ${M}`), applyStyle(I, w.labelStyle), I.style("display", "table-cell"), I.style("white-space", "nowrap"), I.style("line-height", "1.5"), I.style("max-width", j + "px"), I.style("text-align", "center"), I.attr("xmlns", "http://www.w3.org/1999/xhtml"), N && I.attr("class", "labelBkg");
	let B = I.node().getBoundingClientRect();
	return B.width === j && (I.style("display", "table"), I.style("white-space", "break-spaces"), I.style("width", j + "px"), B = I.node().getBoundingClientRect()), F.node();
}
__name(addHtmlSpan, "addHtmlSpan");
function createTspan(i, w, T) {
	return i.append("tspan").attr("class", "text-outer-tspan").attr("x", 0).attr("y", w * T - .1 + "em").attr("dy", T + "em");
}
__name(createTspan, "createTspan");
function computeWidthOfText(i, w, T) {
	let E = i.append("text"), D = createTspan(E, 1, w);
	updateTextContentAndStyles(D, T);
	let O = D.node().getComputedTextLength();
	return E.remove(), O;
}
__name(computeWidthOfText, "computeWidthOfText");
function computeDimensionOfText(i, w, T) {
	let E = i.append("text"), D = createTspan(E, 1, w);
	updateTextContentAndStyles(D, [{
		content: T,
		type: "normal"
	}]);
	let O = D.node()?.getBoundingClientRect();
	return O && E.remove(), O;
}
__name(computeDimensionOfText, "computeDimensionOfText");
function createFormattedText(w, T, E, D = !1) {
	let O = 1.1, A = T.append("g"), j = A.insert("rect").attr("class", "background").attr("style", "stroke: none"), M = A.append("text").attr("y", "-10.1"), N = 0;
	for (let T of E) {
		let E = /* @__PURE__ */ __name((i) => computeWidthOfText(A, O, i) <= w, "checkWidth"), D = E(T) ? [T] : splitLineToFitWidth(T, E);
		for (let i of D) updateTextContentAndStyles(createTspan(M, N, O), i), N++;
	}
	if (D) {
		let i = M.node().getBBox();
		return j.attr("x", i.x - 2).attr("y", i.y - 2).attr("width", i.width + 4).attr("height", i.height + 4), A.node();
	} else return M.node();
}
__name(createFormattedText, "createFormattedText");
function updateTextContentAndStyles(i, w) {
	i.text(""), w.forEach((w, T) => {
		let E = i.append("tspan").attr("font-style", w.type === "em" ? "italic" : "normal").attr("class", "text-inner-tspan").attr("font-weight", w.type === "strong" ? "bold" : "normal");
		T === 0 ? E.text(w.content) : E.text(" " + w.content);
	});
}
__name(updateTextContentAndStyles, "updateTextContentAndStyles");
async function replaceIconSubstring(i, w = {}) {
	let T = [];
	i.replace(/(fa[bklrs]?):fa-([\w-]+)/g, (i, E, D) => (T.push((async () => {
		let T = `${E}:${D}`;
		return await isIconAvailable(T) ? await getIconSVG(T, void 0, { class: "label-icon" }) : `<i class='${sanitizeText(i, w).replace(":", " ")}'></i>`;
	})()), i));
	let E = await Promise.all(T);
	return i.replace(/(fa[bklrs]?):fa-([\w-]+)/g, () => E.shift() ?? "");
}
__name(replaceIconSubstring, "replaceIconSubstring");
var createText = /* @__PURE__ */ __name(async (i, T = "", { style: E = "", isTitle: O = !1, classes: A = "", useHtmlLabels: N = !0, isNode: P = !0, width: F = 200, addSvgBackground: I = !1 } = {}, L) => {
	if (log.debug("XYZ createText", T, E, O, A, N, P, "addSvgBackground: ", I), N) {
		let w = await replaceIconSubstring(decodeEntities(markdownToHTML(T, L)), L), O = T.replace(/\\\\/g, "\\");
		return await addHtmlSpan(i, {
			isNode: P,
			label: hasKatex(T) ? O : w,
			labelStyle: E.replace("fill:", "color:")
		}, F, A, I, L);
	} else {
		let w = createFormattedText(F, i, markdownToLines(T.replace(/<br\s*\/?>/g, "<br/>").replace("<br>", "<br/>"), L), T ? I : !1);
		if (P) {
			/stroke:/.exec(E) && (E = E.replace("stroke:", "lineColor:"));
			let i = E.replace(/stroke:[^;]+;?/g, "").replace(/stroke-width:[^;]+;?/g, "").replace(/fill:[^;]+;?/g, "").replace(/color:/g, "fill:");
			select_default(w).attr("style", i);
		} else {
			let i = E.replace(/stroke:[^;]+;?/g, "").replace(/stroke-width:[^;]+;?/g, "").replace(/fill:[^;]+;?/g, "").replace(/background:/g, "fill:");
			select_default(w).select("rect").attr("style", i.replace(/background:/g, "fill:"));
			let T = E.replace(/stroke:[^;]+;?/g, "").replace(/stroke-width:[^;]+;?/g, "").replace(/fill:[^;]+;?/g, "").replace(/color:/g, "fill:");
			select_default(w).select("text").attr("style", T);
		}
		return w;
	}
}, "createText");
export { computeDimensionOfText, createText, getIconSVG, registerIconPacks, replaceIconSubstring, unknownIcon };
