<?php
/**
 * @package snow-monkey-blocks
 * @author inc2734
 * @license GPL-2.0+
 */

use Snow_Monkey\Plugin\Blocks;

register_block_type(
	__DIR__
);

wp_enqueue_block_style(
	'snow-monkey-blocks/section-break-the-grid',
	array(
		'handle' => generate_block_asset_handle( 'snow-monkey-blocks/section-break-the-grid', 'style' ),
		'src'    => SNOW_MONKEY_BLOCKS_DIR_URL . '/dist/blocks/section-break-the-grid/style-index.css',
		'deps'   => array( generate_block_asset_handle( 'snow-monkey-blocks/section', 'style' ) ),
		'ver'    => filemtime( __DIR__ . '/style-index.css' ),
		'file'   => __DIR__ . '/style-index.css',
	)
);

/**
 * excerpt_allowed_blocks
 */
add_filter(
	'excerpt_allowed_blocks',
	function ( $allowed_blocks ) {
		return array_merge(
			$allowed_blocks,
			array(
				'snow-monkey-blocks/section-break-the-grid',
			)
		);
	}
);

/**
 * In the case of numerical values, "px" is sometimes auto-completed, so it should be removed.
 */
add_filter(
	'render_block_snow-monkey-blocks/section-break-the-grid',
	function ( $block_content ) {
		$block_content = preg_replace(
			'|(--smb-section-break-the-grid--mask-opacity:\d+(?:\.\d+)?)px|',
			'$1',
			$block_content
		);
		return $block_content;
	}
);

add_filter(
	'render_block_snow-monkey-blocks/section-break-the-grid',
	function ( $content ) {
		$p1 = new WP_HTML_Tag_Processor( $content );
		$p1->next_tag( array( 'class_name' => 'is-layout-constrained' ) );
		$p1_class = $p1->get_attribute( 'class' );

		$p2 = new WP_HTML_Tag_Processor( $content );
		$p2->next_tag( array( 'class_name' => 'smb-section__body' ) );
		$p2_class = $p2->get_attribute( 'class' );

		if ( $p1_class === $p2_class ) {
			return $content;
		}

		$p1->remove_class( 'is-layout-constrained' );
		$p1->remove_class( 'wp-block-section-break-the-grid-is-layout-constrained' );
		$p1->next_tag( array( 'class_name' => 'smb-section__body' ) );
		$p1->add_class( 'is-layout-constrained' );
		$p1->add_class( 'wp-block-section-break-the-grid-is-layout-constrained' );
		return $p1->get_updated_html();
	}
);
