(function(o){"use strict";class f{constructor(){this.errors=[],this.maxErrors=50}logError(y,l,r={}){const h={timestamp:new Date().toISOString(),context:y,message:l instanceof Error?l.message:l,stack:l instanceof Error?l.stack:null,metadata:r};this.errors.push(h),this.errors.length>this.maxErrors&&this.errors.shift(),console.error(`[Onboarding Error] ${y}:`,l,r)}recoverFromError(y,l){switch(this.classifyError(y)){case"ELEMENT_NOT_FOUND":return this.logError("Element Not Found",y,{currentStep:l}),{action:"SKIP_STEP",nextStep:l+1,message:"Target element not found, skipping to next step"};case"STORAGE_UNAVAILABLE":return this.logError("Storage Unavailable",y),{action:"USE_MEMORY_STORAGE",message:"Local storage unavailable, using in-memory storage"};case"DRIVER_NOT_LOADED":return this.logError("Driver.js Not Loaded",y),{action:"ABORT_TOUR",message:"Driver.js library not loaded, cannot start tour"};case"INVALID_TOOLTIP":return this.logError("Invalid Tooltip Configuration",y,{currentStep:l}),{action:"SKIP_STEP",nextStep:l+1,message:"Invalid tooltip configuration, skipping"};case"THEME_DETECTION_FAILED":return this.logError("Theme Detection Failed",y),{action:"USE_DEFAULT_THEME",message:"Using default dark theme"};default:return this.logError("Unknown Error",y,{currentStep:l}),{action:"ABORT_TOUR",message:"Unexpected error occurred, aborting tour"}}}classifyError(y){const l=y.message||y.toString();return l.includes("element")&&l.includes("not found")?"ELEMENT_NOT_FOUND":l.includes("storage")||l.includes("quota")?"STORAGE_UNAVAILABLE":l.includes("driver")||l.includes("undefined")?"DRIVER_NOT_LOADED":l.includes("invalid")||l.includes("validation")?"INVALID_TOOLTIP":l.includes("theme")?"THEME_DETECTION_FAILED":"UNKNOWN"}getErrors(){return[...this.errors]}clearErrors(){this.errors=[]}getStatistics(){const y={total:this.errors.length,byContext:{},byType:{},recent:this.errors.slice(-10)};return this.errors.forEach(l=>{y.byContext[l.context]=(y.byContext[l.context]||0)+1;const r=this.classifyError({message:l.message});y.byType[r]=(y.byType[r]||0)+1}),y}handleDriverLoadFailure(){this.logError("Driver.js Load Failure","Driver.js library failed to load");const y=document.createElement("div");return y.id="onboarding-fallback",y.style.cssText=` position: fixed; bottom: 20px; right: 20px; background: var(--card-base, #2a2a2a); color: var(--fg, #ffffff); padding: 15px 20px; border-radius: 8px; box-shadow: 0 4px 12px rgba(0,0,0,0.3); z-index: 9999; max-width: 300px; font-size: 14px; `,y.innerHTML=` Welcome to DashCaddy!

The interactive tour is unavailable, but you can explore the dashboard freely. Check the documentation for help getting started.

`,document.body.appendChild(y),setTimeout(()=>{y.parentNode&&y.parentNode.removeChild(y)},1e4),!0}handleStorageUnavailable(){this.logError("Storage Unavailable","Local storage is not available");const y={data:{},getItem(l){return this.data[l]||null},setItem(l,r){this.data[l]=r},removeItem(l){delete this.data[l]},clear(){this.data={}}};return console.warn("[ErrorHandler] Using in-memory storage - progress will not persist"),y}sendToErrorTracking(y){}}o.ErrorHandler=f,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 y=await fetch("/api/v1/config");if(y.ok){const l=await y.json();if(l.tld&&(SITE.tld=l.tld.startsWith(".")?l.tld:"."+l.tld),l.dns&&(SITE.dnsIp=l.dns.ip||"",SITE.dnsPort=l.dns.port||DC.DEFAULTS.DNS_PORT),l.dnsServers&&typeof l.dnsServers=="object")for(const[h,a]of Object.entries(l.dnsServers))h!=="__proto__"&&h!=="constructor"&&h!=="prototype"&&(SITE.dnsServers[h]=a);l.configurationType&&(SITE.configurationType=l.configurationType),l.domain&&(SITE.domain=l.domain),l.defaults&&(SITE.defaults=l.defaults),l.routingMode&&(SITE.routingMode=l.routingMode),SITE.onboardingCompleted=l.onboardingCompleted===!0,localStorage.setItem("dashcaddy_site_config",JSON.stringify({tld:SITE.tld,configurationType:SITE.configurationType,domain:SITE.domain,routingMode:SITE.routingMode})),renderDnsCards();const r=document.getElementById("manage-tokens");r&&(r.style.display=Object.keys(SITE.dnsServers).length?"":"none")}}catch{}document.querySelectorAll("[data-tld]").forEach(y=>y.textContent=SITE.tld);const f=document.getElementById("edit-tld-suffix");f&&(f.textContent=SITE.tld);const u=document.getElementById("external-proxy-ip");u&&SITE.dnsIp&&(u.value=SITE.dnsIp,u.placeholder=SITE.dnsIp)})();function buildDomain(o){return o+SITE.tld}function buildServiceUrl(o){return SITE.routingMode==="subdirectory"&&SITE.domain?"https://"+SITE.domain+"/"+o:SITE.configurationType==="public"&&SITE.domain?"https://"+o+"."+SITE.domain:"https://"+buildDomain(o)}function getDnsServerAddr(o){const f=SITE.dnsServers[o];return f?`${f.ip}:${f.port}`:buildDomain(o)}function getPrimaryDnsId(){if(!SITE.dnsIp)return null;for(const[o,f]of Object.entries(SITE.dnsServers))if(f.ip===SITE.dnsIp)return o;return null}function renderDnsCards(){const o=document.querySelector(".top");if(!o)return;const f=Object.keys(SITE.dnsServers);if(!f.length)return;const u='',y=o.firstElementChild;f.forEach(l=>{const r=escapeHtml(l),h=escapeHtml((SITE.dnsServers[l].name||l).toUpperCase()),a=document.createElement("div");a.className="card",a.setAttribute("data-app",l),a.setAttribute("data-status","off"),a.innerHTML=`
${u}
${h}OFF
--
--
`,o.insertBefore(a,y)})}window.renderDnsCards=renderDnsCards;let csrfToken=null;async function getCSRFToken(){if(csrfToken)return csrfToken;try{const o=await fetch("/api/v1/csrf-token");if(!o.ok)throw new Error("Failed to fetch CSRF token");return csrfToken=(await o.json()).token,csrfToken}catch(o){throw errorHandler.logError("[CSRF] Get Token",o,{function:"getCSRFToken"}),o}}async function secureFetch(o,f={}){const u=(f.method||"GET").toUpperCase(),y=!["GET","HEAD","OPTIONS"].includes(u);if(y)try{const r=await getCSRFToken();f.headers={...f.headers,"X-CSRF-Token":r}}catch(r){errorHandler.logError("[CSRF] Add to Request",r,{function:"secureFetch"})}f.signal||(f={...f,signal:AbortSignal.timeout(15e3)});const l=await fetch(o,f);if(y&&l.status===403)try{const r=await l.clone().json();if(r.error&&(r.error.includes("DC-100")||r.error.includes("DC-101"))){csrfToken=null;const h=await getCSRFToken();return f.headers={...f.headers,"X-CSRF-Token":h},f.signal=AbortSignal.timeout(15e3),fetch(o,f)}}catch{}return l}async function postJSON(o,f){const u=await secureFetch(o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(f)}),y=await u.json();if(!u.ok||y.success===!1)throw new Error(y.error||`Request failed (${u.status})`);return y}async function getJSON(o){const f=await secureFetch(o);if(!f.ok){let u=`Request failed (${f.status})`;try{u=(await f.json()).error||u}catch{}throw new Error(u)}return f.json()}async function deleteAPI(o){const f=await secureFetch(o,{method:"DELETE"}),u=await f.json();if(!f.ok||u.success===!1)throw new Error(u.error||`Delete failed (${f.status})`);return u}async function withButton(o,f,u,y={}){const l=o.innerHTML,{successText:r="\u2705",resetDelay:h=DC.DELAYS.BTN_RESET}=y;o.disabled=!0,o.innerHTML=f;try{const a=await u();return o.innerHTML=r,setTimeout(()=>{o.innerHTML=l,o.disabled=!1},h),a}catch(a){throw o.innerHTML=l,o.disabled=!1,a}}function openModal(o){document.getElementById(o)?.classList.add("show")}function closeModal(o){document.getElementById(o)?.classList.remove("show")}function wireModal(o,...f){o&&(o.addEventListener("click",u=>{u.target===o&&o.classList.remove("show")}),f.forEach(u=>{u&&typeof u.addEventListener=="function"&&u.addEventListener("click",()=>o.classList.remove("show"))}))}function showNotification(o,f="info",u=3e3){const y=document.querySelector(".deploy-notification");y&&y.remove();const l={info:{bg:"#2196F3",fg:"#fff"},success:{bg:"var(--ok-bg)",fg:"var(--ok-fg)"},error:{bg:"#f44336",fg:"#fff"},warning:{bg:"#ff9800",fg:"#fff"}},r=l[f]||l.info,h=document.createElement("div");h.className="deploy-notification",h.textContent=o,h.style.cssText=` position: fixed; top: 20px; right: 20px; background: ${r.bg}; color: ${r.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(h),u>0&&setTimeout(()=>h.remove(),u)}function timeAgo(o){const f=Date.now()-new Date(o).getTime();return f<6e4?"just now":f<36e5?Math.floor(f/6e4)+"m ago":f<864e5?Math.floor(f/36e5)+"h ago":Math.floor(f/864e5)+"d ago"}function safeGet(o,f=null){try{const u=localStorage.getItem(o);return u!==null?u:f}catch{return f}}function safeSet(o,f){try{localStorage.setItem(o,f)}catch{}}function safeRemove(o){try{localStorage.removeItem(o)}catch{}}function safeSessionGet(o,f=null){try{const u=sessionStorage.getItem(o);return u!==null?u:f}catch{return f}}function safeSessionSet(o,f){try{sessionStorage.setItem(o,f)}catch{}}function safeGetJSON(o,f=null){try{const u=localStorage.getItem(o);return u?JSON.parse(u):f}catch{return f}}function escapeHtml(o){return String(o??"").replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'")}function injectModal(o,f){document.getElementById(o)||document.body.insertAdjacentHTML("beforeend",f)}const DC_BUS={_handlers:{},on(o,f){var u;((u=this._handlers)[o]||(u[o]=[])).push(f)},off(o,f){this._handlers[o]=this._handlers[o]?.filter(u=>u!==f)},emit(o,f){this._handlers[o]?.forEach(u=>u(f))}},AppState={_apps:[],getApps(){return this._apps},setApps(o){this._apps=o,window.APPS=o,DC_BUS.emit("apps:changed",o)},findApp(o){return this._apps.find(f=>f.id===o)},addApp(o){this._apps.push(o),window.APPS=this._apps,DC_BUS.emit("apps:changed",this._apps)},removeApp(o){const f=this._apps.findIndex(u=>u.id===o);return f>-1&&(this._apps.splice(f,1),window.APPS=this._apps,DC_BUS.emit("apps:changed",this._apps)),f>-1},updateApp(o,f){const u=this._apps.find(y=>y.id===o);if(u){for(const[y,l]of Object.entries(f))y!=="__proto__"&&y!=="constructor"&&y!=="prototype"&&(u[y]=l);DC_BUS.emit("apps:changed",this._apps)}return u}};(function(){function o(){const y=document.createElement("div");return y.className="skeleton-card",y.innerHTML='
',y}function f(y){const l=document.getElementById("cards");if(!(!l||l.querySelector(".card"))){y=y||6;for(let r=0;r.4,A={};return A.hover=I?d(w,B,.35):d(w,$,.08),A["card-hover"]=d(w,A.hover,.5),A.base=d(B,w,.6),A["fg-muted"]=d(x,B,.35),A.success=C,A.error=k,A.warning=I?"#d68a00":"#f39c12",A}function s(S,B){var $=B.lightBg||B.bg&&g(B.bg)>.4,x=B.accent||B["accent-strong"]||"#888888",w=m(x);return $?":root."+S+` body { background: radial-gradient(1200px 800px at 10% -10%, rgba(`+w.r+","+w.g+","+w.b+`, .08), transparent 60%), radial-gradient(1000px 700px at 110% 10%, rgba(`+w.r+","+w.g+","+w.b+`, .05), transparent 55%), var(--bg); } `:":root."+S+` body { background: radial-gradient(1200px 900px at 8% -12%, rgba(`+w.r+","+w.g+","+w.b+`, .10), transparent 60%), radial-gradient(1000px 700px at 110% -10%, rgba(`+w.r+","+w.g+","+w.b+`, .07), transparent 55%), var(--bg); } `}function p(S,B){var $=B.lightBg||B.bg&&g(B.bg)>.4;return $?":root."+S+` 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."+S+` 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 c(){r.forEach(function(S){document.documentElement.style.removeProperty("--"+S)})}function v(S,B){var $=S.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"");$||($="custom"),y.indexOf($)!==-1&&($=$+"-custom");for(var x=safeGetJSON(f,{}),w=$,C=2;x[$]&&$!==B;)$=w+"-"+C++;return $}function i(S){var B=document.getElementById("user-theme-styles");B&&B.remove(),l.length=y.length,Object.keys(b).forEach(function(k){y.indexOf(k)===-1&&delete b[k]});var $=S||safeGetJSON(f,{}),x=Object.keys($);if(x=x.filter(function(k){return y.indexOf(k)===-1}),!!x.length){var w="";x.forEach(function(k){var I=$[k];l.indexOf(k)===-1&&l.push(k);var A={};r.forEach(function(D){I[D]&&(A[D]=I[D])}),A["card-bg"]=I["card-base"]||I.bg,I.lightBg&&(A.lightBg=!0);var O=e(A);a.forEach(function(D){!A[D]&&O[D]&&(A[D]=O[D])}),b[k]=A,w+=":root."+k+` { `,r.forEach(function(D){A[D]&&(w+=" --"+D+": "+A[D]+`; `)}),w+=`} `,w+=s(k,A),w+=p(k,A)});var C=document.createElement("style");C.id="user-theme-styles",C.textContent=w,document.head.appendChild(C)}}function E(){secureFetch("/api/v1/themes").then(function(S){return S.json()}).then(function(S){if(!(!S.success||!S.themes)){var B=S.themes,$=safeGetJSON(f,{});if(JSON.stringify(B)!==JSON.stringify($)){safeSet(f,JSON.stringify(B)),i(B);var x=safeGet(o);x&&l.indexOf(x)!==-1&&L(x)}}}).catch(function(){})}function T(){var S=safeGetJSON(u);if(S){var B=S.name||"Custom",$=v(B),x={name:B};r.forEach(function(k){S[k]&&(x[k]=S[k])});var w=safeGetJSON(f,{});w[$]=x,safeSet(f,JSON.stringify(w)),safeGet(o)==="custom"&&safeSet(o,$),safeRemove(u);var C={};r.forEach(function(k){x[k]&&(C[k]=x[k])}),fetch("/api/v1/themes/"+$,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:B,colors:C})}).catch(function(){})}}function L(S){document.documentElement.classList.add("theme-transitioning"),l.forEach(function(w){w!=="dark"&&document.documentElement.classList.remove(w)}),c(),S!=="dark"&&document.documentElement.classList.add(S),safeSet(o,S);var B=b[S],$=document.querySelector('meta[name="theme-color"]');$&&B&&$.setAttribute("content",B.bg);var x=B&&B.lightBg;!x&&B&&B.bg&&(x=g(B.bg)>.4),x?document.documentElement.classList.add("light-bg"):document.documentElement.classList.remove("light-bg"),setTimeout(function(){document.documentElement.classList.remove("theme-transitioning")},300)}T(),i();var P=safeGet(o);P==="red"&&(P="black",safeSet(o,"black")),P&&P!=="dark"&&l.indexOf(P)===-1&&(P=null),L(P||t()),E(),window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change",function(S){safeGet(o)||L(S.matches?"dark":"light")}),window.THEMES=l,window.BUILTIN_THEMES=y,window.THEME_COLORS=b,window.THEME_PROPS=r,window.BASE_PROPS=h,window.DERIVED_PROPS=a,window.USER_THEMES_KEY=f,window.applyTheme=L,window.clearCustomProperties=c,window.injectUserThemeStyles=i,window.syncThemesFromServer=E,window.slugifyThemeName=v,window.getActiveTheme=function(){return safeGet(o)||t()},window.deriveExtendedColors=e,window.hexToRgb=m,window.rgbToHex=n,window.blendColors=d})(),(function(){function o(){const h=document.querySelector(".totp-card");if(!h)return;const b=getComputedStyle(h).backgroundColor.match(/\d+/g);if(!b)return;const m=(.299*+b[0]+.587*+b[1]+.114*+b[2])/255,n=h.querySelector(".totp-logo-dark"),d=h.querySelector(".totp-logo-light");n&&(n.style.display=m>.5?"none":""),d&&(d.style.display=m>.5?"":"none")}function f(){const h=document.getElementById("totp-overlay");if(h){h.classList.add("show"),setTimeout(o,50);const a=h.querySelector(".totp-digits input");a&&setTimeout(()=>a.focus(),100)}}function u(){const h=document.getElementById("totp-overlay");h&&h.classList.remove("show")}const y=document.getElementById("totp-digits");if(y){const h=y.querySelectorAll("input");h.forEach((a,b)=>{a.addEventListener("input",m=>{const n=m.target.value.replace(/\D/g,"");m.target.value=n.slice(0,1),n&&bg.value).join("");d.length===6&&l(d)}),a.addEventListener("keydown",m=>{m.key==="Backspace"&&!m.target.value&&b>0&&(h[b-1].focus(),h[b-1].value="")}),a.addEventListener("paste",m=>{m.preventDefault();const n=(m.clipboardData.getData("text")||"").replace(/\D/g,"");n.length>=6&&(h.forEach((d,g)=>{d.value=n[g]||""}),h[5].focus(),l(n.slice(0,6)))})})}async function l(h){const a=document.getElementById("totp-error");a.textContent="Verifying...",a.className="totp-error verifying";try{const m=await(await secureFetch("/api/v1/totp/verify",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:h})})).json();if(m.success){a.textContent="",m.csrfToken&&(csrfToken=m.csrfToken),u();const n=safeSessionGet("totp_redirect");if(n){try{sessionStorage.removeItem("totp_redirect")}catch{}window.location.href=n;return}typeof window.initializeDashboard=="function"&&window.initializeDashboard()}else{a.textContent=m.error||"Invalid code",a.className="totp-error";const n=document.querySelectorAll("#totp-digits input");n.forEach(d=>{d.value=""}),n[0]?.focus()}}catch{a.textContent="Connection error",a.className="totp-error"}}const r=new URLSearchParams(window.location.search);if(r.get("auth")==="required"){const h=r.get("return");if(h)try{const a=new URL(h,window.location.origin),b=a.hostname,m=a.origin===window.location.origin,n=SITE.tld.startsWith(".")?SITE.tld:"."+SITE.tld,d=b.endsWith(n)||b===n.substring(1);(m||d)&&safeSessionSet("totp_redirect",h)}catch{}window.history.replaceState({},"",window.location.pathname)}window._showTotpOverlay=f})(),(function(){const o=new ErrorHandler;injectModal("folder-browser-modal",`

\u{1F4C2} Browse for Media Folders

/
Loading...
`),injectModal("service-creds-modal",`

Service Credentials

Credentials are injected automatically when accessing this service.

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

Authentication Settings

TOTP is not configured
or
`);async function f(){try{const r=await(await fetch("/api/v1/totp/config")).json();if(!r.success)return;const{enabled:h,sessionDuration:a,isSetUp:b}=r.config,m=document.getElementById("totp-status-dot"),n=document.getElementById("totp-status-text"),d=document.getElementById("totp-status-banner"),g=document.getElementById("totp-setup-section"),e=document.getElementById("totp-qr-section"),s=document.getElementById("totp-duration-section"),p=document.getElementById("totp-disable-section");h&&b?(m.style.background="var(--ok-fg, #7ef2ff)",d.style.borderColor="var(--ok-fg, #7ef2ff)",d.style.background="color-mix(in srgb, var(--ok-fg) 8%, transparent)",n.textContent="TOTP is active",n.style.color="var(--ok-fg, #7ef2ff)",g.style.display="none",e.style.display="none",s.style.display="block",p.style.display="block",document.getElementById("totp-duration-select").value=a):(m.style.background="var(--muted)",d.style.borderColor="var(--border)",d.style.background="transparent",n.textContent="TOTP is not configured",n.style.color="var(--muted)",g.style.display="block",e.style.display="none",s.style.display="none",p.style.display="none"),y(h&&b,a)}catch(l){console.warn("Failed to load TOTP settings:",l)}}const u={"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 y(l,r){const h=document.getElementById("auth-card"),a=document.getElementById("auth-pill"),b=document.getElementById("auth-dot"),m=document.getElementById("auth-status-text");h&&(l?(h.setAttribute("data-status","on"),a.className="badge on",a.textContent="YES",b.className="dot ok at-bl",m.textContent="Session: "+(u[r]||r)):(h.setAttribute("data-status","off"),a.className="badge off",a.textContent="NO",b.className="dot bad at-bl",m.textContent="Not configured"))}document.getElementById("totp-setup-btn")?.addEventListener("click",async()=>{try{const r=await(await secureFetch("/api/v1/totp/setup",{method:"POST"})).json();r.success&&(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())}catch(l){o.logError("[TOTP] Setup Failed",l,{function:"setupTOTP"})}}),document.getElementById("totp-import-btn")?.addEventListener("click",async()=>{const l=document.getElementById("totp-import-key").value.trim(),r=document.getElementById("totp-import-error");if(r.textContent="",!l){r.textContent="Paste a Base32 secret key first";return}try{const a=await(await secureFetch("/api/v1/totp/setup",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({secret:l})})).json();a.success?(r.textContent="",document.getElementById("totp-qr-image").src=a.qrCode,document.getElementById("totp-manual-key").textContent=a.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()):r.textContent=a.error||a.message||"Import failed"}catch{r.textContent="Connection error \u2014 try refreshing the page"}}),document.getElementById("totp-copy-key")?.addEventListener("click",()=>{const l=document.getElementById("totp-manual-key").textContent;navigator.clipboard.writeText(l).then(()=>{const r=document.getElementById("totp-copy-key");r.textContent="\u2705",setTimeout(()=>{r.textContent="\u{1F4CB}"},2e3)})}),document.getElementById("totp-confirm-setup")?.addEventListener("click",async()=>{const l=document.getElementById("totp-setup-code").value,r=document.getElementById("totp-setup-error");if(!/^\d{6}$/.test(l)){r.textContent="Enter a 6-digit code";return}try{const a=await(await secureFetch("/api/v1/totp/verify-setup",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:l})})).json();a.success?(r.textContent="",f()):r.textContent=a.error||"Invalid code"}catch{r.textContent="Connection error"}}),document.getElementById("totp-setup-code")?.addEventListener("keydown",l=>{l.key==="Enter"&&document.getElementById("totp-confirm-setup")?.click()}),document.getElementById("totp-duration-select")?.addEventListener("change",async l=>{try{await secureFetch("/api/v1/totp/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionDuration:l.target.value})}),f()}catch(r){o.logError("[TOTP] Update Session Duration",r,{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&&f()}catch(l){o.logError("[TOTP] Disable Failed",l,{function:"disableTOTP"})}}),document.getElementById("auth-settings-btn")?.addEventListener("click",()=>{f(),openModal("totp-settings-modal")}),document.getElementById("totp-modal-close")?.addEventListener("click",()=>{closeModal("totp-settings-modal")}),document.getElementById("totp-settings-modal")?.addEventListener("click",l=>{l.target.id==="totp-settings-modal"&&closeModal("totp-settings-modal")}),window._updateAuthCard=y,(async()=>{try{const r=await(await fetch("/api/v1/totp/config")).json();if(r.success){const h=r.config.enabled&&r.config.isSetUp;y(h,r.config.sessionDuration)}}catch(l){o.logError("[TOTP] AuthCard Update",l,{function:"authCardUpdate"})}})()})(),(function(){injectModal("token-management-modal",`

\u{1F511} DNS Credentials

Enter Technitium DNS login credentials. Read-only accounts are used for logs; admin accounts for restarts, records, and updates.

`);function o(){return Object.keys(SITE.dnsServers||{})}function f(t){return(SITE.dnsServers||{})[t]?.name||t.toUpperCase()}function u(){const t=document.getElementById("dns-cred-sections");if(!t)return;t.innerHTML="";const c=o();if(c.length===0){t.innerHTML='

No DNS servers configured.

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

${f(v)}

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

DNS Settings

Manage credentials via Tokens in the toolbar
`);let u=null;function y(a){u=a;const b=SITE.dnsServers[a]||{},m=document.getElementById("dns-settings-modal");document.getElementById("dns-settings-title").textContent=`${(b.name||a).toUpperCase()} Settings`,document.getElementById("dns-edit-ip").value=b.ip||"",document.getElementById("dns-edit-port").value=b.port||DC.DEFAULTS.DNS_PORT,document.getElementById("dns-edit-name").value=b.name||"",m.classList.add("show")}async function l(){if(!u)return;const a=document.getElementById("dns-edit-ip").value.trim(),b=document.getElementById("dns-edit-port").value.trim()||DC.DEFAULTS.DNS_PORT,m=document.getElementById("dns-edit-name").value.trim();if(!a){showNotification("Server IP is required","warning");return}const n={dnsServers:{}};n.dnsServers[u]={ip:a,port:String(b)},m&&(n.dnsServers[u].name=m);try{const g=await(await secureFetch("/api/v1/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)})).json();g.success?(SITE.dnsServers[u]=n.dnsServers[u],showNotification(`${u.toUpperCase()} settings saved`,"success"),h(),window.refreshAll()):showNotification(g.error||"Failed to save settings","error")}catch(d){showNotification("Failed to save: "+d.message,"error")}}async function r(){if(u&&confirm(`Remove ${u.toUpperCase()} from dashboard? This won't affect the actual DNS server.`))try{const b=await(await secureFetch("/api/v1/config")).json();b.dnsServers&&delete b.dnsServers[u];const n=await(await secureFetch("/api/v1/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({dnsServers:b.dnsServers||{}})})).json();if(n.success){delete SITE.dnsServers[u];const d=document.querySelector(`.top [data-app="${u}"]`);d&&d.remove(),showNotification(`${u.toUpperCase()} removed from dashboard`,"success"),h()}else showNotification(n.error||"Failed to remove","error")}catch(a){showNotification("Failed to remove: "+a.message,"error")}}function h(){closeModal("dns-settings-modal"),u=null}document.getElementById("dns-settings-cancel")?.addEventListener("click",h),document.getElementById("dns-settings-save")?.addEventListener("click",l),document.getElementById("dns-settings-delete")?.addEventListener("click",r),document.getElementById("dns-settings-modal")?.addEventListener("click",a=>{a.target.id==="dns-settings-modal"&&h()}),document.querySelector(".top")?.addEventListener("click",a=>{const b=a.target.closest('[id$="-settings"]');if(!b)return;const m=b.id.replace("-settings","");SITE.dnsServers[m]&&(a.stopPropagation(),y(m))}),document.getElementById("refresh")?.addEventListener("click",window.refreshAll)})(),(function(){injectModal("logs-modal",`

DNS Logs

Loading logs...
`);let o=null,f=null,u=!1,y=null,l=null,r=!1,h=null,a=null,b=!1,m=null,n=!1;async function d(x,w=25){try{const C=getDnsServerAddr(x),k=await fetch(`/api/v1/dns/logs?server=${C}&limit=${w}`,{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(C){return console.error("DNS logs fetch failed:",C),{error:C.message}}}function g(x){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"}[x]||"var(--fg)"}function e(x){const w=document.createElement("div");if(w.className="log-entry",w.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;",x.parsed===!1)return w.style.gridTemplateColumns="1fr",w.innerHTML=`${escapeHtml(x.raw)}`,w;const C=g(x.rcode),k=x.rcode==="Refused"||x.rcode==="REFUSED";return w.innerHTML=` ${escapeHtml(x.timestamp)} ${escapeHtml(x.client)} ${escapeHtml(x.domain)} ${escapeHtml(x.type)} ${escapeHtml(x.rcode)} `,w}async function s(){if(b){await B();return}if(r){await T();return}if(u||!o)return;const x=parseInt(document.getElementById("log-lines").value),w=document.getElementById("logs-content");try{const C=await d(o,x);if(C.error){w.innerHTML=`
\u26A0\uFE0F Error
${escapeHtml(C.error)}
`;return}w.innerHTML=`
Time Client Domain Type Status
`,C.logs&&C.logs.length>0?C.logs.forEach(k=>{const I=e(k);w.appendChild(I)}):w.innerHTML+=`
No DNS queries logged yet
`}catch(C){w.innerHTML=`
Failed to fetch logs: ${escapeHtml(C.message)}
`}}function p(x){o=x,u=!1,r=!1;const w=document.getElementById("logs-modal"),C=document.getElementById("logs-title"),k=document.getElementById("logs-pause"),I=document.getElementById("logs-stream");C.textContent=`${x.toUpperCase()} DNS Logs`,k.textContent="\u23F8\uFE0F Pause",k.classList.remove("paused"),I&&(I.style.display="none"),w.classList.add("show"),s(),f=setInterval(s,DC.POLL.LOGS)}function t(){document.getElementById("logs-modal").classList.remove("show"),f&&(clearInterval(f),f=null),v(),o=null,r=!1,y=null,l=null,b=!1,h=null,a=null,u=!1}function c(x){m&&v();const w=document.getElementById("logs-stream"),C=document.getElementById("logs-pause"),k=document.getElementById("logs-content");f&&(clearInterval(f),f=null);try{m=new EventSource(`/api/v1/logs/stream/${x}`),n=!0,w.classList.add("active"),w.textContent="\u{1F534} Live",w.title="Streaming - click to stop",C.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}")),m.onmessage=A=>{try{const O=JSON.parse(A.data);if(O.error){console.error("Stream error:",O.error),v();return}const D=document.createElement("div");D.className="log-entry",D.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=(O.stream||"stdout")==="stderr",N=R?"var(--bad-fg)":"var(--fg)",F=`${R?"STDERR":"STDOUT"}`;for(D.innerHTML=`
${F}
${escapeHtml(O.text)}
`,k.appendChild(D),k.scrollTop=k.scrollHeight;k.children.length>500;)k.removeChild(k.firstChild)}catch(O){console.error("Error parsing stream data:",O)}},m.onerror=A=>{console.error("EventSource error:",A),v()}}catch(I){console.error("Failed to start streaming:",I),v()}}function v(){m&&(m.close(),m=null),n=!1;const x=document.getElementById("logs-stream"),w=document.getElementById("logs-pause"),C=document.getElementById("logs-title");x&&(x.classList.remove("active"),x.textContent="\u{1F4E1} Live",x.title="Enable real-time streaming"),w&&(w.style.display=""),C&&(C.textContent=C.textContent.replace(" \u{1F534}","")),r&&y&&!f&&(f=setInterval(T,DC.POLL.LOGS))}async function i(x,w=100){try{const C=`/api/v1/logs/container/${x}?tail=${w}×tamps=true`,k=await fetch(C,{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(C){return console.error("Container logs fetch failed:",C),{error:C.message}}}function E(x){const w=document.createElement("div");w.className="log-entry",w.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 C=x.stream==="stderr"?"var(--bad-fg)":"var(--fg)",k=x.stream==="stderr"?'STDERR':'STDOUT';return w.innerHTML=`
${k}
${escapeHtml(x.text)}
`,w}async function T(){if(u||!y||!r)return;const x=parseInt(document.getElementById("log-lines").value),w=document.getElementById("logs-content");try{const C=await i(y,x);if(C.error){w.innerHTML=`
\u26A0\uFE0F Error
${escapeHtml(C.error)}
`;return}w.innerHTML=`
Stream Log Output
`,C.logs&&C.logs.length>0?(C.logs.forEach(k=>{const I=E(k);w.appendChild(I)}),w.scrollTop=w.scrollHeight):w.innerHTML+=`
No logs available for this container
`}catch(C){w.innerHTML=`
Failed to fetch logs: ${escapeHtml(C.message)}
`}}function L(x,w){y=x,l=w,r=!0,b=!1,u=!1,v();const C=document.getElementById("logs-modal"),k=document.getElementById("logs-title"),I=document.getElementById("logs-pause"),A=document.getElementById("logs-stream");k.textContent=`\u{1F4CB} ${w} - Container Logs`,I.textContent="\u23F8\uFE0F Pause",I.classList.remove("paused"),A&&(A.style.display=""),C.classList.add("show"),T(),f=setInterval(T,DC.POLL.LOGS)}async function P(x,w=100){try{const C=`/api/v1/logs/file?path=${encodeURIComponent(x)}&tail=${w}`,k=await fetch(C,{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(C){return console.error("File logs fetch failed:",C),{error:C.message}}}function S(x){const w=document.createElement("div");w.className="log-entry",w.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 C=x.text;let k="INFO",I="var(--fg)";C.match(/ERROR|FATAL|CRITICAL/i)?(k="ERROR",I="var(--bad-fg)"):C.match(/WARN|WARNING/i)?(k="WARN",I="#f39c12"):C.match(/DEBUG/i)&&(k="DEBUG",I="var(--muted)");const O=`${k}`;return w.innerHTML=`
${O}
${escapeHtml(C)}
`,w}async function B(){if(u||!h||!b)return;const x=parseInt(document.getElementById("log-lines").value),w=document.getElementById("logs-content");try{const C=await P(h,x);if(C.error){w.innerHTML=`
\u26A0\uFE0F Error
${escapeHtml(C.error)}
`;return}w.innerHTML=`
Log Output (${C.count} of ${C.totalLines} lines)
`,C.logs&&C.logs.length>0?(C.logs.forEach(k=>{const I=S(k);w.appendChild(I)}),w.scrollTop=w.scrollHeight):w.innerHTML+=`
No logs available in this file
`}catch(C){w.innerHTML=`
Failed to fetch logs: ${escapeHtml(C.message)}
`}}function $(x,w){h=x,a=w,b=!0,r=!1,u=!1;const C=document.getElementById("logs-modal"),k=document.getElementById("logs-title"),I=document.getElementById("logs-pause"),A=document.getElementById("logs-stream");k.textContent=`\u{1F4CB} ${w} - Application Logs`,I.textContent="\u23F8\uFE0F Pause",I.classList.remove("paused"),A&&(A.style.display="none"),C.classList.add("show"),B(),f=setInterval(B,DC.POLL.LOGS)}document.querySelector(".top")?.addEventListener("click",x=>{const w=x.target.closest('[id$="-logs"]');if(!w)return;const C=w.id.replace("-logs","");SITE.dnsServers[C]&&p(C)}),document.getElementById("logs-close")?.addEventListener("click",t),document.getElementById("logs-pause")?.addEventListener("click",()=>{u=!u;const x=document.getElementById("logs-pause");u?(x.textContent="\u25B6\uFE0F Resume",x.classList.add("paused")):(x.textContent="\u23F8\uFE0F Pause",x.classList.remove("paused"),s())}),document.getElementById("log-lines")?.addEventListener("change",()=>{u||s()}),document.getElementById("logs-stream")?.addEventListener("click",()=>{!r||!y||(n?v():c(y))}),document.getElementById("logs-modal")?.addEventListener("click",x=>{x.target.id==="logs-modal"&&t()}),document.addEventListener("keydown",x=>{x.key==="Escape"&&document.getElementById("logs-modal")?.classList.contains("show")&&t()}),window.openContainerLogsModal=L,window.openFileLogsModal=$,window.openLogsModal=p})(),(function(){injectModal("service-edit-modal",`

Edit Service

.home
The port Caddy will proxy to (container's exposed port)
Enter a URL or upload an image file (PNG, JPG, SVG)
`),injectModal("delete-service-modal",`

Delete Service

`),injectModal("add-service-modal",`

Add Service

Options
Checking Tailscale...
Group services on the dashboard by purpose (Media, Productivity, etc.)

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