            <h1>Nastavení systému</h1>
            
            <div style="display:flex; gap: 10px; margin-bottom: 20px;">
                <button onclick="showSettingsTab('smtp')">E-maily (SMTP)</button>
                <button onclick="showSettingsTab('streams')">Vysílací streamy</button>
                <button onclick="showSettingsTab('integrations')">Integrace a Webhook</button>
                <button onclick="showSettingsTab('newsletter')">Odběratelé (Newsletter)</button>
            </div>

            <div id="settingsSuccess" style="display:none; position:fixed; bottom:20px; right:20px; color:#38ef7d; font-weight:bold; padding:15px; background:rgba(56, 239, 125, 0.2); border:1px solid rgba(56, 239, 125, 0.5); border-radius:8px; z-index:1000; backdrop-filter: blur(10px);"></div>

            <div id="set-smtp" class="settings-tab glass" style="padding: 20px; margin-bottom: 20px; max-width: 800px; display:block;">
                <form id="form-settings-smtp">
                    <h3>SMTP Nastavení (E-maily)</h3>
                    <div style="display:grid; grid-template-columns: 1fr 1fr; gap: 15px; margin-bottom: 15px;">
                        <div><label>Host</label><input type="text" id="smtpHost" style="width:100%;" placeholder="smtp.seznam.cz"></div>
                        <div><label>Port</label><input type="number" id="smtpPort" style="width:100%;" placeholder="465"></div>
                        <div><label>Uživatelské jméno</label><input type="text" id="smtpUser" style="width:100%;" placeholder="info@mojeradio.cz"></div>
                        <div><label>Heslo</label><div class="pwd-wrapper"><input type="password" id="smtpPass" placeholder="********"><button type="button" class="pwd-toggle" onclick="togglePwd('smtpPass', this)">👁️</button></div></div>
                        <div><label>Šifrování</label><select id="smtpEnc" style="width:100%;"><option value="">Žádné (Nebo pro Port 465)</option><option value="tls">STARTTLS (Port 587)</option><option value="ssl">SSL/SMTPS</option></select></div>
                        <div><label>Odesílatel (E-mail)</label><input type="email" id="smtpFromEmail" style="width:100%;" placeholder="info@mojeradio.cz"></div>
                        <div style="grid-column: span 2;"><label>Odesílatel (Zobrazené jméno)</label><input type="text" id="smtpFromName" style="width:100%;" placeholder="RadioWebSystem"></div>
                        <div style="grid-column: span 2; margin-top: 10px;">
                            <label>E-mailový podpis (WYSIWYG) - Přidá se automaticky na konec každé zprávy</label>
                            <textarea id="smtpSignature" class="tinymce" rows="5"></textarea>
                        </div>
                    </div>
                    <div style="display:flex; gap: 15px;">
                        <button type="submit" style="flex: 2;">Uložit SMTP nastavení</button>
                        <button type="button" onclick="testSmtp()" style="flex: 1; background: linear-gradient(135deg, #f2994a 0%, #f2c94c 100%); color: #000;">Test spojení SMTP</button>
                    </div>
                </form>
            </div>

            <div id="set-streams" class="settings-tab glass" style="padding: 20px; margin-bottom: 20px; max-width: 1000px; display:none;">
                <h3>Nastavení streamů (Servery a kvality)</h3>
                <div style="margin-bottom: 15px;"><button type="button" onclick="openStreamModal(-1)">➕ Přidat stream</button></div>
                <table style="margin-bottom: 20px;"><thead><tr><th>Název</th><th>Typ</th><th>URL Přehrávače</th><th>Status URL</th><th>Akce</th></tr></thead><tbody id="tbody-streams"></tbody></table>
                <div class="modal-overlay" id="streamModal" style="z-index:1001;">
                    <div class="modal-content" style="width: 600px;">
                        <h3>Přidat / Upravit stream</h3>
                        <div class="form-group" style="flex-wrap: wrap;">
                            <input type="hidden" id="streamIdx">
                            <div style="width:48%;"><label>Název (např. 128kbps)</label><input type="text" id="streamName" style="width:100%;" required></div>
                            <div style="width:48%;"><label>Typ streamu</label><select id="streamType" style="width:100%;"><option value="icecast2">IceCast V2</option><option value="shoutcast2">ShoutCast V2</option></select></div>
                            <div style="width:100%;"><label>Audio Stream URL (pro přehrávač)</label><input type="text" id="streamListen" style="width:100%;" placeholder="http://..."></div>
                            <div style="width:100%;"><label>JSON Status URL (pro statistiky)</label><input type="text" id="streamStatus" style="width:100%;" placeholder="http://..."></div>
                            <div style="width: 100%; margin-top: 10px; display: flex; gap: 10px;">
                                <button type="button" onclick="saveStream()">Uložit do seznamu</button>
                                <button type="button" onclick="closeStreamModal()" style="background: rgba(255,255,255,0.2);">Zrušit</button>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="modal-overlay" id="streamTestModal" style="z-index:1002; display:none;">
                    <div class="modal-content" style="width: 400px; text-align:center;">
                        <h3>Test připojení streamu</h3>
                        <h4 id="streamTestName" style="color:var(--accent); margin-top:0;"></h4>
                        <audio id="streamTestAudio" controls style="width:100%; margin-bottom:15px; border-radius:8px;"></audio>
                        <button type="button" onclick="closeStreamTestModal()" style="background: rgba(255,255,255,0.2);">Zavřít</button>
                    </div>
                </div>
                
                <button type="button" onclick="saveAllSettings()" style="width: 100%;">Uložit nastavení streamů</button>
            </div>

            <div id="set-integrations" class="settings-tab glass" style="padding: 20px; margin-bottom: 20px; max-width: 800px; display:none;">
                <form id="form-settings-int">
                    <h3>Systémové integrace</h3>
                    
                    <hr style="border-color: rgba(255,255,255,0.2); margin: 20px 0;">
                    <h3>Aktivní jazyky webu</h3>
                    <p style="font-size:0.9rem; color:var(--text-muted);">Vyberte, do jakých jazyků budete chtít web překládat. Nezaškrtnuté jazyky nebudou zobrazeny ani návštěvníkům, ani v administraci článků.</p>
                    <div id="activeLangsWrapper" style="display:flex; flex-wrap:wrap; gap:10px; margin-bottom:15px; background:rgba(0,0,0,0.2); padding:15px; border-radius:8px; border:1px solid var(--glass-border);">
                        <?php foreach($sysLangsAll as $k => $v): ?>
                            <label style="display:flex; align-items:center; gap:5px; width:calc(25% - 10px); cursor:pointer;"><input type="checkbox" value="<?php echo $k; ?>" class="active-lang-cb"> <img src="https://flagcdn.com/w20/<?php echo $flagCodes[$k]; ?>.png" style="width:20px; border-radius:2px;"> <?php echo $v; ?></label>
                        <?php endforeach; ?>
                    </div>

                    <div style="margin-bottom: 15px;"><label>TinyMCE API Klíč (volitelné pro prémiové funkce textového editoru) <a href="https://www.tiny.cloud/my-account/dashboard/" target="_blank" class="api-link">Získat klíč na Tiny.cloud</a></label><div class="pwd-wrapper"><input type="password" id="tinymceApiKey" placeholder="no-api-key"><button type="button" class="pwd-toggle" onclick="togglePwd('tinymceApiKey', this)">👁️</button></div></div>
                    
                    <hr style="border-color: rgba(255,255,255,0.2); margin: 20px 0;">
                    <h3>API Klíče pro AI asistenty a Překlady</h3>
                    <div style="display:flex; gap:15px; margin-bottom:15px;">
                        <div style="flex:1;"><label>OpenAI API Key <a href="https://platform.openai.com/api-keys" target="_blank" class="api-link">Získat klíč na OpenAI</a></label><div class="pwd-wrapper"><input type="password" id="openaiApiKey" placeholder="sk-..."><button type="button" class="pwd-toggle" onclick="togglePwd('openaiApiKey', this)">👁️</button></div></div>
                        <div style="flex:1;"><label>Google Gemini API Key <a href="https://aistudio.google.com/app/apikey" target="_blank" class="api-link">Získat klíč na Google Studio</a></label><div class="pwd-wrapper"><input type="password" id="geminiApiKey" placeholder="AIza..."><button type="button" class="pwd-toggle" onclick="togglePwd('geminiApiKey', this)">👁️</button></div></div>
                    </div>
                    <hr style="border-color: rgba(255,255,255,0.2); margin: 20px 0;">
                    <h3>Ochrana proti SPAMu (Google reCAPTCHA v3)</h3>
                    <div style="display:flex; gap:15px; margin-bottom:15px;">
                        <div style="flex:1;"><label>Site Key (Klíč webu) <a href="https://www.google.com/recaptcha/admin" target="_blank" class="api-link">Získat klíče na reCAPTCHA</a></label><div class="pwd-wrapper"><input type="password" id="recaptchaSite" placeholder="6Le..."><button type="button" class="pwd-toggle" onclick="togglePwd('recaptchaSite', this)">👁️</button></div></div>
                        <div style="flex:1;"><label>Secret Key (Tajný klíč) <a href="https://www.google.com/recaptcha/admin" target="_blank" class="api-link">Získat klíče na reCAPTCHA</a></label><div class="pwd-wrapper"><input type="password" id="recaptchaSecret" placeholder="6Le..."><button type="button" class="pwd-toggle" onclick="togglePwd('recaptchaSecret', this)">👁️</button></div></div>
                    </div>

                    <hr style="border-color: rgba(255,255,255,0.2); margin: 20px 0;">
                    <h3>Webhook API (Propojení se studiem Radio Profesional/RPX/RadioDJ/mAirList) <a href="https://api.mysoft.cz/redir.php?from=radiowebsystem&kam=RP8" target="_blank" class="api-link" style="font-weight:bold; font-size:1rem;">Radio Profesional 8</a></h3>
                    <div style="margin-bottom: 15px;"><label>Webhook Token (Tajné heslo pro API autorizaci)</label><div class="pwd-wrapper"><input type="password" id="webhookToken" placeholder="Zadejte libovolné silné heslo"><button type="button" class="pwd-toggle" onclick="togglePwd('webhookToken', this)">👁️</button></div></div>
                    
                    <hr style="border-color: rgba(255,255,255,0.2); margin: 20px 0;">
                    <h3>Systémová licence</h3>
                    <div style="margin-bottom: 15px;"><label>Licenční API Klíč (Radio Web System)</label><div class="pwd-wrapper"><input type="password" id="rwsApiKey" placeholder="Zadejte váš API klíč pro mysoft.cz"><button type="button" class="pwd-toggle" onclick="togglePwd('rwsApiKey', this)">👁️</button></div></div>
                    
                    <div style="display:flex; gap:15px; margin-bottom:15px;">
                        <div style="flex:1;"><label>Preferovaný AI model pro překlady</label> <select id="aiProvider" style="width:100%;"><option value="openai">OpenAI (GPT-4o-mini)</option><option value="gemini">Google Gemini</option></select></div>
                        <div style="flex:1;">
                            <label>Verze Gemini modelu</label>
                            <select id="geminiModel" style="width:100%;">
                                <option value="gemini-2.5-flash">Gemini 2.5 Flash (Nejnovější, rychlý a levný)</option>
                                <option value="gemini-2.5-pro">Gemini 2.5 Pro (Pokročilý)</option>
                                <option value="gemini-1.5-flash">Gemini 1.5 Flash (Starší, stabilní)</option>
                                <option value="gemini-1.5-pro">Gemini 1.5 Pro (Starší, pokročilý)</option>
                            </select>
                        </div>
                    </div>
                    <div style="font-size:0.9rem; color:#ccc; background:rgba(0,0,0,0.2); padding:10px; border-radius:8px;"><strong>API Endpoint:</strong> <code><?php echo (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://" . $_SERVER['HTTP_HOST'] . "/radiowebsystem/admin/api/webhook"; ?></code><br><strong>Formát POST JSON:</strong> <code>{"token": "VASE_HESLO", "action": "now_playing", "artist": "...", "title": "..."}</code><br><strong>Dostupné akce (action):</strong> <code>now_playing</code>, <code>queue</code> (pole "songs"), <code>set_moderator</code> (ID moderátora)</div>
                    <button type="submit" style="width: 100%; margin-top: 15px;">Uložit integrace</button>
                </form>
            </div>

            <div id="set-newsletter" class="settings-tab glass" style="padding: 20px; margin-bottom: 20px; max-width: 1000px; display:none;">
                <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:15px;">
                    <h3 style="margin:0;">Registrovaní odběratelé novinek</h3>
                    <div>
                        <button type="button" onclick="openAddSubscriberModal()" style="background: var(--accent); color: #000; margin-right: 10px;">➕ Přidat odběratele / Import</button>
                        <button type="button" onclick="window.open('/admin/api/export-csv?type=newsletter', '_blank')" style="background: rgba(255,255,255,0.2); margin-right: 10px;">💾 Export CSV</button>
                        <button type="button" onclick="openNewsletterComposer()" style="background: linear-gradient(135deg, #b026ff 0%, #5a26ff 100%);">✉️ Odeslat Hromadný Newsletter</button>
                    </div>
                </div>
                <table>
                    <thead><tr><th>E-mail</th><th>Datum registrace</th><th>Stav ověření</th><th>Akce</th></tr></thead>
                    <tbody id="tbody-newsletter"></tbody>
                </table>
                <div id="addSubscriberModal" class="modal-overlay" style="z-index:1001; display:none;">
                    <div class="modal-content" style="width: 500px;">
                        <h3>Přidat odběratele</h3>
                        <form id="form-add-subscriber" class="form-group" style="flex-wrap: wrap;">
                            <div style="width:100%;"><label>E-mailová adresa</label><input type="email" id="newSubscriberEmail" style="width:100%;" required></div>
                            <div style="width:100%; margin-top:10px;"><label><input type="checkbox" id="newSubscriberVerified" checked> Označit jako ověřený</label></div>
                            <div style="width:100%; margin-top:15px; display:flex; gap:10px;"><button type="submit">Přidat</button><button type="button" onclick="closeAddSubscriberModal()" style="background: rgba(255,255,255,0.2);">Zrušit</button></div>
                        </form>
                        <hr style="border-color: rgba(255,255,255,0.2); margin: 20px 0;">
                        <h3>Hromadný import ze souboru</h3>
                        <p style="font-size:0.9rem; color:var(--text-muted);">Nahrajte textový soubor (.txt, .csv) obsahující e-mailové adresy. Co řádek, to jedna e-mailová adresa. Importované adresy budou označeny jako ověřené.</p>
                        <form id="form-import-subscribers" class="form-group" style="flex-wrap: wrap;">
                            <div style="width:100%;"><input type="file" id="importSubscribersFile" accept=".txt,.csv" style="width:100%;" required></div>
                            <div style="width:100%; margin-top:15px;"><button type="submit" style="background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%); color: #000; width:100%;">Importovat ze souboru</button></div>
                        </form>
                    </div>
                </div>
            </div>

            <script>
                let appStreams = [];
                let allSubscribers = [];
                function showSettingsTab(tab) { document.querySelectorAll('.settings-tab').forEach(el => el.style.display = 'none'); document.getElementById('set-' + tab).style.display = 'block'; }
                
                function openStreamModal(idx) { document.getElementById('streamIdx').value = idx; if(idx >= 0) { const s = appStreams[idx]; document.getElementById('streamName').value = s.name || ''; document.getElementById('streamType').value = s.type || 'icecast2'; document.getElementById('streamListen').value = s.listen_url || ''; document.getElementById('streamStatus').value = s.status_url || ''; } else { document.getElementById('streamName').value = ''; document.getElementById('streamType').value = 'icecast2'; document.getElementById('streamListen').value = ''; document.getElementById('streamStatus').value = ''; } document.getElementById('streamModal').style.display = 'flex'; }
                function closeStreamModal() { document.getElementById('streamModal').style.display = 'none'; }
                function saveStream() { const idx = parseInt(document.getElementById('streamIdx').value); const s = { id: idx >= 0 ? appStreams[idx].id : Date.now().toString(), name: document.getElementById('streamName').value, type: document.getElementById('streamType').value, listen_url: document.getElementById('streamListen').value, status_url: document.getElementById('streamStatus').value }; if(idx >= 0) appStreams[idx] = s; else appStreams.push(s); closeStreamModal(); renderStreams(); }
                function delStream(idx) { customConfirm('Smazat tento stream?', () => { appStreams.splice(idx, 1); renderStreams(); }); }
                function renderStreams() { document.getElementById('tbody-streams').innerHTML = appStreams.map((s, i) => `<tr><td>${s.name}</td><td>${s.type}</td><td>${s.listen_url}</td><td>${s.status_url}</td><td><button type="button" class="action-btn btn-info" onclick="testStream(${i})">Test</button> <button type="button" class="action-btn" onclick="openStreamModal(${i})">Upravit</button> <button type="button" class="action-btn btn-delete" onclick="delStream(${i})">Smazat</button></td></tr>`).join(''); }
                function testStream(idx) { const s = appStreams[idx]; if (!s || !s.listen_url) return customAlert('Stream nemá nastavenou URL pro přehrávač.'); document.getElementById('streamTestName').innerText = s.name; const audio = document.getElementById('streamTestAudio'); audio.src = s.listen_url; document.getElementById('streamTestModal').style.display = 'flex'; audio.play().catch(e => console.log('Autoplay prevented', e)); }
                function closeStreamTestModal() { const audio = document.getElementById('streamTestAudio'); audio.pause(); audio.removeAttribute('src'); audio.load(); document.getElementById('streamTestModal').style.display = 'none'; }

                async function loadSettings() { 
                    const res = await fetch('/admin/api/settings-config'); const json = await res.json(); 
                    if(json.data && json.data.smtp) { const s = json.data.smtp; document.getElementById('smtpHost').value = s.host || ''; document.getElementById('smtpPort').value = s.port || ''; document.getElementById('smtpUser').value = s.username || ''; document.getElementById('smtpPass').value = s.password || ''; document.getElementById('smtpEnc').value = s.encryption || ''; document.getElementById('smtpFromEmail').value = s.from_email || ''; document.getElementById('smtpFromName').value = s.from_name || ''; } 
                    if(json.data && json.data.email_signature !== undefined) setTinyContent('smtpSignature', json.data.email_signature);
                    if(json.data && json.data.streams) { appStreams = json.data.streams; } else if(json.data && json.data.stream_url) { appStreams = [{id: Date.now().toString(), name: 'Hlavní stream', type: json.data.stream_type || 'icecast2', listen_url: json.data.stream_url, status_url: json.data.icecast_url || ''}]; } renderStreams();
                    if(json.data && json.data.tinymce_api_key !== undefined) document.getElementById('tinymceApiKey').value = json.data.tinymce_api_key; 
                    if(json.data && json.data.webhook_token !== undefined) document.getElementById('webhookToken').value = json.data.webhook_token;
                    if(json.data && json.data.openai_api_key !== undefined) document.getElementById('openaiApiKey').value = json.data.openai_api_key; 
                    if(json.data && json.data.gemini_api_key !== undefined) document.getElementById('geminiApiKey').value = json.data.gemini_api_key; 
                    if(json.data && json.data.ai_provider !== undefined) document.getElementById('aiProvider').value = json.data.ai_provider || 'openai'; 
                    if(json.data && json.data.gemini_model !== undefined) document.getElementById('geminiModel').value = json.data.gemini_model || 'gemini-2.5-flash'; 
                    if(json.data && json.data.recaptcha_site_key != null) document.getElementById('recaptchaSite').value = json.data.recaptcha_site_key; 
                    if(json.data && json.data.recaptcha_secret_key != null) document.getElementById('recaptchaSecret').value = json.data.recaptcha_secret_key; 
                    if(json.data && Array.isArray(json.data.active_langs)) { document.querySelectorAll('.active-lang-cb').forEach(cb => { cb.checked = json.data.active_langs.includes(cb.value); }); }
                    if(json.data && json.data.rws_api_key !== undefined) document.getElementById('rwsApiKey').value = json.data.rws_api_key;
                    
                    const resSubs = await fetch('/admin/api/newsletter'); const jsonSubs = await resSubs.json(); allSubscribers = jsonSubs.data || [];
                    document.getElementById('tbody-newsletter').innerHTML = allSubscribers.map(s => `<tr><td>${s.email}</td><td>${s.created_at || '-'}</td><td>${s.verified ? '🟢 Ověřeno' : '🟠 Čeká na ověření'}</td><td><button class="action-btn btn-delete" onclick="delSubscriber('${s.id}')">Smazat</button></td></tr>`).join('');
                }
                
                async function saveAllSettings() {
                    const smtpData = { host: document.getElementById('smtpHost').value, port: document.getElementById('smtpPort').value, username: document.getElementById('smtpUser').value, password: document.getElementById('smtpPass').value, encryption: document.getElementById('smtpEnc').value, from_email: document.getElementById('smtpFromEmail').value, from_name: document.getElementById('smtpFromName').value };
                    const tinymceApiKey = document.getElementById('tinymceApiKey').value; const webhookToken = document.getElementById('webhookToken').value; 
                    const activeLangs = Array.from(document.querySelectorAll('.active-lang-cb:checked')).map(cb => cb.value);
                    if (activeLangs.length === 0) activeLangs.push('cs');
                    try {
                        const res = await fetch('/admin/api/settings-config', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({smtp: smtpData, email_signature: getTinyContent('smtpSignature'), streams: appStreams, tinymce_api_key: tinymceApiKey, webhook_token: webhookToken, openai_api_key: document.getElementById('openaiApiKey').value, gemini_api_key: document.getElementById('geminiApiKey').value, recaptcha_site_key: document.getElementById('recaptchaSite').value, recaptcha_secret_key: document.getElementById('recaptchaSecret').value, active_langs: activeLangs, ai_provider: document.getElementById('aiProvider').value, gemini_model: document.getElementById('geminiModel').value, rws_api_key: document.getElementById('rwsApiKey').value}) }); 
                        const json = await res.json(); 
                        if (json.status === 'error') { customAlert('Chyba: ' + (json.message || 'Neznámá chyba'), 'Chyba'); } 
                        else { customAlert('Nastavení bylo úspěšně uloženo do systému.', 'Uloženo'); loadSettings(); }
                    } catch (e) { customAlert('Došlo k chybě sítě nebo serveru (Error 500). Skript z důvodu ochrany přerušil ukládání.', 'Kritická chyba'); }
                }

                document.getElementById('form-settings-smtp').addEventListener('submit', async (e) => { e.preventDefault(); saveAllSettings(); });
                document.getElementById('form-settings-int').addEventListener('submit', async (e) => { e.preventDefault(); saveAllSettings(); });

                async function testSmtp() {
                    const smtpData = { host: document.getElementById('smtpHost').value, port: document.getElementById('smtpPort').value, username: document.getElementById('smtpUser').value, password: document.getElementById('smtpPass').value, encryption: document.getElementById('smtpEnc').value, from_email: document.getElementById('smtpFromEmail').value, from_name: document.getElementById('smtpFromName').value };
                    const successMsg = document.getElementById('settingsSuccess');
                    successMsg.style.display = 'block'; successMsg.style.color = '#f2c94c'; successMsg.innerText = 'Testuji spojení, prosím čekejte...';
                    try { const res = await fetch('/admin/api/smtp-test', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({smtp: smtpData}) }); const json = await res.json(); successMsg.style.color = json.status === 'success' ? '#38ef7d' : '#ff4b2b'; successMsg.innerText = json.message; } 
                    catch (e) { successMsg.style.color = '#ff4b2b'; successMsg.innerText = 'Chyba při komunikaci se serverem.'; }
                }
                
                async function testAiConnection() {
                    const payload = { ai_provider: document.getElementById('aiProvider').value, openai_api_key: document.getElementById('openaiApiKey').value, gemini_api_key: document.getElementById('geminiApiKey').value, gemini_model: document.getElementById('geminiModel').value };
                    const successMsg = document.getElementById('settingsSuccess');
                    successMsg.style.display = 'block'; successMsg.style.color = '#f2c94c'; successMsg.innerText = 'Testuji spojení s AI, prosím čekejte...';
                    try { const res = await fetch('/admin/api/ai-test', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) }); const json = await res.json(); successMsg.style.color = json.status === 'success' ? '#38ef7d' : '#ff4b2b'; successMsg.innerText = json.message; } 
                    catch (e) { successMsg.style.color = '#ff4b2b'; successMsg.innerText = 'Chyba sítě při testování AI.'; }
                    setTimeout(() => successMsg.style.display = 'none', 5000);
                }
                
                async function delSubscriber(id) { customConfirm('Opravdu smazat tohoto odběratele?', async () => { await fetch('/admin/api/newsletter', { method: 'DELETE', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ id: id }) }); loadSettings(); }); }
                
                function openAddSubscriberModal() { document.getElementById('addSubscriberModal').style.display = 'flex'; }
                function closeAddSubscriberModal() { document.getElementById('addSubscriberModal').style.display = 'none'; document.getElementById('form-add-subscriber').reset(); document.getElementById('form-import-subscribers').reset(); }
                
                document.getElementById('form-add-subscriber').addEventListener('submit', async (e) => {
                    e.preventDefault();
                    const email = document.getElementById('newSubscriberEmail').value.trim();
                    const verified = document.getElementById('newSubscriberVerified').checked;
                    if (allSubscribers.find(s => s.email === email)) return customAlert('Tento e-mail již je v databázi.', 'Chyba');
                    
                    const btn = e.target.querySelector('button[type="submit"]'); const origTxt = btn.innerText; btn.innerText = 'Přidávám...'; btn.disabled = true;
                    await fetch('/admin/api/newsletter', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email: email, verified: verified }) });
                    
                    btn.innerText = origTxt; btn.disabled = false;
                    customAlert('Odběratel úspěšně přidán.', 'Hotovo');
                    closeAddSubscriberModal(); loadSettings();
                });

                document.getElementById('form-import-subscribers').addEventListener('submit', async (e) => {
                    e.preventDefault();
                    const fileInput = document.getElementById('importSubscribersFile');
                    if (fileInput.files.length === 0) return;
                    const text = await fileInput.files[0].text();
                    const emails = text.split(/\r?\n/).map(e => e.trim()).filter(e => e && /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e));
                    if (emails.length === 0) return customAlert('Nebyly nalezeny žádné platné e-mailové adresy.', 'Chyba');
                    
                    const btn = e.target.querySelector('button[type="submit"]'); const origTxt = btn.innerText; btn.innerText = 'Importuji (může chvíli trvat)...'; btn.disabled = true;
                    
                    let imported = 0;
                    for (const email of emails) {
                        if (!allSubscribers.find(s => s.email === email)) {
                            try {
                                await fetch('/admin/api/newsletter', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email: email, verified: true }) });
                                imported++;
                                allSubscribers.push({email: email}); // Prevence duplicit během stejného importu
                            } catch(err) {}
                        }
                    }
                    
                    btn.innerText = origTxt; btn.disabled = false;
                    customAlert(`Import dokončen. Nově přidáno: ${imported} odběratelů (z celkových ${emails.length} v souboru).`, 'Hotovo');
                    closeAddSubscriberModal(); loadSettings();
                });

                window.openNewsletterComposer = function() {
                    const verifiedEmails = allSubscribers.filter(s => s.verified).map(s => s.email).join(',');
                    if (!verifiedEmails) return customAlert('Nemáte žádné ověřené odběratele pro odeslání newsletteru.');
                    if (typeof window.openEmailComposer !== 'function') return customAlert('E-mailový klient se načítá...');
                    window.openEmailComposer(verifiedEmails, 'Novinky z našeho rádia', 'Dobrý den,<br><br>přinášíme vám nejnovější informace...', '', '/admin/api/send-email', {});
                }
                loadSettings();
            </script>