import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import { useMemo, useCallback, useRef, useState, useEffect } from "react";
import { Box, Text } from "ink";
import { useTerminalSize } from "../../hooks/index.js";
import { useCLIState } from "../../hooks/useCLIState.js";
import { useGitBranch } from "../../hooks/useGitBranch.js";
import { useScrollable } from "../../contexts/index.js";
import { Header } from "../chat/Header.js";
import { MessageItem } from "../chat/MessageItem.js";
import { QUEUE_EDIT_SHORTCUTS, QueuedMessagesDisplay } from "../chat/QueuedMessagesDisplay.js";
import { StatusBar } from "../StatusBar.js";
import { HistorySearchBar } from "../HistorySearchBar.js";
import { Footer } from "../Footer.js";
import { TodoPanel } from "../TodoPanel.js";
import { BackgroundTasksPanel } from "../BackgroundTasksPanel.js";
import {
  VirtualizedList,
  SCROLL_TO_ITEM_END
} from "../shared/VirtualizedList.js";
import { InputContainer } from "../../containers/InputContainer.js";
import { OverlayContainer } from "../../containers/OverlayContainer.js";
import { shouldHideStatusChrome } from "../../utils/overlayPresentation.js";
function AlternateBufferCLI({
  agent,
  initialSessionId,
  initialPrompt,
  startupInfo,
  configFilePath,
  initialBypassPermissions = false,
  onSelectionAttempt,
  useStreaming = true
}) {
  const listRef = useRef(null);
  const listContainerRef = useRef(null);
  const inputContainerRef = useRef(null);
  const [selectionHintVisible, setSelectionHintVisible] = useState(false);
  const handleKeyboardScroll = 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
  } = useCLIState({
    agent,
    initialSessionId,
    startupInfo,
    onKeyboardScroll: handleKeyboardScroll,
    initialBypassPermissions
  });
  const branchName = useGitBranch();
  const getScrollState = useCallback(() => {
    const scrollState = listRef.current?.getScrollState();
    return scrollState ?? { scrollTop: 0, scrollHeight: 0, innerHeight: 0 };
  }, []);
  const scrollBy = useCallback((delta) => {
    listRef.current?.scrollBy(delta);
  }, []);
  const hasFocus = useCallback(() => true, []);
  const historySearchHasMatch = 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 = 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]
  );
  useScrollable(
    {
      ref: listContainerRef,
      getScrollState,
      scrollBy,
      hasFocus
    },
    true
    // Always active in alternate buffer mode
  );
  const handleSelectionAttempt = useCallback(() => {
    setSelectionHintVisible(true);
    onSelectionAttempt?.();
  }, [onSelectionAttempt]);
  useEffect(() => {
    if (!selectionHintVisible) return;
    const timer = setTimeout(() => {
      setSelectionHintVisible(false);
    }, 3e3);
    return () => clearTimeout(timer);
  }, [selectionHintVisible]);
  const { rows: terminalHeight, columns: terminalWidth } = useTerminalSize();
  const listData = 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 = useCallback(
    ({ item }) => {
      if (item.type === "header") {
        return /* @__PURE__ */ jsx(
          Header,
          {
            modelName: session.modelName,
            sessionId: session.id || void 0,
            hasActiveSession: session.hasActiveSession,
            startupInfo
          }
        );
      }
      return /* @__PURE__ */ jsx(
        MessageItem,
        {
          message: item.message,
          terminalWidth,
          showReasoning: ui.showReasoning
        }
      );
    },
    [
      session.modelName,
      session.id,
      session.hasActiveSession,
      startupInfo,
      terminalWidth,
      ui.showReasoning
    ]
  );
  const estimateItemHeight = 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 = useCallback((item) => {
    if (item.type === "header") return "header";
    return item.message.id;
  }, []);
  const hideChrome = shouldHideStatusChrome(ui.activeOverlay, approval);
  return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", height: terminalHeight, children: [
    /* @__PURE__ */ jsx(Box, { ref: listContainerRef, flexGrow: 1, flexShrink: 1, minHeight: 0, children: /* @__PURE__ */ jsx(
      VirtualizedList,
      {
        ref: listRef,
        data: listData,
        renderItem: renderListItem,
        estimatedItemHeight: estimateItemHeight,
        keyExtractor: getItemKey,
        initialScrollIndex: SCROLL_TO_ITEM_END,
        initialScrollOffsetInIndex: SCROLL_TO_ITEM_END
      }
    ) }),
    /* @__PURE__ */ jsxs(Box, { flexDirection: "column", flexShrink: 0, children: [
      !hideChrome && /* @__PURE__ */ jsxs(Fragment, { children: [
        /* @__PURE__ */ jsx(
          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__ */ jsx(
          BackgroundTasksPanel,
          {
            tasks: ui.backgroundTasks,
            isExpanded: ui.backgroundTasksExpanded,
            isProcessing: ui.isProcessing
          }
        ),
        /* @__PURE__ */ jsx(
          TodoPanel,
          {
            todos,
            isExpanded: ui.todoExpanded,
            isProcessing: ui.isProcessing
          }
        ),
        selectionHintVisible && /* @__PURE__ */ jsx(Box, { paddingX: 1, children: /* @__PURE__ */ jsx(Text, { color: "yellowBright", children: "\u{1F4A1} Tip: Hold Option (\u2325) and click to select text, or press Ctrl+S to toggle copy mode" }) }),
        /* @__PURE__ */ jsx(
          QueuedMessagesDisplay,
          {
            messages: steerMessages,
            label: "current-turn input",
            hint: QUEUE_EDIT_SHORTCUTS.currentTurn
          }
        ),
        /* @__PURE__ */ jsx(
          QueuedMessagesDisplay,
          {
            messages: queuedMessages,
            label: "queued follow-up",
            hint: QUEUE_EDIT_SHORTCUTS.followUp
          }
        )
      ] }),
      /* @__PURE__ */ jsx(
        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__ */ jsx(
        OverlayContainer,
        {
          ref: overlayContainerRef,
          ui,
          input,
          session,
          approval,
          setInput,
          setUi,
          setSession,
          setMessages,
          setApproval,
          setApprovalQueue,
          agent,
          inputService,
          buffer,
          onSubmitPromptCommand: handleSubmitPromptCommand,
          configFilePath
        }
      ),
      !hideChrome && ui.exitWarningShown && /* @__PURE__ */ jsxs(Box, { paddingX: 1, children: [
        /* @__PURE__ */ jsx(Text, { color: "yellowBright", bold: true, children: "\u26A0 Press Ctrl+C again to exit" }),
        /* @__PURE__ */ jsx(Text, { color: "gray", children: " (or press any key to cancel)" })
      ] }),
      !hideChrome && /* @__PURE__ */ jsx(
        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__ */ jsx(
        HistorySearchBar,
        {
          query: ui.historySearch.query,
          hasMatch: historySearchHasMatch
        }
      )
    ] })
  ] });
}
export {
  AlternateBufferCLI
};
