<?php
/**
 * Admin bootstrap — full-screen app shell.
 *
 * @package JOCBM
 */

namespace JOCBM\Admin;

use JOCBM\Services\CssSanitizer;

defined( 'ABSPATH' ) || exit;

/**
 * Class Admin
 */
final class Admin {

	/**
	 * Hook admin menus and assets.
	 */
	public function register(): void {
		add_action( 'admin_menu', array( $this, 'register_menu' ) );
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_assets' ) );
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_fullscreen_chrome' ), 5 );
		add_filter( 'admin_body_class', array( $this, 'body_class' ) );
		add_action( 'admin_init', array( $this, 'maybe_activation_redirect' ) );
	}

	/**
	 * Register top-level menu.
	 */
	public function register_menu(): void {
		add_menu_page(
			__( 'JOC Blockora Morph', 'joc-blockora-morph' ),
			__( 'Blockora Morph', 'joc-blockora-morph' ),
			'edit_posts',
			'joc-blockora-morph',
			array( $this, 'render_app' ),
			JOCBM_URL . 'assets/images/joc-blockora-morph-logo.gif',
			58
		);

		// Custom menu images are faded by core; restore full opacity for the brand mark.
		add_action( 'admin_head', array( $this, 'menu_icon_styles' ) );
	}

	/**
	 * Admin sidebar icon sizing / opacity for the logo mark.
	 */
	public function menu_icon_styles(): void {
		echo '<style id="jocbm-menu-icon">'
			. '#toplevel_page_joc-blockora-morph .wp-menu-image img{'
			. 'box-sizing:border-box;padding:2.5px;width:28px;height:28px;'
			. 'background:#fff;border-radius:100%;opacity:1;margin-top:4px;'
			. 'box-shadow:0 3px 10px 2px #0000;'
			. '}'
			. '#toplevel_page_joc-blockora-morph:hover .wp-menu-image img,'
			. '#toplevel_page_joc-blockora-morph.wp-has-current-submenu .wp-menu-image img,'
			. '#toplevel_page_joc-blockora-morph.current .wp-menu-image img{'
			. 'opacity:1;'
			. '}'
			. '</style>';
	}

	/**
	 * After activation, open Blockora Morph.
	 * First install → Welcome (via SPA). Returning users → Dashboard.
	 */
	public function maybe_activation_redirect(): void {
		if ( ! get_transient( 'jocbm_activation_redirect' ) ) {
			return;
		}

		delete_transient( 'jocbm_activation_redirect' );

		if ( ! current_user_can( 'edit_posts' ) ) {
			return;
		}

		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		if ( isset( $_GET['activate-multi'] ) ) {
			return;
		}

		// Avoid redirect loops / AJAX.
		if ( wp_doing_ajax() || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) ) {
			return;
		}

		wp_safe_redirect( admin_url( 'admin.php?page=joc-blockora-morph' ) );
		exit;
	}

	/**
	 * Full-screen body class on our page.
	 *
	 * @param string $classes Body classes.
	 */
	public function body_class( string $classes ): string {
		if ( $this->is_app_page() ) {
			$classes .= ' joc-blockora-morph-fullscreen';
		}

		return $classes;
	}

	/**
	 * Full-screen chrome for the SPA (wp_enqueue + inline, no hard-coded tags).
	 *
	 * @param string $hook Current admin hook.
	 */
	public function enqueue_fullscreen_chrome( string $hook ): void {
		if ( 'toplevel_page_joc-blockora-morph' !== $hook ) {
			return;
		}

		wp_register_style( 'joc-blockora-morph-fullscreen', false, array(), JOCBM_VERSION );
		wp_enqueue_style( 'joc-blockora-morph-fullscreen' );
		wp_add_inline_style(
			'joc-blockora-morph-fullscreen',
			CssSanitizer::sanitize_inline(
				'html.wp-toolbar,html.wp-toolbar.joc-blockora-morph-fullscreen{padding-top:0!important;--wp-admin--admin-bar--height:0px!important;}body.joc-blockora-morph-fullscreen{padding-top:0!important;margin-top:0!important;}'
			)
		);

		wp_register_script( 'joc-blockora-morph-fullscreen', false, array(), JOCBM_VERSION, false );
		wp_enqueue_script( 'joc-blockora-morph-fullscreen' );
		wp_add_inline_script(
			'joc-blockora-morph-fullscreen',
			'document.documentElement.classList.add("joc-blockora-morph-fullscreen");',
			'after'
		);
	}

	/**
	 * Whether the current screen is the Blockora Morph SPA.
	 */
	private function is_app_page(): bool {
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		$page = isset( $_GET['page'] ) ? sanitize_text_field( wp_unslash( $_GET['page'] ) ) : '';
		return 'joc-blockora-morph' === $page;
	}

	/**
	 * Enqueue admin SPA assets.
	 *
	 * @param string $hook Current admin hook.
	 */
	public function enqueue_assets( string $hook ): void {
		if ( 'toplevel_page_joc-blockora-morph' !== $hook ) {
			return;
		}

		$asset_file = JOCBM_PATH . 'build/admin.asset.php';
		$asset      = file_exists( $asset_file )
			? require $asset_file
			: array(
				'dependencies' => array( 'wp-element', 'wp-api-fetch', 'wp-i18n', 'wp-components' ),
				'version'      => JOCBM_VERSION,
			);

		$deps = array_unique(
			array_merge(
				$asset['dependencies'] ?? array(),
				array( 'wp-element', 'wp-api-fetch', 'wp-i18n', 'wp-components', 'wp-block-editor', 'wp-media-utils', 'editor' )
			)
		);

		/**
		 * Filter admin SPA script dependencies (Pro can prepend its bridge handle).
		 *
		 * @param array<int,string> $deps Script handles.
		 */
		$deps = apply_filters( 'jocbm_admin_script_dependencies', $deps );
		$deps = array_values( array_unique( array_map( 'strval', (array) $deps ) ) );

		/**
		 * Register dependent scripts (e.g. Pro admin bridge) before free admin enqueues.
		 *
		 * @param string $hook Current admin page hook.
		 */
		do_action( 'jocbm_register_admin_scripts', $hook );

		wp_enqueue_editor();
		wp_enqueue_media();

		\JOCBM\Theme\ThemeConfig::enqueue_inter_font();

		\JOCBM\Assets\SharedUi::enqueue();

		wp_enqueue_style(
			'joc-blockora-morph-admin',
			JOCBM_URL . 'build/admin.css',
			array(
				'joc-blockora-morph-fonts',
				'wp-components',
				'dashicons',
				\JOCBM\Assets\SharedUi::STYLE_HANDLE,
			),
			$asset['version']
		);

		wp_enqueue_script(
			'joc-blockora-morph-admin',
			JOCBM_URL . 'build/admin.js',
			$deps,
			$asset['version'],
			true
		);

		$welcome_seen = (bool) get_option( 'jocbm_welcome_seen', false );

		$registry = new \JOCBM\Blocks\BlockRegistry();
		$runtime  = \JOCBM\Blocks\BlockRegistry::frontend_runtime_urls();

		$localize = array(
			'version'        => JOCBM_VERSION,
			'restUrl'        => esc_url_raw( rest_url( 'joc-blockora-morph/v1' ) ),
			'nonce'          => wp_create_nonce( 'wp_rest' ),
			'adminUrl'       => admin_url( 'admin.php?page=joc-blockora-morph' ),
			'cmsUrl'         => admin_url(),
			'pluginUrl'      => JOCBM_URL,
			'logoUrl'        => JOCBM_URL . 'assets/images/joc-blockora-morph-logo.gif',
			'interFontUrl'   => \JOCBM\Theme\ThemeConfig::inter_font_url(),
			'welcomeSeen'    => $welcome_seen,
			'isPro'          => jocbm_is_pro(),
			'themeConfig'    => \JOCBM\Rest\ThemeConfigController::get_config_with_fonts(),
			'fontFamilies'   => \JOCBM\Theme\ThemeConfig::get_available_font_families(),
			'themeColors'    => \JOCBM\Theme\ThemeConfig::get_theme_origin_colors(),
			'buttonLibrary'  => $registry->get_button_library(),
			'dashiconsUrl'   => includes_url( 'css/dashicons.min.css' ),
			'themeAgnosticUrl' => \JOCBM\Theme\ThemeConfig::theme_agnostic_url(),
			'frontendJsUrl'  => $runtime['js'],
			'frontendCssUrl' => $runtime['css'],
			'iconLibraries'  => \JOCBM\Services\IconRegistry::localize_payload(),
			'user'           => array(
				'id'          => get_current_user_id(),
				'displayName' => wp_get_current_user()->display_name,
			),
			'routes'         => array(
				'welcome'         => 'welcome',
				'library'         => 'library',
				'myBlocks'        => 'my-blocks',
				'gutenbergBlocks' => 'gutenberg-blocks',
				'shortcodeBlocks' => 'shortcode-blocks',
				'theme'           => 'theme',
				'editor'          => 'editor',
			),
			'ownerLibrary'   => array(
				'configured' => false,
				'unlocked'   => false,
				'wantsGate'  => false,
			),
		);

		/**
		 * Filter admin SPA localization (Pro injects ownerLibrary, etc.).
		 *
		 * @param array<string,mixed> $localize Payload.
		 */
		$localize = apply_filters( 'jocbm_admin_localize', $localize );

		wp_localize_script( 'joc-blockora-morph-admin', 'jocbmAdmin', $localize );

		/**
		 * Fires after the admin SPA script is localized.
		 *
		 * @param string $hook Current admin page hook.
		 */
		do_action( 'jocbm_enqueue_admin', $hook );

		wp_set_script_translations( 'joc-blockora-morph-admin', 'joc-blockora-morph' );
	}

	/**
	 * Render React mount point (hides WP chrome via CSS).
	 */
	public function render_app(): void {
		echo '<div id="joc-blockora-morph-app" class="joc-blockora-morph-app"></div>';
	}
}
