<?php
/**
 * The Jetpack SEO wp-admin page shell.
 *
 * Registers the `admin.php?page=jetpack-seo` screen via Admin_Menu so it is
 * reachable on self-hosted, Atomic/WoA, and Simple sites alike, loads the
 * `@wordpress/build` (wp-build) dashboard bundle that renders it, and
 * bootstraps the React app's initial state onto the page.
 *
 * @package automattic/jetpack-seo-package
 */

namespace Automattic\Jetpack\SEO;

use Automattic\Jetpack\Admin_UI\Admin_Menu;
use Automattic\Jetpack\WP_Build_Polyfills\WP_Build_Polyfills;

/**
 * Registers the SEO admin menu and loads the wp-build dashboard bundle.
 */
class Admin_Page {

	/**
	 * 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';

	/**
	 * 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 Dashboard_Data::register_rest_reads()
		// and the client readers `_inc/data/get-preloaded.ts` + `_inc/data/use-ensure-tab-data.ts`.
		$data[ Initializer::SCRIPT_DATA_KEY ]['preload'] = array_reduce(
			Dashboard_Data::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[ Initializer::SCRIPT_DATA_KEY ]['google_verify'] = Dashboard_Data::get_google_verify_data();
		$data[ Initializer::SCRIPT_DATA_KEY ]['site']          = Dashboard_Data::get_site_data();

		// Plan-gating signal for below-Premium WordPress.com sites: when gated, the
		// dashboard reduces to a free subset and surfaces the upsell banner. Self-hosted
		// is never gated (see Initializer::is_gated()). The upsell URL is only meaningful
		// when gated, so it's built only then — every ungated and self-hosted admin load
		// otherwise pays for a site-suffix lookup it never uses.
		$is_gated                                       = Initializer::is_gated();
		$data[ Initializer::SCRIPT_DATA_KEY ]['gating'] = array(
			'is_gated'   => $is_gated,
			'upsell_url' => $is_gated ? Initializer::get_upsell_url() : '',
		);

		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'] ) );
	}
}
