import { jsx, jsxs } from "react/jsx-runtime";
import { useState, useEffect, forwardRef, useImperativeHandle } from "react";
import { Box, Text } from "ink";
const BREAKDOWN_ITEMS = [
  "systemPrompt",
  "tools",
  "messages",
  "freeSpace",
  "autoCompactBuffer"
];
const ITEM_COLORS = {
  systemPrompt: "cyan",
  tools: "yellow",
  messages: "blue",
  freeSpace: "gray",
  autoCompactBuffer: "magenta"
};
function formatTokens(tokens) {
  if (tokens >= 1e3) {
    return `${(tokens / 1e3).toFixed(1)}k`;
  }
  return tokens.toLocaleString();
}
function createStackedBar(breakdown, maxContextTokens, thresholdPercent, totalWidth = 40) {
  const segments = [];
  const autoCompactBuffer = thresholdPercent > 0 && thresholdPercent < 1 ? Math.floor(maxContextTokens * (1 - thresholdPercent) / thresholdPercent) : 0;
  const totalTokenSpace = maxContextTokens + autoCompactBuffer;
  const usedTokens = breakdown.systemPrompt + breakdown.tools.total + breakdown.messages;
  const freeTokens = Math.max(0, maxContextTokens - usedTokens);
  const getWidth = (tokens) => {
    if (tokens <= 0) return 0;
    const proportional = Math.round(tokens / totalTokenSpace * totalWidth);
    return Math.max(1, proportional);
  };
  const sysWidth = getWidth(breakdown.systemPrompt);
  const toolsWidth = getWidth(breakdown.tools.total);
  const msgsWidth = getWidth(breakdown.messages);
  const freeWidth = getWidth(freeTokens);
  const reservedWidth = getWidth(autoCompactBuffer);
  const totalUsed = sysWidth + toolsWidth + msgsWidth + freeWidth + reservedWidth;
  const adjustment = totalUsed - totalWidth;
  const adjustedFreeWidth = Math.max(0, freeWidth - adjustment);
  if (sysWidth > 0) {
    segments.push({
      char: "\u2588",
      color: ITEM_COLORS.systemPrompt,
      width: sysWidth,
      item: "systemPrompt"
    });
  }
  if (toolsWidth > 0) {
    segments.push({ char: "\u2588", color: ITEM_COLORS.tools, width: toolsWidth, item: "tools" });
  }
  if (msgsWidth > 0) {
    segments.push({
      char: "\u2588",
      color: ITEM_COLORS.messages,
      width: msgsWidth,
      item: "messages"
    });
  }
  if (adjustedFreeWidth > 0) {
    segments.push({ char: "\u2591", color: "gray", width: adjustedFreeWidth, item: "freeSpace" });
  }
  if (reservedWidth > 0) {
    segments.push({
      char: "\u2592",
      color: ITEM_COLORS.autoCompactBuffer,
      width: reservedWidth,
      item: "autoCompactBuffer"
    });
  }
  return segments;
}
const ContextStatsOverlay = forwardRef(
  function ContextStatsOverlay2({ isVisible, onClose, agent, sessionId }, ref) {
    const [stats, setStats] = useState(null);
    const [isLoading, setIsLoading] = useState(false);
    const [error, setError] = useState(null);
    const [selectedIndex, setSelectedIndex] = useState(0);
    const [expandedSections, setExpandedSections] = useState(/* @__PURE__ */ new Set());
    useEffect(() => {
      if (!isVisible) {
        setStats(null);
        setError(null);
        setSelectedIndex(0);
        setExpandedSections(/* @__PURE__ */ new Set());
        return;
      }
      let cancelled = false;
      setIsLoading(true);
      const fetchStats = async () => {
        try {
          const contextStats = await agent.getContextStats(sessionId);
          if (!cancelled) {
            setStats(contextStats);
            setIsLoading(false);
          }
        } catch (err) {
          if (!cancelled) {
            setError(err instanceof Error ? err.message : String(err));
            setIsLoading(false);
          }
        }
      };
      fetchStats();
      return () => {
        cancelled = true;
      };
    }, [isVisible, agent, sessionId]);
    useImperativeHandle(
      ref,
      () => ({
        handleInput: (_input, key) => {
          if (!isVisible) return false;
          if (key.escape || _input === "q") {
            onClose();
            return true;
          }
          if (key.upArrow) {
            setSelectedIndex((prev) => Math.max(0, prev - 1));
            return true;
          }
          if (key.downArrow) {
            setSelectedIndex((prev) => Math.min(BREAKDOWN_ITEMS.length - 1, prev + 1));
            return true;
          }
          if (key.return) {
            const item = BREAKDOWN_ITEMS[selectedIndex];
            if (item === "tools") {
              setExpandedSections((prev) => {
                const next = new Set(prev);
                if (next.has(item)) {
                  next.delete(item);
                } else {
                  next.add(item);
                }
                return next;
              });
              return true;
            }
          }
          return false;
        }
      }),
      [isVisible, onClose, selectedIndex]
    );
    if (!isVisible) return null;
    if (isLoading) {
      return /* @__PURE__ */ jsxs(
        Box,
        {
          flexDirection: "column",
          borderStyle: "round",
          borderColor: "cyan",
          paddingX: 2,
          paddingY: 1,
          children: [
            /* @__PURE__ */ jsx(Text, { color: "cyan", bold: true, children: "\u{1F4CA} Context Usage" }),
            /* @__PURE__ */ jsx(Text, { color: "gray", children: "Loading..." })
          ]
        }
      );
    }
    if (error) {
      return /* @__PURE__ */ jsxs(
        Box,
        {
          flexDirection: "column",
          borderStyle: "round",
          borderColor: "red",
          paddingX: 2,
          paddingY: 1,
          children: [
            /* @__PURE__ */ jsx(Text, { color: "red", bold: true, children: "Error" }),
            /* @__PURE__ */ jsx(Text, { color: "gray", children: error }),
            /* @__PURE__ */ jsx(Box, { marginTop: 1, children: /* @__PURE__ */ jsx(Text, { color: "gray", dimColor: true, children: "Press Esc to close" }) })
          ]
        }
      );
    }
    if (!stats) return null;
    const autoCompactBuffer = stats.thresholdPercent > 0 && stats.thresholdPercent < 1 ? Math.floor(
      stats.maxContextTokens * (1 - stats.thresholdPercent) / stats.thresholdPercent
    ) : 0;
    const totalTokenSpace = stats.maxContextTokens + autoCompactBuffer;
    const pct = (tokens) => {
      const percent = totalTokenSpace > 0 ? (tokens / totalTokenSpace * 100).toFixed(1) : "0.0";
      return `${percent}%`;
    };
    const usedTokens = stats.estimatedTokens + autoCompactBuffer;
    const tokenDisplay = `~${formatTokens(usedTokens)}`;
    const isToolsExpanded = expandedSections.has("tools");
    const barSegments = createStackedBar(
      stats.breakdown,
      stats.maxContextTokens,
      stats.thresholdPercent
    );
    const renderRow = (index, item, label, tokens, isLast, expandable) => {
      const isSelected = selectedIndex === index;
      const prefix = isLast ? "\u2514\u2500" : "\u251C\u2500";
      const expandIcon = expandable ? isToolsExpanded ? "\u25BC" : "\u25B6" : " ";
      const itemColor = ITEM_COLORS[item];
      const indicator = item === "freeSpace" ? "\u2591" : item === "autoCompactBuffer" ? "\u2592" : "\u2588";
      return /* @__PURE__ */ jsxs(Box, { children: [
        /* @__PURE__ */ jsxs(Text, { color: isSelected ? "white" : "gray", children: [
          prefix,
          " "
        ] }),
        /* @__PURE__ */ jsx(Text, { color: itemColor, bold: isSelected, children: indicator }),
        /* @__PURE__ */ jsxs(Text, { color: isSelected ? "white" : "gray", bold: isSelected, children: [
          " ",
          expandIcon,
          " ",
          label,
          ": ",
          formatTokens(tokens),
          " (",
          pct(tokens),
          ")"
        ] }),
        isSelected && expandable && /* @__PURE__ */ jsxs(Text, { color: "gray", dimColor: true, children: [
          " ",
          "(Enter to ",
          isToolsExpanded ? "collapse" : "expand",
          ")"
        ] })
      ] }, item);
    };
    const freeTokens = Math.max(0, stats.maxContextTokens - stats.estimatedTokens);
    const bufferPercent = Math.round((1 - stats.thresholdPercent) * 100);
    return /* @__PURE__ */ jsxs(
      Box,
      {
        flexDirection: "column",
        borderStyle: "round",
        borderColor: "cyan",
        paddingX: 2,
        paddingY: 1,
        children: [
          /* @__PURE__ */ jsxs(Box, { marginBottom: 1, children: [
            /* @__PURE__ */ jsx(Text, { color: "cyan", bold: true, children: "\u{1F4CA} Context Usage" }),
            /* @__PURE__ */ jsxs(Text, { color: "gray", children: [
              " - ",
              stats.modelDisplayName
            ] })
          ] }),
          /* @__PURE__ */ jsx(Box, { children: barSegments.map((segment, idx) => {
            const isHighlighted = BREAKDOWN_ITEMS[selectedIndex] === segment.item;
            return /* @__PURE__ */ jsx(Text, { color: "white", children: isHighlighted ? "\u25BC".repeat(segment.width) : " ".repeat(segment.width) }, idx);
          }) }),
          /* @__PURE__ */ jsx(Box, { children: barSegments.map((segment, idx) => /* @__PURE__ */ jsx(Text, { color: segment.color, children: segment.char.repeat(segment.width) }, idx)) }),
          /* @__PURE__ */ jsxs(Box, { marginBottom: 1, children: [
            /* @__PURE__ */ jsxs(Text, { color: "gray", children: [
              tokenDisplay,
              " / ",
              formatTokens(totalTokenSpace),
              " tokens"
            ] }),
            /* @__PURE__ */ jsx(Text, { color: "gray", children: " \u2022 " }),
            /* @__PURE__ */ jsxs(
              Text,
              {
                color: stats.usagePercent > 80 ? "red" : stats.usagePercent > 60 ? "yellow" : "green",
                children: [
                  stats.usagePercent,
                  "% used"
                ]
              }
            )
          ] }),
          /* @__PURE__ */ jsxs(Box, { flexDirection: "column", children: [
            /* @__PURE__ */ jsx(Text, { color: "white", children: "Breakdown:" }),
            renderRow(
              0,
              "systemPrompt",
              "System prompt",
              stats.breakdown.systemPrompt,
              false
            ),
            renderRow(
              1,
              "tools",
              `Tools (${stats.breakdown.tools.perTool.length})`,
              stats.breakdown.tools.total,
              false,
              true
            ),
            isToolsExpanded && /* @__PURE__ */ jsx(Box, { flexDirection: "column", marginLeft: 4, children: stats.breakdown.tools.perTool.length === 0 ? /* @__PURE__ */ jsx(Text, { color: "gray", dimColor: true, children: "No tools registered" }) : [...stats.breakdown.tools.perTool].sort((a, b) => b.tokens - a.tokens).map((tool, idx, arr) => /* @__PURE__ */ jsxs(Text, { color: "gray", dimColor: true, children: [
              idx === arr.length - 1 ? "\u2514\u2500" : "\u251C\u2500",
              " ",
              /* @__PURE__ */ jsx(Text, { color: "yellow", dimColor: true, children: tool.name }),
              ": ",
              formatTokens(tool.tokens),
              " (",
              pct(tool.tokens),
              ")"
            ] }, tool.name)) }),
            renderRow(2, "messages", "Messages", stats.breakdown.messages, false),
            renderRow(3, "freeSpace", "Free space", freeTokens, false),
            renderRow(
              4,
              "autoCompactBuffer",
              bufferPercent > 0 ? `Auto compact buffer (${bufferPercent}%)` : "Auto compact buffer",
              autoCompactBuffer,
              true
            )
          ] }),
          /* @__PURE__ */ jsxs(Box, { marginTop: 1, flexDirection: "column", children: [
            /* @__PURE__ */ jsxs(Text, { color: "gray", children: [
              "Messages: ",
              stats.filteredMessageCount,
              " visible (",
              stats.messageCount,
              " total)"
            ] }),
            stats.prunedToolCount > 0 && /* @__PURE__ */ jsxs(Text, { color: "yellow", children: [
              "\u{1F5D1}\uFE0F ",
              stats.prunedToolCount,
              " tool output(s) pruned"
            ] }),
            stats.hasSummary && /* @__PURE__ */ jsx(Text, { color: "blue", children: "\u{1F4E6} Context has been compacted (summary present)" }),
            stats.usagePercent > 100 && /* @__PURE__ */ jsx(Text, { color: "yellow", children: "\u{1F4A1} Use /compact to manually compact, or send a message to trigger auto-compaction" })
          ] }),
          /* @__PURE__ */ jsx(Box, { marginTop: 1, children: /* @__PURE__ */ jsx(Text, { color: "gray", dimColor: true, children: "\u2191\u2193: navigate | Enter: expand/collapse | Esc: close" }) })
        ]
      }
    );
  }
);
var ContextStatsOverlay_default = ContextStatsOverlay;
export {
  ContextStatsOverlay_default as default
};
