            <h1>Vzhled, Šablona a Boxy webu</h1>
            <div style="display:flex; gap: 10px; margin-bottom: 20px;">
                <button onclick="showTplTab('design')">Barvy a Pozadí</button> <button onclick="showTplTab('layout')">Šablona a Hlavička</button> <button onclick="showTplTab('menu')">Menu webu</button> <button onclick="showTplTab('boxes')">Správa boxíků</button> <button onclick="showTplTab('errors')">Chybové stránky</button> <button onclick="showTplTab('customcode')">Vlastní kódy</button>
            </div>
            
            <div id="tpl-design" class="tpl-tab glass" style="padding: 20px; display:block;">
                <form id="form-design" class="form-group" style="flex-wrap: wrap;">
                    <div style="width:100%; display:flex; gap:15px; margin-bottom:15px;">
                        <div style="flex:1;"><label>Základní barva přechodu 1</label><input type="color" id="tplColorBg1" style="width:100%; height:40px;"></div>
                        <div style="flex:1;"><label>Základní barva přechodu 2</label><input type="color" id="tplColorBg2" style="width:100%; height:40px;"></div>
                        <div style="flex:1;"><label>Zvýrazňovací barva (Accent)</label><input type="color" id="tplColorAccent" style="width:100%; height:40px;"></div>
                    </div>
                    <div style="width:100%; display:flex; gap:15px; margin-bottom:15px;">
                        <div style="flex:1;"><label>Barva tlačítek</label><input type="color" id="tplColorBtn" style="width:100%; height:40px;"></div>
                        <div style="flex:1;"><label>Text tlačítek</label><input type="color" id="tplColorBtnText" style="width:100%; height:40px;"></div>
                        <div style="flex:1;"><label>Text doplňků (šedá)</label><input type="color" id="tplColorTextMuted" style="width:100%; height:40px;"></div>
                        <div style="flex:1;">
                            <label>Průhledné pozadí panelů</label>
                            <div style="display:flex; gap:10px; align-items:center;">
                                <input type="color" id="tplColorPanelBgHex" style="width:50px; height:40px; padding:0; border:none; border-radius:8px; cursor:pointer; background:none;"> <input type="range" id="tplColorPanelBgAlpha" min="0" max="1" step="0.05" style="flex:1;">
                            </div><input type="hidden" id="tplColorPanelBg">
                        </div>
                    </div>
                    <div style="width:100%; margin-bottom:15px;">
                        <label>Písmo webu (Font)</label>
                        <select id="tplFontFamily" style="width:100%;"><option value="'Segoe UI', Tahoma, Geneva, Verdana, sans-serif">Výchozí (Segoe UI)</option><option value="'Roboto', sans-serif">Roboto</option><option value="'Open Sans', sans-serif">Open Sans</option><option value="'Montserrat', sans-serif">Montserrat</option><option value="'Oswald', sans-serif">Oswald</option><option value="'Playfair Display', serif">Playfair Display</option><option value="'Lora', serif">Lora (Patkové)</option></select>
                    </div>
                    <div style="width:100%; margin-bottom:15px;">
                        <label>Obrázek na pozadí</label> <input type="file" id="tplBgImage" accept="image/*" style="width:100%;">
                        <div id="tplBgImagePreview" style="margin-top:10px;"></div>
                        <label style="display:block; margin-top:5px;"><input type="checkbox" id="tplBgDelete"> Smazat současný obrázek</label>
                    </div>
                    <div style="width:100%; margin-bottom:15px;">
                        <label>Režim zobrazení pozadí</label>
                        <select id="tplBgRepeat" style="width:100%;"><option value="cover">Vyplnit obrazovku (Cover)</option><option value="repeat">Opakovat jako dlaždice (Repeat)</option></select>
                    </div>
                <div style="width:100%; margin-bottom:15px;">
                    <label>Slavnostní efekty na webu</label>
                    <select id="tplFestiveEffect" style="width:100%;">
                        <option value="none">Vypnuto (Bez efektu)</option>
                        <option value="snow">❄️ Sněžení (Vánoce / Zima)</option>
                        <option value="easter">🥚 Velikonoce (Padající kraslice a zajíčci)</option>
                        <option value="summer">☀️ Léto (Květiny a slunce)</option>
                        <option value="fireworks">🎆 Ohňostroj (Nový rok / Oslavy)</option>
                    </select>
                </div>
                    <hr style="width:100%; border-color: rgba(255,255,255,0.2); margin: 15px 0;">
                    <div style="width:100%; display:flex; gap:15px; margin-bottom:15px; align-items:center;">
                        <div style="flex:2;"><label>Logo webu</label> <input type="file" id="tplLogoImage" accept="image/*" style="width:100%;"> <div id="tplLogoImagePreview" style="margin-top:10px;"></div> <label style="display:block; margin-top:5px;"><input type="checkbox" id="tplLogoDelete"> Smazat současné logo</label></div>
                        <div style="flex:1;"><label>Velikost loga</label> <input type="text" id="tplLogoSize" placeholder="např. 100px nebo 100%" style="width:100%;"></div>
                        <div style="flex:1;"><label>Zarovnání loga</label> <select id="tplLogoPosition" style="width:100%;"><option value="left">Vlevo</option><option value="center">Na střed</option><option value="right">Vpravo</option></select></div>
                    </div>
                    <div style="width:100%; display:flex; gap:15px; margin-bottom:15px; align-items:center;">
                        <div style="flex:2;"><label>Titulek webu (pod logem)</label> <input type="text" id="tplSiteTitle" placeholder="Název rádia" style="width:100%;"></div>
                        <div style="flex:1;"><label>Velikost titulku</label> <input type="text" id="tplTitleSize" placeholder="např. 2rem" style="width:100%;"></div>
                        <div style="flex:1;"><label>Zarovnání titulku</label> <select id="tplTitlePosition" style="width:100%;"><option value="left">Vlevo</option><option value="center">Na střed</option><option value="right">Vpravo</option></select></div>
                    </div>
                    <div style="width:100%; display:flex; gap:15px; margin-bottom:15px; align-items:center;">
                        <div style="flex:1;"><label>Facebook URL (volitelné)</label> <input type="text" id="tplSocialFb" placeholder="https://facebook.com/..." style="width:100%;"></div>
                        <div style="flex:1;"><label>Instagram URL (volitelné)</label> <input type="text" id="tplSocialIg" placeholder="https://instagram.com/..." style="width:100%;"></div>
                    </div>
                    <button type="submit" style="width:100%;">Uložit vzhled</button>
                </form>
            </div>
            
            <div id="tpl-layout" class="tpl-tab glass" style="padding: 20px; display:none;">
                <form id="form-layout"><label>Hlavička (HTML)</label> <textarea id="tplHeader" class="tinymce" rows="10" style="width:100%; margin-bottom:15px;"></textarea> <label>Patička (HTML)</label> <textarea id="tplFooter" class="tinymce" rows="10" style="width:100%; margin-bottom:15px;"></textarea> <button type="submit" style="margin-top:10px;">Uložit hlavičku a patičku</button></form>
            </div>
            <div id="tpl-menu" class="tpl-tab glass" style="padding: 20px; display:none;">
                <div style="margin-bottom: 20px;"><button onclick="openMenuModal()">➕ Přidat položku menu</button></div>
                <table><thead><tr><th>Pořadí</th><th>Název</th><th>URL</th><th>Akce</th></tr></thead><tbody id="tbody-menu"></tbody></table>
            </div>
            <div id="tpl-boxes" class="tpl-tab glass" style="padding: 20px; display:none;">
                <div style="margin-bottom: 20px;"><button onclick="openBoxModal()">➕ Přidat vlastní box</button></div>
                <table><thead><tr><th>Pořadí</th><th>Titulek</th><th>Panel</th><th>Stav</th><th>Typ</th><th>Akce</th></tr></thead><tbody id="tbody-boxes"></tbody></table>
            </div>
            <div id="tpl-errors" class="tpl-tab glass" style="padding: 20px; display:none;">
                <h3>Editor systémových chybových stránek (ISPConfig)</h3>
                <p>Zde můžete upravit obsah chybových stránek ve složce <code>/error/</code>, které zobrazuje webový server.</p>
                <div style="margin-bottom: 15px;">
                    <label>Vyberte chybovou stránku k editaci:</label>
                    <select id="errorFileSelect" onchange="loadErrorFile(this.value)" style="width:100%; padding:10px; border-radius:8px; border:1px solid var(--glass-border); background:rgba(0,0,0,0.2); color:#fff;">
                        <option value="400.html">400 - Bad Request</option>
                        <option value="401.html">401 - Unauthorized</option>
                        <option value="404.html" selected>404 - Not Found</option>
                        <option value="405.html">405 - Method Not Allowed</option>
                        <option value="500.html">500 - Internal Server Error</option>
                        <option value="502.html">502 - Bad Gateway</option>
                        <option value="503.html">503 - Service Unavailable</option>
                    </select>
                </div>
                <form id="form-errors">
                    <input type="hidden" id="currentErrorFile" value="404.html">
                    <textarea id="errorFileContent" class="tinymce" rows="20"></textarea>
                    <button type="submit" style="margin-top:15px; width:100%;">Uložit chybovou stránku</button>
                </form>
            </div>
            <div id="tpl-customcode" class="tpl-tab glass" style="padding: 20px; display:none;">
                <h3>Vlastní kódy (CSS / JS / HTML)</h3>
                <p>Zde můžete vložit např. kódy pro Google Analytics, AdSense, vlastní styly nebo skripty (např. chatovací widget).</p>
                <form id="form-customcode">
                    <label style="display:block; margin-bottom:5px;">Vlastní kód do hlavičky (&lt;head&gt;)</label>
                    <textarea id="tplCustomHead" rows="6" placeholder="<script>...</script>" style="width:100%; margin-bottom:15px; background: rgba(0,0,0,0.2); color:#fff; border:1px solid var(--glass-border); padding: 10px; border-radius: 8px; font-family: monospace;"></textarea>
                    
                    <label style="display:block; margin-bottom:5px;">Vlastní kód do patičky (před konec &lt;/body&gt;)</label>
                    <textarea id="tplCustomBody" rows="6" placeholder="<script>...</script>" style="width:100%; margin-bottom:15px; background: rgba(0,0,0,0.2); color:#fff; border:1px solid var(--glass-border); padding: 10px; border-radius: 8px; font-family: monospace;"></textarea>
                    
                    <label style="display:block; margin-bottom:5px;">Vlastní CSS styly (budou automaticky obaleny tagem &lt;style&gt;)</label>
                    <textarea id="tplCustomCss" rows="6" placeholder="body { ... }" style="width:100%; margin-bottom:15px; background: rgba(0,0,0,0.2); color:#fff; border:1px solid var(--glass-border); padding: 10px; border-radius: 8px; font-family: monospace;"></textarea>
                    
                    <button type="submit">Uložit vlastní kódy</button>
                </form>
            </div>
<div class="modal-overlay" id="menuModal">
    <div class="modal-content" style="width: 600px;">
        <h3>Přidat / Upravit položku menu</h3>
        <form id="form-menu" class="form-group" style="flex-wrap: wrap;">
            <input type="hidden" id="menuId">
            <input type="text" id="menuLabel" placeholder="Název" required style="width: 48%;">
            <input type="text" id="menuUrl" placeholder="URL odkaz" required style="width: 48%;">
            <input type="number" id="menuOrder" placeholder="Pořadí" required value="1" style="width:100px;">
            <select id="menuParent" style="padding:10px; border-radius:8px; border:1px solid var(--glass-border); background:rgba(0,0,0,0.2); color:#fff; width:100%; margin-top:10px;"><option value="">-- Hlavní úroveň (bez pod-menu) --</option></select>
            <select id="menuPreset" style="padding:10px; border-radius:8px; border:1px solid var(--glass-border); background:rgba(0,0,0,0.2); color:#fff; width:100%; margin-top:10px;" onchange="if(this.value){document.getElementById('menuUrl').value=this.value; if(!document.getElementById('menuLabel').value){let t=this.options[this.selectedIndex].text; document.getElementById('menuLabel').value=t.replace('📻 ', '').replace('📝 ', '');}}"><option value="">-- Předvyplnit --</option><option value="#play">📻 NALADIT (Pustit rádio)</option><option value="/">Domů</option><option value="/porady">Program vysílání</option><option value="/hitparada">Hitparáda</option><option value="/historie">Historie songů</option><option value="/moderatori">Moderátoři</option><option value="/podcasty">Podcasty</option><option value="/objednavka">📝 Objednávkový formulář</option></select>
            <div style="width:100%; display:flex; gap:10px; margin-top:10px;">
                <button type="submit">Uložit</button>
                <button type="button" onclick="closeMenuModal()" style="background: rgba(255,255,255,0.2);">Zrušit</button>
            </div>
        </form>
    </div>
</div>
<div class="modal-overlay" id="boxModal">
    <div class="modal-content" style="width: 800px; max-height: 90vh; overflow-y: auto;">
        <h3>Přidat / Upravit box</h3>
        <form id="form-boxes" class="form-group" style="flex-wrap: wrap; align-items:flex-start;">
            <input type="hidden" id="boxId"> <input type="hidden" id="boxIsSystem"> <input type="hidden" id="boxSystemType">
            <div style="display:flex; gap:10px; width: 100%;"><input type="text" id="boxTitle" placeholder="Titulek boxu" required style="flex:1;"><select id="boxPosition"><option value="left">Levý</option><option value="right">Pravý</option></select><input type="number" id="boxOrder" placeholder="Pořadí" required value="1" style="width:100px;"></div>
            <label style="width:100%; margin-top: 10px; display:flex; align-items:center; gap:5px;"><input type="checkbox" id="boxActive" checked> Zobrazovat na webu (Aktivní)</label>
            <div style="width: 100%; margin-top:10px;" id="boxContentWrapper"><textarea id="boxContent" rows="8" placeholder="HTML obsah boxu" style="width:100%; background: rgba(0,0,0,0.2); color:#fff; border:1px solid var(--glass-border); padding:10px; border-radius:8px; font-family: monospace;"></textarea></div>
            <div id="boxClockTypeWrapper" style="display:none; width: 100%; margin-top: 10px;"><label style="width:100%; display:block; margin-bottom:5px;">Typ hodin (Vzhled widgetu)</label><select id="boxClockType" style="width:100%; background: rgba(0,0,0,0.2); color:#fff; border:1px solid var(--glass-border); padding:10px; border-radius:8px;"><option value="digital">Digitální</option><option value="analog">Analogové</option></select></div>
            <div id="boxWeatherSettingsWrapper" style="display:none; width: 100%; margin-top: 10px;"><label style="width:100%; display:block; margin-bottom:5px;">Města pro předpověď (více měst oddělte čárkou)</label><input type="text" id="boxWeatherCity" placeholder="např. Praha, Brno, Ostrava..." style="width:100%; background: rgba(0,0,0,0.2); color:#fff; border:1px solid var(--glass-border); padding:10px; border-radius:8px;"></div>
            <div id="boxOnAirSettingsWrapper" style="display:none; width: 100%; margin-top: 10px;"><label style="display:flex; align-items:center; gap:5px;"><input type="checkbox" id="boxOnAirClock" checked> Zobrazit živé hodiny u ON-AIR boxu</label></div>
            <div style="width: 100%; margin-top: 10px; display:flex; gap:10px;"><button type="submit">Uložit</button><button type="button" onclick="closeBoxModal();" style="background: rgba(255,255,255,0.2);">Zrušit</button></div>
        </form>
    </div>
</div>
            <script>
                function showTplTab(tab) { document.querySelectorAll('.tpl-tab').forEach(el => el.style.display = 'none'); document.getElementById('tpl-' + tab).style.display = 'block'; loadTplData(); }
                
                function openMenuModal() { document.getElementById('menuModal').style.display = 'flex'; }
                function closeMenuModal() { document.getElementById('menuModal').style.display = 'none'; document.getElementById('form-menu').reset(); document.getElementById('menuId').value=''; }
                
                function openBoxModal() { document.getElementById('boxModal').style.display = 'flex'; }
                function closeBoxModal() { 
                    document.getElementById('boxModal').style.display = 'none'; 
                    document.getElementById('form-boxes').reset(); 
                    document.getElementById('boxId').value = ''; 
                    document.getElementById('boxIsSystem').value = ''; 
                    document.getElementById('boxSystemType').value = ''; 
                    document.getElementById('boxContentWrapper').style.display = 'block'; 
                    document.getElementById('boxClockTypeWrapper').style.display = 'none';
                    document.getElementById('boxWeatherSettingsWrapper').style.display = 'none';
                    document.getElementById('boxOnAirSettingsWrapper').style.display = 'none';
                }
                
                window.allMenusData = [];
                window.allBoxesData = [];
                
                window.moveMenuDir = async function(id, dir) {
                    const res = await fetch('/admin/api/menus'); let mArr = (await res.json()).data || []; mArr.sort((a,b) => parseInt(a.order) - parseInt(b.order));
                    const idx = mArr.findIndex(x => x.id === id); if (idx < 0) return;
                    const parentId = mArr[idx].parent_id || ''; let targetIdx = -1;
                    if (dir === -1) { for (let i = idx - 1; i >= 0; i--) { if ((mArr[i].parent_id || '') === parentId) { targetIdx = i; break; } } } 
                    else { for (let i = idx + 1; i < mArr.length; i++) { if ((mArr[i].parent_id || '') === parentId) { targetIdx = i; break; } } }
                    if (targetIdx < 0) return;
                    const temp = mArr[idx].order; mArr[idx].order = mArr[targetIdx].order; mArr[targetIdx].order = temp;
                    if (mArr[idx].order === mArr[targetIdx].order) { mArr[idx].order = targetIdx + 1; mArr[targetIdx].order = idx + 1; }
                    await fetch('/admin/api/menus', {method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(mArr[idx])});
                    await fetch('/admin/api/menus', {method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(mArr[targetIdx])});
                    loadTplData();
                };

                async function loadTplData() {
                    const resTpl = await fetch('/admin/api/template-config');
                    const jsonTpl = await resTpl.json();
                    document.getElementById('tplColorBg1').value = jsonTpl.data.color_bg1 || '#1e3c72';
                    document.getElementById('tplColorBg2').value = jsonTpl.data.color_bg2 || '#2a5298';
                    document.getElementById('tplColorAccent').value = jsonTpl.data.color_accent || '#00d2ff';
                    document.getElementById('tplColorBtn').value = jsonTpl.data.color_btn || '#00d2ff';
                    document.getElementById('tplColorBtnText').value = jsonTpl.data.color_btn_text || '#000000';
                    document.getElementById('tplColorTextMuted').value = jsonTpl.data.color_text_muted || '#cccccc';
                    const panelBg = jsonTpl.data.color_panel_bg || 'rgba(255, 255, 255, 0.15)'; document.getElementById('tplColorPanelBg').value = panelBg;
                    const rgbaMatch = panelBg.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([\d.]+))?\)/);
                    if (rgbaMatch) {
                        const r = parseInt(rgbaMatch[1]).toString(16).padStart(2,'0'); const g = parseInt(rgbaMatch[2]).toString(16).padStart(2,'0'); const b = parseInt(rgbaMatch[3]).toString(16).padStart(2,'0');
                        document.getElementById('tplColorPanelBgHex').value = `#${r}${g}${b}`; document.getElementById('tplColorPanelBgAlpha').value = rgbaMatch[4] !== undefined ? rgbaMatch[4] : 1;
                    } else {
                        document.getElementById('tplColorPanelBgHex').value = '#ffffff'; document.getElementById('tplColorPanelBgAlpha').value = '0.15';
                    }

                    document.getElementById('tplFontFamily').value = jsonTpl.data.font_family || "'Segoe UI', Tahoma, Geneva, Verdana, sans-serif";
                    document.getElementById('tplBgRepeat').value = jsonTpl.data.bg_repeat || 'cover';
                    document.getElementById('tplFestiveEffect').value = jsonTpl.data.festive_effect || 'none';
                    document.getElementById('tplBgImagePreview').innerHTML = jsonTpl.data.bg_image ? `<img src="/${jsonTpl.data.bg_image}" style="max-height:100px; border-radius:8px;">` : '';
                    document.getElementById('tplBgDelete').checked = false;
                    document.getElementById('tplSiteTitle').value = jsonTpl.data.site_title || '';
                    document.getElementById('tplLogoImagePreview').innerHTML = jsonTpl.data.logo_image ? `<img src="/${jsonTpl.data.logo_image}" style="max-height:100px; border-radius:8px;">` : '';
                    document.getElementById('tplLogoDelete').checked = false;
                    document.getElementById('tplLogoSize').value = jsonTpl.data.logo_size || '100px';
                    document.getElementById('tplLogoPosition').value = jsonTpl.data.logo_position || 'center';
                    document.getElementById('tplTitleSize').value = jsonTpl.data.title_size || '2rem';
                    document.getElementById('tplTitlePosition').value = jsonTpl.data.title_position || 'center';
                    document.getElementById('tplSocialFb').value = jsonTpl.data.social_fb || '';
                    document.getElementById('tplSocialIg').value = jsonTpl.data.social_ig || '';
                    document.getElementById('tplCustomHead').value = jsonTpl.data.custom_head || '';
                    document.getElementById('tplCustomBody').value = jsonTpl.data.custom_body || '';
                    document.getElementById('tplCustomCss').value = jsonTpl.data.custom_css || '';
                    setTinyContent('tplHeader', jsonTpl.data.header);
                    setTinyContent('tplFooter', jsonTpl.data.footer);
                    const resMenu = await fetch('/admin/api/menus'); const jsonMenu = await resMenu.json(); let menus = jsonMenu.data || []; menus.sort((a,b) => parseInt(a.order) - parseInt(b.order));
                    const parentSelect = document.getElementById('menuParent'); const oldParentVal = parentSelect.value;
                    parentSelect.innerHTML = '<option value="">-- Hlavní úroveň (bez pod-menu) --</option>' + menus.filter(m => !m.parent_id).map(m => `<option value="${m.id}">${m.label}</option>`).join('');
                    parentSelect.value = oldParentVal;
                    let displayMenus = [];
                    menus.filter(m => !m.parent_id).forEach(parent => { displayMenus.push(parent); menus.filter(m => m.parent_id === parent.id).forEach(child => displayMenus.push(child)); });
                    menus.forEach(m => { if (!displayMenus.includes(m)) displayMenus.push(m); });
                    window.allMenusData = displayMenus;
                    document.getElementById('tbody-menu').innerHTML = window.allMenusData.map((m, i) => `<tr><td><button type="button" onclick="moveMenuDir('${m.id}', -1)" class="action-btn" style="padding: 2px 5px;" title="Nahoru">▲</button><button type="button" onclick="moveMenuDir('${m.id}', 1)" class="action-btn" style="padding: 2px 5px;" title="Dolů">▼</button> ${m.order}</td><td style="${m.parent_id ? 'padding-left: 20px; color: var(--accent);' : 'font-weight: bold;'}">${m.parent_id ? '↳ ' : ''}${m.label}</td><td>${m.url}</td><td><button class="action-btn" onclick="editMenu(window.allMenusData[${i}])">Upravit</button><button class="action-btn btn-delete" onclick="delItem('menus', '${m.id}', loadTplData)">Smazat</button></td></tr>`).join('');
                    
                    const resBoxes = await fetch('/admin/api/boxes'); const jsonBoxes = await resBoxes.json();
                    window.allBoxesData = jsonBoxes.data || [];
                    document.getElementById('tbody-boxes').innerHTML = window.allBoxesData.map((b, i) => `<tr><td>${b.order}</td><td>${b.title}</td><td>${b.position==='left'?'Levý':'Pravý'}</td><td>${b.is_system?'🔒 Systémový':'✎ Vlastní'}</td><td><button class="action-btn" onclick="editBox(window.allBoxesData[${i}])">Upravit</button>${!b.is_system ? `<button class="action-btn btn-delete" onclick="delItem('boxes', '${b.id}', loadTplData)">Smazat</button>` : ''}</td></tr>`).join('');
                    const resPages = await fetch('/admin/api/pages'); const jsonPages = await resPages.json(); const pSelect = document.getElementById('menuPreset'); Array.from(pSelect.options).forEach(o => { if(o.value.startsWith('/clanek/')) o.remove(); });
                    (jsonPages.data || []).forEach(p => pSelect.innerHTML += `<option value="/clanek/${p.slug}">📄 Článek: ${p.title}</option>`);

                    loadErrorFile('404.html');
                }
                
                window.loadErrorFile = async function(filename) {
                    document.getElementById('currentErrorFile').value = filename;
                    const resErrors = await fetch('/admin/api/system-files?file=' + filename);
                    const jsonErrors = await resErrors.json();
                    if (jsonErrors.status === 'success') { setTinyContent('errorFileContent', jsonErrors.data.content); }
                };

                function editMenu(m) { 
                    document.getElementById('menuId').value = m.id; 
                    document.getElementById('menuLabel').value = m.label; 
                    document.getElementById('menuUrl').value = m.url; 
                    document.getElementById('menuOrder').value = m.order;
                    document.getElementById('menuParent').value = m.parent_id || '';
                    openMenuModal();
                }
                
                function editBox(b) {
                    document.getElementById('boxId').value = b.id;
                    document.getElementById('boxTitle').value = b.title;
                    document.getElementById('boxPosition').value = b.position;
                    document.getElementById('boxOrder').value = b.order;
                    document.getElementById('boxContent').value = b.content || '';
                    document.getElementById('boxIsSystem').value = b.is_system ? '1' : '';
                    document.getElementById('boxSystemType').value = b.system_type || '';
                    document.getElementById('boxContentWrapper').style.display = b.is_system ? 'none' : 'block';
                    document.getElementById('boxClockTypeWrapper').style.display = b.system_type === 'clock' ? 'block' : 'none';
                    if(b.system_type === 'clock') document.getElementById('boxClockType').value = b.content || 'digital';
                    document.getElementById('boxWeatherSettingsWrapper').style.display = b.system_type === 'weather' ? 'block' : 'none';
                    if(b.system_type === 'weather') document.getElementById('boxWeatherCity').value = b.content || 'Praha';
                    document.getElementById('boxOnAirSettingsWrapper').style.display = b.system_type === 'onair' ? 'block' : 'none';
                    if(b.system_type === 'onair') document.getElementById('boxOnAirClock').checked = b.content !== '0';
                    document.getElementById('boxActive').checked = b.active !== false;
                    openBoxModal();
                }

                document.getElementById('form-design').addEventListener('submit', async(e)=>{ e.preventDefault(); const fileInput = document.getElementById('tplBgImage'); 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 logoInput = document.getElementById('tplLogoImage'); let logoBase64 = null; if (logoInput.files.length > 0) { logoBase64 = await new Promise(resolve => { const reader = new FileReader(); reader.onload = e => resolve(e.target.result); reader.readAsDataURL(logoInput.files[0]); }); } const payload = { color_bg1: document.getElementById('tplColorBg1').value, color_bg2: document.getElementById('tplColorBg2').value, color_accent: document.getElementById('tplColorAccent').value, color_btn: document.getElementById('tplColorBtn').value, color_btn_text: document.getElementById('tplColorBtnText').value, color_text_muted: document.getElementById('tplColorTextMuted').value, color_panel_bg: document.getElementById('tplColorPanelBg').value, font_family: document.getElementById('tplFontFamily').value, bg_repeat: document.getElementById('tplBgRepeat').value, festive_effect: document.getElementById('tplFestiveEffect').value, bg_image_delete: document.getElementById('tplBgDelete').checked ? true : undefined, site_title: document.getElementById('tplSiteTitle').value, logo_size: document.getElementById('tplLogoSize').value, logo_position: document.getElementById('tplLogoPosition').value, title_size: document.getElementById('tplTitleSize').value, title_position: document.getElementById('tplTitlePosition').value, social_fb: document.getElementById('tplSocialFb').value, social_ig: document.getElementById('tplSocialIg').value, logo_image_delete: document.getElementById('tplLogoDelete').checked ? true : undefined }; if (base64) payload.bg_image_base64 = base64; if (logoBase64) payload.logo_image_base64 = logoBase64; await fetch('/admin/api/template-config', {method:'POST', headers:{'Content-Type':'application/json'}, body: JSON.stringify(payload)}); alert('Vzhled uložen. Obnovte stránku pro zobrazení změn.'); loadTplData(); });
                document.getElementById('form-layout').addEventListener('submit', async(e)=>{ e.preventDefault(); await fetch('/admin/api/template-config', {method:'POST', headers:{'Content-Type':'application/json'}, body: JSON.stringify({header: getTinyContent('tplHeader'), footer: getTinyContent('tplFooter')})}); alert('Uloženo.'); });
                document.getElementById('form-customcode').addEventListener('submit', async(e)=>{ 
                    e.preventDefault(); 
                    await fetch('/admin/api/template-config', {
                        method:'POST', 
                        headers:{'Content-Type':'application/json'}, 
                        body: JSON.stringify({
                            custom_head: document.getElementById('tplCustomHead').value, 
                            custom_body: document.getElementById('tplCustomBody').value, 
                            custom_css: document.getElementById('tplCustomCss').value
                        })
                    }); 
                    customAlert('Vlastní kódy uloženy.', 'Hotovo'); 
                });
                document.getElementById('form-menu').addEventListener('submit', async(e)=>{ 
                    e.preventDefault(); 
                    await fetch('/admin/api/menus', {method:'POST', headers:{'Content-Type':'application/json'}, body: JSON.stringify({id: document.getElementById('menuId').value, label: document.getElementById('menuLabel').value, url: document.getElementById('menuUrl').value, order: document.getElementById('menuOrder').value, parent_id: document.getElementById('menuParent').value})}); 
                    closeMenuModal(); 
                    loadTplData(); 
                }); 
                document.getElementById('form-boxes').addEventListener('submit', async(e)=>{ 
                    e.preventDefault(); 
                    const sysType = document.getElementById('boxSystemType').value; 
                    let finalContent = document.getElementById('boxContent').value; 
                    if(sysType === 'clock') finalContent = document.getElementById('boxClockType').value; 
                    if(sysType === 'weather') finalContent = document.getElementById('boxWeatherCity').value || 'Praha'; 
                    if(sysType === 'onair') finalContent = document.getElementById('boxOnAirClock').checked ? '1' : '0'; 
                    await fetch('/admin/api/boxes', {
                        method:'POST', 
                        headers:{'Content-Type':'application/json'}, 
                        body: JSON.stringify({id: document.getElementById('boxId').value, title: document.getElementById('boxTitle').value, position: document.getElementById('boxPosition').value, order: document.getElementById('boxOrder').value, active: document.getElementById('boxActive').checked, content: finalContent, is_system: document.getElementById('boxIsSystem').value === '1', system_type: sysType})
                    }); 
                    closeBoxModal(); 
                    loadTplData(); 
                });
                document.getElementById('form-errors').addEventListener('submit', async(e)=>{ 
                    e.preventDefault(); 
                    const filename = document.getElementById('currentErrorFile').value;
                    await fetch('/admin/api/system-files?file=' + filename, { method:'POST', headers:{'Content-Type':'application/json'}, body: JSON.stringify({ content: getTinyContent('errorFileContent') }) }); 
                    customAlert('Chybová stránka ' + filename + ' byla uložena.', 'Uloženo'); 
                });
                const customForm = document.getElementById('form-custom-forms');
                if (customForm) { customForm.addEventListener('submit', async(e)=>{ e.preventDefault(); try { const fields = JSON.parse(document.getElementById('formFields').value); await fetch('/admin/api/forms', {method:'POST', headers:{'Content-Type':'application/json'}, body: JSON.stringify({id: document.getElementById('formId').value, name: document.getElementById('formName').value, slug: document.getElementById('formSlug').value, notify: document.getElementById('formNotify').value, fields: fields})}); customForm.reset(); document.getElementById('formId').value=''; loadTplData(); } catch(err) { customAlert('JSON definice polí není validní. Zkontrolujte uvozovky.', 'Chyba syntaxe'); } }); }
                loadTplData();
            </script>