import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
import React from "react";
import { cn } from "../lib/utils";
function isTableRow(line) {
    const trimmed = line.trim();
    return trimmed.startsWith("|") && trimmed.endsWith("|");
}
function isTableSeparator(line) {
    const trimmed = line.trim();
    return isTableRow(line) && /^\|[\s\-:|]+\|$/.test(trimmed);
}
function parseTableCells(line) {
    const trimmed = line.trim();
    const inner = trimmed.slice(1, -1);
    return inner.split("|").map((cell) => cell.trim());
}
function parseTableAlignments(separatorLine) {
    const cells = parseTableCells(separatorLine);
    return cells.map((cell) => {
        const trimmed = cell.trim();
        const startsWithColon = trimmed.startsWith(":");
        const endsWithColon = trimmed.endsWith(":");
        if (startsWithColon && endsWithColon)
            return "center";
        if (endsWithColon)
            return "right";
        return "left";
    });
}
function renderWithOverride(tag, key, components, props, children) {
    const Component = components?.[tag];
    if (Component) {
        return (_jsx(Component, { ...props, children: children }, key));
    }
    return React.createElement(tag, { key, ...props }, children);
}
function renderDefaultInline(text, components, keyPrefix) {
    const parts = [];
    const regex = /(\*\*([^*]+)\*\*|`([^`]+)`)/g;
    let lastIndex = 0;
    let match;
    while ((match = regex.exec(text)) !== null) {
        if (match.index > lastIndex) {
            parts.push(text.substring(lastIndex, match.index));
        }
        if (match[2] !== undefined) {
            parts.push(_jsx("strong", { children: match[2] }, `${keyPrefix}-bold-${match.index}`));
        }
        else if (match[3] !== undefined) {
            parts.push(renderWithOverride("code", `${keyPrefix}-code-${match.index}`, components, {
                inline: true,
                className: "rounded bg-neutral-grey-5 px-1 py-0.5 text-[10px] text-neutral-grey-100",
            }, match[3]));
        }
        lastIndex = match.index + match[0].length;
    }
    if (lastIndex < text.length) {
        parts.push(text.substring(lastIndex));
    }
    if (parts.length === 0)
        return text;
    return _jsx(_Fragment, { children: parts });
}
export function MarkdownDisplay({ source, className, components, renderInline, }) {
    const markdown = source.trim();
    if (!markdown)
        return null;
    const normalizedContent = markdown
        .replace(/\r\n/g, "\n")
        .replace(/\r/g, "\n");
    const lines = normalizedContent.split("\n");
    const renderedBlocks = [];
    let lineIndex = 0;
    let blockIndex = 0;
    const renderInlineContent = (text, keyPrefix) => renderInline
        ? renderInline(text)
        : renderDefaultInline(text, components, keyPrefix);
    while (lineIndex < lines.length) {
        const line = lines[lineIndex] || "";
        if (line.trimStart().startsWith("```")) {
            const fence = line.trim();
            const language = fence.slice(3).trim();
            const codeLines = [];
            lineIndex += 1;
            while (lineIndex < lines.length) {
                const currentLine = lines[lineIndex] || "";
                if (currentLine.trim() === "```") {
                    break;
                }
                codeLines.push(currentLine);
                lineIndex += 1;
            }
            if (lineIndex < lines.length &&
                (lines[lineIndex] || "").trim() === "```") {
                lineIndex += 1;
            }
            const codeNode = renderWithOverride("code", `code-block-${blockIndex}`, components, {
                inline: false,
                className: language ? `language-${language}` : undefined,
            }, codeLines.join("\n"));
            renderedBlocks.push(renderWithOverride("pre", `pre-${blockIndex}`, components, {
                className: "my-1 overflow-auto rounded bg-neutral-grey-5 badge-pad text-[11px] leading-4 text-neutral-grey-100",
            }, codeNode));
            blockIndex += 1;
            continue;
        }
        if (isTableRow(line) && !isTableSeparator(line)) {
            const nextLine = lines[lineIndex + 1];
            if (nextLine && isTableSeparator(nextLine)) {
                const headerCells = parseTableCells(line);
                const alignments = parseTableAlignments(nextLine);
                const bodyRows = [];
                let tableLineIndex = lineIndex + 2;
                while (tableLineIndex < lines.length &&
                    isTableRow(lines[tableLineIndex] || "") &&
                    !isTableSeparator(lines[tableLineIndex] || "")) {
                    bodyRows.push(parseTableCells(lines[tableLineIndex] || ""));
                    tableLineIndex += 1;
                }
                const alignClass = {
                    left: "text-left",
                    center: "text-center",
                    right: "text-right",
                };
                renderedBlocks.push(_jsx("div", { className: "my-3 overflow-x-auto", children: _jsxs("table", { className: "border-border-default min-w-full border-collapse rounded-md border text-sm", children: [_jsx("thead", { className: "bg-neutral-grey-5", children: _jsx("tr", { children: headerCells.map((cell, headerIndex) => (_jsx("th", { className: cn("border-border-default text-neutral-grey-100 border px-3 py-2 font-semibold", alignClass[alignments[headerIndex] || "left"]), children: renderInlineContent(cell, `th-${blockIndex}-${headerIndex}`) }, `th-${headerIndex}`))) }) }), _jsx("tbody", { children: bodyRows.map((row, rowIndex) => (_jsx("tr", { className: rowIndex % 2 === 0 ? "bg-white" : "bg-neutral-grey-5", children: row.map((cell, cellIndex) => (_jsx("td", { className: cn("border-border-default text-neutral-grey-50 border px-3 py-2", alignClass[alignments[cellIndex] || "left"]), children: renderInlineContent(cell, `td-${blockIndex}-${rowIndex}-${cellIndex}`) }, `td-${rowIndex}-${cellIndex}`))) }, `tr-${rowIndex}`))) })] }) }, `table-${blockIndex}`));
                lineIndex = tableLineIndex;
                blockIndex += 1;
                continue;
            }
        }
        if (line.startsWith("# ")) {
            renderedBlocks.push(renderWithOverride("h1", `h1-${blockIndex}`, components, { className: "mt-4 mb-2 text-xl font-bold text-neutral-grey-100" }, renderInlineContent(line.substring(2), `h1-${blockIndex}`)));
            lineIndex += 1;
            blockIndex += 1;
            continue;
        }
        if (line.startsWith("## ")) {
            renderedBlocks.push(renderWithOverride("h2", `h2-${blockIndex}`, components, {
                className: "mt-3 mb-2 text-lg font-semibold text-neutral-grey-100",
            }, renderInlineContent(line.substring(3), `h2-${blockIndex}`)));
            lineIndex += 1;
            blockIndex += 1;
            continue;
        }
        if (line.startsWith("### ")) {
            renderedBlocks.push(renderWithOverride("h3", `h3-${blockIndex}`, components, {
                className: "mt-2 mb-1 text-base font-semibold text-neutral-grey-100",
            }, renderInlineContent(line.substring(4), `h3-${blockIndex}`)));
            lineIndex += 1;
            blockIndex += 1;
            continue;
        }
        if (line.startsWith("#### ")) {
            renderedBlocks.push(renderWithOverride("h4", `h4-${blockIndex}`, components, {
                className: "mt-2 mb-1 text-sm font-semibold text-neutral-grey-100",
            }, renderInlineContent(line.substring(5), `h4-${blockIndex}`)));
            lineIndex += 1;
            blockIndex += 1;
            continue;
        }
        if ((line.match(/^[-*] /) || []).length > 0) {
            const listItems = [];
            const startIndex = lineIndex;
            while (lineIndex < lines.length &&
                ((lines[lineIndex] || "").match(/^[-*] /) || []).length > 0) {
                const listLine = lines[lineIndex] || "";
                listItems.push(renderWithOverride("li", `li-${lineIndex}`, components, { className: "text-sm text-neutral-grey-50" }, renderInlineContent(listLine.substring(2), `li-${lineIndex}`)));
                lineIndex += 1;
            }
            renderedBlocks.push(renderWithOverride("ul", `ul-${startIndex}`, components, {
                className: "my-2 ml-6 space-y-1",
                style: { listStyleType: "disc", paddingLeft: "1rem" },
            }, listItems));
            blockIndex += 1;
            continue;
        }
        if ((line.match(/^\d+\.\s/) || []).length > 0) {
            const listItems = [];
            const startIndex = lineIndex;
            const firstNumberMatch = line.match(/^(\d+)\.\s/);
            const listStart = firstNumberMatch
                ? Number.parseInt(firstNumberMatch[1] || "1", 10)
                : 1;
            while (lineIndex < lines.length &&
                ((lines[lineIndex] || "").match(/^\d+\.\s/) || []).length > 0) {
                const listLine = lines[lineIndex] || "";
                const dotIndex = listLine.indexOf(".");
                const itemContent = dotIndex >= 0
                    ? listLine.substring(dotIndex + 1).trimStart()
                    : listLine;
                listItems.push(renderWithOverride("li", `oli-${lineIndex}`, components, { className: "text-sm text-neutral-grey-50" }, renderInlineContent(itemContent, `oli-${lineIndex}`)));
                lineIndex += 1;
            }
            renderedBlocks.push(renderWithOverride("ol", `ol-${startIndex}`, components, {
                start: listStart,
                className: "my-2 ml-6 space-y-1",
                style: { listStyleType: "decimal", paddingLeft: "1rem" },
            }, listItems));
            blockIndex += 1;
            continue;
        }
        if ((line.match(/^[-*_]{3,}\s*$/) || []).length > 0) {
            renderedBlocks.push(renderWithOverride("hr", `hr-${blockIndex}`, components, { className: "my-4 border-t border-border-default" }, null));
            lineIndex += 1;
            blockIndex += 1;
            continue;
        }
        if (line.trim()) {
            renderedBlocks.push(renderWithOverride("p", `p-${blockIndex}`, components, { className: "my-1 text-sm text-neutral-grey-50" }, renderInlineContent(line, `p-${blockIndex}`)));
        }
        else {
            renderedBlocks.push(_jsx("div", { className: "h-2" }, `spacer-${blockIndex}`));
        }
        lineIndex += 1;
        blockIndex += 1;
    }
    return (_jsx("div", { className: cn("min-w-0 space-y-1", className), children: renderedBlocks }));
}
//# sourceMappingURL=MarkdownDisplay.js.map