/**
 * Editor UI for the Cliq Store Locator block. Plain ES5 using WordPress globals
 * (no build step): renders a Placeholder with a template dropdown populated from
 * the public /templates endpoint, plus an Inspector panel of optional default
 * filters (country / category / brand / search term) that pre-scope the listing —
 * e.g. show only one country's stores. The frontend is rendered server-side.
 */
( function ( wp ) {
	if ( ! wp || ! wp.blocks ) {
		return;
	}
	var el = wp.element.createElement;
	var Fragment = wp.element.Fragment;
	var useState = wp.element.useState;
	var useEffect = wp.element.useEffect;
	var SelectControl = wp.components.SelectControl;
	var TextControl = wp.components.TextControl;
	var PanelBody = wp.components.PanelBody;
	var Placeholder = wp.components.Placeholder;
	var Spinner = wp.components.Spinner;
	var useBlockProps = wp.blockEditor.useBlockProps;
	var InspectorControls = wp.blockEditor.InspectorControls;
	var apiFetch = wp.apiFetch;
	var __ = wp.i18n.__;

	// Fetch {value,label} options from the public field-options endpoint.
	var useOptions = function ( source ) {
		var state = useState( null );
		var setOptions = state[ 1 ];
		useEffect( function () {
			apiFetch( { path: 'cliq-store-locator/v1/field-options?source=' + source } )
				.then( function ( res ) {
					setOptions( ( res && res.options ) || [] );
				} )
				.catch( function () {
					setOptions( [] );
				} );
		}, [] );
		return state[ 0 ];
	};

	wp.blocks.registerBlockType( 'cliq/store-locator', {
		edit: function ( props ) {
			var attrs = props.attributes;
			var stateOpts = useState( null );
			var options = stateOpts[ 0 ];
			var setOptions = stateOpts[ 1 ];
			var categories = useOptions( 'categories' );
			var brands = useOptions( 'brands' );

			useEffect( function () {
				apiFetch( { path: 'cliq-store-locator/v1/templates' } )
					.then( function ( res ) {
						var list = ( res && res.templates ) || [];
						setOptions(
							list.map( function ( t ) {
								return { label: t.name, value: String( t.id ) };
							} )
						);
					} )
					.catch( function () {
						setOptions( [] );
					} );
			}, [] );

			var control;
			if ( options === null ) {
				control = el( Spinner, null );
			} else {
				control = el( SelectControl, {
					__next40pxDefaultSize: true,
					label: __( 'Template', 'cliq-store-locator' ),
					value: String( attrs.templateId || '' ),
					options: [ { label: __( 'Select a template…', 'cliq-store-locator' ), value: '' } ].concat( options ),
					onChange: function ( v ) {
						props.setAttributes( { templateId: v ? parseInt( v, 10 ) : 0 } );
					},
				} );
			}

			var emptyOpt = function ( label ) {
				return [ { label: label, value: '' } ];
			};

			var inspector = el(
				InspectorControls,
				null,
				el(
					PanelBody,
					{
						title: __( 'Default filters', 'cliq-store-locator' ),
						initialOpen: false,
					},
					el( 'p', { style: { marginTop: 0, color: '#757575' } },
						__( 'Optionally pre-scope the listing. Visitors can still change these unless your template hides the search form.', 'cliq-store-locator' )
					),
					el( TextControl, {
						label: __( 'Country', 'cliq-store-locator' ),
						help: __( 'Matches the stored country value (e.g. an ISO code or name).', 'cliq-store-locator' ),
						value: attrs.country || '',
						onChange: function ( v ) {
							props.setAttributes( { country: v } );
						},
					} ),
					el( SelectControl, {
						__next40pxDefaultSize: true,
						label: __( 'Category', 'cliq-store-locator' ),
						value: String( attrs.category || '' ),
						options: emptyOpt( __( 'Any category', 'cliq-store-locator' ) ).concat( categories || [] ),
						onChange: function ( v ) {
							props.setAttributes( { category: v } );
						},
					} ),
					el( SelectControl, {
						__next40pxDefaultSize: true,
						label: __( 'Brand', 'cliq-store-locator' ),
						value: String( attrs.brand || '' ),
						options: emptyOpt( __( 'Any brand', 'cliq-store-locator' ) ).concat( brands || [] ),
						onChange: function ( v ) {
							props.setAttributes( { brand: v } );
						},
					} ),
					el( TextControl, {
						label: __( 'Search term', 'cliq-store-locator' ),
						help: __( 'Pre-fill the keyword search.', 'cliq-store-locator' ),
						value: attrs.q || '',
						onChange: function ( v ) {
							props.setAttributes( { q: v } );
						},
					} ),
					el( TextControl, {
						label: __( 'Custom field key', 'cliq-store-locator' ),
						help: __( 'The custom field machine key, for example services or warranty_years.', 'cliq-store-locator' ),
						value: attrs.metaKey || '',
						onChange: function ( v ) {
							props.setAttributes( { metaKey: String( v || '' ).toLowerCase().replace( /[^a-z0-9_-]/g, '' ) } );
						},
					} ),
					el( TextControl, {
						label: __( 'Custom field value', 'cliq-store-locator' ),
						help: __( 'Only stores whose custom field exactly matches this value are shown.', 'cliq-store-locator' ),
						value: attrs.metaValue || '',
						onChange: function ( v ) {
							props.setAttributes( { metaValue: v } );
						},
					} ),
					el( TextControl, {
						type: 'number',
						min: 0,
						label: __( 'Results per page', 'cliq-store-locator' ),
						help: __( 'Overrides the template’s page size for this placement. 0 = use the template’s setting. More stores load via the “Load more” button.', 'cliq-store-locator' ),
						value: attrs.perPage ? String( attrs.perPage ) : '',
						onChange: function ( v ) {
							props.setAttributes( { perPage: v ? Math.max( 0, parseInt( v, 10 ) || 0 ) : 0 } );
						},
					} )
				)
			);

			return el(
				Fragment,
				null,
				inspector,
				el(
					'div',
					useBlockProps(),
					el(
						Placeholder,
						{
							icon: 'location-alt',
							label: __( 'Cliq Store Locator', 'cliq-store-locator' ),
							instructions: __( 'Choose the locator layout to display.', 'cliq-store-locator' ),
						},
						control
					)
				)
			);
		},
		save: function () {
			return null;
		},
	} );
} )( window.wp );
