"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var MarkdownText_exports = {};
__export(MarkdownText_exports, {
  MarkdownText: () => MarkdownText,
  RenderInline: () => RenderInline,
  parseInlineMarkdown: () => parseInlineMarkdown
});
module.exports = __toCommonJS(MarkdownText_exports);
var import_jsx_runtime = require("react/jsx-runtime");
var import_react = require("react");
var import_ink = require("ink");
var import_chalk = __toESM(require("chalk"), 1);
var import_wrap_ansi = __toESM(require("wrap-ansi"), 1);
var import_string_width = __toESM(require("string-width"), 1);
var import_cli_highlight = require("cli-highlight");
function parseInlineMarkdown(text) {
  if (!/[*_~`\[<]|https?:\/\//.test(text)) {
    return [{ type: "text", content: text }];
  }
  const segments = [];
  let lastIndex = 0;
  const inlineRegex = /(\*\*[^*]+\*\*|__[^_]+__|`[^`]+`|\*[^*]+\*|_[^_]+_|~~[^~]+~~|\[[^\]]+\]\([^)]+\)|https?:\/\/[^\s<]+)/g;
  let match;
  while ((match = inlineRegex.exec(text)) !== null) {
    if (match.index > lastIndex) {
      segments.push({ type: "text", content: text.slice(lastIndex, match.index) });
    }
    const fullMatch = match[0];
    if (fullMatch.startsWith("**") && fullMatch.endsWith("**") && fullMatch.length > 4) {
      segments.push({ type: "bold", content: fullMatch.slice(2, -2) });
    } else if (fullMatch.startsWith("__") && fullMatch.endsWith("__") && fullMatch.length > 4) {
      segments.push({ type: "bold", content: fullMatch.slice(2, -2) });
    } else if (fullMatch.startsWith("`") && fullMatch.endsWith("`") && fullMatch.length > 2) {
      segments.push({ type: "code", content: fullMatch.slice(1, -1) });
    } else if (fullMatch.startsWith("~~") && fullMatch.endsWith("~~") && fullMatch.length > 4) {
      segments.push({ type: "strikethrough", content: fullMatch.slice(2, -2) });
    } else if (fullMatch.startsWith("*") && fullMatch.endsWith("*") && fullMatch.length > 2) {
      segments.push({ type: "italic", content: fullMatch.slice(1, -1) });
    } else if (fullMatch.startsWith("_") && fullMatch.endsWith("_") && fullMatch.length > 2) {
      segments.push({ type: "italic", content: fullMatch.slice(1, -1) });
    } else if (fullMatch.startsWith("[") && fullMatch.includes("](") && fullMatch.endsWith(")")) {
      const linkMatch = fullMatch.match(/\[([^\]]+)\]\(([^)]+)\)/);
      if (linkMatch && linkMatch[1] && linkMatch[2]) {
        segments.push({ type: "link", content: linkMatch[1], url: linkMatch[2] });
      } else {
        segments.push({ type: "text", content: fullMatch });
      }
    } else if (/^https?:\/\//.test(fullMatch)) {
      segments.push({ type: "url", content: fullMatch });
    } else {
      segments.push({ type: "text", content: fullMatch });
    }
    lastIndex = inlineRegex.lastIndex;
  }
  if (lastIndex < text.length) {
    segments.push({ type: "text", content: text.slice(lastIndex) });
  }
  return segments;
}
function segmentsToAnsi(segments, defaultColor) {
  const colorFn = getChalkColor(defaultColor);
  return segments.map((segment) => {
    switch (segment.type) {
      case "bold":
        return colorFn.bold(segment.content);
      case "code":
        return import_chalk.default.cyan(segment.content);
      case "italic":
        return import_chalk.default.gray(segment.content);
      case "strikethrough":
        return colorFn.strikethrough(segment.content);
      case "link":
        return colorFn(segment.content) + import_chalk.default.blue(` (${segment.url})`);
      case "url":
        return import_chalk.default.blue(segment.content);
      default:
        return colorFn(segment.content);
    }
  }).join("");
}
function getChalkColor(color) {
  switch (color) {
    case "white":
      return import_chalk.default.white;
    case "gray":
      return import_chalk.default.gray;
    case "blue":
      return import_chalk.default.blue;
    case "cyan":
      return import_chalk.default.cyan;
    case "green":
      return import_chalk.default.green;
    case "yellow":
      return import_chalk.default.rgb(255, 165, 0);
    case "orange":
      return import_chalk.default.rgb(255, 165, 0);
    case "red":
      return import_chalk.default.red;
    case "magenta":
      return import_chalk.default.green;
    default:
      return import_chalk.default.white;
  }
}
const WrappedParagraphInternal = ({
  text,
  defaultColor,
  bulletPrefix,
  isFirstParagraph = false
}) => {
  const { stdout } = (0, import_ink.useStdout)();
  const terminalWidth = stdout?.columns ?? 80;
  const wrappedLines = (0, import_react.useMemo)(() => {
    const segments = parseInlineMarkdown(text);
    const ansiString = segmentsToAnsi(segments, defaultColor);
    const prefixWidth = bulletPrefix ? (0, import_string_width.default)(bulletPrefix) : 0;
    const availableWidth = Math.max(20, terminalWidth - prefixWidth);
    const wrapped = (0, import_wrap_ansi.default)(ansiString, availableWidth, {
      hard: false,
      // Don't break in the middle of words
      wordWrap: true,
      // Enable word wrapping
      trim: false
      // Don't trim whitespace
    });
    return wrapped.split("\n");
  }, [text, defaultColor, bulletPrefix, isFirstParagraph, terminalWidth]);
  const indentSpaces = bulletPrefix ? " ".repeat((0, import_string_width.default)(bulletPrefix)) : "";
  return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_jsx_runtime.Fragment, { children: wrappedLines.map((line, i) => {
    const isFirstLine = i === 0;
    const prefix = isFirstLine && isFirstParagraph && bulletPrefix ? bulletPrefix : indentSpaces;
    return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Box, { children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Text, { children: [
      prefix,
      line
    ] }) }, i);
  }) });
};
const WrappedParagraph = (0, import_react.memo)(WrappedParagraphInternal);
const RenderInlineInternal = ({
  text,
  defaultColor = "white",
  bold: baseBold = false
}) => {
  const segments = parseInlineMarkdown(text);
  return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_jsx_runtime.Fragment, { children: segments.map((segment, i) => {
    switch (segment.type) {
      case "bold":
        return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { bold: true, color: defaultColor, children: segment.content }, i);
      case "code":
        return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { bold: baseBold, color: "cyan", children: segment.content }, i);
      case "italic":
        return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { bold: baseBold, color: "gray", children: segment.content }, i);
      case "strikethrough":
        return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { bold: baseBold, strikethrough: true, color: defaultColor, children: segment.content }, i);
      case "link":
        return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Text, { bold: baseBold, color: defaultColor, children: [
          segment.content,
          /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Text, { color: "blue", children: [
            " (",
            segment.url,
            ")"
          ] })
        ] }, i);
      case "url":
        return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { bold: baseBold, color: "blue", children: segment.content }, i);
      default:
        return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { bold: baseBold, color: defaultColor, children: segment.content }, i);
    }
  }) });
};
const RenderInline = (0, import_react.memo)(RenderInlineInternal);
const MarkdownTextInternal = ({
  children,
  color = "white",
  bulletPrefix
}) => {
  if (!children) return null;
  const defaultColor = color;
  const lines = children.split("\n");
  let isFirstContentLine = true;
  const headerRegex = /^(#{1,6})\s+(.*)$/;
  const codeFenceRegex = /^(`{3,}|~{3,})(\w*)$/;
  const ulItemRegex = /^(\s*)([-*+])\s+(.*)$/;
  const olItemRegex = /^(\s*)(\d+)\.\s+(.*)$/;
  const hrRegex = /^(\s*[-*_]\s*){3,}$/;
  const blocks = [];
  let inCodeBlock = false;
  let codeBlockLines = [];
  let codeBlockLang = "";
  let codeBlockFence = "";
  lines.forEach((line, index) => {
    const key = `line-${index}`;
    const trimmedLine = line.trim();
    if (inCodeBlock) {
      const fenceMatch = trimmedLine.match(codeFenceRegex);
      if (fenceMatch && fenceMatch[1] && codeBlockFence[0] && fenceMatch[1][0] === codeBlockFence[0] && fenceMatch[1].length >= codeBlockFence.length) {
        blocks.push(
          /* @__PURE__ */ (0, import_jsx_runtime.jsx)(RenderCodeBlock, { lines: codeBlockLines, language: codeBlockLang }, key)
        );
        inCodeBlock = false;
        codeBlockLines = [];
        codeBlockLang = "";
        codeBlockFence = "";
      } else {
        codeBlockLines.push(line);
      }
      return;
    }
    const codeFenceMatch = trimmedLine.match(codeFenceRegex);
    if (codeFenceMatch && codeFenceMatch[1]) {
      inCodeBlock = true;
      codeBlockFence = codeFenceMatch[1];
      codeBlockLang = codeFenceMatch[2] || "";
      return;
    }
    const headerMatch = line.match(headerRegex);
    if (headerMatch && headerMatch[1] && headerMatch[2] !== void 0) {
      const level = headerMatch[1].length;
      const headerText = headerMatch[2];
      blocks.push(/* @__PURE__ */ (0, import_jsx_runtime.jsx)(RenderHeader, { level, text: headerText }, key));
      return;
    }
    if (hrRegex.test(trimmedLine)) {
      blocks.push(
        /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Box, { children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: "gray", children: "\u2500".repeat(40) }) }, key)
      );
      return;
    }
    const ulMatch = line.match(ulItemRegex);
    if (ulMatch && ulMatch[1] !== void 0 && ulMatch[3] !== void 0) {
      const indent = ulMatch[1].length;
      const itemText = ulMatch[3];
      blocks.push(
        /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
          RenderListItem,
          {
            indent,
            marker: "-",
            text: itemText,
            defaultColor
          },
          key
        )
      );
      return;
    }
    const olMatch = line.match(olItemRegex);
    if (olMatch && olMatch[1] !== void 0 && olMatch[2] && olMatch[3] !== void 0) {
      const indent = olMatch[1].length;
      const number = olMatch[2];
      const itemText = olMatch[3];
      blocks.push(
        /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
          RenderListItem,
          {
            indent,
            marker: `${number}.`,
            text: itemText,
            defaultColor
          },
          key
        )
      );
      return;
    }
    if (trimmedLine.length === 0) {
      blocks.push(/* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Box, { height: 1 }, key));
      return;
    }
    const usePrefix = isFirstContentLine && bulletPrefix;
    blocks.push(
      /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
        WrappedParagraph,
        {
          text: line,
          defaultColor,
          ...bulletPrefix && { bulletPrefix },
          isFirstParagraph: usePrefix ? true : false
        },
        key
      )
    );
    if (usePrefix) {
      isFirstContentLine = false;
    }
  });
  if (inCodeBlock && codeBlockLines.length > 0) {
    blocks.push(
      /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
        RenderCodeBlock,
        {
          lines: codeBlockLines,
          language: codeBlockLang,
          isPending: true
        },
        "code-pending"
      )
    );
  }
  return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Box, { flexDirection: "column", children: blocks });
};
const RenderHeaderInternal = ({ level, text }) => {
  const headerColors = {
    1: "blue",
    2: "cyan",
    3: "white",
    4: "gray",
    5: "gray",
    6: "gray"
  };
  const headerColor = headerColors[level] || "white";
  return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Box, { marginTop: level <= 2 ? 1 : 0, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(RenderInline, { text, defaultColor: headerColor, bold: true }) });
};
const RenderHeader = (0, import_react.memo)(RenderHeaderInternal);
const RenderListItemInternal = ({
  indent,
  marker,
  text,
  defaultColor
}) => {
  const { stdout } = (0, import_ink.useStdout)();
  const terminalWidth = stdout?.columns ?? 80;
  const paddingLeft = Math.floor(indent / 2);
  const markerWithSpace = `${marker} `;
  const markerWidth = (0, import_string_width.default)(markerWithSpace);
  const wrappedLines = (0, import_react.useMemo)(() => {
    const segments = parseInlineMarkdown(text);
    const ansiString = segmentsToAnsi(segments, defaultColor);
    const availableWidth = Math.max(20, terminalWidth - paddingLeft - markerWidth);
    const wrapped = (0, import_wrap_ansi.default)(ansiString, availableWidth, {
      hard: false,
      wordWrap: true,
      trim: false
    });
    return wrapped.split("\n");
  }, [text, defaultColor, terminalWidth, paddingLeft, markerWidth]);
  const continuationIndent = " ".repeat(markerWidth);
  return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Box, { paddingLeft, flexDirection: "column", children: wrappedLines.map((line, i) => /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Box, { flexDirection: "row", children: [
    /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: defaultColor, children: i === 0 ? markerWithSpace : continuationIndent }),
    /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { children: line })
  ] }, i)) });
};
const RenderListItem = (0, import_react.memo)(RenderListItemInternal);
const RenderCodeBlockInternal = ({
  lines,
  language,
  isPending
}) => {
  const highlightedCode = (0, import_react.useMemo)(() => {
    const code = lines.join("\n");
    if (language && (0, import_cli_highlight.supportsLanguage)(language)) {
      try {
        return (0, import_cli_highlight.highlight)(code, { language, ignoreIllegals: true });
      } catch {
        return import_chalk.default.cyan(code);
      }
    }
    if (!language && code.trim()) {
      try {
        return (0, import_cli_highlight.highlight)(code, { ignoreIllegals: true });
      } catch {
        return import_chalk.default.cyan(code);
      }
    }
    return import_chalk.default.cyan(code);
  }, [lines, language]);
  return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Box, { flexDirection: "column", marginTop: 1, marginBottom: 1, children: [
    language && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: "gray", children: language }),
    /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_ink.Box, { flexDirection: "column", paddingLeft: 1, children: [
      /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { children: highlightedCode }),
      isPending && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ink.Text, { color: "gray", children: "..." })
    ] })
  ] });
};
const RenderCodeBlock = (0, import_react.memo)(RenderCodeBlockInternal);
const MarkdownText = (0, import_react.memo)(MarkdownTextInternal);
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  MarkdownText,
  RenderInline,
  parseInlineMarkdown
});
