<?php
/**
 * Jetpack SEO — the visibility command center for WordPress sites.
 *
 * Registers the `admin.php?page=jetpack-seo` screen via Admin_Menu so it is
 * reachable on self-hosted, Atomic/WoW, and Simple sites alike, and loads the
 * `@wordpress/build` (wp-build) dashboard bundle that renders it.
 *
 * @package automattic/jetpack-seo-package
 */

namespace Automattic\Jetpack\SEO;

use Automattic\Jetpack\Admin_UI\Admin_Menu;
use Automattic\Jetpack\Modules;
use Automattic\Jetpack\Status\Host;
use Automattic\Jetpack\WP_Build_Polyfills\WP_Build_Polyfills;
use Jetpack_SEO_Titles;
use Jetpack_SEO_Utils;
use Jetpack_Sitemap_Librarian;

/**
 * The main Initializer class. Registers the admin menu and loads the wp-build
 * dashboard, bootstrapping the React app's initial state onto the page.
 */
class Initializer {

	/**
	 * Jetpack SEO package version.
	 *
	 * @var string
	 */
	const PACKAGE_VERSION = '0.4.0';

	/**
	 * Filter name that gates the entire Jetpack SEO surface.
	 *
	 * When this filter returns true, the package registers its admin menu and
	 * loads the wp-build dashboard. Default false before release - when the
	 * filter is off the package registers no admin menu and no assets, and
	 * changes nothing about the existing Jetpack UI.
	 *
	 * @var string
	 */
	const FEATURE_FILTER = 'rsm_jetpack_seo';

	/**
	 * URL-facing menu slug (`admin.php?page=jetpack-seo`).
	 */
	const MENU_SLUG = 'jetpack-seo';

	/**
	 * Slug emitted by `@wordpress/build` (`wpPlugin.pages[0]`). wp-build's
	 * auto-generated enqueue callback only fires when `$screen->id` matches
	 * this value, so we alias the screen id to it via `current_screen` without
	 * changing the user-facing URL.
	 */
	const WP_BUILD_SLUG = 'jetpack-seo-dashboard';

	/**
	 * Render function generated by `@wordpress/build` into
	 * `build/pages/jetpack-seo-dashboard/page-wp-admin.php`. Naming convention:
	 * `{wpPlugin.name}_{page-with-underscores}_wp_admin_render_page`.
	 */
	const WP_BUILD_RENDER_FN = 'jetpack_seo_jetpack_seo_dashboard_wp_admin_render_page';

	/**
	 * Key under `window.JetpackScriptData` the React app reads its state from
	 * (`window.JetpackScriptData.seo`). Must match the JS-side reader in
	 * `_inc/data/get-overview.ts`.
	 */
	const SCRIPT_DATA_KEY = 'seo';

	/**
	 * Post-meta keys mirrored from `Jetpack_SEO_Posts` (in plugins/jetpack).
	 * Duplicated here as literals on purpose: that plugin class is NOT reliably
	 * loaded in this package's admin context (the `Jetpack_SEO_Utils`
	 * `class_exists` guard in `get_overview_data()` is there for the same
	 * reason), so referencing its constants would fatal. Content-coverage
	 * counting only needs the key strings, which are stable.
	 */
	const META_DESCRIPTION = 'advanced_seo_description';
	const META_SCHEMA_TYPE = 'jetpack_seo_schema_type';
	const META_TITLE       = 'jetpack_seo_html_title';
	const META_NOINDEX     = 'jetpack_seo_noindex';

	/**
	 * Option recording whether sitemap generation is enabled.
	 *
	 * Read in place of the standalone `sitemaps` module's active state. Module-active
	 * state is filtered against the modules present on disk, so once that module is
	 * removed it would read as inactive even for sites that had it on. A one-time
	 * migration in the Jetpack plugin seeds this option from the site's existing module
	 * state and keeps it in sync while the legacy module still exists. See
	 * `Jetpack::migrate_sitemaps_module_to_seo_option()`.
	 *
	 * @var string
	 */
	const SITEMAP_ENABLED_OPTION = 'jetpack_seo_sitemap_enabled';

	/**
	 * Option recording whether canonical URLs are enabled.
	 *
	 * Read in place of the standalone `canonical-urls` module's active state. Module-active
	 * state is filtered against the modules present on disk, so once that module is
	 * removed it would read as inactive even for sites that had it on. A one-time
	 * migration in the Jetpack plugin seeds this option from the site's existing module
	 * state and keeps it in sync while the legacy module still exists. See
	 * `Jetpack::migrate_canonical_urls_module_to_seo_option()`.
	 *
	 * @var string
	 */
	const CANONICAL_ENABLED_OPTION = 'jetpack_seo_canonical_urls_enabled';

	/**
	 * Option recording whether the Jetpack SEO surface is discoverable on this site.
	 *
	 * Gates whether the SEO admin menu registers on self-hosted sites. Seeded once by the
	 * Jetpack plugin on install/upgrade: fresh installs default to visible, existing
	 * installs default to hidden and opt in via the legacy Traffic page or My Jetpack.
	 * WordPress.com (Simple + Atomic) bypasses this option entirely and is always visible.
	 * Absent until seeded, in which case self-hosted defaults to hidden (the non-disruptive
	 * default). See {@see self::is_seo_surface_visible()}.
	 *
	 * @var string
	 */
	const VISIBILITY_OPTION = 'jetpack_seo_surface_visible';

	/**
	 * Whether the package has been initialized.
	 *
	 * @var bool
	 */
	private static $initialized = false;

	/**
	 * Initialize the package.
	 *
	 * Called from the Jetpack plugin's `late_initialization()` hook.
	 *
	 * @return void
	 */
	public static function init() {
		if ( self::$initialized ) {
			return;
		}
		self::$initialized = true;

		// Gate the entire SEO surface behind the feature flag.
		if ( ! (bool) apply_filters( self::FEATURE_FILTER, false ) ) {
			return;
		}

		// The opt-in endpoint must be reachable even before the surface is visible, so
		// existing self-hosted installs can switch to the new experience from the legacy
		// Traffic page or My Jetpack (JETPACK-1700). Registered ahead of the cohort gate.
		add_action( 'rest_api_init', array( __CLASS__, 'register_optin_route' ) );

		// Expose opt-in availability to other admin surfaces (the legacy Traffic-page
		// banner reads it via `@automattic/jetpack-script-data`). Hooked here — after the
		// feature flag, before the cohort gate — so a still-hidden install gets the signal.
		add_filter( 'jetpack_admin_js_script_data', array( __CLASS__, 'inject_optin_availability' ) );

		// Discoverability cohort gate: the SEO surface is auto-discoverable for fresh
		// installs and all WordPress.com sites; existing self-hosted installs opt in via
		// the legacy Traffic page or My Jetpack (JETPACK-1700). Until it's visible we
		// register nothing else here and let those opt-in surfaces drive discovery.
		if ( ! self::is_seo_surface_visible() ) {
			return;
		}

		// The admin menu and app shell register whenever the surface is visible, even
		// when the `seo-tools` module is inactive, so SEO stays discoverable and can be
		// turned on from within the page itself (JETPACK-1700). When the module is off,
		// the Overview renders only its "enable SEO tools" affordance.
		//
		// Priority 1: load the wp-build bundle (and define its render function)
		// before `add_menu_item()` runs at the default priority and needs it.
		add_action( 'admin_menu', array( __CLASS__, 'maybe_load_wp_build' ), 1 );
		add_action( 'admin_menu', array( __CLASS__, 'add_menu_item' ), 10 );

		// Read-only REST routes the dashboard hydrates its initial state from. Preloaded
		// into the page (see inject_script_data) so a normal load resolves them with no
		// request, and fetched by the app when that preload is missing or stale — so the
		// dashboard recovers its data instead of dead-ending. Registered whenever the
		// surface is visible (independent of the seo-tools module, like the Overview).
		add_action( 'rest_api_init', array( __CLASS__, 'register_rest_reads' ) );

		// The settings surface only comes online once SEO tools are active — there's
		// nothing to configure while the module is off, so we don't register its REST
		// endpoints until then. Expose the core `blog_public` option to the REST settings
		// endpoint so the Settings tab can save search-engine visibility via
		// `/wp/v2/settings` (the Jetpack settings endpoint only accepts Jetpack options).
		// Writes are still capability-gated by the core settings controller.
		if ( self::is_seo_tools_module_active() ) {
			// Front-end JSON-LD schema (Article / FAQ). Self-hooks `wp_head`, so it only
			// emits on front-end requests.
			Schema_Builder::init();
			add_action( 'rest_api_init', array( __CLASS__, 'register_rest_settings' ) );
			// Package-owned route for the site-level Schema settings (see the controller).
			add_action( 'rest_api_init', array( Schema_Settings_Controller::class, 'register_routes' ) );
		}

		/**
		 * Fires after the Jetpack SEO package is initialized.
		 *
		 * @since 0.1.0
		 */
		do_action( 'jetpack_seo_init' );
	}

	/**
	 * Register the admin menu item.
	 *
	 * Uses Admin_Menu so the page is reachable on wp-admin across all site
	 * types. The render callback is wp-build's generated render function when
	 * the bundle is loaded (i.e. on the SEO page itself, after
	 * `maybe_load_wp_build()` ran at priority 1); otherwise it falls back to a
	 * bare mount node so the page never fatals on an unbuilt checkout.
	 *
	 * @return void
	 */
	public static function add_menu_item() {
		$callback = function_exists( self::WP_BUILD_RENDER_FN )
			? self::WP_BUILD_RENDER_FN
			: array( __CLASS__, 'render_fallback' );

		Admin_Menu::add_menu(
			'SEO',
			'SEO',
			'manage_options',
			self::MENU_SLUG,
			$callback,
			2
		);
	}

	/**
	 * On the SEO admin page, load the wp-build bundle, alias the screen id so
	 * wp-build enqueues its assets, and bootstrap the app's initial state.
	 *
	 * Hooked at `admin_menu` priority 1 so polyfills register and the render
	 * function is defined before `add_menu_item()` runs at priority 10.
	 *
	 * @return void
	 */
	public static function maybe_load_wp_build() {
		if ( ! self::is_seo_admin_request() ) {
			return;
		}

		self::load_wp_build();
		add_action( 'current_screen', array( __CLASS__, 'alias_screen_id_for_wp_build' ) );
		add_filter( 'jetpack_admin_js_script_data', array( __CLASS__, 'inject_script_data' ) );
	}

	/**
	 * Load wp-build's generated registration file and register the polyfills
	 * the bundle depends on. No-op on a fresh checkout before `pnpm build`, in
	 * which case `add_menu_item()` falls back to {@see self::render_fallback()}.
	 *
	 * @return void
	 */
	private static function load_wp_build() {
		$build_index = dirname( __DIR__ ) . '/build/build.php';

		if ( ! file_exists( $build_index ) ) {
			return;
		}

		require_once $build_index;

		WP_Build_Polyfills::register(
			'jetpack-seo',
			array_merge( WP_Build_Polyfills::SCRIPT_HANDLES, WP_Build_Polyfills::MODULE_IDS )
		);
	}

	/**
	 * Alias the current screen id to wp-build's expected slug so its
	 * auto-generated enqueue callback fires for our user-facing page.
	 *
	 * @param \WP_Screen|null $screen The current screen object (passed by WP).
	 * @return void
	 */
	public static function alias_screen_id_for_wp_build( $screen ) {
		if ( ! is_object( $screen ) ) {
			return;
		}

		$screen->id = self::WP_BUILD_SLUG;
	}

	/**
	 * Bootstrap the React app's initial state onto `window.JetpackScriptData.seo`.
	 *
	 * Because wp-build pages load as ES modules, `wp_localize_script` can't
	 * attach data to them; the shared `jetpack_admin_js_script_data` filter
	 * (printed by the Script_Data package onto the `jetpack-script-data` handle
	 * the bundle already depends on) is the supported channel. The per-tab state
	 * is provided as an apiFetch *preload* (mirrors Podcast) so the app resolves
	 * it with no request on a normal load yet can re-fetch when the preload is
	 * missing or stale, rather than dead-ending on a one-shot read.
	 *
	 * @param array $data Script data being injected onto the page.
	 * @return array
	 */
	public static function inject_script_data( $data ) {
		if ( ! is_array( $data ) ) {
			$data = array();
		}

		// Preload the dashboard's REST reads into the page so the app resolves them from
		// cache on first paint with no network request — while still being able to
		// re-fetch if that preload is ever missing or stale. This replaces injecting the
		// raw payloads, which the app read synchronously once and couldn't recover from
		// when momentarily absent (the load-error dead-end). See register_rest_reads() and
		// the client readers `_inc/data/get-preloaded.ts` + `_inc/data/use-ensure-tab-data.ts`.
		$data[ self::SCRIPT_DATA_KEY ]['preload'] = array_reduce(
			self::rest_read_paths(),
			'rest_preload_api_request',
			array()
		);

		// Small synchronous reads used outside the per-tab data stores, and not part of
		// the load-error path.
		$data[ self::SCRIPT_DATA_KEY ]['google_verify'] = self::get_google_verify_data();
		$data[ self::SCRIPT_DATA_KEY ]['site']          = self::get_site_data();

		return $data;
	}

	/**
	 * Expose whether this install should be offered the SEO opt-in, onto
	 * `window.JetpackScriptData.seo.optin_available` for other admin surfaces (e.g. the
	 * legacy Traffic-page banner). Only hooked when the feature flag is on, so the field is
	 * simply absent otherwise.
	 *
	 * @param array $data Script data being injected onto the page.
	 * @return array
	 */
	public static function inject_optin_availability( $data ) {
		if ( ! is_array( $data ) ) {
			$data = array();
		}

		$data[ self::SCRIPT_DATA_KEY ]['optin_available'] = self::is_optin_available();
		// Read by the legacy Traffic page to hide its SEO / Sitemaps sections once the
		// site is on the new experience (fresh install / opted-in / WordPress.com), so the
		// two surfaces never show at once. The legacy sections stay for self-hosted installs
		// that haven't opted in.
		$data[ self::SCRIPT_DATA_KEY ]['surface_visible'] = self::is_seo_surface_visible();

		return $data;
	}

	/**
	 * Fallback render used when the wp-build artifact is missing (unbuilt
	 * checkout). Renders a bare wrapper so the page loads without the app.
	 *
	 * @return void
	 */
	public static function render_fallback() {
		echo '<div class="wrap"><h1>SEO</h1></div>';
	}

	/**
	 * Whether the current request targets the SEO admin page.
	 *
	 * @return bool
	 */
	private static function is_seo_admin_request() {
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		if ( ! is_admin() || ! isset( $_GET['page'] ) ) {
			return false;
		}

		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		return self::MENU_SLUG === sanitize_text_field( wp_unslash( $_GET['page'] ) );
	}

	/**
	 * Whether the `seo-tools` Jetpack module is currently active.
	 *
	 * @return bool
	 */
	private static function is_seo_tools_module_active() {
		if ( ! class_exists( 'Automattic\\Jetpack\\Modules' ) ) {
			return false;
		}
		return ( new Modules() )->is_active( 'seo-tools' );
	}

	/**
	 * Whether sitemap generation is enabled.
	 *
	 * Reads the durable {@see self::SITEMAP_ENABLED_OPTION} flag. The default is only
	 * used when the option is absent (for example before the Jetpack plugin's migration
	 * has run on a freshly upgraded site), in which case it falls back to the live
	 * `sitemaps` module state so behavior is unchanged in that gap.
	 *
	 * @param Modules $modules Modules instance to read live module state from.
	 * @return bool
	 */
	private static function is_sitemap_enabled( Modules $modules ) {
		$enabled = get_option( self::SITEMAP_ENABLED_OPTION, null );

		// Only fall back to the live module state when the durable option is absent.
		// Passing it as get_option()'s default would evaluate it on every call, since
		// PHP resolves function arguments eagerly even when the option exists.
		if ( null === $enabled ) {
			$enabled = $modules->is_active( 'sitemaps' );
		}

		return (bool) $enabled;
	}

	/**
	 * The public URL of the generated XML sitemap, or an empty string when none
	 * is currently reachable.
	 *
	 * A sitemap is only reachable when generation is enabled, the site is public
	 * (Jetpack does not load the Sitemaps module on sites that discourage search
	 * engines), and the master sitemap has actually been generated — the Jetpack
	 * plugin builds it via cron 1–15 minutes after activation, so the URL 404s
	 * until then. Callers treat an empty string as "not yet reachable" and skip
	 * linking to it.
	 *
	 * {@see Jetpack_Sitemap_Librarian} and jetpack_sitemap_uri() live in the
	 * Jetpack plugin's Sitemaps module (loaded only for an active module on a
	 * public site), so both are guarded; in the package-only context they are
	 * absent and the sitemap is reported as not reachable.
	 *
	 * @param bool $sitemap_active Whether sitemap generation is enabled.
	 * @return string The sitemap URL, or '' when not reachable.
	 */
	private static function get_reachable_sitemap_url( $sitemap_active ) {
		// Jetpack only serves sitemaps when generation is on and the site is public.
		if ( ! $sitemap_active || (int) get_option( 'blog_public', 1 ) !== 1 ) {
			return '';
		}

		// The Sitemaps module (the librarian class, the `JP_MASTER_SITEMAP_TYPE`
		// constant, and the `jp_sitemap_filename()` / `jetpack_sitemap_uri()`
		// helpers) all live together in plugins/jetpack and load as a unit, so this
		// single guard covers every symbol used below.
		if (
			! class_exists( 'Jetpack_Sitemap_Librarian' )
			|| ! defined( 'JP_MASTER_SITEMAP_TYPE' )
			|| ! function_exists( 'jp_sitemap_filename' )
			|| ! function_exists( 'jetpack_sitemap_uri' )
		) {
			return '';
		}

		// The master sitemap is stored as a post once the cron generation run
		// completes; until then there is nothing to link to.
		// `jp_sitemap_filename( JP_MASTER_SITEMAP_TYPE )` is the master file name
		// ('sitemap.xml'); inlined so this stays one (untestable-in-package) line.
		// @phan-suppress-next-line PhanUndeclaredFunction,PhanUndeclaredClassMethod -- guarded above; symbols live in plugins/jetpack.
		$master = ( new Jetpack_Sitemap_Librarian() )->read_sitemap_data( jp_sitemap_filename( JP_MASTER_SITEMAP_TYPE ), JP_MASTER_SITEMAP_TYPE );
		if ( null === $master ) {
			return '';
		}

		// esc_url_raw (not esc_url): the value is transported via script data and
		// rendered by React, so it must not be HTML-entity-encoded (e.g. the
		// plain-permalink `?jetpack-sitemap=` form keeps its raw `&`).
		// @phan-suppress-next-line PhanUndeclaredFunction -- jp_sitemap_filename()/jetpack_sitemap_uri() live in plugins/jetpack, guarded by function_exists.
		return esc_url_raw( (string) jetpack_sitemap_uri( jp_sitemap_filename( JP_MASTER_SITEMAP_TYPE ) ) );
	}

	/**
	 * Whether canonical URLs are enabled.
	 *
	 * Reads the durable {@see self::CANONICAL_ENABLED_OPTION} flag. The default is only
	 * used when the option is absent (for example before the Jetpack plugin's migration
	 * has run on a freshly upgraded site), in which case it falls back to the live
	 * `canonical-urls` module state so behavior is unchanged in that gap.
	 *
	 * @param Modules $modules Modules instance to read live module state from.
	 * @return bool
	 */
	private static function is_canonical_enabled( Modules $modules ) {
		$enabled = get_option( self::CANONICAL_ENABLED_OPTION, null );

		// Only fall back to the live module state when the durable option is absent.
		// Passing it as get_option()'s default would evaluate it on every call, since
		// PHP resolves function arguments eagerly even when the option exists.
		if ( null === $enabled ) {
			$enabled = $modules->is_active( 'canonical-urls' );
		}

		return (bool) $enabled;
	}

	/**
	 * Whether the Jetpack SEO surface should be discoverable (admin menu registered).
	 *
	 * WordPress.com sites (Simple + Atomic) are always discoverable — how SEO presents
	 * there is a Dotcom decision, independent of the self-hosted rollout. On self-hosted
	 * sites the durable {@see self::VISIBILITY_OPTION} cohort flag decides: fresh installs
	 * are seeded visible, existing installs stay hidden until they opt in. Defaults to
	 * hidden when the option is absent (e.g. before the plugin's seed has run), so an
	 * existing site is never surprised by the new surface before its cohort is recorded.
	 *
	 * @return bool
	 */
	public static function is_seo_surface_visible() {
		if ( class_exists( 'Automattic\\Jetpack\\Status\\Host' ) && ( new Host() )->is_wpcom_platform() ) {
			return true;
		}

		return (bool) get_option( self::VISIBILITY_OPTION, false );
	}

	/**
	 * Whether to offer an existing install the chance to opt into the new SEO experience.
	 *
	 * The single source of truth for the opt-in surfaces (legacy Traffic-page banner, My
	 * Jetpack card). True only when the SEO product is available (the {@see self::FEATURE_FILTER}
	 * flag is on) and the surface isn't visible yet — and since {@see self::is_seo_surface_visible()}
	 * already returns true for WordPress.com and for self-hosted installs that have opted in,
	 * "not visible" cleanly means "a self-hosted install that hasn't opted in".
	 *
	 * @return bool
	 */
	public static function is_optin_available() {
		return (bool) apply_filters( self::FEATURE_FILTER, false ) && ! self::is_seo_surface_visible();
	}

	/**
	 * Build the aggregated Overview state the dashboard renders.
	 *
	 * @return array
	 */
	public static function get_overview_data() {
		$modules = new Modules();
		// @phan-suppress-next-line PhanUndeclaredClassMethod -- Jetpack_SEO_Utils lives in plugins/jetpack and is guarded by class_exists.
		$seo_enabled = class_exists( 'Jetpack_SEO_Utils' ) && Jetpack_SEO_Utils::is_enabled_jetpack_seo();

		$codes = get_option( 'verification_services_codes', array() );
		if ( ! is_array( $codes ) ) {
			$codes = array();
		}

		return array(
			'site_visibility'   => array(
				'search_engines_visible' => (int) get_option( 'blog_public', 1 ) === 1,
				// Read the durable SEO option (seeded/synced from the `sitemaps` module
				// by the Jetpack plugin) so the state survives the module's removal. The
				// reachable sitemap URL + "View" link live on the Settings tab.
				'sitemap_active'         => self::is_sitemap_enabled( $modules ),
				'seo_tools_active'       => $modules->is_active( 'seo-tools' ),
			),
			// Per-service booleans (a code is set or not) for the Overview's
			// Site verification card.
			'site_verification' => array(
				'google'    => ! empty( $codes['google'] ),
				'bing'      => ! empty( $codes['bing'] ),
				'pinterest' => ! empty( $codes['pinterest'] ),
				'yandex'    => ! empty( $codes['yandex'] ),
				'facebook'  => ! empty( $codes['facebook'] ),
			),
			'content_coverage'  => self::get_content_coverage(),
			'plan'              => array(
				'seo_enabled_for_site' => $seo_enabled,
			),
		);
	}

	/**
	 * Factual content-coverage counts for the Overview card: how many published
	 * posts/pages have each SEO field set. State, not a score — the card shows
	 * proportions + raw counts and lets the admin decide what matters.
	 *
	 * @return array{total:int,with_schema:int,with_title:int,with_description:int,with_search_visible:int}
	 */
	private static function get_content_coverage() {
		$post_types = array( 'post', 'page' );

		$total = 0;
		foreach ( $post_types as $post_type ) {
			$counts = wp_count_posts( $post_type );
			$total += isset( $counts->publish ) ? (int) $counts->publish : 0;
		}

		// Search-engine visibility is the inverse of the per-post noindex meta: a
		// post is visible unless it's explicitly set to noindex (stored as '1'), so
		// most posts (no meta row) count as visible.
		$noindexed = self::count_published_with_meta( $post_types, self::META_NOINDEX, '1' );

		return array(
			'total'               => $total,
			'with_schema'         => self::count_published_with_meta( $post_types, self::META_SCHEMA_TYPE ),
			'with_title'          => self::count_published_with_meta( $post_types, self::META_TITLE ),
			'with_description'    => self::count_published_with_meta( $post_types, self::META_DESCRIPTION ),
			'with_search_visible' => max( 0, $total - $noindexed ),
		);
	}

	/**
	 * Count published posts/pages whose meta is set. With no `$value`, counts a
	 * non-empty string meta; with a `$value`, counts an exact match.
	 *
	 * @param string[]    $post_types Post types to count across.
	 * @param string      $meta_key   Meta key to test.
	 * @param string|null $value      Exact value to match, or null for "non-empty".
	 * @return int
	 */
	private static function count_published_with_meta( $post_types, $meta_key, $value = null ) {
		$clause = null === $value
			? array(
				'key'     => $meta_key,
				'value'   => '',
				'compare' => '!=',
			)
			: array(
				'key'   => $meta_key,
				'value' => $value,
			);

		$query = new \WP_Query(
			array(
				'post_type'              => $post_types,
				'post_status'            => 'publish',
				'posts_per_page'         => 1,
				'fields'                 => 'ids',
				'update_post_meta_cache' => false,
				'update_post_term_cache' => false,
				// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query -- Overview snapshot; one count query per metric on the SEO page only.
				'meta_query'             => array( $clause ),
			)
		);

		return (int) $query->found_posts;
	}

	/**
	 * Site identity used to render the homepage search/social previews on the
	 * Settings tab: title, URL, and representative images. The front-page
	 * description that completes the preview is read from the Settings form
	 * (it's editable there), not bootstrapped here.
	 *
	 * @return array
	 */
	public static function get_site_data() {
		$icon_url = (string) get_site_icon_url();

		$logo_id  = (int) get_theme_mod( 'custom_logo' );
		$logo_url = $logo_id ? (string) wp_get_attachment_image_url( $logo_id, 'full' ) : '';

		return array(
			'title' => (string) get_bloginfo( 'name' ),
			'url'   => (string) home_url(),
			'icon'  => $icon_url,
			'image' => $logo_url ? $logo_url : $icon_url,
		);
	}

	/**
	 * Expose the core `blog_public` option to the REST settings endpoint.
	 *
	 * Search-engine visibility is a WordPress core option, not a Jetpack one,
	 * so the Settings tab saves it through `/wp/v2/settings` — which only
	 * round-trips settings registered with `show_in_rest`. The core settings
	 * controller enforces the `manage_options` capability on writes.
	 *
	 * @return void
	 */
	public static function register_rest_settings() {
		register_setting(
			'reading',
			'blog_public',
			array(
				'show_in_rest' => true,
				'type'         => 'integer',
				'default'      => 1,
			)
		);
	}

	/**
	 * Register the opt-in REST route that switches an existing self-hosted install over to
	 * the new SEO experience.
	 *
	 * Lives on the `jetpack/v4` namespace and is registered ahead of the cohort gate, so a
	 * site whose SEO surface is still hidden can reach it from the legacy Traffic page or
	 * My Jetpack. See {@see self::handle_optin()}.
	 *
	 * @return void
	 */
	public static function register_optin_route() {
		register_rest_route(
			'jetpack/v4',
			'/seo/opt-in',
			array(
				'methods'             => \WP_REST_Server::CREATABLE,
				'callback'            => array( __CLASS__, 'handle_optin' ),
				'permission_callback' => function () {
					return current_user_can( 'manage_options' );
				},
			)
		);
	}

	/**
	 * Opt an existing install into the new SEO experience: mark the surface visible and
	 * activate the `seo-tools` module, then hand back the dashboard URL to redirect to.
	 *
	 * Idempotent — re-opting-in is harmless. `Modules::activate()` is called with
	 * `$exit = false, $redirect = false`; the defaults would `exit()` and send a 302,
	 * which break a REST response.
	 *
	 * @return \WP_REST_Response
	 */
	public static function handle_optin() {
		update_option( self::VISIBILITY_OPTION, true );

		if ( class_exists( 'Automattic\\Jetpack\\Modules' ) ) {
			( new Modules() )->activate( 'seo-tools', false, false );
		}

		return rest_ensure_response(
			array(
				'success'  => true,
				'redirect' => admin_url( 'admin.php?page=' . self::MENU_SLUG ),
			)
		);
	}

	/**
	 * Map of read-only dashboard routes: tab slug => data-builder callable. The
	 * single source of truth for both the registered routes and the paths
	 * preloaded onto the page, so the two can't drift.
	 *
	 * @return array<string, callable>
	 */
	private static function rest_reads() {
		return array(
			'overview' => array( __CLASS__, 'get_overview_data' ),
			'settings' => array( __CLASS__, 'get_settings_data' ),
			'ai'       => array( __CLASS__, 'get_ai_data' ),
		);
	}

	/**
	 * REST paths the dashboard reads its initial state from, preloaded into the
	 * page (see {@see self::inject_script_data()}) and fetched by the app.
	 *
	 * @return string[]
	 */
	private static function rest_read_paths() {
		return array_map(
			static function ( $slug ) {
				return '/jetpack/v4/seo/' . $slug;
			},
			array_keys( self::rest_reads() )
		);
	}

	/**
	 * Register the read-only REST routes the dashboard hydrates from — one per
	 * data-backed tab, each returning the same builder payload previously injected
	 * synchronously onto the page. Read-only and gated to the page's own
	 * `manage_options`; writes still go through their existing endpoints.
	 *
	 * @return void
	 */
	public static function register_rest_reads() {
		foreach ( self::rest_reads() as $slug => $builder ) {
			register_rest_route(
				'jetpack/v4',
				'/seo/' . $slug,
				array(
					'methods'             => \WP_REST_Server::READABLE,
					'callback'            => static function () use ( $builder ) {
						return rest_ensure_response( call_user_func( $builder ) );
					},
					'permission_callback' => array( __CLASS__, 'reads_permission_check' ),
				)
			);
		}
	}

	/**
	 * Capability gate for the dashboard's read routes — the same `manage_options`
	 * the SEO admin page itself requires.
	 *
	 * @return bool
	 */
	public static function reads_permission_check() {
		return current_user_can( 'manage_options' );
	}

	/**
	 * Build the editable Settings state the Settings tab hydrates from.
	 *
	 * Read-only bootstrap only. Most writes go through the existing
	 * `/jetpack/v4/settings` REST endpoint, which already validates and
	 * sanitizes those flat fields. Nested Schema writes use the package's
	 * schema-settings route; bootstrapping them here keeps the Settings UI
	 * hydrated without a second request.
	 *
	 * @return array
	 */
	public static function get_settings_data() {
		$modules = new Modules();

		// @phan-suppress-next-line PhanUndeclaredClassMethod -- Jetpack_SEO_Titles lives in plugins/jetpack and is guarded by class_exists.
		$title_formats = class_exists( 'Jetpack_SEO_Titles' ) ? Jetpack_SEO_Titles::get_custom_title_formats() : array();
		// @phan-suppress-next-line PhanUndeclaredClassMethod -- Jetpack_SEO_Utils lives in plugins/jetpack and is guarded by class_exists.
		$front_page_desc = class_exists( 'Jetpack_SEO_Utils' ) ? Jetpack_SEO_Utils::get_front_page_meta_description() : '';

		$codes = get_option( 'verification_services_codes', array() );
		if ( ! is_array( $codes ) ) {
			$codes = array();
		}

		$sitemap_active = self::is_sitemap_enabled( $modules );

		return array(
			'search_engines_visible' => (int) get_option( 'blog_public', 1 ) === 1,
			// Read the durable SEO option (seeded/synced from the `sitemaps` module
			// by the Jetpack plugin) so the state survives the module's removal.
			'sitemap_active'         => $sitemap_active,
			// Empty until the sitemap is genuinely reachable, so the Settings tab can
			// link to it only once it won't 404 (it's built by cron after activation).
			'sitemap_url'            => self::get_reachable_sitemap_url( $sitemap_active ),
			// Read the durable SEO option (seeded/synced from the `canonical-urls` module
			// by the Jetpack plugin) so the state survives the module's removal.
			'canonical_active'       => self::is_canonical_enabled( $modules ),
			// Cast to object so an empty format set serializes as `{}`, not `[]`.
			'title_formats'          => (object) $title_formats,
			'front_page_description' => (string) $front_page_desc,
			'verification'           => array(
				'google'    => isset( $codes['google'] ) ? (string) $codes['google'] : '',
				'bing'      => isset( $codes['bing'] ) ? (string) $codes['bing'] : '',
				'pinterest' => isset( $codes['pinterest'] ) ? (string) $codes['pinterest'] : '',
				'yandex'    => isset( $codes['yandex'] ) ? (string) $codes['yandex'] : '',
				'facebook'  => isset( $codes['facebook'] ) ? (string) $codes['facebook'] : '',
			),
			'schema'                 => Schema_Settings::get_editable(),
		);
	}

	/**
	 * Build the Google site-verification state for the Settings tab.
	 *
	 * The Settings verification card lets a connected user verify with Google via a
	 * WordPress.com keyring OAuth popup (in addition to pasting a meta-tag code). This
	 * bootstraps the keyring connect URL and whether the current user is connected —
	 * the live verified status is fetched client-side from `/jetpack/v4/verify-site/google`
	 * (a wpcom round-trip we don't want to make on every page load).
	 *
	 * Both `Keyring_Helper` (Publicize package) and the connection `Manager` are provided
	 * by the host Jetpack plugin, so they're guarded with `class_exists` like the
	 * `Jetpack_SEO_*` helpers. On a disconnected self-hosted site `is_connected` is false
	 * and the UI falls back to manual code entry only.
	 *
	 * @return array
	 */
	public static function get_google_verify_data() {
		$connect_url = '';
		if ( class_exists( 'Automattic\\Jetpack\\Publicize\\Keyring_Helper' ) ) {
			// @phan-suppress-next-line PhanUndeclaredClassMethod -- guarded; Publicize package is provided by the host plugin.
			$connect_url = (string) \Automattic\Jetpack\Publicize\Keyring_Helper::connect_url( 'google_site_verification', 'other' );
		}

		$is_connected = false;
		if ( class_exists( 'Automattic\\Jetpack\\Connection\\Manager' ) ) {
			// @phan-suppress-next-line PhanUndeclaredClassMethod -- guarded; Connection package is provided by the host plugin.
			$is_connected = ( new \Automattic\Jetpack\Connection\Manager() )->is_user_connected();
		}

		return array(
			'connect_url'  => $connect_url,
			'is_connected' => (bool) $is_connected,
		);
	}

	/**
	 * Build the AI tab's initial state.
	 *
	 * The AI SEO Enhancer auto-generates SEO titles/descriptions/alt-text in the
	 * editor (the generation itself is wpcom/AI-Assistant side); this exposes only
	 * its persisted on/off toggle and whether it's available. Availability mirrors
	 * the legacy Traffic page: the `ai_seo_enhancer_enabled` feature filter must be
	 * on (it still depends on AI being available) AND the site's plan must support
	 * the `ai-seo-enhancer` feature. The toggle writes through the existing
	 * `/jetpack/v4/settings` endpoint (`ai_seo_enhancer_enabled`).
	 *
	 * @return array
	 */
	public static function get_ai_data() {
		$filter_on = (bool) apply_filters( 'ai_seo_enhancer_enabled', true );

		// Current_Plan is provided by the host Jetpack plugin, not a package
		// dependency — guard like the Jetpack_SEO_* helpers above.
		$plan_supports = class_exists( 'Automattic\\Jetpack\\Current_Plan' )
			// @phan-suppress-next-line PhanUndeclaredClassMethod -- guarded by class_exists; host plugin provides the class.
			&& \Automattic\Jetpack\Current_Plan::supports( 'ai-seo-enhancer' );

		return array(
			'enhancer' => array(
				'available' => $filter_on && $plan_supports,
				'enabled'   => (bool) get_option( 'ai_seo_enhancer_enabled', false ),
			),
		);
	}
}
