import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import { memo } from "react";
import { Box, Text } from "ink";
import wrapAnsi from "wrap-ansi";
import {
  ConfigBox,
  StatsBox,
  HelpBox,
  SessionListBox,
  SessionHistoryBox,
  LogConfigBox,
  ShortcutsBox,
  SyspromptBox
} from "./styled-boxes/index.js";
import { ToolResultRenderer } from "../renderers/index.js";
import { MarkdownText } from "../shared/MarkdownText.js";
import { ToolIcon } from "./ToolIcon.js";
import {
  formatToolResultPreview,
  stripAutomationTriggerTags
} from "../../utils/messageFormatting.js";
function stripPlanModeTags(content) {
  const stripped = content.replace(/<plan-mode>[\s\S]*?<\/plan-mode>\s*/g, "");
  return stripped === content ? content : stripped.trim();
}
function formatDuration(ms) {
  const seconds = Math.floor(ms / 1e3);
  const tenths = Math.floor(ms % 1e3 / 100);
  if (seconds < 60) {
    return `${seconds}.${tenths}s`;
  }
  const minutes = Math.floor(seconds / 60);
  const remainingSeconds = seconds % 60;
  if (minutes < 60) {
    return `${minutes}m ${remainingSeconds}s`;
  }
  const hours = Math.floor(minutes / 60);
  const remainingMinutes = minutes % 60;
  return `${hours}h ${remainingMinutes}m`;
}
function formatTime(timestamp) {
  const value = typeof timestamp === "string" ? new Date(timestamp) : timestamp;
  if (Number.isNaN(value.getTime())) {
    return "";
  }
  return value.toLocaleTimeString([], {
    hour: "2-digit",
    minute: "2-digit"
  });
}
function getExternalTriggerColors(source) {
  switch (source) {
    case "scheduler":
      return { background: "#3A235A", foreground: "white" };
    case "a2a":
      return { background: "#0E3B2E", foreground: "white" };
    case "api":
      return { background: "#1E3B5A", foreground: "white" };
    default:
      return { background: "gray", foreground: "white" };
  }
}
function getExternalTriggerSource(label) {
  if (label.startsWith("\u23F0 Scheduled Task")) {
    return "scheduler";
  }
  if (label.startsWith("\u{1F916} A2A Request")) {
    return "a2a";
  }
  if (label.startsWith("\u{1F50C} API Request")) {
    return "api";
  }
  if (label.startsWith("\u{1F4E5} External Request")) {
    return "external";
  }
  return null;
}
function renderExternalTriggerPill(label, timeLabel, source, terminalWidth) {
  const colors = getExternalTriggerColors(source);
  return /* @__PURE__ */ jsx(Box, { marginBottom: 0, width: terminalWidth, children: /* @__PURE__ */ jsxs(
    Box,
    {
      backgroundColor: colors.background,
      paddingX: 1,
      borderStyle: "round",
      borderColor: colors.background,
      flexDirection: "row",
      children: [
        /* @__PURE__ */ jsx(Text, { color: colors.foreground, bold: true, children: label }),
        timeLabel && /* @__PURE__ */ jsx(Box, { marginLeft: 1, children: /* @__PURE__ */ jsx(Text, { color: colors.foreground, children: timeLabel }) })
      ]
    }
  ) });
}
const MessageItem = memo(
  ({ message, terminalWidth = 80, showReasoning = true }) => {
    if (message.styledType && message.styledData) {
      switch (message.styledType) {
        case "config":
          return /* @__PURE__ */ jsx(ConfigBox, { data: message.styledData });
        case "stats":
          return /* @__PURE__ */ jsx(StatsBox, { data: message.styledData });
        case "help":
          return /* @__PURE__ */ jsx(HelpBox, { data: message.styledData });
        case "session-list":
          return /* @__PURE__ */ jsx(SessionListBox, { data: message.styledData });
        case "session-history":
          return /* @__PURE__ */ jsx(SessionHistoryBox, { data: message.styledData });
        case "log-config":
          return /* @__PURE__ */ jsx(LogConfigBox, { data: message.styledData });
        case "run-summary": {
          const data = message.styledData;
          const durationStr = formatDuration(data.durationMs);
          const tokensStr = data.totalTokens >= 1e3 ? `, Used ${(data.totalTokens / 1e3).toFixed(1)}K tokens` : "";
          return /* @__PURE__ */ jsx(Box, { marginTop: 1, marginBottom: 1, width: terminalWidth, children: /* @__PURE__ */ jsxs(Text, { color: "gray", children: [
            "\u2500 Worked for ",
            durationStr,
            tokensStr,
            " \u2500"
          ] }) });
        }
        case "shortcuts":
          return /* @__PURE__ */ jsx(ShortcutsBox, { data: message.styledData });
        case "sysprompt":
          return /* @__PURE__ */ jsx(SyspromptBox, { data: message.styledData });
        case "external-trigger": {
          const data = message.styledData;
          return renderExternalTriggerPill(
            data.label,
            formatTime(data.timestamp),
            data.source,
            terminalWidth
          );
        }
      }
    }
    if (message.role === "user") {
      const prefix = "> ";
      const paddingChars = 2;
      const availableWidth = Math.max(20, terminalWidth - prefix.length - paddingChars);
      const displayContent = stripAutomationTriggerTags(stripPlanModeTags(message.content));
      const wrappedContent = wrapAnsi(displayContent, availableWidth, {
        hard: true,
        wordWrap: true,
        trim: false
      });
      const lines = wrappedContent.split("\n");
      return /* @__PURE__ */ jsx(Box, { flexDirection: "column", marginTop: 1, marginBottom: 0, width: terminalWidth, children: /* @__PURE__ */ jsx(Box, { flexDirection: "column", paddingX: 1, backgroundColor: "gray", children: lines.map((line, i) => /* @__PURE__ */ jsxs(Box, { flexDirection: "row", children: [
        /* @__PURE__ */ jsx(Text, { color: "green", children: i === 0 ? prefix : "  " }),
        /* @__PURE__ */ jsx(Text, { color: "white", children: line })
      ] }, i)) }) });
    }
    if (message.role === "assistant") {
      const hasContent = message.content.trim().length > 0;
      const reasoningBlock = showReasoning && message.reasoning ? /* @__PURE__ */ jsx(Box, { flexDirection: "column", marginBottom: 1, children: /* @__PURE__ */ jsx(MarkdownText, { color: "gray", bulletPrefix: "\u23FA ", children: message.reasoning }) }) : null;
      if (message.isContinuation) {
        return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", width: terminalWidth, children: [
          reasoningBlock,
          hasContent ? /* @__PURE__ */ jsx(MarkdownText, { children: message.content }) : null
        ] });
      }
      return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", marginTop: 1, width: terminalWidth, children: [
        reasoningBlock,
        hasContent ? /* @__PURE__ */ jsx(MarkdownText, { bulletPrefix: "\u23FA ", children: message.content }) : null
      ] });
    }
    if (message.role === "tool") {
      const hasStructuredDisplay = message.toolDisplayData && message.toolContent;
      const isRunning = message.toolStatus === "running";
      const isPending = message.toolStatus === "pending" || message.toolStatus === "pending_approval";
      const subAgentProgress = message.subAgentProgress;
      const contentLines = message.content.split("\n");
      const headerLine = contentLines[0] ?? "";
      const subHeaderLine = contentLines.length > 1 ? contentLines[1] : "";
      const parenIndex = headerLine.indexOf("(");
      const toolName = parenIndex > 0 ? headerLine.slice(0, parenIndex) : headerLine;
      const toolArgs = parenIndex > 0 ? headerLine.slice(parenIndex) : "";
      const statusSuffix = subAgentProgress ? "" : isRunning ? " Running..." : isPending ? " Waiting..." : "";
      const fullToolText = `${toolName}${toolArgs}${statusSuffix}`;
      const iconWidth = 2;
      const availableWidth = Math.max(20, terminalWidth - iconWidth);
      const wrappedToolText = wrapAnsi(fullToolText, availableWidth, {
        hard: true,
        wordWrap: true,
        trim: false
      });
      const toolLines = wrappedToolText.split("\n");
      return /* @__PURE__ */ jsxs(Box, { flexDirection: "column", marginTop: 1, width: terminalWidth, children: [
        toolLines.map((line, i) => /* @__PURE__ */ jsxs(Box, { flexDirection: "row", children: [
          i === 0 ? /* @__PURE__ */ jsx(
            ToolIcon,
            {
              status: message.toolStatus || "finished",
              isError: message.isError ?? false
            }
          ) : /* @__PURE__ */ jsx(Text, { children: "  " }),
          /* @__PURE__ */ jsx(Text, { children: i === 0 ? /* @__PURE__ */ jsxs(Fragment, { children: [
            /* @__PURE__ */ jsx(Text, { bold: true, children: line.slice(0, toolName.length) }),
            /* @__PURE__ */ jsx(Text, { children: line.slice(toolName.length) })
          ] }) : line })
        ] }, i)),
        subHeaderLine && /* @__PURE__ */ jsx(Box, { marginLeft: 2, children: /* @__PURE__ */ jsx(Text, { color: "gray", children: subHeaderLine }) }),
        subAgentProgress && isRunning && /* @__PURE__ */ jsx(Box, { marginLeft: 2, children: /* @__PURE__ */ jsxs(Text, { color: "gray", children: [
          "\u2514\u2500 ",
          subAgentProgress.toolsCalled,
          " tool",
          subAgentProgress.toolsCalled !== 1 ? "s" : "",
          " called | Current:",
          " ",
          subAgentProgress.currentTool,
          subAgentProgress.runtimeAgentId ? ` | Agent: ${subAgentProgress.agentId} (${subAgentProgress.runtimeAgentId})` : ` | Agent: ${subAgentProgress.agentId}`,
          subAgentProgress.tokenUsage && subAgentProgress.tokenUsage.total > 0 ? ` | ${subAgentProgress.tokenUsage.total.toLocaleString()} tokens` : ""
        ] }) }),
        hasStructuredDisplay ? /* @__PURE__ */ jsx(
          ToolResultRenderer,
          {
            display: message.toolDisplayData,
            content: message.toolContent
          }
        ) : message.toolResult && /* @__PURE__ */ jsx(Box, { flexDirection: "column", children: /* @__PURE__ */ jsxs(Text, { color: "gray", children: [
          "\u23BF ",
          formatToolResultPreview(message.toolResult)
        ] }) })
      ] });
    }
    if (message.role === "system") {
      const detectedSource = getExternalTriggerSource(message.content);
      if (detectedSource) {
        return renderExternalTriggerPill(
          message.content,
          null,
          detectedSource,
          terminalWidth
        );
      }
    }
    return /* @__PURE__ */ jsx(Box, { flexDirection: "column", marginBottom: 1, width: terminalWidth, children: /* @__PURE__ */ jsx(Text, { color: "gray", children: message.content }) });
  },
  // Custom comparator: only re-render if message content actually changed
  (prev, next) => {
    return prev.message.id === next.message.id && prev.message.content === next.message.content && prev.message.reasoning === next.message.reasoning && prev.message.role === next.message.role && prev.message.toolStatus === next.message.toolStatus && prev.message.toolResult === next.message.toolResult && prev.message.isStreaming === next.message.isStreaming && prev.message.styledType === next.message.styledType && prev.message.styledData === next.message.styledData && prev.message.isContinuation === next.message.isContinuation && prev.message.isError === next.message.isError && prev.message.toolDisplayData === next.message.toolDisplayData && prev.message.toolContent === next.message.toolContent && prev.terminalWidth === next.terminalWidth && prev.showReasoning === next.showReasoning && prev.message.subAgentProgress?.toolsCalled === next.message.subAgentProgress?.toolsCalled && prev.message.subAgentProgress?.currentTool === next.message.subAgentProgress?.currentTool && prev.message.subAgentProgress?.tokenUsage?.total === next.message.subAgentProgress?.tokenUsage?.total;
  }
);
MessageItem.displayName = "MessageItem";
export {
  MessageItem
};
