/**
 * MenuX — Gutenberg block editor script.
 * Vanilla JS, no build step required.
 * Registered via wp_register_script() in includes/block.php.
 */
( function () {
	'use strict';

	/* Guard: bail if core Gutenberg globals are missing. */
	if (
		! window.wp ||
		! wp.blocks ||
		! wp.element ||
		! wp.blockEditor ||
		! wp.components
	) {
		return;
	}

	var el                = wp.element.createElement;
	var Fragment          = wp.element.Fragment;
	var registerBlockType = wp.blocks.registerBlockType;
	/* wp.serverSideRender is the component; fall back gracefully if unavailable. */
	var ServerSideRender  = wp.serverSideRender || null;
	var InspectorControls = wp.blockEditor.InspectorControls;
	var useBlockProps     = wp.blockEditor.useBlockProps;
	var PanelBody         = wp.components.PanelBody;
	var SelectControl     = wp.components.SelectControl;

	/* Standard locations matching the MenuX builder's Location dropdown. */
	var LOCATIONS = [
		{ label: 'Primary',  value: 'primary'  },
		{ label: 'Footer',   value: 'footer'   },
		{ label: 'Sidebar',  value: 'sidebar'  },
		{ label: 'Mobile',   value: 'mobile'   },
	];

	registerBlockType( 'giuliomax/menu', {

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

			return el(
				Fragment,
				null,

				/* ── Inspector sidebar ── */
				el(
					InspectorControls,
					null,
					el(
						PanelBody,
						{ title: 'MenuX Settings', initialOpen: true },
						el( SelectControl, {
							label: 'Menu Location',
							// Fall back to the same default the server uses so the
							// control and the ServerSideRender preview never disagree
							// before the user makes an explicit selection.
							value: attributes.location || 'primary',
							options: LOCATIONS,
							onChange: function ( val ) {
								setAttributes( { location: val } );
							},
							help: 'Matches the "Location" tag assigned to items in the MenuX builder.',
						} )
					)
				),

				/* ── Block preview via ServerSideRender ── */
				el(
					'div',
					blockProps,
					ServerSideRender
						? el( ServerSideRender, { block: 'giuliomax/menu', attributes: attributes } )
						: el( 'p', { style: { padding: '1em', opacity: '.6' } }, 'MenuX — Menu (' + attributes.location + ')' )
				)
			);
		},

		save: function () {
			/* Dynamic block — PHP render_callback produces the output. */
			return null;
		},
	} );
} )();
