(function(o){"use strict";class f{constructor(){this.errors=[],this.maxErrors=50}logError(g,i,s={}){const h={timestamp:new Date().toISOString(),context:g,message:i instanceof Error?i.message:i,stack:i instanceof Error?i.stack:null,metadata:s};this.errors.push(h),this.errors.length>this.maxErrors&&this.errors.shift(),console.error(`[Onboarding Error] ${g}:`,i,s)}recoverFromError(g,i){switch(this.classifyError(g)){case"ELEMENT_NOT_FOUND":return this.logError("Element Not Found",g,{currentStep:i}),{action:"SKIP_STEP",nextStep:i+1,message:"Target element not found, skipping to next step"};case"STORAGE_UNAVAILABLE":return this.logError("Storage Unavailable",g),{action:"USE_MEMORY_STORAGE",message:"Local storage unavailable, using in-memory storage"};case"DRIVER_NOT_LOADED":return this.logError("Driver.js Not Loaded",g),{action:"ABORT_TOUR",message:"Driver.js library not loaded, cannot start tour"};case"INVALID_TOOLTIP":return this.logError("Invalid Tooltip Configuration",g,{currentStep:i}),{action:"SKIP_STEP",nextStep:i+1,message:"Invalid tooltip configuration, skipping"};case"THEME_DETECTION_FAILED":return this.logError("Theme Detection Failed",g),{action:"USE_DEFAULT_THEME",message:"Using default dark theme"};default:return this.logError("Unknown Error",g,{currentStep:i}),{action:"ABORT_TOUR",message:"Unexpected error occurred, aborting tour"}}}classifyError(g){const i=g.message||g.toString();return i.includes("element")&&i.includes("not found")?"ELEMENT_NOT_FOUND":i.includes("storage")||i.includes("quota")?"STORAGE_UNAVAILABLE":i.includes("driver")||i.includes("undefined")?"DRIVER_NOT_LOADED":i.includes("invalid")||i.includes("validation")?"INVALID_TOOLTIP":i.includes("theme")?"THEME_DETECTION_FAILED":"UNKNOWN"}getErrors(){return[...this.errors]}clearErrors(){this.errors=[]}getStatistics(){const g={total:this.errors.length,byContext:{},byType:{},recent:this.errors.slice(-10)};return this.errors.forEach(i=>{g.byContext[i.context]=(g.byContext[i.context]||0)+1;const s=this.classifyError({message:i.message});g.byType[s]=(g.byType[s]||0)+1}),g}handleDriverLoadFailure(){this.logError("Driver.js Load Failure","Driver.js library failed to load");const g=document.createElement("div");return g.id="onboarding-fallback",g.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;
`,g.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(g),setTimeout(()=>{g.parentNode&&g.parentNode.removeChild(g)},1e4),!0}handleStorageUnavailable(){this.logError("Storage Unavailable","Local storage is not available");const g={data:{},getItem(i){return this.data[i]||null},setItem(i,s){this.data[i]=s},removeItem(i){delete this.data[i]},clear(){this.data={}}};return console.warn("[ErrorHandler] Using in-memory storage - progress will not persist"),g}sendToErrorTracking(g){}}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 g=await fetch("/api/v1/config");if(g.ok){const i=await g.json();if(i.tld&&(SITE.tld=i.tld.startsWith(".")?i.tld:"."+i.tld),i.dns&&(SITE.dnsIp=i.dns.ip||"",SITE.dnsPort=i.dns.port||DC.DEFAULTS.DNS_PORT),i.dnsServers&&typeof i.dnsServers=="object")for(const[h,n]of Object.entries(i.dnsServers))h!=="__proto__"&&h!=="constructor"&&h!=="prototype"&&(SITE.dnsServers[h]=n);i.configurationType&&(SITE.configurationType=i.configurationType),i.domain&&(SITE.domain=i.domain),i.defaults&&(SITE.defaults=i.defaults),i.routingMode&&(SITE.routingMode=i.routingMode),SITE.onboardingCompleted=i.onboardingCompleted===!0,localStorage.setItem("dashcaddy_site_config",JSON.stringify({tld:SITE.tld,configurationType:SITE.configurationType,domain:SITE.domain,routingMode:SITE.routingMode})),renderDnsCards();const s=document.getElementById("manage-tokens");s&&(s.style.display=Object.keys(SITE.dnsServers).length?"":"none")}}catch{}document.querySelectorAll("[data-tld]").forEach(g=>g.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=' ',g=o.firstElementChild;f.forEach(i=>{const s=escapeHtml(i),h=escapeHtml((SITE.dnsServers[i].name||i).toUpperCase()),n=document.createElement("div");n.className="card",n.setAttribute("data-app",i),n.setAttribute("data-status","off"),n.innerHTML=`--
Restart \u2B06\uFE0F Open Logs \u2699\uFE0F
`,o.insertBefore(n,g)})}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(),g=!["GET","HEAD","OPTIONS"].includes(u);if(g)try{const s=await getCSRFToken();f.headers={...f.headers,"X-CSRF-Token":s}}catch(s){errorHandler.logError("[CSRF] Add to Request",s,{function:"secureFetch"})}f.signal||(f={...f,signal:AbortSignal.timeout(15e3)});const i=await fetch(o,f);if(g&&i.status===403)try{const s=await i.clone().json();if(s.error&&(s.error.includes("DC-100")||s.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 i}async function postJSON(o,f){const u=await secureFetch(o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(f)}),g=await u.json();if(!u.ok||g.success===!1)throw new Error(g.error||`Request failed (${u.status})`);return g}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,g={}){const i=o.innerHTML,{successText:s="\u2705",resetDelay:h=DC.DELAYS.BTN_RESET}=g;o.disabled=!0,o.innerHTML=f;try{const n=await u();return o.innerHTML=s,setTimeout(()=>{o.innerHTML=i,o.disabled=!1},h),n}catch(n){throw o.innerHTML=i,o.disabled=!1,n}}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?.addEventListener("click",()=>o.classList.remove("show"))))}function showNotification(o,f="info",u=3e3){const g=document.querySelector(".deploy-notification");g&&g.remove();const i={info:{bg:"#2196F3",fg:"#fff"},success:{bg:"var(--ok-bg)",fg:"var(--ok-fg)"},error:{bg:"#f44336",fg:"#fff"},warning:{bg:"#ff9800",fg:"#fff"}},s=i[f]||i.info,h=document.createElement("div");h.className="deploy-notification",h.textContent=o,h.style.cssText=`
position: fixed; top: 20px; right: 20px;
background: ${s.bg}; color: ${s.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(g=>g.id===o);if(u){for(const[g,i]of Object.entries(f))g!=="__proto__"&&g!=="constructor"&&g!=="prototype"&&(u[g]=i);DC_BUS.emit("apps:changed",this._apps)}return u}};(function(){function o(){const g=document.createElement("div");return g.className="skeleton-card",g.innerHTML='
',g}function f(g){const i=document.getElementById("cards");if(!(!i||i.querySelector(".card"))){g=g||6;for(let s=0;s.4,P={};return P.hover=C?l(b,L,.35):l(b,$,.08),P["card-hover"]=l(b,P.hover,.5),P.base=l(L,b,.6),P["fg-muted"]=l(x,L,.35),P.success=I,P.error=S,P.warning=C?"#d68a00":"#f39c12",P}function a(E,L){var $=L.lightBg||L.bg&&y(L.bg)>.4,x=L.accent||L["accent-strong"]||"#888888",b=m(x);return $?":root."+E+` body {
background:
radial-gradient(1200px 800px at 10% -10%, rgba(`+b.r+","+b.g+","+b.b+`, .08), transparent 60%),
radial-gradient(1000px 700px at 110% 10%, rgba(`+b.r+","+b.g+","+b.b+`, .05), transparent 55%),
var(--bg);
}
`:":root."+E+` body {
background:
radial-gradient(1200px 900px at 8% -12%, rgba(`+b.r+","+b.g+","+b.b+`, .10), transparent 60%),
radial-gradient(1000px 700px at 110% -10%, rgba(`+b.r+","+b.g+","+b.b+`, .07), transparent 55%),
var(--bg);
}
`}function p(E,L){var $=L.lightBg||L.bg&&y(L.bg)>.4;return $?":root."+E+` button:hover {
background: color-mix(in srgb, var(--accent-strong) 12%, white 88%);
border-color: rgba(0, 0, 0, .15);
box-shadow: 0 1px 6px rgba(0, 0, 0, .08), inset 0 1px 0 rgba(255, 255, 255, .8);
}
`:":root."+E+` button:hover {
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(){s.forEach(function(E){document.documentElement.style.removeProperty("--"+E)})}function v(E,L){var $=E.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"");$||($="custom"),g.indexOf($)!==-1&&($=$+"-custom");for(var x=safeGetJSON(f,{}),b=$,I=2;x[$]&&$!==L;)$=b+"-"+I++;return $}function d(E){var L=document.getElementById("user-theme-styles");L&&L.remove(),i.length=g.length,Object.keys(w).forEach(function(S){g.indexOf(S)===-1&&delete w[S]});var $=E||safeGetJSON(f,{}),x=Object.keys($);if(x=x.filter(function(S){return g.indexOf(S)===-1}),!!x.length){var b="";x.forEach(function(S){var C=$[S];i.indexOf(S)===-1&&i.push(S);var P={};s.forEach(function(O){C[O]&&(P[O]=C[O])}),P["card-bg"]=C["card-base"]||C.bg,C.lightBg&&(P.lightBg=!0);var D=e(P);n.forEach(function(O){!P[O]&&D[O]&&(P[O]=D[O])}),w[S]=P,b+=":root."+S+` {
`,s.forEach(function(O){P[O]&&(b+=" --"+O+": "+P[O]+`;
`)}),b+=`}
`,b+=a(S,P),b+=p(S,P)});var I=document.createElement("style");I.id="user-theme-styles",I.textContent=b,document.head.appendChild(I)}}function k(){secureFetch("/api/v1/themes").then(function(E){return E.json()}).then(function(E){if(!(!E.success||!E.themes)){var L=E.themes,$=safeGetJSON(f,{});if(JSON.stringify(L)!==JSON.stringify($)){safeSet(f,JSON.stringify(L)),d(L);var x=safeGet(o);x&&i.indexOf(x)!==-1&&T(x)}}}).catch(function(){})}function B(){var E=safeGetJSON(u);if(E){var L=E.name||"Custom",$=v(L),x={name:L};s.forEach(function(S){E[S]&&(x[S]=E[S])});var b=safeGetJSON(f,{});b[$]=x,safeSet(f,JSON.stringify(b)),safeGet(o)==="custom"&&safeSet(o,$),safeRemove(u);var I={};s.forEach(function(S){x[S]&&(I[S]=x[S])}),fetch("/api/v1/themes/"+$,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:L,colors:I})}).catch(function(){})}}function T(E){document.documentElement.classList.add("theme-transitioning"),i.forEach(function(b){b!=="dark"&&document.documentElement.classList.remove(b)}),c(),E!=="dark"&&document.documentElement.classList.add(E),safeSet(o,E);var L=w[E],$=document.querySelector('meta[name="theme-color"]');$&&L&&$.setAttribute("content",L.bg);var x=L&&L.lightBg;!x&&L&&L.bg&&(x=y(L.bg)>.4),x?document.documentElement.classList.add("light-bg"):document.documentElement.classList.remove("light-bg"),setTimeout(function(){document.documentElement.classList.remove("theme-transitioning")},300)}B(),d();var A=safeGet(o);A==="red"&&(A="black",safeSet(o,"black")),A&&A!=="dark"&&i.indexOf(A)===-1&&(A=null),T(A||t()),k(),window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change",function(E){safeGet(o)||T(E.matches?"dark":"light")}),window.THEMES=i,window.BUILTIN_THEMES=g,window.THEME_COLORS=w,window.THEME_PROPS=s,window.BASE_PROPS=h,window.DERIVED_PROPS=n,window.USER_THEMES_KEY=f,window.applyTheme=T,window.clearCustomProperties=c,window.injectUserThemeStyles=d,window.syncThemesFromServer=k,window.slugifyThemeName=v,window.getActiveTheme=function(){return safeGet(o)||t()},window.deriveExtendedColors=e,window.hexToRgb=m,window.rgbToHex=r,window.blendColors=l})(),(function(){function o(){const h=document.querySelector(".totp-card");if(!h)return;const w=getComputedStyle(h).backgroundColor.match(/\d+/g);if(!w)return;const m=(.299*+w[0]+.587*+w[1]+.114*+w[2])/255,r=h.querySelector(".totp-logo-dark"),l=h.querySelector(".totp-logo-light");r&&(r.style.display=m>.5?"none":""),l&&(l.style.display=m>.5?"":"none")}function f(){const h=document.getElementById("totp-overlay");if(h){h.classList.add("show"),setTimeout(o,50);const n=h.querySelector(".totp-digits input");n&&setTimeout(()=>n.focus(),100)}}function u(){const h=document.getElementById("totp-overlay");h&&h.classList.remove("show")}const g=document.getElementById("totp-digits");if(g){const h=g.querySelectorAll("input");h.forEach((n,w)=>{n.addEventListener("input",m=>{const r=m.target.value.replace(/\D/g,"");m.target.value=r.slice(0,1),r&&wy.value).join("");l.length===6&&i(l)}),n.addEventListener("keydown",m=>{m.key==="Backspace"&&!m.target.value&&w>0&&(h[w-1].focus(),h[w-1].value="")}),n.addEventListener("paste",m=>{m.preventDefault();const r=(m.clipboardData.getData("text")||"").replace(/\D/g,"");r.length>=6&&(h.forEach((l,y)=>{l.value=r[y]||""}),h[5].focus(),i(r.slice(0,6)))})})}async function i(h){const n=document.getElementById("totp-error");n.textContent="Verifying...",n.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){n.textContent="",m.csrfToken&&(csrfToken=m.csrfToken),u();const r=safeSessionGet("totp_redirect");if(r){try{sessionStorage.removeItem("totp_redirect")}catch{}window.location.href=r;return}typeof window.initializeDashboard=="function"&&window.initializeDashboard()}else{n.textContent=m.error||"Invalid code",n.className="totp-error";const r=document.querySelectorAll("#totp-digits input");r.forEach(l=>{l.value=""}),r[0]?.focus()}}catch{n.textContent="Connection error",n.className="totp-error"}}const s=new URLSearchParams(window.location.search);if(s.get("auth")==="required"){const h=s.get("return");if(h)try{const n=new URL(h,window.location.origin),w=n.hostname,m=n.origin===window.location.origin,r=SITE.tld.startsWith(".")?SITE.tld:"."+SITE.tld,l=w.endsWith(r)||w===r.substring(1);(m||l)&&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
/
`),injectModal("service-creds-modal",`
Service Credentials
Credentials are injected automatically when accessing this service.
No credentials stored
Quality Profile
Used when requesting via Seerr
-- Enter API key first --
Fetch
Service Login
Save
Clear
Cancel
`);const f=document.getElementById("service-creds-modal");let u=null;const g=["sonarr","radarr","prowlarr","overseerr"],i=["sonarr","radarr"];function s(r){return r.externalUrl||r.url||""}function h(r){const l=document.getElementById("svc-creds-error");l.textContent=r,l.style.display=""}function n(){const r=document.getElementById("svc-creds-error");r.textContent="",r.style.display="none"}window.openServiceCredsModal=async function(r){u=r,n();const l=document.getElementById("svc-creds-title"),y=document.getElementById("svc-creds-desc"),e=document.getElementById("svc-creds-seedhost"),a=document.getElementById("svc-creds-apikey"),p=document.getElementById("svc-creds-basic"),t=document.getElementById("svc-creds-quality");l.textContent=r.name+" Credentials";const c=!!r.isExternal,v=g.includes(r.id)||g.includes(r.appTemplate),d=i.includes(r.id)||i.includes(r.appTemplate);e.style.display=c?"":"none",a.style.display=v?"":"none",t.style.display=d?"":"none",p.style.display=c?"none":"";const k=document.getElementById("svc-quality-select");k.innerHTML='-- Enter API key first -- ',document.getElementById("svc-quality-status").textContent="",c?(y.textContent="Seedhost credentials auto-login past the HTTP prompt. API key bypasses the app login.",document.getElementById("svc-seedhost-pass").placeholder=`Password for ${r.name}`):v?y.textContent="API key bypasses the app login screen automatically.":y.textContent="Credentials are injected automatically when accessing this service.",await w(r),f.classList.add("show")};async function w(r){const l=document.getElementById("svc-creds-dot"),y=document.getElementById("svc-creds-status"),e=document.getElementById("svc-creds-clear");let a=!1;if(r.isExternal){try{const c=await(await fetch(`/api/v1/seedhost-creds?serviceId=${r.id}`)).json();c.success?(document.getElementById("svc-seedhost-user").value=c.username||"",c.hasCredentials&&(a=!0)):document.getElementById("svc-seedhost-user").value=""}catch{}document.getElementById("svc-seedhost-pass").value=""}try{const c=await(await fetch(`/api/v1/services/${r.id}/credentials`)).json();c.success&&(c.hasApiKey?(document.getElementById("svc-apikey-input").value="\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022",a=!0):document.getElementById("svc-apikey-input").value="",c.hasBasicAuth&&!r.isExternal?(document.getElementById("svc-basic-user").value=c.username||"",a=!0):document.getElementById("svc-basic-user").value="")}catch{}document.getElementById("svc-basic-pass")&&(document.getElementById("svc-basic-pass").value="");const p=r.id||r.appTemplate;if(i.includes(p)&&await m(r),a){l.style.background="var(--ok-fg, #74dfc4)",y.style.color="var(--ok-fg, #74dfc4)",y.textContent="Credentials stored",e.style.display="";const t=document.getElementById(`creds-btn-${r.id}`);t&&t.classList.add("has-creds")}else l.style.background="var(--muted)",y.style.color="var(--muted)",y.textContent="No credentials stored",e.style.display="none"}async function m(r){const l=document.getElementById("svc-quality-select"),y=document.getElementById("svc-quality-status"),e=r.id||r.appTemplate,a=s(r);if(!a){l.innerHTML='-- No service URL -- ';return}l.innerHTML='Loading... ',y.textContent="";try{const p=new URLSearchParams({service:e,url:a}),c=await(await fetch(`/api/v1/arr/quality-profiles?${p}`)).json();if(!c.success||!c.profiles?.length){l.innerHTML='-- No profiles found (enter API key and click Fetch) -- ';return}l.innerHTML="";for(const v of c.profiles){const d=document.createElement("option");d.value=v.id,d.textContent=v.name,l.appendChild(d)}if(c.storedProfileId&&(l.value=String(c.storedProfileId)),!l.value){const v=c.profiles.find(d=>/720/i.test(d.name));v&&(l.value=String(v.id))}!l.value&&c.profiles.length&&(l.value=String(c.profiles[0].id)),y.innerHTML=`${c.profiles.length} profiles loaded `}catch(p){l.innerHTML='-- Failed to load -- ',y.innerHTML=`Error: ${p.message} `}}document.getElementById("svc-quality-fetch")?.addEventListener("click",async()=>{if(!u)return;const r=u.id||u.appTemplate,l=s(u),e=document.getElementById("svc-apikey-input")?.value.trim(),a=document.getElementById("svc-quality-select"),p=document.getElementById("svc-quality-status");if(!l){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}a.innerHTML='Fetching... ',p.textContent="";try{const t=new URLSearchParams({service:r,url:l,apiKey:e}),v=await(await fetch(`/api/v1/arr/quality-profiles?${t}`)).json();if(!v.success){a.innerHTML='-- Error -- ',p.innerHTML=`${v.error||"Failed to fetch profiles"} `;return}if(!v.profiles?.length){a.innerHTML='-- No profiles found -- ';return}a.innerHTML="";for(const k of v.profiles){const B=document.createElement("option");B.value=k.id,B.textContent=k.name,a.appendChild(B)}const d=v.profiles.find(k=>/720/i.test(k.name));d?a.value=String(d.id):v.profiles.length&&(a.value=String(v.profiles[0].id)),p.innerHTML=`${v.profiles.length} profiles loaded `}catch(t){a.innerHTML='-- Error -- ',p.innerHTML=`${t.message} `}}),document.getElementById("svc-creds-save")?.addEventListener("click",async()=>{if(!u)return;const r=document.getElementById("svc-creds-save");r.textContent="Saving...",r.disabled=!0,n();try{const l=g.includes(u.id)||g.includes(u.appTemplate),y=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 a=document.getElementById("svc-apikey-input")?.value.trim();if(a&&a!=="\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022")if(l){const p=s(u),t=document.getElementById("svc-quality-select"),c=t?.value?parseInt(t.value):void 0,v=t?.selectedOptions?.[0]?.textContent||void 0,k=await(await secureFetch("/api/v1/arr/credentials",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({service:y,apiKey:a,url:p||void 0,qualityProfileId:c||void 0,qualityProfileName:v||void 0})})).json();if(!k.success){h(k.error||"Failed to save API key"),r.textContent="Save",r.disabled=!1;return}k.connectionTest&&!k.connectionTest.success&&h(`API key saved but connection test failed: ${k.connectionTest.error}`)}else await secureFetch(`/api/v1/services/${u.id}/credentials`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:a})});else if(l&&i.includes(y)){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:y,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 w(u)}catch(l){o.logError("[ServiceCredentials] Save",l,{function:"saveCredentials"}),h("Failed to save: "+(l.message||"Unknown error"))}r.textContent="Save",r.disabled=!1}),document.getElementById("svc-creds-clear")?.addEventListener("click",async()=>{if(u&&confirm(`Remove stored credentials for ${u.name}?`)){n();try{const r=u.id||u.appTemplate,l=g.includes(r);u.isExternal&&await secureFetch(`/api/v1/seedhost-creds?serviceId=${u.id}`,{method:"DELETE"}),await secureFetch(`/api/v1/services/${u.id}/credentials`,{method:"DELETE"}),l&&await secureFetch(`/api/v1/arr/credentials/${r}`,{method:"DELETE"});const y=document.getElementById(`creds-btn-${u.id}`);y&&y.classList.remove("has-creds"),await w(u)}catch(r){o.logError("[ServiceCredentials] Clear",r,{function:"clearCredentials"}),h("Failed to clear: "+(r.message||"Unknown error"))}}}),document.getElementById("svc-creds-close")?.addEventListener("click",()=>{f.classList.remove("show"),u=null}),f?.addEventListener("click",r=>{r.target===f&&(f.classList.remove("show"),u=null)}),window.refreshCredsButtons=async function(){try{for(const r of window.APPS||[]){if(!r.isExternal&&!r.appTemplate&&!r.url)continue;let l=!1;if(r.isExternal)try{const a=await(await fetch(`/api/v1/seedhost-creds?serviceId=${r.id}`)).json();a.success&&a.hasCredentials&&(l=!0)}catch{}try{const a=await(await fetch(`/api/v1/services/${r.id}/credentials`)).json();a.success&&(a.hasApiKey||a.hasBasicAuth)&&(l=!0)}catch{}const y=document.getElementById(`creds-btn-${r.id}`);y&&y.classList.toggle("has-creds",l)}}catch{}}})(),(function(){const o=new ErrorHandler;injectModal("totp-settings-modal",`
Authentication Settings
TOTP is not configured
Copy this key into your authenticator app:
\u{1F4CB}
Show QR code (for mobile authenticator apps)
Session Duration:
15 minutes
30 minutes
1 hour
2 hours
4 hours
8 hours
12 hours
24 hours
Never (disable TOTP)
How long before you need to re-enter your code
Disable TOTP
Close
`);async function f(){try{const s=await(await fetch("/api/v1/totp/config")).json();if(!s.success)return;const{enabled:h,sessionDuration:n,isSetUp:w}=s.config,m=document.getElementById("totp-status-dot"),r=document.getElementById("totp-status-text"),l=document.getElementById("totp-status-banner"),y=document.getElementById("totp-setup-section"),e=document.getElementById("totp-qr-section"),a=document.getElementById("totp-duration-section"),p=document.getElementById("totp-disable-section");h&&w?(m.style.background="var(--ok-fg, #7ef2ff)",l.style.borderColor="var(--ok-fg, #7ef2ff)",l.style.background="color-mix(in srgb, var(--ok-fg) 8%, transparent)",r.textContent="TOTP is active",r.style.color="var(--ok-fg, #7ef2ff)",y.style.display="none",e.style.display="none",a.style.display="block",p.style.display="block",document.getElementById("totp-duration-select").value=n):(m.style.background="var(--muted)",l.style.borderColor="var(--border)",l.style.background="transparent",r.textContent="TOTP is not configured",r.style.color="var(--muted)",y.style.display="block",e.style.display="none",a.style.display="none",p.style.display="none"),g(h&&w,n)}catch(i){console.warn("Failed to load TOTP settings:",i)}}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 g(i,s){const h=document.getElementById("auth-card"),n=document.getElementById("auth-pill"),w=document.getElementById("auth-dot"),m=document.getElementById("auth-status-text");h&&(i?(h.setAttribute("data-status","on"),n.className="badge on",n.textContent="YES",w.className="dot ok at-bl",m.textContent="Session: "+(u[s]||s)):(h.setAttribute("data-status","off"),n.className="badge off",n.textContent="NO",w.className="dot bad at-bl",m.textContent="Not configured"))}document.getElementById("totp-setup-btn")?.addEventListener("click",async()=>{try{const s=await(await secureFetch("/api/v1/totp/setup",{method:"POST"})).json();s.success&&(document.getElementById("totp-qr-image").src=s.qrCode,document.getElementById("totp-manual-key").textContent=s.manualKey,document.getElementById("totp-setup-section").style.display="none",document.getElementById("totp-qr-section").style.display="block",document.getElementById("totp-setup-code").value="",document.getElementById("totp-setup-error").textContent="",document.getElementById("totp-setup-code").focus())}catch(i){o.logError("[TOTP] Setup Failed",i,{function:"setupTOTP"})}}),document.getElementById("totp-import-btn")?.addEventListener("click",async()=>{const i=document.getElementById("totp-import-key").value.trim(),s=document.getElementById("totp-import-error");if(s.textContent="",!i){s.textContent="Paste a Base32 secret key first";return}try{const n=await(await secureFetch("/api/v1/totp/setup",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({secret:i})})).json();n.success?(s.textContent="",document.getElementById("totp-qr-image").src=n.qrCode,document.getElementById("totp-manual-key").textContent=n.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()):s.textContent=n.error||n.message||"Import failed"}catch{s.textContent="Connection error \u2014 try refreshing the page"}}),document.getElementById("totp-copy-key")?.addEventListener("click",()=>{const i=document.getElementById("totp-manual-key").textContent;navigator.clipboard.writeText(i).then(()=>{const s=document.getElementById("totp-copy-key");s.textContent="\u2705",setTimeout(()=>{s.textContent="\u{1F4CB}"},2e3)})}),document.getElementById("totp-confirm-setup")?.addEventListener("click",async()=>{const i=document.getElementById("totp-setup-code").value,s=document.getElementById("totp-setup-error");if(!/^\d{6}$/.test(i)){s.textContent="Enter a 6-digit code";return}try{const n=await(await secureFetch("/api/v1/totp/verify-setup",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:i})})).json();n.success?(s.textContent="",f()):s.textContent=n.error||"Invalid code"}catch{s.textContent="Connection error"}}),document.getElementById("totp-setup-code")?.addEventListener("keydown",i=>{i.key==="Enter"&&document.getElementById("totp-confirm-setup")?.click()}),document.getElementById("totp-duration-select")?.addEventListener("change",async i=>{try{await secureFetch("/api/v1/totp/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionDuration:i.target.value})}),f()}catch(s){o.logError("[TOTP] Update Session Duration",s,{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(i){o.logError("[TOTP] Disable Failed",i,{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",i=>{i.target.id==="totp-settings-modal"&&closeModal("totp-settings-modal")}),window._updateAuthCard=g,(async()=>{try{const s=await(await fetch("/api/v1/totp/config")).json();if(s.success){const h=s.config.enabled&&s.config.isSetUp;g(h,s.config.sessionDuration)}}catch(i){o.logError("[TOTP] AuthCard Update",i,{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",`
`)}function g(){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,d=>d.toString(16).padStart(2,"0")).join(""),safeSessionSet("dashcaddy-encryption-key",t),t}const i=g();function s(t,c){if(!t)return"";const v=crypto.getRandomValues(new Uint8Array(8)),d=Array.from(v,T=>T.toString(16).padStart(2,"0")).join(""),k=new TextEncoder().encode(c+d);let B="";for(let T=0;TparseInt($,16))),A=atob(t.substring(17)),E=new TextEncoder().encode(c+B);let L="";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=r(t,"readonly"),d=m(t,"admin"),k=r(t,"admin"),B=h(safeGet(`${t}-token-enc`),i),T=h(safeGet(`${t}-username-enc`),i);return{username:k||v||T,token:d||c||B,readonlyToken:c||B,readonlyUsername:v||T,adminToken:d||B,adminUsername:k||T}}document.getElementById("manage-tokens")?.addEventListener("click",()=>{u();const t=document.getElementById("token-management-modal"),c=e();o().forEach(v=>{const d=c[v];document.getElementById(`${v}-readonly-username`).value=d.readonly.username,document.getElementById(`${v}-readonly-token`).value=d.readonly.token,document.getElementById(`${v}-admin-username`).value=d.admin.username,document.getElementById(`${v}-admin-token`).value=d.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,d=document.getElementById(v);d.type==="password"?(d.type="text",c.textContent="\u{1F648}"):(d.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(d=>{y(d,"readonly",document.getElementById(`${d}-readonly-username`).value.trim()),l(d,"readonly",document.getElementById(`${d}-readonly-token`).value.trim()),y(d,"admin",document.getElementById(`${d}-admin-username`).value.trim()),l(d,"admin",document.getElementById(`${d}-admin-token`).value.trim())});const c={};let v=!1;if(t.forEach(d=>{const k={},B=document.getElementById(`${d}-readonly-username`).value.trim(),T=document.getElementById(`${d}-readonly-token`).value.trim(),A=document.getElementById(`${d}-admin-username`).value.trim(),E=document.getElementById(`${d}-admin-token`).value.trim();B&&T&&(k.readonly={username:B,password:T},v=!0),A&&E&&(k.admin={username:A,password:E},v=!0),Object.keys(k).length>0&&(c[d]=k)}),v){t.forEach(d=>{c[d]&&(document.getElementById(`${d}-token-status`).textContent="Verifying...",document.getElementById(`${d}-token-status`).className="token-status")});try{const k=await(await secureFetch("/api/v1/dns/credentials",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({servers:c})})).json();k.results?t.forEach(B=>{const T=document.getElementById(`${B}-token-status`);if(!c[B]){T.textContent="";return}const A=k.results[B];A?.success?(T.textContent="\u2713 Verified & saved",T.className="token-status success"):A?.partial?(T.textContent="\u2713 "+A.partial,T.className="token-status success"):(T.textContent="\u2717 "+(A?.error||"Login failed"),T.className="token-status error")}):k.success?t.forEach(B=>{c[B]&&(document.getElementById(`${B}-token-status`).textContent="\u2713 Saved",document.getElementById(`${B}-token-status`).className="token-status success")}):t.forEach(B=>{c[B]&&(document.getElementById(`${B}-token-status`).textContent="\u2717 "+(k.error||"Failed"),document.getElementById(`${B}-token-status`).className="token-status error")})}catch(d){console.error("Failed to sync DNS credentials to backend:",d),t.forEach(k=>{c[k]&&(document.getElementById(`${k}-token-status`).textContent="\u2713 Saved locally (sync failed)",document.getElementById(`${k}-token-status`).className="token-status")})}}else t.forEach(d=>{document.getElementById(`${d}-token-status`).textContent=""});setTimeout(()=>{t.every(k=>{const B=document.getElementById(`${k}-token-status`)?.textContent;return!B||B.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.")){a(),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=r,window.setToken=l,window.setUsername=y,window.getAllCredentials=e,window.getCredential=n,window.setCredential=w,window.getEncryptionKey=g,window.getDnsIds=o,window.getDnsDisplayName=f})(),(function(){function o(l,y,e=null){const a=document.getElementById(l+"-dot"),p=document.getElementById(l+"-pill"),t=document.getElementById(l+"-time"),c=document.querySelector(`[data-app="${l}"]`);a&&(a.classList.toggle("ok",y),a.classList.toggle("bad",!y)),p&&(p.textContent=y?"ON":"OFF",p.classList.toggle("on",y),p.classList.toggle("off",!y)),t&&e!==null&&(t.textContent=y?`${e}ms`:"timeout",t.className=`response-time ${f(e,y)}`),c&&c.setAttribute("data-status",y?"on":"off")}function f(l,y){return y?l<200?"excellent":l<500?"good":l<1e3?"fair":"slow":"timeout"}async function u(l){const y=performance.now();try{const e=await fetch("/probe/"+l,{cache:"no-store"}),a=performance.now(),p=Math.round(a-y);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-y)}}}window.APPS=[];let g=null,i=!1;async function s(){try{window.SkeletonLoader&&window.SkeletonLoader.show(6);const l=await fetch("/api/v1/services",{cache:"no-store"});l.ok?(window.APPS=await l.json(),window.SkeletonLoader&&window.SkeletonLoader.hide()):(console.error("Failed to load services:",l.status),window.SkeletonLoader&&window.SkeletonLoader.hide())}catch(l){console.error("Failed to load services:",l),window.SkeletonLoader&&window.SkeletonLoader.hide()}}function h(l){const y=window.APPS?.find(a=>a.id===l);if(y?.url)return y.url.startsWith("http")?y.url:"https://"+y.url;if(y?.isExternal&&y.externalUrl)return y.externalUrl;const e=SITE.dnsServers?.[l];return e?"http://"+e.ip+":"+(e.port||5380):buildServiceUrl(l)}function n(l,y,e){const a=document.createElement(l);return y&&(a.className=y),e&&(a.textContent=e),a}function w(){const l=document.getElementById("cards");l.innerHTML="";for(let y=0;y{D.stopPropagation(),window.openContainerLogsModal(e.containerId,e.name)},b.appendChild(S);const C=n("button","update-btn","\u2B06\uFE0F");C.title="Update container to latest version",C.id=`update-btn-${e.id}`,C.onclick=D=>{D.stopPropagation(),window.updateContainer(e.containerId,e.name,e.id)},b.appendChild(C);const P=n("button","exec-btn",">_");P.title="Open terminal",P.onclick=D=>{D.stopPropagation(),window.openExecModal&&window.openExecModal(e.containerId,e.name)},b.appendChild(P)}if(e.logPath&&!e.containerId){const S=n("button","logs-btn","\u{1F4CB}");S.title="View application logs",S.onclick=C=>{C.stopPropagation(),window.openFileLogsModal(e.logPath,e.name)},b.appendChild(S)}if(e.isExternal||e.appTemplate||e.url){const S=n("button","creds-btn","\u{1F511}");S.title="Auto-login credentials",S.id=`creds-btn-${e.id}`,S.onclick=C=>{C.stopPropagation(),window.openServiceCredsModal(e)},b.appendChild(S)}if(e.id!=="internet"){const S=n("button","options-btn","\u2699\uFE0F");S.title="Edit service settings",S.onclick=C=>{C.stopPropagation(),window.openServiceEditModal(e)},b.appendChild(S)}if(e.id!=="internet"){const S=n("button","delete-btn","\u{1F5D1}\uFE0F");S.title="Delete this service",S.onclick=C=>{C.stopPropagation(),window.deleteService(e.id,e.name)},b.appendChild(S)}const I=n("button",null,"Open");I.onclick=()=>window.open(h(e.id),"_blank","noopener"),b.appendChild(I),a.appendChild(b),a.style.transitionDelay=`${Math.min(y*45,270)}ms`,l.appendChild(a)}requestAnimationFrame(()=>{l.querySelectorAll(".card").forEach(y=>y.classList.add("loaded"))}),window.groupRecipeCards&&requestAnimationFrame(()=>window.groupRecipeCards())}function m(l,y,e=null){const a=document.getElementById("dot-"+l+"-grid"),p=document.getElementById("badge-"+l),t=document.getElementById("time-"+l),c=document.querySelector(`[data-app="${l}"]`);a&&(a.classList.toggle("ok",y),a.classList.toggle("bad",!y)),p&&(p.textContent=y?"ON":"OFF",p.classList.toggle("on",y),p.classList.toggle("off",!y)),t&&e!==null&&(t.textContent=y?`${e}ms`:"timeout",t.className=`response-time ${f(e,y)}`),c&&c.setAttribute("data-status",y?"on":"off")}async function r(){if(g)return i=!0,g;function l(a,p=new Date){const t=document.getElementById("stamp");t&&(t.textContent=`${a}: ${new Date(p).toLocaleTimeString()}`)}function y(a){Object.keys(SITE.dnsServers).forEach(t=>{const c=a[t];c&&o(t,c.isUp,c.responseTime)}),a.internet&&o("internet",a.internet.isUp,a.internet.responseTime),window.APPS.forEach(t=>{const c=a[t.id];c&&m(t.id,c.isUp,c.responseTime)})}async function e(){const a=Object.keys(SITE.dnsServers),p=a.map(d=>u(d));p.push(u("internet"));const t=await Promise.all(p);a.forEach((d,k)=>o(d,t[k].isUp,t[k].responseTime));const c=t[t.length-1];o("internet",c.isUp,c.responseTime),(await Promise.all(window.APPS.map(async d=>{const k=await u(d.id);return{id:d.id,...k}}))).forEach(d=>{m(d.id,d.isUp,d.responseTime)})}return g=(async()=>{try{const a=await fetch("/api/v1/services/status",{cache:"no-store"});if(!a.ok)throw new Error(`Status refresh failed (${a.status})`);const p=await a.json();y(p.statuses||{}),l("last check",p.checkedAt||new Date)}catch(a){console.warn("Batched status refresh failed, falling back to direct probes:",a);try{await e(),l("last check")}catch(p){console.error("Dashboard refresh failed:",p),l("last failed")}}finally{g=null,i&&(i=!1,setTimeout(()=>{window.refreshAll()},0))}})(),g}document.querySelector(".top")?.addEventListener("click",l=>{const y=l.target.closest('[id$="-open"]');if(!y)return;const e=y.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",l=>{l.stopPropagation();const y=window.APPS.find(e=>e.id==="ca");y&&window.openServiceCredsModal&&window.openServiceCredsModal(y)}),document.getElementById("options-btn-ca")?.addEventListener("click",l=>{l.stopPropagation();const y=window.APPS.find(e=>e.id==="ca");y&&window.openServiceEditModal&&window.openServiceEditModal(y)}),document.getElementById("delete-btn-ca")?.addEventListener("click",l=>{l.stopPropagation(),window.deleteService&&window.deleteService("ca","DashCA")}),window.loadServices=s,window.buildGrid=w,window.refreshAll=r,window.setQuick=o,window.setBadge=m,window.getResponseTimeClass=f,window.checkServiceWithTiming=u,window.serviceUrl=h,window.el=n})(),(function(){async function o(n){const m=await(await secureFetch(`/api/v1/dns/restart/${n}`,{method:"POST"})).json();if(!m.success)throw new Error(m.error||"Restart failed");return m}document.querySelector(".top")?.addEventListener("click",async n=>{const w=n.target.closest('[id$="-restart"]');if(!w)return;const m=w.id.replace("-restart","");if(SITE.dnsServers[m]&&confirm(`Restart ${m.toUpperCase()} service?`))try{await withButton(w,"...",()=>o(m)),setTimeout(window.refreshAll,DC.DELAYS.RELOAD)}catch(r){showNotification("Restart failed: "+r.message,"error")}});async function f(n,w){const m=document.getElementById(`${n}-update`),r=m?.textContent||"\u2B06\uFE0F";try{m.textContent="\u{1F50D}",m.disabled=!0,m.title="Checking for updates...";const y=await(await fetch(`/api/v1/dns/check-update?server=${encodeURIComponent(w)}`)).json();if(!y.success)throw new Error(y.error||"Failed to check for updates");if(!y.updateAvailable){m.textContent="\u2705",m.title=`Already on latest version (${y.currentVersion})`,showNotification(`${n.toUpperCase()} is already up to date! Current version: ${y.currentVersion}`,"info"),setTimeout(()=>{m.textContent=r,m.disabled=!1,m.title="Update DNS server"},3e3);return}if(!confirm(`Update available for ${n.toUpperCase()}!
Current: ${y.currentVersion}
New: ${y.updateVersion}
`+(y.updateTitle?`${y.updateTitle}
`:"")+`The DNS server will restart during the update.
Proceed?`)){m.textContent=r,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(w)}`,{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(`${n.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(`${n.toUpperCase()} updated successfully! ${p.previousVersion} \u2192 ${p.newVersion}. Server is restarting...`,"success"),setTimeout(()=>{m.textContent=r,m.disabled=!1,m.title="Update DNS server",window.refreshAll()},1e4)}catch(l){console.error("DNS update error:",l),m.textContent="\u274C",m.title="Update failed",showNotification(`Failed to update ${n.toUpperCase()}: ${l.message}`,"error"),setTimeout(()=>{m.textContent=r,m.disabled=!1,m.title="Update DNS server"},3e3)}}document.querySelector(".top")?.addEventListener("click",n=>{const w=n.target.closest('[id$="-update"]');if(!w)return;const m=w.id.replace("-update","");SITE.dnsServers[m]&&f(m,SITE.dnsServers[m]?.ip)}),injectModal("dns-settings-modal",`
DNS Settings
Cancel
Remove
Save
`);let u=null;function g(n){u=n;const w=SITE.dnsServers[n]||{},m=document.getElementById("dns-settings-modal");document.getElementById("dns-settings-title").textContent=`${(w.name||n).toUpperCase()} Settings`,document.getElementById("dns-edit-ip").value=w.ip||"",document.getElementById("dns-edit-port").value=w.port||DC.DEFAULTS.DNS_PORT,document.getElementById("dns-edit-name").value=w.name||"",m.classList.add("show")}async function i(){if(!u)return;const n=document.getElementById("dns-edit-ip").value.trim(),w=document.getElementById("dns-edit-port").value.trim()||DC.DEFAULTS.DNS_PORT,m=document.getElementById("dns-edit-name").value.trim();if(!n){showNotification("Server IP is required","warning");return}const r={dnsServers:{}};r.dnsServers[u]={ip:n,port:String(w)},m&&(r.dnsServers[u].name=m);try{const y=await(await secureFetch("/api/v1/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)})).json();y.success?(SITE.dnsServers[u]=r.dnsServers[u],showNotification(`${u.toUpperCase()} settings saved`,"success"),h(),window.refreshAll()):showNotification(y.error||"Failed to save settings","error")}catch(l){showNotification("Failed to save: "+l.message,"error")}}async function s(){if(u&&confirm(`Remove ${u.toUpperCase()} from dashboard? This won't affect the actual DNS server.`))try{const w=await(await secureFetch("/api/v1/config")).json();w.dnsServers&&delete w.dnsServers[u];const r=await(await secureFetch("/api/v1/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({dnsServers:w.dnsServers||{}})})).json();if(r.success){delete SITE.dnsServers[u];const l=document.querySelector(`.top [data-app="${u}"]`);l&&l.remove(),showNotification(`${u.toUpperCase()} removed from dashboard`,"success"),h()}else showNotification(r.error||"Failed to remove","error")}catch(n){showNotification("Failed to remove: "+n.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",i),document.getElementById("dns-settings-delete")?.addEventListener("click",s),document.getElementById("dns-settings-modal")?.addEventListener("click",n=>{n.target.id==="dns-settings-modal"&&h()}),document.querySelector(".top")?.addEventListener("click",n=>{const w=n.target.closest('[id$="-settings"]');if(!w)return;const m=w.id.replace("-settings","");SITE.dnsServers[m]&&(n.stopPropagation(),g(m))}),document.getElementById("refresh")?.addEventListener("click",window.refreshAll)})(),(function(){injectModal("logs-modal",`
`);let o=null,f=null,u=!1,g=null,i=null,s=!1,h=null,n=null,w=!1,m=null,r=!1;async function l(x,b=25){try{const I=getDnsServerAddr(x),S=await fetch(`/api/v1/dns/logs?server=${I}&limit=${b}`,{cache:"no-store",headers:{Accept:"application/json","Cache-Control":"no-cache"}});if(S.ok){const C=await S.json();return C.success&&C.logs?{logs:C.logs,count:C.count,server:C.server}:{error:C.error||"Failed to fetch logs"}}else return S.status===401?{error:"DNS auto-auth failed - check credentials in settings"}:{error:`HTTP ${S.status}`}}catch(I){return console.error("DNS logs fetch failed:",I),{error:I.message}}}function y(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 b=document.createElement("div");if(b.className="log-entry",b.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 b.style.gridTemplateColumns="1fr",b.innerHTML=`${escapeHtml(x.raw)} `,b;const I=y(x.rcode),S=x.rcode==="Refused"||x.rcode==="REFUSED";return b.innerHTML=`
${escapeHtml(x.timestamp)}
${escapeHtml(x.client)}
${escapeHtml(x.domain)}
${escapeHtml(x.type)}
${escapeHtml(x.rcode)}
`,b}async function a(){if(w){await L();return}if(s){await B();return}if(u||!o)return;const x=parseInt(document.getElementById("log-lines").value),b=document.getElementById("logs-content");try{const I=await l(o,x);if(I.error){b.innerHTML=`
\u26A0\uFE0F Error
${escapeHtml(I.error)}
`;return}b.innerHTML=`
Time
Client
Domain
Type
Status
`,I.logs&&I.logs.length>0?I.logs.forEach(S=>{const C=e(S);b.appendChild(C)}):b.innerHTML+=`
No DNS queries logged yet
`}catch(I){b.innerHTML=`
Failed to fetch logs: ${escapeHtml(I.message)}
`}}function p(x){o=x,u=!1,s=!1;const b=document.getElementById("logs-modal"),I=document.getElementById("logs-title"),S=document.getElementById("logs-pause"),C=document.getElementById("logs-stream");I.textContent=`${x.toUpperCase()} DNS Logs`,S.textContent="\u23F8\uFE0F Pause",S.classList.remove("paused"),C&&(C.style.display="none"),b.classList.add("show"),a(),f=setInterval(a,DC.POLL.LOGS)}function t(){document.getElementById("logs-modal").classList.remove("show"),f&&(clearInterval(f),f=null),v(),o=null,s=!1,g=null,i=null,w=!1,h=null,n=null,u=!1}function c(x){m&&v();const b=document.getElementById("logs-stream"),I=document.getElementById("logs-pause"),S=document.getElementById("logs-content");f&&(clearInterval(f),f=null);try{m=new EventSource(`/api/v1/logs/stream/${x}`),r=!0,b.classList.add("active"),b.textContent="\u{1F534} Live",b.title="Streaming - click to stop",I.style.display="none";const C=document.getElementById("logs-title");C.textContent.includes("\u{1F534}")||(C.innerHTML=C.textContent.replace("\u{1F4CB}","\u{1F4CB} \u{1F534}")),m.onmessage=P=>{try{const D=JSON.parse(P.data);if(D.error){console.error("Stream error:",D.error),v();return}const O=document.createElement("div");O.className="log-entry",O.style.cssText="display: flex; gap: 12px; padding: 6px 10px; border-bottom: 1px solid var(--border); font-size: 0.8rem; align-items: flex-start; font-family: monospace;";const R=(D.stream||"stdout")==="stderr",U=R?"var(--bad-fg)":"var(--fg)",M=`${R?"STDERR":"STDOUT"} `;for(O.innerHTML=`
${M}
${escapeHtml(D.text)}
`,S.appendChild(O),S.scrollTop=S.scrollHeight;S.children.length>500;)S.removeChild(S.firstChild)}catch(D){console.error("Error parsing stream data:",D)}},m.onerror=P=>{console.error("EventSource error:",P),v()}}catch(C){console.error("Failed to start streaming:",C),v()}}function v(){m&&(m.close(),m=null),r=!1;const x=document.getElementById("logs-stream"),b=document.getElementById("logs-pause"),I=document.getElementById("logs-title");x&&(x.classList.remove("active"),x.textContent="\u{1F4E1} Live",x.title="Enable real-time streaming"),b&&(b.style.display=""),I&&(I.textContent=I.textContent.replace(" \u{1F534}","")),s&&g&&!f&&(f=setInterval(B,DC.POLL.LOGS))}async function d(x,b=100){try{const I=`/api/v1/logs/container/${x}?tail=${b}×tamps=true`,S=await fetch(I,{cache:"no-store",headers:{Accept:"application/json","Cache-Control":"no-cache"}});if(S.ok){const C=await S.json();return C.success&&C.logs?{logs:C.logs,count:C.count,containerName:C.containerName,containerId:C.containerId}:{error:C.error||"Failed to fetch container logs"}}else return{error:`HTTP ${S.status}: ${S.statusText}`}}catch(I){return console.error("Container logs fetch failed:",I),{error:I.message}}}function k(x){const b=document.createElement("div");b.className="log-entry",b.style.cssText="display: flex; gap: 12px; padding: 6px 10px; border-bottom: 1px solid var(--border); font-size: 0.8rem; align-items: flex-start; font-family: monospace;";const I=x.stream==="stderr"?"var(--bad-fg)":"var(--fg)",S=x.stream==="stderr"?'STDERR ':'STDOUT ';return b.innerHTML=`
${S}
${escapeHtml(x.text)}
`,b}async function B(){if(u||!g||!s)return;const x=parseInt(document.getElementById("log-lines").value),b=document.getElementById("logs-content");try{const I=await d(g,x);if(I.error){b.innerHTML=`
\u26A0\uFE0F Error
${escapeHtml(I.error)}
`;return}b.innerHTML=`
Stream
Log Output
`,I.logs&&I.logs.length>0?(I.logs.forEach(S=>{const C=k(S);b.appendChild(C)}),b.scrollTop=b.scrollHeight):b.innerHTML+=`
No logs available for this container
`}catch(I){b.innerHTML=`
Failed to fetch logs: ${escapeHtml(I.message)}
`}}function T(x,b){g=x,i=b,s=!0,w=!1,u=!1,v();const I=document.getElementById("logs-modal"),S=document.getElementById("logs-title"),C=document.getElementById("logs-pause"),P=document.getElementById("logs-stream");S.textContent=`\u{1F4CB} ${b} - Container Logs`,C.textContent="\u23F8\uFE0F Pause",C.classList.remove("paused"),P&&(P.style.display=""),I.classList.add("show"),B(),f=setInterval(B,DC.POLL.LOGS)}async function A(x,b=100){try{const I=`/api/v1/logs/file?path=${encodeURIComponent(x)}&tail=${b}`,S=await fetch(I,{cache:"no-store",headers:{Accept:"application/json","Cache-Control":"no-cache"}});if(S.ok){const C=await S.json();return C.success&&C.logs?{logs:C.logs,count:C.count,logPath:C.logPath,totalLines:C.totalLines}:{error:C.error||"Failed to fetch file logs"}}else return{error:(await S.json().catch(()=>({}))).error||`HTTP ${S.status}`}}catch(I){return console.error("File logs fetch failed:",I),{error:I.message}}}function E(x){const b=document.createElement("div");b.className="log-entry",b.style.cssText="display: flex; gap: 12px; padding: 6px 10px; border-bottom: 1px solid var(--border); font-size: 0.8rem; align-items: flex-start; font-family: monospace;";const I=x.text;let S="INFO",C="var(--fg)";I.match(/ERROR|FATAL|CRITICAL/i)?(S="ERROR",C="var(--bad-fg)"):I.match(/WARN|WARNING/i)?(S="WARN",C="#f39c12"):I.match(/DEBUG/i)&&(S="DEBUG",C="var(--muted)");const D=`${S} `;return b.innerHTML=`
${D}
${escapeHtml(I)}
`,b}async function L(){if(u||!h||!w)return;const x=parseInt(document.getElementById("log-lines").value),b=document.getElementById("logs-content");try{const I=await A(h,x);if(I.error){b.innerHTML=`
\u26A0\uFE0F Error
${escapeHtml(I.error)}
`;return}b.innerHTML=`
Log Output (${I.count} of ${I.totalLines} lines)
`,I.logs&&I.logs.length>0?(I.logs.forEach(S=>{const C=E(S);b.appendChild(C)}),b.scrollTop=b.scrollHeight):b.innerHTML+=`
No logs available in this file
`}catch(I){b.innerHTML=`
Failed to fetch logs: ${escapeHtml(I.message)}
`}}function $(x,b){h=x,n=b,w=!0,s=!1,u=!1;const I=document.getElementById("logs-modal"),S=document.getElementById("logs-title"),C=document.getElementById("logs-pause"),P=document.getElementById("logs-stream");S.textContent=`\u{1F4CB} ${b} - Application Logs`,C.textContent="\u23F8\uFE0F Pause",C.classList.remove("paused"),P&&(P.style.display="none"),I.classList.add("show"),L(),f=setInterval(L,DC.POLL.LOGS)}document.querySelector(".top")?.addEventListener("click",x=>{const b=x.target.closest('[id$="-logs"]');if(!b)return;const I=b.id.replace("-logs","");SITE.dnsServers[I]&&p(I)}),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"),a())}),document.getElementById("log-lines")?.addEventListener("change",()=>{u||a()}),document.getElementById("logs-stream")?.addEventListener("click",()=>{!s||!g||(r?v():c(g))}),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=T,window.openFileLogsModal=$,window.openLogsModal=p})(),(function(){injectModal("service-edit-modal",`
Edit Service
Cancel
Save Changes
`),injectModal("delete-service-modal",`
Delete Service
Cancel
Remove
Delete
Remove: Remove from dashboard only (container keeps running)
Delete: Full removal - stops container, removes DNS & Caddy config
`),injectModal("add-service-modal",`
`)})(),(function(){async function o(s){try{const h=await fetch(`/api/v1/caddy/cas?caddyfilePath=${encodeURIComponent(s)}`);if(!h.ok)throw new Error(`Failed to load CAs: ${h.status}`);const n=await h.json();if(n.status==="success"){const w=document.getElementById("existing-ca-select");return w.innerHTML="",n.data.cas.length===0?w.innerHTML='No CAs found in Caddyfile ':(w.innerHTML='Select existing CA... ',n.data.cas.forEach(m=>{const r=document.createElement("option");typeof m=="object"?(r.value=m.id,r.textContent=m.displayName||m.name):(r.value=m,r.textContent=m),w.appendChild(r)})),n.data.cas}else throw new Error(n.message)}catch(h){console.error("Error loading CAs:",h);const n=document.getElementById("existing-ca-select");return n.innerHTML='Error loading CAs ',[]}}function f(s){const{subdomain:h,port:n,ip:w,sslType:m,caName:r,existingCa:l,enableAuth:y,enableCors:e,customHeaders:a,upstreamPath:p,healthCheck:t,timeout:c,tailscaleOnly:v}=s;let d=`${buildDomain(h)} {
`;switch(v&&(d+=` @blocked not remote_ip 100.64.0.0/10
`,d+=` respond @blocked "Access denied. Tailscale connection required." 403
`),m){case"letsencrypt":break;case"caddy-managed":d+=` tls internal
`;break;case"existing-ca":l&&(d+=` tls {
ca ${l}
}
`);break;case"custom-ca":r&&(d+=` tls {
ca ${r}
}
`);break}if(y&&(d+=` basicauth {
admin $2a$14$hashed_password_here
}
`),e&&(d+=` header {
`,d+=` Access-Control-Allow-Origin "*"
`,d+=` Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS"
`,d+=` Access-Control-Allow-Headers "Content-Type, Authorization"
`,d+=` }
`),a)try{const k=JSON.parse(a);d+=` header {
`,Object.entries(k).forEach(([B,T])=>{d+=` ${B} "${T}"
`}),d+=` }
`}catch{console.warn("Invalid JSON in custom headers")}return t&&(d+=` health_uri ${t}
`),d+=` reverse_proxy ${w}:${n} {
`,p&&p!=="/"&&(d+=` rewrite ${p}
`),c&&c!==30&&(d+=` transport http {
`,d+=` dial_timeout ${c}s
`,d+=` response_header_timeout ${c}s
`,d+=` }
`),d+=` }
`,d+=`}
`,d}async function u(s,h,n=DC.DEFAULTS.TTL){const w=window.getToken(getPrimaryDnsId(),"admin");if(!w)throw new Error("DNS admin token not configured. Please set it in the Tokens menu.");const m=buildDomain(s),r=await secureFetch("/api/v1/dns/record",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:m,ip:h,ttl:n,token:w,server:SITE.dnsIp})});if(!r.ok){const y=await r.text();throw new Error(`DNS API Error: ${r.status} - ${y}`)}const l=await r.json();if(!l.success)throw new Error(`DNS Error: ${l.error||"Unknown error"}`);return l}async function g(s){const h={id:s.subdomain,name:s.name,logo:s.logo||`/assets/${s.subdomain}.png`};try{const n=await secureFetch("/api/v1/services",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(h)});if(!n.ok){const w=await n.json();throw new Error(w.error||"Failed to save service")}return await window.loadServices(),window.buildGrid(),h}catch(n){throw console.error("Failed to add service to config:",n),n}}async function i(s){const h=document.getElementById("service-subdomain-input").value.trim(),n=document.getElementById("service-ip-input").value.trim()||"localhost",w=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:`${n}:${w}`,config:s})}),r=await m.json();if(!m.ok||!r.success)throw new Error(r.error||`Caddy API Error: ${m.status}`);return r}window.loadExistingCAs=o,window.generateCaddyConfig=f,window.createDnsRecord=u,window.addServiceToConfig=g,window.addToCaddyfile=i})(),(function(){let o=null;function f(n){o=n;const w=document.getElementById("service-edit-modal");document.getElementById("service-edit-title").textContent=`Edit ${n.name}`,document.getElementById("edit-service-name").value=n.name,document.getElementById("edit-service-url-display").textContent=n.url||buildServiceUrl(n.id),document.getElementById("edit-service-logo-preview").src=n.logo||`/assets/${n.id}.png`,document.getElementById("edit-subdomain").value=n.id,document.getElementById("edit-port").value=n.port||"",document.getElementById("edit-ip").value=n.ip||"localhost",document.getElementById("edit-tailscale-only").checked=n.tailscaleOnly||!1,document.getElementById("edit-logo-url").value=n.logo||"",w.classList.add("show")}function u(){closeModal("service-edit-modal"),o=null}async function g(){if(!o)return;const n=document.getElementById("edit-subdomain").value.trim().toLowerCase(),w=document.getElementById("edit-service-name").value.trim(),m=document.getElementById("edit-port").value.trim(),r=document.getElementById("edit-ip").value.trim()||"localhost",l=document.getElementById("edit-tailscale-only").checked,y=document.getElementById("edit-logo-url").value.trim();if(!n){showNotification("Subdomain is required","warning");return}const e=o.id,a=[];if(n!==e&&a.push("subdomain"),w&&w!==o.name&&a.push("name"),m&&m!==String(o.port)&&a.push("port"),r!==o.ip&&a.push("ip"),l!==(o.tailscaleOnly||!1)&&a.push("tailscale"),y&&y!==o.logo&&a.push("logo"),a.length===0){u();return}const p=document.getElementById("service-edit-save");p.textContent="Saving...",p.disabled=!0;try{const c=await(await secureFetch("/api/v1/services/update",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({oldSubdomain:e,newSubdomain:n,name:w||o.name,port:m||o.port,ip:r,tailscaleOnly:l,logo:y||void 0})})).json();if(!c.success)throw new Error(c.error||"Failed to update service");const v=window.APPS.findIndex(d=>d.id===e);v!==-1&&(window.APPS[v]={...window.APPS[v],id:n,name:w||window.APPS[v].name,port:m||window.APPS[v].port,ip:r,tailscaleOnly:l,logo:y||window.APPS[v].logo}),u(),window.buildGrid(),window.refreshAll()}catch(t){console.error("Error saving service changes:",t),showNotification(`Error saving changes: ${t.message}`,"error")}finally{p.textContent="Save Changes",p.disabled=!1}}document.getElementById("edit-logo-file")?.addEventListener("change",async n=>{const w=n.target.files[0];if(!w)return;if(!w.type.startsWith("image/")){showNotification("Please select an image file","warning");return}const m=new FileReader;m.onload=async r=>{const l=r.target.result;if(document.getElementById("edit-service-logo-preview").src=l,document.getElementById("edit-logo-url").value=l,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:l})})).json();e.success&&e.path&&(document.getElementById("edit-logo-url").value=e.path)}catch{}},m.readAsDataURL(w)}),document.getElementById("service-edit-cancel")?.addEventListener("click",u),document.getElementById("service-edit-save")?.addEventListener("click",g),document.getElementById("service-edit-modal")?.addEventListener("click",n=>{n.target.id==="service-edit-modal"&&u()});function i(n,w,m){return new Promise(r=>{const l=document.getElementById("delete-service-modal"),y=document.getElementById("delete-modal-title"),e=document.getElementById("delete-modal-message"),a=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"),d=document.getElementById("delete-modal-delete");y.textContent=`Delete "${n}"`,w?(e.innerHTML="This service has an associated Docker container. Choose how to proceed:",a.style.display="block",p.textContent=`Container ID: ${m?.slice(0,12)||"Unknown"}`,t.style.display="block",d.style.display="block"):(e.textContent="Remove this service from the dashboard?",a.style.display="none",t.style.display="none",d.style.display="none");const k=()=>{l.classList.remove("show"),c.removeEventListener("click",B),v.removeEventListener("click",T),d.removeEventListener("click",A),l.removeEventListener("click",E)},B=()=>{k(),r(null)},T=()=>{k(),r(!1)},A=()=>{k(),r(!0)},E=L=>{L.target===l&&(k(),r(null))};c.addEventListener("click",B),v.addEventListener("click",T),d.addEventListener("click",A),l.addEventListener("click",E),l.classList.add("show")})}async function s(n,w,m){const r=document.getElementById(`update-btn-${m}`),l=r?.textContent;if(confirm(`Update ${w} 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{r&&(r.textContent="\u{1F504}",r.disabled=!0,r.title="Updating...");const e=await(await secureFetch(`/api/v1/containers/${n}/update`,{method:"POST"})).json();if(e.success){const a=window.APPS.find(p=>p.id===m);a&&e.newContainerId&&(a.containerId=e.newContainerId),r&&(r.textContent="\u2705",r.title="Updated successfully!",setTimeout(()=>{r.textContent=l,r.disabled=!1,r.title="Update container to latest version"},3e3)),setTimeout(()=>window.refreshAll(),2e3),showNotification(`${w} updated successfully!`,"success")}else throw new Error(e.error||"Update failed")}catch(y){console.error("Update error:",y),r&&(r.textContent="\u274C",r.title="Update failed",setTimeout(()=>{r.textContent=l,r.disabled=!1,r.title="Update container to latest version"},3e3)),showNotification(`Failed to update ${w}: ${y.message}`,"error")}}async function h(n,w){const m=window.APPS.find(d=>d.id===n),r=m?buildDomain(m.id):null,l=m?.containerId,y=await i(w||n,l,m?.containerId);if(y===null)return;let e={dashboard:!1,container:null,dns:null,caddy:null,service:null};if(y&&l)try{const d=new URLSearchParams({containerId:m.containerId,subdomain:m.id,ip:m.ip||"localhost",deleteContainer:"true"}),B=await(await secureFetch(`/api/v1/apps/${encodeURIComponent(m.id)}?${d.toString()}`,{method:"DELETE"})).json();B.success?e={...e,...B.results,dashboard:!1}:console.error("App removal failed:",B.error)}catch(d){console.error("App removal error:",d)}else if(y&&r){try{const d=m?.ip||"localhost",B=await(await secureFetch(`/api/v1/dns/record?domain=${encodeURIComponent(r)}&type=A&ipAddress=${encodeURIComponent(d)}&server=${SITE.dnsIp}`,{method:"DELETE"})).json();e.dns=B.success?"deleted":B.error||"failed"}catch(d){e.dns=d.message}try{const k=await(await secureFetch(`/api/v1/site/${encodeURIComponent(r)}`,{method:"DELETE"})).json();e.caddy=k.success||k.error&&k.error.includes("not found")?"removed":k.error||"failed"}catch(d){e.caddy=d.message}}const a=window.APPS.findIndex(d=>d.id===n);a>-1&&(window.APPS.splice(a,1),e.dashboard=!0);try{const d=safeGetJSON("custom-apps",[]),k=d.findIndex(B=>B.id===n);k>-1&&(d.splice(k,1),safeSet("custom-apps",JSON.stringify(d)))}catch{}try{const k=await(await secureFetch(`/api/v1/services/${encodeURIComponent(n)}`,{method:"DELETE"})).json();e.service=k.success?"removed":k.error||"failed"}catch(d){e.service=d.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=d=>!d||c.some(k=>d.toLowerCase().includes(k.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 "${w||n}": ${t.join(", ")}`,"error",6e3)}window.openServiceEditModal=f,window.showDeleteModal=i,window.updateContainer=s,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",a=document.getElementById("service-ip-input").value||g.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,d=document.getElementById("enable-auth").checked,k=document.getElementById("enable-cors").checked,B=document.getElementById("custom-headers-input").value,T=document.getElementById("upstream-path-input").value||"/",A=document.getElementById("health-check-input").value,E=document.getElementById("timeout-input").value||30,L=document.getElementById("dns-preview");L&&(L.textContent=`${buildDomain(e)} \u2192 ${a}`);const $=document.getElementById("url-preview");$&&($.textContent=buildServiceUrl(e));const x={subdomain:e,port:p,ip:a,sslType:t,caName:c,existingCa:v,enableAuth:d,enableCors:k,customHeaders:B,upstreamPath:T,healthCheck:A,timeout:E},b=window.generateCaddyConfig(x),I=document.getElementById("caddy-config-preview");I&&(I.value=b)}const g={localhost:"127.0.0.1",lan:"",tailscale:""};async function i(){try{const t=await fetch("/api/v1/network/ips",{signal:AbortSignal.timeout(2e3)});if(t.ok){const c=await t.json();c.lan&&(g.lan=c.lan),c.tailscale&&(g.tailscale=c.tailscale)}}catch{}const e=document.getElementById("quick-ip-lan"),a=document.getElementById("quick-ip-tailscale");e&&(g.lan?(e.dataset.ip=g.lan,e.textContent=`LAN (${g.lan})`,e.title=`LAN IP: ${g.lan}`):e.style.display="none"),a&&(g.tailscale?(a.dataset.ip=g.tailscale,a.textContent=`Tailscale (${g.tailscale})`,a.title=`Tailscale IP: ${g.tailscale}`):a.style.display="none");const p=document.getElementById("service-ip-input");p&&!p.value&&g.lan&&(p.value=g.lan)}function s(){document.querySelectorAll(".quick-ip-btn").forEach(e=>{e.addEventListener("click",()=>{const a=e.dataset.ip;a&&(document.getElementById("service-ip-input").value=a,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 a=e.target.value;document.querySelectorAll(".quick-ip-btn").forEach(p=>{p.classList.toggle("active",p.dataset.ip===a)})})}async function h(){const e=document.getElementById("add-service-modal");e.classList.add("show");const a=e.querySelector(".weather-modal-content");a&&(a.scrollTop=0),document.body.style.overflow="hidden";const p=document.getElementById("ssl-type-select");p&&(p.value=f()),await i();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 k=await(await fetch("/api/v1/tailscale/status")).json();k.success&&k.installed&&k.connected?(c.innerHTML=`
\u2713 Connected
${k.self?.hostname} (${k.self?.ip})
`,v.disabled=!1):k.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 n(){const e=document.getElementById("service-type-local"),a=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 d(){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",d),a?.addEventListener("change",d)}function w(){const e=document.getElementById("service-name-input"),a=document.getElementById("service-subdomain-input"),p=document.getElementById("subdomain-preview");let t=!1;e?.addEventListener("input",()=>{const T=o(e.value);!t&&a&&(a.value=T),p&&(p.textContent=T?`\u2192 ${buildDomain(T)}`:""),u()}),a?.addEventListener("input",()=>{t=a.value!==o(e?.value||"");const T=a.value.trim()||o(e?.value||"");p&&(p.textContent=T?`\u2192 ${buildDomain(T)}`:""),u()});const c=document.getElementById("external-service-name"),v=document.getElementById("external-service-subdomain"),d=document.getElementById("external-subdomain-preview"),k=document.getElementById("external-domain-preview");let B=!1;c?.addEventListener("input",()=>{const T=o(c.value);!B&&v&&(v.value=T);const A=v?.value||T;d&&(d.textContent=A?`\u2192 ${buildDomain(A)}`:""),k&&(k.textContent=A?buildDomain(A):"")}),v?.addEventListener("input",()=>{B=v.value!==o(c?.value||"");const T=v.value.trim()||o(c?.value||"");d&&(d.textContent=T?`\u2192 ${buildDomain(T)}`:""),k&&(k.textContent=T?buildDomain(T):"")})}async function m(){const e=document.getElementById("external-service-name").value.trim(),a=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,d=document.getElementById("external-create-caddy").checked,k=document.getElementById("external-proxy-ip").value.trim()||SITE.dnsIp||"localhost",B=document.getElementById("external-preserve-host").checked,T=document.getElementById("external-follow-redirects").checked;if(!e||!a){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(!a.startsWith("http://")&&!a.startsWith("https://")){showNotification("External URL must start with http:// or https://","warning");return}const A=buildDomain(p);try{const E={dns:null,caddy:null,dashboard:!1};if(v)if(window.getToken(getPrimaryDnsId(),"admin"))try{const C=await(await secureFetch("/api/v1/dns/record",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:A,ip:k,ttl:DC.DEFAULTS.TTL,server:SITE.dnsIp})})).json();E.dns=C.success?"created":C.error||"failed"}catch(S){E.dns=S.message}else E.dns="no admin token (configure in \u{1F511} Tokens)";if(d)try{const I={subdomain:p,externalUrl:a,preserveHost:B,followRedirects:T,sslType:"caddy-managed",caddyfilePath:DC.DEFAULTS.CADDYFILE,reloadCaddy:!0},C=await(await secureFetch("/api/v1/site/external",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(I)})).json();E.caddy=C.success?"created":C.error||"failed"}catch(I){E.caddy=I.message}const L={id:p,name:e,url:`https://${A}`,externalUrl:a,logo:t||c||"\u{1F310}",isExternal:!0,isCustom:!0};window.APPS.push(L),E.dashboard=!0;const $=["plex","router","chat","sync","torrent","radarr","sonarr","prowlarr","portainer","requests","jellyfin","emby"],x=window.APPS.filter(I=>!$.includes(I.id));safeSet("custom-services",JSON.stringify(x));try{await secureFetch("/api/v1/services",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(window.APPS)})}catch(I){console.warn("Failed to save to services.json:",I)}window.buildGrid(),window.refreshAll(),r();const b=[`External service "${e}" added!`];v&&b.push(`DNS: ${E.dns==="created"?"\u2713":"\u26A0 "+E.dns}`),d&&b.push(`Caddy: ${E.caddy==="created"?"\u2713":"\u26A0 "+E.caddy}`),b.push(`Access at: https://${A}`),showNotification(b.join(" | "),"success",6e3)}catch(E){console.error("Failed to create external service:",E),showNotification(`Failed to create external service: ${E.message}`,"error")}}function r(){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=g.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 a=document.getElementById("external-subdomain-preview");a&&(a.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 d=document.getElementById("external-service-icon");d&&(d.value="");const k=document.getElementById("local-advanced-options");k&&k.removeAttribute("open");const B=document.getElementById("external-advanced-options");B&&B.removeAttribute("open");const T=document.getElementById("service-type-local");T&&(T.checked=!0);const A=document.getElementById("local-service-config"),E=document.getElementById("external-service-config");A&&(A.style.display="grid"),E&&(E.style.display="none");const L=document.getElementById("tab-local"),$=document.getElementById("tab-external");L&&(L.style.background="var(--accent)",L.style.color="var(--bg)"),$&&($.style.background="transparent",$.style.color="var(--muted)")}async function l(){const e=document.getElementById("service-name-input").value.trim(),a=(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,d=parseInt(document.getElementById("dns-ttl-input").value)||DC.DEFAULTS.TTL,k=document.getElementById("manual-tailscale-only")?.checked||!1,B=document.getElementById("ssl-type-select")?.value||"caddy-managed",T=document.getElementById("ca-name-input")?.value||"",A=document.getElementById("existing-ca-select")?.value||"",E=document.getElementById("enable-auth")?.checked||!1,L=document.getElementById("enable-cors")?.checked||!1,$=document.getElementById("custom-headers-input")?.value||"",x=document.getElementById("upstream-path-input")?.value||"/",b=document.getElementById("health-check-input")?.value||"",I=document.getElementById("timeout-input")?.value||30,S=window.getToken(getPrimaryDnsId(),"admin");if(!e||!p||!t){showNotification("Please fill in Name, Port, and IP Address","warning");return}if(!a){showNotification("Could not derive subdomain from name. Please set one in Options.","warning");return}if(v&&!S){showNotification("DNS Admin token required. Configure it in the Tokens menu first.","warning");return}const C={dns:null,caddy:null,dashboard:!1};try{if(v)try{await window.createDnsRecord(a,t,d),C.dns="created"}catch(N){throw console.error("DNS creation failed:",N),C.dns=N.message,new Error(`DNS creation failed: ${N.message}`)}else C.dns="skipped";const P=window.generateCaddyConfig({subdomain:a,port:p,ip:t,sslType:B,caName:T,existingCa:A,enableAuth:E,enableCors:L,customHeaders:$,upstreamPath:x,healthCheck:b,timeout:I,tailscaleOnly:k});try{const R=await(await secureFetch("/api/v1/site",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:buildDomain(a),upstream:`${t}:${p}`,config:P})})).json();if(R.success)C.caddy="added & reloaded";else throw console.error("Caddy configuration failed:",R.error),C.caddy=R.error||"failed",new Error(`Caddy configuration failed: ${R.error}`)}catch(N){throw console.error("Caddy API error:",N),C.caddy=N.message,new Error(`Caddy API error: ${N.message}`)}const D={name:e,subdomain:a,port:p,ip:t,logo:c||`/assets/${a}.png`,tailscaleOnly:k||!1};await window.addServiceToConfig(D),C.dashboard=!0;const O=[`DNS: ${C.dns==="created"?"\u2713":C.dns==="skipped"?"\u25CB":"\u2717"}`,`Caddy: ${C.caddy==="added & reloaded"?"\u2713":"\u2717"}`,`Dashboard: ${C.dashboard?"\u2713":"\u2717"}`];showNotification(`Service "${e}" created! ${O.join(" | ")} \u2014 ${buildServiceUrl(a)}${k?" (Tailscale)":""}`,"success",6e3),r(),window.buildGrid(),window.refreshAll()}catch(P){console.error("Error creating service:",P),showNotification(`Error creating "${e}": ${P.message}`,"error",6e3)}}document.getElementById("add-service")?.addEventListener("click",h),document.getElementById("add-service-cancel")?.addEventListener("click",r),document.getElementById("add-service-create")?.addEventListener("click",()=>{document.querySelector('input[name="service-type"]:checked')?.value==="external"?m():l()}),n(),w(),s(),document.getElementById("ssl-type-select")?.addEventListener("change",e=>{const a=document.getElementById("existing-ca-config"),p=document.getElementById("custom-ca-config");a.style.display="none",p.style.display="none",e.target.value==="existing-ca"?a.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"),a=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=a,e.disabled=!1},2e3)}),document.getElementById("create-dns-record")?.addEventListener("change",e=>{const a=document.getElementById("dns-config");a.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 a=document.getElementById(e);a&&(a.addEventListener("input",u),a.addEventListener("change",u))});function y(){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(a){console.warn("Failed to load custom services:",a)}}y(),window.openAddServiceModal=h,window.closeAddServiceModal=r})(),(function(){let o=null,f=1e3;const u=3e4;function g(){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",i=>{try{const s=JSON.parse(i.data);if(s.serviceId&&typeof window.setBadge=="function"){const h=s.status==="up"||s.status==="healthy";window.setBadge(s.serviceId,h,s.responseTime||null)}}catch{}}),o.addEventListener("resource-alert",i=>{try{const s=JSON.parse(i.data),h=`${s.containerName||s.containerId}: ${s.metric} at ${s.value}% (threshold: ${s.threshold}%)`;typeof showNotification=="function"&&showNotification(h,"warning")}catch{}}),o.addEventListener("auto-restart",i=>{try{const s=JSON.parse(i.data);typeof showNotification=="function"&&showNotification(`Container "${s.containerName}" was auto-restarted`,"info")}catch{}}),o.addEventListener("update-available",i=>{try{const s=JSON.parse(i.data),h=document.getElementById("updates-btn");if(h&&!h.querySelector(".sse-dot")){const n=document.createElement("span");n.className="sse-dot",n.style.cssText="display:inline-block;width:8px;height:8px;border-radius:50%;background:var(--accent);margin-left:6px;vertical-align:middle;",h.appendChild(n)}typeof showNotification=="function"&&showNotification(`Update available for ${s.containerName||s.containerId}`,"info")}catch{}}),o.addEventListener("update-complete",i=>{try{const s=JSON.parse(i.data);typeof showNotification=="function"&&showNotification(`Update completed: ${s.containerName||s.containerId}`,"success"),typeof window.refreshAll=="function"&&window.refreshAll()}catch{}}),o.addEventListener("update-failed",i=>{try{const s=JSON.parse(i.data);typeof showNotification=="function"&&showNotification(`Update failed: ${s.containerName||s.containerId} \u2014 ${s.error||"unknown error"}`,"error")}catch{}}),o.addEventListener("incident",i=>{try{const s=JSON.parse(i.data);typeof showNotification=="function"&&(s.type==="created"?showNotification(`Incident: ${s.message||s.serviceId}`,"error"):s.type==="resolved"&&showNotification(`Resolved: ${s.serviceId||"incident"}`,"success"))}catch{}}),o.onerror=()=>{o.close(),console.warn(`[SSE] Disconnected, reconnecting in ${f/1e3}s...`),setTimeout(g,f),f=Math.min(f*2,u)}}g(),window._sseReconnect=g})(),(function(){const o=document.getElementById("service-filter-search"),f=document.getElementById("service-filter-status"),u=document.getElementById("service-filter-count");function g(){const s=o.value.toLowerCase().trim(),h=f.value,n=document.querySelectorAll("#cards .card");let w=0;if(n.forEach(m=>{const r=m.querySelector(".name")?.textContent?.toLowerCase()||"",l=m.dataset.app?.toLowerCase()||"",y=m.dataset.status||"off";(!s||r.includes(s)||l.includes(s))&&(h==="all"||y===h)?(m.style.display="",w++):m.style.display="none"}),u){const m=n.length;u.textContent=`${w} of ${m} services`}}function i(s,h){let n;return function(...w){clearTimeout(n),n=setTimeout(()=>s.apply(this,w),h)}}o?.addEventListener("input",i(g,200)),f?.addEventListener("change",g),document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>setTimeout(g,500)):setTimeout(g,500),window.refreshServiceFilter=g})(),(function(){const o=document.getElementById("batch-operations-btn"),f=document.getElementById("batch-action-bar"),u=document.getElementById("batch-selected-count"),g=document.getElementById("batch-start-btn"),i=document.getElementById("batch-stop-btn"),s=document.getElementById("batch-restart-btn"),h=document.getElementById("batch-cancel-btn");let n=!1,w=new Set;function m(){n=!0,w.clear(),f.style.display="",o.textContent="\u2713 Exit Batch Mode",l(),document.querySelectorAll("#cards .card[data-app]").forEach(a=>{const p=a.dataset.containerId;if(!p)return;const t=a.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=a.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?w.add(p):w.delete(p),l()}),a.style.position="relative",a.insertBefore(c,a.firstChild)})}function r(){n=!1,w.clear(),f.style.display="none",o.textContent="\u2630 Batch Operations",document.querySelectorAll(".batch-checkbox").forEach(e=>e.remove())}function l(){const e=w.size;u.textContent=`${e} selected`,g.disabled=e===0,i.disabled=e===0,s.disabled=e===0}async function y(e){if(w.size===0)return;const a=Array.from(w),p={start:"Starting",stop:"Stopping",restart:"Restarting"}[e];if(!confirm(`${p} ${a.length} container(s)? This cannot be undone.`))return;const t=[g,i,s];t.forEach(k=>{k.disabled=!0,k.textContent="..."});let c=0,v=0;const d=[];for(const k of a)try{const B=await fetch(`/api/v1/containers/${encodeURIComponent(k)}/${e}`,{method:"POST"});if(B.ok)c++;else{v++;const T=await B.json().catch(()=>({}));d.push(`${k}: ${T.error||B.statusText}`)}}catch(B){v++,d.push(`${k}: ${B.message}`)}t[0].textContent="\u25B6 Start All",t[1].textContent="\u2B1B Stop All",t[2].textContent="\u{1F504} Restart All",l(),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:",d)),setTimeout(()=>{typeof refreshAll=="function"&&refreshAll()},1500)}o?.addEventListener("click",()=>{n?r():m()}),g?.addEventListener("click",()=>y("start")),i?.addEventListener("click",()=>y("stop")),s?.addEventListener("click",()=>y("restart")),h?.addEventListener("click",r)})();