<?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';
}

// Accept hex (#xxx / #xxxxxx / #xxxxxxxx), rgb(a)(), hsl(a)(), and `var(--name)`
// references — the last is what Kadence theme palettes store via the editor's
// ColorPalette (e.g. `var(--global-palette14)`). `sanitize_hex_color()` alone
// rejected those, so picked theme-palette colors silently lost their inline
// style and the frontend fell back to inherited theme text color.
$sanitize_color = static function( string $raw ): string {
	$raw = trim( $raw );
	if ( '' === $raw ) {
		return '';
	}
	if ( false !== strpbrk( $raw, "<>\"';\\" ) ) {
		return '';
	}
	$hex = sanitize_hex_color( $raw );
	if ( is_string( $hex ) && '' !== $hex ) {
		return $hex;
	}
	// 8-digit hex (#rrggbbaa, CSS Color Level 4) — sanitize_hex_color rejects.
	if ( preg_match( '/^#[a-fA-F0-9]{8}$/', $raw ) ) {
		return $raw;
	}
	if ( preg_match( '/^var\(\s*--[a-zA-Z0-9_-]+\s*\)$/', $raw ) ) {
		return $raw;
	}
	if ( preg_match( '/^(?:rgb|rgba|hsl|hsla)\(\s*[\d.,\s%\/-]+\)$/i', $raw ) ) {
		return $raw;
	}
	return '';
};
$color_clean = $sanitize_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.
