/**
 * AIEO Trust Badges — block editor registration.
 *
 * Pairs with the server-side render in includes/class-aieo-trust-badges-block.php.
 * Provides the inserter listing + a repeater (icon / title / subtitle per item).
 * Canvas preview is a static Placeholder; the strip renders server-side.
 */
(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 PanelBody      = wp.components.PanelBody;
	var SelectControl  = wp.components.SelectControl;
	var TextControl    = wp.components.TextControl;
	var ToggleControl  = wp.components.ToggleControl;
	var Button         = wp.components.Button;
	var Placeholder    = wp.components.Placeholder;

	var cfg   = (typeof window !== 'undefined' && window.aieoTrustBadgesConfig) || {};
	var slugs = Array.isArray(cfg.slugs) ? cfg.slugs : ['shipping', 'payment', 'returns', 'quality'];
	var defaultItems = Array.isArray(cfg.defaultItems) ? cfg.defaultItems : [];

	function iconOptions() {
		return slugs.map(function (s) { return { value: s, label: s }; });
	}

	function cloneItems(items) {
		return (items || []).map(function (it) {
			return { icon: it.icon || 'shipping', iconUrl: it.iconUrl || '', title: it.title || '', subtitle: it.subtitle || '' };
		});
	}

	wp.blocks.registerBlockType('aieo/trust-badges', {
		title:       __('AIEO Trust Badges', 'ai-eshop-optimizer'),
		category:    'theme',
		icon:        'awards',
		description: __('A trust strip of icon + title + subtitle columns.', 'ai-eshop-optimizer'),
		keywords:    ['trust', 'badges', 'features', 'usp', 'aieo'],
		supports:    { align: ['wide', 'full'], spacing: { margin: true, padding: true } },
		attributes:  {
			items:        { type: 'array',   default: defaultItems },
			align:        { type: 'string',  default: '' },
			gap:          { type: 'string',  default: '24px' },
			divider:      { type: 'boolean', default: true },
			dividerColor: { type: 'string',  default: '#000000' },
			dividerWidth: { type: 'string',  default: '1px' }
		},

		edit: function (props) {
			var items = Array.isArray(props.attributes.items) ? props.attributes.items : [];
			var setItems = function (next) { props.setAttributes({ items: next }); };

			function updateItem(i, key, value) {
				var next = cloneItems(items);
				if (!next[i]) { return; }
				next[i][key] = value;
				setItems(next);
			}
			function removeItem(i) {
				var next = cloneItems(items);
				next.splice(i, 1);
				setItems(next);
			}
			function addItem() {
				var next = cloneItems(items);
				next.push({ icon: slugs[0] || 'shipping', iconUrl: '', title: '', subtitle: '' });
				setItems(next);
			}

			var itemPanels = items.map(function (it, i) {
				return el(PanelBody, { key: i, title: (__('Badge', 'ai-eshop-optimizer') + ' ' + (i + 1) + (it.title ? ' — ' + it.title : '')), initialOpen: false },
					el(SelectControl, {
						label: __('Built-in icon', 'ai-eshop-optimizer'),
						value: it.icon || 'shipping',
						options: iconOptions(),
						onChange: function (v) { updateItem(i, 'icon', v); }
					}),
					el(TextControl, {
						label: __('Custom icon URL (optional — overrides the built-in)', 'ai-eshop-optimizer'),
						value: it.iconUrl || '',
						onChange: function (v) { updateItem(i, 'iconUrl', v); }
					}),
					el(TextControl, {
						label: __('Title', 'ai-eshop-optimizer'),
						value: it.title || '',
						onChange: function (v) { updateItem(i, 'title', v); }
					}),
					el(TextControl, {
						label: __('Subtitle', 'ai-eshop-optimizer'),
						value: it.subtitle || '',
						onChange: function (v) { updateItem(i, 'subtitle', v); }
					}),
					el(Button, { isDestructive: true, variant: 'secondary', onClick: function () { removeItem(i); } },
						__('Remove badge', 'ai-eshop-optimizer'))
				);
			});

			var controls = el(InspectorControls, {},
				el(PanelBody, { title: __('Trust badges', 'ai-eshop-optimizer'), initialOpen: true },
					el('p', { style: { color: '#50575e' } }, __('One row on desktop, stacked on mobile. Each badge is one column: icon + title + subtitle.', 'ai-eshop-optimizer')),
					el(TextControl, {
						label: __('Space between badges (gap)', 'ai-eshop-optimizer'),
						help: __('CSS length, e.g. 24px, 2rem, 5%.', 'ai-eshop-optimizer'),
						value: props.attributes.gap || '24px',
						onChange: function (v) { props.setAttributes({ gap: v }); }
					}),
					el(ToggleControl, {
						label: __('Vertical divider between badges', 'ai-eshop-optimizer'),
						help: __('A thin line in the gap between each badge (desktop only — hidden when stacked on mobile).', 'ai-eshop-optimizer'),
						checked: props.attributes.divider !== false,
						onChange: function (v) { props.setAttributes({ divider: !!v }); }
					}),
					(props.attributes.divider !== false) && el(TextControl, {
						label: __('Divider colour (hex)', 'ai-eshop-optimizer'),
						help: __('e.g. #000000.', 'ai-eshop-optimizer'),
						value: props.attributes.dividerColor || '#000000',
						onChange: function (v) { props.setAttributes({ dividerColor: v }); }
					}),
					(props.attributes.divider !== false) && el(TextControl, {
						label: __('Divider thickness', 'ai-eshop-optimizer'),
						help: __('CSS length, e.g. 1px, 2px.', 'ai-eshop-optimizer'),
						value: props.attributes.dividerWidth || '1px',
						onChange: function (v) { props.setAttributes({ dividerWidth: v }); }
					}),
					el(Button, { variant: 'primary', onClick: addItem }, __('+ Add badge', 'ai-eshop-optimizer'))
				),
				itemPanels
			);

			var previewLabels = items.map(function (it) { return it.title || '—'; }).join('  ·  ');

			return el(Fragment, {},
				controls,
				el('div', useBlockProps(),
					el(Placeholder, {
						icon: 'awards',
						label: __('AIEO Trust Badges', 'ai-eshop-optimizer'),
						instructions: __('Renders the trust strip on the front-end.', 'ai-eshop-optimizer')
					}, el('div', { style: { color: '#1e1e1e', fontWeight: 600 } }, previewLabels || __('No badges — add one in the sidebar.', 'ai-eshop-optimizer')))
				)
			);
		},

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