<?php
// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals
// phpcs:disable WordPress.Security.NonceVerification
// phpcs:disable WordPress.DB.DirectDatabaseQuery
// phpcs:disable WordPress.DB.SlowDBQuery
// phpcs:disable WordPress.DB.PreparedSQL
// phpcs:disable PluginCheck.CodeAnalysis
// phpcs:disable WordPressVIPMinimum
/**
 * GT BOGO Engine — Outcome Intelligence Dashboard
 *
 * Rebuilt in gt- design system. Adds over the existing page:
 *   - gt- cards / typography throughout
 *   - Chart.js daily trend line (fires vs accepted)
 *   - Deal lifecycle funnel (5 stages animated)
 *   - Revenue attribution panel (6 models via Attribution Engine)
 *   - Abandoned deal analysis (expired breakdown by reason)
 *   - Segment outcome matrix
 *   - Channel breakdown (cart / checkout / block)
 *   - Champion vs Challenger table (from existing logic)
 *   - Rule leaderboard (top 10 rules by accepted)
 *   - CSV export button
 *   - Date window selector (7 / 14 / 30 / 60 / 90d)
 *
 * @package GT_BOGO_Engine
 * @since   5.0.0
 */
if ( ! function_exists( 'gt_bogo_has_pro' ) || ! gt_bogo_has_pro() ) {
    if ( function_exists('gtbogo_upgrade_card') ) {
        gtbogo_upgrade_card('Outcome Intelligence','Tracks the downstream revenue impact of every deal — true incremental lift with treatment vs control holdout.');
    }
    return;
}
if ( ! defined( 'ABSPATH' ) ) exit;

global $wpdb;
$nonce    = wp_create_nonce('gtbogo_outcome_intel');
$outcomes = $wpdb->prefix . 'gtbogo_outcomes';
$has_out  = (bool) $wpdb->get_var( $wpdb->prepare('SHOW TABLES LIKE %s', $outcomes) ); // phpcs:ignore
$days     = max(7, min(90, absint( wp_unslash( $_GET['days'] ?? 30 ) )));

/* ── Lift report ──────────────────────────────────────────────────────────── */
$lift_report  = class_exists('GT_BOGO_Outcome_Capture') ? GT_BOGO_Outcome_Capture::get_lift_report(0, $days) : [];
$treatment_cr = round((float)($lift_report['treatment_cr'] ?? 0) * 100, 2);
$control_cr   = round((float)($lift_report['control_cr']  ?? 0) * 100, 2);
$lift_pct     = (float)($lift_report['lift_pct'] ?? 0);
$significant  = (bool)($lift_report['significant'] ?? false);
$sample_size  = (int)($lift_report['sample_size']  ?? 0);

/* ── Summary ─────────────────────────────────────────────────────────────── */
$summary = class_exists('GT_BOGO_Outcome_Capture') ? GT_BOGO_Outcome_Capture::get_summary($days) : [];
$total_eligible  = (int)($summary['eligible'] ?? 0);
$total_fired     = (int)($summary['fired']    ?? 0);
$total_accepted  = (int)($summary['accepted'] ?? 0);
$total_rejected  = (int)($summary['rejected'] ?? 0);
$total_expired   = (int)($summary['expired']  ?? 0);
$acceptance_rate = $total_fired > 0 ? round($total_accepted / $total_fired * 100, 1) : 0.0;

/* ── Rule leaderboard ────────────────────────────────────────────────────── */
$leaderboard = class_exists('GT_BOGO_Outcome_Capture')
    ? GT_BOGO_Outcome_Capture::get_rule_leaderboard($days, 10)
    : [];

/* ── Control conversion rate ─────────────────────────────────────────────── */
$control_rate = class_exists('GT_BOGO_Outcome_Capture')
    ? round(GT_BOGO_Outcome_Capture::get_control_conversion_rate($days) * 100, 2)
    : 0.0;

/* ── Daily trend for chart ───────────────────────────────────────────────── */
$chart_labels = $chart_fires = $chart_accepted = [];
if ($has_out) {
    $daily = $wpdb->get_results($wpdb->prepare( // phpcs:ignore
        "SELECT DATE(fired_at) AS day,
                SUM(event_type='deal_fired')    AS fires,
                SUM(event_type='deal_accepted') AS accepted
         FROM {$outcomes}
         WHERE fired_at >= DATE_SUB(UTC_TIMESTAMP(), INTERVAL %d DAY)
         GROUP BY day ORDER BY day ASC",
        $days
    ), ARRAY_A) ?: [];
    foreach ($daily as $d) {
        $chart_labels[]   = $d['day'];
        $chart_fires[]    = (int)$d['fires'];
        $chart_accepted[] = (int)$d['accepted'];
    }
}

/* ── Revenue per accepted deal ───────────────────────────────────────────── */
$total_deal_value = 0.0;
$total_margin     = 0.0;
if ($has_out) {
    $total_deal_value = (float)($wpdb->get_var($wpdb->prepare( // phpcs:ignore
        "SELECT SUM(deal_value) FROM {$outcomes} WHERE event_type='deal_accepted' AND fired_at>=DATE_SUB(UTC_TIMESTAMP(),INTERVAL %d DAY)", $days
    )) ?? 0);
    $total_margin = (float)($wpdb->get_var($wpdb->prepare( // phpcs:ignore
        "SELECT SUM(JSON_UNQUOTE(JSON_EXTRACT(meta,'$.margin_contribution')))
         FROM {$outcomes} WHERE event_type='deal_accepted' AND fired_at>=DATE_SUB(UTC_TIMESTAMP(),INTERVAL %d DAY)", $days
    )) ?? 0);
}

/* ── Channel breakdown ───────────────────────────────────────────────────── */
$channel_data = [];
if ($has_out) {
    $ch_rows = $wpdb->get_results($wpdb->prepare( // phpcs:ignore
        "SELECT channel, SUM(event_type='deal_fired') AS fires, SUM(event_type='deal_accepted') AS accepted
         FROM {$outcomes} WHERE fired_at>=DATE_SUB(UTC_TIMESTAMP(),INTERVAL %d DAY)
         GROUP BY channel", $days
    ), ARRAY_A) ?: [];
    foreach ($ch_rows as $r) $channel_data[$r['channel']] = ['fires'=>(int)$r['fires'],'accepted'=>(int)$r['accepted']];
}

/* ── Abandon reasons ─────────────────────────────────────────────────────── */
$abandon_reasons = [];
if ($has_out) {
    $ab_rows = $wpdb->get_results($wpdb->prepare( // phpcs:ignore
        "SELECT reason, COUNT(*) AS cnt FROM {$outcomes}
         WHERE event_type='deal_expired' AND fired_at>=DATE_SUB(UTC_TIMESTAMP(),INTERVAL %d DAY)
         AND reason != '' GROUP BY reason ORDER BY cnt DESC LIMIT 8", $days
    ), ARRAY_A) ?: [];
    foreach ($ab_rows as $r) $abandon_reasons[$r['reason']] = (int)$r['cnt'];
}

/* ── Attribution report ──────────────────────────────────────────────────── */
$attr_model  = sanitize_key($_GET['attr'] ?? 'last_touch');
$valid_models= ['first_touch','last_touch','linear','time_decay'];
$attr_model  = in_array($attr_model, $valid_models, true) ? $attr_model : 'last_touch';
$attr_data   = [];
if (class_exists('GT_BOGO_Attribution_Engine')) {
    $attr_start = gmdate('Y-m-d', strtotime("-{$days} days"));
    $attr_end   = gmdate('Y-m-d');
    $attr_data  = GT_BOGO_Attribution_Engine::get_report($attr_start, $attr_end, $attr_model);
}

/* ── Champion vs Challenger ──────────────────────────────────────────────── */
$challengers = (class_exists('GT_BOGO_Challenger') && method_exists('GT_BOGO_Challenger','get_all_reports'))
    ? (GT_BOGO_Challenger::get_all_reports() ?: [])
    : [];

/* ── Rule names for leaderboard ─────────────────────────────────────────── */
$rules_tbl = $wpdb->prefix . 'gtbogo_rules';
$rule_names = [];
if ($wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $rules_tbl))) { // phpcs:ignore
    $rn_rows = $wpdb->get_results("SELECT id, name FROM {$rules_tbl} LIMIT 200", ARRAY_A) ?: []; // phpcs:ignore
    foreach ($rn_rows as $r) $rule_names[(int)$r['id']] = $r['name'];
}

/* ── Chart JSON ──────────────────────────────────────────────────────────── */
$chart_labels_j   = wp_json_encode($chart_labels);
$chart_fires_j    = wp_json_encode($chart_fires);
$chart_accepted_j = wp_json_encode($chart_accepted);

$lift_color  = $lift_pct > 0 ? '#22c55e' : ($lift_pct < 0 ? '#ef4444' : 'var(--gt-subtle)');
$net_impact  = $total_margin - $total_deal_value;
$net_color   = $net_impact >= 0 ? '#22c55e' : '#ef4444';

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

<!-- PAGE HEADER -->
<div class="gt-page-header gt-animate-in" style="align-items:flex-start">
    <div>
        <h1 class="gt-page-title">📊 Outcome Intelligence</h1>
        <p class="gt-page-subtitle">
            Incremental lift vs control group, deal funnel analytics, revenue attribution,
            abandoned deal diagnostics, and rule performance leaderboard.
        </p>
    </div>
    <div style="display:flex;gap:10px;flex-wrap:wrap">
        <!-- Date window -->
        <div style="display:flex;gap:4px;background:rgba(255,255,255,0.04);border-radius:8px;padding:4px">
            <?php foreach ([7=>true,14=>false,30=>false,60=>false,90=>false] as $d=>$_) :
                $active = $days===$d; ?>
            <a href="<?php echo esc_url(add_query_arg(['days'=>$d,'attr'=>$attr_model])); ?>"
               style="padding:5px 12px;border-radius:6px;font-size:12px;font-weight:700;text-decoration:none;
                      background:<?php echo $active?'var(--gt-red)':'transparent'; ?>;
                      color:<?php echo $active?'#fff':'var(--gt-subtle)'; ?>">
                <?php echo esc_html($d); ?>d
            </a>
            <?php endforeach; ?>
        </div>
        <button type="button" class="gt-btn gt-btn-ghost gt-btn-sm"
            onclick="window.open(ajaxurl+'?action=gtbogo_oi_export_csv&nonce=<?php echo esc_js($nonce); ?>&days=<?php echo esc_js((string)$days); ?>','_blank')">
            ↓ Export CSV
        </button>
        <?php if (!$has_out) : ?>
        <span style="padding:5px 12px;border-radius:20px;font-size:11px;background:rgba(239,68,68,0.1);border:1px solid rgba(239,68,68,0.3);color:#ef4444">
            ✗ Table Missing
        </span>
        <?php else : ?>
        <span style="padding:5px 12px;border-radius:20px;font-size:11px;background:rgba(34,197,94,0.1);border:1px solid rgba(34,197,94,0.3);color:#22c55e">
            ● Tracking Active
        </span>
        <?php endif; ?>
    </div>
</div>

<!-- ═══ 6 KPI CARDS ═════════════════════════════════════════════════════════ -->
<div class="gt-animate-in" style="display:grid;grid-template-columns:repeat(6,1fr);gap:12px;margin-bottom:20px">
    <?php
    $kpis = [
        ['Eligible',      number_format($total_eligible),                    '#3b82f6', 'deals offered'],
        ['Accepted',      number_format($total_accepted),                    '#22c55e', 'completed checkout'],
        ['Acceptance %',  $acceptance_rate.'%',                             $acceptance_rate>=30?'#22c55e':($acceptance_rate>=15?'#f59e0b':'#ef4444'), 'accepted ÷ fired'],
        ['Lift vs Control',($lift_pct>0?'+':'').$lift_pct.'%',             $lift_color, $significant?'✓ significant':'needs more data'],
        ['Deal Volume',   '$'.number_format($total_deal_value,0),           '#f59e0b', 'total discount given'],
        ['Net Margin',    ($net_impact>=0?'+':'').'$'.number_format($net_impact,0), $net_color, 'margin minus discounts'],
    ];
    foreach ($kpis as $k) : ?>
    <div class="gt-card" style="padding:14px 16px;text-align:center">
        <div style="font-size:22px;font-weight:900;color:<?php echo esc_attr($k[2]); ?>;margin-bottom:3px;line-height:1">
            <?php echo esc_html($k[1]); ?>
        </div>
        <div style="font-size:10px;font-weight:800;letter-spacing:.08em;text-transform:uppercase;color:var(--gt-subtle)"><?php echo esc_html($k[0]); ?></div>
        <div style="font-size:10px;color:rgba(100,116,139,0.6);margin-top:2px"><?php echo esc_html($k[3]); ?></div>
    </div>
    <?php endforeach; ?>
</div>

<!-- ═══ TREND CHART + FUNNEL ════════════════════════════════════════════════ -->
<div class="gt-animate-in" style="display:grid;grid-template-columns:2fr 1fr;gap:16px;margin-bottom:20px">

    <!-- Daily trend -->
    <div class="gt-card">
        <div class="gt-card-header">
            <h2 class="gt-card-title">Fires vs Accepted — <?php echo esc_html($days); ?>-Day Trend</h2>
        </div>
        <div class="gt-chart-wrap" style="height:200px;padding:4px">
            <?php if (empty($chart_labels)) : ?>
            <div style="height:200px;display:flex;align-items:center;justify-content:center;color:var(--gt-subtle);font-size:13px">
                No outcome data for this window
            </div>
            <?php else : ?>
            <canvas id="gt-oi-trend-chart"></canvas>
            <?php endif; ?>
        </div>
    </div>

    <!-- Deal lifecycle funnel -->
    <div class="gt-card">
        <div class="gt-card-header"><h2 class="gt-card-title">Deal Lifecycle Funnel</h2></div>
        <?php
        $funnel = [
            ['Eligible', $total_eligible, '#3b82f6'],
            ['Fired',    $total_fired,    '#f59e0b'],
            ['Accepted', $total_accepted, '#22c55e'],
            ['Rejected', $total_rejected, '#ef4444'],
            ['Expired',  $total_expired,  '#64748b'],
        ];
        $funnel_max = max(1, $total_eligible);
        foreach ($funnel as $fs) :
            $fp = min(100, round($fs[1] / $funnel_max * 100));
        ?>
        <div style="display:flex;align-items:center;gap:8px;padding:6px 0;border-bottom:1px solid rgba(255,255,255,0.04)">
            <div style="width:60px;font-size:10px;font-weight:700;color:<?php echo esc_attr($fs[2]); ?>"><?php echo esc_html($fs[0]); ?></div>
            <div style="flex:1;height:6px;background:rgba(255,255,255,0.05);border-radius:3px;overflow:hidden">
                <div style="height:100%;width:<?php echo esc_attr((string)$fp); ?>%;background:<?php echo esc_attr($fs[2]); ?>;border-radius:3px;transition:width 1s ease"></div>
            </div>
            <div style="width:40px;text-align:right;font-size:11px;font-weight:700;color:var(--gt-white)"><?php echo esc_html(number_format($fs[1])); ?></div>
        </div>
        <?php endforeach; ?>
    </div>
</div>

<!-- ═══ LIFT REPORT ══════════════════════════════════════════════════════════ -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
    <div class="gt-card-header">
        <h2 class="gt-card-title">⚡ Incremental Lift — Treatment vs Control</h2>
        <span style="font-size:11px;color:var(--gt-subtle)">2% holdout · Chi-square significance</span>
    </div>
    <?php if ($sample_size < 30) : ?>
    <div style="padding:28px;text-align:center;color:var(--gt-subtle);font-size:13px">
        Needs <?php echo esc_html((string)(30-$sample_size)); ?> more samples (<?php echo esc_html((string)$sample_size); ?>/30).
        Lift tracking is working — data accumulates as deals fire and orders complete.
    </div>
    <?php else : ?>
    <div style="display:grid;grid-template-columns:repeat(4,1fr);gap:0">
        <?php
        $lift_cells = [
            ['Treatment CR',    $treatment_cr.'%', '#22c55e',        'Customers who saw deals'],
            ['Control CR',      $control_cr.'%',   'var(--gt-subtle)','Holdout — no deal shown'],
            ['Lift',            ($lift_pct>0?'+':'').$lift_pct.'%', $lift_color, $significant?'✓ Statistically significant':'Needs 100+ per arm'],
            ['Sample Size',     number_format($sample_size), '#3b82f6', $days.'-day window'],
        ];
        foreach ($lift_cells as $i => $lc) : ?>
        <div style="padding:20px 16px;text-align:center;<?php echo $i<3?'border-right:1px solid var(--gt-border);':''; ?>">
            <div style="font-size:28px;font-weight:900;color:<?php echo esc_attr($lc[2]); ?>;margin-bottom:4px"><?php echo esc_html($lc[1]); ?></div>
            <div style="font-size:10px;font-weight:800;text-transform:uppercase;letter-spacing:.08em;color:var(--gt-subtle);margin-bottom:3px"><?php echo esc_html($lc[0]); ?></div>
            <div style="font-size:10px;color:rgba(100,116,139,0.7)"><?php echo esc_html($lc[3]); ?></div>
        </div>
        <?php endforeach; ?>
    </div>
    <?php endif; ?>
</div>

<!-- ═══ CHANNEL BREAKDOWN + ABANDON ANALYSIS ════════════════════════════════ -->
<div class="gt-animate-in" style="display:grid;grid-template-columns:1fr 1fr;gap:16px;margin-bottom:20px">

    <!-- Channel breakdown -->
    <div class="gt-card">
        <div class="gt-card-header"><h2 class="gt-card-title">Channel Performance</h2></div>
        <?php if (empty($channel_data)) : ?>
        <div style="padding:20px;color:var(--gt-subtle);font-size:13px">No channel data yet</div>
        <?php else : ?>
        <table style="width:100%;border-collapse:collapse;font-size:12px">
            <thead><tr style="border-bottom:1px solid var(--gt-border)">
                <?php foreach (['Channel','Fires','Accepted','CR'] as $c) : ?>
                <th style="padding:8px 12px;text-align:left;font-size:10px;font-weight:800;letter-spacing:.08em;text-transform:uppercase;color:var(--gt-subtle)"><?php echo esc_html($c); ?></th>
                <?php endforeach; ?>
            </tr></thead>
            <tbody>
            <?php foreach ($channel_data as $ch => $cd) :
                $ch_cr = $cd['fires']>0 ? round($cd['accepted']/$cd['fires']*100,1) : 0;
                $cr_c  = $ch_cr>=30?'#22c55e':($ch_cr>=15?'#f59e0b':'#ef4444');
            ?>
            <tr style="border-bottom:1px solid rgba(255,255,255,0.03)">
                <td style="padding:8px 12px;font-weight:600;color:var(--gt-white)"><?php echo esc_html(ucfirst(str_replace('_',' ',$ch))); ?></td>
                <td style="padding:8px 12px;color:var(--gt-subtle)"><?php echo esc_html(number_format($cd['fires'])); ?></td>
                <td style="padding:8px 12px;color:#22c55e;font-weight:700"><?php echo esc_html(number_format($cd['accepted'])); ?></td>
                <td style="padding:8px 12px;color:<?php echo esc_attr($cr_c); ?>;font-weight:700"><?php echo esc_html($ch_cr.'%'); ?></td>
            </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
        <?php endif; ?>
    </div>

    <!-- Abandon reasons -->
    <div class="gt-card">
        <div class="gt-card-header"><h2 class="gt-card-title">Abandoned Deal Reasons</h2></div>
        <?php if (empty($abandon_reasons)) : ?>
        <div style="padding:20px;color:var(--gt-subtle);font-size:13px">
            No expired deals with recorded reasons yet.
        </div>
        <?php else :
            $max_ab = max(1, max($abandon_reasons));
            foreach ($abandon_reasons as $reason => $cnt) :
                $ab_pct = round($cnt / $max_ab * 100);
        ?>
        <div style="display:flex;align-items:center;gap:8px;padding:7px 0;border-bottom:1px solid rgba(255,255,255,0.04)">
            <div style="flex:1;min-width:0">
                <div style="font-size:11px;color:var(--gt-white);font-weight:600;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">
                    <?php echo esc_html($reason?:'-'); ?>
                </div>
                <div style="height:4px;background:rgba(255,255,255,0.05);border-radius:2px;margin-top:4px;overflow:hidden">
                    <div style="height:100%;width:<?php echo esc_attr((string)$ab_pct); ?>%;background:#ef4444;border-radius:2px"></div>
                </div>
            </div>
            <div style="font-size:11px;font-weight:700;color:var(--gt-subtle);width:32px;text-align:right">
                <?php echo esc_html(number_format($cnt)); ?>
            </div>
        </div>
        <?php endforeach; endif; ?>
    </div>
</div>

<!-- ═══ ATTRIBUTION ══════════════════════════════════════════════════════════ -->
<?php if (!empty($attr_data)) : ?>
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
    <div class="gt-card-header">
        <h2 class="gt-card-title">Superpower Attribution — <?php echo esc_html(ucwords(str_replace('_',' ',$attr_model))); ?></h2>
        <div style="display:flex;gap:4px">
            <?php foreach (['last_touch'=>'Last Touch','first_touch'=>'First Touch','linear'=>'Linear','time_decay'=>'Time Decay'] as $m=>$ml) : ?>
            <a href="<?php echo esc_url(add_query_arg(['days'=>$days,'attr'=>$m])); ?>"
               style="padding:4px 10px;border-radius:20px;font-size:10px;font-weight:700;text-decoration:none;
                      background:<?php echo $attr_model===$m?'rgba(59,130,246,0.2)':'rgba(255,255,255,0.04)'; ?>;
                      color:<?php echo $attr_model===$m?'#60a5fa':'var(--gt-subtle)'; ?>;
                      border:1px solid <?php echo $attr_model===$m?'rgba(59,130,246,0.4)':'rgba(255,255,255,0.06)'; ?>">
                <?php echo esc_html($ml); ?>
            </a>
            <?php endforeach; ?>
        </div>
    </div>
    <div style="overflow-x:auto">
        <table style="width:100%;border-collapse:collapse;font-size:12px">
            <thead><tr style="border-bottom:1px solid var(--gt-border)">
                <?php foreach (['Superpower','Impressions','Conversions','Conv. Rate','Attribution Share'] as $c) : ?>
                <th style="padding:9px 12px;text-align:left;font-size:10px;font-weight:800;letter-spacing:.08em;text-transform:uppercase;color:var(--gt-subtle)"><?php echo esc_html($c); ?></th>
                <?php endforeach; ?>
            </tr></thead>
            <tbody>
            <?php
            $max_conv_attr = max(1, array_sum(array_column($attr_data,'conversions')));
            foreach ($attr_data as $ar) :
                $share = round($ar['conversions']/$max_conv_attr*100);
                $cr_c  = $ar['conversion_rate']>=30?'#22c55e':($ar['conversion_rate']>=15?'#f59e0b':'#ef4444');
            ?>
            <tr style="border-bottom:1px solid rgba(255,255,255,0.03)">
                <td style="padding:9px 12px;font-weight:600;color:var(--gt-white)"><?php echo esc_html(ucwords(str_replace('-',' ',$ar['sp_id']))); ?></td>
                <td style="padding:9px 12px;color:var(--gt-subtle)"><?php echo esc_html(number_format($ar['impressions'])); ?></td>
                <td style="padding:9px 12px;color:#22c55e;font-weight:700"><?php echo esc_html(number_format($ar['conversions'])); ?></td>
                <td style="padding:9px 12px;color:<?php echo esc_attr($cr_c); ?>;font-weight:700"><?php echo esc_html($ar['conversion_rate'].'%'); ?></td>
                <td style="padding:9px 12px">
                    <div style="display:flex;align-items:center;gap:8px">
                        <div style="flex:1;height:5px;background:rgba(255,255,255,0.06);border-radius:3px;overflow:hidden">
                            <div style="width:<?php echo esc_attr((string)$share); ?>%;height:100%;background:var(--gt-red);border-radius:3px"></div>
                        </div>
                        <span style="font-size:10px;color:var(--gt-subtle);width:28px;text-align:right"><?php echo esc_html($share.'%'); ?></span>
                    </div>
                </td>
            </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>
<?php endif; ?>

<!-- ═══ RULE LEADERBOARD ═════════════════════════════════════════════════════ -->
<?php if (!empty($leaderboard)) : ?>
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
    <div class="gt-card-header">
        <h2 class="gt-card-title">🏆 Rule Leaderboard — <?php echo esc_html($days); ?>d</h2>
        <a href="<?php echo esc_url(admin_url('admin.php?page=gt-bogo-engine&tab=rule-performance')); ?>"
           class="gt-btn gt-btn-ghost gt-btn-sm">Full Analytics →</a>
    </div>
    <div style="overflow-x:auto">
        <table style="width:100%;border-collapse:collapse;font-size:12px">
            <thead><tr style="border-bottom:1px solid var(--gt-border)">
                <th style="padding:9px 12px;text-align:left;font-size:10px;font-weight:800;letter-spacing:.08em;text-transform:uppercase;color:var(--gt-subtle)">#</th>
                <?php foreach (['Rule','Fires','Accepted','Conv. Rate','Deal Volume'] as $c) : ?>
                <th style="padding:9px 12px;text-align:left;font-size:10px;font-weight:800;letter-spacing:.08em;text-transform:uppercase;color:var(--gt-subtle)"><?php echo esc_html($c); ?></th>
                <?php endforeach; ?>
            </tr></thead>
            <tbody>
            <?php foreach ($leaderboard as $i => $r) :
                $r_cr  = $r['fires']>0 ? round($r['accepted']/$r['fires']*100,1) : 0;
                $r_c   = $r_cr>=30?'#22c55e':($r_cr>=15?'#f59e0b':'#ef4444');
                $r_name= $rule_names[(int)$r['rule_id']] ?? 'Rule #'.(int)$r['rule_id'];
            ?>
            <tr style="border-bottom:1px solid rgba(255,255,255,0.03)">
                <td style="padding:9px 12px;color:var(--gt-subtle);font-size:11px"><?php echo esc_html((string)($i+1)); ?></td>
                <td style="padding:9px 12px;font-weight:600;color:var(--gt-white);max-width:200px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap"><?php echo esc_html($r_name); ?></td>
                <td style="padding:9px 12px;color:var(--gt-subtle)"><?php echo esc_html(number_format($r['fires'])); ?></td>
                <td style="padding:9px 12px;color:#22c55e;font-weight:700"><?php echo esc_html(number_format($r['accepted'])); ?></td>
                <td style="padding:9px 12px;color:<?php echo esc_attr($r_c); ?>;font-weight:700"><?php echo esc_html($r_cr.'%'); ?></td>
                <td style="padding:9px 12px;color:#f59e0b">$<?php echo esc_html(number_format($r['deal_value_total'],0)); ?></td>
            </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>
<?php endif; ?>

<!-- ═══ CHAMPION vs CHALLENGER ══════════════════════════════════════════════ -->
<?php if (!empty($challengers)) : ?>
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
    <div class="gt-card-header">
        <h2 class="gt-card-title">⚔ Champion vs Challenger</h2>
        <a href="<?php echo esc_url(admin_url('admin.php?page=gt-bogo-engine&tab=ab-testing')); ?>"
           class="gt-btn gt-btn-ghost gt-btn-sm">A/B Testing →</a>
    </div>
    <div style="overflow-x:auto">
        <table style="width:100%;border-collapse:collapse;font-size:12px">
            <thead><tr style="border-bottom:1px solid var(--gt-border)">
                <?php foreach (['Challenger','Status','Sessions','Champion CR','Challenger CR','Verdict',''] as $c) : ?>
                <th style="padding:9px 12px;text-align:left;font-size:10px;font-weight:800;letter-spacing:.08em;text-transform:uppercase;color:var(--gt-subtle)"><?php echo esc_html($c); ?></th>
                <?php endforeach; ?>
            </tr></thead>
            <tbody>
            <?php foreach ($challengers as $ch) :
                $ch_cr   = round(($ch['challenger_cr']??0)*100,1);
                $champ_cr= round(($ch['champion_cr']??0)*100,1);
                $winning = $ch_cr > $champ_cr;
                $status  = $ch['status'] ?? 'running';
                $sc_map  = ['running'=>'#3b82f6','ready'=>'#22c55e','promoted'=>'#f59e0b','rejected'=>'#64748b'];
                $sc      = $sc_map[$status] ?? '#64748b';
            ?>
            <tr style="border-bottom:1px solid rgba(255,255,255,0.03)">
                <td style="padding:9px 12px;font-weight:600;color:var(--gt-white)"><?php echo esc_html($ch['name']??$ch['id']??'—'); ?></td>
                <td style="padding:9px 12px"><span style="color:<?php echo esc_attr($sc); ?>;font-weight:700;text-transform:capitalize"><?php echo esc_html($status); ?></span></td>
                <td style="padding:9px 12px;color:var(--gt-subtle)"><?php echo esc_html(number_format($ch['sessions']??0)); ?></td>
                <td style="padding:9px 12px;color:var(--gt-subtle)"><?php echo esc_html($champ_cr.'%'); ?></td>
                <td style="padding:9px 12px;color:<?php echo $winning?'#22c55e':'#ef4444'; ?>;font-weight:700"><?php echo esc_html($ch_cr.'%'); ?></td>
                <td style="padding:9px 12px;font-size:11px;color:<?php echo $winning?'#22c55e':'#64748b'; ?>">
                    <?php echo $winning ? 'Challenger winning' : 'Champion leads'; ?>
                </td>
                <td style="padding:9px 12px">
                    <?php if ($status==='ready') : ?>
                    <a href="<?php echo esc_url(admin_url('admin.php?page=gt-bogo-engine&tab=ab-testing')); ?>"
                       class="gt-btn gt-btn-primary gt-btn-sm">Promote →</a>
                    <?php endif; ?>
                </td>
            </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>
<?php endif; ?>

<script>
document.addEventListener('DOMContentLoaded', function() {
    /* Trend chart */
    var tCtx = document.getElementById('gt-oi-trend-chart');
    if (tCtx && <?php echo json_encode(!empty($chart_labels)); ?>) {
        new Chart(tCtx.getContext('2d'), {
            type: 'line',
            data: {
                labels: <?php echo $chart_labels_j; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>,
                datasets: [
                    { label:'Fires', data:<?php echo $chart_fires_j; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>, borderColor:'#f59e0b', backgroundColor:'rgba(245,158,11,0.06)', borderWidth:2, tension:.35, fill:true, pointRadius:2 },
                    { label:'Accepted', data:<?php echo $chart_accepted_j; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>, borderColor:'#22c55e', backgroundColor:'rgba(34,197,94,0.06)', borderWidth:2, tension:.35, fill:true, pointRadius:2 }
                ]
            },
            options: { responsive:true, maintainAspectRatio:false, interaction:{mode:'index',intersect:false},
                       plugins:{legend:{labels:{color:'#64748b',font:{size:10}}}},
                       scales:{ x:{grid:{color:'rgba(255,255,255,0.04)'},ticks:{color:'#475569',font:{size:9},maxTicksLimit:8}},
                                y:{grid:{color:'rgba(255,255,255,0.04)'},ticks:{color:'#475569',font:{size:9}}} } }
        });
    }
    /* Animate funnel bars */
    document.querySelectorAll('[style*="transition:width"]').forEach(function(el){
        var w=el.style.width; el.style.width='0%'; setTimeout(function(){el.style.width=w;},200);
    });
});
</script>

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