<?php

/**

 * React admin shell — Settings + Dashboard (2.7).

 *

 * @package Newsroom_AI_Assistant

 */



if ( ! defined( 'ABSPATH' ) ) {

	exit;

}



if ( ! function_exists( 'newsai_settings_react_build_exists' ) ) {

	function newsai_settings_react_build_exists() {

		return is_readable( NEWSAI_PATH . 'assets/admin-app/build/index.js' );

	}

}



if ( ! function_exists( 'newsai_admin_react_tab_allowed' ) ) {

	/**

	 * @param string $tab Tab id.

	 * @return bool

	 */

	function newsai_admin_react_tab_allowed( $tab ) {

		if ( isset( $_GET['ui'] ) && sanitize_key( wp_unslash( (string) $_GET['ui'] ) ) === 'classic' ) {

			return false;

		}

		return in_array( $tab, [ 'settings', 'alerts', 'insights', 'perf', 'pro' ], true );

	}

}



if ( ! function_exists( 'newsai_enqueue_settings_react_app' ) ) {

	/**

	 * @param string $hook Admin hook.

	 */

	function newsai_enqueue_settings_react_app( $hook ) {

		if ( strpos( (string) $hook, 'newsai-settings' ) === false ) {

			return;

		}

		if ( ! function_exists( 'newsai_settings_react_enabled' ) || ! newsai_settings_react_enabled() ) {

			return;

		}

		if ( ! newsai_settings_react_build_exists() ) {

			add_action( 'admin_notices', 'newsai_settings_react_build_missing_notice' );

			return;

		}

		$tab = function_exists( 'newsai_admin_current_tab' ) ? newsai_admin_current_tab() : 'alerts';

		if ( ! newsai_admin_react_tab_allowed( $tab ) ) {

			return;

		}

		add_filter(
			'admin_body_class',
			static function ( $classes ) {
				return $classes . ' nros-react-shell-active';
			}
		);



		if ( function_exists( 'newsai_enqueue_nros_admin_dashboard_styles' ) ) {

			newsai_enqueue_nros_admin_dashboard_styles();

		}

		if ( function_exists( 'newsai_enqueue_nros_theme_styles' ) ) {

			newsai_enqueue_nros_theme_styles();

		}



		$asset_base = NEWSAI_PATH . 'assets/admin-app/build/';

		$asset_url  = NEWSAI_URL . 'assets/admin-app/build/';

		$ver        = function_exists( 'newsai_asset_ver' ) ? newsai_asset_ver( 'assets/admin-app/build/index.js' ) : NEWSAI_VERSION;



		$deps = [ 'wp-element', 'wp-components', 'wp-i18n', 'wp-api-fetch' ];

		if ( is_readable( $asset_base . 'index.asset.php' ) ) {

			$asset = include $asset_base . 'index.asset.php';

			if ( is_array( $asset ) && ! empty( $asset['dependencies'] ) ) {

				$deps = $asset['dependencies'];

			}

			if ( is_array( $asset ) && ! empty( $asset['version'] ) ) {

				$ver = (string) $asset['version'];

			}

		}



		$style_file = is_rtl() && is_readable( $asset_base . 'style-index-rtl.css' )

			? 'style-index-rtl.css'

			: 'style-index.css';

		wp_enqueue_style(

			'newsai-settings-react',

			$asset_url . $style_file,

			[ 'newsai-nros-theme', 'newsai-nros-admin-dashboard' ],

			$ver

		);



		wp_enqueue_script(

			'newsai-settings-react',

			$asset_url . 'index.js',

			$deps,

			$ver,

			true

		);



		$surface_map = [
			'alerts'   => 'dashboard',
			'insights' => 'insights',
			'perf'     => 'author-performance',
			'settings' => 'settings',
			'pro'      => 'pro',
		];
		$surface = isset( $surface_map[ $tab ] ) ? $surface_map[ $tab ] : 'dashboard';
		$is_pro  = function_exists( 'newsai_is_pro' ) && newsai_is_pro();
		$nav     = [
			[
				'id'    => 'dashboard',
				'label' => __( 'Dashboard', 'newsroom-ai-assistant' ),
				'url'   => admin_url( 'admin.php?page=newsai-settings&tab=alerts' ),
				'icon'  => '📊',
			],
			[
				'id'    => 'insights',
				'label' => __( 'Chief Insights', 'newsroom-ai-assistant' ),
				'url'   => admin_url( 'admin.php?page=newsai-settings&tab=insights' ),
				'icon'  => '🧭',
			],
		];
		if ( function_exists( 'newsai_author_perf_can_access' ) && newsai_author_perf_can_access() ) {
			$nav[] = [
				'id'    => 'author-performance',
				'label' => __( 'Author Performance', 'newsroom-ai-assistant' ),
				'url'   => admin_url( 'admin.php?page=newsai-settings&tab=perf' ),
				'icon'  => '📈',
			];
		}
		$nav[] = [
			'id'    => 'settings',
			'label' => __( 'Settings', 'newsroom-ai-assistant' ),
			'url'   => admin_url( 'admin.php?page=newsai-settings&tab=settings' ),
			'icon'  => '⚙️',
		];
		if ( current_user_can( 'manage_options' ) || ( function_exists( 'newsai_is_pro' ) && newsai_is_pro() ) ) {
			$nav[] = [
				'id'    => 'pro',
				'label' => __( 'PRO', 'newsroom-ai-assistant' ),
				'url'   => admin_url( 'admin.php?page=newsai-settings&tab=pro' ),
				'icon'  => '🚀',
			];
		}

		wp_localize_script(

			'newsai-settings-react',

			'newsroomSettingsBoot',

			[

				'surface'         => $surface,

				'tab'             => $tab,

				'nav'             => $nav,

				'isPro'           => $is_pro,

				'settingsUrl'     => esc_url_raw( rest_url( 'newsroom-os/v1/settings' ) ),

				'dashboardUrl'    => esc_url_raw( rest_url( 'newsroom-os/v1/dashboard' ) ),

				'insightsUrl'     => esc_url_raw( rest_url( 'newsroom-os/v1/insights' ) ),

				'authorPerfUrl'   => esc_url_raw( rest_url( 'newsroom-os/v1/author-performance' ) ),

				'actionUrl'       => esc_url_raw( rest_url( 'newsroom-os/v1/settings/action' ) ),

				'metaUrl'         => esc_url_raw( rest_url( 'newsroom-os/v1/settings/meta' ) ),

				'restRoot'        => esc_url_raw( rest_url() ),

				'nonce'           => wp_create_nonce( 'wp_rest' ),

				'ajaxUrl'         => esc_url_raw( admin_url( 'admin-ajax.php' ) ),

				'ajaxNonce'       => wp_create_nonce( 'newsai_ajax_nonce' ),

				'classicUrl'      => esc_url_raw( admin_url( 'admin.php?page=newsai-settings&tab=settings&ui=classic' ) ),

				'classicDashUrl'  => esc_url_raw( admin_url( 'admin.php?page=newsai-settings&tab=alerts&ui=classic' ) ),

				'switchClassicUrl' => esc_url_raw( admin_url( 'admin.php?page=newsai-settings&tab=settings&newsai_ui_mode=classic' ) ),

				'settingsPageUrl' => esc_url_raw( admin_url( 'admin.php?page=newsai-settings&tab=settings' ) ),

				'dashboardPageUrl'=> esc_url_raw( admin_url( 'admin.php?page=newsai-settings&tab=alerts' ) ),

				'proUrl'          => esc_url_raw( rest_url( 'newsroom-os/v1/pro' ) ),

				'proPageUrl'      => esc_url_raw( admin_url( 'admin.php?page=newsai-settings&tab=pro' ) ),

				'wpAdminUrl'      => esc_url_raw( admin_url( 'index.php' ) ),

				'i18n'            => [
					'exitToWp' => __( 'Exit to WordPress', 'newsroom-ai-assistant' ),
				],

			]

		);



		if ( function_exists( 'wp_set_script_translations' ) ) {

			wp_set_script_translations( 'newsai-settings-react', 'newsroom-ai-assistant', NEWSAI_PATH . 'languages' );

		}

	}

}

add_action( 'admin_enqueue_scripts', 'newsai_enqueue_settings_react_app', 20 );



if ( ! function_exists( 'newsai_settings_react_build_missing_notice' ) ) {

	function newsai_settings_react_build_missing_notice() {

		if ( ! function_exists( 'newsai_settings_react_enabled' ) || ! newsai_settings_react_enabled() ) {

			return;

		}

		$screen = function_exists( 'get_current_screen' ) ? get_current_screen() : null;

		if ( ! $screen || strpos( (string) $screen->id, 'newsai-settings' ) === false ) {

			return;

		}

		echo '<div class="notice notice-warning"><p>';

		echo esc_html__( 'Newsroom React admin UI is enabled but the JS bundle is missing. Run npm install && npm run build in assets/admin-app/.', 'newsroom-ai-assistant' );

		echo '</p></div>';

	}

}



if ( ! function_exists( 'newsai_admin_react_should_mount' ) ) {

	function newsai_admin_react_should_mount() {

		if ( ! function_exists( 'newsai_settings_react_enabled' ) || ! newsai_settings_react_enabled() ) {

			return false;

		}

		if ( ! newsai_settings_react_build_exists() ) {

			return false;

		}

		$tab = function_exists( 'newsai_admin_current_tab' ) ? newsai_admin_current_tab() : 'alerts';

		return newsai_admin_react_tab_allowed( $tab );

	}

}



if ( ! function_exists( 'newsai_admin_react_render_shell' ) ) {

	function newsai_admin_react_render_shell() {

		if ( ! newsai_admin_react_should_mount() ) {

			return false;

		}

		static $rendered = false;

		if ( $rendered ) {

			return true;

		}

		$rendered = true;

		echo '<div id="newsroom-admin-root" class="newsroom-admin-root" aria-live="polite"></div>';

		return true;

	}

}



if ( ! function_exists( 'newsai_settings_react_should_mount' ) ) {

	function newsai_settings_react_should_mount() {

		return false;

	}

}



if ( ! function_exists( 'newsai_dashboard_react_should_mount' ) ) {

	function newsai_dashboard_react_should_mount() {

		return false;

	}

}



if ( ! function_exists( 'newsai_settings_react_render_mount' ) ) {

		function newsai_settings_react_render_mount() {

		return false;

	}

}



if ( ! function_exists( 'newsai_dashboard_react_render_mount' ) ) {

	function newsai_dashboard_react_render_mount() {

		return false;

	}

}



if ( ! function_exists( 'newsai_settings_handle_ui_mode_query' ) ) {

	function newsai_settings_handle_ui_mode_query() {

		if ( ! current_user_can( 'manage_options' ) ) {

			return;

		}

		if ( ! isset( $_GET['newsai_ui_mode'] ) ) {

			return;

		}

		$mode = sanitize_key( wp_unslash( (string) $_GET['newsai_ui_mode'] ) );

		if ( ! in_array( $mode, [ 'classic', 'react' ], true ) ) {

			return;

		}

		if ( ! function_exists( 'newsai_settings_set_ui_mode' ) ) {

			return;

		}

		newsai_settings_set_ui_mode( $mode );

		$page = isset( $_GET['page'] ) ? sanitize_key( wp_unslash( (string) $_GET['page'] ) ) : 'newsai-settings';

		$tab  = isset( $_GET['tab'] ) ? sanitize_key( wp_unslash( (string) $_GET['tab'] ) ) : 'settings';

		$redirect = add_query_arg( [ 'page' => $page, 'tab' => $tab ], admin_url( 'admin.php' ) );

		if ( $mode === 'classic' ) {

			$redirect = add_query_arg( 'ui', 'classic', $redirect );

		}

		wp_safe_redirect( $redirect );

		exit;

	}

}

add_action( 'admin_init', 'newsai_settings_handle_ui_mode_query', 5 );

