import { normalize } from "../../property-information/lib/normalize.js";
import { find } from "../../property-information/lib/find.js";
import { parse } from "../../comma-separated-tokens/index.js";
import { parseSelector } from "../../hast-util-parse-selector/lib/index.js";
import { parse as parse$1 } from "../../space-separated-tokens/index.js";
function createH(e, t, n) {
	let i = n ? createAdjustMap(n) : void 0;
	function a(n, a, ...l) {
		let u;
		if (n == null) {
			u = {
				type: "root",
				children: []
			};
			let e = a;
			l.unshift(e);
		} else {
			u = parseSelector(n, t);
			let c = u.tagName.toLowerCase(), d = i ? i.get(c) : void 0;
			if (u.tagName = d || c, isChild(a)) l.unshift(a);
			else for (let [t, n] of Object.entries(a)) addProperty(e, u.properties, t, n);
		}
		for (let e of l) addChild(u.children, e);
		return u.type === "element" && u.tagName === "template" && (u.content = {
			type: "root",
			children: u.children
		}, u.children = []), u;
	}
	return a;
}
function isChild(e) {
	if (typeof e != "object" || !e || Array.isArray(e)) return !0;
	if (typeof e.type != "string") return !1;
	let t = e, n = Object.keys(e);
	for (let e of n) {
		let n = t[e];
		if (n && typeof n == "object") {
			if (!Array.isArray(n)) return !0;
			let e = n;
			for (let t of e) if (typeof t != "number" && typeof t != "string") return !0;
		}
	}
	return !!("children" in e && Array.isArray(e.children));
}
function addProperty(e, r, a, o) {
	let s = find(e, a), c;
	if (o != null) {
		if (typeof o == "number") {
			if (Number.isNaN(o)) return;
			c = o;
		} else c = typeof o == "boolean" ? o : typeof o == "string" ? s.spaceSeparated ? parse$1(o) : s.commaSeparated ? parse(o) : s.commaOrSpaceSeparated ? parse$1(parse(o).join(" ")) : parsePrimitive(s, s.property, o) : Array.isArray(o) ? [...o] : s.property === "style" ? style(o) : String(o);
		if (Array.isArray(c)) {
			let e = [];
			for (let t of c) e.push(parsePrimitive(s, s.property, t));
			c = e;
		}
		s.property === "className" && Array.isArray(r.className) && (c = r.className.concat(c)), r[s.property] = c;
	}
}
function addChild(e, t) {
	if (t != null) if (typeof t == "number" || typeof t == "string") e.push({
		type: "text",
		value: String(t)
	});
	else if (Array.isArray(t)) for (let n of t) addChild(e, n);
	else if (typeof t == "object" && "type" in t) t.type === "root" ? addChild(e, t.children) : e.push(t);
	else throw Error("Expected node, nodes, or string, got `" + t + "`");
}
function parsePrimitive(t, n, r) {
	if (typeof r == "string") {
		if (t.number && r && !Number.isNaN(Number(r))) return Number(r);
		if ((t.boolean || t.overloadedBoolean) && (r === "" || normalize(r) === normalize(n))) return !0;
	}
	return r;
}
function style(e) {
	let t = [];
	for (let [n, r] of Object.entries(e)) t.push([n, r].join(": "));
	return t.join("; ");
}
function createAdjustMap(e) {
	let t = /* @__PURE__ */ new Map();
	for (let n of e) t.set(n.toLowerCase(), n);
	return t;
}
export { createH };
