<?php
/**
 * Admin UI — settings page under WooCommerce > FindAstra.
 *
 * Three-tier picker, per-tier credential fields, indexing controls, and a
 * small dashboard with recent searches + zero-result queries. Form submission
 * goes through register_setting → sanitize_settings which encrypts API
 * credentials before persisting.
 *
 * @package FindAstra
 */

defined( 'ABSPATH' ) || exit;

final class FindAstra_Admin {

	public const MENU_SLUG       = 'findastra';
	public const SETTINGS_GROUP  = 'findastra_settings_group';
	public const SETTINGS_OPTION = 'findastra_settings';
	public const CAPABILITY      = 'manage_woocommerce';
	public const ONBOARDING_FLAG = 'findastra_onboarding_done';

	public function register(): void {
		add_action( 'admin_menu', array( $this, 'register_menu' ) );
		add_action( 'admin_init', array( $this, 'register_settings' ) );
		add_action( 'admin_notices', array( $this, 'maybe_onboarding_notice' ) );
		// Suppress third-party plugin/theme noise on our settings page so the
		// buyer's first impression is a clean FindAstra UI, not a wall of
		// "Thank you for choosing Boutique Garment Store" banners.
		add_action( 'in_admin_header', array( $this, 'suppress_third_party_notices' ), 1000 );
	}

	/**
	 * Strip every `admin_notices` / `all_admin_notices` callback when we're
	 * on the FindAstra settings screen. Runs late on `in_admin_header` so
	 * we win against plugins that register on `admin_init` or `admin_menu`.
	 *
	 * `settings_errors()` is restored manually inside `render_page()` so the
	 * "Settings saved" feedback after a form submit still appears.
	 */
	public function suppress_third_party_notices(): void {
		if ( ! function_exists( 'get_current_screen' ) ) {
			return;
		}
		$screen = get_current_screen();
		if ( ! $screen || false === strpos( (string) $screen->id, self::MENU_SLUG ) ) {
			return;
		}
		remove_all_actions( 'admin_notices' );
		remove_all_actions( 'all_admin_notices' );
		remove_all_actions( 'network_admin_notices' );
		remove_all_actions( 'user_admin_notices' );
	}

	public function register_menu(): void {
		// Top-level menu. Position 56 sits right after WooCommerce (55.5) and
		// before the WP separator at 59 — natural place for a WC-adjacent
		// plugin without burying it under WooCommerce.
		//
		// The icon is the official compact brand mark, inlined as a base64
		// data URI so the sidebar never makes an HTTP request for it (and so
		// the icon survives plugin-folder URL weirdness on hosts that block
		// SVG MIME types). The compact mark is designed for ~20px rendering
		// in sidebars — fewer constellation points than the full mark,
		// thicker strokes.
		$icon_svg = file_get_contents( FINDASTRA_DIR . 'assets/findastra-icon-compact.svg' );
		$icon     = is_string( $icon_svg ) && '' !== $icon_svg
			? 'data:image/svg+xml;base64,' . base64_encode( $icon_svg )
			: 'dashicons-search';

		add_menu_page(
			__( 'FindAstra Settings', 'findastra' ),
			__( 'FindAstra', 'findastra' ),
			self::CAPABILITY,
			self::MENU_SLUG,
			array( $this, 'render_page' ),
			$icon,
			56
		);

		// Replace the auto-generated first submenu (which duplicates the
		// top-level "FindAstra" label) with a cleaner "Settings" entry so
		// the sidebar reads:
		//   FindAstra
		//     Settings
		//     Account    (Freemius)
		//     Pricing    (Freemius)
		add_submenu_page(
			self::MENU_SLUG,
			__( 'FindAstra Settings', 'findastra' ),
			__( 'Settings', 'findastra' ),
			self::CAPABILITY,
			self::MENU_SLUG,
			array( $this, 'render_page' )
		);
	}

	public function register_settings(): void {
		register_setting(
			self::SETTINGS_GROUP,
			self::SETTINGS_OPTION,
			array(
				'type'              => 'array',
				'sanitize_callback' => array( $this, 'sanitize_settings' ),
				'default'           => array(
					'provider' => 'local',
					'model'    => 'Xenova/bge-small-en-v1.5',
					'dims'     => 384,
				),
			)
		);
	}

	public function sanitize_settings( $input ): array {
		$input = is_array( $input ) ? $input : array();

		$allowed_providers = array( 'local' );
		if ( FindAstra_License::can( 'engine.openai' ) ) {
			$allowed_providers[] = 'openai';
		}
		if ( FindAstra_License::can( 'engine.huggingface' ) ) {
			$allowed_providers[] = 'huggingface';
		}
		if ( FindAstra_Provider_Mock::is_enabled() ) {
			$allowed_providers[] = FindAstra_Provider_Mock::KEY;
		}
		$provider = isset( $input['provider'] ) ? sanitize_key( $input['provider'] ) : 'local';
		if ( ! in_array( $provider, $allowed_providers, true ) ) {
			$provider = 'local';
		}

		$current = get_option( self::SETTINGS_OPTION, array() );
		$current = is_array( $current ) ? $current : array();

		$openai_key = isset( $input['openai_key'] ) ? trim( (string) $input['openai_key'] ) : '';
		$hf_token   = isset( $input['hf_token'] ) ? trim( (string) $input['hf_token'] ) : '';

		$stored_openai = '' !== $openai_key
			? FindAstra_Crypto::encrypt( $openai_key )
			: (string) ( $current['openai_key'] ?? '' );

		$stored_hf = '' !== $hf_token
			? FindAstra_Crypto::encrypt( $hf_token )
			: (string) ( $current['hf_token'] ?? '' );

		// Fallback product IDs: comma-separated positive integers; preserve order.
		$fallback_raw = isset( $input['fallback_product_ids'] ) ? (string) $input['fallback_product_ids'] : '';
		$fallback_ids = array();
		if ( '' !== trim( $fallback_raw ) ) {
			foreach ( explode( ',', $fallback_raw ) as $piece ) {
				$id = absint( trim( $piece ) );
				if ( $id > 0 ) {
					$fallback_ids[] = (string) $id;
				}
			}
			$fallback_ids = array_values( array_unique( $fallback_ids ) );
		}
		$fallback_clean = implode( ',', $fallback_ids );

		// Theme-integration toggles. Stored as '1' / '0' strings (forms send strings).
		$autocomplete_on  = isset( $input['autocomplete_attach'] )  ? '1' : '0';
		$hijack_results   = isset( $input['hijack_results_page'] )  ? '1' : '0';

		// Match-quality gates: store as numeric strings between 0 and 1, or
		// '' meaning "use the built-in default". Empty input survives empty;
		// invalid input falls back to empty so we never silently mangle a
		// buyer's gate to 0.0 and accept everything.
		$min_top_score = self::sanitize_gate( $input['min_top_score'] ?? '' );
		$min_score     = self::sanitize_gate( $input['min_score']     ?? '' );
		$score_window  = self::sanitize_gate( $input['score_window']  ?? '' );

		// HF model picker — whitelist against FindAstra_Provider_HuggingFace::MODELS.
		// Anything else (or unset on first save) falls back to the default English
		// model so we don't surprise existing buyers with a 1024d reindex. The
		// Hugging Face provider ships only in the paid build, so guard every
		// reference to its class — in the free build it does not exist.
		$hf_model = '';
		if ( class_exists( 'FindAstra_Provider_HuggingFace' ) ) {
			$hf_model_raw = isset( $input['hf_model'] ) ? (string) $input['hf_model'] : (string) ( $current['hf_model'] ?? '' );
			$hf_model     = isset( FindAstra_Provider_HuggingFace::MODELS[ $hf_model_raw ] )
				? $hf_model_raw
				: FindAstra_Provider_HuggingFace::MODEL_DEFAULT;
		}

		// Resolve model + dims for the chosen provider. Only Local is guaranteed
		// to exist; OpenAI / Hugging Face are paid-build-only classes.
		$model_for = array( 'local' => FindAstra_Provider_Local::MODEL );
		$dims_for  = array( 'local' => FindAstra_Provider_Local::DIMS );
		if ( class_exists( 'FindAstra_Provider_OpenAI' ) ) {
			$model_for['openai'] = FindAstra_Provider_OpenAI::MODEL;
			$dims_for['openai']  = FindAstra_Provider_OpenAI::DIMS;
		}
		if ( class_exists( 'FindAstra_Provider_HuggingFace' ) ) {
			$model_for['huggingface'] = $hf_model;
			$dims_for['huggingface']  = (int) FindAstra_Provider_HuggingFace::MODELS[ $hf_model ]['dims'];
		}

		update_option( self::ONBOARDING_FLAG, '1', false );

		return array(
			'provider'             => $provider,
			'model'                => $model_for[ $provider ] ?? FindAstra_Provider_Local::MODEL,
			'dims'                 => $dims_for[ $provider ] ?? FindAstra_Provider_Local::DIMS,
			'hf_model'             => $hf_model,
			'openai_key'           => $stored_openai,
			'hf_token'             => $stored_hf,
			'fallback_product_ids' => $fallback_clean,
			'autocomplete_attach'  => $autocomplete_on,
			'hijack_results_page'  => $hijack_results,
			'min_top_score'        => $min_top_score,
			'min_score'            => $min_score,
			'score_window'         => $score_window,
		);
	}

	/**
	 * Validate a single gate input. Returns the input as a normalized
	 * decimal string (e.g. "0.6") if it parses as a float in (0, 1].
	 * Returns '' for blank input (= use the default) or anything that
	 * doesn't parse cleanly — preferable to silently coercing garbage
	 * to 0 and accepting every match.
	 */
	private static function sanitize_gate( mixed $raw ): string {
		$str = trim( (string) $raw );
		if ( '' === $str ) {
			return '';
		}
		// Accept comma as decimal separator (common in non-US locales).
		$str = str_replace( ',', '.', $str );
		if ( ! is_numeric( $str ) ) {
			return '';
		}
		$f = (float) $str;
		if ( $f <= 0.0 || $f > 1.0 ) {
			return '';
		}
		return rtrim( rtrim( sprintf( '%.4f', $f ), '0' ), '.' );
	}

	/**
	 * Install runtime overrides for the gating filter hooks based on the
	 * stored option values. Called from the plugin bootstrap. No-op when
	 * a value isn't set, so the in-code defaults still apply.
	 */
	public static function register_gate_filters(): void {
		$opts = get_option( self::SETTINGS_OPTION, array() );
		if ( ! is_array( $opts ) ) {
			return;
		}
		$bind = static function ( string $hook, string $key ) use ( $opts ) {
			$value = $opts[ $key ] ?? '';
			if ( '' === $value || ! is_numeric( $value ) ) {
				return;
			}
			add_filter( $hook, static fn() => (float) $value );
		};
		$bind( 'findastra_min_top_score', 'min_top_score' );
		$bind( 'findastra_min_score',     'min_score' );
		$bind( 'findastra_score_window',  'score_window' );
	}

	/**
	 * True when WPML or Polylang is active on the site — used to decide
	 * whether to render the Languages section in the Search tab. Mono-
	 * lingual stores never see it, keeping the settings UI tidy for the
	 * 95% case.
	 */
	public static function is_multilingual_site(): bool {
		if ( function_exists( 'pll_languages_list' ) ) {
			return true;
		}
		if ( defined( 'ICL_SITEPRESS_VERSION' ) ) {
			return true;
		}
		// Last-resort feature detection: WPML registers this filter even before
		// the Sitepress class is loaded on the same request.
		return has_filter( 'wpml_current_language' ) || has_filter( 'wpml_post_language_details' );
	}

	public function maybe_onboarding_notice(): void {
		$screen = function_exists( 'get_current_screen' ) ? get_current_screen() : null;
		if ( $screen && isset( $screen->id ) && false !== strpos( (string) $screen->id, 'findastra' ) ) {
			return;
		}
		if ( '1' === get_option( self::ONBOARDING_FLAG, '0' ) ) {
			return;
		}
		if ( ! current_user_can( self::CAPABILITY ) ) {
			return;
		}
		$url = admin_url( 'admin.php?page=' . self::MENU_SLUG );
		printf(
			'<div class="notice notice-info is-dismissible"><p><strong>%s</strong> %s <a href="%s">%s</a></p></div>',
			esc_html__( 'FindAstra is ready.', 'findastra' ),
			esc_html__( 'Pick a search engine and index your products to enable semantic search.', 'findastra' ),
			esc_url( $url ),
			esc_html__( 'Open settings →', 'findastra' )
		);
	}

	public function render_page(): void {
		if ( ! current_user_can( self::CAPABILITY ) ) {
			wp_die( esc_html__( 'You do not have permission to access this page.', 'findastra' ) );
		}

		// `suppress_third_party_notices()` stripped every `admin_notices` hook
		// for this screen, including WP's auto-rendered settings_errors. Add it
		// back inline so "Settings saved." (and validation errors) still appear
		// after a form submit.
		settings_errors();

		$settings = wp_parse_args(
			get_option( self::SETTINGS_OPTION, array() ),
			array(
				'provider'             => 'local',
				'openai_key'           => '',
				'hf_token'             => '',
				'hf_model'             => class_exists( 'FindAstra_Provider_HuggingFace' ) ? FindAstra_Provider_HuggingFace::MODEL_DEFAULT : '',
				'autocomplete_attach'  => '1',
				'hijack_results_page'  => '1',
				'fallback_product_ids' => '',
				'min_top_score'        => '',
				'min_score'            => '',
				'score_window'         => '',
			)
		);

		$store    = new FindAstra_Vector_Store();
		$indexer  = new FindAstra_Indexer();
		// Search analytics is a paid-tier feature: FindAstra_Search_Log ships only
		// in the paid build (class-findastra-search-log__premium_only.php) and is
		// absent from the free build. Guard every analytics use behind this flag.
		$has_analytics = class_exists( 'FindAstra_Search_Log' );
		$log      = $has_analytics ? new FindAstra_Search_Log() : null;
		$provider = FindAstra_Provider_Factory::current();
		$indexed  = $store->count_for( $provider->key(), $provider->model() );
		$total    = $indexer->count_total_products();
		$totals   = $has_analytics ? $log->totals() : array( 'today_total' => 0, 'today_zero' => 0, 'today_avg_ms' => 0 );
		$last_sync = $store->last_indexed_at( $provider->key(), $provider->model() );

		$openai_masked = FindAstra_Crypto::mask( FindAstra_Crypto::decrypt( (string) $settings['openai_key'] ) );
		$hf_masked     = FindAstra_Crypto::mask( FindAstra_Crypto::decrypt( (string) $settings['hf_token'] ) );

		// Per-language indexed counts for the active engine. Empty key means
		// "no language detected" — that's WPML/Polylang-disabled stores and
		// rows v0.9.x left behind before the migration. We render the
		// Languages section whenever there's more than one language tag (i.e.
		// a translation plugin is actively producing rows) so single-language
		// stores aren't cluttered with a redundant table.
		$language_counts = $store->languages_for( $provider->key(), $provider->model() );
		$multilingual    = self::is_multilingual_site() || count( $language_counts ) > 1;

		// Only Local ships in the free build. The OpenAI and Hugging Face engine
		// cards are added solely when their provider classes are present (the paid
		// build), so the free build advertises only the engine it actually
		// contains rather than dangling locked options.
		$tiers = array(
			'local' => array(
				'tier_num'    => '03',
				'tier_extra'  => 'Default',
				'label'       => __( 'Local (in-browser)', 'findastra' ),
				'short'       => __( 'Local', 'findastra' ),
				'cost'        => __( '$0 forever. In the browser.', 'findastra' ),
				'badge'       => __( 'Free · Default', 'findastra' ),
				'description' => __( 'Runs the embedding model in the shopper\'s browser using transformers.js. No API keys, no monthly cost, no signup. ~33 MB model cached after first visit.', 'findastra' ),
			),
		);
		if ( class_exists( 'FindAstra_Provider_HuggingFace' ) ) {
			$tiers['huggingface'] = array(
				'tier_num'    => '02',
				'tier_extra'  => '',
				'label'       => __( 'Hugging Face (Free)', 'findastra' ),
				'short'       => __( 'Hugging Face', 'findastra' ),
				'cost'        => __( 'Free up to 30k req/mo', 'findastra' ),
				'badge'       => __( 'Bring your own token', 'findastra' ),
				'description' => __( 'BAAI/bge-small-en-v1.5 by default (English, 384d). Multilingual stores can switch to BAAI/bge-m3 (100+ languages, 1024d). Free tier covers ~30k requests/month.', 'findastra' ),
			);
		}
		if ( class_exists( 'FindAstra_Provider_OpenAI' ) ) {
			$tiers['openai'] = array(
				'tier_num'    => '01',
				'tier_extra'  => '',
				'label'       => __( 'OpenAI (Pro)', 'findastra' ),
				'short'       => __( 'OpenAI', 'findastra' ),
				'cost'        => __( '~$2/yr.', 'findastra' ),
				'badge'       => __( 'Bring your own key', 'findastra' ),
				'description' => __( 'Uses text-embedding-3-small via api.openai.com. Typical store cost under $2/year.', 'findastra' ),
			);
		}
		if ( FindAstra_Provider_Mock::is_enabled() ) {
			$tiers[ FindAstra_Provider_Mock::KEY ] = array(
				'tier_num'    => '04',
				'tier_extra'  => 'Test',
				'label'       => __( 'Mock (testing)', 'findastra' ),
				'short'       => __( 'Mock', 'findastra' ),
				'cost'        => __( 'Deterministic. No API.', 'findastra' ),
				'badge'       => __( 'Deterministic — no API', 'findastra' ),
				'description' => __( 'Returns hash-derived vectors for CI testing. Only registered when FINDASTRA_TEST_MODE is true.', 'findastra' ),
			);
		}

		$opt           = self::SETTINGS_OPTION;
		$active_label  = $tiers[ $settings['provider'] ]['short'] ?? $settings['provider'];
		$percent       = $total > 0 ? min( 100, (int) round( ( $indexed / $total ) * 100 ) ) : 0;
		$needs_creds   = $provider->requires_credentials() && ! $provider->is_configured();
		$today_tot     = (int) $totals['today_total'];
		$today_zero    = (int) $totals['today_zero'];
		$today_latency = (int) ( $totals['today_avg_ms'] ?? 0 );
		?>
		<div class="wrap findastra-app">
			<h1 class="screen-reader-text"><?php esc_html_e( 'FindAstra', 'findastra' ); ?></h1>

			<!-- Hero -->
			<div class="fnda-hero">
				<img
					class="fnda-hero__mark"
					src="<?php echo esc_url( FINDASTRA_URL . 'assets/findastra-mark.svg' ); ?>"
					alt=""
					aria-hidden="true"
				/>
				<div class="fnda-hero__body">
					<h2 class="fnda-hero__title"><?php esc_html_e( 'FindAstra', 'findastra' ); ?></h2>
					<p class="fnda-hero__meta">
						<?php esc_html_e( 'AI semantic search for WooCommerce', 'findastra' ); ?>
						·
						<?php
						printf(
							/* translators: 1: indexed count, 2: total products */
							esc_html__( '%1$s of %2$s products indexed', 'findastra' ),
							'<code>' . esc_html( number_format_i18n( $indexed ) ) . '</code>',
							'<code>' . esc_html( number_format_i18n( $total ) ) . '</code>'
						);
						?>
						<?php if ( $last_sync ) : ?>
							·
							<?php
							printf(
								/* translators: %s: human time-diff like "3 minutes" */
								esc_html__( 'last sync %s ago', 'findastra' ),
								'<code>' . esc_html( human_time_diff( $last_sync, time() ) ) . '</code>'
							);
							?>
						<?php endif; ?>
					</p>
				</div>
				<div class="fnda-hero__right">
					<div class="fnda-hero__version">v<?php echo esc_html( FINDASTRA_VERSION ); ?></div>
					<?php
					// Plan badge: Free / Pro / Agency / Unlimited. Pulls from
					// FindAstra_License so the label updates the moment a
					// license is activated or expires — no settings save
					// required. Free buyers see a tinted badge with an
					// upgrade link; paid plans get a solid gold badge.
					$plan           = FindAstra_License::current_plan();
					$plan_label     = ucfirst( $plan );
					$is_free        = FindAstra_License::is_free();
					$upgrade_url    = FindAstra_License::upgrade_url();
					$badge_classes  = 'fnda-hero__plan fnda-hero__plan--' . sanitize_html_class( $plan );
					?>
					<?php if ( $is_free && '' !== $upgrade_url ) : ?>
						<a href="<?php echo esc_url( $upgrade_url ); ?>" class="<?php echo esc_attr( $badge_classes ); ?>" title="<?php esc_attr_e( 'Upgrade to add the OpenAI and Hugging Face engines and multilingual search', 'findastra' ); ?>">
							<?php echo esc_html( $plan_label ); ?>
							<span class="fnda-hero__plan-upgrade"><?php esc_html_e( 'Upgrade →', 'findastra' ); ?></span>
						</a>
					<?php else : ?>
						<div class="<?php echo esc_attr( $badge_classes ); ?>"><?php echo esc_html( $plan_label ); ?></div>
					<?php endif; ?>
					<?php if ( $provider->is_configured() && $indexed > 0 ) : ?>
						<div class="fnda-hero__pill"><?php esc_html_e( 'Active', 'findastra' ); ?></div>
					<?php endif; ?>
				</div>
			</div>

			<!-- Status notice -->
			<?php if ( $needs_creds ) : ?>
				<div class="fnda-notice is-warning">
					<div>
						<b><?php esc_html_e( 'Credentials missing.', 'findastra' ); ?></b>
						<?php esc_html_e( 'Save a key or token in the Engine tab below before indexing.', 'findastra' ); ?>
					</div>
				</div>
			<?php elseif ( 0 === $indexed && $total > 0 ) : ?>
				<div class="fnda-notice">
					<div>
						<b><?php esc_html_e( 'Not indexed yet.', 'findastra' ); ?></b>
						<?php
						printf(
							/* translators: %d: product count */
							esc_html__( '%d products are ready to index. Click "Index now" on the right to build the search index.', 'findastra' ),
							(int) $total
						);
						?>
					</div>
				</div>
			<?php elseif ( $indexed > 0 && $indexed === $total ) : ?>
				<div class="fnda-notice is-success">
					<div>
						<b><?php esc_html_e( 'Index complete.', 'findastra' ); ?></b>
						<?php
						printf(
							/* translators: 1: count, 2: engine name */
							esc_html__( '%1$d products indexed with the %2$s engine. Search is live on your storefront.', 'findastra' ),
							(int) $indexed,
							esc_html( $active_label )
						);
						?>
						<a href="<?php echo esc_url( home_url( '/?s=' ) ); ?>" target="_blank" rel="noopener">
							<?php esc_html_e( 'View live search →', 'findastra' ); ?>
						</a>
					</div>
				</div>
			<?php endif; ?>

				<!-- Tabs -->
			<nav class="fnda-tabs" role="tablist" aria-label="<?php esc_attr_e( 'FindAstra settings', 'findastra' ); ?>">
				<button type="button" data-fnda-tab="general"   role="tab" aria-selected="true"><?php esc_html_e( 'General', 'findastra' ); ?></button>
				<button type="button" data-fnda-tab="engine"    role="tab" aria-selected="false"><?php esc_html_e( 'Engine', 'findastra' ); ?></button>
				<button type="button" data-fnda-tab="search"    role="tab" aria-selected="false"><?php esc_html_e( 'Search', 'findastra' ); ?></button>
				<button type="button" data-fnda-tab="fallback"  role="tab" aria-selected="false"><?php esc_html_e( 'Fallback', 'findastra' ); ?></button>
				<?php if ( $has_analytics ) : ?>
				<button type="button" data-fnda-tab="analytics" role="tab" aria-selected="false"><?php esc_html_e( 'Analytics', 'findastra' ); ?></button>
				<?php endif; ?>
			</nav>

			<div class="fnda-grid">
				<!-- Main column -->
				<div class="fnda-main">
					<form method="post" action="options.php" autocomplete="off">
						<?php settings_fields( self::SETTINGS_GROUP ); ?>

						<!-- General tab -->
						<div class="fnda-tab-panel" data-fnda-tab-panel="general">
							<div class="fnda-card">
								<h3><?php esc_html_e( 'Search engine', 'findastra' ); ?></h3>
								<p class="fnda-card__desc">
									<?php esc_html_e( 'Pick which provider powers the AI search. All three share the same product table. Switch later by re-indexing.', 'findastra' ); ?>
								</p>

								<div class="fnda-engines" data-findastra-tier-grid>
									<?php
									$upgrade_url    = FindAstra_License::upgrade_url();
									foreach ( $tiers as $key => $tier ) :
										$locked = ! FindAstra_Provider_Factory::is_unlocked( (string) $key );
									?>
										<label
											class="fnda-engine findastra-tier <?php echo $settings['provider'] === $key ? 'is-active' : ''; ?><?php echo $locked ? ' is-locked' : ''; ?>"
											data-fnda-engine="<?php echo esc_attr( $key ); ?>"
										>
											<input
												type="radio"
												name="<?php echo esc_attr( $opt ); ?>[provider]"
												value="<?php echo esc_attr( $key ); ?>"
												data-findastra-tier-radio
												<?php checked( $settings['provider'], $key ); ?>
												<?php disabled( $locked ); ?>
											/>
											<div class="fnda-engine__tier">
												<?php
												printf(
													/* translators: 1: tier number */
													esc_html__( 'Tier %1$s', 'findastra' ),
													esc_html( $tier['tier_num'] )
												);
												if ( ! empty( $tier['tier_extra'] ) ) {
													echo ' · ' . esc_html( $tier['tier_extra'] );
												}
												if ( $locked ) {
													echo ' · <span class="fnda-engine__lock">' . esc_html__( 'Pro', 'findastra' ) . '</span>';
												}
												?>
											</div>
											<div class="fnda-engine__name"><?php echo esc_html( $tier['short'] ); ?></div>
											<div class="fnda-engine__cost"><?php echo esc_html( $tier['cost'] ); ?></div>
											<?php if ( $locked && '' !== $upgrade_url ) : ?>
												<a href="<?php echo esc_url( $upgrade_url ); ?>" class="fnda-engine__upgrade">
													<?php esc_html_e( 'Upgrade to unlock', 'findastra' ); ?> →
												</a>
											<?php endif; ?>
										</label>
									<?php endforeach; ?>
								</div>
							</div>

							<div class="fnda-card">
								<h3><?php esc_html_e( 'Quick start', 'findastra' ); ?></h3>
								<p class="fnda-card__desc">
									<?php esc_html_e( 'Three steps after installing.', 'findastra' ); ?>
								</p>
								<ol style="margin: 0 0 0 20px; padding: 0; font-size: 13px; line-height: 1.7; color: var(--ss-fg-2);">
									<li><?php esc_html_e( 'Pick an engine above (Local is free and works without any account).', 'findastra' ); ?></li>
									<li><?php
									printf(
										/* translators: %s: link label "Index now" */
										esc_html__( 'Click %s in the Index status panel on the right.', 'findastra' ),
										'<strong>' . esc_html__( 'Index now', 'findastra' ) . '</strong>'
									);
									?></li>
									<li><?php esc_html_e( 'Open your storefront and search — autocomplete and the results page are wired automatically.', 'findastra' ); ?></li>
								</ol>
							</div>
						</div>

						<!-- Engine tab -->
						<div class="fnda-tab-panel" data-fnda-tab-panel="engine" hidden>
							<div class="fnda-card">
								<h3><?php esc_html_e( 'Credentials', 'findastra' ); ?></h3>
								<p class="fnda-card__desc">
									<?php esc_html_e( 'API keys are stored encrypted at rest and only decrypted at the moment of use. The current engine is highlighted on the General tab.', 'findastra' ); ?>
								</p>
								<div data-findastra-credential-fields data-active-provider="<?php echo esc_attr( $settings['provider'] ); ?>">
									<div class="fnda-field" data-tier-field="local" <?php if ( 'local' !== $settings['provider'] ) echo 'hidden'; ?>>
										<label class="fnda-field__label"><?php esc_html_e( 'How it runs', 'findastra' ); ?></label>
										<div style="font-size: 13px; color: var(--ss-fg-2);">
											<?php esc_html_e( 'On the shopper\'s device. No API key needed.', 'findastra' ); ?>
										</div>
										<p class="fnda-field__help">
											<?php esc_html_e( 'The Local engine runs entirely in the shopper\'s browser via transformers.js. The ~33 MB model is cached after the first visit and never leaves the client.', 'findastra' ); ?>
										</p>
									</div>
									<div class="fnda-field" data-tier-field="huggingface" <?php if ( 'huggingface' !== $settings['provider'] ) echo 'hidden'; ?>>
										<label class="fnda-field__label" for="findastra-hf-token"><?php esc_html_e( 'Hugging Face token', 'findastra' ); ?></label>
										<input
											type="password"
											id="findastra-hf-token"
											name="<?php echo esc_attr( $opt ); ?>[hf_token]"
											value=""
											autocomplete="new-password"
											spellcheck="false"
											placeholder="<?php echo esc_attr( '' !== $hf_masked ? $hf_masked : 'hf_…' ); ?>"
										/>
										<p class="fnda-field__help">
											<?php
											echo '' !== $hf_masked
												? esc_html__( 'A token is saved. Leave blank to keep it, or enter a new one to replace.', 'findastra' )
												: esc_html__( 'Get a free token at huggingface.co/settings/tokens (read access is enough).', 'findastra' );
											?>
										</p>

										<label class="fnda-field__label" for="findastra-hf-model" style="margin-top:14px;"><?php esc_html_e( 'Embedding model', 'findastra' ); ?></label>
										<select
											id="findastra-hf-model"
											name="<?php echo esc_attr( $opt ); ?>[hf_model]"
											data-testid="findastra-hf-model"
										>
											<?php foreach ( ( class_exists( 'FindAstra_Provider_HuggingFace' ) ? FindAstra_Provider_HuggingFace::MODELS : array() ) as $model_id => $model_meta ) : ?>
												<option
													value="<?php echo esc_attr( $model_id ); ?>"
													<?php selected( $settings['hf_model'], $model_id ); ?>
												><?php echo esc_html( $model_meta['label'] ); ?></option>
											<?php endforeach; ?>
										</select>
										<p class="fnda-field__help">
											<?php esc_html_e( 'BGE-small is English-only; pick BGE-M3 for multilingual stores (WPML, Polylang). Switching invalidates the index — click Reindex on the right after saving.', 'findastra' ); ?>
										</p>
									</div>
									<div class="fnda-field" data-tier-field="openai" <?php if ( 'openai' !== $settings['provider'] ) echo 'hidden'; ?>>
										<label class="fnda-field__label" for="findastra-openai-key"><?php esc_html_e( 'OpenAI API key', 'findastra' ); ?></label>
										<input
											type="password"
											id="findastra-openai-key"
											name="<?php echo esc_attr( $opt ); ?>[openai_key]"
											value=""
											autocomplete="new-password"
											spellcheck="false"
											placeholder="<?php echo esc_attr( '' !== $openai_masked ? $openai_masked : 'sk-…' ); ?>"
										/>
										<p class="fnda-field__help">
											<?php
											echo '' !== $openai_masked
												? esc_html__( 'A key is saved. Leave blank to keep it, or enter a new one to replace.', 'findastra' )
												: esc_html__( 'Starts with sk-… or sk-proj-…  · roughly $0.10 per 10,000 products indexed.', 'findastra' );
											?>
										</p>
									</div>
									<?php if ( FindAstra_Provider_Mock::is_enabled() ) : ?>
										<div class="fnda-field" data-tier-field="mock" <?php if ( 'mock' !== $settings['provider'] ) echo 'hidden'; ?>>
											<label class="fnda-field__label"><?php esc_html_e( 'Test mode', 'findastra' ); ?></label>
											<div style="font-size: 13px; color: var(--ss-fg-2);">
												<?php esc_html_e( 'Deterministic hashed bag-of-tokens — used by CI runs only.', 'findastra' ); ?>
											</div>
											<p class="fnda-field__help">
												<?php esc_html_e( 'This tier is only visible because FINDASTRA_TEST_MODE is defined in wp-config.php.', 'findastra' ); ?>
											</p>
										</div>
									<?php endif; ?>
								</div>
							</div>
						</div>

						<!-- Search tab -->
						<div class="fnda-tab-panel" data-fnda-tab-panel="search" hidden>
							<?php if ( $multilingual && class_exists( 'FindAstra_Multilingual' ) ) : ?>
								<div class="fnda-card" data-testid="findastra-languages-section">
									<h3><?php esc_html_e( 'Languages', 'findastra' ); ?></h3>
									<p class="fnda-card__desc">
										<?php
										if ( ! empty( $language_counts ) ) {
											esc_html_e( 'Per-language index counts for the active engine. WPML / Polylang language tags are detected automatically at index time, and shopper searches on translated pages are scoped to that language only.', 'findastra' );
										} else {
											esc_html_e( 'A translation plugin is active but no products have been indexed yet — click Reindex on the right.', 'findastra' );
										}
										?>
									</p>
									<?php if ( ! empty( $language_counts ) ) : ?>
										<div class="fnda-status" style="margin: 0; padding: 0; background: transparent; border: 0;">
											<?php foreach ( $language_counts as $lang => $n ) : ?>
												<div class="fnda-status__row">
													<span>
														<?php
														if ( '' === $lang ) {
															esc_html_e( 'Untagged (site default)', 'findastra' );
														} else {
															echo '<code>' . esc_html( $lang ) . '</code>';
														}
														?>
													</span>
													<span class="v"><?php echo esc_html( number_format_i18n( $n ) ); ?></span>
												</div>
											<?php endforeach; ?>
										</div>
									<?php endif; ?>
									<p class="fnda-field__help" style="margin-top:10px;">
										<?php
										if ( class_exists( 'FindAstra_Provider_HuggingFace' ) && $provider->key() === FindAstra_Provider_HuggingFace::KEY && $provider->model() === FindAstra_Provider_HuggingFace::MODEL_DEFAULT ) {
											esc_html_e( 'Active model is English-only (BGE-small). For accurate cross-language results, switch to BGE-M3 in the Engine tab and reindex.', 'findastra' );
										} elseif ( $provider->key() === FindAstra_Provider_Local::KEY ) {
											esc_html_e( 'The Local engine\'s bundled model is English-only in v0.10. WPML / Polylang stores get better results from the Hugging Face engine with BGE-M3, or OpenAI (multilingual by default).', 'findastra' );
										}
										?>
									</p>
								</div>
							<?php endif; ?>

							<div class="fnda-card">
								<h3><?php esc_html_e( 'Theme integration', 'findastra' ); ?></h3>
								<p class="fnda-card__desc">
									<?php esc_html_e( 'How FindAstra plugs into your theme\'s existing search experience. Both options work on classic and block themes without theme edits.', 'findastra' ); ?>
								</p>
								<div class="fnda-field">
									<label class="fnda-toggle">
										<input
											type="checkbox"
											name="<?php echo esc_attr( $opt ); ?>[autocomplete_attach]"
											value="1"
											data-testid="findastra-toggle-autocomplete"
											<?php checked( '1', (string) ( $settings['autocomplete_attach'] ?? '1' ) ); ?>
										/>
										<span class="fnda-toggle__text">
											<span class="fnda-toggle__title"><?php esc_html_e( 'Live suggestions', 'findastra' ); ?></span>
											<p class="fnda-toggle__help"><?php esc_html_e( 'Attach a semantic-suggestions dropdown to existing search inputs on the site. Detects them automatically — no theme edits needed.', 'findastra' ); ?></p>
										</span>
									</label>
								</div>
								<div class="fnda-field">
									<label class="fnda-toggle">
										<input
											type="checkbox"
											name="<?php echo esc_attr( $opt ); ?>[hijack_results_page]"
											value="1"
											data-testid="findastra-toggle-hijack"
											<?php checked( '1', (string) ( $settings['hijack_results_page'] ?? '1' ) ); ?>
										/>
										<span class="fnda-toggle__text">
											<span class="fnda-toggle__title"><?php esc_html_e( 'Search results pages', 'findastra' ); ?></span>
											<p class="fnda-toggle__help"><?php esc_html_e( 'Use FindAstra ranking when shoppers land on a product search results page. Your theme still renders the page normally — only the product order is replaced.', 'findastra' ); ?></p>
										</span>
									</label>
								</div>
							</div>

							<?php
							// Surface the ACTIVE engine's built-in gate defaults so the
							// copy + placeholders match reality (each model calibrates
							// differently — OpenAI is 0.40/0.33/0.15, bge is 0.60/0.55/0.12).
							$fnda_gate_provider = FindAstra_Provider_Factory::current();
							$fnda_gate_defaults = $fnda_gate_provider->default_gates();
							$fnda_gd_top        = number_format( (float) ( $fnda_gate_defaults['top'] ?? 0.60 ), 2 );
							$fnda_gd_min        = number_format( (float) ( $fnda_gate_defaults['min'] ?? 0.55 ), 2 );
							$fnda_gd_window     = number_format( (float) ( $fnda_gate_defaults['window'] ?? 0.12 ), 2 );
							$fnda_gate_label    = $fnda_gate_provider->label();
							?>
							<div class="fnda-card">
								<h3><?php esc_html_e( 'Match-quality gates', 'findastra' ); ?></h3>
								<p class="fnda-card__desc">
									<?php
									printf(
										/* translators: 1: active engine name, 2: top-score default, 3: per-hit default, 4: window default */
										esc_html__( 'FindAstra auto-tunes relevance on every search, so most stores never need to touch these. They are an advanced override of the built-in thresholds for your current engine (%1$s: %2$s / %3$s / %4$s). Leave all three blank to keep the automatic behaviour.', 'findastra' ),
										esc_html( $fnda_gate_label ),
										esc_html( $fnda_gd_top ),
										esc_html( $fnda_gd_min ),
										esc_html( $fnda_gd_window )
									);
									?>
								</p>
								<p class="fnda-card__desc" style="margin-top:8px;padding:8px 12px;border-left:3px solid #d63638;background:#fcf0f1;color:#8a2424;">
									<?php esc_html_e( 'Advanced — only change these if you understand cosine-similarity thresholds. Set too high, search returns nothing; too low, it surfaces irrelevant products. When unsure, leave them blank.', 'findastra' ); ?>
								</p>
								<div class="fnda-field__inline">
									<div>
										<label class="fnda-field__label" for="findastra-min-top-score"><?php esc_html_e( 'Top-score gate', 'findastra' ); ?></label>
										<input
											type="text"
											id="findastra-min-top-score"
											name="<?php echo esc_attr( $opt ); ?>[min_top_score]"
											value="<?php echo esc_attr( (string) $settings['min_top_score'] ); ?>"
											placeholder="<?php echo esc_attr( $fnda_gd_top ); ?>"
											inputmode="decimal"
										/>
									</div>
									<div>
										<label class="fnda-field__label" for="findastra-min-score"><?php esc_html_e( 'Per-hit floor', 'findastra' ); ?></label>
										<input
											type="text"
											id="findastra-min-score"
											name="<?php echo esc_attr( $opt ); ?>[min_score]"
											value="<?php echo esc_attr( (string) $settings['min_score'] ); ?>"
											placeholder="<?php echo esc_attr( $fnda_gd_min ); ?>"
											inputmode="decimal"
										/>
									</div>
									<div>
										<label class="fnda-field__label" for="findastra-score-window"><?php esc_html_e( 'Window from top', 'findastra' ); ?></label>
										<input
											type="text"
											id="findastra-score-window"
											name="<?php echo esc_attr( $opt ); ?>[score_window]"
											value="<?php echo esc_attr( (string) $settings['score_window'] ); ?>"
											placeholder="<?php echo esc_attr( $fnda_gd_window ); ?>"
											inputmode="decimal"
										/>
									</div>
								</div>
								<p class="fnda-field__help" style="margin-top:10px;">
									<?php esc_html_e( 'Top-score: the best hit must reach this for any results to count. Per-hit: absolute floor every hit must clear. Window: how far below the top hit we still accept. On top of these, search also shows results whenever one product clearly stands out from the rest — automatically, with no settings.', 'findastra' ); ?>
								</p>
							</div>
						</div>

						<!-- Fallback tab -->
						<div class="fnda-tab-panel" data-fnda-tab-panel="fallback" hidden>
							<div class="fnda-card">
								<h3><?php esc_html_e( 'Fallback products', 'findastra' ); ?></h3>
								<p class="fnda-card__desc">
									<?php esc_html_e( 'When a search returns no good matches, shoppers see these products instead under a "Popular products" header. Leave blank to auto-pick featured products, then best-sellers, then most recent.', 'findastra' ); ?>
								</p>
								<div class="fnda-field">
									<label class="fnda-field__label" for="findastra-fallback-ids"><?php esc_html_e( 'Product IDs', 'findastra' ); ?></label>
									<input
										type="text"
										id="findastra-fallback-ids"
										name="<?php echo esc_attr( $opt ); ?>[fallback_product_ids]"
										value="<?php echo esc_attr( (string) $settings['fallback_product_ids'] ); ?>"
										placeholder="42, 137, 1024"
										data-testid="findastra-fallback-ids"
									/>
									<p class="fnda-field__help">
										<?php esc_html_e( 'Comma-separated WooCommerce product IDs, in display order.', 'findastra' ); ?>
									</p>
								</div>
							</div>
						</div>

						<?php if ( $has_analytics ) : ?>
						<!-- Analytics tab -->
						<div class="fnda-tab-panel" data-fnda-tab-panel="analytics" hidden>
							<div class="fnda-card">
								<h3><?php esc_html_e( 'Search analytics', 'findastra' ); ?></h3>
								<p class="fnda-card__desc">
									<?php
									if ( 0 === $today_tot ) {
										esc_html_e( 'No searches recorded today yet.', 'findastra' );
									} elseif ( 0 === $today_zero ) {
										printf(
											/* translators: %d: number of searches today */
											esc_html( _n( '%d search today, all returned products.', '%d searches today, all returned products.', $today_tot, 'findastra' ) ),
											(int) $today_tot
										);
									} else {
										printf(
											/* translators: 1: zero-result count, 2: total */
											esc_html__( '%1$d of %2$d searches today returned no matches — see Catalog gaps for shopper demand you do not yet stock.', 'findastra' ),
											(int) $today_zero,
											(int) $today_tot
										);
									}
									?>
								</p>
								<div class="fnda-analytics" data-testid="findastra-analytics">
									<div>
										<h3><?php esc_html_e( 'Recent searches', 'findastra' ); ?></h3>
										<?php $recent = $log->recent( 10, null ); ?>
										<?php if ( empty( $recent ) ) : ?>
											<p class="fnda-analytics__empty"><?php esc_html_e( 'No searches recorded yet.', 'findastra' ); ?></p>
										<?php else : ?>
											<ol>
												<?php foreach ( $recent as $row ) : ?>
													<li>
														<code><?php echo esc_html( $row['query'] ); ?></code>
														—
														<?php
														printf(
															/* translators: %d: number of results for a past search */
														esc_html( _n( '%d result', '%d results', (int) $row['result_count'], 'findastra' ) ),
															(int) $row['result_count']
														);
														?>
													</li>
												<?php endforeach; ?>
											</ol>
										<?php endif; ?>
									</div>
									<div>
										<h3><?php esc_html_e( 'Catalog gaps', 'findastra' ); ?></h3>
										<p class="fnda-analytics__desc">
											<?php esc_html_e( 'Searches that returned nothing — products your shoppers want but you do not stock.', 'findastra' ); ?>
										</p>
										<?php $zeros = $log->zero_result( 10, null ); ?>
										<?php if ( empty( $zeros ) ) : ?>
											<p class="fnda-analytics__empty"><?php esc_html_e( 'Nothing here yet — every search has returned at least one product.', 'findastra' ); ?></p>
										<?php else : ?>
											<ol>
												<?php foreach ( $zeros as $row ) : ?>
													<li>
														<code><?php echo esc_html( $row['query'] ); ?></code>
														<?php if ( ! empty( $row['hits'] ) ) : ?>
															<small>
																(<?php
																printf(
																	/* translators: %d: number of times shoppers searched this zero-result query */
															esc_html( _n( '%d time', '%d times', (int) $row['hits'], 'findastra' ) ),
																	(int) $row['hits']
																);
																?>)
															</small>
														<?php endif; ?>
													</li>
												<?php endforeach; ?>
											</ol>
										<?php endif; ?>
									</div>
								</div>
							</div>
						</div>
						<?php endif; ?>

						<div class="fnda-form-actions">
							<input
								type="submit"
								name="submit"
								class="fnda-btn fnda-btn--primary"
								value="<?php esc_attr_e( 'Save settings', 'findastra' ); ?>"
							/>
							<span style="font-size:12px; color: var(--ss-fg-3);">
								<?php esc_html_e( 'Settings persist across all tabs in one save.', 'findastra' ); ?>
							</span>
						</div>
					</form>
				</div>

				<!-- Sidebar -->
				<div class="fnda-side">
					<div class="fnda-status"
						data-findastra-admin
						data-server-side="<?php echo $provider->is_server_side() ? '1' : '0'; ?>"
						data-needs-credentials="<?php echo $provider->requires_credentials() ? '1' : '0'; ?>"
						data-configured="<?php echo $provider->is_configured() ? '1' : '0'; ?>"
						data-background-index="<?php echo ( $provider->is_server_side() && FindAstra_Background_Indexer::available() ) ? '1' : '0'; ?>"
					>
						<h4><?php esc_html_e( 'Index status', 'findastra' ); ?></h4>
						<div class="fnda-progress">
							<div class="fnda-progress__bar" style="width: <?php echo esc_attr( (string) $percent ); ?>%;"></div>
						</div>
						<div class="fnda-progress__meta">
							<span><?php echo esc_html( number_format_i18n( $indexed ) . ' / ' . number_format_i18n( $total ) ); ?></span>
							<span><?php echo esc_html( $percent ); ?>%</span>
						</div>

						<div class="fnda-status__row" style="margin-top: 12px; border-top: 1px solid var(--ss-line-2); padding-top: 10px;">
							<span><?php esc_html_e( 'Engine', 'findastra' ); ?></span>
							<span class="v" data-testid="findastra-current-provider">
								<?php echo esc_html( $active_label ); ?>
								<span class="screen-reader-text">(<?php echo esc_html( (string) $settings['provider'] ); ?>)</span>
							</span>
						</div>
						<div class="fnda-status__row">
							<span><?php esc_html_e( 'Model', 'findastra' ); ?></span>
							<span class="v"><?php echo esc_html( basename( $provider->model() ) ); ?></span>
						</div>
						<div class="fnda-status__row" data-testid="findastra-index-stats">
							<span><?php esc_html_e( 'Indexed', 'findastra' ); ?></span>
							<span class="v"><?php echo esc_html( number_format_i18n( $indexed ) . ' / ' . number_format_i18n( $total ) ); ?></span>
						</div>
						<?php if ( $last_sync ) : ?>
							<div class="fnda-status__row">
								<span><?php esc_html_e( 'Last sync', 'findastra' ); ?></span>
								<span class="v"><?php echo esc_html( human_time_diff( $last_sync, time() ) ); ?></span>
							</div>
						<?php endif; ?>
						<div class="fnda-status__row">
							<span><?php esc_html_e( 'Health', 'findastra' ); ?></span>
							<span class="v <?php echo $needs_creds ? 'warn' : ( $indexed > 0 ? 'ok' : '' ); ?>">
								<?php if ( $needs_creds ) : ?>
									● <?php esc_html_e( 'Configure', 'findastra' ); ?>
								<?php elseif ( $indexed > 0 ) : ?>
									● <?php esc_html_e( 'OK', 'findastra' ); ?>
								<?php else : ?>
									● <?php esc_html_e( 'Not indexed', 'findastra' ); ?>
								<?php endif; ?>
							</span>
						</div>

						<button
							type="button"
							class="fnda-btn fnda-btn--primary fnda-btn--block fnda-btn--small"
							style="margin-top: 14px;"
							data-findastra-index-button
							<?php disabled( $needs_creds ); ?>
						><?php echo 0 === $indexed ? esc_html__( 'Index now', 'findastra' ) : esc_html__( 'Reindex store', 'findastra' ); ?></button>
						<button
							type="button"
							class="fnda-btn fnda-btn--ghost fnda-btn--block fnda-btn--small"
							style="margin-top: 6px;"
							data-findastra-reset-button
						><?php esc_html_e( 'Reset index', 'findastra' ); ?></button>

						<div class="fnda-index-progress" data-findastra-progress aria-live="polite"></div>
						<?php if ( $needs_creds ) : ?>
							<div class="fnda-index-warning"><?php esc_html_e( 'Save a key or token in the Engine tab before indexing.', 'findastra' ); ?></div>
						<?php endif; ?>
					</div>

					<?php if ( $has_analytics ) : ?>
					<div class="fnda-status">
						<h4><?php esc_html_e( 'Today', 'findastra' ); ?></h4>
						<div class="fnda-status__row">
							<span><?php esc_html_e( 'Searches', 'findastra' ); ?></span>
							<span class="v"><?php echo esc_html( number_format_i18n( $today_tot ) ); ?></span>
						</div>
						<div class="fnda-status__row">
							<span><?php esc_html_e( 'Zero-results', 'findastra' ); ?></span>
							<span class="v <?php echo $today_zero > 0 ? 'warn' : ''; ?>"><?php echo esc_html( number_format_i18n( $today_zero ) ); ?></span>
						</div>
						<?php if ( $today_latency > 0 ) : ?>
							<div class="fnda-status__row">
								<span><?php esc_html_e( 'Avg latency', 'findastra' ); ?></span>
								<span class="v"><?php
								/* translators: %d: milliseconds */
								printf( esc_html__( '%d ms', 'findastra' ), (int) $today_latency );
								?></span>
							</div>
						<?php endif; ?>
					</div>
					<?php endif; ?>
				</div>
			</div>
		</div>
		<?php
	}
}
