<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <title>{{ $pageTitle }}</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
    <style>
        :root { --primary-color: #4CAF50; --secondary-color: #2E7D32; --bg-color: #f0f2f5; --card-bg: white; --text-color: #333; --light-text-color: #666; --join-btn-color: #007BFF; --max-btn-color: #dc3545; }
        body { font-family: 'Roboto', sans-serif; background-color: var(--bg-color); margin: 0; padding: 15px; }
        .header { display: flex; align-items: center; margin-bottom: 20px; }
        .back-btn { background: none; border: none; font-size: 24px; color: var(--text-color); cursor: pointer; margin-right: 15px; }
        .header h1 { font-size: 22px; margin: 0; color: var(--text-color); }
        .match-card-link { text-decoration: none; color: inherit; display: block; margin-bottom: 20px; }
        .match-card { background-color: var(--card-bg); border-radius: 12px; box-shadow: 0 5px 20px rgba(0,0,0,0.08); overflow: hidden; border: 1px solid #e0e0e0; transition: transform 0.2s; }
        .match-card:hover { transform: translateY(-2px); }
        .match-card-header { display: flex; align-items: center; padding: 15px; border-bottom: 1px solid #eee; position: relative; }
        .match-card-header img { width: 50px; height: 50px; border-radius: 8px; margin-right: 15px; }
        .header-info h3 { margin: 0; font-size: 1.1em; color: var(--text-color); }
        .header-info p { margin: 2px 0 0; font-size: 0.8em; color: var(--light-text-color); }
        .match-id { position: absolute; top: 0; right: 0; background-color: #ff9800; color: white; padding: 3px 10px; font-size: 0.8em; font-weight: bold; border-bottom-left-radius: 8px; }
        .match-card-body { padding: 15px; display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 15px; text-align: center; }
        .stat-block p { font-size: 0.7em; color: var(--light-text-color); margin: 0 0 4px 0; text-transform: uppercase; }
        .stat-block h4 { margin: 0; font-size: 1em; color: var(--text-color); }
        .match-card-progress { padding: 0 15px 15px; display: flex; align-items: center; justify-content: space-between; gap: 15px; }
        .progress-container { flex-grow: 1; }
        .progress-bar { width: 100%; background-color: #e0e0e0; border-radius: 50px; height: 10px; overflow: hidden; }
        .progress-bar-fill { background: linear-gradient(45deg, #FFC107, #FF9800); height: 100%; border-radius: 50px; transition: width 0.5s ease; }
        .progress-info { display: flex; justify-content: space-between; font-size: 0.8em; color: var(--light-text-color); margin-top: 5px; }
        .joined-status { padding: 2px 8px; font-weight: bold; border: 1px solid var(--primary-color); color: var(--primary-color); border-radius: 8px; font-size: 0.9em; }
        
        /* বাটন স্টাইল */
        .join-btn { padding: 8px 25px; background-color: transparent; border: 1px solid var(--join-btn-color); color: var(--join-btn-color); border-radius: 8px; font-weight: 500; cursor: pointer; transition: all 0.2s; white-space: nowrap; }
        .join-btn.joined { border-color: var(--primary-color); color: var(--primary-color); }
        .join-btn.max { border-color: var(--max-btn-color); color: var(--max-btn-color); }

        .match-card-actions { padding: 15px; border-top: 1px solid #eee; display: flex; gap: 10px; }
        .action-btn { flex: 1; padding: 10px; background: #f0f2f5; border: 1px solid #ddd; border-radius: 8px; font-weight: 500; cursor: pointer; display: flex; align-items: center; justify-content: center; gap: 8px; transition: background-color 0.2s; text-decoration: none; color: inherit; }
        .match-card-footer { background: linear-gradient(45deg, var(--primary-color), var(--secondary-color)); color: white; text-align: center; padding: 12px; font-size: 1.1em; font-weight: bold; }
        .modal { display: none; position: fixed; z-index: 1000; left: 0; top: 0; width: 100%; height: 100%; overflow: auto; background-color: rgba(0,0,0,0.6); backdrop-filter: blur(5px); }
        .modal-content { background-color: white; margin: 30% auto; padding: 20px; border-radius: 12px; width: 90%; max-width: 400px; animation: zoomIn 0.3s; }
        @keyframes zoomIn { from { transform: scale(0.7); opacity: 0; } to { transform: scale(1); opacity: 1; } }
    </style>
</head>
<body>
    <div class="header">
        <button onclick="window.location.href='{{ route('home') }}'" class="back-btn"><i class="fas fa-arrow-left"></i></button>
        <h1>{{ $pageTitle }}</h1>
    </div>

    {{-- সিরিয়াল ঠিক করার জন্য sortBy('id') ব্যবহার করা হয়েছে (ছোট থেকে বড়) --}}
    @forelse ($matches->sortBy('id') as $match)
        @php
            $progress = ($match->Player_Need > 0) ? ($match->Player_Join / $match->Player_Need) * 100 : 0;
            $isUserJoined = in_array($match->Match_Key, $joinedMatchKeys);
            $spotsLeft = max(0, $match->Player_Need - $match->Player_Join);
        @endphp
        
        <a href="{{ route('match.details', ['game' => $type, 'id' => $match->id]) }}" class="match-card-link">
            <div class="match-card">
                <div class="match-card-header">
                    <img src="{{ asset($type === 'ludo' ? 'assets/images/ludo_icon.png' : 'assets/images/freefire_icon.png') }}" alt="Game Icon">
                    <div class="header-info">
                        <h3>{{ $match->Match_Title }}</h3>
                        <p>{{ \Carbon\Carbon::parse($match->Match_Time)->format('d-m-Y \a\t h:i A') }}</p>
                    </div>
                    {{-- এখানে আইডি সিরিয়াল অনুযায়ী প্রদর্শিত হবে (#39, #40...) --}}
                    <div class="match-id">#{{ $match->id }}</div>
                </div>
                <div class="match-card-body">
                    <div class="stat-block"><p>WIN PRIZE</p><h4>৳{{ $match->Total_Prize }}</h4></div>
                    <div class="stat-block"><p>TYPE</p><h4>{{ $match->Entry_Type }}</h4></div>
                    <div class="stat-block"><p>ENTRY FEE</p><h4>৳{{ $match->Entry_Fee }}</h4></div>
                    <div class="stat-block"><p>PER KILL</p><h4>৳{{ $match->Per_Kill }}</h4></div>
                    <div class="stat-block"><p>MAP</p><h4>{{ $match->Play_Map }}</h4></div>
                    <div class="stat-block"><p>VERSION</p><h4>{{ $match->Version }}</h4></div>
                </div>
                
                <div class="match-card-progress">
                    <div class="progress-container">
                        <div class="progress-bar"><div class="progress-bar-fill" style="width: {{ $progress }}%;"></div></div>
                        <div class="progress-info">
                            {{-- স্পট লজিক: ০ হলে No Spots Left --}}
                            <span>{{ $spotsLeft > 0 ? "Only $spotsLeft Spots Left" : "No Spots Left" }}</span>
                            @if($isUserJoined)
                                <span class="joined-status">✓ Joined</span>
                            @else
                                <span>{{ $match->Player_Join }}/{{ $match->Player_Need }}</span>
                            @endif
                        </div>
                    </div>

                    {{-- বাটন লজিক: ইউজার জয়েন থাকলে Joined, ফুল হলে Max, নাহলে Join --}}
                    @if($isUserJoined)
                        <button class="join-btn joined">Joined</button>
                    @elseif($spotsLeft <= 0)
                        <button class="join-btn max">Max</button>
                    @else
                        <button class="join-btn">Join</button>
                    @endif
                </div>

                <div class="match-card-actions">
                    <button class="action-btn" onclick="event.preventDefault(); event.stopPropagation(); showRoomDetails({{ $isUserJoined ? 'true' : 'false' }}, '{{ $match->Position }}', '{{ $match->Room_ID ?? 'TBA' }}', '{{ $match->Room_Pass ?? 'TBA' }}')">
                        <i class="fas fa-key"></i> Room Password
                    </button>
                    <button class="action-btn" onclick="event.preventDefault(); event.stopPropagation(); showPrizeDetails('{{ $match->Total_Prize }}', '{{ $match->prize_1st ?? '0' }}', '{{ $match->prize_2nd ?? '0' }}', '{{ $match->prize_3rd ?? '0' }}')">
                        <i class="fas fa-trophy"></i> Prize Details
                    </button>
                </div>
                
                <div class="match-card-footer" data-time="{{ $match->Match_Time }}">
                    <i class="fas fa-clock"></i> STARTS IN: <span class="countdown">Loading...</span>
                </div>
            </div>
        </a>
    @empty
        <p class='no-match' style="text-align: center; padding: 40px; background: white; border-radius: 12px; color: #888;">No upcoming matches available.</p>
    @endforelse

    {{-- Modals and Scripts --}}
    <div id="passwordModal" class="modal"><div class="modal-content"><div class="modal-header"><h2>Room Details</h2><span class="close-btn" onclick="closeModal('passwordModal')" style="cursor:pointer">×</span></div><div id="passwordDisplay"></div></div></div>
    <div id="prizeModal" class="modal"><div class="modal-content"><div class="modal-header"><h2>Prize Pool</h2><span class="close-btn" onclick="closeModal('prizeModal')" style="cursor:pointer">×</span></div><ul id="prizeList" style="list-style:none; padding:0;"></ul></div></div>

    <script>
        document.querySelectorAll('.match-card-footer').forEach(footer => {
            const countdownElement = footer.querySelector('.countdown');
            const matchTime = new Date(footer.getAttribute('data-time').replace(' ', 'T')).getTime();
            const updateCountdown = () => {
                const now = new Date().getTime();
                const distance = matchTime - now;
                if (distance < 0) {
                    countdownElement.innerHTML = "Match Started";
                    return;
                }
                const d = Math.floor(distance / (1000 * 60 * 60 * 24));
                const h = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
                const m = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
                const s = Math.floor((distance % (1000 * 60)) / 1000);
                countdownElement.innerHTML = `${String(d).padStart(2, '0')}d ${String(h).padStart(2, '0')}h ${String(m).padStart(2, '0')}m ${String(s).padStart(2, '0')}s`;
            };
            updateCountdown();
            setInterval(updateCountdown, 1000);
        });

        function openModal(id) { document.getElementById(id).style.display = "block"; }
        function closeModal(id) { document.getElementById(id).style.display = "none"; }
        function showRoomDetails(joined, pos, id, pass) {
            const display = document.getElementById('passwordDisplay');
            display.innerHTML = joined ? (pos === 'OnGoing' ? `<p>ID: ${id}</p><p>Pass: ${pass}</p>` : `<p>Available before match starts.</p>`) : `<p>Join the match first.</p>`;
            openModal('passwordModal');
        }
        function showPrizeDetails(total, p1, p2, p3) {
            document.getElementById('prizeList').innerHTML = `<li>Total: ৳${total}</li><hr><li>1st: ৳${p1}</li><li>2nd: ৳${p2}</li><li>3rd: ৳${p3}</li>`;
            openModal('prizeModal');
        }
        window.onclick = (e) => { if(e.target.className === 'modal') e.target.style.display = "none"; }
    </script>
</body>
</html>