import { marked } from 'marked';

function slugify(text: string): string {
	return text
		.toLowerCase()
		.replace(/<[^>]+>/g, '')
		.replace(/[^\w\s-]/g, '')
		.trim()
		.replace(/\s+/g, '-');
}

marked.use({
	renderer: {
		heading({ tokens, depth }) {
			const text = this.parser.parseInline(tokens);
			const plain = text.replace(/<[^>]+>/g, '');
			const id = slugify(plain);
			return `<h${depth} id="${id}" class="doc-h${depth}">${text}</h${depth}>`;
		},
		table(token) {
			const header = token.header
				.map((cell) => `<th>${this.parser.parseInline(cell.tokens)}</th>`)
				.join('');
			const body = token.rows
				.map(
					(row) =>
						`<tr>${row.map((cell) => `<td>${this.parser.parseInline(cell.tokens)}</td>`).join('')}</tr>`
				)
				.join('');
			return `<div class="doc-table-wrap"><table class="doc-table"><thead><tr>${header}</tr></thead><tbody>${body}</tbody></table></div>`;
		},
		code({ text, lang }) {
			const language = lang ? ` data-lang="${lang}"` : '';
			return `<pre class="doc-pre"${language}><code>${text}</code></pre>`;
		},
		link({ href, title, tokens }) {
			const text = this.parser.parseInline(tokens);
			const titleAttr = title ? ` title="${title}"` : '';
			const isExternal = href.startsWith('http');
			const target = isExternal ? ' target="_blank" rel="noopener noreferrer"' : '';
			return `<a href="${href}" class="doc-link"${titleAttr}${target}>${text}</a>`;
		}
	}
});

export function renderMarkdown(source: string): string {
	return marked.parse(source, { async: false }) as string;
}
