/**
 * AIEO Page Hero — block editor registration for `aieo/page-hero`.
 *
 * A manual twin of the category hero: the operator types the Top title, Left
 * headline and Right description and picks Desktop + Mobile images, instead of
 * the values being pulled from a queried term. The canvas preview is a live
 * ServerSideRender of the SAME render_callback that runs on the front end, so
 * what you see in the editor is exactly what ships — and it reuses the shared
 * .aieo-category-hero markup + stylesheet, so the look is identical.
 */
(function (wp) {
	if (!wp || !wp.blocks || !wp.blockEditor || !wp.components || !wp.element) { return; }

	var el       = wp.element.createElement;
	var Fragment = wp.element.Fragment;
	var __       = (wp.i18n && wp.i18n.__) ? wp.i18n.__ : function (s) { return s; };

	var InspectorControls = wp.blockEditor.InspectorControls;
	var useBlockProps     = wp.blockEditor.useBlockProps;
	var MediaUpload       = wp.blockEditor.MediaUpload;
	var MediaUploadCheck  = wp.blockEditor.MediaUploadCheck;

	var PanelBody       = wp.components.PanelBody;
	var TextControl     = wp.components.TextControl;
	var TextareaControl = wp.components.TextareaControl;
	var Button          = wp.components.Button;

	var ServerSideRender = wp.serverSideRender || (wp.components && wp.components.ServerSideRender);

	// One labelled media picker (button + thumbnail preview + remove), writing
	// an attachment id + url pair into the given attributes.
	function imageField(label, idKey, urlKey, props) {
		var id  = props.attributes[idKey] || 0;
		var url = props.attributes[urlKey] || '';
		return el('div', { style: { marginBottom: '18px' } },
			el('p', { style: { margin: '0 0 4px', fontWeight: 600 } }, label),
			url ? el('img', { src: url, alt: '', style: { display: 'block', maxWidth: '100%', height: 'auto', marginBottom: '6px', border: '1px solid #ddd', borderRadius: '3px' } }) : null,
			el(MediaUploadCheck, {},
				el(MediaUpload, {
					allowedTypes: ['image'],
					value: id,
					onSelect: function (media) {
						var patch = {};
						patch[idKey]  = media.id;
						patch[urlKey] = media.url;
						props.setAttributes(patch);
					},
					render: function (open) {
						return el(Fragment, {},
							el(Button, { variant: 'secondary', onClick: open.open },
								id ? __('Replace image', 'ai-eshop-optimizer') : __('Select image', 'ai-eshop-optimizer')),
							id ? el(Button, {
								variant: 'link',
								isDestructive: true,
								style: { marginLeft: '8px' },
								onClick: function () {
									var patch = {};
									patch[idKey]  = 0;
									patch[urlKey] = '';
									props.setAttributes(patch);
								}
							}, __('Remove', 'ai-eshop-optimizer')) : null
						);
					}
				})
			)
		);
	}

	wp.blocks.registerBlockType('aieo/page-hero', {
		title:       __('AIEO Page Hero', 'ai-eshop-optimizer'),
		description: __('Manual hero — top title, left headline, right description and desktop/mobile images. Same look as the category hero, usable on any page.', 'ai-eshop-optimizer'),
		category:    'theme',
		icon:        'cover-image',
		keywords:    ['hero', 'banner', 'title', 'headline', 'image', 'aieo'],
		supports:    { align: ['wide', 'full'] },
		attributes:  {
			topTitle:    { type: 'string', default: '' },
			headline:    { type: 'string', default: '' },
			description: { type: 'string', default: '' },
			desktopId:   { type: 'number', default: 0 },
			desktopUrl:  { type: 'string', default: '' },
			mobileId:    { type: 'number', default: 0 },
			mobileUrl:   { type: 'string', default: '' },
			align:       { type: 'string', default: '' }
		},

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

			var controls = el(InspectorControls, {},
				el(PanelBody, { title: __('Hero content', 'ai-eshop-optimizer'), initialOpen: true },
					el(TextControl, {
						label: __('Top title', 'ai-eshop-optimizer'),
						value: a.topTitle || '',
						onChange: function (v) { props.setAttributes({ topTitle: v }); }
					}),
					el(TextareaControl, {
						label: __('Left headline', 'ai-eshop-optimizer'),
						help: __('Short, marketing-style headline shown on the left of the hero.', 'ai-eshop-optimizer'),
						value: a.headline || '',
						onChange: function (v) { props.setAttributes({ headline: v }); }
					}),
					el(TextareaControl, {
						label: __('Right description', 'ai-eshop-optimizer'),
						help: __('Longer copy shown on the right. Line breaks become paragraphs.', 'ai-eshop-optimizer'),
						value: a.description || '',
						onChange: function (v) { props.setAttributes({ description: v }); }
					})
				),
				el(PanelBody, { title: __('Images', 'ai-eshop-optimizer'), initialOpen: true },
					imageField(__('Desktop image (shown ≥768px)', 'ai-eshop-optimizer'), 'desktopId', 'desktopUrl', props),
					imageField(__('Mobile image', 'ai-eshop-optimizer'), 'mobileId', 'mobileUrl', props),
					el('p', { style: { color: '#646970', fontSize: '12px', margin: '4px 0 0' } },
						__('Set both for a responsive <picture>; set just one to use it everywhere.', 'ai-eshop-optimizer'))
				)
			);

			var hasContent = (a.topTitle || a.headline || a.description || a.desktopId || a.mobileId);

			var preview;
			if (ServerSideRender && hasContent) {
				preview = el(ServerSideRender, { block: 'aieo/page-hero', attributes: a });
			} else {
				preview = el('div', {
					style: { padding: '28px', border: '1px dashed #c3c4c7', borderRadius: '4px', textAlign: 'center', color: '#646970' }
				},
					el('strong', { style: { display: 'block', marginBottom: '4px', color: '#1e1e1e' } }, __('AIEO Page Hero', 'ai-eshop-optimizer')),
					__('Add a title, headline, description or image in the sidebar.', 'ai-eshop-optimizer'));
			}

			return el(Fragment, {}, controls, el('div', useBlockProps(), preview));
		},

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