import React from 'react';
import p from 'prefix-classname';
import { useDragDropManager } from 'react-dnd';
import { CLS_PREFIX, overingNodeSubject, selectedNodeSubject, useLocationAction, locationActionSubject } from '../../../config/const';
import { addModules } from '../../utils/externals-modules';
import { useSharedMap, useSharedUpdateMap, useShared } from '@rcp/use.shared';
const cn = p('');
const c = p(`${CLS_PREFIX}-stage`);
import './style.scss';
import { headerStatusSubject, useHeaderStatus } from '../header';
import { register, addRemoteGlobalThis, removeRemoteGlobalThis, setId } from '../../../../shared/pipe';
import LocationWidget from '../location-widget';
setId(`main`);
const StageContent = React.memo(({ className, externalModules, bundlerURL }) => {
    React.useLayoutEffect(() => !!externalModules && addModules(externalModules), [externalModules]);
    const iframeRef = React.useRef(null);
    React.useEffect(() => {
        var _a;
        if ((_a = iframeRef.current) === null || _a === void 0 ? void 0 : _a.contentWindow) {
            addRemoteGlobalThis(iframeRef.current.contentWindow);
            return () => {
                var _a;
                removeRemoteGlobalThis((_a = iframeRef.current) === null || _a === void 0 ? void 0 : _a.contentWindow);
            };
        }
    }, [iframeRef]);
    const [action, setAction] = useLocationAction();
    React.useLayoutEffect(() => {
        setAction({ action: 'PUSH', url: bundlerURL, outer: true });
    }, [bundlerURL]);
    const [iframeSrc, setIframeSrc] = React.useState(bundlerURL);
    React.useLayoutEffect(() => {
        if (!action) {
            return;
        }
        if (action.url.includes('#')) {
            setIframeSrc(action.url);
            return;
        }
        if (action.outer) {
            setIframeSrc(action.url);
        }
    }, [action]);
    const [{ showLocation }] = useHeaderStatus();
    const [api] = useShared('api');
    const ddManager = useDragDropManager();
    const _sharedMap = useSharedMap();
    const _sharedUpdateMap = useSharedUpdateMap();
    React.useLayoutEffect(() => register('shared', {
        api,
        overingNodeSubject,
        selectedNodeSubject,
        headerStatusSubject,
        locationActionSubject,
        ddManager,
        _sharedMap,
        _sharedUpdateMap
    }), [ddManager, _sharedMap, _sharedUpdateMap, api]);
    return (React.createElement("div", { className: cn(c(), className) },
        !!showLocation && React.createElement(LocationWidget, { iframeRef: iframeRef }),
        React.createElement("iframe", { ref: iframeRef, src: iframeSrc, className: c('__iframe') })));
});
const Stage = (props) => {
    return React.createElement(StageContent, Object.assign({}, props));
};
Stage.defaultProps = {
    bundlerURL: '/bundler.html'
};
export default Stage;
//# sourceMappingURL=index.js.map