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

    <!-- Breadcrumb + actions -->
    <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 ke Daftar
            </a>
            <div style="font-size:20px;font-weight:800;color:#0f172a;font-family:'Plus Jakarta Sans',sans-serif;margin-top:6px">
                <i class="ti ti-medal" style="color:#1d4ed8"></i> {{ $tournament->title }}
            </div>
        </div>
        <div class="d-flex gap-2 flex-wrap">
            <a href="{{ route('admin.tournament.bracket', $tournament->id) }}" class="btn-pes-primary" style="text-decoration:none;font-size:13px">
                <i class="ti ti-tournament"></i> Kelola Bracket
            </a>
            <a href="{{ route('admin.tournaments.edit', $tournament->id) }}" class="btn-pes-secondary" style="text-decoration:none;font-size:13px">
                <i class="ti ti-edit"></i> Edit
            </a>
            <form method="POST" action="{{ route('admin.tournaments.destroy', $tournament->id) }}"
                  onsubmit="return confirm('Hapus turnamen ini beserta semua data bracket dan pesertanya?')">
                @csrf @method('DELETE')
                <button type="submit" class="btn-pes-ghost" style="font-size:13px;color:#ef4444;border:1px solid #fecaca">
                    <i class="ti ti-trash"></i> Hapus
                </button>
            </form>
        </div>
    </div>

    <!-- Status + quick-change -->
    <div class="pes-card p-4 mb-4">
        <div class="d-flex align-items-center justify-content-between flex-wrap gap-3">
            <div class="d-flex align-items-center gap-3 flex-wrap">
                @php $ss = match($tournament->status) {
                    'registration'=>'background:#f0fdf4;color:#15803d',
                    'in_progress' =>'background:#eff6ff;color:#1d4ed8',
                    'completed'   =>'background:#f1f5f9;color:#64748b',
                    default       =>'background:#fef9c3;color:#ca8a04'
                }; @endphp
                <span style="padding:5px 14px;border-radius:20px;font-size:12px;font-weight:700;{{ $ss }}">
                    {{ ucfirst(str_replace('_',' ',$tournament->status)) }}
                </span>
                <span style="font-size:12px;color:#64748b">
                    {{ $tournament->format === 'group_knockout' ? '⚽ Group + Knockout' : '🏆 Knockout' }}
                </span>
                @if($tournament->format === 'group_knockout')
                <span style="font-size:12px;color:#64748b">
                    · Fase: <strong>{{ ucfirst($tournament->current_phase) }}</strong>
                </span>
                @endif
            </div>
            <!-- Quick status change -->
            <form method="POST" action="{{ route('admin.tournaments.update', $tournament->id) }}" class="d-flex align-items-center gap-2">
                @csrf @method('PATCH')
                <select name="status" class="pes-input" style="width:auto;padding:6px 12px;font-size:12px">
                    @foreach(['draft'=>'Draft','registration'=>'Registrasi','in_progress'=>'Berlangsung','completed'=>'Selesai','cancelled'=>'Dibatalkan'] as $v=>$l)
                    <option value="{{ $v }}" {{ $tournament->status === $v ? 'selected' : '' }}>{{ $l }}</option>
                    @endforeach
                </select>
                <button type="submit" class="btn-pes-secondary" style="font-size:12px">
                    <i class="ti ti-check"></i> Ubah Status
                </button>
            </form>
        </div>
    </div>

    <div class="row g-4">
        <!-- Info detail -->
        <div class="col-lg-8">
            <!-- Main info -->
            <div class="pes-card mb-4">
                <div class="pes-card-header">
                    <div class="pes-card-header-left">
                        <div class="pes-card-icon" style="background:#eff6ff;color:#1d4ed8"><i class="ti ti-info-circle"></i></div>
                        <span class="pes-card-title">Informasi Turnamen</span>
                    </div>
                </div>
                <div class="pes-card-body">
                    @foreach([
                        ['Nama',         $tournament->title],
                        ['Deskripsi',    $tournament->description ?? '—'],
                        ['Hadiah',       $tournament->prize ?? '—'],
                        ['Format',       $tournament->format === 'group_knockout' ? 'Group + Knockout' : 'Knockout'],
                        ['Maks Pemain',  $tournament->max_players],
                        ['Dibuat oleh',  $tournament->creator?->username ?? '—'],
                        ['Dibuat pada',  $tournament->created_at->format('d M Y H:i')],
                        ['Reg. Dibuka',  $tournament->registration_opens_at?->format('d M Y H:i') ?? '—'],
                        ['Reg. Ditutup', $tournament->registration_closes_at?->format('d M Y H:i') ?? '—'],
                        ['Mulai',        $tournament->starts_at?->format('d M Y H:i') ?? '—'],
                    ] as [$label, $value])
                    <div class="d-flex gap-3 py-2" style="border-bottom:1px solid #f8fafc;font-size:13px">
                        <span style="color:#64748b;min-width:120px;flex-shrink:0">{{ $label }}</span>
                        <span style="color:#0f172a;font-weight:500">{{ $value }}</span>
                    </div>
                    @endforeach
                    @if($tournament->format === 'group_knockout')
                    <div class="d-flex gap-3 py-2" style="border-bottom:1px solid #f8fafc;font-size:13px">
                        <span style="color:#64748b;min-width:120px;flex-shrink:0">Jumlah Grup</span>
                        <span style="color:#0f172a;font-weight:500">{{ $tournament->group_count }} grup, {{ $tournament->groups_per_advance }} lolos per grup</span>
                    </div>
                    @endif
                    @php
                        $boCfgS  = $tournament->bo_config  ?? [];
                        $banCfgS = $tournament->ban_config ?? [];
                        $showGrp = $tournament->format === 'group_knockout';
                        $boRows  = array_filter([
                            $showGrp ? ['Grup',    $boCfgS['group']    ?? 1, $banCfgS['group']    ?? 0] : null,
                            ['Knockout', $boCfgS['knockout'] ?? 1, $banCfgS['knockout'] ?? 0],
                            ['Final',    $boCfgS['final']    ?? 1, $banCfgS['final']    ?? 0],
                        ]);
                    @endphp
                    @foreach($boRows as [$phLabel, $bov, $banv])
                    <div class="d-flex gap-3 py-2" style="border-bottom:1px solid #f8fafc;font-size:13px">
                        <span style="color:#64748b;min-width:120px;flex-shrink:0">{{ $phLabel }}</span>
                        <span style="color:#0f172a;font-weight:500;display:flex;align-items:center;gap:8px;flex-wrap:wrap">
                            <span style="background:#eff6ff;color:#1d4ed8;padding:1px 8px;border-radius:20px;font-size:11px;font-weight:700">
                                <i class="ti ti-repeat"></i> BO{{ $bov }}
                            </span>
                            @if($banv > 0)
                            <span style="background:#fff5f5;color:#dc2626;padding:1px 8px;border-radius:20px;font-size:11px;font-weight:700">
                                <i class="ti ti-ban"></i> Ban {{ $banv }} klub
                            </span>
                            @else
                            <span style="color:#94a3b8;font-size:11px">Bebas pilih tim</span>
                            @endif
                        </span>
                    </div>
                    @endforeach
                    <div class="d-flex gap-3 py-2" style="font-size:13px">
                        <span style="color:#64748b;min-width:120px;flex-shrink:0">Tiebreak BO2</span>
                        <span style="color:#0f172a;font-weight:500;display:flex;align-items:center;gap:6px">
                            @if($tournament->useAggregateTiebreak())
                            <span style="background:#eff6ff;color:#1d4ed8;padding:1px 8px;border-radius:20px;font-size:11px;font-weight:700">⚽ Agregat Gol</span>
                            <span style="font-size:11px;color:#64748b">→ gol sama = GG</span>
                            @else
                            <span style="background:#fef9c3;color:#854d0e;padding:1px 8px;border-radius:20px;font-size:11px;font-weight:700">⚡ Langsung Golden Goal</span>
                            @endif
                        </span>
                    </div>
                </div>
            </div>

            <!-- Rules -->
            @if($tournament->rules)
            <div class="pes-card mb-4">
                <div class="pes-card-header">
                    <div class="pes-card-header-left">
                        <div class="pes-card-icon" style="background:#fef9c3;color:#ca8a04"><i class="ti ti-file-text"></i></div>
                        <span class="pes-card-title">Peraturan</span>
                    </div>
                </div>
                <div class="pes-card-body">
                    <div style="font-size:13px;color:#475569;line-height:1.8;white-space:pre-line">{{ $tournament->rules }}</div>
                </div>
            </div>
            @endif

            <!-- Bracket summary -->
            @if(!empty($knockoutData))
            <div class="pes-card">
                <div class="pes-card-header">
                    <div class="pes-card-header-left">
                        <div class="pes-card-icon" style="background:#f3e8ff;color:#7c3aed"><i class="ti ti-tournament"></i></div>
                        <span class="pes-card-title">Bracket Knockout</span>
                    </div>
                    <a href="{{ route('admin.tournament.bracket', $tournament->id) }}"
                       class="btn-pes-ghost" style="font-size:12px;text-decoration:none">
                        Kelola <i class="ti ti-arrow-right"></i>
                    </a>
                </div>
                <div class="pes-card-body" style="overflow-x:auto">
                    <div style="display:flex;gap:0;min-width:max-content">
                        @php
                            $roundLabels = [];
                            foreach ($knockoutData as $r => $ms) {
                                $c = count($ms);
                                $roundLabels[$r] = match(true) {
                                    $c===1=>'Final', $c===2=>'Semi Final', $c===4=>'Perempat Final', default=>'Babak '.$r
                                };
                            }
                        @endphp
                        @foreach($knockoutData as $rn => $matches)
                        @php $isLast = $rn == array_key_last($knockoutData); @endphp
                        <div style="min-width:180px;margin-right:{{ $isLast?0:8 }}px">
                            <div style="font-size:10px;font-weight:700;color:#94a3b8;text-transform:uppercase;text-align:center;padding-bottom:8px">
                                {{ $roundLabels[$rn] }}
                            </div>
                            @foreach($matches as $m)
                            <div style="background:#fff;border:1.5px solid {{ $m->status==='completed'?'#bfdbfe':'#e2e8f0' }};border-radius:10px;overflow:hidden;margin-bottom:12px;font-size:11px">
                                @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; @endphp
                                <div style="padding:6px 10px;{{ !$loop->last?'border-bottom:1px solid #f1f5f9':''}};{{ $win?'background:#f0fdf4':'' }};display:flex;align-items:center;justify-content:space-between;gap:6px">
                                    <span style="color:{{ !$pid?'#94a3b8':($win?'#15803d':'#0f172a') }};font-weight:{{ $win?700:400 }};overflow:hidden;text-overflow:ellipsis;white-space:nowrap">
                                        {{ $pid ? ($player?->username ?? '?') : 'TBD' }}
                                    </span>
                                    @if($m->status==='completed')
                                    <span style="font-weight:800;color:{{ $win?'#15803d':'#94a3b8' }};flex-shrink:0">{{ $score??0 }}</span>
                                    @endif
                                </div>
                                @endforeach
                            </div>
                            @endforeach
                        </div>
                        @endforeach
                    </div>
                </div>
            </div>
            @endif
        </div>

        <!-- Sidebar: stats + participants -->
        <div class="col-lg-4 d-flex flex-column gap-4">
            <!-- Stats -->
            <div class="row g-3">
                @foreach([
                    ['Peserta',  $tournament->participants_count.'/'.$tournament->max_players, 'ti-users',    '#eff6ff','#1d4ed8'],
                    ['Matches',  \App\Models\TournamentMatch::where('tournament_id',$tournament->id)->count(), 'ti-ball-football', '#f0fdf4','#16a34a'],
                ] as [$l,$v,$ic,$bg,$c])
                <div class="col-6">
                    <div class="pes-stat" style="padding:14px">
                        <div class="pes-stat-icon" style="width:40px;height:40px;background:{{ $bg }};color:{{ $c }};font-size:18px"><i class="ti {{ $ic }}"></i></div>
                        <div>
                            <div style="font-size:15px;font-weight:800;color:#0f172a;font-family:'Plus Jakarta Sans',sans-serif">{{ $v }}</div>
                            <div style="font-size:10px;color:#64748b;text-transform:uppercase;font-weight:600">{{ $l }}</div>
                        </div>
                    </div>
                </div>
                @endforeach
            </div>

            <!-- Participants list -->
            <div class="pes-card flex-grow-1">
                <div class="pes-card-header">
                    <div class="pes-card-header-left">
                        <div class="pes-card-icon" style="background:#eff6ff;color:#1d4ed8"><i class="ti ti-users"></i></div>
                        <span class="pes-card-title">Peserta ({{ $tournament->participants_count }} / {{ $tournament->max_players }})</span>
                    </div>
                </div>

                <!-- Add participant form -->
                @if($tournament->participants_count < $tournament->max_players)
                <div style="padding:12px 16px;border-bottom:1px solid #f1f5f9;background:#fafbff">
                    <div style="font-size:11px;font-weight:700;color:#64748b;text-transform:uppercase;letter-spacing:.05em;margin-bottom:8px">
                        Tambah Peserta
                    </div>
                    <!-- Search filter -->
                    <input type="text" id="player-search"
                           placeholder="🔍  Ketik nama pemain..."
                           class="pes-input" style="font-size:12px;padding:8px 12px;margin-bottom:8px"
                           autocomplete="off" oninput="filterPlayers(this.value)">
                    <!-- Scrollable player list -->
                    <div id="player-list"
                         style="max-height:220px;overflow-y:auto;border:1.5px solid #e2e8f0;border-radius:10px;background:#fff">
                        @foreach($availableUsers as $u)
                        @php $ud = getDivision($u->elo ?? 1200); @endphp
                        <form method="POST" action="{{ route('admin.tournaments.participants.add', $tournament->id) }}"
                              class="player-row d-flex align-items-center gap-2 px-3 py-2"
                              style="border-bottom:1px solid #f8fafc;cursor:pointer;transition:background .1s"
                              data-name="{{ strtolower($u->username) }}"
                              onmouseover="this.style.background='#f0f7ff'"
                              onmouseout="this.style.background=''">
                            @csrf
                            <input type="hidden" name="user_id" value="{{ $u->id }}">
                            <img src="{{ $u->avatar ?? 'https://ui-avatars.com/api/?name='.urlencode($u->username).'&background=1d4ed8&color=fff&size=64' }}"
                                 style="width:30px;height:30px;border-radius:8px;object-fit:cover;flex-shrink:0"
                                 onerror="this.src='https://ui-avatars.com/api/?name={{ urlencode($u->username) }}&background=1d4ed8&color=fff&size=64'"
                                 alt="">
                            <div style="flex:1;min-width:0">
                                <div style="font-size:12px;font-weight:600;color:#0f172a;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">
                                    {{ $u->username }}
                                </div>
                                <div style="font-size:10px;font-weight:700;color:{{ $ud['cls'] === 'div-bronze'?'#92400e':($ud['cls']==='div-silver'?'#475569':($ud['cls']==='div-gold'?'#854d0e':($ud['cls']==='div-plat'?'#0369a1':($ud['cls']==='div-diamond'?'#1e40af':($ud['cls']==='div-master'?'#7c3aed':'#ca8a04'))))) }}">
                                    {{ $ud['icon'] }} {{ $ud['name'] }} · {{ number_format($u->elo ?? 1200) }} ELO
                                </div>
                            </div>
                            <button type="submit" class="btn-pes-primary" style="font-size:11px;padding:4px 10px;flex-shrink:0">
                                <i class="ti ti-plus"></i>
                            </button>
                        </form>
                        @endforeach
                        @if($availableUsers->isEmpty())
                        <div style="padding:20px;text-align:center;font-size:12px;color:#94a3b8">Semua pemain sudah terdaftar</div>
                        @endif
                    </div>
                    <div id="no-results" style="display:none;padding:14px;text-align:center;font-size:12px;color:#94a3b8;border:1.5px solid #e2e8f0;border-radius:10px;background:#fff">
                        Pemain tidak ditemukan
                    </div>
                </div>
                @else
                <div style="padding:10px 16px;background:#fef9c3;border-bottom:1px solid #fef08a;font-size:12px;color:#854d0e;font-weight:600">
                    <i class="ti ti-lock"></i> Turnamen sudah penuh ({{ $tournament->max_players }} pemain)
                </div>
                @endif

                <!-- Participant list -->
                <div style="max-height:420px;overflow-y:auto">
                    @forelse($tournament->participants as $i => $p)
                    @php $pd = getDivision($p->user->elo ?? 1200); @endphp
                    <div class="d-flex align-items-center gap-3 px-3 py-2" style="border-bottom:1px solid #f8fafc">
                        <span style="font-size:11px;font-weight:700;color:#94a3b8;width:20px;text-align:center">{{ $i+1 }}</span>
                        <img src="{{ $p->user->avatar ?? 'https://ui-avatars.com/api/?name='.urlencode($p->user->username).'&background=1d4ed8&color=fff' }}"
                             style="width:32px;height:32px;border-radius:8px;object-fit:cover;flex-shrink:0" alt="">
                        <div style="flex:1;min-width:0">
                            <div style="font-size:13px;font-weight:600;color:#0f172a;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">
                                {{ $p->user->username }}
                            </div>
                            <div class="d-flex align-items-center gap-2 mt-1">
                                <span class="div-badge {{ $pd['cls'] }}" style="font-size:10px;padding:1px 6px">{{ $pd['icon'] }} {{ $pd['name'] }}</span>
                                @php $statusColors = ['registered'=>['#f1f5f9','#64748b'],'confirmed'=>['#f0fdf4','#16a34a'],'eliminated'=>['#fef2f2','#dc2626'],'champion'=>['#fefce8','#ca8a04']]; [$sbg,$sc] = $statusColors[$p->status] ?? ['#f1f5f9','#64748b']; @endphp
                                <span style="font-size:10px;font-weight:700;padding:1px 7px;border-radius:20px;background:{{ $sbg }};color:{{ $sc }}">
                                    {{ ucfirst($p->status) }}
                                </span>
                            </div>
                        </div>
                        <div style="font-size:12px;font-weight:700;color:#1d4ed8;flex-shrink:0">{{ number_format($p->user->elo ?? 1200) }}</div>
                        <!-- Remove button -->
                        <form method="POST" action="{{ route('admin.tournaments.participants.remove', [$tournament->id, $p->user_id]) }}"
                              onsubmit="return confirm('Hapus {{ addslashes($p->user->username) }} dari turnamen ini?')">
                            @csrf @method('DELETE')
                            <button type="submit" class="btn-pes-ghost" style="padding:4px 6px;color:#ef4444;font-size:13px" title="Hapus peserta">
                                <i class="ti ti-user-minus"></i>
                            </button>
                        </form>
                    </div>
                    @empty
                    <div style="padding:32px;text-align:center;color:#94a3b8;font-size:13px">
                        <div style="font-size:28px;margin-bottom:8px">👥</div>
                        Belum ada peserta
                    </div>
                    @endforelse
                </div>

                @if($tournament->participants_count > 0)
                <div style="padding:10px 16px;border-top:1px solid #f1f5f9;font-size:11px;color:#94a3b8;text-align:center">
                    {{ $tournament->participants_count }} / {{ $tournament->max_players }} slot terisi
                    &nbsp;·&nbsp;
                    <div class="pes-progress d-inline-flex" style="width:80px;vertical-align:middle">
                        <div class="pes-progress-bar" style="width:{{ round($tournament->participants_count / $tournament->max_players * 100) }}%"></div>
                    </div>
                </div>
                @endif
            </div>

            <!-- Group standings summary -->
            @if(!empty($groupData['standings']))
            <div class="pes-card">
                <div class="pes-card-header">
                    <div class="pes-card-header-left">
                        <div class="pes-card-icon" style="background:#f3e8ff;color:#7c3aed"><i class="ti ti-layout-grid"></i></div>
                        <span class="pes-card-title">Standings Grup</span>
                    </div>
                    <a href="{{ route('admin.tournament.bracket', $tournament->id) }}"
                       class="btn-pes-ghost" style="font-size:11px;text-decoration:none">Detail →</a>
                </div>
                @foreach($groupData['standings'] as $gName => $rows)
                <div style="padding:8px 16px;border-bottom:1px solid #f1f5f9">
                    <div style="font-size:10px;font-weight:700;color:#7c3aed;text-transform:uppercase;margin-bottom:4px">Grup {{ $gName }}</div>
                    @foreach($rows as $uid => $stat)
                    @php $p2 = $groupData['players'][$uid] ?? null; $adv = $loop->index < $tournament->groups_per_advance; @endphp
                    <div style="display:flex;align-items:center;gap:6px;padding:3px 0;font-size:12px">
                        <span style="color:#94a3b8;width:14px;text-align:center;font-weight:700">{{ $loop->iteration }}</span>
                        <span style="flex:1;color:#0f172a;font-weight:{{ $adv?600:400 }};overflow:hidden;text-overflow:ellipsis;white-space:nowrap">{{ $p2?->username ?? '?' }}</span>
                        <span style="font-weight:800;color:#1d4ed8;min-width:20px;text-align:right">{{ $stat['pts'] }}</span>
                        @if($adv)<span style="font-size:9px;color:#16a34a;font-weight:700">↑</span>@endif
                    </div>
                    @endforeach
                </div>
                @endforeach
            </div>
            @endif
        </div>
    </div>

    @push('scripts')
    <script>
    function filterPlayers(q) {
        q = q.toLowerCase().trim();
        var rows    = document.querySelectorAll('#player-list .player-row');
        var visible = 0;
        rows.forEach(function(row) {
            var name = row.dataset.name || '';
            var show = !q || name.indexOf(q) !== -1;
            row.style.display = show ? '' : 'none';
            if (show) visible++;
        });
        var list      = document.getElementById('player-list');
        var noResults = document.getElementById('no-results');
        if (list)      list.style.display      = (visible > 0) ? '' : 'none';
        if (noResults) noResults.style.display = (visible === 0 && q.length > 0) ? '' : 'none';
    }
    </script>
    @endpush
</x-app-layout>
