/**
 * Status Bar Component
 *
 * Displays comprehensive session metrics:
 * - Token usage with progress bar
 * - Cost tracking with budget indicator
 * - Performance metrics (tokens/sec, latency)
 * - Session time
 * - Model info
 */
import React, { useState, useEffect, useMemo } from 'react';
import { Box, Text } from 'ink';
import { useTheme } from '../context/theme-context.js';
import { formatTokenCount } from '../../utils/token-counter.js';
import { getLatencyOptimizer, getStreamingOptimizer, LATENCY_THRESHOLDS, } from '../../optimization/latency-optimizer.js';
/**
 * Format duration in human-readable format
 */
function formatDuration(seconds) {
    if (seconds < 60)
        return `${seconds}s`;
    const mins = Math.floor(seconds / 60);
    const secs = seconds % 60;
    if (mins < 60)
        return `${mins}m ${secs}s`;
    const hours = Math.floor(mins / 60);
    const remainingMins = mins % 60;
    return `${hours}h ${remainingMins}m`;
}
/**
 * Format cost in USD
 */
function formatCost(cost) {
    if (cost === 0)
        return '$0.00';
    if (cost < 0.01)
        return `$${(cost * 1000).toFixed(2)}m`; // Show in millicents
    if (cost < 1)
        return `$${cost.toFixed(3)}`;
    return `$${cost.toFixed(2)}`;
}
/**
 * Calculate tokens per second
 */
function calculateTokensPerSecond(tokens, seconds) {
    if (seconds === 0)
        return 0;
    return Math.round(tokens / seconds);
}
/**
 * Status Bar Component
 */
export function StatusBar({ tokenCount, maxTokens = 128000, cost = 0, budget = 10, modelName = 'codebuddy', mode = 'code', yolo = false, processingTime = 0, sessionStartTime, showDetails = false, compact = false, showLatencyStats = false, }) {
    const { colors } = useTheme();
    const [sessionDuration, setSessionDuration] = useState(0);
    const [latencyStats, setLatencyStats] = useState(null);
    // Update latency stats periodically
    useEffect(() => {
        if (!showLatencyStats)
            return;
        const updateStats = () => {
            const latencyOptimizer = getLatencyOptimizer();
            const streamingOptimizer = getStreamingOptimizer();
            const opStats = latencyOptimizer.getStats();
            const streamStats = streamingOptimizer.getStats();
            setLatencyStats({
                avgDuration: opStats.avgDuration,
                p95: opStats.p95,
                metTarget: opStats.totalOperations > 0
                    ? Math.round((opStats.metTarget / opStats.totalOperations) * 100)
                    : 0,
                totalOperations: opStats.totalOperations,
                avgFirstToken: streamStats.avgFirstToken,
            });
        };
        updateStats(); // Initial update
        const interval = setInterval(updateStats, 2000); // Update every 2 seconds
        return () => clearInterval(interval);
    }, [showLatencyStats]);
    // Update session duration every second
    useEffect(() => {
        if (!sessionStartTime)
            return;
        const interval = setInterval(() => {
            const elapsed = Math.floor((Date.now() - sessionStartTime.getTime()) / 1000);
            setSessionDuration(elapsed);
        }, 1000);
        return () => clearInterval(interval);
    }, [sessionStartTime]);
    // Calculate metrics
    const metrics = useMemo(() => {
        const tokenProgress = maxTokens > 0 ? (tokenCount / maxTokens) * 100 : 0;
        const costProgress = budget > 0 ? (cost / budget) * 100 : 0;
        const tokensPerSec = calculateTokensPerSecond(tokenCount, processingTime);
        // Determine token usage color based on percentage
        let tokenColor;
        if (tokenProgress < 50)
            tokenColor = colors.success;
        else if (tokenProgress < 80)
            tokenColor = colors.warning;
        else
            tokenColor = colors.error;
        // Determine cost color based on budget
        let costColor;
        if (costProgress < 50)
            costColor = colors.success;
        else if (costProgress < 80)
            costColor = colors.warning;
        else
            costColor = colors.error;
        // Mode icons and colors
        const modeIcons = {
            plan: '📋',
            code: '💻',
            ask: '❓',
        };
        const modeColors = {
            plan: colors.info,
            code: colors.primary,
            ask: colors.secondary,
        };
        return {
            tokenProgress,
            costProgress,
            tokensPerSec,
            tokenColor,
            costColor,
            modeIcon: modeIcons[mode] || '🤖',
            modeColor: modeColors[mode] || colors.primary,
        };
    }, [tokenCount, maxTokens, cost, budget, processingTime, colors, mode]);
    // Render progress bar
    const renderProgressBar = (progress, width = 10, color = colors.success) => {
        const filledWidth = Math.max(0, Math.min(width, Math.round((progress / 100) * width)));
        const emptyWidth = width - filledWidth;
        const filled = '█'.repeat(filledWidth);
        const empty = '░'.repeat(emptyWidth);
        return (React.createElement(React.Fragment, null,
            React.createElement(Text, { color: color }, filled),
            React.createElement(Text, { dimColor: true }, empty)));
    };
    // Compact mode - single line
    if (compact) {
        return (React.createElement(Box, { borderStyle: "single", borderColor: colors.border, paddingX: 1 },
            React.createElement(Text, { color: metrics.modeColor },
                metrics.modeIcon,
                " ",
                mode),
            React.createElement(Text, { dimColor: true }, " \u2022 "),
            React.createElement(Text, { color: yolo ? colors.error : colors.success }, yolo ? '🔥 YOLO' : '🛡 SAFE'),
            React.createElement(Text, { dimColor: true }, " \u2022 "),
            React.createElement(Text, { color: colors.textMuted }, modelName),
            React.createElement(Text, { dimColor: true }, " \u2022 "),
            React.createElement(Text, { color: metrics.tokenColor }, formatTokenCount(tokenCount)),
            React.createElement(Text, { dimColor: true }, " tokens"),
            cost > 0 && (React.createElement(React.Fragment, null,
                React.createElement(Text, { dimColor: true }, " \u2022 "),
                React.createElement(Text, { color: metrics.costColor }, formatCost(cost))))));
    }
    // Detailed mode
    return (React.createElement(Box, { flexDirection: "column", borderStyle: "single", borderColor: colors.border, paddingX: 1 },
        React.createElement(Box, { justifyContent: "space-between" },
            React.createElement(Box, null,
                React.createElement(Text, { bold: true, color: colors.primary }, "\uD83D\uDCCA Session Status"),
                sessionStartTime && (React.createElement(Text, { dimColor: true },
                    " \u2022 ",
                    formatDuration(sessionDuration)))),
            React.createElement(Box, null,
                React.createElement(Text, { color: metrics.modeColor },
                    metrics.modeIcon,
                    " Mode: ",
                    mode.toUpperCase(),
                    " "),
                React.createElement(Text, { color: yolo ? colors.error : colors.success },
                    "[",
                    yolo ? 'YOLO' : 'SAFE',
                    "]"))),
        React.createElement(Box, { marginTop: 1 },
            React.createElement(Box, { width: 15 },
                React.createElement(Text, { color: colors.textMuted }, "Tokens:")),
            React.createElement(Box, { width: 12 }, renderProgressBar(metrics.tokenProgress, 10, metrics.tokenColor)),
            React.createElement(Text, { color: metrics.tokenColor },
                " ",
                formatTokenCount(tokenCount)),
            React.createElement(Text, { dimColor: true },
                "/",
                formatTokenCount(maxTokens)),
            React.createElement(Text, { dimColor: true },
                " (",
                metrics.tokenProgress.toFixed(0),
                "%)")),
        cost > 0 && (React.createElement(Box, null,
            React.createElement(Box, { width: 15 },
                React.createElement(Text, { color: colors.textMuted }, "Cost:")),
            React.createElement(Box, { width: 12 }, renderProgressBar(metrics.costProgress, 10, metrics.costColor)),
            React.createElement(Text, { color: metrics.costColor },
                " ",
                formatCost(cost)),
            React.createElement(Text, { dimColor: true },
                "/",
                formatCost(budget)),
            React.createElement(Text, { dimColor: true },
                " (",
                metrics.costProgress.toFixed(0),
                "%)"))),
        showDetails && (React.createElement(React.Fragment, null,
            React.createElement(Box, null,
                React.createElement(Box, { width: 15 },
                    React.createElement(Text, { color: colors.textMuted }, "Model:")),
                React.createElement(Text, null, modelName)),
            processingTime > 0 && (React.createElement(React.Fragment, null,
                React.createElement(Box, null,
                    React.createElement(Box, { width: 15 },
                        React.createElement(Text, { color: colors.textMuted }, "Speed:")),
                    React.createElement(Text, { color: colors.success }, metrics.tokensPerSec),
                    React.createElement(Text, { dimColor: true }, " tokens/sec")),
                React.createElement(Box, null,
                    React.createElement(Box, { width: 15 },
                        React.createElement(Text, { color: colors.textMuted }, "Latency:")),
                    React.createElement(Text, null, processingTime),
                    React.createElement(Text, { dimColor: true }, "s")))),
            showLatencyStats && latencyStats && latencyStats.totalOperations > 0 && (React.createElement(React.Fragment, null,
                React.createElement(Box, { marginTop: 1 },
                    React.createElement(Text, { bold: true, color: colors.info }, "\u23F1 Latency Stats")),
                React.createElement(Box, null,
                    React.createElement(Box, { width: 15 },
                        React.createElement(Text, { color: colors.textMuted }, "Avg:")),
                    React.createElement(Text, { color: latencyStats.avgDuration <= LATENCY_THRESHOLDS.FAST ? colors.success : latencyStats.avgDuration <= LATENCY_THRESHOLDS.ACCEPTABLE ? colors.warning : colors.error },
                        Math.round(latencyStats.avgDuration),
                        "ms"),
                    React.createElement(Text, { dimColor: true },
                        " (P95: ",
                        Math.round(latencyStats.p95),
                        "ms)")),
                React.createElement(Box, null,
                    React.createElement(Box, { width: 15 },
                        React.createElement(Text, { color: colors.textMuted }, "Target Met:")),
                    React.createElement(Text, { color: latencyStats.metTarget >= 80 ? colors.success : latencyStats.metTarget >= 50 ? colors.warning : colors.error },
                        latencyStats.metTarget,
                        "%"),
                    React.createElement(Text, { dimColor: true },
                        " (",
                        latencyStats.totalOperations,
                        " ops)")),
                latencyStats.avgFirstToken > 0 && (React.createElement(Box, null,
                    React.createElement(Box, { width: 15 },
                        React.createElement(Text, { color: colors.textMuted }, "First Token:")),
                    React.createElement(Text, { color: latencyStats.avgFirstToken <= LATENCY_THRESHOLDS.FAST ? colors.success : colors.warning },
                        Math.round(latencyStats.avgFirstToken),
                        "ms"))))))),
        metrics.costProgress > 80 && (React.createElement(Box, { marginTop: 1 },
            React.createElement(Text, { color: colors.warning }, "\u26A0 Approaching budget limit"))),
        metrics.tokenProgress > 80 && (React.createElement(Box, null,
            React.createElement(Text, { color: colors.warning }, "\u26A0 High token usage")))));
}
/**
 * Mini Status Bar - For inline display in chat interface
 */
export function MiniStatusBar({ tokenCount, cost, modelName, mode = 'code', yolo = false, }) {
    const { colors } = useTheme();
    return (React.createElement(Box, null,
        mode && (React.createElement(Text, { color: mode === 'plan' ? colors.info : colors.primary }, mode === 'plan' ? '📋' : mode === 'ask' ? '❓' : '💻')),
        yolo && React.createElement(Text, { color: colors.error }, " \uD83D\uDD25"),
        React.createElement(Text, { dimColor: true }, " \u2022 "),
        modelName && (React.createElement(React.Fragment, null,
            React.createElement(Text, { color: colors.accent },
                "\u224B ",
                modelName),
            React.createElement(Text, { dimColor: true }, " \u2022 "))),
        React.createElement(Text, { color: colors.info },
            "\u2191 ",
            formatTokenCount(tokenCount)),
        cost !== undefined && cost > 0 && (React.createElement(React.Fragment, null,
            React.createElement(Text, { dimColor: true }, " \u2022 "),
            React.createElement(Text, { color: colors.success }, formatCost(cost))))));
}
export default StatusBar;
//# sourceMappingURL=StatusBar.js.map