<?php
/**
 * BW YouTube Embed — front-end render.
 *
 * Reads the YouTube URL from the ACF field configured in plugin settings
 * and outputs a responsive 16:9 iframe embed.
 *
 * @var array    $attributes Block attributes.
 * @var string   $content    Block inner content (empty for dynamic blocks).
 * @var WP_Block $block      Block instance.
 */

$post_id     = get_the_ID();
$field_name  = bw_youtube_get_field_name();
$youtube_url = function_exists( 'get_field' ) ? get_field( $field_name, $post_id ) : '';

$video_id = '';
if ( ! empty( $youtube_url ) && preg_match( '/(?:youtu\.be\/|youtube\.com\/(?:watch\?v=|embed\/|shorts\/))([^\?&"\'>]+)/', $youtube_url, $matches ) ) {
	$video_id = $matches[1];
}

if ( $video_id ) {
	// Render YouTube embed.
	$embed_url = 'https://www.youtube.com/embed/' . rawurlencode( $video_id );
	?>
	<div <?php echo get_block_wrapper_attributes( array( 'class' => 'bw-youtube-block' ) ); ?>>
		<div class="bw-youtube-block__inner">
			<iframe
				src="<?php echo esc_url( $embed_url ); ?>"
				title="YouTube video player"
				frameborder="0"
				allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
				allowfullscreen
				loading="lazy"
			></iframe>
		</div>
	</div>
	<?php
} elseif ( has_post_thumbnail( $post_id ) ) {
	// No video — fall back to featured image.
	?>
	<div <?php echo get_block_wrapper_attributes( array( 'class' => 'bw-youtube-block bw-youtube-block--fallback-image' ) ); ?>>
		<div class="bw-youtube-block__inner">
			<?php echo get_the_post_thumbnail( $post_id, 'large', array( 'class' => 'bw-youtube-block__featured-img' ) ); ?>
		</div>
	</div>
	<?php
}
