<?php
// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals
// phpcs:disable WordPress.Security.NonceVerification
// phpcs:disable WordPress.Security.ValidatedSanitizedInput
// 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 — Rule Performance Intelligence
 *
 * Full per-rule analytics: fires, conversions, margin, lift vs control,
 * segment breakdown, Chart.js visualisations, attribution model selector,
 * sortable/searchable table, per-rule accordion drill-down, and CSV export.
 *
 * Data sources:
 *   GT_BOGO_Outcome_Capture   — fires / accepted / expired / margin
 *   GT_BOGO_Rule_Analytics    — impressions / conversions / revenue_influenced / segments
 *   GT_BOGO_Attribution_Engine — SP-level attribution report
 *   gtbogo_rules              — rule names, status, type
 *
 * @package GT_BOGO_Engine
 * @since   5.0.0
 */

if ( ! defined( 'ABSPATH' ) ) exit;
if ( ! current_user_can( 'manage_woocommerce' ) ) {
    wp_die( esc_html__( 'Insufficient permissions.', 'gt-bogo-engine' ) );
}

global $wpdb;

/* ── Date window ──────────────────────────────────────────────────────────── */
$days = isset( $_GET['perf_days'] ) ? (int) wp_unslash( $_GET['perf_days'] ) : 30;
$days = in_array( $days, [ 7, 30, 90 ], true ) ? $days : 30;

/* ── Attribution model ────────────────────────────────────────────────────── */
$attr_model   = isset( $_GET['attr'] ) ? sanitize_key( wp_unslash( $_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';

/* ── Rule performance summary from Outcome Capture ───────────────────────── */
$perf_data = class_exists( 'GT_BOGO_Outcome_Capture' )
    ? GT_BOGO_Outcome_Capture::instance()->get_rule_performance_summary( $days )
    : [];

/* ── Outcome summary (funnel) ─────────────────────────────────────────────── */
$summary = class_exists( 'GT_BOGO_Outcome_Capture' )
    ? GT_BOGO_Outcome_Capture::get_summary( $days )
    : [ 'eligible' => 0, 'fired' => 0, 'accepted' => 0, 'rejected' => 0, 'expired' => 0 ];

/* ── Lift report (treatment vs control group) ────────────────────────────── */
$lift_report = class_exists( 'GT_BOGO_Outcome_Capture' )
    ? GT_BOGO_Outcome_Capture::get_lift_report( 0, $days )
    : [];

/* ── Rule leaderboard (top rules by accepted) ────────────────────────────── */
$leaderboard = class_exists( 'GT_BOGO_Outcome_Capture' )
    ? GT_BOGO_Outcome_Capture::get_rule_leaderboard( $days, 20 )
    : [];

/* ── All active rules from DB (for name lookup) ──────────────────────────── */
$rules_tbl = $wpdb->prefix . 'gtbogo_rules';
$has_rules = (bool) $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $rules_tbl ) ); // phpcs:ignore

$all_rules = [];
if ( $has_rules ) {
    $rows = $wpdb->get_results( // phpcs:ignore
        "SELECT id, name, status, buy_type, get_type, buy_qty, get_qty,
                impressions, conversions, revenue_influenced
         FROM {$rules_tbl}
         ORDER BY status ASC, name ASC
         LIMIT 200",
        ARRAY_A
    );
    foreach ( $rows as $r ) {
        $all_rules[ (int) $r['id'] ] = $r;
    }
}

/* ── Chart data: daily fires & accepted for the chosen window ────────────── */
$outcomes_tbl = $wpdb->prefix . 'gtbogo_outcomes';
$has_outcomes = (bool) $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $outcomes_tbl ) ); // phpcs:ignore

$chart_labels  = [];
$chart_fires   = [];
$chart_conv    = [];

if ( $has_outcomes ) {
    $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_tbl}
         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_conv[]   = (int) $d['accepted'];
    }
}

$chart_labels_json = wp_json_encode( $chart_labels );
$chart_fires_json  = wp_json_encode( $chart_fires );
$chart_conv_json   = wp_json_encode( $chart_conv );

/* ── Top rules for bar chart ─────────────────────────────────────────────── */
$bar_labels  = [];
$bar_revenue = [];
foreach ( array_slice( $leaderboard, 0, 10 ) as $lb ) {
    $rule_name     = $all_rules[ $lb['rule_id'] ]['name'] ?? 'Rule #' . $lb['rule_id'];
    $bar_labels[]  = mb_strimwidth( $rule_name, 0, 22, '…' );
    $bar_revenue[] = round( $lb['deal_value_total'], 2 );
}
$bar_labels_json  = wp_json_encode( $bar_labels );
$bar_revenue_json = wp_json_encode( $bar_revenue );

/* ── Global KPIs ─────────────────────────────────────────────────────────── */
$total_fires  = array_sum( array_column( $leaderboard, 'fires' ) );
$total_conv   = array_sum( array_column( $leaderboard, 'accepted' ) );
$total_deal   = array_sum( array_column( $leaderboard, 'deal_value_total' ) );
$overall_rate = $total_fires > 0 ? round( $total_conv / $total_fires * 100, 1 ) : 0.0;
$total_margin = array_sum( array_column( $perf_data, 'margin' ) );
$net_impact   = $total_margin - $total_deal;

$control_rate = class_exists( 'GT_BOGO_Outcome_Capture' )
    ? round( GT_BOGO_Outcome_Capture::get_control_conversion_rate( $days ) * 100, 1 )
    : 0.0;

$lift_pct     = isset( $lift_report['lift_pct'] ) ? $lift_report['lift_pct'] : 0.0;
$lift_sig     = isset( $lift_report['significant'] ) ? $lift_report['significant'] : false;

/* ── Nonce for AJAX ───────────────────────────────────────────────────────── */
$nonce = wp_create_nonce( 'gtbogo_rule_perf' );

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">📈 Rule Performance</h1>
        <p class="gt-page-subtitle">
            Closed-loop outcome analytics per BOGO rule — fires, conversions, margin
            contribution, lift vs control, and segment intelligence.
        </p>
    </div>
    <div style="display:flex;gap:10px;flex-wrap:wrap;align-items:center">
        <button type="button" class="gt-btn gt-btn-ghost gt-btn-sm"
            onclick="gtRpExportCSV('<?php echo esc_js( $nonce ); ?>')"
            style="display:flex;align-items:center;gap:6px">
            ↓ Export CSV
        </button>
        <a href="<?php echo esc_url( admin_url( 'admin.php?page=gt-bogo-engine&tab=analytics' ) ); ?>"
           class="gt-btn gt-btn-ghost gt-btn-sm">
            ← Full Analytics
        </a>
    </div>
</div>

<!-- ── Date window + Attribution model ───────────────────────────────────── -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
    <div style="padding:14px 20px;display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:14px">
        <!-- Date range -->
        <div style="display:flex;align-items:center;gap:6px">
            <span style="font-size:12px;color:var(--gt-subtle);font-weight:600;text-transform:uppercase;letter-spacing:.08em;margin-right:6px">Window</span>
            <?php foreach ( [ 7 => '7 days', 30 => '30 days', 90 => '90 days' ] as $d => $label ) :
                $active = $days === $d;
            ?>
            <a href="<?php echo esc_url( add_query_arg( [ 'perf_days' => $d, 'attr' => $attr_model ] ) ); ?>"
               style="padding:6px 14px;border-radius:20px;font-size:12px;font-weight:700;text-decoration:none;
                      background:<?php echo $active ? 'var(--gt-red)' : 'rgba(255,255,255,0.05)'; ?>;
                      color:<?php echo $active ? '#fff' : 'var(--gt-subtle)'; ?>;
                      border:1px solid <?php echo $active ? 'var(--gt-red)' : 'rgba(255,255,255,0.08)'; ?>">
                <?php echo esc_html( $label ); ?>
            </a>
            <?php endforeach; ?>
        </div>
        <!-- Attribution model -->
        <div style="display:flex;align-items:center;gap:6px">
            <span style="font-size:12px;color:var(--gt-subtle);font-weight:600;text-transform:uppercase;letter-spacing:.08em;margin-right:4px">Attribution</span>
            <?php
            $model_labels = [
                'last_touch'  => 'Last Touch',
                'first_touch' => 'First Touch',
                'linear'      => 'Linear',
                'time_decay'  => 'Time Decay',
            ];
            foreach ( $model_labels as $m => $ml ) :
                $active = $attr_model === $m;
            ?>
            <a href="<?php echo esc_url( add_query_arg( [ 'perf_days' => $days, 'attr' => $m ] ) ); ?>"
               style="padding:6px 12px;border-radius:20px;font-size:12px;font-weight:600;text-decoration:none;
                      background:<?php echo $active ? 'rgba(59,130,246,0.2)' : 'rgba(255,255,255,0.04)'; ?>;
                      color:<?php echo $active ? '#60a5fa' : 'var(--gt-subtle)'; ?>;
                      border:1px solid <?php echo $active ? 'rgba(59,130,246,0.4)' : 'rgba(255,255,255,0.06)'; ?>">
                <?php echo esc_html( $ml ); ?>
            </a>
            <?php endforeach; ?>
        </div>
        <!-- Last refreshed -->
        <div style="font-size:11px;color:var(--gt-subtle)">
            Outcomes resolved on order completion &nbsp;·&nbsp; Unresolved = expired after 2h
            &nbsp;·&nbsp; <span id="gt-rp-last-refresh">Refreshed <?php echo esc_html( gmdate( 'H:i' ) ); ?> UTC</span>
            <button type="button" onclick="gtRpRefresh()" style="background:none;border:none;color:var(--gt-red);cursor:pointer;font-size:11px;margin-left:4px">↻ Refresh</button>
        </div>
    </div>
</div>

<!-- ═══════════════════════════════════════════════════════════════════════════
     8 KPI CARDS
════════════════════════════════════════════════════════════════════════════ -->
<div class="gt-animate-in" style="display:grid;grid-template-columns:repeat(4,1fr);gap:14px;margin-bottom:20px">
    <?php
    $rate_color  = $overall_rate >= 30 ? '#22c55e' : ( $overall_rate >= 15 ? '#f59e0b' : '#ef4444' );
    $lift_color  = $lift_pct > 0 ? '#22c55e' : ( $lift_pct === 0.0 ? 'var(--gt-subtle)' : '#ef4444' );
    $net_color   = $net_impact >= 0 ? '#22c55e' : '#ef4444';

    $kpis = [
        [ 'label' => 'Total Fires',      'value' => number_format( $total_fires ),           'color' => 'var(--gt-white)', 'sub' => 'deal_fired events' ],
        [ 'label' => 'Conversions',       'value' => number_format( $total_conv ),            'color' => '#22c55e',        'sub' => 'deal_accepted events' ],
        [ 'label' => 'Conversion Rate',   'value' => $overall_rate . '%',                     'color' => $rate_color,      'sub' => 'accepted ÷ fired' ],
        [ 'label' => 'Total Margin',      'value' => '$' . number_format( $total_margin, 0 ), 'color' => '#22c55e',        'sub' => 'margin contribution' ],
        [ 'label' => 'Discount Volume',   'value' => '$' . number_format( $total_deal, 0 ),   'color' => '#f59e0b',        'sub' => 'total deal value given' ],
        [ 'label' => 'Net Revenue Impact','value' => ( $net_impact >= 0 ? '+' : '' ) . '$' . number_format( $net_impact, 0 ), 'color' => $net_color, 'sub' => 'margin minus discounts' ],
        [ 'label' => 'Control Conv. Rate','value' => $control_rate . '%',                     'color' => 'var(--gt-subtle)', 'sub' => '2% holdout group' ],
        [ 'label' => 'Incremental Lift',  'value' => ( $lift_pct > 0 ? '+' : '' ) . $lift_pct . '%', 'color' => $lift_color, 'sub' => $lift_sig ? '✓ statistically significant' : 'needs more data' ],
    ];
    foreach ( $kpis as $kpi ) :
    ?>
    <div class="gt-card" style="padding:18px 20px;text-align:center">
        <div class="gt-counter" data-target="<?php echo esc_attr( preg_replace( '/[^0-9.]/', '', $kpi['value'] ) ); ?>"
             style="font-size:26px;font-weight:900;color:<?php echo esc_attr( $kpi['color'] ); ?>;margin-bottom:4px;line-height:1">
            <?php echo esc_html( $kpi['value'] ); ?>
        </div>
        <div style="font-size:10px;font-weight:800;letter-spacing:.1em;text-transform:uppercase;color:var(--gt-subtle);margin-bottom:3px">
            <?php echo esc_html( $kpi['label'] ); ?>
        </div>
        <div style="font-size:11px;color:rgba(100,116,139,0.7)">
            <?php echo esc_html( $kpi['sub'] ); ?>
        </div>
    </div>
    <?php endforeach; ?>
</div>

<!-- ═══════════════════════════════════════════════════════════════════════════
     CONVERSION FUNNEL
════════════════════════════════════════════════════════════════════════════ -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
    <div class="gt-card-header">
        <h2 class="gt-card-title">Deal Lifecycle Funnel</h2>
        <span style="font-size:12px;color:var(--gt-subtle)"><?php echo esc_html( $days ); ?>-day window</span>
    </div>
    <div style="display:grid;grid-template-columns:repeat(5,1fr);gap:0">
        <?php
        $funnel_steps = [
            [ 'label' => 'Eligible',   'key' => 'eligible',  'color' => '#3b82f6',  'icon' => '◎' ],
            [ 'label' => 'Fired',      'key' => 'fired',     'color' => '#f59e0b',  'icon' => '⚡' ],
            [ 'label' => 'Accepted',   'key' => 'accepted',  'color' => '#22c55e',  'icon' => '✓' ],
            [ 'label' => 'Rejected',   'key' => 'rejected',  'color' => '#ef4444',  'icon' => '✗' ],
            [ 'label' => 'Expired',    'key' => 'expired',   'color' => 'var(--gt-subtle)', 'icon' => '⌛' ],
        ];
        $max_funnel = max( 1, $summary['eligible'] ?? 1 );
        foreach ( $funnel_steps as $i => $step ) :
            $val = (int) ( $summary[ $step['key'] ] ?? 0 );
            $pct = $max_funnel > 0 ? round( $val / $max_funnel * 100, 0 ) : 0;
        ?>
        <div style="padding:20px 16px;text-align:center;<?php echo $i < 4 ? 'border-right:1px solid var(--gt-border);' : ''; ?>position:relative">
            <div style="font-size:18px;margin-bottom:6px"><?php echo esc_html( $step['icon'] ); ?></div>
            <div style="font-size:22px;font-weight:800;color:<?php echo esc_attr( $step['color'] ); ?>;margin-bottom:4px">
                <?php echo esc_html( number_format( $val ) ); ?>
            </div>
            <div style="font-size:10px;font-weight:700;text-transform:uppercase;letter-spacing:.08em;color:var(--gt-subtle);margin-bottom:8px">
                <?php echo esc_html( $step['label'] ); ?>
            </div>
            <div style="height:4px;background:rgba(255,255,255,0.06);border-radius:2px;overflow:hidden">
                <div style="height:100%;width:<?php echo esc_attr( (string) $pct ); ?>%;background:<?php echo esc_attr( $step['color'] ); ?>;border-radius:2px;transition:width 1.4s ease"></div>
            </div>
            <div style="font-size:10px;color:rgba(100,116,139,0.6);margin-top:4px"><?php echo esc_html( $pct ); ?>% of eligible</div>
        </div>
        <?php endforeach; ?>
    </div>
</div>

<!-- ═══════════════════════════════════════════════════════════════════════════
     CHARTS — FIRES vs CONVERSIONS (line) + TOP RULES (bar)
════════════════════════════════════════════════════════════════════════════ -->
<div class="gt-animate-in" style="display:grid;grid-template-columns:2fr 1fr;gap:16px;margin-bottom:20px">

    <!-- Fires vs Conversions line chart -->
    <div class="gt-card">
        <div class="gt-card-header">
            <h2 class="gt-card-title">Fires vs Conversions — <?php echo esc_html( $days ); ?>-Day Trend</h2>
        </div>
        <div class="gt-chart-wrap" style="height:220px;padding:0 4px 8px">
            <?php if ( empty( $chart_labels ) ) : ?>
            <div style="height:220px;display:flex;align-items:center;justify-content:center;color:var(--gt-subtle);font-size:13px">
                No outcome data in the last <?php echo esc_html( (string) $days ); ?> days.
                Fires are recorded as deals apply to carts.
            </div>
            <?php else : ?>
            <canvas id="gt-rp-line-chart"></canvas>
            <?php endif; ?>
        </div>
    </div>

    <!-- Top rules by deal value bar chart -->
    <div class="gt-card">
        <div class="gt-card-header">
            <h2 class="gt-card-title">Top Rules by Deal Volume</h2>
        </div>
        <div class="gt-chart-wrap" style="height:220px;padding:0 4px 8px">
            <?php if ( empty( $bar_labels ) ) : ?>
            <div style="height:220px;display:flex;align-items:center;justify-content:center;color:var(--gt-subtle);font-size:13px;text-align:center">
                No leaderboard data yet.
            </div>
            <?php else : ?>
            <canvas id="gt-rp-bar-chart"></canvas>
            <?php endif; ?>
        </div>
    </div>
</div>

<!-- ═══════════════════════════════════════════════════════════════════════════
     LIFT REPORT — TREATMENT vs CONTROL
════════════════════════════════════════════════════════════════════════════ -->
<?php if ( ! empty( $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 Report — Treatment vs Control Group</h2>
        <span style="font-size:12px;color:var(--gt-subtle)">
            2% of eligible customers held back as control · Chi-square significance test
        </span>
    </div>
    <div style="display:grid;grid-template-columns:repeat(4,1fr);gap:0">
        <?php
        $tr_cr = round( ( $lift_report['treatment_cr'] ?? 0 ) * 100, 2 );
        $ct_cr = round( ( $lift_report['control_cr']   ?? 0 ) * 100, 2 );
        $lp    = $lift_report['lift_pct']    ?? 0;
        $ss    = $lift_report['sample_size'] ?? 0;
        $sig   = $lift_report['significant'] ?? false;

        $lp_color = $lp > 0 ? '#22c55e' : ( $lp < 0 ? '#ef4444' : 'var(--gt-subtle)' );

        $lift_cells = [
            [ 'Treatment CR',   $tr_cr . '%',  '#22c55e', 'Customers who saw BOGO deals' ],
            [ 'Control CR',     $ct_cr . '%',  'var(--gt-subtle)', 'Holdout — no deal shown' ],
            [ 'Incremental Lift', ( $lp > 0 ? '+' : '' ) . $lp . '%', $lp_color, 'Revenue lift from deals' ],
            [ 'Sample Size',    number_format( $ss ), '#3b82f6', $sig ? '✓ Statistically significant' : 'Needs 100+ per arm' ],
        ];
        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:4px">
                <?php echo esc_html( $lc[0] ); ?>
            </div>
            <div style="font-size:11px;color:rgba(100,116,139,0.7)"><?php echo esc_html( $lc[3] ); ?></div>
        </div>
        <?php endforeach; ?>
    </div>
    <?php if ( ! $sig && $ss > 0 ) : ?>
    <div style="padding:10px 20px;background:rgba(245,158,11,0.05);border-top:1px solid var(--gt-border);font-size:12px;color:#f59e0b">
        ⚠ Significance requires 100+ sessions per arm. Current sample: <?php echo esc_html( number_format( $ss ) ); ?> total.
        Results will stabilize as volume grows.
    </div>
    <?php endif; ?>
</div>
<?php endif; ?>

<!-- ═══════════════════════════════════════════════════════════════════════════
     RULES TABLE — SEARCHABLE, SORTABLE, WITH ACCORDION DRILL-DOWN
════════════════════════════════════════════════════════════════════════════ -->
<div class="gt-card gt-animate-in" style="overflow:hidden;margin-bottom:20px">
    <div class="gt-card-header" style="flex-wrap:wrap;gap:12px">
        <h2 class="gt-card-title">Per-Rule Performance</h2>
        <div style="display:flex;gap:8px;flex-wrap:wrap">
            <!-- Search -->
            <input type="text" id="gt-rp-search"
                   placeholder="Search rules…"
                   oninput="gtRpFilter()"
                   style="padding:7px 12px;background:var(--gt-card);border:1px solid var(--gt-border-md);
                          border-radius:6px;color:var(--gt-white);font-size:13px;width:200px;
                          font-family:inherit">
            <!-- Status filter -->
            <select id="gt-rp-status-filter" onchange="gtRpFilter()"
                    style="padding:7px 12px;background:var(--gt-card);border:1px solid var(--gt-border-md);
                           border-radius:6px;color:var(--gt-white);font-size:13px;font-family:inherit;cursor:pointer">
                <option value="">All statuses</option>
                <option value="active">Active</option>
                <option value="inactive">Inactive</option>
                <option value="draft">Draft</option>
            </select>
            <!-- Sort -->
            <select id="gt-rp-sort" onchange="gtRpSort()"
                    style="padding:7px 12px;background:var(--gt-card);border:1px solid var(--gt-border-md);
                           border-radius:6px;color:var(--gt-white);font-size:13px;font-family:inherit;cursor:pointer">
                <option value="conversions-desc">Sort: Conversions ↓</option>
                <option value="fires-desc">Sort: Fires ↓</option>
                <option value="rate-desc">Sort: Conv. Rate ↓</option>
                <option value="margin-desc">Sort: Margin ↓</option>
                <option value="revenue-desc">Sort: Revenue ↓</option>
                <option value="name-asc">Sort: Name A–Z</option>
            </select>
        </div>
    </div>

    <?php
    // Build merged rule list — combine outcome data + rule DB data
    $merged = [];
    // From outcome capture leaderboard
    foreach ( $leaderboard as $lb ) {
        $rid = (int) $lb['rule_id'];
        $row = $all_rules[ $rid ] ?? null;
        $name = $row ? $row['name'] : 'Rule #' . $rid;
        $status = $row['status'] ?? 'active';

        // Get rule analytics (impressions/conversions from rules table)
        $ra = class_exists( 'GT_BOGO_Rule_Analytics' ) && $rid > 0
            ? GT_BOGO_Rule_Analytics::get_rule_performance( $rid )
            : [];

        $merged[ $rid ] = [
            'id'              => $rid,
            'name'            => $name,
            'status'          => $status,
            'buy_type'        => $row['buy_type'] ?? '',
            'get_type'        => $row['get_type'] ?? '',
            'buy_qty'         => $row['buy_qty'] ?? '',
            'get_qty'         => $row['get_qty'] ?? '',
            'fires'           => (int) $lb['fires'],
            'conversions'     => (int) $lb['accepted'],
            'rate'            => $lb['fires'] > 0 ? round( $lb['accepted'] / $lb['fires'] * 100, 1 ) : 0,
            'deal_vol'        => round( $lb['deal_value_total'], 2 ),
            'margin'          => (float) ( $perf_data[ (string) $rid ]['margin'] ?? 0 ),
            'impressions'     => (int) ( $ra['impressions'] ?? 0 ),
            'revenue_inf'     => (float) ( $ra['revenue_influenced'] ?? 0 ),
        ];
    }

    // Also add any active rules that had zero outcomes but exist in DB
    foreach ( $all_rules as $rid => $rule ) {
        if ( isset( $merged[ $rid ] ) ) continue;
        $ra = class_exists( 'GT_BOGO_Rule_Analytics' ) && $rid > 0
            ? GT_BOGO_Rule_Analytics::get_rule_performance( $rid )
            : [];
        $merged[ $rid ] = [
            'id'          => $rid,
            'name'        => $rule['name'],
            'status'      => $rule['status'],
            'buy_type'    => $rule['buy_type'],
            'get_type'    => $rule['get_type'],
            'buy_qty'     => $rule['buy_qty'],
            'get_qty'     => $rule['get_qty'],
            'fires'       => 0,
            'conversions' => 0,
            'rate'        => 0,
            'deal_vol'    => 0,
            'margin'      => 0,
            'impressions' => (int) ( $ra['impressions'] ?? 0 ),
            'revenue_inf' => (float) ( $ra['revenue_influenced'] ?? 0 ),
        ];
    }

    if ( empty( $merged ) ) :
    ?>
    <div style="padding:48px 24px;text-align:center">
        <div style="font-size:40px;margin-bottom:14px">📊</div>
        <p style="font-size:14px;color:var(--gt-subtle);max-width:400px;margin:0 auto;line-height:1.6">
            No outcome data yet for the last <?php echo esc_html( (string) $days ); ?> days.
            Outcomes record automatically as BOGO deals fire and orders are placed.
        </p>
    </div>
    <?php else : ?>

    <div style="overflow-x:auto">
        <table style="width:100%;border-collapse:collapse;font-size:13px" id="gt-rp-table">
            <thead>
                <tr style="border-bottom:1px solid var(--gt-border)">
                    <?php
                    $cols = [
                        'name'        => 'Rule',
                        'status'      => 'Status',
                        'type'        => 'Type',
                        'fires'       => 'Fires',
                        'conversions' => 'Converted',
                        'rate'        => 'Conv. Rate',
                        'deal_vol'    => 'Deal Volume',
                        'margin'      => 'Margin Contrib.',
                        'revenue_inf' => 'Revenue Influenced',
                        'trend'       => 'Trend',
                        'detail'      => '',
                    ];
                    foreach ( $cols as $key => $col ) :
                    ?>
                    <th style="padding:11px 14px;text-align:left;font-size:10px;font-weight:800;
                               letter-spacing:.1em;text-transform:uppercase;color:var(--gt-subtle);
                               <?php echo in_array( $key, ['fires','conversions','rate','deal_vol','margin','revenue_inf'], true ) ? 'cursor:pointer' : ''; ?>"
                        <?php if ( in_array( $key, ['fires','conversions','rate','deal_vol','margin','revenue_inf'], true ) ) : ?>
                        onclick="gtRpSortByCol('<?php echo esc_js( $key ); ?>')"
                        title="Click to sort"
                        <?php endif; ?>>
                        <?php echo esc_html( $col ); ?>
                        <?php if ( in_array( $key, ['fires','conversions','rate','deal_vol','margin','revenue_inf'], true ) ) : ?>
                        <span style="opacity:0.4">⇅</span>
                        <?php endif; ?>
                    </th>
                    <?php endforeach; ?>
                </tr>
            </thead>
            <tbody id="gt-rp-tbody">
            <?php foreach ( $merged as $r ) :
                $r_color   = $r['rate'] >= 30 ? '#22c55e' : ( $r['rate'] >= 15 ? '#f59e0b' : '#ef4444' );
                $s_color   = $r['status'] === 'active' ? '#22c55e' : ( $r['status'] === 'draft' ? '#3b82f6' : 'var(--gt-subtle)' );
                $bar_w     = min( 100, $r['rate'] );
                $net       = $r['margin'] - $r['deal_vol'];
                $net_color = $net >= 0 ? '#22c55e' : '#ef4444';
                $rule_id   = (int) $r['id'];
            ?>
            <tr class="gt-rp-row"
                data-name="<?php echo esc_attr( strtolower( $r['name'] ) ); ?>"
                data-status="<?php echo esc_attr( $r['status'] ); ?>"
                data-fires="<?php echo esc_attr( (string) $r['fires'] ); ?>"
                data-conversions="<?php echo esc_attr( (string) $r['conversions'] ); ?>"
                data-rate="<?php echo esc_attr( (string) $r['rate'] ); ?>"
                data-deal_vol="<?php echo esc_attr( (string) $r['deal_vol'] ); ?>"
                data-margin="<?php echo esc_attr( (string) $r['margin'] ); ?>"
                data-revenue_inf="<?php echo esc_attr( (string) $r['revenue_inf'] ); ?>"
                style="border-bottom:1px solid rgba(255,255,255,0.04);transition:background .15s">

                <!-- Rule name -->
                <td style="padding:13px 14px;font-weight:600;max-width:220px">
                    <div style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--gt-white)">
                        <?php echo esc_html( $r['name'] ); ?>
                    </div>
                    <div style="font-size:11px;color:var(--gt-subtle);margin-top:2px">
                        <?php echo esc_html( 'Rule #' . $rule_id ); ?>
                    </div>
                </td>

                <!-- Status -->
                <td style="padding:13px 14px">
                    <span style="padding:3px 10px;border-radius:20px;font-size:10px;font-weight:800;
                                 text-transform:uppercase;letter-spacing:.06em;
                                 background:<?php echo esc_attr( $s_color ); ?>15;
                                 color:<?php echo esc_attr( $s_color ); ?>">
                        <?php echo esc_html( ucfirst( $r['status'] ) ); ?>
                    </span>
                </td>

                <!-- Type -->
                <td style="padding:13px 14px;color:var(--gt-subtle);font-size:12px;white-space:nowrap">
                    <?php
                    $type_label = '';
                    if ( $r['buy_type'] ) {
                        $type_label = 'Buy ' . $r['buy_qty'] . ' Get ' . $r['get_qty'];
                    }
                    echo esc_html( $type_label ?: ucfirst( $r['buy_type'] ) );
                    ?>
                </td>

                <!-- Fires -->
                <td style="padding:13px 14px;color:var(--gt-subtle);font-variant-numeric:tabular-nums">
                    <?php echo esc_html( number_format( $r['fires'] ) ); ?>
                </td>

                <!-- Converted -->
                <td style="padding:13px 14px;color:#22c55e;font-weight:700;font-variant-numeric:tabular-nums">
                    <?php echo esc_html( number_format( $r['conversions'] ) ); ?>
                </td>

                <!-- Conversion rate with bar -->
                <td style="padding:13px 14px">
                    <div style="display:flex;align-items:center;gap:8px">
                        <div style="width:64px;height:4px;background:rgba(255,255,255,0.07);border-radius:2px;flex-shrink:0">
                            <div style="width:<?php echo esc_attr( (string) $bar_w ); ?>%;height:100%;
                                        background:<?php echo esc_attr( $r_color ); ?>;border-radius:2px"></div>
                        </div>
                        <span style="font-weight:700;color:<?php echo esc_attr( $r_color ); ?>;white-space:nowrap">
                            <?php echo esc_html( $r['rate'] . '%' ); ?>
                        </span>
                    </div>
                </td>

                <!-- Deal volume -->
                <td style="padding:13px 14px;color:var(--gt-white);font-variant-numeric:tabular-nums">
                    $<?php echo esc_html( number_format( $r['deal_vol'], 0 ) ); ?>
                </td>

                <!-- Margin -->
                <td style="padding:13px 14px;font-weight:700;color:<?php echo esc_attr( $net_color ); ?>;font-variant-numeric:tabular-nums">
                    $<?php echo esc_html( number_format( $r['margin'], 0 ) ); ?>
                </td>

                <!-- Revenue influenced -->
                <td style="padding:13px 14px;color:var(--gt-subtle);font-variant-numeric:tabular-nums">
                    $<?php echo esc_html( number_format( $r['revenue_inf'], 0 ) ); ?>
                </td>

                <!-- Trend sparkline placeholder -->
                <td style="padding:13px 14px">
                    <span class="gt-rp-trend" style="font-size:16px;color:<?php echo $r['rate'] >= 20 ? '#22c55e' : ($r['rate'] >= 10 ? '#f59e0b' : ($r['fires'] > 0 ? '#ef4444' : 'var(--gt-subtle)')); ?>">
                        <?php echo $r['fires'] === 0 ? '—' : ($r['rate'] >= 20 ? '↑' : ($r['rate'] >= 10 ? '→' : '↓')); ?>
                    </span>
                </td>

                <!-- Drill-down toggle -->
                <td style="padding:13px 14px">
                    <?php if ( $rule_id > 0 ) : ?>
                    <button type="button"
                        onclick="gtRpDrilldown(<?php echo esc_attr( (string) $rule_id ); ?>, this, '<?php echo esc_js( $nonce ); ?>')"
                        style="padding:5px 12px;background:rgba(255,255,255,0.05);border:1px solid var(--gt-border-md);
                               border-radius:6px;color:var(--gt-subtle);cursor:pointer;font-size:12px;
                               font-family:inherit;transition:all .15s"
                        onmouseover="this.style.background='rgba(255,255,255,0.1)';this.style.color='var(--gt-white)'"
                        onmouseout="this.style.background='rgba(255,255,255,0.05)';this.style.color='var(--gt-subtle)'">
                        ▸ Drill down
                    </button>
                    <?php endif; ?>
                </td>
            </tr>

            <!-- Drill-down row (hidden by default) -->
            <?php if ( $rule_id > 0 ) : ?>
            <tr id="gt-rp-drilldown-<?php echo esc_attr( (string) $rule_id ); ?>"
                style="display:none;background:rgba(255,255,255,0.02)">
                <td colspan="11" style="padding:0">
                    <div id="gt-rp-drilldown-content-<?php echo esc_attr( (string) $rule_id ); ?>"
                         style="padding:0;border-top:1px solid var(--gt-border)">
                        <div style="padding:20px;color:var(--gt-subtle);font-size:13px;text-align:center">
                            Loading rule intelligence…
                        </div>
                    </div>
                </td>
            </tr>
            <?php endif; ?>

            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php endif; ?>
</div>

<!-- ═══════════════════════════════════════════════════════════════════════════
     SEGMENT PERFORMANCE OVERVIEW
════════════════════════════════════════════════════════════════════════════ -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
    <div class="gt-card-header">
        <h2 class="gt-card-title">Customer Segment Performance</h2>
        <span style="font-size:12px;color:var(--gt-subtle)">Across all rules — which customer types convert on BOGO deals</span>
    </div>
    <?php
    $segments_agg = [ 'new' => [], 'returning' => [], 'vip' => [], 'at_risk' => [], 'lapsed' => [], 'guest' => [] ];
    foreach ( array_keys( $merged ) as $rid ) {
        if ( ! class_exists( 'GT_BOGO_Rule_Analytics' ) ) break;
        $breakdown = GT_BOGO_Rule_Analytics::get_rule_segment_breakdown( $rid );
        foreach ( $breakdown as $seg => $sd ) {
            if ( ! isset( $segments_agg[ $seg ] ) ) continue;
            $segments_agg[ $seg ]['impressions']  = ( $segments_agg[$seg]['impressions'] ?? 0 ) + $sd['impressions'];
            $segments_agg[ $seg ]['conversions']  = ( $segments_agg[$seg]['conversions'] ?? 0 ) + $sd['conversions'];
            $segments_agg[ $seg ]['revenue']      = ( $segments_agg[$seg]['revenue'] ?? 0 ) + $sd['revenue_influenced'];
            $segments_agg[ $seg ]['label']        = $sd['label'];
        }
    }
    $seg_colors = [
        'new' => '#3b82f6', 'returning' => '#22c55e', 'vip' => '#f59e0b',
        'at_risk' => '#ef4444', 'lapsed' => '#8b5cf6', 'guest' => 'var(--gt-subtle)',
    ];
    ?>
    <div style="display:grid;grid-template-columns:repeat(6,1fr);gap:0">
    <?php foreach ( $segments_agg as $seg => $sd ) :
        $impr = (int) ( $sd['impressions'] ?? 0 );
        $conv = (int) ( $sd['conversions'] ?? 0 );
        $rate = $impr > 0 ? round( $conv / $impr * 100, 1 ) : 0;
        $lbl  = $sd['label'] ?? ucfirst( str_replace( '_', ' ', $seg ) );
        $col  = $seg_colors[ $seg ] ?? 'var(--gt-subtle)';
        $rc   = $rate >= 30 ? '#22c55e' : ($rate >= 15 ? '#f59e0b' : ($rate > 0 ? '#ef4444' : 'var(--gt-subtle)'));
        $idx  = array_search($seg, array_keys($segments_agg), true);
    ?>
    <div style="padding:18px 14px;text-align:center;border-right:<?php echo $idx < 5 ? '1px solid var(--gt-border)' : 'none'; ?>">
        <div style="font-size:10px;font-weight:800;text-transform:uppercase;letter-spacing:.08em;color:<?php echo esc_attr($col); ?>;margin-bottom:8px">
            <?php echo esc_html( $lbl ); ?>
        </div>
        <div style="font-size:20px;font-weight:900;color:<?php echo esc_attr($rc); ?>;margin-bottom:2px">
            <?php echo esc_html( $rate . '%' ); ?>
        </div>
        <div style="font-size:11px;color:var(--gt-subtle);margin-bottom:6px">Conv. rate</div>
        <div style="font-size:12px;color:var(--gt-white)"><?php echo esc_html( number_format($conv) ); ?> converted</div>
        <div style="font-size:11px;color:var(--gt-subtle)"><?php echo esc_html( number_format($impr) ); ?> impressions</div>
    </div>
    <?php endforeach; ?>
    </div>
</div>

<!-- ═══════════════════════════════════════════════════════════════════════════
     ATTRIBUTION REPORT — SP-LEVEL
════════════════════════════════════════════════════════════════════════════ -->
<?php 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 );
?>
<?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 ) ) ); ?> Model</h2>
        <span style="font-size:12px;color:var(--gt-subtle)">Which SPs are driving conversions</span>
    </div>
    <div style="overflow-x:auto">
        <table style="width:100%;border-collapse:collapse;font-size:13px">
            <thead>
                <tr style="border-bottom:1px solid var(--gt-border)">
                    <?php foreach ( [ 'Superpower', 'Impressions', 'Conversions', 'Conv. Rate', 'Attribution Share' ] as $col ) : ?>
                    <th style="padding:10px 14px;text-align:left;font-size:10px;font-weight:800;
                               letter-spacing:.1em;text-transform:uppercase;color:var(--gt-subtle)">
                        <?php echo esc_html( $col ); ?>
                    </th>
                    <?php endforeach; ?>
                </tr>
            </thead>
            <tbody>
            <?php
            $max_conv = max( 1, array_sum( array_column( $attr_data, 'conversions' ) ) );
            foreach ( $attr_data as $ar ) :
                $arc = $ar['conversion_rate'] >= 30 ? '#22c55e' : ($ar['conversion_rate'] >= 15 ? '#f59e0b' : '#ef4444');
                $share = $max_conv > 0 ? round( $ar['conversions'] / $max_conv * 100 ) : 0;
            ?>
            <tr style="border-bottom:1px solid rgba(255,255,255,0.04)">
                <td style="padding:11px 14px;font-weight:600;color:var(--gt-white)">
                    <?php echo esc_html( ucwords( str_replace( '-', ' ', $ar['sp_id'] ) ) ); ?>
                </td>
                <td style="padding:11px 14px;color:var(--gt-subtle)"><?php echo esc_html( number_format( $ar['impressions'] ) ); ?></td>
                <td style="padding:11px 14px;color:#22c55e;font-weight:700"><?php echo esc_html( number_format( $ar['conversions'] ) ); ?></td>
                <td style="padding:11px 14px;color:<?php echo esc_attr($arc); ?>;font-weight:700"><?php echo esc_html( $ar['conversion_rate'] . '%' ); ?></td>
                <td style="padding:11px 14px">
                    <div style="display:flex;align-items:center;gap:8px">
                        <div style="flex:1;height:6px;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:11px;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; ?>
<?php endif; ?>

<!-- ═══════════════════════════════════════════════════════════════════════════
     JAVASCRIPT — CHARTS, FILTER, SORT, DRILL-DOWN, EXPORT
════════════════════════════════════════════════════════════════════════════ -->
<script>
(function() {
'use strict';

/* ── Chart.js: Fires vs Conversions ───────────────────────────────────── */
var labelsData = <?php echo $chart_labels_json; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>;
var firesData  = <?php echo $chart_fires_json; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>;
var convData   = <?php echo $chart_conv_json; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>;
var barLabels  = <?php echo $bar_labels_json; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>;
var barRevData = <?php echo $bar_revenue_json; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>;

document.addEventListener('DOMContentLoaded', function() {

    /* Animate funnel bars */
    setTimeout(function() {
        document.querySelectorAll('[style*="transition:width"]').forEach(function(el) {
            var w = el.style.width;
            el.style.width = '0%';
            setTimeout(function() { el.style.width = w; }, 100);
        });
    }, 300);

    /* Line chart */
    var lineCtx = document.getElementById('gt-rp-line-chart');
    if ( lineCtx && labelsData.length > 0 ) {
        new Chart(lineCtx.getContext('2d'), {
            type: 'line',
            data: {
                labels: labelsData,
                datasets: [
                    {
                        label: 'Fires',
                        data: firesData,
                        borderColor: '#f59e0b',
                        backgroundColor: 'rgba(245,158,11,0.08)',
                        borderWidth: 2,
                        tension: 0.35,
                        fill: true,
                        pointRadius: 3,
                        yAxisID: 'y',
                    },
                    {
                        label: 'Conversions',
                        data: convData,
                        borderColor: '#22c55e',
                        backgroundColor: 'rgba(34,197,94,0.08)',
                        borderWidth: 2,
                        tension: 0.35,
                        fill: true,
                        pointRadius: 3,
                        yAxisID: 'y',
                    }
                ]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                interaction: { mode: 'index', intersect: false },
                plugins: {
                    legend: { labels: { color: '#64748b', font: { size: 11 } } }
                },
                scales: {
                    x: { grid: { color: 'rgba(255,255,255,0.04)' }, ticks: { color: '#475569', font: { size: 10 }, maxTicksLimit: 8 } },
                    y: { grid: { color: 'rgba(255,255,255,0.04)' }, ticks: { color: '#475569', font: { size: 10 } } }
                }
            }
        });
    }

    /* Bar chart */
    var barCtx = document.getElementById('gt-rp-bar-chart');
    if ( barCtx && barLabels.length > 0 ) {
        new Chart(barCtx.getContext('2d'), {
            type: 'bar',
            data: {
                labels: barLabels,
                datasets: [{
                    label: 'Deal Volume ($)',
                    data: barRevData,
                    backgroundColor: 'rgba(225,0,0,0.7)',
                    borderColor: '#E10000',
                    borderWidth: 1,
                    borderRadius: 4,
                }]
            },
            options: {
                indexAxis: 'y',
                responsive: true,
                maintainAspectRatio: false,
                plugins: { legend: { display: false } },
                scales: {
                    x: { grid: { color: 'rgba(255,255,255,0.04)' }, ticks: { color: '#475569', font: { size: 10 }, callback: function(v) { return '$' + v.toLocaleString(); } } },
                    y: { grid: { display: false }, ticks: { color: '#94a3b8', font: { size: 10 } } }
                }
            }
        });
    }

    /* Animate KPI counters */
    document.querySelectorAll('.gt-counter[data-target]').forEach(function(el) {
        var raw    = el.getAttribute('data-target');
        var target = parseFloat(raw);
        if (!target || isNaN(target)) return;
        var start  = 0;
        var step   = target / 60;
        var orig   = el.textContent;
        var isFloat = orig.indexOf('.') !== -1;
        var prefix  = orig.match(/^[^0-9]*/)[0] || '';
        var suffix  = orig.match(/[^0-9.]+$/)?.[0] || '';
        var iv = setInterval(function() {
            start += step;
            if (start >= target) { el.textContent = orig; clearInterval(iv); return; }
            var disp = isFloat ? start.toFixed(1) : Math.floor(start).toLocaleString();
            el.textContent = prefix + disp + suffix;
        }, 16);
    });

});

/* ── Filter ───────────────────────────────────────────────────────────── */
window.gtRpFilter = function() {
    var search = document.getElementById('gt-rp-search').value.toLowerCase();
    var status = document.getElementById('gt-rp-status-filter').value;
    var rows   = document.querySelectorAll('.gt-rp-row');
    rows.forEach(function(row) {
        var name   = row.getAttribute('data-name') || '';
        var st     = row.getAttribute('data-status') || '';
        var show   = name.includes(search) && (!status || st === status);
        row.style.display = show ? '' : 'none';
        /* Also hide corresponding drilldown row */
        var next = row.nextElementSibling;
        if (next && next.id && next.id.startsWith('gt-rp-drilldown-')) {
            if (!show) next.style.display = 'none';
        }
    });
};

/* ── Sort ─────────────────────────────────────────────────────────────── */
var sortDir = {};
window.gtRpSortByCol = function(col) {
    sortDir[col] = !sortDir[col];
    gtRpApplySort(col, sortDir[col]);
};
window.gtRpSort = function() {
    var val  = document.getElementById('gt-rp-sort').value;
    var parts = val.split('-');
    var col  = parts.slice(0,-1).join('_');
    var dir  = parts[parts.length-1] === 'desc';
    gtRpApplySort(col, dir);
};
function gtRpApplySort(col, desc) {
    var tbody = document.getElementById('gt-rp-tbody');
    if (!tbody) return;
    /* Collect all data rows (not drilldown rows) */
    var pairs = [];
    var allRows = Array.from(tbody.querySelectorAll('.gt-rp-row'));
    allRows.forEach(function(row) {
        var drilldown = row.nextElementSibling;
        pairs.push({ data: row, dd: drilldown });
    });
    pairs.sort(function(a, b) {
        var av = a.data.getAttribute('data-' + col) || '';
        var bv = b.data.getAttribute('data-' + col) || '';
        var af = parseFloat(av);
        var bf = parseFloat(bv);
        if (!isNaN(af) && !isNaN(bf)) {
            return desc ? bf - af : af - bf;
        }
        return desc ? bv.localeCompare(av) : av.localeCompare(bv);
    });
    pairs.forEach(function(p) {
        tbody.appendChild(p.data);
        if (p.dd) tbody.appendChild(p.dd);
    });
}

/* ── Drill-down ───────────────────────────────────────────────────────── */
window.gtRpDrilldown = function(ruleId, btn, nonce) {
    var ddRow  = document.getElementById('gt-rp-drilldown-' + ruleId);
    var ddCont = document.getElementById('gt-rp-drilldown-content-' + ruleId);
    if (!ddRow || !ddCont) return;

    var isOpen = ddRow.style.display !== 'none';
    if (isOpen) {
        ddRow.style.display = 'none';
        btn.textContent = '▸ Drill down';
        return;
    }

    ddRow.style.display = '';
    btn.textContent = '▾ Close';

    /* Already loaded? */
    if (ddCont.getAttribute('data-loaded')) return;

    /* AJAX load */
    var fd = new FormData();
    fd.append('action',  'gtbogo_rule_perf_drilldown');
    fd.append('nonce',   nonce);
    fd.append('rule_id', ruleId);
    fd.append('days',    '<?php echo esc_js( (string) $days ); ?>');

    fetch(ajaxurl, { method: 'POST', body: fd })
        .then(function(r) { return r.json(); })
        .then(function(resp) {
            if (resp.success) {
                ddCont.innerHTML = resp.data.html;
                ddCont.setAttribute('data-loaded', '1');
            } else {
                ddCont.innerHTML = '<div style="padding:16px;color:#ef4444;font-size:13px">Failed to load rule intelligence: ' + (resp.data || 'unknown error') + '</div>';
            }
        })
        .catch(function(e) {
            ddCont.innerHTML = '<div style="padding:16px;color:#ef4444;font-size:13px">Network error loading drill-down.</div>';
        });
};

/* ── Export CSV ───────────────────────────────────────────────────────── */
window.gtRpExportCSV = function(nonce) {
    window.open(
        ajaxurl + '?action=gtbogo_rule_perf_export&nonce=' + encodeURIComponent(nonce) +
        '&days=<?php echo esc_js( (string) $days ); ?>&attr=<?php echo esc_js( $attr_model ); ?>',
        '_blank'
    );
};

/* ── Refresh ──────────────────────────────────────────────────────────── */
window.gtRpRefresh = function() {
    location.reload();
};

/* ── Row hover ────────────────────────────────────────────────────────── */
document.addEventListener('DOMContentLoaded', function() {
    document.querySelectorAll('.gt-rp-row').forEach(function(row) {
        row.addEventListener('mouseenter', function() {
            this.style.background = 'rgba(255,255,255,0.025)';
        });
        row.addEventListener('mouseleave', function() {
            this.style.background = '';
        });
    });
});

})();
</script>

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