import { convert } from "../../unist-util-is/lib/index.js";
import { visitParents } from "../../unist-util-visit-parents/lib/index.js";
import escapeStringRegexp from "../node_modules/escape-string-regexp/index.js";
function findAndReplace(n, r, a) {
	let o = convert((a || {}).ignore || []), s = toPairs(r), c = -1;
	for (; ++c < s.length;) visitParents(n, "text", l);
	function l(e, t) {
		let n = -1, r;
		for (; ++n < t.length;) {
			let e = t[n], i = r ? r.children : void 0;
			if (o(e, i ? i.indexOf(e) : void 0, r)) return;
			r = e;
		}
		if (r) return u(e, t);
	}
	function u(e, t) {
		let n = t[t.length - 1], r = s[c][0], i = s[c][1], a = 0, o = n.children.indexOf(e), l = !1, u = [];
		r.lastIndex = 0;
		let d = r.exec(e.value);
		for (; d;) {
			let n = d.index, o = {
				index: d.index,
				input: d.input,
				stack: [...t, e]
			}, s = i(...d, o);
			if (typeof s == "string" && (s = s.length > 0 ? {
				type: "text",
				value: s
			} : void 0), s === !1 ? r.lastIndex = n + 1 : (a !== n && u.push({
				type: "text",
				value: e.value.slice(a, n)
			}), Array.isArray(s) ? u.push(...s) : s && u.push(s), a = n + d[0].length, l = !0), !r.global) break;
			d = r.exec(e.value);
		}
		return l ? (a < e.value.length && u.push({
			type: "text",
			value: e.value.slice(a)
		}), n.children.splice(o, 1, ...u)) : u = [e], o + u.length;
	}
}
function toPairs(e) {
	let t = [];
	if (!Array.isArray(e)) throw TypeError("Expected find and replace tuple or list of tuples");
	let n = !e[0] || Array.isArray(e[0]) ? e : [e], r = -1;
	for (; ++r < n.length;) {
		let e = n[r];
		t.push([toExpression(e[0]), toFunction(e[1])]);
	}
	return t;
}
function toExpression(e) {
	return typeof e == "string" ? new RegExp(escapeStringRegexp(e), "g") : e;
}
function toFunction(e) {
	return typeof e == "function" ? e : function() {
		return e;
	};
}
export { findAndReplace };
