/**
 * External dependencies
 */
import clsx from 'clsx';

/**
 * WordPress dependencies
 */
import { __unstableMotion as motion, __unstableAnimatePresence as AnimatePresence, __unstableUseNavigateRegions as useNavigateRegions, SlotFillProvider } from '@wordpress/components';
import { useReducedMotion, useViewportMatch, useResizeObserver, usePrevious } from '@wordpress/compose';
import { __, sprintf } from '@wordpress/i18n';
import { useState, useRef, useEffect } from '@wordpress/element';
import { CommandMenu } from '@wordpress/commands';
import { privateApis as blockEditorPrivateApis } from '@wordpress/block-editor';
import { EditorSnackbars, UnsavedChangesWarning, ErrorBoundary, privateApis as editorPrivateApis } from '@wordpress/editor';
import { privateApis as coreCommandsPrivateApis } from '@wordpress/core-commands';
import { privateApis as routerPrivateApis } from '@wordpress/router';
import { PluginArea } from '@wordpress/plugins';
import { store as noticesStore } from '@wordpress/notices';
import { useDispatch, useSelect } from '@wordpress/data';
import { store as preferencesStore } from '@wordpress/preferences';

/**
 * Internal dependencies
 */
import { default as SiteHub, SiteHubMobile } from '../site-hub';
import ResizableFrame from '../resizable-frame';
import { unlock } from '../../lock-unlock';
import SaveKeyboardShortcut from '../save-keyboard-shortcut';
import { useIsSiteEditorLoading } from './hooks';
import useMovingAnimation from './animation';
import SidebarContent from '../sidebar';
import SaveHub from '../save-hub';
import SavePanel from '../save-panel';
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
const {
  useCommands
} = unlock(coreCommandsPrivateApis);
const {
  useGlobalStyle
} = unlock(blockEditorPrivateApis);
const {
  NavigableRegion,
  GlobalStylesProvider
} = unlock(editorPrivateApis);
const {
  useLocation
} = unlock(routerPrivateApis);
const ANIMATION_DURATION = 0.3;
function Layout() {
  const {
    query,
    name: routeKey,
    areas,
    widths
  } = useLocation();
  const {
    canvas = 'view'
  } = query;
  useCommands();
  const isMobileViewport = useViewportMatch('medium', '<');
  const toggleRef = useRef();
  const navigateRegionsProps = useNavigateRegions();
  const disableMotion = useReducedMotion();
  const [canvasResizer, canvasSize] = useResizeObserver();
  const isEditorLoading = useIsSiteEditorLoading();
  const [isResizableFrameOversized, setIsResizableFrameOversized] = useState(false);
  const animationRef = useMovingAnimation({
    triggerAnimationOnChange: routeKey + '-' + canvas
  });
  const {
    showIconLabels
  } = useSelect(select => {
    return {
      showIconLabels: select(preferencesStore).get('core', 'showIconLabels')
    };
  });
  const [backgroundColor] = useGlobalStyle('color.background');
  const [gradientValue] = useGlobalStyle('color.gradient');
  const previousCanvaMode = usePrevious(canvas);
  useEffect(() => {
    if (previousCanvaMode === 'edit') {
      toggleRef.current?.focus();
    }
    // Should not depend on the previous canvas mode value but the next.
  }, [canvas]);
  return /*#__PURE__*/_jsxs(_Fragment, {
    children: [/*#__PURE__*/_jsx(UnsavedChangesWarning, {}), /*#__PURE__*/_jsx(CommandMenu, {}), canvas === 'view' && /*#__PURE__*/_jsx(SaveKeyboardShortcut, {}), /*#__PURE__*/_jsx("div", {
      ...navigateRegionsProps,
      ref: navigateRegionsProps.ref,
      className: clsx('edit-site-layout', navigateRegionsProps.className, {
        'is-full-canvas': canvas === 'edit',
        'show-icon-labels': showIconLabels
      }),
      children: /*#__PURE__*/_jsxs("div", {
        className: "edit-site-layout__content",
        children: [(!isMobileViewport || !areas.mobile) && /*#__PURE__*/_jsx(NavigableRegion, {
          ariaLabel: __('Navigation'),
          className: "edit-site-layout__sidebar-region",
          children: /*#__PURE__*/_jsx(AnimatePresence, {
            children: canvas === 'view' && /*#__PURE__*/_jsxs(motion.div, {
              initial: {
                opacity: 0
              },
              animate: {
                opacity: 1
              },
              exit: {
                opacity: 0
              },
              transition: {
                type: 'tween',
                duration:
                // Disable transition in mobile to emulate a full page transition.
                disableMotion || isMobileViewport ? 0 : ANIMATION_DURATION,
                ease: 'easeOut'
              },
              className: "edit-site-layout__sidebar",
              children: [/*#__PURE__*/_jsx(SiteHub, {
                ref: toggleRef,
                isTransparent: isResizableFrameOversized
              }), /*#__PURE__*/_jsx(SidebarContent, {
                shouldAnimate: routeKey !== 'styles',
                routeKey: routeKey,
                children: /*#__PURE__*/_jsx(ErrorBoundary, {
                  children: areas.sidebar
                })
              }), /*#__PURE__*/_jsx(SaveHub, {}), /*#__PURE__*/_jsx(SavePanel, {})]
            })
          })
        }), /*#__PURE__*/_jsx(EditorSnackbars, {}), isMobileViewport && areas.mobile && /*#__PURE__*/_jsxs("div", {
          className: "edit-site-layout__mobile",
          children: [canvas !== 'edit' && /*#__PURE__*/_jsx(SidebarContent, {
            routeKey: routeKey,
            children: /*#__PURE__*/_jsx(SiteHubMobile, {
              ref: toggleRef,
              isTransparent: isResizableFrameOversized
            })
          }), /*#__PURE__*/_jsx(ErrorBoundary, {
            children: areas.mobile
          })]
        }), !isMobileViewport && areas.content && canvas !== 'edit' && /*#__PURE__*/_jsx("div", {
          className: "edit-site-layout__area",
          style: {
            maxWidth: widths?.content
          },
          children: /*#__PURE__*/_jsx(ErrorBoundary, {
            children: areas.content
          })
        }), !isMobileViewport && areas.edit && canvas !== 'edit' && /*#__PURE__*/_jsx("div", {
          className: "edit-site-layout__area",
          style: {
            maxWidth: widths?.edit
          },
          children: /*#__PURE__*/_jsx(ErrorBoundary, {
            children: areas.edit
          })
        }), !isMobileViewport && areas.preview && /*#__PURE__*/_jsxs("div", {
          className: "edit-site-layout__canvas-container",
          children: [canvasResizer, !!canvasSize.width && /*#__PURE__*/_jsx("div", {
            className: clsx('edit-site-layout__canvas', {
              'is-right-aligned': isResizableFrameOversized
            }),
            ref: animationRef,
            children: /*#__PURE__*/_jsx(ErrorBoundary, {
              children: /*#__PURE__*/_jsx(ResizableFrame, {
                isReady: !isEditorLoading,
                isFullWidth: canvas === 'edit',
                defaultSize: {
                  width: canvasSize.width - 24 /* $canvas-padding */,
                  height: canvasSize.height
                },
                isOversized: isResizableFrameOversized,
                setIsOversized: setIsResizableFrameOversized,
                innerContentStyle: {
                  background: gradientValue !== null && gradientValue !== void 0 ? gradientValue : backgroundColor
                },
                children: areas.preview
              })
            })
          })]
        })]
      })
    })]
  });
}
export default function LayoutWithGlobalStylesProvider(props) {
  const {
    createErrorNotice
  } = useDispatch(noticesStore);
  function onPluginAreaError(name) {
    createErrorNotice(sprintf(/* translators: %s: plugin name */
    __('The "%s" plugin has encountered an error and cannot be rendered.'), name));
  }
  return /*#__PURE__*/_jsx(SlotFillProvider, {
    children: /*#__PURE__*/_jsxs(GlobalStylesProvider, {
      children: [/*#__PURE__*/_jsx(PluginArea, {
        onError: onPluginAreaError
      }), /*#__PURE__*/_jsx(Layout, {
        ...props
      })]
    })
  });
}
//# sourceMappingURL=index.js.map