import { markdownLineEnding, markdownLineEndingOrSpace, markdownSpace } from "../../micromark-util-character/index.js";
import { splice } from "../../micromark-util-chunked/index.js";
import { factorySpace } from "../../micromark-factory-space/index.js";
const headingAtx = {
	name: "headingAtx",
	resolve: resolveHeadingAtx,
	tokenize: tokenizeHeadingAtx
};
function resolveHeadingAtx(e, t) {
	let n = e.length - 2, i = 3, a, o;
	return e[i][1].type === "whitespace" && (i += 2), n - 2 > i && e[n][1].type === "whitespace" && (n -= 2), e[n][1].type === "atxHeadingSequence" && (i === n - 1 || n - 4 > i && e[n - 2][1].type === "whitespace") && (n -= i + 1 === n ? 2 : 4), n > i && (a = {
		type: "atxHeadingText",
		start: e[i][1].start,
		end: e[n][1].end
	}, o = {
		type: "chunkText",
		start: e[i][1].start,
		end: e[n][1].end,
		contentType: "text"
	}, splice(e, i, n - i + 1, [
		[
			"enter",
			a,
			t
		],
		[
			"enter",
			o,
			t
		],
		[
			"exit",
			o,
			t
		],
		[
			"exit",
			a,
			t
		]
	])), e;
}
function tokenizeHeadingAtx(r, a, o) {
	let s = 0;
	return c;
	function c(e) {
		return r.enter("atxHeading"), l(e);
	}
	function l(e) {
		return r.enter("atxHeadingSequence"), u(e);
	}
	function u(e) {
		return e === 35 && s++ < 6 ? (r.consume(e), u) : e === null || markdownLineEndingOrSpace(e) ? (r.exit("atxHeadingSequence"), d(e)) : o(e);
	}
	function d(t) {
		return t === 35 ? (r.enter("atxHeadingSequence"), f(t)) : t === null || markdownLineEnding(t) ? (r.exit("atxHeading"), a(t)) : markdownSpace(t) ? factorySpace(r, d, "whitespace")(t) : (r.enter("atxHeadingText"), p(t));
	}
	function f(e) {
		return e === 35 ? (r.consume(e), f) : (r.exit("atxHeadingSequence"), d(e));
	}
	function p(e) {
		return e === null || e === 35 || markdownLineEndingOrSpace(e) ? (r.exit("atxHeadingText"), d(e)) : (r.consume(e), p);
	}
}
export { headingAtx };
