<?php
/**
 * Page: jetpack-premium-analytics (wp-admin integrated)
 * Auto-generated by build process.
 * Do not edit this file manually.
 *
 * This version integrates with the standard WordPress admin interface,
 * keeping the wp-admin sidebar and scripts/styles intact.
 *
 * @package jpa
 */

// Global storage for jetpack-premium-analytics routes and menu items
global $jpa_jetpack_premium_analytics_wp_admin_routes, $jpa_jetpack_premium_analytics_wp_admin_menu_items;
$jpa_jetpack_premium_analytics_wp_admin_routes     = array();
$jpa_jetpack_premium_analytics_wp_admin_menu_items = array();

/**
 * Register a route for the jetpack-premium-analytics-wp-admin page.
 *
 * @param string      $path           Route path (e.g., '/types/$type/edit/$id').
 * @param string|null $content_module Script module ID for content (stage/inspector).
 * @param string|null $route_module   Script module ID for route lifecycle hooks.
 */
function jpa_register_jetpack_premium_analytics_wp_admin_route( $path, $content_module = null, $route_module = null ) {
	global $jpa_jetpack_premium_analytics_wp_admin_routes;

	$route = array( 'path' => $path );
	if ( ! empty( $content_module ) ) {
		$route['content_module'] = $content_module;
	}
	if ( ! empty( $route_module ) ) {
		$route['route_module'] = $route_module;
	}

	$jpa_jetpack_premium_analytics_wp_admin_routes[] = $route;
}

/**
 * Register a menu item for the jetpack-premium-analytics-wp-admin page.
 * Note: Menu items are registered but not displayed in single-page mode.
 *
 * @param string $id        Menu item ID.
 * @param string $label     Display label.
 * @param string $to        Route path to navigate to.
 * @param string $parent_id Optional. Parent menu item ID.
 */
function jpa_register_jetpack_premium_analytics_wp_admin_menu_item( $id, $label, $to, $parent_id = '' ) {
	global $jpa_jetpack_premium_analytics_wp_admin_menu_items;

	$menu_item = array(
		'id'    => $id,
		'label' => $label,
		'to'    => $to,
	);

	if ( ! empty( $parent_id ) ) {
		$menu_item['parent'] = $parent_id;
	}

	$jpa_jetpack_premium_analytics_wp_admin_menu_items[] = $menu_item;
}

/**
 * Get all registered routes for the jetpack-premium-analytics-wp-admin page.
 *
 * @return array Array of route objects.
 */
function jpa_get_jetpack_premium_analytics_wp_admin_routes() {
	global $jpa_jetpack_premium_analytics_wp_admin_routes;
	return $jpa_jetpack_premium_analytics_wp_admin_routes ?? array();
}

/**
 * Get all registered menu items for the jetpack-premium-analytics-wp-admin page.
 *
 * @return array Array of menu item objects.
 */
function jpa_get_jetpack_premium_analytics_wp_admin_menu_items() {
	global $jpa_jetpack_premium_analytics_wp_admin_menu_items;
	return $jpa_jetpack_premium_analytics_wp_admin_menu_items ?? array();
}

/**
 * Preload REST API data for the jetpack-premium-analytics-wp-admin page.
 * Automatically called during page rendering.
 */
function jpa_jetpack_premium_analytics_wp_admin_preload_data() {
	// Define paths to preload - same for all pages
	// This must exactly match the _fields list in packages/core-data/src/entities.js,
	// same fields in the same order, or the preload is never consumed.
	$preload_paths = array(
		'/?_fields=description,gmt_offset,home,image_max_bit_depth,image_sizes,image_size_threshold,image_strip_meta,name,site_icon,site_icon_url,site_logo,timezone_string,url,page_for_posts,page_on_front,show_on_front',
		array( '/wp/v2/settings', 'OPTIONS' ),
	);

	// Use rest_preload_api_request to gather the preloaded data
	$preload_data = array_reduce(
		$preload_paths,
		'rest_preload_api_request',
		array()
	);

	// Register the preloading middleware with wp-api-fetch
	wp_add_inline_script(
		'wp-api-fetch',
		sprintf(
			'wp.apiFetch.use( wp.apiFetch.createPreloadingMiddleware( %s ) );',
			wp_json_encode( $preload_data )
		),
		'after'
	);
}

/**
 * Enqueue scripts and styles for the jetpack-premium-analytics-wp-admin page.
 * Hooked to admin_enqueue_scripts.
 *
 * @param string $hook_suffix The current admin page.
 */
function jpa_jetpack_premium_analytics_wp_admin_enqueue_scripts( $hook_suffix ) {
	// Check all possible ways this page can be accessed:
	// 1. Menu page via admin.php?page=jetpack-premium-analytics-wp-admin (plugin)
	// 2. Direct file via jetpack-premium-analytics.php (Core) - screen ID will be 'jetpack-premium-analytics'
	$current_screen = get_current_screen();
	$is_our_page = (
		( isset( $_GET['page'] ) && 'jetpack-premium-analytics-wp-admin' === $_GET['page'] ) || // phpcs:ignore WordPress.Security.NonceVerification.Recommended
		( $current_screen && 'jetpack-premium-analytics' === $current_screen->id )
	);

	if ( ! $is_our_page ) {
		return;
	}

	// Load build constants
	$build_constants = require __DIR__ . '/../../constants.php';

	/**
	 * Fires when the jetpack-premium-analytics admin page is initialized so extensions can register routes and menu items.
	 */
	do_action( 'jetpack-premium-analytics-wp-admin_init' );

	// Preload REST API data
	jpa_jetpack_premium_analytics_wp_admin_preload_data();

	// Get all registered routes
	$routes = jpa_get_jetpack_premium_analytics_wp_admin_routes();

	// Get boot module asset file for dependencies
	$asset_file = __DIR__ . '/../../modules/boot/index.min.asset.php';
	if ( file_exists( $asset_file ) ) {
		$asset = require $asset_file;

		// This script serves two purposes:
		// 1. It ensures all the globals that are made available to the modules are loaded.
		// 2. It initializes the boot module as an inline script.
		wp_register_script( 'jetpack-premium-analytics-wp-admin-prerequisites', '', $asset['dependencies'], $asset['version'], true );

		$init_modules = ["@jetpack-premium-analytics/init"];

		/*
		 * Add inline script to initialize the app using initSinglePage (no menuItems).
		 * The dynamic import is deferred until DOMContentLoaded so that all classic
		 * script dependencies of @wordpress/boot (wp-private-apis, wp-components,
		 * wp-theme, etc.) have finished parsing and executing before the boot module
		 * evaluates. Otherwise, a modulepreloaded @wordpress/boot can win the race
		 * against the classic-script-printing pass on fast CDN-fronted hosts in
		 * Chrome, evaluating before wp.theme.privateApis is defined and throwing
		 * "Cannot unlock an undefined object". See <https://core.trac.wordpress.org/ticket/65103>.
		 */
		$init_js_function = <<<'JS'
		( mountId, routes, initModules ) => {
			const run = async () => {
				const mod = await import( "@wordpress/boot" );
				/*
				 * Run the init modules here instead of delegating to
				 * initSinglePage(): WordPress cores that bundle an older
				 * @wordpress/boot (initModules support postdates WP 7.0's copy,
				 * and the import map resolves @wordpress/boot to core's bundle
				 * when core provides one) silently ignore the option, so init
				 * modules would never execute. Running them before
				 * initSinglePage() gives identical behavior on every core.
				 */
				for ( const id of initModules ?? [] ) {
					try {
						const initModule = await import( id );
						if ( typeof initModule.init === "function" ) {
							await initModule.init();
						}
					} catch ( error ) {
						console.warn( "Failed to run boot init module:", id, error );
					}
				}
				mod.initSinglePage( { mountId, routes } );
			};
			if ( document.readyState === "loading" ) {
				document.addEventListener( "DOMContentLoaded", run );
			} else {
				run();
			}
		}
JS;
		wp_add_inline_script(
			'jetpack-premium-analytics-wp-admin-prerequisites',
			sprintf(
				'( %s )( %s, %s, %s );',
				$init_js_function,
				wp_json_encode( 'jetpack-premium-analytics-wp-admin-app', JSON_HEX_TAG | JSON_UNESCAPED_SLASHES ),
				wp_json_encode( $routes, JSON_HEX_TAG | JSON_UNESCAPED_SLASHES ),
				wp_json_encode( $init_modules, JSON_HEX_TAG | JSON_UNESCAPED_SLASHES )
			)
		);

		// Register prerequisites style by filtering script dependencies to find registered styles
		$style_dependencies = array_filter(
			$asset['dependencies'],
			function ( $handle ) {
				return wp_style_is( $handle, 'registered' );
			}
		);
		wp_register_style( 'jetpack-premium-analytics-wp-admin-prerequisites', false, $style_dependencies, $asset['version'] );

		// Build dependencies for jetpack-premium-analytics-wp-admin module
		$boot_dependencies = array(
			array(
				'import' => 'static',
				'id'     => '@wordpress/boot',
			),
		);

		// Add init modules as static dependencies
			$boot_dependencies[] = array( 'import' => 'static', 'id' => '@jetpack-premium-analytics/init' );

		// Add all registered routes as dependencies
		foreach ( $routes as $route ) {
			if ( isset( $route['route_module'] ) ) {
				$boot_dependencies[] = array(
					'import' => 'static',
					'id'     => $route['route_module'],
				);
			}
			if ( isset( $route['content_module'] ) ) {
				$boot_dependencies[] = array(
					'import' => 'dynamic',
					'id'     => $route['content_module'],
				);
			}
		}

		/**
		 * Filters the boot script-module dependencies for the
		 * jetpack-premium-analytics-wp-admin page.
		 *
		 * Surfaces extending this page can append entries to the boot
		 * dependency list. Each entry is an array with 'import' (string
		 * 'static' or 'dynamic') and 'id' (script-module handle) keys.
		 *
		 * @param array $boot_dependencies Boot dependencies for the page.
		 */
		$boot_dependencies = apply_filters(
			'jetpack-premium-analytics-wp-admin_boot_dependencies',
			$boot_dependencies
		);

		// Dummy script module to ensure dependencies are loaded
		wp_register_script_module(
			'jetpack-premium-analytics-wp-admin',
			$build_constants['build_url'] . 'pages/jetpack-premium-analytics/loader.js',
			$boot_dependencies
		);

		// Enqueue the boot scripts and styles
		wp_enqueue_script( 'jetpack-premium-analytics-wp-admin-prerequisites' );
		wp_enqueue_script_module( 'jetpack-premium-analytics-wp-admin' );
		wp_enqueue_style( 'jetpack-premium-analytics-wp-admin-prerequisites' );
	}
}

/**
 * Render the jetpack-premium-analytics-wp-admin page.
 * Call this function from add_menu_page or add_submenu_page.
 * This renders within the normal WordPress admin interface.
 */
function jpa_jetpack_premium_analytics_wp_admin_render_page() {
	?>
	<style>
		/* Critical styles to prevent layout shifts - inlined for immediate application */

		#wpwrap {
			overflow-y: auto;
		}
		body {
			background: #fff;
		}

		/* Reset wp-admin padding */
		#wpcontent {
			padding-inline-start: 0;
		}
		#wpbody-content {
			padding-bottom: 0;
		}

		/* Hide legacy admin elements */
		#wpbody-content > div:not(.boot-layout-container):not(#screen-meta) {
			display: none;
		}
		#wpfooter {
			display: none;
		}

		/* Accessibility regions */
		.a11y-speak-region {
			inset-inline-start: -1px;
			top: -1px;
		}

		/* Admin menu indicators */
		ul#adminmenu a.wp-has-current-submenu::after,
		ul#adminmenu > li.current > a.current::after {
			border-inline-end-color: #fff;
		}

		/* Media frame fix */
		.media-frame select.attachment-filters:last-of-type {
			width: auto;
			max-width: 100%;
		}

		/* Responsive overflow fix for #wpwrap */
		@media (min-width: 782px) {
			#wpwrap {
				overflow-y: initial;
			}
		}
	</style>
	<div id="jetpack-premium-analytics-wp-admin-app" class="boot-layout-container"></div>
	<?php
}

// Hook the enqueue function to admin_enqueue_scripts
add_action( 'admin_enqueue_scripts', 'jpa_jetpack_premium_analytics_wp_admin_enqueue_scripts' );

