<h1>Soutěže a Výherci</h1>

<div style="display:flex; gap: 10px; margin-bottom: 20px;">
    <button onclick="showCompTab('competitions')">Správa soutěží</button>
    <button onclick="showCompTab('entries')">Soutěžící a Losování</button>
</div>

<div id="comp-competitions" class="comp-tab" style="display:block;">
    <div style="margin-bottom: 20px;">
        <button onclick="openCompModal()">➕ Přidat soutěž</button>
    </div>
    <div class="modal-overlay" id="compModal">
        <div class="modal-content" style="width: 800px; max-height: 90vh; overflow-y: auto;">
            <h3>Přidat / Upravit soutěž</h3>
            <form id="form-competitions" class="form-group" style="flex-wrap: wrap;">
                <input type="hidden" id="compId">
                <input type="text" id="compTitle" placeholder="Název soutěže" required style="width:48%;">
                <input type="text" id="compSlug" placeholder="URL slug (např. letni-soutez)" required style="width:48%;">
                <label style="width:100%; margin-top: 10px;">Obrázek (volitelný): <input type="file" id="compImage" accept="image/*" style="width:100%; border: 1px solid var(--glass-border); padding: 8px; border-radius: 8px; background: rgba(0,0,0,0.2);"></label>
                <div id="compImagePreview" style="width:100%; margin-bottom:10px;"></div>
                <label style="width:100%;"><input type="checkbox" id="compActive" checked> Soutěž je aktivní (běží)</label>
                <label style="width:100%;"><input type="checkbox" id="compFinished"> Soutěž je ukončena (lze losovat)</label>
                <textarea id="compDesc" class="tinymce" rows="8" placeholder="Popis a pravidla soutěže" style="width:100%; background: rgba(0,0,0,0.2); color:#fff; border:1px solid var(--glass-border); padding:10px; border-radius:8px;"></textarea>
                <div style="width: 100%; margin-top: 10px; display: flex; gap: 10px;">
                    <button type="submit">Uložit</button> <button type="button" onclick="closeCompModal()" style="background: rgba(255,255,255,0.2);">Zrušit</button>
                </div>
            </form>
        </div>
    </div>
    <div class="glass" style="padding: 20px;"><table><thead><tr><th>Název</th><th>Odkaz</th><th>Stav</th><th>Akce</th></tr></thead><tbody id="tbody-competitions"></tbody></table></div>
</div>

<div id="comp-entries" class="comp-tab glass" style="padding: 20px; display:none;">
    <div style="margin-bottom: 20px; display: flex; gap: 10px; align-items: center;">
        <select id="entryCompSelect" onchange="loadEntries()" style="padding: 10px; border-radius: 8px; border: 1px solid var(--glass-border); background: rgba(0,0,0,0.2); color: #fff; min-width: 300px;">
            <option value="">-- Vyberte soutěž --</option>
        </select>
        <button onclick="drawWinner()" style="background: linear-gradient(135deg, #f2c94c 0%, #f2994a 100%); color: #000;">🎲 Vylosovat výherce</button>
    </div>
    <div id="winnerDisplay" style="display:none; padding: 20px; background: rgba(56, 239, 125, 0.2); border: 1px solid #38ef7d; border-radius: 10px; margin-bottom: 20px; text-align: center;">
        <h3 style="color: #38ef7d; margin-top:0;">🎉 Máme Výherce!</h3>
        <div id="winnerText" style="font-size: 1.5rem; font-weight: bold;"></div>
    </div>
    <table>
        <thead><tr><th>Datum</th><th>Jméno</th><th>E-mail</th><th>Odpověď / Zpráva</th><th>Akce</th></tr></thead>
        <tbody id="tbody-entries"></tbody>
    </table>
</div>

<script>
    function showCompTab(tab) { document.querySelectorAll('.comp-tab').forEach(el => el.style.display = 'none'); document.getElementById('comp-' + tab).style.display = 'block'; if (tab === 'entries') loadEntries(); else loadCompetitions(); }
    function openCompModal() { document.getElementById('compModal').style.display = 'flex'; }
    function closeCompModal() { document.getElementById('compModal').style.display = 'none'; document.getElementById('form-competitions').reset(); document.getElementById('compId').value=''; document.getElementById('compImagePreview').innerHTML=''; setTinyContent('compDesc', ''); }
    
    window.allCompsData = [];
    window.allEntriesData = [];
    
    async function loadCompetitions() { 
        const res = await fetch('/admin/api/competitions'); 
        const json = await res.json(); 
        window.allCompsData = (json.data || []).sort((a,b) => new Date(b.created_at) - new Date(a.created_at)); 
        
        document.getElementById('tbody-competitions').innerHTML = window.allCompsData.map((c, i) => `<tr><td>${c.title}</td><td>/soutez/${c.slug}</td><td>${c.active ? '🟢 Probíhá' : (c.finished ? '🏁 Ukončena' : '🔴 Vypnuta')}</td><td><button class="action-btn" onclick="editComp(${i})">Upravit</button><button class="action-btn btn-delete" onclick="delComp('${c.id}')">Smazat</button></td></tr>`).join(''); 
        
        const sel = document.getElementById('entryCompSelect');
        const oldVal = sel.value;
        sel.innerHTML = '<option value="">-- Vyberte soutěž --</option>' + window.allCompsData.map(c => `<option value="${c.id}">${c.title}</option>`).join('');
        sel.value = oldVal;
    }
    
    function editComp(i) { 
        const c = window.allCompsData[i]; 
        document.getElementById('compId').value = c.id; 
        document.getElementById('compTitle').value = c.title; 
        document.getElementById('compSlug').value = c.slug; 
        document.getElementById('compActive').checked = c.active; 
        document.getElementById('compFinished').checked = c.finished; 
        setTinyContent('compDesc', c.description); 
        document.getElementById('compImagePreview').innerHTML = c.image ? `<img src="/${c.image}" style="max-height:100px; border-radius:8px;">` : ''; 
        openCompModal(); 
    }
    
    async function delComp(id) { customConfirm('Opravdu smazat soutěž včetně všech soutěžících?', async () => { await fetch('/admin/api/competitions', { method: 'DELETE', headers: {'Content-Type':'application/json'}, body: JSON.stringify({id}) }); loadCompetitions(); }); }
    
    document.getElementById('form-competitions').addEventListener('submit', async (e) => { 
        e.preventDefault(); 
        const fileInput = document.getElementById('compImage'); let base64 = null; 
        if (fileInput.files.length > 0) { base64 = await new Promise(resolve => { const reader = new FileReader(); reader.onload = e => resolve(e.target.result); reader.readAsDataURL(fileInput.files[0]); }); } 
        const payload = { id: document.getElementById('compId').value, title: document.getElementById('compTitle').value, slug: document.getElementById('compSlug').value, active: document.getElementById('compActive').checked, finished: document.getElementById('compFinished').checked, description: getTinyContent('compDesc') }; 
        if (base64) payload.image_base64 = base64; 
        await fetch('/admin/api/competitions', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) }); 
        closeCompModal(); loadCompetitions(); 
    });
    
    async function loadEntries() {
        const compId = document.getElementById('entryCompSelect').value;
        if (!compId) { document.getElementById('tbody-entries').innerHTML = ''; document.getElementById('winnerDisplay').style.display = 'none'; return; }
        const res = await fetch('/admin/api/competition_entries'); const json = await res.json();
        window.allEntriesData = (json.data || []).filter(e => e.comp_id === compId).sort((a,b) => new Date(b.created_at) - new Date(a.created_at));
        document.getElementById('tbody-entries').innerHTML = window.allEntriesData.map(e => `<tr><td>${e.created_at}</td><td>${e.name}</td><td>${e.email}</td><td>${e.message || '-'}</td><td><button class="action-btn btn-delete" onclick="delEntry('${e.id}')">Smazat</button></td></tr>`).join('');
        document.getElementById('winnerDisplay').style.display = 'none';
    }
    
    async function delEntry(id) { customConfirm('Smazat záznam soutěžícího?', async () => { await fetch('/admin/api/competition_entries', { method: 'DELETE', headers: {'Content-Type':'application/json'}, body: JSON.stringify({id}) }); loadEntries(); }); }
    
    function drawWinner() {
        if (window.allEntriesData.length === 0) return customAlert('Není z čeho losovat, žádní soutěžící.', 'Chyba');
        let winnerIndex = 0;
        let interval = setInterval(() => { winnerIndex = Math.floor(Math.random() * window.allEntriesData.length); document.getElementById('winnerDisplay').style.display = 'block'; document.getElementById('winnerText').innerText = 'Losuji... ' + window.allEntriesData[winnerIndex].name; }, 100);
        setTimeout(() => { clearInterval(interval); const winner = window.allEntriesData[winnerIndex]; document.getElementById('winnerText').innerText = winner.name + ' (' + winner.email + ')'; customAlert(`Výhercem se stává:\n\n${winner.name}\n${winner.email}\n\nGratulujeme!`, 'Vylosováno'); }, 3000);
    }
    
    loadCompetitions();
</script>