/**
 * Elementor editor integration for AI Alt Text.
 */
(function ($) {
	'use strict';

	function getPanelModel() {
		if (!window.elementor || !elementor.getPanelView) {
			return null;
		}
		const panel = elementor.getPanelView();
		if (!panel || !panel.getCurrentPageView) {
			return null;
		}
		const page = panel.getCurrentPageView();
		return page && page.model ? page.model : null;
	}

	function getAttachmentId(model) {
		if (!model || !model.get) {
			return 0;
		}
		const widget = model.get('widgetType') || '';
		const settings = model.get('settings') || {};
		const attrs = settings.attributes || settings;

		if (widget === 'image' && attrs.image && attrs.image.id) {
			return parseInt(attrs.image.id, 10) || 0;
		}
		if (widget === 'image-box' && attrs.image && attrs.image.id) {
			return parseInt(attrs.image.id, 10) || 0;
		}
		if (attrs.id) {
			return parseInt(attrs.id, 10) || 0;
		}
		return 0;
	}

	function applyAltToModel(model, altText) {
		const widget = model.get('widgetType') || '';
		const settings = model.get('settings');
		const attrs = settings.attributes || settings;

		if (widget === 'image' || widget === 'image-box') {
			const image = attrs.image || {};
			image.alt = altText;
			settings.set('image', image);
			return;
		}

		settings.set('alt', altText);
	}

	$(document).on('click', '.wpps-ai-alt-elementor-generate', function (event) {
		event.preventDefault();

		if (!window.wppsAiAltElementor) {
			return;
		}

		const model = getPanelModel();
		const attachmentId = getAttachmentId(model);
		const $btn = $(this);

		if (!attachmentId) {
			window.alert(wppsAiAltElementor.strings.noImage);
			return;
		}

		$btn.prop('disabled', true).text(wppsAiAltElementor.strings.generating);

		$.post(wppsAiAltElementor.ajaxUrl, {
			action: 'wpps_ai_alt_elementor_generate',
			nonce: wppsAiAltElementor.nonce,
			attachment_id: attachmentId,
			force: 1
		})
			.done(function (res) {
				if (res.success && res.data && res.data.alt_text) {
					applyAltToModel(model, res.data.alt_text);
					if (window.elementor && elementor.notifications) {
						elementor.notifications.showToast({
							message: wppsAiAltElementor.strings.success
						});
					}
				} else {
					window.alert((res.data && res.data.message) || wppsAiAltElementor.strings.error);
				}
			})
			.fail(function () {
				window.alert(wppsAiAltElementor.strings.error);
			})
			.always(function () {
				$btn.prop('disabled', false).text('Generate alt text with AI');
			});
	});
})(jQuery);
