(function(a){"use strict";class y{constructor(){this.errors=[],this.maxErrors=50}logError(v,i,s={}){const m={timestamp:new Date().toISOString(),context:v,message:i instanceof Error?i.message:i,stack:i instanceof Error?i.stack:null,metadata:s};this.errors.push(m),this.errors.length>this.maxErrors&&this.errors.shift(),console.error(`[Onboarding Error] ${v}:`,i,s)}recoverFromError(v,i){switch(this.classifyError(v)){case"ELEMENT_NOT_FOUND":return this.logError("Element Not Found",v,{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",v),{action:"USE_MEMORY_STORAGE",message:"Local storage unavailable, using in-memory storage"};case"DRIVER_NOT_LOADED":return this.logError("Driver.js Not Loaded",v),{action:"ABORT_TOUR",message:"Driver.js library not loaded, cannot start tour"};case"INVALID_TOOLTIP":return this.logError("Invalid Tooltip Configuration",v,{currentStep:i}),{action:"SKIP_STEP",nextStep:i+1,message:"Invalid tooltip configuration, skipping"};case"THEME_DETECTION_FAILED":return this.logError("Theme Detection Failed",v),{action:"USE_DEFAULT_THEME",message:"Using default dark theme"};default:return this.logError("Unknown Error",v,{currentStep:i}),{action:"ABORT_TOUR",message:"Unexpected error occurred, aborting tour"}}}classifyError(v){const i=v.message||v.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 v={total:this.errors.length,byContext:{},byType:{},recent:this.errors.slice(-10)};return this.errors.forEach(i=>{v.byContext[i.context]=(v.byContext[i.context]||0)+1;const s=this.classifyError({message:i.message});v.byType[s]=(v.byType[s]||0)+1}),v}handleDriverLoadFailure(){this.logError("Driver.js Load Failure","Driver.js library failed to load");const v=document.createElement("div");return v.id="onboarding-fallback",v.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;
      `,v.innerHTML=`
        <strong>Welcome to DashCaddy!</strong><br>
        <p style="margin: 10px 0 0 0; font-size: 12px;">
          The interactive tour is unavailable, but you can explore the dashboard freely.
          Check the documentation for help getting started.
        </p>
      `,document.body.appendChild(v),setTimeout(()=>{v.parentNode&&v.parentNode.removeChild(v)},1e4),!0}handleStorageUnavailable(){this.logError("Storage Unavailable","Local storage is not available");const v={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"),v}sendToErrorTracking(v){}}a.ErrorHandler=y,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 v=await fetch("/api/v1/config");if(v.ok){const i=await v.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[m,t]of Object.entries(i.dnsServers))m!=="__proto__"&&m!=="constructor"&&m!=="prototype"&&(SITE.dnsServers[m]=t);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(v=>v.textContent=SITE.tld);const y=document.getElementById("edit-tld-suffix");y&&(y.textContent=SITE.tld);const p=document.getElementById("external-proxy-ip");p&&SITE.dnsIp&&(p.value=SITE.dnsIp,p.placeholder=SITE.dnsIp)})();function buildDomain(a){return a+SITE.tld}function buildServiceUrl(a){return SITE.routingMode==="subdirectory"&&SITE.domain?"https://"+SITE.domain+"/"+a:SITE.configurationType==="public"&&SITE.domain?"https://"+a+"."+SITE.domain:"https://"+buildDomain(a)}function getDnsServerAddr(a){const y=SITE.dnsServers[a];return y?`${y.ip}:${y.port}`:buildDomain(a)}function getPrimaryDnsId(){if(!SITE.dnsIp)return null;for(const[a,y]of Object.entries(SITE.dnsServers))if(y.ip===SITE.dnsIp)return a;return null}function renderDnsCards(){const a=document.querySelector(".top");if(!a)return;const y=Object.keys(SITE.dnsServers);if(!y.length)return;const p='<svg viewBox="0 0 24 24" class="service-icon"><rect x="3" y="4" width="18" height="16" rx="2" fill="#34495e"/><rect x="5" y="6" width="14" height="2" rx="1" fill="#3498db"/><rect x="5" y="9" width="10" height="1" fill="#ecf0f1"/><rect x="5" y="11" width="12" height="1" fill="#ecf0f1"/><rect x="5" y="13" width="8" height="1" fill="#ecf0f1"/><rect x="5" y="15" width="14" height="1" fill="#ecf0f1"/><circle cx="17" cy="11" r="2" fill="#e74c3c"/><path d="M17 9v4M15 11h4" stroke="white" stroke-width="1"/></svg>',v=a.firstElementChild;y.forEach(i=>{const s=escapeHtml(i),m=escapeHtml((SITE.dnsServers[i].name||i).toUpperCase()),t=document.createElement("div");t.className="card",t.setAttribute("data-app",i),t.setAttribute("data-status","off"),t.innerHTML=`<span id="${s}-dot" class="dot bad at-bl"></span><div class="row"><div class="logo-wrap">${p}</div><span class="name">${m}</span><span class="spacer"></span><span id="${s}-pill" class="badge off">OFF</span></div><div class="response-row"><span id="${s}-time" class="response-time">--</span></div><div class="health-row" id="health-${s}"><span id="uptime-${s}" class="uptime-chip">--</span><div class="uptime-mini-bar"><div class="fill" id="uptime-bar-${s}" style="width: 0%"></div></div></div><div class="btn-row"><button id="${s}-restart" class="restart-btn">Restart</button><button id="${s}-update" class="update-btn" title="Update DNS server">\u2B06\uFE0F</button><button id="${s}-open">Open</button><button id="${s}-logs" class="logs-btn">Logs</button><button id="${s}-settings" class="settings-btn">\u2699\uFE0F</button></div>`,a.insertBefore(t,v)})}window.renderDnsCards=renderDnsCards;let csrfToken=null;async function getCSRFToken(){if(csrfToken)return csrfToken;try{const a=await fetch("/api/v1/csrf-token");if(!a.ok)throw new Error("Failed to fetch CSRF token");return csrfToken=(await a.json()).token,csrfToken}catch(a){throw errorHandler.logError("[CSRF] Get Token",a,{function:"getCSRFToken"}),a}}async function secureFetch(a,y={}){const p=(y.method||"GET").toUpperCase(),v=!["GET","HEAD","OPTIONS"].includes(p);if(v)try{const s=await getCSRFToken();y.headers={...y.headers,"X-CSRF-Token":s}}catch(s){errorHandler.logError("[CSRF] Add to Request",s,{function:"secureFetch"})}y.signal||(y={...y,signal:AbortSignal.timeout(15e3)});const i=await fetch(a,y);if(v&&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 m=await getCSRFToken();return y.headers={...y.headers,"X-CSRF-Token":m},y.signal=AbortSignal.timeout(15e3),fetch(a,y)}}catch{}return i}async function postJSON(a,y){const p=await secureFetch(a,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(y)}),v=await p.json();if(!p.ok||v.success===!1)throw new Error(v.error||`Request failed (${p.status})`);return v}async function getJSON(a){const y=await secureFetch(a);if(!y.ok){let p=`Request failed (${y.status})`;try{p=(await y.json()).error||p}catch{}throw new Error(p)}return y.json()}async function deleteAPI(a){const y=await secureFetch(a,{method:"DELETE"}),p=await y.json();if(!y.ok||p.success===!1)throw new Error(p.error||`Delete failed (${y.status})`);return p}async function withButton(a,y,p,v={}){const i=a.innerHTML,{successText:s="\u2705",resetDelay:m=DC.DELAYS.BTN_RESET}=v;a.disabled=!0,a.innerHTML=y;try{const t=await p();return a.innerHTML=s,setTimeout(()=>{a.innerHTML=i,a.disabled=!1},m),t}catch(t){throw a.innerHTML=i,a.disabled=!1,t}}function openModal(a){document.getElementById(a)?.classList.add("show")}function closeModal(a){document.getElementById(a)?.classList.remove("show")}function wireModal(a,...y){a&&(a.addEventListener("click",p=>{p.target===a&&a.classList.remove("show")}),y.forEach(p=>{p&&typeof p.addEventListener=="function"&&p.addEventListener("click",()=>a.classList.remove("show"))}))}function showNotification(a,y="info",p=3e3){const v=document.querySelector(".deploy-notification");v&&v.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[y]||i.info,m=document.createElement("div");m.className="deploy-notification",m.textContent=a,m.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(m),p>0&&setTimeout(()=>m.remove(),p)}function timeAgo(a){const y=Date.now()-new Date(a).getTime();return y<6e4?"just now":y<36e5?Math.floor(y/6e4)+"m ago":y<864e5?Math.floor(y/36e5)+"h ago":Math.floor(y/864e5)+"d ago"}function safeGet(a,y=null){try{const p=localStorage.getItem(a);return p!==null?p:y}catch{return y}}function safeSet(a,y){try{localStorage.setItem(a,y)}catch{}}function safeRemove(a){try{localStorage.removeItem(a)}catch{}}function safeSessionGet(a,y=null){try{const p=sessionStorage.getItem(a);return p!==null?p:y}catch{return y}}function safeSessionSet(a,y){try{sessionStorage.setItem(a,y)}catch{}}function safeGetJSON(a,y=null){try{const p=localStorage.getItem(a);return p?JSON.parse(p):y}catch{return y}}function escapeHtml(a){return String(a??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function injectModal(a,y){document.getElementById(a)||document.body.insertAdjacentHTML("beforeend",y)}const DC_BUS={_handlers:{},on(a,y){var p;((p=this._handlers)[a]||(p[a]=[])).push(y)},off(a,y){this._handlers[a]=this._handlers[a]?.filter(p=>p!==y)},emit(a,y){this._handlers[a]?.forEach(p=>p(y))}},AppState={_apps:[],getApps(){return this._apps},setApps(a){this._apps=a,window.APPS=a,DC_BUS.emit("apps:changed",a)},findApp(a){return this._apps.find(y=>y.id===a)},addApp(a){this._apps.push(a),window.APPS=this._apps,DC_BUS.emit("apps:changed",this._apps)},removeApp(a){const y=this._apps.findIndex(p=>p.id===a);return y>-1&&(this._apps.splice(y,1),window.APPS=this._apps,DC_BUS.emit("apps:changed",this._apps)),y>-1},updateApp(a,y){const p=this._apps.find(v=>v.id===a);if(p){for(const[v,i]of Object.entries(y))v!=="__proto__"&&v!=="constructor"&&v!=="prototype"&&(p[v]=i);DC_BUS.emit("apps:changed",this._apps)}return p}};(function(){function a(){const v=document.createElement("div");return v.className="skeleton-card",v.innerHTML='<div style="display:flex;align-items:center;gap:12px;margin-bottom:12px"><div class="skeleton-bar" style="width:48px;height:48px;border-radius:8px;flex-shrink:0"></div><div style="flex:1"><div class="skeleton-bar" style="width:60%;height:14px;margin-bottom:6px"></div><div class="skeleton-bar" style="width:35%;height:10px"></div></div><div class="skeleton-bar" style="width:42px;height:22px;border-radius:11px"></div></div><div class="skeleton-bar" style="width:45%;height:12px;margin-bottom:10px"></div><div style="display:flex;gap:8px;margin-top:auto"><div class="skeleton-bar" style="width:64px;height:28px;border-radius:8px"></div><div class="skeleton-bar" style="width:64px;height:28px;border-radius:8px"></div></div>',v}function y(v){const i=document.getElementById("cards");if(!(!i||i.querySelector(".card"))){v=v||6;for(let s=0;s<v;s++){const m=a();i.appendChild(m),setTimeout(function(){m.classList.add("loaded")},s*60)}}}function p(){const v=document.getElementById("cards");if(v){var i=v.querySelectorAll(".skeleton-card");i.length&&(i.forEach(function(s,m){setTimeout(function(){s.style.opacity="0",s.style.transform="translateY(-10px)"},m*25)}),setTimeout(function(){i.forEach(function(s){s.parentNode&&s.remove()})},i.length*25+300))}}window.SkeletonLoader={show:y,hide:p}})(),(function(){var a="theme",y="user-themes",p="custom-theme",v=["dark","light","blue","black","nord","dracula","solarized-dark","solarized-light","taxi","ocean"],i=v.slice(),s=["bg","fg","muted","fg-muted","card-base","card-bg","border","hover","card-hover","base","ok-bg","ok-fg","bad-bg","bad-fg","dot-ok","dot-bad","uptime","success","error","warning","accent","accent-strong"],m=["bg","fg","muted","card-base","card-bg","border","ok-bg","ok-fg","bad-bg","bad-fg","dot-ok","dot-bad","uptime","accent","accent-strong"],t=["fg-muted","hover","card-hover","base","success","error","warning"],h={dark:{bg:"#0b0f1a",fg:"#e8ecf5",muted:"#9aa6bf","fg-muted":"#6b7a94","card-base":"#121826","card-bg":"#121826",border:"#263552",hover:"#1a2235","card-hover":"#161e2e",base:"#151c2b","ok-bg":"#0c2430","ok-fg":"#7ef2ff","bad-bg":"#2a121a","bad-fg":"#ff9aa3","dot-ok":"#35d1ff","dot-bad":"#ff5f7a",uptime:"#35d1ff",success:"#4caf50",error:"#e74c3c",warning:"#f39c12",accent:"#8FD6FF","accent-strong":"#1F7BFF"},light:{bg:"#f6f7fb",fg:"#0f1115",muted:"#5f6b7a","fg-muted":"#8993a4","card-base":"#ffffff","card-bg":"#ffffff",border:"#e2e7ef",hover:"#eef1f6","card-hover":"#f5f6fa",base:"#ebeef3","ok-bg":"#eafff1","ok-fg":"#0a7c3a","bad-bg":"#ffefef","bad-fg":"#b00020","dot-ok":"#0fb15a","dot-bad":"#d93b3b",uptime:"#0fb15a",success:"#0a7c3a",error:"#b00020",warning:"#d68a00",accent:"#4a90d9","accent-strong":"#2563eb",lightBg:!0},blue:{bg:"#1908AC",fg:"#e8f1ff",muted:"#d6e2ff","fg-muted":"#9eafdb","card-base":"#0d1533","card-bg":"#0d1533",border:"#1c2d6a",hover:"#141f4a","card-hover":"#111a3e",base:"#0f1840","ok-bg":"#162040","ok-fg":"#edffff","bad-bg":"#0a0e24","bad-fg":"#ffb3c0","dot-ok":"#c7e5ff","dot-bad":"#ffd6dc",uptime:"#7ec8ff",success:"#7ec8ff",error:"#ffb3c0",warning:"#ffd080",accent:"#9cd4ff","accent-strong":"#6fb2ff"},black:{bg:"#0e0e0e",fg:"#f5f5f5",muted:"#999999","fg-muted":"#666666","card-base":"#1a1a1a","card-bg":"#1a1a1a",border:"#2e2e2e",hover:"#242424","card-hover":"#202020",base:"#161616","ok-bg":"#0f2a12","ok-fg":"#66ff7a","bad-bg":"#2a0f0f","bad-fg":"#ff6b6b","dot-ok":"#4caf50","dot-bad":"#ff4444",uptime:"#e0e0e0",success:"#4caf50",error:"#ff4444",warning:"#ff9800",accent:"#E63946","accent-strong":"#C62828"},nord:{bg:"#2e3440",fg:"#eceff4",muted:"#81a1c1","fg-muted":"#6882a0","card-base":"#3b4252","card-bg":"#3b4252",border:"#4c566a",hover:"#434c5e","card-hover":"#3f4858",base:"#353c4a","ok-bg":"#2d4f3e","ok-fg":"#a3be8c","bad-bg":"#4a2c2a","bad-fg":"#bf616a","dot-ok":"#a3be8c","dot-bad":"#bf616a",uptime:"#a3be8c",success:"#a3be8c",error:"#bf616a",warning:"#ebcb8b",accent:"#88c0d0","accent-strong":"#5e81ac"},dracula:{bg:"#282a36",fg:"#f8f8f2",muted:"#6272a4","fg-muted":"#515d85","card-base":"#44475a","card-bg":"#44475a",border:"#6272a4",hover:"#4e5170","card-hover":"#494c63",base:"#363848","ok-bg":"#1e3a2e","ok-fg":"#50fa7b","bad-bg":"#3d1a1a","bad-fg":"#ff5555","dot-ok":"#50fa7b","dot-bad":"#ff5555",uptime:"#50fa7b",success:"#50fa7b",error:"#ff5555",warning:"#f1fa8c",accent:"#bd93f9","accent-strong":"#8be9fd"},"solarized-dark":{bg:"#002b36",fg:"#839496",muted:"#586e75","fg-muted":"#4a5f65","card-base":"#073642","card-bg":"#073642",border:"#586e75",hover:"#0d4050","card-hover":"#0a3a48",base:"#053340","ok-bg":"#0d3d2c","ok-fg":"#859900","bad-bg":"#3d1a1a","bad-fg":"#dc322f","dot-ok":"#859900","dot-bad":"#dc322f",uptime:"#b5bd68",success:"#859900",error:"#dc322f",warning:"#b58900",accent:"#268bd2","accent-strong":"#2aa198"},"solarized-light":{bg:"#fdf6e3",fg:"#657b83",muted:"#93a1a1","fg-muted":"#adb8b8","card-base":"#eee8d5","card-bg":"#eee8d5",border:"#93a1a1",hover:"#e6dfcb","card-hover":"#eae3cf",base:"#e8e1cd","ok-bg":"#e8f5e8","ok-fg":"#859900","bad-bg":"#fdf2f2","bad-fg":"#dc322f","dot-ok":"#859900","dot-bad":"#dc322f",uptime:"#859900",success:"#859900",error:"#dc322f",warning:"#b58900",accent:"#268bd2","accent-strong":"#2aa198",lightBg:!0},taxi:{bg:"#f3d321",fg:"#0e0e00",muted:"#4a4a10","fg-muted":"#6b6b30","card-base":"#ffd700","card-bg":"#ffd700",border:"#b8a840",hover:"#ffe84d","card-hover":"#ffe033",base:"#f0d000","ok-bg":"#d4ffd9","ok-fg":"#0f2a0f","bad-bg":"#ffd4d4","bad-fg":"#2a0f0f","dot-ok":"#4caf50","dot-bad":"#ff4444",uptime:"#0e0e00",success:"#2e7d32",error:"#c62828",warning:"#e65100",accent:"#7a4a00","accent-strong":"#5c3800",lightBg:!0},ocean:{bg:"#2060b0",fg:"#faf5eb",muted:"#dcd2c0","fg-muted":"#b0a890","card-base":"#7a94ed","card-bg":"#7a94ed",border:"#deb67a",hover:"#8aa0f0","card-hover":"#8298e8",base:"#6888e0","ok-bg":"#4f5bb0","ok-fg":"#c7d7eb","bad-bg":"#f41a3a","bad-fg":"#6a1818","dot-ok":"#30a050","dot-bad":"#d04040",uptime:"#2d32f2",success:"#30a050",error:"#d04040",warning:"#e6a030",accent:"#1860a0","accent-strong":"#104080"}};function c(C){return!C||typeof C!="string"?{r:0,g:0,b:0}:(C=C.replace("#",""),C.length===3&&(C=C[0]+C[0]+C[1]+C[1]+C[2]+C[2]),{r:parseInt(C.substr(0,2),16)||0,g:parseInt(C.substr(2,2),16)||0,b:parseInt(C.substr(4,2),16)||0})}function o(C,B,$){return"#"+[C,B,$].map(function(x){var w=Math.max(0,Math.min(255,Math.round(x))).toString(16);return w.length===1?"0"+w:w}).join("")}function l(C,B,$){var x=c(C),w=c(B);return o(x.r+(w.r-x.r)*$,x.g+(w.g-x.g)*$,x.b+(w.b-x.b)*$)}function g(C){C=C.replace("#",""),C.length===3&&(C=C[0]+C[0]+C[1]+C[1]+C[2]+C[2]);var B=parseInt(C.substr(0,2),16)/255,$=parseInt(C.substr(2,2),16)/255,x=parseInt(C.substr(4,2),16)/255;return B=B<=.03928?B/12.92:Math.pow((B+.055)/1.055,2.4),$=$<=.03928?$/12.92:Math.pow(($+.055)/1.055,2.4),x=x<=.03928?x/12.92:Math.pow((x+.055)/1.055,2.4),.2126*B+.7152*$+.0722*x}function e(C){var B=C.bg||"#0b0f1a",$=C.fg||"#e8ecf5",x=C.muted||"#9aa6bf",w=C["card-base"]||C.bg||"#121826",I=C["dot-ok"]||"#4caf50",k=C["dot-bad"]||"#e74c3c",S=C.lightBg||B&&g(B)>.4,A={};return A.hover=S?l(w,B,.35):l(w,$,.08),A["card-hover"]=l(w,A.hover,.5),A.base=l(B,w,.6),A["fg-muted"]=l(x,B,.35),A.success=I,A.error=k,A.warning=S?"#d68a00":"#f39c12",A}function r(C,B){var $=B.lightBg||B.bg&&g(B.bg)>.4,x=B.accent||B["accent-strong"]||"#888888",w=c(x);return $?":root."+C+` body {
  background:
    radial-gradient(1200px 800px at 10% -10%, rgba(`+w.r+","+w.g+","+w.b+`, .08), transparent 60%),
    radial-gradient(1000px 700px at 110% 10%, rgba(`+w.r+","+w.g+","+w.b+`, .05), transparent 55%),
    var(--bg);
}
`:":root."+C+` body {
  background:
    radial-gradient(1200px 900px at 8% -12%, rgba(`+w.r+","+w.g+","+w.b+`, .10), transparent 60%),
    radial-gradient(1000px 700px at 110% -10%, rgba(`+w.r+","+w.g+","+w.b+`, .07), transparent 55%),
    var(--bg);
}
`}function f(C,B){var $=B.lightBg||B.bg&&g(B.bg)>.4;return $?":root."+C+` button:hover {
  background: color-mix(in srgb, var(--accent-strong) 12%, white 88%);
  border-color: rgba(0, 0, 0, .15);
  box-shadow: 0 1px 6px rgba(0, 0, 0, .08), inset 0 1px 0 rgba(255, 255, 255, .8);
}
`:":root."+C+` button:hover {
  background: color-mix(in srgb, var(--accent) 18%, transparent);
  border-color: color-mix(in srgb, var(--accent) 35%, var(--border));
}
`}function n(){return window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}function u(){s.forEach(function(C){document.documentElement.style.removeProperty("--"+C)})}function b(C,B){var $=C.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"");$||($="custom"),v.indexOf($)!==-1&&($=$+"-custom");for(var x=safeGetJSON(y,{}),w=$,I=2;x[$]&&$!==B;)$=w+"-"+I++;return $}function d(C){var B=document.getElementById("user-theme-styles");B&&B.remove(),i.length=v.length,Object.keys(h).forEach(function(k){v.indexOf(k)===-1&&delete h[k]});var $=C||safeGetJSON(y,{}),x=Object.keys($);if(x=x.filter(function(k){return v.indexOf(k)===-1}),!!x.length){var w="";x.forEach(function(k){var S=$[k];i.indexOf(k)===-1&&i.push(k);var A={};s.forEach(function(D){S[D]&&(A[D]=S[D])}),A["card-bg"]=S["card-base"]||S.bg,S.lightBg&&(A.lightBg=!0);var O=e(A);t.forEach(function(D){!A[D]&&O[D]&&(A[D]=O[D])}),h[k]=A,w+=":root."+k+` {
`,s.forEach(function(D){A[D]&&(w+="  --"+D+": "+A[D]+`;
`)}),w+=`}
`,w+=r(k,A),w+=f(k,A)});var I=document.createElement("style");I.id="user-theme-styles",I.textContent=w,document.head.appendChild(I)}}function E(){secureFetch("/api/v1/themes").then(function(C){return C.json()}).then(function(C){if(!(!C.success||!C.themes)){var B=C.themes,$=safeGetJSON(y,{});if(JSON.stringify(B)!==JSON.stringify($)){safeSet(y,JSON.stringify(B)),d(B);var x=safeGet(a);x&&i.indexOf(x)!==-1&&L(x)}}}).catch(function(){})}function T(){var C=safeGetJSON(p);if(C){var B=C.name||"Custom",$=b(B),x={name:B};s.forEach(function(k){C[k]&&(x[k]=C[k])});var w=safeGetJSON(y,{});w[$]=x,safeSet(y,JSON.stringify(w)),safeGet(a)==="custom"&&safeSet(a,$),safeRemove(p);var I={};s.forEach(function(k){x[k]&&(I[k]=x[k])}),fetch("/api/v1/themes/"+$,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:B,colors:I})}).catch(function(){})}}function L(C){document.documentElement.classList.add("theme-transitioning"),i.forEach(function(w){w!=="dark"&&document.documentElement.classList.remove(w)}),u(),C!=="dark"&&document.documentElement.classList.add(C),safeSet(a,C);var B=h[C],$=document.querySelector('meta[name="theme-color"]');$&&B&&$.setAttribute("content",B.bg);var x=B&&B.lightBg;!x&&B&&B.bg&&(x=g(B.bg)>.4),x?document.documentElement.classList.add("light-bg"):document.documentElement.classList.remove("light-bg"),setTimeout(function(){document.documentElement.classList.remove("theme-transitioning")},300)}T(),d();var P=safeGet(a);P==="red"&&(P="black",safeSet(a,"black")),P&&P!=="dark"&&i.indexOf(P)===-1&&(P=null),L(P||n()),E(),window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change",function(C){safeGet(a)||L(C.matches?"dark":"light")}),window.THEMES=i,window.BUILTIN_THEMES=v,window.THEME_COLORS=h,window.THEME_PROPS=s,window.BASE_PROPS=m,window.DERIVED_PROPS=t,window.USER_THEMES_KEY=y,window.applyTheme=L,window.clearCustomProperties=u,window.injectUserThemeStyles=d,window.syncThemesFromServer=E,window.slugifyThemeName=b,window.getActiveTheme=function(){return safeGet(a)||n()},window.deriveExtendedColors=e,window.hexToRgb=c,window.rgbToHex=o,window.blendColors=l})(),(function(){function a(){const m=document.querySelector(".totp-card");if(!m)return;const h=getComputedStyle(m).backgroundColor.match(/\d+/g);if(!h)return;const c=(.299*+h[0]+.587*+h[1]+.114*+h[2])/255,o=m.querySelector(".totp-logo-dark"),l=m.querySelector(".totp-logo-light");o&&(o.style.display=c>.5?"none":""),l&&(l.style.display=c>.5?"":"none")}function y(){const m=document.getElementById("totp-overlay");if(m){m.classList.add("show"),setTimeout(a,50);const t=m.querySelector(".totp-digits input");t&&setTimeout(()=>t.focus(),100)}typeof window._refreshRecoveryLink=="function"&&window._refreshRecoveryLink()}function p(){const m=document.getElementById("totp-overlay");m&&m.classList.remove("show")}const v=document.getElementById("totp-digits");if(v){const m=v.querySelectorAll("input");m.forEach((t,h)=>{t.addEventListener("input",c=>{const o=c.target.value.replace(/\D/g,"");c.target.value=o.slice(0,1),o&&h<m.length-1&&m[h+1].focus();const l=Array.from(m).map(g=>g.value).join("");l.length===6&&i(l)}),t.addEventListener("keydown",c=>{c.key==="Backspace"&&!c.target.value&&h>0&&(m[h-1].focus(),m[h-1].value="")}),t.addEventListener("paste",c=>{c.preventDefault();const o=(c.clipboardData.getData("text")||"").replace(/\D/g,"");o.length>=6&&(m.forEach((l,g)=>{l.value=o[g]||""}),m[5].focus(),i(o.slice(0,6)))})})}async function i(m){const t=document.getElementById("totp-error");t.textContent="Verifying...",t.className="totp-error verifying";try{const c=await(await secureFetch("/api/v1/totp/verify",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:m})})).json();if(c.success){t.textContent="",c.csrfToken&&(csrfToken=c.csrfToken),p();const o=safeSessionGet("totp_redirect");if(o){try{sessionStorage.removeItem("totp_redirect")}catch{}window.location.href=o;return}typeof window.initializeDashboard=="function"&&window.initializeDashboard()}else{t.textContent=c.error||"Invalid code",t.className="totp-error";const o=document.querySelectorAll("#totp-digits input");o.forEach(l=>{l.value=""}),o[0]?.focus()}}catch{t.textContent="Connection error",t.className="totp-error"}}const s=new URLSearchParams(window.location.search);if(s.get("auth")==="required"){const m=s.get("return");if(m)try{const t=new URL(m,window.location.origin),h=t.hostname,c=t.origin===window.location.origin,o=SITE.tld.startsWith(".")?SITE.tld:"."+SITE.tld,l=h.endsWith(o)||h===o.substring(1);(c||l)&&safeSessionSet("totp_redirect",m)}catch{}window.history.replaceState({},"",window.location.pathname)}window._showTotpOverlay=y})(),(function(){"use strict";async function a(){try{return await(await fetch("/api/v1/totp/recovery-info",{cache:"no-store"})).json()}catch{return{success:!1,status:"unknown",hint:"Could not contact server"}}}function y(m){const t=document.getElementById("totp-recovery-link");t&&(t.style.display=m?"":"none")}function p(){const m=document.getElementById("totp-recovery-panel");m&&(m.style.display="");const t=document.getElementById("totp-recovery-status"),h=document.getElementById("totp-recovery-import"),c=document.getElementById("totp-recovery-verify");h&&(h.style.display=""),c&&(c.style.display="none"),document.getElementById("totp-recovery-error").textContent="",document.getElementById("totp-recovery-confirm-error").textContent="",document.getElementById("totp-recovery-secret").value="",document.getElementById("totp-recovery-code").value="",a().then(o=>{t.textContent=o.hint||"",o.status==="healthy"?t.style.borderColor="var(--ok-fg, #7ef2ff)":o.status==="unreadable"?(t.style.borderColor="var(--bad-fg, #ff9aa3)",t.style.background="color-mix(in srgb, var(--bad-fg) 6%, transparent)"):o.status==="not_configured"?t.style.borderColor="var(--muted)":t.style.borderColor="var(--border)"}),setTimeout(()=>{document.getElementById("totp-recovery-secret")?.focus()},100)}function v(){const m=document.getElementById("totp-recovery-panel");m&&(m.style.display="none")}async function i(){const m=document.getElementById("totp-recovery-secret").value.trim(),t=document.getElementById("totp-recovery-error");if(t.textContent="",!m){t.textContent="Paste your Base32 key first";return}if(!/^[A-Za-z2-7\s]+=*$/.test(m)){t.textContent="Invalid Base32 format \u2014 should be letters A-Z and digits 2-7 only";return}try{const h=await fetch("/api/v1/totp/setup",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({secret:m})}),c=await h.json();if(!h.ok||!c.success){t.textContent=c.error||c.message||"Restore failed";return}document.getElementById("totp-recovery-import").style.display="none",document.getElementById("totp-recovery-verify").style.display="",setTimeout(()=>document.getElementById("totp-recovery-code")?.focus(),100)}catch{t.textContent="Network error \u2014 try again"}}async function s(){const m=document.getElementById("totp-recovery-code").value.trim(),t=document.getElementById("totp-recovery-confirm-error");if(t.textContent="",!/^\d{6}$/.test(m)){t.textContent="Enter a 6-digit code";return}try{const h=await fetch("/api/v1/totp/verify-setup",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:m})}),c=await h.json();if(!h.ok||!c.success){t.textContent=c.error||c.message||"Invalid code",document.getElementById("totp-recovery-code").value="",document.getElementById("totp-recovery-code")?.focus();return}v();const o=document.getElementById("totp-overlay");o&&o.classList.remove("show"),typeof window.initializeDashboard=="function"&&window.initializeDashboard()}catch{t.textContent="Network error \u2014 try again"}}document.getElementById("totp-show-recovery")?.addEventListener("click",m=>{m.preventDefault(),p()}),document.getElementById("totp-recovery-close")?.addEventListener("click",v),document.getElementById("totp-recovery-submit")?.addEventListener("click",i),document.getElementById("totp-recovery-confirm")?.addEventListener("click",s),document.getElementById("totp-recovery-secret")?.addEventListener("keydown",m=>{m.key==="Enter"&&(m.preventDefault(),i())}),document.getElementById("totp-recovery-code")?.addEventListener("keydown",m=>{m.key==="Enter"&&(m.preventDefault(),s())}),window._refreshRecoveryLink=async function(){const m=await a();return m&&m.success&&m.status&&m.status!=="healthy"?y(!0):y(!1),m}})(),(function(){const a=new ErrorHandler;injectModal("folder-browser-modal",`<div id="folder-browser-modal" class="weather-modal">
    <div class="weather-modal-content" style="min-width: 500px; max-width: 700px; max-height: 80vh;">
      <h3>\u{1F4C2} Browse for Media Folders</h3>

      <div id="folder-browser-path" style="padding: 10px; background: var(--card-bg); border-radius: 6px; margin-bottom: 12px; font-family: monospace; font-size: 0.9rem; word-break: break-all;">
        /
      </div>

      <div id="folder-browser-list" style="max-height: 400px; overflow-y: auto; border: 1px solid var(--border); border-radius: 6px;">
        <div style="padding: 20px; text-align: center; color: var(--muted);">Loading...</div>
      </div>

      <div id="folder-browser-selected" style="margin-top: 12px; padding: 10px; background: color-mix(in srgb, var(--success) 10%, transparent); border: 1px solid var(--success); border-radius: 6px; display: none;">
        <div style="font-size: 0.85rem; color: var(--success); margin-bottom: 6px;">Selected folders:</div>
        <div id="folder-browser-selected-list" style="display: flex; flex-wrap: wrap; gap: 6px;"></div>
      </div>

      <div class="weather-modal-buttons" style="margin-top: 16px; display: flex; gap: 8px; justify-content: space-between;">
        <button id="folder-browser-select-current" class="btn-accent">
          + Add Current Folder
        </button>
        <div class="flex-row-gap">
          <button id="folder-browser-cancel">Cancel</button>
          <button id="folder-browser-done" style="background: color-mix(in srgb, var(--success) 20%, transparent); border-color: var(--success); color: var(--success);">Done</button>
        </div>
      </div>
    </div>
  </div>`),injectModal("service-creds-modal",`<div id="service-creds-modal">
    <div class="service-creds-content">
      <h3 id="svc-creds-title" style="margin: 0 0 4px; font-size: 1.05rem;">Service Credentials</h3>
      <p id="svc-creds-desc" style="font-size: 0.75rem; color: var(--muted); margin: 0 0 14px;">Credentials are injected automatically when accessing this service.</p>

      <!-- Status indicator -->
      <div style="display: flex; align-items: center; gap: 6px; margin-bottom: 12px;">
        <span id="svc-creds-dot" class="status-dot"></span>
        <span id="svc-creds-status" class="text-muted-sm">No credentials stored</span>
      </div>

      <!-- Seedhost credentials (shown for external services) -->
      <div id="svc-creds-seedhost" style="display: none; margin-bottom: 14px;">
        <label class="label-bold">Seedhost Login</label>
        <p class="hint-micro">Username shared across all services. Password is per-service.</p>
        <input type="text" id="svc-seedhost-user" placeholder="Username (shared)" autocomplete="username"
               style="width: 100%; padding: 8px 10px; margin-bottom: 6px; background: var(--bg); color: var(--fg); border: 1px solid var(--border); border-radius: 6px; font-size: 0.85rem; box-sizing: border-box;" />
        <input type="password" id="svc-seedhost-pass" placeholder="Password" autocomplete="current-password"
               class="input-creds" />
      </div>

      <!-- API Key (shown for arr services or services with API key support) -->
      <div id="svc-creds-apikey" style="display: none; margin-bottom: 14px;">
        <label class="label-bold">API Key</label>
        <p class="hint-micro">Bypasses the app's own login screen</p>
        <input type="text" id="svc-apikey-input" placeholder="API key"
               style="width: 100%; padding: 8px 10px; background: var(--bg); color: var(--fg); border: 1px solid var(--border); border-radius: 6px; font-size: 0.85rem; font-family: monospace; box-sizing: border-box;" />
      </div>

      <!-- Quality Profile (shown for radarr/sonarr only) -->
      <div id="svc-creds-quality" style="display: none; margin-bottom: 14px;">
        <label class="label-bold">Quality Profile</label>
        <p class="hint-micro">Used when requesting via Seerr</p>
        <div style="display: flex; gap: 8px; align-items: center;">
          <select id="svc-quality-select"
                  style="flex: 1; padding: 8px 10px; background: var(--bg); color: var(--fg); border: 1px solid var(--border); border-radius: 6px; font-size: 0.85rem; box-sizing: border-box;">
            <option value="">-- Enter API key first --</option>
          </select>
          <button id="svc-quality-fetch" type="button"
                  style="padding: 8px 12px; font-size: 0.75rem; cursor: pointer; white-space: nowrap;">
            Fetch
          </button>
        </div>
        <div id="svc-quality-status" style="font-size: 0.75rem; margin-top: 4px; min-height: 1em;"></div>
      </div>

      <!-- Per-service Basic Auth (shown for non-external services) -->
      <div id="svc-creds-basic" style="display: none; margin-bottom: 14px;">
        <label class="label-bold">Service Login</label>
        <input type="text" id="svc-basic-user" placeholder="Username" autocomplete="username"
               style="width: 100%; padding: 8px 10px; margin-top: 6px; margin-bottom: 6px; background: var(--bg); color: var(--fg); border: 1px solid var(--border); border-radius: 6px; font-size: 0.85rem; box-sizing: border-box;" />
        <input type="password" id="svc-basic-pass" placeholder="Password" autocomplete="current-password"
               class="input-creds" />
      </div>

      <!-- Error message -->
      <div id="svc-creds-error" style="display: none; padding: 8px 10px; margin-bottom: 10px; background: color-mix(in srgb, var(--error, #c62828) 12%, transparent); border: 1px solid var(--error, #c62828); border-radius: 6px; font-size: 0.8rem; color: var(--error, #c62828);"></div>

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

      <!-- Status Banner -->
      <div id="totp-status-banner" style="margin-bottom: 16px; padding: 12px 16px; border-radius: 8px; border: 1px solid var(--border); display: flex; align-items: center; gap: 8px;">
        <span id="totp-status-dot" class="status-dot"></span>
        <span id="totp-status-text" style="font-size: 0.9rem;">TOTP is not configured</span>
      </div>

      <!-- Setup Button (not configured state) -->
      <div id="totp-setup-section">
        <button id="totp-setup-btn" class="btn-accent-solid" style="width: 100%; padding: 12px; border: none; border-radius: 8px; cursor: pointer; font-weight: 600; font-size: 0.95rem;">
          Generate New Secret
        </button>
        <div style="display: flex; align-items: center; gap: 8px; margin: 10px 0 0;">
          <div class="divider-line"></div>
          <span class="text-tiny-muted">or</span>
          <div class="divider-line"></div>
        </div>
        <div style="margin-top: 10px;">
          <label class="text-hint">Import an existing secret key:</label>
          <div style="display: flex; gap: 8px; margin-top: 6px;">
            <input type="text" id="totp-import-key" placeholder="Paste your Base32 key" autocomplete="off" spellcheck="false"
                   style="flex: 1; padding: 10px; background: var(--bg); color: var(--fg); border: 1px solid var(--border); border-radius: 6px; font-size: 0.9rem; font-family: monospace; letter-spacing: 1px; text-transform: uppercase;" />
            <button id="totp-import-btn" style="padding: 10px 16px; background: var(--card-base); color: var(--fg); border: 1px solid var(--border); border-radius: 6px; cursor: pointer; font-weight: 600; font-size: 0.85rem; white-space: nowrap;">
              Import
            </button>
          </div>
          <div id="totp-import-error" style="color: var(--bad-fg, #ff9aa3); font-size: 0.8rem; min-height: 1.2em; margin-top: 6px;"></div>
        </div>
      </div>

      <!-- Secret Display (setup flow) -->
      <div id="totp-qr-section" style="display: none;">
        <!-- Manual Key (primary - for WinAuth/desktop authenticators) -->
        <p style="font-size: 0.85rem; color: var(--muted); margin: 0 0 8px;">Copy this key into your authenticator app:</p>
        <div style="display: flex; align-items: center; gap: 8px; margin-bottom: 8px;">
          <code id="totp-manual-key" style="flex: 1; display: block; padding: 12px; background: var(--bg, #0b0f1a); border: 1px solid var(--border); border-radius: 6px; font-size: 1rem; font-family: 'Sami Grotesk', monospace; letter-spacing: 2px; word-break: break-all; user-select: all; color: var(--fg);"></code>
          <button id="totp-copy-key" style="padding: 10px 14px; background: var(--card-base); border: 1px solid var(--border); border-radius: 6px; cursor: pointer; font-size: 1rem; white-space: nowrap; color: var(--fg);" title="Copy to clipboard">\u{1F4CB}</button>
        </div>

        <!-- Download backup file (recovery aid) -->
        <div style="margin-bottom: 16px; padding: 10px 12px; background: var(--bg, #0b0f1a); border: 1px solid var(--border); border-radius: 6px;">
          <div style="display: flex; align-items: center; gap: 8px;">
            <span style="font-size: 0.8rem; color: var(--muted); flex: 1;">
              <strong style="color: var(--fg);">Save a backup file</strong> \u2014 if you ever lose your authenticator,
              this is the only way to recover without SSH access to the server.
            </span>
            <button id="totp-download-backup" type="button"
                    style="padding: 8px 14px; background: var(--card-base); color: var(--fg); border: 1px solid var(--border); border-radius: 6px; cursor: pointer; font-weight: 600; font-size: 0.85rem; white-space: nowrap;">
              \u2B07 Download
            </button>
          </div>
        </div>

        <!-- QR Code (secondary - for mobile apps) -->
        <details class="mb-16">
          <summary style="cursor: pointer; color: var(--muted); font-size: 0.8rem;">Show QR code (for mobile authenticator apps)</summary>
          <div style="text-align: center; margin-top: 8px;">
            <img id="totp-qr-image" style="width: 180px; height: 180px; border-radius: 8px;" />
          </div>
        </details>

        <!-- Verify First Code -->
        <div style="border-top: 1px solid var(--border); padding-top: 16px;">
          <label class="font-bold-sm">Enter code to confirm setup:</label>
          <div style="display: flex; gap: 8px; margin-top: 8px;">
            <input type="text" id="totp-setup-code" maxlength="6" inputmode="numeric" pattern="[0-9]{6}" placeholder="000000"
                   style="flex: 1; text-align: center; font-size: 1.3rem; padding: 10px; font-family: 'Sami Grotesk', monospace; letter-spacing: 4px; background: var(--bg); color: var(--fg); border: 2px solid var(--border); border-radius: 8px; outline: none;" />
            <button id="totp-confirm-setup" class="btn-accent-solid" style="padding: 10px 20px; border: none; border-radius: 8px; cursor: pointer; font-weight: 600;">
              Confirm
            </button>
          </div>
          <div id="totp-setup-error" style="color: var(--bad-fg, #ff9aa3); font-size: 0.8rem; min-height: 1.2em; margin-top: 6px;"></div>
        </div>
      </div>

      <!-- Session Duration (active state) -->
      <div id="totp-duration-section" style="display: none; margin-top: 12px;">
        <label class="font-bold-sm">Session Duration:</label>
        <select id="totp-duration-select" style="width: 100%; padding: 10px; margin-top: 6px; background: var(--bg, #0b0f1a); color: var(--fg); border: 1px solid var(--border); border-radius: 8px; font-size: 0.9rem; cursor: pointer;">
          <option value="15m">15 minutes</option>
          <option value="30m">30 minutes</option>
          <option value="1h">1 hour</option>
          <option value="2h">2 hours</option>
          <option value="4h">4 hours</option>
          <option value="8h">8 hours</option>
          <option value="12h">12 hours</option>
          <option value="24h">24 hours</option>
          <option value="never">Never (disable TOTP)</option>
        </select>
        <p style="font-size: 0.75rem; color: var(--muted); margin: 4px 0 0;">How long before you need to re-enter your code</p>
      </div>

      <!-- Disable Button (active state) -->
      <div id="totp-disable-section" style="display: none; margin-top: 16px; padding-top: 16px; border-top: 1px solid var(--border);">
        <button id="totp-disable-btn" style="width: 100%; padding: 10px; background: transparent; color: var(--bad-fg, #ff9aa3); border: 1px solid var(--bad-fg, #ff9aa3); border-radius: 8px; cursor: pointer; font-size: 0.9rem;">
          Disable TOTP
        </button>
      </div>

      <!-- Close -->
      <div style="margin-top: 16px; text-align: right;">
        <button id="totp-modal-close" style="padding: 8px 20px; background: var(--card-base); color: var(--fg); border: 1px solid var(--border); border-radius: 8px; cursor: pointer;">
          Close
        </button>
      </div>
    </div>
  </div>`);async function y(){try{const s=await(await fetch("/api/v1/totp/config")).json();if(!s.success)return;const{enabled:m,sessionDuration:t,isSetUp:h}=s.config,c=document.getElementById("totp-status-dot"),o=document.getElementById("totp-status-text"),l=document.getElementById("totp-status-banner"),g=document.getElementById("totp-setup-section"),e=document.getElementById("totp-qr-section"),r=document.getElementById("totp-duration-section"),f=document.getElementById("totp-disable-section");if(m&&h){c.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)",o.textContent="TOTP is active",o.style.color="var(--ok-fg, #7ef2ff)",g.style.display="block";const n=document.getElementById("totp-setup-btn");n&&(n.textContent="Generate New Secret"),e.style.display="none",r.style.display="block",f.style.display="block",document.getElementById("totp-duration-select").value=t}else c.style.background="var(--muted)",l.style.borderColor="var(--border)",l.style.background="transparent",o.textContent="TOTP is not configured",o.style.color="var(--muted)",g.style.display="block",e.style.display="none",r.style.display="none",f.style.display="none";v(m&&h,t)}catch(i){console.warn("Failed to load TOTP settings:",i)}}const p={"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 v(i,s){const m=document.getElementById("auth-card"),t=document.getElementById("auth-pill"),h=document.getElementById("auth-dot"),c=document.getElementById("auth-status-text");m&&(i?(m.setAttribute("data-status","on"),t.className="badge on",t.textContent="YES",h.className="dot ok at-bl",c.textContent="Session: "+(p[s]||s)):(m.setAttribute("data-status","off"),t.className="badge off",t.textContent="NO",h.className="dot bad at-bl",c.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){a.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 t=await(await secureFetch("/api/v1/totp/setup",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({secret:i})})).json();t.success?(s.textContent="",document.getElementById("totp-qr-image").src=t.qrCode,document.getElementById("totp-manual-key").textContent=t.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=t.error||t.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-download-backup")?.addEventListener("click",()=>{const i=document.getElementById("totp-manual-key").textContent.trim();if(!i)return;const s={service:"DashCaddy",type:"totp-secret",secret:i,issuer:"DashCaddy",algorithm:"SHA1",digits:6,period:30,issued:new Date().toISOString(),recovery_url:`${window.location.origin}/  (login screen \u2192 "Lost access?")`,note:'Keep this file somewhere safe. Anyone with this secret can generate your login codes. Use it ONLY to recover TOTP access via the "Lost access?" link on the DashCaddy login screen.'},m=new Blob([JSON.stringify(s,null,2)],{type:"application/json"}),t=URL.createObjectURL(m),h=document.createElement("a");h.href=t,h.download=`dashcaddy-totp-backup-${new Date().toISOString().slice(0,10)}.json`,document.body.appendChild(h),h.click(),document.body.removeChild(h),URL.revokeObjectURL(t);const c=document.getElementById("totp-download-backup");c.textContent="\u2705 Saved",setTimeout(()=>{c.textContent="\u2B07 Download"},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 t=await(await secureFetch("/api/v1/totp/verify-setup",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:i})})).json();t.success?(s.textContent="",y()):s.textContent=t.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})}),y()}catch(s){a.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&&y()}catch(i){a.logError("[TOTP] Disable Failed",i,{function:"disableTOTP"})}}),document.getElementById("auth-settings-btn")?.addEventListener("click",()=>{y(),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=v,(async()=>{try{const s=await(await fetch("/api/v1/totp/config")).json();if(s.success){const m=s.config.enabled&&s.config.isSetUp;v(m,s.config.sessionDuration)}}catch(i){a.logError("[TOTP] AuthCard Update",i,{function:"authCardUpdate"})}})()})(),(function(){injectModal("token-management-modal",`
  <div id="token-management-modal" class="weather-modal">
    <div class="weather-modal-content" style="min-width: 500px; max-width: 600px;">
      <h3>\u{1F511} DNS Credentials</h3>

      <p style="font-size: 0.85rem; color: var(--muted); margin: 0 0 16px;">
        Enter Technitium DNS login credentials. Read-only accounts are used for logs; admin accounts for restarts, records, and updates.
      </p>

      <div id="dns-cred-sections"></div>

      <div class="weather-modal-buttons modal-footer-bar">
        <button id="token-clear-all" style="margin-right: auto; background: color-mix(in srgb, var(--bad-fg) 15%, transparent); border-color: var(--bad-fg); color: var(--bad-fg);">Clear All</button>
        <button id="token-cancel">Cancel</button>
        <button id="token-save" class="btn-accent">Save</button>
      </div>
    </div>
  </div>
  `);function a(){return Object.keys(SITE.dnsServers||{})}function y(n){return(SITE.dnsServers||{})[n]?.name||n.toUpperCase()}function p(){const n=document.getElementById("dns-cred-sections");if(!n)return;n.innerHTML="";const u=a();if(u.length===0){n.innerHTML='<p style="color: var(--muted); text-align: center; padding: 20px;">No DNS servers configured.</p>';return}for(const b of u)n.insertAdjacentHTML("beforeend",`
      <div class="token-section">
        <h4 class="token-section-title">${y(b)}</h4>
        <div class="token-grid">
          <div class="token-field">
            <label for="${b}-readonly-username">\u{1F4D6} Read-Only (Logs):</label>
            <input type="text" id="${b}-readonly-username" placeholder="Username" autocomplete="off" style="margin-bottom: 4px;" />
            <div class="token-input-row">
              <input type="password" id="${b}-readonly-token" placeholder="Password" autocomplete="off" />
              <button type="button" class="token-toggle" data-target="${b}-readonly-token">\u{1F441}</button>
            </div>
          </div>
          <div class="token-field">
            <label for="${b}-admin-username">\u{1F527} Admin:</label>
            <input type="text" id="${b}-admin-username" placeholder="Username" autocomplete="off" style="margin-bottom: 4px;" />
            <div class="token-input-row">
              <input type="password" id="${b}-admin-token" placeholder="Password" autocomplete="off" />
              <button type="button" class="token-toggle" data-target="${b}-admin-token">\u{1F441}</button>
            </div>
          </div>
        </div>
        <div class="token-status" id="${b}-token-status"></div>
      </div>
      `)}function v(){let n=safeSessionGet("dashcaddy-encryption-key");if(n)return n;const u=safeGet("dashcaddy-encryption-key");if(u)return safeSessionSet("dashcaddy-encryption-key",u),safeRemove("dashcaddy-encryption-key"),u;const b=new Uint8Array(32);return crypto.getRandomValues(b),n=Array.from(b,d=>d.toString(16).padStart(2,"0")).join(""),safeSessionSet("dashcaddy-encryption-key",n),n}const i=v();function s(n,u){if(!n)return"";const b=crypto.getRandomValues(new Uint8Array(8)),d=Array.from(b,L=>L.toString(16).padStart(2,"0")).join(""),E=new TextEncoder().encode(u+d);let T="";for(let L=0;L<n.length;L++){const P=n.charCodeAt(L)^E[L%E.length]^b[L%b.length]^L*31+17&255;T+=String.fromCharCode(P)}return d+":"+btoa(T)}function m(n,u){if(!n)return"";try{if(n.indexOf(":")===16){const T=n.substring(0,16),L=new Uint8Array(T.match(/.{2}/g).map($=>parseInt($,16))),P=atob(n.substring(17)),C=new TextEncoder().encode(u+T);let B="";for(let $=0;$<P.length;$++){const x=P.charCodeAt($)^C[$%C.length]^L[$%L.length]^$*31+17&255;B+=String.fromCharCode(x)}return B}const d=atob(n);let E="";for(let T=0;T<d.length;T++){const L=d.charCodeAt(T)^u.charCodeAt(T%u.length);E+=String.fromCharCode(L)}return E}catch{return""}}function t(n,u,b){const d=safeGet(`${n}-${u}-${b}-enc`);return m(d,i)}function h(n,u,b,d){const E=`${n}-${u}-${b}-enc`;d?safeSet(E,s(d,i)):safeRemove(E)}function c(n,u){return t(n,u,"token")}function o(n,u){return t(n,u,"username")}function l(n,u,b){h(n,u,"token",b)}function g(n,u,b){h(n,u,"username",b)}function e(){const n={};for(const u of a())n[u]={readonly:{username:o(u,"readonly"),token:c(u,"readonly")},admin:{username:o(u,"admin"),token:c(u,"admin")}};return n}function r(){a().forEach(n=>{["readonly","admin"].forEach(u=>{["token","username"].forEach(b=>{safeRemove(`${n}-${u}-${b}-enc`)})}),safeRemove(`${n}-token-enc`),safeRemove(`${n}-username-enc`)})}function f(n){const u=c(n,"readonly"),b=o(n,"readonly"),d=c(n,"admin"),E=o(n,"admin"),T=m(safeGet(`${n}-token-enc`),i),L=m(safeGet(`${n}-username-enc`),i);return{username:E||b||L,token:d||u||T,readonlyToken:u||T,readonlyUsername:b||L,adminToken:d||T,adminUsername:E||L}}document.getElementById("manage-tokens")?.addEventListener("click",()=>{p();const n=document.getElementById("token-management-modal"),u=e();a().forEach(b=>{const d=u[b];document.getElementById(`${b}-readonly-username`).value=d.readonly.username,document.getElementById(`${b}-readonly-token`).value=d.readonly.token,document.getElementById(`${b}-admin-username`).value=d.admin.username,document.getElementById(`${b}-admin-token`).value=d.admin.token,document.getElementById(`${b}-token-status`).textContent=""}),n.classList.add("show")}),document.getElementById("token-management-modal")?.addEventListener("click",n=>{const u=n.target.closest(".token-toggle");if(u){const b=u.dataset.target,d=document.getElementById(b);d.type==="password"?(d.type="text",u.textContent="\u{1F648}"):(d.type="password",u.textContent="\u{1F441}");return}n.target.id==="token-management-modal"&&n.target.classList.remove("show")}),document.getElementById("token-save")?.addEventListener("click",async()=>{const n=a();n.forEach(d=>{g(d,"readonly",document.getElementById(`${d}-readonly-username`).value.trim()),l(d,"readonly",document.getElementById(`${d}-readonly-token`).value.trim()),g(d,"admin",document.getElementById(`${d}-admin-username`).value.trim()),l(d,"admin",document.getElementById(`${d}-admin-token`).value.trim())});const u={};let b=!1;if(n.forEach(d=>{const E={},T=document.getElementById(`${d}-readonly-username`).value.trim(),L=document.getElementById(`${d}-readonly-token`).value.trim(),P=document.getElementById(`${d}-admin-username`).value.trim(),C=document.getElementById(`${d}-admin-token`).value.trim();T&&L&&(E.readonly={username:T,password:L},b=!0),P&&C&&(E.admin={username:P,password:C},b=!0),Object.keys(E).length>0&&(u[d]=E)}),b){n.forEach(d=>{u[d]&&(document.getElementById(`${d}-token-status`).textContent="Verifying...",document.getElementById(`${d}-token-status`).className="token-status")});try{const E=await(await secureFetch("/api/v1/dns/credentials",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({servers:u})})).json();E.results?n.forEach(T=>{const L=document.getElementById(`${T}-token-status`);if(!u[T]){L.textContent="";return}const P=E.results[T];P?.success?(L.textContent="\u2713 Verified & saved",L.className="token-status success"):P?.partial?(L.textContent="\u2713 "+P.partial,L.className="token-status success"):(L.textContent="\u2717 "+(P?.error||"Login failed"),L.className="token-status error")}):E.success?n.forEach(T=>{u[T]&&(document.getElementById(`${T}-token-status`).textContent="\u2713 Saved",document.getElementById(`${T}-token-status`).className="token-status success")}):n.forEach(T=>{u[T]&&(document.getElementById(`${T}-token-status`).textContent="\u2717 "+(E.error||"Failed"),document.getElementById(`${T}-token-status`).className="token-status error")})}catch(d){console.error("Failed to sync DNS credentials to backend:",d),n.forEach(E=>{u[E]&&(document.getElementById(`${E}-token-status`).textContent="\u2713 Saved locally (sync failed)",document.getElementById(`${E}-token-status`).className="token-status")})}}else n.forEach(d=>{document.getElementById(`${d}-token-status`).textContent=""});setTimeout(()=>{n.every(E=>{const T=document.getElementById(`${E}-token-status`)?.textContent;return!T||T.includes("\u2713")})&&closeModal("token-management-modal")},1500)}),document.getElementById("token-cancel")?.addEventListener("click",()=>{closeModal("token-management-modal")}),document.getElementById("token-clear-all")?.addEventListener("click",async()=>{if(confirm("Clear all stored DNS credentials? This cannot be undone.")){r(),a().forEach(n=>{document.getElementById(`${n}-readonly-username`).value="",document.getElementById(`${n}-readonly-token`).value="",document.getElementById(`${n}-admin-username`).value="",document.getElementById(`${n}-admin-token`).value="",document.getElementById(`${n}-token-status`).textContent="\u2713 Cleared",document.getElementById(`${n}-token-status`).className="token-status success"});try{await secureFetch("/api/v1/dns/credentials",{method:"DELETE"})}catch{}}}),window.getToken=c,window.getUsername=o,window.setToken=l,window.setUsername=g,window.getAllCredentials=e,window.getCredential=t,window.setCredential=h,window.getEncryptionKey=v,window.getDnsIds=a,window.getDnsDisplayName=y})(),(function(){function a(l,g,e=null){const r=document.getElementById(l+"-dot"),f=document.getElementById(l+"-pill"),n=document.getElementById(l+"-time"),u=document.querySelector(`[data-app="${l}"]`);r&&(r.classList.toggle("ok",g),r.classList.toggle("bad",!g)),f&&(f.textContent=g?"ON":"OFF",f.classList.toggle("on",g),f.classList.toggle("off",!g)),n&&e!==null&&(n.textContent=g?`${e}ms`:"timeout",n.className=`response-time ${y(e,g)}`),u&&u.setAttribute("data-status",g?"on":"off")}function y(l,g){return g?l<200?"excellent":l<500?"good":l<1e3?"fair":"slow":"timeout"}async function p(l){const g=performance.now();try{const e=await fetch("/probe/"+l,{cache:"no-store"}),r=performance.now(),f=Math.round(r-g);return{isUp:e.status>=200&&e.status<400||e.status===401||e.status===403,responseTime:f}}catch{const e=performance.now();return{isUp:!1,responseTime:Math.round(e-g)}}}window.APPS=[];let v=null,i=!1;async function s(){try{window.SkeletonLoader&&window.SkeletonLoader.show(6);const l=await fetch("/api/v1/services",{cache:"no-store"});if(l.ok){const g=await l.json();window.APPS=g.services||[],window.SkeletonLoader&&window.SkeletonLoader.hide()}else 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 m(l){const g=window.APPS?.find(r=>r.id===l);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?.[l];return e?"http://"+e.ip+":"+(e.port||5380):buildServiceUrl(l)}function t(l,g,e){const r=document.createElement(l);return g&&(r.className=g),e&&(r.textContent=e),r}function h(){const l=document.getElementById("cards");l.innerHTML="";for(let g=0;g<window.APPS.length;g++){const e=window.APPS[g];if(e.id==="ca")continue;const r=t("div","card");r.setAttribute("data-app",e.id),r.setAttribute("data-status","off"),e.containerId&&r.setAttribute("data-container-id",e.containerId),e.category&&r.setAttribute("data-category",e.category),e.recipeId&&r.setAttribute("data-recipe-id",e.recipeId);const f=t("span","dot bad at-bl");f.id="dot-"+e.id+"-grid",r.appendChild(f);const n=t("div","row"),u=t("div","logo-wrap"),b=document.createElement("img");b.src=e.logo,b.alt=e.name,b.className="logo-img",b.onerror=function(){let k=e.id||e.appTemplate;if(!k&&e.name&&(k=e.name.toLowerCase().replace(/\s+/g,"-")),k){const S=[`https://cdn.jsdelivr.net/gh/walkxcode/dashboard-icons/png/${k}.png`,`https://cdn.jsdelivr.net/gh/walkxcode/dashboard-icons/png/${k.toLowerCase()}.png`,`https://cdn.jsdelivr.net/gh/walkxcode/dashboard-icons/png/${k.replace(/-/g,"")}.png`,`https://cdn.jsdelivr.net/gh/walkxcode/dashboard-icons/png/${e.name.toLowerCase().replace(/\s+/g,"-")}.png`],A=[...new Set(S)],D=A.indexOf(this.src)+1;D<A.length?this.src=A[D]:this.style.display="none"}else this.style.display="none"},u.appendChild(b),n.appendChild(u);const d=t("span","name",e.name);if(n.appendChild(d),e.tailscaleOnly){const k=t("span","ts-badge","\u{1F510}");k.title="Tailscale-only access",k.style.cssText="margin-left: 6px; font-size: 0.75rem; opacity: 0.8;",d.appendChild(k)}if(e.category){const S=(typeof DC<"u"&&DC.CATEGORIES||window.DC_CATEGORIES||{})[e.category]||{},A=t("span","cat-badge",`${S.icon||""} ${e.category}`.trim());A.title=`Category: ${e.category}`,A.style.cssText=`margin-left: 6px; font-size: 0.65rem; padding: 1px 6px; border-radius: 999px; background: color-mix(in srgb, ${S.color||"#7f8c8d"} 25%, transparent); color: ${S.color||"#7f8c8d"}; border: 1px solid color-mix(in srgb, ${S.color||"#7f8c8d"} 50%, transparent); white-space: nowrap; font-weight: 500;`,d.appendChild(A)}n.appendChild(t("span","spacer"));const E=t("span","badge off","OFF");E.id="badge-"+e.id,n.appendChild(E);const T=t("span","update-available-badge","UPDATE");T.id="update-badge-"+e.id,T.title="Update available",n.appendChild(T),r.appendChild(n);const L=t("div","response-row"),P=t("span","response-time","--");P.id="time-"+e.id,L.appendChild(P),r.appendChild(L);const C=t("div","health-row");C.id="health-"+e.id;const B=t("span","uptime-chip","--");B.id="uptime-"+e.id,C.appendChild(B);const $=document.createElement("div");$.className="uptime-mini-bar";const x=document.createElement("div");x.className="fill",x.id="uptime-bar-"+e.id,x.style.width="0%",$.appendChild(x),C.appendChild($),r.appendChild(C);const w=t("div","btn-row");if(e.containerId){const k=t("button","logs-btn","\u{1F4CB}");k.title="View container logs",k.onclick=O=>{O.stopPropagation(),window.openContainerLogsModal(e.containerId,e.name)},w.appendChild(k);const S=t("button","update-btn","\u2B06\uFE0F");S.title="Update container to latest version",S.id=`update-btn-${e.id}`,S.onclick=O=>{O.stopPropagation(),window.updateContainer(e.containerId,e.name,e.id)},w.appendChild(S);const A=t("button","exec-btn",">_");A.title="Open terminal",A.onclick=O=>{O.stopPropagation(),window.openExecModal&&window.openExecModal(e.containerId,e.name)},w.appendChild(A)}if(e.logPath&&!e.containerId){const k=t("button","logs-btn","\u{1F4CB}");k.title="View application logs",k.onclick=S=>{S.stopPropagation(),window.openFileLogsModal(e.logPath,e.name)},w.appendChild(k)}if(e.isExternal||e.appTemplate||e.url){const k=t("button","creds-btn","\u{1F511}");k.title="Auto-login credentials",k.id=`creds-btn-${e.id}`,k.onclick=S=>{S.stopPropagation(),window.openServiceCredsModal(e)},w.appendChild(k)}if(e.id!=="internet"){const k=t("button","options-btn","\u2699\uFE0F");k.title="Edit service settings",k.onclick=S=>{S.stopPropagation(),window.openServiceEditModal(e)},w.appendChild(k)}if(e.id!=="internet"){const k=t("button","delete-btn","\u{1F5D1}\uFE0F");k.title="Delete this service",k.onclick=S=>{S.stopPropagation(),window.deleteService(e.id,e.name)},w.appendChild(k)}const I=t("button",null,"Open");I.onclick=()=>window.open(m(e.id),"_blank","noopener"),w.appendChild(I),r.appendChild(w),r.style.transitionDelay=`${Math.min(g*45,270)}ms`,l.appendChild(r)}requestAnimationFrame(()=>{l.querySelectorAll(".card").forEach(g=>g.classList.add("loaded"))}),window.groupRecipeCards&&requestAnimationFrame(()=>window.groupRecipeCards()),window.refreshServiceFilter&&window.refreshServiceFilter()}function c(l,g,e=null){const r=document.getElementById("dot-"+l+"-grid"),f=document.getElementById("badge-"+l),n=document.getElementById("time-"+l),u=document.querySelector(`[data-app="${l}"]`);r&&(r.classList.toggle("ok",g),r.classList.toggle("bad",!g)),f&&(f.textContent=g?"ON":"OFF",f.classList.toggle("on",g),f.classList.toggle("off",!g)),n&&e!==null&&(n.textContent=g?`${e}ms`:"timeout",n.className=`response-time ${y(e,g)}`),u&&u.setAttribute("data-status",g?"on":"off")}async function o(){if(v)return i=!0,v;function l(r,f=new Date){const n=document.getElementById("stamp");n&&(n.textContent=`${r}: ${new Date(f).toLocaleTimeString()}`)}function g(r){Object.keys(SITE.dnsServers).forEach(n=>{const u=r[n];u&&a(n,u.isUp,u.responseTime)}),r.internet&&a("internet",r.internet.isUp,r.internet.responseTime),window.APPS.forEach(n=>{const u=r[n.id];u&&c(n.id,u.isUp,u.responseTime)})}async function e(){const r=Object.keys(SITE.dnsServers),f=r.map(d=>p(d));f.push(p("internet"));const n=await Promise.all(f);r.forEach((d,E)=>a(d,n[E].isUp,n[E].responseTime));const u=n[n.length-1];a("internet",u.isUp,u.responseTime),(await Promise.all(window.APPS.map(async d=>{const E=await p(d.id);return{id:d.id,...E}}))).forEach(d=>{c(d.id,d.isUp,d.responseTime)})}return v=(async()=>{try{const r=await fetch("/api/v1/services/status",{cache:"no-store"});if(!r.ok)throw new Error(`Status refresh failed (${r.status})`);const f=await r.json();g(f.statuses||{}),l("last check",f.checkedAt||new Date)}catch(r){console.warn("Batched status refresh failed, falling back to direct probes:",r);try{await e(),l("last check")}catch(f){console.error("Dashboard refresh failed:",f),l("last failed")}}finally{v=null,i&&(i=!1,setTimeout(()=>{window.refreshAll()},0))}})(),v}document.querySelector(".top")?.addEventListener("click",l=>{const g=l.target.closest('[id$="-open"]');if(!g)return;const e=g.id.replace("-open","");SITE.dnsServers[e]&&window.open(m(e),"_blank","noopener")}),document.getElementById("ca-open")?.addEventListener("click",()=>window.open(m("ca"),"_blank","noopener")),document.getElementById("creds-btn-ca")?.addEventListener("click",l=>{l.stopPropagation();const g=window.APPS.find(e=>e.id==="ca");g&&window.openServiceCredsModal&&window.openServiceCredsModal(g)}),document.getElementById("options-btn-ca")?.addEventListener("click",l=>{l.stopPropagation();const g=window.APPS.find(e=>e.id==="ca");g&&window.openServiceEditModal&&window.openServiceEditModal(g)}),document.getElementById("delete-btn-ca")?.addEventListener("click",l=>{l.stopPropagation(),window.deleteService&&window.deleteService("ca","DashCA")}),window.loadServices=s,window.buildGrid=h,window.refreshAll=o,window.setQuick=a,window.setBadge=c,window.getResponseTimeClass=y,window.checkServiceWithTiming=p,window.serviceUrl=m,window.el=t})(),(function(){async function a(t){const c=await(await secureFetch(`/api/v1/dns/restart/${t}`,{method:"POST"})).json();if(!c.success)throw new Error(c.error||"Restart failed");return c}document.querySelector(".top")?.addEventListener("click",async t=>{const h=t.target.closest('[id$="-restart"]');if(!h)return;const c=h.id.replace("-restart","");if(SITE.dnsServers[c]&&confirm(`Restart ${c.toUpperCase()} service?`))try{await withButton(h,"...",()=>a(c)),setTimeout(window.refreshAll,DC.DELAYS.RELOAD)}catch(o){showNotification("Restart failed: "+o.message,"error")}});async function y(t,h){const c=document.getElementById(`${t}-update`),o=c?.textContent||"\u2B06\uFE0F";try{c.textContent="\u{1F50D}",c.disabled=!0,c.title="Checking for updates...";const g=await(await fetch(`/api/v1/dns/check-update?server=${encodeURIComponent(h)}`)).json();if(!g.success)throw new Error(g.error||"Failed to check for updates");if(!g.updateAvailable){c.textContent="\u2705",c.title=`Already on latest version (${g.currentVersion})`,showNotification(`${t.toUpperCase()} is already up to date! Current version: ${g.currentVersion}`,"info"),setTimeout(()=>{c.textContent=o,c.disabled=!1,c.title="Update DNS server"},3e3);return}if(!confirm(`Update available for ${t.toUpperCase()}!

Current: ${g.currentVersion}
New: ${g.updateVersion}

`+(g.updateTitle?`${g.updateTitle}

`:"")+`The DNS server will restart during the update.
Proceed?`)){c.textContent=o,c.disabled=!1,c.title="Update DNS server";return}c.textContent="\u{1F504}",c.title="Updating...";const f=await(await secureFetch(`/api/v1/dns/update?server=${encodeURIComponent(h)}`,{method:"POST"})).json();if(!f.success)throw new Error(f.error||"Update failed");if(f.manualUpdateRequired){c.textContent="\u2B06\uFE0F",c.title=`Update available: ${f.newVersion}`;const n=f.downloadLink?`
Download: ${f.downloadLink}`:"",u=f.instructionsLink?`
Instructions: ${f.instructionsLink}`:"";showNotification(`${t.toUpperCase()} update requires manual installation. Current: ${f.previousVersion} \u2192 ${f.newVersion}. Please update manually on the host machine.`,"warning",8e3),c.disabled=!1;return}c.textContent="\u2705",c.title="Updated successfully!",showNotification(`${t.toUpperCase()} updated successfully! ${f.previousVersion} \u2192 ${f.newVersion}. Server is restarting...`,"success"),setTimeout(()=>{c.textContent=o,c.disabled=!1,c.title="Update DNS server",window.refreshAll()},1e4)}catch(l){console.error("DNS update error:",l),c.textContent="\u274C",c.title="Update failed",showNotification(`Failed to update ${t.toUpperCase()}: ${l.message}`,"error"),setTimeout(()=>{c.textContent=o,c.disabled=!1,c.title="Update DNS server"},3e3)}}document.querySelector(".top")?.addEventListener("click",t=>{const h=t.target.closest('[id$="-update"]');if(!h)return;const c=h.id.replace("-update","");SITE.dnsServers[c]&&y(c,SITE.dnsServers[c]?.ip)}),injectModal("dns-settings-modal",`
  <div id="dns-settings-modal" class="weather-modal">
    <div class="weather-modal-content" style="min-width: 420px; max-width: 520px;">
      <h3 id="dns-settings-title">DNS Settings</h3>

      <div style="display: grid; gap: 16px; margin-top: 16px;">
        <div>
          <label for="dns-edit-ip" class="form-label-accent-sm">Server IP</label>
          <input type="text" id="dns-edit-ip" class="form-input-md" placeholder="192.168.1.1" />
        </div>
        <div>
          <label for="dns-edit-port" class="form-label-accent-sm">Port</label>
          <input type="number" id="dns-edit-port" class="form-input-md" placeholder="5380" />
        </div>
        <div>
          <label for="dns-edit-name" class="form-label-accent-sm">Display Name (optional)</label>
          <input type="text" id="dns-edit-name" class="form-input-md" placeholder="e.g. Primary DNS" />
        </div>
        <div class="form-hint-sm">Manage credentials via Tokens in the toolbar</div>
      </div>

      <div class="weather-modal-buttons" style="margin-top: 24px;">
        <button id="dns-settings-cancel">Cancel</button>
        <button id="dns-settings-delete" style="background: color-mix(in srgb, #e74c3c 20%, transparent); border-color: #e74c3c; color: #e74c3c;">Remove</button>
        <button id="dns-settings-save" class="btn-accent">Save</button>
      </div>
    </div>
  </div>`);let p=null;function v(t){p=t;const h=SITE.dnsServers[t]||{},c=document.getElementById("dns-settings-modal");document.getElementById("dns-settings-title").textContent=`${(h.name||t).toUpperCase()} Settings`,document.getElementById("dns-edit-ip").value=h.ip||"",document.getElementById("dns-edit-port").value=h.port||DC.DEFAULTS.DNS_PORT,document.getElementById("dns-edit-name").value=h.name||"",c.classList.add("show")}async function i(){if(!p)return;const t=document.getElementById("dns-edit-ip").value.trim(),h=document.getElementById("dns-edit-port").value.trim()||DC.DEFAULTS.DNS_PORT,c=document.getElementById("dns-edit-name").value.trim();if(!t){showNotification("Server IP is required","warning");return}const o={dnsServers:{}};o.dnsServers[p]={ip:t,port:String(h)},c&&(o.dnsServers[p].name=c);try{const g=await(await secureFetch("/api/v1/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)})).json();g.success?(SITE.dnsServers[p]=o.dnsServers[p],showNotification(`${p.toUpperCase()} settings saved`,"success"),m(),window.refreshAll()):showNotification(g.error||"Failed to save settings","error")}catch(l){showNotification("Failed to save: "+l.message,"error")}}async function s(){if(p&&confirm(`Remove ${p.toUpperCase()} from dashboard? This won't affect the actual DNS server.`))try{const h=await(await secureFetch("/api/v1/config")).json();h.dnsServers&&delete h.dnsServers[p];const o=await(await secureFetch("/api/v1/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({dnsServers:h.dnsServers||{}})})).json();if(o.success){delete SITE.dnsServers[p];const l=document.querySelector(`.top [data-app="${p}"]`);l&&l.remove(),showNotification(`${p.toUpperCase()} removed from dashboard`,"success"),m()}else showNotification(o.error||"Failed to remove","error")}catch(t){showNotification("Failed to remove: "+t.message,"error")}}function m(){closeModal("dns-settings-modal"),p=null}document.getElementById("dns-settings-cancel")?.addEventListener("click",m),document.getElementById("dns-settings-save")?.addEventListener("click",i),document.getElementById("dns-settings-delete")?.addEventListener("click",s),document.getElementById("dns-settings-modal")?.addEventListener("click",t=>{t.target.id==="dns-settings-modal"&&m()}),document.querySelector(".top")?.addEventListener("click",t=>{const h=t.target.closest('[id$="-settings"]');if(!h)return;const c=h.id.replace("-settings","");SITE.dnsServers[c]&&(t.stopPropagation(),v(c))}),document.getElementById("refresh")?.addEventListener("click",window.refreshAll)})(),(function(){injectModal("logs-modal",`
  <div id="logs-modal" class="logs-modal">
    <div class="logs-modal-content" style="min-width: 800px; max-width: 1000px;">
      <div class="logs-header">
        <h3 id="logs-title">DNS Logs</h3>
        <div class="logs-controls">
          <label for="log-lines">Show:</label>
          <select id="log-lines">
            <option value="25" selected>25</option>
            <option value="50">50</option>
            <option value="100">100</option>
            <option value="200">200</option>
          </select>
          <button id="logs-stream" class="stream-btn" title="Enable real-time streaming">\u{1F4E1} Live</button>
          <button id="logs-pause" class="pause-btn">\u23F8\uFE0F Pause</button>
          <button id="logs-close" class="close-btn">\u2715</button>
        </div>
      </div>
      <div class="logs-container scroll-container">
        <div id="logs-content" class="logs-content">
          <div class="logs-loading">Loading logs...</div>
        </div>
      </div>
    </div>
  </div>`);let a=null,y=null,p=!1,v=null,i=null,s=!1,m=null,t=null,h=!1,c=null,o=!1;async function l(x,w=25){try{const I=getDnsServerAddr(x),k=await fetch(`/api/v1/dns/logs?server=${I}&limit=${w}`,{cache:"no-store",headers:{Accept:"application/json","Cache-Control":"no-cache"}});if(k.ok){const S=await k.json();return S.success&&S.logs?{logs:S.logs,count:S.count,server:S.server}:{error:S.error||"Failed to fetch logs"}}else return k.status===401?{error:"DNS auto-auth failed - check credentials in settings"}:{error:`HTTP ${k.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 w=document.createElement("div");if(w.className="log-entry",w.style.cssText="display: grid; grid-template-columns: 140px 110px 1fr 70px 80px; gap: 8px; padding: 6px 10px; border-bottom: 1px solid var(--border); font-size: 0.8rem; align-items: center;",x.parsed===!1)return w.style.gridTemplateColumns="1fr",w.innerHTML=`<span style="color: var(--muted); font-family: monospace; font-size: 0.75rem;">${escapeHtml(x.raw)}</span>`,w;const I=g(x.rcode),k=x.rcode==="Refused"||x.rcode==="REFUSED";return w.innerHTML=`
      <span style="color: var(--muted); font-size: 0.75rem;">${escapeHtml(x.timestamp)}</span>
      <span style="color: var(--accent); font-size: 0.75rem;" title="${escapeHtml(x.client)}">${escapeHtml(x.client)}</span>
      <span style="font-weight: 500; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; ${k?"text-decoration: line-through; opacity: 0.6;":""}" title="${escapeHtml(x.domain)}">${escapeHtml(x.domain)}</span>
      <span style="color: var(--muted); font-size: 0.75rem;">${escapeHtml(x.type)}</span>
      <span style="color: ${I}; font-weight: 500; font-size: 0.75rem;">${escapeHtml(x.rcode)}</span>
    `,w}async function r(){if(h){await B();return}if(s){await T();return}if(p||!a)return;const x=parseInt(document.getElementById("log-lines").value),w=document.getElementById("logs-content");try{const I=await l(a,x);if(I.error){w.innerHTML=`
          <div style="padding: 20px; text-align: center; color: var(--bad-fg);">
            <div style="font-size: 1.2rem; margin-bottom: 8px;">\u26A0\uFE0F Error</div>
            <div>${escapeHtml(I.error)}</div>
          </div>`;return}w.innerHTML=`
        <div style="display: grid; grid-template-columns: 140px 110px 1fr 70px 80px; gap: 8px; padding: 8px 10px; background: var(--card-base); border-bottom: 2px solid var(--border); font-size: 0.75rem; font-weight: 600; color: var(--muted); position: sticky; top: 0;">
          <span>Time</span>
          <span>Client</span>
          <span>Domain</span>
          <span>Type</span>
          <span>Status</span>
        </div>`,I.logs&&I.logs.length>0?I.logs.forEach(k=>{const S=e(k);w.appendChild(S)}):w.innerHTML+=`
          <div style="padding: 20px; text-align: center; color: var(--muted);">
            No DNS queries logged yet
          </div>`}catch(I){w.innerHTML=`
        <div style="padding: 20px; text-align: center; color: var(--bad-fg);">
          Failed to fetch logs: ${escapeHtml(I.message)}
        </div>`}}function f(x){a=x,p=!1,s=!1;const w=document.getElementById("logs-modal"),I=document.getElementById("logs-title"),k=document.getElementById("logs-pause"),S=document.getElementById("logs-stream");I.textContent=`${x.toUpperCase()} DNS Logs`,k.textContent="\u23F8\uFE0F Pause",k.classList.remove("paused"),S&&(S.style.display="none"),w.classList.add("show"),r(),y=setInterval(r,DC.POLL.LOGS)}function n(){document.getElementById("logs-modal").classList.remove("show"),y&&(clearInterval(y),y=null),b(),a=null,s=!1,v=null,i=null,h=!1,m=null,t=null,p=!1}function u(x){c&&b();const w=document.getElementById("logs-stream"),I=document.getElementById("logs-pause"),k=document.getElementById("logs-content");y&&(clearInterval(y),y=null);try{c=new EventSource(`/api/v1/logs/stream/${x}`),o=!0,w.classList.add("active"),w.textContent="\u{1F534} Live",w.title="Streaming - click to stop",I.style.display="none";const S=document.getElementById("logs-title");S.textContent.includes("\u{1F534}")||(S.innerHTML=S.textContent.replace("\u{1F4CB}","\u{1F4CB} \u{1F534}")),c.onmessage=A=>{try{const O=JSON.parse(A.data);if(O.error){console.error("Stream error:",O.error),b();return}const D=document.createElement("div");D.className="log-entry",D.style.cssText="display: flex; gap: 12px; padding: 6px 10px; border-bottom: 1px solid var(--border); font-size: 0.8rem; align-items: flex-start; font-family: monospace;";const R=(O.stream||"stdout")==="stderr",N=R?"var(--bad-fg)":"var(--fg)",F=`<span style="background: ${R?"var(--bad-bg)":"var(--ok-bg)"}; color: ${N}; padding: 2px 6px; border-radius: 4px; font-size: 0.7rem; font-weight: 600; min-width: 50px; text-align: center;">${R?"STDERR":"STDOUT"}</span>`;for(D.innerHTML=`
            <div style="flex-shrink: 0;">${F}</div>
            <div style="flex: 1; color: ${N}; word-break: break-all; white-space: pre-wrap;">${escapeHtml(O.text)}</div>
          `,k.appendChild(D),k.scrollTop=k.scrollHeight;k.children.length>500;)k.removeChild(k.firstChild)}catch(O){console.error("Error parsing stream data:",O)}},c.onerror=A=>{console.error("EventSource error:",A),b()}}catch(S){console.error("Failed to start streaming:",S),b()}}function b(){c&&(c.close(),c=null),o=!1;const x=document.getElementById("logs-stream"),w=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"),w&&(w.style.display=""),I&&(I.textContent=I.textContent.replace(" \u{1F534}","")),s&&v&&!y&&(y=setInterval(T,DC.POLL.LOGS))}async function d(x,w=100){try{const I=`/api/v1/logs/container/${x}?tail=${w}&timestamps=true`,k=await fetch(I,{cache:"no-store",headers:{Accept:"application/json","Cache-Control":"no-cache"}});if(k.ok){const S=await k.json();return S.success&&S.logs?{logs:S.logs,count:S.count,containerName:S.containerName,containerId:S.containerId}:{error:S.error||"Failed to fetch container logs"}}else return{error:`HTTP ${k.status}: ${k.statusText}`}}catch(I){return console.error("Container logs fetch failed:",I),{error:I.message}}}function E(x){const w=document.createElement("div");w.className="log-entry",w.style.cssText="display: flex; gap: 12px; padding: 6px 10px; border-bottom: 1px solid var(--border); font-size: 0.8rem; align-items: flex-start; font-family: monospace;";const I=x.stream==="stderr"?"var(--bad-fg)":"var(--fg)",k=x.stream==="stderr"?'<span style="background: var(--bad-bg); color: var(--bad-fg); padding: 2px 6px; border-radius: 4px; font-size: 0.7rem; font-weight: 600;">STDERR</span>':'<span style="background: var(--ok-bg); color: var(--ok-fg); padding: 2px 6px; border-radius: 4px; font-size: 0.7rem; font-weight: 600;">STDOUT</span>';return w.innerHTML=`
      <div style="flex-shrink: 0;">${k}</div>
      <div style="flex: 1; color: ${I}; word-break: break-all; white-space: pre-wrap;">${escapeHtml(x.text)}</div>
    `,w}async function T(){if(p||!v||!s)return;const x=parseInt(document.getElementById("log-lines").value),w=document.getElementById("logs-content");try{const I=await d(v,x);if(I.error){w.innerHTML=`
          <div style="padding: 20px; text-align: center; color: var(--bad-fg);">
            <div style="font-size: 1.2rem; margin-bottom: 8px;">\u26A0\uFE0F Error</div>
            <div>${escapeHtml(I.error)}</div>
          </div>`;return}w.innerHTML=`
        <div style="display: flex; gap: 12px; padding: 8px 10px; background: var(--card-base); border-bottom: 2px solid var(--border); font-size: 0.75rem; font-weight: 600; color: var(--muted); position: sticky; top: 0;">
          <span style="flex-shrink: 0; width: 80px;">Stream</span>
          <span style="flex: 1;">Log Output</span>
        </div>`,I.logs&&I.logs.length>0?(I.logs.forEach(k=>{const S=E(k);w.appendChild(S)}),w.scrollTop=w.scrollHeight):w.innerHTML+=`
          <div style="padding: 20px; text-align: center; color: var(--muted);">
            No logs available for this container
          </div>`}catch(I){w.innerHTML=`
        <div style="padding: 20px; text-align: center; color: var(--bad-fg);">
          Failed to fetch logs: ${escapeHtml(I.message)}
        </div>`}}function L(x,w){v=x,i=w,s=!0,h=!1,p=!1,b();const I=document.getElementById("logs-modal"),k=document.getElementById("logs-title"),S=document.getElementById("logs-pause"),A=document.getElementById("logs-stream");k.textContent=`\u{1F4CB} ${w} - Container Logs`,S.textContent="\u23F8\uFE0F Pause",S.classList.remove("paused"),A&&(A.style.display=""),I.classList.add("show"),T(),y=setInterval(T,DC.POLL.LOGS)}async function P(x,w=100){try{const I=`/api/v1/logs/file?path=${encodeURIComponent(x)}&tail=${w}`,k=await fetch(I,{cache:"no-store",headers:{Accept:"application/json","Cache-Control":"no-cache"}});if(k.ok){const S=await k.json();return S.success&&S.logs?{logs:S.logs,count:S.count,logPath:S.logPath,totalLines:S.totalLines}:{error:S.error||"Failed to fetch file logs"}}else return{error:(await k.json().catch(()=>({}))).error||`HTTP ${k.status}`}}catch(I){return console.error("File logs fetch failed:",I),{error:I.message}}}function C(x){const w=document.createElement("div");w.className="log-entry",w.style.cssText="display: flex; gap: 12px; padding: 6px 10px; border-bottom: 1px solid var(--border); font-size: 0.8rem; align-items: flex-start; font-family: monospace;";const I=x.text;let k="INFO",S="var(--fg)";I.match(/ERROR|FATAL|CRITICAL/i)?(k="ERROR",S="var(--bad-fg)"):I.match(/WARN|WARNING/i)?(k="WARN",S="#f39c12"):I.match(/DEBUG/i)&&(k="DEBUG",S="var(--muted)");const O=`<span style="background: ${S==="var(--bad-fg)"?"var(--bad-bg)":"var(--ok-bg)"}; color: ${S}; padding: 2px 6px; border-radius: 4px; font-size: 0.7rem; font-weight: 600; min-width: 50px; text-align: center;">${k}</span>`;return w.innerHTML=`
      <div style="flex-shrink: 0;">${O}</div>
      <div style="flex: 1; color: ${S}; word-break: break-all; white-space: pre-wrap;">${escapeHtml(I)}</div>
    `,w}async function B(){if(p||!m||!h)return;const x=parseInt(document.getElementById("log-lines").value),w=document.getElementById("logs-content");try{const I=await P(m,x);if(I.error){w.innerHTML=`
          <div style="padding: 20px; text-align: center; color: var(--bad-fg);">
            <div style="font-size: 1.2rem; margin-bottom: 8px;">\u26A0\uFE0F Error</div>
            <div>${escapeHtml(I.error)}</div>
          </div>`;return}w.innerHTML=`
        <div style="display: flex; gap: 12px; padding: 8px 10px; background: var(--card-base); border-bottom: 2px solid var(--border); font-size: 0.75rem; font-weight: 600; color: var(--muted); position: sticky; top: 0;">
          <span style="flex: 1;">Log Output (${I.count} of ${I.totalLines} lines)</span>
        </div>`,I.logs&&I.logs.length>0?(I.logs.forEach(k=>{const S=C(k);w.appendChild(S)}),w.scrollTop=w.scrollHeight):w.innerHTML+=`
          <div style="padding: 20px; text-align: center; color: var(--muted);">
            No logs available in this file
          </div>`}catch(I){w.innerHTML=`
        <div style="padding: 20px; text-align: center; color: var(--bad-fg);">
          Failed to fetch logs: ${escapeHtml(I.message)}
        </div>`}}function $(x,w){m=x,t=w,h=!0,s=!1,p=!1;const I=document.getElementById("logs-modal"),k=document.getElementById("logs-title"),S=document.getElementById("logs-pause"),A=document.getElementById("logs-stream");k.textContent=`\u{1F4CB} ${w} - Application Logs`,S.textContent="\u23F8\uFE0F Pause",S.classList.remove("paused"),A&&(A.style.display="none"),I.classList.add("show"),B(),y=setInterval(B,DC.POLL.LOGS)}document.querySelector(".top")?.addEventListener("click",x=>{const w=x.target.closest('[id$="-logs"]');if(!w)return;const I=w.id.replace("-logs","");SITE.dnsServers[I]&&f(I)}),document.getElementById("logs-close")?.addEventListener("click",n),document.getElementById("logs-pause")?.addEventListener("click",()=>{p=!p;const x=document.getElementById("logs-pause");p?(x.textContent="\u25B6\uFE0F Resume",x.classList.add("paused")):(x.textContent="\u23F8\uFE0F Pause",x.classList.remove("paused"),r())}),document.getElementById("log-lines")?.addEventListener("change",()=>{p||r()}),document.getElementById("logs-stream")?.addEventListener("click",()=>{!s||!v||(o?b():u(v))}),document.getElementById("logs-modal")?.addEventListener("click",x=>{x.target.id==="logs-modal"&&n()}),document.addEventListener("keydown",x=>{x.key==="Escape"&&document.getElementById("logs-modal")?.classList.contains("show")&&n()}),window.openContainerLogsModal=L,window.openFileLogsModal=$,window.openLogsModal=f})(),(function(){injectModal("service-edit-modal",`
  <div id="service-edit-modal" class="weather-modal">
    <div class="weather-modal-content" style="min-width: 500px; max-width: 600px;">
      <h3 id="service-edit-title">Edit Service</h3>

      <div style="display: grid; gap: 16px; margin-top: 16px;">
        <!-- Service Info -->
        <div style="display: flex; align-items: center; gap: 12px; padding: 12px; background: var(--card-bg); border-radius: 8px;">
          <img id="edit-service-logo-preview" src="" alt="" style="width: 48px; height: 48px; border-radius: 8px; object-fit: contain; background: var(--bg);" />
          <div style="flex: 1;">
            <div id="edit-service-url-display" class="text-muted-sm"></div>
          </div>
        </div>

        <!-- Display Name -->
        <div>
          <label for="edit-service-name" class="form-label-accent-sm">
            Display Name
          </label>
          <input type="text" id="edit-service-name" class="form-input-md" placeholder="Service name shown on dashboard" />
        </div>

        <!-- Subdomain -->
        <div>
          <label for="edit-subdomain" class="form-label-accent-sm">
            Subdomain
          </label>
          <div class="flex-row-gap-center">
            <input type="text" id="edit-subdomain" class="input-flex" />
            <span id="edit-tld-suffix" style="color: var(--muted);">.home</span>
          </div>
        </div>

        <!-- Port -->
        <div>
          <label for="edit-port" class="form-label-accent-sm">
            Port
          </label>
          <input type="number" id="edit-port" class="form-input-md" />
          <div class="form-hint-sm">
            The port Caddy will proxy to (container's exposed port)
          </div>
        </div>

        <!-- IP Address -->
        <div>
          <label for="edit-ip" class="form-label-accent-sm">
            IP Address
          </label>
          <input type="text" id="edit-ip" class="form-input-md" />
        </div>

        <!-- Tailscale Protection -->
        <div>
          <label style="display: flex; align-items: center; gap: 10px; padding: 12px; background: var(--card-bg); border: 1px solid var(--border); border-radius: 6px; cursor: pointer;">
            <input type="checkbox" id="edit-tailscale-only" style="width: 18px; height: 18px;" />
            <div>
              <div class="fw-500">Tailscale-Only Access</div>
              <div class="text-hint">Restrict this service to Tailscale users only</div>
            </div>
          </label>
        </div>

        <!-- Logo -->
        <div>
          <label class="form-label-accent-sm">
            Service Logo
          </label>
          <div class="flex-row-gap-center">
            <input type="text" id="edit-logo-url" placeholder="/assets/service.png or https://..." class="input-flex" />
            <label style="padding: 10px 16px; background: var(--card-bg); border: 1px solid var(--border); border-radius: 6px; cursor: pointer; white-space: nowrap;">
              <input type="file" id="edit-logo-file" accept="image/*" style="display: none;" />
              Upload
            </label>
          </div>
          <div class="form-hint-sm">
            Enter a URL or upload an image file (PNG, JPG, SVG)
          </div>
        </div>

        <!-- Category -->
        <div>
          <label for="edit-service-category" class="form-label-accent-sm">
            Category
          </label>
          <select id="edit-service-category" data-role="service-category" class="form-input-md">
            <option value="">\u2014 No category \u2014</option>
          </select>
        </div>
      </div>

      <div class="weather-modal-buttons" style="margin-top: 24px;">
        <button id="service-edit-cancel">Cancel</button>
        <button id="service-edit-save" class="btn-accent">
          Save Changes
        </button>
      </div>
    </div>
  </div>`),injectModal("delete-service-modal",`
  <div id="delete-service-modal" class="weather-modal">
    <div class="weather-modal-content" style="min-width: 400px; max-width: 500px;">
      <h3 id="delete-modal-title" class="mb-16">Delete Service</h3>

      <div id="delete-modal-message" style="margin-bottom: 20px; line-height: 1.5;">
        <!-- Dynamic content -->
      </div>

      <div id="delete-modal-container-info" style="display: none; margin-bottom: 20px; padding: 12px; background: var(--card-bg); border-radius: 8px; border: 1px solid var(--border);">
        <div style="font-weight: 500; margin-bottom: 8px;">Docker Container</div>
        <div id="delete-modal-container-name" style="font-size: 0.9rem; color: var(--muted);"></div>
      </div>

      <div class="weather-modal-buttons" style="display: flex; gap: 8px; justify-content: flex-end;">
        <button id="delete-modal-cancel" style="padding: 10px 20px;">Cancel</button>
        <button id="delete-modal-remove" style="padding: 10px 20px; background: color-mix(in srgb, var(--accent) 20%, transparent); border-color: var(--accent); color: var(--accent);">
          Remove
        </button>
        <button id="delete-modal-delete" style="display: none; padding: 10px 20px; background: color-mix(in srgb, #e74c3c 20%, transparent); border-color: #e74c3c; color: #e74c3c;">
          Delete
        </button>
      </div>

      <div id="delete-modal-help" style="display: none; margin-top: 16px; padding: 12px; background: color-mix(in srgb, var(--muted) 10%, transparent); border-radius: 8px; font-size: 0.85rem; color: var(--muted);">
        <div><strong>Remove:</strong> Remove from dashboard only (container keeps running)</div>
        <div style="margin-top: 6px;"><strong>Delete:</strong> Full removal - stops container, removes DNS & Caddy config</div>
      </div>
    </div>
  </div>`),injectModal("add-service-modal",`
  <div id="add-service-modal" class="weather-modal">
    <div class="weather-modal-content" style="min-width: 420px; max-width: 520px;">
      <h3>Add Service</h3>

      <!-- Service Type Tabs -->
      <div style="display: flex; gap: 2px; margin-bottom: 16px; background: var(--card-bg); border-radius: 8px; padding: 3px; border: 1px solid var(--border);">
        <label id="tab-local" style="flex: 1; text-align: center; padding: 8px; border-radius: 6px; cursor: pointer; font-size: 0.85rem; font-weight: 500; background: var(--accent); color: var(--bg); transition: all 0.15s;">
          <input type="radio" name="service-type" value="local" id="service-type-local" checked style="display: none;" />
          Local
        </label>
        <label id="tab-external" style="flex: 1; text-align: center; padding: 8px; border-radius: 6px; cursor: pointer; font-size: 0.85rem; font-weight: 500; color: var(--muted); transition: all 0.15s;">
          <input type="radio" name="service-type" value="external" id="service-type-external" style="display: none;" />
          External
        </label>
      </div>
      <span id="service-type-description" style="display: none;"></span>

      <!-- LOCAL SERVICE -->
      <div id="local-service-config" style="display: grid; gap: 12px;">
        <div>
          <label for="service-name-input" style="font-size: 0.8rem; color: var(--muted); margin-bottom: 4px; display: block;">Name</label>
          <input type="text" id="service-name-input" placeholder="e.g., Jellyfin" style="font-size: 1rem;" />
          <div id="subdomain-preview" style="font-size: 0.75rem; color: var(--accent); margin-top: 4px; min-height: 1em;"></div>
        </div>

        <div class="grid-2col">
          <div>
            <label for="service-port-input" style="font-size: 0.8rem; color: var(--muted); margin-bottom: 4px; display: block;">Port</label>
            <input type="number" id="service-port-input" placeholder="e.g., 8096" style="font-size: 1rem;" />
          </div>
          <div>
            <label for="service-ip-input" style="font-size: 0.8rem; color: var(--muted); margin-bottom: 4px; display: block;">IP Address</label>
            <input type="text" id="service-ip-input" placeholder="Auto-detected" style="font-size: 1rem;" />
            <div class="quick-ip-buttons" style="display: flex; gap: 4px; margin-top: 4px; flex-wrap: wrap;">
              <button type="button" class="quick-ip-btn" data-ip="127.0.0.1" title="Localhost" style="font-size: 0.7rem; padding: 2px 6px;">localhost</button>
              <button type="button" class="quick-ip-btn" data-ip="" id="quick-ip-lan" title="LAN IP" style="font-size: 0.7rem; padding: 2px 6px;">LAN</button>
              <button type="button" class="quick-ip-btn" data-ip="" id="quick-ip-tailscale" title="Tailscale IP" style="font-size: 0.7rem; padding: 2px 6px;">Tailscale</button>
            </div>
          </div>
        </div>

        <!-- Options (collapsed by default) -->
        <details id="local-advanced-options">
          <summary style="cursor: pointer; color: var(--accent); font-size: 0.8rem; user-select: none;">Options</summary>
          <div style="margin-top: 10px; display: grid; gap: 10px; font-size: 0.8rem;">

            <div class="grid-2col">
              <div>
                <label for="service-subdomain-input">Subdomain:</label>
                <input type="text" id="service-subdomain-input" placeholder="auto-derived from name" />
              </div>
              <div>
                <label for="service-logo-input">Logo URL:</label>
                <input type="text" id="service-logo-input" placeholder="/assets/name.png" />
              </div>
            </div>

            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 8px; align-items: start;">
              <label style="display: flex; align-items: center; gap: 6px; cursor: pointer;">
                <input type="checkbox" id="create-dns-record" checked />
                Create DNS Record
              </label>
              <div>
                <label for="ssl-type-select">SSL:</label>
                <select id="ssl-type-select" style="width: 100%;">
                  <option value="caddy-managed">Caddy Managed (Internal)</option>
                  <option value="letsencrypt">Let's Encrypt</option>
                  <option value="existing-ca">Existing CA</option>
                  <option value="custom-ca">Custom CA</option>
                </select>
              </div>
            </div>

            <div id="dns-config">
              <div class="grid-2col">
                <div>
                  <label for="dns-ttl-input">DNS TTL:</label>
                  <input type="number" id="dns-ttl-input" value="300" />
                </div>
                <div>
                  <label for="caddyfile-path-input">Caddyfile Path:</label>
                  <input type="text" id="caddyfile-path-input" value="C:\\caddy\\Caddyfile" />
                </div>
              </div>
            </div>

            <div id="existing-ca-config" style="display: none;">
              <label for="existing-ca-select">Existing CA:</label>
              <div class="flex-row-gap">
                <select id="existing-ca-select" style="flex: 1;">
                  <option value="">Loading CAs...</option>
                </select>
                <button type="button" id="refresh-cas" style="padding: 4px 8px; font-size: 0.75rem;">\u{1F504}</button>
              </div>
            </div>

            <div id="custom-ca-config" style="display: none;">
              <label for="ca-name-input">CA Name:</label>
              <input type="text" id="ca-name-input" placeholder="e.g., sami-ca" />
            </div>

            <div id="manual-tailscale-status" style="padding: 6px 10px; background: var(--card-bg); border-radius: 6px; font-size: 0.75rem;">
              <span style="color: var(--muted);">Checking Tailscale...</span>
            </div>
            <label style="display: flex; align-items: center; gap: 8px; cursor: pointer;">
              <input type="checkbox" id="manual-tailscale-only" />
              Tailscale-Only Access
            </label>

            <label style="display: flex; align-items: center; gap: 6px; cursor: pointer;">
              <input type="checkbox" id="reload-caddy" checked />
              Reload Caddy after adding
            </label>

            <!-- Category -->
            <div>
              <label for="service-category-input" style="font-size: 0.8rem; color: var(--muted); margin-bottom: 4px; display: block;">Category</label>
              <select id="service-category-input" data-role="service-category" style="width: 100%;">
                <option value="">\u2014 No category \u2014</option>
              </select>
              <div style="font-size: 0.7rem; color: var(--muted); margin-top: 3px;">Group services on the dashboard by purpose (Media, Productivity, etc.)</div>
            </div>

            <hr style="border: none; border-top: 1px solid var(--border); margin: 4px 0;" />

            <div class="grid-2col">
              <div>
                <label class="field-label-sm">
                  <input type="checkbox" id="enable-auth" />
                  Authentication
                </label>
                <label class="field-label-sm">
                  <input type="checkbox" id="enable-cors" />
                  CORS Headers
                </label>
                <label for="upstream-path-input">Upstream Path:</label>
                <input type="text" id="upstream-path-input" value="/" />
              </div>
              <div>
                <label for="health-check-input">Health Check:</label>
                <input type="text" id="health-check-input" placeholder="/health" />
                <label for="timeout-input">Timeout (s):</label>
                <input type="number" id="timeout-input" value="30" />
                <label for="custom-headers-input">Headers (JSON):</label>
                <textarea id="custom-headers-input" placeholder='{"X-Custom": "value"}' rows="2" style="font-size: 0.7rem;"></textarea>
              </div>
            </div>

          </div>
        </details>
      </div>

      <!-- EXTERNAL SERVICE -->
      <div id="external-service-config" style="display: none;">
        <div style="display: grid; gap: 12px;">
          <div>
            <label for="external-service-name" style="font-size: 0.8rem; color: var(--muted); margin-bottom: 4px; display: block;">Name</label>
            <input type="text" id="external-service-name" placeholder="e.g., Radarr (Seedhost)" style="font-size: 1rem;" />
            <div id="external-subdomain-preview" style="font-size: 0.75rem; color: var(--accent); margin-top: 4px; min-height: 1em;"></div>
          </div>

          <div>
            <label for="external-service-url" style="font-size: 0.8rem; color: var(--muted); margin-bottom: 4px; display: block;">External URL</label>
            <input type="url" id="external-service-url" placeholder="https://username.seedhost.eu/radarr" style="font-size: 1rem;" />
          </div>

          <!-- Options (collapsed by default) -->
          <details id="external-advanced-options">
            <summary style="cursor: pointer; color: var(--accent); font-size: 0.8rem; user-select: none;">Options</summary>
            <div style="margin-top: 10px; display: grid; gap: 10px; font-size: 0.8rem;">

              <div class="grid-2col">
                <div>
                  <label for="external-service-subdomain">Subdomain:</label>
                  <input type="text" id="external-service-subdomain" placeholder="auto-derived from name" />
                  <span id="external-domain-preview" style="font-size: 0.7rem; color: var(--accent);"></span>
                </div>
                <div>
                  <label for="external-service-logo">Logo URL:</label>
                  <input type="text" id="external-service-logo" placeholder="/assets/name.png" />
                </div>
              </div>

              <div>
                <label for="external-service-icon">Icon Emoji:</label>
                <input type="text" id="external-service-icon" placeholder="\u{1F3AC}" maxlength="2" style="width: 60px;" />
              </div>

              <label style="display: flex; align-items: center; gap: 6px; cursor: pointer;">
                <input type="checkbox" id="external-create-dns" checked />
                Create DNS Record
              </label>
              <label style="display: flex; align-items: center; gap: 6px; cursor: pointer;">
                <input type="checkbox" id="external-create-caddy" checked />
                Create Caddy Reverse Proxy
              </label>

              <div>
                <label for="external-proxy-ip">Proxy Server IP:</label>
                <input type="text" id="external-proxy-ip" placeholder="Auto-detected" />
              </div>
              <label style="display: flex; align-items: center; gap: 6px; cursor: pointer;">
                <input type="checkbox" id="external-preserve-host" checked />
                Preserve Host Header
              </label>
              <label style="display: flex; align-items: center; gap: 6px; cursor: pointer;">
                <input type="checkbox" id="external-follow-redirects" checked />
                Follow Redirects
              </label>

              <!-- Category (external) -->
              <div>
                <label for="external-service-category" style="font-size: 0.8rem; color: var(--muted); margin-bottom: 4px; display: block;">Category</label>
                <select id="external-service-category" data-role="service-category" style="width: 100%;">
                  <option value="">\u2014 No category \u2014</option>
                </select>
              </div>

            </div>
          </details>
        </div>
      </div>

      <div class="weather-modal-buttons" style="margin-top: 16px; display: flex; gap: 8px; justify-content: flex-end;">
        <button id="add-service-cancel">Cancel</button>
        <button id="add-service-create" class="btn-accent">Create Service</button>
      </div>
    </div>
  </div>`)})(),(function(){async function a(s){try{const m=await fetch(`/api/v1/caddy/cas?caddyfilePath=${encodeURIComponent(s)}`);if(!m.ok)throw new Error(`Failed to load CAs: ${m.status}`);const t=await m.json();if(t.success){const h=document.getElementById("existing-ca-select");return h.innerHTML="",t.cas.length===0?h.innerHTML='<option value="">No CAs found in Caddyfile</option>':(h.innerHTML='<option value="">Select existing CA...</option>',t.cas.forEach(c=>{const o=document.createElement("option");typeof c=="object"?(o.value=c.id,o.textContent=c.displayName||c.name):(o.value=c,o.textContent=c),h.appendChild(o)})),t.data.cas}else throw new Error(t.message)}catch(m){console.error("Error loading CAs:",m);const t=document.getElementById("existing-ca-select");return t.innerHTML='<option value="">Error loading CAs</option>',[]}}function y(s){const{subdomain:m,port:t,ip:h,sslType:c,caName:o,existingCa:l,enableAuth:g,enableCors:e,customHeaders:r,upstreamPath:f,healthCheck:n,timeout:u,tailscaleOnly:b}=s;let d=`${buildDomain(m)} {
`;switch(b&&(d+=`  @blocked not remote_ip 100.64.0.0/10
`,d+=`  respond @blocked "Access denied. Tailscale connection required." 403
`),c){case"letsencrypt":break;case"caddy-managed":d+=`  tls internal
`;break;case"existing-ca":l&&(d+=`  tls {
    ca ${l}
  }
`);break;case"custom-ca":o&&(d+=`  tls {
    ca ${o}
  }
`);break}if(g&&(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+=`  }
`),r)try{const E=JSON.parse(r);d+=`  header {
`,Object.entries(E).forEach(([T,L])=>{d+=`    ${T} "${L}"
`}),d+=`  }
`}catch{console.warn("Invalid JSON in custom headers")}return n&&(d+=`  health_uri ${n}
`),d+=`  reverse_proxy ${h}:${t} {
`,f&&f!=="/"&&(d+=`    rewrite ${f}
`),u&&u!==30&&(d+=`    transport http {
`,d+=`      dial_timeout ${u}s
`,d+=`      response_header_timeout ${u}s
`,d+=`    }
`),d+=`  }
`,d+=`}
`,d}async function p(s,m,t=DC.DEFAULTS.TTL){const h=window.getToken(getPrimaryDnsId(),"admin");if(!h)throw new Error("DNS admin token not configured. Please set it in the Tokens menu.");const c=buildDomain(s),o=await secureFetch("/api/v1/dns/record",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:c,ip:m,ttl:t,token:h,server:SITE.dnsIp})});if(!o.ok){const g=await o.text();throw new Error(`DNS API Error: ${o.status} - ${g}`)}const l=await o.json();if(!l.success)throw new Error(`DNS Error: ${l.error||"Unknown error"}`);return l}async function v(s){const m={id:s.subdomain,name:s.name,logo:s.logo||`/assets/${s.subdomain}.png`};s.category&&(m.category=s.category),s.containerId&&(m.containerId=s.containerId);try{const t=await secureFetch("/api/v1/services",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(m)});if(!t.ok){const h=await t.json();throw new Error(h.error||"Failed to save service")}return await window.loadServices(),window.buildGrid(),m}catch(t){throw console.error("Failed to add service to config:",t),t}}async function i(s){const m=document.getElementById("service-subdomain-input").value.trim(),t=document.getElementById("service-ip-input").value.trim()||"localhost",h=document.getElementById("service-port-input").value.trim()||"80",c=await secureFetch("/api/v1/site",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:buildDomain(m),upstream:`${t}:${h}`,config:s})}),o=await c.json();if(!c.ok||!o.success)throw new Error(o.error||`Caddy API Error: ${c.status}`);return o}window.loadExistingCAs=a,window.generateCaddyConfig=y,window.createDnsRecord=p,window.addServiceToConfig=v,window.addToCaddyfile=i})(),(function(){let a=null;function y(t){a=t;const h=document.getElementById("service-edit-modal");document.getElementById("service-edit-title").textContent=`Edit ${t.name}`,document.getElementById("edit-service-name").value=t.name,document.getElementById("edit-service-url-display").textContent=t.url||buildServiceUrl(t.id),document.getElementById("edit-service-logo-preview").src=t.logo||`/assets/${t.id}.png`,document.getElementById("edit-subdomain").value=t.id,document.getElementById("edit-port").value=t.port||"",document.getElementById("edit-ip").value=t.ip||"localhost",document.getElementById("edit-tailscale-only").checked=t.tailscaleOnly||!1,document.getElementById("edit-logo-url").value=t.logo||"";const c=document.getElementById("edit-service-category");c&&(c.dataset.current=t.category||"",typeof window.populateCategorySelects=="function"&&window.populateCategorySelects()),h.classList.add("show")}function p(){closeModal("service-edit-modal"),a=null}async function v(){if(!a)return;const t=document.getElementById("edit-subdomain").value.trim().toLowerCase(),h=document.getElementById("edit-service-name").value.trim(),c=document.getElementById("edit-port").value.trim(),o=document.getElementById("edit-ip").value.trim()||"localhost",l=document.getElementById("edit-tailscale-only").checked,g=document.getElementById("edit-logo-url").value.trim(),e=document.getElementById("edit-service-category")?.value||"";if(!t){showNotification("Subdomain is required","warning");return}const r=a.id,f=[];if(t!==r&&f.push("subdomain"),h&&h!==a.name&&f.push("name"),c&&c!==String(a.port)&&f.push("port"),o!==a.ip&&f.push("ip"),l!==(a.tailscaleOnly||!1)&&f.push("tailscale"),g&&g!==a.logo&&f.push("logo"),e!==(a.category||"")&&f.push("category"),f.length===0){p();return}const n=document.getElementById("service-edit-save");n.textContent="Saving...",n.disabled=!0;try{const b=await(await secureFetch("/api/v1/services/update",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({oldSubdomain:r,newSubdomain:t,name:h||a.name,port:c||a.port,ip:o,tailscaleOnly:l,logo:g||void 0,category:e})})).json();if(!b.success)throw new Error(b.error||"Failed to update service");const d=window.APPS.findIndex(E=>E.id===r);d!==-1&&(window.APPS[d]={...window.APPS[d],id:t,name:h||window.APPS[d].name,port:c||window.APPS[d].port,ip:o,tailscaleOnly:l,logo:g||window.APPS[d].logo,category:e||void 0}),p(),window.buildGrid(),window.refreshAll()}catch(u){console.error("Error saving service changes:",u),showNotification(`Error saving changes: ${u.message}`,"error")}finally{n.textContent="Save Changes",n.disabled=!1}}document.getElementById("edit-logo-file")?.addEventListener("change",async t=>{const h=t.target.files[0];if(!h)return;if(!h.type.startsWith("image/")){showNotification("Please select an image file","warning");return}const c=new FileReader;c.onload=async o=>{const l=o.target.result;if(document.getElementById("edit-service-logo-preview").src=l,document.getElementById("edit-logo-url").value=l,a)try{const e=await(await secureFetch("/api/v1/assets/upload",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filename:`${a.id}.png`,data:l})})).json();e.success&&e.path&&(document.getElementById("edit-logo-url").value=e.path)}catch{}},c.readAsDataURL(h)}),document.getElementById("service-edit-cancel")?.addEventListener("click",p),document.getElementById("service-edit-save")?.addEventListener("click",v),document.getElementById("service-edit-modal")?.addEventListener("click",t=>{t.target.id==="service-edit-modal"&&p()});function i(t,h,c){return new Promise(o=>{const l=document.getElementById("delete-service-modal"),g=document.getElementById("delete-modal-title"),e=document.getElementById("delete-modal-message"),r=document.getElementById("delete-modal-container-info"),f=document.getElementById("delete-modal-container-name"),n=document.getElementById("delete-modal-help"),u=document.getElementById("delete-modal-cancel"),b=document.getElementById("delete-modal-remove"),d=document.getElementById("delete-modal-delete");g.textContent=`Delete "${t}"`,h?(e.innerHTML="This service has an associated Docker container.<br>Choose how to proceed:",r.style.display="block",f.textContent=`Container ID: ${c?.slice(0,12)||"Unknown"}`,n.style.display="block",d.style.display="block"):(e.textContent="Remove this service from the dashboard?",r.style.display="none",n.style.display="none",d.style.display="none");const E=()=>{l.classList.remove("show"),u.removeEventListener("click",T),b.removeEventListener("click",L),d.removeEventListener("click",P),l.removeEventListener("click",C)},T=()=>{E(),o(null)},L=()=>{E(),o(!1)},P=()=>{E(),o(!0)},C=B=>{B.target===l&&(E(),o(null))};u.addEventListener("click",T),b.addEventListener("click",L),d.addEventListener("click",P),l.addEventListener("click",C),l.classList.add("show")})}async function s(t,h,c){const o=document.getElementById(`update-btn-${c}`),l=o?.textContent;if(confirm(`Update ${h} to the latest version?

This will:
1. Pull the latest image
2. Stop the container
3. Recreate with same settings

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