(function(){injectModal("logo-modal",`

Dashboard Settings

Customize your dashboard's appearance and system preferences.

Shown in browser tab and header (max 50 characters)


Separate logos for dark and light themes, or use the same for both.

Dark theme logo

Dark themes

Light theme logo

Light themes

Using default logos


Current favicon Using DashCaddy favicon

Upload PNG or SVG - automatically converted to ICO


Used by all deployed containers. Changes apply to new deployments.

`);const h=document.getElementById("logo-modal"),L=document.getElementById("logo-preview-dark"),A=document.getElementById("logo-preview-light"),I=document.getElementById("logo-status"),D=document.getElementById("logo-same-both"),R=document.getElementById("logo-dual-uploads"),H=document.getElementById("logo-single-upload"),P=document.getElementById("logo-upload-dark"),v=document.getElementById("logo-upload-light"),C=document.getElementById("logo-upload-single"),x=document.querySelector("#brand .brand-logo-dark"),$=document.querySelector("#brand .brand-logo-light"),E=document.querySelector(".top-row"),M=document.getElementById("dashboard-title"),S=DC.NAME;let B=null,U=null,T=null,b="left",N=S;D?.addEventListener("change",()=>{D.checked?(R.style.display="none",H.style.display="",B=null,U=null):(R.style.display="flex",H.style.display="none",T=null)});function O(t,e){if(!t||!t.type.startsWith("image/")){showNotification("Please select an image file","warning");return}const a=new FileReader;a.onload=o=>e(o.target.result),a.readAsDataURL(t)}P?.addEventListener("change",t=>{O(t.target.files[0],e=>{B=e,L.src=e,I.textContent="New dark logo ready to save"})}),v?.addEventListener("change",t=>{O(t.target.files[0],e=>{U=e,A.src=e,I.textContent="New light logo ready to save"})}),C?.addEventListener("change",t=>{O(t.target.files[0],e=>{T=e,L.src=e,A.src=e,I.textContent="New logo ready to save (both themes)"})});function p(t){E.setAttribute("data-logo-pos",t),document.querySelectorAll(".logo-pos-btn").forEach(e=>{e.style.background=e.dataset.pos===t?"var(--accent)":"var(--card-bg)",e.style.color=e.dataset.pos===t?"white":"var(--fg)"})}function u(t){N=t||S,document.title=N;const e=document.querySelector(".dashboard-title");e&&(e.textContent=N)}async function f(){try{const t=await fetch("/api/v1/logo");if(t.ok){const e=await t.json();e.customLogoDark&&(x.src=e.customLogoDark,L.src=e.customLogoDark),e.customLogoLight&&($.src=e.customLogoLight,A.src=e.customLogoLight),!e.customLogoDark&&!e.customLogoLight&&e.customLogo&&(x.src=e.customLogo,$.src=e.customLogo,L.src=e.customLogo,A.src=e.customLogo),e.isDefault||(I.textContent="Using custom logo"),e.position&&(b=e.position,p(e.position)),e.dashboardTitle&&u(e.dashboardTitle)}}catch(t){console.warn("Could not load custom logo:",t.message)}}document.querySelectorAll(".logo-pos-btn").forEach(t=>{t.addEventListener("click",()=>{b=t.dataset.pos,p(b)})}),document.getElementById("brand")?.addEventListener("click",()=>{B=null,U=null,T=null,P&&(P.value=""),v&&(v.value=""),C&&(C.value=""),D&&(D.checked=!1),R.style.display="flex",H.style.display="none",L.src=x.src,A.src=$.src;const t=x.src.includes("custom-logo")||$.src.includes("custom-logo");I.textContent=t?"Using custom logo":"Using default logos",p(b),M.value=N,h.classList.add("show")}),document.getElementById("logo-save")?.addEventListener("click",async()=>{try{const t=M.value.trim()||S,e={position:b,dashboardTitle:t};D?.checked&&T?(e.dataDark=T,e.dataLight=T):(B&&(e.dataDark=B),U&&(e.dataLight=U));const a=await secureFetch("/api/v1/logo",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(a.ok){const o=await a.json(),i="?t="+Date.now();o.pathDark&&(x.src=o.pathDark+i,L.src=o.pathDark+i),o.pathLight&&($.src=o.pathLight+i,A.src=o.pathLight+i),p(b),u(t),h.classList.remove("show")}else{const o=await a.json();showNotification("Failed to save: "+o.error,"error")}}catch(t){showNotification("Error saving: "+t.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&&(x.src="/assets/dashcaddy-logo-dark.png",$.src="/assets/dashcaddy-logo-light.png",L.src="/assets/dashcaddy-logo-dark.png",A.src="/assets/dashcaddy-logo-light.png",I.textContent="Using default logos",B=null,U=null,T=null,M.value=S,u(S),b="left",p("left")),(await secureFetch("/api/v1/favicon",{method:"DELETE"})).ok){const a=document.querySelector('link[rel="icon"]'),o=document.getElementById("favicon-preview"),i=document.getElementById("favicon-status");a&&(a.href="/assets/dashcaddy-favicon.ico?t="+Date.now()),o&&(o.src="/assets/dashcaddy-favicon.ico?t="+Date.now()),i&&(i.textContent="Using DashCaddy favicon"),d=null}}catch(t){showNotification("Error resetting branding: "+t.message,"error")}}),wireModal(h,document.getElementById("logo-cancel"));const g=document.getElementById("favicon-preview"),z=document.getElementById("favicon-status"),r=document.getElementById("favicon-upload"),c=document.querySelector('link[rel="icon"]')||document.createElement("link");let d=null;document.querySelector('link[rel="icon"]')||(c.rel="icon",c.href="/assets/dashcaddy-favicon.ico",document.head.appendChild(c));async function w(){try{const t=await fetch("/api/v1/favicon");if(t.ok){const e=await t.json();e.customFavicon&&(c.href=e.customFavicon+"?t="+Date.now(),g.src=e.customFavicon+"?t="+Date.now(),z.textContent="Using custom favicon")}}catch(t){console.warn("Could not load custom favicon:",t.message)}}r?.addEventListener("change",t=>{const e=t.target.files[0];if(!e)return;if(!e.type.match(/^image\/(png|svg\+xml)$/)){showNotification("Please select a PNG or SVG file","warning"),r.value="";return}const a=new FileReader;a.onload=o=>{d=o.target.result,g.src=d,z.textContent="New favicon ready to save"},a.readAsDataURL(e)}),document.getElementById("logo-save")?.addEventListener("click",async()=>{if(d)try{const t=await secureFetch("/api/v1/favicon",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({data:d})});if(t.ok){const e=await t.json();c.href=e.path+"?t="+Date.now(),g.src=e.path+"?t="+Date.now(),z.textContent="Using custom favicon",d=null}else{const e=await t.json();showNotification("Failed to save favicon: "+e.error,"error")}}catch(t){showNotification("Error saving favicon: "+t.message,"error")}}),w(),f();const y=document.getElementById("settings-timezone");y&&(new MutationObserver(()=>{h.classList.contains("show")&&y.options.length===0&&(async()=>{let e;try{const a=await fetch("/api/v1/config");a.ok&&(e=(await a.json()).timezone)}catch{}window.populateTimezoneSelect(y,e)})()}).observe(h,{attributes:!0,attributeFilter:["class"]}),document.getElementById("logo-save")?.addEventListener("click",async()=>{const e=y.value;if(e)try{const a=await fetch("/api/v1/config");if(!a.ok)return;const o=await a.json();o.timezone=e,o.updatedAt=new Date().toISOString(),await secureFetch("/api/v1/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)})}catch(a){console.warn("Failed to save timezone:",a.message)}}))})(),window.populateTimezoneSelect=function(h,L){const A=Intl.supportedValuesOf("timeZone"),I=L||Intl.DateTimeFormat().resolvedOptions().timeZone||"UTC";h.innerHTML="";for(const D of A){const R=document.createElement("option");R.value=D,R.textContent=D.replace(/_/g," "),D===I&&(R.selected=!0),h.appendChild(R)}},(function(){let h="homelab",L=null;async function A(){try{const u=await fetch("/api/v1/config");if(u.ok&&(L=await u.json(),L&&L.setupComplete))return document.getElementById("setup-wizard").style.display="none",!0}catch(u){console.warn("Could not fetch server config, checking localStorage fallback:",u.message)}return safeGet("dashcaddy-setup")?(document.getElementById("setup-wizard").style.display="none",!0):(document.getElementById("setup-wizard").style.display="flex",!1)}A();const I=document.getElementById("setup-timezone");I&&window.populateTimezoneSelect(I);function D(p){document.querySelectorAll(".setup-step").forEach(f=>{f.style.display="none"});const u=document.getElementById(p);u&&(u.style.display="block")}function R(){const p=document.getElementById("setup-summary-content");if(!p)return;let u='
';if(h==="homelab"){const g=document.getElementById("setup-tld")?.value?.trim()||".home",z=document.getElementById("setup-ca-name")?.value?.trim()||"",r=document.getElementById("setup-dns-ip")?.value?.trim()||"",c=document.getElementById("setup-dns-port")?.value?.trim()||DC.DEFAULTS.DNS_PORT;u+=`

Home Lab Configuration

TLD: ${g}
Certificate Authority: ${z}
DNS Server: ${r}:${c}
Example URLs: https://uptime${g}, https://nextcloud${g}
`}else if(h==="simple"){const g=document.getElementById("setup-simple-ip")?.value?.trim()||"localhost";u+=`

Simple Setup

Access Method: IP:Port only
Default IP: ${g}
SSL: None (HTTP only)
Example URLs: http://${g}:8080, http://${g}:3000
`}else if(h==="public"){const g=document.getElementById("setup-public-domain")?.value?.trim()||"",z=document.getElementById("setup-public-email")?.value?.trim()||"",r=document.querySelector('input[name="routing-mode"]:checked')?.value||"subdirectory",c=r==="subdirectory"?`https://${g}/sonarr, https://${g}/grafana`:`https://sonarr.${g}, https://grafana.${g}`;u+=`

Public Server

Domain: ${g}
SSL: Let's Encrypt
Email: ${z}
Routing: ${r==="subdirectory"?"Subdirectory (domain.com/app)":"Subdomain (app.domain.com)"}
Example URLs: ${c}
`}const f=document.getElementById("setup-timezone")?.value||Intl.DateTimeFormat().resolvedOptions().timeZone||"UTC";u+=`
Timezone: ${f.replace(/_/g," ")}
`,u+="
",p.innerHTML=u,D("setup-step-summary")}async function H(p){try{const u=await secureFetch("/api/v1/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(p)});return u.ok?(await u.json(),!0):(errorHandler.logError("[SetupWizard] Save Config",new Error(`Server returned ${u.status}`),{function:"saveConfigToServer"}),!1)}catch(u){return errorHandler.logError("[SetupWizard] Save Config",u,{function:"saveConfigToServer"}),!1}}async function P(){const p={setupComplete:!0,configurationType:h,timestamp:new Date().toISOString(),timezone:document.getElementById("setup-timezone")?.value||Intl.DateTimeFormat().resolvedOptions().timeZone||"UTC"};if(h==="homelab"){p.tld=document.getElementById("setup-tld")?.value?.trim()||".home",p.caName=document.getElementById("setup-ca-name")?.value?.trim()||"";const z=document.getElementById("setup-dns-provider")?.value||"technitium";p.dns={provider:z,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()||""},p.defaults={dnsType:"private",sslType:"internal",targetIP:"localhost"}}else h==="simple"?(p.defaultIP=document.getElementById("setup-simple-ip")?.value?.trim()||"localhost",p.defaults={dnsType:"none",sslType:"none",targetIP:p.defaultIP}):h==="public"&&(p.domain=document.getElementById("setup-public-domain")?.value?.trim()||"",p.email=document.getElementById("setup-public-email")?.value?.trim()||"",p.routingMode=document.querySelector('input[name="routing-mode"]:checked')?.value||"subdirectory",p.defaults={dnsType:p.routingMode==="subdirectory"?"none":"public",sslType:"letsencrypt",targetIP:"localhost"});const u=await H(p);safeSet("dashcaddy-config",JSON.stringify(p)),safeSet("dashcaddy-setup","completed"),document.getElementById("setup-wizard").style.display="none";const f=h==="homelab"?"Professional Home Lab":h==="simple"?"Simple Setup":"Public Server",g=u?"server (shared across all devices)":"locally (this browser only)";showNotification(`Setup Complete! Configured for: ${f}. Settings saved to: ${g}`,"success",5e3),setTimeout(()=>location.reload(),500)}const v=document.getElementById("setup-step-1-next");v&&(v.onclick=function(p){p.preventDefault();const u=document.querySelector('input[name="config-type"]:checked');u&&(h=u.value),D(h==="homelab"?"setup-step-homelab":h==="simple"?"setup-step-simple":h==="public"?"setup-step-public":"setup-step-homelab")});const C=document.getElementById("setup-skip");C&&(C.onclick=async function(p){p.preventDefault(),confirm("Skip setup? You can run it later from Settings.")&&(await H({setupComplete:!0,skipped:!0,timestamp:new Date().toISOString()}),safeSet("dashcaddy-setup","skipped"),document.getElementById("setup-wizard").style.display="none")});const x=document.getElementById("setup-tld");x&&(x.oninput=function(p){const u=p.target.value||".home",f=document.getElementById("tld-preview"),g=document.getElementById("tld-preview-2");f&&(f.textContent=u),g&&(g.textContent=u)});const $=document.getElementById("setup-homelab-back");$&&($.onclick=function(p){p.preventDefault(),D("setup-step-1")});const E=document.getElementById("setup-homelab-next");E&&(E.onclick=function(p){p.preventDefault();const u=document.getElementById("setup-tld")?.value?.trim()||"",f=document.getElementById("setup-ca-name")?.value?.trim()||"",g=document.getElementById("setup-dns-ip")?.value?.trim()||"";if(!u||!u.startsWith(".")){showNotification("Please enter a valid TLD starting with a dot (e.g., .home)","warning");return}if(!f){showNotification("Please enter a Certificate Authority name","warning");return}if(!g){showNotification("Please enter your DNS server IP address","warning");return}R()});const M=document.getElementById("setup-simple-back");M&&(M.onclick=function(p){p.preventDefault(),D("setup-step-1")});const S=document.getElementById("setup-simple-next");S&&(S.onclick=function(p){p.preventDefault(),R()}),document.querySelectorAll('input[name="routing-mode"]').forEach(function(p){p.onchange=function(){var u=document.getElementById("dns-requirement-note");u&&(u.textContent=this.value==="subdirectory"?"Only one DNS record needed (for the main domain)":"You'll need to configure DNS manually for each subdomain")}});const B=document.getElementById("setup-public-back");B&&(B.onclick=function(p){p.preventDefault(),D("setup-step-1")});const U=document.getElementById("setup-public-next");U&&(U.onclick=function(p){p.preventDefault();const u=document.getElementById("setup-public-domain")?.value?.trim()||"",f=document.getElementById("setup-public-email")?.value?.trim()||"";if(!u){showNotification("Please enter your domain name","warning");return}if(!f||!f.includes("@")){showNotification("Please enter a valid email address","warning");return}R()});const T=document.getElementById("setup-summary-back");T&&(T.onclick=function(p){p.preventDefault(),h==="homelab"?D("setup-step-homelab"):h==="simple"?D("setup-step-simple"):h==="public"&&D("setup-step-public")});const b=document.getElementById("setup-summary-next");b&&(b.onclick=function(p){p.preventDefault(),D("setup-step-disk-safety")});const N=document.getElementById("setup-disk-safety-back");N&&(N.onclick=function(p){p.preventDefault(),D("setup-step-summary")});const O=document.getElementById("setup-disk-safety-finish");O&&(O.onclick=function(p){p.preventDefault(),P()}),window.getGlobalConfig=async function(){try{const u=await fetch("/api/v1/config");if(u.ok){const f=await u.json();if(f&&f.setupComplete)return f}}catch{console.warn("Could not fetch config from server")}const p=safeGet("dashcaddy-config");return p?JSON.parse(p):{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(){const h=new ErrorHandler;injectModal("app-selector-modal",`

Choose an App

`),injectModal("app-deploy-modal",`

Deploy Application

Your app will be available at: uptime.home
Checking Tailscale status...
\u2699\uFE0F Advanced Options
Use 'localhost' for same-host containers, or specific IP for remote services
Optional CPU and memory constraints. Leave at 0 for unlimited.
`);const L="custom-apps";let A=null,I=null;const D=document.getElementById("app-selector-modal"),R=document.getElementById("app-selector-grid");async function H(){try{const c=await(await fetch("/api/v1/apps/templates")).json();if(c.success)return A=c.templates,I=c.categories,!0}catch(r){h.logError("[AppSelector] Fetch Templates",r,{function:"fetchApiTemplates"})}return!1}async function P(r){try{return await(await fetch(`/api/v1/apps/ports/${r}/check`)).json()}catch(c){return h.logError("[AppSelector] Check Port",c,{function:"checkPortAvailability"}),{available:!0}}}async function v(r){try{const d=await(await fetch(`/api/v1/apps/ports/${r}/suggest`)).json();if(d.success)return d.suggestedPort}catch(c){h.logError("[AppSelector] Get Suggested Port",c,{function:"getSuggestedPort"})}return r}async function C(){if(R.innerHTML='
Loading app templates...
',!A&&!await H()){R.innerHTML='
Failed to load app templates. Please try again.
';return}R.innerHTML="";const r={};for(const[d,w]of Object.entries(A)){const y=w.category||"Other";r[y]||(r[y]=[]),r[y].push({id:d,...w})}const c=I?Object.keys(I):Object.keys(r).sort();for(const d of c){const w=r[d];if(!w||w.length===0)continue;w.sort((e,a)=>(a.popularity||0)-(e.popularity||0));const y=document.createElement("div");y.className="app-category-header";const t=I?.[d]||{};y.innerHTML=`${escapeHtml(t.icon||"")} ${escapeHtml(d)}`,t.color&&(y.style.borderBottomColor=t.color),R.appendChild(y),w.forEach(e=>{const a=document.createElement("div");a.className="app-option";const o=e.isDashboardWidget,i=o&&safeGet("widget-"+e.id+"-enabled")!=="false",n=o?`
${i?"ON":"OFF"}
`:"",s=!o&&e.difficulty?`
${escapeHtml(e.difficulty)}
`:"";a.innerHTML=`
${escapeHtml(e.icon||"\u{1F4E6}")}
${escapeHtml(e.name)}
${escapeHtml(e.description||"")}
${n}${s} `,o?a.onclick=()=>x(e,a):a.onclick=()=>$(e),R.appendChild(a)})}window.renderRecipeCards&&await window.renderRecipeCards(R)}function x(r,c){const d="widget-"+r.id+"-enabled",y=!(safeGet(d)!=="false");safeSet(d,String(y));const t=r.widgetSelector;if(t){const a=document.querySelector(t);a&&(a.style.display=y?"":"none")}const e=c.querySelector('div[style*="border-radius: 4px"]');e&&(e.textContent=y?"ON":"OFF",e.style.background=y?"#2ecc7130":"#e74c3c30",e.style.color=y?"#2ecc71":"#e74c3c"),showNotification(`${r.name} widget ${y?"enabled":"disabled"}`,"success",2e3)}async function $(r){const c=document.getElementById("app-deploy-modal"),d=document.getElementById("app-deploy-title"),w=document.getElementById("deploy-subdomain"),y=document.getElementById("deploy-url-preview"),t=document.getElementById("deploy-ip"),e=document.getElementById("deploy-port"),a=document.getElementById("deploy-tailscale-only"),o=document.getElementById("tailscale-status");try{const W=await(await secureFetch("/api/v1/apps/check-existing",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({appId:r.id})})).json();if(W.success&&W.exists){const V=W.container;confirm(`Found existing ${r.name} container: Container: ${V.name} Status: ${V.status} Port: ${V.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.`)&&(r._useExisting=!0,r._existingContainer=V)}}catch{}d.textContent=`Deploy ${r.name}`;const i=r.subdomain||r.id.replace(/-/g,"");w.value=i;const n=document.getElementById("subpath-compat-warning");if(n)if(SITE.routingMode==="subdirectory"){const G=r.subpathSupport||"strip";G==="none"?(n.style.display="block",n.innerHTML=''+r.name+" does not support subdirectory mode. It may not work correctly at a subpath."):G==="strip"?(n.style.display="block",n.innerHTML='ⓘ '+r.name+" has unverified subdirectory support. It may require additional configuration."):n.style.display="none"}else n.style.display="none";const s=SITE.defaults.dnsType||(SITE.configurationType==="public"?"public":"private"),l=SITE.defaults.sslType||(SITE.configurationType==="public"?"letsencrypt":"internal"),m=document.querySelector(`input[name="dns-type"][value="${s}"]`),k=document.querySelector(`input[name="ssl-type"][value="${l}"]`);m?m.checked=!0:document.querySelector('input[name="dns-type"][value="private"]').checked=!0,k?k.checked=!0:document.querySelector('input[name="ssl-type"][value="internal"]').checked=!0,t.value=SITE.defaults.targetIP||"localhost",a.checked=!1;const j=document.querySelector("#app-deploy-modal .flex-col-gap")?.closest("div"),_=document.querySelector("#app-deploy-modal details"),F=_?.querySelector("div");if(_&&F&&(SITE.configurationType==="public"||SITE.configurationType==="homelab")){const G=document.querySelectorAll('#app-deploy-modal input[name="dns-type"]')[0]?.closest("div.flex-col-gap")?.parentElement,W=document.querySelectorAll('#app-deploy-modal input[name="ssl-type"]')[0]?.closest("div.flex-col-gap")?.parentElement;G&&!G.dataset.moved&&(F.appendChild(G),G.dataset.moved="1"),W&&!W.dataset.moved&&(F.appendChild(W),W.dataset.moved="1")}const q=document.getElementById("media-path-section"),J=document.getElementById("deploy-media-path"),X=document.getElementById("media-path-description");if(r.mediaMount){q.style.display="block",J.value="",J.placeholder="/media/Movies, /media/TVShows or click Browse";const G=document.getElementById("detected-mounts-container"),W=document.getElementById("detected-mounts-list");try{const K=await(await fetch("/api/v1/media/detected-mounts")).json();if(K.success&&K.mounts.length>0){G.style.display="block",W.innerHTML="";const te=[...new Set(K.mounts.map(ee=>ee.hostPath))];J.value=te.join(", "),K.mounts.forEach(ee=>{const Z=document.createElement("button");Z.type="button";const de=te.includes(ee.hostPath);Z.style.cssText=`padding: 8px 14px; font-size: 0.85rem; background: color-mix(in srgb, var(--success) ${de?"40%":"15%"}, var(--card-bg)); border: 1px solid var(--success); border-radius: 6px; cursor: pointer; color: var(--fg);`,Z.innerHTML=`${escapeHtml(ee.folderName)}
from ${escapeHtml(ee.sourceImage)}`,Z.title=`${ee.hostPath} (from ${ee.sourceContainer})`,Z.onclick=()=>{const le=J.value.split(",").map(ce=>ce.trim()).filter(ce=>ce),pe=le.indexOf(ee.hostPath);pe>=0?(le.splice(pe,1),Z.style.background="color-mix(in srgb, var(--success) 15%, var(--card-bg))"):(le.push(ee.hostPath),Z.style.background="color-mix(in srgb, var(--success) 40%, var(--card-bg))"),J.value=le.join(", ")},W.appendChild(Z)})}else G.style.display="none"}catch{G.style.display="none"}document.getElementById("browse-media-btn").onclick=()=>{openFolderBrowser(J)}}else q.style.display="none",J.value="",document.getElementById("detected-mounts-container").style.display="none";const Q=document.getElementById("plex-claim-section");Q&&(r.id==="plex"||r.claimToken?(Q.style.display="block",document.getElementById("deploy-plex-claim").value=""):Q.style.display="none");const ne=document.getElementById("volume-mounts-section"),oe=document.getElementById("volume-mounts-list");if(oe.innerHTML="",r.docker?.volumes?.length){const G=r.mediaMount?.containerPath,W=r.docker.volumes.filter(V=>!V.includes("{{MEDIA_PATH}}")&&!(G&&V.endsWith(":"+G)));W.length>0?(ne.style.display="block",W.forEach((V,K)=>{const[te,ee]=V.split(":"),Z=document.createElement("div");Z.style.cssText="display: flex; gap: 6px; align-items: center;",Z.innerHTML=` \u2192 ${ee} `,oe.appendChild(Z),Z.querySelector(".vol-browse-btn").onclick=()=>{const de=Z.querySelector(".vol-host-path");openFolderBrowser(de)}})):ne.style.display="none"}else ne.style.display="none";const se=r.defaultPort||8080;e.value="",e.placeholder=`Default: ${se}`;let Y=document.getElementById("deploy-port-status");Y||(Y=document.createElement("div"),Y.id="deploy-port-status",Y.style.cssText="font-size: 0.8rem; margin-top: 4px;",e.parentNode.appendChild(Y));async function ie(){const G=e.value||se;Y.innerHTML='Checking port...';const W=await P(G);if(W.available)Y.innerHTML=`Port ${escapeHtml(String(G))} is available`;else{const V=await v(se);Y.innerHTML=` Port ${escapeHtml(G)} in use by ${escapeHtml(W.conflict?.usedBy||"unknown")} `;const K=document.createElement("button");K.type="button",K.textContent=`Use ${V}`,K.style.cssText="margin-left: 8px; padding: 2px 8px; font-size: 0.75rem; cursor: pointer;",K.onclick=()=>{document.getElementById("deploy-port").value=V,Y.innerHTML=`Using suggested port ${escapeHtml(String(V))}`},Y.appendChild(K)}}let re;e.oninput=function(){clearTimeout(re),re=setTimeout(ie,500)},ie();try{const W=await(await fetch("/api/v1/tailscale/status")).json();W.success&&W.installed&&W.connected?o.innerHTML=` Connected ${W.self?.hostname} (${W.self?.ip}) | ${W.deviceCount} devices `:W.installed?o.innerHTML='Not connected':(o.innerHTML='Not available',a.disabled=!0)}catch{o.innerHTML='Could not check status'}function ae(){const G=w.value||"subdomain",W=document.querySelector('input[name="dns-type"]:checked').value,V=document.querySelector('input[name="ssl-type"]:checked').value;let K="";if(SITE.routingMode==="subdirectory"&&SITE.domain)K=`https://${SITE.domain}/${G}`;else if(W==="private")K=`${V==="none"?"http":"https"}://${buildDomain(G)}`;else if(W==="public"){const te=V==="none"?"http":"https",ee=SITE.domain||G;K=SITE.domain?`${te}://${G}.${SITE.domain}`:`${te}://${G}`}else{const te=e.value||r.defaultPort||DC.DEFAULTS.SERVICE_PORT;K=`http://${t.value}:${te}`}y.textContent=K}w.oninput=ae,t.oninput=ae,e.oninput=ae,document.querySelectorAll('input[name="dns-type"]').forEach(G=>{G.onchange=ae}),document.querySelectorAll('input[name="ssl-type"]').forEach(G=>{G.onchange=ae}),ae(),D.classList.remove("show"),c.classList.add("show"),c.dataset.appTemplate=JSON.stringify(r)}async function E(r){const c=r.appTemplate,d=safeGetJSON(L,[]),w=c._useExisting&&c._existingContainer,y=d.find(t=>t.id===r.subdomain);if(!(y&&!w&&!confirm(`An app with subdomain "${r.subdomain}" already exists. Redeploy?`))){if(y){const t=d.indexOf(y);d.splice(t,1),safeSet(L,JSON.stringify(d))}if(w)r.port=c._existingContainer.primaryPort;else{const t=r.port||c.defaultPort||8080;showNotification(`Checking port ${t} availability...`,"info",0);const e=await P(t);if(!e.available){const a=await v(c.defaultPort||8080);if(confirm(`Port ${t} is already in use by ${e.conflict?.usedBy||"another container"}. Would you like to use port ${a} instead?`))r.port=a;else{showNotification("Deployment cancelled - port conflict","error",5e3);return}}}showNotification(w?`Configuring ${c.name} with existing container...`:`Deploying ${c.name}...`,"info",0);try{const t={appId:c.id,config:{subdomain:r.subdomain,ip:r.ip,createDns:r.dnsType==="private",port:r.port||c.defaultPort||null,sslType:r.sslType,dnsType:r.dnsType,tailscaleOnly:r.tailscaleOnly||!1,mediaPath:r.mediaPath||null,plexClaimToken:r.plexClaimToken||null,customVolumes:r.customVolumes||null}};w&&(t.config.useExisting=!0,t.config.existingContainerId=c._existingContainer.id,t.config.existingPort=c._existingContainer.primaryPort,!r.port&&c._existingContainer.primaryPort&&(t.config.port=c._existingContainer.primaryPort));const a=await(await secureFetch("/api/v1/apps/deploy",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})).json();if(a.success){const o={id:r.subdomain,name:c.name,logo:`/assets/${c.id}.png`,containerId:a.containerId,url:a.url,ip:r.ip,appTemplate:c.id,tailscaleOnly:r.tailscaleOnly||!1};d.push(o),safeSet(L,JSON.stringify(d)),window.APPS&&!window.APPS.some(n=>n.id===c.id)&&(window.APPS.push(o),typeof window.buildGrid=="function"&&window.buildGrid(),typeof window.refreshAll=="function"&&setTimeout(()=>window.refreshAll(),500));let i=a.usedExisting?`${c.name} configured with existing container! URL: ${a.url}`:`${c.name} deployed successfully! URL: ${a.url}`;a.warning&&(i+=` \u26A0 Warning: ${a.warning}`),showNotification(i,"success",8e3),delete c._useExisting,delete c._existingContainer,a.url&&a.url.startsWith("https://")&&M(a.url,c.name),a.setupInstructions&&a.setupInstructions.length>0&&setTimeout(()=>{const n=a.setupInstructions.join(` `);showNotification(`Setup Instructions for ${c.name}: ${n}`,"info",1e4)},1e3)}else throw new Error(a.error||"Deployment failed")}catch(t){h.logError("[AppSelector] Deployment",t,{function:"deploy"}),showNotification(`Failed to deploy ${c.name}: ${t.message}`,"error",8e3)}}}async function M(r,c){showNotification(`\u23F3 Generating SSL certificate for ${c}...`,"warning",6e4);let d=0;const w=12,y=async()=>{d++;try{const t=await fetch(r,{method:"HEAD",mode:"no-cors"});return showNotification(`\u2705 ${c} is ready! SSL certificate generated.`,"success",5e3),!0}catch{return d{window.APPS.some(d=>d.id===c.id)||window.APPS.push(c)})}document.getElementById("add-service-btn")?.addEventListener("click",()=>{C(),D.classList.add("show")}),wireModal(D,document.getElementById("app-selector-cancel"));const B=document.getElementById("app-deploy-modal");document.getElementById("app-deploy-cancel")?.addEventListener("click",()=>{B.classList.remove("show")}),document.getElementById("app-deploy-confirm")?.addEventListener("click",()=>{const r=JSON.parse(B.dataset.appTemplate),c=document.getElementById("deploy-media-path").value.trim(),d=[];document.querySelectorAll("#volume-mounts-list .vol-host-path").forEach(y=>{d.push({hostPath:y.value.trim(),containerPath:y.dataset.containerPath})});const w={appTemplate:r,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:c||null,plexClaimToken:document.getElementById("deploy-plex-claim")?.value.trim()||null,customVolumes:d.length>0?d:null,resources:{cpus:parseFloat(document.getElementById("deploy-cpu-limit").value)||0,memory:parseFloat(document.getElementById("deploy-memory-limit").value)||0}};if(!w.subdomain){showNotification("Please enter a subdomain or domain name","warning");return}if(r.mediaMount?.required&&!c){showNotification("Please enter a media library path for this application","warning");return}B.classList.remove("show"),E(w)}),wireModal(B);const U=document.getElementById("folder-browser-modal"),T=document.getElementById("folder-browser-path"),b=document.getElementById("folder-browser-list"),N=document.getElementById("folder-browser-selected"),O=document.getElementById("folder-browser-selected-list");let p="",u=[],f=null;window.openFolderBrowser=function(r){f=r,u=r.value.split(",").map(c=>c.trim()).filter(c=>c),p="",z(),g(""),U.classList.add("show")};async function g(r){T.textContent=r||"Select a drive...",b.innerHTML='
Loading...
';try{const d=await(await fetch(`/api/v1/browse/directories?path=${encodeURIComponent(r)}`)).json();if(!d.success){b.innerHTML=`
Error: ${escapeHtml(d.error)}
`;return}p=d.path||"",T.textContent=p||"Select a drive...";let w="";d.parent&&d.parent!==d.path&&(w+=`
\u2B06\uFE0F .. Parent Directory
`),d.items.length===0&&!d.parent?w+='
No browseable drives configured. Check your docker-compose.yml volume mounts.
':d.items.length===0?w+='
No subfolders found
':d.items.forEach(y=>{const t=y.type==="drive"?"\u{1F4BE}":"\u{1F4C1}",e=u.includes(y.path),a=e?"background: color-mix(in srgb, var(--success) 20%, transparent);":"";w+=`
${t} ${escapeHtml(y.name)} ${e?'\u2713':""}
`}),b.innerHTML=w,b.querySelectorAll(".folder-item").forEach(y=>{y.addEventListener("click",()=>{g(y.dataset.path)}),y.addEventListener("mouseenter",()=>{y.style.background="var(--card-bg)"}),y.addEventListener("mouseleave",()=>{const t=u.includes(y.dataset.path);y.style.background=t?"color-mix(in srgb, var(--success) 20%, transparent)":""})})}catch(c){b.innerHTML=`
Failed to load: ${escapeHtml(c.message)}
`}}function z(){if(u.length===0){N.style.display="none";return}N.style.display="block",O.innerHTML=u.map(r=>` ${escapeHtml(r)} `).join("")}window.removeSelectedFolder=function(r){u=u.filter(c=>c!==r),z(),g(p)},document.getElementById("folder-browser-select-current").addEventListener("click",()=>{p&&!u.includes(p)&&(u.push(p),z(),g(p))}),wireModal(U,document.getElementById("folder-browser-cancel")),document.getElementById("folder-browser-done").addEventListener("click",()=>{f&&(f.value=u.join(", ")),U.classList.remove("show")}),S()})(),(function(){injectModal("recipe-deploy-modal",`

Deploy Recipe

1 Components
2 Configuration
3 Review
4 Progress
`);let h=null,L=null,A=null,I=1,D=!1;const R=document.getElementById("recipe-deploy-modal"),H=document.getElementById("recipe-cancel"),P=document.getElementById("recipe-prev"),v=document.getElementById("recipe-next");wireModal(R,H);async function C(){try{const p=await fetch("/api/v1/recipes/templates"),u=await p.json();if(u.success)return h=u.templates,L=u.categories,!0;if(p.status===403)return D=!1,!1}catch(p){console.warn("Failed to fetch recipe templates:",p.message)}return!1}async function x(){try{D=(await(await fetch("/api/v1/license/feature/recipes")).json()).available}catch{D=!1}return D}window.renderRecipeCards=async function(p){await x();let u;if(D&&h?u=h:u=$(),!u||u.length===0)return;const f=document.createElement("div");f.className="app-category-header",f.innerHTML="\u{1F9EA} Recipes",f.style.borderBottomColor="#8e44ad",p.appendChild(f);const g=Array.isArray(u)?u:Object.values(u);g.sort((z,r)=>(r.popularity||0)-(z.popularity||0));for(const z of g){const r=document.createElement("div");r.className="app-option",r.style.position="relative";const c=`
${z.componentCount||z.components?.length||"?"} apps
`,d=D?"":'
PREMIUM
';r.innerHTML=` ${d}
${escapeHtml(z.icon||"\u{1F9EA}")}
${escapeHtml(z.name)}
${escapeHtml(z.description||"")}
${c} `,r.onclick=()=>{if(!D){showNotification("Recipes require a DashCaddy Premium license. Click the License button to activate.","warning",5e3),window.openLicenseModal&&window.openLicenseModal();return}E(z)},p.appendChild(r)}};function $(){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 E(p){A=p,I=1;const u=document.getElementById("app-selector-modal");u&&u.classList.remove("show"),document.getElementById("recipe-deploy-title").textContent=`Deploy ${p.name}`,M(),S(),R.classList.add("show")}function M(){document.querySelectorAll("#recipe-steps .recipe-step").forEach(p=>{const u=parseInt(p.dataset.step);p.classList.toggle("active",u===I),p.classList.toggle("completed",u1&&I<4?"":"none",I===4?(v.style.display="none",H.textContent="Close"):I===3?(v.textContent="\u{1F680} Deploy",v.style.display="",H.textContent="Cancel"):(v.textContent="Next",v.style.display="",H.textContent="Cancel")}function S(){const p=document.getElementById("recipe-component-list");p.innerHTML="";const u=A.components||[];for(const f of u){const g=document.createElement("div");g.style.cssText="display: flex; align-items: center; gap: 12px; padding: 12px; border-radius: 8px; background: var(--card-bg); border: 1px solid var(--border);";const z=f.required,r=f.internal;g.innerHTML=`
${escapeHtml(f.role||f.id)}
${f.templateRef?escapeHtml(f.templateRef):"Built-in"} ${z?'Required':'Optional'} ${r?'(Internal)':""}
${f.note?`
\u26A0 ${escapeHtml(f.note)}
`:""}
`,p.appendChild(g)}}function B(){const p=document.getElementById("recipe-volumes-section"),u=document.getElementById("recipe-volume-list"),f=A.sharedVolumes;if(f&&Object.keys(f).length>0){p.style.display="",u.innerHTML="";for(const[g,z]of Object.entries(f)){const r=document.createElement("div");r.style.cssText="display: grid; gap: 4px;",r.innerHTML=`
${escapeHtml(z.description||"")}
`,u.appendChild(r)}}else p.style.display="none"}function U(){const p=document.getElementById("recipe-review-content"),u=T(),f=document.querySelectorAll("#recipe-volume-list input[data-volume-key]"),g={};f.forEach(d=>{g[d.dataset.volumeKey]=d.value});const z=document.getElementById("recipe-timezone").value||"UTC",r=document.getElementById("recipe-ip").value||"host.docker.internal",c=document.getElementById("recipe-tailscale").checked;p.innerHTML=`
${escapeHtml(A.name)}
${escapeHtml(A.description||"")}
Components (${u.length}):
${u.map(d=>`
\u2022 ${escapeHtml(d.role||d.id)} ${d.internal?'(internal)':""}
`).join("")}
${Object.keys(g).length>0?`
Volumes: ${Object.entries(g).map(([d,w])=>`
${d}: ${escapeHtml(w)}
`).join("")}
`:""}
Timezone: ${escapeHtml(z)} • IP: ${escapeHtml(r)} ${c?"• Tailscale only":""}
${A.network?`
Docker network: ${escapeHtml(A.network.name)}
`:""} `}function T(){const p=document.querySelectorAll("#recipe-component-list input[data-component-id]"),u=new Set;p.forEach(g=>{g.checked&&u.add(g.dataset.componentId)});const f=A.components||[];return f.filter(g=>g.required).forEach(g=>u.add(g.id)),f.filter(g=>u.has(g.id))}async function b(){const p=document.getElementById("recipe-progress-list"),u=document.getElementById("recipe-deploy-result");u.style.display="none",p.innerHTML="";const f=T();for(const c of f){const d=document.createElement("div");d.id=`recipe-progress-${c.id}`,d.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;",d.innerHTML=` \u23F3 ${escapeHtml(c.role||c.id)} Queued `,p.appendChild(d)}const g=document.querySelectorAll("#recipe-volume-list input[data-volume-key]"),z={};g.forEach(c=>{z[c.dataset.volumeKey]=c.value});const r={selectedComponents:f.map(c=>c.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:z},componentOverrides:{}};for(const c of f)N(c.id,"deploying","Deploying...");try{const d=await(await secureFetch("/api/v1/recipes/deploy",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({recipeId:A.id,config:r})})).json();if(d.success){for(const w of d.deployed||[])N(w.id,"success",w.url?`Running \u2192 ${w.url}`:"Running");for(const w of d.errors||[])N(w.componentId,"error",w.error);u.style.display="",u.innerHTML=`
${escapeHtml(d.message||"Deployed!")}
${d.setupInstructions?`
Setup tips:
    ${d.setupInstructions.map(w=>`
  • ${escapeHtml(w)}
  • `).join("")}
`:""}
`,showNotification(`${A.name} recipe deployed successfully!`,"success",5e3),window.loadServices&&window.loadServices()}else u.style.display="",u.innerHTML=`
Deployment failed: ${escapeHtml(d.error||"Unknown error")}
`,showNotification(`Recipe deployment failed: ${d.error}`,"error",5e3)}catch(c){u.style.display="",u.innerHTML=`
Network error: ${escapeHtml(c.message)}
`}}function N(p,u,f){const g=document.getElementById(`recipe-progress-${p}`);if(!g)return;const z=g.querySelector(".recipe-progress-icon"),r=g.querySelector(".recipe-progress-status");u==="deploying"?(z.textContent="\u23F3",r.style.color="var(--accent)"):u==="success"?(z.textContent="\u2705",r.style.color="var(--ok-fg)"):u==="error"&&(z.textContent="\u274C",r.style.color="var(--bad-fg)"),r.textContent=f}v.addEventListener("click",()=>{if(I===3){I=4,M(),b();return}I<3&&(I++,M(),I===2&&B(),I===3&&U())}),P.addEventListener("click",()=>{I>1&&I<4&&(I--,M())}),window.groupRecipeCards=function(){const p=document.querySelectorAll(".service-card[data-recipe-id]");if(p.length===0)return;const u={};p.forEach(f=>{const g=f.dataset.recipeId;u[g]||(u[g]=[]),u[g].push(f)});for(const[f,g]of Object.entries(u))g.length<2||g.forEach((z,r)=>{if(z.style.borderLeft="3px solid rgba(142,68,173,0.5)",r===0){let c=z.querySelector(".recipe-group-label");c||(c=document.createElement("div"),c.className="recipe-group-label",c.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;",c.textContent=f.replace(/-/g," "),z.style.position="relative",z.appendChild(c))}})},window.manageRecipe=async function(p,u){const f=`/api/v1/recipes/${p}/${u}`,g=u==="remove"?"DELETE":"POST",z=u==="remove"?`/api/v1/recipes/${p}`:f;if(!(u==="remove"&&!confirm(`Remove the entire ${p} recipe? This will delete all containers and configuration.`)))try{const c=await(await secureFetch(z,{method:g})).json();c.success?(showNotification(`Recipe ${u}: ${c.results?.filter(d=>d.status!=="failed").length||0} components processed`,"success",4e3),window.loadServices&&window.loadServices()):showNotification(`Recipe ${u} failed: ${c.error}`,"error",5e3)}catch(r){showNotification(`Network error: ${r.message}`,"error",5e3)}};const O=document.createElement("style");O.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(O),x()})(),(function(){document.getElementById("reload-caddy-top")?.addEventListener("click",async()=>{const h=document.getElementById("reload-caddy-top"),L=h.textContent;try{h.textContent="\u23F3 Reloading...",h.disabled=!0;const A=await secureFetch("/api/v1/caddy/reload",{method:"POST",headers:{"Content-Type":"application/json"}}),I=await A.json();if(A.ok&&I.success)h.textContent="\u2705 Reloaded!",setTimeout(()=>{h.textContent=L,h.disabled=!1},2e3);else throw new Error(I.error||"Reload failed")}catch(A){h.textContent="\u274C Failed",showNotification(`Failed to reload Caddy: ${A.message}`,"error"),setTimeout(()=>{h.textContent=L,h.disabled=!1},2e3)}})})(),(function(){injectModal("error-log-modal",'

\u{1F4CB} Error Logs

Loading error logs...
');const h=document.getElementById("error-log-modal"),L=document.getElementById("error-log-content"),A=document.getElementById("view-error-logs"),I=document.getElementById("error-log-refresh"),D=document.getElementById("error-log-clear"),R=document.getElementById("error-log-close");async function H(){L.innerHTML='
Loading error logs...
';try{const C=await(await fetch("/api/v1/error-logs")).json();C.success&&C.logs?C.logs.length===0?L.innerHTML='
\u2705 No errors logged! Everything is working smoothly.
':L.innerHTML=C.logs.map(x=>`
${new Date(x.timestamp).toLocaleString()} ERROR
${escapeHtml(x.context)}: ${escapeHtml(x.error)} ${x.details?`
${escapeHtml(x.details)}`:""}
`).join(""):L.innerHTML='
\u274C Failed to load error logs
'}catch(v){L.innerHTML=`
\u274C Error loading logs: ${escapeHtml(v.message)}
`}}async function P(){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),H()):showNotification("\u274C Failed to clear logs","error",3e3)}catch(v){showNotification(`\u274C Error: ${v.message}`,"error",3e3)}}A?.addEventListener("click",()=>{h.classList.add("show"),H()}),I?.addEventListener("click",H),D?.addEventListener("click",P),wireModal(h,R)})(),(function(){injectModal("container-logs-modal",`

\u{1F4DC} Container Logs

Image: - Status: - Created: -
Select a container to view logs
`);const h=document.getElementById("container-logs-modal"),L=document.getElementById("cl-container-select"),A=document.getElementById("cl-log-content"),I=document.getElementById("cl-log-search"),D=document.getElementById("cl-log-tail"),R=document.getElementById("cl-refresh"),H=document.getElementById("cl-stream"),P=document.getElementById("cl-download"),v=document.getElementById("cl-clear-search"),C=document.getElementById("cl-close"),x=document.getElementById("cl-close-btn"),$=document.getElementById("cl-stream-status"),E=document.getElementById("cl-stream-indicator"),M=document.getElementById("cl-stream-text"),S=document.getElementById("cl-line-count"),B=document.getElementById("cl-filter-count"),U=document.getElementById("cl-image"),T=document.getElementById("cl-status"),b=document.getElementById("cl-created");let N=null,O=[],p=[],u=null,f=!1,g=null;function z(s){if(!s)return"-";const l=new Date(s);return isNaN(l.getTime())?s:l.toLocaleString()}function r(s){if(!s)return"";const l=document.createElement("div");return l.textContent=s,l.innerHTML}function c(s,l){const m=s.stream==="stderr"?"log-stderr":"log-stdout",k=s.stream==="stderr"?"\u26A0\uFE0F":"\u{1F4E4}";return`
${l+1} ${k} ${r(s.text)}
`}function d(s,l=""){if(!s||s.length===0){A.innerHTML='
No logs available
',S.textContent="0 lines",B.textContent="0 filtered";return}if(O=s,p=l?s.filter(m=>m.text&&m.text.toLowerCase().includes(l.toLowerCase())):s,S.textContent=`${s.length} lines`,B.textContent=l?`${p.length} of ${s.length} shown`:`${s.length} shown`,p.length===0){A.innerHTML=`
No logs match "${r(l)}"
`;return}A.innerHTML=p.map((m,k)=>c(m,k)).join(""),A.scrollTop=A.scrollHeight}async function w(){try{const l=(await getJSON("/api/v1/logs/containers")).containers||[],m=L.value;L.innerHTML='',l.forEach(k=>{const j=document.createElement("option");j.value=k.id,j.textContent=`${k.name} (${k.image.split(":")[0]}) - ${k.status}`,j.dataset.name=k.name,j.dataset.image=k.image,j.dataset.status=k.status,j.dataset.created=k.created,L.appendChild(j)}),m&&L.querySelector(`option[value="${m}"]`)&&(L.value=m,y(m))}catch(s){console.error("Failed to load containers:",s)}}function y(s){const l=L.querySelector(`option[value="${s}"]`);l&&(U.textContent=l.dataset.image||"-",T.textContent=l.dataset.status||"-",T.style.color=l.dataset.status==="running"?"var(--ok-fg, #4ade80)":"var(--bad-fg, #ef4444)",b.textContent=z(l.dataset.created))}async function t(){const s=L.value;if(!s){A.innerHTML='
Select a container to view logs
';return}a(),N=s,y(s);const l=D.value,m=I.value.trim();A.innerHTML='
Loading logs...
';try{const k=`/api/v1/logs/container/${s}${l!=="all"?`?tail=${l}`:""}`,j=await getJSON(k);j.logs&&j.logs.length>0?d(j.logs,m):(A.innerHTML='
No logs found for this container
',S.textContent="0 lines",B.textContent="0 filtered")}catch(k){A.innerHTML=`
Error loading logs: ${r(k.message)}
`}}function e(){const s=L.value;if(!s)return;a(),f=!0,H.textContent="\u23F9 Stop",$.style.display="flex",E.textContent="\u{1F7E2}",M.textContent="Connecting...";const l=`/api/v1/logs/stream/${s}`;u=new EventSource(l),u.onopen=()=>{E.textContent="\u{1F7E2}",M.textContent="Connected - streaming logs"},u.onmessage=m=>{try{const k=JSON.parse(m.data);if(k.error){E.textContent="\u{1F534}",M.textContent=`Error: ${k.error}`;return}O.push(k),p.push(k),S.textContent=`${O.length} lines`,B.textContent=`${p.length} shown`;const j=I.value.trim();if(!j||k.text&&k.text.toLowerCase().includes(j.toLowerCase())){const _=document.createElement("div");_.innerHTML=c(k,p.length-1);const F=_.firstElementChild;F.style.background="#1a3a1a",A.appendChild(F),A.scrollTop=A.scrollHeight}}catch(k){console.error("Error parsing log:",k)}},u.onerror=()=>{E.textContent="\u{1F534}",M.textContent="Disconnected",f=!1,H.textContent="\u25B6 Stream"},h._eventSource=u}function a(){u&&(u.close(),u=null),h._eventSource&&(h._eventSource.close(),h._eventSource=null),f=!1,H.textContent="\u25B6 Stream",$.style.display="none"}function o(){if(!O||O.length===0){showNotification("No logs to download","error");return}const s=L.querySelector(`option[value="${N}"]`)?.dataset.name||N,l=new Date().toISOString().replace(/[:.]/g,"-"),m=`${s}-logs-${l}.txt`,k=O.map(q=>{const J=q.timestamp||"",X=q.stream==="stderr"?"[ERR]":"[OUT]";return`${J?J+" ":""}${X} ${q.text}`}).join(` `),j=new Blob([k],{type:"text/plain"}),_=URL.createObjectURL(j),F=document.createElement("a");F.href=_,F.download=m,document.body.appendChild(F),F.click(),document.body.removeChild(F),URL.revokeObjectURL(_),showNotification(`Downloaded ${O.length} log lines`,"success")}L?.addEventListener("change",()=>{t()}),D?.addEventListener("change",()=>{t()}),R?.addEventListener("click",()=>{t()}),H?.addEventListener("click",()=>{f?a():e()}),P?.addEventListener("click",()=>{o()}),v?.addEventListener("click",()=>{I.value="",d(O,"")}),I?.addEventListener("input",()=>{clearTimeout(g),g=setTimeout(()=>{d(O,I.value.trim())},300)}),I?.addEventListener("keydown",s=>{s.key==="Escape"&&(I.value="",d(O,""))}),document.getElementById("view-container-logs")?.addEventListener("click",()=>{h.classList.add("show"),w()});function n(){a(),h.classList.remove("show")}C?.addEventListener("click",n),x?.addEventListener("click",n),document.addEventListener("keydown",s=>{s.key==="Escape"&&h.classList.contains("show")&&n()}),h.addEventListener("click",s=>{s.target===h&&n()}),window.openContainerLogsModal=function(s,l){h.classList.add("show"),w().then(()=>{const m=Array.from(L.options).find(k=>k.value===s||k.dataset.name===l);m?(L.value=m.value,y(m.value),t()):s?(N=s,U.textContent=l||s,T.textContent="-",b.textContent="-",t()):A.innerHTML='
Select a container to view logs
'})}})(),(function(){injectModal("snapshot-modal",`

\u{1F4BE} Container Snapshots

`);const h=document.getElementById("snapshot-modal"),L=document.getElementById("snapshot-btn"),A=document.getElementById("snapshot-close"),I=document.getElementById("snapshot-container-select"),D=document.getElementById("snapshot-details"),R=document.getElementById("snapshot-create-btn"),H=document.getElementById("snapshot-create-status");let P=null;async function v(){try{const S=await(await fetch("/api/v1/containers")).json();if(!S.success||!S.containers)return;I.innerHTML='';for(const B of S.containers){const U=document.createElement("option");U.value=B.id,U.textContent=`${B.name||B.id} (${B.image||"unknown"})`,U.dataset.name=B.name,U.dataset.image=B.image,U.dataset.status=B.status,U.dataset.created=B.created,I.appendChild(U)}}catch(M){console.error("Failed to load containers:",M)}}function C(M){if(!M||!M.value){D.style.display="none",P=null;return}P=M.value,document.getElementById("snapshot-image").textContent=M.dataset.image||"-",document.getElementById("snapshot-status").textContent=M.dataset.status||"-",document.getElementById("snapshot-created").textContent=M.dataset.created?new Date(M.dataset.created*1e3).toLocaleString():"-",document.getElementById("snapshot-id").textContent=M.value.substring(0,12),D.style.display=""}async function x(){if(!P){H.textContent="Please select a container first",H.style.color="var(--bad-fg)";return}const M=document.getElementById("snapshot-name").value.trim();if(!M){H.textContent="Please enter a snapshot name",H.style.color="var(--bad-fg)";return}const S=document.getElementById("snapshot-leave-running").checked;R.disabled=!0,R.textContent="Creating...",H.textContent="";try{const U=await(await fetch(`/api/v1/containers/${encodeURIComponent(P)}/checkpoint`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:M,leaveRunning:S})})).json();U.success?(H.textContent=`\u2713 Snapshot "${M}" created successfully`,H.style.color="var(--ok-fg)",document.getElementById("snapshot-name").value=""):(H.textContent=`\u2717 Failed: ${U.error||"Unknown error"}`,H.style.color="var(--bad-fg)")}catch(B){H.textContent=`\u2717 Error: ${B.message}`,H.style.color="var(--bad-fg)"}finally{R.disabled=!1,R.textContent="\u{1F4BE} Create Snapshot"}}function $(){h.classList.add("show"),v()}function E(){h.classList.remove("show"),D.style.display="none",P=null,I.selectedIndex=0}L?.addEventListener("click",$),A?.addEventListener("click",E),wireModal(h,A),I?.addEventListener("change",M=>{const S=I.options[I.selectedIndex];C(S)}),R?.addEventListener("click",x),h?.querySelectorAll(".panel-tab").forEach(M=>{M.addEventListener("click",()=>{h.querySelectorAll(".panel-tab").forEach(S=>S.classList.remove("active")),h.querySelectorAll(".panel-section").forEach(S=>S.classList.remove("active")),M.classList.add("active"),h.querySelector(`#${M.dataset.panel}`).classList.add("active")})})})(),(function(){injectModal("arr-setup-modal",`

\u{1F3AC} Smart Arr Connect

Auto-discover and connect your entire media stack.

Scanning for services...
Where to find API keys:
Radarr/Sonarr/Prowlarr: Settings -> General -> Security -> API Key
`);const h=document.getElementById("arr-setup-modal"),L=document.getElementById("arr-setup-btn"),A=document.getElementById("arr-setup-cancel"),I=document.getElementById("smart-connect-btn"),D=document.getElementById("smart-phase-detect"),R=document.getElementById("smart-phase-credentials"),H=document.getElementById("smart-phase-progress"),P=document.getElementById("smart-phase-results"),v=document.getElementById("smart-detect-results"),C=document.getElementById("smart-credential-inputs"),x=document.getElementById("smart-progress-steps"),$=document.getElementById("smart-results-content"),E=document.getElementById("smart-plex-libraries"),M=document.getElementById("smart-retry-btn");let S=null;const B={plex:"\u{1F3AC}",radarr:"\u{1F3AC}",sonarr:"\u{1F4FA}",prowlarr:"\u{1F50D}",seerr:"\u{1F4CB}"},U={plex:"Plex",radarr:"Radarr (Movies)",sonarr:"Sonarr (TV)",prowlarr:"Prowlarr (Indexers)",seerr:"Seerr"};function T(g){D.style.display=g==="detect"?"block":"none",R.style.display=g==="credentials"?"block":"none",H.style.display=g==="progress"?"block":"none",P.style.display=g==="results"?"block":"none"}function b(g){const z={connected:{bg:"var(--ok-fg)",icon:"✓",text:"Connected"},needs_key:{bg:"#f39c12",icon:"🔑",text:"Needs API Key"},not_found:{bg:"var(--muted)",icon:"—",text:"Not Found"},error:{bg:"var(--bad-fg)",icon:"✗",text:"Error"}},r=z[g]||z.not_found;return`${r.icon} ${r.text}`}async function N(){T("detect"),v.style.display="none";try{if(S=await(await fetch("/api/v1/arr/smart-detect")).json(),!S.success){v.innerHTML=`
Detection failed: ${escapeHtml(S.error)}
`,v.style.display="block";return}let z='
';for(const[c,d]of Object.entries(S.services)){const w=B[c]||"\u{1F4E6}",y=U[c]||c,t=d.source?`${escapeHtml(d.source)}`:"",e=d.version?`v${escapeHtml(d.version)}`:"",a=(d.hasApiKey||d.hasToken)&&d.status==="connected"?'Key saved':"";z+=`
${w}
${y}
${t} ${e} ${a}
${b(d.status)}
`}z+="
";const r=S.summary;z+=`
${escapeHtml(String(r.fullyConnected))}/${escapeHtml(String(r.totalDetected+(5-r.totalDetected)))} services detected · ${escapeHtml(String(r.fullyConnected))} connected${r.needsApiKey>0?` · ${escapeHtml(String(r.needsApiKey))} needs API key`:""}
`,v.innerHTML=z,v.style.display="block",O(S),setTimeout(()=>{T("credentials")},800)}catch(g){v.innerHTML=`
Error: ${escapeHtml(g.message)}
`,v.style.display="block"}}function O(g){let z="";const r=g.services,c=["radarr","sonarr","prowlarr"];for(const y of c){const t=r[y];if(!t||t.status==="not_found"&&!t.url)continue;const e=B[y],a=U[y],o=t.status==="connected";z+=`
${e} ${a} ${o?'✓ Connected':""}
`}const d=r.plex;if(d){const y=d.status==="connected";z+=`
\u{1F3AC} Plex ${b(d.status)} ${escapeHtml(d.source||"")}
`}const w=r.seerr;if(w){const y=w.status==="connected";let t="";if(w.configuredServices){const e=w.configuredServices;t=`
Configured: ${e.radarr?"✓ Radarr":"✗ Radarr"} · ${e.sonarr?"✓ Sonarr":"✗ Sonarr"} · ${e.plex?"✓ Plex":"✗ Plex"}
`}z+=`
\u{1F4CB} Seerr ${b(w.status)}
${t}
`}C.innerHTML=z}window.smartTestConnection=async function(g){const z=document.getElementById(`smart-${g}-url`),r=document.getElementById(`smart-${g}-key`),c=document.getElementById(`smart-${g}-status`),d=z?.value.trim(),w=r?.value.trim();if(!d||!w){c.innerHTML='Enter URL and API key';return}c.innerHTML='';try{const t=await(await secureFetch("/api/v1/arr/test-connection",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({service:g,url:d,apiKey:w})})).json();t.success?c.innerHTML=`✓ ${escapeHtml(t.appName||"Connected")} v${escapeHtml(t.version||"")}`:c.innerHTML=`✗ ${escapeHtml(t.error)}`}catch(y){c.innerHTML=`✗ ${escapeHtml(y.message)}`}};async function p(){T("progress"),x.innerHTML='
Connecting services...
';const g={};for(const r of["radarr","sonarr","prowlarr"]){const c=document.getElementById(`smart-${r}-url`)?.value.trim(),d=document.getElementById(`smart-${r}-key`)?.value.trim();d&&c?g[r]={apiKey:d,url:c}:d&&(g[r]={apiKey:d})}const z={services:Object.keys(g).length>0?g: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 c=await(await secureFetch("/api/v1/arr/smart-connect",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(z)})).json();let d="";for(const w of c.steps||[]){const y=w.status==="success"?'':'',t=w.status==="success"?"var(--muted)":"var(--bad-fg)";d+=`
${y} ${escapeHtml(w.step)} ${escapeHtml(w.details||"")}
`}x.innerHTML=d,setTimeout(()=>u(c),500)}catch(r){x.innerHTML=`
Connection error: ${escapeHtml(r.message)}
`}}function u(g){T("results");const z=g.summary||{},r=z.failed===0&&z.succeeded>0,c=r?"var(--ok-fg)":"#f39c12",d=r?"✓":"⚠",w=r?"All Connected!":`${escapeHtml(String(z.succeeded))}/${escapeHtml(String(z.totalSteps))} Steps Succeeded`;let y=`
${d}
${w}
${escapeHtml(String(z.succeeded))} succeeded, ${escapeHtml(String(z.failed))} failed
`;y+='
';for(const t of g.steps||[]){const e=t.status==="success"?'':'';y+=`
${e} ${escapeHtml(t.step)} ${escapeHtml(t.details||"")}
`}y+="
",$.innerHTML=y,M.style.display=z.failed>0?"block":"none",g.steps?.some(t=>t.step.includes("Plex")&&t.status==="success")&&f()}async function f(){try{const z=await(await fetch("/api/v1/plex/libraries")).json();if(z.success&&z.libraries?.length>0){let r=`

\u{1F3AC} ${escapeHtml(z.serverName)} Libraries

`;for(const c of z.libraries){const d=c.type==="movie"?"\u{1F3AC}":c.type==="show"?"\u{1F4FA}":"\u{1F3B5}";r+=`
${d} ${escapeHtml(c.title)} ${escapeHtml(String(c.count))} items
`}r+="
",E.innerHTML=r,E.style.display="block"}}catch{}}L?.addEventListener("click",()=>{h.classList.add("show"),E.style.display="none",N()}),wireModal(h,A),I?.addEventListener("click",p),M?.addEventListener("click",p)})(),(function(){const h=new ErrorHandler;injectModal("notifications-modal",`

\u{1F514} Notification Settings

Notification Providers

Health Monitoring

Last check: Never

Events to Notify

Notification History

No notifications yet
`);const L=document.getElementById("notifications-modal"),A=document.getElementById("manage-notifications"),I=document.getElementById("notifications-save"),D=document.getElementById("notifications-cancel");["discord","telegram","ntfy","email"].forEach(E=>{const M=document.getElementById(`${E}-enabled`),S=document.getElementById(`${E}-config`);M?.addEventListener("change",()=>{S.style.display=M.checked?"block":"none"})});const R=document.getElementById("health-check-enabled"),H=document.getElementById("health-check-config");R?.addEventListener("change",()=>{H.style.opacity=R.checked?"1":"0.5"});async function P(){try{const M=await(await fetch("/api/v1/notifications/config")).json();if(M.success){const S=M.config;document.getElementById("notifications-enabled").checked=S.enabled,document.getElementById("discord-enabled").checked=S.providers?.discord?.enabled||!1,document.getElementById("telegram-enabled").checked=S.providers?.telegram?.enabled||!1,document.getElementById("ntfy-enabled").checked=S.providers?.ntfy?.enabled||!1,document.getElementById("email-enabled").checked=S.providers?.email?.enabled||!1,document.getElementById("discord-config").style.display=S.providers?.discord?.enabled?"block":"none",document.getElementById("telegram-config").style.display=S.providers?.telegram?.enabled?"block":"none",document.getElementById("ntfy-config").style.display=S.providers?.ntfy?.enabled?"block":"none",document.getElementById("email-config").style.display=S.providers?.email?.enabled?"block":"none",S.providers?.ntfy?.serverUrl&&(document.getElementById("ntfy-server").value=S.providers.ntfy.serverUrl),S.providers?.email?.host&&(document.getElementById("email-host").value=S.providers.email.host),S.providers?.email?.from&&(document.getElementById("email-from").value=S.providers.email.from),document.getElementById("health-check-enabled").checked=S.healthCheck?.enabled||!1,S.healthCheck?.intervalMinutes&&(document.getElementById("health-check-interval").value=S.healthCheck.intervalMinutes),S.healthCheck?.lastCheck&&(document.getElementById("health-check-status").textContent=`Last check: ${new Date(S.healthCheck.lastCheck).toLocaleString()}`),document.getElementById("event-container-down").checked=S.events?.containerDown!==!1,document.getElementById("event-container-up").checked=S.events?.containerUp!==!1,document.getElementById("event-deploy-success").checked=S.events?.deploymentSuccess!==!1,document.getElementById("event-deploy-failed").checked=S.events?.deploymentFailed!==!1,document.getElementById("event-resource-alert").checked=S.events?.resourceAlert!==!1}}catch(E){h.logError("[Notifications] Load Config",E,{function:"loadConfig"})}}async function v(){try{const M=await(await fetch("/api/v1/notifications/history?limit=10")).json(),S=document.getElementById("notification-history");M.success&&M.history?.length>0?S.innerHTML=M.history.map(B=>{const U=new Date(B.timestamp).toLocaleString();return`
${B.type==="success"?"\u2713":B.type==="error"?"\u2717":"\u2139"}
${escapeHtml(B.title)}
${U}
`}).join(""):S.innerHTML='
No notifications yet
'}catch(E){h.logError("[Notifications] Load History",E,{function:"loadHistory"})}}async function C(){try{const E={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()},email:{enabled:document.getElementById("email-enabled").checked,host:document.getElementById("email-host").value.trim(),port:parseInt(document.getElementById("email-port").value)||587,secure:document.getElementById("email-secure").checked,user:document.getElementById("email-user").value.trim(),pass:document.getElementById("email-pass").value.trim(),from:document.getElementById("email-from").value.trim(),to:document.getElementById("email-to").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,resourceAlert:document.getElementById("event-resource-alert").checked},healthCheck:{enabled:document.getElementById("health-check-enabled").checked,intervalMinutes:parseInt(document.getElementById("health-check-interval").value)||5}},S=await(await secureFetch("/api/v1/notifications/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(E)})).json();S.success?(showNotification("Notification settings saved","success",3e3),L.classList.remove("show")):showNotification(`Failed to save: ${S.error}`,"error",3e3)}catch(E){showNotification(`Error: ${E.message}`,"error",3e3)}}async function x(E){try{const S=await(await secureFetch("/api/v1/notifications/test",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:E})})).json();S.success?showNotification(`Test ${E} notification sent!`,"success",3e3):showNotification(`Test failed: ${S.error}`,"error",3e3)}catch(M){showNotification(`Error: ${M.message}`,"error",3e3)}}document.getElementById("discord-test")?.addEventListener("click",()=>x("discord")),document.getElementById("telegram-test")?.addEventListener("click",()=>x("telegram")),document.getElementById("ntfy-test")?.addEventListener("click",()=>x("ntfy")),document.getElementById("email-test")?.addEventListener("click",()=>x("email")),document.getElementById("health-check-now")?.addEventListener("click",async()=>{try{const M=await(await secureFetch("/api/v1/notifications/health-check",{method:"POST"})).json();M.success&&(document.getElementById("health-check-status").textContent=`Last check: ${new Date(M.lastCheck).toLocaleString()} (${M.containersMonitored} containers)`,showNotification("Health check completed","success",2e3))}catch(E){showNotification(`Error: ${E.message}`,"error",3e3)}}),A?.addEventListener("click",()=>{L.classList.add("show"),P(),v()}),I?.addEventListener("click",C),document.getElementById("notifications-send-test")?.addEventListener("click",async()=>{const E=document.getElementById("notifications-send-test"),M=E.textContent;E.textContent="Sending...",E.disabled=!0;try{const B=await(await secureFetch("/api/v1/notifications/send",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({event:"test",data:{message:"This is a test notification from DashCaddy."},type:"info"})})).json();B.success?(showNotification("Test notification sent!","success",3e3),$()):showNotification(`Test failed: ${B.results?.map(U=>`${U.provider}: ${U.error||"ok"}`).join(", ")}`,"error",5e3)}catch(S){showNotification(`Error: ${S.message}`,"error",3e3)}finally{E.textContent=M,E.disabled=!1}});async function $(){try{const M=await(await fetch("/api/v1/notifications/status")).json();if(M.success&&M.lastSent){const S=document.getElementById("last-notification-sent");S&&(S.textContent=`Last sent: ${new Date(M.lastSent).toLocaleString()}`)}}catch{}}wireModal(L,D)})(),(function(){document.addEventListener("click",h=>{const L=h.target.closest(".panel-tab");if(!L)return;const A=L.dataset.panel;if(!A)return;const I=L.closest(".panel-tabs"),D=I.closest(".weather-modal-content");I.querySelectorAll(".panel-tab").forEach(H=>H.classList.remove("active")),L.classList.add("active"),D.querySelectorAll(".panel-section").forEach(H=>H.classList.remove("active"));const R=D.querySelector("#"+A);R&&R.classList.add("active")})})(),(function(){var h=["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 L(){for(var e={},a=0;a

\u{1F4BE} Backup & Restore

\u{1F4E4} Export Backup

Downloads everything \u2014 services, Caddyfile, credentials, encryption key, themes, and all browser preferences.

\u{1F4E5} Restore Backup

Upload a backup file to restore your entire configuration \u2014 drag and drop ready.

\u23F0 Loading schedules...
\u{1F4BE} Loading backup files...
\u23EA Loading...
\u{1F4CB} Loading backup history...
`);var R=document.getElementById("backup-modal"),H=document.getElementById("backup-restore-btn"),P=document.getElementById("backup-cancel"),v=document.getElementById("backup-export-btn"),C=document.getElementById("backup-select-file"),x=document.getElementById("backup-file-input"),$=document.getElementById("backup-file-name"),E=document.getElementById("backup-preview"),M=document.getElementById("backup-preview-content"),S=document.getElementById("backup-do-restore-btn"),B=document.getElementById("backup-result"),U=document.getElementById("backup-schedules-container"),T=document.getElementById("backup-history-container"),b=document.getElementById("backup-disk-container"),N=document.getElementById("pointintime-container"),O=null;H?.addEventListener("click",function(){R.classList.add("show"),B&&(B.style.display="none"),E&&(E.style.display="none"),$&&($.style.display="none"),O=null}),wireModal(R,P),v?.addEventListener("click",async function(){v.disabled=!0,v.innerHTML=' Exporting...';try{var e=await fetch("/api/v1/backup/export"),a=await e.json();a.browserState=L();var o=new Blob([JSON.stringify(a,null,2)],{type:"application/json"}),i=URL.createObjectURL(o),n=document.createElement("a");n.href=i,n.download="dashcaddy-backup-"+new Date().toISOString().split("T")[0]+".json",document.body.appendChild(n),n.click(),document.body.removeChild(n),URL.revokeObjectURL(i);var s=Object.keys(a.browserState).length,l=a.themes?Object.keys(a.themes).length:0;B.innerHTML="\u2705 Full backup downloaded \u2014 server config + "+s+" browser settings"+(l?" + "+l+" themes":""),B.style.display="block",B.style.background="color-mix(in srgb, var(--ok-fg) 15%, transparent)",B.style.border="1px solid var(--ok-fg)"}catch(m){B.innerHTML="\u274C Export failed: "+escapeHtml(m.message),B.style.display="block",B.style.background="color-mix(in srgb, var(--bad-fg) 15%, transparent)",B.style.border="1px solid var(--bad-fg)"}v.disabled=!1,v.innerHTML="\u2B07\uFE0F Download Full Backup"}),C?.addEventListener("click",function(){x.click()}),x?.addEventListener("change",async function(e){var a=e.target.files[0];if(a){$.textContent="\u{1F4C4} "+a.name,$.style.display="block",B.style.display="none";try{var o=await a.text(),i=JSON.parse(o);if(I(i)){O=i;var n='
Legacy format (v'+escapeHtml(i.version)+")
";n+='
',i.services?.length&&(n+='\u{1F4CB} '+i.services.length+" services"),i.customApps?.length&&(n+='\u{1F4E6} '+i.customApps.length+" custom apps"),i.theme&&(n+='\u{1F3A8} Theme: '+escapeHtml(i.theme)+""),i.userThemes&&(n+='\u{1F3A8} '+Object.keys(i.userThemes).length+" custom themes"),n+="
",M.innerHTML=n,E.style.display="block";return}var s=await secureFetch("/api/v1/backup/preview",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)}),l=await s.json();if(l.success){O=i;var n='
Exported: '+new Date(i.exportedAt).toLocaleString()+" (v"+escapeHtml(i.version)+")
";n+='
Server Config
',n+='
';for(var m in l.preview.files){var k=l.preview.files[m],j=k.action==="create"?"\u{1F195}":"\u{1F4DD}";n+=''+j+" "+escapeHtml(k.description)+""}n+="
",l.preview.serviceCount&&(n+='
'+l.preview.serviceCount+" services
"),l.preview.themeCount&&(n+='
\u{1F3A8} '+l.preview.themeCount+" custom themes
"),l.preview.browserStateCount&&(n+='
Browser Preferences
',n+='
\u{1F5A5}\uFE0F '+l.preview.browserStateCount+" saved settings (theme, weather, clock, widgets, etc.)
"),M.innerHTML=n,E.style.display="block"}else B.innerHTML="\u26A0\uFE0F Invalid backup file: "+escapeHtml(l.error),B.style.display="block",B.style.background="color-mix(in srgb, #f39c12 15%, transparent)",B.style.border="1px solid #f39c12",E.style.display="none"}catch(_){B.innerHTML="\u274C Could not read file: "+escapeHtml(_.message),B.style.display="block",B.style.background="color-mix(in srgb, var(--bad-fg) 15%, transparent)",B.style.border="1px solid var(--bad-fg)",E.style.display="none"}}}),S?.addEventListener("click",async function(){if(O&&confirm("This will overwrite your current configuration and browser preferences. Continue?")){S.disabled=!0,S.innerHTML=' Restoring...';try{if(I(O)){D(O),B.innerHTML="\u2705 Legacy backup restored \u2014 browser settings and services imported.",B.style.background="color-mix(in srgb, var(--ok-fg) 15%, transparent)",B.style.border="1px solid var(--ok-fg)",B.style.display="block",setTimeout(function(){location.reload()},2e3),S.disabled=!1,S.innerHTML="\u26A1 Restore Everything";return}var e=document.getElementById("backup-reload-caddy")?.checked??!0,a=await secureFetch("/api/v1/backup/restore",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({backup:O,options:{reloadCaddy:e}})}),o=await a.json(),i=0;if(O.browserState&&(i=A(O.browserState)),o.success){var n="\u2705 "+o.message;i>0&&(n+='
'+i+" browser settings restored"),o.results.caddyReloaded&&(n+='
Caddy configuration reloaded'),B.innerHTML=n,B.style.background="color-mix(in srgb, var(--ok-fg) 15%, transparent)",B.style.border="1px solid var(--ok-fg)",setTimeout(function(){location.reload()},2e3)}else B.innerHTML="\u26A0\uFE0F "+escapeHtml(o.message),i>0&&(B.innerHTML+='
'+i+" browser settings were restored"),o.results?.errors?.length>0&&(B.innerHTML+="
"+o.results.errors.map(function(s){return escapeHtml(s.file)+": "+escapeHtml(s.error)}).join(", ")+""),B.style.background="color-mix(in srgb, #f39c12 15%, transparent)",B.style.border="1px solid #f39c12";B.style.display="block"}catch(s){B.innerHTML="\u274C Restore failed: "+escapeHtml(s.message),B.style.display="block",B.style.background="color-mix(in srgb, var(--bad-fg) 15%, transparent)",B.style.border="1px solid var(--bad-fg)"}S.disabled=!1,S.innerHTML="\u26A1 Restore Everything"}});async function p(){if(U){U.innerHTML='
Loading...
';try{var e=await fetch("/api/v1/backups/schedule"),a=await e.json();if(a.premiumRequired){U.innerHTML=`
\u2B50
Premium Feature
Auto-backup scheduling requires a DashCaddy Premium subscription.
`;return}if(!a.success)throw new Error(a.error||"Failed to load schedules");var o=a.schedules||[];if(o.length===0){U.innerHTML='
\u23F0
No backup schedules configured
Select apps below to enable auto-backup
';return}for(var i='
',n=0;n
Schedule:
Keep last:
Next run: '+escapeHtml(l)+"
Last run: "+escapeHtml(m)+'
'}i+="",i+='

\u2795 Add New Schedule

',U.innerHTML=i,U.querySelectorAll(".schedule-toggle").forEach(function(k){k.addEventListener("change",function(){u(k.dataset.appid,{enabled:k.checked})})}),U.querySelectorAll(".schedule-select").forEach(function(k){k.addEventListener("change",function(){u(k.dataset.appid,{schedule:k.value})})}),U.querySelectorAll(".retention-input").forEach(function(k){k.addEventListener("change",function(){u(k.dataset.appid,{retention:{keep:parseInt(k.value)||7}})})}),U.querySelectorAll(".schedule-run-now").forEach(function(k){k.addEventListener("click",function(){f(k.dataset.appid)})}),U.querySelectorAll(".schedule-delete").forEach(function(k){k.addEventListener("click",function(){g(k.dataset.appid)})}),document.getElementById("add-schedule-btn")?.addEventListener("click",z)}catch(k){U.innerHTML='
Failed to load: '+escapeHtml(k.message)+"
"}}}async function u(e,a){try{var o=await secureFetch("/api/v1/backups/schedule",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({appId:e,...a})}),i=await o.json();i.success?showNotification("Schedule updated for "+e,"success"):(showNotification("Update failed: "+(i.error||"Unknown"),"error"),p())}catch(n){showNotification("Error: "+n.message,"error")}}async function f(e){try{var a=await secureFetch("/api/v1/backups/backup/"+encodeURIComponent(e),{method:"POST",headers:{"Content-Type":"application/json"}}),o=await a.json();o.success?showNotification("Backup started for "+e+"!","success"):showNotification("Backup failed: "+(o.error||"Unknown"),"error")}catch(i){showNotification("Error: "+i.message,"error")}}async function g(e){if(confirm("Remove backup schedule for "+e+"?"))try{var a=await secureFetch("/api/v1/backups/schedule/"+encodeURIComponent(e),{method:"DELETE"}),o=await a.json();o.success?(showNotification("Schedule removed for "+e,"success"),p()):showNotification("Delete failed: "+(o.error||"Unknown"),"error")}catch(i){showNotification("Error: "+i.message,"error")}}async function z(){var e=document.getElementById("new-schedule-appid")?.value?.trim(),a=document.getElementById("new-schedule-interval")?.value||"daily",o=parseInt(document.getElementById("new-schedule-retention")?.value)||7;if(!e){showNotification("Please enter an App ID","warning");return}try{var i=await secureFetch("/api/v1/backups/schedule",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({appId:e,schedule:a,retention:{keep:o},enabled:!0})}),n=await i.json();if(n.success){showNotification("Schedule created for "+e,"success"),p();var s=document.getElementById("new-schedule-appid");s&&(s.value="")}else showNotification("Failed: "+(n.error||"Unknown"),"error")}catch(l){showNotification("Error: "+l.message,"error")}}async function r(){if(b){b.innerHTML='
Loading...
';try{var e=await fetch("/api/v1/backups/files"),a=await e.json();if(!a.success)throw new Error(a.error||"Failed to load");var o=a.files||[];if(o.length===0){b.innerHTML='
\u{1F4BE}
No backup files on disk
Run a backup to create backup files
';return}for(var i={},n=0;n";m+='
';for(var k=Object.keys(i).sort(),j=0;j
'+escapeHtml(l)+' ('+_.length+" backup(s))
";for(var F=0;F<_.length;F++){var s=_[F],q=new Date(s.timestamp).toLocaleString();m+='
'+escapeHtml(s.name)+'
'+s.sizeFormatted+'
'+q+'
'}m+="
"}m+="",b.innerHTML=m,b.querySelectorAll(".disk-compare-btn").forEach(function(J){J.addEventListener("click",function(){y(J.dataset.appid,J.dataset.filename)})}),b.querySelectorAll(".disk-restore-btn").forEach(function(J){J.addEventListener("click",function(){t(J.dataset.appid,J.dataset.filename)})})}catch(J){b.innerHTML='
Failed: '+escapeHtml(J.message)+"
"}}}async function c(){if(T){T.innerHTML='
Loading...
';try{var e=await fetch("/api/v1/backups/history?limit=50"),a=await e.json();if(!a.success||!a.history?.length){T.innerHTML='
\u{1F4CB} No backup history yet
';return}for(var o='
',i=0;i',o+='
',o+=' '+escapeHtml(n.name||"backup")+"",o+='
',o+=' '+escapeHtml(n.status)+"",n.status==="success"&&(o+=' '),o+="
",o+="
",o+='
',o+=" "+new Date(n.timestamp).toLocaleString()+" | "+s+" MB | "+(n.duration?(n.duration/1e3).toFixed(1)+"s":"--"),n.encrypted&&(o+=" | \u{1F512}"),o+="
",o+="
"}o+="",T.innerHTML=o,T.querySelectorAll(".backup-restore-btn").forEach(function(l){l.addEventListener("click",function(){window.__restoreServerBackup(l.dataset.backupId)})})}catch(l){T.innerHTML='
Failed: '+escapeHtml(l.message)+"
"}}}window.__restoreServerBackup=async function(e){if(confirm("Restore from this server backup? This will overwrite current configuration."))try{var a=await secureFetch("/api/v1/backups/restore/"+e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({restoreServices:!0,restoreConfig:!0})}),o=await a.json();o.success?(showNotification("Restore completed successfully!","success"),location.reload()):showNotification("Restore failed: "+(o.error||"Unknown error"),"error")}catch(i){showNotification("Restore error: "+i.message,"error")}},document.querySelector('[data-panel="backup-schedules-tab"]')?.addEventListener("click",p),document.querySelector('[data-panel="backup-disk-tab"]')?.addEventListener("click",r),document.querySelector('[data-panel="backup-pointintime-tab"]')?.addEventListener("click",d),document.querySelector('[data-panel="backup-history-tab"]')?.addEventListener("click",c);async function d(){if(N){try{var e=await fetch("/api/v1/license/status"),a=await e.json();if(a.tier!=="premium"){N.innerHTML=`
\u2B50
Premium Feature
Point-in-time restore requires DashCaddy Premium with auto-backup enabled.
`;return}}catch{}N.innerHTML='
Loading...
';try{var o=await fetch("/api/v1/services"),i=await o.json(),n=i.services||[];if(n.length===0){N.innerHTML='
\u{1F4E6} No apps deployed yet
';return}for(var s='
',N.innerHTML=s,document.getElementById("pit-load-btn")?.addEventListener("click",function(){var m=document.getElementById("pit-app-select")?.value;m&&w(m)})}catch(m){N.innerHTML='
Failed: '+escapeHtml(m.message)+"
"}}}async function w(e){var a=document.getElementById("pit-backups-list");if(a){a.innerHTML='
Loading backups...
';try{var o=await fetch("/api/v1/backups/files/"+encodeURIComponent(e)),i=await o.json();if(!i.success||!i.files||i.files.length===0){a.innerHTML='
\u{1F4BE} No backup files for '+escapeHtml(e)+"
";return}for(var n='
'+i.files.length+' backup(s)
',s=0;s
'+l.sizeFormatted+'
'+m+'
'}n+="",a.innerHTML=n,a.querySelectorAll(".pit-compare-btn").forEach(function(k){k.addEventListener("click",function(){y(k.dataset.appid,k.dataset.filename)})}),a.querySelectorAll(".pit-restore-btn").forEach(function(k){k.addEventListener("click",function(){t(k.dataset.appid,k.dataset.filename)})})}catch(k){a.innerHTML='
Failed: '+escapeHtml(k.message)+"
"}}}async function y(e,a){try{var o=await secureFetch("/api/v1/backups/compare/"+encodeURIComponent(a),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({})}),i=await o.json();if(!i.success){showNotification("Compare failed: "+(i.error||"Unknown"),"error");return}var n=i.diff,s='

\u{1F4CA} Compare: '+escapeHtml(a)+'

Size: '+(n.sizeFormatted||"?")+" | Created: "+new Date(n.timestamp).toLocaleString()+"
";if(n.services){var l=n.services.hasChanges?"\u{1F534}":"\u{1F7E2}";s+='
'+l+' Services (backup vs current)
Backup: '+n.services.backupCount+" services | Current: "+n.services.currentCount+" services
",n.services.hasChanges&&(s+='
Services differ \u2014 restoring will replace current configuration
'),s+="
"}if(n.config){var m=n.config.hasChanges?"\u{1F534}":"\u{1F7E2}";s+='
'+m+" Configuration
",n.config.hasChanges?s+='
Configuration differs \u2014 restoring will replace current settings
':s+='
No changes
',s+="
"}s+='
',document.body.insertAdjacentHTML("beforeend",s),document.getElementById("compare-close-btn")?.addEventListener("click",function(){document.getElementById("compare-overlay")?.remove()}),document.getElementById("compare-overlay")?.addEventListener("click",function(k){k.target===this&&this.remove()})}catch(k){showNotification("Compare error: "+k.message,"error")}}async function t(e,a){if(confirm("Restore "+a+" for "+e+`? This will replace current configuration, credentials, and data. Containers will be restarted.`))try{var o=await secureFetch("/api/v1/apps/"+encodeURIComponent(e)+"/revert/"+encodeURIComponent(a),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({restartContainers:!0})}),i=await o.json();i.success?(showNotification(e+" restored to "+a,"success"),setTimeout(function(){location.reload()},1500)):showNotification("Restore failed: "+(i.error||"Unknown"),"error")}catch(n){showNotification("Restore error: "+n.message,"error")}}})(),(function(){injectModal("stats-modal",`

\u{1F4CA} Resource Monitor

Loading container stats...
\u{1F4C8} Loading 24-hour aggregated metrics...
\u{1F4CA} Choose a container and time range to view history.
\u{1F514} Loading alert configurations...
`);const h=document.getElementById("stats-modal"),L=document.getElementById("container-stats-btn"),A=document.getElementById("stats-cancel"),I=document.getElementById("stats-refresh-btn"),D=document.getElementById("stats-auto-refresh"),R=document.getElementById("stats-container"),H=document.getElementById("stats-aggregated-container"),P=document.getElementById("stats-alerts-container"),v=document.getElementById("stats-last-update");let C=null,x=null;function $(d){if(d===0||!d)return"0 B";const w=1024,y=["B","KB","MB","GB"],t=Math.floor(Math.log(d)/Math.log(w));return parseFloat((d/Math.pow(w,t)).toFixed(1))+" "+y[t]}function E(d){return d<30?"#2ecc71":d<70?"#f39c12":"#e74c3c"}function M(d){return d<50?"#2ecc71":d<80?"#f39c12":"#e74c3c"}async function S(){try{let d=null,w=!1;try{const e=await(await fetch("/api/v1/monitoring/stats")).json();e.success&&e.stats&&(d=e.stats,w=!0,x=e.stats)}catch{}if(!w){const e=await(await fetch("/api/v1/stats/containers")).json();if(e.success&&e.stats){d={};for(const a of e.stats)d[a.name]={name:a.name,current:{cpu:a.cpu,memory:{percent:a.memory.percent,usage:a.memory.used,limit:a.memory.limit,usageMB:Math.round(a.memory.used/1048576),limitMB:Math.round(a.memory.limit/1048576)},network:{rxBytes:a.network.rx,txBytes:a.network.tx,rxMB:(a.network.rx/1048576).toFixed(1),txMB:(a.network.tx/1048576).toFixed(1)},disk:{readMB:0,writeMB:0}},status:a.status};x=d}}if(!d||Object.keys(d).length===0){R.innerHTML='
No running containers found
';return}let y='
';for(const[t,e]of Object.entries(d)){const a=e.current||e,o=a.cpu?.percent||0,i=a.memory?.percent||0,n=E(o),s=M(i),l=a.memory?.usage||a.memory?.used||0,m=a.memory?.limit||0,k=a.network?.rxBytes||a.network?.rx||0,j=a.network?.txBytes||a.network?.tx||0,_=e.aggregated;y+=`
${e.name||t} ${_?`avg ${_.cpu?.avg?.toFixed(0)||0}% cpu`:""} ${e.status||"running"}
CPU
${o.toFixed(1)}%
Memory
${i.toFixed(1)}%
${$(l)} / ${$(m)}
Network
\u2193 ${$(k)} / \u2191 ${$(j)}
`}y+="
",R.innerHTML=y,v.textContent="Updated: "+new Date().toLocaleTimeString()}catch(d){R.innerHTML=`
\u274C Failed to load stats: ${escapeHtml(d.message)}
`}}async function B(){if(!H)return;const d=x;if(!d||Object.keys(d).length===0){H.innerHTML='
\u{1F4C8}No monitoring data available. Open the Live Stats tab first.
';return}let w='
';for(const[y,t]of Object.entries(d)){const e=t.aggregated;e&&(w+=`
${t.name||y}
${e.cpu?.avg?.toFixed(1)||0}%Avg CPU
${e.cpu?.max?.toFixed(1)||0}%Max CPU
${e.memory?.avg?.toFixed(1)||0}%Avg Mem
${e.memory?.max?.toFixed(1)||0}%Max Mem
${e.dataPoints?`
${e.dataPoints} data points over ${e.timeRange||24}h
`:""}
`)}w+="
",H.innerHTML=w}async function U(){if(!P)return;P.innerHTML='
Loading alerts...
';const d=x;if(!d||Object.keys(d).length===0){P.innerHTML='
\u{1F514}No containers found. Open the Live Stats tab first.
';return}let w=!1;try{w=(await(await fetch("/api/v1/license/feature/resource-alerts")).json()).available}catch{w=!1}let y=[];try{const s=await(await fetch("/api/v1/monitoring/alerts?limit=50")).json();s.success&&(y=s.history||[])}catch{}let t={};try{const s=await(await fetch("/api/v1/monitoring/alerts/config")).json();s.success&&(t=s.configs||{})}catch{}const a=Object.entries(d).map(([n,s])=>{const l=t[n]||{cpuThreshold:80,memoryThreshold:90,diskIOThreshold:50,autoRestart:!1,enabled:!1};return` ${s.name||n} `}).join(""),o=y.map(n=>{const s=new Date(n.timestamp).toLocaleString(),l=n.notified?"\u2713":"\u2014";return` ${s} ${n.containerName||n.containerId} ${n.metric||n.type} ${typeof n.value=="number"?n.value.toFixed(1):n.value}${n.metric==="disk"?" MB/s":"%"} ${l} ${n.autoRestartTriggered?"\u21BB":""} `}).join(""),i=w?`

\u2699\uFE0F Alert Configuration

Configure notifications \u2192
${a}
Container CPU % Mem % Disk I/O MB/s Auto-Restart
`:`
\u2B50 Premium Feature

Upgrade to configure resource alert thresholds per container.

`;P.innerHTML=` ${i}

\u{1F4CB} Recent Alerts

${o?`
${o}
Time Container Metric Value \u2713?
`:'
No alerts recorded yet.
'}
`,document.getElementById("save-all-alerts")?.addEventListener("click",async()=>{const n={};document.querySelectorAll("#stats-alerts-container tr[data-container]").forEach(s=>{const l=s.dataset.container;n[l]={cpuThreshold:parseInt(s.querySelector(".alert-cpu")?.value)||80,memoryThreshold:parseInt(s.querySelector(".alert-mem")?.value)||90,diskIOThreshold:parseInt(s.querySelector(".alert-disk")?.value)||50,autoRestart:!!s.querySelector(".alert-autorestart")?.checked,enabled:!0}});try{const l=await(await secureFetch("/api/v1/monitoring/alerts/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({configs:n})})).json(),m=document.getElementById("save-all-alerts");m.textContent=l.success?"\u2705 Saved":"\u274C Failed",setTimeout(()=>{m.textContent="Save All"},2e3)}catch{const l=document.getElementById("save-all-alerts");l.textContent="\u274C Error",setTimeout(()=>{l.textContent="Save All"},2e3)}}),document.getElementById("go-to-notifications")?.addEventListener("click",n=>{n.preventDefault(),h.classList.remove("show"),b(),document.getElementById("manage-notifications")?.click()}),document.querySelectorAll(".alert-test-btn").forEach(n=>{n.addEventListener("click",async()=>{const s=n.textContent;n.textContent="...";try{await secureFetch(`/api/v1/monitoring/alerts/${n.dataset.container}/test`,{method:"POST"}),n.textContent="\u2705",showNotification("Test alert sent for "+n.dataset.name,"success",3e3)}catch{n.textContent="\u274C"}setTimeout(()=>{n.textContent=s},2e3)})}),document.getElementById("upgrade-for-alerts")?.addEventListener("click",()=>{h.classList.remove("show"),b(),typeof openLicenseModal=="function"&&openLicenseModal()})}function T(){C&&clearInterval(C),D?.checked&&(C=setInterval(S,DC.POLL.STATS))}function b(){C&&(clearInterval(C),C=null)}L?.addEventListener("click",()=>{h.classList.add("show"),S(),T()}),A?.addEventListener("click",()=>{h.classList.remove("show"),b()}),h?.addEventListener("click",d=>{d.target===h&&(h.classList.remove("show"),b())}),I?.addEventListener("click",S),D?.addEventListener("change",()=>{D.checked?T():b()}),document.querySelector('[data-panel="stats-aggregated"]')?.addEventListener("click",B),document.querySelector('[data-panel="stats-alerts"]')?.addEventListener("click",U);const N=document.getElementById("stats-history-container"),O=document.getElementById("stats-history-container-area"),p=document.querySelectorAll(".stats-range-btn");let u="1h";function f(d){switch(d){case"1h":return 3600*1e3;case"24h":return 1440*60*1e3;case"7d":return 10080*60*1e3;case"30d":return 720*60*60*1e3;case"1y":return 365*24*60*60*1e3;default:return 3600*1e3}}function g(d){return d==="raw"?"live (10s samples)":d==="hourly"?"hourly average":d==="daily"?"daily average":d}function z(d,w,y,t,e){if(!d||d.length===0)return`
No data for ${escapeHtml(t)}
`;const a=d.map(w).filter(q=>q!=null);if(a.length===0)return`
No data for ${escapeHtml(t)}
`;const o=Math.max(...a,1),i=Math.min(...a,0),n=o-i||1,s=600,l=80,m=4,k=(s-m*2)/Math.max(a.length-1,1),j=a.map((q,J)=>{const X=m+J*k,Q=l-m-(q-i)/n*(l-m*2);return`${X.toFixed(1)},${Q.toFixed(1)}`}).join(" "),_=a[a.length-1],F=a.reduce((q,J)=>q+J,0)/a.length;return`
${escapeHtml(t)} last ${_.toFixed(1)}${e} \xB7 avg ${F.toFixed(1)}${e} \xB7 max ${o.toFixed(1)}${e}
`}function r(){if(!N)return;const d=x||{},w=N.value,y=Object.entries(d);if(y.length===0){N.innerHTML='';return}N.innerHTML=y.map(([t,e])=>``).join(""),w&&d[w]&&(N.value=w)}async function c(){if(!O||!N)return;const d=N.value;if(!d){O.innerHTML='
\u{1F4CA}No container selected.
';return}const w=Date.now(),y=w-f(u);O.innerHTML='
Loading history...
';try{const e=await(await fetch(`/api/v1/monitoring/history/${encodeURIComponent(d)}?startTime=${y}&endTime=${w}`)).json();if(!e.success)throw new Error(e.error||"Failed to load history");const a=e.samples||[],o=e.tier||"raw";if(a.length===0){O.innerHTML=`
\u{1F4CA}No data for the last ${u}. Tier: ${g(o)}.
`;return}const i=o==="raw",n=i?j=>j.cpu?.percent:j=>j.cpu?.avg,s=i?j=>j.memory?.percent:j=>j.memory?.avgPercent,l=i?j=>j.network?.rxMB||0:j=>j.network?.rxMB||0,m=i?j=>j.network?.txMB||0:j=>j.network?.txMB||0;let k=`
${a.length} samples \xB7 ${escapeHtml(g(o))} \xB7 ${new Date(y).toLocaleString()} \u2192 ${new Date(w).toLocaleString()}
`;k+=z(a,n,"#2ecc71","CPU","%"),k+=z(a,s,"#3498db","Memory","%"),k+=z(a,l,"#9b59b6","Network RX"," MB"),k+=z(a,m,"#e67e22","Network TX"," MB"),O.innerHTML=k}catch(t){O.innerHTML=`
\u26A0\uFE0FFailed to load history: ${escapeHtml(t.message)}
`}}p.forEach(d=>{d.addEventListener("click",()=>{p.forEach(w=>w.classList.remove("active")),d.classList.add("active"),u=d.dataset.range,c()})}),N?.addEventListener("change",c),document.querySelector('[data-panel="stats-history"]')?.addEventListener("click",()=>{r(),c()})})(),(function(){injectModal("health-modal",`

\u{1F3E5} Health Check Dashboard

Loading health status...
\u{1F6A8} Loading incidents...
\u2699\uFE0F Loading configuration...

\u{1F30D} Global Settings

Applies to all health checks. Settings are stored locally in this browser.

How often each service's health endpoint is checked.
How often container statistics (CPU/memory) are sampled.
Cap on stored history records per service.
Health history older than this is pruned.
Warn when disk usage exceeds this level.
`);const h=document.getElementById("health-modal"),L=document.getElementById("health-check-btn"),A=document.getElementById("health-cancel"),I=document.getElementById("health-refresh-btn"),D=document.getElementById("health-status-container"),R=document.getElementById("health-incidents-container"),H=document.getElementById("health-config-container"),P=document.getElementById("health-last-update"),v=document.getElementById("health-add-btn"),C=document.getElementById("health-config-form"),x=document.getElementById("health-form-title"),$=document.getElementById("health-form-cancel"),E=document.getElementById("health-form-save"),M="dashcaddy-health-settings",S={retentionDays:30,pollingInterval:60,statsPollingInterval:30,maxEntriesPerService:500,diskUsageThreshold:80},B=document.getElementById("health-global-save"),U=document.getElementById("health-global-reset"),T=document.getElementById("health-global-status"),b=document.getElementById("health-setting-retention"),N=document.getElementById("health-setting-interval"),O=document.getElementById("health-setting-stats-interval"),p=document.getElementById("health-setting-max-entries"),u=document.getElementById("health-setting-disk-threshold");function f(){try{const i=safeGet(M),n=i?JSON.parse(i):{};return Object.assign({},S,n)}catch{return Object.assign({},S)}}function g(){const i=f();b&&(b.value=i.retentionDays),N&&(N.value=i.pollingInterval),O&&(O.value=i.statsPollingInterval),p&&(p.value=i.maxEntriesPerService),u&&(u.value=i.diskUsageThreshold)}function z(){const i={retentionDays:Math.max(1,Math.min(3650,parseInt(b?.value)||S.retentionDays)),pollingInterval:Math.max(5,Math.min(3600,parseInt(N?.value)||S.pollingInterval)),statsPollingInterval:Math.max(5,Math.min(3600,parseInt(O?.value)||S.statsPollingInterval)),maxEntriesPerService:Math.max(10,Math.min(1e5,parseInt(p?.value)||S.maxEntriesPerService)),diskUsageThreshold:Math.max(50,Math.min(99,parseInt(u?.value)||S.diskUsageThreshold))};try{safeSet(M,JSON.stringify(i)),g(),T&&(T.textContent="Saved \u2713",T.style.color="var(--ok-fg)",setTimeout(()=>{T&&(T.textContent="")},2500)),typeof showNotification=="function"&&showNotification("Global health settings saved","success")}catch(n){T&&(T.textContent="Save failed",T.style.color="var(--bad-fg)"),typeof showNotification=="function"&&showNotification("Failed to save settings: "+n.message,"error")}}function r(){try{safeSet(M,JSON.stringify(S))}catch{}g(),T&&(T.textContent="Reset to defaults \u2713",T.style.color="var(--ok-fg)",setTimeout(()=>{T&&(T.textContent="")},2500))}g(),B?.addEventListener("click",z),U?.addEventListener("click",r);let c=null;function d(i){return i>=99.9?"var(--ok-fg)":i>=95?"#f39c12":"var(--bad-fg)"}function w(i){const n={critical:"var(--bad-fg)",high:"#ff6b6b",medium:"#f39c12",low:"var(--muted)"};return`${i}`}async function y(){try{const n=await(await fetch("/api/v1/health-checks/status")).json();if(!n.success||!n.status||Object.keys(n.status).length===0){D.innerHTML='
\u{1F3E5}No health checks configured. Go to the Configure tab to add services.
';return}const s=Object.values(n.status);let l='';l+='',l+='',l+='',l+='';for(const m of s){const k=m.status==="up",j=k?"var(--dot-ok)":"var(--dot-bad)",_=m.uptime?.["24h"]??"-",F=m.uptime?.["7d"]??"-",q=m.avgResponseTime!=null?Math.round(m.avgResponseTime)+"ms":"-",J=m.timestamp?timeAgo(m.timestamp):"-";l+=``,l+=``,l+=``,l+=``,l+=``,l+=``,l+=``,l+="",l+=``}l+="
ServiceStatusUptime 24hUptime 7dAvg ResponseLast Check
${escapeHtml(m.name||m.serviceId)}${k?"Up":"Down"}${typeof _=="number"?_.toFixed(1)+"%":_}${typeof F=="number"?F.toFixed(1)+"%":F}${q}${J}
",D.innerHTML=l,P.textContent="Updated "+new Date().toLocaleTimeString(),D.querySelectorAll("tr[data-health-id]").forEach(m=>{m.addEventListener("click",async()=>{const k=m.dataset.healthId,j=document.getElementById("health-detail-"+k);if(j){if(j.style.display!=="none"){j.style.display="none";return}j.style.display="";try{const F=await(await fetch(`/api/v1/health-checks/${k}/stats?hours=24`)).json();if(F.success&&F.stats){const q=F.stats,J=q.responseTime||{};j.querySelector("td").innerHTML=`
Total Checks
${q.totalChecks||0}
Uptime
${(q.uptime||0).toFixed(2)}%
Avg Response
${Math.round(J.avg||0)}ms
P95 / P99
${Math.round(J.p95||0)}ms / ${Math.round(J.p99||0)}ms
Min Response
${Math.round(J.min||0)}ms
Max Response
${Math.round(J.max||0)}ms
Up Checks
${q.upChecks||0}
Down Checks
${q.downChecks||0}
`}else j.querySelector("td").innerHTML='
No detailed stats available for this period.
'}catch(_){j.querySelector("td").innerHTML=`
Failed: ${escapeHtml(_.message)}
`}}})})}catch(i){D.innerHTML=`
Failed to load health status: ${escapeHtml(i.message)}
`}}async function t(){try{const[i,n]=await Promise.all([fetch("/api/v1/health-checks/incidents"),fetch("/api/v1/health-checks/incidents/history?limit=50")]),s=await i.json(),l=await n.json();let m="";const k=s.success&&s.incidents?s.incidents:[];if(k.length>0){m+='

Open Incidents ('+k.length+")

";for(const _ of k)m+=`
${escapeHtml(_.serviceId)} ${w(_.severity)}
${escapeHtml(_.message)}
Started ${timeAgo(_.createdAt)} \xB7 ${_.occurrences||1} occurrence(s)
`;m+="
"}else m+='
All services operational \u2014 no open incidents
';const j=l.success&&l.history?l.history:[];if(j.length>0){m+='

Incident History

',m+='',m+='';for(const _ of j){const F=_.status==="resolved",q=F&&_.duration?_.duration<6e4?Math.round(_.duration/1e3)+"s":Math.round(_.duration/6e4)+"m":"-";m+='',m+=``,m+=``,m+=``,m+=``,m+=``,m+=``,m+=""}m+="
ServiceTypeSeverityStatusDurationWhen
${escapeHtml(_.serviceId)}${escapeHtml(_.type)}${w(_.severity)}${_.status}${q}${timeAgo(_.createdAt)}
"}R.innerHTML=m||'
\u{1F6A8}No incidents recorded yet.
'}catch(i){R.innerHTML=`
Failed: ${escapeHtml(i.message)}
`}}async function e(){try{const n=await(await fetch("/api/v1/health-checks/status")).json(),s=n.success&&n.status?Object.values(n.status):[];if(s.length===0){H.innerHTML='
\u2699\uFE0FNo health checks configured yet. Click "Add Health Check" below.
';return}let l='';l+='';for(const m of s){const k=m.status==="up";l+='',l+=``,l+=``,l+=``,l+='"}l+="
ServiceStatusSLA TargetActions
${escapeHtml(m.name||m.serviceId)}${k?"Up":"Down"}${m.sla?.target?m.sla.target+"%":"-"}',l+=``,l+=``,l+="
",H.innerHTML=l}catch(i){H.innerHTML=`
Failed: ${escapeHtml(i.message)}
`}}function a(i,n,s,l,m,k,j){c=i||null,x.textContent=i?"Edit Health Check":"Add Health Check",document.getElementById("health-form-id").value=i||"",document.getElementById("health-form-id").disabled=!!i,document.getElementById("health-form-name").value=n||"",document.getElementById("health-form-url").value=s||"",document.getElementById("health-form-timeout").value=l||1e4,document.getElementById("health-form-codes").value=m||"200",document.getElementById("health-form-sla").value=k||99.9,document.getElementById("health-form-slow").value=j||5e3,C.style.display="",v.style.display="none"}function o(){C.style.display="none",v.style.display="",c=null}v?.addEventListener("click",()=>a("","","",1e4,"200",99.9,5e3)),$?.addEventListener("click",o),E?.addEventListener("click",async()=>{const i=c||document.getElementById("health-form-id").value.trim();if(!i)return showNotification("Service ID is required","warning");const n=document.getElementById("health-form-url").value.trim();if(!n)return showNotification("URL is required","warning");const s=document.getElementById("health-form-codes").value.split(",").map(m=>parseInt(m.trim())).filter(Boolean),l={name:document.getElementById("health-form-name").value.trim()||i,url:n,timeout:parseInt(document.getElementById("health-form-timeout").value)||1e4,expectedStatusCodes:s.length?s:[200],sla:{target:parseFloat(document.getElementById("health-form-sla").value)||99.9},slowResponseThreshold:parseInt(document.getElementById("health-form-slow").value)||5e3};try{E.textContent="Saving...",E.disabled=!0;const k=await(await secureFetch(`/api/v1/health-checks/${encodeURIComponent(i)}/configure`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)})).json();if(!k.success)throw new Error(k.error||"Save failed");o(),e(),y()}catch(m){showNotification("Error: "+m.message,"error")}finally{E.textContent="Save",E.disabled=!1}}),document.addEventListener("health-edit",async i=>{const n=i.detail;a(n,"","",1e4,"200",99.9,5e3)}),document.addEventListener("health-delete",async i=>{const n=i.detail;if(confirm(`Delete health check for "${n}"?`))try{const l=await(await secureFetch(`/api/v1/health-checks/${encodeURIComponent(n)}/configure`,{method:"DELETE"})).json();if(!l.success)throw new Error(l.error);e(),y()}catch(s){showNotification("Error: "+s.message,"error")}}),L?.addEventListener("click",()=>{h?.classList.add("show"),y()}),wireModal(h,A),I?.addEventListener("click",y),document.querySelector('[data-panel="health-incidents"]')?.addEventListener("click",t),document.querySelector('[data-panel="health-config"]')?.addEventListener("click",e)})(),(function(){injectModal("updates-modal",`

\u2B06\uFE0F Update Management

\u{1F4E6} Click "Check for Updates" to scan containers.
Loading update history...
\u{1F916} Loading auto-update configuration...
DashCaddy
Loading...
\u{1F4E6}No self-update history.
`);const h=document.getElementById("updates-modal"),L=document.getElementById("updates-btn"),A=document.getElementById("updates-cancel"),I=document.getElementById("updates-check-btn"),D=document.getElementById("updates-available-container"),R=document.getElementById("updates-history-container"),H=document.getElementById("updates-auto-container"),P=document.getElementById("updates-last-check");async function v(){try{const t=await(await fetch("/api/v1/updates/available")).json();if(!t.success)throw new Error(t.error);const e=t.updates||[];if(e.length===0){D.innerHTML='
\u2705All containers are up to date.
',P.textContent="",document.getElementById("updates-update-all-btn").style.display="none",document.getElementById("updates-count-badge").style.display="none",window._pendingUpdates=[];return}let a='';a+='';for(const n of e){const s=(()=>{const l=window.APPS||[];for(const m of l)if(m.containerId===n.containerId||m.name===n.containerName||m.id===n.containerName)return m.id;return n.containerName})();a+=``,a+=``,a+=``,a+=``,a+=``,a+='"}a+="
ContainerImageCurrentLatestActions
${escapeHtml(n.containerName)}${escapeHtml(n.imageName)}${escapeHtml(n.currentDigest)}${escapeHtml(n.latestDigest)}',a+=``,a+=``,a+="
",D.innerHTML=a,P.textContent=e.length+" update(s) available";const o=document.getElementById("updates-count-badge"),i=document.getElementById("updates-update-all-btn");o&&(o.textContent=e.length+" pending",o.style.display=""),i&&e.length>0&&(i.style.display=""),window._pendingUpdates=e,D.querySelectorAll(".update-now-btn").forEach(n=>{n.addEventListener("click",async()=>{const s=n.dataset.id,l=n.dataset.name;if(confirm(`Update "${l}" to the latest version? The container will restart.`)){n.textContent="Updating...",n.disabled=!0;try{const k=await(await secureFetch(`/api/v1/updates/update/${encodeURIComponent(s)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({autoRollback:!0})})).json();if(k.success)n.textContent="Done!",n.style.background="var(--ok-fg)",setTimeout(()=>v(),2e3);else throw new Error(k.error||"Update failed")}catch(m){n.textContent="Failed",n.style.color="var(--bad-fg)",showNotification("Update error: "+m.message,"error"),setTimeout(()=>{n.textContent="Update",n.disabled=!1,n.style.color="",n.style.background=""},3e3)}}})}),D.querySelectorAll(".rollback-btn").forEach(n=>{n.addEventListener("click",async()=>{const s=n.dataset.id,l=n.dataset.name;if(confirm(`Rollback "${l}" to its previous version?`)){n.textContent="Rolling back...",n.disabled=!0;try{const k=await(await secureFetch(`/api/v1/updates/rollback/${encodeURIComponent(s)}`,{method:"POST"})).json();if(k.success)n.textContent="Rolled back!",setTimeout(()=>v(),2e3);else throw new Error(k.error||"Rollback failed")}catch(m){n.textContent="Failed",showNotification("Rollback error: "+m.message,"error"),setTimeout(()=>{n.textContent="Rollback",n.disabled=!1},3e3)}}})})}catch(y){D.innerHTML=`
Failed: ${escapeHtml(y.message)}
`}}async function C(){const y=window._pendingUpdates||[];if(!y.length)return;const t=document.getElementById("updates-update-all-btn");if(!confirm(`Update all ${y.length} containers? Each will restart.`))return;t.textContent="\u23F3 Updating...",t.disabled=!0;let e=0,a=0;for(const o of y)try{(await(await secureFetch(`/api/v1/updates/update/${encodeURIComponent(o.containerId)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({autoRollback:!0})})).json()).success?e++:a++}catch{a++}t.textContent="\u2705 Done",showNotification(`Update all: ${e} succeeded, ${a} failed.`,e>0&&a===0?"success":"error"),setTimeout(()=>{t.textContent="\u2B06\uFE0F Update All",t.disabled=!1,v()},3e3)}document.getElementById("updates-update-all-btn")?.addEventListener("click",C);async function x(){I.textContent="\u{1F50D} Checking...",I.disabled=!0;try{const t=await(await secureFetch("/api/v1/updates/check",{method:"POST"})).json();if(!t.success)throw new Error(t.error);I.textContent="\u2705 Done!",await v()}catch(y){I.textContent="\u274C Failed",showNotification("Check error: "+y.message,"error")}setTimeout(()=>{I.textContent="\u{1F50D} Check for Updates",I.disabled=!1},3e3)}async function $(){try{R.innerHTML='
Loading...
';const t=await(await fetch("/api/v1/updates/history?limit=50")).json(),e=t.success&&t.history?t.history:[];if(e.length===0){R.innerHTML='
\u{1F4CB}No update history yet.
';return}let a='';a+='';for(const o of e){const i=o.status==="success",n=o.duration?o.duration<1e3?o.duration+"ms":Math.round(o.duration/1e3)+"s":"-";a+='',a+=``,a+=``,a+=``,a+=``,a+=``,a+="",!i&&o.error&&(a+=``)}a+="
WhenContainerImageDurationStatus
${timeAgo(o.timestamp)}${escapeHtml(o.containerName)}${escapeHtml(o.imageName)}${n}${i?"\u2713 success":"\u2717 failed"}
${escapeHtml(o.error)}
",R.innerHTML=a}catch(y){R.innerHTML=`
Failed: ${escapeHtml(y.message)}
`}}async function E(){try{H.innerHTML='
Loading...
';const[y,t]=await Promise.all([fetch("/api/v1/stats/containers"),fetch("/api/v1/updates/auto-update")]),e=await y.json(),a=await t.json(),o=e.success&&e.stats?e.stats:[],i=a.success&&a.config?a.config:{};if(o.length===0){H.innerHTML='
\u{1F916}No running containers found.
';return}let n='
Auto-updates run during maintenance window (default 2AM-4AM). Daily = every day, Weekly = Sundays, Monthly = 1st of month.
';n+='',n+='';for(const s of o){const l=s.name||s.Names?.[0]?.replace(/^\//,"")||s.Id?.substring(0,12),m=s.containerId||s.Id,k=i[m]||{},j=k.enabled?k.schedule||"weekly":"",_=k.autoRollback!==!1,F=k.maintenanceWindow||"",q=k.lastAutoUpdate?timeAgo(k.lastAutoUpdate):"Never";n+=``,n+=``,n+=``,n+=``,n+=``,n+=``,n+=``,n+=""}n+="
ContainerScheduleWindowRollbackLast RunActions
${escapeHtml(l)} ${q}
",H.innerHTML=n,H.querySelectorAll(".save-auto-btn").forEach(s=>{s.addEventListener("click",async()=>{const l=s.dataset.id,m=s.closest("tr"),k=m.querySelector(".auto-schedule").value,j=m.querySelector(".auto-rollback").checked,_=m.querySelector(".auto-window").value.trim();s.textContent="Saving...",s.disabled=!0;try{const q=await(await secureFetch(`/api/v1/updates/auto-update/${encodeURIComponent(l)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({enabled:!!k,schedule:k||"weekly",autoRollback:j,maintenanceWindow:_||void 0})})).json();if(q.success)s.textContent="\u2713 Saved";else throw new Error(q.error)}catch(F){s.textContent="\u2717 Error",showNotification("Save error: "+F.message,"error")}setTimeout(()=>{s.textContent="Save",s.disabled=!1},2e3)})})}catch(y){H.innerHTML=`
Failed: ${escapeHtml(y.message)}
`}}const M=document.getElementById("dashcaddy-current-version"),S=document.getElementById("dashcaddy-update-badge"),B=document.getElementById("dashcaddy-update-details"),U=document.getElementById("dashcaddy-new-version"),T=document.getElementById("dashcaddy-changelog"),b=document.getElementById("dashcaddy-apply-btn"),N=document.getElementById("dashcaddy-check-btn"),O=document.getElementById("dashcaddy-rollback-btn"),p=document.getElementById("dashcaddy-status-bar"),u=document.getElementById("dashcaddy-history-container");let f=null;function g(y,t){p&&(p.style.display="block",p.style.background=t==="error"?"var(--bad-bg)":t==="success"?"var(--ok-bg)":"var(--bg)",p.style.color=t==="error"?"var(--bad-fg)":t==="success"?"var(--ok-fg)":"var(--fg)",p.textContent=y)}async function z(){try{const t=await(await fetch("/api/v1/system/version")).json();if(t.success){const e=t.commit&&t.commit!=="unknown"?t.commit:null;M.textContent="v"+t.version+(e?" ("+e.substring(0,7)+")":"")}}catch{M.textContent="Unable to fetch version"}}async function r(y){y||(N.textContent="Checking...",N.disabled=!0);try{const e=await(await fetch("/api/v1/system/update-check")).json();if(f=e,e.success&&e.available&&e.remote){S.style.display="",B.style.display="",U.textContent="v"+e.remote.version,T.textContent=e.remote.changelog||"No changelog available.";const a=document.getElementById("updates-btn");if(a&&!a.querySelector(".update-dot")){const i=document.createElement("span");i.className="update-dot",i.style.cssText="position:absolute;top:2px;right:2px;width:8px;height:8px;border-radius:50%;background:var(--accent);",a.style.position="relative",a.appendChild(i)}const o=document.getElementById("updates-dashcaddy-tab");if(o&&!o.querySelector(".update-dot")){const i=document.createElement("span");i.className="update-dot",i.style.cssText="display:inline-block;width:6px;height:6px;border-radius:50%;background:var(--accent);margin-left:4px;vertical-align:middle;",o.appendChild(i)}}else S.style.display="none",B.style.display="none",await z(),y||g("You are running the latest version.","success");y||(N.textContent="Check for Updates",N.disabled=!1)}catch(t){y||(g("Failed to check: "+t.message,"error"),N.textContent="Check for Updates",N.disabled=!1)}}async function c(){if(!confirm("Apply DashCaddy update? The API container will restart."))return!1;b.textContent="Updating...",b.disabled=!0,g("Downloading and applying update...","info");try{const t=await(await secureFetch("/api/v1/system/update-apply",{method:"POST"})).json();if(t.success)return g("Update initiated: v"+(t.fromVersion||"?")+" \u2192 v"+(t.toVersion||"?")+". The container will restart shortly.","success"),b.textContent="Applied!",document.querySelectorAll(".update-dot").forEach(e=>e.remove()),!0;throw new Error(t.error||"Update failed")}catch(y){throw g("Update failed: "+y.message,"error"),b.textContent="Update Now",b.disabled=!1,y}}async function d(){try{const t=await(await fetch("/api/v1/system/update-history")).json(),e=t.success&&t.history?t.history:[];if(e.length===0){u.innerHTML='
\u{1F4E6}No self-update history.
';return}let a='';a+='';for(const o of e){const i=o.status==="success"?"\u2713 success":o.status==="pending"?"\u23F3 pending":o.status==="partial"?"\u26A0 partial":"\u2717 "+o.status,n=o.status==="success"?"var(--ok-fg)":o.status==="pending"?"var(--muted)":"var(--bad-fg)";a+='',a+='",a+='",a+='",a+='",a+="",o.error&&(a+='"),o.note&&(a+='")}a+="
WhenVersionFromStatus
'+timeAgo(o.timestamp)+"v'+escapeHtml(o.version)+(o.rollback?" (rollback)":"")+"v'+escapeHtml(o.fromVersion||"?")+"'+i+"
'+escapeHtml(o.error)+"
'+escapeHtml(o.note)+"
",u.innerHTML=a}catch(y){u.innerHTML='
Failed: '+escapeHtml(y.message)+"
"}}async function w(){try{const t=await(await fetch("/api/v1/system/rollback-versions")).json(),e=t.success&&t.versions?t.versions:[];if(e.length===0){showNotification("No rollback versions available.","info");return}const a=prompt(`Available rollback versions: `+e.join(` `)+` Enter version to rollback to:`);if(!a)return;if(!e.includes(a)){showNotification("Invalid version: "+a,"error");return}if(!confirm("Rollback DashCaddy to v"+a+"? The container will restart."))return;g("Rolling back to v"+a+"...","info");const i=await(await secureFetch("/api/v1/system/rollback",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({version:a})})).json();if(i.success)g("Rollback to v"+a+" initiated. Container will restart.","success");else throw new Error(i.error||"Rollback failed")}catch(y){g("Rollback failed: "+y.message,"error")}}N?.addEventListener("click",()=>r(!1)),b?.addEventListener("click",()=>c().catch(()=>{})),O?.addEventListener("click",w),I?.addEventListener("click",x),L?.addEventListener("click",()=>{h?.classList.add("show"),v()}),wireModal(h,A),window.openUpdateModal=function(y){h?.classList.add("show"),v().then(()=>{if(!y)return;const t=D.querySelector(`[data-app-id="${y}"]`);t&&(t.scrollIntoView({behavior:"smooth",block:"center"}),t.style.background="rgba(249,115,22,0.15)",setTimeout(()=>{t.style.background=""},3e3))})},document.querySelector('[data-panel="updates-history"]')?.addEventListener("click",$),document.querySelector('[data-panel="updates-auto"]')?.addEventListener("click",E),document.querySelector('[data-panel="updates-dashcaddy"]')?.addEventListener("click",()=>{z(),d(),f||r(!0)}),window.dcApplyUpdate=c,window.dcCheckForUpdate=r,setTimeout(()=>r(!0),5e3)})(),(function(){injectModal("docker-resources-modal",`

\u{1F433} Docker Resources

Loading...
Loading...
Loading...
`);const h=document.getElementById("docker-resources-modal"),L=document.getElementById("docker-resources-btn"),A=document.getElementById("dr-close");function I(P){if(!P||P===0)return"0 B";const v=["B","KB","MB","GB","TB"],C=Math.floor(Math.log(Math.abs(P))/Math.log(1024));return(P/Math.pow(1024,C)).toFixed(1)+" "+v[C]}async function D(){const P=document.getElementById("dr-vol-list");try{const C=(await getJSON("/api/v1/docker/volumes")).volumes||[];if(C.length===0){P.innerHTML='
\u{1F4E6}No volumes found.
';return}let x='';x+='';for(const $ of C){const E=$.name==="buildkit"||$.name.length===64;x+='',x+=``,x+=``,x+=``,x+='"}x+="
NameDriverScopeActions
${escapeHtml($.name.length>40?$.name.substring(0,37)+"...":$.name)}${escapeHtml($.driver)}${escapeHtml($.scope)}',E||(x+=``),x+="
",P.innerHTML=x,P.querySelectorAll(".dr-vol-del").forEach($=>{$.addEventListener("click",async()=>{if(confirm(`Delete volume "${$.dataset.name}"? Data will be lost.`)){$.textContent="...",$.disabled=!0;try{await deleteAPI(`/api/v1/docker/volumes/${encodeURIComponent($.dataset.name)}?force=true`),D()}catch(E){showNotification("Delete failed: "+E.message,"error"),$.textContent="Delete",$.disabled=!1}}})})}catch(v){P.innerHTML=`
Failed: ${escapeHtml(v.message)}
`}}document.getElementById("dr-vol-create")?.addEventListener("click",async()=>{const P=document.getElementById("dr-vol-name"),v=P.value.trim();if(!v){showNotification("Enter a volume name","warning");return}try{await postJSON("/api/v1/docker/volumes",{name:v}),P.value="",showNotification(`Volume "${v}" created`,"success"),D()}catch(C){showNotification("Create failed: "+C.message,"error")}});async function R(){const P=document.getElementById("dr-net-list");try{const C=(await getJSON("/api/v1/docker/networks")).networks||[];if(C.length===0){P.innerHTML='
\u{1F310}No networks found.
';return}let x='';x+='';for(const $ of C){const E=["bridge","host","none"].includes($.name);x+='',x+=``,x+=``,x+=``,x+=``,x+='"}x+="
NameDriverScopeContainersActions
${escapeHtml($.name)}${escapeHtml($.driver)}${escapeHtml($.scope)}${$.containers}',E||(x+=``),x+="
",P.innerHTML=x,P.querySelectorAll(".dr-net-del").forEach($=>{$.addEventListener("click",async()=>{if(confirm(`Delete network "${$.dataset.name}"?`)){$.textContent="...",$.disabled=!0;try{await deleteAPI(`/api/v1/docker/networks/${encodeURIComponent($.dataset.id)}`),R()}catch(E){showNotification("Delete failed: "+E.message,"error"),$.textContent="Delete",$.disabled=!1}}})})}catch(v){P.innerHTML=`
Failed: ${escapeHtml(v.message)}
`}}document.getElementById("dr-net-create")?.addEventListener("click",async()=>{const P=document.getElementById("dr-net-name"),v=document.getElementById("dr-net-driver"),C=P.value.trim();if(!C){showNotification("Enter a network name","warning");return}try{await postJSON("/api/v1/docker/networks",{name:C,driver:v.value}),P.value="",showNotification(`Network "${C}" created`,"success"),R()}catch(x){showNotification("Create failed: "+x.message,"error")}});async function H(){const P=document.getElementById("dr-disk-content");try{const v=await getJSON("/api/v1/docker/disk-usage"),C=[{label:"Images",icon:"\u{1F4C0}",count:v.images.count,size:v.images.size,reclaimable:v.images.reclaimable},{label:"Containers",icon:"\u{1F4E6}",count:v.containers.count,size:v.containers.size,extra:`${v.containers.running} running`},{label:"Volumes",icon:"\u{1F4BE}",count:v.volumes.count,size:v.volumes.size,reclaimable:v.volumes.reclaimable},{label:"Build Cache",icon:"\u{1F527}",count:v.buildCache.count,size:v.buildCache.size,reclaimable:v.buildCache.reclaimable}];let x=`
Total: ${I(v.totalSize)}
`;x+='
';for(const $ of C)x+='
',x+=`
${$.icon} ${$.label} (${$.count})
`,x+=`
${I($.size)}
`,$.reclaimable>0&&(x+=`
Reclaimable: ${I($.reclaimable)}
`),$.extra&&(x+=`
${$.extra}
`),x+="
";x+="
",P.innerHTML=x}catch(v){P.innerHTML=`
Failed: ${escapeHtml(v.message)}
`}}L?.addEventListener("click",()=>{h?.classList.add("show"),D()}),wireModal(h,A),document.querySelector('[data-panel="dr-networks"]')?.addEventListener("click",R),document.querySelector('[data-panel="dr-disk"]')?.addEventListener("click",H)})(),(function(){injectModal("compose-import-modal",`

\u{1F4E6} Import Docker Compose

`);const h=document.getElementById("compose-import-modal"),L=document.getElementById("compose-import-btn"),A=document.getElementById("compose-cancel");wireModal(h,A);let I=null;function D(H){document.getElementById("compose-step-paste").style.display=H==="paste"?"":"none",document.getElementById("compose-step-preview").style.display=H==="preview"?"":"none",document.getElementById("compose-step-progress").style.display=H==="progress"?"":"none"}L?.addEventListener("click",()=>{D("paste"),I=null,document.getElementById("compose-yaml").value="",document.getElementById("compose-stack-name").value="",h?.classList.add("show")}),document.getElementById("compose-file-upload")?.addEventListener("change",H=>{const P=H.target.files[0];if(!P)return;const v=new FileReader;v.onload=()=>{document.getElementById("compose-yaml").value=v.result},v.readAsText(P)}),document.getElementById("compose-parse-btn")?.addEventListener("click",async()=>{const H=document.getElementById("compose-yaml").value.trim(),P=document.getElementById("compose-stack-name").value.trim()||"stack";if(!H){showNotification("Paste a docker-compose.yml","warning");return}const v=document.getElementById("compose-parse-btn"),C=v.textContent;v.textContent="Parsing...",v.disabled=!0;try{const x=await postJSON("/api/v1/apps/import-compose",{yaml:H,stackName:P});I=x,I.stackName=P,R(x),D("preview")}catch(x){showNotification("Parse failed: "+x.message,"error")}finally{v.textContent=C,v.disabled=!1}});function R(H){const P=document.getElementById("compose-preview-content");let v="";H.networks&&H.networks.length>0&&(v+=`
Networks: ${H.networks.map(C=>`${escapeHtml(C)}`).join(", ")}
`),H.volumes&&H.volumes.length>0&&(v+=`
Volumes: ${H.volumes.map(C=>`${escapeHtml(C)}`).join(", ")}
`),v+=`
${H.services.length} service(s)
`,v+='
';for(const C of H.services){const x=C.skip?"var(--bad-fg)":"var(--border)";if(v+=`
`,v+=`
${escapeHtml(C.name)}`,C.skip&&(v+=` \u2014 skipped: ${escapeHtml(C.reason)}`),v+="
",!C.skip&&(v+=`
Image: ${escapeHtml(C.image)}
`,C.ports?.length&&(v+=`
Ports: ${C.ports.map($=>`${$.host}:${$.container}`).join(", ")}
`),C.volumes?.length&&(v+=`
Volumes: ${C.volumes.length}
`),Object.keys(C.environment||{}).length&&(v+=`
Env vars: ${Object.keys(C.environment).length}
`),C.envFileWarning&&(v+=`
\u26A0 ${escapeHtml(C.envFileWarning)}
`),C.resources?.cpus||C.resources?.memory)){const $=[];C.resources.cpus&&$.push(`CPU: ${C.resources.cpus}`),C.resources.memory&&$.push(`Mem: ${C.resources.memory}MB`),v+=`
Limits: ${$.join(", ")}
`}v+="
"}v+="
",P.innerHTML=v}document.getElementById("compose-back-btn")?.addEventListener("click",()=>D("paste")),document.getElementById("compose-deploy-btn")?.addEventListener("click",async()=>{if(!I)return;const H=document.getElementById("compose-deploy-btn");H.textContent="Deploying...",H.disabled=!0,D("progress");const P=document.getElementById("compose-progress-content");P.innerHTML='
Deploying services...
';try{const v=await postJSON("/api/v1/apps/deploy-compose",{services:I.services,networks:I.networks,stackName:I.stackName});let C=`
Stack "${escapeHtml(v.stackName)}" \u2014 Deployment Complete
`;C+='
';for(const x of v.results){const $=x.status==="deployed"||x.status==="created"?"\u2705":x.status==="exists"?"\u26A1":x.status==="skipped"?"\u23ED":"\u274C";C+='
',C+=`${$} ${escapeHtml(x.name)} (${x.type}) \u2014 ${escapeHtml(x.status)}`,x.error&&(C+=` ${escapeHtml(x.error)}`),x.subdomain&&(C+=` \u2192 ${escapeHtml(x.subdomain)}`),x.reason&&(C+=` (${escapeHtml(x.reason)})`),C+="
"}C+="
",C+='',P.innerHTML=C,document.getElementById("compose-done-btn")?.addEventListener("click",()=>{h?.classList.remove("show"),typeof window.loadServices=="function"&&window.loadServices().then(()=>{typeof window.buildGrid=="function"&&window.buildGrid()})}),showNotification(`Stack "${v.stackName}" deployed`,"success")}catch(v){P.innerHTML=`
Deployment failed: ${escapeHtml(v.message)}
`,document.getElementById("compose-retry-btn")?.addEventListener("click",()=>D("paste"))}finally{H.textContent="Deploy All",H.disabled=!1}})})(),(function(){injectModal("exec-modal",`

Terminal

`);const h=document.getElementById("exec-modal"),L=document.getElementById("exec-terminal"),A=document.getElementById("exec-close");let I=null,D=null,R=null;function H(){if(D){try{D.close()}catch{}D=null}if(I){try{I.dispose()}catch{}I=null}R=null,L.innerHTML=""}function P(v,C){if(H(),document.getElementById("exec-title").textContent=`Terminal \u2014 ${C||v}`,h?.classList.add("show"),typeof Terminal>"u"){L.innerHTML='
xterm.js not loaded
';return}I=new Terminal({cursorBlink:!0,fontSize:14,fontFamily:"'Cascadia Code', 'Fira Code', 'Consolas', monospace",theme:{background:"#1e1e1e",foreground:"#d4d4d4",cursor:"#aeafad",selectionBackground:"#264f78"},scrollback:5e3}),typeof FitAddon<"u"&&(R=new FitAddon.FitAddon,I.loadAddon(R)),I.open(L),R&&setTimeout(()=>R.fit(),50);const x=location.protocol==="https:"?"wss:":"ws:";D=new WebSocket(`${x}//${location.host}/ws/exec/${encodeURIComponent(v)}`),D.binaryType="arraybuffer",D.onopen=()=>{if(I.writeln("\x1B[32mConnecting...\x1B[0m"),R){const E=R.proposeDimensions();E&&D.send(JSON.stringify({type:"resize",cols:E.cols,rows:E.rows}))}},D.onmessage=E=>{if(typeof E.data=="string"){try{const M=JSON.parse(E.data);if(M.type==="connected"){I.writeln(`\x1B[32mConnected (${M.shell})\x1B[0m\r `);return}if(M.type==="error"){I.writeln(`\x1B[31mError: ${M.message}\x1B[0m`);return}if(M.type==="exit"){I.writeln(`\r \x1B[33mSession ended.\x1B[0m`);return}}catch{}I.write(E.data)}else I.write(new Uint8Array(E.data))},D.onclose=()=>{I&&I.writeln(`\r \x1B[33mDisconnected.\x1B[0m`)},D.onerror=()=>{I&&I.writeln(`\r \x1B[31mConnection error.\x1B[0m`)},I.onData(E=>{D&&D.readyState===WebSocket.OPEN&&D.send(E)}),I.onResize(({cols:E,rows:M})=>{D&&D.readyState===WebSocket.OPEN&&D.send(JSON.stringify({type:"resize",cols:E,rows:M}))});const $=()=>{R&&R.fit()};window.addEventListener("resize",$),h._resizeHandler=$}A?.addEventListener("click",()=>{H(),h._resizeHandler&&window.removeEventListener("resize",h._resizeHandler),h?.classList.remove("show")}),h?.addEventListener("click",v=>{v.target===h&&(H(),h._resizeHandler&&window.removeEventListener("resize",h._resizeHandler),h?.classList.remove("show"))}),window.openExecModal=P})(),(function(){injectModal("audit-modal",`

\u{1F4DC} Audit Log

Loading audit log...
`);const h=document.getElementById("audit-modal"),L=document.getElementById("audit-log-btn"),A=document.getElementById("audit-cancel"),I=document.getElementById("audit-refresh-btn"),D=document.getElementById("audit-clear-btn"),R=document.getElementById("audit-filter"),H=document.getElementById("audit-log-container"),P=document.getElementById("audit-load-more");let v=0;const C=50;async function x($){try{$||(v=0,H.innerHTML='
Loading...
');const E=R.value;let M=`/api/v1/audit-logs?limit=${C}&offset=${v}`;E&&(M+=`&action=${encodeURIComponent(E)}`);const B=await(await fetch(M)).json(),U=B.success&&B.entries?B.entries:[];if(U.length===0&&!$){H.innerHTML='
\u{1F4DC}No audit log entries yet. Actions will be logged automatically.
',P.style.display="none";return}let T="";$||(T='',T+='');for(const b of U){const N=b.outcome==="success";T+='',T+=``,T+=``,T+=``,T+=``,T+=``,T+="",b.details&&Object.keys(b.details).length>0&&(T+=``)}if(!$)T+="
WhenIPActionResourceResult
${timeAgo(b.timestamp)}${escapeHtml(b.ip||"-")}${escapeHtml(b.action||"-")}${escapeHtml(b.resource||"-")}${N?"\u2713":"\u2717"}
",H.innerHTML=T;else{const b=H.querySelector("table");b&&b.insertAdjacentHTML("beforeend",T)}v+=U.length,P.style.display=U.length>=C?"":"none",H.querySelectorAll(".audit-row").forEach(b=>{b.dataset.wired||(b.dataset.wired="true",b.addEventListener("click",()=>{const N=b.nextElementSibling;N&&N.classList.contains("audit-detail")&&(N.style.display=N.style.display==="none"?"":"none")}))})}catch(E){H.innerHTML=`
Failed: ${escapeHtml(E.message)}
`}}L?.addEventListener("click",()=>{h?.classList.add("show"),x(!1)}),wireModal(h,A),I?.addEventListener("click",()=>x(!1)),R?.addEventListener("change",()=>x(!1)),P?.addEventListener("click",()=>x(!0)),D?.addEventListener("click",async()=>{if(confirm("Clear the entire audit log? This cannot be undone."))try{const E=await(await secureFetch("/api/v1/audit-logs",{method:"DELETE"})).json();E.success?x(!1):showNotification("Error: "+(E.error||"Clear failed"),"error")}catch($){showNotification("Error: "+$.message,"error")}})})(),(function(){injectModal("security-modal",`

\u{1F6E1}\uFE0F Security Center

\u2014 events
\u2014 warnings
\u2014 errors
\u2014 denied
\u2014 hosts

Top Actors (24h)

\u2014

Top Targets (24h)

\u2014
`);const h=document.getElementById("security-modal"),L=document.getElementById("security-center-btn"),A=document.getElementById("sec-cancel"),I=h.querySelectorAll(".sec-tab"),D=h.querySelectorAll(".sec-panel");let R=[],H=[],P=null;I.forEach(r=>{r.addEventListener("click",()=>{I.forEach(c=>c.classList.toggle("active",c===r)),D.forEach(c=>c.style.display=c.dataset.panel===r.dataset.tab?"":"none"),r.dataset.tab==="overview"&&$(),r.dataset.tab==="events"&&b(),r.dataset.tab==="hosts"&&u()})}),L&&L.addEventListener("click",()=>{h.classList.add("show"),$(),C()}),A.addEventListener("click",v),h.addEventListener("click",r=>{r.target===h&&v()});function v(){h.classList.remove("show"),x()}function C(){if(x(),!!document.getElementById("sec-live-tail").checked&&!(typeof EventSource>"u"))try{P=new EventSource("/api/v1/security/events/stream"),P.addEventListener("init",r=>{try{R=JSON.parse(r.data).events||[],N()}catch{}}),P.addEventListener("security",r=>{try{const c=JSON.parse(r.data);R.unshift(c),R.length>500&&(R.length=500);const d=h.querySelector(".sec-tab.active")?.dataset?.tab;d==="events"?N():d==="overview"&&$()}catch{}}),P.onerror=()=>{}}catch(r){console.warn("[security] SSE failed:",r.message)}}function x(){if(P){try{P.close()}catch{}P=null}}document.getElementById("sec-live-tail").addEventListener("change",()=>{h.classList.contains("show")&&C()});async function $(){try{const r=new Date(Date.now()-864e5).toISOString(),[c,d,w]=await Promise.all([fetch(`/api/v1/security/events/stats?since=${encodeURIComponent(r)}`),fetch("/api/v1/security/hosts"),fetch(`/api/v1/security/events?limit=1&since=${encodeURIComponent(r)}`)]),y=(await c.json()).data||{},t=(await d.json()).data?.hosts||[],e=(await w.json()).data?.total||0;document.querySelector('#sec-stats [data-key="total"]').textContent=`${e} events (24h)`,document.querySelector('#sec-stats [data-key="warn"]').textContent=`${y.by_severity?.warn||0} warnings`,document.querySelector('#sec-stats [data-key="error"]').textContent=`${y.by_severity?.error||0} errors`,document.querySelector('#sec-stats [data-key="denied"]').textContent=`${y.by_outcome?.denied||0} denied`,document.querySelector('#sec-stats [data-key="hosts"]').textContent=`${t.length} hosts`,E("sec-top-actors",y.top_actors||[]),E("sec-top-targets",y.top_targets||[])}catch(r){console.warn("[security] refreshOverview failed:",r.message)}}function E(r,c){const d=document.getElementById(r);if(!c.length){d.innerHTML='
No data
';return}d.innerHTML=''+c.map(w=>``).join("")+"
${g(String(w.key))}${w.count}
"}const M=document.getElementById("sec-filter-source"),S=document.getElementById("sec-filter-severity"),B=document.getElementById("sec-filter-host"),U=document.getElementById("sec-filter-actor"),T=document.getElementById("sec-refresh-btn");[M,S,B].forEach(r=>r.addEventListener("change",b)),U.addEventListener("input",z(b,250)),T.addEventListener("click",b);async function b(){try{const r=new URLSearchParams;r.set("limit","200"),M.value&&r.set("source_type",M.value),S.value&&r.set("severity",S.value),B.value&&r.set("source_host",B.value),U.value&&r.set("actor_prefix",U.value),R=(await(await fetch(`/api/v1/security/events?${r}`)).json()).data.events||[],N(),(!B.options.length||B.options.length===1)&&await p()}catch(r){document.getElementById("sec-events-container").innerHTML='
Load failed: '+g(r.message)+"
"}}function N(){const r=document.getElementById("sec-events-container");if(!R.length){r.innerHTML='
No events
';return}r.innerHTML=R.slice(0,200).map(O).join("")}function O(r){const c=r.severity||"info",d={critical:"#c0392b",error:"#e74c3c",warn:"#f39c12",notice:"#3498db",info:"#7f8c8d"}[c]||"#7f8c8d",w=r.ts?new Date(r.ts).toLocaleTimeString():"",y=r.source_type||"",t=r.actor||"\u2014",e=r.target||"",a=r.action||"",o=r.outcome||"";return`
${g(c)} ${g(y)} ${g(t)} ${g(a)} ${g(e)} ${g(o)} ${g(w)}
`}async function p(){try{const c=(await(await fetch("/api/v1/security/hosts")).json()).data?.hosts||[],d=B.value;B.innerHTML=''+c.map(w=>``).join(""),d&&(B.value=d)}catch{}}document.getElementById("sec-host-register-btn").addEventListener("click",f),document.getElementById("sec-hosts-refresh").addEventListener("click",u);async function u(){try{const c=(await(await fetch("/api/v1/security/hosts")).json()).data?.hosts||[];H=c;const d=document.getElementById("sec-hosts-container");if(!c.length){d.innerHTML='
No hosts registered. Click \u2795 Register Host to add one.
';return}d.innerHTML=c.map(w=>{const y=w.enabled?w.last_seen_at?Date.now()-Date.parse(w.last_seen_at)>18e5?"\u{1F7E1} stale":"\u{1F7E2} online":"\u26AA registered":"\u{1F534} disabled";return`
${g(w.label||w.id)} ${g(w.type)}
id: ${g(w.id)} \xB7 registered ${new Date(w.registered_at).toLocaleDateString()} \xB7 last seen ${w.last_seen_at?new Date(w.last_seen_at).toLocaleString():"never"}
${y} ${w.id==="self"?"":``}
`}).join(""),d.querySelectorAll(".sec-host-del").forEach(w=>{w.addEventListener("click",async()=>{confirm(`Remove host ${w.dataset.id}? Events already received will remain in the store.`)&&(await fetch(`/api/v1/security/hosts/${encodeURIComponent(w.dataset.id)}`,{method:"DELETE"}),u())})})}catch(r){document.getElementById("sec-hosts-container").innerHTML='
Load failed: '+g(r.message)+"
"}}async function f(){const r=prompt("Host id (lowercase, no spaces):");if(!r)return;const c=prompt("Display label:",r)||r,d=prompt('Type ("dashcaddy", "service", or "agent"):',"agent")||"agent";try{const w=await fetch("/api/v1/security/hosts",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({id:r,label:c,type:d})}),y=await w.json();if(!w.ok){alert("Failed: "+(y?.error?.message||w.statusText));return}alert(`\u2705 Host registered! id: ${y.data.host.id} label: ${y.data.host.label} type: ${y.data.host.type} \u{1F511} API KEY (save this NOW \u2014 won't be shown again): ${y.data.api_key} Send this key as: Authorization: Bearer To endpoint: POST /api/v1/security/events/ingest or /events/batch`),u()}catch(w){alert("Failed: "+w.message)}}function g(r){return String(r).replace(/[&<>"']/g,c=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[c])}function z(r,c){let d;return function(){clearTimeout(d),d=setTimeout(()=>r.apply(this,arguments),c)}}})(),(function(){const h=new ErrorHandler;injectModal("weather-modal",`

Weather Settings

Enter a city name, postal code, or “City, Country”
`);const L="weather-location",A="weather-zip",I="weather-geo",D="weather-unit";!safeGet(L)&&safeGet(A)&&safeSet(L,safeGet(A));function R(){return safeGet(D)||"imperial"}function H(){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 P={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"},v={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"},C=["N","NNE","NE","ENE","E","ESE","SE","SSE","S","SSW","SW","WSW","W","WNW","NW","NNW"];function x(T){return C[Math.round(T/22.5)%16]}async function $(T){const b=safeGet(I);if(b)try{const f=JSON.parse(b);if(f.query===T)return f}catch{}const N=await fetch(`https://geocoding-api.open-meteo.com/v1/search?name=${encodeURIComponent(T)}&count=1&language=en&format=json`);if(!N.ok)throw new Error("Geocoding failed");const O=await N.json();if(!O.results||!O.results.length)throw new Error("Location not found");const p=O.results[0],u={query:T,lat:p.latitude,lon:p.longitude,city:p.name,state:p.admin1||"",country:p.country||"",countryCode:p.country_code||""};return safeSet(I,JSON.stringify(u)),u}function E(T){return T.countryCode==="US"&&T.state?`${T.city}, ${T.state}`:T.country?`${T.city}, ${T.country}`:T.city}async function M(T){try{const b=await $(T),N=R(),O=N==="metric"?"celsius":"fahrenheit",p=N==="metric"?"kmh":"mph",u=`https://api.open-meteo.com/v1/forecast?latitude=${b.lat}&longitude=${b.lon}¤t=temperature_2m,weather_code,wind_speed_10m,wind_direction_10m&temperature_unit=${O}&wind_speed_unit=${p}`,f=await fetch(u);if(!f.ok)throw new Error("Weather fetch failed");const z=(await f.json()).current,r=z.weather_code;return{temp:Math.round(z.temperature_2m),condition:P[r]||"Unknown",icon:v[r]||"\u{1F324}\uFE0F",locationStr:E(b),windSpeed:Math.round(z.wind_speed_10m),windDir:x(z.wind_direction_10m),unit:N}}catch(b){return console.warn("Weather fetch failed:",b),null}}async function S(){const T=H();if(!T.icon||!T.temp||!T.condition||!T.location||!T.wind){console.warn("Weather widget elements not found");return}const b=safeGet(L);if(!b){T.location.textContent="Set Location",T.temp.textContent="--\xB0",T.condition.textContent="Click \u2699\uFE0F to configure",T.wind.textContent="--",T.icon.innerHTML='\u{1F324}\uFE0F';return}try{const N=await M(b);if(N){const O=N.unit==="metric"?"\xB0C":"\xB0F",p=N.unit==="metric"?"km/h":"mph";T.location.textContent=N.locationStr,T.temp.textContent=`${N.temp}${O}`,T.condition.textContent=N.condition,T.wind.textContent=`Wind: ${N.windSpeed} ${p} ${N.windDir}`,T.icon.innerHTML=`${escapeHtml(N.icon)}`}}catch(N){h.logError("[Weather] Update Error",N,{function:"updateWeather"}),T.location.textContent="Weather Error",T.temp.textContent="Error",T.condition.textContent="Failed to load",T.wind.textContent="--"}}const B=document.getElementById("weather-modal"),U=document.getElementById("weather-location-input");document.getElementById("weather-settings")?.addEventListener("click",()=>{U.value=safeGet(L)||"";const T=R(),b=B.querySelector(`input[name="weather-unit-radio"][value="${T}"]`);b&&(b.checked=!0),B.classList.add("show"),U.focus()}),document.getElementById("weather-cancel")?.addEventListener("click",()=>{B.classList.remove("show")}),document.getElementById("weather-save")?.addEventListener("click",()=>{const T=U.value.trim();if(T){safeGet(L)!==T&&safeSet(I,""),safeSet(L,T);const N=B.querySelector('input[name="weather-unit-radio"]:checked'),O=N?N.value:"imperial",p=R();safeSet(D,O),p!==O&&safeSet(I,""),B.classList.remove("show"),S()}else showNotification("Please enter a location (e.g., Hamburg, London, 90210)","warning")}),wireModal(B),document.addEventListener("keydown",T=>{T.key==="Escape"&&B.classList.contains("show")&&B.classList.remove("show")}),S(),setInterval(S,DC.POLL.WEATHER)})(),(function(){const h=document.getElementById("clock-widget"),L=document.getElementById("clock-render");if(!h||!L)return;const A=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],I=["January","February","March","April","May","June","July","August","September","October","November","December"],D=["XII","I","II","III","IV","V","VI","VII","VIII","IX","X","XI"];let R=safeGet("clock-style")||"default",H=-1,P=!1,v="",C="",x=null,$=null;function E(t){if(P||safeGet("clock-chimes")!=="true")return;P=!0;const e=parseInt(safeGet("clock-chime-volume")||"50",10)/100;let a=0;function o(){if(a>=t){P=!1;return}const i=new Audio("/assets/sounds/church-bell.mp3");i.volume=e,i.play().catch(()=>{}),a++,a{P=!1},2500)}o()}function M(t){return A[t.getDay()]+", "+I[t.getMonth()]+" "+t.getDate()+", "+t.getFullYear()}function S(){C="",x=null}function B(){return C!=="digital"&&(L.innerHTML='
',x={main:L.querySelector(".clock-main"),seconds:L.querySelector(".clock-seconds"),ampm:L.querySelector(".clock-ampm"),date:L.querySelector(".clock-date")},C="digital"),x}function U(t){const e=t.getHours(),a=t.getMinutes(),o=t.getSeconds(),i=e>=12?"PM":"AM",n=e%12||12,s=B();s.main.textContent=`${n}:${String(a).padStart(2,"0")}`,s.seconds.textContent=`:${String(o).padStart(2,"0")}`,s.ampm.textContent=i,s.date.textContent=M(t)}function T(t,e){const a=t.getHours(),o=t.getMinutes(),i=t.getSeconds(),n=a>=12?"PM":"AM",s=a%12||12,l=B();l.main.textContent=`${String(s).padStart(2,"0")}:${String(o).padStart(2,"0")}`,l.seconds.textContent=`:${String(i).padStart(2,"0")}`,l.ampm.textContent=n,l.date.textContent=M(t)}function b(t){const e=t.getHours(),a=t.getMinutes(),o=t.getSeconds(),i=e>=12?"PM":"AM",n=e%12||12,s=String(n).padStart(2," ")+String(a).padStart(2,"0")+String(o).padStart(2,"0");let l='
';if(l+=N(s[0],0),l+=N(s[1],1),l+=':',l+=N(s[2],2),l+=N(s[3],3),l+=':',l+=N(s[4],4),l+=N(s[5],5),l+=`${i}`,l+="
",l+=`
${M(t)}
`,L.innerHTML=l,C="flip",v){for(let m=0;m<6;m++)if(s[m]!==v[m]){const k=L.querySelector(`.flip-card[data-idx="${m}"]`);k&&k.classList.add("flipping")}}v=s}function N(t,e){const a=t===" "?"":t;return`
${a}
${a}
`}function O(t){const e=t.getHours(),a=t.getMinutes(),o=t.getSeconds(),i=e%12||12,n=e>=12?"PM":"AM",s=[Math.floor(i/10),i%10,Math.floor(a/10),a%10,Math.floor(o/10),o%10];let l='
';l+='
HHMMSS
';for(let m=3;m>=0;m--){l+='
';for(let k=0;k<6;k++){const j=s[k]>>m&1;l+=`
`}l+="
"}l+='
';for(let m=0;m<6;m++)l+=`${s[m]}`;l+="
",l+=`
${n}
`,l+="
",l+=`
${M(t)}
`,L.innerHTML=l,C="binary"}function p(t,e){const a=t.getHours(),o=t.getMinutes(),i=t.getSeconds(),n=120,s=n/2,l=n/2,m=i/60*360-90,k=(o+i/60)/60*360-90,j=(a%12+o/60)/12*360-90;let _="";for(let X=1;X<=12;X++){const Q=X/12*2*Math.PI-Math.PI/2,ne=47,oe=s+ne*Math.cos(Q),se=l+ne*Math.sin(Q),Y=e?D[X%12]:X;_+=`${Y}`}let F="";for(let X=0;X<60;X++){const Q=X/60*2*Math.PI-Math.PI/2,ne=56,oe=X%5===0?52:54,se=s+oe*Math.cos(Q),Y=l+oe*Math.sin(Q),ie=s+ne*Math.cos(Q),re=l+ne*Math.sin(Q),ae=X%5===0?1.5:.5;F+=``}const q=` ${F} ${_} `,J=t.getHours()>=12?"PM":"AM";L.innerHTML=`
${q}
${t.getHours()%12||12}:${String(o).padStart(2,"0")} ${J}${M(t)}
`,C="analog"}function u(){const t=new Date,e=t.getHours()%12||12,a=t.getMinutes(),o=t.getSeconds(),i="clock-widget"+(R!=="default"?" "+R:"");switch(h.className!==i&&(h.className=i),R){case"lcd":T(t);break;case"lcd-blue":T(t);break;case"lcd-amber":T(t);break;case"lcd-retro":T(t);break;case"lcd-taxi":T(t);break;case"flip":b(t);break;case"binary":O(t);break;case"analog":p(t,!1);break;case"roman":p(t,!0);break;default:U(t)}a===0&&o===0&&e!==H&&(H=e,E(e)),a!==0&&(H=-1)}function f(){clearTimeout($);const t=document.hidden?6e4:1e3,e=t-Date.now()%t+25;$=setTimeout(()=>{u(),f()},e)}document.addEventListener("visibilitychange",()=>{v="",S(),u(),f()}),u(),f();const g=[{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 z='
';g.forEach(t=>{z+=``}),z+="
",injectModal("clock-settings-modal",`

Clock Settings

${z}
Strikes the number of the hour (e.g., 3 bells at 3:00)
\u{1F508} \u{1F50A}
`);const r=document.getElementById("clock-settings-modal"),c=document.getElementById("clock-chimes-toggle"),d=document.getElementById("clock-chime-volume"),w=document.getElementById("clock-volume-section");function y(){const t=safeGet("clock-style")||"default",e=r.querySelector(`input[value="${t}"]`);e&&(e.checked=!0),c.checked=safeGet("clock-chimes")==="true",d.value=safeGet("clock-chime-volume")||"50",w.style.opacity=c.checked?"1":"0.4"}c?.addEventListener("change",()=>{w.style.opacity=c.checked?"1":"0.4"}),document.getElementById("clock-settings")?.addEventListener("click",()=>{y(),r.classList.add("show")}),document.getElementById("clock-chime-test")?.addEventListener("click",()=>{const t=parseInt(d.value,10)/100,e=new Audio("/assets/sounds/church-bell.mp3");e.volume=t,e.play().catch(()=>{})}),document.getElementById("clock-settings-save")?.addEventListener("click",()=>{const t=r.querySelector('input[name="clock-style-radio"]:checked'),e=t?t.value:"default";safeSet("clock-style",e),safeSet("clock-chimes",String(c.checked)),safeSet("clock-chime-volume",d.value),R=e,v="",S(),u(),f(),r.classList.remove("show"),showNotification("Clock settings saved","success",2e3)}),document.getElementById("clock-settings-cancel")?.addEventListener("click",()=>{r.classList.remove("show")}),wireModal(r),r?.querySelectorAll('input[name="clock-style-radio"]').forEach(t=>{t.addEventListener("change",()=>{R=t.value,v="",S(),u()})})})(),(function(){async function h(){try{const P=await(await fetch("/api/v1/health-checks/status")).json();if(!P.success||!P.status)return;for(const[v,C]of Object.entries(P.status)){const x=document.getElementById("uptime-"+v),$=document.getElementById("uptime-bar-"+v);if(!x)continue;const E=C.uptime?.["24h"];if(E!=null){const M=E.toFixed(1);x.textContent=`${M}% uptime`,x.className="uptime-chip",E>=99.9?x.classList.add("excellent"):E>=99?x.classList.add("good"):E>=95?x.classList.add("degraded"):x.classList.add("poor"),$&&($.style.width=M+"%")}}}catch{console.warn("[Card Badges] Health check API unavailable")}}let L;try{L=new Set(JSON.parse(safeSessionGet("dismissed-updates")||"[]"))}catch{L=new Set}let A=[];async function I(H){try{const v=await(await fetch("/api/v1/updates/available")).json();if(!v.success)return;document.querySelectorAll(".update-available-badge").forEach(x=>x.classList.remove("visible"));const C=v.updates||[];if(A=C,H&&C.length>0){const x=window._lastKnownUpdateCount||0;x>0&&C.length>x&&showNotification(`${C.length} container update(s) available \u2014 click Update Management to review.`,"info"),window._lastKnownUpdateCount=C.length}if(!C.length)return;for(const x of C){const $=window.APPS||[];for(const E of $)if(E.containerId===x.containerId||E.id===x.containerName||E.name===x.containerName){if(L.has(E.id))break;const M=document.getElementById("update-badge-"+E.id),S=document.getElementById("update-btn-"+E.id);M&&(M.classList.add("visible"),M.title="Update available \u2014 click to open Update Management.",M.style.cursor="pointer",M.onclick=B=>{B.stopPropagation(),window.openUpdateModal&&window.openUpdateModal(E.id)}),S&&(S.style.background="#f97316",S.style.borderColor="#f97316",S.style.boxShadow="0 0 6px #f9731688",S.title="Update available \u2014 click to open Update Management.");break}}}catch{console.warn("[Card Badges] Updates API unavailable")}}function D(){setTimeout(()=>{h(),I()},5e3),setInterval(()=>{h(),I(!0)},6e4)}const R=window.refreshAll;R&&(window.refreshAll=async function(){try{await R(),setTimeout(h,1e3)}catch(H){console.warn("[Card Badges] Error in refreshAll hook:",H.message)}}),D()})(),(function(){var h=null,L=null,A={},I={dark:"Dark",light:"Light",blue:"Blue",black:"Black",nord:"Nord",dracula:"Dracula","solarized-dark":"Solarized Dark","solarized-light":"Solarized Light",taxi:"Taxi",ocean:"Ocean"},D=[["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"]],R=document.getElementById("theme");if(!R)return;var H=document.getElementById("theme-label");function P(o){if(I[o])return I[o];var i=safeGetJSON(window.USER_THEMES_KEY,{});return i[o]&&i[o].name||o}function v(){H&&(H.textContent=P(window.getActiveTheme()))}R.addEventListener("click",function(){var o=window.THEMES.slice(),i=window.getActiveTheme(),n=o.indexOf(i),s=o[(n+1)%o.length];window.applyTheme(s),v()}),v();function C(){var o={base:"Base Colors",accent:"Accent",status:"Status",advanced:"Advanced (auto-derived)"},i={};D.forEach(function(s){i[s[2]]||(i[s[2]]=[]),i[s[2]].push(s)});var n="";return Object.keys(o).forEach(function(s){s==="advanced"?(n+='
Show advanced colors ▼
',n+='