<?php

namespace CelerSearch\Blocks;

defined( 'ABSPATH' ) || exit;

use CelerSearch\Repositories\ViewRepository;
use CelerSearch\Views\SearchView;
use CelerSearch\Views\ViewRenderer;

/**
 * CelerSearch Gutenberg block
 *
 * Registers the celersearch/search block and provides its server-side render callback.
 */
class SearchBlock {

	/**
	 * Register the block, its assets, and localize the views list for the editor.
	 *
	 * @return void
	 */
	public static function register(): void {
		$asset_url = CELERSEARCH_PLUGIN_URL . 'assets/blocks/search/';
		$asset_dir = CELERSEARCH_PLUGIN_PATH . 'assets/blocks/search/';
		$version   = CELERSEARCH_PLUGIN_VERSION;

		// Editor script
		wp_register_script(
			'celersearch-block-search-editor',
			$asset_url . 'index.js',
			[ 'wp-blocks', 'wp-element', 'wp-components', 'wp-block-editor', 'wp-i18n' ],
			$version,
			true
		);

		// Editor style
		if ( file_exists( $asset_dir . 'editor.css' ) ) {
			wp_register_style(
				'celersearch-block-search-editor-style',
				$asset_url . 'editor.css',
				[],
				$version
			);
		}

		// Localize views list for the editor dropdown
		$repo  = new ViewRepository();
		$views = $repo->get( [], 1, 100, 'ASC', 'name' );
		$items = array_map( function ( $view ) {
			return [
				'id'   => $view->getId(),
				'name' => $view->getName(),
			];
		}, $views );

		wp_localize_script( 'celersearch-block-search-editor', 'celerSearchBlock', [
			'views' => array_values( $items ),
		] );

		// Register block type with server-side render
		register_block_type(
			CELERSEARCH_PLUGIN_PATH . 'blocks/search',
			[
				'render_callback' => [ self::class, 'render' ],
			]
		);
	}

	/**
	 * Server-side render callback
	 *
	 * @param array $attributes Block attributes.
	 *
	 * @return string
	 */
	public static function render( array $attributes ): string {
		$view_id = absint( $attributes['view'] ?? 0 );

		if ( ! $view_id ) {
			return '';
		}

		$repo        = new ViewRepository();
		$view_config = $repo->find( $view_id );

		if ( ! $view_config ) {
			if ( current_user_can( 'manage_options' ) ) {
				return ViewRenderer::render( 'search/error', [
					'errors' => [
						/* translators: %d: view ID */
						sprintf( __( 'View with ID %d not found.', 'celersearch' ), $view_id ),
					],
				], null );
			}

			return '';
		}

		// Build config from saved view (same logic as SearchShortcode)
		$saved_config = $view_config->getConfig();
		$config       = [
			'index_id'        => $view_config->getIndexId(),
			'limit'           => $saved_config['limit'] ?? 12,
			'placeholder'     => $saved_config['placeholder'] ?? __( 'Search...', 'celersearch' ),
			'class'           => $saved_config['class'] ?? '',
			'show_facets'     => $saved_config['show_facets'] ?? true,
			'highlight'       => $saved_config['highlight'] ?? true,
			'debounce'        => $saved_config['debounce'] ?? 300,
			'min_chars'       => $saved_config['min_chars'] ?? 2,
			'mode'            => $saved_config['mode'] ?? 'live',
			'initial_display' => $saved_config['initial_display'] ?? 'search_only',
		];

		$view   = new SearchView( $config );
		$errors = $view->validate();

		if ( ! empty( $errors ) ) {
			if ( current_user_can( 'manage_options' ) ) {
				return ViewRenderer::render( 'search/error', [ 'errors' => $errors ], $view );
			}

			return '';
		}

		return $view->render();
	}
}
