( 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.wppsOpbBlock || {};
	var fieldOptions = config.fields || [ { label: __( '— Select field —', 'wp-powersuite' ), value: '' } ];

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

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

			return createElement(
				'div',
				blockProps,
				createElement(
					InspectorControls,
					null,
					createElement(
						PanelBody,
						{ title: __( 'PowerSuite Option', 'wp-powersuite' ), initialOpen: true },
						createElement( SelectControl, {
							label: __( 'Option Field', 'wp-powersuite' ),
							value: selection,
							options: fieldOptions,
							onChange: function ( value ) {
								var parsed = parseSelection( value );
								setAttributes( {
									pageSlug: parsed.pageSlug,
									fieldId: parsed.fieldId
								} );
							}
						} ),
						createElement( SelectControl, {
							label: __( 'Output', 'wp-powersuite' ),
							value: attributes.format || 'display',
							options: [
								{ label: __( 'Display value', 'wp-powersuite' ), value: 'display' },
								{ label: __( 'Raw stored value', 'wp-powersuite' ), value: 'raw' },
								{ label: __( 'HTML', 'wp-powersuite' ), value: 'html' },
								{ label: __( 'URL', 'wp-powersuite' ), value: 'url' }
							],
							onChange: function ( value ) {
								setAttributes( { format: value } );
							}
						} )
					)
				),
				createElement(
					'div',
					{ className: 'wpps-opb-block-placeholder' },
					selection
						? __( 'PowerSuite option:', 'wp-powersuite' ) + ' ' + selection
						: __( 'Select an option field in the block settings.', 'wp-powersuite' )
				)
			);
		},
		save: function () {
			return null;
		}
	} );
}( window.wp ) );
