document.addEventListener( 'DOMContentLoaded', function ( ) {
	const editor = grapesjs.init({
		container: '#gjs',
		height: '100%',
		width: 'auto',
		fromElement: 1,
		storageManager: false,
		avoidInlineStyle: false,
		styleManager: { clearProperties: true },

		selectorManager: {
			componentFirst: true,
		},
		clipboardManager: {
			enabled: true,
			storage: {
				get: () => {
					return window.x4emailClipboard || null;
				},
				set: ( data ) => {
					window.x4emailClipboard = data;
				}
			},
			copy: ( component ) => {
				const html = component.toHTML();
				const css = component.getStyle();
				const attributes = component.getAttributes();
				const classes = component.getClasses();
				const components = component.get( 'components' );

				return {
					html,
					css,
					attributes,
					classes,
					components,
					type: component.get( 'type' )
				};
			},
			paste: ( component, data ) => {
				if ( !data ) return;

				const newComponent = editor.Components.addComponent({
					type: data.type || 'default',
					content: data.html,
					style: data.css,
					attributes: data.attributes,
					classes: data.classes,
					components: data.components
				});

				const selected = editor.getSelected();
				if ( selected ) {
					selected.append( newComponent );
				} else {
					editor.getWrapper( ).append(newComponent );
				}

				editor.select( newComponent );
			}
		},
		panels: {
			defaults: [
				{
					id: "basic-actions",
					el: "#actions",
					buttons: [
						{
							id: "visibility",
							active: true,
							label: "<i class='fa-solid fa-eye'></i>",
							command: "sw-visibility",
						},
						{
							id: "save",
							label: "<i class='fa fa-paper-plane btn-save'></i>",
							command: "save-project",
						},
						{
							id: "cmd-clear",
							label: "<i class='fa-solid fa-trash'></i>",
							command: "cmd-clear",
						},
						{
							id: "undo",
							label: "<i class='fa-solid fa-undo'></i>",
							command: "undo",
							togglable: false,
							run: ( editor ) => editor.runCommand( 'undo' ),
						},
						{
							id: "redo",
							label: "<i class='fa-solid fa-redo'></i>",
							command: "redo",
							togglable: false,
							run: ( editor ) => editor.runCommand( 'redo' ),
						},
						{
							id: "export",
							label: "<i class='fa-solid fa-download'></i>",
							command: "export",
						},
					]
				},
			]
		},



		plugins: [
			'grapesjs-plugin-export',
			'grapesjs-style-bg',
			'grapesjs-style-filter',
			'grapesjs-parser-postcss',
			'grapesjs-preset-newsletter',
			"gjs-blocks-basic",

		],
		pluginsOpts: {
			'gjs-preset-webpage': {
				// options
			},

			'grapesjs-plugin-export': {
				// Export options
				filename: 'email-template',
				type: 'html',
				// Custom export function
				exportFn: ( editor ) => {
					const html = editor.getHtml();
					const css = editor.getCss();
					return `
												<!DOCTYPE html>
												<html>
												<head>
														<style>${css}</style>
												</head>
												<body>${html}</body>
												</html>
										`;
				}
			},
			'grapesjs-style-bg': {
				propExtender: p => {
					if ( p.property === 'background-image-gradient-dir' ) {
						p.options.push( { id: 'to bottom right' } );
						p.options.push( { id: 'to bottom left' } );
						p.options.push( { id: 'to top right' } );
						p.options.push( { id: 'to top left' } );
					}
					return p;
				},
				styleGradientOpts: {},
			},


			'grapesjs-preset-newsletter': {},
			'gjs-blocks-basic': {
				blocks: [],
				category: "Basics",
			},


		},

		responsive: {
			breakpoints: [
				{
					name: 'Desktop',
					width: null,
				},
				{
					name: 'Tablet',
					width: 768,
					widthMedia: 992,
				},
				{
					name: 'Mobile',
					width: 320,
					widthMedia: 480,
				}
			],
			rules: [
				{
					select: '.email-section',
					style: {
						'padding': '20px',
						'@media ( max-width: 768px )': {
							'padding': '15px',
						},
						'@media ( max-width: 480px )': {
							'padding': '10px',
						}
					}
				},
				{
					select: '.email-header',
					style: {
						'padding': '20px',
						'@media ( max-width: 768px )': {
							'padding': '15px',
						},
						'@media ( max-width: 480px )': {
							'padding': '10px',
						}
					}
				},
				{
					select: '.button',
					style: {
						'padding': '10px 20px',
						'@media ( max-width: 768px )': {
							'padding': '8px 16px',
							'font-size': '14px',
						},
						'@media ( max-width: 480px )': {
							'padding': '6px 12px',
							'font-size': '12px',
						}
					}
				}
			]
		},

		// Add global styles
		cssIcons: x4emailEditor.pluginUrl + 'assets/css/font-awesome.min.css',
	});

	function toPHPChr( input ) {
		return input
			.split( '' )
			.map( char => `chr(${char.charCodeAt(0 )})`)
			.join( '.' );
	}

	// Load initial template if specified
	if ( x4emailEditor.initialTemplate ) {
		const templateSelect = document.getElementById( 'template-select' );
		const option = Array.from( templateSelect.options ).find( opt => opt.value === x4emailEditor.initialTemplate );
		if ( option ) {
			templateSelect.value = x4emailEditor.initialTemplate;

			// Create form data for AJAX request
			const formData = new FormData();
			formData.append( 'action', 'x4email_load_template' );
			formData.append( 'template_name', x4emailEditor.initialTemplate );
			formData.append( 'nonce', x4emailEditor.nonce );

			// Disable save button while loading
			const saveButton = document.getElementById( 'save-template' );
			saveButton.disabled = true;
			saveButton.classList.remove( 'has-changes' );

			// Load template via AJAX
			fetch(x4emailEditor.ajaxUrl, {
				method: 'POST',
				body: formData,
				credentials: 'same-origin'
			})
				.then( response => response.json( ))
				.then(data => {
					if ( data.success ) {
						// Remove PHP tags and echo statement from content
						const cleanContent = data.data.content.replace( /<\?php\s*echo\s*"|";\s*\?>/g, '' );
						editor.setComponents( cleanContent );
						editor.setStyle( data.data.css );
						hasChanges = false;
						updateSaveButtonState();
					} else {
						alert( data.data.message );
						if ( data.data.redirect ) {
							window.location.href = data.data.redirect;
						}
					}
				})
				.catch(error => {
					console.error( 'Error:', error );
					alert( 'Error loading template. Please try again.' );
				});
		}
	}

	// Remove image block from editor
	editor.on( 'load', ( ) => {
		editor.BlockManager.remove( 'image' );
	});
	// Add site logo block
	editor.DomComponents.addType('non-editable-image', {
		extend: 'image',
		model: {
			defaults: {
				tagName: 'img',
				attributes: {
					alt: 'Site Logo',
					src: '', // real image src
					'data-preview-src': '',
				},
				traits: [
					{
						type: 'text',
						label: 'Real Logo URL',
						name: 'src', // bind to real src
						placeholder: ''
					},
					{
						type: 'text',
						label: 'Preview Logo URL',
						name: 'data-preview-src', // bind to preview src
						placeholder: ''
					}
				],
				editable: true,
				selectable: true,
				hoverable: true,
				draggable: true,
				highlightable: true,
				resizable: true,
				toolbar: [], // remove default edit
			},
			init() {
				this.stopListening( this, 'change:src', this.updateSrc ); // prevent asset manager
			},
			toHTML() {
				const attrs = this.getAttributes();
				// Remove data-preview-src from export
				const attrStr = Object.entries( attrs )
					.filter( ([k] ) => k !== 'data-preview-src')
					.map( ([k, v] ) => `${k}="${v}"`).join( ' ' );
				return `<img ${attrStr}>`;
			}
		},
		view: {
			onRender() {
				// Use preview src in editor
				const attrs = this.model.getAttributes();
				const previewSrc = attrs['data-preview-src'] || attrs['src'] || '';
				this.el.setAttribute( 'src', previewSrc );
			},
			events: {}
		}
	});


	editor.BlockManager.add('site-logo', {
		label: 'Site Logo',
		category: 'Basics',
		attributes: { class: 'fa fa-image' },
		content: {
			type: 'non-editable-image',
			attributes: {
				src: `<?php echo esc_url( wp_get_attachment_image_url(get_theme_mod(${toPHPChr('custom_logo' )}), ${toPHPChr( 'yes' )})); ?>`,
				'data-preview-src': 'data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxMDAiIHZpZXdCb3g9IjAgMCAyNCAyNCIgc3R5bGU9ImZpbGw6IHJnYmEoMCwwLDAsMC4xNSk7IHRyYW5zZm9ybTogc2NhbGUoMC43NSkiPgogICAgICAgIDxwYXRoIGQ9Ik0yLjI4IDNMMSA0LjI3bDIgMlYxOWMwIDEuMS45IDIgMiAyaDEyLjczbDIgMkwyMSAyMS43MiAyLjI4IDNtMi41NSAwTDIxIDE5LjE3VjVhMiAyIDAgMCAwLTItMkg0LjgzTTguNSAxMy41bDIuNSAzIDEtMS4yNUwxNC43MyAxOEg1bDMuNS00LjV6Ij48L3BhdGg+CiAgICAgIDwvc3ZnPg==',
				alt: 'Site Logo',
				style: 'width:125px;'
			}
		}
	});





	// Set basic blocks with Font Awesome icons

	editor.DomComponents.addType('woocommerce-component', {
		isComponent: el => el.classList && el.classList.contains( 'woocommerce-component' ),

		model: {
			defaults: {
				tagName: 'div',
				classes: ['woocommerce-component'],
				draggable: true,
				droppable: false,
				stylable: true,
				traits: [],
				// Defaults for attributes to be saved
				attributes: {
					'data-real-content': 'This is the real content.',
					'data-preview-content': '👀 Preview content ( visible only in editor )',
				},
				components: [], // will be initialized in init()
			},

			init() {
				// Get real content from attribute and set as child component
				const realContent = this.getAttributes()['data-real-content'] || 'This is the real content.';

				this.components([
					{
						type: 'text',
						content: realContent,
						editable: true,
					}
				]);
			},

			// When user changes components inside the real content ( editable text ), update the attribute
			// to keep it saved with the component
			// Listen to components change and update attribute:
			initChildren() {
				this.listenTo( this.components( ), 'change:content', () => {
					const child = this.components( ).at(0 );
					if ( child ) {
						this.addAttributes( { 'data-real-content': child.get('content' ) });
					}
				});
			},
		},

		view: {
			onRender() {
				// Hide real content in editor view
				this.el.querySelectorAll( '*' ).forEach(child => {
					child.style.display = 'none';
				});

				// Add preview content from attribute
				const previewContent = this.model.getAttributes()['data-preview-content'] || '👀 Preview content';
				const preview = document.createElement( 'div' );
				preview.innerHTML = previewContent;
				preview.classList.add( 'preview-only' );
				this.el.appendChild( preview );
			}
		}
	});

	/*    
			editor.DomComponents.addType('security-component', {
				isComponent: el => el.classList && el.classList.contains( 'security-component' ),
			
				model: {
					defaults: {
						tagName: 'div',
						classes: ['security-component'],
						draggable: true,
						droppable: false,
						stylable: true,
						traits: [],
						// Defaults for attributes to be saved
						attributes: {
							'data-real-content': 'This is the real content.',
							'data-preview-content': '👀 Preview content ( visible only in editor )',
						},
						components: [], // will be initialized in init()
						style: {
							padding: '10px'
						}
					},
			
					init() {
						// Get real content from attribute and set as child component
						const realContent = this.getAttributes()['data-real-content'] || 'This is the real content.';
			
						this.components([
							{
								type: 'text',
								content: realContent,
								editable: true,
								style: {
									padding: '10px'
								}
							}
						]);
					},
			
					// When user changes components inside the real content ( editable text ), update the attribute
					// to keep it saved with the component
					// Listen to components change and update attribute:
					initChildren() {
						this.listenTo( this.components( ), 'change:content', () => {
							const child = this.components( ).at(0 );
							if ( child ) {
								this.addAttributes( { 'data-real-content': child.get('content' ) });
							}
						});
					},
				},
			
				view: {
					onRender() {
						// Hide real content in editor view
						this.el.querySelectorAll( '*' ).forEach(child => {
							child.style.display = 'none';
						});
			
						// Add preview content from attribute
						const previewContent = this.model.getAttributes()['data-preview-content'] || '👀 Preview content';
						const preview = document.createElement( 'div' );
						preview.innerHTML = previewContent;
						preview.classList.add( 'preview-only' );
						this.el.appendChild( preview );
					}
				}
			});


			
			editor.BlockManager.add('2fa-name', {
				label: 'Name',
				category: 'Security',
				attributes: { class: 'fa fa-user' },
				content: {
					type: 'security-component',
					classes: ['2fa-name','security-component'],
					attributes: {
						'data-real-content': '<?php echo esc_html( get_bloginfo("name" )); ?>',
						'data-preview-content': 'Admin',
					}
				}
			});

			editor.BlockManager.add('2fa-pin', {
				label: '2FA PIN',
				category: 'Security',
				attributes: { class: 'fa fa-key' },
				content: {
					type: 'security-component',
					classes: ['2fa-pin','security-component'],
					attributes: {
						'data-real-content': '<?php echo esc_html( $pin ); ?>',
						'data-preview-content': '1234',
					}
				}
			});

			editor.BlockManager.add('notify-username', {
				label: 'Username',
				category: 'Security',
				attributes: { class: 'fa fa-user' },
				content: {
					type: 'security-component',
					classes: ['notify-username','security-component'],
					attributes: {
						'data-real-content': '<?php echo esc_html( $user_login ); ?>',
						'data-preview-content': 'Admin',
					}
				}
			});

			editor.BlockManager.add('notify-time', {
				label: 'Time',
				category: 'Security',
				attributes: { class: 'fa fa-clock' },
				content: {
					type: 'security-component',
					classes: ['notify-time','security-component'],
					attributes: {
						'data-real-content': `<?php echo esc_html( current_time('mysql' )); ?>`,
						'data-preview-content': '2025-05-20 12:00:00',
					}
				}
			});

			editor.BlockManager.add('notify-ip', {
				label: 'IP Address',
				category: 'Security',
				attributes: { class: 'fa fa-map-marker-alt' },
				content: {
					type: 'security-component',
					classes: ['notify-ip','security-component'],
					attributes: {
						'data-real-content': `<?php echo esc_html( $_SERVER['REMOTE_ADDR'] ); ?>`,
						'data-preview-content': '123.45.67.89',
					}
				}
			});

			editor.BlockManager.add('notify-user-agent', {
				label: 'User Agent',
				category: 'Security',
				attributes: { class: 'fa fa-robot' },
				content: {
					type: 'security-component',
					classes: ['notify-user-agent','security-component'],
					attributes: {
						'data-real-content': `<?php echo esc_html( $_SERVER['HTTP_USER_AGENT'] ); ?>`,
						'data-preview-content': 'Mozilla/5.0 ( Windows NT 10.0; Win64; x64 ) AppleWebKit/537.36 ( KHTML, like Gecko ) Chrome/91.0.4472.124 Safari/537.36',
					}
				}
			}); 
			
			*/

	editor.BlockManager.add('order-id', {
		label: 'Order ID',
		category: 'WooCommerce',
		attributes: { class: 'fa fa-hashtag' },
		content: {
			type: 'woocommerce-component',
			classes: ['order-id', 'woocommerce-component'],
			attributes: {
				'data-real-content': 'Order ID - #<?php echo $order->get_id(); ?>',
				'data-preview-content': 'Order ID - #1234',
			}
		}
	});
	//User Name
	editor.BlockManager.add('admin-user-name', {
		label: 'Admin User Name',
		category: 'WooCommerce',
		attributes: { class: 'fa fa-user' },
		content: {
			type: 'woocommerce-component',
			classes: ['admin-user-name', 'woocommerce-component'],
			attributes: {
				'data-real-content': '<?php echo $order->get_user(); ?>',
				'data-preview-content': 'Admin',
			}
		}
	});



	// Order Key
	editor.BlockManager.add('order-key', {
		label: 'Order Key',
		category: 'WooCommerce',
		attributes: { class: 'fa fa-key' },
		content: {
			type: 'woocommerce-component',
			classes: ['order-key', 'woocommerce-component'],
			attributes: {
				'data-real-content': '<?php echo $order->get_order_key(); ?>',
				'data-preview-content': 'wc_order_xxxx',
			}
		}
	});

	// Order Status
	editor.BlockManager.add('order-status', {
		label: 'Order Status',
		category: 'WooCommerce',
		attributes: { class: 'fa fa-info-circle' },
		content: {
			type: 'woocommerce-component',
			classes: ['order-status', 'woocommerce-component'],
			attributes: {
				'data-real-content': '<?php echo $order->get_status(); ?>',
				'data-preview-content': 'processing',
			}
		}
	});

	// Order Total
	editor.BlockManager.add('order-total', {
		label: 'Order Total',
		category: 'WooCommerce',
		attributes: { class: 'fa fa-dollar-sign' },
		content: {
			type: 'woocommerce-component',
			classes: ['order-total', 'woocommerce-component'],
			attributes: {
				'data-real-content': '<?php echo $order->get_total(); ?>',
				'data-preview-content': '$120.00',
			}
		}
	});

	// Order Currency
	editor.BlockManager.add('order-currency', {
		label: 'Currency',
		category: 'WooCommerce',
		attributes: { class: 'fa fa-coins' },
		content: {
			type: 'woocommerce-component',
			classes: ['order-currency', 'woocommerce-component'],
			attributes: {
				'data-real-content': '<?php echo $order->get_currency(); ?>',
				'data-preview-content': 'USD',
			}
		}
	});

	// Order Created Date
	editor.BlockManager.add('order-date-created', {
		label: 'Created Date',
		category: 'WooCommerce',
		attributes: { class: 'fa fa-calendar-plus' },
		content: {
			type: 'woocommerce-component',
			classes: ['order-date-created', 'woocommerce-component'],
			attributes: {
				'data-real-content': '<?php echo $order->get_date_created(); ?>',
				'data-preview-content': '2025-05-20',
			}
		}
	});

	// Order Completed Date
	editor.BlockManager.add('order-date-completed', {
		label: 'Completed Date',
		category: 'WooCommerce',
		attributes: { class: 'fa fa-calendar-check' },
		content: {
			type: 'woocommerce-component',
			classes: ['order-date-completed', 'woocommerce-component'],
			attributes: {
				'data-real-content': '<?php echo $order->get_date_completed(); ?>',
				'data-preview-content': '2025-05-21',
			}
		}
	});

	// Billing Email
	editor.BlockManager.add('billing-email', {
		label: 'Billing Email',
		category: 'WooCommerce',
		attributes: { class: 'fa fa-envelope' },
		content: {
			type: 'woocommerce-component',
			classes: ['billing-email', 'woocommerce-component'],
			attributes: {
				'data-real-content': '<?php echo $order->get_billing_email(); ?>',
				'data-preview-content': 'customer@example.com',
			}
		}
	});

	// Billing Phone
	editor.BlockManager.add('billing-phone', {
		label: 'Billing Phone',
		category: 'WooCommerce',
		attributes: { class: 'fa fa-phone' },
		content: {
			type: 'woocommerce-component',
			classes: ['billing-phone', 'woocommerce-component'],
			attributes: {
				'data-real-content': '<?php echo $order->get_billing_phone(); ?>',
				'data-preview-content': '+1234567890',
			}
		}
	});

	// Billing Name
	editor.BlockManager.add('billing-name', {
		label: 'Billing Name',
		category: 'WooCommerce',
		attributes: { class: 'fa fa-user-tag' },
		content: {
			type: 'woocommerce-component',
			classes: ['billing-name', 'woocommerce-component'],
			attributes: {
				'data-real-content': '<?php echo $order->get_formatted_billing_full_name(); ?>',
				'data-preview-content': 'John Doe',
			}
		}
	});

	// Billing Address
	editor.BlockManager.add('billing-address', {
		label: 'Billing Address',
		category: 'WooCommerce',
		attributes: { class: 'fa fa-map-marker-alt' },
		content: {
			type: 'woocommerce-component',
			classes: ['billing-address', 'woocommerce-component'],
			attributes: {
				'data-real-content': '<?php echo $order->get_formatted_billing_address(); ?>',
				'data-preview-content': 'John Doe<br>Company<br>123 Fake Street<br>Faketown, CA 12345<br>United States ( US )',
			}
		}
	});

	// Shipping Name
	editor.BlockManager.add('shipping-name', {
		label: 'Shipping Name',
		category: 'WooCommerce',
		attributes: { class: 'fa fa-user-tag' },
		content: {
			type: 'woocommerce-component',
			classes: ['shipping-name', 'woocommerce-component'],
			attributes: {
				'data-real-content': '<?php echo $order->get_formatted_shipping_full_name(); ?>',
				'data-preview-content': 'John Doe',
			}
		}
	});

	// Shipping Address
	editor.BlockManager.add('shipping-address', {
		label: 'Shipping Address',
		category: 'WooCommerce',
		attributes: { class: 'fa fa-shipping-fast' },
		content: {
			type: 'woocommerce-component',
			classes: ['shipping-address', 'woocommerce-component'],
			attributes: {
				'data-real-content': '<?php echo $order->get_formatted_shipping_address(); ?>',
				'data-preview-content': '456 Elm St, LA, USA',
			}
		}
	});

	// Payment Method
	editor.BlockManager.add('payment-method', {
		label: 'Payment Method',
		category: 'WooCommerce',
		attributes: { class: 'fa fa-credit-card' },
		content: {
			type: 'woocommerce-component',
			classes: ['payment-method', 'woocommerce-component'],
			attributes: {
				'data-real-content': '<?php echo $order->get_payment_method_title(); ?>',
				'data-preview-content': 'Credit Card',
			}
		}
	});

	// Shipping Method
	editor.BlockManager.add('shipping-method', {
		label: 'Shipping Method',
		category: 'WooCommerce',
		attributes: { class: 'fa fa-truck' },
		content: {
			type: 'woocommerce-component',
			classes: ['shipping-method', 'woocommerce-component'],
			attributes: {
				'data-real-content': '<?php echo $order->get_shipping_method(); ?>',
				'data-preview-content': 'Flat Rate',
			}
		}
	});

	// Subtotal
	editor.BlockManager.add('order-subtotal', {
		label: 'Order Subtotal',
		category: 'WooCommerce',
		attributes: { class: 'fa fa-calculator' },
		content: {
			type: 'woocommerce-component',
			classes: ['order-subtotal', 'woocommerce-component'],
			attributes: {
				'data-real-content': '<?php echo $order->get_subtotal(); ?>',
				'data-preview-content': '$100.00',
			}
		}
	});

	// Shipping Total
	editor.BlockManager.add('shipping-total', {
		label: 'Shipping Total',
		category: 'WooCommerce',
		attributes: { class: 'fa fa-shipping-fast' },
		content: {
			type: 'woocommerce-component',
			classes: ['shipping-total', 'woocommerce-component'],
			attributes: {
				'data-real-content': '<?php echo $order->get_shipping_total(); ?>',
				'data-preview-content': '$10.00',
			}
		}
	});

	// Discount Total
	editor.BlockManager.add('discount-total', {
		label: 'Discount Total',
		category: 'WooCommerce',
		attributes: { class: 'fa fa-tags' },
		content: {
			type: 'woocommerce-component',
			classes: ['discount-total', 'woocommerce-component'],
			attributes: {
				'data-real-content': '<?php echo $order->get_discount_total(); ?>',
				'data-preview-content': '$5.00',
			}
		}
	});

	// Tax Total
	editor.BlockManager.add('tax-total', {
		label: 'Tax Total',
		category: 'WooCommerce',
		attributes: { class: 'fa fa-percentage' },
		content: {
			type: 'woocommerce-component',
			classes: ['tax-total', 'woocommerce-component'],
			attributes: {
				'data-real-content': '<?php echo $order->get_total_tax(); ?>',
				'data-preview-content': '$8.00',
			}
		}
	});

	// Password Reset Link
	editor.BlockManager.add('password-reset-link', {
		label: 'Password Reset Link',
		category: 'WooCommerce',
		attributes: { class: 'fa fa-key' },
		content: {
			type: 'woocommerce-component',
			classes: ['password-reset-link', 'woocommerce-component'],
			attributes: {
				'data-real-content': `<a class="link" href="<?php echo esc_url( add_query_arg( array( 'key' => $reset_key, 'id' => $user_id, 'login' => rawurlencode( $user_login ) ), wc_get_endpoint_url( 'lost-password', '', wc_get_page_permalink( 'myaccount' ) ) ) ); ?>"><?php // phpcs:ignore WordPress.Arrays.ArrayDeclarationSpacing.AssociativeArrayFound ?>
					Click here to reset your password
				</a>`,
				'data-preview-content': `<a class="link" href="#" style="color: #0073aa; text-decoration: underline;">
					Click here to reset your password
				</a>`
			}
		}
	});

	// Customer Username
	editor.BlockManager.add('customer-username', {
		label: 'Customer Username',
		category: 'WooCommerce',
		attributes: { class: 'fa fa-user' },
		content: {
			type: 'woocommerce-component',
			classes: ['customer-username', 'woocommerce-component'],
			attributes: {
				'data-real-content': '<?php echo esc_html( $user_login ); ?>',
				'data-preview-content': 'johndoe',
			}
		}
	});


	// Account Links
	editor.BlockManager.add('account-links', {
		label: 'Account Links',
		category: 'WooCommerce',
		attributes: { class: 'fa fa-user-circle' },
		content: {
			type: 'woocommerce-component',
			classes: ['account-links', 'woocommerce-component'],
			attributes: {
				'data-real-content': `<?php if ( ${toPHPChr('yes' )} === get_option( ${toPHPChr('woocommerce_registration_generate_password' )} ) && $password_generated && $set_password_url ) : ?>
					<p><a href="<?php echo esc_attr( $set_password_url ); ?>"><?php echo ${toPHPChr( 'Set your new password.' )}, ${toPHPChr( 'woocommerce' )}; ?></a></p>
				<?php endif; ?>
				<p><a href="<?php echo esc_attr( wc_get_page_permalink( ${toPHPChr('myaccount' )} ) ); ?>"><?php echo ${toPHPChr( 'My account' )}, ${toPHPChr( 'woocommerce' )}; ?></a></p>`,
				'data-preview-content': `<p><a href="#" style="color: #0073aa; text-decoration: underline; display: inline-block; margin-bottom: 10px;">Set your new password.</a></p>
				<p><a href="#" style="color: #0073aa; text-decoration: underline; display: inline-block;">My account</a></p>`
			}
		}
	});

	// Customer Note
	editor.BlockManager.add('customer-note', {
		label: 'Customer Note',
		category: 'WooCommerce',
		attributes: { class: 'fa fa-sticky-note' },
		content: {
			type: 'woocommerce-component',
			classes: ['customer-note', 'woocommerce-component'],
			attributes: {
				'data-real-content': '<?php echo esc_html( $customer_note ); ?>',
				'data-preview-content': 'Please deliver in the afternoon.',
			}
		}
	});

	// Order Items Table
	editor.BlockManager.add('order-items-table', {
		label: 'Order Items Table',
		category: 'WooCommerce',
		attributes: { class: 'fa fa-table' },
		content: {
			type: 'woocommerce-component',
			classes: ['order-items-table', 'woocommerce-component'],
			attributes: {
				'data-real-content': `<table class="order-items" style="width: 100%; border-collapse: collapse; margin: 20px 0; font-family: Arial, sans-serif;">
		<thead>
				<tr>
						<th style="padding: 10px; border: 1px solid #ddd; text-align: left; background-color: #f8f8f8;">Product</th>
						<th style="padding: 10px; border: 1px solid #ddd; text-align: center; background-color: #f8f8f8;">Quantity</th>
						<th style="padding: 10px; border: 1px solid #ddd; text-align: right; background-color: #f8f8f8;">Subtotal</th>
				</tr>
		</thead>
		<tbody>
				<?php foreach ( $order->get_items( ) as $item_id => $item ) : 
						$product_name = $item->get_name();
						$quantity = $item->get_quantity();
						$subtotal = $item->get_subtotal();
				?>
				<tr>
						<td style="padding: 10px; border: 1px solid #ddd;"><?php echo esc_html( $product_name ); ?></td>
						<td style="padding: 10px; border: 1px solid #ddd; text-align: center;"><?php echo esc_html( $quantity ); ?></td>
						<td style="padding: 10px; border: 1px solid #ddd; text-align: right;"><?php echo wc_price( $subtotal ); ?></td>
				</tr>
				<?php endforeach; ?>

				<!-- Subtotal -->
				<tr>
						<th colspan="2" style="padding: 10px; border: 1px solid #ddd; text-align: right; background-color: #f8f8f8;">Sub Total</th>
						<td style="padding: 10px; border: 1px solid #ddd; text-align: right;"><?php echo wc_price( $order->get_subtotal( ) ); ?></td>
				</tr>

				<!-- Discount -->
				<?php if ( $order->get_discount_total( ) > 0 ) : ?>
				<tr>
						<th colspan="2" style="padding: 10px; border: 1px solid #ddd; text-align: right; background-color: #f8f8f8;">Discount</th>
						<td style="padding: 10px; border: 1px solid #ddd; text-align: right; color: #d63638;">-<?php echo wc_price( $order->get_discount_total( ) ); ?></td>
				</tr>
				<?php endif; ?>

				<!-- Shipping -->
				<?php if ( $order->get_shipping_total( ) > 0 ) : ?>
				<tr>
						<th colspan="2" style="padding: 10px; border: 1px solid #ddd; text-align: right; background-color: #f8f8f8;">Shipping - <?php echo esc_html( $order->get_shipping_method( ) ); ?></th>
						<td style="padding: 10px; border: 1px solid #ddd; text-align: right;"><?php echo wc_price( $order->get_shipping_total( ) ); ?></td>
				</tr>
				<?php endif; ?>

				<!-- Order Total -->
				<tr>
						<th colspan="2" style="padding: 10px; border: 1px solid #ddd; text-align: right; background-color: #f8f8f8; font-weight: bold;">Total</th>
						<td style="padding: 10px; border: 1px solid #ddd; text-align: right; font-weight: bold;"><?php echo wc_price( $order->get_total( ) ); ?></td>
				</tr>

				<!-- Payment Method -->
				<tr>
						<th colspan="2" style="padding: 10px; border: 1px solid #ddd; text-align: right; background-color: #f8f8f8;">Payment Method</th>
						<td style="padding: 10px; border: 1px solid #ddd; text-align: right;"><?php echo esc_html( $order->get_payment_method_title( ) ); ?></td>
				</tr>

				<!-- Customer Note -->
				<?php if ( $order->get_customer_note( ) ) : ?>
				<tr>
						<td colspan="3" style="padding: 10px; border: 1px solid #ddd;">
								<strong style="display: block; margin-bottom: 5px;">Customer note:</strong>
								<div style="font-style: italic;"><?php echo nl2br( esc_html( $order->get_customer_note( ) ) ); ?></div>
						</td>
				</tr>
				<?php endif; ?>
		</tbody>
</table>`,

				'data-preview-content': `<table class="order-items" style="width: 100%; border-collapse: collapse; margin: 20px 0; font-family: Arial, sans-serif;">
		<thead>
				<tr>
						<th style="padding: 10px; border: 1px solid #ddd; text-align: left; background-color: #f8f8f8;">Product</th>
						<th style="padding: 10px; border: 1px solid #ddd; text-align: center; background-color: #f8f8f8;">Quantity</th>
						<th style="padding: 10px; border: 1px solid #ddd; text-align: right; background-color: #f8f8f8;">Subtotal</th>
				</tr>
		</thead>
		<tbody>
				<!-- Product Rows - Example Static -->
				<tr>
						<td style="padding: 10px; border: 1px solid #ddd;">Sample Product 1</td>
						<td style="padding: 10px; border: 1px solid #ddd; text-align: center;">2</td>
						<td style="padding: 10px; border: 1px solid #ddd; text-align: right;">$40</td>
				</tr>
				<tr>
						<td style="padding: 10px; border: 1px solid #ddd;">Sample Product 2</td>
						<td style="padding: 10px; border: 1px solid #ddd; text-align: center;">1</td>
						<td style="padding: 10px; border: 1px solid #ddd; text-align: right;">$30</td>
				</tr>

				<!-- Subtotal -->
				<tr>
						<th colspan="2" style="padding: 10px; border: 1px solid #ddd; text-align: right; background-color: #f8f8f8;">Sub Total</th>
						<td style="padding: 10px; border: 1px solid #ddd; text-align: right;">$70</td>
				</tr>

				<!-- Discount -->
				<tr>
						<th colspan="2" style="padding: 10px; border: 1px solid #ddd; text-align: right; background-color: #f8f8f8;">Discount</th>
						<td style="padding: 10px; border: 1px solid #ddd; text-align: right; color: #d63638;">-$10</td>
				</tr>

				<!-- Shipping -->
				<tr>
						<th colspan="2" style="padding: 10px; border: 1px solid #ddd; text-align: right; background-color: #f8f8f8;">Shipping - Flat Rate</th>
						<td style="padding: 10px; border: 1px solid #ddd; text-align: right;">$5</td>
				</tr>

				<!-- Total -->
				<tr>
						<th colspan="2" style="padding: 10px; border: 1px solid #ddd; text-align: right; background-color: #f8f8f8; font-weight: bold;">Total</th>
						<td style="padding: 10px; border: 1px solid #ddd; text-align: right; font-weight: bold;">$65</td>
				</tr>

				<!-- Payment Method -->
				<tr>
						<th colspan="2" style="padding: 10px; border: 1px solid #ddd; text-align: right; background-color: #f8f8f8;">Payment Method</th>
						<td style="padding: 10px; border: 1px solid #ddd; text-align: right;">Direct Bank Transfer</td>
				</tr>

				<!-- Customer Note -->
				<tr>
						<td colspan="3" style="padding: 10px; border: 1px solid #ddd;">
								<strong style="display: block; margin-bottom: 5px;">Customer note:</strong>
								<div style="font-style: italic;">This is a customer note. Customers can add a note to their order on checkout.<br><br>
								It can be multiple lines. If theres no note, this section is hidden.</div>
						</td>
				</tr>
		</tbody>
</table>`
			}
		}
	});




	editor.BlockManager.get( 'text' ).set({
		attributes: { class: 'fa fa-font' },
		category: 'Basics',
		media: false
	});

	// Image block is hidden
	/*
	editor.BlockManager.get( 'image' ).set({
		attributes: { class: 'fa fa-image' },
		category: 'Basics',
		media: false
	});
	*/

	editor.BlockManager.get( 'link' ).set({
		attributes: { class: 'fa fa-link' },
		category: 'Basics',
		media: false
	});

	editor.BlockManager.get( 'button' ).set({
		attributes: { class: 'fa fa-circle' },
		category: 'Basics',
		media: false
	});

	editor.BlockManager.get( 'divider' ).set({
		attributes: { class: 'fa fa-minus' },
		category: 'Basics',
		media: false
	});

	editor.BlockManager.get( 'quote' ).set({
		attributes: { class: 'fa fa-quote-right' },
		category: 'Basics',
		media: false
	});

	editor.BlockManager.get( 'grid-items' ).set({
		attributes: { class: 'fa fa-th' },
		category: 'Basics',
		media: false
	});
	editor.BlockManager.get( 'link-block' ).set({
		attributes: { class: 'fa fa-link' },
		category: 'Basics',
		media: false
	});
	editor.BlockManager.get( 'list-items' ).set({
		attributes: { class: 'fa fa-list' },
		category: 'Basics',
		media: false
	});

	editor.BlockManager.get( 'text-sect' ).set({
		attributes: { class: 'fa fa-align-left' },
		category: 'Basics',
		media: false
	});

	// Additional blocks with Font Awesome icons
	editor.BlockManager.get( 'sect100' ).set({
		attributes: { class: 'fa fa-square-full' },
		category: 'Basics',
		media: false
	});

	editor.BlockManager.get( 'sect30' ).set({
		attributes: { class: 'fa fa-columns' },
		category: 'Basics',
		media: false
	});


	editor.BlockManager.get( 'sect50' ).set({
		attributes: { class: 'fa fa-columns' },
		category: 'Basics',
		media: false
	});

	editor.BlockManager.get( 'sect37' ).set({
		attributes: { class: 'fa fa-columns' },
		category: 'Basics',
		media: false
	});


	// Tab switching functionality
	const tabButtons = document.querySelectorAll( '.tab-button' );
	const tabPanes = document.querySelectorAll( '.tab-pane' );

	function switchTab( tabId ) {
		// Remove active class from all buttons and panes
		tabButtons.forEach( btn => btn.classList.remove('active' ));
		tabPanes.forEach( pane => pane.classList.remove('active' ));

		// Add active class to clicked button and corresponding pane
		const activeButton = document.querySelector( `[data-tab="${tabId}"]` );
		if ( activeButton ) {
			activeButton.classList.add( 'active' );
		}
		const activePane = document.getElementById( tabId );
		if ( activePane ) {
			activePane.classList.add( 'active' );
		}
	}

	tabButtons.forEach(button => {
		button.addEventListener( 'click', ( ) => {
			const tabId = button.getAttribute( 'data-tab' );
			switchTab( tabId );
		});
	});

	// Switch to style tab when element is selected
	editor.on( 'component:selected', ( ) => {
		switchTab( 'styles' );
	});

	// Template selection handling
	const templateSelect = document.getElementById( 'template-select' );

	templateSelect.addEventListener( 'change', function ( ) {
		console.log( "Changing" );

		const selectedOption = this.options[this.selectedIndex];
		const selectedCat = selectedOption.dataset.cat;
		const selectedTemplate = this.value;
		console.log( "Selected Category: ", selectedCat );

		// Update URL with selected template
		const url = new URL( window.location.href );
		if ( selectedTemplate ) {
			url.searchParams.set( 'template', selectedTemplate );
		} else {
			url.searchParams.delete( 'template' );
		}
		window.history.pushState( {}, '', url );

		const categories = document.querySelectorAll( '.gjs-block-category' );

		categories.forEach(category => {
			const title = category.querySelector( '.gjs-title' );

			category.style.display = '';

			if ( selectedCat === 'security-cat' && title && title.textContent.trim( ) === 'WooCommerce') {
				category.style.display = 'none';
			}

			if ( selectedCat === 'woo-cat' && title && title.textContent.trim( ) === 'Security') {
				category.style.display = 'none';
			}
		});

		const templateId = this.value;
		if ( !templateId ) {
			editor.setComponents( '' );
			editor.setStyle( '' );
			return;
		}

		// Disable save button while loading
		const saveButton = document.getElementById( 'save-template' );
		saveButton.disabled = true;
		saveButton.classList.remove( 'has-changes' );

		// Load template via AJAX
		const formData = new FormData();
		formData.append( 'action', 'x4email_load_template' );
		formData.append( 'template_name', templateId );
		formData.append( 'nonce', x4emailEditor.nonce );

		fetch(x4emailEditor.ajaxUrl, {
			method: 'POST',
			body: formData,
			credentials: 'same-origin'
		})
			.then( response => response.json( ))
			.then(data => {
				if ( data.success ) {
					// Remove PHP tags and echo statement from content
					const cleanContent = data.data.content.replace( /<\?php\s*echo\s*"|";\s*\?>/g, '' );
					editor.setComponents( cleanContent );
					editor.setStyle( data.data.css );
					hasChanges = false;
					updateSaveButtonState();
				} else {
					alert( data.data.message );
					if ( data.data.redirect ) {
						window.location.href = data.data.redirect;
					}
				}
			})
			.catch(error => {
				console.error( 'Error:', error );
				alert( 'Error loading template. Please try again.' );
			});
	});

	// Track changes and update save button state
	let hasChanges = false;
	const saveButton = document.getElementById( 'save-template' );

	// Function to update save button state
	function updateSaveButtonState() {
		if ( hasChanges ) {
			saveButton.classList.add( 'has-changes' );
			saveButton.disabled = false;
		} else {
			saveButton.classList.remove( 'has-changes' );
			saveButton.disabled = true;
		}
	}

	// Initialize save button as disabled
	updateSaveButtonState();

	// Listen for changes in the editor
	editor.on( 'component:add', ( ) => {
		hasChanges = true;
		updateSaveButtonState();
	});

	editor.on( 'component:update', ( ) => {
		hasChanges = true;
		updateSaveButtonState();
	});

	editor.on( 'component:remove', ( ) => {
		hasChanges = true;
		updateSaveButtonState();
	});

	editor.on( 'style:add', ( ) => {
		hasChanges = true;
		updateSaveButtonState();
	});

	editor.on( 'style:update', ( ) => {
		hasChanges = true;
		updateSaveButtonState();
	});

	editor.on( 'style:remove', ( ) => {
		hasChanges = true;
		updateSaveButtonState();
	});

	// Reset changes after successful save
	document.getElementById( 'save-template' ).addEventListener( 'click', ( ) => {
		const templateId = templateSelect.value;
		if ( !templateId ) {
			alert( 'Please select a template to save' );
			return;
		}

		const html = editor.getHtml();
		const css = editor.getCss();

		// Remove the body tag from the HTML content
		const contentWithoutBody = html.replace( /<body[^>]*>|<\/body>/g, '' );
		// Convert HTML content to use single quotes and wrap in PHP echo
		const convertedHtml = contentWithoutBody.replace( /"/g, "'" );

		// Create form data
		const formData = new FormData();
		formData.append( 'action', 'x4email_save_template' );
		formData.append( 'template_name', templateId );
		formData.append( 'content', convertedHtml );
		formData.append( 'css', css );
		formData.append( 'nonce', x4emailEditor.nonce );

		// Send AJAX request
		fetch(x4emailEditor.ajaxUrl, {
			method: 'POST',
			body: formData,
			credentials: 'same-origin'
		})
			.then( response => response.json( ))
			.then(data => {
				if ( data.success ) {
					hasChanges = false;
					updateSaveButtonState();
					alert( 'Template saved successfully!' );
				} else {
					alert( 'Error saving template: ' + data.data.message );
				}
			})
			.catch(error => {
				console.error( 'Error:', error );
				alert( 'Error saving template. Please try again.' );
			});
	});





	// Add keyboard shortcuts for undo/redo
	document.addEventListener( 'keydown', (e ) => {
		// Check if Ctrl/Cmd + Z is pressed ( Undo )
		if ( (e.ctrlKey || e.metaKey ) && e.key === 'z' && !e.shiftKey) {
			e.preventDefault();
			editor.runCommand( 'undo' );
		}
		// Check if Ctrl/Cmd + Shift + Z or Ctrl/Cmd + Y is pressed ( Redo )
		if ( ((e.ctrlKey || e.metaKey ) && e.key === 'z' && e.shiftKey) || ( (e.ctrlKey || e.metaKey ) && e.key === 'y')) {
			e.preventDefault();
			editor.runCommand( 'redo' );
		}
	});

	// Update undo/redo button states
	editor.on( 'undo:add', ( ) => {
		const undoBtn = document.querySelector( '[id="undo"]' );
		if ( undoBtn ) {
			undoBtn.classList.add( 'active' );
		}
	});

	editor.on( 'undo:remove', ( ) => {
		const undoBtn = document.querySelector( '[id="undo"]' );
		if ( undoBtn ) {
			undoBtn.classList.remove( 'active' );
		}
	});

	editor.on( 'redo:add', ( ) => {
		const redoBtn = document.querySelector( '[id="redo"]' );
		if ( redoBtn ) {
			redoBtn.classList.add( 'active' );
		}
	});

	editor.on( 'redo:remove', ( ) => {
		const redoBtn = document.querySelector( '[id="redo"]' );
		if ( redoBtn ) {
			redoBtn.classList.remove( 'active' );
		}
	});

	// Add tooltips for undo/redo buttons
	const undoBtn = document.querySelector( '[id="undo"]' );
	const redoBtn = document.querySelector( '[id="redo"]' );

	if ( undoBtn ) {
		undoBtn.title = 'Undo ( Ctrl+Z )';
	}
	if ( redoBtn ) {
		redoBtn.title = 'Redo ( Ctrl+Shift+Z or Ctrl+Y )';
	}

	// Add custom save handler to replace shortcodes with PHP code


	// Fullscreen toggle functionality
	const fullscreenBtn = document.getElementById( 'toggle-fullscreen' );
	const editorWrapper = document.querySelector( '.x4email-editor-wrapper' );
	const editorContainer = document.querySelector( '.x4email-editor-container' );

	fullscreenBtn.addEventListener( 'click', ( ) => {
		editorWrapper.classList.toggle( 'x4email-fullscreen' );

		// Update button icon
		const icon = fullscreenBtn.querySelector( 'i' );
		if ( editorWrapper.classList.contains('x4email-fullscreen' )) {
			icon.classList.remove( 'fa-expand' );
			icon.classList.add( 'fa-compress' );
		} else {
			icon.classList.remove( 'fa-compress' );
			icon.classList.add( 'fa-expand' );
		}

		// Trigger editor resize to adjust to new dimensions
		editor.refresh();
	});

	// Improved keyboard shortcuts
	document.addEventListener( 'keydown', (e ) => {
		// Existing undo/redo shortcuts
		if ( (e.ctrlKey || e.metaKey ) && e.key === 'z' && !e.shiftKey) {
			e.preventDefault();
			editor.runCommand( 'undo' );
		}
		if ( ((e.ctrlKey || e.metaKey ) && e.key === 'z' && e.shiftKey) || ( (e.ctrlKey || e.metaKey ) && e.key === 'y')) {
			e.preventDefault();
			editor.runCommand( 'redo' );
		}


	});


});
