import { jsx, jsxs } from "react/jsx-runtime";
import { forwardRef, useEffect, useImperativeHandle, useMemo, useState } from "react";
import { Box, Text } from "ink";
import wrapAnsi from "wrap-ansi";
import { useTerminalSize } from "../../hooks/useTerminalSize.js";
import { getMaxVisibleItemsForTerminalRows } from "../../utils/overlaySizing.js";
import { HintBar } from "../shared/HintBar.js";
const CommandOutputOverlay = forwardRef(function CommandOutputOverlay2({ isVisible, title, content, onClose }, ref) {
  const { columns, rows } = useTerminalSize();
  const viewportLines = useMemo(() => {
    return getMaxVisibleItemsForTerminalRows({
      rows,
      hardCap: 20,
      reservedRows: 10
    });
  }, [rows]);
  const [scrollOffset, setScrollOffset] = useState(0);
  const wrappedLines = useMemo(() => {
    const width = Math.max(20, columns - 2);
    const wrapped = wrapAnsi(content || "", width, {
      hard: true,
      wordWrap: true,
      trim: false
    });
    return wrapped.length > 0 ? wrapped.split("\n") : [];
  }, [content, columns]);
  const maxScrollOffset = useMemo(() => {
    return Math.max(0, wrappedLines.length - viewportLines);
  }, [wrappedLines.length, viewportLines]);
  useEffect(() => {
    setScrollOffset((prev) => Math.min(maxScrollOffset, Math.max(0, prev)));
  }, [maxScrollOffset]);
  useImperativeHandle(
    ref,
    () => ({
      handleInput: (_input, key) => {
        if (!isVisible) return false;
        if (key.escape) {
          onClose();
          return true;
        }
        if (key.upArrow) {
          setScrollOffset((prev) => Math.max(0, prev - 1));
          return true;
        }
        if (key.downArrow) {
          setScrollOffset((prev) => Math.min(maxScrollOffset, prev + 1));
          return true;
        }
        return true;
      }
    }),
    [isVisible, maxScrollOffset, onClose]
  );
  if (!isVisible) return null;
  const visible = wrappedLines.slice(scrollOffset, scrollOffset + viewportLines);
  const hint = wrappedLines.length > viewportLines ? ["\u2191\u2193 scroll", "Esc close"] : ["Esc close"];
  return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", width: columns, children: [
    /* @__PURE__ */ jsx(Box, { paddingX: 0, paddingY: 0, children: /* @__PURE__ */ jsx(Text, { color: "cyan", bold: true, wrap: "truncate-end", children: title }) }),
    /* @__PURE__ */ jsx(Box, { flexDirection: "column", height: viewportLines, marginTop: 1, children: Array.from({ length: viewportLines }, (_, rowIndex) => {
      const line = visible[rowIndex];
      return /* @__PURE__ */ jsx(Box, { paddingX: 0, paddingY: 0, children: /* @__PURE__ */ jsx(Text, { wrap: "truncate-end", children: line ?? " " }) }, `line-${rowIndex}`);
    }) }),
    /* @__PURE__ */ jsx(Box, { paddingX: 0, paddingY: 0, marginTop: 1, children: /* @__PURE__ */ jsx(HintBar, { hints: hint }) })
  ] });
});
export {
  CommandOutputOverlay
};
