/**
 * Campaign Countdown — editor script.
 *
 * @package AmbassadorHub\Campaigns\Blocks\CampaignCountdown
 */
( function ( wp ) {
	'use strict';

	var __                = wp.i18n.__;
	var el                = wp.element.createElement;
	var Fragment          = wp.element.Fragment;
	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 ServerSideRender  = wp.serverSideRender;

	wp.blocks.registerBlockType( 'ambassadorhub/campaign-countdown', {

		edit: function ( props ) {
			var attrs        = props.attributes;
			var set          = props.setAttributes;
			var urgencyDays  = typeof attrs.urgencyDays === 'number' ? attrs.urgencyDays : 7;
			var showLabel    = attrs.showLabel !== false;
			var endedLabel   = attrs.endedLabel || '';
			var blockProps   = wp.blockEditor.useBlockProps();

			return el(
				Fragment,
				null,

				el( InspectorControls, null,
					el( PanelBody, { title: __( 'Countdown settings', 'ambassadorhub' ), initialOpen: true },

						el( RangeControl, {
							label:    __( 'Urgency threshold (days)', 'ambassadorhub' ),
							value:    urgencyDays,
							min:      0,
							max:      30,
							step:     1,
							help:     __( 'Apply urgency styling when fewer than this many days remain. Set to 0 to disable.', 'ambassadorhub' ),
							onChange: function ( v ) { set( { urgencyDays: v || 0 } ); },
						} ),

						el( ToggleControl, {
							label:    __( 'Show "time remaining" label', 'ambassadorhub' ),
							checked:  showLabel,
							onChange: function ( v ) { set( { showLabel: v } ); },
						} ),

						el( TextControl, {
							label:    __( 'Ended message', 'ambassadorhub' ),
							value:    endedLabel,
							help:     __( 'Shown when the campaign has ended. Leave blank for the default message.', 'ambassadorhub' ),
							onChange: function ( v ) { set( { endedLabel: v } ); },
						} )
					)
				),

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

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

} )( window.wp );
