import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { Box, Text } from 'ink';
/**
 * Lightweight markdown rendering for terminal output: headers, code fences,
 * inline code/bold, list bullets. No dependency, no full CommonMark; just the
 * constructs models actually emit in chat.
 */
function renderInline(text, keyPrefix) {
    // Split on `code`, **bold** spans; render the rest as plain text.
    const parts = text.split(/(`[^`]+`|\*\*[^*]+\*\*)/g);
    return parts
        .filter((p) => p.length > 0)
        .map((part, i) => {
        if (part.startsWith('`') && part.endsWith('`') && part.length > 2) {
            return (_jsx(Text, { color: "yellow", children: part.slice(1, -1) }, `${keyPrefix}-${i}`));
        }
        if (part.startsWith('**') && part.endsWith('**') && part.length > 4) {
            return (_jsx(Text, { bold: true, children: part.slice(2, -2) }, `${keyPrefix}-${i}`));
        }
        return _jsx(Text, { children: part }, `${keyPrefix}-${i}`);
    });
}
export function Markdown({ children }) {
    const lines = children.split('\n');
    const blocks = [];
    let inCode = false;
    let codeLines = [];
    lines.forEach((line, i) => {
        if (line.trimStart().startsWith('```')) {
            if (inCode) {
                blocks.push(_jsx(Box, { paddingLeft: 2, flexDirection: "column", children: codeLines.map((cl, j) => (_jsx(Text, { color: "cyan", children: cl || ' ' }, j))) }, `code-${i}`));
                codeLines = [];
            }
            inCode = !inCode;
            return;
        }
        if (inCode) {
            codeLines.push(line);
            return;
        }
        const header = line.match(/^(#{1,4})\s+(.*)$/);
        if (header) {
            blocks.push(_jsx(Text, { bold: true, underline: header[1].length <= 2, children: header[2] }, i));
            return;
        }
        const bullet = line.match(/^(\s*)[-*]\s+(.*)$/);
        if (bullet) {
            blocks.push(_jsxs(Text, { children: [bullet[1], '• ', renderInline(bullet[2], `b${i}`)] }, i));
            return;
        }
        blocks.push(_jsx(Text, { children: line.length > 0 ? renderInline(line, `l${i}`) : ' ' }, i));
    });
    // Unclosed fence: flush what we have.
    if (inCode && codeLines.length > 0) {
        blocks.push(_jsx(Box, { paddingLeft: 2, flexDirection: "column", children: codeLines.map((cl, j) => (_jsx(Text, { color: "cyan", children: cl || ' ' }, j))) }, "code-tail"));
    }
    return _jsx(Box, { flexDirection: "column", children: blocks });
}
