@php
    $pubRoundLabels = [];
    foreach ($knockoutData as $r => $ms) {
        $cnt = count($ms);
        $pubRoundLabels[$r] = match(true) {
            $cnt === 1 => 'Final',
            $cnt === 2 => 'Semi Final',
            $cnt === 4 => 'Perempat Final',
            default    => 'Babak ' . $r,
        };
    }
    $pubBaseCount = !empty($knockoutData) ? count(array_values($knockoutData)[0]) : 8;
@endphp

@if(!empty($knockoutData))

{{-- ═══════════ MOBILE LIST VIEW (< 768px) ═══════════ --}}
<div class="ko-mobile-list d-md-none">
    @foreach($knockoutData as $roundNum => $matches)
    @php
        $isLastR = $roundNum == array_key_last($knockoutData);
        $rCount  = count($matches);
    @endphp
    <div class="mb-3">
        {{-- Round header --}}
        <div style="display:flex;align-items:center;gap:8px;margin-bottom:8px">
            <div style="height:2px;flex:1;background:{{ $isLastR?'#1d4ed8':'#e2e8f0' }}"></div>
            <span style="font-size:11px;font-weight:700;color:{{ $isLastR?'#1d4ed8':'#64748b' }};text-transform:uppercase;letter-spacing:.07em;white-space:nowrap">
                {{ $pubRoundLabels[$roundNum] }}{{ $isLastR?' 🏆':'' }}
            </span>
            <div style="height:2px;flex:1;background:{{ $isLastR?'#1d4ed8':'#e2e8f0' }}"></div>
        </div>
        {{-- Matches --}}
        <div style="display:flex;flex-direction:column;gap:8px">
        @foreach($matches as $m)
        @php
            $seriesLegsM = $m->relationLoaded('seriesLegs') ? $m->seriesLegs : collect([$m]);
            $mBo2 = 1; $mBan2 = 0;
            if (isset($tournament)) {
                $mIsFinal2 = ($rCount === 1);
                $mBo2  = $tournament->getBoForPhase($mIsFinal2 ? 'final' : 'knockout');
                $mBan2 = $tournament->getBanCountForPhase($mIsFinal2 ? 'final' : 'knockout');
            }
            $compLegs2 = $seriesLegsM->where('status','completed');
            $pendL2    = $seriesLegsM->where('status','pending')->sortBy('leg_number')->first();
            $isDoneM   = ($m->status==='completed' || ($pendL2===null && $m->player1_id && $m->player2_id && $m->winner_id));
            $banRecM   = $m->relationLoaded('seriesBanRecords') ? $m->seriesBanRecords : collect();
            $lwbM      = $seriesLegsM->map(fn($l)=>[
                'leg'=>$l->leg_number,'score1'=>$l->score1??0,'score2'=>$l->score2??0,
                'winner_id'=>$l->winner_id,'is_draw'=>$l->is_draw,'is_gg'=>$l->is_golden_goal,
                'club1'=>$l->club1?['name'=>$l->club1->name,'logo'=>$l->club1->logo_url,'overall'=>$l->club1->overall]:null,
                'club2'=>$l->club2?['name'=>$l->club2->name,'logo'=>$l->club2->logo_url,'overall'=>$l->club2->overall]:null,
                'bans_p1'=>$banRecM->where('player_id',$m->player1_id)->filter(fn($b)=>$b->leg_number===$l->leg_number||$b->leg_number===null)->map(fn($b)=>['name'=>$b->club?->name??'?','logo'=>$b->club?->logo_url??''])->values()->toArray(),
                'bans_p2'=>$banRecM->where('player_id',$m->player2_id)->filter(fn($b)=>$b->leg_number===$l->leg_number||$b->leg_number===null)->map(fn($b)=>['name'=>$b->club?->name??'?','logo'=>$b->club?->logo_url??''])->values()->toArray(),
            ])->values()->toArray();
            $bp1M = $banRecM->where('player_id',$m->player1_id)->map(fn($b)=>['name'=>$b->club?->name??'?','logo'=>$b->club?->logo_url??'','leg'=>$b->leg_number])->values()->toArray();
            $bp2M = $banRecM->where('player_id',$m->player2_id)->map(fn($b)=>['name'=>$b->club?->name??'?','logo'=>$b->club?->logo_url??'','leg'=>$b->leg_number])->values()->toArray();
            $aggS1M = $compLegs2->sum('score1'); $aggS2M = $compLegs2->sum('score2');
            $wS1M   = $compLegs2->filter(fn($l)=>$l->winner_id===$m->player1_id)->count();
            $wS2M   = $compLegs2->filter(fn($l)=>$l->winner_id===$m->player2_id)->count();
        @endphp
        <div class="pes-card" style="overflow:hidden;{{ $isDoneM?'cursor:pointer':'' }}"
             @if($isDoneM) onclick="showMatchDetail({{ json_encode(['id'=>$m->id,'round'=>$pubRoundLabels[$roundNum],'p1'=>$m->player1?->username??'TBD','p2'=>$m->player2?->username??'TBD','p1avatar'=>$m->player1?->avatar??'','p2avatar'=>$m->player2?->avatar??'','winner'=>$m->winner?->username??'','winner_id'=>$m->winner_id,'p1_id'=>$m->player1_id,'p2_id'=>$m->player2_id,'bans_p1'=>$bp1M,'bans_p2'=>$bp2M,'legs'=>$lwbM]) }})" @endif>
            {{-- Player rows --}}
            @foreach([[$m->player1_id,$m->player1,$m->score1,'p1'],[$m->player2_id,$m->player2,$m->score2,'p2']] as [$pid,$player,$score,$side])
            @php
                $isW=$m->winner_id&&$m->winner_id===$pid; $isTbd=!$pid;
                // For multi-leg: show leg wins instead of goal score
                $dispScore = $m->status==='completed'
                    ? ($compLegs2->count() > 1 ? ($side==='p1' ? $wS1M : $wS2M) : ($score??0))
                    : '';
            @endphp
            <div style="display:flex;align-items:center;gap:10px;padding:10px 14px;{{ !$loop->last?'border-bottom:1px solid #f1f5f9':'' }};{{ $isW?'background:#f0fdf4':'' }}">
                @if(!$isTbd)
                <img src="{{ $player?->avatar ?? 'https://ui-avatars.com/api/?name='.urlencode($player?->username??'?').'&background=1d4ed8&color=fff&size=64' }}"
                     style="width:28px;height:28px;border-radius:8px;object-fit:cover;flex-shrink:0" alt="">
                @else
                <div style="width:28px;height:28px;border-radius:8px;background:#f1f5f9;flex-shrink:0"></div>
                @endif
                <span style="flex:1;font-size:13px;font-weight:{{ $isW?700:($isTbd?400:500) }};color:{{ $isTbd?'#94a3b8':($isW?'#15803d':'#0f172a') }};overflow:hidden;text-overflow:ellipsis;white-space:nowrap">
                    {{ $isTbd?'TBD':($player?->username??'?') }}{{ $isW?' 🏆':'' }}
                </span>
                <span style="font-size:15px;font-weight:900;color:{{ $isW?'#15803d':'#94a3b8' }};min-width:20px;text-align:right;flex-shrink:0;font-family:'Plus Jakarta Sans',sans-serif">
                    {{ $dispScore }}
                </span>
            </div>
            @endforeach
            {{-- Footer badges --}}
            @if($mBo2>1||$mBan2>0||$compLegs2->count()>1)
            <div style="padding:5px 14px 6px;background:#f8fafc;display:flex;align-items:center;gap:6px;flex-wrap:wrap">
                @if($mBo2>1)
                <span style="font-size:9px;font-weight:700;color:#7c3aed;background:#f3e8ff;padding:2px 7px;border-radius:20px">BO{{ $mBo2 }}</span>
                @endif
                @if($mBan2>0)
                <span style="font-size:9px;font-weight:700;color:#dc2626;background:#fff5f5;padding:2px 7px;border-radius:20px">Ban {{ $mBan2 }}</span>
                @endif
                @if($compLegs2->count()>1&&$m->status==='completed')
                <span style="font-size:9px;color:#64748b">W {{ $wS1M }}–{{ $wS2M }} · Agg {{ $aggS1M }}–{{ $aggS2M }}</span>
                @endif
                @if($isDoneM)
                <span style="margin-left:auto;font-size:10px;color:#64748b;font-style:italic">Tap detail</span>
                @endif
            </div>
            @endif
        </div>
        @endforeach
        </div>
    </div>
    @endforeach
</div>

{{-- ═══════════ DESKTOP BRACKET VIEW (≥ 768px) ═══════════ --}}
<div class="ko-desktop-bracket d-none d-md-block">
{{-- Swipe hint (tablet only) --}}
<div class="pub-bracket-swipe-hint d-none d-md-flex d-lg-none align-items-center justify-content-end gap-2 mb-1 pe-1"
     style="font-size:11px;color:#94a3b8;font-weight:600">
    <i class="ti ti-arrows-left-right" style="font-size:13px"></i> Geser untuk melihat bracket
</div>
<div class="pes-card" style="overflow-x:auto;-webkit-overflow-scrolling:touch;" id="pub-bracket-container">
<div id="pub-bracket-wrap"
     style="display:flex;gap:0;align-items:stretch;padding:12px 12px 16px;position:relative;width:max-content;min-width:100%">

@foreach($knockoutData as $roundNum => $matches)
@php
    $pubIsLast  = $roundNum == array_key_last($knockoutData);
    $pubCount   = count($matches);
    $pubConnW   = $pubIsLast ? 0 : 28;
@endphp

<div class="pub-ko-round" data-round="{{ $roundNum }}"
     style="display:flex;flex-direction:column;width:clamp(160px,42vw,216px);flex-shrink:0;margin-right:{{ $pubConnW }}px">

    {{-- Round label --}}
    <div style="text-align:center;font-size:10px;font-weight:700;color:#64748b;text-transform:uppercase;
                letter-spacing:.07em;padding-bottom:10px;
                border-bottom:2px solid {{ $pubIsLast ? '#1d4ed8' : '#e2e8f0' }};
                margin-bottom:8px;flex-shrink:0">
        {{ $pubRoundLabels[$roundNum] }}
        @if($pubIsLast)<span style="font-size:14px;margin-left:3px">🏆</span>@endif
    </div>

    {{-- Match slots --}}
    <div style="flex:1;display:flex;flex-direction:column;justify-content:space-around">
    @foreach($matches as $m)
    @php
        $seriesLegs = $m->relationLoaded('seriesLegs') ? $m->seriesLegs : collect([$m]);
        $mBo = 1; $mBan = 0;
        if (isset($tournament)) {
            $mIsFinal = ($pubCount === 1);
            $mPhase   = $mIsFinal ? 'final' : 'knockout';
            $mBo      = $tournament->getBoForPhase($mPhase);
            $mBan     = $tournament->getBanCountForPhase($mPhase);
        }
        $completedLegs = $seriesLegs->where('status','completed');
        $pendingLeg    = $seriesLegs->where('status','pending')->sortBy('leg_number')->first();
        $legLabel      = $pendingLeg ? 'Leg '.$pendingLeg->leg_number : '';
        $isCompleted   = ($m->status === 'completed' || ($pendingLeg === null && $m->player1_id && $m->player2_id && $m->winner_id));
    @endphp

    <div class="pub-ko-slot" data-round="{{ $roundNum }}" data-idx="{{ $loop->index }}"
         style="display:flex;align-items:center;padding:4px 0">

        {{-- Match card --}}
        @php
            $banRec = $m->relationLoaded('seriesBanRecords') ? $m->seriesBanRecords : collect();
            // Build per-leg ban data for the modal
            $legsWithBans = $seriesLegs->map(fn($l) => [
                'leg'      => $l->leg_number,
                'score1'   => $l->score1??0,
                'score2'   => $l->score2??0,
                'winner_id'=> $l->winner_id,
                'is_draw'  => $l->is_draw,
                'is_gg'    => $l->is_golden_goal,
                'club1'    => $l->club1 ? ['name'=>$l->club1->name,'logo'=>$l->club1->logo_url,'overall'=>$l->club1->overall] : null,
                'club2'    => $l->club2 ? ['name'=>$l->club2->name,'logo'=>$l->club2->logo_url,'overall'=>$l->club2->overall] : null,
                'bans_p1'  => $banRec->where('player_id',$m->player1_id)
                                ->filter(fn($b)=> $b->leg_number === $l->leg_number || $b->leg_number === null)
                                ->map(fn($b)=>['name'=>$b->club?->name??'?','logo'=>$b->club?->logo_url??''])
                                ->values()->toArray(),
                'bans_p2'  => $banRec->where('player_id',$m->player2_id)
                                ->filter(fn($b)=> $b->leg_number === $l->leg_number || $b->leg_number === null)
                                ->map(fn($b)=>['name'=>$b->club?->name??'?','logo'=>$b->club?->logo_url??''])
                                ->values()->toArray(),
            ])->values()->toArray();
            // Aggregate bans (all legs combined) for the summary header
            $bansP1r = $banRec->where('player_id',$m->player1_id)->map(fn($b)=>['name'=>$b->club?->name??'?','logo'=>$b->club?->logo_url??'','leg'=>$b->leg_number])->values()->toArray();
            $bansP2r = $banRec->where('player_id',$m->player2_id)->map(fn($b)=>['name'=>$b->club?->name??'?','logo'=>$b->club?->logo_url??'','leg'=>$b->leg_number])->values()->toArray();
        @endphp
        <div class="pub-ko-card"
             style="flex:1;background:#fff;
                    border:1.5px solid {{ $isCompleted?'#bfdbfe':($m->player1_id&&$m->player2_id?'#e2e8f0':'#f1f5f9') }};
                    border-radius:10px;overflow:hidden;box-shadow:0 1px 4px rgba(15,23,42,.05);
                    {{ $isCompleted ? 'cursor:pointer;transition:box-shadow .15s' : '' }}"
             @if($isCompleted)
             onclick="showMatchDetail({{ json_encode([
                 'id'       => $m->id,
                 'round'    => $pubRoundLabels[$roundNum],
                 'p1'       => $m->player1?->username ?? 'TBD',
                 'p2'       => $m->player2?->username ?? 'TBD',
                 'p1avatar' => $m->player1?->avatar ?? '',
                 'p2avatar' => $m->player2?->avatar ?? '',
                 'winner'   => $m->winner?->username ?? '',
                 'winner_id'=> $m->winner_id,
                 'p1_id'    => $m->player1_id,
                 'p2_id'    => $m->player2_id,
                 'bans_p1'  => $bansP1r,
                 'bans_p2'  => $bansP2r,
                 'legs'     => $legsWithBans,
             ]) }})"
             onmouseover="this.style.boxShadow='0 4px 14px rgba(15,23,42,.1)'"
             onmouseout="this.style.boxShadow='0 1px 4px rgba(15,23,42,.05)'"
             title="Klik untuk detail"
             @endif>

            {{-- Players --}}
            @php
                $dispS1 = $m->score1;
                $dispS2 = $m->score2;
                if ($completedLegs->count() > 1) {
                    $dispS1 = $completedLegs->filter(fn($l)=>$l->winner_id===$m->player1_id)->count();
                    $dispS2 = $completedLegs->filter(fn($l)=>$l->winner_id===$m->player2_id)->count();
                }
            @endphp
            @foreach([[$m->player1_id,$m->player1,$dispS1],[$m->player2_id,$m->player2,$dispS2]] as [$pid,$player,$score])
            @php $isWin=$m->winner_id&&$m->winner_id===$pid; $isTbd=!$pid; @endphp
            <div style="display:flex;align-items:center;gap:6px;padding:7px 8px;
                        {{ !$loop->last?'border-bottom:1px solid #f1f5f9':'' }};
                        {{ $isWin?'background:#f0fdf4':'' }}">
                @if(!$isTbd)
                <img src="{{ $player?->avatar ?? 'https://ui-avatars.com/api/?name='.urlencode($player?->username??'?').'&background=1d4ed8&color=fff&size=64' }}"
                     style="width:20px;height:20px;border-radius:5px;object-fit:cover;flex-shrink:0" alt="">
                @else
                <div style="width:20px;height:20px;border-radius:5px;background:#f1f5f9;flex-shrink:0"></div>
                @endif
                <span style="flex:1;font-size:11px;font-weight:{{ $isWin?700:($isTbd?400:500) }};
                             color:{{ $isTbd?'#94a3b8':($isWin?'#15803d':'#0f172a') }};
                             overflow:hidden;text-overflow:ellipsis;white-space:nowrap">
                    {{ $isTbd?'TBD':($player?->username??'?') }}{{ $isWin?' 🏆':'' }}
                </span>
                <span style="font-size:12px;font-weight:800;color:{{ $isWin?'#15803d':'#94a3b8' }};min-width:14px;text-align:right;flex-shrink:0">
                    {{ $m->status==='completed'?($score??0):'' }}
                </span>
            </div>
            @endforeach

            {{-- BO/Ban/Aggregate footer --}}
            @if($mBo>1||$mBan>0||$completedLegs->count()>1)
            @php
                $aggS1 = $completedLegs->sum('score1');
                $aggS2 = $completedLegs->sum('score2');
                $wS1   = $completedLegs->filter(fn($l)=>$l->winner_id===$m->player1_id)->count();
                $wS2   = $completedLegs->filter(fn($l)=>$l->winner_id===$m->player2_id)->count();
            @endphp
            <div style="padding:3px 7px;background:#f8fafc;border-top:1px solid #f1f5f9;display:flex;align-items:center;gap:4px;flex-wrap:wrap">
                @if($mBo>1)
                <span style="font-size:9px;font-weight:700;color:#7c3aed;background:#f3e8ff;padding:1px 5px;border-radius:20px;white-space:nowrap">
                    BO{{ $mBo }}{{ $legLabel?' · '.$legLabel:'' }}
                </span>
                @endif
                @if($mBan>0)
                <span style="font-size:9px;font-weight:700;color:#dc2626;background:#fff5f5;padding:1px 5px;border-radius:20px;white-space:nowrap">
                    Ban {{ $mBan }}
                </span>
                @endif
                @if($completedLegs->count()>1&&$m->status==='completed')
                <span style="font-size:9px;color:#64748b;white-space:nowrap">
                    W {{ $wS1 }}–{{ $wS2 }} · Agg {{ $aggS1 }}–{{ $aggS2 }}
                </span>
                @endif
            </div>
            @endif

        </div>{{-- end pub-ko-card --}}
    </div>{{-- end pub-ko-slot --}}
    @endforeach
    </div>{{-- end justify-content --}}

</div>{{-- end pub-ko-round --}}
@endforeach

</div>{{-- end bracket wrap --}}
</div>{{-- end card --}}
</div>{{-- end ko-desktop-bracket --}}

@else
<div class="pes-card p-5 text-center">
    <div style="font-size:36px;margin-bottom:10px">🏆</div>
    <div style="font-size:14px;font-weight:700;color:#0f172a;margin-bottom:4px">Bracket Knockout belum tersedia</div>
    @if(isset($tournament)&&$tournament->format==='group_knockout')
    <div style="font-size:13px;color:#64748b">Akan muncul setelah fase grup selesai.</div>
    @else
    <div style="font-size:13px;color:#64748b">Turnamen belum dimulai.</div>
    @endif
</div>
@endif

{{-- Modal & JS moved to show.blade.php (must be outside hidden sections) --}}

@push('scripts')
<script>
/* ── Public bracket connector ── */
function drawPubConnectors() {
    var wrap = document.getElementById('pub-bracket-wrap');
    if (!wrap) return;
    wrap.querySelectorAll('.pub-ko-svg').forEach(function(e){ e.remove(); });
    var rounds = wrap.querySelectorAll('.pub-ko-round');
    if (rounds.length < 2) return;
    var wRect = wrap.getBoundingClientRect();
    var svg = document.createElementNS('http://www.w3.org/2000/svg','svg');
    svg.classList.add('pub-ko-svg');
    svg.setAttribute('style','position:absolute;top:0;left:0;width:100%;height:100%;pointer-events:none;overflow:visible;z-index:0');
    wrap.insertBefore(svg, wrap.firstChild);
    for (var ri = 0; ri < rounds.length - 1; ri++) {
        var col = rounds[ri];
        var slots = col.querySelectorAll('.pub-ko-slot');
        var nextRound = rounds[ri + 1];
        var nextSlots = nextRound.querySelectorAll('.pub-ko-slot');
        for (var si = 0; si < slots.length; si += 2) {
            var sA = slots[si], sB = slots[si+1];
            var sN = nextSlots[Math.floor(si/2)];
            if (!sA || !sN) continue;
            var cA = sA.querySelector('.pub-ko-card');
            var cB = sB ? sB.querySelector('.pub-ko-card') : null;
            var cN = sN.querySelector('.pub-ko-card');
            if (!cA || !cN) continue;
            var rA = cA.getBoundingClientRect(), rB = cB ? cB.getBoundingClientRect() : rA;
            var rN = cN.getBoundingClientRect();
            var yA = rA.top - wRect.top + rA.height/2;
            var yB = cB ? (rB.top - wRect.top + rB.height/2) : yA;
            var yN = rN.top - wRect.top + rN.height/2;
            var xR  = rA.right - wRect.left;
            var xNL = rN.left  - wRect.left;
            var xM  = xR + (xNL - xR)/2;
            var yM  = (yA + yB) / 2;
            var d = 'M'+xR+','+yA+' L'+xM+','+yA+' L'+xM+','+yM
                  + (cB ? (' M'+xR+','+yB+' L'+xM+','+yB+' L'+xM+','+yM) : '')
                  + ' M'+xM+','+yM+' L'+xNL+','+yN;
            var p = document.createElementNS('http://www.w3.org/2000/svg','path');
            p.setAttribute('d',d);
            p.setAttribute('fill','none');
            p.setAttribute('stroke','#cbd5e1');
            p.setAttribute('stroke-width','1.5');
            p.setAttribute('stroke-linecap','round');
            p.setAttribute('stroke-linejoin','round');
            svg.appendChild(p);
        }
    }
}
window.addEventListener('load', function(){ setTimeout(drawPubConnectors,200); });

/* ── Swipe hint: hide after first scroll ── */
(function(){
    var container = document.getElementById('pub-bracket-container');
    var hint = document.querySelector('.pub-bracket-swipe-hint');
    if (!container || !hint) return;
    var hidden = false;
    container.addEventListener('scroll', function() {
        if (!hidden && container.scrollLeft > 10) {
            hidden = true;
            hint.style.transition = 'opacity .3s';
            hint.style.opacity = '0';
            setTimeout(function(){ hint.style.display = 'none'; }, 320);
        }
    }, { passive: true });
    /* Redraw connectors on scroll (SVG positions shift) */
    var scrollTimer;
    container.addEventListener('scroll', function(){
        clearTimeout(scrollTimer);
        scrollTimer = setTimeout(drawPubConnectors, 80);
    }, { passive: true });
})();
</script>
@endpush
