(function ( blocks, element, blockEditor, components, i18n, serverSideRender ) {
	'use strict';

	var el                = element.createElement;
	var __                = i18n.__;
	var InspectorControls = blockEditor.InspectorControls;
	var useBlockProps     = blockEditor.useBlockProps;
	var PanelBody         = components.PanelBody;
	var Placeholder       = components.Placeholder;
	var Spinner           = components.Spinner;

	blocks.registerBlockType( 'readjutsu/reading-time', {

		edit: function ( props ) {
			var blockProps = useBlockProps();

			return [
				// ── Sidebar panel ───────────────────────────────────────────
				el( InspectorControls, { key: 'inspector' },
					el( PanelBody, {
						key:         'panel',
						title:       __( 'ReadJutsu', 'readjutsu' ),
						initialOpen: true,
					},
						el( 'p', {
							key:   'desc',
							style: { fontSize: '13px', color: '#666', margin: '0 0 8px' },
						}, __( 'Displays the estimated reading time using your global ReadJutsu settings.', 'readjutsu' ) ),
						el( 'a', {
							key:    'link',
							href:   'admin.php?page=readjutsu-options',
							target: '_blank',
							style:  { fontSize: '13px', color: '#0069FF' },
						}, __( 'Open ReadJutsu settings ↗', 'readjutsu' ) )
					)
				),

				// ── Block preview (server-side render) ───────────────────────
				el( 'div', Object.assign( { key: 'wrap' }, blockProps ),
					el( serverSideRender, {
						key:        'ssr',
						block:      'readjutsu/reading-time',
						attributes: props.attributes,

						LoadingResponsePlaceholder: function () {
							return el( 'div', {
								key:   'loading',
								style: { display: 'flex', alignItems: 'center', gap: '8px', padding: '8px 0', color: '#999' },
							},
								el( Spinner, { key: 'spin' } ),
								el( 'span', { key: 'txt', style: { fontSize: '13px' } }, __( 'Loading preview…', 'readjutsu' ) )
							);
						},

						ErrorResponsePlaceholder: function ( errorProps ) {
							var msg = ( errorProps.response && errorProps.response.errorMsg )
								? errorProps.response.errorMsg
								: __( 'Enable ReadJutsu in Settings to display the badge.', 'readjutsu' );
							return el( Placeholder, {
								key:          'err',
								icon:         'clock',
								label:        __( 'ReadJutsu — Reading Time', 'readjutsu' ),
								instructions: msg,
							} );
						},
					} )
				),
			];
		},

		save: function () {
			return null; // dynamic block — rendered server-side
		},
	} );

}(
	window.wp.blocks,
	window.wp.element,
	window.wp.blockEditor,
	window.wp.components,
	window.wp.i18n,
	window.wp.serverSideRender
) );
