@extends('auth.master')

@section('auth-content')
    <style>
        body {
            background: #ffffff;
            color: #f8f9fa;
        }

        .live-wrap {
            min-height: 80vh;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .live-card {
            width: 920px;
            max-width: 96vw;
            border-radius: .8rem;
            box-shadow: 0 1rem 2rem rgba(0, 0, 0, .35);
        }

        .muted {
            color: #6c757d;
        }

        .athlete-photo {
            width: 96px;
            height: 96px;
            object-fit: cover;
            border-radius: .5rem;
            background: #1a2235;
        }

        .score-pill {
            font-size: 1.05rem;
            background: #131b2c;
            border: 1px solid #223055;
            border-radius: .5rem;
            padding: .35rem .6rem;
            min-width: 5.25rem;
            text-align: center;
        }

        .score-val {
            font-weight: 700;
            font-size: 1.35rem;
        }

        .waiting {
            text-align: center;
            padding: 3rem 1rem;
        }

        .badge-apparatus {
            background: #2b3a67;
        }

        .spinner {
            width: 3rem;
            height: 3rem;
            border: .35rem solid rgba(255, 255, 255, .15);
            border-top-color: #ffc107;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin: 0 auto 1rem;
        }

        @keyframes spin {
            to {
                transform: rotate(360deg);
            }
        }
    </style>

    <div class="container-fluid live-wrap">
        <div class="live-card bg-white p-4 w-100">
            <div class="d-flex justify-content-between align-items-center flex-wrap">
                <div>
                    <div class="h4 mb-1">{{ $competition->name }}</div>
                    <div class="muted">
                        Live —
                        @if (isset($apparatus) && $apparatus)
                            <span class="badge badge-apparatus">{{ $apparatus->name }}</span>
                        @else
                            <span class="badge badge-apparatus">All Apparatuses</span>
                        @endif
                        @if (!empty($judgeId))
                            <span class="ml-2">(Judge #{{ $judgeId }})</span>
                        @endif
                    </div>
                </div>
                <div class="muted" id="clock"></div>
            </div>

            <hr class="border-secondary">

            <div id="stage" aria-live="polite" aria-busy="true">
                <div class="waiting">
                    <div class="spinner" role="status" aria-label="Loading"></div>
                    <div class="display-4">Waiting for scores…</div>
                    <div class="muted mt-2">Stand by for the next athlete. This screen updates automatically.</div>
                </div>
            </div>
        </div>
    </div>

    <script>
        (function() {
            const competitionId = @json($competition->id);
            const apparatusId = @json($apparatusId); // 'all' or numeric
            const judgeId = @json($judgeId);
            const cycleSeconds = @json($cycleDuration ?? 10);

            // Build feed URL that supports 'all' or numeric apparatus id
            const feedUrl = new URL(@json(route('public.leaderboard.live.feed', ['competitionId' => $competition->id, 'apparatusId' => $apparatusId])));
            if (judgeId) feedUrl.searchParams.set('judge_id', judgeId);

            let queue = []; // unseen items to play
            let displayed = new Set(); // prevent repeats within this session
            let lastSeenISO = null; // cursor for incremental fetch
            let playing = false;

            // Clock (top-right)
            setInterval(() => {
                const el = document.getElementById('clock');
                if (el) el.textContent = new Date().toLocaleTimeString();
            }, 1000);

            // Poll for new items every 5s
            async function poll() {
                try {
                    if (lastSeenISO) feedUrl.searchParams.set('since', lastSeenISO);
                    const res = await fetch(feedUrl.toString(), {
                        cache: 'no-store'
                    });
                    if (!res.ok) throw new Error('feed error');
                    const data = await res.json();

                    (data.items || []).forEach(it => {
                        if (!displayed.has(it.id)) queue.push(it);
                    });

                    // Advance cursor regardless (robust against empty arrays)
                    lastSeenISO = data.serverNow || lastSeenISO;

                    if (!playing) playNext();
                } catch (e) {
                    /* silent retry */ }
            }

            function svgAvatar(name) {
                const initials = (name || 'A').split(' ').filter(Boolean).slice(0, 2).map(w => w[0].toUpperCase()).join(
                    '');
                const svg = `<svg xmlns='http://www.w3.org/2000/svg' width='96' height='96' role='img' aria-label='${initials}'>
      <rect width='100%' height='100%' fill='#0000'/>
      <text x='50%' y='52%' text-anchor='middle' dominant-baseline='middle'
            font-family='Arial, Helvetica, sans-serif' font-weight='700' font-size='34' fill='#6c757d'>${initials}</text>
    </svg>`;
                return 'data:image/svg+xml;charset=UTF-8,' + encodeURIComponent(svg);
            }

            function avatarImg(athleteName, photoUrl) {
                const fallback = svgAvatar(athleteName);
                const src = photoUrl || fallback; // ✅ use URL from backend
                return `
    <img
      src="${src}"
      onerror="this.onerror=null;this.src='${fallback}';"
      class="athlete-photo mr-3"
      alt="${athleteName || 'Athlete'}"
      width="96"
      height="96"
    >
  `;
            }


            function num(v) {
                return (v === null || v === undefined || isNaN(v)) ? '—' : Number(v).toFixed(2);
            }

            function cardHTML(it) {
                let medal = '';
                if (it.rank === 1) medal = '🥇';
                else if (it.rank === 2) medal = '🥈';
                else if (it.rank === 3) medal = '🥉';

                return `
    <div class="d-flex align-items-center mb-3">
      ${avatarImg(it.athlete_name, it.photo_url)}
      <div class="flex-fill">
        <div class="h3 mb-0">
          ${it.athlete_name} ${medal}
        </div>
        <div class="muted">${it.club_name || ''}</div>
      </div>
      <div class="text-right">
        <div class="muted" style="font-size:.9rem;">
          Submitted: ${new Date(it.created_at).toLocaleTimeString()}
        </div>
      </div>
    </div>

    <div class="d-flex flex-wrap">
      <div class="score-pill mr-2 mb-2">D<br><span class="score-val">${num(it.d_score)}</span></div>
      <div class="score-pill mr-2 mb-2">E<br><span class="score-val">${num(it.e_score)}</span></div>
      <div class="score-pill mr-2 mb-2">ND<br><span class="score-val">${num(it.nd)}</span></div>
      <div class="score-pill mr-2 mb-2">Penalty<br><span class="score-val">${num(it.penalty)}</span></div>
      <div class="score-pill mr-2 mb-2">Final<br><span class="score-val">${num(it.final_score)}</span></div>
    </div>
  `;
            }


            function showWaiting() {
                const stage = document.getElementById('stage');
                if (!stage) return;
                stage.innerHTML = `
      <div class="waiting">
        <div class="spinner" role="status" aria-label="Loading"></div>
        <div class="display-4">Waiting for scores…</div>
        <div class="muted mt-2">Stand by for the next athlete. This screen updates automatically.</div>
      </div>
    `;
            }

            function playNext() {
                playing = true;

                if (queue.length === 0) {
                    showWaiting();
                    playing = false;
                    return;
                }

                const it = queue.shift();
                displayed.add(it.id);

                const stage = document.getElementById('stage');
                if (stage) {
                    stage.innerHTML = `
        <div class="card bg-white border-0">
          <div class="card-body">
            ${cardHTML(it)}
          </div>
        </div>
      `;
                }
                setTimeout(() => {
                    playing = false;
                    playNext();
                }, cycleSeconds * 1000);
            }

            // Kick off
            poll();
            setInterval(poll, 5000);
        })();
    </script>
@endsection
