<?php
if (!defined('ABSPATH')) exit;

use auctionforge\inc\sync\SyncQueue;
use auctionforge\inc\helpers\SettingsHelper;

$nonce = wp_create_nonce('auctionforge_admin');
$stats_nonce = wp_create_nonce('af_stats_admin');
$pluginInfo = auctionforge_plugin_info();

// ── Sync queue data ──
$queueCounts = SyncQueue::getStatusCounts();
$recentJobs = SyncQueue::getRecentJobs(5);

// ── Heartbeat / cron data ──
$heartbeat_file = BASE_PATH . '/cron-status.json';
$heartbeat = null;
$external_cron = false;
$heartbeat_age = null;
$cron_mode = 'Not Configured';

if (file_exists($heartbeat_file)) {
    $heartbeat = json_decode(file_get_contents($heartbeat_file), true);
    if (is_array($heartbeat) && !empty($heartbeat['last_heartbeat_epoch'])) {
        $external_cron = true;
        $heartbeat_age = time() - intval($heartbeat['last_heartbeat_epoch']);
        $cron_mode = 'External Cron';
    }
}
$wp_cron_enabled = SettingsHelper::getOption('sync_cheduled', 'off') === 'on';
if (!$external_cron && $wp_cron_enabled) {
    $cron_mode = 'WP-Cron';
}

// ── Active/upcoming auctions (includes manual, excludes shops) ──
$allActiveAuctions = \auctionforge\inc\model\Auction::getActiveAuction();
if ($allActiveAuctions instanceof \WP_Error) $allActiveAuctions = [];

// Also query manual auctions (stored as 'manual_auction' post type)
$manualAuctionPosts = get_posts([
    'post_type'   => 'manual_auction',
    'post_status' => 'publish',
    'numberposts' => -1,
    'lang'        => '',
]);

// Filter out auctions marked as "shop" catalogs
$shopAuctionTermIds = SettingsHelper::getAuctionListFromSettings('shop_auction');
$shopAuctionTermIds = array_filter(array_map('trim', $shopAuctionTermIds));
$activeAuctions = [];
foreach ($allActiveAuctions as $auc) {
    if (!in_array((string)$auc->term_id, $shopAuctionTermIds, true)) {
        $activeAuctions[] = $auc;
    }
}
$totalDashboardAuctions = count($activeAuctions) + count($manualAuctionPosts);

// ── Inventory counts ──
global $wpdb;
$total_lots = intval($wpdb->get_var(
    "SELECT COUNT(*) FROM {$wpdb->posts} WHERE post_type='lot' AND post_status='publish'"
));
$total_auctions = intval($wpdb->get_var($wpdb->prepare(
    "SELECT COUNT(*) FROM {$wpdb->term_taxonomy} WHERE taxonomy=%s",
    'auction_number'
)));

// ── Update availability ──
$updates = get_site_transient('update_plugins');
$has_update = isset($updates->response[AUCTIONFORGE_PLUGIN_BASENAME]);
$new_version = $has_update ? $updates->response[AUCTIONFORGE_PLUGIN_BASENAME]->new_version : null;

// ── Stats nonce for AJAX ──
$seven_days_ago = date('Y-m-d', strtotime('-7 days'));
$today = date('Y-m-d');
?>
<div class="wrap af-dashboard-wrap">
    <h1 class="af-dashboard-title">
        <span class="dashicons dashicons-dashboard" style="font-size:28px;margin-right:8px;vertical-align:middle;"></span>
        AuctionForge Dashboard
        <span class="af-dash-version">v<?= esc_html($pluginInfo['ver']) ?></span>
    </h1>

    <div class="af-dash-grid">

        <!-- ═══════════════════════════════════════════
             1. SYNC STATUS
             ═══════════════════════════════════════════ -->
        <div class="af-dash-card af-dash-card--wide" id="af-dash-sync">
            <div class="af-dash-card__header">
                <span class="dashicons dashicons-update-alt"></span>
                <h2>Sync Status</h2>
                <span class="af-dash-badge af-dash-badge--<?= $external_cron ? 'green' : ($wp_cron_enabled ? 'blue' : 'gray') ?>">
                    <?= esc_html($cron_mode) ?>
                </span>
                <a href="<?= admin_url('edit.php?post_type=lot&page=auctionforge-sync-status') ?>" class="af-dash-card__link">Full Details →</a>
            </div>
            <div class="af-dash-card__body">
                <div class="af-dash-kpis af-dash-kpis--4">
                    <div class="af-dash-kpi">
                        <span class="af-dash-kpi__value"><?= $queueCounts['pending'] ?></span>
                        <span class="af-dash-kpi__label">Pending</span>
                    </div>
                    <div class="af-dash-kpi af-dash-kpi--active">
                        <span class="af-dash-kpi__value"><?= $queueCounts['processing'] ?></span>
                        <span class="af-dash-kpi__label">Processing</span>
                    </div>
                    <div class="af-dash-kpi af-dash-kpi--success">
                        <span class="af-dash-kpi__value"><?= $queueCounts['completed'] ?></span>
                        <span class="af-dash-kpi__label">Completed</span>
                    </div>
                    <div class="af-dash-kpi af-dash-kpi--danger">
                        <span class="af-dash-kpi__value"><?= $queueCounts['failed'] ?></span>
                        <span class="af-dash-kpi__label">Failed</span>
                    </div>
                </div>
                <?php if ($external_cron && $heartbeat_age !== null): ?>
                <div class="af-dash-meta">
                    <span class="dashicons dashicons-heart" style="color:#e74c3c"></span>
                    Heartbeat: <strong><?= $heartbeat_age < 120 ? $heartbeat_age . 's ago' : round($heartbeat_age / 60) . 'm ago' ?></strong>
                    <?php if ($heartbeat_age > 600): ?>
                        <span class="af-dash-badge af-dash-badge--red">Overdue</span>
                    <?php endif; ?>
                </div>
                <?php endif; ?>
                <div class="af-dash-actions">
                    <button type="button" class="button button-primary" id="af-dash-sync-now">
                        <span class="dashicons dashicons-update" style="margin-top:4px"></span> Sync All Active Auctions
                    </button>
                    <span id="af-dash-sync-status" class="af-dash-inline-status"></span>
                </div>
            </div>
        </div>

        <!-- ═══════════════════════════════════════════
             2. UPCOMING & ACTIVE AUCTIONS
             ═══════════════════════════════════════════ -->
        <div class="af-dash-card af-dash-card--wide" id="af-dash-auctions">
            <div class="af-dash-card__header">
                <span class="dashicons dashicons-calendar-alt"></span>
                <h2>Upcoming &amp; Active Auctions</h2>
                <span class="af-dash-badge af-dash-badge--blue"><?= $totalDashboardAuctions ?> auction<?= $totalDashboardAuctions !== 1 ? 's' : '' ?></span>
            </div>
            <div class="af-dash-card__body">
                <?php if (empty($activeAuctions) && empty($manualAuctionPosts)): ?>
                    <div class="af-dash-empty">
                        <span class="dashicons dashicons-info-outline"></span>
                        No upcoming or active auctions found.
                    </div>
                <?php else: ?>
                    <div class="af-dash-auction-grid">
                        <?php foreach ($activeAuctions as $auction):
                            $term_id = $auction->term_id;
                            $state = get_term_meta($term_id, 'auction_state', true);
                            $date = get_term_meta($term_id, 'auction_date', true);
                            $auction_id = get_term_meta($term_id, 'auction_id', true);
                            $lot_count = intval($wpdb->get_var($wpdb->prepare(
                                "SELECT COUNT(*) FROM {$wpdb->posts} p
                                 INNER JOIN {$wpdb->term_relationships} tr ON p.ID = tr.object_id
                                 INNER JOIN {$wpdb->term_taxonomy} tt ON tr.term_taxonomy_id = tt.term_taxonomy_id
                                 WHERE tt.term_id = %d AND p.post_type='lot' AND p.post_status='publish'",
                                $term_id
                            )));
                            $state_class = 'gray';
                            $state_label = esc_html($state ?: 'UNKNOWN');
                            if (in_array($state, ['PENDING', 'READY', 'PRE_AUCTION'])) {
                                $state_class = 'blue';
                                $state_label = 'UPCOMING';
                            } elseif (in_array($state, ['RUNNING', 'PAUSED'])) {
                                $state_class = 'green';
                                $state_label = 'LIVE';
                            } elseif ($state === 'POST_AUCTION') {
                                $state_class = 'orange';
                                $state_label = 'POST-AUCTION';
                            }
                        ?>
                        <div class="af-dash-auction-item">
                            <div class="af-dash-auction-item__top">
                                <span class="af-dash-badge af-dash-badge--<?= $state_class ?>"><?= $state_label ?></span>
                                <span class="af-dash-auction-item__lots"><?= $lot_count ?> lots</span>
                            </div>
                            <h3 class="af-dash-auction-item__name"><?= esc_html($auction->name) ?></h3>
                            <?php if ($date): ?>
                            <div class="af-dash-auction-item__date">
                                <span class="dashicons dashicons-clock"></span>
                                <?= esc_html($date) ?>
                            </div>
                            <?php endif; ?>
                            <button type="button" class="button button-small af-dash-sync-auction" data-auction-id="<?= esc_attr($auction_id) ?>">
                                <span class="dashicons dashicons-update" style="font-size:14px;margin-top:3px"></span> Sync
                            </button>
                        </div>
                        <?php endforeach; ?>
                        <?php foreach ($manualAuctionPosts as $mp): ?>
                        <div class="af-dash-auction-item">
                            <div class="af-dash-auction-item__top">
                                <span class="af-dash-badge af-dash-badge--gray">MANUAL</span>
                                <span class="af-dash-auction-item__lots">&nbsp;</span>
                            </div>
                            <h3 class="af-dash-auction-item__name"><?= esc_html($mp->post_title) ?></h3>
                            <div class="af-dash-auction-item__date">
                                <span class="dashicons dashicons-edit"></span>
                                <a href="<?= get_edit_post_link($mp->ID) ?>" style="color:#3858e9;text-decoration:none;font-size:12px">Edit</a>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>

        <!-- ═══════════════════════════════════════════
             3. SITE STATS (Last 7 Days)
             ═══════════════════════════════════════════ -->
        <div class="af-dash-card" id="af-dash-stats">
            <div class="af-dash-card__header">
                <span class="dashicons dashicons-chart-bar"></span>
                <h2>Site Stats <small>(7 days)</small></h2>
                <a href="<?= admin_url('edit.php?post_type=lot&page=af-stats-dashboard') ?>" class="af-dash-card__link">Full Stats →</a>
            </div>
            <div class="af-dash-card__body">
                <div class="af-dash-kpis af-dash-kpis--2x2">
                    <div class="af-dash-kpi" id="af-dash-stat-visitors">
                        <span class="af-dash-kpi__value af-dash-loading">—</span>
                        <span class="af-dash-kpi__label">Visitors</span>
                    </div>
                    <div class="af-dash-kpi" id="af-dash-stat-pageviews">
                        <span class="af-dash-kpi__value af-dash-loading">—</span>
                        <span class="af-dash-kpi__label">Pageviews</span>
                    </div>
                    <div class="af-dash-kpi" id="af-dash-stat-sessions">
                        <span class="af-dash-kpi__value af-dash-loading">—</span>
                        <span class="af-dash-kpi__label">Sessions</span>
                    </div>
                    <div class="af-dash-kpi" id="af-dash-stat-bounce">
                        <span class="af-dash-kpi__value af-dash-loading">—</span>
                        <span class="af-dash-kpi__label">Bounce Rate</span>
                    </div>
                </div>
                <div style="position:relative; height:180px; margin-top:16px">
                    <canvas id="af-dash-traffic-chart"></canvas>
                </div>
            </div>
        </div>

        <!-- ═══════════════════════════════════════════
             4. INVENTORY SUMMARY
             ═══════════════════════════════════════════ -->
        <div class="af-dash-card" id="af-dash-inventory">
            <div class="af-dash-card__header">
                <span class="dashicons dashicons-tag"></span>
                <h2>Inventory</h2>
            </div>
            <div class="af-dash-card__body">
                <div class="af-dash-kpis af-dash-kpis--2x2">
                    <div class="af-dash-kpi af-dash-kpi--large">
                        <span class="af-dash-kpi__value"><?= number_format($total_lots) ?></span>
                        <span class="af-dash-kpi__label">Published Lots</span>
                    </div>
                    <div class="af-dash-kpi af-dash-kpi--large">
                        <span class="af-dash-kpi__value"><?= number_format($total_auctions) ?></span>
                        <span class="af-dash-kpi__label">Total Auctions</span>
                    </div>
                    <div class="af-dash-kpi af-dash-kpi--success">
                        <span class="af-dash-kpi__value"><?= count($activeAuctions) ?></span>
                        <span class="af-dash-kpi__label">Active / Upcoming</span>
                    </div>
                    <div class="af-dash-kpi">
                        <span class="af-dash-kpi__value"><?= $total_auctions - count($activeAuctions) ?></span>
                        <span class="af-dash-kpi__label">Archived / Ended</span>
                    </div>
                </div>
            </div>
        </div>

        <!-- ═══════════════════════════════════════════
             5. SYSTEM HEALTH
             ═══════════════════════════════════════════ -->
        <div class="af-dash-card" id="af-dash-health">
            <div class="af-dash-card__header">
                <span class="dashicons dashicons-admin-tools"></span>
                <h2>System Health</h2>
                <a href="<?= admin_url('edit.php?post_type=lot&page=auctionforge-updates') ?>" class="af-dash-card__link">Updates →</a>
            </div>
            <div class="af-dash-card__body">
                <table class="af-dash-health-table">
                    <tr>
                        <td>Plugin Version</td>
                        <td>
                            <strong><?= esc_html($pluginInfo['ver']) ?></strong>
                            <?php if ($has_update): ?>
                                <span class="af-dash-badge af-dash-badge--orange"><?= esc_html($new_version) ?> available</span>
                            <?php else: ?>
                                <span class="af-dash-badge af-dash-badge--green">Up to date</span>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <tr>
                        <td>PHP Version</td>
                        <td><strong><?= PHP_VERSION ?></strong></td>
                    </tr>
                    <tr>
                        <td>WordPress</td>
                        <td><strong><?= get_bloginfo('version') ?></strong></td>
                    </tr>
                    <tr>
                        <td>Sync Engine</td>
                        <td>
                            <span class="af-dash-badge af-dash-badge--<?= $external_cron ? 'green' : ($wp_cron_enabled ? 'blue' : 'red') ?>">
                                <?= esc_html($cron_mode) ?>
                            </span>
                            <?php if ($external_cron && $heartbeat_age > 600): ?>
                                <span class="af-dash-badge af-dash-badge--red">Heartbeat overdue</span>
                            <?php elseif ($external_cron): ?>
                                <span class="af-dash-badge af-dash-badge--green">Healthy</span>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <tr>
                        <td>Database</td>
                        <td>
                            <strong>v<?= get_option(AUCTIONFORGE_DB_OPTION_NAME, '?') ?></strong>
                            <?php if (intval(get_option(AUCTIONFORGE_DB_OPTION_NAME, 0)) >= AUCTIONFORGE_DB_VERSION): ?>
                                <span class="af-dash-badge af-dash-badge--green">Current</span>
                            <?php else: ?>
                                <span class="af-dash-badge af-dash-badge--orange">Needs migration</span>
                            <?php endif; ?>
                        </td>
                    </tr>
                </table>
            </div>
        </div>

        <!-- ═══════════════════════════════════════════
             6. QUICK LINKS
             ═══════════════════════════════════════════ -->
        <div class="af-dash-card" id="af-dash-links">
            <div class="af-dash-card__header">
                <span class="dashicons dashicons-admin-links"></span>
                <h2>Quick Links</h2>
            </div>
            <div class="af-dash-card__body">
                <div class="af-dash-quicklinks">
                    <a href="<?= admin_url('edit.php?post_type=lot&page=bidspirit_options') ?>" class="af-dash-qlink">
                        <span class="dashicons dashicons-admin-generic"></span> Settings
                    </a>
                    <a href="<?= admin_url('edit.php?post_type=lot&page=auctionforge-sync-status') ?>" class="af-dash-qlink">
                        <span class="dashicons dashicons-update-alt"></span> Sync Status
                    </a>
                    <a href="<?= admin_url('edit.php?post_type=lot&page=af-stats-dashboard') ?>" class="af-dash-qlink">
                        <span class="dashicons dashicons-chart-bar"></span> Statistics
                    </a>
                    <a href="<?= admin_url('edit.php?post_type=lot&page=auctionforge-submissions') ?>" class="af-dash-qlink">
                        <span class="dashicons dashicons-feedback"></span> Submissions
                    </a>
                    <a href="<?= admin_url('edit.php?post_type=lot&page=auctionforge-shortcodes') ?>" class="af-dash-qlink">
                        <span class="dashicons dashicons-shortcode"></span> Shortcodes
                    </a>
                    <a href="<?= admin_url('edit.php?post_type=lot&page=auctionforge-history') ?>" class="af-dash-qlink">
                        <span class="dashicons dashicons-backup"></span> History
                    </a>
                </div>
            </div>
        </div>

    </div><!-- .af-dash-grid -->
</div>

<style>
/* ─── Dashboard Layout ─── */
.af-dashboard-wrap { max-width: 1400px; padding: 20px 20px 40px; }
.af-dashboard-title {
    display: flex; align-items: center; gap: 4px;
    font-size: 24px; font-weight: 600; margin: 0 0 24px; color: #1d2327;
}
.af-dash-version {
    font-size: 12px; font-weight: 400; color: #8c8f94;
    background: #f0f0f1; padding: 2px 8px; border-radius: 4px; margin-left: 8px;
}

.af-dash-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 20px;
}
.af-dash-card {
    background: #fff; border: 1px solid #dcdcde; border-radius: 8px;
    box-shadow: 0 1px 3px rgba(0,0,0,.04);
    overflow: hidden;
}
.af-dash-card--wide { grid-column: 1 / -1; }

.af-dash-card__header {
    display: flex; align-items: center; gap: 8px;
    padding: 14px 20px; border-bottom: 1px solid #f0f0f1;
    background: linear-gradient(135deg, #fafbfc 0%, #f8f9fa 100%);
}
.af-dash-card__header .dashicons {
    font-size: 20px; width: 20px; height: 20px; color: #3858e9;
}
.af-dash-card__header h2 {
    margin: 0; font-size: 15px; font-weight: 600; color: #1d2327; flex: 1;
}
.af-dash-card__header h2 small { color: #8c8f94; font-weight: 400; }
.af-dash-card__link {
    font-size: 12px; text-decoration: none; color: #3858e9; white-space: nowrap;
}
.af-dash-card__link:hover { text-decoration: underline; }
.af-dash-card__body { padding: 20px; }

/* ─── Badges ─── */
.af-dash-badge {
    display: inline-block; font-size: 11px; font-weight: 600; padding: 2px 8px;
    border-radius: 4px; text-transform: uppercase; letter-spacing: .3px; line-height: 18px;
}
.af-dash-badge--green  { background: #d4edda; color: #155724; }
.af-dash-badge--blue   { background: #e8f0fe; color: #1a56db; }
.af-dash-badge--orange  { background: #fff3cd; color: #856404; }
.af-dash-badge--red    { background: #f8d7da; color: #721c24; }
.af-dash-badge--gray   { background: #e9ecef; color: #495057; }

/* ─── KPI Cards ─── */
.af-dash-kpis { display: grid; gap: 12px; }
.af-dash-kpis--4 { grid-template-columns: repeat(4, 1fr); }
.af-dash-kpis--2x2 { grid-template-columns: repeat(2, 1fr); }

.af-dash-kpi {
    background: #f8f9fa; border: 1px solid #e9ecef; border-radius: 6px;
    padding: 14px 16px; text-align: center;
}
.af-dash-kpi__value {
    display: block; font-size: 28px; font-weight: 700; color: #1d2327; line-height: 1.2;
}
.af-dash-kpi__label {
    display: block; font-size: 11px; color: #8c8f94; text-transform: uppercase;
    letter-spacing: .5px; margin-top: 4px;
}
.af-dash-kpi--active { border-left: 3px solid #3858e9; }
.af-dash-kpi--active .af-dash-kpi__value { color: #3858e9; }
.af-dash-kpi--success { border-left: 3px solid #28a745; }
.af-dash-kpi--success .af-dash-kpi__value { color: #28a745; }
.af-dash-kpi--danger { border-left: 3px solid #dc3545; }
.af-dash-kpi--danger .af-dash-kpi__value { color: #dc3545; }
.af-dash-kpi--large .af-dash-kpi__value { font-size: 36px; }

/* ─── Sync Meta / Actions ─── */
.af-dash-meta {
    display: flex; align-items: center; gap: 6px;
    margin: 14px 0 0; font-size: 13px; color: #50575e;
}
.af-dash-actions { margin-top: 16px; display: flex; align-items: center; gap: 12px; }
.af-dash-inline-status { font-size: 13px; color: #50575e; }

/* ─── Auction Grid ─── */
.af-dash-auction-grid {
    display: grid; grid-template-columns: repeat(auto-fill, minmax(240px, 1fr)); gap: 14px;
}
.af-dash-auction-item {
    background: #f8f9fa; border: 1px solid #e9ecef; border-radius: 6px;
    padding: 14px 16px; transition: box-shadow .15s;
}
.af-dash-auction-item:hover { box-shadow: 0 2px 8px rgba(0,0,0,.08); }
.af-dash-auction-item__top { display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px; }
.af-dash-auction-item__lots { font-size: 12px; color: #8c8f94; }
.af-dash-auction-item__name { margin: 0 0 6px; font-size: 14px; font-weight: 600; color: #1d2327; line-height: 1.3; }
.af-dash-auction-item__date { font-size: 12px; color: #50575e; margin-bottom: 10px; display: flex; align-items: center; gap: 4px; }
.af-dash-auction-item__date .dashicons { font-size: 14px; width: 14px; height: 14px; }

/* ─── Health Table ─── */
.af-dash-health-table { width: 100%; border-collapse: collapse; }
.af-dash-health-table td { padding: 10px 0; font-size: 13px; border-bottom: 1px solid #f0f0f1; }
.af-dash-health-table tr:last-child td { border-bottom: none; }
.af-dash-health-table td:first-child { color: #50575e; width: 140px; }
.af-dash-health-table td:last-child { display: flex; align-items: center; gap: 8px; }

/* ─── Quick Links ─── */
.af-dash-quicklinks { display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px; }
.af-dash-qlink {
    display: flex; align-items: center; gap: 8px;
    padding: 10px 14px; border: 1px solid #e9ecef; border-radius: 6px;
    font-size: 13px; font-weight: 500; color: #1d2327; text-decoration: none;
    transition: all .15s;
}
.af-dash-qlink:hover {
    background: #3858e9; color: #fff; border-color: #3858e9;
}
.af-dash-qlink:hover .dashicons { color: #fff; }
.af-dash-qlink .dashicons { font-size: 16px; width: 16px; height: 16px; color: #3858e9; }

/* ─── Empty state ─── */
.af-dash-empty {
    display: flex; align-items: center; gap: 8px;
    padding: 20px; color: #8c8f94; font-size: 14px;
}

/* ─── Loading shimmer ─── */
.af-dash-loading { color: #ddd !important; animation: af-shimmer 1.5s ease-in-out infinite; }
@keyframes af-shimmer { 0%,100%{opacity:1} 50%{opacity:.4} }

/* ─── Responsive ─── */
@media (max-width: 960px) {
    .af-dash-grid { grid-template-columns: 1fr; }
    .af-dash-kpis--4 { grid-template-columns: repeat(2, 1fr); }
    .af-dash-quicklinks { grid-template-columns: repeat(2, 1fr); }
}
</style>

<script src="https://cdn.jsdelivr.net/npm/chart.js@4/dist/chart.umd.min.js"></script>
<script>
(function() {
    var nonce = '<?= esc_js($nonce) ?>';
    var statsNonce = '<?= esc_js($stats_nonce) ?>';
    var ajaxUrl = '<?= admin_url('admin-ajax.php') ?>';

    // ── Sync All Active Auctions ──
    var syncBtn = document.getElementById('af-dash-sync-now');
    var syncStatus = document.getElementById('af-dash-sync-status');

    if (syncBtn) {
        syncBtn.addEventListener('click', function() {
            syncBtn.disabled = true;
            syncBtn.innerHTML = '<span class="dashicons dashicons-update af-spin" style="margin-top:4px"></span> Syncing...';
            syncStatus.textContent = 'Enqueueing full sync...';

            var fd = new FormData();
            fd.append('action', 'auctionforge_sync_enqueue');
            fd.append('nonce', nonce);
            fd.append('job_type', 'full_sync');
            fd.append('auction_id', '__all__');
            fd.append('source', 'admin');

            fetch(ajaxUrl, { method: 'POST', body: fd })
                .then(function(r) { return r.json(); })
                .then(function(data) {
                    if (data.success) {
                        syncStatus.innerHTML = '<span style="color:#28a745">✓ Sync queued successfully</span>';
                    } else {
                        syncStatus.innerHTML = '<span style="color:#dc3545">✗ ' + (data.data || 'Failed') + '</span>';
                    }
                })
                .catch(function() {
                    syncStatus.innerHTML = '<span style="color:#dc3545">✗ Network error</span>';
                })
                .finally(function() {
                    syncBtn.disabled = false;
                    syncBtn.innerHTML = '<span class="dashicons dashicons-update" style="margin-top:4px"></span> Sync All Active Auctions';
                });
        });
    }

    // ── Per-Auction Sync Buttons ──
    document.querySelectorAll('.af-dash-sync-auction').forEach(function(btn) {
        btn.addEventListener('click', function() {
            var auctionId = this.dataset.auctionId;
            var el = this;
            el.disabled = true;
            el.innerHTML = '<span class="dashicons dashicons-update af-spin" style="font-size:14px;margin-top:3px"></span>';

            var fd = new FormData();
            fd.append('action', 'auctionforge_sync_enqueue');
            fd.append('nonce', nonce);
            fd.append('job_type', 'catalog_sync');
            fd.append('auction_id', auctionId);
            fd.append('source', 'admin');

            fetch(ajaxUrl, { method: 'POST', body: fd })
                .then(function(r) { return r.json(); })
                .then(function(data) {
                    el.innerHTML = data.success ? '✓' : '✗';
                    el.style.color = data.success ? '#28a745' : '#dc3545';
                    setTimeout(function() {
                        el.innerHTML = '<span class="dashicons dashicons-update" style="font-size:14px;margin-top:3px"></span> Sync';
                        el.style.color = '';
                        el.disabled = false;
                    }, 2000);
                })
                .catch(function() {
                    el.innerHTML = '✗';
                    el.disabled = false;
                });
        });
    });

    // ── Load Stats via AJAX ──
    var statsFd = new FormData();
    statsFd.append('action', 'af_stats_dashboard');
    statsFd.append('nonce', statsNonce);
    statsFd.append('from', '<?= esc_js($seven_days_ago) ?>');
    statsFd.append('to', '<?= esc_js($today) ?>');

    fetch(ajaxUrl, { method: 'POST', body: statsFd })
        .then(function(r) { return r.json(); })
        .then(function(resp) {
            if (!resp.success) return;
            var d = resp.data;
            setKPI('af-dash-stat-visitors', fmtNum(d.current.visitors));
            setKPI('af-dash-stat-pageviews', fmtNum(d.current.pageviews));
            setKPI('af-dash-stat-sessions', fmtNum(d.current.sessions));
            setKPI('af-dash-stat-bounce', d.current.bounce_rate + '%');

            // Draw mini chart
            if (d.charts && d.charts.daily_visitors && typeof Chart !== 'undefined') {
                var labels = d.charts.daily_visitors.map(function(r) {
                    var parts = r.date.split('-');
                    return parts[1] + '/' + parts[2];
                });
                var visitors = d.charts.daily_visitors.map(function(r) { return parseInt(r.count); });
                var pvs = (d.charts.daily_pageviews || []).map(function(r) { return parseInt(r.count); });

                new Chart(document.getElementById('af-dash-traffic-chart'), {
                    type: 'line',
                    data: {
                        labels: labels,
                        datasets: [
                            {
                                label: 'Visitors',
                                data: visitors,
                                borderColor: '#3858e9',
                                backgroundColor: 'rgba(56,88,233,.08)',
                                fill: true,
                                tension: .4,
                                pointRadius: 3,
                                borderWidth: 2
                            },
                            {
                                label: 'Pageviews',
                                data: pvs,
                                borderColor: '#28a745',
                                backgroundColor: 'rgba(40,167,69,.05)',
                                fill: true,
                                tension: .4,
                                pointRadius: 3,
                                borderWidth: 2
                            }
                        ]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: true,
                        plugins: { legend: { position: 'bottom', labels: { boxWidth: 12, padding: 16 } } },
                        scales: {
                            y: { beginAtZero: true, ticks: { precision: 0 }, grid: { color: '#f0f0f1' } },
                            x: { grid: { display: false } }
                        }
                    }
                });
            }
        })
        .catch(function(err) { console.warn('Dashboard stats load failed:', err); });

    function setKPI(id, val) {
        var el = document.querySelector('#' + id + ' .af-dash-kpi__value');
        if (el) { el.textContent = val; el.classList.remove('af-dash-loading'); }
    }
    function fmtNum(n) {
        n = parseInt(n) || 0;
        if (n >= 1000000) return (n / 1000000).toFixed(1) + 'M';
        if (n >= 1000) return (n / 1000).toFixed(1) + 'K';
        return n.toString();
    }

    // Spin animation
    var style = document.createElement('style');
    style.textContent = '.af-spin { animation: af-spin-anim .8s linear infinite; } @keyframes af-spin-anim { from{transform:rotate(0)} to{transform:rotate(360deg)} }';
    document.head.appendChild(style);
})();
</script>
