/**
 * Admin JavaScript for Broken Image Fallback Pro
 * 
 * @author Nikunj Hatkar
 * @link https://github.com/nikunj8866
 */

jQuery(document).ready(function($) {
	
	// Media uploader for default image
	$('#upload_image_button').click(function(e) {
		e.preventDefault();
		openMediaUploader('default_image_url');
	});
	
	// Media uploader for featured image
	$('#upload_featured_image_button').click(function(e) {
		e.preventDefault();
		if ($(this).is(':disabled')) {
			showUpgradeNotice();
			return false;
		}
		openMediaUploader('featured_image_url');
	});
	
	// Media uploader for featured placeholder image
	$('#upload_featured_placeholder_button').click(function(e) {
		e.preventDefault();
		if ($(this).is(':disabled')) {
			showUpgradeNotice();
			return false;
		}
		openMediaUploader('featured_placeholder_url');
	});
	
	// Generic media uploader function
	function openMediaUploader(targetField) {
		var mediaUploader = wp.media({
			title: 'Choose Fallback Image',
			button: {
				text: 'Choose Image'
			},
			multiple: false
		});
		
		mediaUploader.on('select', function() {
			var attachment = mediaUploader.state().get('selection').first().toJSON();
			$('#' + targetField).val(attachment.url);
			
			// Update preview
			var $container = $('#' + targetField).closest('.brokimfa-image-upload');
			var preview = $container.find('.brokimfa-image-preview');
			if (preview.length) {
				preview.find('img').attr('src', attachment.url);
			} else {
				$container.append(
					'<div class="brokimfa-image-preview">' +
					'<img src="' + attachment.url + '" style="max-width: 150px; max-height: 100px; margin-top: 10px;" />' +
					'</div>'
				);
			}
			
			// Update live preview
			updateLivePreview();
		});
		
		mediaUploader.open();
	}
	
	// Dynamic form behavior
	$('#fallback_method').change(function() {
		var method = $(this).val();
		var $defaultImageRow = $('tr:has(#default_image_url)');
		var $altTextRow = $('tr:has(#alt_text_style)');
		
		// Show/hide relevant fields
		if (method === 'default_image' || method === 'both') {
			$defaultImageRow.show();
		} else {
			$defaultImageRow.hide();
		}
		
		if (method === 'alt_text' || method === 'both') {
			$altTextRow.show();
			// Check if PRO feature is disabled
			if ($('#alt_text_style').is(':disabled')) {
				$altTextRow.find('td').append('<div class="brokimfa-upgrade-notice">This is a PRO feature. <a href="#" onclick="showUpgradeModal(); return false;">Upgrade now</a></div>');
			}
		} else {
			$altTextRow.hide();
			$altTextRow.find('.brokimfa-upgrade-notice').remove();
		}
	}).trigger('change');
	
	// Enable/disable fade duration based on fade checkbox
	$('#enable_fade').change(function() {
		if ($(this).is(':disabled')) {
			$(this).prop('checked', false);
			showUpgradeNotice();
			return false;
		}
		
		var $fadeDurationRow = $('tr:has(#fade_duration)');
		if ($(this).is(':checked')) {
			$fadeDurationRow.show();
			$('#fade_duration').prop('disabled', false);
		} else {
			$fadeDurationRow.hide();
			$('#fade_duration').prop('disabled', true);
		}
	}).trigger('change');
	
	// Show/hide featured placeholder URL based on placeholder checkbox
	$('#show_placeholder_featured').change(function() {
		if ($(this).is(':disabled')) {
			$(this).prop('checked', false);
			showUpgradeNotice();
			return false;
		}
		
		var $placeholderUrlRow = $('tr:has(#featured_placeholder_url)');
		if ($(this).is(':checked')) {
			$placeholderUrlRow.show();
			$('#featured_placeholder_url').prop('disabled', false);
		} else {
			$placeholderUrlRow.hide();
			$('#featured_placeholder_url').prop('disabled', true);
		}
	}).trigger('change');

	// Show/hide featured image URL based on featured image support checkbox
	$('#enable_featured_image').change(function() {
		if ($(this).is(':disabled')) {
			$(this).prop('checked', false);
			showUpgradeNotice();
			return false;
		}
		
		var $featuredImageUrlRow = $('tr:has(#featured_image_url)');
		if ($(this).is(':checked')) {
			$featuredImageUrlRow.show();
			$('#featured_image_url').prop('disabled', false);
		} else {
			$featuredImageUrlRow.hide();
			$('#featured_image_url').prop('disabled', true);
		}
	}).trigger('change');

	
	// CSS syntax highlighting for alt text style (basic)
	$('#alt_text_style').on('input', function() {
		if ($(this).is(':disabled')) {
			return false;
		}
		
		// Add basic CSS validation
		var cssText = $(this).val();
		var isValid = true;
		
		try {
			// Basic validation - check for balanced braces if any
			var openBraces = (cssText.match(/\{/g) || []).length;
			var closeBraces = (cssText.match(/\}/g) || []).length;
			
			if (openBraces !== closeBraces) {
				isValid = false;
			}
		} catch (e) {
			isValid = false;
		}
		
		$(this).toggleClass('brokimfa-invalid-css', !isValid);
	});
	
	// Handle disabled textarea clicks
	$('#alt_text_style').on('click', function() {
		if ($(this).is(':disabled')) {
			showUpgradeNotice();
			return false;
		}
	});
	
	// Live preview functionality
	function updateLivePreview() {
		var method = $('#fallback_method').val();
		var altStyle = $('#alt_text_style').val();
		var enableFade = $('#enable_fade').is(':checked');
		var fadeDuration = $('#fade_duration').val();
		
		var $preview = $('#brokimfa-live-preview');
		if ($preview.length === 0) {
			$('<div id="brokimfa-live-preview" style="margin-top: 20px; padding: 15px; border: 1px solid #ddd; background: #fff;"><h4>Live Preview:</h4><div id="brokimfa-preview-content"></div></div>')
				.insertAfter('.form-table:last');
			$preview = $('#brokimfa-live-preview');
		}
		
		var $content = $('#brokimfa-preview-content');
		
		if (method === 'alt_text' || method === 'both') {
			var previewHtml = '<div class="brokimfa-alt-text-fallback" style="' + altStyle + '">Sample Alt Text</div>';
			$content.html(previewHtml);
			
			if (enableFade) {
				$content.find('.brokimfa-alt-text-fallback').css('transition', 'opacity ' + fadeDuration + 'ms ease-in-out');
			}
		} else if (method === 'default_image') {
			var imageUrl = $('#default_image_url').val() || 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTAwIiBoZWlnaHQ9IjYwIj48cmVjdCB3aWR0aD0iMTAwIiBoZWlnaHQ9IjYwIiBmaWxsPSIjZjVmNWY1Ii8+PHRleHQgeD0iNTAiIHk9IjMwIiBmb250LXNpemU9IjEwIiBmaWxsPSIjOTk5IiB0ZXh0LWFuY2hvcj0ibWlkZGxlIj5JbWFnZTwvdGV4dD48L3N2Zz4=';
			$content.html('<img src="' + imageUrl + '" alt="Preview" style="max-width: 200px; max-height: 100px;" />');
		} else {
			$content.html('<em>Preview not available for this method</em>');
		}
	}
	
	// Bind live preview updates
	$('#fallback_method, #alt_text_style, #enable_fade, #fade_duration, #default_image_url, #featured_image_url, #featured_placeholder_url').on('change input', 
		debounce(updateLivePreview, 500)
	);
	
	// Debounce helper
	function debounce(func, wait) {
		var timeout;
		return function executedFunction() {
			var later = function() {
				clearTimeout(timeout);
				func();
			};
			clearTimeout(timeout);
			timeout = setTimeout(later, wait);
		};
	}
	
	// Initialize live preview
	updateLivePreview();
	
	// Upgrade notice functions
	function showUpgradeNotice() {
		alert('This is a PRO feature. Please upgrade to access all features.');
	}
	
	function showUpgradeModal() {
		if (confirm('This is a PRO feature. Would you like to upgrade now?')) {
			// Redirect to upgrade page or open upgrade modal
			window.open('admin.php?page=broken-image-fallback-pricing', '_blank');
		}
	}
});