/**
 * Default Image Selector
 *
 * Manages WordPress media library integration for selecting default featured
 * images with preview and removal capabilities.
 *
 * @file
 * @since 1.0.0
 * @package AgenticWP
 * @namespace AgenticWPAdmin.defaultImage
 */

(function($) {
	'use strict';

	const AgenticWPAdmin = window.AgenticWPAdmin = window.AgenticWPAdmin || {};

	let mediaFrame = null;
	let currentField = null;

	/**
	 * Initializes default image selector.
	 */
	function init() {
		if (typeof wp === 'undefined' || !wp.media) {
			return;
		}

		$(document).on('click', '.agenticwp-select-default-image', openMediaFrame);
		$(document).on('click', '.agenticwp-remove-default-image', removeDefaultImage);
	}

	function openMediaFrame(event) {
		event.preventDefault();

		if (typeof wp === 'undefined' || !wp.media) {
			return;
		}

		currentField = $(this).closest('.agenticwp-default-image-field');
		if (!currentField.length) {
			return;
		}

		try {
			if (!mediaFrame) {
				mediaFrame = wp.media({
					title: 'Select Image',
					button: { text: 'Use this image' },
					multiple: false,
					library: { type: 'image' }
				});

				mediaFrame.on('select', applySelectedImage);
			}

			mediaFrame.open();
		} catch (e) {
		}
	}

	function applySelectedImage() {
		if (!currentField || !currentField.length) {
			return;
		}

		try {
			if (!mediaFrame || !mediaFrame.state) {
				return;
			}

			const selection = mediaFrame.state().get('selection');
			const attachment = selection && selection.first() ? selection.first().toJSON() : null;

			if (!attachment || !attachment.id) {
				return;
			}

			const hiddenField = currentField.find('#agenticwp-default-image-id');
			const previewImage = currentField.find('.agenticwp-preview-img');
			const removeButton = currentField.find('.agenticwp-remove-default-image');
			const card = currentField.find('.agenticwp-image-selector-card');

			if (!hiddenField.length || !previewImage.length) {
				return;
			}

			if (card.length) {
				card.addClass('loading');
			}

			hiddenField.val(attachment.id);

			const url = resolveAttachmentUrl(attachment);
			if (url) {
				const newImg = new Image();
				newImg.onload = function() {
					previewImage.fadeOut(200, function() {
						previewImage.attr('src', url);
						previewImage.fadeIn(300);
						if (card.length) {
							card.removeClass('loading');
						}
					});
				};
				newImg.onerror = function() {
					previewImage.attr('src', url);
					if (card.length) {
						card.removeClass('loading');
					}
				};
				newImg.src = url;
			} else {
				if (card.length) {
					card.removeClass('loading');
				}
			}

			if (removeButton.length) {
				removeButton.fadeIn(300);
			}
		} catch (e) {
		}
	}

	function resolveAttachmentUrl(attachment) {
		if (!attachment || typeof attachment !== 'object') {
			return '';
		}

		if (attachment.sizes && typeof attachment.sizes === 'object') {
			if (attachment.sizes.medium && attachment.sizes.medium.url) {
				return attachment.sizes.medium.url;
			}
			if (attachment.sizes.large && attachment.sizes.large.url) {
				return attachment.sizes.large.url;
			}
			if (attachment.sizes.full && attachment.sizes.full.url) {
				return attachment.sizes.full.url;
			}
		}

		return attachment.url || '';
	}

	function removeDefaultImage(event) {
		event.preventDefault();

		const $button = $(this);
		const $field = $button.closest('.agenticwp-default-image-field');

		if (!$field.length) {
			return;
		}

		try {
			const fallbackUrl = $field.data('default-url');
			const previewImage = $field.find('.agenticwp-preview-img');
			const card = $field.find('.agenticwp-image-selector-card');
			const hiddenField = $field.find('#agenticwp-default-image-id');

			if (!hiddenField.length) {
				return;
			}

			if (card.length) {
				card.addClass('loading');
			}

			hiddenField.val(0);

			if (fallbackUrl) {
				const newImg = new Image();
				newImg.onload = function() {
					if (previewImage.length) {
						previewImage.fadeOut(200, function() {
							previewImage.attr('src', fallbackUrl);
							previewImage.fadeIn(300);
							if (card.length) {
								card.removeClass('loading');
							}
						});
					} else if (card.length) {
						card.removeClass('loading');
					}
				};
				newImg.onerror = function() {
					if (previewImage.length) {
						previewImage.attr('src', fallbackUrl);
					}
					if (card.length) {
						card.removeClass('loading');
					}
				};
				newImg.src = fallbackUrl;
			} else {
				if (card.length) {
					card.removeClass('loading');
				}
			}

			$button.fadeOut(300);
		} catch (e) {
		}
	}

	AgenticWPAdmin.defaultImage = {
		init: init
	};
})(jQuery);
