( function ( wp ) {
	'use strict';

	var __            = wp.i18n.__;
	var el            = wp.element.createElement;
	var Fragment      = wp.element.Fragment;
	var useState      = wp.element.useState;
	var useEffect     = wp.element.useEffect;
	var InspectorControls = wp.blockEditor.InspectorControls;
	var PanelBody     = wp.components.PanelBody;
	var RadioControl  = wp.components.RadioControl;
	var SelectControl = wp.components.SelectControl;
	var ToggleControl = wp.components.ToggleControl;
	var Notice        = wp.components.Notice;
	var Spinner       = wp.components.Spinner;

	wp.blocks.registerBlockType( 'ambassadorhub/create-fundraiser-form', {
		edit: function ( props ) {
			var attrs          = props.attributes;
			var set            = props.setAttributes;
			var contextMode    = attrs.contextMode || 'auto';
			var presetCampaign = attrs.presetCampaignId || 0;
			var presetParent   = attrs.presetParentId || 0;
			var forceType      = attrs.forceType || '';
			var blockProps     = wp.blockEditor.useBlockProps();

			// Async data for the dropdowns — null means "not yet loaded".
			var campaignState    = useState( null );
			var campaigns        = campaignState[0];
			var setCampaigns     = campaignState[1];
			var fundraiserState  = useState( null );
			var fundraisers      = fundraiserState[0];
			var setFundraisers   = fundraiserState[1];
			var nestingState     = useState( null );
			var nestingEnabled   = nestingState[0];
			var setNestingEnabled = nestingState[1];

			// Load campaigns from the WP REST API when switching to preset mode.
			useEffect( function () {
				if ( contextMode !== 'preset' ) {
					return;
				}
				setCampaigns( null );
				wp.apiFetch( {
					path: '/wp/v2/ambh_campaign?per_page=100&status=publish&orderby=title&order=asc&_fields=id,title',
				} ).then( function ( posts ) {
					setCampaigns( posts.map( function ( p ) {
						var label = ( p.title && ( p.title.rendered || p.title ) ) || 'Campaign #' + p.id;
						return { label: label, value: String( p.id ) };
					} ) );
				} ).catch( function () {
					setCampaigns( [] );
				} );
			}, [ contextMode ] );

			// Load fundraisers for the selected campaign via the REST API.
			useEffect( function () {
				if ( contextMode !== 'preset' || ! presetCampaign ) {
					setFundraisers( null );
					setNestingEnabled( null );
					return;
				}
				setFundraisers( null );
				setNestingEnabled( null );
				wp.apiFetch( {
					path: '/ambassadorhub/v1/fundraisers?campaign_id=' + presetCampaign + '&per_page=100',
				} ).then( function ( data ) {
					var items = data && Array.isArray( data.items ) ? data.items : [];
					setFundraisers( items.map( function ( p ) {
						return { label: p.title || ( 'Fundraiser #' + p.id ), value: String( p.id ) };
					} ) );
					setNestingEnabled( !! ( data && data.nesting_enabled ) );
				} ).catch( function () {
					setFundraisers( [] );
					setNestingEnabled( false );
				} );
			}, [ contextMode, presetCampaign ] );

			// Canvas preview: resolve campaign name from the loaded list.
			var canvasLine = '';
			if ( contextMode === 'preset' ) {
				if ( presetCampaign > 0 ) {
					var campaignLabel = '';
					if ( campaigns ) {
						for ( var i = 0; i < campaigns.length; i++ ) {
							if ( campaigns[ i ].value === String( presetCampaign ) ) {
								campaignLabel = campaigns[ i ].label;
								break;
							}
						}
					}
					canvasLine = campaignLabel || ( 'Campaign #' + presetCampaign );
					if ( presetParent > 0 ) {
						canvasLine += ' · ' + __( 'with parent', 'ambassadorhub' );
					}
				} else {
					canvasLine = __( 'No campaign selected', 'ambassadorhub' );
				}
			}

			// Dropdown options.
			var campaignOptions = [ { label: __( '— Select a campaign —', 'ambassadorhub' ), value: '0' } ];
			if ( campaigns && campaigns.length > 0 ) {
				campaignOptions = campaignOptions.concat( campaigns );
			}

			var fundraiserOptions = [ { label: __( 'None — create a top-level fundraiser', 'ambassadorhub' ), value: '0' } ];
			if ( fundraisers && fundraisers.length > 0 ) {
				fundraiserOptions = fundraiserOptions.concat( fundraisers );
			}

			return el(
				Fragment,
				null,

				// ── Sidebar ───────────────────────────────────────────────────
				el( InspectorControls, null,

					el( PanelBody, { title: __( 'Campaign', 'ambassadorhub' ), initialOpen: true },

						el( RadioControl, {
							label:    __( 'How should the form know which campaign to use?', 'ambassadorhub' ),
							selected: contextMode,
							options: [
								{ label: __( 'Detect automatically from the current page', 'ambassadorhub' ), value: 'auto' },
								{ label: __( 'Always use a specific campaign', 'ambassadorhub' ),          value: 'preset' },
							],
							onChange: function ( v ) {
								set( { contextMode: v, presetCampaignId: 0, presetParentId: 0 } );
							},
							help: contextMode === 'auto'
								? __( 'The campaign is taken from the page the block is placed on, or from a ?campaign_id= link. If no campaign is detected the Ambassador can select a campaign in the first step.', 'ambassadorhub' )
								: __( 'The form will always create fundraisers for the campaign you choose below, regardless of which page it is placed on.', 'ambassadorhub' ),
						} ),

						// Step 1 — select campaign.
						contextMode === 'preset' && (
							campaigns === null
								? el( Spinner )
								: el( SelectControl, {
									label:    __( 'Campaign', 'ambassadorhub' ),
									value:    String( presetCampaign || 0 ),
									options:  campaignOptions,
									onChange: function ( v ) {
										set( { presetCampaignId: parseInt( v, 10 ) || 0, presetParentId: 0 } );
									},
									help: __( 'Fundraisers created through this form will be linked to this campaign.', 'ambassadorhub' ),
								} )
						),

					// Step 2 — optional parent fundraiser (only shown when nesting is enabled for the campaign).
					contextMode === 'preset' && presetCampaign > 0 && (
						fundraisers === null
							? el( Spinner )
							: nestingEnabled
							? el( SelectControl, {
									label:    __( 'Parent fundraiser (optional)', 'ambassadorhub' ),
									value:    String( presetParent || 0 ),
									options:  fundraiserOptions,
									onChange: function ( v ) {
										set( { presetParentId: parseInt( v, 10 ) || 0 } );
									},
									help: fundraisers && fundraisers.length > 0
										? __( 'Choose an existing fundraiser if this form should create a team fundraiser underneath it. Leave blank for top-level fundraisers.', 'ambassadorhub' )
										: __( 'No published fundraisers found for this campaign yet.', 'ambassadorhub' ),
								} )							: null						)
					),

					el( PanelBody, { title: __( 'Fundraiser type', 'ambassadorhub' ), initialOpen: false },

					el( RadioControl, {
						label:    __( 'Fundraiser type', 'ambassadorhub' ),
						selected: forceType,
						options: [
							{ label: __( 'Let the ambassador choose', 'ambassadorhub' ),   value: '' },
							{ label: __( 'Always create a fundraiser', 'ambassadorhub' ), value: 'individual' },
							{ label: __( 'Always create a team', 'ambassadorhub' ),       value: 'team' },
						],
						onChange: function ( v ) { set( { forceType: v } ); },
						help: forceType === 'team'
							? __( 'The form always creates a team fundraiser. Requires the campaign to have teams enabled.', 'ambassadorhub' )
							: forceType === 'individual'
							? __( 'The form always creates an individual fundraiser, even when the campaign supports teams.', 'ambassadorhub' )
							: __( 'When teams are enabled on the campaign, the ambassador picks the type. Otherwise the form defaults to individual.', 'ambassadorhub' ),
					} ),

					// Conflict notice: "Always create a team" is selected but the
					// chosen campaign does not have teams enabled.
					forceType === 'team' && contextMode === 'preset' && presetCampaign > 0 && nestingEnabled === false
						? el(
							Notice,
							{ status: 'warning', isDismissible: false, style: { marginTop: '8px' } },
							__( 'The selected campaign does not have teams enabled. The frontend will show a conflict notice to ambassadors.', 'ambassadorhub' )
						  )
						: null
					)
				),

				// ── Canvas preview ────────────────────────────────────────────
				el( 'div', blockProps,
					el( 'strong', null, __( 'Create Fundraiser Form', 'ambassadorhub' ) ),
					el( 'p', { style: { margin: '4px 0 0', fontSize: '0.8125em', color: '#3c434a', fontWeight: 500 } },
						contextMode === 'auto'
							? __( 'Campaign: auto-detect', 'ambassadorhub' )
							: ( __( 'Campaign: ', 'ambassadorhub' ) + canvasLine )
					),
					forceType
						? el( 'p', { style: { margin: '2px 0 0', fontSize: '0.8125em', color: '#757575' } },
							forceType === 'team' ? __( 'Type: always team', 'ambassadorhub' ) : __( 'Type: always individual', 'ambassadorhub' )
						)
						: null,
					el( 'p', { style: { margin: '6px 0 0', fontSize: '0.8125em', color: '#9e9e9e' } },
						__( 'Renders the fundraiser creation form on the frontend.', 'ambassadorhub' )
					)
				)
			);
		},
		save: function () {
			// Server-side rendered — no static save output.
			return null;
		},
	} );
} )( window.wp );
