"use client";
import { jsx, jsxs } from 'react/jsx-runtime';
import { cn } from '../lib/utils.mjs';
import { useState, useMemo, useEffect, createElement, isValidElement, useRef } from 'react';
import ReactMarkdown from 'react-markdown';
import rehypeHighlight from 'rehype-highlight';
import rehypeRaw from 'rehype-raw';
import remarkGfm from 'remark-gfm';
import { CheckIcon, CopyIcon } from 'lucide-react';

const DefaultLink = (props) => {
  return /* @__PURE__ */ jsx("a", { ...props });
};
const DefaultImage = (props) => {
  return /* @__PURE__ */ 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 (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 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__ */ 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__ */ jsxs("li", { className, ...rest, children: [
      checkboxNode ? createElement(checkboxNode.type, {
        ...checkboxNode.props,
        id: uniqueId,
        "aria-label": labelText || "Task item"
      }) : null,
      /* @__PURE__ */ 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 createElement(
      tag,
      { id, ...rest },
      children,
      text ? /* @__PURE__ */ 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__ */ jsx("code", { className, ...rest, children });
  }
  return /* @__PURE__ */ jsx("code", { className, ...rest, children });
}
function PreRenderer(props) {
  const { children, ...rest } = props;
  const child = Array.isArray(children) ? children[0] : children;
  let language;
  if (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 = useRef(null);
  const [copied, setCopied] = useState(false);
  const resetTimerRef = useRef(null);
  let codeText = "";
  if (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__ */ jsxs(
    "div",
    {
      className: "markdown-code-block",
      style: {
        ["--code-gutter-width"]: `${digitCount + 1}ch`
      },
      children: [
        /* @__PURE__ */ jsxs("div", { className: "code-toolbar", children: [
          /* @__PURE__ */ jsx("span", { className: "language-label", children: label }),
          /* @__PURE__ */ jsx(
            "button",
            {
              type: "button",
              className: "copy-button",
              onClick: onCopy,
              "aria-label": copied ? "Copied" : "Copy code",
              children: copied ? /* @__PURE__ */ jsx(CheckIcon, { size: 16 }) : /* @__PURE__ */ jsx(CopyIcon, { size: 16 })
            }
          )
        ] }),
        /* @__PURE__ */ jsxs("div", { className: "code-content", children: [
          /* @__PURE__ */ jsx("ol", { className: "line-numbers", "aria-hidden": true, children: Array.from({ length: lineCount }).map((_, idx) => /* @__PURE__ */ jsx("li", { children: idx + 1 }, idx + 1)) }),
          /* @__PURE__ */ jsx("pre", { ref: preRef, ...rest, children })
        ] })
      ]
    }
  );
}
function MarkdownContent({
  markdown,
  className,
  variant = "default",
  LinkComponent = DefaultLink,
  ImageComponent = DefaultImage
}) {
  const [mathPlugins, setMathPlugins] = useState(null);
  const [isLoadingMath, setIsLoadingMath] = useState(false);
  const hasMath = useMemo(() => containsMath(markdown), [markdown]);
  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 = useMemo(() => {
    return function AnchorRendererComponent(props) {
      const { href = "", children, className: anchorClassName, ...rest } = props;
      return /* @__PURE__ */ jsx(LinkComponent, { href, className: anchorClassName, ...rest, children });
    };
  }, [LinkComponent]);
  const ImgRenderer = 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__ */ jsx("span", { className: "markdown-image-wrapper", children: /* @__PURE__ */ jsx(ImageComponent, { ...imageProps }) });
      }
      return /* @__PURE__ */ jsx(ImageComponent, { ...imageProps });
    };
  }, [ImageComponent]);
  const components = 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 = useMemo(() => {
    const plugins = [remarkGfm];
    if (hasMath && mathPlugins?.remarkMath) {
      plugins.push(mathPlugins.remarkMath);
    }
    return plugins;
  }, [hasMath, mathPlugins]);
  const rehypePlugins = useMemo(() => {
    const plugins = [rehypeRaw, rehypeHighlight];
    if (hasMath && mathPlugins?.rehypeKatex) {
      plugins.push(mathPlugins.rehypeKatex);
    }
    return plugins;
  }, [hasMath, mathPlugins]);
  const variantClass = variant === "chat" ? "markdown-content-chat" : "";
  return /* @__PURE__ */ jsx("div", { className: cn("markdown-content", variantClass, className), children: /* @__PURE__ */ jsx("div", { className: "markdown-inner", children: /* @__PURE__ */ jsx("div", { className: "markdown-body", children: /* @__PURE__ */ jsx(
    ReactMarkdown,
    {
      remarkPlugins,
      rehypePlugins,
      components,
      children: markdown
    }
  ) }) }) });
}

export { MarkdownContent };
