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

\u{1F4C2} Browse for Media Folders

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

Service Credentials

Credentials are injected automatically when accessing this service.

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

Authentication Settings

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

No DNS servers configured.

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

${m(f)}

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

DNS Settings

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

DNS Logs

Loading logs...
`);let o=null,m=null,l=!1,w=null,v=null,r=!1,h=null,n=null,b=!1,p=null,s=!1;async function c(x,y=25){try{const I=getDnsServerAddr(x),S=await fetch(`/api/v1/dns/logs?server=${I}&limit=${y}`,{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 g(x){return{NoError:"var(--ok-fg)",NOERROR:"var(--ok-fg)",NxDomain:"var(--muted)",NXDOMAIN:"var(--muted)",Refused:"var(--bad-fg)",REFUSED:"var(--bad-fg)",ServerFailure:"#f39c12",SERVFAIL:"#f39c12"}[x]||"var(--fg)"}function e(x){const y=document.createElement("div");if(y.className="log-entry",y.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 y.style.gridTemplateColumns="1fr",y.innerHTML=`${escapeHtml(x.raw)}`,y;const I=g(x.rcode),S=x.rcode==="Refused"||x.rcode==="REFUSED";return y.innerHTML=` ${escapeHtml(x.timestamp)} ${escapeHtml(x.client)} ${escapeHtml(x.domain)} ${escapeHtml(x.type)} ${escapeHtml(x.rcode)} `,y}async function a(){if(b){await L();return}if(r){await B();return}if(l||!o)return;const x=parseInt(document.getElementById("log-lines").value),y=document.getElementById("logs-content");try{const I=await c(o,x);if(I.error){y.innerHTML=`
\u26A0\uFE0F Error
${escapeHtml(I.error)}
`;return}y.innerHTML=`
Time Client Domain Type Status
`,I.logs&&I.logs.length>0?I.logs.forEach(S=>{const C=e(S);y.appendChild(C)}):y.innerHTML+=`
No DNS queries logged yet
`}catch(I){y.innerHTML=`
Failed to fetch logs: ${escapeHtml(I.message)}
`}}function u(x){o=x,l=!1,r=!1;const y=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"),y.classList.add("show"),a(),m=setInterval(a,DC.POLL.LOGS)}function t(){document.getElementById("logs-modal").classList.remove("show"),m&&(clearInterval(m),m=null),f(),o=null,r=!1,w=null,v=null,b=!1,h=null,n=null,l=!1}function d(x){p&&f();const y=document.getElementById("logs-stream"),I=document.getElementById("logs-pause"),S=document.getElementById("logs-content");m&&(clearInterval(m),m=null);try{p=new EventSource(`/api/v1/logs/stream/${x}`),s=!0,y.classList.add("active"),y.textContent="\u{1F534} Live",y.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}")),p.onmessage=P=>{try{const D=JSON.parse(P.data);if(D.error){console.error("Stream error:",D.error),f();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)}},p.onerror=P=>{console.error("EventSource error:",P),f()}}catch(C){console.error("Failed to start streaming:",C),f()}}function f(){p&&(p.close(),p=null),s=!1;const x=document.getElementById("logs-stream"),y=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"),y&&(y.style.display=""),I&&(I.textContent=I.textContent.replace(" \u{1F534}","")),r&&w&&!m&&(m=setInterval(B,DC.POLL.LOGS))}async function i(x,y=100){try{const I=`/api/v1/logs/container/${x}?tail=${y}×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 y=document.createElement("div");y.className="log-entry",y.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 y.innerHTML=`
${S}
${escapeHtml(x.text)}
`,y}async function B(){if(l||!w||!r)return;const x=parseInt(document.getElementById("log-lines").value),y=document.getElementById("logs-content");try{const I=await i(w,x);if(I.error){y.innerHTML=`
\u26A0\uFE0F Error
${escapeHtml(I.error)}
`;return}y.innerHTML=`
Stream Log Output
`,I.logs&&I.logs.length>0?(I.logs.forEach(S=>{const C=k(S);y.appendChild(C)}),y.scrollTop=y.scrollHeight):y.innerHTML+=`
No logs available for this container
`}catch(I){y.innerHTML=`
Failed to fetch logs: ${escapeHtml(I.message)}
`}}function T(x,y){w=x,v=y,r=!0,b=!1,l=!1,f();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} ${y} - Container Logs`,C.textContent="\u23F8\uFE0F Pause",C.classList.remove("paused"),P&&(P.style.display=""),I.classList.add("show"),B(),m=setInterval(B,DC.POLL.LOGS)}async function A(x,y=100){try{const I=`/api/v1/logs/file?path=${encodeURIComponent(x)}&tail=${y}`,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 y=document.createElement("div");y.className="log-entry",y.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 y.innerHTML=`
${D}
${escapeHtml(I)}
`,y}async function L(){if(l||!h||!b)return;const x=parseInt(document.getElementById("log-lines").value),y=document.getElementById("logs-content");try{const I=await A(h,x);if(I.error){y.innerHTML=`
\u26A0\uFE0F Error
${escapeHtml(I.error)}
`;return}y.innerHTML=`
Log Output (${I.count} of ${I.totalLines} lines)
`,I.logs&&I.logs.length>0?(I.logs.forEach(S=>{const C=E(S);y.appendChild(C)}),y.scrollTop=y.scrollHeight):y.innerHTML+=`
No logs available in this file
`}catch(I){y.innerHTML=`
Failed to fetch logs: ${escapeHtml(I.message)}
`}}function $(x,y){h=x,n=y,b=!0,r=!1,l=!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} ${y} - Application Logs`,C.textContent="\u23F8\uFE0F Pause",C.classList.remove("paused"),P&&(P.style.display="none"),I.classList.add("show"),L(),m=setInterval(L,DC.POLL.LOGS)}document.querySelector(".top")?.addEventListener("click",x=>{const y=x.target.closest('[id$="-logs"]');if(!y)return;const I=y.id.replace("-logs","");SITE.dnsServers[I]&&u(I)}),document.getElementById("logs-close")?.addEventListener("click",t),document.getElementById("logs-pause")?.addEventListener("click",()=>{l=!l;const x=document.getElementById("logs-pause");l?(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",()=>{l||a()}),document.getElementById("logs-stream")?.addEventListener("click",()=>{!r||!w||(s?f():d(w))}),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=u})(),(function(){injectModal("service-edit-modal",`

Edit Service

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

Delete Service

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

Add Service

Options
Checking Tailscale...

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