import React, { useEffect, useState } from 'react';
import classNames from 'classnames';
import { Message, MESSAGE_TYPES } from '../message';
import { ExpandableContent } from '../expandable-content';
import { datarobotCSSClasses } from './markdown-utils';
import { useTranslation } from '../hooks/use-translation';
import { jsx as _jsx } from "react/jsx-runtime";
/** Renders markdown content as HTML with support for GFM, math, and syntax highlighting.
 * @midnight-gray-supported
 * @alpine-light-supported
 */
const Markdown = ({
  children,
  className,
  maxHeight
}) => {
  const [html, setHtml] = useState('');
  const [error, setError] = useState('');
  const {
    t
  } = useTranslation();
  const clearPrevChildrenState = () => {
    if (error) {
      setError('');
    }
    if (html) {
      setHtml('');
    }
  };
  useEffect(() => {
    clearPrevChildrenState();
    Promise.all([import(/* webpackChunkName: "unified" */'unified'), import(/* webpackChunkName: "remark-gfm" */'remark-gfm'), import(/* webpackChunkName: "remark-parse" */'remark-parse'), import(/* webpackChunkName: "remark-rehype" */'remark-rehype'), import(/* webpackChunkName: "rehype-sanitize" */'rehype-sanitize'), import(/* webpackChunkName: "rehype-stringify" */'rehype-stringify'), import(/* webpackChunkName: "rehype-highlight" */'rehype-highlight'), import(/* webpackChunkName: "rehype-katex" */'rehype-katex'), import(/* webpackChunkName: "remark-math" */'remark-math')]).then(([{
      unified
    }, {
      default: remarkGfm
    }, {
      default: remarkParse
    }, {
      default: remarkRehype
    }, {
      default: rehypeSanitize
    }, {
      default: rehypeStringify
    }, {
      default: rehypeHighlight
    }, {
      default: rehypeKatex
    }, {
      default: remarkMath
    }]) => {
      unified().use(remarkParse, {
        fragment: true
      })
      // Remark plugins:
      .use(remarkMath).use(remarkGfm).use(remarkRehype)
      // Rehype plugins:
      .use(rehypeSanitize).use(rehypeKatex, {
        output: 'html'
      }).use(rehypeHighlight).use(datarobotCSSClasses).use(rehypeStringify).process(children).then(result => {
        setHtml(result.toString());
      });
    }).catch(err => {
      setError(err);
    });
  }, [children]);
  if (error) {
    return /*#__PURE__*/_jsx(Message, {
      type: MESSAGE_TYPES.ERROR,
      children: t('Something went wrong processing response from the model. Try reloading the page.')
    });
  }
  if (!html) {
    return null;
  }
  const content = /*#__PURE__*/_jsx("div", {
    className: classNames('markdown', className),
    dangerouslySetInnerHTML: {
      __html: String(html)
    }
  });
  if (maxHeight !== undefined) {
    return /*#__PURE__*/_jsx(ExpandableContent, {
      maxHeight: maxHeight,
      children: content
    });
  }
  return content;
};
export { Markdown };