import { splice } from "../micromark-util-chunked/index.js";
import { SpliceBuffer } from "./lib/splice-buffer.js";
function subtokenize(n) {
	let i = {}, a = -1, o, s, c, l, u, d, f, p = new SpliceBuffer(n);
	for (; ++a < p.length;) {
		for (; a in i;) a = i[a];
		if (o = p.get(a), a && o[1].type === "chunkFlow" && p.get(a - 1)[1].type === "listItemPrefix" && (d = o[1]._tokenizer.events, c = 0, c < d.length && d[c][1].type === "lineEndingBlank" && (c += 2), c < d.length && d[c][1].type === "content")) for (; ++c < d.length && d[c][1].type !== "content";) d[c][1].type === "chunkText" && (d[c][1]._isInFirstContentOfListItem = !0, c++);
		if (o[0] === "enter") o[1].contentType && (Object.assign(i, subcontent(p, a)), a = i[a], f = !0);
		else if (o[1]._container) {
			for (c = a, s = void 0; c--;) if (l = p.get(c), l[1].type === "lineEnding" || l[1].type === "lineEndingBlank") l[0] === "enter" && (s && (p.get(s)[1].type = "lineEndingBlank"), l[1].type = "lineEnding", s = c);
			else if (!(l[1].type === "linePrefix" || l[1].type === "listItemIndent")) break;
			s && (o[1].end = { ...p.get(s)[1].start }, u = p.slice(s, a), u.unshift(o), p.splice(s, a - s + 1, u));
		}
	}
	return splice(n, 0, Infinity, p.slice(0)), !f;
}
function subcontent(e, t) {
	let n = e.get(t)[1], r = e.get(t)[2], i = t - 1, a = [], o = n._tokenizer;
	o || (o = r.parser[n.contentType](n.start), n._contentTypeTextTrailing && (o._contentTypeTextTrailing = !0));
	let s = o.events, c = [], l = {}, u, d, f = -1, p = n, m = 0, h = 0, g = [h];
	for (; p;) {
		for (; e.get(++i)[1] !== p;);
		a.push(i), p._tokenizer || (u = r.sliceStream(p), p.next || u.push(null), d && o.defineSkip(p.start), p._isInFirstContentOfListItem && (o._gfmTasklistFirstContentOfListItem = !0), o.write(u), p._isInFirstContentOfListItem && (o._gfmTasklistFirstContentOfListItem = void 0)), d = p, p = p.next;
	}
	for (p = n; ++f < s.length;) s[f][0] === "exit" && s[f - 1][0] === "enter" && s[f][1].type === s[f - 1][1].type && s[f][1].start.line !== s[f][1].end.line && (h = f + 1, g.push(h), p._tokenizer = void 0, p.previous = void 0, p = p.next);
	for (o.events = [], p ? (p._tokenizer = void 0, p.previous = void 0) : g.pop(), f = g.length; f--;) {
		let t = s.slice(g[f], g[f + 1]), n = a.pop();
		c.push([n, n + t.length - 1]), e.splice(n, 2, t);
	}
	for (c.reverse(), f = -1; ++f < c.length;) l[m + c[f][0]] = m + c[f][1], m += c[f][1] - c[f][0] - 1;
	return l;
}
export { subtokenize };
