import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
/**
 * @license
 * Copyright 2025 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
import { Box, Text } from 'ink';
import { useCallback, useMemo } from 'react';
import { IdeIntegrationNudge } from '../IdeIntegrationNudge.js';
import { useRuntimeApi } from '../contexts/RuntimeContext.js';
import { getProjectHash, DebugLogger } from '@vybestack/llxprt-code-core';
import { join } from 'node:path';
import { performResume, } from '../../services/performResume.js';
import { iContentToHistoryItems } from '../utils/iContentToHistoryItems.js';
// import { LoopDetectionConfirmation } from './LoopDetectionConfirmation.js'; // TODO: Not yet ported from upstream
import { FolderTrustDialog } from './FolderTrustDialog.js';
import { WelcomeDialog } from './WelcomeOnboarding/WelcomeDialog.js';
import { ShellConfirmationDialog } from './ShellConfirmationDialog.js';
import { ConsentPrompt } from './ConsentPrompt.js';
import { ThemeDialog } from './ThemeDialog.js';
import { SettingsDialog } from './SettingsDialog.js';
import { AuthDialog } from './AuthDialog.js';
import { OAuthCodeDialog } from './OAuthCodeDialog.js';
import { EditorSettingsDialog } from './EditorSettingsDialog.js';
import { ProviderDialog } from './ProviderDialog.js';
import { LoadProfileDialog } from './LoadProfileDialog.js';
import { ProfileCreateWizard } from './ProfileCreateWizard/index.js';
import { ProfileListDialog } from './ProfileListDialog.js';
import { ProfileDetailDialog } from './ProfileDetailDialog.js';
import { ProfileInlineEditor } from './ProfileInlineEditor.js';
import { ToolsDialog } from './ToolsDialog.js';
import { PrivacyNotice } from '../privacy/PrivacyNotice.js';
import { WorkspaceMigrationDialog } from './WorkspaceMigrationDialog.js';
import { PermissionsModifyTrustDialog } from './PermissionsModifyTrustDialog.js';
import { LoggingDialog } from './LoggingDialog.js';
import { SubagentManagerDialog } from './SubagentManagement/index.js';
import { SubagentView } from './SubagentManagement/types.js';
import { ModelsDialog } from './ModelDialog.js';
/**
 * @plan PLAN-20260214-SESSIONBROWSER.P21
 */
import { SessionBrowserDialog } from './SessionBrowserDialog.js';
import { theme } from '../semantic-colors.js';
import { useUIState } from '../contexts/UIStateContext.js';
import { useUIActions } from '../contexts/UIActionsContext.js';
const dialogManagerLogger = new DebugLogger('llxprt:ui:dialogmanager');
// Props for DialogManager
export const DialogManager = ({ addItem, terminalWidth, config, settings, }) => {
    const uiState = useUIState();
    const uiActions = useUIActions();
    const runtime = useRuntimeApi();
    const { constrainHeight, terminalHeight, mainAreaWidth, commandContext } = uiState;
    // staticExtraHeight not yet implemented in LLxprt
    const staticExtraHeight = 0;
    // Get current provider for ModelsDialog
    const currentProvider = useMemo(() => {
        try {
            return runtime.getActiveProviderName() || null;
        }
        catch {
            return null;
        }
    }, [runtime]);
    const handlePrivacyNoticeExit = useCallback(() => {
        uiActions.handlePrivacyNoticeExit();
    }, [uiActions]);
    // Handler for ModelsDialog selection
    const handleModelsDialogSelect = useCallback(async (model) => {
        try {
            const selectedProvider = model.provider;
            // Check if we need to switch providers
            // Switch if: provider differs OR no current provider set
            if (selectedProvider !== currentProvider) {
                // 1. Switch provider first
                const switchResult = await runtime.switchActiveProvider(selectedProvider, { addItem });
                // 2. Build messages in correct order
                const messages = [];
                // Provider switch message
                messages.push(currentProvider
                    ? `Switched from ${currentProvider} to ${switchResult.nextProvider}`
                    : `Switched to ${switchResult.nextProvider}`);
                // Base URL message (extract from switchResult)
                const baseUrlMsg = (switchResult.infoMessages ?? []).find((m) => m?.includes('Base URL') || m?.includes('base URL'));
                if (baseUrlMsg)
                    messages.push(baseUrlMsg);
                // Set the selected model (override provider's default)
                await runtime.setActiveModel(model.id);
                // Model message with user's selected model
                messages.push(`Active model is '${model.id}' for provider '${selectedProvider}'.`);
                // /key reminder (if not gemini)
                if (selectedProvider !== 'gemini') {
                    messages.push('Use /key to set API key if needed.');
                }
                // Show all messages
                for (const msg of messages) {
                    addItem({ type: 'info', text: msg }, Date.now());
                }
                commandContext.recordingIntegration?.recordProviderSwitch(selectedProvider, model.id);
            }
            else {
                // Same provider — just set model
                const result = await runtime.setActiveModel(model.id);
                addItem({
                    type: 'info',
                    text: `Active model is '${result.nextModel}' for provider '${result.providerName}'.`,
                }, Date.now());
                commandContext.recordingIntegration?.recordProviderSwitch(result.providerName, result.nextModel);
            }
        }
        catch (e) {
            const status = runtime.getActiveProviderStatus();
            addItem({
                type: 'error',
                text: `Failed to switch model for provider '${status.providerName ?? 'unknown'}': ${e instanceof Error ? e.message : String(e)}`,
            }, Date.now());
        }
        uiActions.closeModelsDialog();
    }, [runtime, addItem, uiActions, currentProvider, commandContext]);
    /**
     * Handler for SessionBrowserDialog selection - performs real session resume.
     * @plan PLAN-20260214-SESSIONBROWSER.P23
     * @requirement REQ-PR-001, REQ-PR-002
     */
    const handleSessionBrowserSelect = useCallback(async (session) => {
        const recordingSwapCallbacks = commandContext.recordingSwapCallbacks;
        // Guard: recording infrastructure required
        if (!recordingSwapCallbacks) {
            dialogManagerLogger.warn('Cannot resume session: recording infrastructure not available.');
            return {
                ok: false,
                error: 'Recording infrastructure not available.',
            };
        }
        // Build ResumeContext
        const chatsDir = join(config.getProjectTempDir(), 'chats');
        const projectHash = getProjectHash(config.getProjectRoot());
        const currentSessionId = config.getSessionId();
        const currentProvider = config.getProvider() ?? 'unknown';
        const currentModel = config.getModel();
        const workspaceDirs = [...config.getWorkspaceContext().getDirectories()];
        const resumeContext = {
            chatsDir,
            projectHash,
            currentSessionId,
            currentProvider,
            currentModel,
            workspaceDirs,
            recordingCallbacks: recordingSwapCallbacks,
            logger: dialogManagerLogger,
        };
        // Perform resume
        const resumeResult = await performResume(session.sessionId, resumeContext);
        if (!resumeResult.ok) {
            // Show error but keep dialog open for retry
            addItem({ type: 'error', text: resumeResult.error }, Date.now());
            return resumeResult;
        }
        // Log warnings
        for (const warning of resumeResult.warnings) {
            addItem({ type: 'info', text: `Warning: ${warning}` }, Date.now());
        }
        // Restore history to gemini client
        await config.getGeminiClient()?.restoreHistory(resumeResult.history);
        // Convert IContent[] to UI history items and load
        const uiHistory = iContentToHistoryItems(resumeResult.history);
        commandContext.ui.clear();
        uiHistory.forEach((item, index) => {
            commandContext.ui.addItem(item, index);
        });
        // Close dialog on success
        uiActions.closeSessionBrowserDialog();
        return resumeResult;
    }, [config, commandContext, addItem, uiActions]);
    // TODO: IdeTrustChangeDialog not yet ported from upstream
    // if (uiState.showIdeRestartPrompt) {
    //   return <IdeTrustChangeDialog reason={uiState.ideTrustRestartReason} />;
    // }
    if (uiState.showWorkspaceMigrationDialog) {
        return (_jsx(WorkspaceMigrationDialog, { workspaceExtensions: uiState.workspaceGeminiCLIExtensions, onOpen: uiActions.onWorkspaceMigrationDialogOpen, onClose: uiActions.onWorkspaceMigrationDialogClose }));
    }
    if (uiState.shouldShowIdePrompt) {
        return (_jsx(IdeIntegrationNudge, { ide: uiState.currentIDE, onComplete: uiActions.handleIdePromptComplete }));
    }
    if (uiState.isFolderTrustDialogOpen) {
        return (_jsx(FolderTrustDialog, { onSelect: uiActions.handleFolderTrustSelect, isRestarting: uiState.isRestarting }));
    }
    if (uiState.isWelcomeDialogOpen) {
        return (_jsx(WelcomeDialog, { state: uiState.welcomeState, actions: uiActions.welcomeActions, availableProviders: uiState.welcomeAvailableProviders, availableModels: uiState.welcomeAvailableModels, triggerAuth: uiActions.triggerWelcomeAuth }));
    }
    if (uiState.shellConfirmationRequest) {
        return (_jsx(ShellConfirmationDialog, { request: uiState.shellConfirmationRequest }));
    }
    // TODO: LoopDetectionConfirmation not yet ported from upstream
    // if (uiState.loopDetectionConfirmationRequest) {
    //   return (
    //     <LoopDetectionConfirmation
    //       onComplete={uiState.loopDetectionConfirmationRequest.onComplete}
    //     />
    //   );
    // }
    if (uiState.confirmationRequest) {
        return (_jsx(ConsentPrompt, { prompt: uiState.confirmationRequest.prompt, onConfirm: uiState.confirmationRequest.onConfirm, terminalWidth: terminalWidth }));
    }
    if (uiState.confirmUpdateGeminiCLIExtensionRequests.length > 0) {
        const request = uiState.confirmUpdateGeminiCLIExtensionRequests[0];
        return (_jsx(ConsentPrompt, { prompt: request.prompt, onConfirm: request.onConfirm, terminalWidth: terminalWidth }));
    }
    if (uiState.isThemeDialogOpen) {
        return (_jsxs(Box, { flexDirection: "column", children: [uiState.themeError && (_jsx(Box, { marginBottom: 1, children: _jsx(Text, { color: theme.status.error, children: uiState.themeError }) })), _jsx(ThemeDialog, { onSelect: uiActions.handleThemeSelect, onHighlight: uiActions.handleThemeHighlight, settings: settings, availableTerminalHeight: constrainHeight ? terminalHeight - staticExtraHeight : undefined, terminalWidth: mainAreaWidth })] }));
    }
    if (uiState.isSettingsDialogOpen) {
        return (_jsx(Box, { flexDirection: "column", children: _jsx(SettingsDialog, { settings: settings, onSelect: uiActions.closeSettingsDialog, onRestartRequest: uiActions.handleSettingsRestart, config: config }) }));
    }
    if (uiState.isAuthDialogOpen) {
        return (_jsx(Box, { flexDirection: "column", children: _jsx(AuthDialog, { onSelect: uiActions.handleAuthSelect, settings: settings, initialErrorMessage: uiState.authError }) }));
    }
    if (uiState.isOAuthCodeDialogOpen) {
        const provider = global.__oauth_provider ||
            'unknown';
        return (_jsx(OAuthCodeDialog, { provider: provider, onClose: uiActions.handleOAuthCodeDialogClose, onSubmit: uiActions.handleOAuthCodeSubmit }));
    }
    if (uiState.isEditorDialogOpen) {
        return (_jsxs(Box, { flexDirection: "column", children: [uiState.editorError && (_jsx(Box, { marginBottom: 1, children: _jsx(Text, { color: theme.status.error, children: uiState.editorError }) })), _jsx(EditorSettingsDialog, { onSelect: uiActions.handleEditorSelect, settings: settings, onExit: uiActions.exitEditorDialog })] }));
    }
    if (uiState.isProviderDialogOpen) {
        return (_jsx(Box, { flexDirection: "column", children: _jsx(ProviderDialog, { providers: uiState.providerOptions, currentProvider: uiState.selectedProvider, onSelect: uiActions.handleProviderSelect, onClose: uiActions.exitProviderDialog }) }));
    }
    if (uiState.isLoadProfileDialogOpen) {
        return (_jsx(Box, { flexDirection: "column", children: _jsx(LoadProfileDialog, { profiles: uiState.profiles, onSelect: uiActions.handleProfileSelect, onClose: uiActions.exitLoadProfileDialog }) }));
    }
    if (uiState.isCreateProfileDialogOpen) {
        return (_jsx(Box, { flexDirection: "column", children: _jsx(ProfileCreateWizard, { onClose: uiActions.exitCreateProfileDialog, onLoadProfile: uiActions.handleProfileSelect, availableProviders: uiState.providerOptions }) }));
    }
    if (uiState.isProfileListDialogOpen) {
        return (_jsx(Box, { flexDirection: "column", children: _jsx(ProfileListDialog, { profiles: uiState.profileListItems, onSelect: uiActions.loadProfileFromDetail, onClose: uiActions.closeProfileListDialog, onViewDetail: uiActions.viewProfileDetail, isLoading: uiState.profileDialogLoading, defaultProfileName: uiState.defaultProfileName ?? undefined, activeProfileName: uiState.activeProfileName ?? undefined }) }));
    }
    if (uiState.isProfileDetailDialogOpen) {
        return (_jsx(Box, { flexDirection: "column", children: _jsx(ProfileDetailDialog, { profileName: uiState.selectedProfileName ?? '', profile: uiState.selectedProfileData, onClose: uiActions.closeProfileDetailDialog, onLoad: uiActions.loadProfileFromDetail, onDelete: uiActions.deleteProfileFromDetail, onSetDefault: uiActions.setProfileAsDefault, onEdit: uiActions.openProfileEditor, isLoading: uiState.profileDialogLoading, isDefault: uiState.selectedProfileName === uiState.defaultProfileName, isActive: uiState.selectedProfileName === uiState.activeProfileName, error: uiState.profileDialogError ?? undefined }) }));
    }
    if (uiState.isProfileEditorDialogOpen && uiState.selectedProfileData) {
        return (_jsx(Box, { flexDirection: "column", children: _jsx(ProfileInlineEditor, { profileName: uiState.selectedProfileName ?? '', profile: uiState.selectedProfileData, onSave: uiActions.saveProfileFromEditor, onCancel: uiActions.closeProfileEditor, error: uiState.profileDialogError ?? undefined }) }));
    }
    if (uiState.isToolsDialogOpen) {
        return (_jsx(Box, { flexDirection: "column", children: _jsx(ToolsDialog, { tools: uiState.toolsDialogTools, action: uiState.toolsDialogAction, disabledTools: uiState.toolsDialogDisabledTools, onSelect: uiActions.handleToolsSelect, onClose: uiActions.exitToolsDialog }) }));
    }
    if (uiState.showPrivacyNotice) {
        return _jsx(PrivacyNotice, { onExit: handlePrivacyNoticeExit, config: config });
    }
    if (uiState.isPermissionsDialogOpen) {
        return (_jsx(PermissionsModifyTrustDialog, { onExit: uiActions.closePermissionsDialog, addItem: addItem }));
    }
    if (uiState.isLoggingDialogOpen) {
        return (_jsx(LoggingDialog, { entries: (uiState.loggingDialogData?.entries || []), onClose: uiActions.closeLoggingDialog }));
    }
    if (uiState.isSubagentDialogOpen) {
        return (_jsx(SubagentManagerDialog, { onClose: uiActions.closeSubagentDialog, initialView: uiState.subagentDialogInitialView ?? SubagentView.MENU, initialSubagentName: uiState.subagentDialogInitialName }));
    }
    if (uiState.isModelsDialogOpen) {
        return (_jsx(Box, { flexDirection: "column", children: _jsx(ModelsDialog, { onSelect: handleModelsDialogSelect, onClose: uiActions.closeModelsDialog, initialSearch: uiState.modelsDialogData?.initialSearch, initialFilters: uiState.modelsDialogData?.initialFilters, includeDeprecated: uiState.modelsDialogData?.includeDeprecated, currentProvider: currentProvider, initialProviderFilter: uiState.modelsDialogData?.providerOverride, showAllProviders: uiState.modelsDialogData?.showAllProviders }) }));
    }
    /**
     * Session browser dialog rendering
     * @plan PLAN-20260214-SESSIONBROWSER.P21
     */
    /**
     * Session browser dialog rendering
     * @plan PLAN-20260214-SESSIONBROWSER.P23
     * Uses commandContext.ui.pendingItem to determine if there's an active conversation.
     */
    if (uiState.isSessionBrowserDialogOpen) {
        const chatsDir = join(config.getProjectTempDir(), 'chats');
        const projectHash = getProjectHash(config.getProjectRoot());
        const currentSessionId = config.getSessionId();
        // Determine if there's an active conversation based on pendingItem
        const hasActiveConversation = commandContext.ui.pendingItem !== null;
        return (_jsx(Box, { flexDirection: "column", children: _jsx(SessionBrowserDialog, { chatsDir: chatsDir, projectHash: projectHash, currentSessionId: currentSessionId, hasActiveConversation: hasActiveConversation, onSelect: handleSessionBrowserSelect, onClose: uiActions.closeSessionBrowserDialog }) }));
    }
    return null;
};
//# sourceMappingURL=DialogManager.js.map