/**
 * DataStream List block — deliberately buildless (no JSX) so the plugin
 * ships no toolchain and the source on disk is the source that runs.
 */
( function ( wp ) {
	'use strict';

	var el = wp.element.createElement;
	var __ = wp.i18n.__;
	var registerBlockType = wp.blocks.registerBlockType;
	var InspectorControls = wp.blockEditor.InspectorControls;
	var useBlockProps = wp.blockEditor.useBlockProps;
	var PanelBody = wp.components.PanelBody;
	var TextControl = wp.components.TextControl;
	var RangeControl = wp.components.RangeControl;
	var SelectControl = wp.components.SelectControl;
	var ServerSideRender = wp.serverSideRender;
	var useState = wp.element.useState;
	var useEffect = wp.element.useEffect;

	/**
	 * Clickable chips of typed field paths, computed server-side from records
	 * already synced for the chosen stream.
	 */
	function FieldSuggestions( props ) {
		var stateHook = useState( [] );
		var detected = stateHook[ 0 ];
		var setDetected = stateHook[ 1 ];

		useEffect(
			function () {
				var active = true;
				wp.apiFetch( {
					path: '/datastream/v1/fields?stream=' + encodeURIComponent( props.stream || '' ),
				} ).then( function ( result ) {
					if ( active ) {
						setDetected( result.fields || [] );
					}
				} ).catch( function () {
					if ( active ) {
						setDetected( [] );
					}
				} );
				return function () {
					active = false;
				};
			},
			[ props.stream ]
		);

		if ( ! detected.length ) {
			return null;
		}

		return el(
			'div',
			{ style: { marginBottom: '16px' } },
			detected.map( function ( field ) {
				var spec = -1 === [ 'image', 'url', 'date', 'number', 'bool', 'email' ].indexOf( field.type )
					? field.path
					: field.path + ':' + field.type;

				return el(
					'button',
					{
						key: field.path,
						type: 'button',
						className: 'components-button is-secondary is-small',
						style: { margin: '0 4px 4px 0' },
						disabled: -1 !== ( props.fields || '' ).indexOf( field.path ),
						onClick: function () {
							props.onAdd( spec );
						},
					},
					field.path + ' · ' + field.type
				);
			} )
		);
	}

	registerBlockType( 'datastream/list', {
		title: __( 'DataStream List', 'datastream-api-sync' ),
		description: __( 'Display records synced from your external API.', 'datastream-api-sync' ),
		icon: 'database-import',
		category: 'widgets',
		attributes: {
			stream: { type: 'string', default: '' },
			limit: { type: 'number', default: 10 },
			template: { type: 'string', default: 'list' },
			fields: { type: 'string', default: '' },
		},

		edit: function ( props ) {
			var attributes = props.attributes;
			var setAttributes = props.setAttributes;

			var inspector = el(
				InspectorControls,
				{},
				el(
					PanelBody,
					{ title: __( 'Display Settings', 'datastream-api-sync' ), initialOpen: true },
					el( SelectControl, {
						label: __( 'Template', 'datastream-api-sync' ),
						value: attributes.template,
						options: [
							{ value: 'list', label: __( 'List', 'datastream-api-sync' ) },
							{ value: 'table', label: __( 'Table', 'datastream-api-sync' ) },
							{ value: 'cards', label: __( 'Cards', 'datastream-api-sync' ) },
							{ value: 'grid', label: __( 'Grid (image-led)', 'datastream-api-sync' ) },
							{ value: 'raw', label: __( 'Raw JSON', 'datastream-api-sync' ) },
						],
						onChange: function ( value ) {
							setAttributes( { template: value } );
						},
					} ),
					el( RangeControl, {
						label: __( 'Number of records', 'datastream-api-sync' ),
						value: attributes.limit,
						min: 1,
						max: 100,
						onChange: function ( value ) {
							setAttributes( { limit: value || 10 } );
						},
					} ),
					el( RangeControl, {
						label: __( 'Records per page (0 = no pagination)', 'datastream-api-sync' ),
						value: attributes.pageSize,
						min: 0,
						max: 50,
						onChange: function ( value ) {
							setAttributes( { pageSize: value || 0 } );
						},
					} ),
					el( TextControl, {
						label: __( 'Sort by field', 'datastream-api-sync' ),
						help: __( 'Optional, e.g. price:number or title. Sorts the fetched records.', 'datastream-api-sync' ),
						value: attributes.orderby,
						onChange: function ( value ) {
							setAttributes( { orderby: value } );
						},
					} ),
					el( SelectControl, {
						label: __( 'Sort direction', 'datastream-api-sync' ),
						value: attributes.order,
						options: [
							{ value: 'desc', label: __( 'High to low / Z to A', 'datastream-api-sync' ) },
							{ value: 'asc', label: __( 'Low to high / A to Z', 'datastream-api-sync' ) },
						],
						onChange: function ( value ) {
							setAttributes( { order: value } );
						},
					} ),
					el( wp.components.ToggleControl, {
						label: __( 'Add a search box', 'datastream-api-sync' ),
						checked: !! attributes.searchable,
						onChange: function ( value ) {
							setAttributes( { searchable: !! value } );
						},
					} ),
					el( SelectControl, {
						label: __( 'Style', 'datastream-api-sync' ),
						value: attributes.style,
						options: [
							{ value: '', label: __( 'Default', 'datastream-api-sync' ) },
							{ value: 'clean', label: __( 'Clean (no lines)', 'datastream-api-sync' ) },
							{ value: 'bordered', label: __( 'Bordered', 'datastream-api-sync' ) },
							{ value: 'striped', label: __( 'Striped', 'datastream-api-sync' ) },
							{ value: 'compact', label: __( 'Compact', 'datastream-api-sync' ) },
						],
						onChange: function ( value ) {
							setAttributes( { style: value } );
						},
					} ),
					el( TextControl, {
						label: __( 'Stream filter', 'datastream-api-sync' ),
						help: __( 'Optional. Matches the stream name from the sync settings. Leave empty to show all records.', 'datastream-api-sync' ),
						value: attributes.stream,
						onChange: function ( value ) {
							setAttributes( { stream: value } );
						},
					} ),
					el( TextControl, {
						label: __( 'Fields', 'datastream-api-sync' ),
						help: __( 'Optional comma-separated field names, e.g. name,email:email,photo:image — dot paths reach nested values, ":type" controls formatting. Click a detected field below to add it. Leave empty to auto-detect.', 'datastream-api-sync' ),
						value: attributes.fields,
						onChange: function ( value ) {
							setAttributes( { fields: value } );
						},
					} ),
					el( FieldSuggestions, {
						stream: attributes.stream,
						fields: attributes.fields,
						onAdd: function ( spec ) {
							var current = ( attributes.fields || '' ).trim();
							setAttributes( { fields: current ? current + ',' + spec : spec } );
						},
					} )
				)
			);

			var preview = el(
				'div',
				useBlockProps(),
				el( ServerSideRender, {
					block: 'datastream/list',
					attributes: attributes,
				} )
			);

			return [ inspector, preview ];
		},

		save: function () {
			return null;
		},
	} );
} )( window.wp );
