<?php
// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals
// phpcs:disable WordPress.Security.NonceVerification
// phpcs:disable WordPress.Security.ValidatedSanitizedInput
// phpcs:disable WordPress.WP.EnqueuedResourceParameters
// phpcs:disable WordPress.DB.PreparedSQL
// phpcs:disable WordPress.DB.PreparedSQLPlaceholders
// phpcs:disable WordPress.DB.DirectDatabaseQuery
// phpcs:disable WordPress.DB.SlowDBQuery
// phpcs:disable PluginCheck.Security.DirectDB
// phpcs:disable PluginCheck.CodeAnalysis
// phpcs:disable WordPressVIPMinimum

/**
 * GT BOGO Engine — Onboarding Intelligence Wizard
 *
 * Five-step intelligent setup wizard for new PRO users.
 * Shows one step at a time with rich auto-detected content.
 *
 * Step 1 — Industry Detection   (19 industry cards, auto-detect)
 * Step 2 — Store Profile        (auto-read from WooCommerce)
 * Step 3 — Recommended Packs    (top 3 for detected industry)
 * Step 4 — Recommended Superpowers (top 5 for theme family)
 * Step 5 — Go Live Checklist    (9 automated checks)
 *
 * @package GT_BOGO_Engine
 * @since   3.23.3
 */
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

class GT_BOGO_Onboarding {
 // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedClassFound

	private static ?self $instance = null;

	public static function instance(): self {
		if ( null === self::$instance ) {
			self::$instance = new self();
		}
		return self::$instance;
	}

	private function __construct() {
		add_action( 'gtbogo_before_dashboard', array( $this, 'render' ) );
		add_action( 'wp_ajax_gtbogo_onboarding_step', array( $this, 'ajax_step' ) );
		add_action( 'wp_ajax_gtbogo_onboarding_done', array( $this, 'ajax_dismiss' ) );
	}

	// ── Industry definitions ──────────────────────────────────────────────────

	private function get_industries(): array {
		return array(
			array(
				'id'       => 'fashion',
				'label'    => 'Fashion & Apparel',
				'icon'     => '👗',
				'keywords' => array( 'fashion', 'apparel', 'clothing', 'shirt', 'dress', 'shoes', 'streetwear' ),
			),
			array(
				'id'       => 'beauty',
				'label'    => 'Beauty & Cosmetics',
				'icon'     => '💄',
				'keywords' => array( 'beauty', 'skincare', 'cosmetics', 'makeup', 'hair', 'fragrance' ),
			),
			array(
				'id'       => 'food',
				'label'    => 'Food & Beverage',
				'icon'     => '🍽',
				'keywords' => array( 'food', 'grocery', 'snack', 'beverage', 'coffee', 'tea', 'bakery' ),
			),
			array(
				'id'       => 'electronics',
				'label'    => 'Electronics & Tech',
				'icon'     => '💻',
				'keywords' => array( 'electronics', 'gadget', 'tech', 'computer', 'phone', 'audio', 'gaming' ),
			),
			array(
				'id'       => 'home',
				'label'    => 'Home & Garden',
				'icon'     => '🏠',
				'keywords' => array( 'home', 'furniture', 'decor', 'kitchen', 'garden', 'bedding' ),
			),
			array(
				'id'       => 'sports',
				'label'    => 'Sports & Fitness',
				'icon'     => '🏋',
				'keywords' => array( 'sport', 'fitness', 'gym', 'yoga', 'activewear', 'athletic' ),
			),
			array(
				'id'       => 'automotive',
				'label'    => 'Automotive',
				'icon'     => '🚗',
				'keywords' => array( 'auto', 'car', 'vehicle', 'motorcycle', 'parts', 'tyres' ),
			),
			array(
				'id'       => 'pets',
				'label'    => 'Pet Supplies',
				'icon'     => '🐾',
				'keywords' => array( 'pet', 'dog', 'cat', 'animal', 'veterinary', 'aquarium' ),
			),
			array(
				'id'       => 'books',
				'label'    => 'Books & Education',
				'icon'     => '📚',
				'keywords' => array( 'book', 'education', 'course', 'learning', 'stationery' ),
			),
			array(
				'id'       => 'health',
				'label'    => 'Health & Wellness',
				'icon'     => '🌿',
				'keywords' => array( 'health', 'wellness', 'supplement', 'vitamin', 'pharmacy', 'natural' ),
			),
			array(
				'id'       => 'jewelry',
				'label'    => 'Jewelry & Accessories',
				'icon'     => '💍',
				'keywords' => array( 'jewelry', 'jewellery', 'rings', 'necklace', 'bracelet', 'watches', 'gold' ),
			),
			array(
				'id'       => 'baby',
				'label'    => 'Baby & Kids',
				'icon'     => '🍼',
				'keywords' => array( 'baby', 'kids', 'children', 'toddler', 'infant', 'nursery' ),
			),
			array(
				'id'       => 'arts',
				'label'    => 'Arts & Crafts',
				'icon'     => '🎨',
				'keywords' => array( 'art', 'craft', 'hobby', 'paint', 'canvas', 'handmade' ),
			),
			array(
				'id'       => 'office',
				'label'    => 'Office & Business',
				'icon'     => '💼',
				'keywords' => array( 'office', 'business', 'supply', 'stationery', 'professional' ),
			),
			array(
				'id'       => 'outdoor',
				'label'    => 'Outdoor & Adventure',
				'icon'     => '⛺',
				'keywords' => array( 'outdoor', 'camping', 'hiking', 'climbing', 'adventure', 'survival' ),
			),
			array(
				'id'       => 'music',
				'label'    => 'Music & Entertainment',
				'icon'     => '🎸',
				'keywords' => array( 'music', 'instrument', 'audio', 'recording', 'entertainment' ),
			),
			array(
				'id'       => 'travel',
				'label'    => 'Travel & Hospitality',
				'icon'     => '✈',
				'keywords' => array( 'travel', 'hotel', 'tourism', 'luggage', 'holiday' ),
			),
			array(
				'id'       => 'b2b',
				'label'    => 'B2B & Wholesale',
				'icon'     => '🏭',
				'keywords' => array( 'wholesale', 'b2b', 'trade', 'bulk', 'distributor', 'manufacturer' ),
			),
			array(
				'id'       => 'general',
				'label'    => 'General / Other',
				'icon'     => '🛒',
				'keywords' => array(),
			),
		);
	}

	// ── Auto-detect industry from WC categories ───────────────────────────────

	private function detect_industry(): string {
		$stored = (string) get_option( 'gtbogo_detected_industry', '' );
		if ( $stored ) {
			return $stored;
		}

		$cats = get_terms(
			array(
				'taxonomy'   => 'product_cat',
				'hide_empty' => true,
				'number'     => 30,
			)
		);
		if ( is_wp_error( $cats ) || empty( $cats ) ) {
			return '';
		}

		$cat_names = implode( ' ', array_map( fn( $c ) => strtolower( $c->name ), $cats ) );
		foreach ( $this->get_industries() as $ind ) {
			foreach ( $ind['keywords'] as $kw ) {
				if ( strpos( $cat_names, $kw ) !== false ) {
					update_option( 'gtbogo_detected_industry', $ind['id'] );
					return $ind['id'];
				}
			}
		}
		return '';
	}

	// ── Go Live checks ────────────────────────────────────────────────────────

	private function get_live_checks(): array {
		$blog_name   = get_bloginfo( 'name' );
		$admin_email = get_option( 'admin_email', '' );
		$logo_id     = get_theme_mod( 'custom_logo', 0 );
		$ssl         = is_ssl() || ( isset( $_SERVER['HTTPS'] ) && 'on' === $_SERVER['HTTPS'] );
		$debug       = defined( 'WP_DEBUG' ) && WP_DEBUG;
		$permalink   = get_option( 'permalink_structure', '' );
		$wc_email    = class_exists( 'WooCommerce' ) ? get_option( 'woocommerce_email_from_address', '' ) : '';
		$is_live_opt = (bool) get_option( 'gtbogo_is_live', false );
		$emails_on   = (bool) get_option( 'gtbogo_emails_enabled', false );

		return array(
			array(
				'label'     => 'Store name set',
				'pass'      => ! empty( $blog_name ) && $blog_name !== 'WordPress',
				'fix'       => admin_url( 'options-general.php' ),
				'fix_label' => 'Settings → General',
			),
			array(
				'label'     => 'Admin email confirmed',
				'pass'      => ! empty( $admin_email ) && strpos( $admin_email, 'example.com' ) === false,
				'fix'       => admin_url( 'options-general.php' ),
				'fix_label' => 'Settings → General',
			),
			array(
				'label'     => 'Store logo uploaded',
				'pass'      => ! empty( $logo_id ),
				'fix'       => admin_url( 'customize.php' ),
				'fix_label' => 'Customize → Site Identity',
			),
			array(
				'label'     => 'HTTPS active',
				'pass'      => $ssl,
				'fix'       => admin_url( 'options-general.php' ),
				'fix_label' => 'Hosting / SSL settings',
			),
			array(
				'label'     => 'Debug mode off',
				'pass'      => ! $debug,
				'fix'       => '',
				'fix_label' => 'Set WP_DEBUG=false in wp-config.php',
			),
			array(
				'label'     => 'Pretty permalinks enabled',
				'pass'      => ! empty( $permalink ),
				'fix'       => admin_url( 'options-permalink.php' ),
				'fix_label' => 'Settings → Permalinks',
			),
			array(
				'label'     => 'WooCommerce email address set',
				'pass'      => ! empty( $wc_email ),
				'fix'       => admin_url( 'admin.php?page=wc-settings&tab=email' ),
				'fix_label' => 'WooCommerce → Settings → Email',
			),
			array(
				'label'     => 'GT BOGO emails enabled',
				'pass'      => $emails_on,
				'fix'       => admin_url( 'admin.php?page=gt-bogo-engine&tab=emails' ),
				'fix_label' => 'GT BOGO → Emails → Enable',
			),
			array(
				'label'     => 'WooCommerce installed and active',
				'pass'      => class_exists( 'WooCommerce' ),
				'fix'       => admin_url( 'plugins.php' ),
				'fix_label' => 'Plugins → Install WooCommerce',
			),
		);
	}

	// ── Step recommendations ──────────────────────────────────────────────────

	private function get_pack_recommendations( string $industry ): array {
		$map = array(
			'fashion'     => array( 'Fashion Loyalty — Buy 3 Get 1 Free', 'Style Bundle — Add Accessories Free', 'New Season — Spend $150 Save $30' ),
			'beauty'      => array( 'Beauty Routine — Buy 2 Get Travel Size Free', 'Skincare Bundle — 3 for 2', 'VIP Beauty — Loyalty Tier Unlock' ),
			'food'        => array( 'Bundle & Save — Meal Kit Deal', 'Loyalty Bites — 5th Order Free Item', 'Flash Feast — 4hr Limited Deal' ),
			'electronics' => array( 'Tech Bundle — Accessory Free with Device', 'Upgrade Deal — Trade-In Discount', 'Protection Pack — Add Warranty Free' ),
			'home'        => array( 'Room Bundle — 3 Pieces Save 20%', 'Home Refresh — Spend $200 Free Delivery', 'Loyalty Home — 5th Purchase Reward' ),
			'sports'      => array( 'Performance Bundle — Kit + Accessory Free', 'Season Launch — First Order 15% Off', 'Athlete Loyalty — 4th Order Reward' ),
			'automotive'  => array( 'Service Bundle — Parts + Labour Deal', 'Fleet Discount — Bulk Purchase Tier', 'Loyalty Garage — 3rd Service Free Check' ),
			'pets'        => array( 'Pet Care Bundle — Food + Treat Free', 'Grooming Deal — 3rd Visit Free', 'Subscription Save — Monthly Auto-Deal' ),
			'health'      => array( 'Wellness Bundle — 3 Supplements Save 25%', 'New Customer — First Order Free Shipping', 'Loyalty Health — 4th Order Reward' ),
			'jewelry'     => array( 'Gifting Bundle — Ring + Box Complimentary', 'Anniversary Deal — Engrave Free on $300+', 'VIP Jewels — Spend $500 Get Gift' ),
			'b2b'         => array( 'Volume Tier — 10+ Units 15% Off', 'Trade Account — First Order Deal', 'Wholesale Bundle — Mixed SKU Discount' ),
			'general'     => array( 'Classic BOGO — Buy 2 Get 1 Free', 'Loyalty Starter — 3rd Order Reward', 'Bundle Saver — Spend $100 Save $15' ),
		);
		return $map[ $industry ] ?? $map['general'];
	}

	private function get_superpower_recommendations( string $theme_family ): array {
		$luxury_safe = array(
			array(
				'id'    => 'savings-calculator',
				'label' => 'Savings Calculator',
				'desc'  => 'Shows the exact value saved — drives high-AOV conviction.',
			),
			array(
				'id'    => 'progress-bar',
				'label' => 'Cart Progress Bar',
				'desc'  => 'Threshold indicator without countdown pressure.',
			),
			array(
				'id'    => 'announcement-bar',
				'label' => 'Announcement Bar',
				'desc'  => 'Elegant top bar — deal messaging without urgency.',
			),
			array(
				'id'    => 'vip-badge',
				'label' => 'VIP Badge',
				'desc'  => 'Signals exclusivity to loyalty-tier customers.',
			),
			array(
				'id'    => 'deal-comparison',
				'label' => 'Deal Comparison',
				'desc'  => 'Side-by-side value display — no pressure tactics.',
			),
		);
		$bold        = array(
			array(
				'id'    => 'countdown-timer',
				'label' => 'Countdown Timer',
				'desc'  => 'Time-limited urgency — highest conversion lift.',
			),
			array(
				'id'    => 'scarcity-bar',
				'label' => 'Scarcity Bar',
				'desc'  => 'Stock pressure — fires on low inventory signal.',
			),
			array(
				'id'    => 'exit-intent',
				'label' => 'Exit Intent',
				'desc'  => 'Last-chance popup before tab close.',
			),
			array(
				'id'    => 'social-proof',
				'label' => 'Social Proof',
				'desc'  => 'Recent purchase activity display.',
			),
			array(
				'id'    => 'abandon-nudge',
				'label' => 'Abandon Nudge',
				'desc'  => 'Cart abandonment email + on-site nudge.',
			),
		);
		$clean       = array(
			array(
				'id'    => 'progress-bar',
				'label' => 'Cart Progress Bar',
				'desc'  => 'Clean threshold indicator — no animations.',
			),
			array(
				'id'    => 'savings-calculator',
				'label' => 'Savings Calculator',
				'desc'  => 'Transparent value display.',
			),
			array(
				'id'    => 'announcement-bar',
				'label' => 'Announcement Bar',
				'desc'  => 'Simple top banner — deal summary.',
			),
			array(
				'id'    => 'deal-share',
				'label' => 'Deal Share',
				'desc'  => 'Social sharing — drives referrals.',
			),
			array(
				'id'    => 'quick-add',
				'label' => 'Quick Add',
				'desc'  => 'One-click add qualifying items to cart.',
			),
		);
		$map         = array(
			'luxury'  => $luxury_safe,
			'bold'    => $bold,
			'clean'   => $clean,
			'ai_wp'   => $bold,
			'ai_site' => $bold,
		);
		return $map[ $theme_family ] ?? $clean;
	}

	private function get_theme_family(): string {
		if ( class_exists( 'GT_BOGO_Superpower_Theme_Intelligence' ) ) {
			$cfg = GT_BOGO_Superpower_Theme_Intelligence::resolve( 'progress-bar' );
			return $cfg['family'] ?? 'clean';
		}
		$theme  = strtolower( get_template() );
		$luxury = array( 'salient', 'uncode', 'the7', 'bridge', 'kalium', 'enfold', 'avada' );
		$bold   = array( 'flatsome', 'divi', 'betheme', 'woodmart', 'xstore' );
		if ( in_array( $theme, $luxury, true ) ) {
			return 'luxury';
		}
		if ( in_array( $theme, $bold, true ) ) {
			return 'bold';
		}
		return 'clean';
	}

	// ── State ─────────────────────────────────────────────────────────────────

	private function get_current_step(): int {
		return max( 1, min( 5, (int) get_option( 'gtbogo_onboarding_current_step', 1 ) ) );
	}

	private function should_show(): bool {
		$screen = get_current_screen();
		if ( ! $screen || strpos( $screen->id, 'gt-bogo' ) === false ) {
			return false;
		}
		if ( get_option( 'gtbogo_onboarding_done', false ) ) {
			return false;
		}
		if ( ! ( function_exists( 'gt_bogo_has_pro' ) && gt_bogo_has_pro() ) ) {
			return false;
		}
		return true;
	}

	// ── Render ────────────────────────────────────────────────────────────────

	public function render(): void {
		if ( ! $this->should_show() ) {
			return;
		}

		$current  = $this->get_current_step();
		$industry = $this->detect_industry();
		$nonce    = wp_create_nonce( 'gtbogo_onboarding_nonce' );
		$steps    = array( 'Industry', 'Store Profile', 'Packs', 'Superpowers', 'Go Live' );
		?>
		<div id="gtbogo-onboarding" style="margin:16px 20px 24px 0;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif;">

		<!-- Progress header -->
		<div style="background:#070C1C;border:1px solid rgba(225,0,0,0.2);border-radius:12px 12px 0 0;padding:20px 28px;display:flex;align-items:center;justify-content:space-between;">
			<div>
				<p style="margin:0 0 4px;font-size:15px;font-weight:700;color:#fff;">GT BOGO Engine — Setup Wizard</p>
				<p style="margin:0;font-size:12px;color:#4a6a8a;">Step <?php echo esc_html( $current ); ?> of 5 — <?php echo esc_html( $steps[ $current - 1 ] ); ?></p>
			</div>
			<div style="display:flex;align-items:center;gap:16px;">
				<!-- Step dots -->
				<div style="display:flex;gap:8px;align-items:center;">
				<?php
				foreach ( $steps as $i => $label ) :
					$n      = $i + 1;
					$done   = $n < $current;
					$active = $n === $current;
					?>
					<div title="Step <?php echo esc_html( $n ); ?>: <?php echo esc_html( $label ); ?>" style="
						width:<?php echo $active ? '28px' : '10px'; ?>;height:10px;border-radius:5px;
						background:<?php echo $done ? '#22c55e' : ( $active ? '#E10000' : '#1a2a40' ); ?>;
						transition:all .3s;"></div>
				<?php endforeach; ?>
				</div>
				<button onclick="gtbogoOnboardingDismiss()" style="background:transparent;border:none;color:#4a6a8a;font-size:18px;cursor:pointer;padding:4px;">&times;</button>
			</div>
		</div>

		<!-- Step content -->
		<div id="gtbogo-step-content" style="background:#050a16;border:1px solid rgba(225,0,0,0.2);border-top:none;border-radius:0 0 12px 12px;padding:28px;">
		<?php
		if ( $current === 1 ) {
			$this->render_step_industry( $industry, $nonce );
		} elseif ( $current === 2 ) {
			$this->render_step_profile( $nonce );
		} elseif ( $current === 3 ) {
			$this->render_step_packs( $industry, $nonce );
		} elseif ( $current === 4 ) {
			$this->render_step_superpowers( $nonce );
		} elseif ( $current === 5 ) {
			$this->render_step_golive( $nonce );
		}
		?>
		</div>
		</div>

		<script>
		function gtbogoOnboardingDismiss(){
			fetch(ajaxurl,{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},
				body:'action=gtbogo_onboarding_done&nonce=<?php echo esc_js( $nonce ); ?>'});
			var el=document.getElementById('gtbogo-onboarding');
			if(el){el.style.opacity='0';el.style.transition='opacity .3s';setTimeout(function(){el.remove();},300);}
		}
		function gtbogoOnboardingNext(data){
			var body='action=gtbogo_onboarding_step&nonce=<?php echo esc_js( $nonce ); ?>';
			if(data) body+='&'+data;
			fetch(ajaxurl,{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},body:body})
				.then(function(){window.location.reload();});
		}
		</script>
		<?php
	}

	// ── Step 1: Industry Detection ────────────────────────────────────────────

	private function render_step_industry( string $detected, string $nonce ): void {
		$industries = $this->get_industries();
		?>
		<h3 style="margin:0 0 6px;color:#fff;font-size:17px;font-weight:700;">What industry is your store?</h3>
		<p style="margin:0 0 20px;color:#4a6a8a;font-size:13px;">
			<?php if ( $detected ) : ?>
			We detected <strong style="color:#22c55e;">
				<?php
				$found = array_filter( $this->get_industries(), fn( $i )=>$i['id'] === $detected );
				echo esc_html( $found ? reset( $found )['label'] : ucfirst( $detected ) );
				?>
			</strong> from your product categories. Confirm or select a different industry.
			<?php else : ?>
			Select your industry to receive the most relevant pack and superpower recommendations.
			<?php endif; ?>
		</p>
		<div id="industry-selection" style="display:grid;grid-template-columns:repeat(auto-fill,minmax(150px,1fr));gap:10px;margin-bottom:24px;">
		<?php
		foreach ( $industries as $ind ) :
			$sel = ( $ind['id'] === $detected );
			?>
			<div onclick="gtbogoSelectIndustry('<?php echo esc_js( $ind['id'] ); ?>')"
				id="ind-<?php echo esc_attr( $ind['id'] ); ?>"
				style="cursor:pointer;padding:14px 12px;border-radius:8px;border:1px solid <?php echo $sel ? '#22c55e' : '#1a2a40'; ?>;
						background:<?php echo $sel ? 'rgba(34,197,94,0.06)' : 'rgba(255,255,255,0.02)'; ?>;
						transition:all .2s;text-align:center;">
				<div style="font-size:20px;margin-bottom:6px;"><?php echo esc_html( $ind['icon'] ); ?></div>
				<div style="font-size:11px;font-weight:600;color:<?php echo $sel ? '#22c55e' : '#8ab0d0'; ?>;line-height:1.3;"><?php echo esc_html( $ind['label'] ); ?></div>
			</div>
		<?php endforeach; ?>
		</div>
		<input type="hidden" id="selected-industry" value="<?php echo esc_attr( $detected ); ?>">
		<div style="display:flex;justify-content:flex-end;">
			<button onclick="gtbogoOnboardingNext('step=industry&industry='+document.getElementById('selected-industry').value)"
				style="padding:10px 28px;background:#E10000;color:#fff;border:none;border-radius:999px;font-size:13px;font-weight:700;cursor:pointer;">
				Confirm Industry &rarr;
			</button>
		</div>
		<script>
		function gtbogoSelectIndustry(id){
			document.querySelectorAll('#industry-selection > div').forEach(function(el){
				el.style.border='1px solid #1a2a40';el.style.background='rgba(255,255,255,0.02)';
				el.querySelector('div:last-child').style.color='#8ab0d0';
			});
			var el=document.getElementById('ind-'+id);
			if(el){
				el.style.border='1px solid #22c55e';el.style.background='rgba(34,197,94,0.06)';
				el.querySelector('div:last-child').style.color='#22c55e';
			}
			document.getElementById('selected-industry').value=id;
		}
		</script>
		<?php
	}

	// ── Step 2: Store Profile ─────────────────────────────────────────────────

	private function render_step_profile( string $nonce ): void {
		global $wpdb;
		$store_name    = get_bloginfo( 'name' );
		$theme         = wp_get_theme()->get( 'Name' );
		$family        = $this->get_theme_family();
		$industry      = (string) get_option( 'gtbogo_detected_industry', 'general' );
		$wc_active     = class_exists( 'WooCommerce' );
        $product_count= $wc_active ? (int)$wpdb->get_var("SELECT COUNT(*) FROM {$wpdb->posts} WHERE post_type='product' AND post_status='publish'") : 0; // phpcs:ignore
		$cat_count     = (int) wp_count_terms(
			array(
				'taxonomy'   => 'product_cat',
				'hide_empty' => true,
			)
		);
		$aov           = 0.0;
		if ( $wc_active ) {
			if ( class_exists( 'GT_BOGO_Order_Query' ) && GT_BOGO_Order_Query::is_hpos() ) {
				$om      = GT_BOGO_Order_Query::meta_table();
				$aov_raw = $wpdb->get_var( "SELECT AVG(meta_value) FROM {$om} WHERE meta_key='_order_total' LIMIT 1000" ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.InterpolatedNotPrepared
			} else {
                $aov_raw = $wpdb->get_var("SELECT AVG(meta_value) FROM {$wpdb->postmeta} WHERE meta_key='_order_total' LIMIT 1000"); // phpcs:ignore
			}
			$aov = $aov_raw ? round( (float) $aov_raw, 2 ) : 0.0;
		}
		$industry_obj   = array_filter( $this->get_industries(), fn( $i )=>$i['id'] === $industry );
		$industry_label = $industry_obj ? reset( $industry_obj )['label'] : ucfirst( $industry );
		$rows           = array(
			array( 'Store Name', $store_name, true ),
			array( 'Active Theme', $theme . ' (' . $family . ')', true ),
			array( 'Detected Industry', $industry_label, true ),
			array( 'Published Products', (string) $product_count, $product_count > 0 ),
			array( 'Product Categories', (string) $cat_count, $cat_count > 0 ),
			array( 'Avg Order Value', $aov > 0 ? '$' . number_format( $aov, 2 ) : 'No orders yet', true ),
			array( 'WooCommerce', $wc_active ? 'Active' : 'Not detected', $wc_active ),
		);
		?>
		<h3 style="margin:0 0 6px;color:#fff;font-size:17px;font-weight:700;">Your store profile</h3>
		<p style="margin:0 0 20px;color:#4a6a8a;font-size:13px;">We have read your store configuration. This data shapes how GT BOGO Engine tunes its recommendations.</p>
		<div style="background:#070C1C;border:1px solid #0f1a30;border-radius:8px;overflow:hidden;margin-bottom:24px;">
		<?php foreach ( $rows as $i => [$label, $value, $ok] ) : ?>
			<div style="display:flex;justify-content:space-between;align-items:center;padding:13px 20px;<?php echo $i > 0 ? 'border-top:1px solid #0f1a30;' : ''; ?>">
				<span style="font-size:13px;color:#4a6a8a;font-weight:600;"><?php echo esc_html( $label ); ?></span>
				<span style="font-size:13px;font-weight:700;color:<?php echo $ok ? '#fff' : '#E10000'; ?>;"><?php echo esc_html( $value ); ?></span>
			</div>
		<?php endforeach; ?>
		</div>
		<div style="display:flex;justify-content:space-between;align-items:center;">
			<p style="margin:0;font-size:12px;color:#2a4a6a;">Theme family detected: <strong style="color:#8ab0d0;"><?php echo esc_html( $family ); ?></strong> — superpower recommendations will be tuned accordingly.</p>
			<button onclick="gtbogoOnboardingNext('step=profile')"
				style="padding:10px 28px;background:#E10000;color:#fff;border:none;border-radius:999px;font-size:13px;font-weight:700;cursor:pointer;flex-shrink:0;margin-left:16px;">
				Looks Good &rarr;
			</button>
		</div>
		<?php
	}

	// ── Step 3: Recommended Packs ─────────────────────────────────────────────

	private function render_step_packs( string $industry, string $nonce ): void {
		$packs          = $this->get_pack_recommendations( $industry ?: 'general' );
		$industry_obj   = array_filter( $this->get_industries(), fn( $i )=>$i['id'] === $industry );
		$industry_label = $industry_obj ? reset( $industry_obj )['label'] : 'your industry';
		$browse_url     = admin_url( 'admin.php?page=gt-bogo-engine&tab=pro-rules' );
		?>
		<h3 style="margin:0 0 6px;color:#fff;font-size:17px;font-weight:700;">Recommended packs for <?php echo esc_html( $industry_label ); ?></h3>
		<p style="margin:0 0 20px;color:#4a6a8a;font-size:13px;">These three packs are the highest-performing starting points for your industry. Each installs a complete set of rules in one click.</p>
		<div style="display:grid;gap:12px;margin-bottom:24px;">
		<?php foreach ( $packs as $i => $pack ) : ?>
			<div style="background:#070C1C;border:1px solid #1a2a40;border-left:3px solid #E10000;border-radius:8px;padding:16px 20px;display:flex;align-items:center;justify-content:space-between;">
				<div>
					<span style="font-size:10px;font-weight:800;letter-spacing:.1em;text-transform:uppercase;color:#E10000;">Pack <?php echo esc_html( $i + 1 ); ?></span>
					<p style="margin:4px 0 0;font-size:14px;font-weight:700;color:#fff;"><?php echo esc_html( $pack ); ?></p>
				</div>
				<a href="<?php echo esc_url( $browse_url ); ?>" style="padding:8px 18px;background:rgba(225,0,0,0.1);border:1px solid rgba(225,0,0,0.3);color:#E10000;text-decoration:none;border-radius:999px;font-size:12px;font-weight:700;flex-shrink:0;">Browse &rarr;</a>
			</div>
		<?php endforeach; ?>
		</div>
		<div style="background:rgba(255,255,255,0.02);border:1px solid #1a2a40;border-radius:8px;padding:14px 18px;margin-bottom:20px;">
			<p style="margin:0;font-size:12px;color:#4a6a8a;line-height:1.6;">200 packs are available across all 19 industries. Import packs from <strong style="color:#8ab0d0;">GT BOGO &rarr; Pro Packs</strong>. Each pack adds rules, triggers, and email sequences — no manual configuration needed.</p>
		</div>
		<div style="display:flex;justify-content:flex-end;">
			<button onclick="gtbogoOnboardingNext('step=packs')"
				style="padding:10px 28px;background:#E10000;color:#fff;border:none;border-radius:999px;font-size:13px;font-weight:700;cursor:pointer;">
				Next: Superpowers &rarr;
			</button>
		</div>
		<?php
	}

	// ── Step 4: Recommended Superpowers ──────────────────────────────────────

	private function render_step_superpowers( string $nonce ): void {
		$family      = $this->get_theme_family();
		$superpowers = $this->get_superpower_recommendations( $family );
		$sp_url      = admin_url( 'admin.php?page=gt-bogo-engine&tab=superpowers' );
		$luxury      = $family === 'luxury';
		?>
		<h3 style="margin:0 0 6px;color:#fff;font-size:17px;font-weight:700;">Recommended superpowers for your theme</h3>
		<p style="margin:0 0 4px;color:#4a6a8a;font-size:13px;">
			Theme family: <strong style="color:#8ab0d0;"><?php echo esc_html( ucfirst( $family ) ); ?></strong>
			<?php
			if ( $luxury ) :
				?>
				— Countdown Timers and Scarcity Bars are disabled for luxury themes to preserve brand positioning.<?php endif; ?>
		</p>
		<?php if ( $luxury ) : ?>
		<div style="background:rgba(59,130,246,0.05);border:1px solid rgba(59,130,246,0.2);border-radius:6px;padding:10px 14px;margin:12px 0 18px;font-size:12px;color:#93c5fd;">
			Luxury Theme Detected — urgency superpowers are automatically suppressed. The five recommended superpowers below are fully brand-safe.
		</div>
		<?php else : ?>
		<p style="margin:0 0 18px;color:#4a6a8a;font-size:13px;">Enable these in GT BOGO &rarr; Superpowers to activate behavioral conversion intelligence.</p>
		<?php endif; ?>
		<div style="display:grid;gap:10px;margin-bottom:24px;">
		<?php foreach ( $superpowers as $i => $sp ) : ?>
			<div style="background:#070C1C;border:1px solid #1a2a40;border-radius:8px;padding:14px 18px;display:flex;align-items:center;gap:16px;">
				<div style="width:32px;height:32px;border-radius:50%;background:rgba(225,0,0,0.1);border:1px solid rgba(225,0,0,0.2);display:flex;align-items:center;justify-content:center;flex-shrink:0;font-size:11px;font-weight:800;color:#E10000;"><?php echo esc_html( $i + 1 ); ?></div>
				<div style="flex:1;">
					<p style="margin:0 0 2px;font-size:13px;font-weight:700;color:#fff;"><?php echo esc_html( $sp['label'] ); ?></p>
					<p style="margin:0;font-size:12px;color:#4a6a8a;"><?php echo esc_html( $sp['desc'] ); ?></p>
				</div>
				<a href="<?php echo esc_url( $sp_url ); ?>" style="padding:6px 14px;background:rgba(255,255,255,0.04);border:1px solid #1a2a40;color:#8ab0d0;text-decoration:none;border-radius:999px;font-size:11px;font-weight:700;flex-shrink:0;">Enable</a>
			</div>
		<?php endforeach; ?>
		</div>
		<div style="display:flex;justify-content:flex-end;">
			<button onclick="gtbogoOnboardingNext('step=superpowers')"
				style="padding:10px 28px;background:#E10000;color:#fff;border:none;border-radius:999px;font-size:13px;font-weight:700;cursor:pointer;">
				Next: Go Live &rarr;
			</button>
		</div>
		<?php
	}

	// ── Step 5: Go Live Checklist ─────────────────────────────────────────────

	private function render_step_golive( string $nonce ): void {
		$checks   = $this->get_live_checks();
		$pass_all = count( array_filter( $checks, fn( $c )=>$c['pass'] ) ) === count( $checks );
		$passed   = count( array_filter( $checks, fn( $c )=>$c['pass'] ) );
		?>
		<h3 style="margin:0 0 6px;color:#fff;font-size:17px;font-weight:700;">Go Live Checklist</h3>
		<p style="margin:0 0 20px;color:#4a6a8a;font-size:13px;"><?php echo esc_html( $passed ); ?> of <?php echo esc_html( count( $checks ) ); ?> checks passed. <?php echo $pass_all ? 'All systems ready — you can go live now.' : 'Fix any failing checks before going live.'; ?></p>
		<div style="background:#070C1C;border:1px solid #0f1a30;border-radius:8px;overflow:hidden;margin-bottom:24px;">
		<?php foreach ( $checks as $i => $check ) : ?>
			<div style="display:flex;align-items:center;justify-content:space-between;padding:13px 18px;<?php echo $i > 0 ? 'border-top:1px solid #0f1a30;' : ''; ?>">
				<div style="display:flex;align-items:center;gap:12px;">
					<div style="width:20px;height:20px;border-radius:50%;display:flex;align-items:center;justify-content:center;flex-shrink:0;
						background:<?php echo $check['pass'] ? 'rgba(34,197,94,0.15)' : 'rgba(225,0,0,0.1)'; ?>;
						border:1px solid <?php echo $check['pass'] ? '#22c55e' : '#E10000'; ?>;">
						<?php if ( $check['pass'] ) : ?>
						<svg width="10" height="10" viewBox="0 0 10 10"><path d="M2 5L4.5 7.5L8.5 3" stroke="#22c55e" stroke-width="1.5" fill="none" stroke-linecap="round"/></svg>
						<?php else : ?>
						<svg width="10" height="10" viewBox="0 0 10 10"><path d="M3 3L7 7M7 3L3 7" stroke="#E10000" stroke-width="1.5" stroke-linecap="round"/></svg>
						<?php endif; ?>
					</div>
					<span style="font-size:13px;font-weight:600;color:<?php echo $check['pass'] ? '#fff' : '#8ab0d0'; ?>;"><?php echo esc_html( $check['label'] ); ?></span>
				</div>
				<?php if ( ! $check['pass'] && $check['fix'] ) : ?>
				<a href="<?php echo esc_url( $check['fix'] ); ?>" style="font-size:11px;color:#E10000;text-decoration:none;font-weight:700;"><?php echo esc_html( $check['fix_label'] ); ?> &rarr;</a>
				<?php elseif ( ! $check['pass'] ) : ?>
				<span style="font-size:11px;color:#4a6a8a;"><?php echo esc_html( $check['fix_label'] ); ?></span>
				<?php endif; ?>
			</div>
		<?php endforeach; ?>
		</div>
		<div style="display:flex;justify-content:space-between;align-items:center;">
			<button onclick="window.location.reload()" style="padding:8px 18px;background:transparent;border:1px solid #1a2a40;color:#4a6a8a;border-radius:999px;font-size:12px;cursor:pointer;">Re-run Checks</button>
			<?php if ( $pass_all ) : ?>
			<button onclick="gtbogoOnboardingNext('step=golive&go_live=1')"
				style="padding:10px 28px;background:#22c55e;color:#000;border:none;border-radius:999px;font-size:13px;font-weight:800;cursor:pointer;">
				Go Live Now
			</button>
			<?php else : ?>
			<button onclick="gtbogoOnboardingNext('step=golive')"
				style="padding:10px 28px;background:#1a2a40;color:#4a6a8a;border:none;border-radius:999px;font-size:13px;font-weight:700;cursor:pointer;">
				Continue Anyway &rarr;
			</button>
			<?php endif; ?>
		</div>
		<?php
	}

	// ── AJAX ──────────────────────────────────────────────────────────────────

	public function ajax_step(): void {
		check_ajax_referer( 'gtbogo_onboarding_nonce', 'nonce' );
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die();
		}

		$step    = sanitize_key( $_POST['step'] ?? '' );
		$current = $this->get_current_step();

		// Save step-specific data
		if ( $step === 'industry' ) {
			$industry = sanitize_key( $_POST['industry'] ?? '' );
			if ( $industry ) {
				update_option( 'gtbogo_detected_industry', $industry );
			}
		}

		if ( $step === 'golive' ) {
			$go_live = isset( $_POST['go_live'] ) && '1' === $_POST['go_live'];
			if ( $go_live ) {
				update_option( 'gtbogo_is_live', true );
				update_option( 'gtbogo_onboarding_done', true );
				wp_send_json_success( array( 'done' => true ) );
				return;
			}
		}

		// Advance step
		$next = min( 5, $current + 1 );
		update_option( 'gtbogo_onboarding_current_step', $next );

		// Mark done when reaching step 5 completion
		if ( $current === 5 ) {
			update_option( 'gtbogo_onboarding_done', true );
		}

		wp_send_json_success( array( 'step' => $next ) );
	}

	public function ajax_dismiss(): void {
		check_ajax_referer( 'gtbogo_onboarding_nonce', 'nonce' );
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die();
		}
		update_option( 'gtbogo_onboarding_done', true );
		wp_send_json_success();
	}
}
