import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import React, { useState, useEffect, useCallback } from "react";
import { render, Box, Text } from "ink";
import { HeaderBar } from "./components/header-bar.js";
import { ActivityPane } from "./components/activity-pane.js";
import { InputComposer } from "./components/input-composer.js";
import { PermissionPrompt } from "./components/permission-prompt.js";
function AppInner({ store, onRunTurn, onCtrlC }) {
    const [state, setState] = useState(store.getState());
    useEffect(() => {
        const unsub = store.subscribe(() => {
            setState(store.getState());
        });
        return unsub;
    }, [store]);
    const handleSubmit = useCallback((input) => {
        onRunTurn(input);
    }, [onRunTurn]);
    // Disable the chat input while the agent is working OR while a permission
    // prompt is active. The prompt's `useInput` hook would otherwise compete
    // with InputComposer's for keystrokes, and any non-{y,n,a,Esc} key would
    // get echoed into the chat buffer.
    const disabled = (state.phase !== "idle" && state.phase !== "loading") ||
        state.pendingPermission !== null;
    return (_jsxs(Box, { flexDirection: "column", children: [_jsx(ActivityPane, { items: state.items }), _jsx(HeaderBar, { model: state.model, step: state.step, maxSteps: state.maxSteps, inputTokens: state.inputTokens, outputTokens: state.outputTokens, contextTokens: state.contextTokens, maxContextTokens: state.maxContextTokens, workspaceRoot: state.workspaceRoot, indexStatus: state.indexStatus }), state.pendingPermission && (_jsx(PermissionPrompt, { prompt: state.pendingPermission })), _jsx(InputComposer, { onSubmit: handleSubmit, disabled: disabled, ...(onCtrlC && { onCtrlC }) }), state.errorMessage && (_jsx(Box, { paddingX: 1, children: _jsx(Box, { borderStyle: "single", borderColor: "red", paddingX: 1, children: _jsxs(Text, { color: "red", children: ["Error: ", state.errorMessage] }) }) }))] }));
}
export function runInkApp(store, onRunTurn, onCtrlC) {
    process.stdout.write("\x1b[2J\x1b[H");
    const instance = render(React.createElement(AppInner, {
        store,
        onRunTurn,
        ...(onCtrlC && { onCtrlC }),
    }), { exitOnCtrlC: false });
    return {
        waitUntilExit: () => instance.waitUntilExit(),
    };
}
