<?php
/**
 * Block registration.
 *
 * @package Glyphwell
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Registers the equation block when its built metadata is available.
 */
function glyphwell_register_blocks(): void {
	$block_path = GLYPHWELL_PLUGIN_DIR . 'build/blocks/equation';

	if ( ! file_exists( $block_path . '/block.json' ) ) {
		return;
	}

	$block_type = register_block_type_from_metadata( $block_path );

	if ( ! $block_type instanceof WP_Block_Type ) {
		return;
	}

	// Load the JS translations for the block's editor script so its strings are
	// translatable. The editor script handle is generated by WordPress from the
	// block metadata, so resolve it from the registered block type.
	$handles = ! empty( $block_type->editor_script_handles )
		? $block_type->editor_script_handles // WP 6.1+.
		: array_filter( (array) ( $block_type->editor_script ?? array() ) ); // WP 6.0 fallback.

	foreach ( $handles as $handle ) {
		wp_set_script_translations( $handle, 'glyphwell', GLYPHWELL_PLUGIN_DIR . 'languages' );
	}
}

add_action( 'init', 'glyphwell_register_blocks' );
