import he from 'he'

/**
 * Decodes HTML entities (named and numeric) in a string.
 * - Tolerates missing semicolons like `&quot`
 * - Leaves unknown entities untouched
 * - Repeats up to 3 times to handle nested encodings like `&amp;quot;`
 */
export function decodeHtmlEntities(text: string): string {
	if (!text) return text

	const entityRe = /&(#x[0-9a-fA-F]+|#[0-9]+|[a-zA-Z]+);?/g

	let out = text
	for (let i = 0; i < 3; i++) {
		const next = out.replace(entityRe, (match: string) => {
			const candidate = match.endsWith(';') ? match : `${match};`
			const decoded = he.decode(candidate)
			return decoded === candidate ? match : decoded
		})
		if (next === out) break
		out = next
	}
	return out
}
