/**
 * Default the block editor meta boxes pane to open on Event Genius event screens.
 * Uses core/preferences when available (WP 6.8+ / Gutenberg meta box pane toggle); no-ops safely elsewhere.
 */
( function () {
	if ( typeof wp === 'undefined' || ! wp.data || ! wp.domReady ) {
		return;
	}

	var PREF_SCOPE = 'core/edit-post';
	var PREF_KEY = 'metaBoxesMainIsOpen';
	var MAX_WAIT_MS = 12000;
	var started = Date.now();
	var finished = false;

	function evgeMetaBoxesPaneCanOpen() {
		var selectEditPost = wp.data.select( 'core/edit-post' );
		if ( ! selectEditPost || typeof selectEditPost.hasMetaBoxes !== 'function' ) {
			return false;
		}
		if ( ! selectEditPost.hasMetaBoxes() ) {
			return false;
		}
		var selectEditor = wp.data.select( 'core/editor' );
		if ( ! selectEditor ) {
			return false;
		}
		if ( typeof selectEditor.__unstableIsEditorReady === 'function' ) {
			return selectEditor.__unstableIsEditorReady();
		}
		if ( typeof selectEditor.isReady === 'function' ) {
			return selectEditor.isReady();
		}
		return true;
	}

	function evgeTryOpenMetaBoxesMain() {
		if ( finished ) {
			return true;
		}
		if ( Date.now() - started > MAX_WAIT_MS ) {
			finished = true;
			return true;
		}
		var dispatchPrefs = wp.data.dispatch( 'core/preferences' );
		if ( ! dispatchPrefs || typeof dispatchPrefs.set !== 'function' ) {
			return false;
		}
		if ( ! evgeMetaBoxesPaneCanOpen() ) {
			return false;
		}
		var selectPrefs = wp.data.select( 'core/preferences' );
		if ( selectPrefs && typeof selectPrefs.get === 'function' ) {
			try {
				if ( selectPrefs.get( PREF_SCOPE, PREF_KEY ) === true ) {
					finished = true;
					return true;
				}
			} catch ( e ) {
				// Preference may not exist on older bundles; still attempt set below.
			}
		}
		try {
			dispatchPrefs.set( PREF_SCOPE, PREF_KEY, true );
		} catch ( e ) {
			finished = true;
			return true;
		}
		finished = true;
		return true;
	}

	wp.domReady( function () {
		if ( evgeTryOpenMetaBoxesMain() ) {
			return;
		}
		var unsubscribe = wp.data.subscribe( function () {
			if ( evgeTryOpenMetaBoxesMain() && typeof unsubscribe === 'function' ) {
				unsubscribe();
			}
		} );
	} );
} )();
