<?php
/**
 * BW Dev — Subtitle block. Server-side render.
 *
 * @var array    $attributes
 * @var string   $content
 * @var WP_Block $block
 */

defined( 'ABSPATH' ) || exit;

$text  = isset( $attributes['text'] )  ? trim( (string) $attributes['text'] )  : '';
$align = isset( $attributes['align'] ) ? strtolower( (string) $attributes['align'] ) : 'left';
$color = isset( $attributes['color'] ) ? trim( (string) $attributes['color'] ) : '';
$url   = isset( $attributes['url'] )   ? trim( (string) $attributes['url'] )   : '';
$link_target = isset( $attributes['linkTarget'] ) ? (string) $attributes['linkTarget'] : '_self';

if ( '' === $text ) {
	return;
}

if ( ! in_array( $align, array( 'left', 'center', 'right' ), true ) ) {
	$align = 'left';
}
if ( ! in_array( $link_target, array( '_self', '_blank' ), true ) ) {
	$link_target = '_self';
}

// Validate color as hex (#abc or #aabbcc); anything else falls back to theme inheritance.
$color_clean = sanitize_hex_color( $color );
$style_attr  = $color_clean ? ' style="color:' . esc_attr( $color_clean ) . ';"' : '';

$wrapper_attrs = get_block_wrapper_attributes(
	array( 'class' => 'bw-dev-subtitle-wrapper bw-dev-subtitle-wrapper--' . $align )
);

if ( '' !== $url ) {
	$rel = '_blank' === $link_target ? ' rel="noopener noreferrer"' : '';
	$inner = sprintf(
		'<a class="bw-dev-subtitle" href="%s" target="%s"%s%s>%s</a>',
		esc_url( $url ),
		esc_attr( $link_target ),
		$rel,
		$style_attr,
		esc_html( $text )
	);
} else {
	$inner = sprintf(
		'<span class="bw-dev-subtitle"%s>%s</span>',
		$style_attr,
		esc_html( $text )
	);
}

printf( '<div %s>%s</div>', wp_kses_data( $wrapper_attrs ), $inner ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- inner is already escaped above.
