<?php
/**
 * Background / featured image for a hero article.
 *
 * @package Kutby
 * @since   2.8.0
 */

declare(strict_types=1);

namespace Kutby\Hero\Components;

use Kutby\Hero\Contracts\HeroComponentInterface;
use Kutby\Hero\Support\HeroContext;
use WP_Post;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Class BackgroundImage
 */
final class BackgroundImage implements HeroComponentInterface {

	/**
	 * {@inheritdoc}
	 */
	public static function render( HeroContext $ctx, array $args = array() ): void {
		$post = $args['post'] ?? null;
		if ( ! $post instanceof WP_Post || ! has_post_thumbnail( $post ) ) {
			return;
		}

		$size  = isset( $args['size'] ) ? (string) $args['size'] : 'large';
		$lazy  = ! empty( $args['lazy'] );
		$class = isset( $args['class'] ) ? (string) $args['class'] : 'kutby-hero-media';
		$ratio = $ctx->image_ratio();

		$attr = array(
			'class' => 'kutby-hero-media__img',
			'alt'   => the_title_attribute(
				array(
					'echo' => false,
					'post' => $post,
				)
			),
		);

		if ( $lazy ) {
			$attr['loading']  = 'lazy';
			$attr['decoding'] = 'async';
		} else {
			$attr['fetchpriority'] = 'high';
			$attr['decoding']      = 'async';
		}
		?>
		<div class="<?php echo esc_attr( $class . ' kutby-hero-media--' . $ratio ); ?>">
			<?php echo get_the_post_thumbnail( $post, $size, $attr ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
			<?php
			if ( $ctx->bool( 'overlay' ) ) {
				Overlay::render( $ctx, array( 'force' => true ) );
			}
			?>
		</div>
		<?php
	}
}
