<?php
echo "<h1>E-Mail Klient</h1>";
?>
<div style="display:flex; gap: 20px; height: calc(100vh - 120px);">
    <div class="glass" style="width: 250px; padding: 20px; display:flex; flex-direction:column; gap:10px;">
        <button onclick="window.openEmailComposer()" style="background:var(--accent); color:#000; margin-bottom:15px;">Nová zpráva</button>
        <button onclick="loadEmails('INBOX')" class="action-btn" style="text-align:left; font-size:1.1rem; padding:10px;">📥 Doručená pošta</button>
        <button onclick="loadEmails('Archives/<?php echo date('Y'); ?>')" class="action-btn" style="text-align:left; font-size:1.1rem; padding:10px;">📦 Archiv (<?php echo date('Y'); ?>)</button>
    </div>
    <div class="glass" style="flex:1; padding: 20px; overflow-y:auto; display:flex; flex-direction:column;">
        <div id="emailList" style="flex:1;">
            <table style="width:100%;"><tbody id="tbody-emails"></tbody></table>
        </div>
        <div id="emailDetail" style="display:none; flex-direction:column; flex:1;">
            <button onclick="document.getElementById('emailDetail').style.display='none'; document.getElementById('emailList').style.display='block';" style="align-self:flex-start; margin-bottom:15px;">&larr; Zpět na seznam</button>
            <h2 id="eReadSubj" style="margin-top:0;"></h2>
            <div style="color:var(--text-muted); margin-bottom:20px;">Od: <span id="eReadFrom"></span> | Datum: <span id="eReadDate"></span></div>
            
            <div style="margin-bottom:15px; display:flex; gap:10px;">
                <button onclick="replyEmail()">Odpovědět</button>
                <button onclick="forwardEmail()">Předat</button>
                <button onclick="actionEmail('archive')" style="background:#f2c94c; color:#000;">Archivovat</button>
                <button onclick="actionEmail('delete')" class="btn-delete">Smazat</button>
            </div>
            
            <div style="margin-bottom:15px; display:flex; gap:10px; align-items:center; background:rgba(0,0,0,0.2); padding:10px; border-radius:8px;">
                <select id="eReadLang" style="padding:5px; background:rgba(0,0,0,0.2); color:#fff; border:1px solid var(--glass-border); border-radius:4px;"><option value="cs">Čeština</option><option value="en">English</option><option value="de">Deutsch</option><option value="es">Español</option></select>
                <button onclick="translateReadEmail()" style="padding:5px 10px; font-size:0.85rem;">Přeložit pomocí AI</button>
            </div>
            
            <div id="eReadBody" style="background:rgba(0,0,0,0.2); padding:20px; border-radius:8px; border:1px solid var(--glass-border); flex:1; overflow-y:auto;"></div>
        </div>
    </div>
</div>
<script>
let currentFolder = 'INBOX';
let currentUid = 0;
let currentEmailData = null;

async function loadEmails(folder) {
    currentFolder = folder;
    document.getElementById('emailDetail').style.display = 'none';
    document.getElementById('emailList').style.display = 'block';
    document.getElementById('tbody-emails').innerHTML = '<tr><td>Načítám zprávy (může to trvat déle)...</td></tr>';
    
    const formData = new FormData(); formData.append('folder', folder);
    try {
        const res = await fetch('/admin/api/email-inbox', { method: 'POST', body: formData });
        const json = await res.json();
        if (json.status === 'error') { document.getElementById('tbody-emails').innerHTML = `<tr><td style="color:#ff4b2b;">${json.message}</td></tr>`; return; }
        if (!json.data || json.data.length === 0) { document.getElementById('tbody-emails').innerHTML = '<tr><td>Žádné zprávy.</td></tr>'; return; }
        document.getElementById('tbody-emails').innerHTML = json.data.map(e => `<tr style="cursor:pointer; ${e.seen ? 'color:#ccc;' : 'font-weight:bold; color:#fff;'}" onclick="readEmail(${e.uid})"><td>${e.from}</td><td>${e.subject}</td><td style="text-align:right;">${e.date}</td></tr>`).join('');
    } catch(e) { document.getElementById('tbody-emails').innerHTML = '<tr><td>Chyba sítě.</td></tr>'; }
}

async function readEmail(uid) {
    currentUid = uid;
    document.getElementById('emailList').style.display = 'none'; document.getElementById('emailDetail').style.display = 'flex'; document.getElementById('eReadBody').innerHTML = 'Načítám obsah...';
    const formData = new FormData(); formData.append('folder', currentFolder); formData.append('uid', uid);
    const res = await fetch('/admin/api/email-read', { method: 'POST', body: formData });
    const json = await res.json();
    if (json.status === 'success') { currentEmailData = json.data; document.getElementById('eReadSubj').innerText = json.data.subject; document.getElementById('eReadFrom').innerText = json.data.from; document.getElementById('eReadDate').innerText = json.data.date; document.getElementById('eReadBody').innerHTML = json.data.body; } else { document.getElementById('eReadBody').innerHTML = json.message; }
}

async function actionEmail(act) {
    if (!confirm('Opravdu provést tuto akci?')) return;
    const formData = new FormData(); formData.append('folder', currentFolder); formData.append('uid', currentUid); formData.append('action', act);
    const res = await fetch('/admin/api/email-action', { method: 'POST', body: formData });
    const json = await res.json();
    if (json.status === 'success') { customAlert(json.message); loadEmails(currentFolder); } else { customAlert(json.message); }
}

function replyEmail() { if (!currentEmailData) return; window.openEmailComposer(currentEmailData.from, `Re: ${currentEmailData.subject}`, `<br><br><hr><p>Původní zpráva od ${currentEmailData.from}:</p><div>${currentEmailData.body}</div>`); }
function forwardEmail() { if (!currentEmailData) return; window.openEmailComposer('', `Fwd: ${currentEmailData.subject}`, `<br><br><hr><p>Předaná zpráva od ${currentEmailData.from}:</p><div>${currentEmailData.body}</div>`); }

async function translateReadEmail() { const lang = document.getElementById('eReadLang').value; const btn = document.querySelector('button[onclick="translateReadEmail()"]'); const origBtnText = btn.innerText; btn.innerText = 'Překládám...'; btn.disabled = true; try { const res = await fetch('/admin/api/ai-translate', { method: 'POST', headers: {'Content-Type':'application/json'}, body: JSON.stringify({title: currentEmailData.subject, content: currentEmailData.body, langs: [lang]}) }); const json = JSON.parse(await res.text()); if (json.status === 'success' && json.data[lang]) { document.getElementById('eReadBody').innerHTML = `<strong>Překlad (${lang.toUpperCase()}):</strong><br><br>${json.data[lang].content}<hr><strong>Původní zpráva:</strong><br><br>${currentEmailData.body}`; } else { customAlert('Chyba překladu: ' + (json.message||'')); } } catch(e) { customAlert('Chyba komunikace s AI.'); } btn.innerText = origBtnText; btn.disabled = false; }

loadEmails('INBOX');
</script>
