/**
 * Gutenberg-Block "Leadlotse Formular" (Etappe 3).
 *
 * No-Build-Block: nutzt die globalen wp.*-Objekte und wp.element.createElement
 * statt JSX/ESM. So braucht der Block keinen Webpack-Build und keine Node-
 * Toolchain zur Auslieferung (siehe DECISIONS.md D13). Der Block referenziert
 * nur die Formular-ID (D4); gerendert wird serverseitig ueber dieselbe Pipeline
 * wie der Shortcode [leadlotse id="..."].
 */
( function ( wp ) {
	'use strict';

	var el = wp.element.createElement;
	var useState = wp.element.useState;
	var useEffect = wp.element.useEffect;
	var __ = wp.i18n.__;
	var registerBlockType = wp.blocks.registerBlockType;
	var useBlockProps = wp.blockEditor.useBlockProps;
	var InspectorControls = wp.blockEditor.InspectorControls;
	var PanelBody = wp.components.PanelBody;
	var SelectControl = wp.components.SelectControl;
	var Placeholder = wp.components.Placeholder;
	var Spinner = wp.components.Spinner;
	var apiFetch = wp.apiFetch;
	var ServerSideRender = wp.serverSideRender;

	var BLOCK_NAME = 'leadlotse/form-embed';

	/**
	 * Laedt die Formularliste einmalig ueber die REST-API leadlotse/v1/forms.
	 *
	 * @return {Object} { forms, loading, error }
	 */
	function useForms() {
		var forms = useState( [] );
		var loading = useState( true );
		var error = useState( false );

		useEffect( function () {
			var cancelled = false;
			apiFetch( { path: '/leadlotse/v1/forms?per_page=100' } )
				.then( function ( items ) {
					if ( ! cancelled ) {
						forms[ 1 ]( Array.isArray( items ) ? items : [] );
						loading[ 1 ]( false );
					}
				} )
				.catch( function () {
					if ( ! cancelled ) {
						error[ 1 ]( true );
						loading[ 1 ]( false );
					}
				} );
			return function () {
				cancelled = true;
			};
		}, [] );

		return { forms: forms[ 0 ], loading: loading[ 0 ], error: error[ 0 ] };
	}

	function Edit( props ) {
		var formId = props.attributes.formId;
		var state = useForms();
		var blockProps = useBlockProps();

		var options = [
			{ value: 0, label: __( 'Formular waehlen', 'leadlotse' ) },
		].concat(
			state.forms.map( function ( form ) {
				return {
					value: form.id,
					label:
						form.title +
						( form.status !== 'publish'
							? ' (' + __( 'Entwurf', 'leadlotse' ) + ')'
							: '' ),
				};
			} )
		);

		var selector = el( SelectControl, {
			label: __( 'Formular', 'leadlotse' ),
			value: formId,
			options: options,
			onChange: function ( value ) {
				props.setAttributes( { formId: parseInt( value, 10 ) || 0 } );
			},
			disabled: state.loading,
			__nextHasNoMarginBottom: true,
		} );

		var content;
		if ( formId > 0 ) {
			content = el( ServerSideRender, {
				block: BLOCK_NAME,
				attributes: { formId: formId },
			} );
		} else {
			content = el(
				Placeholder,
				{
					icon: 'feedback',
					label: __( 'Leadlotse Formular', 'leadlotse' ),
					instructions: state.error
						? __(
								'Die Formularliste konnte nicht geladen werden. Bitte pruefen Sie Ihre Berechtigung oder laden Sie den Editor neu.',
								'leadlotse'
						  )
						: __(
								'Waehlen Sie ein Formular aus. Neue Formulare legen Sie im Bereich Leadlotse an.',
								'leadlotse'
						  ),
				},
				state.loading ? el( Spinner, null ) : selector
			);
		}

		return el(
			'div',
			blockProps,
			el(
				InspectorControls,
				null,
				el(
					PanelBody,
					{ title: __( 'Formular', 'leadlotse' ) },
					state.loading ? el( Spinner, null ) : selector
				)
			),
			content
		);
	}

	registerBlockType( BLOCK_NAME, {
		edit: Edit,
		// Serverseitiges Rendering: save liefert null (Dynamic Block).
		save: function () {
			return null;
		},
	} );
} )( window.wp );
