( function( wp ) {
    var registerPlugin = wp.plugins.registerPlugin;
    var PluginDocumentSettingPanel = wp.editor.PluginDocumentSettingPanel;
    var SelectControl = wp.components.SelectControl;
    var withSelect = wp.data.withSelect;
    var withDispatch = wp.data.withDispatch;
    var compose = wp.compose.compose;
    var createElement = wp.element.createElement;

    var SidebarLayoutPanel = function( props ) {
        var postType = props.postType;
        // Show panel for both posts and pages.
        if ( 'page' !== postType && 'post' !== postType ) {
            return null;
        }
        
        // Use the localized setting to disable the control if needed.
        var disableControl = false;
        if ( typeof chic_lifestyle_sidebar_settings !== 'undefined' && chic_lifestyle_sidebar_settings.disable_sidebar ) {
            disableControl = true;
        }
        
        return createElement(
            PluginDocumentSettingPanel,
            {
                name: 'chic-lifestyle-sidebar-layout',
                title: 'Sidebar Layout',
                className: 'chic-lifestyle-sidebar-layout'
            },
            createElement( SelectControl, {
                label: 'Choose sidebar layout',
                value: props.sidebarLayout || '',
                options: [
                    { label: 'Default Layout', value: '' },
                    { label: 'No Sidebar', value: 'no-sidebar' },
                    { label: 'Left Sidebar', value: 'left-sidebar' },
                    { label: 'Right Sidebar', value: 'right-sidebar' }
                ],
                onChange: disableControl ? null : props.setSidebarLayout,
                disabled: disableControl,
                __nextHasNoMarginBottom: true
            } )
        );
    };

    var mapSelectToProps = withSelect( function( select ) {
        var meta = select( 'core/editor' ).getEditedPostAttribute( 'meta' );
        var postType = select( 'core/editor' ).getCurrentPostType();
        return {
            sidebarLayout: meta.chic_lifestyle_sidebar_layout,
            postType: postType
        };
    } );

    var mapDispatchToProps = withDispatch( function( dispatch ) {
        return {
            setSidebarLayout: function( newValue ) {
                dispatch( 'core/editor' ).editPost( {
                    meta: { chic_lifestyle_sidebar_layout: newValue }
                } );
            }
        };
    } );

    var SidebarLayoutPanelPlugin = compose(
        mapSelectToProps,
        mapDispatchToProps
    )( SidebarLayoutPanel );

    registerPlugin( 'chic-lifestyle-sidebar-layout', {
        render: SidebarLayoutPanelPlugin
    } );
} )( window.wp );
