<?php
/**
 * Recently Viewed Vehicles block — JS-hydrated from localStorage.
 *
 * @package ThemeREX\AutoDealer
 */

declare(strict_types=1);

namespace ThemeREX\AutoDealer\Blocks;

use ThemeREX\AutoDealer\Frontend\TemplateLoader;

class RecentlyViewedBlock extends AbstractBlock {

	protected string $slug = 'recently-viewed';

	public function render( array $attributes, string $content = '', $block = null ): string {
		$class = 'wp-block-trx-auto-dealer-recently-viewed';
		if ( ! empty( $attributes['className'] ) ) {
			$class .= ' ' . sanitize_html_class( (string) $attributes['className'] );
		}

		$exclude = 0;
		if ( $block && isset( $block->context['postId'] ) ) {
			$exclude = (int) $block->context['postId'];
		}
		if ( $exclude <= 0 ) {
			$exclude = (int) ( get_the_ID() ?: 0 );
		}

		$limit = max( 1, min( 12, (int) ( $attributes['limit'] ?? 4 ) ) );

		return self::capture(
			static function () use ( $exclude, $limit, $class ): void {
				echo '<div class="' . esc_attr( $class ) . '">';
				TemplateLoader::getTemplatePart(
					'vehicle-recently-viewed',
					array(
						'exclude' => $exclude,
						'limit'   => $limit,
					)
				);
				echo '</div>';
			}
		);
	}
}
