import { jsxs as _jsxs, jsx as _jsx } from "react/jsx-runtime";
import { useState, useEffect } from 'react';
import { Box, Text } from 'ink';
import { theme } from '../semantic-colors.js';
import { SettingScope } from '../../config/settings.js';
import { getScopeMessageForSetting } from '../../utils/dialogScopeUtils.js';
import { ScopeSelector } from './shared/ScopeSelector.js';
import { t } from '../../i18n/index.js';
import { getDialogSettingKeys, setPendingSettingValue, getDisplayValue, saveModifiedSettings, getSettingDefinition, isDefaultValue, requiresRestart, getRestartRequiredFromModified, getDefaultValue, setPendingSettingValueAny, getNestedValue, getEffectiveValue, } from '../../utils/settingsUtils.js';
import { updateOutputLanguageFile } from '../../utils/languageUtils.js';
import { useVimMode } from '../contexts/VimModeContext.js';
import { useCompactMode } from '../contexts/CompactModeContext.js';
import { useUIActions } from '../contexts/UIActionsContext.js';
import { createDebugLogger } from '@hoptrendy/hopcode-core';
import { useKeypress } from '../hooks/useKeypress.js';
import chalk from 'chalk';
import { cpSlice, cpLen, stripUnsafeCharacters } from '../utils/textUtils.js';
import { TOGGLE_TYPES, } from '../../config/settingsSchema.js';
const debugLogger = createDebugLogger('SETTINGS_DIALOG');
const maxItemsToShow = 8;
export function SettingsDialog({ settings, onSelect, onRestartRequest, availableTerminalHeight, config, }) {
    // Get vim mode context to sync vim mode changes
    const { vimEnabled, toggleVimEnabled } = useVimMode();
    // Get compact mode context to sync compact mode changes
    const { compactMode, setCompactMode } = useCompactMode();
    const uiActions = useUIActions();
    // Mode state: 'settings' or 'scope' (view switching like ThemeDialog)
    const [mode, setMode] = useState('settings');
    // Scope selector state (User by default)
    const [selectedScope, setSelectedScope] = useState(SettingScope.User);
    // Active indices
    const [activeSettingIndex, setActiveSettingIndex] = useState(0);
    // Scroll offset for settings
    const [scrollOffset, setScrollOffset] = useState(0);
    // Local pending settings state for the selected scope
    const [pendingSettings, setPendingSettings] = useState(() => 
    // Deep clone to avoid mutation
    structuredClone(settings.forScope(selectedScope).settings));
    // Track which settings have been modified by the user
    const [modifiedSettings, setModifiedSettings] = useState(new Set());
    const [globalPendingChanges, setGlobalPendingChanges] = useState(new Map());
    // Track restart-required settings across scope changes
    const [restartRequiredSettings, setRestartRequiredSettings] = useState(new Set());
    const showRestartPrompt = restartRequiredSettings.size > 0;
    useEffect(() => {
        // Base settings for selected scope
        let updated = structuredClone(settings.forScope(selectedScope).settings);
        // Overlay globally pending (unsaved) changes so user sees their modifications in any scope
        const newModified = new Set();
        for (const [key, value] of globalPendingChanges.entries()) {
            const def = getSettingDefinition(key);
            if (def?.type === 'boolean' && typeof value === 'boolean') {
                updated = setPendingSettingValue(key, value, updated);
            }
            else if ((def?.type === 'number' && typeof value === 'number') ||
                (def?.type === 'string' && typeof value === 'string') ||
                (def?.type === 'enum' &&
                    (typeof value === 'string' || typeof value === 'number'))) {
                updated = setPendingSettingValueAny(key, value, updated);
            }
            newModified.add(key);
        }
        setPendingSettings(updated);
        setModifiedSettings(newModified);
    }, [selectedScope, settings, globalPendingChanges]);
    const generateSettingsItems = () => {
        const settingKeys = getDialogSettingKeys();
        return settingKeys.map((key) => {
            const definition = getSettingDefinition(key);
            return {
                label: definition?.label
                    ? t(definition.label) || definition.label
                    : key,
                value: key,
                type: definition?.type,
                description: definition?.description
                    ? t(definition.description) || definition.description
                    : undefined,
                toggle: () => {
                    if (!TOGGLE_TYPES.has(definition?.type)) {
                        return;
                    }
                    const currentValue = getEffectiveValue(key, pendingSettings, {});
                    let newValue;
                    if (definition?.type === 'boolean') {
                        newValue = !currentValue;
                        setPendingSettings((prev) => setPendingSettingValue(key, newValue, prev));
                    }
                    else if (definition?.type === 'enum' && definition.options) {
                        const options = definition.options;
                        const currentIndex = options?.findIndex((opt) => opt.value === currentValue);
                        if (currentIndex !== -1 && currentIndex < options.length - 1) {
                            newValue = options[currentIndex + 1].value;
                        }
                        else {
                            newValue = options[0].value; // loop back to start.
                        }
                        setPendingSettings((prev) => setPendingSettingValueAny(key, newValue, prev));
                    }
                    if (!requiresRestart(key)) {
                        const immediateSettings = new Set([key]);
                        const immediateSettingsObject = setPendingSettingValueAny(key, newValue, {});
                        debugLogger.debug(`[DEBUG SettingsDialog] Saving ${key} immediately with value:`, newValue);
                        saveModifiedSettings(immediateSettings, immediateSettingsObject, settings, selectedScope);
                        // Special handling for vim mode to sync with VimModeContext
                        if (key === 'general.vimMode' && newValue !== vimEnabled) {
                            // Call toggleVimEnabled to sync the VimModeContext local state
                            toggleVimEnabled().catch((error) => {
                                debugLogger.error('Failed to toggle vim mode:', error);
                            });
                        }
                        // Special handling for compact mode to sync with CompactModeContext
                        // and refresh static content so already-rendered history updates.
                        if (key === 'ui.compactMode' && newValue !== compactMode) {
                            setCompactMode?.(newValue);
                            uiActions.refreshStatic();
                        }
                        // Special handling for approval mode to apply to current session
                        if (key === 'tools.approvalMode' &&
                            settings.merged.tools?.approvalMode) {
                            try {
                                config?.setApprovalMode(settings.merged.tools.approvalMode);
                            }
                            catch (error) {
                                debugLogger.error('Failed to apply approval mode to current session:', error);
                            }
                        }
                        // Remove from modifiedSettings since it's now saved
                        setModifiedSettings((prev) => {
                            const updated = new Set(prev);
                            updated.delete(key);
                            return updated;
                        });
                        // Also remove from restart-required settings if it was there
                        setRestartRequiredSettings((prev) => {
                            const updated = new Set(prev);
                            updated.delete(key);
                            return updated;
                        });
                        // Remove from global pending changes if present
                        setGlobalPendingChanges((prev) => {
                            if (!prev.has(key))
                                return prev;
                            const next = new Map(prev);
                            next.delete(key);
                            return next;
                        });
                        // Refresh pending settings from the saved state
                        setPendingSettings(structuredClone(settings.forScope(selectedScope).settings));
                    }
                    else {
                        // For restart-required settings, save immediately but show restart prompt
                        const immediateSettings = new Set([key]);
                        const immediateSettingsObject = setPendingSettingValueAny(key, newValue, {});
                        saveModifiedSettings(immediateSettings, immediateSettingsObject, settings, selectedScope);
                        // Mark as needing restart and show prompt
                        setRestartRequiredSettings((prev) => new Set(prev).add(key));
                    }
                },
            };
        });
    };
    const items = generateSettingsItems();
    // Generic edit state
    const [editingKey, setEditingKey] = useState(null);
    const [editBuffer, setEditBuffer] = useState('');
    const [editCursorPos, setEditCursorPos] = useState(0); // Cursor position within edit buffer
    const [cursorVisible, setCursorVisible] = useState(true);
    useEffect(() => {
        if (!editingKey) {
            setCursorVisible(true);
            return;
        }
        const id = setInterval(() => setCursorVisible((v) => !v), 500);
        return () => clearInterval(id);
    }, [editingKey]);
    const startEditing = (key, initial) => {
        setEditingKey(key);
        const initialValue = initial ?? '';
        setEditBuffer(initialValue);
        setEditCursorPos(cpLen(initialValue)); // Position cursor at end of initial value
    };
    const commitEdit = (key) => {
        const definition = getSettingDefinition(key);
        const type = definition?.type;
        if (editBuffer.trim() === '' && type === 'number') {
            // Nothing entered for a number; cancel edit
            setEditingKey(null);
            setEditBuffer('');
            setEditCursorPos(0);
            return;
        }
        let parsed;
        if (type === 'number') {
            const numParsed = Number(editBuffer.trim());
            if (Number.isNaN(numParsed)) {
                // Invalid number; cancel edit
                setEditingKey(null);
                setEditBuffer('');
                setEditCursorPos(0);
                return;
            }
            parsed = numParsed;
        }
        else {
            // For strings, use the buffer as is.
            // Special handling for outputLanguage: empty input means 'auto'
            if (key === 'general.outputLanguage') {
                const trimmed = editBuffer.trim();
                parsed = trimmed === '' ? 'auto' : trimmed;
            }
            else {
                parsed = editBuffer;
            }
        }
        // Update pending
        setPendingSettings((prev) => parsed === undefined
            ? setPendingSettingValueAny(key, undefined, prev)
            : setPendingSettingValueAny(key, parsed, prev));
        if (!requiresRestart(key)) {
            const immediateSettings = new Set([key]);
            const immediateSettingsObject = parsed === undefined
                ? {}
                : setPendingSettingValueAny(key, parsed, {});
            saveModifiedSettings(immediateSettings, immediateSettingsObject, settings, selectedScope);
            // Remove from modified sets if present
            setModifiedSettings((prev) => {
                const updated = new Set(prev);
                updated.delete(key);
                return updated;
            });
            setRestartRequiredSettings((prev) => {
                const updated = new Set(prev);
                updated.delete(key);
                return updated;
            });
            // Remove from global pending since it's immediately saved
            setGlobalPendingChanges((prev) => {
                if (!prev.has(key))
                    return prev;
                const next = new Map(prev);
                next.delete(key);
                return next;
            });
        }
        else {
            // For restart-required settings, save immediately but show restart prompt
            const immediateSettings = new Set([key]);
            const immediateSettingsObject = parsed === undefined
                ? {}
                : setPendingSettingValueAny(key, parsed, {});
            saveModifiedSettings(immediateSettings, immediateSettingsObject, settings, selectedScope);
            // Update output language rule file immediately (no restart needed for LLM effect)
            if (key === 'general.outputLanguage' && typeof parsed === 'string') {
                updateOutputLanguageFile(parsed);
            }
            // Mark as needing restart and show prompt
            setRestartRequiredSettings((prev) => new Set(prev).add(key));
        }
        setEditingKey(null);
        setEditBuffer('');
        setEditCursorPos(0);
    };
    const handleScopeHighlight = (scope) => {
        setSelectedScope(scope);
    };
    const handleScopeSelect = (scope) => {
        handleScopeHighlight(scope);
        setMode('settings');
    };
    // Get the description for the currently active setting
    const activeDescription = mode === 'settings' && items[activeSettingIndex]?.description
        ? items[activeSettingIndex].description
        : undefined;
    // Height constraint calculations similar to ThemeDialog
    const DIALOG_PADDING = 2;
    const SETTINGS_TITLE_HEIGHT = 2; // "Settings" title + spacing
    const SCROLL_ARROWS_HEIGHT = 2; // Up and down arrows
    const DESCRIPTION_HEIGHT = 2; // Description line + margin
    const BOTTOM_HELP_TEXT_HEIGHT = 1; // Help text
    const RESTART_PROMPT_HEIGHT = showRestartPrompt ? 1 : 0;
    let currentAvailableTerminalHeight = availableTerminalHeight ?? Number.MAX_SAFE_INTEGER;
    currentAvailableTerminalHeight -= 2; // Top and bottom borders
    // Calculate fixed height (scope selection is now in a separate view, not included here)
    const totalFixedHeight = DIALOG_PADDING +
        SETTINGS_TITLE_HEIGHT +
        SCROLL_ARROWS_HEIGHT +
        DESCRIPTION_HEIGHT +
        BOTTOM_HELP_TEXT_HEIGHT +
        RESTART_PROMPT_HEIGHT;
    // Calculate how much space we have for settings
    const availableHeightForSettings = Math.max(1, currentAvailableTerminalHeight - totalFixedHeight);
    // Each setting item takes 1 line
    const maxVisibleItems = Math.max(1, availableHeightForSettings);
    // Use the calculated maxVisibleItems or fall back to the original maxItemsToShow
    const effectiveMaxItemsToShow = availableTerminalHeight
        ? Math.min(maxVisibleItems, items.length)
        : maxItemsToShow;
    // Scroll logic for settings
    const visibleItems = items.slice(scrollOffset, scrollOffset + effectiveMaxItemsToShow);
    // Show arrows if there are more items than can be displayed
    const showScrollUp = items.length > effectiveMaxItemsToShow;
    const showScrollDown = items.length > effectiveMaxItemsToShow;
    useKeypress((key) => {
        const { name, ctrl } = key;
        if (name === 'tab') {
            setMode((prev) => (prev === 'settings' ? 'scope' : 'settings'));
        }
        if (mode === 'settings') {
            // If editing, capture input and control keys
            if (editingKey) {
                const definition = getSettingDefinition(editingKey);
                const type = definition?.type;
                if (key.paste && key.sequence) {
                    let pasted = key.sequence;
                    if (type === 'number') {
                        pasted = key.sequence.replace(/[^0-9\-+.]/g, '');
                    }
                    if (pasted) {
                        setEditBuffer((b) => {
                            const before = cpSlice(b, 0, editCursorPos);
                            const after = cpSlice(b, editCursorPos);
                            return before + pasted + after;
                        });
                        setEditCursorPos((pos) => pos + cpLen(pasted));
                    }
                    return;
                }
                if (name === 'backspace' || name === 'delete') {
                    if (name === 'backspace' && editCursorPos > 0) {
                        setEditBuffer((b) => {
                            const before = cpSlice(b, 0, editCursorPos - 1);
                            const after = cpSlice(b, editCursorPos);
                            return before + after;
                        });
                        setEditCursorPos((pos) => pos - 1);
                    }
                    else if (name === 'delete' && editCursorPos < cpLen(editBuffer)) {
                        setEditBuffer((b) => {
                            const before = cpSlice(b, 0, editCursorPos);
                            const after = cpSlice(b, editCursorPos + 1);
                            return before + after;
                        });
                        // Cursor position stays the same for delete
                    }
                    return;
                }
                if (name === 'escape') {
                    commitEdit(editingKey);
                    return;
                }
                if (name === 'return') {
                    commitEdit(editingKey);
                    return;
                }
                let ch = key.sequence;
                let isValidChar = false;
                if (type === 'number') {
                    // Allow digits, minus, plus, and dot.
                    isValidChar = /[0-9\-+.]/.test(ch);
                }
                else {
                    ch = stripUnsafeCharacters(ch);
                    // For strings, allow any single character that isn't a control
                    // sequence.
                    isValidChar = ch.length === 1;
                }
                if (isValidChar) {
                    setEditBuffer((currentBuffer) => {
                        const beforeCursor = cpSlice(currentBuffer, 0, editCursorPos);
                        const afterCursor = cpSlice(currentBuffer, editCursorPos);
                        return beforeCursor + ch + afterCursor;
                    });
                    setEditCursorPos((pos) => pos + 1);
                    return;
                }
                // Arrow key navigation
                if (name === 'left') {
                    setEditCursorPos((pos) => Math.max(0, pos - 1));
                    return;
                }
                if (name === 'right') {
                    setEditCursorPos((pos) => Math.min(cpLen(editBuffer), pos + 1));
                    return;
                }
                // Home and End keys
                if (name === 'home') {
                    setEditCursorPos(0);
                    return;
                }
                if (name === 'end') {
                    setEditCursorPos(cpLen(editBuffer));
                    return;
                }
                // Block other keys while editing
                return;
            }
            if (name === 'up' || name === 'k') {
                // If editing, commit first
                if (editingKey) {
                    commitEdit(editingKey);
                }
                const newIndex = activeSettingIndex > 0 ? activeSettingIndex - 1 : items.length - 1;
                setActiveSettingIndex(newIndex);
                // Adjust scroll offset for wrap-around
                if (newIndex === items.length - 1) {
                    setScrollOffset(Math.max(0, items.length - effectiveMaxItemsToShow));
                }
                else if (newIndex < scrollOffset) {
                    setScrollOffset(newIndex);
                }
            }
            else if (name === 'down' || name === 'j') {
                // If editing, commit first
                if (editingKey) {
                    commitEdit(editingKey);
                }
                const newIndex = activeSettingIndex < items.length - 1 ? activeSettingIndex + 1 : 0;
                setActiveSettingIndex(newIndex);
                // Adjust scroll offset for wrap-around
                if (newIndex === 0) {
                    setScrollOffset(0);
                }
                else if (newIndex >= scrollOffset + effectiveMaxItemsToShow) {
                    setScrollOffset(newIndex - effectiveMaxItemsToShow + 1);
                }
            }
            else if (name === 'return' || name === 'space') {
                const currentItem = items[activeSettingIndex];
                if (currentItem?.value === 'ui.theme') {
                    if (name === 'return') {
                        onSelect('ui.theme', selectedScope);
                    }
                    return;
                }
                if (currentItem?.value === 'general.preferredEditor') {
                    if (name === 'return') {
                        onSelect('general.preferredEditor', selectedScope);
                    }
                    return;
                }
                if (currentItem?.value === 'fastModel') {
                    if (name === 'return') {
                        onSelect('fastModel', selectedScope);
                    }
                    return;
                }
                if (currentItem?.type === 'number' ||
                    currentItem?.type === 'string') {
                    startEditing(currentItem.value);
                }
                else {
                    currentItem?.toggle();
                }
            }
            else if (name === 'right') {
                // Right arrow opens sub-dialog settings (like a sub-menu)
                const currentItem = items[activeSettingIndex];
                if (currentItem?.value === 'ui.theme' ||
                    currentItem?.value === 'general.preferredEditor' ||
                    currentItem?.value === 'fastModel') {
                    onSelect(currentItem.value, selectedScope);
                }
            }
            else if (/^[0-9]$/.test(key.sequence || '') && !editingKey) {
                const currentItem = items[activeSettingIndex];
                if (currentItem?.type === 'number') {
                    startEditing(currentItem.value, key.sequence);
                }
            }
            else if (ctrl && (name === 'c' || name === 'l')) {
                // Ctrl+C or Ctrl+L: Clear current setting and reset to default
                const currentSetting = items[activeSettingIndex];
                if (currentSetting) {
                    const defaultValue = getDefaultValue(currentSetting.value);
                    const defType = currentSetting.type;
                    if (defType === 'boolean') {
                        const booleanDefaultValue = typeof defaultValue === 'boolean' ? defaultValue : false;
                        setPendingSettings((prev) => setPendingSettingValue(currentSetting.value, booleanDefaultValue, prev));
                    }
                    else if (defType === 'number' ||
                        defType === 'string' ||
                        defType === 'enum') {
                        if (typeof defaultValue === 'number' ||
                            typeof defaultValue === 'string') {
                            setPendingSettings((prev) => setPendingSettingValueAny(currentSetting.value, defaultValue, prev));
                        }
                    }
                    // Remove from modified settings since it's now at default
                    setModifiedSettings((prev) => {
                        const updated = new Set(prev);
                        updated.delete(currentSetting.value);
                        return updated;
                    });
                    // Remove from restart-required settings if it was there
                    setRestartRequiredSettings((prev) => {
                        const updated = new Set(prev);
                        updated.delete(currentSetting.value);
                        return updated;
                    });
                    // If this setting doesn't require restart, save it immediately
                    if (!requiresRestart(currentSetting.value)) {
                        const immediateSettings = new Set([currentSetting.value]);
                        const toSaveValue = currentSetting.type === 'boolean'
                            ? typeof defaultValue === 'boolean'
                                ? defaultValue
                                : false
                            : typeof defaultValue === 'number' ||
                                typeof defaultValue === 'string'
                                ? defaultValue
                                : undefined;
                        const immediateSettingsObject = toSaveValue !== undefined
                            ? setPendingSettingValueAny(currentSetting.value, toSaveValue, {})
                            : {};
                        saveModifiedSettings(immediateSettings, immediateSettingsObject, settings, selectedScope);
                        // Special handling for approval mode to apply to current session
                        if (currentSetting.value === 'tools.approvalMode' &&
                            settings.merged.tools?.approvalMode) {
                            try {
                                config?.setApprovalMode(settings.merged.tools.approvalMode);
                            }
                            catch (error) {
                                debugLogger.error('Failed to apply approval mode to current session:', error);
                            }
                        }
                        // Remove from global pending changes if present
                        setGlobalPendingChanges((prev) => {
                            if (!prev.has(currentSetting.value))
                                return prev;
                            const next = new Map(prev);
                            next.delete(currentSetting.value);
                            return next;
                        });
                    }
                    else {
                        // Track default reset as a pending change if restart required
                        if ((currentSetting.type === 'boolean' &&
                            typeof defaultValue === 'boolean') ||
                            (currentSetting.type === 'number' &&
                                typeof defaultValue === 'number') ||
                            (currentSetting.type === 'string' &&
                                typeof defaultValue === 'string')) {
                            setGlobalPendingChanges((prev) => {
                                const next = new Map(prev);
                                next.set(currentSetting.value, defaultValue);
                                return next;
                            });
                        }
                        setRestartRequiredSettings((prev) => new Set(prev).add(currentSetting.value));
                    }
                }
            }
        }
        if (showRestartPrompt && name === 'r') {
            // Only save settings that require restart (non-restart settings were already saved immediately)
            const restartRequiredSettings = getRestartRequiredFromModified(modifiedSettings);
            const restartRequiredSet = new Set(restartRequiredSettings);
            if (restartRequiredSet.size > 0) {
                saveModifiedSettings(restartRequiredSet, pendingSettings, settings, selectedScope);
                // Remove saved keys from global pending changes
                setGlobalPendingChanges((prev) => {
                    if (prev.size === 0)
                        return prev;
                    const next = new Map(prev);
                    for (const key of restartRequiredSet) {
                        next.delete(key);
                    }
                    return next;
                });
            }
            setRestartRequiredSettings(new Set()); // Clear restart-required settings
            if (onRestartRequest)
                onRestartRequest();
        }
        if (name === 'escape') {
            if (editingKey) {
                commitEdit(editingKey);
            }
            else {
                onSelect(undefined, selectedScope);
            }
        }
    }, { isActive: true });
    return (_jsxs(Box, { borderStyle: "round", borderColor: theme.border.default, flexDirection: "column", padding: 1, width: "100%", children: [mode === 'settings' ? (_jsxs(Box, { flexDirection: "column", flexGrow: 1, children: [_jsxs(Text, { bold: mode === 'settings', wrap: "truncate", children: [mode === 'settings' ? '> ' : '  ', t('Settings')] }), _jsx(Box, { height: 1 }), showScrollUp && _jsx(Text, { color: theme.text.secondary, children: "\u25B2" }), visibleItems.map((item, idx) => {
                        const isActive = mode === 'settings' && activeSettingIndex === idx + scrollOffset;
                        const scopeSettings = settings.forScope(selectedScope).settings;
                        const mergedSettings = settings.merged;
                        let displayValue;
                        if (editingKey === item.value) {
                            // Show edit buffer with advanced cursor highlighting
                            if (cursorVisible && editCursorPos < cpLen(editBuffer)) {
                                // Cursor is in the middle or at start of text
                                const beforeCursor = cpSlice(editBuffer, 0, editCursorPos);
                                const atCursor = cpSlice(editBuffer, editCursorPos, editCursorPos + 1);
                                const afterCursor = cpSlice(editBuffer, editCursorPos + 1);
                                displayValue =
                                    beforeCursor + chalk.inverse(atCursor) + afterCursor;
                            }
                            else if (cursorVisible && editCursorPos >= cpLen(editBuffer)) {
                                // Cursor is at the end - show inverted space
                                displayValue = editBuffer + chalk.inverse(' ');
                            }
                            else {
                                // Cursor not visible
                                displayValue = editBuffer;
                            }
                        }
                        else if (item.type === 'number' || item.type === 'string') {
                            // Settings that open a sub-dialog on Enter
                            const isSubDialogSetting = item.value === 'ui.theme' ||
                                item.value === 'general.preferredEditor' ||
                                item.value === 'fastModel';
                            // For numbers/strings, get the actual current value from pending settings
                            const path = item.value.split('.');
                            const currentValue = getNestedValue(pendingSettings, path);
                            const defaultValue = getDefaultValue(item.value);
                            if (currentValue !== undefined && currentValue !== null) {
                                displayValue = String(currentValue);
                            }
                            else {
                                displayValue =
                                    defaultValue !== undefined && defaultValue !== null
                                        ? String(defaultValue)
                                        : '';
                            }
                            // Add * if value differs from default OR if currently being modified
                            const isModified = modifiedSettings.has(item.value);
                            const effectiveCurrentValue = currentValue !== undefined && currentValue !== null
                                ? currentValue
                                : defaultValue;
                            const isDifferentFromDefault = effectiveCurrentValue !== defaultValue;
                            if (isDifferentFromDefault || isModified) {
                                displayValue += '*';
                            }
                            // Append ▸ for sub-dialog settings to hint Enter opens a picker
                            if (isSubDialogSetting) {
                                displayValue = displayValue ? displayValue + ' ▸' : '▸';
                            }
                        }
                        else {
                            // For booleans and other types, use existing logic
                            displayValue = getDisplayValue(item.value, scopeSettings, mergedSettings, modifiedSettings, pendingSettings);
                        }
                        const shouldBeGreyedOut = isDefaultValue(item.value, scopeSettings);
                        // Generate scope message for this setting
                        const scopeMessage = getScopeMessageForSetting(item.value, selectedScope, settings);
                        return (_jsxs(Box, { flexDirection: "row", alignItems: "center", children: [_jsx(Box, { minWidth: 2, flexShrink: 0, children: _jsx(Text, { color: isActive ? theme.status.success : theme.text.secondary, children: isActive ? '●' : '' }) }), _jsx(Box, { flexGrow: 1, flexShrink: 1, children: _jsxs(Text, { color: isActive ? theme.status.success : theme.text.primary, wrap: "truncate", children: [item.label, scopeMessage && (_jsxs(Text, { color: theme.text.secondary, children: [" ", scopeMessage] }))] }) }), _jsx(Box, { marginLeft: 1, flexShrink: 0, children: _jsx(Text, { color: isActive
                                            ? theme.status.success
                                            : shouldBeGreyedOut
                                                ? theme.text.secondary
                                                : theme.text.primary, wrap: "truncate", children: displayValue }) })] }, item.value));
                    }), showScrollDown && _jsx(Text, { color: theme.text.secondary, children: "\u25BC" })] })) : (_jsx(ScopeSelector, { onSelect: handleScopeSelect, onHighlight: handleScopeHighlight, isFocused: mode === 'scope', initialScope: selectedScope })), activeDescription && mode === 'settings' && (_jsx(Box, { marginTop: 1, children: _jsx(Text, { color: theme.text.secondary, wrap: "truncate-end", italic: true, children: activeDescription }) })), _jsx(Box, { marginTop: activeDescription && mode === 'settings' ? 0 : 1, children: _jsx(Text, { color: theme.text.secondary, wrap: "truncate", children: mode === 'settings'
                        ? t('(Use Enter to select, Tab to configure scope)')
                        : t('(Use Enter to apply scope, Tab to go back)') }) }), showRestartPrompt && (_jsx(Text, { color: theme.status.warning, children: t('To see changes, HopCode must be restarted. Press r to exit and apply changes now.') }))] }));
}
//# sourceMappingURL=SettingsDialog.js.map