<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

add_action( 'admin_menu', 'newsroom_os_register_wizard_page' );
function newsroom_os_register_wizard_page() {
	// Parent must not be null: add_submenu_page() calls plugin_basename( $parent_slug ). A null
	// parent hits wp_normalize_path( null ) and triggers PHP 8.1+ deprecations (strpos/str_replace on null).
	// Empty string keeps the page out of any visible parent menu (same intent as the old null pattern).
	add_submenu_page(
		'',
		'Welcome to Newsroom OS',
		'Newsroom Setup',
		'manage_options',
		'newsroom-os-wizard',
		'newsroom_os_wizard_screen_render'
	);
}

/**
 * Analyze the site so the wizard can recommend a performance profile tailored to it
 * (not just cache): post volume, page-cache & object-cache, SEO plugin, PHP version.
 *
 * @return array{post_count:int,tier:string,cache_plugins:string[],object_cache:bool,seo_plugins:string[],php:string,rec_richness:string,rec_article_body:string,rec_body_words:int}
 */
function newsroom_os_wizard_analyze_site() {
	$counts     = wp_count_posts( 'post' );
	$post_count = isset( $counts->publish ) ? (int) $counts->publish : 0;

	$active = (array) get_option( 'active_plugins', [] );
	if ( is_multisite() ) {
		$active = array_merge( $active, array_keys( (array) get_site_option( 'active_sitewide_plugins', [] ) ) );
	}
	$known_cache = [
		'Seraphinite Accelerator' => 'seraphinite-accelerator',
		'WP Rocket'               => 'wp-rocket/',
		'W3 Total Cache'          => 'w3-total-cache/',
		'WP Super Cache'          => 'wp-super-cache/',
		'LiteSpeed Cache'         => 'litespeed-cache/',
		'WP Fastest Cache'        => 'wp-fastest-cache/',
		'Cache Enabler'           => 'cache-enabler/',
		'Autoptimize'             => 'autoptimize/',
		'Hummingbird'             => 'hummingbird-performance/',
		'NitroPack'               => 'nitropack/',
	];
	$cache_plugins = [];
	foreach ( $known_cache as $label => $needle ) {
		foreach ( $active as $plugin_file ) {
			if ( is_string( $plugin_file ) && stripos( $plugin_file, $needle ) !== false ) {
				$cache_plugins[] = $label;
				break;
			}
		}
	}
	$cache_plugins = array_values( array_unique( $cache_plugins ) );

	$seo_plugins = [];
	if ( defined( 'WPSEO_VERSION' ) ) {
		$seo_plugins[] = 'Yoast SEO';
	}
	if ( defined( 'RANK_MATH_VERSION' ) || class_exists( 'RankMath' ) ) {
		$seo_plugins[] = 'Rank Math';
	}
	if ( defined( 'AIOSEO_VERSION' ) ) {
		$seo_plugins[] = 'All in One SEO';
	}

	$object_cache = function_exists( 'wp_using_ext_object_cache' ) ? (bool) wp_using_ext_object_cache() : false;

	// Tier: post volume is the dominant cost driver; a hard-to-purge page cache nudges it up.
	$has_heavy_cache = ! empty( $cache_plugins );
	if ( $post_count >= 5000 || ( $post_count >= 2000 && $has_heavy_cache ) ) {
		$tier = 'megasite';
	} elseif ( $post_count >= 500 ) {
		$tier = 'busy';
	} else {
		$tier = 'standard';
	}

	$recs = [
		'standard' => [ 'richness' => 'full',     'article_body' => 'full',    'body_words' => 200 ],
		'busy'     => [ 'richness' => 'full',     'article_body' => 'limited', 'body_words' => 200 ],
		'megasite' => [ 'richness' => 'balanced', 'article_body' => 'limited', 'body_words' => 150 ],
	];
	$rec = $recs[ $tier ];

	return [
		'post_count'       => $post_count,
		'tier'             => $tier,
		'cache_plugins'    => $cache_plugins,
		'object_cache'     => $object_cache,
		'seo_plugins'      => $seo_plugins,
		'php'              => PHP_VERSION,
		'rec_richness'     => $rec['richness'],
		'rec_article_body' => $rec['article_body'],
		'rec_body_words'   => $rec['body_words'],
	];
}

function newsroom_os_wizard_screen_render() {
	if ( ! current_user_can( 'manage_options' ) ) {
		wp_die( 'Unauthorized access' );
	}

	$analysis = newsroom_os_wizard_analyze_site();

	$site_name    = get_bloginfo( 'name' );
	$site_niche   = get_bloginfo( 'description' );
	$comp_rss     = get_option( 'newsai_competitor_rss', '' );
	$primary_city = get_option( 'nros_primary_city', '' );
	$site_profile = get_option( 'newsai_site_profile', 'newsroom' );
	$ver          = defined( 'NEWSAI_VERSION' ) ? NEWSAI_VERSION : '2.7.0';
	$show_registry_consent = ! ( function_exists( 'newsai_is_pro' ) && newsai_is_pro() );
	$show_react_ui_optin   = function_exists( 'newsai_settings_react_build_exists' )
		&& newsai_settings_react_build_exists()
		&& ! ( function_exists( 'newsai_settings_ui_locked_by_constant' ) && newsai_settings_ui_locked_by_constant() );

	$wizard_nonce = wp_create_nonce( 'nros_wizard_nonce' );

	$i18n = [
		's1_title'    => 'Welcome to Newsroom OS',
		's1_desc'     => 'Step 1 of 4: Let\'s get to know your site.',
		'org_name'    => 'Organization / Portal Name',
		'niche'       => 'Main Niche / Topics',
		'city'        => '📍 Primary City / Location',
		'city_p'      => 'Optional. Publisher home city (Organization areaServed). Articles get contentLocation only from tags/lede, or from this city if fallback is enabled in Settings.',
		'comp'        => 'Competitors to Monitor (RSS Feeds)',
		'work'        => 'How do you work?',
		'site_type'   => 'Site Type',
		'site_news'   => 'News Site',
		'site_news_p' => 'Breaking flow, editorial team, high publishing frequency',
		'site_blog'   => 'Blog / Magazine',
		'site_blog_p' => 'Evergreen content, slower cadence',
		'team'        => 'Team',
		'team_p'      => 'Tasks & Intel',
		'solo'        => 'Solo Blogger',
		'solo_p'      => 'SEO Tools Only',

		's2_title' => 'SEO & Schema Engine',
		's2_desc'  => 'Step 2 of 4: Configure schema policy, LiveBlog, and Voice SEO.',
		'mode_label'  => 'Setup mode',
		'mode_easy'   => '✨ Easy (recommended)',
		'mode_easy_p' => 'We auto-detect Voice SEO selectors and turn on full schema richness. No CSS needed.',
		'mode_adv'    => '🛠️ Advanced',
		'mode_adv_p'  => 'I want to set CSS selectors and custom feed pages myself.',
		'easy_note'   => '✨ Easy mode is on: Voice SEO selectors (.entry-title, .entry-content) and full schema richness are configured automatically. Switch to Advanced to customize.',
		'sch_type' => 'Primary Schema markup type:',
		'org_type' => 'Organization Type:',
		'social'   => 'Social Links (1 per line)',
		'c_feed'   => 'Custom Feed Page IDs (For Carousel)',
		'c_feed_p' => 'e.g. 14, 25 (If using a Page Builder for news feeds)',
		'speak'    => 'Voice SEO (Speakable CSS Classes)',
		'speak_p'  => 'e.g. .headline, .summary (What Google Assistant should read aloud)',
		'disab'    => 'Disabled',

		's3_title' => 'Story Timeline Engine',
		's3_desc'  => 'Step 3 of 4: Configure Story Timeline strategy and automated internal linking.',
		'head'     => 'Timeline Heading',
		'inj'      => 'Injection Mode (How should we display it?)',
		'auto'     => 'Auto-Pilot',
		'auto_p'   => 'Show on all articles automatically',
		'man'      => 'Manual Only',
		'man_p'    => 'Only where I use the shortcode',
		'safe_tl'  => 'Safe Uninstall Guarantee:',
		'safe_ds'  => 'Auto-Pilot is 100% safe. It does not modify your database.',

		's4_title' => 'You\'re all set! 🎉',
		's4_desc'  => 'Step 4 of 4: Quick guide to what\'s new in v' . $ver . '.',
		'h_eeat_t' => '👤 Author E-E-A-T Profiles (SEO)',
		'h_eeat_d' => 'Go to <strong>Users &rarr; Profile</strong> and fill in the Social Links and Job Title of each author.',
		'h_trnd_t' => '🔥 Radar, Personalized News & Tasks',
		'h_trnd_d' => 'In the sidebar, Trends stays global for stability, while the NEWS tab is personalized by author beat.',
		'h_clus_t' => '🔗 Story Clusters + Focus Mode',
		'h_clus_d' => 'Use Internal Links and Timeline together: when Storytelling is active, the links check passes correctly.',
		'h_new_t'  => '⚙️ What\'s new (v' . $ver . ')',
		'h_new_d'  => 'In Settings: Target Geo for your audience, semantic JSON-LD, editor tag pool, Wikidata tag enrichment, AI Tag Match (Pro BYOK), Chief Insights, and tabs for Schema, Timeline, UX/AI, Instant Indexing, and Content Decay Radar.',
		'react_ui_label' => 'Use modern settings UI',
		'react_ui_desc'  => 'Open the new guided React settings screen after setup (recommended). You can switch back anytime under Editorial → Editor UX.',

		'next'     => 'Next Step &rarr;',
		'back'     => '&larr; Back',
		'launch'   => 'Launch Newsroom OS 🚀',
		'def_head' => '⏳ Story Timeline: {tag}',

		'privacy_title' => 'Privacy (optional)',
		'privacy_label' => 'I agree to share anonymous site information with NewsOS.io',
		'privacy_desc'  => 'Unchecked by default. If you opt in, Newsroom OS sends a weekly heartbeat with your public site URL, site name, plugin version, WordPress/PHP versions, and locale to help improve the product. No articles, API keys, or license data are sent. You can withdraw consent anytime in Settings → Site Details.',
	];

	if ( empty( $site_niche ) || $site_niche === 'Just another WordPress site' || $site_niche === 'Ένας ακόμα ιστότοπος WordPress' ) {
		$yoast_options = get_option( 'wpseo_titles' );
		if ( ! empty( $yoast_options['metadesc-home-wpseo'] ) ) {
			$site_niche = $yoast_options['metadesc-home-wpseo'];
		} elseif ( get_option( 'rank_math_description_home' ) ) {
			$site_niche = get_option( 'rank_math_description_home' );
		} else {
			$site_niche = '';
		}
	}
	?>
	<style>
		#adminmenumain, #wpadminbar, #wpfooter { display: none !important; }
		#wpcontent, #wpbody-content { margin-left: 0 !important; padding: 0 !important; background: #f3f4f6; }
		.nros-wizard-wrapper { display: flex; align-items: center; justify-content: center; min-height: 100vh; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; padding: 40px 20px; box-sizing: border-box; }
		.nros-wizard-card { background: #ffffff; width: 100%; max-width: 650px; padding: 40px; border-radius: 12px; box-shadow: 0 10px 25px rgba(0,0,0,0.05); position: relative; overflow: hidden; }
		.nros-wizard-header { text-align: center; margin-bottom: 30px; }
		.nros-wizard-header h1 { font-size: 24px; font-weight: 600; color: #111827; margin: 0 0 10px 0; }
		.nros-wizard-header p { color: #6b7280; font-size: 15px; margin: 0; }
		.nros-wizard-step { display: none; animation: fadeIn 0.4s ease-in-out; }
		.nros-wizard-step.active { display: block; }
		@keyframes fadeIn { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } }
		.nros-form-group { margin-bottom: 20px; }
		.nros-form-group label { display: block; font-weight: 500; color: #374151; margin-bottom: 8px; font-size: 14px;}
		.nros-form-group input[type="text"], .nros-form-group textarea { width: 100%; padding: 10px 12px; border: 1px solid #d1d5db; border-radius: 6px; font-size: 14px; box-sizing: border-box; }
		.nros-form-group input:focus, .nros-form-group textarea:focus { border-color: #2563eb; box-shadow: 0 0 0 3px rgba(37,99,235,0.1); outline: none; }
		.nros-form-desc { font-size: 12px; color: #6b7280; margin-top: 5px; display: block; }
		.nros-radio-group { display: flex; gap: 15px; flex-wrap: wrap; }
		.nros-radio-card { flex: 1; min-width: 150px; border: 1px solid #d1d5db; border-radius: 8px; padding: 15px; cursor: pointer; text-align: center; transition: all 0.2s; }
		.nros-radio-card:hover { border-color: #2563eb; }
		.nros-radio-card input[type="radio"] { display: none; }
		.nros-radio-card.active { border-color: #2563eb; background: #eff6ff; }
		.nros-radio-card h4 { margin: 0 0 5px 0; font-size: 14px; color: #111827; }
		.nros-radio-card p { margin: 0; font-size: 12px; color: #6b7280; }
		.nros-safe-box { background: #e0f2fe; border: 1px solid #bfdbfe; border-left: 4px solid #3b82f6; padding: 12px 15px; border-radius: 6px; margin-top: 15px; font-size: 13px; color: #1e40af; }
		.nros-help-card { background: #f9fafb; border: 1px solid #e5e7eb; border-radius: 8px; padding: 15px; margin-bottom: 10px; text-align: left; }
		.nros-help-card h4 { margin: 0 0 5px 0; font-size: 14px; color: #111827; }
		.nros-help-card p { margin: 0; font-size: 13px; color: #6b7280; }
		.nros-buttons { display: flex; gap: 10px; margin-top: 30px; }
		.nros-btn { padding: 12px 20px; border: none; border-radius: 6px; font-size: 15px; font-weight: 500; cursor: pointer; flex: 1; text-align: center; transition: background 0.2s; }
		.nros-btn-primary { background: #2563eb; color: white; }
		.nros-btn-primary:hover { background: #1d4ed8; }
		.nros-btn-secondary { background: #e5e7eb; color: #374151; }
		.nros-btn-secondary:hover { background: #d1d5db; }
		.nros-progress { height: 4px; background: #e5e7eb; border-radius: 2px; margin-bottom: 30px; overflow: hidden; }
		.nros-progress-bar { height: 100%; background: #2563eb; width: 25%; transition: width 0.3s ease; }
	</style>

	<div class="nros-wizard-wrapper" lang="en">
		<div class="nros-wizard-card">

			<div class="nros-progress"><div class="nros-progress-bar" id="nros-progress-bar"></div></div>

			<div id="nros-step-1" class="nros-wizard-step active">
				<div class="nros-wizard-header"><h1><?php echo esc_html( $i18n['s1_title'] ); ?></h1><p><?php echo esc_html( $i18n['s1_desc'] ); ?></p></div>
				<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px;">
					<div class="nros-form-group"><label><?php echo esc_html( $i18n['org_name'] ); ?></label><input type="text" id="nros_site_name" value="<?php echo esc_attr( $site_name ); ?>"></div>
					<div class="nros-form-group"><label><?php echo esc_html( $i18n['niche'] ); ?></label><input type="text" id="nros_site_niche" value="<?php echo esc_attr( $site_niche ); ?>"></div>
				</div>

				<div class="nros-form-group">
					<label><?php echo esc_html( $i18n['city'] ); ?></label>
					<input type="text" id="nros_primary_city" value="<?php echo esc_attr( $primary_city ); ?>" placeholder="e.g. London, Jakarta, New York">
					<span class="nros-form-desc"><?php echo esc_html( $i18n['city_p'] ); ?></span>
				</div>

				<div class="nros-form-group">
					<label><?php echo esc_html( $i18n['comp'] ); ?></label>
					<textarea id="nros_comp_rss" rows="2" placeholder="https://example.com/feed/"><?php echo esc_textarea( $comp_rss ); ?></textarea>
				</div>
				<div class="nros-form-group">
					<label><?php echo esc_html( $i18n['site_type'] ); ?></label>
					<div class="nros-radio-group">
						<label class="nros-radio-card <?php echo ( $site_profile === 'newsroom' ) ? 'active' : ''; ?>" onclick="selectRadio(this, 'nros_site_profile')"><input type="radio" name="nros_site_profile" value="newsroom" <?php checked( $site_profile, 'newsroom' ); ?>><h4><?php echo esc_html( $i18n['site_news'] ); ?></h4><p><?php echo esc_html( $i18n['site_news_p'] ); ?></p></label>
						<label class="nros-radio-card <?php echo ( $site_profile === 'blog' ) ? 'active' : ''; ?>" onclick="selectRadio(this, 'nros_site_profile')"><input type="radio" name="nros_site_profile" value="blog" <?php checked( $site_profile, 'blog' ); ?>><h4><?php echo esc_html( $i18n['site_blog'] ); ?></h4><p><?php echo esc_html( $i18n['site_blog_p'] ); ?></p></label>
					</div>
				</div>
				<div class="nros-form-group">
					<label><?php echo esc_html( $i18n['work'] ); ?></label>
					<div class="nros-radio-group">
						<label class="nros-radio-card active" onclick="selectRadio(this, 'nros_team_size')"><input type="radio" name="nros_team_size" value="team" checked><h4><?php echo esc_html( $i18n['team'] ); ?></h4><p><?php echo esc_html( $i18n['team_p'] ); ?></p></label>
						<label class="nros-radio-card" onclick="selectRadio(this, 'nros_team_size')"><input type="radio" name="nros_team_size" value="solo"><h4><?php echo esc_html( $i18n['solo'] ); ?></h4><p><?php echo esc_html( $i18n['solo_p'] ); ?></p></label>
					</div>
				</div>
				<div class="nros-buttons"><button type="button" class="nros-btn nros-btn-primary" onclick="nextStep(2)"><?php echo wp_kses_post( $i18n['next'] ); ?></button></div>
			</div>

			<div id="nros-step-2" class="nros-wizard-step">
				<div class="nros-wizard-header"><h1><?php echo esc_html( $i18n['s2_title'] ); ?></h1><p><?php echo esc_html( $i18n['s2_desc'] ); ?></p></div>
				<div class="nros-form-group">
					<label><?php echo esc_html( $i18n['mode_label'] ); ?></label>
					<div class="nros-radio-group">
						<label class="nros-radio-card active" onclick="selectRadio(this, 'nros_setup_mode'); nrosSetupMode('easy');"><input type="radio" name="nros_setup_mode" value="easy" checked><h4><?php echo esc_html( $i18n['mode_easy'] ); ?></h4><p><?php echo esc_html( $i18n['mode_easy_p'] ); ?></p></label>
						<label class="nros-radio-card" onclick="selectRadio(this, 'nros_setup_mode'); nrosSetupMode('advanced');"><input type="radio" name="nros_setup_mode" value="advanced"><h4><?php echo esc_html( $i18n['mode_adv'] ); ?></h4><p><?php echo esc_html( $i18n['mode_adv_p'] ); ?></p></label>
					</div>
				</div>
				<div class="nros-form-group">
					<label><?php echo esc_html( $i18n['sch_type'] ); ?></label>
					<div class="nros-radio-group" style="margin-bottom: 15px;">
						<label class="nros-radio-card active" onclick="selectRadio(this, 'nros_schema_type')"><input type="radio" name="nros_schema_type" value="newsarticle" checked><h4>📰 NewsArticle</h4></label>
						<label class="nros-radio-card" onclick="selectRadio(this, 'nros_schema_type')"><input type="radio" name="nros_schema_type" value="article"><h4>🏢 Article</h4></label>
						<label class="nros-radio-card" onclick="selectRadio(this, 'nros_schema_type')"><input type="radio" name="nros_schema_type" value="none"><h4>🚫 <?php echo esc_html( $i18n['disab'] ); ?></h4></label>
					</div>
				</div>
				<?php
				$perf_tier        = $analysis['tier'];
				$perf_cache_label = ! empty( $analysis['cache_plugins'] ) ? implode( ', ', $analysis['cache_plugins'] ) : __( 'none detected', 'newsroom-ai-assistant' );
				$perf_seo_label   = ! empty( $analysis['seo_plugins'] ) ? implode( ', ', $analysis['seo_plugins'] ) : __( 'none', 'newsroom-ai-assistant' );
				$perf_cards       = [
					'standard' => [
						'icon'  => '🌱',
						'title' => __( 'Standard site', 'newsroom-ai-assistant' ),
						'desc'  => __( 'Up to ~500 posts. Full schema richness, full article body, instant rebuild on save.', 'newsroom-ai-assistant' ),
					],
					'busy'     => [
						'icon'  => '🚀',
						'title' => __( 'Busy site', 'newsroom-ai-assistant' ),
						'desc'  => __( '500–5k posts. Full richness, trimmed article body to keep pages light. Background warm.', 'newsroom-ai-assistant' ),
					],
					'megasite' => [
						'icon'  => '🏙️',
						'title' => __( 'Megasite', 'newsroom-ai-assistant' ),
						'desc'  => __( '5k+ posts or a hard-to-purge page cache. Balanced richness, trimmed body, serve-stale + gradual background rebuild (no CPU spikes).', 'newsroom-ai-assistant' ),
					],
				];
				?>
				<div class="nros-form-group">
					<label><?php echo esc_html( __( '⚙️ Performance profile (auto-analyzed)', 'newsroom-ai-assistant' ) ); ?></label>
					<div class="nros-safe-box" style="margin-bottom:12px;">
						<?php
						echo esc_html(
							sprintf(
								/* translators: 1: post count, 2: cache plugins, 3: object cache yes/no, 4: SEO plugins, 5: PHP version */
								__( 'We scanned your site: %1$s published posts · Page cache: %2$s · Persistent object cache: %3$s · SEO: %4$s · PHP %5$s. Recommendation is pre-selected below — change it any time in Settings → Schema.', 'newsroom-ai-assistant' ),
								number_format_i18n( $analysis['post_count'] ),
								$perf_cache_label,
								$analysis['object_cache'] ? __( 'yes', 'newsroom-ai-assistant' ) : __( 'no', 'newsroom-ai-assistant' ),
								$perf_seo_label,
								$analysis['php']
							)
						);
						?>
					</div>
					<div class="nros-radio-group" style="display:grid; grid-template-columns:1fr 1fr 1fr; gap:10px;">
						<?php foreach ( $perf_cards as $tier_key => $card ) : ?>
							<label class="nros-radio-card<?php echo $tier_key === $perf_tier ? ' active' : ''; ?>" onclick="selectRadio(this, 'nros_perf_profile')" style="padding:12px;">
								<input type="radio" name="nros_perf_profile" value="<?php echo esc_attr( $tier_key ); ?>" <?php checked( $tier_key, $perf_tier ); ?>>
								<h4 style="font-size:14px;"><?php echo esc_html( $card['icon'] . ' ' . $card['title'] ); ?><?php echo $tier_key === $perf_tier ? ' <span style="font-size:11px;color:#16a34a;">' . esc_html__( '✓ recommended', 'newsroom-ai-assistant' ) . '</span>' : ''; ?></h4>
								<p style="font-size:12px;"><?php echo esc_html( $card['desc'] ); ?></p>
							</label>
						<?php endforeach; ?>
					</div>
					<span class="nros-form-desc"><?php echo esc_html( __( 'Megasite-safe caching (serve-stale + background rebuild) stays ON for every profile — this only tunes how rich each article\'s schema is.', 'newsroom-ai-assistant' ) ); ?></span>
				</div>
				<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px;">
					<div class="nros-form-group">
						<label><?php echo esc_html( $i18n['org_type'] ); ?></label>
						<div class="nros-radio-group" style="display:flex; gap:10px;">
							<label class="nros-radio-card active" onclick="selectRadio(this, 'nros_org_type')" style="padding:10px;"><input type="radio" name="nros_org_type" value="NewsMediaOrganization" checked><h4 style="font-size:13px;">📡 News Media</h4></label>
							<label class="nros-radio-card" onclick="selectRadio(this, 'nros_org_type')" style="padding:10px;"><input type="radio" name="nros_org_type" value="Organization"><h4 style="font-size:13px;">🏢 General Org</h4></label>
						</div>
					</div>
					<div class="nros-form-group"><label><?php echo esc_html( $i18n['social'] ); ?></label><textarea id="nros_social_links" rows="2" placeholder="https://facebook.com/..."></textarea></div>
				</div>
				<div class="nros-safe-box" id="nros-easy-note">
					<?php echo esc_html( $i18n['easy_note'] ); ?>
				</div>
				<div id="nros-advanced-fields" style="display:none;">
					<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px;">
						<div class="nros-form-group">
							<label><?php echo esc_html( $i18n['c_feed'] ); ?></label>
							<input type="text" id="nros_custom_feed_pages" placeholder="e.g. 14, 25">
							<span class="nros-form-desc"><?php echo esc_html( $i18n['c_feed_p'] ); ?></span>
						</div>
						<div class="nros-form-group">
							<label><?php echo esc_html( $i18n['speak'] ); ?></label>
							<input type="text" id="nros_speakable_selectors" placeholder=".headline, .summary">
							<span class="nros-form-desc"><?php echo esc_html( $i18n['speak_p'] ); ?></span>
						</div>
					</div>
				</div>
				<div class="nros-buttons">
					<button type="button" class="nros-btn nros-btn-secondary" onclick="nextStep(1)"><?php echo wp_kses_post( $i18n['back'] ); ?></button>
					<button type="button" class="nros-btn nros-btn-primary" onclick="nextStep(3)"><?php echo wp_kses_post( $i18n['next'] ); ?></button>
				</div>
			</div>

			<div id="nros-step-3" class="nros-wizard-step">
				<div class="nros-wizard-header"><h1><?php echo esc_html( $i18n['s3_title'] ); ?></h1><p><?php echo esc_html( $i18n['s3_desc'] ); ?></p></div>
				<div class="nros-form-group">
					<label><?php echo esc_html( $i18n['head'] ); ?></label>
					<input type="text" id="nros_t_heading" value="<?php echo esc_attr( $i18n['def_head'] ); ?>">
				</div>
				<div class="nros-form-group">
					<label><?php echo esc_html( $i18n['inj'] ); ?></label>
					<div class="nros-radio-group">
						<label class="nros-radio-card active" onclick="selectRadio(this, 'nros_t_mode')">
							<input type="radio" name="nros_t_mode" value="auto" checked>
							<h4>⚡ <?php echo esc_html( $i18n['auto'] ); ?></h4><p><?php echo esc_html( $i18n['auto_p'] ); ?></p>
						</label>
						<label class="nros-radio-card" onclick="selectRadio(this, 'nros_t_mode')">
							<input type="radio" name="nros_t_mode" value="manual">
							<h4>✋ <?php echo esc_html( $i18n['man'] ); ?></h4><p><?php echo esc_html( $i18n['man_p'] ); ?></p>
						</label>
					</div>
				</div>
				<div class="nros-safe-box">
					<strong>💡 <?php echo esc_html( $i18n['safe_tl'] ); ?></strong> <?php echo esc_html( $i18n['safe_ds'] ); ?>
				</div>
				<div class="nros-buttons">
					<button type="button" class="nros-btn nros-btn-secondary" onclick="nextStep(2)"><?php echo wp_kses_post( $i18n['back'] ); ?></button>
					<button type="button" class="nros-btn nros-btn-primary" onclick="nextStep(4)"><?php echo wp_kses_post( $i18n['next'] ); ?></button>
				</div>
			</div>

			<div id="nros-step-4" class="nros-wizard-step">
				<div class="nros-wizard-header"><h1><?php echo esc_html( $i18n['s4_title'] ); ?></h1><p><?php echo esc_html( $i18n['s4_desc'] ); ?></p></div>

				<div class="nros-help-card">
					<h4><?php echo esc_html( $i18n['h_eeat_t'] ); ?></h4>
					<p><?php echo wp_kses_post( $i18n['h_eeat_d'] ); ?></p>
				</div>

				<div class="nros-help-card">
					<h4><?php echo esc_html( $i18n['h_trnd_t'] ); ?></h4>
					<p><?php echo esc_html( $i18n['h_trnd_d'] ); ?></p>
				</div>

				<div class="nros-help-card">
					<h4><?php echo esc_html( $i18n['h_clus_t'] ); ?></h4>
					<p><?php echo esc_html( $i18n['h_clus_d'] ); ?></p>
				</div>
				<div class="nros-help-card">
					<h4><?php echo esc_html( $i18n['h_new_t'] ); ?></h4>
					<p><?php echo esc_html( $i18n['h_new_d'] ); ?></p>
				</div>

				<?php if ( $show_registry_consent ) : ?>
				<div class="nros-form-group" style="margin-top:20px; padding:14px; border:1px solid #e5e7eb; border-radius:8px; background:#f9fafb;">
					<label style="display:flex; gap:10px; align-items:flex-start; cursor:pointer;">
						<input type="checkbox" id="nros_usage_registry_optin" name="nros_usage_registry_optin" value="1" style="margin-top:3px;">
						<span>
							<strong><?php echo esc_html( $i18n['privacy_label'] ); ?></strong>
							<span class="nros-form-desc" style="display:block; margin-top:6px;"><?php echo esc_html( $i18n['privacy_desc'] ); ?></span>
						</span>
					</label>
				</div>
				<?php endif; ?>

				<?php if ( $show_react_ui_optin ) : ?>
				<div class="nros-form-group" style="margin-top:12px; padding:14px; border:1px solid #dbeafe; border-radius:8px; background:#eff6ff;">
					<label style="display:flex; gap:10px; align-items:flex-start; cursor:pointer;">
						<input type="checkbox" id="nros_react_settings_ui" name="nros_react_settings_ui" value="1" style="margin-top:3px;">
						<span>
							<strong><?php echo esc_html( $i18n['react_ui_label'] ); ?></strong>
							<span class="nros-form-desc" style="display:block; margin-top:6px;"><?php echo esc_html( $i18n['react_ui_desc'] ); ?></span>
						</span>
					</label>
				</div>
				<?php endif; ?>

				<div class="nros-buttons">
					<button type="button" class="nros-btn nros-btn-secondary" onclick="nextStep(3)"><?php echo wp_kses_post( $i18n['back'] ); ?></button>
					<button type="button" class="nros-btn nros-btn-primary" id="nros-launch-btn"><?php echo esc_html( $i18n['launch'] ); ?></button>
				</div>
			</div>

		</div>
	</div>

	<script>
		function selectRadio(element, groupName) {
			const inputs = document.querySelectorAll(`input[name="${groupName}"]`);
			inputs.forEach(input => input.closest('.nros-radio-card').classList.remove('active'));
			element.classList.add('active');
			element.querySelector('input').checked = true;
		}

		function nrosSetupMode(mode) {
			var adv = document.getElementById('nros-advanced-fields');
			var note = document.getElementById('nros-easy-note');
			var isAdvanced = (mode === 'advanced');
			if (adv) { adv.style.display = isAdvanced ? 'block' : 'none'; }
			if (note) { note.style.display = isAdvanced ? 'none' : 'block'; }
		}

		function nextStep(step) {
			document.querySelectorAll('.nros-wizard-step').forEach(el => el.classList.remove('active'));
			document.getElementById(`nros-step-${step}`).classList.add('active');
			const progress = step === 1 ? '25%' : (step === 2 ? '50%' : (step === 3 ? '75%' : '100%'));
			document.getElementById('nros-progress-bar').style.width = progress;
			window.scrollTo(0,0);
		}

		document.getElementById('nros-launch-btn').addEventListener('click', function() {
			const btn = this;
			btn.innerHTML = 'Saving...';
			btn.disabled = true;

			const data = new URLSearchParams();
			data.append('action', 'nros_save_wizard_data');
			data.append('nonce', '<?php echo esc_js( $wizard_nonce ); ?>');
			data.append('site_name', document.getElementById('nros_site_name').value);
			data.append('site_niche', document.getElementById('nros_site_niche').value);
			data.append('primary_city', document.getElementById('nros_primary_city').value);
			data.append('site_profile', document.querySelector('input[name="nros_site_profile"]:checked').value);
			data.append('team_size', document.querySelector('input[name="nros_team_size"]:checked').value);
			data.append('schema_type', document.querySelector('input[name="nros_schema_type"]:checked').value);
			data.append('perf_profile', document.querySelector('input[name="nros_perf_profile"]:checked').value);
			data.append('comp_rss', document.getElementById('nros_comp_rss').value);
			data.append('org_type', document.querySelector('input[name="nros_org_type"]:checked').value);
			data.append('social_links', document.getElementById('nros_social_links').value);
			data.append('setup_mode', document.querySelector('input[name="nros_setup_mode"]:checked').value);
			data.append('feed_pages', document.getElementById('nros_custom_feed_pages').value);
			data.append('speakable', document.getElementById('nros_speakable_selectors').value);
			data.append('t_heading', document.getElementById('nros_t_heading').value);
			data.append('t_mode', document.querySelector('input[name="nros_t_mode"]:checked').value);
			var registryCb = document.getElementById('nros_usage_registry_optin');
			if (registryCb && registryCb.checked) {
				data.append('usage_registry_optin', '1');
			}
			var reactUiCb = document.getElementById('nros_react_settings_ui');
			if (reactUiCb && reactUiCb.checked) {
				data.append('react_settings_ui', '1');
			}

			fetch(ajaxurl, { method: 'POST', body: data })
			.then(response => response.json())
			.then(res => {
				if(res.success) {
					var dest = '<?php echo esc_url( admin_url( 'admin.php?page=newsai-settings&tab=settings' ) ); ?>';
					if (reactUiCb && reactUiCb.checked) {
						window.location.href = dest;
					} else {
						window.location.href = '<?php echo esc_url( admin_url( 'admin.php?page=newsai-settings&tab=alerts' ) ); ?>';
					}
				}
				else { alert('Error: ' + (res.data || 'Try again.')); btn.innerHTML = '<?php echo esc_js( $i18n['launch'] ); ?>'; btn.disabled = false; }
			});
		});
	</script>
	<?php
}

add_action( 'wp_ajax_nros_save_wizard_data', 'newsroom_os_ajax_save_wizard_data' );
function newsroom_os_ajax_save_wizard_data() {
	if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'nros_wizard_nonce' ) ) {
		wp_send_json_error( 'Security check failed.' );
		return;
	}
	if ( ! current_user_can( 'manage_options' ) ) {
		wp_send_json_error( 'Unauthorized access.' );
		return;
	}

	if ( isset( $_POST['site_name'] ) ) {
		update_option( 'nros_site_name', sanitize_text_field( wp_unslash( $_POST['site_name'] ) ) );
	}
	if ( isset( $_POST['site_niche'] ) ) {
		update_option( 'nros_site_niche', sanitize_text_field( wp_unslash( $_POST['site_niche'] ) ) );
	}
	if ( isset( $_POST['primary_city'] ) ) {
		update_option( 'nros_primary_city', sanitize_text_field( wp_unslash( $_POST['primary_city'] ) ) );
	}
	$site_profile = isset( $_POST['site_profile'] ) ? sanitize_text_field( wp_unslash( $_POST['site_profile'] ) ) : 'newsroom';
	if ( ! in_array( $site_profile, [ 'newsroom', 'blog' ], true ) ) {
		$site_profile = 'newsroom';
	}
	update_option( 'newsai_site_profile', $site_profile );
	if ( isset( $_POST['team_size'] ) ) {
		update_option( 'nros_team_size', sanitize_text_field( wp_unslash( $_POST['team_size'] ) ) );
	}
	if ( isset( $_POST['schema_type'] ) ) {
		update_option( 'nros_schema_type', sanitize_text_field( wp_unslash( $_POST['schema_type'] ) ) );
	}
	if ( isset( $_POST['comp_rss'] ) ) {
		update_option( 'newsai_competitor_rss', sanitize_textarea_field( wp_unslash( $_POST['comp_rss'] ) ) );
	}
	if ( isset( $_POST['org_type'] ) ) {
		update_option( 'nros_org_type', sanitize_text_field( wp_unslash( $_POST['org_type'] ) ) );
	}
	if ( isset( $_POST['social_links'] ) ) {
		update_option( 'nros_social_links', sanitize_textarea_field( wp_unslash( $_POST['social_links'] ) ) );
	}
	$setup_mode = isset( $_POST['setup_mode'] ) ? sanitize_key( wp_unslash( $_POST['setup_mode'] ) ) : 'easy';
	if ( ! in_array( $setup_mode, [ 'easy', 'advanced' ], true ) ) {
		$setup_mode = 'easy';
	}
	update_option( 'nros_setup_mode', $setup_mode );

	if ( 'easy' === $setup_mode ) {
		// Smart defaults: skip CSS prompts, auto-detect common WordPress markup for Voice SEO,
		// and keep schema richness at the fullest preset.
		$easy_speakable = (string) get_option( 'newsai_speakable_selectors', '' );
		if ( trim( $easy_speakable ) === '' ) {
			update_option( 'newsai_speakable_selectors', '.entry-title, .entry-content' );
		}
		update_option( 'nros_schema_richness', 'balanced' );
	} else {
		if ( isset( $_POST['feed_pages'] ) ) {
			update_option( 'newsai_custom_feed_pages', sanitize_text_field( wp_unslash( $_POST['feed_pages'] ) ) );
		}
		if ( isset( $_POST['speakable'] ) ) {
			update_option( 'newsai_speakable_selectors', sanitize_text_field( wp_unslash( $_POST['speakable'] ) ) );
		}
	}
	// Performance profile (auto-analyzed in the wizard): tunes schema richness/body per site
	// and keeps megasite-safe caching ON for everyone. Applied after the easy/advanced presets
	// so the analyzed recommendation wins.
	$perf_profile = isset( $_POST['perf_profile'] ) ? sanitize_key( wp_unslash( $_POST['perf_profile'] ) ) : 'standard';
	if ( ! in_array( $perf_profile, [ 'standard', 'busy', 'megasite' ], true ) ) {
		$perf_profile = 'standard';
	}
	$perf_map = [
		'standard' => [ 'richness' => 'balanced', 'article_body' => 'full',    'body_words' => 200 ],
		'busy'     => [ 'richness' => 'balanced', 'article_body' => 'limited', 'body_words' => 200 ],
		'megasite' => [ 'richness' => 'balanced', 'article_body' => 'limited', 'body_words' => 150 ],
	];
	$perf = $perf_map[ $perf_profile ];
	update_option( 'nros_schema_richness', $perf['richness'] );
	update_option( 'nros_schema_article_body', $perf['article_body'] );
	update_option( 'nros_schema_article_body_words', (int) $perf['body_words'] );
	update_option( 'nros_schema_perf_profile', $perf_profile, false );
	update_option( 'nros_schema_megasite_mode', 'yes' );
	if ( function_exists( 'nros_schema_schedule_legacy_warm_cron' ) ) {
		nros_schema_schedule_legacy_warm_cron();
	}

	if ( isset( $_POST['t_heading'] ) ) {
		update_option( 'newsai_timeline_heading', sanitize_text_field( wp_unslash( $_POST['t_heading'] ) ) );
	}

	if ( false === get_option( 'newsai_geo', false ) && function_exists( 'newsai_infer_geo_from_locale' ) ) {
		update_option( 'newsai_geo', newsai_infer_geo_from_locale(), false );
	}

	// Smart defaults by site profile — strategy/limit only; injection mode is set by user choice below.
	if ( $site_profile === 'newsroom' ) {
		update_option( 'newsai_timeline_strategy', 'ongoing' );
		update_option( 'newsai_timeline_limit', 5 );
		update_option( 'newsai_timeline_relevance_threshold', 5 );
		update_option( 'newsai_ui_circular_gauge', 'yes' );
		update_option( 'newsai_ui_onboarding_modal', 'yes' );
		update_option( 'newsai_advanced_nlp', 'yes' );
	} else {
		update_option( 'newsai_timeline_strategy', 'evergreen' );
		update_option( 'newsai_timeline_limit', 3 );
		update_option( 'newsai_timeline_relevance_threshold', 8 );
		update_option( 'newsai_ui_circular_gauge', 'yes' );
		update_option( 'newsai_ui_onboarding_modal', 'yes' );
		update_option( 'newsai_advanced_nlp', 'yes' );
		update_option( 'nros_schema_type', 'article' );
	}

	// Explicit wizard choice (step 3) wins for Auto-Pilot vs Manual — overrides profile default.
	if ( isset( $_POST['t_mode'] ) ) {
		$t_mode = sanitize_text_field( wp_unslash( $_POST['t_mode'] ) );
		if ( in_array( $t_mode, [ 'auto', 'manual' ], true ) ) {
			update_option( 'newsai_timeline_mode', $t_mode );
		}
	}

	if ( ! ( function_exists( 'newsai_is_pro' ) && newsai_is_pro() ) ) {
		if ( isset( $_POST['usage_registry_optin'] ) && '1' === (string) wp_unslash( $_POST['usage_registry_optin'] ) ) {
			if ( function_exists( 'newsai_usage_registry_grant_consent' ) ) {
				newsai_usage_registry_grant_consent();
			}
		} elseif ( function_exists( 'newsai_usage_registry_revoke_consent' ) ) {
			newsai_usage_registry_revoke_consent();
		} else {
			update_option( 'newsai_usage_registry_optin', 'no', false );
		}
	}

	update_option( 'nros_wizard_completed', true );

	if (
		isset( $_POST['react_settings_ui'] )
		&& '1' === (string) wp_unslash( $_POST['react_settings_ui'] )
		&& function_exists( 'newsai_settings_set_ui_mode' )
	) {
		newsai_settings_set_ui_mode( 'react' );
	}

	wp_send_json_success();
}
