import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import { useMemo, useState, useEffect, useRef, useCallback } from "react";
import { Box, Static, Text, useStdout } from "ink";
const CLEAR_TERMINAL = "\x1B[2J\x1B[3J\x1B[H";
import { useCLIState } from "../../hooks/useCLIState.js";
import { useTerminalSize } from "../../hooks/useTerminalSize.js";
import { useGitBranch } from "../../hooks/useGitBranch.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 { InputContainer } from "../../containers/InputContainer.js";
import { OverlayContainer } from "../../containers/OverlayContainer.js";
import { shouldHideStatusChrome } from "../../utils/overlayPresentation.js";
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
  } = useCLIState({
    agent,
    initialSessionId,
    startupInfo,
    initialBypassPermissions
    // No keyboard scroll handler - let terminal handle scrollback
  });
  const branchName = useGitBranch();
  const { write: stdoutWrite } = useStdout();
  const { columns: terminalWidth } = useTerminalSize();
  const [staticRemountKey, setStaticRemountKey] = useState(0);
  const isInitialMount = useRef(true);
  const isInitialShowReasoningMount = useRef(true);
  const inputContainerRef = useRef(null);
  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(
          `StaticCLI.handleSubmitPromptCommand failed: ${error instanceof Error ? error.message : String(error)}`
        );
      }
    },
    [agent]
  );
  const refreshStatic = useCallback(() => {
    stdoutWrite(CLEAR_TERMINAL);
    setStaticRemountKey((prev) => prev + 1);
  }, [stdoutWrite]);
  useEffect(() => {
    if (isInitialMount.current) {
      isInitialMount.current = false;
      return;
    }
    const handler = setTimeout(() => {
      refreshStatic();
    }, 300);
    return () => {
      clearTimeout(handler);
    };
  }, [terminalWidth, refreshStatic]);
  useEffect(() => {
    if (isInitialShowReasoningMount.current) {
      isInitialShowReasoningMount.current = false;
      return;
    }
    refreshStatic();
  }, [ui.showReasoning, refreshStatic]);
  const staticItems = useMemo(() => {
    const items = [
      /* @__PURE__ */ jsx(
        Header,
        {
          modelName: session.modelName,
          sessionId: session.id || void 0,
          hasActiveSession: session.hasActiveSession,
          startupInfo
        },
        "header"
      ),
      ...visibleMessages.map((msg) => /* @__PURE__ */ jsx(
        MessageItem,
        {
          message: msg,
          terminalWidth,
          showReasoning: ui.showReasoning
        },
        msg.id
      ))
    ];
    return items;
  }, [
    visibleMessages,
    session.modelName,
    session.id,
    session.hasActiveSession,
    startupInfo,
    terminalWidth,
    ui.showReasoning
  ]);
  return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", width: terminalWidth, children: [
    /* @__PURE__ */ jsx(Static, { items: staticItems, children: (item) => item }, staticRemountKey),
    pendingMessages.map((message) => /* @__PURE__ */ jsx(
      MessageItem,
      {
        message,
        terminalWidth,
        showReasoning: ui.showReasoning
      },
      message.id
    )),
    dequeuedBuffer.map((message) => /* @__PURE__ */ jsx(
      MessageItem,
      {
        message,
        terminalWidth,
        showReasoning: ui.showReasoning
      },
      message.id
    )),
    /* @__PURE__ */ jsxs(Box, { flexDirection: "column", flexShrink: 0, children: [
      (() => {
        const hideChrome = shouldHideStatusChrome(ui.activeOverlay, approval);
        if (hideChrome) return null;
        return /* @__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
            }
          ),
          /* @__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,
          useStreaming,
          configFilePath
        }
      ),
      /* @__PURE__ */ jsx(
        OverlayContainer,
        {
          ref: overlayContainerRef,
          ui,
          input,
          session,
          approval,
          setInput,
          setUi,
          setSession,
          setMessages,
          setApproval,
          setApprovalQueue,
          agent,
          inputService,
          buffer,
          refreshStatic,
          onSubmitPromptCommand: handleSubmitPromptCommand,
          configFilePath
        }
      ),
      !shouldHideStatusChrome(ui.activeOverlay, approval) && 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)" })
      ] }),
      !shouldHideStatusChrome(ui.activeOverlay, approval) && /* @__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
        }
      ),
      !shouldHideStatusChrome(ui.activeOverlay, approval) && ui.historySearch.isActive && /* @__PURE__ */ jsx(
        HistorySearchBar,
        {
          query: ui.historySearch.query,
          hasMatch: historySearchHasMatch
        }
      )
    ] })
  ] });
}
export {
  StaticCLI
};
