<?php
/**
 * "Featured Carousel" block — Swiper-based carousel of featured listings.
 *
 * Same surface as the Elementor "Featured Carousel" widget. Reuses the
 * vehicle-card template part for each slide so the card markup stays
 * consistent with the grid + archive surfaces. Swiper + the shared
 * featured-carousel.js initialiser are enqueued from render() (both print
 * in the footer, after the block markup); the init config travels in a
 * `data-swiper-config` attribute — no inline <script> (wp.org 2026-07 review).
 *
 * @package ThemeREX\AutoDealer
 */

declare(strict_types=1);

namespace ThemeREX\AutoDealer\Blocks;

use ThemeREX\AutoDealer\Frontend\TemplateLoader;
use ThemeREX\AutoDealer\Search\FilterParams;
use ThemeREX\AutoDealer\Search\VehicleQuery;

class FeaturedCarouselBlock extends AbstractBlock {

	protected string $slug = 'featured-carousel';

	public function render( array $attributes, string $content = '', $block = null ): string {
		$limit           = max( 2, min( 24, (int) ( $attributes['limit'] ?? 8 ) ) );
		$featured_only   = ! empty( $attributes['featuredOnly'] );
		$orderby         = (string) ( $attributes['orderby'] ?? 'date' );
		$slides_per      = max( 1, min( 6, (int) ( $attributes['slidesPerView'] ?? 3 ) ) );
		$space_between   = max( 0, min( 100, (int) ( $attributes['spaceBetween'] ?? 24 ) ) );
		$autoplay        = ! empty( $attributes['autoplay'] );
		$autoplay_delay  = max( 1000, min( 15000, (int) ( $attributes['autoplayDelay'] ?? 4000 ) ) );
		$loop            = ! empty( $attributes['loop'] );
		$show_navigation = ! empty( $attributes['showNavigation'] );
		$show_pagination = ! empty( $attributes['showPagination'] );

		$args = array_filter(
			array(
				'per_page' => $limit,
				'featured' => $featured_only ? 1 : '',
				'orderby'  => $orderby,
			),
			static fn( $v ) => '' !== $v && null !== $v
		);

		$rows = ( new VehicleQuery() )->fetch( FilterParams::fromArray( $args ) );

		if ( empty( $rows ) ) {
			return '';
		}

		$id     = 'trx-ad-fc-' . wp_generate_uuid4();
		$config = array(
			'slidesPerView' => $slides_per,
			'spaceBetween'  => $space_between,
			'loop'          => $loop,
			'breakpoints'   => array(
				'0'    => array( 'slidesPerView' => 1 ),
				'782'  => array( 'slidesPerView' => max( 1, min( $slides_per, 2 ) ) ),
				'1024' => array( 'slidesPerView' => $slides_per ),
			),
		);
		if ( $autoplay ) {
			$config['autoplay'] = array(
				'delay'             => $autoplay_delay,
				'pauseOnMouseEnter' => true,
			);
		}
		// Navigation/pagination are wired up by featured-carousel.js from the
		// child elements below — the config never carries per-instance selectors.

		$class = 'trx-ad-featured-carousel swiper';
		if ( ! empty( $attributes['className'] ) ) {
			$class .= ' ' . sanitize_html_class( (string) $attributes['className'] );
		}

		// Render-time enqueue: scripts land in the footer, styles print via
		// wp_footer's late-styles pass — both after this markup, which is fine
		// because the initialiser waits for DOM ready.
		wp_enqueue_style( 'trx-ad-swiper' );
		wp_enqueue_style( 'trx-ad-frontend' );
		wp_enqueue_script( 'trx-ad-widget-featured-carousel' );

		ob_start();
		?>
		<div id="<?php echo esc_attr( $id ); ?>" class="<?php echo esc_attr( $class ); ?>" data-swiper-config="<?php echo esc_attr( (string) wp_json_encode( $config ) ); ?>">
			<div class="swiper-wrapper">
				<?php foreach ( $rows as $row ) : ?>
					<div class="swiper-slide">
						<?php TemplateLoader::getTemplatePart( 'vehicle-card', array( 'post_id' => (int) $row['ID'] ) ); ?>
					</div>
				<?php endforeach; ?>
			</div>
			<?php if ( $show_navigation ) : ?>
				<div class="swiper-button-prev"></div>
				<div class="swiper-button-next"></div>
			<?php endif; ?>
			<?php if ( $show_pagination ) : ?>
				<div class="swiper-pagination"></div>
			<?php endif; ?>
		</div>
		<?php
		return (string) ob_get_clean();
	}
}
