import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { GhostflowClientProvider, queryClient } from "@ghostflow/ui-core";
import { QueryClientProvider } from "@tanstack/react-query";
import { useMachine } from "@xstate/react";
import { Option as O } from "effect";
import { Box, Text, useApp, useInput } from "ink";
import { Component, useEffect } from "react";
import { SDKProvider } from "./contexts/SDKContext.js";
import { navigationMachine } from "./machines/navigation.js";
import { AddWizardScreen } from "./screens/AddWizardScreen.js";
import { ConfirmDialog } from "./screens/ConfirmDialog.js";
import { DashboardScreen } from "./screens/DashboardScreen.js";
// ============================================================================
// Constants
// ============================================================================
/** Error message displayed when error object has no message */
const UNKNOWN_ERROR_MESSAGE = "Unknown error";
/** Key hint text for error screen */
const ERROR_SCREEN_HINT = "Press 'r' to retry or 'q' to quit";
/** Error screen title */
const ERROR_SCREEN_TITLE = "An error occurred";
/**
 * Error boundary for catching and displaying errors in the TUI.
 * Prevents crashes from propagating and provides recovery option.
 */
class ErrorBoundary extends Component {
    constructor(props) {
        super(props);
        this.state = { hasError: false, error: undefined };
    }
    static getDerivedStateFromError(error) {
        return { hasError: true, error };
    }
    componentDidCatch(error, errorInfo) {
        console.error("[ghostflow] Uncaught error:", error, errorInfo);
    }
    handleReset = () => {
        this.setState({ hasError: false, error: undefined });
        this.props.onReset?.();
    };
    render() {
        if (this.state.hasError) {
            return _jsx(ErrorScreen, { error: this.state.error, onRetry: this.handleReset });
        }
        return this.props.children;
    }
}
/** Extract error message using Option pattern */
const getErrorMessage = (error) => O.match(O.fromNullable(error), {
    onNone: () => UNKNOWN_ERROR_MESSAGE,
    onSome: (e) => e.message
});
/**
 * Error screen displayed when an unhandled error occurs.
 */
const ErrorScreen = ({ error, onRetry }) => {
    const { exit } = useApp();
    useInput((input) => {
        if (input === "r") {
            onRetry();
        }
        if (input === "q") {
            exit();
        }
    });
    return (_jsxs(Box, { flexDirection: "column", padding: 1, children: [_jsx(Text, { bold: true, color: "red", children: ERROR_SCREEN_TITLE }), _jsx(Box, { marginY: 1, children: _jsx(Text, { children: getErrorMessage(error) }) }), _jsx(Text, { dimColor: true, children: ERROR_SCREEN_HINT })] }));
};
/**
 * Inner app component that uses hooks requiring providers.
 * Separated to ensure hooks are called inside provider tree.
 */
const AppContent = ({ send, state }) => {
    return (_jsxs(Box, { flexDirection: "column", height: "100%", children: [state.matches("dashboard") && _jsx(DashboardScreen, { send: send }), state.matches("addWizard") && _jsx(AddWizardScreen, { send: send, wizardData: state.context.wizardData }), state.matches("confirmAction") && _jsx(ConfirmDialog, { send: send, action: state.context.confirmAction })] }));
};
/**
 * Root TUI application component.
 *
 * Provides:
 * - Error boundary for crash protection
 * - React Query for async state management
 * - GhostflowClient context for SDK access
 * - Event subscription for real-time updates
 * - XState navigation for screen routing
 */
export const App = ({ sdk }) => {
    const { exit } = useApp();
    const [state, send] = useMachine(navigationMachine);
    // Exit app when machine reaches final state
    useEffect(() => {
        if (state.matches("exiting")) {
            exit();
        }
    }, [state, exit]);
    return (_jsx(ErrorBoundary, { children: _jsx(QueryClientProvider, { client: queryClient, children: _jsx(GhostflowClientProvider, { client: sdk.client, children: _jsx(SDKProvider, { sdk: sdk, children: _jsx(AppContent, { send: send, state: state }) }) }) }) }));
};
//# sourceMappingURL=App.js.map