(function ($) {
	'use strict';

	var cfg = window.newsaiAiAlt || {};
	var label = cfg.label || 'Generate alt (AI)';
	var busy = cfg.busy || 'Generating…';
	var i18n = cfg.i18n || {};
	var injectTimer = null;

	function humanError(message) {
		var map = {
			invalid_attachment: i18n.invalid_attachment || 'Could not detect the image. Open the image details and try again.',
			unauthorized: i18n.unauthorized || 'You do not have permission to edit this image.',
			pro_required: i18n.pro_required || 'A Pro license is required for AI alt text.',
			ai_not_configured: i18n.ai_not_configured || 'AI Assist is not configured. Add a provider and API key in Settings → AI.',
			no_attachment: i18n.no_attachment || 'No image selected. Open the image (or its details) and click again.'
		};
		if (message && map[message]) {
			return map[message];
		}
		return message || (i18n.generic || 'AI alt generation failed. Please try again.');
	}

	function ensureMsgEl($alt) {
		var $host = $alt.parent();
		var $msg = $host.find('.newsai-ai-alt-msg');
		if (!$msg.length) {
			$msg = $('<span class="newsai-ai-alt-msg" style="display:block;margin-top:4px;font-size:12px;line-height:1.4;"></span>');
			$host.append($msg);
		}
		return $msg;
	}

	function showMsg($alt, text, isError) {
		var $msg = ensureMsgEl($alt);
		$msg.text(text || '').css('color', isError ? '#b91c1c' : '#15803d');
	}

	function getAttachmentId() {
		var id = 0;

		if (window.wp && wp.media && wp.media.frame) {
			try {
				var state = wp.media.frame.state();
				if (state && state.get) {
					var selection = state.get('selection');
					if (selection && selection.first) {
						var model = selection.first();
						if (model) {
							id = parseInt(model.get('id'), 10) || 0;
						}
					}
				}
			} catch (e) {
				/* ignore */
			}
		}

		if (!id) {
			id = parseInt($('#post_ID').val() || $('input[name="attachments[][post]"]').val() || 0, 10);
		}

		if (!id) {
			var $selected = $('.attachments .attachment.selected, .attachments .attachment.details').first();
			if ($selected.length) {
				id = parseInt($selected.data('id') || $selected.attr('data-id') || 0, 10);
			}
		}

		return id || 0;
	}

	function findAltField() {
		var selectors = [
			'#attachment-details-alt-text',
			'#attachment-details-two-column-alt-text',
			'#attachment_alt',
			'textarea[data-setting="alt"]',
			'input[data-setting="alt"]',
			'.attachment-details textarea[name="alt"]',
			'.attachment-details input[name="alt"]',
			'.compat-field-alt textarea',
			'.compat-field-alt input',
			'.setting[data-setting="alt"] textarea',
			'.setting[data-setting="alt"] input',
		];

		for (var i = 0; i < selectors.length; i++) {
			var $field = $(selectors[i]).filter(':visible').first();
			if ($field.length) {
				return $field;
			}
		}

		return $();
	}

	function injectAltBtn() {
		var $alt = findAltField();
		if (!$alt.length) {
			return;
		}

		var $host = $alt.closest('.setting, .compat-field-alt, .attachment-details').first();
		if (!$host.length) {
			$host = $alt.parent();
		}

		if ($host.find('.newsai-ai-alt-btn').length) {
			return;
		}

		var $btn = $('<button type="button" class="button newsai-ai-alt-btn" style="margin-top:6px;display:block;">' + label + '</button>');

		$btn.on('click', function () {
			var id = getAttachmentId();
			if (!id) {
				showMsg($alt, humanError('no_attachment'), true);
				return;
			}

			showMsg($alt, '', false);
			$btn.prop('disabled', true).text(busy);

			$.post(cfg.ajaxurl || ajaxurl, {
				action: 'newsai_ai_generate_alt',
				nonce: cfg.nonce,
				attachment_id: id,
			})
				.done(function (response) {
					if (response && response.success && response.data && response.data.alt) {
						$alt.val(response.data.alt).trigger('input').trigger('change');
						showMsg($alt, i18n.done || 'Alt text generated.', false);

						if (window.wp && wp.media && wp.media.frame) {
							try {
								var state = wp.media.frame.state();
								if (state && state.get) {
									var selection = state.get('selection');
									if (selection && selection.first) {
										var model = selection.first();
										if (model && model.set) {
											model.set('alt', response.data.alt);
										}
									}
								}
							} catch (e) {
								/* ignore */
							}
						}
					} else {
						var okMsg = response && response.data ? response.data.message : '';
						showMsg($alt, humanError(okMsg), true);
					}
				})
				.fail(function (xhr) {
					var msg = '';
					if (xhr && xhr.responseJSON && xhr.responseJSON.data && xhr.responseJSON.data.message) {
						msg = xhr.responseJSON.data.message;
					}
					showMsg($alt, humanError(msg), true);
				})
				.always(function () {
					$btn.prop('disabled', false).text(label);
				});
		});

		$alt.after($btn);
	}

	function scheduleInject() {
		clearTimeout(injectTimer);
		injectTimer = setTimeout(injectAltBtn, 120);
	}

	$(function () {
		scheduleInject();

		$(document).on('click', '.attachment, .media-modal, .upload-php', scheduleInject);

		if (window.wp && wp.media) {
			$(document).on('click', '.media-button, .add_media, .insert-media', function () {
				setTimeout(scheduleInject, 400);
			});
		}

		if (typeof MutationObserver !== 'undefined') {
			var observer = new MutationObserver(scheduleInject);
			observer.observe(document.body, { childList: true, subtree: true });
		} else {
			$(document).on('DOMNodeInserted', scheduleInject);
		}
	});
})(jQuery);
