import React, { useMemo } from "react";
import { FncLeaf } from "../MarkdownEditor/editor/elements/FncLeaf";
var FOOTNOTE_HREF_ID = /user-content-fn-([^#?]+)$/i;
var extractSingleChildText = function extractSingleChildText1(node) {
    if (node === null || node === undefined || node === false) return '';
    if (typeof node === 'string' || typeof node === 'number') return String(node);
    if (Array.isArray(node)) return node.map(extractSingleChildText).join('');
    if (/*#__PURE__*/ React.isValidElement(node) && node.props !== undefined && node.props.children !== undefined && node.props.children !== null) {
        return extractSingleChildText(node.props.children);
    }
    return '';
};
/**
 * 从 GFM 脚注引用 <sup><a href="#user-content-fn-x">…</a></sup> 解析标识符
 */ export var extractFootnoteRefFromSupChildren = function extractFootnoteRefFromSupChildren(children) {
    var _el_props, _el_props1;
    var childArray = React.Children.toArray(children);
    if (childArray.length !== 1) return undefined;
    var only = childArray[0];
    if (!/*#__PURE__*/ React.isValidElement(only)) return undefined;
    var el = only;
    if (typeof el.type !== 'string' || el.type !== 'a') return undefined;
    var href = (_el_props = el.props) === null || _el_props === void 0 ? void 0 : _el_props.href;
    var labelText = extractSingleChildText((_el_props1 = el.props) === null || _el_props1 === void 0 ? void 0 : _el_props1.children);
    if (typeof href === 'string') {
        var m = FOOTNOTE_HREF_ID.exec(href);
        if (m === null || m === void 0 ? void 0 : m[1]) {
            return {
                identifier: decodeURIComponent(m[1]),
                url: href.startsWith('http') ? href : undefined
            };
        }
    }
    if (labelText) {
        return {
            identifier: labelText
        };
    }
    return undefined;
};
/**
 * 将 Markdown hast 中的脚注引用与 Slate 只读路径的 FncLeaf 对齐
 */ export var FncRefForMarkdown = function FncRefForMarkdown(param) {
    var fncProps = param.fncProps, linkConfig = param.linkConfig, identifier = param.identifier, children = param.children, url = param.url;
    var leaf = useMemo(function() {
        return {
            fnc: true,
            text: "[^".concat(identifier, "]"),
            identifier: identifier,
            url: url
        };
    }, [
        identifier,
        url
    ]);
    return /*#__PURE__*/ React.createElement(FncLeaf, {
        attributes: {
            'data-slate-leaf': true
        },
        leaf: leaf,
        text: leaf,
        fncProps: fncProps,
        linkConfig: linkConfig
    }, children);
};
