import { jsx as _jsx } from "react/jsx-runtime";
import { Box } from "ink";
import { estimateTranscriptRows, TranscriptMessage, } from "./TranscriptMessage.js";
import { estimateToolActivityGroupRows, ToolActivityGroup, } from "./ToolActivityGroup.js";
import { VirtualMessageList, virtualMessageWindow } from "./VirtualMessageList.js";
import { WelcomePanel } from "./WelcomePanel.js";
export function Transcript(props) {
    const entries = groupTranscriptItems(props.items);
    return (_jsx(VirtualMessageList, { entries: entries, height: props.height, width: props.width, estimateRows: estimateRows, empty: (_jsx(WelcomePanel, { width: props.width, providerReady: props.providerReady, model: props.model, projectPath: props.projectPath, permissionProfile: props.permissionProfile, shellEnabled: props.shellEnabled, browserEnabled: props.browserEnabled, language: props.language })), scrollOffset: props.scrollOffset, language: props.language, renderEntry: (entry, index) => renderTranscriptEntry(entry, index, props.width) }));
}
export function groupTranscriptItems(items) {
    const entries = [];
    let toolBatch = [];
    function flushToolBatch() {
        if (toolBatch.length >= 3) {
            entries.push({ kind: "tool-group", items: toolBatch });
        }
        else {
            for (const item of toolBatch) {
                entries.push({ kind: "item", item });
            }
        }
        toolBatch = [];
    }
    for (const item of items) {
        if (isToolActivityRole(item.role)) {
            toolBatch.push({ role: item.role, text: item.text });
            continue;
        }
        flushToolBatch();
        entries.push({ kind: "item", item });
    }
    flushToolBatch();
    return entries;
}
export function selectVisibleEntries(entries, height) {
    return virtualMessageWindow(entries, height, 80, estimateRows).visible;
}
function estimateRows(entry, width) {
    if (entry.kind === "tool-group")
        return estimateToolActivityGroupRows(entry.items);
    return estimateTranscriptRows(entry.item, width);
}
function renderTranscriptEntry(entry, index, width) {
    if (entry.kind === "tool-group") {
        return (_jsx(Box, { flexDirection: "column", marginBottom: 1, children: _jsx(ToolActivityGroup, { items: entry.items, detailWidth: Math.max(24, width - 12) }) }, `${index}-tool-group`));
    }
    if (entry.item.role === "display" && entry.item.display) {
        return (_jsx(Box, { flexDirection: "column", marginBottom: 1, children: entry.item.display }, `${index}-${entry.item.role}`));
    }
    return (_jsx(TranscriptMessage, { item: entry.item, width: Math.max(24, width - 2) }, `${index}-${entry.item.role}`));
}
function isToolActivityRole(role) {
    return role === "tool" || role === "tool-start";
}
