<?php // phpcs:ignore
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}
/**
 * Rendered HTML for the Algolia Search Page V2 block.
 *
 * @package WLC_Algolia
 *
 * @param array    $attributes Block attributes.
 * @param string   $content    Block content (innerBlocks as HTML).
 * @param WP_Block $block      Block object with innerBlocks.
 */

( static function () use ( $attributes, $content, $block ) {

$wlc_algolia_block_wrapper_attributes = get_block_wrapper_attributes(); // phpcs:ignore

	$wlc_algolia_accent             = isset( $attributes['accentColor'] ) ? sanitize_hex_color( (string) $attributes['accentColor'] ) : '#DB002F';
	$wlc_algolia_gap                = isset( $attributes['gap'] ) ? absint( $attributes['gap'] ) : 16;
	$wlc_algolia_cols               = isset( $attributes['gridColumns'] ) ? absint( $attributes['gridColumns'] ) : 3;
	$wlc_algolia_cols               = max( 2, min( 4, $wlc_algolia_cols ) );
	$wlc_algolia_selected_post_type = isset( $attributes['selectedPostType'] ) ? sanitize_key( (string) $attributes['selectedPostType'] ) : 'post';
	$wlc_algolia_post_type_object   = '' !== $wlc_algolia_selected_post_type ? get_post_type_object( $wlc_algolia_selected_post_type ) : null;
	$wlc_algolia_is_searchable_pt   = $wlc_algolia_post_type_object
		&& ! empty( $wlc_algolia_post_type_object->public )
		&& ! empty( $wlc_algolia_post_type_object->show_ui )
		&& empty( $wlc_algolia_post_type_object->exclude_from_search )
		&& ! empty( $wlc_algolia_post_type_object->show_in_nav_menus );
	if ( ! $wlc_algolia_is_searchable_pt ) {
		$wlc_algolia_selected_post_type = 'post';
	}

	$wlc_algolia_facets_selected = isset( $attributes['facetsSelected'] ) && is_array( $attributes['facetsSelected'] ) ? $attributes['facetsSelected'] : array();
	$wlc_algolia_facet_labels    = isset( $attributes['facetLabels'] ) && is_array( $attributes['facetLabels'] ) ? $attributes['facetLabels'] : array();
	$wlc_algolia_facets          = array();

	if ( ! empty( $wlc_algolia_facets_selected ) ) {
		foreach ( $wlc_algolia_facets_selected as $wlc_algolia_attr ) {
			$wlc_algolia_attr = sanitize_text_field( (string) $wlc_algolia_attr );
			if ( 'taxonomies' === $wlc_algolia_attr ) {
				continue;
			}
			$wlc_algolia_attr = str_replace( 'taxonomies.taxonomies.', 'taxonomies.', $wlc_algolia_attr );
			if ( '' === $wlc_algolia_attr ) {
				continue;
			}

			// CRITICAL: React InstantSearch requires EXACT match with attributesForFaceting in Algolia Dashboard.
			// In Algolia Dashboard, facets are: taxonomies.taxonomies_names.product_cat.
			// But WordPress selects them as: taxonomies_names.product_cat.
			// So we need to convert WordPress format to Dashboard format.

			// Convert WordPress format (taxonomies_names.*) to Dashboard format (taxonomies.taxonomies_names.*).
			if ( preg_match( '/^taxonomies_(names|slugs)\.(.+)$/', $wlc_algolia_attr, $matches ) ) {
				$wlc_algolia_type     = $matches[1];
				$wlc_algolia_taxonomy = $matches[2];
				$wlc_algolia_attr     = 'taxonomies.taxonomies_' . $wlc_algolia_type . '.' . $wlc_algolia_taxonomy;
			}

			// Handle Algolia Dashboard format: taxonomies.taxonomies_names.{taxonomy} or taxonomies.taxonomies_slugs.{taxonomy}.
			// If already in Dashboard format, keep it (no conversion needed).
			if ( preg_match( '/^taxonomies\.taxonomies_(names|slugs)\.(.+)$/', $wlc_algolia_attr, $matches ) ) { // phpcs:ignore Generic.CodeAnalysis.EmptyStatement.DetectedIf -- Intentional: attr already in correct format.
			}

			// Convert old nested taxonomy facet names to new flat array names.
			// Old format: taxonomies.{taxonomy}.slug or taxonomies.{taxonomy}.name.
			// New format: taxonomies_slugs.{taxonomy} or taxonomies_names.{taxonomy}.
			// Then convert to Dashboard format.
			if ( preg_match( '/^taxonomies\.([^.]+)\.(slug|name)$/', $wlc_algolia_attr, $matches ) ) {
				$wlc_algolia_taxonomy = $matches[1];
				$wlc_algolia_type     = $matches[2];
				$wlc_algolia_attr     = 'taxonomies.taxonomies_' . $wlc_algolia_type . 's.' . $wlc_algolia_taxonomy;
			}

			// Keep facet attribute plain by default.
			// Wrapping with searchable(...) requires a specific Algolia facet configuration
			// and can lead to empty values when not explicitly enabled in index settings.

			// Get label - check multiple formats because we convert attribute names.
			// WordPress stores labels with original format (taxonomies_names.product_cat).
			// But we convert to Dashboard format (taxonomies.taxonomies_names.product_cat).
			// So we need to check both formats.
			$wlc_algolia_label_key = str_replace( 'searchable(', '', str_replace( ')', '', $wlc_algolia_attr ) );

			// Try to find label in multiple formats:
			// 1. Dashboard format (after conversion): taxonomies.taxonomies_names.product_cat.
			// 2. WordPress format (original): taxonomies_names.product_cat.
			// 3. Flat format without prefix: taxonomies_names.product_cat.
			$wlc_algolia_label = '';

			// First try Dashboard format (current format).
			if ( isset( $wlc_algolia_facet_labels[ $wlc_algolia_label_key ] ) ) {
				$wlc_algolia_label = sanitize_text_field( (string) $wlc_algolia_facet_labels[ $wlc_algolia_label_key ] );
			} elseif ( isset( $wlc_algolia_facet_labels[ $wlc_algolia_attr ] ) ) {
				$wlc_algolia_label = sanitize_text_field( (string) $wlc_algolia_facet_labels[ $wlc_algolia_attr ] );
			} else {
				// Try WordPress format (original format before conversion).
				// Convert Dashboard format back to WordPress format for label lookup.
				$wlc_algolia_wp_format = $wlc_algolia_label_key;
				if ( preg_match( '/^taxonomies\.taxonomies_(names|slugs)\.(.+)$/', $wlc_algolia_wp_format, $matches ) ) {
					$wlc_algolia_type      = $matches[1];
					$wlc_algolia_taxonomy  = $matches[2];
					$wlc_algolia_wp_format = 'taxonomies_' . $wlc_algolia_type . '.' . $wlc_algolia_taxonomy;
				}
				if ( isset( $wlc_algolia_facet_labels[ $wlc_algolia_wp_format ] ) ) {
					$wlc_algolia_label = sanitize_text_field( (string) $wlc_algolia_facet_labels[ $wlc_algolia_wp_format ] );
				} else {
					// Fallback: use a human-readable version of the attribute name.
					$wlc_algolia_label = $wlc_algolia_label_key;
					// Try to extract taxonomy name and make it readable.
					if ( preg_match( '/\.([^.]+)$/', $wlc_algolia_label_key, $matches ) ) {
						$wlc_algolia_taxonomy_name = $matches[1];
						$wlc_algolia_label         = ucwords( str_replace( '_', ' ', $wlc_algolia_taxonomy_name ) );
					}
				}
			}

			$wlc_algolia_facets[] = array(
				'attribute' => $wlc_algolia_attr,
				'label'     => $wlc_algolia_label,
			);
		}
	}

	$wlc_algolia_template_blocks = array();

	$wlc_algolia_extract_template_blocks = static function ( $blocks ) use ( &$wlc_algolia_extract_template_blocks ) {
		$out = array();
		if ( ! is_array( $blocks ) ) {
			return $out;
		}
		foreach ( $blocks as $b ) {
			if ( ! is_array( $b ) ) {
				continue;
			}
			$name  = isset( $b['blockName'] ) ? (string) $b['blockName'] : '';
			$attrs = isset( $b['attrs'] ) && is_array( $b['attrs'] ) ? $b['attrs'] : array();

			$common = array(
				'hideIfEmpty' => isset( $attrs['hideIfEmpty'] ) ? (bool) $attrs['hideIfEmpty'] : true,
			);

			if ( 'wlc-algolia/result-title' === $name ) {
				$out[] = array_merge(
					$common,
					array(
						'type'          => 'title',
						'fieldPath'     => sanitize_text_field( (string) ( $attrs['fieldPath'] ?? 'post_title' ) ),
						'linkType'      => sanitize_key( (string) ( $attrs['linkType'] ?? 'permalink' ) ),
						'linkFieldPath' => sanitize_text_field( (string) ( $attrs['linkFieldPath'] ?? '' ) ),
					)
				);
			} elseif ( 'wlc-algolia/result-image' === $name ) {
				$out[] = array_merge(
					$common,
					array(
						'type'          => 'image',
						'fieldPath'     => sanitize_text_field( (string) ( $attrs['fieldPath'] ?? 'images.thumbnail.url' ) ),
						'linkType'      => sanitize_key( (string) ( $attrs['linkType'] ?? 'permalink' ) ),
						'linkFieldPath' => sanitize_text_field( (string) ( $attrs['linkFieldPath'] ?? '' ) ),
					)
				);
			} elseif ( 'wlc-algolia/result-excerpt' === $name ) {
				$out[] = array_merge(
					$common,
					array(
						'type'      => 'excerpt',
						'fieldPath' => sanitize_text_field( (string) ( $attrs['fieldPath'] ?? 'post_excerpt' ) ),
						'maxLength' => absint( $attrs['maxLength'] ?? 220 ),
					)
				);
			} elseif ( 'wlc-algolia/result-meta' === $name ) {
				$out[] = array_merge(
					$common,
					array(
						'type'       => 'meta',
						'metaDate'   => isset( $attrs['metaDate'] ) ? ! empty( $attrs['metaDate'] ) : true,
						'metaAuthor' => isset( $attrs['metaAuthor'] ) ? ! empty( $attrs['metaAuthor'] ) : true,
					)
				);
			} elseif ( 'wlc-algolia/result-field' === $name ) {
				$out[] = array_merge(
					$common,
					array(
						'type'          => 'field',
						'label'         => sanitize_text_field( (string) ( $attrs['label'] ?? '' ) ),
						'fieldPath'     => sanitize_text_field( (string) ( $attrs['fieldPath'] ?? '' ) ),
						'linkType'      => sanitize_key( (string) ( $attrs['linkType'] ?? 'none' ) ),
						'linkFieldPath' => sanitize_text_field( (string) ( $attrs['linkFieldPath'] ?? '' ) ),
					)
				);
			} elseif ( 'wlc-algolia/result-button' === $name ) {
				$out[] = array_merge(
					array( 'hideIfEmpty' => isset( $attrs['hideIfEmpty'] ) ? (bool) $attrs['hideIfEmpty'] : false ),
					array(
						'type'          => 'button',
						'label'         => sanitize_text_field( (string) ( $attrs['label'] ?? 'View' ) ),
						'linkType'      => sanitize_key( (string) ( $attrs['linkType'] ?? 'permalink' ) ),
						'linkFieldPath' => sanitize_text_field( (string) ( $attrs['linkFieldPath'] ?? '' ) ),
					)
				);
			}

			if ( isset( $b['innerBlocks'] ) && is_array( $b['innerBlocks'] ) && ! empty( $b['innerBlocks'] ) ) {
				$out = array_merge( $out, $wlc_algolia_extract_template_blocks( $b['innerBlocks'] ) );
			}
		}
		return $out;
	};

	// Try to get innerBlocks from $block first (most reliable for dynamic blocks).
	$wlc_algolia_inner_blocks = null;
	if ( isset( $block ) ) {
		if ( is_object( $block ) && method_exists( $block, 'get_parsed_block' ) ) {
			$wlc_algolia_parsed       = $block->get_parsed_block();
			$wlc_algolia_inner_blocks = isset( $wlc_algolia_parsed['innerBlocks'] ) ? $wlc_algolia_parsed['innerBlocks'] : null;
		} elseif ( is_object( $block ) && isset( $block->parsed_block['innerBlocks'] ) ) {
			$wlc_algolia_inner_blocks = $block->parsed_block['innerBlocks'];
		} elseif ( is_array( $block ) && isset( $block['innerBlocks'] ) ) {
			$wlc_algolia_inner_blocks = $block['innerBlocks'];
		}
	}

	if ( $wlc_algolia_inner_blocks && is_array( $wlc_algolia_inner_blocks ) && ! empty( $wlc_algolia_inner_blocks ) ) {
		$wlc_algolia_template_blocks = $wlc_algolia_extract_template_blocks( $wlc_algolia_inner_blocks );
	} elseif ( isset( $content ) && is_string( $content ) && '' !== trim( $content ) ) {
		// Fallback: parse content HTML if innerBlocks not available.
		$wlc_algolia_parsed          = parse_blocks( $content );
		$wlc_algolia_template_blocks = $wlc_algolia_extract_template_blocks( $wlc_algolia_parsed );
	}

	// Get Algolia API keys.
	$wlc_algolia_general_settings = get_option( 'wlc_algolia_settings_general', array() );
	$wlc_algolia_app_id           = '';
	$wlc_algolia_search_api_key   = '';
	$wlc_algolia_base_index       = '';

	if ( is_array( $wlc_algolia_general_settings ) && isset( $wlc_algolia_general_settings['general'] ) ) {
		$wlc_algolia_app_id         = isset( $wlc_algolia_general_settings['general']['application_id'] ) ? sanitize_text_field( (string) $wlc_algolia_general_settings['general']['application_id'] ) : '';
		$wlc_algolia_search_api_key = isset( $wlc_algolia_general_settings['general']['search_api_key'] ) ? sanitize_text_field( (string) $wlc_algolia_general_settings['general']['search_api_key'] ) : '';
		$wlc_algolia_base_index     = isset( $wlc_algolia_general_settings['general']['index_name'] ) ? sanitize_text_field( (string) $wlc_algolia_general_settings['general']['index_name'] ) : '';
	}

	// Get WooCommerce currency if available.
	$wlc_algolia_currency = 'USD'; // Default fallback.
	if ( function_exists( 'get_woocommerce_currency' ) ) {
		$wlc_algolia_currency = get_woocommerce_currency();
	}
	$wlc_algolia_image_placeholder = '';
	if ( function_exists( 'wc_placeholder_img_src' ) ) {
		$wlc_algolia_image_placeholder = wc_placeholder_img_src( 'woocommerce_single' );
	}
	$wlc_algolia_pagination_max_pages = isset( $attributes['paginationMaxPages'] ) ? absint( $attributes['paginationMaxPages'] ) : 9;
	$wlc_algolia_pagination_max_pages = max( 3, min( 20, $wlc_algolia_pagination_max_pages ) );
	if ( 0 === $wlc_algolia_pagination_max_pages % 2 ) {
		$wlc_algolia_pagination_max_pages = max( 3, $wlc_algolia_pagination_max_pages - 1 );
	}
	$wlc_algolia_taxonomy_hierarchy      = array();
	$wlc_algolia_hierarchical_taxonomies = array();
	$wlc_algolia_author_labels           = array();
	$wlc_algolia_needs_author_labels     = false;
	foreach ( $wlc_algolia_facets as $wlc_algolia_facet ) {
		$wlc_algolia_attribute = isset( $wlc_algolia_facet['attribute'] ) ? (string) $wlc_algolia_facet['attribute'] : '';
		if ( 'post_author' === $wlc_algolia_attribute ) {
			$wlc_algolia_needs_author_labels = true;
		}
		if ( preg_match( '/^taxonomies\.taxonomies_(?:names|slugs)\.(.+)$/', $wlc_algolia_attribute, $matches ) ) {
			$wlc_algolia_taxonomy = sanitize_key( (string) $matches[1] );
			if ( taxonomy_exists( $wlc_algolia_taxonomy ) && is_taxonomy_hierarchical( $wlc_algolia_taxonomy ) ) {
				$wlc_algolia_hierarchical_taxonomies[] = $wlc_algolia_taxonomy;
			}
		}
	}
	$wlc_algolia_hierarchical_taxonomies = array_values( array_unique( $wlc_algolia_hierarchical_taxonomies ) );
	foreach ( $wlc_algolia_hierarchical_taxonomies as $wlc_algolia_taxonomy ) {
		$wlc_algolia_terms = get_terms(
			array(
				'taxonomy'   => $wlc_algolia_taxonomy,
				'hide_empty' => false,
			)
		);
		if ( is_wp_error( $wlc_algolia_terms ) || ! is_array( $wlc_algolia_terms ) || empty( $wlc_algolia_terms ) ) {
			continue;
		}
		$wlc_algolia_slug_by_id = array();
		foreach ( $wlc_algolia_terms as $wlc_algolia_term ) {
			if ( isset( $wlc_algolia_term->term_id ) && isset( $wlc_algolia_term->slug ) ) {
				$wlc_algolia_slug_by_id[ (int) $wlc_algolia_term->term_id ] = (string) $wlc_algolia_term->slug;
			}
		}
		usort(
			$wlc_algolia_terms,
			static function ( $a, $b ) {
				$name_a = isset( $a->name ) ? (string) $a->name : '';
				$name_b = isset( $b->name ) ? (string) $b->name : '';
				return strcasecmp( $name_a, $name_b );
			}
		);
		$wlc_algolia_taxonomy_hierarchy[ $wlc_algolia_taxonomy ] = array_map(
			static function ( $term ) use ( $wlc_algolia_slug_by_id ) {
				$term_id   = isset( $term->term_id ) ? (int) $term->term_id : 0;
				$parent_id = isset( $term->parent ) ? (int) $term->parent : 0;
				return array(
					'id'         => $term_id,
					'name'       => isset( $term->name ) ? (string) $term->name : '',
					'slug'       => isset( $term->slug ) ? (string) $term->slug : '',
					'parent'     => $parent_id,
					'parentSlug' => isset( $wlc_algolia_slug_by_id[ $parent_id ] ) ? (string) $wlc_algolia_slug_by_id[ $parent_id ] : '',
				);
			},
			$wlc_algolia_terms
		);
	}

	if ( $wlc_algolia_needs_author_labels ) {
		$wlc_algolia_authors = get_users(
			array(
				'fields'              => array( 'ID', 'display_name' ),
				'who'                 => 'authors',
				'has_published_posts' => array( $wlc_algolia_selected_post_type ),
			)
		);
		if ( is_array( $wlc_algolia_authors ) && ! empty( $wlc_algolia_authors ) ) {
			foreach ( $wlc_algolia_authors as $wlc_algolia_user ) {
				if ( ! $wlc_algolia_user instanceof \WP_User ) {
					continue;
				}
				$wlc_algolia_author_id = (int) $wlc_algolia_user->ID;
				if ( $wlc_algolia_author_id <= 0 ) {
					continue;
				}
				$wlc_algolia_first_name = trim( (string) get_user_meta( $wlc_algolia_author_id, 'first_name', true ) );
				$wlc_algolia_last_name  = trim( (string) get_user_meta( $wlc_algolia_author_id, 'last_name', true ) );
				$wlc_algolia_full_name  = trim( $wlc_algolia_first_name . ' ' . $wlc_algolia_last_name );
				$wlc_algolia_nickname   = trim( (string) get_user_meta( $wlc_algolia_author_id, 'nickname', true ) );
				$wlc_algolia_label      = '';
				if ( '' !== $wlc_algolia_full_name ) {
					$wlc_algolia_label = $wlc_algolia_full_name;
				} elseif ( '' !== $wlc_algolia_nickname ) {
					$wlc_algolia_label = $wlc_algolia_nickname;
				} else {
					$wlc_algolia_label = trim( (string) $wlc_algolia_user->display_name );
				}
				if ( '' !== $wlc_algolia_label ) {
					$wlc_algolia_author_labels[ (string) $wlc_algolia_author_id ] = sanitize_text_field( $wlc_algolia_label );
				}
			}
		}
	}

	$wlc_algolia_config = array(
		'appId'              => $wlc_algolia_app_id,
		'apiKey'             => $wlc_algolia_search_api_key,
		'baseIndex'          => $wlc_algolia_base_index,
		'selectedPostType'   => $wlc_algolia_selected_post_type,
		'hitsPerPage'        => isset( $attributes['hitsPerPage'] ) ? absint( $attributes['hitsPerPage'] ) : 10,
		'placeholder'        => isset( $attributes['placeholder'] ) ? sanitize_text_field( (string) $attributes['placeholder'] ) : 'Search...',
		'showFilters'        => ! empty( $attributes['showFilters'] ),
		'showPagination'     => ! empty( $attributes['showPagination'] ),
		'showResultsCount'   => ! empty( $attributes['showResultsCount'] ),
		'paginationMode'     => isset( $attributes['paginationMode'] ) ? sanitize_key( (string) $attributes['paginationMode'] ) : 'simple',
		'paginationMaxPages' => $wlc_algolia_pagination_max_pages,
		'viewMode'           => isset( $attributes['viewMode'] ) ? sanitize_key( (string) $attributes['viewMode'] ) : 'list',
		'gridColumns'        => $wlc_algolia_cols,
		'gap'                => $wlc_algolia_gap,
		'accentColor'        => $wlc_algolia_accent ? $wlc_algolia_accent : '#DB002F',
		'indexNameOverride'  => isset( $attributes['indexNameOverride'] ) ? sanitize_text_field( (string) $attributes['indexNameOverride'] ) : '',
		'facets'             => $wlc_algolia_facets,
		'facetsSelected'     => array_values( $wlc_algolia_facets_selected ),
		'facetLabels'        => $wlc_algolia_facet_labels,
		'showFacetCounts'    => ! empty( $attributes['showFacetCounts'] ),
		'facetCountStyle'    => isset( $attributes['facetCountStyle'] ) ? sanitize_key( (string) $attributes['facetCountStyle'] ) : 'paren',
		'showActiveFilters'  => ! empty( $attributes['showActiveFilters'] ),
		'enableFacetSearch'  => ! empty( $attributes['enableFacetSearch'] ),
		'stickyFilters'      => ! empty( $attributes['stickyFilters'] ),
		'showSort'           => ! empty( $attributes['showSort'] ),
		'enableUrlSync'      => ! empty( $attributes['enableUrlSync'] ),
		'sortDefault'        => isset( $attributes['sortDefault'] ) ? sanitize_key( (string) $attributes['sortDefault'] ) : 'relevance',
		'sortIndexSuffixes'  => isset( $attributes['sortIndexSuffixes'] ) && is_array( $attributes['sortIndexSuffixes'] ) ? $attributes['sortIndexSuffixes'] : array(),
		'templateBlocks'     => $wlc_algolia_template_blocks,
		'taxonomyHierarchy'  => $wlc_algolia_taxonomy_hierarchy,
		'currency'           => $wlc_algolia_currency,
		'imagePlaceholder'   => $wlc_algolia_image_placeholder,
		'authorLabels'       => $wlc_algolia_author_labels,
	);
	?>
<div <?php echo $wlc_algolia_block_wrapper_attributes; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
	data-config="<?php echo esc_attr( wp_json_encode( $wlc_algolia_config ) ); ?>"
	style="--wlc-accent: <?php echo esc_attr( $wlc_algolia_accent ); ?>; --wlc-gap: <?php echo esc_attr( $wlc_algolia_gap ); ?>px; --wlc-cols: <?php echo esc_attr( $wlc_algolia_cols ); ?>;"
>
	<div class="wp-block-wlc-algolia-search-page__container" data-role="react-root"></div>
</div>
	<?php
} )();
