// markdown-renderer.ts — Lightweight markdown-to-HTML converter (zero deps)
function esc(text) {
    return text
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;');
}
/** Strip YAML frontmatter (--- delimited block at start of file). */
function stripFrontmatter(md) {
    return md.replace(/^---\n[\s\S]*?\n---\n*/, '');
}
/** Convert inline markdown: bold, italic, code, links, checkboxes. */
function renderInline(line) {
    return line
        .replace(/`([^`]+)`/g, '<code>$1</code>')
        .replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>')
        .replace(/\*([^*]+)\*/g, '<em>$1</em>')
        .replace(/\[x\]/gi, '<input type="checkbox" checked disabled>')
        .replace(/\[ \]/g, '<input type="checkbox" disabled>')
        .replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2">$1</a>');
}
/** Convert a markdown table block (lines starting with |) into an HTML table. */
function renderTable(lines) {
    const rows = lines.filter((l) => !/^\|\s*[-:]+/.exec(l)); // skip separator row
    if (rows.length === 0) {
        return '';
    }
    const parseRow = (row) => row
        .split('|')
        .slice(1, -1)
        .map((c) => c.trim());
    const headerCells = parseRow(rows[0] ?? '');
    const thead = `<thead><tr>${headerCells.map((c) => `<th>${renderInline(esc(c))}</th>`).join('')}</tr></thead>`;
    const bodyRows = rows.slice(1).map((r) => {
        const cells = parseRow(r);
        return `<tr>${cells.map((c) => `<td>${renderInline(esc(c))}</td>`).join('')}</tr>`;
    });
    return `<table class="md-table">${thead}<tbody>${bodyRows.join('')}</tbody></table>`;
}
/** Convert a fenced code block into an HTML pre/code block. */
function renderCodeBlock(lines, lang) {
    const code = lines.map((l) => esc(l)).join('\n');
    const cls = lang ? ` class="lang-${esc(lang)}"` : '';
    return `<pre><code${cls}>${code}</code></pre>`;
}
/**
 * Convert markdown string to HTML.
 * Supports: headings, bold, italic, code, fenced code blocks,
 * tables, lists (ul/ol), checkboxes, links, paragraphs.
 */
export function markdownToHtml(md) {
    const clean = stripFrontmatter(md);
    const lines = clean.split('\n');
    const out = [];
    let i = 0;
    let inList = false;
    let listTag = 'ul';
    const closeList = () => {
        if (inList) {
            out.push(`</${listTag}>`);
            inList = false;
        }
    };
    while (i < lines.length) {
        const line = lines[i] ?? '';
        // Fenced code block
        if (line.startsWith('```')) {
            closeList();
            const lang = line.slice(3).trim();
            const codeLines = [];
            i++;
            while (i < lines.length && !(lines[i] ?? '').startsWith('```')) {
                codeLines.push(lines[i] ?? '');
                i++;
            }
            out.push(renderCodeBlock(codeLines, lang));
            i++; // skip closing ```
            continue;
        }
        // Table block
        if (line.startsWith('|')) {
            closeList();
            const tableLines = [];
            while (i < lines.length && (lines[i] ?? '').startsWith('|')) {
                tableLines.push(lines[i] ?? '');
                i++;
            }
            out.push(renderTable(tableLines));
            continue;
        }
        // Headings
        const headingMatch = /^(#{1,6})\s+(.+)$/.exec(line);
        if (headingMatch?.[1] && headingMatch[2]) {
            closeList();
            const level = headingMatch[1].length;
            out.push(`<h${String(level)}>${renderInline(esc(headingMatch[2]))}</h${String(level)}>`);
            i++;
            continue;
        }
        // Horizontal rule
        if (/^[-*_]{3,}\s*$/.test(line)) {
            closeList();
            out.push('<hr>');
            i++;
            continue;
        }
        // Unordered list item
        const ulMatch = /^(\s*)[-*+]\s+(.+)$/.exec(line);
        if (ulMatch?.[2]) {
            if (!inList || listTag !== 'ul') {
                closeList();
                out.push('<ul>');
                inList = true;
                listTag = 'ul';
            }
            out.push(`<li>${renderInline(esc(ulMatch[2]))}</li>`);
            i++;
            continue;
        }
        // Ordered list item
        const olMatch = /^(\s*)\d+\.\s+(.+)$/.exec(line);
        if (olMatch?.[2]) {
            if (!inList || listTag !== 'ol') {
                closeList();
                out.push('<ol>');
                inList = true;
                listTag = 'ol';
            }
            out.push(`<li>${renderInline(esc(olMatch[2]))}</li>`);
            i++;
            continue;
        }
        // Blockquote
        if (line.startsWith('>')) {
            closeList();
            const content = line.replace(/^>\s?/, '');
            out.push(`<blockquote>${renderInline(esc(content))}</blockquote>`);
            i++;
            continue;
        }
        // Empty line
        if (line.trim() === '') {
            closeList();
            i++;
            continue;
        }
        // Paragraph
        closeList();
        out.push(`<p>${renderInline(esc(line))}</p>`);
        i++;
    }
    closeList();
    return out.join('\n');
}
//# sourceMappingURL=markdown-renderer.js.map