<?php
/**
 * Vehicle Media Slider block — gallery + video hero.
 *
 * @package ThemeREX\AutoDealer
 */

declare(strict_types=1);

namespace ThemeREX\AutoDealer\Blocks;

use ThemeREX\AutoDealer\Frontend\MediaSliderRenderer;
use ThemeREX\AutoDealer\Frontend\TemplateLoader;
use ThemeREX\AutoDealer\PostTypes\VehiclePostType;

class MediaSliderBlock extends AbstractBlock {

	protected string $slug = 'media-slider';

	public function render( array $attributes, string $content = '', $block = null ): string {
		$post_id = $this->resolveVehicleId( $attributes, $block );
		if ( $post_id <= 0 || VehiclePostType::POST_TYPE !== get_post_type( $post_id ) ) {
			return '';
		}

		$class = 'wp-block-trx-auto-dealer-media-slider';
		if ( ! empty( $attributes['className'] ) ) {
			$class .= ' ' . sanitize_html_class( (string) $attributes['className'] );
		}

		$loop = ! array_key_exists( 'loop', $attributes ) || ! empty( $attributes['loop'] );

		return self::capture(
			static function () use ( $post_id, $loop, $class ): void {
				echo '<div class="' . esc_attr( $class ) . '">';
				TemplateLoader::getTemplatePart(
					'media-slider',
					array(
						'slides' => MediaSliderRenderer::buildSlides( $post_id ),
						'loop'   => $loop,
					)
				);
				echo '</div>';
			}
		);
	}

	/**
	 * @param array<string, mixed> $attributes
	 * @param mixed                $block
	 */
	private function resolveVehicleId( array $attributes, $block ): int {
		$id = (int) ( $attributes['vehicleId'] ?? 0 );
		if ( $id > 0 ) {
			return $id;
		}
		if ( $block && isset( $block->context['postId'] ) ) {
			return (int) $block->context['postId'];
		}
		return (int) ( get_the_ID() ?: 0 );
	}
}
