/**
 * Gutenberg Editor Support for Broken Image Fallback Pro
 * Handles broken images within the WordPress block editor
 * 
 * @author Nikunj Hatkar
 * @link https://github.com/nikunj8866
 */

(function() {
	'use strict';
	
	const { wp } = window;
	if (!wp || !wp.domReady) {
		return;
	}
	
	// Configuration from WordPress
	const config = window.brokimfaGutenbergOptions || {
		fallbackMethod: 'default_image',
		defaultImageUrl: '',
		enableFade: true
	};
	
	// Track processed images in editor
	const processedEditorImages = new WeakSet();

	/**
	 * Clear srcset and sizes attributes for Gutenberg images
	 */
	function clearGutenbergResponsiveAttributes(img) {
		// Remove srcset to prevent browser from loading other images
		if (img.hasAttribute('srcset')) {
			img.removeAttribute('srcset');
		}
		// Remove sizes attribute as it's not needed without srcset  
		if (img.hasAttribute('sizes')) {
			img.removeAttribute('sizes');
		}
	}
	
	/**
	 * Handle broken images in Gutenberg editor
	 */
	function handleGutenbergBrokenImage(img) {
		if (processedEditorImages.has(img)) {
			return;
		}
		
		processedEditorImages.add(img);
		img.setAttribute('data-brokimfa-editor-processed', 'true');
		
		const method = config.fallbackMethod;
		
		switch (method) {
			case 'default_image':
				if (config.defaultImageUrl) {
					clearGutenbergResponsiveAttributes(img);
					img.src = config.defaultImageUrl;
					img.classList.add('brokimfa-editor-fallback');
				}
				break;
				
			case 'alt_text':
				createEditorAltTextFallback(img);
				break;
				
			case 'both':
				if (config.defaultImageUrl) {
					// Try to load default image first
					const testImg = new Image();
					testImg.onload = () => {
						clearGutenbergResponsiveAttributes(img);
						img.src = config.defaultImageUrl;
						img.classList.add('brokimfa-editor-fallback');
					};
					testImg.onerror = () => {
						createEditorAltTextFallback(img);
					};
					testImg.src = config.defaultImageUrl;
				} else {
					createEditorAltTextFallback(img);
				}
				break;
				
			case 'hide':
				img.style.display = 'none';
				break;
		}
	}
	
	/**
	 * Create alt text fallback in editor
	 */
	function createEditorAltTextFallback(img) {
		const altText = img.getAttribute('alt') || 'Image not available';
		const fallbackDiv = document.createElement('div');
		
		fallbackDiv.className = 'brokimfa-editor-alt-fallback';
		fallbackDiv.textContent = altText;
		fallbackDiv.style.cssText = `
			background: #f0f0f0;
			padding: 20px;
			text-align: center;
			color: #666;
			border: 2px dashed #ccc;
			border-radius: 4px;
			font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
			min-height: 100px;
			display: flex;
			align-items: center;
			justify-content: center;
		`;
		
		if (img.parentNode) {
			img.parentNode.replaceChild(fallbackDiv, img);
		}
	}
	
	/**
	 * Check if image is broken
	 */
	function isImageBrokenInEditor(img) {
		return !img.complete || img.naturalWidth === 0 || img.naturalHeight === 0;
	}
	
	/**
	 * Process images in the editor
	 */
	function processEditorImages() {
		const editor = document.querySelector('.edit-post-visual-editor');
		if (!editor) {
			return;
		}
		
		const images = editor.querySelectorAll('.wp-block-image img, .wp-block-gallery img, .wp-block-media-text img');
		
		images.forEach(img => {
			if (processedEditorImages.has(img)) {
				return;
			}
			
			if (isImageBrokenInEditor(img)) {
				handleGutenbergBrokenImage(img);
			} else {
				// Add error listener
				img.addEventListener('error', () => {
					handleGutenbergBrokenImage(img);
				}, { once: true });
			}
		});
	}
	
	/**
	 * Setup editor observer
	 */
	function setupEditorObserver() {
		if (!window.MutationObserver) {
			return;
		}
		
		const editor = document.querySelector('.edit-post-visual-editor');
		if (!editor) {
			// Try again later
			setTimeout(setupEditorObserver, 1000);
			return;
		}
		
		const observer = new MutationObserver((mutations) => {
			let hasNewImages = false;
			
			mutations.forEach(mutation => {
				if (mutation.type === 'childList') {
					mutation.addedNodes.forEach(node => {
						if (node.nodeType === Node.ELEMENT_NODE) {
							if (node.tagName === 'IMG' && node.closest('.wp-block-image, .wp-block-gallery, .wp-block-media-text')) {
								hasNewImages = true;
							} else if (node.querySelector) {
								const imgs = node.querySelectorAll('.wp-block-image img, .wp-block-gallery img, .wp-block-media-text img');
								if (imgs.length > 0) {
									hasNewImages = true;
								}
							}
						}
					});
				}
			});
			
			if (hasNewImages) {
				setTimeout(processEditorImages, 100);
			}
		});
		
		observer.observe(editor, {
			childList: true,
			subtree: true
		});
	}
	
	/**
	 * Initialize Gutenberg support
	 */
	function initGutenbergSupport() {
		// Process existing images
		processEditorImages();
		
		// Setup observer
		setupEditorObserver();
		
		// Add editor-specific styles
		if (!document.getElementById('brokimfa-editor-styles')) {
			const style = document.createElement('style');
			style.id = 'brokimfa-editor-styles';
			style.textContent = `
				.brokimfa-editor-fallback {
					border: 2px solid #0073aa;
					padding: 2px;
				}
				.brokimfa-editor-alt-fallback {
					user-select: none;
				}
				.wp-block-image .brokimfa-editor-fallback,
				.wp-block-gallery .brokimfa-editor-fallback {
					max-width: 100%;
					height: auto;
				}
			`;
			document.head.appendChild(style);
		}
		
		console.log('Broken Image Fallback Pro: Gutenberg support initialized');
	}
	
	// Initialize when editor is ready
	wp.domReady(initGutenbergSupport);
	
	// Fallback initialization for dynamic loading
	if (wp.data && wp.data.select('core/edit-post')) {
		const unsubscribe = wp.data.subscribe(() => {
			const isEditorReady = wp.data.select('core/edit-post') && wp.data.select('core/edit-post').isEditorReady();
			if (isEditorReady) {
				setTimeout(initGutenbergSupport, 500);
				unsubscribe();
			}
		});
	}
	
})();