import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
/**
 * SessionBrowserDialog - Interactive session browser component
 *
 * @plan PLAN-20260214-SESSIONBROWSER.P15
 * @plan PLAN-20260214-SESSIONBROWSER.P17
 * @requirement REQ-SB-012, REQ-RW-001, REQ-RN-001
 * @pseudocode session-browser-dialog.md
 */
import { Box, Text } from 'ink';
import { SemanticColors } from '../colors.js';
import { useResponsive } from '../hooks/useResponsive.js';
import { useKeypress } from '../hooks/useKeypress.js';
import { useSessionBrowser } from '../hooks/useSessionBrowser.js';
import { formatRelativeTime } from '../../utils/formatRelativeTime.js';
import { truncateEnd } from '../utils/responsive.js';
/**
 * Format file size in human-readable format
 */
function formatFileSize(bytes) {
    if (bytes < 1024) {
        return `${bytes}B`;
    }
    if (bytes < 1024 * 1024) {
        return `${(bytes / 1024).toFixed(1)}KB`;
    }
    return `${(bytes / (1024 * 1024)).toFixed(1)}MB`;
}
/**
 * Interactive session browser dialog for selecting and resuming sessions
 * @plan PLAN-20260214-SESSIONBROWSER.P15
 */
export function SessionBrowserDialog(props) {
    const { chatsDir, projectHash, currentSessionId, hasActiveConversation, onSelect, onClose, } = props;
    const { isNarrow, width } = useResponsive();
    const state = useSessionBrowser({
        chatsDir,
        projectHash,
        currentSessionId,
        onSelect,
        onClose,
        hasActiveConversation,
    });
    // Register keypress handler
    useKeypress((key) => {
        state.handleKeypress(key.sequence ?? '', key);
    }, { isActive: true });
    // Loading state
    if (state.isLoading) {
        if (isNarrow) {
            return (_jsxs(Box, { flexDirection: "column", padding: 1, children: [_jsx(Text, { bold: true, color: SemanticColors.text.primary, children: "Sessions" }), _jsx(Text, { color: SemanticColors.text.secondary, children: "Loading sessions..." })] }));
        }
        return (_jsxs(Box, { borderStyle: "round", borderColor: SemanticColors.border.default, flexDirection: "column", padding: 1, children: [_jsx(Text, { bold: true, color: SemanticColors.text.primary, children: "Session Browser" }), _jsx(Text, { color: SemanticColors.text.secondary, children: "Loading sessions..." })] }));
    }
    // Empty state (no sessions)
    if (state.sessions.length === 0 && state.searchTerm === '') {
        if (isNarrow) {
            return (_jsxs(Box, { flexDirection: "column", padding: 1, children: [_jsx(Text, { bold: true, color: SemanticColors.text.primary, children: "Sessions" }), _jsx(Text, { color: SemanticColors.text.primary, children: "No sessions found for this project." }), _jsx(Text, { color: SemanticColors.text.secondary, children: "Sessions are created automatically when you start a conversation." }), _jsx(Box, { marginTop: 1, children: _jsx(Text, { color: SemanticColors.text.secondary, children: "Press Esc to close" }) })] }));
        }
        return (_jsxs(Box, { borderStyle: "round", borderColor: SemanticColors.border.default, flexDirection: "column", padding: 1, children: [_jsx(Text, { bold: true, color: SemanticColors.text.primary, children: "Session Browser" }), _jsx(Text, { color: SemanticColors.text.primary, children: "No sessions found for this project." }), _jsx(Text, { color: SemanticColors.text.secondary, children: "Sessions are created automatically when you start a conversation." }), _jsx(Box, { marginTop: 1, children: _jsx(Text, { color: SemanticColors.text.secondary, children: "Press Esc to close" }) })] }));
    }
    // Render session preview text based on preview state
    const renderPreview = (session) => {
        switch (session.previewState) {
            case 'loading':
                return (_jsx(Text, { color: SemanticColors.text.secondary, italic: true, children: "Loading..." }));
            case 'none':
                return (_jsx(Text, { color: SemanticColors.text.secondary, italic: true, children: "(no user message)" }));
            case 'error':
                return (_jsx(Text, { color: SemanticColors.text.secondary, italic: true, children: "(preview unavailable)" }));
            case 'loaded':
            default: {
                const previewText = session.firstUserMessage ?? '';
                const maxLen = isNarrow ? 40 : 80;
                const truncated = truncateEnd(previewText.replace(/\n/g, ' '), maxLen);
                return _jsx(Text, { color: SemanticColors.text.secondary, children: truncated });
            }
        }
    };
    // Render a session row
    const renderSessionRow = (session, index, isSelected) => {
        const relTime = formatRelativeTime(session.lastModified, {
            mode: isNarrow ? 'short' : 'long',
        });
        if (isNarrow) {
            // Narrow mode: compact layout, no index, show session ID suffix for selected
            return (_jsxs(Box, { flexDirection: "column", children: [_jsxs(Box, { children: [_jsx(Text, { color: isSelected
                                    ? SemanticColors.text.accent
                                    : SemanticColors.text.primary, children: isSelected ? '● ' : '○ ' }), _jsx(Text, { color: isSelected
                                    ? SemanticColors.text.accent
                                    : SemanticColors.text.primary, children: session.provider ?? 'unknown' }), _jsx(Text, { color: SemanticColors.text.secondary, children: " \u00B7 " }), _jsx(Text, { color: SemanticColors.text.secondary, children: relTime }), session.isLocked ? (_jsx(Text, { color: SemanticColors.status.warning, children: " (in use)" })) : null, isSelected ? (_jsxs(Text, { color: SemanticColors.text.secondary, children: [' ', "[", session.sessionId.slice(0, 8), "]"] })) : null] }), _jsx(Box, { marginLeft: 2, children: renderPreview(session) })] }, session.sessionId));
        }
        // Wide mode: full layout with index and file size
        const oneBasedIndex = state.page * 20 + index + 1;
        return (_jsxs(Box, { flexDirection: "column", children: [_jsxs(Box, { children: [_jsx(Text, { color: isSelected
                                ? SemanticColors.text.accent
                                : SemanticColors.text.primary, children: isSelected ? '● ' : '○ ' }), _jsxs(Text, { color: SemanticColors.text.secondary, children: ["#", oneBasedIndex, " "] }), _jsx(Text, { color: isSelected
                                ? SemanticColors.text.accent
                                : SemanticColors.text.primary, children: session.provider ?? 'unknown' }), _jsx(Text, { color: SemanticColors.text.secondary, children: "/" }), _jsx(Text, { color: SemanticColors.text.primary, children: truncateEnd(session.model ?? 'unknown', 30) }), _jsx(Text, { color: SemanticColors.text.secondary, children: " \u00B7 " }), _jsx(Text, { color: SemanticColors.text.secondary, children: relTime }), _jsx(Text, { color: SemanticColors.text.secondary, children: " \u00B7 " }), _jsx(Text, { color: SemanticColors.text.secondary, children: formatFileSize(session.fileSize ?? 0) }), session.isLocked ? (_jsx(Text, { color: SemanticColors.status.warning, children: " (in use)" })) : null] }), _jsx(Box, { marginLeft: 2, children: renderPreview(session) })] }, session.sessionId));
    };
    // Render search bar
    const renderSearchBar = () => {
        const matchCount = state.filteredSessions.length;
        const hasSearch = state.searchTerm.length > 0;
        if (isNarrow) {
            return (_jsxs(Box, { marginY: 1, children: [_jsxs(Text, { color: state.isSearching
                            ? SemanticColors.text.primary
                            : SemanticColors.text.secondary, children: ["Search:", ' '] }), state.isSearching ? (_jsx(Text, { color: SemanticColors.text.accent, children: "\u258C" })) : null, _jsx(Text, { color: SemanticColors.text.primary, children: state.searchTerm }), hasSearch ? (_jsxs(Text, { color: SemanticColors.text.secondary, children: [' ', "(", matchCount, " found)"] })) : null] }));
        }
        return (_jsxs(Box, { marginY: 1, children: [_jsxs(Text, { color: state.isSearching
                        ? SemanticColors.text.primary
                        : SemanticColors.text.secondary, children: ["Search:", ' '] }), state.isSearching ? (_jsx(Text, { color: SemanticColors.text.accent, children: "\u258C" })) : null, _jsx(Text, { color: SemanticColors.text.primary, children: state.searchTerm }), _jsxs(Text, { color: SemanticColors.text.secondary, children: [' ', "(", matchCount, " ", matchCount === 1 ? 'session' : 'sessions', " found)", state.isSearching ? ' (Tab to navigate)' : ''] })] }));
    };
    // Render sort bar (wide mode only)
    const renderSortBar = () => {
        if (isNarrow)
            return null;
        return (_jsxs(Box, { marginBottom: 1, children: [_jsx(Text, { color: SemanticColors.text.secondary, children: "Sort: " }), _jsx(Text, { color: state.sortOrder === 'newest'
                        ? SemanticColors.text.primary
                        : SemanticColors.text.secondary, children: state.sortOrder === 'newest' ? '[newest]' : 'newest' }), _jsx(Text, { color: SemanticColors.text.secondary, children: " " }), _jsx(Text, { color: state.sortOrder === 'oldest'
                        ? SemanticColors.text.primary
                        : SemanticColors.text.secondary, children: state.sortOrder === 'oldest' ? '[oldest]' : 'oldest' }), _jsx(Text, { color: SemanticColors.text.secondary, children: " " }), _jsx(Text, { color: state.sortOrder === 'size'
                        ? SemanticColors.text.primary
                        : SemanticColors.text.secondary, children: state.sortOrder === 'size' ? '[size]' : 'size' }), _jsx(Text, { color: SemanticColors.text.secondary, children: " (press s to cycle)" })] }));
    };
    // Render page indicator
    const renderPageIndicator = () => {
        if (state.totalPages <= 1)
            return null;
        return (_jsx(Box, { marginY: 1, children: _jsxs(Text, { color: SemanticColors.text.secondary, children: ["Page ", state.page + 1, " of ", state.totalPages, " (PgUp/PgDn to navigate)"] }) }));
    };
    // Render selection detail (wide mode only)
    const renderSelectionDetail = () => {
        if (isNarrow || !state.selectedSession)
            return null;
        const session = state.selectedSession;
        const relTime = formatRelativeTime(session.lastModified, { mode: 'long' });
        return (_jsxs(Box, { marginTop: 1, children: [_jsx(Text, { color: SemanticColors.text.secondary, children: "Selected: " }), _jsx(Text, { color: SemanticColors.text.primary, children: session.sessionId }), _jsx(Text, { color: SemanticColors.text.secondary, children: " \u00B7 " }), _jsxs(Text, { color: SemanticColors.text.primary, children: [session.provider, "/", session.model] }), _jsx(Text, { color: SemanticColors.text.secondary, children: " \u00B7 " }), _jsx(Text, { color: SemanticColors.text.secondary, children: relTime })] }));
    };
    // Render controls bar
    const renderControlsBar = () => {
        const hasSessions = state.pageItems.length > 0;
        if (isNarrow) {
            return (_jsx(Box, { marginTop: 1, children: _jsxs(Text, { color: SemanticColors.text.secondary, children: ["Nav:\u2191\u2193 ", hasSessions ? 'Enter ' : '', "s:", state.sortOrder, " Esc"] }) }));
        }
        return (_jsx(Box, { marginTop: 1, children: _jsxs(Text, { color: SemanticColors.text.secondary, children: ["Controls: \u2191\u2193 Navigate", hasSessions ? ' [Enter] Resume [Del] Delete' : '', " [s] Sort [Tab] Toggle Mode [Esc] Close"] }) }));
    };
    // Render error message
    const renderError = () => {
        if (!state.error)
            return null;
        return (_jsx(Box, { marginY: 1, children: _jsx(Text, { color: SemanticColors.status.error, children: state.error }) }));
    };
    // Render skipped notice
    const renderSkippedNotice = () => {
        if (state.skippedCount === 0)
            return null;
        return (_jsx(Box, { marginY: 1, children: _jsxs(Text, { color: SemanticColors.status.warning, children: ["Skipped ", state.skippedCount, " unreadable session(s)."] }) }));
    };
    // Render resuming status
    const renderResumingStatus = () => {
        if (!state.isResuming)
            return null;
        return (_jsx(Box, { marginY: 1, children: _jsx(Text, { color: SemanticColors.text.accent, children: "Resuming..." }) }));
    };
    // Render delete confirmation
    const renderDeleteConfirmation = () => {
        if (state.deleteConfirmIndex === null)
            return null;
        return (_jsx(Box, { marginY: 1, children: _jsx(Text, { color: SemanticColors.status.warning, children: "Delete this session? Press Y to confirm, N or Esc to cancel." }) }));
    };
    // Render conversation confirmation
    const renderConversationConfirmation = () => {
        if (!state.conversationConfirmActive)
            return null;
        return (_jsx(Box, { marginY: 1, children: _jsx(Text, { color: SemanticColors.status.warning, children: "This will replace your current conversation. Continue? Y/N" }) }));
    };
    // Render empty search results
    const renderEmptySearchResults = () => {
        if (state.pageItems.length > 0 || state.searchTerm === '')
            return null;
        return (_jsx(Box, { marginY: 1, children: _jsxs(Text, { color: SemanticColors.text.secondary, children: ["No sessions match \"", state.searchTerm, "\""] }) }));
    };
    // Render session list
    const renderSessionList = () => {
        if (state.pageItems.length === 0) {
            return renderEmptySearchResults();
        }
        return (_jsx(Box, { flexDirection: "column", children: state.pageItems.map((session, index) => renderSessionRow(session, index, index === state.selectedIndex)) }));
    };
    // Main content
    const content = (_jsxs(_Fragment, { children: [_jsx(Text, { bold: true, color: SemanticColors.text.primary, children: isNarrow ? 'Sessions' : 'Session Browser' }), renderSearchBar(), renderSortBar(), renderSkippedNotice(), renderSessionList(), renderPageIndicator(), renderError(), renderResumingStatus(), renderDeleteConfirmation(), renderConversationConfirmation(), renderSelectionDetail(), renderControlsBar()] }));
    // Wrap in box with border (wide mode) or borderless (narrow mode)
    if (isNarrow) {
        return (_jsx(Box, { flexDirection: "column", padding: 1, children: content }));
    }
    return (_jsx(Box, { borderStyle: "round", borderColor: SemanticColors.border.default, flexDirection: "column", padding: 1, width: Math.min(width, 120), children: content }));
}
//# sourceMappingURL=SessionBrowserDialog.js.map