@extends('nexus.layouts.app')

@section('page-title', 'Users')
@section('sys-mode', 'USER ANALYTICS')

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

@section('content')

    @php
        $ratio = $winLossRatio ?? ['wins' => 0, 'losses' => 0, 'win_rate' => 0];
        $part = $participation ?? [];

        $dateStart = $dates['start'] ?? now()->startOfMonth()->toDateString();
        $dateEnd = $dates['end'] ?? now()->toDateString();
        $isToday = $dateStart === now()->toDateString() && $dateEnd === now()->toDateString();

        if ($isToday) {
            $periodLabel = 'TODAY';
            $periodSuffix = 'Today';
        } elseif ($dateStart === now()->subDay()->toDateString() && $dateEnd === now()->subDay()->toDateString()) {
            $periodLabel = 'YESTERDAY';
            $periodSuffix = 'Yesterday';
        } elseif ($dateStart === $dateEnd) {
            $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');
        }

        $currentMonth = request()->input('month', now()->format('Y-m'));
        $activeRange = request()->input('range', '');
        $currentSort = request()->input('sort', 'wins');
        $currentDir = request()->input('dir', 'desc');
        $currentSearch = request()->input('search', '');
        $currentLimit = (int) request()->input('limit', 20);
        $currentPage = (int) request()->input('page', 1);
    @endphp

    {{-- PAGE HEADER --}}
    <div class="page-header">
        <div>
            <h1>USER <em>ANALYTICS</em></h1>
            <p class="page-header-sub">Bidder performance and capital distribution</p>
        </div>
        <div class="page-header-right">
            <div>
                <div class="stat-label">Platform Win Rate</div>
                <div class="stat-value {{ ($ratio['win_rate'] ?? 0) >= 50 ? 'green' : 'orange' }}">{{ $ratio['win_rate'] ?? 0 }}%</div>
            </div>
            <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' ? '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>

    {{-- WIN / LOSS STRIP (date-aware) --}}
    <div class="stat-strip">
        <div class="stat-cell">
            <div class="stat-label">Total Wins <span class="stat-period-badge">{{ $periodLabel }}</span></div>
            <div class="stat-value green">{{ number_format($ratio['wins'] ?? 0) }}</div>
        </div>
        <div class="stat-cell">
            <div class="stat-label">Total Losses <span class="stat-period-badge">{{ $periodLabel }}</span></div>
            <div class="stat-value red">{{ number_format($ratio['losses'] ?? 0) }}</div>
        </div>
        <div class="stat-cell">
            <div class="stat-label">Users In Loss Streak</div>
            <div class="stat-value {{ count($lossAccumulation ?? []) > 0 ? 'yellow' : '' }}">{{ count($lossAccumulation ?? []) }}</div>
        </div>
        <div class="stat-cell">
            <div class="stat-label">Approaching Cap</div>
            <div class="stat-value {{ count($approachingCap ?? []) > 0 ? 'yellow' : '' }}">{{ count($approachingCap ?? []) }}</div>
        </div>
    </div>

    {{-- PARTICIPATION STATS (6 new cells) --}}
    <div class="stat-grid-4col">
        <div class="stat-cell">
            <div class="stat-label">Registered Users</div>
            <div class="stat-value">{{ number_format($part['registered_users'] ?? 0) }}</div>
            <div class="stat-sub-label">Total</div>
        </div>
        <div class="stat-cell">
            <div class="stat-label">Active Traders</div>
            <div class="stat-value">{{ number_format($part['active_traders'] ?? 0) }}</div>
            <div class="stat-sub-label">Ever bid</div>
        </div>
        <div class="stat-cell">
            <div class="stat-label">Unique Bidders</div>
            <div class="stat-value orange">{{ number_format($part['unique_bidders'] ?? 0) }}</div>
            <div class="stat-sub-label">{{ $periodSuffix }}</div>
        </div>
        <div class="stat-cell">
            <div class="stat-label">New Traders</div>
            <div class="stat-value">{{ number_format($part['new_traders'] ?? 0) }}</div>
            <div class="stat-sub-label">First bid {{ strtolower($periodSuffix) }}</div>
        </div>
        <div class="stat-cell">
            <div class="stat-label">First Bid Wins</div>
            <div class="stat-value green">{{ number_format($part['first_bid_wins'] ?? 0) }}</div>
            <div class="stat-sub-label">Guarantee used</div>
        </div>
        <div class="stat-cell">
            <div class="stat-label">First Sell Wins</div>
            <div class="stat-value green">{{ number_format($part['first_sell_wins'] ?? 0) }}</div>
            <div class="stat-sub-label">Guarantee used</div>
        </div>
        <div class="stat-cell">
            <div class="stat-label">ICTP Bidders</div>
            <div class="stat-value">{{ number_format($part['ictp_bidders'] ?? 0) }}</div>
            <div class="stat-sub-label">{{ $periodSuffix }}</div>
        </div>
        <div class="stat-cell">
            <div class="stat-label">ICTP Bids</div>
            <div class="stat-value">{{ number_format($part['ictp_bid_count'] ?? 0) }}</div>
            <div class="stat-sub-label">{{ $periodSuffix }}</div>
        </div>
    </div>

    {{-- CHARTS ROW 1: Daily Active Bidders + Win Rate Distribution --}}
    <div class="chart-row">
        <div class="chart-panel">
            <div class="chart-title">Daily Active Bidders <span class="text-dim">&bull; {{ $periodSuffix }}</span></div>
            <div class="chart-wrap h250"><canvas id="dailyBiddersChart"></canvas></div>
        </div>
        <div class="chart-panel">
            <div class="chart-title">Win Rate Distribution <span class="text-dim">&bull; Manual traders</span></div>
            <div class="chart-wrap h250"><canvas id="winRateDistChart"></canvas></div>
        </div>
    </div>

    {{-- CHARTS ROW 2: Capital + Profit Distribution (existing) --}}
    <div class="chart-row">
        <div class="chart-panel">
            <div class="chart-title">Capital Distribution</div>
            <div class="chart-wrap h250"><canvas id="capitalChart"></canvas></div>
        </div>
        <div class="chart-panel">
            <div class="chart-title">Profit Distribution</div>
            <div class="chart-wrap h250"><canvas id="profitChart"></canvas></div>
        </div>
    </div>

    {{-- TOP BIDDERS LEADERBOARD (AJAX interactive table) --}}
    <div class="section-header">
        <span class="section-label">Top Bidders Leaderboard</span>
        <span class="section-right">{{ $periodSuffix }} &bull; Manual traders only</span>
    </div>

    <div class="section-ajax" id="usersTableSection">
        {{-- Table controls --}}
        <div class="table-controls">
            <div class="table-controls-left">
                <input type="text"
                       class="table-search"
                       id="usersSearch"
                       placeholder="Search by username..."
                       value="{{ $currentSearch }}">
                <div class="row-count-wrap">
                    Showing
                    <select class="row-count-select" id="usersLimit">
                        @foreach ([10, 20, 50, 100] as $opt)
                            <option value="{{ $opt }}" {{ $currentLimit === $opt ? 'selected' : '' }}>{{ $opt }}</option>
                        @endforeach
                    </select>
                    per page
                </div>
            </div>
            <div class="table-controls-right">
                <a href="/nexus/api/users/export?start={{ $dateStart }}&end={{ $dateEnd }}&sort={{ $currentSort }}&dir={{ $currentDir }}{{ $currentSearch ? '&search=' . urlencode($currentSearch) : '' }}"
                   class="btn-export" id="usersExportBtn">EXPORT CSV</a>
            </div>
        </div>

        {{-- Table --}}
        <div class="data-table-wrap">
            <table class="data-table" id="usersTable">
                <thead>
                    <tr>
                        <th style="width: 40px;">#</th>
                        <th class="sortable {{ $currentSort === 'username' ? 'sort-active sort-' . $currentDir : '' }}" data-sort="username">
                            User
                            <span class="sort-indicator"><span class="sort-indicator-up"></span><span class="sort-indicator-down"></span></span>
                        </th>
                        <th class="col-right sortable {{ $currentSort === 'wins' ? 'sort-active sort-' . $currentDir : '' }}" data-sort="wins">
                            Wins
                            <span class="sort-indicator"><span class="sort-indicator-up"></span><span class="sort-indicator-down"></span></span>
                        </th>
                        <th class="col-right sortable {{ $currentSort === 'losses' ? 'sort-active sort-' . $currentDir : '' }}" data-sort="losses">
                            Losses
                            <span class="sort-indicator"><span class="sort-indicator-up"></span><span class="sort-indicator-down"></span></span>
                        </th>
                        <th class="col-right sortable {{ $currentSort === 'win_rate' ? 'sort-active sort-' . $currentDir : '' }}" data-sort="win_rate">
                            Win Rate
                            <span class="sort-indicator"><span class="sort-indicator-up"></span><span class="sort-indicator-down"></span></span>
                        </th>
                        <th class="col-right sortable {{ $currentSort === 'total_profit' ? 'sort-active sort-' . $currentDir : '' }}" data-sort="total_profit">
                            Profit
                            <span class="sort-indicator"><span class="sort-indicator-up"></span><span class="sort-indicator-down"></span></span>
                        </th>
                        <th class="col-right sortable {{ $currentSort === 'total_volume' ? 'sort-active sort-' . $currentDir : '' }}" data-sort="total_volume">
                            Volume
                            <span class="sort-indicator"><span class="sort-indicator-up"></span><span class="sort-indicator-down"></span></span>
                        </th>
                        <th class="col-right sortable {{ $currentSort === 'profit_percent' ? 'sort-active sort-' . $currentDir : '' }}" data-sort="profit_percent">
                            Profit %
                            <span class="sort-indicator"><span class="sort-indicator-up"></span><span class="sort-indicator-down"></span></span>
                        </th>
                        <th class="col-right">Bids</th>
                        <th class="col-right">ICTP</th>
                    </tr>
                </thead>
                <tbody id="usersTableBody">
                    @if (!empty($topBidders) && count($topBidders) > 0)
                        @foreach ($topBidders as $idx => $b)
                            @php
                                $pp = $b['profit_percent'] ?? 0;
                                $rowNum = (($currentPage - 1) * $currentLimit) + $idx + 1;
                            @endphp
                            <tr>
                                <td class="col-num">{{ str_pad($rowNum, 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['win_rate'] ?? 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">
                                    <span class="chip chip-sm {{ $pp >= 10 ? 'chip-error' : ($pp >= 7 ? 'chip-warning' : 'chip-completed') }}">{{ number_format($pp, 1) }}%</span>
                                </td>
                                <td class="col-right">{{ $b['total_bids'] ?? 0 }}</td>
                                <td class="col-right">{{ $b['ictp_bids'] ?? 0 }}</td>
                            </tr>
                        @endforeach
                    @else
                        <tr><td colspan="10"><div class="table-empty"><span class="table-empty-text">No bidder data for this period</span></div></td></tr>
                    @endif
                </tbody>
            </table>
        </div>

        {{-- Pagination --}}
        <div class="ajax-pagination" id="usersPagination">
            <button type="button" class="ajax-pagination-btn {{ $currentPage <= 1 ? 'disabled' : '' }}" id="usersPrev" {{ $currentPage <= 1 ? 'disabled' : '' }}>PREV</button>
            <span class="ajax-pagination-info">Page <em id="usersCurrentPage">{{ $currentPage }}</em> of <em id="usersTotalPages">{{ $topBiddersPages ?? 1 }}</em> &bull; <em id="usersTotalCount">{{ number_format($topBiddersTotal ?? 0) }}</em> users</span>
            <button type="button" class="ajax-pagination-btn {{ $currentPage >= ($topBiddersPages ?? 1) ? 'disabled' : '' }}" id="usersNext" {{ $currentPage >= ($topBiddersPages ?? 1) ? 'disabled' : '' }}>NEXT</button>
        </div>

        {{-- AJAX loading overlay --}}
        <div class="ajax-loading-overlay" id="usersLoading">
            <div class="ajax-loading-spinner">Loading <span class="loading-dot"></span></div>
        </div>
    </div>

    {{-- LOSS ACCUMULATION --}}
    @if (!empty($lossAccumulation) && count($lossAccumulation) > 0)
        <div class="section-header">
            <span class="section-label">Loss Accumulation</span>
            <span class="section-right">Users with consecutive losses > 0</span>
        </div>

        <div class="data-table-wrap">
            <table class="data-table" id="lossAccumTable">
                <thead><tr><th>User</th><th class="col-right">Consecutive Losses</th><th class="col-right">Total Wins</th><th class="col-right">Total Losses</th></tr></thead>
                <tbody>
                    @foreach ($lossAccumulation as $user)
                        <tr class="loss-accum-row">
                            <td><span class="user-link" onclick="nexus.showAuditTrail({{ $user['user_id'] ?? 0 }}, '{{ addslashes($user['username'] ?? '') }}')">{{ $user['username'] ?? 'User #' . ($user['user_id'] ?? '?') }}</span></td>
                            <td class="col-right text-red">{{ $user['consecutive_losses'] ?? 0 }}</td>
                            <td class="col-right text-green">{{ $user['total_wins'] ?? 0 }}</td>
                            <td class="col-right text-dim">{{ $user['total_losses'] ?? 0 }}</td>
                        </tr>
                    @endforeach
                </tbody>
            </table>
        </div>
        @if (count($lossAccumulation) > 15)
        <div class="ajax-pagination" id="lossAccumPagination">
            <button type="button" class="ajax-pagination-btn disabled" id="lossAccumPrev" onclick="nexus.paginateLossAccum(-1)" disabled>PREV</button>
            <span class="ajax-pagination-info">Page <em id="lossAccumCurrentPage">1</em> of <em id="lossAccumTotalPages">{{ ceil(count($lossAccumulation) / 15) }}</em> &bull; {{ count($lossAccumulation) }} users</span>
            <button type="button" class="ajax-pagination-btn" id="lossAccumNext" onclick="nexus.paginateLossAccum(1)">NEXT</button>
        </div>
        @endif
    @endif

    {{-- APPROACHING CAP --}}
    @if (!empty($approachingCap) && count($approachingCap) > 0)
        <div class="section-header">
            <span class="section-label">Approaching Monthly Cap</span>
            <span class="section-right">{{ count($approachingCap) }} users above 70%</span>
        </div>

        @foreach ($approachingCap as $user)
            <div class="alert-row {{ ($user['percent'] ?? 0) >= 95 ? 'critical' : '' }}">
                <span class="alert-prefix">{{ ($user['percent'] ?? 0) >= 95 ? 'CRIT' : 'WARN' }}</span>
                <span class="alert-text">
                    <span class="user-link" onclick="nexus.showAuditTrail({{ $user['user_id'] ?? 0 }}, '{{ addslashes($user['username'] ?? '') }}')">{{ $user['username'] ?? 'User #' . ($user['user_id'] ?? '?') }}</span>
                    &bull; {{ number_format($user['percent'] ?? 0, 1) }}% of cap
                    &bull; ${{ number_format($user['profit'] ?? 0, 2) }} / ${{ number_format($user['cap'] ?? 0, 2) }}
                </span>
            </div>
        @endforeach
    @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;


    /* ── Daily Active Bidders (line chart) ── */

    var dabCtx = document.getElementById('dailyBiddersChart');
    if (dabCtx) {
        var dabData = @json($dailyBidders ?? []);
        var dabLabels = dabData.map(function(r) { return r.label; });
        var dabCounts = dabData.map(function(r) { return r.count; });

        new Chart(dabCtx, {
            type: 'line',
            data: {
                labels: dabLabels,
                datasets: [{
                    label: 'Unique Bidders',
                    data: dabCounts,
                    borderColor: '#e8842a',
                    backgroundColor: 'rgba(232, 132, 42, 0.06)',
                    borderWidth: 1.5,
                    fill: true,
                    tension: 0.3,
                    pointRadius: dabLabels.length <= 14 ? 3 : 0,
                    pointBackgroundColor: '#e8842a',
                    pointHitRadius: 10,
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: { display: false },
                    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 }, stepSize: 1, callback: function(v) { return Number.isInteger(v) ? v : ''; } }, title: { display: true, text: 'Bidders', font: { size: 9 }, color: '#7a7a7a' } }
                }
            }
        });
    }


    /* ── Win Rate Distribution (histogram) ── */

    var wrdCtx = document.getElementById('winRateDistChart');
    if (wrdCtx) {
        var wrdData = @json($winRateDistribution ?? []);
        var wrdLabels = wrdData.map(function(r) { return r.label; });
        var wrdCounts = wrdData.map(function(r) { return r.count; });

        new Chart(wrdCtx, {
            type: 'bar',
            data: {
                labels: wrdLabels,
                datasets: [{
                    label: 'Users',
                    data: wrdCounts,
                    backgroundColor: function(ctx) {
                        var i = ctx.dataIndex;
                        if (i <= 1) return '#cc0000';
                        if (i <= 2) return '#ccaa00';
                        if (i <= 3) return '#999999';
                        return '#00aa00';
                    },
                    borderWidth: 0,
                    barThickness: 20,
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: { display: false },
                    tooltip: { backgroundColor: '#141414', borderColor: '#222222', borderWidth: 1, cornerRadius: 4 }
                },
                scales: {
                    x: { grid: { display: false }, ticks: { font: { size: 9 } }, title: { display: true, text: 'Win Rate', font: { size: 9 }, color: '#7a7a7a' } },
                    y: { grid: { color: '#222222', drawBorder: false }, ticks: { font: { size: 9 }, stepSize: 1, callback: function(v) { return Number.isInteger(v) ? v : ''; } } }
                }
            }
        });
    }


    /* ── Capital Distribution ── */

    var capitalCtx = document.getElementById('capitalChart');
    if (capitalCtx) {
        var capitalRaw = @json($capitalDistribution ?? []);
        var capitalLabels = capitalRaw.map(function(r) { return r.label; });
        var capitalCounts = capitalRaw.map(function(r) { return r.count; });

        new Chart(capitalCtx, {
            type: 'bar',
            data: { labels: capitalLabels, datasets: [{ label: 'Users', data: capitalCounts, backgroundColor: '#e8842a', borderWidth: 0, barThickness: 20 }] },
            options: { responsive: true, maintainAspectRatio: false, plugins: { legend: { display: false }, tooltip: { backgroundColor: '#141414', borderColor: '#222222', borderWidth: 1, cornerRadius: 4 } }, scales: { x: { grid: { display: false }, ticks: { font: { size: 9 } } }, y: { grid: { color: '#222222', drawBorder: false }, ticks: { font: { size: 9 }, stepSize: 1, callback: function(v) { return Number.isInteger(v) ? v : ''; } }, title: { display: true, text: 'Users', font: { size: 9 }, color: '#7a7a7a' } } } }
        });
    }


    /* ── Profit Distribution ── */

    var profitCtx = document.getElementById('profitChart');
    if (profitCtx) {
        var profitRaw = @json($profitDistribution ?? []);
        var profitLabels = profitRaw.map(function(r) { return r.label; });
        var profitCounts = profitRaw.map(function(r) { return r.count; });

        new Chart(profitCtx, {
            type: 'bar',
            data: { labels: profitLabels, datasets: [{ label: 'Users', data: profitCounts, backgroundColor: function(ctx) { var l = profitLabels[ctx.dataIndex] || ''; if (l.indexOf('10') !== -1) return '#cc0000'; if (l.indexOf('8') !== -1) return '#ccaa00'; return '#888888'; }, borderWidth: 0, barThickness: 16 }] },
            options: { responsive: true, maintainAspectRatio: false, plugins: { legend: { display: false }, tooltip: { backgroundColor: '#141414', borderColor: '#222222', borderWidth: 1, cornerRadius: 4 } }, scales: { x: { grid: { display: false }, ticks: { font: { size: 8 } }, title: { display: true, text: '% of Cap', font: { size: 9 }, color: '#7a7a7a' } }, y: { grid: { color: '#222222', drawBorder: false }, ticks: { font: { size: 9 }, stepSize: 1, callback: function(v) { return Number.isInteger(v) ? v : ''; } } } } }
        });
    }


    /* ── Month selector + Quick filters ── */

    nexus.initMonthSelector('monthSelector', '/nexus/users');
    nexus.initQuickFilters('/nexus/users');


    /* ── AJAX Users Table ── */

    nexus.initUsersTable({
        start: @json($dateStart),
        end: @json($dateEnd),
        month: @json(request()->input('month', '')),
        sort: @json($currentSort),
        dir: @json($currentDir),
        search: @json($currentSearch),
        limit: {{ $currentLimit }},
        page: {{ $currentPage }},
        totalPages: {{ $topBiddersPages ?? 1 }},
    });

});
</script>
@endsection
