import { useEffect, useRef } from '@wordpress/element';
import { BaseControl } from '@wordpress/components';

/**
 * Visual (WYSIWYG) editor field.
 *
 * Uses WordPress's bundled editor (TinyMCE via window.wp.editor) when available
 * — the host enqueues it with wp_enqueue_editor(). Falls back to a plain
 * textarea when the editor isn't present, so the field always works.
 *
 * Generic: knows nothing about the consuming domain; stores an HTML string.
 */
let uid = 0;

const RichTextField = ( { field, value, onChange } ) => {
	const idRef = useRef( `cliqthemes-ui-rte-${ ++uid }` );
	const onChangeRef = useRef( onChange );
	onChangeRef.current = onChange;

	useEffect( () => {
		const id = idRef.current;
		const wpEditor = ( typeof window !== 'undefined' && window.wp ) ? window.wp.editor : null;

		if ( ! wpEditor || typeof wpEditor.initialize !== 'function' ) {
			return undefined; // textarea fallback stays interactive
		}

		wpEditor.initialize( id, {
			mediaButtons: false,
			quicktags: true,
			tinymce: {
				wpautop: true,
				toolbar1:
					'formatselect,bold,italic,bullist,numlist,blockquote,alignleft,aligncenter,alignright,link,unlink,undo,redo',
				setup( editor ) {
					const sync = () => onChangeRef.current( editor.getContent() );
					editor.on( 'change keyup input SetContent Undo Redo', sync );
				},
			},
		} );

		return () => {
			if ( typeof wpEditor.remove === 'function' ) {
				wpEditor.remove( id );
			}
		};
		// eslint-disable-next-line react-hooks/exhaustive-deps
	}, [] );

	return (
		<BaseControl
			__nextHasNoMarginBottom
			label={ field.label }
			help={ field.help }
			id={ idRef.current }
		>
			<textarea
				id={ idRef.current }
				className="cliqthemes-ui-richtext"
				rows={ field.rows ?? 8 }
				defaultValue={ value ?? '' }
				onChange={ ( event ) => onChange( event.target.value ) }
			/>
		</BaseControl>
	);
};

export default RichTextField;
