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

const CodeMirrorEditor = ( {value, onChange, isActive} ) => {
	const textareaRef = useRef( null );
	const editorRef = useRef( null );
	const lastPushedValue = useRef( value );

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

	useEffect( () => {
		// Initialisiere den Editor nur, wenn er noch nicht existiert
		if ( textareaRef.current && !editorRef.current ) {
			const editor = wp.codeEditor.initialize( textareaRef.current, { /* ... settings ... */} );
			editorRef.current = editor.codemirror;
			editorRef.current.setValue( value || '' );

			editorRef.current.on( 'change', ( instance ) => {
				const content = instance.getValue();
				lastPushedValue.current = content; // Änderung als "unsere" markieren
				onChangeRef.current( content );
			} );
		}
	}, [] ); // Läuft nur einmal

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

	// NEU: Aktualisiere die Ansicht, wenn der Tab aktiv wird
	useEffect( () => {
		if ( isActive && editorRef.current ) {
			editorRef.current.refresh();
		}
	}, [isActive] );

	return <textarea ref={textareaRef}></textarea>;
};
export default CodeMirrorEditor;
