/**
 * "AEO Controls" document sidebar panel for the block editor.
 *
 * Adds "Generate AI Summary" and "Generate AI FAQs" buttons that send the
 * current post's content to the AEO Engine REST endpoints, which call the
 * configured AI provider server-side (so API keys never reach the browser)
 * and cache the results on the post as `_priizmo_cached_summary` and
 * `_priizmo_cached_faq_data`.
 */
( function ( wp ) {
	'use strict';

	if ( ! wp || ! wp.plugins || ! wp.editPost || ! wp.element ) {
		return;
	}

	var el = wp.element.createElement;
	var useState = wp.element.useState;
	var useSelect = wp.data.useSelect;
	var useDispatch = wp.data.useDispatch;
	var registerPlugin = wp.plugins.registerPlugin;
	var PluginDocumentSettingPanel = wp.editPost.PluginDocumentSettingPanel;
	var Button = wp.components.Button;
	var __ = wp.i18n.__;

	/**
	 * Renders the AEO Controls panel.
	 */
	function AEOControlsPanel() {
		var postId = useSelect( function ( select ) {
			return select( 'core/editor' ).getCurrentPostId();
		}, [] );

		var cachedMeta = useSelect( function ( select ) {
			return select( 'core/editor' ).getEditedPostAttribute( 'meta' ) || {};
		}, [] );

		var createNotice = useDispatch( 'core/notices' ).createNotice;

		var summaryState = useState( cachedMeta._priizmo_cached_summary || '' );
		var summary = summaryState[ 0 ];
		var setSummary = summaryState[ 1 ];

		var faqState = useState( parseFaqMeta( cachedMeta._priizmo_cached_faq_data ) );
		var faqItems = faqState[ 0 ];
		var setFaqItems = faqState[ 1 ];

		var summaryBusyState = useState( false );
		var isGeneratingSummary = summaryBusyState[ 0 ];
		var setIsGeneratingSummary = summaryBusyState[ 1 ];

		var faqBusyState = useState( false );
		var isGeneratingFaq = faqBusyState[ 0 ];
		var setIsGeneratingFaq = faqBusyState[ 1 ];

		/**
		 * Parses the JSON-encoded FAQ meta value into an array, tolerating
		 * empty/invalid values.
		 *
		 * @param {string} raw Raw JSON string from post meta.
		 * @return {Array} Parsed FAQ items, or an empty array.
		 */
		function parseFaqMeta( raw ) {
			if ( ! raw ) {
				return [];
			}

			try {
				var parsed = JSON.parse( raw );
				return Array.isArray( parsed ) ? parsed : [];
			} catch ( e ) {
				return [];
			}
		}

		function generateSummary() {
			if ( ! postId || isGeneratingSummary ) {
				return;
			}

			setIsGeneratingSummary( true );

			var content = wp.data.select( 'core/editor' ).getEditedPostContent();

			wp.apiFetch( {
				path: '/priizmo-engine/v1/generate-summary',
				method: 'POST',
				data: {
					post_id: postId,
					content: content,
					force: true,
				},
			} )
				.then( function ( response ) {
					setSummary( response.summary );
					setIsGeneratingSummary( false );
					createNotice(
						'success',
						__( 'AI summary generated and cached.', 'priizmo-ai-summary-faq-schema' ),
						{ type: 'snackbar', isDismissible: true }
					);
				} )
				.catch( function ( error ) {
					setIsGeneratingSummary( false );
					createNotice(
						'error',
						error && error.message
							? error.message
							: __( 'Failed to generate the AI summary.', 'priizmo-ai-summary-faq-schema' ),
						{ type: 'snackbar', isDismissible: true }
					);
				} );
		}

		function generateFaq() {
			if ( ! postId || isGeneratingFaq ) {
				return;
			}

			setIsGeneratingFaq( true );

			var content = wp.data.select( 'core/editor' ).getEditedPostContent();

			wp.apiFetch( {
				path: '/priizmo-engine/v1/generate-faq',
				method: 'POST',
				data: {
					post_id: postId,
					content: content,
					force: true,
				},
			} )
				.then( function ( response ) {
					setFaqItems( Array.isArray( response.faq ) ? response.faq : [] );
					setIsGeneratingFaq( false );
					createNotice(
						'success',
						__( 'AI FAQs generated and cached.', 'priizmo-ai-summary-faq-schema' ),
						{ type: 'snackbar', isDismissible: true }
					);
				} )
				.catch( function ( error ) {
					setIsGeneratingFaq( false );
					createNotice(
						'error',
						error && error.message
							? error.message
							: __( 'Failed to generate AI FAQs.', 'priizmo-ai-summary-faq-schema' ),
						{ type: 'snackbar', isDismissible: true }
					);
				} );
		}

		return el(
			PluginDocumentSettingPanel,
			{
				name: 'priizmo-engine-controls',
				title: __( 'AEO Controls', 'priizmo-ai-summary-faq-schema' ),
				className: 'priizmo-engine-controls-panel',
			},
			// --- Summary controls ---------------------------------------
			el(
				'p',
				{},
				__(
					'Generate an AI-powered TL;DR summary optimized for AI search engines like ChatGPT and Perplexity.',
					'priizmo-ai-summary-faq-schema'
				)
			),
			el(
				Button,
				{
					isPrimary: true,
					isBusy: isGeneratingSummary,
					disabled: isGeneratingSummary,
					onClick: generateSummary,
				},
				isGeneratingSummary
					? __( 'Generating…', 'priizmo-ai-summary-faq-schema' )
					: __( 'Generate AI Summary', 'priizmo-ai-summary-faq-schema' )
			),
			summary
				? el(
						'div',
						{ className: 'priizmo-engine-controls-preview' },
						el( 'strong', {}, __( 'Cached summary:', 'priizmo-ai-summary-faq-schema' ) ),
						el( 'p', {}, summary )
				  )
				: el(
						'p',
						{ className: 'priizmo-engine-controls-empty' },
						__( 'No summary has been generated yet.', 'priizmo-ai-summary-faq-schema' )
				  ),
			el(
				'p',
				{ className: 'priizmo-engine-controls-hint' },
				__( 'Display it with the ', 'priizmo-ai-summary-faq-schema' ),
				el( 'code', {}, '[priizmo_summary]' ),
				__(
					' shortcode, or choose an automatic placement under Settings > Priizmo AI Summary & FAQ Schema.',
					'priizmo-ai-summary-faq-schema'
				)
			),
			el( 'hr', { className: 'priizmo-engine-controls-divider' } ),
			// --- FAQ controls --------------------------------------------
			el(
				'p',
				{},
				__(
					'Generate AI-powered FAQs with structured FAQPage schema, so AI search engines can surface direct answers from this post.',
					'priizmo-ai-summary-faq-schema'
				)
			),
			el(
				Button,
				{
					isSecondary: true,
					isBusy: isGeneratingFaq,
					disabled: isGeneratingFaq,
					onClick: generateFaq,
				},
				isGeneratingFaq
					? __( 'Generating…', 'priizmo-ai-summary-faq-schema' )
					: __( 'Generate AI FAQs', 'priizmo-ai-summary-faq-schema' )
			),
			faqItems && faqItems.length
				? el(
						'ul',
						{ className: 'priizmo-engine-controls-faq-preview' },
						faqItems.map( function ( item, index ) {
							return el(
								'li',
								{ key: index },
								el( 'strong', {}, item.question ),
								el( 'p', {}, item.answer )
							);
						} )
				  )
				: el(
						'p',
						{ className: 'priizmo-engine-controls-empty' },
						__( 'No FAQs have been generated yet.', 'priizmo-ai-summary-faq-schema' )
				  ),
			el(
				'p',
				{ className: 'priizmo-engine-controls-hint' },
				__( 'Appears automatically at the end of the post, or place it manually with the ', 'priizmo-ai-summary-faq-schema' ),
				el( 'code', {}, '[priizmo_faq]' ),
				__( ' shortcode.', 'priizmo-ai-summary-faq-schema' )
			)
		);
	}

	registerPlugin( 'priizmo-engine-controls', {
		render: AEOControlsPanel,
		icon: 'lightbulb',
	} );
} )( window.wp );
