/**
 * Grid block — reuses Library inspector; outputs [movie_engine_grid].
 */
import { InspectorControls, useBlockProps } from '@wordpress/block-editor';
import ServerSideRender from '@wordpress/server-side-render';
import { Spinner } from '@wordpress/components';
import { __ } from '@wordpress/i18n';

import LibraryInspector from '../../library/src/library-inspector';
import './editor.scss';

const FALLBACK_DEFAULTS = {
	archiveColumnsDesktop: 4,
	archiveColumnsLaptop: 4,
	archiveColumnsTablet: 3,
	archiveColumnsMobile: 2,
	archiveItemsPerPage: 12,
	searchItemsPerPage: 12,
};

export default function Edit({ attributes, setAttributes }) {
	const props = useBlockProps({
		className: 'movie-engine-grid-block-editor',
	});

	const defaults =
		typeof movieEngineLibraryDefaults !== 'undefined' && movieEngineLibraryDefaults
			? movieEngineLibraryDefaults
			: FALLBACK_DEFAULTS;

	return (
		<>
			<InspectorControls>
				<LibraryInspector
					attributes={attributes}
					setAttributes={setAttributes}
					defaults={defaults}
					lockShowSearch="grid"
				/>
			</InspectorControls>
			<div {...props}>
				<div className="movie-engine-grid-block-editor__preview movie-engine-plugin">
					<ServerSideRender
						block="cine-movie-engine/grid"
						attributes={attributes}
						LoadingResponsePlaceholder={() => (
							<p className="movie-engine-grid-block-editor__preview-loading">
								<Spinner />
								{__('Loading preview…', 'cine-movie-engine')}
							</p>
						)}
						ErrorResponsePlaceholder={() => (
							<p className="movie-engine-grid-block-editor__preview-loading">
								{__(
									'Preview unavailable. Check the front end or try saving the page.',
									'cine-movie-engine'
								)}
							</p>
						)}
					/>
				</div>
			</div>
		</>
	);
}
