/**
 * Sanitize HTML preview output — allows only safe Telegram-compatible tags.
 * Used by notification and command template preview renderers.
 */

const ALLOWED_TAGS = new Set(['B', 'I', 'CODE', 'PRE', 'A', 'BR']);

function walkNodes(parent: Node, target: Node): void {
	for (const node of Array.from(parent.childNodes)) {
		if (node.nodeType === Node.TEXT_NODE) {
			target.appendChild(document.createTextNode(node.textContent || ''));
		} else if (node.nodeType === Node.ELEMENT_NODE) {
			const el = node as Element;
			if (ALLOWED_TAGS.has(el.tagName)) {
				const safe = document.createElement(el.tagName);
				if (el.tagName === 'A') {
					const href = el.getAttribute('href') || '';
					if (/^https?:\/\//i.test(href)) {
						safe.setAttribute('href', href);
						safe.setAttribute('target', '_blank');
						safe.setAttribute('rel', 'noopener noreferrer');
					}
				}
				walkNodes(el, safe);
				target.appendChild(safe);
			} else {
				walkNodes(el, target);
			}
		}
	}
}

export function sanitizePreview(html: string): string {
	const doc = new DOMParser().parseFromString(html, 'text/html');
	const fragment = document.createDocumentFragment();
	walkNodes(doc.body, fragment);
	const wrapper = document.createElement('div');
	wrapper.appendChild(fragment);
	return wrapper.innerHTML;
}
