/**
 * @license Copyright (c) 2017-2025, CKSource Holding sp. z o.o. All rights reserved.
 * For licensing, see LICENSE.md.
 */

/**
 * Sanitizes text to prevent XSS attacks by removing potentially dangerous characters.
 *
 * @param text - The text to sanitize
 * @returns Sanitized text safe for DOM operations
 */
export function sanitizeText( text ) {
	if ( typeof text !== 'string' ) {
		return '';
	}

	// Create a temporary element to escape HTML entities
	const temp = document.createElement( 'div' );
	temp.textContent = text;

	// Get the escaped text and remove any remaining script tags or event handlers
	return temp.innerHTML
		.replace( /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, '' )
		.replace( /on\w+\s*=\s*"[^"]*"/gi, '' )
		.replace( /on\w+\s*=\s*'[^']*'/gi, '' )
		.replace( /javascript:/gi, '' );
}
