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); // Hält die TinyMCE-Instanz
	const lastPushedValue = useRef(value);

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

	// Initialisiert den Editor beim Erstellen der Komponente und zerstört ihn beim Entfernen
	useEffect(() => {
		if (!window.wp || !window.wp.editor || !window.wp.editor.initialize) {
			console.error('Classic Editor cannot be initialized: wp.editor is not available.');
			return;
		}

		// Initialisiere den Editor über die WordPress-API
		wp.editor.initialize(textareaId.current, {
			tinymce: {
				wpautop: true,
				height: 350,
				// Wichtig: Der Setup-Callback verbindet React mit TinyMCE
				setup: (editor) => {
					// Speichere die Instanz
					editorRef.current = editor;

					// Setze den initialen Inhalt, wenn der Editor bereit ist
					editor.on('init', () => {
						editor.setContent(value || '');
					});

					// Melde Änderungen an die Eltern-Komponente
					editor.on('change keyup', () => {
						const content = editor.getContent();
						lastPushedValue.current = content;
						onChangeRef.current(content);
					});
				},
			},
			quicktags: true,
			mediaButtons: true,
		});

		// Aufräum-Funktion: Wird beim Unmounten aufgerufen
		return () => {
			if (editorRef.current) {
				wp.editor.remove(textareaId.current);
				editorRef.current = null;
			}
		};
	}, []); // Das leere Array sorgt dafür, dass dieser Effekt nur einmal läuft

	useEffect(() => {
		// Wir überschreiben den Editor nur, wenn:
		// 1. Er aktiv ist
		// 2. Der neue "value" NICHT der ist, den wir gerade selbst getippt haben
		if (editorRef.current && isActive && value !== lastPushedValue.current) {
			editorRef.current.setContent(value || '');
			lastPushedValue.current = value; // Den neuen Stand merken
		}
	}, [value, isActive]);

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

export default ClassicEditor;
