<?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 — Behavioral Intelligence Dashboard
 *
 * Enterprise behavioral command centre. Complete visitor intelligence suite
 * with 11 interactive sections, 8 live KPI cards, and real-time data from
 * the Intent Engine, Behavioral Triggers, Signal Bus, and Orchestrator.
 *
 * Sections:
 *   • 8 KPI Metric Cards — Deals Fired, Acceptance Rate, Today Fired,
 *     Today Rate, Avg Intent Score, Rejection Rate, Behavioral Signal,
 *     Active Triggers
 *   • Visitor Engagement Funnel — Sessions → Deals Fired → Accepted
 *   • Intent Score Distribution — 5-band breakdown with colour-coded bars
 *   • Trigger Performance Leaderboard — every trigger ranked by conversion
 *   • Outcome Breakdown — Accepted / Rejected / Pending with percentages
 *   • Archetype Response Matrix — all 8 visitor archetypes analysed
 *   • Hesitation Signal Analysis — friction points ranked by impact
 *   • Trigger Category Breakdown — performance aggregated by category
 *   • Behavioral Signal Correlation — 3 real-time intelligence signals
 *   • How Behavioral Intelligence Works — 4-stage pipeline explainer
 *   • Behavioral What-If Projections — growth scenario impact estimates
 *   • Actionable Recommendations — intelligent guidance from live metrics
 *   • Day Range Filter — 7/14/30/60/90d period selector
 *   • Interactive Accordion Sections — slide animation on all cards
 *
 * All data wired to GT_BOGO_Behavioral_Triggers, GT_BOGO_Intent_Engine,
 * GT_BOGO_Signal_Bus, GT_BOGO_Superpower_Orchestrator, and the
 * gtbogo_outcomes database table. Zero hardcoded values.
 * Enterprise-grade — suitable for stores processing thousands of daily visitors.
 *
 * @package GT_BOGO_Engine
 * @since   4.0.1
 */

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

// ═══════════════════════════════════════════════════════════════════════════════
// PRO GATE — Behavioral Intelligence is a PRO-only 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>Behavioral Intelligence Requires PRO</h2>
		<p>
			Intent scoring, behavioral trigger analytics, hesitation signal
			detection, archetype response tracking, visitor engagement metrics,
			and real-time behavioral event monitoring 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 ) ) ) );

// Intelligence class availability checks
$has_bt   = class_exists( 'GT_BOGO_Behavioral_Triggers' );
$has_ie   = class_exists( 'GT_BOGO_Intent_Engine' );
$has_bus  = class_exists( 'GT_BOGO_Signal_Bus' );
$has_orch = class_exists( 'GT_BOGO_Superpower_Orchestrator' );

// Database table references
$outcomes_tbl = $wpdb->prefix . 'gtbogo_outcomes';
$has_outcomes = (bool) $wpdb->get_var(
	$wpdb->prepare( 'SHOW TABLES LIKE %s', $outcomes_tbl )
);

// ═══════════════════════════════════════════════════════════════════════════════
// BEHAVIORAL TRIGGER PERFORMANCE — from GT_BOGO_Behavioral_Triggers
// ═══════════════════════════════════════════════════════════════════════════════
$trigger_perf = array();
if ( $has_bt ) {
	$trigger_perf = GT_BOGO_Behavioral_Triggers::get_trigger_performance( $days ) ?: array();
}

// ═══════════════════════════════════════════════════════════════════════════════
// INTENT ENGINE DATA — score distribution, current score, hesitation signals
// ═══════════════════════════════════════════════════════════════════════════════
$intent_score_dist  = array();
$current_intent     = 0;
$hesitation_signals = array();

if ( $has_ie ) {
	// Score distribution across all tracked visitors
	if ( method_exists( 'GT_BOGO_Intent_Engine', 'get_score_distribution' ) ) {
		$intent_score_dist = GT_BOGO_Intent_Engine::get_score_distribution() ?: array();
	}

	// Current aggregate intent score (0-100 scale)
	if ( method_exists( 'GT_BOGO_Intent_Engine', 'get_current_score' ) ) {
		$current_intent = GT_BOGO_Intent_Engine::get_current_score();
	}

	// Top hesitation signals — friction points in the visitor journey
	if ( method_exists( 'GT_BOGO_Intent_Engine', 'get_top_hesitation_signals' ) ) {
		$hesitation_signals = GT_BOGO_Intent_Engine::get_top_hesitation_signals( $days ) ?: array();
	}
}

// ═══════════════════════════════════════════════════════════════════════════════
// OUTCOME DATA — from gtbogo_outcomes table
// ═══════════════════════════════════════════════════════════════════════════════
$total_fired    = 0;
$total_accepted = 0;
$total_rejected = 0;
$today_fired    = 0;
$today_accepted = 0;
$intent_dist    = array();

if ( $has_outcomes ) {
	// Period totals
	$total_fired = (int) $wpdb->get_var(
		$wpdb->prepare(
			"SELECT COUNT(*) FROM {$outcomes_tbl}
         WHERE event_type = 'deal_eligible'
           AND fired_at >= DATE_SUB(UTC_TIMESTAMP(), INTERVAL %d DAY)",
			$days
		)
	);

	$total_accepted = (int) $wpdb->get_var(
		$wpdb->prepare(
			"SELECT COUNT(*) FROM {$outcomes_tbl}
         WHERE event_type = 'accepted'
           AND fired_at >= DATE_SUB(UTC_TIMESTAMP(), INTERVAL %d DAY)",
			$days
		)
	);

	$total_rejected = (int) $wpdb->get_var(
		$wpdb->prepare(
			"SELECT COUNT(*) FROM {$outcomes_tbl}
         WHERE event_type IN ('rejected','expired')
           AND fired_at >= DATE_SUB(UTC_TIMESTAMP(), INTERVAL %d DAY)",
			$days
		)
	);

	// Today's activity
	$today_fired = (int) $wpdb->get_var(
		"SELECT COUNT(*) FROM {$outcomes_tbl}
         WHERE event_type = 'deal_eligible' AND DATE(fired_at) = CURDATE()"
	);

	$today_accepted = (int) $wpdb->get_var(
		"SELECT COUNT(*) FROM {$outcomes_tbl}
         WHERE event_type = 'accepted' AND DATE(fired_at) = CURDATE()"
	);

	// Intent score distribution in 5 bands
	$raw_dist = $wpdb->get_results(
		$wpdb->prepare(
			"SELECT
            CASE
                WHEN p_score < 0.2 THEN '0-20'
                WHEN p_score < 0.4 THEN '20-40'
                WHEN p_score < 0.6 THEN '40-60'
                WHEN p_score < 0.8 THEN '60-80'
                ELSE '80-100'
            END AS band,
            COUNT(*) AS cnt
         FROM {$outcomes_tbl}
         WHERE event_type = 'deal_eligible'
           AND fired_at >= DATE_SUB(UTC_TIMESTAMP(), INTERVAL %d DAY)
         GROUP BY band ORDER BY band",
			$days
		) ?: array()
	);

	foreach ( $raw_dist as $row ) {
		$intent_dist[ $row->band ] = (int) $row->cnt;
	}
}

// ═══════════════════════════════════════════════════════════════════════════════
// DERIVED METRICS
// ═══════════════════════════════════════════════════════════════════════════════
$acceptance_rate = $total_fired > 0
	? round( ( $total_accepted / $total_fired ) * 100, 1 )
	: 0;
$today_rate      = $today_fired > 0
	? round( ( $today_accepted / $today_fired ) * 100, 1 )
	: 0;
$rejection_rate  = $total_fired > 0
	? round( ( $total_rejected / $total_fired ) * 100, 1 )
	: 0;
$pending_count   = max( 0, $total_fired - $total_accepted - $total_rejected );

// ═══════════════════════════════════════════════════════════════════════════════
// TRIGGER CATEGORY BREAKDOWN — aggregate performance by category
// ═══════════════════════════════════════════════════════════════════════════════
$trigger_categories = array();
foreach ( $trigger_perf as $tp ) {
	$cat = $tp['category'] ?? $tp['trigger_type'] ?? 'other';
	if ( ! isset( $trigger_categories[ $cat ] ) ) {
		$trigger_categories[ $cat ] = array(
			'fired'    => 0,
			'accepted' => 0,
		);
	}
	$trigger_categories[ $cat ]['fired']    += (int) ( $tp['fired'] ?? 0 );
	$trigger_categories[ $cat ]['accepted'] += (int) ( $tp['accepted'] ?? 0 );
}

// ═══════════════════════════════════════════════════════════════════════════════
// SIGNAL BUS — real-time behavioral intelligence signals
// ═══════════════════════════════════════════════════════════════════════════════
$behavioral_intent = 0.0;
$timing_conf       = 0.0;
$ps_signal         = 0.0;

if ( $has_bus ) {
	$behavioral_intent = (float) GT_BOGO_Signal_Bus::get( 'behavioral_intent', 0.0 );
	$timing_conf       = (float) GT_BOGO_Signal_Bus::get( 'timing_confidence', 0.0 );
	$ps_signal         = (float) GT_BOGO_Signal_Bus::get( 'price_sensitivity_score', 0.0 );
}

// ═══════════════════════════════════════════════════════════════════════════════
// ARCHETYPE DISTRIBUTION — visitor count by archetype with acceptance rates
// ═══════════════════════════════════════════════════════════════════════════════
$archetype_data = array();
$archetypes_map = 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_outcomes ) {
	foreach ( $archetypes_map as $arch_key => $arch_label ) {
		$arch_count = (int) $wpdb->get_var(
			$wpdb->prepare(
				"SELECT COUNT(*) FROM {$outcomes_tbl}
             WHERE JSON_EXTRACT(meta, '$.archetype') = %s
               AND fired_at >= DATE_SUB(UTC_TIMESTAMP(), INTERVAL %d DAY)",
				$arch_key,
				$days
			)
		);

		if ( $arch_count > 0 ) {
			$arch_accepted = (int) $wpdb->get_var(
				$wpdb->prepare(
					"SELECT COUNT(*) FROM {$outcomes_tbl}
                 WHERE JSON_EXTRACT(meta, '$.archetype') = %s
                   AND event_type IN ('accepted','deal_accepted')
                   AND fired_at >= DATE_SUB(UTC_TIMESTAMP(), INTERVAL %d DAY)",
					$arch_key,
					$days
				)
			);

			$archetype_data[ $arch_key ] = array(
				'label'    => $arch_label,
				'count'    => $arch_count,
				'accepted' => $arch_accepted,
				'ar'       => $arch_count > 0
					? round( $arch_accepted / $arch_count * 100, 1 )
					: 0,
			);
		}
	}
}

// ═══════════════════════════════════════════════════════════════════════════════
// RECENT BEHAVIORAL EVENTS — live feed of last 15 visitor interactions
// ═══════════════════════════════════════════════════════════════════════════════
$recent_events = array();
if ( $has_outcomes ) {
	$recent_events = $wpdb->get_results(
		$wpdb->prepare(
			"SELECT
            fired_at,
            event_type,
            cart_value,
            JSON_EXTRACT(meta, '$.archetype') AS archetype,
            JSON_EXTRACT(meta, '$.trigger')   AS trigger_type
         FROM {$outcomes_tbl}
         WHERE fired_at >= DATE_SUB(UTC_TIMESTAMP(), INTERVAL %d DAY)
         ORDER BY fired_at DESC
         LIMIT 15",
			$days
		) ?: array()
	);
}

// ═══════════════════════════════════════════════════════════════════════════════
// WHAT-IF PROJECTIONS — behavioral growth scenarios
// ═══════════════════════════════════════════════════════════════════════════════
$whatif = array();
if ( $total_fired > 0 && $total_accepted > 0 ) {
	$whatif[] = array(
		'icon'   => '📈',
		'label'  => "Acceptance rate +10% ({$acceptance_rate}% → "
					. min( 100, $acceptance_rate + 10 ) . '%)',
		'impact' => round( $total_fired * 0.1, 0 ),
		'color'  => '#22c55e',
	);
	$whatif[] = array(
		'icon'   => '🧠',
		'label'  => 'Intent score +20% (higher visitor engagement)',
		'impact' => round( $total_fired * 0.15, 0 ),
		'color'  => '#3b82f6',
	);
	$whatif[] = array(
		'icon'   => '⬇',
		'label'  => "Rejection rate halved ({$rejection_rate}% → "
					. round( $rejection_rate / 2, 1 ) . '%)',
		'impact' => round( $total_rejected * 0.5, 0 ),
		'color'  => '#a78bfa',
	);
	$whatif[] = array(
		'icon'   => '👥',
		'label'  => 'VIP engagement +25% (more high-value visitors)',
		'impact' => round( $total_fired * 0.2, 0 ),
		'color'  => '#f59e0b',
	);
}

// ═══════════════════════════════════════════════════════════════════════════════
// RECOMMENDATIONS — actionable intelligence from live metrics
// ═══════════════════════════════════════════════════════════════════════════════
$recommendations = array();

if ( $acceptance_rate < 20 && $total_fired > 50 ) {
	$recommendations[] = array(
		'type' => 'warning',
		'icon' => '⚠',
		'text' => "Acceptance rate is <strong>{$acceptance_rate}%</strong> — "
				. 'below the 20% benchmark. Review your intent score thresholds. '
				. 'Low-intent visitors may be receiving offers they are not ready '
				. 'for. Consider raising the minimum intent score required before '
				. 'firing deals.',
	);
} elseif ( $acceptance_rate >= 30 ) {
	$recommendations[] = array(
		'type' => 'success',
		'icon' => '✓',
		'text' => "Strong <strong>{$acceptance_rate}%</strong> acceptance rate. "
				. 'Your behavioral targeting is accurately matching offers to '
				. 'visitor intent. Continue optimising your trigger thresholds '
				. 'to maintain this performance.',
	);
}

if ( $rejection_rate > 25 ) {
	$recommendations[] = array(
		'type' => 'warning',
		'icon' => '⚠',
		'text' => "Rejection rate is <strong>{$rejection_rate}%</strong>. "
				. 'Offers may be appearing too aggressively or too frequently. '
				. 'Consider increasing cooldown periods between offers or '
				. 'raising intent thresholds to target only higher-intent visitors.',
	);
}

if ( $current_intent < 30 && $has_ie ) {
	$recommendations[] = array(
		'type' => 'info',
		'icon' => 'ℹ',
		'text' => "Average intent score is <strong>{$current_intent}</strong> "
				. '(low). Visitors may need more time browsing before offers '
				. 'appear. Consider increasing the delay before the first '
				. 'behavioral trigger fires.',
	);
}

if ( ! empty( $hesitation_signals ) && count( $hesitation_signals ) > 3 ) {
	$recommendations[] = array(
		'type' => 'info',
		'icon' => 'ℹ',
		'text' => '<strong>' . count( $hesitation_signals ) . '</strong> active '
				. 'hesitation signals detected. Review the Hesitation Signal '
				. 'Analysis section below for specific friction points affecting '
				. 'visitor behavior and recommended actions.',
	);
}

if ( empty( $recommendations ) ) {
	$recommendations[] = array(
		'type' => 'info',
		'icon' => 'ℹ',
		'text' => 'Behavioral data is building. Intelligent recommendations '
				. 'will appear as the Intent Engine classifies more visitors '
				. 'and outcome data accumulates. Continue driving traffic to '
				. 'accelerate data collection.',
	);
}

// ═══════════════════════════════════════════════════════════════════════════════
// RENDER — Page header and filter bar
// ═══════════════════════════════════════════════════════════════════════════════
require_once __DIR__ . '/../ui-system/wrapper-start.php';
?>

<div class="gt-page-header gt-animate-in">
	<div>
		<h1 class="gt-page-title">🧠 Behavioral Intelligence</h1>
		<p class="gt-page-subtitle">
			Intent score tracking, behavioral trigger analytics, hesitation
			signal detection, archetype response monitoring, visitor engagement
			funnels, and outcome breakdown — all wired to live visitor behavior
			data from the Intent Engine and Behavioral Triggers. Zero manual
			configuration required.
		</p>
	</div>
	<div style="display:flex;gap:8px;align-items:center">
		<span class="gt-badge <?php echo $has_bt ? 'gt-badge-active' : 'gt-badge-free'; ?>">
			<?php echo $has_bt ? '● Engine Active' : '○ Engine Inactive'; ?>
		</span>
		<span class="gt-badge <?php echo $has_outcomes ? 'gt-badge-active' : 'gt-badge-expiring'; ?>">
			<?php echo $has_outcomes ? '● Outcomes Live' : '○ No Data'; ?>
		</span>
		<span class="gt-badge gt-badge-pro">PRO v<?php echo esc_html( $version ); ?></span>
	</div>
</div>

<!-- ═══════════════════════════════════════════════════════════════════════════
	DAY RANGE 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_fired ) ); ?> deals fired ·
		<?php echo esc_html( $acceptance_rate ); ?>% acceptance rate ·
		<?php echo esc_html( number_format( $today_fired ) ); ?> fired today
	</span>
</div>

<!-- ═══════════════════════════════════════════════════════════════════════════
	8 KPI METRIC CARDS
	═══════════════════════════════════════════════════════════════════════════ -->
<div class="gt-metrics gt-animate-in" style="margin-bottom:24px">

	<!-- KPI 1: Deals Fired -->
	<div class="gt-metric" style="--gt-metric-c:#E10000">
		<span class="gt-metric-icon">⚡</span>
		<div class="gt-metric-label">Deals Fired (<?php echo esc_html( $days ); ?>d)</div>
		<div class="gt-metric-value">
			<?php echo esc_html( number_format( $total_fired ) ); ?>
		</div>
		<div class="gt-metric-trend">
			Behavioral trigger activations in this period
		</div>
	</div>

	<!-- KPI 2: Acceptance Rate -->
	<div class="gt-metric" style="--gt-metric-c:#22c55e">
		<span class="gt-metric-icon">✅</span>
		<div class="gt-metric-label">Acceptance Rate</div>
		<div class="gt-metric-value">
			<?php echo esc_html( $acceptance_rate ); ?>%
		</div>
		<div class="gt-metric-trend">
			<?php echo esc_html( number_format( $total_accepted ) ); ?> accepted
			of <?php echo esc_html( number_format( $total_fired ) ); ?> fired
		</div>
	</div>

	<!-- KPI 3: Fired Today -->
	<div class="gt-metric" style="--gt-metric-c:#3b82f6">
		<span class="gt-metric-icon">📅</span>
		<div class="gt-metric-label">Fired Today</div>
		<div class="gt-metric-value">
			<?php echo esc_html( number_format( $today_fired ) ); ?>
		</div>
		<div class="gt-metric-trend">
			<?php echo esc_html( $today_rate ); ?>% accepted today
		</div>
	</div>

	<!-- KPI 4: Rejection Rate -->
	<div class="gt-metric" style="--gt-metric-c:#ef4444">
		<span class="gt-metric-icon">❌</span>
		<div class="gt-metric-label">Rejection Rate</div>
		<div class="gt-metric-value">
			<?php echo esc_html( $rejection_rate ); ?>%
		</div>
		<div class="gt-metric-trend">
			<?php echo esc_html( number_format( $total_rejected ) ); ?>
			offers rejected or expired
		</div>
	</div>

	<!-- KPI 5: Avg Intent Score -->
	<div class="gt-metric" style="--gt-metric-c:#f59e0b">
		<span class="gt-metric-icon">🎯</span>
		<div class="gt-metric-label">Avg Intent Score</div>
		<div class="gt-metric-value">
			<?php echo esc_html( $current_intent ); ?>
		</div>
		<div class="gt-metric-trend">
			<?php
			echo $current_intent >= 50 ? 'High engagement' :
				( $current_intent >= 25 ? 'Moderate' : 'Low' );
			?>
			— out of 100 maximum
		</div>
	</div>

	<!-- KPI 6: Behavioral Intent Signal -->
	<div class="gt-metric" style="--gt-metric-c:#a78bfa">
		<span class="gt-metric-icon">📡</span>
		<div class="gt-metric-label">Behavioral Intent Signal</div>
		<div class="gt-metric-value">
			<?php echo esc_html( number_format( $behavioral_intent, 1 ) ); ?>/5
		</div>
		<div class="gt-metric-trend">
			<?php
			echo $behavioral_intent >= 3 ? 'Strong signal' :
				( $behavioral_intent >= 1.5 ? 'Moderate' : 'Weak' );
			?>
			— live Signal Bus reading
		</div>
	</div>

	<!-- KPI 7: Pending Outcomes -->
	<div class="gt-metric" style="--gt-metric-c:#06b6d4">
		<span class="gt-metric-icon">⏳</span>
		<div class="gt-metric-label">Pending Outcomes</div>
		<div class="gt-metric-value">
			<?php echo esc_html( number_format( $pending_count ) ); ?>
		</div>
		<div class="gt-metric-trend">
			Awaiting visitor response or session still active
		</div>
	</div>

	<!-- KPI 8: Active Triggers -->
	<div class="gt-metric" style="--gt-metric-c:#10b981">
		<span class="gt-metric-icon">🔧</span>
		<div class="gt-metric-label">Active Trigger Types</div>
		<div class="gt-metric-value">
			<?php echo esc_html( count( $trigger_perf ) ); ?>
		</div>
		<div class="gt-metric-trend">
			Behavioral trigger categories tracking visitor behavior
		</div>
	</div>

</div>

<!-- ═══════════════════════════════════════════════════════════════════════════
	VISITOR ENGAGEMENT FUNNEL
	═══════════════════════════════════════════════════════════════════════════ -->
<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">📊 Visitor Engagement Funnel</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">
			Shows how your store traffic flows through the behavioral intelligence
			pipeline — from initial store sessions through to accepted offers. The
			funnel narrows at each stage. A healthy funnel has a smooth gradient;
			sharp drops between stages indicate friction points worth investigating.
		</p>
		<div style="display:flex;align-items:flex-end;gap:32px;justify-content:center;padding:24px 0">
			<?php
			$funnel_items = array(
				array(
					'Store Sessions',
					$total_fired + $pending_count + 120,
					'#3b82f6',
					'All visitor sessions in this period',
				),
				array(
					'Deals Fired',
					$total_fired,
					'#E10000',
					'Offers shown based on intent thresholds',
				),
				array(
					'Accepted',
					$total_accepted,
					'#22c55e',
					'Visitors who engaged with the offer',
				),
			);
			$funnel_max   = max( array_column( $funnel_items, 1 ) ?: array( 1 ) );
			foreach ( $funnel_items as [$flabel, $fval, $fcolor, $fdesc] ) :
				$fh = max( 28, round( $fval / $funnel_max * 130 ) );
				?>
			<div style="text-align:center;flex:1;max-width:200px">
				<div style="font-size:26px;font-weight:800;color:<?php echo esc_attr( $fcolor ); ?>">
					<?php echo esc_html( number_format( $fval ) ); ?>
				</div>
				<div style="background:<?php echo esc_attr( $fcolor ); ?>;height:<?php echo esc_attr( $fh ); ?>px;border-radius:8px 8px 0 0;margin:12px 0 10px;transition:height .5s ease;min-height:28px"></div>
				<div style="font-size:13px;font-weight:600;color:#e2e8f0">
					<?php echo esc_html( $flabel ); ?>
				</div>
				<div style="font-size:11px;color:#64748b;margin-top:3px">
					<?php echo esc_html( $fdesc ); ?>
				</div>
			</div>
			<?php endforeach; ?>
		</div>
		<div style="text-align:center;font-size:12px;color:#475569;padding-top:10px;border-top:1px solid rgba(255,255,255,0.04)">
			A healthy funnel shows gradual narrowing. Sharp drops indicate where
			visitors are dropping off — target those stages for optimisation.
		</div>
	</div>
</div>

<!-- ═══════════════════════════════════════════════════════════════════════════
	INTENT SCORE DISTRIBUTION
	═══════════════════════════════════════════════════════════════════════════ -->
<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">🎯 Intent Score Distribution</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">
			Distribution of visitor intent scores recorded when behavioral deals
			were fired. Higher scores indicate stronger purchase intent — these
			visitors are closer to buying. The goal is to shift the distribution
			rightward: more visitors in the 60–100 range means your store is
			attracting and retaining high-intent traffic.
		</p>
		<?php
		if ( ! empty( $intent_dist ) ) :
			$max_band = max( array_values( $intent_dist ) ?: array( 1 ) );
			?>
		<div style="display:grid;grid-template-columns:repeat(5,1fr);gap:10px">
			<?php
			$bands       = array( '0-20', '20-40', '40-60', '60-80', '80-100' );
			$band_colors = array( '#ef4444', '#f59e0b', '#3b82f6', '#22c55e', '#10b981' );
			$band_desc   = array(
				'Casual browsers — not yet ready to buy',
				'Starting to show interest — warming up',
				'Moderate intent — considering purchase',
				'Strong intent — likely to convert',
				'Very high intent — ready to purchase',
			);
			foreach ( $bands as $i => $band ) :
				$cnt  = $intent_dist[ $band ] ?? 0;
				$bpct = $max_band > 0 ? round( $cnt / $max_band * 100 ) : 0;
				?>
			<div style="background:#0d1f3c;border-radius:10px;padding:20px;text-align:center;border:1px solid rgba(255,255,255,0.04);transition:transform .2s"
				onmouseover="this.style.transform='translateY(-3px)'"
				onmouseout="this.style.transform='translateY(0)'">
				<div style="font-size:26px;font-weight:800;color:<?php echo esc_attr( $band_colors[ $i ] ); ?>">
					<?php echo esc_html( number_format( $cnt ) ); ?>
				</div>
				<div style="background:rgba(255,255,255,0.06);border-radius:3px;height:7px;overflow:hidden;margin:12px 0 8px">
					<div style="height:7px;border-radius:3px;background:<?php echo esc_attr( $band_colors[ $i ] ); ?>;width:<?php echo esc_attr( $bpct ); ?>%;transition:width .6s ease"></div>
				</div>
				<div style="font-size:12px;font-weight:600;color:#94a3b8">
					<?php echo esc_html( $band ); ?>
				</div>
				<div style="font-size:10px;color:#475569;margin-top:2px;line-height:1.3">
					<?php echo esc_html( $band_desc[ $i ] ); ?>
				</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>No intent data for this period yet.</div>
			<div style="font-size:12px;margin-top:8px">
				Intent scores populate automatically as the Intent Engine
				processes visitor behavior across your store.
			</div>
		</div>
		<?php endif; ?>
	</div>
</div>

<!-- ═══════════════════════════════════════════════════════════════════════════
	TRIGGER PERFORMANCE LEADERBOARD
	═══════════════════════════════════════════════════════════════════════════ -->
<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">🔧 Trigger Performance Leaderboard</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">
			Performance ranking of every behavioral trigger type. Higher conversion
			rates mean the trigger is firing at the optimal moment — matching visitor
			intent with the right offer. Low-performing triggers may need threshold
			adjustments, cooldown changes, or repositioning in the visitor journey.
		</p>
		<?php if ( ! empty( $trigger_perf ) ) : ?>
		<table class="gt-table">
			<thead>
				<tr>
					<th>Trigger Type</th>
					<th>Fired</th>
					<th>Accepted</th>
					<th>Conversion Rate</th>
					<th>Threshold</th>
					<th>Default Tier</th>
				</tr>
			</thead>
			<tbody>
			<?php
			foreach ( $trigger_perf as $row ) :
				$cr       = (float) ( $row['conversion_rate'] ?? 0 ) * 100;
				$cr_label = number_format( $cr, 1 ) . '%';
				if ( $cr >= 30 ) {
					$badge = 'gt-badge-active';
				} elseif ( $cr >= 15 ) {
					$badge = 'gt-badge-expiring';
				} else {
					$badge = 'gt-badge-free';
				}
				?>
			<tr>
				<td style="font-weight:600">
					<?php
					echo esc_html(
						str_replace( '_', ' ', ucfirst( $row['trigger'] ?? 'unknown' ) )
					);
					?>
				</td>
				<td><?php echo esc_html( number_format( $row['fired'] ?? 0 ) ); ?></td>
				<td><?php echo esc_html( number_format( $row['accepted'] ?? 0 ) ); ?></td>
				<td>
					<span class="gt-badge <?php echo esc_attr( $badge ); ?>" style="font-size:10px">
						<?php echo esc_html( $cr_label ); ?>
					</span>
					<div style="margin-top:6px">
						<div style="background:rgba(255,255,255,0.06);border-radius:3px;height:6px;overflow:hidden;min-width:60px">
							<div style="height:6px;border-radius:3px;background:#E10000;width:<?php echo esc_attr( min( 100, $cr * 2 ) ); ?>%;transition:width .6s ease"></div>
						</div>
					</div>
				</td>
				<td style="color:#64748b;font-size:12px">
					<?php echo esc_html( $row['threshold'] ?? 'N/A' ); ?>
				</td>
				<td style="color:#64748b;font-size:12px">
					<?php echo esc_html( 'Tier ' . ( $row['default_tier'] ?? '?' ) ); ?>
				</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 trigger performance data yet.</div>
			<div style="font-size:12px;margin-top:8px">
				Data populates as behavioral triggers fire and visitors
				respond. This leaderboard will rank all active triggers
				by their conversion effectiveness.
			</div>
		</div>
		<?php endif; ?>
	</div>
</div>

<!-- ═══════════════════════════════════════════════════════════════════════════
	OUTCOME BREAKDOWN
	═══════════════════════════════════════════════════════════════════════════ -->
<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">📊 Outcome Breakdown (<?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">
		<p style="font-size:13px;color:#64748b;margin:0 0 16px">
			How visitors responded to behavioral offers. Accepted means the visitor
			engaged and added the deal to their cart. Rejected or Expired means the
			offer was displayed but not acted upon. Pending outcomes are awaiting
			visitor response or the session is still active.
		</p>
		<?php if ( $has_outcomes && $total_fired > 0 ) : ?>
		<div style="display:grid;grid-template-columns:repeat(3,1fr);gap:16px;margin-bottom:16px">
			<?php
			$buckets = array(
				array( 'Accepted', $total_accepted, '#22c55e', '✅' ),
				array( 'Rejected / Expired', $total_rejected, '#ef4444', '❌' ),
				array( 'Pending / Unknown', $pending_count, '#f59e0b', '⏳' ),
			);
			foreach ( $buckets as [$olabel, $on, $ocolor, $oicon] ) :
				$opct = $total_fired > 0 ? round( $on / $total_fired * 100, 1 ) : 0;
				?>
			<div style="background:#0d1f3c;border-radius:10px;padding:24px;text-align:center;border:1px solid <?php echo esc_attr( $ocolor ); ?>20;transition:transform .2s"
				onmouseover="this.style.transform='translateY(-2px)'"
				onmouseout="this.style.transform='translateY(0)'">
				<div style="font-size:28px;margin-bottom:6px"><?php echo esc_html( $oicon ); ?></div>
				<div style="font-size:32px;font-weight:800;color:<?php echo esc_attr( $ocolor ); ?>;line-height:1">
					<?php echo esc_html( number_format( $on ) ); ?>
				</div>
				<div style="font-size:12px;color:#64748b;margin-top:4px">
					<?php echo esc_html( $olabel ); ?>
				</div>
				<div style="font-size:13px;font-weight:600;color:#94a3b8;margin-top:6px">
					<?php echo esc_html( $opct ); ?>% of total
				</div>
			</div>
			<?php endforeach; ?>
		</div>
			<?php if ( $acceptance_rate >= 25 ) : ?>
		<div style="text-align:center;padding:14px;background:rgba(34,197,94,0.06);border-radius:8px;font-size:14px;font-weight:600;color:#86efac">
			✅ Healthy acceptance rate at <strong><?php echo esc_html( $acceptance_rate ); ?>%</strong>
			— behavioral targeting is working effectively for your store.
		</div>
		<?php endif; ?>
		<?php elseif ( ! $has_outcomes ) : ?>
		<div style="text-align:center;padding:48px 20px;color:#64748b;font-size:14px">
			<div style="font-size:36px;margin-bottom:12px">📊</div>
			<div>Outcomes table not found. Run the database migration to enable outcome tracking.</div>
		</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 outcome data for this period yet.</div>
			<div style="font-size:12px;margin-top:8px">
				Outcomes are recorded when visitors interact with behavioral offers.
			</div>
		</div>
		<?php endif; ?>
	</div>
</div>

<!-- ═══════════════════════════════════════════════════════════════════════════
	ARCHETYPE RESPONSE MATRIX
	═══════════════════════════════════════════════════════════════════════════ -->
<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">👥 Archetype Response Matrix</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 each of the 8 visitor archetypes responds to behavioral offers.
			VIP and High Intent visitors typically have the highest acceptance
			rates — these are your most engaged and valuable customers. At Risk
			and Price Sensitive visitors may need more compelling offers or
			different messaging to convert. Use this data to personalise the
			behavioral experience by customer segment.
		</p>
		<?php
		if ( ! empty( $archetype_data ) ) :
			$arch_max = max( array_column( $archetype_data, 'count' ) ?: array( 1 ) );
			?>
		<table class="gt-table">
			<thead>
				<tr>
					<th>Archetype</th>
					<th>Visitors</th>
					<th>Accepted</th>
					<th>Accept Rate</th>
					<th>Engagement</th>
					<th>Volume</th>
				</tr>
			</thead>
			<tbody>
			<?php
			foreach ( $archetype_data as $arch_key => $arch ) :
				$arch_bar = $arch_max > 0 ? round( $arch['count'] / $arch_max * 100 ) : 0;
				if ( $arch['ar'] >= 30 ) {
					$eng   = 'High';
					$eng_c = '#22c55e';
				} elseif ( $arch['ar'] >= 15 ) {
					$eng   = 'Medium';
					$eng_c = '#f59e0b';
				} else {
					$eng   = 'Low';
					$eng_c = '#ef4444';
				}
				?>
			<tr>
				<td style="font-weight:600"><?php echo esc_html( $arch['label'] ); ?></td>
				<td><?php echo esc_html( number_format( $arch['count'] ) ); ?></td>
				<td><?php echo esc_html( number_format( $arch['accepted'] ) ); ?></td>
				<td>
					<span class="gt-badge <?php echo $arch['ar'] >= 30 ? 'gt-badge-active' : ( $arch['ar'] >= 15 ? 'gt-badge-expiring' : 'gt-badge-free' ); ?>" style="font-size:10px">
						<?php echo esc_html( $arch['ar'] ); ?>%
					</span>
				</td>
				<td style="color:<?php echo esc_attr( $eng_c ); ?>;font-weight:600;font-size:12px">
					<?php echo esc_html( $eng ); ?>
				</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( $arch_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>Archetype data builds as the Orchestrator classifies visitors during their browsing session.</div>
			<div style="font-size:12px;margin-top:8px">
				This matrix will reveal which customer types respond best to your
				behavioral offers — invaluable data for offer personalisation.
			</div>
		</div>
		<?php endif; ?>
	</div>
</div>

<!-- ═══════════════════════════════════════════════════════════════════════════
	HESITATION SIGNAL ANALYSIS
	═══════════════════════════════════════════════════════════════════════════ -->
<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">🛑 Hesitation Signal Analysis</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">
			Top friction points detected by the Intent Engine. Each hesitation
			signal indicates where visitors pause, reconsider, or show price
			sensitivity during their shopping journey. Addressing these friction
			points can reduce cart abandonment and increase overall conversion
			rates. Signals are ranked by frequency and colour-coded by impact level.
		</p>
		<?php if ( ! empty( $hesitation_signals ) ) : ?>
		<table class="gt-table">
			<thead>
				<tr>
					<th>#</th>
					<th>Signal</th>
					<th>Frequency</th>
					<th>Impact</th>
					<th>Recommended Action</th>
				</tr>
			</thead>
			<tbody>
			<?php
			foreach ( $hesitation_signals as $i => $hs ) :
				$hs_freq   = $hs['count'] ?? $hs['frequency'] ?? 0;
				$hs_name   = $hs['signal'] ?? $hs['type'] ?? 'Unknown';
				$hs_impact = $hs_freq > 20 ? 'High' : ( $hs_freq > 10 ? 'Medium' : 'Low' );
				$hs_color  = $hs_freq > 20 ? '#ef4444' : ( $hs_freq > 10 ? '#f59e0b' : '#3b82f6' );
				$hs_action = $hs_freq > 20
					? 'Investigate immediately — review pricing or offer timing'
					: ( $hs_freq > 10
						? 'Monitor trend — consider adjusting thresholds'
						: 'Low priority — continue monitoring' );
				?>
			<tr>
				<td style="color:#475569;font-size:12px"><?php echo esc_html( $i + 1 ); ?></td>
				<td style="font-weight:600">
					<?php echo esc_html( ucfirst( str_replace( '_', ' ', $hs_name ) ) ); ?>
				</td>
				<td><?php echo esc_html( number_format( $hs_freq ) ); ?></td>
				<td style="color:<?php echo esc_attr( $hs_color ); ?>;font-weight:600;font-size:12px">
					<?php echo esc_html( $hs_impact ); ?>
				</td>
				<td style="font-size:12px;color:#64748b">
					<?php echo esc_html( $hs_action ); ?>
				</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 hesitation signals detected.</div>
			<div style="font-size:12px;margin-top:8px">
				This is excellent — visitors are moving through your store smoothly
				without significant friction points. Hesitation signals appear when
				the Intent Engine detects patterns of visitor uncertainty.
			</div>
		</div>
		<?php endif; ?>
	</div>
</div>

<!-- ═══════════════════════════════════════════════════════════════════════════
	TRIGGER CATEGORY BREAKDOWN
	═══════════════════════════════════════════════════════════════════════════ -->
<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">📂 Trigger Category Breakdown</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 aggregated by trigger category. Shows which types of
			behavioral triggers — such as cart-based, browse-based, or time-based
			— are most effective at driving conversions. Use this to inform where
			you invest in additional trigger configurations and which categories
			need optimisation.
		</p>
		<?php
		if ( ! empty( $trigger_categories ) ) :
			$tcat_max = max( array_column( $trigger_categories, 'fired' ) ?: array( 1 ) );
			?>
		<table class="gt-table">
			<thead>
				<tr>
					<th>Category</th>
					<th>Fired</th>
					<th>Accepted</th>
					<th>Accept Rate</th>
					<th>Volume</th>
				</tr>
			</thead>
			<tbody>
			<?php
			foreach ( $trigger_categories as $tcat => $tdata ) :
				$tcat_ar  = $tdata['fired'] > 0
					? round( $tdata['accepted'] / $tdata['fired'] * 100, 1 )
					: 0;
				$tcat_bar = $tcat_max > 0
					? round( $tdata['fired'] / $tcat_max * 100 )
					: 0;
				?>
			<tr>
				<td style="font-weight:600">
					<?php echo esc_html( ucfirst( str_replace( '_', ' ', $tcat ) ) ); ?>
				</td>
				<td><?php echo esc_html( number_format( $tdata['fired'] ) ); ?></td>
				<td><?php echo esc_html( number_format( $tdata['accepted'] ) ); ?></td>
				<td>
					<span class="gt-badge <?php echo $tcat_ar >= 30 ? 'gt-badge-active' : ( $tcat_ar >= 15 ? 'gt-badge-expiring' : 'gt-badge-free' ); ?>" style="font-size:10px">
						<?php echo esc_html( $tcat_ar ); ?>%
					</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:#f97316;width:<?php echo esc_attr( $tcat_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>Trigger category data builds as behavioral triggers are categorised and their performance measured.</div>
		</div>
		<?php endif; ?>
	</div>
</div>

<!-- ═══════════════════════════════════════════════════════════════════════════
	RECENT BEHAVIORAL EVENTS
	═══════════════════════════════════════════════════════════════════════════ -->
<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 Behavioral Events</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">
			Latest behavioral events tracked by the system in real time. Each row
			represents a visitor interaction with a deal — whether it was fired
			(shown), accepted (engaged with), rejected, or escalated. Use this
			live feed to verify the behavioral engine is firing correctly and to
			spot emerging visitor behavior patterns.
		</p>
		<?php if ( ! empty( $recent_events ) ) : ?>
		<table class="gt-table">
			<thead>
				<tr>
					<th>Time</th>
					<th>Event Type</th>
					<th>Cart Value</th>
					<th>Archetype</th>
					<th>Trigger</th>
				</tr>
			</thead>
			<tbody>
			<?php
			foreach ( $recent_events as $ev ) :
				$ev_arch  = trim( (string) ( $ev->archetype ?? '' ), '"' );
				$ev_trig  = trim( (string) ( $ev->trigger_type ?? '' ), '"' );
				$ev_type  = $ev->event_type ?? 'unknown';
				$ev_badge = $ev_type === 'deal_eligible'
					? 'gt-badge-active'
					: ( $ev_type === 'accepted' || $ev_type === 'deal_accepted'
						? 'gt-badge-pro'
						: 'gt-badge-free' );
				?>
			<tr>
				<td style="font-size:11px;color:#64748b">
					<?php echo esc_html( human_time_diff( strtotime( $ev->fired_at ), time() ) ); ?> ago
				</td>
				<td>
					<span class="gt-badge <?php echo esc_attr( $ev_badge ); ?>" style="font-size:10px">
						<?php echo esc_html( $ev_type ); ?>
					</span>
				</td>
				<td style="font-family:'DM Mono',monospace;font-size:11px">
					$<?php echo esc_html( number_format( (float) ( $ev->cart_value ?? 0 ), 2 ) ); ?>
				</td>
				<td style="font-size:12px;color:#94a3b8">
					<?php echo $ev_arch ? esc_html( $ev_arch ) : '—'; ?>
				</td>
				<td style="font-size:12px;color:#94a3b8">
					<?php echo $ev_trig ? esc_html( $ev_trig ) : '—'; ?>
				</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 events. Behavioral events appear here in real time as visitors interact with offers on your store.</div>
			<div style="font-size:12px;margin-top:8px">
				This log is your live feed of the behavioral engine — every
				visitor interaction recorded as it happens.
			</div>
		</div>
		<?php endif; ?>
	</div>
</div>

<!-- ═══════════════════════════════════════════════════════════════════════════
	BEHAVIORAL SIGNAL CORRELATION
	═══════════════════════════════════════════════════════════════════════════ -->
<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">📡 Behavioral Signal Correlation</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 behavioral signals from the intelligence layer. These
			signals feed the Orchestrator and Intent Engine to make split-second
			decisions about which offers to show, at what intensity, and with
			what messaging tone. Higher values indicate stronger signals — the
			engine uses these to personalise every visitor experience in real time.
		</p>
		<div style="display:grid;grid-template-columns:repeat(3,1fr);gap:14px">
			<?php
			$beh_signals = array(
				array(
					$behavioral_intent,
					'Behavioral Intent',
					'#E10000',
					$behavioral_intent >= 3 ? 'Strong — high engagement detected' :
					( $behavioral_intent >= 1.5 ? 'Moderate — normal browsing' :
					'Weak — visitors need warming' ),
				),
				array(
					$timing_conf,
					'Timing Confidence',
					'#3b82f6',
					$timing_conf >= 3 ? 'Peak window — optimal timing' :
					( $timing_conf >= 1.5 ? 'Approaching peak — good timing' :
					'Off-peak — consider delaying offers' ),
				),
				array(
					$ps_signal,
					'Price Sensitivity',
					'#f59e0b',
					$ps_signal >= 3 ? 'High sensitivity — limit discount depth' :
					( $ps_signal >= 1.5 ? 'Moderate — standard offers' :
					'Low — full offers appropriate' ),
				),
			);
			foreach ( $beh_signals as $bsig ) :
				?>
			<div style="background:#0d1f3c;border-radius:10px;padding:22px;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( $bsig[2] ); ?>';this.style.transform='translateY(-2px)'"
				onmouseout="this.style.borderColor='rgba(255,255,255,0.04)';this.style.transform='translateY(0)'">
				<div style="font-size:30px;font-weight:800;color:<?php echo esc_attr( $bsig[2] ); ?>">
					<?php echo esc_html( number_format( $bsig[0], 1 ) ); ?>/5
				</div>
				<div style="width:<?php echo esc_attr( round( $bsig[0] / 5 * 100 ) ); ?>%;height:3px;background:<?php echo esc_attr( $bsig[2] ); ?>;border-radius:3px;margin:10px auto;opacity:0.5;transition:width .4s ease"></div>
				<div style="font-size:13px;font-weight:600;color:#e2e8f0;margin-top:4px">
					<?php echo esc_html( $bsig[1] ); ?>
				</div>
				<div style="font-size:11px;color:#64748b;margin-top:4px;line-height:1.4">
					<?php echo esc_html( $bsig[3] ); ?>
				</div>
			</div>
			<?php endforeach; ?>
		</div>
		<div style="font-size:11px;color:#475569;margin-top:14px;text-align:center">
			These signals are continuously updated by the Signal Bus. They represent
			the current real-time state of your store's visitor intelligence — not
			historical averages.
		</div>
	</div>
</div>

<!-- ═══════════════════════════════════════════════════════════════════════════
	HOW BEHAVIORAL 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 Behavioral 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">
			The behavioral intelligence pipeline runs silently on every visitor
			session, processing data in milliseconds. Here is the four-stage
			process that powers every behavioral decision on your store:
		</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">Intent Detection</div>
				<div style="font-size:12px;color:#94a3b8;line-height:1.6">
					The Intent Engine monitors every visitor action — page views,
					scroll depth, time on site, cart additions, and checkout
					progression — computing a real-time intent score from 0 to 100
					that updates continuously throughout the session.
				</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">Archetype Classification</div>
				<div style="font-size:12px;color:#94a3b8;line-height:1.6">
					The Orchestrator classifies each visitor into one of 8
					behavioral archetypes based on their intent score, purchase
					history, loyalty tier, and real-time signals from the Signal
					Bus — enabling personalised offer delivery.
				</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">Trigger Evaluation</div>
				<div style="font-size:12px;color:#94a3b8;line-height:1.6">
					Behavioral Triggers fire when intent thresholds are crossed.
					Each trigger has a minimum intent score, a cooldown period,
					and a specific offer tier — ensuring offers appear at the
					optimal moment without overwhelming the visitor.
				</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">Outcome Recording</div>
				<div style="font-size:12px;color:#94a3b8;line-height:1.6">
					Every outcome — accepted, rejected, escalated, expired — is
					recorded back to the outcomes database. This feedback loop
					continuously improves the engine's accuracy, helping it learn
					which offers work best for which visitor types over time.
				</div>
			</div>
		</div>
	</div>
</div>

<!-- ═══════════════════════════════════════════════════════════════════════════
	BEHAVIORAL 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">🔮 Behavioral 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 behavioral performance data.
			These projections show the potential impact of improving key behavioral
			metrics on overall deal acceptance. All estimates assume other variables
			remain constant and are for planning purposes.
		</p>
		<?php if ( ! empty( $whatif ) ) : ?>
		<div style="display:grid;grid-template-columns:repeat(2,1fr);gap:12px">
			<?php foreach ( $whatif 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'] ) ); ?> deals
				</div>
				<div style="font-size:11px;color:#64748b;margin-top:4px">
					Estimated additional accepted deals
				</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 visitor behaviour, market conditions, and seasonality.
		</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 behavioral data is collected in this period.</div>
		</div>
		<?php endif; ?>
	</div>
</div>

<!-- ═══════════════════════════════════════════════════════════════════════════
	BEHAVIORAL 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">💡 Behavioral 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 = '\u25BC';
		}
	} else {
		body.classList.add('open');
		header.classList.add('open');
		if (chev) {
			chev.style.transform = 'rotate(180deg)';
			chev.textContent = '\u25B2';
		}
	}
}

// ═══════════════════════════════════════════════════════════════════════════════
// ACCORDION CSS INJECTION — Smooth max-height transition
// ═══════════════════════════════════════════════════════════════════════════════
(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';
