(function (blocks, blockEditor, components, element, i18n) {
	'use strict';

	var registerBlockType = blocks.registerBlockType;
	var useBlockProps = blockEditor.useBlockProps;
	var InspectorControls = blockEditor.InspectorControls;
	var RichText = blockEditor.RichText;
	var PanelBody = components.PanelBody;
	var TextControl = components.TextControl;
	var TextareaControl = components.TextareaControl;
	var SelectControl = components.SelectControl;
	var Notice = components.Notice;
	var Fragment = element.Fragment;
	var el = element.createElement;
	var __ = i18n.__;

	var contactDefaults = {
		nameLabel: 'שם מלא',
		emailLabel: 'דוא״ל לחזרה',
		topicLabel: 'נושא הפנייה',
		subjectLabel: 'כותרת קצרה',
		messageLabel: 'ההודעה',
		submitLabel: 'שליחת ההודעה',
		namePlaceholder: 'ישראל ישראלי',
		emailPlaceholder: 'you@mail.com',
		subjectPlaceholder: 'על מה המכתב?',
		messagePlaceholder: 'כתבו בחופשיות — אנחנו קוראים הכול.',
		generalLabel: 'שאלה כללית',
		contentLabel: 'הצעת תוכן',
		correctionLabel: 'תיקון טעות',
		oracleLabel: 'שאלה לאורקל',
		consentText: 'אני מאשר/ת שהפרטים ישמשו למענה על הפנייה בלבד, בהתאם ל%s.',
		privacyLabel: 'מדיניות הפרטיות',
		securityNote: 'מאובטח באמצעות WordPress. הפרטים משמשים למענה בלבד.',
		successMessage: 'ההודעה התקבלה. נשיב בהקדם.',
		invalidMessage: 'בדקו את שדות החובה ונסו שוב.',
		failedMessage: 'לא הצלחנו לשלוח את ההודעה. נסו שוב או פנו בדוא״ל למנהל האתר.'
	};

	var newsletterDefaults = {
		source: 'site',
		style: 'teal',
		emailLabel: 'כתובת דוא״ל',
		placeholder: 'הדוא״ל שלכם',
		buttonLabel: 'הרשמה',
		subscribedMessage: 'נרשמתם לפנתאון. המגילה הבאה — אליכם.',
		existsMessage: 'כתובת הדוא״ל הזו כבר רשומה.',
		invalidMessage: 'הזינו כתובת דוא״ל תקינה.'
	};

	function stringAttributes(defaults) {
		var schema = {};
		Object.keys(defaults).forEach(function (key) {
			schema[key] = { type: 'string', default: defaults[key] };
		});
		return schema;
	}

	function setValue(setAttributes, key) {
		return function (value) {
			var next = {};
			next[key] = value;
			setAttributes(next);
		};
	}

	function editableText(tagName, className, value, onChange, placeholder) {
		return el(RichText, {
			tagName: tagName,
			className: className,
			value: value,
			onChange: onChange,
			placeholder: placeholder,
			allowedFormats: []
		});
	}

	function fieldPreview(label, placeholder, multiline) {
		return el(
			'div',
			{ className: 'hp-editor-field' },
			label,
			multiline
				? el('div', { className: 'hp-editor-input hp-editor-textarea', 'aria-hidden': 'true' }, placeholder)
				: el('div', { className: 'hp-editor-input', 'aria-hidden': 'true' }, placeholder)
		);
	}

	registerBlockType('hapantheon/contact-form', {
		apiVersion: 2,
		title: __('HaPantheon Contact Form', 'hapantheon'),
		description: __('A visual, editable contact form that sends mail through WordPress.', 'hapantheon'),
		icon: 'email-alt',
		category: 'widgets',
		keywords: [__('contact', 'hapantheon'), __('form', 'hapantheon'), __('email', 'hapantheon')],
		attributes: stringAttributes(contactDefaults),
		supports: {
			align: ['wide', 'full'],
			anchor: true,
			html: false,
			color: { background: true, text: true, gradients: true },
			spacing: { margin: true, padding: true }
		},
		edit: function (props) {
			var a = props.attributes;
			var change = function (key) { return setValue(props.setAttributes, key); };
			var blockProps = useBlockProps({ className: 'hp-editor-form-preview hp-editor-contact-preview', dir: 'rtl' });

			return el(
				Fragment,
				null,
				el(
					InspectorControls,
					null,
					el(
						PanelBody,
						{ title: __('Field placeholders', 'hapantheon'), initialOpen: true },
						el(TextControl, { label: __('Name placeholder', 'hapantheon'), value: a.namePlaceholder, onChange: change('namePlaceholder') }),
						el(TextControl, { label: __('Email placeholder', 'hapantheon'), value: a.emailPlaceholder, onChange: change('emailPlaceholder') }),
						el(TextControl, { label: __('Subject placeholder', 'hapantheon'), value: a.subjectPlaceholder, onChange: change('subjectPlaceholder') }),
						el(TextareaControl, { label: __('Message placeholder', 'hapantheon'), value: a.messagePlaceholder, onChange: change('messagePlaceholder') })
					),
					el(
						PanelBody,
						{ title: __('Consent and privacy', 'hapantheon'), initialOpen: false },
						el(TextareaControl, {
							label: __('Consent sentence', 'hapantheon'),
							help: __('Use %s where the privacy-policy link should appear.', 'hapantheon'),
							value: a.consentText,
							onChange: change('consentText')
						}),
						el(TextControl, { label: __('Privacy link label', 'hapantheon'), value: a.privacyLabel, onChange: change('privacyLabel') }),
						el(TextControl, { label: __('Security note', 'hapantheon'), value: a.securityNote, onChange: change('securityNote') })
					),
					el(
						PanelBody,
						{ title: __('Submission messages', 'hapantheon'), initialOpen: false },
						el(TextareaControl, { label: __('Success message', 'hapantheon'), value: a.successMessage, onChange: change('successMessage') }),
						el(TextareaControl, { label: __('Invalid form message', 'hapantheon'), value: a.invalidMessage, onChange: change('invalidMessage') }),
						el(TextareaControl, { label: __('Sending failed message', 'hapantheon'), value: a.failedMessage, onChange: change('failedMessage') })
					)
				),
				el(
					'div',
					blockProps,
					el(Notice, { status: 'info', isDismissible: false }, __('Visual form preview. Click any label or button text to edit it; use the sidebar for placeholders and messages.', 'hapantheon')),
					el(
						'div',
						{ className: 'hp-editor-two-columns' },
						fieldPreview(
							editableText('label', 'hp-editor-label', a.nameLabel, change('nameLabel'), __('Name label', 'hapantheon')),
							a.namePlaceholder,
							false
						),
						fieldPreview(
							editableText('label', 'hp-editor-label', a.emailLabel, change('emailLabel'), __('Email label', 'hapantheon')),
							a.emailPlaceholder,
							false
						)
					),
					el(
						'div',
						{ className: 'hp-editor-field' },
						editableText('label', 'hp-editor-label', a.topicLabel, change('topicLabel'), __('Topic label', 'hapantheon')),
						el(
							'div',
							{ className: 'hp-editor-segments' },
							editableText('span', 'hp-editor-segment is-active', a.generalLabel, change('generalLabel'), __('General', 'hapantheon')),
							editableText('span', 'hp-editor-segment', a.contentLabel, change('contentLabel'), __('Content', 'hapantheon')),
							editableText('span', 'hp-editor-segment', a.correctionLabel, change('correctionLabel'), __('Correction', 'hapantheon')),
							editableText('span', 'hp-editor-segment', a.oracleLabel, change('oracleLabel'), __('Oracle', 'hapantheon'))
						)
					),
					fieldPreview(
						editableText('label', 'hp-editor-label', a.subjectLabel, change('subjectLabel'), __('Subject label', 'hapantheon')),
						a.subjectPlaceholder,
						false
					),
					fieldPreview(
						editableText('label', 'hp-editor-label', a.messageLabel, change('messageLabel'), __('Message label', 'hapantheon')),
						a.messagePlaceholder,
						true
					),
					el(
						'div',
						{ className: 'hp-editor-consent' },
						el('span', { className: 'hp-editor-checkbox', 'aria-hidden': 'true' }),
						el('span', null, a.consentText.replace('%s', a.privacyLabel))
					),
					editableText('div', 'hp-editor-submit', a.submitLabel, change('submitLabel'), __('Submit label', 'hapantheon')),
					editableText('p', 'hp-editor-security', a.securityNote, change('securityNote'), __('Security note', 'hapantheon'))
				)
			);
		},
		save: function () {
			return null;
		}
	});

	registerBlockType('hapantheon/newsletter', {
		apiVersion: 2,
		title: __('HaPantheon Newsletter', 'hapantheon'),
		description: __('A visual newsletter signup form whose entries are stored in WordPress.', 'hapantheon'),
		icon: 'megaphone',
		category: 'widgets',
		keywords: [__('newsletter', 'hapantheon'), __('signup', 'hapantheon'), __('email', 'hapantheon')],
		attributes: stringAttributes(newsletterDefaults),
		supports: {
			align: ['wide', 'full'],
			anchor: true,
			html: false,
			color: { background: true, text: true, gradients: true },
			spacing: { margin: true, padding: true }
		},
		edit: function (props) {
			var a = props.attributes;
			var change = function (key) { return setValue(props.setAttributes, key); };
			var blockProps = useBlockProps({ className: 'hp-editor-form-preview hp-editor-newsletter-preview is-' + a.style, dir: 'rtl' });

			return el(
				Fragment,
				null,
				el(
					InspectorControls,
					null,
					el(
						PanelBody,
						{ title: __('Newsletter settings', 'hapantheon'), initialOpen: true },
						el(SelectControl, {
							label: __('Button style', 'hapantheon'),
							value: a.style,
							options: [
								{ label: __('Teal', 'hapantheon'), value: 'teal' },
								{ label: __('Gold', 'hapantheon'), value: 'gold' }
							],
							onChange: change('style')
						}),
						el(TextControl, {
							label: __('Signup source', 'hapantheon'),
							help: __('Stored with each subscriber so signup locations can be identified.', 'hapantheon'),
							value: a.source,
							onChange: change('source')
						}),
						el(TextControl, { label: __('Email placeholder', 'hapantheon'), value: a.placeholder, onChange: change('placeholder') })
					),
					el(
						PanelBody,
						{ title: __('Submission messages', 'hapantheon'), initialOpen: false },
						el(TextareaControl, { label: __('Subscribed message', 'hapantheon'), value: a.subscribedMessage, onChange: change('subscribedMessage') }),
						el(TextareaControl, { label: __('Already subscribed message', 'hapantheon'), value: a.existsMessage, onChange: change('existsMessage') }),
						el(TextareaControl, { label: __('Invalid email message', 'hapantheon'), value: a.invalidMessage, onChange: change('invalidMessage') })
					)
				),
				el(
					'div',
					blockProps,
					el(Notice, { status: 'info', isDismissible: false }, __('Visual form preview. Click the label or button text to edit it.', 'hapantheon')),
					editableText('p', 'hp-editor-label hp-editor-newsletter-label', a.emailLabel, change('emailLabel'), __('Email label', 'hapantheon')),
					el(
						'div',
						{ className: 'hp-editor-newsletter-row' },
						el('div', { className: 'hp-editor-input hp-editor-newsletter-input', 'aria-hidden': 'true' }, a.placeholder),
						editableText('div', 'hp-editor-submit', a.buttonLabel, change('buttonLabel'), __('Button label', 'hapantheon'))
					)
				)
			);
		},
		save: function () {
			return null;
		}
	});
})(window.wp.blocks, window.wp.blockEditor, window.wp.components, window.wp.element, window.wp.i18n);
