import { jsx as _jsx } from "react/jsx-runtime";
import { forwardRef, createContext, useContext, useMemo, useState, useEffect } from 'react';
import styled, { css } from 'styled-components';
import { createPortal } from 'react-dom';
import { defaultThemeProp } from '../../theme';
import { useConfiguration, useConsolidatedRef, useElement, useFocusTrap, useScrollToggle, useTestIds } from '../../hooks';
import Configuration from '../Configuration';
import { withTestIds } from '../../utils';
import { getFullscreenTestIds } from './Fullscreen.test-ids';
export const StyledFullscreen = styled.div(({ theme, fullscreen }) => {
    return css `
      ${fullscreen &&
        css `
        --content-height-in-view: 100vh;
        position: fixed;
        z-index: ${theme.base['z-index'].backdrop};
        inset: 0;
      `}
    `;
});
StyledFullscreen.defaultProps = defaultThemeProp;
export const FullscreenContext = createContext(undefined);
export const useFullscreenContext = () => {
    // Ensure easier/safer destructuring in use
    return useContext(FullscreenContext);
};
const PortalRender = ({ parentJSX, parentElRef }) => {
    const { portalTarget } = useConfiguration();
    useFocusTrap(parentElRef);
    const { disableScroll, enableScroll } = useScrollToggle();
    useEffect(() => {
        disableScroll();
        return enableScroll;
    }, []);
    return portalTarget
        ? createPortal(_jsx(Configuration, { portalTarget: parentElRef.current ?? undefined, children: parentJSX }), portalTarget)
        : null;
};
export default withTestIds(forwardRef(function Fullscreen({ children, testId, ...restProps }, ref) {
    const testIds = useTestIds(testId, getFullscreenTestIds);
    // setParentEl ensures one extra render needed for keeping div passed to PortalRender up to date
    const [parentEl, setParentEl] = useElement(null);
    const parentElRef = useConsolidatedRef(setParentEl, ref);
    const [fullscreen, setFullscreen] = useState(undefined);
    const ctxValue = useMemo(() => {
        return [
            fullscreen,
            () => {
                setFullscreen(cur => !cur);
            }
        ];
    }, [fullscreen]);
    const parentJSX = (_jsx(StyledFullscreen, { "data-testid": testIds.root, ...restProps, ref: parentElRef, fullscreen: !!fullscreen, children: children }));
    return (_jsx(FullscreenContext.Provider, { value: ctxValue, children: fullscreen && parentEl ? (_jsx(PortalRender, { parentJSX: parentJSX, parentElRef: parentElRef })) : (parentJSX) }));
}), getFullscreenTestIds);
//# sourceMappingURL=Fullscreen.js.map