<?php

namespace CelerSearch\Views;

defined( 'ABSPATH' ) || exit;

/**
 * Search view: search input + faceted filters + paginated results
 *
 * Portable view that can be used by shortcodes, Elementor, Gutenberg, etc.
 */
class SearchView extends AbstractView {

	/**
	 * @inheritDoc
	 */
	protected function configure( array $config ): array {
		$defaults = [
			'index_id'          => 0,
			'limit'             => 12,
			'placeholder'       => __( 'Search...', 'celersearch' ),
			'class'             => '',
			'show_facets'       => true,
			'highlight'         => true,
			'debounce'          => 300,
			'min_chars'         => 2,
			'mode'              => 'live',
			'initial_query'     => '',
			'initial_display'   => 'search_only',
			'default_sort'      => '',
			'facet_groups_mode' => 'all',
			'facet_groups'      => [],
		];

		$config = wp_parse_args( $config, $defaults );

		// Normalize types
		$config['index_id']        = absint( $config['index_id'] );
		$config['limit']           = absint( $config['limit'] ) ?: 12;
		$config['show_facets']     = filter_var( $config['show_facets'], FILTER_VALIDATE_BOOLEAN );
		$config['highlight']       = filter_var( $config['highlight'], FILTER_VALIDATE_BOOLEAN );
		$config['debounce']        = absint( $config['debounce'] );
		$config['min_chars']       = absint( $config['min_chars'] );
		$config['mode']              = in_array( $config['mode'], [ 'live', 'submit' ], true ) ? $config['mode'] : 'live';
		$config['initial_display']   = in_array( $config['initial_display'], [ 'search_only', 'browse' ], true )
			? $config['initial_display']
			: 'search_only';
		$config['default_sort']      = in_array( $config['default_sort'], [ '', 'date', 'date-asc', 'title', 'title-desc' ], true )
			? $config['default_sort']
			: '';
		$config['facet_groups_mode'] = in_array( $config['facet_groups_mode'], [ 'all', 'selected', 'none' ], true )
			? $config['facet_groups_mode']
			: 'all';
		$config['facet_groups']      = is_array( $config['facet_groups'] ) ? $config['facet_groups'] : [];

		/**
		 * Filter search view configuration
		 *
		 * @param array $config The view configuration.
		 */
		return apply_filters( 'celersearch_view_config', $config );
	}

	/**
	 * @inheritDoc
	 */
	public function validate(): array {
		$errors = [];

		if ( empty( $this->config['index_id'] ) ) {
			$errors[] = __( 'The index_id attribute is required.', 'celersearch' );
		}

		return $errors;
	}

	/**
	 * @inheritDoc
	 */
	public function render(): string {
		// Register in the view registry for asset enqueue
		ViewRegistry::register( $this );

		// Load sub-templates
		$templates = [
			'result-item' => ViewRenderer::render( 'search/result-item', [], $this ),
			'no-results'  => ViewRenderer::render( 'search/no-results', [], $this ),
			'pagination'  => ViewRenderer::render( 'search/pagination', [], $this ),
			'facet-group' => ViewRenderer::render( 'search/facet-group', [], $this ),
		];

		return ViewRenderer::render( 'search/search', [
			'view'      => $this,
			'config'    => $this->config,
			'unique_id' => $this->get_unique_id(),
			'templates' => $templates,
		], $this );
	}

	/**
	 * @inheritDoc
	 */
	public function get_js_config(): array {
		$config = [
			'instanceId'      => $this->get_unique_id(),
			'indexId'         => $this->config['index_id'],
			'limit'           => $this->config['limit'],
			'placeholder'     => $this->config['placeholder'],
			'showFacets'      => $this->config['show_facets'],
			'highlight'       => $this->config['highlight'],
			'debounce'        => $this->config['debounce'],
			'minChars'        => $this->config['min_chars'],
			'mode'            => $this->config['mode'],
			'initialQuery'    => $this->config['initial_query'],
			'initialDisplay'  => $this->config['initial_display'],
			'defaultSort'     => $this->config['default_sort'],
			'facetLabels'     => $this->get_facet_labels(),
			'facetGroupsMode' => $this->config['facet_groups_mode'],
			'facetGroups'     => $this->config['facet_groups'],
		];

		/**
		 * Filter search view JS config
		 *
		 * @param array      $config The JS configuration.
		 * @param SearchView $view   The view instance.
		 */
		return apply_filters( 'celersearch_view_search_js_config', $config, $this );
	}

	/**
	 * Get facet key to label mapping
	 *
	 * @return array
	 */
	private function get_facet_labels(): array {
		$labels = [
			'taxonomies.category'    => __( 'Category', 'celersearch' ),
			'taxonomies.post_tag'    => __( 'Tags', 'celersearch' ),
			'taxonomies.product_cat' => __( 'Category', 'celersearch' ),
			'taxonomies.product_tag' => __( 'Tags', 'celersearch' ),
			'in_stock'               => __( 'Availability', 'celersearch' ),
			'ratings.average_rating' => __( 'Rating', 'celersearch' ),
		];

		// Add WooCommerce product attributes
		if ( function_exists( 'wc_get_attribute_taxonomies' ) ) {
			$attributes = wc_get_attribute_taxonomies();
			foreach ( $attributes as $attr ) {
				$key            = 'taxonomies.pa_' . $attr->attribute_name;
				$labels[ $key ] = $attr->attribute_label;
			}
		}

		/**
		 * Filter facet labels mapping
		 *
		 * @param array      $labels The facet labels map.
		 * @param SearchView $view   The view instance.
		 */
		return apply_filters( 'celersearch_view_facet_labels', $labels, $this );
	}

	/**
	 * @inheritDoc
	 */
	public function get_asset_handle(): string {
		return 'celersearch-search-view';
	}
}
