( function ( wp ) {
	'use strict';

	if ( ! wp || ! wp.blocks || ! wp.element || ! wp.blockEditor || ! wp.components ) {
		return;
	}

	var registerBlockType = wp.blocks.registerBlockType;
	var createElement = wp.element.createElement;
	var useBlockProps = wp.blockEditor.useBlockProps;
	var InspectorControls = wp.blockEditor.InspectorControls;
	var PanelBody = wp.components.PanelBody;
	var SelectControl = wp.components.SelectControl;
	var __ = wp.i18n.__;
	var config = window.wppsCfBlock || {};
	var fieldOptions = config.fields || [ { label: __( '— Select field —', 'wp-powersuite' ), value: '' } ];

	function parseSelection( selection ) {
		if ( ! selection || selection.indexOf( ':' ) === -1 ) {
			return { groupKey: '', fieldName: '' };
		}
		var parts = selection.split( ':' );
		return {
			groupKey: parts[ 0 ] || '',
			fieldName: parts[ 1 ] || ''
		};
	}

	registerBlockType( 'wp-powersuite/custom-field', {
		edit: function ( props ) {
			var attributes = props.attributes;
			var setAttributes = props.setAttributes;
			var selection = attributes.groupKey && attributes.fieldName
				? attributes.groupKey + ':' + attributes.fieldName
				: '';
			var blockProps = useBlockProps( { className: 'wpps-cf-block-preview' } );

			return createElement(
				'div',
				blockProps,
				createElement(
					InspectorControls,
					null,
					createElement(
						PanelBody,
						{ title: __( 'PowerSuite Custom Field', 'wp-powersuite' ), initialOpen: true },
						createElement( SelectControl, {
							label: __( 'Custom Field', 'wp-powersuite' ),
							value: selection,
							options: fieldOptions,
							onChange: function ( value ) {
								var parsed = parseSelection( value );
								setAttributes( {
									groupKey: parsed.groupKey,
									fieldName: parsed.fieldName
								} );
							}
						} ),
						createElement( SelectControl, {
							label: __( 'Output', 'wp-powersuite' ),
							value: attributes.format || 'display',
							options: [
								{ label: __( 'Display value', 'wp-powersuite' ), value: 'display' },
								{ label: __( 'Plain text', 'wp-powersuite' ), value: 'text' },
								{ label: __( 'HTML', 'wp-powersuite' ), value: 'html' },
								{ label: __( 'URL', 'wp-powersuite' ), value: 'url' },
								{ label: __( 'Raw stored value', 'wp-powersuite' ), value: 'raw' }
							],
							onChange: function ( value ) {
								setAttributes( { format: value } );
							}
						} )
					)
				),
				createElement(
					'p',
					null,
					selection
						? __( 'Custom field:', 'wp-powersuite' ) + ' ' + selection
						: __( 'Select a custom field in the block settings.', 'wp-powersuite' )
				)
			);
		},
		save: function () {
			return null;
		}
	} );
}( window.wp ) );
