/**
 * Consent Field Block
 */

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

	registerBlockType('giraforms/consent-field', {
		icon: {
			src: 'privacy',
			foreground: '#3858e9'
		},
		edit: function (props) {
			const { attributes, setAttributes, clientId } = props;
			const { fieldId, label, required, privacyPolicyUrl, privacyPolicyText, consentText, errorMessage } = attributes;

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

			// Get WordPress privacy policy URL if not set
			useEffect(() => {
				if (!privacyPolicyUrl && window.giraFormsData && window.giraFormsData.privacyPolicyUrl) {
					setAttributes({ privacyPolicyUrl: window.giraFormsData.privacyPolicyUrl });
				}
			}, []);

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

			// Replace {privacy_policy} placeholder with link
			const renderConsentText = () => {
				const parts = consentText.split('{privacy_policy}');
				if (parts.length === 1) {
					return consentText;
				}

				return el(
					Fragment,
					null,
					parts[0],
					el('a', {
						href: privacyPolicyUrl || '#',
						target: '_blank',
						rel: 'noopener noreferrer',
					}, privacyPolicyText),
					parts[1]
				);
			};

			return el(
				Fragment,
				null,
				el(
					InspectorControls,
					null,
					el(
						PanelBody,
						{ title: __('Settings', 'giraforms'), initialOpen: true },
						el(ToggleControl, {
							label: __('Required Field', 'giraforms'),
							checked: required,
							onChange: (value) => setAttributes({ required: value }),
							help: __('Consent checkbox should typically be required', 'giraforms')
						})
					),
					el(
						PanelBody,
						{ title: __('Consent Text', 'giraforms'), initialOpen: true },
						el(TextareaControl, {
							label: __('Consent Message', 'giraforms'),
							value: consentText,
							onChange: (value) => setAttributes({ consentText: value }),
							help: __('Use {privacy_policy} as a placeholder for the privacy policy link', 'giraforms'),
							rows: 3
						}),
						el(TextControl, {
							label: __('Privacy Policy Link Text', 'giraforms'),
							value: privacyPolicyText,
							onChange: (value) => setAttributes({ privacyPolicyText: value })
						}),
						el(TextControl, {
							label: __('Privacy Policy URL', 'giraforms'),
							value: privacyPolicyUrl,
							onChange: (value) => setAttributes({ privacyPolicyUrl: value }),
							help: __('Leave empty to use WordPress privacy policy page', 'giraforms'),
							type: 'url'
						})
					),
					el(
						PanelBody,
						{ title: __('Error Message', 'giraforms') },
						el(TextControl, {
							label: __('Error Message', 'giraforms'),
							value: errorMessage,
							onChange: (value) => setAttributes({ errorMessage: value }),
							help: __('Message shown when consent is not given', 'giraforms')
						})
					)
				),
				el(
					'div',
					blockProps,
					el('div', { className: 'giraforms-checkbox-wrapper' },
						el('input', {
							type: 'checkbox',
							disabled: true,
							className: 'giraforms-consent-checkbox',
						}),
						el('label', {
							className: 'giraforms-consent-label',
						},
							renderConsentText(),
							required && el('span', { className: 'required' }, '*')
						)
					)
				)
			);
		},
		save: function () {
			return null;
		},
		deprecated: [
			{
				attributes: {
					fieldId: { type: 'string', default: '' },
					label: { type: 'string', default: 'I agree to the privacy policy' },
					required: { type: 'boolean', default: true },
					privacyPolicyUrl: { type: 'string', default: '' },
					privacyPolicyText: { type: 'string', default: 'privacy policy' },
					consentText: { type: 'string', default: 'I agree to the {privacy_policy} and consent to my data being processed.' },
					errorMessage: { type: 'string', default: 'You must accept the privacy policy to continue.' },
					conditionalRules: { type: 'object', default: { enabled: false, logic: 'and', conditions: [] } },
				},
				save: function (props) {
					var attrs = props.attributes;
					var fieldId = attrs.fieldId;
					var required = attrs.required;
					var consentText = attrs.consentText;
					var errorMessage = attrs.errorMessage;
					var blockProps = useBlockProps.save({
						className: 'giraforms-field giraforms-consent-field',
						'data-field-id': fieldId,
					});
					return el('div', blockProps,
						el('div', { className: 'giraforms-checkbox-wrapper' },
							el('input', {
								type: 'checkbox',
								id: fieldId,
								name: fieldId,
								value: 'yes',
								required: required,
								className: 'giraforms-consent-checkbox',
								'data-error-message': errorMessage,
							}),
							el('label', {
								htmlFor: fieldId,
								className: required ? 'giraforms-consent-label required' : 'giraforms-consent-label',
							}, consentText)
						)
					);
				},
				migrate: function (attributes) {
					return attributes;
				},
			}
		],
	});
})(
	window.wp.blocks,
	window.wp.element,
	window.wp.blockEditor,
	window.wp.components,
	window.wp.i18n
);
