<?php
// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals
// phpcs:disable WordPress.Security.NonceVerification
// phpcs:disable WordPress.DB.PreparedSQL
// 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 — Bundle Intelligence Dashboard
 *
 * Enterprise bundle command centre. Complete bundle analytics suite:
 *
 *   • 8 KPI metric cards — Affinity Pairs, Bundle CR, CR Lift, Bundle AOV,
 *     Bundle Orders, Attachment Rate, Bundle Signal, Last Rebuilt
 *   • Affinity Index Health card with rebuild controls and index metadata
 *   • Top Co-Purchase Pairs table with affinity score bars and strength ratings
 *   • Bundle vs Single-Item Performance comparison (AOV + CR lift side by side)
 *   • Bundle Size Performance analysis (2-pack through 6-pack breakdown)
 *   • Segment Bundle Response matrix — how each customer archetype responds
 *   • Category Bundle Affinity breakdown — which categories appear in bundles
 *   • Recent Bundle Activity log — latest bundle orders detected
 *   • How Bundle Intelligence Works — four-stage pipeline explainer
 *   • Bundle What-If Projections — growth scenario estimates
 *   • Actionable bundle recommendations based on live metrics
 *   • Day range filter (7/14/30/60/90d)
 *   • Interactive accordion sections with slide animation (max-height transition)
 *
 * All data wired to GT_BOGO_Bundle_Intelligence_V2, GT_BOGO_Analytics,
 * GT_BOGO_Signal_Bus, and the gtbogo_analytics table. Zero hardcoded values.
 * Enterprise-grade — suitable for stores with thousands of products.
 *
 * @package GT_BOGO_Engine
 * @since   4.0.1
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}
if ( ! current_user_can( 'manage_woocommerce' ) ) {
	return;
}

// ═══════════════════════════════════════════════════════════════════════════════
// PRO GATE — Bundle Intelligence is a PRO feature
// ═══════════════════════════════════════════════════════════════════════════════
$is_pro = function_exists( 'gt_bogo_has_pro' ) && gt_bogo_has_pro();

if ( ! $is_pro ) {
	require_once __DIR__ . '/../ui-system/wrapper-start.php';
	?>
	<div class="gt-pro-gate">
		<span class="gt-pro-gate-icon">📦</span>
		<h2>Bundle Intelligence Requires PRO</h2>
		<p>AI-assembled product bundles, co-purchase affinity analysis, conversion
			lift tracking, segment bundle response, category affinity breakdown,
			and real-time bundle recommendations are PRO features.</p>
		<div class="gt-flex">
			<a href="<?php echo esc_url( admin_url( 'admin.php?page=gt-bogo-engine&tab=license' ) ); ?>"
				class="gt-btn gt-btn-primary">Activate PRO</a>
			<a href="https://graphictshirts.shop/bogo/" class="gt-btn gt-btn-ghost"
				target="_blank" rel="noopener">Learn More</a>
		</div>
	</div>
	<?php
	require_once __DIR__ . '/../ui-system/wrapper-end.php';
	return;
}

// ═══════════════════════════════════════════════════════════════════════════════
// GLOBALS & CONSTANTS
// ═══════════════════════════════════════════════════════════════════════════════
global $wpdb;
$version = defined( 'GT_BOGO_VERSION' ) ? GT_BOGO_VERSION : '4.0.1';
$days    = max( 7, min( 90, absint( wp_unslash( $_GET['days'] ?? 30 ) ) ) );
$nonce   = wp_create_nonce( 'gtbogo_rebuild_affinity' );

// Intelligence class availability
$has_v2  = class_exists( 'GT_BOGO_Bundle_Intelligence_V2' );
$has_bus = class_exists( 'GT_BOGO_Signal_Bus' );
$has_ana = class_exists( 'GT_BOGO_Analytics' );

// Table references
$analytics_tbl = $wpdb->prefix . 'gtbogo_analytics';
$has_ana_tbl   = (bool) $wpdb->get_var(
	$wpdb->prepare( 'SHOW TABLES LIKE %s', $analytics_tbl )
);

// ═══════════════════════════════════════════════════════════════════════════════
// BUNDLE INTELLIGENCE V2 — Core data
// ═══════════════════════════════════════════════════════════════════════════════
$affinity_pairs = array();
$perf_report    = array();
$last_rebuild   = 'Never';
$total_pairs    = 0;

if ( $has_v2 ) {
	// Fetch performance report from the V2 engine
	if ( method_exists( 'GT_BOGO_Bundle_Intelligence_V2', 'get_performance_report' ) ) {
		$perf_report = GT_BOGO_Bundle_Intelligence_V2::get_performance_report() ?: array();
	}

	// Index metadata from options
	$last_rebuild = get_option( 'gtbogo_affinity_last_rebuild', 'Never' );
	$total_pairs  = (int) get_option( 'gtbogo_affinity_total_pairs', 0 );
}

// ── Handle manual index rebuild ───────────────────────────────────────────────
$rebuild_message = '';
if ( isset( $_POST['rebuild_affinity'] ) && check_admin_referer( 'gtbogo_rebuild_affinity' ) ) {
	if ( $has_v2 && method_exists( 'GT_BOGO_Bundle_Intelligence_V2', 'rebuild_affinity_index' ) ) {
		GT_BOGO_Bundle_Intelligence_V2::rebuild_affinity_index();
		$rebuild_message = 'Affinity index rebuilt successfully. New pairs will appear as orders are processed overnight.';
		$last_rebuild    = current_time( 'mysql', true );
		$total_pairs     = (int) get_option( 'gtbogo_affinity_total_pairs', 0 );
	}
}

// ── Extract performance metrics from report ────────────────────────────────────
$bundle_cr     = (float) ( $perf_report['bundle_cr'] ?? 0 );
$single_cr     = (float) ( $perf_report['single_cr'] ?? 0 );
$cr_lift       = $single_cr > 0
	? round( ( ( $bundle_cr - $single_cr ) / $single_cr ) * 100, 1 )
	: 0;
$bundle_aov    = (float) ( $perf_report['bundle_aov'] ?? 0 );
$single_aov    = (float) ( $perf_report['single_aov'] ?? 0 );
$aov_lift      = $single_aov > 0
	? round( ( ( $bundle_aov - $single_aov ) / $single_aov ) * 100, 1 )
	: 0;
$bundle_orders = (int) ( $perf_report['bundle_orders'] ?? 0 );
$attach_rate   = (float) ( $perf_report['attach_rate'] ?? 0 );
$bundle_rev    = (float) ( $perf_report['bundle_revenue'] ?? 0 );
$avg_items     = (float) ( $perf_report['avg_items'] ?? 0 );

// ── Top affinity pairs ───────────────────────────────────────────────────────
if ( $has_v2 && method_exists( 'GT_BOGO_Bundle_Intelligence_V2', 'get_top_pairs' ) ) {
	$affinity_pairs = GT_BOGO_Bundle_Intelligence_V2::get_top_pairs( 20 ) ?: array();
}

// ═══════════════════════════════════════════════════════════════════════════════
// SIGNAL BUS — Bundle completion proximity
// ═══════════════════════════════════════════════════════════════════════════════
$bundle_signal = 0.0;
if ( $has_bus ) {
	$bundle_signal = (float) GT_BOGO_Signal_Bus::get( 'bundle_completion_proximity', 0.0 );
}

// Signal status helper
$signal_status = $bundle_signal >= 3.5 ? 'Hot' : ( $bundle_signal >= 2.0 ? 'Warm' : 'Cold' );
$signal_color  = $bundle_signal >= 3.5 ? '#22c55e' : ( $bundle_signal >= 2.0 ? '#f59e0b' : '#64748b' );

// ═══════════════════════════════════════════════════════════════════════════════
// BUNDLE SIZE PERFORMANCE — Orders and AOV by number of items per bundle
// ═══════════════════════════════════════════════════════════════════════════════
$size_perf = array();
if ( $has_ana_tbl ) {
	$size_raw = $wpdb->get_results(
		$wpdb->prepare(
			"SELECT
            JSON_EXTRACT(meta, '$.bundle_size') AS sz,
            COUNT(DISTINCT order_id)            AS orders,
            COALESCE(AVG(order_total), 0)       AS aov,
            COALESCE(SUM(order_total), 0)       AS revenue
         FROM {$analytics_tbl}
         WHERE date_created >= %s
           AND JSON_EXTRACT(meta, '$.bundle_size') IS NOT NULL
         GROUP BY JSON_EXTRACT(meta, '$.bundle_size')
         ORDER BY orders DESC",
			gmdate( 'Y-m-d H:i:s', strtotime( "-{$days} days" ) )
		) ?: array()
	);

	foreach ( $size_raw as $row ) {
		$sz = (int) $row->sz;
		if ( $sz >= 2 && $sz <= 6 ) {
			$size_perf[ $sz ] = array(
				'orders'  => (int) $row->orders,
				'aov'     => round( (float) $row->aov, 2 ),
				'revenue' => (float) $row->revenue,
			);
		}
	}
}

// ═══════════════════════════════════════════════════════════════════════════════
// SEGMENT BUNDLE RESPONSE — How each customer archetype responds to bundles
// ═══════════════════════════════════════════════════════════════════════════════
$segment_bundle = array();
$segments_list  = array(
	'new_visitor'        => 'New Visitor',
	'returning'          => 'Returning',
	'vip_active'         => 'VIP',
	'at_risk'            => 'At Risk',
	'gold_returning'     => 'Gold',
	'price_sensitive'    => 'Price Sensitive',
	'high_intent'        => 'High Intent',
	'platinum_returning' => 'Platinum',
);

if ( $has_ana_tbl ) {
	foreach ( $segments_list as $seg_key => $seg_label ) {
		$seg_data = $wpdb->get_row(
			$wpdb->prepare(
				"SELECT
                COUNT(DISTINCT order_id)      AS orders,
                COALESCE(AVG(order_total), 0) AS aov
             FROM {$analytics_tbl}
             WHERE date_created >= %s
               AND JSON_EXTRACT(meta, '$.archetype') = %s
               AND JSON_EXTRACT(meta, '$.bundle_size') IS NOT NULL",
				gmdate( 'Y-m-d H:i:s', strtotime( "-{$days} days" ) ),
				$seg_key
			)
		);

		if ( $seg_data && (int) $seg_data->orders > 0 ) {
			$segment_bundle[ $seg_key ] = array(
				'label'  => $seg_label,
				'orders' => (int) $seg_data->orders,
				'aov'    => round( (float) $seg_data->aov, 2 ),
			);
		}
	}
}

// ═══════════════════════════════════════════════════════════════════════════════
// CATEGORY BUNDLE AFFINITY — Which categories appear most in bundles
// ═══════════════════════════════════════════════════════════════════════════════
$cat_bundle = array();
if ( $has_ana_tbl ) {
	$cat_raw = $wpdb->get_results(
		$wpdb->prepare(
			"SELECT
            JSON_EXTRACT(meta, '$.category') AS cat,
            COUNT(DISTINCT order_id)          AS orders,
            COALESCE(AVG(order_total), 0)     AS aov
         FROM {$analytics_tbl}
         WHERE date_created >= %s
           AND JSON_EXTRACT(meta, '$.category') IS NOT NULL
           AND JSON_EXTRACT(meta, '$.bundle_size') IS NOT NULL
         GROUP BY JSON_EXTRACT(meta, '$.category')
         ORDER BY orders DESC
         LIMIT 12",
			gmdate( 'Y-m-d H:i:s', strtotime( "-{$days} days" ) )
		) ?: array()
	);

	foreach ( $cat_raw as $row ) {
		$cat_name = trim( (string) $row->cat, '"' );
		if ( ! empty( $cat_name ) ) {
			$cat_bundle[] = array(
				'name'   => $cat_name,
				'orders' => (int) $row->orders,
				'aov'    => round( (float) $row->aov, 2 ),
			);
		}
	}
}

// ═══════════════════════════════════════════════════════════════════════════════
// RECENT BUNDLE ACTIVITY — Latest bundle orders for verification
// ═══════════════════════════════════════════════════════════════════════════════
$recent_bundles = array();
if ( $has_ana_tbl ) {
	$recent_bundles = $wpdb->get_results(
		$wpdb->prepare(
			"SELECT
            a.order_id,
            a.order_total,
            a.date_created,
            JSON_EXTRACT(a.meta, '$.bundle_size') AS sz,
            JSON_EXTRACT(a.meta, '$.category')    AS cat
         FROM {$analytics_tbl} a
         WHERE a.date_created >= %s
           AND JSON_EXTRACT(a.meta, '$.bundle_size') IS NOT NULL
         ORDER BY a.date_created DESC
         LIMIT 15",
			gmdate( 'Y-m-d H:i:s', strtotime( "-{$days} days" ) )
		) ?: array()
	);
}

// ═══════════════════════════════════════════════════════════════════════════════
// WHAT-IF PROJECTIONS — Bundle growth scenarios
// ═══════════════════════════════════════════════════════════════════════════════
$whatif_bundle = array();

if ( $bundle_orders > 0 && $bundle_aov > 0 ) {
	// Scenario 1: Attachment rate improves by 10 percentage points
	$whatif_bundle[] = array(
		'icon'   => '📈',
		'label'  => 'Attachment rate +10% ('
					. round( $attach_rate * 100, 1 ) . '% → '
					. round( ( $attach_rate + 0.1 ) * 100, 1 ) . '%)',
		'impact' => round( $bundle_orders * 0.1 * $bundle_aov, 0 ),
		'color'  => '#22c55e',
	);

	// Scenario 2: Bundle order volume doubles
	$whatif_bundle[] = array(
		'icon'   => '🛒',
		'label'  => 'Bundle orders doubled ('
					. number_format( $bundle_orders ) . ' → '
					. number_format( $bundle_orders * 2 ) . ')',
		'impact' => round( $bundle_orders * $bundle_aov, 0 ),
		'color'  => '#3b82f6',
	);

	// Scenario 3: Bundle AOV increases by 10%
	$whatif_bundle[] = array(
		'icon'   => '💵',
		'label'  => 'Bundle AOV +10% ($'
					. number_format( $bundle_aov, 2 ) . ' → $'
					. number_format( $bundle_aov * 1.1, 2 ) . ')',
		'impact' => round( $bundle_orders * $bundle_aov * 0.1, 0 ),
		'color'  => '#a78bfa',
	);

	// Scenario 4: Average items per bundle increases by 1
	$whatif_bundle[] = array(
		'icon'   => '📦',
		'label'  => 'Avg items +1 ('
					. number_format( $avg_items, 1 ) . ' → '
					. number_format( $avg_items + 1, 1 ) . ')',
		'impact' => round( $bundle_orders * ( $bundle_aov / max( 1, $avg_items ) ), 0 ),
		'color'  => '#f59e0b',
	);
}

// ═══════════════════════════════════════════════════════════════════════════════
// RECOMMENDATIONS — Actionable intelligence
// ═══════════════════════════════════════════════════════════════════════════════
$recommendations = array();

if ( $cr_lift > 10 ) {
	$recommendations[] = array(
		'type' => 'success',
		'icon' => '✓',
		'text' => "Bundles drive a <strong>+{$cr_lift}%</strong> conversion lift vs single items. "
				. 'Your bundle strategy is highly effective — consider expanding bundle offers across '
				. 'more product categories and promoting them prominently on cart and checkout pages.',
	);
} elseif ( $cr_lift > 0 ) {
	$recommendations[] = array(
		'type' => 'success',
		'icon' => '✓',
		'text' => "Bundle conversion lift is <strong>+{$cr_lift}%</strong>. Bundles are outperforming "
				. 'single items — continue promoting bundle deals to maximise this advantage.',
	);
}

if ( $attach_rate < 0.3 && $bundle_orders > 10 ) {
	$recommendations[] = array(
		'type' => 'info',
		'icon' => 'ℹ',
		'text' => 'Attachment rate is <strong>' . round( $attach_rate * 100, 1 )
				. '%</strong>. Consider making bundle offers more visible — add bundle callouts on '
				. 'product pages, in the cart sidebar, and during checkout.',
	);
}

if ( $aov_lift > 20 ) {
	$recommendations[] = array(
		'type' => 'success',
		'icon' => '✓',
		'text' => "Bundle AOV is <strong>+{$aov_lift}%</strong> above single-item AOV — bundles "
				. 'are significantly increasing basket size. This is a strong signal to invest in more '
				. 'bundle configurations and upsell opportunities.',
	);
}

if ( $total_pairs < 50 && $has_v2 ) {
	$recommendations[] = array(
		'type' => 'info',
		'icon' => 'ℹ',
		'text' => "Only <strong>{$total_pairs}</strong> affinity pairs detected. More completed "
				. 'orders = better co-purchase detection. Rebuild the index after a busy sales period '
				. 'for richer, more diverse bundle recommendations.',
	);
}

if ( $bundle_orders === 0 ) {
	$recommendations[] = array(
		'type' => 'info',
		'icon' => 'ℹ',
		'text' => 'No bundle orders detected yet. Activate the <strong>Bundle Configurator</strong> '
				. 'superpower to start generating bundle offers. Bundle data will populate as customers '
				. 'engage with and purchase bundle deals.',
	);
}

if ( empty( $recommendations ) ) {
	$recommendations[] = array(
		'type' => 'info',
		'icon' => 'ℹ',
		'text' => 'Bundle data is building. Intelligent recommendations will appear as customers '
				. 'interact with bundle offers and the analytics engine accumulates performance data.',
	);
}

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

<div class="gt-page-header gt-animate-in">
	<div>
		<h1 class="gt-page-title">📦 Bundle Intelligence</h1>
		<p class="gt-page-subtitle">AI-assembled product bundles, co-purchase affinity patterns, conversion lift analysis, segment response, category breakdown, size optimisation, recent activity, and what-if projections — all wired to live store data from the Bundle Intelligence V2 engine.</p>
	</div>
	<div style="display:flex;gap:8px;align-items:center">
		<span class="gt-badge <?php echo $has_v2 ? 'gt-badge-active' : 'gt-badge-free'; ?>">
			<?php echo $has_v2 ? '● V2 Active' : '○ Unavailable'; ?>
		</span>
		<span class="gt-badge gt-badge-pro">PRO v<?php echo esc_html( $version ); ?></span>
	</div>
</div>

<?php if ( $rebuild_message ) : ?>
<div class="gt-notice gt-notice-success gt-animate-in">
	✓ <?php echo esc_html( $rebuild_message ); ?>
</div>
<?php endif; ?>

<!-- ═══ DAY FILTER BAR ═══ -->
<div style="display:flex;align-items:center;gap:8px;margin-bottom:20px;flex-wrap:wrap" class="gt-animate-in">
	<span style="font-size:12px;color:#64748b;font-weight:600">Period:</span>
	<?php foreach ( array( 7, 14, 30, 60, 90 ) as $d ) : ?>
	<a href="<?php echo esc_url( add_query_arg( array( 'days' => $d ) ) ); ?>"
		class="gt-btn gt-btn-xs <?php echo $d === $days ? 'gt-btn-primary' : 'gt-btn-ghost'; ?>">
		<?php echo esc_html( $d ); ?>d
	</a>
	<?php endforeach; ?>
	<span style="margin-left:auto;font-size:11px;color:#475569">
		<?php echo esc_html( number_format( $total_pairs ) ); ?> pairs ·
		<?php echo esc_html( number_format( $bundle_orders ) ); ?> bundle orders ·
		<?php echo esc_html( round( $attach_rate * 100, 1 ) ); ?>% attachment rate
	</span>
</div>

<!-- ═══ 8 KPI METRICS ═══ -->
<div class="gt-metrics gt-animate-in" style="margin-bottom:24px">
	<!-- KPI 1: Affinity Pairs -->
	<div class="gt-metric" style="--gt-metric-c:#E10000">
		<span class="gt-metric-icon">🔗</span>
		<div class="gt-metric-label">Affinity Pairs</div>
		<div class="gt-metric-value"><?php echo esc_html( number_format( $total_pairs ) ); ?></div>
		<div class="gt-metric-trend">Product co-purchase relationships mapped</div>
	</div>
	<!-- KPI 2: Bundle Conversion Rate -->
	<div class="gt-metric" style="--gt-metric-c:#22c55e">
		<span class="gt-metric-icon">📈</span>
		<div class="gt-metric-label">Bundle Conversion Rate</div>
		<div class="gt-metric-value"><?php echo esc_html( number_format( $bundle_cr, 1 ) ); ?>%</div>
		<div class="gt-metric-trend">Vs <?php echo esc_html( number_format( $single_cr, 1 ) ); ?>% single-item CR</div>
	</div>
	<!-- KPI 3: CR Lift -->
	<div class="gt-metric" style="--gt-metric-c:#3b82f6">
		<span class="gt-metric-icon">🔼</span>
		<div class="gt-metric-label">Conversion Rate Lift</div>
		<div class="gt-metric-value" style="color:<?php echo $cr_lift >= 0 ? '#22c55e' : '#ef4444'; ?>">
			<?php echo esc_html( ( $cr_lift >= 0 ? '+' : '' ) . $cr_lift ); ?>%
		</div>
		<div class="gt-metric-trend">Bundles vs single product purchases</div>
	</div>
	<!-- KPI 4: Bundle AOV -->
	<div class="gt-metric" style="--gt-metric-c:#06b6d4">
		<span class="gt-metric-icon">💵</span>
		<div class="gt-metric-label">Bundle Avg Order Value</div>
		<div class="gt-metric-value">$<?php echo esc_html( number_format( $bundle_aov, 2 ) ); ?></div>
		<div class="gt-metric-trend">
			<?php echo $aov_lift >= 0 ? '+' : ''; ?><?php echo esc_html( $aov_lift ); ?>%
			vs single ($<?php echo esc_html( number_format( $single_aov, 2 ) ); ?>)
		</div>
	</div>
	<!-- KPI 5: Bundle Orders -->
	<div class="gt-metric" style="--gt-metric-c:#f59e0b">
		<span class="gt-metric-icon">🛒</span>
		<div class="gt-metric-label">Bundle Orders (<?php echo esc_html( $days ); ?>d)</div>
		<div class="gt-metric-value"><?php echo esc_html( number_format( $bundle_orders ) ); ?></div>
		<div class="gt-metric-trend">$<?php echo esc_html( number_format( $bundle_rev, 0 ) ); ?> total bundle revenue</div>
	</div>
	<!-- KPI 6: Attachment Rate -->
	<div class="gt-metric" style="--gt-metric-c:#a78bfa">
		<span class="gt-metric-icon">🧲</span>
		<div class="gt-metric-label">Attachment Rate</div>
		<div class="gt-metric-value"><?php echo esc_html( number_format( $attach_rate * 100, 1 ) ); ?>%</div>
		<div class="gt-metric-trend">Avg <?php echo esc_html( number_format( $avg_items, 1 ) ); ?> items per bundle</div>
	</div>
	<!-- KPI 7: Bundle Signal -->
	<div class="gt-metric" style="--gt-metric-c:#f97316">
		<span class="gt-metric-icon">📡</span>
		<div class="gt-metric-label">Bundle Signal</div>
		<div class="gt-metric-value" style="color:<?php echo esc_attr( $signal_color ); ?>">
			<?php echo esc_html( number_format( $bundle_signal, 1 ) ); ?>/5
		</div>
		<div class="gt-metric-trend"><?php echo esc_html( $signal_status ); ?> — real-time bundle proximity</div>
	</div>
	<!-- KPI 8: Last Rebuilt -->
	<div class="gt-metric" style="--gt-metric-c:#10b981">
		<span class="gt-metric-icon">🕐</span>
		<div class="gt-metric-label">Last Index Rebuild</div>
		<div class="gt-metric-value" style="font-size:15px">
			<?php
			echo esc_html(
				$last_rebuild === 'Never'
				? 'Never'
				: human_time_diff( strtotime( $last_rebuild ), time() ) . ' ago'
			);
			?>
		</div>
		<div class="gt-metric-trend">Affinity index freshness</div>
	</div>
</div>

<!-- ═══ AFFINITY INDEX HEALTH ═══ -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
	<div class="gt-card-header rev-accordion-header open" onclick="gtRevToggle(this)">
		<h2 class="gt-card-title">🏥 Affinity Index Health</h2>
		<span class="gt-target-chevron" style="color:#64748b;font-size:10px;transition:transform .2s">▲</span>
	</div>
	<div class="rev-accordion-body open">
		<p style="font-size:13px;color:#64748b;margin:0 0 16px">
			The affinity index is the engine that powers all bundle recommendations. It maps which
			products are most frequently purchased together based on real order data from your store.
			A healthy, frequently rebuilt index means more relevant and higher-converting bundle
			suggestions for your customers.
		</p>
		<div style="display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:16px">
			<div style="display:flex;gap:32px;flex-wrap:wrap">
				<div>
					<div class="gt-card-label">Last Rebuilt</div>
					<div style="font-size:15px;font-weight:600;color:#fff">
						<?php
						echo esc_html(
							$last_rebuild === 'Never'
							? 'Never'
							: human_time_diff( strtotime( $last_rebuild ), time() ) . ' ago'
						);
						?>
					</div>
				</div>
				<div>
					<div class="gt-card-label">Total Pairs</div>
					<div style="font-size:15px;font-weight:600;color:#fff">
						<?php echo esc_html( number_format( $total_pairs ) ); ?>
					</div>
				</div>
				<div>
					<div class="gt-card-label">Engine Version</div>
					<div style="font-size:15px;font-weight:600;color:<?php echo $has_v2 ? '#22c55e' : '#64748b'; ?>">
						<?php echo $has_v2 ? 'V2 (Wave 5)' : 'Unavailable'; ?>
					</div>
				</div>
				<div>
					<div class="gt-card-label">Rebuild Schedule</div>
					<div style="font-size:15px;font-weight:600;color:#fff">Daily (automatic)</div>
				</div>
			</div>
			<?php if ( $has_v2 && method_exists( 'GT_BOGO_Bundle_Intelligence_V2', 'rebuild_affinity_index' ) ) : ?>
			<form method="post" style="display:inline">
				<?php wp_nonce_field( 'gtbogo_rebuild_affinity' ); ?>
				<button name="rebuild_affinity" class="gt-btn gt-btn-primary gt-btn-sm" type="submit">
					↺ Rebuild Index Now
				</button>
			</form>
			<?php endif; ?>
		</div>
	</div>
</div>

<!-- ═══ TOP CO-PURCHASE PAIRS ═══ -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
	<div class="gt-card-header rev-accordion-header open" onclick="gtRevToggle(this)">
		<h2 class="gt-card-title">🔗 Top Co-Purchase Pairs</h2>
		<span class="gt-target-chevron" style="color:#64748b;font-size:10px;transition:transform .2s">▲</span>
	</div>
	<div class="rev-accordion-body open">
		<p style="font-size:13px;color:#64748b;margin:0 0 16px">
			Products most frequently purchased together across all orders. Higher affinity scores
			indicate stronger co-purchase relationships. Use these pairs to create targeted bundle
			offers featuring products your customers are already buying together.
		</p>
		<?php
		if ( ! empty( $affinity_pairs ) ) :
			$max_score = max( array_column( $affinity_pairs, 'score' ) ?: array( 1 ) );
			?>
		<table class="gt-table">
			<thead>
				<tr>
					<th>#</th>
					<th>Product A</th>
					<th>Product B</th>
					<th>Affinity Score</th>
					<th>Co-Purchases</th>
					<th>Strength</th>
				</tr>
			</thead>
			<tbody>
			<?php
			foreach ( $affinity_pairs as $i => $pair ) :
				$score_pct = $max_score > 0
					? round( (float) $pair['score'] / $max_score * 100 )
					: 0;
				$name_a    = ! empty( $pair['product_a_name'] )
					? $pair['product_a_name']
					: ( is_numeric( $pair['product_a'] ?? '' )
						? get_the_title( $pair['product_a'] )
						: 'Product ' . ( $pair['product_a'] ?? '?' ) );
				$name_b    = ! empty( $pair['product_b_name'] )
					? $pair['product_b_name']
					: ( is_numeric( $pair['product_b'] ?? '' )
						? get_the_title( $pair['product_b'] )
						: 'Product ' . ( $pair['product_b'] ?? '?' ) );
				$sv        = (float) ( $pair['score'] ?? 0 );
				if ( $sv >= 0.7 ) {
					$strength = 'Very Strong';
					$st_color = '#22c55e';
				} elseif ( $sv >= 0.4 ) {
					$strength = 'Strong';
					$st_color = '#3b82f6';
				} elseif ( $sv >= 0.2 ) {
					$strength = 'Moderate';
					$st_color = '#f59e0b';
				} else {
					$strength = 'Developing';
					$st_color = '#64748b';
				}
				?>
				<tr>
					<td style="color:#475569;font-size:12px"><?php echo esc_html( $i + 1 ); ?></td>
					<td style="font-weight:600;max-width:200px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap"
						title="<?php echo esc_attr( $name_a ); ?>">
						<?php echo esc_html( $name_a ?: '—' ); ?>
					</td>
					<td style="color:#94a3b8;max-width:200px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap"
						title="<?php echo esc_attr( $name_b ); ?>">
						<?php echo esc_html( $name_b ?: '—' ); ?>
					</td>
					<td>
						<span style="font-weight:600;color:#fff;font-family:'DM Mono',monospace">
							<?php echo esc_html( number_format( $sv, 3 ) ); ?>
						</span>
						<div style="display:inline-block;height:5px;border-radius:3px;background:#E10000;vertical-align:middle;margin-left:8px;width:<?php echo esc_attr( $score_pct ); ?>px;max-width:80px"></div>
					</td>
					<td style="color:#64748b;font-family:'DM Mono',monospace">
						<?php echo esc_html( number_format( (int) ( $pair['count'] ?? 0 ) ) ); ?>
					</td>
					<td style="font-size:11px;color:<?php echo esc_attr( $st_color ); ?>;font-weight:600">
						<?php echo esc_html( $strength ); ?>
					</td>
				</tr>
			<?php endforeach; ?>
			</tbody>
		</table>
		<?php else : ?>
		<div style="text-align:center;padding:48px 20px;color:#64748b;font-size:14px">
			<div style="font-size:36px;margin-bottom:12px">🔗</div>
			<div>No affinity pairs detected yet. The index builds automatically as orders complete.</div>
			<div style="font-size:12px;margin-top:8px">
				Click <strong>"Rebuild Index Now"</strong> above to force a rebuild, or wait for the
				daily automatic schedule. More completed orders = richer affinity data.
			</div>
		</div>
		<?php endif; ?>
	</div>
</div>

<!-- ═══ BUNDLE VS SINGLE-ITEM PERFORMANCE ═══ -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
	<div class="gt-card-header rev-accordion-header" onclick="gtRevToggle(this)">
		<h2 class="gt-card-title">📊 Bundle vs Single-Item Performance</h2>
		<span class="gt-target-chevron" style="color:#64748b;font-size:10px;transition:transform .2s">▼</span>
	</div>
	<div class="rev-accordion-body">
		<p style="font-size:13px;color:#64748b;margin:0 0 16px">
			Direct comparison of bundle deal performance against single-item purchases. A positive
			lift in both conversion rate and average order value means bundles are delivering
			measurable value — increasing both purchase likelihood and basket size.
		</p>
		<div style="display:grid;grid-template-columns:repeat(3,1fr);gap:16px;margin-bottom:16px">
			<div style="background:#0d1f3c;border-radius:10px;padding:24px;text-align:center;border:1px solid rgba(34,197,94,0.3);transition:transform .2s"
				onmouseover="this.style.transform='translateY(-2px)'"
				onmouseout="this.style.transform='translateY(0)'">
				<div class="gt-card-label">Bundle AOV</div>
				<div style="font-size:32px;font-weight:800;color:#22c55e;margin-top:4px">
					$<?php echo esc_html( number_format( $bundle_aov, 2 ) ); ?>
				</div>
				<div style="font-size:12px;color:#64748b;margin-top:4px">
					<?php echo $aov_lift >= 0 ? '+' : ''; ?><?php echo esc_html( $aov_lift ); ?>% vs single
				</div>
			</div>
			<div style="background:#0d1f3c;border-radius:10px;padding:24px;text-align:center;border:1px solid rgba(59,130,246,0.2);transition:transform .2s"
				onmouseover="this.style.transform='translateY(-2px)'"
				onmouseout="this.style.transform='translateY(0)'">
				<div class="gt-card-label">Single-Item AOV</div>
				<div style="font-size:32px;font-weight:800;color:#3b82f6;margin-top:4px">
					$<?php echo esc_html( number_format( $single_aov, 2 ) ); ?>
				</div>
				<div style="font-size:12px;color:#64748b;margin-top:4px">Baseline comparison</div>
			</div>
			<div style="background:#0d1f3c;border-radius:10px;padding:24px;text-align:center;border:1px solid <?php echo $cr_lift >= 0 ? 'rgba(34,197,94,0.3)' : 'rgba(239,68,68,0.2)'; ?>;transition:transform .2s"
				onmouseover="this.style.transform='translateY(-2px)'"
				onmouseout="this.style.transform='translateY(0)'">
				<div class="gt-card-label">Conversion Rate Lift</div>
				<div style="font-size:32px;font-weight:800;color:<?php echo $cr_lift >= 0 ? '#22c55e' : '#ef4444'; ?>;margin-top:4px">
					<?php echo esc_html( ( $cr_lift >= 0 ? '+' : '' ) . $cr_lift ); ?>%
				</div>
				<div style="font-size:12px;color:#64748b;margin-top:4px">
					<?php echo esc_html( number_format( $bundle_cr, 1 ) ); ?>% vs
					<?php echo esc_html( number_format( $single_cr, 1 ) ); ?>%
				</div>
			</div>
		</div>
		<?php if ( $cr_lift > 0 || $aov_lift > 0 ) : ?>
		<div style="text-align:center;padding:16px;background:rgba(34,197,94,0.06);border-radius:10px;font-size:14px;font-weight:600;color:#86efac">
			✅ Bundles are outperforming single items — <?php echo esc_html( number_format( $bundle_orders ) ); ?>
			bundle orders generating $<?php echo esc_html( number_format( $bundle_rev, 0 ) ); ?> in revenue.
		</div>
		<?php endif; ?>
	</div>
</div>

<!-- ═══ BUNDLE SIZE PERFORMANCE ═══ -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
	<div class="gt-card-header rev-accordion-header" onclick="gtRevToggle(this)">
		<h2 class="gt-card-title">📦 Bundle Size Performance</h2>
		<span class="gt-target-chevron" style="color:#64748b;font-size:10px;transition:transform .2s">▼</span>
	</div>
	<div class="rev-accordion-body">
		<p style="font-size:13px;color:#64748b;margin:0 0 16px">
			Performance breakdown by number of items in the bundle. Larger bundles typically have
			higher average order values but lower order volume. Find your optimal bundle size by
			balancing order count and AOV for maximum total revenue.
		</p>
		<?php
		if ( ! empty( $size_perf ) ) :
			$size_max_orders = max( array_column( $size_perf, 'orders' ) ?: array( 1 ) );
			?>
		<div style="display:flex;gap:12px;flex-wrap:wrap">
			<?php
			foreach ( $size_perf as $sz => $data ) :
				$bar_h    = round( $data['orders'] / $size_max_orders * 100 ) + 10;
				$sz_color = $sz <= 2 ? '#3b82f6'
							: ( $sz <= 3 ? '#22c55e'
							: ( $sz <= 4 ? '#f59e0b' : '#a78bfa' ) );
				?>
			<div style="flex:1;min-width:100px;text-align:center;background:#0d1f3c;border-radius:10px;padding:20px;border:1px solid rgba(255,255,255,0.04);transition:transform .2s"
				onmouseover="this.style.transform='translateY(-2px)'"
				onmouseout="this.style.transform='translateY(0)'">
				<div style="font-size:20px;font-weight:800;color:<?php echo esc_attr( $sz_color ); ?>">
					<?php echo esc_html( $sz ); ?>-Pack
				</div>
				<div style="background:<?php echo esc_attr( $sz_color ); ?>;height:<?php echo esc_attr( $bar_h ); ?>px;border-radius:4px 4px 0 0;margin:12px 0 8px;transition:height .4s ease"></div>
				<div style="font-size:14px;font-weight:700;color:#fff">
					<?php echo esc_html( number_format( $data['orders'] ) ); ?>
				</div>
				<div style="font-size:11px;color:#64748b;margin-top:2px">orders</div>
				<div style="font-size:13px;font-weight:600;color:#22c55e;margin-top:4px">
					$<?php echo esc_html( number_format( $data['aov'], 2 ) ); ?>
				</div>
				<div style="font-size:10px;color:#475569">avg order</div>
				<div style="font-size:10px;color:#475569;margin-top:2px">
					$<?php echo esc_html( number_format( $data['revenue'], 0 ) ); ?> total
				</div>
			</div>
			<?php endforeach; ?>
		</div>
		<?php else : ?>
		<div style="text-align:center;padding:48px 20px;color:#64748b;font-size:14px">
			<div style="font-size:36px;margin-bottom:12px">📦</div>
			<div>Bundle size data builds as customers purchase bundles of different sizes.</div>
			<div style="font-size:12px;margin-top:8px">
				This chart will show which bundle sizes (2-pack, 3-pack, etc.) generate the most
				orders and revenue for your store.
			</div>
		</div>
		<?php endif; ?>
	</div>
</div>

<!-- ═══ SEGMENT BUNDLE RESPONSE ═══ -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
	<div class="gt-card-header rev-accordion-header" onclick="gtRevToggle(this)">
		<h2 class="gt-card-title">👥 Segment Bundle Response</h2>
		<span class="gt-target-chevron" style="color:#64748b;font-size:10px;transition:transform .2s">▼</span>
	</div>
	<div class="rev-accordion-body">
		<p style="font-size:13px;color:#64748b;margin:0 0 16px">
			How different customer segments respond to bundle offers. VIP and Returning customers
			often have higher bundle AOV. Price-sensitive segments may need more compelling bundle
			discounts. Use this data to personalise bundle recommendations by customer archetype.
		</p>
		<?php
		if ( ! empty( $segment_bundle ) ) :
			$seg_max_orders = max( array_column( $segment_bundle, 'orders' ) ?: array( 1 ) );
			?>
		<table class="gt-table">
			<thead>
				<tr><th>Segment</th><th>Bundle Orders</th><th>Bundle AOV</th><th>Response</th><th>Volume</th></tr>
			</thead>
			<tbody>
			<?php
			foreach ( $segment_bundle as $seg_key => $seg ) :
				$seg_bar = $seg_max_orders > 0
					? round( $seg['orders'] / $seg_max_orders * 100 )
					: 0;
				if ( $seg['orders'] >= 20 ) {
					$resp   = 'Strong';
					$resp_c = '#22c55e';
				} elseif ( $seg['orders'] >= 10 ) {
					$resp   = 'Good';
					$resp_c = '#3b82f6';
				} elseif ( $seg['orders'] >= 5 ) {
					$resp   = 'Moderate';
					$resp_c = '#f59e0b';
				} else {
					$resp   = 'Developing';
					$resp_c = '#64748b';
				}
				?>
			<tr>
				<td style="font-weight:600"><?php echo esc_html( $seg['label'] ); ?></td>
				<td><?php echo esc_html( number_format( $seg['orders'] ) ); ?></td>
				<td style="font-family:'DM Mono',monospace;font-size:11px">
					$<?php echo esc_html( number_format( $seg['aov'], 2 ) ); ?>
				</td>
				<td style="color:<?php echo esc_attr( $resp_c ); ?>;font-weight:600;font-size:12px">
					<?php echo esc_html( $resp ); ?>
				</td>
				<td>
					<div style="background:rgba(255,255,255,0.06);border-radius:3px;height:6px;overflow:hidden;min-width:50px">
						<div style="height:6px;border-radius:3px;background:#a78bfa;width:<?php echo esc_attr( $seg_bar ); ?>%;transition:width .6s ease"></div>
					</div>
				</td>
			</tr>
			<?php endforeach; ?>
			</tbody>
		</table>
		<?php else : ?>
		<div style="text-align:center;padding:48px 20px;color:#64748b;font-size:14px">
			<div style="font-size:36px;margin-bottom:12px">👥</div>
			<div>Segment bundle data builds as the Orchestrator classifies visitors and they purchase bundles.</div>
			<div style="font-size:12px;margin-top:8px">
				This table will break down bundle response by customer archetype (New, Returning, VIP, etc.).
			</div>
		</div>
		<?php endif; ?>
	</div>
</div>

<!-- ═══ CATEGORY BUNDLE AFFINITY ═══ -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
	<div class="gt-card-header rev-accordion-header" onclick="gtRevToggle(this)">
		<h2 class="gt-card-title">🗂️ Category Bundle Affinity</h2>
		<span class="gt-target-chevron" style="color:#64748b;font-size:10px;transition:transform .2s">▼</span>
	</div>
	<div class="rev-accordion-body">
		<p style="font-size:13px;color:#64748b;margin:0 0 16px">
			Product categories most frequently included in bundle purchases. Categories with high
			bundle order counts are prime targets for expanded bundle offers. Use cross-category
			bundles to introduce customers to new product lines and increase category discovery.
		</p>
		<?php
		if ( ! empty( $cat_bundle ) ) :
			$cat_max_orders = max( array_column( $cat_bundle, 'orders' ) ?: array( 1 ) );
			?>
		<table class="gt-table">
			<thead>
				<tr><th>Category</th><th>Bundle Orders</th><th>Bundle AOV</th><th>Volume</th></tr>
			</thead>
			<tbody>
			<?php
			foreach ( $cat_bundle as $cat ) :
				$cat_bar = $cat_max_orders > 0
					? round( $cat['orders'] / $cat_max_orders * 100 )
					: 0;
				?>
			<tr>
				<td style="font-weight:600"><?php echo esc_html( $cat['name'] ); ?></td>
				<td><?php echo esc_html( number_format( $cat['orders'] ) ); ?></td>
				<td style="font-family:'DM Mono',monospace;font-size:11px">
					$<?php echo esc_html( number_format( $cat['aov'], 2 ) ); ?>
				</td>
				<td>
					<div style="background:rgba(255,255,255,0.06);border-radius:3px;height:6px;overflow:hidden;min-width:50px">
						<div style="height:6px;border-radius:3px;background:#06b6d4;width:<?php echo esc_attr( $cat_bar ); ?>%;transition:width .6s ease"></div>
					</div>
				</td>
			</tr>
			<?php endforeach; ?>
			</tbody>
		</table>
		<?php else : ?>
		<div style="text-align:center;padding:48px 20px;color:#64748b;font-size:14px">
			<div style="font-size:36px;margin-bottom:12px">🗂️</div>
			<div>Category bundle data builds as customers purchase bundles with category metadata attached.</div>
			<div style="font-size:12px;margin-top:8px">
				This table will show which product categories appear most frequently in bundle purchases.
			</div>
		</div>
		<?php endif; ?>
	</div>
</div>

<!-- ═══ RECENT BUNDLE ACTIVITY ═══ -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
	<div class="gt-card-header rev-accordion-header" onclick="gtRevToggle(this)">
		<h2 class="gt-card-title">📋 Recent Bundle Activity</h2>
		<span class="gt-target-chevron" style="color:#64748b;font-size:10px;transition:transform .2s">▼</span>
	</div>
	<div class="rev-accordion-body">
		<p style="font-size:13px;color:#64748b;margin:0 0 16px">
			Most recent bundle orders detected by the analytics engine. Each row represents a
			completed order that contained a bundle deal. Use this log to verify bundles are being
			tracked correctly and to spot emerging co-purchase patterns.
		</p>
		<?php if ( ! empty( $recent_bundles ) ) : ?>
		<table class="gt-table">
			<thead>
				<tr><th>Order ID</th><th>Date</th><th>Bundle Size</th><th>Category</th><th>Order Total</th></tr>
			</thead>
			<tbody>
			<?php
			foreach ( $recent_bundles as $rb ) :
				$rb_sz  = (int) $rb->sz;
				$rb_cat = trim( (string) $rb->cat, '"' );
				?>
			<tr>
				<td style="font-weight:600;font-family:'DM Mono',monospace">
					#<?php echo esc_html( $rb->order_id ); ?>
				</td>
				<td style="font-size:11px;color:#64748b">
					<?php echo esc_html( human_time_diff( strtotime( $rb->date_created ), time() ) ); ?> ago
				</td>
				<td>
					<span class="gt-badge gt-badge-pro" style="font-size:10px">
						<?php echo esc_html( $rb_sz ); ?>-pack
					</span>
				</td>
				<td style="font-size:12px;color:#94a3b8">
					<?php echo $rb_cat ? esc_html( $rb_cat ) : '—'; ?>
				</td>
				<td style="font-family:'DM Mono',monospace;font-size:11px">
					$<?php echo esc_html( number_format( (float) $rb->order_total, 2 ) ); ?>
				</td>
			</tr>
			<?php endforeach; ?>
			</tbody>
		</table>
		<?php else : ?>
		<div style="text-align:center;padding:48px 20px;color:#64748b;font-size:14px">
			<div style="font-size:36px;margin-bottom:12px">📋</div>
			<div>No recent bundle activity detected yet.</div>
			<div style="font-size:12px;margin-top:8px">
				Bundle orders appear here as customers complete purchases that include bundle deals.
				Activate the Bundle Configurator superpower to start generating bundle offers.
			</div>
		</div>
		<?php endif; ?>
	</div>
</div>

<!-- ═══ HOW BUNDLE INTELLIGENCE WORKS ═══ -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
	<div class="gt-card-header rev-accordion-header" onclick="gtRevToggle(this)">
		<h2 class="gt-card-title">🧠 How Bundle Intelligence Works</h2>
		<span class="gt-target-chevron" style="color:#64748b;font-size:10px;transition:transform .2s">▼</span>
	</div>
	<div class="rev-accordion-body">
		<p style="font-size:13px;color:#64748b;margin:0 0 16px">
			Bundle Intelligence V2 uses a four-stage pipeline to assemble and deliver personalised
			product bundles. The entire process runs automatically — no manual configuration
			required. Here is what happens under the hood:
		</p>
		<div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:16px">
			<div style="background:#0d1f3c;border-radius:10px;padding:20px;border:1px solid rgba(255,255,255,0.04);transition:transform .2s"
				onmouseover="this.style.transform='translateY(-2px)'"
				onmouseout="this.style.transform='translateY(0)'">
				<div style="font-size:24px;margin-bottom:10px">1️⃣</div>
				<div style="font-weight:700;color:#fff;margin-bottom:6px">Order Analysis</div>
				<div style="font-size:12px;color:#94a3b8;line-height:1.6">
					Scans every completed order to identify which products are purchased together.
					Builds a weighted relationship graph of all product co-purchases across your
					entire order history.
				</div>
			</div>
			<div style="background:#0d1f3c;border-radius:10px;padding:20px;border:1px solid rgba(255,255,255,0.04);transition:transform .2s"
				onmouseover="this.style.transform='translateY(-2px)'"
				onmouseout="this.style.transform='translateY(0)'">
				<div style="font-size:24px;margin-bottom:10px">2️⃣</div>
				<div style="font-weight:700;color:#fff;margin-bottom:6px">Affinity Scoring</div>
				<div style="font-size:12px;color:#94a3b8;line-height:1.6">
					Assigns weighted affinity scores (0–1 scale) based on co-purchase frequency,
					recency of purchases, and combined cart value of paired products. Higher
					scores = stronger co-purchase relationships.
				</div>
			</div>
			<div style="background:#0d1f3c;border-radius:10px;padding:20px;border:1px solid rgba(255,255,255,0.04);transition:transform .2s"
				onmouseover="this.style.transform='translateY(-2px)'"
				onmouseout="this.style.transform='translateY(0)'">
				<div style="font-size:24px;margin-bottom:10px">3️⃣</div>
				<div style="font-weight:700;color:#fff;margin-bottom:6px">AI Assembly</div>
				<div style="font-size:12px;color:#94a3b8;line-height:1.6">
					Matches each customer's unique purchase history and taste profile to affinity
					data, assembling personalised bundles in real time. A customer who always buys
					black items gets a black-themed bundle tailored to their preferences.
				</div>
			</div>
			<div style="background:#0d1f3c;border-radius:10px;padding:20px;border:1px solid rgba(255,255,255,0.04);transition:transform .2s"
				onmouseover="this.style.transform='translateY(-2px)'"
				onmouseout="this.style.transform='translateY(0)'">
				<div style="font-size:24px;margin-bottom:10px">4️⃣</div>
				<div style="font-weight:700;color:#fff;margin-bottom:6px">Smart Pricing</div>
				<div style="font-size:12px;color:#94a3b8;line-height:1.6">
					Uses Cart Value Intelligence to price bundles below individual item totals.
					The value proposition is instantly clear — customers see exactly how much they
					save by purchasing the bundle vs buying items separately.
				</div>
			</div>
		</div>
	</div>
</div>

<!-- ═══ WHAT-IF PROJECTIONS ═══ -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
	<div class="gt-card-header rev-accordion-header" onclick="gtRevToggle(this)">
		<h2 class="gt-card-title">🔮 Bundle What-If Projections</h2>
		<span class="gt-target-chevron" style="color:#64748b;font-size:10px;transition:transform .2s">▼</span>
	</div>
	<div class="rev-accordion-body">
		<p style="font-size:13px;color:#64748b;margin:0 0 16px">
			Forward-looking estimates based on current bundle performance data. These projections
			show potential revenue impact of different bundle growth strategies. All estimates
			assume current conversion rates and AOV remain stable.
		</p>
		<?php if ( ! empty( $whatif_bundle ) ) : ?>
		<div style="display:grid;grid-template-columns:repeat(2,1fr);gap:12px">
			<?php foreach ( $whatif_bundle as $wsc ) : ?>
			<div style="background:#0d1f3c;border-radius:10px;padding:24px;text-align:center;border:1px solid rgba(255,255,255,0.04);transition:transform .2s"
				onmouseover="this.style.transform='translateY(-2px)'"
				onmouseout="this.style.transform='translateY(0)'">
				<div style="font-size:28px;margin-bottom:8px"><?php echo esc_html( $wsc['icon'] ); ?></div>
				<div style="font-size:14px;font-weight:600;color:#e2e8f0;margin-bottom:12px;line-height:1.4">
					<?php echo esc_html( $wsc['label'] ); ?>
				</div>
				<div style="font-size:28px;font-weight:800;color:<?php echo esc_attr( $wsc['color'] ); ?>">
					+$<?php echo esc_html( number_format( $wsc['impact'], 0 ) ); ?>
				</div>
				<div style="font-size:11px;color:#64748b;margin-top:4px">Estimated additional revenue</div>
			</div>
			<?php endforeach; ?>
		</div>
		<div style="font-size:10px;color:#475569;text-align:center;margin-top:12px">
			Projections are estimates based on current data. Actual results depend on market
			conditions, seasonality, and customer behaviour.
		</div>
		<?php else : ?>
		<div style="text-align:center;padding:48px 20px;color:#64748b;font-size:14px">
			<div style="font-size:36px;margin-bottom:12px">🔮</div>
			<div>What-if projections become available after sufficient bundle data is collected.</div>
		</div>
		<?php endif; ?>
	</div>
</div>

<!-- ═══ RECOMMENDATIONS ═══ -->
<div class="gt-card gt-card-premium gt-animate-in" style="margin-bottom:20px">
	<div class="gt-card-header">
		<h2 class="gt-card-title">💡 Bundle Recommendations</h2>
	</div>
	<div style="display:flex;flex-direction:column;gap:10px">
		<?php
		foreach ( $recommendations as $rec ) :
			if ( $rec['type'] === 'success' ) {
				$rec_bg = 'rgba(34,197,94,0.04)';
				$rec_ic = '#86efac';
			} elseif ( $rec['type'] === 'warning' ) {
				$rec_bg = 'rgba(239,68,68,0.04)';
				$rec_ic = '#fca5a5';
			} else {
				$rec_bg = 'rgba(59,130,246,0.04)';
				$rec_ic = '#93c5fd';
			}
			?>
		<div style="padding:14px 18px;background:<?php echo esc_attr( $rec_bg ); ?>;border-radius:8px;font-size:13px;color:#e2e8f0;line-height:1.6">
			<span style="color:<?php echo esc_attr( $rec_ic ); ?>;margin-right:6px">
				<?php echo esc_html( $rec['icon'] ); ?>
			</span>
			<?php echo wp_kses_post( $rec['text'] ); ?>
		</div>
		<?php endforeach; ?>
	</div>
</div>

<script>
// ═══════════════════════════════════════════════════════════════════════════════
// ACCORDION TOGGLE — Slide animation for all rev-accordion sections
// ═══════════════════════════════════════════════════════════════════════════════
function gtRevToggle(header) {
	var body = header.nextElementSibling;
	var chev = header.querySelector('.gt-target-chevron');
	var open = body.classList.contains('open');
	if (open) {
		body.classList.remove('open');
		header.classList.remove('open');
		if (chev) {
			chev.style.transform = 'rotate(0deg)';
			chev.textContent = '▼';
		}
	} else {
		body.classList.add('open');
		header.classList.add('open');
		if (chev) {
			chev.style.transform = 'rotate(180deg)';
			chev.textContent = '▲';
		}
	}
}

// ═══════════════════════════════════════════════════════════════════════════════
// ACCORDION CSS INJECTION
// ═══════════════════════════════════════════════════════════════════════════════
(function() {
	if (document.getElementById('rev-accordion-style')) return;
	var style = document.createElement('style');
	style.id = 'rev-accordion-style';
	style.textContent = [
		'.rev-accordion-body {',
		'  max-height: 0;',
		'  overflow: hidden;',
		'  transition: max-height .35s ease, padding .35s ease;',
		'  padding: 0 24px;',
		'}',
		'.rev-accordion-body.open {',
		'  max-height: 8000px;',
		'  padding: 0 24px 20px;',
		'}',
		'.rev-accordion-header {',
		'  cursor: pointer;',
		'  user-select: none;',
		'}',
		'.rev-accordion-header .gt-target-chevron {',
		'  display: inline-block;',
		'  transition: transform .2s ease;',
		'}'
	].join('');
	document.head.appendChild(style);
})();
</script>

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