var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
import React, { useLayoutEffect, useMemo, useState, useContext, useRef, } from 'react';
import { ConfigProvider as NextConfigProvider } from '@alifd/next';
import hoistNonReactStatics from 'hoist-non-react-statics';
import ctx from './ctx';
import { getInitialRefElement } from './utils';
var refElementStyle = {
    width: 0,
    height: 0,
    display: 'none',
};
var NextConfigConsumer = NextConfigProvider.Consumer;
var ConfigProvider = (function (props) {
    var ref = useRef(getInitialRefElement());
    var _a = useState(ref.current), refElement = _a[0], setRefElement = _a[1];
    // 在初次渲染的时候，refElement还没渲染，因此需要在effect中再获取一次
    useLayoutEffect(function () {
        setRefElement(ref.current);
    }, []);
    // 让ConfigProvider内部的组件，都可以拿到ConfigProvider位置的元素
    // 从而可以从这个元素读取cssVar
    var ctxValue = useMemo(function () {
        return {
            refElement: refElement,
        };
    }, [refElement]);
    return (React.createElement(ctx.Provider, { value: ctxValue },
        React.createElement(NextConfigProvider, __assign({}, props)),
        React.createElement(NextConfigConsumer, null, function (config) {
            var _a, _b;
            var prefix = (_b = (_a = props.prefix) !== null && _a !== void 0 ? _a : config === null || config === void 0 ? void 0 : config.prefix) !== null && _b !== void 0 ? _b : 'next-';
            return (React.createElement("div", { className: "".concat(prefix, "css-var-ref-element"), style: refElementStyle, ref: ref }));
        })));
});
ConfigProvider.displayName = 'ExtendedConfigProvider';
ConfigProvider.useRefElement = useRefElement;
hoistNonReactStatics(ConfigProvider, NextConfigProvider);
export default ConfigProvider;
/**
 * 获取微应用根元素
 */
function useRefElement() {
    var _a, _b;
    return (_b = (_a = useContext(ctx)) === null || _a === void 0 ? void 0 : _a.refElement) !== null && _b !== void 0 ? _b : getInitialRefElement();
}
