import { __name, log } from "./chunk-AGHRB4JF.js";
import { assignWithDepth_default, common_default, detectType, directiveRegex, sanitizeDirective } from "./chunk-ABZYJK2D.js";
import select_default from "../../../../d3-selection/src/select.js";
import linear_default from "../../../../d3-shape/src/curve/linear.js";
import { bumpX, bumpY } from "../../../../d3-shape/src/curve/bump.js";
import basis_default from "../../../../d3-shape/src/curve/basis.js";
import basisClosed_default from "../../../../d3-shape/src/curve/basisClosed.js";
import basisOpen_default from "../../../../d3-shape/src/curve/basisOpen.js";
import bundle_default from "../../../../d3-shape/src/curve/bundle.js";
import cardinal_default from "../../../../d3-shape/src/curve/cardinal.js";
import cardinalClosed_default from "../../../../d3-shape/src/curve/cardinalClosed.js";
import cardinalOpen_default from "../../../../d3-shape/src/curve/cardinalOpen.js";
import catmullRom_default from "../../../../d3-shape/src/curve/catmullRom.js";
import catmullRomClosed_default from "../../../../d3-shape/src/curve/catmullRomClosed.js";
import catmullRomOpen_default from "../../../../d3-shape/src/curve/catmullRomOpen.js";
import linearClosed_default from "../../../../d3-shape/src/curve/linearClosed.js";
import { monotoneX, monotoneY } from "../../../../d3-shape/src/curve/monotone.js";
import natural_default from "../../../../d3-shape/src/curve/natural.js";
import step_default, { stepAfter, stepBefore } from "../../../../d3-shape/src/curve/step.js";
import "../../../../d3/src/index.js";
import { require_dist } from "../../../../@braintree/sanitize-url/dist/index.js";
import memoize_default from "../../../../lodash-es/memoize.js";
import merge_default from "../../../../lodash-es/merge.js";
var import_dist = require_dist(), ZERO_WIDTH_SPACE = "​", d3CurveTypes = {
	curveBasis: basis_default,
	curveBasisClosed: basisClosed_default,
	curveBasisOpen: basisOpen_default,
	curveBumpX: bumpX,
	curveBumpY: bumpY,
	curveBundle: bundle_default,
	curveCardinalClosed: cardinalClosed_default,
	curveCardinalOpen: cardinalOpen_default,
	curveCardinal: cardinal_default,
	curveCatmullRomClosed: catmullRomClosed_default,
	curveCatmullRomOpen: catmullRomOpen_default,
	curveCatmullRom: catmullRom_default,
	curveLinear: linear_default,
	curveLinearClosed: linearClosed_default,
	curveMonotoneX: monotoneX,
	curveMonotoneY: monotoneY,
	curveNatural: natural_default,
	curveStep: step_default,
	curveStepAfter: stepAfter,
	curveStepBefore: stepBefore
}, directiveWithoutOpen = /\s*(?:(\w+)(?=:):|(\w+))\s*(?:(\w+)|((?:(?!}%{2}).|\r?\n)*))?\s*(?:}%{2})?/gi, detectInit = /* @__PURE__ */ __name(function(p, H) {
	let W = detectDirective(p, /(?:init\b)|(?:initialize\b)/), K = {};
	if (Array.isArray(W)) {
		let p = W.map((p) => p.args);
		sanitizeDirective(p), K = assignWithDepth_default(K, [...p]);
	} else K = W.args;
	if (!K) return;
	let J = detectType(p, H), Y = "config";
	return K[Y] !== void 0 && (J === "flowchart-v2" && (J = "flowchart"), K[J] = K[Y], delete K[Y]), K;
}, "detectInit"), detectDirective = /* @__PURE__ */ __name(function(p, U = null) {
	try {
		let W = RegExp(`[%]{2}(?![{]${directiveWithoutOpen.source})(?=[}][%]{2}).*
`, "ig");
		p = p.trim().replace(W, "").replace(/'/gm, "\""), log.debug(`Detecting diagram directive${U === null ? "" : " type:" + U} based on the text:${p}`);
		let G, q = [];
		for (; (G = directiveRegex.exec(p)) !== null;) if (G.index === directiveRegex.lastIndex && directiveRegex.lastIndex++, G && !U || U && G[1]?.match(U) || U && G[2]?.match(U)) {
			let p = G[1] ? G[1] : G[2], H = G[3] ? G[3].trim() : G[4] ? JSON.parse(G[4].trim()) : null;
			q.push({
				type: p,
				args: H
			});
		}
		return q.length === 0 ? {
			type: p,
			args: null
		} : q.length === 1 ? q[0] : q;
	} catch (W) {
		return log.error(`ERROR: ${W.message} - Unable to parse directive type: '${U}' based on the text: '${p}'`), {
			type: void 0,
			args: null
		};
	}
}, "detectDirective"), removeDirectives = /* @__PURE__ */ __name(function(p) {
	return p.replace(directiveRegex, "");
}, "removeDirectives"), isSubstringInArray = /* @__PURE__ */ __name(function(p, H) {
	for (let [U, W] of H.entries()) if (W.match(p)) return U;
	return -1;
}, "isSubstringInArray");
function interpolateToCurve(p, H) {
	return p ? d3CurveTypes[`curve${p.charAt(0).toUpperCase() + p.slice(1)}`] ?? H : H;
}
__name(interpolateToCurve, "interpolateToCurve");
function formatUrl(p, H) {
	let U = p.trim();
	if (U) return H.securityLevel === "loose" ? U : (0, import_dist.sanitizeUrl)(U);
}
__name(formatUrl, "formatUrl");
var runFunc = /* @__PURE__ */ __name((p, ...U) => {
	let W = p.split("."), G = W.length - 1, K = W[G], q = window;
	for (let U = 0; U < G; U++) if (q = q[W[U]], !q) {
		log.error(`Function name: ${p} not found in window`);
		return;
	}
	q[K](...U);
}, "runFunc");
function distance(p, H) {
	return !p || !H ? 0 : Math.sqrt((H.x - p.x) ** 2 + (H.y - p.y) ** 2);
}
__name(distance, "distance");
function traverseEdge(p) {
	let H, U = 0;
	return p.forEach((p) => {
		U += distance(p, H), H = p;
	}), calculatePoint(p, U / 2);
}
__name(traverseEdge, "traverseEdge");
function calcLabelPosition(p) {
	return p.length === 1 ? p[0] : traverseEdge(p);
}
__name(calcLabelPosition, "calcLabelPosition");
var roundNumber = /* @__PURE__ */ __name((p, H = 2) => {
	let U = 10 ** H;
	return Math.round(p * U) / U;
}, "roundNumber"), calculatePoint = /* @__PURE__ */ __name((p, H) => {
	let U, W = H;
	for (let H of p) {
		if (U) {
			let p = distance(H, U);
			if (p === 0) return U;
			if (p < W) W -= p;
			else {
				let G = W / p;
				if (G <= 0) return U;
				if (G >= 1) return {
					x: H.x,
					y: H.y
				};
				if (G > 0 && G < 1) return {
					x: roundNumber((1 - G) * U.x + G * H.x, 5),
					y: roundNumber((1 - G) * U.y + G * H.y, 5)
				};
			}
		}
		U = H;
	}
	throw Error("Could not find a suitable point for the given distance");
}, "calculatePoint"), calcCardinalityPosition = /* @__PURE__ */ __name((p, U, W) => {
	log.info(`our points ${JSON.stringify(U)}`), U[0] !== W && (U = U.reverse());
	let G = calculatePoint(U, 25), K = p ? 10 : 5, q = Math.atan2(U[0].y - G.y, U[0].x - G.x), J = {
		x: 0,
		y: 0
	};
	return J.x = Math.sin(q) * K + (U[0].x + G.x) / 2, J.y = -Math.cos(q) * K + (U[0].y + G.y) / 2, J;
}, "calcCardinalityPosition");
function calcTerminalLabelPosition(p, U, W) {
	let G = structuredClone(W);
	log.info("our points", G), U !== "start_left" && U !== "start_right" && G.reverse();
	let K = calculatePoint(G, 25 + p), q = 10 + p * .5, J = Math.atan2(G[0].y - K.y, G[0].x - K.x), Y = {
		x: 0,
		y: 0
	};
	return U === "start_left" ? (Y.x = Math.sin(J + Math.PI) * q + (G[0].x + K.x) / 2, Y.y = -Math.cos(J + Math.PI) * q + (G[0].y + K.y) / 2) : U === "end_right" ? (Y.x = Math.sin(J - Math.PI) * q + (G[0].x + K.x) / 2 - 5, Y.y = -Math.cos(J - Math.PI) * q + (G[0].y + K.y) / 2 - 5) : U === "end_left" ? (Y.x = Math.sin(J) * q + (G[0].x + K.x) / 2 - 5, Y.y = -Math.cos(J) * q + (G[0].y + K.y) / 2 - 5) : (Y.x = Math.sin(J) * q + (G[0].x + K.x) / 2, Y.y = -Math.cos(J) * q + (G[0].y + K.y) / 2), Y;
}
__name(calcTerminalLabelPosition, "calcTerminalLabelPosition");
function getStylesFromArray(p) {
	let H = "", U = "";
	for (let W of p) W !== void 0 && (W.startsWith("color:") || W.startsWith("text-align:") ? U = U + W + ";" : H = H + W + ";");
	return {
		style: H,
		labelStyle: U
	};
}
__name(getStylesFromArray, "getStylesFromArray");
var cnt = 0, generateId = /* @__PURE__ */ __name(() => (cnt++, "id-" + Math.random().toString(36).substr(2, 12) + "-" + cnt), "generateId");
function makeRandomHex(p) {
	let H = "";
	for (let U = 0; U < p; U++) H += "0123456789abcdef".charAt(Math.floor(Math.random() * 16));
	return H;
}
__name(makeRandomHex, "makeRandomHex");
var random = /* @__PURE__ */ __name((p) => makeRandomHex(p.length), "random"), getTextObj = /* @__PURE__ */ __name(function() {
	return {
		x: 0,
		y: 0,
		fill: void 0,
		anchor: "start",
		style: "#666",
		width: 100,
		height: 100,
		textMargin: 0,
		rx: 0,
		ry: 0,
		valign: void 0,
		text: ""
	};
}, "getTextObj"), drawSimpleText = /* @__PURE__ */ __name(function(p, H) {
	let U = H.text.replace(common_default.lineBreakRegex, " "), [, G] = parseFontSize(H.fontSize), K = p.append("text");
	K.attr("x", H.x), K.attr("y", H.y), K.style("text-anchor", H.anchor), K.style("font-family", H.fontFamily), K.style("font-size", G), K.style("font-weight", H.fontWeight), K.attr("fill", H.fill), H.class !== void 0 && K.attr("class", H.class);
	let q = K.append("tspan");
	return q.attr("x", H.x + H.textMargin * 2), q.attr("fill", H.fill), q.text(U), K;
}, "drawSimpleText"), wrapLabel = memoize_default((p, H, U) => {
	if (!p || (U = Object.assign({
		fontSize: 12,
		fontWeight: 400,
		fontFamily: "Arial",
		joinWith: "<br/>"
	}, U), common_default.lineBreakRegex.test(p))) return p;
	let G = p.split(" ").filter(Boolean), K = [], q = "";
	return G.forEach((p, W) => {
		let J = calculateTextWidth(`${p} `, U), Y = calculateTextWidth(q, U);
		if (J > H) {
			let { hyphenatedStrings: W, remainingWord: G } = breakString(p, H, "-", U);
			K.push(q, ...W), q = G;
		} else Y + J >= H ? (K.push(q), q = p) : q = [q, p].filter(Boolean).join(" ");
		W + 1 === G.length && K.push(q);
	}), K.filter((p) => p !== "").join(U.joinWith);
}, (p, H, U) => `${p}${H}${U.fontSize}${U.fontWeight}${U.fontFamily}${U.joinWith}`), breakString = memoize_default((p, H, U = "-", W) => {
	W = Object.assign({
		fontSize: 12,
		fontWeight: 400,
		fontFamily: "Arial",
		margin: 0
	}, W);
	let G = [...p], K = [], q = "";
	return G.forEach((p, J) => {
		let Y = `${q}${p}`;
		if (calculateTextWidth(Y, W) >= H) {
			let p = J + 1, H = G.length === p, W = `${Y}${U}`;
			K.push(H ? Y : W), q = "";
		} else q = Y;
	}), {
		hyphenatedStrings: K,
		remainingWord: q
	};
}, (p, H, U = "-", W) => `${p}${H}${U}${W.fontSize}${W.fontWeight}${W.fontFamily}`);
function calculateTextHeight(p, H) {
	return calculateTextDimensions(p, H).height;
}
__name(calculateTextHeight, "calculateTextHeight");
function calculateTextWidth(p, H) {
	return calculateTextDimensions(p, H).width;
}
__name(calculateTextWidth, "calculateTextWidth");
var calculateTextDimensions = memoize_default((p, H) => {
	let { fontSize: U = 12, fontFamily: G = "Arial", fontWeight: K = 400 } = H;
	if (!p) return {
		width: 0,
		height: 0
	};
	let [, q] = parseFontSize(U), Y = ["sans-serif", G], X = p.split(common_default.lineBreakRegex), Z = [], Q = select_default("body");
	if (!Q.remove) return {
		width: 0,
		height: 0,
		lineHeight: 0
	};
	let $ = Q.append("svg");
	for (let p of Y) {
		let H = 0, U = {
			width: 0,
			height: 0,
			lineHeight: 0
		};
		for (let W of X) {
			let G = getTextObj();
			G.text = W || "​";
			let J = drawSimpleText($, G).style("font-size", q).style("font-weight", K).style("font-family", p), Y = (J._groups || J)[0][0].getBBox();
			if (Y.width === 0 && Y.height === 0) throw Error("svg element not in render tree");
			U.width = Math.round(Math.max(U.width, Y.width)), H = Math.round(Y.height), U.height += H, U.lineHeight = Math.round(Math.max(U.lineHeight, H));
		}
		Z.push(U);
	}
	return $.remove(), Z[isNaN(Z[1].height) || isNaN(Z[1].width) || isNaN(Z[1].lineHeight) || Z[0].height > Z[1].height && Z[0].width > Z[1].width && Z[0].lineHeight > Z[1].lineHeight ? 0 : 1];
}, (p, H) => `${p}${H.fontSize}${H.fontWeight}${H.fontFamily}`), InitIDGenerator = class {
	constructor(p = !1, H) {
		this.count = 0, this.count = H ? H.length : 0, this.next = p ? () => this.count++ : () => Date.now();
	}
	static #e = __name(this, "InitIDGenerator");
}, decoder, entityDecode = /* @__PURE__ */ __name(function(p) {
	return decoder ||= document.createElement("div"), p = escape(p).replace(/%26/g, "&").replace(/%23/g, "#").replace(/%3B/g, ";"), decoder.innerHTML = p, unescape(decoder.textContent);
}, "entityDecode");
function isDetailedError(p) {
	return "str" in p;
}
__name(isDetailedError, "isDetailedError");
var insertTitle = /* @__PURE__ */ __name((p, H, U, W) => {
	if (!W) return;
	let G = p.node()?.getBBox();
	G && p.append("text").text(W).attr("text-anchor", "middle").attr("x", G.x + G.width / 2).attr("y", -U).attr("class", H);
}, "insertTitle"), parseFontSize = /* @__PURE__ */ __name((p) => {
	if (typeof p == "number") return [p, p + "px"];
	let H = parseInt(p ?? "", 10);
	return Number.isNaN(H) ? [void 0, void 0] : p === String(H) ? [H, p + "px"] : [H, p];
}, "parseFontSize");
function cleanAndMerge(p, H) {
	return merge_default({}, p, H);
}
__name(cleanAndMerge, "cleanAndMerge");
var utils_default = {
	assignWithDepth: assignWithDepth_default,
	wrapLabel,
	calculateTextHeight,
	calculateTextWidth,
	calculateTextDimensions,
	cleanAndMerge,
	detectInit,
	detectDirective,
	isSubstringInArray,
	interpolateToCurve,
	calcLabelPosition,
	calcCardinalityPosition,
	calcTerminalLabelPosition,
	formatUrl,
	getStylesFromArray,
	generateId,
	random,
	runFunc,
	entityDecode,
	insertTitle,
	isLabelCoordinateInPath,
	parseFontSize,
	InitIDGenerator
}, encodeEntities = /* @__PURE__ */ __name(function(p) {
	let H = p;
	return H = H.replace(/style.*:\S*#.*;/g, function(p) {
		return p.substring(0, p.length - 1);
	}), H = H.replace(/classDef.*:\S*#.*;/g, function(p) {
		return p.substring(0, p.length - 1);
	}), H = H.replace(/#\w+;/g, function(p) {
		let H = p.substring(1, p.length - 1);
		return /^\+?\d+$/.test(H) ? "ﬂ°°" + H + "¶ß" : "ﬂ°" + H + "¶ß";
	}), H;
}, "encodeEntities"), decodeEntities = /* @__PURE__ */ __name(function(p) {
	return p.replace(/ﬂ°°/g, "&#").replace(/ﬂ°/g, "&").replace(/¶ß/g, ";");
}, "decodeEntities"), getEdgeId = /* @__PURE__ */ __name((p, H, { counter: U = 0, prefix: W, suffix: G }, K) => K || `${W ? `${W}_` : ""}${p}_${H}_${U}${G ? `_${G}` : ""}`, "getEdgeId");
function handleUndefinedAttr(p) {
	return p ?? null;
}
__name(handleUndefinedAttr, "handleUndefinedAttr");
function isLabelCoordinateInPath(p, H) {
	let U = Math.round(p.x), W = Math.round(p.y), G = H.replace(/(\d+\.\d+)/g, (p) => Math.round(parseFloat(p)).toString());
	return G.includes(U.toString()) || G.includes(W.toString());
}
__name(isLabelCoordinateInPath, "isLabelCoordinateInPath");
export { ZERO_WIDTH_SPACE, calculateTextHeight, calculateTextWidth, cleanAndMerge, decodeEntities, encodeEntities, generateId, getEdgeId, getStylesFromArray, handleUndefinedAttr, interpolateToCurve, isDetailedError, parseFontSize, random, removeDirectives, utils_default, wrapLabel };
