<?php
/**
 * Gutenberg / FSE block — `findastra/widget`.
 *
 * Thin wrapper over the existing `[findastra]` shortcode so block-theme
 * editors can drop the widget anywhere in the site editor. Server-rendered,
 * so the block's HTML always matches the shortcode's output and the
 * front-end JS attaches identically.
 *
 * No JS for the editor side — server-rendered preview is enough for v1.
 *
 * @package FindAstra
 */

defined( 'ABSPATH' ) || exit;

final class FindAstra_Block {

	public function register(): void {
		add_action( 'init', array( $this, 'register_block' ) );
	}

	public function register_block(): void {
		if ( ! function_exists( 'register_block_type' ) ) {
			return;
		}
		register_block_type(
			'findastra/widget',
			array(
				'api_version'     => 3,
				'title'           => __( 'FindAstra — Semantic Search', 'findastra' ),
				'description'     => __( 'AI semantic product search box for WooCommerce.', 'findastra' ),
				'category'        => 'woocommerce',
				'icon'            => 'search',
				'keywords'        => array( 'search', 'product', 'woocommerce', 'semantic', 'ai' ),
				'supports'        => array(
					'html'  => false,
					'align' => array( 'wide', 'full' ),
				),
				'attributes'      => array(
					'placeholder' => array(
						'type'    => 'string',
						'default' => '',
					),
					'limit' => array(
						'type'    => 'integer',
						'default' => 12,
					),
				),
				'render_callback' => array( $this, 'render' ),
			)
		);
	}

	/**
	 * @param array<string, mixed> $attributes
	 */
	public function render( $attributes ): string {
		$placeholder = isset( $attributes['placeholder'] ) ? (string) $attributes['placeholder'] : '';
		$limit       = isset( $attributes['limit'] ) ? (int) $attributes['limit'] : 12;

		$shortcode = '[findastra limit="' . (int) $limit . '"';
		if ( '' !== trim( $placeholder ) ) {
			$shortcode .= ' placeholder="' . esc_attr( $placeholder ) . '"';
		}
		$shortcode .= ']';

		return do_shortcode( $shortcode );
	}
}
