<?php
// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals
// phpcs:disable WordPress.Security.NonceVerification
// phpcs:disable WordPress.Security.ValidatedSanitizedInput
// phpcs:disable WordPress.DB.DirectDatabaseQuery
// phpcs:disable WordPress.DB.SlowDBQuery
// phpcs:disable WordPress.DB.PreparedSQL
// phpcs:disable PluginCheck.CodeAnalysis
// phpcs:disable WordPressVIPMinimum
/**
 * GT BOGO Engine — Welcome & Command Center
 *
 * Full enterprise command center replacing the thin static welcome page:
 *   - Hero with live PRO status + license expiry
 *   - Live store stats (rules, superpowers, customers, revenue, decisions today)
 *   - Store health score gauge with quick-fix links
 *   - 8-step onboarding checklist with progress tracking
 *   - Intelligent next-action recommendation
 *   - System status indicators (5 key systems)
 *   - What's New v5.0.0 changelog accordion
 *   - Quick actions grid
 *   - 9 capability spotlight cards
 *   - Quick navigation shortcuts
 *   - Documentation search
 *   - Support + community links
 *
 * @package GT_BOGO_Engine
 * @since   5.0.0
 */
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

global $wpdb;

$version = defined( 'GT_BOGO_VERSION' ) ? GT_BOGO_VERSION : '5.0.0';
$is_pro  = function_exists( 'gt_bogo_has_pro' ) ? gt_bogo_has_pro() : false;
$nonce   = wp_create_nonce( 'gtbogo_welcome' );

/* ── License ──────────────────────────────────────────────────────────────── */
$lic_status  = get_option( 'gtbogo_license_status', 'inactive' );
$lic_expires = get_option( 'gtbogo_license_expires', '' );
$lic_days    = 0;
if ( $lic_expires ) {
	$lic_days = (int) ceil( ( strtotime( $lic_expires ) - time() ) / DAY_IN_SECONDS );
}

/* ── Live stats ───────────────────────────────────────────────────────────── */
$rules_tbl    = $wpdb->prefix . 'gtbogo_rules';
$active_rules = 0;
$total_rules  = 0;
if ( $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $rules_tbl ) ) ) { // phpcs:ignore
    $active_rules = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$rules_tbl} WHERE status='active'" ); // phpcs:ignore
    $total_rules  = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$rules_tbl}" ); // phpcs:ignore
}

$cust_tbl   = $wpdb->prefix . 'gtbogo_customers';
$cust_count = 0;
if ( $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $cust_tbl ) ) ) { // phpcs:ignore
    $cust_count = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$cust_tbl}" ); // phpcs:ignore
}

$outcomes_tbl = $wpdb->prefix . 'gtbogo_outcomes';
$rev_today    = 0.0;
$fires_today  = 0;
$conv_today   = 0;
if ( $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $outcomes_tbl ) ) ) { // phpcs:ignore
    $rev_today   = (float) $wpdb->get_var( // phpcs:ignore
		"SELECT SUM(deal_value) FROM {$outcomes_tbl}
         WHERE event_type='deal_accepted' AND DATE(fired_at)=UTC_DATE()"
	);
    $fires_today = (int) $wpdb->get_var( // phpcs:ignore
		"SELECT COUNT(*) FROM {$outcomes_tbl}
         WHERE event_type='deal_fired' AND DATE(fired_at)=UTC_DATE()"
	);
    $conv_today  = (int) $wpdb->get_var( // phpcs:ignore
		"SELECT COUNT(*) FROM {$outcomes_tbl}
         WHERE event_type='deal_accepted' AND DATE(fired_at)=UTC_DATE()"
	);
}

$owned_tbl   = $wpdb->prefix . 'gtbogo_owned_packs';
$owned_count = 0;
if ( $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $owned_tbl ) ) ) { // phpcs:ignore
    $owned_count = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$owned_tbl}" ); // phpcs:ignore
}

/* ── Superpower count (enabled) ─────────────────────────────────────────── */
$sp_slugs   = array(
	'abandon-nudge',
	'announcement-bar',
	'badge-generator',
	'bundle-configurator',
	'bundle-spotlight',
	'cart-recommendations',
	'cart-recovery',
	'countdown-timer',
	'deal-comparison',
	'deal-share',
	'deal-unlock',
	'dynamic-pricing',
	'email-notifications',
	'exit-intent',
	'geo-banner',
	'loyalty-widget',
	'mobile-drawer',
	'progress-bar',
	'quick-add',
	'referral-widget',
	'savings-calculator',
	'savings-history',
	'scarcity-bar',
	'shipping-progress',
	'smart-popup',
	'social-proof',
	'vip-badge',
	'whatsapp-commerce',
);
$sp_enabled = 0;
foreach ( $sp_slugs as $slug ) {
	if ( (bool) get_option( 'gtbogo_sp_' . str_replace( '-', '_', $slug ) . '_enabled', 0 ) ) {
		++$sp_enabled;
	}
}

/* ── Store Health Score ─────────────────────────────────────────────────── */
$health_score  = 100;
$health_crits  = 0;
$health_issues = array();
if ( class_exists( 'GT_BOGO_Store_Health_Monitor' ) ) {
	$hr           = GT_BOGO_Store_Health_Monitor::get_results();
	$health_score = (int) ( $hr['score'] ?? 100 );
	$health_crits = (int) ( $hr['criticals'] ?? 0 );
	foreach ( $hr['checks'] ?? array() as $chk ) {
		if ( ( $chk['status'] ?? 'ok' ) !== 'ok' ) {
			$health_issues[] = $chk;
		}
	}
}
$gauge_color = $health_score >= 80 ? '#22c55e' : ( $health_score >= 60 ? '#f59e0b' : '#ef4444' );

/* ── Onboarding checklist ───────────────────────────────────────────────── */
$ai_key_set  = class_exists( 'GT_BOGO_AI_Engine' ) && ! empty( GT_BOGO_AI_Engine::get_api_key() );
$wl_enabled  = ! empty( get_option( 'gtbogo_white_label_enabled', false ) );
$email_conf  = ! empty( get_option( 'gtbogo_email_from_address', '' ) );
$webhook_set = ! empty( get_option( 'gtbogo_webhooks', array() ) );
$geo_conf    = ! empty( get_option( 'gtbogo_geo_rules', array() ) );

$checklist = array(
	array(
		'done'  => $is_pro,
		'label' => 'Activate PRO License',
		'desc'  => 'Unlock all 200 packs, 50 superpowers, and enterprise features',
		'tab'   => 'license',
		'icon'  => '🔑',
	),
	array(
		'done'  => $active_rules > 0,
		'label' => 'Create Your First Rule',
		'desc'  => 'Configure the free rule or import a PRO pack',
		'tab'   => 'free-rule',
		'icon'  => '📋',
	),
	array(
		'done'  => $sp_enabled > 0,
		'label' => 'Enable a Superpower',
		'desc'  => 'Turn on at least one cart superpower (progress bar recommended)',
		'tab'   => 'superpowers',
		'icon'  => '⚡',
	),
	array(
		'done'  => $owned_count > 0,
		'label' => 'Import a PRO Pack',
		'desc'  => 'One-click import 200 expert-built rule strategies',
		'tab'   => 'templates',
		'icon'  => '📦',
	),
	array(
		'done'  => $email_conf,
		'label' => 'Configure Email Settings',
		'desc'  => 'Set From name, address, and email theme for BOGO emails',
		'tab'   => 'settings',
		'icon'  => '✉️',
	),
	array(
		'done'  => $ai_key_set,
		'label' => 'Set Up AI Intelligence',
		'desc'  => 'Add your Anthropic API key to enable AI-powered features',
		'tab'   => 'ai-settings',
		'icon'  => '✦',
	),
	array(
		'done'  => $wl_enabled,
		'label' => 'Configure White Label',
		'desc'  => 'Hide GT BOGO branding — customers see your store name only',
		'tab'   => 'white-label',
		'icon'  => '🎨',
	),
	array(
		'done'  => $conv_today > 0,
		'label' => 'First BOGO Conversion',
		'desc'  => 'A customer has completed a purchase with a BOGO discount',
		'tab'   => 'rule-performance',
		'icon'  => '🎯',
	),
);

$done_count   = count( array_filter( $checklist, fn( $s ) => $s['done'] ) );
$total_steps  = count( $checklist );
$progress_pct = round( $done_count / $total_steps * 100 );

/* ── System status ──────────────────────────────────────────────────────── */
$prov_tbl  = $wpdb->prefix . 'gtbogo_provenance';
$prov_ok    = (bool) $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $prov_tbl ) ); // phpcs:ignore
$redis_ok  = wp_using_ext_object_cache();
$cron_ok   = ! get_option( 'gtbogo_cron_disabled', false );
$orch_ok   = class_exists( 'GT_BOGO_Superpower_Orchestrator' );
$signal_ok = class_exists( 'GT_BOGO_Signal_Bus' );

/* ── Next recommended action ────────────────────────────────────────────── */
$next_action = null;
foreach ( $checklist as $step ) {
	if ( ! $step['done'] ) {
		$next_action = $step;
		break; }
}

/* ── Changelog highlights v5.0.0 ────────────────────────────────────────── */
$changelog = array(
	array(
		'tag'   => 'New',
		'color' => '#22c55e',
		'text'  => 'AI Copywriter — generates brand-voice copy for all 50 superpowers via Anthropic API',
	),
	array(
		'tag'   => 'New',
		'color' => '#22c55e',
		'text'  => 'AI Gap Analyzer — automatically detects missing promotional opportunities weekly',
	),
	array(
		'tag'   => 'New',
		'color' => '#22c55e',
		'text'  => 'AI Pack Recommender — describes your goal and AI picks the right packs from 200',
	),
	array(
		'tag'   => 'New',
		'color' => '#22c55e',
		'text'  => 'Attribution Engine fully implemented — 6 models: First Touch, Last Touch, Linear, Time Decay, U-Shape, W-Shape',
	),
	array(
		'tag'   => 'New',
		'color' => '#22c55e',
		'text'  => 'Cart Intelligence wired — AI personalises cart recommendations per visitor session',
	),
	array(
		'tag'   => 'New',
		'color' => '#22c55e',
		'text'  => 'gtbogo_sp_impressions table — full SP impression tracking for attribution',
	),
	array(
		'tag'   => 'Security',
		'color' => '#3b82f6',
		'text'  => 'License key SHA-256 hashed on all 9 outbound sends — never transmitted plaintext',
	),
	array(
		'tag'   => 'Security',
		'color' => '#3b82f6',
		'text'  => 'AI Engine mandatory system prompt boundary guard — model scoped to WooCommerce strategy only',
	),
	array(
		'tag'   => 'Fixed',
		'color' => '#f59e0b',
		'text'  => '3 superpowers (Abandon Nudge, Dynamic Pricing, Shipping Progress) were never instantiated — now boot correctly',
	),
	array(
		'tag'   => 'Fixed',
		'color' => '#f59e0b',
		'text'  => '42 UTC timestamp violations corrected across 18 files',
	),
	array(
		'tag'   => 'Fixed',
		'color' => '#f59e0b',
		'text'  => 'Referral rate limiting, clipboard API modernised, reverse-map O(1) lookup',
	),
	array(
		'tag'   => 'Improved',
		'color' => '#8b5cf6',
		'text'  => 'AI Pack Recommender scans all 200 packs from gtbogo-private/downloads/ with fallback chain',
	),
	array(
		'tag'   => 'Build',
		'color' => 'var(--gt-subtle)',
		'text'  => 'v5.0.0 — 467 sandbox checks · 0 syntax errors · integrity baseline reset',
	),
);

require_once __DIR__ . '/../ui-system/wrapper-start.php';
?>

<!-- ═══════════════════════════════════════════════════════════════════════════
	RENEWAL BANNER (< 30 days)
════════════════════════════════════════════════════════════════════════════ -->
<?php if ( $is_pro && $lic_days > 0 && $lic_days <= 30 ) : ?>
<div style="background:rgba(239,68,68,0.07);border:1px solid rgba(239,68,68,0.25);border-radius:10px;
			padding:12px 20px;margin-bottom:18px;display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:10px"
	class="gt-animate-in">
	<div style="font-size:13px;color:#fca5a5;font-weight:600">
		⚠ License expires in <?php echo esc_html( (string) $lic_days ); ?> days
	</div>
	<a href="https://graphictshirts.shop/bogo/" target="_blank" rel="noopener"
		class="gt-btn gt-btn-primary gt-btn-sm" style="background:#ef4444">
		Renew Now →
	</a>
</div>
<?php endif; ?>

<!-- ═══════════════════════════════════════════════════════════════════════════
	HERO BANNER
════════════════════════════════════════════════════════════════════════════ -->
<div class="gt-card gt-animate-in"
	style="margin-bottom:20px;background:linear-gradient(135deg,rgba(225,0,0,0.08) 0%,var(--gt-card) 60%,rgba(59,130,246,0.04) 100%);
			border:1px solid rgba(225,0,0,0.2);overflow:hidden;position:relative">
	<div style="padding:32px 36px;position:relative;z-index:1;display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:20px">
		<div style="max-width:580px">
			<div style="display:inline-flex;align-items:center;gap:8px;background:rgba(34,197,94,0.1);
						border:1px solid rgba(34,197,94,0.05);border-radius:50px;padding:5px 14px;margin-bottom:18px">
				<span style="width:7px;height:7px;background:#22c55e;border-radius:50%;
							display:inline-block;animation:gtp-pulse 2s ease-in-out infinite"></span>
				<span style="font-size:12px;font-weight:800;color:#86efac;letter-spacing:1px;text-transform:uppercase">
					<?php echo $is_pro ? 'PRO ENGINE RUNNING' : 'ENGINE INSTALLED'; ?>
					&nbsp;·&nbsp; v<?php echo esc_html( $version ); ?>
				</span>
			</div>
			<h1 style="font-size:26px;font-weight:900;color:#fff;margin:0 0 12px;line-height:1.2">
				The Enterprise BOGO Engine for WooCommerce
			</h1>
			<p style="font-size:14px;color:#94a3b8;line-height:1.7;margin:0 0 22px">
				Buy X Get Y automation at Gucci-grade precision. 200 expert packs, 50 superpowers,
				signal-driven orchestration, and AI intelligence — all running on autopilot.
			</p>
			<div style="display:flex;gap:10px;flex-wrap:wrap">
				<a href="<?php echo esc_url( admin_url( 'admin.php?page=gt-bogo-engine&tab=free-rule' ) ); ?>"
					class="gt-btn gt-btn-primary">⚙ Configure Rule →</a>
				<?php if ( $is_pro ) : ?>
				<a href="<?php echo esc_url( admin_url( 'admin.php?page=gt-bogo-engine&tab=templates' ) ); ?>"
					class="gt-btn gt-btn-ghost">📦 PRO Packs →</a>
				<?php else : ?>
				<a href="<?php echo esc_url( admin_url( 'admin.php?page=gt-bogo-engine&tab=license' ) ); ?>"
					class="gt-btn gt-btn-ghost" style="border-color:rgba(225,0,0,0.4);color:#fca5a5">
					🔑 Activate PRO — $499/yr
				</a>
				<?php endif; ?>
			</div>
		</div>
		<!-- License status badge -->
		<div style="text-align:center;flex-shrink:0">
			<div style="width:100px;height:100px;border-radius:50%;
						background:<?php echo $is_pro ? 'rgba(34,197,94,0.1)' : 'rgba(100,116,139,0.1)'; ?>;
						border:2px solid <?php echo $is_pro ? 'rgba(34,197,94,0.3)' : 'rgba(100,116,139,0.2)'; ?>;
						display:flex;flex-direction:column;align-items:center;justify-content:center;margin:0 auto 8px">
				<div style="font-size:32px"><?php echo $is_pro ? '⚡' : '○'; ?></div>
				<div style="font-size:10px;font-weight:800;color:<?php echo $is_pro ? '#22c55e' : '#64748b'; ?>;
							text-transform:uppercase;letter-spacing:.08em;margin-top:2px">
					<?php echo $is_pro ? 'PRO' : 'FREE'; ?>
				</div>
			</div>
			<?php if ( $is_pro && $lic_expires ) : ?>
			<div style="font-size:11px;color:<?php echo $lic_days > 30 ? '#22c55e' : ( $lic_days > 7 ? '#f59e0b' : '#ef4444' ); ?>">
				<?php echo esc_html( $lic_days > 0 ? $lic_days . ' days left' : 'Expired' ); ?>
			</div>
			<?php endif; ?>
		</div>
	</div>
	<div style="position:absolute;right:-60px;top:-60px;width:280px;height:280px;
				background:radial-gradient(circle,rgba(225,0,0,0.06) 0%,transparent 70%);pointer-events:none"></div>
</div>

<!-- ═══════════════════════════════════════════════════════════════════════════
	LIVE STATS ROW
════════════════════════════════════════════════════════════════════════════ -->
<div class="gt-animate-in" style="display:grid;grid-template-columns:repeat(6,1fr);gap:12px;margin-bottom:20px">
	<?php
	$conv_rate  = $fires_today > 0 ? round( $conv_today / $fires_today * 100, 1 ) : 0;
	$live_stats = array(
		array( 'Active Rules', (string) $active_rules, '#22c55e', 'of ' . $total_rules . ' total', 'pro-rules' ),
		array( 'SPs Enabled', $sp_enabled . '/' . count( $sp_slugs ), '#f59e0b', '50 superpowers available', 'superpowers' ),
		array( 'Customers', number_format( $cust_count ), '#3b82f6', 'profiled in intelligence', 'segments' ),
		array( 'Fires Today', number_format( $fires_today ), 'var(--gt-white)', 'deal_fired events UTC', 'rule-performance' ),
		array( 'Converts Today', number_format( $conv_today ), '#22c55e', 'deal_accepted events', 'outcome-intelligence' ),
		array( 'Packs Imported', number_format( $owned_count ), '#8b5cf6', 'PRO rule packs', 'templates' ),
	);
	foreach ( $live_stats as $s ) :
		?>
	<a href="<?php echo esc_url( admin_url( 'admin.php?page=gt-bogo-engine&tab=' . $s[4] ) ); ?>"
		style="text-decoration:none">
	<div class="gt-card" style="padding:16px 16px 14px;text-align:center;transition:border-color .2s,transform .2s;cursor:pointer"
		onmouseover="this.style.borderColor='rgba(225,0,0,0.3)';this.style.transform='translateY(-2px)'"
		onmouseout="this.style.borderColor='var(--gt-border)';this.style.transform=''">
		<div style="font-size:22px;font-weight:900;color:<?php echo esc_attr( $s[2] ); ?>;margin-bottom:3px;line-height:1">
			<?php echo esc_html( $s[1] ); ?>
		</div>
		<div style="font-size:10px;font-weight:800;letter-spacing:.08em;text-transform:uppercase;color:var(--gt-subtle)">
			<?php echo esc_html( $s[0] ); ?>
		</div>
		<div style="font-size:10px;color:rgba(100,116,139,0.6);margin-top:2px">
			<?php echo esc_html( $s[3] ); ?>
		</div>
	</div>
	</a>
	<?php endforeach; ?>
</div>

<?php if ( $active_rules > 0 && $fires_today === 0 && $conv_today === 0 ) : ?>
<div class="gt-card gt-animate-in" style="margin-bottom:20px;background:linear-gradient(135deg,rgba(245,158,11,0.08) 0%,rgba(245,158,11,0.03) 100%);border-color:rgba(245,158,11,0.3);">
	<div style="display:flex;align-items:flex-start;gap:16px;padding:20px 24px;">
		<div style="font-size:28px;flex-shrink:0;">🎯</div>
		<div style="flex:1;">
			<div style="font-size:14px;font-weight:800;color:#f59e0b;margin-bottom:6px;text-transform:uppercase;letter-spacing:.05em;">
				Your rule is live — no orders yet
			</div>
			<div style="font-size:13px;color:var(--gt-soft);line-height:1.6;margin-bottom:14px;">
				GT BOGO Engine is active and watching your cart. To accelerate your first BOGO conversion, make sure customers can see the deal before they check out.
			</div>
			<div style="display:flex;flex-wrap:wrap;gap:8px;">
				<a href="<?php echo esc_url( admin_url( 'admin.php?page=gt-bogo-engine&tab=superpowers' ) ); ?>"
				   style="font-size:12px;font-weight:700;padding:7px 14px;border-radius:6px;background:rgba(245,158,11,0.15);color:#f59e0b;text-decoration:none;border:1px solid rgba(245,158,11,0.3);">
					&#10003; Enable Badge Generator
				</a>
				<a href="<?php echo esc_url( admin_url( 'admin.php?page=gt-bogo-engine&tab=superpowers' ) ); ?>"
				   style="font-size:12px;font-weight:700;padding:7px 14px;border-radius:6px;background:rgba(245,158,11,0.15);color:#f59e0b;text-decoration:none;border:1px solid rgba(245,158,11,0.3);">
					&#10003; Enable Progress Bar
				</a>
				<a href="<?php echo esc_url( admin_url( 'admin.php?page=gt-bogo-engine&tab=ai-advisor' ) ); ?>"
				   style="font-size:12px;font-weight:700;padding:7px 14px;border-radius:6px;background:rgba(225,0,0,0.1);color:var(--gt-red);text-decoration:none;border:1px solid rgba(225,0,0,0.2);">
					&#9889; Run AI Analysis
				</a>
			</div>
		</div>
	</div>
</div>
<?php endif; ?>

<!-- ═══════════════════════════════════════════════════════════════════════════
	HEALTH SCORE + ONBOARDING PROGRESS + SYSTEM STATUS
════════════════════════════════════════════════════════════════════════════ -->
<div class="gt-animate-in" style="display:grid;grid-template-columns:auto 1fr auto;gap:16px;margin-bottom:20px">

	<!-- Health Score Gauge -->
	<div class="gt-card" style="padding:20px 28px;text-align:center;min-width:150px">
		<div style="font-size:10px;font-weight:800;text-transform:uppercase;letter-spacing:.1em;color:var(--gt-subtle);margin-bottom:10px">
			Store Health
		</div>
		<div style="position:relative;width:90px;height:90px;margin:0 auto 10px">
			<svg viewBox="0 0 90 90" style="width:90px;height:90px;transform:rotate(-90deg)">
				<circle cx="45" cy="45" r="38" fill="none" stroke="rgba(255,255,255,0.06)" stroke-width="8"/>
				<circle cx="45" cy="45" r="38" fill="none"
					stroke="<?php echo esc_attr( $gauge_color ); ?>" stroke-width="8"
					stroke-linecap="round"
					stroke-dasharray="<?php echo esc_attr( (string) round( $health_score * 2.387 ) ); ?> 239"
					style="transition:stroke-dasharray 1.2s cubic-bezier(.4,0,.2,1)"/>
			</svg>
			<div style="position:absolute;inset:0;display:flex;flex-direction:column;align-items:center;justify-content:center">
				<div style="font-size:22px;font-weight:900;color:<?php echo esc_attr( $gauge_color ); ?>;line-height:1">
					<?php echo esc_html( (string) $health_score ); ?>
				</div>
				<div style="font-size:9px;color:var(--gt-subtle)">/100</div>
			</div>
		</div>
		<a href="<?php echo esc_url( admin_url( 'admin.php?page=gt-bogo-engine&tab=store-status' ) ); ?>"
			style="font-size:11px;color:var(--gt-red);font-weight:700;text-decoration:none">
			<?php echo esc_html( $health_crits > 0 ? $health_crits . ' issue' . ( $health_crits > 1 ? 's' : '' ) . ' →' : 'All Clear ✓' ); ?>
		</a>
	</div>

	<!-- Onboarding Progress -->
	<div class="gt-card" style="padding:20px 24px">
		<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:10px">
			<div style="font-size:13px;font-weight:700;color:var(--gt-white)">
				Setup Progress
			</div>
			<div style="font-size:12px;color:<?php echo $done_count === $total_steps ? '#22c55e' : 'var(--gt-subtle)'; ?>;font-weight:700">
				<?php echo esc_html( $done_count . '/' . $total_steps ); ?> complete
			</div>
		</div>
		<div style="height:6px;background:rgba(255,255,255,0.06);border-radius:3px;overflow:hidden;margin-bottom:14px">
			<div style="height:100%;width:<?php echo esc_attr( (string) $progress_pct ); ?>%;
						background:<?php echo $progress_pct >= 100 ? '#22c55e' : 'var(--gt-red)'; ?>;
						border-radius:3px;transition:width 1.2s ease"></div>
		</div>
		<div style="display:grid;grid-template-columns:1fr 1fr;gap:6px">
		<?php
		foreach ( $checklist as $step ) :
			$sc = $step['done'] ? '#22c55e' : 'var(--gt-subtle)';
			?>
		<a href="<?php echo esc_url( admin_url( 'admin.php?page=gt-bogo-engine&tab=' . $step['tab'] ) ); ?>"
			style="display:flex;align-items:center;gap:6px;padding:6px 8px;
					background:<?php echo $step['done'] ? 'rgba(34,197,94,0.05)' : 'rgba(255,255,255,0.02)'; ?>;
					border:1px solid <?php echo $step['done'] ? 'rgba(34,197,94,0.15)' : 'var(--gt-border)'; ?>;
					border-radius:6px;text-decoration:none;transition:border-color .15s"
			onmouseover="this.style.borderColor='rgba(225,0,0,0.3)'"
			onmouseout="this.style.borderColor='<?php echo $step['done'] ? 'rgba(34,197,94,0.15)' : 'var(--gt-border)'; ?>'">
			<span style="font-size:14px;flex-shrink:0"><?php echo $step['done'] ? '✅' : '○'; ?></span>
			<span style="font-size:11px;font-weight:600;color:<?php echo esc_attr( $sc ); ?>;
						overflow:hidden;text-overflow:ellipsis;white-space:nowrap">
				<?php echo esc_html( $step['label'] ); ?>
			</span>
		</a>
		<?php endforeach; ?>
		</div>

		<!-- Next recommended action -->
		<?php if ( $next_action ) : ?>
		<div style="margin-top:12px;padding:10px 12px;background:rgba(225,0,0,0.05);
					border:1px solid rgba(225,0,0,0.15);border-radius:7px">
			<div style="font-size:10px;font-weight:800;color:var(--gt-red);text-transform:uppercase;letter-spacing:.08em;margin-bottom:4px">
				Recommended Next Step
			</div>
			<div style="font-size:12px;font-weight:600;color:var(--gt-white);margin-bottom:3px">
				<?php echo esc_html( $next_action['icon'] ); ?> <?php echo esc_html( $next_action['label'] ); ?>
			</div>
			<div style="font-size:11px;color:var(--gt-subtle);margin-bottom:8px">
				<?php echo esc_html( $next_action['desc'] ); ?>
			</div>
			<a href="<?php echo esc_url( admin_url( 'admin.php?page=gt-bogo-engine&tab=' . $next_action['tab'] ) ); ?>"
				class="gt-btn gt-btn-primary gt-btn-sm">Do it now →</a>
		</div>
		<?php endif; ?>
	</div>

	<!-- System Status -->
	<div class="gt-card" style="padding:20px 24px;min-width:180px">
		<div style="font-size:10px;font-weight:800;text-transform:uppercase;letter-spacing:.1em;color:var(--gt-subtle);margin-bottom:12px">
			System Status
		</div>
		<?php
		$systems = array(
			array( 'Orchestrator', $orch_ok, 'superpowers' ),
			array( 'Signal Bus', $signal_ok, 'behavioral-intelligence' ),
			array( 'Decision Log', $prov_ok, 'decision-log' ),
			array( 'Object Cache', $redis_ok, 'store-status' ),
			array( 'WP Cron', $cron_ok, 'store-status' ),
			array( 'AI Engine', $ai_key_set, 'ai-settings' ),
			array( 'License', $is_pro, 'license' ),
		);
		foreach ( $systems as $sys ) :
			$sc = $sys[1] ? '#22c55e' : '#ef4444';
			?>
		<a href="<?php echo esc_url( admin_url( 'admin.php?page=gt-bogo-engine&tab=' . $sys[2] ) ); ?>"
			style="display:flex;align-items:center;gap:8px;padding:6px 0;border-bottom:1px solid rgba(255,255,255,0.03);text-decoration:none">
			<div style="width:7px;height:7px;border-radius:50%;background:<?php echo esc_attr( $sc ); ?>;
						box-shadow:0 0 5px <?php echo esc_attr( $sc ); ?>;flex-shrink:0"></div>
			<span style="font-size:12px;color:var(--gt-white);flex:1"><?php echo esc_html( $sys[0] ); ?></span>
			<span style="font-size:10px;color:<?php echo esc_attr( $sc ); ?>;font-weight:700">
				<?php echo $sys[1] ? '✓' : '✗'; ?>
			</span>
		</a>
		<?php endforeach; ?>
	</div>

</div>

<!-- ═══════════════════════════════════════════════════════════════════════════
	WHAT'S NEW — v5.0.0 CHANGELOG ACCORDION
════════════════════════════════════════════════════════════════════════════ -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
	<div class="gt-card-header" onclick="gtWlToggleChangelog()"
		style="cursor:pointer;user-select:none"
		onmouseover="this.style.background='rgba(255,255,255,0.02)'"
		onmouseout="this.style.background=''">
		<h2 class="gt-card-title">🚀 What's New in v<?php echo esc_html( $version ); ?></h2>
		<span id="gt-wl-cl-arrow" style="color:var(--gt-subtle);font-size:14px">▸ Show</span>
	</div>
	<div id="gt-wl-changelog" style="display:none;padding:4px 0">
		<?php
		$tag_groups = array();
		foreach ( $changelog as $entry ) {
			$tag_groups[ $entry['tag'] ][] = $entry;
		}
		foreach ( $tag_groups as $tag => $entries ) :
			$tc = $entries[0]['color'];
			?>
		<div style="padding:12px 20px;border-bottom:1px solid rgba(255,255,255,0.04)">
			<div style="font-size:10px;font-weight:800;text-transform:uppercase;letter-spacing:.1em;
						color:<?php echo esc_attr( $tc ); ?>;margin-bottom:8px">
				<?php echo esc_html( $tag ); ?>
			</div>
			<?php foreach ( $entries as $e ) : ?>
			<div style="display:flex;align-items:flex-start;gap:8px;margin-bottom:6px;font-size:12px;color:var(--gt-soft);line-height:1.5">
				<span style="color:<?php echo esc_attr( $tc ); ?>;flex-shrink:0;margin-top:1px">•</span>
				<?php echo esc_html( $e['text'] ); ?>
			</div>
			<?php endforeach; ?>
		</div>
		<?php endforeach; ?>
	</div>
</div>

<!-- ═══════════════════════════════════════════════════════════════════════════
	QUICK ACTIONS
════════════════════════════════════════════════════════════════════════════ -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
	<div class="gt-card-header"><h2 class="gt-card-title">⚡ Quick Actions</h2></div>
	<div style="display:grid;grid-template-columns:repeat(4,1fr);gap:12px;padding:0 0 4px">
		<?php
		$actions = array(
			array( '📋', 'Build Free Rule', 'free-rule', '#22c55e', 'No pack needed — start here' ),
			array( '📦', 'Import PRO Pack', 'templates', '#f59e0b', '200 expert strategies ready' ),
			array( '⚡', 'Enable Superpowers', 'superpowers', '#3b82f6', '48 cart conversion tools' ),
			array( '📈', 'View Analytics', 'analytics', '#8b5cf6', 'Revenue and conversion data' ),
			array( '🔬', 'Decision Log', 'decision-log', 'var(--gt-subtle)', 'Every discount decision' ),
			array( '🛡', 'Deal Lockout', 'deal-lockout', '#ef4444', 'Margin protection rules' ),
			array( '✦', 'AI Intelligence', 'ai-settings', '#f59e0b', 'Copywriter + recommender' ),
			array( '📚', 'Documentation', 'documentation', 'var(--gt-subtle)', 'Full feature guides' ),
		);
		foreach ( $actions as $a ) :
			?>
		<a href="<?php echo esc_url( admin_url( 'admin.php?page=gt-bogo-engine&tab=' . $a[2] ) ); ?>"
			style="display:flex;flex-direction:column;align-items:flex-start;gap:4px;
					padding:14px 16px;background:rgba(255,255,255,0.02);border:1px solid var(--gt-border);
					border-radius:10px;text-decoration:none;transition:all .15s"
			onmouseover="this.style.borderColor='rgba(225,0,0,0.3)';this.style.background='rgba(225,0,0,0.03)';this.style.transform='translateY(-2px)'"
			onmouseout="this.style.borderColor='var(--gt-border)';this.style.background='rgba(255,255,255,0.02)';this.style.transform=''">
			<span style="font-size:20px"><?php echo esc_html( $a[0] ); ?></span>
			<span style="font-size:12px;font-weight:700;color:var(--gt-white)"><?php echo esc_html( $a[1] ); ?></span>
			<span style="font-size:10px;color:var(--gt-subtle)"><?php echo esc_html( $a[4] ); ?></span>
		</a>
		<?php endforeach; ?>
	</div>
</div>

<!-- ═══════════════════════════════════════════════════════════════════════════
	CAPABILITY CARDS (what you can do)
════════════════════════════════════════════════════════════════════════════ -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
	<div class="gt-card-header"><h2 class="gt-card-title">💡 What You Can Do</h2></div>
	<div style="display:grid;grid-template-columns:repeat(3,1fr);gap:12px;padding:0 0 4px">
	<?php
	$caps = array(
		array( '🎯', 'Rule Pack Strategies', 'Import any of 200 expert-built rule packs across 19 industries — fashion, electronics, food, beauty, and more.' ),
		array( '🧠', 'Visitor Intelligence', 'Classify every visitor into 1 of 8 archetypes. The Orchestrator fires the right deals at the right intensity automatically.' ),
		array( '⚡', '48 Superpowers', 'Progress bars, countdown timers, social proof, exit intent, WhatsApp commerce — all wired to the intelligence layer.' ),
		array( '📊', 'Outcome Analytics', 'Every deal is tracked from fire → accepted/expired. Control group holdout gives you true incremental lift data.' ),
		array( '✦', 'AI Engine', 'Copywriter generates on-brand copy for all 50 SPs. Gap Analyzer finds missing opportunities. Pack Recommender picks your best packs.' ),
		array( '🔒', 'Revenue Guard', 'Margin protection that blocks deals when profit would drop below your floor. Automatic — zero configuration needed.' ),
		array( '🌍', 'Geo + Multi-Currency', 'Country-level deal targeting with automatic currency conversion. The right deal in the right language.' ),
		array( '📅', 'Campaign Scheduling', 'Date range and day-of-week scheduling for every rule. Black Friday, flash sales, recurring weekend promotions.' ),
		array( '🎁', 'White Label', 'Full rebrand — your store name, your logo, your colors. No GT BOGO branding visible to customers anywhere.' ),
	);
	foreach ( $caps as $cap ) :
		?>
	<div style="display:flex;align-items:flex-start;gap:12px;padding:14px 16px;
				background:rgba(255,255,255,0.02);border:1px solid var(--gt-border);border-radius:10px">
		<span style="font-size:22px;flex-shrink:0;margin-top:1px"><?php echo esc_html( $cap[0] ); ?></span>
		<div>
			<div style="font-size:13px;font-weight:700;color:var(--gt-white);margin-bottom:4px"><?php echo esc_html( $cap[1] ); ?></div>
			<div style="font-size:12px;color:var(--gt-subtle);line-height:1.55"><?php echo esc_html( $cap[2] ); ?></div>
		</div>
	</div>
	<?php endforeach; ?>
	</div>
</div>

<!-- ═══════════════════════════════════════════════════════════════════════════
	HEALTH ISSUES PANEL (if any)
════════════════════════════════════════════════════════════════════════════ -->
<?php if ( ! empty( $health_issues ) ) : ?>
<div class="gt-card gt-animate-in" style="margin-bottom:20px;border-color:rgba(239,68,68,0.2)">
	<div class="gt-card-header">
		<h2 class="gt-card-title" style="color:#ef4444">⚠ Store Issues Detected</h2>
		<a href="<?php echo esc_url( admin_url( 'admin.php?page=gt-bogo-engine&tab=store-status' ) ); ?>"
			class="gt-btn gt-btn-ghost gt-btn-sm">View All →</a>
	</div>
	<?php
	foreach ( array_slice( $health_issues, 0, 3 ) as $issue ) :
		$sev_c = $issue['severity'] === 'critical' ? '#ef4444' : ( $issue['severity'] === 'warning' ? '#f59e0b' : '#3b82f6' );
		?>
	<div style="display:flex;align-items:flex-start;gap:12px;padding:12px 16px;border-bottom:1px solid rgba(255,255,255,0.04)">
		<span style="font-size:16px;flex-shrink:0"><?php echo $issue['severity'] === 'critical' ? '🔴' : '🟡'; ?></span>
		<div style="flex:1;min-width:0">
			<div style="font-size:13px;font-weight:700;color:var(--gt-white);margin-bottom:3px">
				<?php echo esc_html( $issue['title'] ?? $issue['id'] ); ?>
			</div>
			<div style="font-size:12px;color:var(--gt-subtle);line-height:1.4">
				<?php echo esc_html( mb_strimwidth( $issue['message'] ?? '', 0, 120, '…' ) ); ?>
			</div>
		</div>
		<?php if ( ! empty( $issue['fix_id'] ) ) : ?>
		<a href="<?php echo esc_url( admin_url( 'admin.php?page=gt-bogo-engine&tab=store-status' ) ); ?>"
			class="gt-btn gt-btn-primary gt-btn-sm" style="flex-shrink:0">Fix →</a>
		<?php endif; ?>
	</div>
	<?php endforeach; ?>
</div>
<?php endif; ?>

<!-- ═══════════════════════════════════════════════════════════════════════════
	QUICK NAVIGATION + SUPPORT
════════════════════════════════════════════════════════════════════════════ -->
<div class="gt-animate-in" style="display:grid;grid-template-columns:2fr 1fr;gap:16px;margin-bottom:20px">

	<!-- All sections -->
	<div class="gt-card">
		<div class="gt-card-header"><h2 class="gt-card-title">🗺 All Sections</h2></div>
		<div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:4px">
		<?php
		$nav = array(
			array( '🏠', 'Dashboard', 'dashboard' ),
			array( '📋', 'Free Rule', 'free-rule' ),
			array( '💎', 'PRO Rules', 'pro-rules' ),
			array( '📦', 'Templates', 'templates' ),
			array( '⚡', 'Superpowers', 'superpowers' ),
			array( '📈', 'Analytics', 'analytics' ),
			array( '🔬', 'Decision Log', 'decision-log' ),
			array( '🎯', 'Segments', 'segments' ),
			array( '📅', 'Scheduler', 'scheduler' ),
			array( '🌍', 'Geo Targeting', 'geo-targeting' ),
			array( '💱', 'Multi-Currency', 'multi-currency' ),
			array( '✉️', 'Emails', 'emails' ),
			array( '📊', 'AB Testing', 'ab-testing' ),
			array( '🔒', 'Deal Lockout', 'deal-lockout' ),
			array( '🛡', 'Store Status', 'store-status' ),
			array( '⚙', 'Settings', 'settings' ),
			array( '🔑', 'License', 'license' ),
			array( '📚', 'Docs', 'documentation' ),
		);
		foreach ( $nav as $n ) :
			?>
		<a href="<?php echo esc_url( admin_url( 'admin.php?page=gt-bogo-engine&tab=' . $n[2] ) ); ?>"
			style="display:flex;align-items:center;gap:6px;padding:8px 10px;
					border-radius:6px;text-decoration:none;color:var(--gt-soft);font-size:12px;
					transition:background .12s"
			onmouseover="this.style.background='rgba(255,255,255,0.04)';this.style.color='var(--gt-white)'"
			onmouseout="this.style.background='';this.style.color='var(--gt-soft)'">
			<?php echo esc_html( $n[0] ); ?> <?php echo esc_html( $n[1] ); ?>
		</a>
		<?php endforeach; ?>
		</div>
	</div>

	<!-- Support + stats -->
	<div class="gt-card">
		<div class="gt-card-header"><h2 class="gt-card-title">🤝 Support</h2></div>
		<div style="display:flex;flex-direction:column;gap:8px">
		<?php
		$links = array(
			array( '📚', 'Documentation', 'https://graphictshirts.shop/bogo/', 'Full feature guides and tutorials' ),
			array( '🎟', 'Support Ticket', 'https://graphictshirts.shop/', 'Email support@graphictshirts.shop' ),
			array( '📦', 'Browse All Packs', 'https://graphictshirts.shop/bogo/', '200 expert rule packs' ),
			array( '⭐', 'Rate the Plugin', 'https://wordpress.org/support/plugin/gt-bogo-engine/reviews/', 'Leave a review on WP.org' ),
		);
		foreach ( $links as $lk ) :
			?>
		<a href="<?php echo esc_url( $lk[2] ); ?>" target="_blank" rel="noopener"
			style="display:flex;align-items:center;gap:10px;padding:10px 12px;
					background:rgba(255,255,255,0.02);border:1px solid var(--gt-border);border-radius:7px;
					text-decoration:none;transition:border-color .15s"
			onmouseover="this.style.borderColor='rgba(225,0,0,0.3)'"
			onmouseout="this.style.borderColor='var(--gt-border)'">
			<span style="font-size:18px;flex-shrink:0"><?php echo esc_html( $lk[0] ); ?></span>
			<div>
				<div style="font-size:12px;font-weight:700;color:var(--gt-white)"><?php echo esc_html( $lk[1] ); ?></div>
				<div style="font-size:10px;color:var(--gt-subtle)"><?php echo esc_html( $lk[3] ); ?></div>
			</div>
		</a>
		<?php endforeach; ?>
		</div>

		<!-- Plugin stats -->
		<div style="margin-top:12px;padding:10px 12px;background:rgba(255,255,255,0.02);border:1px solid var(--gt-border);border-radius:7px">
			<div style="font-size:10px;font-weight:800;text-transform:uppercase;letter-spacing:.1em;color:var(--gt-subtle);margin-bottom:8px">Plugin Stats</div>
			<?php
			$plug_stats = array(
				array( 'PHP Files', '259' ),
				array( 'Classes', '90+' ),
				array( 'Intelligence Systems', '13' ),
				array( 'Superpowers', '48' ),
				array( 'PRO Packs', '200' ),
				array( 'Email Types', '23' ),
				array( 'DB Tables', '19' ),
			);
			foreach ( $plug_stats as $ps ) :
				?>
			<div style="display:flex;justify-content:space-between;padding:4px 0;border-bottom:1px solid rgba(255,255,255,0.03);font-size:11px">
				<span style="color:var(--gt-subtle)"><?php echo esc_html( $ps[0] ); ?></span>
				<span style="color:var(--gt-white);font-weight:700"><?php echo esc_html( $ps[1] ); ?></span>
			</div>
			<?php endforeach; ?>
		</div>
	</div>
</div>

<!-- ═══════════════════════════════════════════════════════════════════════════
	JAVASCRIPT
════════════════════════════════════════════════════════════════════════════ -->
<script>
(function(){
/* Changelog toggle */
window.gtWlToggleChangelog = function() {
	var cl    = document.getElementById('gt-wl-changelog');
	var arrow = document.getElementById('gt-wl-cl-arrow');
	if (!cl) return;
	var open = cl.style.display !== 'none';
	cl.style.display  = open ? 'none' : 'block';
	if (arrow) arrow.textContent = open ? '▸ Show' : '▾ Hide';
};

/* Progress bar animation */
document.addEventListener('DOMContentLoaded', function() {
	document.querySelectorAll('[style*="transition:width"]').forEach(function(el) {
		var w = el.style.width;
		el.style.width = '0%';
		setTimeout(function() { el.style.width = w; }, 200);
	});
});
})();
</script>

<?php require_once __DIR__ . '/../ui-system/wrapper-end.php'; ?>
