function renderText(elements) {
    if (!elements)
        return '';
    return elements.map((e) => {
        const tr = e.text_run;
        if (!tr)
            return '';
        let t = tr.content ?? '';
        const s = tr.text_element_style ?? {};
        if (s.inline_code)
            t = `\`${t}\``;
        if (s.bold)
            t = `**${t}**`;
        if (s.italic)
            t = `*${t}*`;
        return t;
    }).join('');
}
export function blocksToMarkdown(blocks) {
    const byId = new Map();
    for (const b of blocks)
        byId.set(b.block_id, b);
    const root = blocks.find((b) => b.block_type === 1);
    if (!root)
        return { markdown: '', unsupported: [] };
    const unsupported = new Set();
    const out = [];
    const renderBlock = (b) => {
        const t = b.block_type;
        if (t === 1) {
            out.push(`# ${renderText(b.page?.elements)}`, '');
        }
        else if (t === 2) {
            out.push(renderText(b.text?.elements), '');
        }
        else if (t >= 3 && t <= 11) {
            const level = Math.min(t - 1, 6);
            const key = `heading${t - 2}`;
            const el = b[key]?.elements;
            out.push(`${'#'.repeat(level)} ${renderText(el)}`, '');
        }
        else if (t === 12) {
            out.push(`- ${renderText(b.bullet?.elements)}`);
        }
        else if (t === 13) {
            out.push(`1. ${renderText(b.ordered?.elements)}`);
        }
        else if (t === 14) {
            const lang = b.code?.language ?? '';
            out.push('```' + lang, renderText(b.code?.elements), '```', '');
        }
        else if (t === 15) {
            out.push(`> ${renderText(b.quote?.elements)}`, '');
        }
        else if (t === 17) {
            out.push(`> **Note:** ${renderText(b.callout?.elements)}`, '');
        }
        else if (t === 31 || t === 32) {
            const rows = b.table?.rows ?? [];
            if (rows.length) {
                const header = rows[0].map((c) => c.join(' ').trim());
                out.push(`| ${header.join(' | ')} |`);
                out.push(`|${header.map(() => '---').join('|')}|`);
                for (const r of rows.slice(1)) {
                    out.push(`| ${r.map((c) => c.join(' ').trim()).join(' | ')} |`);
                }
                out.push('');
            }
        }
        else if (t === 27 || t === 28) {
            // image/file — skip
        }
        else {
            unsupported.add(t);
            out.push(`<!-- unsupported block: ${t} -->`, '');
        }
        for (const cid of b.children ?? []) {
            const c = byId.get(cid);
            if (c)
                renderBlock(c);
        }
    };
    renderBlock(root);
    return {
        markdown: out.join('\n').replace(/\n{3,}/g, '\n\n').trimEnd() + '\n',
        unsupported: [...unsupported].sort((a, b) => a - b),
    };
}
