/**
 * Fundraiser Grid — editor script.
 *
 * Registers the block in the block editor and provides an InspectorControls
 * panel for configuring:
 *  - Context (auto-detect vs preset campaign / parent fundraiser)
 *  - Grid columns, max items, and sort order
 *
 * No frontend JS is needed — the block is fully server-side rendered.
 *
 * @package AmbassadorHub\Fundraisers\Blocks\FundraiserGrid
 */
( 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 RangeControl      = wp.components.RangeControl;
	var TextControl       = wp.components.TextControl;
	var Spinner           = wp.components.Spinner;

	wp.blocks.registerBlockType( 'ambassadorhub/fundraiser-grid', {

		edit: function ( props ) {
			var attrs          = props.attributes;
			var set            = props.setAttributes;
			var title          = attrs.title || '';
			var contextMode    = attrs.contextMode || 'auto';
			var presetCampaign = attrs.presetCampaignId || 0;
			var presetParent   = attrs.presetParentId || 0;
			var columns        = attrs.columns || 3;
			var maxItems       = typeof attrs.maxItems === 'number' ? attrs.maxItems : 0;
			var orderBy        = attrs.orderBy || 'raised';
			var view           = attrs.view || 'grid';
			var blockProps     = wp.blockEditor.useBlockProps();

			// ── Async data ──────────────────────────────────────────────────

			// Campaigns loaded when switching to preset mode.
			var campaignState = useState( null );
			var campaigns     = campaignState[0];
			var setCampaigns  = campaignState[1];

			// Fundraisers for the selected preset campaign.
			var fundraiserState = useState( null );
			var fundraisers     = fundraiserState[0];
			var setFundraisers  = fundraiserState[1];

			// Load campaigns when preset mode is activated.
			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 top-level fundraisers when a campaign is selected.
			useEffect( function () {
				if ( contextMode !== 'preset' || ! presetCampaign ) {
					setFundraisers( null );
					return;
				}
				setFundraisers( 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 ) };
					} ) );
				} ).catch( function () {
					setFundraisers( [] );
				} );
			}, [ contextMode, presetCampaign ] );

			// ── Dropdown option lists ────────────────────────────────────────

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

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

			// ── Canvas summary ───────────────────────────────────────────────

			var contextSummary;
			if ( contextMode === 'auto' ) {
				contextSummary = __( 'Fundraisers detected from the current page context.', 'ambassadorhub' );
			} else if ( presetCampaign > 0 ) {
				contextSummary = presetParent > 0
					? __( 'Showing children of a specific team fundraiser.', 'ambassadorhub' )
					: __( 'Showing top-level fundraisers for a specific campaign.', 'ambassadorhub' );
			} else {
				contextSummary = __( 'No campaign selected — choose one in the sidebar.', 'ambassadorhub' );
			}

			var gridSummary = view === 'list'
				? __( 'List', 'ambassadorhub' )
				: columns + ' ' + __( 'col.', 'ambassadorhub' );
			if ( maxItems > 0 ) {
				gridSummary += ' · ' + maxItems + ' ' + __( 'items', 'ambassadorhub' );
			}
			gridSummary += ' · ' + ( orderBy === 'raised'
				? __( 'most raised first', 'ambassadorhub' )
				: orderBy === 'title'
				? __( 'A–Z', 'ambassadorhub' )
				: __( 'newest first', 'ambassadorhub' ) );

			// ── Render ───────────────────────────────────────────────────────

			return el(
				Fragment,
				null,

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

					// Campaign / context panel.
					el( PanelBody, { title: __( 'Campaign', 'ambassadorhub' ), initialOpen: true },

						el( RadioControl, {
							label:    __( 'Context', 'ambassadorhub' ),
							selected: contextMode,
							options: [
								{
									label: __( 'Detect from current page', 'ambassadorhub' ),
									value: 'auto',
								},
								{
									label: __( 'Use a specific campaign', 'ambassadorhub' ),
									value: 'preset',
								},
							],
							onChange: function ( v ) {
								set( { contextMode: v, presetCampaignId: 0, presetParentId: 0 } );
							},
							help: contextMode === 'auto'
								? __( 'On a campaign page the block shows top-level fundraisers. On a team fundraiser page it shows direct children.', 'ambassadorhub' )
								: null,
						} ),

						// Campaign dropdown — preset mode only.
						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 } );
									},
								} )
						),

						// Parent fundraiser dropdown — shown when a preset campaign is selected.
						contextMode === 'preset' && presetCampaign > 0 && (
							fundraisers === null
								? el( Spinner )
								: el( SelectControl, {
									label:   __( 'Parent fundraiser (optional)', 'ambassadorhub' ),
									value:   String( presetParent || 0 ),
									options: fundraiserOptions,
									onChange: function ( v ) {
										set( { presetParentId: parseInt( v, 10 ) || 0 } );
									},
									help: __( 'Select a team fundraiser to show its direct members. Leave empty to show top-level fundraisers for the campaign.', 'ambassadorhub' ),
								} )
						)
					),

// Display settings panel.
				el( PanelBody, { title: __( 'Display', 'ambassadorhub' ), initialOpen: true },

					el( TextControl, {
						label:    __( 'Title', 'ambassadorhub' ),
						value:    title,
						help:     __( 'Optional heading shown above the fundraiser grid.', 'ambassadorhub' ),
						onChange: function ( v ) { set( { title: v } ); },
					} ),

					el( RadioControl, {
						label:    __( 'View', 'ambassadorhub' ),
						selected: view,
						options: [
							{ label: __( 'Grid', 'ambassadorhub' ), value: 'grid' },
							{ label: __( 'List', 'ambassadorhub' ), value: 'list' },
						],
						onChange: function ( v ) { set( { view: v } ); },
					} ),

					view === 'grid' && el( RangeControl, {
							label:    __( 'Columns', 'ambassadorhub' ),
							value:    columns,
							min:      1,
							max:      6,
							step:     1,
							onChange: function ( v ) { set( { columns: v || 3 } ); },
						} ),

						el( TextControl, {
							label: __( 'Max items (0 = show all)', 'ambassadorhub' ),
							type:  'number',
							value: String( maxItems ),
							min:   '0',
							step:  '1',
							onChange: function ( v ) {
								set( { maxItems: Math.max( 0, parseInt( v, 10 ) || 0 ) } );
							},
						} ),

						el( SelectControl, {
							label:    __( 'Sort order', 'ambassadorhub' ),
							value:    orderBy,
							options: [
								{ label: __( 'Most raised first', 'ambassadorhub' ), value: 'raised' },
								{ label: __( 'Alphabetical (A–Z)',  'ambassadorhub' ), value: 'title'  },
								{ label: __( 'Newest first',         'ambassadorhub' ), value: 'date'   },
							],
							onChange: function ( v ) { set( { orderBy: v } ); },
						} )
					)
				),

				// ── Canvas preview ───────────────────────────────────────────
				el( 'div', blockProps,
					title ? el( 'h2', { style: { margin: '0 0 8px', fontSize: '1.25em' } }, title ) : null,
					el( 'div', { className: 'ambh-fundraiser-grid ambh-block-preview' },
						el( 'p', { className: 'ambh-block-preview__label' },
							view === 'list'
								? __( 'Fundraiser List', 'ambassadorhub' )
								: __( 'Fundraiser Grid', 'ambassadorhub' )
						),
						el( 'p', { className: 'ambh-block-preview__meta' },
							contextSummary
						),
						el( 'p', { className: 'ambh-block-preview__meta' },
							gridSummary
						)
					)
				)
			);
		},

		save: function () {
			// Server-side rendered — no static save output.
			return null;
		},

	} );

} )( window.wp );
