/**
 * WordPress dependencies
 */
import { useSelect } from '@wordpress/data';
import { store as blockEditorStore } from '@wordpress/block-editor';
import { Notice } from '@wordpress/components';
import { __ } from '@wordpress/i18n';

/**
 * Internal dependencies
 */
import UserDirectoryContent from './user-directory-content';
import UserDirectoryPlaceholder from './user-directory-placeholder';

const UserDirectoryEdit = (props) => {
	const { clientId, attributes } = props;

	const hasInnerBlocks = useSelect(
		(select) => !!select(blockEditorStore).getBlocks(clientId).length,
		[clientId]
	);

	// Check if Profile block exists on the page
	const hasProfileBlock = useSelect((select) => {
		const { getBlocks } = select(blockEditorStore);
		const checkBlocks = (blocks) => {
			for (const block of blocks) {
				if (block.name === 'wpuf-ud/profile') {
					return true;
				}
				if (block.innerBlocks && block.innerBlocks.length > 0) {
					if (checkBlocks(block.innerBlocks)) {
						return true;
					}
				}
			}
			return false;
		};
		return checkBlocks(getBlocks());
	}, []);

	// Check if layout has been selected
	const hasSelectedLayout = attributes.hasSelectedLayout || false;

	// Show placeholder if no layout selected or no inner blocks
	// BUT if we're switching layouts, always show content component
	// AND if it's a table layout, always show content component (settings-driven)
	const isSwitchingLayout = attributes.isSwitchingLayout || false;
	const isTableLayout = attributes.directory_layout === 'table';
	const showPlaceholder = (!hasSelectedLayout || (!hasInnerBlocks && !isTableLayout)) && !isSwitchingLayout;

	const Component = showPlaceholder ? UserDirectoryPlaceholder : UserDirectoryContent;

	return (
		<>
			{!hasProfileBlock && (
				<Notice status="warning" isDismissible={false}>
					{__('The User Directory block requires the User Profile block to be present on the same page. Please add the User Profile block to enable full functionality.', 'wpuf-pro')}
				</Notice>
			)}
			<Component {...props} />
		</>
	);
};

export default UserDirectoryEdit;
