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

const ClassicEditor = ({ value, onChange, isActive }) => {
	const textareaId = useRef(`adpresso-classic-editor-${Math.random().toString(36).substring(2, 9)}`);
	const editorRef = useRef(null);
	const lastPushedValue = useRef(value);

	const onChangeRef = useRef(onChange);
	useEffect(() => {
		onChangeRef.current = onChange;
	}, [onChange]);

	useEffect(() => {
		if (!window.wp || !window.wp.editor || !window.wp.editor.initialize) {
			console.error('Classic Editor cannot be initialized: wp.editor is not available.');
			return;
		}

		wp.editor.initialize(textareaId.current, {
			tinymce: {
				wpautop: true,
				height: 350,
				setup: (editor) => {
					editorRef.current = editor;

					editor.on('init', () => {
						editor.setContent(value || '');
					});

					editor.on('change keyup', () => {
						const content = editor.getContent();
						lastPushedValue.current = content;
						onChangeRef.current(content);
					});
				},
			},
			quicktags: true,
			mediaButtons: true,
		});

		// Unmount
		return () => {
			if (editorRef.current) {
				wp.editor.remove(textareaId.current);
				editorRef.current = null;
			}
		};
	}, []);

	useEffect(() => {
		if (editorRef.current && isActive && value !== lastPushedValue.current) {
			editorRef.current.setContent(value || '');
			lastPushedValue.current = value;
		}
	}, [value, isActive]);

	return (
		<textarea id={textareaId.current} className="adpresso-classic-editor-textarea"></textarea>
	);
};

export default ClassicEditor;
