/**
 * Create Fundraiser Button — editor script.
 *
 * Registers the block in the block editor. The editor UI mirrors the
 * Create Fundraiser Form block's inspector panels so that the same
 * campaign, parent, and type presets can be configured here too.
 *
 * Differences from the form block:
 *  - "Button" panel at the top with a TextControl for the button label.
 *  - No frontend JS needed — the output is a plain <a> tag.
 *  - Canvas preview renders the button directly.
 *
 * @package AmbassadorHub\Fundraisers\Blocks\CreateFundraiserButton
 */
( 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 TextControl      = wp.components.TextControl;
	var Notice           = wp.components.Notice;
	var Spinner          = wp.components.Spinner;
	var ToggleControl    = wp.components.ToggleControl;

	wp.blocks.registerBlockType( 'ambassadorhub/create-fundraiser-button', {
		edit: function ( props ) {
			var attrs          = props.attributes;
			var set            = props.setAttributes;
			var buttonLabel    = attrs.buttonLabel || '';
			var contextMode    = attrs.contextMode || 'auto';
			var presetCampaign = attrs.presetCampaignId || 0;
			var presetParent   = attrs.presetParentId || 0;
			var forceType          = attrs.forceType || '';
			var rootMode           = !! attrs.rootMode;
			var hideIfNotAllowed   = !! attrs.hideIfNotAllowed;
			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 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.
			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 ] );

			// Resolve a human-readable summary for the canvas preview.
			var campaignSummary = '';
			if ( contextMode === 'preset' ) {
				if ( presetCampaign > 0 ) {
					var matchedLabel = '';
					if ( campaigns ) {
						for ( var i = 0; i < campaigns.length; i++ ) {
							if ( campaigns[ i ].value === String( presetCampaign ) ) {
								matchedLabel = campaigns[ i ].label;
								break;
							}
						}
					}
					campaignSummary = matchedLabel || ( 'Campaign #' + presetCampaign );
					if ( presetParent > 0 ) {
						campaignSummary += ' · ' + __( 'with parent', 'ambassadorhub' );
					}
				} else {
					campaignSummary = __( '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 — top-level fundraiser', 'ambassadorhub' ), value: '0' } ];
			if ( fundraisers && fundraisers.length > 0 ) {
				fundraiserOptions = fundraiserOptions.concat( fundraisers );
			}

			var displayLabel = buttonLabel || __( 'Create fundraiser', 'ambassadorhub' );

			// Build a concise URL hint for the canvas preview.
			var urlHint = __( 'Links to: create fundraiser page', 'ambassadorhub' );
			if ( contextMode === 'auto' ) {
				urlHint += ' · ' + __( 'campaign detected from the page this button is placed on', 'ambassadorhub' );
			} else if ( campaignSummary ) {
				urlHint += ' · ' + campaignSummary;
			}
			if ( forceType ) {
				urlHint += ' · ' + __( 'type', 'ambassadorhub' ) + '=' + forceType;
			}
			if ( rootMode ) {
				urlHint += ' · ' + __( 'root (no parent)', 'ambassadorhub' );
			}

			return el(
				Fragment,
				null,

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

					el( PanelBody, { title: __( 'Button', 'ambassadorhub' ), initialOpen: true },
						el( TextControl, {
							label:    __( 'Button label', 'ambassadorhub' ),
							value:    buttonLabel,
							onChange: function ( v ) { set( { buttonLabel: v } ); },
							help:     __( 'Leave empty to use the default label: "Create fundraiser".', 'ambassadorhub' ),
						} )
					),

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

						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 link to a specific campaign', 'ambassadorhub' ),         value: 'preset' },
							],
							onChange: function ( v ) {
								set( { contextMode: v, presetCampaignId: 0, presetParentId: 0 } );
							},
							help: contextMode === 'auto'
								? __( 'The form page will detect the campaign from its own context or from a ?campaign_id= parameter already in the URL.', 'ambassadorhub' )
								: __( 'A ?campaign_id= query parameter will be appended to the button link.', 'ambassadorhub' ),
						} ),

						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 the linked form will be linked to this campaign.', 'ambassadorhub' ),
								} )
						),

						// Parent fundraiser selector — only shown when nesting is enabled for the selected 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 to pre-set as the parent for team creation. A ?parent_id= query parameter will be appended to the link.', '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 an individual fundraiser', 'ambassadorhub' ), value: 'individual' },
								{ label: __( 'Always create a team', 'ambassadorhub' ),                  value: 'team' },
							],
							onChange: function ( v ) { set( { forceType: v } ); },
							help: forceType === 'team'
								? __( 'Appends ?type=team to the link. The form will skip the type-selection step.', 'ambassadorhub' )
								: forceType === 'individual'
								? __( 'Appends ?type=individual to the link. The form will skip the type-selection step.', 'ambassadorhub' )
								: __( 'No ?type= parameter is added. The form decides based on its own campaign settings.', 'ambassadorhub' ),
						} ),

						// Hide-if-not-allowed toggle — only when a type is forced.
						forceType !== '' && el( ToggleControl, {
							label:    __( 'Hide button if type is not available', 'ambassadorhub' ),
							checked:  hideIfNotAllowed,
							onChange: function ( v ) { set( { hideIfNotAllowed: v } ); },
							help:     forceType === 'team'
								? __( 'When enabled, the button is hidden if the resolved campaign does not have teams enabled, or if the parent does not allow nested teams.', 'ambassadorhub' )
								: __( 'When enabled, the button is hidden if the forced type is not available for the resolved campaign.', 'ambassadorhub' ),
						} ),

					// rootMode — only relevant for individual type.
					forceType === 'individual' && contextMode === 'auto' && el( ToggleControl, {
						label:    __( 'Root fundraiser (no parent)', 'ambassadorhub' ),
						checked:  rootMode,
						onChange: function ( v ) { set( { rootMode: v } ); },
						help:     rootMode
							? __( 'Campaign is detected from the page, but no parent is passed — creates a root individual fundraiser, not a team member.', 'ambassadorhub' )
							: __( 'When on a team page, the team is passed as parent — creates an individual fundraiser inside that team.', 'ambassadorhub' ),
					} ),
					)
				),

				// ── Canvas preview ───────────────────────────────────────────
				el( 'div', blockProps,
					el( 'a', {
						className: ( function () {
							var cls = 'ambh-cfb-btn ambh-cfb-btn--preview';
							if ( attrs.backgroundColor ) { cls += ' has-' + attrs.backgroundColor + '-background-color has-background'; }
							if ( attrs.textColor )       { cls += ' has-' + attrs.textColor + '-color has-text-color'; }
							return cls;
						} )(),
						style: ( function () {
							var colorAttrs = ( attrs.style && attrs.style.color ) || {};
							var hasBg   = !! ( attrs.backgroundColor || colorAttrs.background );
							var hasText = !! ( attrs.textColor       || colorAttrs.text );
							var s = {};
							if ( colorAttrs.background ) { s.backgroundColor = colorAttrs.background; }
							if ( colorAttrs.text )       { s.color = colorAttrs.text; }
							if ( ! hasBg )   { s.backgroundColor = 'var(--ambh-color-primary, #2271b1)'; }
							if ( ! hasText ) { s.color = '#ffffff'; }
							return s;
						} )(),
						href:    '#',
						onClick: function ( e ) { e.preventDefault(); },
					}, displayLabel ),
					el( 'p', { style: { margin: '6px 0 0', fontSize: '0.8125em', color: '#9e9e9e' } },
						urlHint
					)
				)
			);
		},

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