<script>
    function togglePwd(id, btn) {
        const input = document.getElementById(id);
        if (input.type === 'password') { input.type = 'text'; btn.innerText = '🙈'; }
        else { input.type = 'password'; btn.innerText = '👁️'; }
    }
    function setTinyContent(id, content) { 
        if (typeof tinymce === 'undefined') {
            const el = document.getElementById(id); 
            if (el) el.value = content || '';
            setTimeout(() => {
                if (typeof tinymce !== 'undefined') {
                    const checkEd = tinymce.get(id);
                    if(checkEd) { try { checkEd.setContent(content || ''); } catch(e){} }
                }
            }, 1000);
            return;
        }
        const ed = tinymce.get(id); 
        if (ed && ed.initialized) { 
            try { ed.setContent(content || ''); } catch(e){}
        } else { 
            const el = document.getElementById(id); 
            if (el) el.value = content || ''; 
            if (ed) {
                ed.on('init', function() { try { this.setContent(content || ''); } catch(e){} }); 
            } else {
                setTimeout(() => {
                    if (typeof tinymce !== 'undefined') {
                        const checkEd = tinymce.get(id);
                        if(checkEd) { try { checkEd.setContent(content || ''); } catch(e){} }
                    }
                }, 800);
            }
        } 
    }
    function getTinyContent(id) { 
        if (typeof tinymce === 'undefined') {
            const el = document.getElementById(id); return el ? el.value : '';
        }
        const ed = tinymce.get(id); 
        if (ed && ed.initialized) return ed.getContent(); 
        const el = document.getElementById(id); return el ? el.value : ''; 
    }
    tinymce.init({ selector: '.tinymce', plugins: 'advlist autolink lists link image charmap preview anchor pagebreak searchreplace wordcount visualblocks visualchars code fullscreen insertdatetime media nonbreaking table emoticons template help', toolbar: 'undo redo | styles | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image | code', toolbar_mode: 'floating', skin: 'oxide-dark', content_css: 'dark', setup: function (editor) { editor.on('change', function () { editor.save(); }); } });
</script>

<div class="modal-overlay" id="customAlertModal" style="z-index:99999;">
    <div class="modal-content" style="width:600px; max-width:95%; text-align:center; display:flex; flex-direction:column; max-height:90vh;">
        <h3 id="customAlertTitle" style="color:var(--accent); flex-shrink:0; margin-top:0;">Upozornění</h3>
        <div id="customAlertText" style="margin: 20px 0; overflow-y: auto; text-align: left; word-break: break-word; white-space: pre-wrap; font-size: 0.9rem; flex:1;"></div>
        <button onclick="document.getElementById('customAlertModal').style.display='none'; if(window.customAlertCallback) window.customAlertCallback();" style="flex-shrink:0;">OK</button>
    </div>
</div>

<div class="modal-overlay" id="customConfirmModal" style="z-index:99999;">
    <div class="modal-content" style="width:400px; text-align:center;">
        <h3 id="customConfirmTitle" style="color:#ff4b2b;">Potvrzení akce</h3>
        <p id="customConfirmText" style="margin: 20px 0;"></p>
        <div style="display:flex; gap:10px; justify-content:center;">
            <button onclick="document.getElementById('customConfirmModal').style.display='none'; if(window.customConfirmOk) window.customConfirmOk();" style="background:#ff4b2b; color:#fff;">Ano, provést</button>
            <button onclick="document.getElementById('customConfirmModal').style.display='none';" style="background:rgba(255,255,255,0.2);">Zrušit</button>
        </div>
    </div>
</div>

<!-- EMAIL COMPOSER MODAL (S integrovaným AI Překladem) -->
<div class="modal-overlay" id="emailComposerModal" style="z-index:99998; display:none;">
    <div class="modal-content" style="width:800px; max-width:95%;">
        <h3 id="ecTitle" style="color:var(--accent); margin-top:0;">Nová zpráva</h3>
        <form id="emailComposerForm" class="form-group" style="flex-wrap: wrap;">
            <div style="width:100%; display:flex; gap:10px;"><input type="email" id="ecTo" placeholder="Příjemce (E-mail)" required style="flex:1;"></div>
            <div style="width:100%; display:flex; gap:10px; margin-top:10px;"><input type="text" id="ecSubject" placeholder="Předmět" required style="flex:1;"></div>
            <div style="width:100%; display:flex; gap:10px; margin-top:10px; align-items:center; background:rgba(0,0,0,0.2); padding:10px; border-radius:8px; border:1px solid var(--glass-border);">
                <select id="ecTranslateLang" style="padding:5px; border-radius:4px; border:1px solid var(--glass-border); background:rgba(0,0,0,0.5); color:#fff; font-size:0.85rem;"><option value="en">English</option><option value="de">Deutsch</option><option value="es">Español</option><option value="fr">Français</option><option value="cs">Čeština</option><option value="sk">Slovenčina</option><option value="pl">Polština</option></select>
                <button type="button" onclick="translateComposerEmail()" style="padding:5px 15px; font-size:0.85rem; background:linear-gradient(135deg, #b026ff 0%, #5a26ff 100%); color:#fff; border:none; border-radius:4px;">🤖 Přeložit e-mail pomocí AI</button>
                <div style="font-size:0.8rem; color:var(--text-muted); margin-left:10px;">AI automaticky detekuje a přeloží tělo i předmět do zvoleného cíle.</div>
            </div>
            <div style="width:100%; margin-top:10px;"><textarea id="ecMessage" class="tinymce" rows="12" style="width:100%;"></textarea></div>
            <div style="width:100%; margin-top:10px; background:rgba(0,0,0,0.2); padding:10px; border-radius:8px; border:1px solid var(--glass-border);">
                <div style="margin-bottom:5px; font-weight:bold; font-size:0.9rem;">Přílohy:</div>
                <div id="ecSystemAttachments" style="font-size:0.85rem; color:var(--accent); margin-bottom:5px;"></div>
                <input type="file" id="ecAttachments" multiple style="width:100%; font-size:0.85rem;">
            </div>
            <div style="width:100%; margin-top:15px; display:flex; justify-content:flex-end; gap:10px;">
                <button type="button" onclick="closeEmailComposer()" style="background:rgba(255,255,255,0.2);">Zrušit</button>
                <button type="submit" id="ecSubmitBtn">Odeslat e-mail</button>
            </div>
        </form>
    </div>
</div>

<script>
    window.customAlert = function(text, title='Upozornění', callback=null) {
        document.getElementById('customAlertTitle').innerText = title;
        document.getElementById('customAlertText').innerText = text;
        window.customAlertCallback = callback;
        document.getElementById('customAlertModal').style.display = 'flex';
    };
    window.customConfirm = function(text, okCallback) {
        document.getElementById('customConfirmText').innerText = text;
        window.customConfirmOk = okCallback;
        document.getElementById('customConfirmModal').style.display = 'flex';
    };
    window.alert = function(text) { customAlert(text); };
    
    document.addEventListener('DOMContentLoaded', () => {
        const sidebar = document.querySelector('.sidebar');
        if (sidebar) {
            const savedScroll = localStorage.getItem('sidebarScroll');
            if (savedScroll) sidebar.scrollTop = parseInt(savedScroll);
            sidebar.addEventListener('scroll', () => { localStorage.setItem('sidebarScroll', sidebar.scrollTop); });
        }
    });

    const currentUserName = <?php echo json_encode($currentUser['name'] ?? 'Moderátor'); ?>;
    
    window.openEmailComposer = async function(toEmail = '', subject = '', message = '', systemAttachmentDesc = '', apiEndpoint = '/admin/api/send-email', extraData = {}) {
        document.getElementById('ecTo').value = toEmail; 
        document.getElementById('ecSubject').value = subject;
        let signature = ''; 
        try { 
            const res = await fetch('/admin/api/settings-config'); 
            const json = await res.json(); 
            if (json.data && json.data.email_signature) { signature = '<br><br>' + json.data.email_signature.replace(/{JMENO_MODERATORA}/g, currentUserName); }
        } catch(e) {}
        document.getElementById('emailComposerModal').style.display = 'flex';
        setTimeout(() => setTinyContent('ecMessage', message + signature), 150);
        
        document.getElementById('ecSystemAttachments').innerHTML = systemAttachmentDesc ? '📎 ' + systemAttachmentDesc : '';
        document.getElementById('ecAttachments').value = '';
        window.ecCurrentApiEndpoint = apiEndpoint; 
        window.ecExtraData = extraData;
    };

    window.translateComposerEmail = async function() {
        const lang = document.getElementById('ecTranslateLang').value;
        const content = getTinyContent('ecMessage');
        const subj = document.getElementById('ecSubject').value || 'E-mail';
        if (!content || !content.trim()) return customAlert('Napište nejprve nějaký text zprávy k překladu.');
        const btn = document.querySelector('button[onclick="translateComposerEmail()"]');
        if(!btn) return; const origText = btn.innerHTML; btn.innerHTML = '⏳ 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: subj, content: content, langs: [lang]}) }); const textResponse = await res.text(); try { const json = JSON.parse(textResponse); if (json.status === 'success' && json.data[lang]) { if (json.data[lang].title && json.data[lang].title !== 'E-mail') document.getElementById('ecSubject').value = json.data[lang].title; setTinyContent('ecMessage', json.data[lang].content); } else { customAlert('Chyba překladu: ' + (json.message || '')); } } catch(e) { customAlert('Chyba při čtení dat z AI:\n\n' + textResponse, 'Chyba parsování'); } } catch(e) { customAlert('Chyba komunikace s AI (Síťový problém).', 'Chyba sítě'); }
        btn.innerHTML = origText; btn.disabled = false;
    };

    window.closeEmailComposer = function() { document.getElementById('emailComposerModal').style.display = 'none'; };

    document.getElementById('emailComposerForm').addEventListener('submit', async function(e) {
        e.preventDefault(); const btn = document.getElementById('ecSubmitBtn'); const origText = btn.innerText; btn.innerText = 'Odesílám...'; btn.disabled = true;
        const formData = new FormData(); formData.append('to', document.getElementById('ecTo').value); formData.append('subject', document.getElementById('ecSubject').value); formData.append('message', getTinyContent('ecMessage'));
        if (window.ecExtraData) { for (const key in window.ecExtraData) { formData.append(key, window.ecExtraData[key]); } }
        const files = document.getElementById('ecAttachments').files; for (let i = 0; i < files.length; i++) { formData.append('attachments[]', files[i]); }
        try { const res = await fetch(window.ecCurrentApiEndpoint, { method: 'POST', body: formData }); const text = await res.text(); let json; try { json = JSON.parse(text); } catch(e) { json = {status:'error', message: text}; } if (json.status === 'success') { customAlert(json.message || 'E-mail byl úspěšně odeslán.', 'Hotovo'); closeEmailComposer(); } else { customAlert('Chyba: ' + json.message, 'Chyba odesílání'); } } catch (err) { customAlert('Nastala síťová chyba při odesílání.', 'Chyba sítě'); }
        btn.innerText = origText; btn.disabled = false;
    });
</script>