Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
81.16% covered (warning)
81.16%
698 / 860
61.18% covered (warning)
61.18%
52 / 85
CRAP
0.00% covered (danger)
0.00%
0 / 1
Search_Blocks
81.16% covered (warning)
81.16%
698 / 860
61.18% covered (warning)
61.18%
52 / 85
936.98
0.00% covered (danger)
0.00%
0 / 1
 init
97.30% covered (success)
97.30%
36 / 37
0.00% covered (danger)
0.00%
0 / 1
12
 owns_search_results
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
2
 is_tracking_disabled
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
3
 filter__posts_pre_query
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
3
 is_block_template_overlay_enabled
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 is_block_template_overlay_filter_on
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 is_free_plan
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 reset_is_free_plan_cache
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 supports_paid_search
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
3
 set_supports_paid_search_for_testing
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 reset_supports_paid_search_cache
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 woocommerce_blocks_enabled
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
3
 woocommerce_version_supported
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
3
 set_woocommerce_blocks_enabled_for_testing
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 reset_woocommerce_blocks_enabled_cache
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 woocommerce_search_template_override_enabled
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 is_woocommerce_product_search
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
3
 woocommerce_only_block_names
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
1
 is_woocommerce_only_block
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 custom_taxonomy_map
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 resolve_taxonomy_slot
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 reset_custom_taxonomy_map_cache
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 supported_custom_taxonomies
88.89% covered (warning)
88.89%
16 / 18
0.00% covered (danger)
0.00%
0 / 1
4.02
 get_search_param_name
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
3
 enqueue_editor_assets
96.88% covered (success)
96.88%
31 / 32
0.00% covered (danger)
0.00%
0 / 1
3
 widget_area_hiding_blocks
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
5
 register_block_category
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
12
 register_blocks
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
12
 load_block_styles_only_where_rendered
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
6
 register_store_script_module
92.31% covered (success)
92.31%
12 / 13
0.00% covered (danger)
0.00%
0 / 1
3.00
 same_origin_script_module_src
100.00% covered (success)
100.00%
19 / 19
100.00% covered (success)
100.00%
1 / 1
8
 inject_filter_checkbox_variations
100.00% covered (success)
100.00%
98 / 98
100.00% covered (success)
100.00%
1 / 1
7
 register_patterns
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
42
 pattern_content_from_template
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
3
 get_search_template_content
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 register_search_template
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
4
 should_use_product_overlay
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
2
 get_overlay_template_content
78.57% covered (warning)
78.57%
11 / 14
0.00% covered (danger)
0.00%
0 / 1
7.48
 reset_overlay_template_content_cache
66.67% covered (warning)
66.67%
2 / 3
0.00% covered (danger)
0.00%
0 / 1
3.33
 print_block_template_overlay
0.00% covered (danger)
0.00%
0 / 19
0.00% covered (danger)
0.00%
0 / 1
12
 enqueue_block_template_overlay_assets
0.00% covered (danger)
0.00%
0 / 21
0.00% covered (danger)
0.00%
0 / 1
12
 print_theme_token_sampler
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
3
 block_template_overlay_inline_css
n/a
0 / 0
n/a
0 / 0
1
 enqueue_search_page_assets
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 enqueue_search_layout_style
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
6
 search_layout_inline_css
n/a
0 / 0
n/a
0 / 0
1
 get_product_search_template_content
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 substitute_template_placeholders
91.67% covered (success)
91.67%
11 / 12
0.00% covered (danger)
0.00%
0 / 1
2.00
 resolve_chrome_slugs
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 sync_filters_popover_content
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
5
 find_block_by_name
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
5
 replace_block_inner_content
88.89% covered (warning)
88.89%
8 / 9
0.00% covered (danger)
0.00%
0 / 1
5.03
 replace_block_template
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
3
 register_product_search_template
84.62% covered (warning)
84.62%
11 / 13
0.00% covered (danger)
0.00%
0 / 1
4.06
 get_parent_plugin_slug
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
3
 prepend_search_template
100.00% covered (success)
100.00%
14 / 14
100.00% covered (success)
100.00%
1 / 1
5
 route_classic_theme_search_template
92.86% covered (success)
92.86%
13 / 14
0.00% covered (danger)
0.00%
0 / 1
10.04
 get_classic_theme_search_body
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 get_classic_theme_product_search_body
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 strip_top_level_template_parts
66.67% covered (warning)
66.67%
2 / 3
0.00% covered (danger)
0.00%
0 / 1
2.15
 get_classic_theme_layout_style
n/a
0 / 0
n/a
0 / 0
1
 set_block_templates_active_for_testing
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 block_templates_active
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 route_woocommerce_product_search_template
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
4
 seed_interactivity_state
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
6
 build_seed_state
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 collect_filter_configs_from_post
78.57% covered (warning)
78.57%
11 / 14
0.00% covered (danger)
0.00%
0 / 1
8.63
 post_content_has_filter_block
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
3
 filter_block_helpers
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
4
 walk_blocks_for_filter_configs
84.62% covered (warning)
84.62%
11 / 13
0.00% covered (danger)
0.00%
0 / 1
7.18
 build_initial_state
100.00% covered (success)
100.00%
56 / 56
100.00% covered (success)
100.00%
1 / 1
14
 get_instant_search_query_options
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 build_stock_status_labels
77.78% covered (warning)
77.78%
7 / 9
0.00% covered (danger)
0.00%
0 / 1
4.18
 block_directories
93.33% covered (success)
93.33%
14 / 15
0.00% covered (danger)
0.00%
0 / 1
8.02
 is_initial_loading
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
4
 reset_initial_loading_cache
66.67% covered (warning)
66.67%
2 / 3
0.00% covered (danger)
0.00%
0 / 1
3.33
 pre_hydration_filter_view
66.67% covered (warning)
66.67%
10 / 15
0.00% covered (danger)
0.00%
0 / 1
3.33
 emit_filter_wrapper_context
90.00% covered (success)
90.00%
9 / 10
0.00% covered (danger)
0.00%
0 / 1
2.00
 normalize_display_style
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 build_initial_strings
51.35% covered (warning)
51.35%
19 / 37
0.00% covered (danger)
0.00%
0 / 1
4.04
 build_ai_extended_loading_hints
51.43% covered (warning)
51.43%
18 / 35
0.00% covered (danger)
0.00%
0 / 1
2.46
 parse_url_search_query
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
2
 has_search_param
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
2
 parse_url_sort
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
3
 parse_url_price_range
91.67% covered (success)
91.67%
11 / 12
0.00% covered (danger)
0.00%
0 / 1
7.03
 parse_price_bound
77.78% covered (warning)
77.78%
7 / 9
0.00% covered (danger)
0.00%
0 / 1
7.54
 parse_url_filters
96.77% covered (success)
96.77%
30 / 31
0.00% covered (danger)
0.00%
0 / 1
10
 parse_url_filter_logic
43.75% covered (danger)
43.75%
7 / 16
0.00% covered (danger)
0.00%
0 / 1
27.80
1<?php
2/**
3 * Search Blocks: Interactivity API block registration and state initialization.
4 *
5 * @package automattic/jetpack-search
6 */
7
8namespace Automattic\Jetpack\Search;
9
10use Automattic\Jetpack\Status;
11
12/**
13 * Registers Jetpack Search Interactivity API blocks and initializes their shared state.
14 */
15class Search_Blocks {
16
17    /**
18     * Reserved query params (mirrors `RESERVED_PARAMS` in `store/url-state.js`).
19     * `s` is the WP search route key; `q` is what the inline blocks use on
20     * non-search pages (see `get_search_param_name()`). Neither may be parsed as a filter key.
21     */
22    const RESERVED_QUERY_PARAMS = array( 's', 'q', 'orderby', 'min_price', 'max_price' );
23
24    /**
25     * Query-string param for inline search on non-search pages (e.g. `/about/?q=boots`).
26     * Not `s`, because on singular pages WP's `WP_Query::get_posts()` AND's a
27     * `post_content LIKE` clause into the lookup and 404s on refresh. See
28     * `docs/explorations/embedded-search-refresh-404.md` (RSM-1754).
29     */
30    const NON_SEARCH_QUERY_PARAM = 'q';
31
32    /**
33     * Jetpack Search page template slug. Distinct from WP's `search` slug so a
34     * block theme's `search.html` doesn't dedupe ours; `search_template_hierarchy`
35     * prepends this slug so it still wins on `/?s=...`.
36     */
37    const SEARCH_TEMPLATE_SLUG = 'jetpack-search';
38
39    /**
40     * Jetpack product-search template slug. Separate from `SEARCH_TEMPLATE_SLUG`
41     * so it gets its own Site Editor entry.
42     */
43    const PRODUCT_SEARCH_TEMPLATE_SLUG = 'jetpack-search-product-results';
44
45    /**
46     * Mirror of `ProductSearchResultsTemplate::SLUG`, inlined to avoid a hard
47     * dependency on the WooCommerce class.
48     */
49    const WC_PRODUCT_SEARCH_TEMPLATE_SLUG = 'product-search-results';
50
51    /**
52     * Lowest WC version that registers the `product-search-results` template
53     * (WC 6.5 bundled WC Blocks 7.4, the release that first added it). Below
54     * this, WC-only Search features have nothing to front and the gate stays closed.
55     */
56    const MIN_WOOCOMMERCE_VERSION = '6.5.0';
57
58    /**
59     * Per-request memo for `is_initial_loading()`. Lifted out of a method-local
60     * `static` so tests can clear it via `reset_initial_loading_cache()`;
61     * otherwise URL state from the first test leaks into subsequent ones.
62     *
63     * @var bool|null
64     */
65    private static $is_initial_loading_cache = null;
66
67    /**
68     * Per-request memo for `get_overlay_template_content()`, keyed `default` /
69     * `product`. Lifted out of a method-local `static` so tests can clear it via
70     * `reset_overlay_template_content_cache()` — otherwise a CPT-customized
71     * overlay saved mid-test would be pinned by an earlier bundled-file read.
72     *
73     * @var array<string,string>
74     */
75    private static $overlay_template_content_cache = array();
76
77    /**
78     * Per-request memo for `is_free_plan()`. Avoids the cold-cache hazard where
79     * `Plan::get_plan_info()` falls back to a synchronous WPCOM HTTP call —
80     * render callbacks hit the plan gate on every inner render.
81     *
82     * @var bool|null
83     */
84    private static $is_free_plan_cache = null;
85
86    /**
87     * Per-request memo for `supports_paid_search()`. Separate from
88     * `is_free_plan_cache` because the two answers can disagree: a site with
89     * no plan info is neither on the free plan nor on a paid one.
90     *
91     * @var bool|null
92     */
93    private static $supports_paid_search_cache = null;
94
95    /**
96     * Per-request memo for `woocommerce_blocks_enabled()`. Centralized so every
97     * gate (registration, render, editor config, IA store seed) shares one probe.
98     *
99     * @var bool|null
100     */
101    private static $woocommerce_blocks_enabled_cache = null;
102
103    /**
104     * Per-request memo for `supported_custom_taxonomies()`. Derived from the
105     * Sync allowlist intersected with registered taxonomies and unioned with
106     * the map's user-facing keys — same inputs every request.
107     *
108     * @var string[]|null
109     */
110    private static $supported_custom_taxonomies_cache = null;
111
112    /**
113     * Cached rendered overlay-template HTML. Filled during `wp_enqueue_scripts`
114     * so the embedded blocks' view-module enqueues land before
115     * `wp_print_import_map()` (footer priority 1) — see AGENTS.md
116     * § Hydration & SSR seeding.
117     *
118     * @var string|null
119     */
120    private static $block_template_overlay_rendered_html = null;
121
122    /**
123     * Register block types and hook into WordPress.
124     *
125     * Two gates apply: the caller (`Initializer`) gates everything behind the
126     * `jetpack_search_blocks_enabled` feature flag, and within this method the
127     * template-takeover surface (registering the Search template and prepending
128     * it to `search_template_hierarchy`) is additionally gated on the saved
129     * experience being `'embedded'` — only Embedded should override the theme's
130     * `search.html`. Block registration, editor assets, and IA state seeding
131     * always run so blocks inserted anywhere (post content, widgets, custom
132     * templates) get their base seed.
133     */
134    public static function init() {
135        add_action( 'init', array( static::class, 'register_blocks' ) );
136        add_action( 'wp_enqueue_scripts', array( static::class, 'load_block_styles_only_where_rendered' ), 9 );
137        add_filter( 'block_categories_all', array( static::class, 'register_block_category' ) );
138        add_action( 'enqueue_block_editor_assets', array( static::class, 'enqueue_editor_assets' ) );
139        add_action( 'wp_body_open', array( static::class, 'print_theme_token_sampler' ) );
140        // Relativize `jetpack-search/*` Script Module URLs whose host matches
141        // the site canonical so the rendered `<script type="module">` is
142        // same-origin with the page. ES modules go through CORS even without
143        // a `crossorigin` attribute, and `wp-content/*` typically lacks the
144        // `Access-Control-Allow-Origin` header — see
145        // `same_origin_script_module_src()`.
146        add_filter( 'script_module_loader_src', array( static::class, 'same_origin_script_module_src' ), 10, 2 );
147        Custom_Taxonomy_Slot_Mapping::init();
148        // Both hooks needed; see AGENTS.md § Hydration & SSR seeding.
149        add_action( 'template_redirect', array( static::class, 'seed_interactivity_state' ) );
150        add_action( 'wp_enqueue_scripts', array( static::class, 'seed_interactivity_state' ) );
151
152        $experience = ( new Module_Control() )->get_experience();
153
154        if ( Module_Control::EXPERIENCE_EMBEDDED === $experience ) {
155            if ( static::block_templates_active() ) {
156                // Block themes: register the template and front it via the FSE hierarchy filter.
157                add_action( 'init', array( static::class, 'register_search_template' ) );
158                add_filter( 'search_template_hierarchy', array( static::class, 'prepend_search_template' ) );
159                add_action( 'wp_enqueue_scripts', array( static::class, 'enqueue_search_page_assets' ) );
160                Theme_Chrome_Slug_Resolver::register_hooks();
161            } else {
162                // Classic themes: no FSE hierarchy to prepend to, so swap the
163                // resolved template path via `template_include`. The block markup
164                // renders inside the theme's `get_header()`/`get_footer()`.
165                //
166                // Priority 20: WooCommerce's `WC_Template_Loader::template_loader`
167                // hooks at priority 10 and rewrites the path to `archive-product.php`
168                // on product-archive requests — that includes product search. We
169                // need to run *after* WC so the override actually sticks; running
170                // at 10 (same priority, later registration) is order-of-load
171                // dependent. Higher priorities (anything > 20 used by chrome
172                // filters) aren't relevant — nothing else swaps the path.
173                add_filter( 'template_include', array( static::class, 'route_classic_theme_search_template' ), 20 );
174                // No Site Editor entry on classic themes; the singleton CPTs give
175                // authors the standard block editor on hidden posts instead. Both
176                // init regardless of the WooCommerce override option so admins can
177                // pre-customize either template before activating the relevant
178                // surface — matching `Search_Template`'s "expose URLs before
179                // activation" rule. The override option still gates the actual
180                // front-end render path in `route_classic_theme_search_template()`.
181                Search_Template::init();
182                Product_Search_Template::init();
183            }
184        }
185
186        // Inline on a classic theme: the theme renders regular searches, but a
187        // WooCommerce product search can still be routed to the Jetpack product
188        // shim. `route_classic_theme_search_template()` is product-only for
189        // Inline (it bails on regular searches unless Embedded); the block-theme
190        // Inline path is covered by the `search_template_hierarchy` route below.
191        // Init the product CPT regardless of the override so admins can
192        // pre-customize it (expose-before-activation, as in the Embedded branch).
193        if (
194            Module_Control::EXPERIENCE_INLINE === $experience
195            && ! static::block_templates_active()
196        ) {
197            add_filter( 'template_include', array( static::class, 'route_classic_theme_search_template' ), 20 );
198            Product_Search_Template::init();
199        }
200
201        // Blocks render results client-side, so the server-side search is wasted work.
202        // (Classic/Instant init is also suppressed in `Initializer::init_search_blocks()`.)
203        if ( ! is_admin() && static::owns_search_results() ) {
204            add_filter( 'posts_pre_query', array( static::class, 'filter__posts_pre_query' ), 10, 2 );
205        }
206
207        // Priority 20: after WC's priority-10 prepend so the result is load-order
208        // independent. Gated to server-rendered experiences (Embedded / Inline) —
209        // Overlay intercepts client-side, and a stale option from a since-switched
210        // experience must not keep rerouting the template hierarchy.
211        if (
212            static::woocommerce_search_template_override_enabled()
213            && in_array( $experience, array( Module_Control::EXPERIENCE_EMBEDDED, Module_Control::EXPERIENCE_INLINE ), true )
214        ) {
215            add_action( 'init', array( static::class, 'register_product_search_template' ) );
216            add_filter( 'search_template_hierarchy', array( static::class, 'route_woocommerce_product_search_template' ), 20 );
217            // Inline experience doesn't go through the EMBEDDED branch above, so
218            // hook the page-template CSS enqueue here too. Idempotent on EMBEDDED
219            // — `add_action` dedupes same callback at same priority.
220            add_action( 'wp_enqueue_scripts', array( static::class, 'enqueue_search_page_assets' ) );
221        }
222
223        // Two-tier gate: register the editable template CPT + admin-init editor
224        // handler whenever the operator filter is on, so admins can edit the
225        // overlay template *before* opting into the blocks Overlay experience
226        // (e.g. preview the editor from the Beta card while the preact Overlay
227        // is still the active arm — without this split, the editorUrl seeded
228        // into the React initial state at page load would be null and the
229        // link would become a no-op once the user switched to the Beta card
230        // without a page refresh). The front-end render hooks stay gated on
231        // the active experience — they only paint the overlay when the user
232        // has actually committed to it.
233        if ( static::is_block_template_overlay_filter_on() ) {
234            Overlay_Template::init();
235            // The product overlay only renders on a Woo store, so its editable
236            // CPT is pointless off Woo. Init regardless of the override option
237            // (parity with `Product_Search_Template`) so admins can pre-customize
238            // before flipping it on; the front-end render path stays gated by
239            // the override option in `should_use_product_overlay()`.
240            if ( static::woocommerce_blocks_enabled() ) {
241                Product_Overlay_Template::init();
242            }
243        }
244        if ( static::is_block_template_overlay_enabled() ) {
245            add_action( 'wp_enqueue_scripts', array( static::class, 'enqueue_block_template_overlay_assets' ) );
246            add_action( 'wp_footer', array( static::class, 'print_block_template_overlay' ) );
247        }
248    }
249
250    /**
251     * Whether the Search blocks own the front-end search results for the active
252     * experience, meaning the server should run no search of its own.
253     *
254     * True for Embedded (the blocks template takes over the search page) and for
255     * the enabled blocks Overlay (a full-screen modal over the theme's search
256     * page). The Overlay arm goes through `is_block_template_overlay_enabled()`
257     * — operator filter plus saved experience — so a stale `overlay_blocks`
258     * option can't keep suppressing server search after the overlay is turned
259     * off. Drives both the Classic/Instant init suppression in
260     * `Initializer::init_search_blocks()` and the `posts_pre_query` short-circuit
261     * registered in `init()`.
262     *
263     * @return bool
264     */
265    public static function owns_search_results(): bool {
266        return Module_Control::EXPERIENCE_EMBEDDED === ( new Module_Control() )->get_experience()
267            || static::is_block_template_overlay_enabled();
268    }
269
270    /**
271     * Whether TrainTracks analytics are suppressed for this request. Mirrors
272     * instant search (Helper::get_search_options): the `?disable_tracking=1`
273     * crawler/QA param plus the `jetpack_instant_search_disable_tracking`
274     * operator filter. Gates both the `_tkq` pushes (seeded into
275     * `state.disableTracking`) and whether the Tracks consumer script loads.
276     *
277     * @return bool
278     */
279    public static function is_tracking_disabled(): bool {
280        return ( class_exists( Helper::class ) && Helper::is_tracking_disabled() )
281            || apply_filters( 'jetpack_instant_search_disable_tracking', false );
282    }
283
284    /**
285     * Short-circuit the main front-end search query when the blocks own results
286     * (see AGENTS.md § Search experiences). Registered only when
287     * `owns_search_results()` is true and off `is_admin()`.
288     *
289     * Pagination totals are set to `1` (not `0`) so `have_posts()`-gated
290     * templates still render the shell the client hydrates — WP core skips
291     * `set_found_posts()` when `posts_pre_query` returns an array.
292     *
293     * @param array|null $posts Posts to return in place of the query (null by default).
294     * @param \WP_Query  $query The WP_Query being filtered.
295     * @return array|null Empty array to short-circuit, or $posts to let it run.
296     */
297    public static function filter__posts_pre_query( $posts, $query ) {
298        if ( ! $query->is_main_query() || ! $query->is_search() ) {
299            return $posts;
300        }
301
302        $query->found_posts   = 1;
303        $query->max_num_pages = 1;
304
305        return array();
306    }
307
308    /**
309     * Whether to replace the legacy instant-search overlay with the
310     * server-rendered Search blocks template
311     * (`templates/jetpack-search-overlay.html`).
312     *
313     * Two conditions: the operator filter `is_block_template_overlay_filter_on()`
314     * is on (defaults true), AND the site owner has chosen
315     * `Module_Control::EXPERIENCE_OVERLAY_BLOCKS` in the dashboard. When both
316     * hold, the legacy `SearchApp` is bypassed via
317     * `jetpack_search_init_instant_search` in `Initializer::init_search_blocks()`.
318     *
319     * @return bool
320     */
321    public static function is_block_template_overlay_enabled(): bool {
322        if ( ! static::is_block_template_overlay_filter_on() ) {
323            return false;
324        }
325        return Module_Control::EXPERIENCE_OVERLAY_BLOCKS === ( new Module_Control() )->get_experience();
326    }
327
328    /**
329     * Whether the operator filter that exposes the blocks-powered overlay is on.
330     *
331     * Lighter than `is_block_template_overlay_enabled()` — doesn't require the
332     * user to have opted into the new overlay. Use for one-time setup that
333     * should run *before* opt-in (e.g. registering the editable template CPT
334     * so admins can preview the editor while preact Overlay is still active).
335     *
336     * @return bool
337     */
338    public static function is_block_template_overlay_filter_on(): bool {
339        /**
340         * Opt out of the experimental Search blocks overlay. Available by
341         * default; return false to hide the Beta card from the Experience
342         * Selector and disable the editable-template CPT.
343         *
344         * @param bool $enabled Default true.
345         */
346        return (bool) apply_filters( 'jetpack_search_overlay_block_template_enabled', true );
347    }
348
349    /**
350     * Memoized `Plan::is_free_plan()`. See `$is_free_plan_cache`.
351     *
352     * @return bool
353     */
354    public static function is_free_plan(): bool {
355        if ( null === self::$is_free_plan_cache ) {
356            self::$is_free_plan_cache = ( new Plan() )->is_free_plan();
357        }
358        return self::$is_free_plan_cache;
359    }
360
361    /**
362     * Reset the `is_free_plan()` memo. Tests only.
363     */
364    public static function reset_is_free_plan_cache() {
365        self::$is_free_plan_cache = null;
366    }
367
368    /**
369     * Whether the site has a paid Jetpack Search subscription. Paid-only block
370     * surfaces (AI Answer) call this on every render.
371     *
372     * Both probes are needed: `supports_instant_search()` is true on the free
373     * Search plan too ("plan supports the feature"), so it alone would let free
374     * through. `! is_free_plan()` excludes free + forced-free; `supports_instant_search()`
375     * excludes the no-plan case (which `is_free_plan()` returns false for).
376     *
377     * No `apply_filters()` wrapper by design — a filter that any plugin could
378     * flip would defeat a paid-feature gate. Tests bypass via
379     * `set_supports_paid_search_for_testing()`.
380     *
381     * @return bool
382     */
383    public static function supports_paid_search(): bool {
384        if ( null === self::$supports_paid_search_cache ) {
385            $plan                             = new Plan();
386            self::$supports_paid_search_cache = $plan->supports_instant_search() && ! $plan->is_free_plan();
387        }
388        return self::$supports_paid_search_cache;
389    }
390
391    /**
392     * Force the `supports_paid_search()` answer — tests only. Pass `null` to clear.
393     *
394     * @internal
395     * @param bool|null $value Forced answer or null to clear.
396     */
397    public static function set_supports_paid_search_for_testing( ?bool $value ): void {
398        self::$supports_paid_search_cache = $value;
399    }
400
401    /**
402     * Reset the `supports_paid_search()` memo. Tests only.
403     *
404     * @internal
405     */
406    public static function reset_supports_paid_search_cache(): void {
407        self::$supports_paid_search_cache = null;
408    }
409
410    /**
411     * Whether Jetpack Search exposes its WooCommerce-only blocks, filter
412     * variations, and render paths. See AGENTS.md § WooCommerce gating.
413     *
414     * **Load-order contract:** call at or after `plugins_loaded`. WC includes
415     * its main class during `plugins_loaded`, so an earlier call returns false
416     * on a WC site. Existing callers all fire later (`enqueue_block_editor_assets`,
417     * `template_redirect`, `wp_enqueue_scripts`, block render).
418     *
419     * @return bool
420     */
421    public static function woocommerce_blocks_enabled(): bool {
422        if ( null === self::$woocommerce_blocks_enabled_cache ) {
423            // `false` second arg: skip the autoloader on non-Woo sites — this
424            // gate is hit on every request and autoloader work would be wasted.
425            $probed = class_exists( 'WooCommerce', false ) && self::woocommerce_version_supported();
426
427            /**
428             * Whether Jetpack Search exposes its WooCommerce-only blocks,
429             * filter variations, and render paths. Default is the
430             * `class_exists( 'WooCommerce', false )` probe AND a minimum
431             * WooCommerce version check.
432             *
433             * @since 0.59.0
434             *
435             * @param bool $enabled Defaults to the WooCommerce class + version probe.
436             */
437            self::$woocommerce_blocks_enabled_cache = (bool) apply_filters(
438                'jetpack_search_woocommerce_blocks_enabled',
439                $probed
440            );
441        }
442        return self::$woocommerce_blocks_enabled_cache;
443    }
444
445    /**
446     * Whether the active WooCommerce is at `MIN_WOOCOMMERCE_VERSION` or newer.
447     * Older or absent WooCommerce reads as unsupported.
448     *
449     * @since 7.1.0
450     *
451     * @param string|null $version WooCommerce version to test; defaults to the
452     *   live `WC_VERSION` constant. Override is for tests pinning a version.
453     * @return bool
454     */
455    public static function woocommerce_version_supported( ?string $version = null ): bool {
456        // `constant()` keeps static analysis happy — WC isn't a dependency here.
457        $version ??= ( defined( 'WC_VERSION' ) ? (string) constant( 'WC_VERSION' ) : '' );
458        return '' !== $version && version_compare( $version, self::MIN_WOOCOMMERCE_VERSION, '>=' );
459    }
460
461    /**
462     * Force the `woocommerce_blocks_enabled()` answer to a specific boolean —
463     * tests only. Pass `null` to clear the override and revive the real
464     * `class_exists()` probe (also done by `reset_woocommerce_blocks_enabled_cache()`).
465     *
466     * @internal
467     *
468     * @param bool|null $value Forced answer or null to clear.
469     */
470    public static function set_woocommerce_blocks_enabled_for_testing( ?bool $value ): void {
471        self::$woocommerce_blocks_enabled_cache = $value;
472    }
473
474    /**
475     * Reset the `woocommerce_blocks_enabled()` memo. Tests only.
476     *
477     * @internal
478     */
479    public static function reset_woocommerce_blocks_enabled_cache(): void {
480        self::$woocommerce_blocks_enabled_cache = null;
481    }
482
483    /**
484     * The `jetpack_search_override_woocommerce_search_template` opt-in
485     * (default off), set from the Search dashboard.
486     *
487     * @return bool
488     */
489    public static function woocommerce_search_template_override_enabled(): bool {
490        return (bool) get_option( 'jetpack_search_override_woocommerce_search_template', false );
491    }
492
493    /**
494     * Whether the current request is a WooCommerce product search — a search
495     * query scoped to the `product` post-type archive on a Woo-enabled site.
496     *
497     * Theme-agnostic. Block-theme-only behavior (FSE hierarchy work) gates on
498     * {@see block_templates_active()} at the call site so this predicate also
499     * drives the classic-theme product shim. Public to keep the WC-gating
500     * surface (see AGENTS.md § WooCommerce gating) discoverable from outside
501     * the class; the in-class callers are `route_classic_theme_search_template()`
502     * and `route_woocommerce_product_search_template()`.
503     *
504     * @return bool
505     */
506    public static function is_woocommerce_product_search(): bool {
507        return self::woocommerce_blocks_enabled()
508            && is_search()
509            && is_post_type_archive( 'product' );
510    }
511
512    /**
513     * Canonical list of WooCommerce-only block names. Single source of truth
514     * for the WC gate across registration, helpers, and editor bundle — see
515     * AGENTS.md § WooCommerce gating. Add an entry and every gate picks it up.
516     *
517     * @return string[]
518     */
519    public static function woocommerce_only_block_names(): array {
520        return array(
521            'jetpack-search/filter-wc-attribute',
522            'jetpack-search/filter-wc-price',
523            'jetpack-search/filter-wc-rating',
524            'jetpack-search/filter-wc-stock-status',
525            'jetpack-search/filters-product',
526        );
527    }
528
529    /**
530     * Whether a block name belongs to a WooCommerce-only block. Accepts either
531     * the full namespaced name or a bare directory basename (the registration
532     * loop walks basenames; helpers and editor hold full names).
533     *
534     * @param string $block_name Full block name (`jetpack-search/filter-wc-rating`)
535     *                           or bare directory basename (`filter-wc-rating`).
536     * @return bool
537     */
538    public static function is_woocommerce_only_block( string $block_name ): bool {
539        $candidate = false === strpos( $block_name, '/' )
540            ? 'jetpack-search/' . $block_name
541            : $block_name;
542        return in_array( $candidate, self::woocommerce_only_block_names(), true );
543    }
544
545    /**
546     * Built-in taxonomies that have dedicated filter-checkbox variations.
547     * Excluded from the "Custom Taxonomy" picker so authors reach for the
548     * dedicated variation. Mirrors `BUILT_IN_TAXONOMY_SLUGS` in
549     * `filter-checkbox/edit.js` — must stay in lockstep.
550     *
551     * @var string[]
552     */
553    const BUILT_IN_CUSTOM_TAXONOMY_EXCLUSIONS = array(
554        'category',
555        'post_tag',
556        'product_cat',
557        'product_tag',
558        'product_brand',
559    );
560
561    /**
562     * Back-compat proxy for `Custom_Taxonomy_Slot_Mapping::get_map()`.
563     *
564     * @return array<string, string>
565     */
566    public static function custom_taxonomy_map(): array {
567        return Custom_Taxonomy_Slot_Mapping::get_map();
568    }
569
570    /**
571     * Back-compat proxy for `Custom_Taxonomy_Slot_Mapping::resolve_slot()`.
572     *
573     * @param string $taxonomy User-facing taxonomy slug.
574     * @return string Effective ES field slug.
575     */
576    public static function resolve_taxonomy_slot( string $taxonomy ): string {
577        return Custom_Taxonomy_Slot_Mapping::resolve_slot( $taxonomy );
578    }
579
580    /**
581     * Reset both the slot-mapping and `supported_custom_taxonomies()` memos. Tests only.
582     *
583     * @internal
584     */
585    public static function reset_custom_taxonomy_map_cache(): void {
586        Custom_Taxonomy_Slot_Mapping::reset_cache_for_testing();
587        self::$supported_custom_taxonomies_cache = null;
588    }
589
590    /**
591     * Custom-taxonomy slugs the "Custom Taxonomy" filter variation offers.
592     *
593     * Supported when registered locally AND either (a) in the Jetpack Search
594     * indexable allowlist (`Sync\Modules\Search::get_all_taxonomies()`, so
595     * aggregations actually return buckets) or (b) a key in `custom_taxonomy_map()`
596     * (queries route through a reserved slot). Built-ins with dedicated variations
597     * are stripped. The Sync `class_exists` guard is defensive — partial installs
598     * fall back to "map keys only".
599     *
600     * @return string[] Distinct, zero-indexed list of supported taxonomy slugs.
601     */
602    public static function supported_custom_taxonomies(): array {
603        if ( null !== self::$supported_custom_taxonomies_cache ) {
604            return self::$supported_custom_taxonomies_cache;
605        }
606
607        // Public taxonomies only — the editor's `core.getTaxonomies()` only returns
608        // REST-visible ones, and a private taxonomy in the Sync allowlist shouldn't surface.
609        $registered = function_exists( 'get_taxonomies' )
610            ? array_values( get_taxonomies( array( 'public' => true ), 'names' ) )
611            : array();
612
613        $indexed = class_exists( '\\Automattic\\Jetpack\\Sync\\Modules\\Search' )
614            ? \Automattic\Jetpack\Sync\Modules\Search::get_all_taxonomies()
615            : array();
616
617        $map_keys = array_keys( self::custom_taxonomy_map() );
618
619        $candidates = array_unique( array_merge( $indexed, $map_keys ) );
620        $supported  = array_values(
621            array_diff(
622                array_values( array_intersect( $registered, $candidates ) ),
623                self::BUILT_IN_CUSTOM_TAXONOMY_EXCLUSIONS
624            )
625        );
626
627        self::$supported_custom_taxonomies_cache = $supported;
628        return $supported;
629    }
630
631    /**
632     * URL param key the inline search experience uses for the current request.
633     * On the WP search route `s`; elsewhere `q` (see `NON_SEARCH_QUERY_PARAM`).
634     *
635     * Uses direct property access on `$wp_query` rather than the `is_search()`
636     * global function, because the function calls `_doing_it_wrong()` when
637     * invoked before the query has finished running (e.g. during block render).
638     *
639     * @return string
640     */
641    public static function get_search_param_name(): string {
642        global $wp_query;
643        if ( isset( $wp_query ) && ! empty( $wp_query->is_search ) ) {
644            return 's';
645        }
646        return self::NON_SEARCH_QUERY_PARAM;
647    }
648
649    /**
650     * Enqueue the client-side block registration bundle in the block editor.
651     *
652     * WP bootstraps server-side block metadata into the editor, but each block
653     * still needs a client-side `registerBlockType()` call so the editor knows
654     * how to render a preview. This script does that with ServerSideRender.
655     */
656    public static function enqueue_editor_assets() {
657        $base_path  = Package::get_installed_path() . 'build/search-blocks-editor/';
658        $asset_file = $base_path . 'register-blocks.asset.php';
659        if ( ! file_exists( $asset_file ) ) {
660            return;
661        }
662        $asset = require $asset_file;
663
664        // `plugins_url()` resolves against the nearest plugin directory, which
665        // handles the `jetpack_vendor` location Composer installs into.
666        $url = plugins_url( 'register-blocks.js', $base_path . 'register-blocks.js' );
667
668        wp_enqueue_script(
669            'jetpack-search-blocks-register',
670            $url,
671            $asset['dependencies'] ?? array(),
672            $asset['version'] ?? false,
673            true
674        );
675        wp_set_script_translations( 'jetpack-search-blocks-register', 'jetpack-search-pkg' );
676
677        // Surface PHP gates to the editor bundle so block edits and the
678        // registration loop branch consistently with server-side renders.
679        // `wp_add_inline_script` (not `wp_localize_script`) per core #25280 —
680        // the latter HTML-encodes ampersands inside nested values.
681        wp_add_inline_script(
682            'jetpack-search-blocks-register',
683            'window.JetpackSearchBlocksConfig = ' . wp_json_encode(
684                array(
685                    'isWooCommerceBlocksEnabled' => self::woocommerce_blocks_enabled(),
686                    'woocommerceOnlyBlocks'      => self::woocommerce_only_block_names(),
687                    'supportsPaidSearch'         => self::supports_paid_search(),
688                    'aiMasterEnabled'            => AI_Answers::host_allows_ai() && AI_Answers::is_master_enabled(),
689                    'supportedCustomTaxonomies'  => self::supported_custom_taxonomies(),
690                    'customTaxonomyMap'          => (object) self::custom_taxonomy_map(),
691                    // Resolved the same way `search-results/render.php` resolves the
692                    // live value, so the editor placeholder never claims a default
693                    // visitors won't actually get.
694                    'defaultResultsPerPage'      => Helper::resolve_results_per_page(),
695                    'maxResultsPerPage'          => Helper::get_max_posts_per_page(),
696                    'hideFromWidgetArea'         => self::widget_area_hiding_blocks(),
697                ),
698                JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP
699            ) . ';',
700            'before'
701        );
702    }
703
704    /**
705     * The widget area whose inserter must not offer the Search blocks, if the current screen edits widgets.
706     *
707     * The legacy Overlay's sidebar renders on `wp_footer`, after a block theme has printed the importmap, so a block's view module can't resolve `jetpack-search/store` and never hydrates.
708     *
709     * @since 8.2.0
710     *
711     * @return string|null Sidebar ID, or null when no area needs hiding.
712     */
713    public static function widget_area_hiding_blocks(): ?string {
714        if ( ! is_registered_sidebar( Instant_Search::INSTANT_SEARCH_SIDEBAR ) || ! function_exists( 'get_current_screen' ) ) {
715            return null;
716        }
717        $screen = get_current_screen();
718        if ( ! $screen || ! in_array( $screen->id, array( 'widgets', 'customize' ), true ) ) {
719            return null;
720        }
721        return Instant_Search::INSTANT_SEARCH_SIDEBAR;
722    }
723
724    /**
725     * Add a "Jetpack Search" block category so our blocks appear under that
726     * heading in the inserter instead of "Uncategorized".
727     *
728     * @param array $categories Existing block categories.
729     * @return array
730     */
731    public static function register_block_category( $categories ) {
732        foreach ( $categories as $category ) {
733            if ( 'jetpack-search' === ( $category['slug'] ?? '' ) ) {
734                return $categories;
735            }
736        }
737        $categories[] = array(
738            'slug'  => 'jetpack-search',
739            'title' => __( 'Jetpack Search', 'jetpack-search-pkg' ),
740        );
741        return $categories;
742    }
743
744    /**
745     * Register all search blocks from their block.json files.
746     */
747    public static function register_blocks() {
748        // Register block pattern category first so patterns can reference it.
749        if ( function_exists( 'register_block_pattern_category' ) ) {
750            register_block_pattern_category(
751                'jetpack-search',
752                array( 'label' => __( 'Jetpack Search', 'jetpack-search-pkg' ) )
753            );
754        }
755
756        self::register_store_script_module();
757
758        foreach ( self::block_directories() as $block_dir ) {
759            register_block_type( $block_dir );
760        }
761
762        add_filter( 'get_block_type_variations', array( static::class, 'inject_filter_checkbox_variations' ), 10, 2 );
763        static::register_patterns();
764    }
765
766    /**
767     * On a site that turned off on-demand block assets, load the Search blocks' styles only where they render.
768     *
769     * Mirrors Automattic\Jetpack\Blocks::load_styles_only_where_blocks_render(), which says why. The search page renders
770     * these blocks anyway, and a classic theme there can't hoist a late style, so it keeps them in the head.
771     *
772     * @since 8.4.4
773     */
774    public static function load_block_styles_only_where_rendered() {
775        if ( wp_should_load_block_assets_on_demand() || is_search() ) {
776            return;
777        }
778
779        foreach ( \WP_Block_Type_Registry::get_instance()->get_all_registered() as $block_type ) {
780            if ( ! str_starts_with( $block_type->name, 'jetpack-search/' ) || empty( $block_type->style_handles ) ) {
781                continue;
782            }
783            $block_type->view_style_handles = array_values( array_unique( array_merge( $block_type->style_handles, $block_type->view_style_handles ) ) );
784            $block_type->style_handles      = array();
785        }
786    }
787
788    /**
789     * Register the shared store as the `jetpack-search/store` Script Module.
790     * See AGENTS.md § Shared store / bundles for why this is externalized.
791     */
792    public static function register_store_script_module() {
793        if ( ! function_exists( 'wp_register_script_module' ) ) {
794            return;
795        }
796
797        $base_path  = Package::get_installed_path() . 'build/search-blocks/store/';
798        $asset_file = $base_path . 'index.asset.php';
799        if ( ! file_exists( $asset_file ) ) {
800            return;
801        }
802        $asset = require $asset_file;
803
804        wp_register_script_module(
805            'jetpack-search/store',
806            plugins_url( 'index.js', $base_path . 'index.js' ),
807            $asset['dependencies'] ?? array(),
808            $asset['version'] ?? false
809        );
810    }
811
812    /**
813     * Relativize Jetpack Search Script Module URLs so the browser fetches them
814     * same-origin with the page.
815     *
816     * `wp_register_script_module()` resolves src via `plugins_url()`, which
817     * returns the canonical `site_url()` host. When a visitor is on a
818     * different host (Multisite mapped domains, www vs non-www without a
819     * canonical redirect, asset-offload plugins, reverse-proxy staging) the
820     * `<script type="module">` becomes cross-origin and is blocked with
821     * `MissingAllowOriginHeader` — ES modules always go through the CORS
822     * algorithm, even without a `crossorigin` attribute, and typical WP
823     * hosts don't send `Access-Control-Allow-Origin` for `wp-content/*`.
824     *
825     * Stripping scheme + host with `wp_make_link_relative()` lets the browser
826     * resolve against the page's actual origin. No `$_SERVER['HTTP_HOST']`
827     * trust — emitting an attacker-controllable host into a `<script src>`
828     * would be a cache-poisoning vector.
829     *
830     * No-op when the src host is a deliberately external host (CDN that
831     * doesn't match `home_url()`/`site_url()`); operators of those setups
832     * configure CORS on the CDN themselves.
833     *
834     * Identifier gate covers both shapes Jetpack Search ships: directly-
835     * registered modules with a slash (`jetpack-search/store`,
836     * `jetpack-search/overlay-bootstrap`) and the per-block view modules
837     * WP auto-registers from `block.json`'s `viewScriptModule`, which run
838     * `generate_block_asset_handle()` and emit hyphen-joined IDs like
839     * `jetpack-search-results-list-view-script-module`.
840     *
841     * @param string $src        Module src URL.
842     * @param string $identifier Module identifier (e.g. `jetpack-search/results-list`
843     *                           or `jetpack-search-results-list-view-script-module`).
844     * @return string Relativized src on match, original otherwise.
845     */
846    public static function same_origin_script_module_src( $src, $identifier ) {
847        if ( ! is_string( $src ) || '' === $src || ! is_string( $identifier ) ) {
848            return $src;
849        }
850        if ( 0 !== strpos( $identifier, 'jetpack-search/' ) && 0 !== strpos( $identifier, 'jetpack-search-' ) ) {
851            return $src;
852        }
853
854        $src_host = wp_parse_url( $src, PHP_URL_HOST );
855        if ( ! $src_host ) {
856            return $src;
857        }
858
859        $canonical_hosts = array_map(
860            'strtolower',
861            array_filter(
862                array(
863                    wp_parse_url( home_url(), PHP_URL_HOST ),
864                    wp_parse_url( site_url(), PHP_URL_HOST ),
865                )
866            )
867        );
868
869        if ( ! in_array( strtolower( $src_host ), $canonical_hosts, true ) ) {
870            return $src;
871        }
872
873        return wp_make_link_relative( $src );
874    }
875
876    /**
877     * Inject named block variations for the filter-checkbox block.
878     *
879     * Uses the `get_block_type_variations` filter (WP 6.5+) rather than
880     * `register_block_variation()` — the latter is JS-only and has no PHP
881     * equivalent. Variation names + default attributes mirror the
882     * instant-search overlay so both surfaces describe the same filters.
883     *
884     * @param array          $variations Variations registered on the block type.
885     * @param \WP_Block_Type $block_type Block type the filter is being applied to.
886     * @return array
887     */
888    public static function inject_filter_checkbox_variations( $variations, $block_type ) {
889        if ( ! isset( $block_type->name ) || 'jetpack-search/filter-checkbox' !== $block_type->name ) {
890            return $variations;
891        }
892
893        $additions = array(
894            array(
895                'name'        => 'category',
896                'title'       => __( 'Filter by Category', 'jetpack-search-pkg' ),
897                'description' => __( 'Show category checkboxes with live result counts.', 'jetpack-search-pkg' ),
898                'attributes'  => array(
899                    'filterType' => 'taxonomy',
900                    'taxonomy'   => 'category',
901                    'label'      => __( 'Category', 'jetpack-search-pkg' ),
902                ),
903                'isActive'    => array( 'filterType', 'taxonomy' ),
904            ),
905            array(
906                'name'        => 'post_tag',
907                'title'       => __( 'Filter by Tag', 'jetpack-search-pkg' ),
908                'description' => __( 'Show tag checkboxes with live result counts.', 'jetpack-search-pkg' ),
909                'attributes'  => array(
910                    'filterType' => 'taxonomy',
911                    'taxonomy'   => 'post_tag',
912                    'label'      => __( 'Tag', 'jetpack-search-pkg' ),
913                ),
914                'isActive'    => array( 'filterType', 'taxonomy' ),
915            ),
916            array(
917                'name'        => 'post_type',
918                'title'       => __( 'Filter by Post Type', 'jetpack-search-pkg' ),
919                'description' => __( 'Show post type checkboxes with live result counts.', 'jetpack-search-pkg' ),
920                'attributes'  => array(
921                    'filterType' => 'post_type',
922                    'label'      => __( 'Post Type', 'jetpack-search-pkg' ),
923                ),
924                'isActive'    => array( 'filterType' ),
925            ),
926            array(
927                'name'        => 'author',
928                'title'       => __( 'Filter by Author', 'jetpack-search-pkg' ),
929                'description' => __( 'Show author checkboxes with live result counts.', 'jetpack-search-pkg' ),
930                'attributes'  => array(
931                    'filterType' => 'author',
932                    'label'      => __( 'Author', 'jetpack-search-pkg' ),
933                ),
934                'isActive'    => array( 'filterType' ),
935            ),
936        );
937
938        // WC-only product-taxonomy variations. `product_brand` gets an extra
939        // `taxonomy_exists()` probe — it isn't core WC, it ships via extensions
940        // (WC Brands, Perfect Brands) or recent bundled WC versions.
941        if ( self::woocommerce_blocks_enabled() ) {
942            $additions[] = array(
943                'name'        => 'product_cat',
944                'title'       => __( 'Filter by Product Category', 'jetpack-search-pkg' ),
945                'description' => __( 'Show product category checkboxes with live result counts.', 'jetpack-search-pkg' ),
946                'attributes'  => array(
947                    'filterType' => 'taxonomy',
948                    'taxonomy'   => 'product_cat',
949                    'label'      => __( 'Product Category', 'jetpack-search-pkg' ),
950                ),
951                'isActive'    => array( 'filterType', 'taxonomy' ),
952            );
953            $additions[] = array(
954                'name'        => 'product_tag',
955                'title'       => __( 'Filter by Product Tag', 'jetpack-search-pkg' ),
956                'description' => __( 'Show product tag checkboxes with live result counts.', 'jetpack-search-pkg' ),
957                'attributes'  => array(
958                    'filterType' => 'taxonomy',
959                    'taxonomy'   => 'product_tag',
960                    'label'      => __( 'Product Tag', 'jetpack-search-pkg' ),
961                ),
962                'isActive'    => array( 'filterType', 'taxonomy' ),
963            );
964            if ( taxonomy_exists( 'product_brand' ) ) {
965                $additions[] = array(
966                    'name'        => 'product_brand',
967                    'title'       => __( 'Filter by Product Brand', 'jetpack-search-pkg' ),
968                    'description' => __( 'Show product brand checkboxes with live result counts.', 'jetpack-search-pkg' ),
969                    'attributes'  => array(
970                        'filterType' => 'taxonomy',
971                        'taxonomy'   => 'product_brand',
972                        'label'      => __( 'Product Brand', 'jetpack-search-pkg' ),
973                    ),
974                    'isActive'    => array( 'filterType', 'taxonomy' ),
975                );
976            }
977        }
978
979        $additions[] = array(
980            'name'        => 'custom_taxonomy',
981            'title'       => __( 'Filter by Custom Taxonomy', 'jetpack-search-pkg' ),
982            'description' => __( 'Show checkboxes for a custom taxonomy. Pick which taxonomy in the block settings after inserting.', 'jetpack-search-pkg' ),
983            'attributes'  => array(
984                'filterType' => 'taxonomy',
985                'taxonomy'   => '',
986                'label'      => '',
987            ),
988            // Match on filterType only so identity survives the author picking a
989            // slug. The dedicated variations pin `taxonomy` in their isActive
990            // arrays, so WP's most-specific-match resolution still routes named
991            // slugs to those; Custom Taxonomy claims every other taxonomy.
992            'isActive'    => array( 'filterType' ),
993        );
994
995        // Merge by `name` so an upstream variation (block.json or earlier filter)
996        // wins over our preset of the same name; plain `array_merge` would
997        // append duplicates and the inserter would render two cards.
998        $variations    = (array) $variations;
999        $existing_keys = array_flip( array_column( $variations, 'name' ) );
1000        foreach ( $additions as $variation ) {
1001            if ( ! isset( $existing_keys[ $variation['name'] ] ) ) {
1002                $variations[] = $variation;
1003            }
1004        }
1005        return $variations;
1006    }
1007
1008    /**
1009     * Register block patterns. Files prefixed `wc-` compose WooCommerce-only
1010     * blocks and load only when WC is active (mirrors `filter-wc-*` blocks).
1011     */
1012    protected static function register_patterns() {
1013        $patterns_dir = __DIR__ . '/patterns';
1014        if ( ! is_dir( $patterns_dir ) ) {
1015            return;
1016        }
1017        $pattern_files = glob( $patterns_dir . '/*.php' );
1018        if ( ! $pattern_files ) {
1019            return;
1020        }
1021        $wc_blocks_enabled = self::woocommerce_blocks_enabled();
1022        foreach ( $pattern_files as $pattern_file ) {
1023            if ( ! $wc_blocks_enabled && 0 === strpos( basename( $pattern_file ), 'wc-' ) ) {
1024                continue;
1025            }
1026            require_once $pattern_file;
1027        }
1028    }
1029
1030    /**
1031     * Derive a block-pattern's content from a chrome-free layout template (the
1032     * overlay templates, which already ship without header/footer/main page
1033     * chrome), so patterns stay in sync with the template they mirror instead of
1034     * carrying a hand-copied second copy of the layout.
1035     *
1036     * @param string $template_file Template basename under `templates/`.
1037     * @return string Block markup ready for `register_block_pattern()`, or '' when unreadable.
1038     */
1039    public static function pattern_content_from_template( string $template_file ): string {
1040        $template_path = __DIR__ . '/templates/' . basename( $template_file );
1041        // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents -- local, bundled template file.
1042        $raw = is_readable( $template_path ) ? (string) file_get_contents( $template_path ) : '';
1043        if ( '' === $raw ) {
1044            return '';
1045        }
1046        return trim( static::substitute_template_placeholders( $raw ) );
1047    }
1048
1049    /**
1050     * Build the full search page template content.
1051     *
1052     * Markup lives in `templates/jetpack-search.html` with a `{{FILTER_HEADING}}`
1053     * placeholder so the sidebar heading still goes through `esc_html__()`.
1054     *
1055     * @return string Block markup for a complete page template.
1056     */
1057    protected static function get_search_template_content(): string {
1058        $template_path = __DIR__ . '/templates/jetpack-search.html';
1059        // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents -- local, bundled template file.
1060        $raw = is_readable( $template_path ) ? (string) file_get_contents( $template_path ) : '';
1061        return static::sync_filters_popover_content( static::substitute_template_placeholders( $raw ) );
1062    }
1063
1064    /**
1065     * Register the Jetpack Search page template so it surfaces in the Site
1066     * Editor and resolves via the template hierarchy. DB-stored customizations
1067     * still win automatically — the `custom` source beats `plugin`. Classic
1068     * themes are skipped: the registry is only consulted by block themes.
1069     */
1070    public static function register_search_template() {
1071        if ( ! function_exists( 'register_block_template' ) || ! static::block_templates_active() ) {
1072            return;
1073        }
1074        $content = static::get_search_template_content();
1075        // Bail on missing/unreadable file: our slug is prepended to the search
1076        // hierarchy, so registering empty content would render a blank page on
1077        // `/?s=…`. Falling through lets core resolve the theme's `search.html`.
1078        if ( '' === $content ) {
1079            return;
1080        }
1081        static::replace_block_template(
1082            static::get_parent_plugin_slug() . '//' . self::SEARCH_TEMPLATE_SLUG,
1083            array(
1084                'title'       => __( 'Jetpack Search Results', 'jetpack-search-pkg' ),
1085                'description' => __( 'Displays search results with Jetpack Search filters.', 'jetpack-search-pkg' ),
1086                'content'     => $content,
1087            )
1088        );
1089    }
1090
1091    /**
1092     * Whether the overlay should paint the WooCommerce product variant for the
1093     * current request. True only when the override option is on and the request
1094     * is a product search — mirrors the embedded/inline interception
1095     * (`is_woocommerce_product_search()` already folds in the WC probe). The
1096     * overlay opens client-side from any search box, so this only flips on the
1097     * server-rendered product-search request (deep link or product-archive
1098     * search), not on a live form intercept from a non-product page.
1099     *
1100     * @return bool
1101     */
1102    protected static function should_use_product_overlay(): bool {
1103        return static::woocommerce_search_template_override_enabled()
1104            && static::is_woocommerce_product_search();
1105    }
1106
1107    /**
1108     * Read the dedicated overlay-template markup.
1109     *
1110     * Distinct from `get_search_template_content()`: a modal isn't a page, so
1111     * the overlay markup ships without `header`/`main`/`footer` template-parts
1112     * rather than runtime-stripping them.
1113     *
1114     * Picks the product variant on a WooCommerce product search (see
1115     * `should_use_product_overlay()`). Source of truth, in order:
1116     *   1. Customized singleton CPT (`Overlay_Template` / `Product_Overlay_Template`).
1117     *   2. The bundled `jetpack-search-overlay{-product}.html`.
1118     *
1119     * @return string Block markup for the overlay body.
1120     */
1121    protected static function get_overlay_template_content(): string {
1122        $is_product = static::should_use_product_overlay();
1123        $key        = $is_product ? 'product' : 'default';
1124        if ( isset( self::$overlay_template_content_cache[ $key ] ) ) {
1125            return self::$overlay_template_content_cache[ $key ];
1126        }
1127        $cpt_class  = $is_product ? Product_Overlay_Template::class : Overlay_Template::class;
1128        $customized = $cpt_class::get_customized_content();
1129        if ( null !== $customized ) {
1130            self::$overlay_template_content_cache[ $key ] = $customized;
1131            return self::$overlay_template_content_cache[ $key ];
1132        }
1133        $file          = $is_product ? 'jetpack-search-overlay-product.html' : 'jetpack-search-overlay.html';
1134        $template_path = __DIR__ . '/templates/' . $file;
1135        // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents -- local, bundled template file; wp_remote_get() is for remote URLs.
1136        $raw = is_readable( $template_path ) ? (string) file_get_contents( $template_path ) : '';
1137        self::$overlay_template_content_cache[ $key ] = static::sync_filters_popover_content( $raw );
1138        return self::$overlay_template_content_cache[ $key ];
1139    }
1140
1141    /**
1142     * Reset the `get_overlay_template_content()` memo. Tests only — PHPUnit
1143     * reuses a single process, so a CPT-customized overlay saved in one test
1144     * would otherwise be pinned (or a bundled read would mask it) in the next.
1145     * Guarded against accidental production use.
1146     */
1147    public static function reset_overlay_template_content_cache(): void {
1148        if ( defined( 'ABSPATH' ) && ! defined( 'PHPUNIT_COMPOSER_INSTALL' ) ) {
1149            return;
1150        }
1151        self::$overlay_template_content_cache = array();
1152    }
1153
1154    /**
1155     * Echo the Search-blocks overlay shell into `wp_footer`. Block markup
1156     * carries `data-wp-interactive` so the IA's standard `DOMContentLoaded`
1157     * hydration picks it up — no client-side fetch needed. The caller (`init()`)
1158     * gates registration on `is_block_template_overlay_enabled()`.
1159     */
1160    public static function print_block_template_overlay() {
1161        $rendered = self::$block_template_overlay_rendered_html;
1162        if ( null === $rendered || '' === $rendered ) {
1163            return;
1164        }
1165        $config = wp_json_encode(
1166            array(
1167                'searchInputSelector'    => 'input[name="s"]:not(.jetpack-search-input__field), #searchform input.search-field, .search-form input.search-field, .searchform input.search-field',
1168                'overlayTriggerSelector' => '.jetpack-search-block-overlay-trigger, .jetpack-instant-search__open-overlay-button, header#site-header .search-toggle[data-toggle-target]',
1169            ),
1170            JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP
1171        );
1172        ?>
1173        <script id="jetpack-search-block-overlay-config">window.JetpackSearchBlockOverlay=<?php echo $config; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- wp_json_encode + JSON_HEX_* flags. ?>;</script>
1174        <?php
1175        // `<template>` keeps the region out of `document.querySelectorAll` so
1176        // the IA runtime's DOMContentLoaded walk skips it. The bootstrap clones
1177        // into the shell on first open and hydrates there.
1178        // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- do_blocks output.
1179        printf( '<template id="jetpack-search-block-overlay-template">%s</template>', $rendered );
1180        ?>
1181        <div
1182            id="jetpack-search-block-overlay"
1183            class="jetpack-search-block-overlay"
1184            role="dialog"
1185            aria-modal="true"
1186            aria-label="<?php echo esc_attr__( 'Search', 'jetpack-search-pkg' ); ?>"
1187            hidden
1188        >
1189            <div class="jetpack-search-block-overlay__card">
1190                <button
1191                    type="button"
1192                    class="jetpack-search-block-overlay__close"
1193                    aria-label="<?php echo esc_attr__( 'Close search', 'jetpack-search-pkg' ); ?>"
1194                >
1195                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
1196                        <path d="M18.3 5.71a1 1 0 0 0-1.41 0L12 10.59 7.11 5.7A1 1 0 0 0 5.7 7.11L10.59 12 5.7 16.89a1 1 0 1 0 1.41 1.41L12 13.41l4.89 4.89a1 1 0 0 0 1.41-1.41L13.41 12l4.89-4.89a1 1 0 0 0 0-1.4z" fill="currentColor" />
1197                    </svg>
1198                </button>
1199                <div class="jetpack-search-block-overlay__content"></div>
1200            </div>
1201        </div>
1202        <?php
1203    }
1204
1205    /**
1206     * Register + enqueue the overlay-bootstrap Script Module that wires
1207     * theme-defined search triggers to the rendered shell. Inline-CSS for the
1208     * modal chrome. Config emits alongside the overlay HTML in
1209     * `print_block_template_overlay()`.
1210     */
1211    public static function enqueue_block_template_overlay_assets() {
1212        if ( ! function_exists( 'wp_register_script_module' ) ) {
1213            return;
1214        }
1215        $base_path  = Package::get_installed_path() . 'build/search-blocks/overlay-bootstrap/';
1216        $asset_file = $base_path . 'index.asset.php';
1217        if ( ! file_exists( $asset_file ) ) {
1218            return;
1219        }
1220        $asset = require $asset_file;
1221        wp_register_script_module(
1222            'jetpack-search/overlay-bootstrap',
1223            plugins_url( 'index.js', $base_path . 'index.js' ),
1224            $asset['dependencies'] ?? array(),
1225            $asset['version'] ?? false
1226        );
1227        wp_enqueue_script_module( 'jetpack-search/overlay-bootstrap' );
1228
1229        wp_register_style( 'jetpack-search-block-overlay', false, array(), $asset['version'] ?? false );
1230        wp_enqueue_style( 'jetpack-search-block-overlay' );
1231        wp_add_inline_style( 'jetpack-search-block-overlay', static::block_template_overlay_inline_css() );
1232
1233        // Shared responsive layout CSS (narrow-width sidebar collapse +
1234        // in-header popover toggle). Same rules ship to the embedded /
1235        // WC-product page templates via `enqueue_search_page_assets()`.
1236        static::enqueue_search_layout_style();
1237
1238        // Render here (during `wp_enqueue_scripts`) so view-module enqueues
1239        // from `do_blocks()` land before the importmap prints — see
1240        // AGENTS.md § Hydration & SSR seeding.
1241        self::$block_template_overlay_rendered_html = trim(
1242            No_Results::render_self_contained( static::get_overlay_template_content() )
1243        );
1244    }
1245
1246    /**
1247     * Print the body-sampler `<script>` that sets `--jp-search-page-ink` /
1248     * `--jp-search-page-surface` on `:root` from the body's resolved `color` /
1249     * `backgroundColor`. Skips writing surface when bg is transparent (the
1250     * theme paints on the browser canvas) or when bg equals ink (vintage
1251     * frame-themes like Twenty Sixteen use body as a colored border around a
1252     * lighter `.site` content wrapper). See AGENTS.md § Theme tokens.
1253     *
1254     * The `wp_body_open` hook registers unconditionally in `init()`, before
1255     * the module-active check in `Initializer::init_search_blocks()` — so the
1256     * module gate lives here instead, front-end only.
1257     */
1258    public static function print_theme_token_sampler(): void {
1259        if ( is_admin() || ! ( new Module_Control() )->is_active() ) {
1260            return;
1261        }
1262        echo "<script id='jetpack-search-theme-token-sampler'>(function(){try{var c=getComputedStyle(document.body),r=document.documentElement,ink=c.color,bg=c.backgroundColor;if(ink){r.style.setProperty('--jp-search-page-ink',ink);}if(bg&&bg!==ink&&bg!=='rgba(0, 0, 0, 0)'&&bg!=='transparent'){r.style.setProperty('--jp-search-page-surface',bg);}}catch(e){}})();</script>";
1263    }
1264
1265    /**
1266     * Inline CSS for the overlay modal chrome. Block content brings its own
1267     * theme styling; this is just the scrim, centered card, 60px header strip,
1268     * close button, mobile padding tweaks, and scroll lock. The responsive
1269     * sidebar-collapse + in-header popover rules shared with the page
1270     * templates live in `search_layout_inline_css()`.
1271     *
1272     * Surface/ink hoist `--jp-search-page-*` (with the legacy
1273     * `--wp--preset--color--*` chain as fallback — see AGENTS.md § Theme
1274     * tokens) onto two custom props so in-card surfaces share one source.
1275     * Hairlines use `color-mix(--jp-search-overlay-ink, --jp-search-overlay-surface)`.
1276     *
1277     * @return string
1278     */
1279    protected static function block_template_overlay_inline_css(): string {
1280        return <<<'CSS'
1281.jetpack-search-block-overlay {
1282    position: fixed;
1283    inset: 0;
1284    z-index: 100000;
1285    display: flex;
1286    justify-content: center;
1287    align-items: flex-start;
1288    background: rgba(31, 31, 31, 0.7);
1289    overflow-y: auto;
1290    padding: 3em 1em;
1291    transition: opacity 0.1s ease-in;
1292}
1293.jetpack-search-block-overlay[hidden] {
1294    display: none;
1295}
1296@media (prefers-reduced-motion: reduce) {
1297    .jetpack-search-block-overlay {
1298        transition: none;
1299    }
1300}
1301.jetpack-search-block-overlay__card {
1302    position: relative;
1303    width: 100%;
1304    max-width: 1080px;
1305    --jp-search-overlay-surface: var(--jp-search-page-surface, var(--wp--preset--color--base, var(--wp--preset--color--background, #fff)));
1306    --jp-search-overlay-ink: var(--jp-search-page-ink, var(--wp--preset--color--contrast, var(--wp--preset--color--foreground, #1d2327)));
1307    /* Single source for the content group's inset. The corner-join in
1308     * search_layout_inline_css() zeroes the block-start/block-end of this
1309     * padding on the group and re-adds the same tokens on the columns, so the
1310     * sidebar hairline reaches both card edges — keep them as var()s so the
1311     * two sites can't drift. */
1312    --jp-search-overlay-content-pad-block-start: 0.5em;
1313    --jp-search-overlay-content-pad-inline: 2em;
1314    --jp-search-overlay-content-pad-block-end: 2em;
1315    background: var(--jp-search-overlay-surface);
1316    color: var(--jp-search-overlay-ink);
1317    border: 1px solid rgba(128, 128, 128, 0.25);
1318    border-radius: 4px;
1319    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.18);
1320    padding-top: 60px;
1321}
1322/* Token-aware card / scrim separation (SEARCH-270): tint the resolved surface
1323 * ~5% toward ink and paint the hairline border with the same ink-over-surface
1324 * mix used for the header `::before`. Both auto-invert polarity per theme, so
1325 * dark themes get a card that visibly layers above the scrim without losing
1326 * the themed surface color. The static `rgba(128,128,128,.25)` border + the
1327 * un-tinted token chain stay as the fallback for browsers without `color-mix`. */
1328@supports (background: color-mix(in sRGB, black 50%, white)) {
1329    .jetpack-search-block-overlay__card {
1330        --jp-search-overlay-surface: color-mix(in sRGB, var(--jp-search-page-ink, var(--wp--preset--color--contrast, var(--wp--preset--color--foreground, #1d2327))) 5%, var(--jp-search-page-surface, var(--wp--preset--color--base, var(--wp--preset--color--background, #fff))));
1331        border-color: color-mix(in sRGB, var(--jp-search-overlay-ink) 20%, var(--jp-search-overlay-surface));
1332        /* Ink-derived shadow inverts polarity per theme (SEARCH-289): a dark drop
1333         * shadow on light cards, a soft light halo on dark — a flat black shadow is
1334         * invisible against the dark scrim. Static black above is the fallback. */
1335        box-shadow: 0 8px 32px color-mix(in sRGB, var(--jp-search-overlay-ink) 22%, transparent);
1336    }
1337}
1338/* Single hairline over the full 60px header strip — siblings paint with a seam (SEARCH-260). */
1339.jetpack-search-block-overlay__card::before {
1340    content: "";
1341    position: absolute;
1342    top: 60px;
1343    left: 0;
1344    right: 0;
1345    height: 1px;
1346    background: transparent;
1347    pointer-events: none;
1348}
1349@supports (background: color-mix(in sRGB, black 50%, white)) {
1350    .jetpack-search-block-overlay__card::before {
1351        background: color-mix(in sRGB, var(--jp-search-overlay-ink) 15%, var(--jp-search-overlay-surface));
1352    }
1353}
1354.jetpack-search-block-overlay__close {
1355    position: absolute;
1356    top: 0;
1357    right: 0;
1358    width: 60px;
1359    height: 60px;
1360    display: flex;
1361    align-items: center;
1362    justify-content: center;
1363    background: transparent;
1364    border: 0;
1365    cursor: pointer;
1366    color: inherit;
1367}
1368/* Opaque ink-over-surface mix — `color-mix(currentColor, transparent)` collapses to full-opacity ink on Safari <16.4 and swallows the X icon. */
1369@supports (background: color-mix(in sRGB, black 50%, white)) {
1370    .jetpack-search-block-overlay__close:hover,
1371    .jetpack-search-block-overlay__close:focus-visible {
1372        background: color-mix(in sRGB, var(--jp-search-overlay-ink) 14%, var(--jp-search-overlay-surface));
1373    }
1374}
1375.jetpack-search-block-overlay__close svg {
1376    width: 24px;
1377    height: 24px;
1378}
1379/* Pin in-overlay button `color` against host-theme `button:hover|:focus` overrides
1380 * (fieldguide and similar legacy themes flip button color to a brand accent on hover).
1381 * Our block-level rules set `color: inherit` at (0,1,0); a stray `button:hover` rule
1382 * at (0,1,1) outranks it on `:hover`, and the `color-mix(currentColor X%, …)` hover
1383 * affordances on the filters-popover trigger, results-sort trigger, suggestions
1384 * options, etc. then resolve against the host's hover color (often white-on-white).
1385 * Card-scoped `:hover|:focus|[aria-expanded=true]` lands at (0,2,1) — beats the
1386 * theme rule without escalating to `!important`. */
1387.jetpack-search-block-overlay__card button:hover,
1388.jetpack-search-block-overlay__card button:focus,
1389.jetpack-search-block-overlay__card button:focus-visible,
1390.jetpack-search-block-overlay__card button[aria-expanded="true"] {
1391    color: var(--jp-search-overlay-ink);
1392}
1393/* Load More is a solid theme `core/button` on the search page, which is right
1394 * there. Inside the overlay card it sits on the resolved card surface, where the
1395 * theme's solid button background (and its accent `:hover`, e.g. Twenty Sixteen's
1396 * #007acc) reads as a heavy slab that clashes with the card's otherwise
1397 * `currentColor`-ghost controls (close, sort/filter triggers, active-filter
1398 * pills). Card-scoped (0,2,0 / 0,2,1) so it only restyles the in-overlay button
1399 * to the same ghost affordance — the page button is untouched. */
1400.jetpack-search-block-overlay__card .jetpack-search-load-more__button {
1401    background: transparent;
1402    border: 1px solid;
1403    border-color: color-mix(in sRGB, currentColor 20%, transparent);
1404    color: var(--jp-search-overlay-ink);
1405}
1406.jetpack-search-block-overlay__card .jetpack-search-load-more__button:hover:not(:disabled),
1407.jetpack-search-block-overlay__card .jetpack-search-load-more__button:focus-visible {
1408    background: color-mix(in sRGB, currentColor 8%, transparent);
1409}
1410/* Promote the first child (search-input) to a 60px header strip flush with
1411 * the close button, matching the legacy `__box` header. Suppress the input
1412 * block's own border-bottom — the card's `::before` hairline handles the
1413 * separator across the whole strip. */
1414.jetpack-search-block-overlay__card .wp-block-jetpack-search-search-input {
1415    position: absolute;
1416    top: 0;
1417    left: 0;
1418    right: 60px;
1419    height: 60px;
1420    margin: 0;
1421    padding: 0;
1422}
1423.jetpack-search-block-overlay__card .wp-block-jetpack-search-search-input .jetpack-search-input__inside-wrapper {
1424    height: 100%;
1425    display: flex;
1426    align-items: stretch;
1427    gap: 0;
1428    padding: 0;
1429    border-bottom: 0;
1430}
1431.jetpack-search-block-overlay__card .wp-block-jetpack-search-search-input .jetpack-search-input__icon {
1432    flex: 0 0 60px;
1433    width: 60px;
1434    height: 60px;
1435    padding: 18px;
1436    box-sizing: border-box;
1437    opacity: 0.5;
1438}
1439.jetpack-search-block-overlay__card .wp-block-jetpack-search-search-input .jetpack-search-input__field {
1440    flex: 1 1 auto;
1441    min-width: 0;
1442    height: 100%;
1443    font-size: 18px;
1444    line-height: 1;
1445    margin: 0;
1446    padding: 0;
1447    background: transparent;
1448}
1449.jetpack-search-block-overlay__card .wp-block-jetpack-search-search-input .jetpack-search-input__clear {
1450    flex: 0 0 60px;
1451    width: 60px;
1452    height: 60px;
1453    padding: 0;
1454    font-size: 0.875rem;
1455    font-weight: 400;
1456    line-height: 1;
1457}
1458/* Suggestions panel covers the full card width (cancel the input's `right: 60px`
1459 * offset) and sits above `results-sort` / `filters-popover` (both `z-index: 20`).
1460 * Background reads from `--jp-search-overlay-surface` so the panel tracks the
1461 * resolved card surface — a hardcoded `#fff` would re-introduce the white-on-dark
1462 * bug on legacy `--background`/`--foreground` themes. */
1463.jetpack-search-block-overlay__card .wp-block-jetpack-search-search-input .jetpack-search-input__suggestions {
1464    right: -60px;
1465    z-index: 30;
1466    background: var(--jp-search-overlay-surface, #fff);
1467}
1468/* Top padding clears the absolutely-positioned 60px header strip (SEARCH-243). */
1469.jetpack-search-block-overlay__content > .wp-block-group:first-child {
1470    padding: var(--jp-search-overlay-content-pad-block-start) var(--jp-search-overlay-content-pad-inline) var(--jp-search-overlay-content-pad-block-end);
1471}
1472@media (max-width: 781px) {
1473    .jetpack-search-block-overlay {
1474        padding: 0;
1475    }
1476    .jetpack-search-block-overlay__card {
1477        min-height: 100vh;
1478        border: 0;
1479        border-radius: 0;
1480        box-shadow: none;
1481        --jp-search-overlay-content-pad-inline: 1em;
1482        --jp-search-overlay-content-pad-block-end: 1em;
1483    }
1484}
1485/* Mirror legacy `$break-lg: 992px → $modal-max-width-lg: 95%` from `instant-search/components/search-results.scss`. */
1486@media (min-width: 992px) {
1487    .jetpack-search-block-overlay__card {
1488        max-width: 95%;
1489    }
1490}
1491/* Body-scroll lock while open. JS side stashes/restores scrollY on toggle. */
1492body.jetpack-search-block-overlay-open {
1493    position: fixed;
1494    left: 0;
1495    right: 0;
1496    width: 100%;
1497    overflow: hidden;
1498}
1499CSS;
1500    }
1501
1502    /**
1503     * Register + enqueue the shared responsive layout CSS on the embedded /
1504     * WC-product page templates (`jetpack-search.html`,
1505     * `jetpack-search-product-results.html`). Self-gates on `is_search()` so
1506     * non-search requests skip the work entirely; the overlay path enqueues
1507     * the same handle unconditionally from its own asset hook.
1508     */
1509    public static function enqueue_search_page_assets() {
1510        if ( ! is_search() ) {
1511            return;
1512        }
1513        static::enqueue_search_layout_style();
1514    }
1515
1516    /**
1517     * Register + enqueue the inline CSS that drives the shared responsive
1518     * layout pattern across all three Search Blocks templates — narrow-width
1519     * sidebar collapse and in-header popover toggle. Called from both the
1520     * overlay enqueue path and the page-template enqueue path.
1521     *
1522     * `wp_register_style` / `wp_enqueue_style` are idempotent, but
1523     * `wp_add_inline_style` is **not** — it appends to an internal array on
1524     * every call, so a second invocation would double the inline payload.
1525     * The `wp_style_is( …, 'enqueued' )` short-circuit makes the helper safe
1526     * to call from multiple sites in one request.
1527     */
1528    public static function enqueue_search_layout_style() {
1529        // No src — this handle exists only as a target for `wp_add_inline_style`.
1530        // Version tracks the package so a release bust cache-invalidates any
1531        // reusing site's inline-style cache.
1532        wp_register_style( 'jetpack-search-layout', false, array(), Package::VERSION );
1533        if ( wp_style_is( 'jetpack-search-layout', 'enqueued' ) ) {
1534            return;
1535        }
1536        wp_enqueue_style( 'jetpack-search-layout' );
1537        wp_add_inline_style( 'jetpack-search-layout', static::search_layout_inline_css() );
1538    }
1539
1540    /**
1541     * Inline CSS for the responsive search-results layout shared across the
1542     * overlay, embedded (`jetpack-search.html`), and WC product
1543     * (`jetpack-search-product-results.html`) templates.
1544     *
1545     * Below 992px the right-column filter sidebar collapses to a popover
1546     * trigger docked next to results-sort; at >= 992px the sidebar is the
1547     * sole filter UI and the in-header popover is hidden so the two don't
1548     * double up. Same breakpoint as the legacy Instant Search overlay
1549     * (`.jetpack-instant-search__search-results-secondary { display: none }`
1550     * below `$break-lg`). Lives next to `block_template_overlay_inline_css()`
1551     * (which keeps overlay-only chrome) because the rules target the
1552     * templates' outer columns + results-header, none of which any single
1553     * block owns.
1554     *
1555     * @return string
1556     */
1557    protected static function search_layout_inline_css(): string {
1558        return <<<'CSS'
1559/* The block group already carries `layout.type:flex` which makes the WordPress
1560 * block-layout system emit `display:flex` / `flex-wrap:nowrap` /
1561 * `justify-content:space-between`. Restating them is defensive (decouples us
1562 * from block-layout CSS being present); the operative net-new rule is
1563 * `align-items: center`, which centers `results-count` against the controls
1564 * cluster. */
1565.jetpack-search-layout__results-header {
1566    display: flex;
1567    flex-wrap: nowrap;
1568    justify-content: space-between;
1569    align-items: center;
1570}
1571/* Right-side controls cluster: sort + filters-popover trigger. Without this
1572 * the three `__results-header` children get spread evenly by the parent's
1573 * `space-between`; nesting sort + popover here pins them as one block on the
1574 * trailing edge. */
1575.jetpack-search-layout__results-header-controls {
1576    display: flex;
1577    flex-wrap: nowrap;
1578    align-items: center;
1579    gap: 0.75rem;
1580}
1581/* Name the columns row as the layout container so the sidebar/popover flip
1582 * tracks its inline-size. The `@media` rules below are the universal base —
1583 * they fire in every browser (including legacy ones without container-query
1584 * support) and they drive standalone usage outside the named container (no
1585 * container ancestor → only `@media` applies). The `@container` rule further
1586 * down overrides `@media` via source-order cascade at equal specificity when
1587 * the named container is in scope AND narrower than 992px. The override has
1588 * to undo `@media (min-width: 992px)`'s `popover { display: none }`
1589 * explicitly: in the "wide viewport, narrow container" case `@media
1590 * (min-width: 992px)` keeps firing on the viewport width and would otherwise
1591 * leave the visitor with no filter UI at all. `@container (min-width: 992px)`
1592 * isn't defined — container width is bounded by viewport width in practice,
1593 * so the matching `@media (min-width: 992px)` already covers the wide case. */
1594.wp-block-columns:has(> .jetpack-search-layout__filters-column) {
1595    container-type: inline-size;
1596    container-name: jetpack-search-layout;
1597}
1598/* Below 992px the right-column filter sidebar collapses to a popover trigger
1599 * docked next to results-sort. The trigger comes from the
1600 * `jetpack-search/filters-popover` block that ships in each template. The
1601 * selector is scoped to the named outer column so nested `wp-block-column`s
1602 * inside result-card templates aren't affected. */
1603@media (max-width: 991.98px) {
1604    .jetpack-search-layout__filters-column {
1605        display: none;
1606    }
1607    /* `!important` defends against the parent `wp:columns` block-layout CSS
1608     * that pins `.wp-block-column` to its inline `flex-basis` (or to an even
1609     * split when no width is set). Once the filter column is `display:none`,
1610     * the results column has to be able to claim the full row at any
1611     * specificity. */
1612    .jetpack-search-layout__results-column {
1613        flex-basis: 100% !important;
1614    }
1615}
1616/* Sidebar left divider tracks `currentColor` so the hairline stays subtle on
1617 * light themes and visible on dark themes, matching the search-input
1618 * underline. We only set color; each template's column block sets
1619 * `border-left-width: 1px` inline. Fallback to `transparent` so themes/UAs
1620 * without `color-mix` support get an invisible divider rather than a hard
1621 * grey rule. */
1622.jetpack-search-layout__filters-column {
1623    border-left-color: transparent;
1624}
1625@supports (border-color: color-mix(in sRGB, black 50%, white)) {
1626    .jetpack-search-layout__filters-column {
1627        border-left-color: color-mix(in sRGB, currentColor 15%, transparent);
1628    }
1629}
1630/* Sidebar-showing rules (>= 992px). The corner-join is structural: the
1631 * columns row is pulled flush to the search-input hairline and breathing
1632 * room re-added as internal column padding, so the filters column's
1633 * `border-left` runs the row's full height — hairline (top) to end-of-div
1634 * (bottom). Three vertical gaps are neutralised:
1635 *
1636 *   a) `margin-block-start` on the row (outer group's `spacing.blockGap` or
1637 *      the theme's default block-gap) — zeroed.
1638 *
1639 *   b) `.is-layout-flex { align-items: center }` (theme/core default), which
1640 *      centres the shorter filters column and drops its top edge. Overridden
1641 *      to `stretch` (not `flex-start`) so the column also grows to full row
1642 *      height; it's flow layout, so its content stays top-aligned regardless.
1643 *
1644 *   c) Overlay-only: SEARCH-243's content-group inset sits outside the
1645 *      columns, so the stretched column stops short of the card edges (below
1646 *      the `::before` hairline at the top, and short of the bottom). Zeroed
1647 *      on the group's block axis and re-added on the columns, both sides
1648 *      reading the same `--jp-search-overlay-content-pad-*` tokens the group
1649 *      itself uses — so the divider reaches both edges while content keeps
1650 *      its breathing room, and the two sites can't drift.
1651 *
1652 * `.is-layout-flex` bumps the columns selector to (0,3,0) to outrank
1653 * per-container `blockGap` CSS; `:has(> filters-column)` scopes it to our
1654 * rows. These target the row/group, which `@container` can't reach from
1655 * inside the named container, so they stay viewport-driven — harmless when
1656 * the sidebar collapses below 992px. (b) is also a no-op wherever WP core's
1657 * `.wp-block-columns { align-items: normal !important }` is present; see
1658 * AGENTS.md. */
1659@media (min-width: 992px) {
1660    /* Sidebar shown, popover-in-results-header hidden. The `@container
1661     * (max-width: 991.98px)` block below re-shows the popover when the
1662     * named container is narrower than the viewport. */
1663    .jetpack-search-layout__results-header .jetpack-search-filters-popover {
1664        display: none;
1665    }
1666    .wp-block-columns.is-layout-flex:has(> .jetpack-search-layout__filters-column) {
1667        align-items: stretch;
1668        margin-block-start: 0;
1669    }
1670    .jetpack-search-block-overlay__content > .wp-block-group:first-child:has(.jetpack-search-layout__filters-column) {
1671        padding-top: 0;
1672        padding-bottom: 0;
1673    }
1674    .wp-block-columns:has(> .jetpack-search-layout__filters-column) > .wp-block-column {
1675        padding-top: var(--jp-search-overlay-content-pad-block-start, 0.5em);
1676    }
1677    .jetpack-search-block-overlay__content .wp-block-columns:has(> .jetpack-search-layout__filters-column) > .wp-block-column {
1678        padding-bottom: var(--jp-search-overlay-content-pad-block-end, 2em);
1679    }
1680}
1681/* @container override: applies when the named container exists. Placed AFTER
1682 * the `@media` rules so source-order cascade lets it win over them at equal
1683 * specificity. In "wide viewport, narrow container" (the case the change is
1684 * meant to fix), `@media (max-width: 991.98px)` doesn't fire but `@media
1685 * (min-width: 992px)` does — this block undoes the latter's `popover {
1686 * display: none }` via `display: inline-block` and hides the sidebar that
1687 * the `@media (max-width)` rule wouldn't have hidden at this viewport. Same
1688 * `!important` reasoning on `flex-basis: 100%` as the @media block. */
1689@container jetpack-search-layout (max-width: 991.98px) {
1690    .jetpack-search-layout__filters-column {
1691        display: none;
1692    }
1693    .jetpack-search-layout__results-column {
1694        flex-basis: 100% !important;
1695    }
1696    .jetpack-search-layout__results-header .jetpack-search-filters-popover {
1697        display: inline-block;
1698    }
1699}
1700CSS;
1701    }
1702
1703    /**
1704     * Product-search counterpart of `get_search_template_content()`.
1705     *
1706     * @return string Block markup for the product-search template.
1707     */
1708    protected static function get_product_search_template_content(): string {
1709        $template_path = __DIR__ . '/templates/jetpack-search-product-results.html';
1710        // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents -- local, bundled template file.
1711        $raw = is_readable( $template_path ) ? (string) file_get_contents( $template_path ) : '';
1712        return static::sync_filters_popover_content( static::substitute_template_placeholders( $raw ) );
1713    }
1714
1715    /**
1716     * Substitute `{{FILTER_HEADING}}` / `{{HEADER_SLUG}}` / `{{FOOTER_SLUG}}` in a
1717     * bundled template. Empty input passes through.
1718     *
1719     * @param string $raw Raw template-file contents.
1720     * @return string
1721     */
1722    protected static function substitute_template_placeholders( string $raw ): string {
1723        if ( '' === $raw ) {
1724            return $raw;
1725        }
1726        $slugs = static::resolve_chrome_slugs();
1727        return str_replace(
1728            array( '{{FILTER_HEADING}}', '{{HEADER_SLUG}}', '{{FOOTER_SLUG}}' ),
1729            array(
1730                esc_html__( 'Filter options', 'jetpack-search-pkg' ),
1731                $slugs['header'],
1732                $slugs['footer'],
1733            ),
1734            $raw
1735        );
1736    }
1737
1738    /**
1739     * Active theme's chrome slugs. Test seam; resolver lives on
1740     * `Theme_Chrome_Slug_Resolver`.
1741     *
1742     * @return array{header:string,footer:string}
1743     */
1744    protected static function resolve_chrome_slugs(): array {
1745        return Theme_Chrome_Slug_Resolver::resolve();
1746    }
1747
1748    /**
1749     * Names of the "source of truth" filter-composition blocks — whichever is
1750     * present in a template supplies the canonical filter config that
1751     * `jetpack-search/filters-popover` mirrors. See {@see sync_filters_popover_content()}.
1752     */
1753    const FILTERS_SOURCE_BLOCK_NAMES = array( 'jetpack-search/filters', 'jetpack-search/filters-product' );
1754
1755    /**
1756     * `jetpack-search/filters-popover` (the collapsible/mobile filter panel) and
1757     * `jetpack-search/filters` / `jetpack-search/filters-product` (the wide-viewport
1758     * sidebar) are two independently-serialized copies of the same filter
1759     * configuration, shown one-or-the-other via a CSS breakpoint. Nothing keeps
1760     * them in sync, so editing one silently leaves the other stale (SEARCH-307).
1761     *
1762     * Rather than a two-way sync, the sidebar block is treated as the single
1763     * source of truth: every time template content is read — for rendering or
1764     * for editing — the popover's inner blocks are recomputed to mirror
1765     * whatever the sidebar currently contains. A direct edit to the popover's
1766     * own inner blocks still saves, but is overwritten back to match the
1767     * sidebar on the next read; self-healing, no migration needed for content
1768     * that already diverged before this existed.
1769     *
1770     * @param string $content Block markup, e.g. a full template or singleton-CPT post_content.
1771     * @return string Block markup with the popover's inner blocks synced to the sidebar's, unchanged if either block is absent.
1772     */
1773    public static function sync_filters_popover_content( string $content ): string {
1774        if ( '' === $content || false === strpos( $content, 'jetpack-search/filters-popover' ) ) {
1775            return $content;
1776        }
1777        $blocks = parse_blocks( $content );
1778        $source = static::find_block_by_name( $blocks, self::FILTERS_SOURCE_BLOCK_NAMES );
1779        if ( null === $source ) {
1780            return $content;
1781        }
1782        $replaced = static::replace_block_inner_content( $blocks, 'jetpack-search/filters-popover', $source );
1783        return $replaced ? serialize_blocks( $blocks ) : $content;
1784    }
1785
1786    /**
1787     * Depth-first search for the first block matching one of `$names`.
1788     *
1789     * @param array<int,array<string,mixed>> $blocks Parsed blocks (`parse_blocks()` shape).
1790     * @param string[]                       $names  Block names to match.
1791     * @return array<string,mixed>|null
1792     */
1793    protected static function find_block_by_name( array $blocks, array $names ): ?array {
1794        foreach ( $blocks as $block ) {
1795            if ( in_array( $block['blockName'], $names, true ) ) {
1796                return $block;
1797            }
1798            if ( ! empty( $block['innerBlocks'] ) ) {
1799                $found = static::find_block_by_name( $block['innerBlocks'], $names );
1800                if ( null !== $found ) {
1801                    return $found;
1802                }
1803            }
1804        }
1805        return null;
1806    }
1807
1808    /**
1809     * Depth-first search that overwrites the first block named `$name` with
1810     * `$source`'s inner blocks. `innerBlocks`/`innerContent`/`innerHTML` are
1811     * copied together from `$source` so the null-placeholder bookkeeping in
1812     * `innerContent` stays internally consistent regardless of how many
1813     * filters `$source` has.
1814     *
1815     * @param array<int,array<string,mixed>> $blocks Parsed blocks, modified in place.
1816     * @param string                         $name   Block name to replace.
1817     * @param array<string,mixed>            $source Block whose inner content is cloned onto the match.
1818     * @return bool Whether a match was found and replaced.
1819     */
1820    protected static function replace_block_inner_content( array &$blocks, string $name, array $source ): bool {
1821        foreach ( $blocks as &$block ) {
1822            if ( $block['blockName'] === $name ) {
1823                $block['innerBlocks']  = $source['innerBlocks'];
1824                $block['innerContent'] = $source['innerContent'];
1825                $block['innerHTML']    = $source['innerHTML'];
1826                return true;
1827            }
1828            if ( ! empty( $block['innerBlocks'] ) && static::replace_block_inner_content( $block['innerBlocks'], $name, $source ) ) {
1829                return true;
1830            }
1831        }
1832        return false;
1833    }
1834
1835    /**
1836     * Idempotent wrapper around `register_block_template`. Unregisters first so
1837     * a stale entry from a prior init (long-lived PHP-FPM worker) is replaced
1838     * rather than triggering `doing_it_wrong`.
1839     *
1840     * @param string              $name Fully-qualified template name.
1841     * @param array<string,mixed> $args Args for register_block_template().
1842     */
1843    protected static function replace_block_template( string $name, array $args ) {
1844        if ( class_exists( '\WP_Block_Templates_Registry' ) ) {
1845            $registry = \WP_Block_Templates_Registry::get_instance();
1846            if ( $registry->is_registered( $name ) ) {
1847                $registry->unregister( $name );
1848            }
1849        }
1850        register_block_template( $name, $args );
1851    }
1852
1853    /**
1854     * Counterpart of `register_search_template()` for product search.
1855     */
1856    public static function register_product_search_template() {
1857        if ( ! function_exists( 'register_block_template' ) || ! static::block_templates_active() ) {
1858            return;
1859        }
1860        $content = static::get_product_search_template_content();
1861        if ( '' === $content ) {
1862            return;
1863        }
1864        static::replace_block_template(
1865            static::get_parent_plugin_slug() . '//' . self::PRODUCT_SEARCH_TEMPLATE_SLUG,
1866            array(
1867                'title'       => __( 'Jetpack Search Product Results', 'jetpack-search-pkg' ),
1868                'description' => __( 'Displays WooCommerce product search results with Jetpack Search filters.', 'jetpack-search-pkg' ),
1869                'content'     => $content,
1870            )
1871        );
1872    }
1873
1874    /**
1875     * Directory slug of the plugin that owns the template in the Site Editor UI.
1876     * Picked by preference so the more-specific "Jetpack Search" label wins
1877     * when both the standalone plugin and the Jetpack monolith are active:
1878     * `jetpack-search` → `jetpack` → `jetpack-search` fallback.
1879     *
1880     * @return string
1881     */
1882    protected static function get_parent_plugin_slug(): string {
1883        $active    = Helper::get_active_plugins();
1884        $preferred = array(
1885            'jetpack-search' => 'jetpack-search/jetpack-search.php',
1886            'jetpack'        => 'jetpack/jetpack.php',
1887        );
1888        foreach ( $preferred as $slug => $plugin_file ) {
1889            if ( in_array( $plugin_file, $active, true ) ) {
1890                return $slug;
1891            }
1892        }
1893        return 'jetpack-search';
1894    }
1895
1896    /**
1897     * Prepend the Jetpack Search slug to the search template hierarchy on
1898     * block-theme search requests. Existing occurrences are stripped first
1899     * so a second init pass / another filter on the same hook can't dup.
1900     *
1901     * WooCommerce product-search carve-out: override off → leave to WC's
1902     * prepend; override on → fall through here, then
1903     * `route_woocommerce_product_search_template()` swaps WC's slug for ours.
1904     *
1905     * @param string[] $templates Template hierarchy slugs.
1906     * @return string[]
1907     */
1908    public static function prepend_search_template( $templates ) {
1909        if ( ! is_search() || ! static::block_templates_active() ) {
1910            return $templates;
1911        }
1912        if ( ! static::woocommerce_search_template_override_enabled() && static::is_woocommerce_product_search() ) {
1913            return $templates;
1914        }
1915        $templates = array_values(
1916            array_filter(
1917                (array) $templates,
1918                static function ( $slug ) {
1919                    return self::SEARCH_TEMPLATE_SLUG !== $slug;
1920                }
1921            )
1922        );
1923        array_unshift( $templates, self::SEARCH_TEMPLATE_SLUG );
1924        return $templates;
1925    }
1926
1927    /**
1928     * Classic-theme counterpart to `prepend_search_template()`. Block-theme
1929     * hierarchy filters are a no-op on classic themes — `locate_template()`
1930     * walks slugs as `{slug}.php` and a classic theme doesn't ship one for
1931     * our slug. So let the hierarchy resolve normally, then swap the path
1932     * via `template_include` to our bundled PHP shim, which renders the same
1933     * block markup inside the theme's `get_header()`/`get_footer()`.
1934     *
1935     * @param string $template Resolved template path.
1936     * @return string
1937     */
1938    public static function route_classic_theme_search_template( $template ) {
1939        if ( ! is_search() ) {
1940            return $template;
1941        }
1942        $is_product_search = static::is_woocommerce_product_search();
1943        // Override off: leave product search to WooCommerce / the theme's own
1944        // archive routing — we don't impose the product shim without opt-in.
1945        if ( ! static::woocommerce_search_template_override_enabled() && $is_product_search ) {
1946            return $template;
1947        }
1948        // Override on + product search: route to the product-results shim.
1949        // Bail back to the theme's template if neither a customization nor a
1950        // bundled body is available — rendering header/footer around an empty
1951        // body looks broken.
1952        if ( $is_product_search ) {
1953            if ( null === Product_Search_Template::get_customized_content() && '' === static::get_classic_theme_product_search_body() ) {
1954                return $template;
1955            }
1956            return __DIR__ . '/templates/classic-theme-product-search.php';
1957        }
1958        // Regular (non-product) search: only Embedded takes over the whole search
1959        // page. Inline registers this router too (for the product shim above) but
1960        // leaves regular searches to the theme, so bail here unless Embedded.
1961        if ( Module_Control::EXPERIENCE_EMBEDDED !== ( new Module_Control() )->get_experience() ) {
1962            return $template;
1963        }
1964        // Same empty-body bail-out for the generic shim. A saved empty
1965        // customization ('' vs null) is honored as intentional.
1966        if ( null === Search_Template::get_customized_content() && '' === static::get_classic_theme_search_body() ) {
1967            return $template;
1968        }
1969        return __DIR__ . '/templates/classic-theme-search.php';
1970    }
1971
1972    /**
1973     * Classic-theme search body — same markup as the block-theme path with
1974     * top-level `core/template-part` references stripped so the theme's
1975     * `get_header()` / `get_footer()` drive the chrome.
1976     *
1977     * Source of truth: customized `Search_Template` CPT → bundled `jetpack-search.html`.
1978     * Public because `templates/classic-theme-search.php` calls it from outside the class.
1979     *
1980     * @return string Block markup, no template-part wrappers.
1981     */
1982    public static function get_classic_theme_search_body(): string {
1983        $customized = Search_Template::get_customized_content();
1984        if ( null !== $customized ) {
1985            return $customized;
1986        }
1987        return static::strip_top_level_template_parts( static::get_search_template_content() );
1988    }
1989
1990    /**
1991     * Product-search counterpart to {@see get_classic_theme_search_body()} —
1992     * source of truth for the classic-theme product-results shim. Customized
1993     * `Product_Search_Template` CPT → bundled `jetpack-search-product-results.html`.
1994     * Public because `templates/classic-theme-product-search.php` calls it from
1995     * outside the class.
1996     *
1997     * @return string Block markup, no template-part wrappers.
1998     */
1999    public static function get_classic_theme_product_search_body(): string {
2000        $customized = Product_Search_Template::get_customized_content();
2001        if ( null !== $customized ) {
2002            return $customized;
2003        }
2004        return static::strip_top_level_template_parts( static::get_product_search_template_content() );
2005    }
2006
2007    /**
2008     * Strip top-level `core/template-part` self-closing comments — classic
2009     * themes can't resolve their slugs. Non-greedy `.*?` capped by `-->` keeps
2010     * matching cleanly across template revisions and across nested attribute
2011     * payloads.
2012     *
2013     * @param string $content Block markup, possibly empty.
2014     * @return string
2015     */
2016    protected static function strip_top_level_template_parts( string $content ): string {
2017        if ( '' === $content ) {
2018            return '';
2019        }
2020        return (string) preg_replace( '#<!--\s*wp:template-part\s+.*?/-->\s*#s', '', $content );
2021    }
2022
2023    /**
2024     * Inline layout `<style>` block the classic-theme shims emit before the
2025     * bundled block markup. Classic themes don't emit core's block-supports
2026     * layout CSS, so two traits the bundled templates rely on collapse on
2027     * classic themes: the inner group's 1.5rem `blockGap` vanishes (search
2028     * input runs straight into the results row), and `alignwide` has no
2029     * effect (content stretches edge-to-edge because `template_include`
2030     * bypasses the theme's own content wrapper). Reapplying both, scoped to
2031     * `<main class="wp-block-group">`, restores parity without leaking
2032     * outside the shim. Shared by both shims so a future layout tweak
2033     * touches one place. The `<style>` `id` is unique per render — routing
2034     * ensures only one shim runs per request, so duplicate IDs can't occur.
2035     *
2036     * Public because both `templates/classic-theme-search.php` and
2037     * `templates/classic-theme-product-search.php` call it from outside the
2038     * class.
2039     *
2040     * @return string Inline `<style>` element ready to echo.
2041     */
2042    public static function get_classic_theme_layout_style(): string {
2043        return <<<'HTML'
2044<style id="jetpack-search-classic-theme-layout">
2045main.wp-block-group {
2046    max-width: var(--wp--style--global--wide-size, 1280px);
2047    margin-inline: auto;
2048    padding-inline: clamp(1rem, 4vw, 2rem);
2049}
2050main.wp-block-group .is-layout-flow > * + * {
2051    margin-block-start: var(--wp--style--block-gap, 1.5rem);
2052}
2053</style>
2054HTML;
2055    }
2056
2057    /**
2058     * Test override for `block_templates_active()`. Null = read the live state.
2059     *
2060     * @var bool|null
2061     */
2062    private static $block_templates_active_for_testing = null;
2063
2064    /**
2065     * Test seam. Set true/false to force `block_templates_active()`, or null to clear.
2066     *
2067     * @param bool|null $active Forced value, or null to clear.
2068     */
2069    public static function set_block_templates_active_for_testing( ?bool $active ): void {
2070        self::$block_templates_active_for_testing = $active;
2071    }
2072
2073    /**
2074     * Whether the theme resolves block templates. Overridable seam over
2075     * `wp_is_block_theme()` for tests.
2076     *
2077     * @return bool
2078     */
2079    protected static function block_templates_active(): bool {
2080        if ( null !== self::$block_templates_active_for_testing ) {
2081            return self::$block_templates_active_for_testing;
2082        }
2083        return wp_is_block_theme();
2084    }
2085
2086    /**
2087     * Front the `jetpack-search-product-results` template for WC product
2088     * search. Drops WC's `product-search-results` and unshifts ours so it
2089     * resolves before any `jetpack-search` prepend for the generic route.
2090     *
2091     * @param string[] $templates Template hierarchy slugs.
2092     * @return string[]
2093     */
2094    public static function route_woocommerce_product_search_template( $templates ) {
2095        // FSE-hierarchy work — classic themes resolve template slugs as `{slug}.php`
2096        // and there's no `jetpack-search-product-results.php`. The classic-theme
2097        // equivalent runs through `route_classic_theme_search_template()` instead.
2098        if ( ! static::block_templates_active() || ! static::is_woocommerce_product_search() ) {
2099            return $templates;
2100        }
2101        $templates = array_values(
2102            array_filter(
2103                (array) $templates,
2104                static function ( $slug ) {
2105                    return self::WC_PRODUCT_SEARCH_TEMPLATE_SLUG !== $slug
2106                        && self::PRODUCT_SEARCH_TEMPLATE_SLUG !== $slug;
2107                }
2108            )
2109        );
2110        array_unshift( $templates, self::PRODUCT_SEARCH_TEMPLATE_SLUG );
2111        return $templates;
2112    }
2113
2114    /**
2115     * Seed the Interactivity API store with initial state. Per-block render
2116     * callbacks deep-merge their own entries on top (e.g. filter-checkbox
2117     * writes its filterConfig). See AGENTS.md § Hydration & SSR seeding.
2118     */
2119    public static function seed_interactivity_state() {
2120        if ( ! function_exists( 'wp_interactivity_state' ) ) {
2121            return;
2122        }
2123        wp_interactivity_state(
2124            'jetpack-search',
2125            static::build_seed_state( static::collect_filter_configs_from_post() )
2126        );
2127    }
2128
2129    /**
2130     * Compose the final seeded state for `wp_interactivity_state()`.
2131     *
2132     * @param array<string, array<string, mixed>> $filter_configs Map of filter configs.
2133     * @return array<string, mixed>
2134     */
2135    public static function build_seed_state( array $filter_configs ): array {
2136        $state                  = static::build_initial_state();
2137        $state['filterConfigs'] = $filter_configs;
2138        return $state;
2139    }
2140
2141    /**
2142     * Walk the current post's block tree for filter blocks and build the
2143     * filterConfigs map. Template-part scans are not performed — a filter
2144     * inside a template part still works, but its config isn't available to
2145     * the search-results SSR until hydration.
2146     *
2147     * @return array<string, array<string, mixed>>
2148     */
2149    protected static function collect_filter_configs_from_post(): array {
2150        if ( ! function_exists( 'get_post' ) || ! function_exists( 'parse_blocks' ) ) {
2151            return array();
2152        }
2153        // Bail if any helper is missing — half-loaded feature would ship inconsistent filterConfigs.
2154        $helpers = static::filter_block_helpers();
2155        foreach ( $helpers as $helper ) {
2156            if ( ! class_exists( $helper ) ) {
2157                return array();
2158            }
2159        }
2160        $post = get_post();
2161        if ( ! $post || empty( $post->post_content ) ) {
2162            return array();
2163        }
2164        if ( ! static::post_content_has_filter_block( $post, array_keys( $helpers ) ) ) {
2165            return array();
2166        }
2167        $configs = array();
2168        static::walk_blocks_for_filter_configs( parse_blocks( $post->post_content ), $configs );
2169        return $configs;
2170    }
2171
2172    /**
2173     * Does the post contain any of the given block names? SEARCH-295: a
2174     * has_block() scan to gate parse_blocks() on large, filter-less posts.
2175     *
2176     * @param \WP_Post $post        Post to scan.
2177     * @param string[] $block_names Block names to scan for.
2178     * @return bool
2179     */
2180    protected static function post_content_has_filter_block( \WP_Post $post, array $block_names ): bool {
2181        foreach ( $block_names as $block_name ) {
2182            if ( has_block( $block_name, $post ) ) {
2183                return true;
2184            }
2185        }
2186        return false;
2187    }
2188
2189    /**
2190     * Map of filter block name → helper class. Add a new filter block type
2191     * by appending one entry here.
2192     *
2193     * @return array<string, class-string>
2194     */
2195    protected static function filter_block_helpers(): array {
2196        $helpers = array(
2197            'jetpack-search/filter-checkbox'        => Filter_Checkbox::class,
2198            'jetpack-search/filter-date'            => Filter_Date::class,
2199            'jetpack-search/filter-wc-rating'       => Filter_Wc_Rating::class,
2200            'jetpack-search/filter-wc-attribute'    => Filter_Wc_Attribute::class,
2201            'jetpack-search/filter-wc-stock-status' => Search_Product_Filter_Status::class,
2202        );
2203        if ( self::woocommerce_blocks_enabled() ) {
2204            return $helpers;
2205        }
2206        // Non-Woo sites: drop WC-only entries so the filter-config walk stays
2207        // symmetric with what `register_blocks()` actually registered.
2208        foreach ( array_keys( $helpers ) as $name ) {
2209            if ( self::is_woocommerce_only_block( $name ) ) {
2210                unset( $helpers[ $name ] );
2211            }
2212        }
2213        return $helpers;
2214    }
2215
2216    /**
2217     * Recursively walk a parsed block tree, pushing each filter block's
2218     * config into `$configs` by reference.
2219     *
2220     * @param array $blocks  Parsed block tree from parse_blocks().
2221     * @param array $configs Accumulator map keyed by filterKey.
2222     * @return void
2223     */
2224    protected static function walk_blocks_for_filter_configs( array $blocks, array &$configs ): void {
2225        $helpers = static::filter_block_helpers();
2226        foreach ( $blocks as $block ) {
2227            if ( ! is_array( $block ) ) {
2228                continue;
2229            }
2230            $block_name = (string) ( $block['blockName'] ?? '' );
2231            if ( isset( $helpers[ $block_name ] ) ) {
2232                $helper = $helpers[ $block_name ];
2233                $attrs  = (array) ( $block['attrs'] ?? array() );
2234                $key    = $helper::derive_filter_key( $attrs );
2235                if ( '' !== $key ) {
2236                    $configs[ $key ] = $helper::build_config( $attrs, $key );
2237                }
2238            }
2239
2240            if ( ! empty( $block['innerBlocks'] ) && is_array( $block['innerBlocks'] ) ) {
2241                static::walk_blocks_for_filter_configs( $block['innerBlocks'], $configs );
2242            }
2243        }
2244    }
2245
2246    /**
2247     * Build the initial state array for the jetpack-search Interactivity API store.
2248     *
2249     * @return array<string, mixed>
2250     */
2251    public static function build_initial_state() {
2252        $is_private                = class_exists( Status::class ) ? ( new Status() )->is_private_site() : false;
2253        $is_wpcom                  = class_exists( Helper::class ) ? Helper::is_wpcom() : false;
2254        $site_id                   = class_exists( Helper::class ) ? Helper::get_wpcom_site_id() : 0;
2255        $is_jetpack_photon_enabled = method_exists( 'Jetpack', 'is_module_active' ) && \Jetpack::is_module_active( 'photon' );
2256        $search_query              = static::parse_url_search_query();
2257        $active_filters            = static::parse_url_filters();
2258        $filter_logic              = static::parse_url_filter_logic( $active_filters );
2259        $price_range               = static::parse_url_price_range();
2260        $is_initial_loading        = static::is_initial_loading();
2261        $searching_text            = function_exists( '__' ) ? __( 'Searching…', 'jetpack-search-pkg' ) : 'Searching…';
2262        $query_options             = static::get_instant_search_query_options();
2263
2264        return array(
2265            // Connection / routing config.
2266            'siteId'                     => $site_id,
2267            'apiRoot'                    => function_exists( 'rest_url' ) ? esc_url_raw( rest_url() ) : '',
2268            'nonce'                      => function_exists( 'wp_create_nonce' ) ? wp_create_nonce( 'wp_rest' ) : '',
2269            'isPrivateSite'              => $is_private,
2270            'isWpcom'                    => $is_wpcom,
2271            'isPhotonEnabled'            => ( $is_wpcom || $is_jetpack_photon_enabled ) && ! $is_private,
2272            // TrainTracks gate, mirroring instant search's `disableTracking`
2273            // (Helper::get_search_options): suppresses `_tkq` pushes for
2274            // `?disable_tracking=1` crawlers/QA and the filter override.
2275            'disableTracking'            => static::is_tracking_disabled(),
2276            // Threaded through url-state so `?orderby=price_asc` round-trips on Woo only.
2277            'isWooCommerceBlocksEnabled' => self::woocommerce_blocks_enabled(),
2278            'homeUrl'                    => function_exists( 'home_url' ) ? home_url() : '',
2279            // Blog locale (not viewer's profile locale) for consistent
2280            // logged-out formatting. BCP47-ish (`en-US`).
2281            'locale'                     => function_exists( 'get_locale' )
2282                ? str_replace( '_', '-', get_locale() )
2283                : 'en-US',
2284            // PHP-style token string parsed client-side by `wp-date-format.js`
2285            // (IA view bundle can't import `@wordpress/date`). Empty → Intl fallback.
2286            'dateFormat'                 => function_exists( 'get_option' )
2287                ? (string) get_option( 'date_format', '' )
2288                : '',
2289
2290            // URL-seeded so deep links render on first paint.
2291            'searchQuery'                => $search_query,
2292            // `?s=` (empty value) must still fire the initial fetch; `searchQuery`
2293            // alone collapses present-but-empty and missing to `''`.
2294            'hasSearchParam'             => static::has_search_param(),
2295            'searchParamName'            => static::get_search_param_name(),
2296            'sortOrder'                  => static::parse_url_sort(),
2297            'activeFilters'              => $active_filters,
2298            'filterLogic'                => $filter_logic,
2299            'priceRange'                 => $price_range,
2300            // Scalar `?filter_id=value`; seeded as `{}` so JS readers see a defined shape.
2301            'staticFilterSelections'     => (object) array(),
2302
2303            // Each filter block's render.php deep-merges its entry. Shape:
2304            // `{ [key]: { filterKey, filterType, taxonomy, effectiveSlug, label, showCount, maxItems } }`.
2305            'filterConfigs'              => array(),
2306
2307            // JS hydration fills these. `aggregations` is stdClass so JS sees `{}`.
2308            'results'                    => array(),
2309            'aggregations'               => (object) array(),
2310            // See AGENTS.md § Filter bucket lifecycle.
2311            'retainedFilterOptions'      => (object) array(),
2312            'totalResults'               => 0,
2313            'pageHandle'                 => null,
2314
2315            // `isLoading` true on deep links keeps the empty-state hidden until
2316            // JS fires the initial fetch (otherwise "No results found" flashes).
2317            'isLoading'                  => $is_initial_loading,
2318            'isLoadingMore'              => false,
2319            'hasError'                   => false,
2320
2321            // Seeded so SSR resolves `data-wp-text` on first paint.
2322            'resultsCountText'           => $is_initial_loading ? $searching_text : '',
2323
2324            'strings'                    => static::build_initial_strings(),
2325            'priceCurrencySymbol'        => '$',
2326
2327            // Top-level (not under `strings`) — keeps Phan's `array<string,string>`
2328            // contract on `strings` intact.
2329            'aiExtendedLoadingHints'     => static::build_ai_extended_loading_hints(),
2330
2331            'wcStockStatusLabels'        => static::build_stock_status_labels(),
2332
2333            // Query customization from `jetpack_instant_search_options` — same
2334            // keys Instant Search / Inline Search honor, so Embedded and the
2335            // blocks Overlay stay compatible with those filters.
2336            'highlightPhraseOnly'        => $query_options['highlightPhraseOnly'],
2337            'highlightFilterStopwords'   => $query_options['highlightFilterStopwords'],
2338            'highlightFields'            => $query_options['highlightFields'],
2339            'additionalBlogIds'          => $query_options['additionalBlogIds'],
2340            'adminQueryFilter'           => $query_options['adminQueryFilter'],
2341            'customResults'              => $query_options['customResults'],
2342        );
2343    }
2344
2345    /**
2346     * Read Instant Search query-customization options for the blocks store.
2347     *
2348     * @since 7.4.0
2349     *
2350     * @return array Query options with keys:
2351     *               `highlightPhraseOnly`, `highlightFilterStopwords`, `highlightFields`,
2352     *               `additionalBlogIds`, `adminQueryFilter`, and `customResults`.
2353     */
2354    public static function get_instant_search_query_options(): array {
2355        return Helper::get_instant_search_query_options();
2356    }
2357
2358    /**
2359     * Slug → display-label map for `wc_stock_status` selections, used by the
2360     * active-filters block for product-aware chips. RSM-1932 will swap this
2361     * for WC's translated labels (`wc_get_product_stock_status_options()`)
2362     * without changing the shape. Empty when the status helper isn't loaded.
2363     *
2364     * @return array<string, string>
2365     */
2366    protected static function build_stock_status_labels(): array {
2367        if ( ! class_exists( Search_Product_Filter_Status::class ) ) {
2368            return array();
2369        }
2370        $labels = array();
2371        foreach ( Search_Product_Filter_Status::get_options() as $option ) {
2372            $value = (string) ( $option['value'] ?? '' );
2373            if ( '' === $value ) {
2374                continue;
2375            }
2376            $labels[ $value ] = (string) ( $option['label'] ?? $value );
2377        }
2378        return $labels;
2379    }
2380
2381    /**
2382     * Every block directory to register, parents first then their children.
2383     *
2384     * A block directory may nest child blocks that only ever render inside it
2385     * (`no-results/slot`). They live there rather than beside their parent so
2386     * the relationship is obvious in the tree, and they inherit the parent's
2387     * WooCommerce gating for free — a skipped parent is never descended into.
2388     *
2389     * @internal Public only so the registration walk can be asserted directly.
2390     *
2391     * @return string[] Absolute directory paths, each holding a `block.json`.
2392     */
2393    public static function block_directories(): array {
2394        $block_dirs = glob( __DIR__ . '/blocks/*', GLOB_ONLYDIR );
2395        if ( ! $block_dirs ) {
2396            return array();
2397        }
2398
2399        $wc_blocks_enabled = self::woocommerce_blocks_enabled();
2400        $directories       = array();
2401        foreach ( $block_dirs as $block_dir ) {
2402            if ( ! file_exists( $block_dir . '/block.json' ) ) {
2403                continue;
2404            }
2405            if ( ! $wc_blocks_enabled && self::is_woocommerce_only_block( basename( $block_dir ) ) ) {
2406                continue;
2407            }
2408            $directories[] = $block_dir;
2409
2410            foreach ( (array) glob( $block_dir . '/*', GLOB_ONLYDIR ) as $child_dir ) {
2411                if ( file_exists( $child_dir . '/block.json' ) ) {
2412                    $directories[] = $child_dir;
2413                }
2414            }
2415        }
2416
2417        return $directories;
2418    }
2419
2420    /**
2421     * Whether the URL carries a search query, filter, or price range — i.e.
2422     * the JS store will fire an initial fetch on hydration. Render callbacks
2423     * use this to emit pre-hydration affordances (skeleton, "Searching…").
2424     *
2425     * URL-derived rather than read back from `wp_interactivity_state()`
2426     * because FSE pre-resolves block attributes before `wp_enqueue_scripts`
2427     * fires, so a state-read would silently return false on the very pages
2428     * this is meant to flag. Mirrors the `isLoading` seed exactly.
2429     *
2430     * @return bool
2431     */
2432    public static function is_initial_loading(): bool {
2433        if ( null !== self::$is_initial_loading_cache ) {
2434            return self::$is_initial_loading_cache;
2435        }
2436        // `has_search_param()` not `parse_url_search_query() !== ''` — an
2437        // explicit `?s=` (empty value) still means "visitor landed on a
2438        // search page" and should fire an unfiltered initial fetch.
2439        if ( static::has_search_param() ) {
2440            self::$is_initial_loading_cache = true;
2441            return true;
2442        }
2443        if ( ! empty( static::parse_url_filters() ) ) {
2444            self::$is_initial_loading_cache = true;
2445            return true;
2446        }
2447        self::$is_initial_loading_cache = null !== static::parse_url_price_range();
2448        return self::$is_initial_loading_cache;
2449    }
2450
2451    /**
2452     * Reset the `is_initial_loading()` memo. Tests only — PHPUnit reuses a
2453     * single process so `$_GET` from an earlier test would pin the value.
2454     * Guarded against accidental production use.
2455     */
2456    public static function reset_initial_loading_cache(): void {
2457        if ( defined( 'ABSPATH' ) && ! defined( 'PHPUNIT_COMPOSER_INSTALL' ) ) {
2458            return;
2459        }
2460        self::$is_initial_loading_cache = null;
2461    }
2462
2463    /**
2464     * Pre-hydration view state for a filter block's wrapper. Centralizes the
2465     * seeded-state read shared by filter-checkbox and filter-date so each
2466     * render.php branches on a single struct rather than re-deriving the
2467     * same flags inline.
2468     *
2469     * @param string $filter_key The filter key (e.g. `category`, `post_type`).
2470     * @return array{has_buckets:bool,is_initial_loading:bool,show_wrapper:bool}
2471     */
2472    public static function pre_hydration_filter_view( string $filter_key ): array {
2473        if ( ! function_exists( 'wp_interactivity_state' ) ) {
2474            return array(
2475                'has_buckets'        => false,
2476                'is_initial_loading' => false,
2477                'show_wrapper'       => false,
2478            );
2479        }
2480        // `aggregations` is seeded as `stdClass` when empty (so JS sees `{}`,
2481        // not `[]`); cast before subscripting so the read works in either shape.
2482        $state              = wp_interactivity_state( 'jetpack-search' );
2483        $aggs               = (array) ( $state['aggregations'] ?? array() );
2484        $has_buckets        = ! empty( $aggs[ $filter_key ]['buckets'] ?? array() );
2485        $is_initial_loading = static::is_initial_loading();
2486        return array(
2487            'has_buckets'        => $has_buckets,
2488            'is_initial_loading' => $is_initial_loading,
2489            'show_wrapper'       => $has_buckets || $is_initial_loading,
2490        );
2491    }
2492
2493    /**
2494     * Emit the `data-wp-context` attribute for a filter block's wrapper. The
2495     * seeded `wrapperHidden` value is what the IA SSR pass evaluates
2496     * `data-wp-bind--hidden="context.wrapperHidden"` against, and what the
2497     * `syncFilterWrapperVisibility` callback updates after hydration.
2498     *
2499     * @param string $filter_key   The filter key.
2500     * @param bool   $show_wrapper Whether the wrapper should be visible on first paint.
2501     */
2502    public static function emit_filter_wrapper_context( string $filter_key, bool $show_wrapper ): void {
2503        if ( ! function_exists( 'wp_interactivity_data_wp_context' ) ) {
2504            return;
2505        }
2506        echo wp_kses_data(
2507            wp_interactivity_data_wp_context(
2508                array(
2509                    'filterKey'     => $filter_key,
2510                    'wrapperHidden' => ! $show_wrapper,
2511                )
2512            )
2513        );
2514    }
2515
2516    /**
2517     * Normalize the shared `displayStyle` attribute to one of the two CSS
2518     * variants. `filter-wc-stock-status` and `filter-wc-rating` deliberately
2519     * don't ship a chip variant and don't call this helper.
2520     *
2521     * @param mixed $value Raw attribute value.
2522     * @return string Either 'checkbox-list' or 'chips'.
2523     */
2524    public static function normalize_display_style( $value ): string {
2525        return 'chips' === $value ? 'chips' : 'checkbox-list';
2526    }
2527
2528    /**
2529     * Seed translated view-bundle strings for the Interactivity API store.
2530     *
2531     * @return array<string, string>
2532     */
2533    protected static function build_initial_strings(): array {
2534        if ( ! function_exists( '__' ) || ! function_exists( '_n' ) ) {
2535            return array(
2536                'searching'               => 'Searching…',
2537                'resultsCountSingle'      => 'Found %d result',
2538                'resultsCountPlural'      => 'Found %d results',
2539                'removeFilter'            => 'Remove %s',
2540                'ratingStarsTop'          => '5 stars',
2541                'ratingStarsAndUpSingle'  => '%d star and up',
2542                'ratingStarsAndUpPlural'  => '%d stars and up',
2543                'priceRangeFromTo'        => '%1$s – %2$s',
2544                'priceRangeFrom'          => '%s+',
2545                'priceRangeUpTo'          => 'Under %s',
2546                'priceLabel'              => 'Price',
2547                'suggestionLabelQuery'    => 'Suggestions',
2548                'suggestionLabelTaxonomy' => 'Popular Filters',
2549                'suggestionLabelPost'     => 'Articles',
2550                'aiErrorMessage'          => 'Sorry, an error occurred while generating an answer.',
2551                'aiErrorCode'             => 'Error code: %s',
2552            );
2553        }
2554        return array(
2555            'searching'               => __( 'Searching…', 'jetpack-search-pkg' ),
2556            /* translators: %d: number of results. */
2557            'resultsCountSingle'      => _n( 'Found %d result', 'Found %d results', 1, 'jetpack-search-pkg' ),
2558            /* translators: %d: number of results. */
2559            'resultsCountPlural'      => _n( 'Found %d result', 'Found %d results', 2, 'jetpack-search-pkg' ),
2560            /* translators: %s: filter label (e.g. "Category: News"). Announced by screen readers when focus lands on a filter pill's remove button. */
2561            'removeFilter'            => __( 'Remove %s', 'jetpack-search-pkg' ),
2562            /* translators: Active-filter chip label for the 5-star row. The 5-star row is "exactly 5 stars" — no "& up" affordance — because there is no higher rating. Mirrors the row's aria-label in filter-wc-rating/render.php. */
2563            'ratingStarsTop'          => __( '5 stars', 'jetpack-search-pkg' ),
2564            /* translators: %d: rating threshold (singular form, i.e. 1). Active-filter chip label for the "1 star and up" threshold row. Mirrors the row's aria-label in filter-wc-rating/render.php. */
2565            'ratingStarsAndUpSingle'  => _n( '%d star and up', '%d stars and up', 1, 'jetpack-search-pkg' ),
2566            /* translators: %d: rating threshold (plural form, i.e. 2-4). Active-filter chip label for the "X stars and up" threshold rows. Mirrors the row's aria-label in filter-wc-rating/render.php. */
2567            'ratingStarsAndUpPlural'  => _n( '%d star and up', '%d stars and up', 2, 'jetpack-search-pkg' ),
2568            /* translators: 1: minimum price (already includes the currency symbol). 2: maximum price (already includes the currency symbol). Renders an active "Price: $10 – $50" filter pill. */
2569            'priceRangeFromTo'        => __( '%1$s – %2$s', 'jetpack-search-pkg' ),
2570            /* translators: %s: minimum price (already includes the currency symbol). Renders an active "Price: $10+" filter pill (no upper bound) — compact "and above" form aligned with mainstream e-commerce filter chips. */
2571            'priceRangeFrom'          => __( '%s+', 'jetpack-search-pkg' ),
2572            /* translators: %s: maximum price (already includes the currency symbol). Renders an active "Price: Under $50" filter pill (no lower bound) — mirrors Amazon/eBay/Walmart's "Under $X" convention. */
2573            'priceRangeUpTo'          => __( 'Under %s', 'jetpack-search-pkg' ),
2574            /* translators: Group label for the price filter pill ("Price: $10 – $50"). Mirrors the price block's default heading; falls back to this when no price block is on the page. */
2575            'priceLabel'              => __( 'Price', 'jetpack-search-pkg' ),
2576            /* translators: Group label for the typed-query suggestions section of the Search Input autocomplete dropdown. */
2577            'suggestionLabelQuery'    => __( 'Suggestions', 'jetpack-search-pkg' ),
2578            /* translators: Group label for the taxonomy (category / tag) section of the Search Input autocomplete dropdown. */
2579            'suggestionLabelTaxonomy' => __( 'Popular Filters', 'jetpack-search-pkg' ),
2580            /* translators: Group label for the post-title section of the Search Input autocomplete dropdown. */
2581            'suggestionLabelPost'     => __( 'Articles', 'jetpack-search-pkg' ),
2582            /* translators: Heading shown on the AI Answer panel when the agent endpoint returns an error. The technical message + HTTP/JSON-RPC code render below this string. */
2583            'aiErrorMessage'          => __( 'Sorry, an error occurred while generating an answer.', 'jetpack-search-pkg' ),
2584            /* translators: %s: numeric error code. Surfaces the HTTP / JSON-RPC code that came back with the AI Answer failure, under the technical message. */
2585            'aiErrorCode'             => __( 'Error code: %s', 'jetpack-search-pkg' ),
2586        );
2587    }
2588
2589    /**
2590     * Rotating loading hints for the "Show more" extended AI answer.
2591     * Mirrors the overlay verbatim so visitors switching surfaces see
2592     * the same copy.
2593     *
2594     * @return array<int, string>
2595     */
2596    protected static function build_ai_extended_loading_hints(): array {
2597        // Strings omit trailing `…` — render.php appends an animated ellipsis,
2598        // so a static one would double up. Overlay does the same.
2599        if ( ! function_exists( '__' ) ) {
2600            return array(
2601                'Searching harder',
2602                'Looking deeper into this',
2603                'Finding a more complete answer',
2604                'Analyzing additional sources',
2605                'Gathering more details',
2606                'Pulling in more context',
2607                'Expanding the search',
2608                'Rolling up my virtual sleeves',
2609                'Digging through the archives',
2610                'Putting on my reading glasses',
2611                'Checking under the digital couch cushions',
2612                'Consulting the oracle',
2613                'Asking a smarter algorithm',
2614                'Brewing a fresh batch of insights',
2615                'Unleashing the full power of search',
2616            );
2617        }
2618        return array(
2619            __( 'Searching harder', 'jetpack-search-pkg' ),
2620            __( 'Looking deeper into this', 'jetpack-search-pkg' ),
2621            __( 'Finding a more complete answer', 'jetpack-search-pkg' ),
2622            __( 'Analyzing additional sources', 'jetpack-search-pkg' ),
2623            __( 'Gathering more details', 'jetpack-search-pkg' ),
2624            __( 'Pulling in more context', 'jetpack-search-pkg' ),
2625            __( 'Expanding the search', 'jetpack-search-pkg' ),
2626            __( 'Rolling up my virtual sleeves', 'jetpack-search-pkg' ),
2627            __( 'Digging through the archives', 'jetpack-search-pkg' ),
2628            __( 'Putting on my reading glasses', 'jetpack-search-pkg' ),
2629            __( 'Checking under the digital couch cushions', 'jetpack-search-pkg' ),
2630            __( 'Consulting the oracle', 'jetpack-search-pkg' ),
2631            __( 'Asking a smarter algorithm', 'jetpack-search-pkg' ),
2632            __( 'Brewing a fresh batch of insights', 'jetpack-search-pkg' ),
2633            __( 'Unleashing the full power of search', 'jetpack-search-pkg' ),
2634        );
2635    }
2636
2637    /**
2638     * Parse the search query from the URL using whichever key
2639     * `get_search_param_name()` returns (`s` on search routes, `q` elsewhere).
2640     * Public so render templates can seed their input from the same source.
2641     *
2642     * @return string
2643     */
2644    public static function parse_url_search_query(): string {
2645        $key = self::get_search_param_name();
2646        // phpcs:ignore WordPress.Security.NonceVerification.Recommended,WordPress.Security.ValidatedSanitizedInput.InputNotSanitized,WordPress.Security.ValidatedSanitizedInput.MissingUnslash -- read-only URL state; coerced to string + sanitize_text_field( wp_unslash( ... ) ) on the next line.
2647        $raw = $_GET[ $key ] ?? '';
2648        if ( ! is_scalar( $raw ) ) {
2649            return '';
2650        }
2651        return trim( sanitize_text_field( wp_unslash( (string) $raw ) ) );
2652    }
2653
2654    /**
2655     * Whether the search-query key is present in `$_GET` (any value).
2656     * Distinguishes `?s=` (blank search) from a URL that omits the key —
2657     * `parse_url_search_query()` collapses both to `''`. Array-shaped
2658     * `?s[]=foo` reads as "not present" to stay in lockstep.
2659     *
2660     * @return bool
2661     */
2662    public static function has_search_param(): bool {
2663        $key = self::get_search_param_name();
2664        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only URL presence check; the value is never read here.
2665        return isset( $_GET[ $key ] ) && is_scalar( $_GET[ $key ] );
2666    }
2667
2668    /**
2669     * Parse the sort order from the URL, defaulting to 'relevance'. Allowed
2670     * values track `Results_Sort::get_all_option_keys()` — on non-Woo sites
2671     * a `?orderby=price_asc` deep link collapses to `relevance` (mirrors
2672     * `store/url-state.js`).
2673     *
2674     * @return string
2675     */
2676    protected static function parse_url_sort(): string {
2677        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only URL state.
2678        $orderby = isset( $_GET['orderby'] ) ? sanitize_key( wp_unslash( $_GET['orderby'] ) ) : '';
2679        $allowed = array_values(
2680            array_filter(
2681                Results_Sort::get_all_option_keys(),
2682                static function ( $key ) {
2683                    return 'relevance' !== $key;
2684                }
2685            )
2686        );
2687        return in_array( $orderby, $allowed, true ) ? $orderby : 'relevance';
2688    }
2689
2690    /**
2691     * Parse the price range from the URL. Mirrors `store/url-state.js`.
2692     * Either bound may be null for a half-open range; non-numeric or
2693     * negative values null out. Returns null entirely on non-Woo sites —
2694     * `min_price`/`max_price` are WC-only and a stray param shouldn't drive
2695     * the API into a `range` clause for a field the index doesn't have.
2696     *
2697     * @return array{min: float|null, max: float|null}|null
2698     */
2699    protected static function parse_url_price_range(): ?array {
2700        if ( ! self::woocommerce_blocks_enabled() ) {
2701            return null;
2702        }
2703        // phpcs:disable WordPress.Security.NonceVerification.Recommended,WordPress.Security.ValidatedSanitizedInput.InputNotSanitized,WordPress.Security.ValidatedSanitizedInput.MissingUnslash -- coerced to float in parse_price_bound().
2704        $min = self::parse_price_bound( $_GET['min_price'] ?? null );
2705        $max = self::parse_price_bound( $_GET['max_price'] ?? null );
2706        // phpcs:enable
2707
2708        if ( null === $min && null === $max ) {
2709            return null;
2710        }
2711        // Inverted bounds → empty ES `range` clause / zero results silently.
2712        // Treat as garbage and bail so the page falls back to unfiltered search.
2713        if ( null !== $min && null !== $max && $min > $max ) {
2714            return null;
2715        }
2716        return array(
2717            'min' => $min,
2718            'max' => $max,
2719        );
2720    }
2721
2722    /**
2723     * Coerce a single price-range URL value into a finite, non-negative float.
2724     *
2725     * @param mixed $raw Raw value pulled from $_GET.
2726     * @return float|null
2727     */
2728    private static function parse_price_bound( $raw ): ?float {
2729        if ( null === $raw || '' === $raw || ! is_scalar( $raw ) ) {
2730            return null;
2731        }
2732        // `is_numeric` keeps PHP in lockstep with JS's `Number()`: rejects
2733        // partially-numeric strings ("1.5.3") that `(float)` would silently
2734        // extract as `1.5` while `Number()` returns `NaN`.
2735        $raw = wp_unslash( $raw );
2736        if ( ! is_numeric( $raw ) ) {
2737            return null;
2738        }
2739        $num = (float) $raw;
2740        if ( ! is_finite( $num ) || $num < 0 ) {
2741            return null;
2742        }
2743        return $num;
2744    }
2745
2746    /**
2747     * Parse `?<filterKey>[]=<value>` URL params into `{ [filterKey]: string[] }`.
2748     * Mirrors the shape `store/url-state.js` writes (see AGENTS.md § URL format).
2749     * No registered-key filtering here — `filterConfigs` aren't available until
2750     * blocks render. The JS layer gates on hydration.
2751     *
2752     * Scalar `?post_type=<slug>` is also accepted as a shortcut for
2753     * `?post_types[]=<slug>` — matches WP/WC's own URL convention. Merged into
2754     * any existing array selections so `?post_type=foo&post_types[]=bar` reads
2755     * as `[foo, bar]`. Singular-form-on-an-array-key keeps its existing
2756     * "ignored noise" behaviour for every other filter.
2757     *
2758     * @return array<string, string[]>
2759     */
2760    protected static function parse_url_filters(): array {
2761        // phpcs:ignore WordPress.Security.NonceVerification.Recommended,WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- read-only URL state; sanitized per-value below.
2762        $raw = wp_unslash( $_GET );
2763        if ( ! is_array( $raw ) ) {
2764            return array();
2765        }
2766
2767        $out = array();
2768        foreach ( $raw as $key => $values ) {
2769            $filter_key = sanitize_key( (string) $key );
2770            if ( '' === $filter_key || in_array( $filter_key, self::RESERVED_QUERY_PARAMS, true ) ) {
2771                continue;
2772            }
2773            if ( 'post_type' === $filter_key ) {
2774                // `is_string` (not `is_scalar`) keeps the gate consistent with
2775                // `parse_url_filter_logic`'s value check — `$_GET` only ever
2776                // carries strings or arrays, and the array case takes the
2777                // `is_array( $values )` branch immediately below.
2778                if ( ! is_string( $values ) ) {
2779                    continue;
2780                }
2781                // `sanitize_key`, not `sanitize_text_field` — post-type slugs are
2782                // always lowercase + `[a-z0-9_-]`; the lowercase pass keeps a
2783                // `?post_type=Product` URL from reaching ES with the wrong case
2784                // and silently returning zero results.
2785                $slug = sanitize_key( $values );
2786                if ( '' === $slug ) {
2787                    continue;
2788                }
2789                $existing          = $out['post_types'] ?? array();
2790                $out['post_types'] = array_values( array_unique( array_merge( $existing, array( $slug ) ) ) );
2791                continue;
2792            }
2793            if ( ! is_array( $values ) ) {
2794                continue;
2795            }
2796            $clean = array_values(
2797                array_filter(
2798                    array_map( 'sanitize_text_field', $values ),
2799                    static function ( $v ) {
2800                        return '' !== $v;
2801                    }
2802                )
2803            );
2804            if ( $clean ) {
2805                $existing           = $out[ $filter_key ] ?? array();
2806                $out[ $filter_key ] = array_values( array_unique( array_merge( $existing, $clean ) ) );
2807            }
2808        }
2809        return $out;
2810    }
2811
2812    /**
2813     * Parse `?query_type_<key>=and` overrides into `{ [filterKey]: 'and' }`.
2814     * Only literal `'and'` is honoured — anything else is dropped so it
2815     * can't round-trip back through `pushStateToUrl`. Mirrors
2816     * `store/url-state.js`.
2817     *
2818     * @param array<string, string[]> $active_filters Result of parse_url_filters().
2819     * @return array<string, string>
2820     */
2821    protected static function parse_url_filter_logic( array $active_filters ): array {
2822        // phpcs:ignore WordPress.Security.NonceVerification.Recommended,WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- read-only URL state; sanitized per-value below.
2823        $raw = wp_unslash( $_GET );
2824        if ( ! is_array( $raw ) ) {
2825            return array();
2826        }
2827
2828        $out = array();
2829        foreach ( $raw as $key => $value ) {
2830            if ( ! is_string( $key ) || 0 !== strpos( $key, 'query_type_' ) ) {
2831                continue;
2832            }
2833            if ( ! is_string( $value ) || 'and' !== $value ) {
2834                continue;
2835            }
2836            $filter_key = sanitize_key( substr( $key, strlen( 'query_type_' ) ) );
2837            if ( '' === $filter_key || in_array( $filter_key, self::RESERVED_QUERY_PARAMS, true ) ) {
2838                continue;
2839            }
2840            if ( empty( $active_filters[ $filter_key ] ) ) {
2841                continue;
2842            }
2843            $out[ $filter_key ] = 'and';
2844        }
2845        return $out;
2846    }
2847}