import { useSelect, useDispatch } from '@wordpress/data';
import { useEffect } from '@wordpress/element';
import { InterfaceSkeleton, FullscreenMode, ComplementaryArea, store as interfaceStore } from '@wordpress/interface';
import { BlockBreadcrumb, BlockCanvas, store as blockEditorStore } from '@wordpress/block-editor';

import Sidebar from './Sidebar';

export default function BlockEditor() {
		const { styles, sidebarIsOpen, hasBlockSelected } = useSelect(( select ) => {
				const { getSettings, getBlockSelectionStart } = select( blockEditorStore );
				const { getActiveComplementaryArea } = select( interfaceStore );
				return {
						styles: getSettings().styles,
						hasBlockSelected: !!getBlockSelectionStart(),
						sidebarIsOpen: !!getActiveComplementaryArea( 'tipus/editor' )
				};
		}, []);

		const { enableComplementaryArea, disableComplementaryArea } = useDispatch( interfaceStore );
		useEffect(() => {
				if (hasBlockSelected) {
						enableComplementaryArea( 'tipus/editor', 'edit-post/block' );
				} else {
						disableComplementaryArea( 'tipus/editor' );
				}
		}, [ hasBlockSelected ]);

		return (
				<>
						<FullscreenMode isActive={ true } />
						<Sidebar />
						<InterfaceSkeleton
								content={ <BlockCanvas height="100%" styles={styles} /> }
								sidebar={ sidebarIsOpen && <ComplementaryArea.Slot scope="tipus/editor" /> }
								footer={ <BlockBreadcrumb /> }
						/>
				</>
		);
}
