@extends('layouts.dashboard')

@section('title', 'Leaderboard')

@section('content')
    @php
        $pointName = site_setting('points_name', config('rewards.points_name'));
        $periods = ['daily' => 'Daily', 'weekly' => 'Weekly', 'monthly' => 'Monthly', 'all_time' => 'All time'];
    @endphp

    <main class="race-board" aria-labelledby="leaderboardTitle">
        <section class="race-hero">
            <div class="race-hero-top">
                <nav class="race-periods" aria-label="Leaderboard period">
                    @foreach($periods as $value => $label)
                        <a href="{{ route('user.leaderboard', ['period' => $value]) }}"
                           class="{{ $period === $value ? 'active' : '' }}"
                           @if($period === $value) aria-current="page" @endif>{{ $label }}</a>
                    @endforeach
                </nav>
                <span class="race-live-label"><i data-feather="activity" aria-hidden="true"></i>Live standings</span>
            </div>

            <div class="race-hero-copy">
                <span class="race-eyebrow">Top earners · {{ $periodLabel }}</span>
                @if($prizePool > 0)
                    <strong class="race-prize-value">{{ number_format($prizePool) }}</strong>
                    <h1 id="leaderboardTitle">{{ ucfirst($pointName) }} prize race</h1>
                    <p>Earn from approved offers to climb the standings and share the configured prize pool.</p>
                @else
                    <strong class="race-prize-value">Top {{ $limit }}</strong>
                    <h1 id="leaderboardTitle">Community leaderboard</h1>
                    <p>Complete approved offers, build your score, and move up the Basketloot league.</p>
                @endif
            </div>

            @if($periodEnd)
                <div class="race-countdown" data-race-end="{{ $periodEnd->toIso8601String() }}" aria-label="Time remaining in {{ strtolower($periodLabel) }}">
                    <div><strong data-race-days>00</strong><span>Days</span></div>
                    <div><strong data-race-hours>00</strong><span>Hours</span></div>
                    <div><strong data-race-minutes>00</strong><span>Minutes</span></div>
                    <div><strong data-race-seconds>00</strong><span>Seconds</span></div>
                </div>
            @endif
        </section>

        @if($topThree->isNotEmpty())
            <section class="race-podium" aria-label="Top three members">
                @foreach($topThree as $winner)
                    @php
                        $rank = $loop->iteration;
                        $recentLead = $winner->latestLead;
                        $publicName = $winner->username;
                        $publicAvatar = $winner->avatar();
                        $publicActivity = $winner->is_profile_private ? 'Profile activity is private' : ($recentLead?->offer_name ?: 'No public activity yet');
                        $leaderboardPoints = (float) ($winner->leaderboard_points ?? 0);
                    @endphp
                    <button class="race-podium-card rank-{{ $rank }}" type="button"
                            aria-label="View {{ $publicName }} leaderboard profile, rank {{ $rank }}"
                            data-bs-toggle="modal" data-bs-target="#memberProfileModal"
                            data-profile-url="{{ route('user.leaderboard.profile', $winner) }}"
                            data-name="{{ $publicName }}" data-avatar="{{ $publicAvatar }}" data-rank="{{ $rank }}"
                            data-points="{{ number_format($leaderboardPoints) }}" data-points-raw="{{ $leaderboardPoints }}"
                            data-total-points="{{ (float) $winner->total_points }}" data-total-coins="{{ number_format((float) $winner->total_points) }} coins"
                            data-total-usd="{{ format_coins_as_usd($winner->total_points) }}" data-private="{{ $winner->is_profile_private ? '1' : '0' }}"
                            data-completed="{{ $winner->leads_count }}" data-joined="Joined {{ $winner->created_at->format('M Y') }}"
                            data-activity="{{ $publicActivity }}"
                            data-activity-time="{{ $winner->is_profile_private ? 'Hidden' : ($recentLead?->created_at?->diffForHumans() ?: 'Not started') }}"
                            data-activity-reward="{{ $winner->is_profile_private ? '-' : number_format((float) ($recentLead?->credited_points ?? 0)) }}">
                        <span class="race-medal"><i data-feather="award" aria-hidden="true"></i>#{{ $rank }}</span>
                        <img src="{{ $publicAvatar }}" alt="" width="88" height="88">
                        <strong>{{ $publicName }}</strong>
                        <span>{{ number_format($leaderboardPoints) }} {{ $pointName }}</span>
                        <small>Total earned {{ format_coins_as_usd($winner->total_points) }} · {{ number_format($winner->total_points) }} coins</small>
                    </button>
                @endforeach
            </section>
        @endif

        <section class="race-standings" aria-labelledby="standingsTitle">
            <header class="race-section-header">
                <div>
                    <span class="race-eyebrow">Current standings</span>
                    <h2 id="standingsTitle">Leaderboard</h2>
                </div>
                <span class="loot-pill">{{ number_format($winners->total()) }} members</span>
            </header>

            <div class="race-table-wrap">
                <table class="race-table">
                    <thead>
                    <tr>
                        <th scope="col">Place</th>
                        <th scope="col">Member</th>
                        <th scope="col">{{ ucfirst($pointName) }}</th>
                        <th scope="col">Prize</th>
                        <th scope="col"><span class="visually-hidden">Profile</span></th>
                    </tr>
                    </thead>
                    <tbody>
                    @forelse($winners as $winner)
                        @php
                            $rank = ($winners->currentPage() - 1) * $winners->perPage() + $loop->iteration;
                            $recentLead = $winner->latestLead;
                            $publicName = $winner->username;
                            $publicAvatar = $winner->avatar();
                            $publicActivity = $winner->is_profile_private ? 'Profile activity is private' : ($recentLead?->offer_name ?: 'No public activity yet');
                            $leaderboardPoints = (float) ($winner->leaderboard_points ?? 0);
                        @endphp
                        <tr>
                            <td data-label="Place"><span class="race-rank">#{{ $rank }}</span></td>
                            <td data-label="Member">
                                <span class="race-member">
                                    <img src="{{ $publicAvatar }}" alt="" width="44" height="44" loading="lazy">
                                    <span><strong>{{ $publicName }}</strong><small>Total earned {{ format_coins_as_usd($winner->total_points) }} · {{ number_format($winner->total_points) }} coins</small></span>
                                </span>
                            </td>
                            <td data-label="{{ ucfirst($pointName) }}"><strong class="race-points">{{ number_format($leaderboardPoints) }}</strong></td>
                            <td data-label="Prize"><span class="race-prize">{{ isset($prizes[$rank]) ? number_format($prizes[$rank]).' '.$pointName : '—' }}</span></td>
                            <td>
                                <button class="race-profile-button" type="button"
                                        aria-label="View {{ $publicName }} leaderboard profile, rank {{ $rank }}"
                                        data-bs-toggle="modal" data-bs-target="#memberProfileModal"
                                        data-profile-url="{{ route('user.leaderboard.profile', $winner) }}"
                                        data-name="{{ $publicName }}" data-avatar="{{ $publicAvatar }}" data-rank="{{ $rank }}"
                                        data-points="{{ number_format($leaderboardPoints) }}" data-points-raw="{{ $leaderboardPoints }}"
                                        data-total-points="{{ (float) $winner->total_points }}" data-total-coins="{{ number_format((float) $winner->total_points) }} coins"
                                        data-total-usd="{{ format_coins_as_usd($winner->total_points) }}" data-private="{{ $winner->is_profile_private ? '1' : '0' }}"
                                        data-completed="{{ $winner->leads_count }}" data-joined="Joined {{ $winner->created_at->format('M Y') }}"
                                        data-activity="{{ $publicActivity }}"
                                        data-activity-time="{{ $winner->is_profile_private ? 'Hidden' : ($recentLead?->created_at?->diffForHumans() ?: 'Not started') }}"
                                        data-activity-reward="{{ $winner->is_profile_private ? '-' : number_format((float) ($recentLead?->credited_points ?? 0)) }}">
                                    <i data-feather="chevron-right" aria-hidden="true"></i>
                                </button>
                            </td>
                        </tr>
                    @empty
                        <tr><td colspan="5">
                            <div class="race-empty">
                                <span><i data-feather="award" aria-hidden="true"></i></span>
                                <h3>The race is ready</h3>
                                <p>No approved activity exists for this period yet. Complete an offer to take the first spot.</p>
                                <a class="btn btn-loot" href="{{ route('user.earn') }}">Browse offers</a>
                            </div>
                        </td></tr>
                    @endforelse
                    </tbody>
                </table>
            </div>

            @if($winners->hasPages())
                <div class="race-pagination">{{ $winners->links() }}</div>
            @endif
        </section>
    </main>

    <div class="modal fade loot-member-modal" id="memberProfileModal" tabindex="-1" aria-labelledby="memberProfileTitle" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <div>
                        <span class="modal-eyebrow">Leaderboard member</span>
                        <h2 class="modal-title" id="memberProfileTitle">Profile overview</h2>
                    </div>
                    <button type="button" class="btn-close loot-modal-close" data-bs-dismiss="modal" aria-label="Close profile"></button>
                </div>
                <div class="modal-body">
                    <div class="member-summary">
                        <div class="member-avatar"><img id="memberAvatar" src="" alt="" width="88" height="88"></div>
                        <div class="member-identity">
                            <h3 id="memberName"></h3>
                            <span id="memberJoined"></span>
                        </div>
                        <span class="member-rank-badge" id="memberRank">#1</span>
                    </div>

                    <div class="member-level">
                        <div><strong id="memberLevel">Level 1</strong><span id="memberNextLevel">1,000 to next level</span></div>
                        <div class="member-progress" role="progressbar" aria-label="Level progress" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0">
                            <span id="memberProgress"></span>
                        </div>
                    </div>

                    <div class="member-stat-grid" aria-label="Member statistics">
                        <div><span>Total earned</span><strong id="memberTotalUsd">$0.00</strong><small id="memberTotalCoins">0 {{ $pointName }}</small></div>
                        <div><span>Completed offers</span><strong id="memberCompleted">0</strong></div>
                        <div><span>League position</span><strong id="memberPosition">#1</strong></div>
                    </div>

                    <div class="activity-privacy-note" id="memberPrivacyNote" hidden>
                        <i data-feather="lock" aria-hidden="true"></i>
                        <div><strong>Activity is private</strong><span>This member shares their profile and total earnings, but keeps individual offers hidden.</span></div>
                    </div>
                    <section class="activity-history member-activity-history" id="memberActivityHistory" aria-labelledby="memberActivityTitle">
                        <div class="activity-history-head">
                            <span id="memberActivityTitle">Recent public activity</span>
                            <small id="memberActivityStatus" role="status" aria-live="polite">Loading…</small>
                        </div>
                        <div class="activity-history-list" id="memberActivityList"></div>
                    </section>
                </div>
            </div>
        </div>
    </div>
@endsection

@push('scripts')
    <script>
        (function () {
            const modal = document.getElementById('memberProfileModal');
            modal?.addEventListener('show.bs.modal', async function (event) {
                const trigger = event.relatedTarget;
                if (!trigger) return;

                const points = Number(trigger.getAttribute('data-total-points') || 0);
                const level = Math.max(1, Math.floor(points / 1000) + 1);
                const progress = Math.max(0, Math.min(100, (points % 1000) / 10));
                const remaining = progress === 0 && points > 0 ? 1000 : 1000 - (points % 1000);
                const rank = trigger.getAttribute('data-rank') || '1';
                const avatar = document.getElementById('memberAvatar');

                avatar.src = trigger.getAttribute('data-avatar') || '';
                avatar.alt = trigger.getAttribute('data-name') || 'Leaderboard member';
                document.getElementById('memberName').textContent = trigger.getAttribute('data-name') || 'Member';
                document.getElementById('memberJoined').textContent = trigger.getAttribute('data-joined') || '';
                document.getElementById('memberRank').textContent = `#${rank}`;
                document.getElementById('memberPosition').textContent = `#${rank}`;
                document.getElementById('memberTotalUsd').textContent = trigger.getAttribute('data-total-usd') || '$0.00';
                document.getElementById('memberTotalCoins').textContent = trigger.getAttribute('data-total-coins') || '0 coins';
                document.getElementById('memberCompleted').textContent = trigger.getAttribute('data-completed') || '0';
                document.getElementById('memberLevel').textContent = `Level ${level}`;
                document.getElementById('memberNextLevel').textContent = `${remaining.toLocaleString()} ${@json($pointName)} to next level`;
                document.getElementById('memberProgress').style.transform = `scaleX(${progress / 100})`;
                document.querySelector('.member-progress').setAttribute('aria-valuenow', Math.round(progress));
                const isPrivate = trigger.getAttribute('data-private') === '1';
                const privacyNote = document.getElementById('memberPrivacyNote');
                const history = document.getElementById('memberActivityHistory');
                const list = document.getElementById('memberActivityList');
                const status = document.getElementById('memberActivityStatus');
                privacyNote.hidden = !isPrivate;
                history.hidden = isPrivate;
                list.replaceChildren();
                status.textContent = isPrivate ? 'Private' : 'Loading…';

                const requestId = String(Date.now()) + Math.random();
                modal.dataset.activityRequest = requestId;

                try {
                    const response = await fetch(trigger.getAttribute('data-profile-url'), {
                        headers: {'Accept': 'application/json', 'X-Requested-With': 'XMLHttpRequest'}
                    });
                    if (!response.ok) throw new Error('Profile activity request failed');
                    const profile = await response.json();
                    if (modal.dataset.activityRequest !== requestId) return;

                    document.getElementById('memberTotalUsd').textContent = profile.total_usd || '$0.00';
                    document.getElementById('memberTotalCoins').textContent = profile.total_coins || '0 coins';
                    document.getElementById('memberCompleted').textContent = String(profile.completed_offers || 0);
                    privacyNote.hidden = !profile.private;
                    history.hidden = Boolean(profile.private);

                    if (profile.private) {
                        status.textContent = 'Private';
                        return;
                    }

                    (profile.activities || []).forEach(function (item) {
                        const row = document.createElement('div');
                        row.className = 'activity-history-item';
                        const copy = document.createElement('div');
                        const title = document.createElement('strong');
                        const meta = document.createElement('span');
                        const reward = document.createElement('b');
                        title.textContent = item.offer || 'Offer completed';
                        meta.textContent = (item.provider || 'Basketloot') + ' · ' + (item.time || 'Recently');
                        reward.textContent = item.usd || '$0.00';
                        copy.append(title, meta);
                        row.append(copy, reward);
                        list.append(row);
                    });

                    if (!profile.activities?.length) {
                        const empty = document.createElement('p');
                        empty.className = 'loot-muted mb-0 py-1';
                        empty.textContent = 'No public activity is available yet.';
                        list.append(empty);
                    }
                    status.textContent = `${profile.activities?.length || 0} recent`;
                } catch (error) {
                    if (modal.dataset.activityRequest !== requestId || isPrivate) return;
                    const failed = document.createElement('p');
                    failed.className = 'loot-muted mb-0 py-1';
                    failed.textContent = 'Activity could not be loaded. Please try again.';
                    list.append(failed);
                    status.textContent = 'Unavailable';
                }
            });

            const countdown = document.querySelector('[data-race-end]');
            if (!countdown) return;

            const end = new Date(countdown.dataset.raceEnd).getTime();
            const fields = {
                days: countdown.querySelector('[data-race-days]'),
                hours: countdown.querySelector('[data-race-hours]'),
                minutes: countdown.querySelector('[data-race-minutes]'),
                seconds: countdown.querySelector('[data-race-seconds]')
            };

            function updateCountdown() {
                const remaining = Math.max(0, end - Date.now());
                const totalSeconds = Math.floor(remaining / 1000);
                fields.days.textContent = String(Math.floor(totalSeconds / 86400)).padStart(2, '0');
                fields.hours.textContent = String(Math.floor((totalSeconds % 86400) / 3600)).padStart(2, '0');
                fields.minutes.textContent = String(Math.floor((totalSeconds % 3600) / 60)).padStart(2, '0');
                fields.seconds.textContent = String(totalSeconds % 60).padStart(2, '0');
            }

            updateCountdown();
            window.setInterval(updateCountdown, 1000);
        })();
    </script>
@endpush
