/**
 * 轻量 Markdown → HTML（供微信小程序 rich-text 使用）
 * 覆盖聊天场景常用语法：粗体、斜体、行内代码、链接、标题、列表、换行
 */

function escapeHtml(text) {
	return String(text || '')
		.replace(/&/g, '&amp;')
		.replace(/</g, '&lt;')
		.replace(/>/g, '&gt;')
		.replace(/"/g, '&quot;')
}

function formatInline(text) {
	let s = escapeHtml(text)
	// 链接 [text](url)
	s = s.replace(/\[([^\]]+)\]\((https?:\/\/[^)\s]+)\)/g,
		'<a href="$2" style="color:#7C3AED;text-decoration:underline;">$1</a>')
	// 粗体 ** / __
	s = s.replace(/\*\*(.+?)\*\*/g, '<strong style="font-weight:700;">$1</strong>')
	s = s.replace(/__(.+?)__/g, '<strong style="font-weight:700;">$1</strong>')
	// 行内代码 `
	s = s.replace(/`([^`\n]+)`/g,
		'<code style="font-family:Menlo,Consolas,monospace;font-size:0.92em;padding:0 6px;border-radius:6px;background:#F1F5F9;color:#334155;">$1</code>')
	// 斜体 *text*（避免吃掉已转换的 **）
	s = s.replace(/(^|[^*])\*([^*\n]+)\*(?!\*)/g, '$1<em style="font-style:italic;">$2</em>')
	s = s.replace(/(^|[^_])_([^_\n]+)_(?!_)/g, '$1<em style="font-style:italic;">$2</em>')
	return s
}

/**
 * @param {string} markdown
 * @returns {string} HTML string for rich-text :nodes
 */
export function markdownToHtml(markdown) {
	const raw = String(markdown || '')
	if (!raw) return ''

	const lines = raw.replace(/\r\n/g, '\n').split('\n')
	const html = []
	let inUl = false
	let inOl = false
	let inCode = false
	let codeBuf = []

	const closeLists = () => {
		if (inUl) {
			html.push('</ul>')
			inUl = false
		}
		if (inOl) {
			html.push('</ol>')
			inOl = false
		}
	}

	for (let i = 0; i < lines.length; i++) {
		const line = lines[i]

		if (line.trim().startsWith('```')) {
			if (inCode) {
				html.push(
					'<pre style="margin:8px 0;padding:12px;border-radius:8px;background:#F1F5F9;color:#334155;font-size:12px;white-space:pre-wrap;word-break:break-all;">'
					+ escapeHtml(codeBuf.join('\n'))
					+ '</pre>'
				)
				codeBuf = []
				inCode = false
			} else {
				closeLists()
				inCode = true
			}
			continue
		}

		if (inCode) {
			codeBuf.push(line)
			continue
		}

		const heading = line.match(/^(#{1,3})\s+(.+)$/)
		if (heading) {
			closeLists()
			const level = heading[1].length
			const size = level === 1 ? '17px' : (level === 2 ? '16px' : '15px')
			html.push(
				`<div style="margin:8px 0 4px;font-size:${size};font-weight:700;line-height:1.5;">${formatInline(heading[2])}</div>`
			)
			continue
		}

		const ul = line.match(/^[-*+]\s+(.+)$/)
		if (ul) {
			if (inOl) {
				html.push('</ol>')
				inOl = false
			}
			if (!inUl) {
				html.push('<ul style="margin:6px 0;padding-left:1.2em;">')
				inUl = true
			}
			html.push(`<li style="margin:2px 0;line-height:1.6;">${formatInline(ul[1])}</li>`)
			continue
		}

		const ol = line.match(/^\d+\.\s+(.+)$/)
		if (ol) {
			if (inUl) {
				html.push('</ul>')
				inUl = false
			}
			if (!inOl) {
				html.push('<ol style="margin:6px 0;padding-left:1.2em;">')
				inOl = true
			}
			html.push(`<li style="margin:2px 0;line-height:1.6;">${formatInline(ol[1])}</li>`)
			continue
		}

		closeLists()

		if (!line.trim()) {
			html.push('<div style="height:8px;"></div>')
			continue
		}

		html.push(`<div style="margin:0;line-height:1.65;">${formatInline(line)}</div>`)
	}

	if (inCode) {
		html.push(
			'<pre style="margin:8px 0;padding:12px;border-radius:8px;background:#F1F5F9;color:#334155;font-size:12px;white-space:pre-wrap;word-break:break-all;">'
			+ escapeHtml(codeBuf.join('\n'))
			+ '</pre>'
		)
	}
	closeLists()

	return (
		'<div style="font-size:14px;line-height:1.65;color:#0F172A;word-break:break-word;">'
		+ html.join('')
		+ '</div>'
	)
}
