import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { useEffect, useState } from 'react';
import { Terminal } from 'lucide-react';
import { NERD_FONT_FAMILY, loadNerdFont } from '../../../lib/nerd-font';
import { formatDuration } from './utils';
import { ToolErrorDisplay } from './ToolErrorDisplay';
import { ToolHeader, ToolHeaderSeparator, ToolHeaderMeta, ToolHeaderSuccess, ToolContentBox, } from './shared';
const ANSI_RE = /[\x1B\x9B][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nq-uy=><~]/g;
const CONTROL_RE = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g;
function cleanTerminalOutput(raw) {
    return raw
        .replace(ANSI_RE, '')
        .replace(CONTROL_RE, '')
        .replace(/\\n/g, '\n')
        .replace(/\r\n/g, '\n')
        .replace(/\r/g, '\n');
}
export function TerminalRenderer({ contentJson, toolDurationMs, isExpanded, onToggle, compact, }) {
    const [, setFontReady] = useState(false);
    useEffect(() => {
        loadNerdFont().then(() => setFontReady(true));
    }, []);
    const result = contentJson.result || {};
    const args = contentJson.args || {};
    const operation = String(args.operation || args.command || '');
    const hasToolError = typeof result === 'object' && 'ok' in result && result.ok === false;
    const errorMessage = hasToolError && 'error' in result && typeof result.error === 'string'
        ? result.error
        : null;
    const errorStack = hasToolError && 'stack' in result && typeof result.stack === 'string'
        ? result.stack
        : undefined;
    const timeStr = formatDuration(toolDurationMs);
    const terminalId = String(result.terminalId || args.terminalId || '');
    const shortId = terminalId.length > 12 ? `${terminalId.slice(0, 12)}…` : terminalId;
    const purpose = String(result.purpose || args.purpose || '');
    const command = String(result.command || args.command || '');
    const renderStartResult = () => {
        const pid = result.pid ? `PID ${result.pid}` : '';
        return (_jsxs("div", { className: "mt-2 ml-5 flex flex-col gap-1 text-xs", children: [command && (_jsxs("div", { className: "flex items-center gap-2 text-foreground/70", children: [_jsx(Terminal, { className: "h-3 w-3" }), _jsx("code", { className: "font-mono", children: command })] })), purpose && _jsx("div", { className: "text-muted-foreground/70", children: purpose }), _jsxs("div", { className: "flex items-center gap-2 text-muted-foreground/60", children: [shortId && _jsx("span", { className: "font-mono", children: shortId }), pid && (_jsxs(_Fragment, { children: [_jsx("span", { children: "\u00B7" }), _jsx("span", { children: pid })] }))] })] }));
    };
    const renderReadResult = () => {
        const rawOutput = String(result.text || result.output || '');
        const output = cleanTerminalOutput(rawOutput);
        const status = String(result.status || '');
        const exitCode = result.exitCode;
        const lineCount = typeof result.lines === 'number' ? result.lines : 0;
        return (_jsxs("div", { className: "mt-2 ml-5 flex flex-col gap-2 max-w-full", children: [_jsxs("div", { className: "flex items-center gap-2 text-xs text-muted-foreground/70", children: [shortId && _jsx("span", { className: "font-mono", children: shortId }), _jsx("span", { children: "\u00B7" }), _jsxs("span", { children: [lineCount, " lines"] }), _jsx("span", { children: "\u00B7" }), _jsxs("span", { className: status === 'running'
                                ? 'text-emerald-600 dark:text-emerald-400'
                                : '', children: [status, status === 'exited' && exitCode !== undefined
                                    ? ` (${exitCode})`
                                    : ''] })] }), output.trim() && (_jsx(ToolContentBox, { title: "output", copyText: output, maxHeight: "max-h-[30rem]", children: _jsx("pre", { className: "px-3 py-2 text-xs text-foreground/85 whitespace-pre-wrap break-words overflow-x-auto", style: { fontFamily: NERD_FONT_FAMILY }, children: output }) }))] }));
    };
    const renderListResult = () => {
        const terminals = Array.isArray(result.terminals) ? result.terminals : [];
        const count = typeof result.count === 'number' ? result.count : terminals.length;
        return (_jsxs("div", { className: "mt-2 ml-5 flex flex-col gap-1 text-xs", children: [_jsxs("div", { className: "text-muted-foreground/70", children: [count, " terminal", count !== 1 ? 's' : ''] }), terminals.slice(0, 8).map((t, i) => (_jsxs("div", { className: "flex items-center gap-2 text-foreground/70 font-mono", children: [_jsx("span", { className: `h-2 w-2 rounded-full ${t.status === 'running' ? 'bg-emerald-500' : 'bg-muted-foreground/40'}` }), _jsx("span", { className: "truncate max-w-[100px]", children: String(t.id || '').slice(0, 12) }), _jsx("span", { className: "text-muted-foreground/60 truncate", children: String(t.purpose || '') })] }, String(t.id || i))))] }));
    };
    const renderWriteResult = () => {
        const written = String(args.input || '');
        return written ? (_jsx("div", { className: "mt-2 ml-5 text-xs", children: _jsx("code", { className: "font-mono text-foreground/70 whitespace-pre-wrap", children: written }) })) : null;
    };
    const label = operation || 'terminal';
    const headerLabel = `terminal ${label}`;
    const hasContent = !hasToolError &&
        (operation === 'start' ||
            operation === 'read' ||
            operation === 'list' ||
            (operation === 'write' && (args.input || result.message)));
    return (_jsxs("div", { className: "text-xs", children: [_jsxs(ToolHeader, { toolName: headerLabel, isExpanded: isExpanded, onToggle: onToggle, isError: !!hasToolError, colorVariant: "amber", canExpand: !!hasContent || !!hasToolError, children: [!compact && shortId && (_jsxs(_Fragment, { children: [_jsx(ToolHeaderSeparator, {}), _jsx("span", { className: "text-foreground/70 font-mono text-[11px]", children: shortId })] })), !compact && purpose && !shortId && (_jsxs(_Fragment, { children: [_jsx(ToolHeaderSeparator, {}), _jsx("span", { className: "text-foreground/70 text-[11px] truncate max-w-xs", children: purpose })] })), !hasToolError && !compact && (_jsxs(_Fragment, { children: [_jsx(ToolHeaderSeparator, {}), _jsx(ToolHeaderSuccess, { children: "ok" }), _jsx(ToolHeaderSeparator, {}), _jsx(ToolHeaderMeta, { children: timeStr })] })), hasToolError && !compact && (_jsxs(ToolHeaderMeta, { children: ["\u00B7 ", timeStr] }))] }), isExpanded && hasToolError && errorMessage && (_jsx(ToolErrorDisplay, { error: errorMessage, stack: errorStack, showStack: true })), isExpanded &&
                !hasToolError &&
                operation === 'start' &&
                renderStartResult(), isExpanded &&
                !hasToolError &&
                operation === 'read' &&
                renderReadResult(), isExpanded &&
                !hasToolError &&
                operation === 'list' &&
                renderListResult(), isExpanded &&
                !hasToolError &&
                operation === 'write' &&
                renderWriteResult()] }));
}
//# sourceMappingURL=TerminalRenderer.js.map