import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
/**
 * @license
 * Copyright 2025 Vybestack LLC
 * SPDX-License-Identifier: Apache-2.0
 */
import { useState, useMemo, useEffect } from 'react';
import { Box, Text } from 'ink';
import { SemanticColors } from '../colors.js';
import { useResponsive } from '../hooks/useResponsive.js';
import { useTerminalSize } from '../hooks/useTerminalSize.js';
import { useKeypress } from '../hooks/useKeypress.js';
const formatTimestamp = (timestamp, isNarrow) => {
    const date = new Date(timestamp);
    if (isNarrow) {
        // Short format for narrow screens: HH:MM
        return date.toLocaleTimeString('en-US', {
            hour: '2-digit',
            minute: '2-digit',
            hour12: false,
        });
    }
    else {
        // Full format for wider screens
        return date.toLocaleString('en-US', {
            month: 'short',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit',
            hour12: false,
        });
    }
};
const formatContent = (content, maxLength) => {
    // Remove excess whitespace and newlines
    const cleaned = content.replace(/\s+/g, ' ').trim();
    if (cleaned.length <= maxLength) {
        return cleaned;
    }
    return cleaned.substring(0, maxLength - 3) + '...';
};
const formatTokenCount = (tokens) => {
    if (!tokens)
        return '';
    const parts = [];
    if (tokens.input)
        parts.push(`in:${tokens.input}`);
    if (tokens.output)
        parts.push(`out:${tokens.output}`);
    return parts.length > 0 ? `[${parts.join(' ')}]` : '';
};
export const LoggingDialog = ({ entries, onClose, }) => {
    const { isNarrow, width } = useResponsive();
    const { rows: height } = useTerminalSize();
    const [selectedIndex, setSelectedIndex] = useState(0);
    const [scrollOffset, setScrollOffset] = useState(0);
    // Calculate dialog dimensions
    const dialogWidth = isNarrow ? width - 4 : Math.min(width - 8, 120);
    const dialogHeight = Math.min(height - 6, 30);
    const contentHeight = dialogHeight - 6; // Account for header, footer, borders
    // Reverse entries to show newest first
    const reversedEntries = useMemo(() => [...entries].reverse(), [entries]);
    // Calculate visible range based on scroll
    const visibleEntries = useMemo(() => {
        const start = scrollOffset;
        const end = Math.min(start + contentHeight, reversedEntries.length);
        return reversedEntries.slice(start, end);
    }, [reversedEntries, scrollOffset, contentHeight]);
    // Adjust scroll when selection moves out of view
    useEffect(() => {
        const relativeIndex = selectedIndex - scrollOffset;
        if (relativeIndex < 0) {
            setScrollOffset(selectedIndex);
        }
        else if (relativeIndex >= contentHeight) {
            setScrollOffset(Math.max(0, selectedIndex - contentHeight + 1));
        }
    }, [selectedIndex, scrollOffset, contentHeight]);
    useKeypress((key) => {
        if (key.name === 'escape' || key.sequence === 'q') {
            return onClose();
        }
        if (reversedEntries.length === 0) {
            return;
        }
        if (key.name === 'up' || key.sequence === 'k') {
            setSelectedIndex((prev) => Math.max(0, prev - 1));
        }
        if (key.name === 'down' || key.sequence === 'j') {
            setSelectedIndex((prev) => Math.min(reversedEntries.length - 1, prev + 1));
        }
        if (key.name === 'pageup') {
            setSelectedIndex((prev) => Math.max(0, prev - Math.floor(contentHeight / 2)));
        }
        if (key.name === 'pagedown') {
            setSelectedIndex((prev) => Math.min(reversedEntries.length - 1, prev + Math.floor(contentHeight / 2)));
        }
        if (key.sequence === 'g') {
            setSelectedIndex(0);
        }
        if (key.sequence === 'G') {
            setSelectedIndex(reversedEntries.length - 1);
        }
    }, { isActive: true });
    const renderEntry = (entry, index, isSelected) => {
        const globalIndex = scrollOffset + index;
        const timestamp = formatTimestamp(entry.timestamp, isNarrow);
        const typeIcon = entry.type === 'request'
            ? '→'
            : entry.type === 'tool_call'
                ? '[TOOL]'
                : '←';
        const typeColor = entry.type === 'request'
            ? SemanticColors.text.accent
            : entry.type === 'tool_call'
                ? SemanticColors.status.warning
                : SemanticColors.status.success;
        // Calculate available width for content
        const metadataWidth = timestamp.length + entry.provider.length + 10; // Icons, spacing
        const contentWidth = dialogWidth - metadataWidth - 4; // Padding
        // Format the main content
        let mainContent = '';
        if (entry.type === 'request' && entry.messages) {
            const lastMessage = entry.messages[entry.messages.length - 1];
            if (lastMessage) {
                mainContent = formatContent(lastMessage.content, contentWidth);
            }
        }
        else if (entry.type === 'response' && entry.response) {
            mainContent = formatContent(entry.response, contentWidth);
        }
        else if (entry.type === 'tool_call') {
            // Format tool call content
            let toolContent = `${entry.tool || 'Unknown tool'}`;
            if (entry.duration) {
                toolContent += ` (${entry.duration}ms)`;
            }
            if (entry.success === false) {
                toolContent += ' FAILED';
            }
            // Add git stats if present
            if (entry.gitStats) {
                const { linesAdded, linesRemoved, filesChanged } = entry.gitStats;
                toolContent += ` [+${linesAdded} -${linesRemoved} in ${filesChanged} files]`;
            }
            mainContent = formatContent(toolContent, contentWidth);
        }
        else if (entry.error) {
            mainContent = `Error: ${entry.error}`;
        }
        const tokens = formatTokenCount(entry.tokens);
        return (_jsxs(Box, { flexDirection: "column", marginBottom: isNarrow ? 0 : 1, children: [_jsxs(Box, { flexDirection: "row", gap: 1, children: [_jsx(Text, { color: isSelected ? SemanticColors.status.warning : undefined, children: isSelected ? '▶' : ' ' }), _jsx(Text, { color: SemanticColors.text.secondary, children: timestamp }), _jsx(Text, { color: typeColor, children: typeIcon }), _jsxs(Text, { color: SemanticColors.text.primary, children: [entry.provider, entry.model && !isNarrow && ` (${entry.model})`] }), tokens && !isNarrow && (_jsx(Text, { color: SemanticColors.text.secondary, children: tokens }))] }), mainContent && (_jsx(Box, { paddingLeft: 2, children: _jsx(Text, { color: entry.error
                            ? SemanticColors.status.error
                            : SemanticColors.text.secondary, wrap: "wrap", children: mainContent }) }))] }, `entry-${globalIndex}`));
    };
    const hasScroll = reversedEntries.length > contentHeight;
    const scrollPercentage = hasScroll
        ? Math.round(((scrollOffset + contentHeight) / reversedEntries.length) * 100)
        : 100;
    return (_jsxs(Box, { flexDirection: "column", width: dialogWidth, borderStyle: "round", borderColor: SemanticColors.border.default, children: [_jsx(Box, { paddingX: 1, paddingY: 0, borderStyle: "round", borderBottom: false, borderLeft: false, borderRight: false, borderTop: false, children: _jsxs(Box, { flexDirection: "row", justifyContent: "space-between", width: "100%", children: [_jsx(Text, { color: SemanticColors.text.primary, bold: true, children: "Conversation Logs" }), _jsxs(Text, { color: SemanticColors.text.secondary, children: [reversedEntries.length, " entries"] })] }) }), _jsx(Box, { paddingX: 1, children: _jsx(Text, { color: SemanticColors.border.default, children: '─'.repeat(dialogWidth - 4) }) }), _jsx(Box, { flexDirection: "column", height: contentHeight, paddingX: 1, overflow: "hidden", children: visibleEntries.length > 0 ? (visibleEntries.map((entry, index) => renderEntry(entry, index, scrollOffset + index === selectedIndex))) : (_jsx(Box, { justifyContent: "center", alignItems: "center", height: "100%", children: _jsx(Text, { color: SemanticColors.text.secondary, children: "No log entries found" }) })) }), _jsx(Box, { paddingX: 1, children: _jsx(Text, { color: SemanticColors.border.default, children: '─'.repeat(dialogWidth - 4) }) }), _jsx(Box, { paddingX: 1, paddingBottom: 0, children: _jsxs(Box, { flexDirection: "row", justifyContent: "space-between", width: "100%", children: [_jsxs(Text, { color: SemanticColors.text.secondary, children: [isNarrow ? '↑↓ Nav' : '↑↓ Navigate', ' ', !isNarrow && 'g/G Top/Bottom ', "ESC Close"] }), hasScroll && (_jsxs(Text, { color: SemanticColors.text.secondary, children: [scrollPercentage, "%"] }))] }) })] }));
};
//# sourceMappingURL=LoggingDialog.js.map