<?php

namespace Brandy\BlocksOverride\Gutenberg;

use Brandy\Traits\SingletonTrait;

/**
 * Normalize core/image border-radius: move from <img> to <figure>.
 * Ensures overlays, shadows, and borders clip to rounded corners.
 */
class CoreImage {
	use SingletonTrait;

	protected function __construct() {
		$allowed_blocks = array( 'core/image', 'core/post-featured-image' );
		foreach ( $allowed_blocks as $block ) {
			add_filter( "render_block_{$block}", array( $this, 'normalize_border_radius' ), 10, 3 );
		}
	}

	/**
	 * Move border-radius from <img> to <figure> so child elements inherit it.
	 * Some themes (e.g. Twenty Twenty-Five) only set border-radius on <img>.
	 */
	public function normalize_border_radius( $html, $block, $instance ) {
		$img_tag = new \WP_HTML_Tag_Processor( $html );
		if ( ! $img_tag->next_tag( 'img' ) ) {
			return $html;
		}

		$img_style = $img_tag->get_attribute( 'style' ) ?? '';
		if ( empty( $img_style ) || strpos( $img_style, 'border' ) === false ) {
			return $html;
		}

		// Extract all border-radius variants (shorthand + individual corners)
		preg_match_all(
			'/border(?:-top-left|-top-right|-bottom-left|-bottom-right)?-radius\s*:\s*[^;]+/i',
			$img_style,
			$matches
		);

		if ( empty( $matches[0] ) ) {
			return $html;
		}

		$radius_props = array_map( 'trim', $matches[0] );

		// Remove border-radius from <img> — it will inherit from <figure>
		// $cleaned = preg_replace(
		// 	'/border(?:-top-left|-top-right|-bottom-left|-bottom-right)?-radius\s*:\s*[^;]+;?\s*/i',
		// 	'',
		// 	$img_style
		// );
		// if ( ! empty( $cleaned ) ) {
		// 	$img_tag->set_attribute( 'style', trim( $cleaned, '; ' ) ?: null );
		// } else {
		// 	$img_tag->remove_attribute( 'style' );
		// }
		// $html = $img_tag->get_updated_html();

		// Apply border-radius to <figure> (first tag)
		$figure_tag = new \WP_HTML_Tag_Processor( $html );
		if ( ! $figure_tag->next_tag() ) {
			return $html;
		}

		$existing_style = $figure_tag->get_attribute( 'style' ) ?? '';
		// Skip if figure already has border-radius
		if ( strpos( $existing_style, 'border-radius' ) !== false ) {
			return $html;
		}

		if ( ! empty( $existing_style ) && ! str_ends_with( $existing_style, ';' ) ) {
			$existing_style .= ';';
		}
		$figure_tag->set_attribute( 'style', $existing_style . esc_attr( implode( ';', $radius_props ) ) );

		return $figure_tag->get_updated_html();
	}
}

CoreImage::get_instance();
