<?php
/**
 * Brentwood Video Text — front-end render.
 *
 * Helper functions live in render-helpers.php. require_once guarantees they are
 * declared exactly once even though render.php is included per block instance.
 *
 * @var array    $attributes Block attributes.
 * @var string   $content    Inner content (unused — dynamic block).
 * @var WP_Block $block      Block instance.
 */

defined( 'ABSPATH' ) || exit;

require_once __DIR__ . '/render-helpers.php';

// ── sanitize attributes ───────────────────────────────────────────────────

$layout               = sanitize_text_field( $attributes['layout']               ?? 'layout-1' );
$video_source         = sanitize_text_field( $attributes['videoSource']           ?? 'youtube' );
$youtube_url          = esc_url_raw( $attributes['youtubeUrl']                    ?? '' );
$video_file_url       = esc_url_raw( $attributes['videoFileUrl']                  ?? '' );
$thumb_url            = esc_url_raw( $attributes['customThumbnailUrl']            ?? '' );
$image_caption        = sanitize_text_field( $attributes['imageCaption']           ?? '' );
$heading_text         = wp_kses_post( $attributes['headingText']                  ?? '' );
$body_content         = wp_kses_post( $attributes['bodyContent']                  ?? '' );
$text_color           = bw_vt_sanitize_color( $attributes['textColor']              ?? '' );
$heading_color        = bw_vt_sanitize_color( $attributes['headingColor']           ?? '' );
$text_bg_color        = bw_vt_sanitize_color( $attributes['textBgColor']            ?? '' );
$heading_font_size    = sanitize_text_field( $attributes['headingFontSize']       ?? '' );
$heading_font_weight  = sanitize_text_field( $attributes['headingFontWeight']     ?? 'normal' );
$heading_font_style   = sanitize_text_field( $attributes['headingFontStyle']      ?? 'normal' );
$font_size            = sanitize_text_field( $attributes['fontSize']              ?? '' );
$font_weight          = sanitize_text_field( $attributes['fontWeight']            ?? 'normal' );
$font_style_val       = sanitize_text_field( $attributes['fontStyle']             ?? 'normal' );
$play_btn_color       = bw_vt_sanitize_color( $attributes['playButtonColor']        ?? '' ) ?: '#cc0000';

$show_heading_icon    = ! empty( $attributes['showHeadingVideoIcon'] );

// Number badge — top-left of the media, like the Brentwood Images cards. Only
// offered for media (uploaded file) videos; off by default.
$video_number      = sanitize_text_field( $attributes['videoNumber'] ?? '' );
$show_video_number = ! empty( $attributes['showVideoNumber'] )
	&& 'file' === $video_source
	&& '' !== $video_number;

// Hide the title/tagline without losing the stored text (toggle in the editor).
$show_heading = ! isset( $attributes['showHeading'] ) || ! empty( $attributes['showHeading'] );
if ( ! $show_heading ) {
	$heading_text = '';
}
$show_play_link       = ! empty( $attributes['showPlayLink'] );
$play_link_text       = sanitize_text_field( $attributes['playLinkText']          ?? 'Play Video' ) ?: 'Play Video';
$play_link_color      = bw_vt_sanitize_color( $attributes['playLinkColor']          ?? '' ) ?: '#cc0000';
$show_text_dash       = ! empty( $attributes['showTextDash'] );
$show_bottom_border   = ! empty( $attributes['showTextBottomBorder'] );
$bottom_border_color  = bw_vt_sanitize_color( $attributes['textBottomBorderColor']  ?? '' ) ?: '#cc0000';

$show_cta   = ! empty( $attributes['showCta'] );
$cta_text   = sanitize_text_field( $attributes['ctaText']  ?? 'Learn More' ) ?: 'Learn More';
$cta_url    = esc_url_raw( $attributes['ctaUrl']   ?? '' );
$cta_color  = bw_vt_sanitize_color( $attributes['ctaColor']  ?? '' ) ?: '#cc0000';
$cta_new_tab = ! empty( $attributes['ctaNewTab'] );

// Whitelist layout and heading tag.
if ( ! in_array( $layout, array( 'layout-1', 'layout-2', 'layout-3', 'layout-4', 'layout-5', 'layout-6', 'layout-7' ), true ) ) {
	$layout = 'layout-1';
}

// ── extract YouTube video ID ──────────────────────────────────────────────

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

// ── resolve poster / thumbnail ────────────────────────────────────────────
// A custom poster image (customThumbnailUrl), when set, takes precedence for
// BOTH sources and acts as a cover over the video until it is played. YouTube
// falls back to its own auto-generated thumbnail when no poster is provided.
$has_custom_poster = ( '' !== $thumb_url );

if ( $has_custom_poster ) {
	$thumbnail_src = $thumb_url;
} elseif ( 'youtube' === $video_source && $video_id ) {
	$thumbnail_src = 'https://img.youtube.com/vi/' . rawurlencode( $video_id ) . '/maxresdefault.jpg';
} else {
	$thumbnail_src = '';
}

$has_video = ( 'youtube' === $video_source && $video_id )
          || ( 'file' === $video_source && $video_file_url );

// Poster focal point → background-position on the poster image. Stored as two
// 0–1 floats (default 0.5 = centred); clamped and expressed as percentages.
$focal_x = isset( $attributes['posterFocalX'] ) ? (float) $attributes['posterFocalX'] : 0.5;
$focal_y = isset( $attributes['posterFocalY'] ) ? (float) $attributes['posterFocalY'] : 0.5;
$focal_x = max( 0.0, min( 1.0, $focal_x ) );
$focal_y = max( 0.0, min( 1.0, $focal_y ) );
// Only emit a non-default position (keeps the CSS `center` default otherwise).
$poster_pos = ( 0.5 === $focal_x && 0.5 === $focal_y )
	? ''
	: round( $focal_x * 100, 2 ) . '% ' . round( $focal_y * 100, 2 ) . '%';

// ── inline styles ─────────────────────────────────────────────────────────

$text_col_css = array();
if ( $text_bg_color )   $text_col_css[] = 'background-color:' . $text_bg_color;
if ( $text_color )      $text_col_css[] = 'color:' . $text_color;
if ( $show_bottom_border ) $text_col_css[] = 'border-bottom:4px solid ' . $bottom_border_color;

$heading_css = array();
if ( $heading_color )                                           $heading_css[] = 'color:' . $heading_color;
if ( $heading_font_size )                                       $heading_css[] = 'font-size:' . $heading_font_size;
if ( $heading_font_weight && 'normal' !== $heading_font_weight ) $heading_css[] = 'font-weight:' . $heading_font_weight;
if ( 'italic' === $heading_font_style )                        $heading_css[] = 'font-style:italic';

$body_css = array();
if ( $font_size )                                $body_css[] = 'font-size:' . $font_size;
if ( $font_weight && 'normal' !== $font_weight ) $body_css[] = 'font-weight:' . $font_weight;
if ( 'italic' === $font_style_val )             $body_css[] = 'font-style:italic';

// ── assemble ──────────────────────────────────────────────────────────────

$video_first = in_array( $layout, array( 'layout-1', 'layout-4', 'layout-5', 'layout-7' ), true );

// Layout 3 reverse option: put the media column on the left and the text column
// on the right (default layout-3 is text-left / media-right). Scoped to layout-3
// so the toggle never silently flips another layout it was left enabled on.
if ( ! empty( $attributes['reverse'] ) && 'layout-3' === $layout ) {
	$video_first = true;
}

// Layout 6: full-width single video, no text column. YouTube shows a banner
// thumbnail that expands to the video on click.
$video_only = ( 'layout-6' === $layout );

// YouTube renders as a deferred poster banner (iframe built on click) when it's
// layout 6 OR a custom poster image is set — so the poster covers the video
// until played. Without a poster, layouts 1–5 keep the immediate-iframe embed.
$yt_deferred = $video_only || $has_custom_poster;

$vcol = bw_vt_render_video_col(
	$has_video, $thumbnail_src, $play_btn_color,
	$video_source, $video_id, $video_file_url,
	$yt_deferred, // YouTube click-to-play poster banner (layout 6 or custom poster).
	$video_only ? $image_caption : '', // Caption overlay — layout 6 only.
	$show_video_number ? $video_number : '', // Number badge — media (file) videos only.
	$poster_pos // Poster focal point as a CSS background-position ('' = centre).
);
// "Title as H1" is a layout-1-only option: render the tag-line as a real <h1>.
$title_as_h1 = ! empty( $attributes['titleAsH1'] ) && 'layout-1' === $layout;

$tcol = bw_vt_render_text_col(
	$text_col_css, $heading_text, $heading_css,
	$body_css, $body_content, $show_heading_icon, $show_play_link,
	$play_link_text, $play_link_color, $show_text_dash,
	$show_cta, $cta_text, $cta_url, $cta_color, $cta_new_tab, $title_as_h1
);

$block_class = 'bw-video-text bw-video-text--' . esc_attr( $layout );

// Layout 6 with a MEDIA (uploaded file) video behaves like the live site's
// full-layout media video: a fixed-height 16:9 full-width video that autoplays
// (muted + looping — see frontend.js), NOT the YouTube banner→click-to-expand.
// The flag class scopes both the fixed-height CSS and the JS autoplay to this
// case, so a layout-6 YouTube video keeps its banner behaviour.
if ( $video_only && 'file' === $video_source && $video_file_url ) {
	$block_class .= ' bw-vt-l6-media';
}
?>
<div <?php echo get_block_wrapper_attributes( array( 'class' => $block_class ) ); ?>>
	<div class="bw-vt-row">
		<?php
		if ( $video_only ) {
			echo $vcol; // phpcs:ignore WordPress.Security.EscapeOutput -- escaped inside helper
		} elseif ( $video_first ) {
			echo $vcol; // phpcs:ignore WordPress.Security.EscapeOutput -- escaped inside helper
			echo $tcol; // phpcs:ignore WordPress.Security.EscapeOutput -- escaped inside helper
		} else {
			echo $tcol; // phpcs:ignore WordPress.Security.EscapeOutput -- escaped inside helper
			echo $vcol; // phpcs:ignore WordPress.Security.EscapeOutput -- escaped inside helper
		}
		?>
	</div>
</div>
