import { jsx } from "react/jsx-runtime";
import { memo, useCallback, useEffect, useMemo, useState } from "react";
import { Spin } from "antd";
import { useRequest } from "../../api-client/index.mjs";
import { useStyles } from "../../schema-component/antd/markdown/style.mjs";
import { useParseMarkdown } from "../../schema-component/antd/markdown/util.mjs";
import { useGlobalTheme } from "../../style/theme/index.mjs";
import { useStyles as external_style_mjs_useStyles } from "./style.mjs";
const PLUGIN_STATICS_PATH = '/static/plugins/';
const PluginDocument = /*#__PURE__*/ memo((props)=>{
    const { isDarkTheme } = useGlobalTheme();
    const { componentCls, hashId } = useStyles({
        isDarkTheme
    });
    const { styles } = external_style_mjs_useStyles();
    const { url, packageName } = props;
    const [docUrl, setDocUrl] = useState(url);
    const { data, loading, error } = useRequest({
        url: docUrl,
        baseURL: '/'
    }, {
        refreshDeps: [
            docUrl
        ]
    });
    const { html, loading: parseLoading } = useParseMarkdown(data);
    const htmlWithOutRelativeDirect = useMemo(()=>{
        if (html) {
            let res = html;
            const pattern = /<a\s+href="\..*?\/([^/]+)"/g;
            res = res.replace(pattern, (match, $1)=>match + 'onclick="return false;"');
            res = res.replace(/src="(.*?)"/g, (match, src)=>{
                if (src.startsWith('http') || src.startsWith('//:')) return match;
                return 'src="'.concat(PLUGIN_STATICS_PATH).concat(packageName, "/").concat(src, '"');
            });
            return res;
        }
        return '';
    }, [
        html,
        packageName
    ]);
    const handleSwitchDocLang = useCallback((e)=>{
        const url = e.target.getAttribute('href');
        if (!url) return;
        const parsedUrl = new URL(docUrl, window.location.origin);
        const combinedUrl = new URL(url, parsedUrl);
        setDocUrl(combinedUrl.pathname);
    }, []);
    useEffect(()=>{
        const md = document.getElementById('pm-md-preview');
        md.addEventListener('click', handleSwitchDocLang);
        return ()=>{
            removeEventListener('click', handleSwitchDocLang);
        };
    }, [
        handleSwitchDocLang
    ]);
    return /*#__PURE__*/ jsx("div", {
        className: styles.PluginDocument,
        id: "pm-md-preview",
        children: loading || parseLoading ? /*#__PURE__*/ jsx(Spin, {}) : /*#__PURE__*/ jsx("div", {
            className: "".concat(componentCls, " ").concat(hashId, " tb-markdown tb-markdown-default tb-markdown-table"),
            dangerouslySetInnerHTML: {
                __html: error ? '' : htmlWithOutRelativeDirect
            }
        })
    });
});
PluginDocument.displayName = 'PluginDocument';
export { PluginDocument };
