<x-app-layout>
    <x-slot name="title">Bracket — {{ $tournament->title }}</x-slot>

    @php
        $isGroupKO     = $tournament->format === 'group_knockout';
        $isLive        = in_array($tournament->status, ['in_progress','registration']);
        $phaseIsGroup  = $tournament->current_phase === 'group';
        $groupCount    = (int)($tournament->group_count ?? 4);
        $groupNames    = array_slice(range('A','Z'), 0, $groupCount);
        $participants  = $tournament->participants->load('user');
    @endphp

    <!-- ── Header ──────────────────────────────────────────────────────── -->
    <div class="d-flex align-items-start justify-content-between flex-wrap gap-3 mb-4">
        <div>
            <a href="{{ route('admin.tournaments') }}" style="font-size:12px;color:#64748b;text-decoration:none">
                <i class="ti ti-arrow-left"></i> Kembali
            </a>
            <div style="font-size:20px;font-weight:800;color:#0f172a;font-family:'Plus Jakarta Sans',sans-serif;margin-top:4px">
                <i class="ti ti-tournament" style="color:#1d4ed8"></i> {{ $tournament->title }}
            </div>
            <div style="font-size:12px;color:#64748b;margin-top:2px">
                {{ $isGroupKO ? 'Group + Knockout' : 'Knockout' }}
                · {{ $participants->count() }} Peserta
                @if($isGroupKO) · Fase: <strong>{{ ucfirst($tournament->current_phase) }}</strong> @endif
            </div>
        </div>
        <div class="d-flex gap-2 flex-wrap">
            <form method="POST" action="{{ route('admin.tournament.generate', $tournament->id) }}"
                  onsubmit="return confirm('Generate ulang bracket? Data lama akan dihapus.')">
                @csrf
                <button class="btn-pes-primary" style="font-size:12px">
                    <i class="ti ti-refresh"></i> <span class="d-none d-sm-inline">Generate</span>
                </button>
            </form>
            @if($isGroupKO && $phaseIsGroup)
            <form method="POST" action="{{ route('admin.tournament.advance', $tournament->id) }}"
                  onsubmit="return confirm('Lanjutkan ke fase Knockout?')">
                @csrf
                <button class="btn-pes-secondary" style="font-size:12px">
                    <i class="ti ti-player-skip-forward"></i> <span class="d-none d-sm-inline">Mulai Knockout</span>
                </button>
            </form>
            <form method="POST" action="{{ route('admin.tournament.checkTiebreakers', $tournament->id) }}">
                @csrf
                <button class="btn-pes-ghost" style="font-size:12px;border:1px solid #e2e8f0" title="Cek Tiebreaker">
                    <i class="ti ti-bolt" style="color:#ca8a04"></i> <span class="d-none d-md-inline">Cek Tiebreaker</span>
                </button>
            </form>
            @endif
        </div>
    </div>

    <!-- ── Tabs ─────────────────────────────────────────────────────────── -->
    @if($isGroupKO)
    <div class="d-flex gap-2 mb-4 flex-wrap">
        <button onclick="switchTab('draw')" id="tab-draw" class="btn-pes-primary" style="font-size:13px">
            <i class="ti ti-wheel"></i> Undian Grup
        </button>
        <button onclick="switchTab('group')" id="tab-group" class="btn-pes-secondary" style="font-size:13px">
            <i class="ti ti-layout-grid"></i> Fase Grup
        </button>
        <button onclick="switchTab('knockout')" id="tab-knockout" class="btn-pes-secondary" style="font-size:13px">
            <i class="ti ti-tournament"></i> Fase Knockout
        </button>
    </div>
    @else
    {{-- Knockout-only format: show draw tab + bracket tab --}}
    <div class="d-flex gap-2 mb-4 flex-wrap">
        <button onclick="switchTabKO('draw')" id="kotab-draw" class="btn-pes-primary" style="font-size:13px">
            <i class="ti ti-wheel"></i> Undian Bracket
        </button>
        <button onclick="switchTabKO('bracket')" id="kotab-bracket" class="btn-pes-secondary" style="font-size:13px">
            <i class="ti ti-tournament"></i> Bracket
        </button>
    </div>
    @endif

    <!-- ── BO/Ban Rules Summary ──────────────────────────────────────────── -->
    @php
        $boCfgBanner  = $tournament->bo_config  ?? [];
        $banCfgBanner = $tournament->ban_config ?? [];
        $bannerPhases = [];
        if ($isGroupKO) $bannerPhases['Grup']    = ['bo' => $boCfgBanner['group']    ?? 1, 'ban' => $banCfgBanner['group']    ?? 0];
        $bannerPhases['Knockout'] = ['bo' => $boCfgBanner['knockout'] ?? 1, 'ban' => $banCfgBanner['knockout'] ?? 0];
        $bannerPhases['Final']    = ['bo' => $boCfgBanner['final']    ?? 1, 'ban' => $banCfgBanner['final']    ?? 0];
        $showBanner = collect($bannerPhases)->contains(fn($v) => $v['bo'] > 1 || $v['ban'] > 0);
    @endphp
    @if($showBanner)
    <div style="background:#f8fafc;border:1.5px solid #e2e8f0;border-radius:12px;padding:12px 16px;margin-bottom:20px;display:flex;align-items:center;gap:12px;flex-wrap:wrap">
        <div style="font-size:11px;font-weight:700;color:#64748b;text-transform:uppercase;letter-spacing:.05em;flex-shrink:0">
            <i class="ti ti-clipboard-list"></i> Aturan Match
        </div>
        @foreach($bannerPhases as $phName => $cfg)
        <div style="display:flex;align-items:center;gap:6px;padding:4px 10px;background:#fff;border:1px solid #e2e8f0;border-radius:8px;flex-wrap:wrap">
            <span style="font-size:11px;font-weight:600;color:#64748b">{{ $phName }}:</span>
            <span style="font-size:11px;font-weight:700;color:#1d4ed8;background:#eff6ff;padding:1px 7px;border-radius:20px">
                <i class="ti ti-repeat"></i> BO{{ $cfg['bo'] }}
            </span>
            @if($cfg['ban'] > 0)
            <span style="font-size:11px;font-weight:700;color:#dc2626;background:#fff5f5;padding:1px 7px;border-radius:20px">
                <i class="ti ti-ban"></i> Ban {{ $cfg['ban'] }}
            </span>
            @endif
        </div>
        @endforeach
        {{-- Tiebreak indicator --}}
        @php $hasBO2 = collect($bannerPhases)->contains(fn($v)=>$v['bo']===2); @endphp
        @if($hasBO2)
        <div style="display:flex;align-items:center;gap:6px;padding:4px 10px;background:#fff;border:1px solid #e2e8f0;border-radius:8px">
            <span style="font-size:11px;font-weight:600;color:#64748b">Tiebreak:</span>
            @if($tournament->useAggregateTiebreak())
            <span style="font-size:11px;font-weight:700;color:#1d4ed8;background:#eff6ff;padding:1px 7px;border-radius:20px">⚽ Agregat</span>
            @else
            <span style="font-size:11px;font-weight:700;color:#854d0e;background:#fef9c3;padding:1px 7px;border-radius:20px">⚡ GG</span>
            @endif
        </div>
        @endif
    </div>
    @endif

    <!-- ══════════════════════════════════════ WHEEL DRAW SECTION -->
    @if($isGroupKO)
    <div id="section-draw">
        <div class="row g-4">
            <!-- LEFT: Wheel -->
            <div class="col-lg-5">
                <div class="pes-card p-4 text-center">
                    <div style="font-size:14px;font-weight:700;color:#0f172a;margin-bottom:4px">
                        <i class="ti ti-wheel" style="color:#7c3aed"></i> Roda Undian
                    </div>
                    <div style="font-size:12px;color:#64748b;margin-bottom:16px">
                        Putar untuk mengacak penempatan peserta ke grup
                    </div>

                    <!-- Wheel canvas -->
                    <div style="position:relative;display:inline-block;margin-bottom:16px;width:100%;max-width:300px">
                        <canvas id="wheel-canvas" width="300" height="300"
                                style="border-radius:50%;box-shadow:0 8px 32px rgba(15,23,42,.18);width:100%;height:auto"></canvas>
                        <!-- Pointer arrow -->
                        <div style="position:absolute;top:-12px;left:50%;transform:translateX(-50%);font-size:24px;filter:drop-shadow(0 2px 4px rgba(0,0,0,.3))">▼</div>
                    </div>

                    <div class="d-flex gap-2 justify-content-center flex-wrap">
                        <button id="btn-spin" onclick="spinWheel()" class="btn-pes-primary" style="font-size:13px;padding:10px 24px">
                            <i class="ti ti-player-play"></i> Putar!
                        </button>
                        <button onclick="spinAll()" class="btn-pes-secondary" style="font-size:13px;padding:10px 20px" id="btn-spin-all">
                            <i class="ti ti-bolt"></i> Acak Semua
                        </button>
                        <button onclick="resetDraw()" class="btn-pes-ghost" style="font-size:12px">
                            <i class="ti ti-refresh"></i> Reset
                        </button>
                    </div>

                    <!-- Queue info -->
                    <div id="spin-queue-info" style="margin-top:12px;font-size:12px;color:#64748b"></div>
                    <!-- Last result -->
                    <div id="spin-result" style="margin-top:10px;min-height:36px"></div>
                </div>
            </div>

            <!-- RIGHT: Group pools (drag & drop) -->
            <div class="col-lg-7">
                <div class="pes-card p-4">
                    <div class="d-flex align-items-center justify-content-between mb-3 flex-wrap gap-2">
                        <div style="font-size:14px;font-weight:700;color:#0f172a">
                            <i class="ti ti-layout-grid" style="color:#7c3aed"></i> Pembagian Grup
                        </div>
                        <div class="d-flex gap-2">
                            <button onclick="saveGroups()" class="btn-pes-primary" style="font-size:12px" id="btn-save-groups">
                                <i class="ti ti-device-floppy"></i> Simpan & Buat Jadwal
                            </button>
                        </div>
                    </div>

                    <!-- Unassigned pool -->
                    <div style="margin-bottom:16px">
                        <div style="font-size:11px;font-weight:700;color:#94a3b8;text-transform:uppercase;letter-spacing:.06em;margin-bottom:8px">
                            Belum Ditempatkan (<span id="unassigned-count">{{ $participants->count() }}</span>)
                        </div>
                        <div id="pool-unassigned" class="drag-pool"
                             data-group="unassigned"
                             style="min-height:48px;padding:8px;background:#f8fafc;border:2px dashed #e2e8f0;border-radius:12px;display:flex;flex-wrap:wrap;gap:6px">
                            @foreach($participants as $p)
                            <div class="player-chip" draggable="true"
                                 data-uid="{{ $p->user_id }}"
                                 data-name="{{ $p->user->username }}"
                                 data-pool="unassigned">
                                <img src="{{ $p->user->avatar ?? 'https://ui-avatars.com/api/?name='.urlencode($p->user->username).'&background=1d4ed8&color=fff&size=64' }}"
                                     alt="">
                                {{ $p->user->username }}
                            </div>
                            @endforeach
                        </div>
                    </div>

                    <!-- Group pools -->
                    <div class="row g-3">
                        @foreach($groupNames as $g)
                        @php
                            $colors = ['A'=>['#eff6ff','#1d4ed8'],'B'=>['#f0fdf4','#16a34a'],'C'=>['#fef9c3','#854d0e'],'D'=>['#f3e8ff','#7c3aed'],'E'=>['#fef2f2','#dc2626'],'F'=>['#f0f9ff','#0c4a6e'],'G'=>['#fff7ed','#9a3412'],'H'=>['#f0fdf4','#166534']];
                            [$bg, $clr] = $colors[$g] ?? ['#f8fafc','#64748b'];
                        @endphp
                        <div class="col-sm-6">
                            <div style="border:1.5px solid {{ $clr }}30;border-radius:12px;overflow:hidden">
                                <div style="background:{{ $bg }};color:{{ $clr }};font-size:12px;font-weight:800;padding:8px 12px;display:flex;align-items:center;gap:6px">
                                    <span style="width:24px;height:24px;background:{{ $clr }};color:#fff;border-radius:6px;display:inline-flex;align-items:center;justify-content:center;font-size:13px">{{ $g }}</span>
                                    Grup {{ $g }}
                                    <span class="group-count" data-group="{{ $g }}" style="margin-left:auto;font-weight:500;color:{{ $clr }}80">(0)</span>
                                </div>
                                <div id="pool-{{ $g }}" class="drag-pool group-pool" data-group="{{ $g }}"
                                     style="min-height:56px;padding:8px;background:#fff;display:flex;flex-wrap:wrap;gap:6px;overflow-x:auto">
                                </div>
                            </div>
                        </div>
                        @endforeach
                    </div>

                    <div id="save-status" style="margin-top:12px;font-size:12px"></div>
                </div>
            </div>
        </div>
    </div>
    @endif

    <!-- ══════════════════════════════════════ GROUP STAGE -->
    @if($isGroupKO)
    <div id="section-group" style="display:none">
        @if(!empty($groupData['standings']))
            @foreach($groupData['standings'] as $groupName => $rows)
            <div class="pes-card mb-4">
                <div class="pes-card-header">
                    <div class="pes-card-header-left">
                        <div class="pes-card-icon" style="background:#f3e8ff;color:#7c3aed;font-weight:800;font-size:15px">{{ $groupName }}</div>
                        <span class="pes-card-title">Grup {{ $groupName }}</span>
                    </div>
                </div>
                <div style="overflow-x:auto">
                    <table class="pes-table" style="min-width:360px">
                        <thead><tr>
                            <th>#</th><th>Pemain</th>
                            <th style="text-align:center">M</th><th style="text-align:center">W</th>
                            <th style="text-align:center">D</th><th style="text-align:center">L</th>
                            <th class="d-none d-sm-table-cell" style="text-align:center">GF</th>
                            <th class="d-none d-sm-table-cell" style="text-align:center">GA</th>
                            <th style="text-align:center">Pts</th>
                        </tr></thead>
                        <tbody>
                            @foreach($rows as $uid => $stat)
                            @php $adv = $loop->index < $tournament->groups_per_advance; $p = $groupData['players'][$uid] ?? null; @endphp
                            <tr style="{{ $adv ? 'background:#f0fdf4' : '' }}">
                                <td style="font-weight:700;color:#94a3b8;text-align:center">{{ $loop->iteration }}</td>
                                <td>
                                    <div class="d-flex align-items-center gap-2">
                                        <img src="{{ $p?->avatar ?? 'https://ui-avatars.com/api/?name='.urlencode($p?->username??'?').'&background=1d4ed8&color=fff' }}"
                                             style="width:30px;height:30px;border-radius:8px;object-fit:cover" alt="">
                                        <span style="font-size:13px;font-weight:600">{{ $p?->username ?? '?' }}</span>
                                        @if($adv)<span style="font-size:10px;color:#16a34a;font-weight:700;margin-left:4px">↑ LOLOS</span>@endif
                                    </div>
                                </td>
                                <td style="text-align:center">{{ $stat['played'] }}</td>
                                <td style="text-align:center;color:#16a34a;font-weight:600">{{ $stat['w'] }}</td>
                                <td style="text-align:center;color:#ca8a04;font-weight:600">{{ $stat['d'] ?? 0 }}</td>
                                <td style="text-align:center;color:#dc2626;font-weight:600">{{ $stat['l'] }}</td>
                                <td class="d-none d-sm-table-cell" style="text-align:center">{{ $stat['gf'] }}</td>
                                <td class="d-none d-sm-table-cell" style="text-align:center">{{ $stat['ga'] }}</td>
                                <td style="text-align:center;font-size:14px;font-weight:800;color:#1d4ed8">{{ $stat['pts'] }}</td>
                            </tr>
                            @endforeach
                        </tbody>
                    </table>
                </div>
                <div class="pes-card-header" style="border-top:1px solid #f1f5f9">
                    <span class="pes-card-title" style="font-size:12px;color:#64748b">Pertandingan Grup {{ $groupName }}</span>
                </div>
                @foreach($groupData['matches'] as $gm)
                @if($gm->group_name === $groupName)
                @php
                    $gLegsAll  = $gm->relationLoaded('seriesLegs') ? $gm->seriesLegs : collect([$gm]);
                    $gBo       = $tournament->getBoForPhase('group');
                    $gBan      = $tournament->getBanCountForPhase('group');
                    $gLegDone  = $gLegsAll->where('status','completed')->count();
                    $gPending  = $gLegsAll->where('status','pending')->sortBy('leg_number')->first();
                    $gSubmitId = $gPending ? $gPending->id : $gm->id;
                    $gSeriesDone = ($gPending === null && $gm->player1_id && $gm->player2_id);

                    // Build modal data for completed admin group matches
                    $adminGmBanRec = $gm->relationLoaded('seriesBanRecords') ? $gm->seriesBanRecords : collect();
                    $adminGmLwb = $gLegsAll->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'  => $adminGmBanRec->where('player_id',$gm->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'  => $adminGmBanRec->where('player_id',$gm->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();
                    $adminGmBp1 = $adminGmBanRec->where('player_id',$gm->player1_id)->map(fn($b)=>['name'=>$b->club?->name??'?','logo'=>$b->club?->logo_url??'','leg'=>$b->leg_number])->values()->toArray();
                    $adminGmBp2 = $adminGmBanRec->where('player_id',$gm->player2_id)->map(fn($b)=>['name'=>$b->club?->name??'?','logo'=>$b->club?->logo_url??'','leg'=>$b->leg_number])->values()->toArray();
                    $adminGmModalData = json_encode([
                        'id'       => $gm->id,
                        'round'    => 'Grup '.$groupName,
                        'p1'       => $gm->player1?->username ?? 'TBD',
                        'p2'       => $gm->player2?->username ?? 'TBD',
                        'p1avatar' => $gm->player1?->avatar ?? '',
                        'p2avatar' => $gm->player2?->avatar ?? '',
                        'winner'   => $gm->winner?->username ?? ($gm->is_draw ? 'Seri' : ''),
                        'winner_id'=> $gm->winner_id,
                        'p1_id'    => $gm->player1_id,
                        'p2_id'    => $gm->player2_id,
                        'bans_p1'  => $adminGmBp1,
                        'bans_p2'  => $adminGmBp2,
                        'legs'     => $adminGmLwb,
                    ]);
                @endphp
                @if($gSeriesDone)
                <script>window._gmd=window._gmd||{};window._gmd[{{ $gm->id }}]={!! $adminGmModalData !!};</script>
                @endif
                <div class="d-flex align-items-center gap-3 px-3 py-2"
                     style="border-bottom:1px solid #f8fafc;flex-wrap:wrap;{{ $gSeriesDone ? 'cursor:pointer' : '' }}"
                     @if($gSeriesDone) onclick="var d=window._gmd&&window._gmd[{{ $gm->id }}];if(d&&typeof window.showMatchDetail==='function')window.showMatchDetail(d);" @endif>
                    <div style="flex:1;min-width:120px">
                        <span style="font-size:13px;font-weight:600;color:#0f172a">{{ $gm->player1?->username ?? 'TBD' }}</span>
                        <span style="color:#94a3b8;margin:0 6px">vs</span>
                        <span style="font-size:13px;font-weight:600;color:#0f172a">{{ $gm->player2?->username ?? 'TBD' }}</span>
                    </div>

                    @if($gSeriesDone)
                        {{-- Series fully completed --}}
                        @if($gLegsAll->count() > 1)
                        @php
                            $gmAgg1  = $gLegsAll->sum('score1');
                            $gmAgg2  = $gLegsAll->sum('score2');
                            $gmWins1 = $gLegsAll->filter(fn($l)=>$l->winner_id===$gm->player1_id)->count();
                            $gmWins2 = $gLegsAll->filter(fn($l)=>$l->winner_id===$gm->player2_id)->count();
                            $gmDraws = $gLegsAll->filter(fn($l)=>$l->is_draw)->count();
                        @endphp
                        <div>
                            {{-- BO / Ban badges --}}
                            <div style="display:flex;align-items:center;gap:4px;flex-wrap:wrap;margin-bottom:4px">
                                @if($gBo > 1)
                                <span style="font-size:9px;font-weight:700;color:#7c3aed;background:#f3e8ff;padding:1px 6px;border-radius:20px;white-space:nowrap">
                                    <i class="ti ti-repeat" style="font-size:9px"></i> BO{{ $gBo }}
                                </span>
                                @endif
                                @if($gBan > 0)
                                <span style="font-size:9px;font-weight:700;color:#dc2626;background:#fff5f5;padding:1px 6px;border-radius:20px;white-space:nowrap">
                                    <i class="ti ti-ban" style="font-size:9px"></i> Ban {{ $gBan }}
                                </span>
                                @endif
                            </div>
                            <span style="font-size:14px;font-weight:900;color:#0f172a;font-family:'Plus Jakarta Sans',sans-serif;letter-spacing:-0.5px">{{ $gmWins1 }} – {{ $gmWins2 }}</span>
                            <div style="font-size:10px;color:#64748b;font-weight:600;margin-top:2px">
                                Leg Wins · Agg: {{ $gmAgg1 }}–{{ $gmAgg2 }}@if($gmDraws > 0) · Seri {{ $gmDraws }}@endif
                                · Pts +{{ $gmWins1 > $gmWins2 ? 3 : ($gmWins1 === $gmWins2 ? 1 : 0) }}
                            </div>
                        </div>
                        @else
                        <div>
                            {{-- BO1 badge (single leg) --}}
                            @if($gBan > 0)
                            <div style="margin-bottom:3px">
                                <span style="font-size:9px;font-weight:700;color:#dc2626;background:#fff5f5;padding:1px 6px;border-radius:20px">
                                    <i class="ti ti-ban" style="font-size:9px"></i> Ban {{ $gBan }}
                                </span>
                            </div>
                            @endif
                            <span style="font-size:14px;font-weight:800;color:#0f172a">{{ $gm->score1 }} – {{ $gm->score2 }}</span>
                            @if($gm->is_draw)
                                <span style="font-size:11px;font-weight:700;padding:2px 8px;border-radius:20px;background:#fef9c3;color:#854d0e;margin-left:4px">Draw · 1pt</span>
                            @else
                                <span style="font-size:11px;color:#16a34a;font-weight:700;margin-left:4px">✓ Selesai</span>
                            @endif
                        </div>
                        @endif
                        <span style="font-size:10px;color:#94a3b8;font-style:italic;flex-shrink:0;margin-left:auto">↗ detail</span>

                    @elseif($gm->player1_id && $gm->player2_id)
                        {{-- Series has pending leg(s) — show score form --}}
                        <div>
                            @if($gBo > 1)
                            <div style="font-size:10px;color:#7c3aed;font-weight:700;margin-bottom:3px;display:flex;align-items:center;gap:4px">
                                <i class="ti ti-repeat"></i> BO{{ $gBo }} · Leg {{ $gLegDone + 1 }}/{{ $gBo }}
                                @if($gBan > 0)<span style="color:#dc2626"><i class="ti ti-ban"></i> Ban {{ $gBan }}</span>@endif
                            </div>
                            @elseif($gBan > 0)
                            <div style="font-size:10px;color:#dc2626;font-weight:700;margin-bottom:3px">
                                <i class="ti ti-ban"></i> Ban {{ $gBan }} klub/pemain
                            </div>
                            @endif
                            <div class="d-flex align-items-center gap-2 flex-wrap">
                                <form method="POST" action="{{ route('admin.tournament.score', [$tournament->id, $gSubmitId]) }}" class="d-flex align-items-center gap-2">
                                    @csrf
                                    <input type="number" name="score1" min="0" max="99" placeholder="0" class="pes-input" style="width:60px;text-align:center;padding:5px;font-size:14px;font-weight:700" required>
                                    <span style="color:#94a3b8;font-weight:700">–</span>
                                    <input type="number" name="score2" min="0" max="99" placeholder="0" class="pes-input" style="width:60px;text-align:center;padding:5px;font-size:14px;font-weight:700" required>
                                    <button class="btn-pes-primary" style="font-size:11px;padding:5px 10px"><i class="ti ti-check"></i> Submit</button>
                                </form>
                                @if($gBan > 0 || $gBo > 1)
                                <a href="{{ route('admin.tournament.pickban', [$tournament->id, $gm->id]) }}"
                                   class="btn-pes-ghost" style="font-size:11px;padding:5px 10px;text-decoration:none;border:1px solid #e2e8f0;flex-shrink:0">
                                    <i class="ti ti-ban" style="color:#dc2626"></i> Pick/Ban
                                </a>
                                @endif
                            </div>
                            @if($gLegDone > 0)
                            @php $aggG1=$gLegsAll->where('status','completed')->sum('score1'); $aggG2=$gLegsAll->where('status','completed')->sum('score2'); @endphp
                            <div style="font-size:10px;color:#64748b;margin-top:2px">Agregat leg selesai: {{ $aggG1 }}–{{ $aggG2 }}</div>
                            @else
                            <span style="font-size:10px;color:#94a3b8">Seri = 1 poin tiap pemain</span>
                            @endif
                        </div>

                    @else
                        <span style="font-size:11px;color:#94a3b8">Menunggu pemain</span>
                    @endif
                </div>
                @endif
                @endforeach

                {{-- Tiebreaker matches for this group --}}
                @if(!empty($groupData['tiebreakers']) && $groupData['tiebreakers']->where('group_name', $groupName)->count())
                <div style="padding:8px 16px;background:#fef9c3;border-top:2px solid #fef08a">
                    <div style="font-size:11px;font-weight:700;color:#854d0e;margin-bottom:8px;display:flex;align-items:center;gap:6px">
                        <i class="ti ti-bolt"></i> GOLDEN GOAL — Tiebreaker Grup {{ $groupName }}
                        <span style="font-size:10px;font-weight:500">Gol pertama menang</span>
                    </div>
                    @foreach($groupData['tiebreakers']->where('group_name', $groupName) as $tb)
                    <div class="d-flex align-items-center gap-3 py-2" style="border-bottom:1px solid #fef08a;flex-wrap:wrap">
                        <div style="flex:1;min-width:120px">
                            <span style="font-size:13px;font-weight:600;color:#0f172a">{{ $tb->player1?->username ?? 'TBD' }}</span>
                            <span style="color:#94a3b8;margin:0 6px">vs</span>
                            <span style="font-size:13px;font-weight:600;color:#0f172a">{{ $tb->player2?->username ?? 'TBD' }}</span>
                        </div>
                        @if($tb->status === 'completed')
                            <span style="font-size:14px;font-weight:800;color:#0f172a">{{ $tb->score1 }} – {{ $tb->score2 }}</span>
                            <span style="font-size:11px;font-weight:700;padding:2px 8px;border-radius:20px;background:#f0fdf4;color:#15803d">
                                🏆 {{ $tb->winner?->username ?? '?' }} lolos
                            </span>
                        @elseif($tb->player1_id && $tb->player2_id)
                            <form method="POST" action="{{ route('admin.tournament.score', [$tournament->id, $tb->id]) }}" class="d-flex align-items-center gap-2">
                                @csrf
                                <input type="number" name="score1" min="0" max="99" placeholder="0" class="pes-input" style="width:60px;text-align:center;padding:5px;font-size:14px;font-weight:700" required>
                                <span style="color:#94a3b8;font-weight:700">–</span>
                                <input type="number" name="score2" min="0" max="99" placeholder="0" class="pes-input" style="width:60px;text-align:center;padding:5px;font-size:14px;font-weight:700" required>
                                <button class="btn-pes-primary" style="font-size:11px;padding:5px 10px;background:#ca8a04;border-color:#ca8a04">
                                    <i class="ti ti-bolt"></i> Submit GG
                                </button>
                            </form>
                            <span style="font-size:10px;color:#854d0e;font-weight:600">⚡ Tidak boleh seri!</span>
                        @else
                            <span style="font-size:11px;color:#94a3b8">Menunggu pemain</span>
                        @endif
                    </div>
                    @endforeach
                </div>
                @endif
            </div>
            @endforeach
        @else
            <div class="pes-card p-5 text-center">
                <div style="font-size:36px;margin-bottom:12px">🎯</div>
                <div style="font-size:15px;font-weight:700;color:#0f172a;margin-bottom:4px">Bracket belum dibuat</div>
                <div style="font-size:13px;color:#64748b">Gunakan tab "Undian Grup" untuk membagi peserta, lalu simpan.</div>
            </div>
        @endif
    </div>
    @endif

    <!-- ══════════════════════════════════════ KNOCKOUT DRAW (format=knockout only) -->
    @if(!$isGroupKO)
    <div id="section-ko-draw">
        <div class="row g-4">
            <!-- LEFT: Wheel -->
            <div class="col-lg-5">
                <div class="pes-card p-4 text-center">
                    <div style="font-size:14px;font-weight:700;color:#0f172a;margin-bottom:4px">
                        <i class="ti ti-wheel" style="color:#7c3aed"></i> Roda Undian Bracket
                    </div>
                    <div style="font-size:12px;color:#64748b;margin-bottom:16px">
                        Putar untuk menentukan urutan seeding di bracket knockout
                    </div>
                    <div style="position:relative;display:inline-block;margin-bottom:16px;width:100%;max-width:300px">
                        <canvas id="ko-wheel-canvas" width="300" height="300"
                                style="border-radius:50%;box-shadow:0 8px 32px rgba(15,23,42,.18);width:100%;height:auto"></canvas>
                        <div style="position:absolute;top:-12px;left:50%;transform:translateX(-50%);font-size:24px;filter:drop-shadow(0 2px 4px rgba(0,0,0,.3))">▼</div>
                    </div>
                    <div class="d-flex gap-2 justify-content-center flex-wrap">
                        <button id="ko-btn-spin" onclick="koSpinWheel()" class="btn-pes-primary" style="font-size:13px;padding:10px 24px">
                            <i class="ti ti-player-play"></i> Putar!
                        </button>
                        <button onclick="koSpinAll()" class="btn-pes-secondary" style="font-size:13px;padding:10px 20px" id="ko-btn-spin-all">
                            <i class="ti ti-bolt"></i> Acak Semua
                        </button>
                        <button onclick="koResetDraw()" class="btn-pes-ghost" style="font-size:12px">
                            <i class="ti ti-refresh"></i> Reset
                        </button>
                    </div>
                    <div id="ko-spin-queue-info" style="margin-top:12px;font-size:12px;color:#64748b"></div>
                    <div id="ko-spin-result" style="margin-top:10px;min-height:36px"></div>
                </div>
            </div>

            <!-- RIGHT: Seed order list -->
            <div class="col-lg-7">
                <div class="pes-card p-4">
                    <div class="d-flex align-items-center justify-content-between mb-3 flex-wrap gap-2">
                        <div>
                            <div style="font-size:14px;font-weight:700;color:#0f172a">
                                <i class="ti ti-list-numbers" style="color:#7c3aed"></i> Urutan Seeding
                            </div>
                            <div style="font-size:11px;color:#64748b;margin-top:2px">
                                Seed 1 vs Seed {{ $participants->count() }}, Seed 2 vs Seed {{ $participants->count()-1 }}, dst.
                            </div>
                        </div>
                        <button onclick="koSaveDraw()" class="btn-pes-primary" style="font-size:12px" id="ko-btn-save">
                            <i class="ti ti-device-floppy"></i> Simpan & Buat Bracket
                        </button>
                    </div>

                    <!-- Undrawn pool -->
                    <div style="margin-bottom:14px">
                        <div style="font-size:11px;font-weight:700;color:#94a3b8;text-transform:uppercase;letter-spacing:.05em;margin-bottom:6px">
                            Belum Diundi (<span id="ko-undrawn-count">{{ $participants->count() }}</span>)
                        </div>
                        <div id="ko-pool-undrawn"
                             style="min-height:48px;padding:8px;background:#f8fafc;border:2px dashed #e2e8f0;border-radius:12px;display:flex;flex-wrap:wrap;gap:6px">
                            @foreach($participants as $p)
                            <div class="player-chip ko-chip"
                                 data-uid="{{ $p->user_id }}"
                                 data-name="{{ $p->user->username }}"
                                 data-avatar="{{ $p->user->avatar ?? '' }}">
                                <img src="{{ $p->user->avatar ?? 'https://ui-avatars.com/api/?name='.urlencode($p->user->username).'&background=1d4ed8&color=fff&size=64' }}" alt="">
                                {{ $p->user->username }}
                            </div>
                            @endforeach
                        </div>
                    </div>

                    <!-- Seed slots -->
                    <div style="font-size:11px;font-weight:700;color:#94a3b8;text-transform:uppercase;letter-spacing:.05em;margin-bottom:8px">
                        Urutan Seed (hasil undian)
                    </div>
                    <div id="ko-seed-list" style="display:flex;flex-direction:column;gap:6px;max-height:380px;overflow-y:auto"></div>
                    <div id="ko-save-status" style="margin-top:10px;font-size:12px"></div>

                    <!-- Preview bracket matchups -->
                    <div id="ko-preview-section" style="display:none;margin-top:16px;border-top:1px solid #f1f5f9;padding-top:14px">
                        <div style="font-size:11px;font-weight:700;color:#64748b;text-transform:uppercase;margin-bottom:8px">
                            Preview Round 1
                        </div>
                        <div id="ko-matchup-preview" style="display:flex;flex-direction:column;gap:4px"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    @endif

    <!-- ══════════════════════════════════════ KNOCKOUT -->
    <div id="section-knockout" style="{{ $isGroupKO ? 'display:none' : 'display:none' }}">
        @if(!empty($knockoutData))
        @php
            $koRoundLabels = [];
            foreach ($knockoutData as $r => $ms) {
                $c = count($ms);
                $koRoundLabels[$r] = match(true) {
                    $c===1 => 'Final 🏆', $c===2 => 'Semi Final', $c===4 => 'Perempat Final',
                    default => 'Babak '.$r
                };
            }
            // Total matches in round 1 = total base slots
            $baseMatchCount = count(array_values($knockoutData)[0]);
            $CARD_H = 72; // estimated card height px
            $GAP    = 8;  // gap between cards in round 1
        @endphp

        {{-- Swipe hint (mobile only, hidden after first scroll) --}}
        <div class="admin-bracket-swipe-hint" style="text-align:right;font-size:11px;color:#94a3b8;font-weight:600;padding:4px 2px 2px;display:none">
            <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="admin-bracket-container">
        <div id="ko-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
            $isLastRound = $roundNum == array_key_last($knockoutData);
            $matchCount  = count($matches);
            $roundIndex  = array_search($roundNum, array_keys($knockoutData));
            $colW        = 'clamp(160px,42vw,220px)';
            $connW       = $isLastRound ? 0 : 28;
        @endphp

        {{-- Round column --}}
        <div class="ko-round" data-round="{{ $roundNum }}" data-matches="{{ $matchCount }}"
             style="display:flex;flex-direction:column;width:{{ $colW }};flex-shrink:0;margin-right:{{ $connW }}px">

            {{-- Round header --}}
            <div style="font-size:10px;font-weight:700;color:#64748b;text-transform:uppercase;
                        letter-spacing:.06em;text-align:center;padding-bottom:10px;
                        border-bottom:2px solid {{ $isLastRound ? '#1d4ed8' : '#e2e8f0' }};
                        margin-bottom:8px;flex-shrink:0">
                {{ $koRoundLabels[$roundNum] }}
            </div>

            {{-- Match slots: evenly spaced --}}
            <div style="flex:1;display:flex;flex-direction:column;justify-content:space-around">
            @foreach($matches as $matchIdx => $m)
            @php
                $seriesLegsKo  = $m->relationLoaded('seriesLegs') ? $m->seriesLegs : collect([$m]);
                $completedLegs = $seriesLegsKo->where('status','completed');
                $pendingLegKo  = $seriesLegsKo->where('status','pending')->sortBy('leg_number')->first();
                $submitIdKo    = $pendingLegKo ? $pendingLegKo->id : null;
                $currentLegNum = $pendingLegKo ? $pendingLegKo->leg_number : null;
                $isGGDecider   = $pendingLegKo && $pendingLegKo->is_golden_goal;
                $seriesDone    = $pendingLegKo === null && $m->player1_id && $m->player2_id;
                $legsDoneKo    = $completedLegs->count();
                $aggKo1 = $completedLegs->sum('score1');
                $aggKo2 = $completedLegs->sum('score2');
                $wKo1   = $completedLegs->filter(fn($l)=>$l->winner_id===$m->player1_id)->count();
                $wKo2   = $completedLegs->filter(fn($l)=>$l->winner_id===$m->player2_id)->count();
                $isFinalRound = ($matchCount === 1);
                $boPhase      = $isFinalRound ? 'final' : 'knockout';
                $mBo          = $tournament->getBoForPhase($boPhase);
                $mBan         = $tournament->getBanCountForPhase($boPhase);
                $adminBanRecs = $m->relationLoaded('seriesBanRecords') ? $m->seriesBanRecords : collect();
                $adminBansP1  = $adminBanRecs->where('player_id', $m->player1_id)->map(fn($b)=>['name'=>$b->club?->name??'?','logo'=>$b->club?->logo_url??''])->values()->toArray();
                $adminBansP2  = $adminBanRecs->where('player_id', $m->player2_id)->map(fn($b)=>['name'=>$b->club?->name??'?','logo'=>$b->club?->logo_url??''])->values()->toArray();
                $adminIsCompleted = $seriesDone && $m->winner_id;
            @endphp

            {{-- Single match slot --}}
            <div class="ko-match-slot" data-round="{{ $roundNum }}" data-idx="{{ $matchIdx }}"
                 style="display:flex;align-items:center;padding:4px 0">
                <div class="ko-card" style="flex:1;background:#fff;
                            border:1.5px solid {{ $adminIsCompleted?'#bfdbfe':($m->player1_id&&$m->player2_id?'#e2e8f0':'#f1f5f9') }};
                            border-radius:10px;overflow:hidden;
                            {{ $adminIsCompleted ? 'cursor:pointer;transition:box-shadow .15s' : '' }}"
                     @if($adminIsCompleted)
                     onclick="showMatchDetail({{ json_encode([
                         'id'       => $m->id,
                         'round'    => $koRoundLabels[$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'  => $adminBansP1,
                         'bans_p2'  => $adminBansP2,
                         'legs'     => $seriesLegsKo->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,
                         ])->values()->toArray(),
                     ]) }})"
                     onmouseover="this.style.boxShadow='0 4px 14px rgba(15,23,42,.1)'"
                     onmouseout="this.style.boxShadow=''"
                     title="Klik untuk detail"
                     @endif>

                    @foreach([[$m->player1_id,$m->player1,$m->score1],[$m->player2_id,$m->player2,$m->score2]] as [$pid,$player,$score])
                    @php
                        $win=$m->winner_id&&$m->winner_id===$pid; $tbd=!$pid;
                        // Multi-leg: show leg wins instead of goal score
                        $dispKoScore = ($m->status==='completed')
                            ? ($completedLegs->count() > 1 ? ($pid===$m->player1_id ? $wKo1 : $wKo2) : ($score??0))
                            : '';
                    @endphp
                    <div style="display:flex;align-items:center;gap:6px;padding:7px 8px;
                                {{ !$loop->last?'border-bottom:1px solid #f1f5f9':'' }};
                                {{ $win?'background:#f0fdf4':'' }}">
                        @if(!$tbd)
                        <img src="{{ $player?->avatar ?? 'https://ui-avatars.com/api/?name='.urlencode($player?->username??'?').'&background=1d4ed8&color=fff&size=32' }}"
                             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:{{ $win?700:500 }};
                                     color:{{ $tbd?'#94a3b8':($win?'#15803d':'#0f172a') }};
                                     overflow:hidden;text-overflow:ellipsis;white-space:nowrap">
                            {{ $tbd?'TBD':($player?->username??'?') }}{{ $win?' 🏆':'' }}
                        </span>
                        <span style="font-size:12px;font-weight:800;color:{{ $win?'#15803d':'#64748b' }};min-width:14px;text-align:right;flex-shrink:0">
                            {{ $dispKoScore }}
                        </span>
                    </div>
                    @endforeach

                    @if($m->player1_id&&$m->player2_id)
                    @if($pendingLegKo)
                    <div style="padding:5px 8px;background:{{ $isGGDecider?'#fef9c3':'#f8fafc' }};border-top:1px solid {{ $isGGDecider?'#fde68a':'#f1f5f9' }}">
                        @if($mBo>1&&!$isGGDecider)
                        <div style="font-size:9px;color:#7c3aed;font-weight:700;margin-bottom:3px">
                            BO{{ $mBo }} · Leg {{ $currentLegNum }}/{{ $mBo }}{{ $legsDoneKo>0?' · W '.$wKo1.'-'.$wKo2.' · Agg '.$aggKo1.'–'.$aggKo2:'' }}
                        </div>
                        @elseif($isGGDecider)
                        <div style="font-size:9px;color:#854d0e;font-weight:700;margin-bottom:3px">⚡ GOLDEN GOAL</div>
                        @endif
                        <div style="display:flex;align-items:center;gap:3px">
                            <form method="POST" action="{{ route('admin.tournament.score',[$tournament->id,$submitIdKo]) }}"
                                  style="display:flex;align-items:center;gap:3px">
                                @csrf
                                <input type="number" name="score1" min="0" max="99" placeholder="0" class="pes-input"
                                       style="width:36px;text-align:center;padding:3px;font-size:12px;font-weight:700" required>
                                <span style="color:#94a3b8;font-size:10px">–</span>
                                <input type="number" name="score2" min="0" max="99" placeholder="0" class="pes-input"
                                       style="width:36px;text-align:center;padding:3px;font-size:12px;font-weight:700" required>
                                <button style="font-size:10px;padding:3px 7px;background:{{ $isGGDecider?'#ca8a04':'#1d4ed8' }};color:#fff;border:none;border-radius:5px;cursor:pointer">
                                    {{ $isGGDecider?'⚡':'✓' }}
                                </button>
                            </form>
                            @if($mBan>0||$mBo>1)
                            <a href="{{ route('admin.tournament.pickban',[$tournament->id,$m->id]) }}"
                               style="font-size:9px;color:#dc2626;background:#fff5f5;border:1px solid #fecaca;border-radius:5px;padding:3px 5px;text-decoration:none">🚫</a>
                            @endif
                        </div>
                    </div>
                    @elseif($seriesDone&&$seriesLegsKo->count()>1)
                    <div style="padding:3px 8px;background:#f0f9ff;border-top:1px solid #bfdbfe;font-size:9px;color:#0c4a6e;text-align:center">
                        {{ $seriesLegsKo->count() }}L · W{{ $wKo1 }}-{{ $wKo2 }} · Agg {{ $aggKo1 }}–{{ $aggKo2 }}
                    </div>
                    @endif
                    @endif
                </div>
            </div>
            @endforeach
            </div>{{-- end justify-content --}}

        </div>{{-- end round column --}}
        @endforeach

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

        @push('styles')
        <style>
        .ko-round { min-height: {{ $baseMatchCount * 72 + 40 }}px; }
        /* Mobile: bracket card width adapts */
        @media(max-width:768px) {
            .ko-round { min-width: clamp(160px, 42vw, 200px); }
        }
        </style>
        @endpush

        @else
        <div class="pes-card p-5 text-center">
            <div style="font-size:36px;margin-bottom:12px">🏆</div>
            <div style="font-size:15px;font-weight:700;color:#0f172a;margin-bottom:4px">Bracket Knockout belum tersedia</div>
            <div style="font-size:13px;color:#64748b">
                {{ $isGroupKO ? 'Selesaikan fase grup lalu klik "Mulai Knockout".' : 'Klik "Generate Otomatis" untuk membuat bagan.' }}
            </div>
        </div>
        @endif

    </div>{{-- end section-knockout --}}

    {{-- ── Match Detail Modal (admin) — di luar semua section ─────────── --}}
    <div id="ko-match-modal"
         style="display:none;position:fixed;inset:0;z-index:9990;background:rgba(15,23,42,.55);backdrop-filter:blur(3px)"
         onclick="if(event.target===this)closeMatchModal()">
        <div style="position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);
                    width:min(92vw,500px);background:#fff;border-radius:20px;
                    box-shadow:0 24px 64px rgba(15,23,42,.2);overflow:hidden;max-height:90vh;display:flex;flex-direction:column">

            <!-- Header -->
            <div style="padding:16px 20px;background:linear-gradient(135deg,#0f172a,#1e3a5f);
                        display:flex;align-items:center;justify-content:space-between;flex-shrink:0">
                <div>
                    <div id="ko-modal-round" style="font-size:11px;font-weight:700;color:rgba(255,255,255,.5);text-transform:uppercase;letter-spacing:.07em"></div>
                    <div style="font-size:15px;font-weight:800;color:#fff;margin-top:2px">Detail Pertandingan</div>
                </div>
                <button onclick="closeMatchModal()"
                        style="background:rgba(255,255,255,.1);border:none;border-radius:10px;width:32px;height:32px;
                               cursor:pointer;color:#fff;font-size:16px;display:flex;align-items:center;justify-content:center">✕</button>
            </div>

            <!-- Scrollable body -->
            <div style="overflow-y:auto;flex:1">

            <!-- VS section -->
            <div style="padding:20px;border-bottom:1px solid #f1f5f9">
                <div style="display:flex;align-items:center;justify-content:center;gap:12px">
                    <div style="flex:1;text-align:center">
                        <img id="ko-modal-p1-avatar" src="" alt=""
                             style="width:52px;height:52px;border-radius:14px;object-fit:cover;margin-bottom:8px;border:3px solid #e2e8f0">
                        <div id="ko-modal-p1-name" style="font-size:13px;font-weight:700;color:#0f172a"></div>
                        <div id="ko-modal-p1-badge" style="margin-top:4px;font-size:11px"></div>
                    </div>
                    <div style="flex-shrink:0;text-align:center">
                        <div id="ko-modal-score" style="font-size:28px;font-weight:900;color:#0f172a;font-family:'Plus Jakarta Sans',sans-serif;letter-spacing:-1px;line-height:1"></div>
                        <div id="ko-modal-score-sub" style="font-size:10px;color:#94a3b8;margin-top:4px;font-weight:600"></div>
                    </div>
                    <div style="flex:1;text-align:center">
                        <img id="ko-modal-p2-avatar" src="" alt=""
                             style="width:52px;height:52px;border-radius:14px;object-fit:cover;margin-bottom:8px;border:3px solid #e2e8f0">
                        <div id="ko-modal-p2-name" style="font-size:13px;font-weight:700;color:#0f172a"></div>
                        <div id="ko-modal-p2-badge" style="margin-top:4px;font-size:11px"></div>
                    </div>
                </div>
            </div>

            <!-- Ban section -->
            <div id="ko-modal-bans" style="padding:14px 20px;border-bottom:1px solid #f1f5f9;display:none">
                <div style="font-size:11px;font-weight:700;color:#dc2626;text-transform:uppercase;letter-spacing:.06em;margin-bottom:10px;display:flex;align-items:center;gap:5px">
                    <i class="ti ti-ban"></i> Klub yang Di-ban
                </div>
                <div style="display:grid;grid-template-columns:1fr 1fr;gap:10px">
                    <div>
                        <div id="ko-modal-ban-p1-label" style="font-size:10px;font-weight:700;color:#1d4ed8;margin-bottom:6px;text-transform:uppercase"></div>
                        <div id="ko-modal-bans-p1" style="display:flex;flex-direction:column;gap:4px"></div>
                    </div>
                    <div>
                        <div id="ko-modal-ban-p2-label" style="font-size:10px;font-weight:700;color:#7c3aed;margin-bottom:6px;text-transform:uppercase"></div>
                        <div id="ko-modal-bans-p2" style="display:flex;flex-direction:column;gap:4px"></div>
                    </div>
                </div>
            </div>

            <!-- Legs breakdown -->
            <div id="ko-modal-legs" style="padding:16px 20px;border-bottom:1px solid #f1f5f9;display:none">
                <div style="font-size:11px;font-weight:700;color:#64748b;text-transform:uppercase;letter-spacing:.06em;margin-bottom:10px">Rincian Per Leg</div>
                <div id="ko-modal-legs-list" style="display:flex;flex-direction:column;gap:8px"></div>
            </div>

            </div><!-- end scrollable -->

            <!-- Winner banner -->
            <div id="ko-modal-winner" style="padding:14px 20px;background:#f0fdf4;display:flex;align-items:center;gap:10px;flex-shrink:0">
                <span style="font-size:24px">🏆</span>
                <div>
                    <div style="font-size:11px;font-weight:700;color:#15803d;text-transform:uppercase;letter-spacing:.06em">Pemenang</div>
                    <div id="ko-modal-winner-name" style="font-size:15px;font-weight:800;color:#0f172a;margin-top:1px"></div>
                </div>
            </div>
        </div>
    </div>

    @push('styles')
    <style>
    /* ── Bracket connectors (CSS border approach) ── */
    .ko-connector-wrap {
        position: absolute;
        right: -32px;
        top: 0;
        width: 32px;
        height: 100%;
        pointer-events: none;
    }
    /* ── Player chip ── */
    .player-chip {
        display:inline-flex;align-items:center;gap:6px;
        background:#fff;border:1.5px solid #e2e8f0;border-radius:20px;
        padding:4px 10px 4px 4px;font-size:12px;font-weight:600;color:#0f172a;
        cursor:grab;user-select:none;transition:all .15s;
    }
    .player-chip img { width:22px;height:22px;border-radius:50%;object-fit:cover;flex-shrink:0; }
    .player-chip:hover { border-color:#1d4ed8;background:#eff6ff;color:#1d4ed8; }
    .player-chip.dragging { opacity:.4;cursor:grabbing; }
    /* ── Drop pools ── */
    .drag-pool { transition:background .15s; }
    .drag-pool.drag-over { background:#eff6ff !important;border-color:#1d4ed8 !important; }
    /* ── Spin result ── */
    .spin-badge {
        display:inline-flex;align-items:center;gap:8px;
        padding:8px 16px;border-radius:20px;font-size:13px;font-weight:700;
        background:#f3e8ff;color:#7c3aed;border:1.5px solid #ddd6fe;
        animation:popIn .3s ease;
    }
    @@keyframes popIn { from{transform:scale(.8);opacity:0} to{transform:scale(1);opacity:1} }
    .ko-match { transition:box-shadow .15s; }
    .ko-match:hover { box-shadow:0 4px 16px rgba(15,23,42,.1) !important; }
    </style>
    @endpush>

    @push('scripts')
    <script>
    var IS_GROUP_KO = {{ $isGroupKO ? 'true' : 'false' }};
    var GROUP_NAMES = {!! json_encode($groupNames) !!};
    var ASSIGN_URL  = '{{ route("admin.tournament.assignGroups", $tournament->id) }}';
    var CSRF_TOKEN  = (document.querySelector('meta[name="csrf-token"]')||{}).content || '{{ csrf_token() }}';
    var IS_LIVE     = {{ $isLive ? 'true' : 'false' }};
    var TOUR_ID     = {{ $tournament->id }};
    var KO_DRAW_URL = '{{ route("admin.tournament.knockoutDraw", $tournament->id) }}';
    var ALL_PLAYERS = [
        @foreach($participants as $p)
        { id: {{ $p->user_id }}, name: {!! json_encode($p->user->username) !!}, avatar: {!! json_encode($p->user->avatar ?? '') !!} },
        @endforeach
    ];
    var wheelQueue = [], groupPools = {}, isSpinning = false, currentAngle = 0;
    var dragUID = null, dragFrom = null;
    var SEG_COLORS = ['#6366f1','#8b5cf6','#ec4899','#f59e0b','#10b981','#3b82f6','#ef4444','#14b8a6','#f97316','#a78bfa'];

    function switchTab(tab) {
        ['draw','group','knockout'].forEach(function(t) {
            var s=document.getElementById('section-'+t), b=document.getElementById('tab-'+t);
            if(s) s.style.display = t===tab?'':'none';
            if(b) b.className   = t===tab?'btn-pes-primary':'btn-pes-secondary';
        });
        if(tab === 'knockout') setTimeout(drawBracketConnectors, 150);
        try{localStorage.setItem('bTab_'+TOUR_ID,tab);}catch(e){}
    }

    function drawWheel() {
        var cv=document.getElementById('wheel-canvas'); if(!cv) return;
        var ctx=cv.getContext('2d'), cx=cv.width/2, cy=cv.height/2, r=cx-8;
        ctx.clearRect(0,0,cv.width,cv.height);
        if(!wheelQueue.length){
            ctx.fillStyle='#f1f5f9'; ctx.beginPath(); ctx.arc(cx,cy,r,0,2*Math.PI); ctx.fill();
            ctx.fillStyle='#94a3b8'; ctx.font='bold 13px Inter,sans-serif'; ctx.textAlign='center';
            ctx.fillText('Semua sudah',cx,cy-6); ctx.fillText('ditempatkan!',cx,cy+12); return;
        }
        var n=wheelQueue.length, arc=2*Math.PI/n;
        wheelQueue.forEach(function(p,i){
            var s=currentAngle+i*arc-Math.PI/2, e=s+arc;
            ctx.beginPath(); ctx.moveTo(cx,cy); ctx.arc(cx,cy,r,s,e); ctx.closePath();
            ctx.fillStyle=SEG_COLORS[i%SEG_COLORS.length]; ctx.fill();
            ctx.strokeStyle='#fff'; ctx.lineWidth=2; ctx.stroke();
            ctx.save(); ctx.translate(cx,cy); ctx.rotate(s+arc/2);
            ctx.textAlign='right'; ctx.fillStyle='#fff';
            ctx.font='bold '+Math.min(13,Math.max(8,Math.floor(200/n)))+'px Inter,sans-serif';
            ctx.fillText(p.name.length>13?p.name.slice(0,12)+'…':p.name, r-8, 5);
            ctx.restore();
        });
        ctx.beginPath(); ctx.arc(cx,cy,26,0,2*Math.PI); ctx.fillStyle='#fff'; ctx.fill();
        ctx.strokeStyle='#e2e8f0'; ctx.lineWidth=2; ctx.stroke();
        ctx.fillStyle='#1d4ed8'; ctx.font='bold 10px Inter,sans-serif'; ctx.textAlign='center';
        ctx.fillText('PUTAR',cx,cy+4);
    }

    function spinWheel() {
        if(isSpinning||!wheelQueue.length) return;
        isSpinning=true;
        var bs=document.getElementById('btn-spin'), ba=document.getElementById('btn-spin-all');
        if(bs) bs.disabled=true; if(ba) ba.disabled=true;
        var total=2*Math.PI*(5+Math.random()*4), dur=3200, t0=null, a0=currentAngle;
        function ease(t){return 1-Math.pow(1-t,3);}
        function frame(ts){
            if(!t0) t0=ts;
            var p=Math.min((ts-t0)/dur,1);
            currentAngle=a0+total*ease(p); drawWheel();
            if(p<1){requestAnimationFrame(frame);return;}
            var n=wheelQueue.length, arc=2*Math.PI/n;
            var norm=((currentAngle%(2*Math.PI))+2*Math.PI)%(2*Math.PI);
            var ptr=(3*Math.PI/2-norm+2*Math.PI*10)%(2*Math.PI);
            var idx=Math.floor(ptr/arc)%n; if(idx<0) idx=0;
            assignToNextGroup(wheelQueue[idx]||wheelQueue[0]);
            isSpinning=false; if(bs) bs.disabled=false; if(ba) ba.disabled=false;
        }
        requestAnimationFrame(frame);
    }

    function assignToNextGroup(player) {
        var tgt=GROUP_NAMES[0], mn=Infinity;
        GROUP_NAMES.forEach(function(g){ var l=(groupPools[g]||[]).length; if(l<mn){mn=l;tgt=g;} });
        if(!groupPools[tgt]) groupPools[tgt]=[];
        groupPools[tgt].push(player);
        wheelQueue=wheelQueue.filter(function(p){return String(p.id)!==String(player.id);});
        renderAllPools(); drawWheel(); updateQueueInfo(); showSpinResult(player,tgt);
    }

    function showSpinResult(player,group){
        var el=document.getElementById('spin-result'); if(!el) return;
        var img=player.avatar?'<img src="'+player.avatar+'" style="width:26px;height:26px;border-radius:50%;object-fit:cover">':'';
        el.innerHTML='<div class="spin-badge">'+img+'<span style="font-weight:700">'+player.name+'</span>'
            +'<span style="background:#7c3aed;color:#fff;border-radius:20px;padding:2px 10px;font-size:11px">→ Grup '+group+'</span></div>';
    }

    function updateQueueInfo(){
        var n=wheelQueue.length, el=document.getElementById('spin-queue-info'), uc=document.getElementById('unassigned-count');
        if(el){el.textContent=n>0?'Sisa '+n+' peserta belum ditempatkan':'✅ Semua sudah ditempatkan!';el.style.color=n>0?'#64748b':'#16a34a';}
        if(uc) uc.textContent=n;
    }

    function spinAll(){
        if(isSpinning||!wheelQueue.length) return;
        var q=wheelQueue.slice();
        q.forEach(function(p,i){
            setTimeout(function(){
                var mx=Math.ceil(ALL_PLAYERS.length/GROUP_NAMES.length);
                var av=GROUP_NAMES.filter(function(g){return (groupPools[g]||[]).length<mx;});
                if(!av.length) av=GROUP_NAMES.slice();
                var g=av[Math.floor(Math.random()*av.length)];
                if(!groupPools[g]) groupPools[g]=[];
                groupPools[g].push(p);
                wheelQueue=wheelQueue.filter(function(x){return String(x.id)!==String(p.id);});
                renderAllPools(); drawWheel(); updateQueueInfo(); showSpinResult(p,g);
            }, i*250);
        });
    }

    function resetDraw(){
        currentAngle=0; GROUP_NAMES.forEach(function(g){groupPools[g]=[];}); wheelQueue=ALL_PLAYERS.slice();
        renderAllPools(); drawWheel(); updateQueueInfo();
        var sr=document.getElementById('spin-result'); if(sr) sr.innerHTML='';
        var ss=document.getElementById('save-status'); if(ss) ss.innerHTML='';
    }

    function renderAllPools(){
        var up=document.getElementById('pool-unassigned');
        if(up){up.innerHTML=''; wheelQueue.forEach(function(p){up.appendChild(makeChip(p,'unassigned'));});}
        GROUP_NAMES.forEach(function(g){
            var pool=document.getElementById('pool-'+g); if(!pool) return;
            pool.innerHTML=''; (groupPools[g]||[]).forEach(function(p){pool.appendChild(makeChip(p,g));});
            var badge=document.querySelector('.group-count[data-group="'+g+'"]');
            if(badge) badge.textContent='('+(groupPools[g]||[]).length+')';
        });
        var uc=document.getElementById('unassigned-count'); if(uc) uc.textContent=wheelQueue.length;
    }

    function makeChip(player,poolId){
        var d=document.createElement('div');
        d.className='player-chip'; d.draggable=true;
        d.dataset.uid=String(player.id); d.dataset.name=player.name; d.dataset.pool=poolId;
        var fb='https://ui-avatars.com/api/?name='+encodeURIComponent(player.name)+'&background=1d4ed8&color=fff&size=64';
        var src=player.avatar||fb;
        d.innerHTML='<img src="'+src+'" alt="" onerror="this.src=\''+fb+'\'">'+player.name;
        return d;
    }

    document.addEventListener('dragstart',function(e){
        var chip=e.target.closest?e.target.closest('.player-chip'):null; if(!chip) return;
        dragUID=chip.dataset.uid;
        var pool=chip.closest?chip.closest('.drag-pool'):null;
        dragFrom=pool?(pool.dataset.group||'unassigned'):'unassigned';
        chip.classList.add('dragging'); e.dataTransfer.effectAllowed='move';
        try{e.dataTransfer.setData('text/plain',dragUID);}catch(ex){}
    });
    document.addEventListener('dragend',function(e){
        var chip=e.target.closest?e.target.closest('.player-chip'):null;
        if(chip) chip.classList.remove('dragging');
    });

    function setupDropZones(){
        document.querySelectorAll('.drag-pool').forEach(function(pool){
            pool.addEventListener('dragover',function(e){e.preventDefault();pool.classList.add('drag-over');});
            pool.addEventListener('dragleave',function(e){if(!pool.contains(e.relatedTarget)) pool.classList.remove('drag-over');});
            pool.addEventListener('drop',function(e){
                e.preventDefault(); pool.classList.remove('drag-over');
                var uid=dragUID; try{var d=e.dataTransfer.getData('text/plain');if(d)uid=d;}catch(ex){}
                if(!uid) return;
                var tgt=pool.dataset.group||'unassigned';
                if(tgt===dragFrom) return;
                var player=null; ALL_PLAYERS.forEach(function(p){if(String(p.id)===String(uid))player=p;});
                if(!player) return;
                if(dragFrom==='unassigned'){wheelQueue=wheelQueue.filter(function(p){return String(p.id)!==String(uid);});}
                else{groupPools[dragFrom]=(groupPools[dragFrom]||[]).filter(function(p){return String(p.id)!==String(uid);});}
                if(tgt==='unassigned'){wheelQueue.push(player);}
                else{if(!groupPools[tgt])groupPools[tgt]=[];groupPools[tgt].push(player);}
                dragUID=null; dragFrom=null; renderAllPools(); drawWheel(); updateQueueInfo();
            });
        });
    }

    function saveGroups(){
        if(wheelQueue.length>0 && !confirm(wheelQueue.length+' peserta belum ditempatkan. Tetap simpan?')) return;
        var inv=GROUP_NAMES.filter(function(g){return (groupPools[g]||[]).length<2;});
        if(inv.length){alert('Grup '+inv.join(', ')+' minimal harus 2 pemain.');return;}
        var payload={};
        GROUP_NAMES.forEach(function(g){payload[g]=(groupPools[g]||[]).map(function(p){return p.id;});});
        var btn=document.getElementById('btn-save-groups'), ss=document.getElementById('save-status');
        btn.disabled=true; btn.innerHTML='<i class="ti ti-loader"></i> Menyimpan...';
        fetch(ASSIGN_URL,{method:'POST',headers:{'Content-Type':'application/json','X-CSRF-TOKEN':CSRF_TOKEN},body:JSON.stringify({groups:payload})})
        .then(function(r){if(!r.ok)throw new Error('HTTP '+r.status);return r.json();})
        .then(function(data){
            if(!data.ok)throw new Error('Server error');
            if(ss) ss.innerHTML='<span style="color:#16a34a;font-weight:700"><i class="ti ti-circle-check"></i> Grup berhasil disimpan!</span>';
            btn.innerHTML='<i class="ti ti-check"></i> Tersimpan!';
            setTimeout(function(){location.reload();},1200);
        })
        .catch(function(err){
            if(ss) ss.innerHTML='<span style="color:#dc2626">❌ Gagal: '+err.message+'</span>';
            btn.disabled=false; btn.innerHTML='<i class="ti ti-device-floppy"></i> Simpan & Buat Jadwal';
        });
    }

    if(IS_LIVE) setInterval(function(){location.reload();},15000);

    /* ══ Match Detail Modal ══ */
    window.showMatchDetail = function showMatchDetail(data) {
        var p1name = data.p1 || 'TBD';
        var p2name = data.p2 || 'TBD';
        var fb1 = 'https://ui-avatars.com/api/?name='+encodeURIComponent(p1name)+'&background=1d4ed8&color=fff&size=80';
        var fb2 = 'https://ui-avatars.com/api/?name='+encodeURIComponent(p2name)+'&background=7c3aed&color=fff&size=80';

        document.getElementById('ko-modal-round').textContent    = data.round || '';
        document.getElementById('ko-modal-p1-avatar').src        = data.p1avatar || fb1;
        document.getElementById('ko-modal-p2-avatar').src        = data.p2avatar || fb2;
        document.getElementById('ko-modal-p1-name').textContent  = p1name;
        document.getElementById('ko-modal-p2-name').textContent  = p2name;
        document.getElementById('ko-modal-winner-name').textContent = data.winner || '?';

        var p1Win = data.winner_id && data.winner_id === data.p1_id;
        var p2Win = data.winner_id && data.winner_id === data.p2_id;
        var isDraw = !data.winner_id && (data.legs||[]).some(function(l){return l.is_draw;});
        document.getElementById('ko-modal-p1-badge').innerHTML = p1Win ? '<span style="background:#f0fdf4;color:#15803d;padding:2px 8px;border-radius:20px;font-weight:700;font-size:11px">Menang 🏆</span>' : (isDraw?'<span style="background:#fef9c3;color:#854d0e;padding:2px 8px;border-radius:20px;font-weight:700;font-size:11px">Seri</span>':'');
        document.getElementById('ko-modal-p2-badge').innerHTML = p2Win ? '<span style="background:#f0fdf4;color:#15803d;padding:2px 8px;border-radius:20px;font-weight:700;font-size:11px">Menang 🏆</span>' : '';
        document.getElementById('ko-modal-p1-avatar').style.borderColor = p1Win ? '#16a34a' : '#e2e8f0';
        document.getElementById('ko-modal-p2-avatar').style.borderColor = p2Win ? '#16a34a' : '#e2e8f0';

        /* Bans */
        var bansP1 = data.bans_p1 || [], bansP2 = data.bans_p2 || [];
        var banSec = document.getElementById('ko-modal-bans');
        if (bansP1.length || bansP2.length) {
            banSec.style.display = '';
            document.getElementById('ko-modal-ban-p1-label').textContent = p1name + ' Ban:';
            document.getElementById('ko-modal-ban-p2-label').textContent = p2name + ' Ban:';
            function banHtml(list) {
                if (!list.length) return '<div style="font-size:11px;color:#94a3b8;font-style:italic">Tidak ada ban</div>';
                return list.map(function(b) {
                    var logo = b.logo ? '<img src="'+b.logo+'" style="width:20px;height:20px;object-fit:contain;border-radius:4px;flex-shrink:0;background:#fff" onerror="this.style.display=\'none\'">' : '';
                    var legBadge = b.leg ? '<span style="font-size:9px;color:#7c3aed;font-weight:700;margin-left:3px;background:#faf5ff;padding:1px 4px;border-radius:3px">L'+b.leg+'</span>' : '';
                    return '<div style="display:flex;align-items:center;gap:6px;padding:6px 10px;background:#fff5f5;border:1px solid #fecaca;border-radius:8px">'
                        + logo + '<span style="font-size:12px;font-weight:600;color:#dc2626;flex:1">🚫 ' + b.name + '</span>' + legBadge + '</div>';
                }).join('');
            }
            document.getElementById('ko-modal-bans-p1').innerHTML = banHtml(bansP1);
            document.getElementById('ko-modal-bans-p2').innerHTML = banHtml(bansP2);
        } else {
            banSec.style.display = 'none';
        }

        /* Legs */
        var legs = data.legs || [];
        function clubChip(club, side) {
            if (!club) return '<span style="font-size:10px;color:#94a3b8;font-style:italic">—</span>';
            var logo = club.logo ? '<img src="'+club.logo+'" style="width:18px;height:18px;object-fit:contain;border-radius:4px;flex-shrink:0;background:#fff" onerror="this.style.display=\'none\'">' : '';
            var bg = side==='p1' ? '#eff6ff' : '#faf5ff';
            var cl = side==='p1' ? '#1d4ed8' : '#7c3aed';
            var br = side==='p1' ? '#bfdbfe' : '#ddd6fe';
            var ovr = club.overall ? '<span style="font-size:9px;color:#94a3b8;margin-left:2px">('+club.overall+')</span>' : '';
            return '<span style="display:inline-flex;align-items:center;gap:4px;padding:3px 8px;background:'+bg+';border:1px solid '+br+';border-radius:8px;font-size:11px;font-weight:600;color:'+cl+'">'
                + logo + '<span>' + club.name + ovr + '</span></span>';
        }
        function legBanRow(legBansP1, legBansP2, p1n, p2n) {
            if (!(legBansP1||[]).length && !(legBansP2||[]).length) return '';
            function miniChip(list, color) {
                return (list||[]).map(function(b){
                    var logo=b.logo?'<img src="'+b.logo+'" style="width:14px;height:14px;object-fit:contain;border-radius:3px;background:#fff" onerror="this.style.display=\'none\'">':'';
                    return '<span style="display:inline-flex;align-items:center;gap:2px;font-size:10px;font-weight:600;color:'+color+';background:#fff;padding:2px 5px;border-radius:4px;border:1px solid #fee2e2">'+logo+' 🚫 '+b.name+'</span>';
                }).join(' ');
            }
            return '<div style="padding:6px 10px;background:#fff8f8;border-top:1px solid #fee2e2;display:flex;gap:8px;flex-wrap:wrap;font-size:10px">'
                + (legBansP1&&legBansP1.length ? '<div style="display:flex;align-items:center;gap:3px"><span style="font-weight:700;color:#1d4ed8">'+p1n+':</span>'+miniChip(legBansP1,'#dc2626')+'</div>' : '')
                + (legBansP2&&legBansP2.length ? '<div style="display:flex;align-items:center;gap:3px"><span style="font-weight:700;color:#7c3aed">'+p2n+':</span>'+miniChip(legBansP2,'#dc2626')+'</div>' : '')
                + '</div>';
        }

        if (legs.length <= 1) {
            var leg = legs[0] || {};
            document.getElementById('ko-modal-score').textContent = (leg.score1??0) + ' – ' + (leg.score2??0);
            document.getElementById('ko-modal-score-sub').textContent = leg.is_draw ? 'Seri · 1 poin tiap pemain' : '';
            document.getElementById('ko-modal-legs').style.display = 'none';
            if (leg.club1 || leg.club2) {
                document.getElementById('ko-modal-p1-badge').innerHTML += '<div style="margin-top:6px">' + clubChip(leg.club1,'p1') + '</div>';
                document.getElementById('ko-modal-p2-badge').innerHTML += '<div style="margin-top:6px">' + clubChip(leg.club2,'p2') + '</div>';
            }
        } else {
            var tS1=0,tS2=0,tW1=0,tW2=0;
            legs.forEach(function(l){ tS1+=(l.score1||0);tS2+=(l.score2||0);if(l.winner_id===data.p1_id)tW1++;if(l.winner_id===data.p2_id)tW2++; });
            document.getElementById('ko-modal-score').textContent = tW1+' – '+tW2;
            document.getElementById('ko-modal-score-sub').textContent = 'Leg Wins · Agg Gol: '+tS1+'–'+tS2;

            var html='';
            legs.forEach(function(leg) {
                var w1=leg.winner_id===data.p1_id, w2=leg.winner_id===data.p2_id;
                var isGG=leg.is_gg, isDraw=leg.is_draw;
                var label = isGG ? '⚡ Golden Goal' : 'Leg '+leg.leg;
                var bg    = isGG ? '#fef9c3' : '#f8fafc';
                var res   = isDraw ? '<span style="color:#ca8a04;font-size:10px;font-weight:700;background:#fef9c3;padding:2px 6px;border-radius:4px">Seri</span>'
                          : (w1 ? '<span style="color:#16a34a;font-size:10px;font-weight:700;background:#f0fdf4;padding:2px 6px;border-radius:4px;white-space:nowrap">'+p1name+' ✓</span>'
                                : '<span style="color:#16a34a;font-size:10px;font-weight:700;background:#f0fdf4;padding:2px 6px;border-radius:4px;white-space:nowrap">'+p2name+' ✓</span>');

                html += '<div style="background:'+bg+';border:1px solid #e2e8f0;border-radius:10px;overflow:hidden">';
                html += '<div style="display:flex;align-items:center;gap:8px;padding:8px 12px;border-bottom:1px solid #f1f5f9">';
                html += '<span style="font-size:11px;font-weight:700;color:#64748b;min-width:48px">'+label+'</span>';
                html += '<span style="font-size:16px;font-weight:900;color:#0f172a;flex:1;text-align:center">'+(leg.score1||0)+' – '+(leg.score2||0)+'</span>';
                html += res+'</div>';
                if (leg.club1||leg.club2) {
                    html += '<div style="display:flex;align-items:center;gap:6px;padding:8px 12px;background:#fefefe;border-bottom:1px solid #f1f5f9">';
                    html += '<div style="flex:1">' + clubChip(leg.club1,'p1') + '</div>';
                    html += '<span style="font-size:9px;color:#94a3b8;font-weight:700;text-transform:uppercase">VS</span>';
                    html += '<div style="flex:1;text-align:right">' + clubChip(leg.club2,'p2') + '</div>';
                    html += '</div>';
                }
                html += legBanRow(leg.bans_p1, leg.bans_p2, p1name, p2name);
                html += '</div>';
            });
            document.getElementById('ko-modal-legs-list').innerHTML = html;
            document.getElementById('ko-modal-legs').style.display = '';
        }

        document.getElementById('ko-match-modal').style.display = 'block';
        document.body.style.overflow = 'hidden';
    }

    window.closeMatchModal = function closeMatchModal() {
        document.getElementById('ko-match-modal').style.display = 'none';
        document.body.style.overflow = '';
    }
    document.addEventListener('keydown', function(e){ if(e.key==='Escape') window.closeMatchModal(); });

    /* ── Admin bracket swipe hint ── */
    (function(){
        var container = document.getElementById('admin-bracket-container');
        var hint = document.querySelector('.admin-bracket-swipe-hint');
        if (!container || !hint) return;
        // Show hint on mobile
        if (window.innerWidth < 768) hint.style.display = 'block';
        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 */
        var t;
        container.addEventListener('scroll', function(){
            clearTimeout(t);
            t = setTimeout(drawBracketConnectors, 80);
        }, { passive: true });
    })();

    /* ══ Bracket connectors — draw after flexbox layout ══ */
    function drawBracketConnectors() {
        var wrap = document.getElementById('ko-bracket-wrap');
        if (!wrap) return;

        // Remove old connectors
        wrap.querySelectorAll('.ko-svg-conn').forEach(function(e){ e.remove(); });

        var rounds = wrap.querySelectorAll('.ko-round');
        if (rounds.length < 2) return;

        // Create one overlay SVG covering the entire bracket
        var wRect = wrap.getBoundingClientRect();
        var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
        svg.classList.add('ko-svg-conn');
        svg.setAttribute('style',
            'position:absolute;top:0;left:0;width:100%;height:100%;pointer-events:none;overflow:visible;z-index:0');
        wrap.style.position = 'relative';
        wrap.insertBefore(svg, wrap.firstChild);

        for (var ri = 0; ri < rounds.length - 1; ri++) {
            var col     = rounds[ri];
            var colRect = col.getBoundingClientRect();

            // Get match slots from this round
            var slots = col.querySelectorAll('.ko-match-slot');
            var nextSlots = rounds[ri + 1].querySelectorAll('.ko-match-slot');

            for (var si = 0; si < slots.length; si += 2) {
                var slotA = slots[si];
                var slotB = slots[si + 1];
                var nextSlot = nextSlots[Math.floor(si / 2)];
                if (!slotA || !nextSlot) continue;

                var cardA = slotA.querySelector('.ko-card');
                var cardB = slotB ? slotB.querySelector('.ko-card') : null;
                var cardN = nextSlot.querySelector('.ko-card');
                if (!cardA || !cardN) continue;

                var rA = cardA.getBoundingClientRect();
                var rB = cardB ? cardB.getBoundingClientRect() : rA;
                var rN = cardN.getBoundingClientRect();

                // Convert to wrap-relative coords
                var yA   = rA.top - wRect.top + rA.height / 2;
                var yB   = cardB ? (rB.top - wRect.top + rB.height / 2) : yA;
                var yN   = rN.top - wRect.top + rN.height / 2;
                var xR   = rA.right - wRect.left;        // right edge of card A (and B)
                var xNL  = rN.left  - wRect.left;        // left edge of next card
                var xMid = xR + (xNL - xR) / 2;         // midpoint in the gap

                // Draw: card A right → midX, then midX → midY (between A and B), then → next card left
                var yMid = (yA + yB) / 2;

                var d = 'M'+xR+','+yA
                    + ' L'+xMid+','+yA
                    + ' L'+xMid+','+yMid;

                if (cardB) {
                    d += ' M'+xR+','+yB
                       + ' L'+xMid+','+yB
                       + ' L'+xMid+','+yMid;
                }

                d += ' M'+xMid+','+yMid+' L'+xNL+','+yMid;

                var path = document.createElementNS('http://www.w3.org/2000/svg','path');
                path.setAttribute('d', d);
                path.setAttribute('fill', 'none');
                path.setAttribute('stroke', '#cbd5e1');
                path.setAttribute('stroke-width', '1.5');
                path.setAttribute('stroke-linecap', 'round');
                path.setAttribute('stroke-linejoin', 'round');
                svg.appendChild(path);
            }
        }
    }

    // Draw connectors after DOM renders
    if (document.readyState === 'complete') {
        setTimeout(drawBracketConnectors, 200);
    } else {
        window.addEventListener('load', function(){ setTimeout(drawBracketConnectors, 200); });
    }
    // Redraw on tab switch
    var origSwitchTabKO = window.switchTabKO;
    window.switchTabKO = function(tab) {
        if (origSwitchTabKO) origSwitchTabKO(tab);
        if (tab === 'bracket') setTimeout(drawBracketConnectors, 100);
    };

    function boot(){
        if(!IS_GROUP_KO){
            // Knockout-only: init KO draw wheel
            koInitDraw();
            try{var sv=localStorage.getItem('koTab_'+TOUR_ID);if(sv){switchTabKO(sv);return;}}catch(e){}
            switchTabKO('draw');
            return;
        }        GROUP_NAMES.forEach(function(g){groupPools[g]=[];}); wheelQueue=ALL_PLAYERS.slice();
        renderAllPools(); drawWheel(); updateQueueInfo(); setupDropZones();
        try{var sv=localStorage.getItem('bTab_'+TOUR_ID);if(sv){switchTab(sv);return;}}catch(e){}
        switchTab('draw');
    }
    if(document.readyState==='loading'){document.addEventListener('DOMContentLoaded',boot);}else{boot();}

    /* ══════════════════════════════════════════════════════════
       KNOCKOUT DRAW — roulette wheel untuk seeding bracket
    ══════════════════════════════════════════════════════════ */
    var koQueue   = [];   // players not yet seeded
    var koSeeds   = [];   // ordered seed list (index 0 = seed 1)
    var koSpin    = false;
    var koAngle   = 0;
    var KO_COLORS = ['#6366f1','#8b5cf6','#ec4899','#f59e0b','#10b981','#3b82f6','#ef4444','#14b8a6','#f97316','#a78bfa','#34d399','#f472b6'];

    function switchTabKO(tab) {
        var secs = {'draw':'section-ko-draw','bracket':'section-knockout'};
        var tabs = {'draw':'kotab-draw','bracket':'kotab-bracket'};
        Object.keys(secs).forEach(function(t) {
            var s = document.getElementById(secs[t]);
            var b = document.getElementById(tabs[t]);
            if (s) s.style.display = t === tab ? '' : 'none';
            if (b) b.className   = t === tab ? 'btn-pes-primary' : 'btn-pes-secondary';
        });
        if (tab === 'bracket') setTimeout(drawBracketConnectors, 150);
        try{ localStorage.setItem('koTab_'+TOUR_ID, tab); }catch(e){}
    }

    function koInitDraw() {
        koQueue  = ALL_PLAYERS.slice();
        koSeeds  = [];
        koAngle  = 0;
        koRenderSeedList();
        koDrawWheel();
        koUpdateInfo();
    }

    function koDrawWheel() {
        var cv = document.getElementById('ko-wheel-canvas');
        if (!cv) return;
        var ctx = cv.getContext('2d'), cx = cv.width/2, cy = cv.height/2, r = cx - 8;
        ctx.clearRect(0, 0, cv.width, cv.height);
        if (!koQueue.length) {
            ctx.fillStyle='#f0fdf4'; ctx.beginPath(); ctx.arc(cx,cy,r,0,2*Math.PI); ctx.fill();
            ctx.fillStyle='#16a34a'; ctx.font='bold 13px Inter,sans-serif'; ctx.textAlign='center';
            ctx.fillText('Semua sudah', cx, cy-6); ctx.fillText('diundi!', cx, cy+12);
            return;
        }
        var n = koQueue.length, arc = 2*Math.PI/n;
        koQueue.forEach(function(p, i) {
            var s = koAngle + i*arc - Math.PI/2, e = s + arc;
            ctx.beginPath(); ctx.moveTo(cx,cy); ctx.arc(cx,cy,r,s,e); ctx.closePath();
            ctx.fillStyle = KO_COLORS[i % KO_COLORS.length]; ctx.fill();
            ctx.strokeStyle='#fff'; ctx.lineWidth=2; ctx.stroke();
            ctx.save(); ctx.translate(cx,cy); ctx.rotate(s+arc/2);
            ctx.textAlign='right'; ctx.fillStyle='#fff';
            ctx.font = 'bold '+Math.min(13,Math.max(8,Math.floor(200/n)))+'px Inter,sans-serif';
            var label = p.name.length > 13 ? p.name.slice(0,12)+'…' : p.name;
            ctx.fillText(label, r-8, 5);
            ctx.restore();
        });
        ctx.beginPath(); ctx.arc(cx,cy,24,0,2*Math.PI); ctx.fillStyle='#fff'; ctx.fill();
        ctx.strokeStyle='#e2e8f0'; ctx.lineWidth=2; ctx.stroke();
        ctx.fillStyle='#1d4ed8'; ctx.font='bold 9px Inter,sans-serif'; ctx.textAlign='center';
        ctx.fillText('PUTAR', cx, cy+4);
    }

    function koSpinWheel() {
        if (koSpin || !koQueue.length) return;
        koSpin = true;
        var bs = document.getElementById('ko-btn-spin'), ba = document.getElementById('ko-btn-spin-all');
        if (bs) bs.disabled=true; if (ba) ba.disabled=true;
        var total = 2*Math.PI*(5+Math.random()*4), dur = 3200, t0 = null, a0 = koAngle;
        function ease(t){ return 1-Math.pow(1-t,3); }
        function frame(ts) {
            if (!t0) t0=ts;
            var p = Math.min((ts-t0)/dur, 1);
            koAngle = a0 + total*ease(p); koDrawWheel();
            if (p < 1){ requestAnimationFrame(frame); return; }
            var n = koQueue.length, arc = 2*Math.PI/n;
            var norm = ((koAngle%(2*Math.PI))+2*Math.PI)%(2*Math.PI);
            var ptr  = (3*Math.PI/2-norm+2*Math.PI*10)%(2*Math.PI);
            var idx  = Math.floor(ptr/arc)%n; if (idx<0) idx=0;
            koAssignSeed(koQueue[idx] || koQueue[0]);
            koSpin=false; if(bs)bs.disabled=false; if(ba)ba.disabled=false;
        }
        requestAnimationFrame(frame);
    }

    function koAssignSeed(player) {
        koSeeds.push(player);
        koQueue = koQueue.filter(function(p){ return String(p.id) !== String(player.id); });
        koRenderSeedList();
        koDrawWheel();
        koUpdateInfo();
        koShowResult(player, koSeeds.length);
        koUpdatePreview();
        // Update undrawn pool chips
        var pool = document.getElementById('ko-pool-undrawn');
        if (pool) {
            pool.querySelectorAll('.ko-chip').forEach(function(c) {
                c.style.display = koQueue.some(function(p){ return String(p.id)===c.dataset.uid; }) ? '' : 'none';
            });
        }
        var cnt = document.getElementById('ko-undrawn-count');
        if (cnt) cnt.textContent = koQueue.length;
    }

    function koShowResult(player, seedNum) {
        var el = document.getElementById('ko-spin-result'); if (!el) return;
        var img = player.avatar ? '<img src="'+player.avatar+'" style="width:26px;height:26px;border-radius:50%;object-fit:cover">' : '';
        el.innerHTML = '<div class="spin-badge">'
            + img + '<span style="font-weight:700">'+player.name+'</span>'
            + '<span style="background:#1d4ed8;color:#fff;border-radius:20px;padding:2px 10px;font-size:11px">Seed '+seedNum+'</span>'
            + '</div>';
    }

    function koUpdateInfo() {
        var n = koQueue.length;
        var el = document.getElementById('ko-spin-queue-info');
        var cnt = document.getElementById('ko-undrawn-count');
        if (el) { el.textContent = n>0 ? 'Sisa '+n+' peserta belum diundi' : '✅ Semua sudah diundi!'; el.style.color=n>0?'#64748b':'#16a34a'; }
        if (cnt) cnt.textContent = n;
    }

    function koSpinAll() {
        if (koSpin || !koQueue.length) return;
        var q = koQueue.slice();
        q.forEach(function(p, i) {
            setTimeout(function(){ koAssignSeed(p); }, i*220);
        });
    }

    function koResetDraw() {
        koInitDraw();
        var pool = document.getElementById('ko-pool-undrawn');
        if (pool) pool.querySelectorAll('.ko-chip').forEach(function(c){ c.style.display=''; });
        var sr = document.getElementById('ko-spin-result'); if (sr) sr.innerHTML='';
        var ss = document.getElementById('ko-save-status'); if (ss) ss.innerHTML='';
        document.getElementById('ko-preview-section').style.display='none';
    }

    function koRenderSeedList() {
        var list = document.getElementById('ko-seed-list'); if (!list) return;
        if (!koSeeds.length) {
            list.innerHTML = '<div style="text-align:center;padding:24px;color:#94a3b8;font-size:13px">Putar roda untuk memulai undian...</div>';
            return;
        }
        var html = '';
        koSeeds.forEach(function(p, i) {
            var seed = i+1;
            var opponent = koSeeds[koSeeds.length - seed]; // mirror seed
            var totalPlayers = ALL_PLAYERS.length;
            var nextPow2 = 1; while(nextPow2 < totalPlayers) nextPow2 *= 2;
            var mirrorSeed = nextPow2 + 1 - seed; // e.g. seed1 vs seed16 in 16-player bracket
            var fb = 'https://ui-avatars.com/api/?name='+encodeURIComponent(p.name)+'&background=1d4ed8&color=fff&size=64';
            var src = p.avatar || fb;
            html += '<div style="display:flex;align-items:center;gap:10px;padding:8px 12px;background:'+(seed===1?'#fefce8':(seed%2===1?'#f8fafc':'#fff'))+';border:1px solid #e2e8f0;border-radius:10px">';
            html += '<div style="width:28px;height:28px;background:'+(seed<=4?'#fde68a':'#f1f5f9')+';color:'+(seed<=4?'#92400e':'#64748b')+';border-radius:8px;display:flex;align-items:center;justify-content:center;font-size:11px;font-weight:800;flex-shrink:0">';
            html += seed + '</div>';
            html += '<img src="'+src+'" onerror="this.src=\''+fb+'\'" style="width:28px;height:28px;border-radius:8px;object-fit:cover;flex-shrink:0">';
            html += '<span style="flex:1;font-size:13px;font-weight:600;color:#0f172a">'+p.name+'</span>';
            html += '<span style="font-size:10px;color:#94a3b8">Seed '+seed+'</span>';
            html += '</div>';
        });
        list.innerHTML = html;
    }

    function koUpdatePreview() {
        var totalPlayers = ALL_PLAYERS.length;
        var nextPow2 = 1; while(nextPow2 < totalPlayers) nextPow2 *= 2;
        var preview = document.getElementById('ko-preview-section');
        var matchDiv = document.getElementById('ko-matchup-preview');
        if (koSeeds.length < totalPlayers) {
            preview.style.display='none'; return;
        }
        // Build bracket positions using same algorithm as PHP service
        var slots = koBuildSeedPositions(nextPow2);
        var bracket = new Array(nextPow2).fill(null);
        for (var i=0; i<koSeeds.length && i<slots.length; i++) {
            bracket[slots[i]] = koSeeds[i];
        }
        var html = '';
        for (var m=0; m<nextPow2/2; m++) {
            var p1 = bracket[m*2];
            var p2 = bracket[m*2+1];
            var n1 = p1 ? p1.name : 'BYE';
            var n2 = p2 ? p2.name : 'BYE';
            var s1 = koSeeds.indexOf(p1)+1;
            var s2 = koSeeds.indexOf(p2)+1;
            html += '<div style="display:flex;align-items:center;gap:8px;padding:6px 10px;background:#f8fafc;border-radius:8px;border:1px solid #e2e8f0">';
            html += '<span style="font-size:10px;font-weight:700;color:#1d4ed8;width:14px">'+(m+1)+'.</span>';
            html += '<span style="font-size:12px;font-weight:600;flex:1">'+n1+'</span>';
            html += '<span style="font-size:10px;color:#94a3b8;background:#e2e8f0;padding:1px 6px;border-radius:20px">Seed '+s1+' vs '+s2+'</span>';
            html += '<span style="font-size:12px;font-weight:600;flex:1;text-align:right">'+n2+'</span>';
            html += '</div>';
        }
        matchDiv.innerHTML = html;
        preview.style.display='';
    }

    function koBuildSeedPositions(size) {
        var slots = [0, 1];
        while (slots.length < size) {
            var newSlots = [];
            var half = slots.length * 2;
            slots.forEach(function(slot) {
                newSlots.push(slot * 2);
                newSlots.push(half - 1 - slot * 2);
            });
            slots = newSlots;
        }
        return slots.slice(0, size);
    }

    function koSaveDraw() {
        if (koQueue.length > 0 && !confirm(koQueue.length+' peserta belum diundi. Sisa akan diacak otomatis.\nLanjutkan?')) return;
        // Auto-fill remaining
        if (koQueue.length > 0) {
            var remaining = koQueue.slice();
            remaining.sort(function(){ return Math.random()-0.5; });
            remaining.forEach(function(p){ koSeeds.push(p); });
            koQueue = [];
        }
        var seedIds = koSeeds.map(function(p){ return p.id; });
        var btn = document.getElementById('ko-btn-save');
        var ss  = document.getElementById('ko-save-status');
        btn.disabled = true; btn.innerHTML = '<i class="ti ti-loader"></i> Menyimpan...';
        var csrf = (document.querySelector('meta[name="csrf-token"]')||{}).content || '';
        fetch(KO_DRAW_URL, {
            method: 'POST',
            headers: { 'Content-Type':'application/json', 'X-CSRF-TOKEN': csrf },
            body: JSON.stringify({ seeds: seedIds })
        })
        .then(function(r){ if(!r.ok) throw new Error('HTTP '+r.status); return r.json(); })
        .then(function(data) {
            if (!data.ok) throw new Error('Server error');
            if (ss) ss.innerHTML = '<span style="color:#16a34a;font-weight:700"><i class="ti ti-check"></i> Bracket berhasil dibuat!</span>';
            btn.innerHTML = '<i class="ti ti-check"></i> Tersimpan!';
            setTimeout(function(){ location.reload(); }, 1200);
        })
        .catch(function(err) {
            if (ss) ss.innerHTML = '<span style="color:#dc2626">❌ Gagal: '+err.message+'</span>';
            btn.disabled = false; btn.innerHTML = '<i class="ti ti-device-floppy"></i> Simpan & Buat Bracket';
        });
    }
    </script>
    @endpush
</x-app-layout>
