(function (wp) {
	'use strict';

	var registerBlockType = wp.blocks.registerBlockType;
	var useBlockProps = wp.blockEditor.useBlockProps;
	var InspectorControls = wp.blockEditor.InspectorControls;
	var useSelect = wp.data.useSelect;
	var ServerSideRender = wp.serverSideRender
		? wp.serverSideRender.default || wp.serverSideRender
		: null;
	var el = wp.element.createElement;
	var Fragment = wp.element.Fragment;
	var PanelBody = wp.components.PanelBody;
	var SelectControl = wp.components.SelectControl;
	var TextControl = wp.components.TextControl;
	var Placeholder = wp.components.Placeholder;
	var Spinner = wp.components.Spinner;
	var __ = wp.i18n.__;

	function productOptions(products) {
		var options = [{ label: __('Select a product…', 'dude-commerce'), value: 0 }];
		(products || []).forEach(function (product) {
			options.push({
				label:
					product.title && product.title.rendered
						? product.title.rendered.replace(/<[^>]+>/g, '')
						: '#' + product.id,
				value: product.id
			});
		});
		return options;
	}

	function Edit(props) {
		var attributes = props.attributes;
		var setAttributes = props.setAttributes;
		var blockProps = useBlockProps();
		var productsQuery = useSelect(function (select) {
			return select('core').getEntityRecords('postType', 'wpdude_dc_product', {
				per_page: 100,
				status: 'publish',
				orderby: 'title',
				order: 'asc'
			});
		}, []);
		var isLoading = productsQuery === null;

		var inspector = el(
			InspectorControls,
			null,
			el(
				PanelBody,
				{ title: __('Product settings', 'dude-commerce'), initialOpen: true },
				isLoading
					? el(Spinner, null)
					: el(SelectControl, {
							label: __('Product', 'dude-commerce'),
							value: attributes.productId || 0,
							options: productOptions(productsQuery),
							onChange: function (value) {
								setAttributes({ productId: parseInt(value, 10) || 0 });
							}
					  }),
				el(TextControl, {
					label: __('Button label', 'dude-commerce'),
					value: attributes.buttonText || '',
					help: __('Leave blank for “Buy Now”.', 'dude-commerce'),
					onChange: function (value) {
						setAttributes({ buttonText: value });
					}
				})
			)
		);

		var preview;
		if (!attributes.productId) {
			preview = el(Placeholder, {
				icon: 'cart',
				label: __('Dude Commerce Buy Now', 'dude-commerce'),
				instructions: __('Choose a product in the block sidebar.', 'dude-commerce')
			});
		} else if (ServerSideRender) {
			preview = el(ServerSideRender, {
				block: 'dude-commerce/buy',
				attributes: attributes
			});
		} else {
			preview = el('p', null, __('Preview unavailable.', 'dude-commerce'));
		}

		return el(Fragment, null, inspector, el('div', blockProps, preview));
	}

	registerBlockType('dude-commerce/buy', {
		edit: Edit,
		save: function () {
			return null;
		}
	});
})(window.wp);
