import { injectCssIntoNode, injectGlobalStyle } from '../../../../../../internal/style-injector/src/index.mjs';
import React__default, { useRef, useState, useLayoutEffect } from 'react';
import { createPortal } from 'react-dom';
import { useIsMounted__INTERNAL, useStytch } from '../b2c/StytchContext.mjs';
import { noProviderError } from '../utils/errors.mjs';
import { invariant } from '../utils/invariant.mjs';

// Mirrors createB2BComponent and createWebComponent
function createB2CComponent(name, Component) {
    const Wrapped = (props)=>{
        invariant(useIsMounted__INTERNAL(), noProviderError(`<${name} />`));
        const client = useStytch();
        const shadow = props.presentation?.options?.enableShadowDOM ?? props.config?.enableShadowDOM;
        const root = useRef(null);
        const [mountPoint, setMountPoint] = useState();
        useLayoutEffect(()=>{
            if (shadow) {
                if (!root.current || root.current.shadowRoot) return;
                const shadowRoot = root.current.attachShadow({
                    mode: 'open'
                });
                const mountPoint = document.createElement('div');
                shadowRoot.appendChild(injectCssIntoNode());
                shadowRoot.appendChild(mountPoint);
                setMountPoint(mountPoint);
            } else {
                injectGlobalStyle();
            }
        }, [
            shadow
        ]);
        const element = /*#__PURE__*/ React__default.createElement(Component, {
            ...props,
            client: client
        });
        if (shadow) {
            return /*#__PURE__*/ React__default.createElement("div", {
                ref: root
            }, mountPoint && /*#__PURE__*/ createPortal(element, mountPoint));
        } else {
            return element;
        }
    };
    Wrapped.displayName = name;
    return Wrapped;
}

export { createB2CComponent };
//# sourceMappingURL=createB2CComponent.mjs.map
