<?php
/**
 * Block editor integration.
 *
 * @package MenuVerse
 */

namespace WPXero\MenuVerse\Admin;

use WPXero\MenuVerse\Plugin;

defined( 'ABSPATH' ) || exit;

/**
 * Registers the shared editor bundle every MenuVerse block declares.
 *
 * One bundle serves every block, so adding a module does not add an editor
 * request.
 */
final class Editor {

	/**
	 * Script handle declared by each block.json.
	 *
	 * @var string
	 */
	const HANDLE = 'menuverse-editor';

	/**
	 * Registers hooks.
	 *
	 * @return void
	 */
	public function boot() {
		// Priority 5 so the handle exists before modules register their blocks.
		add_action( 'init', array( $this, 'register_assets' ), 5 );
	}

	/**
	 * Registers the editor script and style.
	 *
	 * @return void
	 */
	public function register_assets() {
		$assets = Plugin::instance()->assets();
		$script = $assets->url( 'editor.js' );

		if ( ! $script ) {
			return;
		}

		$meta = $assets->script_meta( 'editor' );

		wp_register_script( self::HANDLE, $script, $meta['dependencies'], $meta['version'], true );
		wp_set_script_translations( self::HANDLE, 'menuverse', MENUVERSE_PATH . 'languages' );

		$style = $assets->url( 'editor.css' );

		if ( $style ) {
			// Declared as editorStyle on each block rather than enqueued on
			// enqueue_block_editor_assets: the canvas is an iframe, and only
			// block assets are carried into it.
			wp_register_style( self::HANDLE, $style, array(), $assets->version( 'editor.css' ) );
			wp_style_add_data( self::HANDLE, 'rtl', 'replace' );
		}
	}
}
