/**
 * Form Container Block
 */

(function (blocks, element, blockEditor, components, i18n, data) {
	const { registerBlockType } = blocks;
	const { createElement: el, Fragment, useEffect, useMemo } = element;
	const { InnerBlocks, InspectorControls, BlockControls, useBlockProps } = blockEditor;
	const { PanelBody, TextControl, TextareaControl, ToggleControl, SelectControl, CheckboxControl, ColorPalette, ColorPicker, ColorIndicator, Dropdown, RangeControl, BaseControl, Button, DateTimePicker, Popover, Placeholder, Modal, Icon, FormTokenField } = components;
	const { __ } = i18n;
	const { dispatch, select, useSelect } = data;

	// Allowed Inner Blocks
	const ALLOWED_BLOCKS = [
		// Blocks GiraForms
		'giraforms/text-field',
		'giraforms/number-field',
		'giraforms/textarea-field',
		'giraforms/email-field',
		'giraforms/phone-field',
		'giraforms/url-field',
		'giraforms/password-field',
		'giraforms/hidden-field',
		'giraforms/date-field',
		'giraforms/select-field',
		'giraforms/checkbox-field',
		'giraforms/radio-field',
		'giraforms/color-picker-field',
		'giraforms/range-slider-field',
		'giraforms/submit-button',
		
		// Blocks WordPress core (for layout purposes)
		'core/columns',
		'core/column',
		'core/group',
		'core/row',
		'core/stack',
		'core/separator',
		'core/spacer',
		'core/heading',
		'core/paragraph',
	];

	// Helper function to check if URL is internal (same domain)
	const isInternalUrl = (url) => {
		if (!url) return true;
		// Relative URLs are always internal
		if (url.startsWith('/') || url.startsWith('#') || url.startsWith('?')) {
			return true;
		}
		try {
			const urlObj = new URL(url, window.location.origin);
			return urlObj.hostname === window.location.hostname;
		} catch (e) {
			// Invalid URL, consider it as internal (will be validated server-side)
			return true;
		}
	};

	// Template Categories
	const TEMPLATE_CATEGORIES = {
		general: { label: __('General', 'giraforms'), order: 1 },
		business: { label: __('Business', 'giraforms'), order: 2 },
		events: { label: __('Events & Booking', 'giraforms'), order: 3 },
		feedback: { label: __('Feedback & Survey', 'giraforms'), order: 4 },
	};

	// Form Templates
	const FORM_TEMPLATES = [
		{
			key: 'contact',
			name: __('Contact Form', 'giraforms'),
			description: __('A simple contact form with name, email, subject and message', 'giraforms'),
			category: 'general',
			icon: 'email',
			formName: 'Contact',
			blocks: [
				['giraforms/text-field', { label: 'Full Name', placeholder: 'Your name', required: true }],
				['giraforms/email-field', { label: 'Email Address', placeholder: 'your@email.com', required: true }],
				['giraforms/text-field', { label: 'Subject', placeholder: 'Message subject', required: true }],
				['giraforms/textarea-field', { label: 'Message', placeholder: 'Your message...', rows: 6, required: true }],
				['giraforms/submit-button', { buttonText: 'Send Message', alignment: 'left' }],
			],
		},
		{
			key: 'registration',
			name: __('Registration Form', 'giraforms'),
			description: __('A complete registration form with personal information', 'giraforms'),
			category: 'general',
			icon: 'admin-users',
			formName: 'Registration',
			blocks: [
				['giraforms/text-field', { label: 'First Name', required: true }],
				['giraforms/text-field', { label: 'Last Name', required: true }],
				['giraforms/email-field', { label: 'Email', placeholder: 'your@email.com', required: true }],
				['giraforms/phone-field', { label: 'Phone', placeholder: '+1 234 567 8900', required: false }],
				['giraforms/select-field', {
					label: 'Country',
					required: true,
					options: [
						{ label: 'United States', value: 'US' },
						{ label: 'United Kingdom', value: 'UK' },
						{ label: 'Canada', value: 'CA' },
						{ label: 'Australia', value: 'AU' }
					]
				}],
				['giraforms/checkbox-field', {
					label: 'Terms',
					required: true,
					options: [{ label: 'I accept the terms and conditions', value: 'terms' }]
				}],
				['giraforms/submit-button', { buttonText: 'Register', alignment: 'center' }],
			],
		},
		{
			key: 'newsletter',
			name: __('Newsletter Form', 'giraforms'),
			description: __('A simple newsletter subscription form', 'giraforms'),
			category: 'general',
			icon: 'megaphone',
			formName: 'Newsletter',
			blocks: [
				['giraforms/text-field', { label: 'First Name', placeholder: 'Your first name', required: true }],
				['giraforms/email-field', { label: 'Email', placeholder: 'your@email.com', required: true }],
				['giraforms/checkbox-field', {
					label: 'Preferences',
					required: false,
					options: [
						{ label: 'Product updates', value: 'products' },
						{ label: 'Promotional offers', value: 'offers' },
						{ label: 'Blog articles', value: 'blog' }
					]
				}],
				['giraforms/submit-button', { buttonText: 'Subscribe', alignment: 'center' }],
			],
		},
		{
			key: 'feedback',
			name: __('Feedback Form', 'giraforms'),
			description: __('A form to collect feedback and comments', 'giraforms'),
			category: 'feedback',
			icon: 'format-status',
			formName: 'Feedback',
			blocks: [
				['giraforms/text-field', { label: 'Name', required: true }],
				['giraforms/email-field', { label: 'Email', placeholder: 'your@email.com', required: true }],
				['giraforms/radio-field', {
					label: 'How would you rate our service?',
					required: true,
					options: [
						{ label: 'Excellent', value: 'excellent' },
						{ label: 'Good', value: 'good' },
						{ label: 'Average', value: 'average' },
						{ label: 'Poor', value: 'poor' }
					]
				}],
				['giraforms/textarea-field', { label: 'Your comments', placeholder: 'Share your experience...', rows: 5, required: true }],
				['giraforms/checkbox-field', {
					label: '',
					required: false,
					options: [{ label: 'I would like to be contacted about my feedback', value: 'contact' }]
				}],
				['giraforms/submit-button', { buttonText: 'Submit Feedback', alignment: 'left' }],
			],
		},
		{
			key: 'support',
			name: __('Support Request', 'giraforms'),
			description: __('A support ticket form with category and priority selection', 'giraforms'),
			category: 'general',
			icon: 'sos',
			formName: 'Support Request',
			blocks: [
				['giraforms/text-field', { label: 'Full Name', placeholder: 'Your name', required: true }],
				['giraforms/email-field', { label: 'Email', placeholder: 'your@email.com', required: true }],
				['giraforms/select-field', {
					label: 'Category',
					required: true,
					options: [
						{ label: 'Technical Issue', value: 'technical' },
						{ label: 'Billing', value: 'billing' },
						{ label: 'Account', value: 'account' },
						{ label: 'Feature Request', value: 'feature' },
						{ label: 'Other', value: 'other' }
					]
				}],
				['giraforms/radio-field', {
					label: 'Priority',
					required: true,
					options: [
						{ label: 'Low', value: 'low' },
						{ label: 'Medium', value: 'medium' },
						{ label: 'High', value: 'high' },
						{ label: 'Critical', value: 'critical' }
					]
				}],
				['giraforms/textarea-field', { label: 'Description', placeholder: 'Describe your issue in detail...', rows: 6, required: true }],
				['giraforms/submit-button', { buttonText: 'Submit Request', alignment: 'left' }],
			],
		},
		{
			key: 'quote',
			name: __('Quote Request', 'giraforms'),
			description: __('A multi-column quote request form for services or products', 'giraforms'),
			category: 'business',
			icon: 'money-alt',
			formName: 'Quote Request',
			blocks: [
				['core/columns', {}, [
					['core/column', {}, [
						['giraforms/text-field', { label: 'First Name', required: true }],
					]],
					['core/column', {}, [
						['giraforms/text-field', { label: 'Last Name', required: true }],
					]],
				]],
				['core/columns', {}, [
					['core/column', {}, [
						['giraforms/email-field', { label: 'Email', placeholder: 'your@email.com', required: true }],
					]],
					['core/column', {}, [
						['giraforms/phone-field', { label: 'Phone', placeholder: '+1 234 567 8900', required: false }],
					]],
				]],
				['giraforms/select-field', {
					label: 'Service',
					required: true,
					options: [
						{ label: 'Web Design', value: 'web-design' },
						{ label: 'Development', value: 'development' },
						{ label: 'Consulting', value: 'consulting' },
						{ label: 'Marketing', value: 'marketing' },
						{ label: 'Other', value: 'other' }
					]
				}],
				['giraforms/select-field', {
					label: 'Budget',
					required: false,
					options: [
						{ label: 'Under $1,000', value: 'under-1k' },
						{ label: '$1,000 - $5,000', value: '1k-5k' },
						{ label: '$5,000 - $10,000', value: '5k-10k' },
						{ label: '$10,000 - $25,000', value: '10k-25k' },
						{ label: 'Over $25,000', value: 'over-25k' }
					]
				}],
				['giraforms/textarea-field', { label: 'Project Description', placeholder: 'Tell us about your project...', rows: 5, required: true }],
				['giraforms/submit-button', { buttonText: 'Request Quote', alignment: 'left' }],
			],
		},
		{
			key: 'event',
			name: __('Event Registration', 'giraforms'),
			description: __('A multi-column event registration form with attendee details', 'giraforms'),
			category: 'events',
			icon: 'calendar-alt',
			formName: 'Event Registration',
			blocks: [
				['core/columns', {}, [
					['core/column', {}, [
						['giraforms/text-field', { label: 'First Name', required: true }],
					]],
					['core/column', {}, [
						['giraforms/text-field', { label: 'Last Name', required: true }],
					]],
				]],
				['core/columns', {}, [
					['core/column', {}, [
						['giraforms/email-field', { label: 'Email', placeholder: 'your@email.com', required: true }],
					]],
					['core/column', {}, [
						['giraforms/phone-field', { label: 'Phone', required: false }],
					]],
				]],
				['core/heading', { content: 'Event Details', level: 3 }],
				['giraforms/date-field', { label: 'Preferred Date', required: true }],
				['giraforms/select-field', {
					label: 'Number of Attendees',
					required: true,
					options: [
						{ label: '1', value: '1' },
						{ label: '2', value: '2' },
						{ label: '3', value: '3' },
						{ label: '4', value: '4' },
						{ label: '5+', value: '5plus' }
					]
				}],
				['giraforms/textarea-field', { label: 'Dietary Requirements / Special Needs', placeholder: 'Let us know if you have any special requirements...', rows: 4, required: false }],
				['giraforms/consent-field', { required: true }],
				['giraforms/submit-button', { buttonText: 'Register', alignment: 'center' }],
			],
		},
		{
			key: 'job',
			name: __('Job Application', 'giraforms'),
			description: __('A professional job application form with multi-column layout', 'giraforms'),
			category: 'business',
			icon: 'businessperson',
			formName: 'Job Application',
			blocks: [
				['core/heading', { content: 'Job Application', level: 3 }],
				['core/columns', {}, [
					['core/column', {}, [
						['giraforms/text-field', { label: 'First Name', required: true }],
					]],
					['core/column', {}, [
						['giraforms/text-field', { label: 'Last Name', required: true }],
					]],
				]],
				['core/columns', {}, [
					['core/column', {}, [
						['giraforms/email-field', { label: 'Email', placeholder: 'your@email.com', required: true }],
					]],
					['core/column', {}, [
						['giraforms/phone-field', { label: 'Phone', required: true }],
					]],
				]],
				['giraforms/url-field', { label: 'Portfolio / LinkedIn URL', placeholder: 'https://', required: false }],
				['giraforms/select-field', {
					label: 'Position',
					required: true,
					options: [
						{ label: 'Frontend Developer', value: 'frontend' },
						{ label: 'Backend Developer', value: 'backend' },
						{ label: 'Designer', value: 'designer' },
						{ label: 'Project Manager', value: 'pm' },
						{ label: 'Other', value: 'other' }
					]
				}],
				['giraforms/textarea-field', { label: 'Cover Letter / Motivation', placeholder: 'Tell us why you would be a great fit...', rows: 6, required: true }],
				['giraforms/consent-field', { required: true }],
				['giraforms/submit-button', { buttonText: 'Submit Application', alignment: 'left' }],
			],
		},
		{
			key: 'survey',
			name: __('Survey Form', 'giraforms'),
			description: __('A survey form with rating scales and multiple choice questions', 'giraforms'),
			category: 'feedback',
			icon: 'chart-bar',
			formName: 'Survey',
			blocks: [
				['core/heading', { content: 'We value your opinion', level: 3 }],
				['giraforms/radio-field', {
					label: 'How satisfied are you with our service?',
					required: true,
					options: [
						{ label: 'Very Satisfied', value: 'very-satisfied' },
						{ label: 'Satisfied', value: 'satisfied' },
						{ label: 'Neutral', value: 'neutral' },
						{ label: 'Dissatisfied', value: 'dissatisfied' },
						{ label: 'Very Dissatisfied', value: 'very-dissatisfied' }
					]
				}],
				['giraforms/radio-field', {
					label: 'How likely are you to recommend us?',
					required: true,
					options: [
						{ label: 'Very Likely', value: 'very-likely' },
						{ label: 'Likely', value: 'likely' },
						{ label: 'Neutral', value: 'neutral' },
						{ label: 'Unlikely', value: 'unlikely' },
						{ label: 'Very Unlikely', value: 'very-unlikely' }
					]
				}],
				['giraforms/checkbox-field', {
					label: 'What areas interest you most?',
					required: false,
					options: [
						{ label: 'Product Quality', value: 'quality' },
						{ label: 'Customer Service', value: 'service' },
						{ label: 'Pricing', value: 'pricing' },
						{ label: 'Innovation', value: 'innovation' },
						{ label: 'User Experience', value: 'ux' }
					]
				}],
				['giraforms/textarea-field', { label: 'Additional Comments', placeholder: 'Share any additional thoughts...', rows: 5, required: false }],
				['giraforms/submit-button', { buttonText: 'Submit Survey', alignment: 'center' }],
			],
		},
		{
			key: 'booking',
			name: __('Booking Form', 'giraforms'),
			description: __('A booking form with date, time selection and service options', 'giraforms'),
			category: 'events',
			icon: 'clock',
			formName: 'Booking',
			blocks: [
				['core/columns', {}, [
					['core/column', {}, [
						['giraforms/text-field', { label: 'Full Name', required: true }],
					]],
					['core/column', {}, [
						['giraforms/email-field', { label: 'Email', placeholder: 'your@email.com', required: true }],
					]],
				]],
				['core/columns', {}, [
					['core/column', {}, [
						['giraforms/date-field', { label: 'Preferred Date', required: true }],
					]],
					['core/column', {}, [
						['giraforms/time-field', { label: 'Preferred Time', required: true }],
					]],
				]],
				['giraforms/select-field', {
					label: 'Service',
					required: true,
					options: [
						{ label: 'Consultation', value: 'consultation' },
						{ label: 'Training Session', value: 'training' },
						{ label: 'Workshop', value: 'workshop' },
						{ label: 'Other', value: 'other' }
					]
				}],
				['giraforms/textarea-field', { label: 'Additional Notes', placeholder: 'Any special requests or notes...', rows: 4, required: false }],
				['giraforms/submit-button', { buttonText: 'Book Now', alignment: 'center' }],
			],
		},
		
	];

	// Helper to count form fields in a template (recursive, excludes submit button)
	var countTemplateFields = function(blocks) {
		var count = 0;
		blocks.forEach(function(block) {
			if (block[0].startsWith('giraforms/') && block[0] !== 'giraforms/submit-button') {
				count++;
			}
			if (block[2] && block[2].length > 0) {
				count += countTemplateFields(block[2]);
			}
		});
		return count;
	};


	registerBlockType('giraforms/form-container', {
		icon: {
			src: el('svg', { xmlns: 'http://www.w3.org/2000/svg', viewBox: '0 0 20 20', width: '20', height: '20' },
				el('path', { fill: '#3859ea', d: 'm7.3 0h0.2 0.2 0.2 0.2l0.3 0.2 0.2 0.3 0.1 0.3v0.2 0.3 0.3 0.4 0.3 0.3 0.5h1.2v-0.5-0.3l-0.1-0.4v-0.3-0.4-0.3l0.1-0.2 0.1-0.2 0.1-0.2 0.3-0.2 0.1-0.1h0.3 0.2 0.2l0.3 0.2 0.2 0.3 0.2 0.3v0.3 0.3 0.2 0.2 0.2 0.3 0.2 0.3 0.2 0.2 0.3 0.2 0.2 0.4l0.1 0.1 0.2 0.2 0.2 0.1 0.1-0.1 0.1-0.2 0.1-0.2 0.2-0.2 0.1-0.2 0.2-0.1 0.1-0.2 0.2-0.1 0.3-0.2 0.2-0.1h0.2l0.2-0.1h0.2 0.2 1.3c0 0.3 0 0.5 0 0.8v0.3l-0.1 0.2-0.1 0.2-0.1 0.2-0.1 0.2-0.1 0.2-0.1 0.2-0.3 0.3-0.1 0.1-0.2 0.1-0.2 0.1-0.2 0.1-0.2 0.1-0.1 0.1-0.2 0.1 0.1 0.1 0.2 0.2 0.2 0.2 0.3 0.2 0.2 0.3 0.3 0.2 0.2 0.2 0.3 0.3 0.2 0.2 0.3 0.3 0.3 0.2 0.2 0.2 0.2 0.3 0.2 0.2 0.2 0.3 0.2 0.2 0.1 0.3v0.3 0.3 0.3 0.3c-0.1 0.6-0.2 0.8-0.6 0.8h-0.2q-0.3 0-0.6 0.1h-0.2c-0.7-0.1-1.1-0.7-1.6-1.2h-4.4v8.9h-7.1c1-4.5 2-8.9 3-12.9 0.1-0.3 0.2-0.5 0.3-0.9l-0.4 0.1h-0.2-0.2-0.2-0.3-0.2l-0.2-0.1h-0.3l-0.2-0.2-0.3-0.1-0.2-0.2-0.1-0.1-0.3-0.2-0.2-0.2-0.1-0.2-0.1-0.3-0.1-0.2-0.1-0.2-0.1-0.2v-0.3c0-0.2 0-0.5 0-0.8 0.7 0.1 1.2 0 1.7 0l0.4 0.1 0.2 0.1 0.3 0.2 0.3 0.3 0.2 0.2 0.3 0.2 0.1 0.3 0.1 0.3 0.1 0.3v0.3l0.1 0.4v0.2l0.1-0.3 0.1-0.3v-0.4l0.1-0.3 0.1-0.1v-0.4-0.2-0.3-0.2-0.3-0.2-0.3-0.3-0.3-0.2-0.3-0.2-0.3-0.2-0.1l0.1-0.2 0.1-0.2 0.2-0.1z' }),
				el('path', { fill: '#fff', fillRule: 'evenodd', d: 'm10.8 8.1c-0.6 0-1-0.5-1-1 0-0.5 0.4-0.9 1-0.9 0.5 0 0.9 0.4 0.9 0.9 0 0.5-0.4 1-0.9 1z' })
			),
		},
		edit: function (props) {
			const { attributes, setAttributes, clientId } = props;
			const {
				formId,
				formName,
				submitButtonText,
				successMessage,
				redirectUrl,
				enableAjax,
				enableEmailNotifications,
				emailTemplateId,
				accentColor,
				textColor,
				borderColor,
				borderRadius,
				inputBackgroundColor,
				requiredColor,
				labelPosition,
				labelFontWeight,
				labelSpacing,
				uniqueEntryEnabled,
				uniqueEntryField,
				uniqueEntryMessage,
				accessRestriction,
				accessRestrictionMessage,
				accessAllowedRoles,
				submissionWindowEnabled,
				submissionWindowDays,
				submissionWindowStartTime,
				submissionWindowEndTime,
				submissionWindowMessage,
				scheduleEnabled,
				scheduleStartDate,
				scheduleEndDate,
				scheduleMessage,
				brevoEnabled,
				brevoListId,
				brevoEmailField,
				brevoFirstNameField,
				brevoLastNameField,
				brevoUpdateIfExists,
			} = attributes;

			// Check if premium is active (passed from PHP via wp_localize_script)
			const isPremium = typeof giraFormsData !== 'undefined' && giraFormsData.isPremium;

			// State for Form ID editing
			const [editingFormId, setEditingFormId] = wp.element.useState(false);
			const formIdBeforeEdit = wp.element.useRef(formId);

			

			const availableTemplates = useMemo(function() {
				return FORM_TEMPLATES.filter(function(template) {
					return !template.isPremium || isPremium;
				});
			}, [isPremium]);

			const availableTemplateCategories = useMemo(function() {
				return Object.keys(TEMPLATE_CATEGORIES).filter(function(catKey) {
					return availableTemplates.some(function(template) {
						return template.category === catKey;
					});
				});
			}, [availableTemplates]);

			const featuredTemplates = useMemo(function() {
				var shuffledTemplates = availableTemplates.slice();

				for (var i = shuffledTemplates.length - 1; i > 0; i--) {
					var randomIndex = Math.floor(Math.random() * (i + 1));
					var currentTemplate = shuffledTemplates[i];
					shuffledTemplates[i] = shuffledTemplates[randomIndex];
					shuffledTemplates[randomIndex] = currentTemplate;
				}

				return shuffledTemplates.slice(0, 4);
			}, [availableTemplates]);

			// State for template library modal
			var [showTemplateModal, setShowTemplateModal] = wp.element.useState(false);
			var [selectedCategory, setSelectedCategory] = wp.element.useState('all');
			var [isPreview, setIsPreview] = wp.element.useState(false);

			// Detect if form has inner blocks (for showing placeholder vs form content)
			var hasInnerBlocks = useSelect(function(select) {
				var block = select('core/block-editor').getBlock(clientId);
				return !!(block && block.innerBlocks && block.innerBlocks.length > 0);
			}, [clientId]);

			// Generate unique form ID if not exists
			useEffect(() => {
				if (!formId) {
					setAttributes({
						formId: 'form_' + Math.random().toString(36).substring(2, 11),
					});
				}
			}, []);

			// Recursive function to create blocks from template definition
			// Supports nested innerBlocks for core/columns layouts
			// blockConfig format: [blockName, attributes] or [blockName, attributes, innerBlocksTemplate]
			var createBlocksFromTemplate = function(templateBlocks) {
				return templateBlocks.map(function(blockConfig) {
					var blockName = blockConfig[0];
					var blockAttributes = blockConfig[1] || {};
					var innerBlocksTemplate = blockConfig[2] || [];

					var innerBlocks = [];
					if (innerBlocksTemplate.length > 0) {
						innerBlocks = createBlocksFromTemplate(innerBlocksTemplate);
					}

					return wp.blocks.createBlock(blockName, blockAttributes, innerBlocks);
				});
			};

			// Function to load a template by key
			var loadTemplate = function(templateKey) {
				var template = availableTemplates.find(function(t) { return t.key === templateKey; });
				if (!template) return;

				setAttributes({ formName: template.formName });

				var blocks = createBlocksFromTemplate(template.blocks);
				dispatch('core/block-editor').replaceInnerBlocks(clientId, blocks, false);
			};

			// Function to load a blank form with default fields
			var loadBlankForm = function() {
				var blocks = createBlocksFromTemplate([
					['giraforms/text-field', { label: 'Name' }],
					['giraforms/email-field', { label: 'Email' }],
					['giraforms/submit-button', { buttonText: 'Submit' }],
				]);
				dispatch('core/block-editor').replaceInnerBlocks(clientId, blocks, false);
			};

			// Build custom styles object for live preview
			const customStyles = {};
			if (accentColor) customStyles['--giraforms-accent-color'] = accentColor;
			if (textColor) customStyles['--giraforms-text-color'] = textColor;
			if (borderColor) customStyles['--giraforms-border-color'] = borderColor;
			if (borderRadius) customStyles['--giraforms-border-radius'] = borderRadius;
			if (inputBackgroundColor) customStyles['--giraforms-input-bg-color'] = inputBackgroundColor;
			if (requiredColor) customStyles['--giraforms-required-color'] = requiredColor;
			if (labelFontWeight) customStyles['--giraforms-label-font-weight'] = labelFontWeight;
			if (labelSpacing) customStyles['--giraforms-label-spacing'] = labelSpacing;

			const blockProps = useBlockProps({
				className: 'giraforms-form-container' + (isPreview ? ' giraforms-preview-mode' : ''),
				style: Object.keys(customStyles).length > 0 ? customStyles : undefined,
				'data-label-position': labelPosition || 'above',
			});

			return el(
				Fragment,
				null,
				// Toolbar
				el(
					BlockControls,
					null,
					el(components.ToolbarGroup, null,
						el(components.ToolbarButton, {
							icon: isPreview ? 'edit' : 'visibility',
							label: isPreview ? __('Edit', 'giraforms') : __('Preview', 'giraforms'),
							onClick: function () { setIsPreview(!isPreview); },
							isPressed: isPreview,
						})
					)
				),
				// Inspector Controls
				el(
					InspectorControls,
					null,
					// Form Templates Panel
					el(
						PanelBody,
						{
							title: __('Form Templates', 'giraforms'),
							initialOpen: false,
						},
						el('p', {
							style: { marginBottom: '12px', fontSize: '13px', color: '#757575' }
						}, __('Load a pre-built form template. This will replace your current form fields.', 'giraforms')),
						el('div', { style: { display: 'flex', flexDirection: 'column', gap: '8px' } },
							featuredTemplates.map(function(template) {
								return el(
									'div',
									{
										key: template.key,
										style: {
											border: '1px solid #ddd',
											borderRadius: '4px',
											padding: '12px',
											cursor: 'pointer',
											transition: 'all 0.2s',
											backgroundColor: '#fff'
										},
										onMouseEnter: function(e) {
											e.currentTarget.style.borderColor = '#385aea';
											e.currentTarget.style.backgroundColor = '#f0f6fc';
										},
										onMouseLeave: function(e) {
											e.currentTarget.style.borderColor = '#ddd';
											e.currentTarget.style.backgroundColor = '#fff';
										}
									},
									el('div', { style: { display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '4px' } },
										el(Icon, { icon: template.icon, size: 20 }),
										el('span', { style: { fontWeight: '600', fontSize: '13px' } }, template.name)
									),
									el('div', { style: { marginBottom: '8px', fontSize: '12px', color: '#757575' } }, template.description),
									el(Button, {
										variant: 'secondary',
										isSmall: true,
										onClick: function() {
											if (confirm(__('This will replace your current form fields. Continue?', 'giraforms'))) {
												loadTemplate(template.key);
											}
										}
									}, __('Load Template', 'giraforms'))
								);
							})
						),
						el(Button, {
							variant: 'secondary',
							onClick: function() { setShowTemplateModal(true); },
							style: { width: '100%', justifyContent: 'center', marginTop: '12px' },
						}, __('Browse All Templates', 'giraforms')),
					),
					el(
						PanelBody,
						{
							title: __('Form Settings', 'giraforms'),
							initialOpen: false,
						},
						el(TextControl, {
							label: __('Form Name', 'giraforms'),
							value: formName,
							onChange: (value) => setAttributes({ formName: value }),
							help: __('Used to identify the form in admin', 'giraforms'),
						}),
						el(TextControl, {
							label: __('Form ID', 'giraforms'),
							value: formId,
							onChange: function (value) {
								if ( editingFormId ) {
									setAttributes({ formId: value.replace(/[^a-zA-Z0-9_-]/g, '') });
								}
							},
							help: editingFormId
								? __('Only letters, numbers, hyphens and underscores allowed.', 'giraforms')
								: __('Unique form ID (auto-generated)', 'giraforms'),
							disabled: !editingFormId,
							className: editingFormId ? '' : 'giraforms-readonly-field',
						}),
						el('div', { style: { display: 'flex', gap: '8px', marginTop: '8px', flexWrap: 'wrap' } },
							el(Button, {
								variant: 'secondary',
								isSmall: true,
								onClick: function() {
									if ( !editingFormId ) {
										if (confirm(__('Edit the Form ID manually? Changing it will detach this form from its current submissions.', 'giraforms'))) {
											formIdBeforeEdit.current = formId;
											setEditingFormId(true);
										}
									} else {
										setEditingFormId(false);
									}
								}
							}, editingFormId ? __('Lock', 'giraforms') : __('Edit', 'giraforms')),
							el(Button, {
								variant: 'secondary',
								isSmall: true,
								onClick: function() {
									if (confirm(__('Generate a new Form ID? This will create a separate submission history for this form.', 'giraforms'))) {
										if ( !editingFormId ) {
											formIdBeforeEdit.current = formId;
										}
										setAttributes({
											formId: 'form_' + Math.random().toString(36).substring(2, 11),
										});
										setEditingFormId(false);
									}
								}
							}, __('Regenerate', 'giraforms')),
							formId !== formIdBeforeEdit.current && el(Button, {
								variant: 'tertiary',
								isSmall: true,
								isDestructive: true,
								onClick: function() {
									setAttributes({ formId: formIdBeforeEdit.current });
									setEditingFormId(false);
								}
							}, __('Reset', 'giraforms'))
						),
						el('p', {
							style: {
								fontSize: '12px',
								color: '#757575',
								marginTop: '8px',
								fontStyle: 'italic'
							}
						}, __('Note: Forms with the same ID share the same submission history. Use "Regenerate" to separate them.', 'giraforms'))
					),
					el(
						PanelBody,
						{
							title: __('Submission', 'giraforms'),
							initialOpen: false,
						},
						el(ToggleControl, {
							label: __('Enable AJAX', 'giraforms'),
							checked: enableAjax,
							onChange: (value) => setAttributes({ enableAjax: value }),
							help: __(
								'Submit the form without refreshing the page',
								'giraforms'
							),
						}),
						el(TextControl, {
							label: __('Success Message', 'giraforms'),
							value: successMessage,
							onChange: (value) => setAttributes({ successMessage: value }),
						}),
						el(TextControl, {
							label: __('Redirect URL (optional)', 'giraforms'),
							value: redirectUrl,
							onChange: (value) => setAttributes({ redirectUrl: value }),
							help: !isInternalUrl(redirectUrl)
								? __('⚠️ External URLs are not allowed for security reasons. Use a relative URL (e.g., /thank-you/) or a URL on this domain.', 'giraforms')
								: __('Redirect to this URL after submission. Only URLs on this domain are allowed.', 'giraforms'),
							className: !isInternalUrl(redirectUrl) ? 'giraforms-invalid-url' : '',
						})
					),
					el(
						PanelBody,
						{
							title: __('Notifications', 'giraforms'),
							initialOpen: false,
						},
						el(ToggleControl, {
							label: __('Enable Email Notifications', 'giraforms'),
							checked: enableEmailNotifications,
							onChange: (value) => setAttributes({ enableEmailNotifications: value }),
							help: __(
								'Send an email notification to the admins when submitted',
								'giraforms'
							),
						}),
						enableEmailNotifications && el(BaseControl, {
							help: __(
								'Leave empty to use global settings. Press Enter to add each email.',
								'giraforms'
							),
						},
							el(FormTokenField, {
								label: __('Recipient Email(s)', 'giraforms'),
								value: attributes.notificationEmails ? attributes.notificationEmails.split('\n').filter(Boolean) : [],
								onChange: function (tokens) {
									setAttributes({ notificationEmails: tokens.join('\n') });
								},
								__experimentalShowHowTo: false,
								__experimentalValidateInput: function (value) {
									return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value);
								},
							})
						),
						
					),
					// Pro Features upsell panel (visible in free version only)
					!(typeof giraFormsData !== 'undefined' && giraFormsData.isPremium) && el(
						PanelBody,
						{
							title: __('Pro Features', 'giraforms'),
							initialOpen: false,
							className: 'giraforms-pro-panel',
						},
						el('p', {
							style: { fontSize: '13px', color: '#757575', marginTop: 0 }
						}, __('Unlock advanced form fields with Giraforms Pro:', 'giraforms')),
						el('ul', { className: 'giraforms-pro-features-list' },
								[
									{ icon: 'upload', label: __('File Upload', 'giraforms') },
									{ icon: 'admin-links', label: __('Webhooks', 'giraforms') },
									{ icon: 'money-alt', label: __('Stripe Payments', 'giraforms') },
									{ icon: 'star-filled', label: __('Rating', 'giraforms') },
									{ icon: 'calendar', label: __('Calendar', 'giraforms') },
								{ icon: 'clock', label: __('Booking', 'giraforms') },
								{ icon: 'phone', label: __('Phone (Advanced)', 'giraforms') },
								{ icon: 'edit', label: __('Signature', 'giraforms') },
								{ icon: 'money-alt', label: __('Currency', 'giraforms') },
								{ icon: 'location-alt', label: __('Geolocation', 'giraforms') },
								{ icon: 'email', label: __('Brevo', 'giraforms') },
							].map(function(feature) {
								return el('li', { key: feature.label, className: 'giraforms-pro-feature-item' },
									el(Icon, { icon: feature.icon, size: 16 }),
									el('span', null, feature.label)
								);
							})
						),
						el('p', {
							style: { fontSize: '13px', color: '#757575', marginTop: '4px', marginBottom: '12px' }
						}, __('Plus: Conditional Logic, Multi-step Forms, Custom Styles, Access Restrictions, and more.', 'giraforms')),
						el(Button, {
							variant: 'primary',
							href: 'https://giraforms.com',
							target: '_blank',
							className: 'giraforms-pro-upgrade-btn',
						}, __('Upgrade to Pro', 'giraforms') + ' \u2192')
					),
					
				),
				// Inspector Controls - Styles Tab
				
				// Template Library Modal
				showTemplateModal && el(Modal, {
					title: __('Form Templates Library', 'giraforms'),
					onRequestClose: function() { setShowTemplateModal(false); },
					isFullScreen: true,
					className: 'giraforms-template-modal',
				},
					el('div', { className: 'giraforms-modal-content' },
						// Category filter tabs
						el('div', { className: 'giraforms-modal-categories' },
							el(Button, {
								className: 'giraforms-category-btn' + (selectedCategory === 'all' ? ' is-active' : ''),
								onClick: function() { setSelectedCategory('all'); },
							}, __('All Templates', 'giraforms')),
							availableTemplateCategories.map(function(catKey) {
								return el(Button, {
									key: catKey,
									className: 'giraforms-category-btn' + (selectedCategory === catKey ? ' is-active' : ''),
									onClick: function() { setSelectedCategory(catKey); },
								}, TEMPLATE_CATEGORIES[catKey].label);
							})
						),
						// Templates grid
						el('div', { className: 'giraforms-modal-grid' },
							availableTemplates
								.filter(function(t) { return selectedCategory === 'all' || t.category === selectedCategory; })
								.map(function(template) {
									return el('div', {
										key: template.key,
										className: 'giraforms-modal-card',
									},
										el('div', { className: 'giraforms-modal-card-header' },
											el(Icon, { icon: template.icon, size: 32 }),
											template.blocks.some(function(b) { return b[0] === 'core/columns'; })
												&& el('span', { className: 'giraforms-badge-columns' }, __('Multi-column', 'giraforms'))
										),
										el('h3', { className: 'giraforms-modal-card-title' }, template.name),
										el('p', { className: 'giraforms-modal-card-desc' }, template.description),
										el('div', { className: 'giraforms-modal-card-meta' },
											el('span', null, countTemplateFields(template.blocks) + ' ' + __('fields', 'giraforms'))
										),
										el(Button, {
											variant: 'primary',
											className: 'giraforms-modal-card-btn',
											onClick: function() {
												if (!hasInnerBlocks || confirm(__('This will replace your current form fields. Continue?', 'giraforms'))) {
													loadTemplate(template.key);
													setShowTemplateModal(false);
												}
											},
										}, __('Use Template', 'giraforms'))
									);
								})
						)
					)
				),
				// Block Content - Conditional rendering
				hasInnerBlocks
					? el(
						'div',
						blockProps,
						el(
							'div',
							{ className: 'giraforms-form-header' },
							el('h3', null, formName),
							el('p', { className: 'giraforms-form-id' }, 'ID: ' + formId)
						),
						el(
							'div',
							{ className: 'giraforms-form-inner' },
							el(InnerBlocks, {
								allowedBlocks: ALLOWED_BLOCKS,
								renderAppender: InnerBlocks.ButtonBlockAppender,
							})
						)
					)
					: el(
						'div',
						blockProps,
						el(Placeholder, {
							label: __('Giraforms', 'giraforms'),
							instructions: __('Choose a template to get started or start with a blank form.', 'giraforms'),
							className: 'giraforms-template-placeholder',
						},
							el('div', { className: 'giraforms-template-picker' },
								// Quick templates grid (first 4)
								el('div', { className: 'giraforms-quick-templates' },
									featuredTemplates.map(function(template) {
										return el(Button, {
											key: template.key,
											className: 'giraforms-quick-template-btn',
											onClick: function() { loadTemplate(template.key); },
										},
											el(Icon, { icon: template.icon, size: 24 }),
											el('span', { className: 'giraforms-quick-template-label' }, template.name)
										);
									})
								),
								// Action buttons
								el('div', { className: 'giraforms-template-actions' },
									el(Button, {
										variant: 'primary',
										onClick: function() { setShowTemplateModal(true); },
									}, __('Browse All Templates', 'giraforms')),
									el(Button, {
										variant: 'tertiary',
										onClick: function() { loadBlankForm(); },
									}, __('Blank Form', 'giraforms'))
								)
							)
						)
					)
			);
		},

		save: function () {
			return el(InnerBlocks.Content);
		},

		deprecated: [],
	});
})(
	window.wp.blocks,
	window.wp.element,
	window.wp.blockEditor,
	window.wp.components,
	window.wp.i18n,
	window.wp.data
);
