/**
 * Top Fundraisers — editor script.
 *
 * Ranked leaderboard of top fundraisers scoped to the current campaign.
 * Controls: count, optional title, show/hide thumbnails, optional campaign preset.
 */
( 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 RangeControl      = wp.components.RangeControl;
	var TextControl       = wp.components.TextControl;
	var ToggleControl     = wp.components.ToggleControl;
	var SelectControl     = wp.components.SelectControl;
	var RadioControl      = wp.components.RadioControl;
	var Spinner           = wp.components.Spinner;
	var ServerSideRender  = wp.serverSideRender;

	wp.blocks.registerBlockType( 'ambassadorhub/top-fundraisers', {

		edit: function ( props ) {
			var attrs      = props.attributes;
			var set        = props.setAttributes;
			var blockProps = wp.blockEditor.useBlockProps();
			var mode       = ( attrs.presetCampaignId || 0 ) > 0 ? 'preset' : 'auto';

			var campaignState = useState( null );
			var campaigns     = campaignState[0];
			var setCampaigns  = campaignState[1];

			useEffect( function () {
				if ( mode !== 'preset' || campaigns !== null ) return;
				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( [] ); } );
			}, [ mode ] );

			var campaignOptions = [ { label: __( '— Select a campaign —', 'ambassadorhub' ), value: '0' } ]
				.concat( campaigns || [] );

			return el(
				Fragment,
				null,

				el( InspectorControls, null,

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

						el( RangeControl, {
							label:    __( 'Number of fundraisers', 'ambassadorhub' ),
							value:    attrs.count || 5,
							min:      1,
							max:      20,
							step:     1,
							onChange: function ( v ) { set( { count: v || 5 } ); },
						} ),

						el( TextControl, {
							label: __( 'Block title (leave empty to hide)', 'ambassadorhub' ),
							value: attrs.title !== undefined ? attrs.title : __( 'Top fundraisers', 'ambassadorhub' ),
							onChange: function ( v ) { set( { title: v } ); },
						} ),

						el( ToggleControl, {
							label:    __( 'Show profile image', 'ambassadorhub' ),
							checked:  attrs.showImage !== false,
							onChange: function ( v ) { set( { showImage: v } ); },
						} )
					),

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

						el( RadioControl, {
							label:    __( 'Context', 'ambassadorhub' ),
							selected: mode,
							options: [
								{ label: __( 'Detect from current page', 'ambassadorhub' ), value: 'auto' },
								{ label: __( 'Use a specific campaign', 'ambassadorhub' ), value: 'preset' },
							],
							onChange: function ( v ) {
								set( { presetCampaignId: 0 } );
								if ( v === 'preset' ) setCampaigns( null );
							},
						} ),

						mode === 'preset' && (
							campaigns === null
								? el( Spinner )
								: el( SelectControl, {
										label:    __( 'Campaign', 'ambassadorhub' ),
										value:    String( attrs.presetCampaignId || 0 ),
										options:  campaignOptions,
										onChange: function ( v ) { set( { presetCampaignId: parseInt( v, 10 ) || 0 } ); },
								} )
						)
					)
				),

				el( 'div', blockProps,
					el( ServerSideRender, {
						block:      'ambassadorhub/top-fundraisers',
						attributes: attrs,
					} )
				)
			);
		},

		save: function () { return null; },
	} );

} )( window.wp );
