import { jsx, jsxs } from "react/jsx-runtime";
import { tcx } from "@choiceform/design-system";
import { memo, useId, useMemo } from "react";
import { useMarkdownBlocks } from "./hooks/index.js";
import { mdTv } from "./tv.js";
import { createComponents } from "./components/markdown-renderers.js";
import { MarkdownBlock } from "./components/markdown-block.js";
import { getDefaultFilenameForLanguage } from "./utils/default-filename.js";
import { CodeBlock } from "../code-block/index.js";
function extractLanguage(className) {
  if (!className) return "plaintext";
  const match = className.match(/language-(\w+)/);
  return match ? match[1] : "plaintext";
}
const INITIAL_COMPONENTS = {
  code: function CodeComponent({ className, children, filename, ...props }) {
    const isInline = !props.node?.position?.start?.line || props.node?.position?.start?.line === props.node?.position?.end?.line;
    if (isInline) {
      return /* @__PURE__ */ jsx("code", { ...props, children });
    }
    const language = extractLanguage(className);
    const effectiveFilename = filename ?? getDefaultFilenameForLanguage(language);
    return /* @__PURE__ */ jsxs(
      CodeBlock,
      {
        language,
        filename: effectiveFilename,
        children: [
          /* @__PURE__ */ jsx(CodeBlock.Header, {}),
          /* @__PURE__ */ jsx(CodeBlock.BlockCode, { code: children }),
          /* @__PURE__ */ jsx(CodeBlock.Footer, {})
        ]
      }
    );
  }
};
const Markdown = memo(function Markdown2(props) {
  const { children, id, className, components: customComponents, mode = "default" } = props;
  const generatedId = useId();
  const blockId = id ?? generatedId;
  const blocks = useMarkdownBlocks(children);
  const tv = useMemo(() => mdTv({ mode }), [mode]);
  const tvComponents = useMemo(() => createComponents(tv), [tv]);
  const components = useMemo(() => {
    const base = {
      ...tvComponents,
      ...customComponents,
      ...INITIAL_COMPONENTS
    };
    return base;
  }, [tvComponents, customComponents]);
  return /* @__PURE__ */ jsx("div", { className: tcx(tv.root(), className), children: blocks.map((block, index) => /* @__PURE__ */ jsx(
    MarkdownBlock,
    {
      content: block,
      components
    },
    `${blockId}-block-${index}`
  )) });
});
export {
  Markdown
};
//# sourceMappingURL=markdown.js.map
