import { normalizeUri } from "../../micromark-util-sanitize-uri/index.js";
import esm_default from "../../@ungap/structured-clone/esm/index.js";
function defaultFootnoteBackContent(e, t) {
	let n = [{
		type: "text",
		value: "↩"
	}];
	return t > 1 && n.push({
		type: "element",
		tagName: "sup",
		properties: {},
		children: [{
			type: "text",
			value: String(t)
		}]
	}), n;
}
function defaultFootnoteBackLabel(e, t) {
	return "Back to reference " + (e + 1) + (t > 1 ? "-" + t : "");
}
function footer(i) {
	let a = typeof i.options.clobberPrefix == "string" ? i.options.clobberPrefix : "user-content-", o = i.options.footnoteBackContent || defaultFootnoteBackContent, s = i.options.footnoteBackLabel || defaultFootnoteBackLabel, c = i.options.footnoteLabel || "Footnotes", l = i.options.footnoteLabelTagName || "h2", u = i.options.footnoteLabelProperties || { className: ["sr-only"] }, d = [], f = -1;
	for (; ++f < i.footnoteOrder.length;) {
		let t = i.footnoteById.get(i.footnoteOrder[f]);
		if (!t) continue;
		let n = i.all(t), r = String(t.identifier).toUpperCase(), c = normalizeUri(r.toLowerCase()), l = 0, u = [], p = i.footnoteCounts.get(r);
		for (; p !== void 0 && ++l <= p;) {
			u.length > 0 && u.push({
				type: "text",
				value: " "
			});
			let e = typeof o == "string" ? o : o(f, l);
			typeof e == "string" && (e = {
				type: "text",
				value: e
			}), u.push({
				type: "element",
				tagName: "a",
				properties: {
					href: "#" + a + "fnref-" + c + (l > 1 ? "-" + l : ""),
					dataFootnoteBackref: "",
					ariaLabel: typeof s == "string" ? s : s(f, l),
					className: ["data-footnote-backref"]
				},
				children: Array.isArray(e) ? e : [e]
			});
		}
		let m = n[n.length - 1];
		if (m && m.type === "element" && m.tagName === "p") {
			let e = m.children[m.children.length - 1];
			e && e.type === "text" ? e.value += " " : m.children.push({
				type: "text",
				value: " "
			}), m.children.push(...u);
		} else n.push(...u);
		let h = {
			type: "element",
			tagName: "li",
			properties: { id: a + "fn-" + c },
			children: i.wrap(n, !0)
		};
		i.patch(t, h), d.push(h);
	}
	if (d.length !== 0) return {
		type: "element",
		tagName: "section",
		properties: {
			dataFootnotes: !0,
			className: ["footnotes"]
		},
		children: [
			{
				type: "element",
				tagName: l,
				properties: {
					...esm_default(u),
					id: "footnote-label"
				},
				children: [{
					type: "text",
					value: c
				}]
			},
			{
				type: "text",
				value: "\n"
			},
			{
				type: "element",
				tagName: "ol",
				properties: {},
				children: i.wrap(d, !0)
			},
			{
				type: "text",
				value: "\n"
			}
		]
	};
}
export { footer };
