"use client";
'use strict';

const jsxRuntime = require('react/jsx-runtime');
const utils = require('../lib/utils.cjs');
const React = require('react');
const ReactMarkdown = require('react-markdown');
const rehypeHighlight = require('rehype-highlight');
const rehypeRaw = require('rehype-raw');
const remarkGfm = require('remark-gfm');
const LucideIcons = require('lucide-react');

function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e.default : e; }

const ReactMarkdown__default = /*#__PURE__*/_interopDefaultCompat(ReactMarkdown);
const rehypeHighlight__default = /*#__PURE__*/_interopDefaultCompat(rehypeHighlight);
const rehypeRaw__default = /*#__PURE__*/_interopDefaultCompat(rehypeRaw);
const remarkGfm__default = /*#__PURE__*/_interopDefaultCompat(remarkGfm);

const DefaultLink = (props) => {
  return /* @__PURE__ */ jsxRuntime.jsx("a", { ...props });
};
const DefaultImage = (props) => {
  return /* @__PURE__ */ jsxRuntime.jsx("img", { ...props });
};
function containsMath(markdown) {
  return /\$\$[\s\S]+?\$\$/.test(markdown) || // Display math
  /(?<!\$)\$(?!\$)[^\$\n]+?\$(?!\$)/.test(markdown) || // Inline math (not $$)
  /\\begin\{(equation|align|gather|math)\}/.test(markdown);
}
function slugify(text) {
  return text.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/(^-|-$)/g, "");
}
function getNodeText(node) {
  if (node == null) return "";
  if (typeof node === "string" || typeof node === "number") return String(node);
  if (Array.isArray(node)) return node.map(getNodeText).join("");
  if (React.isValidElement(node)) {
    const props = node.props;
    return getNodeText(props.children);
  }
  return "";
}
function simpleHash(str) {
  let hash = 0;
  for (let i = 0; i < str.length; i++) {
    const char = str.charCodeAt(i);
    hash = (hash << 5) - hash + char;
    hash = hash & hash;
  }
  return Math.abs(hash).toString(36).slice(0, 6);
}
function isCheckboxElement(node) {
  return React.isValidElement(node) && node.type === "input" && node.props.type === "checkbox";
}
function createTaskListItemRenderer() {
  return function LiRenderer(props) {
    const { className, children, ...rest } = props;
    const isTaskItem = (className ?? "").split(" ").includes("task-list-item");
    if (!isTaskItem) {
      return /* @__PURE__ */ jsxRuntime.jsx("li", { className, ...rest, children });
    }
    const childArray = Array.isArray(children) ? children : [children];
    const checkboxNode = childArray.find(isCheckboxElement);
    const nonCheckboxChildren = childArray.filter((c) => !isCheckboxElement(c));
    const labelText = getNodeText(nonCheckboxChildren);
    const baseId = slugify(labelText || "task-item");
    const hashSuffix = simpleHash(labelText || "task-item");
    const uniqueId = `${baseId}-${hashSuffix}`;
    return /* @__PURE__ */ jsxRuntime.jsxs("li", { className, ...rest, children: [
      checkboxNode ? React.createElement(checkboxNode.type, {
        ...checkboxNode.props,
        id: uniqueId,
        "aria-label": labelText || "Task item"
      }) : null,
      /* @__PURE__ */ jsxRuntime.jsx("label", { htmlFor: uniqueId, children: nonCheckboxChildren })
    ] });
  };
}
function createHeadingRenderer(tag) {
  return function HeadingRenderer(props) {
    const { children, ...rest } = props;
    const text = getNodeText(children);
    const id = slugify(text);
    return React.createElement(
      tag,
      { id, ...rest },
      children,
      text ? /* @__PURE__ */ jsxRuntime.jsx(
        "a",
        {
          className: "heading-anchor",
          href: `#${id}`,
          "aria-label": "Link to heading",
          children: "#"
        }
      ) : null
    );
  };
}
function CodeRenderer({ inline, className, children, ...rest }) {
  const hasLanguage = /language-([a-z0-9-]+)/i.test(className ?? "");
  const isInline = inline ?? !hasLanguage;
  if (isInline) {
    return /* @__PURE__ */ jsxRuntime.jsx("code", { className, ...rest, children });
  }
  return /* @__PURE__ */ jsxRuntime.jsx("code", { className, ...rest, children });
}
function PreRenderer(props) {
  const { children, ...rest } = props;
  const child = Array.isArray(children) ? children[0] : children;
  let language;
  if (React.isValidElement(child)) {
    const className = child.props.className;
    const match = /language-([a-z0-9-]+)/i.exec(className ?? "");
    language = match?.[1];
  }
  const label = (language ?? "text").toUpperCase();
  const preRef = React.useRef(null);
  const [copied, setCopied] = React.useState(false);
  const resetTimerRef = React.useRef(null);
  let codeText = "";
  if (React.isValidElement(child)) {
    const childProps = child.props;
    codeText = getNodeText(childProps.children);
  }
  const normalized = codeText.endsWith("\n") ? codeText.slice(0, -1) : codeText;
  const lineCount = Math.max(1, normalized.split("\n").length);
  const digitCount = String(lineCount).length;
  const onCopy = async (e) => {
    e.preventDefault();
    e.stopPropagation();
    try {
      const text = preRef.current?.textContent ?? "";
      if (text && typeof navigator !== "undefined" && navigator.clipboard?.writeText) {
        await navigator.clipboard.writeText(text);
        setCopied(true);
        if (resetTimerRef.current) window.clearTimeout(resetTimerRef.current);
        resetTimerRef.current = window.setTimeout(() => {
          setCopied(false);
          resetTimerRef.current = null;
        }, 2e3);
      }
    } catch {
    }
  };
  return /* @__PURE__ */ jsxRuntime.jsxs(
    "div",
    {
      className: "markdown-code-block",
      style: {
        ["--code-gutter-width"]: `${digitCount + 1}ch`
      },
      children: [
        /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "code-toolbar", children: [
          /* @__PURE__ */ jsxRuntime.jsx("span", { className: "language-label", children: label }),
          /* @__PURE__ */ jsxRuntime.jsx(
            "button",
            {
              type: "button",
              className: "copy-button",
              onClick: onCopy,
              "aria-label": copied ? "Copied" : "Copy code",
              children: copied ? /* @__PURE__ */ jsxRuntime.jsx(LucideIcons.CheckIcon, { size: 16 }) : /* @__PURE__ */ jsxRuntime.jsx(LucideIcons.CopyIcon, { size: 16 })
            }
          )
        ] }),
        /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "code-content", children: [
          /* @__PURE__ */ jsxRuntime.jsx("ol", { className: "line-numbers", "aria-hidden": true, children: Array.from({ length: lineCount }).map((_, idx) => /* @__PURE__ */ jsxRuntime.jsx("li", { children: idx + 1 }, idx + 1)) }),
          /* @__PURE__ */ jsxRuntime.jsx("pre", { ref: preRef, ...rest, children })
        ] })
      ]
    }
  );
}
function MarkdownContent({
  markdown,
  className,
  variant = "default",
  LinkComponent = DefaultLink,
  ImageComponent = DefaultImage
}) {
  const [mathPlugins, setMathPlugins] = React.useState(null);
  const [isLoadingMath, setIsLoadingMath] = React.useState(false);
  const hasMath = React.useMemo(() => containsMath(markdown), [markdown]);
  React.useEffect(() => {
    if (!hasMath || mathPlugins || isLoadingMath) return;
    setIsLoadingMath(true);
    const katexCSSId = "katex-css";
    if (typeof document !== "undefined" && !document.getElementById(katexCSSId)) {
      const link = document.createElement("link");
      link.id = katexCSSId;
      link.rel = "stylesheet";
      link.href = "https://cdn.jsdelivr.net/npm/katex@0.16.11/dist/katex.min.css";
      link.integrity = "sha384-nB0miv6/jRmo5UMMR1wu3Gz6NLsoTkbqJghGIsx//Rlm+ZU03BU6SQNC66uf4l5+";
      link.crossOrigin = "anonymous";
      document.head.appendChild(link);
      const fontDisplayStyleId = "katex-font-display-override";
      if (!document.getElementById(fontDisplayStyleId)) {
        const style = document.createElement("style");
        style.id = fontDisplayStyleId;
        style.textContent = `
					@font-face {
						font-family: 'KaTeX_Main';
						font-style: normal;
						font-weight: normal;
						font-display: swap;
						src: url('https://cdn.jsdelivr.net/npm/katex@0.16.11/dist/fonts/KaTeX_Main-Regular.woff2') format('woff2');
					}
					@font-face {
						font-family: 'KaTeX_Math';
						font-style: italic;
						font-weight: normal;
						font-display: swap;
						src: url('https://cdn.jsdelivr.net/npm/katex@0.16.11/dist/fonts/KaTeX_Math-Italic.woff2') format('woff2');
					}
				`;
        document.head.appendChild(style);
      }
    }
    Promise.all([import('remark-math'), import('rehype-katex')]).then(([remarkMathModule, rehypeKatexModule]) => {
      setMathPlugins({
        remarkMath: remarkMathModule.default,
        rehypeKatex: rehypeKatexModule.default
      });
    }).catch((error) => {
      console.error("Failed to load math plugins:", error);
    }).finally(() => {
      setIsLoadingMath(false);
    });
  }, [hasMath, mathPlugins, isLoadingMath]);
  const AnchorRenderer = React.useMemo(() => {
    return function AnchorRendererComponent(props) {
      const { href = "", children, className: anchorClassName, ...rest } = props;
      return /* @__PURE__ */ jsxRuntime.jsx(LinkComponent, { href, className: anchorClassName, ...rest, children });
    };
  }, [LinkComponent]);
  const ImgRenderer = React.useMemo(() => {
    return function ImgRendererComponent(props) {
      const {
        src = "",
        alt = "",
        className: imgClassName,
        width,
        height,
        style,
        ...rest
      } = props;
      const imageProps = {
        src,
        alt,
        className: imgClassName,
        style,
        ...rest
      };
      if (width != null && height != null) {
        imageProps.width = width;
        imageProps.height = height;
      } else {
        return /* @__PURE__ */ jsxRuntime.jsx("span", { className: "markdown-image-wrapper", children: /* @__PURE__ */ jsxRuntime.jsx(ImageComponent, { ...imageProps }) });
      }
      return /* @__PURE__ */ jsxRuntime.jsx(ImageComponent, { ...imageProps });
    };
  }, [ImageComponent]);
  const components = React.useMemo(() => {
    return {
      a: AnchorRenderer,
      img: ImgRenderer,
      code: CodeRenderer,
      pre: PreRenderer,
      h1: createHeadingRenderer("h1"),
      h2: createHeadingRenderer("h2"),
      h3: createHeadingRenderer("h3"),
      h4: createHeadingRenderer("h4"),
      h5: createHeadingRenderer("h5"),
      h6: createHeadingRenderer("h6"),
      li: createTaskListItemRenderer()
    };
  }, [AnchorRenderer, ImgRenderer]);
  const remarkPlugins = React.useMemo(() => {
    const plugins = [remarkGfm__default];
    if (hasMath && mathPlugins?.remarkMath) {
      plugins.push(mathPlugins.remarkMath);
    }
    return plugins;
  }, [hasMath, mathPlugins]);
  const rehypePlugins = React.useMemo(() => {
    const plugins = [rehypeRaw__default, rehypeHighlight__default];
    if (hasMath && mathPlugins?.rehypeKatex) {
      plugins.push(mathPlugins.rehypeKatex);
    }
    return plugins;
  }, [hasMath, mathPlugins]);
  const variantClass = variant === "chat" ? "markdown-content-chat" : "";
  return /* @__PURE__ */ jsxRuntime.jsx("div", { className: utils.cn("markdown-content", variantClass, className), children: /* @__PURE__ */ jsxRuntime.jsx("div", { className: "markdown-inner", children: /* @__PURE__ */ jsxRuntime.jsx("div", { className: "markdown-body", children: /* @__PURE__ */ jsxRuntime.jsx(
    ReactMarkdown__default,
    {
      remarkPlugins,
      rehypePlugins,
      components,
      children: markdown
    }
  ) }) }) });
}

exports.MarkdownContent = MarkdownContent;
