<?php
/**
 * "Favorites List" block — page block that hydrates the visitor's saved
 * favorites.
 *
 * Same surface as the `[trx_ad_favorites]` shortcode and the Elementor
 * "Favorites List" widget. Delegates to `FavoritesHandler::renderPage()`
 * so output stays in lock-step; JS hydrates from `localStorage` (free) or
 * the Pro plugin's REST CRUD endpoint (Pro tier swaps the data source via
 * the `trx_ad_favorites_button` filter without changing the markup).
 *
 * @package ThemeREX\AutoDealer
 */

declare(strict_types=1);

namespace ThemeREX\AutoDealer\Blocks;

use ThemeREX\AutoDealer\Frontend\FavoritesHandler;

class FavoritesListBlock extends AbstractBlock {

	protected string $slug = 'favorites-list';

	public function render( array $attributes, string $content = '', $block = null ): string {
		$html = FavoritesHandler::renderPage();

		// Optional heading + empty-message overrides applied via post-process
		// regex so the data-* selectors the JS hydrator hooks onto stay intact.
		$heading = isset( $attributes['heading'] ) ? trim( (string) $attributes['heading'] ) : '';
		$empty   = isset( $attributes['emptyMessage'] ) ? trim( (string) $attributes['emptyMessage'] ) : '';

		if ( '' !== $heading ) {
			$html = (string) preg_replace(
				'/(<h1[^>]*class="trx-ad-favorites-page__heading"[^>]*>)[^<]*(<\\/h1>)/',
				'$1' . esc_html( $heading ) . '$2',
				$html,
				1
			);
		}
		if ( '' !== $empty ) {
			$html = (string) preg_replace(
				'/(<p[^>]*data-trx-ad-favorites-empty[^>]*>)[^<]*(<\\/p>)/',
				'$1' . esc_html( $empty ) . '$2',
				$html,
				1
			);
		}

		if ( ! empty( $attributes['className'] ) ) {
			$class = sanitize_html_class( (string) $attributes['className'] );
			$html  = (string) preg_replace(
				'/(<section[^>]*class="trx-ad-favorites-page)(")/',
				'$1 ' . $class . '$2',
				$html,
				1
			);
		}

		return $html;
	}
}
