import { CopyOutlined, DownloadOutlined } from "@ant-design/icons";
import { ConfigProvider, theme } from "antd";
import classNames from "clsx";
import copy from "copy-to-clipboard";
import React, { useCallback, useContext, useMemo, useRef } from "react";
import { ActionIconBox } from "../../Components/ActionIconBox";
import { useIntersectionOnce } from "../../Hooks/useIntersectionOnce";
import { useLocale } from "../../I18n";
import { useStyle } from "./style";
import { useMermaidRender } from "./useMermaidRender";
import { createMermaidThemeConfig } from "./utils";
var PRE_STYLE = {
    margin: 0,
    whiteSpace: 'pre-wrap',
    wordBreak: 'break-word'
};
var serializeSvgForFile = function serializeSvgForFile(svg) {
    var clone = svg.cloneNode(true);
    if (!clone.getAttribute('xmlns')) {
        clone.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
    }
    if (!clone.getAttribute('xmlns:xlink')) {
        clone.setAttribute('xmlns:xlink', 'http://www.w3.org/1999/xlink');
    }
    return new XMLSerializer().serializeToString(clone);
};
export var MermaidRendererImpl = function MermaidRendererImpl(props) {
    var context = useContext(ConfigProvider.ConfigContext);
    var locale = useLocale();
    var token = theme.useToken().token;
    var baseCls = (context === null || context === void 0 ? void 0 : context.getPrefixCls('agentic-plugin-mermaid')) || 'plugin-mermaid';
    var _useStyle = useStyle(baseCls), wrapSSR = _useStyle.wrapSSR, hashId = _useStyle.hashId;
    var containerRef = useRef(null);
    var divRef = useRef(null);
    var id = useMemo(function() {
        return 'm' + (Date.now() + Math.ceil(Math.random() * 1000));
    }, []);
    var mermaidTheme = useMemo(function() {
        return createMermaidThemeConfig({
            colorBgContainer: token.colorBgContainer,
            colorBgElevated: token.colorBgElevated,
            colorText: token.colorText,
            colorTextSecondary: token.colorTextSecondary,
            colorBorder: token.colorBorder,
            colorPrimary: token.colorPrimary,
            fontFamily: token.fontFamily
        });
    }, [
        token.colorBgContainer,
        token.colorBgElevated,
        token.colorText,
        token.colorTextSecondary,
        token.colorBorder,
        token.colorPrimary,
        token.fontFamily
    ]);
    var isVisible = useIntersectionOnce(containerRef);
    var _useMermaidRender = useMermaidRender(props.element.value || '', divRef, id, isVisible, {
        colorBgContainer: token.colorBgContainer,
        colorBgElevated: token.colorBgElevated,
        colorText: token.colorText,
        colorTextSecondary: token.colorTextSecondary,
        colorBorder: token.colorBorder,
        colorPrimary: token.colorPrimary,
        fontFamily: token.fontFamily
    }), error = _useMermaidRender.error, renderedCode = _useMermaidRender.renderedCode;
    var isError = useMemo(function() {
        return !!error && !!error.trim();
    }, [
        error
    ]);
    var isRendered = useMemo(function() {
        return !!renderedCode && !isError;
    }, [
        renderedCode,
        isError
    ]);
    var diagramStyle = useMemo(function() {
        return {
            opacity: isRendered ? 1 : 0,
            pointerEvents: isRendered ? 'auto' : 'none',
            width: '100%',
            minHeight: isRendered ? '120px' : '0',
            maxHeight: isRendered ? 'none' : '0',
            height: isRendered ? 'auto' : '0',
            overflow: isRendered ? 'auto' : 'hidden'
        };
    }, [
        isRendered
    ]);
    var code = props.element.value || '';
    var handleCopySource = useCallback(function() {
        if (!code) {
            return;
        }
        copy(code);
    }, [
        code
    ]);
    var handleDownloadSvg = useCallback(function() {
        var root = divRef.current;
        if (!root) {
            return;
        }
        var svg = root.querySelector('[data-mermaid-svg="true"]');
        if (!svg) {
            return;
        }
        var payload = serializeSvgForFile(svg);
        var blob = new Blob([
            payload
        ], {
            type: 'image/svg+xml;charset=utf-8'
        });
        var url = URL.createObjectURL(blob);
        var anchor = document.createElement('a');
        anchor.href = url;
        anchor.download = "mermaid-diagram-".concat(Date.now(), ".svg");
        anchor.rel = 'noopener';
        anchor.click();
        URL.revokeObjectURL(url);
    }, []);
    return wrapSSR(/*#__PURE__*/ React.createElement("div", {
        ref: containerRef,
        className: classNames(baseCls, hashId),
        contentEditable: false,
        "data-mermaid-theme": mermaidTheme.darkMode ? 'dark' : 'light'
    }, /*#__PURE__*/ React.createElement("div", {
        contentEditable: false,
        className: classNames("".concat(baseCls, "-viewport"), hashId),
        "data-mermaid-viewport": "true"
    }, /*#__PURE__*/ React.createElement("div", {
        contentEditable: false,
        ref: divRef,
        className: classNames(hashId),
        style: diagramStyle,
        "data-mermaid-container": "true"
    }), isRendered && /*#__PURE__*/ React.createElement("div", {
        className: classNames("".concat(baseCls, "-toolbar-float"), hashId),
        role: "toolbar",
        "aria-label": "Mermaid diagram actions",
        "data-mermaid-toolbar": true,
        onPointerDown: function onPointerDown(e) {
            e.stopPropagation();
        }
    }, /*#__PURE__*/ React.createElement("span", {
        "data-mermaid-action": "copy-source"
    }, /*#__PURE__*/ React.createElement(ActionIconBox, {
        title: locale.copy,
        borderLess: true,
        noPadding: true,
        onClick: handleCopySource,
        iconStyle: {
            color: token.colorTextSecondary
        }
    }, /*#__PURE__*/ React.createElement(CopyOutlined, null))), /*#__PURE__*/ React.createElement("span", {
        "data-mermaid-action": "download-svg"
    }, /*#__PURE__*/ React.createElement(ActionIconBox, {
        title: locale.download,
        borderLess: true,
        noPadding: true,
        onClick: handleDownloadSvg,
        iconStyle: {
            color: token.colorTextSecondary
        }
    }, /*#__PURE__*/ React.createElement(DownloadOutlined, null))))), error && /*#__PURE__*/ React.createElement("div", {
        className: classNames("".concat(baseCls, "-error"), hashId)
    }, /*#__PURE__*/ React.createElement("pre", {
        style: PRE_STYLE
    }, code)), !renderedCode && !error && /*#__PURE__*/ React.createElement("div", {
        className: classNames("".concat(baseCls, "-empty"), hashId)
    }, /*#__PURE__*/ React.createElement("pre", {
        style: PRE_STYLE
    }, code))));
};
