",x.innerHTML=A,N("setup-step-summary")}async function z(x){try{const A=await secureFetch("/api/v1/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(x)});return A.ok?(await A.json(),!0):(errorHandler.logError("[SetupWizard] Save Config",new Error(`Server returned ${A.status}`),{function:"saveConfigToServer"}),!1)}catch(A){return errorHandler.logError("[SetupWizard] Save Config",A,{function:"saveConfigToServer"}),!1}}async function P(){const x={setupComplete:!0,configurationType:h,timestamp:new Date().toISOString(),timezone:document.getElementById("setup-timezone")?.value||Intl.DateTimeFormat().resolvedOptions().timeZone||"UTC"};if(h==="homelab"){x.tld=document.getElementById("setup-tld")?.value?.trim()||".home",x.caName=document.getElementById("setup-ca-name")?.value?.trim()||"";const b=document.getElementById("setup-dns-provider")?.value||"technitium";x.dns={provider:b,ip:document.getElementById("setup-dns-ip")?.value?.trim()||"",port:document.getElementById("setup-dns-port")?.value?.trim()||DC.DEFAULTS.DNS_PORT,token:document.getElementById("setup-dns-token")?.value?.trim()||""},x.defaults={dnsType:"private",sslType:"internal",targetIP:"localhost"}}else h==="simple"?(x.defaultIP=document.getElementById("setup-simple-ip")?.value?.trim()||"localhost",x.defaults={dnsType:"none",sslType:"none",targetIP:x.defaultIP}):h==="public"&&(x.domain=document.getElementById("setup-public-domain")?.value?.trim()||"",x.email=document.getElementById("setup-public-email")?.value?.trim()||"",x.routingMode=document.querySelector('input[name="routing-mode"]:checked')?.value||"subdirectory",x.defaults={dnsType:x.routingMode==="subdirectory"?"none":"public",sslType:"letsencrypt",targetIP:"localhost"});const A=await z(x);safeSet("dashcaddy-config",JSON.stringify(x)),safeSet("dashcaddy-setup","completed"),document.getElementById("setup-wizard").style.display="none";const y=h==="homelab"?"Professional Home Lab":h==="simple"?"Simple Setup":"Public Server",m=A?"server (shared across all devices)":"locally (this browser only)";showNotification(`Setup Complete! Configured for: ${y}. Settings saved to: ${m}`,"success",5e3),setTimeout(()=>location.reload(),500)}const g=document.getElementById("setup-step-1-next");g&&(g.onclick=function(x){x.preventDefault();const A=document.querySelector('input[name="config-type"]:checked');A&&(h=A.value),N(h==="homelab"?"setup-step-homelab":h==="simple"?"setup-step-simple":h==="public"?"setup-step-public":"setup-step-homelab")});const L=document.getElementById("setup-skip");L&&(L.onclick=async function(x){x.preventDefault(),confirm("Skip setup? You can run it later from Settings.")&&(await z({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(x){const A=x.target.value||".home",y=document.getElementById("tld-preview"),m=document.getElementById("tld-preview-2");y&&(y.textContent=A),m&&(m.textContent=A)});const T=document.getElementById("setup-homelab-back");T&&(T.onclick=function(x){x.preventDefault(),N("setup-step-1")});const k=document.getElementById("setup-homelab-next");k&&(k.onclick=function(x){x.preventDefault();const A=document.getElementById("setup-tld")?.value?.trim()||"",y=document.getElementById("setup-ca-name")?.value?.trim()||"",m=document.getElementById("setup-dns-ip")?.value?.trim()||"";if(!A||!A.startsWith(".")){showNotification("Please enter a valid TLD starting with a dot (e.g., .home)","warning");return}if(!y){showNotification("Please enter a Certificate Authority name","warning");return}if(!m){showNotification("Please enter your DNS server IP address","warning");return}R()});const B=document.getElementById("setup-simple-back");B&&(B.onclick=function(x){x.preventDefault(),N("setup-step-1")});const I=document.getElementById("setup-simple-next");I&&(I.onclick=function(x){x.preventDefault(),R()}),document.querySelectorAll('input[name="routing-mode"]').forEach(function(x){x.onchange=function(){var A=document.getElementById("dns-requirement-note");A&&(A.textContent=this.value==="subdirectory"?"Only one DNS record needed (for the main domain)":"You'll need to configure DNS manually for each subdomain")}});const C=document.getElementById("setup-public-back");C&&(C.onclick=function(x){x.preventDefault(),N("setup-step-1")});const j=document.getElementById("setup-public-next");j&&(j.onclick=function(x){x.preventDefault();const A=document.getElementById("setup-public-domain")?.value?.trim()||"",y=document.getElementById("setup-public-email")?.value?.trim()||"";if(!A){showNotification("Please enter your domain name","warning");return}if(!y||!y.includes("@")){showNotification("Please enter a valid email address","warning");return}R()});const M=document.getElementById("setup-summary-back");M&&(M.onclick=function(x){x.preventDefault(),h==="homelab"?N("setup-step-homelab"):h==="simple"?N("setup-step-simple"):h==="public"&&N("setup-step-public")});const D=document.getElementById("setup-finish");D&&(D.onclick=function(x){x.preventDefault(),P()}),window.getGlobalConfig=async function(){try{const A=await fetch("/api/v1/config");if(A.ok){const y=await A.json();if(y&&y.setupComplete)return y}}catch{console.warn("Could not fetch config from server")}const x=safeGet("dashcaddy-config");return x?JSON.parse(x):{setupComplete:!1,configurationType:"homelab",tld:".home",caName:"",defaults:{dnsType:"private",sslType:"internal",targetIP:"localhost"}}},window.resetSetupWizard=async function(){if(confirm("Reset DashCaddy configuration? This will show the setup wizard again.")){try{await secureFetch("/api/v1/config",{method:"DELETE"})}catch{console.warn("Could not delete server config")}safeRemove("dashcaddy-setup"),safeRemove("dashcaddy-config"),location.reload()}}})(),(function(){const h=new ErrorHandler;injectModal("app-selector-modal",`
Choose an App
`),injectModal("app-deploy-modal",`
Deploy Application
Your app will be available at: uptime.home
\u2713 Detected from existing media servers:
Select folders from existing servers, browse, or type paths manually. Separate multiple with commas.
Token expires in 4 minutes! Get it right before clicking Deploy. Leave empty to configure Plex manually later.
Checking Tailscale status...
\u2699\uFE0F Advanced Options
Use 'localhost' for same-host containers, or specific IP for remote services
Customize where container data is stored on the host. Media volumes are configured above.
Optional CPU and memory constraints. Leave at 0 for unlimited.
`);const S="custom-apps";let O=null,E=null;const N=document.getElementById("app-selector-modal"),R=document.getElementById("app-selector-grid");async function z(){try{const d=await(await fetch("/api/v1/apps/templates")).json();if(d.success)return O=d.templates,E=d.categories,!0}catch(s){h.logError("[AppSelector] Fetch Templates",s,{function:"fetchApiTemplates"})}return!1}async function P(s){try{return await(await fetch(`/api/v1/apps/ports/${s}/check`)).json()}catch(d){return h.logError("[AppSelector] Check Port",d,{function:"checkPortAvailability"}),{available:!0}}}async function g(s){try{const r=await(await fetch(`/api/v1/apps/ports/${s}/suggest`)).json();if(r.success)return r.suggestedPort}catch(d){h.logError("[AppSelector] Get Suggested Port",d,{function:"getSuggestedPort"})}return s}async function L(){if(R.innerHTML='
Loading app templates...
',!O&&!await z()){R.innerHTML='
Failed to load app templates. Please try again.
';return}R.innerHTML="";const s={};for(const[r,f]of Object.entries(O)){const v=f.category||"Other";s[v]||(s[v]=[]),s[v].push({id:r,...f})}const d=E?Object.keys(E):Object.keys(s).sort();for(const r of d){const f=s[r];if(!f||f.length===0)continue;f.sort((e,n)=>(n.popularity||0)-(e.popularity||0));const v=document.createElement("div");v.className="app-category-header";const t=E?.[r]||{};v.innerHTML=`${escapeHtml(t.icon||"")} ${escapeHtml(r)}`,t.color&&(v.style.borderBottomColor=t.color),R.appendChild(v),f.forEach(e=>{const n=document.createElement("div");n.className="app-option";const a=e.isDashboardWidget,l=a&&safeGet("widget-"+e.id+"-enabled")!=="false",o=a?`
${l?"ON":"OFF"}
`:"",i=!a&&e.difficulty?`
${escapeHtml(e.difficulty)}
`:"";n.innerHTML=`
${escapeHtml(e.icon||"\u{1F4E6}")}
${escapeHtml(e.name)}
${escapeHtml(e.description||"")}
${o}${i}
`,a?n.onclick=()=>w(e,n):n.onclick=()=>T(e),R.appendChild(n)})}window.renderRecipeCards&&await window.renderRecipeCards(R)}function w(s,d){const r="widget-"+s.id+"-enabled",v=!(safeGet(r)!=="false");safeSet(r,String(v));const t=s.widgetSelector;if(t){const n=document.querySelector(t);n&&(n.style.display=v?"":"none")}const e=d.querySelector('div[style*="border-radius: 4px"]');e&&(e.textContent=v?"ON":"OFF",e.style.background=v?"#2ecc7130":"#e74c3c30",e.style.color=v?"#2ecc71":"#e74c3c"),showNotification(`${s.name} widget ${v?"enabled":"disabled"}`,"success",2e3)}async function T(s){const d=document.getElementById("app-deploy-modal"),r=document.getElementById("app-deploy-title"),f=document.getElementById("deploy-subdomain"),v=document.getElementById("deploy-url-preview"),t=document.getElementById("deploy-ip"),e=document.getElementById("deploy-port"),n=document.getElementById("deploy-tailscale-only"),a=document.getElementById("tailscale-status");try{const W=await(await secureFetch("/api/v1/apps/check-existing",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({appId:s.id})})).json();if(W.success&&W.exists){const V=W.container;confirm(`Found existing ${s.name} container:
Container: ${V.name}
Status: ${V.status}
Port: ${V.primaryPort||"N/A"}
Would you like to use this existing container?
Click OK to configure DNS/Caddy for the existing container.
Click Cancel to deploy a new container.`)&&(s._useExisting=!0,s._existingContainer=V)}}catch{}r.textContent=`Deploy ${s.name}`;const l=s.subdomain||s.id.replace(/-/g,"");f.value=l;const o=document.getElementById("subpath-compat-warning");if(o)if(SITE.routingMode==="subdirectory"){const _=s.subpathSupport||"strip";_==="none"?(o.style.display="block",o.innerHTML='⚠ '+s.name+" does not support subdirectory mode. It may not work correctly at a subpath."):_==="strip"?(o.style.display="block",o.innerHTML='ⓘ '+s.name+" has unverified subdirectory support. It may require additional configuration."):o.style.display="none"}else o.style.display="none";const i=SITE.defaults.dnsType||(SITE.configurationType==="public"?"public":"private"),c=SITE.defaults.sslType||(SITE.configurationType==="public"?"letsencrypt":"internal"),$=document.querySelector(`input[name="dns-type"][value="${i}"]`),H=document.querySelector(`input[name="ssl-type"][value="${c}"]`);$?$.checked=!0:document.querySelector('input[name="dns-type"][value="private"]').checked=!0,H?H.checked=!0:document.querySelector('input[name="ssl-type"][value="internal"]').checked=!0,t.value=SITE.defaults.targetIP||"localhost",n.checked=!1;const U=document.querySelector("#app-deploy-modal .flex-col-gap")?.closest("div"),q=document.querySelector("#app-deploy-modal details"),F=q?.querySelector("div");if(q&&F&&(SITE.configurationType==="public"||SITE.configurationType==="homelab")){const _=document.querySelectorAll('#app-deploy-modal input[name="dns-type"]')[0]?.closest("div.flex-col-gap")?.parentElement,W=document.querySelectorAll('#app-deploy-modal input[name="ssl-type"]')[0]?.closest("div.flex-col-gap")?.parentElement;_&&!_.dataset.moved&&(F.appendChild(_),_.dataset.moved="1"),W&&!W.dataset.moved&&(F.appendChild(W),W.dataset.moved="1")}const G=document.getElementById("media-path-section"),J=document.getElementById("deploy-media-path"),X=document.getElementById("media-path-description");if(s.mediaMount){G.style.display="block",J.value="",J.placeholder="/media/Movies, /media/TVShows or click Browse";const _=document.getElementById("detected-mounts-container"),W=document.getElementById("detected-mounts-list");try{const K=await(await fetch("/api/v1/media/detected-mounts")).json();if(K.success&&K.mounts.length>0){_.style.display="block",W.innerHTML="";const te=[...new Set(K.mounts.map(ee=>ee.hostPath))];J.value=te.join(", "),K.mounts.forEach(ee=>{const Z=document.createElement("button");Z.type="button";const de=te.includes(ee.hostPath);Z.style.cssText=`padding: 8px 14px; font-size: 0.85rem; background: color-mix(in srgb, var(--success) ${de?"40%":"15%"}, var(--card-bg)); border: 1px solid var(--success); border-radius: 6px; cursor: pointer; color: var(--fg);`,Z.innerHTML=`${escapeHtml(ee.folderName)} from ${escapeHtml(ee.sourceImage)}`,Z.title=`${ee.hostPath} (from ${ee.sourceContainer})`,Z.onclick=()=>{const le=J.value.split(",").map(ce=>ce.trim()).filter(ce=>ce),pe=le.indexOf(ee.hostPath);pe>=0?(le.splice(pe,1),Z.style.background="color-mix(in srgb, var(--success) 15%, var(--card-bg))"):(le.push(ee.hostPath),Z.style.background="color-mix(in srgb, var(--success) 40%, var(--card-bg))"),J.value=le.join(", ")},W.appendChild(Z)})}else _.style.display="none"}catch{_.style.display="none"}document.getElementById("browse-media-btn").onclick=()=>{openFolderBrowser(J)}}else G.style.display="none",J.value="",document.getElementById("detected-mounts-container").style.display="none";const Q=document.getElementById("plex-claim-section");Q&&(s.id==="plex"||s.claimToken?(Q.style.display="block",document.getElementById("deploy-plex-claim").value=""):Q.style.display="none");const ne=document.getElementById("volume-mounts-section"),oe=document.getElementById("volume-mounts-list");if(oe.innerHTML="",s.docker?.volumes?.length){const _=s.mediaMount?.containerPath,W=s.docker.volumes.filter(V=>!V.includes("{{MEDIA_PATH}}")&&!(_&&V.endsWith(":"+_)));W.length>0?(ne.style.display="block",W.forEach((V,K)=>{const[te,ee]=V.split(":"),Z=document.createElement("div");Z.style.cssText="display: flex; gap: 6px; align-items: center;",Z.innerHTML=`
\u2192 ${ee}
`,oe.appendChild(Z),Z.querySelector(".vol-browse-btn").onclick=()=>{const de=Z.querySelector(".vol-host-path");openFolderBrowser(de)}})):ne.style.display="none"}else ne.style.display="none";const se=s.defaultPort||8080;e.value="",e.placeholder=`Default: ${se}`;let Y=document.getElementById("deploy-port-status");Y||(Y=document.createElement("div"),Y.id="deploy-port-status",Y.style.cssText="font-size: 0.8rem; margin-top: 4px;",e.parentNode.appendChild(Y));async function ie(){const _=e.value||se;Y.innerHTML='Checking port...';const W=await P(_);if(W.available)Y.innerHTML=`Port ${escapeHtml(String(_))} is available`;else{const V=await g(se);Y.innerHTML=`
Port ${escapeHtml(_)} in use by ${escapeHtml(W.conflict?.usedBy||"unknown")}
`;const K=document.createElement("button");K.type="button",K.textContent=`Use ${V}`,K.style.cssText="margin-left: 8px; padding: 2px 8px; font-size: 0.75rem; cursor: pointer;",K.onclick=()=>{document.getElementById("deploy-port").value=V,Y.innerHTML=`Using suggested port ${escapeHtml(String(V))}`},Y.appendChild(K)}}let re;e.oninput=function(){clearTimeout(re),re=setTimeout(ie,500)},ie();try{const W=await(await fetch("/api/v1/tailscale/status")).json();W.success&&W.installed&&W.connected?a.innerHTML=`
Connected${W.self?.hostname} (${W.self?.ip})| ${W.deviceCount} devices
`:W.installed?a.innerHTML='Not connected':(a.innerHTML='Not available',n.disabled=!0)}catch{a.innerHTML='Could not check status'}function ae(){const _=f.value||"subdomain",W=document.querySelector('input[name="dns-type"]:checked').value,V=document.querySelector('input[name="ssl-type"]:checked').value;let K="";if(SITE.routingMode==="subdirectory"&&SITE.domain)K=`https://${SITE.domain}/${_}`;else if(W==="private")K=`${V==="none"?"http":"https"}://${buildDomain(_)}`;else if(W==="public"){const te=V==="none"?"http":"https",ee=SITE.domain||_;K=SITE.domain?`${te}://${_}.${SITE.domain}`:`${te}://${_}`}else{const te=e.value||s.defaultPort||DC.DEFAULTS.SERVICE_PORT;K=`http://${t.value}:${te}`}v.textContent=K}f.oninput=ae,t.oninput=ae,e.oninput=ae,document.querySelectorAll('input[name="dns-type"]').forEach(_=>{_.onchange=ae}),document.querySelectorAll('input[name="ssl-type"]').forEach(_=>{_.onchange=ae}),ae(),N.classList.remove("show"),d.classList.add("show"),d.dataset.appTemplate=JSON.stringify(s)}async function k(s){const d=s.appTemplate,r=safeGetJSON(S,[]),f=d._useExisting&&d._existingContainer,v=r.find(t=>t.id===s.subdomain);if(!(v&&!f&&!confirm(`An app with subdomain "${s.subdomain}" already exists. Redeploy?`))){if(v){const t=r.indexOf(v);r.splice(t,1),safeSet(S,JSON.stringify(r))}if(f)s.port=d._existingContainer.primaryPort;else{const t=s.port||d.defaultPort||8080;showNotification(`Checking port ${t} availability...`,"info",0);const e=await P(t);if(!e.available){const n=await g(d.defaultPort||8080);if(confirm(`Port ${t} is already in use by ${e.conflict?.usedBy||"another container"}.
Would you like to use port ${n} instead?`))s.port=n;else{showNotification("Deployment cancelled - port conflict","error",5e3);return}}}showNotification(f?`Configuring ${d.name} with existing container...`:`Deploying ${d.name}...`,"info",0);try{const t={appId:d.id,config:{subdomain:s.subdomain,ip:s.ip,createDns:s.dnsType==="private",port:s.port||d.defaultPort||null,sslType:s.sslType,dnsType:s.dnsType,tailscaleOnly:s.tailscaleOnly||!1,mediaPath:s.mediaPath||null,plexClaimToken:s.plexClaimToken||null,customVolumes:s.customVolumes||null}};f&&(t.config.useExisting=!0,t.config.existingContainerId=d._existingContainer.id,t.config.existingPort=d._existingContainer.primaryPort,!s.port&&d._existingContainer.primaryPort&&(t.config.port=d._existingContainer.primaryPort));const n=await(await secureFetch("/api/v1/apps/deploy",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})).json();if(n.success){const a={id:s.subdomain,name:d.name,logo:`/assets/${d.id}.png`,containerId:n.containerId,url:n.url,ip:s.ip,appTemplate:d.id,tailscaleOnly:s.tailscaleOnly||!1};r.push(a),safeSet(S,JSON.stringify(r)),window.APPS&&!window.APPS.some(o=>o.id===d.id)&&(window.APPS.push(a),typeof window.buildGrid=="function"&&window.buildGrid(),typeof window.refreshAll=="function"&&setTimeout(()=>window.refreshAll(),500));let l=n.usedExisting?`${d.name} configured with existing container!
URL: ${n.url}`:`${d.name} deployed successfully!
URL: ${n.url}`;n.warning&&(l+=`
\u26A0 Warning: ${n.warning}`),showNotification(l,"success",8e3),delete d._useExisting,delete d._existingContainer,n.url&&n.url.startsWith("https://")&&B(n.url,d.name),n.setupInstructions&&n.setupInstructions.length>0&&setTimeout(()=>{const o=n.setupInstructions.join(`
`);showNotification(`Setup Instructions for ${d.name}: ${o}`,"info",1e4)},1e3)}else throw new Error(n.error||"Deployment failed")}catch(t){h.logError("[AppSelector] Deployment",t,{function:"deploy"}),showNotification(`Failed to deploy ${d.name}: ${t.message}`,"error",8e3)}}}async function B(s,d){showNotification(`\u23F3 Generating SSL certificate for ${d}...`,"warning",6e4);let r=0;const f=12,v=async()=>{r++;try{const t=await fetch(s,{method:"HEAD",mode:"no-cors"});return showNotification(`\u2705 ${d} is ready! SSL certificate generated.`,"success",5e3),!0}catch{return r{window.APPS.some(r=>r.id===d.id)||window.APPS.push(d)})}document.getElementById("add-service-btn")?.addEventListener("click",()=>{L(),N.classList.add("show")}),wireModal(N,document.getElementById("app-selector-cancel"));const C=document.getElementById("app-deploy-modal");document.getElementById("app-deploy-cancel")?.addEventListener("click",()=>{C.classList.remove("show")}),document.getElementById("app-deploy-confirm")?.addEventListener("click",()=>{const s=JSON.parse(C.dataset.appTemplate),d=document.getElementById("deploy-media-path").value.trim(),r=[];document.querySelectorAll("#volume-mounts-list .vol-host-path").forEach(v=>{r.push({hostPath:v.value.trim(),containerPath:v.dataset.containerPath})});const f={appTemplate:s,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:d||null,plexClaimToken:document.getElementById("deploy-plex-claim")?.value.trim()||null,customVolumes:r.length>0?r:null,resources:{cpus:parseFloat(document.getElementById("deploy-cpu-limit").value)||0,memory:parseFloat(document.getElementById("deploy-memory-limit").value)||0}};if(!f.subdomain){showNotification("Please enter a subdomain or domain name","warning");return}if(s.mediaMount?.required&&!d){showNotification("Please enter a media library path for this application","warning");return}C.classList.remove("show"),k(f)}),wireModal(C);const j=document.getElementById("folder-browser-modal"),M=document.getElementById("folder-browser-path"),D=document.getElementById("folder-browser-list"),x=document.getElementById("folder-browser-selected"),A=document.getElementById("folder-browser-selected-list");let y="",m=[],b=null;window.openFolderBrowser=function(s){b=s,m=s.value.split(",").map(d=>d.trim()).filter(d=>d),y="",u(),p(""),j.classList.add("show")};async function p(s){M.textContent=s||"Select a drive...",D.innerHTML='
');const h=document.getElementById("error-log-modal"),S=document.getElementById("error-log-content"),O=document.getElementById("view-error-logs"),E=document.getElementById("error-log-refresh"),N=document.getElementById("error-log-clear"),R=document.getElementById("error-log-close");async function z(){S.innerHTML='
Create and manage Docker container checkpoints for instant state recovery.
Image:
Status:
Created:
Container ID:
\u{1F4BE}Select a container to view its snapshots
`);const h=document.getElementById("snapshot-modal"),S=document.getElementById("snapshot-btn"),O=document.getElementById("snapshot-close"),E=document.getElementById("snapshot-container-select"),N=document.getElementById("snapshot-details"),R=document.getElementById("snapshot-create-btn"),z=document.getElementById("snapshot-create-status");let P=null;async function g(){try{const I=await(await fetch("/api/v1/containers")).json();if(!I.success||!I.containers)return;E.innerHTML='';for(const C of I.containers){const j=document.createElement("option");j.value=C.id,j.textContent=`${C.name||C.id} (${C.image||"unknown"})`,j.dataset.name=C.name,j.dataset.image=C.image,j.dataset.status=C.status,j.dataset.created=C.created,E.appendChild(j)}}catch(B){console.error("Failed to load containers:",B)}}function L(B){if(!B||!B.value){N.style.display="none",P=null;return}P=B.value,document.getElementById("snapshot-image").textContent=B.dataset.image||"-",document.getElementById("snapshot-status").textContent=B.dataset.status||"-",document.getElementById("snapshot-created").textContent=B.dataset.created?new Date(B.dataset.created*1e3).toLocaleString():"-",document.getElementById("snapshot-id").textContent=B.value.substring(0,12),N.style.display=""}async function w(){if(!P){z.textContent="Please select a container first",z.style.color="var(--bad-fg)";return}const B=document.getElementById("snapshot-name").value.trim();if(!B){z.textContent="Please enter a snapshot name",z.style.color="var(--bad-fg)";return}const I=document.getElementById("snapshot-leave-running").checked;R.disabled=!0,R.textContent="Creating...",z.textContent="";try{const j=await(await fetch(`/api/v1/containers/${encodeURIComponent(P)}/checkpoint`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:B,leaveRunning:I})})).json();j.success?(z.textContent=`\u2713 Snapshot "${B}" created successfully`,z.style.color="var(--ok-fg)",document.getElementById("snapshot-name").value=""):(z.textContent=`\u2717 Failed: ${j.error||"Unknown error"}`,z.style.color="var(--bad-fg)")}catch(C){z.textContent=`\u2717 Error: ${C.message}`,z.style.color="var(--bad-fg)"}finally{R.disabled=!1,R.textContent="\u{1F4BE} Create Snapshot"}}function T(){h.classList.add("show"),g()}function k(){h.classList.remove("show"),N.style.display="none",P=null,E.selectedIndex=0}S?.addEventListener("click",T),O?.addEventListener("click",k),wireModal(h,O),E?.addEventListener("change",B=>{const I=E.options[E.selectedIndex];L(I)}),R?.addEventListener("click",w),h?.querySelectorAll(".panel-tab").forEach(B=>{B.addEventListener("click",()=>{h.querySelectorAll(".panel-tab").forEach(I=>I.classList.remove("active")),h.querySelectorAll(".panel-section").forEach(I=>I.classList.remove("active")),B.classList.add("active"),h.querySelector(`#${B.dataset.panel}`).classList.add("active")})})})(),(function(){injectModal("arr-setup-modal",`
\u{1F3AC} Smart Arr Connect
Auto-discover and connect your entire media stack.
`,g.style.display="block"}}function A(p){let u="";const s=p.services,d=["radarr","sonarr","prowlarr"];for(const v of d){const t=s[v];if(!t||t.status==="not_found"&&!t.url)continue;const e=C[v],n=j[v],a=t.status==="connected";u+=`
`}L.innerHTML=u}window.smartTestConnection=async function(p){const u=document.getElementById(`smart-${p}-url`),s=document.getElementById(`smart-${p}-key`),d=document.getElementById(`smart-${p}-status`),r=u?.value.trim(),f=s?.value.trim();if(!r||!f){d.innerHTML='Enter URL and API key';return}d.innerHTML='';try{const t=await(await secureFetch("/api/v1/arr/test-connection",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({service:p,url:r,apiKey:f})})).json();t.success?d.innerHTML=`✓ ${escapeHtml(t.appName||"Connected")} v${escapeHtml(t.version||"")}`:d.innerHTML=`✗ ${escapeHtml(t.error)}`}catch(v){d.innerHTML=`✗ ${escapeHtml(v.message)}`}};async function y(){M("progress"),w.innerHTML='
Connecting services...
';const p={};for(const s of["radarr","sonarr","prowlarr"]){const d=document.getElementById(`smart-${s}-url`)?.value.trim(),r=document.getElementById(`smart-${s}-key`)?.value.trim();r&&d?p[s]={apiKey:r,url:d}:r&&(p[s]={apiKey:r})}const u={services:Object.keys(p).length>0?p:void 0,configurePlex:document.getElementById("smart-opt-plex")?.checked,configureProwlarr:document.getElementById("smart-opt-prowlarr")?.checked,configureSeerr:document.getElementById("smart-opt-seerr")?.checked,saveCredentials:document.getElementById("smart-opt-save")?.checked};try{const d=await(await secureFetch("/api/v1/arr/smart-connect",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(u)})).json();let r="";for(const f of d.steps||[]){const v=f.status==="success"?'✓':'✗',t=f.status==="success"?"var(--muted)":"var(--bad-fg)";r+=`
"}}}async function m(e,n){try{var a=await secureFetch("/api/v1/backups/schedule",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({appId:e,...n})}),l=await a.json();l.success?showNotification("Schedule updated for "+e,"success"):(showNotification("Update failed: "+(l.error||"Unknown"),"error"),y())}catch(o){showNotification("Error: "+o.message,"error")}}async function b(e){try{var n=await secureFetch("/api/v1/backups/backup/"+encodeURIComponent(e),{method:"POST",headers:{"Content-Type":"application/json"}}),a=await n.json();a.success?showNotification("Backup started for "+e+"!","success"):showNotification("Backup failed: "+(a.error||"Unknown"),"error")}catch(l){showNotification("Error: "+l.message,"error")}}async function p(e){if(confirm("Remove backup schedule for "+e+"?"))try{var n=await secureFetch("/api/v1/backups/schedule/"+encodeURIComponent(e),{method:"DELETE"}),a=await n.json();a.success?(showNotification("Schedule removed for "+e,"success"),y()):showNotification("Delete failed: "+(a.error||"Unknown"),"error")}catch(l){showNotification("Error: "+l.message,"error")}}async function u(){var e=document.getElementById("new-schedule-appid")?.value?.trim(),n=document.getElementById("new-schedule-interval")?.value||"daily",a=parseInt(document.getElementById("new-schedule-retention")?.value)||7;if(!e){showNotification("Please enter an App ID","warning");return}try{var l=await secureFetch("/api/v1/backups/schedule",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({appId:e,schedule:n,retention:{keep:a},enabled:!0})}),o=await l.json();if(o.success){showNotification("Schedule created for "+e,"success"),y();var i=document.getElementById("new-schedule-appid");i&&(i.value="")}else showNotification("Failed: "+(o.error||"Unknown"),"error")}catch(c){showNotification("Error: "+c.message,"error")}}async function s(){if(D){D.innerHTML='
Loading...
';try{var e=await fetch("/api/v1/backups/files"),n=await e.json();if(!n.success)throw new Error(n.error||"Failed to load");var a=n.files||[];if(a.length===0){D.innerHTML='
\u{1F4BE}
No backup files on disk
Run a backup to create backup files
';return}for(var l={},o=0;o'+a.length+" backup file(s) across "+Object.keys(l).length+" app(s)";$+='
"}}}window.__restoreServerBackup=async function(e){if(confirm("Restore from this server backup? This will overwrite current configuration."))try{var n=await secureFetch("/api/v1/backups/restore/"+e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({restoreServices:!0,restoreConfig:!0})}),a=await n.json();a.success?(showNotification("Restore completed successfully!","success"),location.reload()):showNotification("Restore failed: "+(a.error||"Unknown error"),"error")}catch(l){showNotification("Restore error: "+l.message,"error")}},document.querySelector('[data-panel="backup-schedules-tab"]')?.addEventListener("click",y),document.querySelector('[data-panel="backup-disk-tab"]')?.addEventListener("click",s),document.querySelector('[data-panel="backup-pointintime-tab"]')?.addEventListener("click",r),document.querySelector('[data-panel="backup-history-tab"]')?.addEventListener("click",d);async function r(){if(x){try{var e=await fetch("/api/v1/license/status"),n=await e.json();if(n.tier!=="premium"){x.innerHTML=`
\u2B50
Premium Feature
Point-in-time restore requires DashCaddy Premium with auto-backup enabled.
Configuration differs \u2014 restoring will replace current settings
':i+='
No changes
',i+="
"}i+='
',document.body.insertAdjacentHTML("beforeend",i),document.getElementById("compare-close-btn")?.addEventListener("click",function(){document.getElementById("compare-overlay")?.remove()}),document.getElementById("compare-overlay")?.addEventListener("click",function(H){H.target===this&&this.remove()})}catch(H){showNotification("Compare error: "+H.message,"error")}}async function t(e,n){if(confirm("Restore "+n+" for "+e+`?
This will replace current configuration, credentials, and data. Containers will be restarted.`))try{var a=await secureFetch("/api/v1/apps/"+encodeURIComponent(e)+"/revert/"+encodeURIComponent(n),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({restartContainers:!0})}),l=await a.json();l.success?(showNotification(e+" restored to "+n,"success"),setTimeout(function(){location.reload()},1500)):showNotification("Restore failed: "+(l.error||"Unknown"),"error")}catch(o){showNotification("Restore error: "+o.message,"error")}}})(),(function(){injectModal("stats-modal",`
\u{1F4CA} Resource Monitor
Real-time and historical CPU, memory, network, and disk usage for containers.
Loading container stats...
\u{1F4C8}
Loading 24-hour aggregated metrics...
\u{1F4CA}
Choose a container and time range to view history.
\u{1F514}
Loading alert configurations...
`);const h=document.getElementById("stats-modal"),S=document.getElementById("container-stats-btn"),O=document.getElementById("stats-cancel"),E=document.getElementById("stats-refresh-btn"),N=document.getElementById("stats-auto-refresh"),R=document.getElementById("stats-container"),z=document.getElementById("stats-aggregated-container"),P=document.getElementById("stats-alerts-container"),g=document.getElementById("stats-last-update");let L=null,w=null;function T(r){if(r===0||!r)return"0 B";const f=1024,v=["B","KB","MB","GB"],t=Math.floor(Math.log(r)/Math.log(f));return parseFloat((r/Math.pow(f,t)).toFixed(1))+" "+v[t]}function k(r){return r<30?"#2ecc71":r<70?"#f39c12":"#e74c3c"}function B(r){return r<50?"#2ecc71":r<80?"#f39c12":"#e74c3c"}async function I(){try{let r=null,f=!1;try{const e=await(await fetch("/api/v1/monitoring/stats")).json();e.success&&e.stats&&(r=e.stats,f=!0,w=e.stats)}catch{}if(!f){const e=await(await fetch("/api/v1/stats/containers")).json();if(e.success&&e.stats){r={};for(const n of e.stats)r[n.name]={name:n.name,current:{cpu:n.cpu,memory:{percent:n.memory.percent,usage:n.memory.used,limit:n.memory.limit,usageMB:Math.round(n.memory.used/1048576),limitMB:Math.round(n.memory.limit/1048576)},network:{rxBytes:n.network.rx,txBytes:n.network.tx,rxMB:(n.network.rx/1048576).toFixed(1),txMB:(n.network.tx/1048576).toFixed(1)},disk:{readMB:0,writeMB:0}},status:n.status};w=r}}if(!r||Object.keys(r).length===0){R.innerHTML='
';try{const e=await(await fetch(`/api/v1/monitoring/history/${encodeURIComponent(r)}?startTime=${v}&endTime=${f}`)).json();if(!e.success)throw new Error(e.error||"Failed to load history");const n=e.samples||[],a=e.tier||"raw";if(n.length===0){A.innerHTML=`
\u{1F4CA}No data for the last ${m}. Tier: ${p(a)}.
\u{1F3E5}No health checks configured. Go to the Configure tab to add services.
';return}const b=Object.values(m.status);let p='
';p+='
',p+='
Service
Status
',p+='
Uptime 24h
Uptime 7d
',p+='
Avg Response
Last Check
';for(const u of b){const s=u.status==="up",d=s?"var(--dot-ok)":"var(--dot-bad)",r=u.uptime?.["24h"]??"-",f=u.uptime?.["7d"]??"-",v=u.avgResponseTime!=null?Math.round(u.avgResponseTime)+"ms":"-",t=u.timestamp?timeAgo(u.timestamp):"-";p+=`
';for(const r of d){const f=r.status==="resolved",v=f&&r.duration?r.duration<6e4?Math.round(r.duration/1e3)+"s":Math.round(r.duration/6e4)+"m":"-";u+='
',u+=`
${escapeHtml(r.serviceId)}
`,u+=`
${escapeHtml(r.type)}
`,u+=`
${C(r.severity)}
`,u+=`
${r.status}
`,u+=`
${v}
`,u+=`
${timeAgo(r.createdAt)}
`,u+="
"}u+="
"}R.innerHTML=u||'
\u{1F6A8}No incidents recorded yet.
'}catch(y){R.innerHTML=`
Failed: ${escapeHtml(y.message)}
`}}async function D(){try{const m=await(await fetch("/api/v1/health-checks/status")).json(),b=m.success&&m.status?Object.values(m.status):[];if(b.length===0){z.innerHTML='
\u2699\uFE0FNo health checks configured yet. Click "Add Health Check" below.
';return}let p='
';p+='
Service
Status
SLA Target
Actions
';for(const u of b){const s=u.status==="up";p+='
',p+=`
${escapeHtml(u.name||u.serviceId)}
`,p+=`
${s?"Up":"Down"}
`,p+=`
${u.sla?.target?u.sla.target+"%":"-"}
`,p+='
',p+=``,p+=``,p+="
"}p+="
",z.innerHTML=p}catch(y){z.innerHTML=`
Failed: ${escapeHtml(y.message)}
`}}function x(y,m,b,p,u,s,d){B=y||null,w.textContent=y?"Edit Health Check":"Add Health Check",document.getElementById("health-form-id").value=y||"",document.getElementById("health-form-id").disabled=!!y,document.getElementById("health-form-name").value=m||"",document.getElementById("health-form-url").value=b||"",document.getElementById("health-form-timeout").value=p||1e4,document.getElementById("health-form-codes").value=u||"200",document.getElementById("health-form-sla").value=s||99.9,document.getElementById("health-form-slow").value=d||5e3,L.style.display="",g.style.display="none"}function A(){L.style.display="none",g.style.display="",B=null}g?.addEventListener("click",()=>x("","","",1e4,"200",99.9,5e3)),T?.addEventListener("click",A),k?.addEventListener("click",async()=>{const y=B||document.getElementById("health-form-id").value.trim();if(!y)return showNotification("Service ID is required","warning");const m=document.getElementById("health-form-url").value.trim();if(!m)return showNotification("URL is required","warning");const b=document.getElementById("health-form-codes").value.split(",").map(u=>parseInt(u.trim())).filter(Boolean),p={name:document.getElementById("health-form-name").value.trim()||y,url:m,timeout:parseInt(document.getElementById("health-form-timeout").value)||1e4,expectedStatusCodes:b.length?b:[200],sla:{target:parseFloat(document.getElementById("health-form-sla").value)||99.9},slowResponseThreshold:parseInt(document.getElementById("health-form-slow").value)||5e3};try{k.textContent="Saving...",k.disabled=!0;const s=await(await secureFetch(`/api/v1/health-checks/${encodeURIComponent(y)}/configure`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(p)})).json();if(!s.success)throw new Error(s.error||"Save failed");A(),D(),j()}catch(u){showNotification("Error: "+u.message,"error")}finally{k.textContent="Save",k.disabled=!1}}),document.addEventListener("health-edit",async y=>{const m=y.detail;x(m,"","",1e4,"200",99.9,5e3)}),document.addEventListener("health-delete",async y=>{const m=y.detail;if(confirm(`Delete health check for "${m}"?`))try{const p=await(await secureFetch(`/api/v1/health-checks/${encodeURIComponent(m)}/configure`,{method:"DELETE"})).json();if(!p.success)throw new Error(p.error);D(),j()}catch(b){showNotification("Error: "+b.message,"error")}}),S?.addEventListener("click",()=>{h?.classList.add("show"),j()}),wireModal(h,O),E?.addEventListener("click",j),document.querySelector('[data-panel="health-incidents"]')?.addEventListener("click",M),document.querySelector('[data-panel="health-config"]')?.addEventListener("click",D)})(),(function(){injectModal("updates-modal",`
\u2B06\uFE0F Update Management
Check for container image updates, apply them, and manage rollbacks.
\u{1F4E6} Click "Check for Updates" to scan containers.
Loading update history...
\u{1F916} Loading auto-update configuration...
DashCaddy
Loading...
Update available
New version:
\u{1F4E6}No self-update history.
`);const h=document.getElementById("updates-modal"),S=document.getElementById("updates-btn"),O=document.getElementById("updates-cancel"),E=document.getElementById("updates-check-btn"),N=document.getElementById("updates-available-container"),R=document.getElementById("updates-history-container"),z=document.getElementById("updates-auto-container"),P=document.getElementById("updates-last-check");async function g(){try{const t=await(await fetch("/api/v1/updates/available")).json();if(!t.success)throw new Error(t.error);const e=t.updates||[];if(e.length===0){N.innerHTML='
';for(const o of e){const i=(()=>{const c=window.APPS||[];for(const $ of c)if($.containerId===o.containerId||$.name===o.containerName||$.id===o.containerName)return $.id;return o.containerName})();n+=`
`,n+=`
${escapeHtml(o.containerName)}
`,n+=`
${escapeHtml(o.imageName)}
`,n+=`
${escapeHtml(o.currentDigest)}
`,n+=`
${escapeHtml(o.latestDigest)}
`,n+='
',n+=``,n+=``,n+="
"}n+="
",N.innerHTML=n,P.textContent=e.length+" update(s) available";const a=document.getElementById("updates-count-badge"),l=document.getElementById("updates-update-all-btn");a&&(a.textContent=e.length+" pending",a.style.display=""),l&&e.length>0&&(l.style.display=""),window._pendingUpdates=e,N.querySelectorAll(".update-now-btn").forEach(o=>{o.addEventListener("click",async()=>{const i=o.dataset.id,c=o.dataset.name;if(confirm(`Update "${c}" to the latest version? The container will restart.`)){o.textContent="Updating...",o.disabled=!0;try{const H=await(await secureFetch(`/api/v1/updates/update/${encodeURIComponent(i)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({autoRollback:!0})})).json();if(H.success)o.textContent="Done!",o.style.background="var(--ok-fg)",setTimeout(()=>g(),2e3);else throw new Error(H.error||"Update failed")}catch($){o.textContent="Failed",o.style.color="var(--bad-fg)",showNotification("Update error: "+$.message,"error"),setTimeout(()=>{o.textContent="Update",o.disabled=!1,o.style.color="",o.style.background=""},3e3)}}})}),N.querySelectorAll(".rollback-btn").forEach(o=>{o.addEventListener("click",async()=>{const i=o.dataset.id,c=o.dataset.name;if(confirm(`Rollback "${c}" to its previous version?`)){o.textContent="Rolling back...",o.disabled=!0;try{const H=await(await secureFetch(`/api/v1/updates/rollback/${encodeURIComponent(i)}`,{method:"POST"})).json();if(H.success)o.textContent="Rolled back!",setTimeout(()=>g(),2e3);else throw new Error(H.error||"Rollback failed")}catch($){o.textContent="Failed",showNotification("Rollback error: "+$.message,"error"),setTimeout(()=>{o.textContent="Rollback",o.disabled=!1},3e3)}}})})}catch(v){N.innerHTML=`
Failed: ${escapeHtml(v.message)}
`}}async function L(){const v=window._pendingUpdates||[];if(!v.length)return;const t=document.getElementById("updates-update-all-btn");if(!confirm(`Update all ${v.length} containers? Each will restart.`))return;t.textContent="\u23F3 Updating...",t.disabled=!0;let e=0,n=0;for(const a of v)try{(await(await secureFetch(`/api/v1/updates/update/${encodeURIComponent(a.containerId)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({autoRollback:!0})})).json()).success?e++:n++}catch{n++}t.textContent="\u2705 Done",showNotification(`Update all: ${e} succeeded, ${n} failed.`,e>0&&n===0?"success":"error"),setTimeout(()=>{t.textContent="\u2B06\uFE0F Update All",t.disabled=!1,g()},3e3)}document.getElementById("updates-update-all-btn")?.addEventListener("click",L);async function w(){E.textContent="\u{1F50D} Checking...",E.disabled=!0;try{const t=await(await secureFetch("/api/v1/updates/check",{method:"POST"})).json();if(!t.success)throw new Error(t.error);E.textContent="\u2705 Done!",await g()}catch(v){E.textContent="\u274C Failed",showNotification("Check error: "+v.message,"error")}setTimeout(()=>{E.textContent="\u{1F50D} Check for Updates",E.disabled=!1},3e3)}async function T(){try{R.innerHTML='
Auto-updates run during maintenance window (default 2AM-4AM). Daily = every day, Weekly = Sundays, Monthly = 1st of month.
';o+='
',o+='
Container
Schedule
Window
Rollback
Last Run
Actions
';for(const i of a){const c=i.name||i.Names?.[0]?.replace(/^\//,"")||i.Id?.substring(0,12),$=i.containerId||i.Id,H=l[$]||{},U=H.enabled?H.schedule||"weekly":"",q=H.autoRollback!==!1,F=H.maintenanceWindow||"",G=H.lastAutoUpdate?timeAgo(H.lastAutoUpdate):"Never";o+=`
`}}const B=document.getElementById("dashcaddy-current-version"),I=document.getElementById("dashcaddy-update-badge"),C=document.getElementById("dashcaddy-update-details"),j=document.getElementById("dashcaddy-new-version"),M=document.getElementById("dashcaddy-changelog"),D=document.getElementById("dashcaddy-apply-btn"),x=document.getElementById("dashcaddy-check-btn"),A=document.getElementById("dashcaddy-rollback-btn"),y=document.getElementById("dashcaddy-status-bar"),m=document.getElementById("dashcaddy-history-container");let b=null;function p(v,t){y&&(y.style.display="block",y.style.background=t==="error"?"var(--bad-bg)":t==="success"?"var(--ok-bg)":"var(--bg)",y.style.color=t==="error"?"var(--bad-fg)":t==="success"?"var(--ok-fg)":"var(--fg)",y.textContent=v)}async function u(){try{const t=await(await fetch("/api/v1/system/version")).json();if(t.success){const e=t.commit&&t.commit!=="unknown"?t.commit:null;B.textContent="v"+t.version+(e?" ("+e.substring(0,7)+")":"")}}catch{B.textContent="Unable to fetch version"}}async function s(v){v||(x.textContent="Checking...",x.disabled=!0);try{const e=await(await fetch("/api/v1/system/update-check")).json();if(b=e,e.success&&e.available&&e.remote){I.style.display="",C.style.display="",j.textContent="v"+e.remote.version,M.textContent=e.remote.changelog||"No changelog available.";const n=document.getElementById("updates-btn");if(n&&!n.querySelector(".update-dot")){const l=document.createElement("span");l.className="update-dot",l.style.cssText="position:absolute;top:2px;right:2px;width:8px;height:8px;border-radius:50%;background:var(--accent);",n.style.position="relative",n.appendChild(l)}const a=document.getElementById("updates-dashcaddy-tab");if(a&&!a.querySelector(".update-dot")){const l=document.createElement("span");l.className="update-dot",l.style.cssText="display:inline-block;width:6px;height:6px;border-radius:50%;background:var(--accent);margin-left:4px;vertical-align:middle;",a.appendChild(l)}}else I.style.display="none",C.style.display="none",await u(),v||p("You are running the latest version.","success");v||(x.textContent="Check for Updates",x.disabled=!1)}catch(t){v||(p("Failed to check: "+t.message,"error"),x.textContent="Check for Updates",x.disabled=!1)}}async function d(){if(!confirm("Apply DashCaddy update? The API container will restart."))return!1;D.textContent="Updating...",D.disabled=!0,p("Downloading and applying update...","info");try{const t=await(await secureFetch("/api/v1/system/update-apply",{method:"POST"})).json();if(t.success)return p("Update initiated: v"+(t.fromVersion||"?")+" \u2192 v"+(t.toVersion||"?")+". The container will restart shortly.","success"),D.textContent="Applied!",document.querySelectorAll(".update-dot").forEach(e=>e.remove()),!0;throw new Error(t.error||"Update failed")}catch(v){throw p("Update failed: "+v.message,"error"),D.textContent="Update Now",D.disabled=!1,v}}async function r(){try{const t=await(await fetch("/api/v1/system/update-history")).json(),e=t.success&&t.history?t.history:[];if(e.length===0){m.innerHTML='
\u{1F4E6}No self-update history.
';return}let n='
';n+='
When
Version
From
Status
';for(const a of e){const l=a.status==="success"?"\u2713 success":a.status==="pending"?"\u23F3 pending":a.status==="partial"?"\u26A0 partial":"\u2717 "+a.status,o=a.status==="success"?"var(--ok-fg)":a.status==="pending"?"var(--muted)":"var(--bad-fg)";n+='
"}}async function f(){try{const t=await(await fetch("/api/v1/system/rollback-versions")).json(),e=t.success&&t.versions?t.versions:[];if(e.length===0){showNotification("No rollback versions available.","info");return}const n=prompt(`Available rollback versions:
`+e.join(`
`)+`
Enter version to rollback to:`);if(!n)return;if(!e.includes(n)){showNotification("Invalid version: "+n,"error");return}if(!confirm("Rollback DashCaddy to v"+n+"? The container will restart."))return;p("Rolling back to v"+n+"...","info");const l=await(await secureFetch("/api/v1/system/rollback",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({version:n})})).json();if(l.success)p("Rollback to v"+n+" initiated. Container will restart.","success");else throw new Error(l.error||"Rollback failed")}catch(v){p("Rollback failed: "+v.message,"error")}}x?.addEventListener("click",()=>s(!1)),D?.addEventListener("click",()=>d().catch(()=>{})),A?.addEventListener("click",f),E?.addEventListener("click",w),S?.addEventListener("click",()=>{h?.classList.add("show"),g()}),wireModal(h,O),window.openUpdateModal=function(v){h?.classList.add("show"),g().then(()=>{if(!v)return;const t=N.querySelector(`[data-app-id="${v}"]`);t&&(t.scrollIntoView({behavior:"smooth",block:"center"}),t.style.background="rgba(249,115,22,0.15)",setTimeout(()=>{t.style.background=""},3e3))})},document.querySelector('[data-panel="updates-history"]')?.addEventListener("click",T),document.querySelector('[data-panel="updates-auto"]')?.addEventListener("click",k),document.querySelector('[data-panel="updates-dashcaddy"]')?.addEventListener("click",()=>{u(),r(),b||s(!0)}),window.dcApplyUpdate=d,window.dcCheckForUpdate=s,setTimeout(()=>s(!0),5e3)})(),(function(){injectModal("docker-resources-modal",`
",P.innerHTML=w,P.querySelectorAll(".dr-vol-del").forEach(T=>{T.addEventListener("click",async()=>{if(confirm(`Delete volume "${T.dataset.name}"? Data will be lost.`)){T.textContent="...",T.disabled=!0;try{await deleteAPI(`/api/v1/docker/volumes/${encodeURIComponent(T.dataset.name)}?force=true`),N()}catch(k){showNotification("Delete failed: "+k.message,"error"),T.textContent="Delete",T.disabled=!1}}})})}catch(g){P.innerHTML=`
Failed: ${escapeHtml(g.message)}
`}}document.getElementById("dr-vol-create")?.addEventListener("click",async()=>{const P=document.getElementById("dr-vol-name"),g=P.value.trim();if(!g){showNotification("Enter a volume name","warning");return}try{await postJSON("/api/v1/docker/volumes",{name:g}),P.value="",showNotification(`Volume "${g}" created`,"success"),N()}catch(L){showNotification("Create failed: "+L.message,"error")}});async function R(){const P=document.getElementById("dr-net-list");try{const L=(await getJSON("/api/v1/docker/networks")).networks||[];if(L.length===0){P.innerHTML='
\u{1F310}No networks found.
';return}let w='
';w+='
Name
Driver
Scope
Containers
Actions
';for(const T of L){const k=["bridge","host","none"].includes(T.name);w+='
';for(const w of g.results){const T=w.status==="deployed"||w.status==="created"?"\u2705":w.status==="exists"?"\u26A1":w.status==="skipped"?"\u23ED":"\u274C";L+='
`}}S?.addEventListener("click",()=>{h?.classList.add("show"),w(!1)}),wireModal(h,O),E?.addEventListener("click",()=>w(!1)),R?.addEventListener("change",()=>w(!1)),P?.addEventListener("click",()=>w(!0)),N?.addEventListener("click",async()=>{if(confirm("Clear the entire audit log? This cannot be undone."))try{const k=await(await secureFetch("/api/v1/audit-logs",{method:"DELETE"})).json();k.success?w(!1):showNotification("Error: "+(k.error||"Clear failed"),"error")}catch(T){showNotification("Error: "+T.message,"error")}})})(),(function(){injectModal("security-modal",`
\u{1F6E1}\uFE0F Security Center
Live events from API, Caddy, fail2ban & shared_bans. Live-tail via SSE.
`}async function y(){try{const d=(await(await fetch("/api/v1/security/hosts")).json()).data?.hosts||[],r=C.value;C.innerHTML=''+d.map(f=>``).join(""),r&&(C.value=r)}catch{}}document.getElementById("sec-host-register-btn").addEventListener("click",b),document.getElementById("sec-hosts-refresh").addEventListener("click",m);async function m(){try{const d=(await(await fetch("/api/v1/security/hosts")).json()).data?.hosts||[];z=d;const r=document.getElementById("sec-hosts-container");if(!d.length){r.innerHTML='
No hosts registered. Click \u2795 Register Host to add one.
id: ${p(f.id)} \xB7
registered ${new Date(f.registered_at).toLocaleDateString()} \xB7
last seen ${f.last_seen_at?new Date(f.last_seen_at).toLocaleString():"never"}
${v}
${f.id==="self"?"":``}
`}).join(""),r.querySelectorAll(".sec-host-del").forEach(f=>{f.addEventListener("click",async()=>{confirm(`Remove host ${f.dataset.id}? Events already received will remain in the store.`)&&(await fetch(`/api/v1/security/hosts/${encodeURIComponent(f.dataset.id)}`,{method:"DELETE"}),m())})})}catch(s){document.getElementById("sec-hosts-container").innerHTML='
Load failed: '+p(s.message)+"
"}}async function b(){const s=prompt("Host id (lowercase, no spaces):");if(!s)return;const d=prompt("Display label:",s)||s,r=prompt('Type ("dashcaddy", "service", or "agent"):',"agent")||"agent";try{const f=await fetch("/api/v1/security/hosts",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({id:s,label:d,type:r})}),v=await f.json();if(!f.ok){alert("Failed: "+(v?.error?.message||f.statusText));return}alert(`\u2705 Host registered!
id: ${v.data.host.id}
label: ${v.data.host.label}
type: ${v.data.host.type}
\u{1F511} API KEY (save this NOW \u2014 won't be shown again):
${v.data.api_key}
Send this key as: Authorization: Bearer
To endpoint: POST /api/v1/security/events/ingest or /events/batch`),m()}catch(f){alert("Failed: "+f.message)}}function p(s){return String(s).replace(/[&<>"']/g,d=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[d])}function u(s,d){let r;return function(){clearTimeout(r),r=setTimeout(()=>s.apply(this,arguments),d)}}})(),(function(){const h=new ErrorHandler;injectModal("weather-modal",`
Weather Settings
Enter a city name, postal code, or “City, Country”
`);const S="weather-location",O="weather-zip",E="weather-geo",N="weather-unit";!safeGet(S)&&safeGet(O)&&safeSet(S,safeGet(O));function R(){return safeGet(N)||"imperial"}function z(){return{icon:document.querySelector(".weather-icon"),temp:document.querySelector(".weather-temp"),condition:document.querySelector(".weather-condition"),location:document.querySelector(".weather-location"),wind:document.querySelector(".weather-wind")}}const P={0:"Clear sky",1:"Mainly clear",2:"Partly cloudy",3:"Overcast",45:"Fog",48:"Rime fog",51:"Light drizzle",53:"Drizzle",55:"Dense drizzle",56:"Freezing drizzle",57:"Dense freezing drizzle",61:"Light rain",63:"Moderate rain",65:"Heavy rain",66:"Light freezing rain",67:"Heavy freezing rain",71:"Light snow",73:"Moderate snow",75:"Heavy snow",77:"Snow grains",80:"Light showers",81:"Moderate showers",82:"Violent showers",85:"Light snow showers",86:"Heavy snow showers",95:"Thunderstorm",96:"Thunderstorm with hail",99:"Severe thunderstorm"},g={0:"\u2600\uFE0F",1:"\u{1F324}\uFE0F",2:"\u26C5",3:"\u2601\uFE0F",45:"\u{1F32B}\uFE0F",48:"\u{1F32B}\uFE0F",51:"\u{1F326}\uFE0F",53:"\u{1F326}\uFE0F",55:"\u{1F326}\uFE0F",56:"\u{1F328}\uFE0F",57:"\u{1F328}\uFE0F",61:"\u{1F326}\uFE0F",63:"\u{1F327}\uFE0F",65:"\u{1F327}\uFE0F",66:"\u{1F328}\uFE0F",67:"\u{1F328}\uFE0F",71:"\u{1F328}\uFE0F",73:"\u2744\uFE0F",75:"\u2744\uFE0F",77:"\u2744\uFE0F",80:"\u{1F326}\uFE0F",81:"\u{1F327}\uFE0F",82:"\u{1F327}\uFE0F",85:"\u{1F328}\uFE0F",86:"\u2744\uFE0F",95:"\u26C8\uFE0F",96:"\u26C8\uFE0F",99:"\u26C8\uFE0F"},L=["N","NNE","NE","ENE","E","ESE","SE","SSE","S","SSW","SW","WSW","W","WNW","NW","NNW"];function w(M){return L[Math.round(M/22.5)%16]}async function T(M){const D=safeGet(E);if(D)try{const b=JSON.parse(D);if(b.query===M)return b}catch{}const x=await fetch(`https://geocoding-api.open-meteo.com/v1/search?name=${encodeURIComponent(M)}&count=1&language=en&format=json`);if(!x.ok)throw new Error("Geocoding failed");const A=await x.json();if(!A.results||!A.results.length)throw new Error("Location not found");const y=A.results[0],m={query:M,lat:y.latitude,lon:y.longitude,city:y.name,state:y.admin1||"",country:y.country||"",countryCode:y.country_code||""};return safeSet(E,JSON.stringify(m)),m}function k(M){return M.countryCode==="US"&&M.state?`${M.city}, ${M.state}`:M.country?`${M.city}, ${M.country}`:M.city}async function B(M){try{const D=await T(M),x=R(),A=x==="metric"?"celsius":"fahrenheit",y=x==="metric"?"kmh":"mph",m=`https://api.open-meteo.com/v1/forecast?latitude=${D.lat}&longitude=${D.lon}¤t=temperature_2m,weather_code,wind_speed_10m,wind_direction_10m&temperature_unit=${A}&wind_speed_unit=${y}`,b=await fetch(m);if(!b.ok)throw new Error("Weather fetch failed");const u=(await b.json()).current,s=u.weather_code;return{temp:Math.round(u.temperature_2m),condition:P[s]||"Unknown",icon:g[s]||"\u{1F324}\uFE0F",locationStr:k(D),windSpeed:Math.round(u.wind_speed_10m),windDir:w(u.wind_direction_10m),unit:x}}catch(D){return console.warn("Weather fetch failed:",D),null}}async function I(){const M=z();if(!M.icon||!M.temp||!M.condition||!M.location||!M.wind){console.warn("Weather widget elements not found");return}const D=safeGet(S);if(!D){M.location.textContent="Set Location",M.temp.textContent="--\xB0",M.condition.textContent="Click \u2699\uFE0F to configure",M.wind.textContent="--",M.icon.innerHTML='\u{1F324}\uFE0F';return}try{const x=await B(D);if(x){const A=x.unit==="metric"?"\xB0C":"\xB0F",y=x.unit==="metric"?"km/h":"mph";M.location.textContent=x.locationStr,M.temp.textContent=`${x.temp}${A}`,M.condition.textContent=x.condition,M.wind.textContent=`Wind: ${x.windSpeed} ${y} ${x.windDir}`,M.icon.innerHTML=`${escapeHtml(x.icon)}`}}catch(x){h.logError("[Weather] Update Error",x,{function:"updateWeather"}),M.location.textContent="Weather Error",M.temp.textContent="Error",M.condition.textContent="Failed to load",M.wind.textContent="--"}}const C=document.getElementById("weather-modal"),j=document.getElementById("weather-location-input");document.getElementById("weather-settings")?.addEventListener("click",()=>{j.value=safeGet(S)||"";const M=R(),D=C.querySelector(`input[name="weather-unit-radio"][value="${M}"]`);D&&(D.checked=!0),C.classList.add("show"),j.focus()}),document.getElementById("weather-cancel")?.addEventListener("click",()=>{C.classList.remove("show")}),document.getElementById("weather-save")?.addEventListener("click",()=>{const M=j.value.trim();if(M){safeGet(S)!==M&&safeSet(E,""),safeSet(S,M);const x=C.querySelector('input[name="weather-unit-radio"]:checked'),A=x?x.value:"imperial",y=R();safeSet(N,A),y!==A&&safeSet(E,""),C.classList.remove("show"),I()}else showNotification("Please enter a location (e.g., Hamburg, London, 90210)","warning")}),wireModal(C),document.addEventListener("keydown",M=>{M.key==="Escape"&&C.classList.contains("show")&&C.classList.remove("show")}),I(),setInterval(I,DC.POLL.WEATHER)})(),(function(){const h=document.getElementById("clock-widget"),S=document.getElementById("clock-render");if(!h||!S)return;const O=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],E=["January","February","March","April","May","June","July","August","September","October","November","December"],N=["XII","I","II","III","IV","V","VI","VII","VIII","IX","X","XI"];let R=safeGet("clock-style")||"default",z=-1,P=!1,g="",L="",w=null,T=null;function k(t){if(P||safeGet("clock-chimes")!=="true")return;P=!0;const e=parseInt(safeGet("clock-chime-volume")||"50",10)/100;let n=0;function a(){if(n>=t){P=!1;return}const l=new Audio("/assets/sounds/church-bell.mp3");l.volume=e,l.play().catch(()=>{}),n++,n{P=!1},2500)}a()}function B(t){return O[t.getDay()]+", "+E[t.getMonth()]+" "+t.getDate()+", "+t.getFullYear()}function I(){L="",w=null}function C(){return L!=="digital"&&(S.innerHTML='
`).join("")}async function M(){try{const p=await(await fetch("/api/v1/license/status")).json();p.success&&(j(p.license),A(p.license))}catch(b){console.warn("Failed to load license status:",b.message)}}async function D(){const b=S.value.trim();if(!b){I("Please enter a license code.");return}B(),O.disabled=!0,O.textContent="Activating...";try{const u=await(await secureFetch("/api/v1/license/activate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:b})})).json();u.success?(C(u.message),S.value="",j(u.license),showNotification("License activated! Premium features unlocked.","success",5e3),A(u.license)):I(u.error||"Activation failed")}catch(p){I("Network error: "+p.message)}finally{O.disabled=!1,O.textContent="Activate"}}async function x(){if(confirm("Deactivate your license? You can reuse the code on another machine.")){E.disabled=!0,E.textContent="Deactivating...";try{const p=await(await secureFetch("/api/v1/license/deactivate",{method:"POST"})).json();p.success?(C(p.message),await M(),showNotification("License deactivated.","info",3e3),A({active:!1})):I(p.error||"Deactivation failed")}catch(b){I("Network error: "+b.message)}finally{E.disabled=!1,E.textContent="Deactivate"}}}function A(b){const p=document.getElementById("license-status-topbar"),u=document.getElementById("license-topbar-icon"),s=document.getElementById("license-topbar-text"),d=document.getElementById("license-topbar-time");if(p)if(p.className="license-status-topbar "+(b.active?"premium":"free"),b.active)if(u.textContent="\u2605",s.textContent="PREMIUM",b.lifetime)d.textContent="\xB7 LIFETIME";else{const r=b.daysRemaining;d.textContent=r!=null?"\xB7 "+r+"d remaining":""}else u.textContent="\u2606",s.textContent=b.expired?"EXPIRED":"FREE TIER",d.textContent=""}function y(){B(),M(),h.classList.add("show")}S.addEventListener("input",function(){let b=this.value.toUpperCase().replace(/[^A-Z0-9-]/g,"");if(b.length>this._prevLength&&(b=b.replace(/-/g,""),b.length>2&&!b.startsWith("DC")&&(b="DC"+b),b.startsWith("DC")&&b.length>2)){const p=["DC"],u=b.substring(2);for(let s=0;s{b.key==="Enter"&&D()}),wireModal(h,document.getElementById("license-cancel"));const m=document.getElementById("license-status-topbar");m&&m.addEventListener("click",()=>window.openLicenseModal&&window.openLicenseModal()),window.openLicenseModal=y,window.checkPremiumFeature=async function(b){try{return(await(await fetch(`/api/v1/license/feature/${b}`)).json()).available}catch{return!1}},M().then(b=>{k&&A(k)})})(),(function(){"use strict";if(window.__dc_058_share_modal_loaded)return;window.__dc_058_share_modal_loaded=!0;const h=[{ms:3600*1e3,label:"1 hour"},{ms:1440*60*1e3,label:"24 hours"},{ms:10080*60*1e3,label:"7 days"}];injectModal("share-modal",`
Share \u2026
Create a public link or Tailscale invite so someone outside your network can access this service.
A single-use Tailscale pre-auth key is generated and emailed. The device joins your tailnet and is routed to this service via Caddy.
`}).join(""),L.querySelectorAll(".share-revoke").forEach(l=>{l.addEventListener("click",()=>s(l.dataset.shareId))})}catch{L.innerHTML='Could not load outstanding shares.'}}async function s(t){try{const e=await fetch(`/api/v1/share/${encodeURIComponent(t)}`,{method:"DELETE",credentials:"same-origin"});if(!e.ok){const n=await e.json().catch(()=>({}));D(n&&n.error||`Revoke failed (HTTP ${e.status}).`);return}x("Share revoked."),u()}catch{D("Network error while revoking.")}}async function d(){if(!C)return;M(),T.disabled=!0;const t=T.textContent;T.textContent="Creating\u2026";try{const e=parseInt(I.value,10),n=await fetch("/api/v1/share",{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json"},body:JSON.stringify({serviceId:C.id,ttlMs:e})}),a=await n.json().catch(()=>({}));if(!n.ok||!a.success){f(n.status,a);return}const l=a.data.urlPath;N.value=y(l),z.textContent=`Public link \xB7 expires ${m(a.data.expiresAt)}`,E.style.display="block",x("Share link created."),u()}catch{D("Network error while creating share.")}finally{T.disabled=!1,T.textContent=t}}async function r(){if(!C)return;const t=(B.value||"").trim();if(!t||!t.includes("@")){D("A valid recipient email is required.");return}M(),k.disabled=!0;const e=k.textContent;k.textContent="Creating\u2026";try{const n=await fetch("/api/v1/share/tailscale",{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json"},body:JSON.stringify({serviceId:C.id,email:t})}),a=await n.json().catch(()=>({}));if(!n.ok||!a.success){f(n.status,a);return}const l=a.data&&a.data.urlPath;l?(N.value=y(l),z.textContent=`Tailscale invite \xB7 emailed to ${t} (or use this URL manually if delivery failed).`):(N.value="",z.textContent=`Tailscale invite sent to ${t}.`),E.style.display="block",x("Tailscale invite created."),B.value="",u()}catch{D("Network error while creating Tailscale invite.")}finally{k.disabled=!1,k.textContent=e}}function f(t,e){const n=e&&e.error||"";if(t===402){D("Share is a Pro feature. Activate a license to unlock.");return}if(t===400&&/tailscale/i.test(n)){D("Tailscale is not configured on this host. Set up Tailscale in the dashboard first.");return}if(t===403){D("You do not have permission to share services.");return}if(t===404){D("Service not found. It may have been deleted.");return}D(n||`Request failed (HTTP ${t}).`)}function v(t){!t||!t.id||(C={id:t.id,name:t.name||t.id},O.textContent=C.name,M(),p("public"),B.value="",I.value=String(h[1].ms),S.classList.add("show"),u())}S.querySelectorAll(".share-tab").forEach(t=>{t.addEventListener("click",()=>p(t.dataset.tab))}),T.addEventListener("click",d),k.addEventListener("click",r),w.addEventListener("click",()=>S.classList.remove("show")),wireModal(S,w),R.addEventListener("click",async()=>{const t=N.value;if(t)try{navigator.clipboard&&navigator.clipboard.writeText?await navigator.clipboard.writeText(t):(N.select(),document.execCommand("copy"));const e=R.textContent;R.textContent="Copied!",setTimeout(()=>{R.textContent=e},1200)}catch{D("Could not copy to clipboard. Select the URL manually.")}}),window.openShareModal=v})();