import { fromHtmlIsomorphic } from "../../hast-util-from-html-isomorphic/lib/browser.js";
import { toText } from "../../hast-util-to-text/lib/index.js";
import katex from "../../katex/dist/katex.js";
import { SKIP, visitParents } from "../../unist-util-visit-parents/lib/index.js";
var emptyOptions = {}, emptyClasses = [];
function rehypeKatex(s) {
	let c = s || emptyOptions;
	return function(o, s) {
		visitParents(o, "element", function(a, o) {
			let l = Array.isArray(a.properties.className) ? a.properties.className : emptyClasses, u = l.includes("language-math"), d = l.includes("math-display"), f = l.includes("math-inline"), p = d;
			if (!u && !d && !f) return;
			let m = o[o.length - 1], h = a;
			/* c8 ignore next -- verbose to test. */
			if (a.tagName === "code" && u && m && m.type === "element" && m.tagName === "pre" && (h = m, m = o[o.length - 2], p = !0), !m) return;
			let g = toText(h, { whitespace: "pre" }), _;
			try {
				_ = katex.renderToString(g, {
					...c,
					displayMode: p,
					throwOnError: !0
				});
			} catch (e) {
				let r = e, i = r.name.toLowerCase();
				s.message("Could not render math with KaTeX", {
					ancestors: [...o, a],
					cause: r,
					place: a.position,
					ruleId: i,
					source: "rehype-katex"
				});
				try {
					_ = katex.renderToString(g, {
						...c,
						displayMode: p,
						strict: "ignore",
						throwOnError: !1
					});
				} catch {
					_ = [{
						type: "element",
						tagName: "span",
						properties: {
							className: ["katex-error"],
							style: "color:" + (c.errorColor || "#cc0000"),
							title: String(e)
						},
						children: [{
							type: "text",
							value: g
						}]
					}];
				}
			}
			typeof _ == "string" && (_ = fromHtmlIsomorphic(_, { fragment: !0 }).children);
			let v = m.children.indexOf(h);
			return m.children.splice(v, 1, ..._), SKIP;
		});
	};
}
export { rehypeKatex as default };
