@extends('nexus.layouts.app')

@section('page-title', 'Overview')
@section('sys-mode', 'OVERVIEW')

@section('head')
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.4.1/chart.umd.min.js"></script>
@endsection

@section('content')

@php
$isOpen = $sessionMetrics['is_open'] ?? false;
$activeSession = $sessionMetrics['active_session'] ?? null;
$engineStatus = \App\Nexus\Engine\NexusConfig::get('nexus_status', 'inactive');

// Live session state for the controller grid (always today, even on historical views)
$liveIsOpen = $sessionMetrics['live_is_open'] ?? $isOpen;
$liveActiveSession = $sessionMetrics['live_active_session'] ?? $activeSession;
$sessionsLive = $sessionMetrics['sessions_live'] ?? ($sessionMetrics['sessions_today'] ?? []);

// Index live sessions by session_number for the controller grid
$sessionsByNum = [];
foreach ($sessionsLive as $s) {
$num = is_array($s) ? ($s['session_number'] ?? null) : ($s->session_number ?? null);
if ($num !== null) $sessionsByNum[$num] = $s;
}

$sessionLabels = ['ASIA-PACIFIC', 'EUROPE', 'AMERICAS'];
$sessionTimes = ['01:00 -- 02:00 UTC', '09:00 -- 10:00 UTC', '17:00 -- 18:00 UTC'];

// Date range context for labels
$dateStart = $dates['start'] ?? now()->startOfMonth()->toDateString();
$dateEnd = $dates['end'] ?? now()->toDateString();
$isToday = $dateStart === now()->toDateString() && $dateEnd === now()->toDateString();
$isYesterday = $dateStart === now()->subDay()->toDateString() && $dateEnd === now()->subDay()->toDateString();
$isSingleDay = $dateStart === $dateEnd;
$isCurrentMonth = \Carbon\Carbon::parse($dateStart)->month === now()->month
&& \Carbon\Carbon::parse($dateStart)->year === now()->year
&& \Carbon\Carbon::parse($dateStart)->day === 1;

// Build period label for stat strips
if ($isToday) {
$periodLabel = 'TODAY';
$periodSuffix = 'Today';
} elseif ($isYesterday) {
$periodLabel = 'YESTERDAY';
$periodSuffix = 'Yesterday';
} elseif ($isSingleDay) {
$periodLabel = strtoupper(\Carbon\Carbon::parse($dateStart)->format('M j'));
$periodSuffix = \Carbon\Carbon::parse($dateStart)->format('M j');
} else {
$periodLabel = strtoupper(\Carbon\Carbon::parse($dateStart)->format('M Y'));
$periodSuffix = \Carbon\Carbon::parse($dateStart)->format('M Y');
}

// Current month for selector highlight
$currentMonth = request()->input('month', now()->format('Y-m'));
$activeRange = request()->input('range', '');
@endphp

{{-- PAGE HEADER --}}
<div class="page-header">
    <div>
        <h1>SYSTEM <em>OVERVIEW</em></h1>
        <p class="page-header-sub">Real-time engine telemetry</p>
    </div>
    <div class="page-header-right">
        <span class="chip {{ $engineStatus === 'active' ? ($isOpen ? 'chip-live' : 'chip-active') : 'chip-pending' }}">
            {{ strtoupper($engineStatus) }}
        </span>

        {{-- DATE CONTROLS --}}
        <div class="date-controls" style="margin-top: 8px;">
            <div class="month-selector" id="monthSelector">
                <button type="button" class="month-selector-btn" id="monthSelectorBtn">
                    {{ \Carbon\Carbon::parse($dateStart)->format('F Y') }}
                </button>
                <div class="month-selector-dropdown" id="monthSelectorDropdown">
                    @foreach ($availableMonths ?? [] as $m)
                    <div class="month-option {{ $currentMonth === $m ? 'active' : '' }}"
                        data-month="{{ $m }}">
                        {{ \Carbon\Carbon::parse($m . '-01')->format('F Y') }}
                    </div>
                    @endforeach
                </div>
            </div>
            <div class="quick-filters">
                <button type="button" class="quick-filter {{ $activeRange === 'today' || ($isToday && !$activeRange) ? 'active' : '' }}" data-range="today">Today</button>
                <button type="button" class="quick-filter {{ $activeRange === 'yesterday' ? 'active' : '' }}" data-range="yesterday">Yesterday</button>
                <button type="button" class="quick-filter {{ $activeRange === '7days' ? 'active' : '' }}" data-range="7days">7 Days</button>
            </div>
        </div>
    </div>
</div>


{{-- SESSION CONTROLLER --}}

<div class="section-header">
    <span class="section-label">Session Controller</span>
    <span class="section-right">3 daily &bull; 1hr windows</span>
</div>

<div class="session-grid">
    @for ($i = 1; $i <= 3; $i++)
        @php
        $sess=$sessionsByNum[$i] ?? null;
        $sStatus=$sess ? (is_array($sess) ? ($sess['status'] ?? 'pending' ) : ($sess->status ?? 'pending')) : 'pending';
        $sActive = $sStatus === 'active';
        $sDone = in_array($sStatus, ['completed', 'processing']);
        @endphp
        <div class="session-block {{ $sActive ? 'active-session' : '' }}">
            <div class="session-num">SESSION {{ $i }}</div>
            <div class="session-name">{{ $sessionLabels[$i - 1] }}</div>
            <div class="session-time">{{ $sessionTimes[$i - 1] }}</div>

            @if ($sActive && $liveActiveSession)
            @php $endTime = now()->addSeconds($liveActiveSession['seconds_remaining'] ?? 0)->toIso8601String(); @endphp
            <div class="session-countdown" id="countdown" data-end="{{ $endTime }}">--:--</div>
            <div class="session-countdown-label">Remaining</div>
            @elseif ($sDone)
            <span class="chip chip-completed">COMPLETED</span>
            @else
            <span class="chip chip-pending">PENDING</span>
            @endif
        </div>
        @endfor
</div>


{{-- KEY METRICS (date-aware labels) --}}

<div class="stat-strip">
    <div class="stat-cell">
        <div class="stat-label">Pending Sells</div>
        @php
            $pendingManual = $sessionMetrics['pending_sell_count'] ?? 0;
            $pendingAi = $sessionMetrics['pending_ai_sell_count'] ?? 0;
        @endphp
        <div class="stat-value orange" id="pendingSellsCount">{{ number_format($pendingManual + $pendingAi) }}</div>
        <div class="stat-sub">Manual: {{ number_format($pendingManual) }} / Bot: {{ number_format($pendingAi) }}</div>
    </div>
    <div class="stat-cell">
        <div class="stat-label">Bids <span class="stat-period-badge">{{ $periodLabel }}</span></div>
        <div class="stat-value">{{ number_format($sessionMetrics['total_bids'] ?? 0) }}</div>
    </div>
    <div class="stat-cell">
        <div class="stat-label">Volume <span class="stat-period-badge">{{ $periodLabel }}</span></div>
        <div class="stat-value">${{ number_format($sessionMetrics['total_volume'] ?? 0, 2) }}</div>
    </div>
    <div class="stat-cell">
        <div class="stat-label">Win Rate <span class="stat-period-badge">{{ $periodLabel }}</span></div>
        @php $wr = $sessionMetrics['win_rate'] ?? 0; @endphp
        <div class="stat-value {{ $wr > 0 ? 'green' : '' }}">{{ number_format($wr, 1) }}%</div>
    </div>
</div>


{{-- CHARTS --}}

@php
$hasActivity = false;
$ds = $chartData['datasets'] ?? [];
foreach ($ds as $dataset) {
foreach ($dataset['data'] ?? [] as $val) {
if ($val > 0) { $hasActivity = true; break 2; }
}
}
$hasResults = ($resultSummary['won'] ?? 0) > 0 || ($resultSummary['lost'] ?? 0) > 0;
$chartGranularity = $chartData['granularity'] ?? 'hourly';
@endphp

<div class="chart-row">
    <div class="chart-panel">
        <div class="chart-title">Trading Activity <span class="text-dim">&bull; {{ $chartGranularity === 'daily' ? $periodSuffix : ($isToday ? '24hr' : $periodSuffix) }}</span></div>
        <div class="chart-wrap h250" style="position: relative;">
            <canvas id="activityChart"></canvas>
            @if (!$hasActivity)
            <div class="chart-empty-overlay">
                <span class="chart-empty-text">Engine inactive -- no trading data</span>
            </div>
            @endif
        </div>
    </div>
    <div class="chart-panel">
        <div class="chart-title">Session Results <span class="text-dim">&bull; {{ $periodSuffix }}</span></div>
        <div class="chart-wrap h250" style="position: relative;">
            <canvas id="resultsChart"></canvas>
            @php
            $rWon = $resultSummary['won'] ?? 0;
            $rLost = $resultSummary['lost'] ?? 0;
            $rPending = $resultSummary['pending'] ?? 0;
            $rTotal = $rWon + $rLost + $rPending;
            @endphp
            @if ($hasResults)
            <div class="chart-center-label">
                <div class="chart-center-value">{{ number_format($rTotal) }}</div>
                <div class="chart-center-text">TRADES</div>
            </div>
            @else
            <div class="chart-empty-overlay">
                <span class="chart-empty-text">{{ $rPending }} pending &bull; No results yet</span>
            </div>
            @endif
        </div>
    </div>
</div>


{{-- SESSION HISTORY --}}

<div class="section-header" style="flex-wrap: wrap; gap: 8px;">
    <span class="section-label">Session History</span>
    <div style="display: flex; align-items: center; gap: 16px;">
        <span class="section-right" style="margin: 0;">{{ $periodSuffix }}</span>
        <a href="/nexus/api/sessions/export?start={{ $dateStart }}&end={{ $dateEnd }}" class="btn-export">EXPORT CSV</a>
    </div>
</div>

@if (!empty($sessionHistory) && count($sessionHistory) > 0)
<div class="data-table-wrap">
    <table class="data-table" id="sessionHistoryTable">
        <thead>
            <tr>
                <th style="width: 30px;"></th>
                <th>Date</th>
                <th>Session</th>
                <th>Status</th>
                <th class="col-right">Bids</th>
                <th class="col-right">Evaluated</th>
                <th class="col-right">Approved</th>
                <th class="col-right">Rejected</th>
                <th class="col-right">Win Rate</th>
            </tr>
        </thead>
        <tbody>
            @foreach ($sessionHistory as $sh)
            @php
            $shCompleted = $sh['status'] === 'completed';
            $shActive = $sh['status'] === 'active';
            $wrt = $sh['win_rate_target'] ?? 0;
            $wra = $sh['win_rate_actual'] ?? 0;
            @endphp
            <tr class="session-history-row {{ $shCompleted ? 'expandable' : '' }} sh-page-row"
                data-session-id="{{ $sh['id'] }}"
                data-expandable="{{ $shCompleted ? '1' : '0' }}">
                <td>
                    @if ($shCompleted)
                    <span class="session-expand-icon">&rsaquo;</span>
                    @endif
                </td>
                <td>{{ \Carbon\Carbon::parse($sh['session_date'])->format('M d') }}</td>
                <td>S{{ $sh['session_number'] }}</td>
                <td>
                    <span class="chip chip-sm {{ $shCompleted ? 'chip-completed' : ($shActive ? 'chip-active' : 'chip-pending') }}">
                        {{ strtoupper($sh['status']) }}
                    </span>
                </td>
                <td class="col-right">{{ $shCompleted ? number_format($sh['total_bids']) : '--' }}</td>
                <td class="col-right">{{ $shCompleted ? number_format($sh['evaluated']) : '--' }}</td>
                <td class="col-right text-green">{{ $shCompleted ? number_format($sh['approved']) : '--' }}</td>
                <td class="col-right text-red">{{ $shCompleted ? number_format($sh['rejected']) : '--' }}</td>
                <td class="col-right">
                    @if ($shCompleted)
                    <span class="text-dim">{{ number_format($wrt, 0) }}%</span>
                    &rarr;
                    <span class="{{ $wra >= $wrt ? 'text-green' : 'text-yellow' }}">{{ number_format($wra, 1) }}%</span>
                    @else
                    --
                    @endif
                </td>
            </tr>
            {{-- Expandable detail row (loaded via AJAX) --}}
            @if ($shCompleted)
            <tr class="session-detail-row sh-detail-row" id="session-detail-{{ $sh['id'] }}" data-parent-session="{{ $sh['id'] }}" style="display: none;">
                <td colspan="9" style="padding: 0;">
                    <div class="session-detail" id="session-detail-content-{{ $sh['id'] }}">
                        <div class="ajax-loading-spinner">
                            Loading <span class="loading-dot"></span>
                        </div>
                    </div>
                </td>
            </tr>
            @endif
            @endforeach
        </tbody>
    </table>
</div>
@if (count($sessionHistory) > 10)
<div class="ajax-pagination" id="shPagination">
    <button type="button" class="ajax-pagination-btn disabled" id="shPrev" onclick="nexus.paginateSessionHistory(-1)" disabled>PREV</button>
    <span class="ajax-pagination-info">Page <em id="shCurrentPage">1</em> of <em id="shTotalPages">{{ ceil(count($sessionHistory) / 10) }}</em> &bull; {{ count($sessionHistory) }} sessions</span>
    <button type="button" class="ajax-pagination-btn" id="shNext" onclick="nexus.paginateSessionHistory(1)">NEXT</button>
</div>
@endif
@else
<div class="empty-state"><span class="empty-state-text">No session data for this period</span></div>
@endif

{{-- BOT GOVERNANCE GLANCE --}}

@php
$bg = $botGlance ?? [];
$bgBots = $bg['total_bots'] ?? 0;
$bgCapital = $bg['total_capital'] ?? 0;
$bgProfit = $bg['total_profit'] ?? 0;
$bgOnTrack = $bg['on_track'] ?? 0;
$bgHot = $bg['hot'] ?? 0;
$bgCold = $bg['cold'] ?? 0;
$bgPlans = $bg['plan_counts'] ?? [];
@endphp

<div class="section-header">
    <span class="section-label">Bot Governance</span>
    <span class="section-right">AI bot profit oversight</span>
</div>

@if ($bgBots > 0)
<div class="bot-glance">
    <div class="bot-glance-cell">
        <span class="stat-label">Active Bots</span>
        <span class="bot-glance-value orange">{{ $bgBots }}</span>
        <div class="bot-glance-plans">
            @foreach ($bgPlans as $planName => $count)
            {{ $planName }}: {{ $count }}<br>
            @endforeach
        </div>
    </div>
    <div class="bot-glance-cell">
        <span class="stat-label">Capital</span>
        <span class="bot-glance-value">${{ number_format($bgCapital, 0) }}</span>
    </div>
    <div class="bot-glance-cell">
        <span class="stat-label">Profit</span>
        <span class="bot-glance-value text-green">${{ number_format($bgProfit, 0) }}</span>
    </div>
    <div class="bot-glance-cell">
        <span class="stat-label">Track Status</span>
        <span class="bot-glance-value">
            <span class="text-green">{{ $bgOnTrack }}</span>
            <span class="text-dim">/</span>
            <span class="text-yellow">{{ $bgHot }}</span>
            <span class="text-dim">/</span>
            <span class="text-red">{{ $bgCold }}</span>
        </span>
        <span class="stat-sub">On Track / Hot / Cold</span>
        <a href="/nexus/bots" class="bot-glance-link">View Full Report</a>
    </div>
</div>
@else
<div class="empty-state"><span class="empty-state-text">No active bots with governance configured</span></div>
@endif

{{-- ECONOMY HEALTH --}}

@php
$eHealth = $economyPanel['economy_health'] ?? 'unknown';
$eLiq = $economyPanel['liquidity_index'] ?? 0;
$eCap = $economyPanel['users_at_cap'] ?? 0;
$eWin = $economyPanel['win_rate_avg'] ?? 0;
$eVol = $economyPanel['total_volume'] ?? 0;
$eHealthColor = match($eHealth) { 'healthy' => 'text-green', 'overheated' => 'text-red', 'stagnant' => 'text-yellow', default => 'text-dim' };
@endphp

<div class="section-header">
    <span class="section-label">Economy Health</span>
    <span class="section-right"><span class="{{ $eHealthColor }}">{{ strtoupper($eHealth) }}</span></span>
</div>

<div class="health-grid">
    <div class="health-cell">
        <div class="health-row">
            <span class="stat-label">Liquidity Index</span>
            <span class="health-value {{ $eLiq >= 0.6 ? 'text-green' : ($eLiq >= 0.3 ? 'text-yellow' : 'text-red') }}">{{ number_format($eLiq * 100, 1) }}%</span>
        </div>
        <div class="health-bar-track">
            <div class="health-bar-fill {{ $eLiq >= 0.6 ? 'green' : ($eLiq >= 0.3 ? 'yellow' : 'red') }}" style="width: {{ min($eLiq * 100, 100) }}%"></div>
        </div>
    </div>
    <div class="health-cell">
        <div class="health-row">
            <span class="stat-label">Users At Cap</span>
            <span class="health-value {{ $eCap > 10 ? 'text-yellow' : '' }}">{{ $eCap }}</span>
        </div>
        <div class="health-bar-track">
            <div class="health-bar-fill {{ $eCap > 10 ? 'yellow' : 'green' }}" style="width: {{ min($eCap * 5, 100) }}%"></div>
        </div>
    </div>
    <div class="health-cell">
        <div class="health-row">
            <span class="stat-label">Avg Win Rate</span>
            <span class="health-value {{ $eWin > 30 ? 'text-green' : 'text-yellow' }}">{{ number_format($eWin, 1) }}%</span>
        </div>
        <div class="health-bar-track">
            <div class="health-bar-fill {{ $eWin > 30 ? 'green' : 'yellow' }}" style="width: {{ min($eWin, 100) }}%"></div>
        </div>
    </div>
    <div class="health-cell">
        <div class="health-row">
            <span class="stat-label">Volume</span>
            <span class="health-value text-orange">${{ number_format($eVol, 0) }}</span>
        </div>
        <div class="health-bar-track">
            <div class="health-bar-fill orange" style="width: 100%"></div>
        </div>
    </div>
</div>


{{-- CAP WARNINGS --}}

@if (!empty($capWarnings) && count($capWarnings) > 0)
<div class="section-header">
    <span class="section-label">Profit Cap Warnings</span>
    <span class="section-right">{{ count($capWarnings) }} user(s)</span>
</div>

@foreach ($capWarnings as $w)
@php $wPct = $w['cap_percent'] ?? 0; @endphp
<div class="alert-row {{ $wPct >= 95 ? 'critical' : '' }}">
    <span class="alert-prefix">{{ $wPct >= 95 ? 'CRIT' : 'WARN' }}</span>
    <span class="alert-text">
        <span class="user-link" onclick="nexus.showAuditTrail({{ $w['user_id'] ?? 0 }}, '{{ addslashes($w['username'] ?? '') }}')">{{ $w['username'] ?? 'User #' . ($w['user_id'] ?? '?') }}</span>
        &bull; {{ number_format($wPct, 1) }}% of cap
        &bull; ${{ number_format($w['profit'] ?? 0, 2) }} / ${{ number_format($w['cap'] ?? 0, 2) }}
    </span>
</div>
@endforeach
@endif


{{-- TOP BIDDERS --}}

<div class="section-header">
    <span class="section-label">Top Bidders</span>
    <span class="section-right">{{ $periodSuffix }} &bull; by wins &bull; Manual traders only</span>
</div>

@if (!empty($topBidders) && count($topBidders) > 0)
<div class="data-table-wrap">
    <table class="data-table">
        <thead>
            <tr>
                <th>#</th>
                <th>User</th>
                <th class="col-right">Wins</th>
                <th class="col-right">Losses</th>
                <th class="col-right">Profit</th>
                <th class="col-right">Volume</th>
                <th class="col-right">Cap %</th>
            </tr>
        </thead>
        <tbody>
            @foreach ($topBidders as $idx => $b)
            @php
            $pp = $b['profit_percent'] ?? 0;
            $ppColor = $pp >= 9 ? 'red' : ($pp >= 7 ? 'yellow' : 'green');
            @endphp
            <tr>
                <td class="col-num">{{ str_pad($idx + 1, 2, '0', STR_PAD_LEFT) }}</td>
                <td><span class="user-link" onclick="nexus.showAuditTrail({{ $b['user_id'] ?? 0 }}, '{{ addslashes($b['username'] ?? '') }}')">{{ $b['username'] ?? 'User #' . ($b['user_id'] ?? '?') }}</span></td>
                <td class="col-right text-green">{{ $b['wins'] ?? 0 }}</td>
                <td class="col-right text-red">{{ $b['losses'] ?? 0 }}</td>
                <td class="col-right {{ ($b['total_profit'] ?? 0) >= 0 ? 'text-green' : 'text-red' }}">${{ number_format($b['total_profit'] ?? 0, 2) }}</td>
                <td class="col-right text-orange">${{ number_format($b['total_volume'] ?? 0, 2) }}</td>
                <td class="col-right">
                    <div class="inline-bar-cell">
                        <span class="text-{{ $ppColor }}">{{ number_format($pp, 1) }}%</span>
                        <div class="inline-bar-track">
                            <div class="inline-bar-fill {{ $ppColor }}" style="width: {{ min($pp * 10, 100) }}%"></div>
                        </div>
                    </div>
                </td>
            </tr>
            @endforeach
        </tbody>
    </table>
</div>
@else
<div class="empty-state"><span class="empty-state-text">No bidding data for this period</span></div>
@endif

@endsection


@section('scripts')
<script>
    document.addEventListener('DOMContentLoaded', function() {

        Chart.defaults.color = '#7a7a7a';
        Chart.defaults.borderColor = '#222222';
        Chart.defaults.font.family = "'IBM Plex Mono', monospace";
        Chart.defaults.font.size = 10;


        /* ── Trading Activity ── */

        var actCtx = document.getElementById('activityChart');
        if (actCtx) {
            var cd = @json($chartData ?? []);
            var ds = cd.datasets || [];
            new Chart(actCtx, {
                type: 'line',
                data: {
                    labels: cd.labels || [],
                    datasets: [{
                            label: 'Bids',
                            data: ds[0] ? ds[0].data : [],
                            borderColor: '#e8842a',
                            backgroundColor: 'rgba(232, 132, 42, 0.06)',
                            borderWidth: 1.5,
                            fill: true,
                            tension: 0.3,
                            pointRadius: 0,
                            pointHitRadius: 10,
                        },
                        {
                            label: 'Sells',
                            data: ds[1] ? ds[1].data : [],
                            borderColor: '#888888',
                            backgroundColor: 'rgba(136, 136, 136, 0.04)',
                            borderWidth: 1.5,
                            fill: true,
                            tension: 0.3,
                            pointRadius: 0,
                            pointHitRadius: 10,
                        }
                    ]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            position: 'bottom',
                            labels: {
                                padding: 16,
                                usePointStyle: true,
                                pointStyle: 'line',
                                font: {
                                    size: 9
                                }
                            }
                        },
                        tooltip: {
                            backgroundColor: '#141414',
                            borderColor: '#222222',
                            borderWidth: 1,
                            cornerRadius: 4,
                            titleFont: {
                                size: 10
                            },
                            bodyFont: {
                                size: 10
                            },
                        }
                    },
                    scales: {
                        x: {
                            grid: {
                                display: false
                            },
                            ticks: {
                                font: {
                                    size: 9
                                },
                                maxTicksLimit: 12
                            }
                        },
                        y: {
                            grid: {
                                color: '#222222',
                                drawBorder: false
                            },
                            ticks: {
                                font: {
                                    size: 9
                                }
                            }
                        }
                    }
                }
            });
        }


        /* ── Session Results Doughnut ── */

        var resCtx = document.getElementById('resultsChart');
        if (resCtx) {
            var rd = @json($resultSummary ?? []);
            new Chart(resCtx, {
                type: 'doughnut',
                data: {
                    labels: ['Won', 'Lost', 'Pending'],
                    datasets: [{
                        data: [rd.won || 0, rd.lost || 0, rd.pending || 0],
                        backgroundColor: ['#00aa00', '#cc0000', '#2e2e2e'],
                        borderColor: '#0a0a0a',
                        borderWidth: 2,
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    cutout: '68%',
                    plugins: {
                        legend: {
                            position: 'bottom',
                            labels: {
                                padding: 12,
                                usePointStyle: true,
                                pointStyle: 'rect',
                                font: {
                                    size: 9
                                }
                            }
                        },
                        tooltip: {
                            backgroundColor: '#141414',
                            borderColor: '#222222',
                            borderWidth: 1,
                            cornerRadius: 4,
                            bodyFont: {
                                size: 10
                            },
                        }
                    }
                }
            });
        }


        /* ── Countdown ── */

        var cdEl = document.getElementById('countdown');
        if (cdEl && cdEl.dataset.end) {
            nexus.startCountdown(cdEl, cdEl.dataset.end);
        }


        /* ── Live poll: pending sells every 30s ── */

        setInterval(function() {
            nexus.fetchJson('/nexus/api/pending-sells', function(data) {
                var el = document.getElementById('pendingSellsCount');
                if (el && data.data) el.textContent = (data.data.count || 0).toLocaleString();
            });
        }, 30000);


        /* ── Month selector ── */

        nexus.initMonthSelector('monthSelector', '/nexus/dashboard');


        /* ── Quick filters ── */

        nexus.initQuickFilters('/nexus/dashboard');


        /* ── Session history expand/collapse ── */

        nexus.initSessionHistory();

    });
</script>
@endsection