<?php

namespace CelerSearch\Views;

defined( 'ABSPATH' ) || exit;

use CelerSearch\Interfaces\IRegistrable;

/**
 * Conditional asset enqueue for views
 *
 * Reads ViewRegistry in wp_footer to determine if assets should be enqueued.
 */
class ViewAssets implements IRegistrable {

	const SCRIPT_HANDLE = 'celersearch-search-view';
	const STYLE_HANDLE  = 'celersearch-search-view';

	/**
	 * @inheritDoc
	 */
	public function register(): void {
		add_action( 'wp_enqueue_scripts', [ $this, 'register_assets' ] );
		add_action( 'wp_footer', [ $this, 'maybe_enqueue' ], 0 );
	}

	/**
	 * Register (but don't enqueue) the assets so they're available
	 *
	 * @return void
	 */
	public function register_assets(): void {
		wp_register_style(
			self::STYLE_HANDLE,
			\CELERSEARCH_PLUGIN_URL . 'assets/frontend/search-view.css',
			[],
			\CELERSEARCH_PLUGIN_VERSION
		);

		wp_register_script(
			self::SCRIPT_HANDLE,
			\CELERSEARCH_PLUGIN_URL . 'assets/frontend/search-view.js',
			[],
			\CELERSEARCH_PLUGIN_VERSION,
			true
		);
	}

	/**
	 * Enqueue assets if any search views were rendered on this page
	 *
	 * @return void
	 */
	public function maybe_enqueue(): void {
		$views = ViewRegistry::get_views_by_type( SearchView::class );

		if ( empty( $views ) ) {
			return;
		}

		wp_enqueue_style( self::STYLE_HANDLE );
		wp_enqueue_script( self::SCRIPT_HANDLE );

		// Build per-instance configs
		$instances = [];
		foreach ( $views as $view ) {
			$instances[] = $view->get_js_config();
		}

		wp_localize_script( self::SCRIPT_HANDLE, 'celerSearchViews', [
			'restUrl'   => rest_url( 'celersearch/v1/search' ),
			'nonce'     => wp_create_nonce( 'wp_rest' ),
			'instances' => $instances,
			'i18n'      => [
				'noResults'     => __( 'No results found.', 'celersearch' ),
				'searching'     => __( 'Searching...', 'celersearch' ),
				'errorMessage'  => __( 'An error occurred. Please try again.', 'celersearch' ),
				'clearFilters'  => __( 'Clear filters', 'celersearch' ),
				'showMore'      => __( 'Show more', 'celersearch' ),
				'showLess'      => __( 'Show less', 'celersearch' ),
				'page'          => __( 'Page', 'celersearch' ),
				'of'            => __( 'of', 'celersearch' ),
				'previous'      => __( 'Previous', 'celersearch' ),
				'next'          => __( 'Next', 'celersearch' ),
				'resultsCount'  => __( '%d results found', 'celersearch' ),
			],
		] );
	}
}
