<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Card Players Unite | The Lounge</title>
    <link href="https://fonts.googleapis.com/css2?family=Sen:wght@400;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        :root {
            --aria-gold: #4dbf00; /* Matching your theme brand color [cite: 113] */
            --aria-dark: #151515; /* [cite: 121] */
            --aria-surface: #1f1f1f;
        }

        body {
            font-family: 'Sen', sans-serif;
            background-color: var(--aria-dark);
            color: white;
            margin: 0;
            padding: 40px;
        }

        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            border-bottom: 2px solid var(--aria-gold);
            padding-bottom: 20px;
            margin-bottom: 40px;
        }

        .btn-gold {
            background-color: var(--aria-gold);
            color: white;
            border: none;
            padding: 12px 24px;
            border-radius: 8px;
            font-weight: bold;
            cursor: pointer;
            transition: transform 0.2s;
        }

        .btn-gold:hover {
            transform: scale(1.05);
            background-color: #3e9a00;
        }

        /* Tournament Table Styling */
        .tournament-grid {
            width: 100%;
            border-collapse: collapse;
            background: var(--aria-surface);
            border-radius: 12px;
            overflow: hidden;
        }

        th, td {
            padding: 18px;
            text-align: left;
            border-bottom: 1px solid #333;
        }

        th {
            background-color: #2a2a2a;
            color: var(--aria-gold);
            text-transform: uppercase;
            font-size: 0.8rem;
        }

        /* Modal / Popup Box */
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.8);
            justify-content: center;
            align-items: center;
        }

        .modal-content {
            background: var(--aria-surface);
            padding: 40px;
            border-radius: 15px;
            width: 400px;
            border: 1px solid var(--aria-gold);
        }

        .form-group { margin-bottom: 20px; }
        input, textarea {
            width: 100%;
            padding: 10px;
            background: #111;
            border: 1px solid #444;
            color: white;
            border-radius: 5px;
        }
    </style>
</head>
<body>

    <div class="header">
        <h1>Card Players Unite <small style="font-size: 0.5em; color: gray;">Tournament Management</small></h1>
        <button class="btn-gold" onclick="toggleModal(true)">
            <i class="fas fa-plus"></i> NEW TOURNAMENT
        </button>
    </div>

    <table class="tournament-grid">
        <thead>
            <tr>
                <th>Tournament Name</th>
                <th>Description</th>
                <th>Buy-in (Price)</th>
                <th>Status</th>
            </tr>
        </thead>
        <tbody id="tournament-list">
            </tbody>
    </table>

    <div id="createModal" class="modal">
        <div class="modal-content">
            <h2 style="color: var(--aria-gold);">Host a New Table</h2>
            <form id="tournamentForm">
                <div class="form-group">
                    <label>Name</label>
                    <input type="text" id="name" required placeholder="High Roller Hold'em">
                </div>
                <div class="form-group">
                    <label>Description</label>
                    <textarea id="description" rows="3" placeholder="No-limit stakes..."></textarea>
                </div>
                <div class="form-group">
                    <label>Price</label>
                    <input type="number" id="rental_price" step="0.01" value="999.99">
                </div>
                <input type="hidden" id="rented_user_id" value="0">

                <div style="display: flex; gap: 10px;">
                    <button type="submit" class="btn-gold">START EVENT</button>
                    <button type="button" class="btn-gold" style="background:#444;" onclick="toggleModal(false)">CLOSE</button>
                </div>
            </form>
        </div>
    </div>

    <script>
        // Toggle the popup
        function toggleModal(show) {
            document.getElementById('createModal').style.display = show ? 'flex' : 'none';
        }

        // Fetch and List Tournaments
        async function fetchTournaments() {
            const response = await fetch('/tournament/');
            const data = await response.json();
            const list = document.getElementById('tournament-list');
            list.innerHTML = '';

            data.forEach(t => {
                const row = `<tr>
                    <td><strong>${t.name}</strong></td>
                    <td>${t.description}</td>
                    <td>$${t.rental_price}</td>
                    <td>${t.rented_user_id === 0 ? 'AVAILABLE' : 'BOOKED'}</td>
                </tr>`;
                list.innerHTML += row;
            });
        }

        // Create Tournament [cite: 150, 155]
        document.getElementById('tournamentForm').addEventListener('submit', async (e) => {
            e.preventDefault();
            const payload = {
                name: document.getElementById('name').value,
                description: document.getElementById('description').value,
                rental_price: parseFloat(document.getElementById('rental_price').value),
                rented_user_id: parseInt(document.getElementById('rented_user_id').value)
            };

            const response = await fetch('/tournament/create/', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json', 'X-CSRFToken': '{{ csrf_token }}' },
                body: JSON.stringify(payload)
            });

            if (response.ok) {
                toggleModal(false);
                fetchTournaments();
                document.getElementById('tournamentForm').reset();
            } else {
                alert("The house always wins... but this time, your form failed.");
            }
        });

// This function captures the form data and sends it to the house (the database)
async function saveTournament() {
    // 1. Gather the intel from the form fields
    const tournamentData = {
        name: document.getElementById('name').value,
        description: document.getElementById('description').value,
        rental_price: parseFloat(document.getElementById('rental_price').value),
        rented_user_id: 0 // Defaulting to 0 for available tables 
    };

    // 2. Place the bet (The POST request)
    const response = await fetch('/tournament/create/', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            // Ensure you handle CSRF if this is rendered via Django [cite: 95]
        },
        body: JSON.stringify(tournamentData)
    });

    if (response.ok) {
        console.log("Record saved to the vault.");
        // Refresh the list to show the new table
        fetchTournaments(); 
    } else {
        console.error("The house declined the transaction.");
    }
}

// This listener waits for the user to hit 'START EVENT'
document.getElementById('tournamentForm').addEventListener('submit', async (e) => {
    e.preventDefault(); // Keep the lounge smooth—no page reloads
    await saveTournament(); // This is the moment the record hits the database
});


        // Initialize the floor
        fetchTournaments();
    </script>
</body>
</html>
