"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var StaticCLI_exports = {};
__export(StaticCLI_exports, {
  StaticCLI: () => StaticCLI
});
module.exports = __toCommonJS(StaticCLI_exports);
var import_jsx_runtime = require("react/jsx-runtime");
var import_react = require("react");
var import_ink = require("ink");
var import_useCLIState = require("../../hooks/useCLIState.js");
var import_useTerminalSize = require("../../hooks/useTerminalSize.js");
var import_useGitBranch = require("../../hooks/useGitBranch.js");
var import_Header = require("../chat/Header.js");
var import_MessageItem = require("../chat/MessageItem.js");
var import_QueuedMessagesDisplay = require("../chat/QueuedMessagesDisplay.js");
var import_StatusBar = require("../StatusBar.js");
var import_HistorySearchBar = require("../HistorySearchBar.js");
var import_Footer = require("../Footer.js");
var import_TodoPanel = require("../TodoPanel.js");
var import_BackgroundTasksPanel = require("../BackgroundTasksPanel.js");
var import_InputContainer = require("../../containers/InputContainer.js");
var import_OverlayContainer = require("../../containers/OverlayContainer.js");
var import_overlayPresentation = require("../../utils/overlayPresentation.js");
const CLEAR_TERMINAL = "\x1B[2J\x1B[3J\x1B[H";
function StaticCLI({
  agent,
  initialSessionId,
  initialPrompt,
  startupInfo,
  configFilePath,
  initialBypassPermissions = false,
  useStreaming = true
}) {
  const {
    messages,
    setMessages,
    pendingMessages,
    setPendingMessages,
    dequeuedBuffer,
    setDequeuedBuffer,
    steerMessages,
    setSteerMessages,
    queuedMessages,
    setQueuedMessages,
    todos,
    setTodos,
    ui,
    setUi,
    input,
    setInput,
    session,
    setSession,
    approval,
    setApproval,
    approvalQueue,
    setApprovalQueue,
    inputService,
    buffer,
    overlayContainerRef,
    visibleMessages
  } = (0, import_useCLIState.useCLIState)({
    agent,
    initialSessionId,
    startupInfo,
    initialBypassPermissions
    // No keyboard scroll handler - let terminal handle scrollback
  });
  const branchName = (0, import_useGitBranch.useGitBranch)();
  const { write: stdoutWrite } = (0, import_ink.useStdout)();
  const { columns: terminalWidth } = (0, import_useTerminalSize.useTerminalSize)();
  const [staticRemountKey, setStaticRemountKey] = (0, import_react.useState)(0);
  const isInitialMount = (0, import_react.useRef)(true);
  const isInitialShowReasoningMount = (0, import_react.useRef)(true);
  const inputContainerRef = (0, import_react.useRef)(null);
  const historySearchHasMatch = (0, import_react.useMemo)(() => {
    if (!ui.historySearch.isActive || !ui.historySearch.query) return false;
    const query = ui.historySearch.query.toLowerCase();
    return input.history.some((item) => item.toLowerCase().includes(query));
  }, [ui.historySearch.isActive, ui.historySearch.query, input.history]);
  const handleSubmitPromptCommand = (0, import_react.useCallback)(
    async (commandText) => {
      try {
        await inputContainerRef.current?.submit(commandText);
      } catch (error) {
        agent.logger.error(
          `StaticCLI.handleSubmitPromptCommand failed: ${error instanceof Error ? error.message : String(error)}`
        );
      }
    },
    [agent]
  );
  const refreshStatic = (0, import_react.useCallback)(() => {
    stdoutWrite(CLEAR_TERMINAL);
    setStaticRemountKey((prev) => prev + 1);
  }, [stdoutWrite]);
  (0, import_react.useEffect)(() => {
    if (isInitialMount.current) {
      isInitialMount.current = false;
      return;
    }
    const handler = setTimeout(() => {
      refreshStatic();
    }, 300);
    return () => {
      clearTimeout(handler);
    };
  }, [terminalWidth, refreshStatic]);
  (0, import_react.useEffect)(() => {
    if (isInitialShowReasoningMount.current) {
      isInitialShowReasoningMount.current = false;
      return;
    }
    refreshStatic();
  }, [ui.showReasoning, refreshStatic]);
  const staticItems = (0, import_react.useMemo)(() => {
    const items = [
      /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
        import_Header.Header,
        {
          modelName: session.modelName,
          sessionId: session.id || void 0,
          hasActiveSession: session.hasActiveSession,
          startupInfo
        },
        "header"
      ),
      ...visibleMessages.map((msg) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
        import_MessageItem.MessageItem,
        {
          message: msg,
          terminalWidth,
          showReasoning: ui.showReasoning
        },
        msg.id
      ))
    ];
    return items;
  }, [
    visibleMessages,
    session.modelName,
    session.id,
    session.hasActiveSession,
    startupInfo,
    terminalWidth,
    ui.showReasoning
  ]);
  return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Box, { flexDirection: "column", width: terminalWidth, children: [
    /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Static, { items: staticItems, children: (item) => item }, staticRemountKey),
    pendingMessages.map((message) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
      import_MessageItem.MessageItem,
      {
        message,
        terminalWidth,
        showReasoning: ui.showReasoning
      },
      message.id
    )),
    dequeuedBuffer.map((message) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
      import_MessageItem.MessageItem,
      {
        message,
        terminalWidth,
        showReasoning: ui.showReasoning
      },
      message.id
    )),
    /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Box, { flexDirection: "column", flexShrink: 0, children: [
      (() => {
        const hideChrome = (0, import_overlayPresentation.shouldHideStatusChrome)(ui.activeOverlay, approval);
        if (hideChrome) return null;
        return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_jsx_runtime.Fragment, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
            import_StatusBar.StatusBar,
            {
              agent,
              isProcessing: ui.isProcessing,
              isThinking: ui.isThinking,
              isCompacting: ui.isCompacting,
              approvalQueueCount: approvalQueue.length,
              copyModeEnabled: ui.copyModeEnabled,
              isAwaitingApproval: approval !== null,
              todoExpanded: ui.todoExpanded,
              hasTodos: todos.some((t) => t.status !== "completed"),
              planModeActive: ui.planModeActive,
              autoApproveEdits: ui.autoApproveEdits,
              backgroundTasksRunning: ui.backgroundTasksRunning
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
            import_BackgroundTasksPanel.BackgroundTasksPanel,
            {
              tasks: ui.backgroundTasks,
              isExpanded: ui.backgroundTasksExpanded,
              isProcessing: ui.isProcessing
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
            import_TodoPanel.TodoPanel,
            {
              todos,
              isExpanded: ui.todoExpanded,
              isProcessing: ui.isProcessing
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
            import_QueuedMessagesDisplay.QueuedMessagesDisplay,
            {
              messages: steerMessages,
              label: "current-turn input",
              hint: import_QueuedMessagesDisplay.QUEUE_EDIT_SHORTCUTS.currentTurn
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
            import_QueuedMessagesDisplay.QueuedMessagesDisplay,
            {
              messages: queuedMessages,
              label: "queued follow-up",
              hint: import_QueuedMessagesDisplay.QUEUE_EDIT_SHORTCUTS.followUp
            }
          )
        ] });
      })(),
      /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
        import_InputContainer.InputContainer,
        {
          ref: inputContainerRef,
          buffer,
          input,
          ui,
          session,
          initialPrompt,
          approval,
          steerMessages,
          queuedMessages,
          setInput,
          setUi,
          setSession,
          setMessages,
          setPendingMessages,
          setDequeuedBuffer,
          setSteerMessages,
          setQueuedMessages,
          setApproval,
          setApprovalQueue,
          setTodos,
          agent,
          inputService,
          useStreaming,
          configFilePath
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
        import_OverlayContainer.OverlayContainer,
        {
          ref: overlayContainerRef,
          ui,
          input,
          session,
          approval,
          setInput,
          setUi,
          setSession,
          setMessages,
          setApproval,
          setApprovalQueue,
          agent,
          inputService,
          buffer,
          refreshStatic,
          onSubmitPromptCommand: handleSubmitPromptCommand,
          configFilePath
        }
      ),
      !(0, import_overlayPresentation.shouldHideStatusChrome)(ui.activeOverlay, approval) && ui.exitWarningShown && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Box, { paddingX: 1, children: [
        /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: "yellowBright", bold: true, children: "\u26A0 Press Ctrl+C again to exit" }),
        /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: "gray", children: " (or press any key to cancel)" })
      ] }),
      !(0, import_overlayPresentation.shouldHideStatusChrome)(ui.activeOverlay, approval) && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
        import_Footer.Footer,
        {
          agent,
          sessionId: session.id,
          modelName: session.modelName,
          cwd: process.cwd(),
          ...branchName ? { branchName } : {},
          autoApproveEdits: ui.autoApproveEdits,
          bypassPermissions: ui.bypassPermissions,
          planModeActive: ui.planModeActive,
          isShellMode: buffer.text.startsWith("!"),
          chatgptRateLimitStatus: ui.chatgptRateLimitStatus
        }
      ),
      !(0, import_overlayPresentation.shouldHideStatusChrome)(ui.activeOverlay, approval) && ui.historySearch.isActive && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
        import_HistorySearchBar.HistorySearchBar,
        {
          query: ui.historySearch.query,
          hasMatch: historySearchHasMatch
        }
      )
    ] })
  ] });
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  StaticCLI
});
