import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useCallback, useMemo, useReducer, useState } from 'react';
import { Box, Text } from 'ink';
import { theme } from '../semantic-colors.js';
import { useSettingsStore } from '../contexts/SettingsContext.js';
import { useUIState } from '../contexts/UIStateContext.js';
import { useKeypress } from '../hooks/useKeypress.js';
import { Command } from '../key/keyMatchers.js';
import { FooterRow } from './Footer.js';
import { ALL_ITEMS, resolveFooterState } from '../../config/footerItems.js';
import { SettingScope } from '../../config/settings.js';
import { BaseSelectionList } from './shared/BaseSelectionList.js';
import { DialogFooter } from './shared/DialogFooter.js';
import { useKeyMatchers } from '../hooks/useKeyMatchers.js';
function footerConfigReducer(state, action) {
    switch (action.type) {
        case 'MOVE_ITEM': {
            const currentIndex = state.orderedIds.indexOf(action.id);
            const newIndex = currentIndex + action.direction;
            if (currentIndex === -1 ||
                newIndex < 0 ||
                newIndex >= state.orderedIds.length) {
                return state;
            }
            const newOrderedIds = [...state.orderedIds];
            [newOrderedIds[currentIndex], newOrderedIds[newIndex]] = [
                newOrderedIds[newIndex],
                newOrderedIds[currentIndex],
            ];
            return { ...state, orderedIds: newOrderedIds };
        }
        case 'TOGGLE_ITEM': {
            const nextSelected = new Set(state.selectedIds);
            if (nextSelected.has(action.id)) {
                nextSelected.delete(action.id);
            }
            else {
                nextSelected.add(action.id);
            }
            return { ...state, selectedIds: nextSelected };
        }
        case 'SET_STATE':
            return { ...state, ...action.payload };
        default:
            return state;
    }
}
export const FooterConfigDialog = ({ onClose, }) => {
    const keyMatchers = useKeyMatchers();
    const { settings, setSetting } = useSettingsStore();
    const { constrainHeight, terminalHeight, staticExtraHeight } = useUIState();
    const [state, dispatch] = useReducer(footerConfigReducer, undefined, () => resolveFooterState(settings.merged));
    const { orderedIds, selectedIds } = state;
    const [focusKey, setFocusKey] = useState(orderedIds[0]);
    const listItems = useMemo(() => {
        const items = orderedIds
            .map((id) => {
            const item = ALL_ITEMS.find((i) => i.id === id);
            if (!item)
                return null;
            return {
                key: id,
                value: {
                    key: id,
                    id,
                    label: item.id,
                    description: item.description,
                    type: 'config',
                },
            };
        })
            .filter((i) => i !== null);
        items.push({
            key: 'show-labels',
            value: {
                key: 'show-labels',
                id: 'show-labels',
                label: 'Show footer labels',
                type: 'labels-toggle',
            },
        });
        items.push({
            key: 'reset',
            value: {
                key: 'reset',
                id: 'reset',
                label: 'Reset to default footer',
                type: 'reset',
            },
        });
        return items;
    }, [orderedIds]);
    const handleSaveAndClose = useCallback(() => {
        const finalItems = orderedIds.filter((id) => selectedIds.has(id));
        const currentSetting = settings.merged.ui?.footer?.items;
        if (JSON.stringify(finalItems) !== JSON.stringify(currentSetting)) {
            setSetting(SettingScope.User, 'ui.footer.items', finalItems);
        }
        onClose?.();
    }, [
        orderedIds,
        selectedIds,
        setSetting,
        settings.merged.ui?.footer?.items,
        onClose,
    ]);
    const handleResetToDefaults = useCallback(() => {
        setSetting(SettingScope.User, 'ui.footer.items', undefined);
        const newState = resolveFooterState(settings.merged);
        dispatch({ type: 'SET_STATE', payload: newState });
        setFocusKey(newState.orderedIds[0]);
    }, [setSetting, settings.merged]);
    const handleToggleLabels = useCallback(() => {
        const current = settings.merged.ui.footer.showLabels !== false;
        setSetting(SettingScope.User, 'ui.footer.showLabels', !current);
    }, [setSetting, settings.merged.ui.footer.showLabels]);
    const handleSelect = useCallback((item) => {
        if (item.type === 'config') {
            dispatch({ type: 'TOGGLE_ITEM', id: item.id });
        }
        else if (item.type === 'labels-toggle') {
            handleToggleLabels();
        }
        else if (item.type === 'reset') {
            handleResetToDefaults();
        }
    }, [handleResetToDefaults, handleToggleLabels]);
    const handleHighlight = useCallback((item) => {
        setFocusKey(item.key);
    }, []);
    useKeypress((key) => {
        if (keyMatchers[Command.ESCAPE](key)) {
            handleSaveAndClose();
            return true;
        }
        if (keyMatchers[Command.MOVE_LEFT](key)) {
            if (focusKey && orderedIds.includes(focusKey)) {
                dispatch({ type: 'MOVE_ITEM', id: focusKey, direction: -1 });
                return true;
            }
        }
        if (keyMatchers[Command.MOVE_RIGHT](key)) {
            if (focusKey && orderedIds.includes(focusKey)) {
                dispatch({ type: 'MOVE_ITEM', id: focusKey, direction: 1 });
                return true;
            }
        }
        return false;
    }, { isActive: true, priority: true });
    const showLabels = settings.merged.ui.footer.showLabels !== false;
    // Preview logic
    const previewContent = useMemo(() => {
        if (focusKey === 'reset') {
            return (_jsx(Text, { color: theme.ui.comment, italic: true, children: "Default footer (uses legacy settings)" }));
        }
        const itemsToPreview = orderedIds.filter((id) => selectedIds.has(id));
        if (itemsToPreview.length === 0)
            return null;
        const itemColor = showLabels ? theme.text.primary : theme.ui.comment;
        const getColor = (id, defaultColor) => defaultColor || itemColor;
        // Mock data for preview (headers come from ALL_ITEMS)
        const mockData = {
            workspace: (_jsx(Text, { color: getColor('workspace', itemColor), children: "~/project/path" })),
            'git-branch': _jsx(Text, { color: getColor('git-branch', itemColor), children: "main" }),
            sandbox: _jsx(Text, { color: getColor('sandbox', 'green'), children: "docker" }),
            'model-name': (_jsx(Text, { color: getColor('model-name', itemColor), children: "gemini-2.5-pro" })),
            'context-used': (_jsx(Text, { color: getColor('context-used', itemColor), children: "85% used" })),
            quota: _jsx(Text, { color: getColor('quota', itemColor), children: "97%" }),
            'memory-usage': (_jsx(Text, { color: getColor('memory-usage', itemColor), children: "260 MB" })),
            'session-id': (_jsx(Text, { color: getColor('session-id', itemColor), children: "769992f9" })),
            'code-changes': (_jsxs(Box, { flexDirection: "row", children: [_jsx(Text, { color: getColor('code-changes', theme.status.success), children: "+12" }), _jsx(Text, { color: getColor('code-changes'), children: " " }), _jsx(Text, { color: getColor('code-changes', theme.status.error), children: "-4" })] })),
            'token-count': (_jsx(Text, { color: getColor('token-count', itemColor), children: "1.5k tokens" })),
        };
        const rowItems = itemsToPreview
            .filter((id) => mockData[id])
            .map((id) => ({
            key: id,
            header: ALL_ITEMS.find((i) => i.id === id)?.header ?? id,
            element: mockData[id],
            flexGrow: 0,
            isFocused: id === focusKey,
        }));
        return (_jsx(Box, { overflow: "hidden", flexWrap: "nowrap", width: "100%", children: _jsx(FooterRow, { items: rowItems, showLabels: showLabels }) }));
    }, [orderedIds, selectedIds, focusKey, showLabels]);
    const availableTerminalHeight = constrainHeight
        ? terminalHeight - staticExtraHeight
        : Number.MAX_SAFE_INTEGER;
    const BORDER_HEIGHT = 2; // Outer round border
    const STATIC_ELEMENTS = 13; // Text, margins, preview box, dialog footer
    // Default padding adds 2 lines (top and bottom)
    let includePadding = true;
    if (availableTerminalHeight < BORDER_HEIGHT + 2 + STATIC_ELEMENTS + 6) {
        includePadding = false;
    }
    const effectivePaddingY = includePadding ? 2 : 0;
    const availableListSpace = Math.max(0, availableTerminalHeight -
        BORDER_HEIGHT -
        effectivePaddingY -
        STATIC_ELEMENTS);
    const maxItemsToShow = Math.max(1, Math.min(listItems.length, Math.floor(availableListSpace / 2)));
    return (_jsxs(Box, { flexDirection: "column", borderStyle: "round", borderColor: theme.border.default, paddingX: 2, paddingY: includePadding ? 1 : 0, width: "100%", children: [_jsxs(Text, { bold: true, children: ["Configure Footer", '\n'] }), _jsx(Text, { color: theme.text.secondary, children: "Select which items to display in the footer." }), _jsx(Box, { flexDirection: "column", marginTop: 1, flexGrow: 1, children: _jsx(BaseSelectionList, { items: listItems, onSelect: handleSelect, onHighlight: handleHighlight, focusKey: focusKey, showNumbers: false, maxItemsToShow: maxItemsToShow, showScrollArrows: true, selectedIndicator: ">", renderItem: (item, { isSelected, titleColor }) => {
                        const configItem = item.value;
                        const isChecked = configItem.type === 'config'
                            ? selectedIds.has(configItem.id)
                            : configItem.type === 'labels-toggle'
                                ? showLabels
                                : false;
                        return (_jsxs(Box, { flexDirection: "column", minHeight: 2, children: [_jsxs(Box, { flexDirection: "row", children: [configItem.type !== 'reset' && (_jsxs(Text, { color: isChecked ? theme.status.success : theme.text.secondary, children: ["[", isChecked ? '✓' : ' ', "]"] })), _jsxs(Text, { color: configItem.type === 'reset' && isSelected
                                                ? theme.status.warning
                                                : titleColor, children: [configItem.type !== 'reset' ? ' ' : '', configItem.label] })] }), configItem.description && (_jsxs(Text, { color: theme.text.secondary, wrap: "wrap", children: [' ', configItem.description] }))] }));
                    } }) }), _jsx(DialogFooter, { primaryAction: "Enter to select", navigationActions: "\u2191/\u2193 to navigate \u00B7 \u2190/\u2192 to reorder", cancelAction: "Esc to close" }), _jsxs(Box, { marginTop: 1, borderStyle: "single", borderColor: theme.border.default, paddingX: 1, flexDirection: "column", children: [_jsx(Text, { bold: true, children: "Preview:" }), _jsx(Box, { flexDirection: "row", width: "100%", children: previewContent })] })] }));
};
//# sourceMappingURL=FooterConfigDialog.js.map