/**
 * Answyr — tiny, safe Markdown renderer.
 *
 * Renders the small subset the AI actually produces (bold, italic, inline code,
 * links, bullet/numbered lists, headings, paragraphs). HTML is escaped FIRST,
 * then only safe tags are reintroduced and links are restricted to http(s), so
 * this is XSS-safe for untrusted text. Exposed as window.AnswyrMD.
 */
(() => {
	function escapeHtml(s) {
		return s
			.replace(/&/g, '&amp;')
			.replace(/</g, '&lt;')
			.replace(/>/g, '&gt;')
			.replace(/"/g, '&quot;');
	}

	function inline(s) {
		// s is already HTML-escaped. Links first so their text isn't mangled.
		var out = s.replace(
			/\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)/g,
			'<a href="$2" target="_blank" rel="noopener">$1</a>',
		);
		out = out.replace(
			/(^|[\s(])(https?:\/\/[^\s<]+)/g,
			'$1<a href="$2" target="_blank" rel="noopener">$2</a>',
		);
		out = out.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>');
		out = out.replace(/(^|[^*])\*([^*\n]+)\*/g, '$1<em>$2</em>');
		out = out.replace(/`([^`]+)`/g, '<code>$1</code>');
		return out;
	}

	function render(text) {
		if (text == null) {
			return '';
		}
		var lines = escapeHtml(String(text)).split(/\r?\n/);
		var html = '';
		var listType = null;
		var para = [];

		function flushPara() {
			if (para.length) {
				html += `<p>${inline(para.join(' '))}</p>`;
				para = [];
			}
		}
		function flushList() {
			if (listType) {
				html += `</${listType}>`;
				listType = null;
			}
		}

		for (let i = 0; i < lines.length; i++) {
			const trimmed = lines[i].trim();
			if (trimmed === '') {
				flushPara();
				flushList();
				continue;
			}
			const heading = trimmed.match(/^#{1,6}\s+(.*)/);
			const bullet = trimmed.match(/^[-*]\s+(.*)/);
			const numbered = trimmed.match(/^\d+\.\s+(.*)/);

			if (heading) {
				flushPara();
				flushList();
				html += `<strong>${inline(heading[1])}</strong>`;
			} else if (bullet) {
				flushPara();
				if (listType !== 'ul') {
					flushList();
					html += '<ul>';
					listType = 'ul';
				}
				html += `<li>${inline(bullet[1])}</li>`;
			} else if (numbered) {
				flushPara();
				if (listType !== 'ol') {
					flushList();
					html += '<ol>';
					listType = 'ol';
				}
				html += `<li>${inline(numbered[1])}</li>`;
			} else {
				flushList();
				para.push(trimmed);
			}
		}
		flushPara();
		flushList();
		return html;
	}

	window.AnswyrMD = { render: render };
})();
