"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 AlternateBufferCLI_exports = {};
__export(AlternateBufferCLI_exports, {
  AlternateBufferCLI: () => AlternateBufferCLI
});
module.exports = __toCommonJS(AlternateBufferCLI_exports);
var import_jsx_runtime = require("react/jsx-runtime");
var import_react = require("react");
var import_ink = require("ink");
var import_hooks = require("../../hooks/index.js");
var import_useCLIState = require("../../hooks/useCLIState.js");
var import_useGitBranch = require("../../hooks/useGitBranch.js");
var import_contexts = require("../../contexts/index.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_VirtualizedList = require("../shared/VirtualizedList.js");
var import_InputContainer = require("../../containers/InputContainer.js");
var import_OverlayContainer = require("../../containers/OverlayContainer.js");
var import_overlayPresentation = require("../../utils/overlayPresentation.js");
function AlternateBufferCLI({
  agent,
  initialSessionId,
  initialPrompt,
  startupInfo,
  configFilePath,
  initialBypassPermissions = false,
  onSelectionAttempt,
  useStreaming = true
}) {
  const listRef = (0, import_react.useRef)(null);
  const listContainerRef = (0, import_react.useRef)(null);
  const inputContainerRef = (0, import_react.useRef)(null);
  const [selectionHintVisible, setSelectionHintVisible] = (0, import_react.useState)(false);
  const handleKeyboardScroll = (0, import_react.useCallback)((direction) => {
    const delta = direction === "up" ? -10 : 10;
    listRef.current?.scrollBy(delta);
  }, []);
  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,
    onKeyboardScroll: handleKeyboardScroll,
    initialBypassPermissions
  });
  const branchName = (0, import_useGitBranch.useGitBranch)();
  const getScrollState = (0, import_react.useCallback)(() => {
    const scrollState = listRef.current?.getScrollState();
    return scrollState ?? { scrollTop: 0, scrollHeight: 0, innerHeight: 0 };
  }, []);
  const scrollBy = (0, import_react.useCallback)((delta) => {
    listRef.current?.scrollBy(delta);
  }, []);
  const hasFocus = (0, import_react.useCallback)(() => true, []);
  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(
          `AlternateBufferCLI.handleSubmitPromptCommand failed: ${error instanceof Error ? error.message : String(error)}`
        );
      }
    },
    [agent]
  );
  (0, import_contexts.useScrollable)(
    {
      ref: listContainerRef,
      getScrollState,
      scrollBy,
      hasFocus
    },
    true
    // Always active in alternate buffer mode
  );
  const handleSelectionAttempt = (0, import_react.useCallback)(() => {
    setSelectionHintVisible(true);
    onSelectionAttempt?.();
  }, [onSelectionAttempt]);
  (0, import_react.useEffect)(() => {
    if (!selectionHintVisible) return;
    const timer = setTimeout(() => {
      setSelectionHintVisible(false);
    }, 3e3);
    return () => clearTimeout(timer);
  }, [selectionHintVisible]);
  const { rows: terminalHeight, columns: terminalWidth } = (0, import_hooks.useTerminalSize)();
  const listData = (0, import_react.useMemo)(() => {
    const items = [{ type: "header" }];
    const seenIds = /* @__PURE__ */ new Set();
    for (const msg of visibleMessages) {
      items.push({ type: "message", message: msg });
      seenIds.add(msg.id);
    }
    for (const msg of pendingMessages) {
      if (!seenIds.has(msg.id)) {
        items.push({ type: "message", message: msg });
        seenIds.add(msg.id);
      }
    }
    for (const msg of dequeuedBuffer) {
      if (!seenIds.has(msg.id)) {
        items.push({ type: "message", message: msg });
      }
    }
    return items;
  }, [visibleMessages, pendingMessages, dequeuedBuffer]);
  const renderListItem = (0, import_react.useCallback)(
    ({ item }) => {
      if (item.type === "header") {
        return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
          import_Header.Header,
          {
            modelName: session.modelName,
            sessionId: session.id || void 0,
            hasActiveSession: session.hasActiveSession,
            startupInfo
          }
        );
      }
      return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
        import_MessageItem.MessageItem,
        {
          message: item.message,
          terminalWidth,
          showReasoning: ui.showReasoning
        }
      );
    },
    [
      session.modelName,
      session.id,
      session.hasActiveSession,
      startupInfo,
      terminalWidth,
      ui.showReasoning
    ]
  );
  const estimateItemHeight = (0, import_react.useCallback)(
    (index) => {
      const item = listData[index];
      if (!item) return 3;
      if (item.type === "header") {
        return 10;
      }
      const msg = item.message;
      if (msg.role === "tool") {
        if (msg.toolResult) {
          const resultLines = Math.ceil(msg.toolResult.length / 80);
          return Math.min(2 + resultLines, 10);
        }
        return 2;
      }
      if (msg.role === "user") {
        const contentLines = Math.ceil(msg.content.length / 80);
        return Math.max(3, contentLines + 2);
      }
      if (msg.role === "assistant") {
        if (msg.isStreaming) return 5;
        const contentLines = Math.ceil(msg.content.length / 80);
        const reasoningLines = ui.showReasoning && msg.reasoning ? Math.ceil(msg.reasoning.length / 80) : 0;
        return Math.max(2, contentLines + reasoningLines + 1);
      }
      if (msg.styledType) {
        return 8;
      }
      return 3;
    },
    [listData, ui.showReasoning]
  );
  const getItemKey = (0, import_react.useCallback)((item) => {
    if (item.type === "header") return "header";
    return item.message.id;
  }, []);
  const hideChrome = (0, import_overlayPresentation.shouldHideStatusChrome)(ui.activeOverlay, approval);
  return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Box, { flexDirection: "column", height: terminalHeight, children: [
    /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Box, { ref: listContainerRef, flexGrow: 1, flexShrink: 1, minHeight: 0, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
      import_VirtualizedList.VirtualizedList,
      {
        ref: listRef,
        data: listData,
        renderItem: renderListItem,
        estimatedItemHeight: estimateItemHeight,
        keyExtractor: getItemKey,
        initialScrollIndex: import_VirtualizedList.SCROLL_TO_ITEM_END,
        initialScrollOffsetInIndex: import_VirtualizedList.SCROLL_TO_ITEM_END
      }
    ) }),
    /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Box, { flexDirection: "column", flexShrink: 0, children: [
      !hideChrome && /* @__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
          }
        ),
        selectionHintVisible && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Box, { paddingX: 1, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: "yellowBright", children: "\u{1F4A1} Tip: Hold Option (\u2325) and click to select text, or press Ctrl+S to toggle copy mode" }) }),
        /* @__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,
          onKeyboardScroll: handleKeyboardScroll,
          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,
          onSubmitPromptCommand: handleSubmitPromptCommand,
          configFilePath
        }
      ),
      !hideChrome && 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)" })
      ] }),
      !hideChrome && /* @__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
        }
      ),
      !hideChrome && 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 = {
  AlternateBufferCLI
});
