<?php
/**
 * BW Dev — YouTube block. Server-side render.
 *
 * Reads the YouTube URL from the ACF field configured on this block (or the
 * global default from Settings → BW Dev → YouTube Block) and emits a
 * responsive 16:9 iframe. Falls back to the post's featured image if no URL
 * is available — useful for Kadence Query Loop layouts where every card
 * gets a slot.
 *
 * @var array    $attributes
 * @var string   $content
 * @var WP_Block $block
 */

defined( 'ABSPATH' ) || exit;

$post_id = get_the_ID();

// Per-block attribute wins; fall back to the global setting.
$field_name = '';
if ( isset( $attributes['acfField'] ) && '' !== trim( (string) $attributes['acfField'] ) ) {
	$field_name = trim( (string) $attributes['acfField'] );
} else {
	$field_name = BW_Dev_Module_Youtube::get_default_field_name();
}

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

$video_id = BW_Dev_Module_Youtube::extract_video_id( (string) $youtube_url );

if ( $video_id ) {
	$embed_url = 'https://www.youtube.com/embed/' . rawurlencode( $video_id );
	?>
	<div <?php echo wp_kses_data( get_block_wrapper_attributes( array( 'class' => 'bw-dev-youtube-block' ) ) ); ?>>
		<div class="bw-dev-youtube-block__inner">
			<iframe
				src="<?php echo esc_url( $embed_url ); ?>"
				title="<?php echo esc_attr__( 'YouTube video player', 'bw-dev' ); ?>"
				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 ) ) {
	?>
	<div <?php echo wp_kses_data( get_block_wrapper_attributes( array( 'class' => 'bw-dev-youtube-block bw-dev-youtube-block--fallback-image' ) ) ); ?>>
		<div class="bw-dev-youtube-block__inner">
			<?php echo get_the_post_thumbnail( $post_id, 'large', array( 'class' => 'bw-dev-youtube-block__featured-img' ) ); ?>
		</div>
	</div>
	<?php
}
