<?php
/**
 * GT BOGO Engine — Dashboard v3.12.0
 * Clean, coherent store performance overview.
 *
 * @package GT_BOGO_Engine
 * @since   3.12.0
 */
if ( ! defined( 'ABSPATH' ) ) exit;
if ( ! current_user_can( 'manage_options' ) ) return;

$is_pro  = function_exists( 'gt_bogo_has_pro' ) ? gt_bogo_has_pro() : false;
$version = defined( 'GT_BOGO_VERSION' ) ? GT_BOGO_VERSION : '3.16.0';
global $wpdb;

// ── Data ─────────────────────────────────────────────────────────────────────
$rtbl = $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $wpdb->prefix . 'gtbogo_rules' ) );
$atbl = $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $wpdb->prefix . 'gtbogo_analytics' ) );

$rules_all    = $rtbl ? $wpdb->get_results( "SELECT * FROM {$wpdb->prefix}gtbogo_rules ORDER BY priority ASC" ) : [];
$rules_active = array_values( array_filter( $rules_all, fn( $r ) => $r->status === 'active' ) );
$free_rule    = get_option( 'gtbogo_free_rule', [] );

// Analytics
$a30 = $a7 = [ 'orders' => 0, 'revenue' => 0, 'discounts' => 0, 'aov' => 0 ];
$sparkline   = [];
$leaderboard = [];

if ( $atbl ) {
    $start30 = gmdate( 'Y-m-d H:i:s', strtotime( '-30 days' ) );
    $start7  = gmdate( 'Y-m-d H:i:s', strtotime( '-7 days' ) );

    $row30 = $wpdb->get_row( $wpdb->prepare(
        "SELECT COUNT(DISTINCT order_id) AS orders,
                COALESCE(SUM(order_total),0) AS revenue,
                COALESCE(SUM(discount_amount),0) AS discounts,
                COALESCE(AVG(order_total),0) AS aov
         FROM {$wpdb->prefix}gtbogo_analytics WHERE date_created >= %s", $start30
    ), ARRAY_A );
    if ( $row30 ) $a30 = $row30;

    $row7 = $wpdb->get_row( $wpdb->prepare(
        "SELECT COUNT(DISTINCT order_id) AS orders,
                COALESCE(SUM(order_total),0) AS revenue
         FROM {$wpdb->prefix}gtbogo_analytics WHERE date_created >= %s", $start7
    ), ARRAY_A );
    if ( $row7 ) $a7 = $row7;

    // Sparkline — 14 days
    for ( $i = 13; $i >= 0; $i-- ) {
        $day   = gmdate( 'Y-m-d', strtotime( "-{$i} days" ) );
        $count = (int) $wpdb->get_var( $wpdb->prepare(
            "SELECT COUNT(DISTINCT order_id) FROM {$wpdb->prefix}gtbogo_analytics WHERE DATE(date_created) = %s", $day
        ) );
        $sparkline[] = [ 'label' => gmdate( 'M j', strtotime( "-{$i} days" ) ), 'orders' => $count ];
    }

    // Top 5 rules
    $leaderboard = $wpdb->get_results( $wpdb->prepare(
        "SELECT COALESCE(r.name, CONCAT('Rule #',a.rule_id)) AS rule_name,
                COUNT(DISTINCT a.order_id) AS orders,
                COALESCE(SUM(a.order_total),0) AS revenue,
                COALESCE(SUM(a.discount_amount),0) AS cost
         FROM {$wpdb->prefix}gtbogo_analytics a
         LEFT JOIN {$wpdb->prefix}gtbogo_rules r ON a.rule_id = r.id
         WHERE a.date_created >= %s
         GROUP BY a.rule_id ORDER BY orders DESC LIMIT 5",
        $start30
    ) );
}

// License
$license_expiry = get_option( 'gtbogo_license_expiry', '' );
$days_left      = $license_expiry ? (int) ceil( ( strtotime( $license_expiry ) - time() ) / 86400 ) : 0;

// Schedules
$schedules    = get_option( 'gtbogo_schedules', [] );
$now_tz       = new DateTimeZone( wp_timezone_string() );
$now_dt       = new DateTime( 'now', $now_tz );
$upcoming     = [];
foreach ( $schedules as $sched ) {
    if ( ! empty( $sched['start_date'] ) ) {
        $start = new DateTime( $sched['start_date'] . ' ' . ( $sched['start_time'] ?? '00:00' ), $now_tz );
        if ( $start > $now_dt ) {
            $upcoming[] = [ 'name' => $sched['name'] ?? '', 'start' => $start->format( 'M j, g:ia' ) ];
        }
    }
}
usort( $upcoming, fn( $a, $b ) => strtotime( $a['start'] ) - strtotime( $b['start'] ) );

$spark_max = max( 1, max( array_column( $sparkline, 'orders' ) ?: [0] ) );
$has_data  = (int) $a30['orders'] > 0;

// Active rule count including free rule
$total_active = count( $rules_active ) + ( ! empty( $free_rule['enabled'] ) ? 1 : 0 );

require_once __DIR__ . '/../ui-system/wrapper-start.php';
do_action( 'gtbogo_before_dashboard' );
?>

<!-- ── License expiry warning ─────────────────────────────────────────────── -->
<?php if ( $is_pro && $license_expiry && $days_left > 0 && $days_left <= 30 ): ?>
<div style="display:flex;align-items:center;justify-content:space-between;padding:14px 20px;margin-bottom:20px;background:rgba(245,158,11,0.06);border:1px solid rgba(245,158,11,0.2);border-radius:10px" class="gt-animate-in">
  <span style="font-size:14px;color:#fcd34d">PRO license expires in <?php echo esc_html( $days_left ); ?> days.</span>
  <a href="<?php echo esc_url( admin_url( 'admin.php?page=gt-bogo-engine&tab=license' ) ); ?>" style="font-size:14px;font-weight:700;color:#fcd34d;text-decoration:none">Renew →</a>
</div>
<?php endif; ?>

<!-- ── ROW 1: Four KPI cards ──────────────────────────────────────────────── -->
<div style="display:grid;grid-template-columns:repeat(4,1fr);gap:16px;margin-bottom:20px" class="gt-animate-in">
  <?php foreach ( [
    [ 'Revenue Influenced (30d)', (float) $a30['revenue'],   '$', 'Last 7d: $' . number_format( (float) $a7['revenue'] ),          '#22c55e' ],
    [ 'BOGO Orders (30d)',        (int) $a30['orders'],       '',  'Last 7d: ' . number_format( (int) $a7['orders'] ),              '#E10000' ],
    [ 'Discount Given (30d)',     (float) $a30['discounts'],  '$', 'Avg order: $' . number_format( (float) $a30['aov'], 2 ),        '#f59e0b' ],
    [ 'Active Rules',             (int) $total_active,        '',  count( $rules_all ) . ' total configured',                       '#3b82f6' ],
  ] as $m ): ?>
  <div style="background:var(--gt-card);border:1px solid var(--gt-border);border-radius:14px;padding:28px 24px;position:relative;overflow:hidden;min-height:150px;display:flex;flex-direction:column;justify-content:space-between">
    <div style="position:absolute;top:0;left:0;right:0;height:3px;background:<?php echo esc_attr( $m[4] ); ?>"></div>
    <p style="margin:0 0 12px;font-size:11px;font-weight:800;letter-spacing:.12em;text-transform:uppercase;color:var(--gt-subtle)"><?php echo esc_html( $m[0] ); ?></p>
    <p style="margin:0 0 8px;font-size:52px;font-weight:900;color:<?php echo esc_attr( $m[4] ); ?>;line-height:1;font-family:'DM Mono',monospace"
       data-countup="<?php echo esc_attr( $m[1] ); ?>"
       data-prefix="<?php echo esc_attr( $m[2] ); ?>"><?php echo esc_html( $m[2] . number_format( $m[1] ) ); ?></p>
    <p style="margin:0;font-size:13px;color:var(--gt-subtle)"><?php echo esc_html( $m[3] ); ?></p>
  </div>
  <?php endforeach; ?>
</div>

<!-- ── ROW 2: Live Activity (full width, near top) ────────────────────────── -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px" id="gtbogo-live-card">
  <div class="gt-card-header" style="display:flex;align-items:center;justify-content:space-between">
    <div style="display:flex;align-items:center;gap:10px">
      <h2 class="gt-card-title">Live Activity</h2>
      <span id="gtbogo-live-dot" style="width:9px;height:9px;border-radius:50%;background:#22c55e;display:inline-block;animation:gtbogo-pulse 2s infinite"></span>
      <span id="gtbogo-live-status" style="font-size:12px;color:var(--gt-subtle)">Connecting...</span>
      <span style="font-size:11px;color:var(--gt-border)">·</span>
      <span id="gtbogo-cart-count" style="font-size:13px;color:#93c5fd;font-weight:600">— active carts</span>
      <span style="font-size:11px;color:var(--gt-border)">·</span>
      <span id="gtbogo-active-rules-count" style="font-size:13px;color:#86efac;font-weight:600">— rules live</span>
    </div>
    <span id="gtbogo-last-refresh" style="font-size:11px;color:var(--gt-subtle)">—</span>
  </div>
  <div id="gtbogo-live-feed" style="display:flex;flex-direction:column;gap:6px;min-height:100px;padding:8px 0">
    <div style="color:var(--gt-subtle);font-size:14px;padding:24px;text-align:center">Loading live data...</div>
  </div>
  <!-- Live KPI strip inside the live card -->
  <div style="display:grid;grid-template-columns:repeat(4,1fr);gap:12px;margin-top:16px;padding-top:16px;border-top:1px solid var(--gt-border)">
    <div style="text-align:center">
      <div style="font-size:11px;font-weight:700;letter-spacing:1px;text-transform:uppercase;color:var(--gt-subtle);margin-bottom:6px">Revenue (30d)</div>
      <div id="lkpi-revenue" style="font-size:26px;font-weight:900;color:#22c55e;font-family:'DM Mono',monospace">—</div>
    </div>
    <div style="text-align:center">
      <div style="font-size:11px;font-weight:700;letter-spacing:1px;text-transform:uppercase;color:var(--gt-subtle);margin-bottom:6px">BOGO Orders (30d)</div>
      <div id="lkpi-orders" style="font-size:26px;font-weight:900;color:#E10000;font-family:'DM Mono',monospace">—</div>
    </div>
    <div style="text-align:center">
      <div style="font-size:11px;font-weight:700;letter-spacing:1px;text-transform:uppercase;color:var(--gt-subtle);margin-bottom:6px">Discounts Given (30d)</div>
      <div id="lkpi-discounts" style="font-size:26px;font-weight:900;color:#f59e0b;font-family:'DM Mono',monospace">—</div>
    </div>
    <div style="text-align:center">
      <div style="font-size:11px;font-weight:700;letter-spacing:1px;text-transform:uppercase;color:var(--gt-subtle);margin-bottom:6px">Avg Order Value</div>
      <div id="lkpi-aov" style="font-size:26px;font-weight:900;color:#86efac;font-family:'DM Mono',monospace">—</div>
    </div>
  </div>
</div>

<!-- ── ROW 3: Orders chart · Top Rules · Active Rules (3 equal cols) ─────── -->
<div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:20px;margin-bottom:20px">

  <!-- Orders sparkline -->
  <div class="gt-card gt-animate-in">
    <div class="gt-card-header">
      <h2 class="gt-card-title">Orders — Last 14 Days</h2>
      <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">Analytics →</a>
    </div>
    <?php if ( $has_data ): ?>
    <div style="display:flex;align-items:flex-end;gap:4px;height:120px">
      <?php foreach ( $sparkline as $day ):
        $h = $spark_max > 0 ? max( 4, round( ( $day['orders'] / $spark_max ) * 112 ) ) : 4;
        $active = $day['orders'] > 0;
      ?>
      <div style="flex:1;display:flex;flex-direction:column;align-items:center;justify-content:flex-end;height:100%" title="<?php echo esc_attr( $day['label'] . ': ' . esc_html( $day['orders'] ) . ' orders' ); ?>">
        <div style="width:100%;height:<?php echo esc_html( $h ); ?>px;background:<?php echo esc_html( $active ) ? '#E10000' : 'rgba(255,255,255,0.04)'; ?>;border-radius:3px 3px 0 0;transition:height .3s"></div>
      </div>
      <?php endforeach; ?>
    </div>
    <div style="display:flex;justify-content:space-between;padding:8px 0 0;font-size:12px;color:var(--gt-subtle)">
      <span><?php echo esc_html( $sparkline[0]['label'] ); ?></span>
      <span><?php echo esc_html( $sparkline[6]['label'] ); ?></span>
      <span>Today</span>
    </div>
    <?php else: ?>
    <div style="display:flex;flex-direction:column;align-items:center;justify-content:center;padding:40px 20px;text-align:center">
      <p style="margin:0 0 12px;font-size:14px;color:var(--gt-subtle)">Orders appear once BOGO rules start firing.</p>
      <a href="<?php echo esc_url( admin_url( 'admin.php?page=gt-bogo-engine&tab=pro-rules' ) ); ?>" class="gt-btn gt-btn-primary gt-btn-sm">Import a Pack →</a>
    </div>
    <?php endif; ?>
  </div>

  <!-- Top rules leaderboard -->
  <div class="gt-card gt-animate-in">
    <div class="gt-card-header">
      <h2 class="gt-card-title">Top Rules (30d)</h2>
    </div>
    <?php if ( ! empty( $leaderboard ) ): ?>
    <div style="display:flex;flex-direction:column;gap:16px">
      <?php foreach ( $leaderboard as $i => $row ):
        $pct = $leaderboard[0]->orders > 0 ? round( ( $row->orders / $leaderboard[0]->orders ) * 100 ) : 0;
        $medals = [ '🥇', '🥈', '🥉' ];
      ?>
      <div>
        <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:6px">
          <span style="font-size:14px;font-weight:<?php echo $i === 0 ? '700' : '500'; ?>;color:<?php echo $i === 0 ? 'var(--gt-white)' : 'var(--gt-soft)'; ?>;max-width:160px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">
            <?php echo isset( $medals[$i] ) ? esc_html( $medals[$i] ) . ' ' : ''; ?><?php echo esc_html( $row->rule_name ); ?>
          </span>
          <span style="font-size:13px;color:var(--gt-subtle)"><?php echo number_format( (int) $row->orders ); ?> orders</span>
        </div>
        <div style="height:4px;border-radius:4px;background:rgba(255,255,255,0.05)">
          <div style="height:100%;width:<?php echo esc_html( $pct ); ?>%;background:#E10000;border-radius:4px"></div>
        </div>
      </div>
      <?php endforeach; ?>
    </div>
    <?php else: ?>
    <div style="padding:40px 16px;text-align:center">
      <p style="margin:0;font-size:14px;color:var(--gt-subtle)">No rule performance data yet.</p>
    </div>
    <?php endif; ?>
  </div>

  <!-- Active rules -->
  <div class="gt-card gt-animate-in">
    <div class="gt-card-header">
      <h2 class="gt-card-title">Active Rules</h2>
      <a href="<?php echo esc_url( admin_url( 'admin.php?page=gt-bogo-engine&tab=pro-rules' ) ); ?>" class="gt-btn gt-btn-ghost gt-btn-sm">Manage →</a>
    </div>
    <?php
    $display_rules = [];
    if ( ! empty( $free_rule['enabled'] ) ) {
        $display_rules[] = (object) [
            'name'           => $free_rule['title'] ?? 'Free Core Rule',
            'buy_quantity'   => $free_rule['buy_quantity'] ?? 1,
            'get_quantity'   => $free_rule['get_quantity'] ?? 1,
            'discount_value' => $free_rule['discount_value'] ?? 100,
            'discount_type'  => $free_rule['discount_type'] ?? 'percent',
        ];
    }
    foreach ( $rules_active as $r ) $display_rules[] = $r;
    ?>
    <?php if ( ! empty( $display_rules ) ): ?>
    <div style="display:flex;flex-direction:column;gap:8px">
      <?php foreach ( array_slice( $display_rules, 0, 6 ) as $r ):
        $dval = (int) $r->discount_value;
        $mechanic = $dval === 100
          ? 'Buy ' . $r->buy_quantity . ' Get ' . $r->get_quantity . ' FREE'
          : 'Buy ' . $r->buy_quantity . ' Get ' . $r->get_quantity . ' — ' . esc_html( $dval ) . '% off';
      ?>
      <div style="display:flex;align-items:center;justify-content:space-between;padding:12px 14px;border-radius:8px;background:rgba(255,255,255,0.02);border:1px solid rgba(255,255,255,0.05)">
        <div style="min-width:0">
          <p style="margin:0 0 3px;font-size:14px;font-weight:700;color:var(--gt-white);overflow:hidden;text-overflow:ellipsis;white-space:nowrap"><?php echo esc_html( $r->name ); ?></p>
          <p style="margin:0;font-size:12px;color:var(--gt-subtle)"><?php echo esc_html( $mechanic ); ?></p>
        </div>
        <span style="flex-shrink:0;width:9px;height:9px;border-radius:50%;background:#22c55e;margin-left:12px"></span>
      </div>
      <?php endforeach; ?>
      <?php if ( count( $display_rules ) > 6 ): ?>
      <p style="margin:4px 0 0;font-size:13px;color:var(--gt-subtle);text-align:center">+<?php echo count( $display_rules ) - 6; ?> more active</p>
      <?php endif; ?>
    </div>
    <?php else: ?>
    <div style="display:flex;flex-direction:column;align-items:center;padding:32px 20px;text-align:center">
      <p style="margin:0 0 16px;font-size:14px;color:var(--gt-subtle)">No active rules yet.</p>
      <div style="display:flex;gap:8px;flex-wrap:wrap;justify-content:center">
        <a href="<?php echo esc_url( admin_url( 'admin.php?page=gt-bogo-engine&tab=free-rule' ) ); ?>" class="gt-btn gt-btn-ghost gt-btn-sm">Free Rule</a>
        <a href="<?php echo esc_url( admin_url( 'admin.php?page=gt-bogo-engine&tab=pro-rules' ) ); ?>" class="gt-btn gt-btn-primary gt-btn-sm">Import a Pack</a>
      </div>
    </div>
    <?php endif; ?>
  </div>

</div>

<!-- ── ROW 4: System status + Upcoming campaigns ──────────────────────────── -->
<div style="display:grid;grid-template-columns:1fr 1fr;gap:20px;margin-bottom:20px">

  <!-- System status -->
  <div class="gt-card gt-animate-in">
    <div class="gt-card-header">
      <h2 class="gt-card-title">System</h2>
      <a href="<?php echo esc_url( admin_url( 'admin.php?page=gt-bogo-engine&tab=system-status' ) ); ?>" class="gt-btn gt-btn-ghost gt-btn-sm">Full Status →</a>
    </div>
    <div style="display:grid;grid-template-columns:1fr 1fr;gap:2px">
      <?php
      $checks = [
        [ 'PRO License',     $is_pro,                                                     $is_pro ? 'Active' : 'Not activated' ],
        [ 'Customer Emails', (bool) get_option( 'gtbogo_customer_emails_enabled', false ), get_option( 'gtbogo_customer_emails_enabled', false ) ? 'Enabled' : 'Disabled' ],
        [ 'Analytics',       (bool) get_option( 'gtbogo_analytics_enabled', true ),       get_option( 'gtbogo_analytics_enabled', true ) ? 'Tracking' : 'Off' ],
        [ 'Rule Cache',      (bool) get_option( 'gtbogo_cache_rules', true ),              get_option( 'gtbogo_cache_rules', true ) ? 'Enabled' : 'Off' ],
        [ 'WP Cron',         ! ( defined( 'DISABLE_WP_CRON' ) && DISABLE_WP_CRON ),       ! ( defined( 'DISABLE_WP_CRON' ) && DISABLE_WP_CRON ) ? 'Running' : 'Disabled' ],
        [ 'Debug Mode',      ! get_option( 'gtbogo_debug_mode', false ),                   get_option( 'gtbogo_debug_mode', false ) ? 'On' : 'Off' ],
        [ 'Schedules',       true,                                                         count( array_filter( $schedules, fn( $s ) => ! empty( $s['enabled'] ) ) ) . ' active' ],
        [ 'Upcoming',        true,                                                         count( $upcoming ) . ' scheduled' ],
      ];
      foreach ( $checks as $chk ):
        $ok = $chk[1];
      ?>
      <div style="display:flex;align-items:center;justify-content:space-between;padding:10px 14px;border-radius:6px;<?php echo ! $ok ? 'background:rgba(239,68,68,0.04)' : ''; ?>">
        <span style="font-size:13px;color:var(--gt-soft)"><?php echo esc_html( $chk[0] ); ?></span>
        <span style="font-size:13px;font-weight:600;color:<?php echo esc_html( $ok ) ? '#86efac' : '#fca5a5'; ?>"><?php echo esc_html( $chk[2] ); ?></span>
      </div>
      <?php endforeach; ?>
    </div>
  </div>

  <!-- Upcoming campaigns — always shown, empty state if none -->
  <div class="gt-card gt-animate-in">
    <div class="gt-card-header">
      <h2 class="gt-card-title">Upcoming Campaigns</h2>
      <a href="<?php echo esc_url( admin_url( 'admin.php?page=gt-bogo-engine&tab=scheduler' ) ); ?>" class="gt-btn gt-btn-ghost gt-btn-sm">Scheduler →</a>
    </div>
    <?php if ( ! empty( $upcoming ) ): ?>
    <div style="display:flex;flex-direction:column;gap:8px">
      <?php foreach ( array_slice( $upcoming, 0, 6 ) as $sch ): ?>
      <div style="display:flex;justify-content:space-between;align-items:center;padding:12px 14px;border-radius:8px;background:rgba(59,130,246,0.04);border:1px solid rgba(59,130,246,0.12)">
        <span style="font-size:14px;font-weight:600;color:var(--gt-white);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;max-width:200px"><?php echo esc_html( $sch['name'] ); ?></span>
        <span style="font-size:13px;color:#93c5fd;flex-shrink:0;margin-left:8px"><?php echo esc_html( $sch['start'] ); ?></span>
      </div>
      <?php endforeach; ?>
    </div>
    <?php else: ?>
    <div style="display:flex;flex-direction:column;align-items:center;padding:40px 20px;text-align:center">
      <p style="margin:0 0 16px;font-size:14px;color:var(--gt-subtle)">No upcoming campaigns scheduled.</p>
      <a href="<?php echo esc_url( admin_url( 'admin.php?page=gt-bogo-engine&tab=scheduler' ) ); ?>" class="gt-btn gt-btn-ghost gt-btn-sm">Schedule a Campaign →</a>
    </div>
    <?php endif; ?>
  </div>

</div>

<!-- ── ROW 5: Navigate (full width, large tiles) ──────────────────────────── -->
<div class="gt-card gt-animate-in">
  <div class="gt-card-header"><h2 class="gt-card-title">Navigate</h2></div>
  <div style="display:grid;grid-template-columns:repeat(5,1fr);gap:12px">
    <?php foreach ( [
      [ '⚡', 'PRO Rules',    'pro-rules'            ],
      [ '💎', 'Superpowers',  'superpowers'          ],
      [ '📅', 'Scheduler',    'scheduler'            ],
      [ '📈', 'Analytics',    'analytics'            ],
      [ '🧠', 'Intelligence', 'customer-intelligence'],
      [ '🔬', 'A/B Testing',  'ab-testing'           ],
      [ '🎯', 'Segments',     'segments'             ],
      [ '🌍', 'Geo',          'geo-targeting'        ],
      [ '📄', 'PDF Export',   'pdf-export'           ],
      [ '⚙️', 'Settings',     'settings'             ],
    ] as $nav ): ?>
    <a href="<?php echo esc_url( admin_url( 'admin.php?page=gt-bogo-engine&tab=' . $nav[2] ) ); ?>" class="gt-nav-btn">
      <span style="font-size:28px"><?php echo esc_html( $nav[0] ); ?></span>
      <span style="font-size:13px;font-weight:700;color:var(--gt-soft);text-align:center"><?php echo esc_html( $nav[1] ); ?></span>
    </a>
    <?php endforeach; ?>
  </div>
</div>


<style>
@keyframes gtbogo-pulse {
  0%,100%{opacity:1;transform:scale(1)}
  50%{opacity:.4;transform:scale(.8)}
}
@keyframes gtbogo-slide-in {
  from{opacity:0;transform:translateY(-8px)}
  to{opacity:1;transform:translateY(0)}
}
.gtbogo-feed-row {
  display:flex;align-items:center;gap:12px;padding:10px 14px;
  border-radius:8px;background:rgba(255,255,255,0.02);
  border:1px solid rgba(255,255,255,0.04);
  animation:gtbogo-slide-in .25s ease;
  transition:background .15s;
}
.gtbogo-feed-row:hover{background:rgba(255,255,255,0.04)}
.gt-nav-btn {
  display:flex;flex-direction:column;align-items:center;gap:10px;
  padding:20px 12px;border-radius:12px;border:1px solid var(--gt-border);
  background:transparent;text-decoration:none;transition:all .15s;
}
.gt-nav-btn:hover{border-color:#E10000;background:rgba(225,0,0,0.04)}
</style>

<script>
(function(){
  var nonce   = '<?php echo esc_js(wp_create_nonce("gtbogo_live_nonce")); ?>';
  var ajaxUrl = '<?php echo esc_js(admin_url("admin-ajax.php")); ?>';
  var lastTs  = null;

  function fmtMoney(v){ return '$' + parseFloat(v||0).toLocaleString('en-US',{minimumFractionDigits:2,maximumFractionDigits:2}); }

  function fetchFeed(){
    var fd = new FormData();
    fd.append('action','gtbogo_live_feed');
    fd.append('nonce', nonce);
    fetch(ajaxUrl,{method:'POST',body:fd,credentials:'same-origin'})
    .then(function(r){return r.json();})
    .then(function(res){
      if(!res.success) return;
      var d = res.data;
      var feed = document.getElementById('gtbogo-live-feed');
      if(!feed) return;
      if(d.timestamp === lastTs) return;
      lastTs = d.timestamp;
      var html = '';
      (d.events||[]).forEach(function(e){
        html += '<div class="gtbogo-feed-row">' +
          '<span style="font-size:18px;flex-shrink:0">' + (e.icon||'⚡') + '</span>' +
          '<div style="flex:1;min-width:0">' +
            '<div style="font-size:14px;font-weight:600;color:var(--gt-white);white-space:nowrap;overflow:hidden;text-overflow:ellipsis">' + (e.message||'') + '</div>' +
            '<div style="font-size:12px;color:var(--gt-subtle)">' + (e.detail||'') + '</div>' +
          '</div>' +
          '<div style="text-align:right;flex-shrink:0">' +
            '<div style="font-size:14px;font-weight:700;color:' + (e.color||'#94a3b8') + '">' + (e.value||'') + '</div>' +
            '<div style="font-size:11px;color:var(--gt-subtle)">' + (e.time||'') + '</div>' +
          '</div>' +
        '</div>';
      });
      feed.innerHTML = html || '<div style="color:var(--gt-subtle);font-size:14px;padding:24px;text-align:center">No activity yet — engine is running</div>';
      var statusEl = document.getElementById('gtbogo-live-status');
      var dotEl    = document.getElementById('gtbogo-live-dot');
      var refreshEl= document.getElementById('gtbogo-last-refresh');
      if(statusEl) statusEl.textContent = 'Live';
      if(dotEl)    dotEl.style.background = '#22c55e';
      if(refreshEl){ var now = new Date(); refreshEl.textContent = 'Updated ' + now.toLocaleTimeString(); }
    })
    .catch(function(){
      var dotEl = document.getElementById('gtbogo-live-dot');
      if(dotEl) dotEl.style.background = '#ef4444';
    });
  }

  function fetchCart(){
    var fd = new FormData();
    fd.append('action','gtbogo_cart_monitor');
    fd.append('nonce', nonce);
    fetch(ajaxUrl,{method:'POST',body:fd,credentials:'same-origin'})
    .then(function(r){return r.json();})
    .then(function(res){
      if(!res.success) return;
      var d = res.data;
      var cartEl  = document.getElementById('gtbogo-cart-count');
      var rulesEl = document.getElementById('gtbogo-active-rules-count');
      if(cartEl)  cartEl.textContent  = (d.active_carts||0) + ' active carts';
      if(rulesEl) rulesEl.textContent = (d.active_rules||0) + ' rules live';
    });
  }

  function fetchAnalytics(){
    var fd = new FormData();
    fd.append('action','gtbogo_get_analytics');
    fd.append('nonce', '<?php echo esc_js(wp_create_nonce("gtbogo_analytics_nonce")); ?>');
    fd.append('days', '30');
    fetch(ajaxUrl,{method:'POST',body:fd,credentials:'same-origin'})
    .then(function(r){return r.json();})
    .then(function(res){
      if(!res.success) return;
      var d = res.data;
      var rev = document.getElementById('lkpi-revenue');
      var ord = document.getElementById('lkpi-orders');
      var dis = document.getElementById('lkpi-discounts');
      var aov = document.getElementById('lkpi-aov');
      if(rev) rev.textContent = fmtMoney(d.revenue);
      if(ord) ord.textContent = parseInt(d.orders||0).toLocaleString();
      if(dis) dis.textContent = fmtMoney(d.discounts);
      if(aov) aov.textContent = fmtMoney(d.aov);
    });
  }

  fetchFeed(); fetchCart(); fetchAnalytics();
  setInterval(fetchFeed, 30000);
  setInterval(fetchCart, 30000);
  setInterval(fetchAnalytics, 60000);
})();
</script>

<script>
(function(){
  function countUp(el, target, duration) {
    var startTime = null;
    var isFloat = target !== Math.floor(target);
    var prefix = el.dataset.prefix || '';
    function step(timestamp) {
      if (!startTime) startTime = timestamp;
      var progress = Math.min((timestamp - startTime) / duration, 1);
      var ease = 1 - Math.pow(1 - progress, 3);
      var current = target * ease;
      el.textContent = prefix + (isFloat ? current.toFixed(2) : Math.floor(current).toLocaleString());
      if (progress < 1) requestAnimationFrame(step);
      else el.textContent = prefix + (isFloat ? target.toFixed(2) : target.toLocaleString());
    }
    requestAnimationFrame(step);
  }
  document.addEventListener('DOMContentLoaded', function(){
    document.querySelectorAll('[data-countup]').forEach(function(el){
      var target = parseFloat(el.dataset.countup);
      if (!isNaN(target)) countUp(el, target, 900);
    });
  });
})();
</script>
<?php require_once __DIR__ . '/../ui-system/wrapper-end.php'; ?>