<?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 — Discount Intelligence Dashboard
 *
 * Enterprise discount command centre. Complete discount analytics suite:
 *
 *   • 8 KPI metric cards with live outcome data
 *   • Acceptance funnel visualisation (Eligible → Escalated → Accepted)
 *   • Daily trend chart (eligible, accepted, avg deal value)
 *   • Full discount distribution table (eligible, accepted, AR, escalated,
 *     avg cart, avg deal, revenue, volume bar)
 *   • Segment response matrix — how each customer archetype responds
 *   • Category discount response — which product categories convert best
 *   • Time-of-day heatmap — peak discount acceptance hours
 *   • Savings optimisation report — avg tier given, escalations, gap
 *   • Discount tier configuration cards with learned minimum indicator
 *   • Escalation path analysis — steps before acceptance
 *   • Rule-level discount efficiency table
 *   • Conversion Guard monitoring with recent suppression event log
 *   • Cart Value Intelligence band display with current margin ratio
 *   • Intelligence signal correlation (Price Sensitivity, Revenue Health,
 *     LTV Score, Cohort Performance)
 *   • What-if projections (min tier all, AR +10%, halved escalations)
 *   • Actionable recommendations based on current metrics
 *   • Day range filter (7/14/30/60/90d) with period comparison
 *   • Interactive accordion sections with slide animation
 *
 * All data wired to gtbogo_outcomes, gtbogo_analytics, and gtbogo_rules
 * tables. Uses Discount Discovery, Cart Value Intelligence, Conversion
 * Guard, Price Sensitivity, and Signal Bus intelligence classes.
 *
 * @package GT_BOGO_Engine
 * @since   4.0.1
 */

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

// ═══════════════════════════════════════════════════════════════════════════════
// PRO GATE
// ═══════════════════════════════════════════════════════════════════════════════
$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>Discount Intelligence Requires PRO</h2>
		<p>Discount tier optimisation, margin guard monitoring, Cart Value Intelligence,
			savings reports, conversion guard analytics, segment response analysis,
			escalation path tracking, category response breakdowns, time-of-day
			heatmaps, what-if projections, and intelligent recommendations are
			PRO features.</p>
		<div class="gt-flex">
			<a href="<?php echo esc_url( admin_url( 'admin.php?page=gt-bogo-engine&tab=license' ) ); ?>"
				class="gt-btn gt-btn-primary">Activate PRO</a>
			<a href="https://graphictshirts.shop/bogo/" class="gt-btn gt-btn-ghost"
				target="_blank" rel="noopener">Learn More</a>
		</div>
	</div>
	<?php
	require_once __DIR__ . '/../ui-system/wrapper-end.php';
	return;
}

// ═══════════════════════════════════════════════════════════════════════════════
// CONSTANTS & GLOBALS
// ═══════════════════════════════════════════════════════════════════════════════
global $wpdb;
$version = defined( 'GT_BOGO_VERSION' ) ? GT_BOGO_VERSION : '4.0.1';

// Day range filters with bounds checking
$days_raw        = isset( $_GET['days'] ) ? (int) $_GET['days'] : 30;
$days            = max( 7, min( 90, $days_raw ) );
$comparison_raw  = isset( $_GET['compare'] ) ? (int) $_GET['compare'] : 14;
$comparison_days = max( 7, min( 90, $comparison_raw ) );

// Table references
$outcomes_tbl  = $wpdb->prefix . 'gtbogo_outcomes';
$analytics_tbl = $wpdb->prefix . 'gtbogo_analytics';
$rules_tbl     = $wpdb->prefix . 'gtbogo_rules';
$has_outcomes  = (bool) $wpdb->get_var(
	$wpdb->prepare( 'SHOW TABLES LIKE %s', $outcomes_tbl )
);
$has_analytics = (bool) $wpdb->get_var(
	$wpdb->prepare( 'SHOW TABLES LIKE %s', $analytics_tbl )
);
$has_rules     = (bool) $wpdb->get_var(
	$wpdb->prepare( 'SHOW TABLES LIKE %s', $rules_tbl )
);

// Intelligence class availability
$has_dd        = class_exists( 'GT_BOGO_Discount_Discovery' );
$has_cvi       = class_exists( 'GT_BOGO_Cart_Value_Intelligence' );
$has_guard     = class_exists( 'GT_BOGO_Conversion_Guard' );
$has_ps        = class_exists( 'GT_BOGO_Price_Sensitivity' );
$has_analytics = class_exists( 'GT_BOGO_Analytics' );
$has_bus       = class_exists( 'GT_BOGO_Signal_Bus' );
$has_oc        = class_exists( 'GT_BOGO_Outcome_Capture' );

// ═══════════════════════════════════════════════════════════════════════════════
// DISCOUNT DISCOVERY TIERS
// ═══════════════════════════════════════════════════════════════════════════════
$tiers        = array();
$learned_min  = 1;
$min_tier_pct = 5;

if ( $has_dd ) {
	if ( method_exists( 'GT_BOGO_Discount_Discovery', 'get_tiers' ) ) {
		$tiers = GT_BOGO_Discount_Discovery::get_tiers() ?: array();
	}
	if ( method_exists( 'GT_BOGO_Discount_Discovery', 'get_learned_minimum_tier' ) ) {
		$learned_min = (int) GT_BOGO_Discount_Discovery::get_learned_minimum_tier( '' );
	}
}

// Default tier configuration if none stored
if ( empty( $tiers ) ) {
	$tiers = array(
		1 => 5,
		2 => 10,
		3 => 15,
		4 => 20,
		5 => 25,
	);
}

$min_tier_pct = $tiers[ $learned_min ] ?? ( $tiers[1] ?? 5 );

// ═══════════════════════════════════════════════════════════════════════════════
// SAVINGS REPORT (from Discount Discovery)
// ═══════════════════════════════════════════════════════════════════════════════
$savings_report     = array();
$avg_tier_given     = null;
$avg_discount_given = 0.0;
$avg_escalations    = 0.0;
$gap_pct            = 0.0;
$potential_savings  = '';

if ( $has_dd && method_exists( 'GT_BOGO_Discount_Discovery', 'get_savings_report' ) ) {
	$savings_report     = GT_BOGO_Discount_Discovery::get_savings_report( $days ) ?: array();
	$avg_tier_given     = $savings_report['avg_tier_given'] ?? null;
	$avg_discount_given = (float) ( $savings_report['avg_discount_given'] ?? 0 );
	$avg_escalations    = (float) ( $savings_report['avg_escalations'] ?? 0 );
	$gap_pct            = (float) ( $savings_report['gap_pct'] ?? 0 );
	$potential_savings  = $savings_report['potential_savings'] ?? '';
}

// ═══════════════════════════════════════════════════════════════════════════════
// CONVERSION GUARD REPORT
// ═══════════════════════════════════════════════════════════════════════════════
$guard_report  = array();
$block_rate    = 0.0;
$deals_blocked = 0;
$deals_total_g = 0;

if ( $has_guard && method_exists( 'GT_BOGO_Conversion_Guard', 'get_guard_report' ) ) {
	$guard_report  = GT_BOGO_Conversion_Guard::get_guard_report( $days ) ?: array();
	$block_rate    = (float) ( $guard_report['block_rate'] ?? 0 );
	$deals_blocked = (int) ( $guard_report['deals_saved'] ?? 0 );
	$deals_total_g = (int) ( $guard_report['total_events'] ?? 0 );
}

// ═══════════════════════════════════════════════════════════════════════════════
// OUTCOME ANALYSIS: CORE DISTRIBUTION
// ═══════════════════════════════════════════════════════════════════════════════
$tier_dist          = array();
$total_eligible     = 0;
$total_accepted     = 0;
$total_escalations  = 0;
$avg_discount       = 0.0;
$total_revenue      = 0.0;
$accepted_by_disc   = array();
$escalation_by_disc = array();

if ( $has_outcomes ) {
	// ── Eligible deals by discount percentage ──
	$eligible_raw = $wpdb->get_results(
		$wpdb->prepare(
			"SELECT
            ROUND(deal_value / NULLIF(cart_value,0) * 100) AS disc_pct,
            COUNT(*)          AS cnt,
            AVG(deal_value)   AS avg_deal,
            AVG(cart_value)   AS avg_cart,
            SUM(cart_value)   AS total_rev,
            MIN(fired_at)     AS first_seen,
            MAX(fired_at)     AS last_seen
         FROM {$outcomes_tbl}
         WHERE event_type = 'deal_eligible'
           AND fired_at >= DATE_SUB(UTC_TIMESTAMP(), INTERVAL %d DAY)
           AND cart_value > 0
         GROUP BY disc_pct
         ORDER BY cnt DESC
         LIMIT 30",
			$days
		) ?: array()
	);

	foreach ( $eligible_raw as $row ) {
		$pct               = (int) $row->disc_pct;
		$tier_dist[ $pct ] = array(
			'cnt'        => (int) $row->cnt,
			'avg_deal'   => (float) $row->avg_deal,
			'avg_cart'   => (float) $row->avg_cart,
			'total_rev'  => (float) $row->total_rev,
			'first_seen' => $row->first_seen,
			'last_seen'  => $row->last_seen,
		);
		$total_eligible   += (int) $row->cnt;
		$total_revenue    += (float) $row->total_rev;
	}

	// ── Accepted deals by discount percentage ──
	$accepted_raw = $wpdb->get_results(
		$wpdb->prepare(
			"SELECT
            ROUND(deal_value / NULLIF(cart_value,0) * 100) AS disc_pct,
            COUNT(*) AS cnt,
            AVG(deal_value) AS avg_deal
         FROM {$outcomes_tbl}
         WHERE event_type IN ('accepted', 'deal_accepted')
           AND fired_at >= DATE_SUB(UTC_TIMESTAMP(), INTERVAL %d DAY)
           AND cart_value > 0
         GROUP BY disc_pct",
			$days
		) ?: array()
	);

	foreach ( $accepted_raw as $row ) {
		$pct                      = (int) $row->disc_pct;
		$accepted_by_disc[ $pct ] = (int) $row->cnt;
		$total_accepted          += (int) $row->cnt;
	}

	// ── Escalated deals by discount percentage ──
	$escalated_raw = $wpdb->get_results(
		$wpdb->prepare(
			"SELECT
            ROUND(deal_value / NULLIF(cart_value,0) * 100) AS disc_pct,
            COUNT(*) AS cnt
         FROM {$outcomes_tbl}
         WHERE event_type = 'escalated'
           AND fired_at >= DATE_SUB(UTC_TIMESTAMP(), INTERVAL %d DAY)
         GROUP BY disc_pct",
			$days
		) ?: array()
	);

	foreach ( $escalated_raw as $row ) {
		$pct                        = (int) $row->disc_pct;
		$escalation_by_disc[ $pct ] = (int) $row->cnt;
		$total_escalations         += (int) $row->cnt;
	}

	// Weighted average discount
	if ( $total_eligible > 0 ) {
		$weighted_sum = 0;
		foreach ( $tier_dist as $pct => $data ) {
			$weighted_sum += $data['cnt'] * $data['avg_deal'];
		}
		$avg_discount = $weighted_sum / $total_eligible;
	}
}

// ═══════════════════════════════════════════════════════════════════════════════
// DERIVED METRICS
// ═══════════════════════════════════════════════════════════════════════════════
$overall_ar      = $total_eligible > 0
	? round( $total_accepted / $total_eligible * 100, 1 )
	: 0;
$tier1_count     = $tier_dist[ $min_tier_pct ]['cnt'] ?? 0;
$margin_saved    = $total_eligible > 0
	? round( $tier1_count / $total_eligible * 100, 1 )
	: 0;
$escalation_rate = $total_eligible > 0
	? round( $total_escalations / $total_eligible * 100, 1 )
	: 0;

// ═══════════════════════════════════════════════════════════════════════════════
// COMPARISON PERIOD
// ═══════════════════════════════════════════════════════════════════════════════
$comp_eligible = 0;
$comp_accepted = 0;

if ( $has_outcomes ) {
	$comp_eligible = (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)
           AND fired_at < DATE_SUB(UTC_TIMESTAMP(), INTERVAL %d DAY)",
			$comparison_days + $days,
			$comparison_days
		)
	);

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

$comp_ar   = $comp_eligible > 0
	? round( $comp_accepted / $comp_eligible * 100, 1 )
	: 0;
$ar_trend  = round( $overall_ar - $comp_ar, 1 );
$vol_trend = $comp_eligible > 0
	? round( ( ( $total_eligible - $comp_eligible ) / $comp_eligible ) * 100, 1 )
	: 0;

// ═══════════════════════════════════════════════════════════════════════════════
// SEGMENT RESPONSE MATRIX
// ═══════════════════════════════════════════════════════════════════════════════
$segment_data = array();
$segments_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 ( $segments_map as $seg_key => $seg_label ) {
		$seg_eligible = (int) $wpdb->get_var(
			$wpdb->prepare(
				"SELECT COUNT(*)
             FROM {$outcomes_tbl}
             WHERE event_type = 'deal_eligible'
               AND JSON_EXTRACT(meta, '$.archetype') = %s
               AND fired_at >= DATE_SUB(UTC_TIMESTAMP(), INTERVAL %d DAY)",
				$seg_key,
				$days
			)
		);

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

		if ( $seg_eligible > 0 ) {
			$seg_ar = round( $seg_accepted / $seg_eligible * 100, 1 );
			// Response classification
			if ( $seg_ar >= 40 ) {
				$seg_response   = 'Strong';
				$seg_resp_color = '#22c55e';
			} elseif ( $seg_ar >= 20 ) {
				$seg_response   = 'Good';
				$seg_resp_color = '#3b82f6';
			} elseif ( $seg_ar >= 10 ) {
				$seg_response   = 'Moderate';
				$seg_resp_color = '#f59e0b';
			} else {
				$seg_response   = 'Low';
				$seg_resp_color = '#ef4444';
			}

			$segment_data[ $seg_key ] = array(
				'label'          => $seg_label,
				'eligible'       => $seg_eligible,
				'accepted'       => $seg_accepted,
				'ar'             => $seg_ar,
				'response'       => $seg_response,
				'response_color' => $seg_resp_color,
			);
		}
	}
}

// ═══════════════════════════════════════════════════════════════════════════════
// CATEGORY DISCOUNT RESPONSE
// ═══════════════════════════════════════════════════════════════════════════════
$cat_response = array();

if ( $has_outcomes ) {
	$cat_raw = $wpdb->get_results(
		$wpdb->prepare(
			"SELECT
            JSON_EXTRACT(meta, '$.category') AS cat,
            COUNT(*)          AS cnt,
            AVG(CASE WHEN event_type IN ('accepted','deal_accepted') THEN 1 ELSE 0 END) AS ar
         FROM {$outcomes_tbl}
         WHERE event_type IN ('deal_eligible', 'accepted', 'deal_accepted')
           AND fired_at >= DATE_SUB(UTC_TIMESTAMP(), INTERVAL %d DAY)
           AND JSON_EXTRACT(meta, '$.category') IS NOT NULL
         GROUP BY JSON_EXTRACT(meta, '$.category')
         ORDER BY cnt DESC
         LIMIT 15",
			$days
		) ?: array()
	);

	foreach ( $cat_raw as $row ) {
		$cat_name = trim( (string) $row->cat, '"' );
		$cat_cnt  = (int) $row->cnt;
		if ( ! empty( $cat_name ) && $cat_cnt > 0 ) {
			$cat_response[] = array(
				'name' => $cat_name,
				'cnt'  => $cat_cnt,
				'ar'   => round( (float) $row->ar * 100, 1 ),
			);
		}
	}
}

// ═══════════════════════════════════════════════════════════════════════════════
// TIME-OF-DAY HEATMAP
// ═══════════════════════════════════════════════════════════════════════════════
$tod_data = array();

if ( $has_outcomes ) {
	$tod_raw = $wpdb->get_results(
		$wpdb->prepare(
			"SELECT
            HOUR(fired_at) AS hr,
            COUNT(*)       AS cnt,
            AVG(CASE WHEN event_type IN ('accepted','deal_accepted') THEN 1 ELSE 0 END) AS ar
         FROM {$outcomes_tbl}
         WHERE event_type IN ('deal_eligible', 'accepted', 'deal_accepted')
           AND fired_at >= DATE_SUB(UTC_TIMESTAMP(), INTERVAL %d DAY)
         GROUP BY HOUR(fired_at)
         ORDER BY hr",
			$days
		) ?: array()
	);

	foreach ( $tod_raw as $row ) {
		$tod_data[ (int) $row->hr ] = array(
			'cnt' => (int) $row->cnt,
			'ar'  => round( (float) $row->ar * 100, 1 ),
		);
	}
}

$tod_max = max( array_column( $tod_data, 'cnt' ) ?: array( 1 ) );

// ═══════════════════════════════════════════════════════════════════════════════
// RULE-LEVEL DISCOUNT EFFICIENCY
// ═══════════════════════════════════════════════════════════════════════════════
$rule_efficiency = array();

if ( $has_analytics && $has_rules ) {
	$rule_raw = $wpdb->get_results(
		$wpdb->prepare(
			"SELECT
            r.name,
            r.id,
            COUNT(DISTINCT a.order_id)          AS orders,
            COALESCE(SUM(a.order_total), 0)     AS revenue,
            COALESCE(SUM(a.discount_amount), 0) AS discounts,
            COALESCE(AVG(a.order_total), 0)     AS aov
         FROM {$analytics_tbl} a
         JOIN {$rules_tbl} r ON a.rule_id = r.id
         WHERE a.date_created >= %s
         GROUP BY r.id, r.name
         HAVING orders > 0
         ORDER BY revenue DESC
         LIMIT 12",
			gmdate( 'Y-m-d H:i:s', strtotime( "-{$days} days" ) )
		) ?: array()
	);

	foreach ( $rule_raw as $row ) {
		$rev  = (float) $row->revenue;
		$disc = (float) $row->discounts;
		$rate = $rev > 0 ? round( $disc / $rev * 100, 1 ) : 0;

		// Efficiency rating
		if ( $rate < 10 ) {
			$eff_label = 'Efficient';
			$eff_color = '#22c55e';
		} elseif ( $rate < 25 ) {
			$eff_label = 'Moderate';
			$eff_color = '#f59e0b';
		} else {
			$eff_label = 'High Cost';
			$eff_color = '#ef4444';
		}

		$rule_efficiency[] = array(
			'name'      => $row->name ?: 'Unnamed Rule',
			'orders'    => (int) $row->orders,
			'revenue'   => $rev,
			'discounts' => $disc,
			'aov'       => round( (float) $row->aov, 2 ),
			'rate'      => $rate,
			'eff_label' => $eff_label,
			'eff_color' => $eff_color,
		);
	}
}

// ═══════════════════════════════════════════════════════════════════════════════
// ESCALATION PATH ANALYSIS
// ═══════════════════════════════════════════════════════════════════════════════
$escalation_paths = array();

if ( $has_outcomes ) {
	$esc_raw = $wpdb->get_results(
		$wpdb->prepare(
			"SELECT
            JSON_EXTRACT(meta, '$.escalations') AS steps,
            COUNT(*) AS cnt,
            AVG(CASE WHEN event_type IN ('accepted','deal_accepted') THEN 1 ELSE 0 END) AS ar
         FROM {$outcomes_tbl}
         WHERE event_type IN ('deal_eligible', 'accepted', 'deal_accepted', 'escalated')
           AND fired_at >= DATE_SUB(UTC_TIMESTAMP(), INTERVAL %d DAY)
           AND JSON_EXTRACT(meta, '$.escalations') IS NOT NULL
         GROUP BY JSON_EXTRACT(meta, '$.escalations')
         ORDER BY steps",
			$days
		) ?: array()
	);

	foreach ( $esc_raw as $row ) {
		$steps = (int) $row->steps;
		if ( $steps >= 0 && $steps <= 5 ) {
			$escalation_paths[ $steps ] = array(
				'cnt' => (int) $row->cnt,
				'ar'  => round( (float) $row->ar * 100, 1 ),
			);
		}
	}
}

// ═══════════════════════════════════════════════════════════════════════════════
// CONVERSION GUARD EVENT LOG
// ═══════════════════════════════════════════════════════════════════════════════
$guard_log = array();

if ( $has_outcomes && $has_guard ) {
	$guard_log = $wpdb->get_results(
		$wpdb->prepare(
			"SELECT
            fired_at,
            JSON_EXTRACT(meta, '$.reason') AS reason,
            cart_value,
            deal_value,
            JSON_EXTRACT(meta, '$.product_id') AS product_id
         FROM {$outcomes_tbl}
         WHERE event_type = 'deal_eligible'
           AND JSON_EXTRACT(meta, '$.reason') = 'conversion_guard'
           AND fired_at >= DATE_SUB(UTC_TIMESTAMP(), INTERVAL %d DAY)
         ORDER BY fired_at DESC
         LIMIT 20",
			$days
		) ?: array()
	);
}

// ═══════════════════════════════════════════════════════════════════════════════
// CART VALUE INTELLIGENCE
// ═══════════════════════════════════════════════════════════════════════════════
$margin_ratio = 1.0;
$margin_pct   = 100;

if ( $has_cvi ) {
	$margin_ratio = GT_BOGO_Cart_Value_Intelligence::get_cart_margin_ratio();
	$margin_pct   = round( $margin_ratio * 100 );
}

// Margin status determination
if ( $margin_ratio < 0.5 ) {
	$margin_status = 'Heavily Discounted';
	$margin_color  = '#ef4444';
	$margin_bg     = 'rgba(239,68,68,0.06)';
	$margin_msg    = 'Cart is heavily discounted. Additional discounts suppressed to protect margins.';
} elseif ( $margin_ratio > 0.8 ) {
	$margin_status = 'Healthy';
	$margin_color  = '#22c55e';
	$margin_bg     = 'rgba(34,197,94,0.06)';
	$margin_msg    = 'Cart has healthy margin. Full discount available.';
} else {
	$margin_status = 'Moderate';
	$margin_color  = '#3b82f6';
	$margin_bg     = 'rgba(59,130,246,0.06)';
	$margin_msg    = 'Cart has moderate discount headroom. Partial discount applied.';
}

// ═══════════════════════════════════════════════════════════════════════════════
// SIGNAL BUS INTELLIGENCE
// ═══════════════════════════════════════════════════════════════════════════════
$ps_signal    = 0.0;
$guard_health = 4.0;
$ltv_score    = 0.0;
$cohort_perf  = 0.0;
$rfm_score    = 0.0;
$attrib_conf  = 0.0;
$loyalty_tier = 0.0;
$timing_conf  = 0.0;

if ( $has_bus ) {
	$ps_signal    = (float) GT_BOGO_Signal_Bus::get( 'price_sensitivity_score', 0.0 );
	$guard_health = (float) GT_BOGO_Signal_Bus::get( 'revenue_health', 4.0 );
	$ltv_score    = (float) GT_BOGO_Signal_Bus::get( 'ltv_score', 0.0 );
	$cohort_perf  = (float) GT_BOGO_Signal_Bus::get( 'cohort_performance', 0.0 );
	$rfm_score    = (float) GT_BOGO_Signal_Bus::get( 'rfm_score', 0.0 );
	$attrib_conf  = (float) GT_BOGO_Signal_Bus::get( 'attribution_confidence', 0.0 );
	$loyalty_tier = (float) GT_BOGO_Signal_Bus::get( 'loyalty_tier', 0.0 );
	$timing_conf  = (float) GT_BOGO_Signal_Bus::get( 'timing_confidence', 0.0 );
}

// ═══════════════════════════════════════════════════════════════════════════════
// DAILY TREND DATA
// ═══════════════════════════════════════════════════════════════════════════════
$daily_trend = array();

if ( $has_outcomes ) {
	$trend_raw = $wpdb->get_results(
		$wpdb->prepare(
			"SELECT
            DATE(fired_at) AS dt,
            SUM(CASE WHEN event_type = 'deal_eligible' THEN 1 ELSE 0 END) AS eligible,
            SUM(CASE WHEN event_type IN ('accepted','deal_accepted') THEN 1 ELSE 0 END) AS accepted,
            AVG(CASE WHEN event_type IN ('accepted','deal_accepted') THEN deal_value END) AS avg_deal,
            SUM(CASE WHEN event_type = 'escalated' THEN 1 ELSE 0 END) AS escalated
         FROM {$outcomes_tbl}
         WHERE fired_at >= DATE_SUB(UTC_TIMESTAMP(), INTERVAL %d DAY)
         GROUP BY dt
         ORDER BY dt ASC",
			$days
		) ?: array()
	);

	foreach ( $trend_raw as $row ) {
		$daily_trend[] = array(
			'date'      => $row->dt,
			'eligible'  => (int) $row->eligible,
			'accepted'  => (int) $row->accepted,
			'avg_deal'  => round( (float) $row->avg_deal, 2 ),
			'escalated' => (int) $row->escalated,
		);
	}
}

$chart_dates     = array_column( $daily_trend, 'date' );
$chart_eligible  = array_column( $daily_trend, 'eligible' );
$chart_accepted  = array_column( $daily_trend, 'accepted' );
$chart_deal      = array_column( $daily_trend, 'avg_deal' );
$chart_escalated = array_column( $daily_trend, 'escalated' );

// ═══════════════════════════════════════════════════════════════════════════════
// ACCEPTANCE FUNNEL
// ═══════════════════════════════════════════════════════════════════════════════
$funnel_steps = array(
	'deal_eligible' => array(
		'label' => 'Eligible',
		'icon'  => '⚡',
		'color' => '#3b82f6',
	),
	'escalated'     => array(
		'label' => 'Escalated',
		'icon'  => '⬆',
		'color' => '#f59e0b',
	),
	'accepted'      => array(
		'label' => 'Accepted',
		'icon'  => '✅',
		'color' => '#22c55e',
	),
);

$funnel_data = array();
if ( $has_outcomes ) {
	$funnel_data['deal_eligible'] = $total_eligible;
	$funnel_data['escalated']     = $total_escalations;
	$funnel_data['accepted']      = $total_accepted;
}

// ═══════════════════════════════════════════════════════════════════════════════
// WHAT-IF PROJECTIONS
// ═══════════════════════════════════════════════════════════════════════════════
$whatif_scenarios = array();

if ( $total_eligible > 0 && $total_accepted > 0 && $total_revenue > 0 ) {
	$avg_rev_per_accepted = $total_accepted > 0
		? $total_revenue / $total_accepted
		: 0;

	// Scenario 1: All deals closed at minimum tier
	$whatif_min_tier_savings = round(
		$total_accepted * $avg_rev_per_accepted * ( $avg_discount_given / 100 - $min_tier_pct / 100 ),
		0
	);
	$whatif_scenarios[]      = array(
		'label'  => "All deals at minimum tier ({$min_tier_pct}%)",
		'impact' => $whatif_min_tier_savings,
		'icon'   => '🛡️',
	);

	// Scenario 2: Acceptance rate improved by 10 percentage points
	$improved_ar        = min( 100, $overall_ar + 10 );
	$improved_accepted  = round( $total_eligible * $improved_ar / 100 );
	$whatif_ar_impact   = round(
		( $improved_accepted - $total_accepted ) * $avg_rev_per_accepted,
		0
	);
	$whatif_scenarios[] = array(
		'label'  => "AR +10% ({$overall_ar}% → {$improved_ar}%)",
		'impact' => $whatif_ar_impact,
		'icon'   => '📈',
	);

	// Scenario 3: Escalation rate halved
	$halved_esc_rate    = round( $escalation_rate / 2, 1 );
	$halved_esc_count   = round( $total_escalations * 0.5 );
	$whatif_esc_impact  = round(
		$halved_esc_count * $avg_rev_per_accepted * $min_tier_pct / 100,
		0
	);
	$whatif_scenarios[] = array(
		'label'  => "Escalation rate halved ({$escalation_rate}% → {$halved_esc_rate}%)",
		'impact' => $whatif_esc_impact,
		'icon'   => '⬇',
	);

	// Scenario 4: Cart margin improved by 10%
	$improved_margin_ratio = min( 1.0, $margin_ratio + 0.1 );
	$improved_margin_pct   = round( $improved_margin_ratio * 100 );
	$whatif_margin_impact  = round(
		$total_revenue * 0.1 * $margin_pct / 100,
		0
	);
	$whatif_scenarios[]    = array(
		'label'  => "Margin +10% ({$margin_pct}% → {$improved_margin_pct}%)",
		'impact' => $whatif_margin_impact,
		'icon'   => '💵',
	);
}

// ═══════════════════════════════════════════════════════════════════════════════
// ACTIONABLE RECOMMENDATIONS
// ═══════════════════════════════════════════════════════════════════════════════
$recommendations = array();

if ( $margin_saved < 30 ) {
	$recommendations[] = array(
		'type' => 'warning',
		'icon' => '⚠',
		'text' => "Only <strong>{$margin_saved}%</strong> of deals close at the minimum tier ({$min_tier_pct}%). "
				. 'Consider reviewing your escalation thresholds — customers may be waiting for higher discounts.',
	);
} else {
	$recommendations[] = array(
		'type' => 'success',
		'icon' => '✓',
		'text' => "<strong>{$margin_saved}%</strong> of deals close at minimum tier ({$min_tier_pct}%) — excellent margin preservation.",
	);
}

if ( $escalation_rate > 30 ) {
	$recommendations[] = array(
		'type' => 'warning',
		'icon' => '⚠',
		'text' => "Escalation rate is <strong>{$escalation_rate}%</strong>. High escalation suggests your minimum tier "
				. "({$min_tier_pct}%) may be too low for your customer base. Consider raising it to "
				. round( $min_tier_pct * 1.5 ) . '%.',
	);
} elseif ( $escalation_rate > 15 ) {
	$recommendations[] = array(
		'type' => 'info',
		'icon' => 'ℹ',
		'text' => "Escalation rate at <strong>{$escalation_rate}%</strong> is within acceptable range. "
				. 'Monitor for upward trends.',
	);
} else {
	$recommendations[] = array(
		'type' => 'success',
		'icon' => '✓',
		'text' => "Escalation rate at <strong>{$escalation_rate}%</strong> is healthy. Most customers accept the first offer.",
	);
}

if ( $block_rate > 0.05 ) {
	$recommendations[] = array(
		'type' => 'info',
		'icon' => '⚡',
		'text' => 'Conversion Guard is blocking <strong>' . round( $block_rate * 100, 1 )
				. "%</strong> of deals ({$deals_blocked} suppressed). "
				. 'Check guard thresholds in Settings if this seems high.',
	);
}

if ( $margin_ratio < 0.5 ) {
	$recommendations[] = array(
		'type' => 'warning',
		'icon' => '⚠',
		'text' => "Cart margin ratio is <strong>{$margin_pct}%</strong> — Cart Value Intelligence is "
				. 'suppressing additional discounts to protect margins. Review your product pricing strategy.',
	);
}

if ( $overall_ar < 15 && $total_eligible > 50 ) {
	$recommendations[] = array(
		'type' => 'warning',
		'icon' => '⚠',
		'text' => "Acceptance rate is <strong>{$overall_ar}%</strong> — below the typical 15-30% range. "
				. 'Your discount offer may not be compelling enough. Try increasing the minimum tier discount.',
	);
}

if ( $total_eligible === 0 ) {
	$recommendations[] = array(
		'type' => 'info',
		'icon' => 'ℹ',
		'text' => 'No discount data yet for this period. Data builds as customers interact with deals. '
				. 'Check that at least one BOGO rule is active.',
	);
}

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

<div class="gt-page-header gt-animate-in">
	<div>
		<h1 class="gt-page-title">🏷️ Discount Intelligence</h1>
		<p class="gt-page-subtitle">Complete discount command centre — tier efficiency, segment response, category analysis, escalation paths, conversion guard, margin intelligence, and what-if projections. All wired to live outcome data.</p>
	</div>
	<div style="display:flex;gap:8px;align-items:center">
		<span class="gt-badge <?php echo $has_dd ? 'gt-badge-active' : 'gt-badge-free'; ?>">
			<?php echo $has_dd ? '● Discovery Active' : '○ Unavailable'; ?>
		</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 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' => $comparison_days,
				)
			)
		);
		?>
				"
		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 === $comparison_days ? '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( $total_eligible ) ); ?> eligible ·
		<?php echo esc_html( number_format( $total_accepted ) ); ?> accepted ·
		<?php echo esc_html( $overall_ar ); ?>% AR
	</span>
</div>

<!-- ═══ 8 KPI METRICS ═══ -->
<div class="gt-metrics gt-animate-in" style="margin-bottom:24px">
	<!-- KPI 1: Deals Eligible -->
	<div class="gt-metric" style="--gt-metric-c:#E10000">
		<span class="gt-metric-icon">⚡</span>
		<div class="gt-metric-label">Deals Eligible (<?php echo esc_html( $days ); ?>d)</div>
		<div class="gt-metric-value"><?php echo esc_html( number_format( $total_eligible ) ); ?></div>
		<div class="gt-metric-trend">
			<?php echo $vol_trend >= 0 ? '↑' : '↓'; ?>
			<?php echo esc_html( abs( $vol_trend ) ); ?>% vs prev <?php echo esc_html( $comparison_days ); ?>d
		</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( $overall_ar ); ?>%</div>
		<div class="gt-metric-trend" style="color:<?php echo $ar_trend >= 0 ? '#86efac' : '#fca5a5'; ?>">
			<?php echo $ar_trend >= 0 ? '↑' : '↓'; ?>
			<?php echo esc_html( abs( $ar_trend ) ); ?>% vs prev
		</div>
	</div>
	<!-- KPI 3: Margin Preserved -->
	<div class="gt-metric" style="--gt-metric-c:#10b981">
		<span class="gt-metric-icon">🛡️</span>
		<div class="gt-metric-label">Margin Preserved</div>
		<div class="gt-metric-value"><?php echo esc_html( $margin_saved ); ?>%</div>
		<div class="gt-metric-trend">Closed at min tier (<?php echo esc_html( $min_tier_pct ); ?>%)</div>
	</div>
	<!-- KPI 4: Avg Discount -->
	<div class="gt-metric" style="--gt-metric-c:#f59e0b">
		<span class="gt-metric-icon">💵</span>
		<div class="gt-metric-label">Avg Discount</div>
		<div class="gt-metric-value">$<?php echo esc_html( number_format( $avg_discount, 2 ) ); ?></div>
		<div class="gt-metric-trend">Per eligible cart moment</div>
	</div>
	<!-- KPI 5: Learned Min Tier -->
	<div class="gt-metric" style="--gt-metric-c:#3b82f6">
		<span class="gt-metric-icon">🧠</span>
		<div class="gt-metric-label">Learned Min Tier</div>
		<div class="gt-metric-value" style="font-size:20px">T<?php echo esc_html( $learned_min ); ?> (<?php echo esc_html( $min_tier_pct ); ?>%)</div>
		<div class="gt-metric-trend">Lowest that reliably converts</div>
	</div>
	<!-- KPI 6: Escalation Rate -->
	<div class="gt-metric" style="--gt-metric-c:#a78bfa">
		<span class="gt-metric-icon">⬆</span>
		<div class="gt-metric-label">Escalation Rate</div>
		<div class="gt-metric-value"><?php echo esc_html( $escalation_rate ); ?>%</div>
		<div class="gt-metric-trend"><?php echo esc_html( number_format( $total_escalations ) ); ?> escalated</div>
	</div>
	<!-- KPI 7: Guard Blocked -->
	<div class="gt-metric" style="--gt-metric-c:#ef4444">
		<span class="gt-metric-icon">🚫</span>
		<div class="gt-metric-label">Guard Blocked</div>
		<div class="gt-metric-value"><?php echo esc_html( number_format( $deals_blocked ) ); ?></div>
		<div class="gt-metric-trend"><?php echo esc_html( round( $block_rate * 100, 1 ) ); ?>% of eligible</div>
	</div>
	<!-- KPI 8: Cart Margin -->
	<div class="gt-metric" style="--gt-metric-c:#06b6d4">
		<span class="gt-metric-icon">📐</span>
		<div class="gt-metric-label">Cart Margin</div>
		<div class="gt-metric-value"><?php echo esc_html( $margin_pct ); ?>%</div>
		<div class="gt-metric-trend"><?php echo esc_html( $margin_status ); ?></div>
	</div>
</div>

<!-- ═══ DAILY 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">📈 Daily Discount Activity</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="disc-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>● Eligible: <strong style="color:#3b82f6"><?php echo esc_html( number_format( array_sum( $chart_eligible ) ) ); ?></strong></span>
			<span>● Accepted: <strong style="color:#22c55e"><?php echo esc_html( number_format( array_sum( $chart_accepted ) ) ); ?></strong></span>
			<span>● Avg Deal: <strong style="color:#f59e0b">$<?php echo esc_html( number_format( array_sum( $chart_deal ) / max( 1, count( $chart_deal ) ), 2 ) ); ?></strong></span>
			<span>● Escalated: <strong style="color:#ef4444"><?php echo esc_html( number_format( array_sum( $chart_escalated ) ) ); ?></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 daily trend data yet. Activity builds as customers interact with deals.</div>
		</div>
		<?php endif; ?>
	</div>
</div>

<!-- ═══ ACCEPTANCE 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">📊 Acceptance Funnel (<?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">
		<div style="display:flex;align-items:flex-end;gap:32px;justify-content:center;padding:24px 0">
			<?php
			$funnel_max = max( array_values( $funnel_data ) ?: array( 1 ) );
			$prev_count = null;
			foreach ( $funnel_steps as $event => $meta ) :
				$cnt        = $funnel_data[ $event ] ?? 0;
				$pct        = $funnel_max > 0 ? round( $cnt / $funnel_max * 100 ) : 0;
				$conv       = ( $prev_count !== null && $prev_count > 0 )
					? round( $cnt / $prev_count * 100, 1 )
					: 100;
				$prev_count = $cnt;
				$bar_height = max( 24, $pct * 1.2 );
				?>
			<div style="text-align:center;flex:1;max-width:180px">
				<div style="font-size:32px;margin-bottom:8px"><?php echo esc_html( $meta['icon'] ); ?></div>
				<div style="background:<?php echo esc_attr( $meta['color'] ); ?>;height:<?php echo esc_attr( $bar_height ); ?>px;border-radius:8px 8px 0 0;margin-bottom:10px;min-height:24px;transition:height .6s ease"></div>
				<div style="font-size:26px;font-weight:800;color:#fff"><?php echo esc_html( number_format( $cnt ) ); ?></div>
				<div style="font-size:12px;font-weight:600;color:<?php echo esc_attr( $meta['color'] ); ?>;margin-top:4px"><?php echo esc_html( $meta['label'] ); ?></div>
				<div style="font-size:11px;color:#64748b;margin-top:2px"><?php echo esc_html( $conv ); ?>% conversion</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)">
			<?php echo esc_html( number_format( $total_accepted ) ); ?> accepted of <?php echo esc_html( number_format( $total_eligible ) ); ?> eligible — funnel health: <?php echo $escalation_rate < 20 ? 'Good' : 'Needs attention'; ?>
		</div>
	</div>
</div>

<!-- ═══ DISCOUNT DISTRIBUTION TABLE ═══ -->
<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">📋 Discount Distribution (<?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( $tier_dist ) ) :
			$max_cnt = max( array_column( $tier_dist, 'cnt' ) ?: array( 1 ) );
			arsort( $tier_dist );
			?>
		<table class="gt-table">
			<thead>
				<tr>
					<th>Discount %</th>
					<th>Eligible</th>
					<th>Accepted</th>
					<th>AR</th>
					<th>Escalated</th>
					<th>Avg Cart</th>
					<th>Avg Deal</th>
					<th>Revenue</th>
					<th>Volume</th>
				</tr>
			</thead>
			<tbody>
			<?php
			foreach ( $tier_dist as $pct => $data ) :
				$acc   = $accepted_by_disc[ $pct ] ?? 0;
				$esc   = $escalation_by_disc[ $pct ] ?? 0;
				$ar    = $data['cnt'] > 0 ? round( $acc / $data['cnt'] * 100, 1 ) : 0;
				$bar_w = $max_cnt > 0 ? round( $data['cnt'] / $max_cnt * 100 ) : 0;
				// AR badge class
				if ( $ar >= 30 ) {
					$ar_class = 'gt-badge-active';
				} elseif ( $ar >= 15 ) {
					$ar_class = 'gt-badge-expiring';
				} else {
					$ar_class = 'gt-badge-free';
				}
				?>
			<tr>
				<td style="font-weight:700"><?php echo esc_html( $pct ); ?>%</td>
				<td><?php echo esc_html( number_format( $data['cnt'] ) ); ?></td>
				<td><?php echo esc_html( number_format( $acc ) ); ?></td>
				<td><span class="gt-badge <?php echo esc_attr( $ar_class ); ?>" style="font-size:10px"><?php echo esc_html( $ar ); ?>%</span></td>
				<td><?php echo esc_html( number_format( $esc ) ); ?></td>
				<td style="font-family:'DM Mono',monospace;font-size:11px">$<?php echo esc_html( number_format( $data['avg_cart'], 2 ) ); ?></td>
				<td style="font-family:'DM Mono',monospace;font-size:11px">$<?php echo esc_html( number_format( $data['avg_deal'], 2 ) ); ?></td>
				<td style="font-family:'DM Mono',monospace;font-size:11px">$<?php echo esc_html( number_format( $data['total_rev'], 0 ) ); ?></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:#E10000;width:<?php echo esc_attr( $bar_w ); ?>%;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>No distribution data for this period. Data populates as deals fire and outcomes are recorded.</div>
		</div>
		<?php endif; ?>
	</div>
</div>

<!-- ═══ SEGMENT 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">👥 Segment 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 different customer archetypes respond to discount offers. High AR on price-sensitive segments = offer is compelling. Low AR on VIP = discount not needed.</p>
		<?php
		if ( ! empty( $segment_data ) ) :
			$seg_max_eligible = max( array_column( $segment_data, 'eligible' ) ?: array( 1 ) );
			?>
		<table class="gt-table">
			<thead><tr><th>Segment</th><th>Eligible</th><th>Accepted</th><th>Accept Rate</th><th>Response</th><th>Volume</th></tr></thead>
			<tbody>
			<?php
			foreach ( $segment_data as $seg_key => $seg ) :
				$seg_bar_w = $seg_max_eligible > 0 ? round( $seg['eligible'] / $seg_max_eligible * 100 ) : 0;
				?>
			<tr>
				<td style="font-weight:600"><?php echo esc_html( $seg['label'] ); ?></td>
				<td><?php echo esc_html( number_format( $seg['eligible'] ) ); ?></td>
				<td><?php echo esc_html( number_format( $seg['accepted'] ) ); ?></td>
				<td>
					<span class="gt-badge <?php echo $seg['ar'] >= 30 ? 'gt-badge-active' : ( $seg['ar'] >= 15 ? 'gt-badge-expiring' : 'gt-badge-free' ); ?>" style="font-size:10px">
						<?php echo esc_html( $seg['ar'] ); ?>%
					</span>
				</td>
				<td style="color:<?php echo esc_attr( $seg['response_color'] ); ?>;font-weight:600;font-size:12px"><?php echo esc_html( $seg['response'] ); ?></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_w ); ?>%;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 interact with deals.</div>
		</div>
		<?php endif; ?>
	</div>
</div>

<!-- ═══ CATEGORY DISCOUNT RESPONSE ═══ -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
	<div class="gt-card-header rev-accordion-header" onclick="gtRevToggle(this)">
		<h2 class="gt-card-title">🗂️ Category Discount Response</h2>
		<span class="gt-target-chevron" style="color:#64748b;font-size:10px;transition:transform .2s">▼</span>
	</div>
	<div class="rev-accordion-body">
		<p style="font-size:13px;color:#64748b;margin:0 0 16px">Which product categories have the highest discount acceptance. Use this to target categories that respond well to BOGO offers.</p>
		<?php
		if ( ! empty( $cat_response ) ) :
			$cat_max = max( array_column( $cat_response, 'cnt' ) ?: array( 1 ) );
			?>
		<table class="gt-table">
			<thead><tr><th>Category</th><th>Deals</th><th>Accept Rate</th><th>Recommendation</th><th>Volume</th></tr></thead>
			<tbody>
			<?php
			foreach ( $cat_response as $cat ) :
				$cat_bar_w = $cat_max > 0 ? round( $cat['cnt'] / $cat_max * 100 ) : 0;
				if ( $cat['ar'] >= 30 ) {
					$cat_rec   = '⭐ High performer';
					$cat_rec_c = '#22c55e'; } elseif ( $cat['ar'] >= 15 ) {
					$cat_rec   = 'Good target';
					$cat_rec_c = '#3b82f6'; } else {
						$cat_rec   = 'Low response';
						$cat_rec_c = '#64748b'; }
					?>
			<tr>
				<td style="font-weight:600"><?php echo esc_html( $cat['name'] ); ?></td>
				<td><?php echo esc_html( number_format( $cat['cnt'] ) ); ?></td>
				<td><span class="gt-badge <?php echo $cat['ar'] >= 30 ? 'gt-badge-active' : ( $cat['ar'] >= 15 ? 'gt-badge-expiring' : 'gt-badge-free' ); ?>" style="font-size:10px"><?php echo esc_html( $cat['ar'] ); ?>%</span></td>
				<td style="color:<?php echo esc_attr( $cat_rec_c ); ?>;font-size:12px"><?php echo esc_html( $cat_rec ); ?></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_w ); ?>%;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 data builds as deals fire with category metadata attached.</div>
		</div>
		<?php endif; ?>
	</div>
</div>

<!-- ═══ TIME-OF-DAY 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">🕐 Time-of-Day Performance</h2>
		<span class="gt-target-chevron" style="color:#64748b;font-size:10px;transition:transform .2s">▼</span>
	</div>
	<div class="rev-accordion-body">
		<?php if ( ! empty( $tod_data ) ) : ?>
		<p style="font-size:13px;color:#64748b;margin:0 0 14px">Peak deal activity hours. Darker bars = higher volume. Use this to schedule campaigns when discount acceptance is highest.</p>
		<div style="display:flex;gap:3px;align-items:flex-end;margin-bottom:10px;flex-wrap:wrap">
			<?php
			for ( $h = 0; $h < 24; $h++ ) :
				$td     = $tod_data[ $h ] ?? array(
					'cnt' => 0,
					'ar'  => 0,
				);
				$height = $tod_max > 0 ? round( $td['cnt'] / $tod_max * 80 ) + 10 : 10;
				$alpha  = $tod_max > 0 ? round( 0.08 + ( $td['cnt'] / $tod_max ) * 0.9, 2 ) : 0.08;
				$label  = $h === 0 ? '12a' : ( $h < 12 ? $h . 'a' : ( $h === 12 ? '12p' : ( $h - 12 ) . 'p' ) );
				$title  = $label . ': ' . number_format( $td['cnt'] ) . ' deals, ' . $td['ar'] . '% AR';
				?>
			<div style="flex:1;min-width:22px;text-align:center" title="<?php echo esc_attr( $title ); ?>">
				<div style="height:<?php echo esc_attr( $height ); ?>px;border-radius:3px 3px 0 0;background:rgba(225,0,0,<?php echo esc_attr( $alpha ); ?>);margin-bottom:2px;transition:height .3s ease"></div>
				<div style="font-size:8px;color:#475569"><?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">
			<span>Low</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</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>Time-of-day data builds automatically as deals fire throughout the day.</div>
		</div>
		<?php endif; ?>
	</div>
</div>

<!-- ═══ SAVINGS OPTIMISATION REPORT ═══ -->
<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">💰 Savings Optimisation Report</h2>
		<span class="gt-target-chevron" style="color:#64748b;font-size:10px;transition:transform .2s">▼</span>
	</div>
	<div class="rev-accordion-body">
		<?php if ( $has_dd && $avg_tier_given !== null ) : ?>
		<div style="display:grid;grid-template-columns:repeat(3,1fr);gap:16px;margin-bottom:16px">
			<div style="background:#0d1f3c;border-radius:10px;padding:24px;text-align:center;border:1px solid rgba(255,255,255,0.04);transition:transform .2s" onmouseover="this.style.transform='translateY(-2px)'" onmouseout="this.style.transform='translateY(0)'">
				<div class="gt-card-label">Average Tier Given</div>
				<div style="font-size:36px;font-weight:800;color:#f59e0b;margin-top:4px">T<?php echo esc_html( $avg_tier_given ); ?></div>
				<div style="font-size:12px;color:#64748b;margin-top:4px"><?php echo esc_html( $avg_discount_given ); ?>% avg discount</div>
			</div>
			<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 class="gt-card-label">Average Escalations</div>
				<div style="font-size:36px;font-weight:800;color:#3b82f6;margin-top:4px"><?php echo esc_html( $avg_escalations ); ?></div>
				<div style="font-size:12px;color:#64748b;margin-top:4px">Steps before acceptance</div>
			</div>
			<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 class="gt-card-label">Discount Gap</div>
				<div style="font-size:36px;font-weight:800;color:#ef4444;margin-top:4px"><?php echo esc_html( $gap_pct ); ?>%</div>
				<div style="font-size:12px;color:#64748b;margin-top:4px">Avg − Min tier</div>
			</div>
		</div>
		<div style="text-align:center;padding:14px;background:rgba(245,158,11,0.06);border-radius:8px;font-size:14px;font-weight:600;color:#fcd34d">
			<?php echo esc_html( $potential_savings ); ?> — <?php echo esc_html( $margin_saved ); ?>% of deals already close at minimum tier (<?php echo esc_html( $min_tier_pct ); ?>%).
		</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>Savings report requires Discount Discovery engine with outcome data. Builds automatically as customers interact with deals.</div>
		</div>
		<?php endif; ?>
	</div>
</div>

<!-- ═══ TIER CONFIGURATION ═══ -->
<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">🎚️ Discount Tier Configuration</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">Current tier setup. ★ = Learned minimum — the lowest discount that reliably converts for your store. Higher tiers escalate only when necessary.</p>
		<div style="display:grid;grid-template-columns:repeat(<?php echo count( $tiers ); ?>,1fr);gap:12px;margin-bottom:12px">
			<?php
			foreach ( $tiers as $tier_n => $pct ) :
				$is_min = (int) $tier_n === $learned_min;
				if ( $is_min ) {
					$tcolor = '#10b981'; } elseif ( (int) $tier_n <= 2 ) {
					$tcolor = '#3b82f6'; } elseif ( (int) $tier_n <= 4 ) {
						$tcolor = '#f59e0b'; } else {
						$tcolor = '#ef4444'; }
						$in_use   = isset( $tier_dist[ (int) $pct ] );
						$use_cnt  = $tier_dist[ (int) $pct ]['cnt'] ?? 0;
						$border_c = $is_min ? 'rgba(16,185,129,0.4)' : 'rgba(255,255,255,0.05)';
						?>
			<div style="background:#0d1f3c;border-radius:10px;padding:20px;text-align:center;border:1px solid <?php echo esc_attr( $border_c ); ?>;transition:border-color .2s,transform .2s"
				onmouseover="this.style.borderColor='<?php echo esc_attr( $tcolor ); ?>';this.style.transform='translateY(-2px)'"
				onmouseout="this.style.borderColor='<?php echo esc_attr( $border_c ); ?>';this.style.transform='translateY(0)'">
				<div style="font-size:30px;font-weight:800;color:<?php echo esc_attr( $tcolor ); ?>;line-height:1"><?php echo esc_html( $pct ); ?>%</div>
				<div style="font-size:11px;font-weight:700;color:#94a3b8;margin-top:6px;text-transform:uppercase;letter-spacing:0.5px">Tier <?php echo esc_html( $tier_n ); ?><?php echo $is_min ? ' ★' : ''; ?></div>
				<?php if ( $is_min ) : ?>
				<div style="font-size:10px;color:#10b981;margin-top:4px">Learned minimum</div>
				<?php endif; ?>
				<div style="font-size:10px;color:#475569;margin-top:6px"><?php echo $in_use ? esc_html( number_format( $use_cnt ) . ' deals' ) : 'Not used'; ?></div>
			</div>
			<?php endforeach; ?>
		</div>
	</div>
</div>

<!-- ═══ ESCALATION PATH 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">🪜 Escalation Path 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">How many escalation steps before a customer accepts. Fewer steps = better. If most acceptances require 2+ steps, your minimum tier may be too low.</p>
		<?php
		if ( ! empty( $escalation_paths ) ) :
			$esc_path_max = max( array_column( $escalation_paths, 'cnt' ) ?: array( 1 ) );
			?>
		<div style="display:flex;gap:16px;flex-wrap:wrap">
			<?php
			foreach ( $escalation_paths as $steps => $data ) :
				$esc_h = round( $data['cnt'] / $esc_path_max * 140 ) + 20;
				if ( $steps === 0 ) {
					$esc_c = '#22c55e';
				} elseif ( $steps === 1 ) {
					$esc_c = '#3b82f6';
				} elseif ( $steps === 2 ) {
					$esc_c = '#f59e0b';
				} else {
					$esc_c = '#ef4444';
				}
				?>
			<div style="flex:1;min-width:80px;text-align:center">
				<div style="font-size:22px;font-weight:800;color:#fff"><?php echo esc_html( $steps ); ?> step<?php echo $steps !== 1 ? 's' : ''; ?></div>
				<div style="background:<?php echo esc_attr( $esc_c ); ?>;height:<?php echo esc_attr( $esc_h ); ?>px;border-radius:6px 6px 0 0;margin:8px 0 6px;transition:height .4s ease"></div>
				<div style="font-size:12px;color:#475569"><?php echo esc_html( number_format( $data['cnt'] ) ); ?> deals</div>
				<div style="font-size:11px;font-weight:600;color:<?php echo $data['ar'] >= 30 ? '#86efac' : '#fca5a5'; ?>"><?php echo esc_html( $data['ar'] ); ?>% AR</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>Escalation path data builds as the discount engine escalates tiers and records outcomes.</div>
		</div>
		<?php endif; ?>
	</div>
</div>

<!-- ═══ RULE-LEVEL DISCOUNT EFFICIENCY ═══ -->
<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">📋 Rule Discount Efficiency</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">Per-rule discount efficiency. Rules with low discount rates relative to revenue are most efficient. High discount rates may indicate the rule is too generous.</p>
		<?php if ( ! empty( $rule_efficiency ) ) : ?>
		<table class="gt-table">
			<thead><tr><th>Rule</th><th>Orders</th><th>Revenue</th><th>Discounts</th><th>Disc Rate</th><th>AOV</th><th>Efficiency</th></tr></thead>
			<tbody>
			<?php foreach ( $rule_efficiency as $rle ) : ?>
			<tr>
				<td style="font-weight:600;max-width:180px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap"><?php echo esc_html( $rle['name'] ); ?></td>
				<td><?php echo esc_html( number_format( $rle['orders'] ) ); ?></td>
				<td style="font-family:'DM Mono',monospace;font-size:11px">$<?php echo esc_html( number_format( $rle['revenue'], 0 ) ); ?></td>
				<td style="font-family:'DM Mono',monospace;font-size:11px;color:#f59e0b">$<?php echo esc_html( number_format( $rle['discounts'], 0 ) ); ?></td>
				<td><?php echo esc_html( $rle['rate'] ); ?>%</td>
				<td style="font-family:'DM Mono',monospace;font-size:11px">$<?php echo esc_html( number_format( $rle['aov'], 2 ) ); ?></td>
				<td><span class="gt-badge" style="font-size:10px;background:<?php echo esc_attr( $rle['eff_color'] ); ?>20;border-color:<?php echo esc_attr( $rle['eff_color'] ); ?>40;color:<?php echo esc_attr( $rle['eff_color'] ); ?>"><?php echo esc_html( $rle['eff_label'] ); ?></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>Rule-level data requires the gtbogo_analytics table with completed BOGO orders.</div>
		</div>
		<?php endif; ?>
	</div>
</div>

<!-- ═══ CONVERSION GUARD ═══ -->
<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">🛡️ Conversion Guard</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">Prevents deals from being offered to customers already converting at full price — preserving margin. Block rate should be 0-5% in a healthy store.</p>
		<div style="display:grid;grid-template-columns:repeat(3,1fr);gap:16px;margin-bottom:16px">
			<div style="background:#0d1f3c;border-radius:10px;padding:24px;text-align:center;border:1px solid rgba(255,255,255,0.04)">
				<div class="gt-card-label">Block Rate</div>
				<div style="font-size:32px;font-weight:800;color:#ef4444;margin-top:4px"><?php echo esc_html( round( $block_rate * 100, 1 ) ); ?>%</div>
				<div style="font-size:11px;color:#64748b;margin-top:4px">Of eligible deals</div>
			</div>
			<div style="background:#0d1f3c;border-radius:10px;padding:24px;text-align:center;border:1px solid rgba(255,255,255,0.04)">
				<div class="gt-card-label">Deals Blocked</div>
				<div style="font-size:32px;font-weight:800;color:#f59e0b;margin-top:4px"><?php echo esc_html( number_format( $deals_blocked ) ); ?></div>
				<div style="font-size:11px;color:#64748b;margin-top:4px">Margin preserved</div>
			</div>
			<div style="background:#0d1f3c;border-radius:10px;padding:24px;text-align:center;border:1px solid rgba(255,255,255,0.04)">
				<div class="gt-card-label">Total Processed</div>
				<div style="font-size:32px;font-weight:800;color:#94a3b8;margin-top:4px"><?php echo esc_html( number_format( $deals_total_g ) ); ?></div>
				<div style="font-size:11px;color:#64748b;margin-top:4px">Events in period</div>
			</div>
		</div>
		<?php if ( ! empty( $guard_log ) ) : ?>
		<div class="gt-card-label" style="margin-bottom:8px">Recent Suppression Events</div>
		<table class="gt-table">
			<thead><tr><th>Time</th><th>Cart Value</th><th>Deal Value</th><th>Product ID</th><th>Reason</th></tr></thead>
			<tbody>
			<?php
			foreach ( $guard_log as $entry ) :
				$reason   = trim( (string) ( $entry->reason ?? '' ), '"' );
				$product  = trim( (string) ( $entry->product_id ?? '' ), '"' );
				$time_ago = human_time_diff( strtotime( $entry->fired_at ?? '' ), time() );
				?>
			<tr>
				<td style="font-size:11px;color:#64748b"><?php echo esc_html( $time_ago ); ?> ago</td>
				<td style="font-family:'DM Mono',monospace;font-size:11px">$<?php echo esc_html( number_format( (float) $entry->cart_value, 2 ) ); ?></td>
				<td style="font-family:'DM Mono',monospace;font-size:11px">$<?php echo esc_html( number_format( (float) $entry->deal_value, 2 ) ); ?></td>
				<td style="font-size:11px;color:#64748b"><?php echo $product ? '#' . esc_html( $product ) : '—'; ?></td>
				<td style="font-size:11px;color:#fca5a5"><?php echo esc_html( $reason ?: 'conversion_guard' ); ?></td>
			</tr>
			<?php endforeach; ?>
			</tbody>
		</table>
		<?php endif; ?>
	</div>
</div>

<!-- ═══ CART VALUE INTELLIGENCE ═══ -->
<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">🛒 Cart Value Intelligence</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">Automatically adjusts discount depth based on cart total. High-value carts receive smaller discounts (already converting). Low-value carts receive full discounts to push conversion.</p>
		<div style="display:grid;grid-template-columns:repeat(3,1fr);gap:12px;margin-bottom:16px">
			<?php
			$cvi_bands = array(
				array( '$0–100', '#3b82f6', 'Full discount (100%)', 'Low cart — needs maximum incentive' ),
				array( '$100–300', '#f59e0b', 'Partial discount (75%)', 'Mid cart — moderate incentive' ),
				array( '$300+', '#22c55e', 'Capped discount (50%)', 'High cart — converting naturally' ),
			);
			foreach ( $cvi_bands as $band ) :
				?>
			<div style="background:#0d1f3c;border-radius:8px;padding:20px;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:22px;font-weight:800;color:<?php echo esc_attr( $band[1] ); ?>"><?php echo esc_html( $band[0] ); ?></div>
				<div style="font-size:12px;color:#64748b;margin-top:6px"><?php echo esc_html( $band[2] ); ?></div>
				<div style="font-size:11px;color:#475569;margin-top:2px"><?php echo esc_html( $band[3] ); ?></div>
			</div>
			<?php endforeach; ?>
		</div>
		<div style="text-align:center;padding:14px;background:<?php echo esc_attr( $margin_bg ); ?>;border-radius:8px;font-size:14px;font-weight:600;color:<?php echo esc_attr( $margin_color ); ?>">
			Current margin ratio: <?php echo esc_html( $margin_pct ); ?>% — <?php echo esc_html( $margin_msg ); ?>
		</div>
	</div>
</div>

<!-- ═══ INTELLIGENCE SIGNALS ═══ -->
<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 Signals</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 bus readings. These signals feed into the discount decision engine to personalise offers per customer archetype.</p>
		<div style="display:grid;grid-template-columns:repeat(4,1fr);gap:12px">
			<?php
			$signals_display = array(
				array( $ps_signal, 'Price Sensitivity', '#f59e0b', $ps_signal >= 3 ? 'High — limit depth' : ( $ps_signal >= 1.5 ? 'Moderate' : 'Low' ) ),
				array( $guard_health, 'Revenue Health', '#a78bfa', $guard_health >= 3 ? 'Healthy' : ( $guard_health >= 1 ? 'Warning' : 'Guard active' ) ),
				array( $ltv_score, 'LTV Score', '#10b981', $ltv_score >= 3 ? 'High value' : ( $ltv_score >= 1.5 ? 'Growing' : 'Developing' ) ),
				array( $cohort_perf, 'Cohort Perf', '#06b6d4', $cohort_perf >= 3 ? 'Strong' : ( $cohort_perf >= 1.5 ? 'Average' : 'Below avg' ) ),
				array( $rfm_score, 'RFM Score', '#8b5cf6', $rfm_score >= 3.5 ? 'High retention' : ( $rfm_score >= 2 ? 'Moderate' : 'At risk' ) ),
				array( $attrib_conf, 'Attribution', '#f97316', $attrib_conf >= 3 ? 'High confidence' : ( $attrib_conf >= 1.5 ? 'Moderate' : 'Building' ) ),
				array( $loyalty_tier, 'Loyalty Tier', '#ec4899', $loyalty_tier >= 4 ? 'Platinum' : ( $loyalty_tier >= 3 ? 'VIP' : ( $loyalty_tier >= 2 ? 'Gold' : 'Standard' ) ) ),
				array( $timing_conf, 'Timing Confidence', '#14b8a6', $timing_conf >= 3 ? 'Peak window' : ( $timing_conf >= 1.5 ? 'Approaching' : 'Off-peak' ) ),
			);
			foreach ( $signals_display as $sig ) :
				?>
			<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"
				onmouseover="this.style.borderColor='<?php echo esc_attr( $sig[2] ); ?>'"
				onmouseout="this.style.borderColor='rgba(255,255,255,0.04)'">
				<div style="font-size:24px;font-weight:800;color:<?php echo esc_attr( $sig[2] ); ?>"><?php echo esc_html( number_format( $sig[0], 1 ) ); ?></div>
				<div style="width:<?php echo esc_attr( round( $sig[0] / 5 * 100 ) ); ?>%;height:3px;background:<?php echo esc_attr( $sig[2] ); ?>;border-radius:3px;margin:8px auto;opacity:0.5;transition:width .4s ease"></div>
				<div style="font-size:12px;font-weight:600;color:#e2e8f0"><?php echo esc_html( $sig[1] ); ?></div>
				<div style="font-size:10px;color:#64748b;margin-top:2px"><?php echo esc_html( $sig[3] ); ?></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">🔮 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 margin impact of different discount strategies.</p>
		<?php if ( ! empty( $whatif_scenarios ) ) : ?>
		<div style="display:grid;grid-template-columns:repeat(2,1fr);gap:12px">
			<?php foreach ( $whatif_scenarios as $sc ) : ?>
			<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( $sc['icon'] ); ?></div>
				<div style="font-size:14px;font-weight:600;color:#e2e8f0;margin-bottom:10px;line-height:1.4"><?php echo esc_html( $sc['label'] ); ?></div>
				<div style="font-size:28px;font-weight:800;color:<?php echo $sc['impact'] > 0 ? '#22c55e' : ( $sc['impact'] < 0 ? '#ef4444' : '#94a3b8' ); ?>">
					<?php echo $sc['impact'] >= 0 ? '+' : ''; ?>$<?php echo esc_html( number_format( abs( $sc['impact'] ), 0 ) ); ?>
				</div>
				<div style="font-size:11px;color:#64748b;margin-top:4px">Estimated margin impact</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>What-if projections become available after sufficient deal data is collected.</div>
		</div>
		<?php endif; ?>
	</div>
</div>

<!-- ═══ RECOMMENDATIONS ═══ -->
<div class="gt-card gt-card-premium gt-animate-in" style="margin-bottom:20px">
	<div class="gt-card-header">
		<h2 class="gt-card-title">💡 Intelligent Recommendations</h2>
	</div>
	<div style="display:flex;flex-direction:column;gap:10px">
		<?php if ( empty( $recommendations ) ) : ?>
		<div style="padding:14px 18px;background:rgba(255,255,255,0.02);border-radius:8px;font-size:13px;color:#86efac;line-height:1.5">
			<span style="color:#86efac">✓</span> All discount intelligence 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_icon_color = '#86efac';
				} elseif ( $rec['type'] === 'warning' ) {
					$rec_bg         = 'rgba(239,68,68,0.04)';
					$rec_icon_color = '#fca5a5';
				} else {
					$rec_bg         = 'rgba(59,130,246,0.04)';
					$rec_icon_color = '#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_icon_color ); ?>;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
// ═══════════════════════════════════════════════════════════════════════════════
function gtRevToggle(header) {
	var body = header.nextElementSibling;
	var chev = header.querySelector('.gt-target-chevron');
	var open = body.classList.contains('open');
	if (open) {
		body.classList.remove('open');
		header.classList.remove('open');
		if (chev) {
			chev.style.transform = 'rotate(0deg)';
			chev.textContent = '▼';
		}
	} else {
		body.classList.add('open');
		header.classList.add('open');
		if (chev) {
			chev.style.transform = 'rotate(180deg)';
			chev.textContent = '▲';
		}
	}
}

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

// ═══════════════════════════════════════════════════════════════════════════════
// DAILY TREND CHART (Chart.js)
// ═══════════════════════════════════════════════════════════════════════════════
document.addEventListener('DOMContentLoaded', function(){
	var canvas = document.getElementById('disc-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_dates ); ?>,
			datasets: [
				{
					label: 'Eligible',
					data: <?php echo wp_json_encode( $chart_eligible ); ?>,
					borderColor: '#3b82f6',
					backgroundColor: 'rgba(59,130,246,0.05)',
					fill: true,
					tension: 0.3,
					pointRadius: 2,
					pointHoverRadius: 4,
					borderWidth: 2,
					yAxisID: 'y'
				},
				{
					label: 'Accepted',
					data: <?php echo wp_json_encode( $chart_accepted ); ?>,
					borderColor: '#22c55e',
					backgroundColor: 'rgba(34,197,94,0.05)',
					fill: true,
					tension: 0.3,
					pointRadius: 2,
					pointHoverRadius: 4,
					borderWidth: 2,
					yAxisID: 'y'
				},
				{
					label: 'Avg Deal ($)',
					data: <?php echo wp_json_encode( $chart_deal ); ?>,
					borderColor: '#f59e0b',
					borderDash: [4, 2],
					fill: false,
					tension: 0.3,
					pointRadius: 1,
					pointHoverRadius: 3,
					borderWidth: 1.5,
					yAxisID: 'y1'
				},
				{
					label: 'Escalated',
					data: <?php echo wp_json_encode( $chart_escalated ); ?>,
					borderColor: '#ef4444',
					borderDash: [2, 2],
					fill: false,
					tension: 0.3,
					pointRadius: 1,
					pointHoverRadius: 3,
					borderWidth: 1,
					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: 10
				}
			},
			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: 'Deals',
						color: '#64748b'
					},
					ticks: {
						color: '#475569',
						font: { size: 10 }
					},
					grid: {
						color: 'rgba(255,255,255,0.03)'
					}
				},
				y1: {
					type: 'linear',
					display: true,
					position: 'right',
					title: {
						display: true,
						text: 'USD ($)',
						color: '#64748b'
					},
					ticks: {
						color: '#475569',
						font: { size: 10 },
						callback: function(value) {
							return '$' + value.toFixed(2);
						}
					},
					grid: {
						drawOnChartArea: false
					}
				}
			}
		}
	});
});
</script>

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