/**
 * Sidebar Panel
 * エディターサイドバーパネル（統合版）
 */

import { registerPlugin } from '@wordpress/plugins';
import { PluginSidebar, PluginSidebarMoreMenuItem } from '@wordpress/editor';
import { useEffect, useRef } from '@wordpress/element';
import { useSelect, useDispatch } from '@wordpress/data';
import { __ } from '@wordpress/i18n';
import ZenblocksLogo from '../assets/ZenblocksLogo';
import { ColorSettings } from './site-settings/panels/colors/ColorSettings';
import { TypographySettings } from './site-settings/panels/typography/TypographySettings';
import { ResponsiveSettings } from './site-settings/panels/responsive/ResponsiveSettings';

// ロゴアイコン要素（MenuItem の cloneElement に対応するため要素として定義）
const LogoIcon = <ZenblocksLogo width={ 20 } height={ 20 } />;

const SiteSettingsContent = () => {
	return (
		<div className="zenblocks-sidebar-tabs">
			<ResponsiveSettings initialOpen={ false } />
			<ColorSettings initialOpen={ false } />
			<TypographySettings initialOpen={ false } />
		</div>
	);
};

const ZenblocksSidebar = () => {
	const prevSelectedBlockRef = useRef( null );

	const { selectedBlockClientId, activeGeneralSidebar } = useSelect(
		( select ) => {
			return {
				selectedBlockClientId:
					select( 'core/block-editor' ).getSelectedBlockClientId(),
				activeGeneralSidebar:
					select( 'core/edit-post' ).getActiveGeneralSidebarName(),
			};
		},
		[]
	);

	const { openGeneralSidebar } = useDispatch( 'core/edit-post' );

	useEffect( () => {
		if (
			selectedBlockClientId &&
			selectedBlockClientId !== prevSelectedBlockRef.current &&
			activeGeneralSidebar === 'zenblocks-sidebar/zenblocks-sidebar'
		) {
			openGeneralSidebar( 'edit-post/block' );
		}
		prevSelectedBlockRef.current = selectedBlockClientId;
	}, [ selectedBlockClientId, activeGeneralSidebar, openGeneralSidebar ] );

	return (
		<>
			<PluginSidebarMoreMenuItem
				target="zenblocks-sidebar"
				icon={ LogoIcon }
			>
				{ __( 'ZenBlocks', 'zenblocks' ) }
			</PluginSidebarMoreMenuItem>
			<PluginSidebar
				name="zenblocks-sidebar"
				title={ __( 'Site Settings', 'zenblocks' ) }
				icon={ LogoIcon }
			>
				<SiteSettingsContent />
			</PluginSidebar>
		</>
	);
};

registerPlugin( 'zenblocks-sidebar', {
	render: ZenblocksSidebar,
	icon: LogoIcon,
} );
