<?php
declare(strict_types=1);

namespace Wohno\Plugin\Block;

use Wohno\Plugin\Api\Client;
use Wohno\Plugin\Api\ListingQuery;
use Wohno\Plugin\Render\ListingsRenderer;

use const Wohno\Plugin\VERSION;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Dynamic (server-rendered) Gutenberg block `wohno/listing` — embeds a single
 * listing's card by id. Shares the buildless editor script with the grid block.
 */
final class SingleListingBlock {

	/**
	 * Constructor.
	 *
	 * @param Client           $client   API client.
	 * @param ListingsRenderer $renderer HTML renderer.
	 */
	public function __construct(
		private readonly Client $client,
		private readonly ListingsRenderer $renderer
	) {
	}

	/**
	 * Hook block registration into `init`.
	 *
	 * @return void
	 */
	public function register(): void {
		add_action( 'init', array( $this, 'register_block' ) );
	}

	/**
	 * Register the dynamic block type (and the shared editor script if the grid
	 * block has not already registered it).
	 *
	 * @return void
	 */
	public function register_block(): void {
		if ( ! function_exists( 'register_block_type' ) ) {
			return;
		}

		if ( ! wp_script_is( 'wohno-block-editor', 'registered' ) ) {
			wp_register_script(
				'wohno-block-editor',
				WOHNO_PLUGIN_URL . 'assets/js/block-editor.js',
				array( 'wp-blocks', 'wp-element', 'wp-block-editor', 'wp-components', 'wp-server-side-render', 'wp-i18n' ),
				VERSION,
				true
			);
			wp_set_script_translations( 'wohno-block-editor', 'wohno', WOHNO_PLUGIN_DIR . 'languages' );
		}

		register_block_type(
			__DIR__ . '/listing-block.json',
			array(
				'render_callback' => array( $this, 'render' ),
			)
		);
	}

	/**
	 * Server-side render callback for the block.
	 *
	 * @param array<string, mixed> $attributes Block attributes.
	 * @return string Escaped HTML.
	 */
	public function render( array $attributes ): string {
		$id = ListingQuery::sanitize_id( $attributes['id'] ?? '' );
		if ( '' === $id ) {
			return current_user_can( 'edit_posts' )
				? '<p class="wohno-error">' . esc_html__( 'Bitte eine Inserat-ID wählen.', 'wohno' ) . '</p>'
				: '';
		}

		$result = $this->client->listing( $id );
		if ( is_wp_error( $result ) ) {
			return current_user_can( 'edit_posts' )
				? '<p class="wohno-error">' . esc_html( $result->get_error_message() ) . '</p>'
				: '';
		}

		return $this->renderer->single( $result );
	}
}
