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