import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { Box, Text } from 'ink';
import { theme } from '../semantic-colors.js';
import { shortenPath, tildeifyPath, getDisplayString, checkExhaustive, } from '@google/gemini-cli-core';
import { ConsoleSummaryDisplay } from './ConsoleSummaryDisplay.js';
import process from 'node:process';
import { MemoryUsageDisplay } from './MemoryUsageDisplay.js';
import { ContextUsageDisplay } from './ContextUsageDisplay.js';
import { QuotaDisplay } from './QuotaDisplay.js';
import { DebugProfiler } from './DebugProfiler.js';
import { useUIState } from '../contexts/UIStateContext.js';
import { useConfig } from '../contexts/ConfigContext.js';
import { useSettings } from '../contexts/SettingsContext.js';
import { useVimMode } from '../contexts/VimModeContext.js';
import { ALL_ITEMS, deriveItemsFromLegacySettings, } from '../../config/footerItems.js';
import { isDevelopment } from '../../utils/installationInfo.js';
const CwdIndicator = ({ targetDir, maxWidth, debugMode, debugMessage, color = theme.text.primary, }) => {
    const debugSuffix = debugMode ? ' ' + (debugMessage || '--debug') : '';
    const availableForPath = Math.max(10, maxWidth - debugSuffix.length);
    const displayPath = shortenPath(tildeifyPath(targetDir), availableForPath);
    return (_jsxs(Text, { color: color, children: [displayPath, debugMode && _jsx(Text, { color: theme.status.error, children: debugSuffix })] }));
};
const SandboxIndicator = ({ isTrustedFolder, }) => {
    if (isTrustedFolder === false) {
        return _jsx(Text, { color: theme.status.warning, children: "untrusted" });
    }
    const sandbox = process.env['SANDBOX'];
    if (sandbox && sandbox !== 'sandbox-exec') {
        return (_jsx(Text, { color: "green", children: sandbox.replace(/^gemini-(?:cli-)?/, '') }));
    }
    if (sandbox === 'sandbox-exec') {
        return (_jsxs(Text, { color: theme.status.warning, children: ["macOS Seatbelt", ' ', _jsxs(Text, { color: theme.ui.comment, children: ["(", process.env['SEATBELT_PROFILE'], ")"] })] }));
    }
    return _jsx(Text, { color: theme.status.error, children: "no sandbox" });
};
const CorgiIndicator = () => (_jsxs(Text, { children: [_jsx(Text, { color: theme.status.error, children: "\u25BC" }), _jsx(Text, { color: theme.text.primary, children: "(\u00B4" }), _jsx(Text, { color: theme.status.error, children: "\u1D25" }), _jsx(Text, { color: theme.text.primary, children: "`)" }), _jsx(Text, { color: theme.status.error, children: "\u25BC" })] }));
const COLUMN_GAP = 3;
export const FooterRow = ({ items, showLabels }) => {
    const elements = [];
    items.forEach((item, idx) => {
        if (idx > 0) {
            elements.push(_jsx(Box, { flexGrow: 1, flexShrink: 1, minWidth: showLabels ? COLUMN_GAP : 3, justifyContent: "center", alignItems: "center", children: !showLabels && _jsx(Text, { color: theme.ui.comment, children: " \u00B7 " }) }, `sep-${item.key}`));
        }
        elements.push(_jsxs(Box, { flexDirection: "column", flexGrow: item.flexGrow ?? 0, flexShrink: item.flexShrink ?? 1, alignItems: item.alignItems, backgroundColor: item.isFocused ? theme.background.focus : undefined, children: [showLabels && (_jsx(Box, { height: 1, children: _jsx(Text, { color: item.isFocused ? theme.text.primary : theme.ui.comment, children: item.header }) })), _jsx(Box, { height: 1, children: item.element })] }, item.key));
    });
    return (_jsx(Box, { flexDirection: "row", flexWrap: "nowrap", width: "100%", children: elements }));
};
function isFooterItemId(id) {
    return ALL_ITEMS.some((i) => i.id === id);
}
export const Footer = () => {
    const uiState = useUIState();
    const config = useConfig();
    const settings = useSettings();
    const { vimEnabled, vimMode } = useVimMode();
    const { model, targetDir, debugMode, branchName, debugMessage, corgiMode, errorCount, showErrorDetails, promptTokenCount, isTrustedFolder, terminalWidth, quotaStats, } = {
        model: uiState.currentModel,
        targetDir: config.getTargetDir(),
        debugMode: config.getDebugMode(),
        branchName: uiState.branchName,
        debugMessage: uiState.debugMessage,
        corgiMode: uiState.corgiMode,
        errorCount: uiState.errorCount,
        showErrorDetails: uiState.showErrorDetails,
        promptTokenCount: uiState.sessionStats.lastPromptTokenCount,
        isTrustedFolder: uiState.isTrustedFolder,
        terminalWidth: uiState.terminalWidth,
        quotaStats: uiState.quota.stats,
    };
    const isFullErrorVerbosity = settings.merged.ui.errorVerbosity === 'full';
    const showErrorSummary = !showErrorDetails &&
        errorCount > 0 &&
        (isFullErrorVerbosity || debugMode || isDevelopment);
    const displayVimMode = vimEnabled ? vimMode : undefined;
    const items = settings.merged.ui.footer.items ??
        deriveItemsFromLegacySettings(settings.merged);
    const showLabels = settings.merged.ui.footer.showLabels !== false;
    const itemColor = showLabels ? theme.text.primary : theme.ui.comment;
    const potentialColumns = [];
    const addCol = (id, header, element, dataWidth, isHighPriority = false) => {
        potentialColumns.push({
            id,
            header: showLabels ? header : '',
            element,
            width: Math.max(dataWidth, showLabels ? header.length : 0),
            isHighPriority,
        });
    };
    // 1. System Indicators (Far Left, high priority)
    if (uiState.showDebugProfiler) {
        addCol('debug', '', () => _jsx(DebugProfiler, {}), 45, true);
    }
    if (displayVimMode) {
        const vimStr = `[${displayVimMode}]`;
        addCol('vim', '', () => _jsx(Text, { color: theme.text.accent, children: vimStr }), vimStr.length, true);
    }
    // 2. Main Configurable Items
    for (const id of items) {
        if (!isFooterItemId(id))
            continue;
        const itemConfig = ALL_ITEMS.find((i) => i.id === id);
        const header = itemConfig?.header ?? id;
        switch (id) {
            case 'workspace': {
                const fullPath = tildeifyPath(targetDir);
                const debugSuffix = debugMode ? ' ' + (debugMessage || '--debug') : '';
                addCol(id, header, (maxWidth) => (_jsx(CwdIndicator, { targetDir: targetDir, maxWidth: maxWidth, debugMode: debugMode, debugMessage: debugMessage, color: itemColor })), fullPath.length + debugSuffix.length);
                break;
            }
            case 'git-branch': {
                if (branchName) {
                    addCol(id, header, () => _jsx(Text, { color: itemColor, children: branchName }), branchName.length);
                }
                break;
            }
            case 'sandbox': {
                let str = 'no sandbox';
                const sandbox = process.env['SANDBOX'];
                if (isTrustedFolder === false)
                    str = 'untrusted';
                else if (sandbox === 'sandbox-exec')
                    str = `macOS Seatbelt (${process.env['SEATBELT_PROFILE']})`;
                else if (sandbox)
                    str = sandbox.replace(/^gemini-(?:cli-)?/, '');
                addCol(id, header, () => _jsx(SandboxIndicator, { isTrustedFolder: isTrustedFolder }), str.length);
                break;
            }
            case 'model-name': {
                const str = getDisplayString(model);
                addCol(id, header, () => _jsx(Text, { color: itemColor, children: str }), str.length);
                break;
            }
            case 'context-used': {
                addCol(id, header, () => (_jsx(ContextUsageDisplay, { promptTokenCount: promptTokenCount, model: model, terminalWidth: terminalWidth })), 10);
                break;
            }
            case 'quota': {
                if (quotaStats?.remaining !== undefined && quotaStats.limit) {
                    addCol(id, header, () => (_jsx(QuotaDisplay, { remaining: quotaStats.remaining, limit: quotaStats.limit, resetTime: quotaStats.resetTime, terse: true, forceShow: true, lowercase: true })), 10);
                }
                break;
            }
            case 'memory-usage': {
                addCol(id, header, () => _jsx(MemoryUsageDisplay, { color: itemColor }), 10);
                break;
            }
            case 'session-id': {
                addCol(id, header, () => (_jsx(Text, { color: itemColor, children: uiState.sessionStats.sessionId.slice(0, 8) })), 8);
                break;
            }
            case 'code-changes': {
                const added = uiState.sessionStats.metrics.files.totalLinesAdded;
                const removed = uiState.sessionStats.metrics.files.totalLinesRemoved;
                if (added > 0 || removed > 0) {
                    const str = `+${added} -${removed}`;
                    addCol(id, header, () => (_jsxs(Text, { children: [_jsxs(Text, { color: theme.status.success, children: ["+", added] }), ' ', _jsxs(Text, { color: theme.status.error, children: ["-", removed] })] })), str.length);
                }
                break;
            }
            case 'token-count': {
                let total = 0;
                for (const m of Object.values(uiState.sessionStats.metrics.models))
                    total += m.tokens.total;
                if (total > 0) {
                    const formatter = new Intl.NumberFormat('en-US', {
                        notation: 'compact',
                        maximumFractionDigits: 1,
                    });
                    const formatted = formatter.format(total).toLowerCase();
                    addCol(id, header, () => _jsxs(Text, { color: itemColor, children: [formatted, " tokens"] }), formatted.length + 7);
                }
                break;
            }
            default:
                checkExhaustive(id);
                break;
        }
    }
    // 3. Transients
    if (corgiMode)
        addCol('corgi', '', () => _jsx(CorgiIndicator, {}), 5);
    if (showErrorSummary) {
        addCol('error-count', '', () => _jsx(ConsoleSummaryDisplay, { errorCount: errorCount }), 12, true);
    }
    // --- Width Fitting Logic ---
    const columnsToRender = [];
    let droppedAny = false;
    let currentUsedWidth = 2; // Initial padding
    for (const col of potentialColumns) {
        const gap = columnsToRender.length > 0 ? (showLabels ? COLUMN_GAP : 3) : 0;
        const budgetWidth = col.id === 'workspace' ? 20 : col.width;
        if (col.isHighPriority ||
            currentUsedWidth + gap + budgetWidth <= terminalWidth - 2) {
            columnsToRender.push(col);
            currentUsedWidth += gap + budgetWidth;
        }
        else {
            droppedAny = true;
        }
    }
    const rowItems = columnsToRender.map((col, index) => {
        const isWorkspace = col.id === 'workspace';
        const isLast = index === columnsToRender.length - 1;
        // Calculate exact space available for growth to prevent over-estimation truncation
        const otherItemsWidth = columnsToRender
            .filter((c) => c.id !== 'workspace')
            .reduce((sum, c) => sum + c.width, 0);
        const numItems = columnsToRender.length + (droppedAny ? 1 : 0);
        const numGaps = numItems > 1 ? numItems - 1 : 0;
        const gapsWidth = numGaps * (showLabels ? COLUMN_GAP : 3);
        const ellipsisWidth = droppedAny ? 1 : 0;
        const availableForWorkspace = Math.max(20, terminalWidth - 2 - gapsWidth - otherItemsWidth - ellipsisWidth);
        const estimatedWidth = isWorkspace ? availableForWorkspace : col.width;
        return {
            key: col.id,
            header: col.header,
            element: col.element(estimatedWidth),
            flexGrow: 0,
            flexShrink: isWorkspace ? 1 : 0,
            alignItems: isLast && !droppedAny && index > 0 ? 'flex-end' : 'flex-start',
        };
    });
    if (droppedAny) {
        rowItems.push({
            key: 'ellipsis',
            header: '',
            element: _jsx(Text, { color: theme.ui.comment, children: "\u2026" }),
            flexGrow: 0,
            flexShrink: 0,
            alignItems: 'flex-end',
        });
    }
    return (_jsx(Box, { width: terminalWidth, paddingX: 1, overflow: "hidden", flexWrap: "nowrap", children: _jsx(FooterRow, { items: rowItems, showLabels: showLabels }) }));
};
//# sourceMappingURL=Footer.js.map