Files
dashcaddy/status/dist/features.js
2026-03-23 10:34:57 +01:00

1368 lines
208 KiB
JavaScript

(function(){injectModal("logo-modal",`<div id="logo-modal" class="weather-modal">
<div class="weather-modal-content" style="min-width: 400px; max-width: 520px;">
<h3>Dashboard Settings</h3>
<p style="font-size: 0.85rem; color: var(--muted); margin: 0 0 16px;">
Customize your dashboard's appearance and system preferences.
</p>
<div class="mb-16">
<label for="dashboard-title" class="form-label-bold">Dashboard Title:</label>
<input type="text" id="dashboard-title" placeholder="DashCaddy" maxlength="50" style="width: 100%; padding: 10px 12px; border: 1px solid var(--border); border-radius: 4px; background: var(--card-bg); color: var(--fg); font-size: 1rem;" />
<p class="tiny-hint">Shown in browser tab and header (max 50 characters)</p>
</div>
<hr class="hr-divider" />
<div class="mb-16">
<label class="form-label-bold">Logo:</label>
<p class="tiny-hint" style="margin-top: 2px;">Separate logos for dark and light themes, or use the same for both.</p>
</div>
<div style="display: flex; gap: 12px; margin-bottom: 12px;">
<div style="flex: 1; text-align: center; padding: 16px 10px; border-radius: 8px; background: #1a1a2e; border: 1px solid rgba(255,255,255,.1);">
<img id="logo-preview-dark" src="/assets/dashcaddy-logo-dark.png" alt="Dark theme logo" style="max-height: 60px; max-width: 100%;" />
<p style="font-size: 0.65rem; color: #9aa6bf; margin-top: 6px;">Dark themes</p>
</div>
<div style="flex: 1; text-align: center; padding: 16px 10px; border-radius: 8px; background: #f0f0f0; border: 1px solid rgba(0,0,0,.1);">
<img id="logo-preview-light" src="/assets/dashcaddy-logo-light.png" alt="Light theme logo" style="max-height: 60px; max-width: 100%;" />
<p style="font-size: 0.65rem; color: #5f6b7a; margin-top: 6px;">Light themes</p>
</div>
</div>
<p id="logo-status" style="font-size: 0.75rem; color: var(--muted); margin-bottom: 12px; text-align: center;">Using default logos</p>
<div class="mb-16">
<label style="display: flex; align-items: center; gap: 8px; font-size: 0.82rem; cursor: pointer; user-select: none;">
<input type="checkbox" id="logo-same-both" /> Use same logo for both
</label>
</div>
<div id="logo-dual-uploads" class="mb-16" style="display: flex; gap: 12px;">
<div style="flex: 1;">
<label for="logo-upload-dark" style="display: block; margin-bottom: 6px; font-size: 0.8rem;">Dark theme logo:</label>
<input type="file" id="logo-upload-dark" accept="image/*" class="input-card-alt" style="font-size: 0.75rem;" />
</div>
<div style="flex: 1;">
<label for="logo-upload-light" style="display: block; margin-bottom: 6px; font-size: 0.8rem;">Light theme logo:</label>
<input type="file" id="logo-upload-light" accept="image/*" class="input-card-alt" style="font-size: 0.75rem;" />
</div>
</div>
<div id="logo-single-upload" class="mb-16" style="display: none;">
<label for="logo-upload-single" style="display: block; margin-bottom: 6px; font-size: 0.8rem;">Upload logo:</label>
<input type="file" id="logo-upload-single" accept="image/*" class="input-card-alt" />
<p class="tiny-hint">This logo will be used on all themes</p>
</div>
<div class="mb-16">
<label style="display: block; margin-bottom: 8px;">Logo Position:</label>
<div id="logo-position-btns" class="flex-row-gap">
<button type="button" data-pos="left" class="logo-pos-btn btn-option">Left</button>
<button type="button" data-pos="center" class="logo-pos-btn btn-option">Center</button>
<button type="button" data-pos="right" class="logo-pos-btn btn-option">Right</button>
</div>
</div>
<hr class="hr-divider" />
<div class="mb-16">
<label class="form-label-bold">Favicon (Browser Tab Icon):</label>
<div id="favicon-preview-container" style="display: flex; align-items: center; gap: 12px; margin-bottom: 8px; padding: 12px; border-radius: 6px; background: var(--card-bg);">
<img id="favicon-preview" src="/assets/dashcaddy-favicon.ico" alt="Current favicon" style="width: 32px; height: 32px; image-rendering: pixelated;" onerror="this.src='data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 32 32%22><rect fill=%22%23667%22 width=%2232%22 height=%2232%22 rx=%224%22/></svg>'" />
<span id="favicon-status" class="text-tiny-muted">Using DashCaddy favicon</span>
</div>
<input type="file" id="favicon-upload" accept="image/png,image/svg+xml" class="input-card-alt" />
<p class="tiny-hint">Upload PNG or SVG - automatically converted to ICO</p>
</div>
<hr class="hr-divider" />
<div class="mb-16">
<label for="settings-timezone" class="form-label-bold">Timezone:</label>
<select id="settings-timezone" style="width: 100%; padding: 10px 12px; border: 1px solid var(--border); border-radius: 4px; background: var(--card-bg); color: var(--fg); font-size: 1rem;">
<!-- Populated by JS with IANA timezones -->
</select>
<p class="tiny-hint">Used by all deployed containers. Changes apply to new deployments.</p>
</div>
<div class="weather-modal-buttons">
<button id="logo-reset" style="background: color-mix(in srgb, #ef4444 20%, transparent); border-color: #ef4444; color: #ef4444;">Reset to Default</button>
<button id="logo-cancel">Cancel</button>
<button id="logo-save" class="btn-accent">Save</button>
</div>
</div>
</div>`);const y=document.getElementById("logo-modal"),h=document.getElementById("logo-preview-dark"),L=document.getElementById("logo-preview-light"),T=document.getElementById("logo-status"),B=document.getElementById("logo-same-both"),N=document.getElementById("logo-dual-uploads"),D=document.getElementById("logo-single-upload"),A=document.getElementById("logo-upload-dark"),$=document.getElementById("logo-upload-light"),P=document.getElementById("logo-upload-single"),C=document.querySelector("#brand .brand-logo-dark"),H=document.querySelector("#brand .brand-logo-light"),x=document.querySelector(".top-row"),O=document.getElementById("dashboard-title"),z=DC.NAME;let S=null,E=null,k=null,b="left",m=z;B?.addEventListener("change",()=>{B.checked?(N.style.display="none",D.style.display="",S=null,E=null):(N.style.display="flex",D.style.display="none",k=null)});function f(o,s){if(!o||!o.type.startsWith("image/")){showNotification("Please select an image file","warning");return}const u=new FileReader;u.onload=l=>s(l.target.result),u.readAsDataURL(o)}A?.addEventListener("change",o=>{f(o.target.files[0],s=>{S=s,h.src=s,T.textContent="New dark logo ready to save"})}),$?.addEventListener("change",o=>{f(o.target.files[0],s=>{E=s,L.src=s,T.textContent="New light logo ready to save"})}),P?.addEventListener("change",o=>{f(o.target.files[0],s=>{k=s,h.src=s,L.src=s,T.textContent="New logo ready to save (both themes)"})});function c(o){x.setAttribute("data-logo-pos",o),document.querySelectorAll(".logo-pos-btn").forEach(s=>{s.style.background=s.dataset.pos===o?"var(--accent)":"var(--card-bg)",s.style.color=s.dataset.pos===o?"white":"var(--fg)"})}function d(o){m=o||z,document.title=m;const s=document.querySelector(".dashboard-title");s&&(s.textContent=m)}async function a(){try{const o=await fetch("/api/v1/logo");if(o.ok){const s=await o.json();s.customLogoDark&&(C.src=s.customLogoDark,h.src=s.customLogoDark),s.customLogoLight&&(H.src=s.customLogoLight,L.src=s.customLogoLight),!s.customLogoDark&&!s.customLogoLight&&s.customLogo&&(C.src=s.customLogo,H.src=s.customLogo,h.src=s.customLogo,L.src=s.customLogo),s.isDefault||(T.textContent="Using custom logo"),s.position&&(b=s.position,c(s.position)),s.dashboardTitle&&d(s.dashboardTitle)}}catch(o){console.warn("Could not load custom logo:",o.message)}}document.querySelectorAll(".logo-pos-btn").forEach(o=>{o.addEventListener("click",()=>{b=o.dataset.pos,c(b)})}),document.getElementById("brand")?.addEventListener("click",()=>{S=null,E=null,k=null,A&&(A.value=""),$&&($.value=""),P&&(P.value=""),B&&(B.checked=!1),N.style.display="flex",D.style.display="none",h.src=C.src,L.src=H.src;const o=C.src.includes("custom-logo")||H.src.includes("custom-logo");T.textContent=o?"Using custom logo":"Using default logos",c(b),O.value=m,y.classList.add("show")}),document.getElementById("logo-save")?.addEventListener("click",async()=>{try{const o=O.value.trim()||z,s={position:b,dashboardTitle:o};B?.checked&&k?(s.dataDark=k,s.dataLight=k):(S&&(s.dataDark=S),E&&(s.dataLight=E));const u=await secureFetch("/api/v1/logo",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});if(u.ok){const l=await u.json(),g="?t="+Date.now();l.pathDark&&(C.src=l.pathDark+g,h.src=l.pathDark+g),l.pathLight&&(H.src=l.pathLight+g,L.src=l.pathLight+g),c(b),d(o),y.classList.remove("show")}else{const l=await u.json();showNotification("Failed to save: "+l.error,"error")}}catch(o){showNotification("Error saving: "+o.message,"error")}}),document.getElementById("logo-reset")?.addEventListener("click",async()=>{if(confirm(`Reset all branding to DashCaddy defaults?
This will reset the logo, favicon, title, and position.`))try{if((await secureFetch("/api/v1/logo",{method:"DELETE"})).ok&&(C.src="/assets/dashcaddy-logo-dark.png",H.src="/assets/dashcaddy-logo-light.png",h.src="/assets/dashcaddy-logo-dark.png",L.src="/assets/dashcaddy-logo-light.png",T.textContent="Using default logos",S=null,E=null,k=null,O.value=z,d(z),b="left",c("left")),(await secureFetch("/api/v1/favicon",{method:"DELETE"})).ok){const u=document.querySelector('link[rel="icon"]'),l=document.getElementById("favicon-preview"),g=document.getElementById("favicon-status");u&&(u.href="/assets/dashcaddy-favicon.ico?t="+Date.now()),l&&(l.src="/assets/dashcaddy-favicon.ico?t="+Date.now()),g&&(g.textContent="Using DashCaddy favicon"),r=null}}catch(o){showNotification("Error resetting branding: "+o.message,"error")}}),wireModal(y,document.getElementById("logo-cancel"));const n=document.getElementById("favicon-preview"),e=document.getElementById("favicon-status"),t=document.getElementById("favicon-upload"),i=document.querySelector('link[rel="icon"]')||document.createElement("link");let r=null;document.querySelector('link[rel="icon"]')||(i.rel="icon",i.href="/assets/dashcaddy-favicon.ico",document.head.appendChild(i));async function p(){try{const o=await fetch("/api/v1/favicon");if(o.ok){const s=await o.json();s.customFavicon&&(i.href=s.customFavicon+"?t="+Date.now(),n.src=s.customFavicon+"?t="+Date.now(),e.textContent="Using custom favicon")}}catch(o){console.warn("Could not load custom favicon:",o.message)}}t?.addEventListener("change",o=>{const s=o.target.files[0];if(!s)return;if(!s.type.match(/^image\/(png|svg\+xml)$/)){showNotification("Please select a PNG or SVG file","warning"),t.value="";return}const u=new FileReader;u.onload=l=>{r=l.target.result,n.src=r,e.textContent="New favicon ready to save"},u.readAsDataURL(s)}),document.getElementById("logo-save")?.addEventListener("click",async()=>{if(r)try{const o=await secureFetch("/api/v1/favicon",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({data:r})});if(o.ok){const s=await o.json();i.href=s.path+"?t="+Date.now(),n.src=s.path+"?t="+Date.now(),e.textContent="Using custom favicon",r=null}else{const s=await o.json();showNotification("Failed to save favicon: "+s.error,"error")}}catch(o){showNotification("Error saving favicon: "+o.message,"error")}}),p(),a();const v=document.getElementById("settings-timezone");v&&(new MutationObserver(()=>{y.classList.contains("show")&&v.options.length===0&&(async()=>{let s;try{const u=await fetch("/api/v1/config");u.ok&&(s=(await u.json()).timezone)}catch{}window.populateTimezoneSelect(v,s)})()}).observe(y,{attributes:!0,attributeFilter:["class"]}),document.getElementById("logo-save")?.addEventListener("click",async()=>{const s=v.value;if(s)try{const u=await fetch("/api/v1/config");if(!u.ok)return;const l=await u.json();l.timezone=s,l.updatedAt=new Date().toISOString(),await secureFetch("/api/v1/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)})}catch(u){console.warn("Failed to save timezone:",u.message)}}))})(),window.populateTimezoneSelect=function(y,h){const L=Intl.supportedValuesOf("timeZone"),T=h||Intl.DateTimeFormat().resolvedOptions().timeZone||"UTC";y.innerHTML="";for(const B of L){const N=document.createElement("option");N.value=B,N.textContent=B.replace(/_/g," "),B===T&&(N.selected=!0),y.appendChild(N)}},(function(){let y="homelab",h=null;async function L(){try{const f=await fetch("/api/v1/config");if(f.ok&&(h=await f.json(),h&&h.setupComplete))return document.getElementById("setup-wizard").style.display="none",!0}catch(f){console.warn("Could not fetch server config, checking localStorage fallback:",f.message)}return safeGet("dashcaddy-setup")?(document.getElementById("setup-wizard").style.display="none",!0):(document.getElementById("setup-wizard").style.display="flex",!1)}L();const T=document.getElementById("setup-timezone");T&&window.populateTimezoneSelect(T);function B(m){document.querySelectorAll(".setup-step").forEach(c=>{c.style.display="none"});const f=document.getElementById(m);f&&(f.style.display="block")}function N(){const m=document.getElementById("setup-summary-content");if(!m)return;let f='<div style="display: grid; gap: 20px;">';if(y==="homelab"){const d=document.getElementById("setup-tld")?.value?.trim()||".home",a=document.getElementById("setup-ca-name")?.value?.trim()||"",n=document.getElementById("setup-dns-ip")?.value?.trim()||"",e=document.getElementById("setup-dns-port")?.value?.trim()||DC.DEFAULTS.DNS_PORT;f+=`
<div>
<h3 style="margin: 0 0 12px; color: var(--accent);">Home Lab Configuration</h3>
<div style="display: grid; gap: 12px; font-size: 0.95rem;">
<div><strong>TLD:</strong> ${d}</div>
<div><strong>Certificate Authority:</strong> ${a}</div>
<div><strong>DNS Server:</strong> ${n}:${e}</div>
<div><strong>Example URLs:</strong> https://uptime${d}, https://nextcloud${d}</div>
</div>
</div>
`}else if(y==="simple"){const d=document.getElementById("setup-simple-ip")?.value?.trim()||"localhost";f+=`
<div>
<h3 style="margin: 0 0 12px; color: var(--accent);">Simple Setup</h3>
<div style="display: grid; gap: 12px; font-size: 0.95rem;">
<div><strong>Access Method:</strong> IP:Port only</div>
<div><strong>Default IP:</strong> ${d}</div>
<div><strong>SSL:</strong> None (HTTP only)</div>
<div><strong>Example URLs:</strong> http://${d}:8080, http://${d}:3000</div>
</div>
</div>
`}else if(y==="public"){const d=document.getElementById("setup-public-domain")?.value?.trim()||"",a=document.getElementById("setup-public-email")?.value?.trim()||"",n=document.querySelector('input[name="routing-mode"]:checked')?.value||"subdirectory",e=n==="subdirectory"?`https://${d}/sonarr, https://${d}/grafana`:`https://sonarr.${d}, https://grafana.${d}`;f+=`
<div>
<h3 style="margin: 0 0 12px; color: var(--accent);">Public Server</h3>
<div style="display: grid; gap: 12px; font-size: 0.95rem;">
<div><strong>Domain:</strong> ${d}</div>
<div><strong>SSL:</strong> Let's Encrypt</div>
<div><strong>Email:</strong> ${a}</div>
<div><strong>Routing:</strong> ${n==="subdirectory"?"Subdirectory (domain.com/app)":"Subdomain (app.domain.com)"}</div>
<div><strong>Example URLs:</strong> ${e}</div>
</div>
</div>
`}const c=document.getElementById("setup-timezone")?.value||Intl.DateTimeFormat().resolvedOptions().timeZone||"UTC";f+=`
<div style="margin-top: 8px; padding-top: 12px; border-top: 1px solid var(--border);">
<div style="font-size: 0.95rem;"><strong>Timezone:</strong> ${c.replace(/_/g," ")}</div>
</div>
`,f+="</div>",m.innerHTML=f,B("setup-step-summary")}async function D(m){try{const f=await secureFetch("/api/v1/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(m)});return f.ok?(await f.json(),!0):(console.error("Failed to save config to server:",f.status),!1)}catch(f){return console.error("Error saving config to server:",f),!1}}async function A(){const m={setupComplete:!0,configurationType:y,timestamp:new Date().toISOString(),timezone:document.getElementById("setup-timezone")?.value||Intl.DateTimeFormat().resolvedOptions().timeZone||"UTC"};y==="homelab"?(m.tld=document.getElementById("setup-tld")?.value?.trim()||".home",m.caName=document.getElementById("setup-ca-name")?.value?.trim()||"",m.dns={provider:"technitium",ip:document.getElementById("setup-dns-ip")?.value?.trim()||"",port:document.getElementById("setup-dns-port")?.value?.trim()||DC.DEFAULTS.DNS_PORT,token:document.getElementById("setup-dns-token")?.value?.trim()||""},m.defaults={dnsType:"private",sslType:"internal",targetIP:"localhost"}):y==="simple"?(m.defaultIP=document.getElementById("setup-simple-ip")?.value?.trim()||"localhost",m.defaults={dnsType:"none",sslType:"none",targetIP:m.defaultIP}):y==="public"&&(m.domain=document.getElementById("setup-public-domain")?.value?.trim()||"",m.email=document.getElementById("setup-public-email")?.value?.trim()||"",m.routingMode=document.querySelector('input[name="routing-mode"]:checked')?.value||"subdirectory",m.defaults={dnsType:m.routingMode==="subdirectory"?"none":"public",sslType:"letsencrypt",targetIP:"localhost"});const f=await D(m);safeSet("dashcaddy-config",JSON.stringify(m)),safeSet("dashcaddy-setup","completed"),document.getElementById("setup-wizard").style.display="none";const c=y==="homelab"?"Professional Home Lab":y==="simple"?"Simple Setup":"Public Server",d=f?"server (shared across all devices)":"locally (this browser only)";showNotification(`Setup Complete! Configured for: ${c}. Settings saved to: ${d}`,"success",5e3),setTimeout(()=>location.reload(),500)}const $=document.getElementById("setup-step-1-next");$&&($.onclick=function(m){m.preventDefault();const f=document.querySelector('input[name="config-type"]:checked');f&&(y=f.value),B(y==="homelab"?"setup-step-homelab":y==="simple"?"setup-step-simple":y==="public"?"setup-step-public":"setup-step-homelab")});const P=document.getElementById("setup-skip");P&&(P.onclick=async function(m){m.preventDefault(),confirm("Skip setup? You can run it later from Settings.")&&(await D({setupComplete:!0,skipped:!0,timestamp:new Date().toISOString()}),safeSet("dashcaddy-setup","skipped"),document.getElementById("setup-wizard").style.display="none")});const C=document.getElementById("setup-tld");C&&(C.oninput=function(m){const f=m.target.value||".home",c=document.getElementById("tld-preview"),d=document.getElementById("tld-preview-2");c&&(c.textContent=f),d&&(d.textContent=f)});const H=document.getElementById("setup-homelab-back");H&&(H.onclick=function(m){m.preventDefault(),B("setup-step-1")});const x=document.getElementById("setup-homelab-next");x&&(x.onclick=function(m){m.preventDefault();const f=document.getElementById("setup-tld")?.value?.trim()||"",c=document.getElementById("setup-ca-name")?.value?.trim()||"",d=document.getElementById("setup-dns-ip")?.value?.trim()||"";if(!f||!f.startsWith(".")){showNotification("Please enter a valid TLD starting with a dot (e.g., .home)","warning");return}if(!c){showNotification("Please enter a Certificate Authority name","warning");return}if(!d){showNotification("Please enter your DNS server IP address","warning");return}N()});const O=document.getElementById("setup-simple-back");O&&(O.onclick=function(m){m.preventDefault(),B("setup-step-1")});const z=document.getElementById("setup-simple-next");z&&(z.onclick=function(m){m.preventDefault(),N()}),document.querySelectorAll('input[name="routing-mode"]').forEach(function(m){m.onchange=function(){var f=document.getElementById("dns-requirement-note");f&&(f.textContent=this.value==="subdirectory"?"Only one DNS record needed (for the main domain)":"You'll need to configure DNS manually for each subdomain")}});const S=document.getElementById("setup-public-back");S&&(S.onclick=function(m){m.preventDefault(),B("setup-step-1")});const E=document.getElementById("setup-public-next");E&&(E.onclick=function(m){m.preventDefault();const f=document.getElementById("setup-public-domain")?.value?.trim()||"",c=document.getElementById("setup-public-email")?.value?.trim()||"";if(!f){showNotification("Please enter your domain name","warning");return}if(!c||!c.includes("@")){showNotification("Please enter a valid email address","warning");return}N()});const k=document.getElementById("setup-summary-back");k&&(k.onclick=function(m){m.preventDefault(),y==="homelab"?B("setup-step-homelab"):y==="simple"?B("setup-step-simple"):y==="public"&&B("setup-step-public")});const b=document.getElementById("setup-finish");b&&(b.onclick=function(m){m.preventDefault(),A()}),window.getGlobalConfig=async function(){try{const f=await fetch("/api/v1/config");if(f.ok){const c=await f.json();if(c&&c.setupComplete)return c}}catch{console.warn("Could not fetch config from server")}const m=safeGet("dashcaddy-config");return m?JSON.parse(m):{setupComplete:!1,configurationType:"homelab",tld:".home",caName:"",defaults:{dnsType:"private",sslType:"internal",targetIP:"localhost"}}},window.resetSetupWizard=async function(){if(confirm("Reset DashCaddy configuration? This will show the setup wizard again.")){try{await secureFetch("/api/v1/config",{method:"DELETE"})}catch{console.warn("Could not delete server config")}safeRemove("dashcaddy-setup"),safeRemove("dashcaddy-config"),location.reload()}}})(),(function(){injectModal("app-selector-modal",`<div id="app-selector-modal" class="weather-modal">
<div class="app-selector-content">
<h2 style="margin: 0 0 24px; color: var(--fg); text-align: center;">Choose an App</h2>
<div id="app-selector-grid" class="app-selector-grid"></div>
<div style="text-align: center; margin-top: 24px;">
<button id="app-selector-cancel">Cancel</button>
</div>
</div>
</div>`),injectModal("app-deploy-modal",`<div id="app-deploy-modal" class="weather-modal">
<div class="weather-modal-content" style="min-width: 600px; max-width: 700px;">
<h3 id="app-deploy-title">Deploy Application</h3>
<div style="display: grid; grid-template-columns: 1fr; gap: 16px; margin-top: 16px;">
<!-- Subdomain/Domain -->
<div>
<label for="deploy-subdomain" class="form-label-accent-sm">
\u{1F310} Subdomain or Domain
</label>
<input type="text" id="deploy-subdomain" placeholder="uptime"
style="width: 100%; padding: 10px; background: var(--card-bg); color: var(--fg); border: 1px solid var(--border); border-radius: 6px; font-size: 0.95rem;" />
<div class="form-hint-sm">
Your app will be available at: <span id="deploy-url-preview" style="color: var(--accent); font-weight: 500;">uptime.home</span>
</div>
<div id="subpath-compat-warning" style="display: none; padding: 8px 12px; border-radius: 6px; background: color-mix(in srgb, #ff9800 10%, var(--card-bg)); border: 1px solid color-mix(in srgb, #ff9800 30%, transparent); margin-top: 8px; font-size: 0.85rem;"></div>
</div>
<!-- DNS Configuration -->
<div>
<label class="form-label-accent">
\u{1F5C2}\uFE0F DNS Configuration
</label>
<div class="flex-col-gap">
<label class="radio-option">
<input type="radio" name="dns-type" value="private" checked style="margin-right: 10px;" />
<div>
<div class="fw-500">Private DNS (Technitium)</div>
<div class="text-hint">Use your local DNS server with custom TLD (.sami, .home, etc.)</div>
</div>
</label>
<label class="radio-option">
<input type="radio" name="dns-type" value="public" style="margin-right: 10px;" />
<div>
<div class="fw-500">Public DNS</div>
<div class="text-hint">Use a real domain (example.com) - requires DNS provider setup</div>
</div>
</label>
<label class="radio-option">
<input type="radio" name="dns-type" value="none" style="margin-right: 10px;" />
<div>
<div class="fw-500">No DNS (IP:Port only)</div>
<div class="text-hint">Access via IP address and port - no domain setup</div>
</div>
</label>
</div>
</div>
<!-- SSL Configuration -->
<div>
<label class="form-label-accent">
\u{1F512} SSL/TLS Certificate
</label>
<div class="flex-col-gap">
<label class="radio-option">
<input type="radio" name="ssl-type" value="internal" checked style="margin-right: 10px;" />
<div>
<div class="fw-500">Internal CA</div>
<div class="text-hint">Use Caddy's internal certificate authority (self-signed)</div>
</div>
</label>
<label class="radio-option">
<input type="radio" name="ssl-type" value="letsencrypt" style="margin-right: 10px;" />
<div>
<div class="fw-500">Let's Encrypt</div>
<div class="text-hint">Free public SSL certificate (requires public domain)</div>
</div>
</label>
<label class="radio-option">
<input type="radio" name="ssl-type" value="none" style="margin-right: 10px;" />
<div>
<div class="fw-500">No SSL (HTTP only)</div>
<div class="text-hint">\u26A0\uFE0F Not recommended - traffic will be unencrypted</div>
</div>
</label>
</div>
</div>
<!-- Media Library Path (shown for media apps) -->
<div id="media-path-section" style="display: none;">
<label class="form-label-accent">
\u{1F4C1} Media Library Location
</label>
<div style="display: flex; flex-direction: column; gap: 10px;">
<!-- Detected mounts from existing media servers -->
<div id="detected-mounts-container" style="display: none;">
<div style="font-size: 0.85rem; color: var(--success); margin-bottom: 6px;">
\u2713 Detected from existing media servers:
</div>
<div id="detected-mounts-list" style="display: flex; gap: 8px; flex-wrap: wrap;"></div>
</div>
<!-- Path input with browse button -->
<div class="flex-row-gap">
<input type="text" id="deploy-media-path" placeholder="/media/Movies, /media/TVShows"
class="input-flex" style="font-size: 0.95rem;" />
<button type="button" id="browse-media-btn" style="padding: 10px 16px; background: var(--accent); color: white; border: none; border-radius: 6px; cursor: pointer; font-weight: 500; white-space: nowrap;">
\u{1F4C2} Browse
</button>
</div>
<div id="media-path-description" class="text-hint">
Select folders from existing servers, browse, or type paths manually. Separate multiple with commas.
</div>
<!-- Selected paths display -->
<div id="selected-media-paths" style="display: none; flex-wrap: wrap; gap: 6px;"></div>
</div>
</div>
<!-- Plex Claim Token (shown only for Plex deployments) -->
<div id="plex-claim-section" style="display: none;">
<label class="form-label-accent">
\u{1F511} Plex Claim Token
</label>
<div class="flex-row-gap">
<input type="text" id="deploy-plex-claim" placeholder="claim-xxxxxxxxxxxxxxxxxxxx"
class="input-flex" style="font-size: 0.95rem;" />
<a href="https://plex.tv/claim" target="_blank" rel="noopener noreferrer"
style="padding: 10px 16px; background: #e5a00d; color: #000; border: none; border-radius: 6px; cursor: pointer; font-weight: 500; white-space: nowrap; text-decoration: none; display: flex; align-items: center;">
Get Token
</a>
</div>
<div style="font-size: 0.8rem; color: #e5a00d; margin-top: 4px;">
Token expires in 4 minutes! Get it right before clicking Deploy. Leave empty to configure Plex manually later.
</div>
</div>
<!-- Tailscale Security -->
<div id="tailscale-section">
<label class="form-label-accent">
\u{1F510} Tailscale Security
</label>
<div class="flex-col-gap">
<label class="radio-option">
<input type="checkbox" id="deploy-tailscale-only" style="margin-right: 10px; width: 18px; height: 18px;" />
<div>
<div class="fw-500">Tailscale-Only Access</div>
<div class="text-hint">Restrict this service to Tailscale users only (100.x.x.x IPs)</div>
</div>
</label>
<div id="tailscale-status" style="padding: 8px 12px; background: var(--card-bg); border-radius: 6px; font-size: 0.85rem;">
<span style="color: var(--muted);">Checking Tailscale status...</span>
</div>
</div>
</div>
<!-- Advanced Options (Collapsible) -->
<details>
<summary style="cursor: pointer; color: var(--accent); font-weight: 500; margin-bottom: 8px;">\u2699\uFE0F Advanced Options</summary>
<div style="margin-top: 12px; display: grid; gap: 12px;">
<div>
<label for="deploy-port" style="display: block; margin-bottom: 6px;">Custom Port (optional)</label>
<input type="number" id="deploy-port" placeholder="Leave empty for default"
class="form-input-card" />
</div>
<div>
<label for="deploy-ip" style="display: block; margin-bottom: 6px;">Target IP Address</label>
<input type="text" id="deploy-ip" value="localhost"
class="form-input-card" />
<div class="form-hint-sm">
Use 'localhost' for same-host containers, or specific IP for remote services
</div>
</div>
<div id="volume-mounts-section" style="display: none;">
<label class="form-label-accent-sm">\u{1F4C2} Volume Mounts</label>
<div style="font-size: 0.8rem; color: var(--muted); margin-bottom: 8px;">
Customize where container data is stored on the host. Media volumes are configured above.
</div>
<div id="volume-mounts-list" style="display: grid; gap: 8px;"></div>
</div>
</div>
</details>
</div>
<div class="weather-modal-buttons" style="margin-top: 24px;">
<button id="app-deploy-cancel">Cancel</button>
<button id="app-deploy-confirm" class="btn-accent">
\u{1F680} Deploy
</button>
</div>
</div>
</div>`);const y="custom-apps";let h=null,L=null;const T=document.getElementById("app-selector-modal"),B=document.getElementById("app-selector-grid");async function N(){try{const t=await(await fetch("/api/v1/apps/templates")).json();if(t.success)return h=t.templates,L=t.categories,!0}catch(e){console.error("Failed to fetch app templates:",e)}return!1}async function D(e){try{return await(await fetch(`/api/v1/apps/ports/${e}/check`)).json()}catch(t){return console.error("Failed to check port:",t),{available:!0}}}async function A(e){try{const i=await(await fetch(`/api/v1/apps/ports/${e}/suggest`)).json();if(i.success)return i.suggestedPort}catch(t){console.error("Failed to get suggested port:",t)}return e}async function $(){if(B.innerHTML='<div style="text-align: center; padding: 40px; color: var(--muted);">Loading app templates...</div>',!h&&!await N()){B.innerHTML='<div style="text-align: center; padding: 40px; color: var(--error);">Failed to load app templates. Please try again.</div>';return}B.innerHTML="";const e={};for(const[i,r]of Object.entries(h)){const p=r.category||"Other";e[p]||(e[p]=[]),e[p].push({id:i,...r})}const t=L?Object.keys(L):Object.keys(e).sort();for(const i of t){const r=e[i];if(!r||r.length===0)continue;r.sort((o,s)=>(s.popularity||0)-(o.popularity||0));const p=document.createElement("div");p.className="app-category-header";const v=L?.[i]||{};p.innerHTML=`${escapeHtml(v.icon||"")} ${escapeHtml(i)}`,v.color&&(p.style.borderBottomColor=v.color),B.appendChild(p),r.forEach(o=>{const s=document.createElement("div");s.className="app-option";const u=o.isDashboardWidget,l=u&&safeGet("widget-"+o.id+"-enabled")!=="false",g=u?`<div style="font-size: 0.65rem; padding: 2px 6px; border-radius: 4px; margin-top: 4px; background: ${l?"#2ecc7130":"#e74c3c30"}; color: ${l?"#2ecc71":"#e74c3c"}; font-weight: 600;">${l?"ON":"OFF"}</div>`:"",I=!u&&o.difficulty?`<div style="font-size: 0.65rem; padding: 2px 6px; border-radius: 4px; margin-top: 4px; background: ${o.difficulty==="Easy"?"#2ecc71":o.difficulty==="Intermediate"?"#f39c12":"#e74c3c"}20; color: ${o.difficulty==="Easy"?"#2ecc71":o.difficulty==="Intermediate"?"#f39c12":"#e74c3c"};">${escapeHtml(o.difficulty)}</div>`:"";s.innerHTML=`
<div class="app-option-icon">${escapeHtml(o.icon||"\u{1F4E6}")}</div>
<div class="app-option-name">${escapeHtml(o.name)}</div>
<div class="app-option-desc">${escapeHtml(o.description||"")}</div>
${g}${I}
`,u?s.onclick=()=>P(o,s):s.onclick=()=>C(o),B.appendChild(s)})}window.renderRecipeCards&&await window.renderRecipeCards(B)}function P(e,t){const i="widget-"+e.id+"-enabled",p=!(safeGet(i)!=="false");safeSet(i,String(p));const v=e.widgetSelector;if(v){const s=document.querySelector(v);s&&(s.style.display=p?"":"none")}const o=t.querySelector('div[style*="border-radius: 4px"]');o&&(o.textContent=p?"ON":"OFF",o.style.background=p?"#2ecc7130":"#e74c3c30",o.style.color=p?"#2ecc71":"#e74c3c"),showNotification(`${e.name} widget ${p?"enabled":"disabled"}`,"success",2e3)}async function C(e){const t=document.getElementById("app-deploy-modal"),i=document.getElementById("app-deploy-title"),r=document.getElementById("deploy-subdomain"),p=document.getElementById("deploy-url-preview"),v=document.getElementById("deploy-ip"),o=document.getElementById("deploy-port"),s=document.getElementById("deploy-tailscale-only"),u=document.getElementById("tailscale-status");try{const U=await(await secureFetch("/api/v1/apps/check-existing",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({appId:e.id})})).json();if(U.success&&U.exists){const J=U.container;confirm(`Found existing ${e.name} container:
Container: ${J.name}
Status: ${J.status}
Port: ${J.primaryPort||"N/A"}
Would you like to use this existing container?
Click OK to configure DNS/Caddy for the existing container.
Click Cancel to deploy a new container.`)&&(e._useExisting=!0,e._existingContainer=J)}}catch{}i.textContent=`Deploy ${e.name}`;const l=e.subdomain||e.id.replace(/-/g,"");r.value=l;const g=document.getElementById("subpath-compat-warning");if(g)if(SITE.routingMode==="subdirectory"){const F=e.subpathSupport||"strip";F==="none"?(g.style.display="block",g.innerHTML='<span style="color: #ff9800;">&#9888; <strong>'+e.name+"</strong> does not support subdirectory mode. It may not work correctly at a subpath.</span>"):F==="strip"?(g.style.display="block",g.innerHTML='<span style="color: var(--muted);">&#9432; '+e.name+" has unverified subdirectory support. It may require additional configuration.</span>"):g.style.display="none"}else g.style.display="none";const I=SITE.defaults.dnsType||(SITE.configurationType==="public"?"public":"private"),w=SITE.defaults.sslType||(SITE.configurationType==="public"?"letsencrypt":"internal"),M=document.querySelector(`input[name="dns-type"][value="${I}"]`),R=document.querySelector(`input[name="ssl-type"][value="${w}"]`);M?M.checked=!0:document.querySelector('input[name="dns-type"][value="private"]').checked=!0,R?R.checked=!0:document.querySelector('input[name="ssl-type"][value="internal"]').checked=!0,v.value=SITE.defaults.targetIP||"localhost",s.checked=!1;const q=document.querySelector("#app-deploy-modal .flex-col-gap")?.closest("div"),_=document.querySelector("#app-deploy-modal details"),W=_?.querySelector("div");if(_&&W&&(SITE.configurationType==="public"||SITE.configurationType==="homelab")){const F=document.querySelectorAll('#app-deploy-modal input[name="dns-type"]')[0]?.closest("div.flex-col-gap")?.parentElement,U=document.querySelectorAll('#app-deploy-modal input[name="ssl-type"]')[0]?.closest("div.flex-col-gap")?.parentElement;F&&!F.dataset.moved&&(W.appendChild(F),F.dataset.moved="1"),U&&!U.dataset.moved&&(W.appendChild(U),U.dataset.moved="1")}const j=document.getElementById("media-path-section"),V=document.getElementById("deploy-media-path"),se=document.getElementById("media-path-description");if(e.mediaMount){j.style.display="block",V.value="",V.placeholder="/media/Movies, /media/TVShows or click Browse";const F=document.getElementById("detected-mounts-container"),U=document.getElementById("detected-mounts-list");try{const G=await(await fetch("/api/v1/media/detected-mounts")).json();if(G.success&&G.mounts.length>0){F.style.display="block",U.innerHTML="";const ee=[...new Set(G.mounts.map(Z=>Z.hostPath))];V.value=ee.join(", "),G.mounts.forEach(Z=>{const Y=document.createElement("button");Y.type="button";const le=ee.includes(Z.hostPath);Y.style.cssText=`padding: 8px 14px; font-size: 0.85rem; background: color-mix(in srgb, var(--success) ${le?"40%":"15%"}, var(--card-bg)); border: 1px solid var(--success); border-radius: 6px; cursor: pointer; color: var(--fg);`,Y.innerHTML=`<span style="font-weight: 500;">${escapeHtml(Z.folderName)}</span><br><span style="font-size: 0.7rem; color: var(--muted);">from ${escapeHtml(Z.sourceImage)}</span>`,Y.title=`${Z.hostPath} (from ${Z.sourceContainer})`,Y.onclick=()=>{const re=V.value.split(",").map(de=>de.trim()).filter(de=>de),ce=re.indexOf(Z.hostPath);ce>=0?(re.splice(ce,1),Y.style.background="color-mix(in srgb, var(--success) 15%, var(--card-bg))"):(re.push(Z.hostPath),Y.style.background="color-mix(in srgb, var(--success) 40%, var(--card-bg))"),V.value=re.join(", ")},U.appendChild(Y)})}else F.style.display="none"}catch{F.style.display="none"}document.getElementById("browse-media-btn").onclick=()=>{openFolderBrowser(V)}}else j.style.display="none",V.value="",document.getElementById("detected-mounts-container").style.display="none";const K=document.getElementById("plex-claim-section");K&&(e.id==="plex"||e.claimToken?(K.style.display="block",document.getElementById("deploy-plex-claim").value=""):K.style.display="none");const Q=document.getElementById("volume-mounts-section"),te=document.getElementById("volume-mounts-list");if(te.innerHTML="",e.docker?.volumes?.length){const F=e.mediaMount?.containerPath,U=e.docker.volumes.filter(J=>!J.includes("{{MEDIA_PATH}}")&&!(F&&J.endsWith(":"+F)));U.length>0?(Q.style.display="block",U.forEach((J,G)=>{const[ee,Z]=J.split(":"),Y=document.createElement("div");Y.style.cssText="display: flex; gap: 6px; align-items: center;",Y.innerHTML=`
<input type="text" class="vol-host-path" data-container-path="${Z}" value="${ee}"
style="flex: 1; padding: 8px; background: var(--card-bg); color: var(--fg); border: 1px solid var(--border); border-radius: 6px; font-size: 0.85rem;" />
<span style="color: var(--muted); font-size: 0.85rem; white-space: nowrap;">\u2192 ${Z}</span>
<button type="button" class="vol-browse-btn" style="padding: 8px 10px; background: var(--accent); color: white; border: none; border-radius: 6px; cursor: pointer; font-size: 0.8rem;">\u{1F4C2}</button>
`,te.appendChild(Y),Y.querySelector(".vol-browse-btn").onclick=()=>{const le=Y.querySelector(".vol-host-path");openFolderBrowser(le)}})):Q.style.display="none"}else Q.style.display="none";const ne=e.defaultPort||8080;o.value="",o.placeholder=`Default: ${ne}`;let X=document.getElementById("deploy-port-status");X||(X=document.createElement("div"),X.id="deploy-port-status",X.style.cssText="font-size: 0.8rem; margin-top: 4px;",o.parentNode.appendChild(X));async function oe(){const F=o.value||ne;X.innerHTML='<span style="color: var(--muted);">Checking port...</span>';const U=await D(F);if(U.available)X.innerHTML=`<span style="color: #4caf50;">Port ${escapeHtml(String(F))} is available</span>`;else{const J=await A(ne);X.innerHTML=`
<span style="color: #e74c3c;">Port ${escapeHtml(F)} in use by ${escapeHtml(U.conflict?.usedBy||"unknown")}</span>
`;const G=document.createElement("button");G.type="button",G.textContent=`Use ${J}`,G.style.cssText="margin-left: 8px; padding: 2px 8px; font-size: 0.75rem; cursor: pointer;",G.onclick=()=>{document.getElementById("deploy-port").value=J,X.innerHTML=`<span style="color: #4caf50;">Using suggested port ${escapeHtml(String(J))}</span>`},X.appendChild(G)}}let ie;o.oninput=function(){clearTimeout(ie),ie=setTimeout(oe,500)},oe();try{const U=await(await fetch("/api/v1/tailscale/status")).json();U.success&&U.installed&&U.connected?u.innerHTML=`
<span style="color: #4caf50;">Connected</span>
<span style="color: var(--muted); margin-left: 8px;">${U.self?.hostname} (${U.self?.ip})</span>
<span style="color: var(--muted); margin-left: 8px;">| ${U.deviceCount} devices</span>
`:U.installed?u.innerHTML='<span style="color: #ff9800;">Not connected</span>':(u.innerHTML='<span style="color: var(--muted);">Not available</span>',s.disabled=!0)}catch{u.innerHTML='<span style="color: var(--muted);">Could not check status</span>'}function ae(){const F=r.value||"subdomain",U=document.querySelector('input[name="dns-type"]:checked').value,J=document.querySelector('input[name="ssl-type"]:checked').value;let G="";if(SITE.routingMode==="subdirectory"&&SITE.domain)G=`https://${SITE.domain}/${F}`;else if(U==="private")G=`${J==="none"?"http":"https"}://${buildDomain(F)}`;else if(U==="public"){const ee=J==="none"?"http":"https",Z=SITE.domain||F;G=SITE.domain?`${ee}://${F}.${SITE.domain}`:`${ee}://${F}`}else{const ee=o.value||e.defaultPort||DC.DEFAULTS.SERVICE_PORT;G=`http://${v.value}:${ee}`}p.textContent=G}r.oninput=ae,v.oninput=ae,o.oninput=ae,document.querySelectorAll('input[name="dns-type"]').forEach(F=>{F.onchange=ae}),document.querySelectorAll('input[name="ssl-type"]').forEach(F=>{F.onchange=ae}),ae(),T.classList.remove("show"),t.classList.add("show"),t.dataset.appTemplate=JSON.stringify(e)}async function H(e){const t=e.appTemplate,i=safeGetJSON(y,[]),r=t._useExisting&&t._existingContainer,p=i.find(v=>v.id===e.subdomain);if(!(p&&!r&&!confirm(`An app with subdomain "${e.subdomain}" already exists. Redeploy?`))){if(p){const v=i.indexOf(p);i.splice(v,1),safeSet(y,JSON.stringify(i))}if(r)e.port=t._existingContainer.primaryPort;else{const v=e.port||t.defaultPort||8080;showNotification(`Checking port ${v} availability...`,"info",0);const o=await D(v);if(!o.available){const s=await A(t.defaultPort||8080);if(confirm(`Port ${v} is already in use by ${o.conflict?.usedBy||"another container"}.
Would you like to use port ${s} instead?`))e.port=s;else{showNotification("Deployment cancelled - port conflict","error",5e3);return}}}showNotification(r?`Configuring ${t.name} with existing container...`:`Deploying ${t.name}...`,"info",0);try{const v={appId:t.id,config:{subdomain:e.subdomain,ip:e.ip,createDns:e.dnsType==="private",port:e.port||t.defaultPort||null,sslType:e.sslType,dnsType:e.dnsType,tailscaleOnly:e.tailscaleOnly||!1,mediaPath:e.mediaPath||null,plexClaimToken:e.plexClaimToken||null,customVolumes:e.customVolumes||null}};r&&(v.config.useExisting=!0,v.config.existingContainerId=t._existingContainer.id,v.config.existingPort=t._existingContainer.primaryPort,!e.port&&t._existingContainer.primaryPort&&(v.config.port=t._existingContainer.primaryPort));const s=await(await secureFetch("/api/v1/apps/deploy",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(v)})).json();if(s.success){const u={id:e.subdomain,name:t.name,logo:`/assets/${t.id}.png`,containerId:s.containerId,url:s.url,ip:e.ip,appTemplate:t.id,tailscaleOnly:e.tailscaleOnly||!1};i.push(u),safeSet(y,JSON.stringify(i)),window.APPS&&!window.APPS.some(g=>g.id===t.id)&&(window.APPS.push(u),typeof window.buildGrid=="function"&&window.buildGrid(),typeof window.refreshAll=="function"&&setTimeout(()=>window.refreshAll(),500));let l=s.usedExisting?`${t.name} configured with existing container!
URL: ${s.url}`:`${t.name} deployed successfully!
URL: ${s.url}`;s.warning&&(l+=`
\u26A0 Warning: ${s.warning}`),showNotification(l,"success",8e3),delete t._useExisting,delete t._existingContainer,s.url&&s.url.startsWith("https://")&&x(s.url,t.name),s.setupInstructions&&s.setupInstructions.length>0&&setTimeout(()=>{const g=s.setupInstructions.join(`
`);showNotification(`Setup Instructions for ${t.name}: ${g}`,"info",1e4)},1e3)}else throw new Error(s.error||"Deployment failed")}catch(v){console.error("Deployment error:",v),showNotification(`Failed to deploy ${t.name}: ${v.message}`,"error",8e3)}}}async function x(e,t){showNotification(`\u23F3 Generating SSL certificate for ${t}...`,"warning",6e4);let i=0;const r=12,p=async()=>{i++;try{const v=await fetch(e,{method:"HEAD",mode:"no-cors"});return showNotification(`\u2705 ${t} is ready! SSL certificate generated.`,"success",5e3),!0}catch{return i<r?setTimeout(p,5e3):showNotification(`\u26A0\uFE0F ${t} deployed but SSL certificate may still be generating.
Try refreshing in a moment if you see a certificate error.`,"warning",1e4),!1}};setTimeout(p,3e3)}function O(){safeGetJSON(y,[]).forEach(t=>{window.APPS.some(i=>i.id===t.id)||window.APPS.push(t)})}document.getElementById("add-service-btn")?.addEventListener("click",()=>{$(),T.classList.add("show")}),wireModal(T,document.getElementById("app-selector-cancel"));const z=document.getElementById("app-deploy-modal");document.getElementById("app-deploy-cancel")?.addEventListener("click",()=>{z.classList.remove("show")}),document.getElementById("app-deploy-confirm")?.addEventListener("click",()=>{const e=JSON.parse(z.dataset.appTemplate),t=document.getElementById("deploy-media-path").value.trim(),i=[];document.querySelectorAll("#volume-mounts-list .vol-host-path").forEach(p=>{i.push({hostPath:p.value.trim(),containerPath:p.dataset.containerPath})});const r={appTemplate:e,subdomain:document.getElementById("deploy-subdomain").value.trim(),dnsType:document.querySelector('input[name="dns-type"]:checked').value,sslType:document.querySelector('input[name="ssl-type"]:checked').value,ip:document.getElementById("deploy-ip").value.trim(),port:document.getElementById("deploy-port").value.trim(),tailscaleOnly:document.getElementById("deploy-tailscale-only").checked,mediaPath:t||null,plexClaimToken:document.getElementById("deploy-plex-claim")?.value.trim()||null,customVolumes:i.length>0?i:null};if(!r.subdomain){showNotification("Please enter a subdomain or domain name","warning");return}if(e.mediaMount?.required&&!t){showNotification("Please enter a media library path for this application","warning");return}z.classList.remove("show"),H(r)}),wireModal(z);const S=document.getElementById("folder-browser-modal"),E=document.getElementById("folder-browser-path"),k=document.getElementById("folder-browser-list"),b=document.getElementById("folder-browser-selected"),m=document.getElementById("folder-browser-selected-list");let f="",c=[],d=null;window.openFolderBrowser=function(e){d=e,c=e.value.split(",").map(t=>t.trim()).filter(t=>t),f="",n(),a(""),S.classList.add("show")};async function a(e){E.textContent=e||"Select a drive...",k.innerHTML='<div style="padding: 20px; text-align: center; color: var(--muted);">Loading...</div>';try{const i=await(await fetch(`/api/v1/browse/directories?path=${encodeURIComponent(e)}`)).json();if(!i.success){k.innerHTML=`<div style="padding: 20px; text-align: center; color: var(--error);">Error: ${escapeHtml(i.error)}</div>`;return}f=i.path||"",E.textContent=f||"Select a drive...";let r="";i.parent&&i.parent!==i.path&&(r+=`<div class="folder-item" data-path="${escapeHtml(i.parent)}" style="padding: 12px 16px; border-bottom: 1px solid var(--border); cursor: pointer; display: flex; align-items: center; gap: 10px;">
<span style="font-size: 1.2rem;">\u2B06\uFE0F</span>
<span style="color: var(--muted);">.. Parent Directory</span>
</div>`),i.items.length===0&&!i.parent?r+='<div style="padding: 20px; text-align: center; color: var(--muted);">No browseable drives configured. Check your docker-compose.yml volume mounts.</div>':i.items.length===0?r+='<div style="padding: 20px; text-align: center; color: var(--muted);">No subfolders found</div>':i.items.forEach(p=>{const v=p.type==="drive"?"\u{1F4BE}":"\u{1F4C1}",o=c.includes(p.path),s=o?"background: color-mix(in srgb, var(--success) 20%, transparent);":"";r+=`<div class="folder-item" data-path="${escapeHtml(p.path)}" style="padding: 12px 16px; border-bottom: 1px solid var(--border); cursor: pointer; display: flex; align-items: center; gap: 10px; ${s}">
<span style="font-size: 1.2rem;">${v}</span>
<span style="flex: 1;">${escapeHtml(p.name)}</span>
${o?'<span style="color: var(--success);">\u2713</span>':""}
</div>`}),k.innerHTML=r,k.querySelectorAll(".folder-item").forEach(p=>{p.addEventListener("click",()=>{a(p.dataset.path)}),p.addEventListener("mouseenter",()=>{p.style.background="var(--card-bg)"}),p.addEventListener("mouseleave",()=>{const v=c.includes(p.dataset.path);p.style.background=v?"color-mix(in srgb, var(--success) 20%, transparent)":""})})}catch(t){k.innerHTML=`<div style="padding: 20px; text-align: center; color: var(--error);">Failed to load: ${escapeHtml(t.message)}</div>`}}function n(){if(c.length===0){b.style.display="none";return}b.style.display="block",m.innerHTML=c.map(e=>`
<span style="padding: 6px 12px; background: var(--card-bg); border: 1px solid var(--success); border-radius: 4px; display: flex; align-items: center; gap: 6px;">
${escapeHtml(e)}
<button type="button" onclick="removeSelectedFolder('${escapeHtml(e)}')" style="background: none; border: none; cursor: pointer; color: var(--error); font-size: 1rem; padding: 0;">\xD7</button>
</span>
`).join("")}window.removeSelectedFolder=function(e){c=c.filter(t=>t!==e),n(),a(f)},document.getElementById("folder-browser-select-current").addEventListener("click",()=>{f&&!c.includes(f)&&(c.push(f),n(),a(f))}),wireModal(S,document.getElementById("folder-browser-cancel")),document.getElementById("folder-browser-done").addEventListener("click",()=>{d&&(d.value=c.join(", ")),S.classList.remove("show")}),O()})(),(function(){injectModal("recipe-deploy-modal",`<div id="recipe-deploy-modal" class="weather-modal">
<div class="weather-modal-content" style="min-width: 620px; max-width: 740px;">
<h3 id="recipe-deploy-title">Deploy Recipe</h3>
<!-- Step indicator -->
<div id="recipe-steps" style="display: flex; gap: 4px; margin: 16px 0 24px;">
<div class="recipe-step active" data-step="1"><span>1</span> Components</div>
<div class="recipe-step" data-step="2"><span>2</span> Configuration</div>
<div class="recipe-step" data-step="3"><span>3</span> Review</div>
<div class="recipe-step" data-step="4"><span>4</span> Progress</div>
</div>
<!-- Step 1: Component Selection -->
<div id="recipe-step-1" class="recipe-step-panel">
<label class="form-label-accent-sm">Select Components:</label>
<div id="recipe-component-list" style="display: grid; gap: 10px; margin-top: 8px;"></div>
</div>
<!-- Step 2: Shared Configuration -->
<div id="recipe-step-2" class="recipe-step-panel" style="display:none;">
<div style="display: grid; gap: 16px;">
<!-- Shared volumes -->
<div id="recipe-volumes-section" style="display:none;">
<label class="form-label-accent-sm">Shared Volumes:</label>
<div id="recipe-volume-list" style="display: grid; gap: 10px; margin-top: 8px;"></div>
</div>
<!-- Timezone -->
<div>
<label class="form-label-accent-sm">Timezone:</label>
<input type="text" id="recipe-timezone" value="UTC" placeholder="e.g. America/New_York"
style="width: 100%; padding: 8px 12px; background: var(--card-bg); color: var(--fg); border: 1px solid var(--border); border-radius: 6px;" />
</div>
<!-- Target IP -->
<div>
<label class="form-label-accent-sm">Target IP Address:</label>
<input type="text" id="recipe-ip" value="host.docker.internal" placeholder="localhost or IP"
style="width: 100%; padding: 8px 12px; background: var(--card-bg); color: var(--fg); border: 1px solid var(--border); border-radius: 6px;" />
<div class="form-hint-sm">IP where containers expose ports</div>
</div>
<!-- Tailscale -->
<label class="checkbox-label">
<input type="checkbox" id="recipe-tailscale" />
<span>Restrict to Tailscale network only</span>
</label>
</div>
</div>
<!-- Step 3: Review -->
<div id="recipe-step-3" class="recipe-step-panel" style="display:none;">
<div id="recipe-review-content" style="font-size: 0.9rem; line-height: 1.7;"></div>
</div>
<!-- Step 4: Progress -->
<div id="recipe-step-4" class="recipe-step-panel" style="display:none;">
<div id="recipe-progress-list" style="display: grid; gap: 8px;"></div>
<div id="recipe-deploy-result" style="margin-top: 16px; display:none;"></div>
</div>
<div class="weather-modal-buttons" style="margin-top: 20px;">
<button id="recipe-cancel">Cancel</button>
<button id="recipe-prev" class="btn-accent" style="display:none;">Back</button>
<button id="recipe-next" class="btn-accent-solid">Next</button>
</div>
</div>
</div>`);let y=null,h=null,L=null,T=1,B=!1;const N=document.getElementById("recipe-deploy-modal"),D=document.getElementById("recipe-cancel"),A=document.getElementById("recipe-prev"),$=document.getElementById("recipe-next");wireModal(N,D);async function P(){try{const c=await fetch("/api/v1/recipes/templates"),d=await c.json();if(d.success)return y=d.templates,h=d.categories,!0;if(c.status===403)return B=!1,!1}catch(c){console.warn("Failed to fetch recipe templates:",c.message)}return!1}async function C(){try{B=(await(await fetch("/api/v1/license/feature/recipes")).json()).available}catch{B=!1}return B}window.renderRecipeCards=async function(c){await C();let d;if(B&&y?d=y:d=H(),!d||d.length===0)return;const a=document.createElement("div");a.className="app-category-header",a.innerHTML="\u{1F9EA} Recipes",a.style.borderBottomColor="#8e44ad",c.appendChild(a);const n=Array.isArray(d)?d:Object.values(d);n.sort((e,t)=>(t.popularity||0)-(e.popularity||0));for(const e of n){const t=document.createElement("div");t.className="app-option",t.style.position="relative";const i=`<div style="font-size: 0.65rem; padding: 2px 6px; border-radius: 4px; margin-top: 4px; background: rgba(142,68,173,0.2); color: #a855f7;">${e.componentCount||e.components?.length||"?"} apps</div>`,r=B?"":'<div style="position: absolute; top: 6px; right: 6px; font-size: 0.65rem; padding: 2px 8px; border-radius: 10px; background: rgba(241,196,15,0.2); color: #f1c40f; font-weight: 600;">PREMIUM</div>';t.innerHTML=`
${r}
<div class="app-option-icon">${escapeHtml(e.icon||"\u{1F9EA}")}</div>
<div class="app-option-name">${escapeHtml(e.name)}</div>
<div class="app-option-desc">${escapeHtml(e.description||"")}</div>
${i}
`,t.onclick=()=>{if(!B){showNotification("Recipes require a DashCaddy Premium license. Click the License button to activate.","warning",5e3),window.openLicenseModal&&window.openLicenseModal();return}x(e)},c.appendChild(t)}};function H(){return[{id:"htpc-suite",name:"HTPC Suite",icon:"\u{1F3AC}",description:"Complete media automation: find, download, organize, and stream",componentCount:6,popularity:98},{id:"nextcloud-complete",name:"Nextcloud Complete",icon:"\u2601\uFE0F",description:"Full productivity suite: cloud storage, office editing, and collaboration",componentCount:4,popularity:90},{id:"smart-home",name:"Smart Home Hub",icon:"\u{1F3E0}",description:"Home automation: control, automate, and monitor IoT devices",componentCount:4,popularity:88},{id:"dev-environment",name:"Dev Environment",icon:"\u{1F4BB}",description:"Self-hosted development workflow: Git, CI/CD, IDE, and database",componentCount:4,popularity:82}]}function x(c){L=c,T=1;const d=document.getElementById("app-selector-modal");d&&d.classList.remove("show"),document.getElementById("recipe-deploy-title").textContent=`Deploy ${c.name}`,O(),z(),N.classList.add("show")}function O(){document.querySelectorAll("#recipe-steps .recipe-step").forEach(c=>{const d=parseInt(c.dataset.step);c.classList.toggle("active",d===T),c.classList.toggle("completed",d<T)});for(let c=1;c<=4;c++){const d=document.getElementById(`recipe-step-${c}`);d&&(d.style.display=c===T?"":"none")}A.style.display=T>1&&T<4?"":"none",T===4?($.style.display="none",D.textContent="Close"):T===3?($.textContent="\u{1F680} Deploy",$.style.display="",D.textContent="Cancel"):($.textContent="Next",$.style.display="",D.textContent="Cancel")}function z(){const c=document.getElementById("recipe-component-list");c.innerHTML="";const d=L.components||[];for(const a of d){const n=document.createElement("div");n.style.cssText="display: flex; align-items: center; gap: 12px; padding: 12px; border-radius: 8px; background: var(--card-bg); border: 1px solid var(--border);";const e=a.required,t=a.internal;n.innerHTML=`
<input type="checkbox" ${e?"checked disabled":"checked"} data-component-id="${a.id}"
style="width: 18px; height: 18px; accent-color: var(--accent);" />
<div style="flex: 1;">
<div style="font-weight: 600; font-size: 0.9rem;">${escapeHtml(a.role||a.id)}</div>
<div style="font-size: 0.78rem; color: var(--muted);">
${a.templateRef?escapeHtml(a.templateRef):"Built-in"}
${e?'<span style="color: var(--accent); margin-left: 6px;">Required</span>':'<span style="color: var(--muted); margin-left: 6px;">Optional</span>'}
${t?'<span style="color: var(--muted); margin-left: 6px;">(Internal)</span>':""}
</div>
${a.note?`<div style="font-size: 0.75rem; color: var(--warn-fg); margin-top: 4px;">\u26A0 ${escapeHtml(a.note)}</div>`:""}
</div>
`,c.appendChild(n)}}function S(){const c=document.getElementById("recipe-volumes-section"),d=document.getElementById("recipe-volume-list"),a=L.sharedVolumes;if(a&&Object.keys(a).length>0){c.style.display="",d.innerHTML="";for(const[n,e]of Object.entries(a)){const t=document.createElement("div");t.style.cssText="display: grid; gap: 4px;",t.innerHTML=`
<label style="font-weight: 500; font-size: 0.85rem;">${escapeHtml(e.label||n)}</label>
<input type="text" data-volume-key="${n}" value="${escapeHtml(e.defaultPath||"")}"
placeholder="${escapeHtml(e.defaultPath||"/path")}"
style="width: 100%; padding: 8px 12px; background: var(--card-bg); color: var(--fg); border: 1px solid var(--border); border-radius: 6px; font-family: monospace; font-size: 0.85rem;" />
<div class="form-hint-sm">${escapeHtml(e.description||"")}</div>
`,d.appendChild(t)}}else c.style.display="none"}function E(){const c=document.getElementById("recipe-review-content"),d=k(),a=document.querySelectorAll("#recipe-volume-list input[data-volume-key]"),n={};a.forEach(r=>{n[r.dataset.volumeKey]=r.value});const e=document.getElementById("recipe-timezone").value||"UTC",t=document.getElementById("recipe-ip").value||"host.docker.internal",i=document.getElementById("recipe-tailscale").checked;c.innerHTML=`
<div style="font-weight: 600; font-size: 1rem; margin-bottom: 12px;">${escapeHtml(L.name)}</div>
<div style="color: var(--muted); margin-bottom: 16px;">${escapeHtml(L.description||"")}</div>
<div style="margin-bottom: 12px;">
<strong>Components (${d.length}):</strong>
<div style="display: grid; gap: 4px; margin-top: 6px;">
${d.map(r=>`<div style="padding: 4px 0; font-size: 0.85rem;">
\u2022 <strong>${escapeHtml(r.role||r.id)}</strong> ${r.internal?'<span style="color:var(--muted)">(internal)</span>':""}
</div>`).join("")}
</div>
</div>
${Object.keys(n).length>0?`<div style="margin-bottom: 12px;">
<strong>Volumes:</strong>
${Object.entries(n).map(([r,p])=>`<div style="font-size: 0.85rem; font-family: monospace; color: var(--muted);">${r}: ${escapeHtml(p)}</div>`).join("")}
</div>`:""}
<div style="font-size: 0.85rem; color: var(--muted);">
Timezone: ${escapeHtml(e)} &bull; IP: ${escapeHtml(t)} ${i?"&bull; Tailscale only":""}
</div>
${L.network?`<div style="font-size: 0.85rem; color: var(--muted); margin-top: 4px;">Docker network: <code>${escapeHtml(L.network.name)}</code></div>`:""}
`}function k(){const c=document.querySelectorAll("#recipe-component-list input[data-component-id]"),d=new Set;c.forEach(n=>{n.checked&&d.add(n.dataset.componentId)});const a=L.components||[];return a.filter(n=>n.required).forEach(n=>d.add(n.id)),a.filter(n=>d.has(n.id))}async function b(){const c=document.getElementById("recipe-progress-list"),d=document.getElementById("recipe-deploy-result");d.style.display="none",c.innerHTML="";const a=k();for(const i of a){const r=document.createElement("div");r.id=`recipe-progress-${i.id}`,r.style.cssText="display: flex; align-items: center; gap: 10px; padding: 10px 12px; border-radius: 6px; background: var(--card-bg); border: 1px solid var(--border); font-size: 0.85rem;",r.innerHTML=`
<span class="recipe-progress-icon" style="font-size: 1.1rem;">\u23F3</span>
<span style="flex:1; font-weight: 500;">${escapeHtml(i.role||i.id)}</span>
<span class="recipe-progress-status" style="color: var(--muted);">Queued</span>
`,c.appendChild(r)}const n=document.querySelectorAll("#recipe-volume-list input[data-volume-key]"),e={};n.forEach(i=>{e[i.dataset.volumeKey]=i.value});const t={selectedComponents:a.map(i=>i.id),sharedConfig:{ip:document.getElementById("recipe-ip").value||"host.docker.internal",timezone:document.getElementById("recipe-timezone").value||"UTC",tailscaleOnly:document.getElementById("recipe-tailscale").checked,volumes:e},componentOverrides:{}};for(const i of a)m(i.id,"deploying","Deploying...");try{const r=await(await secureFetch("/api/v1/recipes/deploy",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({recipeId:L.id,config:t})})).json();if(r.success){for(const p of r.deployed||[])m(p.id,"success",p.url?`Running \u2192 ${p.url}`:"Running");for(const p of r.errors||[])m(p.componentId,"error",p.error);d.style.display="",d.innerHTML=`
<div style="padding: 14px; border-radius: 8px; background: rgba(46,204,113,0.1); border: 1px solid rgba(46,204,113,0.3);">
<div style="font-weight: 600; color: var(--ok-fg); margin-bottom: 6px;">${escapeHtml(r.message||"Deployed!")}</div>
${r.setupInstructions?`<div style="font-size: 0.8rem; color: var(--muted); margin-top: 8px;">
<strong>Setup tips:</strong>
<ul style="margin: 4px 0 0 16px; padding: 0;">${r.setupInstructions.map(p=>`<li>${escapeHtml(p)}</li>`).join("")}</ul>
</div>`:""}
</div>
`,showNotification(`${L.name} recipe deployed successfully!`,"success",5e3),window.loadServices&&window.loadServices()}else d.style.display="",d.innerHTML=`<div style="padding: 14px; border-radius: 8px; background: rgba(231,76,60,0.1); border: 1px solid rgba(231,76,60,0.3); color: var(--bad-fg);">
<strong>Deployment failed:</strong> ${escapeHtml(r.error||"Unknown error")}
</div>`,showNotification(`Recipe deployment failed: ${r.error}`,"error",5e3)}catch(i){d.style.display="",d.innerHTML=`<div style="padding: 14px; border-radius: 8px; background: rgba(231,76,60,0.1); border: 1px solid rgba(231,76,60,0.3); color: var(--bad-fg);">
<strong>Network error:</strong> ${escapeHtml(i.message)}
</div>`}}function m(c,d,a){const n=document.getElementById(`recipe-progress-${c}`);if(!n)return;const e=n.querySelector(".recipe-progress-icon"),t=n.querySelector(".recipe-progress-status");d==="deploying"?(e.textContent="\u23F3",t.style.color="var(--accent)"):d==="success"?(e.textContent="\u2705",t.style.color="var(--ok-fg)"):d==="error"&&(e.textContent="\u274C",t.style.color="var(--bad-fg)"),t.textContent=a}$.addEventListener("click",()=>{if(T===3){T=4,O(),b();return}T<3&&(T++,O(),T===2&&S(),T===3&&E())}),A.addEventListener("click",()=>{T>1&&T<4&&(T--,O())}),window.groupRecipeCards=function(){const c=document.querySelectorAll(".service-card[data-recipe-id]");if(c.length===0)return;const d={};c.forEach(a=>{const n=a.dataset.recipeId;d[n]||(d[n]=[]),d[n].push(a)});for(const[a,n]of Object.entries(d))n.length<2||n.forEach((e,t)=>{if(e.style.borderLeft="3px solid rgba(142,68,173,0.5)",t===0){let i=e.querySelector(".recipe-group-label");i||(i=document.createElement("div"),i.className="recipe-group-label",i.style.cssText="position: absolute; top: -8px; left: 12px; font-size: 0.6rem; padding: 1px 8px; border-radius: 8px; background: rgba(142,68,173,0.3); color: #d4a5ff; font-weight: 600; text-transform: uppercase; letter-spacing: 0.5px;",i.textContent=a.replace(/-/g," "),e.style.position="relative",e.appendChild(i))}})},window.manageRecipe=async function(c,d){const a=`/api/v1/recipes/${c}/${d}`,n=d==="remove"?"DELETE":"POST",e=d==="remove"?`/api/v1/recipes/${c}`:a;if(!(d==="remove"&&!confirm(`Remove the entire ${c} recipe? This will delete all containers and configuration.`)))try{const i=await(await secureFetch(e,{method:n})).json();i.success?(showNotification(`Recipe ${d}: ${i.results?.filter(r=>r.status!=="failed").length||0} components processed`,"success",4e3),window.loadServices&&window.loadServices()):showNotification(`Recipe ${d} failed: ${i.error}`,"error",5e3)}catch(t){showNotification(`Network error: ${t.message}`,"error",5e3)}};const f=document.createElement("style");f.textContent=`
.recipe-step {
flex: 1;
text-align: center;
padding: 8px 4px;
font-size: 0.78rem;
color: var(--muted);
border-bottom: 2px solid var(--border);
transition: all 0.2s;
}
.recipe-step span {
display: inline-flex;
align-items: center;
justify-content: center;
width: 20px;
height: 20px;
border-radius: 50%;
background: var(--border);
color: var(--muted);
font-size: 0.7rem;
font-weight: 700;
margin-right: 4px;
}
.recipe-step.active {
color: var(--accent);
border-bottom-color: var(--accent);
}
.recipe-step.active span {
background: var(--accent);
color: #fff;
}
.recipe-step.completed {
color: var(--ok-fg);
border-bottom-color: var(--ok-fg);
}
.recipe-step.completed span {
background: var(--ok-fg);
color: #fff;
}
.recipe-step-panel {
min-height: 180px;
}
`,document.head.appendChild(f),C()})(),(function(){document.getElementById("reload-caddy-top")?.addEventListener("click",async()=>{const y=document.getElementById("reload-caddy-top"),h=y.textContent;try{y.textContent="\u23F3 Reloading...",y.disabled=!0;const L=await secureFetch("/api/v1/caddy/reload",{method:"POST",headers:{"Content-Type":"application/json"}}),T=await L.json();if(L.ok&&T.success)y.textContent="\u2705 Reloaded!",setTimeout(()=>{y.textContent=h,y.disabled=!1},2e3);else throw new Error(T.error||"Reload failed")}catch(L){y.textContent="\u274C Failed",showNotification(`Failed to reload Caddy: ${L.message}`,"error"),setTimeout(()=>{y.textContent=h,y.disabled=!1},2e3)}})})(),(function(){injectModal("error-log-modal",'<div id="error-log-modal" class="logs-modal"><div class="logs-modal-content"><div class="logs-header"><h3>\u{1F4CB} Error Logs</h3><div class="logs-controls"><button id="error-log-refresh" style="padding:4px 12px!important;font-size:.85rem!important">\u{1F504} Refresh</button><button id="error-log-clear" style="padding:4px 12px!important;font-size:.85rem!important;background:color-mix(in srgb,var(--bad-fg) 15%,transparent)!important;border-color:var(--bad-fg)!important;color:var(--bad-fg)!important">\u{1F5D1}\uFE0F Clear</button><button id="error-log-close" class="close-btn">\u2715</button></div></div><div class="logs-container"><div id="error-log-content" class="logs-content"><div class="logs-loading">Loading error logs...</div></div></div></div></div>');const y=document.getElementById("error-log-modal"),h=document.getElementById("error-log-content"),L=document.getElementById("view-error-logs"),T=document.getElementById("error-log-refresh"),B=document.getElementById("error-log-clear"),N=document.getElementById("error-log-close");async function D(){h.innerHTML='<div class="logs-loading">Loading error logs...</div>';try{const P=await(await fetch("/api/v1/error-logs")).json();P.success&&P.logs?P.logs.length===0?h.innerHTML='<div style="padding: 20px; text-align: center; color: var(--muted);">\u2705 No errors logged! Everything is working smoothly.</div>':h.innerHTML=P.logs.map(C=>`
<div class="log-entry error">
<span class="log-timestamp">${new Date(C.timestamp).toLocaleString()}</span>
<span class="log-level">ERROR</span>
<div class="log-message">
<strong>${escapeHtml(C.context)}</strong>: ${escapeHtml(C.error)}
${C.details?`<br><small style="opacity: 0.7;">${escapeHtml(C.details)}</small>`:""}
</div>
</div>
`).join(""):h.innerHTML='<div style="padding: 20px; color: var(--bad-fg);">\u274C Failed to load error logs</div>'}catch($){h.innerHTML=`<div style="padding: 20px; color: var(--bad-fg);">\u274C Error loading logs: ${escapeHtml($.message)}</div>`}}async function A(){if(confirm("Clear all error logs?"))try{(await(await secureFetch("/api/v1/error-logs",{method:"DELETE"})).json()).success?(showNotification("\u2705 Error logs cleared","success",3e3),D()):showNotification("\u274C Failed to clear logs","error",3e3)}catch($){showNotification(`\u274C Error: ${$.message}`,"error",3e3)}}L?.addEventListener("click",()=>{y.classList.add("show"),D()}),T?.addEventListener("click",D),B?.addEventListener("click",A),wireModal(y,N)})(),(function(){injectModal("arr-setup-modal",`<div id="arr-setup-modal" class="weather-modal">
<div class="weather-modal-content" style="min-width: 600px; max-width: 720px;">
<h3>\u{1F3AC} Smart Arr Connect</h3>
<p style="color: var(--muted); margin: 0 0 16px; font-size: 0.9rem;">
Auto-discover and connect your entire media stack.
</p>
<!-- Phase 1: Detection -->
<div id="smart-phase-detect">
<div style="text-align: center; padding: 20px;">
<span class="brand-spinner" style="margin-bottom: 12px; display: inline-block;"></span>
<div style="color: var(--muted); font-size: 0.9rem;">Scanning for services...</div>
</div>
<div id="smart-detect-results" style="display: none;"></div>
</div>
<!-- Phase 2: Credential Input (only for services needing keys) -->
<div id="smart-phase-credentials" style="display: none;">
<h4 class="heading-accent-section">Enter Missing API Keys</h4>
<div id="smart-credential-inputs"></div>
<!-- Connection Options -->
<div style="margin-top: 16px; padding: 12px; background: var(--card-base); border-radius: 8px; border: 1px solid var(--border);">
<h4 style="margin: 0 0 10px; font-size: 0.85rem; color: var(--accent);">Connection Options</h4>
<label class="option-label">
<input type="checkbox" id="smart-opt-seerr" checked class="checkbox-sm" />
Configure Seerr with Radarr + Sonarr
</label>
<label class="option-label">
<input type="checkbox" id="smart-opt-plex" checked class="checkbox-sm" />
Connect Plex to Seerr
</label>
<label class="option-label">
<input type="checkbox" id="smart-opt-prowlarr" checked class="checkbox-sm" />
Connect Prowlarr to Radarr + Sonarr
</label>
<label style="display: flex; align-items: center; gap: 8px; cursor: pointer; font-size: 0.85rem;">
<input type="checkbox" id="smart-opt-save" checked class="checkbox-sm" />
Save API keys for one-click reconnect
</label>
</div>
<button id="smart-connect-btn" style="width: 100%; margin-top: 16px; padding: 12px; background: linear-gradient(135deg, #e74c3c 0%, #9b59b6 100%); border: none; color: white; font-weight: 600; font-size: 1rem; border-radius: 8px; cursor: pointer;">
Smart Connect
</button>
</div>
<!-- Phase 3: Connection Progress -->
<div id="smart-phase-progress" style="display: none;">
<h4 class="heading-accent-section">Connecting Everything...</h4>
<div id="smart-progress-steps" style="display: flex; flex-direction: column; gap: 6px;"></div>
</div>
<!-- Phase 4: Results -->
<div id="smart-phase-results" style="display: none;">
<div id="smart-results-content"></div>
<div id="smart-plex-libraries" style="display: none; margin-top: 12px;"></div>
<div style="display: flex; gap: 8px; margin-top: 16px;">
<button id="smart-retry-btn" style="display: none; flex: 1; padding: 10px; background: #f39c12; border: none; color: white; font-weight: 500; border-radius: 8px; cursor: pointer;">
Retry Failed Steps
</button>
<a id="smart-open-seerr" href="#" target="_blank" rel="noopener noreferrer"
style="flex: 1; padding: 10px; background: var(--accent); color: white; border: none; border-radius: 8px; cursor: pointer; font-weight: 500; text-decoration: none; text-align: center;">
Open Seerr
</a>
</div>
</div>
<!-- Help Text -->
<div style="font-size: 0.75rem; color: var(--muted); margin-top: 12px; padding: 10px; background: color-mix(in srgb, var(--accent) 5%, transparent); border-radius: 6px;">
<strong>Where to find API keys:</strong><br>
Radarr/Sonarr/Prowlarr: Settings -> General -> Security -> API Key
</div>
<!-- Close Button -->
<div class="weather-modal-buttons modal-footer-bar">
<button id="arr-setup-cancel">Close</button>
</div>
</div>
</div>`);const y=document.getElementById("arr-setup-modal"),h=document.getElementById("arr-setup-btn"),L=document.getElementById("arr-setup-cancel"),T=document.getElementById("smart-connect-btn"),B=document.getElementById("smart-phase-detect"),N=document.getElementById("smart-phase-credentials"),D=document.getElementById("smart-phase-progress"),A=document.getElementById("smart-phase-results"),$=document.getElementById("smart-detect-results"),P=document.getElementById("smart-credential-inputs"),C=document.getElementById("smart-progress-steps"),H=document.getElementById("smart-results-content"),x=document.getElementById("smart-plex-libraries"),O=document.getElementById("smart-retry-btn");let z=null;const S={plex:"\u{1F3AC}",radarr:"\u{1F3AC}",sonarr:"\u{1F4FA}",prowlarr:"\u{1F50D}",seerr:"\u{1F4CB}"},E={plex:"Plex",radarr:"Radarr (Movies)",sonarr:"Sonarr (TV)",prowlarr:"Prowlarr (Indexers)",seerr:"Seerr"};function k(n){B.style.display=n==="detect"?"block":"none",N.style.display=n==="credentials"?"block":"none",D.style.display=n==="progress"?"block":"none",A.style.display=n==="results"?"block":"none"}function b(n){const e={connected:{bg:"var(--ok-fg)",icon:"&#10003;",text:"Connected"},needs_key:{bg:"#f39c12",icon:"&#128273;",text:"Needs API Key"},not_found:{bg:"var(--muted)",icon:"&mdash;",text:"Not Found"},error:{bg:"var(--bad-fg)",icon:"&#10007;",text:"Error"}},t=e[n]||e.not_found;return`<span style="display: inline-flex; align-items: center; gap: 4px; padding: 2px 8px; border-radius: 4px; font-size: 0.75rem; background: color-mix(in srgb, ${t.bg} 20%, transparent); color: ${t.bg};">${t.icon} ${t.text}</span>`}async function m(){k("detect"),$.style.display="none";try{if(z=await(await fetch("/api/v1/arr/smart-detect")).json(),!z.success){$.innerHTML=`<div style="padding: 12px; color: var(--bad-fg);">Detection failed: ${escapeHtml(z.error)}</div>`,$.style.display="block";return}let e='<div style="display: flex; flex-direction: column; gap: 8px;">';for(const[i,r]of Object.entries(z.services)){const p=S[i]||"\u{1F4E6}",v=E[i]||i,o=r.source?`<span style="font-size: 0.7rem; color: var(--muted); padding: 1px 6px; background: var(--card-bg); border-radius: 3px;">${escapeHtml(r.source)}</span>`:"",s=r.version?`<span style="font-size: 0.7rem; color: var(--muted);">v${escapeHtml(r.version)}</span>`:"",u=(r.hasApiKey||r.hasToken)&&r.status==="connected"?'<span style="font-size: 0.7rem; color: var(--ok-fg);">Key saved</span>':"";e+=`<div style="display: flex; align-items: center; gap: 10px; padding: 10px 12px; background: var(--card-base); border-radius: 8px; border: 1px solid var(--border);">
<span style="font-size: 1.1rem;">${p}</span>
<div style="flex: 1;">
<div style="font-weight: 500; font-size: 0.9rem;">${v}</div>
<div style="display: flex; gap: 6px; align-items: center; flex-wrap: wrap;">
${o} ${s} ${u}
</div>
</div>
${b(r.status)}
</div>`}e+="</div>";const t=z.summary;e+=`<div style="margin-top: 12px; padding: 10px; background: color-mix(in srgb, var(--accent) 8%, transparent); border-radius: 8px; font-size: 0.85rem;">
${escapeHtml(String(t.fullyConnected))}/${escapeHtml(String(t.totalDetected+(5-t.totalDetected)))} services detected &middot;
${escapeHtml(String(t.fullyConnected))} connected${t.needsApiKey>0?` &middot; <strong>${escapeHtml(String(t.needsApiKey))} needs API key</strong>`:""}
</div>`,$.innerHTML=e,$.style.display="block",f(z),setTimeout(()=>{k("credentials")},800)}catch(n){$.innerHTML=`<div style="padding: 12px; color: var(--bad-fg);">Error: ${escapeHtml(n.message)}</div>`,$.style.display="block"}}function f(n){let e="";const t=n.services,i=["radarr","sonarr","prowlarr"];for(const v of i){const o=t[v];if(!o||o.status==="not_found"&&!o.url)continue;const s=S[v],u=E[v],l=o.status==="connected";e+=`<div style="margin-bottom: 10px; padding: 12px; background: var(--card-base); border-radius: 8px; border: 1px solid ${l?"var(--ok-fg)":"var(--border)"};">
<div style="display: flex; align-items: center; gap: 8px; margin-bottom: 8px;">
<span style="font-size: 1.1rem;">${s}</span>
<span style="font-weight: 500;">${u}</span>
<span id="smart-${v}-status" style="margin-left: auto; font-size: 0.75rem;">
${l?'<span style="color: var(--ok-fg);">&#10003; Connected</span>':""}
</span>
</div>
<div style="display: grid; grid-template-columns: 2fr 1fr; gap: 8px;">
<div>
<label style="font-size: 0.75rem; color: var(--muted);">URL:</label>
<input type="text" id="smart-${v}-url" value="${escapeHtml(o.url||"")}" placeholder="https://seedbox.com/${v}/"
style="width: 100%; font-size: 0.85rem; padding: 6px 8px; background: var(--card-bg); color: var(--fg); border: 1px solid var(--border); border-radius: 4px;" />
</div>
<div>
<label style="font-size: 0.75rem; color: var(--muted);">API Key:</label>
<input type="password" id="smart-${v}-key" placeholder="${l?"(saved)":"Paste API key"}"
style="width: 100%; font-size: 0.85rem; padding: 6px 8px; background: var(--card-bg); color: var(--fg); border: 1px solid var(--border); border-radius: 4px;" />
</div>
</div>
<button onclick="smartTestConnection('${v}')" style="margin-top: 8px; padding: 4px 12px; font-size: 0.75rem; cursor: pointer;">Test</button>
</div>`}const r=t.plex;if(r){const v=r.status==="connected";e+=`<div style="padding: 10px 12px; background: var(--card-base); border-radius: 8px; border: 1px solid ${v?"var(--ok-fg)":"var(--border)"}; margin-bottom: 10px;">
<div style="display: flex; align-items: center; gap: 8px;">
<span style="font-size: 1.1rem;">\u{1F3AC}</span>
<span style="font-weight: 500;">Plex</span>
${b(r.status)}
<span style="margin-left: auto; font-size: 0.75rem; color: var(--muted);">${escapeHtml(r.source||"")}</span>
</div>
</div>`}const p=t.seerr;if(p){const v=p.status==="connected";let o="";if(p.configuredServices){const s=p.configuredServices;o=`<div style="font-size: 0.75rem; color: var(--muted); margin-top: 4px;">
Configured: ${s.radarr?"&#10003; Radarr":"&#10007; Radarr"} &middot;
${s.sonarr?"&#10003; Sonarr":"&#10007; Sonarr"} &middot;
${s.plex?"&#10003; Plex":"&#10007; Plex"}
</div>`}e+=`<div style="padding: 10px 12px; background: var(--card-base); border-radius: 8px; border: 1px solid ${v?"var(--ok-fg)":"var(--border)"};">
<div style="display: flex; align-items: center; gap: 8px;">
<span style="font-size: 1.1rem;">\u{1F4CB}</span>
<span style="font-weight: 500;">Seerr</span>
${b(p.status)}
</div>
${o}
</div>`}P.innerHTML=e}window.smartTestConnection=async function(n){const e=document.getElementById(`smart-${n}-url`),t=document.getElementById(`smart-${n}-key`),i=document.getElementById(`smart-${n}-status`),r=e?.value.trim(),p=t?.value.trim();if(!r||!p){i.innerHTML='<span style="color: var(--bad-fg);">Enter URL and API key</span>';return}i.innerHTML='<span class="brand-spinner"></span>';try{const o=await(await secureFetch("/api/v1/arr/test-connection",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({service:n,url:r,apiKey:p})})).json();o.success?i.innerHTML=`<span style="color: var(--ok-fg);">&#10003; ${escapeHtml(o.appName||"Connected")} v${escapeHtml(o.version||"")}</span>`:i.innerHTML=`<span style="color: var(--bad-fg);">&#10007; ${escapeHtml(o.error)}</span>`}catch(v){i.innerHTML=`<span style="color: var(--bad-fg);">&#10007; ${escapeHtml(v.message)}</span>`}};async function c(){k("progress"),C.innerHTML='<div style="text-align: center; padding: 20px;"><span class="brand-spinner"></span><div style="color: var(--muted); margin-top: 8px;">Connecting services...</div></div>';const n={};for(const t of["radarr","sonarr","prowlarr"]){const i=document.getElementById(`smart-${t}-url`)?.value.trim(),r=document.getElementById(`smart-${t}-key`)?.value.trim();r&&i?n[t]={apiKey:r,url:i}:r&&(n[t]={apiKey:r})}const e={services:Object.keys(n).length>0?n:void 0,configurePlex:document.getElementById("smart-opt-plex")?.checked,configureProwlarr:document.getElementById("smart-opt-prowlarr")?.checked,configureSeerr:document.getElementById("smart-opt-seerr")?.checked,saveCredentials:document.getElementById("smart-opt-save")?.checked};try{const i=await(await secureFetch("/api/v1/arr/smart-connect",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})).json();let r="";for(const p of i.steps||[]){const v=p.status==="success"?'<span style="color: var(--ok-fg);">&#10003;</span>':'<span style="color: var(--bad-fg);">&#10007;</span>',o=p.status==="success"?"var(--muted)":"var(--bad-fg)";r+=`<div style="display: flex; align-items: center; gap: 8px; padding: 6px 10px; background: var(--card-base); border-radius: 6px; font-size: 0.85rem;">
${v}
<span>${escapeHtml(p.step)}</span>
<span style="margin-left: auto; font-size: 0.75rem; color: ${o};">${escapeHtml(p.details||"")}</span>
</div>`}C.innerHTML=r,setTimeout(()=>d(i),500)}catch(t){C.innerHTML=`<div style="padding: 12px; color: var(--bad-fg);">Connection error: ${escapeHtml(t.message)}</div>`}}function d(n){k("results");const e=n.summary||{},t=e.failed===0&&e.succeeded>0,i=t?"var(--ok-fg)":"#f39c12",r=t?"&#10003;":"&#9888;",p=t?"All Connected!":`${escapeHtml(String(e.succeeded))}/${escapeHtml(String(e.totalSteps))} Steps Succeeded`;let v=`<div style="text-align: center; padding: 16px; background: color-mix(in srgb, ${i} 12%, transparent); border-radius: 10px; border: 1px solid ${i}; margin-bottom: 12px;">
<div style="font-size: 1.5rem; color: ${i};">${r}</div>
<div style="font-size: 1.1rem; font-weight: 600; color: ${i};">${p}</div>
<div style="font-size: 0.85rem; color: var(--muted); margin-top: 4px;">${escapeHtml(String(e.succeeded))} succeeded, ${escapeHtml(String(e.failed))} failed</div>
</div>`;v+='<div style="display: flex; flex-direction: column; gap: 4px;">';for(const o of n.steps||[]){const s=o.status==="success"?'<span style="color: var(--ok-fg);">&#10003;</span>':'<span style="color: var(--bad-fg);">&#10007;</span>';v+=`<div style="display: flex; align-items: center; gap: 8px; padding: 4px 8px; font-size: 0.8rem;">
${s} ${escapeHtml(o.step)} <span style="margin-left: auto; color: var(--muted); font-size: 0.75rem;">${escapeHtml(o.details||"")}</span>
</div>`}v+="</div>",H.innerHTML=v,O.style.display=e.failed>0?"block":"none",n.steps?.some(o=>o.step.includes("Plex")&&o.status==="success")&&a()}async function a(){try{const e=await(await fetch("/api/v1/plex/libraries")).json();if(e.success&&e.libraries?.length>0){let t=`<div style="padding: 12px; background: var(--card-base); border-radius: 8px; border: 1px solid var(--border);">
<h4 style="margin: 0 0 8px; font-size: 0.85rem; color: var(--accent);">\u{1F3AC} ${escapeHtml(e.serverName)} Libraries</h4>
<div style="display: flex; flex-wrap: wrap; gap: 8px;">`;for(const i of e.libraries){const r=i.type==="movie"?"\u{1F3AC}":i.type==="show"?"\u{1F4FA}":"\u{1F3B5}";t+=`<div style="padding: 8px 12px; background: var(--card-bg); border-radius: 6px; font-size: 0.85rem;">
${r} <strong>${escapeHtml(i.title)}</strong>
<span style="color: var(--muted); font-size: 0.75rem;">${escapeHtml(String(i.count))} items</span>
</div>`}t+="</div></div>",x.innerHTML=t,x.style.display="block"}}catch{}}h?.addEventListener("click",()=>{y.classList.add("show"),x.style.display="none",m()}),wireModal(y,L),T?.addEventListener("click",c),O?.addEventListener("click",c)})(),(function(){injectModal("notifications-modal",`<div id="notifications-modal" class="weather-modal">
<div class="weather-modal-content" style="min-width: 550px; max-width: 650px;">
<h3>\u{1F514} Notification Settings</h3>
<!-- Master Toggle -->
<div class="accent-info-box">
<label style="display: flex; align-items: center; gap: 10px; cursor: pointer;">
<input type="checkbox" id="notifications-enabled" />
<div>
<span style="font-weight: 600; color: var(--accent);">Enable Notifications</span>
<div class="text-tiny-muted">Receive alerts when containers go up/down</div>
</div>
</label>
</div>
<!-- Providers Section -->
<h4 class="section-heading">Notification Providers</h4>
<!-- Discord -->
<div class="notification-provider provider-card">
<div class="provider-header">
<label class="checkbox-label">
<input type="checkbox" id="discord-enabled" />
<span class="fw-500">Discord</span>
</label>
<button id="discord-test" class="test-btn btn-xs">Test</button>
</div>
<div id="discord-config" style="display: none;">
<label class="field-label-sm">Webhook URL:</label>
<input type="text" id="discord-webhook" placeholder="https://discord.com/api/v1/webhooks/..." style="width: 100%;" />
</div>
</div>
<!-- Telegram -->
<div class="notification-provider provider-card">
<div class="provider-header">
<label class="checkbox-label">
<input type="checkbox" id="telegram-enabled" />
<span class="fw-500">Telegram</span>
</label>
<button id="telegram-test" class="test-btn btn-xs">Test</button>
</div>
<div id="telegram-config" style="display: none;">
<div class="grid-2col">
<div>
<label class="field-label-sm">Bot Token:</label>
<input type="text" id="telegram-bot-token" placeholder="123456:ABC..." />
</div>
<div>
<label class="field-label-sm">Chat ID:</label>
<input type="text" id="telegram-chat-id" placeholder="-1001234567890" />
</div>
</div>
</div>
</div>
<!-- ntfy.sh -->
<div class="notification-provider provider-card">
<div class="provider-header">
<label class="checkbox-label">
<input type="checkbox" id="ntfy-enabled" />
<span class="fw-500">ntfy.sh</span>
</label>
<button id="ntfy-test" class="test-btn btn-xs">Test</button>
</div>
<div id="ntfy-config" style="display: none;">
<div style="display: grid; grid-template-columns: 2fr 1fr; gap: 8px;">
<div>
<label class="field-label-sm">Server URL:</label>
<input type="text" id="ntfy-server" placeholder="https://ntfy.sh" value="https://ntfy.sh" />
</div>
<div>
<label class="field-label-sm">Topic:</label>
<input type="text" id="ntfy-topic" placeholder="dashcaddy-alerts" />
</div>
</div>
</div>
</div>
<!-- Health Check Settings -->
<h4 class="section-heading">Health Monitoring</h4>
<div style="padding: 12px; background: var(--card-base); border-radius: 8px; border: 1px solid var(--border);">
<label style="display: flex; align-items: center; gap: 10px; cursor: pointer; margin-bottom: 10px;">
<input type="checkbox" id="health-check-enabled" />
<div>
<span class="fw-500">Enable Health Monitoring</span>
<div class="text-tiny-muted">Periodically check container status</div>
</div>
</label>
<div id="health-check-config" style="display: flex; align-items: center; gap: 10px;">
<label class="field-label-sm">Check interval:</label>
<select id="health-check-interval" style="width: auto;">
<option value="1">1 minute</option>
<option value="5" selected>5 minutes</option>
<option value="15">15 minutes</option>
<option value="30">30 minutes</option>
<option value="60">1 hour</option>
</select>
<button id="health-check-now" style="padding: 4px 10px; font-size: 0.75rem; margin-left: auto;">Check Now</button>
</div>
<div id="health-check-status" style="font-size: 0.75rem; color: var(--muted); margin-top: 8px;">
Last check: Never
</div>
</div>
<!-- Event Types -->
<h4 class="section-heading">Events to Notify</h4>
<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 6px; padding: 12px; background: var(--card-base); border-radius: 8px; border: 1px solid var(--border);">
<label class="checkbox-label-sm">
<input type="checkbox" id="event-container-down" checked /> Container Down
</label>
<label class="checkbox-label-sm">
<input type="checkbox" id="event-container-up" checked /> Container Recovered
</label>
<label class="checkbox-label-sm">
<input type="checkbox" id="event-deploy-success" checked /> Deployment Success
</label>
<label class="checkbox-label-sm">
<input type="checkbox" id="event-deploy-failed" checked /> Deployment Failed
</label>
</div>
<!-- History -->
<h4 class="section-heading">Notification History</h4>
<div id="notification-history" style="max-height: 150px; overflow-y: auto; padding: 8px; background: var(--card-base); border-radius: 8px; border: 1px solid var(--border); font-size: 0.8rem;">
<div style="color: var(--muted); text-align: center; padding: 20px;">No notifications yet</div>
</div>
<!-- Buttons -->
<div class="weather-modal-buttons modal-footer-bar">
<button id="notifications-cancel">Cancel</button>
<button id="notifications-save" class="btn-accent">Save Settings</button>
</div>
</div>
</div>`);const y=document.getElementById("notifications-modal"),h=document.getElementById("manage-notifications"),L=document.getElementById("notifications-save"),T=document.getElementById("notifications-cancel");["discord","telegram","ntfy"].forEach(C=>{const H=document.getElementById(`${C}-enabled`),x=document.getElementById(`${C}-config`);H?.addEventListener("change",()=>{x.style.display=H.checked?"block":"none"})});const B=document.getElementById("health-check-enabled"),N=document.getElementById("health-check-config");B?.addEventListener("change",()=>{N.style.opacity=B.checked?"1":"0.5"});async function D(){try{const H=await(await fetch("/api/v1/notifications/config")).json();if(H.success){const x=H.config;document.getElementById("notifications-enabled").checked=x.enabled,document.getElementById("discord-enabled").checked=x.providers?.discord?.enabled||!1,document.getElementById("telegram-enabled").checked=x.providers?.telegram?.enabled||!1,document.getElementById("ntfy-enabled").checked=x.providers?.ntfy?.enabled||!1,document.getElementById("discord-config").style.display=x.providers?.discord?.enabled?"block":"none",document.getElementById("telegram-config").style.display=x.providers?.telegram?.enabled?"block":"none",document.getElementById("ntfy-config").style.display=x.providers?.ntfy?.enabled?"block":"none",x.providers?.ntfy?.serverUrl&&(document.getElementById("ntfy-server").value=x.providers.ntfy.serverUrl),document.getElementById("health-check-enabled").checked=x.healthCheck?.enabled||!1,x.healthCheck?.intervalMinutes&&(document.getElementById("health-check-interval").value=x.healthCheck.intervalMinutes),x.healthCheck?.lastCheck&&(document.getElementById("health-check-status").textContent=`Last check: ${new Date(x.healthCheck.lastCheck).toLocaleString()}`),document.getElementById("event-container-down").checked=x.events?.containerDown!==!1,document.getElementById("event-container-up").checked=x.events?.containerUp!==!1,document.getElementById("event-deploy-success").checked=x.events?.deploymentSuccess!==!1,document.getElementById("event-deploy-failed").checked=x.events?.deploymentFailed!==!1}}catch(C){console.error("Failed to load notification config:",C)}}async function A(){try{const H=await(await fetch("/api/v1/notifications/history?limit=10")).json(),x=document.getElementById("notification-history");H.success&&H.history?.length>0?x.innerHTML=H.history.map(O=>{const z=new Date(O.timestamp).toLocaleString();return`
<div style="padding: 6px 8px; border-bottom: 1px solid var(--border); display: flex; gap: 8px; align-items: flex-start;">
<span style="color: ${{success:"var(--ok-fg)",error:"var(--bad-fg)",warning:"#f39c12",info:"var(--accent)"}[O.type]||"var(--muted)"}">${O.type==="success"?"\u2713":O.type==="error"?"\u2717":"\u2139"}</span>
<div style="flex: 1; min-width: 0;">
<div style="font-weight: 500; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">${escapeHtml(O.title)}</div>
<div style="font-size: 0.7rem; color: var(--muted);">${z}</div>
</div>
</div>
`}).join(""):x.innerHTML='<div style="color: var(--muted); text-align: center; padding: 20px;">No notifications yet</div>'}catch(C){console.error("Failed to load notification history:",C)}}async function $(){try{const C={enabled:document.getElementById("notifications-enabled").checked,providers:{discord:{enabled:document.getElementById("discord-enabled").checked,webhookUrl:document.getElementById("discord-webhook").value.trim()},telegram:{enabled:document.getElementById("telegram-enabled").checked,botToken:document.getElementById("telegram-bot-token").value.trim(),chatId:document.getElementById("telegram-chat-id").value.trim()},ntfy:{enabled:document.getElementById("ntfy-enabled").checked,serverUrl:document.getElementById("ntfy-server").value.trim()||"https://ntfy.sh",topic:document.getElementById("ntfy-topic").value.trim()}},events:{containerDown:document.getElementById("event-container-down").checked,containerUp:document.getElementById("event-container-up").checked,deploymentSuccess:document.getElementById("event-deploy-success").checked,deploymentFailed:document.getElementById("event-deploy-failed").checked},healthCheck:{enabled:document.getElementById("health-check-enabled").checked,intervalMinutes:parseInt(document.getElementById("health-check-interval").value)||5}},x=await(await secureFetch("/api/v1/notifications/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(C)})).json();x.success?(showNotification("Notification settings saved","success",3e3),y.classList.remove("show")):showNotification(`Failed to save: ${x.error}`,"error",3e3)}catch(C){showNotification(`Error: ${C.message}`,"error",3e3)}}async function P(C){try{const x=await(await secureFetch("/api/v1/notifications/test",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:C})})).json();x.success?showNotification(`Test ${C} notification sent!`,"success",3e3):showNotification(`Test failed: ${x.error}`,"error",3e3)}catch(H){showNotification(`Error: ${H.message}`,"error",3e3)}}document.getElementById("discord-test")?.addEventListener("click",()=>P("discord")),document.getElementById("telegram-test")?.addEventListener("click",()=>P("telegram")),document.getElementById("ntfy-test")?.addEventListener("click",()=>P("ntfy")),document.getElementById("health-check-now")?.addEventListener("click",async()=>{try{const H=await(await secureFetch("/api/v1/notifications/health-check",{method:"POST"})).json();H.success&&(document.getElementById("health-check-status").textContent=`Last check: ${new Date(H.lastCheck).toLocaleString()} (${H.containersMonitored} containers)`,showNotification("Health check completed","success",2e3))}catch(C){showNotification(`Error: ${C.message}`,"error",3e3)}}),h?.addEventListener("click",()=>{y.classList.add("show"),D(),A()}),L?.addEventListener("click",$),wireModal(y,T)})(),(function(){document.addEventListener("click",y=>{const h=y.target.closest(".panel-tab");if(!h)return;const L=h.dataset.panel;if(!L)return;const T=h.closest(".panel-tabs"),B=T.closest(".weather-modal-content");T.querySelectorAll(".panel-tab").forEach(D=>D.classList.remove("active")),h.classList.add("active"),B.querySelectorAll(".panel-section").forEach(D=>D.classList.remove("active"));const N=B.querySelector("#"+L);N&&N.classList.add("active")})})(),(function(){var y=["dashcaddy_site_config","dashcaddy_onboarding","dashcaddy-encryption-key","dashcaddy-setup","dashcaddy-config","theme","user-themes","custom-theme","custom-apps","custom-services","toolbar-sections","weather-location","weather-zip","weather-geo","weather-unit","clock-style","clock-chimes","clock-chime-volume"];function h(){for(var a={},n=0;n<y.length;n++){var e=y[n],t=safeGet(e);t!=null&&(a[e]=t)}try{for(var i=0;i<localStorage.length;i++){var r=localStorage.key(i);/^widget-.+-enabled$/.test(r)&&(a[r]=localStorage.getItem(r))}}catch{}return a}function L(a){if(!a||typeof a!="object")return 0;var n=0;for(var e in a)a.hasOwnProperty(e)&&(safeSet(e,a[e]),n++);return n}function T(a){return a.version&&!a.files&&a.services}function B(a){var n={};a.customServices&&(n["custom-services"]=JSON.stringify(a.customServices)),a.customApps&&(n["custom-apps"]=JSON.stringify(a.customApps)),a.weatherZip&&(n["weather-zip"]=a.weatherZip),a.theme&&(n.theme=a.theme),a.userThemes&&Object.keys(a.userThemes).length&&(n["user-themes"]=JSON.stringify(a.userThemes)),L(n),a.services&&Array.isArray(a.services)&&secureFetch("/api/v1/services",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(a.services)}).catch(function(){}),a.userThemes&&Object.keys(a.userThemes).forEach(function(e){var t=a.userThemes[e],i={};(window.THEME_PROPS||[]).forEach(function(r){t[r]&&(i[r]=t[r])}),secureFetch("/api/v1/themes/"+e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:t.name||e,colors:i})}).catch(function(){})})}injectModal("backup-modal",`<div id="backup-modal" class="weather-modal">
<div class="weather-modal-content" style="min-width: 550px; max-width: 650px;">
<h3>\u{1F4BE} Backup & Restore</h3>
<p class="modal-subtitle">
Full backup of your entire DashCaddy setup \u2014 server config, credentials, themes, and browser preferences in one file.
</p>
<!-- Tab bar -->
<div class="panel-tabs">
<button class="panel-tab active" data-panel="backup-manual">Manual</button>
<button class="panel-tab" data-panel="backup-automated">Automated</button>
<button class="panel-tab" data-panel="backup-history-tab">History</button>
</div>
<!-- Tab: Manual -->
<div id="backup-manual" class="panel-section active">
<!-- Export Section -->
<div style="margin-bottom: 20px; padding: 16px; background: linear-gradient(135deg, color-mix(in srgb, #27ae60 15%, transparent), color-mix(in srgb, #2ecc71 10%, transparent)); border-radius: 10px; border: 1px solid #27ae60;">
<h4 style="margin: 0 0 8px; color: #2ecc71; font-size: 0.95rem;">\u{1F4E4} Export Backup</h4>
<p style="font-size: 0.8rem; color: var(--muted); margin: 0 0 12px;">
Downloads everything \u2014 services, Caddyfile, credentials, encryption key, themes, and all browser preferences.
</p>
<button id="backup-export-btn" style="width: 100%; padding: 10px; background: linear-gradient(135deg, #27ae60 0%, #2ecc71 100%); border: none; color: white; font-weight: 600; border-radius: 8px; cursor: pointer;">
\u2B07\uFE0F Download Full Backup
</button>
</div>
<!-- Import Section -->
<div style="padding: 16px; background: linear-gradient(135deg, color-mix(in srgb, #3498db 15%, transparent), color-mix(in srgb, #2980b9 10%, transparent)); border-radius: 10px; border: 1px solid #3498db;">
<h4 style="margin: 0 0 8px; color: #3498db; font-size: 0.95rem;">\u{1F4E5} Restore Backup</h4>
<p style="font-size: 0.8rem; color: var(--muted); margin: 0 0 12px;">
Upload a backup file to restore your entire configuration \u2014 drag and drop ready.
</p>
<input type="file" id="backup-file-input" accept=".json" style="display: none;" />
<button id="backup-select-file" style="width: 100%; padding: 10px; background: linear-gradient(135deg, #3498db 0%, #2980b9 100%); border: none; color: white; font-weight: 600; border-radius: 8px; cursor: pointer;">
\u{1F4C1} Select Backup File
</button>
<div id="backup-file-name" style="display: none; margin-top: 8px; padding: 8px; background: var(--card-base); border-radius: 6px; font-size: 0.85rem;"></div>
</div>
<!-- Preview Section (shown after file selected) -->
<div id="backup-preview" style="display: none; margin-top: 16px; padding: 16px; background: var(--card-base); border-radius: 10px; border: 1px solid var(--border);">
<h4 style="margin: 0 0 12px; font-size: 0.9rem;">\u{1F4CB} Backup Contents</h4>
<div id="backup-preview-content" style="font-size: 0.85rem;"></div>
<div style="margin-top: 12px; padding-top: 12px; border-top: 1px solid var(--border);">
<label class="checkbox-label" style="font-size: 0.85rem;">
<input type="checkbox" id="backup-reload-caddy" checked />
Reload Caddy after restore
</label>
</div>
<button id="backup-do-restore-btn" style="width: 100%; margin-top: 12px; padding: 10px; background: linear-gradient(135deg, #e74c3c 0%, #c0392b 100%); border: none; color: white; font-weight: 600; border-radius: 8px; cursor: pointer;">
\u26A1 Restore Everything
</button>
</div>
<!-- Result Message -->
<div id="backup-result" style="display: none; margin-top: 16px; padding: 12px; border-radius: 8px;"></div>
</div>
<!-- Tab: Automated Backups -->
<div id="backup-automated" class="panel-section">
<div id="backup-schedule-container">
<div class="panel-empty">
<span class="empty-icon">\u23F0</span>
<span class="brand-spinner"></span> Loading backup schedule...
</div>
</div>
</div>
<!-- Tab: Backup History -->
<div id="backup-history-tab" class="panel-section">
<div id="backup-history-container" style="max-height: 400px; overflow-y: auto;">
<div class="panel-empty">
<span class="empty-icon">\u{1F4CB}</span>
<span class="brand-spinner"></span> Loading backup history...
</div>
</div>
</div>
<!-- Close Button -->
<div class="weather-modal-buttons modal-footer-bar">
<button id="backup-cancel">Close</button>
</div>
</div>
</div>`);var N=document.getElementById("backup-modal"),D=document.getElementById("backup-restore-btn"),A=document.getElementById("backup-cancel"),$=document.getElementById("backup-export-btn"),P=document.getElementById("backup-select-file"),C=document.getElementById("backup-file-input"),H=document.getElementById("backup-file-name"),x=document.getElementById("backup-preview"),O=document.getElementById("backup-preview-content"),z=document.getElementById("backup-do-restore-btn"),S=document.getElementById("backup-result"),E=document.getElementById("backup-schedule-container"),k=document.getElementById("backup-history-container"),b=null;D?.addEventListener("click",function(){N.classList.add("show"),S&&(S.style.display="none"),x&&(x.style.display="none"),H&&(H.style.display="none"),b=null}),wireModal(N,A),$?.addEventListener("click",async function(){$.disabled=!0,$.innerHTML='<span class="brand-spinner"></span> Exporting...';try{var a=await fetch("/api/v1/backup/export"),n=await a.json();n.browserState=h();var e=new Blob([JSON.stringify(n,null,2)],{type:"application/json"}),t=URL.createObjectURL(e),i=document.createElement("a");i.href=t,i.download="dashcaddy-backup-"+new Date().toISOString().split("T")[0]+".json",document.body.appendChild(i),i.click(),document.body.removeChild(i),URL.revokeObjectURL(t);var r=Object.keys(n.browserState).length,p=n.themes?Object.keys(n.themes).length:0;S.innerHTML="\u2705 Full backup downloaded \u2014 server config + "+r+" browser settings"+(p?" + "+p+" themes":""),S.style.display="block",S.style.background="color-mix(in srgb, var(--ok-fg) 15%, transparent)",S.style.border="1px solid var(--ok-fg)"}catch(v){S.innerHTML="\u274C Export failed: "+escapeHtml(v.message),S.style.display="block",S.style.background="color-mix(in srgb, var(--bad-fg) 15%, transparent)",S.style.border="1px solid var(--bad-fg)"}$.disabled=!1,$.innerHTML="\u2B07\uFE0F Download Full Backup"}),P?.addEventListener("click",function(){C.click()}),C?.addEventListener("change",async function(a){var n=a.target.files[0];if(n){H.textContent="\u{1F4C4} "+n.name,H.style.display="block",S.style.display="none";try{var e=await n.text(),t=JSON.parse(e);if(T(t)){b=t;var i='<div style="margin-bottom: 8px; color: var(--muted); font-size: 0.8rem;">Legacy format (v'+escapeHtml(t.version)+")</div>";i+='<div style="display: flex; flex-wrap: wrap; gap: 6px;">',t.services?.length&&(i+='<span style="padding: 4px 8px; background: var(--base); border-radius: 4px; font-size: 0.8rem;">\u{1F4CB} '+t.services.length+" services</span>"),t.customApps?.length&&(i+='<span style="padding: 4px 8px; background: var(--base); border-radius: 4px; font-size: 0.8rem;">\u{1F4E6} '+t.customApps.length+" custom apps</span>"),t.theme&&(i+='<span style="padding: 4px 8px; background: var(--base); border-radius: 4px; font-size: 0.8rem;">\u{1F3A8} Theme: '+escapeHtml(t.theme)+"</span>"),t.userThemes&&(i+='<span style="padding: 4px 8px; background: var(--base); border-radius: 4px; font-size: 0.8rem;">\u{1F3A8} '+Object.keys(t.userThemes).length+" custom themes</span>"),i+="</div>",O.innerHTML=i,x.style.display="block";return}var r=await secureFetch("/api/v1/backup/preview",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),p=await r.json();if(p.success){b=t;var i='<div style="margin-bottom: 8px; color: var(--muted); font-size: 0.8rem;">Exported: '+new Date(t.exportedAt).toLocaleString()+" (v"+escapeHtml(t.version)+")</div>";i+='<div style="margin-bottom: 6px; font-size: 0.75rem; color: var(--muted); text-transform: uppercase; letter-spacing: 0.5px;">Server Config</div>',i+='<div style="display: flex; flex-wrap: wrap; gap: 6px; margin-bottom: 10px;">';for(var v in p.preview.files){var o=p.preview.files[v],s=o.action==="create"?"\u{1F195}":"\u{1F4DD}";i+='<span style="padding: 4px 8px; background: var(--base); border-radius: 4px; font-size: 0.8rem;">'+s+" "+escapeHtml(o.description)+"</span>"}i+="</div>",p.preview.serviceCount&&(i+='<div style="font-size: 0.8rem; color: var(--accent); margin-bottom: 6px;">'+p.preview.serviceCount+" services</div>"),p.preview.themeCount&&(i+='<div style="font-size: 0.8rem; color: var(--accent); margin-bottom: 6px;">\u{1F3A8} '+p.preview.themeCount+" custom themes</div>"),p.preview.browserStateCount&&(i+='<div style="margin-top: 6px; font-size: 0.75rem; color: var(--muted); text-transform: uppercase; letter-spacing: 0.5px;">Browser Preferences</div>',i+='<div style="font-size: 0.8rem; color: var(--accent);">\u{1F5A5}\uFE0F '+p.preview.browserStateCount+" saved settings (theme, weather, clock, widgets, etc.)</div>"),O.innerHTML=i,x.style.display="block"}else S.innerHTML="\u26A0\uFE0F Invalid backup file: "+escapeHtml(p.error),S.style.display="block",S.style.background="color-mix(in srgb, #f39c12 15%, transparent)",S.style.border="1px solid #f39c12",x.style.display="none"}catch(u){S.innerHTML="\u274C Could not read file: "+escapeHtml(u.message),S.style.display="block",S.style.background="color-mix(in srgb, var(--bad-fg) 15%, transparent)",S.style.border="1px solid var(--bad-fg)",x.style.display="none"}}}),z?.addEventListener("click",async function(){if(b&&confirm("This will overwrite your current configuration and browser preferences. Continue?")){z.disabled=!0,z.innerHTML='<span class="brand-spinner"></span> Restoring...';try{if(T(b)){B(b),S.innerHTML="\u2705 Legacy backup restored \u2014 browser settings and services imported.",S.style.background="color-mix(in srgb, var(--ok-fg) 15%, transparent)",S.style.border="1px solid var(--ok-fg)",S.style.display="block",setTimeout(function(){location.reload()},2e3),z.disabled=!1,z.innerHTML="\u26A1 Restore Everything";return}var a=document.getElementById("backup-reload-caddy")?.checked??!0,n=await secureFetch("/api/v1/backup/restore",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({backup:b,options:{reloadCaddy:a}})}),e=await n.json(),t=0;if(b.browserState&&(t=L(b.browserState)),e.success){var i="\u2705 "+e.message;t>0&&(i+='<br><small style="color: var(--muted);">'+t+" browser settings restored</small>"),e.results.caddyReloaded&&(i+='<br><small style="color: var(--muted);">Caddy configuration reloaded</small>'),S.innerHTML=i,S.style.background="color-mix(in srgb, var(--ok-fg) 15%, transparent)",S.style.border="1px solid var(--ok-fg)",setTimeout(function(){location.reload()},2e3)}else S.innerHTML="\u26A0\uFE0F "+escapeHtml(e.message),t>0&&(S.innerHTML+='<br><small style="color: var(--muted);">'+t+" browser settings were restored</small>"),e.results?.errors?.length>0&&(S.innerHTML+="<br><small>"+e.results.errors.map(function(r){return escapeHtml(r.file)+": "+escapeHtml(r.error)}).join(", ")+"</small>"),S.style.background="color-mix(in srgb, #f39c12 15%, transparent)",S.style.border="1px solid #f39c12";S.style.display="block"}catch(r){S.innerHTML="\u274C Restore failed: "+escapeHtml(r.message),S.style.display="block",S.style.background="color-mix(in srgb, var(--bad-fg) 15%, transparent)",S.style.border="1px solid var(--bad-fg)"}z.disabled=!1,z.innerHTML="\u26A1 Restore Everything"}});async function m(){if(E)try{var a=await fetch("/api/v1/backups/config"),n=await a.json();if(!n.success)throw new Error(n.error||"Failed to load config");var e=n.config?.backups||{},t=Object.keys(e)[0],i=t?e[t]:null,r='<div style="padding: 16px; background: color-mix(in srgb, var(--accent) 8%, transparent); border-radius: 10px; border: 1px solid color-mix(in srgb, var(--accent) 25%, transparent); margin-bottom: 16px;">';r+='<h4 style="margin: 0 0 12px; color: var(--accent); font-size: 0.9rem;">\u23F0 Backup Schedule</h4>',r+='<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 12px;">',r+='<div><label style="font-size: 0.8rem; color: var(--muted);">Schedule:</label>',r+=' <select id="backup-schedule-select" style="width: 100%;">',r+=' <option value="disabled"'+(i?.enabled?"":" selected")+">Disabled</option>",r+=' <option value="hourly"'+(i?.schedule==="hourly"?" selected":"")+">Hourly</option>",r+=' <option value="daily"'+(i?.schedule==="daily"?" selected":"")+">Daily</option>",r+=' <option value="weekly"'+(i?.schedule==="weekly"?" selected":"")+">Weekly</option>",r+=' <option value="monthly"'+(i?.schedule==="monthly"?" selected":"")+">Monthly</option>",r+=" </select></div>",r+='<div><label style="font-size: 0.8rem; color: var(--muted);">Keep last:</label>',r+=' <select id="backup-retention-select" style="width: 100%;">',r+=' <option value="3"'+(i?.retention?.keep===3?" selected":"")+">3 backups</option>",r+=' <option value="5"'+(!i?.retention||i?.retention?.keep===5?" selected":"")+">5 backups</option>",r+=' <option value="10"'+(i?.retention?.keep===10?" selected":"")+">10 backups</option>",r+=' <option value="30"'+(i?.retention?.keep===30?" selected":"")+">30 backups</option>",r+=" </select></div>",r+="</div>",r+='<div style="margin-top: 12px;">',r+=' <label style="display: flex; align-items: center; gap: 8px; font-size: 0.85rem; cursor: pointer;">',r+=' <input type="checkbox" id="backup-encrypt-toggle"'+(i?.encrypt!==!1?" checked":"")+" />",r+=" Encrypt backups",r+=" </label></div>",r+='<div style="display: flex; gap: 8px; margin-top: 12px;">',r+=' <button id="backup-save-schedule" style="padding: 8px 16px; background: color-mix(in srgb, var(--accent) 20%, transparent); border: 1px solid var(--accent); color: var(--accent); border-radius: 6px; cursor: pointer; font-weight: 500;">Save Schedule</button>',r+=' <button id="backup-run-now" style="padding: 8px 16px; border-radius: 6px; cursor: pointer;">\u25B6\uFE0F Run Backup Now</button>',r+="</div>",r+="</div>",r+='<div id="backup-schedule-result" style="display: none; margin-top: 12px; padding: 10px; border-radius: 8px; font-size: 0.85rem;"></div>',E.innerHTML=r,document.getElementById("backup-save-schedule")?.addEventListener("click",f),document.getElementById("backup-run-now")?.addEventListener("click",c)}catch(p){E.innerHTML='<div class="panel-empty" style="color: var(--bad-fg);">Failed to load schedule: '+escapeHtml(p.message)+"</div>"}}async function f(){var a=document.getElementById("backup-schedule-select")?.value,n=parseInt(document.getElementById("backup-retention-select")?.value)||5,e=document.getElementById("backup-encrypt-toggle")?.checked??!0,t=document.getElementById("backup-schedule-result");try{var i=await secureFetch("/api/v1/backups/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({backups:{auto:{enabled:a!=="disabled",schedule:a==="disabled"?"daily":a,include:["all"],encrypt:e,verify:!0,retention:{keep:n},destinations:[{type:"local"}]}}})}),r=await i.json();t&&(t.innerHTML=r.success?"\u2705 Schedule saved":"\u26A0\uFE0F "+escapeHtml(r.error),t.style.display="block",t.style.background=r.success?"color-mix(in srgb, var(--ok-fg) 15%, transparent)":"color-mix(in srgb, var(--bad-fg) 15%, transparent)",t.style.border=r.success?"1px solid var(--ok-fg)":"1px solid var(--bad-fg)",setTimeout(function(){t&&(t.style.display="none")},3e3))}catch(p){t&&(t.innerHTML="\u274C "+escapeHtml(p.message),t.style.display="block",t.style.background="color-mix(in srgb, var(--bad-fg) 15%, transparent)",t.style.border="1px solid var(--bad-fg)")}}async function c(){var a=document.getElementById("backup-run-now"),n=document.getElementById("backup-schedule-result");a&&(a.disabled=!0,a.innerHTML='<span class="brand-spinner"></span> Running...');try{var e=await secureFetch("/api/v1/backups/execute",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({include:["all"],destinations:[{type:"local"}]})}),t=await e.json();if(n){if(t.success){var i=t.backup?.size?(t.backup.size/1024/1024).toFixed(2):"?";n.innerHTML="\u2705 Backup complete ("+i+" MB)",n.style.background="color-mix(in srgb, var(--ok-fg) 15%, transparent)",n.style.border="1px solid var(--ok-fg)"}else n.innerHTML="\u26A0\uFE0F "+escapeHtml(t.error),n.style.background="color-mix(in srgb, var(--bad-fg) 15%, transparent)",n.style.border="1px solid var(--bad-fg)";n.style.display="block"}d()}catch(r){n&&(n.innerHTML="\u274C "+escapeHtml(r.message),n.style.display="block",n.style.background="color-mix(in srgb, var(--bad-fg) 15%, transparent)",n.style.border="1px solid var(--bad-fg)")}a&&(a.disabled=!1,a.innerHTML="\u25B6\uFE0F Run Backup Now")}async function d(){if(k){k.innerHTML='<div class="panel-empty"><span class="brand-spinner"></span> Loading...</div>';try{var a=await fetch("/api/v1/backups/history?limit=50"),n=await a.json();if(!n.success||!n.history?.length){k.innerHTML='<div class="panel-empty"><span class="empty-icon">\u{1F4CB}</span> No backup history yet</div>';return}for(var e='<div style="display: flex; flex-direction: column; gap: 6px;">',t=0;t<n.history.length;t++){var i=n.history[t],r=i.size?(i.size/1024/1024).toFixed(2):"?";e+='<div style="padding: 10px 12px; background: var(--card-base); border-radius: 6px; border: 1px solid var(--border); font-size: 0.85rem;">',e+=' <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 4px;">',e+=' <span style="font-weight: 500;">'+escapeHtml(i.name||"backup")+"</span>",e+=' <div style="display: flex; align-items: center; gap: 8px;">',e+=' <span class="status-badge '+(i.status==="success"?"success":"down")+'">'+escapeHtml(i.status)+"</span>",i.status==="success"&&(e+=' <button class="backup-restore-btn" data-backup-id="'+escapeHtml(i.id)+'" style="padding: 3px 8px; font-size: 0.75rem;">Restore</button>'),e+=" </div>",e+=" </div>",e+=' <div style="font-size: 0.75rem; color: var(--muted);">',e+=" "+new Date(i.timestamp).toLocaleString()+" | "+r+" MB | "+(i.duration?(i.duration/1e3).toFixed(1)+"s":"--"),i.encrypted&&(e+=" | \u{1F512}"),e+=" </div>",e+="</div>"}e+="</div>",k.innerHTML=e,k.querySelectorAll(".backup-restore-btn").forEach(function(p){p.addEventListener("click",function(){window.__restoreServerBackup(p.dataset.backupId)})})}catch(p){k.innerHTML='<div class="panel-empty" style="color: var(--bad-fg);">Failed: '+escapeHtml(p.message)+"</div>"}}}window.__restoreServerBackup=async function(a){if(confirm("Restore from this server backup? This will overwrite current configuration."))try{var n=await secureFetch("/api/v1/backups/restore/"+a,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({restoreServices:!0,restoreConfig:!0})}),e=await n.json();e.success?(showNotification("Restore completed successfully!","success"),location.reload()):showNotification("Restore failed: "+(e.error||"Unknown error"),"error")}catch(t){showNotification("Restore error: "+t.message,"error")}},document.querySelector('[data-panel="backup-automated"]')?.addEventListener("click",m),document.querySelector('[data-panel="backup-history-tab"]')?.addEventListener("click",d)})(),(function(){injectModal("stats-modal",`<div id="stats-modal" class="weather-modal">
<div class="weather-modal-content" style="min-width: 750px; max-width: 950px;">
<h3>\u{1F4CA} Resource Monitor</h3>
<p class="modal-subtitle">
Real-time and historical CPU, memory, network, and disk usage for containers.
</p>
<!-- Tab bar -->
<div class="panel-tabs">
<button class="panel-tab active" data-panel="stats-live">Live Stats</button>
<button class="panel-tab" data-panel="stats-aggregated">24h Summary</button>
<button class="panel-tab" data-panel="stats-alerts">Alerts</button>
</div>
<!-- Tab: Live Stats -->
<div id="stats-live" class="panel-section active">
<div id="stats-container" class="scroll-container">
<div style="text-align: center; padding: 40px; color: var(--muted);">
<span class="brand-spinner"></span> Loading container stats...
</div>
</div>
</div>
<!-- Tab: 24h Aggregated Summary -->
<div id="stats-aggregated" class="panel-section">
<div id="stats-aggregated-container" class="scroll-container">
<div class="panel-empty">
<span class="empty-icon">\u{1F4C8}</span>
Loading 24-hour aggregated metrics...
</div>
</div>
</div>
<!-- Tab: Alert Configuration -->
<div id="stats-alerts" class="panel-section">
<div id="stats-alerts-container" class="scroll-container">
<div class="panel-empty">
<span class="empty-icon">\u{1F514}</span>
Loading alert configurations...
</div>
</div>
</div>
<!-- Auto-refresh toggle (bottom bar) -->
<div class="panel-bottom-bar">
<label class="checkbox-label" style="font-size: 0.85rem;">
<input type="checkbox" id="stats-auto-refresh" checked />
Auto-refresh every 5s
</label>
<button id="stats-refresh-btn" class="btn-sm">\u{1F504} Refresh Now</button>
<span id="stats-last-update" class="text-auto-right"></span>
</div>
<!-- Close Button -->
<div class="weather-modal-buttons modal-footer-bar">
<button id="stats-cancel">Close</button>
</div>
</div>
</div>`);const y=document.getElementById("stats-modal"),h=document.getElementById("container-stats-btn"),L=document.getElementById("stats-cancel"),T=document.getElementById("stats-refresh-btn"),B=document.getElementById("stats-auto-refresh"),N=document.getElementById("stats-container"),D=document.getElementById("stats-aggregated-container"),A=document.getElementById("stats-alerts-container"),$=document.getElementById("stats-last-update");let P=null,C=null;function H(m){if(m===0||!m)return"0 B";const f=1024,c=["B","KB","MB","GB"],d=Math.floor(Math.log(m)/Math.log(f));return parseFloat((m/Math.pow(f,d)).toFixed(1))+" "+c[d]}function x(m){return m<30?"#2ecc71":m<70?"#f39c12":"#e74c3c"}function O(m){return m<50?"#2ecc71":m<80?"#f39c12":"#e74c3c"}async function z(){try{let m=null,f=!1;try{const a=await(await fetch("/api/v1/monitoring/stats")).json();a.success&&a.stats&&(m=a.stats,f=!0,C=a.stats)}catch{}if(!f){const a=await(await fetch("/api/v1/stats/containers")).json();if(a.success&&a.stats){m={};for(const n of a.stats)m[n.name]={name:n.name,current:{cpu:n.cpu,memory:{percent:n.memory.percent,usage:n.memory.used,limit:n.memory.limit,usageMB:Math.round(n.memory.used/1048576),limitMB:Math.round(n.memory.limit/1048576)},network:{rxBytes:n.network.rx,txBytes:n.network.tx,rxMB:(n.network.rx/1048576).toFixed(1),txMB:(n.network.tx/1048576).toFixed(1)},disk:{readMB:0,writeMB:0}},status:n.status};C=m}}if(!m||Object.keys(m).length===0){N.innerHTML='<div style="text-align: center; padding: 40px; color: var(--muted);">No running containers found</div>';return}let c='<div style="display: flex; flex-direction: column; gap: 8px;">';for(const[d,a]of Object.entries(m)){const n=a.current||a,e=n.cpu?.percent||0,t=n.memory?.percent||0,i=x(e),r=O(t),p=n.memory?.usage||n.memory?.used||0,v=n.memory?.limit||0,o=n.network?.rxBytes||n.network?.rx||0,s=n.network?.txBytes||n.network?.tx||0,u=a.aggregated;c+=`
<div style="padding: 12px; background: var(--card-base); border-radius: 8px; border: 1px solid var(--border);">
<div style="display: flex; align-items: center; gap: 12px; margin-bottom: 10px;">
<span style="font-weight: 600; flex: 1;">${a.name||d}</span>
${u?`<span style="font-size: 0.65rem; color: var(--muted); padding: 2px 6px; background: color-mix(in srgb, var(--accent) 10%, transparent); border-radius: 4px;">avg ${u.cpu?.avg?.toFixed(0)||0}% cpu</span>`:""}
<span style="font-size: 0.75rem; color: var(--muted); background: var(--base); padding: 2px 8px; border-radius: 4px;">${a.status||"running"}</span>
</div>
<div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 12px;">
<div>
<div style="font-size: 0.7rem; color: var(--muted); margin-bottom: 4px;">CPU</div>
<div style="display: flex; align-items: center; gap: 8px;">
<div style="flex: 1; height: 6px; background: var(--base); border-radius: 3px; overflow: hidden;">
<div style="height: 100%; width: ${Math.min(e,100)}%; background: ${i}; border-radius: 3px; transition: width 0.3s;"></div>
</div>
<span style="font-size: 0.8rem; font-weight: 500; color: ${i}; min-width: 45px; text-align: right;">${e.toFixed(1)}%</span>
</div>
</div>
<div>
<div style="font-size: 0.7rem; color: var(--muted); margin-bottom: 4px;">Memory</div>
<div style="display: flex; align-items: center; gap: 8px;">
<div style="flex: 1; height: 6px; background: var(--base); border-radius: 3px; overflow: hidden;">
<div style="height: 100%; width: ${Math.min(t,100)}%; background: ${r}; border-radius: 3px; transition: width 0.3s;"></div>
</div>
<span style="font-size: 0.8rem; font-weight: 500; color: ${r}; min-width: 45px; text-align: right;">${t.toFixed(1)}%</span>
</div>
<div style="font-size: 0.65rem; color: var(--muted); margin-top: 2px;">${H(p)} / ${H(v)}</div>
</div>
<div>
<div style="font-size: 0.7rem; color: var(--muted); margin-bottom: 4px;">Network</div>
<div style="font-size: 0.8rem;">
<span style="color: #3498db;">\u2193 ${H(o)}</span>
<span style="color: var(--muted); margin: 0 4px;">/</span>
<span style="color: #e74c3c;">\u2191 ${H(s)}</span>
</div>
</div>
</div>
</div>`}c+="</div>",N.innerHTML=c,$.textContent="Updated: "+new Date().toLocaleTimeString()}catch(m){N.innerHTML=`<div style="text-align: center; padding: 40px; color: var(--bad-fg);">\u274C Failed to load stats: ${escapeHtml(m.message)}</div>`}}async function S(){if(!D)return;const m=C;if(!m||Object.keys(m).length===0){D.innerHTML='<div class="panel-empty"><span class="empty-icon">\u{1F4C8}</span>No monitoring data available. Open the Live Stats tab first.</div>';return}let f='<div style="display: flex; flex-direction: column; gap: 12px;">';for(const[c,d]of Object.entries(m)){const a=d.aggregated;a&&(f+=`<div style="padding: 12px; background: var(--card-base); border-radius: 8px; border: 1px solid var(--border);">
<div style="font-weight: 600; margin-bottom: 10px;">${d.name||c}</div>
<div style="display: grid; grid-template-columns: repeat(4, 1fr); gap: 8px;">
<div class="stat-mini-card"><span class="stat-val">${a.cpu?.avg?.toFixed(1)||0}%</span><span class="stat-lbl">Avg CPU</span></div>
<div class="stat-mini-card"><span class="stat-val">${a.cpu?.max?.toFixed(1)||0}%</span><span class="stat-lbl">Max CPU</span></div>
<div class="stat-mini-card"><span class="stat-val">${a.memory?.avg?.toFixed(1)||0}%</span><span class="stat-lbl">Avg Mem</span></div>
<div class="stat-mini-card"><span class="stat-val">${a.memory?.max?.toFixed(1)||0}%</span><span class="stat-lbl">Max Mem</span></div>
</div>
${a.dataPoints?`<div style="font-size: 0.7rem; color: var(--muted); margin-top: 6px;">${a.dataPoints} data points over ${a.timeRange||24}h</div>`:""}
</div>`)}f+="</div>",D.innerHTML=f}async function E(){if(!A)return;A.innerHTML='<div class="panel-empty"><span class="brand-spinner"></span> Loading alerts...</div>';const m=C;if(!m||Object.keys(m).length===0){A.innerHTML='<div class="panel-empty"><span class="empty-icon">\u{1F514}</span>No containers found. Open the Live Stats tab first.</div>';return}let f='<div style="display: flex; flex-direction: column; gap: 12px;">';for(const[c,d]of Object.entries(m)){const a=d.alertConfig||{};f+=`<div style="padding: 12px; background: var(--card-base); border-radius: 8px; border: 1px solid var(--border);">
<div style="display: flex; align-items: center; gap: 8px; margin-bottom: 10px;">
<span style="font-weight: 600; flex: 1;">${d.name||c}</span>
<label style="display: flex; align-items: center; gap: 6px; font-size: 0.8rem; cursor: pointer;">
<input type="checkbox" class="alert-enabled" data-container="${c}" ${a.enabled?"checked":""} /> Enabled
</label>
</div>
<div style="display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 8px;">
<div>
<label style="font-size: 0.75rem; color: var(--muted);">CPU Threshold %</label>
<input type="number" class="alert-cpu" data-container="${c}" value="${a.cpuThreshold||80}" min="1" max="100" style="width: 100%; font-size: 0.85rem;" />
</div>
<div>
<label style="font-size: 0.75rem; color: var(--muted);">Memory Threshold %</label>
<input type="number" class="alert-mem" data-container="${c}" value="${a.memoryThreshold||85}" min="1" max="100" style="width: 100%; font-size: 0.85rem;" />
</div>
<div>
<label style="font-size: 0.75rem; color: var(--muted);">Cooldown (min)</label>
<input type="number" class="alert-cooldown" data-container="${c}" value="${a.cooldownMinutes||15}" min="1" max="1440" style="width: 100%; font-size: 0.85rem;" />
</div>
</div>
<div style="display: flex; gap: 8px; margin-top: 8px; align-items: center;">
<label style="display: flex; align-items: center; gap: 6px; font-size: 0.8rem; cursor: pointer;">
<input type="checkbox" class="alert-autorestart" data-container="${c}" ${a.autoRestart?"checked":""} /> Auto-restart on breach
</label>
<span style="flex: 1;"></span>
<button class="alert-save-btn" data-container="${c}" style="padding: 4px 12px; font-size: 0.8rem; background: color-mix(in srgb, var(--accent) 20%, transparent); border: 1px solid var(--accent); color: var(--accent); border-radius: 4px; cursor: pointer;">Save</button>
</div>
</div>`}f+="</div>",A.innerHTML=f,A.querySelectorAll(".alert-save-btn").forEach(c=>{c.addEventListener("click",async()=>{const d=c.dataset.container,a=A.querySelector(`.alert-enabled[data-container="${d}"]`)?.checked||!1,n=parseInt(A.querySelector(`.alert-cpu[data-container="${d}"]`)?.value)||80,e=parseInt(A.querySelector(`.alert-mem[data-container="${d}"]`)?.value)||85,t=parseInt(A.querySelector(`.alert-cooldown[data-container="${d}"]`)?.value)||15,i=A.querySelector(`.alert-autorestart[data-container="${d}"]`)?.checked||!1;try{const p=await(await secureFetch(`/api/v1/monitoring/alerts/${d}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({enabled:a,cpuThreshold:n,memoryThreshold:e,cooldownMinutes:t,autoRestart:i})})).json();c.textContent=p.success?"\u2705 Saved":"\u26A0\uFE0F Failed",setTimeout(()=>{c.textContent="Save"},2e3)}catch{c.textContent="\u274C Error",setTimeout(()=>{c.textContent="Save"},2e3)}})})}function k(){P&&clearInterval(P),B?.checked&&(P=setInterval(z,DC.POLL.STATS))}function b(){P&&(clearInterval(P),P=null)}h?.addEventListener("click",()=>{y.classList.add("show"),z(),k()}),L?.addEventListener("click",()=>{y.classList.remove("show"),b()}),y?.addEventListener("click",m=>{m.target===y&&(y.classList.remove("show"),b())}),T?.addEventListener("click",z),B?.addEventListener("change",()=>{B.checked?k():b()}),document.querySelector('[data-panel="stats-aggregated"]')?.addEventListener("click",S),document.querySelector('[data-panel="stats-alerts"]')?.addEventListener("click",E)})(),(function(){injectModal("health-modal",`<div id="health-modal" class="weather-modal">
<div class="weather-modal-content" style="min-width: 800px; max-width: 1000px;">
<h3>\u{1F3E5} Health Check Dashboard</h3>
<p class="modal-subtitle">
Service uptime tracking, SLA monitoring, and incident management.
</p>
<div class="panel-tabs">
<button class="panel-tab active" data-panel="health-status">Status</button>
<button class="panel-tab" data-panel="health-incidents">Incidents</button>
<button class="panel-tab" data-panel="health-config">Configure</button>
</div>
<!-- Tab: Status -->
<div id="health-status" class="panel-section active">
<div id="health-status-container" class="scroll-container">
<div class="panel-empty"><span class="brand-spinner"></span> Loading health status...</div>
</div>
</div>
<!-- Tab: Incidents -->
<div id="health-incidents" class="panel-section">
<div id="health-incidents-container" class="scroll-container">
<div class="panel-empty"><span class="empty-icon">\u{1F6A8}</span> Loading incidents...</div>
</div>
</div>
<!-- Tab: Configure -->
<div id="health-config" class="panel-section">
<div id="health-config-container" class="scroll-container">
<div class="panel-empty"><span class="empty-icon">\u2699\uFE0F</span> Loading configuration...</div>
</div>
<!-- Add/Edit Health Check Form -->
<div id="health-config-form" style="display: none; margin-top: 16px; padding: 16px; border: 1px solid var(--border); border-radius: var(--radius); background: var(--card-base);">
<h4 id="health-form-title" style="margin: 0 0 12px;">Add Health Check</h4>
<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 12px;">
<div>
<label class="text-muted-sm">Service ID</label>
<input type="text" id="health-form-id" placeholder="e.g. plex" class="form-input" />
</div>
<div>
<label class="text-muted-sm">Display Name</label>
<input type="text" id="health-form-name" placeholder="e.g. Plex Media Server" class="form-input" />
</div>
<div style="grid-column: span 2;">
<label class="text-muted-sm">URL</label>
<input type="text" id="health-form-url" placeholder="https://plex.home" class="form-input" />
</div>
<div>
<label class="text-muted-sm">Timeout (ms)</label>
<input type="number" id="health-form-timeout" value="10000" class="form-input" />
</div>
<div>
<label class="text-muted-sm">Expected Status Codes</label>
<input type="text" id="health-form-codes" value="200" placeholder="200, 301, 302" class="form-input" />
</div>
<div>
<label class="text-muted-sm">SLA Target (%)</label>
<input type="number" id="health-form-sla" value="99.9" step="0.1" class="form-input" />
</div>
<div>
<label class="text-muted-sm">Slow Response Threshold (ms)</label>
<input type="number" id="health-form-slow" value="5000" class="form-input" />
</div>
</div>
<div style="margin-top: 12px; display: flex; gap: 8px; justify-content: flex-end;">
<button id="health-form-cancel">Cancel</button>
<button id="health-form-save" class="btn-accent-solid">Save</button>
</div>
</div>
<div style="margin-top: 12px;">
<button id="health-add-btn" class="btn-accent-solid">+ Add Health Check</button>
</div>
</div>
<div class="panel-bottom-bar">
<button id="health-refresh-btn" class="btn-sm">\u{1F504} Refresh</button>
<span id="health-last-update" class="text-auto-right"></span>
</div>
<div class="weather-modal-buttons modal-footer-bar">
<button id="health-cancel">Close</button>
</div>
</div>
</div>`);const y=document.getElementById("health-modal"),h=document.getElementById("health-check-btn"),L=document.getElementById("health-cancel"),T=document.getElementById("health-refresh-btn"),B=document.getElementById("health-status-container"),N=document.getElementById("health-incidents-container"),D=document.getElementById("health-config-container"),A=document.getElementById("health-last-update"),$=document.getElementById("health-add-btn"),P=document.getElementById("health-config-form"),C=document.getElementById("health-form-title"),H=document.getElementById("health-form-cancel"),x=document.getElementById("health-form-save");let O=null;function z(c){return c>=99.9?"var(--ok-fg)":c>=95?"#f39c12":"var(--bad-fg)"}function S(c){const d={critical:"var(--bad-fg)",high:"#ff6b6b",medium:"#f39c12",low:"var(--muted)"};return`<span style="padding: 2px 8px; border-radius: 4px; font-size: 0.75rem; background: ${d[c]||"var(--muted)"}20; color: ${d[c]||"var(--muted)"};">${c}</span>`}async function E(){try{const d=await(await fetch("/api/v1/health-checks/status")).json();if(!d.success||!d.status||Object.keys(d.status).length===0){B.innerHTML='<div class="panel-empty"><span class="empty-icon">\u{1F3E5}</span>No health checks configured. Go to the Configure tab to add services.</div>';return}const a=Object.values(d.status);let n='<table style="width: 100%; border-collapse: collapse; font-size: 0.85rem;">';n+='<tr style="border-bottom: 1px solid var(--border); color: var(--muted); text-align: left;">',n+='<th style="padding: 8px;">Service</th><th style="padding: 8px;">Status</th>',n+='<th style="padding: 8px;">Uptime 24h</th><th style="padding: 8px;">Uptime 7d</th>',n+='<th style="padding: 8px;">Avg Response</th><th style="padding: 8px;">Last Check</th></tr>';for(const e of a){const t=e.status==="up",i=t?"var(--dot-ok)":"var(--dot-bad)",r=e.uptime?.["24h"]??"-",p=e.uptime?.["7d"]??"-",v=e.avgResponseTime!=null?Math.round(e.avgResponseTime)+"ms":"-",o=e.timestamp?timeAgo(e.timestamp):"-";n+=`<tr style="border-bottom: 1px solid var(--border); cursor: pointer;" data-health-id="${escapeHtml(e.serviceId)}">`,n+=`<td style="padding: 8px; font-weight: 500;">${escapeHtml(e.name||e.serviceId)}</td>`,n+=`<td style="padding: 8px;"><span style="display: inline-block; width: 8px; height: 8px; border-radius: 50%; background: ${i}; margin-right: 6px;"></span>${t?"Up":"Down"}</td>`,n+=`<td style="padding: 8px; color: ${typeof r=="number"?z(r):"var(--muted)"};">${typeof r=="number"?r.toFixed(1)+"%":r}</td>`,n+=`<td style="padding: 8px; color: ${typeof p=="number"?z(p):"var(--muted)"};">${typeof p=="number"?p.toFixed(1)+"%":p}</td>`,n+=`<td style="padding: 8px;">${v}</td>`,n+=`<td style="padding: 8px; color: var(--muted);">${o}</td>`,n+="</tr>",n+=`<tr id="health-detail-${escapeHtml(e.serviceId)}" style="display: none;"><td colspan="6" style="padding: 12px; background: var(--bg); border-bottom: 1px solid var(--border);"><div class="panel-empty"><span class="brand-spinner"></span> Loading details...</div></td></tr>`}n+="</table>",B.innerHTML=n,A.textContent="Updated "+new Date().toLocaleTimeString(),B.querySelectorAll("tr[data-health-id]").forEach(e=>{e.addEventListener("click",async()=>{const t=e.dataset.healthId,i=document.getElementById("health-detail-"+t);if(i){if(i.style.display!=="none"){i.style.display="none";return}i.style.display="";try{const p=await(await fetch(`/api/v1/health-checks/${t}/stats?hours=24`)).json();if(p.success&&p.stats){const v=p.stats,o=v.responseTime||{};i.querySelector("td").innerHTML=`
<div style="display: grid; grid-template-columns: repeat(4, 1fr); gap: 12px; font-size: 0.82rem;">
<div><span style="color: var(--muted);">Total Checks</span><br><strong>${v.totalChecks||0}</strong></div>
<div><span style="color: var(--muted);">Uptime</span><br><strong style="color: ${z(v.uptime||0)};">${(v.uptime||0).toFixed(2)}%</strong></div>
<div><span style="color: var(--muted);">Avg Response</span><br><strong>${Math.round(o.avg||0)}ms</strong></div>
<div><span style="color: var(--muted);">P95 / P99</span><br><strong>${Math.round(o.p95||0)}ms / ${Math.round(o.p99||0)}ms</strong></div>
<div><span style="color: var(--muted);">Min Response</span><br><strong>${Math.round(o.min||0)}ms</strong></div>
<div><span style="color: var(--muted);">Max Response</span><br><strong>${Math.round(o.max||0)}ms</strong></div>
<div><span style="color: var(--muted);">Up Checks</span><br><strong style="color: var(--ok-fg);">${v.upChecks||0}</strong></div>
<div><span style="color: var(--muted);">Down Checks</span><br><strong style="color: var(--bad-fg);">${v.downChecks||0}</strong></div>
</div>`}else i.querySelector("td").innerHTML='<div class="panel-empty">No detailed stats available for this period.</div>'}catch(r){i.querySelector("td").innerHTML=`<div class="panel-empty" style="color: var(--bad-fg);">Failed: ${escapeHtml(r.message)}</div>`}}})})}catch(c){B.innerHTML=`<div class="panel-empty" style="color: var(--bad-fg);">Failed to load health status: ${escapeHtml(c.message)}</div>`}}async function k(){try{const[c,d]=await Promise.all([fetch("/api/v1/health-checks/incidents"),fetch("/api/v1/health-checks/incidents/history?limit=50")]),a=await c.json(),n=await d.json();let e="";const t=a.success&&a.incidents?a.incidents:[];if(t.length>0){e+='<div style="margin-bottom: 16px;"><h4 style="color: var(--bad-fg); margin: 0 0 8px;">Open Incidents ('+t.length+")</h4>";for(const r of t)e+=`<div style="padding: 10px 12px; margin-bottom: 8px; border: 1px solid var(--bad-fg)30; border-radius: 8px; background: var(--bad-bg);">
<div style="display: flex; justify-content: space-between; align-items: center;">
<span style="font-weight: 500;">${escapeHtml(r.serviceId)}</span>
<span>${S(r.severity)}</span>
</div>
<div style="font-size: 0.82rem; color: var(--muted); margin-top: 4px;">${escapeHtml(r.message)}</div>
<div style="font-size: 0.75rem; color: var(--muted); margin-top: 4px;">Started ${timeAgo(r.createdAt)} \xB7 ${r.occurrences||1} occurrence(s)</div>
</div>`;e+="</div>"}else e+='<div style="padding: 12px; margin-bottom: 16px; border: 1px solid var(--ok-fg)30; border-radius: 8px; background: var(--ok-bg); text-align: center; color: var(--ok-fg); font-size: 0.9rem;">All services operational \u2014 no open incidents</div>';const i=n.success&&n.history?n.history:[];if(i.length>0){e+='<h4 style="margin: 0 0 8px; color: var(--muted);">Incident History</h4>',e+='<table style="width: 100%; border-collapse: collapse; font-size: 0.82rem;">',e+='<tr style="border-bottom: 1px solid var(--border); color: var(--muted);"><th style="padding: 6px; text-align: left;">Service</th><th style="padding: 6px; text-align: left;">Type</th><th style="padding: 6px; text-align: left;">Severity</th><th style="padding: 6px; text-align: left;">Status</th><th style="padding: 6px; text-align: left;">Duration</th><th style="padding: 6px; text-align: left;">When</th></tr>';for(const r of i){const p=r.status==="resolved",v=p&&r.duration?r.duration<6e4?Math.round(r.duration/1e3)+"s":Math.round(r.duration/6e4)+"m":"-";e+='<tr style="border-bottom: 1px solid var(--border);">',e+=`<td style="padding: 6px;">${escapeHtml(r.serviceId)}</td>`,e+=`<td style="padding: 6px;">${escapeHtml(r.type)}</td>`,e+=`<td style="padding: 6px;">${S(r.severity)}</td>`,e+=`<td style="padding: 6px;"><span style="color: ${p?"var(--ok-fg)":"var(--bad-fg)"};">${r.status}</span></td>`,e+=`<td style="padding: 6px;">${v}</td>`,e+=`<td style="padding: 6px; color: var(--muted);">${timeAgo(r.createdAt)}</td>`,e+="</tr>"}e+="</table>"}N.innerHTML=e||'<div class="panel-empty"><span class="empty-icon">\u{1F6A8}</span>No incidents recorded yet.</div>'}catch(c){N.innerHTML=`<div class="panel-empty" style="color: var(--bad-fg);">Failed: ${escapeHtml(c.message)}</div>`}}async function b(){try{const d=await(await fetch("/api/v1/health-checks/status")).json(),a=d.success&&d.status?Object.values(d.status):[];if(a.length===0){D.innerHTML='<div class="panel-empty"><span class="empty-icon">\u2699\uFE0F</span>No health checks configured yet. Click "Add Health Check" below.</div>';return}let n='<table style="width: 100%; border-collapse: collapse; font-size: 0.85rem;">';n+='<tr style="border-bottom: 1px solid var(--border); color: var(--muted);"><th style="padding: 8px; text-align: left;">Service</th><th style="padding: 8px; text-align: left;">Status</th><th style="padding: 8px; text-align: left;">SLA Target</th><th style="padding: 8px; text-align: right;">Actions</th></tr>';for(const e of a){const t=e.status==="up";n+='<tr style="border-bottom: 1px solid var(--border);">',n+=`<td style="padding: 8px; font-weight: 500;">${escapeHtml(e.name||e.serviceId)}</td>`,n+=`<td style="padding: 8px; color: ${t?"var(--ok-fg)":"var(--bad-fg)"};">${t?"Up":"Down"}</td>`,n+=`<td style="padding: 8px;">${e.sla?.target?e.sla.target+"%":"-"}</td>`,n+='<td style="padding: 8px; text-align: right;">',n+=`<button onclick="document.dispatchEvent(new CustomEvent('health-edit', {detail:'${escapeHtml(e.serviceId)}'}))" style="padding: 4px 10px; font-size: 0.78rem; margin-right: 4px;">Edit</button>`,n+=`<button onclick="document.dispatchEvent(new CustomEvent('health-delete', {detail:'${escapeHtml(e.serviceId)}'}))" style="padding: 4px 10px; font-size: 0.78rem; color: var(--bad-fg); border-color: var(--bad-fg);">Delete</button>`,n+="</td></tr>"}n+="</table>",D.innerHTML=n}catch(c){D.innerHTML=`<div class="panel-empty" style="color: var(--bad-fg);">Failed: ${escapeHtml(c.message)}</div>`}}function m(c,d,a,n,e,t,i){O=c||null,C.textContent=c?"Edit Health Check":"Add Health Check",document.getElementById("health-form-id").value=c||"",document.getElementById("health-form-id").disabled=!!c,document.getElementById("health-form-name").value=d||"",document.getElementById("health-form-url").value=a||"",document.getElementById("health-form-timeout").value=n||1e4,document.getElementById("health-form-codes").value=e||"200",document.getElementById("health-form-sla").value=t||99.9,document.getElementById("health-form-slow").value=i||5e3,P.style.display="",$.style.display="none"}function f(){P.style.display="none",$.style.display="",O=null}$?.addEventListener("click",()=>m("","","",1e4,"200",99.9,5e3)),H?.addEventListener("click",f),x?.addEventListener("click",async()=>{const c=O||document.getElementById("health-form-id").value.trim();if(!c)return showNotification("Service ID is required","warning");const d=document.getElementById("health-form-url").value.trim();if(!d)return showNotification("URL is required","warning");const a=document.getElementById("health-form-codes").value.split(",").map(e=>parseInt(e.trim())).filter(Boolean),n={name:document.getElementById("health-form-name").value.trim()||c,url:d,timeout:parseInt(document.getElementById("health-form-timeout").value)||1e4,expectedStatusCodes:a.length?a:[200],sla:{target:parseFloat(document.getElementById("health-form-sla").value)||99.9},slowResponseThreshold:parseInt(document.getElementById("health-form-slow").value)||5e3};try{x.textContent="Saving...",x.disabled=!0;const t=await(await secureFetch(`/api/v1/health-checks/${encodeURIComponent(c)}/configure`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)})).json();if(!t.success)throw new Error(t.error||"Save failed");f(),b(),E()}catch(e){showNotification("Error: "+e.message,"error")}finally{x.textContent="Save",x.disabled=!1}}),document.addEventListener("health-edit",async c=>{const d=c.detail;m(d,"","",1e4,"200",99.9,5e3)}),document.addEventListener("health-delete",async c=>{const d=c.detail;if(confirm(`Delete health check for "${d}"?`))try{const n=await(await secureFetch(`/api/v1/health-checks/${encodeURIComponent(d)}/configure`,{method:"DELETE"})).json();if(!n.success)throw new Error(n.error);b(),E()}catch(a){showNotification("Error: "+a.message,"error")}}),h?.addEventListener("click",()=>{y?.classList.add("show"),E()}),wireModal(y,L),T?.addEventListener("click",E),document.querySelector('[data-panel="health-incidents"]')?.addEventListener("click",k),document.querySelector('[data-panel="health-config"]')?.addEventListener("click",b)})(),(function(){injectModal("updates-modal",`<div id="updates-modal" class="weather-modal">
<div class="weather-modal-content" style="min-width: 750px; max-width: 950px;">
<h3>\u2B06\uFE0F Update Management</h3>
<p class="modal-subtitle">
Check for container image updates, apply them, and manage rollbacks.
</p>
<div class="panel-tabs">
<button class="panel-tab active" data-panel="updates-available">Available</button>
<button class="panel-tab" data-panel="updates-history">History</button>
<button class="panel-tab" data-panel="updates-auto">Auto-Update</button>
<button class="panel-tab" data-panel="updates-dashcaddy" id="updates-dashcaddy-tab">DashCaddy</button>
</div>
<!-- Tab: Available Updates -->
<div id="updates-available" class="panel-section active">
<div style="margin-bottom: 12px;">
<button id="updates-check-btn" class="btn-accent-solid">\u{1F50D} Check for Updates</button>
</div>
<div id="updates-available-container" style="max-height: 450px; overflow-y: auto;">
<div class="panel-empty"><span class="empty-icon">\u{1F4E6}</span> Click "Check for Updates" to scan containers.</div>
</div>
</div>
<!-- Tab: History -->
<div id="updates-history" class="panel-section">
<div id="updates-history-container" class="scroll-container">
<div class="panel-empty"><span class="brand-spinner"></span> Loading update history...</div>
</div>
</div>
<!-- Tab: Auto-Update -->
<div id="updates-auto" class="panel-section">
<div id="updates-auto-container" class="scroll-container">
<div class="panel-empty"><span class="empty-icon">\u{1F916}</span> Loading auto-update configuration...</div>
</div>
</div>
<!-- Tab: DashCaddy Self-Update -->
<div id="updates-dashcaddy" class="panel-section">
<div id="dashcaddy-version-info" style="display: flex; align-items: center; gap: 16px; margin-bottom: 16px; padding: 12px; border-radius: 8px; background: var(--bg);">
<div style="flex: 1;">
<div style="font-weight: 600; font-size: 1rem;">DashCaddy</div>
<div id="dashcaddy-current-version" style="color: var(--muted); font-size: 0.85rem;">Loading...</div>
</div>
<div id="dashcaddy-update-badge" style="display: none; padding: 4px 12px; border-radius: 12px; font-size: 0.78rem; font-weight: 600; background: var(--accent); color: var(--bg);">Update available</div>
</div>
<div id="dashcaddy-update-details" style="display: none; margin-bottom: 16px; padding: 12px; border-radius: 8px; border: 1px solid var(--border);">
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px;">
<span style="font-weight: 600;">New version: <span id="dashcaddy-new-version"></span></span>
<button id="dashcaddy-apply-btn" class="btn-accent-solid" style="padding: 6px 16px; font-size: 0.85rem;">Update Now</button>
</div>
<div id="dashcaddy-changelog" style="font-size: 0.8rem; color: var(--muted); max-height: 120px; overflow-y: auto; white-space: pre-wrap; font-family: var(--font-mono); line-height: 1.5;"></div>
</div>
<div id="dashcaddy-status-bar" style="display: none; margin-bottom: 16px; padding: 10px 12px; border-radius: 8px; font-size: 0.85rem;"></div>
<div style="margin-bottom: 12px;">
<button id="dashcaddy-check-btn" style="padding: 6px 14px; font-size: 0.82rem;">Check for Updates</button>
<button id="dashcaddy-rollback-btn" style="padding: 6px 14px; font-size: 0.82rem; margin-left: 6px;">Rollback</button>
</div>
<div id="dashcaddy-history-container" style="max-height: 250px; overflow-y: auto;">
<div class="panel-empty"><span class="empty-icon">\u{1F4E6}</span>No self-update history.</div>
</div>
</div>
<div class="panel-bottom-bar">
<span id="updates-last-check" class="text-auto-right"></span>
</div>
<div class="weather-modal-buttons modal-footer-bar">
<button id="updates-cancel">Close</button>
</div>
</div>
</div>`);const y=document.getElementById("updates-modal"),h=document.getElementById("updates-btn"),L=document.getElementById("updates-cancel"),T=document.getElementById("updates-check-btn"),B=document.getElementById("updates-available-container"),N=document.getElementById("updates-history-container"),D=document.getElementById("updates-auto-container"),A=document.getElementById("updates-last-check");async function $(){try{const v=await(await fetch("/api/v1/updates/available")).json();if(!v.success)throw new Error(v.error);const o=v.updates||[];if(o.length===0){B.innerHTML='<div class="panel-empty"><span class="empty-icon">\u2705</span>All containers are up to date.</div>',A.textContent="";return}let s='<table style="width: 100%; border-collapse: collapse; font-size: 0.85rem;">';s+='<tr style="border-bottom: 1px solid var(--border); color: var(--muted);"><th style="padding: 8px; text-align: left;">Container</th><th style="padding: 8px; text-align: left;">Image</th><th style="padding: 8px; text-align: left;">Current</th><th style="padding: 8px; text-align: left;">Latest</th><th style="padding: 8px; text-align: right;">Actions</th></tr>';for(const u of o)s+='<tr style="border-bottom: 1px solid var(--border);">',s+=`<td style="padding: 8px; font-weight: 500;">${escapeHtml(u.containerName)}</td>`,s+=`<td style="padding: 8px; color: var(--muted);">${escapeHtml(u.imageName)}</td>`,s+=`<td style="padding: 8px;"><code style="font-size: 0.78rem; background: var(--bg); padding: 2px 6px; border-radius: 4px;">${escapeHtml(u.currentDigest)}</code></td>`,s+=`<td style="padding: 8px;"><code style="font-size: 0.78rem; background: var(--ok-bg); color: var(--ok-fg); padding: 2px 6px; border-radius: 4px;">${escapeHtml(u.latestDigest)}</code></td>`,s+='<td style="padding: 8px; text-align: right;">',s+=`<button class="update-now-btn" data-id="${escapeHtml(u.containerId)}" data-name="${escapeHtml(u.containerName)}" style="padding: 4px 10px; font-size: 0.78rem; background: var(--accent); color: var(--bg); border-color: var(--accent); margin-right: 4px;">Update</button>`,s+=`<button class="rollback-btn" data-id="${escapeHtml(u.containerId)}" data-name="${escapeHtml(u.containerName)}" style="padding: 4px 10px; font-size: 0.78rem;">Rollback</button>`,s+="</td></tr>";s+="</table>",B.innerHTML=s,A.textContent=o.length+" update(s) available",B.querySelectorAll(".update-now-btn").forEach(u=>{u.addEventListener("click",async()=>{const l=u.dataset.id,g=u.dataset.name;if(confirm(`Update "${g}" to the latest version? The container will restart.`)){u.textContent="Updating...",u.disabled=!0;try{const w=await(await secureFetch(`/api/v1/updates/update/${encodeURIComponent(l)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({autoRollback:!0})})).json();if(w.success)u.textContent="Done!",u.style.background="var(--ok-fg)",setTimeout(()=>$(),2e3);else throw new Error(w.error||"Update failed")}catch(I){u.textContent="Failed",u.style.color="var(--bad-fg)",showNotification("Update error: "+I.message,"error"),setTimeout(()=>{u.textContent="Update",u.disabled=!1,u.style.color="",u.style.background=""},3e3)}}})}),B.querySelectorAll(".rollback-btn").forEach(u=>{u.addEventListener("click",async()=>{const l=u.dataset.id,g=u.dataset.name;if(confirm(`Rollback "${g}" to its previous version?`)){u.textContent="Rolling back...",u.disabled=!0;try{const w=await(await secureFetch(`/api/v1/updates/rollback/${encodeURIComponent(l)}`,{method:"POST"})).json();if(w.success)u.textContent="Rolled back!",setTimeout(()=>$(),2e3);else throw new Error(w.error||"Rollback failed")}catch(I){u.textContent="Failed",showNotification("Rollback error: "+I.message,"error"),setTimeout(()=>{u.textContent="Rollback",u.disabled=!1},3e3)}}})})}catch(p){B.innerHTML=`<div class="panel-empty" style="color: var(--bad-fg);">Failed: ${escapeHtml(p.message)}</div>`}}async function P(){T.textContent="\u{1F50D} Checking...",T.disabled=!0;try{const v=await(await secureFetch("/api/v1/updates/check",{method:"POST"})).json();if(!v.success)throw new Error(v.error);T.textContent="\u2705 Done!",await $()}catch(p){T.textContent="\u274C Failed",showNotification("Check error: "+p.message,"error")}setTimeout(()=>{T.textContent="\u{1F50D} Check for Updates",T.disabled=!1},3e3)}async function C(){try{N.innerHTML='<div class="panel-empty"><span class="brand-spinner"></span> Loading...</div>';const v=await(await fetch("/api/v1/updates/history?limit=50")).json(),o=v.success&&v.history?v.history:[];if(o.length===0){N.innerHTML='<div class="panel-empty"><span class="empty-icon">\u{1F4CB}</span>No update history yet.</div>';return}let s='<table style="width: 100%; border-collapse: collapse; font-size: 0.82rem;">';s+='<tr style="border-bottom: 1px solid var(--border); color: var(--muted);"><th style="padding: 6px; text-align: left;">When</th><th style="padding: 6px; text-align: left;">Container</th><th style="padding: 6px; text-align: left;">Image</th><th style="padding: 6px; text-align: left;">Duration</th><th style="padding: 6px; text-align: left;">Status</th></tr>';for(const u of o){const l=u.status==="success",g=u.duration?u.duration<1e3?u.duration+"ms":Math.round(u.duration/1e3)+"s":"-";s+='<tr style="border-bottom: 1px solid var(--border);">',s+=`<td style="padding: 6px; color: var(--muted);">${timeAgo(u.timestamp)}</td>`,s+=`<td style="padding: 6px; font-weight: 500;">${escapeHtml(u.containerName)}</td>`,s+=`<td style="padding: 6px; color: var(--muted);">${escapeHtml(u.imageName)}</td>`,s+=`<td style="padding: 6px;">${g}</td>`,s+=`<td style="padding: 6px;"><span style="color: ${l?"var(--ok-fg)":"var(--bad-fg)"};">${l?"\u2713 success":"\u2717 failed"}</span></td>`,s+="</tr>",!l&&u.error&&(s+=`<tr><td colspan="5" style="padding: 4px 6px 8px; font-size: 0.78rem; color: var(--bad-fg);">${escapeHtml(u.error)}</td></tr>`)}s+="</table>",N.innerHTML=s}catch(p){N.innerHTML=`<div class="panel-empty" style="color: var(--bad-fg);">Failed: ${escapeHtml(p.message)}</div>`}}async function H(){try{D.innerHTML='<div class="panel-empty"><span class="brand-spinner"></span> Loading...</div>';const v=await(await fetch("/api/v1/stats/containers")).json(),o=v.success&&v.stats?v.stats:[];if(o.length===0){D.innerHTML='<div class="panel-empty"><span class="empty-icon">\u{1F916}</span>No running containers found.</div>';return}let s='<table style="width: 100%; border-collapse: collapse; font-size: 0.85rem;">';s+='<tr style="border-bottom: 1px solid var(--border); color: var(--muted);"><th style="padding: 8px; text-align: left;">Container</th><th style="padding: 8px; text-align: left;">Schedule</th><th style="padding: 8px; text-align: left;">Auto-Rollback</th><th style="padding: 8px; text-align: right;">Actions</th></tr>';for(const u of o){const l=u.name||u.Names?.[0]?.replace(/^\//,"")||u.Id?.substring(0,12),g=u.containerId||u.Id;s+=`<tr style="border-bottom: 1px solid var(--border);" data-container-id="${escapeHtml(g)}">`,s+=`<td style="padding: 8px; font-weight: 500;">${escapeHtml(l)}</td>`,s+=`<td style="padding: 8px;">
<select class="auto-schedule" data-id="${escapeHtml(g)}" style="padding: 4px 8px; border-radius: 4px; border: 1px solid var(--border); background: var(--bg); color: var(--fg); font-size: 0.82rem;">
<option value="">Disabled</option>
<option value="daily">Daily</option>
<option value="weekly">Weekly</option>
<option value="monthly">Monthly</option>
</select></td>`,s+=`<td style="padding: 8px;"><input type="checkbox" class="auto-rollback" data-id="${escapeHtml(g)}" checked /></td>`,s+=`<td style="padding: 8px; text-align: right;"><button class="save-auto-btn" data-id="${escapeHtml(g)}" data-name="${escapeHtml(l)}" style="padding: 4px 10px; font-size: 0.78rem;">Save</button></td>`,s+="</tr>"}s+="</table>",D.innerHTML=s,D.querySelectorAll(".save-auto-btn").forEach(u=>{u.addEventListener("click",async()=>{const l=u.dataset.id,g=u.closest("tr"),I=g.querySelector(".auto-schedule").value,w=g.querySelector(".auto-rollback").checked;u.textContent="Saving...",u.disabled=!0;try{const R=await(await secureFetch(`/api/v1/updates/auto-update/${encodeURIComponent(l)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({enabled:!!I,schedule:I||"weekly",autoRollback:w})})).json();if(R.success)u.textContent="\u2713 Saved";else throw new Error(R.error)}catch(M){u.textContent="\u2717 Error",showNotification("Save error: "+M.message,"error")}setTimeout(()=>{u.textContent="Save",u.disabled=!1},2e3)})})}catch(p){D.innerHTML=`<div class="panel-empty" style="color: var(--bad-fg);">Failed: ${escapeHtml(p.message)}</div>`}}const x=document.getElementById("dashcaddy-current-version"),O=document.getElementById("dashcaddy-update-badge"),z=document.getElementById("dashcaddy-update-details"),S=document.getElementById("dashcaddy-new-version"),E=document.getElementById("dashcaddy-changelog"),k=document.getElementById("dashcaddy-apply-btn"),b=document.getElementById("dashcaddy-check-btn"),m=document.getElementById("dashcaddy-rollback-btn"),f=document.getElementById("dashcaddy-status-bar"),c=document.getElementById("dashcaddy-history-container");let d=null;function a(p,v){f&&(f.style.display="block",f.style.background=v==="error"?"var(--bad-bg)":v==="success"?"var(--ok-bg)":"var(--bg)",f.style.color=v==="error"?"var(--bad-fg)":v==="success"?"var(--ok-fg)":"var(--fg)",f.textContent=p)}async function n(){try{const v=await(await fetch("/api/v1/system/version")).json();v.success&&(x.textContent="v"+v.version+(v.commit?" ("+v.commit.substring(0,7)+")":""))}catch{x.textContent="Unable to fetch version"}}async function e(p){p||(b.textContent="Checking...",b.disabled=!0);try{const o=await(await fetch("/api/v1/system/update-check")).json();if(d=o,o.success&&o.available&&o.remote){O.style.display="",z.style.display="",S.textContent="v"+o.remote.version,E.textContent=o.remote.changelog||"No changelog available.";const s=document.getElementById("updates-btn");if(s&&!s.querySelector(".update-dot")){const l=document.createElement("span");l.className="update-dot",l.style.cssText="position:absolute;top:2px;right:2px;width:8px;height:8px;border-radius:50%;background:var(--accent);",s.style.position="relative",s.appendChild(l)}const u=document.getElementById("updates-dashcaddy-tab");if(u&&!u.querySelector(".update-dot")){const l=document.createElement("span");l.className="update-dot",l.style.cssText="display:inline-block;width:6px;height:6px;border-radius:50%;background:var(--accent);margin-left:4px;vertical-align:middle;",u.appendChild(l)}}else O.style.display="none",z.style.display="none",p||a("You are running the latest version.","success");p||(b.textContent="Check for Updates",b.disabled=!1)}catch(v){p||(a("Failed to check: "+v.message,"error"),b.textContent="Check for Updates",b.disabled=!1)}}async function t(){if(confirm("Apply DashCaddy update? The API container will restart.")){k.textContent="Updating...",k.disabled=!0,a("Downloading and applying update...","info");try{const v=await(await secureFetch("/api/v1/system/update-apply",{method:"POST"})).json();if(v.success)a("Update initiated: v"+(v.fromVersion||"?")+" \u2192 v"+(v.toVersion||"?")+". The container will restart shortly.","success"),k.textContent="Applied!",document.querySelectorAll(".update-dot").forEach(o=>o.remove());else throw new Error(v.error||"Update failed")}catch(p){a("Update failed: "+p.message,"error"),k.textContent="Update Now",k.disabled=!1}}}async function i(){try{const v=await(await fetch("/api/v1/system/update-history")).json(),o=v.success&&v.history?v.history:[];if(o.length===0){c.innerHTML='<div class="panel-empty"><span class="empty-icon">\u{1F4E6}</span>No self-update history.</div>';return}let s='<table style="width: 100%; border-collapse: collapse; font-size: 0.82rem;">';s+='<tr style="border-bottom: 1px solid var(--border); color: var(--muted);"><th style="padding: 6px; text-align: left;">When</th><th style="padding: 6px; text-align: left;">Version</th><th style="padding: 6px; text-align: left;">From</th><th style="padding: 6px; text-align: left;">Status</th></tr>';for(const u of o){const l=u.status==="success"?"\u2713 success":u.status==="pending"?"\u23F3 pending":u.status==="partial"?"\u26A0 partial":"\u2717 "+u.status,g=u.status==="success"?"var(--ok-fg)":u.status==="pending"?"var(--muted)":"var(--bad-fg)";s+='<tr style="border-bottom: 1px solid var(--border);">',s+='<td style="padding: 6px; color: var(--muted);">'+timeAgo(u.timestamp)+"</td>",s+='<td style="padding: 6px; font-weight: 500;">v'+escapeHtml(u.version)+(u.rollback?" (rollback)":"")+"</td>",s+='<td style="padding: 6px; color: var(--muted);">v'+escapeHtml(u.fromVersion||"?")+"</td>",s+='<td style="padding: 6px;"><span style="color: '+g+';">'+l+"</span></td>",s+="</tr>",u.error&&(s+='<tr><td colspan="4" style="padding: 4px 6px 8px; font-size: 0.78rem; color: var(--bad-fg);">'+escapeHtml(u.error)+"</td></tr>"),u.note&&(s+='<tr><td colspan="4" style="padding: 4px 6px 8px; font-size: 0.78rem; color: var(--muted);">'+escapeHtml(u.note)+"</td></tr>")}s+="</table>",c.innerHTML=s}catch(p){c.innerHTML='<div class="panel-empty" style="color: var(--bad-fg);">Failed: '+escapeHtml(p.message)+"</div>"}}async function r(){try{const v=await(await fetch("/api/v1/system/rollback-versions")).json(),o=v.success&&v.versions?v.versions:[];if(o.length===0){showNotification("No rollback versions available.","info");return}const s=prompt(`Available rollback versions:
`+o.join(`
`)+`
Enter version to rollback to:`);if(!s)return;if(!o.includes(s)){showNotification("Invalid version: "+s,"error");return}if(!confirm("Rollback DashCaddy to v"+s+"? The container will restart."))return;a("Rolling back to v"+s+"...","info");const l=await(await secureFetch("/api/v1/system/rollback",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({version:s})})).json();if(l.success)a("Rollback to v"+s+" initiated. Container will restart.","success");else throw new Error(l.error||"Rollback failed")}catch(p){a("Rollback failed: "+p.message,"error")}}b?.addEventListener("click",()=>e(!1)),k?.addEventListener("click",t),m?.addEventListener("click",r),T?.addEventListener("click",P),h?.addEventListener("click",()=>{y?.classList.add("show"),$()}),wireModal(y,L),document.querySelector('[data-panel="updates-history"]')?.addEventListener("click",C),document.querySelector('[data-panel="updates-auto"]')?.addEventListener("click",H),document.querySelector('[data-panel="updates-dashcaddy"]')?.addEventListener("click",()=>{n(),i(),d||e(!0)}),setTimeout(()=>e(!0),5e3)})(),(function(){injectModal("audit-modal",`<div id="audit-modal" class="weather-modal">
<div class="weather-modal-content" style="min-width: 850px; max-width: 1050px;">
<h3>\u{1F4DC} Audit Log</h3>
<p class="modal-subtitle">
Track all actions performed through the API.
</p>
<div style="display: flex; gap: 12px; margin-bottom: 16px; align-items: center;">
<label class="text-muted-sm">Filter:</label>
<select id="audit-filter" style="padding: 6px 10px; border-radius: 6px; border: 1px solid var(--border); background: var(--bg); color: var(--fg); font-size: 0.85rem;">
<option value="">All Actions</option>
<option value="service">Services</option>
<option value="container">Containers</option>
<option value="caddy">Caddy</option>
<option value="dns">DNS</option>
<option value="backup">Backups</option>
<option value="config">Config</option>
<option value="auth">Auth</option>
</select>
<button id="audit-refresh-btn" class="btn-sm">\u{1F504} Refresh</button>
<span style="flex: 1;"></span>
<button id="audit-clear-btn" style="padding: 6px 12px; font-size: 0.8rem; color: var(--bad-fg); border-color: var(--bad-fg);">\u{1F5D1}\uFE0F Clear Log</button>
</div>
<div id="audit-log-container" class="scroll-container">
<div class="panel-empty"><span class="brand-spinner"></span> Loading audit log...</div>
</div>
<div style="margin-top: 12px; text-align: center;">
<button id="audit-load-more" style="display: none; padding: 6px 16px; font-size: 0.8rem;">Load More</button>
</div>
<div class="weather-modal-buttons modal-footer-bar">
<button id="audit-cancel">Close</button>
</div>
</div>
</div>`);const y=document.getElementById("audit-modal"),h=document.getElementById("audit-log-btn"),L=document.getElementById("audit-cancel"),T=document.getElementById("audit-refresh-btn"),B=document.getElementById("audit-clear-btn"),N=document.getElementById("audit-filter"),D=document.getElementById("audit-log-container"),A=document.getElementById("audit-load-more");let $=0;const P=50;async function C(H){try{H||($=0,D.innerHTML='<div class="panel-empty"><span class="brand-spinner"></span> Loading...</div>');const x=N.value;let O=`/api/v1/audit-logs?limit=${P}&offset=${$}`;x&&(O+=`&action=${encodeURIComponent(x)}`);const S=await(await fetch(O)).json(),E=S.success&&S.entries?S.entries:[];if(E.length===0&&!H){D.innerHTML='<div class="panel-empty"><span class="empty-icon">\u{1F4DC}</span>No audit log entries yet. Actions will be logged automatically.</div>',A.style.display="none";return}let k="";H||(k='<table style="width: 100%; border-collapse: collapse; font-size: 0.82rem;">',k+='<tr style="border-bottom: 1px solid var(--border); color: var(--muted);"><th style="padding: 6px; text-align: left;">When</th><th style="padding: 6px; text-align: left;">IP</th><th style="padding: 6px; text-align: left;">Action</th><th style="padding: 6px; text-align: left;">Resource</th><th style="padding: 6px; text-align: left;">Result</th></tr>');for(const b of E){const m=b.outcome==="success";k+='<tr style="border-bottom: 1px solid var(--border); cursor: pointer;" class="audit-row">',k+=`<td style="padding: 6px; color: var(--muted);">${timeAgo(b.timestamp)}</td>`,k+=`<td style="padding: 6px; font-family: monospace; font-size: 0.78rem;">${escapeHtml(b.ip||"-")}</td>`,k+=`<td style="padding: 6px; font-weight: 500;">${escapeHtml(b.action||"-")}</td>`,k+=`<td style="padding: 6px;">${escapeHtml(b.resource||"-")}</td>`,k+=`<td style="padding: 6px;"><span style="color: ${m?"var(--ok-fg)":"var(--bad-fg)"};">${m?"\u2713":"\u2717"}</span></td>`,k+="</tr>",b.details&&Object.keys(b.details).length>0&&(k+=`<tr class="audit-detail" style="display: none;"><td colspan="5" style="padding: 6px 6px 10px; font-size: 0.78rem; color: var(--muted);"><pre style="margin: 0; white-space: pre-wrap; font-family: monospace;">${escapeHtml(JSON.stringify(b.details,null,2))}</pre></td></tr>`)}if(!H)k+="</table>",D.innerHTML=k;else{const b=D.querySelector("table");b&&b.insertAdjacentHTML("beforeend",k)}$+=E.length,A.style.display=E.length>=P?"":"none",D.querySelectorAll(".audit-row").forEach(b=>{b.dataset.wired||(b.dataset.wired="true",b.addEventListener("click",()=>{const m=b.nextElementSibling;m&&m.classList.contains("audit-detail")&&(m.style.display=m.style.display==="none"?"":"none")}))})}catch(x){D.innerHTML=`<div class="panel-empty" style="color: var(--bad-fg);">Failed: ${escapeHtml(x.message)}</div>`}}h?.addEventListener("click",()=>{y?.classList.add("show"),C(!1)}),wireModal(y,L),T?.addEventListener("click",()=>C(!1)),N?.addEventListener("change",()=>C(!1)),A?.addEventListener("click",()=>C(!0)),B?.addEventListener("click",async()=>{if(confirm("Clear the entire audit log? This cannot be undone."))try{const x=await(await secureFetch("/api/v1/audit-logs",{method:"DELETE"})).json();x.success?C(!1):showNotification("Error: "+(x.error||"Clear failed"),"error")}catch(H){showNotification("Error: "+H.message,"error")}})})(),(function(){injectModal("weather-modal",`<div id="weather-modal" class="weather-modal"><div class="weather-modal-content"><h3>Weather Settings</h3>
<label for="weather-location-input">Location:</label>
<input type="text" id="weather-location-input" placeholder="City name or ZIP (e.g., Hamburg, 90210)" maxlength="100">
<div style="font-size: 0.78rem; color: var(--muted); margin-top: 4px;">Enter a city name, postal code, or &ldquo;City, Country&rdquo;</div>
<div style="margin-top: 14px; padding-top: 12px; border-top: 1px solid var(--border);">
<label style="display: block; margin-bottom: 8px; font-weight: 600; color: var(--fg);">Units</label>
<div style="display: flex; gap: 8px;">
<label class="weather-unit-option"><input type="radio" name="weather-unit-radio" value="imperial"><span class="weather-unit-card">&deg;F / mph</span></label>
<label class="weather-unit-option"><input type="radio" name="weather-unit-radio" value="metric"><span class="weather-unit-card">&deg;C / km/h</span></label>
</div>
</div>
<div class="weather-modal-buttons"><button id="weather-cancel">Cancel</button><button id="weather-save">Save</button></div></div></div>`);const y="weather-location",h="weather-zip",L="weather-geo",T="weather-unit";!safeGet(y)&&safeGet(h)&&safeSet(y,safeGet(h));function B(){return safeGet(T)||"imperial"}function N(){return{icon:document.querySelector(".weather-icon"),temp:document.querySelector(".weather-temp"),condition:document.querySelector(".weather-condition"),location:document.querySelector(".weather-location"),wind:document.querySelector(".weather-wind")}}const D={0:"Clear sky",1:"Mainly clear",2:"Partly cloudy",3:"Overcast",45:"Fog",48:"Rime fog",51:"Light drizzle",53:"Drizzle",55:"Dense drizzle",56:"Freezing drizzle",57:"Dense freezing drizzle",61:"Light rain",63:"Moderate rain",65:"Heavy rain",66:"Light freezing rain",67:"Heavy freezing rain",71:"Light snow",73:"Moderate snow",75:"Heavy snow",77:"Snow grains",80:"Light showers",81:"Moderate showers",82:"Violent showers",85:"Light snow showers",86:"Heavy snow showers",95:"Thunderstorm",96:"Thunderstorm with hail",99:"Severe thunderstorm"},A={0:"\u2600\uFE0F",1:"\u{1F324}\uFE0F",2:"\u26C5",3:"\u2601\uFE0F",45:"\u{1F32B}\uFE0F",48:"\u{1F32B}\uFE0F",51:"\u{1F326}\uFE0F",53:"\u{1F326}\uFE0F",55:"\u{1F326}\uFE0F",56:"\u{1F328}\uFE0F",57:"\u{1F328}\uFE0F",61:"\u{1F326}\uFE0F",63:"\u{1F327}\uFE0F",65:"\u{1F327}\uFE0F",66:"\u{1F328}\uFE0F",67:"\u{1F328}\uFE0F",71:"\u{1F328}\uFE0F",73:"\u2744\uFE0F",75:"\u2744\uFE0F",77:"\u2744\uFE0F",80:"\u{1F326}\uFE0F",81:"\u{1F327}\uFE0F",82:"\u{1F327}\uFE0F",85:"\u{1F328}\uFE0F",86:"\u2744\uFE0F",95:"\u26C8\uFE0F",96:"\u26C8\uFE0F",99:"\u26C8\uFE0F"},$=["N","NNE","NE","ENE","E","ESE","SE","SSE","S","SSW","SW","WSW","W","WNW","NW","NNW"];function P(E){return $[Math.round(E/22.5)%16]}async function C(E){const k=safeGet(L);if(k)try{const d=JSON.parse(k);if(d.query===E)return d}catch{}const b=await fetch(`https://geocoding-api.open-meteo.com/v1/search?name=${encodeURIComponent(E)}&count=1&language=en&format=json`);if(!b.ok)throw new Error("Geocoding failed");const m=await b.json();if(!m.results||!m.results.length)throw new Error("Location not found");const f=m.results[0],c={query:E,lat:f.latitude,lon:f.longitude,city:f.name,state:f.admin1||"",country:f.country||"",countryCode:f.country_code||""};return safeSet(L,JSON.stringify(c)),c}function H(E){return E.countryCode==="US"&&E.state?`${E.city}, ${E.state}`:E.country?`${E.city}, ${E.country}`:E.city}async function x(E){try{const k=await C(E),b=B(),m=b==="metric"?"celsius":"fahrenheit",f=b==="metric"?"kmh":"mph",c=`https://api.open-meteo.com/v1/forecast?latitude=${k.lat}&longitude=${k.lon}&current=temperature_2m,weather_code,wind_speed_10m,wind_direction_10m&temperature_unit=${m}&wind_speed_unit=${f}`,d=await fetch(c);if(!d.ok)throw new Error("Weather fetch failed");const n=(await d.json()).current,e=n.weather_code;return{temp:Math.round(n.temperature_2m),condition:D[e]||"Unknown",icon:A[e]||"\u{1F324}\uFE0F",locationStr:H(k),windSpeed:Math.round(n.wind_speed_10m),windDir:P(n.wind_direction_10m),unit:b}}catch(k){return console.warn("Weather fetch failed:",k),null}}async function O(){const E=N();if(!E.icon||!E.temp||!E.condition||!E.location||!E.wind){console.warn("Weather widget elements not found");return}const k=safeGet(y);if(!k){E.location.textContent="Set Location",E.temp.textContent="--\xB0",E.condition.textContent="Click \u2699\uFE0F to configure",E.wind.textContent="--",E.icon.innerHTML='<span class="weather-emoji">\u{1F324}\uFE0F</span>';return}try{const b=await x(k);if(b){const m=b.unit==="metric"?"\xB0C":"\xB0F",f=b.unit==="metric"?"km/h":"mph";E.location.textContent=b.locationStr,E.temp.textContent=`${b.temp}${m}`,E.condition.textContent=b.condition,E.wind.textContent=`Wind: ${b.windSpeed} ${f} ${b.windDir}`,E.icon.innerHTML=`<span class="weather-emoji">${escapeHtml(b.icon)}</span>`}}catch(b){console.error("Weather update error:",b),E.location.textContent="Weather Error",E.temp.textContent="Error",E.condition.textContent="Failed to load",E.wind.textContent="--"}}const z=document.getElementById("weather-modal"),S=document.getElementById("weather-location-input");document.getElementById("weather-settings")?.addEventListener("click",()=>{S.value=safeGet(y)||"";const E=B(),k=z.querySelector(`input[name="weather-unit-radio"][value="${E}"]`);k&&(k.checked=!0),z.classList.add("show"),S.focus()}),document.getElementById("weather-cancel")?.addEventListener("click",()=>{z.classList.remove("show")}),document.getElementById("weather-save")?.addEventListener("click",()=>{const E=S.value.trim();if(E){safeGet(y)!==E&&safeSet(L,""),safeSet(y,E);const b=z.querySelector('input[name="weather-unit-radio"]:checked'),m=b?b.value:"imperial",f=B();safeSet(T,m),f!==m&&safeSet(L,""),z.classList.remove("show"),O()}else showNotification("Please enter a location (e.g., Hamburg, London, 90210)","warning")}),wireModal(z),document.addEventListener("keydown",E=>{E.key==="Escape"&&z.classList.contains("show")&&z.classList.remove("show")}),O(),setInterval(O,DC.POLL.WEATHER)})(),(function(){const y=document.getElementById("clock-widget"),h=document.getElementById("clock-render");if(!y||!h)return;const L=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],T=["January","February","March","April","May","June","July","August","September","October","November","December"],B=["XII","I","II","III","IV","V","VI","VII","VIII","IX","X","XI"];let N=safeGet("clock-style")||"default",D=-1,A=!1,$="",P="",C=null,H=null;function x(o){if(A||safeGet("clock-chimes")!=="true")return;A=!0;const s=parseInt(safeGet("clock-chime-volume")||"50",10)/100;let u=0;function l(){if(u>=o){A=!1;return}const g=new Audio("/assets/sounds/church-bell.mp3");g.volume=s,g.play().catch(()=>{}),u++,u<o?setTimeout(l,2500):setTimeout(()=>{A=!1},2500)}l()}function O(o){return L[o.getDay()]+", "+T[o.getMonth()]+" "+o.getDate()+", "+o.getFullYear()}function z(){P="",C=null}function S(){return P!=="digital"&&(h.innerHTML='<div class="clock-time"><span class="clock-main"></span><span class="clock-seconds"></span><span class="clock-ampm"></span></div><div class="clock-date"></div>',C={main:h.querySelector(".clock-main"),seconds:h.querySelector(".clock-seconds"),ampm:h.querySelector(".clock-ampm"),date:h.querySelector(".clock-date")},P="digital"),C}function E(o){const s=o.getHours(),u=o.getMinutes(),l=o.getSeconds(),g=s>=12?"PM":"AM",I=s%12||12,w=S();w.main.textContent=`${I}:${String(u).padStart(2,"0")}`,w.seconds.textContent=`:${String(l).padStart(2,"0")}`,w.ampm.textContent=g,w.date.textContent=O(o)}function k(o,s){const u=o.getHours(),l=o.getMinutes(),g=o.getSeconds(),I=u>=12?"PM":"AM",w=u%12||12,M=S();M.main.textContent=`${String(w).padStart(2,"0")}:${String(l).padStart(2,"0")}`,M.seconds.textContent=`:${String(g).padStart(2,"0")}`,M.ampm.textContent=I,M.date.textContent=O(o)}function b(o){const s=o.getHours(),u=o.getMinutes(),l=o.getSeconds(),g=s>=12?"PM":"AM",I=s%12||12,w=String(I).padStart(2," ")+String(u).padStart(2,"0")+String(l).padStart(2,"0");let M='<div class="flip-clock-row">';if(M+=m(w[0],0),M+=m(w[1],1),M+='<span class="flip-colon">:</span>',M+=m(w[2],2),M+=m(w[3],3),M+='<span class="flip-colon">:</span>',M+=m(w[4],4),M+=m(w[5],5),M+=`<span class="flip-ampm">${g}</span>`,M+="</div>",M+=`<div class="clock-date">${O(o)}</div>`,h.innerHTML=M,P="flip",$){for(let R=0;R<6;R++)if(w[R]!==$[R]){const q=h.querySelector(`.flip-card[data-idx="${R}"]`);q&&q.classList.add("flipping")}}$=w}function m(o,s){const u=o===" "?"":o;return`<div class="flip-card" data-idx="${s}"><div class="flip-top">${u}</div><div class="flip-bottom">${u}</div></div>`}function f(o){const s=o.getHours(),u=o.getMinutes(),l=o.getSeconds(),g=s%12||12,I=s>=12?"PM":"AM",w=[Math.floor(g/10),g%10,Math.floor(u/10),u%10,Math.floor(l/10),l%10];let M='<div class="binary-clock">';M+='<div class="binary-labels"><span>H</span><span>H</span><span>M</span><span>M</span><span>S</span><span>S</span></div>';for(let R=3;R>=0;R--){M+='<div class="binary-row">';for(let q=0;q<6;q++){const _=w[q]>>R&1;M+=`<div class="binary-dot ${_?"on":""}"></div>`}M+="</div>"}M+='<div class="binary-values">';for(let R=0;R<6;R++)M+=`<span>${w[R]}</span>`;M+="</div>",M+=`<div class="binary-ampm">${I}</div>`,M+="</div>",M+=`<div class="clock-date">${O(o)}</div>`,h.innerHTML=M,P="binary"}function c(o,s){const u=o.getHours(),l=o.getMinutes(),g=o.getSeconds(),I=120,w=I/2,M=I/2,R=g/60*360-90,q=(l+g/60)/60*360-90,_=(u%12+l/60)/12*360-90;let W="";for(let K=1;K<=12;K++){const Q=K/12*2*Math.PI-Math.PI/2,te=47,ne=w+te*Math.cos(Q),X=M+te*Math.sin(Q),oe=s?B[K%12]:K;W+=`<text x="${ne}" y="${X}" text-anchor="middle" dominant-baseline="central" fill="var(--fg)" font-size="${s?"7":"9"}" font-weight="600" font-family="'Sami Grotesk',sans-serif">${oe}</text>`}let j="";for(let K=0;K<60;K++){const Q=K/60*2*Math.PI-Math.PI/2,te=56,ne=K%5===0?52:54,X=w+ne*Math.cos(Q),oe=M+ne*Math.sin(Q),ie=w+te*Math.cos(Q),ae=M+te*Math.sin(Q),F=K%5===0?1.5:.5;j+=`<line x1="${X}" y1="${oe}" x2="${ie}" y2="${ae}" stroke="var(--muted)" stroke-width="${F}" stroke-linecap="round"/>`}const V=`<svg class="analog-clock-svg" viewBox="0 0 ${I} ${I}" width="${I}" height="${I}">
<circle cx="${w}" cy="${M}" r="58" fill="none" stroke="var(--border)" stroke-width="2"/>
${j}
${W}
<line x1="${w}" y1="${M}" x2="${w+28*Math.cos(_*Math.PI/180)}" y2="${M+28*Math.sin(_*Math.PI/180)}" stroke="var(--fg)" stroke-width="3" stroke-linecap="round"/>
<line x1="${w}" y1="${M}" x2="${w+38*Math.cos(q*Math.PI/180)}" y2="${M+38*Math.sin(q*Math.PI/180)}" stroke="var(--fg)" stroke-width="2" stroke-linecap="round"/>
<line x1="${w}" y1="${M}" x2="${w+42*Math.cos(R*Math.PI/180)}" y2="${M+42*Math.sin(R*Math.PI/180)}" stroke="#e74c3c" stroke-width="1" stroke-linecap="round"/>
<circle cx="${w}" cy="${M}" r="3" fill="var(--fg)"/>
</svg>`,se=o.getHours()>=12?"PM":"AM";h.innerHTML=`<div class="analog-clock-wrap">${V}<div class="analog-info"><span class="analog-digital">${o.getHours()%12||12}:${String(l).padStart(2,"0")} ${se}</span><span class="analog-date-sm">${O(o)}</span></div></div>`,P="analog"}function d(){const o=new Date,s=o.getHours()%12||12,u=o.getMinutes(),l=o.getSeconds(),g="clock-widget"+(N!=="default"?" "+N:"");switch(y.className!==g&&(y.className=g),N){case"lcd":k(o);break;case"lcd-blue":k(o);break;case"lcd-amber":k(o);break;case"lcd-retro":k(o);break;case"lcd-taxi":k(o);break;case"flip":b(o);break;case"binary":f(o);break;case"analog":c(o,!1);break;case"roman":c(o,!0);break;default:E(o)}u===0&&l===0&&s!==D&&(D=s,x(s)),u!==0&&(D=-1)}function a(){clearTimeout(H);const o=document.hidden?6e4:1e3,s=o-Date.now()%o+25;H=setTimeout(()=>{d(),a()},s)}document.addEventListener("visibilitychange",()=>{$="",z(),d(),a()}),d(),a();const n=[{id:"default",label:"Default",icon:"\u{1F550}"},{id:"lcd",label:"LCD Green",icon:"\u{1F49A}"},{id:"lcd-blue",label:"LCD Blue",icon:"\u{1F499}"},{id:"lcd-amber",label:"LCD Amber",icon:"\u{1F7E0}"},{id:"lcd-retro",label:"LCD Retro",icon:"\u{1F7E9}"},{id:"lcd-taxi",label:"LCD Taxi",icon:"\u{1F7E1}"},{id:"flip",label:"Flip Clock",icon:"\u{1F4DF}"},{id:"binary",label:"Binary",icon:"\u{1F4BB}"},{id:"analog",label:"Analog",icon:"\u23F0"},{id:"roman",label:"Roman",icon:"\u{1F3DB}\uFE0F"}];let e='<div class="clock-style-grid">';n.forEach(o=>{e+=`<label class="clock-style-option">
<input type="radio" name="clock-style-radio" value="${o.id}">
<span class="clock-style-card"><span class="clock-style-icon">${o.icon}</span><span class="clock-style-label">${o.label}</span></span>
</label>`}),e+="</div>",injectModal("clock-settings-modal",`<div id="clock-settings-modal" class="weather-modal">
<div class="weather-modal-content" style="max-width: 420px;">
<h3>Clock Settings</h3>
<div style="margin-bottom: 16px;">
<label style="display: block; margin-bottom: 8px; font-weight: 600; color: var(--fg);">Style</label>
${e}
</div>
<div style="margin-bottom: 16px; padding-top: 12px; border-top: 1px solid var(--border);">
<label style="display: flex; align-items: center; gap: 8px; cursor: pointer; font-weight: 600; color: var(--fg);">
<input type="checkbox" id="clock-chimes-toggle"> Hourly church bell chimes
</label>
<div style="font-size: 0.78rem; color: var(--muted); margin-top: 4px; margin-left: 24px;">
Strikes the number of the hour (e.g., 3 bells at 3:00)
</div>
</div>
<div style="margin-bottom: 16px;" id="clock-volume-section">
<label style="display: block; margin-bottom: 6px; font-weight: 600; color: var(--fg);">Volume</label>
<div style="display: flex; align-items: center; gap: 10px;">
<span style="font-size: 0.85rem;">\u{1F508}</span>
<input type="range" id="clock-chime-volume" min="0" max="100" value="50" style="flex: 1; accent-color: var(--ok-fg);">
<span style="font-size: 0.85rem;">\u{1F50A}</span>
<button id="clock-chime-test" style="padding: 4px 10px; font-size: 0.78rem; border-radius: 4px; cursor: pointer;">Test</button>
</div>
</div>
<div class="weather-modal-buttons">
<button id="clock-settings-cancel">Cancel</button>
<button id="clock-settings-save">Save</button>
</div>
</div>
</div>`);const t=document.getElementById("clock-settings-modal"),i=document.getElementById("clock-chimes-toggle"),r=document.getElementById("clock-chime-volume"),p=document.getElementById("clock-volume-section");function v(){const o=safeGet("clock-style")||"default",s=t.querySelector(`input[value="${o}"]`);s&&(s.checked=!0),i.checked=safeGet("clock-chimes")==="true",r.value=safeGet("clock-chime-volume")||"50",p.style.opacity=i.checked?"1":"0.4"}i?.addEventListener("change",()=>{p.style.opacity=i.checked?"1":"0.4"}),document.getElementById("clock-settings")?.addEventListener("click",()=>{v(),t.classList.add("show")}),document.getElementById("clock-chime-test")?.addEventListener("click",()=>{const o=parseInt(r.value,10)/100,s=new Audio("/assets/sounds/church-bell.mp3");s.volume=o,s.play().catch(()=>{})}),document.getElementById("clock-settings-save")?.addEventListener("click",()=>{const o=t.querySelector('input[name="clock-style-radio"]:checked'),s=o?o.value:"default";safeSet("clock-style",s),safeSet("clock-chimes",String(i.checked)),safeSet("clock-chime-volume",r.value),N=s,$="",z(),d(),a(),t.classList.remove("show"),showNotification("Clock settings saved","success",2e3)}),document.getElementById("clock-settings-cancel")?.addEventListener("click",()=>{t.classList.remove("show")}),wireModal(t),t?.querySelectorAll('input[name="clock-style-radio"]').forEach(o=>{o.addEventListener("change",()=>{N=o.value,$="",z(),d()})})})(),(function(){async function y(){try{const D=await(await fetch("/api/v1/health-checks/status")).json();if(!D.success||!D.status)return;for(const[A,$]of Object.entries(D.status)){const P=document.getElementById("uptime-"+A),C=document.getElementById("uptime-bar-"+A);if(!P)continue;const H=$.uptime?.["24h"];if(H!=null){const x=H.toFixed(1);P.textContent=`${x}% uptime`,P.className="uptime-chip",H>=99.9?P.classList.add("excellent"):H>=99?P.classList.add("good"):H>=95?P.classList.add("degraded"):P.classList.add("poor"),C&&(C.style.width=x+"%")}}}catch{console.warn("[Card Badges] Health check API unavailable")}}let h;try{h=new Set(JSON.parse(safeSessionGet("dismissed-updates")||"[]"))}catch{h=new Set}async function L(){try{const D=await(await fetch("/api/v1/updates/available")).json();if(!D.success||(document.querySelectorAll(".update-available-badge").forEach(A=>A.classList.remove("visible")),!D.updates?.length))return;for(const A of D.updates){const $=window.APPS||[];for(const P of $)if(P.containerId===A.containerId||P.id===A.containerName||P.name===A.containerName){if(h.has(P.id))break;const C=document.getElementById("update-badge-"+P.id);C&&(C.classList.add("visible"),C.title=`Image digest changed. Click to dismiss if already up to date.
${A.imageName||""}`,C.style.cursor="pointer",C.onclick=H=>{H.stopPropagation(),C.classList.remove("visible"),h.add(P.id),safeSessionSet("dismissed-updates",JSON.stringify([...h]))});break}}}catch{console.warn("[Card Badges] Updates API unavailable")}}function T(){setTimeout(()=>{y(),L()},5e3),setInterval(()=>{y(),L()},6e4)}const B=window.refreshAll;B&&(window.refreshAll=async function(){try{await B(),setTimeout(y,1e3)}catch(N){console.warn("[Card Badges] Error in refreshAll hook:",N.message)}}),T()})(),(function(){var y=null,h=null,L={},T={dark:"Dark",light:"Light",blue:"Blue",black:"Black",nord:"Nord",dracula:"Dracula","solarized-dark":"Solarized Dark","solarized-light":"Solarized Light",taxi:"Taxi",ocean:"Ocean"},B=[["bg","Background","base"],["card-base","Card","base"],["fg","Text","base"],["muted","Muted Text","base"],["border","Border","base"],["accent","Accent","accent"],["accent-strong","Accent Strong","accent"],["ok-bg","OK Background","status"],["ok-fg","OK Text","status"],["bad-bg","Error Bg","status"],["bad-fg","Error Text","status"],["dot-ok","Dot OK","status"],["dot-bad","Dot Error","status"],["uptime","Uptime Bar","status"],["hover","Hover","advanced"],["card-hover","Card Hover","advanced"],["base","Tags/Badges","advanced"],["fg-muted","Dim Text","advanced"],["success","Success","advanced"],["error","Error","advanced"],["warning","Warning","advanced"]],N=document.getElementById("theme");if(!N)return;var D=document.getElementById("theme-label");function A(l){if(T[l])return T[l];var g=safeGetJSON(window.USER_THEMES_KEY,{});return g[l]&&g[l].name||l}function $(){D&&(D.textContent=A(window.getActiveTheme()))}N.addEventListener("click",function(){var l=window.THEMES.slice(),g=window.getActiveTheme(),I=l.indexOf(g),w=l[(I+1)%l.length];window.applyTheme(w),$()}),$();function P(){var l={base:"Base Colors",accent:"Accent",status:"Status",advanced:"Advanced (auto-derived)"},g={};B.forEach(function(w){g[w[2]]||(g[w[2]]=[]),g[w[2]].push(w)});var I="";return Object.keys(l).forEach(function(w){w==="advanced"?(I+='<div id="theme-builder-advanced-toggle" class="theme-builder-advanced-toggle" style="margin:12px 0 4px;cursor:pointer;color:var(--accent);font-size:.85rem;user-select:none;">Show advanced colors &#9660;</div>',I+='<div id="theme-builder-advanced" class="theme-builder-section" style="display:none;">'):I+='<div class="theme-builder-section">',I+='<div class="theme-builder-section-title">'+l[w]+"</div>",(g[w]||[]).forEach(function(M){I+='<div class="theme-builder-row"><span class="theme-builder-label">'+M[1]+'</span><input type="color" class="theme-builder-color" data-prop="'+M[0]+'"'+(w==="advanced"?' data-advanced="1"':"")+' value="#000000" /><span class="theme-builder-hex" data-hex="'+M[0]+'">#000000</span></div>'}),I+="</div>"}),I}function C(){return window.THEMES.map(function(l){return'<option value="'+l+'">'+A(l)+"</option>"}).join("")}var H='<div id="theme-builder-modal" class="weather-modal"><div class="weather-modal-content" style="min-width:420px;max-width:560px;"><h3>Theme Builder</h3><div id="theme-builder-existing" style="margin-bottom:16px;display:none;"><label style="font-size:.85rem;color:var(--muted);margin-right:8px;">Edit:</label><select id="theme-builder-edit-select" style="padding:6px 10px;background:var(--card-bg);color:var(--fg);border:1px solid var(--border);border-radius:6px;font-size:.85rem;margin-right:8px;"><option value="">\u2014 New Theme \u2014</option></select><button id="theme-builder-delete" style="padding:4px 10px;background:color-mix(in srgb,var(--bad-fg) 15%,transparent);border:1px solid var(--bad-fg);color:var(--bad-fg);border-radius:6px;font-size:.8rem;cursor:pointer;">Delete</button></div><div style="margin-bottom:16px;"><label style="font-size:.85rem;color:var(--muted);margin-right:8px;">Name:</label><input type="text" id="theme-builder-name" maxlength="20" placeholder="My Theme" style="padding:6px 10px;background:var(--card-bg);color:var(--fg);border:1px solid var(--border);border-radius:6px;font-size:.85rem;width:140px;" /></div><div style="margin-bottom:16px;display:flex;align-items:center;"><label style="font-size:.85rem;color:var(--muted);margin-right:8px;cursor:pointer;" for="theme-builder-lightbg"><input type="checkbox" id="theme-builder-lightbg" style="margin-right:6px;cursor:pointer;vertical-align:middle;" />Light background (use dark logo)</label></div><div style="margin-bottom:16px;"><label style="font-size:.85rem;color:var(--muted);margin-right:8px;">Start from:</label><select id="theme-builder-start" style="padding:6px 10px;background:var(--card-bg);color:var(--fg);border:1px solid var(--border);border-radius:6px;font-size:.85rem;">'+C()+'</select></div><div class="theme-builder-preview" id="theme-builder-preview"><div class="theme-builder-card" id="theme-preview-card"><div class="preview-title">Sample Card</div><div class="preview-muted">Secondary text preview</div><div class="preview-badges"><span class="preview-badge" id="preview-badge-ok">ON</span><span class="preview-badge" id="preview-badge-bad">OFF</span></div><div class="preview-dots"><span><span class="preview-dot" id="preview-dot-ok"></span> Online</span><span><span class="preview-dot" id="preview-dot-bad"></span> Offline</span></div><button class="preview-btn" id="preview-accent-btn">Accent Button</button></div></div>'+P()+'<div class="weather-modal-buttons"><button id="theme-builder-cancel">Cancel</button><button id="theme-builder-import" style="margin-left:auto;" title="Import theme from JSON file">Import</button><button id="theme-builder-export" title="Export theme as JSON file">Export</button><button id="theme-builder-save" class="btn-accent">Save Theme</button></div></div></div>';injectModal("theme-builder-modal",H);var x=document.getElementById("theme-builder-modal"),O=document.getElementById("theme-builder-start"),z=document.getElementById("theme-builder-name"),S=document.getElementById("theme-builder-edit-select"),E=document.getElementById("theme-builder-existing"),k=document.getElementById("theme-builder-lightbg"),b=x.querySelectorAll(".theme-builder-color"),m=document.getElementById("theme-builder-advanced"),f=document.getElementById("theme-builder-advanced-toggle"),c=document.getElementById("theme-builder-export"),d=!1;f.addEventListener("click",function(){d=!d,m.style.display=d?"":"none",f.innerHTML=d?"Hide advanced colors &#9650;":"Show advanced colors &#9660;"});function a(){var l={};return b.forEach(function(g){l[g.dataset.prop]=g.value}),l["card-bg"]=l["card-base"],l}function n(){var l={};return b.forEach(function(g){g.dataset.advanced||(l[g.dataset.prop]=g.value)}),l["card-bg"]=l["card-base"],k.checked&&(l.lightBg=!0),l}function e(){var l=n(),g=window.deriveExtendedColors?window.deriveExtendedColors(l):{};b.forEach(function(I){if(I.dataset.advanced&&!L[I.dataset.prop]){var w=g[I.dataset.prop]||"#333333";I.value=w;var M=x.querySelector('[data-hex="'+I.dataset.prop+'"]');M&&(M.textContent=w.toUpperCase())}})}function t(l){var g=window.THEME_COLORS[l];g&&(L={},b.forEach(function(I){var w=g[I.dataset.prop]||"#000000";(w.startsWith("rgba")||w.startsWith("color-mix"))&&(w="#333333"),I.value=w;var M=x.querySelector('[data-hex="'+I.dataset.prop+'"]');M&&(M.textContent=w.toUpperCase())}),k.checked=!!g.lightBg,r())}function i(l){var g=safeGetJSON(window.USER_THEMES_KEY,{}),I=g[l];I&&(L={},b.forEach(function(w){var M=I[w.dataset.prop]||"#000000";w.value=M;var R=x.querySelector('[data-hex="'+w.dataset.prop+'"]');R&&(R.textContent=M.toUpperCase()),w.dataset.advanced&&I[w.dataset.prop]&&(L[w.dataset.prop]=!0)}),z.value=I.name||"",k.checked=!!I.lightBg,e(),r())}function r(){var l=a(),g=document.getElementById("theme-builder-preview"),I=document.getElementById("theme-preview-card"),w=I.querySelector(".preview-title"),M=I.querySelector(".preview-muted"),R=document.getElementById("preview-badge-ok"),q=document.getElementById("preview-badge-bad"),_=document.getElementById("preview-dot-ok"),W=document.getElementById("preview-dot-bad"),j=document.getElementById("preview-accent-btn"),V=I.querySelector(".preview-dots");g.style.background=l.bg,I.style.background=l["card-base"],I.style.borderColor=l.border,w.style.color=l.fg,M.style.color=l.muted,R.style.background=l["ok-bg"],R.style.color=l["ok-fg"],q.style.background=l["bad-bg"],q.style.color=l["bad-fg"],_.style.background=l["dot-ok"],W.style.background=l["dot-bad"],V.style.color=l.fg,j.style.background=l.accent,j.style.color=l.bg}function p(l){var g=window.deriveExtendedColors?window.deriveExtendedColors(l):{};window.THEME_PROPS.forEach(function(I){var w=l[I]||g[I];w&&document.documentElement.style.setProperty("--"+I,w)})}b.forEach(function(l){l.addEventListener("input",function(){var g=x.querySelector('[data-hex="'+l.dataset.prop+'"]');g&&(g.textContent=l.value.toUpperCase()),l.dataset.advanced?L[l.dataset.prop]=!0:e(),r(),p(a())})}),k.addEventListener("change",function(){e(),r(),p(a())}),O.addEventListener("change",function(){L={},t(O.value),p(a())});function v(){var l=safeGetJSON(window.USER_THEMES_KEY,{}),g=Object.keys(l);S.innerHTML='<option value="">\u2014 New Theme \u2014</option>',g.forEach(function(I){var w=document.createElement("option");w.value=I,w.textContent=l[I].name||I,S.appendChild(w)}),E.style.display=g.length?"":"none"}function o(){O.innerHTML=C()}S.addEventListener("change",function(){var l=this.value;l?(h=l,i(l),p(a())):(h=null,L={},z.value="",O.value=window.getActiveTheme(),t(O.value)),c.style.display=h?"":"none"});function s(){y=window.getActiveTheme(),h=null,L={},d=!1,m.style.display="none",f.innerHTML="Show advanced colors &#9660;",v(),o();var l=safeGetJSON(window.USER_THEMES_KEY,{});l[y]?(S.value=y,h=y,i(y)):(S.value="",z.value="",O.value=y,t(y)),c.style.display=h?"":"none",x.classList.add("show")}var u=document.getElementById("theme-customize-btn");u&&u.addEventListener("click",function(){s()}),document.getElementById("theme-builder-save").addEventListener("click",function(){var l=a(),g=z.value.trim();if(!g){showNotification("Please enter a theme name","warning",3e3),z.focus();return}var I=safeGetJSON(window.USER_THEMES_KEY,{}),w,M=null;if(h){w=h;var R=window.slugifyThemeName(g,h);if(R!==h){M=h,delete I[h];var q=window.THEMES.indexOf(h);q!==-1&&window.THEMES.splice(q,1),delete window.THEME_COLORS[h],w=R}}else w=window.slugifyThemeName(g);var _={name:g};k.checked&&(_.lightBg=!0),window.THEME_PROPS.forEach(function(j){l[j]&&(_[j]=l[j])}),I[w]=_,safeSet(window.USER_THEMES_KEY,JSON.stringify(I)),window.clearCustomProperties(),window.injectUserThemeStyles(),window.applyTheme(w),x.classList.remove("show"),$();var W={};window.THEME_PROPS.forEach(function(j){l[j]&&(W[j]=l[j])}),M&&secureFetch("/api/v1/themes/"+M,{method:"DELETE"}).catch(function(){}),secureFetch("/api/v1/themes/"+w,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:g,colors:W,lightBg:k.checked})}).then(function(){showNotification(g+" theme saved","success",3e3)}).catch(function(){showNotification(g+" theme saved locally (server sync failed)","warning",3e3)})}),document.getElementById("theme-builder-cancel").addEventListener("click",function(){x.classList.remove("show"),window.clearCustomProperties(),y&&window.applyTheme(y)}),document.getElementById("theme-builder-delete").addEventListener("click",function(){if(h){var l=safeGetJSON(window.USER_THEMES_KEY,{}),g=l[h]?l[h].name:h;if(confirm('Delete "'+g+'" theme?')){var I=h;delete l[I],safeSet(window.USER_THEMES_KEY,JSON.stringify(l));var w=window.THEMES.indexOf(I);w!==-1&&window.THEMES.splice(w,1),delete window.THEME_COLORS[I],window.clearCustomProperties(),window.injectUserThemeStyles();var M=y&&y!==I?y:"dark";window.applyTheme(M),h=null,x.classList.remove("show"),$(),secureFetch("/api/v1/themes/"+I,{method:"DELETE"}).then(function(){showNotification(g+" theme deleted","success",3e3)}).catch(function(){showNotification(g+" theme deleted locally (server sync failed)","warning",3e3)})}}}),document.getElementById("theme-builder-export").addEventListener("click",function(){if(!h){showNotification("Save the theme first, then export","warning",3e3);return}var l=safeGetJSON(window.USER_THEMES_KEY,{}),g=l[h];if(g){var I={_dashcaddy_theme:!0,version:"1.0",exportDate:new Date().toISOString(),slug:h,name:g.name,lightBg:g.lightBg||!1,colors:{}};window.THEME_PROPS.forEach(function(q){g[q]&&(I.colors[q]=g[q])});var w=new Blob([JSON.stringify(I,null,2)],{type:"application/json"}),M=URL.createObjectURL(w),R=document.createElement("a");R.href=M,R.download=h+"-theme.json",document.body.appendChild(R),R.click(),document.body.removeChild(R),URL.revokeObjectURL(M),showNotification("Theme exported as "+h+"-theme.json","success",3e3)}}),document.getElementById("theme-builder-import").addEventListener("click",function(){var l=document.createElement("input");l.type="file",l.accept=".json",l.onchange=function(g){var I=g.target.files[0];if(I){var w=new FileReader;w.onload=function(M){try{var R=JSON.parse(M.target.result),q,_,W;if(R._dashcaddy_theme&&R.colors)q=R.name||"Imported",_=R.colors,W=R.lightBg||!1;else if(R.name&&(R.bg||R["card-base"]))q=R.name,_={},window.THEME_PROPS.forEach(function(j){R[j]&&(_[j]=R[j])}),W=R.lightBg||!1;else throw new Error("Not a valid DashCaddy theme file");z.value=q,k.checked=!!W,h=null,S.value="",L={},b.forEach(function(j){var V=_[j.dataset.prop]||"#000000";j.value=V;var se=x.querySelector('[data-hex="'+j.dataset.prop+'"]');se&&(se.textContent=V.toUpperCase()),j.dataset.advanced&&_[j.dataset.prop]&&(L[j.dataset.prop]=!0)}),e(),r(),p(a()),c.style.display="none",showNotification('"'+q+'" loaded into builder. Click Save to keep it.',"success",5e3)}catch(j){showNotification("Import failed: "+j.message,"error",5e3)}},w.readAsText(I)}},l.click()}),wireModal(x),x.addEventListener("click",function(l){l.target===x&&(window.clearCustomProperties(),y&&window.applyTheme(y))})})(),(function(){injectModal("license-modal",`<div id="license-modal" class="weather-modal">
<div class="weather-modal-content" style="min-width: 420px; max-width: 520px;">
<h3>DashCaddy License</h3>
<p style="font-size: 0.85rem; color: var(--muted); margin: 0 0 16px;">
Activate a license code to unlock premium features.
</p>
<div id="license-status-section" style="margin-bottom: 16px;">
<div id="license-badge" style="display: inline-flex; align-items: center; gap: 6px; padding: 6px 14px; border-radius: 20px; font-size: 0.85rem; font-weight: 600; margin-bottom: 12px;">
<span id="license-badge-icon"></span>
<span id="license-badge-text"></span>
</div>
<div id="license-details" style="font-size: 0.85rem; color: var(--muted); line-height: 1.6;"></div>
</div>
<div id="license-activate-section">
<label class="form-label-bold">License Code:</label>
<input type="text" id="license-code-input" placeholder="DC-XXXXX-XXXXX-XXXXX-XXXXX-XXXXX"
maxlength="35" spellcheck="false" autocomplete="off"
style="width: 100%; padding: 10px 12px; border: 1px solid var(--border); border-radius: 4px; background: var(--card-bg); color: var(--fg); font-size: 1rem; font-family: monospace; letter-spacing: 1px;" />
<p class="tiny-hint">Enter your license code to activate premium features</p>
</div>
<div id="license-features" style="margin-top: 16px;">
<label class="form-label-bold" style="margin-bottom: 8px; display: block;">Premium Features:</label>
<div id="license-feature-list" style="display: grid; gap: 8px;"></div>
</div>
<div id="license-error" style="display: none; margin-top: 12px; padding: 10px; border-radius: 4px; background: rgba(231,76,60,0.15); color: var(--bad-fg); font-size: 0.85rem;"></div>
<div id="license-success" style="display: none; margin-top: 12px; padding: 10px; border-radius: 4px; background: rgba(46,204,113,0.15); color: var(--ok-fg); font-size: 0.85rem;"></div>
<div class="weather-modal-buttons" style="margin-top: 16px;">
<button id="license-cancel">Close</button>
<button id="license-deactivate" class="btn-accent" style="display: none; background: var(--bad-bg); border-color: var(--bad-fg); color: var(--bad-fg);">Deactivate</button>
<button id="license-activate" class="btn-accent">Activate</button>
</div>
</div>
</div>`);const y=document.getElementById("license-modal"),h=document.getElementById("license-code-input"),L=document.getElementById("license-activate"),T=document.getElementById("license-deactivate"),B=document.getElementById("license-error"),N=document.getElementById("license-success"),D=document.getElementById("license-badge-icon"),A=document.getElementById("license-badge-text"),$=document.getElementById("license-badge"),P=document.getElementById("license-details"),C=document.getElementById("license-feature-list"),H=document.getElementById("license-activate-section");let x=null;function O(){B.style.display="none",N.style.display="none"}function z(a){O(),B.textContent=a,B.style.display="block"}function S(a){O(),N.textContent=a,N.style.display="block"}function E(a){if(x=a,a.active){$.style.background="rgba(46,204,113,0.15)",$.style.color="var(--ok-fg)",D.textContent="\u2605",A.textContent="Premium Active";const t=a.lifetime?"<div>License: <strong>LIFETIME</strong></div>":`<div>Expires: <strong>${new Date(a.expiresAt).toLocaleDateString()}</strong> (${a.daysRemaining} days remaining)</div>`;P.innerHTML=`
<div>Code: <code style="font-family: monospace;">${a.code||"***"}</code></div>
${t}
`,H.style.display="none",L.style.display="none",T.style.display=""}else $.style.background="rgba(149,165,166,0.15)",$.style.color="var(--muted)",D.textContent="\u2606",A.textContent=a.expired?"License Expired":"Free Tier",P.innerHTML=a.expired?"<div>Your license has expired. Enter a new code to renew.</div>":"<div>Enter a license code to unlock premium features.</div>",H.style.display="",L.style.display="",T.style.display="none";const n=a.premiumFeatures||{},e=new Set(a.features||[]);C.innerHTML=Object.entries(n).map(([t,i])=>`<div style="display: flex; align-items: center; gap: 8px; padding: 8px 12px; border-radius: 6px; background: var(--card-bg); border: 1px solid var(--border);">
<span style="font-size: 1.1rem;">${e.has(t)?"\u2705":"\u{1F512}"}</span>
<div>
<div style="font-weight: 600; font-size: 0.9rem;">${i.name}</div>
<div style="font-size: 0.78rem; color: var(--muted);">${i.description}</div>
</div>
</div>`).join("")}async function k(){try{const n=await(await fetch("/api/v1/license/status")).json();n.success&&(E(n.license),f(n.license))}catch(a){console.warn("Failed to load license status:",a.message)}}async function b(){const a=h.value.trim();if(!a){z("Please enter a license code.");return}O(),L.disabled=!0,L.textContent="Activating...";try{const e=await(await secureFetch("/api/v1/license/activate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:a})})).json();e.success?(S(e.message),h.value="",E(e.license),showNotification("License activated! Premium features unlocked.","success",5e3),f(e.license)):z(e.error||"Activation failed")}catch(n){z("Network error: "+n.message)}finally{L.disabled=!1,L.textContent="Activate"}}async function m(){if(confirm("Deactivate your license? You can reuse the code on another machine.")){T.disabled=!0,T.textContent="Deactivating...";try{const n=await(await secureFetch("/api/v1/license/deactivate",{method:"POST"})).json();n.success?(S(n.message),await k(),showNotification("License deactivated.","info",3e3),f({active:!1})):z(n.error||"Deactivation failed")}catch(a){z("Network error: "+a.message)}finally{T.disabled=!1,T.textContent="Deactivate"}}}function f(a){const n=document.getElementById("license-status-topbar"),e=document.getElementById("license-topbar-icon"),t=document.getElementById("license-topbar-text"),i=document.getElementById("license-topbar-time");if(n)if(n.className="license-status-topbar "+(a.active?"premium":"free"),a.active)if(e.textContent="\u2605",t.textContent="PREMIUM",a.lifetime)i.textContent="\xB7 LIFETIME";else{const r=a.daysRemaining;i.textContent=r!=null?"\xB7 "+r+"d remaining":""}else e.textContent="\u2606",t.textContent=a.expired?"EXPIRED":"FREE TIER",i.textContent=""}function c(){O(),k(),y.classList.add("show")}h.addEventListener("input",function(){let a=this.value.toUpperCase().replace(/[^A-Z0-9-]/g,"");if(a.length>this._prevLength&&(a=a.replace(/-/g,""),a.length>2&&!a.startsWith("DC")&&(a="DC"+a),a.startsWith("DC")&&a.length>2)){const n=["DC"],e=a.substring(2);for(let t=0;t<e.length;t+=5)n.push(e.substring(t,t+5));a=n.join("-")}this._prevLength=a.length,this.value=a}),L.addEventListener("click",b),T.addEventListener("click",m),h.addEventListener("keydown",a=>{a.key==="Enter"&&b()}),wireModal(y,document.getElementById("license-cancel"));const d=document.getElementById("license-status-topbar");d&&d.addEventListener("click",()=>window.openLicenseModal&&window.openLicenseModal()),window.openLicenseModal=c,window.checkPremiumFeature=async function(a){try{return(await(await fetch(`/api/v1/license/feature/${a}`)).json()).available}catch{return!1}},k().then(a=>{x&&f(x)})})();