(function(wp) {
	if (!wp || !wp.plugins || !wp.blockEditor) return;

	var registerPlugin = wp.plugins.registerPlugin;
	var PluginSidebar = wp.editor.PluginSidebar;
	var PluginSidebarMoreMenuItem = wp.editor.PluginSidebarMoreMenuItem;
	var useState = wp.element.useState;
	var useEffect = wp.element.useEffect;
	var createElement = wp.element.createElement;
	var Button = wp.components.Button;
	var TextareaControl = wp.components.TextareaControl;
	var PanelBody = wp.components.PanelBody;
	var useSelect = wp.data.useSelect;
	var useDispatch = wp.data.useDispatch;
	var __ = wp.i18n.__;

	var config = window.wppsAiAltGutenberg || {};
	var strings = config.strings || {};

	function getSelectedImageBlock(select) {
		var selected = select('core/block-editor').getSelectedBlock();
		if (!selected) return null;

		var imageBlocks = ['core/image', 'core/cover', 'core/media-text'];
		if (imageBlocks.indexOf(selected.name) === -1) return null;

		var attrs = selected.attributes || {};
		var attachmentId = attrs.id || 0;
		var alt = attrs.alt || '';

		return {
			clientId: selected.clientId,
			blockName: selected.name,
			attachmentId: attachmentId,
			alt: alt
		};
	}

	function postAjax(action, payload) {
		var body = new FormData();
		body.append('action', action);
		body.append('nonce', config.nonce || '');
		Object.keys(payload || {}).forEach(function(key) {
			body.append(key, payload[key]);
		});
		return fetch(config.ajaxUrl, { method: 'POST', body: body, credentials: 'same-origin' }).then(function(r) {
			return r.json();
		});
	}

	function AiAltSidebar() {
		var block = useSelect(function(select) {
			return getSelectedImageBlock(select);
		}, []);

		var dispatch = useDispatch('core/block-editor');
		var updateBlockAttributes = dispatch.updateBlockAttributes;

		var altState = useState(block ? block.alt : '');
		var altText = altState[0];
		var setAltText = altState[1];

		var busyState = useState(false);
		var busy = busyState[0];
		var setBusy = busyState[1];

		var messageState = useState('');
		var message = messageState[0];
		var setMessage = messageState[1];

		useEffect(function() {
			setAltText(block ? (block.alt || '') : '');
			setMessage('');
		}, [block ? block.clientId : null, block ? block.alt : null]);

		if (!block) {
			return createElement(PanelBody, { title: strings.panelTitle || 'AI Alt Text' },
				createElement('p', null, strings.noImage || 'Select an image block.')
			);
		}

		function applyToBlock(value) {
			updateBlockAttributes(block.clientId, { alt: value || '' });
			setAltText(value || '');
		}

		function generateAi() {
			if (!config.hasApiKey) {
				setMessage(strings.noApiKey || 'API key missing.');
				return;
			}
			if (!block.attachmentId) {
				setMessage('This block is not linked to a media library item.');
				return;
			}
			setBusy(true);
			setMessage(strings.generating || 'Generating...');
			postAjax('wpps_ai_alt_generate', { attachment_id: block.attachmentId })
				.then(function(res) {
					setBusy(false);
					if (res.success && res.data && res.data.alt_text) {
						setAltText(res.data.alt_text);
						setMessage(strings.saved || 'Suggestion ready.');
					} else {
						setMessage((res.data && res.data.message) || strings.error);
					}
				})
				.catch(function() {
					setBusy(false);
					setMessage(strings.error || 'Error');
				});
		}

		function localSuggest() {
			if (!block.attachmentId) return;
			setBusy(true);
			postAjax('wpps_ai_alt_local_suggest', { attachment_id: block.attachmentId })
				.then(function(res) {
					setBusy(false);
					if (res.success && res.data && res.data.alt_text) {
						setAltText(res.data.alt_text);
						setMessage(strings.saved || 'Suggestion ready.');
					} else {
						setMessage((res.data && res.data.message) || strings.error);
					}
				});
		}

		function saveToMedia() {
			if (!block.attachmentId) return;
			setBusy(true);
			postAjax('wpps_ai_alt_save', { attachment_id: block.attachmentId, alt_text: altText })
				.then(function(res) {
					setBusy(false);
					setMessage(res.success ? (strings.saved || 'Saved.') : ((res.data && res.data.message) || strings.error));
				});
		}

		return createElement(
			PanelBody,
			{ title: strings.panelTitle || 'AI Alt Text', initialOpen: true },
			createElement(TextareaControl, {
				label: __('Alt text', 'wp-powersuite'),
				value: altText,
				onChange: setAltText,
				rows: 4
			}),
			createElement('div', { style: { display: 'flex', gap: '8px', flexWrap: 'wrap', marginBottom: '8px' } },
				createElement(Button, { variant: 'primary', onClick: generateAi, disabled: busy }, strings.generate || 'Generate'),
				createElement(Button, { variant: 'secondary', onClick: localSuggest, disabled: busy }, strings.local || 'Local'),
				createElement(Button, { variant: 'secondary', onClick: function() { applyToBlock(altText); }, disabled: busy }, strings.saveBlock || 'Apply to block'),
				createElement(Button, { variant: 'secondary', onClick: saveToMedia, disabled: busy || !block.attachmentId }, strings.saveMedia || 'Save to library')
			),
			message && createElement('p', { style: { margin: 0 } }, message)
		);
	}

	registerPlugin('wpps-ai-alt-text-sidebar', {
		render: function() {
			return createElement(
				wp.element.Fragment,
				null,
				createElement(PluginSidebarMoreMenuItem, { target: 'wpps-ai-alt-text-sidebar', icon: 'format-image' },
					strings.panelTitle || 'AI Alt Text'
				),
				createElement(
					PluginSidebar,
					{ name: 'wpps-ai-alt-text-sidebar', title: strings.panelTitle || 'AI Alt Text', icon: 'format-image' },
					createElement(AiAltSidebar, null)
				)
			);
		}
	});
})(window.wp);
