/**
 * Classic Editor fallback for the "AEO Controls" panel: adds Generate
 * Summary/FAQ buttons to a meta box on post edit screens that won't load
 * the block editor (e.g. the Classic Editor plugin is active). Mirrors
 * editor.js's block-editor sidebar panel and calls the exact same REST
 * endpoints, but as plain vanilla JS against server-rendered markup --
 * Classic Editor screens don't load the `@wordpress/plugins` /
 * `@wordpress/edit-post` bundles that panel depends on. Only `wp-api-fetch`
 * (enqueued as this script's dependency) is needed, and it works standalone.
 */
( function ( wp ) {
	'use strict';

	document.addEventListener( 'DOMContentLoaded', function () {
		var root = document.getElementById( 'priizmo-engine-classic-controls' );

		if ( ! root || ! wp || ! wp.apiFetch || typeof window.priizmoEngineClassicEditor === 'undefined' ) {
			return;
		}

		var settings = window.priizmoEngineClassicEditor;
		var postId = parseInt( root.getAttribute( 'data-post-id' ), 10 );

		var summaryButton = document.getElementById( 'priizmo-engine-classic-generate-summary' );
		var summaryPreview = document.getElementById( 'priizmo-engine-classic-summary-preview' );
		var faqButton = document.getElementById( 'priizmo-engine-classic-generate-faq' );
		var faqPreview = document.getElementById( 'priizmo-engine-classic-faq-preview' );

		/**
		 * Escapes text for safe insertion as HTML (the AI-generated
		 * summary/FAQ text is plain text, but is inserted via innerHTML
		 * alongside markup, so it must be escaped first).
		 *
		 * @param {string} str Raw text.
		 * @return {string} HTML-escaped text.
		 */
		function escapeHtml( str ) {
			var div = document.createElement( 'div' );
			div.textContent = str || '';
			return div.innerHTML;
		}

		/**
		 * Toggles a button's disabled/busy state and label.
		 *
		 * @param {HTMLButtonElement} button   Button element.
		 * @param {boolean}           isBusy   Whether a request is in flight.
		 * @param {string}            idleLabel Label to restore when not busy.
		 */
		function setButtonBusy( button, isBusy, idleLabel ) {
			button.disabled = isBusy;
			button.textContent = isBusy ? settings.i18n.generating : idleLabel;
		}

		if ( summaryButton && postId ) {
			summaryButton.addEventListener( 'click', function () {
				setButtonBusy( summaryButton, true, settings.i18n.generateSummary );

				wp.apiFetch( {
					path: '/priizmo-engine/v1/generate-summary',
					method: 'POST',
					data: { post_id: postId, force: true },
				} )
					.then( function ( response ) {
						setButtonBusy( summaryButton, false, settings.i18n.generateSummary );
						summaryPreview.innerHTML =
							'<div class="priizmo-engine-controls-preview">' +
							'<strong>' + escapeHtml( settings.i18n.cachedSummary ) + '</strong>' +
							'<p>' + escapeHtml( response.summary ) + '</p>' +
							'</div>';
					} )
					.catch( function ( error ) {
						setButtonBusy( summaryButton, false, settings.i18n.generateSummary );
						window.alert( ( error && error.message ) || settings.i18n.summaryError );
					} );
			} );
		}

		if ( faqButton && postId ) {
			faqButton.addEventListener( 'click', function () {
				setButtonBusy( faqButton, true, settings.i18n.generateFaq );

				wp.apiFetch( {
					path: '/priizmo-engine/v1/generate-faq',
					method: 'POST',
					data: { post_id: postId, force: true },
				} )
					.then( function ( response ) {
						setButtonBusy( faqButton, false, settings.i18n.generateFaq );

						var items = Array.isArray( response.faq ) ? response.faq : [];

						if ( ! items.length ) {
							faqPreview.innerHTML = '<p class="priizmo-engine-controls-empty">' + escapeHtml( settings.i18n.noFaq ) + '</p>';
							return;
						}

						var html = '<ul class="priizmo-engine-controls-faq-preview">';
						items.forEach( function ( item ) {
							html += '<li><strong>' + escapeHtml( item.question ) + '</strong><p>' + escapeHtml( item.answer ) + '</p></li>';
						} );
						html += '</ul>';

						faqPreview.innerHTML = html;
					} )
					.catch( function ( error ) {
						setButtonBusy( faqButton, false, settings.i18n.generateFaq );
						window.alert( ( error && error.message ) || settings.i18n.faqError );
					} );
			} );
		}
	} );
} )( window.wp );
