<?php
/**
 * Icon Block Markup
 *
 * @package StrategyBlocks
 */

use StrategyBlocks\Utility;
use StrategyBlocks\FontAwesomeSVG;

$id         = ! empty( $attributes['anchor'] ) ? $attributes['anchor'] : '';
$class_name = 'lg-block lg-block__icon';
$class_name .= Utility\get_block_style_classes( $attributes );
$class_name .= Utility\get_native_wp_classes( $attributes );
$class_name .= Utility\get_visibility_classes( $attributes );
$animations = Utility\get_animation_data( $attributes );

$icon_markup = '';
$icon = $attributes['icon'] ?? [];
$display_type = $attributes['iconDisplay'] ?? 'decorative';

if ( 'upload' === $icon['type'] && ! empty( $icon['url'] ) ) {
	$icon_markup = Utility\get_svg_by_url_and_format_svg(
		$icon['url'],
		'icon__svg',
		null,
		null,
		$display_type,
		null,
		$icon['mediaId'] ?? null
	);
} elseif ( 'library' === $icon['type'] && ! empty( $icon['library'] ) && ! empty( $icon['iconSet'] ) ) {
	$fa = new FontAwesomeSVG( STRATEGY_BLOCKS_DIST_PATH . 'font-awesome/svgs' );
	$svg_raw = $fa->get_svg( "{$icon['iconSet']} {$icon['library']}" );

	$icon_markup = preg_replace_callback(
		'/<svg\b([^>]*)>/i',
		function ( $matches ) use ( $display_type, $icon ) {
			$existing_attrs = $matches[1];
			$clean_attrs = preg_replace(
				'/\s*(class|role|focusable|aria-[a-z\-]+)=["\'][^"\']*["\']/i',
				'',
				$existing_attrs
			);
			if ( 'informational' === $display_type ) {
				$label = ! empty( $icon['library'] )
					? ucfirst( str_replace( '-', ' ', $icon['library'] ) )
					: 'Informational icon';
				$svg_attrs = sprintf( ' class="icon__svg" role="img" aria-label="%s"', esc_attr( $label ) );
			} else {
				$svg_attrs = ' class="icon__svg" aria-hidden="true" focusable="false"';
			}
			return '<svg' . $clean_attrs . $svg_attrs . '>';
		},
		$svg_raw,
		1
	);
}

$args = [
	'id' => $id,
	'class_name' => $class_name,
	'display_type' => $display_type,
	'markup' => $icon_markup,
];

do_action( 'lg_block_icon_before', $args ); ?>

<div <?php echo $id ? 'id="' . esc_attr( $id ) . '"' : ''; ?>
	class="<?php echo esc_attr( $class_name ); ?>"
	<?php echo $animations ? 'data-animation="' . esc_attr( $animations ) . '"' : ''; ?>
>
	<?php
	do_action( 'lg_block_icon_before_inner_html', $args );
	if ( $icon_markup ) {
		Utility\sanitize_and_output_svg( $icon_markup, true, $display_type );
	}
	do_action( 'lg_block_icon_after_inner_html', $args );
	?>
</div>

<?php do_action( 'lg_block_icon_after', $args ); ?>
