<?php
/**
 * "Vehicle Card" block.
 *
 * Resolution order for which vehicle to render:
 *   1. Inserter `vehicleId` attribute (explicit override).
 *   2. The Query Loop's `postId` context (when used inside core/query
 *      with the listing CPT — pattern usage).
 *   3. The current global post (fallback for theme templates).
 *
 * @package ThemeREX\AutoDealer
 * @version 1.0.0
 */

declare(strict_types=1);

namespace ThemeREX\AutoDealer\Blocks;

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

class VehicleCardBlock extends AbstractBlock {

	protected string $slug = 'vehicle-card';

	public function render( array $attributes, string $content = '', $block = null ): string {
		$post_id = (int) ( $attributes['vehicleId'] ?? 0 );

		if ( $post_id <= 0 && $block instanceof \WP_Block && isset( $block->context['postId'] ) ) {
			$post_id = (int) $block->context['postId'];
		}
		if ( $post_id <= 0 ) {
			$post_id = (int) get_the_ID();
		}

		if ( $post_id <= 0 || VehiclePostType::POST_TYPE !== get_post_type( $post_id ) ) {
			return '';
		}

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

		// Display-toggle modifiers. Same modifier names as the grid block
		// so a single set of CSS rules works whether the modifier sits on
		// the card wrapper or the grid wrapper (descendant selectors).
		// All default-on; the modifier is added only when an attribute is
		// explicitly false.
		$class .= self::renderToggles( $attributes );

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

	/**
	 * Translate the four card-display attributes (`showMeta`, `showLabel`,
	 * `showFavorite`, `showCompare`) into space-prefixed modifier classes.
	 * Shared with VehicleGridBlock so the grid wrapper can disable the
	 * same elements on every card it contains.
	 *
	 * @param array<string, mixed> $attributes
	 */
	public static function renderToggles( array $attributes ): string {
		$out = '';
		$map = array(
			'showMeta'     => 'no-meta',
			'showLabel'    => 'no-label',
			'showFavorite' => 'no-favorite',
			'showCompare'  => 'no-compare',
		);
		foreach ( $map as $attr => $modifier ) {
			$enabled = ! array_key_exists( $attr, $attributes ) || ! empty( $attributes[ $attr ] );
			if ( ! $enabled ) {
				$out .= ' trx-ad-card-display--' . $modifier;
			}
		}
		return $out;
	}
}
