(function(c){"use strict";class a{constructor(){this.errors=[],this.maxErrors=50}logError(h,b,g={}){const v={timestamp:new Date().toISOString(),context:h,message:b instanceof Error?b.message:b,stack:b instanceof Error?b.stack:null,metadata:g};this.errors.push(v),this.errors.length>this.maxErrors&&this.errors.shift(),console.error(`[Onboarding Error] ${h}:`,b,g)}recoverFromError(h,b){switch(this.classifyError(h)){case"ELEMENT_NOT_FOUND":return this.logError("Element Not Found",h,{currentStep:b}),{action:"SKIP_STEP",nextStep:b+1,message:"Target element not found, skipping to next step"};case"STORAGE_UNAVAILABLE":return this.logError("Storage Unavailable",h),{action:"USE_MEMORY_STORAGE",message:"Local storage unavailable, using in-memory storage"};case"DRIVER_NOT_LOADED":return this.logError("Driver.js Not Loaded",h),{action:"ABORT_TOUR",message:"Driver.js library not loaded, cannot start tour"};case"INVALID_TOOLTIP":return this.logError("Invalid Tooltip Configuration",h,{currentStep:b}),{action:"SKIP_STEP",nextStep:b+1,message:"Invalid tooltip configuration, skipping"};case"THEME_DETECTION_FAILED":return this.logError("Theme Detection Failed",h),{action:"USE_DEFAULT_THEME",message:"Using default dark theme"};default:return this.logError("Unknown Error",h,{currentStep:b}),{action:"ABORT_TOUR",message:"Unexpected error occurred, aborting tour"}}}classifyError(h){const b=h.message||h.toString();return b.includes("element")&&b.includes("not found")?"ELEMENT_NOT_FOUND":b.includes("storage")||b.includes("quota")?"STORAGE_UNAVAILABLE":b.includes("driver")||b.includes("undefined")?"DRIVER_NOT_LOADED":b.includes("invalid")||b.includes("validation")?"INVALID_TOOLTIP":b.includes("theme")?"THEME_DETECTION_FAILED":"UNKNOWN"}getErrors(){return[...this.errors]}clearErrors(){this.errors=[]}getStatistics(){const h={total:this.errors.length,byContext:{},byType:{},recent:this.errors.slice(-10)};return this.errors.forEach(b=>{h.byContext[b.context]=(h.byContext[b.context]||0)+1;const g=this.classifyError({message:b.message});h.byType[g]=(h.byType[g]||0)+1}),h}handleDriverLoadFailure(){this.logError("Driver.js Load Failure","Driver.js library failed to load");const h=document.createElement("div");return h.id="onboarding-fallback",h.style.cssText=`
        position: fixed;
        bottom: 20px;
        right: 20px;
        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;
      `,h.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(h),setTimeout(()=>{h.parentNode&&h.parentNode.removeChild(h)},1e4),!0}handleStorageUnavailable(){this.logError("Storage Unavailable","Local storage is not available");const h={data:{},getItem(b){return this.data[b]||null},setItem(b,g){this.data[b]=g},removeItem(b){delete this.data[b]},clear(){this.data={}}};return console.warn("[ErrorHandler] Using in-memory storage - progress will not persist"),h}sendToErrorTracking(h){}}c.ErrorHandler=a,console.log("[ErrorHandler] Module loaded")})(window),(function(){try{var a=typeof localStorage<"u"&&localStorage.getItem("dashcaddy-health-settings")||null;if(a){var m=JSON.parse(a);m.statsPollingInterval&&m.statsPollingInterval>=5&&m.statsPollingInterval<=3600&&(window.__DC_STATS_OVERRIDE=m.statsPollingInterval*1e3)}}catch{}})();const DC={NAME:"DashCaddy",POLL:{DASHBOARD:1e4,LOGS:3e3,STATS:typeof window<"u"&&window.__DC_STATS_OVERRIDE||5e3,WEATHER:6e5,HEALTH:1e3,DEPLOY_SSL:5e3},DELAYS:{BTN_RESET:2e3,RELOAD:5e3,MODAL_CLOSE:500,PORT_CHECK:500,DEPLOY_INIT:3e3},DEFAULTS:{DNS_PORT:"5380",SERVICE_PORT:"8080",TTL:300,CADDYFILE:"C:\\caddy\\Caddyfile"}},errorHandler=new ErrorHandler,_cachedCfg=JSON.parse(localStorage.getItem("dashcaddy_site_config")||"null"),SITE={tld:_cachedCfg&&_cachedCfg.tld||".home",dnsIp:"",dnsPort:DC.DEFAULTS.DNS_PORT,dnsServers:{},configurationType:_cachedCfg&&_cachedCfg.configurationType||"homelab",domain:_cachedCfg&&_cachedCfg.domain||"",defaults:_cachedCfg&&_cachedCfg.defaults||{},routingMode:_cachedCfg&&_cachedCfg.routingMode||"subdomain",onboardingCompleted:!1};window.__dashcaddySiteConfigLoaded=(async function(){try{const h=await fetch("/api/v1/config");if(h.ok){const b=await h.json();if(b.tld&&(SITE.tld=b.tld.startsWith(".")?b.tld:"."+b.tld),b.dns&&(SITE.dnsIp=b.dns.ip||"",SITE.dnsPort=b.dns.port||DC.DEFAULTS.DNS_PORT),b.dnsServers&&typeof b.dnsServers=="object")for(const[v,p]of Object.entries(b.dnsServers))v!=="__proto__"&&v!=="constructor"&&v!=="prototype"&&(SITE.dnsServers[v]=p);b.configurationType&&(SITE.configurationType=b.configurationType),b.domain&&(SITE.domain=b.domain),b.defaults&&(SITE.defaults=b.defaults),b.routingMode&&(SITE.routingMode=b.routingMode),SITE.onboardingCompleted=b.onboardingCompleted===!0,localStorage.setItem("dashcaddy_site_config",JSON.stringify({tld:SITE.tld,configurationType:SITE.configurationType,domain:SITE.domain,routingMode:SITE.routingMode})),renderDnsCards();const g=document.getElementById("manage-tokens");g&&(g.style.display=Object.keys(SITE.dnsServers).length?"":"none")}}catch{}document.querySelectorAll("[data-tld]").forEach(h=>h.textContent=SITE.tld);const a=document.getElementById("edit-tld-suffix");a&&(a.textContent=SITE.tld);const m=document.getElementById("external-proxy-ip");m&&SITE.dnsIp&&(m.value=SITE.dnsIp,m.placeholder=SITE.dnsIp)})();function buildDomain(c){return c+SITE.tld}function buildServiceUrl(c){return SITE.routingMode==="subdirectory"&&SITE.domain?"https://"+SITE.domain+"/"+c:SITE.configurationType==="public"&&SITE.domain?"https://"+c+"."+SITE.domain:"https://"+buildDomain(c)}function getDnsServerAddr(c){const a=SITE.dnsServers[c];return a?`${a.ip}:${a.port}`:buildDomain(c)}function getPrimaryDnsId(){if(!SITE.dnsIp)return null;for(const[c,a]of Object.entries(SITE.dnsServers))if(a.ip===SITE.dnsIp)return c;return null}function renderDnsCards(){const c=document.querySelector(".top");if(!c)return;const a=Object.keys(SITE.dnsServers);if(!a.length)return;const m='<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>',h=c.firstElementChild;a.forEach(b=>{const g=escapeHtml(b),v=escapeHtml((SITE.dnsServers[b].name||b).toUpperCase()),p=document.createElement("div");p.className="card",p.setAttribute("data-app",b),p.setAttribute("data-status","off"),p.innerHTML=`<span id="${g}-dot" class="dot bad at-bl"></span><div class="row"><div class="logo-wrap">${m}</div><span class="name">${v}</span><span class="spacer"></span><span id="${g}-pill" class="badge off" data-i18n-live-status="binary">OFF</span></div><div class="response-row"><span id="${g}-time" class="response-time">--</span></div><div class="health-row" id="health-${g}"><span id="uptime-${g}" class="uptime-chip">--</span><div class="uptime-mini-bar"><div class="fill" id="uptime-bar-${g}" style="width: 0%"></div></div></div><div class="btn-row"><button id="${g}-restart" class="restart-btn" data-i18n="action.restart">Restart</button><button id="${g}-update" class="update-btn" title="Update DNS server">\u2B06\uFE0F</button><button id="${g}-open" data-i18n="action.open">Open</button><button id="${g}-logs" class="logs-btn" data-i18n="action.logs">Logs</button><button id="${g}-settings" class="settings-btn">\u2699\uFE0F</button></div>`,c.insertBefore(p,h)}),window.DCI18n&&window.DCI18n.isLoaded()&&window.DCI18n.applyTranslations()}window.renderDnsCards=renderDnsCards;let csrfToken=null;async function getCSRFToken(){if(csrfToken)return csrfToken;try{const c=await fetch("/api/v1/csrf-token");if(!c.ok)throw new Error("Failed to fetch CSRF token");return csrfToken=(await c.json()).token,csrfToken}catch(c){throw errorHandler.logError("[CSRF] Get Token",c,{function:"getCSRFToken"}),c}}async function secureFetch(c,a={}){const m=(a.method||"GET").toUpperCase(),h=!["GET","HEAD","OPTIONS"].includes(m);if(h)try{const g=await getCSRFToken();a.headers={...a.headers,"X-CSRF-Token":g}}catch(g){errorHandler.logError("[CSRF] Add to Request",g,{function:"secureFetch"})}a.signal||(a={...a,signal:AbortSignal.timeout(15e3)}),a.credentials=a.credentials||"same-origin";const b=await fetch(c,a);if(h&&b.status===403)try{const g=await b.clone().json();if(g.error&&(g.error.includes("DC-100")||g.error.includes("DC-101"))){csrfToken=null;const v=await getCSRFToken();return a.headers={...a.headers,"X-CSRF-Token":v},a.signal=AbortSignal.timeout(15e3),fetch(c,a)}}catch{}return b}async function postJSON(c,a){const m=await secureFetch(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)}),h=await m.json();if(!m.ok||h.success===!1)throw new Error(h.error||`Request failed (${m.status})`);return h}async function getJSON(c){const a=await secureFetch(c);if(!a.ok){let m=`Request failed (${a.status})`;try{m=(await a.json()).error||m}catch{}throw new Error(m)}return a.json()}async function deleteAPI(c){const a=await secureFetch(c,{method:"DELETE"}),m=await a.json();if(!a.ok||m.success===!1)throw new Error(m.error||`Delete failed (${a.status})`);return m}async function withButton(c,a,m,h={}){const b=c.innerHTML,{successText:g="\u2705",resetDelay:v=DC.DELAYS.BTN_RESET}=h;c.disabled=!0,c.innerHTML=a;try{const p=await m();return c.innerHTML=g,setTimeout(()=>{c.innerHTML=b,c.disabled=!1},v),p}catch(p){throw c.innerHTML=b,c.disabled=!1,p}}function openModal(c){document.getElementById(c)?.classList.add("show")}function closeModal(c){document.getElementById(c)?.classList.remove("show")}function wireModal(c,...a){c&&(c.addEventListener("click",m=>{m.target===c&&c.classList.remove("show")}),a.forEach(m=>{m&&typeof m.addEventListener=="function"&&m.addEventListener("click",()=>c.classList.remove("show"))}))}function showNotification(c,a="info",m=3e3){const h=document.querySelector(".deploy-notification");h&&h.remove();const b={info:{bg:"#2196F3",fg:"#fff"},success:{bg:"var(--ok-bg)",fg:"var(--ok-fg)"},error:{bg:"#f44336",fg:"#fff"},warning:{bg:"#ff9800",fg:"#fff"}},g=b[a]||b.info,v=document.createElement("div");v.className="deploy-notification",v.textContent=c,v.style.cssText=`
    position: fixed; top: 20px; right: 20px;
    background: ${g.bg}; color: ${g.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(v),m>0&&setTimeout(()=>v.remove(),m)}function timeAgo(c){const a=Date.now()-new Date(c).getTime();return a<6e4?"just now":a<36e5?Math.floor(a/6e4)+"m ago":a<864e5?Math.floor(a/36e5)+"h ago":Math.floor(a/864e5)+"d ago"}function safeGet(c,a=null){try{const m=localStorage.getItem(c);return m!==null?m:a}catch{return a}}function safeSet(c,a){try{localStorage.setItem(c,a)}catch{}}function safeRemove(c){try{localStorage.removeItem(c)}catch{}}function safeSessionGet(c,a=null){try{const m=sessionStorage.getItem(c);return m!==null?m:a}catch{return a}}function safeSessionSet(c,a){try{sessionStorage.setItem(c,a)}catch{}}function safeGetJSON(c,a=null){try{const m=localStorage.getItem(c);return m?JSON.parse(m):a}catch{return a}}function escapeHtml(c){return String(c??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function injectModal(c,a){document.getElementById(c)||document.body.insertAdjacentHTML("beforeend",a)}const DC_BUS={_handlers:{},on(c,a){var m;((m=this._handlers)[c]||(m[c]=[])).push(a)},off(c,a){this._handlers[c]=this._handlers[c]?.filter(m=>m!==a)},emit(c,a){this._handlers[c]?.forEach(m=>m(a))}},AppState={_apps:[],getApps(){return this._apps},setApps(c){this._apps=c,window.APPS=c,DC_BUS.emit("apps:changed",c)},findApp(c){return this._apps.find(a=>a.id===c)},addApp(c){this._apps.push(c),window.APPS=this._apps,DC_BUS.emit("apps:changed",this._apps)},removeApp(c){const a=this._apps.findIndex(m=>m.id===c);return a>-1&&(this._apps.splice(a,1),window.APPS=this._apps,DC_BUS.emit("apps:changed",this._apps)),a>-1},updateApp(c,a){const m=this._apps.find(h=>h.id===c);if(m){for(const[h,b]of Object.entries(a))h!=="__proto__"&&h!=="constructor"&&h!=="prototype"&&(m[h]=b);DC_BUS.emit("apps:changed",this._apps)}return m}};(function(){function c(){const h=document.createElement("div");return h.className="skeleton-card",h.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>',h}function a(h){const b=document.getElementById("cards");if(!(!b||b.querySelector(".card"))){h=h||6;for(let g=0;g<h;g++){const v=c();b.appendChild(v),setTimeout(function(){v.classList.add("loaded")},g*60)}}}function m(){const h=document.getElementById("cards");if(h){var b=h.querySelectorAll(".skeleton-card");b.length&&(b.forEach(function(g,v){setTimeout(function(){g.style.opacity="0",g.style.transform="translateY(-10px)"},v*25)}),setTimeout(function(){b.forEach(function(g){g.parentNode&&g.remove()})},b.length*25+300))}}window.SkeletonLoader={show:a,hide:m}})(),(function(){var c="theme",a="user-themes",m="custom-theme",h=["dark","light","blue","black","nord","dracula","solarized-dark","solarized-light","taxi","ocean"],b=h.slice(),g=["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"],v=["bg","fg","muted","card-base","card-bg","border","ok-bg","ok-fg","bad-bg","bad-fg","dot-ok","dot-bad","uptime","accent","accent-strong"],p=["fg-muted","hover","card-hover","base","success","error","warning"],d={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 r(x){return!x||typeof x!="string"?{r:0,g:0,b:0}:(x=x.replace("#",""),x.length===3&&(x=x[0]+x[0]+x[1]+x[1]+x[2]+x[2]),{r:parseInt(x.substr(0,2),16)||0,g:parseInt(x.substr(2,2),16)||0,b:parseInt(x.substr(4,2),16)||0})}function f(x,B,A){return"#"+[x,B,A].map(function(E){var C=Math.max(0,Math.min(255,Math.round(E))).toString(16);return C.length===1?"0"+C:C}).join("")}function w(x,B,A){var E=r(x),C=r(B);return f(E.r+(C.r-E.r)*A,E.g+(C.g-E.g)*A,E.b+(C.b-E.b)*A)}function s(x){x=x.replace("#",""),x.length===3&&(x=x[0]+x[0]+x[1]+x[1]+x[2]+x[2]);var B=parseInt(x.substr(0,2),16)/255,A=parseInt(x.substr(2,2),16)/255,E=parseInt(x.substr(4,2),16)/255;return B=B<=.03928?B/12.92:Math.pow((B+.055)/1.055,2.4),A=A<=.03928?A/12.92:Math.pow((A+.055)/1.055,2.4),E=E<=.03928?E/12.92:Math.pow((E+.055)/1.055,2.4),.2126*B+.7152*A+.0722*E}function t(x){var B=x.bg||"#0b0f1a",A=x.fg||"#e8ecf5",E=x.muted||"#9aa6bf",C=x["card-base"]||x.bg||"#121826",T=x["dot-ok"]||"#4caf50",$=x["dot-bad"]||"#e74c3c",I=x.lightBg||B&&s(B)>.4,P={};return P.hover=I?w(C,B,.35):w(C,A,.08),P["card-hover"]=w(C,P.hover,.5),P.base=w(B,C,.6),P["fg-muted"]=w(E,B,.35),P.success=T,P.error=$,P.warning=I?"#d68a00":"#f39c12",P}function e(x,B){var A=B.lightBg||B.bg&&s(B.bg)>.4,E=B.accent||B["accent-strong"]||"#888888",C=r(E);return A?":root."+x+` body {
  background:
    radial-gradient(1200px 800px at 10% -10%, rgba(`+C.r+","+C.g+","+C.b+`, .08), transparent 60%),
    radial-gradient(1000px 700px at 110% 10%, rgba(`+C.r+","+C.g+","+C.b+`, .05), transparent 55%),
    var(--bg);
}
`:":root."+x+` body {
  background:
    radial-gradient(1200px 900px at 8% -12%, rgba(`+C.r+","+C.g+","+C.b+`, .10), transparent 60%),
    radial-gradient(1000px 700px at 110% -10%, rgba(`+C.r+","+C.g+","+C.b+`, .07), transparent 55%),
    var(--bg);
}
`}function o(x,B){var A=B.lightBg||B.bg&&s(B.bg)>.4;return A?":root."+x+` 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."+x+` button:hover {
  background: color-mix(in srgb, var(--accent) 18%, transparent);
  border-color: color-mix(in srgb, var(--accent) 35%, var(--border));
}
`}function u(){return window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}function n(){g.forEach(function(x){document.documentElement.style.removeProperty("--"+x)})}function i(x,B){var A=x.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"");A||(A="custom"),h.indexOf(A)!==-1&&(A=A+"-custom");for(var E=safeGetJSON(a,{}),C=A,T=2;E[A]&&A!==B;)A=C+"-"+T++;return A}function l(x){var B=document.getElementById("user-theme-styles");B&&B.remove(),b.length=h.length,Object.keys(d).forEach(function($){h.indexOf($)===-1&&delete d[$]});var A=x||safeGetJSON(a,{}),E=Object.keys(A);if(E=E.filter(function($){return h.indexOf($)===-1}),!!E.length){var C="";E.forEach(function($){var I=A[$];b.indexOf($)===-1&&b.push($);var P={};g.forEach(function(O){I[O]&&(P[O]=I[O])}),P["card-bg"]=I["card-base"]||I.bg,I.lightBg&&(P.lightBg=!0);var D=t(P);p.forEach(function(O){!P[O]&&D[O]&&(P[O]=D[O])}),d[$]=P,C+=":root."+$+` {
`,g.forEach(function(O){P[O]&&(C+="  --"+O+": "+P[O]+`;
`)}),C+=`}
`,C+=e($,P),C+=o($,P)});var T=document.createElement("style");T.id="user-theme-styles",T.textContent=C,document.head.appendChild(T)}}function y(){secureFetch("/api/v1/themes").then(function(x){return x.json()}).then(function(x){if(!(!x.success||!x.themes)){var B=x.themes,A=safeGetJSON(a,{});if(JSON.stringify(B)!==JSON.stringify(A)){safeSet(a,JSON.stringify(B)),l(B);var E=safeGet(c);E&&b.indexOf(E)!==-1&&k(E)}}}).catch(function(){})}function S(){var x=safeGetJSON(m);if(x){var B=x.name||"Custom",A=i(B),E={name:B};g.forEach(function($){x[$]&&(E[$]=x[$])});var C=safeGetJSON(a,{});C[A]=E,safeSet(a,JSON.stringify(C)),safeGet(c)==="custom"&&safeSet(c,A),safeRemove(m);var T={};g.forEach(function($){E[$]&&(T[$]=E[$])}),fetch("/api/v1/themes/"+A,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:B,colors:T})}).catch(function(){})}}function k(x){document.documentElement.classList.add("theme-transitioning"),b.forEach(function(C){C!=="dark"&&document.documentElement.classList.remove(C)}),n(),x!=="dark"&&document.documentElement.classList.add(x),safeSet(c,x);var B=d[x],A=document.querySelector('meta[name="theme-color"]');A&&B&&A.setAttribute("content",B.bg);var E=B&&B.lightBg;!E&&B&&B.bg&&(E=s(B.bg)>.4),E?document.documentElement.classList.add("light-bg"):document.documentElement.classList.remove("light-bg"),setTimeout(function(){document.documentElement.classList.remove("theme-transitioning")},300)}S(),l();var L=safeGet(c);L==="red"&&(L="black",safeSet(c,"black")),L&&L!=="dark"&&b.indexOf(L)===-1&&(L=null),k(L||u()),y(),window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change",function(x){safeGet(c)||k(x.matches?"dark":"light")}),window.THEMES=b,window.BUILTIN_THEMES=h,window.THEME_COLORS=d,window.THEME_PROPS=g,window.BASE_PROPS=v,window.DERIVED_PROPS=p,window.USER_THEMES_KEY=a,window.applyTheme=k,window.clearCustomProperties=n,window.injectUserThemeStyles=l,window.syncThemesFromServer=y,window.slugifyThemeName=i,window.getActiveTheme=function(){return safeGet(c)||u()},window.deriveExtendedColors=t,window.hexToRgb=r,window.rgbToHex=f,window.blendColors=w})(),(function(){let c=null;async function a(){if(c)return c;try{const w=await fetch("/api/v1/auth/login/methods",{cache:"no-store"});if(!w.ok)throw new Error(`methods HTTP ${w.status}`);const s=await w.json();return c=Array.isArray(s.providers)?s.providers:[],c}catch(w){return console.warn("[auth-gate] methods fetch failed; falling back to TOTP-only",w),[]}}function m(w){const s=document.getElementById("totp-overlay");if(!s)return;const t=s.querySelector(".totp-card");if(!t)return;const e=t.innerHTML;t.dataset.originalBody||(t.dataset.originalBody=e);const o=w.map(u=>{const n=u.config&&(u.config.label||u.name)||u.name;return`<button class="provider-btn" data-provider="${u.name}"
                          style="margin: 6px 4px; padding: 10px 16px; background: var(--accent); color: white; border: 0; border-radius: 6px; cursor: pointer; font-size: 0.95rem;">
        Sign in with ${n}
      </button>`}).join(`
`);t.innerHTML=`
      <img class="totp-logo totp-logo-dark" src="/assets/dashcaddy-logo-dark.png" alt="DashCaddy" onerror="this.style.display='none'">
      <img class="totp-logo totp-logo-light" src="/assets/dashcaddy-logo-light.png" alt="DashCaddy" onerror="this.style.display='none'">
      <p class="subtitle">Choose how to sign in</p>
      <div id="auth-gate-providers" style="margin: 14px 0 10px;">${o}</div>
      <div id="auth-gate-message" style="margin-top: 8px; color: var(--muted); font-size: 0.8rem;"></div>
    `,s.classList.add("show"),t.querySelectorAll(".provider-btn").forEach(u=>{u.addEventListener("click",()=>{const n=u.dataset.provider,i=w.find(l=>l.name===n);b(i)})})}function h(){const w=document.getElementById("totp-overlay");if(!w)return;const s=w.querySelector(".totp-card");!s||!s.dataset.originalBody||(s.innerHTML=s.dataset.originalBody,window.location.reload())}function b(w){const s=document.getElementById("totp-overlay");if(!s)return;const t=s.querySelector(".totp-card");if(t){if(w.name==="totp"){window.location.reload();return}if(w.name==="email"){t.innerHTML=`
        <img class="totp-logo totp-logo-dark" src="/assets/dashcaddy-logo-dark.png" alt="DashCaddy" onerror="this.style.display='none'">
        <img class="totp-logo totp-logo-light" src="/assets/dashcaddy-logo-light.png" alt="DashCaddy" onerror="this.style.display='none'">
        <p class="subtitle">Sign in with email</p>
        <p style="margin: 6px 0 14px; font-size: 0.85rem; color: var(--muted);">
          We'll email you a one-time sign-in link.
        </p>
        <input id="auth-gate-email-input" type="email" inputmode="email" autocomplete="email"
               placeholder="you@example.com"
               style="width: 100%; padding: 10px 12px; font-size: 1rem; background: var(--input-bg); color: var(--text); border: 1px solid var(--border); border-radius: 6px; box-sizing: border-box;">
        <button id="auth-gate-email-submit" class="provider-btn"
                style="margin-top: 14px; padding: 10px 16px; background: var(--accent); color: white; border: 0; border-radius: 6px; cursor: pointer; font-size: 0.95rem; width: 100%;">
          Send sign-in link
        </button>
        <div id="auth-gate-email-status" style="margin-top: 12px; font-size: 0.85rem; line-height: 1.4;"></div>
        <div style="margin-top: 16px;">
          <a href="#" id="auth-gate-back" style="color: var(--muted); font-size: 0.8rem;">\u2190 Back</a>
        </div>
      `,s.classList.add("show");const e=t.querySelector("#auth-gate-email-input"),o=t.querySelector("#auth-gate-email-submit"),u=t.querySelector("#auth-gate-email-status"),n=t.querySelector("#auth-gate-back");o.addEventListener("click",async()=>{const i=(e.value||"").trim();if(!i||!i.includes("@")){u.textContent="Enter a valid email address.",u.style.color="var(--error, #d33)";return}o.disabled=!0,u.textContent="Sending\u2026",u.style.color="";try{const y=await(await fetch("/api/v1/auth/login/email/initiate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:i})})).json();if(y.success){const S=y.deliveredVia||"email",k=y.maskedEmail||i;S==="dev-console"?u.innerHTML=`
                Check the server logs for your one-time link.
                (Dev mode: no SMTP configured. In production this would email <strong>${k}</strong>.)`:u.innerHTML=`Sign-in link sent to <strong>${k}</strong>.
                Check your inbox (and spam folder).`,u.style.color="var(--success, #2a7)"}else u.textContent=y.error||"Could not send link.",u.style.color="var(--error, #d33)",o.disabled=!1}catch{u.textContent="Connection error. Try again.",u.style.color="var(--error, #d33)",o.disabled=!1}}),e.addEventListener("keydown",i=>{i.key==="Enter"&&o.click()}),n.addEventListener("click",i=>{i.preventDefault(),m(providers)});return}console.warn("[auth-gate] unknown provider",w.name),window.location.reload()}}async function g(){if(!document.getElementById("totp-overlay"))return;const s=await a();if(s.length===0){typeof window._showTotpOverlay=="function"&&window._showTotpOverlay();return}if(s.length===1&&s[0].name==="totp"){v(s[0]);return}m(s)}function v(w){const s=c&&c.find(u=>u.name==="email");if(!s){typeof window._showTotpOverlay=="function"&&window._showTotpOverlay();return}const t=document.getElementById("totp-overlay"),e=t.querySelector(".totp-card");if(!e)return;if(e.dataset.originalBody||(e.dataset.originalBody=e.innerHTML),!e.querySelector("#auth-gate-email-alt")){const u=document.createElement("div");u.id="auth-gate-email-alt",u.style.cssText="margin-top: 18px; padding-top: 14px; border-top: 1px solid var(--border); font-size: 0.85rem;",u.innerHTML=`<a href="#" id="auth-gate-email-alt-link"
        style="color: var(--accent); text-decoration: none;">
        Or sign in with email instead \u2192
      </a>`,e.appendChild(u),u.querySelector("#auth-gate-email-alt-link").addEventListener("click",n=>{n.preventDefault(),b(s)})}t.classList.add("show")}window.__dc_049_handled=!0;function p(w){try{const s=new URL(w,window.location.origin);if(!["http:","https:"].includes(s.protocol))return!1;if(s.origin===window.location.origin)return!0;if(s.protocol!=="https:")return!1;const t=SITE.tld.startsWith(".")?SITE.tld:`.${SITE.tld}`;return s.hostname===t.slice(1)||s.hostname.endsWith(t)}catch{return!1}}function d(w,s){const t=new URL(w,window.location.origin);if(t.origin===window.location.origin)return t.toString();const e=SITE.tld.startsWith(".")?SITE.tld:`.${SITE.tld}`,o=t.hostname===e.slice(1)||t.hostname.endsWith(e);if(t.protocol!=="https:"||!o||!s)return null;const u=`${t.pathname}${t.search}${t.hash}`;return t.pathname="/dashcaddy-sso",t.search="",t.hash="",t.searchParams.set("token",s),t.searchParams.set("return",u),t.toString()}async function r(w){if(!w||!p(w))return!1;try{const s=new URL(w,window.location.origin),t=SITE.tld.startsWith(".")?SITE.tld:`.${SITE.tld}`,e=s.hostname.slice(0,-t.length);if(!/^[a-z0-9][a-z0-9-]*$/.test(e))return!1;const o=await fetch(`/api/v1/auth/sso-handoff?serviceId=${encodeURIComponent(e)}`,{credentials:"include",cache:"no-store"});if(!o.ok)return!1;const u=await o.json(),n=u.success&&d(w,u.ssoToken);if(!n)return!1;try{sessionStorage.removeItem("totp_redirect")}catch{}return window.location.replace(n),!0}catch{return!1}}const f=new URLSearchParams(window.location.search);if(f.get("auth")==="required"){const w=f.get("return");if(w&&p(w))try{sessionStorage.setItem("totp_redirect",w)}catch{}window.history.replaceState({},"",window.location.pathname),setTimeout(async()=>{await r(w)||await g()},0)}window._showAuthGate=g,window._authGateMethods=a})(),(function(){function c(){const p=document.querySelector(".totp-card");if(!p)return;const r=getComputedStyle(p).backgroundColor.match(/\d+/g);if(!r)return;const f=(.299*+r[0]+.587*+r[1]+.114*+r[2])/255,w=p.querySelector(".totp-logo-dark"),s=p.querySelector(".totp-logo-light");w&&(w.style.display=f>.5?"none":""),s&&(s.style.display=f>.5?"":"none")}function a(){const p=document.getElementById("totp-overlay");if(p){p.classList.add("show"),setTimeout(c,50);const d=p.querySelector(".totp-digits input");d&&setTimeout(()=>d.focus(),100)}typeof window._refreshRecoveryLink=="function"&&window._refreshRecoveryLink()}function m(){const p=document.getElementById("totp-overlay");p&&p.classList.remove("show")}function h(p,d){const r=new URL(p,window.location.origin);if(r.origin===window.location.origin)return r.toString();const f=SITE.tld.startsWith(".")?SITE.tld:`.${SITE.tld}`,w=r.hostname===f.slice(1)||r.hostname.endsWith(f);if(r.protocol!=="https:"||!w)return null;if(!d)return r.toString();const s=`${r.pathname}${r.search}${r.hash}`;return r.pathname="/dashcaddy-sso",r.search="",r.hash="",r.searchParams.set("token",d),r.searchParams.set("return",s),r.toString()}const b=document.getElementById("totp-digits");if(b){const p=b.querySelectorAll("input");p.forEach((d,r)=>{d.addEventListener("input",f=>{const w=f.target.value.replace(/\D/g,"");f.target.value=w.slice(0,1),w&&r<p.length-1&&p[r+1].focus();const s=Array.from(p).map(t=>t.value).join("");s.length===6&&g(s)}),d.addEventListener("keydown",f=>{f.key==="Backspace"&&!f.target.value&&r>0&&(p[r-1].focus(),p[r-1].value="")}),d.addEventListener("paste",f=>{f.preventDefault();const w=(f.clipboardData.getData("text")||"").replace(/\D/g,"");w.length>=6&&(p.forEach((s,t)=>{s.value=w[t]||""}),p[5].focus(),g(w.slice(0,6)))})})}async function g(p){const d=document.getElementById("totp-error");d.textContent="Verifying...",d.className="totp-error verifying";const r=safeSessionGet("totp_redirect");let f=null;if(r)try{const w=new URL(r,window.location.origin),s=SITE.tld.startsWith(".")?SITE.tld:`.${SITE.tld}`,t=w.hostname.slice(0,-s.length);w.hostname.endsWith(s)&&/^[a-z0-9][a-z0-9-]*$/.test(t)&&(f=t)}catch{}try{const s=await(await secureFetch("/api/v1/totp/verify",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:p,serviceId:f})})).json();if(s.success){if(d.textContent="",s.csrfToken&&(csrfToken=s.csrfToken),m(),r){try{sessionStorage.removeItem("totp_redirect")}catch{}const t=h(r,s.ssoToken);if(!t)return;window.location.href=t;return}typeof window.initializeDashboard=="function"&&window.initializeDashboard(),window._dcAuthLost=!1,typeof window._sseResume=="function"?window._sseResume():typeof window._sseReconnect=="function"&&window._sseReconnect(),typeof window.refreshAll=="function"&&window.refreshAll()}else{d.textContent=s.error||"Invalid code",d.className="totp-error";const t=document.querySelectorAll("#totp-digits input");t.forEach(e=>{e.value=""}),t[0]?.focus()}}catch{d.textContent="Connection error",d.className="totp-error"}}if(!!!window.__dc_049_handled&&urlParams.get("auth")==="required"){const p=urlParams.get("return");if(p)try{const d=new URL(p,window.location.origin),r=d.hostname,f=d.origin===window.location.origin,w=SITE.tld.startsWith(".")?SITE.tld:"."+SITE.tld,s=r.endsWith(w)||r===w.substring(1);(f||s)&&safeSessionSet("totp_redirect",p)}catch{}window.history.replaceState({},"",window.location.pathname)}window._showTotpOverlay=a})(),(function(){"use strict";async function c(){try{return await(await fetch("/api/v1/totp/recovery-info",{cache:"no-store"})).json()}catch{return{success:!1,status:"unknown",hint:"Could not contact server"}}}function a(v){const p=document.getElementById("totp-recovery-link");p&&(p.style.display=v?"":"none")}function m(){const v=document.getElementById("totp-recovery-panel");v&&(v.style.display="");const p=document.getElementById("totp-recovery-status"),d=document.getElementById("totp-recovery-import"),r=document.getElementById("totp-recovery-verify");d&&(d.style.display=""),r&&(r.style.display="none"),document.getElementById("totp-recovery-error").textContent="",document.getElementById("totp-recovery-confirm-error").textContent="",document.getElementById("totp-recovery-secret").value="",document.getElementById("totp-recovery-code").value="",c().then(f=>{p.textContent=f.hint||"",f.status==="healthy"?p.style.borderColor="var(--ok-fg, #7ef2ff)":f.status==="unreadable"?(p.style.borderColor="var(--bad-fg, #ff9aa3)",p.style.background="color-mix(in srgb, var(--bad-fg) 6%, transparent)"):f.status==="not_configured"?p.style.borderColor="var(--muted)":p.style.borderColor="var(--border)"}),setTimeout(()=>{document.getElementById("totp-recovery-secret")?.focus()},100)}function h(){const v=document.getElementById("totp-recovery-panel");v&&(v.style.display="none")}async function b(){const v=document.getElementById("totp-recovery-secret").value.trim(),p=document.getElementById("totp-recovery-error");if(p.textContent="",!v){p.textContent="Paste your Base32 key first";return}if(!/^[A-Za-z2-7\s]+=*$/.test(v)){p.textContent="Invalid Base32 format \u2014 should be letters A-Z and digits 2-7 only";return}try{const d=await fetch("/api/v1/totp/setup",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({secret:v})}),r=await d.json();if(!d.ok||!r.success){p.textContent=r.error||r.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{p.textContent="Network error \u2014 try again"}}async function g(){const v=document.getElementById("totp-recovery-code").value.trim(),p=document.getElementById("totp-recovery-confirm-error");if(p.textContent="",!/^\d{6}$/.test(v)){p.textContent="Enter a 6-digit code";return}try{const d=await fetch("/api/v1/totp/verify-setup",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:v})}),r=await d.json();if(!d.ok||!r.success){p.textContent=r.error||r.message||"Invalid code",document.getElementById("totp-recovery-code").value="",document.getElementById("totp-recovery-code")?.focus();return}h();const f=document.getElementById("totp-overlay");f&&f.classList.remove("show"),typeof window.initializeDashboard=="function"&&window.initializeDashboard()}catch{p.textContent="Network error \u2014 try again"}}document.getElementById("totp-show-recovery")?.addEventListener("click",v=>{v.preventDefault(),m()}),document.getElementById("totp-recovery-close")?.addEventListener("click",h),document.getElementById("totp-recovery-submit")?.addEventListener("click",b),document.getElementById("totp-recovery-confirm")?.addEventListener("click",g),document.getElementById("totp-recovery-secret")?.addEventListener("keydown",v=>{v.key==="Enter"&&(v.preventDefault(),b())}),document.getElementById("totp-recovery-code")?.addEventListener("keydown",v=>{v.key==="Enter"&&(v.preventDefault(),g())}),window._refreshRecoveryLink=async function(){const v=await c();return v&&v.success&&v.status&&v.status!=="healthy"?a(!0):a(!1),v}})(),(function(){function c(h,b){if(!h||!b||!/^[a-z0-9][a-z0-9-]*$/.test(b))return!1;try{const g=new URL(h,window.location.origin),v=SITE.tld.startsWith(".")?SITE.tld:`.${SITE.tld}`,p=`${b}${v}`;return g.protocol==="https:"&&g.hostname===p}catch{return!1}}function a(h,b,g){if(!c(h,g))return null;const v=new URL(h,window.location.origin);if(!b)return null;const p=`${v.pathname}${v.search}${v.hash}`;return v.pathname="/dashcaddy-sso",v.search="",v.hash="",v.searchParams.set("token",b),v.searchParams.set("return",p),v.toString()}async function m(h,b,g={}){if(!c(h,b))return!1;const v=g.fetch||window.fetch.bind(window),p=g.location||window.location;try{const d=await v(`/api/v1/auth/sso-handoff?serviceId=${encodeURIComponent(b)}`,{credentials:"include",cache:"no-store"});if(!d.ok)return!1;const r=await d.json(),f=r.success&&a(h,r.ssoToken,b);return f?(p.replace(f),!0):!1}catch{return!1}}window.DCCredentialVault={isAllowedReturnUrl:c,buildHandoffTarget:a,resume:m}})(),(function(){const c=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;">Encrypted Credential Vault</h3>
      <p id="svc-creds-desc" style="font-size: 0.75rem; color: var(--muted); margin: 0 0 14px;">Passwords are encrypted at rest and used automatically when you open 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 to encrypted vault
        </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 a=document.getElementById("service-creds-modal");let m=null,h=null,b=!1;const g=["sonarr","radarr","prowlarr","overseerr"],v=["sonarr","radarr"];function p(e){return e.externalUrl||e.url||""}function d(e){const o=document.getElementById("svc-creds-error");o.textContent=e,o.style.display=""}function r(){const e=document.getElementById("svc-creds-error");e.textContent="",e.style.display="none"}async function f(e,o){if(!e)throw new Error(`${o} failed: no response`);let u;try{u=await e.json()}catch{throw new Error(`${o} failed: invalid server response`)}if(!e.ok||u?.success!==!0)throw new Error(u?.error||`${o} failed (${e.status||"unknown status"})`);return u}function w(e,o){return!!window.DCCredentialVault?.isAllowedReturnUrl(e,o)}window.openServiceCredsModal=async function(e,o={}){m=e,h=w(o.returnUrl,e.id)?o.returnUrl:null,b=!1,r();const u=document.getElementById("svc-creds-title"),n=document.getElementById("svc-creds-desc"),i=document.getElementById("svc-creds-seedhost"),l=document.getElementById("svc-creds-apikey"),y=document.getElementById("svc-creds-basic"),S=document.getElementById("svc-creds-quality");u.textContent=e.name+" \u2014 Encrypted Vault",document.getElementById("svc-creds-save").textContent=h?"Save to vault & open service":"Save to encrypted vault";const k=!!e.isExternal,L=g.includes(e.id)||g.includes(e.appTemplate),x=v.includes(e.id)||v.includes(e.appTemplate);i.style.display=k?"":"none",l.style.display=L?"":"none",S.style.display=x?"":"none",y.style.display=k?"none":"";const B=document.getElementById("svc-quality-select");B.innerHTML='<option value="">-- Enter API key first --</option>',document.getElementById("svc-quality-status").textContent="",k?(n.textContent="Seedhost credentials auto-login past the HTTP prompt. API key bypasses the app login.",document.getElementById("svc-seedhost-pass").placeholder=`Password for ${e.name}`):L?n.textContent="API key bypasses the app login screen automatically.":n.textContent="Credentials are injected automatically when accessing this service.",await s(e),a.classList.add("show")};async function s(e){const o=document.getElementById("svc-creds-dot"),u=document.getElementById("svc-creds-status"),n=document.getElementById("svc-creds-clear");let i=!1;if(e.isExternal){try{const S=await(await fetch(`/api/v1/seedhost-creds?serviceId=${e.id}`)).json();S.success?(document.getElementById("svc-seedhost-user").value=S.username||"",S.hasCredentials&&(i=!0)):document.getElementById("svc-seedhost-user").value=""}catch{}document.getElementById("svc-seedhost-pass").value=""}try{const S=await(await fetch(`/api/v1/services/${e.id}/credentials`)).json();S.success&&(S.hasApiKey?(document.getElementById("svc-apikey-input").value="\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022",i=!0):document.getElementById("svc-apikey-input").value="",S.hasBasicAuth&&!e.isExternal?(document.getElementById("svc-basic-user").value=S.username||"",i=!0):document.getElementById("svc-basic-user").value="")}catch{}document.getElementById("svc-basic-pass")&&(document.getElementById("svc-basic-pass").value="");const l=e.id||e.appTemplate;if(v.includes(l)&&await t(e),i){b=!0,o.style.background="var(--ok-fg, #74dfc4)",u.style.color="var(--ok-fg, #74dfc4)",u.textContent="Credentials stored",n.style.display="";const y=document.getElementById(`creds-btn-${e.id}`);y&&y.classList.add("has-creds")}else o.style.background="var(--muted)",u.style.color="var(--muted)",u.textContent="No credentials stored",n.style.display="none"}async function t(e){const o=document.getElementById("svc-quality-select"),u=document.getElementById("svc-quality-status"),n=e.id||e.appTemplate,i=p(e);if(!i){o.innerHTML='<option value="">-- No service URL --</option>';return}o.innerHTML='<option value="">Loading...</option>',u.textContent="";try{const l=new URLSearchParams({service:n,url:i}),S=await(await fetch(`/api/v1/arr/quality-profiles?${l}`)).json();if(!S.success||!S.profiles?.length){o.innerHTML='<option value="">-- No profiles found (enter API key and click Fetch) --</option>';return}o.innerHTML="";for(const k of S.profiles){const L=document.createElement("option");L.value=k.id,L.textContent=k.name,o.appendChild(L)}if(S.storedProfileId&&(o.value=String(S.storedProfileId)),!o.value){const k=S.profiles.find(L=>/720/i.test(L.name));k&&(o.value=String(k.id))}!o.value&&S.profiles.length&&(o.value=String(S.profiles[0].id)),u.innerHTML=`<span style="color: var(--ok-fg);">${S.profiles.length} profiles loaded</span>`}catch(l){o.innerHTML='<option value="">-- Failed to load --</option>',u.innerHTML=`<span style="color: var(--error, #c62828);">Error: ${l.message}</span>`}}document.getElementById("svc-quality-fetch")?.addEventListener("click",async()=>{if(!m)return;const e=m.id||m.appTemplate,o=p(m),n=document.getElementById("svc-apikey-input")?.value.trim(),i=document.getElementById("svc-quality-select"),l=document.getElementById("svc-quality-status");if(!o){l.innerHTML='<span style="color: var(--error, #c62828);">No service URL available</span>';return}if(!n||n==="\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022"){l.innerHTML='<span style="color: var(--error, #c62828);">Enter an API key first</span>';return}i.innerHTML='<option value="">Fetching...</option>',l.textContent="";try{const y=new URLSearchParams({service:e,url:o,apiKey:n}),k=await(await fetch(`/api/v1/arr/quality-profiles?${y}`)).json();if(!k.success){i.innerHTML='<option value="">-- Error --</option>',l.innerHTML=`<span style="color: var(--error, #c62828);">${k.error||"Failed to fetch profiles"}</span>`;return}if(!k.profiles?.length){i.innerHTML='<option value="">-- No profiles found --</option>';return}i.innerHTML="";for(const x of k.profiles){const B=document.createElement("option");B.value=x.id,B.textContent=x.name,i.appendChild(B)}const L=k.profiles.find(x=>/720/i.test(x.name));L?i.value=String(L.id):k.profiles.length&&(i.value=String(k.profiles[0].id)),l.innerHTML=`<span style="color: var(--ok-fg);">${k.profiles.length} profiles loaded</span>`}catch(y){i.innerHTML='<option value="">-- Error --</option>',l.innerHTML=`<span style="color: var(--error, #c62828);">${y.message}</span>`}}),document.getElementById("svc-creds-save")?.addEventListener("click",async()=>{if(!m)return;const e=document.getElementById("svc-creds-save");e.textContent="Saving...",e.disabled=!0,r();try{const o=g.includes(m.id)||g.includes(m.appTemplate),u=m.id||m.appTemplate;if(h&&!b){const l=document.getElementById("svc-seedhost-user").value.trim(),y=document.getElementById("svc-seedhost-pass").value,k=document.getElementById("svc-apikey-input")?.value.trim(),L=document.getElementById("svc-basic-user").value.trim(),x=document.getElementById("svc-basic-pass").value,B=m.isExternal&&l&&y,A=o&&k&&k!=="\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022",E=!m.isExternal&&L&&x;if(!B&&!A&&!E){d("Enter the login or API key DashCaddy should store for this service."),e.textContent="Save to vault & open service",e.disabled=!1;return}}if(m.isExternal){const l=document.getElementById("svc-seedhost-user").value.trim(),y=document.getElementById("svc-seedhost-pass").value;if(l){const S=await secureFetch("/api/v1/seedhost-creds",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:l,password:y||void 0,serviceId:m.id})});await f(S,"Seedhost credential save")}}const i=document.getElementById("svc-apikey-input")?.value.trim();if(i&&i!=="\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022")if(o){const l=p(m),y=document.getElementById("svc-quality-select"),S=y?.value?parseInt(y.value):void 0,k=y?.selectedOptions?.[0]?.textContent||void 0,L=await secureFetch("/api/v1/arr/credentials",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({service:u,apiKey:i,url:l||void 0,qualityProfileId:S||void 0,qualityProfileName:k||void 0})}),x=await f(L,"ARR credential save");x.connectionTest&&!x.connectionTest.success&&d(`API key saved but connection test failed: ${x.connectionTest.error}`)}else{const l=await secureFetch(`/api/v1/services/${m.id}/credentials`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:i})});await f(l,"API key save")}else if(o&&v.includes(u)){const l=document.getElementById("svc-quality-select"),y=l?.value?parseInt(l.value):void 0,S=l?.selectedOptions?.[0]?.textContent||void 0;if(y){const k=await secureFetch("/api/v1/arr/quality-profiles",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({service:u,qualityProfileId:y,qualityProfileName:S})});await f(k,"Quality profile save")}}if(!m.isExternal){const l=document.getElementById("svc-basic-user").value.trim(),y=document.getElementById("svc-basic-pass").value;if(l&&y){const S=await secureFetch(`/api/v1/services/${m.id}/credentials`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:l,password:y})});await f(S,"Service credential save")}}if(await s(m),h){const l=h;if(!await window.DCCredentialVault?.resume(l,m.id))throw new Error("Credential saved, but the secure service handoff failed. Try opening the service again.");h=null;return}}catch(o){c.logError("[ServiceCredentials] Save",o,{function:"saveCredentials"}),d("Failed to save: "+(o.message||"Unknown error"))}e.textContent=h?"Save to vault & open service":"Save to encrypted vault",e.disabled=!1}),document.getElementById("svc-creds-clear")?.addEventListener("click",async()=>{if(m&&confirm(`Remove stored credentials for ${m.name}?`)){r();try{const e=m.id||m.appTemplate,o=g.includes(e);if(m.isExternal){const i=await secureFetch(`/api/v1/seedhost-creds?serviceId=${m.id}`,{method:"DELETE"});await f(i,"Seedhost credential removal")}const u=await secureFetch(`/api/v1/services/${m.id}/credentials`,{method:"DELETE"});if(await f(u,"Service credential removal"),o){const i=await secureFetch(`/api/v1/arr/credentials/${e}`,{method:"DELETE"});await f(i,"ARR credential removal")}const n=document.getElementById(`creds-btn-${m.id}`);n&&n.classList.remove("has-creds"),await s(m)}catch(e){c.logError("[ServiceCredentials] Clear",e,{function:"clearCredentials"}),d("Failed to clear: "+(e.message||"Unknown error"))}}}),document.getElementById("svc-creds-close")?.addEventListener("click",()=>{a.classList.remove("show"),m=null,h=null}),a?.addEventListener("click",e=>{e.target===a&&(a.classList.remove("show"),m=null,h=null)}),window.refreshCredsButtons=async function(){try{for(const e of window.APPS||[]){if(!e.isExternal&&!e.appTemplate&&!e.url)continue;let o=!1;if(e.isExternal)try{const i=await(await fetch(`/api/v1/seedhost-creds?serviceId=${e.id}`)).json();i.success&&i.hasCredentials&&(o=!0)}catch{}try{const i=await(await fetch(`/api/v1/services/${e.id}/credentials`)).json();i.success&&(i.hasApiKey||i.hasBasicAuth)&&(o=!0)}catch{}const u=document.getElementById(`creds-btn-${e.id}`);u&&u.classList.toggle("has-creds",o)}}catch{}},window.openRequestedCredentialForm=function(){const e=new URLSearchParams(window.location.search),o=e.get("credentials");if(!o)return!1;const u=(window.APPS||[]).find(i=>i.id===o||i.appTemplate===o);if(!u)return!1;const n=e.get("return");return window.history.replaceState({},"",window.location.pathname),window.openServiceCredsModal(u,{returnUrl:n}),!0}})(),(function(){const c=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 a(){try{const v=await(await fetch("/api/v1/totp/config")).json();if(!v.success)return;const{enabled:p,sessionDuration:d,isSetUp:r}=v.config,f=document.getElementById("totp-status-dot"),w=document.getElementById("totp-status-text"),s=document.getElementById("totp-status-banner"),t=document.getElementById("totp-setup-section"),e=document.getElementById("totp-qr-section"),o=document.getElementById("totp-duration-section"),u=document.getElementById("totp-disable-section");if(p&&r){f.style.background="var(--ok-fg, #7ef2ff)",s.style.borderColor="var(--ok-fg, #7ef2ff)",s.style.background="color-mix(in srgb, var(--ok-fg) 8%, transparent)",w.textContent="TOTP is active",w.style.color="var(--ok-fg, #7ef2ff)",t.style.display="block";const n=document.getElementById("totp-setup-btn");n&&(n.textContent="Generate New Secret"),e.style.display="none",o.style.display="block",u.style.display="block",document.getElementById("totp-duration-select").value=d}else f.style.background="var(--muted)",s.style.borderColor="var(--border)",s.style.background="transparent",w.textContent="TOTP is not configured",w.style.color="var(--muted)",t.style.display="block",e.style.display="none",o.style.display="none",u.style.display="none";b(p&&r,d)}catch(g){console.warn("Failed to load TOTP settings:",g)}}const m={"15m":"15 min","30m":"30 min","1h":"1 hour","2h":"2 hours","4h":"4 hours","8h":"8 hours","12h":"12 hours","24h":"24 hours",never:"Disabled"};function h(g,v){const p=window.DCI18n;return p&&p.isLoaded()?p.t(g):v}function b(g,v){const p=document.getElementById("auth-card"),d=document.getElementById("auth-pill"),r=document.getElementById("auth-dot"),f=document.getElementById("auth-status-text");p&&(g?(p.setAttribute("data-status","on"),d.className="badge on",d.textContent=h("card.status.yes","YES"),r.className="dot ok at-bl",f.textContent="Session: "+(m[v]||v)):(p.setAttribute("data-status","off"),d.className="badge off",d.textContent=h("card.status.no","NO"),r.className="dot bad at-bl",f.textContent=h("card.auth.not_configured","Not configured")))}document.getElementById("totp-setup-btn")?.addEventListener("click",async()=>{try{const v=await(await secureFetch("/api/v1/totp/setup",{method:"POST"})).json();v.success&&(document.getElementById("totp-qr-image").src=v.qrCode,document.getElementById("totp-manual-key").textContent=v.manualKey,document.getElementById("totp-setup-section").style.display="none",document.getElementById("totp-qr-section").style.display="block",document.getElementById("totp-setup-code").value="",document.getElementById("totp-setup-error").textContent="",document.getElementById("totp-setup-code").focus())}catch(g){c.logError("[TOTP] Setup Failed",g,{function:"setupTOTP"})}}),document.getElementById("totp-import-btn")?.addEventListener("click",async()=>{const g=document.getElementById("totp-import-key").value.trim(),v=document.getElementById("totp-import-error");if(v.textContent="",!g){v.textContent="Paste a Base32 secret key first";return}try{const d=await(await secureFetch("/api/v1/totp/setup",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({secret:g})})).json();d.success?(v.textContent="",document.getElementById("totp-qr-image").src=d.qrCode,document.getElementById("totp-manual-key").textContent=d.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()):v.textContent=d.error||d.message||"Import failed"}catch{v.textContent="Connection error \u2014 try refreshing the page"}}),document.getElementById("totp-copy-key")?.addEventListener("click",()=>{const g=document.getElementById("totp-manual-key").textContent;navigator.clipboard.writeText(g).then(()=>{const v=document.getElementById("totp-copy-key");v.textContent="\u2705",setTimeout(()=>{v.textContent="\u{1F4CB}"},2e3)})}),document.getElementById("totp-download-backup")?.addEventListener("click",()=>{const g=document.getElementById("totp-manual-key").textContent.trim();if(!g)return;const v={service:"DashCaddy",type:"totp-secret",secret:g,issuer:"DashCaddy",algorithm:"SHA1",digits:6,period:30,issued:new Date().toISOString(),recovery_url:`${window.location.origin}/  (login screen \u2192 "Lost access?")`,note:'Keep this file somewhere safe. Anyone with this secret can generate your login codes. Use it ONLY to recover TOTP access via the "Lost access?" link on the DashCaddy login screen.'},p=new Blob([JSON.stringify(v,null,2)],{type:"application/json"}),d=URL.createObjectURL(p),r=document.createElement("a");r.href=d,r.download=`dashcaddy-totp-backup-${new Date().toISOString().slice(0,10)}.json`,document.body.appendChild(r),r.click(),document.body.removeChild(r),URL.revokeObjectURL(d);const f=document.getElementById("totp-download-backup");f.textContent="\u2705 Saved",setTimeout(()=>{f.textContent="\u2B07 Download"},2e3)}),document.getElementById("totp-confirm-setup")?.addEventListener("click",async()=>{const g=document.getElementById("totp-setup-code").value,v=document.getElementById("totp-setup-error");if(!/^\d{6}$/.test(g)){v.textContent="Enter a 6-digit code";return}try{const d=await(await secureFetch("/api/v1/totp/verify-setup",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:g})})).json();d.success?(v.textContent="",a()):v.textContent=d.error||"Invalid code"}catch{v.textContent="Connection error"}}),document.getElementById("totp-setup-code")?.addEventListener("keydown",g=>{g.key==="Enter"&&document.getElementById("totp-confirm-setup")?.click()}),document.getElementById("totp-duration-select")?.addEventListener("change",async g=>{try{await secureFetch("/api/v1/totp/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionDuration:g.target.value})}),a()}catch(v){c.logError("[TOTP] Update Session Duration",v,{function:"updateSessionDuration"})}}),document.getElementById("totp-disable-btn")?.addEventListener("click",async()=>{if(confirm("Disable TOTP authentication? All services will be accessible without a code."))try{(await(await secureFetch("/api/v1/totp/disable",{method:"POST",headers:{"Content-Type":"application/json"},body:"{}"})).json()).success&&a()}catch(g){c.logError("[TOTP] Disable Failed",g,{function:"disableTOTP"})}}),document.getElementById("auth-settings-btn")?.addEventListener("click",()=>{a(),openModal("totp-settings-modal")}),document.getElementById("totp-modal-close")?.addEventListener("click",()=>{closeModal("totp-settings-modal")}),document.getElementById("totp-settings-modal")?.addEventListener("click",g=>{g.target.id==="totp-settings-modal"&&closeModal("totp-settings-modal")}),window._updateAuthCard=b,(async()=>{try{const v=await(await fetch("/api/v1/totp/config")).json();if(v.success){const p=v.config.enabled&&v.config.isSetUp;b(p,v.config.sessionDuration)}}catch(g){c.logError("[TOTP] AuthCard Update",g,{function:"authCardUpdate"})}})()})(),(function(){"use strict";const c={me:"/api/v1/auth/me",users:"/api/v1/auth/admin/users",allowlist:"/api/v1/auth/admin/allowlist",invites:"/api/v1/auth/admin/invites"};function a(s,t,...e){const o=document.createElement(s);if(t)for(const u of Object.keys(t)){const n=t[u];n==null||n===!1||(u==="class"?o.className=n:u==="text"?o.textContent=n:u==="html"?o.innerHTML=n:u.startsWith("on")&&typeof n=="function"?o.addEventListener(u.slice(2).toLowerCase(),n):o.setAttribute(u,n))}for(const u of e)u==null||u===!1||(typeof u=="string"?o.appendChild(document.createTextNode(u)):o.appendChild(u));return o}async function m(s,t){const e=window.SITE&&window.SITE.csrfToken||"";t=t||{},t.headers=Object.assign({"Content-Type":"application/json"},t.headers||{},e?{"X-CSRF-Token":e}:{}),t.body&&typeof t.body!="string"&&(t.body=JSON.stringify(t.body));const o=await fetch(s,t),u=await o.json().catch(()=>({}));if(!o.ok){const n=u&&(u.message||u.error)||"HTTP "+o.status,i=new Error(n);throw i.status=o.status,i}return u}function h(s){const t={admin:"background:#7c3aed;color:#fff",operator:"background:#2563eb;color:#fff",viewer:"background:#6b7280;color:#fff"};return a("span",{class:"role-badge",style:"display:inline-block;padding:2px 8px;border-radius:4px;font-size:0.75rem;font-weight:600;text-transform:uppercase;"+(t[s]||t.viewer),text:s})}function b(s,t,e){if(s.innerHTML="",!t||t.length===0){s.appendChild(a("p",{style:"color:var(--muted)",text:"No users yet."}));return}const o=a("table",{style:"width:100%;border-collapse:collapse;font-size:0.9rem"});o.appendChild(a("thead",null,a("tr",{style:"border-bottom:1px solid var(--border)"},a("th",{style:"text-align:left;padding:8px",text:"Email"}),a("th",{style:"text-align:left;padding:8px",text:"Role"}),a("th",{style:"text-align:left;padding:8px",text:"Created"}),a("th",{style:"text-align:left;padding:8px",text:"Last login"}),a("th",{style:"text-align:right;padding:8px",text:"Actions"}))));const u=a("tbody");for(const n of t){const i=a("tr",{style:"border-bottom:1px solid var(--border)"}),l=a("td",{style:"padding:8px"});l.appendChild(a("span",{text:n.email||"(no email)"})),n.displayName&&n.displayName!==(n.email||"").split("@")[0]&&(l.appendChild(a("br")),l.appendChild(a("small",{style:"color:var(--muted)",text:n.displayName}))),i.appendChild(l);const y=a("td",{style:"padding:8px"});y.appendChild(h(n.role)),i.appendChild(y),i.appendChild(a("td",{style:"padding:8px;color:var(--muted);font-size:0.85rem",text:n.createdAt?new Date(n.createdAt).toLocaleDateString():"\u2014"})),i.appendChild(a("td",{style:"padding:8px;color:var(--muted);font-size:0.85rem",text:n.lastLoginAt?new Date(n.lastLoginAt).toLocaleString():"\u2014"}));const S=a("td",{style:"padding:8px;text-align:right"}),k=a("select",{style:"padding:2px 6px;margin-right:6px",onchange:async x=>{try{await m(c.users+"/"+encodeURIComponent(n.id),{method:"PATCH",body:{role:x.target.value}}),e&&e()}catch(B){window.errorHandler&&window.errorHandler.show("Role update failed: "+B.message),x.target.value=n.role}}});for(const x of["admin","operator","viewer"]){const B=a("option",{value:x,text:x});x===n.role&&(B.selected=!0),k.appendChild(B)}S.appendChild(k);const L=a("button",{class:"btn-sm",style:"padding:2px 8px",text:"Delete",onclick:async()=>{if(confirm("Delete user "+(n.email||n.id)+"? This cannot be undone."))try{await m(c.users+"/"+encodeURIComponent(n.id),{method:"DELETE"}),e&&e()}catch(x){window.errorHandler&&window.errorHandler.show("Delete failed: "+x.message)}}});S.appendChild(L),i.appendChild(S),u.appendChild(i)}o.appendChild(u),s.appendChild(o)}function g(s,t){const e=a("form",{style:"display:flex;gap:8px;flex-wrap:wrap;align-items:end",onsubmit:async u=>{u.preventDefault();const n=new FormData(u.target),i={email:n.get("email"),role:n.get("role"),ttlHours:parseInt(n.get("ttlHours"),10)||24,sendEmail:n.get("sendEmail")==="on"};try{const l=await m(c.invites,{method:"POST",body:i});u.target.reset(),t&&t(l)}catch(l){window.errorHandler&&window.errorHandler.show("Invite failed: "+l.message)}}});e.appendChild(a("label",{style:"display:flex;flex-direction:column;gap:2px;font-size:0.85rem"},a("span",{text:"Email"}),a("input",{name:"email",type:"email",required:!0,placeholder:"user@example.com",style:"padding:6px"})));const o=a("select",{name:"role",style:"padding:6px"});for(const u of["operator","viewer","admin"])o.appendChild(a("option",{value:u,text:u}));e.appendChild(a("label",{style:"display:flex;flex-direction:column;gap:2px;font-size:0.85rem"},a("span",{text:"Role"}),o)),e.appendChild(a("label",{style:"display:flex;flex-direction:column;gap:2px;font-size:0.85rem"},a("span",{text:"TTL (hours)"}),a("input",{name:"ttlHours",type:"number",min:"1",max:"168",value:"24",style:"padding:6px;width:80px"}))),e.appendChild(a("label",{style:"display:flex;gap:4px;align-items:center;font-size:0.85rem"},a("input",{name:"sendEmail",type:"checkbox",checked:!1}),a("span",{text:"Also send via email (optional)"}))),e.appendChild(a("button",{type:"submit",class:"btn-sm",style:"padding:6px 12px",text:"Issue invite"})),s.appendChild(e)}function v(s,t,e){if(s.innerHTML="",!t||t.length===0){s.appendChild(a("p",{style:"color:var(--muted)",text:"No outstanding invites."}));return}const o=a("table",{style:"width:100%;border-collapse:collapse;font-size:0.9rem"});o.appendChild(a("thead",null,a("tr",{style:"border-bottom:1px solid var(--border)"},a("th",{style:"text-align:left;padding:8px",text:"Email"}),a("th",{style:"text-align:left;padding:8px",text:"Role"}),a("th",{style:"text-align:left;padding:8px",text:"Invited by"}),a("th",{style:"text-align:left;padding:8px",text:"Expires"}),a("th",{style:"text-align:right;padding:8px",text:"Actions"}))));const u=a("tbody");for(const n of t){const i=a("tr",{style:"border-bottom:1px solid var(--border)"});i.appendChild(a("td",{style:"padding:8px",text:n.email})),i.appendChild(a("td",{style:"padding:8px"},h(n.role))),i.appendChild(a("td",{style:"padding:8px;color:var(--muted)",text:n.invitedBy||"\u2014"})),i.appendChild(a("td",{style:"padding:8px;color:var(--muted);font-size:0.85rem",text:n.expiresAt?new Date(n.expiresAt).toLocaleString():"\u2014"}));const l=a("td",{style:"padding:8px;text-align:right"});l.appendChild(a("button",{class:"btn-sm",style:"padding:2px 8px",text:"Revoke",onclick:async()=>{if(confirm("Revoke invite for "+n.email+"?"))try{await m(c.invites+"/"+encodeURIComponent(n.id),{method:"DELETE"}),e&&e()}catch(y){window.errorHandler&&window.errorHandler.show("Revoke failed: "+y.message)}}})),i.appendChild(l),u.appendChild(i)}o.appendChild(u),s.appendChild(o)}function p(s,t){const e=a("div",{style:"margin-top:12px;padding:12px;border:1px solid #16a34a;border-radius:6px;background:#052e1a;color:#bbf7d0;font-size:0.85rem"});e.appendChild(a("strong",{text:"Invite issued \u2014 copy the link below. It will not be shown again."})),e.appendChild(a("br")),e.appendChild(a("code",{style:"display:block;margin-top:8px;padding:8px;background:#000;border-radius:4px;word-break:break-all;color:#d1fae5",text:s.acceptUrl}));const o=a("button",{class:"btn-sm",style:"margin-top:8px;padding:4px 10px",text:"Copy link",onclick:async()=>{try{await navigator.clipboard.writeText(s.acceptUrl),o.textContent="Copied!",setTimeout(()=>{o.textContent="Copy link"},2e3)}catch{window.errorHandler&&window.errorHandler.show("Clipboard blocked: select the link manually.")}}});if(e.appendChild(o),s.shareText){const u=a("div",{style:"margin-top:12px"});u.appendChild(a("div",{style:"font-size:0.8rem;color:#86efac;margin-bottom:4px",text:"Share this message:"})),u.appendChild(a("div",{style:"padding:8px;background:#000;border-radius:4px;color:#d1fae5;white-space:pre-wrap",text:s.shareText}));const n=a("div",{style:"margin-top:6px;display:flex;gap:6px;flex-wrap:wrap"}),i=a("button",{class:"btn-sm",style:"padding:4px 10px",text:"Copy message",onclick:async()=>{try{await navigator.clipboard.writeText(s.shareText),i.textContent="Copied!",setTimeout(()=>{i.textContent="Copy message"},2e3)}catch{window.errorHandler&&window.errorHandler.show("Clipboard blocked: select the text manually.")}}});if(n.appendChild(i),typeof navigator<"u"&&typeof navigator.share=="function"){const l=a("button",{class:"btn-sm",style:"padding:4px 10px",text:"Share via\u2026",onclick:async()=>{try{await navigator.share({title:"DashCaddy invite",text:s.shareText,url:s.acceptUrl})}catch(y){y&&y.name&&y.name!=="AbortError"&&window.errorHandler&&window.errorHandler.show("Share failed: "+y.message)}}});n.appendChild(l)}u.appendChild(n),e.appendChild(u)}s.deliveredVia==="failed"?e.appendChild(a("p",{style:"margin-top:8px;color:#fbbf24;font-size:0.8rem",text:"Email could not be sent (SMTP not configured). Share the link above instead \u2014 it works the same way."})):s.deliveredVia==="email"?e.appendChild(a("p",{style:"margin-top:8px;color:#86efac;font-size:0.8rem",text:"Email sent to "+s.email+"."})):s.deliveredVia==="manual"&&e.appendChild(a("p",{style:"margin-top:8px;color:#86efac;font-size:0.8rem",text:"Share the link above via text, chat, or any messenger."})),t.appendChild(e)}async function d(s){s.innerHTML="",s.appendChild(a("h2",{style:"margin:0 0 16px",text:"Admin \xB7 Users & Invites"}));const t=await m(c.me).catch(()=>({}));if(!t||!t.user||t.user.role!=="admin"){s.appendChild(a("p",{style:"color:var(--muted)",text:"Admin role required to view this panel. If multi-user mode is enabled and you should have access, check /api/v1/auth/me."}));return}const e=a("button",{class:"btn-sm",style:"float:right;padding:4px 10px",text:"Refresh",onclick:()=>d(s)});s.appendChild(e);const o=a("h3",{style:"margin:24px 0 8px;clear:both",text:"Users"});s.appendChild(o);const u=a("div",{id:"admin-users-list"});s.appendChild(u);const n=await m(c.users).catch(()=>({users:[]}));b(u,n.users,()=>d(s)),s.appendChild(a("h4",{style:"margin:24px 0 8px;font-size:0.95rem",text:"Pre-authorize email"}));const i=a("form",{style:"display:flex;gap:8px;align-items:end",onsubmit:async k=>{k.preventDefault();const L=k.target.email.value.trim();if(L)try{await m(c.users,{method:"POST",body:{email:L}}),k.target.reset(),d(s)}catch(x){window.errorHandler&&window.errorHandler.show("Add failed: "+x.message)}}});i.appendChild(a("input",{name:"email",type:"email",required:!0,placeholder:"user@example.com",style:"padding:6px"})),i.appendChild(a("button",{type:"submit",class:"btn-sm",style:"padding:6px 12px",text:"Add to allowlist"})),s.appendChild(i),s.appendChild(a("h3",{style:"margin:24px 0 8px",text:"Issue invite"}));const l=a("div");s.appendChild(l);const y=a("div",{id:"admin-invites-list",style:"margin-top:16px"});s.appendChild(y);const S=await m(c.invites).catch(()=>({invites:[]}));v(y,S.invites,()=>d(s)),g(l,k=>{p(k,l),d(s)})}async function r(){if(document.getElementById("admin-panel-root"))return;const t=a("div",{id:"admin-panel-root",style:"position:fixed;inset:0;background:rgba(0,0,0,0.5);z-index:1000;display:flex;align-items:center;justify-content:center;",onclick:u=>{u.target===t&&f()}}),e=a("div",{style:"background:var(--card-base,#1f2937);color:var(--text,#f3f4f6);border-radius:8px;padding:24px;max-width:900px;width:90%;max-height:85vh;overflow:auto;position:relative;box-shadow:0 10px 30px rgba(0,0,0,0.3)"});e.appendChild(a("button",{class:"btn-sm",style:"position:absolute;top:12px;right:12px;padding:4px 10px",text:"Close",onclick:f}));const o=a("div",{id:"admin-panel-body"});e.appendChild(o),t.appendChild(e),document.body.appendChild(t);try{await d(o)}catch(u){o.innerHTML='<p style="color:#f87171">Failed to load admin panel: '+(u.message||u)+"</p>"}}function f(){const s=document.getElementById("admin-panel-root");s&&s.remove()}async function w(s){async function t(){const e=await m(c.me).catch(()=>({})),o=document.getElementById("admin-trigger-btn");if(e&&e.user&&e.user.role==="admin"){if(o)return;const u=a("button",{id:"admin-trigger-btn",class:"btn-sm",style:"margin-left:8px;padding:6px 12px",text:"Admin",onclick:r});s?s.appendChild(u):document.body&&document.body.appendChild(u)}else o&&o.remove()}await t(),setInterval(t,6e4)}window.AdminPanel={open:r,close:f,attachTrigger:w}})(),(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 c(){return Object.keys(SITE.dnsServers||{})}function a(n){return(SITE.dnsServers||{})[n]?.name||n.toUpperCase()}async function m(n,i){if(!n)throw new Error(`${i} failed: no response`);let l;try{l=await n.json()}catch{throw new Error(`${i} failed: invalid server response`)}if(!n.ok||l?.success!==!0)throw new Error(l?.error||`${i} failed (${n.status||"unknown status"})`);return l}function h(){const n=document.getElementById("dns-cred-sections");if(!n)return;n.innerHTML="";const i=c();if(i.length===0){n.innerHTML='<p style="color: var(--muted); text-align: center; padding: 20px;">No DNS servers configured.</p>';return}for(const l of i)n.insertAdjacentHTML("beforeend",`
      <div class="token-section">
        <h4 class="token-section-title">${a(l)}</h4>
        <div class="token-grid">
          <div class="token-field">
            <label for="${l}-readonly-username">\u{1F4D6} Read-Only (Logs):</label>
            <input type="text" id="${l}-readonly-username" placeholder="Username" autocomplete="off" style="margin-bottom: 4px;" />
            <div class="token-input-row">
              <input type="password" id="${l}-readonly-token" placeholder="Password" autocomplete="off" />
              <button type="button" class="token-toggle" data-target="${l}-readonly-token">\u{1F441}</button>
            </div>
          </div>
          <div class="token-field">
            <label for="${l}-admin-username">\u{1F527} Admin:</label>
            <input type="text" id="${l}-admin-username" placeholder="Username" autocomplete="off" style="margin-bottom: 4px;" />
            <div class="token-input-row">
              <input type="password" id="${l}-admin-token" placeholder="Password" autocomplete="off" />
              <button type="button" class="token-toggle" data-target="${l}-admin-token">\u{1F441}</button>
            </div>
          </div>
        </div>
        <div class="token-status" id="${l}-token-status"></div>
      </div>
      `)}function b(){let n=safeSessionGet("dashcaddy-encryption-key");if(n)return n;const i=safeGet("dashcaddy-encryption-key");if(i)return safeSessionSet("dashcaddy-encryption-key",i),safeRemove("dashcaddy-encryption-key"),i;const l=new Uint8Array(32);return crypto.getRandomValues(l),n=Array.from(l,y=>y.toString(16).padStart(2,"0")).join(""),safeSessionSet("dashcaddy-encryption-key",n),n}const g=b();function v(n,i){if(!n)return"";const l=crypto.getRandomValues(new Uint8Array(8)),y=Array.from(l,L=>L.toString(16).padStart(2,"0")).join(""),S=new TextEncoder().encode(i+y);let k="";for(let L=0;L<n.length;L++){const x=n.charCodeAt(L)^S[L%S.length]^l[L%l.length]^L*31+17&255;k+=String.fromCharCode(x)}return y+":"+btoa(k)}function p(n,i){if(!n)return"";try{if(n.indexOf(":")===16){const k=n.substring(0,16),L=new Uint8Array(k.match(/.{2}/g).map(E=>parseInt(E,16))),x=atob(n.substring(17)),B=new TextEncoder().encode(i+k);let A="";for(let E=0;E<x.length;E++){const C=x.charCodeAt(E)^B[E%B.length]^L[E%L.length]^E*31+17&255;A+=String.fromCharCode(C)}return A}const y=atob(n);let S="";for(let k=0;k<y.length;k++){const L=y.charCodeAt(k)^i.charCodeAt(k%i.length);S+=String.fromCharCode(L)}return S}catch{return""}}function d(n,i,l){const y=safeGet(`${n}-${i}-${l}-enc`);return p(y,g)}function r(n,i,l,y){const S=`${n}-${i}-${l}-enc`;y?safeSet(S,v(y,g)):safeRemove(S)}function f(n,i){return d(n,i,"token")}function w(n,i){return d(n,i,"username")}function s(n,i,l){r(n,i,"token",l)}function t(n,i,l){r(n,i,"username",l)}function e(){const n={};for(const i of c())n[i]={readonly:{username:w(i,"readonly"),token:f(i,"readonly")},admin:{username:w(i,"admin"),token:f(i,"admin")}};return n}function o(){c().forEach(n=>{["readonly","admin"].forEach(i=>{["token","username"].forEach(l=>{safeRemove(`${n}-${i}-${l}-enc`)})}),safeRemove(`${n}-token-enc`),safeRemove(`${n}-username-enc`)})}function u(n){const i=f(n,"readonly"),l=w(n,"readonly"),y=f(n,"admin"),S=w(n,"admin"),k=p(safeGet(`${n}-token-enc`),g),L=p(safeGet(`${n}-username-enc`),g);return{username:S||l||L,token:y||i||k,readonlyToken:i||k,readonlyUsername:l||L,adminToken:y||k,adminUsername:S||L}}document.getElementById("manage-tokens")?.addEventListener("click",()=>{h();const n=document.getElementById("token-management-modal"),i=e();c().forEach(l=>{const y=i[l];document.getElementById(`${l}-readonly-username`).value=y.readonly.username,document.getElementById(`${l}-readonly-token`).value=y.readonly.token,document.getElementById(`${l}-admin-username`).value=y.admin.username,document.getElementById(`${l}-admin-token`).value=y.admin.token,document.getElementById(`${l}-token-status`).textContent=""}),n.classList.add("show")}),document.getElementById("token-management-modal")?.addEventListener("click",n=>{const i=n.target.closest(".token-toggle");if(i){const l=i.dataset.target,y=document.getElementById(l);y.type==="password"?(y.type="text",i.textContent="\u{1F648}"):(y.type="password",i.textContent="\u{1F441}");return}n.target.id==="token-management-modal"&&n.target.classList.remove("show")}),document.getElementById("token-save")?.addEventListener("click",async()=>{const n=c(),i={};let l=!1;if(n.forEach(y=>{const S={},k=document.getElementById(`${y}-readonly-username`).value.trim(),L=document.getElementById(`${y}-readonly-token`).value.trim(),x=document.getElementById(`${y}-admin-username`).value.trim(),B=document.getElementById(`${y}-admin-token`).value.trim();k&&L&&(S.readonly={username:k,password:L},l=!0),x&&B&&(S.admin={username:x,password:B},l=!0),Object.keys(S).length>0&&(i[y]=S)}),l){n.forEach(y=>{i[y]&&(document.getElementById(`${y}-token-status`).textContent="Verifying...",document.getElementById(`${y}-token-status`).className="token-status")});try{const y=await secureFetch("/api/v1/dns/credentials",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({servers:i})}),S=await m(y,"DNS credential save");if(S.results){const k=Object.keys(i).filter(L=>S.results[L]?.success!==!0);if(k.length){const L=k.map(x=>S.results[x]?.error||`${x} failed`).join("; ");throw new Error(L)}}n.forEach(k=>{t(k,"readonly",document.getElementById(`${k}-readonly-username`).value.trim()),s(k,"readonly",document.getElementById(`${k}-readonly-token`).value.trim()),t(k,"admin",document.getElementById(`${k}-admin-username`).value.trim()),s(k,"admin",document.getElementById(`${k}-admin-token`).value.trim())}),n.forEach(k=>{const L=document.getElementById(`${k}-token-status`);if(!i[k]){L.textContent="";return}const x=S.results?.[k];L.textContent=x?.partial?"\u2713 "+x.partial:"\u2713 Verified & saved",L.className="token-status success"})}catch(y){console.error("Failed to sync DNS credentials to backend:",y),n.forEach(S=>{i[S]&&(document.getElementById(`${S}-token-status`).textContent="\u2717 "+(y.message||"Save failed"),document.getElementById(`${S}-token-status`).className="token-status error")})}}else n.forEach(y=>{document.getElementById(`${y}-token-status`).textContent=""});setTimeout(()=>{n.every(S=>{const k=document.getElementById(`${S}-token-status`)?.textContent;return!k||k.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."))try{const n=await secureFetch("/api/v1/dns/credentials",{method:"DELETE"});await m(n,"DNS credential removal"),o(),c().forEach(i=>{document.getElementById(`${i}-readonly-username`).value="",document.getElementById(`${i}-readonly-token`).value="",document.getElementById(`${i}-admin-username`).value="",document.getElementById(`${i}-admin-token`).value="",document.getElementById(`${i}-token-status`).textContent="\u2713 Cleared",document.getElementById(`${i}-token-status`).className="token-status success"})}catch(n){c().forEach(i=>{document.getElementById(`${i}-token-status`).textContent="\u2717 "+(n.message||"Clear failed"),document.getElementById(`${i}-token-status`).className="token-status error"})}}),window.getToken=f,window.getUsername=w,window.setToken=s,window.setUsername=t,window.getAllCredentials=e,window.getCredential=d,window.setCredential=r,window.getEncryptionKey=b,window.getDnsIds=c,window.getDnsDisplayName=a})(),(function(){function c(s){const t=window.DCI18n;return!t||!t.isLoaded()?s?"ON":"OFF":t.t(s?"card.status.on":"card.status.off")}function a(s,t,e=null){const o=document.getElementById(s+"-dot"),u=document.getElementById(s+"-pill"),n=document.getElementById(s+"-time"),i=document.querySelector(`[data-app="${s}"]`);o&&(o.classList.toggle("ok",t),o.classList.toggle("bad",!t)),u&&(u.textContent=c(t),u.classList.toggle("on",t),u.classList.toggle("off",!t)),n&&e!==null&&(n.textContent=t?`${e}ms`:"timeout",n.className=`response-time ${m(e,t)}`),i&&i.setAttribute("data-status",t?"on":"off")}function m(s,t){return t?s<200?"excellent":s<500?"good":s<1e3?"fair":"slow":"timeout"}async function h(s){const t=performance.now();try{const e=await fetch("/probe/"+s,{cache:"no-store"}),o=performance.now(),u=Math.round(o-t);return{isUp:e.status>=200&&e.status<400||e.status===401||e.status===403,responseTime:u}}catch{const e=performance.now();return{isUp:!1,responseTime:Math.round(e-t)}}}window.APPS=[];let b=null,g=!1;async function v(){try{window.SkeletonLoader&&window.SkeletonLoader.show(6);const s=await fetch("/api/v1/services",{cache:"no-store"});if(s.ok){const t=await s.json();window.APPS=t.services||[],window.SkeletonLoader&&window.SkeletonLoader.hide()}else console.error("Failed to load services:",s.status),window.SkeletonLoader&&window.SkeletonLoader.hide()}catch(s){console.error("Failed to load services:",s),window.SkeletonLoader&&window.SkeletonLoader.hide()}}function p(s){const t=window.APPS?.find(o=>o.id===s);if(t?.url)return t.url.startsWith("http")?t.url:"https://"+t.url;if(t?.isExternal&&t.externalUrl)return t.externalUrl;const e=SITE.dnsServers?.[s];return e?"http://"+e.ip+":"+(e.port||5380):buildServiceUrl(s)}function d(s,t,e){const o=document.createElement(s);return t&&(o.className=t),e&&(o.textContent=e),o}function r(){const s=document.getElementById("cards");s.innerHTML="";for(let t=0;t<window.APPS.length;t++){const e=window.APPS[t];if(e.id==="ca")continue;const o=d("div","card");o.setAttribute("data-app",e.id),o.setAttribute("data-status","off"),e.containerId&&o.setAttribute("data-container-id",e.containerId),e.category&&o.setAttribute("data-category",e.category),e.recipeId&&o.setAttribute("data-recipe-id",e.recipeId);const u=d("span","dot bad at-bl");u.id="dot-"+e.id+"-grid",o.appendChild(u);const n=d("div","row"),i=d("div","logo-wrap"),l=document.createElement("img");l.src=e.logo,l.alt=e.name,l.className="logo-img",l.onerror=function(){let I=e.id||e.appTemplate;if(!I&&e.name&&(I=e.name.toLowerCase().replace(/\s+/g,"-")),I){const P=[`https://cdn.jsdelivr.net/gh/walkxcode/dashboard-icons/png/${I}.png`,`https://cdn.jsdelivr.net/gh/walkxcode/dashboard-icons/png/${I.toLowerCase()}.png`,`https://cdn.jsdelivr.net/gh/walkxcode/dashboard-icons/png/${I.replace(/-/g,"")}.png`,`https://cdn.jsdelivr.net/gh/walkxcode/dashboard-icons/png/${e.name.toLowerCase().replace(/\s+/g,"-")}.png`],D=[...new Set(P)],N=D.indexOf(this.src)+1;N<D.length?this.src=D[N]:this.style.display="none"}else this.style.display="none"},i.appendChild(l),n.appendChild(i);const y=d("span","name",e.name);if(n.appendChild(y),e.tailscaleOnly){const I=d("span","ts-badge","\u{1F510}");I.title="Tailscale-only access",I.style.cssText="margin-left: 6px; font-size: 0.75rem; opacity: 0.8;",y.appendChild(I)}if(e.category){const P=(typeof DC<"u"&&DC.CATEGORIES||window.DC_CATEGORIES||{})[e.category]||{},D=d("span","cat-badge",`${P.icon||""} ${e.category}`.trim());D.title=`Category: ${e.category}`,D.style.cssText=`margin-left: 6px; font-size: 0.65rem; padding: 1px 6px; border-radius: 999px; background: color-mix(in srgb, ${P.color||"#7f8c8d"} 25%, transparent); color: ${P.color||"#7f8c8d"}; border: 1px solid color-mix(in srgb, ${P.color||"#7f8c8d"} 50%, transparent); white-space: nowrap; font-weight: 500;`,y.appendChild(D)}n.appendChild(d("span","spacer"));const S=d("span","badge off","OFF");S.id="badge-"+e.id,S.setAttribute("data-i18n-live-status","binary"),n.appendChild(S);const k=d("span","update-available-badge","UPDATE");k.id="update-badge-"+e.id,k.title="Update available",n.appendChild(k),o.appendChild(n);const L=d("div","response-row"),x=d("span","response-time","--");x.id="time-"+e.id,L.appendChild(x),o.appendChild(L);const B=d("div","health-row");B.id="health-"+e.id;const A=d("span","uptime-chip","--");A.id="uptime-"+e.id,B.appendChild(A);const E=document.createElement("div");E.className="uptime-mini-bar";const C=document.createElement("div");C.className="fill",C.id="uptime-bar-"+e.id,C.style.width="0%",E.appendChild(C),B.appendChild(E),o.appendChild(B);const T=d("div","btn-row");if(e.containerId){const I=d("button","logs-btn","\u{1F4CB}");I.title="View container logs",I.onclick=O=>{O.stopPropagation(),window.openContainerLogsModal(e.containerId,e.name)},T.appendChild(I);const P=d("button","update-btn","\u2B06\uFE0F");P.title="Update container to latest version",P.id=`update-btn-${e.id}`,P.onclick=O=>{O.stopPropagation(),window.updateContainer(e.containerId,e.name,e.id)},T.appendChild(P);const D=d("button","exec-btn",">_");D.title="Open terminal",D.onclick=O=>{O.stopPropagation(),window.openExecModal&&window.openExecModal(e.containerId,e.name)},T.appendChild(D)}if(e.logPath&&!e.containerId){const I=d("button","logs-btn","\u{1F4CB}");I.title="View application logs",I.onclick=P=>{P.stopPropagation(),window.openFileLogsModal(e.logPath,e.name)},T.appendChild(I)}if(e.isExternal||e.appTemplate||e.url){const I=d("button","creds-btn","\u{1F511}");I.title="Auto-login credentials",I.id=`creds-btn-${e.id}`,I.onclick=P=>{P.stopPropagation(),window.openServiceCredsModal(e)},T.appendChild(I)}if(e.id!=="internet"){const I=d("button","options-btn","\u2699\uFE0F");I.title="Edit service settings",I.onclick=P=>{P.stopPropagation(),window.openServiceEditModal(e)},T.appendChild(I)}if(e.id!=="internet"){const I=d("button","share-btn","\u{1F517}");I.title="Share this service (Pro)",I.onclick=P=>{P.stopPropagation(),typeof window.openShareModal=="function"?window.openShareModal(e):typeof window.showNotification=="function"&&window.showNotification("Share modal not loaded. Refresh the page.","error")},T.appendChild(I)}if(e.id!=="internet"){const I=d("button","delete-btn","\u{1F5D1}\uFE0F");I.title="Delete this service",I.onclick=P=>{P.stopPropagation(),window.deleteService(e.id,e.name)},T.appendChild(I)}const $=d("button",null,"Open");$.setAttribute("data-i18n","action.open"),$.onclick=()=>window.open(p(e.id),"_blank","noopener"),T.appendChild($),o.appendChild(T),o.style.transitionDelay=`${Math.min(t*45,270)}ms`,s.appendChild(o)}window.DCI18n&&window.DCI18n.isLoaded()&&window.DCI18n.applyTranslations(),requestAnimationFrame(()=>{s.querySelectorAll(".card").forEach(t=>t.classList.add("loaded"))}),window.groupRecipeCards&&requestAnimationFrame(()=>window.groupRecipeCards()),window.refreshServiceFilter&&window.refreshServiceFilter()}function f(s,t,e=null){const o=document.getElementById("dot-"+s+"-grid"),u=document.getElementById("badge-"+s),n=document.getElementById("time-"+s),i=document.querySelector(`[data-app="${s}"]`);o&&(o.classList.toggle("ok",t),o.classList.toggle("bad",!t)),u&&(u.textContent=c(t),u.classList.toggle("on",t),u.classList.toggle("off",!t)),n&&e!==null&&(n.textContent=t?`${e}ms`:"timeout",n.className=`response-time ${m(e,t)}`),i&&i.setAttribute("data-status",t?"on":"off")}async function w(){if(window._dcAuthLost)return;if(b)return g=!0,b;function s(o,u=new Date){const n=document.getElementById("stamp");n&&(n.textContent=`${o}: ${new Date(u).toLocaleTimeString()}`)}function t(o){Object.keys(SITE.dnsServers).forEach(n=>{const i=o[n];i&&a(n,i.isUp,i.responseTime)}),o.internet&&a("internet",o.internet.isUp,o.internet.responseTime),window.APPS.forEach(n=>{const i=o[n.id];i&&f(n.id,i.isUp,i.responseTime)})}async function e(){const o=Object.keys(SITE.dnsServers),u=o.map(y=>h(y));u.push(h("internet"));const n=await Promise.all(u);o.forEach((y,S)=>a(y,n[S].isUp,n[S].responseTime));const i=n[n.length-1];a("internet",i.isUp,i.responseTime),(await Promise.all(window.APPS.map(async y=>{const S=await h(y.id);return{id:y.id,...S}}))).forEach(y=>{f(y.id,y.isUp,y.responseTime)})}return b=(async()=>{try{const o=await fetch("/api/v1/services/status",{cache:"no-store"});if(o.status===401||o.status===403){window._dcAuthLost=!0,window._sseReconnect&&window._sseClose&&window._sseClose(),s("auth required");return}if(!o.ok)throw new Error(`Status refresh failed (${o.status})`);window._dcAuthLost=!1;const u=await o.json();t(u.statuses||{}),s("last check",u.checkedAt||new Date)}catch(o){console.warn("Batched status refresh failed, falling back to direct probes:",o);try{await e(),s("last check")}catch(u){console.error("Dashboard refresh failed:",u),s("last failed")}}finally{b=null,g&&!window._dcAuthLost?(g=!1,setTimeout(()=>{window.refreshAll()},0)):g=!1}})(),b}document.querySelector(".top")?.addEventListener("click",s=>{const t=s.target.closest('[id$="-open"]');if(!t)return;const e=t.id.replace("-open","");SITE.dnsServers[e]&&window.open(p(e),"_blank","noopener")}),document.getElementById("ca-open")?.addEventListener("click",()=>window.open(p("ca"),"_blank","noopener")),document.getElementById("creds-btn-ca")?.addEventListener("click",s=>{s.stopPropagation();const t=window.APPS.find(e=>e.id==="ca");t&&window.openServiceCredsModal&&window.openServiceCredsModal(t)}),document.getElementById("options-btn-ca")?.addEventListener("click",s=>{s.stopPropagation();const t=window.APPS.find(e=>e.id==="ca");t&&window.openServiceEditModal&&window.openServiceEditModal(t)}),document.getElementById("delete-btn-ca")?.addEventListener("click",s=>{s.stopPropagation(),window.deleteService&&window.deleteService("ca","DashCA")}),window.loadServices=v,window.buildGrid=r,window.refreshAll=w,window.setQuick=a,window.setBadge=f,window.getResponseTimeClass=m,window.checkServiceWithTiming=h,window.serviceUrl=p,window.el=d})(),(function(){async function c(p){const r=await(await secureFetch(`/api/v1/dns/restart/${p}`,{method:"POST"})).json();if(!r.success)throw new Error(r.error||"Restart failed");return r}document.querySelector(".top")?.addEventListener("click",async p=>{const d=p.target.closest('[id$="-restart"]');if(!d)return;const r=d.id.replace("-restart","");if(SITE.dnsServers[r]&&confirm(`Restart ${r.toUpperCase()} service?`))try{await withButton(d,"...",()=>c(r)),setTimeout(window.refreshAll,DC.DELAYS.RELOAD)}catch(f){showNotification("Restart failed: "+f.message,"error")}});async function a(p,d){const r=document.getElementById(`${p}-update`),f=r?.textContent||"\u2B06\uFE0F";try{r.textContent="\u{1F50D}",r.disabled=!0,r.title="Checking for updates...";const s=await(await fetch(`/api/v1/dns/check-update?server=${encodeURIComponent(d)}`)).json();if(!s.success)throw new Error(s.error||"Failed to check for updates");if(!s.updateAvailable){r.textContent="\u2705",r.title=`Already on latest version (${s.currentVersion})`,showNotification(`${p.toUpperCase()} is already up to date! Current version: ${s.currentVersion}`,"info"),setTimeout(()=>{r.textContent=f,r.disabled=!1,r.title="Update DNS server"},3e3);return}if(!confirm(`Update available for ${p.toUpperCase()}!

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

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

`:"")+`The DNS server will restart during the update.
Proceed?`)){r.textContent=f,r.disabled=!1,r.title="Update DNS server";return}r.textContent="\u{1F504}",r.title="Updating...";const o=await(await secureFetch(`/api/v1/dns/update?server=${encodeURIComponent(d)}`,{method:"POST"})).json();if(!o.success)throw new Error(o.error||"Update failed");if(o.manualUpdateRequired){r.textContent="\u2B06\uFE0F",r.title=`Update available: ${o.newVersion}`;const u=o.downloadLink?`
Download: ${o.downloadLink}`:"",n=o.instructionsLink?`
Instructions: ${o.instructionsLink}`:"";showNotification(`${p.toUpperCase()} update requires manual installation. Current: ${o.previousVersion} \u2192 ${o.newVersion}. Please update manually on the host machine.`,"warning",8e3),r.disabled=!1;return}r.textContent="\u2705",r.title="Updated successfully!",showNotification(`${p.toUpperCase()} updated successfully! ${o.previousVersion} \u2192 ${o.newVersion}. Server is restarting...`,"success"),setTimeout(()=>{r.textContent=f,r.disabled=!1,r.title="Update DNS server",window.refreshAll()},1e4)}catch(w){console.error("DNS update error:",w),r.textContent="\u274C",r.title="Update failed",showNotification(`Failed to update ${p.toUpperCase()}: ${w.message}`,"error"),setTimeout(()=>{r.textContent=f,r.disabled=!1,r.title="Update DNS server"},3e3)}}document.querySelector(".top")?.addEventListener("click",p=>{const d=p.target.closest('[id$="-update"]');if(!d)return;const r=d.id.replace("-update","");SITE.dnsServers[r]&&a(r,SITE.dnsServers[r]?.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 m=null;function h(p){m=p;const d=SITE.dnsServers[p]||{},r=document.getElementById("dns-settings-modal");document.getElementById("dns-settings-title").textContent=`${(d.name||p).toUpperCase()} Settings`,document.getElementById("dns-edit-ip").value=d.ip||"",document.getElementById("dns-edit-port").value=d.port||DC.DEFAULTS.DNS_PORT,document.getElementById("dns-edit-name").value=d.name||"",r.classList.add("show")}async function b(){if(!m)return;const p=document.getElementById("dns-edit-ip").value.trim(),d=document.getElementById("dns-edit-port").value.trim()||DC.DEFAULTS.DNS_PORT,r=document.getElementById("dns-edit-name").value.trim();if(!p){showNotification("Server IP is required","warning");return}const f={dnsServers:{}};f.dnsServers[m]={ip:p,port:String(d)},r&&(f.dnsServers[m].name=r);try{const s=await(await secureFetch("/api/v1/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(f)})).json();s.success?(SITE.dnsServers[m]=f.dnsServers[m],showNotification(`${m.toUpperCase()} settings saved`,"success"),v(),window.refreshAll()):showNotification(s.error||"Failed to save settings","error")}catch(w){showNotification("Failed to save: "+w.message,"error")}}async function g(){if(m&&confirm(`Remove ${m.toUpperCase()} from dashboard? This won't affect the actual DNS server.`))try{const d=await(await secureFetch("/api/v1/config")).json();d.dnsServers&&delete d.dnsServers[m];const f=await(await secureFetch("/api/v1/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({dnsServers:d.dnsServers||{}})})).json();if(f.success){delete SITE.dnsServers[m];const w=document.querySelector(`.top [data-app="${m}"]`);w&&w.remove(),showNotification(`${m.toUpperCase()} removed from dashboard`,"success"),v()}else showNotification(f.error||"Failed to remove","error")}catch(p){showNotification("Failed to remove: "+p.message,"error")}}function v(){closeModal("dns-settings-modal"),m=null}document.getElementById("dns-settings-cancel")?.addEventListener("click",v),document.getElementById("dns-settings-save")?.addEventListener("click",b),document.getElementById("dns-settings-delete")?.addEventListener("click",g),document.getElementById("dns-settings-modal")?.addEventListener("click",p=>{p.target.id==="dns-settings-modal"&&v()}),document.querySelector(".top")?.addEventListener("click",p=>{const d=p.target.closest('[id$="-settings"]');if(!d)return;const r=d.id.replace("-settings","");SITE.dnsServers[r]&&(p.stopPropagation(),h(r))}),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 c=null,a=null,m=!1,h=null,b=null,g=!1,v=null,p=null,d=!1,r=null,f=!1;async function w(E,C=25){try{const T=getDnsServerAddr(E),$=await fetch(`/api/v1/dns/logs?server=${T}&limit=${C}`,{cache:"no-store",headers:{Accept:"application/json","Cache-Control":"no-cache"}});if($.ok){const I=await $.json();return I.success&&I.logs?{logs:I.logs,count:I.count,server:I.server}:{error:I.error||"Failed to fetch logs"}}else return $.status===401?{error:"DNS auto-auth failed - check credentials in settings"}:{error:`HTTP ${$.status}`}}catch(T){return console.error("DNS logs fetch failed:",T),{error:T.message}}}function s(E){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"}[E]||"var(--fg)"}function t(E){const C=document.createElement("div");if(C.className="log-entry",C.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;",E.parsed===!1)return C.style.gridTemplateColumns="1fr",C.innerHTML=`<span style="color: var(--muted); font-family: monospace; font-size: 0.75rem;">${escapeHtml(E.raw)}</span>`,C;const T=s(E.rcode),$=E.rcode==="Refused"||E.rcode==="REFUSED";return C.innerHTML=`
      <span style="color: var(--muted); font-size: 0.75rem;">${escapeHtml(E.timestamp)}</span>
      <span style="color: var(--accent); font-size: 0.75rem;" title="${escapeHtml(E.client)}">${escapeHtml(E.client)}</span>
      <span style="font-weight: 500; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; ${$?"text-decoration: line-through; opacity: 0.6;":""}" title="${escapeHtml(E.domain)}">${escapeHtml(E.domain)}</span>
      <span style="color: var(--muted); font-size: 0.75rem;">${escapeHtml(E.type)}</span>
      <span style="color: ${T}; font-weight: 500; font-size: 0.75rem;">${escapeHtml(E.rcode)}</span>
    `,C}async function e(){if(d){await B();return}if(g){await S();return}if(m||!c)return;const E=parseInt(document.getElementById("log-lines").value),C=document.getElementById("logs-content");try{const T=await w(c,E);if(T.error){C.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(T.error)}</div>
          </div>`;return}C.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>`,T.logs&&T.logs.length>0?T.logs.forEach($=>{const I=t($);C.appendChild(I)}):C.innerHTML+=`
          <div style="padding: 20px; text-align: center; color: var(--muted);">
            No DNS queries logged yet
          </div>`}catch(T){C.innerHTML=`
        <div style="padding: 20px; text-align: center; color: var(--bad-fg);">
          Failed to fetch logs: ${escapeHtml(T.message)}
        </div>`}}function o(E){c=E,m=!1,g=!1;const C=document.getElementById("logs-modal"),T=document.getElementById("logs-title"),$=document.getElementById("logs-pause"),I=document.getElementById("logs-stream");T.textContent=`${E.toUpperCase()} DNS Logs`,$.textContent="\u23F8\uFE0F Pause",$.classList.remove("paused"),I&&(I.style.display="none"),C.classList.add("show"),e(),a=setInterval(e,DC.POLL.LOGS)}function u(){document.getElementById("logs-modal").classList.remove("show"),a&&(clearInterval(a),a=null),i(),c=null,g=!1,h=null,b=null,d=!1,v=null,p=null,m=!1}function n(E){r&&i();const C=document.getElementById("logs-stream"),T=document.getElementById("logs-pause"),$=document.getElementById("logs-content");a&&(clearInterval(a),a=null);try{r=new EventSource(`/api/v1/logs/stream/${E}`),f=!0,C.classList.add("active"),C.textContent="\u{1F534} Live",C.title="Streaming - click to stop",T.style.display="none";const I=document.getElementById("logs-title");I.textContent.includes("\u{1F534}")||(I.innerHTML=I.textContent.replace("\u{1F4CB}","\u{1F4CB} \u{1F534}")),r.onmessage=P=>{try{const D=JSON.parse(P.data);if(D.error){console.error("Stream error:",D.error),i();return}const O=document.createElement("div");O.className="log-entry",O.style.cssText="display: flex; gap: 12px; padding: 6px 10px; border-bottom: 1px solid var(--border); font-size: 0.8rem; align-items: flex-start; font-family: monospace;";const _=(D.stream||"stdout")==="stderr",R=_?"var(--bad-fg)":"var(--fg)",M=`<span style="background: ${_?"var(--bad-bg)":"var(--ok-bg)"}; color: ${R}; padding: 2px 6px; border-radius: 4px; font-size: 0.7rem; font-weight: 600; min-width: 50px; text-align: center;">${_?"STDERR":"STDOUT"}</span>`;for(O.innerHTML=`
            <div style="flex-shrink: 0;">${M}</div>
            <div style="flex: 1; color: ${R}; word-break: break-all; white-space: pre-wrap;">${escapeHtml(D.text)}</div>
          `,$.appendChild(O),$.scrollTop=$.scrollHeight;$.children.length>500;)$.removeChild($.firstChild)}catch(D){console.error("Error parsing stream data:",D)}},r.onerror=P=>{console.error("EventSource error:",P),i()}}catch(I){console.error("Failed to start streaming:",I),i()}}function i(){r&&(r.close(),r=null),f=!1;const E=document.getElementById("logs-stream"),C=document.getElementById("logs-pause"),T=document.getElementById("logs-title");E&&(E.classList.remove("active"),E.textContent="\u{1F4E1} Live",E.title="Enable real-time streaming"),C&&(C.style.display=""),T&&(T.textContent=T.textContent.replace(" \u{1F534}","")),g&&h&&!a&&(a=setInterval(S,DC.POLL.LOGS))}async function l(E,C=100){try{const T=`/api/v1/logs/container/${E}?tail=${C}&timestamps=true`,$=await fetch(T,{cache:"no-store",headers:{Accept:"application/json","Cache-Control":"no-cache"}});if($.ok){const I=await $.json();return I.success&&I.logs?{logs:I.logs,count:I.count,containerName:I.containerName,containerId:I.containerId}:{error:I.error||"Failed to fetch container logs"}}else return{error:`HTTP ${$.status}: ${$.statusText}`}}catch(T){return console.error("Container logs fetch failed:",T),{error:T.message}}}function y(E){const C=document.createElement("div");C.className="log-entry",C.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 T=E.stream==="stderr"?"var(--bad-fg)":"var(--fg)",$=E.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 C.innerHTML=`
      <div style="flex-shrink: 0;">${$}</div>
      <div style="flex: 1; color: ${T}; word-break: break-all; white-space: pre-wrap;">${escapeHtml(E.text)}</div>
    `,C}async function S(){if(m||!h||!g)return;const E=parseInt(document.getElementById("log-lines").value),C=document.getElementById("logs-content");try{const T=await l(h,E);if(T.error){C.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(T.error)}</div>
          </div>`;return}C.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>`,T.logs&&T.logs.length>0?(T.logs.forEach($=>{const I=y($);C.appendChild(I)}),C.scrollTop=C.scrollHeight):C.innerHTML+=`
          <div style="padding: 20px; text-align: center; color: var(--muted);">
            No logs available for this container
          </div>`}catch(T){C.innerHTML=`
        <div style="padding: 20px; text-align: center; color: var(--bad-fg);">
          Failed to fetch logs: ${escapeHtml(T.message)}
        </div>`}}function k(E,C){h=E,b=C,g=!0,d=!1,m=!1,i();const T=document.getElementById("logs-modal"),$=document.getElementById("logs-title"),I=document.getElementById("logs-pause"),P=document.getElementById("logs-stream");$.textContent=`\u{1F4CB} ${C} - Container Logs`,I.textContent="\u23F8\uFE0F Pause",I.classList.remove("paused"),P&&(P.style.display=""),T.classList.add("show"),S(),a=setInterval(S,DC.POLL.LOGS)}async function L(E,C=100){try{const T=`/api/v1/logs/file?path=${encodeURIComponent(E)}&tail=${C}`,$=await fetch(T,{cache:"no-store",headers:{Accept:"application/json","Cache-Control":"no-cache"}});if($.ok){const I=await $.json();return I.success&&I.logs?{logs:I.logs,count:I.count,logPath:I.logPath,totalLines:I.totalLines}:{error:I.error||"Failed to fetch file logs"}}else return{error:(await $.json().catch(()=>({}))).error||`HTTP ${$.status}`}}catch(T){return console.error("File logs fetch failed:",T),{error:T.message}}}function x(E){const C=document.createElement("div");C.className="log-entry",C.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 T=E.text;let $="INFO",I="var(--fg)";T.match(/ERROR|FATAL|CRITICAL/i)?($="ERROR",I="var(--bad-fg)"):T.match(/WARN|WARNING/i)?($="WARN",I="#f39c12"):T.match(/DEBUG/i)&&($="DEBUG",I="var(--muted)");const D=`<span style="background: ${I==="var(--bad-fg)"?"var(--bad-bg)":"var(--ok-bg)"}; color: ${I}; padding: 2px 6px; border-radius: 4px; font-size: 0.7rem; font-weight: 600; min-width: 50px; text-align: center;">${$}</span>`;return C.innerHTML=`
      <div style="flex-shrink: 0;">${D}</div>
      <div style="flex: 1; color: ${I}; word-break: break-all; white-space: pre-wrap;">${escapeHtml(T)}</div>
    `,C}async function B(){if(m||!v||!d)return;const E=parseInt(document.getElementById("log-lines").value),C=document.getElementById("logs-content");try{const T=await L(v,E);if(T.error){C.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(T.error)}</div>
          </div>`;return}C.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 (${T.count} of ${T.totalLines} lines)</span>
        </div>`,T.logs&&T.logs.length>0?(T.logs.forEach($=>{const I=x($);C.appendChild(I)}),C.scrollTop=C.scrollHeight):C.innerHTML+=`
          <div style="padding: 20px; text-align: center; color: var(--muted);">
            No logs available in this file
          </div>`}catch(T){C.innerHTML=`
        <div style="padding: 20px; text-align: center; color: var(--bad-fg);">
          Failed to fetch logs: ${escapeHtml(T.message)}
        </div>`}}function A(E,C){v=E,p=C,d=!0,g=!1,m=!1;const T=document.getElementById("logs-modal"),$=document.getElementById("logs-title"),I=document.getElementById("logs-pause"),P=document.getElementById("logs-stream");$.textContent=`\u{1F4CB} ${C} - Application Logs`,I.textContent="\u23F8\uFE0F Pause",I.classList.remove("paused"),P&&(P.style.display="none"),T.classList.add("show"),B(),a=setInterval(B,DC.POLL.LOGS)}document.querySelector(".top")?.addEventListener("click",E=>{const C=E.target.closest('[id$="-logs"]');if(!C)return;const T=C.id.replace("-logs","");SITE.dnsServers[T]&&o(T)}),document.getElementById("logs-close")?.addEventListener("click",u),document.getElementById("logs-pause")?.addEventListener("click",()=>{m=!m;const E=document.getElementById("logs-pause");m?(E.textContent="\u25B6\uFE0F Resume",E.classList.add("paused")):(E.textContent="\u23F8\uFE0F Pause",E.classList.remove("paused"),e())}),document.getElementById("log-lines")?.addEventListener("change",()=>{m||e()}),document.getElementById("logs-stream")?.addEventListener("click",()=>{!g||!h||(f?i():n(h))}),document.getElementById("logs-modal")?.addEventListener("click",E=>{E.target.id==="logs-modal"&&u()}),document.addEventListener("keydown",E=>{E.key==="Escape"&&document.getElementById("logs-modal")?.classList.contains("show")&&u()}),window.openContainerLogsModal=k,window.openFileLogsModal=A,window.openLogsModal=o})(),(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 c(g){try{const v=await fetch(`/api/v1/caddy/cas?caddyfilePath=${encodeURIComponent(g)}`);if(!v.ok)throw new Error(`Failed to load CAs: ${v.status}`);const p=await v.json();if(p.success){const d=document.getElementById("existing-ca-select");return d.innerHTML="",p.cas.length===0?d.innerHTML='<option value="">No CAs found in Caddyfile</option>':(d.innerHTML='<option value="">Select existing CA...</option>',p.cas.forEach(r=>{const f=document.createElement("option");typeof r=="object"?(f.value=r.id,f.textContent=r.displayName||r.name):(f.value=r,f.textContent=r),d.appendChild(f)})),p.data.cas}else throw new Error(p.message)}catch(v){console.error("Error loading CAs:",v);const p=document.getElementById("existing-ca-select");return p.innerHTML='<option value="">Error loading CAs</option>',[]}}function a(g){const{subdomain:v,port:p,ip:d,sslType:r,caName:f,existingCa:w,enableAuth:s,enableCors:t,customHeaders:e,upstreamPath:o,healthCheck:u,timeout:n,tailscaleOnly:i}=g;let l=`${buildDomain(v)} {
`;switch(i&&(l+=`  @blocked not remote_ip 100.64.0.0/10
`,l+=`  respond @blocked "Access denied. Tailscale connection required." 403
`),r){case"letsencrypt":break;case"caddy-managed":l+=`  tls internal
`;break;case"existing-ca":w&&(l+=`  tls {
    ca ${w}
  }
`);break;case"custom-ca":f&&(l+=`  tls {
    ca ${f}
  }
`);break}if(s&&(l+=`  basicauth {
    admin $2a$14$hashed_password_here
  }
`),t&&(l+=`  header {
`,l+=`    Access-Control-Allow-Origin "*"
`,l+=`    Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS"
`,l+=`    Access-Control-Allow-Headers "Content-Type, Authorization"
`,l+=`  }
`),e)try{const y=JSON.parse(e);l+=`  header {
`,Object.entries(y).forEach(([S,k])=>{l+=`    ${S} "${k}"
`}),l+=`  }
`}catch{console.warn("Invalid JSON in custom headers")}return u&&(l+=`  health_uri ${u}
`),l+=`  reverse_proxy ${d}:${p} {
`,o&&o!=="/"&&(l+=`    rewrite ${o}
`),n&&n!==30&&(l+=`    transport http {
`,l+=`      dial_timeout ${n}s
`,l+=`      response_header_timeout ${n}s
`,l+=`    }
`),l+=`  }
`,l+=`}
`,l}async function m(g,v,p=DC.DEFAULTS.TTL){const d=window.getToken(getPrimaryDnsId(),"admin");if(!d)throw new Error("DNS admin token not configured. Please set it in the Tokens menu.");const r=buildDomain(g),f=await secureFetch("/api/v1/dns/record",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:r,ip:v,ttl:p,token:d,server:SITE.dnsIp})});if(!f.ok){const s=await f.text();throw new Error(`DNS API Error: ${f.status} - ${s}`)}const w=await f.json();if(!w.success)throw new Error(`DNS Error: ${w.error||"Unknown error"}`);return w}async function h(g){const v={id:g.subdomain,name:g.name,logo:g.logo||`/assets/${g.subdomain}.png`};g.category&&(v.category=g.category),g.containerId&&(v.containerId=g.containerId);try{const p=await secureFetch("/api/v1/services",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(v)});if(!p.ok){const d=await p.json();throw new Error(d.error||"Failed to save service")}return await window.loadServices(),window.buildGrid(),v}catch(p){throw console.error("Failed to add service to config:",p),p}}async function b(g){const v=document.getElementById("service-subdomain-input").value.trim(),p=document.getElementById("service-ip-input").value.trim()||"localhost",d=document.getElementById("service-port-input").value.trim()||"80",r=await secureFetch("/api/v1/site",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:buildDomain(v),upstream:`${p}:${d}`,config:g})}),f=await r.json();if(!r.ok||!f.success)throw new Error(f.error||`Caddy API Error: ${r.status}`);return f}window.loadExistingCAs=c,window.generateCaddyConfig=a,window.createDnsRecord=m,window.addServiceToConfig=h,window.addToCaddyfile=b})(),(function(){let c=null;function a(p){c=p;const d=document.getElementById("service-edit-modal");document.getElementById("service-edit-title").textContent=`Edit ${p.name}`,document.getElementById("edit-service-name").value=p.name,document.getElementById("edit-service-url-display").textContent=p.url||buildServiceUrl(p.id),document.getElementById("edit-service-logo-preview").src=p.logo||`/assets/${p.id}.png`,document.getElementById("edit-subdomain").value=p.id,document.getElementById("edit-port").value=p.port||"",document.getElementById("edit-ip").value=p.ip||"localhost",document.getElementById("edit-tailscale-only").checked=p.tailscaleOnly||!1,document.getElementById("edit-logo-url").value=p.logo||"";const r=document.getElementById("edit-service-category");r&&(r.dataset.current=p.category||"",typeof window.populateCategorySelects=="function"&&window.populateCategorySelects()),d.classList.add("show")}function m(){closeModal("service-edit-modal"),c=null}async function h(){if(!c)return;const p=document.getElementById("edit-subdomain").value.trim().toLowerCase(),d=document.getElementById("edit-service-name").value.trim(),r=document.getElementById("edit-port").value.trim(),f=document.getElementById("edit-ip").value.trim()||"localhost",w=document.getElementById("edit-tailscale-only").checked,s=document.getElementById("edit-logo-url").value.trim(),t=document.getElementById("edit-service-category")?.value||"";if(!p){showNotification("Subdomain is required","warning");return}const e=c.id,o=[];if(p!==e&&o.push("subdomain"),d&&d!==c.name&&o.push("name"),r&&r!==String(c.port)&&o.push("port"),f!==c.ip&&o.push("ip"),w!==(c.tailscaleOnly||!1)&&o.push("tailscale"),s&&s!==c.logo&&o.push("logo"),t!==(c.category||"")&&o.push("category"),o.length===0){m();return}const u=document.getElementById("service-edit-save");u.textContent="Saving...",u.disabled=!0;try{const i=await(await secureFetch("/api/v1/services/update",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({oldSubdomain:e,newSubdomain:p,name:d||c.name,port:r||c.port,ip:f,tailscaleOnly:w,logo:s||void 0,category:t})})).json();if(!i.success)throw new Error(i.error||"Failed to update service");const l=window.APPS.findIndex(y=>y.id===e);l!==-1&&(window.APPS[l]={...window.APPS[l],id:p,name:d||window.APPS[l].name,port:r||window.APPS[l].port,ip:f,tailscaleOnly:w,logo:s||window.APPS[l].logo,category:t||void 0}),m(),window.buildGrid(),window.refreshAll()}catch(n){console.error("Error saving service changes:",n),showNotification(`Error saving changes: ${n.message}`,"error")}finally{u.textContent="Save Changes",u.disabled=!1}}document.getElementById("edit-logo-file")?.addEventListener("change",async p=>{const d=p.target.files[0];if(!d)return;if(!d.type.startsWith("image/")){showNotification("Please select an image file","warning");return}const r=new FileReader;r.onload=async f=>{const w=f.target.result;if(document.getElementById("edit-service-logo-preview").src=w,document.getElementById("edit-logo-url").value=w,c)try{const t=await(await secureFetch("/api/v1/assets/upload",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filename:`${c.id}.png`,data:w})})).json();t.success&&t.path&&(document.getElementById("edit-logo-url").value=t.path)}catch{}},r.readAsDataURL(d)}),document.getElementById("service-edit-cancel")?.addEventListener("click",m),document.getElementById("service-edit-save")?.addEventListener("click",h),document.getElementById("service-edit-modal")?.addEventListener("click",p=>{p.target.id==="service-edit-modal"&&m()});function b(p,d,r){return new Promise(f=>{const w=document.getElementById("delete-service-modal"),s=document.getElementById("delete-modal-title"),t=document.getElementById("delete-modal-message"),e=document.getElementById("delete-modal-container-info"),o=document.getElementById("delete-modal-container-name"),u=document.getElementById("delete-modal-help"),n=document.getElementById("delete-modal-cancel"),i=document.getElementById("delete-modal-remove"),l=document.getElementById("delete-modal-delete");s.textContent=`Delete "${p}"`,d?(t.innerHTML="This service has an associated Docker container.<br>Choose how to proceed:",e.style.display="block",o.textContent=`Container ID: ${r?.slice(0,12)||"Unknown"}`,u.style.display="block",l.style.display="block"):(t.textContent="Remove this service from the dashboard?",e.style.display="none",u.style.display="none",l.style.display="none");const y=()=>{w.classList.remove("show"),n.removeEventListener("click",S),i.removeEventListener("click",k),l.removeEventListener("click",L),w.removeEventListener("click",x)},S=()=>{y(),f(null)},k=()=>{y(),f(!1)},L=()=>{y(),f(!0)},x=B=>{B.target===w&&(y(),f(null))};n.addEventListener("click",S),i.addEventListener("click",k),l.addEventListener("click",L),w.addEventListener("click",x),w.classList.add("show")})}async function g(p,d,r){const f=document.getElementById(`update-btn-${r}`),w=f?.textContent;if(confirm(`Update ${d} 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{f&&(f.textContent="\u{1F504}",f.disabled=!0,f.title="Updating...");const t=await(await secureFetch(`/api/v1/containers/${p}/update`,{method:"POST"})).json();if(t.success){const e=window.APPS.find(o=>o.id===r);e&&t.newContainerId&&(e.containerId=t.newContainerId),f&&(f.textContent="\u2705",f.title="Updated successfully!",setTimeout(()=>{f.textContent=w,f.disabled=!1,f.title="Update container to latest version"},3e3)),setTimeout(()=>window.refreshAll(),2e3),showNotification(`${d} updated successfully!`,"success")}else throw new Error(t.error||"Update failed")}catch(s){console.error("Update error:",s),f&&(f.textContent="\u274C",f.title="Update failed",setTimeout(()=>{f.textContent=w,f.disabled=!1,f.title="Update container to latest version"},3e3)),showNotification(`Failed to update ${d}: ${s.message}`,"error")}}async function v(p,d){const r=window.APPS.find(l=>l.id===p),f=r?buildDomain(r.id):null,w=r?.containerId,s=await b(d||p,w,r?.containerId);if(s===null)return;let t={dashboard:!1,container:null,dns:null,caddy:null,service:null};if(s&&w)try{const l=new URLSearchParams({containerId:r.containerId,subdomain:r.id,ip:r.ip||"localhost",deleteContainer:"true"}),S=await(await secureFetch(`/api/v1/apps/${encodeURIComponent(r.id)}?${l.toString()}`,{method:"DELETE"})).json();S.success?t={...t,...S.results,dashboard:!1}:console.error("App removal failed:",S.error)}catch(l){console.error("App removal error:",l)}else if(s&&f){try{const l=r?.ip||"localhost",S=await(await secureFetch(`/api/v1/dns/record?domain=${encodeURIComponent(f)}&type=A&ipAddress=${encodeURIComponent(l)}&server=${SITE.dnsIp}`,{method:"DELETE"})).json();t.dns=S.success?"deleted":S.error||"failed"}catch(l){t.dns=l.message}try{const y=await(await secureFetch(`/api/v1/site/${encodeURIComponent(f)}`,{method:"DELETE"})).json();t.caddy=y.success||y.error&&y.error.includes("not found")?"removed":y.error||"failed"}catch(l){t.caddy=l.message}}const e=window.APPS.findIndex(l=>l.id===p);e>-1&&(window.APPS.splice(e,1),t.dashboard=!0);try{const l=safeGetJSON("custom-apps",[]),y=l.findIndex(S=>S.id===p);y>-1&&(l.splice(y,1),safeSet("custom-apps",JSON.stringify(l)))}catch{}try{const y=await(await secureFetch(`/api/v1/services/${encodeURIComponent(p)}`,{method:"DELETE"})).json();t.service=y.success?"removed":y.error||"failed"}catch(l){t.service=l.message}window.buildGrid(),window.refreshAll();let o=!1,u=[];t.dashboard||(o=!0,u.push("\u2717 Failed to remove from dashboard"));const n=["removed","already removed","not found","deleted","kept (user choice)","skipped","no such record","does not exist"],i=l=>!l||n.some(y=>l.toLowerCase().includes(y.toLowerCase()));t.container&&!i(t.container)&&(o=!0,u.push(`\u26A0 Container: ${t.container}`)),t.dns&&!i(t.dns)&&(o=!0,u.push(`\u26A0 DNS Record: ${t.dns}`)),t.caddy&&!i(t.caddy)&&(o=!0,u.push(`\u26A0 Caddy Config: ${t.caddy}`)),t.service&&!i(t.service)&&(o=!0,u.push(`\u26A0 Service File: ${t.service}`)),o&&showNotification(`Error deleting "${d||p}": ${u.join(", ")}`,"error",6e3)}window.openServiceEditModal=a,window.showDeleteModal=b,window.updateContainer=g,window.deleteService=v})(),(function(){function c(t){return t.toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,"").replace(/-+/g,"-").replace(/^-|-$/g,"")}function a(){return SITE.defaults?.sslType||(SITE.configurationType==="public"?"letsencrypt":"caddy-managed")}function m(){const t=document.getElementById("service-subdomain-input").value||"subdomain",e=document.getElementById("service-ip-input").value||h.lan||"localhost",o=document.getElementById("service-port-input").value||DC.DEFAULTS.SERVICE_PORT,u=document.getElementById("ssl-type-select").value,n=document.getElementById("ca-name-input").value||"sami-ca",i=document.getElementById("existing-ca-select").value,l=document.getElementById("enable-auth").checked,y=document.getElementById("enable-cors").checked,S=document.getElementById("custom-headers-input").value,k=document.getElementById("upstream-path-input").value||"/",L=document.getElementById("health-check-input").value,x=document.getElementById("timeout-input").value||30,B=document.getElementById("dns-preview");B&&(B.textContent=`${buildDomain(t)} \u2192 ${e}`);const A=document.getElementById("url-preview");A&&(A.textContent=buildServiceUrl(t));const E={subdomain:t,port:o,ip:e,sslType:u,caName:n,existingCa:i,enableAuth:l,enableCors:y,customHeaders:S,upstreamPath:k,healthCheck:L,timeout:x},C=window.generateCaddyConfig(E),T=document.getElementById("caddy-config-preview");T&&(T.value=C)}const h={localhost:"127.0.0.1",lan:"",tailscale:""};async function b(){try{const u=await fetch("/api/v1/network/ips",{signal:AbortSignal.timeout(2e3)});if(u.ok){const n=await u.json();n.lan&&(h.lan=n.lan),n.tailscale&&(h.tailscale=n.tailscale)}}catch{}const t=document.getElementById("quick-ip-lan"),e=document.getElementById("quick-ip-tailscale");t&&(h.lan?(t.dataset.ip=h.lan,t.textContent=`LAN (${h.lan})`,t.title=`LAN IP: ${h.lan}`):t.style.display="none"),e&&(h.tailscale?(e.dataset.ip=h.tailscale,e.textContent=`Tailscale (${h.tailscale})`,e.title=`Tailscale IP: ${h.tailscale}`):e.style.display="none");const o=document.getElementById("service-ip-input");o&&!o.value&&h.lan&&(o.value=h.lan)}function g(){document.querySelectorAll(".quick-ip-btn").forEach(t=>{t.addEventListener("click",()=>{const e=t.dataset.ip;e&&(document.getElementById("service-ip-input").value=e,document.querySelectorAll(".quick-ip-btn").forEach(o=>o.classList.remove("active")),t.classList.add("active"),m())})}),document.getElementById("service-ip-input")?.addEventListener("input",t=>{const e=t.target.value;document.querySelectorAll(".quick-ip-btn").forEach(o=>{o.classList.toggle("active",o.dataset.ip===e)})})}async function v(){const t=document.getElementById("add-service-modal");t.classList.add("show");const e=t.querySelector(".weather-modal-content");e&&(e.scrollTop=0),document.body.style.overflow="hidden";const o=document.getElementById("ssl-type-select");o&&(o.value=a()),await b();const u=document.getElementById("caddyfile-path-input").value||DC.DEFAULTS.CADDYFILE;await window.loadExistingCAs(u);const n=document.getElementById("manual-tailscale-status"),i=document.getElementById("manual-tailscale-only");try{const y=await(await fetch("/api/v1/tailscale/status")).json();y.success&&y.installed&&y.connected?(n.innerHTML=`
          <span style="color: #4caf50;">\u2713 Connected</span>
          <span style="color: var(--muted); margin-left: 6px;">${y.self?.hostname} (${y.self?.ip})</span>
        `,i.disabled=!1):y.installed?(n.innerHTML='<span style="color: #ff9800;">\u26A0 Not connected</span>',i.disabled=!0):(n.innerHTML='<span style="color: var(--muted);">Not available</span>',i.disabled=!0)}catch{n.innerHTML='<span style="color: var(--muted);">Could not check</span>',i.disabled=!0}i.checked=!1,m()}function p(){const t=document.getElementById("service-type-local"),e=document.getElementById("service-type-external"),o=document.getElementById("local-service-config"),u=document.getElementById("external-service-config"),n=document.getElementById("tab-local"),i=document.getElementById("tab-external");function l(){t.checked?(o.style.display="grid",u.style.display="none",n&&(n.style.background="var(--accent)",n.style.color="var(--bg)"),i&&(i.style.background="transparent",i.style.color="var(--muted)")):(o.style.display="none",u.style.display="block",i&&(i.style.background="var(--accent)",i.style.color="var(--bg)"),n&&(n.style.background="transparent",n.style.color="var(--muted)"))}t?.addEventListener("change",l),e?.addEventListener("change",l)}function d(){const t=document.getElementById("service-name-input"),e=document.getElementById("service-subdomain-input"),o=document.getElementById("subdomain-preview");let u=!1;t?.addEventListener("input",()=>{const k=c(t.value);!u&&e&&(e.value=k),o&&(o.textContent=k?`\u2192 ${buildDomain(k)}`:""),m()}),e?.addEventListener("input",()=>{u=e.value!==c(t?.value||"");const k=e.value.trim()||c(t?.value||"");o&&(o.textContent=k?`\u2192 ${buildDomain(k)}`:""),m()});const n=document.getElementById("external-service-name"),i=document.getElementById("external-service-subdomain"),l=document.getElementById("external-subdomain-preview"),y=document.getElementById("external-domain-preview");let S=!1;n?.addEventListener("input",()=>{const k=c(n.value);!S&&i&&(i.value=k);const L=i?.value||k;l&&(l.textContent=L?`\u2192 ${buildDomain(L)}`:""),y&&(y.textContent=L?buildDomain(L):"")}),i?.addEventListener("input",()=>{S=i.value!==c(n?.value||"");const k=i.value.trim()||c(n?.value||"");l&&(l.textContent=k?`\u2192 ${buildDomain(k)}`:""),y&&(y.textContent=k?buildDomain(k):"")})}async function r(){const t=document.getElementById("external-service-name").value.trim(),e=document.getElementById("external-service-url").value.trim(),o=(document.getElementById("external-service-subdomain").value.trim()||c(t)).toLowerCase(),u=document.getElementById("external-service-logo").value.trim(),n=document.getElementById("external-service-icon").value.trim(),i=document.getElementById("external-create-dns").checked,l=document.getElementById("external-create-caddy").checked,y=document.getElementById("external-proxy-ip").value.trim()||SITE.dnsIp||"localhost",S=document.getElementById("external-preserve-host").checked,k=document.getElementById("external-follow-redirects").checked,L=document.getElementById("external-service-category")?.value||"";if(!t||!e){showNotification("Please fill in Name and External URL","warning");return}if(!o){showNotification("Could not derive subdomain from name. Please set one in Options.","warning");return}if(!e.startsWith("http://")&&!e.startsWith("https://")){showNotification("External URL must start with http:// or https://","warning");return}const x=buildDomain(o);try{const B={dns:null,caddy:null,dashboard:!1};if(i)if(window.getToken(getPrimaryDnsId(),"admin"))try{const P=await(await secureFetch("/api/v1/dns/record",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:x,ip:y,ttl:DC.DEFAULTS.TTL,server:SITE.dnsIp})})).json();B.dns=P.success?"created":P.error||"failed"}catch(I){B.dns=I.message}else B.dns="no admin token (configure in \u{1F511} Tokens)";if(l)try{const $={subdomain:o,externalUrl:e,preserveHost:S,followRedirects:k,sslType:"caddy-managed",caddyfilePath:DC.DEFAULTS.CADDYFILE,reloadCaddy:!0},P=await(await secureFetch("/api/v1/site/external",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify($)})).json();B.caddy=P.success?"created":P.error||"failed"}catch($){B.caddy=$.message}const A={id:o,name:t,url:`https://${x}`,externalUrl:e,logo:u||n||"\u{1F310}",isExternal:!0,isCustom:!0};L&&(A.category=L),window.APPS.push(A),B.dashboard=!0;const E=["plex","router","chat","sync","torrent","radarr","sonarr","prowlarr","portainer","requests","jellyfin","emby"],C=window.APPS.filter($=>!E.includes($.id));safeSet("custom-services",JSON.stringify(C));try{await secureFetch("/api/v1/services",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(window.APPS)})}catch($){console.warn("Failed to save to services.json:",$)}window.buildGrid(),window.refreshAll(),f();const T=[`External service "${t}" added!`];i&&T.push(`DNS: ${B.dns==="created"?"\u2713":"\u26A0 "+B.dns}`),l&&T.push(`Caddy: ${B.caddy==="created"?"\u2713":"\u26A0 "+B.caddy}`),T.push(`Access at: https://${x}`),showNotification(T.join(" | "),"success",6e3)}catch(B){console.error("Failed to create external service:",B),showNotification(`Failed to create external service: ${B.message}`,"error")}}function f(){closeModal("add-service-modal"),document.body.style.overflow="",document.getElementById("service-name-input").value="",document.getElementById("service-subdomain-input").value="",document.getElementById("service-port-input").value="",document.getElementById("service-ip-input").value=h.lan||"",document.getElementById("service-logo-input").value="",document.getElementById("dns-ttl-input").value=DC.DEFAULTS.TTL,document.getElementById("ssl-type-select").value=a(),document.getElementById("ca-name-input").value="",document.getElementById("enable-auth").checked=!1,document.getElementById("enable-cors").checked=!1,document.getElementById("custom-headers-input").value="",document.getElementById("upstream-path-input").value="/",document.getElementById("health-check-input").value="",document.getElementById("timeout-input").value="30";const t=document.getElementById("subdomain-preview");t&&(t.textContent="");const e=document.getElementById("external-subdomain-preview");e&&(e.textContent="");const o=document.getElementById("external-service-name");o&&(o.value="");const u=document.getElementById("external-service-subdomain");u&&(u.value="");const n=document.getElementById("external-service-url");n&&(n.value="");const i=document.getElementById("external-service-logo");i&&(i.value="");const l=document.getElementById("external-service-icon");l&&(l.value="");const y=document.getElementById("local-advanced-options");y&&y.removeAttribute("open");const S=document.getElementById("external-advanced-options");S&&S.removeAttribute("open");const k=document.getElementById("service-type-local");k&&(k.checked=!0);const L=document.getElementById("local-service-config"),x=document.getElementById("external-service-config");L&&(L.style.display="grid"),x&&(x.style.display="none");const B=document.getElementById("tab-local"),A=document.getElementById("tab-external");B&&(B.style.background="var(--accent)",B.style.color="var(--bg)"),A&&(A.style.background="transparent",A.style.color="var(--muted)")}async function w(){const t=document.getElementById("service-name-input").value.trim(),e=(document.getElementById("service-subdomain-input").value.trim()||c(t)).toLowerCase(),o=document.getElementById("service-port-input").value.trim(),u=document.getElementById("service-ip-input").value.trim(),n=document.getElementById("service-logo-input").value.trim(),i=document.getElementById("create-dns-record").checked,l=parseInt(document.getElementById("dns-ttl-input").value)||DC.DEFAULTS.TTL,y=document.getElementById("manual-tailscale-only")?.checked||!1,S=document.getElementById("ssl-type-select")?.value||"caddy-managed",k=document.getElementById("ca-name-input")?.value||"",L=document.getElementById("existing-ca-select")?.value||"",x=document.getElementById("enable-auth")?.checked||!1,B=document.getElementById("enable-cors")?.checked||!1,A=document.getElementById("custom-headers-input")?.value||"",E=document.getElementById("upstream-path-input")?.value||"/",C=document.getElementById("health-check-input")?.value||"",T=document.getElementById("timeout-input")?.value||30,I=(document.getElementById("service-category-input")||document.getElementById("external-service-category"))?.value||"",P=window.getToken(getPrimaryDnsId(),"admin");if(!t||!o||!u){showNotification("Please fill in Name, Port, and IP Address","warning");return}if(!e){showNotification("Could not derive subdomain from name. Please set one in Options.","warning");return}if(i&&!P){showNotification("DNS Admin token required. Configure it in the Tokens menu first.","warning");return}const D={dns:null,caddy:null,dashboard:!1};try{if(i)try{await window.createDnsRecord(e,u,l),D.dns="created"}catch(R){throw console.error("DNS creation failed:",R),D.dns=R.message,new Error(`DNS creation failed: ${R.message}`)}else D.dns="skipped";const O=window.generateCaddyConfig({subdomain:e,port:o,ip:u,sslType:S,caName:k,existingCa:L,enableAuth:x,enableCors:B,customHeaders:A,upstreamPath:E,healthCheck:C,timeout:T,tailscaleOnly:y});try{const U=await(await secureFetch("/api/v1/site",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:buildDomain(e),upstream:`${u}:${o}`,config:O})})).json();if(U.success)D.caddy="added & reloaded";else throw console.error("Caddy configuration failed:",U.error),D.caddy=U.error||"failed",new Error(`Caddy configuration failed: ${U.error}`)}catch(R){throw console.error("Caddy API error:",R),D.caddy=R.message,new Error(`Caddy API error: ${R.message}`)}const N={name:t,subdomain:e,port:o,ip:u,logo:n||`/assets/${e}.png`,tailscaleOnly:y||!1};I&&(N.category=I),await window.addServiceToConfig(N),D.dashboard=!0;const _=[`DNS: ${D.dns==="created"?"\u2713":D.dns==="skipped"?"\u25CB":"\u2717"}`,`Caddy: ${D.caddy==="added & reloaded"?"\u2713":"\u2717"}`,`Dashboard: ${D.dashboard?"\u2713":"\u2717"}`];showNotification(`Service "${t}" created! ${_.join(" | ")} \u2014 ${buildServiceUrl(e)}${y?" (Tailscale)":""}`,"success",6e3),f(),window.buildGrid(),window.refreshAll()}catch(O){console.error("Error creating service:",O),showNotification(`Error creating "${t}": ${O.message}`,"error",6e3)}}document.getElementById("add-service")?.addEventListener("click",v),document.getElementById("add-service-cancel")?.addEventListener("click",f),document.getElementById("add-service-create")?.addEventListener("click",()=>{document.querySelector('input[name="service-type"]:checked')?.value==="external"?r():w()}),p(),d(),g(),document.getElementById("ssl-type-select")?.addEventListener("change",t=>{const e=document.getElementById("existing-ca-config"),o=document.getElementById("custom-ca-config");e.style.display="none",o.style.display="none",t.target.value==="existing-ca"?e.style.display="block":t.target.value==="custom-ca"&&(o.style.display="block"),m()}),document.getElementById("refresh-cas")?.addEventListener("click",async()=>{const t=document.getElementById("refresh-cas"),e=t.textContent;t.textContent="\u231B Loading...",t.disabled=!0;try{const o=document.getElementById("caddyfile-path-input").value||DC.DEFAULTS.CADDYFILE;await window.loadExistingCAs(o),t.textContent="\u2705 Refreshed"}catch(o){t.textContent="\u274C Failed",console.error("Failed to refresh CAs:",o)}setTimeout(()=>{t.textContent=e,t.disabled=!1},2e3)}),document.getElementById("create-dns-record")?.addEventListener("change",t=>{const e=document.getElementById("dns-config");e.style.display=t.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(t=>{const e=document.getElementById(t);e&&(e.addEventListener("input",m),e.addEventListener("change",m))});function s(){const t=safeGet("custom-services");if(t)try{JSON.parse(t).forEach(o=>{window.APPS.find(u=>u.id===o.id)||window.APPS.push(o)})}catch(e){console.warn("Failed to load custom services:",e)}}s(),window.openAddServiceModal=v,window.closeAddServiceModal=f})(),(function(){let c=null,a=1e3;const m=3e4;let h=0,b=!1;function g(){if(c)try{c.close()}catch{}b||(c=new EventSource("/api/v1/events/stream"),c.addEventListener("connected",()=>{a=1e3,h=0,debug("[SSE] Connected to event stream")}),c.addEventListener("status-change",d=>{try{const r=JSON.parse(d.data);if(r.serviceId&&typeof window.setBadge=="function"){const f=r.status==="up"||r.status==="healthy";window.setBadge(r.serviceId,f,r.responseTime||null)}}catch{}}),c.addEventListener("resource-alert",d=>{try{const r=JSON.parse(d.data),f=`${r.containerName||r.containerId}: ${r.metric} at ${r.value}% (threshold: ${r.threshold}%)`;typeof showNotification=="function"&&showNotification(f,"warning")}catch{}}),c.addEventListener("auto-restart",d=>{try{const r=JSON.parse(d.data);typeof showNotification=="function"&&showNotification(`Container "${r.containerName}" was auto-restarted`,"info")}catch{}}),c.addEventListener("update-available",d=>{try{const r=JSON.parse(d.data),f=document.getElementById("updates-btn");if(f&&!f.querySelector(".sse-dot")){const w=document.createElement("span");w.className="sse-dot",w.style.cssText="display:inline-block;width:8px;height:8px;border-radius:50%;background:var(--accent);margin-left:6px;vertical-align:middle;",f.appendChild(w)}typeof showNotification=="function"&&showNotification(`Update available for ${r.containerName||r.containerId}`,"info")}catch{}}),c.addEventListener("update-complete",d=>{try{const r=JSON.parse(d.data);typeof showNotification=="function"&&showNotification(`Update completed: ${r.containerName||r.containerId}`,"success"),typeof window.refreshAll=="function"&&window.refreshAll()}catch{}}),c.addEventListener("update-failed",d=>{try{const r=JSON.parse(d.data);typeof showNotification=="function"&&showNotification(`Update failed: ${r.containerName||r.containerId} \u2014 ${r.error||"unknown error"}`,"error")}catch{}}),c.addEventListener("incident",d=>{try{const r=JSON.parse(d.data);typeof showNotification=="function"&&(r.type==="created"?showNotification(`Incident: ${r.message||r.serviceId}`,"error"):r.type==="resolved"&&showNotification(`Resolved: ${r.serviceId||"incident"}`,"success"))}catch{}}),c.onerror=()=>{if(c.close(),window._dcAuthLost||b){console.warn("[SSE] Auth lost \u2014 stopping reconnection");return}if(h++,h>5){console.warn("[SSE] Max reconnect attempts reached \u2014 stopping (server unreachable)");return}console.warn(`[SSE] Disconnected, reconnecting in ${a/1e3}s...`),setTimeout(g,a),a=Math.min(a*2,m)})}function v(){if(b=!0,c)try{c.close()}catch{}}function p(){b=!1,h=0,a=1e3,g()}g(),window._sseReconnect=g,window._sseClose=v,window._sseResume=p})(),(function(){const c=document.getElementById("service-filter-search"),a=document.getElementById("service-filter-status"),m=document.getElementById("service-filter-category"),h=document.getElementById("service-filter-count");function b(){const d=new Set,r=new Set;document.querySelectorAll("#cards .card[data-category]").forEach(s=>{const t=s.dataset.category.trim();t&&r.add(t)});const f=window.DC_CATEGORIES||typeof DC<"u"&&DC.CATEGORIES||{};return Object.keys(f).concat([...r].filter(s=>!f[s])).forEach(s=>d.add(s)),{list:[...d],apiCats:f}}function g(){if(!m)return;const{list:d,apiCats:r}=b(),f=m.value;m.innerHTML='<option value="all">All Categories</option>',d.sort().forEach(w=>{const s=r[w],t=document.createElement("option");t.value=w,t.textContent=s?`${s.icon||""} ${w}`.trim():w,m.appendChild(t)}),f&&[...m.options].some(w=>w.value===f)?m.value=f:m.value="all"}function v(){g();const d=c.value.toLowerCase().trim(),r=a.value,f=m?m.value:"all",w=document.querySelectorAll("#cards .card");let s=0;if(w.forEach(t=>{const e=t.querySelector(".name")?.textContent?.toLowerCase()||"",o=t.dataset.app?.toLowerCase()||"",u=t.dataset.status||"off",n=t.dataset.category||"";(!d||e.includes(d)||o.includes(d))&&(r==="all"||u===r)&&(f==="all"||n===f)?(t.style.display="",s++):t.style.display="none"}),h){const t=w.length;h.textContent=`${s} of ${t} services`}}function p(d,r){let f;return function(...w){clearTimeout(f),f=setTimeout(()=>d.apply(this,w),r)}}c?.addEventListener("input",p(v,200)),a?.addEventListener("change",v),m?.addEventListener("change",v),document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>setTimeout(v,500)):setTimeout(v,500),window.refreshServiceFilter=v,window.refreshCategoryDropdown=g})(),(function(){const c=document.getElementById("batch-operations-btn"),a=document.getElementById("batch-action-bar"),m=document.getElementById("batch-selected-count"),h=document.getElementById("batch-start-btn"),b=document.getElementById("batch-stop-btn"),g=document.getElementById("batch-restart-btn"),v=document.getElementById("batch-cancel-btn");let p=!1,d=new Set;function r(){p=!0,d.clear(),a.style.display="",c.textContent="\u2713 Exit Batch Mode",w(),document.querySelectorAll("#cards .card[data-app]").forEach(e=>{const o=e.dataset.containerId;if(!o)return;const u=e.querySelector(".batch-checkbox");u&&u.remove();const n=document.createElement("input");n.type="checkbox",n.className="batch-checkbox",n.dataset.containerId=o,n.dataset.serviceName=e.querySelector(".name")?.textContent||o,n.style.cssText="position: absolute; top: 8px; left: 8px; z-index: 10; width: 18px; height: 18px; cursor: pointer;",n.addEventListener("change",i=>{i.stopPropagation(),n.checked?d.add(o):d.delete(o),w()}),e.style.position="relative",e.insertBefore(n,e.firstChild)})}function f(){p=!1,d.clear(),a.style.display="none",c.textContent="\u2630 Batch Operations",document.querySelectorAll(".batch-checkbox").forEach(t=>t.remove())}function w(){const t=d.size;m.textContent=`${t} selected`,h.disabled=t===0,b.disabled=t===0,g.disabled=t===0}async function s(t){if(d.size===0)return;const e=Array.from(d),o={start:"Starting",stop:"Stopping",restart:"Restarting"}[t];if(!confirm(`${o} ${e.length} container(s)? This cannot be undone.`))return;const u=[h,b,g];u.forEach(y=>{y.disabled=!0,y.textContent="..."});let n=0,i=0;const l=[];for(const y of e)try{const S=await fetch(`/api/v1/containers/${encodeURIComponent(y)}/${t}`,{method:"POST"});if(S.ok)n++;else{i++;const k=await S.json().catch(()=>({}));l.push(`${y}: ${k.error||S.statusText}`)}}catch(S){i++,l.push(`${y}: ${S.message}`)}u[0].textContent="\u25B6 Start All",u[1].textContent="\u2B1B Stop All",u[2].textContent="\u{1F504} Restart All",w(),i===0?typeof showNotification=="function"&&showNotification(`${o} completed: ${n} container(s)`,"success"):(typeof showNotification=="function"&&showNotification(`${o}: ${n} succeeded, ${i} failed`,"warning"),console.error("Batch operation errors:",l)),setTimeout(()=>{typeof refreshAll=="function"&&refreshAll()},1500)}c?.addEventListener("click",()=>{p?f():r()}),h?.addEventListener("click",()=>s("start")),b?.addEventListener("click",()=>s("stop")),g?.addEventListener("click",()=>s("restart")),v?.addEventListener("click",f)})();
//# sourceMappingURL=data:application/json;base64,[encoded data, 591916 characters]
