/**
 * Hidden Field Block
 */

(function (blocks, element, blockEditor, components, i18n) {
	const { registerBlockType } = blocks;
	const { createElement: el, Fragment, useEffect } = element;
	const { InspectorControls, useBlockProps } = blockEditor;
	const { PanelBody, TextControl } = components;
	const { __ } = i18n;

	registerBlockType('giraforms/hidden-field', {
		icon: {
			src: 'hidden',
			foreground: '#3858e9'
		},
		edit: function (props) {
			const { attributes, setAttributes } = props;
			const { fieldId, fieldName, defaultValue } = attributes;

			// Generate field ID if not set
			useEffect(() => {
				if (!fieldId) {
					setAttributes({
						fieldId: 'hidden_' + Math.random().toString(36).substring(2, 11),
					});
				}
			}, []);

			const blockProps = useBlockProps({
				className: 'giraforms-field giraforms-field-hidden',
			});

			return el(
				Fragment,
				null,
				// Inspector Controls
				el(
					InspectorControls,
					null,
					el(
						PanelBody,
						{ title: __('Field Settings', 'giraforms'), initialOpen: true },
						el(TextControl, {
							label: __('Field Name', 'giraforms'),
							help: __('Internal name for this hidden field (not visible to users)', 'giraforms'),
							value: fieldName,
							onChange: (value) => setAttributes({ fieldName: value }),
						}),
						el(TextControl, {
							label: __('Default Value', 'giraforms'),
							help: __('The value to store in this hidden field', 'giraforms'),
							value: defaultValue,
							onChange: (value) => setAttributes({ defaultValue: value }),
						})
					)
				),
				// Block Content - Visual indicator in editor
				el(
					'div',
					blockProps,
					el(
						'div',
						{
							className: 'giraforms-hidden-field-indicator',
							style: {
								padding: '12px',
								backgroundColor: '#f0f0f1',
								border: '1px dashed #8c8f94',
								borderRadius: '4px',
								textAlign: 'center'
							}
						},
						el('span', {
							style: {
								fontSize: '12px',
								color: '#50575e',
								fontFamily: 'monospace'
							}
						}, '🔒 ' + __('Hidden Field:', 'giraforms') + ' ' + fieldName),
						defaultValue && el('div', {
							style: {
								fontSize: '11px',
								color: '#757575',
								marginTop: '4px'
							}
						}, __('Value:', 'giraforms') + ' "' + defaultValue + '"')
					)
				)
			);
		},

		save: function (props) {
			const { attributes } = props;
			const { fieldId, fieldName, defaultValue } = attributes;

			const blockProps = useBlockProps.save({
				className: 'giraforms-field giraforms-field-hidden',
				'data-field-id': fieldId,
				'data-label': fieldName,
			});

			return el(
				'div',
				blockProps,
				el('input', {
					type: 'hidden',
					id: fieldId,
					name: fieldId,
					value: defaultValue,
					'data-label': fieldName,
				})
			);
		},
	});
})(
	window.wp.blocks,
	window.wp.element,
	window.wp.blockEditor,
	window.wp.components,
	window.wp.i18n
);
