@@ -127,7 +127,7 @@ This will reset the logo, favicon, title, and position.`))try{if((await secureFe
Timezone: ${c.replace(/_/g," ")}
- `,o+="
",u.innerHTML=o,N("setup-step-summary")}async function $(u){try{const o=await secureFetch("/api/v1/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(u)});return o.ok?(await o.json(),!0):(errorHandler.logError("[SetupWizard] Save Config",new Error(`Server returned ${o.status}`),{function:"saveConfigToServer"}),!1)}catch(o){return errorHandler.logError("[SetupWizard] Save Config",o,{function:"saveConfigToServer"}),!1}}async function R(){const u={setupComplete:!0,configurationType:b,timestamp:new Date().toISOString(),timezone:document.getElementById("setup-timezone")?.value||Intl.DateTimeFormat().resolvedOptions().timeZone||"UTC"};if(b==="homelab"){u.tld=document.getElementById("setup-tld")?.value?.trim()||".home",u.caName=document.getElementById("setup-ca-name")?.value?.trim()||"";const g=document.getElementById("setup-dns-provider")?.value||"technitium";u.dns=DnsProviderConfig.buildDnsConfig(g,document.getElementById("setup-dns-ip")?.value?.trim()||"",document.getElementById("setup-dns-port")?.value?.trim()||"",document.getElementById("setup-dns-token")?.value?.trim()||"",DC.DEFAULTS.DNS_PORT),u.defaults={dnsType:"private",sslType:"internal",targetIP:"localhost"}}else b==="simple"?(u.defaultIP=document.getElementById("setup-simple-ip")?.value?.trim()||"localhost",u.defaults={dnsType:"none",sslType:"none",targetIP:u.defaultIP}):b==="public"&&(u.domain=document.getElementById("setup-public-domain")?.value?.trim()||"",u.email=document.getElementById("setup-public-email")?.value?.trim()||"",u.routingMode=document.querySelector('input[name="routing-mode"]:checked')?.value||"subdirectory",u.defaults={dnsType:u.routingMode==="subdirectory"?"none":"public",sslType:"letsencrypt",targetIP:"localhost"});const o=await $(u);safeSet("dashcaddy-config",JSON.stringify(u)),safeSet("dashcaddy-setup","completed"),document.getElementById("setup-wizard").style.display="none";const c=b==="homelab"?"Professional Home Lab":b==="simple"?"Simple Setup":"Public Server",d=o?"server (shared across all devices)":"locally (this browser only)";showNotification(`Setup Complete! Configured for: ${c}. Settings saved to: ${d}`,"success",5e3),setTimeout(()=>location.reload(),500)}const y=document.getElementById("setup-step-1-next");y&&(y.onclick=function(u){u.preventDefault();const o=document.querySelector('input[name="config-type"]:checked');o&&(b=o.value),N(b==="homelab"?"setup-step-homelab":b==="simple"?"setup-step-simple":b==="public"?"setup-step-public":"setup-step-homelab")});const L=document.getElementById("setup-skip");L&&(L.onclick=async function(u){u.preventDefault(),confirm("Skip setup? You can run it later from Settings.")&&(await $({setupComplete:!0,skipped:!0,timestamp:new Date().toISOString()}),safeSet("dashcaddy-setup","skipped"),document.getElementById("setup-wizard").style.display="none")});const w=document.getElementById("setup-tld");w&&(w.oninput=function(u){const o=u.target.value||".home",c=document.getElementById("tld-preview"),d=document.getElementById("tld-preview-2");c&&(c.textContent=o),d&&(d.textContent=o)});const z=document.getElementById("setup-homelab-back");z&&(z.onclick=function(u){u.preventDefault(),N("setup-step-1")});const x=document.getElementById("setup-homelab-next");x&&(x.onclick=function(u){u.preventDefault();const o=document.getElementById("setup-tld")?.value?.trim()||"",c=document.getElementById("setup-ca-name")?.value?.trim()||"",d=document.getElementById("setup-dns-ip")?.value?.trim()||"";if(!o||!o.startsWith(".")){showNotification("Please enter a valid TLD starting with a dot (e.g., .home)","warning");return}if(!c){showNotification("Please enter a Certificate Authority name","warning");return}if(!d){showNotification("Please enter your DNS server IP address","warning");return}M()});const C=document.getElementById("setup-simple-back");C&&(C.onclick=function(u){u.preventDefault(),N("setup-step-1")});const k=document.getElementById("setup-simple-next");k&&(k.onclick=function(u){u.preventDefault(),M()}),document.querySelectorAll('input[name="routing-mode"]').forEach(function(u){u.onchange=function(){var o=document.getElementById("dns-requirement-note");o&&(o.textContent=this.value==="subdirectory"?"Only one DNS record needed (for the main domain)":"You'll need to configure DNS manually for each subdomain")}});const T=document.getElementById("setup-public-back");T&&(T.onclick=function(u){u.preventDefault(),N("setup-step-1")});const P=document.getElementById("setup-public-next");P&&(P.onclick=function(u){u.preventDefault();const o=document.getElementById("setup-public-domain")?.value?.trim()||"",c=document.getElementById("setup-public-email")?.value?.trim()||"";if(!o){showNotification("Please enter your domain name","warning");return}if(!c||!c.includes("@")){showNotification("Please enter a valid email address","warning");return}M()});const f=document.getElementById("setup-summary-back");f&&(f.onclick=function(u){u.preventDefault(),b==="homelab"?N("setup-step-homelab"):b==="simple"?N("setup-step-simple"):b==="public"&&N("setup-step-public")});const B=document.getElementById("setup-summary-next");B&&(B.onclick=function(u){u.preventDefault(),N("setup-step-disk-safety")});const D=document.getElementById("setup-disk-safety-back");D&&(D.onclick=function(u){u.preventDefault(),N("setup-step-summary")});const F=document.getElementById("setup-disk-safety-finish");F&&(F.onclick=function(u){u.preventDefault(),R()}),window.getGlobalConfig=async function(){try{const o=await fetch("/api/v1/config");if(o.ok){const c=await o.json();if(c&&c.setupComplete)return c}}catch{console.warn("Could not fetch config from server")}const u=safeGet("dashcaddy-config");return u?JSON.parse(u):{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()}};const S={technitium:"\u2705 Full management \u2014 records, zones and health checks via the Technitium API. DashCaddy can create, delete, list and resolve records.",cloudflare:"\u2705 Full management \u2014 records via the Cloudflare API token. DashCaddy can create, delete, list and resolve records.",rfc2136:"\u26A0\uFE0F Partial (push-only protocol) \u2014 records can be created, deleted and resolved, and listed via AXFR zone transfer if the server permits transfers for your key (BIND: allow-transfer { key ; };). Listing requires that server-side setting.",powerdns:"\u2705 Full management \u2014 records and zones via the PowerDNS HTTP API (X-API-Key). Requires api=yes, webserver=yes and api-key in pdns.conf. DashCaddy can create, delete, list and resolve records.",manual:"\u2139\uFE0F No API control \u2014 DashCaddy shows the records you create yourself with your DNS provider's tools. Everything else (reverse proxy, SSL) works normally."};function I(){const u=document.getElementById("setup-dns-provider"),o=document.getElementById("setup-dns-provider-hints");!u||!o||(o.innerHTML=S[u.value]?`${H(u.selectedOptions[0]?.text||u.value)} ${S[u.value]}`:"")}function H(u){return String(u??"").replace(/&/g,"&").replace(//g,">")}const E=document.getElementById("setup-dns-provider");E&&(E.addEventListener("change",I),I())})(),(function(){const b=new ErrorHandler;injectModal("app-selector-modal",`
+ `,o+="
",u.innerHTML=o,D("setup-step-summary")}async function $(u){try{const o=await secureFetch("/api/v1/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(u)});return o.ok?(await o.json(),!0):(errorHandler.logError("[SetupWizard] Save Config",new Error(`Server returned ${o.status}`),{function:"saveConfigToServer"}),!1)}catch(o){return errorHandler.logError("[SetupWizard] Save Config",o,{function:"saveConfigToServer"}),!1}}async function R(){const u={setupComplete:!0,configurationType:b,timestamp:new Date().toISOString(),timezone:document.getElementById("setup-timezone")?.value||Intl.DateTimeFormat().resolvedOptions().timeZone||"UTC"};if(b==="homelab"){u.tld=document.getElementById("setup-tld")?.value?.trim()||".home",u.caName=document.getElementById("setup-ca-name")?.value?.trim()||"";const g=document.getElementById("setup-dns-provider")?.value||"technitium";u.dns=DnsProviderConfig.buildDnsConfig(g,document.getElementById("setup-dns-ip")?.value?.trim()||"",document.getElementById("setup-dns-port")?.value?.trim()||"",document.getElementById("setup-dns-token")?.value?.trim()||"",DC.DEFAULTS.DNS_PORT),u.defaults={dnsType:"private",sslType:"internal",targetIP:"localhost"}}else b==="simple"?(u.defaultIP=document.getElementById("setup-simple-ip")?.value?.trim()||"localhost",u.defaults={dnsType:"none",sslType:"none",targetIP:u.defaultIP}):b==="public"&&(u.domain=document.getElementById("setup-public-domain")?.value?.trim()||"",u.email=document.getElementById("setup-public-email")?.value?.trim()||"",u.routingMode=document.querySelector('input[name="routing-mode"]:checked')?.value||"subdirectory",u.defaults={dnsType:u.routingMode==="subdirectory"?"none":"public",sslType:"letsencrypt",targetIP:"localhost"});const o=await $(u);safeSet("dashcaddy-config",JSON.stringify(u)),safeSet("dashcaddy-setup","completed"),document.getElementById("setup-wizard").style.display="none";const c=b==="homelab"?"Professional Home Lab":b==="simple"?"Simple Setup":"Public Server",d=o?"server (shared across all devices)":"locally (this browser only)";showNotification(`Setup Complete! Configured for: ${c}. Settings saved to: ${d}`,"success",5e3),setTimeout(()=>location.reload(),500)}const y=document.getElementById("setup-step-1-next");y&&(y.onclick=function(u){u.preventDefault();const o=document.querySelector('input[name="config-type"]:checked');o&&(b=o.value),D(b==="homelab"?"setup-step-homelab":b==="simple"?"setup-step-simple":b==="public"?"setup-step-public":"setup-step-homelab")});const L=document.getElementById("setup-skip");L&&(L.onclick=async function(u){u.preventDefault(),confirm("Skip setup? You can run it later from Settings.")&&(await $({setupComplete:!0,skipped:!0,timestamp:new Date().toISOString()}),safeSet("dashcaddy-setup","skipped"),document.getElementById("setup-wizard").style.display="none")});const w=document.getElementById("setup-tld");w&&(w.oninput=function(u){const o=u.target.value||".home",c=document.getElementById("tld-preview"),d=document.getElementById("tld-preview-2");c&&(c.textContent=o),d&&(d.textContent=o)});const z=document.getElementById("setup-homelab-back");z&&(z.onclick=function(u){u.preventDefault(),D("setup-step-1")});const x=document.getElementById("setup-homelab-next");x&&(x.onclick=function(u){u.preventDefault();const o=document.getElementById("setup-tld")?.value?.trim()||"",c=document.getElementById("setup-ca-name")?.value?.trim()||"",d=document.getElementById("setup-dns-ip")?.value?.trim()||"";if(!o||!o.startsWith(".")){showNotification("Please enter a valid TLD starting with a dot (e.g., .home)","warning");return}if(!c){showNotification("Please enter a Certificate Authority name","warning");return}if(!d){showNotification("Please enter your DNS server IP address","warning");return}M()});const C=document.getElementById("setup-simple-back");C&&(C.onclick=function(u){u.preventDefault(),D("setup-step-1")});const k=document.getElementById("setup-simple-next");k&&(k.onclick=function(u){u.preventDefault(),M()}),document.querySelectorAll('input[name="routing-mode"]').forEach(function(u){u.onchange=function(){var o=document.getElementById("dns-requirement-note");o&&(o.textContent=this.value==="subdirectory"?"Only one DNS record needed (for the main domain)":"You'll need to configure DNS manually for each subdomain")}});const T=document.getElementById("setup-public-back");T&&(T.onclick=function(u){u.preventDefault(),D("setup-step-1")});const N=document.getElementById("setup-public-next");N&&(N.onclick=function(u){u.preventDefault();const o=document.getElementById("setup-public-domain")?.value?.trim()||"",c=document.getElementById("setup-public-email")?.value?.trim()||"";if(!o){showNotification("Please enter your domain name","warning");return}if(!c||!c.includes("@")){showNotification("Please enter a valid email address","warning");return}M()});const f=document.getElementById("setup-summary-back");f&&(f.onclick=function(u){u.preventDefault(),b==="homelab"?D("setup-step-homelab"):b==="simple"?D("setup-step-simple"):b==="public"&&D("setup-step-public")});const B=document.getElementById("setup-summary-next");B&&(B.onclick=function(u){u.preventDefault(),D("setup-step-disk-safety")});const P=document.getElementById("setup-disk-safety-back");P&&(P.onclick=function(u){u.preventDefault(),D("setup-step-summary")});const O=document.getElementById("setup-disk-safety-finish");O&&(O.onclick=function(u){u.preventDefault(),R()}),window.getGlobalConfig=async function(){try{const o=await fetch("/api/v1/config");if(o.ok){const c=await o.json();if(c&&c.setupComplete)return c}}catch{console.warn("Could not fetch config from server")}const u=safeGet("dashcaddy-config");return u?JSON.parse(u):{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()}};const S={technitium:"\u2705 Full management \u2014 records, zones and health checks via the Technitium API. DashCaddy can create, delete, list and resolve records.",cloudflare:"\u2705 Full management \u2014 records via the Cloudflare API token. DashCaddy can create, delete, list and resolve records.",rfc2136:"\u26A0\uFE0F Partial (push-only protocol) \u2014 records can be created, deleted and resolved, and listed via AXFR zone transfer if the server permits transfers for your key (BIND: allow-transfer { key ; };). Listing requires that server-side setting.",powerdns:"\u2705 Full management \u2014 records and zones via the PowerDNS HTTP API (X-API-Key). Requires api=yes, webserver=yes and api-key in pdns.conf. DashCaddy can create, delete, list and resolve records.",manual:"\u2139\uFE0F No API control \u2014 DashCaddy shows the records you create yourself with your DNS provider's tools. Everything else (reverse proxy, SSL) works normally."};function I(){const u=document.getElementById("setup-dns-provider"),o=document.getElementById("setup-dns-provider-hints");!u||!o||(o.innerHTML=S[u.value]?`${H(u.selectedOptions[0]?.text||u.value)} ${S[u.value]}`:"")}function H(u){return String(u??"").replace(/&/g,"&").replace(//g,">")}const E=document.getElementById("setup-dns-provider");E&&(E.addEventListener("change",I),I())})(),(function(){const b=new ErrorHandler;injectModal("app-selector-modal",`
Choose an App
@@ -333,7 +333,7 @@ This will reset the logo, favicon, title, and position.`))try{if((await secureFe
-
`);const h="custom-apps";let j=null,v=null;const N=document.getElementById("app-selector-modal"),M=document.getElementById("app-selector-grid");async function $(){try{const c=await(await fetch("/api/v1/apps/templates")).json();if(c.success)return j=c.templates,v=c.categories,!0}catch(o){b.logError("[AppSelector] Fetch Templates",o,{function:"fetchApiTemplates"})}return!1}async function R(o){try{return await(await fetch(`/api/v1/apps/ports/${o}/check`)).json()}catch(c){return b.logError("[AppSelector] Check Port",c,{function:"checkPortAvailability"}),{available:!0}}}async function y(o){try{const d=await(await fetch(`/api/v1/apps/ports/${o}/suggest`)).json();if(d.success)return d.suggestedPort}catch(c){b.logError("[AppSelector] Get Suggested Port",c,{function:"getSuggestedPort"})}return o}async function L(){if(M.innerHTML='
Loading app templates...
',!j&&!await $()){M.innerHTML='
Failed to load app templates. Please try again.
';return}M.innerHTML="";const o={};for(const[d,g]of Object.entries(j)){const p=g.category||"Other";o[p]||(o[p]=[]),o[p].push({id:d,...g})}const c=v?Object.keys(v):Object.keys(o).sort();for(const d of c){const g=o[d];if(!g||g.length===0)continue;g.sort((i,l)=>(l.popularity||0)-(i.popularity||0));const p=document.createElement("div");p.className="app-category-header";const e=v?.[d]||{};p.innerHTML=`${escapeHtml(e.icon||"")} ${escapeHtml(d)}`,e.color&&(p.style.borderBottomColor=e.color),M.appendChild(p),g.forEach(i=>{const l=document.createElement("div");l.className="app-option";const s=i.isDashboardWidget,a=s&&safeGet("widget-"+i.id+"-enabled")!=="false",t=s?`
${a?"ON":"OFF"}
`:"",n=!s&&i.difficulty?`
${escapeHtml(i.difficulty)}
`:"";l.innerHTML=`
+
`);const h="custom-apps";let j=null,v=null;const D=document.getElementById("app-selector-modal"),M=document.getElementById("app-selector-grid");async function $(){try{const c=await(await fetch("/api/v1/apps/templates")).json();if(c.success)return j=c.templates,v=c.categories,!0}catch(o){b.logError("[AppSelector] Fetch Templates",o,{function:"fetchApiTemplates"})}return!1}async function R(o){try{return await(await fetch(`/api/v1/apps/ports/${o}/check`)).json()}catch(c){return b.logError("[AppSelector] Check Port",c,{function:"checkPortAvailability"}),{available:!0}}}async function y(o){try{const d=await(await fetch(`/api/v1/apps/ports/${o}/suggest`)).json();if(d.success)return d.suggestedPort}catch(c){b.logError("[AppSelector] Get Suggested Port",c,{function:"getSuggestedPort"})}return o}async function L(){if(M.innerHTML='
Loading app templates...
',!j&&!await $()){M.innerHTML='
Failed to load app templates. Please try again.
';return}M.innerHTML="";const o={};for(const[d,g]of Object.entries(j)){const p=g.category||"Other";o[p]||(o[p]=[]),o[p].push({id:d,...g})}const c=v?Object.keys(v):Object.keys(o).sort();for(const d of c){const g=o[d];if(!g||g.length===0)continue;g.sort((i,l)=>(l.popularity||0)-(i.popularity||0));const p=document.createElement("div");p.className="app-category-header";const e=v?.[d]||{};p.innerHTML=`${escapeHtml(e.icon||"")} ${escapeHtml(d)}`,e.color&&(p.style.borderBottomColor=e.color),M.appendChild(p),g.forEach(i=>{const l=document.createElement("div");l.className="app-option";const s=i.isDashboardWidget,a=s&&safeGet("widget-"+i.id+"-enabled")!=="false",t=s?`
${a?"ON":"OFF"}
`:"",n=!s&&i.difficulty?`
${escapeHtml(i.difficulty)}
`:"";l.innerHTML=`
${escapeHtml(i.icon||"\u{1F4E6}")}
${escapeHtml(i.name)}
${escapeHtml(i.description||"")}
@@ -347,7 +347,7 @@ Port: ${Y.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.`)&&(o._useExisting=!0,o._existingContainer=Y)}}catch{}d.textContent=`Deploy ${o.name}`;const a=o.subdomain||o.id.replace(/-/g,"");g.value=a;const t=document.getElementById("subpath-compat-warning");if(t)if(SITE.routingMode==="subdirectory"){const W=o.subpathSupport||"strip";W==="none"?(t.style.display="block",t.innerHTML='⚠ '+o.name+" does not support subdirectory mode. It may not work correctly at a subpath."):W==="strip"?(t.style.display="block",t.innerHTML='ⓘ '+o.name+" has unverified subdirectory support. It may require additional configuration."):t.style.display="none"}else t.style.display="none";const n=SITE.defaults.dnsType||(SITE.configurationType==="public"?"public":"private"),r=SITE.defaults.sslType||(SITE.configurationType==="public"?"letsencrypt":"internal"),m=document.querySelector(`input[name="dns-type"][value="${n}"]`),A=document.querySelector(`input[name="ssl-type"][value="${r}"]`);m?m.checked=!0:document.querySelector('input[name="dns-type"][value="private"]').checked=!0,A?A.checked=!0:document.querySelector('input[name="ssl-type"][value="internal"]').checked=!0,e.value=SITE.defaults.targetIP||"localhost",l.checked=!1;const O=document.querySelector("#app-deploy-modal .flex-col-gap")?.closest("div"),_=document.querySelector("#app-deploy-modal details"),U=_?.querySelector("div");if(_&&U&&(SITE.configurationType==="public"||SITE.configurationType==="homelab")){const W=document.querySelectorAll('#app-deploy-modal input[name="dns-type"]')[0]?.closest("div.flex-col-gap")?.parentElement,V=document.querySelectorAll('#app-deploy-modal input[name="ssl-type"]')[0]?.closest("div.flex-col-gap")?.parentElement;W&&!W.dataset.moved&&(U.appendChild(W),W.dataset.moved="1"),V&&!V.dataset.moved&&(U.appendChild(V),V.dataset.moved="1")}const q=document.getElementById("media-path-section"),J=document.getElementById("deploy-media-path"),G=document.getElementById("media-path-description");if(o.mediaMount){q.style.display="block",J.value="",J.placeholder="/media/Movies, /media/TVShows or click Browse";const W=document.getElementById("detected-mounts-container"),V=document.getElementById("detected-mounts-list");try{const X=await(await fetch("/api/v1/media/detected-mounts")).json();if(X.success&&X.mounts.length>0){W.style.display="block",V.innerHTML="";const ae=[...new Set(X.mounts.map(te=>te.hostPath))];J.value=ae.join(", "),X.mounts.forEach(te=>{const Q=document.createElement("button");Q.type="button";const de=ae.includes(te.hostPath);Q.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);`,Q.innerHTML=`${escapeHtml(te.folderName)} from ${escapeHtml(te.sourceImage)}`,Q.title=`${te.hostPath} (from ${te.sourceContainer})`,Q.onclick=()=>{const le=J.value.split(",").map(ce=>ce.trim()).filter(ce=>ce),pe=le.indexOf(te.hostPath);pe>=0?(le.splice(pe,1),Q.style.background="color-mix(in srgb, var(--success) 15%, var(--card-bg))"):(le.push(te.hostPath),Q.style.background="color-mix(in srgb, var(--success) 40%, var(--card-bg))"),J.value=le.join(", ")},V.appendChild(Q)})}else W.style.display="none"}catch{W.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 Z=document.getElementById("plex-claim-section");Z&&(o.id==="plex"||o.claimToken?(Z.style.display="block",document.getElementById("deploy-plex-claim").value=""):Z.style.display="none");const ee=document.getElementById("volume-mounts-section"),ne=document.getElementById("volume-mounts-list");if(ne.innerHTML="",o.docker?.volumes?.length){const W=o.mediaMount?.containerPath,V=o.docker.volumes.filter(Y=>!Y.includes("{{MEDIA_PATH}}")&&!(W&&Y.endsWith(":"+W)));V.length>0?(ee.style.display="block",V.forEach((Y,X)=>{const[ae,te]=Y.split(":"),Q=document.createElement("div");Q.style.cssText="display: flex; gap: 6px; align-items: center;",Q.innerHTML=`
+Click Cancel to deploy a new container.`)&&(o._useExisting=!0,o._existingContainer=Y)}}catch{}d.textContent=`Deploy ${o.name}`;const a=o.subdomain||o.id.replace(/-/g,"");g.value=a;const t=document.getElementById("subpath-compat-warning");if(t)if(SITE.routingMode==="subdirectory"){const W=o.subpathSupport||"strip";W==="none"?(t.style.display="block",t.innerHTML='⚠ '+o.name+" does not support subdirectory mode. It may not work correctly at a subpath."):W==="strip"?(t.style.display="block",t.innerHTML='ⓘ '+o.name+" has unverified subdirectory support. It may require additional configuration."):t.style.display="none"}else t.style.display="none";const n=SITE.defaults.dnsType||(SITE.configurationType==="public"?"public":"private"),r=SITE.defaults.sslType||(SITE.configurationType==="public"?"letsencrypt":"internal"),m=document.querySelector(`input[name="dns-type"][value="${n}"]`),A=document.querySelector(`input[name="ssl-type"][value="${r}"]`);m?m.checked=!0:document.querySelector('input[name="dns-type"][value="private"]').checked=!0,A?A.checked=!0:document.querySelector('input[name="ssl-type"][value="internal"]').checked=!0,e.value=SITE.defaults.targetIP||"localhost",l.checked=!1;const F=document.querySelector("#app-deploy-modal .flex-col-gap")?.closest("div"),_=document.querySelector("#app-deploy-modal details"),U=_?.querySelector("div");if(_&&U&&(SITE.configurationType==="public"||SITE.configurationType==="homelab")){const W=document.querySelectorAll('#app-deploy-modal input[name="dns-type"]')[0]?.closest("div.flex-col-gap")?.parentElement,V=document.querySelectorAll('#app-deploy-modal input[name="ssl-type"]')[0]?.closest("div.flex-col-gap")?.parentElement;W&&!W.dataset.moved&&(U.appendChild(W),W.dataset.moved="1"),V&&!V.dataset.moved&&(U.appendChild(V),V.dataset.moved="1")}const q=document.getElementById("media-path-section"),J=document.getElementById("deploy-media-path"),G=document.getElementById("media-path-description");if(o.mediaMount){q.style.display="block",J.value="",J.placeholder="/media/Movies, /media/TVShows or click Browse";const W=document.getElementById("detected-mounts-container"),V=document.getElementById("detected-mounts-list");try{const X=await(await fetch("/api/v1/media/detected-mounts")).json();if(X.success&&X.mounts.length>0){W.style.display="block",V.innerHTML="";const ae=[...new Set(X.mounts.map(te=>te.hostPath))];J.value=ae.join(", "),X.mounts.forEach(te=>{const Q=document.createElement("button");Q.type="button";const de=ae.includes(te.hostPath);Q.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);`,Q.innerHTML=`${escapeHtml(te.folderName)} from ${escapeHtml(te.sourceImage)}`,Q.title=`${te.hostPath} (from ${te.sourceContainer})`,Q.onclick=()=>{const le=J.value.split(",").map(ce=>ce.trim()).filter(ce=>ce),pe=le.indexOf(te.hostPath);pe>=0?(le.splice(pe,1),Q.style.background="color-mix(in srgb, var(--success) 15%, var(--card-bg))"):(le.push(te.hostPath),Q.style.background="color-mix(in srgb, var(--success) 40%, var(--card-bg))"),J.value=le.join(", ")},V.appendChild(Q)})}else W.style.display="none"}catch{W.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 Z=document.getElementById("plex-claim-section");Z&&(o.id==="plex"||o.claimToken?(Z.style.display="block",document.getElementById("deploy-plex-claim").value=""):Z.style.display="none");const ee=document.getElementById("volume-mounts-section"),ne=document.getElementById("volume-mounts-list");if(ne.innerHTML="",o.docker?.volumes?.length){const W=o.mediaMount?.containerPath,V=o.docker.volumes.filter(Y=>!Y.includes("{{MEDIA_PATH}}")&&!(W&&Y.endsWith(":"+W)));V.length>0?(ee.style.display="block",V.forEach((Y,X)=>{const[ae,te]=Y.split(":"),Q=document.createElement("div");Q.style.cssText="display: flex; gap: 6px; align-items: center;",Q.innerHTML=`
\u2192 ${te}
@@ -358,7 +358,7 @@ Click Cancel to deploy a new container.`)&&(o._useExisting=!0,o._existingContain
Connected${V.self?.hostname} (${V.self?.ip})| ${V.deviceCount} devices
- `:V.installed?s.innerHTML='Not connected':(s.innerHTML='Not available',l.disabled=!0)}catch{s.innerHTML='Could not check status'}function se(){const W=g.value||"subdomain",V=document.querySelector('input[name="dns-type"]:checked').value,Y=document.querySelector('input[name="ssl-type"]:checked').value;let X="";if(SITE.routingMode==="subdirectory"&&SITE.domain)X=`https://${SITE.domain}/${W}`;else if(V==="private")X=`${Y==="none"?"http":"https"}://${buildDomain(W)}`;else if(V==="public"){const ae=Y==="none"?"http":"https",te=SITE.domain||W;X=SITE.domain?`${ae}://${W}.${SITE.domain}`:`${ae}://${W}`}else{const ae=i.value||o.defaultPort||DC.DEFAULTS.SERVICE_PORT;X=`http://${e.value}:${ae}`}p.textContent=X}g.oninput=se,e.oninput=se,i.oninput=se,document.querySelectorAll('input[name="dns-type"]').forEach(W=>{W.onchange=se}),document.querySelectorAll('input[name="ssl-type"]').forEach(W=>{W.onchange=se}),se(),N.classList.remove("show"),c.classList.add("show"),c.dataset.appTemplate=JSON.stringify(o)}async function x(o){const c=o.appTemplate,d=safeGetJSON(h,[]),g=c._useExisting&&c._existingContainer,p=d.find(e=>e.id===o.subdomain);if(!(p&&!g&&!confirm(`An app with subdomain "${o.subdomain}" already exists. Redeploy?`))){if(p){const e=d.indexOf(p);d.splice(e,1),safeSet(h,JSON.stringify(d))}if(g)o.port=c._existingContainer.primaryPort;else{const e=o.port||c.defaultPort||8080;showNotification(`Checking port ${e} availability...`,"info",0);const i=await R(e);if(!i.available){const l=await y(c.defaultPort||8080);if(confirm(`Port ${e} is already in use by ${i.conflict?.usedBy||"another container"}.
+ `:V.installed?s.innerHTML='Not connected':(s.innerHTML='Not available',l.disabled=!0)}catch{s.innerHTML='Could not check status'}function se(){const W=g.value||"subdomain",V=document.querySelector('input[name="dns-type"]:checked').value,Y=document.querySelector('input[name="ssl-type"]:checked').value;let X="";if(SITE.routingMode==="subdirectory"&&SITE.domain)X=`https://${SITE.domain}/${W}`;else if(V==="private")X=`${Y==="none"?"http":"https"}://${buildDomain(W)}`;else if(V==="public"){const ae=Y==="none"?"http":"https",te=SITE.domain||W;X=SITE.domain?`${ae}://${W}.${SITE.domain}`:`${ae}://${W}`}else{const ae=i.value||o.defaultPort||DC.DEFAULTS.SERVICE_PORT;X=`http://${e.value}:${ae}`}p.textContent=X}g.oninput=se,e.oninput=se,i.oninput=se,document.querySelectorAll('input[name="dns-type"]').forEach(W=>{W.onchange=se}),document.querySelectorAll('input[name="ssl-type"]').forEach(W=>{W.onchange=se}),se(),D.classList.remove("show"),c.classList.add("show"),c.dataset.appTemplate=JSON.stringify(o)}async function x(o){const c=o.appTemplate,d=safeGetJSON(h,[]),g=c._useExisting&&c._existingContainer,p=d.find(e=>e.id===o.subdomain);if(!(p&&!g&&!confirm(`An app with subdomain "${o.subdomain}" already exists. Redeploy?`))){if(p){const e=d.indexOf(p);d.splice(e,1),safeSet(h,JSON.stringify(d))}if(g)o.port=c._existingContainer.primaryPort;else{const e=o.port||c.defaultPort||8080;showNotification(`Checking port ${e} availability...`,"info",0);const i=await R(e);if(!i.available){const l=await y(c.defaultPort||8080);if(confirm(`Port ${e} is already in use by ${i.conflict?.usedBy||"another container"}.
Would you like to use port ${l} instead?`))o.port=l;else{showNotification("Deployment cancelled - port conflict","error",5e3);return}}}showNotification(g?`Configuring ${c.name} with existing container...`:`Deploying ${c.name}...`,"info",0);try{const e={appId:c.id,config:{subdomain:o.subdomain,ip:o.ip,createDns:o.dnsType==="private",port:o.port||c.defaultPort||null,sslType:o.sslType,dnsType:o.dnsType,tailscaleOnly:o.tailscaleOnly||!1,mediaPath:o.mediaPath||null,plexClaimToken:o.plexClaimToken||null,customVolumes:o.customVolumes||null}};g&&(e.config.useExisting=!0,e.config.existingContainerId=c._existingContainer.id,e.config.existingPort=c._existingContainer.primaryPort,!o.port&&c._existingContainer.primaryPort&&(e.config.port=c._existingContainer.primaryPort));const i={app:c.id,port:o.port||c.defaultPort||null,subdomain:o.subdomain||"",media_path:o.mediaPath||"",env:o.plexClaimToken?{PLEX_CLAIM:o.plexClaimToken}:{}},s=await(await secureFetch("/api/v1/deploys/catalog/deploy",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)})).json();if(s.success){const a={id:o.subdomain,name:c.name,logo:`/assets/${c.id}.png`,containerId:null,url:s.url||`http://127.0.0.1:${i.port}`,ip:o.ip,appTemplate:c.id,tailscaleOnly:o.tailscaleOnly||!1};d.push(a),safeSet(h,JSON.stringify(d)),window.APPS&&!window.APPS.some(n=>n.id===c.id)&&(window.APPS.push(a),typeof window.buildGrid=="function"&&window.buildGrid(),typeof window.refreshAll=="function"&&setTimeout(()=>window.refreshAll(),500));let t=s.usedExisting?`${c.name} configured with existing container!
URL: ${s.url}`:`${c.name} deployed successfully!
@@ -366,19 +366,19 @@ URL: ${s.url}`;s.warning&&(t+=`
\u26A0 Warning: ${s.warning}`),showNotification(t,"success",8e3),delete c._useExisting,delete c._existingContainer,s.url&&s.url.startsWith("https://")&&C(s.url,c.name),s.setupInstructions&&s.setupInstructions.length>0&&setTimeout(()=>{const n=s.setupInstructions.join(`
`);showNotification(`Setup Instructions for ${c.name}: ${n}`,"info",1e4)},1e3)}else throw new Error(s.error||"Deployment failed")}catch(e){b.logError("[AppSelector] Deployment",e,{function:"deploy"}),showNotification(`Failed to deploy ${c.name}: ${e.message}`,"error",8e3)}}}async function C(o,c){showNotification(`\u23F3 Generating SSL certificate for ${c}...`,"warning",6e4);let d=0;const g=12,p=async()=>{d++;try{const e=await fetch(o,{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",()=>{L(),N.classList.add("show")}),window.openDeployConfigFor=async function(o){if(!j&&!await $())return!1;const c=String(o||"").toLowerCase(),d=Object.entries(j).find(([p])=>p.toLowerCase()===c);if(!d)return!1;const g={id:d[0],...d[1]};return g.isDashboardWidget?(await L(),N.classList.add("show"),"selector"):(await z(g),!0)},wireModal(N,document.getElementById("app-selector-cancel"));const T=document.getElementById("app-deploy-modal");document.getElementById("app-deploy-cancel")?.addEventListener("click",()=>{T.classList.remove("show")}),document.getElementById("app-deploy-confirm")?.addEventListener("click",()=>{const o=JSON.parse(T.dataset.appTemplate),c=document.getElementById("deploy-media-path").value.trim(),d=[];document.querySelectorAll("#volume-mounts-list .vol-host-path").forEach(p=>{d.push({hostPath:p.value.trim(),containerPath:p.dataset.containerPath})});const g={appTemplate:o,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(!g.subdomain){showNotification("Please enter a subdomain or domain name","warning");return}if(o.mediaMount?.required&&!c){showNotification("Please enter a media library path for this application","warning");return}T.classList.remove("show"),x(g)}),wireModal(T);const P=document.getElementById("folder-browser-modal"),f=document.getElementById("folder-browser-path"),B=document.getElementById("folder-browser-list"),D=document.getElementById("folder-browser-selected"),F=document.getElementById("folder-browser-selected-list");let S="",I=[],H=null;window.openFolderBrowser=function(o){H=o,I=o.value.split(",").map(c=>c.trim()).filter(c=>c),S="",u(),E(""),P.classList.add("show")};async function E(o){f.textContent=o||"Select a drive...",B.innerHTML='
`;return}S=d.path||"",f.textContent=S||"Select a drive...";let g="";d.parent&&d.parent!==d.path&&(g+=`
+Try refreshing in a moment if you see a certificate error.`,"warning",1e4),!1}};setTimeout(p,3e3)}function k(){safeGetJSON(h,[]).forEach(c=>{window.APPS.some(d=>d.id===c.id)||window.APPS.push(c)})}document.getElementById("add-service-btn")?.addEventListener("click",()=>{L(),D.classList.add("show")}),window.openDeployConfigFor=async function(o){if(!j&&!await $())return!1;const c=String(o||"").toLowerCase(),d=Object.entries(j).find(([p])=>p.toLowerCase()===c);if(!d)return!1;const g={id:d[0],...d[1]};return g.isDashboardWidget?(await L(),D.classList.add("show"),"selector"):(await z(g),!0)},wireModal(D,document.getElementById("app-selector-cancel"));const T=document.getElementById("app-deploy-modal");document.getElementById("app-deploy-cancel")?.addEventListener("click",()=>{T.classList.remove("show")}),document.getElementById("app-deploy-confirm")?.addEventListener("click",()=>{const o=JSON.parse(T.dataset.appTemplate),c=document.getElementById("deploy-media-path").value.trim(),d=[];document.querySelectorAll("#volume-mounts-list .vol-host-path").forEach(p=>{d.push({hostPath:p.value.trim(),containerPath:p.dataset.containerPath})});const g={appTemplate:o,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(!g.subdomain){showNotification("Please enter a subdomain or domain name","warning");return}if(o.mediaMount?.required&&!c){showNotification("Please enter a media library path for this application","warning");return}T.classList.remove("show"),x(g)}),wireModal(T);const N=document.getElementById("folder-browser-modal"),f=document.getElementById("folder-browser-path"),B=document.getElementById("folder-browser-list"),P=document.getElementById("folder-browser-selected"),O=document.getElementById("folder-browser-selected-list");let S="",I=[],H=null;window.openFolderBrowser=function(o){H=o,I=o.value.split(",").map(c=>c.trim()).filter(c=>c),S="",u(),E(""),N.classList.add("show")};async function E(o){f.textContent=o||"Select a drive...",B.innerHTML='
@@ -496,7 +496,7 @@ Try refreshing in a moment if you see a certificate error.`,"warning",1e4),!1}};
\u23F3${escapeHtml(c.role||c.id)}Queued
- `,S.appendChild(d)}const E=document.querySelectorAll("#recipe-volume-list input[data-volume-key]"),u={};E.forEach(c=>{u[c.dataset.volumeKey]=c.value});const o={selectedComponents:H.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:u},componentOverrides:{}};for(const c of H)D(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:j.id,config:o})})).json();if(d.success){for(const g of d.deployed||[])D(g.id,"success",g.url?`Running \u2192 ${g.url}`:"Running");for(const g of d.errors||[])D(g.componentId,"error",g.error);I.style.display="",I.innerHTML=`
+ `,S.appendChild(d)}const E=document.querySelectorAll("#recipe-volume-list input[data-volume-key]"),u={};E.forEach(c=>{u[c.dataset.volumeKey]=c.value});const o={selectedComponents:H.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:u},componentOverrides:{}};for(const c of H)P(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:j.id,config:o})})).json();if(d.success){for(const g of d.deployed||[])P(g.id,"success",g.url?`Running \u2192 ${g.url}`:"Running");for(const g of d.errors||[])P(g.componentId,"error",g.error);I.style.display="",I.innerHTML=`
${escapeHtml(d.message||"Deployed!")}
${d.setupInstructions?`
@@ -508,7 +508,7 @@ Try refreshing in a moment if you see a certificate error.`,"warning",1e4),!1}};
Deployment failed: ${escapeHtml(d.error||"Unknown error")}
`,z.style.display="none",x.textContent="";return}if(!u&&o!==P)return;const p=Array.isArray(g.logs)?g.logs:[];if(p.length===0&&!u){const i=g.filters&&(g.filters.level||g.filters.context||g.filters.search||g.filters.since||g.filters.until)?"No error log entries match your filters.":"\u2705 No errors logged! Everything is working smoothly.";w.innerHTML=`
");for(const i of p){const l=(i.level||"?").toUpperCase(),s=l==="ERR"?"var(--bad-fg)":l==="WARN"?"var(--warn-fg, #f0c674)":"var(--muted)",a=i.timestamp?new Date(i.timestamp).toLocaleString():"\u2014",t=i.context||"\u2014",n=(i.error||"").split(`
-`)[0],r=i.request&&i.request.ip||"";e+='
`,z.style.display="none",x.textContent="";return}if(!u&&o!==N)return;const p=Array.isArray(g.logs)?g.logs:[];if(p.length===0&&!u){const i=g.filters&&(g.filters.level||g.filters.context||g.filters.search||g.filters.since||g.filters.until)?"No error log entries match your filters.":"\u2705 No errors logged! Everything is working smoothly.";w.innerHTML=`
");for(const i of p){const l=(i.level||"?").toUpperCase(),s=l==="ERR"?"var(--bad-fg)":l==="WARN"?"var(--warn-fg, #f0c674)":"var(--muted)",a=i.timestamp?new Date(i.timestamp).toLocaleString():"\u2014",t=i.context||"\u2014",n=(i.error||"").split(`
+`)[0],r=i.request&&i.request.ip||"";e+='
'})}})(),(function(){"use strict";const b=[{unit:"caddy",label:"Caddy (reverse proxy)"},{unit:"dashcaddy-api",label:"DashCaddy API (host systemd unit, not this container)"},{unit:"docker",label:"Docker daemon"},{unit:"ssh",label:"SSH server"},{unit:"systemd-journald",label:"systemd-journald"},{unit:"tailscaled",label:"Tailscale"},{unit:"networkd-dispatcher",label:"Networkd dispatcher"}];injectModal("journald-modal",`
+ `}function d(n,r=""){if(!n||n.length===0){j.innerHTML='
No logs available
',k.textContent="0 lines",T.textContent="0 filtered";return}if(O=n,S=r?n.filter(m=>m.text&&m.text.toLowerCase().includes(r.toLowerCase())):n,k.textContent=`${n.length} lines`,T.textContent=r?`${S.length} of ${n.length} shown`:`${n.length} shown`,S.length===0){j.innerHTML=`
No logs match "${o(r)}"
`;return}j.innerHTML=S.map((m,A)=>c(m,A)).join(""),j.scrollTop=j.scrollHeight}async function g(){try{const r=(await getJSON("/api/v1/logs/containers")).containers||[],m=h.value;h.innerHTML='',r.forEach(A=>{const F=document.createElement("option");F.value=A.id,F.textContent=`${A.name} (${A.image.split(":")[0]}) - ${A.status}`,F.dataset.name=A.name,F.dataset.image=A.image,F.dataset.status=A.status,F.dataset.created=A.created,h.appendChild(F)}),m&&h.querySelector(`option[value="${m}"]`)&&(h.value=m,p(m))}catch(n){console.error("Failed to load containers:",n)}}function p(n){const r=h.querySelector(`option[value="${n}"]`);r&&(N.textContent=r.dataset.image||"-",f.textContent=r.dataset.status||"-",f.style.color=r.dataset.status==="running"?"var(--ok-fg, #4ade80)":"var(--bad-fg, #ef4444)",B.textContent=u(r.dataset.created))}async function e(){const n=h.value;if(!n){j.innerHTML='
'})}})(),(function(){"use strict";const b=[{unit:"caddy",label:"Caddy (reverse proxy)"},{unit:"dashcaddy-api",label:"DashCaddy API (host systemd unit, not this container)"},{unit:"docker",label:"Docker daemon"},{unit:"ssh",label:"SSH server"},{unit:"systemd-journald",label:"systemd-journald"},{unit:"tailscaled",label:"Tailscale"},{unit:"networkd-dispatcher",label:"Networkd dispatcher"}];injectModal("journald-modal",`
@@ -698,7 +698,7 @@ Try refreshing in a moment if you see a certificate error.`,"warning",1e4),!1}};
`}).join("");w.innerHTML=i,w.scrollHeight-w.scrollTop-w.clientHeight<80&&(w.scrollTop=w.scrollHeight)}z.textContent=`${f.length} entries`,x.textContent=p?`${e.length} of ${f.length} shown`:`${f.length} shown`}async function u(){if(!P)return;c();const p=j.value;if(!p)return;const e=Math.max(1,Math.min(5e3,Number(N.value)||200)),i=(v.value||"").trim();w.innerHTML='
`}).join("");w.innerHTML=i,w.scrollHeight-w.scrollTop-w.clientHeight<80&&(w.scrollTop=w.scrollHeight)}z.textContent=`${f.length} entries`,x.textContent=p?`${e.length} of ${f.length} shown`:`${f.length} shown`}async function u(){if(!N)return;c();const p=j.value;if(!p)return;const e=Math.max(1,Math.min(5e3,Number(D.value)||200)),i=(v.value||"").trim();w.innerHTML='
@@ -752,7 +752,7 @@ Try refreshing in a moment if you see a certificate error.`,"warning",1e4),!1}};
-
`);const b=document.getElementById("snapshot-modal"),h=document.getElementById("snapshot-btn"),j=document.getElementById("snapshot-close"),v=document.getElementById("snapshot-container-select"),N=document.getElementById("snapshot-details"),M=document.getElementById("snapshot-create-btn"),$=document.getElementById("snapshot-create-status");let R=null;async function y(){try{const k=await(await fetch("/api/v1/containers")).json();if(!k.success||!k.containers)return;v.innerHTML='';for(const T of k.containers){const P=document.createElement("option");P.value=T.id,P.textContent=`${T.name||T.id} (${T.image||"unknown"})`,P.dataset.name=T.name,P.dataset.image=T.image,P.dataset.status=T.status,P.dataset.created=T.created,v.appendChild(P)}}catch(C){console.error("Failed to load containers:",C)}}function L(C){if(!C||!C.value){N.style.display="none",R=null;return}R=C.value,document.getElementById("snapshot-image").textContent=C.dataset.image||"-",document.getElementById("snapshot-status").textContent=C.dataset.status||"-",document.getElementById("snapshot-created").textContent=C.dataset.created?new Date(C.dataset.created*1e3).toLocaleString():"-",document.getElementById("snapshot-id").textContent=C.value.substring(0,12),N.style.display=""}async function w(){if(!R){$.textContent="Please select a container first",$.style.color="var(--bad-fg)";return}const C=document.getElementById("snapshot-name").value.trim();if(!C){$.textContent="Please enter a snapshot name",$.style.color="var(--bad-fg)";return}const k=document.getElementById("snapshot-leave-running").checked;M.disabled=!0,M.textContent="Creating...",$.textContent="";try{const P=await(await fetch(`/api/v1/containers/${encodeURIComponent(R)}/checkpoint`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:C,leaveRunning:k})})).json();P.success?($.textContent=`\u2713 Snapshot "${C}" created successfully`,$.style.color="var(--ok-fg)",document.getElementById("snapshot-name").value=""):($.textContent=`\u2717 Failed: ${P.error||"Unknown error"}`,$.style.color="var(--bad-fg)")}catch(T){$.textContent=`\u2717 Error: ${T.message}`,$.style.color="var(--bad-fg)"}finally{M.disabled=!1,M.textContent="\u{1F4BE} Create Snapshot"}}function z(){b.classList.add("show"),y()}function x(){b.classList.remove("show"),N.style.display="none",R=null,v.selectedIndex=0}h?.addEventListener("click",z),j?.addEventListener("click",x),wireModal(b,j),v?.addEventListener("change",C=>{const k=v.options[v.selectedIndex];L(k)}),M?.addEventListener("click",w),b?.querySelectorAll(".panel-tab").forEach(C=>{C.addEventListener("click",()=>{b.querySelectorAll(".panel-tab").forEach(k=>k.classList.remove("active")),b.querySelectorAll(".panel-section").forEach(k=>k.classList.remove("active")),C.classList.add("active"),b.querySelector(`#${C.dataset.panel}`).classList.add("active")})})})(),(function(){injectModal("arr-setup-modal",`
+
`);const b=document.getElementById("snapshot-modal"),h=document.getElementById("snapshot-btn"),j=document.getElementById("snapshot-close"),v=document.getElementById("snapshot-container-select"),D=document.getElementById("snapshot-details"),M=document.getElementById("snapshot-create-btn"),$=document.getElementById("snapshot-create-status");let R=null;async function y(){try{const k=await(await fetch("/api/v1/containers")).json();if(!k.success||!k.containers)return;v.innerHTML='';for(const T of k.containers){const N=document.createElement("option");N.value=T.id,N.textContent=`${T.name||T.id} (${T.image||"unknown"})`,N.dataset.name=T.name,N.dataset.image=T.image,N.dataset.status=T.status,N.dataset.created=T.created,v.appendChild(N)}}catch(C){console.error("Failed to load containers:",C)}}function L(C){if(!C||!C.value){D.style.display="none",R=null;return}R=C.value,document.getElementById("snapshot-image").textContent=C.dataset.image||"-",document.getElementById("snapshot-status").textContent=C.dataset.status||"-",document.getElementById("snapshot-created").textContent=C.dataset.created?new Date(C.dataset.created*1e3).toLocaleString():"-",document.getElementById("snapshot-id").textContent=C.value.substring(0,12),D.style.display=""}async function w(){if(!R){$.textContent="Please select a container first",$.style.color="var(--bad-fg)";return}const C=document.getElementById("snapshot-name").value.trim();if(!C){$.textContent="Please enter a snapshot name",$.style.color="var(--bad-fg)";return}const k=document.getElementById("snapshot-leave-running").checked;M.disabled=!0,M.textContent="Creating...",$.textContent="";try{const N=await(await fetch(`/api/v1/containers/${encodeURIComponent(R)}/checkpoint`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:C,leaveRunning:k})})).json();N.success?($.textContent=`\u2713 Snapshot "${C}" created successfully`,$.style.color="var(--ok-fg)",document.getElementById("snapshot-name").value=""):($.textContent=`\u2717 Failed: ${N.error||"Unknown error"}`,$.style.color="var(--bad-fg)")}catch(T){$.textContent=`\u2717 Error: ${T.message}`,$.style.color="var(--bad-fg)"}finally{M.disabled=!1,M.textContent="\u{1F4BE} Create Snapshot"}}function z(){b.classList.add("show"),y()}function x(){b.classList.remove("show"),D.style.display="none",R=null,v.selectedIndex=0}h?.addEventListener("click",z),j?.addEventListener("click",x),wireModal(b,j),v?.addEventListener("change",C=>{const k=v.options[v.selectedIndex];L(k)}),M?.addEventListener("click",w),b?.querySelectorAll(".panel-tab").forEach(C=>{C.addEventListener("click",()=>{b.querySelectorAll(".panel-tab").forEach(k=>k.classList.remove("active")),b.querySelectorAll(".panel-section").forEach(k=>k.classList.remove("active")),C.classList.add("active"),b.querySelector(`#${C.dataset.panel}`).classList.add("active")})})})(),(function(){injectModal("arr-setup-modal",`
\u{1F3AC} Smart Arr Connect
@@ -831,7 +831,7 @@ Try refreshing in a moment if you see a certificate error.`,"warning",1e4),!1}};
-
`);const b=document.getElementById("arr-setup-modal"),h=document.getElementById("arr-setup-btn"),j=document.getElementById("arr-setup-cancel"),v=document.getElementById("smart-connect-btn"),N=document.getElementById("smart-phase-detect"),M=document.getElementById("smart-phase-credentials"),$=document.getElementById("smart-phase-progress"),R=document.getElementById("smart-phase-results"),y=document.getElementById("smart-detect-results"),L=document.getElementById("smart-credential-inputs"),w=document.getElementById("smart-progress-steps"),z=document.getElementById("smart-results-content"),x=document.getElementById("smart-plex-libraries"),C=document.getElementById("smart-retry-btn");let k=null;const T={plex:"\u{1F3AC}",radarr:"\u{1F3AC}",sonarr:"\u{1F4FA}",prowlarr:"\u{1F50D}",seerr:"\u{1F4CB}"},P={plex:"Plex",radarr:"Radarr (Movies)",sonarr:"Sonarr (TV)",prowlarr:"Prowlarr (Indexers)",seerr:"Seerr"};function f(E){N.style.display=E==="detect"?"block":"none",M.style.display=E==="credentials"?"block":"none",$.style.display=E==="progress"?"block":"none",R.style.display=E==="results"?"block":"none"}function B(E){const u={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"}},o=u[E]||u.not_found;return`${o.icon} ${o.text}`}async function D(){f("detect"),y.style.display="none";try{if(k=await(await fetch("/api/v1/arr/smart-detect")).json(),!k.success){y.innerHTML=`
`,y.style.display="block"}}function F(E){let u="";const o=E.services,c=["radarr","sonarr","prowlarr"];for(const p of c){const e=o[p];if(!e||e.status==="not_found"&&!e.url)continue;const i=T[p],l=P[p],s=e.status==="connected";u+=`
`,y.style.display="block"}}function O(E){let u="";const o=E.services,c=["radarr","sonarr","prowlarr"];for(const p of c){const e=o[p];if(!e||e.status==="not_found"&&!e.url)continue;const i=T[p],l=N[p],s=e.status==="connected";u+=`
${i}${l}
@@ -897,7 +897,7 @@ Try refreshing in a moment if you see a certificate error.`,"warning",1e4),!1}};
`;for(const c of u.libraries){const d=c.type==="movie"?"\u{1F3AC}":c.type==="show"?"\u{1F4FA}":"\u{1F3B5}";o+=`
"}}}async function H(l,s){try{var a=await secureFetch("/api/v1/backups/schedule",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({appId:l,...s})}),t=await a.json();t.success?showNotification("Schedule updated for "+l,"success"):(showNotification("Update failed: "+(t.error||"Unknown"),"error"),I())}catch(n){showNotification("Error: "+n.message,"error")}}async function E(l){try{var s=await secureFetch("/api/v1/backups/backup/"+encodeURIComponent(l),{method:"POST",headers:{"Content-Type":"application/json"}}),a=await s.json();a.success?showNotification("Backup started for "+l+"!","success"):showNotification("Backup failed: "+(a.error||"Unknown"),"error")}catch(t){showNotification("Error: "+t.message,"error")}}async function u(l){if(confirm("Remove backup schedule for "+l+"?"))try{var s=await secureFetch("/api/v1/backups/schedule/"+encodeURIComponent(l),{method:"DELETE"}),a=await s.json();a.success?(showNotification("Schedule removed for "+l,"success"),I()):showNotification("Delete failed: "+(a.error||"Unknown"),"error")}catch(t){showNotification("Error: "+t.message,"error")}}async function o(){var l=document.getElementById("new-schedule-appid")?.value?.trim(),s=document.getElementById("new-schedule-interval")?.value||"daily",a=parseInt(document.getElementById("new-schedule-retention")?.value)||7;if(!l){showNotification("Please enter an App ID","warning");return}try{var t=await secureFetch("/api/v1/backups/schedule",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({appId:l,schedule:s,retention:{keep:a},enabled:!0})}),n=await t.json();if(n.success){showNotification("Schedule created for "+l,"success"),I();var r=document.getElementById("new-schedule-appid");r&&(r.value="")}else showNotification("Failed: "+(n.error||"Unknown"),"error")}catch(m){showNotification("Error: "+m.message,"error")}}async function c(){if(D){D.innerHTML='
Loading...
';try{var l=await fetch("/api/v1/backups/files"),s=await l.json();if(!s.success)throw new Error(s.error||"Failed to load");var a=s.files||[];if(a.length===0){D.innerHTML='
"}}}window.__restoreServerBackup=async function(l){if(confirm("Restore from this server backup? This will overwrite current configuration."))try{var s=await secureFetch("/api/v1/backups/restore/"+l,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({restoreServices:!0,restoreConfig:!0})}),a=await s.json();a.success?(showNotification("Restore completed successfully!","success"),location.reload()):showNotification("Restore failed: "+(a.error||"Unknown error"),"error")}catch(t){showNotification("Restore error: "+t.message,"error")}},document.querySelector('[data-panel="backup-schedules-tab"]')?.addEventListener("click",I),document.querySelector('[data-panel="backup-disk-tab"]')?.addEventListener("click",c),document.querySelector('[data-panel="backup-pointintime-tab"]')?.addEventListener("click",g),document.querySelector('[data-panel="backup-history-tab"]')?.addEventListener("click",d);async function g(){if(F){try{var l=await fetch("/api/v1/license/status"),s=await l.json();if(s.tier!=="premium"){F.innerHTML='
\u2B50
Premium Feature
Point-in-time restore requires DashCaddy Premium with auto-backup enabled.
"}}}async function H(l,s){try{var a=await secureFetch("/api/v1/backups/schedule",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({appId:l,...s})}),t=await a.json();t.success?showNotification("Schedule updated for "+l,"success"):(showNotification("Update failed: "+(t.error||"Unknown"),"error"),I())}catch(n){showNotification("Error: "+n.message,"error")}}async function E(l){try{var s=await secureFetch("/api/v1/backups/backup/"+encodeURIComponent(l),{method:"POST",headers:{"Content-Type":"application/json"}}),a=await s.json();a.success?showNotification("Backup started for "+l+"!","success"):showNotification("Backup failed: "+(a.error||"Unknown"),"error")}catch(t){showNotification("Error: "+t.message,"error")}}async function u(l){if(confirm("Remove backup schedule for "+l+"?"))try{var s=await secureFetch("/api/v1/backups/schedule/"+encodeURIComponent(l),{method:"DELETE"}),a=await s.json();a.success?(showNotification("Schedule removed for "+l,"success"),I()):showNotification("Delete failed: "+(a.error||"Unknown"),"error")}catch(t){showNotification("Error: "+t.message,"error")}}async function o(){var l=document.getElementById("new-schedule-appid")?.value?.trim(),s=document.getElementById("new-schedule-interval")?.value||"daily",a=parseInt(document.getElementById("new-schedule-retention")?.value)||7;if(!l){showNotification("Please enter an App ID","warning");return}try{var t=await secureFetch("/api/v1/backups/schedule",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({appId:l,schedule:s,retention:{keep:a},enabled:!0})}),n=await t.json();if(n.success){showNotification("Schedule created for "+l,"success"),I();var r=document.getElementById("new-schedule-appid");r&&(r.value="")}else showNotification("Failed: "+(n.error||"Unknown"),"error")}catch(m){showNotification("Error: "+m.message,"error")}}async function c(){if(P){P.innerHTML='
Loading...
';try{var l=await fetch("/api/v1/backups/files"),s=await l.json();if(!s.success)throw new Error(s.error||"Failed to load");var a=s.files||[];if(a.length===0){P.innerHTML='
"}}}window.__restoreServerBackup=async function(l){if(confirm("Restore from this server backup? This will overwrite current configuration."))try{var s=await secureFetch("/api/v1/backups/restore/"+l,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({restoreServices:!0,restoreConfig:!0})}),a=await s.json();a.success?(showNotification("Restore completed successfully!","success"),location.reload()):showNotification("Restore failed: "+(a.error||"Unknown error"),"error")}catch(t){showNotification("Restore error: "+t.message,"error")}},document.querySelector('[data-panel="backup-schedules-tab"]')?.addEventListener("click",I),document.querySelector('[data-panel="backup-disk-tab"]')?.addEventListener("click",c),document.querySelector('[data-panel="backup-pointintime-tab"]')?.addEventListener("click",g),document.querySelector('[data-panel="backup-history-tab"]')?.addEventListener("click",d);async function g(){if(O){try{var l=await fetch("/api/v1/license/status"),s=await l.json();if(s.tier!=="premium"){O.innerHTML='
\u2B50
Premium Feature
Point-in-time restore requires DashCaddy Premium with auto-backup enabled.
Configuration differs \u2014 restoring will replace current settings
':r+='
No changes
',r+="
"}r+='
',document.body.insertAdjacentHTML("beforeend",r),document.getElementById("compare-close-btn")?.addEventListener("click",function(){document.getElementById("compare-overlay")?.remove()}),document.getElementById("compare-overlay")?.addEventListener("click",function(F){F.target===this&&this.remove()})}catch(F){showNotification("Compare error: "+F.message,"error")}}async function i(l,s){if(confirm("Restore "+s+" for "+l+`?
This will replace current configuration, credentials, and data. Containers will be restarted.`))try{var a=await secureFetch("/api/v1/apps/"+encodeURIComponent(l)+"/revert/"+encodeURIComponent(s),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({restartContainers:!0})}),t=await a.json();t.success?(showNotification(l+" restored to "+s,"success"),setTimeout(function(){location.reload()},1500)):showNotification("Restore failed: "+(t.error||"Unknown"),"error")}catch(n){showNotification("Restore error: "+n.message,"error")}}})(),(function(){injectModal("stats-modal",`
@@ -1305,7 +1305,7 @@ This will replace current configuration, credentials, and data. Containers will
- `);const b=document.getElementById("stats-modal"),h=document.getElementById("container-stats-btn"),j=document.getElementById("stats-cancel"),v=document.getElementById("stats-refresh-btn"),N=document.getElementById("stats-auto-refresh"),M=document.getElementById("stats-container"),$=document.getElementById("stats-aggregated-container"),R=document.getElementById("stats-alerts-container"),y=document.getElementById("stats-last-update");let L=null,w=null;function z(d){if(d===0||!d)return"0 B";const g=1024,p=["B","KB","MB","GB"],e=Math.floor(Math.log(d)/Math.log(g));return parseFloat((d/Math.pow(g,e)).toFixed(1))+" "+p[e]}function x(d){return d<30?"#2ecc71":d<70?"#f39c12":"#e74c3c"}function C(d){return d<50?"#2ecc71":d<80?"#f39c12":"#e74c3c"}async function k(){try{let d=null,g=!1;try{const i=await(await fetch("/api/v1/monitoring/stats")).json();i.success&&i.stats&&(d=i.stats,g=!0,w=i.stats)}catch{}if(!g){const i=await(await fetch("/api/v1/stats/containers")).json();if(i.success&&i.stats){d={};for(const l of i.stats)d[l.name]={name:l.name,current:{cpu:l.cpu,memory:{percent:l.memory.percent,usage:l.memory.used,limit:l.memory.limit,usageMB:Math.round(l.memory.used/1048576),limitMB:Math.round(l.memory.limit/1048576)},network:{rxBytes:l.network.rx,txBytes:l.network.tx,rxMB:(l.network.rx/1048576).toFixed(1),txMB:(l.network.tx/1048576).toFixed(1)},disk:{readMB:0,writeMB:0}},status:l.status};w=d}}if(!d||Object.keys(d).length===0){M.innerHTML='
';try{const i=await(await fetch(`/api/v1/monitoring/history/${encodeURIComponent(d)}?startTime=${p}&endTime=${g}`)).json();if(!i.success)throw new Error(i.error||"Failed to load history");const l=i.samples||[],s=i.tier||"raw";if(l.length===0){F.innerHTML=`
\u{1F4CA}No data for the last ${I}. Tier: ${E(s)}.
`;return}const a=s==="raw",t=a?O=>O.cpu?.percent:O=>O.cpu?.avg,n=a?O=>O.memory?.percent:O=>O.memory?.avgPercent,r=a?O=>O.network?.rxMB||0:O=>O.network?.rxMB||0,m=a?O=>O.network?.txMB||0:O=>O.network?.txMB||0;let A=`
+ `}function o(){if(!P)return;const d=w||{},g=P.value,p=Object.entries(d);if(p.length===0){P.innerHTML='';return}P.innerHTML=p.map(([e,i])=>``).join(""),g&&d[g]&&(P.value=g)}async function c(){if(!O||!P)return;const d=P.value;if(!d){O.innerHTML='
';try{const i=await(await fetch(`/api/v1/monitoring/history/${encodeURIComponent(d)}?startTime=${p}&endTime=${g}`)).json();if(!i.success)throw new Error(i.error||"Failed to load history");const l=i.samples||[],s=i.tier||"raw";if(l.length===0){O.innerHTML=`
\u{1F4CA}No data for the last ${I}. Tier: ${E(s)}.
@@ -1561,7 +1561,7 @@ This will replace current configuration, credentials, and data. Containers will
-
`);const b=document.getElementById("health-modal"),h=document.getElementById("health-check-btn"),j=document.getElementById("health-cancel"),v=document.getElementById("health-refresh-btn"),N=document.getElementById("health-status-container"),M=document.getElementById("health-incidents-container"),$=document.getElementById("health-config-container"),R=document.getElementById("health-last-update"),y=document.getElementById("health-add-btn"),L=document.getElementById("health-config-form"),w=document.getElementById("health-form-title"),z=document.getElementById("health-form-cancel"),x=document.getElementById("health-form-save"),C="dashcaddy-health-settings",k={retentionDays:30,pollingInterval:60,statsPollingInterval:30,maxEntriesPerService:500,diskUsageThreshold:80},T=document.getElementById("health-global-save"),P=document.getElementById("health-global-reset"),f=document.getElementById("health-global-status"),B=document.getElementById("health-setting-retention"),D=document.getElementById("health-setting-interval"),F=document.getElementById("health-setting-stats-interval"),S=document.getElementById("health-setting-max-entries"),I=document.getElementById("health-setting-disk-threshold");function H(){try{const a=safeGet(C),t=a?JSON.parse(a):{};return Object.assign({},k,t)}catch{return Object.assign({},k)}}function E(){const a=H();B&&(B.value=a.retentionDays),D&&(D.value=a.pollingInterval),F&&(F.value=a.statsPollingInterval),S&&(S.value=a.maxEntriesPerService),I&&(I.value=a.diskUsageThreshold)}function u(){const a={retentionDays:Math.max(1,Math.min(3650,parseInt(B?.value)||k.retentionDays)),pollingInterval:Math.max(5,Math.min(3600,parseInt(D?.value)||k.pollingInterval)),statsPollingInterval:Math.max(5,Math.min(3600,parseInt(F?.value)||k.statsPollingInterval)),maxEntriesPerService:Math.max(10,Math.min(1e5,parseInt(S?.value)||k.maxEntriesPerService)),diskUsageThreshold:Math.max(50,Math.min(99,parseInt(I?.value)||k.diskUsageThreshold))};try{safeSet(C,JSON.stringify(a)),E(),f&&(f.textContent="Saved \u2713",f.style.color="var(--ok-fg)",setTimeout(()=>{f&&(f.textContent="")},2500)),typeof showNotification=="function"&&showNotification("Global health settings saved","success")}catch(t){f&&(f.textContent="Save failed",f.style.color="var(--bad-fg)"),typeof showNotification=="function"&&showNotification("Failed to save settings: "+t.message,"error")}}function o(){try{safeSet(C,JSON.stringify(k))}catch{}E(),f&&(f.textContent="Reset to defaults \u2713",f.style.color="var(--ok-fg)",setTimeout(()=>{f&&(f.textContent="")},2500))}E(),T?.addEventListener("click",u),P?.addEventListener("click",o);let c=null;function d(a){return a>=99.9?"var(--ok-fg)":a>=95?"#f39c12":"var(--bad-fg)"}function g(a){const t={critical:"var(--bad-fg)",high:"#ff6b6b",medium:"#f39c12",low:"var(--muted)"};return`${a}`}async function p(){try{const t=await(await fetch("/api/v1/health-checks/status")).json();if(!t.success||!t.status||Object.keys(t.status).length===0){N.innerHTML='
\u{1F3E5}No health checks configured. Go to the Configure tab to add services.
';return}const n=Object.values(t.status);let r='
';r+='
',r+='
Service
Status
',r+='
Uptime 24h
Uptime 7d
',r+='
Avg Response
Last Check
';for(const m of n){const A=m.status==="up",O=A?"var(--dot-ok)":"var(--dot-bad)",_=m.uptime?.["24h"]??"-",U=m.uptime?.["7d"]??"-",q=m.avgResponseTime!=null?Math.round(m.avgResponseTime)+"ms":"-",J=m.timestamp?timeAgo(m.timestamp):"-";r+=`
`,r+=`
${escapeHtml(m.name||m.serviceId)}
`,r+=`
${A?"Up":"Down"}
`,r+=`
${typeof _=="number"?_.toFixed(1)+"%":_}
`,r+=`
${typeof U=="number"?U.toFixed(1)+"%":U}
`,r+=`
${q}
`,r+=`
${J}
`,r+="
",r+=`
Loading details...
`}r+="
",N.innerHTML=r,R.textContent="Updated "+new Date().toLocaleTimeString(),N.querySelectorAll("tr[data-health-id]").forEach(m=>{m.addEventListener("click",async()=>{const A=m.dataset.healthId,O=document.getElementById("health-detail-"+A);if(O){if(O.style.display!=="none"){O.style.display="none";return}O.style.display="";try{const U=await(await fetch(`/api/v1/health-checks/${A}/stats?hours=24`)).json();if(U.success&&U.stats){const q=U.stats,J=q.responseTime||{};O.querySelector("td").innerHTML=`
+ `);const b=document.getElementById("health-modal"),h=document.getElementById("health-check-btn"),j=document.getElementById("health-cancel"),v=document.getElementById("health-refresh-btn"),D=document.getElementById("health-status-container"),M=document.getElementById("health-incidents-container"),$=document.getElementById("health-config-container"),R=document.getElementById("health-last-update"),y=document.getElementById("health-add-btn"),L=document.getElementById("health-config-form"),w=document.getElementById("health-form-title"),z=document.getElementById("health-form-cancel"),x=document.getElementById("health-form-save"),C="dashcaddy-health-settings",k={retentionDays:30,pollingInterval:60,statsPollingInterval:30,maxEntriesPerService:500,diskUsageThreshold:80},T=document.getElementById("health-global-save"),N=document.getElementById("health-global-reset"),f=document.getElementById("health-global-status"),B=document.getElementById("health-setting-retention"),P=document.getElementById("health-setting-interval"),O=document.getElementById("health-setting-stats-interval"),S=document.getElementById("health-setting-max-entries"),I=document.getElementById("health-setting-disk-threshold");function H(){try{const a=safeGet(C),t=a?JSON.parse(a):{};return Object.assign({},k,t)}catch{return Object.assign({},k)}}function E(){const a=H();B&&(B.value=a.retentionDays),P&&(P.value=a.pollingInterval),O&&(O.value=a.statsPollingInterval),S&&(S.value=a.maxEntriesPerService),I&&(I.value=a.diskUsageThreshold)}function u(){const a={retentionDays:Math.max(1,Math.min(3650,parseInt(B?.value)||k.retentionDays)),pollingInterval:Math.max(5,Math.min(3600,parseInt(P?.value)||k.pollingInterval)),statsPollingInterval:Math.max(5,Math.min(3600,parseInt(O?.value)||k.statsPollingInterval)),maxEntriesPerService:Math.max(10,Math.min(1e5,parseInt(S?.value)||k.maxEntriesPerService)),diskUsageThreshold:Math.max(50,Math.min(99,parseInt(I?.value)||k.diskUsageThreshold))};try{safeSet(C,JSON.stringify(a)),E(),f&&(f.textContent="Saved \u2713",f.style.color="var(--ok-fg)",setTimeout(()=>{f&&(f.textContent="")},2500)),typeof showNotification=="function"&&showNotification("Global health settings saved","success")}catch(t){f&&(f.textContent="Save failed",f.style.color="var(--bad-fg)"),typeof showNotification=="function"&&showNotification("Failed to save settings: "+t.message,"error")}}function o(){try{safeSet(C,JSON.stringify(k))}catch{}E(),f&&(f.textContent="Reset to defaults \u2713",f.style.color="var(--ok-fg)",setTimeout(()=>{f&&(f.textContent="")},2500))}E(),T?.addEventListener("click",u),N?.addEventListener("click",o);let c=null;function d(a){return a>=99.9?"var(--ok-fg)":a>=95?"#f39c12":"var(--bad-fg)"}function g(a){const t={critical:"var(--bad-fg)",high:"#ff6b6b",medium:"#f39c12",low:"var(--muted)"};return`${a}`}async function p(){try{const t=await(await fetch("/api/v1/health-checks/status")).json();if(!t.success||!t.status||Object.keys(t.status).length===0){D.innerHTML='
\u{1F3E5}No health checks configured. Go to the Configure tab to add services.
';return}const n=Object.values(t.status);let r='
';r+='
',r+='
Service
Status
',r+='
Uptime 24h
Uptime 7d
',r+='
Avg Response
Last Check
';for(const m of n){const A=m.status==="up",F=A?"var(--dot-ok)":"var(--dot-bad)",_=m.uptime?.["24h"]??"-",U=m.uptime?.["7d"]??"-",q=m.avgResponseTime!=null?Math.round(m.avgResponseTime)+"ms":"-",J=m.timestamp?timeAgo(m.timestamp):"-";r+=`
';for(const _ of O){const U=_.status==="resolved",q=U&&_.duration?_.duration<6e4?Math.round(_.duration/1e3)+"s":Math.round(_.duration/6e4)+"m":"-";m+='
',m+=`
${escapeHtml(_.serviceId)}
`,m+=`
${escapeHtml(_.type)}
`,m+=`
${g(_.severity)}
`,m+=`
${_.status}
`,m+=`
${q}
`,m+=`
${timeAgo(_.createdAt)}
`,m+="
"}m+="
"}M.innerHTML=m||'
\u{1F6A8}No incidents recorded yet.
'}catch(a){M.innerHTML=`
Failed: ${escapeHtml(a.message)}
`}}async function i(){try{const t=await(await fetch("/api/v1/health-checks/status")).json(),n=t.success&&t.status?Object.values(t.status):[];if(n.length===0){$.innerHTML='
\u2699\uFE0FNo health checks configured yet. Click "Add Health Check" below.
`}}function l(a,t,n,r,m,A,O){c=a||null,w.textContent=a?"Edit Health Check":"Add Health Check",document.getElementById("health-form-id").value=a||"",document.getElementById("health-form-id").disabled=!!a,document.getElementById("health-form-name").value=t||"",document.getElementById("health-form-url").value=n||"",document.getElementById("health-form-timeout").value=r||1e4,document.getElementById("health-form-codes").value=m||"200",document.getElementById("health-form-sla").value=A||99.9,document.getElementById("health-form-slow").value=O||5e3,L.style.display="",y.style.display="none"}function s(){L.style.display="none",y.style.display="",c=null}y?.addEventListener("click",()=>l("","","",1e4,"200",99.9,5e3)),z?.addEventListener("click",s),x?.addEventListener("click",async()=>{const a=c||document.getElementById("health-form-id").value.trim();if(!a)return showNotification("Service ID is required","warning");const t=document.getElementById("health-form-url").value.trim();if(!t)return showNotification("URL is required","warning");const n=document.getElementById("health-form-codes").value.split(",").map(m=>parseInt(m.trim())).filter(Boolean),r={name:document.getElementById("health-form-name").value.trim()||a,url:t,timeout:parseInt(document.getElementById("health-form-timeout").value)||1e4,expectedStatusCodes:n.length?n:[200],sla:{target:parseFloat(document.getElementById("health-form-sla").value)||99.9},slowResponseThreshold:parseInt(document.getElementById("health-form-slow").value)||5e3};try{x.textContent="Saving...",x.disabled=!0;const A=await(await secureFetch(`/api/v1/health-checks/${encodeURIComponent(a)}/configure`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)})).json();if(!A.success)throw new Error(A.error||"Save failed");s(),i(),p()}catch(m){showNotification("Error: "+m.message,"error")}finally{x.textContent="Save",x.disabled=!1}}),document.addEventListener("health-edit",async a=>{const t=a.detail;l(t,"","",1e4,"200",99.9,5e3)}),document.addEventListener("health-delete",async a=>{const t=a.detail;if(confirm(`Delete health check for "${t}"?`))try{const r=await(await secureFetch(`/api/v1/health-checks/${encodeURIComponent(t)}/configure`,{method:"DELETE"})).json();if(!r.success)throw new Error(r.error);i(),p()}catch(n){showNotification("Error: "+n.message,"error")}}),h?.addEventListener("click",()=>{b?.classList.add("show"),p()}),wireModal(b,j),v?.addEventListener("click",p),document.querySelector('[data-panel="health-incidents"]')?.addEventListener("click",e),document.querySelector('[data-panel="health-config"]')?.addEventListener("click",i)})(),(function(){injectModal("updates-modal",`
';for(const _ of F){const U=_.status==="resolved",q=U&&_.duration?_.duration<6e4?Math.round(_.duration/1e3)+"s":Math.round(_.duration/6e4)+"m":"-";m+='
',m+=`
${escapeHtml(_.serviceId)}
`,m+=`
${escapeHtml(_.type)}
`,m+=`
${g(_.severity)}
`,m+=`
${_.status}
`,m+=`
${q}
`,m+=`
${timeAgo(_.createdAt)}
`,m+="
"}m+="
"}M.innerHTML=m||'
\u{1F6A8}No incidents recorded yet.
'}catch(a){M.innerHTML=`
Failed: ${escapeHtml(a.message)}
`}}async function i(){try{const t=await(await fetch("/api/v1/health-checks/status")).json(),n=t.success&&t.status?Object.values(t.status):[];if(n.length===0){$.innerHTML='
\u2699\uFE0FNo health checks configured yet. Click "Add Health Check" below.
`}}function l(a,t,n,r,m,A,F){c=a||null,w.textContent=a?"Edit Health Check":"Add Health Check",document.getElementById("health-form-id").value=a||"",document.getElementById("health-form-id").disabled=!!a,document.getElementById("health-form-name").value=t||"",document.getElementById("health-form-url").value=n||"",document.getElementById("health-form-timeout").value=r||1e4,document.getElementById("health-form-codes").value=m||"200",document.getElementById("health-form-sla").value=A||99.9,document.getElementById("health-form-slow").value=F||5e3,L.style.display="",y.style.display="none"}function s(){L.style.display="none",y.style.display="",c=null}y?.addEventListener("click",()=>l("","","",1e4,"200",99.9,5e3)),z?.addEventListener("click",s),x?.addEventListener("click",async()=>{const a=c||document.getElementById("health-form-id").value.trim();if(!a)return showNotification("Service ID is required","warning");const t=document.getElementById("health-form-url").value.trim();if(!t)return showNotification("URL is required","warning");const n=document.getElementById("health-form-codes").value.split(",").map(m=>parseInt(m.trim())).filter(Boolean),r={name:document.getElementById("health-form-name").value.trim()||a,url:t,timeout:parseInt(document.getElementById("health-form-timeout").value)||1e4,expectedStatusCodes:n.length?n:[200],sla:{target:parseFloat(document.getElementById("health-form-sla").value)||99.9},slowResponseThreshold:parseInt(document.getElementById("health-form-slow").value)||5e3};try{x.textContent="Saving...",x.disabled=!0;const A=await(await secureFetch(`/api/v1/health-checks/${encodeURIComponent(a)}/configure`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)})).json();if(!A.success)throw new Error(A.error||"Save failed");s(),i(),p()}catch(m){showNotification("Error: "+m.message,"error")}finally{x.textContent="Save",x.disabled=!1}}),document.addEventListener("health-edit",async a=>{const t=a.detail;l(t,"","",1e4,"200",99.9,5e3)}),document.addEventListener("health-delete",async a=>{const t=a.detail;if(confirm(`Delete health check for "${t}"?`))try{const r=await(await secureFetch(`/api/v1/health-checks/${encodeURIComponent(t)}/configure`,{method:"DELETE"})).json();if(!r.success)throw new Error(r.error);i(),p()}catch(n){showNotification("Error: "+n.message,"error")}}),h?.addEventListener("click",()=>{b?.classList.add("show"),p()}),wireModal(b,j),v?.addEventListener("click",p),document.querySelector('[data-panel="health-incidents"]')?.addEventListener("click",e),document.querySelector('[data-panel="health-config"]')?.addEventListener("click",i)})(),(function(){injectModal("updates-modal",`
\u2B06\uFE0F Update Management
@@ -1652,17 +1652,17 @@ This will replace current configuration, credentials, and data. Containers will
- `);const b=document.getElementById("updates-modal"),h=document.getElementById("updates-btn"),j=document.getElementById("updates-cancel"),v=document.getElementById("updates-check-btn"),N=document.getElementById("updates-available-container"),M=document.getElementById("updates-history-container"),$=document.getElementById("updates-auto-container"),R=document.getElementById("updates-last-check");async function y(){try{const e=await(await fetch("/api/v1/updates/available")).json();if(!e.success)throw new Error(e.error);const i=e.updates||[];if(i.length===0){N.innerHTML='
';for(const t of i){const n=(()=>{const r=window.APPS||[];for(const m of r)if(m.containerId===t.containerId||m.name===t.containerName||m.id===t.containerName)return m.id;return t.containerName})();l+=`
`,l+=`
${escapeHtml(t.containerName)}
`,l+=`
${escapeHtml(t.imageName)}
`,l+=`
${escapeHtml(t.currentDigest)}
`,l+=`
${escapeHtml(t.latestDigest)}
`,l+='
',l+=``,l+=``,l+="
"}l+="
",N.innerHTML=l,R.textContent=i.length+" update(s) available";const s=document.getElementById("updates-count-badge"),a=document.getElementById("updates-update-all-btn");s&&(s.textContent=i.length+" pending",s.style.display=""),a&&i.length>0&&(a.style.display=""),window._pendingUpdates=i,N.querySelectorAll(".update-now-btn").forEach(t=>{t.addEventListener("click",async()=>{const n=t.dataset.id,r=t.dataset.name;if(confirm(`Update "${r}" to the latest version? The container will restart.`)){t.textContent="Updating...",t.disabled=!0;try{const A=await(await secureFetch(`/api/v1/updates/update/${encodeURIComponent(n)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({autoRollback:!0})})).json();if(A.success)t.textContent="Done!",t.style.background="var(--ok-fg)",setTimeout(()=>y(),2e3);else throw new Error(A.error||"Update failed")}catch(m){t.textContent="Failed",t.style.color="var(--bad-fg)",showNotification("Update error: "+m.message,"error"),setTimeout(()=>{t.textContent="Update",t.disabled=!1,t.style.color="",t.style.background=""},3e3)}}})}),N.querySelectorAll(".rollback-btn").forEach(t=>{t.addEventListener("click",async()=>{const n=t.dataset.id,r=t.dataset.name;if(confirm(`Rollback "${r}" to its previous version?`)){t.textContent="Rolling back...",t.disabled=!0;try{const A=await(await secureFetch(`/api/v1/updates/rollback/${encodeURIComponent(n)}`,{method:"POST"})).json();if(A.success)t.textContent="Rolled back!",setTimeout(()=>y(),2e3);else throw new Error(A.error||"Rollback failed")}catch(m){t.textContent="Failed",showNotification("Rollback error: "+m.message,"error"),setTimeout(()=>{t.textContent="Rollback",t.disabled=!1},3e3)}}})})}catch(p){N.innerHTML=`
Failed: ${escapeHtml(p.message)}
`}}async function L(){const p=window._pendingUpdates||[];if(!p.length)return;const e=document.getElementById("updates-update-all-btn");if(!confirm(`Update all ${p.length} containers? Each will restart.`))return;e.textContent="\u23F3 Updating...",e.disabled=!0;let i=0,l=0;for(const s of p)try{(await(await secureFetch(`/api/v1/updates/update/${encodeURIComponent(s.containerId)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({autoRollback:!0})})).json()).success?i++:l++}catch{l++}e.textContent="\u2705 Done",showNotification(`Update all: ${i} succeeded, ${l} failed.`,i>0&&l===0?"success":"error"),setTimeout(()=>{e.textContent="\u2B06\uFE0F Update All",e.disabled=!1,y()},3e3)}document.getElementById("updates-update-all-btn")?.addEventListener("click",L);async function w(){v.textContent="\u{1F50D} Checking...",v.disabled=!0;try{const e=await(await secureFetch("/api/v1/updates/check",{method:"POST"})).json();if(!e.success)throw new Error(e.error);v.textContent="\u2705 Done!",await y()}catch(p){v.textContent="\u274C Failed",showNotification("Check error: "+p.message,"error")}setTimeout(()=>{v.textContent="\u{1F50D} Check for Updates",v.disabled=!1},3e3)}async function z(){try{M.innerHTML='
Auto-updates run during maintenance window (default 2AM-4AM). Daily = every day, Weekly = Sundays, Monthly = 1st of month.
';t+='
',t+='
Container
Schedule
Window
Rollback
Last Run
Actions
';for(const n of s){const r=n.name||n.Names?.[0]?.replace(/^\//,"")||n.Id?.substring(0,12),m=n.containerId||n.Id,A=a[m]||{},O=A.enabled?A.schedule||"weekly":"",_=A.autoRollback!==!1,U=A.maintenanceWindow||"",q=A.lastAutoUpdate?timeAgo(A.lastAutoUpdate):"Never";t+=`
`,t+=`
${escapeHtml(r)}
`,t+=`
+ `);const b=document.getElementById("updates-modal"),h=document.getElementById("updates-btn"),j=document.getElementById("updates-cancel"),v=document.getElementById("updates-check-btn"),D=document.getElementById("updates-available-container"),M=document.getElementById("updates-history-container"),$=document.getElementById("updates-auto-container"),R=document.getElementById("updates-last-check");async function y(){try{const e=await(await fetch("/api/v1/updates/available")).json();if(!e.success)throw new Error(e.error);const i=e.updates||[];if(i.length===0){D.innerHTML='
';for(const t of i){const n=(()=>{const r=window.APPS||[];for(const m of r)if(m.containerId===t.containerId||m.name===t.containerName||m.id===t.containerName)return m.id;return t.containerName})();l+=`
`,l+=`
${escapeHtml(t.containerName)}
`,l+=`
${escapeHtml(t.imageName)}
`,l+=`
${escapeHtml(t.currentDigest)}
`,l+=`
${escapeHtml(t.latestDigest)}
`,l+='
',l+=``,l+=``,l+="
"}l+="
",D.innerHTML=l,R.textContent=i.length+" update(s) available";const s=document.getElementById("updates-count-badge"),a=document.getElementById("updates-update-all-btn");s&&(s.textContent=i.length+" pending",s.style.display=""),a&&i.length>0&&(a.style.display=""),window._pendingUpdates=i,D.querySelectorAll(".update-now-btn").forEach(t=>{t.addEventListener("click",async()=>{const n=t.dataset.id,r=t.dataset.name;if(confirm(`Update "${r}" to the latest version? The container will restart.`)){t.textContent="Updating...",t.disabled=!0;try{const A=await(await secureFetch(`/api/v1/updates/update/${encodeURIComponent(n)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({autoRollback:!0})})).json();if(A.success)t.textContent="Done!",t.style.background="var(--ok-fg)",setTimeout(()=>y(),2e3);else throw new Error(A.error||"Update failed")}catch(m){t.textContent="Failed",t.style.color="var(--bad-fg)",showNotification("Update error: "+m.message,"error"),setTimeout(()=>{t.textContent="Update",t.disabled=!1,t.style.color="",t.style.background=""},3e3)}}})}),D.querySelectorAll(".rollback-btn").forEach(t=>{t.addEventListener("click",async()=>{const n=t.dataset.id,r=t.dataset.name;if(confirm(`Rollback "${r}" to its previous version?`)){t.textContent="Rolling back...",t.disabled=!0;try{const A=await(await secureFetch(`/api/v1/updates/rollback/${encodeURIComponent(n)}`,{method:"POST"})).json();if(A.success)t.textContent="Rolled back!",setTimeout(()=>y(),2e3);else throw new Error(A.error||"Rollback failed")}catch(m){t.textContent="Failed",showNotification("Rollback error: "+m.message,"error"),setTimeout(()=>{t.textContent="Rollback",t.disabled=!1},3e3)}}})})}catch(p){D.innerHTML=`
Failed: ${escapeHtml(p.message)}
`}}async function L(){const p=window._pendingUpdates||[];if(!p.length)return;const e=document.getElementById("updates-update-all-btn");if(!confirm(`Update all ${p.length} containers? Each will restart.`))return;e.textContent="\u23F3 Updating...",e.disabled=!0;let i=0,l=0;for(const s of p)try{(await(await secureFetch(`/api/v1/updates/update/${encodeURIComponent(s.containerId)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({autoRollback:!0})})).json()).success?i++:l++}catch{l++}e.textContent="\u2705 Done",showNotification(`Update all: ${i} succeeded, ${l} failed.`,i>0&&l===0?"success":"error"),setTimeout(()=>{e.textContent="\u2B06\uFE0F Update All",e.disabled=!1,y()},3e3)}document.getElementById("updates-update-all-btn")?.addEventListener("click",L);async function w(){v.textContent="\u{1F50D} Checking...",v.disabled=!0;try{const e=await(await secureFetch("/api/v1/updates/check",{method:"POST"})).json();if(!e.success)throw new Error(e.error);v.textContent="\u2705 Done!",await y()}catch(p){v.textContent="\u274C Failed",showNotification("Check error: "+p.message,"error")}setTimeout(()=>{v.textContent="\u{1F50D} Check for Updates",v.disabled=!1},3e3)}async function z(){try{M.innerHTML='
Auto-updates run during maintenance window (default 2AM-4AM). Daily = every day, Weekly = Sundays, Monthly = 1st of month.
';t+='
',t+='
Container
Schedule
Window
Rollback
Last Run
Actions
';for(const n of s){const r=n.name||n.Names?.[0]?.replace(/^\//,"")||n.Id?.substring(0,12),m=n.containerId||n.Id,A=a[m]||{},F=A.enabled?A.schedule||"weekly":"",_=A.autoRollback!==!1,U=A.maintenanceWindow||"",q=A.lastAutoUpdate?timeAgo(A.lastAutoUpdate):"Never";t+=`
`}}const C=document.getElementById("dashcaddy-current-version"),k=document.getElementById("dashcaddy-update-badge"),T=document.getElementById("dashcaddy-update-details"),P=document.getElementById("dashcaddy-new-version"),f=document.getElementById("dashcaddy-changelog"),B=document.getElementById("dashcaddy-apply-btn"),D=document.getElementById("dashcaddy-check-btn"),F=document.getElementById("dashcaddy-rollback-btn"),S=document.getElementById("dashcaddy-status-bar"),I=document.getElementById("dashcaddy-history-container");let H=null;function E(p,e){S&&(S.style.display="block",S.style.background=e==="error"?"var(--bad-bg)":e==="success"?"var(--ok-bg)":"var(--bg)",S.style.color=e==="error"?"var(--bad-fg)":e==="success"?"var(--ok-fg)":"var(--fg)",S.textContent=p)}async function u(){try{const e=await(await fetch("/api/v1/system/version")).json();if(e.success){const i=e.commit&&e.commit!=="unknown"?e.commit:null;C.textContent="v"+e.version+(i?" ("+i.substring(0,7)+")":"")}}catch{C.textContent="Unable to fetch version"}}async function o(p){p||(D.textContent="Checking...",D.disabled=!0);try{const i=await(await fetch("/api/v1/system/update-check")).json();if(H=i,i.success&&i.available&&i.remote){k.style.display="",T.style.display="",P.textContent="v"+i.remote.version,f.textContent=i.remote.changelog||"No changelog available.";const l=document.getElementById("updates-btn");if(l&&!l.querySelector(".update-dot")){const a=document.createElement("span");a.className="update-dot",a.style.cssText="position:absolute;top:2px;right:2px;width:8px;height:8px;border-radius:50%;background:var(--accent);",l.style.position="relative",l.appendChild(a)}const s=document.getElementById("updates-dashcaddy-tab");if(s&&!s.querySelector(".update-dot")){const a=document.createElement("span");a.className="update-dot",a.style.cssText="display:inline-block;width:6px;height:6px;border-radius:50%;background:var(--accent);margin-left:4px;vertical-align:middle;",s.appendChild(a)}}else k.style.display="none",T.style.display="none",await u(),p||E("You are running the latest version.","success");p||(D.textContent="Check for Updates",D.disabled=!1)}catch(e){p||(E("Failed to check: "+e.message,"error"),D.textContent="Check for Updates",D.disabled=!1)}}async function c(){if(!confirm("Apply DashCaddy update? The API container will restart."))return!1;B.textContent="Updating...",B.disabled=!0,E("Downloading and applying update...","info");try{const e=await(await secureFetch("/api/v1/system/update-apply",{method:"POST"})).json();if(e.success)return E("Update initiated: v"+(e.fromVersion||"?")+" \u2192 v"+(e.toVersion||"?")+". The container will restart shortly.","success"),B.textContent="Applied!",document.querySelectorAll(".update-dot").forEach(i=>i.remove()),!0;throw new Error(e.error||"Update failed")}catch(p){throw E("Update failed: "+p.message,"error"),B.textContent="Update Now",B.disabled=!1,p}}async function d(){try{const e=await(await fetch("/api/v1/system/update-history")).json(),i=e.success&&e.history?e.history:[];if(i.length===0){I.innerHTML='
\u{1F4E6}No self-update history.
';return}let l='
';l+='
When
Version
From
Status
';for(const s of i){const a=s.status==="success"?"\u2713 success":s.status==="pending"?"\u23F3 pending":s.status==="partial"?"\u26A0 partial":"\u2717 "+s.status,t=s.status==="success"?"var(--ok-fg)":s.status==="pending"?"var(--muted)":"var(--bad-fg)";l+='
`}}const C=document.getElementById("dashcaddy-current-version"),k=document.getElementById("dashcaddy-update-badge"),T=document.getElementById("dashcaddy-update-details"),N=document.getElementById("dashcaddy-new-version"),f=document.getElementById("dashcaddy-changelog"),B=document.getElementById("dashcaddy-apply-btn"),P=document.getElementById("dashcaddy-check-btn"),O=document.getElementById("dashcaddy-rollback-btn"),S=document.getElementById("dashcaddy-status-bar"),I=document.getElementById("dashcaddy-history-container");let H=null;function E(p,e){S&&(S.style.display="block",S.style.background=e==="error"?"var(--bad-bg)":e==="success"?"var(--ok-bg)":"var(--bg)",S.style.color=e==="error"?"var(--bad-fg)":e==="success"?"var(--ok-fg)":"var(--fg)",S.textContent=p)}async function u(){try{const e=await(await fetch("/api/v1/system/version")).json();if(e.success){const i=e.commit&&e.commit!=="unknown"?e.commit:null;C.textContent="v"+e.version+(i?" ("+i.substring(0,7)+")":"")}}catch{C.textContent="Unable to fetch version"}}async function o(p){p||(P.textContent="Checking...",P.disabled=!0);try{const i=await(await fetch("/api/v1/system/update-check")).json();if(H=i,i.success&&i.available&&i.remote){k.style.display="",T.style.display="",N.textContent="v"+i.remote.version,f.textContent=i.remote.changelog||"No changelog available.";const l=document.getElementById("updates-btn");if(l&&!l.querySelector(".update-dot")){const a=document.createElement("span");a.className="update-dot",a.style.cssText="position:absolute;top:2px;right:2px;width:8px;height:8px;border-radius:50%;background:var(--accent);",l.style.position="relative",l.appendChild(a)}const s=document.getElementById("updates-dashcaddy-tab");if(s&&!s.querySelector(".update-dot")){const a=document.createElement("span");a.className="update-dot",a.style.cssText="display:inline-block;width:6px;height:6px;border-radius:50%;background:var(--accent);margin-left:4px;vertical-align:middle;",s.appendChild(a)}}else k.style.display="none",T.style.display="none",await u(),p||E("You are running the latest version.","success");p||(P.textContent="Check for Updates",P.disabled=!1)}catch(e){p||(E("Failed to check: "+e.message,"error"),P.textContent="Check for Updates",P.disabled=!1)}}async function c(){if(!confirm("Apply DashCaddy update? The API container will restart."))return!1;B.textContent="Updating...",B.disabled=!0,E("Downloading and applying update...","info");try{const e=await(await secureFetch("/api/v1/system/update-apply",{method:"POST"})).json();if(e.success)return E("Update initiated: v"+(e.fromVersion||"?")+" \u2192 v"+(e.toVersion||"?")+". The container will restart shortly.","success"),B.textContent="Applied!",document.querySelectorAll(".update-dot").forEach(i=>i.remove()),!0;throw new Error(e.error||"Update failed")}catch(p){throw E("Update failed: "+p.message,"error"),B.textContent="Update Now",B.disabled=!1,p}}async function d(){try{const e=await(await fetch("/api/v1/system/update-history")).json(),i=e.success&&e.history?e.history:[];if(i.length===0){I.innerHTML='
\u{1F4E6}No self-update history.
';return}let l='
';l+='
When
Version
From
Status
';for(const s of i){const a=s.status==="success"?"\u2713 success":s.status==="pending"?"\u23F3 pending":s.status==="partial"?"\u26A0 partial":"\u2717 "+s.status,t=s.status==="success"?"var(--ok-fg)":s.status==="pending"?"var(--muted)":"var(--bad-fg)";l+='
"}}async function g(){try{const e=await(await fetch("/api/v1/system/rollback-versions")).json(),i=e.success&&e.versions?e.versions:[];if(i.length===0){showNotification("No rollback versions available.","info");return}const l=prompt(`Available rollback versions:
`+i.join(`
`)+`
-Enter version to rollback to:`);if(!l)return;if(!i.includes(l)){showNotification("Invalid version: "+l,"error");return}if(!confirm("Rollback DashCaddy to v"+l+"? The container will restart."))return;E("Rolling back to v"+l+"...","info");const a=await(await secureFetch("/api/v1/system/rollback",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({version:l})})).json();if(a.success)E("Rollback to v"+l+" initiated. Container will restart.","success");else throw new Error(a.error||"Rollback failed")}catch(p){E("Rollback failed: "+p.message,"error")}}D?.addEventListener("click",()=>o(!1)),B?.addEventListener("click",()=>c().catch(()=>{})),F?.addEventListener("click",g),v?.addEventListener("click",w),h?.addEventListener("click",()=>{b?.classList.add("show"),y()}),wireModal(b,j),window.openUpdateModal=function(p){b?.classList.add("show"),y().then(()=>{if(!p)return;const e=N.querySelector(`[data-app-id="${p}"]`);e&&(e.scrollIntoView({behavior:"smooth",block:"center"}),e.style.background="rgba(249,115,22,0.15)",setTimeout(()=>{e.style.background=""},3e3))})},document.querySelector('[data-panel="updates-history"]')?.addEventListener("click",z),document.querySelector('[data-panel="updates-auto"]')?.addEventListener("click",x),document.querySelector('[data-panel="updates-dashcaddy"]')?.addEventListener("click",()=>{u(),d(),H||o(!0)}),window.dcApplyUpdate=c,window.dcCheckForUpdate=o,setTimeout(()=>o(!0),5e3)})(),(function(){injectModal("docker-resources-modal",`
+Enter version to rollback to:`);if(!l)return;if(!i.includes(l)){showNotification("Invalid version: "+l,"error");return}if(!confirm("Rollback DashCaddy to v"+l+"? The container will restart."))return;E("Rolling back to v"+l+"...","info");const a=await(await secureFetch("/api/v1/system/rollback",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({version:l})})).json();if(a.success)E("Rollback to v"+l+" initiated. Container will restart.","success");else throw new Error(a.error||"Rollback failed")}catch(p){E("Rollback failed: "+p.message,"error")}}P?.addEventListener("click",()=>o(!1)),B?.addEventListener("click",()=>c().catch(()=>{})),O?.addEventListener("click",g),v?.addEventListener("click",w),h?.addEventListener("click",()=>{b?.classList.add("show"),y()}),wireModal(b,j),window.openUpdateModal=function(p){b?.classList.add("show"),y().then(()=>{if(!p)return;const e=D.querySelector(`[data-app-id="${p}"]`);e&&(e.scrollIntoView({behavior:"smooth",block:"center"}),e.style.background="rgba(249,115,22,0.15)",setTimeout(()=>{e.style.background=""},3e3))})},document.querySelector('[data-panel="updates-history"]')?.addEventListener("click",z),document.querySelector('[data-panel="updates-auto"]')?.addEventListener("click",x),document.querySelector('[data-panel="updates-dashcaddy"]')?.addEventListener("click",()=>{u(),d(),H||o(!0)}),window.dcApplyUpdate=c,window.dcCheckForUpdate=o,setTimeout(()=>o(!0),5e3)})(),(function(){injectModal("docker-resources-modal",`
\u{1F433} Docker Resources
Manage volumes, networks, and view disk usage.
@@ -1711,7 +1711,7 @@ Enter version to rollback to:`);if(!l)return;if(!i.includes(l)){showNotification
",R.innerHTML=w,R.querySelectorAll(".dr-vol-del").forEach(z=>{z.addEventListener("click",async()=>{if(confirm(`Delete volume "${z.dataset.name}"? Data will be lost.`)){z.textContent="...",z.disabled=!0;try{await deleteAPI(`/api/v1/docker/volumes/${encodeURIComponent(z.dataset.name)}?force=true`),N()}catch(x){showNotification("Delete failed: "+x.message,"error"),z.textContent="Delete",z.disabled=!1}}})})}catch(y){R.innerHTML=`
Failed: ${escapeHtml(y.message)}
`}}document.getElementById("dr-vol-create")?.addEventListener("click",async()=>{const R=document.getElementById("dr-vol-name"),y=R.value.trim();if(!y){showNotification("Enter a volume name","warning");return}try{await postJSON("/api/v1/docker/volumes",{name:y}),R.value="",showNotification(`Volume "${y}" created`,"success"),N()}catch(L){showNotification("Create failed: "+L.message,"error")}});async function M(){const R=document.getElementById("dr-net-list");try{const L=(await getJSON("/api/v1/docker/networks")).networks||[];if(L.length===0){R.innerHTML='
\u{1F310}No networks found.
';return}let w='
';w+='
Name
Driver
Scope
Containers
Actions
';for(const z of L){const x=["bridge","host","none"].includes(z.name);w+='
",R.innerHTML=w,R.querySelectorAll(".dr-vol-del").forEach(z=>{z.addEventListener("click",async()=>{if(confirm(`Delete volume "${z.dataset.name}"? Data will be lost.`)){z.textContent="...",z.disabled=!0;try{await deleteAPI(`/api/v1/docker/volumes/${encodeURIComponent(z.dataset.name)}?force=true`),D()}catch(x){showNotification("Delete failed: "+x.message,"error"),z.textContent="Delete",z.disabled=!1}}})})}catch(y){R.innerHTML=`
Failed: ${escapeHtml(y.message)}
`}}document.getElementById("dr-vol-create")?.addEventListener("click",async()=>{const R=document.getElementById("dr-vol-name"),y=R.value.trim();if(!y){showNotification("Enter a volume name","warning");return}try{await postJSON("/api/v1/docker/volumes",{name:y}),R.value="",showNotification(`Volume "${y}" created`,"success"),D()}catch(L){showNotification("Create failed: "+L.message,"error")}});async function M(){const R=document.getElementById("dr-net-list");try{const L=(await getJSON("/api/v1/docker/networks")).networks||[];if(L.length===0){R.innerHTML='
\u{1F310}No networks found.
';return}let w='
';w+='
Name
Driver
Scope
Containers
Actions
';for(const z of L){const x=["bridge","host","none"].includes(z.name);w+='
';for(const w of y.results){const z=w.status==="deployed"||w.status==="created"?"\u2705":w.status==="exists"?"\u26A1":w.status==="skipped"?"\u23ED":"\u274C";L+='
';for(const w of y.results){const z=w.status==="deployed"||w.status==="created"?"\u2705":w.status==="exists"?"\u26A1":w.status==="skipped"?"\u23ED":"\u274C";L+='
`,w.style.display="none";return}if(!D&&F!==C)return;const d=Array.isArray(c.entries)?c.entries:[];if(d.length===0&&!D){const p=c.filters&&(c.filters.action||c.filters.outcome||c.filters.since||c.filters.until)?"No entries match your filters.":"No audit log entries yet. Actions will be logged automatically.";L.innerHTML=`
\u{1F4DC}${escapeHtml(p)}
`,w.style.display="none";return}let g="";D||(g='
',g+='
',g+='
When
',g+='
Actor
',g+='
IP
',g+='
Action
',g+='
Resource
',g+='
Result
',g+="
");for(const p of d){const e=p.outcome==="success",i=f(p);g+='
`,w.style.display="none";return}if(!P&&O!==C)return;const d=Array.isArray(c.entries)?c.entries:[];if(d.length===0&&!P){const p=c.filters&&(c.filters.action||c.filters.outcome||c.filters.since||c.filters.until)?"No entries match your filters.":"No audit log entries yet. Actions will be logged automatically.";L.innerHTML=`
\u{1F4DC}${escapeHtml(p)}
`,w.style.display="none";return}let g="";P||(g='
',g+='
',g+='
When
',g+='
Actor
',g+='
IP
',g+='
Action
',g+='
Resource
',g+='
Result
',g+="
");for(const p of d){const e=p.outcome==="success",i=f(p);g+='