/**
 * Helper function to sanitize HTML content by removing potentially dangerous content.
 * @param {string} htmlString - The HTML string to sanitize.
 * @param {Object} [options={}] - Optional configuration options.
 * @returns {string} The sanitized HTML string.
 */
export function sanitizeHtml(htmlString, options = {}) {
	const parser = new DOMParser();
	const doc = parser.parseFromString(htmlString, "text/html");

	options = Object.assign(
		{
			blockedTags: ["script", "iframe", "object", "embed", "link", "meta"],
		},
		options,
	);

	const blockedTags = options.blockedTags || [];

	blockedTags.forEach((tag) => {
		doc.querySelectorAll(tag).forEach((el) => el.remove());
	});

	// remove dangerous attributes
	const dangerousAttr = /^on/i;
	const urlAttrs = ["xlink:href", "action", "formaction"];

	doc.querySelectorAll("*").forEach((el) => {
		// remove dangerous attributes
		[...el.attributes].forEach((attr) => {
			const name = attr.name;
			const value = attr.value;

			// remove attributes that start with "on" (event handlers)
			if (dangerousAttr.test(name)) {
				el.removeAttribute(name);
			}

			// remove URL attributes that start with javascript:, data:, or vbscript:
			if (urlAttrs.includes(name)) {
				const val = value.trim().toLowerCase();
				if (
					val.startsWith("javascript:") ||
					val.startsWith("data:") ||
					val.startsWith("vbscript:")
				) {
					el.removeAttribute(name);
				}
			}
		});
	});

	return doc.body.innerHTML;
}
