diff --git a/status/build.js b/status/build.js index 253efaf..0512377 100644 --- a/status/build.js +++ b/status/build.js @@ -72,6 +72,11 @@ const bundles = { JS('card-badges.js'), JS('theme-builder.js'), JS('license.js'), + // DC-058: Share modal — opened from the share button on each service card. + // Must come after license.js because it uses window.openShareModal and + // window.wireModal + window.injectModal + window.escapeHtml helpers + // defined in globals.js (already in core.js). + JS('share-modal.js'), ], 'onboarding.js': [ JS('driver.min.js'), diff --git a/status/dist/core.js b/status/dist/core.js index 9ee6a23..52ad8ef 100644 --- a/status/dist/core.js +++ b/status/dist/core.js @@ -1,4 +1,4 @@ -(function(c){"use strict";class a{constructor(){this.errors=[],this.maxErrors=50}logError(h,f,m={}){const b={timestamp:new Date().toISOString(),context:h,message:f instanceof Error?f.message:f,stack:f instanceof Error?f.stack:null,metadata:m};this.errors.push(b),this.errors.length>this.maxErrors&&this.errors.shift(),console.error(`[Onboarding Error] ${h}:`,f,m)}recoverFromError(h,f){switch(this.classifyError(h)){case"ELEMENT_NOT_FOUND":return this.logError("Element Not Found",h,{currentStep:f}),{action:"SKIP_STEP",nextStep:f+1,message:"Target element not found, skipping to next step"};case"STORAGE_UNAVAILABLE":return this.logError("Storage Unavailable",h),{action:"USE_MEMORY_STORAGE",message:"Local storage unavailable, using in-memory storage"};case"DRIVER_NOT_LOADED":return this.logError("Driver.js Not Loaded",h),{action:"ABORT_TOUR",message:"Driver.js library not loaded, cannot start tour"};case"INVALID_TOOLTIP":return this.logError("Invalid Tooltip Configuration",h,{currentStep:f}),{action:"SKIP_STEP",nextStep:f+1,message:"Invalid tooltip configuration, skipping"};case"THEME_DETECTION_FAILED":return this.logError("Theme Detection Failed",h),{action:"USE_DEFAULT_THEME",message:"Using default dark theme"};default:return this.logError("Unknown Error",h,{currentStep:f}),{action:"ABORT_TOUR",message:"Unexpected error occurred, aborting tour"}}}classifyError(h){const f=h.message||h.toString();return f.includes("element")&&f.includes("not found")?"ELEMENT_NOT_FOUND":f.includes("storage")||f.includes("quota")?"STORAGE_UNAVAILABLE":f.includes("driver")||f.includes("undefined")?"DRIVER_NOT_LOADED":f.includes("invalid")||f.includes("validation")?"INVALID_TOOLTIP":f.includes("theme")?"THEME_DETECTION_FAILED":"UNKNOWN"}getErrors(){return[...this.errors]}clearErrors(){this.errors=[]}getStatistics(){const h={total:this.errors.length,byContext:{},byType:{},recent:this.errors.slice(-10)};return this.errors.forEach(f=>{h.byContext[f.context]=(h.byContext[f.context]||0)+1;const m=this.classifyError({message:f.message});h.byType[m]=(h.byType[m]||0)+1}),h}handleDriverLoadFailure(){this.logError("Driver.js Load Failure","Driver.js library failed to load");const h=document.createElement("div");return h.id="onboarding-fallback",h.style.cssText=` +(function(c){"use strict";class a{constructor(){this.errors=[],this.maxErrors=50}logError(h,g,m={}){const b={timestamp:new Date().toISOString(),context:h,message:g instanceof Error?g.message:g,stack:g instanceof Error?g.stack:null,metadata:m};this.errors.push(b),this.errors.length>this.maxErrors&&this.errors.shift(),console.error(`[Onboarding Error] ${h}:`,g,m)}recoverFromError(h,g){switch(this.classifyError(h)){case"ELEMENT_NOT_FOUND":return this.logError("Element Not Found",h,{currentStep:g}),{action:"SKIP_STEP",nextStep:g+1,message:"Target element not found, skipping to next step"};case"STORAGE_UNAVAILABLE":return this.logError("Storage Unavailable",h),{action:"USE_MEMORY_STORAGE",message:"Local storage unavailable, using in-memory storage"};case"DRIVER_NOT_LOADED":return this.logError("Driver.js Not Loaded",h),{action:"ABORT_TOUR",message:"Driver.js library not loaded, cannot start tour"};case"INVALID_TOOLTIP":return this.logError("Invalid Tooltip Configuration",h,{currentStep:g}),{action:"SKIP_STEP",nextStep:g+1,message:"Invalid tooltip configuration, skipping"};case"THEME_DETECTION_FAILED":return this.logError("Theme Detection Failed",h),{action:"USE_DEFAULT_THEME",message:"Using default dark theme"};default:return this.logError("Unknown Error",h,{currentStep:g}),{action:"ABORT_TOUR",message:"Unexpected error occurred, aborting tour"}}}classifyError(h){const g=h.message||h.toString();return g.includes("element")&&g.includes("not found")?"ELEMENT_NOT_FOUND":g.includes("storage")||g.includes("quota")?"STORAGE_UNAVAILABLE":g.includes("driver")||g.includes("undefined")?"DRIVER_NOT_LOADED":g.includes("invalid")||g.includes("validation")?"INVALID_TOOLTIP":g.includes("theme")?"THEME_DETECTION_FAILED":"UNKNOWN"}getErrors(){return[...this.errors]}clearErrors(){this.errors=[]}getStatistics(){const h={total:this.errors.length,byContext:{},byType:{},recent:this.errors.slice(-10)};return this.errors.forEach(g=>{h.byContext[g.context]=(h.byContext[g.context]||0)+1;const m=this.classifyError({message:g.message});h.byType[m]=(h.byType[m]||0)+1}),h}handleDriverLoadFailure(){this.logError("Driver.js Load Failure","Driver.js library failed to load");const h=document.createElement("div");return h.id="onboarding-fallback",h.style.cssText=` position: fixed; bottom: 20px; right: 20px; @@ -16,38 +16,38 @@ The interactive tour is unavailable, but you can explore the dashboard freely. Check the documentation for help getting started.

- `,document.body.appendChild(h),setTimeout(()=>{h.parentNode&&h.parentNode.removeChild(h)},1e4),!0}handleStorageUnavailable(){this.logError("Storage Unavailable","Local storage is not available");const h={data:{},getItem(f){return this.data[f]||null},setItem(f,m){this.data[f]=m},removeItem(f){delete this.data[f]},clear(){this.data={}}};return console.warn("[ErrorHandler] Using in-memory storage - progress will not persist"),h}sendToErrorTracking(h){}}c.ErrorHandler=a,console.log("[ErrorHandler] Module loaded")})(window);const DC={NAME:"DashCaddy",POLL:{DASHBOARD:1e4,LOGS:3e3,STATS:5e3,WEATHER:6e5,HEALTH:1e3,DEPLOY_SSL:5e3},DELAYS:{BTN_RESET:2e3,RELOAD:5e3,MODAL_CLOSE:500,PORT_CHECK:500,DEPLOY_INIT:3e3},DEFAULTS:{DNS_PORT:"5380",SERVICE_PORT:"8080",TTL:300,CADDYFILE:"C:\\caddy\\Caddyfile"}},errorHandler=new ErrorHandler,_cachedCfg=JSON.parse(localStorage.getItem("dashcaddy_site_config")||"null"),SITE={tld:_cachedCfg&&_cachedCfg.tld||".home",dnsIp:"",dnsPort:DC.DEFAULTS.DNS_PORT,dnsServers:{},configurationType:_cachedCfg&&_cachedCfg.configurationType||"homelab",domain:_cachedCfg&&_cachedCfg.domain||"",defaults:_cachedCfg&&_cachedCfg.defaults||{},routingMode:_cachedCfg&&_cachedCfg.routingMode||"subdomain",onboardingCompleted:!1};window.__dashcaddySiteConfigLoaded=(async function(){try{const h=await fetch("/api/v1/config");if(h.ok){const f=await h.json();if(f.tld&&(SITE.tld=f.tld.startsWith(".")?f.tld:"."+f.tld),f.dns&&(SITE.dnsIp=f.dns.ip||"",SITE.dnsPort=f.dns.port||DC.DEFAULTS.DNS_PORT),f.dnsServers&&typeof f.dnsServers=="object")for(const[b,s]of Object.entries(f.dnsServers))b!=="__proto__"&&b!=="constructor"&&b!=="prototype"&&(SITE.dnsServers[b]=s);f.configurationType&&(SITE.configurationType=f.configurationType),f.domain&&(SITE.domain=f.domain),f.defaults&&(SITE.defaults=f.defaults),f.routingMode&&(SITE.routingMode=f.routingMode),SITE.onboardingCompleted=f.onboardingCompleted===!0,localStorage.setItem("dashcaddy_site_config",JSON.stringify({tld:SITE.tld,configurationType:SITE.configurationType,domain:SITE.domain,routingMode:SITE.routingMode})),renderDnsCards();const m=document.getElementById("manage-tokens");m&&(m.style.display=Object.keys(SITE.dnsServers).length?"":"none")}}catch{}document.querySelectorAll("[data-tld]").forEach(h=>h.textContent=SITE.tld);const a=document.getElementById("edit-tld-suffix");a&&(a.textContent=SITE.tld);const g=document.getElementById("external-proxy-ip");g&&SITE.dnsIp&&(g.value=SITE.dnsIp,g.placeholder=SITE.dnsIp)})();function buildDomain(c){return c+SITE.tld}function buildServiceUrl(c){return SITE.routingMode==="subdirectory"&&SITE.domain?"https://"+SITE.domain+"/"+c:SITE.configurationType==="public"&&SITE.domain?"https://"+c+"."+SITE.domain:"https://"+buildDomain(c)}function getDnsServerAddr(c){const a=SITE.dnsServers[c];return a?`${a.ip}:${a.port}`:buildDomain(c)}function getPrimaryDnsId(){if(!SITE.dnsIp)return null;for(const[c,a]of Object.entries(SITE.dnsServers))if(a.ip===SITE.dnsIp)return c;return null}function renderDnsCards(){const c=document.querySelector(".top");if(!c)return;const a=Object.keys(SITE.dnsServers);if(!a.length)return;const g='',h=c.firstElementChild;a.forEach(f=>{const m=escapeHtml(f),b=escapeHtml((SITE.dnsServers[f].name||f).toUpperCase()),s=document.createElement("div");s.className="card",s.setAttribute("data-app",f),s.setAttribute("data-status","off"),s.innerHTML=`
${g}
${b}OFF
--
--
`,c.insertBefore(s,h)})}window.renderDnsCards=renderDnsCards;let csrfToken=null;async function getCSRFToken(){if(csrfToken)return csrfToken;try{const c=await fetch("/api/v1/csrf-token");if(!c.ok)throw new Error("Failed to fetch CSRF token");return csrfToken=(await c.json()).token,csrfToken}catch(c){throw errorHandler.logError("[CSRF] Get Token",c,{function:"getCSRFToken"}),c}}async function secureFetch(c,a={}){const g=(a.method||"GET").toUpperCase(),h=!["GET","HEAD","OPTIONS"].includes(g);if(h)try{const m=await getCSRFToken();a.headers={...a.headers,"X-CSRF-Token":m}}catch(m){errorHandler.logError("[CSRF] Add to Request",m,{function:"secureFetch"})}a.signal||(a={...a,signal:AbortSignal.timeout(15e3)});const f=await fetch(c,a);if(h&&f.status===403)try{const m=await f.clone().json();if(m.error&&(m.error.includes("DC-100")||m.error.includes("DC-101"))){csrfToken=null;const b=await getCSRFToken();return a.headers={...a.headers,"X-CSRF-Token":b},a.signal=AbortSignal.timeout(15e3),fetch(c,a)}}catch{}return f}async function postJSON(c,a){const g=await secureFetch(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)}),h=await g.json();if(!g.ok||h.success===!1)throw new Error(h.error||`Request failed (${g.status})`);return h}async function getJSON(c){const a=await secureFetch(c);if(!a.ok){let g=`Request failed (${a.status})`;try{g=(await a.json()).error||g}catch{}throw new Error(g)}return a.json()}async function deleteAPI(c){const a=await secureFetch(c,{method:"DELETE"}),g=await a.json();if(!a.ok||g.success===!1)throw new Error(g.error||`Delete failed (${a.status})`);return g}async function withButton(c,a,g,h={}){const f=c.innerHTML,{successText:m="\u2705",resetDelay:b=DC.DELAYS.BTN_RESET}=h;c.disabled=!0,c.innerHTML=a;try{const s=await g();return c.innerHTML=m,setTimeout(()=>{c.innerHTML=f,c.disabled=!1},b),s}catch(s){throw c.innerHTML=f,c.disabled=!1,s}}function openModal(c){document.getElementById(c)?.classList.add("show")}function closeModal(c){document.getElementById(c)?.classList.remove("show")}function wireModal(c,...a){c&&(c.addEventListener("click",g=>{g.target===c&&c.classList.remove("show")}),a.forEach(g=>{g&&typeof g.addEventListener=="function"&&g.addEventListener("click",()=>c.classList.remove("show"))}))}function showNotification(c,a="info",g=3e3){const h=document.querySelector(".deploy-notification");h&&h.remove();const f={info:{bg:"#2196F3",fg:"#fff"},success:{bg:"var(--ok-bg)",fg:"var(--ok-fg)"},error:{bg:"#f44336",fg:"#fff"},warning:{bg:"#ff9800",fg:"#fff"}},m=f[a]||f.info,b=document.createElement("div");b.className="deploy-notification",b.textContent=c,b.style.cssText=` + `,document.body.appendChild(h),setTimeout(()=>{h.parentNode&&h.parentNode.removeChild(h)},1e4),!0}handleStorageUnavailable(){this.logError("Storage Unavailable","Local storage is not available");const h={data:{},getItem(g){return this.data[g]||null},setItem(g,m){this.data[g]=m},removeItem(g){delete this.data[g]},clear(){this.data={}}};return console.warn("[ErrorHandler] Using in-memory storage - progress will not persist"),h}sendToErrorTracking(h){}}c.ErrorHandler=a,console.log("[ErrorHandler] Module loaded")})(window);const DC={NAME:"DashCaddy",POLL:{DASHBOARD:1e4,LOGS:3e3,STATS:5e3,WEATHER:6e5,HEALTH:1e3,DEPLOY_SSL:5e3},DELAYS:{BTN_RESET:2e3,RELOAD:5e3,MODAL_CLOSE:500,PORT_CHECK:500,DEPLOY_INIT:3e3},DEFAULTS:{DNS_PORT:"5380",SERVICE_PORT:"8080",TTL:300,CADDYFILE:"C:\\caddy\\Caddyfile"}},errorHandler=new ErrorHandler,_cachedCfg=JSON.parse(localStorage.getItem("dashcaddy_site_config")||"null"),SITE={tld:_cachedCfg&&_cachedCfg.tld||".home",dnsIp:"",dnsPort:DC.DEFAULTS.DNS_PORT,dnsServers:{},configurationType:_cachedCfg&&_cachedCfg.configurationType||"homelab",domain:_cachedCfg&&_cachedCfg.domain||"",defaults:_cachedCfg&&_cachedCfg.defaults||{},routingMode:_cachedCfg&&_cachedCfg.routingMode||"subdomain",onboardingCompleted:!1};window.__dashcaddySiteConfigLoaded=(async function(){try{const h=await fetch("/api/v1/config");if(h.ok){const g=await h.json();if(g.tld&&(SITE.tld=g.tld.startsWith(".")?g.tld:"."+g.tld),g.dns&&(SITE.dnsIp=g.dns.ip||"",SITE.dnsPort=g.dns.port||DC.DEFAULTS.DNS_PORT),g.dnsServers&&typeof g.dnsServers=="object")for(const[b,r]of Object.entries(g.dnsServers))b!=="__proto__"&&b!=="constructor"&&b!=="prototype"&&(SITE.dnsServers[b]=r);g.configurationType&&(SITE.configurationType=g.configurationType),g.domain&&(SITE.domain=g.domain),g.defaults&&(SITE.defaults=g.defaults),g.routingMode&&(SITE.routingMode=g.routingMode),SITE.onboardingCompleted=g.onboardingCompleted===!0,localStorage.setItem("dashcaddy_site_config",JSON.stringify({tld:SITE.tld,configurationType:SITE.configurationType,domain:SITE.domain,routingMode:SITE.routingMode})),renderDnsCards();const m=document.getElementById("manage-tokens");m&&(m.style.display=Object.keys(SITE.dnsServers).length?"":"none")}}catch{}document.querySelectorAll("[data-tld]").forEach(h=>h.textContent=SITE.tld);const a=document.getElementById("edit-tld-suffix");a&&(a.textContent=SITE.tld);const f=document.getElementById("external-proxy-ip");f&&SITE.dnsIp&&(f.value=SITE.dnsIp,f.placeholder=SITE.dnsIp)})();function buildDomain(c){return c+SITE.tld}function buildServiceUrl(c){return SITE.routingMode==="subdirectory"&&SITE.domain?"https://"+SITE.domain+"/"+c:SITE.configurationType==="public"&&SITE.domain?"https://"+c+"."+SITE.domain:"https://"+buildDomain(c)}function getDnsServerAddr(c){const a=SITE.dnsServers[c];return a?`${a.ip}:${a.port}`:buildDomain(c)}function getPrimaryDnsId(){if(!SITE.dnsIp)return null;for(const[c,a]of Object.entries(SITE.dnsServers))if(a.ip===SITE.dnsIp)return c;return null}function renderDnsCards(){const c=document.querySelector(".top");if(!c)return;const a=Object.keys(SITE.dnsServers);if(!a.length)return;const f='',h=c.firstElementChild;a.forEach(g=>{const m=escapeHtml(g),b=escapeHtml((SITE.dnsServers[g].name||g).toUpperCase()),r=document.createElement("div");r.className="card",r.setAttribute("data-app",g),r.setAttribute("data-status","off"),r.innerHTML=`
${f}
${b}OFF
--
--
`,c.insertBefore(r,h)})}window.renderDnsCards=renderDnsCards;let csrfToken=null;async function getCSRFToken(){if(csrfToken)return csrfToken;try{const c=await fetch("/api/v1/csrf-token");if(!c.ok)throw new Error("Failed to fetch CSRF token");return csrfToken=(await c.json()).token,csrfToken}catch(c){throw errorHandler.logError("[CSRF] Get Token",c,{function:"getCSRFToken"}),c}}async function secureFetch(c,a={}){const f=(a.method||"GET").toUpperCase(),h=!["GET","HEAD","OPTIONS"].includes(f);if(h)try{const m=await getCSRFToken();a.headers={...a.headers,"X-CSRF-Token":m}}catch(m){errorHandler.logError("[CSRF] Add to Request",m,{function:"secureFetch"})}a.signal||(a={...a,signal:AbortSignal.timeout(15e3)});const g=await fetch(c,a);if(h&&g.status===403)try{const m=await g.clone().json();if(m.error&&(m.error.includes("DC-100")||m.error.includes("DC-101"))){csrfToken=null;const b=await getCSRFToken();return a.headers={...a.headers,"X-CSRF-Token":b},a.signal=AbortSignal.timeout(15e3),fetch(c,a)}}catch{}return g}async function postJSON(c,a){const f=await secureFetch(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)}),h=await f.json();if(!f.ok||h.success===!1)throw new Error(h.error||`Request failed (${f.status})`);return h}async function getJSON(c){const a=await secureFetch(c);if(!a.ok){let f=`Request failed (${a.status})`;try{f=(await a.json()).error||f}catch{}throw new Error(f)}return a.json()}async function deleteAPI(c){const a=await secureFetch(c,{method:"DELETE"}),f=await a.json();if(!a.ok||f.success===!1)throw new Error(f.error||`Delete failed (${a.status})`);return f}async function withButton(c,a,f,h={}){const g=c.innerHTML,{successText:m="\u2705",resetDelay:b=DC.DELAYS.BTN_RESET}=h;c.disabled=!0,c.innerHTML=a;try{const r=await f();return c.innerHTML=m,setTimeout(()=>{c.innerHTML=g,c.disabled=!1},b),r}catch(r){throw c.innerHTML=g,c.disabled=!1,r}}function openModal(c){document.getElementById(c)?.classList.add("show")}function closeModal(c){document.getElementById(c)?.classList.remove("show")}function wireModal(c,...a){c&&(c.addEventListener("click",f=>{f.target===c&&c.classList.remove("show")}),a.forEach(f=>{f&&typeof f.addEventListener=="function"&&f.addEventListener("click",()=>c.classList.remove("show"))}))}function showNotification(c,a="info",f=3e3){const h=document.querySelector(".deploy-notification");h&&h.remove();const g={info:{bg:"#2196F3",fg:"#fff"},success:{bg:"var(--ok-bg)",fg:"var(--ok-fg)"},error:{bg:"#f44336",fg:"#fff"},warning:{bg:"#ff9800",fg:"#fff"}},m=g[a]||g.info,b=document.createElement("div");b.className="deploy-notification",b.textContent=c,b.style.cssText=` position: fixed; top: 20px; right: 20px; background: ${m.bg}; color: ${m.fg}; padding: 16px 24px; border-radius: 8px; box-shadow: 0 4px 12px rgba(0,0,0,.3); z-index: 10000; animation: slideIn 0.3s ease-out; max-width: 400px; white-space: pre-line; font-size: 14px; - `,document.body.appendChild(b),g>0&&setTimeout(()=>b.remove(),g)}function timeAgo(c){const a=Date.now()-new Date(c).getTime();return a<6e4?"just now":a<36e5?Math.floor(a/6e4)+"m ago":a<864e5?Math.floor(a/36e5)+"h ago":Math.floor(a/864e5)+"d ago"}function safeGet(c,a=null){try{const g=localStorage.getItem(c);return g!==null?g:a}catch{return a}}function safeSet(c,a){try{localStorage.setItem(c,a)}catch{}}function safeRemove(c){try{localStorage.removeItem(c)}catch{}}function safeSessionGet(c,a=null){try{const g=sessionStorage.getItem(c);return g!==null?g:a}catch{return a}}function safeSessionSet(c,a){try{sessionStorage.setItem(c,a)}catch{}}function safeGetJSON(c,a=null){try{const g=localStorage.getItem(c);return g?JSON.parse(g):a}catch{return a}}function escapeHtml(c){return String(c??"").replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'")}function injectModal(c,a){document.getElementById(c)||document.body.insertAdjacentHTML("beforeend",a)}const DC_BUS={_handlers:{},on(c,a){var g;((g=this._handlers)[c]||(g[c]=[])).push(a)},off(c,a){this._handlers[c]=this._handlers[c]?.filter(g=>g!==a)},emit(c,a){this._handlers[c]?.forEach(g=>g(a))}},AppState={_apps:[],getApps(){return this._apps},setApps(c){this._apps=c,window.APPS=c,DC_BUS.emit("apps:changed",c)},findApp(c){return this._apps.find(a=>a.id===c)},addApp(c){this._apps.push(c),window.APPS=this._apps,DC_BUS.emit("apps:changed",this._apps)},removeApp(c){const a=this._apps.findIndex(g=>g.id===c);return a>-1&&(this._apps.splice(a,1),window.APPS=this._apps,DC_BUS.emit("apps:changed",this._apps)),a>-1},updateApp(c,a){const g=this._apps.find(h=>h.id===c);if(g){for(const[h,f]of Object.entries(a))h!=="__proto__"&&h!=="constructor"&&h!=="prototype"&&(g[h]=f);DC_BUS.emit("apps:changed",this._apps)}return g}};(function(){function c(){const h=document.createElement("div");return h.className="skeleton-card",h.innerHTML='
',h}function a(h){const f=document.getElementById("cards");if(!(!f||f.querySelector(".card"))){h=h||6;for(let m=0;m.4,A={};return A.hover=I?p(x,B,.35):p(x,$,.08),A["card-hover"]=p(x,A.hover,.5),A.base=p(B,x,.6),A["fg-muted"]=p(C,B,.35),A.success=S,A.error=k,A.warning=I?"#d68a00":"#f39c12",A}function n(E,B){var $=B.lightBg||B.bg&&r(B.bg)>.4,C=B.accent||B["accent-strong"]||"#888888",x=d(C);return $?":root."+E+` body { + `,document.body.appendChild(b),f>0&&setTimeout(()=>b.remove(),f)}function timeAgo(c){const a=Date.now()-new Date(c).getTime();return a<6e4?"just now":a<36e5?Math.floor(a/6e4)+"m ago":a<864e5?Math.floor(a/36e5)+"h ago":Math.floor(a/864e5)+"d ago"}function safeGet(c,a=null){try{const f=localStorage.getItem(c);return f!==null?f:a}catch{return a}}function safeSet(c,a){try{localStorage.setItem(c,a)}catch{}}function safeRemove(c){try{localStorage.removeItem(c)}catch{}}function safeSessionGet(c,a=null){try{const f=sessionStorage.getItem(c);return f!==null?f:a}catch{return a}}function safeSessionSet(c,a){try{sessionStorage.setItem(c,a)}catch{}}function safeGetJSON(c,a=null){try{const f=localStorage.getItem(c);return f?JSON.parse(f):a}catch{return a}}function escapeHtml(c){return String(c??"").replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'")}function injectModal(c,a){document.getElementById(c)||document.body.insertAdjacentHTML("beforeend",a)}const DC_BUS={_handlers:{},on(c,a){var f;((f=this._handlers)[c]||(f[c]=[])).push(a)},off(c,a){this._handlers[c]=this._handlers[c]?.filter(f=>f!==a)},emit(c,a){this._handlers[c]?.forEach(f=>f(a))}},AppState={_apps:[],getApps(){return this._apps},setApps(c){this._apps=c,window.APPS=c,DC_BUS.emit("apps:changed",c)},findApp(c){return this._apps.find(a=>a.id===c)},addApp(c){this._apps.push(c),window.APPS=this._apps,DC_BUS.emit("apps:changed",this._apps)},removeApp(c){const a=this._apps.findIndex(f=>f.id===c);return a>-1&&(this._apps.splice(a,1),window.APPS=this._apps,DC_BUS.emit("apps:changed",this._apps)),a>-1},updateApp(c,a){const f=this._apps.find(h=>h.id===c);if(f){for(const[h,g]of Object.entries(a))h!=="__proto__"&&h!=="constructor"&&h!=="prototype"&&(f[h]=g);DC_BUS.emit("apps:changed",this._apps)}return f}};(function(){function c(){const h=document.createElement("div");return h.className="skeleton-card",h.innerHTML='
',h}function a(h){const g=document.getElementById("cards");if(!(!g||g.querySelector(".card"))){h=h||6;for(let m=0;m.4,A={};return A.hover=S?p(x,B,.35):p(x,$,.08),A["card-hover"]=p(x,A.hover,.5),A.base=p(B,x,.6),A["fg-muted"]=p(k,B,.35),A.success=I,A.error=E,A.warning=S?"#d68a00":"#f39c12",A}function n(C,B){var $=B.lightBg||B.bg&&s(B.bg)>.4,k=B.accent||B["accent-strong"]||"#888888",x=d(k);return $?":root."+C+` body { background: radial-gradient(1200px 800px at 10% -10%, rgba(`+x.r+","+x.g+","+x.b+`, .08), transparent 60%), radial-gradient(1000px 700px at 110% 10%, rgba(`+x.r+","+x.g+","+x.b+`, .05), transparent 55%), var(--bg); } -`:":root."+E+` body { +`:":root."+C+` body { background: radial-gradient(1200px 900px at 8% -12%, rgba(`+x.r+","+x.g+","+x.b+`, .10), transparent 60%), radial-gradient(1000px 700px at 110% -10%, rgba(`+x.r+","+x.g+","+x.b+`, .07), transparent 55%), var(--bg); } -`}function l(E,B){var $=B.lightBg||B.bg&&r(B.bg)>.4;return $?":root."+E+` button:hover { +`}function l(C,B){var $=B.lightBg||B.bg&&s(B.bg)>.4;return $?":root."+C+` button:hover { background: color-mix(in srgb, var(--accent-strong) 12%, white 88%); border-color: rgba(0, 0, 0, .15); box-shadow: 0 1px 6px rgba(0, 0, 0, .08), inset 0 1px 0 rgba(255, 255, 255, .8); } -`:":root."+E+` button:hover { +`:":root."+C+` button:hover { background: color-mix(in srgb, var(--accent) 18%, transparent); border-color: color-mix(in srgb, var(--accent) 35%, var(--border)); } -`}function t(){return window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}function i(){m.forEach(function(E){document.documentElement.style.removeProperty("--"+E)})}function y(E,B){var $=E.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"");$||($="custom"),h.indexOf($)!==-1&&($=$+"-custom");for(var C=safeGetJSON(a,{}),x=$,S=2;C[$]&&$!==B;)$=x+"-"+S++;return $}function u(E){var B=document.getElementById("user-theme-styles");B&&B.remove(),f.length=h.length,Object.keys(v).forEach(function(k){h.indexOf(k)===-1&&delete v[k]});var $=E||safeGetJSON(a,{}),C=Object.keys($);if(C=C.filter(function(k){return h.indexOf(k)===-1}),!!C.length){var x="";C.forEach(function(k){var I=$[k];f.indexOf(k)===-1&&f.push(k);var A={};m.forEach(function(O){I[O]&&(A[O]=I[O])}),A["card-bg"]=I["card-base"]||I.bg,I.lightBg&&(A.lightBg=!0);var D=e(A);s.forEach(function(O){!A[O]&&D[O]&&(A[O]=D[O])}),v[k]=A,x+=":root."+k+` { +`}function t(){return window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}function i(){m.forEach(function(C){document.documentElement.style.removeProperty("--"+C)})}function y(C,B){var $=C.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"");$||($="custom"),h.indexOf($)!==-1&&($=$+"-custom");for(var k=safeGetJSON(a,{}),x=$,I=2;k[$]&&$!==B;)$=x+"-"+I++;return $}function u(C){var B=document.getElementById("user-theme-styles");B&&B.remove(),g.length=h.length,Object.keys(v).forEach(function(E){h.indexOf(E)===-1&&delete v[E]});var $=C||safeGetJSON(a,{}),k=Object.keys($);if(k=k.filter(function(E){return h.indexOf(E)===-1}),!!k.length){var x="";k.forEach(function(E){var S=$[E];g.indexOf(E)===-1&&g.push(E);var A={};m.forEach(function(O){S[O]&&(A[O]=S[O])}),A["card-bg"]=S["card-base"]||S.bg,S.lightBg&&(A.lightBg=!0);var D=e(A);r.forEach(function(O){!A[O]&&D[O]&&(A[O]=D[O])}),v[E]=A,x+=":root."+E+` { `,m.forEach(function(O){A[O]&&(x+=" --"+O+": "+A[O]+`; `)}),x+=`} -`,x+=n(k,A),x+=l(k,A)});var S=document.createElement("style");S.id="user-theme-styles",S.textContent=x,document.head.appendChild(S)}}function w(){secureFetch("/api/v1/themes").then(function(E){return E.json()}).then(function(E){if(!(!E.success||!E.themes)){var B=E.themes,$=safeGetJSON(a,{});if(JSON.stringify(B)!==JSON.stringify($)){safeSet(a,JSON.stringify(B)),u(B);var C=safeGet(c);C&&f.indexOf(C)!==-1&&L(C)}}}).catch(function(){})}function T(){var E=safeGetJSON(g);if(E){var B=E.name||"Custom",$=y(B),C={name:B};m.forEach(function(k){E[k]&&(C[k]=E[k])});var x=safeGetJSON(a,{});x[$]=C,safeSet(a,JSON.stringify(x)),safeGet(c)==="custom"&&safeSet(c,$),safeRemove(g);var S={};m.forEach(function(k){C[k]&&(S[k]=C[k])}),fetch("/api/v1/themes/"+$,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:B,colors:S})}).catch(function(){})}}function L(E){document.documentElement.classList.add("theme-transitioning"),f.forEach(function(x){x!=="dark"&&document.documentElement.classList.remove(x)}),i(),E!=="dark"&&document.documentElement.classList.add(E),safeSet(c,E);var B=v[E],$=document.querySelector('meta[name="theme-color"]');$&&B&&$.setAttribute("content",B.bg);var C=B&&B.lightBg;!C&&B&&B.bg&&(C=r(B.bg)>.4),C?document.documentElement.classList.add("light-bg"):document.documentElement.classList.remove("light-bg"),setTimeout(function(){document.documentElement.classList.remove("theme-transitioning")},300)}T(),u();var P=safeGet(c);P==="red"&&(P="black",safeSet(c,"black")),P&&P!=="dark"&&f.indexOf(P)===-1&&(P=null),L(P||t()),w(),window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change",function(E){safeGet(c)||L(E.matches?"dark":"light")}),window.THEMES=f,window.BUILTIN_THEMES=h,window.THEME_COLORS=v,window.THEME_PROPS=m,window.BASE_PROPS=b,window.DERIVED_PROPS=s,window.USER_THEMES_KEY=a,window.applyTheme=L,window.clearCustomProperties=i,window.injectUserThemeStyles=u,window.syncThemesFromServer=w,window.slugifyThemeName=y,window.getActiveTheme=function(){return safeGet(c)||t()},window.deriveExtendedColors=e,window.hexToRgb=d,window.rgbToHex=o,window.blendColors=p})(),(function(){let c=null;async function a(){if(c)return c;try{const d=await fetch("/api/v1/auth/login/methods",{cache:"no-store"});if(!d.ok)throw new Error(`methods HTTP ${d.status}`);const o=await d.json();return c=Array.isArray(o.providers)?o.providers:[],c}catch(d){return console.warn("[auth-gate] methods fetch failed; falling back to TOTP-only",d),[]}}function g(d){const o=document.getElementById("totp-overlay");if(!o)return;const p=o.querySelector(".totp-card");if(!p)return;const r=p.innerHTML;p.dataset.originalBody||(p.dataset.originalBody=r);const e=d.map(n=>{const l=n.config&&(n.config.label||n.name)||n.name;return``}).join(` @@ -57,7 +57,7 @@

Choose how to sign in

${e}
- `,o.classList.add("show"),p.querySelectorAll(".provider-btn").forEach(n=>{n.addEventListener("click",()=>{const l=n.dataset.provider,t=d.find(i=>i.name===l);f(t)})})}function h(){const d=document.getElementById("totp-overlay");if(!d)return;const o=d.querySelector(".totp-card");!o||!o.dataset.originalBody||(o.innerHTML=o.dataset.originalBody,window.location.reload())}function f(d){const o=document.getElementById("totp-overlay");if(!o)return;const p=o.querySelector(".totp-card");if(p){if(d.name==="totp"){window.location.reload();return}if(d.name==="email"){p.innerHTML=` + `,o.classList.add("show"),p.querySelectorAll(".provider-btn").forEach(n=>{n.addEventListener("click",()=>{const l=n.dataset.provider,t=d.find(i=>i.name===l);g(t)})})}function h(){const d=document.getElementById("totp-overlay");if(!d)return;const o=d.querySelector(".totp-card");!o||!o.dataset.originalBody||(o.innerHTML=o.dataset.originalBody,window.location.reload())}function g(d){const o=document.getElementById("totp-overlay");if(!o)return;const p=o.querySelector(".totp-card");if(p){if(d.name==="totp"){window.location.reload();return}if(d.name==="email"){p.innerHTML=`

Sign in with email

@@ -75,13 +75,13 @@
\u2190 Back
- `,o.classList.add("show");const r=p.querySelector("#auth-gate-email-input"),e=p.querySelector("#auth-gate-email-submit"),n=p.querySelector("#auth-gate-email-status"),l=p.querySelector("#auth-gate-back");e.addEventListener("click",async()=>{const t=(r.value||"").trim();if(!t||!t.includes("@")){n.textContent="Enter a valid email address.",n.style.color="var(--error, #d33)";return}e.disabled=!0,n.textContent="Sending\u2026",n.style.color="";try{const y=await(await fetch("/api/v1/auth/login/email/initiate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:t})})).json();if(y.success){const u=y.deliveredVia||"email",w=y.maskedEmail||t;u==="dev-console"?n.innerHTML=` + `,o.classList.add("show");const s=p.querySelector("#auth-gate-email-input"),e=p.querySelector("#auth-gate-email-submit"),n=p.querySelector("#auth-gate-email-status"),l=p.querySelector("#auth-gate-back");e.addEventListener("click",async()=>{const t=(s.value||"").trim();if(!t||!t.includes("@")){n.textContent="Enter a valid email address.",n.style.color="var(--error, #d33)";return}e.disabled=!0,n.textContent="Sending\u2026",n.style.color="";try{const y=await(await fetch("/api/v1/auth/login/email/initiate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:t})})).json();if(y.success){const u=y.deliveredVia||"email",w=y.maskedEmail||t;u==="dev-console"?n.innerHTML=` Check the server logs for your one-time link. (Dev mode: no SMTP configured. In production this would email ${w}.)`:n.innerHTML=`Sign-in link sent to ${w}. - Check your inbox (and spam folder).`,n.style.color="var(--success, #2a7)"}else n.textContent=y.error||"Could not send link.",n.style.color="var(--error, #d33)",e.disabled=!1}catch{n.textContent="Connection error. Try again.",n.style.color="var(--error, #d33)",e.disabled=!1}}),r.addEventListener("keydown",t=>{t.key==="Enter"&&e.click()}),l.addEventListener("click",t=>{t.preventDefault(),g(providers)});return}console.warn("[auth-gate] unknown provider",d.name),window.location.reload()}}async function m(){if(!document.getElementById("totp-overlay"))return;const o=await a();if(o.length===0){typeof window._showTotpOverlay=="function"&&window._showTotpOverlay();return}if(o.length===1&&o[0].name==="totp"){b(o[0]);return}g(o)}function b(d){const o=c&&c.find(n=>n.name==="email");if(!o){typeof window._showTotpOverlay=="function"&&window._showTotpOverlay();return}const p=document.getElementById("totp-overlay"),r=p.querySelector(".totp-card");if(!r)return;if(r.dataset.originalBody||(r.dataset.originalBody=r.innerHTML),!r.querySelector("#auth-gate-email-alt")){const n=document.createElement("div");n.id="auth-gate-email-alt",n.style.cssText="margin-top: 18px; padding-top: 14px; border-top: 1px solid var(--border); font-size: 0.85rem;",n.innerHTML=`{t.key==="Enter"&&e.click()}),l.addEventListener("click",t=>{t.preventDefault(),f(providers)});return}console.warn("[auth-gate] unknown provider",d.name),window.location.reload()}}async function m(){if(!document.getElementById("totp-overlay"))return;const o=await a();if(o.length===0){typeof window._showTotpOverlay=="function"&&window._showTotpOverlay();return}if(o.length===1&&o[0].name==="totp"){b(o[0]);return}f(o)}function b(d){const o=c&&c.find(n=>n.name==="email");if(!o){typeof window._showTotpOverlay=="function"&&window._showTotpOverlay();return}const p=document.getElementById("totp-overlay"),s=p.querySelector(".totp-card");if(!s)return;if(s.dataset.originalBody||(s.dataset.originalBody=s.innerHTML),!s.querySelector("#auth-gate-email-alt")){const n=document.createElement("div");n.id="auth-gate-email-alt",n.style.cssText="margin-top: 18px; padding-top: 14px; border-top: 1px solid var(--border); font-size: 0.85rem;",n.innerHTML=` Or sign in with email instead \u2192 - `,r.appendChild(n),n.querySelector("#auth-gate-email-alt-link").addEventListener("click",l=>{l.preventDefault(),f(o)})}p.classList.add("show")}window.__dc_049_handled=!0;function s(d){try{const o=new URL(d,window.location.origin);if(!["http:","https:"].includes(o.protocol))return!1;if(o.origin===window.location.origin)return!0;if(o.protocol!=="https:")return!1;const p=SITE.tld.startsWith(".")?SITE.tld:`.${SITE.tld}`;return o.hostname===p.slice(1)||o.hostname.endsWith(p)}catch{return!1}}const v=new URLSearchParams(window.location.search);if(v.get("auth")==="required"){const d=v.get("return");if(d&&s(d))try{sessionStorage.setItem("totp_redirect",d)}catch{}window.history.replaceState({},"",window.location.pathname),setTimeout(m,0)}window._showAuthGate=m,window._authGateMethods=a})(),(function(){function c(){const s=document.querySelector(".totp-card");if(!s)return;const d=getComputedStyle(s).backgroundColor.match(/\d+/g);if(!d)return;const o=(.299*+d[0]+.587*+d[1]+.114*+d[2])/255,p=s.querySelector(".totp-logo-dark"),r=s.querySelector(".totp-logo-light");p&&(p.style.display=o>.5?"none":""),r&&(r.style.display=o>.5?"":"none")}function a(){const s=document.getElementById("totp-overlay");if(s){s.classList.add("show"),setTimeout(c,50);const v=s.querySelector(".totp-digits input");v&&setTimeout(()=>v.focus(),100)}typeof window._refreshRecoveryLink=="function"&&window._refreshRecoveryLink()}function g(){const s=document.getElementById("totp-overlay");s&&s.classList.remove("show")}function h(s,v){const d=new URL(s,window.location.origin);if(d.origin===window.location.origin)return d.toString();const o=SITE.tld.startsWith(".")?SITE.tld:`.${SITE.tld}`,p=d.hostname===o.slice(1)||d.hostname.endsWith(o);if(d.protocol!=="https:"||!p)return null;if(!v)return d.toString();const r=`${d.pathname}${d.search}${d.hash}`;return d.pathname="/dashcaddy-sso",d.search="",d.hash="",d.searchParams.set("token",v),d.searchParams.set("return",r),d.toString()}const f=document.getElementById("totp-digits");if(f){const s=f.querySelectorAll("input");s.forEach((v,d)=>{v.addEventListener("input",o=>{const p=o.target.value.replace(/\D/g,"");o.target.value=p.slice(0,1),p&&de.value).join("");r.length===6&&m(r)}),v.addEventListener("keydown",o=>{o.key==="Backspace"&&!o.target.value&&d>0&&(s[d-1].focus(),s[d-1].value="")}),v.addEventListener("paste",o=>{o.preventDefault();const p=(o.clipboardData.getData("text")||"").replace(/\D/g,"");p.length>=6&&(s.forEach((r,e)=>{r.value=p[e]||""}),s[5].focus(),m(p.slice(0,6)))})})}async function m(s){const v=document.getElementById("totp-error");v.textContent="Verifying...",v.className="totp-error verifying";try{const o=await(await secureFetch("/api/v1/totp/verify",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:s})})).json();if(o.success){v.textContent="",o.csrfToken&&(csrfToken=o.csrfToken),g();const p=safeSessionGet("totp_redirect");if(p){try{sessionStorage.removeItem("totp_redirect")}catch{}const r=h(p,o.ssoToken);if(!r)return;window.location.href=r;return}typeof window.initializeDashboard=="function"&&window.initializeDashboard()}else{v.textContent=o.error||"Invalid code",v.className="totp-error";const p=document.querySelectorAll("#totp-digits input");p.forEach(r=>{r.value=""}),p[0]?.focus()}}catch{v.textContent="Connection error",v.className="totp-error"}}if(!!!window.__dc_049_handled&&urlParams.get("auth")==="required"){const s=urlParams.get("return");if(s)try{const v=new URL(s,window.location.origin),d=v.hostname,o=v.origin===window.location.origin,p=SITE.tld.startsWith(".")?SITE.tld:"."+SITE.tld,r=d.endsWith(p)||d===p.substring(1);(o||r)&&safeSessionSet("totp_redirect",s)}catch{}window.history.replaceState({},"",window.location.pathname)}window._showTotpOverlay=a})(),(function(){"use strict";async function c(){try{return await(await fetch("/api/v1/totp/recovery-info",{cache:"no-store"})).json()}catch{return{success:!1,status:"unknown",hint:"Could not contact server"}}}function a(b){const s=document.getElementById("totp-recovery-link");s&&(s.style.display=b?"":"none")}function g(){const b=document.getElementById("totp-recovery-panel");b&&(b.style.display="");const s=document.getElementById("totp-recovery-status"),v=document.getElementById("totp-recovery-import"),d=document.getElementById("totp-recovery-verify");v&&(v.style.display=""),d&&(d.style.display="none"),document.getElementById("totp-recovery-error").textContent="",document.getElementById("totp-recovery-confirm-error").textContent="",document.getElementById("totp-recovery-secret").value="",document.getElementById("totp-recovery-code").value="",c().then(o=>{s.textContent=o.hint||"",o.status==="healthy"?s.style.borderColor="var(--ok-fg, #7ef2ff)":o.status==="unreadable"?(s.style.borderColor="var(--bad-fg, #ff9aa3)",s.style.background="color-mix(in srgb, var(--bad-fg) 6%, transparent)"):o.status==="not_configured"?s.style.borderColor="var(--muted)":s.style.borderColor="var(--border)"}),setTimeout(()=>{document.getElementById("totp-recovery-secret")?.focus()},100)}function h(){const b=document.getElementById("totp-recovery-panel");b&&(b.style.display="none")}async function f(){const b=document.getElementById("totp-recovery-secret").value.trim(),s=document.getElementById("totp-recovery-error");if(s.textContent="",!b){s.textContent="Paste your Base32 key first";return}if(!/^[A-Za-z2-7\s]+=*$/.test(b)){s.textContent="Invalid Base32 format \u2014 should be letters A-Z and digits 2-7 only";return}try{const v=await fetch("/api/v1/totp/setup",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({secret:b})}),d=await v.json();if(!v.ok||!d.success){s.textContent=d.error||d.message||"Restore failed";return}document.getElementById("totp-recovery-import").style.display="none",document.getElementById("totp-recovery-verify").style.display="",setTimeout(()=>document.getElementById("totp-recovery-code")?.focus(),100)}catch{s.textContent="Network error \u2014 try again"}}async function m(){const b=document.getElementById("totp-recovery-code").value.trim(),s=document.getElementById("totp-recovery-confirm-error");if(s.textContent="",!/^\d{6}$/.test(b)){s.textContent="Enter a 6-digit code";return}try{const v=await fetch("/api/v1/totp/verify-setup",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:b})}),d=await v.json();if(!v.ok||!d.success){s.textContent=d.error||d.message||"Invalid code",document.getElementById("totp-recovery-code").value="",document.getElementById("totp-recovery-code")?.focus();return}h();const o=document.getElementById("totp-overlay");o&&o.classList.remove("show"),typeof window.initializeDashboard=="function"&&window.initializeDashboard()}catch{s.textContent="Network error \u2014 try again"}}document.getElementById("totp-show-recovery")?.addEventListener("click",b=>{b.preventDefault(),g()}),document.getElementById("totp-recovery-close")?.addEventListener("click",h),document.getElementById("totp-recovery-submit")?.addEventListener("click",f),document.getElementById("totp-recovery-confirm")?.addEventListener("click",m),document.getElementById("totp-recovery-secret")?.addEventListener("keydown",b=>{b.key==="Enter"&&(b.preventDefault(),f())}),document.getElementById("totp-recovery-code")?.addEventListener("keydown",b=>{b.key==="Enter"&&(b.preventDefault(),m())}),window._refreshRecoveryLink=async function(){const b=await c();return b&&b.success&&b.status&&b.status!=="healthy"?a(!0):a(!1),b}})(),(function(){const c=new ErrorHandler;injectModal("folder-browser-modal",`
+ `,s.appendChild(n),n.querySelector("#auth-gate-email-alt-link").addEventListener("click",l=>{l.preventDefault(),g(o)})}p.classList.add("show")}window.__dc_049_handled=!0;function r(d){try{const o=new URL(d,window.location.origin);if(!["http:","https:"].includes(o.protocol))return!1;if(o.origin===window.location.origin)return!0;if(o.protocol!=="https:")return!1;const p=SITE.tld.startsWith(".")?SITE.tld:`.${SITE.tld}`;return o.hostname===p.slice(1)||o.hostname.endsWith(p)}catch{return!1}}const v=new URLSearchParams(window.location.search);if(v.get("auth")==="required"){const d=v.get("return");if(d&&r(d))try{sessionStorage.setItem("totp_redirect",d)}catch{}window.history.replaceState({},"",window.location.pathname),setTimeout(m,0)}window._showAuthGate=m,window._authGateMethods=a})(),(function(){function c(){const r=document.querySelector(".totp-card");if(!r)return;const d=getComputedStyle(r).backgroundColor.match(/\d+/g);if(!d)return;const o=(.299*+d[0]+.587*+d[1]+.114*+d[2])/255,p=r.querySelector(".totp-logo-dark"),s=r.querySelector(".totp-logo-light");p&&(p.style.display=o>.5?"none":""),s&&(s.style.display=o>.5?"":"none")}function a(){const r=document.getElementById("totp-overlay");if(r){r.classList.add("show"),setTimeout(c,50);const v=r.querySelector(".totp-digits input");v&&setTimeout(()=>v.focus(),100)}typeof window._refreshRecoveryLink=="function"&&window._refreshRecoveryLink()}function f(){const r=document.getElementById("totp-overlay");r&&r.classList.remove("show")}function h(r,v){const d=new URL(r,window.location.origin);if(d.origin===window.location.origin)return d.toString();const o=SITE.tld.startsWith(".")?SITE.tld:`.${SITE.tld}`,p=d.hostname===o.slice(1)||d.hostname.endsWith(o);if(d.protocol!=="https:"||!p)return null;if(!v)return d.toString();const s=`${d.pathname}${d.search}${d.hash}`;return d.pathname="/dashcaddy-sso",d.search="",d.hash="",d.searchParams.set("token",v),d.searchParams.set("return",s),d.toString()}const g=document.getElementById("totp-digits");if(g){const r=g.querySelectorAll("input");r.forEach((v,d)=>{v.addEventListener("input",o=>{const p=o.target.value.replace(/\D/g,"");o.target.value=p.slice(0,1),p&&de.value).join("");s.length===6&&m(s)}),v.addEventListener("keydown",o=>{o.key==="Backspace"&&!o.target.value&&d>0&&(r[d-1].focus(),r[d-1].value="")}),v.addEventListener("paste",o=>{o.preventDefault();const p=(o.clipboardData.getData("text")||"").replace(/\D/g,"");p.length>=6&&(r.forEach((s,e)=>{s.value=p[e]||""}),r[5].focus(),m(p.slice(0,6)))})})}async function m(r){const v=document.getElementById("totp-error");v.textContent="Verifying...",v.className="totp-error verifying";try{const o=await(await secureFetch("/api/v1/totp/verify",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:r})})).json();if(o.success){v.textContent="",o.csrfToken&&(csrfToken=o.csrfToken),f();const p=safeSessionGet("totp_redirect");if(p){try{sessionStorage.removeItem("totp_redirect")}catch{}const s=h(p,o.ssoToken);if(!s)return;window.location.href=s;return}typeof window.initializeDashboard=="function"&&window.initializeDashboard()}else{v.textContent=o.error||"Invalid code",v.className="totp-error";const p=document.querySelectorAll("#totp-digits input");p.forEach(s=>{s.value=""}),p[0]?.focus()}}catch{v.textContent="Connection error",v.className="totp-error"}}if(!!!window.__dc_049_handled&&urlParams.get("auth")==="required"){const r=urlParams.get("return");if(r)try{const v=new URL(r,window.location.origin),d=v.hostname,o=v.origin===window.location.origin,p=SITE.tld.startsWith(".")?SITE.tld:"."+SITE.tld,s=d.endsWith(p)||d===p.substring(1);(o||s)&&safeSessionSet("totp_redirect",r)}catch{}window.history.replaceState({},"",window.location.pathname)}window._showTotpOverlay=a})(),(function(){"use strict";async function c(){try{return await(await fetch("/api/v1/totp/recovery-info",{cache:"no-store"})).json()}catch{return{success:!1,status:"unknown",hint:"Could not contact server"}}}function a(b){const r=document.getElementById("totp-recovery-link");r&&(r.style.display=b?"":"none")}function f(){const b=document.getElementById("totp-recovery-panel");b&&(b.style.display="");const r=document.getElementById("totp-recovery-status"),v=document.getElementById("totp-recovery-import"),d=document.getElementById("totp-recovery-verify");v&&(v.style.display=""),d&&(d.style.display="none"),document.getElementById("totp-recovery-error").textContent="",document.getElementById("totp-recovery-confirm-error").textContent="",document.getElementById("totp-recovery-secret").value="",document.getElementById("totp-recovery-code").value="",c().then(o=>{r.textContent=o.hint||"",o.status==="healthy"?r.style.borderColor="var(--ok-fg, #7ef2ff)":o.status==="unreadable"?(r.style.borderColor="var(--bad-fg, #ff9aa3)",r.style.background="color-mix(in srgb, var(--bad-fg) 6%, transparent)"):o.status==="not_configured"?r.style.borderColor="var(--muted)":r.style.borderColor="var(--border)"}),setTimeout(()=>{document.getElementById("totp-recovery-secret")?.focus()},100)}function h(){const b=document.getElementById("totp-recovery-panel");b&&(b.style.display="none")}async function g(){const b=document.getElementById("totp-recovery-secret").value.trim(),r=document.getElementById("totp-recovery-error");if(r.textContent="",!b){r.textContent="Paste your Base32 key first";return}if(!/^[A-Za-z2-7\s]+=*$/.test(b)){r.textContent="Invalid Base32 format \u2014 should be letters A-Z and digits 2-7 only";return}try{const v=await fetch("/api/v1/totp/setup",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({secret:b})}),d=await v.json();if(!v.ok||!d.success){r.textContent=d.error||d.message||"Restore failed";return}document.getElementById("totp-recovery-import").style.display="none",document.getElementById("totp-recovery-verify").style.display="",setTimeout(()=>document.getElementById("totp-recovery-code")?.focus(),100)}catch{r.textContent="Network error \u2014 try again"}}async function m(){const b=document.getElementById("totp-recovery-code").value.trim(),r=document.getElementById("totp-recovery-confirm-error");if(r.textContent="",!/^\d{6}$/.test(b)){r.textContent="Enter a 6-digit code";return}try{const v=await fetch("/api/v1/totp/verify-setup",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:b})}),d=await v.json();if(!v.ok||!d.success){r.textContent=d.error||d.message||"Invalid code",document.getElementById("totp-recovery-code").value="",document.getElementById("totp-recovery-code")?.focus();return}h();const o=document.getElementById("totp-overlay");o&&o.classList.remove("show"),typeof window.initializeDashboard=="function"&&window.initializeDashboard()}catch{r.textContent="Network error \u2014 try again"}}document.getElementById("totp-show-recovery")?.addEventListener("click",b=>{b.preventDefault(),f()}),document.getElementById("totp-recovery-close")?.addEventListener("click",h),document.getElementById("totp-recovery-submit")?.addEventListener("click",g),document.getElementById("totp-recovery-confirm")?.addEventListener("click",m),document.getElementById("totp-recovery-secret")?.addEventListener("keydown",b=>{b.key==="Enter"&&(b.preventDefault(),g())}),document.getElementById("totp-recovery-code")?.addEventListener("keydown",b=>{b.key==="Enter"&&(b.preventDefault(),m())}),window._refreshRecoveryLink=async function(){const b=await c();return b&&b.success&&b.status&&b.status!=="healthy"?a(!0):a(!1),b}})(),(function(){const c=new ErrorHandler;injectModal("folder-browser-modal",`

\u{1F4C2} Browse for Media Folders

@@ -179,7 +179,7 @@
-
`);const a=document.getElementById("service-creds-modal");let g=null;const h=["sonarr","radarr","prowlarr","overseerr"],f=["sonarr","radarr"];function m(o){return o.externalUrl||o.url||""}function b(o){const p=document.getElementById("svc-creds-error");p.textContent=o,p.style.display=""}function s(){const o=document.getElementById("svc-creds-error");o.textContent="",o.style.display="none"}window.openServiceCredsModal=async function(o){g=o,s();const p=document.getElementById("svc-creds-title"),r=document.getElementById("svc-creds-desc"),e=document.getElementById("svc-creds-seedhost"),n=document.getElementById("svc-creds-apikey"),l=document.getElementById("svc-creds-basic"),t=document.getElementById("svc-creds-quality");p.textContent=o.name+" Credentials";const i=!!o.isExternal,y=h.includes(o.id)||h.includes(o.appTemplate),u=f.includes(o.id)||f.includes(o.appTemplate);e.style.display=i?"":"none",n.style.display=y?"":"none",t.style.display=u?"":"none",l.style.display=i?"none":"";const w=document.getElementById("svc-quality-select");w.innerHTML='',document.getElementById("svc-quality-status").textContent="",i?(r.textContent="Seedhost credentials auto-login past the HTTP prompt. API key bypasses the app login.",document.getElementById("svc-seedhost-pass").placeholder=`Password for ${o.name}`):y?r.textContent="API key bypasses the app login screen automatically.":r.textContent="Credentials are injected automatically when accessing this service.",await v(o),a.classList.add("show")};async function v(o){const p=document.getElementById("svc-creds-dot"),r=document.getElementById("svc-creds-status"),e=document.getElementById("svc-creds-clear");let n=!1;if(o.isExternal){try{const i=await(await fetch(`/api/v1/seedhost-creds?serviceId=${o.id}`)).json();i.success?(document.getElementById("svc-seedhost-user").value=i.username||"",i.hasCredentials&&(n=!0)):document.getElementById("svc-seedhost-user").value=""}catch{}document.getElementById("svc-seedhost-pass").value=""}try{const i=await(await fetch(`/api/v1/services/${o.id}/credentials`)).json();i.success&&(i.hasApiKey?(document.getElementById("svc-apikey-input").value="\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022",n=!0):document.getElementById("svc-apikey-input").value="",i.hasBasicAuth&&!o.isExternal?(document.getElementById("svc-basic-user").value=i.username||"",n=!0):document.getElementById("svc-basic-user").value="")}catch{}document.getElementById("svc-basic-pass")&&(document.getElementById("svc-basic-pass").value="");const l=o.id||o.appTemplate;if(f.includes(l)&&await d(o),n){p.style.background="var(--ok-fg, #74dfc4)",r.style.color="var(--ok-fg, #74dfc4)",r.textContent="Credentials stored",e.style.display="";const t=document.getElementById(`creds-btn-${o.id}`);t&&t.classList.add("has-creds")}else p.style.background="var(--muted)",r.style.color="var(--muted)",r.textContent="No credentials stored",e.style.display="none"}async function d(o){const p=document.getElementById("svc-quality-select"),r=document.getElementById("svc-quality-status"),e=o.id||o.appTemplate,n=m(o);if(!n){p.innerHTML='';return}p.innerHTML='',r.textContent="";try{const l=new URLSearchParams({service:e,url:n}),i=await(await fetch(`/api/v1/arr/quality-profiles?${l}`)).json();if(!i.success||!i.profiles?.length){p.innerHTML='';return}p.innerHTML="";for(const y of i.profiles){const u=document.createElement("option");u.value=y.id,u.textContent=y.name,p.appendChild(u)}if(i.storedProfileId&&(p.value=String(i.storedProfileId)),!p.value){const y=i.profiles.find(u=>/720/i.test(u.name));y&&(p.value=String(y.id))}!p.value&&i.profiles.length&&(p.value=String(i.profiles[0].id)),r.innerHTML=`${i.profiles.length} profiles loaded`}catch(l){p.innerHTML='',r.innerHTML=`Error: ${l.message}`}}document.getElementById("svc-quality-fetch")?.addEventListener("click",async()=>{if(!g)return;const o=g.id||g.appTemplate,p=m(g),e=document.getElementById("svc-apikey-input")?.value.trim(),n=document.getElementById("svc-quality-select"),l=document.getElementById("svc-quality-status");if(!p){l.innerHTML='No service URL available';return}if(!e||e==="\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022"){l.innerHTML='Enter an API key first';return}n.innerHTML='',l.textContent="";try{const t=new URLSearchParams({service:o,url:p,apiKey:e}),y=await(await fetch(`/api/v1/arr/quality-profiles?${t}`)).json();if(!y.success){n.innerHTML='',l.innerHTML=`${y.error||"Failed to fetch profiles"}`;return}if(!y.profiles?.length){n.innerHTML='';return}n.innerHTML="";for(const w of y.profiles){const T=document.createElement("option");T.value=w.id,T.textContent=w.name,n.appendChild(T)}const u=y.profiles.find(w=>/720/i.test(w.name));u?n.value=String(u.id):y.profiles.length&&(n.value=String(y.profiles[0].id)),l.innerHTML=`${y.profiles.length} profiles loaded`}catch(t){n.innerHTML='',l.innerHTML=`${t.message}`}}),document.getElementById("svc-creds-save")?.addEventListener("click",async()=>{if(!g)return;const o=document.getElementById("svc-creds-save");o.textContent="Saving...",o.disabled=!0,s();try{const p=h.includes(g.id)||h.includes(g.appTemplate),r=g.id||g.appTemplate;if(g.isExternal){const l=document.getElementById("svc-seedhost-user").value.trim(),t=document.getElementById("svc-seedhost-pass").value;l&&await secureFetch("/api/v1/seedhost-creds",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:l,password:t||void 0,serviceId:g.id})})}const n=document.getElementById("svc-apikey-input")?.value.trim();if(n&&n!=="\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022")if(p){const l=m(g),t=document.getElementById("svc-quality-select"),i=t?.value?parseInt(t.value):void 0,y=t?.selectedOptions?.[0]?.textContent||void 0,w=await(await secureFetch("/api/v1/arr/credentials",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({service:r,apiKey:n,url:l||void 0,qualityProfileId:i||void 0,qualityProfileName:y||void 0})})).json();if(!w.success){b(w.error||"Failed to save API key"),o.textContent="Save",o.disabled=!1;return}w.connectionTest&&!w.connectionTest.success&&b(`API key saved but connection test failed: ${w.connectionTest.error}`)}else await secureFetch(`/api/v1/services/${g.id}/credentials`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:n})});else if(p&&f.includes(r)){const l=document.getElementById("svc-quality-select"),t=l?.value?parseInt(l.value):void 0,i=l?.selectedOptions?.[0]?.textContent||void 0;t&&await secureFetch("/api/v1/arr/quality-profiles",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({service:r,qualityProfileId:t,qualityProfileName:i})})}if(!g.isExternal){const l=document.getElementById("svc-basic-user").value.trim(),t=document.getElementById("svc-basic-pass").value;l&&t&&await secureFetch(`/api/v1/services/${g.id}/credentials`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:l,password:t})})}await v(g)}catch(p){c.logError("[ServiceCredentials] Save",p,{function:"saveCredentials"}),b("Failed to save: "+(p.message||"Unknown error"))}o.textContent="Save",o.disabled=!1}),document.getElementById("svc-creds-clear")?.addEventListener("click",async()=>{if(g&&confirm(`Remove stored credentials for ${g.name}?`)){s();try{const o=g.id||g.appTemplate,p=h.includes(o);g.isExternal&&await secureFetch(`/api/v1/seedhost-creds?serviceId=${g.id}`,{method:"DELETE"}),await secureFetch(`/api/v1/services/${g.id}/credentials`,{method:"DELETE"}),p&&await secureFetch(`/api/v1/arr/credentials/${o}`,{method:"DELETE"});const r=document.getElementById(`creds-btn-${g.id}`);r&&r.classList.remove("has-creds"),await v(g)}catch(o){c.logError("[ServiceCredentials] Clear",o,{function:"clearCredentials"}),b("Failed to clear: "+(o.message||"Unknown error"))}}}),document.getElementById("svc-creds-close")?.addEventListener("click",()=>{a.classList.remove("show"),g=null}),a?.addEventListener("click",o=>{o.target===a&&(a.classList.remove("show"),g=null)}),window.refreshCredsButtons=async function(){try{for(const o of window.APPS||[]){if(!o.isExternal&&!o.appTemplate&&!o.url)continue;let p=!1;if(o.isExternal)try{const n=await(await fetch(`/api/v1/seedhost-creds?serviceId=${o.id}`)).json();n.success&&n.hasCredentials&&(p=!0)}catch{}try{const n=await(await fetch(`/api/v1/services/${o.id}/credentials`)).json();n.success&&(n.hasApiKey||n.hasBasicAuth)&&(p=!0)}catch{}const r=document.getElementById(`creds-btn-${o.id}`);r&&r.classList.toggle("has-creds",p)}}catch{}}})(),(function(){const c=new ErrorHandler;injectModal("totp-settings-modal",`
+
`);const a=document.getElementById("service-creds-modal");let f=null;const h=["sonarr","radarr","prowlarr","overseerr"],g=["sonarr","radarr"];function m(o){return o.externalUrl||o.url||""}function b(o){const p=document.getElementById("svc-creds-error");p.textContent=o,p.style.display=""}function r(){const o=document.getElementById("svc-creds-error");o.textContent="",o.style.display="none"}window.openServiceCredsModal=async function(o){f=o,r();const p=document.getElementById("svc-creds-title"),s=document.getElementById("svc-creds-desc"),e=document.getElementById("svc-creds-seedhost"),n=document.getElementById("svc-creds-apikey"),l=document.getElementById("svc-creds-basic"),t=document.getElementById("svc-creds-quality");p.textContent=o.name+" Credentials";const i=!!o.isExternal,y=h.includes(o.id)||h.includes(o.appTemplate),u=g.includes(o.id)||g.includes(o.appTemplate);e.style.display=i?"":"none",n.style.display=y?"":"none",t.style.display=u?"":"none",l.style.display=i?"none":"";const w=document.getElementById("svc-quality-select");w.innerHTML='',document.getElementById("svc-quality-status").textContent="",i?(s.textContent="Seedhost credentials auto-login past the HTTP prompt. API key bypasses the app login.",document.getElementById("svc-seedhost-pass").placeholder=`Password for ${o.name}`):y?s.textContent="API key bypasses the app login screen automatically.":s.textContent="Credentials are injected automatically when accessing this service.",await v(o),a.classList.add("show")};async function v(o){const p=document.getElementById("svc-creds-dot"),s=document.getElementById("svc-creds-status"),e=document.getElementById("svc-creds-clear");let n=!1;if(o.isExternal){try{const i=await(await fetch(`/api/v1/seedhost-creds?serviceId=${o.id}`)).json();i.success?(document.getElementById("svc-seedhost-user").value=i.username||"",i.hasCredentials&&(n=!0)):document.getElementById("svc-seedhost-user").value=""}catch{}document.getElementById("svc-seedhost-pass").value=""}try{const i=await(await fetch(`/api/v1/services/${o.id}/credentials`)).json();i.success&&(i.hasApiKey?(document.getElementById("svc-apikey-input").value="\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022",n=!0):document.getElementById("svc-apikey-input").value="",i.hasBasicAuth&&!o.isExternal?(document.getElementById("svc-basic-user").value=i.username||"",n=!0):document.getElementById("svc-basic-user").value="")}catch{}document.getElementById("svc-basic-pass")&&(document.getElementById("svc-basic-pass").value="");const l=o.id||o.appTemplate;if(g.includes(l)&&await d(o),n){p.style.background="var(--ok-fg, #74dfc4)",s.style.color="var(--ok-fg, #74dfc4)",s.textContent="Credentials stored",e.style.display="";const t=document.getElementById(`creds-btn-${o.id}`);t&&t.classList.add("has-creds")}else p.style.background="var(--muted)",s.style.color="var(--muted)",s.textContent="No credentials stored",e.style.display="none"}async function d(o){const p=document.getElementById("svc-quality-select"),s=document.getElementById("svc-quality-status"),e=o.id||o.appTemplate,n=m(o);if(!n){p.innerHTML='';return}p.innerHTML='',s.textContent="";try{const l=new URLSearchParams({service:e,url:n}),i=await(await fetch(`/api/v1/arr/quality-profiles?${l}`)).json();if(!i.success||!i.profiles?.length){p.innerHTML='';return}p.innerHTML="";for(const y of i.profiles){const u=document.createElement("option");u.value=y.id,u.textContent=y.name,p.appendChild(u)}if(i.storedProfileId&&(p.value=String(i.storedProfileId)),!p.value){const y=i.profiles.find(u=>/720/i.test(u.name));y&&(p.value=String(y.id))}!p.value&&i.profiles.length&&(p.value=String(i.profiles[0].id)),s.innerHTML=`${i.profiles.length} profiles loaded`}catch(l){p.innerHTML='',s.innerHTML=`Error: ${l.message}`}}document.getElementById("svc-quality-fetch")?.addEventListener("click",async()=>{if(!f)return;const o=f.id||f.appTemplate,p=m(f),e=document.getElementById("svc-apikey-input")?.value.trim(),n=document.getElementById("svc-quality-select"),l=document.getElementById("svc-quality-status");if(!p){l.innerHTML='No service URL available';return}if(!e||e==="\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022"){l.innerHTML='Enter an API key first';return}n.innerHTML='',l.textContent="";try{const t=new URLSearchParams({service:o,url:p,apiKey:e}),y=await(await fetch(`/api/v1/arr/quality-profiles?${t}`)).json();if(!y.success){n.innerHTML='',l.innerHTML=`${y.error||"Failed to fetch profiles"}`;return}if(!y.profiles?.length){n.innerHTML='';return}n.innerHTML="";for(const w of y.profiles){const T=document.createElement("option");T.value=w.id,T.textContent=w.name,n.appendChild(T)}const u=y.profiles.find(w=>/720/i.test(w.name));u?n.value=String(u.id):y.profiles.length&&(n.value=String(y.profiles[0].id)),l.innerHTML=`${y.profiles.length} profiles loaded`}catch(t){n.innerHTML='',l.innerHTML=`${t.message}`}}),document.getElementById("svc-creds-save")?.addEventListener("click",async()=>{if(!f)return;const o=document.getElementById("svc-creds-save");o.textContent="Saving...",o.disabled=!0,r();try{const p=h.includes(f.id)||h.includes(f.appTemplate),s=f.id||f.appTemplate;if(f.isExternal){const l=document.getElementById("svc-seedhost-user").value.trim(),t=document.getElementById("svc-seedhost-pass").value;l&&await secureFetch("/api/v1/seedhost-creds",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:l,password:t||void 0,serviceId:f.id})})}const n=document.getElementById("svc-apikey-input")?.value.trim();if(n&&n!=="\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022")if(p){const l=m(f),t=document.getElementById("svc-quality-select"),i=t?.value?parseInt(t.value):void 0,y=t?.selectedOptions?.[0]?.textContent||void 0,w=await(await secureFetch("/api/v1/arr/credentials",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({service:s,apiKey:n,url:l||void 0,qualityProfileId:i||void 0,qualityProfileName:y||void 0})})).json();if(!w.success){b(w.error||"Failed to save API key"),o.textContent="Save",o.disabled=!1;return}w.connectionTest&&!w.connectionTest.success&&b(`API key saved but connection test failed: ${w.connectionTest.error}`)}else await secureFetch(`/api/v1/services/${f.id}/credentials`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:n})});else if(p&&g.includes(s)){const l=document.getElementById("svc-quality-select"),t=l?.value?parseInt(l.value):void 0,i=l?.selectedOptions?.[0]?.textContent||void 0;t&&await secureFetch("/api/v1/arr/quality-profiles",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({service:s,qualityProfileId:t,qualityProfileName:i})})}if(!f.isExternal){const l=document.getElementById("svc-basic-user").value.trim(),t=document.getElementById("svc-basic-pass").value;l&&t&&await secureFetch(`/api/v1/services/${f.id}/credentials`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:l,password:t})})}await v(f)}catch(p){c.logError("[ServiceCredentials] Save",p,{function:"saveCredentials"}),b("Failed to save: "+(p.message||"Unknown error"))}o.textContent="Save",o.disabled=!1}),document.getElementById("svc-creds-clear")?.addEventListener("click",async()=>{if(f&&confirm(`Remove stored credentials for ${f.name}?`)){r();try{const o=f.id||f.appTemplate,p=h.includes(o);f.isExternal&&await secureFetch(`/api/v1/seedhost-creds?serviceId=${f.id}`,{method:"DELETE"}),await secureFetch(`/api/v1/services/${f.id}/credentials`,{method:"DELETE"}),p&&await secureFetch(`/api/v1/arr/credentials/${o}`,{method:"DELETE"});const s=document.getElementById(`creds-btn-${f.id}`);s&&s.classList.remove("has-creds"),await v(f)}catch(o){c.logError("[ServiceCredentials] Clear",o,{function:"clearCredentials"}),b("Failed to clear: "+(o.message||"Unknown error"))}}}),document.getElementById("svc-creds-close")?.addEventListener("click",()=>{a.classList.remove("show"),f=null}),a?.addEventListener("click",o=>{o.target===a&&(a.classList.remove("show"),f=null)}),window.refreshCredsButtons=async function(){try{for(const o of window.APPS||[]){if(!o.isExternal&&!o.appTemplate&&!o.url)continue;let p=!1;if(o.isExternal)try{const n=await(await fetch(`/api/v1/seedhost-creds?serviceId=${o.id}`)).json();n.success&&n.hasCredentials&&(p=!0)}catch{}try{const n=await(await fetch(`/api/v1/services/${o.id}/credentials`)).json();n.success&&(n.hasApiKey||n.hasBasicAuth)&&(p=!0)}catch{}const s=document.getElementById(`creds-btn-${o.id}`);s&&s.classList.toggle("has-creds",p)}}catch{}}})(),(function(){const c=new ErrorHandler;injectModal("totp-settings-modal",`

Authentication Settings

@@ -288,7 +288,7 @@
- `);async function a(){try{const m=await(await fetch("/api/v1/totp/config")).json();if(!m.success)return;const{enabled:b,sessionDuration:s,isSetUp:v}=m.config,d=document.getElementById("totp-status-dot"),o=document.getElementById("totp-status-text"),p=document.getElementById("totp-status-banner"),r=document.getElementById("totp-setup-section"),e=document.getElementById("totp-qr-section"),n=document.getElementById("totp-duration-section"),l=document.getElementById("totp-disable-section");if(b&&v){d.style.background="var(--ok-fg, #7ef2ff)",p.style.borderColor="var(--ok-fg, #7ef2ff)",p.style.background="color-mix(in srgb, var(--ok-fg) 8%, transparent)",o.textContent="TOTP is active",o.style.color="var(--ok-fg, #7ef2ff)",r.style.display="block";const t=document.getElementById("totp-setup-btn");t&&(t.textContent="Generate New Secret"),e.style.display="none",n.style.display="block",l.style.display="block",document.getElementById("totp-duration-select").value=s}else d.style.background="var(--muted)",p.style.borderColor="var(--border)",p.style.background="transparent",o.textContent="TOTP is not configured",o.style.color="var(--muted)",r.style.display="block",e.style.display="none",n.style.display="none",l.style.display="none";h(b&&v,s)}catch(f){console.warn("Failed to load TOTP settings:",f)}}const g={"15m":"15 min","30m":"30 min","1h":"1 hour","2h":"2 hours","4h":"4 hours","8h":"8 hours","12h":"12 hours","24h":"24 hours",never:"Disabled"};function h(f,m){const b=document.getElementById("auth-card"),s=document.getElementById("auth-pill"),v=document.getElementById("auth-dot"),d=document.getElementById("auth-status-text");b&&(f?(b.setAttribute("data-status","on"),s.className="badge on",s.textContent="YES",v.className="dot ok at-bl",d.textContent="Session: "+(g[m]||m)):(b.setAttribute("data-status","off"),s.className="badge off",s.textContent="NO",v.className="dot bad at-bl",d.textContent="Not configured"))}document.getElementById("totp-setup-btn")?.addEventListener("click",async()=>{try{const m=await(await secureFetch("/api/v1/totp/setup",{method:"POST"})).json();m.success&&(document.getElementById("totp-qr-image").src=m.qrCode,document.getElementById("totp-manual-key").textContent=m.manualKey,document.getElementById("totp-setup-section").style.display="none",document.getElementById("totp-qr-section").style.display="block",document.getElementById("totp-setup-code").value="",document.getElementById("totp-setup-error").textContent="",document.getElementById("totp-setup-code").focus())}catch(f){c.logError("[TOTP] Setup Failed",f,{function:"setupTOTP"})}}),document.getElementById("totp-import-btn")?.addEventListener("click",async()=>{const f=document.getElementById("totp-import-key").value.trim(),m=document.getElementById("totp-import-error");if(m.textContent="",!f){m.textContent="Paste a Base32 secret key first";return}try{const s=await(await secureFetch("/api/v1/totp/setup",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({secret:f})})).json();s.success?(m.textContent="",document.getElementById("totp-qr-image").src=s.qrCode,document.getElementById("totp-manual-key").textContent=s.manualKey,document.getElementById("totp-setup-section").style.display="none",document.getElementById("totp-qr-section").style.display="block",document.getElementById("totp-setup-code").value="",document.getElementById("totp-setup-error").textContent="",document.getElementById("totp-setup-code").focus()):m.textContent=s.error||s.message||"Import failed"}catch{m.textContent="Connection error \u2014 try refreshing the page"}}),document.getElementById("totp-copy-key")?.addEventListener("click",()=>{const f=document.getElementById("totp-manual-key").textContent;navigator.clipboard.writeText(f).then(()=>{const m=document.getElementById("totp-copy-key");m.textContent="\u2705",setTimeout(()=>{m.textContent="\u{1F4CB}"},2e3)})}),document.getElementById("totp-download-backup")?.addEventListener("click",()=>{const f=document.getElementById("totp-manual-key").textContent.trim();if(!f)return;const m={service:"DashCaddy",type:"totp-secret",secret:f,issuer:"DashCaddy",algorithm:"SHA1",digits:6,period:30,issued:new Date().toISOString(),recovery_url:`${window.location.origin}/ (login screen \u2192 "Lost access?")`,note:'Keep this file somewhere safe. Anyone with this secret can generate your login codes. Use it ONLY to recover TOTP access via the "Lost access?" link on the DashCaddy login screen.'},b=new Blob([JSON.stringify(m,null,2)],{type:"application/json"}),s=URL.createObjectURL(b),v=document.createElement("a");v.href=s,v.download=`dashcaddy-totp-backup-${new Date().toISOString().slice(0,10)}.json`,document.body.appendChild(v),v.click(),document.body.removeChild(v),URL.revokeObjectURL(s);const d=document.getElementById("totp-download-backup");d.textContent="\u2705 Saved",setTimeout(()=>{d.textContent="\u2B07 Download"},2e3)}),document.getElementById("totp-confirm-setup")?.addEventListener("click",async()=>{const f=document.getElementById("totp-setup-code").value,m=document.getElementById("totp-setup-error");if(!/^\d{6}$/.test(f)){m.textContent="Enter a 6-digit code";return}try{const s=await(await secureFetch("/api/v1/totp/verify-setup",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:f})})).json();s.success?(m.textContent="",a()):m.textContent=s.error||"Invalid code"}catch{m.textContent="Connection error"}}),document.getElementById("totp-setup-code")?.addEventListener("keydown",f=>{f.key==="Enter"&&document.getElementById("totp-confirm-setup")?.click()}),document.getElementById("totp-duration-select")?.addEventListener("change",async f=>{try{await secureFetch("/api/v1/totp/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionDuration:f.target.value})}),a()}catch(m){c.logError("[TOTP] Update Session Duration",m,{function:"updateSessionDuration"})}}),document.getElementById("totp-disable-btn")?.addEventListener("click",async()=>{if(confirm("Disable TOTP authentication? All services will be accessible without a code."))try{(await(await secureFetch("/api/v1/totp/disable",{method:"POST",headers:{"Content-Type":"application/json"},body:"{}"})).json()).success&&a()}catch(f){c.logError("[TOTP] Disable Failed",f,{function:"disableTOTP"})}}),document.getElementById("auth-settings-btn")?.addEventListener("click",()=>{a(),openModal("totp-settings-modal")}),document.getElementById("totp-modal-close")?.addEventListener("click",()=>{closeModal("totp-settings-modal")}),document.getElementById("totp-settings-modal")?.addEventListener("click",f=>{f.target.id==="totp-settings-modal"&&closeModal("totp-settings-modal")}),window._updateAuthCard=h,(async()=>{try{const m=await(await fetch("/api/v1/totp/config")).json();if(m.success){const b=m.config.enabled&&m.config.isSetUp;h(b,m.config.sessionDuration)}}catch(f){c.logError("[TOTP] AuthCard Update",f,{function:"authCardUpdate"})}})()})(),(function(){"use strict";const c={me:"/api/v1/auth/me",users:"/api/v1/auth/admin/users",allowlist:"/api/v1/auth/admin/allowlist",invites:"/api/v1/auth/admin/invites"};function a(r,e,...n){const l=document.createElement(r);if(e)for(const t of Object.keys(e)){const i=e[t];i==null||i===!1||(t==="class"?l.className=i:t==="text"?l.textContent=i:t==="html"?l.innerHTML=i:t.startsWith("on")&&typeof i=="function"?l.addEventListener(t.slice(2).toLowerCase(),i):l.setAttribute(t,i))}for(const t of n)t==null||t===!1||(typeof t=="string"?l.appendChild(document.createTextNode(t)):l.appendChild(t));return l}async function g(r,e){const n=window.SITE&&window.SITE.csrfToken||"";e=e||{},e.headers=Object.assign({"Content-Type":"application/json"},e.headers||{},n?{"X-CSRF-Token":n}:{}),e.body&&typeof e.body!="string"&&(e.body=JSON.stringify(e.body));const l=await fetch(r,e),t=await l.json().catch(()=>({}));if(!l.ok){const i=t&&(t.message||t.error)||"HTTP "+l.status,y=new Error(i);throw y.status=l.status,y}return t}function h(r){const e={admin:"background:#7c3aed;color:#fff",operator:"background:#2563eb;color:#fff",viewer:"background:#6b7280;color:#fff"};return a("span",{class:"role-badge",style:"display:inline-block;padding:2px 8px;border-radius:4px;font-size:0.75rem;font-weight:600;text-transform:uppercase;"+(e[r]||e.viewer),text:r})}function f(r,e,n){if(r.innerHTML="",!e||e.length===0){r.appendChild(a("p",{style:"color:var(--muted)",text:"No users yet."}));return}const l=a("table",{style:"width:100%;border-collapse:collapse;font-size:0.9rem"});l.appendChild(a("thead",null,a("tr",{style:"border-bottom:1px solid var(--border)"},a("th",{style:"text-align:left;padding:8px",text:"Email"}),a("th",{style:"text-align:left;padding:8px",text:"Role"}),a("th",{style:"text-align:left;padding:8px",text:"Created"}),a("th",{style:"text-align:left;padding:8px",text:"Last login"}),a("th",{style:"text-align:right;padding:8px",text:"Actions"}))));const t=a("tbody");for(const i of e){const y=a("tr",{style:"border-bottom:1px solid var(--border)"}),u=a("td",{style:"padding:8px"});u.appendChild(a("span",{text:i.email||"(no email)"})),i.displayName&&i.displayName!==(i.email||"").split("@")[0]&&(u.appendChild(a("br")),u.appendChild(a("small",{style:"color:var(--muted)",text:i.displayName}))),y.appendChild(u);const w=a("td",{style:"padding:8px"});w.appendChild(h(i.role)),y.appendChild(w),y.appendChild(a("td",{style:"padding:8px;color:var(--muted);font-size:0.85rem",text:i.createdAt?new Date(i.createdAt).toLocaleDateString():"\u2014"})),y.appendChild(a("td",{style:"padding:8px;color:var(--muted);font-size:0.85rem",text:i.lastLoginAt?new Date(i.lastLoginAt).toLocaleString():"\u2014"}));const T=a("td",{style:"padding:8px;text-align:right"}),L=a("select",{style:"padding:2px 6px;margin-right:6px",onchange:async E=>{try{await g(c.users+"/"+encodeURIComponent(i.id),{method:"PATCH",body:{role:E.target.value}}),n&&n()}catch(B){window.errorHandler&&window.errorHandler.show("Role update failed: "+B.message),E.target.value=i.role}}});for(const E of["admin","operator","viewer"]){const B=a("option",{value:E,text:E});E===i.role&&(B.selected=!0),L.appendChild(B)}T.appendChild(L);const P=a("button",{class:"btn-sm",style:"padding:2px 8px",text:"Delete",onclick:async()=>{if(confirm("Delete user "+(i.email||i.id)+"? This cannot be undone."))try{await g(c.users+"/"+encodeURIComponent(i.id),{method:"DELETE"}),n&&n()}catch(E){window.errorHandler&&window.errorHandler.show("Delete failed: "+E.message)}}});T.appendChild(P),y.appendChild(T),t.appendChild(y)}l.appendChild(t),r.appendChild(l)}function m(r,e){const n=a("form",{style:"display:flex;gap:8px;flex-wrap:wrap;align-items:end",onsubmit:async t=>{t.preventDefault();const i=new FormData(t.target),y={email:i.get("email"),role:i.get("role"),ttlHours:parseInt(i.get("ttlHours"),10)||24,sendEmail:i.get("sendEmail")==="on"};try{const u=await g(c.invites,{method:"POST",body:y});t.target.reset(),e&&e(u)}catch(u){window.errorHandler&&window.errorHandler.show("Invite failed: "+u.message)}}});n.appendChild(a("label",{style:"display:flex;flex-direction:column;gap:2px;font-size:0.85rem"},a("span",{text:"Email"}),a("input",{name:"email",type:"email",required:!0,placeholder:"user@example.com",style:"padding:6px"})));const l=a("select",{name:"role",style:"padding:6px"});for(const t of["operator","viewer","admin"])l.appendChild(a("option",{value:t,text:t}));n.appendChild(a("label",{style:"display:flex;flex-direction:column;gap:2px;font-size:0.85rem"},a("span",{text:"Role"}),l)),n.appendChild(a("label",{style:"display:flex;flex-direction:column;gap:2px;font-size:0.85rem"},a("span",{text:"TTL (hours)"}),a("input",{name:"ttlHours",type:"number",min:"1",max:"168",value:"24",style:"padding:6px;width:80px"}))),n.appendChild(a("label",{style:"display:flex;gap:4px;align-items:center;font-size:0.85rem"},a("input",{name:"sendEmail",type:"checkbox",checked:!0}),a("span",{text:"Send email"}))),n.appendChild(a("button",{type:"submit",class:"btn-sm",style:"padding:6px 12px",text:"Issue invite"})),r.appendChild(n)}function b(r,e,n){if(r.innerHTML="",!e||e.length===0){r.appendChild(a("p",{style:"color:var(--muted)",text:"No outstanding invites."}));return}const l=a("table",{style:"width:100%;border-collapse:collapse;font-size:0.9rem"});l.appendChild(a("thead",null,a("tr",{style:"border-bottom:1px solid var(--border)"},a("th",{style:"text-align:left;padding:8px",text:"Email"}),a("th",{style:"text-align:left;padding:8px",text:"Role"}),a("th",{style:"text-align:left;padding:8px",text:"Invited by"}),a("th",{style:"text-align:left;padding:8px",text:"Expires"}),a("th",{style:"text-align:right;padding:8px",text:"Actions"}))));const t=a("tbody");for(const i of e){const y=a("tr",{style:"border-bottom:1px solid var(--border)"});y.appendChild(a("td",{style:"padding:8px",text:i.email})),y.appendChild(a("td",{style:"padding:8px"},h(i.role))),y.appendChild(a("td",{style:"padding:8px;color:var(--muted)",text:i.invitedBy||"\u2014"})),y.appendChild(a("td",{style:"padding:8px;color:var(--muted);font-size:0.85rem",text:i.expiresAt?new Date(i.expiresAt).toLocaleString():"\u2014"}));const u=a("td",{style:"padding:8px;text-align:right"});u.appendChild(a("button",{class:"btn-sm",style:"padding:2px 8px",text:"Revoke",onclick:async()=>{if(confirm("Revoke invite for "+i.email+"?"))try{await g(c.invites+"/"+encodeURIComponent(i.id),{method:"DELETE"}),n&&n()}catch(w){window.errorHandler&&window.errorHandler.show("Revoke failed: "+w.message)}}})),y.appendChild(u),t.appendChild(y)}l.appendChild(t),r.appendChild(l)}function s(r,e){const n=a("div",{style:"margin-top:12px;padding:12px;border:1px solid #16a34a;border-radius:6px;background:#052e1a;color:#bbf7d0;font-size:0.85rem"});n.appendChild(a("strong",{text:"Invite issued \u2014 copy the link below. It will not be shown again."})),n.appendChild(a("br")),n.appendChild(a("code",{style:"display:block;margin-top:8px;padding:8px;background:#000;border-radius:4px;word-break:break-all;color:#d1fae5",text:r.acceptUrl}));const l=a("button",{class:"btn-sm",style:"margin-top:8px;padding:4px 10px",text:"Copy link",onclick:async()=>{try{await navigator.clipboard.writeText(r.acceptUrl),l.textContent="Copied!",setTimeout(()=>{l.textContent="Copy link"},2e3)}catch{window.errorHandler&&window.errorHandler.show("Clipboard blocked: select the link manually.")}}});n.appendChild(l),r.deliveredVia==="dev-console"?n.appendChild(a("p",{style:"margin-top:8px;color:#fbbf24;font-size:0.8rem",text:"SMTP not configured \u2014 the invite was logged to the server console (search for [DC-048-DEV-INVITE-LINK])."})):r.deliveredVia==="email"&&n.appendChild(a("p",{style:"margin-top:8px;color:#86efac;font-size:0.8rem",text:"Email sent to "+r.email+"."})),e.appendChild(n)}async function v(r){r.innerHTML="",r.appendChild(a("h2",{style:"margin:0 0 16px",text:"Admin \xB7 Users & Invites"}));const e=await g(c.me).catch(()=>({}));if(!e||!e.user||e.user.role!=="admin"){r.appendChild(a("p",{style:"color:var(--muted)",text:"Admin role required to view this panel. If multi-user mode is enabled and you should have access, check /api/v1/auth/me."}));return}const n=a("button",{class:"btn-sm",style:"float:right;padding:4px 10px",text:"Refresh",onclick:()=>v(r)});r.appendChild(n);const l=a("h3",{style:"margin:24px 0 8px;clear:both",text:"Users"});r.appendChild(l);const t=a("div",{id:"admin-users-list"});r.appendChild(t);const i=await g(c.users).catch(()=>({users:[]}));f(t,i.users,()=>v(r)),r.appendChild(a("h4",{style:"margin:24px 0 8px;font-size:0.95rem",text:"Pre-authorize email"}));const y=a("form",{style:"display:flex;gap:8px;align-items:end",onsubmit:async L=>{L.preventDefault();const P=L.target.email.value.trim();if(P)try{await g(c.users,{method:"POST",body:{email:P}}),L.target.reset(),v(r)}catch(E){window.errorHandler&&window.errorHandler.show("Add failed: "+E.message)}}});y.appendChild(a("input",{name:"email",type:"email",required:!0,placeholder:"user@example.com",style:"padding:6px"})),y.appendChild(a("button",{type:"submit",class:"btn-sm",style:"padding:6px 12px",text:"Add to allowlist"})),r.appendChild(y),r.appendChild(a("h3",{style:"margin:24px 0 8px",text:"Issue invite"}));const u=a("div");r.appendChild(u);const w=a("div",{id:"admin-invites-list",style:"margin-top:16px"});r.appendChild(w);const T=await g(c.invites).catch(()=>({invites:[]}));b(w,T.invites,()=>v(r)),m(u,L=>{s(L,u),v(r)})}async function d(){if(document.getElementById("admin-panel-root"))return;const e=a("div",{id:"admin-panel-root",style:"position:fixed;inset:0;background:rgba(0,0,0,0.5);z-index:1000;display:flex;align-items:center;justify-content:center;",onclick:t=>{t.target===e&&o()}}),n=a("div",{style:"background:var(--card-base,#1f2937);color:var(--text,#f3f4f6);border-radius:8px;padding:24px;max-width:900px;width:90%;max-height:85vh;overflow:auto;position:relative;box-shadow:0 10px 30px rgba(0,0,0,0.3)"});n.appendChild(a("button",{class:"btn-sm",style:"position:absolute;top:12px;right:12px;padding:4px 10px",text:"Close",onclick:o}));const l=a("div",{id:"admin-panel-body"});n.appendChild(l),e.appendChild(n),document.body.appendChild(e);try{await v(l)}catch(t){l.innerHTML='

Failed to load admin panel: '+(t.message||t)+"

"}}function o(){const r=document.getElementById("admin-panel-root");r&&r.remove()}async function p(r){async function e(){const n=await g(c.me).catch(()=>({})),l=document.getElementById("admin-trigger-btn");if(n&&n.user&&n.user.role==="admin"){if(l)return;const t=a("button",{id:"admin-trigger-btn",class:"btn-sm",style:"margin-left:8px;padding:6px 12px",text:"Admin",onclick:d});r?r.appendChild(t):document.body&&document.body.appendChild(t)}else l&&l.remove()}await e(),setInterval(e,6e4)}window.AdminPanel={open:d,close:o,attachTrigger:p}})(),(function(){injectModal("token-management-modal",` + `);async function a(){try{const m=await(await fetch("/api/v1/totp/config")).json();if(!m.success)return;const{enabled:b,sessionDuration:r,isSetUp:v}=m.config,d=document.getElementById("totp-status-dot"),o=document.getElementById("totp-status-text"),p=document.getElementById("totp-status-banner"),s=document.getElementById("totp-setup-section"),e=document.getElementById("totp-qr-section"),n=document.getElementById("totp-duration-section"),l=document.getElementById("totp-disable-section");if(b&&v){d.style.background="var(--ok-fg, #7ef2ff)",p.style.borderColor="var(--ok-fg, #7ef2ff)",p.style.background="color-mix(in srgb, var(--ok-fg) 8%, transparent)",o.textContent="TOTP is active",o.style.color="var(--ok-fg, #7ef2ff)",s.style.display="block";const t=document.getElementById("totp-setup-btn");t&&(t.textContent="Generate New Secret"),e.style.display="none",n.style.display="block",l.style.display="block",document.getElementById("totp-duration-select").value=r}else d.style.background="var(--muted)",p.style.borderColor="var(--border)",p.style.background="transparent",o.textContent="TOTP is not configured",o.style.color="var(--muted)",s.style.display="block",e.style.display="none",n.style.display="none",l.style.display="none";h(b&&v,r)}catch(g){console.warn("Failed to load TOTP settings:",g)}}const f={"15m":"15 min","30m":"30 min","1h":"1 hour","2h":"2 hours","4h":"4 hours","8h":"8 hours","12h":"12 hours","24h":"24 hours",never:"Disabled"};function h(g,m){const b=document.getElementById("auth-card"),r=document.getElementById("auth-pill"),v=document.getElementById("auth-dot"),d=document.getElementById("auth-status-text");b&&(g?(b.setAttribute("data-status","on"),r.className="badge on",r.textContent="YES",v.className="dot ok at-bl",d.textContent="Session: "+(f[m]||m)):(b.setAttribute("data-status","off"),r.className="badge off",r.textContent="NO",v.className="dot bad at-bl",d.textContent="Not configured"))}document.getElementById("totp-setup-btn")?.addEventListener("click",async()=>{try{const m=await(await secureFetch("/api/v1/totp/setup",{method:"POST"})).json();m.success&&(document.getElementById("totp-qr-image").src=m.qrCode,document.getElementById("totp-manual-key").textContent=m.manualKey,document.getElementById("totp-setup-section").style.display="none",document.getElementById("totp-qr-section").style.display="block",document.getElementById("totp-setup-code").value="",document.getElementById("totp-setup-error").textContent="",document.getElementById("totp-setup-code").focus())}catch(g){c.logError("[TOTP] Setup Failed",g,{function:"setupTOTP"})}}),document.getElementById("totp-import-btn")?.addEventListener("click",async()=>{const g=document.getElementById("totp-import-key").value.trim(),m=document.getElementById("totp-import-error");if(m.textContent="",!g){m.textContent="Paste a Base32 secret key first";return}try{const r=await(await secureFetch("/api/v1/totp/setup",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({secret:g})})).json();r.success?(m.textContent="",document.getElementById("totp-qr-image").src=r.qrCode,document.getElementById("totp-manual-key").textContent=r.manualKey,document.getElementById("totp-setup-section").style.display="none",document.getElementById("totp-qr-section").style.display="block",document.getElementById("totp-setup-code").value="",document.getElementById("totp-setup-error").textContent="",document.getElementById("totp-setup-code").focus()):m.textContent=r.error||r.message||"Import failed"}catch{m.textContent="Connection error \u2014 try refreshing the page"}}),document.getElementById("totp-copy-key")?.addEventListener("click",()=>{const g=document.getElementById("totp-manual-key").textContent;navigator.clipboard.writeText(g).then(()=>{const m=document.getElementById("totp-copy-key");m.textContent="\u2705",setTimeout(()=>{m.textContent="\u{1F4CB}"},2e3)})}),document.getElementById("totp-download-backup")?.addEventListener("click",()=>{const g=document.getElementById("totp-manual-key").textContent.trim();if(!g)return;const m={service:"DashCaddy",type:"totp-secret",secret:g,issuer:"DashCaddy",algorithm:"SHA1",digits:6,period:30,issued:new Date().toISOString(),recovery_url:`${window.location.origin}/ (login screen \u2192 "Lost access?")`,note:'Keep this file somewhere safe. Anyone with this secret can generate your login codes. Use it ONLY to recover TOTP access via the "Lost access?" link on the DashCaddy login screen.'},b=new Blob([JSON.stringify(m,null,2)],{type:"application/json"}),r=URL.createObjectURL(b),v=document.createElement("a");v.href=r,v.download=`dashcaddy-totp-backup-${new Date().toISOString().slice(0,10)}.json`,document.body.appendChild(v),v.click(),document.body.removeChild(v),URL.revokeObjectURL(r);const d=document.getElementById("totp-download-backup");d.textContent="\u2705 Saved",setTimeout(()=>{d.textContent="\u2B07 Download"},2e3)}),document.getElementById("totp-confirm-setup")?.addEventListener("click",async()=>{const g=document.getElementById("totp-setup-code").value,m=document.getElementById("totp-setup-error");if(!/^\d{6}$/.test(g)){m.textContent="Enter a 6-digit code";return}try{const r=await(await secureFetch("/api/v1/totp/verify-setup",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:g})})).json();r.success?(m.textContent="",a()):m.textContent=r.error||"Invalid code"}catch{m.textContent="Connection error"}}),document.getElementById("totp-setup-code")?.addEventListener("keydown",g=>{g.key==="Enter"&&document.getElementById("totp-confirm-setup")?.click()}),document.getElementById("totp-duration-select")?.addEventListener("change",async g=>{try{await secureFetch("/api/v1/totp/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionDuration:g.target.value})}),a()}catch(m){c.logError("[TOTP] Update Session Duration",m,{function:"updateSessionDuration"})}}),document.getElementById("totp-disable-btn")?.addEventListener("click",async()=>{if(confirm("Disable TOTP authentication? All services will be accessible without a code."))try{(await(await secureFetch("/api/v1/totp/disable",{method:"POST",headers:{"Content-Type":"application/json"},body:"{}"})).json()).success&&a()}catch(g){c.logError("[TOTP] Disable Failed",g,{function:"disableTOTP"})}}),document.getElementById("auth-settings-btn")?.addEventListener("click",()=>{a(),openModal("totp-settings-modal")}),document.getElementById("totp-modal-close")?.addEventListener("click",()=>{closeModal("totp-settings-modal")}),document.getElementById("totp-settings-modal")?.addEventListener("click",g=>{g.target.id==="totp-settings-modal"&&closeModal("totp-settings-modal")}),window._updateAuthCard=h,(async()=>{try{const m=await(await fetch("/api/v1/totp/config")).json();if(m.success){const b=m.config.enabled&&m.config.isSetUp;h(b,m.config.sessionDuration)}}catch(g){c.logError("[TOTP] AuthCard Update",g,{function:"authCardUpdate"})}})()})(),(function(){"use strict";const c={me:"/api/v1/auth/me",users:"/api/v1/auth/admin/users",allowlist:"/api/v1/auth/admin/allowlist",invites:"/api/v1/auth/admin/invites"};function a(s,e,...n){const l=document.createElement(s);if(e)for(const t of Object.keys(e)){const i=e[t];i==null||i===!1||(t==="class"?l.className=i:t==="text"?l.textContent=i:t==="html"?l.innerHTML=i:t.startsWith("on")&&typeof i=="function"?l.addEventListener(t.slice(2).toLowerCase(),i):l.setAttribute(t,i))}for(const t of n)t==null||t===!1||(typeof t=="string"?l.appendChild(document.createTextNode(t)):l.appendChild(t));return l}async function f(s,e){const n=window.SITE&&window.SITE.csrfToken||"";e=e||{},e.headers=Object.assign({"Content-Type":"application/json"},e.headers||{},n?{"X-CSRF-Token":n}:{}),e.body&&typeof e.body!="string"&&(e.body=JSON.stringify(e.body));const l=await fetch(s,e),t=await l.json().catch(()=>({}));if(!l.ok){const i=t&&(t.message||t.error)||"HTTP "+l.status,y=new Error(i);throw y.status=l.status,y}return t}function h(s){const e={admin:"background:#7c3aed;color:#fff",operator:"background:#2563eb;color:#fff",viewer:"background:#6b7280;color:#fff"};return a("span",{class:"role-badge",style:"display:inline-block;padding:2px 8px;border-radius:4px;font-size:0.75rem;font-weight:600;text-transform:uppercase;"+(e[s]||e.viewer),text:s})}function g(s,e,n){if(s.innerHTML="",!e||e.length===0){s.appendChild(a("p",{style:"color:var(--muted)",text:"No users yet."}));return}const l=a("table",{style:"width:100%;border-collapse:collapse;font-size:0.9rem"});l.appendChild(a("thead",null,a("tr",{style:"border-bottom:1px solid var(--border)"},a("th",{style:"text-align:left;padding:8px",text:"Email"}),a("th",{style:"text-align:left;padding:8px",text:"Role"}),a("th",{style:"text-align:left;padding:8px",text:"Created"}),a("th",{style:"text-align:left;padding:8px",text:"Last login"}),a("th",{style:"text-align:right;padding:8px",text:"Actions"}))));const t=a("tbody");for(const i of e){const y=a("tr",{style:"border-bottom:1px solid var(--border)"}),u=a("td",{style:"padding:8px"});u.appendChild(a("span",{text:i.email||"(no email)"})),i.displayName&&i.displayName!==(i.email||"").split("@")[0]&&(u.appendChild(a("br")),u.appendChild(a("small",{style:"color:var(--muted)",text:i.displayName}))),y.appendChild(u);const w=a("td",{style:"padding:8px"});w.appendChild(h(i.role)),y.appendChild(w),y.appendChild(a("td",{style:"padding:8px;color:var(--muted);font-size:0.85rem",text:i.createdAt?new Date(i.createdAt).toLocaleDateString():"\u2014"})),y.appendChild(a("td",{style:"padding:8px;color:var(--muted);font-size:0.85rem",text:i.lastLoginAt?new Date(i.lastLoginAt).toLocaleString():"\u2014"}));const T=a("td",{style:"padding:8px;text-align:right"}),L=a("select",{style:"padding:2px 6px;margin-right:6px",onchange:async C=>{try{await f(c.users+"/"+encodeURIComponent(i.id),{method:"PATCH",body:{role:C.target.value}}),n&&n()}catch(B){window.errorHandler&&window.errorHandler.show("Role update failed: "+B.message),C.target.value=i.role}}});for(const C of["admin","operator","viewer"]){const B=a("option",{value:C,text:C});C===i.role&&(B.selected=!0),L.appendChild(B)}T.appendChild(L);const P=a("button",{class:"btn-sm",style:"padding:2px 8px",text:"Delete",onclick:async()=>{if(confirm("Delete user "+(i.email||i.id)+"? This cannot be undone."))try{await f(c.users+"/"+encodeURIComponent(i.id),{method:"DELETE"}),n&&n()}catch(C){window.errorHandler&&window.errorHandler.show("Delete failed: "+C.message)}}});T.appendChild(P),y.appendChild(T),t.appendChild(y)}l.appendChild(t),s.appendChild(l)}function m(s,e){const n=a("form",{style:"display:flex;gap:8px;flex-wrap:wrap;align-items:end",onsubmit:async t=>{t.preventDefault();const i=new FormData(t.target),y={email:i.get("email"),role:i.get("role"),ttlHours:parseInt(i.get("ttlHours"),10)||24,sendEmail:i.get("sendEmail")==="on"};try{const u=await f(c.invites,{method:"POST",body:y});t.target.reset(),e&&e(u)}catch(u){window.errorHandler&&window.errorHandler.show("Invite failed: "+u.message)}}});n.appendChild(a("label",{style:"display:flex;flex-direction:column;gap:2px;font-size:0.85rem"},a("span",{text:"Email"}),a("input",{name:"email",type:"email",required:!0,placeholder:"user@example.com",style:"padding:6px"})));const l=a("select",{name:"role",style:"padding:6px"});for(const t of["operator","viewer","admin"])l.appendChild(a("option",{value:t,text:t}));n.appendChild(a("label",{style:"display:flex;flex-direction:column;gap:2px;font-size:0.85rem"},a("span",{text:"Role"}),l)),n.appendChild(a("label",{style:"display:flex;flex-direction:column;gap:2px;font-size:0.85rem"},a("span",{text:"TTL (hours)"}),a("input",{name:"ttlHours",type:"number",min:"1",max:"168",value:"24",style:"padding:6px;width:80px"}))),n.appendChild(a("label",{style:"display:flex;gap:4px;align-items:center;font-size:0.85rem"},a("input",{name:"sendEmail",type:"checkbox",checked:!0}),a("span",{text:"Send email"}))),n.appendChild(a("button",{type:"submit",class:"btn-sm",style:"padding:6px 12px",text:"Issue invite"})),s.appendChild(n)}function b(s,e,n){if(s.innerHTML="",!e||e.length===0){s.appendChild(a("p",{style:"color:var(--muted)",text:"No outstanding invites."}));return}const l=a("table",{style:"width:100%;border-collapse:collapse;font-size:0.9rem"});l.appendChild(a("thead",null,a("tr",{style:"border-bottom:1px solid var(--border)"},a("th",{style:"text-align:left;padding:8px",text:"Email"}),a("th",{style:"text-align:left;padding:8px",text:"Role"}),a("th",{style:"text-align:left;padding:8px",text:"Invited by"}),a("th",{style:"text-align:left;padding:8px",text:"Expires"}),a("th",{style:"text-align:right;padding:8px",text:"Actions"}))));const t=a("tbody");for(const i of e){const y=a("tr",{style:"border-bottom:1px solid var(--border)"});y.appendChild(a("td",{style:"padding:8px",text:i.email})),y.appendChild(a("td",{style:"padding:8px"},h(i.role))),y.appendChild(a("td",{style:"padding:8px;color:var(--muted)",text:i.invitedBy||"\u2014"})),y.appendChild(a("td",{style:"padding:8px;color:var(--muted);font-size:0.85rem",text:i.expiresAt?new Date(i.expiresAt).toLocaleString():"\u2014"}));const u=a("td",{style:"padding:8px;text-align:right"});u.appendChild(a("button",{class:"btn-sm",style:"padding:2px 8px",text:"Revoke",onclick:async()=>{if(confirm("Revoke invite for "+i.email+"?"))try{await f(c.invites+"/"+encodeURIComponent(i.id),{method:"DELETE"}),n&&n()}catch(w){window.errorHandler&&window.errorHandler.show("Revoke failed: "+w.message)}}})),y.appendChild(u),t.appendChild(y)}l.appendChild(t),s.appendChild(l)}function r(s,e){const n=a("div",{style:"margin-top:12px;padding:12px;border:1px solid #16a34a;border-radius:6px;background:#052e1a;color:#bbf7d0;font-size:0.85rem"});n.appendChild(a("strong",{text:"Invite issued \u2014 copy the link below. It will not be shown again."})),n.appendChild(a("br")),n.appendChild(a("code",{style:"display:block;margin-top:8px;padding:8px;background:#000;border-radius:4px;word-break:break-all;color:#d1fae5",text:s.acceptUrl}));const l=a("button",{class:"btn-sm",style:"margin-top:8px;padding:4px 10px",text:"Copy link",onclick:async()=>{try{await navigator.clipboard.writeText(s.acceptUrl),l.textContent="Copied!",setTimeout(()=>{l.textContent="Copy link"},2e3)}catch{window.errorHandler&&window.errorHandler.show("Clipboard blocked: select the link manually.")}}});n.appendChild(l),s.deliveredVia==="dev-console"?n.appendChild(a("p",{style:"margin-top:8px;color:#fbbf24;font-size:0.8rem",text:"SMTP not configured \u2014 the invite was logged to the server console (search for [DC-048-DEV-INVITE-LINK])."})):s.deliveredVia==="email"&&n.appendChild(a("p",{style:"margin-top:8px;color:#86efac;font-size:0.8rem",text:"Email sent to "+s.email+"."})),e.appendChild(n)}async function v(s){s.innerHTML="",s.appendChild(a("h2",{style:"margin:0 0 16px",text:"Admin \xB7 Users & Invites"}));const e=await f(c.me).catch(()=>({}));if(!e||!e.user||e.user.role!=="admin"){s.appendChild(a("p",{style:"color:var(--muted)",text:"Admin role required to view this panel. If multi-user mode is enabled and you should have access, check /api/v1/auth/me."}));return}const n=a("button",{class:"btn-sm",style:"float:right;padding:4px 10px",text:"Refresh",onclick:()=>v(s)});s.appendChild(n);const l=a("h3",{style:"margin:24px 0 8px;clear:both",text:"Users"});s.appendChild(l);const t=a("div",{id:"admin-users-list"});s.appendChild(t);const i=await f(c.users).catch(()=>({users:[]}));g(t,i.users,()=>v(s)),s.appendChild(a("h4",{style:"margin:24px 0 8px;font-size:0.95rem",text:"Pre-authorize email"}));const y=a("form",{style:"display:flex;gap:8px;align-items:end",onsubmit:async L=>{L.preventDefault();const P=L.target.email.value.trim();if(P)try{await f(c.users,{method:"POST",body:{email:P}}),L.target.reset(),v(s)}catch(C){window.errorHandler&&window.errorHandler.show("Add failed: "+C.message)}}});y.appendChild(a("input",{name:"email",type:"email",required:!0,placeholder:"user@example.com",style:"padding:6px"})),y.appendChild(a("button",{type:"submit",class:"btn-sm",style:"padding:6px 12px",text:"Add to allowlist"})),s.appendChild(y),s.appendChild(a("h3",{style:"margin:24px 0 8px",text:"Issue invite"}));const u=a("div");s.appendChild(u);const w=a("div",{id:"admin-invites-list",style:"margin-top:16px"});s.appendChild(w);const T=await f(c.invites).catch(()=>({invites:[]}));b(w,T.invites,()=>v(s)),m(u,L=>{r(L,u),v(s)})}async function d(){if(document.getElementById("admin-panel-root"))return;const e=a("div",{id:"admin-panel-root",style:"position:fixed;inset:0;background:rgba(0,0,0,0.5);z-index:1000;display:flex;align-items:center;justify-content:center;",onclick:t=>{t.target===e&&o()}}),n=a("div",{style:"background:var(--card-base,#1f2937);color:var(--text,#f3f4f6);border-radius:8px;padding:24px;max-width:900px;width:90%;max-height:85vh;overflow:auto;position:relative;box-shadow:0 10px 30px rgba(0,0,0,0.3)"});n.appendChild(a("button",{class:"btn-sm",style:"position:absolute;top:12px;right:12px;padding:4px 10px",text:"Close",onclick:o}));const l=a("div",{id:"admin-panel-body"});n.appendChild(l),e.appendChild(n),document.body.appendChild(e);try{await v(l)}catch(t){l.innerHTML='

Failed to load admin panel: '+(t.message||t)+"

"}}function o(){const s=document.getElementById("admin-panel-root");s&&s.remove()}async function p(s){async function e(){const n=await f(c.me).catch(()=>({})),l=document.getElementById("admin-trigger-btn");if(n&&n.user&&n.user.role==="admin"){if(l)return;const t=a("button",{id:"admin-trigger-btn",class:"btn-sm",style:"margin-left:8px;padding:6px 12px",text:"Admin",onclick:d});s?s.appendChild(t):document.body&&document.body.appendChild(t)}else l&&l.remove()}await e(),setInterval(e,6e4)}window.AdminPanel={open:d,close:o,attachTrigger:p}})(),(function(){injectModal("token-management-modal",`

\u{1F511} DNS Credentials

@@ -306,7 +306,7 @@
- `);function c(){return Object.keys(SITE.dnsServers||{})}function a(t){return(SITE.dnsServers||{})[t]?.name||t.toUpperCase()}function g(){const t=document.getElementById("dns-cred-sections");if(!t)return;t.innerHTML="";const i=c();if(i.length===0){t.innerHTML='

No DNS servers configured.

';return}for(const y of i)t.insertAdjacentHTML("beforeend",` + `);function c(){return Object.keys(SITE.dnsServers||{})}function a(t){return(SITE.dnsServers||{})[t]?.name||t.toUpperCase()}function f(){const t=document.getElementById("dns-cred-sections");if(!t)return;t.innerHTML="";const i=c();if(i.length===0){t.innerHTML='

No DNS servers configured.

';return}for(const y of i)t.insertAdjacentHTML("beforeend",`

${a(y)}

@@ -329,17 +329,17 @@
- `)}function h(){let t=safeSessionGet("dashcaddy-encryption-key");if(t)return t;const i=safeGet("dashcaddy-encryption-key");if(i)return safeSessionSet("dashcaddy-encryption-key",i),safeRemove("dashcaddy-encryption-key"),i;const y=new Uint8Array(32);return crypto.getRandomValues(y),t=Array.from(y,u=>u.toString(16).padStart(2,"0")).join(""),safeSessionSet("dashcaddy-encryption-key",t),t}const f=h();function m(t,i){if(!t)return"";const y=crypto.getRandomValues(new Uint8Array(8)),u=Array.from(y,L=>L.toString(16).padStart(2,"0")).join(""),w=new TextEncoder().encode(i+u);let T="";for(let L=0;LparseInt($,16))),P=atob(t.substring(17)),E=new TextEncoder().encode(i+T);let B="";for(let $=0;${["readonly","admin"].forEach(i=>{["token","username"].forEach(y=>{safeRemove(`${t}-${i}-${y}-enc`)})}),safeRemove(`${t}-token-enc`),safeRemove(`${t}-username-enc`)})}function l(t){const i=d(t,"readonly"),y=o(t,"readonly"),u=d(t,"admin"),w=o(t,"admin"),T=b(safeGet(`${t}-token-enc`),f),L=b(safeGet(`${t}-username-enc`),f);return{username:w||y||L,token:u||i||T,readonlyToken:i||T,readonlyUsername:y||L,adminToken:u||T,adminUsername:w||L}}document.getElementById("manage-tokens")?.addEventListener("click",()=>{g();const t=document.getElementById("token-management-modal"),i=e();c().forEach(y=>{const u=i[y];document.getElementById(`${y}-readonly-username`).value=u.readonly.username,document.getElementById(`${y}-readonly-token`).value=u.readonly.token,document.getElementById(`${y}-admin-username`).value=u.admin.username,document.getElementById(`${y}-admin-token`).value=u.admin.token,document.getElementById(`${y}-token-status`).textContent=""}),t.classList.add("show")}),document.getElementById("token-management-modal")?.addEventListener("click",t=>{const i=t.target.closest(".token-toggle");if(i){const y=i.dataset.target,u=document.getElementById(y);u.type==="password"?(u.type="text",i.textContent="\u{1F648}"):(u.type="password",i.textContent="\u{1F441}");return}t.target.id==="token-management-modal"&&t.target.classList.remove("show")}),document.getElementById("token-save")?.addEventListener("click",async()=>{const t=c();t.forEach(u=>{r(u,"readonly",document.getElementById(`${u}-readonly-username`).value.trim()),p(u,"readonly",document.getElementById(`${u}-readonly-token`).value.trim()),r(u,"admin",document.getElementById(`${u}-admin-username`).value.trim()),p(u,"admin",document.getElementById(`${u}-admin-token`).value.trim())});const i={};let y=!1;if(t.forEach(u=>{const w={},T=document.getElementById(`${u}-readonly-username`).value.trim(),L=document.getElementById(`${u}-readonly-token`).value.trim(),P=document.getElementById(`${u}-admin-username`).value.trim(),E=document.getElementById(`${u}-admin-token`).value.trim();T&&L&&(w.readonly={username:T,password:L},y=!0),P&&E&&(w.admin={username:P,password:E},y=!0),Object.keys(w).length>0&&(i[u]=w)}),y){t.forEach(u=>{i[u]&&(document.getElementById(`${u}-token-status`).textContent="Verifying...",document.getElementById(`${u}-token-status`).className="token-status")});try{const w=await(await secureFetch("/api/v1/dns/credentials",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({servers:i})})).json();w.results?t.forEach(T=>{const L=document.getElementById(`${T}-token-status`);if(!i[T]){L.textContent="";return}const P=w.results[T];P?.success?(L.textContent="\u2713 Verified & saved",L.className="token-status success"):P?.partial?(L.textContent="\u2713 "+P.partial,L.className="token-status success"):(L.textContent="\u2717 "+(P?.error||"Login failed"),L.className="token-status error")}):w.success?t.forEach(T=>{i[T]&&(document.getElementById(`${T}-token-status`).textContent="\u2713 Saved",document.getElementById(`${T}-token-status`).className="token-status success")}):t.forEach(T=>{i[T]&&(document.getElementById(`${T}-token-status`).textContent="\u2717 "+(w.error||"Failed"),document.getElementById(`${T}-token-status`).className="token-status error")})}catch(u){console.error("Failed to sync DNS credentials to backend:",u),t.forEach(w=>{i[w]&&(document.getElementById(`${w}-token-status`).textContent="\u2713 Saved locally (sync failed)",document.getElementById(`${w}-token-status`).className="token-status")})}}else t.forEach(u=>{document.getElementById(`${u}-token-status`).textContent=""});setTimeout(()=>{t.every(w=>{const T=document.getElementById(`${w}-token-status`)?.textContent;return!T||T.includes("\u2713")})&&closeModal("token-management-modal")},1500)}),document.getElementById("token-cancel")?.addEventListener("click",()=>{closeModal("token-management-modal")}),document.getElementById("token-clear-all")?.addEventListener("click",async()=>{if(confirm("Clear all stored DNS credentials? This cannot be undone.")){n(),c().forEach(t=>{document.getElementById(`${t}-readonly-username`).value="",document.getElementById(`${t}-readonly-token`).value="",document.getElementById(`${t}-admin-username`).value="",document.getElementById(`${t}-admin-token`).value="",document.getElementById(`${t}-token-status`).textContent="\u2713 Cleared",document.getElementById(`${t}-token-status`).className="token-status success"});try{await secureFetch("/api/v1/dns/credentials",{method:"DELETE"})}catch{}}}),window.getToken=d,window.getUsername=o,window.setToken=p,window.setUsername=r,window.getAllCredentials=e,window.getCredential=s,window.setCredential=v,window.getEncryptionKey=h,window.getDnsIds=c,window.getDnsDisplayName=a})(),(function(){function c(p,r,e=null){const n=document.getElementById(p+"-dot"),l=document.getElementById(p+"-pill"),t=document.getElementById(p+"-time"),i=document.querySelector(`[data-app="${p}"]`);n&&(n.classList.toggle("ok",r),n.classList.toggle("bad",!r)),l&&(l.textContent=r?"ON":"OFF",l.classList.toggle("on",r),l.classList.toggle("off",!r)),t&&e!==null&&(t.textContent=r?`${e}ms`:"timeout",t.className=`response-time ${a(e,r)}`),i&&i.setAttribute("data-status",r?"on":"off")}function a(p,r){return r?p<200?"excellent":p<500?"good":p<1e3?"fair":"slow":"timeout"}async function g(p){const r=performance.now();try{const e=await fetch("/probe/"+p,{cache:"no-store"}),n=performance.now(),l=Math.round(n-r);return{isUp:e.status>=200&&e.status<400||e.status===401||e.status===403,responseTime:l}}catch{const e=performance.now();return{isUp:!1,responseTime:Math.round(e-r)}}}window.APPS=[];let h=null,f=!1;async function m(){try{window.SkeletonLoader&&window.SkeletonLoader.show(6);const p=await fetch("/api/v1/services",{cache:"no-store"});if(p.ok){const r=await p.json();window.APPS=r.services||[],window.SkeletonLoader&&window.SkeletonLoader.hide()}else console.error("Failed to load services:",p.status),window.SkeletonLoader&&window.SkeletonLoader.hide()}catch(p){console.error("Failed to load services:",p),window.SkeletonLoader&&window.SkeletonLoader.hide()}}function b(p){const r=window.APPS?.find(n=>n.id===p);if(r?.url)return r.url.startsWith("http")?r.url:"https://"+r.url;if(r?.isExternal&&r.externalUrl)return r.externalUrl;const e=SITE.dnsServers?.[p];return e?"http://"+e.ip+":"+(e.port||5380):buildServiceUrl(p)}function s(p,r,e){const n=document.createElement(p);return r&&(n.className=r),e&&(n.textContent=e),n}function v(){const p=document.getElementById("cards");p.innerHTML="";for(let r=0;r{D.stopPropagation(),window.openContainerLogsModal(e.containerId,e.name)},x.appendChild(k);const I=s("button","update-btn","\u2B06\uFE0F");I.title="Update container to latest version",I.id=`update-btn-${e.id}`,I.onclick=D=>{D.stopPropagation(),window.updateContainer(e.containerId,e.name,e.id)},x.appendChild(I);const A=s("button","exec-btn",">_");A.title="Open terminal",A.onclick=D=>{D.stopPropagation(),window.openExecModal&&window.openExecModal(e.containerId,e.name)},x.appendChild(A)}if(e.logPath&&!e.containerId){const k=s("button","logs-btn","\u{1F4CB}");k.title="View application logs",k.onclick=I=>{I.stopPropagation(),window.openFileLogsModal(e.logPath,e.name)},x.appendChild(k)}if(e.isExternal||e.appTemplate||e.url){const k=s("button","creds-btn","\u{1F511}");k.title="Auto-login credentials",k.id=`creds-btn-${e.id}`,k.onclick=I=>{I.stopPropagation(),window.openServiceCredsModal(e)},x.appendChild(k)}if(e.id!=="internet"){const k=s("button","options-btn","\u2699\uFE0F");k.title="Edit service settings",k.onclick=I=>{I.stopPropagation(),window.openServiceEditModal(e)},x.appendChild(k)}if(e.id!=="internet"){const k=s("button","delete-btn","\u{1F5D1}\uFE0F");k.title="Delete this service",k.onclick=I=>{I.stopPropagation(),window.deleteService(e.id,e.name)},x.appendChild(k)}const S=s("button",null,"Open");S.onclick=()=>window.open(b(e.id),"_blank","noopener"),x.appendChild(S),n.appendChild(x),n.style.transitionDelay=`${Math.min(r*45,270)}ms`,p.appendChild(n)}requestAnimationFrame(()=>{p.querySelectorAll(".card").forEach(r=>r.classList.add("loaded"))}),window.groupRecipeCards&&requestAnimationFrame(()=>window.groupRecipeCards()),window.refreshServiceFilter&&window.refreshServiceFilter()}function d(p,r,e=null){const n=document.getElementById("dot-"+p+"-grid"),l=document.getElementById("badge-"+p),t=document.getElementById("time-"+p),i=document.querySelector(`[data-app="${p}"]`);n&&(n.classList.toggle("ok",r),n.classList.toggle("bad",!r)),l&&(l.textContent=r?"ON":"OFF",l.classList.toggle("on",r),l.classList.toggle("off",!r)),t&&e!==null&&(t.textContent=r?`${e}ms`:"timeout",t.className=`response-time ${a(e,r)}`),i&&i.setAttribute("data-status",r?"on":"off")}async function o(){if(h)return f=!0,h;function p(n,l=new Date){const t=document.getElementById("stamp");t&&(t.textContent=`${n}: ${new Date(l).toLocaleTimeString()}`)}function r(n){Object.keys(SITE.dnsServers).forEach(t=>{const i=n[t];i&&c(t,i.isUp,i.responseTime)}),n.internet&&c("internet",n.internet.isUp,n.internet.responseTime),window.APPS.forEach(t=>{const i=n[t.id];i&&d(t.id,i.isUp,i.responseTime)})}async function e(){const n=Object.keys(SITE.dnsServers),l=n.map(u=>g(u));l.push(g("internet"));const t=await Promise.all(l);n.forEach((u,w)=>c(u,t[w].isUp,t[w].responseTime));const i=t[t.length-1];c("internet",i.isUp,i.responseTime),(await Promise.all(window.APPS.map(async u=>{const w=await g(u.id);return{id:u.id,...w}}))).forEach(u=>{d(u.id,u.isUp,u.responseTime)})}return h=(async()=>{try{const n=await fetch("/api/v1/services/status",{cache:"no-store"});if(!n.ok)throw new Error(`Status refresh failed (${n.status})`);const l=await n.json();r(l.statuses||{}),p("last check",l.checkedAt||new Date)}catch(n){console.warn("Batched status refresh failed, falling back to direct probes:",n);try{await e(),p("last check")}catch(l){console.error("Dashboard refresh failed:",l),p("last failed")}}finally{h=null,f&&(f=!1,setTimeout(()=>{window.refreshAll()},0))}})(),h}document.querySelector(".top")?.addEventListener("click",p=>{const r=p.target.closest('[id$="-open"]');if(!r)return;const e=r.id.replace("-open","");SITE.dnsServers[e]&&window.open(b(e),"_blank","noopener")}),document.getElementById("ca-open")?.addEventListener("click",()=>window.open(b("ca"),"_blank","noopener")),document.getElementById("creds-btn-ca")?.addEventListener("click",p=>{p.stopPropagation();const r=window.APPS.find(e=>e.id==="ca");r&&window.openServiceCredsModal&&window.openServiceCredsModal(r)}),document.getElementById("options-btn-ca")?.addEventListener("click",p=>{p.stopPropagation();const r=window.APPS.find(e=>e.id==="ca");r&&window.openServiceEditModal&&window.openServiceEditModal(r)}),document.getElementById("delete-btn-ca")?.addEventListener("click",p=>{p.stopPropagation(),window.deleteService&&window.deleteService("ca","DashCA")}),window.loadServices=m,window.buildGrid=v,window.refreshAll=o,window.setQuick=c,window.setBadge=d,window.getResponseTimeClass=a,window.checkServiceWithTiming=g,window.serviceUrl=b,window.el=s})(),(function(){async function c(s){const d=await(await secureFetch(`/api/v1/dns/restart/${s}`,{method:"POST"})).json();if(!d.success)throw new Error(d.error||"Restart failed");return d}document.querySelector(".top")?.addEventListener("click",async s=>{const v=s.target.closest('[id$="-restart"]');if(!v)return;const d=v.id.replace("-restart","");if(SITE.dnsServers[d]&&confirm(`Restart ${d.toUpperCase()} service?`))try{await withButton(v,"...",()=>c(d)),setTimeout(window.refreshAll,DC.DELAYS.RELOAD)}catch(o){showNotification("Restart failed: "+o.message,"error")}});async function a(s,v){const d=document.getElementById(`${s}-update`),o=d?.textContent||"\u2B06\uFE0F";try{d.textContent="\u{1F50D}",d.disabled=!0,d.title="Checking for updates...";const r=await(await fetch(`/api/v1/dns/check-update?server=${encodeURIComponent(v)}`)).json();if(!r.success)throw new Error(r.error||"Failed to check for updates");if(!r.updateAvailable){d.textContent="\u2705",d.title=`Already on latest version (${r.currentVersion})`,showNotification(`${s.toUpperCase()} is already up to date! Current version: ${r.currentVersion}`,"info"),setTimeout(()=>{d.textContent=o,d.disabled=!1,d.title="Update DNS server"},3e3);return}if(!confirm(`Update available for ${s.toUpperCase()}! + `)}function h(){let t=safeSessionGet("dashcaddy-encryption-key");if(t)return t;const i=safeGet("dashcaddy-encryption-key");if(i)return safeSessionSet("dashcaddy-encryption-key",i),safeRemove("dashcaddy-encryption-key"),i;const y=new Uint8Array(32);return crypto.getRandomValues(y),t=Array.from(y,u=>u.toString(16).padStart(2,"0")).join(""),safeSessionSet("dashcaddy-encryption-key",t),t}const g=h();function m(t,i){if(!t)return"";const y=crypto.getRandomValues(new Uint8Array(8)),u=Array.from(y,L=>L.toString(16).padStart(2,"0")).join(""),w=new TextEncoder().encode(i+u);let T="";for(let L=0;LparseInt($,16))),P=atob(t.substring(17)),C=new TextEncoder().encode(i+T);let B="";for(let $=0;${["readonly","admin"].forEach(i=>{["token","username"].forEach(y=>{safeRemove(`${t}-${i}-${y}-enc`)})}),safeRemove(`${t}-token-enc`),safeRemove(`${t}-username-enc`)})}function l(t){const i=d(t,"readonly"),y=o(t,"readonly"),u=d(t,"admin"),w=o(t,"admin"),T=b(safeGet(`${t}-token-enc`),g),L=b(safeGet(`${t}-username-enc`),g);return{username:w||y||L,token:u||i||T,readonlyToken:i||T,readonlyUsername:y||L,adminToken:u||T,adminUsername:w||L}}document.getElementById("manage-tokens")?.addEventListener("click",()=>{f();const t=document.getElementById("token-management-modal"),i=e();c().forEach(y=>{const u=i[y];document.getElementById(`${y}-readonly-username`).value=u.readonly.username,document.getElementById(`${y}-readonly-token`).value=u.readonly.token,document.getElementById(`${y}-admin-username`).value=u.admin.username,document.getElementById(`${y}-admin-token`).value=u.admin.token,document.getElementById(`${y}-token-status`).textContent=""}),t.classList.add("show")}),document.getElementById("token-management-modal")?.addEventListener("click",t=>{const i=t.target.closest(".token-toggle");if(i){const y=i.dataset.target,u=document.getElementById(y);u.type==="password"?(u.type="text",i.textContent="\u{1F648}"):(u.type="password",i.textContent="\u{1F441}");return}t.target.id==="token-management-modal"&&t.target.classList.remove("show")}),document.getElementById("token-save")?.addEventListener("click",async()=>{const t=c();t.forEach(u=>{s(u,"readonly",document.getElementById(`${u}-readonly-username`).value.trim()),p(u,"readonly",document.getElementById(`${u}-readonly-token`).value.trim()),s(u,"admin",document.getElementById(`${u}-admin-username`).value.trim()),p(u,"admin",document.getElementById(`${u}-admin-token`).value.trim())});const i={};let y=!1;if(t.forEach(u=>{const w={},T=document.getElementById(`${u}-readonly-username`).value.trim(),L=document.getElementById(`${u}-readonly-token`).value.trim(),P=document.getElementById(`${u}-admin-username`).value.trim(),C=document.getElementById(`${u}-admin-token`).value.trim();T&&L&&(w.readonly={username:T,password:L},y=!0),P&&C&&(w.admin={username:P,password:C},y=!0),Object.keys(w).length>0&&(i[u]=w)}),y){t.forEach(u=>{i[u]&&(document.getElementById(`${u}-token-status`).textContent="Verifying...",document.getElementById(`${u}-token-status`).className="token-status")});try{const w=await(await secureFetch("/api/v1/dns/credentials",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({servers:i})})).json();w.results?t.forEach(T=>{const L=document.getElementById(`${T}-token-status`);if(!i[T]){L.textContent="";return}const P=w.results[T];P?.success?(L.textContent="\u2713 Verified & saved",L.className="token-status success"):P?.partial?(L.textContent="\u2713 "+P.partial,L.className="token-status success"):(L.textContent="\u2717 "+(P?.error||"Login failed"),L.className="token-status error")}):w.success?t.forEach(T=>{i[T]&&(document.getElementById(`${T}-token-status`).textContent="\u2713 Saved",document.getElementById(`${T}-token-status`).className="token-status success")}):t.forEach(T=>{i[T]&&(document.getElementById(`${T}-token-status`).textContent="\u2717 "+(w.error||"Failed"),document.getElementById(`${T}-token-status`).className="token-status error")})}catch(u){console.error("Failed to sync DNS credentials to backend:",u),t.forEach(w=>{i[w]&&(document.getElementById(`${w}-token-status`).textContent="\u2713 Saved locally (sync failed)",document.getElementById(`${w}-token-status`).className="token-status")})}}else t.forEach(u=>{document.getElementById(`${u}-token-status`).textContent=""});setTimeout(()=>{t.every(w=>{const T=document.getElementById(`${w}-token-status`)?.textContent;return!T||T.includes("\u2713")})&&closeModal("token-management-modal")},1500)}),document.getElementById("token-cancel")?.addEventListener("click",()=>{closeModal("token-management-modal")}),document.getElementById("token-clear-all")?.addEventListener("click",async()=>{if(confirm("Clear all stored DNS credentials? This cannot be undone.")){n(),c().forEach(t=>{document.getElementById(`${t}-readonly-username`).value="",document.getElementById(`${t}-readonly-token`).value="",document.getElementById(`${t}-admin-username`).value="",document.getElementById(`${t}-admin-token`).value="",document.getElementById(`${t}-token-status`).textContent="\u2713 Cleared",document.getElementById(`${t}-token-status`).className="token-status success"});try{await secureFetch("/api/v1/dns/credentials",{method:"DELETE"})}catch{}}}),window.getToken=d,window.getUsername=o,window.setToken=p,window.setUsername=s,window.getAllCredentials=e,window.getCredential=r,window.setCredential=v,window.getEncryptionKey=h,window.getDnsIds=c,window.getDnsDisplayName=a})(),(function(){function c(p,s,e=null){const n=document.getElementById(p+"-dot"),l=document.getElementById(p+"-pill"),t=document.getElementById(p+"-time"),i=document.querySelector(`[data-app="${p}"]`);n&&(n.classList.toggle("ok",s),n.classList.toggle("bad",!s)),l&&(l.textContent=s?"ON":"OFF",l.classList.toggle("on",s),l.classList.toggle("off",!s)),t&&e!==null&&(t.textContent=s?`${e}ms`:"timeout",t.className=`response-time ${a(e,s)}`),i&&i.setAttribute("data-status",s?"on":"off")}function a(p,s){return s?p<200?"excellent":p<500?"good":p<1e3?"fair":"slow":"timeout"}async function f(p){const s=performance.now();try{const e=await fetch("/probe/"+p,{cache:"no-store"}),n=performance.now(),l=Math.round(n-s);return{isUp:e.status>=200&&e.status<400||e.status===401||e.status===403,responseTime:l}}catch{const e=performance.now();return{isUp:!1,responseTime:Math.round(e-s)}}}window.APPS=[];let h=null,g=!1;async function m(){try{window.SkeletonLoader&&window.SkeletonLoader.show(6);const p=await fetch("/api/v1/services",{cache:"no-store"});if(p.ok){const s=await p.json();window.APPS=s.services||[],window.SkeletonLoader&&window.SkeletonLoader.hide()}else console.error("Failed to load services:",p.status),window.SkeletonLoader&&window.SkeletonLoader.hide()}catch(p){console.error("Failed to load services:",p),window.SkeletonLoader&&window.SkeletonLoader.hide()}}function b(p){const s=window.APPS?.find(n=>n.id===p);if(s?.url)return s.url.startsWith("http")?s.url:"https://"+s.url;if(s?.isExternal&&s.externalUrl)return s.externalUrl;const e=SITE.dnsServers?.[p];return e?"http://"+e.ip+":"+(e.port||5380):buildServiceUrl(p)}function r(p,s,e){const n=document.createElement(p);return s&&(n.className=s),e&&(n.textContent=e),n}function v(){const p=document.getElementById("cards");p.innerHTML="";for(let s=0;s{D.stopPropagation(),window.openContainerLogsModal(e.containerId,e.name)},x.appendChild(E);const S=r("button","update-btn","\u2B06\uFE0F");S.title="Update container to latest version",S.id=`update-btn-${e.id}`,S.onclick=D=>{D.stopPropagation(),window.updateContainer(e.containerId,e.name,e.id)},x.appendChild(S);const A=r("button","exec-btn",">_");A.title="Open terminal",A.onclick=D=>{D.stopPropagation(),window.openExecModal&&window.openExecModal(e.containerId,e.name)},x.appendChild(A)}if(e.logPath&&!e.containerId){const E=r("button","logs-btn","\u{1F4CB}");E.title="View application logs",E.onclick=S=>{S.stopPropagation(),window.openFileLogsModal(e.logPath,e.name)},x.appendChild(E)}if(e.isExternal||e.appTemplate||e.url){const E=r("button","creds-btn","\u{1F511}");E.title="Auto-login credentials",E.id=`creds-btn-${e.id}`,E.onclick=S=>{S.stopPropagation(),window.openServiceCredsModal(e)},x.appendChild(E)}if(e.id!=="internet"){const E=r("button","options-btn","\u2699\uFE0F");E.title="Edit service settings",E.onclick=S=>{S.stopPropagation(),window.openServiceEditModal(e)},x.appendChild(E)}if(e.id!=="internet"){const E=r("button","share-btn","\u{1F517}");E.title="Share this service (Pro)",E.onclick=S=>{S.stopPropagation(),typeof window.openShareModal=="function"?window.openShareModal(e):typeof window.showNotification=="function"&&window.showNotification("Share modal not loaded. Refresh the page.","error")},x.appendChild(E)}if(e.id!=="internet"){const E=r("button","delete-btn","\u{1F5D1}\uFE0F");E.title="Delete this service",E.onclick=S=>{S.stopPropagation(),window.deleteService(e.id,e.name)},x.appendChild(E)}const I=r("button",null,"Open");I.onclick=()=>window.open(b(e.id),"_blank","noopener"),x.appendChild(I),n.appendChild(x),n.style.transitionDelay=`${Math.min(s*45,270)}ms`,p.appendChild(n)}requestAnimationFrame(()=>{p.querySelectorAll(".card").forEach(s=>s.classList.add("loaded"))}),window.groupRecipeCards&&requestAnimationFrame(()=>window.groupRecipeCards()),window.refreshServiceFilter&&window.refreshServiceFilter()}function d(p,s,e=null){const n=document.getElementById("dot-"+p+"-grid"),l=document.getElementById("badge-"+p),t=document.getElementById("time-"+p),i=document.querySelector(`[data-app="${p}"]`);n&&(n.classList.toggle("ok",s),n.classList.toggle("bad",!s)),l&&(l.textContent=s?"ON":"OFF",l.classList.toggle("on",s),l.classList.toggle("off",!s)),t&&e!==null&&(t.textContent=s?`${e}ms`:"timeout",t.className=`response-time ${a(e,s)}`),i&&i.setAttribute("data-status",s?"on":"off")}async function o(){if(h)return g=!0,h;function p(n,l=new Date){const t=document.getElementById("stamp");t&&(t.textContent=`${n}: ${new Date(l).toLocaleTimeString()}`)}function s(n){Object.keys(SITE.dnsServers).forEach(t=>{const i=n[t];i&&c(t,i.isUp,i.responseTime)}),n.internet&&c("internet",n.internet.isUp,n.internet.responseTime),window.APPS.forEach(t=>{const i=n[t.id];i&&d(t.id,i.isUp,i.responseTime)})}async function e(){const n=Object.keys(SITE.dnsServers),l=n.map(u=>f(u));l.push(f("internet"));const t=await Promise.all(l);n.forEach((u,w)=>c(u,t[w].isUp,t[w].responseTime));const i=t[t.length-1];c("internet",i.isUp,i.responseTime),(await Promise.all(window.APPS.map(async u=>{const w=await f(u.id);return{id:u.id,...w}}))).forEach(u=>{d(u.id,u.isUp,u.responseTime)})}return h=(async()=>{try{const n=await fetch("/api/v1/services/status",{cache:"no-store"});if(!n.ok)throw new Error(`Status refresh failed (${n.status})`);const l=await n.json();s(l.statuses||{}),p("last check",l.checkedAt||new Date)}catch(n){console.warn("Batched status refresh failed, falling back to direct probes:",n);try{await e(),p("last check")}catch(l){console.error("Dashboard refresh failed:",l),p("last failed")}}finally{h=null,g&&(g=!1,setTimeout(()=>{window.refreshAll()},0))}})(),h}document.querySelector(".top")?.addEventListener("click",p=>{const s=p.target.closest('[id$="-open"]');if(!s)return;const e=s.id.replace("-open","");SITE.dnsServers[e]&&window.open(b(e),"_blank","noopener")}),document.getElementById("ca-open")?.addEventListener("click",()=>window.open(b("ca"),"_blank","noopener")),document.getElementById("creds-btn-ca")?.addEventListener("click",p=>{p.stopPropagation();const s=window.APPS.find(e=>e.id==="ca");s&&window.openServiceCredsModal&&window.openServiceCredsModal(s)}),document.getElementById("options-btn-ca")?.addEventListener("click",p=>{p.stopPropagation();const s=window.APPS.find(e=>e.id==="ca");s&&window.openServiceEditModal&&window.openServiceEditModal(s)}),document.getElementById("delete-btn-ca")?.addEventListener("click",p=>{p.stopPropagation(),window.deleteService&&window.deleteService("ca","DashCA")}),window.loadServices=m,window.buildGrid=v,window.refreshAll=o,window.setQuick=c,window.setBadge=d,window.getResponseTimeClass=a,window.checkServiceWithTiming=f,window.serviceUrl=b,window.el=r})(),(function(){async function c(r){const d=await(await secureFetch(`/api/v1/dns/restart/${r}`,{method:"POST"})).json();if(!d.success)throw new Error(d.error||"Restart failed");return d}document.querySelector(".top")?.addEventListener("click",async r=>{const v=r.target.closest('[id$="-restart"]');if(!v)return;const d=v.id.replace("-restart","");if(SITE.dnsServers[d]&&confirm(`Restart ${d.toUpperCase()} service?`))try{await withButton(v,"...",()=>c(d)),setTimeout(window.refreshAll,DC.DELAYS.RELOAD)}catch(o){showNotification("Restart failed: "+o.message,"error")}});async function a(r,v){const d=document.getElementById(`${r}-update`),o=d?.textContent||"\u2B06\uFE0F";try{d.textContent="\u{1F50D}",d.disabled=!0,d.title="Checking for updates...";const s=await(await fetch(`/api/v1/dns/check-update?server=${encodeURIComponent(v)}`)).json();if(!s.success)throw new Error(s.error||"Failed to check for updates");if(!s.updateAvailable){d.textContent="\u2705",d.title=`Already on latest version (${s.currentVersion})`,showNotification(`${r.toUpperCase()} is already up to date! Current version: ${s.currentVersion}`,"info"),setTimeout(()=>{d.textContent=o,d.disabled=!1,d.title="Update DNS server"},3e3);return}if(!confirm(`Update available for ${r.toUpperCase()}! -Current: ${r.currentVersion} -New: ${r.updateVersion} +Current: ${s.currentVersion} +New: ${s.updateVersion} -`+(r.updateTitle?`${r.updateTitle} +`+(s.updateTitle?`${s.updateTitle} `:"")+`The DNS server will restart during the update. Proceed?`)){d.textContent=o,d.disabled=!1,d.title="Update DNS server";return}d.textContent="\u{1F504}",d.title="Updating...";const l=await(await secureFetch(`/api/v1/dns/update?server=${encodeURIComponent(v)}`,{method:"POST"})).json();if(!l.success)throw new Error(l.error||"Update failed");if(l.manualUpdateRequired){d.textContent="\u2B06\uFE0F",d.title=`Update available: ${l.newVersion}`;const t=l.downloadLink?` Download: ${l.downloadLink}`:"",i=l.instructionsLink?` -Instructions: ${l.instructionsLink}`:"";showNotification(`${s.toUpperCase()} update requires manual installation. Current: ${l.previousVersion} \u2192 ${l.newVersion}. Please update manually on the host machine.`,"warning",8e3),d.disabled=!1;return}d.textContent="\u2705",d.title="Updated successfully!",showNotification(`${s.toUpperCase()} updated successfully! ${l.previousVersion} \u2192 ${l.newVersion}. Server is restarting...`,"success"),setTimeout(()=>{d.textContent=o,d.disabled=!1,d.title="Update DNS server",window.refreshAll()},1e4)}catch(p){console.error("DNS update error:",p),d.textContent="\u274C",d.title="Update failed",showNotification(`Failed to update ${s.toUpperCase()}: ${p.message}`,"error"),setTimeout(()=>{d.textContent=o,d.disabled=!1,d.title="Update DNS server"},3e3)}}document.querySelector(".top")?.addEventListener("click",s=>{const v=s.target.closest('[id$="-update"]');if(!v)return;const d=v.id.replace("-update","");SITE.dnsServers[d]&&a(d,SITE.dnsServers[d]?.ip)}),injectModal("dns-settings-modal",` +Instructions: ${l.instructionsLink}`:"";showNotification(`${r.toUpperCase()} update requires manual installation. Current: ${l.previousVersion} \u2192 ${l.newVersion}. Please update manually on the host machine.`,"warning",8e3),d.disabled=!1;return}d.textContent="\u2705",d.title="Updated successfully!",showNotification(`${r.toUpperCase()} updated successfully! ${l.previousVersion} \u2192 ${l.newVersion}. Server is restarting...`,"success"),setTimeout(()=>{d.textContent=o,d.disabled=!1,d.title="Update DNS server",window.refreshAll()},1e4)}catch(p){console.error("DNS update error:",p),d.textContent="\u274C",d.title="Update failed",showNotification(`Failed to update ${r.toUpperCase()}: ${p.message}`,"error"),setTimeout(()=>{d.textContent=o,d.disabled=!1,d.title="Update DNS server"},3e3)}}document.querySelector(".top")?.addEventListener("click",r=>{const v=r.target.closest('[id$="-update"]');if(!v)return;const d=v.id.replace("-update","");SITE.dnsServers[d]&&a(d,SITE.dnsServers[d]?.ip)}),injectModal("dns-settings-modal",`

DNS Settings

@@ -366,7 +366,7 @@ Instructions: ${l.instructionsLink}`:"";showNotification(`${s.toUpperCase()} upd
- `);let g=null;function h(s){g=s;const v=SITE.dnsServers[s]||{},d=document.getElementById("dns-settings-modal");document.getElementById("dns-settings-title").textContent=`${(v.name||s).toUpperCase()} Settings`,document.getElementById("dns-edit-ip").value=v.ip||"",document.getElementById("dns-edit-port").value=v.port||DC.DEFAULTS.DNS_PORT,document.getElementById("dns-edit-name").value=v.name||"",d.classList.add("show")}async function f(){if(!g)return;const s=document.getElementById("dns-edit-ip").value.trim(),v=document.getElementById("dns-edit-port").value.trim()||DC.DEFAULTS.DNS_PORT,d=document.getElementById("dns-edit-name").value.trim();if(!s){showNotification("Server IP is required","warning");return}const o={dnsServers:{}};o.dnsServers[g]={ip:s,port:String(v)},d&&(o.dnsServers[g].name=d);try{const r=await(await secureFetch("/api/v1/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)})).json();r.success?(SITE.dnsServers[g]=o.dnsServers[g],showNotification(`${g.toUpperCase()} settings saved`,"success"),b(),window.refreshAll()):showNotification(r.error||"Failed to save settings","error")}catch(p){showNotification("Failed to save: "+p.message,"error")}}async function m(){if(g&&confirm(`Remove ${g.toUpperCase()} from dashboard? This won't affect the actual DNS server.`))try{const v=await(await secureFetch("/api/v1/config")).json();v.dnsServers&&delete v.dnsServers[g];const o=await(await secureFetch("/api/v1/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({dnsServers:v.dnsServers||{}})})).json();if(o.success){delete SITE.dnsServers[g];const p=document.querySelector(`.top [data-app="${g}"]`);p&&p.remove(),showNotification(`${g.toUpperCase()} removed from dashboard`,"success"),b()}else showNotification(o.error||"Failed to remove","error")}catch(s){showNotification("Failed to remove: "+s.message,"error")}}function b(){closeModal("dns-settings-modal"),g=null}document.getElementById("dns-settings-cancel")?.addEventListener("click",b),document.getElementById("dns-settings-save")?.addEventListener("click",f),document.getElementById("dns-settings-delete")?.addEventListener("click",m),document.getElementById("dns-settings-modal")?.addEventListener("click",s=>{s.target.id==="dns-settings-modal"&&b()}),document.querySelector(".top")?.addEventListener("click",s=>{const v=s.target.closest('[id$="-settings"]');if(!v)return;const d=v.id.replace("-settings","");SITE.dnsServers[d]&&(s.stopPropagation(),h(d))}),document.getElementById("refresh")?.addEventListener("click",window.refreshAll)})(),(function(){injectModal("logs-modal",` + `);let f=null;function h(r){f=r;const v=SITE.dnsServers[r]||{},d=document.getElementById("dns-settings-modal");document.getElementById("dns-settings-title").textContent=`${(v.name||r).toUpperCase()} Settings`,document.getElementById("dns-edit-ip").value=v.ip||"",document.getElementById("dns-edit-port").value=v.port||DC.DEFAULTS.DNS_PORT,document.getElementById("dns-edit-name").value=v.name||"",d.classList.add("show")}async function g(){if(!f)return;const r=document.getElementById("dns-edit-ip").value.trim(),v=document.getElementById("dns-edit-port").value.trim()||DC.DEFAULTS.DNS_PORT,d=document.getElementById("dns-edit-name").value.trim();if(!r){showNotification("Server IP is required","warning");return}const o={dnsServers:{}};o.dnsServers[f]={ip:r,port:String(v)},d&&(o.dnsServers[f].name=d);try{const s=await(await secureFetch("/api/v1/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)})).json();s.success?(SITE.dnsServers[f]=o.dnsServers[f],showNotification(`${f.toUpperCase()} settings saved`,"success"),b(),window.refreshAll()):showNotification(s.error||"Failed to save settings","error")}catch(p){showNotification("Failed to save: "+p.message,"error")}}async function m(){if(f&&confirm(`Remove ${f.toUpperCase()} from dashboard? This won't affect the actual DNS server.`))try{const v=await(await secureFetch("/api/v1/config")).json();v.dnsServers&&delete v.dnsServers[f];const o=await(await secureFetch("/api/v1/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({dnsServers:v.dnsServers||{}})})).json();if(o.success){delete SITE.dnsServers[f];const p=document.querySelector(`.top [data-app="${f}"]`);p&&p.remove(),showNotification(`${f.toUpperCase()} removed from dashboard`,"success"),b()}else showNotification(o.error||"Failed to remove","error")}catch(r){showNotification("Failed to remove: "+r.message,"error")}}function b(){closeModal("dns-settings-modal"),f=null}document.getElementById("dns-settings-cancel")?.addEventListener("click",b),document.getElementById("dns-settings-save")?.addEventListener("click",g),document.getElementById("dns-settings-delete")?.addEventListener("click",m),document.getElementById("dns-settings-modal")?.addEventListener("click",r=>{r.target.id==="dns-settings-modal"&&b()}),document.querySelector(".top")?.addEventListener("click",r=>{const v=r.target.closest('[id$="-settings"]');if(!v)return;const d=v.id.replace("-settings","");SITE.dnsServers[d]&&(r.stopPropagation(),h(d))}),document.getElementById("refresh")?.addEventListener("click",window.refreshAll)})(),(function(){injectModal("logs-modal",`
@@ -390,16 +390,16 @@ Instructions: ${l.instructionsLink}`:"";showNotification(`${s.toUpperCase()} upd
- `);let c=null,a=null,g=!1,h=null,f=null,m=!1,b=null,s=null,v=!1,d=null,o=!1;async function p(C,x=25){try{const S=getDnsServerAddr(C),k=await fetch(`/api/v1/dns/logs?server=${S}&limit=${x}`,{cache:"no-store",headers:{Accept:"application/json","Cache-Control":"no-cache"}});if(k.ok){const I=await k.json();return I.success&&I.logs?{logs:I.logs,count:I.count,server:I.server}:{error:I.error||"Failed to fetch logs"}}else return k.status===401?{error:"DNS auto-auth failed - check credentials in settings"}:{error:`HTTP ${k.status}`}}catch(S){return console.error("DNS logs fetch failed:",S),{error:S.message}}}function r(C){return{NoError:"var(--ok-fg)",NOERROR:"var(--ok-fg)",NxDomain:"var(--muted)",NXDOMAIN:"var(--muted)",Refused:"var(--bad-fg)",REFUSED:"var(--bad-fg)",ServerFailure:"#f39c12",SERVFAIL:"#f39c12"}[C]||"var(--fg)"}function e(C){const x=document.createElement("div");if(x.className="log-entry",x.style.cssText="display: grid; grid-template-columns: 140px 110px 1fr 70px 80px; gap: 8px; padding: 6px 10px; border-bottom: 1px solid var(--border); font-size: 0.8rem; align-items: center;",C.parsed===!1)return x.style.gridTemplateColumns="1fr",x.innerHTML=`${escapeHtml(C.raw)}`,x;const S=r(C.rcode),k=C.rcode==="Refused"||C.rcode==="REFUSED";return x.innerHTML=` - ${escapeHtml(C.timestamp)} - ${escapeHtml(C.client)} - ${escapeHtml(C.domain)} - ${escapeHtml(C.type)} - ${escapeHtml(C.rcode)} - `,x}async function n(){if(v){await B();return}if(m){await T();return}if(g||!c)return;const C=parseInt(document.getElementById("log-lines").value),x=document.getElementById("logs-content");try{const S=await p(c,C);if(S.error){x.innerHTML=` + `);let c=null,a=null,f=!1,h=null,g=null,m=!1,b=null,r=null,v=!1,d=null,o=!1;async function p(k,x=25){try{const I=getDnsServerAddr(k),E=await fetch(`/api/v1/dns/logs?server=${I}&limit=${x}`,{cache:"no-store",headers:{Accept:"application/json","Cache-Control":"no-cache"}});if(E.ok){const S=await E.json();return S.success&&S.logs?{logs:S.logs,count:S.count,server:S.server}:{error:S.error||"Failed to fetch logs"}}else return E.status===401?{error:"DNS auto-auth failed - check credentials in settings"}:{error:`HTTP ${E.status}`}}catch(I){return console.error("DNS logs fetch failed:",I),{error:I.message}}}function s(k){return{NoError:"var(--ok-fg)",NOERROR:"var(--ok-fg)",NxDomain:"var(--muted)",NXDOMAIN:"var(--muted)",Refused:"var(--bad-fg)",REFUSED:"var(--bad-fg)",ServerFailure:"#f39c12",SERVFAIL:"#f39c12"}[k]||"var(--fg)"}function e(k){const x=document.createElement("div");if(x.className="log-entry",x.style.cssText="display: grid; grid-template-columns: 140px 110px 1fr 70px 80px; gap: 8px; padding: 6px 10px; border-bottom: 1px solid var(--border); font-size: 0.8rem; align-items: center;",k.parsed===!1)return x.style.gridTemplateColumns="1fr",x.innerHTML=`${escapeHtml(k.raw)}`,x;const I=s(k.rcode),E=k.rcode==="Refused"||k.rcode==="REFUSED";return x.innerHTML=` + ${escapeHtml(k.timestamp)} + ${escapeHtml(k.client)} + ${escapeHtml(k.domain)} + ${escapeHtml(k.type)} + ${escapeHtml(k.rcode)} + `,x}async function n(){if(v){await B();return}if(m){await T();return}if(f||!c)return;const k=parseInt(document.getElementById("log-lines").value),x=document.getElementById("logs-content");try{const I=await p(c,k);if(I.error){x.innerHTML=`
\u26A0\uFE0F Error
-
${escapeHtml(S.error)}
+
${escapeHtml(I.error)}
`;return}x.innerHTML=`
Time @@ -407,49 +407,49 @@ Instructions: ${l.instructionsLink}`:"";showNotification(`${s.toUpperCase()} upd Domain Type Status -
`,S.logs&&S.logs.length>0?S.logs.forEach(k=>{const I=e(k);x.appendChild(I)}):x.innerHTML+=` + `,I.logs&&I.logs.length>0?I.logs.forEach(E=>{const S=e(E);x.appendChild(S)}):x.innerHTML+=`
No DNS queries logged yet -
`}catch(S){x.innerHTML=` + `}catch(I){x.innerHTML=`
- Failed to fetch logs: ${escapeHtml(S.message)} -
`}}function l(C){c=C,g=!1,m=!1;const x=document.getElementById("logs-modal"),S=document.getElementById("logs-title"),k=document.getElementById("logs-pause"),I=document.getElementById("logs-stream");S.textContent=`${C.toUpperCase()} DNS Logs`,k.textContent="\u23F8\uFE0F Pause",k.classList.remove("paused"),I&&(I.style.display="none"),x.classList.add("show"),n(),a=setInterval(n,DC.POLL.LOGS)}function t(){document.getElementById("logs-modal").classList.remove("show"),a&&(clearInterval(a),a=null),y(),c=null,m=!1,h=null,f=null,v=!1,b=null,s=null,g=!1}function i(C){d&&y();const x=document.getElementById("logs-stream"),S=document.getElementById("logs-pause"),k=document.getElementById("logs-content");a&&(clearInterval(a),a=null);try{d=new EventSource(`/api/v1/logs/stream/${C}`),o=!0,x.classList.add("active"),x.textContent="\u{1F534} Live",x.title="Streaming - click to stop",S.style.display="none";const I=document.getElementById("logs-title");I.textContent.includes("\u{1F534}")||(I.innerHTML=I.textContent.replace("\u{1F4CB}","\u{1F4CB} \u{1F534}")),d.onmessage=A=>{try{const D=JSON.parse(A.data);if(D.error){console.error("Stream error:",D.error),y();return}const O=document.createElement("div");O.className="log-entry",O.style.cssText="display: flex; gap: 12px; padding: 6px 10px; border-bottom: 1px solid var(--border); font-size: 0.8rem; align-items: flex-start; font-family: monospace;";const R=(D.stream||"stdout")==="stderr",N=R?"var(--bad-fg)":"var(--fg)",_=`${R?"STDERR":"STDOUT"}`;for(O.innerHTML=` + Failed to fetch logs: ${escapeHtml(I.message)} + `}}function l(k){c=k,f=!1,m=!1;const x=document.getElementById("logs-modal"),I=document.getElementById("logs-title"),E=document.getElementById("logs-pause"),S=document.getElementById("logs-stream");I.textContent=`${k.toUpperCase()} DNS Logs`,E.textContent="\u23F8\uFE0F Pause",E.classList.remove("paused"),S&&(S.style.display="none"),x.classList.add("show"),n(),a=setInterval(n,DC.POLL.LOGS)}function t(){document.getElementById("logs-modal").classList.remove("show"),a&&(clearInterval(a),a=null),y(),c=null,m=!1,h=null,g=null,v=!1,b=null,r=null,f=!1}function i(k){d&&y();const x=document.getElementById("logs-stream"),I=document.getElementById("logs-pause"),E=document.getElementById("logs-content");a&&(clearInterval(a),a=null);try{d=new EventSource(`/api/v1/logs/stream/${k}`),o=!0,x.classList.add("active"),x.textContent="\u{1F534} Live",x.title="Streaming - click to stop",I.style.display="none";const S=document.getElementById("logs-title");S.textContent.includes("\u{1F534}")||(S.innerHTML=S.textContent.replace("\u{1F4CB}","\u{1F4CB} \u{1F534}")),d.onmessage=A=>{try{const D=JSON.parse(A.data);if(D.error){console.error("Stream error:",D.error),y();return}const O=document.createElement("div");O.className="log-entry",O.style.cssText="display: flex; gap: 12px; padding: 6px 10px; border-bottom: 1px solid var(--border); font-size: 0.8rem; align-items: flex-start; font-family: monospace;";const R=(D.stream||"stdout")==="stderr",N=R?"var(--bad-fg)":"var(--fg)",_=`${R?"STDERR":"STDOUT"}`;for(O.innerHTML=`
${_}
${escapeHtml(D.text)}
- `,k.appendChild(O),k.scrollTop=k.scrollHeight;k.children.length>500;)k.removeChild(k.firstChild)}catch(D){console.error("Error parsing stream data:",D)}},d.onerror=A=>{console.error("EventSource error:",A),y()}}catch(I){console.error("Failed to start streaming:",I),y()}}function y(){d&&(d.close(),d=null),o=!1;const C=document.getElementById("logs-stream"),x=document.getElementById("logs-pause"),S=document.getElementById("logs-title");C&&(C.classList.remove("active"),C.textContent="\u{1F4E1} Live",C.title="Enable real-time streaming"),x&&(x.style.display=""),S&&(S.textContent=S.textContent.replace(" \u{1F534}","")),m&&h&&!a&&(a=setInterval(T,DC.POLL.LOGS))}async function u(C,x=100){try{const S=`/api/v1/logs/container/${C}?tail=${x}×tamps=true`,k=await fetch(S,{cache:"no-store",headers:{Accept:"application/json","Cache-Control":"no-cache"}});if(k.ok){const I=await k.json();return I.success&&I.logs?{logs:I.logs,count:I.count,containerName:I.containerName,containerId:I.containerId}:{error:I.error||"Failed to fetch container logs"}}else return{error:`HTTP ${k.status}: ${k.statusText}`}}catch(S){return console.error("Container logs fetch failed:",S),{error:S.message}}}function w(C){const x=document.createElement("div");x.className="log-entry",x.style.cssText="display: flex; gap: 12px; padding: 6px 10px; border-bottom: 1px solid var(--border); font-size: 0.8rem; align-items: flex-start; font-family: monospace;";const S=C.stream==="stderr"?"var(--bad-fg)":"var(--fg)",k=C.stream==="stderr"?'STDERR':'STDOUT';return x.innerHTML=` -
${k}
-
${escapeHtml(C.text)}
- `,x}async function T(){if(g||!h||!m)return;const C=parseInt(document.getElementById("log-lines").value),x=document.getElementById("logs-content");try{const S=await u(h,C);if(S.error){x.innerHTML=` + `,E.appendChild(O),E.scrollTop=E.scrollHeight;E.children.length>500;)E.removeChild(E.firstChild)}catch(D){console.error("Error parsing stream data:",D)}},d.onerror=A=>{console.error("EventSource error:",A),y()}}catch(S){console.error("Failed to start streaming:",S),y()}}function y(){d&&(d.close(),d=null),o=!1;const k=document.getElementById("logs-stream"),x=document.getElementById("logs-pause"),I=document.getElementById("logs-title");k&&(k.classList.remove("active"),k.textContent="\u{1F4E1} Live",k.title="Enable real-time streaming"),x&&(x.style.display=""),I&&(I.textContent=I.textContent.replace(" \u{1F534}","")),m&&h&&!a&&(a=setInterval(T,DC.POLL.LOGS))}async function u(k,x=100){try{const I=`/api/v1/logs/container/${k}?tail=${x}×tamps=true`,E=await fetch(I,{cache:"no-store",headers:{Accept:"application/json","Cache-Control":"no-cache"}});if(E.ok){const S=await E.json();return S.success&&S.logs?{logs:S.logs,count:S.count,containerName:S.containerName,containerId:S.containerId}:{error:S.error||"Failed to fetch container logs"}}else return{error:`HTTP ${E.status}: ${E.statusText}`}}catch(I){return console.error("Container logs fetch failed:",I),{error:I.message}}}function w(k){const x=document.createElement("div");x.className="log-entry",x.style.cssText="display: flex; gap: 12px; padding: 6px 10px; border-bottom: 1px solid var(--border); font-size: 0.8rem; align-items: flex-start; font-family: monospace;";const I=k.stream==="stderr"?"var(--bad-fg)":"var(--fg)",E=k.stream==="stderr"?'STDERR':'STDOUT';return x.innerHTML=` +
${E}
+
${escapeHtml(k.text)}
+ `,x}async function T(){if(f||!h||!m)return;const k=parseInt(document.getElementById("log-lines").value),x=document.getElementById("logs-content");try{const I=await u(h,k);if(I.error){x.innerHTML=`
\u26A0\uFE0F Error
-
${escapeHtml(S.error)}
+
${escapeHtml(I.error)}
`;return}x.innerHTML=`
Stream Log Output -
`,S.logs&&S.logs.length>0?(S.logs.forEach(k=>{const I=w(k);x.appendChild(I)}),x.scrollTop=x.scrollHeight):x.innerHTML+=` + `,I.logs&&I.logs.length>0?(I.logs.forEach(E=>{const S=w(E);x.appendChild(S)}),x.scrollTop=x.scrollHeight):x.innerHTML+=`
No logs available for this container -
`}catch(S){x.innerHTML=` + `}catch(I){x.innerHTML=`
- Failed to fetch logs: ${escapeHtml(S.message)} -
`}}function L(C,x){h=C,f=x,m=!0,v=!1,g=!1,y();const S=document.getElementById("logs-modal"),k=document.getElementById("logs-title"),I=document.getElementById("logs-pause"),A=document.getElementById("logs-stream");k.textContent=`\u{1F4CB} ${x} - Container Logs`,I.textContent="\u23F8\uFE0F Pause",I.classList.remove("paused"),A&&(A.style.display=""),S.classList.add("show"),T(),a=setInterval(T,DC.POLL.LOGS)}async function P(C,x=100){try{const S=`/api/v1/logs/file?path=${encodeURIComponent(C)}&tail=${x}`,k=await fetch(S,{cache:"no-store",headers:{Accept:"application/json","Cache-Control":"no-cache"}});if(k.ok){const I=await k.json();return I.success&&I.logs?{logs:I.logs,count:I.count,logPath:I.logPath,totalLines:I.totalLines}:{error:I.error||"Failed to fetch file logs"}}else return{error:(await k.json().catch(()=>({}))).error||`HTTP ${k.status}`}}catch(S){return console.error("File logs fetch failed:",S),{error:S.message}}}function E(C){const x=document.createElement("div");x.className="log-entry",x.style.cssText="display: flex; gap: 12px; padding: 6px 10px; border-bottom: 1px solid var(--border); font-size: 0.8rem; align-items: flex-start; font-family: monospace;";const S=C.text;let k="INFO",I="var(--fg)";S.match(/ERROR|FATAL|CRITICAL/i)?(k="ERROR",I="var(--bad-fg)"):S.match(/WARN|WARNING/i)?(k="WARN",I="#f39c12"):S.match(/DEBUG/i)&&(k="DEBUG",I="var(--muted)");const D=`${k}`;return x.innerHTML=` + Failed to fetch logs: ${escapeHtml(I.message)} + `}}function L(k,x){h=k,g=x,m=!0,v=!1,f=!1,y();const I=document.getElementById("logs-modal"),E=document.getElementById("logs-title"),S=document.getElementById("logs-pause"),A=document.getElementById("logs-stream");E.textContent=`\u{1F4CB} ${x} - Container Logs`,S.textContent="\u23F8\uFE0F Pause",S.classList.remove("paused"),A&&(A.style.display=""),I.classList.add("show"),T(),a=setInterval(T,DC.POLL.LOGS)}async function P(k,x=100){try{const I=`/api/v1/logs/file?path=${encodeURIComponent(k)}&tail=${x}`,E=await fetch(I,{cache:"no-store",headers:{Accept:"application/json","Cache-Control":"no-cache"}});if(E.ok){const S=await E.json();return S.success&&S.logs?{logs:S.logs,count:S.count,logPath:S.logPath,totalLines:S.totalLines}:{error:S.error||"Failed to fetch file logs"}}else return{error:(await E.json().catch(()=>({}))).error||`HTTP ${E.status}`}}catch(I){return console.error("File logs fetch failed:",I),{error:I.message}}}function C(k){const x=document.createElement("div");x.className="log-entry",x.style.cssText="display: flex; gap: 12px; padding: 6px 10px; border-bottom: 1px solid var(--border); font-size: 0.8rem; align-items: flex-start; font-family: monospace;";const I=k.text;let E="INFO",S="var(--fg)";I.match(/ERROR|FATAL|CRITICAL/i)?(E="ERROR",S="var(--bad-fg)"):I.match(/WARN|WARNING/i)?(E="WARN",S="#f39c12"):I.match(/DEBUG/i)&&(E="DEBUG",S="var(--muted)");const D=`${E}`;return x.innerHTML=`
${D}
-
${escapeHtml(S)}
- `,x}async function B(){if(g||!b||!v)return;const C=parseInt(document.getElementById("log-lines").value),x=document.getElementById("logs-content");try{const S=await P(b,C);if(S.error){x.innerHTML=` +
${escapeHtml(I)}
+ `,x}async function B(){if(f||!b||!v)return;const k=parseInt(document.getElementById("log-lines").value),x=document.getElementById("logs-content");try{const I=await P(b,k);if(I.error){x.innerHTML=`
\u26A0\uFE0F Error
-
${escapeHtml(S.error)}
+
${escapeHtml(I.error)}
`;return}x.innerHTML=`
- Log Output (${S.count} of ${S.totalLines} lines) -
`,S.logs&&S.logs.length>0?(S.logs.forEach(k=>{const I=E(k);x.appendChild(I)}),x.scrollTop=x.scrollHeight):x.innerHTML+=` + Log Output (${I.count} of ${I.totalLines} lines) + `,I.logs&&I.logs.length>0?(I.logs.forEach(E=>{const S=C(E);x.appendChild(S)}),x.scrollTop=x.scrollHeight):x.innerHTML+=`
No logs available in this file -
`}catch(S){x.innerHTML=` + `}catch(I){x.innerHTML=`
- Failed to fetch logs: ${escapeHtml(S.message)} -
`}}function $(C,x){b=C,s=x,v=!0,m=!1,g=!1;const S=document.getElementById("logs-modal"),k=document.getElementById("logs-title"),I=document.getElementById("logs-pause"),A=document.getElementById("logs-stream");k.textContent=`\u{1F4CB} ${x} - Application Logs`,I.textContent="\u23F8\uFE0F Pause",I.classList.remove("paused"),A&&(A.style.display="none"),S.classList.add("show"),B(),a=setInterval(B,DC.POLL.LOGS)}document.querySelector(".top")?.addEventListener("click",C=>{const x=C.target.closest('[id$="-logs"]');if(!x)return;const S=x.id.replace("-logs","");SITE.dnsServers[S]&&l(S)}),document.getElementById("logs-close")?.addEventListener("click",t),document.getElementById("logs-pause")?.addEventListener("click",()=>{g=!g;const C=document.getElementById("logs-pause");g?(C.textContent="\u25B6\uFE0F Resume",C.classList.add("paused")):(C.textContent="\u23F8\uFE0F Pause",C.classList.remove("paused"),n())}),document.getElementById("log-lines")?.addEventListener("change",()=>{g||n()}),document.getElementById("logs-stream")?.addEventListener("click",()=>{!m||!h||(o?y():i(h))}),document.getElementById("logs-modal")?.addEventListener("click",C=>{C.target.id==="logs-modal"&&t()}),document.addEventListener("keydown",C=>{C.key==="Escape"&&document.getElementById("logs-modal")?.classList.contains("show")&&t()}),window.openContainerLogsModal=L,window.openFileLogsModal=$,window.openLogsModal=l})(),(function(){injectModal("service-edit-modal",` + Failed to fetch logs: ${escapeHtml(I.message)} + `}}function $(k,x){b=k,r=x,v=!0,m=!1,f=!1;const I=document.getElementById("logs-modal"),E=document.getElementById("logs-title"),S=document.getElementById("logs-pause"),A=document.getElementById("logs-stream");E.textContent=`\u{1F4CB} ${x} - Application Logs`,S.textContent="\u23F8\uFE0F Pause",S.classList.remove("paused"),A&&(A.style.display="none"),I.classList.add("show"),B(),a=setInterval(B,DC.POLL.LOGS)}document.querySelector(".top")?.addEventListener("click",k=>{const x=k.target.closest('[id$="-logs"]');if(!x)return;const I=x.id.replace("-logs","");SITE.dnsServers[I]&&l(I)}),document.getElementById("logs-close")?.addEventListener("click",t),document.getElementById("logs-pause")?.addEventListener("click",()=>{f=!f;const k=document.getElementById("logs-pause");f?(k.textContent="\u25B6\uFE0F Resume",k.classList.add("paused")):(k.textContent="\u23F8\uFE0F Pause",k.classList.remove("paused"),n())}),document.getElementById("log-lines")?.addEventListener("change",()=>{f||n()}),document.getElementById("logs-stream")?.addEventListener("click",()=>{!m||!h||(o?y():i(h))}),document.getElementById("logs-modal")?.addEventListener("click",k=>{k.target.id==="logs-modal"&&t()}),document.addEventListener("keydown",k=>{k.key==="Escape"&&document.getElementById("logs-modal")?.classList.contains("show")&&t()}),window.openContainerLogsModal=L,window.openFileLogsModal=$,window.openLogsModal=l})(),(function(){injectModal("service-edit-modal",`

Edit Service

@@ -805,7 +805,7 @@ Instructions: ${l.instructionsLink}`:"";showNotification(`${s.toUpperCase()} upd
- `)})(),(function(){async function c(m){try{const b=await fetch(`/api/v1/caddy/cas?caddyfilePath=${encodeURIComponent(m)}`);if(!b.ok)throw new Error(`Failed to load CAs: ${b.status}`);const s=await b.json();if(s.success){const v=document.getElementById("existing-ca-select");return v.innerHTML="",s.cas.length===0?v.innerHTML='':(v.innerHTML='',s.cas.forEach(d=>{const o=document.createElement("option");typeof d=="object"?(o.value=d.id,o.textContent=d.displayName||d.name):(o.value=d,o.textContent=d),v.appendChild(o)})),s.data.cas}else throw new Error(s.message)}catch(b){console.error("Error loading CAs:",b);const s=document.getElementById("existing-ca-select");return s.innerHTML='',[]}}function a(m){const{subdomain:b,port:s,ip:v,sslType:d,caName:o,existingCa:p,enableAuth:r,enableCors:e,customHeaders:n,upstreamPath:l,healthCheck:t,timeout:i,tailscaleOnly:y}=m;let u=`${buildDomain(b)} { + `)})(),(function(){async function c(m){try{const b=await fetch(`/api/v1/caddy/cas?caddyfilePath=${encodeURIComponent(m)}`);if(!b.ok)throw new Error(`Failed to load CAs: ${b.status}`);const r=await b.json();if(r.success){const v=document.getElementById("existing-ca-select");return v.innerHTML="",r.cas.length===0?v.innerHTML='':(v.innerHTML='',r.cas.forEach(d=>{const o=document.createElement("option");typeof d=="object"?(o.value=d.id,o.textContent=d.displayName||d.name):(o.value=d,o.textContent=d),v.appendChild(o)})),r.data.cas}else throw new Error(r.message)}catch(b){console.error("Error loading CAs:",b);const r=document.getElementById("existing-ca-select");return r.innerHTML='',[]}}function a(m){const{subdomain:b,port:r,ip:v,sslType:d,caName:o,existingCa:p,enableAuth:s,enableCors:e,customHeaders:n,upstreamPath:l,healthCheck:t,timeout:i,tailscaleOnly:y}=m;let u=`${buildDomain(b)} { `;switch(y&&(u+=` @blocked not remote_ip 100.64.0.0/10 `,u+=` respond @blocked "Access denied. Tailscale connection required." 403 `),d){case"letsencrypt":break;case"caddy-managed":u+=` tls internal @@ -815,7 +815,7 @@ Instructions: ${l.instructionsLink}`:"";showNotification(`${s.toUpperCase()} upd `);break;case"custom-ca":o&&(u+=` tls { ca ${o} } -`);break}if(r&&(u+=` basicauth { +`);break}if(s&&(u+=` basicauth { admin $2a$14$hashed_password_here } `),e&&(u+=` header { @@ -827,7 +827,7 @@ Instructions: ${l.instructionsLink}`:"";showNotification(`${s.toUpperCase()} upd `,Object.entries(w).forEach(([T,L])=>{u+=` ${T} "${L}" `}),u+=` } `}catch{console.warn("Invalid JSON in custom headers")}return t&&(u+=` health_uri ${t} -`),u+=` reverse_proxy ${v}:${s} { +`),u+=` reverse_proxy ${v}:${r} { `,l&&l!=="/"&&(u+=` rewrite ${l} `),i&&i!==30&&(u+=` transport http { `,u+=` dial_timeout ${i}s @@ -835,14 +835,14 @@ Instructions: ${l.instructionsLink}`:"";showNotification(`${s.toUpperCase()} upd `,u+=` } `),u+=` } `,u+=`} -`,u}async function g(m,b,s=DC.DEFAULTS.TTL){const v=window.getToken(getPrimaryDnsId(),"admin");if(!v)throw new Error("DNS admin token not configured. Please set it in the Tokens menu.");const d=buildDomain(m),o=await secureFetch("/api/v1/dns/record",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:d,ip:b,ttl:s,token:v,server:SITE.dnsIp})});if(!o.ok){const r=await o.text();throw new Error(`DNS API Error: ${o.status} - ${r}`)}const p=await o.json();if(!p.success)throw new Error(`DNS Error: ${p.error||"Unknown error"}`);return p}async function h(m){const b={id:m.subdomain,name:m.name,logo:m.logo||`/assets/${m.subdomain}.png`};m.category&&(b.category=m.category),m.containerId&&(b.containerId=m.containerId);try{const s=await secureFetch("/api/v1/services",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(b)});if(!s.ok){const v=await s.json();throw new Error(v.error||"Failed to save service")}return await window.loadServices(),window.buildGrid(),b}catch(s){throw console.error("Failed to add service to config:",s),s}}async function f(m){const b=document.getElementById("service-subdomain-input").value.trim(),s=document.getElementById("service-ip-input").value.trim()||"localhost",v=document.getElementById("service-port-input").value.trim()||"80",d=await secureFetch("/api/v1/site",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:buildDomain(b),upstream:`${s}:${v}`,config:m})}),o=await d.json();if(!d.ok||!o.success)throw new Error(o.error||`Caddy API Error: ${d.status}`);return o}window.loadExistingCAs=c,window.generateCaddyConfig=a,window.createDnsRecord=g,window.addServiceToConfig=h,window.addToCaddyfile=f})(),(function(){let c=null;function a(s){c=s;const v=document.getElementById("service-edit-modal");document.getElementById("service-edit-title").textContent=`Edit ${s.name}`,document.getElementById("edit-service-name").value=s.name,document.getElementById("edit-service-url-display").textContent=s.url||buildServiceUrl(s.id),document.getElementById("edit-service-logo-preview").src=s.logo||`/assets/${s.id}.png`,document.getElementById("edit-subdomain").value=s.id,document.getElementById("edit-port").value=s.port||"",document.getElementById("edit-ip").value=s.ip||"localhost",document.getElementById("edit-tailscale-only").checked=s.tailscaleOnly||!1,document.getElementById("edit-logo-url").value=s.logo||"";const d=document.getElementById("edit-service-category");d&&(d.dataset.current=s.category||"",typeof window.populateCategorySelects=="function"&&window.populateCategorySelects()),v.classList.add("show")}function g(){closeModal("service-edit-modal"),c=null}async function h(){if(!c)return;const s=document.getElementById("edit-subdomain").value.trim().toLowerCase(),v=document.getElementById("edit-service-name").value.trim(),d=document.getElementById("edit-port").value.trim(),o=document.getElementById("edit-ip").value.trim()||"localhost",p=document.getElementById("edit-tailscale-only").checked,r=document.getElementById("edit-logo-url").value.trim(),e=document.getElementById("edit-service-category")?.value||"";if(!s){showNotification("Subdomain is required","warning");return}const n=c.id,l=[];if(s!==n&&l.push("subdomain"),v&&v!==c.name&&l.push("name"),d&&d!==String(c.port)&&l.push("port"),o!==c.ip&&l.push("ip"),p!==(c.tailscaleOnly||!1)&&l.push("tailscale"),r&&r!==c.logo&&l.push("logo"),e!==(c.category||"")&&l.push("category"),l.length===0){g();return}const t=document.getElementById("service-edit-save");t.textContent="Saving...",t.disabled=!0;try{const y=await(await secureFetch("/api/v1/services/update",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({oldSubdomain:n,newSubdomain:s,name:v||c.name,port:d||c.port,ip:o,tailscaleOnly:p,logo:r||void 0,category:e})})).json();if(!y.success)throw new Error(y.error||"Failed to update service");const u=window.APPS.findIndex(w=>w.id===n);u!==-1&&(window.APPS[u]={...window.APPS[u],id:s,name:v||window.APPS[u].name,port:d||window.APPS[u].port,ip:o,tailscaleOnly:p,logo:r||window.APPS[u].logo,category:e||void 0}),g(),window.buildGrid(),window.refreshAll()}catch(i){console.error("Error saving service changes:",i),showNotification(`Error saving changes: ${i.message}`,"error")}finally{t.textContent="Save Changes",t.disabled=!1}}document.getElementById("edit-logo-file")?.addEventListener("change",async s=>{const v=s.target.files[0];if(!v)return;if(!v.type.startsWith("image/")){showNotification("Please select an image file","warning");return}const d=new FileReader;d.onload=async o=>{const p=o.target.result;if(document.getElementById("edit-service-logo-preview").src=p,document.getElementById("edit-logo-url").value=p,c)try{const e=await(await secureFetch("/api/v1/assets/upload",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filename:`${c.id}.png`,data:p})})).json();e.success&&e.path&&(document.getElementById("edit-logo-url").value=e.path)}catch{}},d.readAsDataURL(v)}),document.getElementById("service-edit-cancel")?.addEventListener("click",g),document.getElementById("service-edit-save")?.addEventListener("click",h),document.getElementById("service-edit-modal")?.addEventListener("click",s=>{s.target.id==="service-edit-modal"&&g()});function f(s,v,d){return new Promise(o=>{const p=document.getElementById("delete-service-modal"),r=document.getElementById("delete-modal-title"),e=document.getElementById("delete-modal-message"),n=document.getElementById("delete-modal-container-info"),l=document.getElementById("delete-modal-container-name"),t=document.getElementById("delete-modal-help"),i=document.getElementById("delete-modal-cancel"),y=document.getElementById("delete-modal-remove"),u=document.getElementById("delete-modal-delete");r.textContent=`Delete "${s}"`,v?(e.innerHTML="This service has an associated Docker container.
Choose how to proceed:",n.style.display="block",l.textContent=`Container ID: ${d?.slice(0,12)||"Unknown"}`,t.style.display="block",u.style.display="block"):(e.textContent="Remove this service from the dashboard?",n.style.display="none",t.style.display="none",u.style.display="none");const w=()=>{p.classList.remove("show"),i.removeEventListener("click",T),y.removeEventListener("click",L),u.removeEventListener("click",P),p.removeEventListener("click",E)},T=()=>{w(),o(null)},L=()=>{w(),o(!1)},P=()=>{w(),o(!0)},E=B=>{B.target===p&&(w(),o(null))};i.addEventListener("click",T),y.addEventListener("click",L),u.addEventListener("click",P),p.addEventListener("click",E),p.classList.add("show")})}async function m(s,v,d){const o=document.getElementById(`update-btn-${d}`),p=o?.textContent;if(confirm(`Update ${v} to the latest version? +`,u}async function f(m,b,r=DC.DEFAULTS.TTL){const v=window.getToken(getPrimaryDnsId(),"admin");if(!v)throw new Error("DNS admin token not configured. Please set it in the Tokens menu.");const d=buildDomain(m),o=await secureFetch("/api/v1/dns/record",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:d,ip:b,ttl:r,token:v,server:SITE.dnsIp})});if(!o.ok){const s=await o.text();throw new Error(`DNS API Error: ${o.status} - ${s}`)}const p=await o.json();if(!p.success)throw new Error(`DNS Error: ${p.error||"Unknown error"}`);return p}async function h(m){const b={id:m.subdomain,name:m.name,logo:m.logo||`/assets/${m.subdomain}.png`};m.category&&(b.category=m.category),m.containerId&&(b.containerId=m.containerId);try{const r=await secureFetch("/api/v1/services",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(b)});if(!r.ok){const v=await r.json();throw new Error(v.error||"Failed to save service")}return await window.loadServices(),window.buildGrid(),b}catch(r){throw console.error("Failed to add service to config:",r),r}}async function g(m){const b=document.getElementById("service-subdomain-input").value.trim(),r=document.getElementById("service-ip-input").value.trim()||"localhost",v=document.getElementById("service-port-input").value.trim()||"80",d=await secureFetch("/api/v1/site",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:buildDomain(b),upstream:`${r}:${v}`,config:m})}),o=await d.json();if(!d.ok||!o.success)throw new Error(o.error||`Caddy API Error: ${d.status}`);return o}window.loadExistingCAs=c,window.generateCaddyConfig=a,window.createDnsRecord=f,window.addServiceToConfig=h,window.addToCaddyfile=g})(),(function(){let c=null;function a(r){c=r;const v=document.getElementById("service-edit-modal");document.getElementById("service-edit-title").textContent=`Edit ${r.name}`,document.getElementById("edit-service-name").value=r.name,document.getElementById("edit-service-url-display").textContent=r.url||buildServiceUrl(r.id),document.getElementById("edit-service-logo-preview").src=r.logo||`/assets/${r.id}.png`,document.getElementById("edit-subdomain").value=r.id,document.getElementById("edit-port").value=r.port||"",document.getElementById("edit-ip").value=r.ip||"localhost",document.getElementById("edit-tailscale-only").checked=r.tailscaleOnly||!1,document.getElementById("edit-logo-url").value=r.logo||"";const d=document.getElementById("edit-service-category");d&&(d.dataset.current=r.category||"",typeof window.populateCategorySelects=="function"&&window.populateCategorySelects()),v.classList.add("show")}function f(){closeModal("service-edit-modal"),c=null}async function h(){if(!c)return;const r=document.getElementById("edit-subdomain").value.trim().toLowerCase(),v=document.getElementById("edit-service-name").value.trim(),d=document.getElementById("edit-port").value.trim(),o=document.getElementById("edit-ip").value.trim()||"localhost",p=document.getElementById("edit-tailscale-only").checked,s=document.getElementById("edit-logo-url").value.trim(),e=document.getElementById("edit-service-category")?.value||"";if(!r){showNotification("Subdomain is required","warning");return}const n=c.id,l=[];if(r!==n&&l.push("subdomain"),v&&v!==c.name&&l.push("name"),d&&d!==String(c.port)&&l.push("port"),o!==c.ip&&l.push("ip"),p!==(c.tailscaleOnly||!1)&&l.push("tailscale"),s&&s!==c.logo&&l.push("logo"),e!==(c.category||"")&&l.push("category"),l.length===0){f();return}const t=document.getElementById("service-edit-save");t.textContent="Saving...",t.disabled=!0;try{const y=await(await secureFetch("/api/v1/services/update",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({oldSubdomain:n,newSubdomain:r,name:v||c.name,port:d||c.port,ip:o,tailscaleOnly:p,logo:s||void 0,category:e})})).json();if(!y.success)throw new Error(y.error||"Failed to update service");const u=window.APPS.findIndex(w=>w.id===n);u!==-1&&(window.APPS[u]={...window.APPS[u],id:r,name:v||window.APPS[u].name,port:d||window.APPS[u].port,ip:o,tailscaleOnly:p,logo:s||window.APPS[u].logo,category:e||void 0}),f(),window.buildGrid(),window.refreshAll()}catch(i){console.error("Error saving service changes:",i),showNotification(`Error saving changes: ${i.message}`,"error")}finally{t.textContent="Save Changes",t.disabled=!1}}document.getElementById("edit-logo-file")?.addEventListener("change",async r=>{const v=r.target.files[0];if(!v)return;if(!v.type.startsWith("image/")){showNotification("Please select an image file","warning");return}const d=new FileReader;d.onload=async o=>{const p=o.target.result;if(document.getElementById("edit-service-logo-preview").src=p,document.getElementById("edit-logo-url").value=p,c)try{const e=await(await secureFetch("/api/v1/assets/upload",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filename:`${c.id}.png`,data:p})})).json();e.success&&e.path&&(document.getElementById("edit-logo-url").value=e.path)}catch{}},d.readAsDataURL(v)}),document.getElementById("service-edit-cancel")?.addEventListener("click",f),document.getElementById("service-edit-save")?.addEventListener("click",h),document.getElementById("service-edit-modal")?.addEventListener("click",r=>{r.target.id==="service-edit-modal"&&f()});function g(r,v,d){return new Promise(o=>{const p=document.getElementById("delete-service-modal"),s=document.getElementById("delete-modal-title"),e=document.getElementById("delete-modal-message"),n=document.getElementById("delete-modal-container-info"),l=document.getElementById("delete-modal-container-name"),t=document.getElementById("delete-modal-help"),i=document.getElementById("delete-modal-cancel"),y=document.getElementById("delete-modal-remove"),u=document.getElementById("delete-modal-delete");s.textContent=`Delete "${r}"`,v?(e.innerHTML="This service has an associated Docker container.
Choose how to proceed:",n.style.display="block",l.textContent=`Container ID: ${d?.slice(0,12)||"Unknown"}`,t.style.display="block",u.style.display="block"):(e.textContent="Remove this service from the dashboard?",n.style.display="none",t.style.display="none",u.style.display="none");const w=()=>{p.classList.remove("show"),i.removeEventListener("click",T),y.removeEventListener("click",L),u.removeEventListener("click",P),p.removeEventListener("click",C)},T=()=>{w(),o(null)},L=()=>{w(),o(!1)},P=()=>{w(),o(!0)},C=B=>{B.target===p&&(w(),o(null))};i.addEventListener("click",T),y.addEventListener("click",L),u.addEventListener("click",P),p.addEventListener("click",C),p.classList.add("show")})}async function m(r,v,d){const o=document.getElementById(`update-btn-${d}`),p=o?.textContent;if(confirm(`Update ${v} to the latest version? This will: 1. Pull the latest image 2. Stop the container 3. Recreate with same settings -The service will be briefly unavailable.`))try{o&&(o.textContent="\u{1F504}",o.disabled=!0,o.title="Updating...");const e=await(await secureFetch(`/api/v1/containers/${s}/update`,{method:"POST"})).json();if(e.success){const n=window.APPS.find(l=>l.id===d);n&&e.newContainerId&&(n.containerId=e.newContainerId),o&&(o.textContent="\u2705",o.title="Updated successfully!",setTimeout(()=>{o.textContent=p,o.disabled=!1,o.title="Update container to latest version"},3e3)),setTimeout(()=>window.refreshAll(),2e3),showNotification(`${v} updated successfully!`,"success")}else throw new Error(e.error||"Update failed")}catch(r){console.error("Update error:",r),o&&(o.textContent="\u274C",o.title="Update failed",setTimeout(()=>{o.textContent=p,o.disabled=!1,o.title="Update container to latest version"},3e3)),showNotification(`Failed to update ${v}: ${r.message}`,"error")}}async function b(s,v){const d=window.APPS.find(u=>u.id===s),o=d?buildDomain(d.id):null,p=d?.containerId,r=await f(v||s,p,d?.containerId);if(r===null)return;let e={dashboard:!1,container:null,dns:null,caddy:null,service:null};if(r&&p)try{const u=new URLSearchParams({containerId:d.containerId,subdomain:d.id,ip:d.ip||"localhost",deleteContainer:"true"}),T=await(await secureFetch(`/api/v1/apps/${encodeURIComponent(d.id)}?${u.toString()}`,{method:"DELETE"})).json();T.success?e={...e,...T.results,dashboard:!1}:console.error("App removal failed:",T.error)}catch(u){console.error("App removal error:",u)}else if(r&&o){try{const u=d?.ip||"localhost",T=await(await secureFetch(`/api/v1/dns/record?domain=${encodeURIComponent(o)}&type=A&ipAddress=${encodeURIComponent(u)}&server=${SITE.dnsIp}`,{method:"DELETE"})).json();e.dns=T.success?"deleted":T.error||"failed"}catch(u){e.dns=u.message}try{const w=await(await secureFetch(`/api/v1/site/${encodeURIComponent(o)}`,{method:"DELETE"})).json();e.caddy=w.success||w.error&&w.error.includes("not found")?"removed":w.error||"failed"}catch(u){e.caddy=u.message}}const n=window.APPS.findIndex(u=>u.id===s);n>-1&&(window.APPS.splice(n,1),e.dashboard=!0);try{const u=safeGetJSON("custom-apps",[]),w=u.findIndex(T=>T.id===s);w>-1&&(u.splice(w,1),safeSet("custom-apps",JSON.stringify(u)))}catch{}try{const w=await(await secureFetch(`/api/v1/services/${encodeURIComponent(s)}`,{method:"DELETE"})).json();e.service=w.success?"removed":w.error||"failed"}catch(u){e.service=u.message}window.buildGrid(),window.refreshAll();let l=!1,t=[];e.dashboard||(l=!0,t.push("\u2717 Failed to remove from dashboard"));const i=["removed","already removed","not found","deleted","kept (user choice)","skipped","no such record","does not exist"],y=u=>!u||i.some(w=>u.toLowerCase().includes(w.toLowerCase()));e.container&&!y(e.container)&&(l=!0,t.push(`\u26A0 Container: ${e.container}`)),e.dns&&!y(e.dns)&&(l=!0,t.push(`\u26A0 DNS Record: ${e.dns}`)),e.caddy&&!y(e.caddy)&&(l=!0,t.push(`\u26A0 Caddy Config: ${e.caddy}`)),e.service&&!y(e.service)&&(l=!0,t.push(`\u26A0 Service File: ${e.service}`)),l&&showNotification(`Error deleting "${v||s}": ${t.join(", ")}`,"error",6e3)}window.openServiceEditModal=a,window.showDeleteModal=f,window.updateContainer=m,window.deleteService=b})(),(function(){function c(e){return e.toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,"").replace(/-+/g,"-").replace(/^-|-$/g,"")}function a(){return SITE.defaults?.sslType||(SITE.configurationType==="public"?"letsencrypt":"caddy-managed")}function g(){const e=document.getElementById("service-subdomain-input").value||"subdomain",n=document.getElementById("service-ip-input").value||h.lan||"localhost",l=document.getElementById("service-port-input").value||DC.DEFAULTS.SERVICE_PORT,t=document.getElementById("ssl-type-select").value,i=document.getElementById("ca-name-input").value||"sami-ca",y=document.getElementById("existing-ca-select").value,u=document.getElementById("enable-auth").checked,w=document.getElementById("enable-cors").checked,T=document.getElementById("custom-headers-input").value,L=document.getElementById("upstream-path-input").value||"/",P=document.getElementById("health-check-input").value,E=document.getElementById("timeout-input").value||30,B=document.getElementById("dns-preview");B&&(B.textContent=`${buildDomain(e)} \u2192 ${n}`);const $=document.getElementById("url-preview");$&&($.textContent=buildServiceUrl(e));const C={subdomain:e,port:l,ip:n,sslType:t,caName:i,existingCa:y,enableAuth:u,enableCors:w,customHeaders:T,upstreamPath:L,healthCheck:P,timeout:E},x=window.generateCaddyConfig(C),S=document.getElementById("caddy-config-preview");S&&(S.value=x)}const h={localhost:"127.0.0.1",lan:"",tailscale:""};async function f(){try{const t=await fetch("/api/v1/network/ips",{signal:AbortSignal.timeout(2e3)});if(t.ok){const i=await t.json();i.lan&&(h.lan=i.lan),i.tailscale&&(h.tailscale=i.tailscale)}}catch{}const e=document.getElementById("quick-ip-lan"),n=document.getElementById("quick-ip-tailscale");e&&(h.lan?(e.dataset.ip=h.lan,e.textContent=`LAN (${h.lan})`,e.title=`LAN IP: ${h.lan}`):e.style.display="none"),n&&(h.tailscale?(n.dataset.ip=h.tailscale,n.textContent=`Tailscale (${h.tailscale})`,n.title=`Tailscale IP: ${h.tailscale}`):n.style.display="none");const l=document.getElementById("service-ip-input");l&&!l.value&&h.lan&&(l.value=h.lan)}function m(){document.querySelectorAll(".quick-ip-btn").forEach(e=>{e.addEventListener("click",()=>{const n=e.dataset.ip;n&&(document.getElementById("service-ip-input").value=n,document.querySelectorAll(".quick-ip-btn").forEach(l=>l.classList.remove("active")),e.classList.add("active"),g())})}),document.getElementById("service-ip-input")?.addEventListener("input",e=>{const n=e.target.value;document.querySelectorAll(".quick-ip-btn").forEach(l=>{l.classList.toggle("active",l.dataset.ip===n)})})}async function b(){const e=document.getElementById("add-service-modal");e.classList.add("show");const n=e.querySelector(".weather-modal-content");n&&(n.scrollTop=0),document.body.style.overflow="hidden";const l=document.getElementById("ssl-type-select");l&&(l.value=a()),await f();const t=document.getElementById("caddyfile-path-input").value||DC.DEFAULTS.CADDYFILE;await window.loadExistingCAs(t);const i=document.getElementById("manual-tailscale-status"),y=document.getElementById("manual-tailscale-only");try{const w=await(await fetch("/api/v1/tailscale/status")).json();w.success&&w.installed&&w.connected?(i.innerHTML=` +The service will be briefly unavailable.`))try{o&&(o.textContent="\u{1F504}",o.disabled=!0,o.title="Updating...");const e=await(await secureFetch(`/api/v1/containers/${r}/update`,{method:"POST"})).json();if(e.success){const n=window.APPS.find(l=>l.id===d);n&&e.newContainerId&&(n.containerId=e.newContainerId),o&&(o.textContent="\u2705",o.title="Updated successfully!",setTimeout(()=>{o.textContent=p,o.disabled=!1,o.title="Update container to latest version"},3e3)),setTimeout(()=>window.refreshAll(),2e3),showNotification(`${v} updated successfully!`,"success")}else throw new Error(e.error||"Update failed")}catch(s){console.error("Update error:",s),o&&(o.textContent="\u274C",o.title="Update failed",setTimeout(()=>{o.textContent=p,o.disabled=!1,o.title="Update container to latest version"},3e3)),showNotification(`Failed to update ${v}: ${s.message}`,"error")}}async function b(r,v){const d=window.APPS.find(u=>u.id===r),o=d?buildDomain(d.id):null,p=d?.containerId,s=await g(v||r,p,d?.containerId);if(s===null)return;let e={dashboard:!1,container:null,dns:null,caddy:null,service:null};if(s&&p)try{const u=new URLSearchParams({containerId:d.containerId,subdomain:d.id,ip:d.ip||"localhost",deleteContainer:"true"}),T=await(await secureFetch(`/api/v1/apps/${encodeURIComponent(d.id)}?${u.toString()}`,{method:"DELETE"})).json();T.success?e={...e,...T.results,dashboard:!1}:console.error("App removal failed:",T.error)}catch(u){console.error("App removal error:",u)}else if(s&&o){try{const u=d?.ip||"localhost",T=await(await secureFetch(`/api/v1/dns/record?domain=${encodeURIComponent(o)}&type=A&ipAddress=${encodeURIComponent(u)}&server=${SITE.dnsIp}`,{method:"DELETE"})).json();e.dns=T.success?"deleted":T.error||"failed"}catch(u){e.dns=u.message}try{const w=await(await secureFetch(`/api/v1/site/${encodeURIComponent(o)}`,{method:"DELETE"})).json();e.caddy=w.success||w.error&&w.error.includes("not found")?"removed":w.error||"failed"}catch(u){e.caddy=u.message}}const n=window.APPS.findIndex(u=>u.id===r);n>-1&&(window.APPS.splice(n,1),e.dashboard=!0);try{const u=safeGetJSON("custom-apps",[]),w=u.findIndex(T=>T.id===r);w>-1&&(u.splice(w,1),safeSet("custom-apps",JSON.stringify(u)))}catch{}try{const w=await(await secureFetch(`/api/v1/services/${encodeURIComponent(r)}`,{method:"DELETE"})).json();e.service=w.success?"removed":w.error||"failed"}catch(u){e.service=u.message}window.buildGrid(),window.refreshAll();let l=!1,t=[];e.dashboard||(l=!0,t.push("\u2717 Failed to remove from dashboard"));const i=["removed","already removed","not found","deleted","kept (user choice)","skipped","no such record","does not exist"],y=u=>!u||i.some(w=>u.toLowerCase().includes(w.toLowerCase()));e.container&&!y(e.container)&&(l=!0,t.push(`\u26A0 Container: ${e.container}`)),e.dns&&!y(e.dns)&&(l=!0,t.push(`\u26A0 DNS Record: ${e.dns}`)),e.caddy&&!y(e.caddy)&&(l=!0,t.push(`\u26A0 Caddy Config: ${e.caddy}`)),e.service&&!y(e.service)&&(l=!0,t.push(`\u26A0 Service File: ${e.service}`)),l&&showNotification(`Error deleting "${v||r}": ${t.join(", ")}`,"error",6e3)}window.openServiceEditModal=a,window.showDeleteModal=g,window.updateContainer=m,window.deleteService=b})(),(function(){function c(e){return e.toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,"").replace(/-+/g,"-").replace(/^-|-$/g,"")}function a(){return SITE.defaults?.sslType||(SITE.configurationType==="public"?"letsencrypt":"caddy-managed")}function f(){const e=document.getElementById("service-subdomain-input").value||"subdomain",n=document.getElementById("service-ip-input").value||h.lan||"localhost",l=document.getElementById("service-port-input").value||DC.DEFAULTS.SERVICE_PORT,t=document.getElementById("ssl-type-select").value,i=document.getElementById("ca-name-input").value||"sami-ca",y=document.getElementById("existing-ca-select").value,u=document.getElementById("enable-auth").checked,w=document.getElementById("enable-cors").checked,T=document.getElementById("custom-headers-input").value,L=document.getElementById("upstream-path-input").value||"/",P=document.getElementById("health-check-input").value,C=document.getElementById("timeout-input").value||30,B=document.getElementById("dns-preview");B&&(B.textContent=`${buildDomain(e)} \u2192 ${n}`);const $=document.getElementById("url-preview");$&&($.textContent=buildServiceUrl(e));const k={subdomain:e,port:l,ip:n,sslType:t,caName:i,existingCa:y,enableAuth:u,enableCors:w,customHeaders:T,upstreamPath:L,healthCheck:P,timeout:C},x=window.generateCaddyConfig(k),I=document.getElementById("caddy-config-preview");I&&(I.value=x)}const h={localhost:"127.0.0.1",lan:"",tailscale:""};async function g(){try{const t=await fetch("/api/v1/network/ips",{signal:AbortSignal.timeout(2e3)});if(t.ok){const i=await t.json();i.lan&&(h.lan=i.lan),i.tailscale&&(h.tailscale=i.tailscale)}}catch{}const e=document.getElementById("quick-ip-lan"),n=document.getElementById("quick-ip-tailscale");e&&(h.lan?(e.dataset.ip=h.lan,e.textContent=`LAN (${h.lan})`,e.title=`LAN IP: ${h.lan}`):e.style.display="none"),n&&(h.tailscale?(n.dataset.ip=h.tailscale,n.textContent=`Tailscale (${h.tailscale})`,n.title=`Tailscale IP: ${h.tailscale}`):n.style.display="none");const l=document.getElementById("service-ip-input");l&&!l.value&&h.lan&&(l.value=h.lan)}function m(){document.querySelectorAll(".quick-ip-btn").forEach(e=>{e.addEventListener("click",()=>{const n=e.dataset.ip;n&&(document.getElementById("service-ip-input").value=n,document.querySelectorAll(".quick-ip-btn").forEach(l=>l.classList.remove("active")),e.classList.add("active"),f())})}),document.getElementById("service-ip-input")?.addEventListener("input",e=>{const n=e.target.value;document.querySelectorAll(".quick-ip-btn").forEach(l=>{l.classList.toggle("active",l.dataset.ip===n)})})}async function b(){const e=document.getElementById("add-service-modal");e.classList.add("show");const n=e.querySelector(".weather-modal-content");n&&(n.scrollTop=0),document.body.style.overflow="hidden";const l=document.getElementById("ssl-type-select");l&&(l.value=a()),await g();const t=document.getElementById("caddyfile-path-input").value||DC.DEFAULTS.CADDYFILE;await window.loadExistingCAs(t);const i=document.getElementById("manual-tailscale-status"),y=document.getElementById("manual-tailscale-only");try{const w=await(await fetch("/api/v1/tailscale/status")).json();w.success&&w.installed&&w.connected?(i.innerHTML=` \u2713 Connected ${w.self?.hostname} (${w.self?.ip}) - `,y.disabled=!1):w.installed?(i.innerHTML='\u26A0 Not connected',y.disabled=!0):(i.innerHTML='Not available',y.disabled=!0)}catch{i.innerHTML='Could not check',y.disabled=!0}y.checked=!1,g()}function s(){const e=document.getElementById("service-type-local"),n=document.getElementById("service-type-external"),l=document.getElementById("local-service-config"),t=document.getElementById("external-service-config"),i=document.getElementById("tab-local"),y=document.getElementById("tab-external");function u(){e.checked?(l.style.display="grid",t.style.display="none",i&&(i.style.background="var(--accent)",i.style.color="var(--bg)"),y&&(y.style.background="transparent",y.style.color="var(--muted)")):(l.style.display="none",t.style.display="block",y&&(y.style.background="var(--accent)",y.style.color="var(--bg)"),i&&(i.style.background="transparent",i.style.color="var(--muted)"))}e?.addEventListener("change",u),n?.addEventListener("change",u)}function v(){const e=document.getElementById("service-name-input"),n=document.getElementById("service-subdomain-input"),l=document.getElementById("subdomain-preview");let t=!1;e?.addEventListener("input",()=>{const L=c(e.value);!t&&n&&(n.value=L),l&&(l.textContent=L?`\u2192 ${buildDomain(L)}`:""),g()}),n?.addEventListener("input",()=>{t=n.value!==c(e?.value||"");const L=n.value.trim()||c(e?.value||"");l&&(l.textContent=L?`\u2192 ${buildDomain(L)}`:""),g()});const i=document.getElementById("external-service-name"),y=document.getElementById("external-service-subdomain"),u=document.getElementById("external-subdomain-preview"),w=document.getElementById("external-domain-preview");let T=!1;i?.addEventListener("input",()=>{const L=c(i.value);!T&&y&&(y.value=L);const P=y?.value||L;u&&(u.textContent=P?`\u2192 ${buildDomain(P)}`:""),w&&(w.textContent=P?buildDomain(P):"")}),y?.addEventListener("input",()=>{T=y.value!==c(i?.value||"");const L=y.value.trim()||c(i?.value||"");u&&(u.textContent=L?`\u2192 ${buildDomain(L)}`:""),w&&(w.textContent=L?buildDomain(L):"")})}async function d(){const e=document.getElementById("external-service-name").value.trim(),n=document.getElementById("external-service-url").value.trim(),l=(document.getElementById("external-service-subdomain").value.trim()||c(e)).toLowerCase(),t=document.getElementById("external-service-logo").value.trim(),i=document.getElementById("external-service-icon").value.trim(),y=document.getElementById("external-create-dns").checked,u=document.getElementById("external-create-caddy").checked,w=document.getElementById("external-proxy-ip").value.trim()||SITE.dnsIp||"localhost",T=document.getElementById("external-preserve-host").checked,L=document.getElementById("external-follow-redirects").checked,P=document.getElementById("external-service-category")?.value||"";if(!e||!n){showNotification("Please fill in Name and External URL","warning");return}if(!l){showNotification("Could not derive subdomain from name. Please set one in Options.","warning");return}if(!n.startsWith("http://")&&!n.startsWith("https://")){showNotification("External URL must start with http:// or https://","warning");return}const E=buildDomain(l);try{const B={dns:null,caddy:null,dashboard:!1};if(y)if(window.getToken(getPrimaryDnsId(),"admin"))try{const A=await(await secureFetch("/api/v1/dns/record",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:E,ip:w,ttl:DC.DEFAULTS.TTL,server:SITE.dnsIp})})).json();B.dns=A.success?"created":A.error||"failed"}catch(I){B.dns=I.message}else B.dns="no admin token (configure in \u{1F511} Tokens)";if(u)try{const k={subdomain:l,externalUrl:n,preserveHost:T,followRedirects:L,sslType:"caddy-managed",caddyfilePath:DC.DEFAULTS.CADDYFILE,reloadCaddy:!0},A=await(await secureFetch("/api/v1/site/external",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(k)})).json();B.caddy=A.success?"created":A.error||"failed"}catch(k){B.caddy=k.message}const $={id:l,name:e,url:`https://${E}`,externalUrl:n,logo:t||i||"\u{1F310}",isExternal:!0,isCustom:!0};P&&($.category=P),window.APPS.push($),B.dashboard=!0;const C=["plex","router","chat","sync","torrent","radarr","sonarr","prowlarr","portainer","requests","jellyfin","emby"],x=window.APPS.filter(k=>!C.includes(k.id));safeSet("custom-services",JSON.stringify(x));try{await secureFetch("/api/v1/services",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(window.APPS)})}catch(k){console.warn("Failed to save to services.json:",k)}window.buildGrid(),window.refreshAll(),o();const S=[`External service "${e}" added!`];y&&S.push(`DNS: ${B.dns==="created"?"\u2713":"\u26A0 "+B.dns}`),u&&S.push(`Caddy: ${B.caddy==="created"?"\u2713":"\u26A0 "+B.caddy}`),S.push(`Access at: https://${E}`),showNotification(S.join(" | "),"success",6e3)}catch(B){console.error("Failed to create external service:",B),showNotification(`Failed to create external service: ${B.message}`,"error")}}function o(){closeModal("add-service-modal"),document.body.style.overflow="",document.getElementById("service-name-input").value="",document.getElementById("service-subdomain-input").value="",document.getElementById("service-port-input").value="",document.getElementById("service-ip-input").value=h.lan||"",document.getElementById("service-logo-input").value="",document.getElementById("dns-ttl-input").value=DC.DEFAULTS.TTL,document.getElementById("ssl-type-select").value=a(),document.getElementById("ca-name-input").value="",document.getElementById("enable-auth").checked=!1,document.getElementById("enable-cors").checked=!1,document.getElementById("custom-headers-input").value="",document.getElementById("upstream-path-input").value="/",document.getElementById("health-check-input").value="",document.getElementById("timeout-input").value="30";const e=document.getElementById("subdomain-preview");e&&(e.textContent="");const n=document.getElementById("external-subdomain-preview");n&&(n.textContent="");const l=document.getElementById("external-service-name");l&&(l.value="");const t=document.getElementById("external-service-subdomain");t&&(t.value="");const i=document.getElementById("external-service-url");i&&(i.value="");const y=document.getElementById("external-service-logo");y&&(y.value="");const u=document.getElementById("external-service-icon");u&&(u.value="");const w=document.getElementById("local-advanced-options");w&&w.removeAttribute("open");const T=document.getElementById("external-advanced-options");T&&T.removeAttribute("open");const L=document.getElementById("service-type-local");L&&(L.checked=!0);const P=document.getElementById("local-service-config"),E=document.getElementById("external-service-config");P&&(P.style.display="grid"),E&&(E.style.display="none");const B=document.getElementById("tab-local"),$=document.getElementById("tab-external");B&&(B.style.background="var(--accent)",B.style.color="var(--bg)"),$&&($.style.background="transparent",$.style.color="var(--muted)")}async function p(){const e=document.getElementById("service-name-input").value.trim(),n=(document.getElementById("service-subdomain-input").value.trim()||c(e)).toLowerCase(),l=document.getElementById("service-port-input").value.trim(),t=document.getElementById("service-ip-input").value.trim(),i=document.getElementById("service-logo-input").value.trim(),y=document.getElementById("create-dns-record").checked,u=parseInt(document.getElementById("dns-ttl-input").value)||DC.DEFAULTS.TTL,w=document.getElementById("manual-tailscale-only")?.checked||!1,T=document.getElementById("ssl-type-select")?.value||"caddy-managed",L=document.getElementById("ca-name-input")?.value||"",P=document.getElementById("existing-ca-select")?.value||"",E=document.getElementById("enable-auth")?.checked||!1,B=document.getElementById("enable-cors")?.checked||!1,$=document.getElementById("custom-headers-input")?.value||"",C=document.getElementById("upstream-path-input")?.value||"/",x=document.getElementById("health-check-input")?.value||"",S=document.getElementById("timeout-input")?.value||30,I=(document.getElementById("service-category-input")||document.getElementById("external-service-category"))?.value||"",A=window.getToken(getPrimaryDnsId(),"admin");if(!e||!l||!t){showNotification("Please fill in Name, Port, and IP Address","warning");return}if(!n){showNotification("Could not derive subdomain from name. Please set one in Options.","warning");return}if(y&&!A){showNotification("DNS Admin token required. Configure it in the Tokens menu first.","warning");return}const D={dns:null,caddy:null,dashboard:!1};try{if(y)try{await window.createDnsRecord(n,t,u),D.dns="created"}catch(N){throw console.error("DNS creation failed:",N),D.dns=N.message,new Error(`DNS creation failed: ${N.message}`)}else D.dns="skipped";const O=window.generateCaddyConfig({subdomain:n,port:l,ip:t,sslType:T,caName:L,existingCa:P,enableAuth:E,enableCors:B,customHeaders:$,upstreamPath:C,healthCheck:x,timeout:S,tailscaleOnly:w});try{const U=await(await secureFetch("/api/v1/site",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:buildDomain(n),upstream:`${t}:${l}`,config:O})})).json();if(U.success)D.caddy="added & reloaded";else throw console.error("Caddy configuration failed:",U.error),D.caddy=U.error||"failed",new Error(`Caddy configuration failed: ${U.error}`)}catch(N){throw console.error("Caddy API error:",N),D.caddy=N.message,new Error(`Caddy API error: ${N.message}`)}const M={name:e,subdomain:n,port:l,ip:t,logo:i||`/assets/${n}.png`,tailscaleOnly:w||!1};I&&(M.category=I),await window.addServiceToConfig(M),D.dashboard=!0;const R=[`DNS: ${D.dns==="created"?"\u2713":D.dns==="skipped"?"\u25CB":"\u2717"}`,`Caddy: ${D.caddy==="added & reloaded"?"\u2713":"\u2717"}`,`Dashboard: ${D.dashboard?"\u2713":"\u2717"}`];showNotification(`Service "${e}" created! ${R.join(" | ")} \u2014 ${buildServiceUrl(n)}${w?" (Tailscale)":""}`,"success",6e3),o(),window.buildGrid(),window.refreshAll()}catch(O){console.error("Error creating service:",O),showNotification(`Error creating "${e}": ${O.message}`,"error",6e3)}}document.getElementById("add-service")?.addEventListener("click",b),document.getElementById("add-service-cancel")?.addEventListener("click",o),document.getElementById("add-service-create")?.addEventListener("click",()=>{document.querySelector('input[name="service-type"]:checked')?.value==="external"?d():p()}),s(),v(),m(),document.getElementById("ssl-type-select")?.addEventListener("change",e=>{const n=document.getElementById("existing-ca-config"),l=document.getElementById("custom-ca-config");n.style.display="none",l.style.display="none",e.target.value==="existing-ca"?n.style.display="block":e.target.value==="custom-ca"&&(l.style.display="block"),g()}),document.getElementById("refresh-cas")?.addEventListener("click",async()=>{const e=document.getElementById("refresh-cas"),n=e.textContent;e.textContent="\u231B Loading...",e.disabled=!0;try{const l=document.getElementById("caddyfile-path-input").value||DC.DEFAULTS.CADDYFILE;await window.loadExistingCAs(l),e.textContent="\u2705 Refreshed"}catch(l){e.textContent="\u274C Failed",console.error("Failed to refresh CAs:",l)}setTimeout(()=>{e.textContent=n,e.disabled=!1},2e3)}),document.getElementById("create-dns-record")?.addEventListener("change",e=>{const n=document.getElementById("dns-config");n.style.display=e.target.checked?"block":"none"}),["service-subdomain-input","service-ip-input","service-port-input","ca-name-input","existing-ca-select","enable-auth","enable-cors","custom-headers-input","upstream-path-input","health-check-input","timeout-input"].forEach(e=>{const n=document.getElementById(e);n&&(n.addEventListener("input",g),n.addEventListener("change",g))});function r(){const e=safeGet("custom-services");if(e)try{JSON.parse(e).forEach(l=>{window.APPS.find(t=>t.id===l.id)||window.APPS.push(l)})}catch(n){console.warn("Failed to load custom services:",n)}}r(),window.openAddServiceModal=b,window.closeAddServiceModal=o})(),(function(){let c=null,a=1e3;const g=3e4;function h(){if(c)try{c.close()}catch{}c=new EventSource("/api/v1/events/stream"),c.addEventListener("connected",()=>{a=1e3,debug("[SSE] Connected to event stream")}),c.addEventListener("status-change",f=>{try{const m=JSON.parse(f.data);if(m.serviceId&&typeof window.setBadge=="function"){const b=m.status==="up"||m.status==="healthy";window.setBadge(m.serviceId,b,m.responseTime||null)}}catch{}}),c.addEventListener("resource-alert",f=>{try{const m=JSON.parse(f.data),b=`${m.containerName||m.containerId}: ${m.metric} at ${m.value}% (threshold: ${m.threshold}%)`;typeof showNotification=="function"&&showNotification(b,"warning")}catch{}}),c.addEventListener("auto-restart",f=>{try{const m=JSON.parse(f.data);typeof showNotification=="function"&&showNotification(`Container "${m.containerName}" was auto-restarted`,"info")}catch{}}),c.addEventListener("update-available",f=>{try{const m=JSON.parse(f.data),b=document.getElementById("updates-btn");if(b&&!b.querySelector(".sse-dot")){const s=document.createElement("span");s.className="sse-dot",s.style.cssText="display:inline-block;width:8px;height:8px;border-radius:50%;background:var(--accent);margin-left:6px;vertical-align:middle;",b.appendChild(s)}typeof showNotification=="function"&&showNotification(`Update available for ${m.containerName||m.containerId}`,"info")}catch{}}),c.addEventListener("update-complete",f=>{try{const m=JSON.parse(f.data);typeof showNotification=="function"&&showNotification(`Update completed: ${m.containerName||m.containerId}`,"success"),typeof window.refreshAll=="function"&&window.refreshAll()}catch{}}),c.addEventListener("update-failed",f=>{try{const m=JSON.parse(f.data);typeof showNotification=="function"&&showNotification(`Update failed: ${m.containerName||m.containerId} \u2014 ${m.error||"unknown error"}`,"error")}catch{}}),c.addEventListener("incident",f=>{try{const m=JSON.parse(f.data);typeof showNotification=="function"&&(m.type==="created"?showNotification(`Incident: ${m.message||m.serviceId}`,"error"):m.type==="resolved"&&showNotification(`Resolved: ${m.serviceId||"incident"}`,"success"))}catch{}}),c.onerror=()=>{c.close(),console.warn(`[SSE] Disconnected, reconnecting in ${a/1e3}s...`),setTimeout(h,a),a=Math.min(a*2,g)}}h(),window._sseReconnect=h})(),(function(){const c=document.getElementById("service-filter-search"),a=document.getElementById("service-filter-status"),g=document.getElementById("service-filter-category"),h=document.getElementById("service-filter-count");function f(){const v=new Set,d=new Set;document.querySelectorAll("#cards .card[data-category]").forEach(r=>{const e=r.dataset.category.trim();e&&d.add(e)});const o=window.DC_CATEGORIES||typeof DC<"u"&&DC.CATEGORIES||{};return Object.keys(o).concat([...d].filter(r=>!o[r])).forEach(r=>v.add(r)),{list:[...v],apiCats:o}}function m(){if(!g)return;const{list:v,apiCats:d}=f(),o=g.value;g.innerHTML='',v.sort().forEach(p=>{const r=d[p],e=document.createElement("option");e.value=p,e.textContent=r?`${r.icon||""} ${p}`.trim():p,g.appendChild(e)}),o&&[...g.options].some(p=>p.value===o)?g.value=o:g.value="all"}function b(){m();const v=c.value.toLowerCase().trim(),d=a.value,o=g?g.value:"all",p=document.querySelectorAll("#cards .card");let r=0;if(p.forEach(e=>{const n=e.querySelector(".name")?.textContent?.toLowerCase()||"",l=e.dataset.app?.toLowerCase()||"",t=e.dataset.status||"off",i=e.dataset.category||"";(!v||n.includes(v)||l.includes(v))&&(d==="all"||t===d)&&(o==="all"||i===o)?(e.style.display="",r++):e.style.display="none"}),h){const e=p.length;h.textContent=`${r} of ${e} services`}}function s(v,d){let o;return function(...p){clearTimeout(o),o=setTimeout(()=>v.apply(this,p),d)}}c?.addEventListener("input",s(b,200)),a?.addEventListener("change",b),g?.addEventListener("change",b),document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>setTimeout(b,500)):setTimeout(b,500),window.refreshServiceFilter=b,window.refreshCategoryDropdown=m})(),(function(){const c=document.getElementById("batch-operations-btn"),a=document.getElementById("batch-action-bar"),g=document.getElementById("batch-selected-count"),h=document.getElementById("batch-start-btn"),f=document.getElementById("batch-stop-btn"),m=document.getElementById("batch-restart-btn"),b=document.getElementById("batch-cancel-btn");let s=!1,v=new Set;function d(){s=!0,v.clear(),a.style.display="",c.textContent="\u2713 Exit Batch Mode",p(),document.querySelectorAll("#cards .card[data-app]").forEach(n=>{const l=n.dataset.containerId;if(!l)return;const t=n.querySelector(".batch-checkbox");t&&t.remove();const i=document.createElement("input");i.type="checkbox",i.className="batch-checkbox",i.dataset.containerId=l,i.dataset.serviceName=n.querySelector(".name")?.textContent||l,i.style.cssText="position: absolute; top: 8px; left: 8px; z-index: 10; width: 18px; height: 18px; cursor: pointer;",i.addEventListener("change",y=>{y.stopPropagation(),i.checked?v.add(l):v.delete(l),p()}),n.style.position="relative",n.insertBefore(i,n.firstChild)})}function o(){s=!1,v.clear(),a.style.display="none",c.textContent="\u2630 Batch Operations",document.querySelectorAll(".batch-checkbox").forEach(e=>e.remove())}function p(){const e=v.size;g.textContent=`${e} selected`,h.disabled=e===0,f.disabled=e===0,m.disabled=e===0}async function r(e){if(v.size===0)return;const n=Array.from(v),l={start:"Starting",stop:"Stopping",restart:"Restarting"}[e];if(!confirm(`${l} ${n.length} container(s)? This cannot be undone.`))return;const t=[h,f,m];t.forEach(w=>{w.disabled=!0,w.textContent="..."});let i=0,y=0;const u=[];for(const w of n)try{const T=await fetch(`/api/v1/containers/${encodeURIComponent(w)}/${e}`,{method:"POST"});if(T.ok)i++;else{y++;const L=await T.json().catch(()=>({}));u.push(`${w}: ${L.error||T.statusText}`)}}catch(T){y++,u.push(`${w}: ${T.message}`)}t[0].textContent="\u25B6 Start All",t[1].textContent="\u2B1B Stop All",t[2].textContent="\u{1F504} Restart All",p(),y===0?typeof showNotification=="function"&&showNotification(`${l} completed: ${i} container(s)`,"success"):(typeof showNotification=="function"&&showNotification(`${l}: ${i} succeeded, ${y} failed`,"warning"),console.error("Batch operation errors:",u)),setTimeout(()=>{typeof refreshAll=="function"&&refreshAll()},1500)}c?.addEventListener("click",()=>{s?o():d()}),h?.addEventListener("click",()=>r("start")),f?.addEventListener("click",()=>r("stop")),m?.addEventListener("click",()=>r("restart")),b?.addEventListener("click",o)})(); + `,y.disabled=!1):w.installed?(i.innerHTML='\u26A0 Not connected',y.disabled=!0):(i.innerHTML='Not available',y.disabled=!0)}catch{i.innerHTML='Could not check',y.disabled=!0}y.checked=!1,f()}function r(){const e=document.getElementById("service-type-local"),n=document.getElementById("service-type-external"),l=document.getElementById("local-service-config"),t=document.getElementById("external-service-config"),i=document.getElementById("tab-local"),y=document.getElementById("tab-external");function u(){e.checked?(l.style.display="grid",t.style.display="none",i&&(i.style.background="var(--accent)",i.style.color="var(--bg)"),y&&(y.style.background="transparent",y.style.color="var(--muted)")):(l.style.display="none",t.style.display="block",y&&(y.style.background="var(--accent)",y.style.color="var(--bg)"),i&&(i.style.background="transparent",i.style.color="var(--muted)"))}e?.addEventListener("change",u),n?.addEventListener("change",u)}function v(){const e=document.getElementById("service-name-input"),n=document.getElementById("service-subdomain-input"),l=document.getElementById("subdomain-preview");let t=!1;e?.addEventListener("input",()=>{const L=c(e.value);!t&&n&&(n.value=L),l&&(l.textContent=L?`\u2192 ${buildDomain(L)}`:""),f()}),n?.addEventListener("input",()=>{t=n.value!==c(e?.value||"");const L=n.value.trim()||c(e?.value||"");l&&(l.textContent=L?`\u2192 ${buildDomain(L)}`:""),f()});const i=document.getElementById("external-service-name"),y=document.getElementById("external-service-subdomain"),u=document.getElementById("external-subdomain-preview"),w=document.getElementById("external-domain-preview");let T=!1;i?.addEventListener("input",()=>{const L=c(i.value);!T&&y&&(y.value=L);const P=y?.value||L;u&&(u.textContent=P?`\u2192 ${buildDomain(P)}`:""),w&&(w.textContent=P?buildDomain(P):"")}),y?.addEventListener("input",()=>{T=y.value!==c(i?.value||"");const L=y.value.trim()||c(i?.value||"");u&&(u.textContent=L?`\u2192 ${buildDomain(L)}`:""),w&&(w.textContent=L?buildDomain(L):"")})}async function d(){const e=document.getElementById("external-service-name").value.trim(),n=document.getElementById("external-service-url").value.trim(),l=(document.getElementById("external-service-subdomain").value.trim()||c(e)).toLowerCase(),t=document.getElementById("external-service-logo").value.trim(),i=document.getElementById("external-service-icon").value.trim(),y=document.getElementById("external-create-dns").checked,u=document.getElementById("external-create-caddy").checked,w=document.getElementById("external-proxy-ip").value.trim()||SITE.dnsIp||"localhost",T=document.getElementById("external-preserve-host").checked,L=document.getElementById("external-follow-redirects").checked,P=document.getElementById("external-service-category")?.value||"";if(!e||!n){showNotification("Please fill in Name and External URL","warning");return}if(!l){showNotification("Could not derive subdomain from name. Please set one in Options.","warning");return}if(!n.startsWith("http://")&&!n.startsWith("https://")){showNotification("External URL must start with http:// or https://","warning");return}const C=buildDomain(l);try{const B={dns:null,caddy:null,dashboard:!1};if(y)if(window.getToken(getPrimaryDnsId(),"admin"))try{const A=await(await secureFetch("/api/v1/dns/record",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:C,ip:w,ttl:DC.DEFAULTS.TTL,server:SITE.dnsIp})})).json();B.dns=A.success?"created":A.error||"failed"}catch(S){B.dns=S.message}else B.dns="no admin token (configure in \u{1F511} Tokens)";if(u)try{const E={subdomain:l,externalUrl:n,preserveHost:T,followRedirects:L,sslType:"caddy-managed",caddyfilePath:DC.DEFAULTS.CADDYFILE,reloadCaddy:!0},A=await(await secureFetch("/api/v1/site/external",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(E)})).json();B.caddy=A.success?"created":A.error||"failed"}catch(E){B.caddy=E.message}const $={id:l,name:e,url:`https://${C}`,externalUrl:n,logo:t||i||"\u{1F310}",isExternal:!0,isCustom:!0};P&&($.category=P),window.APPS.push($),B.dashboard=!0;const k=["plex","router","chat","sync","torrent","radarr","sonarr","prowlarr","portainer","requests","jellyfin","emby"],x=window.APPS.filter(E=>!k.includes(E.id));safeSet("custom-services",JSON.stringify(x));try{await secureFetch("/api/v1/services",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(window.APPS)})}catch(E){console.warn("Failed to save to services.json:",E)}window.buildGrid(),window.refreshAll(),o();const I=[`External service "${e}" added!`];y&&I.push(`DNS: ${B.dns==="created"?"\u2713":"\u26A0 "+B.dns}`),u&&I.push(`Caddy: ${B.caddy==="created"?"\u2713":"\u26A0 "+B.caddy}`),I.push(`Access at: https://${C}`),showNotification(I.join(" | "),"success",6e3)}catch(B){console.error("Failed to create external service:",B),showNotification(`Failed to create external service: ${B.message}`,"error")}}function o(){closeModal("add-service-modal"),document.body.style.overflow="",document.getElementById("service-name-input").value="",document.getElementById("service-subdomain-input").value="",document.getElementById("service-port-input").value="",document.getElementById("service-ip-input").value=h.lan||"",document.getElementById("service-logo-input").value="",document.getElementById("dns-ttl-input").value=DC.DEFAULTS.TTL,document.getElementById("ssl-type-select").value=a(),document.getElementById("ca-name-input").value="",document.getElementById("enable-auth").checked=!1,document.getElementById("enable-cors").checked=!1,document.getElementById("custom-headers-input").value="",document.getElementById("upstream-path-input").value="/",document.getElementById("health-check-input").value="",document.getElementById("timeout-input").value="30";const e=document.getElementById("subdomain-preview");e&&(e.textContent="");const n=document.getElementById("external-subdomain-preview");n&&(n.textContent="");const l=document.getElementById("external-service-name");l&&(l.value="");const t=document.getElementById("external-service-subdomain");t&&(t.value="");const i=document.getElementById("external-service-url");i&&(i.value="");const y=document.getElementById("external-service-logo");y&&(y.value="");const u=document.getElementById("external-service-icon");u&&(u.value="");const w=document.getElementById("local-advanced-options");w&&w.removeAttribute("open");const T=document.getElementById("external-advanced-options");T&&T.removeAttribute("open");const L=document.getElementById("service-type-local");L&&(L.checked=!0);const P=document.getElementById("local-service-config"),C=document.getElementById("external-service-config");P&&(P.style.display="grid"),C&&(C.style.display="none");const B=document.getElementById("tab-local"),$=document.getElementById("tab-external");B&&(B.style.background="var(--accent)",B.style.color="var(--bg)"),$&&($.style.background="transparent",$.style.color="var(--muted)")}async function p(){const e=document.getElementById("service-name-input").value.trim(),n=(document.getElementById("service-subdomain-input").value.trim()||c(e)).toLowerCase(),l=document.getElementById("service-port-input").value.trim(),t=document.getElementById("service-ip-input").value.trim(),i=document.getElementById("service-logo-input").value.trim(),y=document.getElementById("create-dns-record").checked,u=parseInt(document.getElementById("dns-ttl-input").value)||DC.DEFAULTS.TTL,w=document.getElementById("manual-tailscale-only")?.checked||!1,T=document.getElementById("ssl-type-select")?.value||"caddy-managed",L=document.getElementById("ca-name-input")?.value||"",P=document.getElementById("existing-ca-select")?.value||"",C=document.getElementById("enable-auth")?.checked||!1,B=document.getElementById("enable-cors")?.checked||!1,$=document.getElementById("custom-headers-input")?.value||"",k=document.getElementById("upstream-path-input")?.value||"/",x=document.getElementById("health-check-input")?.value||"",I=document.getElementById("timeout-input")?.value||30,S=(document.getElementById("service-category-input")||document.getElementById("external-service-category"))?.value||"",A=window.getToken(getPrimaryDnsId(),"admin");if(!e||!l||!t){showNotification("Please fill in Name, Port, and IP Address","warning");return}if(!n){showNotification("Could not derive subdomain from name. Please set one in Options.","warning");return}if(y&&!A){showNotification("DNS Admin token required. Configure it in the Tokens menu first.","warning");return}const D={dns:null,caddy:null,dashboard:!1};try{if(y)try{await window.createDnsRecord(n,t,u),D.dns="created"}catch(N){throw console.error("DNS creation failed:",N),D.dns=N.message,new Error(`DNS creation failed: ${N.message}`)}else D.dns="skipped";const O=window.generateCaddyConfig({subdomain:n,port:l,ip:t,sslType:T,caName:L,existingCa:P,enableAuth:C,enableCors:B,customHeaders:$,upstreamPath:k,healthCheck:x,timeout:I,tailscaleOnly:w});try{const U=await(await secureFetch("/api/v1/site",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:buildDomain(n),upstream:`${t}:${l}`,config:O})})).json();if(U.success)D.caddy="added & reloaded";else throw console.error("Caddy configuration failed:",U.error),D.caddy=U.error||"failed",new Error(`Caddy configuration failed: ${U.error}`)}catch(N){throw console.error("Caddy API error:",N),D.caddy=N.message,new Error(`Caddy API error: ${N.message}`)}const M={name:e,subdomain:n,port:l,ip:t,logo:i||`/assets/${n}.png`,tailscaleOnly:w||!1};S&&(M.category=S),await window.addServiceToConfig(M),D.dashboard=!0;const R=[`DNS: ${D.dns==="created"?"\u2713":D.dns==="skipped"?"\u25CB":"\u2717"}`,`Caddy: ${D.caddy==="added & reloaded"?"\u2713":"\u2717"}`,`Dashboard: ${D.dashboard?"\u2713":"\u2717"}`];showNotification(`Service "${e}" created! ${R.join(" | ")} \u2014 ${buildServiceUrl(n)}${w?" (Tailscale)":""}`,"success",6e3),o(),window.buildGrid(),window.refreshAll()}catch(O){console.error("Error creating service:",O),showNotification(`Error creating "${e}": ${O.message}`,"error",6e3)}}document.getElementById("add-service")?.addEventListener("click",b),document.getElementById("add-service-cancel")?.addEventListener("click",o),document.getElementById("add-service-create")?.addEventListener("click",()=>{document.querySelector('input[name="service-type"]:checked')?.value==="external"?d():p()}),r(),v(),m(),document.getElementById("ssl-type-select")?.addEventListener("change",e=>{const n=document.getElementById("existing-ca-config"),l=document.getElementById("custom-ca-config");n.style.display="none",l.style.display="none",e.target.value==="existing-ca"?n.style.display="block":e.target.value==="custom-ca"&&(l.style.display="block"),f()}),document.getElementById("refresh-cas")?.addEventListener("click",async()=>{const e=document.getElementById("refresh-cas"),n=e.textContent;e.textContent="\u231B Loading...",e.disabled=!0;try{const l=document.getElementById("caddyfile-path-input").value||DC.DEFAULTS.CADDYFILE;await window.loadExistingCAs(l),e.textContent="\u2705 Refreshed"}catch(l){e.textContent="\u274C Failed",console.error("Failed to refresh CAs:",l)}setTimeout(()=>{e.textContent=n,e.disabled=!1},2e3)}),document.getElementById("create-dns-record")?.addEventListener("change",e=>{const n=document.getElementById("dns-config");n.style.display=e.target.checked?"block":"none"}),["service-subdomain-input","service-ip-input","service-port-input","ca-name-input","existing-ca-select","enable-auth","enable-cors","custom-headers-input","upstream-path-input","health-check-input","timeout-input"].forEach(e=>{const n=document.getElementById(e);n&&(n.addEventListener("input",f),n.addEventListener("change",f))});function s(){const e=safeGet("custom-services");if(e)try{JSON.parse(e).forEach(l=>{window.APPS.find(t=>t.id===l.id)||window.APPS.push(l)})}catch(n){console.warn("Failed to load custom services:",n)}}s(),window.openAddServiceModal=b,window.closeAddServiceModal=o})(),(function(){let c=null,a=1e3;const f=3e4;function h(){if(c)try{c.close()}catch{}c=new EventSource("/api/v1/events/stream"),c.addEventListener("connected",()=>{a=1e3,debug("[SSE] Connected to event stream")}),c.addEventListener("status-change",g=>{try{const m=JSON.parse(g.data);if(m.serviceId&&typeof window.setBadge=="function"){const b=m.status==="up"||m.status==="healthy";window.setBadge(m.serviceId,b,m.responseTime||null)}}catch{}}),c.addEventListener("resource-alert",g=>{try{const m=JSON.parse(g.data),b=`${m.containerName||m.containerId}: ${m.metric} at ${m.value}% (threshold: ${m.threshold}%)`;typeof showNotification=="function"&&showNotification(b,"warning")}catch{}}),c.addEventListener("auto-restart",g=>{try{const m=JSON.parse(g.data);typeof showNotification=="function"&&showNotification(`Container "${m.containerName}" was auto-restarted`,"info")}catch{}}),c.addEventListener("update-available",g=>{try{const m=JSON.parse(g.data),b=document.getElementById("updates-btn");if(b&&!b.querySelector(".sse-dot")){const r=document.createElement("span");r.className="sse-dot",r.style.cssText="display:inline-block;width:8px;height:8px;border-radius:50%;background:var(--accent);margin-left:6px;vertical-align:middle;",b.appendChild(r)}typeof showNotification=="function"&&showNotification(`Update available for ${m.containerName||m.containerId}`,"info")}catch{}}),c.addEventListener("update-complete",g=>{try{const m=JSON.parse(g.data);typeof showNotification=="function"&&showNotification(`Update completed: ${m.containerName||m.containerId}`,"success"),typeof window.refreshAll=="function"&&window.refreshAll()}catch{}}),c.addEventListener("update-failed",g=>{try{const m=JSON.parse(g.data);typeof showNotification=="function"&&showNotification(`Update failed: ${m.containerName||m.containerId} \u2014 ${m.error||"unknown error"}`,"error")}catch{}}),c.addEventListener("incident",g=>{try{const m=JSON.parse(g.data);typeof showNotification=="function"&&(m.type==="created"?showNotification(`Incident: ${m.message||m.serviceId}`,"error"):m.type==="resolved"&&showNotification(`Resolved: ${m.serviceId||"incident"}`,"success"))}catch{}}),c.onerror=()=>{c.close(),console.warn(`[SSE] Disconnected, reconnecting in ${a/1e3}s...`),setTimeout(h,a),a=Math.min(a*2,f)}}h(),window._sseReconnect=h})(),(function(){const c=document.getElementById("service-filter-search"),a=document.getElementById("service-filter-status"),f=document.getElementById("service-filter-category"),h=document.getElementById("service-filter-count");function g(){const v=new Set,d=new Set;document.querySelectorAll("#cards .card[data-category]").forEach(s=>{const e=s.dataset.category.trim();e&&d.add(e)});const o=window.DC_CATEGORIES||typeof DC<"u"&&DC.CATEGORIES||{};return Object.keys(o).concat([...d].filter(s=>!o[s])).forEach(s=>v.add(s)),{list:[...v],apiCats:o}}function m(){if(!f)return;const{list:v,apiCats:d}=g(),o=f.value;f.innerHTML='',v.sort().forEach(p=>{const s=d[p],e=document.createElement("option");e.value=p,e.textContent=s?`${s.icon||""} ${p}`.trim():p,f.appendChild(e)}),o&&[...f.options].some(p=>p.value===o)?f.value=o:f.value="all"}function b(){m();const v=c.value.toLowerCase().trim(),d=a.value,o=f?f.value:"all",p=document.querySelectorAll("#cards .card");let s=0;if(p.forEach(e=>{const n=e.querySelector(".name")?.textContent?.toLowerCase()||"",l=e.dataset.app?.toLowerCase()||"",t=e.dataset.status||"off",i=e.dataset.category||"";(!v||n.includes(v)||l.includes(v))&&(d==="all"||t===d)&&(o==="all"||i===o)?(e.style.display="",s++):e.style.display="none"}),h){const e=p.length;h.textContent=`${s} of ${e} services`}}function r(v,d){let o;return function(...p){clearTimeout(o),o=setTimeout(()=>v.apply(this,p),d)}}c?.addEventListener("input",r(b,200)),a?.addEventListener("change",b),f?.addEventListener("change",b),document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>setTimeout(b,500)):setTimeout(b,500),window.refreshServiceFilter=b,window.refreshCategoryDropdown=m})(),(function(){const c=document.getElementById("batch-operations-btn"),a=document.getElementById("batch-action-bar"),f=document.getElementById("batch-selected-count"),h=document.getElementById("batch-start-btn"),g=document.getElementById("batch-stop-btn"),m=document.getElementById("batch-restart-btn"),b=document.getElementById("batch-cancel-btn");let r=!1,v=new Set;function d(){r=!0,v.clear(),a.style.display="",c.textContent="\u2713 Exit Batch Mode",p(),document.querySelectorAll("#cards .card[data-app]").forEach(n=>{const l=n.dataset.containerId;if(!l)return;const t=n.querySelector(".batch-checkbox");t&&t.remove();const i=document.createElement("input");i.type="checkbox",i.className="batch-checkbox",i.dataset.containerId=l,i.dataset.serviceName=n.querySelector(".name")?.textContent||l,i.style.cssText="position: absolute; top: 8px; left: 8px; z-index: 10; width: 18px; height: 18px; cursor: pointer;",i.addEventListener("change",y=>{y.stopPropagation(),i.checked?v.add(l):v.delete(l),p()}),n.style.position="relative",n.insertBefore(i,n.firstChild)})}function o(){r=!1,v.clear(),a.style.display="none",c.textContent="\u2630 Batch Operations",document.querySelectorAll(".batch-checkbox").forEach(e=>e.remove())}function p(){const e=v.size;f.textContent=`${e} selected`,h.disabled=e===0,g.disabled=e===0,m.disabled=e===0}async function s(e){if(v.size===0)return;const n=Array.from(v),l={start:"Starting",stop:"Stopping",restart:"Restarting"}[e];if(!confirm(`${l} ${n.length} container(s)? This cannot be undone.`))return;const t=[h,g,m];t.forEach(w=>{w.disabled=!0,w.textContent="..."});let i=0,y=0;const u=[];for(const w of n)try{const T=await fetch(`/api/v1/containers/${encodeURIComponent(w)}/${e}`,{method:"POST"});if(T.ok)i++;else{y++;const L=await T.json().catch(()=>({}));u.push(`${w}: ${L.error||T.statusText}`)}}catch(T){y++,u.push(`${w}: ${T.message}`)}t[0].textContent="\u25B6 Start All",t[1].textContent="\u2B1B Stop All",t[2].textContent="\u{1F504} Restart All",p(),y===0?typeof showNotification=="function"&&showNotification(`${l} completed: ${i} container(s)`,"success"):(typeof showNotification=="function"&&showNotification(`${l}: ${i} succeeded, ${y} failed`,"warning"),console.error("Batch operation errors:",u)),setTimeout(()=>{typeof refreshAll=="function"&&refreshAll()},1500)}c?.addEventListener("click",()=>{r?o():d()}),h?.addEventListener("click",()=>s("start")),g?.addEventListener("click",()=>s("stop")),m?.addEventListener("click",()=>s("restart")),b?.addEventListener("click",o)})(); diff --git a/status/dist/features.js b/status/dist/features.js index 3909e42..9e88075 100644 --- a/status/dist/features.js +++ b/status/dist/features.js @@ -90,19 +90,19 @@ - `);const h=document.getElementById("logo-modal"),S=document.getElementById("logo-preview-dark"),A=document.getElementById("logo-preview-light"),k=document.getElementById("logo-status"),N=document.getElementById("logo-same-both"),R=document.getElementById("logo-dual-uploads"),z=document.getElementById("logo-single-upload"),P=document.getElementById("logo-upload-dark"),g=document.getElementById("logo-upload-light"),T=document.getElementById("logo-upload-single"),w=document.querySelector("#brand .brand-logo-dark"),H=document.querySelector("#brand .brand-logo-light"),E=document.querySelector(".top-row"),$=document.getElementById("dashboard-title"),I=DC.NAME;let L=null,j=null,M=null,O="left",x=I;N?.addEventListener("change",()=>{N.checked?(R.style.display="none",z.style.display="",L=null,j=null):(R.style.display="flex",z.style.display="none",M=null)});function D(t,e){if(!t||!t.type.startsWith("image/")){showNotification("Please select an image file","warning");return}const o=new FileReader;o.onload=a=>e(a.target.result),o.readAsDataURL(t)}P?.addEventListener("change",t=>{D(t.target.files[0],e=>{L=e,S.src=e,k.textContent="New dark logo ready to save"})}),g?.addEventListener("change",t=>{D(t.target.files[0],e=>{j=e,A.src=e,k.textContent="New light logo ready to save"})}),T?.addEventListener("change",t=>{D(t.target.files[0],e=>{M=e,S.src=e,A.src=e,k.textContent="New logo ready to save (both themes)"})});function y(t){E.setAttribute("data-logo-pos",t),document.querySelectorAll(".logo-pos-btn").forEach(e=>{e.style.background=e.dataset.pos===t?"var(--accent)":"var(--card-bg)",e.style.color=e.dataset.pos===t?"white":"var(--fg)"})}function m(t){x=t||I,document.title=x;const e=document.querySelector(".dashboard-title");e&&(e.textContent=x)}async function b(){try{const t=await fetch("/api/v1/logo");if(t.ok){const e=await t.json();e.customLogoDark&&(w.src=e.customLogoDark,S.src=e.customLogoDark),e.customLogoLight&&(H.src=e.customLogoLight,A.src=e.customLogoLight),!e.customLogoDark&&!e.customLogoLight&&e.customLogo&&(w.src=e.customLogo,H.src=e.customLogo,S.src=e.customLogo,A.src=e.customLogo),e.isDefault||(k.textContent="Using custom logo"),e.position&&(O=e.position,y(e.position)),e.dashboardTitle&&m(e.dashboardTitle)}}catch(t){console.warn("Could not load custom logo:",t.message)}}document.querySelectorAll(".logo-pos-btn").forEach(t=>{t.addEventListener("click",()=>{O=t.dataset.pos,y(O)})}),document.getElementById("brand")?.addEventListener("click",()=>{L=null,j=null,M=null,P&&(P.value=""),g&&(g.value=""),T&&(T.value=""),N&&(N.checked=!1),R.style.display="flex",z.style.display="none",S.src=w.src,A.src=H.src;const t=w.src.includes("custom-logo")||H.src.includes("custom-logo");k.textContent=t?"Using custom logo":"Using default logos",y(O),$.value=x,h.classList.add("show")}),document.getElementById("logo-save")?.addEventListener("click",async()=>{try{const t=$.value.trim()||I,e={position:O,dashboardTitle:t};N?.checked&&M?(e.dataDark=M,e.dataLight=M):(L&&(e.dataDark=L),j&&(e.dataLight=j));const o=await secureFetch("/api/v1/logo",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(o.ok){const a=await o.json(),d="?t="+Date.now();a.pathDark&&(w.src=a.pathDark+d,S.src=a.pathDark+d),a.pathLight&&(H.src=a.pathLight+d,A.src=a.pathLight+d),y(O),m(t),h.classList.remove("show")}else{const a=await o.json();showNotification("Failed to save: "+a.error,"error")}}catch(t){showNotification("Error saving: "+t.message,"error")}}),document.getElementById("logo-reset")?.addEventListener("click",async()=>{if(confirm(`Reset all branding to DashCaddy defaults? + `);const h=document.getElementById("logo-modal"),S=document.getElementById("logo-preview-dark"),O=document.getElementById("logo-preview-light"),E=document.getElementById("logo-status"),N=document.getElementById("logo-same-both"),R=document.getElementById("logo-dual-uploads"),z=document.getElementById("logo-single-upload"),P=document.getElementById("logo-upload-dark"),g=document.getElementById("logo-upload-light"),L=document.getElementById("logo-upload-single"),w=document.querySelector("#brand .brand-logo-dark"),T=document.querySelector("#brand .brand-logo-light"),k=document.querySelector(".top-row"),B=document.getElementById("dashboard-title"),I=DC.NAME;let C=null,j=null,M=null,D="left",x=I;N?.addEventListener("change",()=>{N.checked?(R.style.display="none",z.style.display="",C=null,j=null):(R.style.display="flex",z.style.display="none",M=null)});function A(t,e){if(!t||!t.type.startsWith("image/")){showNotification("Please select an image file","warning");return}const n=new FileReader;n.onload=a=>e(a.target.result),n.readAsDataURL(t)}P?.addEventListener("change",t=>{A(t.target.files[0],e=>{C=e,S.src=e,E.textContent="New dark logo ready to save"})}),g?.addEventListener("change",t=>{A(t.target.files[0],e=>{j=e,O.src=e,E.textContent="New light logo ready to save"})}),L?.addEventListener("change",t=>{A(t.target.files[0],e=>{M=e,S.src=e,O.src=e,E.textContent="New logo ready to save (both themes)"})});function y(t){k.setAttribute("data-logo-pos",t),document.querySelectorAll(".logo-pos-btn").forEach(e=>{e.style.background=e.dataset.pos===t?"var(--accent)":"var(--card-bg)",e.style.color=e.dataset.pos===t?"white":"var(--fg)"})}function m(t){x=t||I,document.title=x;const e=document.querySelector(".dashboard-title");e&&(e.textContent=x)}async function b(){try{const t=await fetch("/api/v1/logo");if(t.ok){const e=await t.json();e.customLogoDark&&(w.src=e.customLogoDark,S.src=e.customLogoDark),e.customLogoLight&&(T.src=e.customLogoLight,O.src=e.customLogoLight),!e.customLogoDark&&!e.customLogoLight&&e.customLogo&&(w.src=e.customLogo,T.src=e.customLogo,S.src=e.customLogo,O.src=e.customLogo),e.isDefault||(E.textContent="Using custom logo"),e.position&&(D=e.position,y(e.position)),e.dashboardTitle&&m(e.dashboardTitle)}}catch(t){console.warn("Could not load custom logo:",t.message)}}document.querySelectorAll(".logo-pos-btn").forEach(t=>{t.addEventListener("click",()=>{D=t.dataset.pos,y(D)})}),document.getElementById("brand")?.addEventListener("click",()=>{C=null,j=null,M=null,P&&(P.value=""),g&&(g.value=""),L&&(L.value=""),N&&(N.checked=!1),R.style.display="flex",z.style.display="none",S.src=w.src,O.src=T.src;const t=w.src.includes("custom-logo")||T.src.includes("custom-logo");E.textContent=t?"Using custom logo":"Using default logos",y(D),B.value=x,h.classList.add("show")}),document.getElementById("logo-save")?.addEventListener("click",async()=>{try{const t=B.value.trim()||I,e={position:D,dashboardTitle:t};N?.checked&&M?(e.dataDark=M,e.dataLight=M):(C&&(e.dataDark=C),j&&(e.dataLight=j));const n=await secureFetch("/api/v1/logo",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(n.ok){const a=await n.json(),l="?t="+Date.now();a.pathDark&&(w.src=a.pathDark+l,S.src=a.pathDark+l),a.pathLight&&(T.src=a.pathLight+l,O.src=a.pathLight+l),y(D),m(t),h.classList.remove("show")}else{const a=await n.json();showNotification("Failed to save: "+a.error,"error")}}catch(t){showNotification("Error saving: "+t.message,"error")}}),document.getElementById("logo-reset")?.addEventListener("click",async()=>{if(confirm(`Reset all branding to DashCaddy defaults? -This will reset the logo, favicon, title, and position.`))try{if((await secureFetch("/api/v1/logo",{method:"DELETE"})).ok&&(w.src="/assets/dashcaddy-logo-dark.png",H.src="/assets/dashcaddy-logo-light.png",S.src="/assets/dashcaddy-logo-dark.png",A.src="/assets/dashcaddy-logo-light.png",k.textContent="Using default logos",L=null,j=null,M=null,$.value=I,m(I),O="left",y("left")),(await secureFetch("/api/v1/favicon",{method:"DELETE"})).ok){const o=document.querySelector('link[rel="icon"]'),a=document.getElementById("favicon-preview"),d=document.getElementById("favicon-status");o&&(o.href="/assets/dashcaddy-favicon.ico?t="+Date.now()),a&&(a.src="/assets/dashcaddy-favicon.ico?t="+Date.now()),d&&(d.textContent="Using DashCaddy favicon"),r=null}}catch(t){showNotification("Error resetting branding: "+t.message,"error")}}),wireModal(h,document.getElementById("logo-cancel"));const p=document.getElementById("favicon-preview"),v=document.getElementById("favicon-status"),s=document.getElementById("favicon-upload"),l=document.querySelector('link[rel="icon"]')||document.createElement("link");let r=null;document.querySelector('link[rel="icon"]')||(l.rel="icon",l.href="/assets/dashcaddy-favicon.ico",document.head.appendChild(l));async function f(){try{const t=await fetch("/api/v1/favicon");if(t.ok){const e=await t.json();e.customFavicon&&(l.href=e.customFavicon+"?t="+Date.now(),p.src=e.customFavicon+"?t="+Date.now(),v.textContent="Using custom favicon")}}catch(t){console.warn("Could not load custom favicon:",t.message)}}s?.addEventListener("change",t=>{const e=t.target.files[0];if(!e)return;if(!e.type.match(/^image\/(png|svg\+xml)$/)){showNotification("Please select a PNG or SVG file","warning"),s.value="";return}const o=new FileReader;o.onload=a=>{r=a.target.result,p.src=r,v.textContent="New favicon ready to save"},o.readAsDataURL(e)}),document.getElementById("logo-save")?.addEventListener("click",async()=>{if(r)try{const t=await secureFetch("/api/v1/favicon",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({data:r})});if(t.ok){const e=await t.json();l.href=e.path+"?t="+Date.now(),p.src=e.path+"?t="+Date.now(),v.textContent="Using custom favicon",r=null}else{const e=await t.json();showNotification("Failed to save favicon: "+e.error,"error")}}catch(t){showNotification("Error saving favicon: "+t.message,"error")}}),f(),b();const u=document.getElementById("settings-timezone");u&&(new MutationObserver(()=>{h.classList.contains("show")&&u.options.length===0&&(async()=>{let e;try{const o=await fetch("/api/v1/config");o.ok&&(e=(await o.json()).timezone)}catch{}window.populateTimezoneSelect(u,e)})()}).observe(h,{attributes:!0,attributeFilter:["class"]}),document.getElementById("logo-save")?.addEventListener("click",async()=>{const e=u.value;if(e)try{const o=await fetch("/api/v1/config");if(!o.ok)return;const a=await o.json();a.timezone=e,a.updatedAt=new Date().toISOString(),await secureFetch("/api/v1/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)})}catch(o){console.warn("Failed to save timezone:",o.message)}}))})(),window.populateTimezoneSelect=function(h,S){const A=Intl.supportedValuesOf("timeZone"),k=S||Intl.DateTimeFormat().resolvedOptions().timeZone||"UTC";h.innerHTML="";for(const N of A){const R=document.createElement("option");R.value=N,R.textContent=N.replace(/_/g," "),N===k&&(R.selected=!0),h.appendChild(R)}},(function(){let h="homelab",S=null;async function A(){try{const D=await fetch("/api/v1/config");if(D.ok&&(S=await D.json(),S&&S.setupComplete))return document.getElementById("setup-wizard").style.display="none",!0}catch(D){console.warn("Could not fetch server config, checking localStorage fallback:",D.message)}return safeGet("dashcaddy-setup")?(document.getElementById("setup-wizard").style.display="none",!0):(document.getElementById("setup-wizard").style.display="flex",!1)}A();const k=document.getElementById("setup-timezone");k&&window.populateTimezoneSelect(k);function N(x){document.querySelectorAll(".setup-step").forEach(y=>{y.style.display="none"});const D=document.getElementById(x);D&&(D.style.display="block")}function R(){const x=document.getElementById("setup-summary-content");if(!x)return;let D='
';if(h==="homelab"){const m=document.getElementById("setup-tld")?.value?.trim()||".home",b=document.getElementById("setup-ca-name")?.value?.trim()||"",p=document.getElementById("setup-dns-ip")?.value?.trim()||"",v=document.getElementById("setup-dns-port")?.value?.trim()||DC.DEFAULTS.DNS_PORT;D+=` +This will reset the logo, favicon, title, and position.`))try{if((await secureFetch("/api/v1/logo",{method:"DELETE"})).ok&&(w.src="/assets/dashcaddy-logo-dark.png",T.src="/assets/dashcaddy-logo-light.png",S.src="/assets/dashcaddy-logo-dark.png",O.src="/assets/dashcaddy-logo-light.png",E.textContent="Using default logos",C=null,j=null,M=null,B.value=I,m(I),D="left",y("left")),(await secureFetch("/api/v1/favicon",{method:"DELETE"})).ok){const n=document.querySelector('link[rel="icon"]'),a=document.getElementById("favicon-preview"),l=document.getElementById("favicon-status");n&&(n.href="/assets/dashcaddy-favicon.ico?t="+Date.now()),a&&(a.src="/assets/dashcaddy-favicon.ico?t="+Date.now()),l&&(l.textContent="Using DashCaddy favicon"),r=null}}catch(t){showNotification("Error resetting branding: "+t.message,"error")}}),wireModal(h,document.getElementById("logo-cancel"));const p=document.getElementById("favicon-preview"),u=document.getElementById("favicon-status"),s=document.getElementById("favicon-upload"),d=document.querySelector('link[rel="icon"]')||document.createElement("link");let r=null;document.querySelector('link[rel="icon"]')||(d.rel="icon",d.href="/assets/dashcaddy-favicon.ico",document.head.appendChild(d));async function f(){try{const t=await fetch("/api/v1/favicon");if(t.ok){const e=await t.json();e.customFavicon&&(d.href=e.customFavicon+"?t="+Date.now(),p.src=e.customFavicon+"?t="+Date.now(),u.textContent="Using custom favicon")}}catch(t){console.warn("Could not load custom favicon:",t.message)}}s?.addEventListener("change",t=>{const e=t.target.files[0];if(!e)return;if(!e.type.match(/^image\/(png|svg\+xml)$/)){showNotification("Please select a PNG or SVG file","warning"),s.value="";return}const n=new FileReader;n.onload=a=>{r=a.target.result,p.src=r,u.textContent="New favicon ready to save"},n.readAsDataURL(e)}),document.getElementById("logo-save")?.addEventListener("click",async()=>{if(r)try{const t=await secureFetch("/api/v1/favicon",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({data:r})});if(t.ok){const e=await t.json();d.href=e.path+"?t="+Date.now(),p.src=e.path+"?t="+Date.now(),u.textContent="Using custom favicon",r=null}else{const e=await t.json();showNotification("Failed to save favicon: "+e.error,"error")}}catch(t){showNotification("Error saving favicon: "+t.message,"error")}}),f(),b();const v=document.getElementById("settings-timezone");v&&(new MutationObserver(()=>{h.classList.contains("show")&&v.options.length===0&&(async()=>{let e;try{const n=await fetch("/api/v1/config");n.ok&&(e=(await n.json()).timezone)}catch{}window.populateTimezoneSelect(v,e)})()}).observe(h,{attributes:!0,attributeFilter:["class"]}),document.getElementById("logo-save")?.addEventListener("click",async()=>{const e=v.value;if(e)try{const n=await fetch("/api/v1/config");if(!n.ok)return;const a=await n.json();a.timezone=e,a.updatedAt=new Date().toISOString(),await secureFetch("/api/v1/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)})}catch(n){console.warn("Failed to save timezone:",n.message)}}))})(),window.populateTimezoneSelect=function(h,S){const O=Intl.supportedValuesOf("timeZone"),E=S||Intl.DateTimeFormat().resolvedOptions().timeZone||"UTC";h.innerHTML="";for(const N of O){const R=document.createElement("option");R.value=N,R.textContent=N.replace(/_/g," "),N===E&&(R.selected=!0),h.appendChild(R)}},(function(){let h="homelab",S=null;async function O(){try{const A=await fetch("/api/v1/config");if(A.ok&&(S=await A.json(),S&&S.setupComplete))return document.getElementById("setup-wizard").style.display="none",!0}catch(A){console.warn("Could not fetch server config, checking localStorage fallback:",A.message)}return safeGet("dashcaddy-setup")?(document.getElementById("setup-wizard").style.display="none",!0):(document.getElementById("setup-wizard").style.display="flex",!1)}O();const E=document.getElementById("setup-timezone");E&&window.populateTimezoneSelect(E);function N(x){document.querySelectorAll(".setup-step").forEach(y=>{y.style.display="none"});const A=document.getElementById(x);A&&(A.style.display="block")}function R(){const x=document.getElementById("setup-summary-content");if(!x)return;let A='
';if(h==="homelab"){const m=document.getElementById("setup-tld")?.value?.trim()||".home",b=document.getElementById("setup-ca-name")?.value?.trim()||"",p=document.getElementById("setup-dns-ip")?.value?.trim()||"",u=document.getElementById("setup-dns-port")?.value?.trim()||DC.DEFAULTS.DNS_PORT;A+=`

Home Lab Configuration

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

Simple Setup

@@ -112,7 +112,7 @@ This will reset the logo, favicon, title, and position.`))try{if((await secureFe
Example URLs: http://${m}:8080, http://${m}:3000
- `}else if(h==="public"){const m=document.getElementById("setup-public-domain")?.value?.trim()||"",b=document.getElementById("setup-public-email")?.value?.trim()||"",p=document.querySelector('input[name="routing-mode"]:checked')?.value||"subdirectory",v=p==="subdirectory"?`https://${m}/sonarr, https://${m}/grafana`:`https://sonarr.${m}, https://grafana.${m}`;D+=` + `}else if(h==="public"){const m=document.getElementById("setup-public-domain")?.value?.trim()||"",b=document.getElementById("setup-public-email")?.value?.trim()||"",p=document.querySelector('input[name="routing-mode"]:checked')?.value||"subdirectory",u=p==="subdirectory"?`https://${m}/sonarr, https://${m}/grafana`:`https://sonarr.${m}, https://grafana.${m}`;A+=`

Public Server

@@ -120,14 +120,14 @@ This will reset the logo, favicon, title, and position.`))try{if((await secureFe
SSL: Let's Encrypt
Email: ${b}
Routing: ${p==="subdirectory"?"Subdirectory (domain.com/app)":"Subdomain (app.domain.com)"}
-
Example URLs: ${v}
+
Example URLs: ${u}
- `}const y=document.getElementById("setup-timezone")?.value||Intl.DateTimeFormat().resolvedOptions().timeZone||"UTC";D+=` + `}const y=document.getElementById("setup-timezone")?.value||Intl.DateTimeFormat().resolvedOptions().timeZone||"UTC";A+=`
Timezone: ${y.replace(/_/g," ")}
- `,D+="
",x.innerHTML=D,N("setup-step-summary")}async function z(x){try{const D=await secureFetch("/api/v1/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(x)});return D.ok?(await D.json(),!0):(errorHandler.logError("[SetupWizard] Save Config",new Error(`Server returned ${D.status}`),{function:"saveConfigToServer"}),!1)}catch(D){return errorHandler.logError("[SetupWizard] Save Config",D,{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 D=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=D?"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 D=document.querySelector('input[name="config-type"]:checked');D&&(h=D.value),N(h==="homelab"?"setup-step-homelab":h==="simple"?"setup-step-simple":h==="public"?"setup-step-public":"setup-step-homelab")});const T=document.getElementById("setup-skip");T&&(T.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 D=x.target.value||".home",y=document.getElementById("tld-preview"),m=document.getElementById("tld-preview-2");y&&(y.textContent=D),m&&(m.textContent=D)});const H=document.getElementById("setup-homelab-back");H&&(H.onclick=function(x){x.preventDefault(),N("setup-step-1")});const E=document.getElementById("setup-homelab-next");E&&(E.onclick=function(x){x.preventDefault();const D=document.getElementById("setup-tld")?.value?.trim()||"",y=document.getElementById("setup-ca-name")?.value?.trim()||"",m=document.getElementById("setup-dns-ip")?.value?.trim()||"";if(!D||!D.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 $=document.getElementById("setup-simple-back");$&&($.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 D=document.getElementById("dns-requirement-note");D&&(D.textContent=this.value==="subdirectory"?"Only one DNS record needed (for the main domain)":"You'll need to configure DNS manually for each subdomain")}});const L=document.getElementById("setup-public-back");L&&(L.onclick=function(x){x.preventDefault(),N("setup-step-1")});const j=document.getElementById("setup-public-next");j&&(j.onclick=function(x){x.preventDefault();const D=document.getElementById("setup-public-domain")?.value?.trim()||"",y=document.getElementById("setup-public-email")?.value?.trim()||"";if(!D){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 O=document.getElementById("setup-finish");O&&(O.onclick=function(x){x.preventDefault(),P()}),window.getGlobalConfig=async function(){try{const D=await fetch("/api/v1/config");if(D.ok){const y=await D.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",`
+ `,A+="
",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

@@ -333,12 +333,12 @@ This will reset the logo, favicon, title, and position.`))try{if((await secureFe
-
`);const S="custom-apps";let A=null,k=null;const N=document.getElementById("app-selector-modal"),R=document.getElementById("app-selector-grid");async function z(){try{const l=await(await fetch("/api/v1/apps/templates")).json();if(l.success)return A=l.templates,k=l.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(l){return h.logError("[AppSelector] Check Port",l,{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(l){h.logError("[AppSelector] Get Suggested Port",l,{function:"getSuggestedPort"})}return s}async function T(){if(R.innerHTML='
Loading app templates...
',!A&&!await z()){R.innerHTML='
Failed to load app templates. Please try again.
';return}R.innerHTML="";const s={};for(const[r,f]of Object.entries(A)){const u=f.category||"Other";s[u]||(s[u]=[]),s[u].push({id:r,...f})}const l=k?Object.keys(k):Object.keys(s).sort();for(const r of l){const f=s[r];if(!f||f.length===0)continue;f.sort((e,o)=>(o.popularity||0)-(e.popularity||0));const u=document.createElement("div");u.className="app-category-header";const t=k?.[r]||{};u.innerHTML=`${escapeHtml(t.icon||"")} ${escapeHtml(r)}`,t.color&&(u.style.borderBottomColor=t.color),R.appendChild(u),f.forEach(e=>{const o=document.createElement("div");o.className="app-option";const a=e.isDashboardWidget,d=a&&safeGet("widget-"+e.id+"-enabled")!=="false",n=a?`
${d?"ON":"OFF"}
`:"",i=!a&&e.difficulty?`
${escapeHtml(e.difficulty)}
`:"";o.innerHTML=` + `);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||"")}
- ${n}${i} - `,a?o.onclick=()=>w(e,o):o.onclick=()=>H(e),R.appendChild(o)})}window.renderRecipeCards&&await window.renderRecipeCards(R)}function w(s,l){const r="widget-"+s.id+"-enabled",u=!(safeGet(r)!=="false");safeSet(r,String(u));const t=s.widgetSelector;if(t){const o=document.querySelector(t);o&&(o.style.display=u?"":"none")}const e=l.querySelector('div[style*="border-radius: 4px"]');e&&(e.textContent=u?"ON":"OFF",e.style.background=u?"#2ecc7130":"#e74c3c30",e.style.color=u?"#2ecc71":"#e74c3c"),showNotification(`${s.name} widget ${u?"enabled":"disabled"}`,"success",2e3)}async function H(s){const l=document.getElementById("app-deploy-modal"),r=document.getElementById("app-deploy-title"),f=document.getElementById("deploy-subdomain"),u=document.getElementById("deploy-url-preview"),t=document.getElementById("deploy-ip"),e=document.getElementById("deploy-port"),o=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: + ${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} @@ -347,38 +347,38 @@ 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 d=s.subdomain||s.id.replace(/-/g,"");f.value=d;const n=document.getElementById("subpath-compat-warning");if(n)if(SITE.routingMode==="subdirectory"){const _=s.subpathSupport||"strip";_==="none"?(n.style.display="block",n.innerHTML=''+s.name+" does not support subdirectory mode. It may not work correctly at a subpath."):_==="strip"?(n.style.display="block",n.innerHTML='ⓘ '+s.name+" has unverified subdirectory support. It may require additional configuration."):n.style.display="none"}else n.style.display="none";const i=SITE.defaults.dnsType||(SITE.configurationType==="public"?"public":"private"),c=SITE.defaults.sslType||(SITE.configurationType==="public"?"letsencrypt":"internal"),C=document.querySelector(`input[name="dns-type"][value="${i}"]`),B=document.querySelector(`input[name="ssl-type"][value="${c}"]`);C?C.checked=!0:document.querySelector('input[name="dns-type"][value="private"]').checked=!0,B?B.checked=!0:document.querySelector('input[name="ssl-type"][value="internal"]').checked=!0,t.value=SITE.defaults.targetIP||"localhost",o.checked=!1;const F=document.querySelector("#app-deploy-modal .flex-col-gap")?.closest("div"),q=document.querySelector("#app-deploy-modal details"),U=q?.querySelector("div");if(q&&U&&(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&&(U.appendChild(_),_.dataset.moved="1"),W&&!W.dataset.moved&&(U.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 le=te.includes(ee.hostPath);Z.style.cssText=`padding: 8px 14px; font-size: 0.85rem; background: color-mix(in srgb, var(--success) ${le?"40%":"15%"}, var(--card-bg)); border: 1px solid var(--success); border-radius: 6px; cursor: pointer; color: var(--fg);`,Z.innerHTML=`${escapeHtml(ee.folderName)}
from ${escapeHtml(ee.sourceImage)}`,Z.title=`${ee.hostPath} (from ${ee.sourceContainer})`,Z.onclick=()=>{const de=J.value.split(",").map(ce=>ce.trim()).filter(ce=>ce),pe=de.indexOf(ee.hostPath);pe>=0?(de.splice(pe,1),Z.style.background="color-mix(in srgb, var(--success) 15%, var(--card-bg))"):(de.push(ee.hostPath),Z.style.background="color-mix(in srgb, var(--success) 40%, var(--card-bg))"),J.value=de.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=` +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 le=Z.querySelector(".vol-host-path");openFolderBrowser(le)}})):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=` + `,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',o.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}`}u.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"),l.classList.add("show"),l.dataset.appTemplate=JSON.stringify(s)}async function E(s){const l=s.appTemplate,r=safeGetJSON(S,[]),f=l._useExisting&&l._existingContainer,u=r.find(t=>t.id===s.subdomain);if(!(u&&!f&&!confirm(`An app with subdomain "${s.subdomain}" already exists. Redeploy?`))){if(u){const t=r.indexOf(u);r.splice(t,1),safeSet(S,JSON.stringify(r))}if(f)s.port=l._existingContainer.primaryPort;else{const t=s.port||l.defaultPort||8080;showNotification(`Checking port ${t} availability...`,"info",0);const e=await P(t);if(!e.available){const o=await g(l.defaultPort||8080);if(confirm(`Port ${t} is already in use by ${e.conflict?.usedBy||"another container"}. + `: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 ${o} instead?`))s.port=o;else{showNotification("Deployment cancelled - port conflict","error",5e3);return}}}showNotification(f?`Configuring ${l.name} with existing container...`:`Deploying ${l.name}...`,"info",0);try{const t={appId:l.id,config:{subdomain:s.subdomain,ip:s.ip,createDns:s.dnsType==="private",port:s.port||l.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=l._existingContainer.id,t.config.existingPort=l._existingContainer.primaryPort,!s.port&&l._existingContainer.primaryPort&&(t.config.port=l._existingContainer.primaryPort));const o=await(await secureFetch("/api/v1/apps/deploy",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})).json();if(o.success){const a={id:s.subdomain,name:l.name,logo:`/assets/${l.id}.png`,containerId:o.containerId,url:o.url,ip:s.ip,appTemplate:l.id,tailscaleOnly:s.tailscaleOnly||!1};r.push(a),safeSet(S,JSON.stringify(r)),window.APPS&&!window.APPS.some(n=>n.id===l.id)&&(window.APPS.push(a),typeof window.buildGrid=="function"&&window.buildGrid(),typeof window.refreshAll=="function"&&setTimeout(()=>window.refreshAll(),500));let d=o.usedExisting?`${l.name} configured with existing container! -URL: ${o.url}`:`${l.name} deployed successfully! -URL: ${o.url}`;o.warning&&(d+=` +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: ${o.warning}`),showNotification(d,"success",8e3),delete l._useExisting,delete l._existingContainer,o.url&&o.url.startsWith("https://")&&$(o.url,l.name),o.setupInstructions&&o.setupInstructions.length>0&&setTimeout(()=>{const n=o.setupInstructions.join(` -`);showNotification(`Setup Instructions for ${l.name}: ${n}`,"info",1e4)},1e3)}else throw new Error(o.error||"Deployment failed")}catch(t){h.logError("[AppSelector] Deployment",t,{function:"deploy"}),showNotification(`Failed to deploy ${l.name}: ${t.message}`,"error",8e3)}}}async function $(s,l){showNotification(`\u23F3 Generating SSL certificate for ${l}...`,"warning",6e4);let r=0;const f=12,u=async()=>{r++;try{const t=await fetch(s,{method:"HEAD",mode:"no-cors"});return showNotification(`\u2705 ${l} is ready! SSL certificate generated.`,"success",5e3),!0}catch{return r{window.APPS.some(r=>r.id===l.id)||window.APPS.push(l)})}document.getElementById("add-service-btn")?.addEventListener("click",()=>{T(),N.classList.add("show")}),wireModal(N,document.getElementById("app-selector-cancel"));const L=document.getElementById("app-deploy-modal");document.getElementById("app-deploy-cancel")?.addEventListener("click",()=>{L.classList.remove("show")}),document.getElementById("app-deploy-confirm")?.addEventListener("click",()=>{const s=JSON.parse(L.dataset.appTemplate),l=document.getElementById("deploy-media-path").value.trim(),r=[];document.querySelectorAll("#volume-mounts-list .vol-host-path").forEach(u=>{r.push({hostPath:u.value.trim(),containerPath:u.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:l||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&&!l){showNotification("Please enter a media library path for this application","warning");return}L.classList.remove("show"),E(f)}),wireModal(L);const j=document.getElementById("folder-browser-modal"),M=document.getElementById("folder-browser-path"),O=document.getElementById("folder-browser-list"),x=document.getElementById("folder-browser-selected"),D=document.getElementById("folder-browser-selected-list");let y="",m=[],b=null;window.openFolderBrowser=function(s){b=s,m=s.value.split(",").map(l=>l.trim()).filter(l=>l),y="",v(),p(""),j.classList.add("show")};async function p(s){M.textContent=s||"Select a drive...",O.innerHTML='
Loading...
';try{const r=await(await fetch(`/api/v1/browse/directories?path=${encodeURIComponent(s)}`)).json();if(!r.success){O.innerHTML=`
Error: ${escapeHtml(r.error)}
`;return}y=r.path||"",M.textContent=y||"Select a drive...";let f="";r.parent&&r.parent!==r.path&&(f+=`
+\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='
Loading...
';try{const r=await(await fetch(`/api/v1/browse/directories?path=${encodeURIComponent(s)}`)).json();if(!r.success){D.innerHTML=`
Error: ${escapeHtml(r.error)}
`;return}y=r.path||"",M.textContent=y||"Select a drive...";let f="";r.parent&&r.parent!==r.path&&(f+=`
\u2B06\uFE0F .. Parent Directory -
`),r.items.length===0&&!r.parent?f+='
No browseable drives configured. Check your docker-compose.yml volume mounts.
':r.items.length===0?f+='
No subfolders found
':r.items.forEach(u=>{const t=u.type==="drive"?"\u{1F4BE}":"\u{1F4C1}",e=m.includes(u.path),o=e?"background: color-mix(in srgb, var(--success) 20%, transparent);":"";f+=`
+
`),r.items.length===0&&!r.parent?f+='
No browseable drives configured. Check your docker-compose.yml volume mounts.
':r.items.length===0?f+='
No subfolders found
':r.items.forEach(v=>{const t=v.type==="drive"?"\u{1F4BE}":"\u{1F4C1}",e=m.includes(v.path),n=e?"background: color-mix(in srgb, var(--success) 20%, transparent);":"";f+=`
${t} - ${escapeHtml(u.name)} + ${escapeHtml(v.name)} ${e?'\u2713':""} -
`}),O.innerHTML=f,O.querySelectorAll(".folder-item").forEach(u=>{u.addEventListener("click",()=>{p(u.dataset.path)}),u.addEventListener("mouseenter",()=>{u.style.background="var(--card-bg)"}),u.addEventListener("mouseleave",()=>{const t=m.includes(u.dataset.path);u.style.background=t?"color-mix(in srgb, var(--success) 20%, transparent)":""})})}catch(l){O.innerHTML=`
Failed to load: ${escapeHtml(l.message)}
`}}function v(){if(m.length===0){x.style.display="none";return}x.style.display="block",D.innerHTML=m.map(s=>` +
`}),D.innerHTML=f,D.querySelectorAll(".folder-item").forEach(v=>{v.addEventListener("click",()=>{p(v.dataset.path)}),v.addEventListener("mouseenter",()=>{v.style.background="var(--card-bg)"}),v.addEventListener("mouseleave",()=>{const t=m.includes(v.dataset.path);v.style.background=t?"color-mix(in srgb, var(--success) 20%, transparent)":""})})}catch(d){D.innerHTML=`
Failed to load: ${escapeHtml(d.message)}
`}}function u(){if(m.length===0){x.style.display="none";return}x.style.display="block",A.innerHTML=m.map(s=>` ${escapeHtml(s)} - `).join("")}window.removeSelectedFolder=function(s){m=m.filter(l=>l!==s),v(),p(y)},document.getElementById("folder-browser-select-current").addEventListener("click",()=>{y&&!m.includes(y)&&(m.push(y),v(),p(y))}),wireModal(j,document.getElementById("folder-browser-cancel")),document.getElementById("folder-browser-done").addEventListener("click",()=>{b&&(b.value=m.join(", ")),j.classList.remove("show")}),I()})(),(function(){injectModal("recipe-deploy-modal",`
+ `).join("")}window.removeSelectedFolder=function(s){m=m.filter(d=>d!==s),u(),p(y)},document.getElementById("folder-browser-select-current").addEventListener("click",()=>{y&&!m.includes(y)&&(m.push(y),u(),p(y))}),wireModal(j,document.getElementById("folder-browser-cancel")),document.getElementById("folder-browser-done").addEventListener("click",()=>{b&&(b.value=m.join(", ")),j.classList.remove("show")}),I()})(),(function(){injectModal("recipe-deploy-modal",`

Deploy Recipe

@@ -445,33 +445,33 @@ Try refreshing in a moment if you see a certificate error.`,"warning",1e4),!1}};
-
`);let h=null,S=null,A=null,k=1,N=!1;const R=document.getElementById("recipe-deploy-modal"),z=document.getElementById("recipe-cancel"),P=document.getElementById("recipe-prev"),g=document.getElementById("recipe-next");wireModal(R,z);async function T(){try{const y=await fetch("/api/v1/recipes/templates"),m=await y.json();if(m.success)return h=m.templates,S=m.categories,!0;if(y.status===403)return N=!1,!1}catch(y){console.warn("Failed to fetch recipe templates:",y.message)}return!1}async function w(){try{N=(await(await fetch("/api/v1/license/feature/recipes")).json()).available}catch{N=!1}return N}window.renderRecipeCards=async function(y){await w();let m;if(N&&h?m=h:m=H(),!m||m.length===0)return;const b=document.createElement("div");b.className="app-category-header",b.innerHTML="\u{1F9EA} Recipes",b.style.borderBottomColor="#8e44ad",y.appendChild(b);const p=Array.isArray(m)?m:Object.values(m);p.sort((v,s)=>(s.popularity||0)-(v.popularity||0));for(const v of p){const s=document.createElement("div");s.className="app-option",s.style.position="relative";const l=`
${v.componentCount||v.components?.length||"?"} apps
`,r=N?"":'
PREMIUM
';s.innerHTML=` + `);let h=null,S=null,O=null,E=1,N=!1;const R=document.getElementById("recipe-deploy-modal"),z=document.getElementById("recipe-cancel"),P=document.getElementById("recipe-prev"),g=document.getElementById("recipe-next");wireModal(R,z);async function L(){try{const y=await fetch("/api/v1/recipes/templates"),m=await y.json();if(m.success)return h=m.templates,S=m.categories,!0;if(y.status===403)return N=!1,!1}catch(y){console.warn("Failed to fetch recipe templates:",y.message)}return!1}async function w(){try{N=(await(await fetch("/api/v1/license/feature/recipes")).json()).available}catch{N=!1}return N}window.renderRecipeCards=async function(y){await w();let m;if(N&&h?m=h:m=T(),!m||m.length===0)return;const b=document.createElement("div");b.className="app-category-header",b.innerHTML="\u{1F9EA} Recipes",b.style.borderBottomColor="#8e44ad",y.appendChild(b);const p=Array.isArray(m)?m:Object.values(m);p.sort((u,s)=>(s.popularity||0)-(u.popularity||0));for(const u of p){const s=document.createElement("div");s.className="app-option",s.style.position="relative";const d=`
${u.componentCount||u.components?.length||"?"} apps
`,r=N?"":'
PREMIUM
';s.innerHTML=` ${r} -
${escapeHtml(v.icon||"\u{1F9EA}")}
-
${escapeHtml(v.name)}
-
${escapeHtml(v.description||"")}
- ${l} - `,s.onclick=()=>{if(!N){showNotification("Recipes require a DashCaddy Premium license. Click the License button to activate.","warning",5e3),window.openLicenseModal&&window.openLicenseModal();return}E(v)},y.appendChild(s)}};function H(){return[{id:"htpc-suite",name:"HTPC Suite",icon:"\u{1F3AC}",description:"Complete media automation: find, download, organize, and stream",componentCount:6,popularity:98},{id:"nextcloud-complete",name:"Nextcloud Complete",icon:"\u2601\uFE0F",description:"Full productivity suite: cloud storage, office editing, and collaboration",componentCount:4,popularity:90},{id:"smart-home",name:"Smart Home Hub",icon:"\u{1F3E0}",description:"Home automation: control, automate, and monitor IoT devices",componentCount:4,popularity:88},{id:"dev-environment",name:"Dev Environment",icon:"\u{1F4BB}",description:"Self-hosted development workflow: Git, CI/CD, IDE, and database",componentCount:4,popularity:82}]}function E(y){A=y,k=1;const m=document.getElementById("app-selector-modal");m&&m.classList.remove("show"),document.getElementById("recipe-deploy-title").textContent=`Deploy ${y.name}`,$(),I(),R.classList.add("show")}function $(){document.querySelectorAll("#recipe-steps .recipe-step").forEach(y=>{const m=parseInt(y.dataset.step);y.classList.toggle("active",m===k),y.classList.toggle("completed",m1&&k<4?"":"none",k===4?(g.style.display="none",z.textContent="Close"):k===3?(g.textContent="\u{1F680} Deploy",g.style.display="",z.textContent="Cancel"):(g.textContent="Next",g.style.display="",z.textContent="Cancel")}function I(){const y=document.getElementById("recipe-component-list");y.innerHTML="";const m=A.components||[];for(const b of m){const p=document.createElement("div");p.style.cssText="display: flex; align-items: center; gap: 12px; padding: 12px; border-radius: 8px; background: var(--card-bg); border: 1px solid var(--border);";const v=b.required,s=b.internal;p.innerHTML=` - ${escapeHtml(u.icon||"\u{1F9EA}")} +
${escapeHtml(u.name)}
+
${escapeHtml(u.description||"")}
+ ${d} + `,s.onclick=()=>{if(!N){showNotification("Recipes require a DashCaddy Premium license. Click the License button to activate.","warning",5e3),window.openLicenseModal&&window.openLicenseModal();return}k(u)},y.appendChild(s)}};function T(){return[{id:"htpc-suite",name:"HTPC Suite",icon:"\u{1F3AC}",description:"Complete media automation: find, download, organize, and stream",componentCount:6,popularity:98},{id:"nextcloud-complete",name:"Nextcloud Complete",icon:"\u2601\uFE0F",description:"Full productivity suite: cloud storage, office editing, and collaboration",componentCount:4,popularity:90},{id:"smart-home",name:"Smart Home Hub",icon:"\u{1F3E0}",description:"Home automation: control, automate, and monitor IoT devices",componentCount:4,popularity:88},{id:"dev-environment",name:"Dev Environment",icon:"\u{1F4BB}",description:"Self-hosted development workflow: Git, CI/CD, IDE, and database",componentCount:4,popularity:82}]}function k(y){O=y,E=1;const m=document.getElementById("app-selector-modal");m&&m.classList.remove("show"),document.getElementById("recipe-deploy-title").textContent=`Deploy ${y.name}`,B(),I(),R.classList.add("show")}function B(){document.querySelectorAll("#recipe-steps .recipe-step").forEach(y=>{const m=parseInt(y.dataset.step);y.classList.toggle("active",m===E),y.classList.toggle("completed",m1&&E<4?"":"none",E===4?(g.style.display="none",z.textContent="Close"):E===3?(g.textContent="\u{1F680} Deploy",g.style.display="",z.textContent="Cancel"):(g.textContent="Next",g.style.display="",z.textContent="Cancel")}function I(){const y=document.getElementById("recipe-component-list");y.innerHTML="";const m=O.components||[];for(const b of m){const p=document.createElement("div");p.style.cssText="display: flex; align-items: center; gap: 12px; padding: 12px; border-radius: 8px; background: var(--card-bg); border: 1px solid var(--border);";const u=b.required,s=b.internal;p.innerHTML=` +
${escapeHtml(b.role||b.id)}
${b.templateRef?escapeHtml(b.templateRef):"Built-in"} - ${v?'Required':'Optional'} + ${u?'Required':'Optional'} ${s?'(Internal)':""}
${b.note?`
\u26A0 ${escapeHtml(b.note)}
`:""}
- `,y.appendChild(p)}}function L(){const y=document.getElementById("recipe-volumes-section"),m=document.getElementById("recipe-volume-list"),b=A.sharedVolumes;if(b&&Object.keys(b).length>0){y.style.display="",m.innerHTML="";for(const[p,v]of Object.entries(b)){const s=document.createElement("div");s.style.cssText="display: grid; gap: 4px;",s.innerHTML=` - - 0){y.style.display="",m.innerHTML="";for(const[p,u]of Object.entries(b)){const s=document.createElement("div");s.style.cssText="display: grid; gap: 4px;",s.innerHTML=` + + -
${escapeHtml(v.description||"")}
- `,m.appendChild(s)}}else y.style.display="none"}function j(){const y=document.getElementById("recipe-review-content"),m=M(),b=document.querySelectorAll("#recipe-volume-list input[data-volume-key]"),p={};b.forEach(r=>{p[r.dataset.volumeKey]=r.value});const v=document.getElementById("recipe-timezone").value||"UTC",s=document.getElementById("recipe-ip").value||"host.docker.internal",l=document.getElementById("recipe-tailscale").checked;y.innerHTML=` -
${escapeHtml(A.name)}
-
${escapeHtml(A.description||"")}
+
${escapeHtml(u.description||"")}
+ `,m.appendChild(s)}}else y.style.display="none"}function j(){const y=document.getElementById("recipe-review-content"),m=M(),b=document.querySelectorAll("#recipe-volume-list input[data-volume-key]"),p={};b.forEach(r=>{p[r.dataset.volumeKey]=r.value});const u=document.getElementById("recipe-timezone").value||"UTC",s=document.getElementById("recipe-ip").value||"host.docker.internal",d=document.getElementById("recipe-tailscale").checked;y.innerHTML=` +
${escapeHtml(O.name)}
+
${escapeHtml(O.description||"")}
Components (${m.length}): @@ -488,15 +488,15 @@ Try refreshing in a moment if you see a certificate error.`,"warning",1e4),!1}};
`:""}
- Timezone: ${escapeHtml(v)} • IP: ${escapeHtml(s)} ${l?"• Tailscale only":""} + Timezone: ${escapeHtml(u)} • IP: ${escapeHtml(s)} ${d?"• Tailscale only":""}
- ${A.network?`
Docker network: ${escapeHtml(A.network.name)}
`:""} - `}function M(){const y=document.querySelectorAll("#recipe-component-list input[data-component-id]"),m=new Set;y.forEach(p=>{p.checked&&m.add(p.dataset.componentId)});const b=A.components||[];return b.filter(p=>p.required).forEach(p=>m.add(p.id)),b.filter(p=>m.has(p.id))}async function O(){const y=document.getElementById("recipe-progress-list"),m=document.getElementById("recipe-deploy-result");m.style.display="none",y.innerHTML="";const b=M();for(const l of b){const r=document.createElement("div");r.id=`recipe-progress-${l.id}`,r.style.cssText="display: flex; align-items: center; gap: 10px; padding: 10px 12px; border-radius: 6px; background: var(--card-bg); border: 1px solid var(--border); font-size: 0.85rem;",r.innerHTML=` + ${O.network?`
Docker network: ${escapeHtml(O.network.name)}
`:""} + `}function M(){const y=document.querySelectorAll("#recipe-component-list input[data-component-id]"),m=new Set;y.forEach(p=>{p.checked&&m.add(p.dataset.componentId)});const b=O.components||[];return b.filter(p=>p.required).forEach(p=>m.add(p.id)),b.filter(p=>m.has(p.id))}async function D(){const y=document.getElementById("recipe-progress-list"),m=document.getElementById("recipe-deploy-result");m.style.display="none",y.innerHTML="";const b=M();for(const d of b){const r=document.createElement("div");r.id=`recipe-progress-${d.id}`,r.style.cssText="display: flex; align-items: center; gap: 10px; padding: 10px 12px; border-radius: 6px; background: var(--card-bg); border: 1px solid var(--border); font-size: 0.85rem;",r.innerHTML=` \u23F3 - ${escapeHtml(l.role||l.id)} + ${escapeHtml(d.role||d.id)} Queued - `,y.appendChild(r)}const p=document.querySelectorAll("#recipe-volume-list input[data-volume-key]"),v={};p.forEach(l=>{v[l.dataset.volumeKey]=l.value});const s={selectedComponents:b.map(l=>l.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:v},componentOverrides:{}};for(const l of b)x(l.id,"deploying","Deploying...");try{const r=await(await secureFetch("/api/v1/recipes/deploy",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({recipeId:A.id,config:s})})).json();if(r.success){for(const f of r.deployed||[])x(f.id,"success",f.url?`Running \u2192 ${f.url}`:"Running");for(const f of r.errors||[])x(f.componentId,"error",f.error);m.style.display="",m.innerHTML=` + `,y.appendChild(r)}const p=document.querySelectorAll("#recipe-volume-list input[data-volume-key]"),u={};p.forEach(d=>{u[d.dataset.volumeKey]=d.value});const s={selectedComponents:b.map(d=>d.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 d of b)x(d.id,"deploying","Deploying...");try{const r=await(await secureFetch("/api/v1/recipes/deploy",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({recipeId:O.id,config:s})})).json();if(r.success){for(const f of r.deployed||[])x(f.id,"success",f.url?`Running \u2192 ${f.url}`:"Running");for(const f of r.errors||[])x(f.componentId,"error",f.error);m.style.display="",m.innerHTML=`
${escapeHtml(r.message||"Deployed!")}
${r.setupInstructions?`
@@ -504,11 +504,11 @@ Try refreshing in a moment if you see a certificate error.`,"warning",1e4),!1}};
    ${r.setupInstructions.map(f=>`
  • ${escapeHtml(f)}
  • `).join("")}
`:""}
- `,showNotification(`${A.name} recipe deployed successfully!`,"success",5e3),window.loadServices&&window.loadServices()}else m.style.display="",m.innerHTML=`
+ `,showNotification(`${O.name} recipe deployed successfully!`,"success",5e3),window.loadServices&&window.loadServices()}else m.style.display="",m.innerHTML=`
Deployment failed: ${escapeHtml(r.error||"Unknown error")} -
`,showNotification(`Recipe deployment failed: ${r.error}`,"error",5e3)}catch(l){m.style.display="",m.innerHTML=`
- Network error: ${escapeHtml(l.message)} -
`}}function x(y,m,b){const p=document.getElementById(`recipe-progress-${y}`);if(!p)return;const v=p.querySelector(".recipe-progress-icon"),s=p.querySelector(".recipe-progress-status");m==="deploying"?(v.textContent="\u23F3",s.style.color="var(--accent)"):m==="success"?(v.textContent="\u2705",s.style.color="var(--ok-fg)"):m==="error"&&(v.textContent="\u274C",s.style.color="var(--bad-fg)"),s.textContent=b}g.addEventListener("click",()=>{if(k===3){k=4,$(),O();return}k<3&&(k++,$(),k===2&&L(),k===3&&j())}),P.addEventListener("click",()=>{k>1&&k<4&&(k--,$())}),window.groupRecipeCards=function(){const y=document.querySelectorAll(".service-card[data-recipe-id]");if(y.length===0)return;const m={};y.forEach(b=>{const p=b.dataset.recipeId;m[p]||(m[p]=[]),m[p].push(b)});for(const[b,p]of Object.entries(m))p.length<2||p.forEach((v,s)=>{if(v.style.borderLeft="3px solid rgba(142,68,173,0.5)",s===0){let l=v.querySelector(".recipe-group-label");l||(l=document.createElement("div"),l.className="recipe-group-label",l.style.cssText="position: absolute; top: -8px; left: 12px; font-size: 0.6rem; padding: 1px 8px; border-radius: 8px; background: rgba(142,68,173,0.3); color: #d4a5ff; font-weight: 600; text-transform: uppercase; letter-spacing: 0.5px;",l.textContent=b.replace(/-/g," "),v.style.position="relative",v.appendChild(l))}})},window.manageRecipe=async function(y,m){const b=`/api/v1/recipes/${y}/${m}`,p=m==="remove"?"DELETE":"POST",v=m==="remove"?`/api/v1/recipes/${y}`:b;if(!(m==="remove"&&!confirm(`Remove the entire ${y} recipe? This will delete all containers and configuration.`)))try{const l=await(await secureFetch(v,{method:p})).json();l.success?(showNotification(`Recipe ${m}: ${l.results?.filter(r=>r.status!=="failed").length||0} components processed`,"success",4e3),window.loadServices&&window.loadServices()):showNotification(`Recipe ${m} failed: ${l.error}`,"error",5e3)}catch(s){showNotification(`Network error: ${s.message}`,"error",5e3)}};const D=document.createElement("style");D.textContent=` +
`,showNotification(`Recipe deployment failed: ${r.error}`,"error",5e3)}catch(d){m.style.display="",m.innerHTML=`
+ Network error: ${escapeHtml(d.message)} +
`}}function x(y,m,b){const p=document.getElementById(`recipe-progress-${y}`);if(!p)return;const u=p.querySelector(".recipe-progress-icon"),s=p.querySelector(".recipe-progress-status");m==="deploying"?(u.textContent="\u23F3",s.style.color="var(--accent)"):m==="success"?(u.textContent="\u2705",s.style.color="var(--ok-fg)"):m==="error"&&(u.textContent="\u274C",s.style.color="var(--bad-fg)"),s.textContent=b}g.addEventListener("click",()=>{if(E===3){E=4,B(),D();return}E<3&&(E++,B(),E===2&&C(),E===3&&j())}),P.addEventListener("click",()=>{E>1&&E<4&&(E--,B())}),window.groupRecipeCards=function(){const y=document.querySelectorAll(".service-card[data-recipe-id]");if(y.length===0)return;const m={};y.forEach(b=>{const p=b.dataset.recipeId;m[p]||(m[p]=[]),m[p].push(b)});for(const[b,p]of Object.entries(m))p.length<2||p.forEach((u,s)=>{if(u.style.borderLeft="3px solid rgba(142,68,173,0.5)",s===0){let d=u.querySelector(".recipe-group-label");d||(d=document.createElement("div"),d.className="recipe-group-label",d.style.cssText="position: absolute; top: -8px; left: 12px; font-size: 0.6rem; padding: 1px 8px; border-radius: 8px; background: rgba(142,68,173,0.3); color: #d4a5ff; font-weight: 600; text-transform: uppercase; letter-spacing: 0.5px;",d.textContent=b.replace(/-/g," "),u.style.position="relative",u.appendChild(d))}})},window.manageRecipe=async function(y,m){const b=`/api/v1/recipes/${y}/${m}`,p=m==="remove"?"DELETE":"POST",u=m==="remove"?`/api/v1/recipes/${y}`:b;if(!(m==="remove"&&!confirm(`Remove the entire ${y} recipe? This will delete all containers and configuration.`)))try{const d=await(await secureFetch(u,{method:p})).json();d.success?(showNotification(`Recipe ${m}: ${d.results?.filter(r=>r.status!=="failed").length||0} components processed`,"success",4e3),window.loadServices&&window.loadServices()):showNotification(`Recipe ${m} failed: ${d.error}`,"error",5e3)}catch(s){showNotification(`Network error: ${s.message}`,"error",5e3)}};const A=document.createElement("style");A.textContent=` .recipe-step { flex: 1; text-align: center; @@ -550,7 +550,7 @@ Try refreshing in a moment if you see a certificate error.`,"warning",1e4),!1}}; .recipe-step-panel { min-height: 180px; } - `,document.head.appendChild(D),w()})(),(function(){document.getElementById("reload-caddy-top")?.addEventListener("click",async()=>{const h=document.getElementById("reload-caddy-top"),S=h.textContent;try{h.textContent="\u23F3 Reloading...",h.disabled=!0;const A=await secureFetch("/api/v1/caddy/reload",{method:"POST",headers:{"Content-Type":"application/json"}}),k=await A.json();if(A.ok&&k.success)h.textContent="\u2705 Reloaded!",setTimeout(()=>{h.textContent=S,h.disabled=!1},2e3);else throw new Error(k.error||"Reload failed")}catch(A){h.textContent="\u274C Failed",showNotification(`Failed to reload Caddy: ${A.message}`,"error"),setTimeout(()=>{h.textContent=S,h.disabled=!1},2e3)}})})(),(function(){injectModal("error-log-modal",'

\u{1F4CB} Error Logs

Loading error logs...
');const h=document.getElementById("error-log-modal"),S=document.getElementById("error-log-content"),A=document.getElementById("view-error-logs"),k=document.getElementById("error-log-refresh"),N=document.getElementById("error-log-clear"),R=document.getElementById("error-log-close");async function z(){S.innerHTML='
Loading error logs...
';try{const T=await(await fetch("/api/v1/error-logs")).json();T.success&&T.logs?T.logs.length===0?S.innerHTML='
\u2705 No errors logged! Everything is working smoothly.
':S.innerHTML=T.logs.map(w=>` + `,document.head.appendChild(A),w()})(),(function(){document.getElementById("reload-caddy-top")?.addEventListener("click",async()=>{const h=document.getElementById("reload-caddy-top"),S=h.textContent;try{h.textContent="\u23F3 Reloading...",h.disabled=!0;const O=await secureFetch("/api/v1/caddy/reload",{method:"POST",headers:{"Content-Type":"application/json"}}),E=await O.json();if(O.ok&&E.success)h.textContent="\u2705 Reloaded!",setTimeout(()=>{h.textContent=S,h.disabled=!1},2e3);else throw new Error(E.error||"Reload failed")}catch(O){h.textContent="\u274C Failed",showNotification(`Failed to reload Caddy: ${O.message}`,"error"),setTimeout(()=>{h.textContent=S,h.disabled=!1},2e3)}})})(),(function(){injectModal("error-log-modal",'

\u{1F4CB} Error Logs

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

\u{1F4BE} Container Snapshots

-
`);const h=document.getElementById("snapshot-modal"),S=document.getElementById("snapshot-btn"),A=document.getElementById("snapshot-close"),k=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;k.innerHTML='';for(const L of I.containers){const j=document.createElement("option");j.value=L.id,j.textContent=`${L.name||L.id} (${L.image||"unknown"})`,j.dataset.name=L.name,j.dataset.image=L.image,j.dataset.status=L.status,j.dataset.created=L.created,k.appendChild(j)}}catch($){console.error("Failed to load containers:",$)}}function T($){if(!$||!$.value){N.style.display="none",P=null;return}P=$.value,document.getElementById("snapshot-image").textContent=$.dataset.image||"-",document.getElementById("snapshot-status").textContent=$.dataset.status||"-",document.getElementById("snapshot-created").textContent=$.dataset.created?new Date($.dataset.created*1e3).toLocaleString():"-",document.getElementById("snapshot-id").textContent=$.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 $=document.getElementById("snapshot-name").value.trim();if(!$){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:$,leaveRunning:I})})).json();j.success?(z.textContent=`\u2713 Snapshot "${$}" 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(L){z.textContent=`\u2717 Error: ${L.message}`,z.style.color="var(--bad-fg)"}finally{R.disabled=!1,R.textContent="\u{1F4BE} Create Snapshot"}}function H(){h.classList.add("show"),g()}function E(){h.classList.remove("show"),N.style.display="none",P=null,k.selectedIndex=0}S?.addEventListener("click",H),A?.addEventListener("click",E),wireModal(h,A),k?.addEventListener("change",$=>{const I=k.options[k.selectedIndex];T(I)}),R?.addEventListener("click",w),h?.querySelectorAll(".panel-tab").forEach($=>{$.addEventListener("click",()=>{h.querySelectorAll(".panel-tab").forEach(I=>I.classList.remove("active")),h.querySelectorAll(".panel-section").forEach(I=>I.classList.remove("active")),$.classList.add("active"),h.querySelector(`#${$.dataset.panel}`).classList.add("active")})})})(),(function(){injectModal("arr-setup-modal",`
+
`);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

@@ -749,73 +749,73 @@ Try refreshing in a moment if you see a certificate error.`,"warning",1e4),!1}};

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

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

-
`;for(const l of v.libraries){const r=l.type==="movie"?"\u{1F3AC}":l.type==="show"?"\u{1F4FA}":"\u{1F3B5}";s+=`
- ${r} ${escapeHtml(l.title)} - ${escapeHtml(String(l.count))} items -
`}s+="
",E.innerHTML=s,E.style.display="block"}}catch{}}S?.addEventListener("click",()=>{h.classList.add("show"),E.style.display="none",x()}),wireModal(h,A),k?.addEventListener("click",y),$?.addEventListener("click",y)})(),(function(){const h=new ErrorHandler;injectModal("notifications-modal",`
+
`}v+="
",T.innerHTML=v,B.style.display=u.failed>0?"block":"none",p.steps?.some(t=>t.step.includes("Plex")&&t.status==="success")&&b()}async function b(){try{const u=await(await fetch("/api/v1/plex/libraries")).json();if(u.success&&u.libraries?.length>0){let s=`
+

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

+
`;for(const d of u.libraries){const r=d.type==="movie"?"\u{1F3AC}":d.type==="show"?"\u{1F4FA}":"\u{1F3B5}";s+=`
+ ${r} ${escapeHtml(d.title)} + ${escapeHtml(String(d.count))} items +
`}s+="
",k.innerHTML=s,k.style.display="block"}}catch{}}S?.addEventListener("click",()=>{h.classList.add("show"),k.style.display="none",x()}),wireModal(h,O),E?.addEventListener("click",y),B?.addEventListener("click",y)})(),(function(){const h=new ErrorHandler;injectModal("notifications-modal",`

\u{1F514} Notification Settings

@@ -1000,15 +1000,15 @@ Try refreshing in a moment if you see a certificate error.`,"warning",1e4),!1}};
-
`);const S=document.getElementById("notifications-modal"),A=document.getElementById("manage-notifications"),k=document.getElementById("notifications-save"),N=document.getElementById("notifications-cancel");["discord","telegram","ntfy","email"].forEach(E=>{const $=document.getElementById(`${E}-enabled`),I=document.getElementById(`${E}-config`);$?.addEventListener("change",()=>{I.style.display=$.checked?"block":"none"})});const R=document.getElementById("health-check-enabled"),z=document.getElementById("health-check-config");R?.addEventListener("change",()=>{z.style.opacity=R.checked?"1":"0.5"});async function P(){try{const $=await(await fetch("/api/v1/notifications/config")).json();if($.success){const I=$.config;document.getElementById("notifications-enabled").checked=I.enabled,document.getElementById("discord-enabled").checked=I.providers?.discord?.enabled||!1,document.getElementById("telegram-enabled").checked=I.providers?.telegram?.enabled||!1,document.getElementById("ntfy-enabled").checked=I.providers?.ntfy?.enabled||!1,document.getElementById("email-enabled").checked=I.providers?.email?.enabled||!1,document.getElementById("discord-config").style.display=I.providers?.discord?.enabled?"block":"none",document.getElementById("telegram-config").style.display=I.providers?.telegram?.enabled?"block":"none",document.getElementById("ntfy-config").style.display=I.providers?.ntfy?.enabled?"block":"none",document.getElementById("email-config").style.display=I.providers?.email?.enabled?"block":"none",I.providers?.ntfy?.serverUrl&&(document.getElementById("ntfy-server").value=I.providers.ntfy.serverUrl),I.providers?.email?.host&&(document.getElementById("email-host").value=I.providers.email.host),I.providers?.email?.from&&(document.getElementById("email-from").value=I.providers.email.from),document.getElementById("health-check-enabled").checked=I.healthCheck?.enabled||!1,I.healthCheck?.intervalMinutes&&(document.getElementById("health-check-interval").value=I.healthCheck.intervalMinutes),I.healthCheck?.lastCheck&&(document.getElementById("health-check-status").textContent=`Last check: ${new Date(I.healthCheck.lastCheck).toLocaleString()}`),document.getElementById("event-container-down").checked=I.events?.containerDown!==!1,document.getElementById("event-container-up").checked=I.events?.containerUp!==!1,document.getElementById("event-deploy-success").checked=I.events?.deploymentSuccess!==!1,document.getElementById("event-deploy-failed").checked=I.events?.deploymentFailed!==!1,document.getElementById("event-resource-alert").checked=I.events?.resourceAlert!==!1}}catch(E){h.logError("[Notifications] Load Config",E,{function:"loadConfig"})}}async function g(){try{const $=await(await fetch("/api/v1/notifications/history?limit=10")).json(),I=document.getElementById("notification-history");$.success&&$.history?.length>0?I.innerHTML=$.history.map(L=>{const j=new Date(L.timestamp).toLocaleString();return` + `);const S=document.getElementById("notifications-modal"),O=document.getElementById("manage-notifications"),E=document.getElementById("notifications-save"),N=document.getElementById("notifications-cancel");["discord","telegram","ntfy","email"].forEach(k=>{const B=document.getElementById(`${k}-enabled`),I=document.getElementById(`${k}-config`);B?.addEventListener("change",()=>{I.style.display=B.checked?"block":"none"})});const R=document.getElementById("health-check-enabled"),z=document.getElementById("health-check-config");R?.addEventListener("change",()=>{z.style.opacity=R.checked?"1":"0.5"});async function P(){try{const B=await(await fetch("/api/v1/notifications/config")).json();if(B.success){const I=B.config;document.getElementById("notifications-enabled").checked=I.enabled,document.getElementById("discord-enabled").checked=I.providers?.discord?.enabled||!1,document.getElementById("telegram-enabled").checked=I.providers?.telegram?.enabled||!1,document.getElementById("ntfy-enabled").checked=I.providers?.ntfy?.enabled||!1,document.getElementById("email-enabled").checked=I.providers?.email?.enabled||!1,document.getElementById("discord-config").style.display=I.providers?.discord?.enabled?"block":"none",document.getElementById("telegram-config").style.display=I.providers?.telegram?.enabled?"block":"none",document.getElementById("ntfy-config").style.display=I.providers?.ntfy?.enabled?"block":"none",document.getElementById("email-config").style.display=I.providers?.email?.enabled?"block":"none",I.providers?.ntfy?.serverUrl&&(document.getElementById("ntfy-server").value=I.providers.ntfy.serverUrl),I.providers?.email?.host&&(document.getElementById("email-host").value=I.providers.email.host),I.providers?.email?.from&&(document.getElementById("email-from").value=I.providers.email.from),document.getElementById("health-check-enabled").checked=I.healthCheck?.enabled||!1,I.healthCheck?.intervalMinutes&&(document.getElementById("health-check-interval").value=I.healthCheck.intervalMinutes),I.healthCheck?.lastCheck&&(document.getElementById("health-check-status").textContent=`Last check: ${new Date(I.healthCheck.lastCheck).toLocaleString()}`),document.getElementById("event-container-down").checked=I.events?.containerDown!==!1,document.getElementById("event-container-up").checked=I.events?.containerUp!==!1,document.getElementById("event-deploy-success").checked=I.events?.deploymentSuccess!==!1,document.getElementById("event-deploy-failed").checked=I.events?.deploymentFailed!==!1,document.getElementById("event-resource-alert").checked=I.events?.resourceAlert!==!1}}catch(k){h.logError("[Notifications] Load Config",k,{function:"loadConfig"})}}async function g(){try{const B=await(await fetch("/api/v1/notifications/history?limit=10")).json(),I=document.getElementById("notification-history");B.success&&B.history?.length>0?I.innerHTML=B.history.map(C=>{const j=new Date(C.timestamp).toLocaleString();return`
- ${L.type==="success"?"\u2713":L.type==="error"?"\u2717":"\u2139"} + ${C.type==="success"?"\u2713":C.type==="error"?"\u2717":"\u2139"}
-
${escapeHtml(L.title)}
+
${escapeHtml(C.title)}
${j}
- `}).join(""):I.innerHTML='
No notifications yet
'}catch(E){h.logError("[Notifications] Load History",E,{function:"loadHistory"})}}async function T(){try{const E={enabled:document.getElementById("notifications-enabled").checked,providers:{discord:{enabled:document.getElementById("discord-enabled").checked,webhookUrl:document.getElementById("discord-webhook").value.trim()},telegram:{enabled:document.getElementById("telegram-enabled").checked,botToken:document.getElementById("telegram-bot-token").value.trim(),chatId:document.getElementById("telegram-chat-id").value.trim()},ntfy:{enabled:document.getElementById("ntfy-enabled").checked,serverUrl:document.getElementById("ntfy-server").value.trim()||"https://ntfy.sh",topic:document.getElementById("ntfy-topic").value.trim()},email:{enabled:document.getElementById("email-enabled").checked,host:document.getElementById("email-host").value.trim(),port:parseInt(document.getElementById("email-port").value)||587,secure:document.getElementById("email-secure").checked,user:document.getElementById("email-user").value.trim(),pass:document.getElementById("email-pass").value.trim(),from:document.getElementById("email-from").value.trim(),to:document.getElementById("email-to").value.trim()}},events:{containerDown:document.getElementById("event-container-down").checked,containerUp:document.getElementById("event-container-up").checked,deploymentSuccess:document.getElementById("event-deploy-success").checked,deploymentFailed:document.getElementById("event-deploy-failed").checked,resourceAlert:document.getElementById("event-resource-alert").checked},healthCheck:{enabled:document.getElementById("health-check-enabled").checked,intervalMinutes:parseInt(document.getElementById("health-check-interval").value)||5}},I=await(await secureFetch("/api/v1/notifications/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(E)})).json();I.success?(showNotification("Notification settings saved","success",3e3),S.classList.remove("show")):showNotification(`Failed to save: ${I.error}`,"error",3e3)}catch(E){showNotification(`Error: ${E.message}`,"error",3e3)}}async function w(E){try{const I=await(await secureFetch("/api/v1/notifications/test",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:E})})).json();I.success?showNotification(`Test ${E} notification sent!`,"success",3e3):showNotification(`Test failed: ${I.error}`,"error",3e3)}catch($){showNotification(`Error: ${$.message}`,"error",3e3)}}document.getElementById("discord-test")?.addEventListener("click",()=>w("discord")),document.getElementById("telegram-test")?.addEventListener("click",()=>w("telegram")),document.getElementById("ntfy-test")?.addEventListener("click",()=>w("ntfy")),document.getElementById("email-test")?.addEventListener("click",()=>w("email")),document.getElementById("health-check-now")?.addEventListener("click",async()=>{try{const $=await(await secureFetch("/api/v1/notifications/health-check",{method:"POST"})).json();$.success&&(document.getElementById("health-check-status").textContent=`Last check: ${new Date($.lastCheck).toLocaleString()} (${$.containersMonitored} containers)`,showNotification("Health check completed","success",2e3))}catch(E){showNotification(`Error: ${E.message}`,"error",3e3)}}),A?.addEventListener("click",()=>{S.classList.add("show"),P(),g()}),k?.addEventListener("click",T),document.getElementById("notifications-send-test")?.addEventListener("click",async()=>{const E=document.getElementById("notifications-send-test"),$=E.textContent;E.textContent="Sending...",E.disabled=!0;try{const L=await(await secureFetch("/api/v1/notifications/send",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({event:"test",data:{message:"This is a test notification from DashCaddy."},type:"info"})})).json();L.success?(showNotification("Test notification sent!","success",3e3),H()):showNotification(`Test failed: ${L.results?.map(j=>`${j.provider}: ${j.error||"ok"}`).join(", ")}`,"error",5e3)}catch(I){showNotification(`Error: ${I.message}`,"error",3e3)}finally{E.textContent=$,E.disabled=!1}});async function H(){try{const $=await(await fetch("/api/v1/notifications/status")).json();if($.success&&$.lastSent){const I=document.getElementById("last-notification-sent");I&&(I.textContent=`Last sent: ${new Date($.lastSent).toLocaleString()}`)}}catch{}}wireModal(S,N)})(),(function(){document.addEventListener("click",h=>{const S=h.target.closest(".panel-tab");if(!S)return;const A=S.dataset.panel;if(!A)return;const k=S.closest(".panel-tabs"),N=k.closest(".weather-modal-content");k.querySelectorAll(".panel-tab").forEach(z=>z.classList.remove("active")),S.classList.add("active"),N.querySelectorAll(".panel-section").forEach(z=>z.classList.remove("active"));const R=N.querySelector("#"+A);R&&R.classList.add("active")})})(),(function(){var h=["dashcaddy_site_config","dashcaddy_onboarding","dashcaddy-encryption-key","dashcaddy-setup","dashcaddy-config","theme","user-themes","custom-theme","custom-apps","custom-services","toolbar-sections","weather-location","weather-zip","weather-geo","weather-unit","clock-style","clock-chimes","clock-chime-volume"];function S(){for(var e={},o=0;o + `}).join(""):I.innerHTML='
No notifications yet
'}catch(k){h.logError("[Notifications] Load History",k,{function:"loadHistory"})}}async function L(){try{const k={enabled:document.getElementById("notifications-enabled").checked,providers:{discord:{enabled:document.getElementById("discord-enabled").checked,webhookUrl:document.getElementById("discord-webhook").value.trim()},telegram:{enabled:document.getElementById("telegram-enabled").checked,botToken:document.getElementById("telegram-bot-token").value.trim(),chatId:document.getElementById("telegram-chat-id").value.trim()},ntfy:{enabled:document.getElementById("ntfy-enabled").checked,serverUrl:document.getElementById("ntfy-server").value.trim()||"https://ntfy.sh",topic:document.getElementById("ntfy-topic").value.trim()},email:{enabled:document.getElementById("email-enabled").checked,host:document.getElementById("email-host").value.trim(),port:parseInt(document.getElementById("email-port").value)||587,secure:document.getElementById("email-secure").checked,user:document.getElementById("email-user").value.trim(),pass:document.getElementById("email-pass").value.trim(),from:document.getElementById("email-from").value.trim(),to:document.getElementById("email-to").value.trim()}},events:{containerDown:document.getElementById("event-container-down").checked,containerUp:document.getElementById("event-container-up").checked,deploymentSuccess:document.getElementById("event-deploy-success").checked,deploymentFailed:document.getElementById("event-deploy-failed").checked,resourceAlert:document.getElementById("event-resource-alert").checked},healthCheck:{enabled:document.getElementById("health-check-enabled").checked,intervalMinutes:parseInt(document.getElementById("health-check-interval").value)||5}},I=await(await secureFetch("/api/v1/notifications/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(k)})).json();I.success?(showNotification("Notification settings saved","success",3e3),S.classList.remove("show")):showNotification(`Failed to save: ${I.error}`,"error",3e3)}catch(k){showNotification(`Error: ${k.message}`,"error",3e3)}}async function w(k){try{const I=await(await secureFetch("/api/v1/notifications/test",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:k})})).json();I.success?showNotification(`Test ${k} notification sent!`,"success",3e3):showNotification(`Test failed: ${I.error}`,"error",3e3)}catch(B){showNotification(`Error: ${B.message}`,"error",3e3)}}document.getElementById("discord-test")?.addEventListener("click",()=>w("discord")),document.getElementById("telegram-test")?.addEventListener("click",()=>w("telegram")),document.getElementById("ntfy-test")?.addEventListener("click",()=>w("ntfy")),document.getElementById("email-test")?.addEventListener("click",()=>w("email")),document.getElementById("health-check-now")?.addEventListener("click",async()=>{try{const B=await(await secureFetch("/api/v1/notifications/health-check",{method:"POST"})).json();B.success&&(document.getElementById("health-check-status").textContent=`Last check: ${new Date(B.lastCheck).toLocaleString()} (${B.containersMonitored} containers)`,showNotification("Health check completed","success",2e3))}catch(k){showNotification(`Error: ${k.message}`,"error",3e3)}}),O?.addEventListener("click",()=>{S.classList.add("show"),P(),g()}),E?.addEventListener("click",L),document.getElementById("notifications-send-test")?.addEventListener("click",async()=>{const k=document.getElementById("notifications-send-test"),B=k.textContent;k.textContent="Sending...",k.disabled=!0;try{const C=await(await secureFetch("/api/v1/notifications/send",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({event:"test",data:{message:"This is a test notification from DashCaddy."},type:"info"})})).json();C.success?(showNotification("Test notification sent!","success",3e3),T()):showNotification(`Test failed: ${C.results?.map(j=>`${j.provider}: ${j.error||"ok"}`).join(", ")}`,"error",5e3)}catch(I){showNotification(`Error: ${I.message}`,"error",3e3)}finally{k.textContent=B,k.disabled=!1}});async function T(){try{const B=await(await fetch("/api/v1/notifications/status")).json();if(B.success&&B.lastSent){const I=document.getElementById("last-notification-sent");I&&(I.textContent=`Last sent: ${new Date(B.lastSent).toLocaleString()}`)}}catch{}}wireModal(S,N)})(),(function(){document.addEventListener("click",h=>{const S=h.target.closest(".panel-tab");if(!S)return;const O=S.dataset.panel;if(!O)return;const E=S.closest(".panel-tabs"),N=E.closest(".weather-modal-content");E.querySelectorAll(".panel-tab").forEach(z=>z.classList.remove("active")),S.classList.add("active"),N.querySelectorAll(".panel-section").forEach(z=>z.classList.remove("active"));const R=N.querySelector("#"+O);R&&R.classList.add("active")})})(),(function(){var h=["dashcaddy_site_config","dashcaddy_onboarding","dashcaddy-encryption-key","dashcaddy-setup","dashcaddy-config","theme","user-themes","custom-theme","custom-apps","custom-services","toolbar-sections","weather-location","weather-zip","weather-geo","weather-unit","clock-style","clock-chimes","clock-chime-volume"];function S(){for(var e={},n=0;n

\u{1F4BE} Backup & Restore

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

\u2795 Add New Schedule

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

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

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

\u2795 Add New Schedule

',j.innerHTML=l,j.querySelectorAll(".schedule-toggle").forEach(function(H){H.addEventListener("change",function(){m(H.dataset.appid,{enabled:H.checked})})}),j.querySelectorAll(".schedule-select").forEach(function(H){H.addEventListener("change",function(){m(H.dataset.appid,{schedule:H.value})})}),j.querySelectorAll(".retention-input").forEach(function(H){H.addEventListener("change",function(){m(H.dataset.appid,{retention:{keep:parseInt(H.value)||7}})})}),j.querySelectorAll(".schedule-run-now").forEach(function(H){H.addEventListener("click",function(){b(H.dataset.appid)})}),j.querySelectorAll(".schedule-delete").forEach(function(H){H.addEventListener("click",function(){p(H.dataset.appid)})}),document.getElementById("add-schedule-btn")?.addEventListener("click",u)}catch(H){j.innerHTML='
Failed to load: '+escapeHtml(H.message)+"
"}}}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";$+='
';for(var H=Object.keys(l).sort(),U=0;U
'+escapeHtml(c)+' ('+q.length+" backup(s))
";for(var F=0;F
'+i.sizeFormatted+'
'+G+'
'}$+=""}$+="",D.innerHTML=$,D.querySelectorAll(".disk-compare-btn").forEach(function(J){J.addEventListener("click",function(){v(J.dataset.appid,J.dataset.filename)})}),D.querySelectorAll(".disk-restore-btn").forEach(function(J){J.addEventListener("click",function(){t(J.dataset.appid,J.dataset.filename)})})}catch(J){D.innerHTML='
Failed: '+escapeHtml(J.message)+"
"}}}async function d(){if(M){M.innerHTML='
Loading...
';try{var e=await fetch("/api/v1/backups/history?limit=50"),n=await e.json();if(!n.success||!n.history?.length){M.innerHTML='
\u{1F4CB} No backup history yet
';return}for(var a='
',l=0;l',a+='
',a+=' '+escapeHtml(o.name||"backup")+"",a+='
',a+=' '+escapeHtml(o.status)+"",o.status==="success"&&(a+=' '),a+="
",a+="
",a+='
',a+=" "+new Date(o.timestamp).toLocaleString()+" | "+i+" MB | "+(o.duration?(o.duration/1e3).toFixed(1)+"s":"--"),o.encrypted&&(a+=" | \u{1F512}"),a+="
",a+="
"}a+="",M.innerHTML=a,M.querySelectorAll(".backup-restore-btn").forEach(function(c){c.addEventListener("click",function(){window.__restoreServerBackup(c.dataset.backupId)})})}catch(c){M.innerHTML='
Failed: '+escapeHtml(c.message)+"
"}}}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.
`;return}}catch{}x.innerHTML='
Loading...
';try{var a=await fetch("/api/v1/services"),l=await a.json(),o=l.services||[];if(o.length===0){x.innerHTML='
\u{1F4E6} No apps deployed yet
';return}for(var i='
',x.innerHTML=i,document.getElementById("pit-load-btn")?.addEventListener("click",function(){var $=document.getElementById("pit-app-select")?.value;$&&f($)})}catch($){x.innerHTML='
Failed: '+escapeHtml($.message)+"
"}}}async function f(e){var n=document.getElementById("pit-backups-list");if(n){n.innerHTML='
Loading backups...
';try{var a=await fetch("/api/v1/backups/files/"+encodeURIComponent(e)),l=await a.json();if(!l.success||!l.files||l.files.length===0){n.innerHTML='
\u{1F4BE} No backup files for '+escapeHtml(e)+"
";return}for(var o='
'+l.files.length+' backup(s)
',i=0;i
'+c.sizeFormatted+'
'+$+'
'}o+="",n.innerHTML=o,n.querySelectorAll(".pit-compare-btn").forEach(function(H){H.addEventListener("click",function(){v(H.dataset.appid,H.dataset.filename)})}),n.querySelectorAll(".pit-restore-btn").forEach(function(H){H.addEventListener("click",function(){t(H.dataset.appid,H.dataset.filename)})})}catch(H){n.innerHTML='
Failed: '+escapeHtml(H.message)+"
"}}}async function v(e,n){try{var a=await secureFetch("/api/v1/backups/compare/"+encodeURIComponent(n),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({})}),l=await a.json();if(!l.success){showNotification("Compare failed: "+(l.error||"Unknown"),"error");return}var o=l.diff,i='

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

Size: '+(o.sizeFormatted||"?")+" | Created: "+new Date(o.timestamp).toLocaleString()+"
";if(o.services){var c=o.services.hasChanges?"\u{1F534}":"\u{1F7E2}";i+='
'+c+' Services (backup vs current)
Backup: '+o.services.backupCount+" services | Current: "+o.services.currentCount+" services
",o.services.hasChanges&&(i+='
Services differ \u2014 restoring will replace current configuration
'),i+="
"}if(o.config){var $=o.config.hasChanges?"\u{1F534}":"\u{1F7E2}";i+='
'+$+" Configuration
",o.config.hasChanges?i+='
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(o),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({restartContainers:!0})}),d=await a.json();d.success?(showNotification(e+" restored to "+o,"success"),setTimeout(function(){location.reload()},1500)):showNotification("Restore failed: "+(d.error||"Unknown"),"error")}catch(n){showNotification("Restore error: "+n.message,"error")}}})(),(function(){injectModal("stats-modal",`
+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

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

\u2699\uFE0F Alert Configuration

@@ -1279,7 +1279,7 @@ This will replace current configuration, credentials, and data. Containers will - ${o} + ${n}
@@ -1293,7 +1293,7 @@ This will replace current configuration, credentials, and data. Containers will
`;P.innerHTML=` - ${d} + ${l}

\u{1F4CB} Recent Alerts

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

\u{1F3E5} Health Check Dashboard

-
`);const h=document.getElementById("health-modal"),S=document.getElementById("health-check-btn"),A=document.getElementById("health-cancel"),k=document.getElementById("health-refresh-btn"),N=document.getElementById("health-status-container"),R=document.getElementById("health-incidents-container"),z=document.getElementById("health-config-container"),P=document.getElementById("health-last-update"),g=document.getElementById("health-add-btn"),T=document.getElementById("health-config-form"),w=document.getElementById("health-form-title"),H=document.getElementById("health-form-cancel"),E=document.getElementById("health-form-save");let $=null;function I(y){return y>=99.9?"var(--ok-fg)":y>=95?"#f39c12":"var(--bad-fg)"}function L(y){const m={critical:"var(--bad-fg)",high:"#ff6b6b",medium:"#f39c12",low:"var(--muted)"};return`${y}`}async function j(){try{const m=await(await fetch("/api/v1/health-checks/status")).json();if(!m.success||!m.status||Object.keys(m.status).length===0){N.innerHTML='
\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+='',p+='',p+='';for(const v of b){const s=v.status==="up",l=s?"var(--dot-ok)":"var(--dot-bad)",r=v.uptime?.["24h"]??"-",f=v.uptime?.["7d"]??"-",u=v.avgResponseTime!=null?Math.round(v.avgResponseTime)+"ms":"-",t=v.timestamp?timeAgo(v.timestamp):"-";p+=``,p+=``,p+=``,p+=``,p+=``,p+=``,p+=``,p+="",p+=``}p+="
ServiceStatusUptime 24hUptime 7dAvg ResponseLast Check
${escapeHtml(v.name||v.serviceId)}${s?"Up":"Down"}${typeof r=="number"?r.toFixed(1)+"%":r}${typeof f=="number"?f.toFixed(1)+"%":f}${u}${t}
",N.innerHTML=p,P.textContent="Updated "+new Date().toLocaleTimeString(),N.querySelectorAll("tr[data-health-id]").forEach(v=>{v.addEventListener("click",async()=>{const s=v.dataset.healthId,l=document.getElementById("health-detail-"+s);if(l){if(l.style.display!=="none"){l.style.display="none";return}l.style.display="";try{const f=await(await fetch(`/api/v1/health-checks/${s}/stats?hours=24`)).json();if(f.success&&f.stats){const u=f.stats,t=u.responseTime||{};l.querySelector("td").innerHTML=` + `);const h=document.getElementById("health-modal"),S=document.getElementById("health-check-btn"),O=document.getElementById("health-cancel"),E=document.getElementById("health-refresh-btn"),N=document.getElementById("health-status-container"),R=document.getElementById("health-incidents-container"),z=document.getElementById("health-config-container"),P=document.getElementById("health-last-update"),g=document.getElementById("health-add-btn"),L=document.getElementById("health-config-form"),w=document.getElementById("health-form-title"),T=document.getElementById("health-form-cancel"),k=document.getElementById("health-form-save");let B=null;function I(y){return y>=99.9?"var(--ok-fg)":y>=95?"#f39c12":"var(--bad-fg)"}function C(y){const m={critical:"var(--bad-fg)",high:"#ff6b6b",medium:"#f39c12",low:"var(--muted)"};return`${y}`}async function j(){try{const m=await(await fetch("/api/v1/health-checks/status")).json();if(!m.success||!m.status||Object.keys(m.status).length===0){N.innerHTML='
\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+='',p+='',p+='';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+=``,p+=``,p+=``,p+=``,p+=``,p+=``,p+=``,p+="",p+=``}p+="
ServiceStatusUptime 24hUptime 7dAvg ResponseLast Check
${escapeHtml(u.name||u.serviceId)}${s?"Up":"Down"}${typeof r=="number"?r.toFixed(1)+"%":r}${typeof f=="number"?f.toFixed(1)+"%":f}${v}${t}
",N.innerHTML=p,P.textContent="Updated "+new Date().toLocaleTimeString(),N.querySelectorAll("tr[data-health-id]").forEach(u=>{u.addEventListener("click",async()=>{const s=u.dataset.healthId,d=document.getElementById("health-detail-"+s);if(d){if(d.style.display!=="none"){d.style.display="none";return}d.style.display="";try{const f=await(await fetch(`/api/v1/health-checks/${s}/stats?hours=24`)).json();if(f.success&&f.stats){const v=f.stats,t=v.responseTime||{};d.querySelector("td").innerHTML=`
-
Total Checks
${u.totalChecks||0}
-
Uptime
${(u.uptime||0).toFixed(2)}%
+
Total Checks
${v.totalChecks||0}
+
Uptime
${(v.uptime||0).toFixed(2)}%
Avg Response
${Math.round(t.avg||0)}ms
P95 / P99
${Math.round(t.p95||0)}ms / ${Math.round(t.p99||0)}ms
Min Response
${Math.round(t.min||0)}ms
Max Response
${Math.round(t.max||0)}ms
-
Up Checks
${u.upChecks||0}
-
Down Checks
${u.downChecks||0}
-
`}else l.querySelector("td").innerHTML='
No detailed stats available for this period.
'}catch(r){l.querySelector("td").innerHTML=`
Failed: ${escapeHtml(r.message)}
`}}})})}catch(y){N.innerHTML=`
Failed to load health status: ${escapeHtml(y.message)}
`}}async function M(){try{const[y,m]=await Promise.all([fetch("/api/v1/health-checks/incidents"),fetch("/api/v1/health-checks/incidents/history?limit=50")]),b=await y.json(),p=await m.json();let v="";const s=b.success&&b.incidents?b.incidents:[];if(s.length>0){v+='

Open Incidents ('+s.length+")

";for(const r of s)v+=`
+
Up Checks
${v.upChecks||0}
+
Down Checks
${v.downChecks||0}
+
`}else d.querySelector("td").innerHTML='
No detailed stats available for this period.
'}catch(r){d.querySelector("td").innerHTML=`
Failed: ${escapeHtml(r.message)}
`}}})})}catch(y){N.innerHTML=`
Failed to load health status: ${escapeHtml(y.message)}
`}}async function M(){try{const[y,m]=await Promise.all([fetch("/api/v1/health-checks/incidents"),fetch("/api/v1/health-checks/incidents/history?limit=50")]),b=await y.json(),p=await m.json();let u="";const s=b.success&&b.incidents?b.incidents:[];if(s.length>0){u+='

Open Incidents ('+s.length+")

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

Incident History

',v+='',v+='';for(const r of l){const f=r.status==="resolved",u=f&&r.duration?r.duration<6e4?Math.round(r.duration/1e3)+"s":Math.round(r.duration/6e4)+"m":"-";v+='',v+=``,v+=``,v+=``,v+=``,v+=``,v+=``,v+=""}v+="
ServiceTypeSeverityStatusDurationWhen
${escapeHtml(r.serviceId)}${escapeHtml(r.type)}${L(r.severity)}${r.status}${u}${timeAgo(r.createdAt)}
"}R.innerHTML=v||'
\u{1F6A8}No incidents recorded yet.
'}catch(y){R.innerHTML=`
Failed: ${escapeHtml(y.message)}
`}}async function O(){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+='';for(const v of b){const s=v.status==="up";p+='',p+=``,p+=``,p+=``,p+='"}p+="
ServiceStatusSLA TargetActions
${escapeHtml(v.name||v.serviceId)}${s?"Up":"Down"}${v.sla?.target?v.sla.target+"%":"-"}',p+=``,p+=``,p+="
",z.innerHTML=p}catch(y){z.innerHTML=`
Failed: ${escapeHtml(y.message)}
`}}function x(y,m,b,p,v,s,l){$=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=v||"200",document.getElementById("health-form-sla").value=s||99.9,document.getElementById("health-form-slow").value=l||5e3,T.style.display="",g.style.display="none"}function D(){T.style.display="none",g.style.display="",$=null}g?.addEventListener("click",()=>x("","","",1e4,"200",99.9,5e3)),H?.addEventListener("click",D),E?.addEventListener("click",async()=>{const y=$||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(v=>parseInt(v.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{E.textContent="Saving...",E.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");D(),O(),j()}catch(v){showNotification("Error: "+v.message,"error")}finally{E.textContent="Save",E.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);O(),j()}catch(b){showNotification("Error: "+b.message,"error")}}),S?.addEventListener("click",()=>{h?.classList.add("show"),j()}),wireModal(h,A),k?.addEventListener("click",j),document.querySelector('[data-panel="health-incidents"]')?.addEventListener("click",M),document.querySelector('[data-panel="health-config"]')?.addEventListener("click",O)})(),(function(){injectModal("updates-modal",`
+
`;u+="
"}else u+='
All services operational \u2014 no open incidents
';const d=p.success&&p.history?p.history:[];if(d.length>0){u+='

Incident History

',u+='',u+='';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+=``,u+=``,u+=``,u+=``,u+=``,u+=``,u+=""}u+="
ServiceTypeSeverityStatusDurationWhen
${escapeHtml(r.serviceId)}${escapeHtml(r.type)}${C(r.severity)}${r.status}${v}${timeAgo(r.createdAt)}
"}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+='';for(const u of b){const s=u.status==="up";p+='',p+=``,p+=``,p+=``,p+='"}p+="
ServiceStatusSLA TargetActions
${escapeHtml(u.name||u.serviceId)}${s?"Up":"Down"}${u.sla?.target?u.sla.target+"%":"-"}',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

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

\u{1F433} Docker Resources

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

\u{1F4E6} Import Docker Compose

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

Terminal

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

\u{1F4DC} Audit Log

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

- `);const h=document.getElementById("security-modal"),S=document.getElementById("security-center-btn"),A=document.getElementById("sec-cancel"),k=h.querySelectorAll(".sec-tab"),N=h.querySelectorAll(".sec-panel");let R=[],z=[],P=null;k.forEach(s=>{s.addEventListener("click",()=>{k.forEach(l=>l.classList.toggle("active",l===s)),N.forEach(l=>l.style.display=l.dataset.panel===s.dataset.tab?"":"none"),s.dataset.tab==="overview"&&H(),s.dataset.tab==="events"&&O(),s.dataset.tab==="hosts"&&m()})}),S&&S.addEventListener("click",()=>{h.classList.add("show"),H(),T()}),A.addEventListener("click",g),h.addEventListener("click",s=>{s.target===h&&g()});function g(){h.classList.remove("show"),w()}function T(){if(w(),!!document.getElementById("sec-live-tail").checked&&!(typeof EventSource>"u"))try{P=new EventSource("/api/v1/security/events/stream"),P.addEventListener("init",s=>{try{R=JSON.parse(s.data).events||[],x()}catch{}}),P.addEventListener("security",s=>{try{const l=JSON.parse(s.data);R.unshift(l),R.length>500&&(R.length=500);const r=h.querySelector(".sec-tab.active")?.dataset?.tab;r==="events"?x():r==="overview"&&H()}catch{}}),P.onerror=()=>{}}catch(s){console.warn("[security] SSE failed:",s.message)}}function w(){if(P){try{P.close()}catch{}P=null}}document.getElementById("sec-live-tail").addEventListener("change",()=>{h.classList.contains("show")&&T()});async function H(){try{const s=new Date(Date.now()-864e5).toISOString(),[l,r,f]=await Promise.all([fetch(`/api/v1/security/events/stats?since=${encodeURIComponent(s)}`),fetch("/api/v1/security/hosts"),fetch(`/api/v1/security/events?limit=1&since=${encodeURIComponent(s)}`)]),u=(await l.json()).data||{},t=(await r.json()).data?.hosts||[],e=(await f.json()).data?.total||0;document.querySelector('#sec-stats [data-key="total"]').textContent=`${e} events (24h)`,document.querySelector('#sec-stats [data-key="warn"]').textContent=`${u.by_severity?.warn||0} warnings`,document.querySelector('#sec-stats [data-key="error"]').textContent=`${u.by_severity?.error||0} errors`,document.querySelector('#sec-stats [data-key="denied"]').textContent=`${u.by_outcome?.denied||0} denied`,document.querySelector('#sec-stats [data-key="hosts"]').textContent=`${t.length} hosts`,E("sec-top-actors",u.top_actors||[]),E("sec-top-targets",u.top_targets||[])}catch(s){console.warn("[security] refreshOverview failed:",s.message)}}function E(s,l){const r=document.getElementById(s);if(!l.length){r.innerHTML='
No data
';return}r.innerHTML=''+l.map(f=>``).join("")+"
${p(String(f.key))}${f.count}
"}const $=document.getElementById("sec-filter-source"),I=document.getElementById("sec-filter-severity"),L=document.getElementById("sec-filter-host"),j=document.getElementById("sec-filter-actor"),M=document.getElementById("sec-refresh-btn");[$,I,L].forEach(s=>s.addEventListener("change",O)),j.addEventListener("input",v(O,250)),M.addEventListener("click",O);async function O(){try{const s=new URLSearchParams;s.set("limit","200"),$.value&&s.set("source_type",$.value),I.value&&s.set("severity",I.value),L.value&&s.set("source_host",L.value),j.value&&s.set("actor_prefix",j.value),R=(await(await fetch(`/api/v1/security/events?${s}`)).json()).data.events||[],x(),(!L.options.length||L.options.length===1)&&await y()}catch(s){document.getElementById("sec-events-container").innerHTML='
Load failed: '+p(s.message)+"
"}}function x(){const s=document.getElementById("sec-events-container");if(!R.length){s.innerHTML='
No events
';return}s.innerHTML=R.slice(0,200).map(D).join("")}function D(s){const l=s.severity||"info",r={critical:"#c0392b",error:"#e74c3c",warn:"#f39c12",notice:"#3498db",info:"#7f8c8d"}[l]||"#7f8c8d",f=s.ts?new Date(s.ts).toLocaleTimeString():"",u=s.source_type||"",t=s.actor||"\u2014",e=s.target||"",o=s.action||"",a=s.outcome||"";return`
- ${p(l)} - ${p(u)} +
`);const h=document.getElementById("security-modal"),S=document.getElementById("security-center-btn"),O=document.getElementById("sec-cancel"),E=h.querySelectorAll(".sec-tab"),N=h.querySelectorAll(".sec-panel");let R=[],z=[],P=null;E.forEach(s=>{s.addEventListener("click",()=>{E.forEach(d=>d.classList.toggle("active",d===s)),N.forEach(d=>d.style.display=d.dataset.panel===s.dataset.tab?"":"none"),s.dataset.tab==="overview"&&T(),s.dataset.tab==="events"&&D(),s.dataset.tab==="hosts"&&m()})}),S&&S.addEventListener("click",()=>{h.classList.add("show"),T(),L()}),O.addEventListener("click",g),h.addEventListener("click",s=>{s.target===h&&g()});function g(){h.classList.remove("show"),w()}function L(){if(w(),!!document.getElementById("sec-live-tail").checked&&!(typeof EventSource>"u"))try{P=new EventSource("/api/v1/security/events/stream"),P.addEventListener("init",s=>{try{R=JSON.parse(s.data).events||[],x()}catch{}}),P.addEventListener("security",s=>{try{const d=JSON.parse(s.data);R.unshift(d),R.length>500&&(R.length=500);const r=h.querySelector(".sec-tab.active")?.dataset?.tab;r==="events"?x():r==="overview"&&T()}catch{}}),P.onerror=()=>{}}catch(s){console.warn("[security] SSE failed:",s.message)}}function w(){if(P){try{P.close()}catch{}P=null}}document.getElementById("sec-live-tail").addEventListener("change",()=>{h.classList.contains("show")&&L()});async function T(){try{const s=new Date(Date.now()-864e5).toISOString(),[d,r,f]=await Promise.all([fetch(`/api/v1/security/events/stats?since=${encodeURIComponent(s)}`),fetch("/api/v1/security/hosts"),fetch(`/api/v1/security/events?limit=1&since=${encodeURIComponent(s)}`)]),v=(await d.json()).data||{},t=(await r.json()).data?.hosts||[],e=(await f.json()).data?.total||0;document.querySelector('#sec-stats [data-key="total"]').textContent=`${e} events (24h)`,document.querySelector('#sec-stats [data-key="warn"]').textContent=`${v.by_severity?.warn||0} warnings`,document.querySelector('#sec-stats [data-key="error"]').textContent=`${v.by_severity?.error||0} errors`,document.querySelector('#sec-stats [data-key="denied"]').textContent=`${v.by_outcome?.denied||0} denied`,document.querySelector('#sec-stats [data-key="hosts"]').textContent=`${t.length} hosts`,k("sec-top-actors",v.top_actors||[]),k("sec-top-targets",v.top_targets||[])}catch(s){console.warn("[security] refreshOverview failed:",s.message)}}function k(s,d){const r=document.getElementById(s);if(!d.length){r.innerHTML='
No data
';return}r.innerHTML=''+d.map(f=>``).join("")+"
${p(String(f.key))}${f.count}
"}const B=document.getElementById("sec-filter-source"),I=document.getElementById("sec-filter-severity"),C=document.getElementById("sec-filter-host"),j=document.getElementById("sec-filter-actor"),M=document.getElementById("sec-refresh-btn");[B,I,C].forEach(s=>s.addEventListener("change",D)),j.addEventListener("input",u(D,250)),M.addEventListener("click",D);async function D(){try{const s=new URLSearchParams;s.set("limit","200"),B.value&&s.set("source_type",B.value),I.value&&s.set("severity",I.value),C.value&&s.set("source_host",C.value),j.value&&s.set("actor_prefix",j.value),R=(await(await fetch(`/api/v1/security/events?${s}`)).json()).data.events||[],x(),(!C.options.length||C.options.length===1)&&await y()}catch(s){document.getElementById("sec-events-container").innerHTML='
Load failed: '+p(s.message)+"
"}}function x(){const s=document.getElementById("sec-events-container");if(!R.length){s.innerHTML='
No events
';return}s.innerHTML=R.slice(0,200).map(A).join("")}function A(s){const d=s.severity||"info",r={critical:"#c0392b",error:"#e74c3c",warn:"#f39c12",notice:"#3498db",info:"#7f8c8d"}[d]||"#7f8c8d",f=s.ts?new Date(s.ts).toLocaleTimeString():"",v=s.source_type||"",t=s.actor||"\u2014",e=s.target||"",n=s.action||"",a=s.outcome||"";return`
+ ${p(d)} + ${p(v)} ${p(t)} - ${p(o)} ${p(e)} + ${p(n)} ${p(e)} ${p(a)} ${p(f)} -
`}async function y(){try{const l=(await(await fetch("/api/v1/security/hosts")).json()).data?.hosts||[],r=L.value;L.innerHTML=''+l.map(f=>``).join(""),r&&(L.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 l=(await(await fetch("/api/v1/security/hosts")).json()).data?.hosts||[];z=l;const r=document.getElementById("sec-hosts-container");if(!l.length){r.innerHTML='
No hosts registered. Click \u2795 Register Host to add one.
';return}r.innerHTML=l.map(f=>{const u=f.enabled?f.last_seen_at?Date.now()-Date.parse(f.last_seen_at)>18e5?"\u{1F7E1} stale":"\u{1F7E2} online":"\u26AA registered":"\u{1F534} disabled";return`
+
`}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.
';return}r.innerHTML=d.map(f=>{const v=f.enabled?f.last_seen_at?Date.now()-Date.parse(f.last_seen_at)>18e5?"\u{1F7E1} stale":"\u{1F7E2} online":"\u26AA registered":"\u{1F534} disabled";return`
${p(f.label||f.id)} ${p(f.type)} @@ -1751,21 +1751,21 @@ Enter version to rollback to:`);if(!o)return;if(!e.includes(o)){showNotification
- ${u} + ${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 l=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:l,type:r})}),u=await f.json();if(!f.ok){alert("Failed: "+(u?.error?.message||f.statusText));return}alert(`\u2705 Host registered! + `}).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: ${u.data.host.id} -label: ${u.data.host.label} -type: ${u.data.host.type} +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): -${u.data.api_key} +${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,l=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[l])}function v(s,l){let r;return function(){clearTimeout(r),r=setTimeout(()=>s.apply(this,arguments),l)}}})(),(function(){const h=new ErrorHandler;injectModal("weather-modal",`

Weather Settings

+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”
@@ -1776,23 +1776,23 @@ To endpoint: POST /api/v1/security/events/ingest or /events/batch`),m()}catch(f)
-
`);const S="weather-location",A="weather-zip",k="weather-geo",N="weather-unit";!safeGet(S)&&safeGet(A)&&safeSet(S,safeGet(A));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"},T=["N","NNE","NE","ENE","E","ESE","SE","SSE","S","SSW","SW","WSW","W","WNW","NW","NNW"];function w(M){return T[Math.round(M/22.5)%16]}async function H(M){const O=safeGet(k);if(O)try{const b=JSON.parse(O);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 D=await x.json();if(!D.results||!D.results.length)throw new Error("Location not found");const y=D.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(k,JSON.stringify(m)),m}function E(M){return M.countryCode==="US"&&M.state?`${M.city}, ${M.state}`:M.country?`${M.city}, ${M.country}`:M.city}async function $(M){try{const O=await H(M),x=R(),D=x==="metric"?"celsius":"fahrenheit",y=x==="metric"?"kmh":"mph",m=`https://api.open-meteo.com/v1/forecast?latitude=${O.lat}&longitude=${O.lon}¤t=temperature_2m,weather_code,wind_speed_10m,wind_direction_10m&temperature_unit=${D}&wind_speed_unit=${y}`,b=await fetch(m);if(!b.ok)throw new Error("Weather fetch failed");const v=(await b.json()).current,s=v.weather_code;return{temp:Math.round(v.temperature_2m),condition:P[s]||"Unknown",icon:g[s]||"\u{1F324}\uFE0F",locationStr:E(O),windSpeed:Math.round(v.wind_speed_10m),windDir:w(v.wind_direction_10m),unit:x}}catch(O){return console.warn("Weather fetch failed:",O),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 O=safeGet(S);if(!O){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 $(O);if(x){const D=x.unit==="metric"?"\xB0C":"\xB0F",y=x.unit==="metric"?"km/h":"mph";M.location.textContent=x.locationStr,M.temp.textContent=`${x.temp}${D}`,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 L=document.getElementById("weather-modal"),j=document.getElementById("weather-location-input");document.getElementById("weather-settings")?.addEventListener("click",()=>{j.value=safeGet(S)||"";const M=R(),O=L.querySelector(`input[name="weather-unit-radio"][value="${M}"]`);O&&(O.checked=!0),L.classList.add("show"),j.focus()}),document.getElementById("weather-cancel")?.addEventListener("click",()=>{L.classList.remove("show")}),document.getElementById("weather-save")?.addEventListener("click",()=>{const M=j.value.trim();if(M){safeGet(S)!==M&&safeSet(k,""),safeSet(S,M);const x=L.querySelector('input[name="weather-unit-radio"]:checked'),D=x?x.value:"imperial",y=R();safeSet(N,D),y!==D&&safeSet(k,""),L.classList.remove("show"),I()}else showNotification("Please enter a location (e.g., Hamburg, London, 90210)","warning")}),wireModal(L),document.addEventListener("keydown",M=>{M.key==="Escape"&&L.classList.contains("show")&&L.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 A=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],k=["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="",T="",w=null,H=null;function E(t){if(P||safeGet("clock-chimes")!=="true")return;P=!0;const e=parseInt(safeGet("clock-chime-volume")||"50",10)/100;let o=0;function a(){if(o>=t){P=!1;return}const d=new Audio("/assets/sounds/church-bell.mp3");d.volume=e,d.play().catch(()=>{}),o++,o{P=!1},2500)}a()}function $(t){return A[t.getDay()]+", "+k[t.getMonth()]+" "+t.getDate()+", "+t.getFullYear()}function I(){T="",w=null}function L(){return T!=="digital"&&(S.innerHTML='
',w={main:S.querySelector(".clock-main"),seconds:S.querySelector(".clock-seconds"),ampm:S.querySelector(".clock-ampm"),date:S.querySelector(".clock-date")},T="digital"),w}function j(t){const e=t.getHours(),o=t.getMinutes(),a=t.getSeconds(),d=e>=12?"PM":"AM",n=e%12||12,i=L();i.main.textContent=`${n}:${String(o).padStart(2,"0")}`,i.seconds.textContent=`:${String(a).padStart(2,"0")}`,i.ampm.textContent=d,i.date.textContent=$(t)}function M(t,e){const o=t.getHours(),a=t.getMinutes(),d=t.getSeconds(),n=o>=12?"PM":"AM",i=o%12||12,c=L();c.main.textContent=`${String(i).padStart(2,"0")}:${String(a).padStart(2,"0")}`,c.seconds.textContent=`:${String(d).padStart(2,"0")}`,c.ampm.textContent=n,c.date.textContent=$(t)}function O(t){const e=t.getHours(),o=t.getMinutes(),a=t.getSeconds(),d=e>=12?"PM":"AM",n=e%12||12,i=String(n).padStart(2," ")+String(o).padStart(2,"0")+String(a).padStart(2,"0");let c='
';if(c+=x(i[0],0),c+=x(i[1],1),c+=':',c+=x(i[2],2),c+=x(i[3],3),c+=':',c+=x(i[4],4),c+=x(i[5],5),c+=`${d}`,c+="
",c+=`
${$(t)}
`,S.innerHTML=c,T="flip",g){for(let C=0;C<6;C++)if(i[C]!==g[C]){const B=S.querySelector(`.flip-card[data-idx="${C}"]`);B&&B.classList.add("flipping")}}g=i}function x(t,e){const o=t===" "?"":t;return`
${o}
${o}
`}function D(t){const e=t.getHours(),o=t.getMinutes(),a=t.getSeconds(),d=e%12||12,n=e>=12?"PM":"AM",i=[Math.floor(d/10),d%10,Math.floor(o/10),o%10,Math.floor(a/10),a%10];let c='
';c+='
HHMMSS
';for(let C=3;C>=0;C--){c+='
';for(let B=0;B<6;B++){const F=i[B]>>C&1;c+=`
`}c+="
"}c+='
';for(let C=0;C<6;C++)c+=`${i[C]}`;c+="
",c+=`
${n}
`,c+="
",c+=`
${$(t)}
`,S.innerHTML=c,T="binary"}function y(t,e){const o=t.getHours(),a=t.getMinutes(),d=t.getSeconds(),n=120,i=n/2,c=n/2,C=d/60*360-90,B=(a+d/60)/60*360-90,F=(o%12+a/60)/12*360-90;let q="";for(let X=1;X<=12;X++){const Q=X/12*2*Math.PI-Math.PI/2,ne=47,oe=i+ne*Math.cos(Q),se=c+ne*Math.sin(Q),Y=e?N[X%12]:X;q+=`${Y}`}let U="";for(let X=0;X<60;X++){const Q=X/60*2*Math.PI-Math.PI/2,ne=56,oe=X%5===0?52:54,se=i+oe*Math.cos(Q),Y=c+oe*Math.sin(Q),ie=i+ne*Math.cos(Q),re=c+ne*Math.sin(Q),ae=X%5===0?1.5:.5;U+=``}const G=` +
`);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='
',w={main:S.querySelector(".clock-main"),seconds:S.querySelector(".clock-seconds"),ampm:S.querySelector(".clock-ampm"),date:S.querySelector(".clock-date")},L="digital"),w}function j(t){const e=t.getHours(),n=t.getMinutes(),a=t.getSeconds(),l=e>=12?"PM":"AM",o=e%12||12,i=C();i.main.textContent=`${o}:${String(n).padStart(2,"0")}`,i.seconds.textContent=`:${String(a).padStart(2,"0")}`,i.ampm.textContent=l,i.date.textContent=B(t)}function M(t,e){const n=t.getHours(),a=t.getMinutes(),l=t.getSeconds(),o=n>=12?"PM":"AM",i=n%12||12,c=C();c.main.textContent=`${String(i).padStart(2,"0")}:${String(a).padStart(2,"0")}`,c.seconds.textContent=`:${String(l).padStart(2,"0")}`,c.ampm.textContent=o,c.date.textContent=B(t)}function D(t){const e=t.getHours(),n=t.getMinutes(),a=t.getSeconds(),l=e>=12?"PM":"AM",o=e%12||12,i=String(o).padStart(2," ")+String(n).padStart(2,"0")+String(a).padStart(2,"0");let c='
';if(c+=x(i[0],0),c+=x(i[1],1),c+=':',c+=x(i[2],2),c+=x(i[3],3),c+=':',c+=x(i[4],4),c+=x(i[5],5),c+=`${l}`,c+="
",c+=`
${B(t)}
`,S.innerHTML=c,L="flip",g){for(let $=0;$<6;$++)if(i[$]!==g[$]){const H=S.querySelector(`.flip-card[data-idx="${$}"]`);H&&H.classList.add("flipping")}}g=i}function x(t,e){const n=t===" "?"":t;return`
${n}
${n}
`}function A(t){const e=t.getHours(),n=t.getMinutes(),a=t.getSeconds(),l=e%12||12,o=e>=12?"PM":"AM",i=[Math.floor(l/10),l%10,Math.floor(n/10),n%10,Math.floor(a/10),a%10];let c='
';c+='
HHMMSS
';for(let $=3;$>=0;$--){c+='
';for(let H=0;H<6;H++){const U=i[H]>>$&1;c+=`
`}c+="
"}c+='
';for(let $=0;$<6;$++)c+=`${i[$]}`;c+="
",c+=`
${o}
`,c+="
",c+=`
${B(t)}
`,S.innerHTML=c,L="binary"}function y(t,e){const n=t.getHours(),a=t.getMinutes(),l=t.getSeconds(),o=120,i=o/2,c=o/2,$=l/60*360-90,H=(a+l/60)/60*360-90,U=(n%12+a/60)/12*360-90;let q="";for(let X=1;X<=12;X++){const Q=X/12*2*Math.PI-Math.PI/2,ne=47,oe=i+ne*Math.cos(Q),se=c+ne*Math.sin(Q),Y=e?N[X%12]:X;q+=`${Y}`}let F="";for(let X=0;X<60;X++){const Q=X/60*2*Math.PI-Math.PI/2,ne=56,oe=X%5===0?52:54,se=i+oe*Math.cos(Q),Y=c+oe*Math.sin(Q),ie=i+ne*Math.cos(Q),re=c+ne*Math.sin(Q),ae=X%5===0?1.5:.5;F+=``}const G=` - ${U} + ${F} ${q} - - - + + + - `,J=t.getHours()>=12?"PM":"AM";S.innerHTML=`
${G}
${t.getHours()%12||12}:${String(a).padStart(2,"0")} ${J}${$(t)}
`,T="analog"}function m(){const t=new Date,e=t.getHours()%12||12,o=t.getMinutes(),a=t.getSeconds(),d="clock-widget"+(R!=="default"?" "+R:"");switch(h.className!==d&&(h.className=d),R){case"lcd":M(t);break;case"lcd-blue":M(t);break;case"lcd-amber":M(t);break;case"lcd-retro":M(t);break;case"lcd-taxi":M(t);break;case"flip":O(t);break;case"binary":D(t);break;case"analog":y(t,!1);break;case"roman":y(t,!0);break;default:j(t)}o===0&&a===0&&e!==z&&(z=e,E(e)),o!==0&&(z=-1)}function b(){clearTimeout(H);const t=document.hidden?6e4:1e3,e=t-Date.now()%t+25;H=setTimeout(()=>{m(),b()},e)}document.addEventListener("visibilitychange",()=>{g="",I(),m(),b()}),m(),b();const p=[{id:"default",label:"Default",icon:"\u{1F550}"},{id:"lcd",label:"LCD Green",icon:"\u{1F49A}"},{id:"lcd-blue",label:"LCD Blue",icon:"\u{1F499}"},{id:"lcd-amber",label:"LCD Amber",icon:"\u{1F7E0}"},{id:"lcd-retro",label:"LCD Retro",icon:"\u{1F7E9}"},{id:"lcd-taxi",label:"LCD Taxi",icon:"\u{1F7E1}"},{id:"flip",label:"Flip Clock",icon:"\u{1F4DF}"},{id:"binary",label:"Binary",icon:"\u{1F4BB}"},{id:"analog",label:"Analog",icon:"\u23F0"},{id:"roman",label:"Roman",icon:"\u{1F3DB}\uFE0F"}];let v='
';p.forEach(t=>{v+=`