/**
 * WordPress dependencies
 */
import { __ } from "@wordpress/i18n";
import { addFilter } from "@wordpress/hooks";

/**
 * Define our blocks for larger reuse.
 */
const variationsBlocks = [
	'personalizewp-pro/variations-block',
	'personalizewp-pro/variation-fallback',
	'personalizewp-pro/variation',
];

/**
 * Add the variations container block as being Personalized to gain the Base indicator status.
 *
 * @param {boolean} display
 * @param {object} props    Block properties
 * @returns {boolean}
 */
addFilter(
	'personalizewp.hasPersonalizeControls',
	'personalizewp/indicate-variation-blocks',
	function( display, props) {
		return ( 'personalizewp-pro/variations-block' === props.name ) || display;
	}
);

/**
 * Add the variation blocks to the Base restricted blocks to suppress the normal PersonalizeWP controls.
 *
 * @param {array} restrictedBlocks
 * @returns {array}
 */
addFilter(
	'personalizeWP.globallyRestrictedBlockTypes',
	'personalizewp/restrict-variation-blocks',
	function( restrictedBlocks ) {
		return [ ...restrictedBlocks, ...variationsBlocks ];
	}
);

/**
 * Ensure all blocks (not Variation ones) inherit the isVariationContent context so as to suppress the normal PersonalizeWP controls.
 *
 * @param {object} settings block settings
 * @param {string} name block name
 * @returns {object} modified settings
 *
 * @see https://developer.wordpress.org/block-editor/reference-guides/filters/block-filters/#blocks-registerblocktype
 */
addFilter(
	'blocks.registerBlockType',
	'personalizewp/register-variations-context',
	function ( settings, name ) {
		// Automatically exclude adding to our blocks.
		if ( ! variationsBlocks.includes( name ) ) {
			settings = {
				...settings,
				usesContext: [ ...settings.usesContext, 'personalizewp/isVariationContent' ],
			};
		}
		return settings;
	},
	100
);

/**
 * Restrict descendent blocks of Variations showing PersonalizeWP controls.
 *
 * @param {null} shouldRender Default null, return non-null to suppress.
 * @param {object} props Complete Block
 */
addFilter(
	'personalizeWP.preRenderControls',
	'personalizewp/restrict-personalize-controls-showing',
	function( shouldRender, props ) {

		if ( props.context['personalizewp/isVariationContent'] ) {
			// Force the removal of normal PersonalizeWP controls.
			return false;
		}
		return shouldRender;
	}
);
