Files
dashcaddy/status/dist/core.js
2026-03-23 10:34:57 +01:00

728 lines
123 KiB
JavaScript

const DC={NAME:"DashCaddy",POLL:{DASHBOARD:1e4,LOGS:3e3,STATS:5e3,WEATHER:6e5,HEALTH:1e3,DEPLOY_SSL:5e3},DELAYS:{BTN_RESET:2e3,RELOAD:5e3,MODAL_CLOSE:500,PORT_CHECK:500,DEPLOY_INIT:3e3},DEFAULTS:{DNS_PORT:"5380",SERVICE_PORT:"8080",TTL:300,CADDYFILE:"C:\\caddy\\Caddyfile"}},_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 p=await fetch("/api/v1/config");if(p.ok){const r=await p.json();if(r.tld&&(SITE.tld=r.tld.startsWith(".")?r.tld:"."+r.tld),r.dns&&(SITE.dnsIp=r.dns.ip||"",SITE.dnsPort=r.dns.port||DC.DEFAULTS.DNS_PORT),r.dnsServers&&typeof r.dnsServers=="object")for(const[f,t]of Object.entries(r.dnsServers))f!=="__proto__"&&f!=="constructor"&&f!=="prototype"&&(SITE.dnsServers[f]=t);r.configurationType&&(SITE.configurationType=r.configurationType),r.domain&&(SITE.domain=r.domain),r.defaults&&(SITE.defaults=r.defaults),r.routingMode&&(SITE.routingMode=r.routingMode),SITE.onboardingCompleted=r.onboardingCompleted===!0,localStorage.setItem("dashcaddy_site_config",JSON.stringify({tld:SITE.tld,configurationType:SITE.configurationType,domain:SITE.domain,routingMode:SITE.routingMode})),renderDnsCards();const E=document.getElementById("manage-tokens");E&&(E.style.display=Object.keys(SITE.dnsServers).length?"":"none")}}catch{}document.querySelectorAll("[data-tld]").forEach(p=>p.textContent=SITE.tld);const i=document.getElementById("edit-tld-suffix");i&&(i.textContent=SITE.tld);const g=document.getElementById("external-proxy-ip");g&&SITE.dnsIp&&(g.value=SITE.dnsIp,g.placeholder=SITE.dnsIp)})();function buildDomain(n){return n+SITE.tld}function buildServiceUrl(n){return SITE.routingMode==="subdirectory"&&SITE.domain?"https://"+SITE.domain+"/"+n:SITE.configurationType==="public"&&SITE.domain?"https://"+n+"."+SITE.domain:"https://"+buildDomain(n)}function getDnsServerAddr(n){const i=SITE.dnsServers[n];return i?`${i.ip}:${i.port}`:buildDomain(n)}function getPrimaryDnsId(){if(!SITE.dnsIp)return null;for(const[n,i]of Object.entries(SITE.dnsServers))if(i.ip===SITE.dnsIp)return n;return null}function renderDnsCards(){const n=document.querySelector(".top");if(!n)return;const i=Object.keys(SITE.dnsServers);if(!i.length)return;const g='<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>',p=n.firstElementChild;i.forEach(r=>{const E=escapeHtml(r),f=escapeHtml((SITE.dnsServers[r].name||r).toUpperCase()),t=document.createElement("div");t.className="card",t.setAttribute("data-app",r),t.setAttribute("data-status","off"),t.innerHTML=`<span id="${E}-dot" class="dot bad at-bl"></span><div class="row"><div class="logo-wrap">${g}</div><span class="name">${f}</span><span class="spacer"></span><span id="${E}-pill" class="badge off">OFF</span></div><div class="response-row"><span id="${E}-time" class="response-time">--</span></div><div class="health-row" id="health-${E}"><span id="uptime-${E}" class="uptime-chip">--</span><div class="uptime-mini-bar"><div class="fill" id="uptime-bar-${E}" style="width: 0%"></div></div></div><div class="btn-row"><button id="${E}-restart" class="restart-btn">Restart</button><button id="${E}-update" class="update-btn" title="Update DNS server">\u2B06\uFE0F</button><button id="${E}-open">Open</button><button id="${E}-logs" class="logs-btn">Logs</button><button id="${E}-settings" class="settings-btn">\u2699\uFE0F</button></div>`,n.insertBefore(t,p)})}window.renderDnsCards=renderDnsCards;let csrfToken=null;async function getCSRFToken(){if(csrfToken)return csrfToken;try{const n=await fetch("/api/v1/csrf-token");if(!n.ok)throw new Error("Failed to fetch CSRF token");return csrfToken=(await n.json()).token,csrfToken}catch(n){throw console.error("Failed to get CSRF token:",n),n}}async function secureFetch(n,i={}){const g=(i.method||"GET").toUpperCase();if(!["GET","HEAD","OPTIONS"].includes(g))try{const p=await getCSRFToken();i.headers={...i.headers,"X-CSRF-Token":p}}catch(p){console.error("Failed to add CSRF token to request:",p)}return i.signal||(i={...i,signal:AbortSignal.timeout(15e3)}),fetch(n,i)}async function postJSON(n,i){const g=await secureFetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)}),p=await g.json();if(!g.ok||p.success===!1)throw new Error(p.error||`Request failed (${g.status})`);return p}async function getJSON(n){const i=await secureFetch(n);if(!i.ok){let g=`Request failed (${i.status})`;try{g=(await i.json()).error||g}catch{}throw new Error(g)}return i.json()}async function deleteAPI(n){const i=await secureFetch(n,{method:"DELETE"}),g=await i.json();if(!i.ok||g.success===!1)throw new Error(g.error||`Delete failed (${i.status})`);return g}async function withButton(n,i,g,p={}){const r=n.innerHTML,{successText:E="\u2705",resetDelay:f=DC.DELAYS.BTN_RESET}=p;n.disabled=!0,n.innerHTML=i;try{const t=await g();return n.innerHTML=E,setTimeout(()=>{n.innerHTML=r,n.disabled=!1},f),t}catch(t){throw n.innerHTML=r,n.disabled=!1,t}}function openModal(n){document.getElementById(n)?.classList.add("show")}function closeModal(n){document.getElementById(n)?.classList.remove("show")}function wireModal(n,...i){n&&(n.addEventListener("click",g=>{g.target===n&&n.classList.remove("show")}),i.forEach(g=>g?.addEventListener("click",()=>n.classList.remove("show"))))}function showNotification(n,i="info",g=3e3){const p=document.querySelector(".deploy-notification");p&&p.remove();const r={info:{bg:"#2196F3",fg:"#fff"},success:{bg:"var(--ok-bg)",fg:"var(--ok-fg)"},error:{bg:"#f44336",fg:"#fff"},warning:{bg:"#ff9800",fg:"#fff"}},E=r[i]||r.info,f=document.createElement("div");f.className="deploy-notification",f.textContent=n,f.style.cssText=`
position: fixed; top: 20px; right: 20px;
background: ${E.bg}; color: ${E.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(f),g>0&&setTimeout(()=>f.remove(),g)}function timeAgo(n){const i=Date.now()-new Date(n).getTime();return i<6e4?"just now":i<36e5?Math.floor(i/6e4)+"m ago":i<864e5?Math.floor(i/36e5)+"h ago":Math.floor(i/864e5)+"d ago"}function safeGet(n,i=null){try{const g=localStorage.getItem(n);return g!==null?g:i}catch{return i}}function safeSet(n,i){try{localStorage.setItem(n,i)}catch{}}function safeRemove(n){try{localStorage.removeItem(n)}catch{}}function safeSessionGet(n,i=null){try{const g=sessionStorage.getItem(n);return g!==null?g:i}catch{return i}}function safeSessionSet(n,i){try{sessionStorage.setItem(n,i)}catch{}}function safeGetJSON(n,i=null){try{const g=localStorage.getItem(n);return g?JSON.parse(g):i}catch{return i}}function escapeHtml(n){return String(n??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function injectModal(n,i){document.getElementById(n)||document.body.insertAdjacentHTML("beforeend",i)}const DC_BUS={_handlers:{},on(n,i){var g;((g=this._handlers)[n]||(g[n]=[])).push(i)},off(n,i){this._handlers[n]=this._handlers[n]?.filter(g=>g!==i)},emit(n,i){this._handlers[n]?.forEach(g=>g(i))}},AppState={_apps:[],getApps(){return this._apps},setApps(n){this._apps=n,window.APPS=n,DC_BUS.emit("apps:changed",n)},findApp(n){return this._apps.find(i=>i.id===n)},addApp(n){this._apps.push(n),window.APPS=this._apps,DC_BUS.emit("apps:changed",this._apps)},removeApp(n){const i=this._apps.findIndex(g=>g.id===n);return i>-1&&(this._apps.splice(i,1),window.APPS=this._apps,DC_BUS.emit("apps:changed",this._apps)),i>-1},updateApp(n,i){const g=this._apps.find(p=>p.id===n);if(g){for(const[p,r]of Object.entries(i))p!=="__proto__"&&p!=="constructor"&&p!=="prototype"&&(g[p]=r);DC_BUS.emit("apps:changed",this._apps)}return g}};(function(){function n(){const p=document.createElement("div");return p.className="skeleton-card",p.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>',p}function i(p){const r=document.getElementById("cards");if(!(!r||r.querySelector(".card"))){p=p||6;for(let E=0;E<p;E++){const f=n();r.appendChild(f),setTimeout(function(){f.classList.add("loaded")},E*60)}}}function g(){const p=document.getElementById("cards");if(p){var r=p.querySelectorAll(".skeleton-card");r.length&&(r.forEach(function(E,f){setTimeout(function(){E.style.opacity="0",E.style.transform="translateY(-10px)"},f*25)}),setTimeout(function(){r.forEach(function(E){E.parentNode&&E.remove()})},r.length*25+300))}}window.SkeletonLoader={show:i,hide:g}})(),(function(){var n="theme",i="user-themes",g="custom-theme",p=["dark","light","blue","black","nord","dracula","solarized-dark","solarized-light","taxi","ocean"],r=p.slice(),E=["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"],f=["bg","fg","muted","card-base","card-bg","border","ok-bg","ok-fg","bad-bg","bad-fg","dot-ok","dot-bad","uptime","accent","accent-strong"],t=["fg-muted","hover","card-hover","base","success","error","warning"],m={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:"#0e0e00","accent-strong":"#1a1a05",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 s(h){return!h||typeof h!="string"?{r:0,g:0,b:0}:(h=h.replace("#",""),h.length===3&&(h=h[0]+h[0]+h[1]+h[1]+h[2]+h[2]),{r:parseInt(h.substr(0,2),16)||0,g:parseInt(h.substr(2,2),16)||0,b:parseInt(h.substr(4,2),16)||0})}function c(h,T,$){return"#"+[h,T,$].map(function(b){var l=Math.max(0,Math.min(255,Math.round(b))).toString(16);return l.length===1?"0"+l:l}).join("")}function y(h,T,$){var b=s(h),l=s(T);return c(b.r+(l.r-b.r)*$,b.g+(l.g-b.g)*$,b.b+(l.b-b.b)*$)}function k(h){h=h.replace("#",""),h.length===3&&(h=h[0]+h[0]+h[1]+h[1]+h[2]+h[2]);var T=parseInt(h.substr(0,2),16)/255,$=parseInt(h.substr(2,2),16)/255,b=parseInt(h.substr(4,2),16)/255;return T=T<=.03928?T/12.92:Math.pow((T+.055)/1.055,2.4),$=$<=.03928?$/12.92:Math.pow(($+.055)/1.055,2.4),b=b<=.03928?b/12.92:Math.pow((b+.055)/1.055,2.4),.2126*T+.7152*$+.0722*b}function e(h){var T=h.bg||"#0b0f1a",$=h.fg||"#e8ecf5",b=h.muted||"#9aa6bf",l=h["card-base"]||h.bg||"#121826",S=h["dot-ok"]||"#4caf50",x=h["dot-bad"]||"#e74c3c",C=h.lightBg||T&&k(T)>.4,P={};return P.hover=C?y(l,T,.35):y(l,$,.08),P["card-hover"]=y(l,P.hover,.5),P.base=y(T,l,.6),P["fg-muted"]=y(b,T,.35),P.success=S,P.error=x,P.warning=C?"#d68a00":"#f39c12",P}function d(h,T){var $=T.lightBg||T.bg&&k(T.bg)>.4,b=T.accent||T["accent-strong"]||"#888888",l=s(b);return $?":root."+h+` body {
background:
radial-gradient(1200px 800px at 10% -10%, rgba(`+l.r+","+l.g+","+l.b+`, .08), transparent 60%),
radial-gradient(1000px 700px at 110% 10%, rgba(`+l.r+","+l.g+","+l.b+`, .05), transparent 55%),
var(--bg);
}
`:":root."+h+` body {
background:
radial-gradient(1200px 900px at 8% -12%, rgba(`+l.r+","+l.g+","+l.b+`, .10), transparent 60%),
radial-gradient(1000px 700px at 110% -10%, rgba(`+l.r+","+l.g+","+l.b+`, .07), transparent 55%),
var(--bg);
}
`}function v(h,T){var $=T.lightBg||T.bg&&k(T.bg)>.4;return $?":root."+h+` 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."+h+` button:hover {
background: color-mix(in srgb, var(--accent) 18%, transparent);
border-color: color-mix(in srgb, var(--accent) 35%, var(--border));
}
`}function o(){return window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}function u(){E.forEach(function(h){document.documentElement.style.removeProperty("--"+h)})}function w(h,T){var $=h.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"");$||($="custom"),p.indexOf($)!==-1&&($=$+"-custom");for(var b=safeGetJSON(i,{}),l=$,S=2;b[$]&&$!==T;)$=l+"-"+S++;return $}function a(h){var T=document.getElementById("user-theme-styles");T&&T.remove(),r.length=p.length,Object.keys(m).forEach(function(x){p.indexOf(x)===-1&&delete m[x]});var $=h||safeGetJSON(i,{}),b=Object.keys($);if(b=b.filter(function(x){return p.indexOf(x)===-1}),!!b.length){var l="";b.forEach(function(x){var C=$[x];r.indexOf(x)===-1&&r.push(x);var P={};E.forEach(function(D){C[D]&&(P[D]=C[D])}),P["card-bg"]=C["card-base"]||C.bg,C.lightBg&&(P.lightBg=!0);var O=e(P);t.forEach(function(D){!P[D]&&O[D]&&(P[D]=O[D])}),m[x]=P,l+=":root."+x+` {
`,E.forEach(function(D){P[D]&&(l+=" --"+D+": "+P[D]+`;
`)}),l+=`}
`,l+=d(x,P),l+=v(x,P)});var S=document.createElement("style");S.id="user-theme-styles",S.textContent=l,document.head.appendChild(S)}}function I(){secureFetch("/api/v1/themes").then(function(h){return h.json()}).then(function(h){if(!(!h.success||!h.themes)){var T=h.themes,$=safeGetJSON(i,{});if(JSON.stringify(T)!==JSON.stringify($)){safeSet(i,JSON.stringify(T)),a(T);var b=safeGet(n);b&&r.indexOf(b)!==-1&&L(b)}}}).catch(function(){})}function B(){var h=safeGetJSON(g);if(h){var T=h.name||"Custom",$=w(T),b={name:T};E.forEach(function(x){h[x]&&(b[x]=h[x])});var l=safeGetJSON(i,{});l[$]=b,safeSet(i,JSON.stringify(l)),safeGet(n)==="custom"&&safeSet(n,$),safeRemove(g);var S={};E.forEach(function(x){b[x]&&(S[x]=b[x])}),fetch("/api/v1/themes/"+$,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:T,colors:S})}).catch(function(){})}}function L(h){document.documentElement.classList.add("theme-transitioning"),r.forEach(function(l){l!=="dark"&&document.documentElement.classList.remove(l)}),u(),h!=="dark"&&document.documentElement.classList.add(h),safeSet(n,h);var T=m[h],$=document.querySelector('meta[name="theme-color"]');$&&T&&$.setAttribute("content",T.bg);var b=T&&T.lightBg;!b&&T&&T.bg&&(b=k(T.bg)>.4),b?document.documentElement.classList.add("light-bg"):document.documentElement.classList.remove("light-bg"),setTimeout(function(){document.documentElement.classList.remove("theme-transitioning")},300)}B(),a();var A=safeGet(n);A==="red"&&(A="black",safeSet(n,"black")),A&&A!=="dark"&&r.indexOf(A)===-1&&(A=null),L(A||o()),I(),window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change",function(h){safeGet(n)||L(h.matches?"dark":"light")}),window.THEMES=r,window.BUILTIN_THEMES=p,window.THEME_COLORS=m,window.THEME_PROPS=E,window.BASE_PROPS=f,window.DERIVED_PROPS=t,window.USER_THEMES_KEY=i,window.applyTheme=L,window.clearCustomProperties=u,window.injectUserThemeStyles=a,window.syncThemesFromServer=I,window.slugifyThemeName=w,window.getActiveTheme=function(){return safeGet(n)||o()},window.deriveExtendedColors=e,window.hexToRgb=s,window.rgbToHex=c,window.blendColors=y})(),(function(){function n(){const f=document.querySelector(".totp-card");if(!f)return;const m=getComputedStyle(f).backgroundColor.match(/\d+/g);if(!m)return;const s=(.299*+m[0]+.587*+m[1]+.114*+m[2])/255,c=f.querySelector(".totp-logo-dark"),y=f.querySelector(".totp-logo-light");c&&(c.style.display=s>.5?"none":""),y&&(y.style.display=s>.5?"":"none")}function i(){const f=document.getElementById("totp-overlay");if(f){f.classList.add("show"),setTimeout(n,50);const t=f.querySelector(".totp-digits input");t&&setTimeout(()=>t.focus(),100)}}function g(){const f=document.getElementById("totp-overlay");f&&f.classList.remove("show")}const p=document.getElementById("totp-digits");if(p){const f=p.querySelectorAll("input");f.forEach((t,m)=>{t.addEventListener("input",s=>{const c=s.target.value.replace(/\D/g,"");s.target.value=c.slice(0,1),c&&m<f.length-1&&f[m+1].focus();const y=Array.from(f).map(k=>k.value).join("");y.length===6&&r(y)}),t.addEventListener("keydown",s=>{s.key==="Backspace"&&!s.target.value&&m>0&&(f[m-1].focus(),f[m-1].value="")}),t.addEventListener("paste",s=>{s.preventDefault();const c=(s.clipboardData.getData("text")||"").replace(/\D/g,"");c.length>=6&&(f.forEach((y,k)=>{y.value=c[k]||""}),f[5].focus(),r(c.slice(0,6)))})})}async function r(f){const t=document.getElementById("totp-error");t.textContent="Verifying...",t.className="totp-error verifying";try{const s=await(await secureFetch("/api/v1/totp/verify",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:f})})).json();if(s.success){t.textContent="",g();const c=safeSessionGet("totp_redirect");if(c){try{sessionStorage.removeItem("totp_redirect")}catch{}window.location.href=c;return}typeof window.initializeDashboard=="function"&&window.initializeDashboard()}else{t.textContent=s.error||"Invalid code",t.className="totp-error";const c=document.querySelectorAll("#totp-digits input");c.forEach(y=>{y.value=""}),c[0]?.focus()}}catch{t.textContent="Connection error",t.className="totp-error"}}const E=new URLSearchParams(window.location.search);if(E.get("auth")==="required"){const f=E.get("return");if(f)try{const t=new URL(f,window.location.origin),m=t.hostname,s=t.origin===window.location.origin,c=SITE.tld.startsWith(".")?SITE.tld:"."+SITE.tld,y=m.endsWith(c)||m===c.substring(1);(s||y)&&safeSessionSet("totp_redirect",f)}catch{}window.history.replaceState({},"",window.location.pathname)}window._showTotpOverlay=i})(),(function(){injectModal("folder-browser-modal",`<div id="folder-browser-modal" class="weather-modal">
<div class="weather-modal-content" style="min-width: 500px; max-width: 700px; max-height: 80vh;">
<h3>\u{1F4C2} Browse for Media Folders</h3>
<div id="folder-browser-path" style="padding: 10px; background: var(--card-bg); border-radius: 6px; margin-bottom: 12px; font-family: monospace; font-size: 0.9rem; word-break: break-all;">
/
</div>
<div id="folder-browser-list" style="max-height: 400px; overflow-y: auto; border: 1px solid var(--border); border-radius: 6px;">
<div style="padding: 20px; text-align: center; color: var(--muted);">Loading...</div>
</div>
<div id="folder-browser-selected" style="margin-top: 12px; padding: 10px; background: color-mix(in srgb, var(--success) 10%, transparent); border: 1px solid var(--success); border-radius: 6px; display: none;">
<div style="font-size: 0.85rem; color: var(--success); margin-bottom: 6px;">Selected folders:</div>
<div id="folder-browser-selected-list" style="display: flex; flex-wrap: wrap; gap: 6px;"></div>
</div>
<div class="weather-modal-buttons" style="margin-top: 16px; display: flex; gap: 8px; justify-content: space-between;">
<button id="folder-browser-select-current" class="btn-accent">
+ Add Current Folder
</button>
<div class="flex-row-gap">
<button id="folder-browser-cancel">Cancel</button>
<button id="folder-browser-done" style="background: color-mix(in srgb, var(--success) 20%, transparent); border-color: var(--success); color: var(--success);">Done</button>
</div>
</div>
</div>
</div>`),injectModal("service-creds-modal",`<div id="service-creds-modal">
<div class="service-creds-content">
<h3 id="svc-creds-title" style="margin: 0 0 4px; font-size: 1.05rem;">Service Credentials</h3>
<p id="svc-creds-desc" style="font-size: 0.75rem; color: var(--muted); margin: 0 0 14px;">Credentials are injected automatically when accessing this service.</p>
<!-- Status indicator -->
<div style="display: flex; align-items: center; gap: 6px; margin-bottom: 12px;">
<span id="svc-creds-dot" class="status-dot"></span>
<span id="svc-creds-status" class="text-muted-sm">No credentials stored</span>
</div>
<!-- Seedhost credentials (shown for external services) -->
<div id="svc-creds-seedhost" style="display: none; margin-bottom: 14px;">
<label class="label-bold">Seedhost Login</label>
<p class="hint-micro">Username shared across all services. Password is per-service.</p>
<input type="text" id="svc-seedhost-user" placeholder="Username (shared)" autocomplete="username"
style="width: 100%; padding: 8px 10px; margin-bottom: 6px; background: var(--bg); color: var(--fg); border: 1px solid var(--border); border-radius: 6px; font-size: 0.85rem; box-sizing: border-box;" />
<input type="password" id="svc-seedhost-pass" placeholder="Password" autocomplete="current-password"
class="input-creds" />
</div>
<!-- API Key (shown for arr services or services with API key support) -->
<div id="svc-creds-apikey" style="display: none; margin-bottom: 14px;">
<label class="label-bold">API Key</label>
<p class="hint-micro">Bypasses the app's own login screen</p>
<input type="text" id="svc-apikey-input" placeholder="API key"
style="width: 100%; padding: 8px 10px; background: var(--bg); color: var(--fg); border: 1px solid var(--border); border-radius: 6px; font-size: 0.85rem; font-family: monospace; box-sizing: border-box;" />
</div>
<!-- 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>
<!-- Buttons -->
<div style="display: flex; gap: 8px; margin-top: 14px;">
<button id="svc-creds-save" style="flex: 1; padding: 9px; background: var(--accent, #8FD6FF); color: #0b0f1a; border: none; border-radius: 6px; cursor: pointer; font-weight: 600; font-size: 0.85rem;">
Save
</button>
<button id="svc-creds-clear" style="padding: 9px 14px; background: transparent; color: var(--bad-fg, #ff9aa3); border: 1px solid var(--bad-fg, #ff9aa3); border-radius: 6px; cursor: pointer; font-size: 0.85rem; display: none;">
Clear
</button>
<button id="svc-creds-close" style="padding: 9px 16px; background: var(--card-base); color: var(--fg); border: 1px solid var(--border); border-radius: 6px; cursor: pointer; font-size: 0.85rem;">
Cancel
</button>
</div>
</div>
</div>`);const n=document.getElementById("service-creds-modal");let i=null;const g=["sonarr","radarr","prowlarr","overseerr"];window.openServiceCredsModal=async function(r){i=r;const E=document.getElementById("svc-creds-title"),f=document.getElementById("svc-creds-desc"),t=document.getElementById("svc-creds-seedhost"),m=document.getElementById("svc-creds-apikey"),s=document.getElementById("svc-creds-basic");E.textContent=r.name+" Credentials";const c=!!r.isExternal,y=g.includes(r.id)||g.includes(r.appTemplate);t.style.display=c?"":"none",m.style.display=y?"":"none",s.style.display=c?"none":"",c?(f.textContent="Seedhost credentials auto-login past the HTTP prompt. API key bypasses the app login.",document.getElementById("svc-seedhost-pass").placeholder=`Password for ${r.name}`):y?f.textContent="API key bypasses the app login screen automatically.":f.textContent="Credentials are injected automatically when accessing this service.",await p(r),n.classList.add("show")};async function p(r){const E=document.getElementById("svc-creds-dot"),f=document.getElementById("svc-creds-status"),t=document.getElementById("svc-creds-clear");let m=!1;if(r.isExternal){try{const c=await(await fetch(`/api/v1/seedhost-creds?serviceId=${r.id}`)).json();c.success?(document.getElementById("svc-seedhost-user").value=c.username||"",c.hasCredentials&&(m=!0)):document.getElementById("svc-seedhost-user").value=""}catch{}document.getElementById("svc-seedhost-pass").value=""}try{const c=await(await fetch(`/api/v1/services/${r.id}/credentials`)).json();c.success&&(c.hasApiKey?(document.getElementById("svc-apikey-input").value="\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022",m=!0):document.getElementById("svc-apikey-input").value="",c.hasBasicAuth&&!r.isExternal?(document.getElementById("svc-basic-user").value=c.username||"",m=!0):document.getElementById("svc-basic-user").value="")}catch{}if(document.getElementById("svc-basic-pass")&&(document.getElementById("svc-basic-pass").value=""),m){E.style.background="var(--ok-fg, #74dfc4)",f.style.color="var(--ok-fg, #74dfc4)",f.textContent="Credentials stored",t.style.display="";const s=document.getElementById(`creds-btn-${r.id}`);s&&s.classList.add("has-creds")}else E.style.background="var(--muted)",f.style.color="var(--muted)",f.textContent="No credentials stored",t.style.display="none"}document.getElementById("svc-creds-save")?.addEventListener("click",async()=>{if(!i)return;const r=document.getElementById("svc-creds-save");r.textContent="Saving...",r.disabled=!0;try{if(i.isExternal){const t=document.getElementById("svc-seedhost-user").value.trim(),m=document.getElementById("svc-seedhost-pass").value;t&&await secureFetch("/api/v1/seedhost-creds",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:t,password:m||void 0,serviceId:i.id})})}const f=document.getElementById("svc-apikey-input").value.trim();if(f&&f!=="\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022"&&await secureFetch(`/api/v1/services/${i.id}/credentials`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:f})}),!i.isExternal){const t=document.getElementById("svc-basic-user").value.trim(),m=document.getElementById("svc-basic-pass").value;t&&m&&await secureFetch(`/api/v1/services/${i.id}/credentials`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:t,password:m})})}await p(i)}catch(E){console.error("Failed to save credentials:",E)}r.textContent="Save",r.disabled=!1}),document.getElementById("svc-creds-clear")?.addEventListener("click",async()=>{if(i&&confirm(`Remove stored credentials for ${i.name}?`))try{i.isExternal&&await secureFetch(`/api/v1/seedhost-creds?serviceId=${i.id}`,{method:"DELETE"}),await secureFetch(`/api/v1/services/${i.id}/credentials`,{method:"DELETE"});const r=document.getElementById(`creds-btn-${i.id}`);r&&r.classList.remove("has-creds"),await p(i)}catch(r){console.error("Failed to clear credentials:",r)}}),document.getElementById("svc-creds-close")?.addEventListener("click",()=>{n.classList.remove("show"),i=null}),n?.addEventListener("click",r=>{r.target===n&&(n.classList.remove("show"),i=null)}),window.refreshCredsButtons=async function(){try{for(const r of window.APPS||[]){if(!r.isExternal&&!r.appTemplate&&!r.url)continue;let E=!1;if(r.isExternal)try{const m=await(await fetch(`/api/v1/seedhost-creds?serviceId=${r.id}`)).json();m.success&&m.hasCredentials&&(E=!0)}catch{}try{const m=await(await fetch(`/api/v1/services/${r.id}/credentials`)).json();m.success&&(m.hasApiKey||m.hasBasicAuth)&&(E=!0)}catch{}const f=document.getElementById(`creds-btn-${r.id}`);f&&f.classList.toggle("has-creds",E)}}catch{}}})(),(function(){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" style="width: 100%; padding: 12px; background: var(--accent, #8FD6FF); color: #0b0f1a; 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>
</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: 16px;">
<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>
<!-- 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" style="padding: 10px 20px; background: var(--accent, #8FD6FF); color: #0b0f1a; 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 n(){try{const r=await(await fetch("/api/v1/totp/config")).json();if(!r.success)return;const{enabled:E,sessionDuration:f,isSetUp:t}=r.config,m=document.getElementById("totp-status-dot"),s=document.getElementById("totp-status-text"),c=document.getElementById("totp-status-banner"),y=document.getElementById("totp-setup-section"),k=document.getElementById("totp-qr-section"),e=document.getElementById("totp-duration-section"),d=document.getElementById("totp-disable-section");E&&t?(m.style.background="var(--ok-fg, #7ef2ff)",c.style.borderColor="var(--ok-fg, #7ef2ff)",c.style.background="color-mix(in srgb, var(--ok-fg) 8%, transparent)",s.textContent="TOTP is active",s.style.color="var(--ok-fg, #7ef2ff)",y.style.display="none",k.style.display="none",e.style.display="block",d.style.display="block",document.getElementById("totp-duration-select").value=f):(m.style.background="var(--muted)",c.style.borderColor="var(--border)",c.style.background="transparent",s.textContent="TOTP is not configured",s.style.color="var(--muted)",y.style.display="block",k.style.display="none",e.style.display="none",d.style.display="none"),g(E&&t,f)}catch(p){console.warn("Failed to load TOTP settings:",p)}}const i={"15m":"15 min","30m":"30 min","1h":"1 hour","2h":"2 hours","4h":"4 hours","8h":"8 hours","12h":"12 hours","24h":"24 hours",never:"Disabled"};function g(p,r){const E=document.getElementById("auth-card"),f=document.getElementById("auth-pill"),t=document.getElementById("auth-dot"),m=document.getElementById("auth-status-text");E&&(p?(E.setAttribute("data-status","on"),f.className="badge on",f.textContent="YES",t.className="dot ok at-bl",m.textContent="Session: "+(i[r]||r)):(E.setAttribute("data-status","off"),f.className="badge off",f.textContent="NO",t.className="dot bad at-bl",m.textContent="Not configured"))}document.getElementById("totp-setup-btn")?.addEventListener("click",async()=>{try{const r=await(await secureFetch("/api/v1/totp/setup",{method:"POST"})).json();r.success&&(document.getElementById("totp-qr-image").src=r.qrCode,document.getElementById("totp-manual-key").textContent=r.manualKey,document.getElementById("totp-setup-section").style.display="none",document.getElementById("totp-qr-section").style.display="block",document.getElementById("totp-setup-code").value="",document.getElementById("totp-setup-error").textContent="",document.getElementById("totp-setup-code").focus())}catch(p){console.error("TOTP setup failed:",p)}}),document.getElementById("totp-import-btn")?.addEventListener("click",async()=>{const p=document.getElementById("totp-import-key").value.trim();if(p)try{const E=await(await secureFetch("/api/v1/totp/setup",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({secret:p})})).json();E.success?(document.getElementById("totp-qr-image").src=E.qrCode,document.getElementById("totp-manual-key").textContent=E.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()):(document.getElementById("totp-import-key").style.borderColor="var(--bad-fg)",setTimeout(()=>{document.getElementById("totp-import-key").style.borderColor=""},2e3))}catch(r){console.error("TOTP import failed:",r)}}),document.getElementById("totp-copy-key")?.addEventListener("click",()=>{const p=document.getElementById("totp-manual-key").textContent;navigator.clipboard.writeText(p).then(()=>{const r=document.getElementById("totp-copy-key");r.textContent="\u2705",setTimeout(()=>{r.textContent="\u{1F4CB}"},2e3)})}),document.getElementById("totp-confirm-setup")?.addEventListener("click",async()=>{const p=document.getElementById("totp-setup-code").value,r=document.getElementById("totp-setup-error");if(!/^\d{6}$/.test(p)){r.textContent="Enter a 6-digit code";return}try{const f=await(await secureFetch("/api/v1/totp/verify-setup",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:p})})).json();f.success?(r.textContent="",n()):r.textContent=f.error||"Invalid code"}catch{r.textContent="Connection error"}}),document.getElementById("totp-setup-code")?.addEventListener("keydown",p=>{p.key==="Enter"&&document.getElementById("totp-confirm-setup")?.click()}),document.getElementById("totp-duration-select")?.addEventListener("change",async p=>{try{await secureFetch("/api/v1/totp/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionDuration:p.target.value})}),n()}catch(r){console.error("Failed to update session duration:",r)}}),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&&n()}catch(p){console.error("Failed to disable TOTP:",p)}}),document.getElementById("auth-settings-btn")?.addEventListener("click",()=>{n(),openModal("totp-settings-modal")}),document.getElementById("totp-modal-close")?.addEventListener("click",()=>{closeModal("totp-settings-modal")}),document.getElementById("totp-settings-modal")?.addEventListener("click",p=>{p.target.id==="totp-settings-modal"&&closeModal("totp-settings-modal")}),window._updateAuthCard=g,(async()=>{try{const r=await(await fetch("/api/v1/totp/config")).json();if(r.success){const E=r.config.enabled&&r.config.isSetUp;g(E,r.config.sessionDuration)}}catch(p){console.error("[AuthCard] Failed to update:",p)}})()})(),(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 n(){return Object.keys(SITE.dnsServers||{})}function i(o){return(SITE.dnsServers||{})[o]?.name||o.toUpperCase()}function g(){const o=document.getElementById("dns-cred-sections");if(!o)return;o.innerHTML="";const u=n();if(u.length===0){o.innerHTML='<p style="color: var(--muted); text-align: center; padding: 20px;">No DNS servers configured.</p>';return}for(const w of u)o.insertAdjacentHTML("beforeend",`
<div class="token-section">
<h4 class="token-section-title">${i(w)}</h4>
<div class="token-grid">
<div class="token-field">
<label for="${w}-readonly-username">\u{1F4D6} Read-Only (Logs):</label>
<input type="text" id="${w}-readonly-username" placeholder="Username" autocomplete="off" style="margin-bottom: 4px;" />
<div class="token-input-row">
<input type="password" id="${w}-readonly-token" placeholder="Password" autocomplete="off" />
<button type="button" class="token-toggle" data-target="${w}-readonly-token">\u{1F441}</button>
</div>
</div>
<div class="token-field">
<label for="${w}-admin-username">\u{1F527} Admin:</label>
<input type="text" id="${w}-admin-username" placeholder="Username" autocomplete="off" style="margin-bottom: 4px;" />
<div class="token-input-row">
<input type="password" id="${w}-admin-token" placeholder="Password" autocomplete="off" />
<button type="button" class="token-toggle" data-target="${w}-admin-token">\u{1F441}</button>
</div>
</div>
</div>
<div class="token-status" id="${w}-token-status"></div>
</div>
`)}function p(){let o=safeSessionGet("dashcaddy-encryption-key");if(o)return o;const u=safeGet("dashcaddy-encryption-key");if(u)return safeSessionSet("dashcaddy-encryption-key",u),safeRemove("dashcaddy-encryption-key"),u;const w=new Uint8Array(32);return crypto.getRandomValues(w),o=Array.from(w,a=>a.toString(16).padStart(2,"0")).join(""),safeSessionSet("dashcaddy-encryption-key",o),o}const r=p();function E(o,u){if(!o)return"";const w=crypto.getRandomValues(new Uint8Array(8)),a=Array.from(w,L=>L.toString(16).padStart(2,"0")).join(""),I=new TextEncoder().encode(u+a);let B="";for(let L=0;L<o.length;L++){const A=o.charCodeAt(L)^I[L%I.length]^w[L%w.length]^L*31+17&255;B+=String.fromCharCode(A)}return a+":"+btoa(B)}function f(o,u){if(!o)return"";try{if(o.indexOf(":")===16){const B=o.substring(0,16),L=new Uint8Array(B.match(/.{2}/g).map($=>parseInt($,16))),A=atob(o.substring(17)),h=new TextEncoder().encode(u+B);let T="";for(let $=0;$<A.length;$++){const b=A.charCodeAt($)^h[$%h.length]^L[$%L.length]^$*31+17&255;T+=String.fromCharCode(b)}return T}const a=atob(o);let I="";for(let B=0;B<a.length;B++){const L=a.charCodeAt(B)^u.charCodeAt(B%u.length);I+=String.fromCharCode(L)}return I}catch{return""}}function t(o,u,w){const a=safeGet(`${o}-${u}-${w}-enc`);return f(a,r)}function m(o,u,w,a){const I=`${o}-${u}-${w}-enc`;a?safeSet(I,E(a,r)):safeRemove(I)}function s(o,u){return t(o,u,"token")}function c(o,u){return t(o,u,"username")}function y(o,u,w){m(o,u,"token",w)}function k(o,u,w){m(o,u,"username",w)}function e(){const o={};for(const u of n())o[u]={readonly:{username:c(u,"readonly"),token:s(u,"readonly")},admin:{username:c(u,"admin"),token:s(u,"admin")}};return o}function d(){n().forEach(o=>{["readonly","admin"].forEach(u=>{["token","username"].forEach(w=>{safeRemove(`${o}-${u}-${w}-enc`)})}),safeRemove(`${o}-token-enc`),safeRemove(`${o}-username-enc`)})}function v(o){const u=s(o,"readonly"),w=c(o,"readonly"),a=s(o,"admin"),I=c(o,"admin"),B=f(safeGet(`${o}-token-enc`),r),L=f(safeGet(`${o}-username-enc`),r);return{username:I||w||L,token:a||u||B,readonlyToken:u||B,readonlyUsername:w||L,adminToken:a||B,adminUsername:I||L}}document.getElementById("manage-tokens")?.addEventListener("click",()=>{g();const o=document.getElementById("token-management-modal"),u=e();n().forEach(w=>{const a=u[w];document.getElementById(`${w}-readonly-username`).value=a.readonly.username,document.getElementById(`${w}-readonly-token`).value=a.readonly.token,document.getElementById(`${w}-admin-username`).value=a.admin.username,document.getElementById(`${w}-admin-token`).value=a.admin.token,document.getElementById(`${w}-token-status`).textContent=""}),o.classList.add("show")}),document.getElementById("token-management-modal")?.addEventListener("click",o=>{const u=o.target.closest(".token-toggle");if(u){const w=u.dataset.target,a=document.getElementById(w);a.type==="password"?(a.type="text",u.textContent="\u{1F648}"):(a.type="password",u.textContent="\u{1F441}");return}o.target.id==="token-management-modal"&&o.target.classList.remove("show")}),document.getElementById("token-save")?.addEventListener("click",async()=>{const o=n();o.forEach(a=>{k(a,"readonly",document.getElementById(`${a}-readonly-username`).value.trim()),y(a,"readonly",document.getElementById(`${a}-readonly-token`).value.trim()),k(a,"admin",document.getElementById(`${a}-admin-username`).value.trim()),y(a,"admin",document.getElementById(`${a}-admin-token`).value.trim())});const u={};let w=!1;if(o.forEach(a=>{const I={},B=document.getElementById(`${a}-readonly-username`).value.trim(),L=document.getElementById(`${a}-readonly-token`).value.trim(),A=document.getElementById(`${a}-admin-username`).value.trim(),h=document.getElementById(`${a}-admin-token`).value.trim();B&&L&&(I.readonly={username:B,password:L},w=!0),A&&h&&(I.admin={username:A,password:h},w=!0),Object.keys(I).length>0&&(u[a]=I)}),w){o.forEach(a=>{u[a]&&(document.getElementById(`${a}-token-status`).textContent="Verifying...",document.getElementById(`${a}-token-status`).className="token-status")});try{const I=await(await secureFetch("/api/v1/dns/credentials",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({servers:u})})).json();I.results?o.forEach(B=>{const L=document.getElementById(`${B}-token-status`);if(!u[B]){L.textContent="";return}const A=I.results[B];A?.success?(L.textContent="\u2713 Verified & saved",L.className="token-status success"):A?.partial?(L.textContent="\u2713 "+A.partial,L.className="token-status success"):(L.textContent="\u2717 "+(A?.error||"Login failed"),L.className="token-status error")}):I.success?o.forEach(B=>{u[B]&&(document.getElementById(`${B}-token-status`).textContent="\u2713 Saved",document.getElementById(`${B}-token-status`).className="token-status success")}):o.forEach(B=>{u[B]&&(document.getElementById(`${B}-token-status`).textContent="\u2717 "+(I.error||"Failed"),document.getElementById(`${B}-token-status`).className="token-status error")})}catch(a){console.error("Failed to sync DNS credentials to backend:",a),o.forEach(I=>{u[I]&&(document.getElementById(`${I}-token-status`).textContent="\u2713 Saved locally (sync failed)",document.getElementById(`${I}-token-status`).className="token-status")})}}else o.forEach(a=>{document.getElementById(`${a}-token-status`).textContent=""});setTimeout(()=>{o.every(I=>{const B=document.getElementById(`${I}-token-status`)?.textContent;return!B||B.includes("\u2713")})&&closeModal("token-management-modal")},1500)}),document.getElementById("token-cancel")?.addEventListener("click",()=>{closeModal("token-management-modal")}),document.getElementById("token-clear-all")?.addEventListener("click",async()=>{if(confirm("Clear all stored DNS credentials? This cannot be undone.")){d(),n().forEach(o=>{document.getElementById(`${o}-readonly-username`).value="",document.getElementById(`${o}-readonly-token`).value="",document.getElementById(`${o}-admin-username`).value="",document.getElementById(`${o}-admin-token`).value="",document.getElementById(`${o}-token-status`).textContent="\u2713 Cleared",document.getElementById(`${o}-token-status`).className="token-status success"});try{await secureFetch("/api/v1/dns/credentials",{method:"DELETE"})}catch{}}}),window.getToken=s,window.getUsername=c,window.setToken=y,window.setUsername=k,window.getAllCredentials=e,window.getCredential=t,window.setCredential=m,window.getEncryptionKey=p,window.getDnsIds=n,window.getDnsDisplayName=i})(),(function(){function n(y,k,e=null){const d=document.getElementById(y+"-dot"),v=document.getElementById(y+"-pill"),o=document.getElementById(y+"-time"),u=document.querySelector(`[data-app="${y}"]`);d&&(d.classList.toggle("ok",k),d.classList.toggle("bad",!k)),v&&(v.textContent=k?"ON":"OFF",v.classList.toggle("on",k),v.classList.toggle("off",!k)),o&&e!==null&&(o.textContent=k?`${e}ms`:"timeout",o.className=`response-time ${i(e,k)}`),u&&u.setAttribute("data-status",k?"on":"off")}function i(y,k){return k?y<200?"excellent":y<500?"good":y<1e3?"fair":"slow":"timeout"}async function g(y){const k=performance.now();try{const e=await fetch("/probe/"+y,{cache:"no-store"}),d=performance.now(),v=Math.round(d-k);return{isUp:e.status>=200&&e.status<400||e.status===401||e.status===403,responseTime:v}}catch{const e=performance.now();return{isUp:!1,responseTime:Math.round(e-k)}}}window.APPS=[];let p=null,r=!1;async function E(){try{window.SkeletonLoader&&window.SkeletonLoader.show(6);const y=await fetch("/api/v1/services",{cache:"no-store"});y.ok?(window.APPS=await y.json(),window.SkeletonLoader&&window.SkeletonLoader.hide()):(console.error("Failed to load services:",y.status),window.SkeletonLoader&&window.SkeletonLoader.hide())}catch(y){console.error("Failed to load services:",y),window.SkeletonLoader&&window.SkeletonLoader.hide()}}function f(y){return buildServiceUrl(y)}function t(y,k,e){const d=document.createElement(y);return k&&(d.className=k),e&&(d.textContent=e),d}function m(){const y=document.getElementById("cards");y.innerHTML="";for(let k=0;k<window.APPS.length;k++){const e=window.APPS[k];if(e.id==="ca")continue;const d=t("div","card");d.setAttribute("data-app",e.id),d.setAttribute("data-status","off"),e.recipeId&&d.setAttribute("data-recipe-id",e.recipeId);const v=t("span","dot bad at-bl");v.id="dot-"+e.id+"-grid",d.appendChild(v);const o=t("div","row"),u=t("div","logo-wrap"),w=document.createElement("img");w.src=e.logo,w.alt=e.name,w.className="logo-img",w.onerror=function(){let x=e.id||e.appTemplate;if(!x&&e.name&&(x=e.name.toLowerCase().replace(/\s+/g,"-")),x){const C=[`https://cdn.jsdelivr.net/gh/walkxcode/dashboard-icons/png/${x}.png`,`https://cdn.jsdelivr.net/gh/walkxcode/dashboard-icons/png/${x.toLowerCase()}.png`,`https://cdn.jsdelivr.net/gh/walkxcode/dashboard-icons/png/${x.replace(/-/g,"")}.png`,`https://cdn.jsdelivr.net/gh/walkxcode/dashboard-icons/png/${e.name.toLowerCase().replace(/\s+/g,"-")}.png`],P=[...new Set(C)],D=P.indexOf(this.src)+1;D<P.length?this.src=P[D]:this.style.display="none"}else this.style.display="none"},u.appendChild(w),o.appendChild(u);const a=t("span","name",e.name);if(o.appendChild(a),e.tailscaleOnly){const x=t("span","ts-badge","\u{1F510}");x.title="Tailscale-only access",x.style.cssText="margin-left: 6px; font-size: 0.75rem; opacity: 0.8;",a.appendChild(x)}o.appendChild(t("span","spacer"));const I=t("span","badge off","OFF");I.id="badge-"+e.id,o.appendChild(I);const B=t("span","update-available-badge","UPDATE");B.id="update-badge-"+e.id,B.title="Update available",o.appendChild(B),d.appendChild(o);const L=t("div","response-row"),A=t("span","response-time","--");A.id="time-"+e.id,L.appendChild(A),d.appendChild(L);const h=t("div","health-row");h.id="health-"+e.id;const T=t("span","uptime-chip","--");T.id="uptime-"+e.id,h.appendChild(T);const $=document.createElement("div");$.className="uptime-mini-bar";const b=document.createElement("div");b.className="fill",b.id="uptime-bar-"+e.id,b.style.width="0%",$.appendChild(b),h.appendChild($),d.appendChild(h);const l=t("div","btn-row");if(e.containerId){const x=t("button","logs-btn","\u{1F4CB}");x.title="View container logs",x.onclick=P=>{P.stopPropagation(),window.openContainerLogsModal(e.containerId,e.name)},l.appendChild(x);const C=t("button","update-btn","\u2B06\uFE0F");C.title="Update container to latest version",C.id=`update-btn-${e.id}`,C.onclick=P=>{P.stopPropagation(),window.updateContainer(e.containerId,e.name,e.id)},l.appendChild(C)}if(e.logPath&&!e.containerId){const x=t("button","logs-btn","\u{1F4CB}");x.title="View application logs",x.onclick=C=>{C.stopPropagation(),window.openFileLogsModal(e.logPath,e.name)},l.appendChild(x)}if(e.isExternal||e.appTemplate||e.url){const x=t("button","creds-btn","\u{1F511}");x.title="Auto-login credentials",x.id=`creds-btn-${e.id}`,x.onclick=C=>{C.stopPropagation(),window.openServiceCredsModal(e)},l.appendChild(x)}if(e.id!=="internet"){const x=t("button","options-btn","\u2699\uFE0F");x.title="Edit service settings",x.onclick=C=>{C.stopPropagation(),window.openServiceEditModal(e)},l.appendChild(x)}if(e.id!=="internet"){const x=t("button","delete-btn","\u{1F5D1}\uFE0F");x.title="Delete this service",x.onclick=C=>{C.stopPropagation(),window.deleteService(e.id,e.name)},l.appendChild(x)}const S=t("button",null,"Open");S.onclick=()=>window.open(f(e.id),"_blank","noopener"),l.appendChild(S),d.appendChild(l),d.style.transitionDelay=`${Math.min(k*45,270)}ms`,y.appendChild(d)}requestAnimationFrame(()=>{y.querySelectorAll(".card").forEach(k=>k.classList.add("loaded"))}),window.groupRecipeCards&&requestAnimationFrame(()=>window.groupRecipeCards())}function s(y,k,e=null){const d=document.getElementById("dot-"+y+"-grid"),v=document.getElementById("badge-"+y),o=document.getElementById("time-"+y),u=document.querySelector(`[data-app="${y}"]`);d&&(d.classList.toggle("ok",k),d.classList.toggle("bad",!k)),v&&(v.textContent=k?"ON":"OFF",v.classList.toggle("on",k),v.classList.toggle("off",!k)),o&&e!==null&&(o.textContent=k?`${e}ms`:"timeout",o.className=`response-time ${i(e,k)}`),u&&u.setAttribute("data-status",k?"on":"off")}async function c(){if(p)return r=!0,p;function y(d,v=new Date){const o=document.getElementById("stamp");o&&(o.textContent=`${d}: ${new Date(v).toLocaleTimeString()}`)}function k(d){Object.keys(SITE.dnsServers).forEach(o=>{const u=d[o];u&&n(o,u.isUp,u.responseTime)}),d.internet&&n("internet",d.internet.isUp,d.internet.responseTime),window.APPS.forEach(o=>{const u=d[o.id];u&&s(o.id,u.isUp,u.responseTime)})}async function e(){const d=Object.keys(SITE.dnsServers),v=d.map(a=>g(a));v.push(g("internet"));const o=await Promise.all(v);d.forEach((a,I)=>n(a,o[I].isUp,o[I].responseTime));const u=o[o.length-1];n("internet",u.isUp,u.responseTime),(await Promise.all(window.APPS.map(async a=>{const I=await g(a.id);return{id:a.id,...I}}))).forEach(a=>{s(a.id,a.isUp,a.responseTime)})}return p=(async()=>{try{const d=await fetch("/api/v1/services/status",{cache:"no-store"});if(!d.ok)throw new Error(`Status refresh failed (${d.status})`);const v=await d.json();k(v.statuses||{}),y("last check",v.checkedAt||new Date)}catch(d){console.warn("Batched status refresh failed, falling back to direct probes:",d);try{await e(),y("last check")}catch(v){console.error("Dashboard refresh failed:",v),y("last failed")}}finally{p=null,r&&(r=!1,setTimeout(()=>{window.refreshAll()},0))}})(),p}document.querySelector(".top")?.addEventListener("click",y=>{const k=y.target.closest('[id$="-open"]');if(!k)return;const e=k.id.replace("-open","");SITE.dnsServers[e]&&window.open(f(e),"_blank","noopener")}),document.getElementById("ca-open")?.addEventListener("click",()=>window.open(f("ca"),"_blank","noopener")),document.getElementById("creds-btn-ca")?.addEventListener("click",y=>{y.stopPropagation();const k=window.APPS.find(e=>e.id==="ca");k&&window.openServiceCredsModal&&window.openServiceCredsModal(k)}),document.getElementById("options-btn-ca")?.addEventListener("click",y=>{y.stopPropagation();const k=window.APPS.find(e=>e.id==="ca");k&&window.openServiceEditModal&&window.openServiceEditModal(k)}),document.getElementById("delete-btn-ca")?.addEventListener("click",y=>{y.stopPropagation(),window.deleteService&&window.deleteService("ca","DashCA")}),window.loadServices=E,window.buildGrid=m,window.refreshAll=c,window.setQuick=n,window.setBadge=s,window.getResponseTimeClass=i,window.checkServiceWithTiming=g,window.serviceUrl=f,window.el=t})(),(function(){async function n(t){const s=await(await secureFetch(`/api/v1/dns/restart/${t}`,{method:"POST"})).json();if(!s.success)throw new Error(s.error||"Restart failed");return s}document.querySelector(".top")?.addEventListener("click",async t=>{const m=t.target.closest('[id$="-restart"]');if(!m)return;const s=m.id.replace("-restart","");if(SITE.dnsServers[s]&&confirm(`Restart ${s.toUpperCase()} service?`))try{await withButton(m,"...",()=>n(s)),setTimeout(window.refreshAll,DC.DELAYS.RELOAD)}catch(c){showNotification("Restart failed: "+c.message,"error")}});async function i(t,m){const s=document.getElementById(`${t}-update`),c=s?.textContent||"\u2B06\uFE0F";try{s.textContent="\u{1F50D}",s.disabled=!0,s.title="Checking for updates...";const k=await(await fetch(`/api/v1/dns/check-update?server=${encodeURIComponent(m)}`)).json();if(!k.success)throw new Error(k.error||"Failed to check for updates");if(!k.updateAvailable){s.textContent="\u2705",s.title=`Already on latest version (${k.currentVersion})`,showNotification(`${t.toUpperCase()} is already up to date! Current version: ${k.currentVersion}`,"info"),setTimeout(()=>{s.textContent=c,s.disabled=!1,s.title="Update DNS server"},3e3);return}if(!confirm(`Update available for ${t.toUpperCase()}!
Current: ${k.currentVersion}
New: ${k.updateVersion}
`+(k.updateTitle?`${k.updateTitle}
`:"")+`The DNS server will restart during the update.
Proceed?`)){s.textContent=c,s.disabled=!1,s.title="Update DNS server";return}s.textContent="\u{1F504}",s.title="Updating...";const v=await(await secureFetch(`/api/v1/dns/update?server=${encodeURIComponent(m)}`,{method:"POST"})).json();if(!v.success)throw new Error(v.error||"Update failed");if(v.manualUpdateRequired){s.textContent="\u2B06\uFE0F",s.title=`Update available: ${v.newVersion}`;const o=v.downloadLink?`
Download: ${v.downloadLink}`:"",u=v.instructionsLink?`
Instructions: ${v.instructionsLink}`:"";showNotification(`${t.toUpperCase()} update requires manual installation. Current: ${v.previousVersion} \u2192 ${v.newVersion}. Please update manually on the host machine.`,"warning",8e3),s.disabled=!1;return}s.textContent="\u2705",s.title="Updated successfully!",showNotification(`${t.toUpperCase()} updated successfully! ${v.previousVersion} \u2192 ${v.newVersion}. Server is restarting...`,"success"),setTimeout(()=>{s.textContent=c,s.disabled=!1,s.title="Update DNS server",window.refreshAll()},1e4)}catch(y){console.error("DNS update error:",y),s.textContent="\u274C",s.title="Update failed",showNotification(`Failed to update ${t.toUpperCase()}: ${y.message}`,"error"),setTimeout(()=>{s.textContent=c,s.disabled=!1,s.title="Update DNS server"},3e3)}}document.querySelector(".top")?.addEventListener("click",t=>{const m=t.target.closest('[id$="-update"]');if(!m)return;const s=m.id.replace("-update","");SITE.dnsServers[s]&&i(s,SITE.dnsServers[s]?.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 g=null;function p(t){g=t;const m=SITE.dnsServers[t]||{},s=document.getElementById("dns-settings-modal");document.getElementById("dns-settings-title").textContent=`${(m.name||t).toUpperCase()} Settings`,document.getElementById("dns-edit-ip").value=m.ip||"",document.getElementById("dns-edit-port").value=m.port||DC.DEFAULTS.DNS_PORT,document.getElementById("dns-edit-name").value=m.name||"",s.classList.add("show")}async function r(){if(!g)return;const t=document.getElementById("dns-edit-ip").value.trim(),m=document.getElementById("dns-edit-port").value.trim()||DC.DEFAULTS.DNS_PORT,s=document.getElementById("dns-edit-name").value.trim();if(!t){showNotification("Server IP is required","warning");return}const c={dnsServers:{}};c.dnsServers[g]={ip:t,port:String(m)},s&&(c.dnsServers[g].name=s);try{const k=await(await secureFetch("/api/v1/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)})).json();k.success?(SITE.dnsServers[g]=c.dnsServers[g],showNotification(`${g.toUpperCase()} settings saved`,"success"),f(),window.refreshAll()):showNotification(k.error||"Failed to save settings","error")}catch(y){showNotification("Failed to save: "+y.message,"error")}}async function E(){if(g&&confirm(`Remove ${g.toUpperCase()} from dashboard? This won't affect the actual DNS server.`))try{const m=await(await secureFetch("/api/v1/config")).json();m.dnsServers&&delete m.dnsServers[g];const c=await(await secureFetch("/api/v1/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({dnsServers:m.dnsServers||{}})})).json();if(c.success){delete SITE.dnsServers[g];const y=document.querySelector(`.top [data-app="${g}"]`);y&&y.remove(),showNotification(`${g.toUpperCase()} removed from dashboard`,"success"),f()}else showNotification(c.error||"Failed to remove","error")}catch(t){showNotification("Failed to remove: "+t.message,"error")}}function f(){closeModal("dns-settings-modal"),g=null}document.getElementById("dns-settings-cancel")?.addEventListener("click",f),document.getElementById("dns-settings-save")?.addEventListener("click",r),document.getElementById("dns-settings-delete")?.addEventListener("click",E),document.getElementById("dns-settings-modal")?.addEventListener("click",t=>{t.target.id==="dns-settings-modal"&&f()}),document.querySelector(".top")?.addEventListener("click",t=>{const m=t.target.closest('[id$="-settings"]');if(!m)return;const s=m.id.replace("-settings","");SITE.dnsServers[s]&&(t.stopPropagation(),p(s))}),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 n=null,i=null,g=!1,p=null,r=null,E=!1,f=null,t=null,m=!1,s=null,c=!1;async function y(b,l=25){try{const S=getDnsServerAddr(b),x=await fetch(`/api/v1/dns/logs?server=${S}&limit=${l}`,{cache:"no-store",headers:{Accept:"application/json","Cache-Control":"no-cache"}});if(x.ok){const C=await x.json();return C.success&&C.logs?{logs:C.logs,count:C.count,server:C.server}:{error:C.error||"Failed to fetch logs"}}else return x.status===401?{error:"DNS auto-auth failed - check credentials in settings"}:{error:`HTTP ${x.status}`}}catch(S){return console.error("DNS logs fetch failed:",S),{error:S.message}}}function k(b){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"}[b]||"var(--fg)"}function e(b){const l=document.createElement("div");if(l.className="log-entry",l.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;",b.parsed===!1)return l.style.gridTemplateColumns="1fr",l.innerHTML=`<span style="color: var(--muted); font-family: monospace; font-size: 0.75rem;">${escapeHtml(b.raw)}</span>`,l;const S=k(b.rcode),x=b.rcode==="Refused"||b.rcode==="REFUSED";return l.innerHTML=`
<span style="color: var(--muted); font-size: 0.75rem;">${escapeHtml(b.timestamp)}</span>
<span style="color: var(--accent); font-size: 0.75rem;" title="${escapeHtml(b.client)}">${escapeHtml(b.client)}</span>
<span style="font-weight: 500; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; ${x?"text-decoration: line-through; opacity: 0.6;":""}" title="${escapeHtml(b.domain)}">${escapeHtml(b.domain)}</span>
<span style="color: var(--muted); font-size: 0.75rem;">${escapeHtml(b.type)}</span>
<span style="color: ${S}; font-weight: 500; font-size: 0.75rem;">${escapeHtml(b.rcode)}</span>
`,l}async function d(){if(m){await T();return}if(E){await B();return}if(g||!n)return;const b=parseInt(document.getElementById("log-lines").value),l=document.getElementById("logs-content");try{const S=await y(n,b);if(S.error){l.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(S.error)}</div>
</div>`;return}l.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>`,S.logs&&S.logs.length>0?S.logs.forEach(x=>{const C=e(x);l.appendChild(C)}):l.innerHTML+=`
<div style="padding: 20px; text-align: center; color: var(--muted);">
No DNS queries logged yet
</div>`}catch(S){l.innerHTML=`
<div style="padding: 20px; text-align: center; color: var(--bad-fg);">
Failed to fetch logs: ${escapeHtml(S.message)}
</div>`}}function v(b){n=b,g=!1,E=!1;const l=document.getElementById("logs-modal"),S=document.getElementById("logs-title"),x=document.getElementById("logs-pause"),C=document.getElementById("logs-stream");S.textContent=`${b.toUpperCase()} DNS Logs`,x.textContent="\u23F8\uFE0F Pause",x.classList.remove("paused"),C&&(C.style.display="none"),l.classList.add("show"),d(),i=setInterval(d,DC.POLL.LOGS)}function o(){document.getElementById("logs-modal").classList.remove("show"),i&&(clearInterval(i),i=null),w(),n=null,E=!1,p=null,r=null,m=!1,f=null,t=null,g=!1}function u(b){s&&w();const l=document.getElementById("logs-stream"),S=document.getElementById("logs-pause"),x=document.getElementById("logs-content");i&&(clearInterval(i),i=null);try{s=new EventSource(`/api/v1/logs/stream/${b}`),c=!0,l.classList.add("active"),l.textContent="\u{1F534} Live",l.title="Streaming - click to stop",S.style.display="none";const C=document.getElementById("logs-title");C.textContent.includes("\u{1F534}")||(C.innerHTML=C.textContent.replace("\u{1F4CB}","\u{1F4CB} \u{1F534}")),s.onmessage=P=>{try{const O=JSON.parse(P.data);if(O.error){console.error("Stream error:",O.error),w();return}const D=document.createElement("div");D.className="log-entry",D.style.cssText="display: flex; gap: 12px; padding: 6px 10px; border-bottom: 1px solid var(--border); font-size: 0.8rem; align-items: flex-start; font-family: monospace;";const R=(O.stream||"stdout")==="stderr",U=R?"var(--bad-fg)":"var(--fg)",F=`<span style="background: ${R?"var(--bad-bg)":"var(--ok-bg)"}; color: ${U}; padding: 2px 6px; border-radius: 4px; font-size: 0.7rem; font-weight: 600; min-width: 50px; text-align: center;">${R?"STDERR":"STDOUT"}</span>`;for(D.innerHTML=`
<div style="flex-shrink: 0;">${F}</div>
<div style="flex: 1; color: ${U}; word-break: break-all; white-space: pre-wrap;">${escapeHtml(O.text)}</div>
`,x.appendChild(D),x.scrollTop=x.scrollHeight;x.children.length>500;)x.removeChild(x.firstChild)}catch(O){console.error("Error parsing stream data:",O)}},s.onerror=P=>{console.error("EventSource error:",P),w()}}catch(C){console.error("Failed to start streaming:",C),w()}}function w(){s&&(s.close(),s=null),c=!1;const b=document.getElementById("logs-stream"),l=document.getElementById("logs-pause"),S=document.getElementById("logs-title");b&&(b.classList.remove("active"),b.textContent="\u{1F4E1} Live",b.title="Enable real-time streaming"),l&&(l.style.display=""),S&&(S.textContent=S.textContent.replace(" \u{1F534}","")),E&&p&&!i&&(i=setInterval(B,DC.POLL.LOGS))}async function a(b,l=100){try{const S=`/api/v1/logs/container/${b}?tail=${l}&timestamps=true`,x=await fetch(S,{cache:"no-store",headers:{Accept:"application/json","Cache-Control":"no-cache"}});if(x.ok){const C=await x.json();return C.success&&C.logs?{logs:C.logs,count:C.count,containerName:C.containerName,containerId:C.containerId}:{error:C.error||"Failed to fetch container logs"}}else return{error:`HTTP ${x.status}: ${x.statusText}`}}catch(S){return console.error("Container logs fetch failed:",S),{error:S.message}}}function I(b){const l=document.createElement("div");l.className="log-entry",l.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 S=b.stream==="stderr"?"var(--bad-fg)":"var(--fg)",x=b.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 l.innerHTML=`
<div style="flex-shrink: 0;">${x}</div>
<div style="flex: 1; color: ${S}; word-break: break-all; white-space: pre-wrap;">${escapeHtml(b.text)}</div>
`,l}async function B(){if(g||!p||!E)return;const b=parseInt(document.getElementById("log-lines").value),l=document.getElementById("logs-content");try{const S=await a(p,b);if(S.error){l.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(S.error)}</div>
</div>`;return}l.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>`,S.logs&&S.logs.length>0?(S.logs.forEach(x=>{const C=I(x);l.appendChild(C)}),l.scrollTop=l.scrollHeight):l.innerHTML+=`
<div style="padding: 20px; text-align: center; color: var(--muted);">
No logs available for this container
</div>`}catch(S){l.innerHTML=`
<div style="padding: 20px; text-align: center; color: var(--bad-fg);">
Failed to fetch logs: ${escapeHtml(S.message)}
</div>`}}function L(b,l){p=b,r=l,E=!0,m=!1,g=!1,w();const S=document.getElementById("logs-modal"),x=document.getElementById("logs-title"),C=document.getElementById("logs-pause"),P=document.getElementById("logs-stream");x.textContent=`\u{1F4CB} ${l} - Container Logs`,C.textContent="\u23F8\uFE0F Pause",C.classList.remove("paused"),P&&(P.style.display=""),S.classList.add("show"),B(),i=setInterval(B,DC.POLL.LOGS)}async function A(b,l=100){try{const S=`/api/v1/logs/file?path=${encodeURIComponent(b)}&tail=${l}`,x=await fetch(S,{cache:"no-store",headers:{Accept:"application/json","Cache-Control":"no-cache"}});if(x.ok){const C=await x.json();return C.success&&C.logs?{logs:C.logs,count:C.count,logPath:C.logPath,totalLines:C.totalLines}:{error:C.error||"Failed to fetch file logs"}}else return{error:(await x.json().catch(()=>({}))).error||`HTTP ${x.status}`}}catch(S){return console.error("File logs fetch failed:",S),{error:S.message}}}function h(b){const l=document.createElement("div");l.className="log-entry",l.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 S=b.text;let x="INFO",C="var(--fg)";S.match(/ERROR|FATAL|CRITICAL/i)?(x="ERROR",C="var(--bad-fg)"):S.match(/WARN|WARNING/i)?(x="WARN",C="#f39c12"):S.match(/DEBUG/i)&&(x="DEBUG",C="var(--muted)");const O=`<span style="background: ${C==="var(--bad-fg)"?"var(--bad-bg)":"var(--ok-bg)"}; color: ${C}; padding: 2px 6px; border-radius: 4px; font-size: 0.7rem; font-weight: 600; min-width: 50px; text-align: center;">${x}</span>`;return l.innerHTML=`
<div style="flex-shrink: 0;">${O}</div>
<div style="flex: 1; color: ${C}; word-break: break-all; white-space: pre-wrap;">${escapeHtml(S)}</div>
`,l}async function T(){if(g||!f||!m)return;const b=parseInt(document.getElementById("log-lines").value),l=document.getElementById("logs-content");try{const S=await A(f,b);if(S.error){l.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(S.error)}</div>
</div>`;return}l.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 (${S.count} of ${S.totalLines} lines)</span>
</div>`,S.logs&&S.logs.length>0?(S.logs.forEach(x=>{const C=h(x);l.appendChild(C)}),l.scrollTop=l.scrollHeight):l.innerHTML+=`
<div style="padding: 20px; text-align: center; color: var(--muted);">
No logs available in this file
</div>`}catch(S){l.innerHTML=`
<div style="padding: 20px; text-align: center; color: var(--bad-fg);">
Failed to fetch logs: ${escapeHtml(S.message)}
</div>`}}function $(b,l){f=b,t=l,m=!0,E=!1,g=!1;const S=document.getElementById("logs-modal"),x=document.getElementById("logs-title"),C=document.getElementById("logs-pause"),P=document.getElementById("logs-stream");x.textContent=`\u{1F4CB} ${l} - Application Logs`,C.textContent="\u23F8\uFE0F Pause",C.classList.remove("paused"),P&&(P.style.display="none"),S.classList.add("show"),T(),i=setInterval(T,DC.POLL.LOGS)}document.querySelector(".top")?.addEventListener("click",b=>{const l=b.target.closest('[id$="-logs"]');if(!l)return;const S=l.id.replace("-logs","");SITE.dnsServers[S]&&v(S)}),document.getElementById("logs-close")?.addEventListener("click",o),document.getElementById("logs-pause")?.addEventListener("click",()=>{g=!g;const b=document.getElementById("logs-pause");g?(b.textContent="\u25B6\uFE0F Resume",b.classList.add("paused")):(b.textContent="\u23F8\uFE0F Pause",b.classList.remove("paused"),d())}),document.getElementById("log-lines")?.addEventListener("change",()=>{g||d()}),document.getElementById("logs-stream")?.addEventListener("click",()=>{!E||!p||(c?w():u(p))}),document.getElementById("logs-modal")?.addEventListener("click",b=>{b.target.id==="logs-modal"&&o()}),document.addEventListener("keydown",b=>{b.key==="Escape"&&document.getElementById("logs-modal")?.classList.contains("show")&&o()}),window.openContainerLogsModal=L,window.openFileLogsModal=$,window.openLogsModal=v})(),(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>
<div id="edit-service-name-display" style="font-weight: 600; font-size: 1.1rem;"></div>
<div id="edit-service-url-display" class="text-muted-sm"></div>
</div>
</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>
</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>
<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>
</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 n(E){try{const f=await fetch(`/api/v1/caddy/cas?caddyfilePath=${encodeURIComponent(E)}`);if(!f.ok)throw new Error(`Failed to load CAs: ${f.status}`);const t=await f.json();if(t.status==="success"){const m=document.getElementById("existing-ca-select");return m.innerHTML="",t.data.cas.length===0?m.innerHTML='<option value="">No CAs found in Caddyfile</option>':(m.innerHTML='<option value="">Select existing CA...</option>',t.data.cas.forEach(s=>{const c=document.createElement("option");typeof s=="object"?(c.value=s.id,c.textContent=s.displayName||s.name):(c.value=s,c.textContent=s),m.appendChild(c)})),t.data.cas}else throw new Error(t.message)}catch(f){console.error("Error loading CAs:",f);const t=document.getElementById("existing-ca-select");return t.innerHTML='<option value="">Error loading CAs</option>',[]}}function i(E){const{subdomain:f,port:t,ip:m,sslType:s,caName:c,existingCa:y,enableAuth:k,enableCors:e,customHeaders:d,upstreamPath:v,healthCheck:o,timeout:u,tailscaleOnly:w}=E;let a=`${buildDomain(f)} {
`;switch(w&&(a+=` @blocked not remote_ip 100.64.0.0/10
`,a+=` respond @blocked "Access denied. Tailscale connection required." 403
`),s){case"letsencrypt":break;case"caddy-managed":a+=` tls internal
`;break;case"existing-ca":y&&(a+=` tls {
ca ${y}
}
`);break;case"custom-ca":c&&(a+=` tls {
ca ${c}
}
`);break}if(k&&(a+=` basicauth {
admin $2a$14$hashed_password_here
}
`),e&&(a+=` header {
`,a+=` Access-Control-Allow-Origin "*"
`,a+=` Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS"
`,a+=` Access-Control-Allow-Headers "Content-Type, Authorization"
`,a+=` }
`),d)try{const I=JSON.parse(d);a+=` header {
`,Object.entries(I).forEach(([B,L])=>{a+=` ${B} "${L}"
`}),a+=` }
`}catch{console.warn("Invalid JSON in custom headers")}return o&&(a+=` health_uri ${o}
`),a+=` reverse_proxy ${m}:${t} {
`,v&&v!=="/"&&(a+=` rewrite ${v}
`),u&&u!==30&&(a+=` transport http {
`,a+=` dial_timeout ${u}s
`,a+=` response_header_timeout ${u}s
`,a+=` }
`),a+=` }
`,a+=`}
`,a}async function g(E,f,t=DC.DEFAULTS.TTL){const m=window.getToken(getPrimaryDnsId(),"admin");if(!m)throw new Error("DNS admin token not configured. Please set it in the Tokens menu.");const s=buildDomain(E),c=await secureFetch("/api/v1/dns/record",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:s,ip:f,ttl:t,token:m,server:SITE.dnsIp})});if(!c.ok){const k=await c.text();throw new Error(`DNS API Error: ${c.status} - ${k}`)}const y=await c.json();if(!y.success)throw new Error(`DNS Error: ${y.error||"Unknown error"}`);return y}async function p(E){const f={id:E.subdomain,name:E.name,logo:E.logo||`/assets/${E.subdomain}.png`};try{const t=await secureFetch("/api/v1/services",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(f)});if(!t.ok){const m=await t.json();throw new Error(m.error||"Failed to save service")}return await window.loadServices(),window.buildGrid(),f}catch(t){throw console.error("Failed to add service to config:",t),t}}async function r(E){const f=document.getElementById("service-subdomain-input").value.trim(),t=document.getElementById("service-ip-input").value.trim()||"localhost",m=document.getElementById("service-port-input").value.trim()||"80",s=await secureFetch("/api/v1/site",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:buildDomain(f),upstream:`${t}:${m}`,config:E})}),c=await s.json();if(!s.ok||!c.success)throw new Error(c.error||`Caddy API Error: ${s.status}`);return c}window.loadExistingCAs=n,window.generateCaddyConfig=i,window.createDnsRecord=g,window.addServiceToConfig=p,window.addToCaddyfile=r})(),(function(){let n=null;function i(t){n=t;const m=document.getElementById("service-edit-modal");document.getElementById("service-edit-title").textContent=`Edit ${t.name}`,document.getElementById("edit-service-name-display").textContent=t.name,document.getElementById("edit-service-url-display").textContent=t.url||buildServiceUrl(t.id),document.getElementById("edit-service-logo-preview").src=t.logo||`/assets/${t.id}.png`,document.getElementById("edit-subdomain").value=t.id,document.getElementById("edit-port").value=t.port||"",document.getElementById("edit-ip").value=t.ip||"localhost",document.getElementById("edit-tailscale-only").checked=t.tailscaleOnly||!1,document.getElementById("edit-logo-url").value=t.logo||"",m.classList.add("show")}function g(){closeModal("service-edit-modal"),n=null}async function p(){if(!n)return;const t=document.getElementById("edit-subdomain").value.trim().toLowerCase(),m=document.getElementById("edit-port").value.trim(),s=document.getElementById("edit-ip").value.trim()||"localhost",c=document.getElementById("edit-tailscale-only").checked,y=document.getElementById("edit-logo-url").value.trim();if(!t){showNotification("Subdomain is required","warning");return}const k=n.id,e=[];if(t!==k&&e.push("subdomain"),m&&m!==String(n.port)&&e.push("port"),s!==n.ip&&e.push("ip"),c!==(n.tailscaleOnly||!1)&&e.push("tailscale"),y!==n.logo&&e.push("logo"),e.length===0){g();return}const d=document.getElementById("service-edit-save");d.textContent="Saving...",d.disabled=!0;try{if(e.includes("subdomain")||e.includes("port")||e.includes("ip")||e.includes("tailscale")){const u=await(await secureFetch("/api/v1/services/update",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({oldSubdomain:k,newSubdomain:t,port:m||n.port,ip:s,tailscaleOnly:c})})).json();if(!u.success)throw new Error(u.error||"Failed to update service")}const v=window.APPS.findIndex(o=>o.id===k);v!==-1&&(window.APPS[v]={...window.APPS[v],id:t,port:m||window.APPS[v].port,ip:s,tailscaleOnly:c,logo:y||window.APPS[v].logo}),await secureFetch("/api/v1/services",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({id:t,name:n.name,port:m||n.port,ip:s,logo:y||n.logo,tailscaleOnly:c,containerId:n.containerId,appTemplate:n.appTemplate})}),t!==k&&await secureFetch(`/api/v1/services/${k}`,{method:"DELETE"}),g(),window.buildGrid(),window.refreshAll()}catch(v){console.error("Error saving service changes:",v),showNotification(`Error saving changes: ${v.message}`,"error")}finally{d.textContent="Save Changes",d.disabled=!1}}document.getElementById("edit-logo-file")?.addEventListener("change",async t=>{const m=t.target.files[0];if(!m)return;if(!m.type.startsWith("image/")){showNotification("Please select an image file","warning");return}const s=new FileReader;s.onload=async c=>{const y=c.target.result;if(document.getElementById("edit-service-logo-preview").src=y,document.getElementById("edit-logo-url").value=y,n)try{const e=await(await secureFetch("/api/v1/assets/upload",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filename:`${n.id}.png`,data:y})})).json();e.success&&e.path&&(document.getElementById("edit-logo-url").value=e.path)}catch{}},s.readAsDataURL(m)}),document.getElementById("service-edit-cancel")?.addEventListener("click",g),document.getElementById("service-edit-save")?.addEventListener("click",p),document.getElementById("service-edit-modal")?.addEventListener("click",t=>{t.target.id==="service-edit-modal"&&g()});function r(t,m,s){return new Promise(c=>{const y=document.getElementById("delete-service-modal"),k=document.getElementById("delete-modal-title"),e=document.getElementById("delete-modal-message"),d=document.getElementById("delete-modal-container-info"),v=document.getElementById("delete-modal-container-name"),o=document.getElementById("delete-modal-help"),u=document.getElementById("delete-modal-cancel"),w=document.getElementById("delete-modal-remove"),a=document.getElementById("delete-modal-delete");k.textContent=`Delete "${t}"`,m?(e.innerHTML="This service has an associated Docker container.<br>Choose how to proceed:",d.style.display="block",v.textContent=`Container ID: ${s?.slice(0,12)||"Unknown"}`,o.style.display="block",a.style.display="block"):(e.textContent="Remove this service from the dashboard?",d.style.display="none",o.style.display="none",a.style.display="none");const I=()=>{y.classList.remove("show"),u.removeEventListener("click",B),w.removeEventListener("click",L),a.removeEventListener("click",A),y.removeEventListener("click",h)},B=()=>{I(),c(null)},L=()=>{I(),c(!1)},A=()=>{I(),c(!0)},h=T=>{T.target===y&&(I(),c(null))};u.addEventListener("click",B),w.addEventListener("click",L),a.addEventListener("click",A),y.addEventListener("click",h),y.classList.add("show")})}async function E(t,m,s){const c=document.getElementById(`update-btn-${s}`),y=c?.textContent;if(confirm(`Update ${m} 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{c&&(c.textContent="\u{1F504}",c.disabled=!0,c.title="Updating...");const e=await(await secureFetch(`/api/v1/containers/${t}/update`,{method:"POST"})).json();if(e.success){const d=window.APPS.find(v=>v.id===s);d&&e.newContainerId&&(d.containerId=e.newContainerId),c&&(c.textContent="\u2705",c.title="Updated successfully!",setTimeout(()=>{c.textContent=y,c.disabled=!1,c.title="Update container to latest version"},3e3)),setTimeout(()=>window.refreshAll(),2e3),showNotification(`${m} updated successfully!`,"success")}else throw new Error(e.error||"Update failed")}catch(k){console.error("Update error:",k),c&&(c.textContent="\u274C",c.title="Update failed",setTimeout(()=>{c.textContent=y,c.disabled=!1,c.title="Update container to latest version"},3e3)),showNotification(`Failed to update ${m}: ${k.message}`,"error")}}async function f(t,m){const s=window.APPS.find(a=>a.id===t),c=s?buildDomain(s.id):null,y=s?.containerId,k=await r(m||t,y,s?.containerId);if(k===null)return;let e={dashboard:!1,container:null,dns:null,caddy:null,service:null};if(k&&y)try{const a=new URLSearchParams({containerId:s.containerId,subdomain:s.id,ip:s.ip||"localhost",deleteContainer:"true"}),B=await(await secureFetch(`/api/v1/apps/${encodeURIComponent(s.id)}?${a.toString()}`,{method:"DELETE"})).json();B.success?e={...e,...B.results,dashboard:!1}:console.error("App removal failed:",B.error)}catch(a){console.error("App removal error:",a)}else if(k&&c){try{const a=s?.ip||"localhost",B=await(await secureFetch(`/api/v1/dns/record?domain=${encodeURIComponent(c)}&type=A&ipAddress=${encodeURIComponent(a)}&server=${SITE.dnsIp}`,{method:"DELETE"})).json();e.dns=B.success?"deleted":B.error||"failed"}catch(a){e.dns=a.message}try{const I=await(await secureFetch(`/api/v1/site/${encodeURIComponent(c)}`,{method:"DELETE"})).json();e.caddy=I.success||I.error&&I.error.includes("not found")?"removed":I.error||"failed"}catch(a){e.caddy=a.message}}const d=window.APPS.findIndex(a=>a.id===t);d>-1&&(window.APPS.splice(d,1),e.dashboard=!0);try{const a=safeGetJSON("custom-apps",[]),I=a.findIndex(B=>B.id===t);I>-1&&(a.splice(I,1),safeSet("custom-apps",JSON.stringify(a)))}catch{}try{const I=await(await secureFetch(`/api/v1/services/${encodeURIComponent(t)}`,{method:"DELETE"})).json();e.service=I.success?"removed":I.error||"failed"}catch(a){e.service=a.message}window.buildGrid(),window.refreshAll();let v=!1,o=[];e.dashboard||(v=!0,o.push("\u2717 Failed to remove from dashboard"));const u=["removed","already removed","not found","deleted","kept (user choice)","skipped","no such record","does not exist"],w=a=>!a||u.some(I=>a.toLowerCase().includes(I.toLowerCase()));e.container&&!w(e.container)&&(v=!0,o.push(`\u26A0 Container: ${e.container}`)),e.dns&&!w(e.dns)&&(v=!0,o.push(`\u26A0 DNS Record: ${e.dns}`)),e.caddy&&!w(e.caddy)&&(v=!0,o.push(`\u26A0 Caddy Config: ${e.caddy}`)),e.service&&!w(e.service)&&(v=!0,o.push(`\u26A0 Service File: ${e.service}`)),v&&showNotification(`Error deleting "${m||t}": ${o.join(", ")}`,"error",6e3)}window.openServiceEditModal=i,window.showDeleteModal=r,window.updateContainer=E,window.deleteService=f})(),(function(){function n(e){return e.toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,"").replace(/-+/g,"-").replace(/^-|-$/g,"")}function i(){return SITE.defaults?.sslType||(SITE.configurationType==="public"?"letsencrypt":"caddy-managed")}function g(){const e=document.getElementById("service-subdomain-input").value||"subdomain",d=document.getElementById("service-ip-input").value||p.lan||"localhost",v=document.getElementById("service-port-input").value||DC.DEFAULTS.SERVICE_PORT,o=document.getElementById("ssl-type-select").value,u=document.getElementById("ca-name-input").value||"sami-ca",w=document.getElementById("existing-ca-select").value,a=document.getElementById("enable-auth").checked,I=document.getElementById("enable-cors").checked,B=document.getElementById("custom-headers-input").value,L=document.getElementById("upstream-path-input").value||"/",A=document.getElementById("health-check-input").value,h=document.getElementById("timeout-input").value||30,T=document.getElementById("dns-preview");T&&(T.textContent=`${buildDomain(e)} \u2192 ${d}`);const $=document.getElementById("url-preview");$&&($.textContent=buildServiceUrl(e));const b={subdomain:e,port:v,ip:d,sslType:o,caName:u,existingCa:w,enableAuth:a,enableCors:I,customHeaders:B,upstreamPath:L,healthCheck:A,timeout:h},l=window.generateCaddyConfig(b),S=document.getElementById("caddy-config-preview");S&&(S.value=l)}const p={localhost:"127.0.0.1",lan:"",tailscale:""};async function r(){try{const o=await fetch("/api/v1/network/ips",{signal:AbortSignal.timeout(2e3)});if(o.ok){const u=await o.json();u.lan&&(p.lan=u.lan),u.tailscale&&(p.tailscale=u.tailscale)}}catch{}const e=document.getElementById("quick-ip-lan"),d=document.getElementById("quick-ip-tailscale");e&&(p.lan?(e.dataset.ip=p.lan,e.textContent=`LAN (${p.lan})`,e.title=`LAN IP: ${p.lan}`):e.style.display="none"),d&&(p.tailscale?(d.dataset.ip=p.tailscale,d.textContent=`Tailscale (${p.tailscale})`,d.title=`Tailscale IP: ${p.tailscale}`):d.style.display="none");const v=document.getElementById("service-ip-input");v&&!v.value&&p.lan&&(v.value=p.lan)}function E(){document.querySelectorAll(".quick-ip-btn").forEach(e=>{e.addEventListener("click",()=>{const d=e.dataset.ip;d&&(document.getElementById("service-ip-input").value=d,document.querySelectorAll(".quick-ip-btn").forEach(v=>v.classList.remove("active")),e.classList.add("active"),g())})}),document.getElementById("service-ip-input")?.addEventListener("input",e=>{const d=e.target.value;document.querySelectorAll(".quick-ip-btn").forEach(v=>{v.classList.toggle("active",v.dataset.ip===d)})})}async function f(){const e=document.getElementById("add-service-modal");e.classList.add("show");const d=e.querySelector(".weather-modal-content");d&&(d.scrollTop=0),document.body.style.overflow="hidden";const v=document.getElementById("ssl-type-select");v&&(v.value=i()),await r();const o=document.getElementById("caddyfile-path-input").value||DC.DEFAULTS.CADDYFILE;await window.loadExistingCAs(o);const u=document.getElementById("manual-tailscale-status"),w=document.getElementById("manual-tailscale-only");try{const I=await(await fetch("/api/v1/tailscale/status")).json();I.success&&I.installed&&I.connected?(u.innerHTML=`
<span style="color: #4caf50;">\u2713 Connected</span>
<span style="color: var(--muted); margin-left: 6px;">${I.self?.hostname} (${I.self?.ip})</span>
`,w.disabled=!1):I.installed?(u.innerHTML='<span style="color: #ff9800;">\u26A0 Not connected</span>',w.disabled=!0):(u.innerHTML='<span style="color: var(--muted);">Not available</span>',w.disabled=!0)}catch{u.innerHTML='<span style="color: var(--muted);">Could not check</span>',w.disabled=!0}w.checked=!1,g()}function t(){const e=document.getElementById("service-type-local"),d=document.getElementById("service-type-external"),v=document.getElementById("local-service-config"),o=document.getElementById("external-service-config"),u=document.getElementById("tab-local"),w=document.getElementById("tab-external");function a(){e.checked?(v.style.display="grid",o.style.display="none",u&&(u.style.background="var(--accent)",u.style.color="var(--bg)"),w&&(w.style.background="transparent",w.style.color="var(--muted)")):(v.style.display="none",o.style.display="block",w&&(w.style.background="var(--accent)",w.style.color="var(--bg)"),u&&(u.style.background="transparent",u.style.color="var(--muted)"))}e?.addEventListener("change",a),d?.addEventListener("change",a)}function m(){const e=document.getElementById("service-name-input"),d=document.getElementById("service-subdomain-input"),v=document.getElementById("subdomain-preview");let o=!1;e?.addEventListener("input",()=>{const L=n(e.value);!o&&d&&(d.value=L),v&&(v.textContent=L?`\u2192 ${buildDomain(L)}`:""),g()}),d?.addEventListener("input",()=>{o=d.value!==n(e?.value||"");const L=d.value.trim()||n(e?.value||"");v&&(v.textContent=L?`\u2192 ${buildDomain(L)}`:""),g()});const u=document.getElementById("external-service-name"),w=document.getElementById("external-service-subdomain"),a=document.getElementById("external-subdomain-preview"),I=document.getElementById("external-domain-preview");let B=!1;u?.addEventListener("input",()=>{const L=n(u.value);!B&&w&&(w.value=L);const A=w?.value||L;a&&(a.textContent=A?`\u2192 ${buildDomain(A)}`:""),I&&(I.textContent=A?buildDomain(A):"")}),w?.addEventListener("input",()=>{B=w.value!==n(u?.value||"");const L=w.value.trim()||n(u?.value||"");a&&(a.textContent=L?`\u2192 ${buildDomain(L)}`:""),I&&(I.textContent=L?buildDomain(L):"")})}async function s(){const e=document.getElementById("external-service-name").value.trim(),d=document.getElementById("external-service-url").value.trim(),v=(document.getElementById("external-service-subdomain").value.trim()||n(e)).toLowerCase(),o=document.getElementById("external-service-logo").value.trim(),u=document.getElementById("external-service-icon").value.trim(),w=document.getElementById("external-create-dns").checked,a=document.getElementById("external-create-caddy").checked,I=document.getElementById("external-proxy-ip").value.trim()||SITE.dnsIp||"localhost",B=document.getElementById("external-preserve-host").checked,L=document.getElementById("external-follow-redirects").checked;if(!e||!d){showNotification("Please fill in Name and External URL","warning");return}if(!v){showNotification("Could not derive subdomain from name. Please set one in Options.","warning");return}if(!d.startsWith("http://")&&!d.startsWith("https://")){showNotification("External URL must start with http:// or https://","warning");return}const A=buildDomain(v);try{const h={dns:null,caddy:null,dashboard:!1};if(w)if(window.getToken(getPrimaryDnsId(),"admin"))try{const C=await(await secureFetch("/api/v1/dns/record",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:A,ip:I,ttl:DC.DEFAULTS.TTL,server:SITE.dnsIp})})).json();h.dns=C.success?"created":C.error||"failed"}catch(x){h.dns=x.message}else h.dns="no admin token (configure in \u{1F511} Tokens)";if(a)try{const S={subdomain:v,externalUrl:d,preserveHost:B,followRedirects:L,sslType:"caddy-managed",caddyfilePath:DC.DEFAULTS.CADDYFILE,reloadCaddy:!0},C=await(await secureFetch("/api/v1/site/external",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(S)})).json();h.caddy=C.success?"created":C.error||"failed"}catch(S){h.caddy=S.message}const T={id:v,name:e,url:`https://${A}`,externalUrl:d,logo:o||u||"\u{1F310}",isExternal:!0,isCustom:!0};window.APPS.push(T),h.dashboard=!0;const $=["plex","router","chat","sync","torrent","radarr","sonarr","prowlarr","portainer","requests","jellyfin","emby"],b=window.APPS.filter(S=>!$.includes(S.id));safeSet("custom-services",JSON.stringify(b));try{await secureFetch("/api/v1/services",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(window.APPS)})}catch(S){console.warn("Failed to save to services.json:",S)}window.buildGrid(),window.refreshAll(),c();const l=[`External service "${e}" added!`];w&&l.push(`DNS: ${h.dns==="created"?"\u2713":"\u26A0 "+h.dns}`),a&&l.push(`Caddy: ${h.caddy==="created"?"\u2713":"\u26A0 "+h.caddy}`),l.push(`Access at: https://${A}`),showNotification(l.join(" | "),"success",6e3)}catch(h){console.error("Failed to create external service:",h),showNotification(`Failed to create external service: ${h.message}`,"error")}}function c(){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=p.lan||"",document.getElementById("service-logo-input").value="",document.getElementById("dns-ttl-input").value=DC.DEFAULTS.TTL,document.getElementById("ssl-type-select").value=i(),document.getElementById("ca-name-input").value="",document.getElementById("enable-auth").checked=!1,document.getElementById("enable-cors").checked=!1,document.getElementById("custom-headers-input").value="",document.getElementById("upstream-path-input").value="/",document.getElementById("health-check-input").value="",document.getElementById("timeout-input").value="30";const e=document.getElementById("subdomain-preview");e&&(e.textContent="");const d=document.getElementById("external-subdomain-preview");d&&(d.textContent="");const v=document.getElementById("external-service-name");v&&(v.value="");const o=document.getElementById("external-service-subdomain");o&&(o.value="");const u=document.getElementById("external-service-url");u&&(u.value="");const w=document.getElementById("external-service-logo");w&&(w.value="");const a=document.getElementById("external-service-icon");a&&(a.value="");const I=document.getElementById("local-advanced-options");I&&I.removeAttribute("open");const B=document.getElementById("external-advanced-options");B&&B.removeAttribute("open");const L=document.getElementById("service-type-local");L&&(L.checked=!0);const A=document.getElementById("local-service-config"),h=document.getElementById("external-service-config");A&&(A.style.display="grid"),h&&(h.style.display="none");const T=document.getElementById("tab-local"),$=document.getElementById("tab-external");T&&(T.style.background="var(--accent)",T.style.color="var(--bg)"),$&&($.style.background="transparent",$.style.color="var(--muted)")}async function y(){const e=document.getElementById("service-name-input").value.trim(),d=(document.getElementById("service-subdomain-input").value.trim()||n(e)).toLowerCase(),v=document.getElementById("service-port-input").value.trim(),o=document.getElementById("service-ip-input").value.trim(),u=document.getElementById("service-logo-input").value.trim(),w=document.getElementById("create-dns-record").checked,a=parseInt(document.getElementById("dns-ttl-input").value)||DC.DEFAULTS.TTL,I=document.getElementById("manual-tailscale-only")?.checked||!1,B=document.getElementById("ssl-type-select")?.value||"caddy-managed",L=document.getElementById("ca-name-input")?.value||"",A=document.getElementById("existing-ca-select")?.value||"",h=document.getElementById("enable-auth")?.checked||!1,T=document.getElementById("enable-cors")?.checked||!1,$=document.getElementById("custom-headers-input")?.value||"",b=document.getElementById("upstream-path-input")?.value||"/",l=document.getElementById("health-check-input")?.value||"",S=document.getElementById("timeout-input")?.value||30,x=window.getToken(getPrimaryDnsId(),"admin");if(!e||!v||!o){showNotification("Please fill in Name, Port, and IP Address","warning");return}if(!d){showNotification("Could not derive subdomain from name. Please set one in Options.","warning");return}if(w&&!x){showNotification("DNS Admin token required. Configure it in the Tokens menu first.","warning");return}const C={dns:null,caddy:null,dashboard:!1};try{if(w)try{await window.createDnsRecord(d,o,a),C.dns="created"}catch(N){throw console.error("DNS creation failed:",N),C.dns=N.message,new Error(`DNS creation failed: ${N.message}`)}else C.dns="skipped";const P=window.generateCaddyConfig({subdomain:d,port:v,ip:o,sslType:B,caName:L,existingCa:A,enableAuth:h,enableCors:T,customHeaders:$,upstreamPath:b,healthCheck:l,timeout:S,tailscaleOnly:I});try{const R=await(await secureFetch("/api/v1/site",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:buildDomain(d),upstream:`${o}:${v}`,config:P})})).json();if(R.success)C.caddy="added & reloaded";else throw console.error("Caddy configuration failed:",R.error),C.caddy=R.error||"failed",new Error(`Caddy configuration failed: ${R.error}`)}catch(N){throw console.error("Caddy API error:",N),C.caddy=N.message,new Error(`Caddy API error: ${N.message}`)}const O={name:e,subdomain:d,port:v,ip:o,logo:u||`/assets/${d}.png`,tailscaleOnly:I||!1};await window.addServiceToConfig(O),C.dashboard=!0;const D=[`DNS: ${C.dns==="created"?"\u2713":C.dns==="skipped"?"\u25CB":"\u2717"}`,`Caddy: ${C.caddy==="added & reloaded"?"\u2713":"\u2717"}`,`Dashboard: ${C.dashboard?"\u2713":"\u2717"}`];showNotification(`Service "${e}" created! ${D.join(" | ")} \u2014 ${buildServiceUrl(d)}${I?" (Tailscale)":""}`,"success",6e3),c(),window.buildGrid(),window.refreshAll()}catch(P){console.error("Error creating service:",P),showNotification(`Error creating "${e}": ${P.message}`,"error",6e3)}}document.getElementById("add-service")?.addEventListener("click",f),document.getElementById("add-service-cancel")?.addEventListener("click",c),document.getElementById("add-service-create")?.addEventListener("click",()=>{document.querySelector('input[name="service-type"]:checked')?.value==="external"?s():y()}),t(),m(),E(),document.getElementById("ssl-type-select")?.addEventListener("change",e=>{const d=document.getElementById("existing-ca-config"),v=document.getElementById("custom-ca-config");d.style.display="none",v.style.display="none",e.target.value==="existing-ca"?d.style.display="block":e.target.value==="custom-ca"&&(v.style.display="block"),g()}),document.getElementById("refresh-cas")?.addEventListener("click",async()=>{const e=document.getElementById("refresh-cas"),d=e.textContent;e.textContent="\u231B Loading...",e.disabled=!0;try{const v=document.getElementById("caddyfile-path-input").value||DC.DEFAULTS.CADDYFILE;await window.loadExistingCAs(v),e.textContent="\u2705 Refreshed"}catch(v){e.textContent="\u274C Failed",console.error("Failed to refresh CAs:",v)}setTimeout(()=>{e.textContent=d,e.disabled=!1},2e3)}),document.getElementById("create-dns-record")?.addEventListener("change",e=>{const d=document.getElementById("dns-config");d.style.display=e.target.checked?"block":"none"}),["service-subdomain-input","service-ip-input","service-port-input","ca-name-input","existing-ca-select","enable-auth","enable-cors","custom-headers-input","upstream-path-input","health-check-input","timeout-input"].forEach(e=>{const d=document.getElementById(e);d&&(d.addEventListener("input",g),d.addEventListener("change",g))});function k(){const e=safeGet("custom-services");if(e)try{JSON.parse(e).forEach(v=>{window.APPS.find(o=>o.id===v.id)||window.APPS.push(v)})}catch(d){console.warn("Failed to load custom services:",d)}}k(),window.openAddServiceModal=f,window.closeAddServiceModal=c})();