import { jsx as _jsx, Fragment as _Fragment } from "react/jsx-runtime";
import React, { Fragment } from 'react';
import markdoc from '@markdoc/markdoc';
import { useAtomValue } from 'jotai';
import DOMPurify from 'dompurify';
import { isString } from '@redocly/theme/core/openapi';
import { Markdown as MarkdownWrapper } from '@redocly/theme/components/Markdown/Markdown';
import { globalOptionsAtom } from '../../jotai/store.js';
const TAGS_NOT_TO_WRAP = ['OpenApiResponse', 'OpenApiRequestBody'];
export const Markdown = ({ source, ast, htmlWrap, markdocOptions: markdocOptionsProps, ...props }) => {
    const options = useAtomValue(globalOptionsAtom);
    if (!source && !ast) {
        return null;
    }
    const markdocOptions = Object.keys(options?.markdocOptions || {}).length
        ? options?.markdocOptions
        : markdocOptionsProps;
    const config = markdocOptions && {
        tags: markdocOptions?.tags,
        nodes: markdocOptions?.nodes,
        partials: markdocOptions?.partials,
        variables: markdocOptions?.variables,
        functions: markdocOptions?.functions,
    };
    const components = markdocOptions && {
        components: markdocOptions?.components,
    };
    let nodes;
    if (source) {
        if (isString(source)) {
            const sanitizeSource = options?.unstable_hooks?.sanitize
                ? options.unstable_hooks?.sanitize?.(source)
                : options?.sanitize
                    ? DOMPurify.sanitize(source)
                    : source;
            const ast = markdoc.parse(sanitizeSource);
            nodes = markdoc.transform(ast, config);
        }
        else {
            const ast = markdoc.Ast.fromJSON(typeof source.result === 'object' ? JSON.stringify(source.result) : source.result);
            if (Array.isArray(ast)) {
                nodes = markdoc.transform(ast, config);
            }
            else {
                nodes = markdoc.transform(ast, config);
            }
        }
    }
    else if (ast) {
        nodes = markdoc.transform(ast, config);
    }
    const htmlRender = (content) => {
        const html = markdoc.renderers.react(content, React, components);
        return _jsx(MarkdownWrapper, { ...props, children: html, as: "div" });
    };
    if (!htmlWrap) {
        return htmlRender(nodes);
    }
    const shouldWrap = (node) => node.attributes?.htmlWrap !== false && !TAGS_NOT_TO_WRAP.includes(node?.name);
    const render = (wrap, content) => (wrap ? htmlWrap(htmlRender(content)) : htmlRender(content));
    nodes = Array.isArray(nodes) ? nodes : nodes.children;
    return (_jsx(_Fragment, { children: nodes.map((item, index) => (_jsx(Fragment, { children: render(shouldWrap(item), item) }, item?.attributes?.id || index))) }));
};
//# sourceMappingURL=Markdown.js.map