<?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 — Revenue Intelligence Dashboard
 *
 * Enterprise revenue command centre. Complete revenue analytics suite with
 * live data from GT_BOGO_Analytics, GT_BOGO_Revenue_Maximizer,
 * GT_BOGO_Predictive_Timing, GT_BOGO_Signal_Bus, and GT_BOGO_Revenue_Guard.
 *
 * Features:
 *   • 8 KPI metric cards — Revenue Influenced, BOGO Orders, BOGO AOV,
 *     Total Discounts, Maximizer Mode, Attribution Confidence, Margin
 *     Health, Timing Profiles
 *   • 30-day revenue trend chart (revenue, orders, discounts — dual axis)
 *   • Rule ROI ranking table with efficiency scoring (Excellent/Good/
 *     Moderate/Low)
 *   • Revenue Maximizer mode display with objective weight bars (CR, AOV,
 *     Margin, LTV) and mode description
 *   • Predictive Timing 24-hour heatmap with peak hour detection
 *   • Signal Bus snapshot — 8 intelligence signals with colour-coded
 *     gauges and hot/warm/cold status
 *   • BOGO vs Non-BOGO AOV comparison cards with uplift/downlift indicator
 *   • Revenue Guard status with margin health gauge
 *   • Segment revenue contribution matrix
 *   • Category revenue lift analysis
 *   • Revenue what-if projections (orders +10%, AOV +$5, share doubled,
 *     discount halved)
 *   • Actionable intelligent recommendations
 *   • Day range filter (7/14/30/60/90d) with comparison period selector
 *   • Interactive accordion sections with slide animation (max-height
 *     transition)
 *
 * All data wired to live store analytics. Zero hardcoded values.
 * Enterprise-grade — suitable for stores processing 10,000+ orders/month.
 *
 * @package GT_BOGO_Engine
 * @since   4.0.1
 */

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

// ═══════════════════════════════════════════════════════════════════════════════
// PRO GATE — Revenue 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>Revenue Intelligence Requires PRO</h2>
		<p>Real-time revenue guard, predictive timing heatmaps, Revenue Maximizer
			controls, rule ROI ranking, BOGO vs non-BOGO comparisons, segment
			revenue analysis, and what-if projections 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';

// Day range filter with bounds
$days    = max( 7, min( 90, absint( wp_unslash( $_GET['days'] ?? 30 ) ) ) );
$compare = max( 7, min( 90, absint( wp_unslash( $_GET['compare'] ?? 14 ) ) ) );

// Intelligence class availability checks
$has_rm    = class_exists( 'GT_BOGO_Revenue_Maximizer' );
$has_pt    = class_exists( 'GT_BOGO_Predictive_Timing' );
$has_ana   = class_exists( 'GT_BOGO_Analytics' );
$has_bus   = class_exists( 'GT_BOGO_Signal_Bus' );
$has_guard = class_exists( 'GT_BOGO_Revenue_Guard' );
$has_cvi   = class_exists( 'GT_BOGO_Cart_Value_Intelligence' );

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

// ═══════════════════════════════════════════════════════════════════════════════
// REVENUE MAXIMIZER — Mode, weights, and score
// ═══════════════════════════════════════════════════════════════════════════════
$rm_mode    = 'balanced';
$rm_weights = array(
	'cr'     => 0.35,
	'aov'    => 0.25,
	'margin' => 0.25,
	'ltv'    => 0.15,
);
$rm_score   = 0;
$rm_report  = array();

if ( $has_rm ) {
	if ( method_exists( 'GT_BOGO_Revenue_Maximizer', 'get_report' ) ) {
		$rm_report  = GT_BOGO_Revenue_Maximizer::get_report() ?: array();
		$rm_mode    = $rm_report['mode'] ?? 'balanced';
		$rm_weights = $rm_report['weights'] ?? $rm_weights;
		$rm_score   = (float) ( $rm_report['score'] ?? 0 );
	} elseif ( method_exists( 'GT_BOGO_Revenue_Maximizer', 'get_weights' ) ) {
		$rm_weights = GT_BOGO_Revenue_Maximizer::get_weights() ?: $rm_weights;
	}
}

// Mode metadata for display
$mode_labels = array(
	'growth'   => array(
		'label' => 'Growth',
		'desc'  => 'Maximise conversions, accept lower margin',
		'color' => '#3b82f6',
		'icon'  => '🚀',
	),
	'profit'   => array(
		'label' => 'Profit',
		'desc'  => 'Prioritise margin over conversion volume',
		'color' => '#10b981',
		'icon'  => '💎',
	),
	'balanced' => array(
		'label' => 'Balanced',
		'desc'  => 'Equal weight across CR, AOV, margin, LTV',
		'color' => '#a78bfa',
		'icon'  => '⚖️',
	),
	'custom'   => array(
		'label' => 'Custom',
		'desc'  => 'Manual weight configuration',
		'color' => '#E10000',
		'icon'  => '🔧',
	),
);
$mode_cfg    = $mode_labels[ $rm_mode ] ?? $mode_labels['balanced'];

// ═══════════════════════════════════════════════════════════════════════════════
// PREDICTIVE TIMING — Peak purchase windows
// ═══════════════════════════════════════════════════════════════════════════════
$pt_model       = array();
$profiled_count = 0;
$peak_hour      = null;
$peak_intensity = 0.0;

if ( $has_pt ) {
	if ( method_exists( 'GT_BOGO_Predictive_Timing', 'build_store_timing_model' ) ) {
		$pt_model = GT_BOGO_Predictive_Timing::build_store_timing_model() ?: array();
	}
	$profiled_count = (int) get_option( 'gtbogo_timing_profiled_customers', 0 );

	if ( ! empty( $pt_model['hours'] ) ) {
		$hours = $pt_model['hours'];
		arsort( $hours );
		$peak_hour      = array_key_first( $hours );
		$peak_intensity = (float) ( $hours[ $peak_hour ] ?? 0 );
	}
}

// Format peak hour for display
if ( $peak_hour !== null ) {
	$peak_label = gmdate( 'gA', strtotime( "{$peak_hour}:00" ) );
} else {
	$peak_label = 'N/A';
}

// ═══════════════════════════════════════════════════════════════════════════════
// ANALYTICS DATA — ROI stats, daily trend, top rules, recent activity
// ═══════════════════════════════════════════════════════════════════════════════
$roi_stats     = $has_ana ? GT_BOGO_Analytics::get_roi_stats( $days ) : array();
$daily_trend   = $has_ana ? GT_BOGO_Analytics::get_daily_trend( $days ) : array();
$top_rules     = $has_ana ? GT_BOGO_Analytics::get_top_rules(
	gmdate( 'Y-m-d H:i:s', strtotime( "-{$days} days" ) ),
	10
) : array();
$recent_act    = $has_ana ? GT_BOGO_Analytics::get_recent_activity( 15 ) : array();
$rules_summary = $has_ana ? GT_BOGO_Analytics::get_active_rules_summary() : array();

// ── Extract ROI stats ─────────────────────────────────────────────────────────
$revenue_influenced = (float) ( $roi_stats['revenue_influenced'] ?? 0 );
$bogo_orders        = (int) ( $roi_stats['bogo_orders'] ?? 0 );
$bogo_aov           = (float) ( $roi_stats['bogo_aov'] ?? 0 );
$total_discounts    = (float) ( $roi_stats['total_discounts'] ?? 0 );
$non_bogo_aov       = (float) ( $roi_stats['non_bogo_aov'] ?? 0 );
$total_orders_store = (int) ( $roi_stats['total_orders'] ?? 0 );

// ── Derived metrics ───────────────────────────────────────────────────────────
$non_bogo_orders    = max( 0, $total_orders_store - $bogo_orders );
$uplift_pct         = $non_bogo_aov > 0
	? round( ( ( $bogo_aov - $non_bogo_aov ) / $non_bogo_aov ) * 100, 1 )
	: 0;
$share_pct          = $total_orders_store > 0
	? round( ( $bogo_orders / $total_orders_store ) * 100, 1 )
	: 0;
$discount_rate      = $revenue_influenced > 0
	? round( ( $total_discounts / $revenue_influenced ) * 100, 1 )
	: 0;
$avg_disc_per_order = $bogo_orders > 0
	? round( $total_discounts / $bogo_orders, 2 )
	: 0;

// ── Comparison period data ────────────────────────────────────────────────────
$comp_roi = array();
if ( $has_ana ) {
	$comp_roi = GT_BOGO_Analytics::get_roi_stats( $compare ) ?: array();
}
$comp_revenue = (float) ( $comp_roi['revenue_influenced'] ?? 0 );
$comp_orders  = (int) ( $comp_roi['bogo_orders'] ?? 0 );
$rev_trend    = $comp_revenue > 0
	? round( ( ( $revenue_influenced - $comp_revenue ) / $comp_revenue ) * 100, 1 )
	: 0;
$ord_trend    = $comp_orders > 0
	? round( ( ( $bogo_orders - $comp_orders ) / $comp_orders ) * 100, 1 )
	: 0;

// ── Chart data arrays ─────────────────────────────────────────────────────────
$chart_labels  = array();
$chart_revenue = array();
$chart_orders  = array();
$chart_disc    = array();

foreach ( $daily_trend as $day ) {
	$chart_labels[]  = gmdate( 'M j', strtotime( $day['date'] ) );
	$chart_revenue[] = round( (float) ( $day['revenue'] ?? 0 ), 2 );
	$chart_orders[]  = (int) ( $day['orders'] ?? 0 );
	$chart_disc[]    = round( (float) ( $day['discounts'] ?? 0 ), 2 );
}

$chart_rev_sum  = array_sum( $chart_revenue );
$chart_ord_sum  = array_sum( $chart_orders );
$chart_disc_sum = array_sum( $chart_disc );

// ═══════════════════════════════════════════════════════════════════════════════
// REVENUE GUARD — Margin protection status
// ═══════════════════════════════════════════════════════════════════════════════
$guard_paused = false;
$guard_reason = '';
$guard_health = 4.0;

if ( $has_guard || $has_bus ) {
	$guard_health = $has_bus
		? (float) GT_BOGO_Signal_Bus::get( 'revenue_health', 4.0 )
		: 4.0;
	$guard_paused = $guard_health < 1.0;
	$guard_reason = $guard_paused
		? 'Revenue Guard is actively suppressing deals to protect margin.'
		: '';
}

// Guard status display
if ( $guard_health >= 3.0 ) {
	$guard_status = 'Healthy';
	$guard_color  = '#22c55e';
} elseif ( $guard_health >= 1.0 ) {
	$guard_status = 'Warning';
	$guard_color  = '#f59e0b';
} else {
	$guard_status = 'Critical';
	$guard_color  = '#ef4444';
}

// ═══════════════════════════════════════════════════════════════════════════════
// SIGNAL BUS — 8 intelligence signals
// ═══════════════════════════════════════════════════════════════════════════════
$signals     = array();
$key_signals = array(
	'timing_confidence'       => array( 'Peak Timing', '#3b82f6' ),
	'price_sensitivity_score' => array( 'Price Sensitivity', '#f59e0b' ),
	'ltv_score'               => array( 'LTV Score', '#10b981' ),
	'revenue_health'          => array( 'Revenue Health', '#a78bfa' ),
	'attribution_confidence'  => array( 'Attribution', '#f97316' ),
	'loyalty_tier'            => array( 'Loyalty Tier', '#ec4899' ),
	'cohort_performance'      => array( 'Cohort Performance', '#06b6d4' ),
	'rfm_score'               => array( 'RFM Score', '#8b5cf6' ),
);

if ( $has_bus ) {
	foreach ( $key_signals as $key => $meta ) {
		$signals[ $key ] = (float) GT_BOGO_Signal_Bus::get( $key, 0.0 );
	}
}

// Signal status helper
function gt_rev_signal_status( $val ) {
	if ( $val >= 3.5 ) {
		return 'Hot';
	}
	if ( $val >= 2.0 ) {
		return 'Warm';
	}
	return 'Cold';
}

// ═══════════════════════════════════════════════════════════════════════════════
// CATEGORY REVENUE LIFT — Revenue by product category
// ═══════════════════════════════════════════════════════════════════════════════
$cat_revenue = 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(SUM(order_total), 0)    AS revenue,
                COALESCE(AVG(order_total), 0)    AS aov
         FROM {$analytics_tbl}
         WHERE date_created >= %s
           AND JSON_EXTRACT(meta, '$.category') IS NOT NULL
         GROUP BY JSON_EXTRACT(meta, '$.category')
         ORDER BY revenue 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_revenue[] = array(
				'name'    => $cat_name,
				'orders'  => (int) $row->orders,
				'revenue' => (float) $row->revenue,
				'aov'     => round( (float) $row->aov, 2 ),
			);
		}
	}
}

// ═══════════════════════════════════════════════════════════════════════════════
// SEGMENT REVENUE CONTRIBUTION — Revenue by customer archetype
// ═══════════════════════════════════════════════════════════════════════════════
$segment_revenue = 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(SUM(order_total), 0) AS revenue
             FROM {$analytics_tbl}
             WHERE date_created >= %s
               AND JSON_EXTRACT(meta, '$.archetype') = %s",
				gmdate( 'Y-m-d H:i:s', strtotime( "-{$days} days" ) ),
				$seg_key
			)
		);
		if ( $seg_data && (int) $seg_data->orders > 0 ) {
			$segment_revenue[ $seg_key ] = array(
				'label'   => $seg_label,
				'orders'  => (int) $seg_data->orders,
				'revenue' => (float) $seg_data->revenue,
			);
		}
	}
}

// ═══════════════════════════════════════════════════════════════════════════════
// WHAT-IF PROJECTIONS — Revenue scenarios
// ═══════════════════════════════════════════════════════════════════════════════
$whatif_revenue = array();

if ( $revenue_influenced > 0 && $bogo_orders > 0 ) {
	$avg_rev = $revenue_influenced / max( 1, $bogo_orders );

	// Scenario 1: BOGO orders increase by 10%
	$whatif_revenue[] = array(
		'icon'   => '📈',
		'label'  => 'Orders +10% (' . number_format( $bogo_orders ) . ' → '
					. number_format( round( $bogo_orders * 1.1 ) ) . ')',
		'impact' => round( $bogo_orders * 0.1 * $avg_rev, 0 ),
		'color'  => '#22c55e',
	);

	// Scenario 2: AOV increases by $5
	$whatif_revenue[] = array(
		'icon'   => '💵',
		'label'  => 'AOV +$5 ($' . number_format( $bogo_aov, 2 ) . ' → $'
					. number_format( $bogo_aov + 5, 2 ) . ')',
		'impact' => round( $bogo_orders * 5, 0 ),
		'color'  => '#3b82f6',
	);

	// Scenario 3: Share of store orders doubles
	$doubled_share    = min( 100, $share_pct * 2 );
	$whatif_revenue[] = array(
		'icon'   => '🔄',
		'label'  => "Share doubled ({$share_pct}% → {$doubled_share}% of store)",
		'impact' => round( $bogo_orders * $avg_rev, 0 ),
		'color'  => '#a78bfa',
	);

	// Scenario 4: Discount rate halved
	$halved_disc      = round( $discount_rate / 2, 1 );
	$whatif_revenue[] = array(
		'icon'   => '🛡️',
		'label'  => "Discount rate halved ({$discount_rate}% → {$halved_disc}%)",
		'impact' => round( $total_discounts * 0.5, 0 ),
		'color'  => '#f59e0b',
	);
}

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

if ( $uplift_pct > 5 ) {
	$recommendations[] = array(
		'type' => 'success',
		'icon' => '✓',
		'text' => "BOGO drives a <strong>+{$uplift_pct}%</strong> AOV uplift vs non-BOGO orders. "
				. 'Your discount strategy is adding significant value per transaction.',
	);
} elseif ( $uplift_pct > 0 ) {
	$recommendations[] = array(
		'type' => 'success',
		'icon' => '✓',
		'text' => "BOGO AOV is <strong>+{$uplift_pct}%</strong> above non-BOGO — your offer is working.",
	);
} elseif ( $uplift_pct < -5 ) {
	$recommendations[] = array(
		'type' => 'warning',
		'icon' => '⚠',
		'text' => "BOGO AOV is <strong>{$uplift_pct}%</strong> below non-BOGO. "
				. 'Consider reducing the discount percentage or tightening eligibility.',
	);
}

if ( $share_pct < 5 && $bogo_orders > 10 ) {
	$recommendations[] = array(
		'type' => 'info',
		'icon' => 'ℹ',
		'text' => "BOGO accounts for only <strong>{$share_pct}%</strong> of store orders. "
				. 'Promote your offer more prominently on cart and checkout pages.',
	);
}

if ( $discount_rate > 25 ) {
	$recommendations[] = array(
		'type' => 'warning',
		'icon' => '⚠',
		'text' => "Discount rate is <strong>{$discount_rate}%</strong> of BOGO revenue — "
				. 'this may be eroding margin. Review your tier configuration in Discount Intelligence.',
	);
}

if ( $guard_paused ) {
	$recommendations[] = array(
		'type' => 'warning',
		'icon' => '⚠',
		'text' => 'Revenue Guard is <strong>actively suppressing deals</strong>. '
				. 'Review COGS settings to restore deal visibility.',
	);
}

if ( $profiled_count < 10 && $has_pt ) {
	$recommendations[] = array(
		'type' => 'info',
		'icon' => 'ℹ',
		'text' => "Only <strong>{$profiled_count}</strong> customers profiled for predictive timing. "
				. 'More completed orders = better peak window detection.',
	);
}

if ( $rm_score > 80 ) {
	$recommendations[] = array(
		'type' => 'success',
		'icon' => '✓',
		'text' => "Revenue Maximizer score is <strong>{$rm_score}</strong> — "
				. 'your store is optimising well across all weighted objectives.',
	);
}

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

<div class="gt-page-header gt-animate-in">
	<div>
		<h1 class="gt-page-title">📊 Revenue Intelligence</h1>
		<p class="gt-page-subtitle">Complete revenue command centre — ROI analytics, Revenue Maximizer controls, predictive timing, rule ranking, signal bus, BOGO vs non-BOGO comparisons, segment contribution, category lift, and what-if projections. All wired to live store data.</p>
	</div>
	<div style="display:flex;gap:8px;align-items:center">
		<?php if ( $guard_paused ) : ?>
		<span class="gt-badge gt-badge-expired">⚠ Guard Active</span>
		<?php else : ?>
		<span class="gt-badge gt-badge-active">● Margin Healthy</span>
		<?php endif; ?>
		<span class="gt-badge gt-badge-pro">PRO v<?php echo esc_html( $version ); ?></span>
	</div>
</div>

<?php if ( $guard_paused ) : ?>
<div class="gt-notice gt-notice-error gt-animate-in">
	<strong>Revenue Guard is suppressing deals.</strong> <?php echo esc_html( $guard_reason ); ?>
	Review COGS in <a href="<?php echo esc_url( admin_url( 'admin.php?page=gt-bogo-engine&tab=settings' ) ); ?>" style="color:#fca5a5;text-decoration:underline">Settings</a>.
</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,
					'compare' => $compare,
				)
			)
		);
		?>
				"
		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:12px;font-size:12px;color:#64748b;font-weight:600">Compare:</span>
	<?php foreach ( array( 7, 14, 30 ) as $d ) : ?>
	<a href="
		<?php
		echo esc_url(
			add_query_arg(
				array(
					'days'    => $days,
					'compare' => $d,
				)
			)
		);
		?>
				"
		class="gt-btn gt-btn-xs <?php echo $d === $compare ? 'gt-btn-secondary' : 'gt-btn-ghost'; ?>">vs prev <?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( $revenue_influenced, 0 ) ); ?> revenue · <?php echo esc_html( number_format( $bogo_orders ) ); ?> orders · $<?php echo esc_html( number_format( $bogo_aov, 2 ) ); ?> AOV
	</span>
</div>

<!-- ═══ 8 KPI METRICS ═══ -->
<div class="gt-metrics gt-animate-in" style="margin-bottom:24px">
	<!-- KPI 1: Revenue Influenced -->
	<div class="gt-metric" style="--gt-metric-c:#3b82f6">
		<span class="gt-metric-icon">💰</span>
		<div class="gt-metric-label">Revenue Influenced (<?php echo esc_html( $days ); ?>d)</div>
		<div class="gt-metric-value">$<?php echo esc_html( number_format( $revenue_influenced, 0 ) ); ?></div>
		<div class="gt-metric-trend" style="color:<?php echo $rev_trend >= 0 ? '#86efac' : '#fca5a5'; ?>">
			<?php echo $rev_trend >= 0 ? '↑' : '↓'; ?><?php echo esc_html( abs( $rev_trend ) ); ?>% vs prev <?php echo esc_html( $compare ); ?>d
		</div>
	</div>
	<!-- KPI 2: BOGO Orders -->
	<div class="gt-metric" style="--gt-metric-c:#22c55e">
		<span class="gt-metric-icon">🛒</span>
		<div class="gt-metric-label">BOGO Orders</div>
		<div class="gt-metric-value"><?php echo esc_html( number_format( $bogo_orders ) ); ?></div>
		<div class="gt-metric-trend"><?php echo esc_html( $share_pct ); ?>% of store (<?php echo esc_html( number_format( $total_orders_store ) ); ?> total)</div>
	</div>
	<!-- KPI 3: BOGO AOV -->
	<div class="gt-metric" style="--gt-metric-c:#06b6d4">
		<span class="gt-metric-icon">💵</span>
		<div class="gt-metric-label">BOGO Avg Order Value</div>
		<div class="gt-metric-value">$<?php echo esc_html( number_format( $bogo_aov, 2 ) ); ?></div>
		<div class="gt-metric-trend" style="color:<?php echo $uplift_pct >= 0 ? '#86efac' : '#fca5a5'; ?>">
			<?php echo $uplift_pct >= 0 ? '+' : ''; ?><?php echo esc_html( $uplift_pct ); ?>% vs non-BOGO ($<?php echo esc_html( number_format( $non_bogo_aov, 2 ) ); ?>)
		</div>
	</div>
	<!-- KPI 4: Total Discounts -->
	<div class="gt-metric" style="--gt-metric-c:#f59e0b">
		<span class="gt-metric-icon">🏷️</span>
		<div class="gt-metric-label">Total Discounts Given</div>
		<div class="gt-metric-value">$<?php echo esc_html( number_format( $total_discounts, 0 ) ); ?></div>
		<div class="gt-metric-trend"><?php echo esc_html( $discount_rate ); ?>% of BOGO revenue · $<?php echo esc_html( number_format( $avg_disc_per_order, 2 ) ); ?>/order</div>
	</div>
	<!-- KPI 5: Maximizer Mode -->
	<div class="gt-metric" style="--gt-metric-c:<?php echo esc_attr( $mode_cfg['color'] ); ?>">
		<span class="gt-metric-icon"><?php echo esc_html( $mode_cfg['icon'] ); ?></span>
		<div class="gt-metric-label">Maximizer Mode</div>
		<div class="gt-metric-value" style="font-size:20px;color:<?php echo esc_attr( $mode_cfg['color'] ); ?>"><?php echo esc_html( $mode_cfg['label'] ); ?></div>
		<div class="gt-metric-trend"><?php echo esc_html( $mode_cfg['desc'] ); ?></div>
	</div>
	<!-- KPI 6: Attribution Confidence -->
	<div class="gt-metric" style="--gt-metric-c:#f97316">
		<span class="gt-metric-icon">📈</span>
		<div class="gt-metric-label">Attribution Confidence</div>
		<div class="gt-metric-value"><?php echo esc_html( number_format( ( $signals['attribution_confidence'] ?? 0 ) * 20, 0 ) ); ?>%</div>
		<div class="gt-metric-trend">Revenue lift measurement accuracy</div>
	</div>
	<!-- KPI 7: Margin Health -->
	<div class="gt-metric" style="--gt-metric-c:<?php echo esc_attr( $guard_color ); ?>">
		<span class="gt-metric-icon">🛡️</span>
		<div class="gt-metric-label">Margin Health</div>
		<div class="gt-metric-value" style="font-size:20px;color:<?php echo esc_attr( $guard_color ); ?>"><?php echo esc_html( number_format( $guard_health, 1 ) ); ?>/5</div>
		<div class="gt-metric-trend"><?php echo esc_html( $guard_status ); ?></div>
	</div>
	<!-- KPI 8: Timing Profiles -->
	<div class="gt-metric" style="--gt-metric-c:#8b5cf6">
		<span class="gt-metric-icon">⏱️</span>
		<div class="gt-metric-label">Timing Profiles</div>
		<div class="gt-metric-value"><?php echo esc_html( number_format( $profiled_count ) ); ?></div>
		<div class="gt-metric-trend">Peak: <?php echo esc_html( $peak_label ); ?></div>
	</div>
</div>

<!-- ═══ REVENUE TREND CHART ═══ -->
<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">📈 Revenue Trend (<?php echo esc_html( $days ); ?>d)</h2>
		<span class="gt-target-chevron" style="color:#64748b;font-size:10px;transition:transform .2s">▲</span>
	</div>
	<div class="rev-accordion-body open">
		<?php if ( ! empty( $daily_trend ) ) : ?>
		<div style="position:relative;height:300px"><canvas id="rev-trend-chart"></canvas></div>
		<div style="display:flex;gap:24px;margin-top:14px;font-size:12px;color:#64748b;justify-content:center;flex-wrap:wrap">
			<span>● Revenue: <strong style="color:#3b82f6">$<?php echo esc_html( number_format( $chart_rev_sum, 0 ) ); ?></strong></span>
			<span>● Orders: <strong style="color:#22c55e"><?php echo esc_html( number_format( $chart_ord_sum ) ); ?></strong></span>
			<span>● Discounts: <strong style="color:#f59e0b">$<?php echo esc_html( number_format( $chart_disc_sum, 0 ) ); ?></strong></span>
			<span>● Days tracked: <strong style="color:#94a3b8"><?php echo count( $daily_trend ); ?></strong></span>
		</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>No trend data yet. Revenue data builds as orders are placed and the analytics table populates.</div>
			<div style="font-size:12px;margin-top:8px">This chart will show daily revenue, order count, and discount totals.</div>
		</div>
		<?php endif; ?>
	</div>
</div>

<!-- ═══ RULE ROI RANKING ═══ -->
<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">🏆 Rule ROI Ranking (<?php echo esc_html( $days ); ?>d)</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">Revenue performance per active BOGO rule. ROI = revenue ÷ discount cost. Higher is better. Rules with ROI below 2x may need adjustment.</p>
		<?php if ( ! empty( $top_rules ) ) : ?>
		<table class="gt-table">
			<thead>
				<tr><th>Rule Name</th><th>Revenue</th><th>Orders</th><th>AOV</th><th>Discounts</th><th>ROI</th><th>Efficiency</th></tr>
			</thead>
			<tbody>
			<?php
			foreach ( $top_rules as $rule ) :
				$r_rev  = (float) ( $rule['revenue'] ?? 0 );
				$r_ord  = (int) ( $rule['orders'] ?? 0 );
				$r_aov  = $r_ord > 0 ? round( $r_rev / $r_ord, 2 ) : 0;
				$r_disc = (float) ( $rule['discounts'] ?? 0 );
				$r_roi  = $r_disc > 0 ? round( $r_rev / $r_disc, 1 ) : 0;
				if ( $r_roi >= 10 ) {
					$eff   = 'Excellent';
					$eff_c = '#22c55e'; } elseif ( $r_roi >= 5 ) {
					$eff   = 'Good';
					$eff_c = '#3b82f6'; } elseif ( $r_roi >= 2 ) {
						$eff   = 'Moderate';
						$eff_c = '#f59e0b'; } else {
						$eff   = 'Low';
						$eff_c = '#ef4444'; }
						?>
			<tr>
				<td style="font-weight:600;max-width:180px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap" title="<?php echo esc_attr( $rule['name'] ?? '' ); ?>"><?php echo esc_html( $rule['name'] ?? 'Unnamed Rule' ); ?></td>
				<td style="font-family:'DM Mono',monospace;font-size:11px">$<?php echo esc_html( number_format( $r_rev, 0 ) ); ?></td>
				<td><?php echo esc_html( number_format( $r_ord ) ); ?></td>
				<td style="font-family:'DM Mono',monospace;font-size:11px">$<?php echo esc_html( number_format( $r_aov, 2 ) ); ?></td>
				<td style="color:#f59e0b;font-family:'DM Mono',monospace;font-size:11px">$<?php echo esc_html( number_format( $r_disc, 0 ) ); ?></td>
				<td style="font-weight:700"><?php echo esc_html( $r_roi ); ?>x</td>
				<td><span class="gt-badge" style="font-size:10px;background:<?php echo esc_attr( $eff_c ); ?>20;border-color:<?php echo esc_attr( $eff_c ); ?>40;color:<?php echo esc_attr( $eff_c ); ?>"><?php echo esc_html( $eff ); ?></span></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 rule performance data yet. Rules generate analytics as customers complete BOGO orders.</div>
			<div style="font-size:12px;margin-top:8px">This table will rank all active rules by revenue and ROI efficiency.</div>
		</div>
		<?php endif; ?>
	</div>
</div>

<!-- ═══ REVENUE MAXIMIZER ═══ -->
<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">⚖️ Revenue Maximizer — <?php echo esc_html( $mode_cfg['label'] ); ?> Mode</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"><?php echo esc_html( $mode_cfg['desc'] ); ?>. These weights determine how the engine ranks and prioritises active BOGO rules. Adjust in Settings → Revenue Maximizer.</p>
		<?php
		$weight_labels = array(
			'cr'     => array( 'Conversion Rate', '#3b82f6', 'How much weight on maximising conversion percentage' ),
			'aov'    => array( 'Avg Order Value', '#06b6d4', 'How much weight on increasing basket size' ),
			'margin' => array( 'Margin Protection', '#10b981', 'How much weight on preserving profit per order' ),
			'ltv'    => array( 'Lifetime Value', '#a78bfa', 'How much weight on long-term customer value' ),
		);
		foreach ( $weight_labels as $key => [$wlabel, $wcolor, $wdesc] ) :
			$w    = (float) ( $rm_weights[ $key ] ?? 0 );
			$wpct = round( $w * 100 );
			?>
		<div style="display:flex;align-items:center;gap:12px;padding:14px 0;border-bottom:1px solid rgba(255,255,255,0.04)">
			<div style="width:150px;flex-shrink:0">
				<div style="font-size:13px;font-weight:600;color:#e2e8f0"><?php echo esc_html( $wlabel ); ?></div>
				<div style="font-size:10px;color:#475569;margin-top:2px"><?php echo esc_html( $wdesc ); ?></div>
			</div>
			<div style="flex:1;background:rgba(255,255,255,0.06);border-radius:4px;height:12px;overflow:hidden">
				<div style="height:12px;border-radius:4px;width:<?php echo esc_attr( $wpct ); ?>%;background:<?php echo esc_attr( $wcolor ); ?>;transition:width .6s ease"></div>
			</div>
			<span style="width:48px;text-align:right;flex-shrink:0;font-size:14px;font-weight:800;color:<?php echo esc_attr( $wcolor ); ?>;font-family:'DM Mono',monospace"><?php echo esc_html( $wpct ); ?>%</span>
		</div>
		<?php endforeach; ?>
		<div style="margin-top:12px;font-size:11px;color:#475569">Configured in <a href="<?php echo esc_url( admin_url( 'admin.php?page=gt-bogo-engine&tab=settings' ) ); ?>" style="color:#E10000;text-decoration:none;font-weight:600">Settings</a> → Revenue Maximizer section.</div>
	</div>
</div>

<!-- ═══ BOGO VS NON-BOGO 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">📊 BOGO vs Non-BOGO 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">Side-by-side comparison of BOGO-influenced orders vs store orders without BOGO discounts. A positive AOV uplift means BOGO is increasing basket size.</p>
		<div style="display:grid;grid-template-columns:1fr 1fr;gap:20px;margin-bottom:16px">
			<div style="background:#0d1f3c;border-radius:10px;padding:28px;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">BOGO Orders</div>
				<div style="font-size:36px;font-weight:800;color:#22c55e;margin-top:6px">$<?php echo esc_html( number_format( $bogo_aov, 2 ) ); ?></div>
				<div style="font-size:13px;color:#64748b;margin-top:6px">Average Order Value</div>
				<div style="font-size:11px;color:#475569;margin-top:6px;line-height:1.5">
					<?php echo esc_html( number_format( $bogo_orders ) ); ?> orders<br>
					$<?php echo esc_html( number_format( $revenue_influenced, 0 ) ); ?> total revenue
				</div>
			</div>
			<div style="background:#0d1f3c;border-radius:10px;padding:28px;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">Non-BOGO Orders</div>
				<div style="font-size:36px;font-weight:800;color:#3b82f6;margin-top:6px">$<?php echo esc_html( number_format( $non_bogo_aov, 2 ) ); ?></div>
				<div style="font-size:13px;color:#64748b;margin-top:6px">Average Order Value</div>
				<div style="font-size:11px;color:#475569;margin-top:6px;line-height:1.5">
					<?php echo esc_html( number_format( $non_bogo_orders ) ); ?> orders<br>
					Store baseline AOV
				</div>
			</div>
		</div>
		<?php if ( $uplift_pct !== 0 ) : ?>
		<div style="text-align:center;padding:16px;background:<?php echo $uplift_pct > 0 ? 'rgba(34,197,94,0.06)' : 'rgba(239,68,68,0.06)'; ?>;border-radius:10px;font-size:14px;font-weight:600;color:<?php echo $uplift_pct > 0 ? '#86efac' : '#fca5a5'; ?>">
			<?php if ( $uplift_pct > 0 ) : ?>
			✅ BOGO drives a <strong>+<?php echo esc_html( $uplift_pct ); ?>%</strong> increase in average order value vs non-BOGO orders — that's $<?php echo esc_html( number_format( $bogo_aov - $non_bogo_aov, 2 ) ); ?> more per order.
			<?php else : ?>
			⚠ BOGO AOV is <strong><?php echo esc_html( $uplift_pct ); ?>%</strong> below non-BOGO — your discount may be too deep or your qualifying thresholds too low.
			<?php endif; ?>
		</div>
		<?php endif; ?>
	</div>
</div>

<!-- ═══ SEGMENT REVENUE CONTRIBUTION ═══ -->
<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 Revenue Contribution</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">Revenue breakdown by customer archetype. Shows which segments contribute most to BOGO revenue. Use this to target high-value segments with personalised offers.</p>
		<?php
		if ( ! empty( $segment_revenue ) ) :
			$seg_max_rev = max( array_column( $segment_revenue, 'revenue' ) ?: array( 1 ) );
			?>
		<table class="gt-table">
			<thead><tr><th>Segment</th><th>Orders</th><th>Revenue</th><th>Share of BOGO Rev</th><th>Volume</th></tr></thead>
			<tbody>
			<?php
			foreach ( $segment_revenue as $seg_key => $seg ) :
				$seg_share = $revenue_influenced > 0 ? round( $seg['revenue'] / $revenue_influenced * 100, 1 ) : 0;
				$seg_bar   = $seg_max_rev > 0 ? round( $seg['revenue'] / $seg_max_rev * 100 ) : 0;
				?>
			<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['revenue'], 0 ) ); ?></td>
				<td><span class="gt-badge <?php echo $seg_share >= 20 ? 'gt-badge-active' : ( $seg_share >= 10 ? 'gt-badge-expiring' : 'gt-badge-free' ); ?>" style="font-size:10px"><?php echo esc_html( $seg_share ); ?>%</span></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 data builds as the Orchestrator classifies visitors and they complete BOGO orders.</div>
			<div style="font-size:12px;margin-top:8px">This table will break down revenue by customer archetype (New, Returning, VIP, At Risk, etc).</div>
		</div>
		<?php endif; ?>
	</div>
</div>

<!-- ═══ CATEGORY REVENUE LIFT ═══ -->
<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 Revenue Lift</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">Revenue performance by product category. Identify which categories generate the most BOGO revenue and which have the highest average order values.</p>
		<?php
		if ( ! empty( $cat_revenue ) ) :
			$cat_max_rev = max( array_column( $cat_revenue, 'revenue' ) ?: array( 1 ) );
			?>
		<table class="gt-table">
			<thead><tr><th>Category</th><th>Orders</th><th>Revenue</th><th>AOV</th><th>Volume</th></tr></thead>
			<tbody>
			<?php
			foreach ( $cat_revenue as $cat ) :
				$cat_bar = $cat_max_rev > 0 ? round( $cat['revenue'] / $cat_max_rev * 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['revenue'], 0 ) ); ?></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 revenue data builds as BOGO orders complete with category metadata.</div>
			<div style="font-size:12px;margin-top:8px">This table shows which product categories drive the highest BOGO revenue.</div>
		</div>
		<?php endif; ?>
	</div>
</div>

<!-- ═══ PREDICTIVE TIMING HEATMAP ═══ -->
<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">⏱️ Predictive Timing Heatmap</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 14px">24-hour purchase probability for <?php echo esc_html( $profiled_count ); ?> profiled customers. Darker cells = higher purchase probability. Peak: <strong style="color:#E10000"><?php echo esc_html( $peak_label ); ?></strong>. Use this to schedule time-sensitive campaigns.</p>
		<?php
		if ( ! empty( $pt_model ) && isset( $pt_model['hours'] ) ) :
			$hours = $pt_model['hours'];
			$max_w = max( array_values( $hours ) ?: array( 0.01 ) );
			?>
		<div style="display:flex;gap:4px;flex-wrap:wrap;align-items:flex-end;margin-bottom:12px">
			<?php
			for ( $h = 0; $h < 24; $h++ ) :
				$w       = (float) ( $hours[ $h ] ?? 0 );
				$pct     = $max_w > 0 ? $w / $max_w : 0;
				$alpha   = round( 0.08 + $pct * 0.9, 2 );
				$label   = $h === 0 ? '12a' : ( $h < 12 ? $h . 'a' : ( $h === 12 ? '12p' : ( $h - 12 ) . 'p' ) );
				$is_peak = ( $h === $peak_hour );
				?>
			<div style="flex:1;min-width:24px;text-align:center" title="<?php echo esc_attr( $label . ': ' . round( $pct * 100 ) . '% probability' ); ?>">
				<div style="height:<?php echo esc_attr( round( 20 + $pct * 60 ) ); ?>px;border-radius:3px 3px 0 0;background:rgba(225,0,0,<?php echo esc_attr( $alpha ); ?>);margin-bottom:3px;<?php echo $is_peak ? 'border:1px solid #fff;border-bottom:none;' : ''; ?>transition:height .3s ease"></div>
				<div style="font-size:8px;color:<?php echo $is_peak ? '#fff' : '#475569'; ?>;font-weight:<?php echo $is_peak ? '700' : '400'; ?>"><?php echo esc_html( $label ); ?></div>
			</div>
			<?php endfor; ?>
		</div>
		<div style="display:flex;align-items:center;gap:6px;font-size:10px;color:#475569;justify-content:center;margin-bottom:8px">
			<span>Low probability</span>
			<div style="width:14px;height:8px;border-radius:2px;background:rgba(225,0,0,0.1)"></div>
			<div style="width:14px;height:8px;border-radius:2px;background:rgba(225,0,0,0.35)"></div>
			<div style="width:14px;height:8px;border-radius:2px;background:rgba(225,0,0,0.65)"></div>
			<div style="width:14px;height:8px;border-radius:2px;background:rgba(225,0,0,0.95)"></div>
			<span>High probability</span>
		</div>
		<div style="font-size:11px;color:#475569;text-align:center">White outlined bar = detected peak purchase hour</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>Timing model builds automatically as customers complete purchases.</div>
			<div style="font-size:12px;margin-top:8px"><?php echo esc_html( $profiled_count ); ?> customer<?php echo $profiled_count === 1 ? '' : 's'; ?> profiled so far. More orders = better predictions.</div>
		</div>
		<?php endif; ?>
	</div>
</div>

<!-- ═══ SIGNAL BUS SNAPSHOT ═══ -->
<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">📡 Intelligence Signal Bus</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">Real-time signal readings from the intelligence layer. All signals on 0–5 scale. Scores ≥3.5 indicate high confidence for personalisation. These feed the Revenue Maximizer decision engine.</p>
		<div style="display:grid;grid-template-columns:repeat(4,1fr);gap:10px">
			<?php
			foreach ( $key_signals as $key => [$slabel, $scolor] ) :
				$val     = $signals[ $key ] ?? 0;
				$spct    = round( $val / 5 * 100 );
				$sstatus = gt_rev_signal_status( $val );
				$sicon   = $sstatus === 'Hot' ? '🔥' : ( $sstatus === 'Warm' ? '🌤' : '❄️' );
				?>
			<div style="background:#0d1f3c;border-radius:8px;padding:16px;text-align:center;border:1px solid rgba(255,255,255,0.04);transition:border-color .2s,transform .15s"
				onmouseover="this.style.borderColor='<?php echo esc_attr( $scolor ); ?>';this.style.transform='translateY(-2px)'"
				onmouseout="this.style.borderColor='rgba(255,255,255,0.04)';this.style.transform='translateY(0)'">
				<div style="font-size:24px;font-weight:800;color:<?php echo esc_attr( $scolor ); ?>;line-height:1"><?php echo esc_html( number_format( $val, 1 ) ); ?></div>
				<div style="margin:8px auto;width:<?php echo esc_attr( $spct ); ?>%;height:3px;background:<?php echo esc_attr( $scolor ); ?>;border-radius:3px;opacity:0.5;transition:width .4s ease"></div>
				<div style="font-size:11px;font-weight:600;color:#e2e8f0"><?php echo esc_html( $slabel ); ?></div>
				<div style="font-size:10px;color:#64748b;margin-top:2px"><?php echo esc_html( $sicon ); ?> <?php echo esc_html( $sstatus ); ?></div>
			</div>
			<?php endforeach; ?>
		</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">🔮 Revenue 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 period data. These show potential revenue impact of different growth strategies. Projections assume current AOV and discount rates remain constant.</p>
		<?php if ( ! empty( $whatif_revenue ) ) : ?>
		<div style="display:grid;grid-template-columns:repeat(2,1fr);gap:12px">
			<?php foreach ( $whatif_revenue 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 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 revenue data is collected in this period.</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">💡 Revenue Recommendations</h2>
	</div>
	<div style="display:flex;flex-direction:column;gap:10px">
		<?php if ( empty( $recommendations ) ) : ?>
		<div style="padding:14px 18px;background:rgba(34,197,94,0.04);border-radius:8px;font-size:13px;color:#86efac;line-height:1.5">
			<span style="color:#86efac">✓</span> Revenue metrics are within optimal ranges. Continue monitoring as data accumulates.
		</div>
		<?php else : ?>
			<?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; ?>
		<?php endif; ?>
	</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 = '\u25BC';
		}
	} else {
		body.classList.add('open');
		header.classList.add('open');
		if (chev) {
			chev.style.transform = 'rotate(180deg)';
			chev.textContent = '\u25B2';
		}
	}
}

// ═══════════════════════════════════════════════════════════════════════════════
// 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);
})();

// ═══════════════════════════════════════════════════════════════════════════════
// REVENUE TREND CHART — Chart.js dual-axis line chart
// ═══════════════════════════════════════════════════════════════════════════════
document.addEventListener('DOMContentLoaded', function() {
	var canvas = document.getElementById('rev-trend-chart');
	if (!canvas || typeof Chart === 'undefined') return;

	var ctx = canvas.getContext('2d');
	new Chart(ctx, {
		type: 'line',
		data: {
			labels: <?php echo wp_json_encode( $chart_labels ); ?>,
			datasets: [
				{
					label: 'Revenue ($)',
					data: <?php echo wp_json_encode( $chart_revenue ); ?>,
					borderColor: '#3b82f6',
					backgroundColor: 'rgba(59,130,246,0.05)',
					fill: true,
					tension: 0.3,
					pointRadius: 2,
					pointHoverRadius: 5,
					borderWidth: 2,
					yAxisID: 'y'
				},
				{
					label: 'Orders',
					data: <?php echo wp_json_encode( $chart_orders ); ?>,
					borderColor: '#22c55e',
					backgroundColor: 'rgba(34,197,94,0.05)',
					fill: true,
					tension: 0.3,
					pointRadius: 2,
					pointHoverRadius: 5,
					borderWidth: 2,
					yAxisID: 'y1'
				},
				{
					label: 'Discounts ($)',
					data: <?php echo wp_json_encode( $chart_disc ); ?>,
					borderColor: '#f59e0b',
					borderDash: [4, 2],
					fill: false,
					tension: 0.3,
					pointRadius: 1,
					pointHoverRadius: 3,
					borderWidth: 1.5,
					yAxisID: 'y'
				}
			]
		},
		options: {
			responsive: true,
			maintainAspectRatio: false,
			interaction: {
				mode: 'index',
				intersect: false
			},
			plugins: {
				legend: {
					labels: {
						color: '#94a3b8',
						usePointStyle: true,
						padding: 20,
						font: { size: 11 }
					}
				},
				tooltip: {
					backgroundColor: '#0f172a',
					titleColor: '#fff',
					bodyColor: '#94a3b8',
					borderColor: 'rgba(255,255,255,0.1)',
					borderWidth: 1,
					padding: 12
				}
			},
			scales: {
				x: {
					ticks: {
						color: '#475569',
						maxTicksLimit: 15,
						font: { size: 9 }
					},
					grid: {
						color: 'rgba(255,255,255,0.03)'
					}
				},
				y: {
					type: 'linear',
					display: true,
					position: 'left',
					title: {
						display: true,
						text: 'USD ($)',
						color: '#64748b'
					},
					ticks: {
						color: '#475569',
						font: { size: 10 },
						callback: function(value) {
							return '$' + value.toLocaleString();
						}
					},
					grid: {
						color: 'rgba(255,255,255,0.03)'
					}
				},
				y1: {
					type: 'linear',
					display: true,
					position: 'right',
					title: {
						display: true,
						text: 'Orders',
						color: '#64748b'
					},
					ticks: {
						color: '#475569',
						font: { size: 10 }
					},
					grid: {
						drawOnChartArea: false
					}
				}
			}
		}
	});
});
</script>

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