[glm-grade=A] feat(api): error-log filter + pagination + distinct-contexts (DC-052)

Backend (dashcaddy-api/routes/errorlogs.js):
- GET /error-logs: server-side filter chain (level, context substring,
  free-text search across error/context/detail/IP, ISO since/until),
  real pagination via limit/offset with hasMore reporting, MAX_LIMIT=500
  clamp, newest-first sort.
- New endpoint GET /error-logs/contexts returns distinct contexts with
  occurrence counts for the frontend dropdown.
- Robust entry parser handles malformed blocks as raw entries so nothing
  silently disappears from the operator's view.
- DELETE /error-logs requires { confirm: 'CLEAR' } body and audits the
  wipe itself (mirrors DC-050 hardening).
- DC-052 fix: removed legacy /audit-logs GET/DELETE handlers that lived
  here before DC-050. errorLogsRoutes is mounted in src/app.js (L733)
  BEFORE auditLogRoutes (L789), so Express router.use() semantics meant
  the legacy proxies shadowed DC-050's hardened versions — DELETE
  without confirm=CLEAR would silently wipe the audit log, and
  /audit-logs/actions was unreachable. The hardened routes/audit-log.js
  is now the single source of truth.

Frontend (status/js/error-logs.js):
- Level / Context / Search / Since / Until filter row mirroring the
  audit-log UI (DC-050).
- Load More pagination with abort-on-filter-change.
- Click-to-expand stack frames in <pre> with scroll-cap.
- Contexts dropdown populated from /error-logs/contexts (refreshes on
  every modal open and after a clear).
- confirm=CLEAR clear with success/error notification.

Tests (__tests__/routes/errorlogs.routes.test.js — 20 cases, all pass):
- Endpoint shape, newest-first, level/context/search/since/until filters,
  invalid-since + unknown-level 400s, pagination + hasMore, MAX_LIMIT
  clamp, /contexts distinct list, confirm=CLEAR gating + audit emission,
  missing-file empty results, malformed entry fallback, /contexts
  missing-file empty, search-by-IP, huge since/until, combined filters.

Full suite: 86 suites / 1910 tests, all green.

GLM judge round 1 (372s, 50 tool calls): grade D — HIGH audit-log
shadowing + MEDIUM coverage gaps + LOW tofu glyph.
GLM judge round 2 (114s, 25 tool calls): grade A — all findings fixed,
no new regressions, ship recommendation: ship.
This commit is contained in:
DashCaddy Polish Loop committed 2026-08-17 20:53:13 -07:00
1 parent d79d19b769
commit 60852ee1ef
5 files changed
+1116 -319

No files matched your search

+277 -228
View File
@@ -90,44 +90,44 @@
<button id="logo-save" class="btn-accent">Save</button>
</div>
</div>
</div>`);const f=document.getElementById("logo-modal"),I=document.getElementById("logo-preview-dark"),A=document.getElementById("logo-preview-light"),E=document.getElementById("logo-status"),M=document.getElementById("logo-same-both"),P=document.getElementById("logo-dual-uploads"),z=document.getElementById("logo-single-upload"),D=document.getElementById("logo-upload-dark"),v=document.getElementById("logo-upload-light"),B=document.getElementById("logo-upload-single"),x=document.querySelector("#brand .brand-logo-dark"),$=document.querySelector("#brand .brand-logo-light"),k=document.querySelector(".top-row"),T=document.getElementById("dashboard-title"),S=DC.NAME;let L=null,j=null,C=null,N="left",R=S;M?.addEventListener("change",()=>{M.checked?(P.style.display="none",z.style.display="",L=null,j=null):(P.style.display="flex",z.style.display="none",C=null)});function U(t,e){if(!t||!t.type.startsWith("image/")){showNotification("Please select an image file","warning");return}const a=new FileReader;a.onload=o=>e(o.target.result),a.readAsDataURL(t)}D?.addEventListener("change",t=>{U(t.target.files[0],e=>{L=e,I.src=e,E.textContent="New dark logo ready to save"})}),v?.addEventListener("change",t=>{U(t.target.files[0],e=>{j=e,A.src=e,E.textContent="New light logo ready to save"})}),B?.addEventListener("change",t=>{U(t.target.files[0],e=>{C=e,I.src=e,A.src=e,E.textContent="New logo ready to save (both themes)"})});function u(t){k.setAttribute("data-logo-pos",t),document.querySelectorAll(".logo-pos-btn").forEach(e=>{e.style.background=e.dataset.pos===t?"var(--accent)":"var(--card-bg)",e.style.color=e.dataset.pos===t?"white":"var(--fg)"})}function m(t){R=t||S,document.title=R;const e=document.querySelector(".dashboard-title");e&&(e.textContent=R)}async function h(){try{const t=await fetch("/api/v1/logo");if(t.ok){const e=await t.json();e.customLogoDark&&(x.src=e.customLogoDark,I.src=e.customLogoDark),e.customLogoLight&&($.src=e.customLogoLight,A.src=e.customLogoLight),!e.customLogoDark&&!e.customLogoLight&&e.customLogo&&(x.src=e.customLogo,$.src=e.customLogo,I.src=e.customLogo,A.src=e.customLogo),e.isDefault||(E.textContent="Using custom logo"),e.position&&(N=e.position,u(e.position)),e.dashboardTitle&&m(e.dashboardTitle)}}catch(t){console.warn("Could not load custom logo:",t.message)}}document.querySelectorAll(".logo-pos-btn").forEach(t=>{t.addEventListener("click",()=>{N=t.dataset.pos,u(N)})}),document.getElementById("brand")?.addEventListener("click",()=>{L=null,j=null,C=null,D&&(D.value=""),v&&(v.value=""),B&&(B.value=""),M&&(M.checked=!1),P.style.display="flex",z.style.display="none",I.src=x.src,A.src=$.src;const t=x.src.includes("custom-logo")||$.src.includes("custom-logo");E.textContent=t?"Using custom logo":"Using default logos",u(N),T.value=R,f.classList.add("show")}),document.getElementById("logo-save")?.addEventListener("click",async()=>{try{const t=T.value.trim()||S,e={position:N,dashboardTitle:t};M?.checked&&C?(e.dataDark=C,e.dataLight=C):(L&&(e.dataDark=L),j&&(e.dataLight=j));const a=await secureFetch("/api/v1/logo",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(a.ok){const o=await a.json(),i="?t="+Date.now();o.pathDark&&(x.src=o.pathDark+i,I.src=o.pathDark+i),o.pathLight&&($.src=o.pathLight+i,A.src=o.pathLight+i),u(N),m(t),f.classList.remove("show")}else{const o=await a.json();showNotification("Failed to save: "+o.error,"error")}}catch(t){showNotification("Error saving: "+t.message,"error")}}),document.getElementById("logo-reset")?.addEventListener("click",async()=>{if(confirm(`Reset all branding to DashCaddy defaults?
</div>`);const x=document.getElementById("logo-modal"),B=document.getElementById("logo-preview-dark"),A=document.getElementById("logo-preview-light"),C=document.getElementById("logo-status"),M=document.getElementById("logo-same-both"),P=document.getElementById("logo-dual-uploads"),z=document.getElementById("logo-single-upload"),N=document.getElementById("logo-upload-dark"),f=document.getElementById("logo-upload-light"),L=document.getElementById("logo-upload-single"),w=document.querySelector("#brand .brand-logo-dark"),$=document.querySelector("#brand .brand-logo-light"),k=document.querySelector(".top-row"),T=document.getElementById("dashboard-title"),E=DC.NAME;let I=null,j=null,H=null,R="left",D=E;M?.addEventListener("change",()=>{M.checked?(P.style.display="none",z.style.display="",I=null,j=null):(P.style.display="flex",z.style.display="none",H=null)});function O(t,e){if(!t||!t.type.startsWith("image/")){showNotification("Please select an image file","warning");return}const a=new FileReader;a.onload=o=>e(o.target.result),a.readAsDataURL(t)}N?.addEventListener("change",t=>{O(t.target.files[0],e=>{I=e,B.src=e,C.textContent="New dark logo ready to save"})}),f?.addEventListener("change",t=>{O(t.target.files[0],e=>{j=e,A.src=e,C.textContent="New light logo ready to save"})}),L?.addEventListener("change",t=>{O(t.target.files[0],e=>{H=e,B.src=e,A.src=e,C.textContent="New logo ready to save (both themes)"})});function p(t){k.setAttribute("data-logo-pos",t),document.querySelectorAll(".logo-pos-btn").forEach(e=>{e.style.background=e.dataset.pos===t?"var(--accent)":"var(--card-bg)",e.style.color=e.dataset.pos===t?"white":"var(--fg)"})}function v(t){D=t||E,document.title=D;const e=document.querySelector(".dashboard-title");e&&(e.textContent=D)}async function b(){try{const t=await fetch("/api/v1/logo");if(t.ok){const e=await t.json();e.customLogoDark&&(w.src=e.customLogoDark,B.src=e.customLogoDark),e.customLogoLight&&($.src=e.customLogoLight,A.src=e.customLogoLight),!e.customLogoDark&&!e.customLogoLight&&e.customLogo&&(w.src=e.customLogo,$.src=e.customLogo,B.src=e.customLogo,A.src=e.customLogo),e.isDefault||(C.textContent="Using custom logo"),e.position&&(R=e.position,p(e.position)),e.dashboardTitle&&v(e.dashboardTitle)}}catch(t){console.warn("Could not load custom logo:",t.message)}}document.querySelectorAll(".logo-pos-btn").forEach(t=>{t.addEventListener("click",()=>{R=t.dataset.pos,p(R)})}),document.getElementById("brand")?.addEventListener("click",()=>{I=null,j=null,H=null,N&&(N.value=""),f&&(f.value=""),L&&(L.value=""),M&&(M.checked=!1),P.style.display="flex",z.style.display="none",B.src=w.src,A.src=$.src;const t=w.src.includes("custom-logo")||$.src.includes("custom-logo");C.textContent=t?"Using custom logo":"Using default logos",p(R),T.value=D,x.classList.add("show")}),document.getElementById("logo-save")?.addEventListener("click",async()=>{try{const t=T.value.trim()||E,e={position:R,dashboardTitle:t};M?.checked&&H?(e.dataDark=H,e.dataLight=H):(I&&(e.dataDark=I),j&&(e.dataLight=j));const a=await secureFetch("/api/v1/logo",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(a.ok){const o=await a.json(),r="?t="+Date.now();o.pathDark&&(w.src=o.pathDark+r,B.src=o.pathDark+r),o.pathLight&&($.src=o.pathLight+r,A.src=o.pathLight+r),p(R),v(t),x.classList.remove("show")}else{const o=await a.json();showNotification("Failed to save: "+o.error,"error")}}catch(t){showNotification("Error saving: "+t.message,"error")}}),document.getElementById("logo-reset")?.addEventListener("click",async()=>{if(confirm(`Reset all branding to DashCaddy defaults?
This will reset the logo, favicon, title, and position.`))try{if((await secureFetch("/api/v1/logo",{method:"DELETE"})).ok&&(x.src="/assets/dashcaddy-logo-dark.png",$.src="/assets/dashcaddy-logo-light.png",I.src="/assets/dashcaddy-logo-dark.png",A.src="/assets/dashcaddy-logo-light.png",E.textContent="Using default logos",L=null,j=null,C=null,T.value=S,m(S),N="left",u("left")),(await secureFetch("/api/v1/favicon",{method:"DELETE"})).ok){const a=document.querySelector('link[rel="icon"]'),o=document.getElementById("favicon-preview"),i=document.getElementById("favicon-status");a&&(a.href="/assets/dashcaddy-favicon.ico?t="+Date.now()),o&&(o.src="/assets/dashcaddy-favicon.ico?t="+Date.now()),i&&(i.textContent="Using DashCaddy favicon"),d=null}}catch(t){showNotification("Error resetting branding: "+t.message,"error")}}),wireModal(f,document.getElementById("logo-cancel"));const g=document.getElementById("favicon-preview"),H=document.getElementById("favicon-status"),r=document.getElementById("favicon-upload"),c=document.querySelector('link[rel="icon"]')||document.createElement("link");let d=null;document.querySelector('link[rel="icon"]')||(c.rel="icon",c.href="/assets/dashcaddy-favicon.ico",document.head.appendChild(c));async function b(){try{const t=await fetch("/api/v1/favicon");if(t.ok){const e=await t.json();e.customFavicon&&(c.href=e.customFavicon+"?t="+Date.now(),g.src=e.customFavicon+"?t="+Date.now(),H.textContent="Using custom favicon")}}catch(t){console.warn("Could not load custom favicon:",t.message)}}r?.addEventListener("change",t=>{const e=t.target.files[0];if(!e)return;if(!e.type.match(/^image\/(png|svg\+xml)$/)){showNotification("Please select a PNG or SVG file","warning"),r.value="";return}const a=new FileReader;a.onload=o=>{d=o.target.result,g.src=d,H.textContent="New favicon ready to save"},a.readAsDataURL(e)}),document.getElementById("logo-save")?.addEventListener("click",async()=>{if(d)try{const t=await secureFetch("/api/v1/favicon",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({data:d})});if(t.ok){const e=await t.json();c.href=e.path+"?t="+Date.now(),g.src=e.path+"?t="+Date.now(),H.textContent="Using custom favicon",d=null}else{const e=await t.json();showNotification("Failed to save favicon: "+e.error,"error")}}catch(t){showNotification("Error saving favicon: "+t.message,"error")}}),b(),h();const y=document.getElementById("settings-timezone");y&&(new MutationObserver(()=>{f.classList.contains("show")&&y.options.length===0&&(async()=>{let e;try{const a=await fetch("/api/v1/config");a.ok&&(e=(await a.json()).timezone)}catch{}window.populateTimezoneSelect(y,e)})()}).observe(f,{attributes:!0,attributeFilter:["class"]}),document.getElementById("logo-save")?.addEventListener("click",async()=>{const e=y.value;if(e)try{const a=await fetch("/api/v1/config");if(!a.ok)return;const o=await a.json();o.timezone=e,o.updatedAt=new Date().toISOString(),await secureFetch("/api/v1/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)})}catch(a){console.warn("Failed to save timezone:",a.message)}}))})(),window.populateTimezoneSelect=function(f,I){const A=Intl.supportedValuesOf("timeZone"),E=I||Intl.DateTimeFormat().resolvedOptions().timeZone||"UTC";f.innerHTML="";for(const M of A){const P=document.createElement("option");P.value=M,P.textContent=M.replace(/_/g," "),M===E&&(P.selected=!0),f.appendChild(P)}},(function(){let f="homelab",I=null;async function A(){try{const m=await fetch("/api/v1/config");if(m.ok&&(I=await m.json(),I&&I.setupComplete))return document.getElementById("setup-wizard").style.display="none",!0}catch(m){console.warn("Could not fetch server config, checking localStorage fallback:",m.message)}return safeGet("dashcaddy-setup")?(document.getElementById("setup-wizard").style.display="none",!0):(document.getElementById("setup-wizard").style.display="flex",!1)}A();const E=document.getElementById("setup-timezone");E&&window.populateTimezoneSelect(E);function M(u){document.querySelectorAll(".setup-step").forEach(h=>{h.style.display="none"});const m=document.getElementById(u);m&&(m.style.display="block")}function P(){const u=document.getElementById("setup-summary-content");if(!u)return;let m='<div style="display: grid; gap: 20px;">';if(f==="homelab"){const g=document.getElementById("setup-tld")?.value?.trim()||".home",H=document.getElementById("setup-ca-name")?.value?.trim()||"",r=document.getElementById("setup-dns-ip")?.value?.trim()||"",c=document.getElementById("setup-dns-port")?.value?.trim()||DC.DEFAULTS.DNS_PORT;m+=`
This will reset the logo, favicon, title, and position.`))try{if((await secureFetch("/api/v1/logo",{method:"DELETE"})).ok&&(w.src="/assets/dashcaddy-logo-dark.png",$.src="/assets/dashcaddy-logo-light.png",B.src="/assets/dashcaddy-logo-dark.png",A.src="/assets/dashcaddy-logo-light.png",C.textContent="Using default logos",I=null,j=null,H=null,T.value=E,v(E),R="left",p("left")),(await secureFetch("/api/v1/favicon",{method:"DELETE"})).ok){const a=document.querySelector('link[rel="icon"]'),o=document.getElementById("favicon-preview"),r=document.getElementById("favicon-status");a&&(a.href="/assets/dashcaddy-favicon.ico?t="+Date.now()),o&&(o.src="/assets/dashcaddy-favicon.ico?t="+Date.now()),r&&(r.textContent="Using DashCaddy favicon"),l=null}}catch(t){showNotification("Error resetting branding: "+t.message,"error")}}),wireModal(x,document.getElementById("logo-cancel"));const y=document.getElementById("favicon-preview"),h=document.getElementById("favicon-status"),s=document.getElementById("favicon-upload"),c=document.querySelector('link[rel="icon"]')||document.createElement("link");let l=null;document.querySelector('link[rel="icon"]')||(c.rel="icon",c.href="/assets/dashcaddy-favicon.ico",document.head.appendChild(c));async function m(){try{const t=await fetch("/api/v1/favicon");if(t.ok){const e=await t.json();e.customFavicon&&(c.href=e.customFavicon+"?t="+Date.now(),y.src=e.customFavicon+"?t="+Date.now(),h.textContent="Using custom favicon")}}catch(t){console.warn("Could not load custom favicon:",t.message)}}s?.addEventListener("change",t=>{const e=t.target.files[0];if(!e)return;if(!e.type.match(/^image\/(png|svg\+xml)$/)){showNotification("Please select a PNG or SVG file","warning"),s.value="";return}const a=new FileReader;a.onload=o=>{l=o.target.result,y.src=l,h.textContent="New favicon ready to save"},a.readAsDataURL(e)}),document.getElementById("logo-save")?.addEventListener("click",async()=>{if(l)try{const t=await secureFetch("/api/v1/favicon",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({data:l})});if(t.ok){const e=await t.json();c.href=e.path+"?t="+Date.now(),y.src=e.path+"?t="+Date.now(),h.textContent="Using custom favicon",l=null}else{const e=await t.json();showNotification("Failed to save favicon: "+e.error,"error")}}catch(t){showNotification("Error saving favicon: "+t.message,"error")}}),m(),b();const u=document.getElementById("settings-timezone");u&&(new MutationObserver(()=>{x.classList.contains("show")&&u.options.length===0&&(async()=>{let e;try{const a=await fetch("/api/v1/config");a.ok&&(e=(await a.json()).timezone)}catch{}window.populateTimezoneSelect(u,e)})()}).observe(x,{attributes:!0,attributeFilter:["class"]}),document.getElementById("logo-save")?.addEventListener("click",async()=>{const e=u.value;if(e)try{const a=await fetch("/api/v1/config");if(!a.ok)return;const o=await a.json();o.timezone=e,o.updatedAt=new Date().toISOString(),await secureFetch("/api/v1/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)})}catch(a){console.warn("Failed to save timezone:",a.message)}}))})(),window.populateTimezoneSelect=function(x,B){const A=Intl.supportedValuesOf("timeZone"),C=B||Intl.DateTimeFormat().resolvedOptions().timeZone||"UTC";x.innerHTML="";for(const M of A){const P=document.createElement("option");P.value=M,P.textContent=M.replace(/_/g," "),M===C&&(P.selected=!0),x.appendChild(P)}},(function(){let x="homelab",B=null;async function A(){try{const v=await fetch("/api/v1/config");if(v.ok&&(B=await v.json(),B&&B.setupComplete))return document.getElementById("setup-wizard").style.display="none",!0}catch(v){console.warn("Could not fetch server config, checking localStorage fallback:",v.message)}return safeGet("dashcaddy-setup")?(document.getElementById("setup-wizard").style.display="none",!0):(document.getElementById("setup-wizard").style.display="flex",!1)}A();const C=document.getElementById("setup-timezone");C&&window.populateTimezoneSelect(C);function M(p){document.querySelectorAll(".setup-step").forEach(b=>{b.style.display="none"});const v=document.getElementById(p);v&&(v.style.display="block")}function P(){const p=document.getElementById("setup-summary-content");if(!p)return;let v='<div style="display: grid; gap: 20px;">';if(x==="homelab"){const y=document.getElementById("setup-tld")?.value?.trim()||".home",h=document.getElementById("setup-ca-name")?.value?.trim()||"",s=document.getElementById("setup-dns-ip")?.value?.trim()||"",c=document.getElementById("setup-dns-port")?.value?.trim()||DC.DEFAULTS.DNS_PORT;v+=`
<div>
<h3 style="margin: 0 0 12px; color: var(--accent);">Home Lab Configuration</h3>
<div style="display: grid; gap: 12px; font-size: 0.95rem;">
<div><strong>TLD:</strong> ${g}</div>
<div><strong>Certificate Authority:</strong> ${H}</div>
<div><strong>DNS Server:</strong> ${r}:${c}</div>
<div><strong>Example URLs:</strong> https://uptime${g}, https://nextcloud${g}</div>
<div><strong>TLD:</strong> ${y}</div>
<div><strong>Certificate Authority:</strong> ${h}</div>
<div><strong>DNS Server:</strong> ${s}:${c}</div>
<div><strong>Example URLs:</strong> https://uptime${y}, https://nextcloud${y}</div>
</div>
</div>
`}else if(f==="simple"){const g=document.getElementById("setup-simple-ip")?.value?.trim()||"localhost";m+=`
`}else if(x==="simple"){const y=document.getElementById("setup-simple-ip")?.value?.trim()||"localhost";v+=`
<div>
<h3 style="margin: 0 0 12px; color: var(--accent);">Simple Setup</h3>
<div style="display: grid; gap: 12px; font-size: 0.95rem;">
<div><strong>Access Method:</strong> IP:Port only</div>
<div><strong>Default IP:</strong> ${g}</div>
<div><strong>Default IP:</strong> ${y}</div>
<div><strong>SSL:</strong> None (HTTP only)</div>
<div><strong>Example URLs:</strong> http://${g}:8080, http://${g}:3000</div>
<div><strong>Example URLs:</strong> http://${y}:8080, http://${y}:3000</div>
</div>
</div>
`}else if(f==="public"){const g=document.getElementById("setup-public-domain")?.value?.trim()||"",H=document.getElementById("setup-public-email")?.value?.trim()||"",r=document.querySelector('input[name="routing-mode"]:checked')?.value||"subdirectory",c=r==="subdirectory"?`https://${g}/sonarr, https://${g}/grafana`:`https://sonarr.${g}, https://grafana.${g}`;m+=`
`}else if(x==="public"){const y=document.getElementById("setup-public-domain")?.value?.trim()||"",h=document.getElementById("setup-public-email")?.value?.trim()||"",s=document.querySelector('input[name="routing-mode"]:checked')?.value||"subdirectory",c=s==="subdirectory"?`https://${y}/sonarr, https://${y}/grafana`:`https://sonarr.${y}, https://grafana.${y}`;v+=`
<div>
<h3 style="margin: 0 0 12px; color: var(--accent);">Public Server</h3>
<div style="display: grid; gap: 12px; font-size: 0.95rem;">
<div><strong>Domain:</strong> ${g}</div>
<div><strong>Domain:</strong> ${y}</div>
<div><strong>SSL:</strong> Let's Encrypt</div>
<div><strong>Email:</strong> ${H}</div>
<div><strong>Routing:</strong> ${r==="subdirectory"?"Subdirectory (domain.com/app)":"Subdomain (app.domain.com)"}</div>
<div><strong>Email:</strong> ${h}</div>
<div><strong>Routing:</strong> ${s==="subdirectory"?"Subdirectory (domain.com/app)":"Subdomain (app.domain.com)"}</div>
<div><strong>Example URLs:</strong> ${c}</div>
</div>
</div>
`}const h=document.getElementById("setup-timezone")?.value||Intl.DateTimeFormat().resolvedOptions().timeZone||"UTC";m+=`
`}const b=document.getElementById("setup-timezone")?.value||Intl.DateTimeFormat().resolvedOptions().timeZone||"UTC";v+=`
<div style="margin-top: 8px; padding-top: 12px; border-top: 1px solid var(--border);">
<div style="font-size: 0.95rem;"><strong>Timezone:</strong> ${h.replace(/_/g," ")}</div>
<div style="font-size: 0.95rem;"><strong>Timezone:</strong> ${b.replace(/_/g," ")}</div>
</div>
`,m+="</div>",u.innerHTML=m,M("setup-step-summary")}async function z(u){try{const m=await secureFetch("/api/v1/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(u)});return m.ok?(await m.json(),!0):(errorHandler.logError("[SetupWizard] Save Config",new Error(`Server returned ${m.status}`),{function:"saveConfigToServer"}),!1)}catch(m){return errorHandler.logError("[SetupWizard] Save Config",m,{function:"saveConfigToServer"}),!1}}async function D(){const u={setupComplete:!0,configurationType:f,timestamp:new Date().toISOString(),timezone:document.getElementById("setup-timezone")?.value||Intl.DateTimeFormat().resolvedOptions().timeZone||"UTC"};if(f==="homelab"){u.tld=document.getElementById("setup-tld")?.value?.trim()||".home",u.caName=document.getElementById("setup-ca-name")?.value?.trim()||"";const H=document.getElementById("setup-dns-provider")?.value||"technitium";u.dns={provider:H,ip:document.getElementById("setup-dns-ip")?.value?.trim()||"",port:document.getElementById("setup-dns-port")?.value?.trim()||DC.DEFAULTS.DNS_PORT,token:document.getElementById("setup-dns-token")?.value?.trim()||""},u.defaults={dnsType:"private",sslType:"internal",targetIP:"localhost"}}else f==="simple"?(u.defaultIP=document.getElementById("setup-simple-ip")?.value?.trim()||"localhost",u.defaults={dnsType:"none",sslType:"none",targetIP:u.defaultIP}):f==="public"&&(u.domain=document.getElementById("setup-public-domain")?.value?.trim()||"",u.email=document.getElementById("setup-public-email")?.value?.trim()||"",u.routingMode=document.querySelector('input[name="routing-mode"]:checked')?.value||"subdirectory",u.defaults={dnsType:u.routingMode==="subdirectory"?"none":"public",sslType:"letsencrypt",targetIP:"localhost"});const m=await z(u);safeSet("dashcaddy-config",JSON.stringify(u)),safeSet("dashcaddy-setup","completed"),document.getElementById("setup-wizard").style.display="none";const h=f==="homelab"?"Professional Home Lab":f==="simple"?"Simple Setup":"Public Server",g=m?"server (shared across all devices)":"locally (this browser only)";showNotification(`Setup Complete! Configured for: ${h}. Settings saved to: ${g}`,"success",5e3),setTimeout(()=>location.reload(),500)}const v=document.getElementById("setup-step-1-next");v&&(v.onclick=function(u){u.preventDefault();const m=document.querySelector('input[name="config-type"]:checked');m&&(f=m.value),M(f==="homelab"?"setup-step-homelab":f==="simple"?"setup-step-simple":f==="public"?"setup-step-public":"setup-step-homelab")});const B=document.getElementById("setup-skip");B&&(B.onclick=async function(u){u.preventDefault(),confirm("Skip setup? You can run it later from Settings.")&&(await z({setupComplete:!0,skipped:!0,timestamp:new Date().toISOString()}),safeSet("dashcaddy-setup","skipped"),document.getElementById("setup-wizard").style.display="none")});const x=document.getElementById("setup-tld");x&&(x.oninput=function(u){const m=u.target.value||".home",h=document.getElementById("tld-preview"),g=document.getElementById("tld-preview-2");h&&(h.textContent=m),g&&(g.textContent=m)});const $=document.getElementById("setup-homelab-back");$&&($.onclick=function(u){u.preventDefault(),M("setup-step-1")});const k=document.getElementById("setup-homelab-next");k&&(k.onclick=function(u){u.preventDefault();const m=document.getElementById("setup-tld")?.value?.trim()||"",h=document.getElementById("setup-ca-name")?.value?.trim()||"",g=document.getElementById("setup-dns-ip")?.value?.trim()||"";if(!m||!m.startsWith(".")){showNotification("Please enter a valid TLD starting with a dot (e.g., .home)","warning");return}if(!h){showNotification("Please enter a Certificate Authority name","warning");return}if(!g){showNotification("Please enter your DNS server IP address","warning");return}P()});const T=document.getElementById("setup-simple-back");T&&(T.onclick=function(u){u.preventDefault(),M("setup-step-1")});const S=document.getElementById("setup-simple-next");S&&(S.onclick=function(u){u.preventDefault(),P()}),document.querySelectorAll('input[name="routing-mode"]').forEach(function(u){u.onchange=function(){var m=document.getElementById("dns-requirement-note");m&&(m.textContent=this.value==="subdirectory"?"Only one DNS record needed (for the main domain)":"You'll need to configure DNS manually for each subdomain")}});const L=document.getElementById("setup-public-back");L&&(L.onclick=function(u){u.preventDefault(),M("setup-step-1")});const j=document.getElementById("setup-public-next");j&&(j.onclick=function(u){u.preventDefault();const m=document.getElementById("setup-public-domain")?.value?.trim()||"",h=document.getElementById("setup-public-email")?.value?.trim()||"";if(!m){showNotification("Please enter your domain name","warning");return}if(!h||!h.includes("@")){showNotification("Please enter a valid email address","warning");return}P()});const C=document.getElementById("setup-summary-back");C&&(C.onclick=function(u){u.preventDefault(),f==="homelab"?M("setup-step-homela Line truncated
`,v+="</div>",p.innerHTML=v,M("setup-step-summary")}async function z(p){try{const v=await secureFetch("/api/v1/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(p)});return v.ok?(await v.json(),!0):(errorHandler.logError("[SetupWizard] Save Config",new Error(`Server returned ${v.status}`),{function:"saveConfigToServer"}),!1)}catch(v){return errorHandler.logError("[SetupWizard] Save Config",v,{function:"saveConfigToServer"}),!1}}async function N(){const p={setupComplete:!0,configurationType:x,timestamp:new Date().toISOString(),timezone:document.getElementById("setup-timezone")?.value||Intl.DateTimeFormat().resolvedOptions().timeZone||"UTC"};if(x==="homelab"){p.tld=document.getElementById("setup-tld")?.value?.trim()||".home",p.caName=document.getElementById("setup-ca-name")?.value?.trim()||"";const h=document.getElementById("setup-dns-provider")?.value||"technitium";p.dns={provider:h,ip:document.getElementById("setup-dns-ip")?.value?.trim()||"",port:document.getElementById("setup-dns-port")?.value?.trim()||DC.DEFAULTS.DNS_PORT,token:document.getElementById("setup-dns-token")?.value?.trim()||""},p.defaults={dnsType:"private",sslType:"internal",targetIP:"localhost"}}else x==="simple"?(p.defaultIP=document.getElementById("setup-simple-ip")?.value?.trim()||"localhost",p.defaults={dnsType:"none",sslType:"none",targetIP:p.defaultIP}):x==="public"&&(p.domain=document.getElementById("setup-public-domain")?.value?.trim()||"",p.email=document.getElementById("setup-public-email")?.value?.trim()||"",p.routingMode=document.querySelector('input[name="routing-mode"]:checked')?.value||"subdirectory",p.defaults={dnsType:p.routingMode==="subdirectory"?"none":"public",sslType:"letsencrypt",targetIP:"localhost"});const v=await z(p);safeSet("dashcaddy-config",JSON.stringify(p)),safeSet("dashcaddy-setup","completed"),document.getElementById("setup-wizard").style.display="none";const b=x==="homelab"?"Professional Home Lab":x==="simple"?"Simple Setup":"Public Server",y=v?"server (shared across all devices)":"locally (this browser only)";showNotification(`Setup Complete! Configured for: ${b}. Settings saved to: ${y}`,"success",5e3),setTimeout(()=>location.reload(),500)}const f=document.getElementById("setup-step-1-next");f&&(f.onclick=function(p){p.preventDefault();const v=document.querySelector('input[name="config-type"]:checked');v&&(x=v.value),M(x==="homelab"?"setup-step-homelab":x==="simple"?"setup-step-simple":x==="public"?"setup-step-public":"setup-step-homelab")});const L=document.getElementById("setup-skip");L&&(L.onclick=async function(p){p.preventDefault(),confirm("Skip setup? You can run it later from Settings.")&&(await z({setupComplete:!0,skipped:!0,timestamp:new Date().toISOString()}),safeSet("dashcaddy-setup","skipped"),document.getElementById("setup-wizard").style.display="none")});const w=document.getElementById("setup-tld");w&&(w.oninput=function(p){const v=p.target.value||".home",b=document.getElementById("tld-preview"),y=document.getElementById("tld-preview-2");b&&(b.textContent=v),y&&(y.textContent=v)});const $=document.getElementById("setup-homelab-back");$&&($.onclick=function(p){p.preventDefault(),M("setup-step-1")});const k=document.getElementById("setup-homelab-next");k&&(k.onclick=function(p){p.preventDefault();const v=document.getElementById("setup-tld")?.value?.trim()||"",b=document.getElementById("setup-ca-name")?.value?.trim()||"",y=document.getElementById("setup-dns-ip")?.value?.trim()||"";if(!v||!v.startsWith(".")){showNotification("Please enter a valid TLD starting with a dot (e.g., .home)","warning");return}if(!b){showNotification("Please enter a Certificate Authority name","warning");return}if(!y){showNotification("Please enter your DNS server IP address","warning");return}P()});const T=document.getElementById("setup-simple-back");T&&(T.onclick=function(p){p.preventDefault(),M("setup-step-1")});const E=document.getElementById("setup-simple-next");E&&(E.onclick=function(p){p.preventDefault(),P()}),document.querySelectorAll('input[name="routing-mode"]').forEach(function(p){p.onchange=function(){var v=document.getElementById("dns-requirement-note");v&&(v.textContent=this.value==="subdirectory"?"Only one DNS record needed (for the main domain)":"You'll need to configure DNS manually for each subdomain")}});const I=document.getElementById("setup-public-back");I&&(I.onclick=function(p){p.preventDefault(),M("setup-step-1")});const j=document.getElementById("setup-public-next");j&&(j.onclick=function(p){p.preventDefault();const v=document.getElementById("setup-public-domain")?.value?.trim()||"",b=document.getElementById("setup-public-email")?.value?.trim()||"";if(!v){showNotification("Please enter your domain name","warning");return}if(!b||!b.includes("@")){showNotification("Please enter a valid email address","warning");return}P()});const H=document.getElementById("setup-summary-back");H&&(H.onclick=function(p){p.preventDefault(),x==="homelab"?M("setup-step-homela Line truncated
<div class="app-selector-content">
<h2 style="margin: 0 0 24px; color: var(--fg); text-align: center;">Choose an App</h2>
<div id="app-selector-grid" class="app-selector-grid"></div>
@@ -333,12 +333,12 @@ This will reset the logo, favicon, title, and position.`))try{if((await secureFe
</button>
</div>
</div>
</div>`);const I="custom-apps";let A=null,E=null;const M=document.getElementById("app-selector-modal"),P=document.getElementById("app-selector-grid");async function z(){try{const c=await(await fetch("/api/v1/apps/templates")).json();if(c.success)return A=c.templates,E=c.categories,!0}catch(r){f.logError("[AppSelector] Fetch Templates",r,{function:"fetchApiTemplates"})}return!1}async function D(r){try{return await(await fetch(`/api/v1/apps/ports/${r}/check`)).json()}catch(c){return f.logError("[AppSelector] Check Port",c,{function:"checkPortAvailability"}),{available:!0}}}async function v(r){try{const d=await(await fetch(`/api/v1/apps/ports/${r}/suggest`)).json();if(d.success)return d.suggestedPort}catch(c){f.logError("[AppSelector] Get Suggested Port",c,{function:"getSuggestedPort"})}return r}async function B(){if(P.innerHTML='<div style="text-align: center; padding: 40px; color: var(--muted);">Loading app templates...</div>',!A&&!await z()){P.innerHTML='<div style="text-align: center; padding: 40px; color: var(--error);">Failed to load app templates. Please try again.</div>';return}P.innerHTML="";const r={};for(const[d,b]of Object.entries(A)){const y=b.category||"Other";r[y]||(r[y]=[]),r[y].push({id:d,...b})}const c=E?Object.keys(E):Object.keys(r).sort();for(const d of c){const b=r[d];if(!b||b.length===0)continue;b.sort((e,a)=>(a.popularity||0)-(e.popularity||0));const y=document.createElement("div");y.className="app-category-header";const t=E?.[d]||{};y.innerHTML=`${escapeHtml(t.icon||"")} ${escapeHtml(d)}`,t.color&&(y.style.borderBottomColor=t.color),P.appendChild(y),b.forEach(e=>{const a=document.createElement("div");a.className="app-option";const o=e.isDashboardWidget,i=o&&safeGet("widget-"+e.id+"-enabled")!=="false",n=o?`<div style="font-size: 0.65rem; padding: 2px 6px; border-radius: 4px; margin-top: 4px; background: ${i?"#2ecc7130":"#e74c3c30"}; color: ${i?"#2ecc71":"#e74c3c"}; font-weight: 600;">${i?"ON":"OFF"}</div>`:"",s=!o&&e.difficulty?`<div style="font-size: 0.65rem; padding: 2px 6px; border-radius: 4px; margin-top: 4px; background: ${e.difficulty==="Easy"?"#2ecc71":e.difficulty==="Intermediate"?"#f39c12":"#e74c3c"}20; color: ${e.difficulty==="Easy"?"#2ecc71":e.difficulty==="Intermediate"?"#f39c12":"#e74c3c"};">${escapeHtml(e.difficulty)}</div>`:"";a.innerHTML=`
</div>`);const B="custom-apps";let A=null,C=null;const M=document.getElementById("app-selector-modal"),P=document.getElementById("app-selector-grid");async function z(){try{const c=await(await fetch("/api/v1/apps/templates")).json();if(c.success)return A=c.templates,C=c.categories,!0}catch(s){x.logError("[AppSelector] Fetch Templates",s,{function:"fetchApiTemplates"})}return!1}async function N(s){try{return await(await fetch(`/api/v1/apps/ports/${s}/check`)).json()}catch(c){return x.logError("[AppSelector] Check Port",c,{function:"checkPortAvailability"}),{available:!0}}}async function f(s){try{const l=await(await fetch(`/api/v1/apps/ports/${s}/suggest`)).json();if(l.success)return l.suggestedPort}catch(c){x.logError("[AppSelector] Get Suggested Port",c,{function:"getSuggestedPort"})}return s}async function L(){if(P.innerHTML='<div style="text-align: center; padding: 40px; color: var(--muted);">Loading app templates...</div>',!A&&!await z()){P.innerHTML='<div style="text-align: center; padding: 40px; color: var(--error);">Failed to load app templates. Please try again.</div>';return}P.innerHTML="";const s={};for(const[l,m]of Object.entries(A)){const u=m.category||"Other";s[u]||(s[u]=[]),s[u].push({id:l,...m})}const c=C?Object.keys(C):Object.keys(s).sort();for(const l of c){const m=s[l];if(!m||m.length===0)continue;m.sort((e,a)=>(a.popularity||0)-(e.popularity||0));const u=document.createElement("div");u.className="app-category-header";const t=C?.[l]||{};u.innerHTML=`${escapeHtml(t.icon||"")} ${escapeHtml(l)}`,t.color&&(u.style.borderBottomColor=t.color),P.appendChild(u),m.forEach(e=>{const a=document.createElement("div");a.className="app-option";const o=e.isDashboardWidget,r=o&&safeGet("widget-"+e.id+"-enabled")!=="false",n=o?`<div style="font-size: 0.65rem; padding: 2px 6px; border-radius: 4px; margin-top: 4px; background: ${r?"#2ecc7130":"#e74c3c30"}; color: ${r?"#2ecc71":"#e74c3c"}; font-weight: 600;">${r?"ON":"OFF"}</div>`:"",i=!o&&e.difficulty?`<div style="font-size: 0.65rem; padding: 2px 6px; border-radius: 4px; margin-top: 4px; background: ${e.difficulty==="Easy"?"#2ecc71":e.difficulty==="Intermediate"?"#f39c12":"#e74c3c"}20; color: ${e.difficulty==="Easy"?"#2ecc71":e.difficulty==="Intermediate"?"#f39c12":"#e74c3c"};">${escapeHtml(e.difficulty)}</div>`:"";a.innerHTML=`
<div class="app-option-icon">${escapeHtml(e.icon||"\u{1F4E6}")}</div>
<div class="app-option-name">${escapeHtml(e.name)}</div>
<div class="app-option-desc">${escapeHtml(e.description||"")}</div>
${n}${s}
`,o?a.onclick=()=>x(e,a):a.onclick=()=>$(e),P.appendChild(a)})}window.renderRecipeCards&&await window.renderRecipeCards(P)}function x(r,c){const d="widget-"+r.id+"-enabled",y=!(safeGet(d)!=="false");safeSet(d,String(y));const t=r.widgetSelector;if(t){const a=document.querySelector(t);a&&(a.style.display=y?"":"none")}const e=c.querySelector('div[style*="border-radius: 4px"]');e&&(e.textContent=y?"ON":"OFF",e.style.background=y?"#2ecc7130":"#e74c3c30",e.style.color=y?"#2ecc71":"#e74c3c"),showNotification(`${r.name} widget ${y?"enabled":"disabled"}`,"success",2e3)}async function $(r){const c=document.getElementById("app-deploy-modal"),d=document.getElementById("app-deploy-title"),b=document.getElementById("deploy-subdomain"),y=document.getElementById("deploy-url-preview"),t=document.getElementById("deploy-ip"),e=document.getElementById("deploy-port"),a=document.getElementById("deploy-tailscale-only"),o=document.getElementById("tailscale-status");try{const G=await(await secureFetch("/api/v1/apps/check-existing",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({appId:r.id})})).json();if(G.success&&G.exists){const V=G.container;confirm(`Found existing ${r.name} container:
${n}${i}
`,o?a.onclick=()=>w(e,a):a.onclick=()=>$(e),P.appendChild(a)})}window.renderRecipeCards&&await window.renderRecipeCards(P)}function w(s,c){const l="widget-"+s.id+"-enabled",u=!(safeGet(l)!=="false");safeSet(l,String(u));const t=s.widgetSelector;if(t){const a=document.querySelector(t);a&&(a.style.display=u?"":"none")}const e=c.querySelector('div[style*="border-radius: 4px"]');e&&(e.textContent=u?"ON":"OFF",e.style.background=u?"#2ecc7130":"#e74c3c30",e.style.color=u?"#2ecc71":"#e74c3c"),showNotification(`${s.name} widget ${u?"enabled":"disabled"}`,"success",2e3)}async function $(s){const c=document.getElementById("app-deploy-modal"),l=document.getElementById("app-deploy-title"),m=document.getElementById("deploy-subdomain"),u=document.getElementById("deploy-url-preview"),t=document.getElementById("deploy-ip"),e=document.getElementById("deploy-port"),a=document.getElementById("deploy-tailscale-only"),o=document.getElementById("tailscale-status");try{const G=await(await secureFetch("/api/v1/apps/check-existing",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({appId:s.id})})).json();if(G.success&&G.exists){const V=G.container;confirm(`Found existing ${s.name} container:
Container: ${V.name}
Status: ${V.status}
@@ -347,38 +347,38 @@ Port: ${V.primaryPort||"N/A"}
Would you like to use this existing container?
Click OK to configure DNS/Caddy for the existing container.
Click Cancel to deploy a new container.`)&&(r._useExisting=!0,r._existingContainer=V)}}catch{}d.textContent=`Deploy ${r.name}`;const i=r.subdomain||r.id.replace(/-/g,"");b.value=i;const n=document.getElementById("subpath-compat-warning");if(n)if(SITE.routingMode==="subdirectory"){const W=r.subpathSupport||"strip";W==="none"?(n.style.display="block",n.innerHTML='<span style="color: #ff9800;">&#9888; <strong>'+r.name+"</strong> does not support subdirectory mode. It may not work correctly at a subpath.</span>"):W==="strip"?(n.style.display="block",n.innerHTML='<span style="color: var(--muted);">&#9432; '+r.name+" has unverified subdirectory support. It may require additional configuration.</span>"):n.style.display="none"}else n.style.display="none";const s=SITE.defaults.dnsType||(SITE.configurationType==="public"?"public":"private"),l=SITE.defaults.sslType||(SITE.configurationType==="public"?"letsencrypt":"internal"),p=document.querySelector(`input[name="dns-type"][value="${s}"]`),w=document.querySelector(`input[name="ssl-type"][value="${l}"]`);p?p.checked=!0:document.querySelector('input[name="dns-type"][value="private"]').checked=!0,w?w.checked=!0:document.querySelector('input[name="ssl-type"][value="internal"]').checked=!0,t.value=SITE.defaults.targetIP||"localhost",a.checked=!1;const O=document.querySelector("#app-deploy-modal .flex-col-gap")?.closest("div"),_=document.querySelector("#app-deploy-modal details"),F=_?.querySelector("div");if(_&&F&&(SITE.configurationType==="public"||SITE.configurationType==="homelab")){const W=document.querySelectorAll('#app-deploy-modal input[name="dns-type"]')[0]?.closest("div.flex-col-gap")?.parentElement,G=document.querySelectorAll('#app-deploy-modal input[name="ssl-type"]')[0]?.closest("div.flex-col-gap")?.parentElement;W&&!W.dataset.moved&&(F.appendChild(W),W.dataset.moved="1"),G&&!G.dataset.moved&&(F.appendChild(G),G.dataset.moved="1")}const q=document.getElementById("media-path-section"),J=document.getElementById("deploy-media-path"),X=document.getElementById("media-path-description");if(r.mediaMount){q.style.display="block",J.value="",J.placeholder="/media/Movies, /media/TVShows or click Browse";const W=document.getElementById("detected-mounts-container"),G=document.getElementById("detected-mounts-list");try{const K=await(await fetch("/api/v1/media/detected-mounts")).json();if(K.success&&K.mounts.length>0){W.style.display="block",G.innerHTML="";const te=[...new Set(K.mounts.map(ee=>ee.hostPath))];J.value=te.join(", "),K.mounts.forEach(ee=>{const Z=document.createElement("button");Z.type="button";const de=te.includes(ee.hostPath);Z.style.cssText=`padding: 8px 14px; font-size: 0.85rem; background: color-mix(in srgb, var(--success) ${de?"40%":"15%"}, var(--card-bg)); border: 1px solid var(--success); border-radius: 6px; cursor: pointer; color: var(--fg);`,Z.innerHTML=`<span style="font-weight: 500;">${escapeHtml(ee.folderName)}</span><br><span style="font-size: 0.7rem; color: var(--muted);">from ${escapeHtml(ee.sourceImage)}</span>`,Z.title=`${ee.hostPath} (from ${ee.sourceContainer})`,Z.onclick=()=>{const le=J.value.split(",").map(ce=>ce.trim()).filter(ce=>ce),pe=le.indexOf(ee.hostPath);pe>=0?(le.splice(pe,1),Z.style.background="color-mix(in srgb, var(--success) 15%, var(--card-bg))"):(le.push(ee.hostPath),Z.style.background="color-mix(in srgb, var(--success) 40%, var(--card-bg))"),J.value=le.join(", ")},G.appendChild(Z)})}else W.style.display="none"}catch{W.style.display="none"}document.getElementById("browse-media-btn").onclick=()=>{openFolderBrowser(J)}}else q.style.display="none",J.value="",document.getElementById("detected-mounts-container").style.display="none";const Q=document.getElementById("plex-claim-section");Q&&(r.id==="plex"||r.claimToken?(Q.style.display="block",document.getElementById("deploy-plex-claim").value=""):Q.style.display="none");const ne=document.getElementById("volume-mounts-section"),oe=document.getElementById("volume-mounts-list");if(oe.innerHTML="",r.docker?.volumes?.length){const W=r.mediaMount?.containerPath,G=r.docker.volumes.filter(V=>!V.includes("{{MEDIA_PATH}}")&&!(W&&V.endsWith(":"+W)));G.length>0?(ne.style.display="block",G.forEach((V,K)=>{const[te,ee]=V.split(":"),Z=document.createElement("div");Z.style.cssText="display: flex; gap: 6px; align-items: center;",Z.innerHTML=`
Click Cancel to deploy a new container.`)&&(s._useExisting=!0,s._existingContainer=V)}}catch{}l.textContent=`Deploy ${s.name}`;const r=s.subdomain||s.id.replace(/-/g,"");m.value=r;const n=document.getElementById("subpath-compat-warning");if(n)if(SITE.routingMode==="subdirectory"){const W=s.subpathSupport||"strip";W==="none"?(n.style.display="block",n.innerHTML='<span style="color: #ff9800;">&#9888; <strong>'+s.name+"</strong> does not support subdirectory mode. It may not work correctly at a subpath.</span>"):W==="strip"?(n.style.display="block",n.innerHTML='<span style="color: var(--muted);">&#9432; '+s.name+" has unverified subdirectory support. It may require additional configuration.</span>"):n.style.display="none"}else n.style.display="none";const i=SITE.defaults.dnsType||(SITE.configurationType==="public"?"public":"private"),d=SITE.defaults.sslType||(SITE.configurationType==="public"?"letsencrypt":"internal"),g=document.querySelector(`input[name="dns-type"][value="${i}"]`),S=document.querySelector(`input[name="ssl-type"][value="${d}"]`);g?g.checked=!0:document.querySelector('input[name="dns-type"][value="private"]').checked=!0,S?S.checked=!0:document.querySelector('input[name="ssl-type"][value="internal"]').checked=!0,t.value=SITE.defaults.targetIP||"localhost",a.checked=!1;const U=document.querySelector("#app-deploy-modal .flex-col-gap")?.closest("div"),q=document.querySelector("#app-deploy-modal details"),F=q?.querySelector("div");if(q&&F&&(SITE.configurationType==="public"||SITE.configurationType==="homelab")){const W=document.querySelectorAll('#app-deploy-modal input[name="dns-type"]')[0]?.closest("div.flex-col-gap")?.parentElement,G=document.querySelectorAll('#app-deploy-modal input[name="ssl-type"]')[0]?.closest("div.flex-col-gap")?.parentElement;W&&!W.dataset.moved&&(F.appendChild(W),W.dataset.moved="1"),G&&!G.dataset.moved&&(F.appendChild(G),G.dataset.moved="1")}const _=document.getElementById("media-path-section"),J=document.getElementById("deploy-media-path"),X=document.getElementById("media-path-description");if(s.mediaMount){_.style.display="block",J.value="",J.placeholder="/media/Movies, /media/TVShows or click Browse";const W=document.getElementById("detected-mounts-container"),G=document.getElementById("detected-mounts-list");try{const K=await(await fetch("/api/v1/media/detected-mounts")).json();if(K.success&&K.mounts.length>0){W.style.display="block",G.innerHTML="";const te=[...new Set(K.mounts.map(ee=>ee.hostPath))];J.value=te.join(", "),K.mounts.forEach(ee=>{const Z=document.createElement("button");Z.type="button";const de=te.includes(ee.hostPath);Z.style.cssText=`padding: 8px 14px; font-size: 0.85rem; background: color-mix(in srgb, var(--success) ${de?"40%":"15%"}, var(--card-bg)); border: 1px solid var(--success); border-radius: 6px; cursor: pointer; color: var(--fg);`,Z.innerHTML=`<span style="font-weight: 500;">${escapeHtml(ee.folderName)}</span><br><span style="font-size: 0.7rem; color: var(--muted);">from ${escapeHtml(ee.sourceImage)}</span>`,Z.title=`${ee.hostPath} (from ${ee.sourceContainer})`,Z.onclick=()=>{const le=J.value.split(",").map(ce=>ce.trim()).filter(ce=>ce),pe=le.indexOf(ee.hostPath);pe>=0?(le.splice(pe,1),Z.style.background="color-mix(in srgb, var(--success) 15%, var(--card-bg))"):(le.push(ee.hostPath),Z.style.background="color-mix(in srgb, var(--success) 40%, var(--card-bg))"),J.value=le.join(", ")},G.appendChild(Z)})}else W.style.display="none"}catch{W.style.display="none"}document.getElementById("browse-media-btn").onclick=()=>{openFolderBrowser(J)}}else _.style.display="none",J.value="",document.getElementById("detected-mounts-container").style.display="none";const Q=document.getElementById("plex-claim-section");Q&&(s.id==="plex"||s.claimToken?(Q.style.display="block",document.getElementById("deploy-plex-claim").value=""):Q.style.display="none");const ne=document.getElementById("volume-mounts-section"),oe=document.getElementById("volume-mounts-list");if(oe.innerHTML="",s.docker?.volumes?.length){const W=s.mediaMount?.containerPath,G=s.docker.volumes.filter(V=>!V.includes("{{MEDIA_PATH}}")&&!(W&&V.endsWith(":"+W)));G.length>0?(ne.style.display="block",G.forEach((V,K)=>{const[te,ee]=V.split(":"),Z=document.createElement("div");Z.style.cssText="display: flex; gap: 6px; align-items: center;",Z.innerHTML=`
<input type="text" class="vol-host-path" data-container-path="${ee}" value="${te}"
style="flex: 1; padding: 8px; background: var(--card-bg); color: var(--fg); border: 1px solid var(--border); border-radius: 6px; font-size: 0.85rem;" />
<span style="color: var(--muted); font-size: 0.85rem; white-space: nowrap;">\u2192 ${ee}</span>
<button type="button" class="vol-browse-btn" style="padding: 8px 10px; background: var(--accent); color: white; border: none; border-radius: 6px; cursor: pointer; font-size: 0.8rem;">\u{1F4C2}</button>
`,oe.appendChild(Z),Z.querySelector(".vol-browse-btn").onclick=()=>{const de=Z.querySelector(".vol-host-path");openFolderBrowser(de)}})):ne.style.display="none"}else ne.style.display="none";const se=r.defaultPort||8080;e.value="",e.placeholder=`Default: ${se}`;let Y=document.getElementById("deploy-port-status");Y||(Y=document.createElement("div"),Y.id="deploy-port-status",Y.style.cssText="font-size: 0.8rem; margin-top: 4px;",e.parentNode.appendChild(Y));async function ie(){const W=e.value||se;Y.innerHTML='<span style="color: var(--muted);">Checking port...</span>';const G=await D(W);if(G.available)Y.innerHTML=`<span style="color: #4caf50;">Port ${escapeHtml(String(W))} is available</span>`;else{const V=await v(se);Y.innerHTML=`
`,oe.appendChild(Z),Z.querySelector(".vol-browse-btn").onclick=()=>{const de=Z.querySelector(".vol-host-path");openFolderBrowser(de)}})):ne.style.display="none"}else ne.style.display="none";const se=s.defaultPort||8080;e.value="",e.placeholder=`Default: ${se}`;let Y=document.getElementById("deploy-port-status");Y||(Y=document.createElement("div"),Y.id="deploy-port-status",Y.style.cssText="font-size: 0.8rem; margin-top: 4px;",e.parentNode.appendChild(Y));async function ie(){const W=e.value||se;Y.innerHTML='<span style="color: var(--muted);">Checking port...</span>';const G=await N(W);if(G.available)Y.innerHTML=`<span style="color: #4caf50;">Port ${escapeHtml(String(W))} is available</span>`;else{const V=await f(se);Y.innerHTML=`
<span style="color: #e74c3c;">Port ${escapeHtml(W)} in use by ${escapeHtml(G.conflict?.usedBy||"unknown")}</span>
`;const K=document.createElement("button");K.type="button",K.textContent=`Use ${V}`,K.style.cssText="margin-left: 8px; padding: 2px 8px; font-size: 0.75rem; cursor: pointer;",K.onclick=()=>{document.getElementById("deploy-port").value=V,Y.innerHTML=`<span style="color: #4caf50;">Using suggested port ${escapeHtml(String(V))}</span>`},Y.appendChild(K)}}let re;e.oninput=function(){clearTimeout(re),re=setTimeout(ie,500)},ie();try{const G=await(await fetch("/api/v1/tailscale/status")).json();G.success&&G.installed&&G.connected?o.innerHTML=`
<span style="color: #4caf50;">Connected</span>
<span style="color: var(--muted); margin-left: 8px;">${G.self?.hostname} (${G.self?.ip})</span>
<span style="color: var(--muted); margin-left: 8px;">| ${G.deviceCount} devices</span>
`:G.installed?o.innerHTML='<span style="color: #ff9800;">Not connected</span>':(o.innerHTML='<span style="color: var(--muted);">Not available</span>',a.disabled=!0)}catch{o.innerHTML='<span style="color: var(--muted);">Could not check status</span>'}function ae(){const W=b.value||"subdomain",G=document.querySelector('input[name="dns-type"]:checked').value,V=document.querySelector('input[name="ssl-type"]:checked').value;let K="";if(SITE.routingMode==="subdirectory"&&SITE.domain)K=`https://${SITE.domain}/${W}`;else if(G==="private")K=`${V==="none"?"http":"https"}://${buildDomain(W)}`;else if(G==="public"){const te=V==="none"?"http":"https",ee=SITE.domain||W;K=SITE.domain?`${te}://${W}.${SITE.domain}`:`${te}://${W}`}else{const te=e.value||r.defaultPort||DC.DEFAULTS.SERVICE_PORT;K=`http://${t.value}:${te}`}y.textContent=K}b.oninput=ae,t.oninput=ae,e.oninput=ae,document.querySelectorAll('input[name="dns-type"]').forEach(W=>{W.onchange=ae}),document.querySelectorAll('input[name="ssl-type"]').forEach(W=>{W.onchange=ae}),ae(),M.classList.remove("show"),c.classList.add("show"),c.dataset.appTemplate=JSON.stringify(r)}async function k(r){const c=r.appTemplate,d=safeGetJSON(I,[]),b=c._useExisting&&c._existingContainer,y=d.find(t=>t.id===r.subdomain);if(!(y&&!b&&!confirm(`An app with subdomain "${r.subdomain}" already exists. Redeploy?`))){if(y){const t=d.indexOf(y);d.splice(t,1),safeSet(I,JSON.stringify(d))}if(b)r.port=c._existingContainer.primaryPort;else{const t=r.port||c.defaultPort||8080;showNotification(`Checking port ${t} availability...`,"info",0);const e=await D(t);if(!e.available){const a=await v(c.defaultPort||8080);if(confirm(`Port ${t} is already in use by ${e.conflict?.usedBy||"another container"}.
`:G.installed?o.innerHTML='<span style="color: #ff9800;">Not connected</span>':(o.innerHTML='<span style="color: var(--muted);">Not available</span>',a.disabled=!0)}catch{o.innerHTML='<span style="color: var(--muted);">Could not check status</span>'}function ae(){const W=m.value||"subdomain",G=document.querySelector('input[name="dns-type"]:checked').value,V=document.querySelector('input[name="ssl-type"]:checked').value;let K="";if(SITE.routingMode==="subdirectory"&&SITE.domain)K=`https://${SITE.domain}/${W}`;else if(G==="private")K=`${V==="none"?"http":"https"}://${buildDomain(W)}`;else if(G==="public"){const te=V==="none"?"http":"https",ee=SITE.domain||W;K=SITE.domain?`${te}://${W}.${SITE.domain}`:`${te}://${W}`}else{const te=e.value||s.defaultPort||DC.DEFAULTS.SERVICE_PORT;K=`http://${t.value}:${te}`}u.textContent=K}m.oninput=ae,t.oninput=ae,e.oninput=ae,document.querySelectorAll('input[name="dns-type"]').forEach(W=>{W.onchange=ae}),document.querySelectorAll('input[name="ssl-type"]').forEach(W=>{W.onchange=ae}),ae(),M.classList.remove("show"),c.classList.add("show"),c.dataset.appTemplate=JSON.stringify(s)}async function k(s){const c=s.appTemplate,l=safeGetJSON(B,[]),m=c._useExisting&&c._existingContainer,u=l.find(t=>t.id===s.subdomain);if(!(u&&!m&&!confirm(`An app with subdomain "${s.subdomain}" already exists. Redeploy?`))){if(u){const t=l.indexOf(u);l.splice(t,1),safeSet(B,JSON.stringify(l))}if(m)s.port=c._existingContainer.primaryPort;else{const t=s.port||c.defaultPort||8080;showNotification(`Checking port ${t} availability...`,"info",0);const e=await N(t);if(!e.available){const a=await f(c.defaultPort||8080);if(confirm(`Port ${t} is already in use by ${e.conflict?.usedBy||"another container"}.
Would you like to use port ${a} instead?`))r.port=a;else{showNotification("Deployment cancelled - port conflict","error",5e3);return}}}showNotification(b?`Configuring ${c.name} with existing container...`:`Deploying ${c.name}...`,"info",0);try{const t={appId:c.id,config:{subdomain:r.subdomain,ip:r.ip,createDns:r.dnsType==="private",port:r.port||c.defaultPort||null,sslType:r.sslType,dnsType:r.dnsType,tailscaleOnly:r.tailscaleOnly||!1,mediaPath:r.mediaPath||null,plexClaimToken:r.plexClaimToken||null,customVolumes:r.customVolumes||null}};b&&(t.config.useExisting=!0,t.config.existingContainerId=c._existingContainer.id,t.config.existingPort=c._existingContainer.primaryPort,!r.port&&c._existingContainer.primaryPort&&(t.config.port=c._existingContainer.primaryPort));const a=await(await secureFetch("/api/v1/apps/deploy",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})).json();if(a.success){const o={id:r.subdomain,name:c.name,logo:`/assets/${c.id}.png`,containerId:a.containerId,url:a.url,ip:r.ip,appTemplate:c.id,tailscaleOnly:r.tailscaleOnly||!1};d.push(o),safeSet(I,JSON.stringify(d)),window.APPS&&!window.APPS.some(n=>n.id===c.id)&&(window.APPS.push(o),typeof window.buildGrid=="function"&&window.buildGrid(),typeof window.refreshAll=="function"&&setTimeout(()=>window.refreshAll(),500));let i=a.usedExisting?`${c.name} configured with existing container!
Would you like to use port ${a} instead?`))s.port=a;else{showNotification("Deployment cancelled - port conflict","error",5e3);return}}}showNotification(m?`Configuring ${c.name} with existing container...`:`Deploying ${c.name}...`,"info",0);try{const t={appId:c.id,config:{subdomain:s.subdomain,ip:s.ip,createDns:s.dnsType==="private",port:s.port||c.defaultPort||null,sslType:s.sslType,dnsType:s.dnsType,tailscaleOnly:s.tailscaleOnly||!1,mediaPath:s.mediaPath||null,plexClaimToken:s.plexClaimToken||null,customVolumes:s.customVolumes||null}};m&&(t.config.useExisting=!0,t.config.existingContainerId=c._existingContainer.id,t.config.existingPort=c._existingContainer.primaryPort,!s.port&&c._existingContainer.primaryPort&&(t.config.port=c._existingContainer.primaryPort));const a=await(await secureFetch("/api/v1/apps/deploy",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})).json();if(a.success){const o={id:s.subdomain,name:c.name,logo:`/assets/${c.id}.png`,containerId:a.containerId,url:a.url,ip:s.ip,appTemplate:c.id,tailscaleOnly:s.tailscaleOnly||!1};l.push(o),safeSet(B,JSON.stringify(l)),window.APPS&&!window.APPS.some(n=>n.id===c.id)&&(window.APPS.push(o),typeof window.buildGrid=="function"&&window.buildGrid(),typeof window.refreshAll=="function"&&setTimeout(()=>window.refreshAll(),500));let r=a.usedExisting?`${c.name} configured with existing container!
URL: ${a.url}`:`${c.name} deployed successfully!
URL: ${a.url}`;a.warning&&(i+=`
URL: ${a.url}`;a.warning&&(r+=`
\u26A0 Warning: ${a.warning}`),showNotification(i,"success",8e3),delete c._useExisting,delete c._existingContainer,a.url&&a.url.startsWith("https://")&&T(a.url,c.name),a.setupInstructions&&a.setupInstructions.length>0&&setTimeout(()=>{const n=a.setupInstructions.join(`
`);showNotification(`Setup Instructions for ${c.name}: ${n}`,"info",1e4)},1e3)}else throw new Error(a.error||"Deployment failed")}catch(t){f.logError("[AppSelector] Deployment",t,{function:"deploy"}),showNotification(`Failed to deploy ${c.name}: ${t.message}`,"error",8e3)}}}async function T(r,c){showNotification(`\u23F3 Generating SSL certificate for ${c}...`,"warning",6e4);let d=0;const b=12,y=async()=>{d++;try{const t=await fetch(r,{method:"HEAD",mode:"no-cors"});return showNotification(`\u2705 ${c} is ready! SSL certificate generated.`,"success",5e3),!0}catch{return d<b?setTimeout(y,5e3):showNotification(`\u26A0\uFE0F ${c} deployed but SSL certificate may still be generating.
Try refreshing in a moment if you see a certificate error.`,"warning",1e4),!1}};setTimeout(y,3e3)}function S(){safeGetJSON(I,[]).forEach(c=>{window.APPS.some(d=>d.id===c.id)||window.APPS.push(c)})}document.getElementById("add-service-btn")?.addEventListener("click",()=>{B(),M.classList.add("show")}),wireModal(M,document.getElementById("app-selector-cancel"));const L=document.getElementById("app-deploy-modal");document.getElementById("app-deploy-cancel")?.addEventListener("click",()=>{L.classList.remove("show")}),document.getElementById("app-deploy-confirm")?.addEventListener("click",()=>{const r=JSON.parse(L.dataset.appTemplate),c=document.getElementById("deploy-media-path").value.trim(),d=[];document.querySelectorAll("#volume-mounts-list .vol-host-path").forEach(y=>{d.push({hostPath:y.value.trim(),containerPath:y.dataset.containerPath})});const b={appTemplate:r,subdomain:document.getElementById("deploy-subdomain").value.trim(),dnsType:document.querySelector('input[name="dns-type"]:checked').value,sslType:document.querySelector('input[name="ssl-type"]:checked').value,ip:document.getElementById("deploy-ip").value.trim(),port:document.getElementById("deploy-port").value.trim(),tailscaleOnly:document.getElementById("deploy-tailscale-only").checked,mediaPath:c||null,plexClaimToken:document.getElementById("deploy-plex-claim")?.value.trim()||null,customVolumes:d.length>0?d:null,resources:{cpus:parseFloat(document.getElementById("deploy-cpu-limit").value)||0,memory:parseFloat(document.getElementById("deploy-memory-limit").value)||0}};if(!b.subdomain){showNotification("Please enter a subdomain or domain name","warning");return}if(r.mediaMount?.required&&!c){showNotification("Please enter a media library path for this application","warning");return}L.classList.remove("show"),k(b)}),wireModal(L);const j=document.getElementById("folder-browser-modal"),C=document.getElementById("folder-browser-path"),N=document.getElementById("folder-browser-list"),R=document.getElementById("folder-browser-selected"),U=document.getElementById("folder-browser-selected-list");let u="",m=[],h=null;window.openFolderBrowser=function(r){h=r,m=r.value.split(",").map(c=>c.trim()).filter(c=>c),u="",H(),g(""),j.classList.add("show")};async function g(r){C.textContent=r||"Select a drive...",N.innerHTML='<div style="padding: 20px; text-align: center; color: var(--muted);">Loading...</div>';try{const d=await(await fetch(`/api/v1/browse/directories?path=${encodeURIComponent(r)}`)).json();if(!d.success){N.innerHTML=`<div style="padding: 20px; text-align: center; color: var(--error);">Error: ${escapeHtml(d.error)}</div>`;return}u=d.path||"",C.textContent=u||"Select a drive...";let b="";d.parent&&d.parent!==d.path&&(b+=`<div class="folder-item" data-path="${escapeHtml(d.parent)}" style="padding: 12px 16px; border-bottom: 1px solid var(--border); cursor: pointer; display: flex; align-items: center; gap: 10px;">
\u26A0 Warning: ${a.warning}`),showNotification(r,"success",8e3),delete c._useExisting,delete c._existingContainer,a.url&&a.url.startsWith("https://")&&T(a.url,c.name),a.setupInstructions&&a.setupInstructions.length>0&&setTimeout(()=>{const n=a.setupInstructions.join(`
`);showNotification(`Setup Instructions for ${c.name}: ${n}`,"info",1e4)},1e3)}else throw new Error(a.error||"Deployment failed")}catch(t){x.logError("[AppSelector] Deployment",t,{function:"deploy"}),showNotification(`Failed to deploy ${c.name}: ${t.message}`,"error",8e3)}}}async function T(s,c){showNotification(`\u23F3 Generating SSL certificate for ${c}...`,"warning",6e4);let l=0;const m=12,u=async()=>{l++;try{const t=await fetch(s,{method:"HEAD",mode:"no-cors"});return showNotification(`\u2705 ${c} is ready! SSL certificate generated.`,"success",5e3),!0}catch{return l<m?setTimeout(u,5e3):showNotification(`\u26A0\uFE0F ${c} deployed but SSL certificate may still be generating.
Try refreshing in a moment if you see a certificate error.`,"warning",1e4),!1}};setTimeout(u,3e3)}function E(){safeGetJSON(B,[]).forEach(c=>{window.APPS.some(l=>l.id===c.id)||window.APPS.push(c)})}document.getElementById("add-service-btn")?.addEventListener("click",()=>{L(),M.classList.add("show")}),wireModal(M,document.getElementById("app-selector-cancel"));const I=document.getElementById("app-deploy-modal");document.getElementById("app-deploy-cancel")?.addEventListener("click",()=>{I.classList.remove("show")}),document.getElementById("app-deploy-confirm")?.addEventListener("click",()=>{const s=JSON.parse(I.dataset.appTemplate),c=document.getElementById("deploy-media-path").value.trim(),l=[];document.querySelectorAll("#volume-mounts-list .vol-host-path").forEach(u=>{l.push({hostPath:u.value.trim(),containerPath:u.dataset.containerPath})});const m={appTemplate:s,subdomain:document.getElementById("deploy-subdomain").value.trim(),dnsType:document.querySelector('input[name="dns-type"]:checked').value,sslType:document.querySelector('input[name="ssl-type"]:checked').value,ip:document.getElementById("deploy-ip").value.trim(),port:document.getElementById("deploy-port").value.trim(),tailscaleOnly:document.getElementById("deploy-tailscale-only").checked,mediaPath:c||null,plexClaimToken:document.getElementById("deploy-plex-claim")?.value.trim()||null,customVolumes:l.length>0?l:null,resources:{cpus:parseFloat(document.getElementById("deploy-cpu-limit").value)||0,memory:parseFloat(document.getElementById("deploy-memory-limit").value)||0}};if(!m.subdomain){showNotification("Please enter a subdomain or domain name","warning");return}if(s.mediaMount?.required&&!c){showNotification("Please enter a media library path for this application","warning");return}I.classList.remove("show"),k(m)}),wireModal(I);const j=document.getElementById("folder-browser-modal"),H=document.getElementById("folder-browser-path"),R=document.getElementById("folder-browser-list"),D=document.getElementById("folder-browser-selected"),O=document.getElementById("folder-browser-selected-list");let p="",v=[],b=null;window.openFolderBrowser=function(s){b=s,v=s.value.split(",").map(c=>c.trim()).filter(c=>c),p="",h(),y(""),j.classList.add("show")};async function y(s){H.textContent=s||"Select a drive...",R.innerHTML='<div style="padding: 20px; text-align: center; color: var(--muted);">Loading...</div>';try{const l=await(await fetch(`/api/v1/browse/directories?path=${encodeURIComponent(s)}`)).json();if(!l.success){R.innerHTML=`<div style="padding: 20px; text-align: center; color: var(--error);">Error: ${escapeHtml(l.error)}</div>`;return}p=l.path||"",H.textContent=p||"Select a drive...";let m="";l.parent&&l.parent!==l.path&&(m+=`<div class="folder-item" data-path="${escapeHtml(l.parent)}" style="padding: 12px 16px; border-bottom: 1px solid var(--border); cursor: pointer; display: flex; align-items: center; gap: 10px;">
<span style="font-size: 1.2rem;">\u2B06\uFE0F</span>
<span style="color: var(--muted);">.. Parent Directory</span>
</div>`),d.items.length===0&&!d.parent?b+='<div style="padding: 20px; text-align: center; color: var(--muted);">No browseable drives configured. Check your docker-compose.yml volume mounts.</div>':d.items.length===0?b+='<div style="padding: 20px; text-align: center; color: var(--muted);">No subfolders found</div>':d.items.forEach(y=>{const t=y.type==="drive"?"\u{1F4BE}":"\u{1F4C1}",e=m.includes(y.path),a=e?"background: color-mix(in srgb, var(--success) 20%, transparent);":"";b+=`<div class="folder-item" data-path="${escapeHtml(y.path)}" style="padding: 12px 16px; border-bottom: 1px solid var(--border); cursor: pointer; display: flex; align-items: center; gap: 10px; ${a}">
</div>`),l.items.length===0&&!l.parent?m+='<div style="padding: 20px; text-align: center; color: var(--muted);">No browseable drives configured. Check your docker-compose.yml volume mounts.</div>':l.items.length===0?m+='<div style="padding: 20px; text-align: center; color: var(--muted);">No subfolders found</div>':l.items.forEach(u=>{const t=u.type==="drive"?"\u{1F4BE}":"\u{1F4C1}",e=v.includes(u.path),a=e?"background: color-mix(in srgb, var(--success) 20%, transparent);":"";m+=`<div class="folder-item" data-path="${escapeHtml(u.path)}" style="padding: 12px 16px; border-bottom: 1px solid var(--border); cursor: pointer; display: flex; align-items: center; gap: 10px; ${a}">
<span style="font-size: 1.2rem;">${t}</span>
<span style="flex: 1;">${escapeHtml(y.name)}</span>
<span style="flex: 1;">${escapeHtml(u.name)}</span>
${e?'<span style="color: var(--success);">\u2713</span>':""}
</div>`}),N.innerHTML=b,N.querySelectorAll(".folder-item").forEach(y=>{y.addEventListener("click",()=>{g(y.dataset.path)}),y.addEventListener("mouseenter",()=>{y.style.background="var(--card-bg)"}),y.addEventListener("mouseleave",()=>{const t=m.includes(y.dataset.path);y.style.background=t?"color-mix(in srgb, var(--success) 20%, transparent)":""})})}catch(c){N.innerHTML=`<div style="padding: 20px; text-align: center; color: var(--error);">Failed to load: ${escapeHtml(c.message)}</div>`}}function H(){if(m.length===0){R.style.display="none";return}R.style.display="block",U.innerHTML=m.map(r=>`
</div>`}),R.innerHTML=m,R.querySelectorAll(".folder-item").forEach(u=>{u.addEventListener("click",()=>{y(u.dataset.path)}),u.addEventListener("mouseenter",()=>{u.style.background="var(--card-bg)"}),u.addEventListener("mouseleave",()=>{const t=v.includes(u.dataset.path);u.style.background=t?"color-mix(in srgb, var(--success) 20%, transparent)":""})})}catch(c){R.innerHTML=`<div style="padding: 20px; text-align: center; color: var(--error);">Failed to load: ${escapeHtml(c.message)}</div>`}}function h(){if(v.length===0){D.style.display="none";return}D.style.display="block",O.innerHTML=v.map(s=>`
<span style="padding: 6px 12px; background: var(--card-bg); border: 1px solid var(--success); border-radius: 4px; display: flex; align-items: center; gap: 6px;">
${escapeHtml(r)}
<button type="button" onclick="removeSelectedFolder('${escapeHtml(r)}')" style="background: none; border: none; cursor: pointer; color: var(--error); font-size: 1rem; padding: 0;">\xD7</button>
${escapeHtml(s)}
<button type="button" onclick="removeSelectedFolder('${escapeHtml(s)}')" style="background: none; border: none; cursor: pointer; color: var(--error); font-size: 1rem; padding: 0;">\xD7</button>
</span>
`).join("")}window.removeSelectedFolder=function(r){m=m.filter(c=>c!==r),H(),g(u)},document.getElementById("folder-browser-select-current").addEventListener("click",()=>{u&&!m.includes(u)&&(m.push(u),H(),g(u))}),wireModal(j,document.getElementById("folder-browser-cancel")),document.getElementById("folder-browser-done").addEventListener("click",()=>{h&&(h.value=m.join(", ")),j.classList.remove("show")}),S()})(),(function(){injectModal("recipe-deploy-modal",`<div id="recipe-deploy-modal" class="weather-modal">
`).join("")}window.removeSelectedFolder=function(s){v=v.filter(c=>c!==s),h(),y(p)},document.getElementById("folder-browser-select-current").addEventListener("click",()=>{p&&!v.includes(p)&&(v.push(p),h(),y(p))}),wireModal(j,document.getElementById("folder-browser-cancel")),document.getElementById("folder-browser-done").addEventListener("click",()=>{b&&(b.value=v.join(", ")),j.classList.remove("show")}),E()})(),(function(){injectModal("recipe-deploy-modal",`<div id="recipe-deploy-modal" class="weather-modal">
<div class="weather-modal-content" style="min-width: 620px; max-width: 740px;">
<h3 id="recipe-deploy-title">Deploy Recipe</h3>
@@ -445,70 +445,70 @@ Try refreshing in a moment if you see a certificate error.`,"warning",1e4),!1}};
<button id="recipe-next" class="btn-accent-solid">Next</button>
</div>
</div>
</div>`);let f=null,I=null,A=null,E=1,M=!1;const P=document.getElementById("recipe-deploy-modal"),z=document.getElementById("recipe-cancel"),D=document.getElementById("recipe-prev"),v=document.getElementById("recipe-next");wireModal(P,z);async function B(){try{const u=await fetch("/api/v1/recipes/templates"),m=await u.json();if(m.success)return f=m.templates,I=m.categories,!0;if(u.status===403)return M=!1,!1}catch(u){console.warn("Failed to fetch recipe templates:",u.message)}return!1}async function x(){try{M=(await(await fetch("/api/v1/license/feature/recipes")).json()).available}catch{M=!1}return M}window.renderRecipeCards=async function(u){await x();let m;if(M&&f?m=f:m=$(),!m||m.length===0)return;const h=document.createElement("div");h.className="app-category-header",h.innerHTML="\u{1F9EA} Recipes",h.style.borderBottomColor="#8e44ad",u.appendChild(h);const g=Array.isArray(m)?m:Object.values(m);g.sort((H,r)=>(r.popularity||0)-(H.popularity||0));for(const H of g){const r=document.createElement("div");r.className="app-option",r.style.position="relative";const c=`<div style="font-size: 0.65rem; padding: 2px 6px; border-radius: 4px; margin-top: 4px; background: rgba(142,68,173,0.2); color: #a855f7;">${H.componentCount||H.components?.length||"?"} apps</div>`,d=M?"":'<div style="position: absolute; top: 6px; right: 6px; font-size: 0.65rem; padding: 2px 8px; border-radius: 10px; background: rgba(241,196,15,0.2); color: #f1c40f; font-weight: 600;">PREMIUM</div>';r.innerHTML=`
${d}
<div class="app-option-icon">${escapeHtml(H.icon||"\u{1F9EA}")}</div>
<div class="app-option-name">${escapeHtml(H.name)}</div>
<div class="app-option-desc">${escapeHtml(H.description||"")}</div>
</div>`);let x=null,B=null,A=null,C=1,M=!1;const P=document.getElementById("recipe-deploy-modal"),z=document.getElementById("recipe-cancel"),N=document.getElementById("recipe-prev"),f=document.getElementById("recipe-next");wireModal(P,z);async function L(){try{const p=await fetch("/api/v1/recipes/templates"),v=await p.json();if(v.success)return x=v.templates,B=v.categories,!0;if(p.status===403)return M=!1,!1}catch(p){console.warn("Failed to fetch recipe templates:",p.message)}return!1}async function w(){try{M=(await(await fetch("/api/v1/license/feature/recipes")).json()).available}catch{M=!1}return M}window.renderRecipeCards=async function(p){await w();let v;if(M&&x?v=x:v=$(),!v||v.length===0)return;const b=document.createElement("div");b.className="app-category-header",b.innerHTML="\u{1F9EA} Recipes",b.style.borderBottomColor="#8e44ad",p.appendChild(b);const y=Array.isArray(v)?v:Object.values(v);y.sort((h,s)=>(s.popularity||0)-(h.popularity||0));for(const h of y){const s=document.createElement("div");s.className="app-option",s.style.position="relative";const c=`<div style="font-size: 0.65rem; padding: 2px 6px; border-radius: 4px; margin-top: 4px; background: rgba(142,68,173,0.2); color: #a855f7;">${h.componentCount||h.components?.length||"?"} apps</div>`,l=M?"":'<div style="position: absolute; top: 6px; right: 6px; font-size: 0.65rem; padding: 2px 8px; border-radius: 10px; background: rgba(241,196,15,0.2); color: #f1c40f; font-weight: 600;">PREMIUM</div>';s.innerHTML=`
${l}
<div class="app-option-icon">${escapeHtml(h.icon||"\u{1F9EA}")}</div>
<div class="app-option-name">${escapeHtml(h.name)}</div>
<div class="app-option-desc">${escapeHtml(h.description||"")}</div>
${c}
`,r.onclick=()=>{if(!M){showNotification("Recipes require a DashCaddy Premium license. Click the License button to activate.","warning",5e3),window.openLicenseModal&&window.openLicenseModal();return}k(H)},u.appendChild(r)}};function $(){return[{id:"htpc-suite",name:"HTPC Suite",icon:"\u{1F3AC}",description:"Complete media automation: find, download, organize, and stream",componentCount:6,popularity:98},{id:"nextcloud-complete",name:"Nextcloud Complete",icon:"\u2601\uFE0F",description:"Full productivity suite: cloud storage, office editing, and collaboration",componentCount:4,popularity:90},{id:"smart-home",name:"Smart Home Hub",icon:"\u{1F3E0}",description:"Home automation: control, automate, and monitor IoT devices",componentCount:4,popularity:88},{id:"dev-environment",name:"Dev Environment",icon:"\u{1F4BB}",description:"Self-hosted development workflow: Git, CI/CD, IDE, and database",componentCount:4,popularity:82}]}function k(u){A=u,E=1;const m=document.getElementById("app-selector-modal");m&&m.classList.remove("show"),document.getElementById("recipe-deploy-title").textContent=`Deploy ${u.name}`,T(),S(),P.classList.add("show")}function T(){document.querySelectorAll("#recipe-steps .recipe-step").forEach(u=>{const m=parseInt(u.dataset.step);u.classList.toggle("active",m===E),u.classList.toggle("completed",m<E)});for(let u=1;u<=4;u++){const m=document.getElementById(`recipe-step-${u}`);m&&(m.style.display=u===E?"":"none")}D.style.display=E>1&&E<4?"":"none",E===4?(v.style.display="none",z.textContent="Close"):E===3?(v.textContent="\u{1F680} Deploy",v.style.display="",z.textContent="Cancel"):(v.textContent="Next",v.style.display="",z.textContent="Cancel")}function S(){const u=document.getElementById("recipe-component-list");u.innerHTML="";const m=A.components||[];for(const h of m){const g=document.createElement("div");g.style.cssText="display: flex; align-items: center; gap: 12px; padding: 12px; border-radius: 8px; background: var(--card-bg); border: 1px solid var(--border);";const H=h.required,r=h.internal;g.innerHTML=`
<input type="checkbox" ${H?"checked disabled":"checked"} data-component-id="${h.id}"
`,s.onclick=()=>{if(!M){showNotification("Recipes require a DashCaddy Premium license. Click the License button to activate.","warning",5e3),window.openLicenseModal&&window.openLicenseModal();return}k(h)},p.appendChild(s)}};function $(){return[{id:"htpc-suite",name:"HTPC Suite",icon:"\u{1F3AC}",description:"Complete media automation: find, download, organize, and stream",componentCount:6,popularity:98},{id:"nextcloud-complete",name:"Nextcloud Complete",icon:"\u2601\uFE0F",description:"Full productivity suite: cloud storage, office editing, and collaboration",componentCount:4,popularity:90},{id:"smart-home",name:"Smart Home Hub",icon:"\u{1F3E0}",description:"Home automation: control, automate, and monitor IoT devices",componentCount:4,popularity:88},{id:"dev-environment",name:"Dev Environment",icon:"\u{1F4BB}",description:"Self-hosted development workflow: Git, CI/CD, IDE, and database",componentCount:4,popularity:82}]}function k(p){A=p,C=1;const v=document.getElementById("app-selector-modal");v&&v.classList.remove("show"),document.getElementById("recipe-deploy-title").textContent=`Deploy ${p.name}`,T(),E(),P.classList.add("show")}function T(){document.querySelectorAll("#recipe-steps .recipe-step").forEach(p=>{const v=parseInt(p.dataset.step);p.classList.toggle("active",v===C),p.classList.toggle("completed",v<C)});for(let p=1;p<=4;p++){const v=document.getElementById(`recipe-step-${p}`);v&&(v.style.display=p===C?"":"none")}N.style.display=C>1&&C<4?"":"none",C===4?(f.style.display="none",z.textContent="Close"):C===3?(f.textContent="\u{1F680} Deploy",f.style.display="",z.textContent="Cancel"):(f.textContent="Next",f.style.display="",z.textContent="Cancel")}function E(){const p=document.getElementById("recipe-component-list");p.innerHTML="";const v=A.components||[];for(const b of v){const y=document.createElement("div");y.style.cssText="display: flex; align-items: center; gap: 12px; padding: 12px; border-radius: 8px; background: var(--card-bg); border: 1px solid var(--border);";const h=b.required,s=b.internal;y.innerHTML=`
<input type="checkbox" ${h?"checked disabled":"checked"} data-component-id="${b.id}"
style="width: 18px; height: 18px; accent-color: var(--accent);" />
<div style="flex: 1;">
<div style="font-weight: 600; font-size: 0.9rem;">${escapeHtml(h.role||h.id)}</div>
<div style="font-weight: 600; font-size: 0.9rem;">${escapeHtml(b.role||b.id)}</div>
<div style="font-size: 0.78rem; color: var(--muted);">
${h.templateRef?escapeHtml(h.templateRef):"Built-in"}
${H?'<span style="color: var(--accent); margin-left: 6px;">Required</span>':'<span style="color: var(--muted); margin-left: 6px;">Optional</span>'}
${r?'<span style="color: var(--muted); margin-left: 6px;">(Internal)</span>':""}
${b.templateRef?escapeHtml(b.templateRef):"Built-in"}
${h?'<span style="color: var(--accent); margin-left: 6px;">Required</span>':'<span style="color: var(--muted); margin-left: 6px;">Optional</span>'}
${s?'<span style="color: var(--muted); margin-left: 6px;">(Internal)</span>':""}
</div>
${h.note?`<div style="font-size: 0.75rem; color: var(--warn-fg); margin-top: 4px;">\u26A0 ${escapeHtml(h.note)}</div>`:""}
${b.note?`<div style="font-size: 0.75rem; color: var(--warn-fg); margin-top: 4px;">\u26A0 ${escapeHtml(b.note)}</div>`:""}
</div>
`,u.appendChild(g)}}function L(){const u=document.getElementById("recipe-volumes-section"),m=document.getElementById("recipe-volume-list"),h=A.sharedVolumes;if(h&&Object.keys(h).length>0){u.style.display="",m.innerHTML="";for(const[g,H]of Object.entries(h)){const r=document.createElement("div");r.style.cssText="display: grid; gap: 4px;",r.innerHTML=`
<label style="font-weight: 500; font-size: 0.85rem;">${escapeHtml(H.label||g)}</label>
<input type="text" data-volume-key="${g}" value="${escapeHtml(H.defaultPath||"")}"
placeholder="${escapeHtml(H.defaultPath||"/path")}"
`,p.appendChild(y)}}function I(){const p=document.getElementById("recipe-volumes-section"),v=document.getElementById("recipe-volume-list"),b=A.sharedVolumes;if(b&&Object.keys(b).length>0){p.style.display="",v.innerHTML="";for(const[y,h]of Object.entries(b)){const s=document.createElement("div");s.style.cssText="display: grid; gap: 4px;",s.innerHTML=`
<label style="font-weight: 500; font-size: 0.85rem;">${escapeHtml(h.label||y)}</label>
<input type="text" data-volume-key="${y}" value="${escapeHtml(h.defaultPath||"")}"
placeholder="${escapeHtml(h.defaultPath||"/path")}"
style="width: 100%; padding: 8px 12px; background: var(--card-bg); color: var(--fg); border: 1px solid var(--border); border-radius: 6px; font-family: monospace; font-size: 0.85rem;" />
<div class="form-hint-sm">${escapeHtml(H.description||"")}</div>
`,m.appendChild(r)}}else u.style.display="none"}function j(){const u=document.getElementById("recipe-review-content"),m=C(),h=document.querySelectorAll("#recipe-volume-list input[data-volume-key]"),g={};h.forEach(d=>{g[d.dataset.volumeKey]=d.value});const H=document.getElementById("recipe-timezone").value||"UTC",r=document.getElementById("recipe-ip").value||"host.docker.internal",c=document.getElementById("recipe-tailscale").checked;u.innerHTML=`
<div class="form-hint-sm">${escapeHtml(h.description||"")}</div>
`,v.appendChild(s)}}else p.style.display="none"}function j(){const p=document.getElementById("recipe-review-content"),v=H(),b=document.querySelectorAll("#recipe-volume-list input[data-volume-key]"),y={};b.forEach(l=>{y[l.dataset.volumeKey]=l.value});const h=document.getElementById("recipe-timezone").value||"UTC",s=document.getElementById("recipe-ip").value||"host.docker.internal",c=document.getElementById("recipe-tailscale").checked;p.innerHTML=`
<div style="font-weight: 600; font-size: 1rem; margin-bottom: 12px;">${escapeHtml(A.name)}</div>
<div style="color: var(--muted); margin-bottom: 16px;">${escapeHtml(A.description||"")}</div>
<div style="margin-bottom: 12px;">
<strong>Components (${m.length}):</strong>
<strong>Components (${v.length}):</strong>
<div style="display: grid; gap: 4px; margin-top: 6px;">
${m.map(d=>`<div style="padding: 4px 0; font-size: 0.85rem;">
\u2022 <strong>${escapeHtml(d.role||d.id)}</strong> ${d.internal?'<span style="color:var(--muted)">(internal)</span>':""}
${v.map(l=>`<div style="padding: 4px 0; font-size: 0.85rem;">
\u2022 <strong>${escapeHtml(l.role||l.id)}</strong> ${l.internal?'<span style="color:var(--muted)">(internal)</span>':""}
</div>`).join("")}
</div>
</div>
${Object.keys(g).length>0?`<div style="margin-bottom: 12px;">
${Object.keys(y).length>0?`<div style="margin-bottom: 12px;">
<strong>Volumes:</strong>
${Object.entries(g).map(([d,b])=>`<div style="font-size: 0.85rem; font-family: monospace; color: var(--muted);">${d}: ${escapeHtml(b)}</div>`).join("")}
${Object.entries(y).map(([l,m])=>`<div style="font-size: 0.85rem; font-family: monospace; color: var(--muted);">${l}: ${escapeHtml(m)}</div>`).join("")}
</div>`:""}
<div style="font-size: 0.85rem; color: var(--muted);">
Timezone: ${escapeHtml(H)} &bull; IP: ${escapeHtml(r)} ${c?"&bull; Tailscale only":""}
Timezone: ${escapeHtml(h)} &bull; IP: ${escapeHtml(s)} ${c?"&bull; Tailscale only":""}
</div>
${A.network?`<div style="font-size: 0.85rem; color: var(--muted); margin-top: 4px;">Docker network: <code>${escapeHtml(A.network.name)}</code></div>`:""}
`}function C(){const u=document.querySelectorAll("#recipe-component-list input[data-component-id]"),m=new Set;u.forEach(g=>{g.checked&&m.add(g.dataset.componentId)});const h=A.components||[];return h.filter(g=>g.required).forEach(g=>m.add(g.id)),h.filter(g=>m.has(g.id))}async function N(){const u=document.getElementById("recipe-progress-list"),m=document.getElementById("recipe-deploy-result");m.style.display="none",u.innerHTML="";const h=C();for(const c of h){const d=document.createElement("div");d.id=`recipe-progress-${c.id}`,d.style.cssText="display: flex; align-items: center; gap: 10px; padding: 10px 12px; border-radius: 6px; background: var(--card-bg); border: 1px solid var(--border); font-size: 0.85rem;",d.innerHTML=`
`}function H(){const p=document.querySelectorAll("#recipe-component-list input[data-component-id]"),v=new Set;p.forEach(y=>{y.checked&&v.add(y.dataset.componentId)});const b=A.components||[];return b.filter(y=>y.required).forEach(y=>v.add(y.id)),b.filter(y=>v.has(y.id))}async function R(){const p=document.getElementById("recipe-progress-list"),v=document.getElementById("recipe-deploy-result");v.style.display="none",p.innerHTML="";const b=H();for(const c of b){const l=document.createElement("div");l.id=`recipe-progress-${c.id}`,l.style.cssText="display: flex; align-items: center; gap: 10px; padding: 10px 12px; border-radius: 6px; background: var(--card-bg); border: 1px solid var(--border); font-size: 0.85rem;",l.innerHTML=`
<span class="recipe-progress-icon" style="font-size: 1.1rem;">\u23F3</span>
<span style="flex:1; font-weight: 500;">${escapeHtml(c.role||c.id)}</span>
<span class="recipe-progress-status" style="color: var(--muted);">Queued</span>
`,u.appendChild(d)}const g=document.querySelectorAll("#recipe-volume-list input[data-volume-key]"),H={};g.forEach(c=>{H[c.dataset.volumeKey]=c.value});const r={selectedComponents:h.map(c=>c.id),sharedConfig:{ip:document.getElementById("recipe-ip").value||"host.docker.internal",timezone:document.getElementById("recipe-timezone").value||"UTC",tailscaleOnly:document.getElementById("recipe-tailscale").checked,volumes:H},componentOverrides:{}};for(const c of h)R(c.id,"deploying","Deploying...");try{const d=await(await secureFetch("/api/v1/recipes/deploy",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({recipeId:A.id,config:r})})).json();if(d.success){for(const b of d.deployed||[])R(b.id,"success",b.url?`Running \u2192 ${b.url}`:"Running");for(const b of d.errors||[])R(b.componentId,"error",b.error);m.style.display="",m.innerHTML=`
`,p.appendChild(l)}const y=document.querySelectorAll("#recipe-volume-list input[data-volume-key]"),h={};y.forEach(c=>{h[c.dataset.volumeKey]=c.value});const s={selectedComponents:b.map(c=>c.id),sharedConfig:{ip:document.getElementById("recipe-ip").value||"host.docker.internal",timezone:document.getElementById("recipe-timezone").value||"UTC",tailscaleOnly:document.getElementById("recipe-tailscale").checked,volumes:h},componentOverrides:{}};for(const c of b)D(c.id,"deploying","Deploying...");try{const l=await(await secureFetch("/api/v1/recipes/deploy",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({recipeId:A.id,config:s})})).json();if(l.success){for(const m of l.deployed||[])D(m.id,"success",m.url?`Running \u2192 ${m.url}`:"Running");for(const m of l.errors||[])D(m.componentId,"error",m.error);v.style.display="",v.innerHTML=`
<div style="padding: 14px; border-radius: 8px; background: rgba(46,204,113,0.1); border: 1px solid rgba(46,204,113,0.3);">
<div style="font-weight: 600; color: var(--ok-fg); margin-bottom: 6px;">${escapeHtml(d.message||"Deployed!")}</div>
${d.setupInstructions?`<div style="font-size: 0.8rem; color: var(--muted); margin-top: 8px;">
<div style="font-weight: 600; color: var(--ok-fg); margin-bottom: 6px;">${escapeHtml(l.message||"Deployed!")}</div>
${l.setupInstructions?`<div style="font-size: 0.8rem; color: var(--muted); margin-top: 8px;">
<strong>Setup tips:</strong>
<ul style="margin: 4px 0 0 16px; padding: 0;">${d.setupInstructions.map(b=>`<li>${escapeHtml(b)}</li>`).join("")}</ul>
<ul style="margin: 4px 0 0 16px; padding: 0;">${l.setupInstructions.map(m=>`<li>${escapeHtml(m)}</li>`).join("")}</ul>
</div>`:""}
</div>
`,showNotification(`${A.name} recipe deployed successfully!`,"success",5e3),window.loadServices&&window.loadServices()}else m.style.display="",m.innerHTML=`<div style="padding: 14px; border-radius: 8px; background: rgba(231,76,60,0.1); border: 1px solid rgba(231,76,60,0.3); color: var(--bad-fg);">
<strong>Deployment failed:</strong> ${escapeHtml(d.error||"Unknown error")}
</div>`,showNotification(`Recipe deployment failed: ${d.error}`,"error",5e3)}catch(c){m.style.display="",m.innerHTML=`<div style="padding: 14px; border-radius: 8px; background: rgba(231,76,60,0.1); border: 1px solid rgba(231,76,60,0.3); color: var(--bad-fg);">
`,showNotification(`${A.name} recipe deployed successfully!`,"success",5e3),window.loadServices&&window.loadServices()}else v.style.display="",v.innerHTML=`<div style="padding: 14px; border-radius: 8px; background: rgba(231,76,60,0.1); border: 1px solid rgba(231,76,60,0.3); color: var(--bad-fg);">
<strong>Deployment failed:</strong> ${escapeHtml(l.error||"Unknown error")}
</div>`,showNotification(`Recipe deployment failed: ${l.error}`,"error",5e3)}catch(c){v.style.display="",v.innerHTML=`<div style="padding: 14px; border-radius: 8px; background: rgba(231,76,60,0.1); border: 1px solid rgba(231,76,60,0.3); color: var(--bad-fg);">
<strong>Network error:</strong> ${escapeHtml(c.message)}
</div>`}}function R(u,m,h){const g=document.getElementById(`recipe-progress-${u}`);if(!g)return;const H=g.querySelector(".recipe-progress-icon"),r=g.querySelector(".recipe-progress-status");m==="deploying"?(H.textContent="\u23F3",r.style.color="var(--accent)"):m==="success"?(H.textContent="\u2705",r.style.color="var(--ok-fg)"):m==="error"&&(H.textContent="\u274C",r.style.color="var(--bad-fg)"),r.textContent=h}v.addEventListener("click",()=>{if(E===3){E=4,T(),N();return}E<3&&(E++,T(),E===2&&L(),E===3&&j())}),D.addEventListener("click",()=>{E>1&&E<4&&(E--,T())}),window.groupRecipeCards=function(){const u=document.querySelectorAll(".service-card[data-recipe-id]");if(u.length===0)return;const m={};u.forEach(h=>{const g=h.dataset.recipeId;m[g]||(m[g]=[]),m[g].push(h)});for(const[h,g]of Object.entries(m))g.length<2||g.forEach((H,r)=>{if(H.style.borderLeft="3px solid rgba(142,68,173,0.5)",r===0){let c=H.querySelector(".recipe-group-label");c||(c=document.createElement("div"),c.className="recipe-group-label",c.style.cssText="position: absolute; top: -8px; left: 12px; font-size: 0.6rem; padding: 1px 8px; border-radius: 8px; background: rgba(142,68,173,0.3); color: #d4a5ff; font-weight: 600; text-transform: uppercase; letter-spacing: 0.5px;",c.textContent=h.replace(/-/g," "),H.style.position="relative",H.appendChild(c))}})},window.manageRecipe=async function(u,m){const h=`/api/v1/recipes/${u}/${m}`,g=m==="remove"?"DELETE":"POST",H=m==="remove"?`/api/v1/recipes/${u}`:h;if(!(m==="remove"&&!confirm(`Remove the entire ${u} recipe? This will delete all containers and configuration.`)))try{const c=await(await secureFetch(H,{method:g})).json();c.success?(showNotification(`Recipe ${m}: ${c.results?.filter(d=>d.status!=="failed").length||0} components processed`,"success",4e3),window.loadServices&&window.loadServices()):showNotification(`Recipe ${m} failed: ${c.error}`,"error",5e3)}catch(r){showNotification(`Network error: ${r.message}`,"error",5e3)}};const U=document.createElement("style");U.textContent=`
</div>`}}function D(p,v,b){const y=document.getElementById(`recipe-progress-${p}`);if(!y)return;const h=y.querySelector(".recipe-progress-icon"),s=y.querySelector(".recipe-progress-status");v==="deploying"?(h.textContent="\u23F3",s.style.color="var(--accent)"):v==="success"?(h.textContent="\u2705",s.style.color="var(--ok-fg)"):v==="error"&&(h.textContent="\u274C",s.style.color="var(--bad-fg)"),s.textContent=b}f.addEventListener("click",()=>{if(C===3){C=4,T(),R();return}C<3&&(C++,T(),C===2&&I(),C===3&&j())}),N.addEventListener("click",()=>{C>1&&C<4&&(C--,T())}),window.groupRecipeCards=function(){const p=document.querySelectorAll(".service-card[data-recipe-id]");if(p.length===0)return;const v={};p.forEach(b=>{const y=b.dataset.recipeId;v[y]||(v[y]=[]),v[y].push(b)});for(const[b,y]of Object.entries(v))y.length<2||y.forEach((h,s)=>{if(h.style.borderLeft="3px solid rgba(142,68,173,0.5)",s===0){let c=h.querySelector(".recipe-group-label");c||(c=document.createElement("div"),c.className="recipe-group-label",c.style.cssText="position: absolute; top: -8px; left: 12px; font-size: 0.6rem; padding: 1px 8px; border-radius: 8px; background: rgba(142,68,173,0.3); color: #d4a5ff; font-weight: 600; text-transform: uppercase; letter-spacing: 0.5px;",c.textContent=b.replace(/-/g," "),h.style.position="relative",h.appendChild(c))}})},window.manageRecipe=async function(p,v){const b=`/api/v1/recipes/${p}/${v}`,y=v==="remove"?"DELETE":"POST",h=v==="remove"?`/api/v1/recipes/${p}`:b;if(!(v==="remove"&&!confirm(`Remove the entire ${p} recipe? This will delete all containers and configuration.`)))try{const c=await(await secureFetch(h,{method:y})).json();c.success?(showNotification(`Recipe ${v}: ${c.results?.filter(l=>l.status!=="failed").length||0} components processed`,"success",4e3),window.loadServices&&window.loadServices()):showNotification(`Recipe ${v} failed: ${c.error}`,"error",5e3)}catch(s){showNotification(`Network error: ${s.message}`,"error",5e3)}};const O=document.createElement("style");O.textContent=`
.recipe-step {
flex: 1;
text-align: center;
@@ -550,16 +550,55 @@ Try refreshing in a moment if you see a certificate error.`,"warning",1e4),!1}};
.recipe-step-panel {
min-height: 180px;
}
`,document.head.appendChild(U),x()})(),(function(){document.getElementById("reload-caddy-top")?.addEventListener("click",async()=>{const f=document.getElementById("reload-caddy-top"),I=f.textContent;try{f.textContent="\u23F3 Reloading...",f.disabled=!0;const A=await secureFetch("/api/v1/caddy/reload",{method:"POST",headers:{"Content-Type":"application/json"}}),E=await A.json();if(A.ok&&E.success)f.textContent="\u2705 Reloaded!",setTimeout(()=>{f.textContent=I,f.disabled=!1},2e3);else throw new Error(E.error||"Reload failed")}catch(A){f.textContent="\u274C Failed",showNotification(`Failed to reload Caddy: ${A.message}`,"error"),setTimeout(()=>{f.textContent=I,f.disabled=!1},2e3)}})})(),(function(){injectModal("error-log-modal",'<div id="error-log-modal" class="logs-modal"><div class="logs-modal-content"><div class="logs-header"><h3>\u{1F4CB} Error Logs</h3><div class="logs-controls"><button id="error-log-refresh" style="padding:4px 12px!important;font-size:.85rem!important">\u{1F504} Refresh</button><button id="error-log-clear" style="padding:4px 12px!important;font-size:.85rem!important;background:color-mix(in srgb,var(--bad-fg) 15%,transparent)!important;border-color:var(--bad-fg)!important;color:var(--bad-fg)!important">\u{1F5D1}\uFE0F Clear</button><button id="error-log-close" class="close-btn">\u2715</button></div></div><div class="logs-container"><div id="error-log-content" class="logs-content"><div class="logs-loading">Loading error logs...</div></div></div></div></div>');const f=document.getElementById("error-log-modal"),I=document.getElementById("error-log-content"),A=document.getElementById("view-error-logs"),E=document.getElementById("error-log-refresh"),M=document.getElementById("error-log-clear"),P=document.getElementById("error-log-close");async function z(){I.innerHTML='<div class="logs-loading">Loading error logs...</div>';try{const B=await(await fetch("/api/v1/error-logs")).json();B.success&&B.logs?B.logs.length===0?I.innerHTML='<div style="padding: 20px; text-align: center; color: var(--muted);">\u2705 No errors logged! Everything is working smoothly.</div>':I.innerHTML=B.logs.map(x=>`
<div class="log-entry error">
<span class="log-timestamp">${new Date(x.timestamp).toLocaleString()}</span>
<span class="log-level">ERROR</span>
<div class="log-message">
<strong>${escapeHtml(x.context)}</strong>: ${escapeHtml(x.error)}
${x.details?`<br><small style="opacity: 0.7;">${escapeHtml(x.details)}</small>`:""}
</div>
</div>
`).join(""):I.innerHTML='<div style="padding: 20px; color: var(--bad-fg);">\u274C Failed to load error logs</div>'}catch(v){I.innerHTML=`<div style="padding: 20px; color: var(--bad-fg);">\u274C Error loading logs: ${escapeHtml(v.message)}</div>`}}async function D(){if(confirm("Clear all error logs?"))try{(await(await secureFetch("/api/v1/error-logs",{method:"DELETE"})).json()).success?(showNotification("\u2705 Error logs cleared","success",3e3),z()):showNotification("\u274C Failed to clear logs","error",3e3)}catch(v){showNotification(`\u274C Error: ${v.message}`,"error",3e3)}}A?.addEventListener("click",()=>{f.classList.add("show"),z()}),E?.addEventListener("click",z),M?.addEventListener("click",D),wireModal(f,P)})(),(function(){injectModal("container-logs-modal",`<div id="container-logs-modal" class="weather-modal" style="z-index: 1001;">
`,document.head.appendChild(O),w()})(),(function(){document.getElementById("reload-caddy-top")?.addEventListener("click",async()=>{const x=document.getElementById("reload-caddy-top"),B=x.textContent;try{x.textContent="\u23F3 Reloading...",x.disabled=!0;const A=await secureFetch("/api/v1/caddy/reload",{method:"POST",headers:{"Content-Type":"application/json"}}),C=await A.json();if(A.ok&&C.success)x.textContent="\u2705 Reloaded!",setTimeout(()=>{x.textContent=B,x.disabled=!1},2e3);else throw new Error(C.error||"Reload failed")}catch(A){x.textContent="\u274C Failed",showNotification(`Failed to reload Caddy: ${A.message}`,"error"),setTimeout(()=>{x.textContent=B,x.disabled=!1},2e3)}})})(),(function(){injectModal("error-log-modal",`<div id="error-log-modal" class="weather-modal">
<div class="weather-modal-content" style="min-width: 950px; max-width: 1150px;">
<h3>\u{1F4CB} Error Logs</h3>
<p class="modal-subtitle">
Errors and warnings from the DashCaddy API. Click a row to see the full stack trace.
</p>
<div style="display: flex; gap: 12px; margin-bottom: 12px; align-items: center; flex-wrap: wrap;">
<label class="text-muted-sm">Level:</label>
<select id="error-log-level" style="padding: 6px 10px; border-radius: 6px; border: 1px solid var(--border); background: var(--bg); color: var(--fg); font-size: 0.85rem;">
<option value="">All</option>
<option value="ERR">Errors</option>
<option value="WARN">Warnings</option>
<option value="INFO">Info</option>
<option value="DEBUG">Debug</option>
</select>
<label class="text-muted-sm">Context:</label>
<select id="error-log-context" style="padding: 6px 10px; border-radius: 6px; border: 1px solid var(--border); background: var(--bg); color: var(--fg); font-size: 0.85rem; max-width: 220px;">
<option value="">All</option>
</select>
<label class="text-muted-sm" style="margin-left: 8px;">Search:</label>
<input id="error-log-search" type="search" placeholder="message / stack / ip" style="padding: 5px 8px; border-radius: 6px; border: 1px solid var(--border); background: var(--bg); color: var(--fg); font-size: 0.82rem; min-width: 180px;">
<label class="text-muted-sm" style="margin-left: 8px;">Since:</label>
<input id="error-log-since" type="datetime-local" style="padding: 5px 8px; border-radius: 6px; border: 1px solid var(--border); background: var(--bg); color: var(--fg); font-size: 0.82rem;">
<label class="text-muted-sm">Until:</label>
<input id="error-log-until" type="datetime-local" style="padding: 5px 8px; border-radius: 6px; border: 1px solid var(--border); background: var(--bg); color: var(--fg); font-size: 0.82rem;">
<button id="error-log-refresh" class="btn-sm">\u{1F504} Refresh</button>
<span style="flex: 1;"></span>
<button id="error-log-clear" style="padding: 6px 12px; font-size: 0.8rem; color: var(--bad-fg); border-color: var(--bad-fg);">\u{1F5D1}\uFE0F Clear Log</button>
</div>
<div id="error-log-container" class="scroll-container">
<div class="panel-empty"><span class="brand-spinner"></span> Loading error logs...</div>
</div>
<div style="margin-top: 12px; text-align: center;">
<button id="error-log-load-more" style="display: none; padding: 6px 16px; font-size: 0.8rem;">Load More</button>
</div>
<div style="margin-top: 8px; font-size: 0.78rem; color: var(--muted); text-align: right;">
<span id="error-log-total"></span>
</div>
<div class="weather-modal-buttons modal-footer-bar">
<button id="error-log-close">Close</button>
</div>
</div>
</div>`);const x=document.getElementById("error-log-modal"),B=document.getElementById("view-error-logs"),A=document.getElementById("error-log-refresh"),C=document.getElementById("error-log-clear"),M=document.getElementById("error-log-close"),P=document.getElementById("error-log-level"),z=document.getElementById("error-log-context"),N=document.getElementById("error-log-search"),f=document.getElementById("error-log-since"),L=document.getElementById("error-log-until"),w=document.getElementById("error-log-container"),$=document.getElementById("error-log-load-more"),k=document.getElementById("error-log-total"),T=50;let E=0,I=null,j=0,H=[];function R(h){if(!h)return null;const s=new Date(h);return isNaN(s.getTime())?null:s.toISOString()}async function D(){try{const h=await fetch("/api/v1/error-logs/contexts");if(!h.ok)return;const s=await h.json();if(!s.success||!Array.isArray(s.contexts))return;H=s.contexts;const c=z.value;z.innerHTML='<option value="">All</option>';for(const l of s.contexts){const m=document.createElement("option");m.value=l.name,m.textContent=`${l.name} (${l.count})`,z.appendChild(m)}c&&s.contexts.some(l=>l.name===c)&&(z.value=c)}catch{}}function O(){const h=new URLSearchParams;h.set("limit",String(T)),h.set("offset",String(E)),P.value&&h.set("level",P.value),z.value&&h.set("context",z.value);const s=R(f.value),c=R(L.value);s&&h.set("since",s),c&&h.set("until",c);const l=(N.value||"").trim();return l&&h.set("search",l),h}async function p(h){try{h?(I&&I.abort(),I=new AbortController):(I&&I.abort(),I=new AbortController,E=0,j++,w.innerHTML='<div class="panel-empty"><span class="brand-spinner"></span> Loading...</div>');const s=j,c=O(),l=await fetch("/api/v1/error-logs?"+c.toString(),{signal:I.signal});if(!l.ok){w.innerHTML=`<div class="panel-empty" style="color: var(--bad-fg);">Failed: HTTP ${l.status}</div>`,$.style.display="none",k.textContent="";return}const m=await l.json();if(!m.success){w.innerHTML=`<div class="panel-empty" style="color: var(--bad-fg);">Failed: ${escapeHtml(m.error||"unknown")}</div>`,$.style.display="none",k.textContent="";return}if(!h&&s!==j)return;const u=Array.isArray(m.logs)?m.logs:[];if(u.length===0&&!h){const e=m.filters&&(m.filters.level||m.filters.context||m.filters.search||m.filters.since||m.filters.until)?"No error log entries match your filters.":"\u2705 No errors logged! Everything is working smoothly.";w.innerHTML=`<div class="panel-empty"><span class="empty-icon">\u{1F4CB}</span>${escapeHtml(e)}</div>`,$.style.display="none",k.textContent=m.total?`${m.total} total`:"";return}let t="";h||(t='<table style="width: 100%; border-collapse: collapse; font-size: 0.82rem;">',t+='<tr style="border-bottom: 1px solid var(--border); color: var(--muted);">',t+='<th style="padding: 6px; text-align: left; width: 160px;">When</th>',t+='<th style="padding: 6px; text-align: left; width: 80px;">Level</th>',t+='<th style="padding: 6px; text-align: left; width: 140px;">Context</th>',t+='<th style="padding: 6px; text-align: left;">Message</th>',t+='<th style="padding: 6px; text-align: left; width: 110px;">IP</th>',t+="</tr>");for(const e of u){const a=(e.level||"?").toUpperCase(),o=a==="ERR"?"var(--bad-fg)":a==="WARN"?"var(--warn-fg, #f0c674)":"var(--muted)",r=e.timestamp?new Date(e.timestamp).toLocaleString():"\u2014",n=e.context||"\u2014",i=(e.error||"").split(`
`)[0],d=e.request&&e.request.ip||"";t+='<tr style="border-bottom: 1px solid var(--border); cursor: pointer;" class="error-log-row">',t+=`<td style="padding: 6px; color: var(--muted);" title="${escapeHtml(e.timestamp||"")}">${escapeHtml(r)}</td>`,t+=`<td style="padding: 6px;"><span style="color: ${o}; font-weight: 600;">${escapeHtml(a)}</span></td>`,t+=`<td style="padding: 6px; font-family: monospace; font-size: 0.78rem;">${escapeHtml(n)}</td>`,t+=`<td style="padding: 6px;">${escapeHtml(i)}</td>`,t+=`<td style="padding: 6px; font-family: monospace; font-size: 0.78rem;">${escapeHtml(d)}</td>`,t+="</tr>",e.detail&&(t+=`<tr class="error-log-detail" style="display: none;"><td colspan="5" style="padding: 6px 6px 10px; font-size: 0.78rem; color: var(--muted);"><pre style="margin: 0; white-space: pre-wrap; font-family: monospace; max-height: 320px; overflow: auto;">${escapeHtml(e.detail)}</pre></td></tr>`)}if(!h)t+="</table>",w.innerHTML=t;else{const e=w.querySelector("table");e&&e.insertAdjacentHTML("beforeend",t)}E+=u.length,$.style.display=m.hasMore?"":"none",k.textContent=`${m.total} total${m.hasMore?" (showing "+E+")":""}`,w.querySelectorAll(".error-log-row").forEach(e=>{e.dataset.wired||(e.dataset.wired="true",e.addEventListener("click",()=>{const a=e.nextElementSibling;a&&a.classList.contains("error-log-detail")&&(a.style.display=a.style.display==="none"?"":"none")}))})}catch(s){if(s&&s.name==="AbortError")return;w.innerHTML=`<div class="panel-empty" style="color: var(--bad-fg);">Failed: ${escapeHtml(s.message)}</div>`,k.textContent=""}}async function v(){if(confirm("Clear the entire error log? This cannot be undone."))try{const s=await(await secureFetch("/api/v1/error-logs",{method:"DELETE",headers:{"content-type":"application/json"},body:JSON.stringify({confirm:"CLEAR"})})).json();s.success?(await D(),p(!1),showNotification("\u2705 Error logs cleared","success",3e3)):showNotification("\u274C "+(s.error||"Clear failed"),"error",4e3)}catch(h){showNotification("\u274C "+h.message,"error",4e3)}}let b;function y(){P?.addEventListener("change",()=>p(!1)),z?.addEventListener("change",()=>p(!1)),N?.addEventListener("input",()=>{clearTimeout(b),b=setTimeout(()=>p(!1),250)});let h;[f,L].forEach(s=>{s?.addEventListener("change",()=>{clearTimeout(h),h=setTimeout(()=>p(!1),250)})}),A?.addEventListener("click",()=>p(!1)),$?.addEventListener("click",()=>p(!0)),C?.addEventListener("click",v),wireModal(x,M)}B?.addEventListener("click",async()=>{x?.classList.add("show"),await D(),p(!1)}),y()})(),(function(){injectModal("container-logs-modal",`<div id="container-logs-modal" class="weather-modal" style="z-index: 1001;">
<div class="weather-modal-content" style="min-width: 900px; max-width: 95vw; height: 80vh; display: flex; flex-direction: column;">
<div class="logs-header" style="display: flex; justify-content: space-between; align-items: center; padding-bottom: 12px; border-bottom: 1px solid var(--border); margin-bottom: 12px;">
<div>
@@ -609,14 +648,14 @@ Try refreshing in a moment if you see a certificate error.`,"warning",1e4),!1}};
<button id="cl-close-btn" class="btn-secondary">Close</button>
</div>
</div>
</div>`);const f=document.getElementById("container-logs-modal"),I=document.getElementById("cl-container-select"),A=document.getElementById("cl-log-content"),E=document.getElementById("cl-log-search"),M=document.getElementById("cl-log-tail"),P=document.getElementById("cl-refresh"),z=document.getElementById("cl-stream"),D=document.getElementById("cl-download"),v=document.getElementById("cl-clear-search"),B=document.getElementById("cl-close"),x=document.getElementById("cl-close-btn"),$=document.getElementById("cl-stream-status"),k=document.getElementById("cl-stream-indicator"),T=document.getElementById("cl-stream-text"),S=document.getElementById("cl-line-count"),L=document.getElementById("cl-filter-count"),j=document.getElementById("cl-image"),C=document.getElementById("cl-status"),N=document.getElementById("cl-created");let R=null,U=[],u=[],m=null,h=!1,g=null;function H(s){if(!s)return"-";const l=new Date(s);return isNaN(l.getTime())?s:l.toLocaleString()}function r(s){if(!s)return"";const l=document.createElement("div");return l.textContent=s,l.innerHTML}function c(s,l){const p=s.stream==="stderr"?"log-stderr":"log-stdout",w=s.stream==="stderr"?"\u26A0\uFE0F":"\u{1F4E4}";return`
<div class="log-entry ${p}" data-index="${l}" style="padding: 4px 8px; border-bottom: 1px solid #333; display: flex; gap: 8px;">
<span class="log-line-num" style="color: #666; min-width: 40px; text-align: right; user-select: none;">${l+1}</span>
<span class="log-stream-icon" style="color: ${s.stream==="stderr"?"#f59e0b":"#22c55e"};">${w}</span>
<span class="log-text" style="flex: 1; white-space: pre-wrap; word-break: break-all; color: #e5e5e5;">${r(s.text)}</span>
</div>`);const x=document.getElementById("container-logs-modal"),B=document.getElementById("cl-container-select"),A=document.getElementById("cl-log-content"),C=document.getElementById("cl-log-search"),M=document.getElementById("cl-log-tail"),P=document.getElementById("cl-refresh"),z=document.getElementById("cl-stream"),N=document.getElementById("cl-download"),f=document.getElementById("cl-clear-search"),L=document.getElementById("cl-close"),w=document.getElementById("cl-close-btn"),$=document.getElementById("cl-stream-status"),k=document.getElementById("cl-stream-indicator"),T=document.getElementById("cl-stream-text"),E=document.getElementById("cl-line-count"),I=document.getElementById("cl-filter-count"),j=document.getElementById("cl-image"),H=document.getElementById("cl-status"),R=document.getElementById("cl-created");let D=null,O=[],p=[],v=null,b=!1,y=null;function h(i){if(!i)return"-";const d=new Date(i);return isNaN(d.getTime())?i:d.toLocaleString()}function s(i){if(!i)return"";const d=document.createElement("div");return d.textContent=i,d.innerHTML}function c(i,d){const g=i.stream==="stderr"?"log-stderr":"log-stdout",S=i.stream==="stderr"?"\u26A0\uFE0F":"\u{1F4E4}";return`
<div class="log-entry ${g}" data-index="${d}" style="padding: 4px 8px; border-bottom: 1px solid #333; display: flex; gap: 8px;">
<span class="log-line-num" style="color: #666; min-width: 40px; text-align: right; user-select: none;">${d+1}</span>
<span class="log-stream-icon" style="color: ${i.stream==="stderr"?"#f59e0b":"#22c55e"};">${S}</span>
<span class="log-text" style="flex: 1; white-space: pre-wrap; word-break: break-all; color: #e5e5e5;">${s(i.text)}</span>
</div>
`}function d(s,l=""){if(!s||s.length===0){A.innerHTML='<div class="logs-loading" style="color: var(--muted); text-align: center; padding: 40px;">No logs available</div>',S.textContent="0 lines",L.textContent="0 filtered";return}if(U=s,u=l?s.filter(p=>p.text&&p.text.toLowerCase().includes(l.toLowerCase())):s,S.textContent=`${s.length} lines`,L.textContent=l?`${u.length} of ${s.length} shown`:`${s.length} shown`,u.length===0){A.innerHTML=`<div class="logs-loading" style="color: var(--muted); text-align: center; padding: 40px;">No logs match "${r(l)}"</div>`;return}A.innerHTML=u.map((p,w)=>c(p,w)).join(""),A.scrollTop=A.scrollHeight}async function b(){try{const l=(await getJSON("/api/v1/logs/containers")).containers||[],p=I.value;I.innerHTML='<option value="">Select a container...</option>',l.forEach(w=>{const O=document.createElement("option");O.value=w.id,O.textContent=`${w.name} (${w.image.split(":")[0]}) - ${w.status}`,O.dataset.name=w.name,O.dataset.image=w.image,O.dataset.status=w.status,O.dataset.created=w.created,I.appendChild(O)}),p&&I.querySelector(`option[value="${p}"]`)&&(I.value=p,y(p))}catch(s){console.error("Failed to load containers:",s)}}function y(s){const l=I.querySelector(`option[value="${s}"]`);l&&(j.textContent=l.dataset.image||"-",C.textContent=l.dataset.status||"-",C.style.color=l.dataset.status==="running"?"var(--ok-fg, #4ade80)":"var(--bad-fg, #ef4444)",N.textContent=H(l.dataset.created))}async function t(){const s=I.value;if(!s){A.innerHTML='<div class="logs-loading" style="color: var(--muted); text-align: center; padding: 40px;">Select a container to view logs</div>';return}a(),R=s,y(s);const l=M.value,p=E.value.trim();A.innerHTML='<div class="logs-loading" style="color: var(--muted); text-align: center; padding: 40px;">Loading logs...</div>';try{const w=`/api/v1/logs/container/${s}${l!=="all"?`?tail=${l}`:""}`,O=await getJSON(w);O.logs&&O.logs.length>0?d(O.logs,p):(A.innerHTML='<div class="logs-loading" style="color: var(--muted); text-align: center; padding: 40px;">No logs found for this container</div>',S.textContent="0 lines",L.textContent="0 filtered")}catch(w){A.innerHTML=`<div class="logs-loading" style="color: var(--bad-fg, #ef4444); text-align: center; padding: 40px;">Error loading logs: ${r(w.message)}</div>`}}function e(){const s=I.value;if(!s)return;a(),h=!0,z.textContent="\u23F9 Stop",$.style.display="flex",k.textContent="\u{1F7E2}",T.textContent="Connecting...";const l=`/api/v1/logs/stream/${s}`;m=new EventSource(l),m.onopen=()=>{k.textContent="\u{1F7E2}",T.textContent="Connected - streaming logs"},m.onmessage=p=>{try{const w=JSON.parse(p.data);if(w.error){k.textContent="\u{1F534}",T.textContent=`Error: ${w.error}`;return}U.push(w),u.push(w),S.textContent=`${U.length} lines`,L.textContent=`${u.length} shown`;const O=E.value.trim();if(!O||w.text&&w.text.toLowerCase().includes(O.toLowerCase())){const _=document.createElement("div");_.innerHTML=c(w,u.length-1);const F=_.firstElementChild;F.style.background="#1a3a1a",A.appendChild(F),A.scrollTop=A.scrollHeight}}catch(w){console.error("Error parsing log:",w)}},m.onerror=()=>{k.textContent="\u{1F534}",T.textContent="Disconnected",h=!1,z.textContent="\u25B6 Stream"},f._eventSource=m}function a(){m&&(m.close(),m=null),f._eventSource&&(f._eventSource.close(),f._eventSource=null),h=!1,z.textContent="\u25B6 Stream",$.style.display="none"}function o(){if(!U||U.length===0){showNotification("No logs to download","error");return}const s=I.querySelector(`option[value="${R}"]`)?.dataset.name||R,l=new Date().toISOString().replace(/[:.]/g,"-"),p=`${s}-logs-${l}.txt`,w=U.map(q=>{const J=q.timestamp||"",X=q.stream==="stderr"?"[ERR]":"[OUT]";return`${J?J+" ":""}${X} ${q.text}`}).join(`
`),O=new Blob([w],{type:"text/plain"}),_=URL.createObjectURL(O),F=document.createElement("a");F.href=_,F.download=p,document.body.appendChild(F),F.click(),document.body.removeChild(F),URL.revokeObjectURL(_),showNotification(`Downloaded ${U.length} log lines`,"success")}I?.addEventListener("change",()=>{t()}),M?.addEventListener("change",()=>{t()}),P?.addEventListener("click",()=>{t()}),z?.addEventListener("click",()=>{h?a():e()}),D?.addEventListener("click",()=>{o()}),v?.addEventListener("click",()=>{E.value="",d(U,"")}),E?.addEventListener("input",()=>{clearTimeout(g),g=setTimeout(()=>{d(U,E.value.trim())},300)}),E?.addEventListener("keydown",s=>{s.key==="Escape"&&(E.value="",d(U,""))}),document.getElementById("view-container-logs")?.addEventListener("click",()=>{f.classList.add("show"),b()});function n(){a(),f.classList.remove("show")}B?.addEventListener("click",n),x?.addEventListener("click",n),document.addEventListener("keydown",s=>{s.key==="Escape"&&f.classList.contains("show")&&n()}),f.addEventListener("click",s=>{s.target===f&&n()}),window.openContainerLogsModal=function(s,l){f.classList.add("show"),b().then(()=>{const p=Array.from(I.options).find(w=>w.value===s||w.dataset.name===l);p?(I.value=p.value,y(p.value),t()):s?(R=s,j.textContent=l||s,C.textContent="-",N.textContent="-",t()):A.innerHTML='<div class="logs-loading" style="color: var(--muted); text-align: center; padding: 40px;">Select a container to view logs</div>'})}})(),(function(){injectModal("snapshot-modal",`<div id="snapshot-modal" class="weather-modal">
`}function l(i,d=""){if(!i||i.length===0){A.innerHTML='<div class="logs-loading" style="color: var(--muted); text-align: center; padding: 40px;">No logs available</div>',E.textContent="0 lines",I.textContent="0 filtered";return}if(O=i,p=d?i.filter(g=>g.text&&g.text.toLowerCase().includes(d.toLowerCase())):i,E.textContent=`${i.length} lines`,I.textContent=d?`${p.length} of ${i.length} shown`:`${i.length} shown`,p.length===0){A.innerHTML=`<div class="logs-loading" style="color: var(--muted); text-align: center; padding: 40px;">No logs match "${s(d)}"</div>`;return}A.innerHTML=p.map((g,S)=>c(g,S)).join(""),A.scrollTop=A.scrollHeight}async function m(){try{const d=(await getJSON("/api/v1/logs/containers")).containers||[],g=B.value;B.innerHTML='<option value="">Select a container...</option>',d.forEach(S=>{const U=document.createElement("option");U.value=S.id,U.textContent=`${S.name} (${S.image.split(":")[0]}) - ${S.status}`,U.dataset.name=S.name,U.dataset.image=S.image,U.dataset.status=S.status,U.dataset.created=S.created,B.appendChild(U)}),g&&B.querySelector(`option[value="${g}"]`)&&(B.value=g,u(g))}catch(i){console.error("Failed to load containers:",i)}}function u(i){const d=B.querySelector(`option[value="${i}"]`);d&&(j.textContent=d.dataset.image||"-",H.textContent=d.dataset.status||"-",H.style.color=d.dataset.status==="running"?"var(--ok-fg, #4ade80)":"var(--bad-fg, #ef4444)",R.textContent=h(d.dataset.created))}async function t(){const i=B.value;if(!i){A.innerHTML='<div class="logs-loading" style="color: var(--muted); text-align: center; padding: 40px;">Select a container to view logs</div>';return}a(),D=i,u(i);const d=M.value,g=C.value.trim();A.innerHTML='<div class="logs-loading" style="color: var(--muted); text-align: center; padding: 40px;">Loading logs...</div>';try{const S=`/api/v1/logs/container/${i}${d!=="all"?`?tail=${d}`:""}`,U=await getJSON(S);U.logs&&U.logs.length>0?l(U.logs,g):(A.innerHTML='<div class="logs-loading" style="color: var(--muted); text-align: center; padding: 40px;">No logs found for this container</div>',E.textContent="0 lines",I.textContent="0 filtered")}catch(S){A.innerHTML=`<div class="logs-loading" style="color: var(--bad-fg, #ef4444); text-align: center; padding: 40px;">Error loading logs: ${s(S.message)}</div>`}}function e(){const i=B.value;if(!i)return;a(),b=!0,z.textContent="\u23F9 Stop",$.style.display="flex",k.textContent="\u{1F7E2}",T.textContent="Connecting...";const d=`/api/v1/logs/stream/${i}`;v=new EventSource(d),v.onopen=()=>{k.textContent="\u{1F7E2}",T.textContent="Connected - streaming logs"},v.onmessage=g=>{try{const S=JSON.parse(g.data);if(S.error){k.textContent="\u{1F534}",T.textContent=`Error: ${S.error}`;return}O.push(S),p.push(S),E.textContent=`${O.length} lines`,I.textContent=`${p.length} shown`;const U=C.value.trim();if(!U||S.text&&S.text.toLowerCase().includes(U.toLowerCase())){const q=document.createElement("div");q.innerHTML=c(S,p.length-1);const F=q.firstElementChild;F.style.background="#1a3a1a",A.appendChild(F),A.scrollTop=A.scrollHeight}}catch(S){console.error("Error parsing log:",S)}},v.onerror=()=>{k.textContent="\u{1F534}",T.textContent="Disconnected",b=!1,z.textContent="\u25B6 Stream"},x._eventSource=v}function a(){v&&(v.close(),v=null),x._eventSource&&(x._eventSource.close(),x._eventSource=null),b=!1,z.textContent="\u25B6 Stream",$.style.display="none"}function o(){if(!O||O.length===0){showNotification("No logs to download","error");return}const i=B.querySelector(`option[value="${D}"]`)?.dataset.name||D,d=new Date().toISOString().replace(/[:.]/g,"-"),g=`${i}-logs-${d}.txt`,S=O.map(_=>{const J=_.timestamp||"",X=_.stream==="stderr"?"[ERR]":"[OUT]";return`${J?J+" ":""}${X} ${_.text}`}).join(`
`),U=new Blob([S],{type:"text/plain"}),q=URL.createObjectURL(U),F=document.createElement("a");F.href=q,F.download=g,document.body.appendChild(F),F.click(),document.body.removeChild(F),URL.revokeObjectURL(q),showNotification(`Downloaded ${O.length} log lines`,"success")}B?.addEventListener("change",()=>{t()}),M?.addEventListener("change",()=>{t()}),P?.addEventListener("click",()=>{t()}),z?.addEventListener("click",()=>{b?a():e()}),N?.addEventListener("click",()=>{o()}),f?.addEventListener("click",()=>{C.value="",l(O,"")}),C?.addEventListener("input",()=>{clearTimeout(y),y=setTimeout(()=>{l(O,C.value.trim())},300)}),C?.addEventListener("keydown",i=>{i.key==="Escape"&&(C.value="",l(O,""))}),document.getElementById("view-container-logs")?.addEventListener("click",()=>{x.classList.add("show"),m()});function n(){a(),x.classList.remove("show")}L?.addEventListener("click",n),w?.addEventListener("click",n),document.addEventListener("keydown",i=>{i.key==="Escape"&&x.classList.contains("show")&&n()}),x.addEventListener("click",i=>{i.target===x&&n()}),window.openContainerLogsModal=function(i,d){x.classList.add("show"),m().then(()=>{const g=Array.from(B.options).find(S=>S.value===i||S.dataset.name===d);g?(B.value=g.value,u(g.value),t()):i?(D=i,j.textContent=d||i,H.textContent="-",R.textContent="-",t()):A.innerHTML='<div class="logs-loading" style="color: var(--muted); text-align: center; padding: 40px;">Select a container to view logs</div>'})}})(),(function(){injectModal("snapshot-modal",`<div id="snapshot-modal" class="weather-modal">
<div class="weather-modal-content" style="min-width: 700px; max-width: 850px;">
<h3>\u{1F4BE} Container Snapshots</h3>
<p class="modal-subtitle">
@@ -670,7 +709,7 @@ Try refreshing in a moment if you see a certificate error.`,"warning",1e4),!1}};
<button id="snapshot-close">Close</button>
</div>
</div>
</div>`);const f=document.getElementById("snapshot-modal"),I=document.getElementById("snapshot-btn"),A=document.getElementById("snapshot-close"),E=document.getElementById("snapshot-container-select"),M=document.getElementById("snapshot-details"),P=document.getElementById("snapshot-create-btn"),z=document.getElementById("snapshot-create-status");let D=null;async function v(){try{const S=await(await fetch("/api/v1/containers")).json();if(!S.success||!S.containers)return;E.innerHTML='<option value="">-- Select a container --</option>';for(const L of S.containers){const j=document.createElement("option");j.value=L.id,j.textContent=`${L.name||L.id} (${L.image||"unknown"})`,j.dataset.name=L.name,j.dataset.image=L.image,j.dataset.status=L.status,j.dataset.created=L.created,E.appendChild(j)}}catch(T){console.error("Failed to load containers:",T)}}function B(T){if(!T||!T.value){M.style.display="none",D=null;return}D=T.value,document.getElementById("snapshot-image").textContent=T.dataset.image||"-",document.getElementById("snapshot-status").textContent=T.dataset.status||"-",document.getElementById("snapshot-created").textContent=T.dataset.created?new Date(T.dataset.created*1e3).toLocaleString():"-",document.getElementById("snapshot-id").textContent=T.value.substring(0,12),M.style.display=""}async function x(){if(!D){z.textContent="Please select a container first",z.style.color="var(--bad-fg)";return}const T=document.getElementById("snapshot-name").value.trim();if(!T){z.textContent="Please enter a snapshot name",z.style.color="var(--bad-fg)";return}const S=document.getElementById("snapshot-leave-running").checked;P.disabled=!0,P.textContent="Creating...",z.textContent="";try{const j=await(await fetch(`/api/v1/containers/${encodeURIComponent(D)}/checkpoint`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:T,leaveRunning:S})})).json();j.success?(z.textContent=`\u2713 Snapshot "${T}" created successfully`,z.style.color="var(--ok-fg)",document.getElementById("snapshot-name").value=""):(z.textContent=`\u2717 Failed: ${j.error||"Unknown error"}`,z.style.color="var(--bad-fg)")}catch(L){z.textContent=`\u2717 Error: ${L.message}`,z.style.color="var(--bad-fg)"}finally{P.disabled=!1,P.textContent="\u{1F4BE} Create Snapshot"}}function $(){f.classList.add("show"),v()}function k(){f.classList.remove("show"),M.style.display="none",D=null,E.selectedIndex=0}I?.addEventListener("click",$),A?.addEventListener("click",k),wireModal(f,A),E?.addEventListener("change",T=>{const S=E.options[E.selectedIndex];B(S)}),P?.addEventListener("click",x),f?.querySelectorAll(".panel-tab").forEach(T=>{T.addEventListener("click",()=>{f.querySelectorAll(".panel-tab").forEach(S=>S.classList.remove("active")),f.querySelectorAll(".panel-section").forEach(S=>S.classList.remove("active")),T.classList.add("active"),f.querySelector(`#${T.dataset.panel}`).classList.add("active")})})})(),(function(){injectModal("arr-setup-modal",`<div id="arr-setup-modal" class="weather-modal">
</div>`);const x=document.getElementById("snapshot-modal"),B=document.getElementById("snapshot-btn"),A=document.getElementById("snapshot-close"),C=document.getElementById("snapshot-container-select"),M=document.getElementById("snapshot-details"),P=document.getElementById("snapshot-create-btn"),z=document.getElementById("snapshot-create-status");let N=null;async function f(){try{const E=await(await fetch("/api/v1/containers")).json();if(!E.success||!E.containers)return;C.innerHTML='<option value="">-- Select a container --</option>';for(const I of E.containers){const j=document.createElement("option");j.value=I.id,j.textContent=`${I.name||I.id} (${I.image||"unknown"})`,j.dataset.name=I.name,j.dataset.image=I.image,j.dataset.status=I.status,j.dataset.created=I.created,C.appendChild(j)}}catch(T){console.error("Failed to load containers:",T)}}function L(T){if(!T||!T.value){M.style.display="none",N=null;return}N=T.value,document.getElementById("snapshot-image").textContent=T.dataset.image||"-",document.getElementById("snapshot-status").textContent=T.dataset.status||"-",document.getElementById("snapshot-created").textContent=T.dataset.created?new Date(T.dataset.created*1e3).toLocaleString():"-",document.getElementById("snapshot-id").textContent=T.value.substring(0,12),M.style.display=""}async function w(){if(!N){z.textContent="Please select a container first",z.style.color="var(--bad-fg)";return}const T=document.getElementById("snapshot-name").value.trim();if(!T){z.textContent="Please enter a snapshot name",z.style.color="var(--bad-fg)";return}const E=document.getElementById("snapshot-leave-running").checked;P.disabled=!0,P.textContent="Creating...",z.textContent="";try{const j=await(await fetch(`/api/v1/containers/${encodeURIComponent(N)}/checkpoint`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:T,leaveRunning:E})})).json();j.success?(z.textContent=`\u2713 Snapshot "${T}" created successfully`,z.style.color="var(--ok-fg)",document.getElementById("snapshot-name").value=""):(z.textContent=`\u2717 Failed: ${j.error||"Unknown error"}`,z.style.color="var(--bad-fg)")}catch(I){z.textContent=`\u2717 Error: ${I.message}`,z.style.color="var(--bad-fg)"}finally{P.disabled=!1,P.textContent="\u{1F4BE} Create Snapshot"}}function $(){x.classList.add("show"),f()}function k(){x.classList.remove("show"),M.style.display="none",N=null,C.selectedIndex=0}B?.addEventListener("click",$),A?.addEventListener("click",k),wireModal(x,A),C?.addEventListener("change",T=>{const E=C.options[C.selectedIndex];L(E)}),P?.addEventListener("click",w),x?.querySelectorAll(".panel-tab").forEach(T=>{T.addEventListener("click",()=>{x.querySelectorAll(".panel-tab").forEach(E=>E.classList.remove("active")),x.querySelectorAll(".panel-section").forEach(E=>E.classList.remove("active")),T.classList.add("active"),x.querySelector(`#${T.dataset.panel}`).classList.add("active")})})})(),(function(){injectModal("arr-setup-modal",`<div id="arr-setup-modal" class="weather-modal">
<div class="weather-modal-content" style="min-width: 600px; max-width: 720px;">
<h3>\u{1F3AC} Smart Arr Connect</h3>
<p style="color: var(--muted); margin: 0 0 16px; font-size: 0.9rem;">
@@ -749,73 +788,73 @@ Try refreshing in a moment if you see a certificate error.`,"warning",1e4),!1}};
<button id="arr-setup-cancel">Close</button>
</div>
</div>
</div>`);const f=document.getElementById("arr-setup-modal"),I=document.getElementById("arr-setup-btn"),A=document.getElementById("arr-setup-cancel"),E=document.getElementById("smart-connect-btn"),M=document.getElementById("smart-phase-detect"),P=document.getElementById("smart-phase-credentials"),z=document.getElementById("smart-phase-progress"),D=document.getElementById("smart-phase-results"),v=document.getElementById("smart-detect-results"),B=document.getElementById("smart-credential-inputs"),x=document.getElementById("smart-progress-steps"),$=document.getElementById("smart-results-content"),k=document.getElementById("smart-plex-libraries"),T=document.getElementById("smart-retry-btn");let S=null;const L={plex:"\u{1F3AC}",radarr:"\u{1F3AC}",sonarr:"\u{1F4FA}",prowlarr:"\u{1F50D}",seerr:"\u{1F4CB}"},j={plex:"Plex",radarr:"Radarr (Movies)",sonarr:"Sonarr (TV)",prowlarr:"Prowlarr (Indexers)",seerr:"Seerr"};function C(g){M.style.display=g==="detect"?"block":"none",P.style.display=g==="credentials"?"block":"none",z.style.display=g==="progress"?"block":"none",D.style.display=g==="results"?"block":"none"}function N(g){const H={connected:{bg:"var(--ok-fg)",icon:"&#10003;",text:"Connected"},needs_key:{bg:"#f39c12",icon:"&#128273;",text:"Needs API Key"},not_found:{bg:"var(--muted)",icon:"&mdash;",text:"Not Found"},error:{bg:"var(--bad-fg)",icon:"&#10007;",text:"Error"}},r=H[g]||H.not_found;return`<span style="display: inline-flex; align-items: center; gap: 4px; padding: 2px 8px; border-radius: 4px; font-size: 0.75rem; background: color-mix(in srgb, ${r.bg} 20%, transparent); color: ${r.bg};">${r.icon} ${r.text}</span>`}async function R(){C("detect"),v.style.display="none";try{if(S=await(await fetch("/api/v1/arr/smart-detect")).json(),!S.success){v.innerHTML=`<div style="padding: 12px; color: var(--bad-fg);">Detection failed: ${escapeHtml(S.error)}</div>`,v.style.display="block";return}let H='<div style="display: flex; flex-direction: column; gap: 8px;">';for(const[c,d]of Object.entries(S.services)){const b=L[c]||"\u{1F4E6}",y=j[c]||c,t=d.source?`<span style="font-size: 0.7rem; color: var(--muted); padding: 1px 6px; background: var(--card-bg); border-radius: 3px;">${escapeHtml(d.source)}</span>`:"",e=d.version?`<span style="font-size: 0.7rem; color: var(--muted);">v${escapeHtml(d.version)}</span>`:"",a=(d.hasApiKey||d.hasToken)&&d.status==="connected"?'<span style="font-size: 0.7rem; color: var(--ok-fg);">Key saved</span>':"";H+=`<div style="display: flex; align-items: center; gap: 10px; padding: 10px 12px; background: var(--card-base); border-radius: 8px; border: 1px solid var(--border);">
<span style="font-size: 1.1rem;">${b}</span>
</div>`);const x=document.getElementById("arr-setup-modal"),B=document.getElementById("arr-setup-btn"),A=document.getElementById("arr-setup-cancel"),C=document.getElementById("smart-connect-btn"),M=document.getElementById("smart-phase-detect"),P=document.getElementById("smart-phase-credentials"),z=document.getElementById("smart-phase-progress"),N=document.getElementById("smart-phase-results"),f=document.getElementById("smart-detect-results"),L=document.getElementById("smart-credential-inputs"),w=document.getElementById("smart-progress-steps"),$=document.getElementById("smart-results-content"),k=document.getElementById("smart-plex-libraries"),T=document.getElementById("smart-retry-btn");let E=null;const I={plex:"\u{1F3AC}",radarr:"\u{1F3AC}",sonarr:"\u{1F4FA}",prowlarr:"\u{1F50D}",seerr:"\u{1F4CB}"},j={plex:"Plex",radarr:"Radarr (Movies)",sonarr:"Sonarr (TV)",prowlarr:"Prowlarr (Indexers)",seerr:"Seerr"};function H(y){M.style.display=y==="detect"?"block":"none",P.style.display=y==="credentials"?"block":"none",z.style.display=y==="progress"?"block":"none",N.style.display=y==="results"?"block":"none"}function R(y){const h={connected:{bg:"var(--ok-fg)",icon:"&#10003;",text:"Connected"},needs_key:{bg:"#f39c12",icon:"&#128273;",text:"Needs API Key"},not_found:{bg:"var(--muted)",icon:"&mdash;",text:"Not Found"},error:{bg:"var(--bad-fg)",icon:"&#10007;",text:"Error"}},s=h[y]||h.not_found;return`<span style="display: inline-flex; align-items: center; gap: 4px; padding: 2px 8px; border-radius: 4px; font-size: 0.75rem; background: color-mix(in srgb, ${s.bg} 20%, transparent); color: ${s.bg};">${s.icon} ${s.text}</span>`}async function D(){H("detect"),f.style.display="none";try{if(E=await(await fetch("/api/v1/arr/smart-detect")).json(),!E.success){f.innerHTML=`<div style="padding: 12px; color: var(--bad-fg);">Detection failed: ${escapeHtml(E.error)}</div>`,f.style.display="block";return}let h='<div style="display: flex; flex-direction: column; gap: 8px;">';for(const[c,l]of Object.entries(E.services)){const m=I[c]||"\u{1F4E6}",u=j[c]||c,t=l.source?`<span style="font-size: 0.7rem; color: var(--muted); padding: 1px 6px; background: var(--card-bg); border-radius: 3px;">${escapeHtml(l.source)}</span>`:"",e=l.version?`<span style="font-size: 0.7rem; color: var(--muted);">v${escapeHtml(l.version)}</span>`:"",a=(l.hasApiKey||l.hasToken)&&l.status==="connected"?'<span style="font-size: 0.7rem; color: var(--ok-fg);">Key saved</span>':"";h+=`<div style="display: flex; align-items: center; gap: 10px; padding: 10px 12px; background: var(--card-base); border-radius: 8px; border: 1px solid var(--border);">
<span style="font-size: 1.1rem;">${m}</span>
<div style="flex: 1;">
<div style="font-weight: 500; font-size: 0.9rem;">${y}</div>
<div style="font-weight: 500; font-size: 0.9rem;">${u}</div>
<div style="display: flex; gap: 6px; align-items: center; flex-wrap: wrap;">
${t} ${e} ${a}
</div>
</div>
${N(d.status)}
</div>`}H+="</div>";const r=S.summary;H+=`<div style="margin-top: 12px; padding: 10px; background: color-mix(in srgb, var(--accent) 8%, transparent); border-radius: 8px; font-size: 0.85rem;">
${escapeHtml(String(r.fullyConnected))}/${escapeHtml(String(r.totalDetected+(5-r.totalDetected)))} services detected &middot;
${escapeHtml(String(r.fullyConnected))} connected${r.needsApiKey>0?` &middot; <strong>${escapeHtml(String(r.needsApiKey))} needs API key</strong>`:""}
</div>`,v.innerHTML=H,v.style.display="block",U(S),setTimeout(()=>{C("credentials")},800)}catch(g){v.innerHTML=`<div style="padding: 12px; color: var(--bad-fg);">Error: ${escapeHtml(g.message)}</div>`,v.style.display="block"}}function U(g){let H="";const r=g.services,c=["radarr","sonarr","prowlarr"];for(const y of c){const t=r[y];if(!t||t.status==="not_found"&&!t.url)continue;const e=L[y],a=j[y],o=t.status==="connected";H+=`<div style="margin-bottom: 10px; padding: 12px; background: var(--card-base); border-radius: 8px; border: 1px solid ${o?"var(--ok-fg)":"var(--border)"};">
${R(l.status)}
</div>`}h+="</div>";const s=E.summary;h+=`<div style="margin-top: 12px; padding: 10px; background: color-mix(in srgb, var(--accent) 8%, transparent); border-radius: 8px; font-size: 0.85rem;">
${escapeHtml(String(s.fullyConnected))}/${escapeHtml(String(s.totalDetected+(5-s.totalDetected)))} services detected &middot;
${escapeHtml(String(s.fullyConnected))} connected${s.needsApiKey>0?` &middot; <strong>${escapeHtml(String(s.needsApiKey))} needs API key</strong>`:""}
</div>`,f.innerHTML=h,f.style.display="block",O(E),setTimeout(()=>{H("credentials")},800)}catch(y){f.innerHTML=`<div style="padding: 12px; color: var(--bad-fg);">Error: ${escapeHtml(y.message)}</div>`,f.style.display="block"}}function O(y){let h="";const s=y.services,c=["radarr","sonarr","prowlarr"];for(const u of c){const t=s[u];if(!t||t.status==="not_found"&&!t.url)continue;const e=I[u],a=j[u],o=t.status==="connected";h+=`<div style="margin-bottom: 10px; padding: 12px; background: var(--card-base); border-radius: 8px; border: 1px solid ${o?"var(--ok-fg)":"var(--border)"};">
<div style="display: flex; align-items: center; gap: 8px; margin-bottom: 8px;">
<span style="font-size: 1.1rem;">${e}</span>
<span style="font-weight: 500;">${a}</span>
<span id="smart-${y}-status" style="margin-left: auto; font-size: 0.75rem;">
<span id="smart-${u}-status" style="margin-left: auto; font-size: 0.75rem;">
${o?'<span style="color: var(--ok-fg);">&#10003; Connected</span>':""}
</span>
</div>
<div style="display: grid; grid-template-columns: 2fr 1fr; gap: 8px;">
<div>
<label style="font-size: 0.75rem; color: var(--muted);">URL:</label>
<input type="text" id="smart-${y}-url" value="${escapeHtml(t.url||"")}" placeholder="https://seedbox.com/${y}/"
<input type="text" id="smart-${u}-url" value="${escapeHtml(t.url||"")}" placeholder="https://seedbox.com/${u}/"
style="width: 100%; font-size: 0.85rem; padding: 6px 8px; background: var(--card-bg); color: var(--fg); border: 1px solid var(--border); border-radius: 4px;" />
</div>
<div>
<label style="font-size: 0.75rem; color: var(--muted);">API Key:</label>
<input type="password" id="smart-${y}-key" placeholder="${o?"(saved)":"Paste API key"}"
<input type="password" id="smart-${u}-key" placeholder="${o?"(saved)":"Paste API key"}"
style="width: 100%; font-size: 0.85rem; padding: 6px 8px; background: var(--card-bg); color: var(--fg); border: 1px solid var(--border); border-radius: 4px;" />
</div>
</div>
<button onclick="smartTestConnection('${y}')" style="margin-top: 8px; padding: 4px 12px; font-size: 0.75rem; cursor: pointer;">Test</button>
</div>`}const d=r.plex;if(d){const y=d.status==="connected";H+=`<div style="padding: 10px 12px; background: var(--card-base); border-radius: 8px; border: 1px solid ${y?"var(--ok-fg)":"var(--border)"}; margin-bottom: 10px;">
<button onclick="smartTestConnection('${u}')" style="margin-top: 8px; padding: 4px 12px; font-size: 0.75rem; cursor: pointer;">Test</button>
</div>`}const l=s.plex;if(l){const u=l.status==="connected";h+=`<div style="padding: 10px 12px; background: var(--card-base); border-radius: 8px; border: 1px solid ${u?"var(--ok-fg)":"var(--border)"}; margin-bottom: 10px;">
<div style="display: flex; align-items: center; gap: 8px;">
<span style="font-size: 1.1rem;">\u{1F3AC}</span>
<span style="font-weight: 500;">Plex</span>
${N(d.status)}
<span style="margin-left: auto; font-size: 0.75rem; color: var(--muted);">${escapeHtml(d.source||"")}</span>
${R(l.status)}
<span style="margin-left: auto; font-size: 0.75rem; color: var(--muted);">${escapeHtml(l.source||"")}</span>
</div>
</div>`}const b=r.seerr;if(b){const y=b.status==="connected";let t="";if(b.configuredServices){const e=b.configuredServices;t=`<div style="font-size: 0.75rem; color: var(--muted); margin-top: 4px;">
</div>`}const m=s.seerr;if(m){const u=m.status==="connected";let t="";if(m.configuredServices){const e=m.configuredServices;t=`<div style="font-size: 0.75rem; color: var(--muted); margin-top: 4px;">
Configured: ${e.radarr?"&#10003; Radarr":"&#10007; Radarr"} &middot;
${e.sonarr?"&#10003; Sonarr":"&#10007; Sonarr"} &middot;
${e.plex?"&#10003; Plex":"&#10007; Plex"}
</div>`}H+=`<div style="padding: 10px 12px; background: var(--card-base); border-radius: 8px; border: 1px solid ${y?"var(--ok-fg)":"var(--border)"};">
</div>`}h+=`<div style="padding: 10px 12px; background: var(--card-base); border-radius: 8px; border: 1px solid ${u?"var(--ok-fg)":"var(--border)"};">
<div style="display: flex; align-items: center; gap: 8px;">
<span style="font-size: 1.1rem;">\u{1F4CB}</span>
<span style="font-weight: 500;">Seerr</span>
${N(b.status)}
${R(m.status)}
</div>
${t}
</div>`}B.innerHTML=H}window.smartTestConnection=async function(g){const H=document.getElementById(`smart-${g}-url`),r=document.getElementById(`smart-${g}-key`),c=document.getElementById(`smart-${g}-status`),d=H?.value.trim(),b=r?.value.trim();if(!d||!b){c.innerHTML='<span style="color: var(--bad-fg);">Enter URL and API key</span>';return}c.innerHTML='<span class="brand-spinner"></span>';try{const t=await(await secureFetch("/api/v1/arr/test-connection",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({service:g,url:d,apiKey:b})})).json();t.success?c.innerHTML=`<span style="color: var(--ok-fg);">&#10003; ${escapeHtml(t.appName||"Connected")} v${escapeHtml(t.version||"")}</span>`:c.innerHTML=`<span style="color: var(--bad-fg);">&#10007; ${escapeHtml(t.error)}</span>`}catch(y){c.innerHTML=`<span style="color: var(--bad-fg);">&#10007; ${escapeHtml(y.message)}</span>`}};async function u(){C("progress"),x.innerHTML='<div style="text-align: center; padding: 20px;"><span class="brand-spinner"></span><div style="color: var(--muted); margin-top: 8px;">Connecting services...</div></div>';const g={};for(const r of["radarr","sonarr","prowlarr"]){const c=document.getElementById(`smart-${r}-url`)?.value.trim(),d=document.getElementById(`smart-${r}-key`)?.value.trim();d&&c?g[r]={apiKey:d,url:c}:d&&(g[r]={apiKey:d})}const H={services:Object.keys(g).length>0?g:void 0,configurePlex:document.getElementById("smart-opt-plex")?.checked,configureProwlarr:document.getElementById("smart-opt-prowlarr")?.checked,configureSeerr:document.getElementById("smart-opt-seerr")?.checked,saveCredentials:document.getElementById("smart-opt-save")?.checked};try{const c=await(await secureFetch("/api/v1/arr/smart-connect",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(H)})).json();let d="";for(const b of c.steps||[]){const y=b.status==="success"?'<span style="color: var(--ok-fg);">&#10003;</span>':'<span style="color: var(--bad-fg);">&#10007;</span>',t=b.status==="success"?"var(--muted)":"var(--bad-fg)";d+=`<div style="display: flex; align-items: center; gap: 8px; padding: 6px 10px; background: var(--card-base); border-radius: 6px; font-size: 0.85rem;">
${y}
<span>${escapeHtml(b.step)}</span>
<span style="margin-left: auto; font-size: 0.75rem; color: ${t};">${escapeHtml(b.details||"")}</span>
</div>`}x.innerHTML=d,setTimeout(()=>m(c),500)}catch(r){x.innerHTML=`<div style="padding: 12px; color: var(--bad-fg);">Connection error: ${escapeHtml(r.message)}</div>`}}function m(g){C("results");const H=g.summary||{},r=H.failed===0&&H.succeeded>0,c=r?"var(--ok-fg)":"#f39c12",d=r?"&#10003;":"&#9888;",b=r?"All Connected!":`${escapeHtml(String(H.succeeded))}/${escapeHtml(String(H.totalSteps))} Steps Succeeded`;let y=`<div style="text-align: center; padding: 16px; background: color-mix(in srgb, ${c} 12%, transparent); border-radius: 10px; border: 1px solid ${c}; margin-bottom: 12px;">
<div style="font-size: 1.5rem; color: ${c};">${d}</div>
<div style="font-size: 1.1rem; font-weight: 600; color: ${c};">${b}</div>
<div style="font-size: 0.85rem; color: var(--muted); margin-top: 4px;">${escapeHtml(String(H.succeeded))} succeeded, ${escapeHtml(String(H.failed))} failed</div>
</div>`;y+='<div style="display: flex; flex-direction: column; gap: 4px;">';for(const t of g.steps||[]){const e=t.status==="success"?'<span style="color: var(--ok-fg);">&#10003;</span>':'<span style="color: var(--bad-fg);">&#10007;</span>';y+=`<div style="display: flex; align-items: center; gap: 8px; padding: 4px 8px; font-size: 0.8rem;">
</div>`}L.innerHTML=h}window.smartTestConnection=async function(y){const h=document.getElementById(`smart-${y}-url`),s=document.getElementById(`smart-${y}-key`),c=document.getElementById(`smart-${y}-status`),l=h?.value.trim(),m=s?.value.trim();if(!l||!m){c.innerHTML='<span style="color: var(--bad-fg);">Enter URL and API key</span>';return}c.innerHTML='<span class="brand-spinner"></span>';try{const t=await(await secureFetch("/api/v1/arr/test-connection",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({service:y,url:l,apiKey:m})})).json();t.success?c.innerHTML=`<span style="color: var(--ok-fg);">&#10003; ${escapeHtml(t.appName||"Connected")} v${escapeHtml(t.version||"")}</span>`:c.innerHTML=`<span style="color: var(--bad-fg);">&#10007; ${escapeHtml(t.error)}</span>`}catch(u){c.innerHTML=`<span style="color: var(--bad-fg);">&#10007; ${escapeHtml(u.message)}</span>`}};async function p(){H("progress"),w.innerHTML='<div style="text-align: center; padding: 20px;"><span class="brand-spinner"></span><div style="color: var(--muted); margin-top: 8px;">Connecting services...</div></div>';const y={};for(const s of["radarr","sonarr","prowlarr"]){const c=document.getElementById(`smart-${s}-url`)?.value.trim(),l=document.getElementById(`smart-${s}-key`)?.value.trim();l&&c?y[s]={apiKey:l,url:c}:l&&(y[s]={apiKey:l})}const h={services:Object.keys(y).length>0?y:void 0,configurePlex:document.getElementById("smart-opt-plex")?.checked,configureProwlarr:document.getElementById("smart-opt-prowlarr")?.checked,configureSeerr:document.getElementById("smart-opt-seerr")?.checked,saveCredentials:document.getElementById("smart-opt-save")?.checked};try{const c=await(await secureFetch("/api/v1/arr/smart-connect",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(h)})).json();let l="";for(const m of c.steps||[]){const u=m.status==="success"?'<span style="color: var(--ok-fg);">&#10003;</span>':'<span style="color: var(--bad-fg);">&#10007;</span>',t=m.status==="success"?"var(--muted)":"var(--bad-fg)";l+=`<div style="display: flex; align-items: center; gap: 8px; padding: 6px 10px; background: var(--card-base); border-radius: 6px; font-size: 0.85rem;">
${u}
<span>${escapeHtml(m.step)}</span>
<span style="margin-left: auto; font-size: 0.75rem; color: ${t};">${escapeHtml(m.details||"")}</span>
</div>`}w.innerHTML=l,setTimeout(()=>v(c),500)}catch(s){w.innerHTML=`<div style="padding: 12px; color: var(--bad-fg);">Connection error: ${escapeHtml(s.message)}</div>`}}function v(y){H("results");const h=y.summary||{},s=h.failed===0&&h.succeeded>0,c=s?"var(--ok-fg)":"#f39c12",l=s?"&#10003;":"&#9888;",m=s?"All Connected!":`${escapeHtml(String(h.succeeded))}/${escapeHtml(String(h.totalSteps))} Steps Succeeded`;let u=`<div style="text-align: center; padding: 16px; background: color-mix(in srgb, ${c} 12%, transparent); border-radius: 10px; border: 1px solid ${c}; margin-bottom: 12px;">
<div style="font-size: 1.5rem; color: ${c};">${l}</div>
<div style="font-size: 1.1rem; font-weight: 600; color: ${c};">${m}</div>
<div style="font-size: 0.85rem; color: var(--muted); margin-top: 4px;">${escapeHtml(String(h.succeeded))} succeeded, ${escapeHtml(String(h.failed))} failed</div>
</div>`;u+='<div style="display: flex; flex-direction: column; gap: 4px;">';for(const t of y.steps||[]){const e=t.status==="success"?'<span style="color: var(--ok-fg);">&#10003;</span>':'<span style="color: var(--bad-fg);">&#10007;</span>';u+=`<div style="display: flex; align-items: center; gap: 8px; padding: 4px 8px; font-size: 0.8rem;">
${e} ${escapeHtml(t.step)} <span style="margin-left: auto; color: var(--muted); font-size: 0.75rem;">${escapeHtml(t.details||"")}</span>
</div>`}y+="</div>",$.innerHTML=y,T.style.display=H.failed>0?"block":"none",g.steps?.some(t=>t.step.includes("Plex")&&t.status==="success")&&h()}async function h(){try{const H=await(await fetch("/api/v1/plex/libraries")).json();if(H.success&&H.libraries?.length>0){let r=`<div style="padding: 12px; background: var(--card-base); border-radius: 8px; border: 1px solid var(--border);">
<h4 style="margin: 0 0 8px; font-size: 0.85rem; color: var(--accent);">\u{1F3AC} ${escapeHtml(H.serverName)} Libraries</h4>
<div style="display: flex; flex-wrap: wrap; gap: 8px;">`;for(const c of H.libraries){const d=c.type==="movie"?"\u{1F3AC}":c.type==="show"?"\u{1F4FA}":"\u{1F3B5}";r+=`<div style="padding: 8px 12px; background: var(--card-bg); border-radius: 6px; font-size: 0.85rem;">
${d} <strong>${escapeHtml(c.title)}</strong>
</div>`}u+="</div>",$.innerHTML=u,T.style.display=h.failed>0?"block":"none",y.steps?.some(t=>t.step.includes("Plex")&&t.status==="success")&&b()}async function b(){try{const h=await(await fetch("/api/v1/plex/libraries")).json();if(h.success&&h.libraries?.length>0){let s=`<div style="padding: 12px; background: var(--card-base); border-radius: 8px; border: 1px solid var(--border);">
<h4 style="margin: 0 0 8px; font-size: 0.85rem; color: var(--accent);">\u{1F3AC} ${escapeHtml(h.serverName)} Libraries</h4>
<div style="display: flex; flex-wrap: wrap; gap: 8px;">`;for(const c of h.libraries){const l=c.type==="movie"?"\u{1F3AC}":c.type==="show"?"\u{1F4FA}":"\u{1F3B5}";s+=`<div style="padding: 8px 12px; background: var(--card-bg); border-radius: 6px; font-size: 0.85rem;">
${l} <strong>${escapeHtml(c.title)}</strong>
<span style="color: var(--muted); font-size: 0.75rem;">${escapeHtml(String(c.count))} items</span>
</div>`}r+="</div></div>",k.innerHTML=r,k.style.display="block"}}catch{}}I?.addEventListener("click",()=>{f.classList.add("show"),k.style.display="none",R()}),wireModal(f,A),E?.addEventListener("click",u),T?.addEventListener("click",u)})(),(function(){const f=new ErrorHandler;injectModal("notifications-modal",`<div id="notifications-modal" class="weather-modal">
</div>`}s+="</div></div>",k.innerHTML=s,k.style.display="block"}}catch{}}B?.addEventListener("click",()=>{x.classList.add("show"),k.style.display="none",D()}),wireModal(x,A),C?.addEventListener("click",p),T?.addEventListener("click",p)})(),(function(){const x=new ErrorHandler;injectModal("notifications-modal",`<div id="notifications-modal" class="weather-modal">
<div class="weather-modal-content" style="min-width: 550px; max-width: 650px;">
<h3>\u{1F514} Notification Settings</h3>
@@ -1000,15 +1039,15 @@ Try refreshing in a moment if you see a certificate error.`,"warning",1e4),!1}};
<button id="notifications-save" class="btn-accent">Save Settings</button>
</div>
</div>
</div>`);const I=document.getElementById("notifications-modal"),A=document.getElementById("manage-notifications"),E=document.getElementById("notifications-save"),M=document.getElementById("notifications-cancel");["discord","telegram","ntfy","email"].forEach(k=>{const T=document.getElementById(`${k}-enabled`),S=document.getElementById(`${k}-config`);T?.addEventListener("change",()=>{S.style.display=T.checked?"block":"none"})});const P=document.getElementById("health-check-enabled"),z=document.getElementById("health-check-config");P?.addEventListener("change",()=>{z.style.opacity=P.checked?"1":"0.5"});async function D(){try{const T=await(await fetch("/api/v1/notifications/config")).json();if(T.success){const S=T.config;document.getElementById("notifications-enabled").checked=S.enabled,document.getElementById("discord-enabled").checked=S.providers?.discord?.enabled||!1,document.getElementById("telegram-enabled").checked=S.providers?.telegram?.enabled||!1,document.getElementById("ntfy-enabled").checked=S.providers?.ntfy?.enabled||!1,document.getElementById("email-enabled").checked=S.providers?.email?.enabled||!1,document.getElementById("discord-config").style.display=S.providers?.discord?.enabled?"block":"none",document.getElementById("telegram-config").style.display=S.providers?.telegram?.enabled?"block":"none",document.getElementById("ntfy-config").style.display=S.providers?.ntfy?.enabled?"block":"none",document.getElementById("email-config").style.display=S.providers?.email?.enabled?"block":"none",S.providers?.ntfy?.serverUrl&&(document.getElementById("ntfy-server").value=S.providers.ntfy.serverUrl),S.providers?.email?.host&&(document.getElementById("email-host").value=S.providers.email.host),S.providers?.email?.from&&(document.getElementById("email-from").value=S.providers.email.from),document.getElementById("health-check-enabled").checked=S.healthCheck?.enabled||!1,S.healthCheck?.intervalMinutes&&(document.getElementById("health-check-interval").value=S.healthCheck.intervalMinutes),S.healthCheck?.lastCheck&&(document.getElementById("health-check-status").textContent=`Last check: ${new Date(S.healthCheck.lastCheck).toLocaleString()}`),document.getElementById("event-container-down").checked=S.events?.containerDown!==!1,document.getElementById("event-container-up").checked=S.events?.containerUp!==!1,document.getElementById("event-deploy-success").checked=S.events?.deploymentSuccess!==!1,document.getElementById("event-deploy-failed").checked=S.events?.deploymentFailed!==!1,document.getElementById("event-resource-alert").checked=S.events?.resourceAlert!==!1}}catch(k){f.logError("[Notifications] Load Config",k,{function:"loadConfig"})}}async function v(){try{const T=await(await fetch("/api/v1/notifications/history?limit=10")).json(),S=document.getElementById("notification-history");T.success&&T.history?.length>0?S.innerHTML=T.history.map(L=>{const j=new Date(L.timestamp).toLocaleString();return`
</div>`);const B=document.getElementById("notifications-modal"),A=document.getElementById("manage-notifications"),C=document.getElementById("notifications-save"),M=document.getElementById("notifications-cancel");["discord","telegram","ntfy","email"].forEach(k=>{const T=document.getElementById(`${k}-enabled`),E=document.getElementById(`${k}-config`);T?.addEventListener("change",()=>{E.style.display=T.checked?"block":"none"})});const P=document.getElementById("health-check-enabled"),z=document.getElementById("health-check-config");P?.addEventListener("change",()=>{z.style.opacity=P.checked?"1":"0.5"});async function N(){try{const T=await(await fetch("/api/v1/notifications/config")).json();if(T.success){const E=T.config;document.getElementById("notifications-enabled").checked=E.enabled,document.getElementById("discord-enabled").checked=E.providers?.discord?.enabled||!1,document.getElementById("telegram-enabled").checked=E.providers?.telegram?.enabled||!1,document.getElementById("ntfy-enabled").checked=E.providers?.ntfy?.enabled||!1,document.getElementById("email-enabled").checked=E.providers?.email?.enabled||!1,document.getElementById("discord-config").style.display=E.providers?.discord?.enabled?"block":"none",document.getElementById("telegram-config").style.display=E.providers?.telegram?.enabled?"block":"none",document.getElementById("ntfy-config").style.display=E.providers?.ntfy?.enabled?"block":"none",document.getElementById("email-config").style.display=E.providers?.email?.enabled?"block":"none",E.providers?.ntfy?.serverUrl&&(document.getElementById("ntfy-server").value=E.providers.ntfy.serverUrl),E.providers?.email?.host&&(document.getElementById("email-host").value=E.providers.email.host),E.providers?.email?.from&&(document.getElementById("email-from").value=E.providers.email.from),document.getElementById("health-check-enabled").checked=E.healthCheck?.enabled||!1,E.healthCheck?.intervalMinutes&&(document.getElementById("health-check-interval").value=E.healthCheck.intervalMinutes),E.healthCheck?.lastCheck&&(document.getElementById("health-check-status").textContent=`Last check: ${new Date(E.healthCheck.lastCheck).toLocaleString()}`),document.getElementById("event-container-down").checked=E.events?.containerDown!==!1,document.getElementById("event-container-up").checked=E.events?.containerUp!==!1,document.getElementById("event-deploy-success").checked=E.events?.deploymentSuccess!==!1,document.getElementById("event-deploy-failed").checked=E.events?.deploymentFailed!==!1,document.getElementById("event-resource-alert").checked=E.events?.resourceAlert!==!1}}catch(k){x.logError("[Notifications] Load Config",k,{function:"loadConfig"})}}async function f(){try{const T=await(await fetch("/api/v1/notifications/history?limit=10")).json(),E=document.getElementById("notification-history");T.success&&T.history?.length>0?E.innerHTML=T.history.map(I=>{const j=new Date(I.timestamp).toLocaleString();return`
<div style="padding: 6px 8px; border-bottom: 1px solid var(--border); display: flex; gap: 8px; align-items: flex-start;">
<span style="color: ${{success:"var(--ok-fg)",error:"var(--bad-fg)",warning:"#f39c12",info:"var(--accent)"}[L.type]||"var(--muted)"}">${L.type==="success"?"\u2713":L.type==="error"?"\u2717":"\u2139"}</span>
<span style="color: ${{success:"var(--ok-fg)",error:"var(--bad-fg)",warning:"#f39c12",info:"var(--accent)"}[I.type]||"var(--muted)"}">${I.type==="success"?"\u2713":I.type==="error"?"\u2717":"\u2139"}</span>
<div style="flex: 1; min-width: 0;">
<div style="font-weight: 500; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">${escapeHtml(L.title)}</div>
<div style="font-weight: 500; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">${escapeHtml(I.title)}</div>
<div style="font-size: 0.7rem; color: var(--muted);">${j}</div>
</div>
</div>
`}).join(""):S.innerHTML='<div style="color: var(--muted); text-align: center; padding: 20px;">No notifications yet</div>'}catch(k){f.logError("[Notifications] Load History",k,{function:"loadHistory"})}}async function B(){try{const k={enabled:document.getElementById("notifications-enabled").checked,providers:{discord:{enabled:document.getElementById("discord-enabled").checked,webhookUrl:document.getElementById("discord-webhook").value.trim()},telegram:{enabled:document.getElementById("telegram-enabled").checked,botToken:document.getElementById("telegram-bot-token").value.trim(),chatId:document.getElementById("telegram-chat-id").value.trim()},ntfy:{enabled:document.getElementById("ntfy-enabled").checked,serverUrl:document.getElementById("ntfy-server").value.trim()||"https://ntfy.sh",topic:document.getElementById("ntfy-topic").value.trim()},email:{enabled:document.getElementById("email-enabled").checked,host:document.getElementById("email-host").value.trim(),port:parseInt(document.getElementById("email-port").value)||587,secure:document.getElementById("email-secure").checked,user:document.getElementById("email-user").value.trim(),pass:document.getElementById("email-pass").value.trim(),from:document.getElementById("email-from").value.trim(),to:document.getElementById("email-to").value.trim()}},events:{containerDown:document.getElementById("event-container-down").checked,containerUp:document.getElementById("event-container-up").checked,deploymentSuccess:document.getElementById("event-deploy-success").checked,deploymentFailed:document.getElementById("event-deploy-failed").checked,resourceAlert:document.getElementById("event-resource-alert").checked},healthCheck:{enabled:document.getElementById("health-check-enabled").checked,intervalMinutes:parseInt(document.getElementById("health-check-interval").value)||5}},S=await(await secureFetch("/api/v1/notifications/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(k)})).json();S.success?(showNotification("Notification settings saved","success",3e3),I.classList.remove("show")):showNotification(`Failed to save: ${S.error}`,"error",3e3)}catch(k){showNotification(`Error: ${k.message}`,"error",3e3)}}async function x(k){try{const S=await(await secureFetch("/api/v1/notifications/test",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:k})})).json();S.success?showNotification(`Test ${k} notification sent!`,"success",3e3):showNotification(`Test failed: ${S.error}`,"error",3e3)}catch(T){showNotification(`Error: ${T.message}`,"error",3e3)}}document.getElementById("discord-test")?.addEventListener("click",()=>x("discord")),document.getElementById("telegram-test")?.addEventListener("click",()=>x("telegram")),document.getElementById("ntfy-test")?.addEventListener("click",()=>x("ntfy")),document.getElementById("email-test")?.addEventListener("click",()=>x("email")),document.getElementById("health-check-now")?.addEventListener("click",async()=>{try{const T=await(await secureFetch("/api/v1/notifications/health-check",{method:"POST"})).json();T.success&&(document.getElementById("health-check-status").textContent=`Last check: ${new Date(T.lastCheck).toLocaleString()} (${T.containersMonitored} containers)`,showNotification("Health check completed","success",2e3))}catch(k){showNotification(`Error: ${k.message}`,"error",3e3)}}),A?.addEventListener("click",()=>{I.classList.add("show"),D(),v()}),E?.addEventListener("click",B),document.getElementById("notifications-send-test")?.addEventListener("click",async()=>{const k=document.getElementById("notifications-send-test"),T=k.textContent;k.textContent="Sending...",k.disabled=!0;try{const L=await(await secureFetch("/api/v1/notifications/send",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({event:"test",data:{message:"This is a test notification from DashCaddy."},type:"info"})})).json();L.success?(showNotification("Test notification sent!","success",3e3),$()):showNotification(`Test failed: ${L.results?.map(j=>`${j.provider}: ${j.error||"ok"}`).join(", ")}`,"error",5e3)}catch(S){showNotification(`Error: ${S.message}`,"error",3e3)}finally{k.textContent=T,k.disabled=!1}});async function $(){try{const T=await(await fetch("/api/v1/notifications/status")).json();if(T.success&&T.lastSent){const S=document.getElementById("last-notification-sent");S&&(S.textContent=`Last sent: ${new Date(T.lastSent).toLocaleString()}`)}}catch{}}wireModal(I,M)})(),(function(){document.addEventListener("click",f=>{const I=f.target.closest(".panel-tab");if(!I)return;const A=I.dataset.panel;if(!A)return;const E=I.closest(".panel-tabs"),M=E.closest(".weather-modal-content");E.querySelectorAll(".panel-tab").forEach(z=>z.classList.remove("active")),I.classList.add("active"),M.querySelectorAll(".panel-section").forEach(z=>z.classList.remove("active"));const P=M.querySelector("#"+A);P&&P.classList.add("active")})})(),(function(){var f=["dashcaddy_site_config","dashca Line truncated
`}).join(""):E.innerHTML='<div style="color: var(--muted); text-align: center; padding: 20px;">No notifications yet</div>'}catch(k){x.logError("[Notifications] Load History",k,{function:"loadHistory"})}}async function L(){try{const k={enabled:document.getElementById("notifications-enabled").checked,providers:{discord:{enabled:document.getElementById("discord-enabled").checked,webhookUrl:document.getElementById("discord-webhook").value.trim()},telegram:{enabled:document.getElementById("telegram-enabled").checked,botToken:document.getElementById("telegram-bot-token").value.trim(),chatId:document.getElementById("telegram-chat-id").value.trim()},ntfy:{enabled:document.getElementById("ntfy-enabled").checked,serverUrl:document.getElementById("ntfy-server").value.trim()||"https://ntfy.sh",topic:document.getElementById("ntfy-topic").value.trim()},email:{enabled:document.getElementById("email-enabled").checked,host:document.getElementById("email-host").value.trim(),port:parseInt(document.getElementById("email-port").value)||587,secure:document.getElementById("email-secure").checked,user:document.getElementById("email-user").value.trim(),pass:document.getElementById("email-pass").value.trim(),from:document.getElementById("email-from").value.trim(),to:document.getElementById("email-to").value.trim()}},events:{containerDown:document.getElementById("event-container-down").checked,containerUp:document.getElementById("event-container-up").checked,deploymentSuccess:document.getElementById("event-deploy-success").checked,deploymentFailed:document.getElementById("event-deploy-failed").checked,resourceAlert:document.getElementById("event-resource-alert").checked},healthCheck:{enabled:document.getElementById("health-check-enabled").checked,intervalMinutes:parseInt(document.getElementById("health-check-interval").value)||5}},E=await(await secureFetch("/api/v1/notifications/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(k)})).json();E.success?(showNotification("Notification settings saved","success",3e3),B.classList.remove("show")):showNotification(`Failed to save: ${E.error}`,"error",3e3)}catch(k){showNotification(`Error: ${k.message}`,"error",3e3)}}async function w(k){try{const E=await(await secureFetch("/api/v1/notifications/test",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:k})})).json();E.success?showNotification(`Test ${k} notification sent!`,"success",3e3):showNotification(`Test failed: ${E.error}`,"error",3e3)}catch(T){showNotification(`Error: ${T.message}`,"error",3e3)}}document.getElementById("discord-test")?.addEventListener("click",()=>w("discord")),document.getElementById("telegram-test")?.addEventListener("click",()=>w("telegram")),document.getElementById("ntfy-test")?.addEventListener("click",()=>w("ntfy")),document.getElementById("email-test")?.addEventListener("click",()=>w("email")),document.getElementById("health-check-now")?.addEventListener("click",async()=>{try{const T=await(await secureFetch("/api/v1/notifications/health-check",{method:"POST"})).json();T.success&&(document.getElementById("health-check-status").textContent=`Last check: ${new Date(T.lastCheck).toLocaleString()} (${T.containersMonitored} containers)`,showNotification("Health check completed","success",2e3))}catch(k){showNotification(`Error: ${k.message}`,"error",3e3)}}),A?.addEventListener("click",()=>{B.classList.add("show"),N(),f()}),C?.addEventListener("click",L),document.getElementById("notifications-send-test")?.addEventListener("click",async()=>{const k=document.getElementById("notifications-send-test"),T=k.textContent;k.textContent="Sending...",k.disabled=!0;try{const I=await(await secureFetch("/api/v1/notifications/send",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({event:"test",data:{message:"This is a test notification from DashCaddy."},type:"info"})})).json();I.success?(showNotification("Test notification sent!","success",3e3),$()):showNotification(`Test failed: ${I.results?.map(j=>`${j.provider}: ${j.error||"ok"}`).join(", ")}`,"error",5e3)}catch(E){showNotification(`Error: ${E.message}`,"error",3e3)}finally{k.textContent=T,k.disabled=!1}});async function $(){try{const T=await(await fetch("/api/v1/notifications/status")).json();if(T.success&&T.lastSent){const E=document.getElementById("last-notification-sent");E&&(E.textContent=`Last sent: ${new Date(T.lastSent).toLocaleString()}`)}}catch{}}wireModal(B,M)})(),(function(){document.addEventListener("click",x=>{const B=x.target.closest(".panel-tab");if(!B)return;const A=B.dataset.panel;if(!A)return;const C=B.closest(".panel-tabs"),M=C.closest(".weather-modal-content");C.querySelectorAll(".panel-tab").forEach(z=>z.classList.remove("active")),B.classList.add("active"),M.querySelectorAll(".panel-section").forEach(z=>z.classList.remove("active"));const P=M.querySelector("#"+A);P&&P.classList.add("active")})})(),(function(){var x=["dashcaddy_site_config","dashca Line truncated
<div class="weather-modal-content" style="min-width: 550px; max-width: 650px;">
<h3>\u{1F4BE} Backup & Restore</h3>
<p class="modal-subtitle">
@@ -1114,9 +1153,9 @@ Try refreshing in a moment if you see a certificate error.`,"warning",1e4),!1}};
<button id="backup-cancel">Close</button>
</div>
</div>
</div>`);var P=document.getElementById("backup-modal"),z=document.getElementById("backup-restore-btn"),D=document.getElementById("backup-cancel"),v=document.getElementById("backup-export-btn"),B=document.getElementById("backup-select-file"),x=document.getElementById("backup-file-input"),$=document.getElementById("backup-file-name"),k=document.getElementById("backup-preview"),T=document.getElementById("backup-preview-content"),S=document.getElementById("backup-do-restore-btn"),L=document.getElementById("backup-result"),j=document.getElementById("backup-schedules-container"),C=document.getElementById("backup-history-container"),N=document.getElementById("backup-disk-container"),R=document.getElementById("pointintime-container"),U=null;z?.addEventListener("click",function(){P.classList.add("show"),L&&(L.style.display="none"),k&&(k.style.display="none"),$&&($.style.display="none"),U=null}),wireModal(P,D),v?.addEventListener("click",async function(){v.disabled=!0,v.innerHTML='<span class="brand-spinner"></span> Exporting...';try{var e=await fetch("/api/v1/backup/export"),a=await e.json();a.browserState=I();var o=new Blob([JSON.stringify(a,null,2)],{type:"application/json"}),i=URL.createObjectURL(o),n=document.createElement("a");n.href=i,n.download="dashcaddy-backup-"+new Date().toISOString().split("T")[0]+".json",document.body.appendChild(n),n.click(),document.body.removeChild(n),URL.revokeObjectURL(i);var s=Object.keys(a.browserState).length,l=a.themes?Object.keys(a.themes).length:0;L.innerHTML="\u2705 Full backup downloaded \u2014 server config + "+s+" browser settings"+(l?" + "+l+" themes":""),L.style.display="block",L.style.background="color-mix(in srgb, var(--ok-fg) 15%, transparent)",L.style.border="1px solid var(--ok-fg)"}catch(p){L.innerHTML="\u274C Export failed: "+escapeHtml(p.message),L.style.display="block",L.style.background="color-mix(in srgb, var(--bad-fg) 15%, transparent)",L.style.border="1px solid var(--bad-fg)"}v.disabled=!1,v.innerHTML="\u2B07\uFE0F Download Full Backup"}),B?.addEventListener("click",function(){x.click()}),x?.addEventListener("change",async function(e){var a=e.target.files[0];if(a){$.textContent="\u{1F4C4} "+a.name,$.style.display="block",L.style.display="none";try{var o=await a.text(),i=JSON.parse(o);if(E(i)){U=i;var n='<div style="margin-bottom: 8px; color: var(--muted); font-size: 0.8rem;">Legacy format (v'+escapeHtml(i.version)+")</div>";n+='<div style="display: flex; flex-wrap: wrap; gap: 6px;">',i.services?.length&&(n+='<span style="padding: 4px 8px; background: var(--base); border-radius: 4px; font-size: 0.8rem;">\u{1F4CB} '+i.services.length+" services</span>"),i.customApps?.length&&(n+='<span style="padding: 4px 8px; background: var(--base); border-radius: 4px; font-size: 0.8rem;">\u{1F4E6} '+i.customApps.length+" custom apps</span>"),i.theme&&(n+='<span style="padding: 4px 8px; background: var(--base); border-radius: 4px; font-size: 0.8rem;">\u{1F3A8} Theme: '+escapeHtml(i.theme)+"</span>"),i.userThemes&&(n+='<span style="padding: 4px 8px; background: var(--base); border-radius: 4px; font-size: 0.8rem;">\u{1F3A8} '+Object.keys(i.userThemes).length+" custom themes</span>"),n+="</div>",T.innerHTML=n,k.style.display="block";return}var s=await secureFetch("/api/v1/backup/preview",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)}),l=await s.json();if(l.success){U=i;var n='<div style="margin-bottom: 8px; color: var(--muted); font-size: 0.8rem;">Exported: '+new Date(i.exportedAt).toLocaleString()+" (v"+escapeHtml(i.version)+")</div>";n+='<div style="margin-bottom: 6px; font-size: 0.75rem; color: var(--muted); text-transform: uppercase; letter-spacing: 0.5px;">Server Config</div>',n+='<div style="display: flex; flex-wrap: wrap; gap: 6px; margin-bottom: 10px;">';for(var p in l.preview.files){var w=l.preview.files[p],O=w.action==="create"?"\u{1F195}":"\u{1F4DD}";n+='<span style="padding: 4px 8px; background: var(--base); border-radius: 4px; font-size: 0.8rem;">'+O+" "+escapeHtml(w.description)+"</span>"}n+="</div>",l.preview.serviceCount&&(n+='<div style="font-size: 0.8rem; color: var(--accent); margin-bottom: 6px;">'+l.preview.serviceCount+" services</div>"),l.preview.themeCount&&(n+='<div style="font-size: 0.8rem; color: var(--accent); margin-bottom: 6px;">\u{1F3A8} '+l.preview.themeCount+" custom themes</div>"),l.preview.browserStateCount&&(n+='<div style="margin-top: 6px; font-size: 0.75rem; color: var(--muted); text-transform: uppercase; letter-spacing: 0.5px;">Browser Preferences</div>',n+='<div style="font-size: 0.8rem; color: var(--accent);">\u{1F5A5}\uFE0F '+l.preview.browserStateCount+" saved settings (theme, weather, clock, widgets, etc.)</div>"),T.innerHTML=n,k.style.display="block"}else L.innerHTML="\u26A0\uFE0F Invalid backup file: "+escapeHtml(l.error),L.style.display="block",L.style.background="color-mix(in srgb, #f39c12 15%, transparent)",L.style.border="1px solid #f39c12",k.style.display="none"}catch(_){L.innerHTML="\u274CLine truncated
</div>`);var P=document.getElementById("backup-modal"),z=document.getElementById("backup-restore-btn"),N=document.getElementById("backup-cancel"),f=document.getElementById("backup-export-btn"),L=document.getElementById("backup-select-file"),w=document.getElementById("backup-file-input"),$=document.getElementById("backup-file-name"),k=document.getElementById("backup-preview"),T=document.getElementById("backup-preview-content"),E=document.getElementById("backup-do-restore-btn"),I=document.getElementById("backup-result"),j=document.getElementById("backup-schedules-container"),H=document.getElementById("backup-history-container"),R=document.getElementById("backup-disk-container"),D=document.getElementById("pointintime-container"),O=null;z?.addEventListener("click",function(){P.classList.add("show"),I&&(I.style.display="none"),k&&(k.style.display="none"),$&&($.style.display="none"),O=null}),wireModal(P,N),f?.addEventListener("click",async function(){f.disabled=!0,f.innerHTML='<span class="brand-spinner"></span> Exporting...';try{var e=await fetch("/api/v1/backup/export"),a=await e.json();a.browserState=B();var o=new Blob([JSON.stringify(a,null,2)],{type:"application/json"}),r=URL.createObjectURL(o),n=document.createElement("a");n.href=r,n.download="dashcaddy-backup-"+new Date().toISOString().split("T")[0]+".json",document.body.appendChild(n),n.click(),document.body.removeChild(n),URL.revokeObjectURL(r);var i=Object.keys(a.browserState).length,d=a.themes?Object.keys(a.themes).length:0;I.innerHTML="\u2705 Full backup downloaded \u2014 server config + "+i+" browser settings"+(d?" + "+d+" themes":""),I.style.display="block",I.style.background="color-mix(in srgb, var(--ok-fg) 15%, transparent)",I.style.border="1px solid var(--ok-fg)"}catch(g){I.innerHTML="\u274C Export failed: "+escapeHtml(g.message),I.style.display="block",I.style.background="color-mix(in srgb, var(--bad-fg) 15%, transparent)",I.style.border="1px solid var(--bad-fg)"}f.disabled=!1,f.innerHTML="\u2B07\uFE0F Download Full Backup"}),L?.addEventListener("click",function(){w.click()}),w?.addEventListener("change",async function(e){var a=e.target.files[0];if(a){$.textContent="\u{1F4C4} "+a.name,$.style.display="block",I.style.display="none";try{var o=await a.text(),r=JSON.parse(o);if(C(r)){O=r;var n='<div style="margin-bottom: 8px; color: var(--muted); font-size: 0.8rem;">Legacy format (v'+escapeHtml(r.version)+")</div>";n+='<div style="display: flex; flex-wrap: wrap; gap: 6px;">',r.services?.length&&(n+='<span style="padding: 4px 8px; background: var(--base); border-radius: 4px; font-size: 0.8rem;">\u{1F4CB} '+r.services.length+" services</span>"),r.customApps?.length&&(n+='<span style="padding: 4px 8px; background: var(--base); border-radius: 4px; font-size: 0.8rem;">\u{1F4E6} '+r.customApps.length+" custom apps</span>"),r.theme&&(n+='<span style="padding: 4px 8px; background: var(--base); border-radius: 4px; font-size: 0.8rem;">\u{1F3A8} Theme: '+escapeHtml(r.theme)+"</span>"),r.userThemes&&(n+='<span style="padding: 4px 8px; background: var(--base); border-radius: 4px; font-size: 0.8rem;">\u{1F3A8} '+Object.keys(r.userThemes).length+" custom themes</span>"),n+="</div>",T.innerHTML=n,k.style.display="block";return}var i=await secureFetch("/api/v1/backup/preview",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)}),d=await i.json();if(d.success){O=r;var n='<div style="margin-bottom: 8px; color: var(--muted); font-size: 0.8rem;">Exported: '+new Date(r.exportedAt).toLocaleString()+" (v"+escapeHtml(r.version)+")</div>";n+='<div style="margin-bottom: 6px; font-size: 0.75rem; color: var(--muted); text-transform: uppercase; letter-spacing: 0.5px;">Server Config</div>',n+='<div style="display: flex; flex-wrap: wrap; gap: 6px; margin-bottom: 10px;">';for(var g in d.preview.files){var S=d.preview.files[g],U=S.action==="create"?"\u{1F195}":"\u{1F4DD}";n+='<span style="padding: 4px 8px; background: var(--base); border-radius: 4px; font-size: 0.8rem;">'+U+" "+escapeHtml(S.description)+"</span>"}n+="</div>",d.preview.serviceCount&&(n+='<div style="font-size: 0.8rem; color: var(--accent); margin-bottom: 6px;">'+d.preview.serviceCount+" services</div>"),d.preview.themeCount&&(n+='<div style="font-size: 0.8rem; color: var(--accent); margin-bottom: 6px;">\u{1F3A8} '+d.preview.themeCount+" custom themes</div>"),d.preview.browserStateCount&&(n+='<div style="margin-top: 6px; font-size: 0.75rem; color: var(--muted); text-transform: uppercase; letter-spacing: 0.5px;">Browser Preferences</div>',n+='<div style="font-size: 0.8rem; color: var(--accent);">\u{1F5A5}\uFE0F '+d.preview.browserStateCount+" saved settings (theme, weather, clock, widgets, etc.)</div>"),T.innerHTML=n,k.style.display="block"}else I.innerHTML="\u26A0\uFE0F Invalid backup file: "+escapeHtml(d.error),I.style.display="block",I.style.background="color-mix(in srgb, #f39c12 15%, transparent)",I.style.border="1px solid #f39c12",k.style.display="none"}catch(q){I.innerHTML="\u274CLine truncated
This will replace current configuration, credentials, and data. Containers will be restarted.`))try{var o=await secureFetch("/api/v1/apps/"+encodeURIComponent(e)+"/revert/"+encodeURIComponent(a),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({restartContainers:!0})}),i=await o.json();i.success?(showNotification(e+" restored to "+a,"success"),setTimeout(function(){location.reload()},1500)):showNotification("Restore failed: "+(i.error||"Unknown"),"error")}catch(n){showNotification("Restore error: "+n.message,"error")}}})(),(function(){injectModal("stats-modal",`<div id="stats-modal" class="weather-modal">
This will replace current configuration, credentials, and data. Containers will be restarted.`))try{var o=await secureFetch("/api/v1/apps/"+encodeURIComponent(e)+"/revert/"+encodeURIComponent(a),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({restartContainers:!0})}),r=await o.json();r.success?(showNotification(e+" restored to "+a,"success"),setTimeout(function(){location.reload()},1500)):showNotification("Restore failed: "+(r.error||"Unknown"),"error")}catch(n){showNotification("Restore error: "+n.message,"error")}}})(),(function(){injectModal("stats-modal",`<div id="stats-modal" class="weather-modal">
<div class="weather-modal-content" style="min-width: 750px; max-width: 950px;">
<h3>\u{1F4CA} Resource Monitor</h3>
<p class="modal-subtitle">
@@ -1196,11 +1235,11 @@ This will replace current configuration, credentials, and data. Containers will
<button id="stats-cancel">Close</button>
</div>
</div>
</div>`);const f=document.getElementById("stats-modal"),I=document.getElementById("container-stats-btn"),A=document.getElementById("stats-cancel"),E=document.getElementById("stats-refresh-btn"),M=document.getElementById("stats-auto-refresh"),P=document.getElementById("stats-container"),z=document.getElementById("stats-aggregated-container"),D=document.getElementById("stats-alerts-container"),v=document.getElementById("stats-last-update");let B=null,x=null;function $(d){if(d===0||!d)return"0 B";const b=1024,y=["B","KB","MB","GB"],t=Math.floor(Math.log(d)/Math.log(b));return parseFloat((d/Math.pow(b,t)).toFixed(1))+" "+y[t]}function k(d){return d<30?"#2ecc71":d<70?"#f39c12":"#e74c3c"}function T(d){return d<50?"#2ecc71":d<80?"#f39c12":"#e74c3c"}async function S(){try{let d=null,b=!1;try{const e=await(await fetch("/api/v1/monitoring/stats")).json();e.success&&e.stats&&(d=e.stats,b=!0,x=e.stats)}catch{}if(!b){const e=await(await fetch("/api/v1/stats/containers")).json();if(e.success&&e.stats){d={};for(const a of e.stats)d[a.name]={name:a.name,current:{cpu:a.cpu,memory:{percent:a.memory.percent,usage:a.memory.used,limit:a.memory.limit,usageMB:Math.round(a.memory.used/1048576),limitMB:Math.round(a.memory.limit/1048576)},network:{rxBytes:a.network.rx,txBytes:a.network.tx,rxMB:(a.network.rx/1048576).toFixed(1),txMB:(a.network.tx/1048576).toFixed(1)},disk:{readMB:0,writeMB:0}},status:a.status};x=d}}if(!d||Object.keys(d).length===0){P.innerHTML='<div style="text-align: center; padding: 40px; color: var(--muted);">No running containers found</div>';return}let y='<div style="display: flex; flex-direction: column; gap: 8px;">';for(const[t,e]of Object.entries(d)){const a=e.current||e,o=a.cpu?.percent||0,i=a.memory?.percent||0,n=k(o),s=T(i),l=a.memory?.usage||a.memory?.used||0,p=a.memory?.limit||0,w=a.network?.rxBytes||a.network?.rx||0,O=a.network?.txBytes||a.network?.tx||0,_=e.aggregated;y+=`
</div>`);const x=document.getElementById("stats-modal"),B=document.getElementById("container-stats-btn"),A=document.getElementById("stats-cancel"),C=document.getElementById("stats-refresh-btn"),M=document.getElementById("stats-auto-refresh"),P=document.getElementById("stats-container"),z=document.getElementById("stats-aggregated-container"),N=document.getElementById("stats-alerts-container"),f=document.getElementById("stats-last-update");let L=null,w=null;function $(l){if(l===0||!l)return"0 B";const m=1024,u=["B","KB","MB","GB"],t=Math.floor(Math.log(l)/Math.log(m));return parseFloat((l/Math.pow(m,t)).toFixed(1))+" "+u[t]}function k(l){return l<30?"#2ecc71":l<70?"#f39c12":"#e74c3c"}function T(l){return l<50?"#2ecc71":l<80?"#f39c12":"#e74c3c"}async function E(){try{let l=null,m=!1;try{const e=await(await fetch("/api/v1/monitoring/stats")).json();e.success&&e.stats&&(l=e.stats,m=!0,w=e.stats)}catch{}if(!m){const e=await(await fetch("/api/v1/stats/containers")).json();if(e.success&&e.stats){l={};for(const a of e.stats)l[a.name]={name:a.name,current:{cpu:a.cpu,memory:{percent:a.memory.percent,usage:a.memory.used,limit:a.memory.limit,usageMB:Math.round(a.memory.used/1048576),limitMB:Math.round(a.memory.limit/1048576)},network:{rxBytes:a.network.rx,txBytes:a.network.tx,rxMB:(a.network.rx/1048576).toFixed(1),txMB:(a.network.tx/1048576).toFixed(1)},disk:{readMB:0,writeMB:0}},status:a.status};w=l}}if(!l||Object.keys(l).length===0){P.innerHTML='<div style="text-align: center; padding: 40px; color: var(--muted);">No running containers found</div>';return}let u='<div style="display: flex; flex-direction: column; gap: 8px;">';for(const[t,e]of Object.entries(l)){const a=e.current||e,o=a.cpu?.percent||0,r=a.memory?.percent||0,n=k(o),i=T(r),d=a.memory?.usage||a.memory?.used||0,g=a.memory?.limit||0,S=a.network?.rxBytes||a.network?.rx||0,U=a.network?.txBytes||a.network?.tx||0,q=e.aggregated;u+=`
<div style="padding: 12px; background: var(--card-base); border-radius: 8px; border: 1px solid var(--border);">
<div style="display: flex; align-items: center; gap: 12px; margin-bottom: 10px;">
<span style="font-weight: 600; flex: 1;">${e.name||t}</span>
${_?`<span style="font-size: 0.65rem; color: var(--muted); padding: 2px 6px; background: color-mix(in srgb, var(--accent) 10%, transparent); border-radius: 4px;">avg ${_.cpu?.avg?.toFixed(0)||0}% cpu</span>`:""}
${q?`<span style="font-size: 0.65rem; color: var(--muted); padding: 2px 6px; background: color-mix(in srgb, var(--accent) 10%, transparent); border-radius: 4px;">avg ${q.cpu?.avg?.toFixed(0)||0}% cpu</span>`:""}
<span style="font-size: 0.75rem; color: var(--muted); background: var(--base); padding: 2px 8px; border-radius: 4px;">${e.status||"running"}</span>
</div>
<div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 12px;">
@@ -1217,23 +1256,23 @@ This will replace current configuration, credentials, and data. Containers will
<div style="font-size: 0.7rem; color: var(--muted); margin-bottom: 4px;">Memory</div>
<div style="display: flex; align-items: center; gap: 8px;">
<div style="flex: 1; height: 6px; background: var(--base); border-radius: 3px; overflow: hidden;">
<div style="height: 100%; width: ${Math.min(i,100)}%; background: ${s}; border-radius: 3px; transition: width 0.3s;"></div>
<div style="height: 100%; width: ${Math.min(r,100)}%; background: ${i}; border-radius: 3px; transition: width 0.3s;"></div>
</div>
<span style="font-size: 0.8rem; font-weight: 500; color: ${s}; min-width: 45px; text-align: right;">${i.toFixed(1)}%</span>
<span style="font-size: 0.8rem; font-weight: 500; color: ${i}; min-width: 45px; text-align: right;">${r.toFixed(1)}%</span>
</div>
<div style="font-size: 0.65rem; color: var(--muted); margin-top: 2px;">${$(l)} / ${$(p)}</div>
<div style="font-size: 0.65rem; color: var(--muted); margin-top: 2px;">${$(d)} / ${$(g)}</div>
</div>
<div>
<div style="font-size: 0.7rem; color: var(--muted); margin-bottom: 4px;">Network</div>
<div style="font-size: 0.8rem;">
<span style="color: #3498db;">\u2193 ${$(w)}</span>
<span style="color: #3498db;">\u2193 ${$(S)}</span>
<span style="color: var(--muted); margin: 0 4px;">/</span>
<span style="color: #e74c3c;">\u2191 ${$(O)}</span>
<span style="color: #e74c3c;">\u2191 ${$(U)}</span>
</div>
</div>
</div>
</div>`}y+="</div>",P.innerHTML=y,v.textContent="Updated: "+new Date().toLocaleTimeString()}catch(d){P.innerHTML=`<div style="text-align: center; padding: 40px; color: var(--bad-fg);">\u274C Failed to load stats: ${escapeHtml(d.message)}</div>`}}async function L(){if(!z)return;const d=x;if(!d||Object.keys(d).length===0){z.innerHTML='<div class="panel-empty"><span class="empty-icon">\u{1F4C8}</span>No monitoring data available. Open the Live Stats tab first.</div>';return}let b='<div style="display: flex; flex-direction: column; gap: 12px;">';for(const[y,t]of Object.entries(d)){const e=t.aggregated;e&&(b+=`<div style="padding: 12px; background: var(--card-base); border-radius: 8px; border: 1px solid var(--border);">
<div style="font-weight: 600; margin-bottom: 10px;">${t.name||y}</div>
</div>`}u+="</div>",P.innerHTML=u,f.textContent="Updated: "+new Date().toLocaleTimeString()}catch(l){P.innerHTML=`<div style="text-align: center; padding: 40px; color: var(--bad-fg);">\u274C Failed to load stats: ${escapeHtml(l.message)}</div>`}}async function I(){if(!z)return;const l=w;if(!l||Object.keys(l).length===0){z.innerHTML='<div class="panel-empty"><span class="empty-icon">\u{1F4C8}</span>No monitoring data available. Open the Live Stats tab first.</div>';return}let m='<div style="display: flex; flex-direction: column; gap: 12px;">';for(const[u,t]of Object.entries(l)){const e=t.aggregated;e&&(m+=`<div style="padding: 12px; background: var(--card-base); border-radius: 8px; border: 1px solid var(--border);">
<div style="font-weight: 600; margin-bottom: 10px;">${t.name||u}</div>
<div style="display: grid; grid-template-columns: repeat(4, 1fr); gap: 8px;">
<div class="stat-mini-card"><span class="stat-val">${e.cpu?.avg?.toFixed(1)||0}%</span><span class="stat-lbl">Avg CPU</span></div>
<div class="stat-mini-card"><span class="stat-val">${e.cpu?.max?.toFixed(1)||0}%</span><span class="stat-lbl">Max CPU</span></div>
@@ -1241,27 +1280,27 @@ This will replace current configuration, credentials, and data. Containers will
<div class="stat-mini-card"><span class="stat-val">${e.memory?.max?.toFixed(1)||0}%</span><span class="stat-lbl">Max Mem</span></div>
</div>
${e.dataPoints?`<div style="font-size: 0.7rem; color: var(--muted); margin-top: 6px;">${e.dataPoints} data points over ${e.timeRange||24}h</div>`:""}
</div>`)}b+="</div>",z.innerHTML=b}async function j(){if(!D)return;D.innerHTML='<div class="panel-empty"><span class="brand-spinner"></span> Loading alerts...</div>';const d=x;if(!d||Object.keys(d).length===0){D.innerHTML='<div class="panel-empty"><span class="empty-icon">\u{1F514}</span>No containers found. Open the Live Stats tab first.</div>';return}let b=!1;try{b=(await(await fetch("/api/v1/license/feature/resource-alerts")).json()).available}catch{b=!1}let y=[];try{const s=await(await fetch("/api/v1/monitoring/alerts?limit=50")).json();s.success&&(y=s.history||[])}catch{}let t={};try{const s=await(await fetch("/api/v1/monitoring/alerts/config")).json();s.success&&(t=s.configs||{})}catch{}const a=Object.entries(d).map(([n,s])=>{const l=t[n]||{cpuThreshold:80,memoryThreshold:90,diskIOThreshold:50,autoRestart:!1,enabled:!1};return`
</div>`)}m+="</div>",z.innerHTML=m}async function j(){if(!N)return;N.innerHTML='<div class="panel-empty"><span class="brand-spinner"></span> Loading alerts...</div>';const l=w;if(!l||Object.keys(l).length===0){N.innerHTML='<div class="panel-empty"><span class="empty-icon">\u{1F514}</span>No containers found. Open the Live Stats tab first.</div>';return}let m=!1;try{m=(await(await fetch("/api/v1/license/feature/resource-alerts")).json()).available}catch{m=!1}let u=[];try{const i=await(await fetch("/api/v1/monitoring/alerts?limit=50")).json();i.success&&(u=i.history||[])}catch{}let t={};try{const i=await(await fetch("/api/v1/monitoring/alerts/config")).json();i.success&&(t=i.configs||{})}catch{}const a=Object.entries(l).map(([n,i])=>{const d=t[n]||{cpuThreshold:80,memoryThreshold:90,diskIOThreshold:50,autoRestart:!1,enabled:!1};return`
<tr data-container="${n}">
<td style="font-weight: 600; padding: 8px;">${s.name||n}</td>
<td style="padding: 4px 8px;"><input type="number" class="alert-cpu" value="${l.cpuThreshold??80}" min="0" max="100" style="width: 60px; font-size: 0.8rem; padding: 2px 4px;" ${b?"":"disabled"} /></td>
<td style="padding: 4px 8px;"><input type="number" class="alert-mem" value="${l.memoryThreshold??90}" min="0" max="100" style="width: 60px; font-size: 0.8rem; padding: 2px 4px;" ${b?"":"disabled"} /></td>
<td style="padding: 4px 8px;"><input type="number" class="alert-disk" value="${l.diskIOThreshold??50}" min="0" max="1000" style="width: 70px; font-size: 0.8rem; padding: 2px 4px;" ${b?"":"disabled"} /></td>
<td style="padding: 4px 8px;"><input type="checkbox" class="alert-autorestart" ${l.autoRestart?"checked":""} ${b?"":"disabled"} /></td>
<td style="font-weight: 600; padding: 8px;">${i.name||n}</td>
<td style="padding: 4px 8px;"><input type="number" class="alert-cpu" value="${d.cpuThreshold??80}" min="0" max="100" style="width: 60px; font-size: 0.8rem; padding: 2px 4px;" ${m?"":"disabled"} /></td>
<td style="padding: 4px 8px;"><input type="number" class="alert-mem" value="${d.memoryThreshold??90}" min="0" max="100" style="width: 60px; font-size: 0.8rem; padding: 2px 4px;" ${m?"":"disabled"} /></td>
<td style="padding: 4px 8px;"><input type="number" class="alert-disk" value="${d.diskIOThreshold??50}" min="0" max="1000" style="width: 70px; font-size: 0.8rem; padding: 2px 4px;" ${m?"":"disabled"} /></td>
<td style="padding: 4px 8px;"><input type="checkbox" class="alert-autorestart" ${d.autoRestart?"checked":""} ${m?"":"disabled"} /></td>
<td style="padding: 4px 8px;">
<button class="alert-test-btn btn-xs" data-container="${n}" data-name="${s.name||n}" style="padding: 2px 8px; font-size: 0.75rem; background: var(--card-base); border: 1px solid var(--border); border-radius: 4px; cursor: pointer;">Test</button>
<button class="alert-test-btn btn-xs" data-container="${n}" data-name="${i.name||n}" style="padding: 2px 8px; font-size: 0.75rem; background: var(--card-base); border: 1px solid var(--border); border-radius: 4px; cursor: pointer;">Test</button>
</td>
</tr>
`}).join(""),o=y.map(n=>{const s=new Date(n.timestamp).toLocaleString(),l=n.notified?"\u2713":"\u2014";return`
`}).join(""),o=u.map(n=>{const i=new Date(n.timestamp).toLocaleString(),d=n.notified?"\u2713":"\u2014";return`
<tr>
<td style="padding: 6px 8px; font-size: 0.8rem; color: var(--muted);">${s}</td>
<td style="padding: 6px 8px; font-size: 0.8rem; color: var(--muted);">${i}</td>
<td style="padding: 6px 8px; font-weight: 500;">${n.containerName||n.containerId}</td>
<td style="padding: 6px 8px; text-transform: capitalize;">${n.metric||n.type}</td>
<td style="padding: 6px 8px;">${typeof n.value=="number"?n.value.toFixed(1):n.value}${n.metric==="disk"?" MB/s":"%"}</td>
<td style="padding: 6px 8px; text-align: center;">${l}</td>
<td style="padding: 6px 8px; text-align: center;">${d}</td>
<td style="padding: 6px 8px; font-size: 0.75rem; color: ${n.autoRestartTriggered?"#f39c12":"var(--muted)"};">${n.autoRestartTriggered?"\u21BB":""}</td>
</tr>
`}).join(""),i=b?`
`}).join(""),r=m?`
<div style="margin-bottom: 20px;">
<div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 10px;">
<h4 style="margin: 0; font-size: 0.9rem;">\u2699\uFE0F Alert Configuration</h4>
@@ -1292,8 +1331,8 @@ This will replace current configuration, credentials, and data. Containers will
<p style="margin: 6px 0 0; font-size: 0.75rem; color: var(--muted);">Upgrade to configure resource alert thresholds per container.</p>
<button id="upgrade-for-alerts" style="margin-top: 8px; padding: 4px 12px; font-size: 0.75rem; background: #f1c40f; color: #000; border: none; border-radius: 4px; cursor: pointer; font-weight: 600;">Upgrade Now</button>
</div>
`;D.innerHTML=`
${i}
`;N.innerHTML=`
${r}
<div>
<h4 style="margin: 0 0 10px; font-size: 0.9rem;">\u{1F4CB} Recent Alerts</h4>
${o?`
@@ -1314,21 +1353,21 @@ This will replace current configuration, credentials, and data. Containers will
</div>
`:'<div style="color: var(--muted); text-align: center; padding: 20px;">No alerts recorded yet.</div>'}
</div>
`,document.getElementById("save-all-alerts")?.addEventListener("click",async()=>{const n={};document.querySelectorAll("#stats-alerts-container tr[data-container]").forEach(s=>{const l=s.dataset.container;n[l]={cpuThreshold:parseInt(s.querySelector(".alert-cpu")?.value)||80,memoryThreshold:parseInt(s.querySelector(".alert-mem")?.value)||90,diskIOThreshold:parseInt(s.querySelector(".alert-disk")?.value)||50,autoRestart:!!s.querySelector(".alert-autorestart")?.checked,enabled:!0}});try{const l=await(await secureFetch("/api/v1/monitoring/alerts/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({configs:n})})).json(),p=document.getElementById("save-all-alerts");p.textContent=l.success?"\u2705 Saved":"\u274C Failed",setTimeout(()=>{p.textContent="Save All"},2e3)}catch{const l=document.getElementById("save-all-alerts");l.textContent="\u274C Error",setTimeout(()=>{l.textContent="Save All"},2e3)}}),document.getElementById("go-to-notifications")?.addEventListener("click",n=>{n.preventDefault(),f.classList.remove("show"),N(),document.getElementById("manage-notifications")?.click()}),document.querySelectorAll(".alert-test-btn").forEach(n=>{n.addEventListener("click",async()=>{const s=n.textContent;n.textContent="...";try{await secureFetch(`/api/v1/monitoring/alerts/${n.dataset.container}/test`,{method:"POST"}),n.textContent="\u2705",showNotification("Test alert sent for "+n.dataset.name,"success",3e3)}catch{n.textContent="\u274C"}setTimeout(()=>{n.textContent=s},2e3)})}),document.getElementById("upgrade-for-alerts")?.addEventListener("click",()=>{f.classList.remove("show"),N(),typeof openLicenseModal=="function"&&openLicenseModal()})}function C(){B&&clearInterval(B),M?.checked&&(B=setInterval(S,DC.POLL.STATS))}function N(){B&&(clearInterval(B),B=null)}I?.addEventListener("click",()=>{f.classList.add("show"),S(),C()}),A?.addEventListener("click",()=>{f.classList.remove("show"),N()}),f?.addEventListener("click",d=>{d.target===f&&(f.classList.remove("show"),N())}),E?.addEventListener("click",S),M?.addEventListener("change",()=>{M.checked?C():N()}),document.querySelector('[data-panel="stats-aggregated"]')?.addEventListener("click",L),document.querySelector('[data-panel="stats-alerts"]')?.addEventListener("click",j);const R=document.getElementById("stats-history-container"),U=document.getElementById("stats-history-container-area"),u=document.querySelectorAll(".stats-range-btn");let m="1h";function h(d){switch(d){case"1h":return 3600*1e3;case"24h":return 1440*60*1e3;case"7d":return 10080*60*1e3;case"30d":return 720*60*60*1e3;case"1y":return 365*24*60*60*1e3;default:return 3600*1e3}}function g(d){return d==="raw"?"live (10s samples)":d==="hourly"?"hourly average":d==="daily"?"daily average":d}function H(d,b,y,t,e){if(!d||d.length===0)return`<div style="text-align: center; color: var(--muted); padding: 20px;">No data for ${escapeHtml(t)}</div>`;const a=d.map(b).filter(q=>q!=null);if(a.length===0)return`<div style="text-align: center; color: var(--muted); padding: 20px;">No data for ${escapeHtml(t)}</div>`;const o=Math.max(...a,1),i=Math.min(...a,0),n=o-i||1,s=600,l=80,p=4,w=(s-p*2)/Math.max(a.length-1,1),O=a.map((q,J)=>{const X=p+J*w,Q=l-p-(q-i)/n*(l-p*2);return`${X.toFixed(1)},${Q.toFixed(1)}`}).join(" "),_=a[a.length-1],F=a.reduce((q,J)=>q+J,0)/a.length;return`
`,document.getElementById("save-all-alerts")?.addEventListener("click",async()=>{const n={};document.querySelectorAll("#stats-alerts-container tr[data-container]").forEach(i=>{const d=i.dataset.container;n[d]={cpuThreshold:parseInt(i.querySelector(".alert-cpu")?.value)||80,memoryThreshold:parseInt(i.querySelector(".alert-mem")?.value)||90,diskIOThreshold:parseInt(i.querySelector(".alert-disk")?.value)||50,autoRestart:!!i.querySelector(".alert-autorestart")?.checked,enabled:!0}});try{const d=await(await secureFetch("/api/v1/monitoring/alerts/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({configs:n})})).json(),g=document.getElementById("save-all-alerts");g.textContent=d.success?"\u2705 Saved":"\u274C Failed",setTimeout(()=>{g.textContent="Save All"},2e3)}catch{const d=document.getElementById("save-all-alerts");d.textContent="\u274C Error",setTimeout(()=>{d.textContent="Save All"},2e3)}}),document.getElementById("go-to-notifications")?.addEventListener("click",n=>{n.preventDefault(),x.classList.remove("show"),R(),document.getElementById("manage-notifications")?.click()}),document.querySelectorAll(".alert-test-btn").forEach(n=>{n.addEventListener("click",async()=>{const i=n.textContent;n.textContent="...";try{await secureFetch(`/api/v1/monitoring/alerts/${n.dataset.container}/test`,{method:"POST"}),n.textContent="\u2705",showNotification("Test alert sent for "+n.dataset.name,"success",3e3)}catch{n.textContent="\u274C"}setTimeout(()=>{n.textContent=i},2e3)})}),document.getElementById("upgrade-for-alerts")?.addEventListener("click",()=>{x.classList.remove("show"),R(),typeof openLicenseModal=="function"&&openLicenseModal()})}function H(){L&&clearInterval(L),M?.checked&&(L=setInterval(E,DC.POLL.STATS))}function R(){L&&(clearInterval(L),L=null)}B?.addEventListener("click",()=>{x.classList.add("show"),E(),H()}),A?.addEventListener("click",()=>{x.classList.remove("show"),R()}),x?.addEventListener("click",l=>{l.target===x&&(x.classList.remove("show"),R())}),C?.addEventListener("click",E),M?.addEventListener("change",()=>{M.checked?H():R()}),document.querySelector('[data-panel="stats-aggregated"]')?.addEventListener("click",I),document.querySelector('[data-panel="stats-alerts"]')?.addEventListener("click",j);const D=document.getElementById("stats-history-container"),O=document.getElementById("stats-history-container-area"),p=document.querySelectorAll(".stats-range-btn");let v="1h";function b(l){switch(l){case"1h":return 3600*1e3;case"24h":return 1440*60*1e3;case"7d":return 10080*60*1e3;case"30d":return 720*60*60*1e3;case"1y":return 365*24*60*60*1e3;default:return 3600*1e3}}function y(l){return l==="raw"?"live (10s samples)":l==="hourly"?"hourly average":l==="daily"?"daily average":l}function h(l,m,u,t,e){if(!l||l.length===0)return`<div style="text-align: center; color: var(--muted); padding: 20px;">No data for ${escapeHtml(t)}</div>`;const a=l.map(m).filter(_=>_!=null);if(a.length===0)return`<div style="text-align: center; color: var(--muted); padding: 20px;">No data for ${escapeHtml(t)}</div>`;const o=Math.max(...a,1),r=Math.min(...a,0),n=o-r||1,i=600,d=80,g=4,S=(i-g*2)/Math.max(a.length-1,1),U=a.map((_,J)=>{const X=g+J*S,Q=d-g-(_-r)/n*(d-g*2);return`${X.toFixed(1)},${Q.toFixed(1)}`}).join(" "),q=a[a.length-1],F=a.reduce((_,J)=>_+J,0)/a.length;return`
<div style="margin-bottom: 14px;">
<div style="display: flex; align-items: baseline; gap: 12px; margin-bottom: 4px;">
<span style="font-weight: 600; font-size: 0.9rem;">${escapeHtml(t)}</span>
<span style="font-size: 0.75rem; color: var(--muted);">last ${_.toFixed(1)}${e} \xB7 avg ${F.toFixed(1)}${e} \xB7 max ${o.toFixed(1)}${e}</span>
<span style="font-size: 0.75rem; color: var(--muted);">last ${q.toFixed(1)}${e} \xB7 avg ${F.toFixed(1)}${e} \xB7 max ${o.toFixed(1)}${e}</span>
</div>
<svg viewBox="0 0 ${s} ${l}" preserveAspectRatio="none" style="width: 100%; height: ${l}px; background: var(--base); border-radius: 4px;">
<polyline fill="none" stroke="${y}" stroke-width="1.5" points="${O}" />
<svg viewBox="0 0 ${i} ${d}" preserveAspectRatio="none" style="width: 100%; height: ${d}px; background: var(--base); border-radius: 4px;">
<polyline fill="none" stroke="${u}" stroke-width="1.5" points="${U}" />
</svg>
</div>
`}function r(){if(!R)return;const d=x||{},b=R.value,y=Object.entries(d);if(y.length===0){R.innerHTML='<option value="">No containers</option>';return}R.innerHTML=y.map(([t,e])=>`<option value="${escapeHtml(t)}">${escapeHtml(e.name||t)}</option>`).join(""),b&&d[b]&&(R.value=b)}async function c(){if(!U||!R)return;const d=R.value;if(!d){U.innerHTML='<div class="panel-empty"><span class="empty-icon">\u{1F4CA}</span>No container selected.</div>';return}const b=Date.now(),y=b-h(m);U.innerHTML='<div class="panel-empty"><span class="brand-spinner"></span> Loading history...</div>';try{const e=await(await fetch(`/api/v1/monitoring/history/${encodeURIComponent(d)}?startTime=${y}&endTime=${b}`)).json();if(!e.success)throw new Error(e.error||"Failed to load history");const a=e.samples||[],o=e.tier||"raw";if(a.length===0){U.innerHTML=`<div class="panel-empty"><span class="empty-icon">\u{1F4CA}</span>No data for the last ${m}. Tier: ${g(o)}.</div>`;return}const i=o==="raw",n=i?O=>O.cpu?.percent:O=>O.cpu?.avg,s=i?O=>O.memory?.percent:O=>O.memory?.avgPercent,l=i?O=>O.network?.rxMB||0:O=>O.network?.rxMB||0,p=i?O=>O.network?.txMB||0:O=>O.network?.txMB||0;let w=`
`}function s(){if(!D)return;const l=w||{},m=D.value,u=Object.entries(l);if(u.length===0){D.innerHTML='<option value="">No containers</option>';return}D.innerHTML=u.map(([t,e])=>`<option value="${escapeHtml(t)}">${escapeHtml(e.name||t)}</option>`).join(""),m&&l[m]&&(D.value=m)}async function c(){if(!O||!D)return;const l=D.value;if(!l){O.innerHTML='<div class="panel-empty"><span class="empty-icon">\u{1F4CA}</span>No container selected.</div>';return}const m=Date.now(),u=m-b(v);O.innerHTML='<div class="panel-empty"><span class="brand-spinner"></span> Loading history...</div>';try{const e=await(await fetch(`/api/v1/monitoring/history/${encodeURIComponent(l)}?startTime=${u}&endTime=${m}`)).json();if(!e.success)throw new Error(e.error||"Failed to load history");const a=e.samples||[],o=e.tier||"raw";if(a.length===0){O.innerHTML=`<div class="panel-empty"><span class="empty-icon">\u{1F4CA}</span>No data for the last ${v}. Tier: ${y(o)}.</div>`;return}const r=o==="raw",n=r?U=>U.cpu?.percent:U=>U.cpu?.avg,i=r?U=>U.memory?.percent:U=>U.memory?.avgPercent,d=r?U=>U.network?.rxMB||0:U=>U.network?.rxMB||0,g=r?U=>U.network?.txMB||0:U=>U.network?.txMB||0;let S=`
<div style="font-size: 0.75rem; color: var(--muted); margin-bottom: 8px;">
${a.length} samples \xB7 ${escapeHtml(g(o))} \xB7 ${new Date(y).toLocaleString()} \u2192 ${new Date(b).toLocaleString()}
${a.length} samples \xB7 ${escapeHtml(y(o))} \xB7 ${new Date(u).toLocaleString()} \u2192 ${new Date(m).toLocaleString()}
</div>
`;w+=H(a,n,"#2ecc71","CPU","%"),w+=H(a,s,"#3498db","Memory","%"),w+=H(a,l,"#9b59b6","Network RX"," MB"),w+=H(a,p,"#e67e22","Network TX"," MB"),U.innerHTML=w}catch(t){U.innerHTML=`<div class="panel-empty"><span class="empty-icon">\u26A0\uFE0F</span>Failed to load history: ${escapeHtml(t.message)}</div>`}}u.forEach(d=>{d.addEventListener("click",()=>{u.forEach(b=>b.classList.remove("active")),d.classList.add("active"),m=d.dataset.range,c()})}),R?.addEventListener("change",c),document.querySelector('[data-panel="stats-history"]')?.addEventListener("click",()=>{r(),c()})})(),(function(){injectModal("health-modal",`<div id="health-modal" class="weather-modal">
`;S+=h(a,n,"#2ecc71","CPU","%"),S+=h(a,i,"#3498db","Memory","%"),S+=h(a,d,"#9b59b6","Network RX"," MB"),S+=h(a,g,"#e67e22","Network TX"," MB"),O.innerHTML=S}catch(t){O.innerHTML=`<div class="panel-empty"><span class="empty-icon">\u26A0\uFE0F</span>Failed to load history: ${escapeHtml(t.message)}</div>`}}p.forEach(l=>{l.addEventListener("click",()=>{p.forEach(m=>m.classList.remove("active")),l.classList.add("active"),v=l.dataset.range,c()})}),D?.addEventListener("change",c),document.querySelector('[data-panel="stats-history"]')?.addEventListener("click",()=>{s(),c()})})(),(function(){injectModal("health-modal",`<div id="health-modal" class="weather-modal">
<div class="weather-modal-content" style="min-width: 800px; max-width: 1000px;">
<h3>\u{1F3E5} Health Check Dashboard</h3>
<p class="modal-subtitle">
@@ -1452,24 +1491,24 @@ This will replace current configuration, credentials, and data. Containers will
<button id="health-cancel">Close</button>
</div>
</div>
</div>`);const f=document.getElementById("health-modal"),I=document.getElementById("health-check-btn"),A=document.getElementById("health-cancel"),E=document.getElementById("health-refresh-btn"),M=document.getElementById("health-status-container"),P=document.getElementById("health-incidents-container"),z=document.getElementById("health-config-container"),D=document.getElementById("health-last-update"),v=document.getElementById("health-add-btn"),B=document.getElementById("health-config-form"),x=document.getElementById("health-form-title"),$=document.getElementById("health-form-cancel"),k=document.getElementById("health-form-save"),T="dashcaddy-health-settings",S={retentionDays:30,pollingInterval:60,statsPollingInterval:30,maxEntriesPerService:500,diskUsageThreshold:80},L=document.getElementById("health-global-save"),j=document.getElementById("health-global-reset"),C=document.getElementById("health-global-status"),N=document.getElementById("health-setting-retention"),R=document.getElementById("health-setting-interval"),U=document.getElementById("health-setting-stats-interval"),u=document.getElementById("health-setting-max-entries"),m=document.getElementById("health-setting-disk-threshold");function h(){try{const i=safeGet(T),n=i?JSON.parse(i):{};return Object.assign({},S,n)}catch{return Object.assign({},S)}}function g(){const i=h();N&&(N.value=i.retentionDays),R&&(R.value=i.pollingInterval),U&&(U.value=i.statsPollingInterval),u&&(u.value=i.maxEntriesPerService),m&&(m.value=i.diskUsageThreshold)}function H(){const i={retentionDays:Math.max(1,Math.min(3650,parseInt(N?.value)||S.retentionDays)),pollingInterval:Math.max(5,Math.min(3600,parseInt(R?.value)||S.pollingInterval)),statsPollingInterval:Math.max(5,Math.min(3600,parseInt(U?.value)||S.statsPollingInterval)),maxEntriesPerService:Math.max(10,Math.min(1e5,parseInt(u?.value)||S.maxEntriesPerService)),diskUsageThreshold:Math.max(50,Math.min(99,parseInt(m?.value)||S.diskUsageThreshold))};try{safeSet(T,JSON.stringify(i)),g(),C&&(C.textContent="Saved \u2713",C.style.color="var(--ok-fg)",setTimeout(()=>{C&&(C.textContent="")},2500)),typeof showNotification=="function"&&showNotification("Global health settings saved","success")}catch(n){C&&(C.textContent="Save failed",C.style.color="var(--bad-fg)"),typeof showNotification=="function"&&showNotification("Failed to save settings: "+n.message,"error")}}function r(){try{safeSet(T,JSON.stringify(S))}catch{}g(),C&&(C.textContent="Reset to defaults \u2713",C.style.color="var(--ok-fg)",setTimeout(()=>{C&&(C.textContent="")},2500))}g(),L?.addEventListener("click",H),j?.addEventListener("click",r);let c=null;function d(i){return i>=99.9?"var(--ok-fg)":i>=95?"#f39c12":"var(--bad-fg)"}function b(i){const n={critical:"var(--bad-fg)",high:"#ff6b6b",medium:"#f39c12",low:"var(--muted)"};return`<span style="padding: 2px 8px; border-radius: 4px; font-size: 0.75rem; background: ${n[i]||"var(--muted)"}20; color: ${n[i]||"var(--muted)"};">${i}</span>`}async function y(){try{const n=await(await fetch("/api/v1/health-checks/status")).json();if(!n.success||!n.status||Object.keys(n.status).length===0){M.innerHTML='<div class="panel-empty"><span class="empty-icon">\u{1F3E5}</span>No health checks configured. Go to the Configure tab to add services.</div>';return}const s=Object.values(n.status);let l='<table style="width: 100%; border-collapse: collapse; font-size: 0.85rem;">';l+='<tr style="border-bottom: 1px solid var(--border); color: var(--muted); text-align: left;">',l+='<th style="padding: 8px;">Service</th><th style="padding: 8px;">Status</th>',l+='<th style="padding: 8px;">Uptime 24h</th><th style="padding: 8px;">Uptime 7d</th>',l+='<th style="padding: 8px;">Avg Response</th><th style="padding: 8px;">Last Check</th></tr>';for(const p of s){const w=p.status==="up",O=w?"var(--dot-ok)":"var(--dot-bad)",_=p.uptime?.["24h"]??"-",F=p.uptime?.["7d"]??"-",q=p.avgResponseTime!=null?Math.round(p.avgResponseTime)+"ms":"-",J=p.timestamp?timeAgo(p.timestamp):"-";l+=`<tr style="border-bottom: 1px solid var(--border); cursor: pointer;" data-health-id="${escapeHtml(p.serviceId)}">`,l+=`<td style="padding: 8px; font-weight: 500;">${escapeHtml(p.name||p.serviceId)}</td>`,l+=`<td style="padding: 8px;"><span style="display: inline-block; width: 8px; height: 8px; border-radius: 50%; background: ${O}; margin-right: 6px;"></span>${w?"Up":"Down"}</td>`,l+=`<td style="padding: 8px; color: ${typeof _=="number"?d(_):"var(--muted)"};">${typeof _=="number"?_.toFixed(1)+"%":_}</td>`,l+=`<td style="padding: 8px; color: ${typeof F=="number"?d(F):"var(--muted)"};">${typeof F=="number"?F.toFixed(1)+"%":F}</td>`,l+=`<td style="padding: 8px;">${q}</td>`,l+=`<td style="padding: 8px; color: var(--muted);">${J}</td>`,l+="</tr>",l+=`<tr id="health-detail-${escapeHtml(p.serviceId)}" style="display: none;"><td colspan="6" style="padding: 12px; background: var(--bg); border-bottom: 1px solid var(--border);"><div class="panel-empty"><span class="brand-spinner"></span> Loading Line truncated
</div>`);const x=document.getElementById("health-modal"),B=document.getElementById("health-check-btn"),A=document.getElementById("health-cancel"),C=document.getElementById("health-refresh-btn"),M=document.getElementById("health-status-container"),P=document.getElementById("health-incidents-container"),z=document.getElementById("health-config-container"),N=document.getElementById("health-last-update"),f=document.getElementById("health-add-btn"),L=document.getElementById("health-config-form"),w=document.getElementById("health-form-title"),$=document.getElementById("health-form-cancel"),k=document.getElementById("health-form-save"),T="dashcaddy-health-settings",E={retentionDays:30,pollingInterval:60,statsPollingInterval:30,maxEntriesPerService:500,diskUsageThreshold:80},I=document.getElementById("health-global-save"),j=document.getElementById("health-global-reset"),H=document.getElementById("health-global-status"),R=document.getElementById("health-setting-retention"),D=document.getElementById("health-setting-interval"),O=document.getElementById("health-setting-stats-interval"),p=document.getElementById("health-setting-max-entries"),v=document.getElementById("health-setting-disk-threshold");function b(){try{const r=safeGet(T),n=r?JSON.parse(r):{};return Object.assign({},E,n)}catch{return Object.assign({},E)}}function y(){const r=b();R&&(R.value=r.retentionDays),D&&(D.value=r.pollingInterval),O&&(O.value=r.statsPollingInterval),p&&(p.value=r.maxEntriesPerService),v&&(v.value=r.diskUsageThreshold)}function h(){const r={retentionDays:Math.max(1,Math.min(3650,parseInt(R?.value)||E.retentionDays)),pollingInterval:Math.max(5,Math.min(3600,parseInt(D?.value)||E.pollingInterval)),statsPollingInterval:Math.max(5,Math.min(3600,parseInt(O?.value)||E.statsPollingInterval)),maxEntriesPerService:Math.max(10,Math.min(1e5,parseInt(p?.value)||E.maxEntriesPerService)),diskUsageThreshold:Math.max(50,Math.min(99,parseInt(v?.value)||E.diskUsageThreshold))};try{safeSet(T,JSON.stringify(r)),y(),H&&(H.textContent="Saved \u2713",H.style.color="var(--ok-fg)",setTimeout(()=>{H&&(H.textContent="")},2500)),typeof showNotification=="function"&&showNotification("Global health settings saved","success")}catch(n){H&&(H.textContent="Save failed",H.style.color="var(--bad-fg)"),typeof showNotification=="function"&&showNotification("Failed to save settings: "+n.message,"error")}}function s(){try{safeSet(T,JSON.stringify(E))}catch{}y(),H&&(H.textContent="Reset to defaults \u2713",H.style.color="var(--ok-fg)",setTimeout(()=>{H&&(H.textContent="")},2500))}y(),I?.addEventListener("click",h),j?.addEventListener("click",s);let c=null;function l(r){return r>=99.9?"var(--ok-fg)":r>=95?"#f39c12":"var(--bad-fg)"}function m(r){const n={critical:"var(--bad-fg)",high:"#ff6b6b",medium:"#f39c12",low:"var(--muted)"};return`<span style="padding: 2px 8px; border-radius: 4px; font-size: 0.75rem; background: ${n[r]||"var(--muted)"}20; color: ${n[r]||"var(--muted)"};">${r}</span>`}async function u(){try{const n=await(await fetch("/api/v1/health-checks/status")).json();if(!n.success||!n.status||Object.keys(n.status).length===0){M.innerHTML='<div class="panel-empty"><span class="empty-icon">\u{1F3E5}</span>No health checks configured. Go to the Configure tab to add services.</div>';return}const i=Object.values(n.status);let d='<table style="width: 100%; border-collapse: collapse; font-size: 0.85rem;">';d+='<tr style="border-bottom: 1px solid var(--border); color: var(--muted); text-align: left;">',d+='<th style="padding: 8px;">Service</th><th style="padding: 8px;">Status</th>',d+='<th style="padding: 8px;">Uptime 24h</th><th style="padding: 8px;">Uptime 7d</th>',d+='<th style="padding: 8px;">Avg Response</th><th style="padding: 8px;">Last Check</th></tr>';for(const g of i){const S=g.status==="up",U=S?"var(--dot-ok)":"var(--dot-bad)",q=g.uptime?.["24h"]??"-",F=g.uptime?.["7d"]??"-",_=g.avgResponseTime!=null?Math.round(g.avgResponseTime)+"ms":"-",J=g.timestamp?timeAgo(g.timestamp):"-";d+=`<tr style="border-bottom: 1px solid var(--border); cursor: pointer;" data-health-id="${escapeHtml(g.serviceId)}">`,d+=`<td style="padding: 8px; font-weight: 500;">${escapeHtml(g.name||g.serviceId)}</td>`,d+=`<td style="padding: 8px;"><span style="display: inline-block; width: 8px; height: 8px; border-radius: 50%; background: ${U}; margin-right: 6px;"></span>${S?"Up":"Down"}</td>`,d+=`<td style="padding: 8px; color: ${typeof q=="number"?l(q):"var(--muted)"};">${typeof q=="number"?q.toFixed(1)+"%":q}</td>`,d+=`<td style="padding: 8px; color: ${typeof F=="number"?l(F):"var(--muted)"};">${typeof F=="number"?F.toFixed(1)+"%":F}</td>`,d+=`<td style="padding: 8px;">${_}</td>`,d+=`<td style="padding: 8px; color: var(--muted);">${J}</td>`,d+="</tr>",d+=`<tr id="health-detail-${escapeHtml(g.serviceId)}" style="display: none;"><td colspan="6" style="padding: 12px; background: var(--bg); border-bottom: 1px solid var(--border);"><div class="panel-empty"><span class="brand-spinner"></span> Loading Line truncated
<div style="display: grid; grid-template-columns: repeat(4, 1fr); gap: 12px; font-size: 0.82rem;">
<div><span style="color: var(--muted);">Total Checks</span><br><strong>${q.totalChecks||0}</strong></div>
<div><span style="color: var(--muted);">Uptime</span><br><strong style="color: ${d(q.uptime||0)};">${(q.uptime||0).toFixed(2)}%</strong></div>
<div><span style="color: var(--muted);">Total Checks</span><br><strong>${_.totalChecks||0}</strong></div>
<div><span style="color: var(--muted);">Uptime</span><br><strong style="color: ${l(_.uptime||0)};">${(_.uptime||0).toFixed(2)}%</strong></div>
<div><span style="color: var(--muted);">Avg Response</span><br><strong>${Math.round(J.avg||0)}ms</strong></div>
<div><span style="color: var(--muted);">P95 / P99</span><br><strong>${Math.round(J.p95||0)}ms / ${Math.round(J.p99||0)}ms</strong></div>
<div><span style="color: var(--muted);">Min Response</span><br><strong>${Math.round(J.min||0)}ms</strong></div>
<div><span style="color: var(--muted);">Max Response</span><br><strong>${Math.round(J.max||0)}ms</strong></div>
<div><span style="color: var(--muted);">Up Checks</span><br><strong style="color: var(--ok-fg);">${q.upChecks||0}</strong></div>
<div><span style="color: var(--muted);">Down Checks</span><br><strong style="color: var(--bad-fg);">${q.downChecks||0}</strong></div>
</div>`}else O.querySelector("td").innerHTML='<div class="panel-empty">No detailed stats available for this period.</div>'}catch(_){O.querySelector("td").innerHTML=`<div class="panel-empty" style="color: var(--bad-fg);">Failed: ${escapeHtml(_.message)}</div>`}}})})}catch(i){M.innerHTML=`<div class="panel-empty" style="color: var(--bad-fg);">Failed to load health status: ${escapeHtml(i.message)}</div>`}}async function t(){try{const[i,n]=await Promise.all([fetch("/api/v1/health-checks/incidents"),fetch("/api/v1/health-checks/incidents/history?limit=50")]),s=await i.json(),l=await n.json();let p="";const w=s.success&&s.incidents?s.incidents:[];if(w.length>0){p+='<div style="margin-bottom: 16px;"><h4 style="color: var(--bad-fg); margin: 0 0 8px;">Open Incidents ('+w.length+")</h4>";for(const _ of w)p+=`<div style="padding: 10px 12px; margin-bottom: 8px; border: 1px solid var(--bad-fg)30; border-radius: 8px; background: var(--bad-bg);">
<div><span style="color: var(--muted);">Up Checks</span><br><strong style="color: var(--ok-fg);">${_.upChecks||0}</strong></div>
<div><span style="color: var(--muted);">Down Checks</span><br><strong style="color: var(--bad-fg);">${_.downChecks||0}</strong></div>
</div>`}else U.querySelector("td").innerHTML='<div class="panel-empty">No detailed stats available for this period.</div>'}catch(q){U.querySelector("td").innerHTML=`<div class="panel-empty" style="color: var(--bad-fg);">Failed: ${escapeHtml(q.message)}</div>`}}})})}catch(r){M.innerHTML=`<div class="panel-empty" style="color: var(--bad-fg);">Failed to load health status: ${escapeHtml(r.message)}</div>`}}async function t(){try{const[r,n]=await Promise.all([fetch("/api/v1/health-checks/incidents"),fetch("/api/v1/health-checks/incidents/history?limit=50")]),i=await r.json(),d=await n.json();let g="";const S=i.success&&i.incidents?i.incidents:[];if(S.length>0){g+='<div style="margin-bottom: 16px;"><h4 style="color: var(--bad-fg); margin: 0 0 8px;">Open Incidents ('+S.length+")</h4>";for(const q of S)g+=`<div style="padding: 10px 12px; margin-bottom: 8px; border: 1px solid var(--bad-fg)30; border-radius: 8px; background: var(--bad-bg);">
<div style="display: flex; justify-content: space-between; align-items: center;">
<span style="font-weight: 500;">${escapeHtml(_.serviceId)}</span>
<span>${b(_.severity)}</span>
<span style="font-weight: 500;">${escapeHtml(q.serviceId)}</span>
<span>${m(q.severity)}</span>
</div>
<div style="font-size: 0.82rem; color: var(--muted); margin-top: 4px;">${escapeHtml(_.message)}</div>
<div style="font-size: 0.75rem; color: var(--muted); margin-top: 4px;">Started ${timeAgo(_.createdAt)} \xB7 ${_.occurrences||1} occurrence(s)</div>
</div>`;p+="</div>"}else p+='<div style="padding: 12px; margin-bottom: 16px; border: 1px solid var(--ok-fg)30; border-radius: 8px; background: var(--ok-bg); text-align: center; color: var(--ok-fg); font-size: 0.9rem;">All services operational \u2014 no open incidents</div>';const O=l.success&&l.history?l.history:[];if(O.length>0){p+='<h4 style="margin: 0 0 8px; color: var(--muted);">Incident History</h4>',p+='<table style="width: 100%; border-collapse: collapse; font-size: 0.82rem;">',p+='<tr style="border-bottom: 1px solid var(--border); color: var(--muted);"><th style="padding: 6px; text-align: left;">Service</th><th style="padding: 6px; text-align: left;">Type</th><th style="padding: 6px; text-align: left;">Severity</th><th style="padding: 6px; text-align: left;">Status</th><th style="padding: 6px; text-align: left;">Duration</th><th style="padding: 6px; text-align: left;">When</th></tr>';for(const _ of O){const F=_.status==="resolved",q=F&&_.duration?_.duration<6e4?Math.round(_.duration/1e3)+"s":Math.round(_.duration/6e4)+"m":"-";p+='<tr style="border-bottom: 1px solid var(--border);">',p+=`<td style="padding: 6px;">${escapeHtml(_.serviceId)}</td>`,p+=`<td style="padding: 6px;">${escapeHtml(_.type)}</td>`,p+=`<td style="padding: 6px;">${b(_.severity)}</td>`,p+=`<td style="padding: 6px;"><span style="color: ${F?"var(--ok-fg)":"var(--bad-fg)"};">${_.status}</span></td>`,p+=`<td style="padding: 6px;">${q}</td>`,p+=`<td style="padding: 6px; color: var(--muted);">${timeAgo(_.createdAt)}</td>`,p+="</tr>"}p+="</table>"}P.innerHTML=p||'<div class="panel-empty"><span class="empty-icon">\u{1F6A8}</span>No incidents recorded yet.</div>'}catch(i){P.innerHTML=`<div class="panel-empty" style="color: var(--bad-fg);">Failed: ${escapeHtml(i.message)}</div>`}}async function e(){try{const n=await(await fetch("/api/v1/health-checks/status")).json(),s=n.success&&n.status?Object.values(n.status):[];if(s.length===0){z.innerHTML='<div class="panel-empty"><span class="empty-icon">\u2699\uFE0F</span>No health checks configured yet. Click "Add Health Check" below.</div>';return}let l='<table style="width: 100%; border-collapse: collapse; font-size: 0.85rem;">';l+='<tr style="border-bottom: 1px solid var(--border); color: var(--muted);"><th style="padding: 8px; text-align: left;">Service</th><th style="padding: 8px; text-align: left;">Status</th><th style="padding: 8px; text-align: left;">SLA Target</th><th style="padding: 8px; text-align: right;">Actions</th></tr>';for(const p of s){const w=p.status==="up";l+='<tr style="border-bottom: 1px solid var(--border);">',l+=`<td style="padding: 8px; font-weight: 500;">${escapeHtml(p.name||p.serviceId)}</td>`,l+=`<td style="padding: 8px; color: ${w?"var(--ok-fg)":"var(--bad-fg)"};">${w?"Up":"Down"}</td>`,l+=`<td style="padding: 8px;">${p.sla?.target?p.sla.target+"%":"-"}</td>`,l+='<td style="padding: 8px; text-align: right;">',l+=`<button onclick="document.dispatchEvent(new CustomEvent('health-edit', {detail:'${escapeHtml(p.serviceId)}'}))" style="padding: 4px 10px; font-size: 0.78rem; margin-right: 4px;">Edit</button>`,l+=`<button onclick="document.dispatchEvent(new CustomEvent('health-delete', {detail:'${escapeHtml(p.serviceId)}'}))" style="padding: 4px 10px; font-size: 0.78rem; color: var(--bad-fg); border-color: var(--bad-fg);">Delete</button>`,l+="</td></tr>"}l+="</table>",z.innerHTML=l}catch(i){z.innerHTML=`<div class="panel-empty" style="color: var(--bad-fg);">Failed: ${escapeHtml(i.message)}</div>`}}function a(i,n,s,l,p,w,O){c=i||null,x.textContent=i?"Edit Health Check":"Add Health Check",document.getElementById("health-form-id").value=i||"",document.getElementById("health-form-id").disabled=!!i,document.getElementById("health-form-name").value=n||"",document.getElementById("health-form-url").value=s||"",document.getElementById("health-form-timeout").value=l||1e4,document.getElementById("health-form-codes").value=p||"200",document.getElementById("health-form-sla").value=w||99.9,document.getElementById("health-form-slow").value=O||5e3,B.style.display="",v.style.display="none"}function o(){B.style.display="none",v.style.display="",c=null}v?.addEventListener("click",()=>a("","","",1e4,"200",99.9,5e3)),$?.addEventListener("click",o),k?.addEventListener("click",async()=>{const i=c||document.getElementById("health-form-id").value.trim();if(!i)return showNotification("Service ID is required","warning");const n=document.getElementById("health-form-url").value.trim();if(!n)return showNotification("URL is required","warning");const s=document.getElementById("health-form-codes").value.split(",").map(p=>parseInt(p.trim())).filter(Boolean),l={name:document.getElementById("health-form-name").value.trim()||i,url:n,timeout:parseInt(document.getElementById("health-form-timeout").value)||1e4,expectedStatusCodes:s.length?s:[200],sla:{target:parseFloat(document.getElementById("health-form-sla").value)||99.9},slowResponseThreshold:parseInt(document.getElementById("health-form-slow").value)|Line truncated
<div style="font-size: 0.82rem; color: var(--muted); margin-top: 4px;">${escapeHtml(q.message)}</div>
<div style="font-size: 0.75rem; color: var(--muted); margin-top: 4px;">Started ${timeAgo(q.createdAt)} \xB7 ${q.occurrences||1} occurrence(s)</div>
</div>`;g+="</div>"}else g+='<div style="padding: 12px; margin-bottom: 16px; border: 1px solid var(--ok-fg)30; border-radius: 8px; background: var(--ok-bg); text-align: center; color: var(--ok-fg); font-size: 0.9rem;">All services operational \u2014 no open incidents</div>';const U=d.success&&d.history?d.history:[];if(U.length>0){g+='<h4 style="margin: 0 0 8px; color: var(--muted);">Incident History</h4>',g+='<table style="width: 100%; border-collapse: collapse; font-size: 0.82rem;">',g+='<tr style="border-bottom: 1px solid var(--border); color: var(--muted);"><th style="padding: 6px; text-align: left;">Service</th><th style="padding: 6px; text-align: left;">Type</th><th style="padding: 6px; text-align: left;">Severity</th><th style="padding: 6px; text-align: left;">Status</th><th style="padding: 6px; text-align: left;">Duration</th><th style="padding: 6px; text-align: left;">When</th></tr>';for(const q of U){const F=q.status==="resolved",_=F&&q.duration?q.duration<6e4?Math.round(q.duration/1e3)+"s":Math.round(q.duration/6e4)+"m":"-";g+='<tr style="border-bottom: 1px solid var(--border);">',g+=`<td style="padding: 6px;">${escapeHtml(q.serviceId)}</td>`,g+=`<td style="padding: 6px;">${escapeHtml(q.type)}</td>`,g+=`<td style="padding: 6px;">${m(q.severity)}</td>`,g+=`<td style="padding: 6px;"><span style="color: ${F?"var(--ok-fg)":"var(--bad-fg)"};">${q.status}</span></td>`,g+=`<td style="padding: 6px;">${_}</td>`,g+=`<td style="padding: 6px; color: var(--muted);">${timeAgo(q.createdAt)}</td>`,g+="</tr>"}g+="</table>"}P.innerHTML=g||'<div class="panel-empty"><span class="empty-icon">\u{1F6A8}</span>No incidents recorded yet.</div>'}catch(r){P.innerHTML=`<div class="panel-empty" style="color: var(--bad-fg);">Failed: ${escapeHtml(r.message)}</div>`}}async function e(){try{const n=await(await fetch("/api/v1/health-checks/status")).json(),i=n.success&&n.status?Object.values(n.status):[];if(i.length===0){z.innerHTML='<div class="panel-empty"><span class="empty-icon">\u2699\uFE0F</span>No health checks configured yet. Click "Add Health Check" below.</div>';return}let d='<table style="width: 100%; border-collapse: collapse; font-size: 0.85rem;">';d+='<tr style="border-bottom: 1px solid var(--border); color: var(--muted);"><th style="padding: 8px; text-align: left;">Service</th><th style="padding: 8px; text-align: left;">Status</th><th style="padding: 8px; text-align: left;">SLA Target</th><th style="padding: 8px; text-align: right;">Actions</th></tr>';for(const g of i){const S=g.status==="up";d+='<tr style="border-bottom: 1px solid var(--border);">',d+=`<td style="padding: 8px; font-weight: 500;">${escapeHtml(g.name||g.serviceId)}</td>`,d+=`<td style="padding: 8px; color: ${S?"var(--ok-fg)":"var(--bad-fg)"};">${S?"Up":"Down"}</td>`,d+=`<td style="padding: 8px;">${g.sla?.target?g.sla.target+"%":"-"}</td>`,d+='<td style="padding: 8px; text-align: right;">',d+=`<button onclick="document.dispatchEvent(new CustomEvent('health-edit', {detail:'${escapeHtml(g.serviceId)}'}))" style="padding: 4px 10px; font-size: 0.78rem; margin-right: 4px;">Edit</button>`,d+=`<button onclick="document.dispatchEvent(new CustomEvent('health-delete', {detail:'${escapeHtml(g.serviceId)}'}))" style="padding: 4px 10px; font-size: 0.78rem; color: var(--bad-fg); border-color: var(--bad-fg);">Delete</button>`,d+="</td></tr>"}d+="</table>",z.innerHTML=d}catch(r){z.innerHTML=`<div class="panel-empty" style="color: var(--bad-fg);">Failed: ${escapeHtml(r.message)}</div>`}}function a(r,n,i,d,g,S,U){c=r||null,w.textContent=r?"Edit Health Check":"Add Health Check",document.getElementById("health-form-id").value=r||"",document.getElementById("health-form-id").disabled=!!r,document.getElementById("health-form-name").value=n||"",document.getElementById("health-form-url").value=i||"",document.getElementById("health-form-timeout").value=d||1e4,document.getElementById("health-form-codes").value=g||"200",document.getElementById("health-form-sla").value=S||99.9,document.getElementById("health-form-slow").value=U||5e3,L.style.display="",f.style.display="none"}function o(){L.style.display="none",f.style.display="",c=null}f?.addEventListener("click",()=>a("","","",1e4,"200",99.9,5e3)),$?.addEventListener("click",o),k?.addEventListener("click",async()=>{const r=c||document.getElementById("health-form-id").value.trim();if(!r)return showNotification("Service ID is required","warning");const n=document.getElementById("health-form-url").value.trim();if(!n)return showNotification("URL is required","warning");const i=document.getElementById("health-form-codes").value.split(",").map(g=>parseInt(g.trim())).filter(Boolean),d={name:document.getElementById("health-form-name").value.trim()||r,url:n,timeout:parseInt(document.getElementById("health-form-timeout").value)||1e4,expectedStatusCodes:i.length?i:[200],sla:{target:parseFloat(document.getElementById("health-form-sla").value)||99.9},slowResponseThreshold:parseInt(document.getElementById("health-form-slow").value)|Line truncated
<div class="weather-modal-content" style="min-width: 750px; max-width: 950px;">
<h3>\u2B06\uFE0F Update Management</h3>
<p class="modal-subtitle">
@@ -1543,17 +1582,17 @@ This will replace current configuration, credentials, and data. Containers will
<button id="updates-cancel">Close</button>
</div>
</div>
</div>`);const f=document.getElementById("updates-modal"),I=document.getElementById("updates-btn"),A=document.getElementById("updates-cancel"),E=document.getElementById("updates-check-btn"),M=document.getElementById("updates-available-container"),P=document.getElementById("updates-history-container"),z=document.getElementById("updates-auto-container"),D=document.getElementById("updates-last-check");async function v(){try{const t=await(await fetch("/api/v1/updates/available")).json();if(!t.success)throw new Error(t.error);const e=t.updates||[];if(e.length===0){M.innerHTML='<div class="panel-empty"><span class="empty-icon">\u2705</span>All containers are up to date.</div>',D.textContent="",document.getElementById("updates-update-all-btn").style.display="none",document.getElementById("updates-count-badge").style.display="none",window._pendingUpdates=[];return}let a='<table style="width: 100%; border-collapse: collapse; font-size: 0.85rem;">';a+='<tr style="border-bottom: 1px solid var(--border); color: var(--muted);"><th style="padding: 8px; text-align: left;">Container</th><th style="padding: 8px; text-align: left;">Image</th><th style="padding: 8px; text-align: left;">Current</th><th style="padding: 8px; text-align: left;">Latest</th><th style="padding: 8px; text-align: right;">Actions</th></tr>';for(const n of e){const s=(()=>{const l=window.APPS||[];for(const p of l)if(p.containerId===n.containerId||p.name===n.containerName||p.id===n.containerName)return p.id;return n.containerName})();a+=`<tr data-app-id="${escapeHtml(s)}" style="border-bottom: 1px solid var(--border);">`,a+=`<td style="padding: 8px; font-weight: 500;">${escapeHtml(n.containerName)}</td>`,a+=`<td style="padding: 8px; color: var(--muted);">${escapeHtml(n.imageName)}</td>`,a+=`<td style="padding: 8px;"><code style="font-size: 0.78rem; background: var(--bg); padding: 2px 6px; border-radius: 4px;">${escapeHtml(n.currentDigest)}</code></td>`,a+=`<td style="padding: 8px;"><code style="font-size: 0.78rem; background: var(--ok-bg); color: var(--ok-fg); padding: 2px 6px; border-radius: 4px;">${escapeHtml(n.latestDigest)}</code></td>`,a+='<td style="padding: 8px; text-align: right;">',a+=`<button class="update-now-btn" data-id="${escapeHtml(n.containerId)}" data-name="${escapeHtml(n.containerName)}" style="padding: 4px 10px; font-size: 0.78rem; background: var(--accent); color: var(--bg); border-color: var(--accent); margin-right: 4px;">Update</button>`,a+=`<button class="rollback-btn" data-id="${escapeHtml(n.containerId)}" data-name="${escapeHtml(n.containerName)}" style="padding: 4px 10px; font-size: 0.78rem;">Rollback</button>`,a+="</td></tr>"}a+="</table>",M.innerHTML=a,D.textContent=e.length+" update(s) available";const o=document.getElementById("updates-count-badge"),i=document.getElementById("updates-update-all-btn");o&&(o.textContent=e.length+" pending",o.style.display=""),i&&e.length>0&&(i.style.display=""),window._pendingUpdates=e,M.querySelectorAll(".update-now-btn").forEach(n=>{n.addEventListener("click",async()=>{const s=n.dataset.id,l=n.dataset.name;if(confirm(`Update "${l}" to the latest version? The container will restart.`)){n.textContent="Updating...",n.disabled=!0;try{const w=await(await secureFetch(`/api/v1/updates/update/${encodeURIComponent(s)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({autoRollback:!0})})).json();if(w.success)n.textContent="Done!",n.style.background="var(--ok-fg)",setTimeout(()=>v(),2e3);else throw new Error(w.error||"Update failed")}catch(p){n.textContent="Failed",n.style.color="var(--bad-fg)",showNotification("Update error: "+p.message,"error"),setTimeout(()=>{n.textContent="Update",n.disabled=!1,n.style.color="",n.style.background=""},3e3)}}})}),M.querySelectorAll(".rollback-btn").forEach(n=>{n.addEventListener("click",async()=>{const s=n.dataset.id,l=n.dataset.name;if(confirm(`Rollback "${l}" to its previous version?`)){n.textContent="Rolling back...",n.disabled=!0;try{const w=await(await secureFetch(`/api/v1/updates/rollback/${encodeURIComponent(s)}`,{method:"POST"})).json();if(w.success)n.textContent="Rolled back!",setTimeout(()=>v(),2e3);else throw new Error(w.error||"Rollback failed")}catch(p){n.textContent="Failed",showNotification("Rollback error: "+p.message,"error"),setTimeout(()=>{n.textContent="Rollback",n.disabled=!1},3e3)}}})})}catch(y){M.innerHTML=`<div class="panel-empty" style="color: var(--bad-fg);">Failed: ${escapeHtml(y.message)}</div>`}}async function B(){const y=window._pendingUpdates||[];if(!y.length)return;const t=document.getElementById("updates-update-all-btn");if(!confirm(`Update all ${y.length} containers? Each will restart.`))return;t.textContent="\u23F3 Updating...",t.disabled=!0;let e=0,a=0;for(const o of y)try{(await(await secureFetch(`/api/v1/updates/update/${encodeURIComponent(o.containerId)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({autoRollback:!0})})).json()).success?e++:a++}catch{a++}t.textCLine truncated
<select class="auto-schedule" data-id="${escapeHtml(p)}" style="padding: 4px 8px; border-radius: 4px; border: 1px solid var(--border); background: var(--bg); color: var(--fg); font-size: 0.82rem;">
<option value=""${O?"":" selected"}>Disabled</option>
<option value="daily"${O==="daily"?" selected":""}>Daily</option>
<option value="weekly"${O==="weekly"?" selected":""}>Weekly</option>
<option value="monthly"${O==="monthly"?" selected":""}>Monthly</option>
</select></td>`,n+=`<td style="padding: 8px;"><input type="text" class="auto-window" data-id="${escapeHtml(p)}" value="${escapeHtml(F)}" placeholder="02:00-04:00" style="width: 90px; padding: 3px 6px; font-size: 0.78rem; border: 1px solid var(--border); border-radius: 4px; background: var(--bg); color: var(--fg);" /></td>`,n+=`<td style="padding: 8px;"><input type="checkbox" class="auto-rollback" data-id="${escapeHtml(p)}"${_?" checked":""} /></td>`,n+=`<td style="padding: 8px; font-size: 0.78rem; color: var(--muted);">${q}</td>`,n+=`<td style="padding: 8px; text-align: right;"><button class="save-auto-btn" data-id="${escapeHtml(p)}" data-name="${escapeHtml(l)}" style="padding: 4px 10px; font-size: 0.78rem;">Save</button></td>`,n+="</tr>"}n+="</table>",z.innerHTML=n,z.querySelectorAll(".save-auto-btn").forEach(s=>{s.addEventListener("click",async()=>{const l=s.dataset.id,p=s.closest("tr"),w=p.querySelector(".auto-schedule").value,O=p.querySelector(".auto-rollback").checked,_=p.querySelector(".auto-window").value.trim();s.textContent="Saving...",s.disabled=!0;try{const q=await(await secureFetch(`/api/v1/updates/auto-update/${encodeURIComponent(l)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({enabled:!!w,schedule:w||"weekly",autoRollback:O,maintenanceWindow:_||void 0})})).json();if(q.success)s.textContent="\u2713 Saved";else throw new Error(q.error)}catch(F){s.textContent="\u2717 Error",showNotification("Save error: "+F.message,"error")}setTimeout(()=>{s.textContent="Save",s.disabled=!1},2e3)})})}catch(y){z.innerHTML=`<div class="panel-empty" style="color: var(--bad-fg);">Failed: ${escapeHtml(y.message)}</div>`}}const T=document.getElementById("dashcaddy-current-version"),S=document.getElementById("dashcaddy-update-badge"),L=document.getElementById("dashcaddy-update-details"),j=document.getElementById("dashcaddy-new-version"),C=document.getElementById("dashcaddy-changelog"),N=document.getElementById("dashcaddy-apply-btn"),R=document.getElementById("dashcaddy-check-btn"),U=document.getElementById("dashcaddy-rollback-btn"),u=document.getElementById("dashcaddy-status-bar"),m=document.getElementById("dashcaddy-history-container");let h=null;function g(y,t){u&&(u.style.display="block",u.style.background=t==="error"?"var(--bad-bg)":t==="success"?"var(--ok-bg)":"var(--bg)",u.style.color=t==="error"?"var(--bad-fg)":t==="success"?"var(--ok-fg)":"var(--fg)",u.textContent=y)}async function H(){try{const t=await(await fetch("/api/v1/system/version")).json();if(t.success){const e=t.commit&&t.commit!=="unknown"?t.commit:null;T.textContent="v"+t.version+(e?" ("+e.substring(0,7)+")":"")}}catch{T.textContent="Unable to fetch version"}}async function r(y){y||(R.textContent="Checking...",R.disabled=!0);try{const e=await(await fetch("/api/v1/system/update-check")).json();if(h=e,e.success&&e.available&&e.remote){S.style.display="",L.style.display="",j.textContent="v"+e.remote.version,C.textContent=e.remote.changelog||"No changelog available.";const a=document.getElementById("updates-btn");if(a&&!a.querySelector(".update-dot")){const i=document.createElement("span");i.className="update-dot",i.style.cssText="position:absolute;top:2px;right:2px;width:8px;height:8px;border-radius:50%;background:var(--accent);",a.style.position="relative",a.appendChild(i)}const o=document.getElementById("updates-dashcaddy-tab");if(o&&!o.querySelector(".update-dot")){const i=document.createElement("span");i.className="update-dot",i.style.cssText="display:inline-block;width:6px;height:6px;border-radius:50%;background:var(--accent);margin-left:4px;vertical-align:middle;",o.appendChild(i)}}else S.style.display="none",L.style.display="none",await H(),y||g("You are running the latest version.","success");y||(R.textContent="Check for Updates",R.disabled=!1)}catch(t){y||(g("Failed to check: "+t.message,"error"),R.textContent="Check for Updates",R.disabled=!1)}}async function c(){if(!confirm("Apply DashCaddy update? The API container will restart."))return!1;N.textContent="Updating...",N.disabled=!0,g("Downloading and applying update...","info");try{const t=await(await secureFetch("/api/v1/system/update-apply",{method:"POST"})).json();if(t.success)return g("Update initiated: v"+(t.fromVersion||"?")+" \u2192 v"+(t.toVersion||"?")+". The container will restart shortly.","success"),N.textContent="Applied!",document.querySelectorAll(".update-dot").forEach(e=>e.remove()),!0;throw new Error(t.error||"Update failed")}catch(y){throw g("Update failed: "+y.message,"error"),N.textContent="Update Now",N.disabled=!1,y}}async function d(){try{const t=await(await fetch("/api/v1/system/update-history")).json(),e=t.success&&t.history?t.history:[];if(e.length===0){m.innerHTML='<div class="panel-empty"><span class="empty-icon">\u{1F4E6}</span>No self-update history.</div>';return}let a='<table style="width: 100%; border-collapse: collapse; font-size: 0.82rem;">';a+='<tr style="border-bottom: 1px solid var(--border); color: var(--mutLine truncated
</div>`);const x=document.getElementById("updates-modal"),B=document.getElementById("updates-btn"),A=document.getElementById("updates-cancel"),C=document.getElementById("updates-check-btn"),M=document.getElementById("updates-available-container"),P=document.getElementById("updates-history-container"),z=document.getElementById("updates-auto-container"),N=document.getElementById("updates-last-check");async function f(){try{const t=await(await fetch("/api/v1/updates/available")).json();if(!t.success)throw new Error(t.error);const e=t.updates||[];if(e.length===0){M.innerHTML='<div class="panel-empty"><span class="empty-icon">\u2705</span>All containers are up to date.</div>',N.textContent="",document.getElementById("updates-update-all-btn").style.display="none",document.getElementById("updates-count-badge").style.display="none",window._pendingUpdates=[];return}let a='<table style="width: 100%; border-collapse: collapse; font-size: 0.85rem;">';a+='<tr style="border-bottom: 1px solid var(--border); color: var(--muted);"><th style="padding: 8px; text-align: left;">Container</th><th style="padding: 8px; text-align: left;">Image</th><th style="padding: 8px; text-align: left;">Current</th><th style="padding: 8px; text-align: left;">Latest</th><th style="padding: 8px; text-align: right;">Actions</th></tr>';for(const n of e){const i=(()=>{const d=window.APPS||[];for(const g of d)if(g.containerId===n.containerId||g.name===n.containerName||g.id===n.containerName)return g.id;return n.containerName})();a+=`<tr data-app-id="${escapeHtml(i)}" style="border-bottom: 1px solid var(--border);">`,a+=`<td style="padding: 8px; font-weight: 500;">${escapeHtml(n.containerName)}</td>`,a+=`<td style="padding: 8px; color: var(--muted);">${escapeHtml(n.imageName)}</td>`,a+=`<td style="padding: 8px;"><code style="font-size: 0.78rem; background: var(--bg); padding: 2px 6px; border-radius: 4px;">${escapeHtml(n.currentDigest)}</code></td>`,a+=`<td style="padding: 8px;"><code style="font-size: 0.78rem; background: var(--ok-bg); color: var(--ok-fg); padding: 2px 6px; border-radius: 4px;">${escapeHtml(n.latestDigest)}</code></td>`,a+='<td style="padding: 8px; text-align: right;">',a+=`<button class="update-now-btn" data-id="${escapeHtml(n.containerId)}" data-name="${escapeHtml(n.containerName)}" style="padding: 4px 10px; font-size: 0.78rem; background: var(--accent); color: var(--bg); border-color: var(--accent); margin-right: 4px;">Update</button>`,a+=`<button class="rollback-btn" data-id="${escapeHtml(n.containerId)}" data-name="${escapeHtml(n.containerName)}" style="padding: 4px 10px; font-size: 0.78rem;">Rollback</button>`,a+="</td></tr>"}a+="</table>",M.innerHTML=a,N.textContent=e.length+" update(s) available";const o=document.getElementById("updates-count-badge"),r=document.getElementById("updates-update-all-btn");o&&(o.textContent=e.length+" pending",o.style.display=""),r&&e.length>0&&(r.style.display=""),window._pendingUpdates=e,M.querySelectorAll(".update-now-btn").forEach(n=>{n.addEventListener("click",async()=>{const i=n.dataset.id,d=n.dataset.name;if(confirm(`Update "${d}" to the latest version? The container will restart.`)){n.textContent="Updating...",n.disabled=!0;try{const S=await(await secureFetch(`/api/v1/updates/update/${encodeURIComponent(i)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({autoRollback:!0})})).json();if(S.success)n.textContent="Done!",n.style.background="var(--ok-fg)",setTimeout(()=>f(),2e3);else throw new Error(S.error||"Update failed")}catch(g){n.textContent="Failed",n.style.color="var(--bad-fg)",showNotification("Update error: "+g.message,"error"),setTimeout(()=>{n.textContent="Update",n.disabled=!1,n.style.color="",n.style.background=""},3e3)}}})}),M.querySelectorAll(".rollback-btn").forEach(n=>{n.addEventListener("click",async()=>{const i=n.dataset.id,d=n.dataset.name;if(confirm(`Rollback "${d}" to its previous version?`)){n.textContent="Rolling back...",n.disabled=!0;try{const S=await(await secureFetch(`/api/v1/updates/rollback/${encodeURIComponent(i)}`,{method:"POST"})).json();if(S.success)n.textContent="Rolled back!",setTimeout(()=>f(),2e3);else throw new Error(S.error||"Rollback failed")}catch(g){n.textContent="Failed",showNotification("Rollback error: "+g.message,"error"),setTimeout(()=>{n.textContent="Rollback",n.disabled=!1},3e3)}}})})}catch(u){M.innerHTML=`<div class="panel-empty" style="color: var(--bad-fg);">Failed: ${escapeHtml(u.message)}</div>`}}async function L(){const u=window._pendingUpdates||[];if(!u.length)return;const t=document.getElementById("updates-update-all-btn");if(!confirm(`Update all ${u.length} containers? Each will restart.`))return;t.textContent="\u23F3 Updating...",t.disabled=!0;let e=0,a=0;for(const o of u)try{(await(await secureFetch(`/api/v1/updates/update/${encodeURIComponent(o.containerId)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({autoRollback:!0})})).json()).success?e++:a++}catch{a++}t.textCLine truncated
<select class="auto-schedule" data-id="${escapeHtml(g)}" style="padding: 4px 8px; border-radius: 4px; border: 1px solid var(--border); background: var(--bg); color: var(--fg); font-size: 0.82rem;">
<option value=""${U?"":" selected"}>Disabled</option>
<option value="daily"${U==="daily"?" selected":""}>Daily</option>
<option value="weekly"${U==="weekly"?" selected":""}>Weekly</option>
<option value="monthly"${U==="monthly"?" selected":""}>Monthly</option>
</select></td>`,n+=`<td style="padding: 8px;"><input type="text" class="auto-window" data-id="${escapeHtml(g)}" value="${escapeHtml(F)}" placeholder="02:00-04:00" style="width: 90px; padding: 3px 6px; font-size: 0.78rem; border: 1px solid var(--border); border-radius: 4px; background: var(--bg); color: var(--fg);" /></td>`,n+=`<td style="padding: 8px;"><input type="checkbox" class="auto-rollback" data-id="${escapeHtml(g)}"${q?" checked":""} /></td>`,n+=`<td style="padding: 8px; font-size: 0.78rem; color: var(--muted);">${_}</td>`,n+=`<td style="padding: 8px; text-align: right;"><button class="save-auto-btn" data-id="${escapeHtml(g)}" data-name="${escapeHtml(d)}" style="padding: 4px 10px; font-size: 0.78rem;">Save</button></td>`,n+="</tr>"}n+="</table>",z.innerHTML=n,z.querySelectorAll(".save-auto-btn").forEach(i=>{i.addEventListener("click",async()=>{const d=i.dataset.id,g=i.closest("tr"),S=g.querySelector(".auto-schedule").value,U=g.querySelector(".auto-rollback").checked,q=g.querySelector(".auto-window").value.trim();i.textContent="Saving...",i.disabled=!0;try{const _=await(await secureFetch(`/api/v1/updates/auto-update/${encodeURIComponent(d)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({enabled:!!S,schedule:S||"weekly",autoRollback:U,maintenanceWindow:q||void 0})})).json();if(_.success)i.textContent="\u2713 Saved";else throw new Error(_.error)}catch(F){i.textContent="\u2717 Error",showNotification("Save error: "+F.message,"error")}setTimeout(()=>{i.textContent="Save",i.disabled=!1},2e3)})})}catch(u){z.innerHTML=`<div class="panel-empty" style="color: var(--bad-fg);">Failed: ${escapeHtml(u.message)}</div>`}}const T=document.getElementById("dashcaddy-current-version"),E=document.getElementById("dashcaddy-update-badge"),I=document.getElementById("dashcaddy-update-details"),j=document.getElementById("dashcaddy-new-version"),H=document.getElementById("dashcaddy-changelog"),R=document.getElementById("dashcaddy-apply-btn"),D=document.getElementById("dashcaddy-check-btn"),O=document.getElementById("dashcaddy-rollback-btn"),p=document.getElementById("dashcaddy-status-bar"),v=document.getElementById("dashcaddy-history-container");let b=null;function y(u,t){p&&(p.style.display="block",p.style.background=t==="error"?"var(--bad-bg)":t==="success"?"var(--ok-bg)":"var(--bg)",p.style.color=t==="error"?"var(--bad-fg)":t==="success"?"var(--ok-fg)":"var(--fg)",p.textContent=u)}async function h(){try{const t=await(await fetch("/api/v1/system/version")).json();if(t.success){const e=t.commit&&t.commit!=="unknown"?t.commit:null;T.textContent="v"+t.version+(e?" ("+e.substring(0,7)+")":"")}}catch{T.textContent="Unable to fetch version"}}async function s(u){u||(D.textContent="Checking...",D.disabled=!0);try{const e=await(await fetch("/api/v1/system/update-check")).json();if(b=e,e.success&&e.available&&e.remote){E.style.display="",I.style.display="",j.textContent="v"+e.remote.version,H.textContent=e.remote.changelog||"No changelog available.";const a=document.getElementById("updates-btn");if(a&&!a.querySelector(".update-dot")){const r=document.createElement("span");r.className="update-dot",r.style.cssText="position:absolute;top:2px;right:2px;width:8px;height:8px;border-radius:50%;background:var(--accent);",a.style.position="relative",a.appendChild(r)}const o=document.getElementById("updates-dashcaddy-tab");if(o&&!o.querySelector(".update-dot")){const r=document.createElement("span");r.className="update-dot",r.style.cssText="display:inline-block;width:6px;height:6px;border-radius:50%;background:var(--accent);margin-left:4px;vertical-align:middle;",o.appendChild(r)}}else E.style.display="none",I.style.display="none",await h(),u||y("You are running the latest version.","success");u||(D.textContent="Check for Updates",D.disabled=!1)}catch(t){u||(y("Failed to check: "+t.message,"error"),D.textContent="Check for Updates",D.disabled=!1)}}async function c(){if(!confirm("Apply DashCaddy update? The API container will restart."))return!1;R.textContent="Updating...",R.disabled=!0,y("Downloading and applying update...","info");try{const t=await(await secureFetch("/api/v1/system/update-apply",{method:"POST"})).json();if(t.success)return y("Update initiated: v"+(t.fromVersion||"?")+" \u2192 v"+(t.toVersion||"?")+". The container will restart shortly.","success"),R.textContent="Applied!",document.querySelectorAll(".update-dot").forEach(e=>e.remove()),!0;throw new Error(t.error||"Update failed")}catch(u){throw y("Update failed: "+u.message,"error"),R.textContent="Update Now",R.disabled=!1,u}}async function l(){try{const t=await(await fetch("/api/v1/system/update-history")).json(),e=t.success&&t.history?t.history:[];if(e.length===0){v.innerHTML='<div class="panel-empty"><span class="empty-icon">\u{1F4E6}</span>No self-update history.</div>';return}let a='<table style="width: 100%; border-collapse: collapse; font-size: 0.82rem;">';a+='<tr style="border-bottom: 1px solid var(--border); color: var(--mutLine truncated
`+e.join(`
`)+`
Enter version to rollback to:`);if(!a)return;if(!e.includes(a)){showNotification("Invalid version: "+a,"error");return}if(!confirm("Rollback DashCaddy to v"+a+"? The container will restart."))return;g("Rolling back to v"+a+"...","info");const i=await(await secureFetch("/api/v1/system/rollback",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({version:a})})).json();if(i.success)g("Rollback to v"+a+" initiated. Container will restart.","success");else throw new Error(i.error||"Rollback failed")}catch(y){g("Rollback failed: "+y.message,"error")}}R?.addEventListener("click",()=>r(!1)),N?.addEventListener("click",()=>c().catch(()=>{})),U?.addEventListener("click",b),E?.addEventListener("click",x),I?.addEventListener("click",()=>{f?.classList.add("show"),v()}),wireModal(f,A),window.openUpdateModal=function(y){f?.classList.add("show"),v().then(()=>{if(!y)return;const t=M.querySelector(`[data-app-id="${y}"]`);t&&(t.scrollIntoView({behavior:"smooth",block:"center"}),t.style.background="rgba(249,115,22,0.15)",setTimeout(()=>{t.style.background=""},3e3))})},document.querySelector('[data-panel="updates-history"]')?.addEventListener("click",$),document.querySelector('[data-panel="updates-auto"]')?.addEventListener("click",k),document.querySelector('[data-panel="updates-dashcaddy"]')?.addEventListener("click",()=>{H(),d(),h||r(!0)}),window.dcApplyUpdate=c,window.dcCheckForUpdate=r,setTimeout(()=>r(!0),5e3)})(),(function(){injectModal("docker-resources-modal",`<div id="docker-resources-modal" class="weather-modal">
Enter version to rollback to:`);if(!a)return;if(!e.includes(a)){showNotification("Invalid version: "+a,"error");return}if(!confirm("Rollback DashCaddy to v"+a+"? The container will restart."))return;y("Rolling back to v"+a+"...","info");const r=await(await secureFetch("/api/v1/system/rollback",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({version:a})})).json();if(r.success)y("Rollback to v"+a+" initiated. Container will restart.","success");else throw new Error(r.error||"Rollback failed")}catch(u){y("Rollback failed: "+u.message,"error")}}D?.addEventListener("click",()=>s(!1)),R?.addEventListener("click",()=>c().catch(()=>{})),O?.addEventListener("click",m),C?.addEventListener("click",w),B?.addEventListener("click",()=>{x?.classList.add("show"),f()}),wireModal(x,A),window.openUpdateModal=function(u){x?.classList.add("show"),f().then(()=>{if(!u)return;const t=M.querySelector(`[data-app-id="${u}"]`);t&&(t.scrollIntoView({behavior:"smooth",block:"center"}),t.style.background="rgba(249,115,22,0.15)",setTimeout(()=>{t.style.background=""},3e3))})},document.querySelector('[data-panel="updates-history"]')?.addEventListener("click",$),document.querySelector('[data-panel="updates-auto"]')?.addEventListener("click",k),document.querySelector('[data-panel="updates-dashcaddy"]')?.addEventListener("click",()=>{h(),l(),b||s(!0)}),window.dcApplyUpdate=c,window.dcCheckForUpdate=s,setTimeout(()=>s(!0),5e3)})(),(function(){injectModal("docker-resources-modal",`<div id="docker-resources-modal" class="weather-modal">
<div class="weather-modal-content" style="min-width: 750px; max-width: 950px;">
<h3>\u{1F433} Docker Resources</h3>
<p class="modal-subtitle">Manage volumes, networks, and view disk usage.</p>
@@ -1602,7 +1641,7 @@ Enter version to rollback to:`);if(!a)return;if(!e.includes(a)){showNotification
<button id="dr-close">Close</button>
</div>
</div>
</div>`);const f=document.getElementById("docker-resources-modal"),I=document.getElementById("docker-resources-btn"),A=document.getElementById("dr-close");function E(D){if(!D||D===0)return"0 B";const v=["B","KB","MB","GB","TB"],B=Math.floor(Math.log(Math.abs(D))/Math.log(1024));return(D/Math.pow(1024,B)).toFixed(1)+" "+v[B]}async function M(){const D=document.getElementById("dr-vol-list");try{const B=(await getJSON("/api/v1/docker/volumes")).volumes||[];if(B.length===0){D.innerHTML='<div class="panel-empty"><span class="empty-icon">\u{1F4E6}</span>No volumes found.</div>';return}let x='<table style="width: 100%; border-collapse: collapse; font-size: 0.82rem;">';x+='<tr style="border-bottom: 1px solid var(--border); color: var(--muted);"><th style="padding: 6px; text-align: left;">Name</th><th style="padding: 6px;">Driver</th><th style="padding: 6px;">Scope</th><th style="padding: 6px; text-align: right;">Actions</th></tr>';for(const $ of B){const k=$.name==="buildkit"||$.name.length===64;x+='<tr style="border-bottom: 1px solid var(--border);">',x+=`<td style="padding: 6px; font-weight: 500; max-width: 300px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;" title="${escapeHtml($.name)}">${escapeHtml($.name.length>40?$.name.substring(0,37)+"...":$.name)}</td>`,x+=`<td style="padding: 6px; text-align: center; color: var(--muted);">${escapeHtml($.driver)}</td>`,x+=`<td style="padding: 6px; text-align: center; color: var(--muted);">${escapeHtml($.scope)}</td>`,x+='<td style="padding: 6px; text-align: right;">',k||(x+=`<button class="dr-vol-del" data-name="${escapeHtml($.name)}" style="padding: 3px 8px; font-size: 0.75rem; color: var(--bad-fg);">Delete</button>`),x+="</td></tr>"}x+="</table>",D.innerHTML=x,D.querySelectorAll(".dr-vol-del").forEach($=>{$.addEventListener("click",async()=>{if(confirm(`Delete volume "${$.dataset.name}"? Data will be lost.`)){$.textContent="...",$.disabled=!0;try{await deleteAPI(`/api/v1/docker/volumes/${encodeURIComponent($.dataset.name)}?force=true`),M()}catch(k){showNotification("Delete failed: "+k.message,"error"),$.textContent="Delete",$.disabled=!1}}})})}catch(v){D.innerHTML=`<div class="panel-empty" style="color: var(--bad-fg);">Failed: ${escapeHtml(v.message)}</div>`}}document.getElementById("dr-vol-create")?.addEventListener("click",async()=>{const D=document.getElementById("dr-vol-name"),v=D.value.trim();if(!v){showNotification("Enter a volume name","warning");return}try{await postJSON("/api/v1/docker/volumes",{name:v}),D.value="",showNotification(`Volume "${v}" created`,"success"),M()}catch(B){showNotification("Create failed: "+B.message,"error")}});async function P(){const D=document.getElementById("dr-net-list");try{const B=(await getJSON("/api/v1/docker/networks")).networks||[];if(B.length===0){D.innerHTML='<div class="panel-empty"><span class="empty-icon">\u{1F310}</span>No networks found.</div>';return}let x='<table style="width: 100%; border-collapse: collapse; font-size: 0.82rem;">';x+='<tr style="border-bottom: 1px solid var(--border); color: var(--muted);"><th style="padding: 6px; text-align: left;">Name</th><th style="padding: 6px;">Driver</th><th style="padding: 6px;">Scope</th><th style="padding: 6px;">Containers</th><th style="padding: 6px; text-align: right;">Actions</th></tr>';for(const $ of B){const k=["bridge","host","none"].includes($.name);x+='<tr style="border-bottom: 1px solid var(--border);">',x+=`<td style="padding: 6px; font-weight: 500;">${escapeHtml($.name)}</td>`,x+=`<td style="padding: 6px; text-align: center; color: var(--muted);">${escapeHtml($.driver)}</td>`,x+=`<td style="padding: 6px; text-align: center; color: var(--muted);">${escapeHtml($.scope)}</td>`,x+=`<td style="padding: 6px; text-align: center;">${$.containers}</td>`,x+='<td style="padding: 6px; text-align: right;">',k||(x+=`<button class="dr-net-del" data-id="${escapeHtml($.id)}" data-name="${escapeHtml($.name)}" style="padding: 3px 8px; font-size: 0.75rem; color: var(--bad-fg);">Delete</button>`),x+="</td></tr>"}x+="</table>",D.innerHTML=x,D.querySelectorAll(".dr-net-del").forEach($=>{$.addEventListener("click",async()=>{if(confirm(`Delete network "${$.dataset.name}"?`)){$.textContent="...",$.disabled=!0;try{await deleteAPI(`/api/v1/docker/networks/${encodeURIComponent($.dataset.id)}`),P()}catch(k){showNotification("Delete failed: "+k.message,"error"),$.textContent="Delete",$.disabled=!1}}})})}catch(v){D.innerHTML=`<div class="panel-empty" style="color: var(--bad-fg);">Failed: ${escapeHtml(v.message)}</div>`}}document.getElementById("dr-net-create")?.addEventListener("click",async()=>{const D=document.getElementById("dr-net-name"),v=document.getElementById("dr-net-driver"),B=D.value.trim();if(!B){showNotification("Enter a network name","warning");return}try{await postJSON("/api/v1/docker/networks",{name:B,driver:v.value}),D.value="",showNotification(`Network "${B}" created`,"success"),P()}catch(x){showNotification("Create failed: "+x.message,"error")}});async fuLine truncated
</div>`);const x=document.getElementById("docker-resources-modal"),B=document.getElementById("docker-resources-btn"),A=document.getElementById("dr-close");function C(N){if(!N||N===0)return"0 B";const f=["B","KB","MB","GB","TB"],L=Math.floor(Math.log(Math.abs(N))/Math.log(1024));return(N/Math.pow(1024,L)).toFixed(1)+" "+f[L]}async function M(){const N=document.getElementById("dr-vol-list");try{const L=(await getJSON("/api/v1/docker/volumes")).volumes||[];if(L.length===0){N.innerHTML='<div class="panel-empty"><span class="empty-icon">\u{1F4E6}</span>No volumes found.</div>';return}let w='<table style="width: 100%; border-collapse: collapse; font-size: 0.82rem;">';w+='<tr style="border-bottom: 1px solid var(--border); color: var(--muted);"><th style="padding: 6px; text-align: left;">Name</th><th style="padding: 6px;">Driver</th><th style="padding: 6px;">Scope</th><th style="padding: 6px; text-align: right;">Actions</th></tr>';for(const $ of L){const k=$.name==="buildkit"||$.name.length===64;w+='<tr style="border-bottom: 1px solid var(--border);">',w+=`<td style="padding: 6px; font-weight: 500; max-width: 300px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;" title="${escapeHtml($.name)}">${escapeHtml($.name.length>40?$.name.substring(0,37)+"...":$.name)}</td>`,w+=`<td style="padding: 6px; text-align: center; color: var(--muted);">${escapeHtml($.driver)}</td>`,w+=`<td style="padding: 6px; text-align: center; color: var(--muted);">${escapeHtml($.scope)}</td>`,w+='<td style="padding: 6px; text-align: right;">',k||(w+=`<button class="dr-vol-del" data-name="${escapeHtml($.name)}" style="padding: 3px 8px; font-size: 0.75rem; color: var(--bad-fg);">Delete</button>`),w+="</td></tr>"}w+="</table>",N.innerHTML=w,N.querySelectorAll(".dr-vol-del").forEach($=>{$.addEventListener("click",async()=>{if(confirm(`Delete volume "${$.dataset.name}"? Data will be lost.`)){$.textContent="...",$.disabled=!0;try{await deleteAPI(`/api/v1/docker/volumes/${encodeURIComponent($.dataset.name)}?force=true`),M()}catch(k){showNotification("Delete failed: "+k.message,"error"),$.textContent="Delete",$.disabled=!1}}})})}catch(f){N.innerHTML=`<div class="panel-empty" style="color: var(--bad-fg);">Failed: ${escapeHtml(f.message)}</div>`}}document.getElementById("dr-vol-create")?.addEventListener("click",async()=>{const N=document.getElementById("dr-vol-name"),f=N.value.trim();if(!f){showNotification("Enter a volume name","warning");return}try{await postJSON("/api/v1/docker/volumes",{name:f}),N.value="",showNotification(`Volume "${f}" created`,"success"),M()}catch(L){showNotification("Create failed: "+L.message,"error")}});async function P(){const N=document.getElementById("dr-net-list");try{const L=(await getJSON("/api/v1/docker/networks")).networks||[];if(L.length===0){N.innerHTML='<div class="panel-empty"><span class="empty-icon">\u{1F310}</span>No networks found.</div>';return}let w='<table style="width: 100%; border-collapse: collapse; font-size: 0.82rem;">';w+='<tr style="border-bottom: 1px solid var(--border); color: var(--muted);"><th style="padding: 6px; text-align: left;">Name</th><th style="padding: 6px;">Driver</th><th style="padding: 6px;">Scope</th><th style="padding: 6px;">Containers</th><th style="padding: 6px; text-align: right;">Actions</th></tr>';for(const $ of L){const k=["bridge","host","none"].includes($.name);w+='<tr style="border-bottom: 1px solid var(--border);">',w+=`<td style="padding: 6px; font-weight: 500;">${escapeHtml($.name)}</td>`,w+=`<td style="padding: 6px; text-align: center; color: var(--muted);">${escapeHtml($.driver)}</td>`,w+=`<td style="padding: 6px; text-align: center; color: var(--muted);">${escapeHtml($.scope)}</td>`,w+=`<td style="padding: 6px; text-align: center;">${$.containers}</td>`,w+='<td style="padding: 6px; text-align: right;">',k||(w+=`<button class="dr-net-del" data-id="${escapeHtml($.id)}" data-name="${escapeHtml($.name)}" style="padding: 3px 8px; font-size: 0.75rem; color: var(--bad-fg);">Delete</button>`),w+="</td></tr>"}w+="</table>",N.innerHTML=w,N.querySelectorAll(".dr-net-del").forEach($=>{$.addEventListener("click",async()=>{if(confirm(`Delete network "${$.dataset.name}"?`)){$.textContent="...",$.disabled=!0;try{await deleteAPI(`/api/v1/docker/networks/${encodeURIComponent($.dataset.id)}`),P()}catch(k){showNotification("Delete failed: "+k.message,"error"),$.textContent="Delete",$.disabled=!1}}})})}catch(f){N.innerHTML=`<div class="panel-empty" style="color: var(--bad-fg);">Failed: ${escapeHtml(f.message)}</div>`}}document.getElementById("dr-net-create")?.addEventListener("click",async()=>{const N=document.getElementById("dr-net-name"),f=document.getElementById("dr-net-driver"),L=N.value.trim();if(!L){showNotification("Enter a network name","warning");return}try{await postJSON("/api/v1/docker/networks",{name:L,driver:f.value}),N.value="",showNotification(`Network "${L}" created`,"success"),P()}catch(w){showNotification("Create failed: "+w.message,"error")}});async fuLine truncated
<div class="weather-modal-content" style="min-width: 650px; max-width: 800px;">
<h3>\u{1F4E6} Import Docker Compose</h3>
<p class="modal-subtitle">Paste a docker-compose.yml to import and deploy services.</p>
@@ -1643,7 +1682,7 @@ Enter version to rollback to:`);if(!a)return;if(!e.includes(a)){showNotification
<div id="compose-progress-content"></div>
</div>
</div>
</div>`);const f=document.getElementById("compose-import-modal"),I=document.getElementById("compose-import-btn"),A=document.getElementById("compose-cancel");wireModal(f,A);let E=null;function M(z){document.getElementById("compose-step-paste").style.display=z==="paste"?"":"none",document.getElementById("compose-step-preview").style.display=z==="preview"?"":"none",document.getElementById("compose-step-progress").style.display=z==="progress"?"":"none"}I?.addEventListener("click",()=>{M("paste"),E=null,document.getElementById("compose-yaml").value="",document.getElementById("compose-stack-name").value="",f?.classList.add("show")}),document.getElementById("compose-file-upload")?.addEventListener("change",z=>{const D=z.target.files[0];if(!D)return;const v=new FileReader;v.onload=()=>{document.getElementById("compose-yaml").value=v.result},v.readAsText(D)}),document.getElementById("compose-parse-btn")?.addEventListener("click",async()=>{const z=document.getElementById("compose-yaml").value.trim(),D=document.getElementById("compose-stack-name").value.trim()||"stack";if(!z){showNotification("Paste a docker-compose.yml","warning");return}const v=document.getElementById("compose-parse-btn"),B=v.textContent;v.textContent="Parsing...",v.disabled=!0;try{const x=await postJSON("/api/v1/apps/import-compose",{yaml:z,stackName:D});E=x,E.stackName=D,P(x),M("preview")}catch(x){showNotification("Parse failed: "+x.message,"error")}finally{v.textContent=B,v.disabled=!1}});function P(z){const D=document.getElementById("compose-preview-content");let v="";z.networks&&z.networks.length>0&&(v+=`<div style="margin-bottom: 12px; font-size: 0.82rem; color: var(--muted);">Networks: ${z.networks.map(B=>`<code>${escapeHtml(B)}</code>`).join(", ")}</div>`),z.volumes&&z.volumes.length>0&&(v+=`<div style="margin-bottom: 12px; font-size: 0.82rem; color: var(--muted);">Volumes: ${z.volumes.map(B=>`<code>${escapeHtml(B)}</code>`).join(", ")}</div>`),v+=`<div style="font-weight: 600; margin-bottom: 8px;">${z.services.length} service(s)</div>`,v+='<div class="scroll-container" style="max-height: 350px;">';for(const B of z.services){const x=B.skip?"var(--bad-fg)":"var(--border)";if(v+=`<div style="padding: 10px 14px; border: 1px solid ${x}; border-radius: 8px; margin-bottom: 8px; background: var(--bg);">`,v+=`<div style="font-weight: 600; font-size: 0.9rem;">${escapeHtml(B.name)}`,B.skip&&(v+=` <span style="color: var(--bad-fg); font-weight: 400; font-size: 0.78rem;">\u2014 skipped: ${escapeHtml(B.reason)}</span>`),v+="</div>",!B.skip&&(v+=`<div style="font-size: 0.8rem; color: var(--muted); margin-top: 4px;">Image: <code>${escapeHtml(B.image)}</code></div>`,B.ports?.length&&(v+=`<div style="font-size: 0.8rem; color: var(--muted);">Ports: ${B.ports.map($=>`${$.host}:${$.container}`).join(", ")}</div>`),B.volumes?.length&&(v+=`<div style="font-size: 0.8rem; color: var(--muted);">Volumes: ${B.volumes.length}</div>`),Object.keys(B.environment||{}).length&&(v+=`<div style="font-size: 0.8rem; color: var(--muted);">Env vars: ${Object.keys(B.environment).length}</div>`),B.envFileWarning&&(v+=`<div style="font-size: 0.78rem; color: var(--bad-fg);">\u26A0 ${escapeHtml(B.envFileWarning)}</div>`),B.resources?.cpus||B.resources?.memory)){const $=[];B.resources.cpus&&$.push(`CPU: ${B.resources.cpus}`),B.resources.memory&&$.push(`Mem: ${B.resources.memory}MB`),v+=`<div style="font-size: 0.8rem; color: var(--muted);">Limits: ${$.join(", ")}</div>`}v+="</div>"}v+="</div>",D.innerHTML=v}document.getElementById("compose-back-btn")?.addEventListener("click",()=>M("paste")),document.getElementById("compose-deploy-btn")?.addEventListener("click",async()=>{if(!E)return;const z=document.getElementById("compose-deploy-btn");z.textContent="Deploying...",z.disabled=!0,M("progress");const D=document.getElementById("compose-progress-content");D.innerHTML='<div class="panel-empty"><span class="brand-spinner"></span> Deploying services...</div>';try{const v=await postJSON("/api/v1/apps/deploy-compose",{services:E.services,networks:E.networks,stackName:E.stackName});let B=`<div style="font-weight: 600; margin-bottom: 12px;">Stack "${escapeHtml(v.stackName)}" \u2014 Deployment Complete</div>`;B+='<div class="scroll-container" style="max-height: 350px;">';for(const x of v.results){const $=x.status==="deployed"||x.status==="created"?"\u2705":x.status==="exists"?"\u26A1":x.status==="skipped"?"\u23ED":"\u274C";B+='<div style="padding: 8px 12px; border-bottom: 1px solid var(--border); font-size: 0.85rem;">',B+=`${$} <strong>${escapeHtml(x.name)}</strong> (${x.type}) \u2014 ${escapeHtml(x.status)}`,x.error&&(B+=` <span style="color: var(--bad-fg);">${escapeHtml(x.error)}</span>`),x.subdomain&&(B+=` \u2192 <code>${escapeHtml(x.subdomain)}</code>`),x.reason&&(B+=` <span style="color: var(--muted);">(${escapeHtml(x.reason)})</span>`),B+="</div>"}B+="</div>",B+='<div class="weather-modal-buttons modal-footer-bar" style="margin-top: 16px;"><button id="compose-done-btn">Done</button></div>Line truncated
</div>`);const x=document.getElementById("compose-import-modal"),B=document.getElementById("compose-import-btn"),A=document.getElementById("compose-cancel");wireModal(x,A);let C=null;function M(z){document.getElementById("compose-step-paste").style.display=z==="paste"?"":"none",document.getElementById("compose-step-preview").style.display=z==="preview"?"":"none",document.getElementById("compose-step-progress").style.display=z==="progress"?"":"none"}B?.addEventListener("click",()=>{M("paste"),C=null,document.getElementById("compose-yaml").value="",document.getElementById("compose-stack-name").value="",x?.classList.add("show")}),document.getElementById("compose-file-upload")?.addEventListener("change",z=>{const N=z.target.files[0];if(!N)return;const f=new FileReader;f.onload=()=>{document.getElementById("compose-yaml").value=f.result},f.readAsText(N)}),document.getElementById("compose-parse-btn")?.addEventListener("click",async()=>{const z=document.getElementById("compose-yaml").value.trim(),N=document.getElementById("compose-stack-name").value.trim()||"stack";if(!z){showNotification("Paste a docker-compose.yml","warning");return}const f=document.getElementById("compose-parse-btn"),L=f.textContent;f.textContent="Parsing...",f.disabled=!0;try{const w=await postJSON("/api/v1/apps/import-compose",{yaml:z,stackName:N});C=w,C.stackName=N,P(w),M("preview")}catch(w){showNotification("Parse failed: "+w.message,"error")}finally{f.textContent=L,f.disabled=!1}});function P(z){const N=document.getElementById("compose-preview-content");let f="";z.networks&&z.networks.length>0&&(f+=`<div style="margin-bottom: 12px; font-size: 0.82rem; color: var(--muted);">Networks: ${z.networks.map(L=>`<code>${escapeHtml(L)}</code>`).join(", ")}</div>`),z.volumes&&z.volumes.length>0&&(f+=`<div style="margin-bottom: 12px; font-size: 0.82rem; color: var(--muted);">Volumes: ${z.volumes.map(L=>`<code>${escapeHtml(L)}</code>`).join(", ")}</div>`),f+=`<div style="font-weight: 600; margin-bottom: 8px;">${z.services.length} service(s)</div>`,f+='<div class="scroll-container" style="max-height: 350px;">';for(const L of z.services){const w=L.skip?"var(--bad-fg)":"var(--border)";if(f+=`<div style="padding: 10px 14px; border: 1px solid ${w}; border-radius: 8px; margin-bottom: 8px; background: var(--bg);">`,f+=`<div style="font-weight: 600; font-size: 0.9rem;">${escapeHtml(L.name)}`,L.skip&&(f+=` <span style="color: var(--bad-fg); font-weight: 400; font-size: 0.78rem;">\u2014 skipped: ${escapeHtml(L.reason)}</span>`),f+="</div>",!L.skip&&(f+=`<div style="font-size: 0.8rem; color: var(--muted); margin-top: 4px;">Image: <code>${escapeHtml(L.image)}</code></div>`,L.ports?.length&&(f+=`<div style="font-size: 0.8rem; color: var(--muted);">Ports: ${L.ports.map($=>`${$.host}:${$.container}`).join(", ")}</div>`),L.volumes?.length&&(f+=`<div style="font-size: 0.8rem; color: var(--muted);">Volumes: ${L.volumes.length}</div>`),Object.keys(L.environment||{}).length&&(f+=`<div style="font-size: 0.8rem; color: var(--muted);">Env vars: ${Object.keys(L.environment).length}</div>`),L.envFileWarning&&(f+=`<div style="font-size: 0.78rem; color: var(--bad-fg);">\u26A0 ${escapeHtml(L.envFileWarning)}</div>`),L.resources?.cpus||L.resources?.memory)){const $=[];L.resources.cpus&&$.push(`CPU: ${L.resources.cpus}`),L.resources.memory&&$.push(`Mem: ${L.resources.memory}MB`),f+=`<div style="font-size: 0.8rem; color: var(--muted);">Limits: ${$.join(", ")}</div>`}f+="</div>"}f+="</div>",N.innerHTML=f}document.getElementById("compose-back-btn")?.addEventListener("click",()=>M("paste")),document.getElementById("compose-deploy-btn")?.addEventListener("click",async()=>{if(!C)return;const z=document.getElementById("compose-deploy-btn");z.textContent="Deploying...",z.disabled=!0,M("progress");const N=document.getElementById("compose-progress-content");N.innerHTML='<div class="panel-empty"><span class="brand-spinner"></span> Deploying services...</div>';try{const f=await postJSON("/api/v1/apps/deploy-compose",{services:C.services,networks:C.networks,stackName:C.stackName});let L=`<div style="font-weight: 600; margin-bottom: 12px;">Stack "${escapeHtml(f.stackName)}" \u2014 Deployment Complete</div>`;L+='<div class="scroll-container" style="max-height: 350px;">';for(const w of f.results){const $=w.status==="deployed"||w.status==="created"?"\u2705":w.status==="exists"?"\u26A1":w.status==="skipped"?"\u23ED":"\u274C";L+='<div style="padding: 8px 12px; border-bottom: 1px solid var(--border); font-size: 0.85rem;">',L+=`${$} <strong>${escapeHtml(w.name)}</strong> (${w.type}) \u2014 ${escapeHtml(w.status)}`,w.error&&(L+=` <span style="color: var(--bad-fg);">${escapeHtml(w.error)}</span>`),w.subdomain&&(L+=` \u2192 <code>${escapeHtml(w.subdomain)}</code>`),w.reason&&(L+=` <span style="color: var(--muted);">(${escapeHtml(w.reason)})</span>`),L+="</div>"}L+="</div>",L+='<div class="weather-modal-buttons modal-footer-bar" style="margin-top: 16px;"><button id="compose-done-btn">Done</button></div>Line truncated
<div class="weather-modal-buttons modal-footer-bar" style="margin-top: 16px;"><button id="compose-retry-btn">Back</button></div>`,document.getElementById("compose-retry-btn")?.addEventListener("click",()=>M("paste"))}finally{z.textContent="Deploy All",z.disabled=!1}})})(),(function(){injectModal("exec-modal",`<div id="exec-modal" class="weather-modal">
<div class="weather-modal-content" style="min-width: 700px; max-width: 900px; padding-bottom: 0;">
<h3 id="exec-title">Terminal</h3>
@@ -1652,21 +1691,21 @@ Enter version to rollback to:`);if(!a)return;if(!e.includes(a)){showNotification
<button id="exec-close">Close</button>
</div>
</div>
</div>`);const f=document.getElementById("exec-modal"),I=document.getElementById("exec-terminal"),A=document.getElementById("exec-close");let E=null,M=null,P=null;function z(){if(M){try{M.close()}catch{}M=null}if(E){try{E.dispose()}catch{}E=null}P=null,I.innerHTML=""}function D(v,B){if(z(),document.getElementById("exec-title").textContent=`Terminal \u2014 ${B||v}`,f?.classList.add("show"),typeof Terminal>"u"){I.innerHTML='<div style="color: #f44; padding: 20px; font-family: monospace;">xterm.js not loaded</div>';return}E=new Terminal({cursorBlink:!0,fontSize:14,fontFamily:"'Cascadia Code', 'Fira Code', 'Consolas', monospace",theme:{background:"#1e1e1e",foreground:"#d4d4d4",cursor:"#aeafad",selectionBackground:"#264f78"},scrollback:5e3}),typeof FitAddon<"u"&&(P=new FitAddon.FitAddon,E.loadAddon(P)),E.open(I),P&&setTimeout(()=>P.fit(),50);const x=location.protocol==="https:"?"wss:":"ws:";M=new WebSocket(`${x}//${location.host}/ws/exec/${encodeURIComponent(v)}`),M.binaryType="arraybuffer",M.onopen=()=>{if(E.writeln("\x1B[32mConnecting...\x1B[0m"),P){const k=P.proposeDimensions();k&&M.send(JSON.stringify({type:"resize",cols:k.cols,rows:k.rows}))}},M.onmessage=k=>{if(typeof k.data=="string"){try{const T=JSON.parse(k.data);if(T.type==="connected"){E.writeln(`\x1B[32mConnected (${T.shell})\x1B[0m\r
`);return}if(T.type==="error"){E.writeln(`\x1B[31mError: ${T.message}\x1B[0m`);return}if(T.type==="exit"){E.writeln(`\r
\x1B[33mSession ended.\x1B[0m`);return}}catch{}E.write(k.data)}else E.write(new Uint8Array(k.data))},M.onclose=()=>{E&&E.writeln(`\r
\x1B[33mDisconnected.\x1B[0m`)},M.onerror=()=>{E&&E.writeln(`\r
\x1B[31mConnection error.\x1B[0m`)},E.onData(k=>{M&&M.readyState===WebSocket.OPEN&&M.send(k)}),E.onResize(({cols:k,rows:T})=>{M&&M.readyState===WebSocket.OPEN&&M.send(JSON.stringify({type:"resize",cols:k,rows:T}))});const $=()=>{P&&P.fit()};window.addEventListener("resize",$),f._resizeHandler=$}A?.addEventListener("click",()=>{z(),f._resizeHandler&&window.removeEventListener("resize",f._resizeHandler),f?.classList.remove("show")}),f?.addEventListener("click",v=>{v.target===f&&(z(),f._resizeHandler&&window.removeEventListener("resize",f._resizeHandler),f?.classList.remove("show"))}),window.openExecModal=D})(),(function(){injectModal("audit-modal",`<div id="audit-modal" class="weather-modal">
<div class="weather-modal-content" style="min-width: 850px; max-width: 1050px;">
</div>`);const x=document.getElementById("exec-modal"),B=document.getElementById("exec-terminal"),A=document.getElementById("exec-close");let C=null,M=null,P=null;function z(){if(M){try{M.close()}catch{}M=null}if(C){try{C.dispose()}catch{}C=null}P=null,B.innerHTML=""}function N(f,L){if(z(),document.getElementById("exec-title").textContent=`Terminal \u2014 ${L||f}`,x?.classList.add("show"),typeof Terminal>"u"){B.innerHTML='<div style="color: #f44; padding: 20px; font-family: monospace;">xterm.js not loaded</div>';return}C=new Terminal({cursorBlink:!0,fontSize:14,fontFamily:"'Cascadia Code', 'Fira Code', 'Consolas', monospace",theme:{background:"#1e1e1e",foreground:"#d4d4d4",cursor:"#aeafad",selectionBackground:"#264f78"},scrollback:5e3}),typeof FitAddon<"u"&&(P=new FitAddon.FitAddon,C.loadAddon(P)),C.open(B),P&&setTimeout(()=>P.fit(),50);const w=location.protocol==="https:"?"wss:":"ws:";M=new WebSocket(`${w}//${location.host}/ws/exec/${encodeURIComponent(f)}`),M.binaryType="arraybuffer",M.onopen=()=>{if(C.writeln("\x1B[32mConnecting...\x1B[0m"),P){const k=P.proposeDimensions();k&&M.send(JSON.stringify({type:"resize",cols:k.cols,rows:k.rows}))}},M.onmessage=k=>{if(typeof k.data=="string"){try{const T=JSON.parse(k.data);if(T.type==="connected"){C.writeln(`\x1B[32mConnected (${T.shell})\x1B[0m\r
`);return}if(T.type==="error"){C.writeln(`\x1B[31mError: ${T.message}\x1B[0m`);return}if(T.type==="exit"){C.writeln(`\r
\x1B[33mSession ended.\x1B[0m`);return}}catch{}C.write(k.data)}else C.write(new Uint8Array(k.data))},M.onclose=()=>{C&&C.writeln(`\r
\x1B[33mDisconnected.\x1B[0m`)},M.onerror=()=>{C&&C.writeln(`\r
\x1B[31mConnection error.\x1B[0m`)},C.onData(k=>{M&&M.readyState===WebSocket.OPEN&&M.send(k)}),C.onResize(({cols:k,rows:T})=>{M&&M.readyState===WebSocket.OPEN&&M.send(JSON.stringify({type:"resize",cols:k,rows:T}))});const $=()=>{P&&P.fit()};window.addEventListener("resize",$),x._resizeHandler=$}A?.addEventListener("click",()=>{z(),x._resizeHandler&&window.removeEventListener("resize",x._resizeHandler),x?.classList.remove("show")}),x?.addEventListener("click",f=>{f.target===x&&(z(),x._resizeHandler&&window.removeEventListener("resize",x._resizeHandler),x?.classList.remove("show"))}),window.openExecModal=N})(),(function(){injectModal("audit-modal",`<div id="audit-modal" class="weather-modal">
<div class="weather-modal-content" style="min-width: 950px; max-width: 1150px;">
<h3>\u{1F4DC} Audit Log</h3>
<p class="modal-subtitle">
Track all actions performed through the API.
</p>
<div style="display: flex; gap: 12px; margin-bottom: 16px; align-items: center;">
<label class="text-muted-sm">Filter:</label>
<div style="display: flex; gap: 12px; margin-bottom: 12px; align-items: center; flex-wrap: wrap;">
<label class="text-muted-sm">Category:</label>
<select id="audit-filter" style="padding: 6px 10px; border-radius: 6px; border: 1px solid var(--border); background: var(--bg); color: var(--fg); font-size: 0.85rem;">
<option value="">All Actions</option>
<option value="">All</option>
<option value="service">Services</option>
<option value="container">Containers</option>
<option value="caddy">Caddy</option>
@@ -1675,6 +1714,16 @@ Enter version to rollback to:`);if(!a)return;if(!e.includes(a)){showNotification
<option value="config">Config</option>
<option value="auth">Auth</option>
</select>
<label class="text-muted-sm">Result:</label>
<select id="audit-outcome-filter" style="padding: 6px 10px; border-radius: 6px; border: 1px solid var(--border); background: var(--bg); color: var(--fg); font-size: 0.85rem;">
<option value="">Any</option>
<option value="success">\u2713 Success</option>
<option value="failure">\u2717 Failure</option>
</select>
<label class="text-muted-sm" style="margin-left: 8px;">Since:</label>
<input id="audit-since" type="datetime-local" style="padding: 5px 8px; border-radius: 6px; border: 1px solid var(--border); background: var(--bg); color: var(--fg); font-size: 0.82rem;">
<label class="text-muted-sm">Until:</label>
<input id="audit-until" type="datetime-local" style="padding: 5px 8px; border-radius: 6px; border: 1px solid var(--border); background: var(--bg); color: var(--fg); font-size: 0.82rem;">
<button id="audit-refresh-btn" class="btn-sm">\u{1F504} Refresh</button>
<span style="flex: 1;"></span>
<button id="audit-clear-btn" style="padding: 6px 12px; font-size: 0.8rem; color: var(--bad-fg); border-color: var(--bad-fg);">\u{1F5D1}\uFE0F Clear Log</button>
@@ -1692,7 +1741,7 @@ Enter version to rollback to:`);if(!a)return;if(!e.includes(a)){showNotification
<button id="audit-cancel">Close</button>
</div>
</div>
</div>`);const f=document.getElementById("audit-modal"),I=document.getElementById("audit-log-btn"),A=document.getElementById("audit-cancel"),E=document.getElementById("audit-refresh-btn"),M=document.getElementById("audit-clear-btn"),P=document.getElementById("audit-filter"),z=document.getElementById("audit-log-container"),D=document.getElementById("audit-load-more");let v=0;const B=50;async function x($){try{$||(v=0,z.innerHTML='<div class="panel-empty"><span class="brand-spinner"></span> Loading...</div>');const k=P.value;let T=`/api/v1/audit-logs?limit=${B}&offset=${v}`;k&&(T+=`&action=${encodeURIComponent(k)}`);const L=await(await fetch(T)).json(),j=L.success&&L.entries?L.entries:[];if(j.length===0&&!$){z.innerHTML='<div class="panel-empty"><span class="empty-icon">\u{1F4DC}</span>No audit log entries yet. Actions will be logged automatically.</div>',D.style.display="none";return}let C="";$||(C='<table style="width: 100%; border-collapse: collapse; font-size: 0.82rem;">',C+='<tr style="border-bottom: 1px solid var(--border); color: var(--muted);"><th style="padding: 6px; text-align: left;">When</th><th style="padding: 6px; text-align: left;">IP</th><th style="padding: 6px; text-align: left;">Action</th><th style="padding: 6px; text-align: left;">Resource</th><th style="padding: 6px; text-align: left;">Result</th></tr>');for(const N of j){const R=N.outcome==="success";C+='<tr style="border-bottom: 1px solid var(--border); cursor: pointer;" class="audit-row">',C+=`<td style="padding: 6px; color: var(--muted);">${timeAgo(N.timestamp)}</td>`,C+=`<td style="padding: 6px; font-family: monospace; font-size: 0.78rem;">${escapeHtml(N.ip||"-")}</td>`,C+=`<td style="padding: 6px; font-weight: 500;">${escapeHtml(N.action||"-")}</td>`,C+=`<td style="padding: 6px;">${escapeHtml(N.resource||"-")}</td>`,C+=`<td style="padding: 6px;"><span style="color: ${R?"var(--ok-fg)":"var(--bad-fg)"};">${R?"\u2713":"\u2717"}</span></td>`,C+="</tr>",N.details&&Object.keys(N.details).length>0&&(C+=`<tr class="audit-detail" style="display: none;"><td colspan="5" style="padding: 6px 6px 10px; font-size: 0.78rem; color: var(--muted);"><pre style="margin: 0; white-space: pre-wrap; font-family: monospace;">${escapeHtml(JSON.stringify(N.details,null,2))}</pre></td></tr>`)}if(!$)C+="</table>",z.innerHTML=C;else{const N=z.querySelector("table");N&&N.insertAdjacentHTML("beforeend",C)}v+=j.length,D.style.display=j.length>=B?"":"none",z.querySelectorAll(".audit-row").forEach(N=>{N.dataset.wired||(N.dataset.wired="true",N.addEventListener("click",()=>{const R=N.nextElementSibling;R&&R.classList.contains("audit-detail")&&(R.style.display=R.style.display==="none"?"":"none")}))})}catch(k){z.innerHTML=`<div class="panel-empty" style="color: var(--bad-fg);">Failed: ${escapeHtml(k.message)}</div>`}}I?.addEventListener("click",()=>{f?.classList.add("show"),x(!1)}),wireModal(f,A),E?.addEventListener("click",()=>x(!1)),P?.addEventListener("change",()=>x(!1)),D?.addEventListener("click",()=>x(!0)),M?.addEventListener("click",async()=>{if(confirm("Clear the entire audit log? This cannot be undone."))try{const k=await(await secureFetch("/api/v1/audit-logs",{method:"DELETE"})).json();k.success?x(!1):showNotification("Error: "+(k.error||"Clear failed"),"error")}catch($){showNotification("Error: "+$.message,"error")}})})(),(function(){injectModal("security-modal",`<div id="security-modal" class="weather-modal">
</div>`);const x=document.getElementById("audit-modal"),B=document.getElementById("audit-log-btn"),A=document.getElementById("audit-cancel"),C=document.getElementById("audit-refresh-btn"),M=document.getElementById("audit-clear-btn"),P=document.getElementById("audit-filter"),z=document.getElementById("audit-outcome-filter"),N=document.getElementById("audit-since"),f=document.getElementById("audit-until"),L=document.getElementById("audit-log-container"),w=document.getElementById("audit-load-more");let $=0,k=null,T=0;const E=50;function I(D){if(!D)return null;const O=new Date(D);return isNaN(O.getTime())?null:O.toISOString()}async function j(D){try{D?(k&&k.abort(),k=new AbortController):(k&&k.abort(),k=new AbortController,$=0,T++,L.innerHTML='<div class="panel-empty"><span class="brand-spinner"></span> Loading...</div>');const O=T,p=new URLSearchParams;p.set("limit",String(E)),p.set("offset",String($));const v=P.value,b=z.value,y=I(N.value),h=I(f.value);v&&p.set("action",v),b&&p.set("outcome",b),y&&p.set("since",y),h&&p.set("until",h);const s=await fetch("/api/v1/audit-logs?"+p.toString(),{signal:k.signal});if(!s.ok){L.innerHTML=`<div class="panel-empty" style="color: var(--bad-fg);">Failed: HTTP ${s.status}</div>`,w.style.display="none";return}const c=await s.json();if(!c.success){L.innerHTML=`<div class="panel-empty" style="color: var(--bad-fg);">Failed: ${escapeHtml(c.error||"unknown")}</div>`,w.style.display="none";return}if(!D&&O!==T)return;const l=Array.isArray(c.entries)?c.entries:[];if(l.length===0&&!D){const u=c.filters&&(c.filters.action||c.filters.outcome||c.filters.since||c.filters.until)?"No entries match your filters.":"No audit log entries yet. Actions will be logged automatically.";L.innerHTML=`<div class="panel-empty"><span class="empty-icon">\u{1F4DC}</span>${escapeHtml(u)}</div>`,w.style.display="none";return}let m="";D||(m='<table style="width: 100%; border-collapse: collapse; font-size: 0.82rem;">',m+='<tr style="border-bottom: 1px solid var(--border); color: var(--muted);">',m+='<th style="padding: 6px; text-align: left;">When</th>',m+='<th style="padding: 6px; text-align: left;">Actor</th>',m+='<th style="padding: 6px; text-align: left;">IP</th>',m+='<th style="padding: 6px; text-align: left;">Action</th>',m+='<th style="padding: 6px; text-align: left;">Resource</th>',m+='<th style="padding: 6px; text-align: left;">Result</th>',m+="</tr>");for(const u of l){const t=u.outcome==="success",e=H(u);m+='<tr style="border-bottom: 1px solid var(--border); cursor: pointer;" class="audit-row">',m+=`<td style="padding: 6px; color: var(--muted);" title="${escapeHtml(u.timestamp||"")}">${timeAgo(u.timestamp)}</td>`,m+=`<td style="padding: 6px; font-size: 0.78rem;">${e}</td>`,m+=`<td style="padding: 6px; font-family: monospace; font-size: 0.78rem;">${escapeHtml(u.ip||"-")}</td>`,m+=`<td style="padding: 6px; font-weight: 500;">${escapeHtml(u.action||"-")}</td>`,m+=`<td style="padding: 6px;">${escapeHtml(u.resource||"-")}</td>`,m+=`<td style="padding: 6px;"><span style="color: ${t?"var(--ok-fg)":"var(--bad-fg)"};">${t?"\u2713":"\u2717"} ${escapeHtml(u.outcome||"")}</span></td>`,m+="</tr>",u.details&&Object.keys(u.details).length>0&&(m+=`<tr class="audit-detail" style="display: none;"><td colspan="6" style="padding: 6px 6px 10px; font-size: 0.78rem; color: var(--muted);"><pre style="margin: 0; white-space: pre-wrap; font-family: monospace;">${escapeHtml(JSON.stringify(u.details,null,2))}</pre></td></tr>`)}if(!D)m+="</table>",L.innerHTML=m;else{const u=L.querySelector("table");u&&u.insertAdjacentHTML("beforeend",m)}$+=l.length,w.style.display=c.hasMore?"":"none",L.querySelectorAll(".audit-row").forEach(u=>{u.dataset.wired||(u.dataset.wired="true",u.addEventListener("click",()=>{const t=u.nextElementSibling;t&&t.classList.contains("audit-detail")&&(t.style.display=t.style.display==="none"?"":"none")}))})}catch(O){if(O&&O.name==="AbortError")return;L.innerHTML=`<div class="panel-empty" style="color: var(--bad-fg);">Failed: ${escapeHtml(O.message)}</div>`}}function H(D){const O=D.details||{},p=O.userEmail,v=O.userId,b=O.userRole,y=O.viaProvider;if(p){const h=b?` <span style="color: var(--muted); font-size: 0.72rem;">[${escapeHtml(b)}${y?"/"+escapeHtml(y):""}]</span>`:"";return`${escapeHtml(p)}${h}`}return v?`<span style="font-family: monospace; color: var(--muted);">${escapeHtml(v)}</span>`:D.ip?'<span style="color: var(--muted);">anon</span>':'<span style="color: var(--muted);">system</span>'}B?.addEventListener("click",()=>{x?.classList.add("show"),j(!1)}),wireModal(x,A),C?.addEventListener("click",()=>j(!1)),P?.addEventListener("change",()=>j(!1)),z?.addEventListener("change",()=>j(!1));let R;[N,f].forEach(D=>{D?.addEventListener("change",()=>{clearTimeout(R),R=setTimeout(()=>j(!1),250)})}),w?.addEventListener("click",()=>j(!0)),M?.addEventListener("click",async()=>{if(confirm("Clear the entire audit log? This cannot be undone."))try{const O=await(await secureFetch("/api/v1/audit-logs",{method:"DELETE"Line truncated
<div class="weather-modal-content" style="min-width: 980px; max-width: 1280px;">
<h3>\u{1F6E1}\uFE0F Security Center</h3>
<p class="modal-subtitle">
@@ -1771,39 +1820,39 @@ Enter version to rollback to:`);if(!a)return;if(!e.includes(a)){showNotification
<button id="sec-cancel">Close</button>
</div>
</div>
</div>`);const f=document.getElementById("security-modal"),I=document.getElementById("security-center-btn"),A=document.getElementById("sec-cancel"),E=f.querySelectorAll(".sec-tab"),M=f.querySelectorAll(".sec-panel");let P=[],z=[],D=null;E.forEach(r=>{r.addEventListener("click",()=>{E.forEach(c=>c.classList.toggle("active",c===r)),M.forEach(c=>c.style.display=c.dataset.panel===r.dataset.tab?"":"none"),r.dataset.tab==="overview"&&$(),r.dataset.tab==="events"&&N(),r.dataset.tab==="hosts"&&m()})}),I&&I.addEventListener("click",()=>{f.classList.add("show"),$(),B()}),A.addEventListener("click",v),f.addEventListener("click",r=>{r.target===f&&v()});function v(){f.classList.remove("show"),x()}function B(){if(x(),!!document.getElementById("sec-live-tail").checked&&!(typeof EventSource>"u"))try{D=new EventSource("/api/v1/security/events/stream"),D.addEventListener("init",r=>{try{P=JSON.parse(r.data).events||[],R()}catch{}}),D.addEventListener("security",r=>{try{const c=JSON.parse(r.data);P.unshift(c),P.length>500&&(P.length=500);const d=f.querySelector(".sec-tab.active")?.dataset?.tab;d==="events"?R():d==="overview"&&$()}catch{}}),D.onerror=()=>{}}catch(r){console.warn("[security] SSE failed:",r.message)}}function x(){if(D){try{D.close()}catch{}D=null}}document.getElementById("sec-live-tail").addEventListener("change",()=>{f.classList.contains("show")&&B()});async function $(){try{const r=new Date(Date.now()-864e5).toISOString(),[c,d,b]=await Promise.all([fetch(`/api/v1/security/events/stats?since=${encodeURIComponent(r)}`),fetch("/api/v1/security/hosts"),fetch(`/api/v1/security/events?limit=1&since=${encodeURIComponent(r)}`)]),y=(await c.json()).data||{},t=(await d.json()).data?.hosts||[],e=(await b.json()).data?.total||0;document.querySelector('#sec-stats [data-key="total"]').textContent=`${e} events (24h)`,document.querySelector('#sec-stats [data-key="warn"]').textContent=`${y.by_severity?.warn||0} warnings`,document.querySelector('#sec-stats [data-key="error"]').textContent=`${y.by_severity?.error||0} errors`,document.querySelector('#sec-stats [data-key="denied"]').textContent=`${y.by_outcome?.denied||0} denied`,document.querySelector('#sec-stats [data-key="hosts"]').textContent=`${t.length} hosts`,k("sec-top-actors",y.top_actors||[]),k("sec-top-targets",y.top_targets||[])}catch(r){console.warn("[security] refreshOverview failed:",r.message)}}function k(r,c){const d=document.getElementById(r);if(!c.length){d.innerHTML='<div class="panel-empty">No data</div>';return}d.innerHTML='<table style="width:100%;font-size:0.85rem;">'+c.map(b=>`<tr><td style="padding:3px 0;word-break:break-all;">${g(String(b.key))}</td><td style="text-align:right;color:var(--muted);">${b.count}</td></tr>`).join("")+"</table>"}const T=document.getElementById("sec-filter-source"),S=document.getElementById("sec-filter-severity"),L=document.getElementById("sec-filter-host"),j=document.getElementById("sec-filter-actor"),C=document.getElementById("sec-refresh-btn");[T,S,L].forEach(r=>r.addEventListener("change",N)),j.addEventListener("input",H(N,250)),C.addEventListener("click",N);async function N(){try{const r=new URLSearchParams;r.set("limit","200"),T.value&&r.set("source_type",T.value),S.value&&r.set("severity",S.value),L.value&&r.set("source_host",L.value),j.value&&r.set("actor_prefix",j.value),P=(await(await fetch(`/api/v1/security/events?${r}`)).json()).data.events||[],R(),(!L.options.length||L.options.length===1)&&await u()}catch(r){document.getElementById("sec-events-container").innerHTML='<div class="panel-empty">Load failed: '+g(r.message)+"</div>"}}function R(){const r=document.getElementById("sec-events-container");if(!P.length){r.innerHTML='<div class="panel-empty">No events</div>';return}r.innerHTML=P.slice(0,200).map(U).join("")}function U(r){const c=r.severity||"info",d={critical:"#c0392b",error:"#e74c3c",warn:"#f39c12",notice:"#3498db",info:"#7f8c8d"}[c]||"#7f8c8d",b=r.ts?new Date(r.ts).toLocaleTimeString():"",y=r.source_type||"",t=r.actor||"\u2014",e=r.target||"",a=r.action||"",o=r.outcome||"";return`<div class="sec-event-row" style="display:grid;grid-template-columns:84px 80px 1fr 1fr 100px 90px;gap:8px;padding:5px 8px;border-bottom:1px solid var(--border);font-size:0.82rem;align-items:center;">
<span style="color:${d};font-weight:600;">${g(c)}</span>
<span style="color:var(--muted);font-size:0.75rem;">${g(y)}</span>
<span title="${g(t)}" style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">${g(t)}</span>
<span title="${g(e)}" style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">${g(a)} ${g(e)}</span>
<span style="color:var(--muted);font-size:0.75rem;">${g(o)}</span>
<span style="color:var(--muted);font-size:0.75rem;text-align:right;">${g(b)}</span>
</div>`}async function u(){try{const c=(await(await fetch("/api/v1/security/hosts")).json()).data?.hosts||[],d=L.value;L.innerHTML='<option value="">All hosts</option>'+c.map(b=>`<option value="${g(b.id)}">${g(b.label||b.id)}</option>`).join(""),d&&(L.value=d)}catch{}}document.getElementById("sec-host-register-btn").addEventListener("click",h),document.getElementById("sec-hosts-refresh").addEventListener("click",m);async function m(){try{const c=(await(await fetch("/api/v1/security/hosts")).json()).data?.hosts||[];z=c;const d=document.getElementById("sec-hosts-container");if(!c.length){d.innerHTML='<div class="panel-empty">No hosts registered. Click \u2795 Register Host to add one.</div>';return}d.innerHTML=c.map(b=>{const y=b.enabled?b.last_seen_at?Date.now()-Date.parse(b.last_seen_at)>18e5?"\u{1F7E1} stale":"\u{1F7E2} online":"\u26AA registered":"\u{1F534} disabled";return`<div style="padding:10px 12px;border-bottom:1px solid var(--border);display:flex;justify-content:space-between;align-items:center;">
</div>`);const x=document.getElementById("security-modal"),B=document.getElementById("security-center-btn"),A=document.getElementById("sec-cancel"),C=x.querySelectorAll(".sec-tab"),M=x.querySelectorAll(".sec-panel");let P=[],z=[],N=null;C.forEach(s=>{s.addEventListener("click",()=>{C.forEach(c=>c.classList.toggle("active",c===s)),M.forEach(c=>c.style.display=c.dataset.panel===s.dataset.tab?"":"none"),s.dataset.tab==="overview"&&$(),s.dataset.tab==="events"&&R(),s.dataset.tab==="hosts"&&v()})}),B&&B.addEventListener("click",()=>{x.classList.add("show"),$(),L()}),A.addEventListener("click",f),x.addEventListener("click",s=>{s.target===x&&f()});function f(){x.classList.remove("show"),w()}function L(){if(w(),!!document.getElementById("sec-live-tail").checked&&!(typeof EventSource>"u"))try{N=new EventSource("/api/v1/security/events/stream"),N.addEventListener("init",s=>{try{P=JSON.parse(s.data).events||[],D()}catch{}}),N.addEventListener("security",s=>{try{const c=JSON.parse(s.data);P.unshift(c),P.length>500&&(P.length=500);const l=x.querySelector(".sec-tab.active")?.dataset?.tab;l==="events"?D():l==="overview"&&$()}catch{}}),N.onerror=()=>{}}catch(s){console.warn("[security] SSE failed:",s.message)}}function w(){if(N){try{N.close()}catch{}N=null}}document.getElementById("sec-live-tail").addEventListener("change",()=>{x.classList.contains("show")&&L()});async function $(){try{const s=new Date(Date.now()-864e5).toISOString(),[c,l,m]=await Promise.all([fetch(`/api/v1/security/events/stats?since=${encodeURIComponent(s)}`),fetch("/api/v1/security/hosts"),fetch(`/api/v1/security/events?limit=1&since=${encodeURIComponent(s)}`)]),u=(await c.json()).data||{},t=(await l.json()).data?.hosts||[],e=(await m.json()).data?.total||0;document.querySelector('#sec-stats [data-key="total"]').textContent=`${e} events (24h)`,document.querySelector('#sec-stats [data-key="warn"]').textContent=`${u.by_severity?.warn||0} warnings`,document.querySelector('#sec-stats [data-key="error"]').textContent=`${u.by_severity?.error||0} errors`,document.querySelector('#sec-stats [data-key="denied"]').textContent=`${u.by_outcome?.denied||0} denied`,document.querySelector('#sec-stats [data-key="hosts"]').textContent=`${t.length} hosts`,k("sec-top-actors",u.top_actors||[]),k("sec-top-targets",u.top_targets||[])}catch(s){console.warn("[security] refreshOverview failed:",s.message)}}function k(s,c){const l=document.getElementById(s);if(!c.length){l.innerHTML='<div class="panel-empty">No data</div>';return}l.innerHTML='<table style="width:100%;font-size:0.85rem;">'+c.map(m=>`<tr><td style="padding:3px 0;word-break:break-all;">${y(String(m.key))}</td><td style="text-align:right;color:var(--muted);">${m.count}</td></tr>`).join("")+"</table>"}const T=document.getElementById("sec-filter-source"),E=document.getElementById("sec-filter-severity"),I=document.getElementById("sec-filter-host"),j=document.getElementById("sec-filter-actor"),H=document.getElementById("sec-refresh-btn");[T,E,I].forEach(s=>s.addEventListener("change",R)),j.addEventListener("input",h(R,250)),H.addEventListener("click",R);async function R(){try{const s=new URLSearchParams;s.set("limit","200"),T.value&&s.set("source_type",T.value),E.value&&s.set("severity",E.value),I.value&&s.set("source_host",I.value),j.value&&s.set("actor_prefix",j.value),P=(await(await fetch(`/api/v1/security/events?${s}`)).json()).data.events||[],D(),(!I.options.length||I.options.length===1)&&await p()}catch(s){document.getElementById("sec-events-container").innerHTML='<div class="panel-empty">Load failed: '+y(s.message)+"</div>"}}function D(){const s=document.getElementById("sec-events-container");if(!P.length){s.innerHTML='<div class="panel-empty">No events</div>';return}s.innerHTML=P.slice(0,200).map(O).join("")}function O(s){const c=s.severity||"info",l={critical:"#c0392b",error:"#e74c3c",warn:"#f39c12",notice:"#3498db",info:"#7f8c8d"}[c]||"#7f8c8d",m=s.ts?new Date(s.ts).toLocaleTimeString():"",u=s.source_type||"",t=s.actor||"\u2014",e=s.target||"",a=s.action||"",o=s.outcome||"";return`<div class="sec-event-row" style="display:grid;grid-template-columns:84px 80px 1fr 1fr 100px 90px;gap:8px;padding:5px 8px;border-bottom:1px solid var(--border);font-size:0.82rem;align-items:center;">
<span style="color:${l};font-weight:600;">${y(c)}</span>
<span style="color:var(--muted);font-size:0.75rem;">${y(u)}</span>
<span title="${y(t)}" style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">${y(t)}</span>
<span title="${y(e)}" style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">${y(a)} ${y(e)}</span>
<span style="color:var(--muted);font-size:0.75rem;">${y(o)}</span>
<span style="color:var(--muted);font-size:0.75rem;text-align:right;">${y(m)}</span>
</div>`}async function p(){try{const c=(await(await fetch("/api/v1/security/hosts")).json()).data?.hosts||[],l=I.value;I.innerHTML='<option value="">All hosts</option>'+c.map(m=>`<option value="${y(m.id)}">${y(m.label||m.id)}</option>`).join(""),l&&(I.value=l)}catch{}}document.getElementById("sec-host-register-btn").addEventListener("click",b),document.getElementById("sec-hosts-refresh").addEventListener("click",v);async function v(){try{const c=(await(await fetch("/api/v1/security/hosts")).json()).data?.hosts||[];z=c;const l=document.getElementById("sec-hosts-container");if(!c.length){l.innerHTML='<div class="panel-empty">No hosts registered. Click \u2795 Register Host to add one.</div>';return}l.innerHTML=c.map(m=>{const u=m.enabled?m.last_seen_at?Date.now()-Date.parse(m.last_seen_at)>18e5?"\u{1F7E1} stale":"\u{1F7E2} online":"\u26AA registered":"\u{1F534} disabled";return`<div style="padding:10px 12px;border-bottom:1px solid var(--border);display:flex;justify-content:space-between;align-items:center;">
<div>
<strong>${g(b.label||b.id)}</strong>
<span style="color:var(--muted);margin-left:8px;font-size:0.8rem;">${g(b.type)}</span>
<strong>${y(m.label||m.id)}</strong>
<span style="color:var(--muted);margin-left:8px;font-size:0.8rem;">${y(m.type)}</span>
<div style="color:var(--muted);font-size:0.78rem;margin-top:2px;">
id: ${g(b.id)} \xB7
registered ${new Date(b.registered_at).toLocaleDateString()} \xB7
last seen ${b.last_seen_at?new Date(b.last_seen_at).toLocaleString():"never"}
id: ${y(m.id)} \xB7
registered ${new Date(m.registered_at).toLocaleDateString()} \xB7
last seen ${m.last_seen_at?new Date(m.last_seen_at).toLocaleString():"never"}
</div>
</div>
<div>
<span style="font-size:0.85rem;margin-right:12px;">${y}</span>
${b.id==="self"?"":`<button class="btn-sm sec-host-del" data-id="${g(b.id)}" style="color:var(--bad-fg);">Remove</button>`}
<span style="font-size:0.85rem;margin-right:12px;">${u}</span>
${m.id==="self"?"":`<button class="btn-sm sec-host-del" data-id="${y(m.id)}" style="color:var(--bad-fg);">Remove</button>`}
</div>
</div>`}).join(""),d.querySelectorAll(".sec-host-del").forEach(b=>{b.addEventListener("click",async()=>{confirm(`Remove host ${b.dataset.id}? Events already received will remain in the store.`)&&(await fetch(`/api/v1/security/hosts/${encodeURIComponent(b.dataset.id)}`,{method:"DELETE"}),m())})})}catch(r){document.getElementById("sec-hosts-container").innerHTML='<div class="panel-empty">Load failed: '+g(r.message)+"</div>"}}async function h(){const r=prompt("Host id (lowercase, no spaces):");if(!r)return;const c=prompt("Display label:",r)||r,d=prompt('Type ("dashcaddy", "service", or "agent"):',"agent")||"agent";try{const b=await fetch("/api/v1/security/hosts",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({id:r,label:c,type:d})}),y=await b.json();if(!b.ok){alert("Failed: "+(y?.error?.message||b.statusText));return}alert(`\u2705 Host registered!
</div>`}).join(""),l.querySelectorAll(".sec-host-del").forEach(m=>{m.addEventListener("click",async()=>{confirm(`Remove host ${m.dataset.id}? Events already received will remain in the store.`)&&(await fetch(`/api/v1/security/hosts/${encodeURIComponent(m.dataset.id)}`,{method:"DELETE"}),v())})})}catch(s){document.getElementById("sec-hosts-container").innerHTML='<div class="panel-empty">Load failed: '+y(s.message)+"</div>"}}async function b(){const s=prompt("Host id (lowercase, no spaces):");if(!s)return;const c=prompt("Display label:",s)||s,l=prompt('Type ("dashcaddy", "service", or "agent"):',"agent")||"agent";try{const m=await fetch("/api/v1/security/hosts",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({id:s,label:c,type:l})}),u=await m.json();if(!m.ok){alert("Failed: "+(u?.error?.message||m.statusText));return}alert(`\u2705 Host registered!
id: ${y.data.host.id}
label: ${y.data.host.label}
type: ${y.data.host.type}
id: ${u.data.host.id}
label: ${u.data.host.label}
type: ${u.data.host.type}
\u{1F511} API KEY (save this NOW \u2014 won't be shown again):
${y.data.api_key}
${u.data.api_key}
Send this key as: Authorization: Bearer <api_key>
To endpoint: POST /api/v1/security/events/ingest or /events/batch`),m()}catch(b){alert("Failed: "+b.message)}}function g(r){return String(r).replace(/[&<>"']/g,c=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[c])}function H(r,c){let d;return function(){clearTimeout(d),d=setTimeout(()=>r.apply(this,arguments),c)}}})(),(function(){const f=new ErrorHandler;injectModal("weather-modal",`<div id="weather-modal" class="weather-modal"><div class="weather-modal-content"><h3>Weather Settings</h3>
To endpoint: POST /api/v1/security/events/ingest or /events/batch`),v()}catch(m){alert("Failed: "+m.message)}}function y(s){return String(s).replace(/[&<>"']/g,c=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[c])}function h(s,c){let l;return function(){clearTimeout(l),l=setTimeout(()=>s.apply(this,arguments),c)}}})(),(function(){const x=new ErrorHandler;injectModal("weather-modal",`<div id="weather-modal" class="weather-modal"><div class="weather-modal-content"><h3>Weather Settings</h3>
<label for="weather-location-input">Location:</label>
<input type="text" id="weather-location-input" placeholder="City name or ZIP (e.g., Hamburg, 90210)" maxlength="100">
<div style="font-size: 0.78rem; color: var(--muted); margin-top: 4px;">Enter a city name, postal code, or &ldquo;City, Country&rdquo;</div>
@@ -1814,23 +1863,23 @@ To endpoint: POST /api/v1/security/events/ingest or /events/batch`),m()}catch(b)
<label class="weather-unit-option"><input type="radio" name="weather-unit-radio" value="metric"><span class="weather-unit-card">&deg;C / km/h</span></label>
</div>
</div>
<div class="weather-modal-buttons"><button id="weather-cancel">Cancel</button><button id="weather-save">Save</button></div></div></div>`);const I="weather-location",A="weather-zip",E="weather-geo",M="weather-unit";!safeGet(I)&&safeGet(A)&&safeSet(I,safeGet(A));function P(){return safeGet(M)||"imperial"}function z(){return{icon:document.querySelector(".weather-icon"),temp:document.querySelector(".weather-temp"),condition:document.querySelector(".weather-condition"),location:document.querySelector(".weather-location"),wind:document.querySelector(".weather-wind")}}const D={0:"Clear sky",1:"Mainly clear",2:"Partly cloudy",3:"Overcast",45:"Fog",48:"Rime fog",51:"Light drizzle",53:"Drizzle",55:"Dense drizzle",56:"Freezing drizzle",57:"Dense freezing drizzle",61:"Light rain",63:"Moderate rain",65:"Heavy rain",66:"Light freezing rain",67:"Heavy freezing rain",71:"Light snow",73:"Moderate snow",75:"Heavy snow",77:"Snow grains",80:"Light showers",81:"Moderate showers",82:"Violent showers",85:"Light snow showers",86:"Heavy snow showers",95:"Thunderstorm",96:"Thunderstorm with hail",99:"Severe thunderstorm"},v={0:"\u2600\uFE0F",1:"\u{1F324}\uFE0F",2:"\u26C5",3:"\u2601\uFE0F",45:"\u{1F32B}\uFE0F",48:"\u{1F32B}\uFE0F",51:"\u{1F326}\uFE0F",53:"\u{1F326}\uFE0F",55:"\u{1F326}\uFE0F",56:"\u{1F328}\uFE0F",57:"\u{1F328}\uFE0F",61:"\u{1F326}\uFE0F",63:"\u{1F327}\uFE0F",65:"\u{1F327}\uFE0F",66:"\u{1F328}\uFE0F",67:"\u{1F328}\uFE0F",71:"\u{1F328}\uFE0F",73:"\u2744\uFE0F",75:"\u2744\uFE0F",77:"\u2744\uFE0F",80:"\u{1F326}\uFE0F",81:"\u{1F327}\uFE0F",82:"\u{1F327}\uFE0F",85:"\u{1F328}\uFE0F",86:"\u2744\uFE0F",95:"\u26C8\uFE0F",96:"\u26C8\uFE0F",99:"\u26C8\uFE0F"},B=["N","NNE","NE","ENE","E","ESE","SE","SSE","S","SSW","SW","WSW","W","WNW","NW","NNW"];function x(C){return B[Math.round(C/22.5)%16]}async function $(C){const N=safeGet(E);if(N)try{const h=JSON.parse(N);if(h.query===C)return h}catch{}const R=await fetch(`https://geocoding-api.open-meteo.com/v1/search?name=${encodeURIComponent(C)}&count=1&language=en&format=json`);if(!R.ok)throw new Error("Geocoding failed");const U=await R.json();if(!U.results||!U.results.length)throw new Error("Location not found");const u=U.results[0],m={query:C,lat:u.latitude,lon:u.longitude,city:u.name,state:u.admin1||"",country:u.country||"",countryCode:u.country_code||""};return safeSet(E,JSON.stringify(m)),m}function k(C){return C.countryCode==="US"&&C.state?`${C.city}, ${C.state}`:C.country?`${C.city}, ${C.country}`:C.city}async function T(C){try{const N=await $(C),R=P(),U=R==="metric"?"celsius":"fahrenheit",u=R==="metric"?"kmh":"mph",m=`https://api.open-meteo.com/v1/forecast?latitude=${N.lat}&longitude=${N.lon}&current=temperature_2m,weather_code,wind_speed_10m,wind_direction_10m&temperature_unit=${U}&wind_speed_unit=${u}`,h=await fetch(m);if(!h.ok)throw new Error("Weather fetch failed");const H=(await h.json()).current,r=H.weather_code;return{temp:Math.round(H.temperature_2m),condition:D[r]||"Unknown",icon:v[r]||"\u{1F324}\uFE0F",locationStr:k(N),windSpeed:Math.round(H.wind_speed_10m),windDir:x(H.wind_direction_10m),unit:R}}catch(N){return console.warn("Weather fetch failed:",N),null}}async function S(){const C=z();if(!C.icon||!C.temp||!C.condition||!C.location||!C.wind){console.warn("Weather widget elements not found");return}const N=safeGet(I);if(!N){C.location.textContent="Set Location",C.temp.textContent="--\xB0",C.condition.textContent="Click \u2699\uFE0F to configure",C.wind.textContent="--",C.icon.innerHTML='<span class="weather-emoji">\u{1F324}\uFE0F</span>';return}try{const R=await T(N);if(R){const U=R.unit==="metric"?"\xB0C":"\xB0F",u=R.unit==="metric"?"km/h":"mph";C.location.textContent=R.locationStr,C.temp.textContent=`${R.temp}${U}`,C.condition.textContent=R.condition,C.wind.textContent=`Wind: ${R.windSpeed} ${u} ${R.windDir}`,C.icon.innerHTML=`<span class="weather-emoji">${escapeHtml(R.icon)}</span>`}}catch(R){f.logError("[Weather] Update Error",R,{function:"updateWeather"}),C.location.textContent="Weather Error",C.temp.textContent="Error",C.condition.textContent="Failed to load",C.wind.textContent="--"}}const L=document.getElementById("weather-modal"),j=document.getElementById("weather-location-input");document.getElementById("weather-settings")?.addEventListener("click",()=>{j.value=safeGet(I)||"";const C=P(),N=L.querySelector(`input[name="weather-unit-radio"][value="${C}"]`);N&&(N.checked=!0),L.classList.add("show"),j.focus()}),document.getElementById("weather-cancel")?.addEventListener("click",()=>{L.classList.remove("show")}),document.getElementById("weather-save")?.addEventListener("click",()=>{const C=j.value.trim();if(C){safeGet(I)!==C&&safeSet(E,""),safeSet(I,C);const R=L.querySelector('input[name="weather-unit-radio"]:checked'),U=R?R.value:"imperial",u=P();safeSet(M,U),u!==U&&safeSet(E,""),L.classList.remove("show"),S()}else showNotification("Please enter a location (e.g., Hamburg, London, 90210)","warning")}),wireModal(L),document.addEventListener("keydown",C=>{C.keyLine truncated
<circle cx="${s}" cy="${l}" r="58" fill="none" stroke="var(--border)" stroke-width="2"/>
<div class="weather-modal-buttons"><button id="weather-cancel">Cancel</button><button id="weather-save">Save</button></div></div></div>`);const B="weather-location",A="weather-zip",C="weather-geo",M="weather-unit";!safeGet(B)&&safeGet(A)&&safeSet(B,safeGet(A));function P(){return safeGet(M)||"imperial"}function z(){return{icon:document.querySelector(".weather-icon"),temp:document.querySelector(".weather-temp"),condition:document.querySelector(".weather-condition"),location:document.querySelector(".weather-location"),wind:document.querySelector(".weather-wind")}}const N={0:"Clear sky",1:"Mainly clear",2:"Partly cloudy",3:"Overcast",45:"Fog",48:"Rime fog",51:"Light drizzle",53:"Drizzle",55:"Dense drizzle",56:"Freezing drizzle",57:"Dense freezing drizzle",61:"Light rain",63:"Moderate rain",65:"Heavy rain",66:"Light freezing rain",67:"Heavy freezing rain",71:"Light snow",73:"Moderate snow",75:"Heavy snow",77:"Snow grains",80:"Light showers",81:"Moderate showers",82:"Violent showers",85:"Light snow showers",86:"Heavy snow showers",95:"Thunderstorm",96:"Thunderstorm with hail",99:"Severe thunderstorm"},f={0:"\u2600\uFE0F",1:"\u{1F324}\uFE0F",2:"\u26C5",3:"\u2601\uFE0F",45:"\u{1F32B}\uFE0F",48:"\u{1F32B}\uFE0F",51:"\u{1F326}\uFE0F",53:"\u{1F326}\uFE0F",55:"\u{1F326}\uFE0F",56:"\u{1F328}\uFE0F",57:"\u{1F328}\uFE0F",61:"\u{1F326}\uFE0F",63:"\u{1F327}\uFE0F",65:"\u{1F327}\uFE0F",66:"\u{1F328}\uFE0F",67:"\u{1F328}\uFE0F",71:"\u{1F328}\uFE0F",73:"\u2744\uFE0F",75:"\u2744\uFE0F",77:"\u2744\uFE0F",80:"\u{1F326}\uFE0F",81:"\u{1F327}\uFE0F",82:"\u{1F327}\uFE0F",85:"\u{1F328}\uFE0F",86:"\u2744\uFE0F",95:"\u26C8\uFE0F",96:"\u26C8\uFE0F",99:"\u26C8\uFE0F"},L=["N","NNE","NE","ENE","E","ESE","SE","SSE","S","SSW","SW","WSW","W","WNW","NW","NNW"];function w(H){return L[Math.round(H/22.5)%16]}async function $(H){const R=safeGet(C);if(R)try{const b=JSON.parse(R);if(b.query===H)return b}catch{}const D=await fetch(`https://geocoding-api.open-meteo.com/v1/search?name=${encodeURIComponent(H)}&count=1&language=en&format=json`);if(!D.ok)throw new Error("Geocoding failed");const O=await D.json();if(!O.results||!O.results.length)throw new Error("Location not found");const p=O.results[0],v={query:H,lat:p.latitude,lon:p.longitude,city:p.name,state:p.admin1||"",country:p.country||"",countryCode:p.country_code||""};return safeSet(C,JSON.stringify(v)),v}function k(H){return H.countryCode==="US"&&H.state?`${H.city}, ${H.state}`:H.country?`${H.city}, ${H.country}`:H.city}async function T(H){try{const R=await $(H),D=P(),O=D==="metric"?"celsius":"fahrenheit",p=D==="metric"?"kmh":"mph",v=`https://api.open-meteo.com/v1/forecast?latitude=${R.lat}&longitude=${R.lon}&current=temperature_2m,weather_code,wind_speed_10m,wind_direction_10m&temperature_unit=${O}&wind_speed_unit=${p}`,b=await fetch(v);if(!b.ok)throw new Error("Weather fetch failed");const h=(await b.json()).current,s=h.weather_code;return{temp:Math.round(h.temperature_2m),condition:N[s]||"Unknown",icon:f[s]||"\u{1F324}\uFE0F",locationStr:k(R),windSpeed:Math.round(h.wind_speed_10m),windDir:w(h.wind_direction_10m),unit:D}}catch(R){return console.warn("Weather fetch failed:",R),null}}async function E(){const H=z();if(!H.icon||!H.temp||!H.condition||!H.location||!H.wind){console.warn("Weather widget elements not found");return}const R=safeGet(B);if(!R){H.location.textContent="Set Location",H.temp.textContent="--\xB0",H.condition.textContent="Click \u2699\uFE0F to configure",H.wind.textContent="--",H.icon.innerHTML='<span class="weather-emoji">\u{1F324}\uFE0F</span>';return}try{const D=await T(R);if(D){const O=D.unit==="metric"?"\xB0C":"\xB0F",p=D.unit==="metric"?"km/h":"mph";H.location.textContent=D.locationStr,H.temp.textContent=`${D.temp}${O}`,H.condition.textContent=D.condition,H.wind.textContent=`Wind: ${D.windSpeed} ${p} ${D.windDir}`,H.icon.innerHTML=`<span class="weather-emoji">${escapeHtml(D.icon)}</span>`}}catch(D){x.logError("[Weather] Update Error",D,{function:"updateWeather"}),H.location.textContent="Weather Error",H.temp.textContent="Error",H.condition.textContent="Failed to load",H.wind.textContent="--"}}const I=document.getElementById("weather-modal"),j=document.getElementById("weather-location-input");document.getElementById("weather-settings")?.addEventListener("click",()=>{j.value=safeGet(B)||"";const H=P(),R=I.querySelector(`input[name="weather-unit-radio"][value="${H}"]`);R&&(R.checked=!0),I.classList.add("show"),j.focus()}),document.getElementById("weather-cancel")?.addEventListener("click",()=>{I.classList.remove("show")}),document.getElementById("weather-save")?.addEventListener("click",()=>{const H=j.value.trim();if(H){safeGet(B)!==H&&safeSet(C,""),safeSet(B,H);const D=I.querySelector('input[name="weather-unit-radio"]:checked'),O=D?D.value:"imperial",p=P();safeSet(M,O),p!==O&&safeSet(C,""),I.classList.remove("show"),E()}else showNotification("Please enter a location (e.g., Hamburg, London, 90210)","warning")}),wireModal(I),document.addEventListener("keydown",H=>{H.keyLine truncated
<circle cx="${i}" cy="${d}" r="58" fill="none" stroke="var(--border)" stroke-width="2"/>
${F}
${_}
<line x1="${s}" y1="${l}" x2="${s+28*Math.cos(O*Math.PI/180)}" y2="${l+28*Math.sin(O*Math.PI/180)}" stroke="var(--fg)" stroke-width="3" stroke-linecap="round"/>
<line x1="${s}" y1="${l}" x2="${s+38*Math.cos(w*Math.PI/180)}" y2="${l+38*Math.sin(w*Math.PI/180)}" stroke="var(--fg)" stroke-width="2" stroke-linecap="round"/>
<line x1="${s}" y1="${l}" x2="${s+42*Math.cos(p*Math.PI/180)}" y2="${l+42*Math.sin(p*Math.PI/180)}" stroke="#e74c3c" stroke-width="1" stroke-linecap="round"/>
<circle cx="${s}" cy="${l}" r="3" fill="var(--fg)"/>
</svg>`,J=t.getHours()>=12?"PM":"AM";I.innerHTML=`<div class="analog-clock-wrap">${q}<div class="analog-info"><span class="analog-digital">${t.getHours()%12||12}:${String(o).padStart(2,"0")} ${J}</span><span class="analog-date-sm">${T(t)}</span></div></div>`,B="analog"}function m(){const t=new Date,e=t.getHours()%12||12,a=t.getMinutes(),o=t.getSeconds(),i="clock-widget"+(P!=="default"?" "+P:"");switch(f.className!==i&&(f.className=i),P){case"lcd":C(t);break;case"lcd-blue":C(t);break;case"lcd-amber":C(t);break;case"lcd-retro":C(t);break;case"lcd-taxi":C(t);break;case"flip":N(t);break;case"binary":U(t);break;case"analog":u(t,!1);break;case"roman":u(t,!0);break;default:j(t)}a===0&&o===0&&e!==z&&(z=e,k(e)),a!==0&&(z=-1)}function h(){clearTimeout($);const t=document.hidden?6e4:1e3,e=t-Date.now()%t+25;$=setTimeout(()=>{m(),h()},e)}document.addEventListener("visibilitychange",()=>{v="",S(),m(),h()}),m(),h();const g=[{id:"default",label:"Default",icon:"\u{1F550}"},{id:"lcd",label:"LCD Green",icon:"\u{1F49A}"},{id:"lcd-blue",label:"LCD Blue",icon:"\u{1F499}"},{id:"lcd-amber",label:"LCD Amber",icon:"\u{1F7E0}"},{id:"lcd-retro",label:"LCD Retro",icon:"\u{1F7E9}"},{id:"lcd-taxi",label:"LCD Taxi",icon:"\u{1F7E1}"},{id:"flip",label:"Flip Clock",icon:"\u{1F4DF}"},{id:"binary",label:"Binary",icon:"\u{1F4BB}"},{id:"analog",label:"Analog",icon:"\u23F0"},{id:"roman",label:"Roman",icon:"\u{1F3DB}\uFE0F"}];let H='<div class="clock-style-grid">';g.forEach(t=>{H+=`<label class="clock-style-option">
${q}
<line x1="${i}" y1="${d}" x2="${i+28*Math.cos(U*Math.PI/180)}" y2="${d+28*Math.sin(U*Math.PI/180)}" stroke="var(--fg)" stroke-width="3" stroke-linecap="round"/>
<line x1="${i}" y1="${d}" x2="${i+38*Math.cos(S*Math.PI/180)}" y2="${d+38*Math.sin(S*Math.PI/180)}" stroke="var(--fg)" stroke-width="2" stroke-linecap="round"/>
<line x1="${i}" y1="${d}" x2="${i+42*Math.cos(g*Math.PI/180)}" y2="${d+42*Math.sin(g*Math.PI/180)}" stroke="#e74c3c" stroke-width="1" stroke-linecap="round"/>
<circle cx="${i}" cy="${d}" r="3" fill="var(--fg)"/>
</svg>`,J=t.getHours()>=12?"PM":"AM";B.innerHTML=`<div class="analog-clock-wrap">${_}<div class="analog-info"><span class="analog-digital">${t.getHours()%12||12}:${String(o).padStart(2,"0")} ${J}</span><span class="analog-date-sm">${T(t)}</span></div></div>`,L="analog"}function v(){const t=new Date,e=t.getHours()%12||12,a=t.getMinutes(),o=t.getSeconds(),r="clock-widget"+(P!=="default"?" "+P:"");switch(x.className!==r&&(x.className=r),P){case"lcd":H(t);break;case"lcd-blue":H(t);break;case"lcd-amber":H(t);break;case"lcd-retro":H(t);break;case"lcd-taxi":H(t);break;case"flip":R(t);break;case"binary":O(t);break;case"analog":p(t,!1);break;case"roman":p(t,!0);break;default:j(t)}a===0&&o===0&&e!==z&&(z=e,k(e)),a!==0&&(z=-1)}function b(){clearTimeout($);const t=document.hidden?6e4:1e3,e=t-Date.now()%t+25;$=setTimeout(()=>{v(),b()},e)}document.addEventListener("visibilitychange",()=>{f="",E(),v(),b()}),v(),b();const y=[{id:"default",label:"Default",icon:"\u{1F550}"},{id:"lcd",label:"LCD Green",icon:"\u{1F49A}"},{id:"lcd-blue",label:"LCD Blue",icon:"\u{1F499}"},{id:"lcd-amber",label:"LCD Amber",icon:"\u{1F7E0}"},{id:"lcd-retro",label:"LCD Retro",icon:"\u{1F7E9}"},{id:"lcd-taxi",label:"LCD Taxi",icon:"\u{1F7E1}"},{id:"flip",label:"Flip Clock",icon:"\u{1F4DF}"},{id:"binary",label:"Binary",icon:"\u{1F4BB}"},{id:"analog",label:"Analog",icon:"\u23F0"},{id:"roman",label:"Roman",icon:"\u{1F3DB}\uFE0F"}];let h='<div class="clock-style-grid">';y.forEach(t=>{h+=`<label class="clock-style-option">
<input type="radio" name="clock-style-radio" value="${t.id}">
<span class="clock-style-card"><span class="clock-style-icon">${t.icon}</span><span class="clock-style-label">${t.label}</span></span>
</label>`}),H+="</div>",injectModal("clock-settings-modal",`<div id="clock-settings-modal" class="weather-modal">
</label>`}),h+="</div>",injectModal("clock-settings-modal",`<div id="clock-settings-modal" class="weather-modal">
<div class="weather-modal-content" style="max-width: 420px;">
<h3>Clock Settings</h3>
<div style="margin-bottom: 16px;">
<label style="display: block; margin-bottom: 8px; font-weight: 600; color: var(--fg);">Style</label>
${H}
${h}
</div>
<div style="margin-bottom: 16px; padding-top: 12px; border-top: 1px solid var(--border);">
<label style="display: flex; align-items: center; gap: 8px; cursor: pointer; font-weight: 600; color: var(--fg);">
@@ -1854,7 +1903,7 @@ To endpoint: POST /api/v1/security/events/ingest or /events/batch`),m()}catch(b)
<button id="clock-settings-save">Save</button>
</div>
</div>
</div>`);const r=document.getElementById("clock-settings-modal"),c=document.getElementById("clock-chimes-toggle"),d=document.getElementById("clock-chime-volume"),b=document.getElementById("clock-volume-section");function y(){const t=safeGet("clock-style")||"default",e=r.querySelector(`input[value="${t}"]`);e&&(e.checked=!0),c.checked=safeGet("clock-chimes")==="true",d.value=safeGet("clock-chime-volume")||"50",b.style.opacity=c.checked?"1":"0.4"}c?.addEventListener("change",()=>{b.style.opacity=c.checked?"1":"0.4"}),document.getElementById("clock-settings")?.addEventListener("click",()=>{y(),r.classList.add("show")}),document.getElementById("clock-chime-test")?.addEventListener("click",()=>{const t=parseInt(d.value,10)/100,e=new Audio("/assets/sounds/church-bell.mp3");e.volume=t,e.play().catch(()=>{})}),document.getElementById("clock-settings-save")?.addEventListener("click",()=>{const t=r.querySelector('input[name="clock-style-radio"]:checked'),e=t?t.value:"default";safeSet("clock-style",e),safeSet("clock-chimes",String(c.checked)),safeSet("clock-chime-volume",d.value),P=e,v="",S(),m(),h(),r.classList.remove("show"),showNotification("Clock settings saved","success",2e3)}),document.getElementById("clock-settings-cancel")?.addEventListener("click",()=>{r.classList.remove("show")}),wireModal(r),r?.querySelectorAll('input[name="clock-style-radio"]').forEach(t=>{t.addEventListener("change",()=>{P=t.value,v="",S(),m()})})})(),(function(){async function f(){try{const D=await(await fetch("/api/v1/health-checks/status")).json();if(!D.success||!D.status)return;for(const[v,B]of Object.entries(D.status)){const x=document.getElementById("uptime-"+v),$=document.getElementById("uptime-bar-"+v);if(!x)continue;const k=B.uptime?.["24h"];if(k!=null){const T=k.toFixed(1);x.textContent=`${T}% uptime`,x.className="uptime-chip",k>=99.9?x.classList.add("excellent"):k>=99?x.classList.add("good"):k>=95?x.classList.add("degraded"):x.classList.add("poor"),$&&($.style.width=T+"%")}}}catch{console.warn("[Card Badges] Health check API unavailable")}}let I;try{I=new Set(JSON.parse(safeSessionGet("dismissed-updates")||"[]"))}catch{I=new Set}let A=[];async function E(z){try{const v=await(await fetch("/api/v1/updates/available")).json();if(!v.success)return;document.querySelectorAll(".update-available-badge").forEach(x=>x.classList.remove("visible"));const B=v.updates||[];if(A=B,z&&B.length>0){const x=window._lastKnownUpdateCount||0;x>0&&B.length>x&&showNotification(`${B.length} container update(s) available \u2014 click Update Management to review.`,"info"),window._lastKnownUpdateCount=B.length}if(!B.length)return;for(const x of B){const $=window.APPS||[];for(const k of $)if(k.containerId===x.containerId||k.id===x.containerName||k.name===x.containerName){if(I.has(k.id))break;const T=document.getElementById("update-badge-"+k.id),S=document.getElementById("update-btn-"+k.id);T&&(T.classList.add("visible"),T.title="Update available \u2014 click to open Update Management.",T.style.cursor="pointer",T.onclick=L=>{L.stopPropagation(),window.openUpdateModal&&window.openUpdateModal(k.id)}),S&&(S.style.background="#f97316",S.style.borderColor="#f97316",S.style.boxShadow="0 0 6px #f9731688",S.title="Update available \u2014 click to open Update Management.");break}}}catch{console.warn("[Card Badges] Updates API unavailable")}}function M(){setTimeout(()=>{f(),E()},5e3),setInterval(()=>{f(),E(!0)},6e4)}const P=window.refreshAll;P&&(window.refreshAll=async function(){try{await P(),setTimeout(f,1e3)}catch(z){console.warn("[Card Badges] Error in refreshAll hook:",z.message)}}),M()})(),(function(){var f=null,I=null,A={},E={dark:"Dark",light:"Light",blue:"Blue",black:"Black",nord:"Nord",dracula:"Dracula","solarized-dark":"Solarized Dark","solarized-light":"Solarized Light",taxi:"Taxi",ocean:"Ocean"},M=[["bg","Background","base"],["card-base","Card","base"],["fg","Text","base"],["muted","Muted Text","base"],["border","Border","base"],["accent","Accent","accent"],["accent-strong","Accent Strong","accent"],["ok-bg","OK Background","status"],["ok-fg","OK Text","status"],["bad-bg","Error Bg","status"],["bad-fg","Error Text","status"],["dot-ok","Dot OK","status"],["dot-bad","Dot Error","status"],["uptime","Uptime Bar","status"],["hover","Hover","advanced"],["card-hover","Card Hover","advanced"],["base","Tags/Badges","advanced"],["fg-muted","Dim Text","advanced"],["success","Success","advanced"],["error","Error","advanced"],["warning","Warning","advanced"]],P=document.getElementById("theme");if(!P)return;var z=document.getElementById("theme-label");function D(o){if(E[o])return E[o];var i=safeGetJSON(window.USER_THEMES_KEY,{});return i[o]&&i[o].name||o}function v(){z&&(z.textContent=D(window.getActiveTheme()))}P.addEventListener("click",function(){var o=window.THEMES.slice(),i=window.getActiveTheme(),n=o.indexOf(i),s=o[(n+1)%o.length];window.applyTheme(s),v()}),v();function B(){var o={base:"Base Colors",accent:"Accent",status:"Status",advanced:"Advanced (auto-deriLine truncated
</div>`);const s=document.getElementById("clock-settings-modal"),c=document.getElementById("clock-chimes-toggle"),l=document.getElementById("clock-chime-volume"),m=document.getElementById("clock-volume-section");function u(){const t=safeGet("clock-style")||"default",e=s.querySelector(`input[value="${t}"]`);e&&(e.checked=!0),c.checked=safeGet("clock-chimes")==="true",l.value=safeGet("clock-chime-volume")||"50",m.style.opacity=c.checked?"1":"0.4"}c?.addEventListener("change",()=>{m.style.opacity=c.checked?"1":"0.4"}),document.getElementById("clock-settings")?.addEventListener("click",()=>{u(),s.classList.add("show")}),document.getElementById("clock-chime-test")?.addEventListener("click",()=>{const t=parseInt(l.value,10)/100,e=new Audio("/assets/sounds/church-bell.mp3");e.volume=t,e.play().catch(()=>{})}),document.getElementById("clock-settings-save")?.addEventListener("click",()=>{const t=s.querySelector('input[name="clock-style-radio"]:checked'),e=t?t.value:"default";safeSet("clock-style",e),safeSet("clock-chimes",String(c.checked)),safeSet("clock-chime-volume",l.value),P=e,f="",E(),v(),b(),s.classList.remove("show"),showNotification("Clock settings saved","success",2e3)}),document.getElementById("clock-settings-cancel")?.addEventListener("click",()=>{s.classList.remove("show")}),wireModal(s),s?.querySelectorAll('input[name="clock-style-radio"]').forEach(t=>{t.addEventListener("change",()=>{P=t.value,f="",E(),v()})})})(),(function(){async function x(){try{const N=await(await fetch("/api/v1/health-checks/status")).json();if(!N.success||!N.status)return;for(const[f,L]of Object.entries(N.status)){const w=document.getElementById("uptime-"+f),$=document.getElementById("uptime-bar-"+f);if(!w)continue;const k=L.uptime?.["24h"];if(k!=null){const T=k.toFixed(1);w.textContent=`${T}% uptime`,w.className="uptime-chip",k>=99.9?w.classList.add("excellent"):k>=99?w.classList.add("good"):k>=95?w.classList.add("degraded"):w.classList.add("poor"),$&&($.style.width=T+"%")}}}catch{console.warn("[Card Badges] Health check API unavailable")}}let B;try{B=new Set(JSON.parse(safeSessionGet("dismissed-updates")||"[]"))}catch{B=new Set}let A=[];async function C(z){try{const f=await(await fetch("/api/v1/updates/available")).json();if(!f.success)return;document.querySelectorAll(".update-available-badge").forEach(w=>w.classList.remove("visible"));const L=f.updates||[];if(A=L,z&&L.length>0){const w=window._lastKnownUpdateCount||0;w>0&&L.length>w&&showNotification(`${L.length} container update(s) available \u2014 click Update Management to review.`,"info"),window._lastKnownUpdateCount=L.length}if(!L.length)return;for(const w of L){const $=window.APPS||[];for(const k of $)if(k.containerId===w.containerId||k.id===w.containerName||k.name===w.containerName){if(B.has(k.id))break;const T=document.getElementById("update-badge-"+k.id),E=document.getElementById("update-btn-"+k.id);T&&(T.classList.add("visible"),T.title="Update available \u2014 click to open Update Management.",T.style.cursor="pointer",T.onclick=I=>{I.stopPropagation(),window.openUpdateModal&&window.openUpdateModal(k.id)}),E&&(E.style.background="#f97316",E.style.borderColor="#f97316",E.style.boxShadow="0 0 6px #f9731688",E.title="Update available \u2014 click to open Update Management.");break}}}catch{console.warn("[Card Badges] Updates API unavailable")}}function M(){setTimeout(()=>{x(),C()},5e3),setInterval(()=>{x(),C(!0)},6e4)}const P=window.refreshAll;P&&(window.refreshAll=async function(){try{await P(),setTimeout(x,1e3)}catch(z){console.warn("[Card Badges] Error in refreshAll hook:",z.message)}}),M()})(),(function(){var x=null,B=null,A={},C={dark:"Dark",light:"Light",blue:"Blue",black:"Black",nord:"Nord",dracula:"Dracula","solarized-dark":"Solarized Dark","solarized-light":"Solarized Light",taxi:"Taxi",ocean:"Ocean"},M=[["bg","Background","base"],["card-base","Card","base"],["fg","Text","base"],["muted","Muted Text","base"],["border","Border","base"],["accent","Accent","accent"],["accent-strong","Accent Strong","accent"],["ok-bg","OK Background","status"],["ok-fg","OK Text","status"],["bad-bg","Error Bg","status"],["bad-fg","Error Text","status"],["dot-ok","Dot OK","status"],["dot-bad","Dot Error","status"],["uptime","Uptime Bar","status"],["hover","Hover","advanced"],["card-hover","Card Hover","advanced"],["base","Tags/Badges","advanced"],["fg-muted","Dim Text","advanced"],["success","Success","advanced"],["error","Error","advanced"],["warning","Warning","advanced"]],P=document.getElementById("theme");if(!P)return;var z=document.getElementById("theme-label");function N(o){if(C[o])return C[o];var r=safeGetJSON(window.USER_THEMES_KEY,{});return r[o]&&r[o].name||o}function f(){z&&(z.textContent=N(window.getActiveTheme()))}P.addEventListener("click",function(){var o=window.THEMES.slice(),r=window.getActiveTheme(),n=o.indexOf(r),i=o[(n+1)%o.length];window.applyTheme(i),f()}),f();function L(){var o={base:"Base Colors",accent:"Accent",status:"Status",advanced:"Advanced (auto-deriLine truncated
<div class="weather-modal-content" style="min-width: 420px; max-width: 520px;">
<h3>DashCaddy License</h3>
<p style="font-size: 0.85rem; color: var(--muted); margin: 0 0 16px;">
@@ -1891,16 +1940,16 @@ To endpoint: POST /api/v1/security/events/ingest or /events/batch`),m()}catch(b)
<button id="license-activate" class="btn-accent">Activate</button>
</div>
</div>
</div>`);const f=document.getElementById("license-modal"),I=document.getElementById("license-code-input"),A=document.getElementById("license-activate"),E=document.getElementById("license-deactivate"),M=document.getElementById("license-error"),P=document.getElementById("license-success"),z=document.getElementById("license-badge-icon"),D=document.getElementById("license-badge-text"),v=document.getElementById("license-badge"),B=document.getElementById("license-details"),x=document.getElementById("license-feature-list"),$=document.getElementById("license-activate-section");let k=null;function T(){M.style.display="none",P.style.display="none"}function S(h){T(),M.textContent=h,M.style.display="block"}function L(h){T(),P.textContent=h,P.style.display="block"}function j(h){if(k=h,h.active){v.style.background="rgba(46,204,113,0.15)",v.style.color="var(--ok-fg)",z.textContent="\u2605",D.textContent="Premium Active";const r=h.lifetime?"<div>License: <strong>LIFETIME</strong></div>":`<div>Expires: <strong>${new Date(h.expiresAt).toLocaleDateString()}</strong> (${h.daysRemaining} days remaining)</div>`;B.innerHTML=`
<div>Code: <code style="font-family: monospace;">${h.code||"***"}</code></div>
${r}
`,$.style.display="none",A.style.display="none",E.style.display=""}else v.style.background="rgba(149,165,166,0.15)",v.style.color="var(--muted)",z.textContent="\u2606",D.textContent=h.expired?"License Expired":"Free Tier",B.innerHTML=h.expired?"<div>Your license has expired. Enter a new code to renew.</div>":"<div>Enter a license code to unlock premium features.</div>",$.style.display="",A.style.display="",E.style.display="none";const g=h.premiumFeatures||{},H=new Set(h.features||[]);x.innerHTML=Object.entries(g).map(([r,c])=>`<div style="display: flex; align-items: center; gap: 8px; padding: 8px 12px; border-radius: 6px; background: var(--card-bg); border: 1px solid var(--border);">
<span style="font-size: 1.1rem;">${H.has(r)?"\u2705":"\u{1F512}"}</span>
</div>`);const x=document.getElementById("license-modal"),B=document.getElementById("license-code-input"),A=document.getElementById("license-activate"),C=document.getElementById("license-deactivate"),M=document.getElementById("license-error"),P=document.getElementById("license-success"),z=document.getElementById("license-badge-icon"),N=document.getElementById("license-badge-text"),f=document.getElementById("license-badge"),L=document.getElementById("license-details"),w=document.getElementById("license-feature-list"),$=document.getElementById("license-activate-section");let k=null;function T(){M.style.display="none",P.style.display="none"}function E(b){T(),M.textContent=b,M.style.display="block"}function I(b){T(),P.textContent=b,P.style.display="block"}function j(b){if(k=b,b.active){f.style.background="rgba(46,204,113,0.15)",f.style.color="var(--ok-fg)",z.textContent="\u2605",N.textContent="Premium Active";const s=b.lifetime?"<div>License: <strong>LIFETIME</strong></div>":`<div>Expires: <strong>${new Date(b.expiresAt).toLocaleDateString()}</strong> (${b.daysRemaining} days remaining)</div>`;L.innerHTML=`
<div>Code: <code style="font-family: monospace;">${b.code||"***"}</code></div>
${s}
`,$.style.display="none",A.style.display="none",C.style.display=""}else f.style.background="rgba(149,165,166,0.15)",f.style.color="var(--muted)",z.textContent="\u2606",N.textContent=b.expired?"License Expired":"Free Tier",L.innerHTML=b.expired?"<div>Your license has expired. Enter a new code to renew.</div>":"<div>Enter a license code to unlock premium features.</div>",$.style.display="",A.style.display="",C.style.display="none";const y=b.premiumFeatures||{},h=new Set(b.features||[]);w.innerHTML=Object.entries(y).map(([s,c])=>`<div style="display: flex; align-items: center; gap: 8px; padding: 8px 12px; border-radius: 6px; background: var(--card-bg); border: 1px solid var(--border);">
<span style="font-size: 1.1rem;">${h.has(s)?"\u2705":"\u{1F512}"}</span>
<div>
<div style="font-weight: 600; font-size: 0.9rem;">${c.name}</div>
<div style="font-size: 0.78rem; color: var(--muted);">${c.description}</div>
</div>
</div>`).join("")}async function C(){try{const g=await(await fetch("/api/v1/license/status")).json();g.success&&(j(g.license),U(g.license))}catch(h){console.warn("Failed to load license status:",h.message)}}async function N(){const h=I.value.trim();if(!h){S("Please enter a license code.");return}T(),A.disabled=!0,A.textContent="Activating...";try{const H=await(await secureFetch("/api/v1/license/activate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:h})})).json();H.success?(L(H.message),I.value="",j(H.license),showNotification("License activated! Premium features unlocked.","success",5e3),U(H.license)):S(H.error||"Activation failed")}catch(g){S("Network error: "+g.message)}finally{A.disabled=!1,A.textContent="Activate"}}async function R(){if(confirm("Deactivate your license? You can reuse the code on another machine.")){E.disabled=!0,E.textContent="Deactivating...";try{const g=await(await secureFetch("/api/v1/license/deactivate",{method:"POST"})).json();g.success?(L(g.message),await C(),showNotification("License deactivated.","info",3e3),U({active:!1})):S(g.error||"Deactivation failed")}catch(h){S("Network error: "+h.message)}finally{E.disabled=!1,E.textContent="Deactivate"}}}function U(h){const g=document.getElementById("license-status-topbar"),H=document.getElementById("license-topbar-icon"),r=document.getElementById("license-topbar-text"),c=document.getElementById("license-topbar-time");if(g)if(g.className="license-status-topbar "+(h.active?"premium":"free"),h.active)if(H.textContent="\u2605",r.textContent="PREMIUM",h.lifetime)c.textContent="\xB7 LIFETIME";else{const d=h.daysRemaining;c.textContent=d!=null?"\xB7 "+d+"d remaining":""}else H.textContent="\u2606",r.textContent=h.expired?"EXPIRED":"FREE TIER",c.textContent=""}function u(){T(),C(),f.classList.add("show")}I.addEventListener("input",function(){let h=this.value.toUpperCase().replace(/[^A-Z0-9-]/g,"");if(h.length>this._prevLength&&(h=h.replace(/-/g,""),h.length>2&&!h.startsWith("DC")&&(h="DC"+h),h.startsWith("DC")&&h.length>2)){const g=["DC"],H=h.substring(2);for(let r=0;r<H.length;r+=5)g.push(H.substring(r,r+5));h=g.join("-")}this._prevLength=h.length,this.value=h}),A.addEventListener("click",N),E.addEventListener("click",R),I.addEventListener("keydown",h=>{h.key==="Enter"&&N()}),wireModal(f,document.getElementById("license-cancel"));const m=document.getElementById("license-status-topbar");m&&m.addEventListener("click",()=>window.openLicenseModal&&window.openLicenseModal()),window.openLicenseModal=u,window.checkPremiumFeature=async function(h){try{return(await(await fetch(`/api/v1/license/feature/${h}`)).json()).available}catch{return!1}},C().then(h=>{k&&U(k)})})(),(function(){"use strict";if(window.__dc_058_share_modal_loaded)return;window.__dc_058_share_modal_loaded=!0;const f=[{ms:3600*1e3,label:"1 hour"},{ms:1440*60*1e3,label:"24 hours"},{ms:10080*60*1e3,label:"7 days"}];injectModal("share-modal",`
</div>`).join("")}async function H(){try{const y=await(await fetch("/api/v1/license/status")).json();y.success&&(j(y.license),O(y.license))}catch(b){console.warn("Failed to load license status:",b.message)}}async function R(){const b=B.value.trim();if(!b){E("Please enter a license code.");return}T(),A.disabled=!0,A.textContent="Activating...";try{const h=await(await secureFetch("/api/v1/license/activate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:b})})).json();h.success?(I(h.message),B.value="",j(h.license),showNotification("License activated! Premium features unlocked.","success",5e3),O(h.license)):E(h.error||"Activation failed")}catch(y){E("Network error: "+y.message)}finally{A.disabled=!1,A.textContent="Activate"}}async function D(){if(confirm("Deactivate your license? You can reuse the code on another machine.")){C.disabled=!0,C.textContent="Deactivating...";try{const y=await(await secureFetch("/api/v1/license/deactivate",{method:"POST"})).json();y.success?(I(y.message),await H(),showNotification("License deactivated.","info",3e3),O({active:!1})):E(y.error||"Deactivation failed")}catch(b){E("Network error: "+b.message)}finally{C.disabled=!1,C.textContent="Deactivate"}}}function O(b){const y=document.getElementById("license-status-topbar"),h=document.getElementById("license-topbar-icon"),s=document.getElementById("license-topbar-text"),c=document.getElementById("license-topbar-time");if(y)if(y.className="license-status-topbar "+(b.active?"premium":"free"),b.active)if(h.textContent="\u2605",s.textContent="PREMIUM",b.lifetime)c.textContent="\xB7 LIFETIME";else{const l=b.daysRemaining;c.textContent=l!=null?"\xB7 "+l+"d remaining":""}else h.textContent="\u2606",s.textContent=b.expired?"EXPIRED":"FREE TIER",c.textContent=""}function p(){T(),H(),x.classList.add("show")}B.addEventListener("input",function(){let b=this.value.toUpperCase().replace(/[^A-Z0-9-]/g,"");if(b.length>this._prevLength&&(b=b.replace(/-/g,""),b.length>2&&!b.startsWith("DC")&&(b="DC"+b),b.startsWith("DC")&&b.length>2)){const y=["DC"],h=b.substring(2);for(let s=0;s<h.length;s+=5)y.push(h.substring(s,s+5));b=y.join("-")}this._prevLength=b.length,this.value=b}),A.addEventListener("click",R),C.addEventListener("click",D),B.addEventListener("keydown",b=>{b.key==="Enter"&&R()}),wireModal(x,document.getElementById("license-cancel"));const v=document.getElementById("license-status-topbar");v&&v.addEventListener("click",()=>window.openLicenseModal&&window.openLicenseModal()),window.openLicenseModal=p,window.checkPremiumFeature=async function(b){try{return(await(await fetch(`/api/v1/license/feature/${b}`)).json()).available}catch{return!1}},H().then(b=>{k&&O(k)})})(),(function(){"use strict";if(window.__dc_058_share_modal_loaded)return;window.__dc_058_share_modal_loaded=!0;const x=[{ms:3600*1e3,label:"1 hour"},{ms:1440*60*1e3,label:"24 hours"},{ms:10080*60*1e3,label:"7 days"}];injectModal("share-modal",`
<div id="share-modal" class="weather-modal" role="dialog" aria-labelledby="share-modal-title">
<div class="weather-modal-content" style="min-width: 460px; max-width: 580px;">
<h3 id="share-modal-title">Share <span id="share-modal-service-name">\u2026</span></h3>
@@ -1922,7 +1971,7 @@ To endpoint: POST /api/v1/security/events/ingest or /events/batch`),m()}catch(b)
<div class="share-tab-panel" data-panel="public">
<label class="form-label-bold" for="share-public-ttl">Link duration:</label>
<select id="share-public-ttl" style="width: 100%; padding: 8px 10px; margin: 6px 0 12px; background: var(--input-bg); color: var(--fg); border: 1px solid var(--border); border-radius: 4px;">
${f.map(t=>`<option value="${t.ms}">${t.label}</option>`).join("")}
${x.map(t=>`<option value="${t.ms}">${t.label}</option>`).join("")}
</select>
<button id="share-public-create" class="btn-accent" type="button"
style="width: 100%; padding: 10px; background: var(--accent); color: #04141f; border: 0; border-radius: 4px; font-weight: 600; cursor: pointer;">
@@ -1969,17 +2018,17 @@ To endpoint: POST /api/v1/security/events/ingest or /events/batch`),m()}catch(b)
</div>
</div>
</div>
`);const I=document.getElementById("share-modal"),A=document.getElementById("share-modal-service-name"),E=document.getElementById("share-issued"),M=document.getElementById("share-issued-url"),P=document.getElementById("share-issued-copy"),z=document.getElementById("share-issued-meta"),D=document.getElementById("share-error"),v=document.getElementById("share-success"),B=document.getElementById("share-outstanding-list"),x=document.getElementById("share-cancel"),$=document.getElementById("share-public-create"),k=document.getElementById("share-ts-create"),T=document.getElementById("share-ts-email"),S=document.getElementById("share-public-ttl");let L=null,j="public";function C(){D.style.display="none",v.style.display="none",E.style.display="none"}function N(t){v.style.display="none",E.style.display="none",D.textContent=t,D.style.display="block"}function R(t){D.style.display="none",v.textContent=t,v.style.display="block"}function U(){return window.location.origin}function u(t){return t.startsWith("http")?t:U()+t}function m(t){if(!t)return"";const e=new Date(t);return Number.isNaN(e.getTime())?"":e.toLocaleString()}function h(t){if(t<=0)return"expired";const e=Math.floor(t/36e5);if(e>=24)return`${Math.floor(e/24)}d ${e%24}h left`;const a=Math.floor(t%36e5/6e4);return`${e}h ${a}m left`}function g(t){j=t,C(),I.querySelectorAll(".share-tab").forEach(e=>{const a=e.dataset.tab===t;e.classList.toggle("active",a),e.style.borderBottomColor=a?"var(--accent)":"transparent",e.style.color=a?"var(--fg)":"var(--muted)",e.style.fontWeight=a?"600":"400"}),I.querySelectorAll(".share-tab-panel").forEach(e=>{e.style.display=e.dataset.panel===t?"":"none"})}async function H(){B.innerHTML='<span style="color: var(--muted);">Loading\u2026</span>';try{const t=await fetch("/api/v1/share",{credentials:"same-origin"});if(!t.ok){B.innerHTML='<span style="color: var(--muted);">No shares listed.</span>';return}const e=await t.json(),o=(e&&e.data||[]).filter(i=>i.serviceId===L.id);if(o.length===0){B.innerHTML='<span style="color: var(--muted);">No outstanding shares for this service.</span>';return}B.innerHTML=o.map(i=>{const n=i.expiresAt?h(new Date(i.expiresAt).getTime()-Date.now()):"";return`
<div class="share-row" data-share-id="${escapeHtml(i.id)}"
`);const B=document.getElementById("share-modal"),A=document.getElementById("share-modal-service-name"),C=document.getElementById("share-issued"),M=document.getElementById("share-issued-url"),P=document.getElementById("share-issued-copy"),z=document.getElementById("share-issued-meta"),N=document.getElementById("share-error"),f=document.getElementById("share-success"),L=document.getElementById("share-outstanding-list"),w=document.getElementById("share-cancel"),$=document.getElementById("share-public-create"),k=document.getElementById("share-ts-create"),T=document.getElementById("share-ts-email"),E=document.getElementById("share-public-ttl");let I=null,j="public";function H(){N.style.display="none",f.style.display="none",C.style.display="none"}function R(t){f.style.display="none",C.style.display="none",N.textContent=t,N.style.display="block"}function D(t){N.style.display="none",f.textContent=t,f.style.display="block"}function O(){return window.location.origin}function p(t){return t.startsWith("http")?t:O()+t}function v(t){if(!t)return"";const e=new Date(t);return Number.isNaN(e.getTime())?"":e.toLocaleString()}function b(t){if(t<=0)return"expired";const e=Math.floor(t/36e5);if(e>=24)return`${Math.floor(e/24)}d ${e%24}h left`;const a=Math.floor(t%36e5/6e4);return`${e}h ${a}m left`}function y(t){j=t,H(),B.querySelectorAll(".share-tab").forEach(e=>{const a=e.dataset.tab===t;e.classList.toggle("active",a),e.style.borderBottomColor=a?"var(--accent)":"transparent",e.style.color=a?"var(--fg)":"var(--muted)",e.style.fontWeight=a?"600":"400"}),B.querySelectorAll(".share-tab-panel").forEach(e=>{e.style.display=e.dataset.panel===t?"":"none"})}async function h(){L.innerHTML='<span style="color: var(--muted);">Loading\u2026</span>';try{const t=await fetch("/api/v1/share",{credentials:"same-origin"});if(!t.ok){L.innerHTML='<span style="color: var(--muted);">No shares listed.</span>';return}const e=await t.json(),o=(e&&e.data||[]).filter(r=>r.serviceId===I.id);if(o.length===0){L.innerHTML='<span style="color: var(--muted);">No outstanding shares for this service.</span>';return}L.innerHTML=o.map(r=>{const n=r.expiresAt?b(new Date(r.expiresAt).getTime()-Date.now()):"";return`
<div class="share-row" data-share-id="${escapeHtml(r.id)}"
style="display: flex; align-items: center; gap: 8px; padding: 6px 0; border-bottom: 1px dashed var(--border);">
<span style="flex: 1;">
<strong>${i.kind==="tailscale"?"Tailscale":"Public"}</strong>
<span style="color: var(--muted);"> \xB7 expires ${escapeHtml(m(i.expiresAt))} (${n})</span>
<strong>${r.kind==="tailscale"?"Tailscale":"Public"}</strong>
<span style="color: var(--muted);"> \xB7 expires ${escapeHtml(v(r.expiresAt))} (${n})</span>
</span>
<button class="share-revoke" data-share-id="${escapeHtml(i.id)}" type="button"
<button class="share-revoke" data-share-id="${escapeHtml(r.id)}" type="button"
style="padding: 4px 10px; background: transparent; color: var(--bad-fg); border: 1px solid var(--bad-fg); border-radius: 4px; cursor: pointer; font-size: 0.8rem;">
Revoke
</button>
</div>
`}).join(""),B.querySelectorAll(".share-revoke").forEach(i=>{i.addEventListener("click",()=>r(i.dataset.shareId))})}catch{B.innerHTML='<span style="color: var(--muted);">Could not load outstanding shares.</span>'}}async function r(t){try{const e=await fetch(`/api/v1/share/${encodeURIComponent(t)}`,{method:"DELETE",credentials:"same-origin"});if(!e.ok){const a=await e.json().catch(()=>({}));N(a&&a.error||`Revoke failed (HTTP ${e.status}).`);return}R("Share revoked."),H()}catch{N("Network error while revoking.")}}async function c(){if(!L)return;C(),$.disabled=!0;const t=$.textContent;$.textContent="Creating\u2026";try{const e=parseInt(S.value,10),a=await fetch("/api/v1/share",{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json"},body:JSON.stringify({serviceId:L.id,ttlMs:e})}),o=await a.json().catch(()=>({}));if(!a.ok||!o.success){b(a.status,o);return}const i=o.data.urlPath;M.value=u(i),z.textContent=`Public link \xB7 expires ${m(o.data.expiresAt)}`,E.style.display="block",R("Share link created."),H()}catch{N("Network error while creating share.")}finally{$.disabled=!1,$.textContent=t}}async function d(){if(!L)return;const t=(T.value||"").trim();if(!t||!t.includes("@")){N("A valid recipient email is required.");return}C(),k.disabled=!0;const e=k.textContent;k.textContent="Creating\u2026";try{const a=await fetch("/api/v1/share/tailscale",{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json"},body:JSON.stringify({serviceId:L.id,email:t})}),o=await a.json().catch(()=>({}));if(!a.ok||!o.success){b(a.status,o);return}const i=o.data&&o.data.urlPath;i?(M.value=u(i),z.textContent=`Tailscale invite \xB7 emailed to ${t} (or use this URL manually if delivery failed).`):(M.value="",z.textContent=`Tailscale invite sent to ${t}.`),E.style.display="block",R("Tailscale invite created."),T.value="",H()}catch{N("Network error while creating Tailscale invite.")}finally{k.disabled=!1,k.textContent=e}}function b(t,e){const a=e&&e.error||"";if(t===402){N("Share is a Pro feature. Activate a license to unlock.");return}if(t===400&&/tailscale/i.test(a)){N("Tailscale is not configured on this host. Set up Tailscale in the dashboard first.");return}if(t===403){N("You do not have permission to share services.");return}if(t===404){N("Service not found. It may have been deleted.");return}N(a||`Request failed (HTTP ${t}).`)}function y(t){!t||!t.id||(L={id:t.id,name:t.name||t.id},A.textContent=L.name,C(),g("public"),T.value="",S.value=String(f[1].ms),I.classList.add("show"),H())}I.querySelectorAll(".share-tab").forEach(t=>{t.addEventListener("click",()=>g(t.dataset.tab))}),$.addEventListener("click",c),k.addEventListener("click",d),x.addEventListener("click",()=>I.classList.remove("show")),wireModal(I,x),P.addEventListener("click",async()=>{const t=M.value;if(t)try{navigator.clipboard&&navigator.clipboard.writeText?await navigator.clipboard.writeText(t):(M.select(),document.execCommand("copy"));const e=P.textContent;P.textContent="Copied!",setTimeout(()=>{P.textContent=e},1200)}catch{N("Could not copy to clipboard. Select the URL manually.")}}),window.openShareModal=y})();
//# sourceMappingURL=data:application/json;base64,ewogICJ2ZXJzaW9uIjogMywKICAic291cmNlcyI6IFsiPHN0ZGluPiJdLAogICJzb3VyY2VzQ29udGVudCI6IFsiLy8gTG9nbyBDdXN0b21pemF0aW9uIFN5c3RlbVxuKGZ1bmN0aW9uKCkge1xuICAvLyBJbmplY3QgbW9kYWwgSFRNTFxuICBpbmplY3RNb2RhbCgnbG9nby1tb2RhbCcsIGA8ZGl2IGlkPVwibG9nby1tb2RhbFwiIGNsYXNzPVwid2VhdGhlci1tb2RhbFwiPlxuICAgIDxkaXYgY2xhc3M9XCJ3ZWF0aGVyLW1vZGFsLWNvbnRlbnRcIiBzdHlsZT1cIm1pbi13aWR0aDogNDAwcHg7IG1heC13aWR0aDogNTIwcHg7XCI+XG4gICAgICA8aDM+RGFzaGJvYXJkIFNldHRpbmdzPC9oMz5cbiAgICAgIDxwIHN0eWxlPVwiZm9udC1zaXplOiAwLjg1cmVtOyBjb2xvcjogdmFyKC0tbXV0ZWQpOyBtYXJnaW46IDAgMCAxNnB4O1wiPlxuICAgICAgICBDdXN0b21pemUgeW91ciBkYXNoYm9hcmQncyBhcHBlYXJhbmNlIGFuZCBzeXN0ZW0gcHJlZmVyZW5jZXMuXG4gICAgICA8L3A+XG5cbiAgICAgIDxkaXYgY2xhc3M9XCJtYi0xNlwiPlxuICAgICAgICA8bGFiZWwgZm9yPVwiZGFzaGJvYXJkLXRpdGxlXCIgY2xhc3M9XCJmb3JtLWxhYmVsLWJvbGRcIj5EYXNoYm9hcmQgVGl0bGU6PC9sYWJlbD5cbiAgICAgICAgPGlucHV0IHR5cGU9XCJ0ZXh0XCIgaWQ9XCJkYXNoYm9hcmQtdGl0bGVcIiBwbGFjZWhvbGRlcj1cIkRhc2hDYWRkeVwiIG1heGxlbmd0aD1cIjUwXCIgc3R5bGU9XCJ3aWR0aDogMTAwJTsgcGFkZGluZzogMTBweCAxMnB4OyBib3JkZXI6IDFweCBzb2xpZCB2YXIoLS1ib3JkZXIpOyBib3JkZXItcmFkaXVzOiA0cHg7IGJhY2tncm91bmQ6IHZhcigtLWNhcmQtYmcpOyBjb2xvcjogdmFyKC0tZmcpOyBmb250LXNpemU6IDFyZW07XCIgLz5cbiAgICAgICAgPHAgY2xhc3M9XCJ0aW55LWhpbnRcIj5TaG93biBpbiBicm93c2VyIHRhYiBhbmQgaGVhZGVyIChtYXggNTAgY2hhcmFjdGVycyk8L3A+XG4gICAgICA8L2Rpdj5cblxuICAgICAgPGhyIGNsYXNzPVwiaHItZGl2aWRlclwiIC8+XG5cbiAgICAgIDxkaXYgY2xhc3M9XCJtYi0xNlwiPlxuICAgICAgICA8bGFiZWwgY2xhc3M9XCJmb3JtLWxhYmVsLWJvbGRcIj5Mb2dvOjwvbGFiZWw+XG4gICAgICAgIDxwIGNsYXNzPVwidGlueS1oaW50XCIgc3R5bGU9XCJtYXJnaW4tdG9wOiAycHg7XCI+U2VwYXJhdGUgbG9nb3MgZm9yIGRhcmsgYW5kIGxpZ2h0IHRoZW1lcywgb3IgdXNlIHRoZSBzYW1lIGZvciBib3RoLjwvcD5cbiAgICAgIDwvZGl2PlxuXG4gICAgICA8ZGl2IHN0eWxlPVwiZGlzcGxheTogZmxleDsgZ2FwOiAxMnB4OyBtYXJnaW4tYm90dG9tOiAxMnB4O1wiPlxuICAgICAgICA8ZGl2IHN0eWxlPVwiZmxleDogMTsgdGV4dC1hbGlnbjogY2VudGVyOyBwYWRkaW5nOiAxNnB4IDEwcHg7IGJvcmRlci1yYWRpdXM6IDhweDsgYmFja2dyb3VuZDogIzFhMWEyZTsgYm9yZGVyOiAxcHggc29saWQgcmdiYSgyNTUsMjU1LDI1NSwuMSk7XCI+XG4gICAgICAgICAgPGltZyBpZD1cImxvZ28tcHJldmlldy1kYXJrXCIgc3JjPVwiL2Fzc2V0cy9kYXNoY2FkZHktbG9nby1kYXJrLnBuZ1wiIGFsdD1cIkRhcmsgdGhlbWUgbG9nb1wiIHN0eWxlPVwibWF4LWhlaWdodDogNjBweDsgbWF4LXdpZHRoOiAxMDAlO1wiIC8+XG4gICAgICAgICAgPHAgc3R5bGU9XCJmb250LXNpemU6IDAuNjVyZW07IGNvbG9yOiAjOWFhNmJmOyBtYXJnaW4tdG9wOiA2cHg7XCI+RGFyayB0aGVtZXM8L3A+XG4gICAgICAgIDwvZGl2PlxuICAgICAgICA8ZGl2IHN0eWxlPVwiZmxleDogMTsgdGV4dC1hbGlnbjogY2VudGVyOyBwYWRkaW5nOiAxNnB4IDEwcHg7IGJvcmRlci1yYWRpdXM6IDhweDsgYmFja2dyb3VuZDogI2YwZjBmMDsgYm9yZGVyOiAxcHggc29saWQgcmdiYSgwLDAsMCwuMSk7XCI+XG4gICAgICAgICAgPGltZyBpZD1cImxvZ28tcHJldmlldy1saWdodFwiIHNyYz1cIi9hc3NldHMvZGFzaGNhZGR5LWxvZ28tbGlnaHQucG5nXCIgYWx0PVwiTGlnaHQgdGhlbWUgbG9nb1wiIHN0eWxlPVwibWF4LWhlaWdodDogNjBweDsgbWF4LXdpZHRoOiAxMDAlO1wiIC8+XG4gICAgICAgICAgPHAgc3R5bGU9XCJmb250LXNpemU6IDAuNjVyZW07IGNvbG9yOiAjNWY2YjdhOyBtYXJnaW4tdG9wOiA2cHg7XCI+TGlnaHQgdGhlbWVzPC9wPlxuICAgICAgICA8L2Rpdj5cbiAgICAgIDwvZGl2PlxuICAgICAgPHAgaWQ9XCJsb2dvLXN0YXR1c1wiIHN0eWxlPVwiZm9udC1zaXplOiAwLjc1cmVtOyBjb2xvcjogdmFyKC0tbXV0ZWQpOyBtYXJnaW4tYm90dG9tOiAxMnB4OyB0ZXh0LWFsaWduOiBjZW50ZXI7XCI+VXNpbmcgZGVmYXVsdCBsb2dvczwvcD5cblxuICAgICAgPGRpdiBjbGFzcz1cIm1iLTE2XCI+XG4gICAgICAgIDxsYWJlbCBzdHlsZT1cImRpc3BsYXk6IGZsZXg7IGFsaWduLWl0ZW1zOiBjZW50ZXI7IGdhcDogOHB4OyBmb250LXNpemU6IDAuODJyZW07IGN1cnNvcjogcG9pbnRlcjsgdXNlci1zZWxlY3Q6IG5vbmU7XCI+XG4gICAgICAgICAgPGlucHV0IHR5cGU9XCJjaGVja2JveFwiIGlkPVwibG9nby1zYW1lLWJvdGhcIiAvPiBVc2Ugc2FtZSBsb2dvIGZvciBib3RoXG4gICAgICAgIDwvbGFiZWw+XG4gICAgICA8L2Rpdj5cblxuICAgICAgPGRpdiBpZD1cImxvZ28tZHVhbC11cGxvYWRzXCIgY2xhc3M9XCJtYi0xNlwiIHN0eWxlPVwiZGlzcGxheTogZmxleDsgZ2FwOiAxMnB4O1wiPlxuICAgICAgICA8ZGl2IHN0eWxlPVwiZmxleDogMTtcIj5cbiAgICAgICAgICA8bGFiZWwgZm9yPVwibG9nby11cGxvYWQtZGFya1wiIHN0eWxlPVwiZGlzcGxheTogYmxvY2s7IG1hcmdpbi1ib3R0b206IDZweDsgZm9udC1zaXplOiAwLjhyZW07XCI+RGFyayB0aGVtZSBsb2dvOjwvbGFiZWw+XG4gICAgICAgICAgPGlucHV0IHR5cGU9XCJmaWxlXCIgaWQ9XCJsb2dvLXVwbG9hZC1kYXJrXCIgYWNjZXB0PVwiaW1hZ2UvKlwiIGNsYXNzPVwiaW5wdXQtY2FyZC1hbHRcIiBzdHlsZT1cImZvbnQtc2l6ZTogMC43NXJlbTtcIiAvPlxuICAgICAgICA8L2Rpdj5cbiAgICAgICAgPGRpdiBzdHlsZT1cImZsZXg6IDE7XCI+XG4gICAgICAgICAgPGxhYmVsIGZvcj1cImxvZ28tdXBsb2FkLWxpZ2h0XCIgc3R5bGU9XCJkaXNwbGF5OiBibG9jazsgbWFyZ2luLWJvdHRvbTogNnB4OyBmb250LXNpemU6IDAuOHJlbTtcIj5MaWdodCB0aGVtZSBsb2dvOjwvbGFiZWw+XG4gICAgICAgICAgPGlucHV0IHR5cGU9XCJmaWxlXCIgaWQ9XCJsb2dvLXVwbG9hZC1saWdodFwiIGFjY2VwdD1cImltYWdlLypcIiBjbGFzcz1cImlucHV0LWNhcmQtYWx0XCIgc3R5bGU9XCJmb250LXNpemU6IDAuNzVyZW07XCIgLz5cbiAgICAgICAgPC9kaXY+XG4gICAgICA8L2Rpdj5cblxuICAgICAgPGRpdiBpZD1cImxvZ28tc2luZ2xlLXVwbG9hZFwiIGNsYXNzPVwibWItMTZcIiBzdHlsZT1cImRpc3BsYXk6IG5vbmU7XCI+XG4gICAgICAgIDxsYWJlbCBmb3I9XCJsb2dvLXVwbG9hZC1zaW5nbGVcIiBzdHlsZT1cImRpc3BsYXk6IGJsb2NrOyBtYXJnaW4tYm90dG9tOiA2cHg7IGZvbnQtc2l6ZTogMC44cmVtO1wiPlVwbG9hZCBsb2dvOjwvbGFiZWw+XG4gICAgICAgIDxpbnB1dCB0eXBlPVwiZmlsZVwiIGlkPVwibG9nby11cGxvYWQtc2luZ2xlXCIgYWNjZXB0PVwiaW1hZ2UvKlwiIGNsYXNzPVwiaW5wdXQtY2FyZC1hbHRcIiAvPlxuICAgICAgICA8cCBjbGFzcz1cInRpbnktaGludFwiPlRoaXMgbG9nbyB3aWxsIGJlIHVzZWQgb24gYWxsIHRoZW1lc Line truncated
`}).join(""),L.querySelectorAll(".share-revoke").forEach(r=>{r.addEventListener("click",()=>s(r.dataset.shareId))})}catch{L.innerHTML='<span style="color: var(--muted);">Could not load outstanding shares.</span>'}}async function s(t){try{const e=await fetch(`/api/v1/share/${encodeURIComponent(t)}`,{method:"DELETE",credentials:"same-origin"});if(!e.ok){const a=await e.json().catch(()=>({}));R(a&&a.error||`Revoke failed (HTTP ${e.status}).`);return}D("Share revoked."),h()}catch{R("Network error while revoking.")}}async function c(){if(!I)return;H(),$.disabled=!0;const t=$.textContent;$.textContent="Creating\u2026";try{const e=parseInt(E.value,10),a=await fetch("/api/v1/share",{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json"},body:JSON.stringify({serviceId:I.id,ttlMs:e})}),o=await a.json().catch(()=>({}));if(!a.ok||!o.success){m(a.status,o);return}const r=o.data.urlPath;M.value=p(r),z.textContent=`Public link \xB7 expires ${v(o.data.expiresAt)}`,C.style.display="block",D("Share link created."),h()}catch{R("Network error while creating share.")}finally{$.disabled=!1,$.textContent=t}}async function l(){if(!I)return;const t=(T.value||"").trim();if(!t||!t.includes("@")){R("A valid recipient email is required.");return}H(),k.disabled=!0;const e=k.textContent;k.textContent="Creating\u2026";try{const a=await fetch("/api/v1/share/tailscale",{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json"},body:JSON.stringify({serviceId:I.id,email:t})}),o=await a.json().catch(()=>({}));if(!a.ok||!o.success){m(a.status,o);return}const r=o.data&&o.data.urlPath;r?(M.value=p(r),z.textContent=`Tailscale invite \xB7 emailed to ${t} (or use this URL manually if delivery failed).`):(M.value="",z.textContent=`Tailscale invite sent to ${t}.`),C.style.display="block",D("Tailscale invite created."),T.value="",h()}catch{R("Network error while creating Tailscale invite.")}finally{k.disabled=!1,k.textContent=e}}function m(t,e){const a=e&&e.error||"";if(t===402){R("Share is a Pro feature. Activate a license to unlock.");return}if(t===400&&/tailscale/i.test(a)){R("Tailscale is not configured on this host. Set up Tailscale in the dashboard first.");return}if(t===403){R("You do not have permission to share services.");return}if(t===404){R("Service not found. It may have been deleted.");return}R(a||`Request failed (HTTP ${t}).`)}function u(t){!t||!t.id||(I={id:t.id,name:t.name||t.id},A.textContent=I.name,H(),y("public"),T.value="",E.value=String(x[1].ms),B.classList.add("show"),h())}B.querySelectorAll(".share-tab").forEach(t=>{t.addEventListener("click",()=>y(t.dataset.tab))}),$.addEventListener("click",c),k.addEventListener("click",l),w.addEventListener("click",()=>B.classList.remove("show")),wireModal(B,w),P.addEventListener("click",async()=>{const t=M.value;if(t)try{navigator.clipboard&&navigator.clipboard.writeText?await navigator.clipboard.writeText(t):(M.select(),document.execCommand("copy"));const e=P.textContent;P.textContent="Copied!",setTimeout(()=>{P.textContent=e},1200)}catch{R("Could not copy to clipboard. Select the URL manually.")}}),window.openShareModal=u})();
//# sourceMappingURL=data:application/json;base64,ewogICJ2ZXJzaW9uIjogMywKICAic291cmNlcyI6IFsiPHN0ZGluPiJdLAogICJzb3VyY2VzQ29udGVudCI6IFsiLy8gTG9nbyBDdXN0b21pemF0aW9uIFN5c3RlbVxuKGZ1bmN0aW9uKCkge1xuICAvLyBJbmplY3QgbW9kYWwgSFRNTFxuICBpbmplY3RNb2RhbCgnbG9nby1tb2RhbCcsIGA8ZGl2IGlkPVwibG9nby1tb2RhbFwiIGNsYXNzPVwid2VhdGhlci1tb2RhbFwiPlxuICAgIDxkaXYgY2xhc3M9XCJ3ZWF0aGVyLW1vZGFsLWNvbnRlbnRcIiBzdHlsZT1cIm1pbi13aWR0aDogNDAwcHg7IG1heC13aWR0aDogNTIwcHg7XCI+XG4gICAgICA8aDM+RGFzaGJvYXJkIFNldHRpbmdzPC9oMz5cbiAgICAgIDxwIHN0eWxlPVwiZm9udC1zaXplOiAwLjg1cmVtOyBjb2xvcjogdmFyKC0tbXV0ZWQpOyBtYXJnaW46IDAgMCAxNnB4O1wiPlxuICAgICAgICBDdXN0b21pemUgeW91ciBkYXNoYm9hcmQncyBhcHBlYXJhbmNlIGFuZCBzeXN0ZW0gcHJlZmVyZW5jZXMuXG4gICAgICA8L3A+XG5cbiAgICAgIDxkaXYgY2xhc3M9XCJtYi0xNlwiPlxuICAgICAgICA8bGFiZWwgZm9yPVwiZGFzaGJvYXJkLXRpdGxlXCIgY2xhc3M9XCJmb3JtLWxhYmVsLWJvbGRcIj5EYXNoYm9hcmQgVGl0bGU6PC9sYWJlbD5cbiAgICAgICAgPGlucHV0IHR5cGU9XCJ0ZXh0XCIgaWQ9XCJkYXNoYm9hcmQtdGl0bGVcIiBwbGFjZWhvbGRlcj1cIkRhc2hDYWRkeVwiIG1heGxlbmd0aD1cIjUwXCIgc3R5bGU9XCJ3aWR0aDogMTAwJTsgcGFkZGluZzogMTBweCAxMnB4OyBib3JkZXI6IDFweCBzb2xpZCB2YXIoLS1ib3JkZXIpOyBib3JkZXItcmFkaXVzOiA0cHg7IGJhY2tncm91bmQ6IHZhcigtLWNhcmQtYmcpOyBjb2xvcjogdmFyKC0tZmcpOyBmb250LXNpemU6IDFyZW07XCIgLz5cbiAgICAgICAgPHAgY2xhc3M9XCJ0aW55LWhpbnRcIj5TaG93biBpbiBicm93c2VyIHRhYiBhbmQgaGVhZGVyIChtYXggNTAgY2hhcmFjdGVycyk8L3A+XG4gICAgICA8L2Rpdj5cblxuICAgICAgPGhyIGNsYXNzPVwiaHItZGl2aWRlclwiIC8+XG5cbiAgICAgIDxkaXYgY2xhc3M9XCJtYi0xNlwiPlxuICAgICAgICA8bGFiZWwgY2xhc3M9XCJmb3JtLWxhYmVsLWJvbGRcIj5Mb2dvOjwvbGFiZWw+XG4gICAgICAgIDxwIGNsYXNzPVwidGlueS1oaW50XCIgc3R5bGU9XCJtYXJnaW4tdG9wOiAycHg7XCI+U2VwYXJhdGUgbG9nb3MgZm9yIGRhcmsgYW5kIGxpZ2h0IHRoZW1lcywgb3IgdXNlIHRoZSBzYW1lIGZvciBib3RoLjwvcD5cbiAgICAgIDwvZGl2PlxuXG4gICAgICA8ZGl2IHN0eWxlPVwiZGlzcGxheTogZmxleDsgZ2FwOiAxMnB4OyBtYXJnaW4tYm90dG9tOiAxMnB4O1wiPlxuICAgICAgICA8ZGl2IHN0eWxlPVwiZmxleDogMTsgdGV4dC1hbGlnbjogY2VudGVyOyBwYWRkaW5nOiAxNnB4IDEwcHg7IGJvcmRlci1yYWRpdXM6IDhweDsgYmFja2dyb3VuZDogIzFhMWEyZTsgYm9yZGVyOiAxcHggc29saWQgcmdiYSgyNTUsMjU1LDI1NSwuMSk7XCI+XG4gICAgICAgICAgPGltZyBpZD1cImxvZ28tcHJldmlldy1kYXJrXCIgc3JjPVwiL2Fzc2V0cy9kYXNoY2FkZHktbG9nby1kYXJrLnBuZ1wiIGFsdD1cIkRhcmsgdGhlbWUgbG9nb1wiIHN0eWxlPVwibWF4LWhlaWdodDogNjBweDsgbWF4LXdpZHRoOiAxMDAlO1wiIC8+XG4gICAgICAgICAgPHAgc3R5bGU9XCJmb250LXNpemU6IDAuNjVyZW07IGNvbG9yOiAjOWFhNmJmOyBtYXJnaW4tdG9wOiA2cHg7XCI+RGFyayB0aGVtZXM8L3A+XG4gICAgICAgIDwvZGl2PlxuICAgICAgICA8ZGl2IHN0eWxlPVwiZmxleDogMTsgdGV4dC1hbGlnbjogY2VudGVyOyBwYWRkaW5nOiAxNnB4IDEwcHg7IGJvcmRlci1yYWRpdXM6IDhweDsgYmFja2dyb3VuZDogI2YwZjBmMDsgYm9yZGVyOiAxcHggc29saWQgcmdiYSgwLDAsMCwuMSk7XCI+XG4gICAgICAgICAgPGltZyBpZD1cImxvZ28tcHJldmlldy1saWdodFwiIHNyYz1cIi9hc3NldHMvZGFzaGNhZGR5LWxvZ28tbGlnaHQucG5nXCIgYWx0PVwiTGlnaHQgdGhlbWUgbG9nb1wiIHN0eWxlPVwibWF4LWhlaWdodDogNjBweDsgbWF4LXdpZHRoOiAxMDAlO1wiIC8+XG4gICAgICAgICAgPHAgc3R5bGU9XCJmb250LXNpemU6IDAuNjVyZW07IGNvbG9yOiAjNWY2YjdhOyBtYXJnaW4tdG9wOiA2cHg7XCI+TGlnaHQgdGhlbWVzPC9wPlxuICAgICAgICA8L2Rpdj5cbiAgICAgIDwvZGl2PlxuICAgICAgPHAgaWQ9XCJsb2dvLXN0YXR1c1wiIHN0eWxlPVwiZm9udC1zaXplOiAwLjc1cmVtOyBjb2xvcjogdmFyKC0tbXV0ZWQpOyBtYXJnaW4tYm90dG9tOiAxMnB4OyB0ZXh0LWFsaWduOiBjZW50ZXI7XCI+VXNpbmcgZGVmYXVsdCBsb2dvczwvcD5cblxuICAgICAgPGRpdiBjbGFzcz1cIm1iLTE2XCI+XG4gICAgICAgIDxsYWJlbCBzdHlsZT1cImRpc3BsYXk6IGZsZXg7IGFsaWduLWl0ZW1zOiBjZW50ZXI7IGdhcDogOHB4OyBmb250LXNpemU6IDAuODJyZW07IGN1cnNvcjogcG9pbnRlcjsgdXNlci1zZWxlY3Q6IG5vbmU7XCI+XG4gICAgICAgICAgPGlucHV0IHR5cGU9XCJjaGVja2JveFwiIGlkPVwibG9nby1zYW1lLWJvdGhcIiAvPiBVc2Ugc2FtZSBsb2dvIGZvciBib3RoXG4gICAgICAgIDwvbGFiZWw+XG4gICAgICA8L2Rpdj5cblxuICAgICAgPGRpdiBpZD1cImxvZ28tZHVhbC11cGxvYWRzXCIgY2xhc3M9XCJtYi0xNlwiIHN0eWxlPVwiZGlzcGxheTogZmxleDsgZ2FwOiAxMnB4O1wiPlxuICAgICAgICA8ZGl2IHN0eWxlPVwiZmxleDogMTtcIj5cbiAgICAgICAgICA8bGFiZWwgZm9yPVwibG9nby11cGxvYWQtZGFya1wiIHN0eWxlPVwiZGlzcGxheTogYmxvY2s7IG1hcmdpbi1ib3R0b206IDZweDsgZm9udC1zaXplOiAwLjhyZW07XCI+RGFyayB0aGVtZSBsb2dvOjwvbGFiZWw+XG4gICAgICAgICAgPGlucHV0IHR5cGU9XCJmaWxlXCIgaWQ9XCJsb2dvLXVwbG9hZC1kYXJrXCIgYWNjZXB0PVwiaW1hZ2UvKlwiIGNsYXNzPVwiaW5wdXQtY2FyZC1hbHRcIiBzdHlsZT1cImZvbnQtc2l6ZTogMC43NXJlbTtcIiAvPlxuICAgICAgICA8L2Rpdj5cbiAgICAgICAgPGRpdiBzdHlsZT1cImZsZXg6IDE7XCI+XG4gICAgICAgICAgPGxhYmVsIGZvcj1cImxvZ28tdXBsb2FkLWxpZ2h0XCIgc3R5bGU9XCJkaXNwbGF5OiBibG9jazsgbWFyZ2luLWJvdHRvbTogNnB4OyBmb250LXNpemU6IDAuOHJlbTtcIj5MaWdodCB0aGVtZSBsb2dvOjwvbGFiZWw+XG4gICAgICAgICAgPGlucHV0IHR5cGU9XCJmaWxlXCIgaWQ9XCJsb2dvLXVwbG9hZC1saWdodFwiIGFjY2VwdD1cImltYWdlLypcIiBjbGFzcz1cImlucHV0LWNhcmQtYWx0XCIgc3R5bGU9XCJmb250LXNpemU6IDAuNzVyZW07XCIgLz5cbiAgICAgICAgPC9kaXY+XG4gICAgICA8L2Rpdj5cblxuICAgICAgPGRpdiBpZD1cImxvZ28tc2luZ2xlLXVwbG9hZFwiIGNsYXNzPVwibWItMTZcIiBzdHlsZT1cImRpc3BsYXk6IG5vbmU7XCI+XG4gICAgICAgIDxsYWJlbCBmb3I9XCJsb2dvLXVwbG9hZC1zaW5nbGVcIiBzdHlsZT1cImRpc3BsYXk6IGJsb2NrOyBtYXJnaW4tYm90dG9tOiA2cHg7IGZvbnQtc2l6ZTogMC44cmVtO1wiPlVwbG9hZCBsb2dvOjwvbGFiZWw+XG4gICAgICAgIDxpbnB1dCB0eXBlPVwiZmlsZVwiIGlkPVwibG9nby11cGxvYWQtc2luZ2xlXCIgYWNjZXB0PVwiaW1hZ2UvKlwiIGNsYXNzPVwiaW5wdXQtY2FyZC1hbHRcIiAvPlxuICAgICAgICA8cCBjbGFzcz1cInRpbnktaGludFwiPlRoaXMgbG9nbyB3aWxsIGJlIHVzZWQgb24gYWxsIHRoZW1lc Line truncated
+268 -48
View File
@@ -1,72 +1,292 @@
// ========== ERROR LOG VIEWER ==========
// ========== ERROR LOG VIEWER (DC-052) ==========
// DC-052: Adds Level / Context / Search / Time-range filters, server-side
// pagination with Load More, click-to-expand stack frames, and a distinct
// contexts dropdown backed by /api/v1/error-logs/contexts. Mirrors the
// audit-log UX (DC-050) so operators can drill into a subsystem as easily
// as they can audit who-did-what.
(function() {
// Inject modal HTML
injectModal('error-log-modal', '<div id="error-log-modal" class="logs-modal"><div class="logs-modal-content"><div class="logs-header"><h3>📋 Error Logs</h3><div class="logs-controls"><button id="error-log-refresh" style="padding:4px 12px!important;font-size:.85rem!important">🔄 Refresh</button><button id="error-log-clear" style="padding:4px 12px!important;font-size:.85rem!important;background:color-mix(in srgb,var(--bad-fg) 15%,transparent)!important;border-color:var(--bad-fg)!important;color:var(--bad-fg)!important">🗑️ Clear</button><button id="error-log-close" class="close-btn">✕</button></div></div><div class="logs-container"><div id="error-log-content" class="logs-content"><div class="logs-loading">Loading error logs...</div></div></div></div></div>');
// Inject modal HTML. Same weather-modal shell as audit-log so styles
// are shared; wider min-width because error stacks need room to breathe.
injectModal('error-log-modal', `<div id="error-log-modal" class="weather-modal">
<div class="weather-modal-content" style="min-width: 950px; max-width: 1150px;">
<h3>📋 Error Logs</h3>
<p class="modal-subtitle">
Errors and warnings from the DashCaddy API. Click a row to see the full stack trace.
</p>
<div style="display: flex; gap: 12px; margin-bottom: 12px; align-items: center; flex-wrap: wrap;">
<label class="text-muted-sm">Level:</label>
<select id="error-log-level" style="padding: 6px 10px; border-radius: 6px; border: 1px solid var(--border); background: var(--bg); color: var(--fg); font-size: 0.85rem;">
<option value="">All</option>
<option value="ERR">Errors</option>
<option value="WARN">Warnings</option>
<option value="INFO">Info</option>
<option value="DEBUG">Debug</option>
</select>
<label class="text-muted-sm">Context:</label>
<select id="error-log-context" style="padding: 6px 10px; border-radius: 6px; border: 1px solid var(--border); background: var(--bg); color: var(--fg); font-size: 0.85rem; max-width: 220px;">
<option value="">All</option>
</select>
<label class="text-muted-sm" style="margin-left: 8px;">Search:</label>
<input id="error-log-search" type="search" placeholder="message / stack / ip" style="padding: 5px 8px; border-radius: 6px; border: 1px solid var(--border); background: var(--bg); color: var(--fg); font-size: 0.82rem; min-width: 180px;">
<label class="text-muted-sm" style="margin-left: 8px;">Since:</label>
<input id="error-log-since" type="datetime-local" style="padding: 5px 8px; border-radius: 6px; border: 1px solid var(--border); background: var(--bg); color: var(--fg); font-size: 0.82rem;">
<label class="text-muted-sm">Until:</label>
<input id="error-log-until" type="datetime-local" style="padding: 5px 8px; border-radius: 6px; border: 1px solid var(--border); background: var(--bg); color: var(--fg); font-size: 0.82rem;">
<button id="error-log-refresh" class="btn-sm">🔄 Refresh</button>
<span style="flex: 1;"></span>
<button id="error-log-clear" style="padding: 6px 12px; font-size: 0.8rem; color: var(--bad-fg); border-color: var(--bad-fg);">🗑️ Clear Log</button>
</div>
<div id="error-log-container" class="scroll-container">
<div class="panel-empty"><span class="brand-spinner"></span> Loading error logs...</div>
</div>
<div style="margin-top: 12px; text-align: center;">
<button id="error-log-load-more" style="display: none; padding: 6px 16px; font-size: 0.8rem;">Load More</button>
</div>
<div style="margin-top: 8px; font-size: 0.78rem; color: var(--muted); text-align: right;">
<span id="error-log-total"></span>
</div>
<div class="weather-modal-buttons modal-footer-bar">
<button id="error-log-close">Close</button>
</div>
</div>
</div>`);
const modal = document.getElementById('error-log-modal');
const content = document.getElementById('error-log-content');
const viewBtn = document.getElementById('view-error-logs');
const refreshBtn = document.getElementById('error-log-refresh');
const clearBtn = document.getElementById('error-log-clear');
const closeBtn = document.getElementById('error-log-close');
const levelSel = document.getElementById('error-log-level');
const contextSel = document.getElementById('error-log-context');
const searchInput = document.getElementById('error-log-search');
const sinceInput = document.getElementById('error-log-since');
const untilInput = document.getElementById('error-log-until');
const container = document.getElementById('error-log-container');
const loadMoreBtn = document.getElementById('error-log-load-more');
const totalSpan = document.getElementById('error-log-total');
async function loadErrorLogs() {
content.innerHTML = '<div class="logs-loading">Loading error logs...</div>';
const PAGE_SIZE = 50;
let currentOffset = 0;
let inflight = null;
let filterNonce = 0;
// Cached distinct contexts so the dropdown is populated once per open and
// re-populated after a clear (which removes all contexts) or a refresh
// that surfaces a new subsystem for the first time.
let knownContexts = [];
// datetime-local fields are naive local time — convert to UTC ISO so the
// server compares correctly. Same shape as audit-log.js so the operator
// sees consistent behaviour between the two modals.
function toIso(localDtValue) {
if (!localDtValue) return null;
const d = new Date(localDtValue);
if (isNaN(d.getTime())) return null;
return d.toISOString();
}
// Pull the distinct contexts list once per open. Failures are silent
// (the dropdown will just show "All" only) so a transient backend hiccup
// doesn't block the operator from seeing the actual error rows.
async function refreshContexts() {
try {
const response = await fetch('/api/v1/error-logs');
const data = await response.json();
if (data.success && data.logs) {
if (data.logs.length === 0) {
content.innerHTML = '<div style="padding: 20px; text-align: center; color: var(--muted);">✅ No errors logged! Everything is working smoothly.</div>';
} else {
content.innerHTML = data.logs.map(log => {
const date = new Date(log.timestamp).toLocaleString();
return `
<div class="log-entry error">
<span class="log-timestamp">${date}</span>
<span class="log-level">ERROR</span>
<div class="log-message">
<strong>${escapeHtml(log.context)}</strong>: ${escapeHtml(log.error)}
${log.details ? `<br><small style="opacity: 0.7;">${escapeHtml(log.details)}</small>` : ''}
</div>
</div>
`;
}).join('');
const res = await fetch('/api/v1/error-logs/contexts');
if (!res.ok) return;
const data = await res.json();
if (!data.success || !Array.isArray(data.contexts)) return;
knownContexts = data.contexts;
const currentValue = contextSel.value;
contextSel.innerHTML = '<option value="">All</option>';
for (const c of data.contexts) {
const opt = document.createElement('option');
opt.value = c.name;
opt.textContent = `${c.name} (${c.count})`;
contextSel.appendChild(opt);
}
// Restore previous selection if still present.
if (currentValue && data.contexts.some((c) => c.name === currentValue)) {
contextSel.value = currentValue;
}
} catch { /* ignore */ }
}
function buildQuery() {
const params = new URLSearchParams();
params.set('limit', String(PAGE_SIZE));
params.set('offset', String(currentOffset));
if (levelSel.value) params.set('level', levelSel.value);
if (contextSel.value) params.set('context', contextSel.value);
const since = toIso(sinceInput.value);
const until = toIso(untilInput.value);
if (since) params.set('since', since);
if (until) params.set('until', until);
const search = (searchInput.value || '').trim();
if (search) params.set('search', search);
return params;
}
async function loadLogs(append) {
try {
if (!append) {
if (inflight) inflight.abort();
inflight = new AbortController();
currentOffset = 0;
filterNonce++;
container.innerHTML = '<div class="panel-empty"><span class="brand-spinner"></span> Loading...</div>';
} else {
if (inflight) inflight.abort();
inflight = new AbortController();
}
const myNonce = filterNonce;
const params = buildQuery();
const res = await fetch('/api/v1/error-logs?' + params.toString(), {
signal: inflight.signal,
});
// Mirror audit-log: surface 4xx/5xx explicitly instead of falling
// through to a misleading "no entries yet" empty state.
if (!res.ok) {
container.innerHTML = `<div class="panel-empty" style="color: var(--bad-fg);">Failed: HTTP ${res.status}</div>`;
loadMoreBtn.style.display = 'none';
totalSpan.textContent = '';
return;
}
const data = await res.json();
if (!data.success) {
container.innerHTML = `<div class="panel-empty" style="color: var(--bad-fg);">Failed: ${escapeHtml(data.error || 'unknown')}</div>`;
loadMoreBtn.style.display = 'none';
totalSpan.textContent = '';
return;
}
// Stale-response guard: a non-append load happened after this fetch,
// discard so we don't splice into the wrong DOM.
if (!append && myNonce !== filterNonce) return;
const logs = Array.isArray(data.logs) ? data.logs : [];
if (logs.length === 0 && !append) {
const reason = (data.filters && (data.filters.level || data.filters.context || data.filters.search || data.filters.since || data.filters.until))
? 'No error log entries match your filters.'
: '✅ No errors logged! Everything is working smoothly.';
container.innerHTML = `<div class="panel-empty"><span class="empty-icon">📋</span>${escapeHtml(reason)}</div>`;
loadMoreBtn.style.display = 'none';
totalSpan.textContent = data.total ? `${data.total} total` : '';
return;
}
let html = '';
if (!append) {
html = '<table style="width: 100%; border-collapse: collapse; font-size: 0.82rem;">';
html += '<tr style="border-bottom: 1px solid var(--border); color: var(--muted);">';
html += '<th style="padding: 6px; text-align: left; width: 160px;">When</th>';
html += '<th style="padding: 6px; text-align: left; width: 80px;">Level</th>';
html += '<th style="padding: 6px; text-align: left; width: 140px;">Context</th>';
html += '<th style="padding: 6px; text-align: left;">Message</th>';
html += '<th style="padding: 6px; text-align: left; width: 110px;">IP</th>';
html += '</tr>';
}
for (const log of logs) {
const level = (log.level || '?').toUpperCase();
const levelColor = level === 'ERR' ? 'var(--bad-fg)' : (level === 'WARN' ? 'var(--warn-fg, #f0c674)' : 'var(--muted)');
const ts = log.timestamp ? new Date(log.timestamp).toLocaleString() : '—';
const ctx = log.context || '—';
const msg = (log.error || '').split('\n')[0];
const ip = (log.request && log.request.ip) || '';
html += `<tr style="border-bottom: 1px solid var(--border); cursor: pointer;" class="error-log-row">`;
html += `<td style="padding: 6px; color: var(--muted);" title="${escapeHtml(log.timestamp || '')}">${escapeHtml(ts)}</td>`;
html += `<td style="padding: 6px;"><span style="color: ${levelColor}; font-weight: 600;">${escapeHtml(level)}</span></td>`;
html += `<td style="padding: 6px; font-family: monospace; font-size: 0.78rem;">${escapeHtml(ctx)}</td>`;
html += `<td style="padding: 6px;">${escapeHtml(msg)}</td>`;
html += `<td style="padding: 6px; font-family: monospace; font-size: 0.78rem;">${escapeHtml(ip)}</td>`;
html += '</tr>';
if (log.detail) {
html += `<tr class="error-log-detail" style="display: none;"><td colspan="5" style="padding: 6px 6px 10px; font-size: 0.78rem; color: var(--muted);"><pre style="margin: 0; white-space: pre-wrap; font-family: monospace; max-height: 320px; overflow: auto;">${escapeHtml(log.detail)}</pre></td></tr>`;
}
} else {
content.innerHTML = '<div style="padding: 20px; color: var(--bad-fg);">❌ Failed to load error logs</div>';
}
} catch (error) {
content.innerHTML = `<div style="padding: 20px; color: var(--bad-fg);">❌ Error loading logs: ${escapeHtml(error.message)}</div>`;
if (!append) {
html += '</table>';
container.innerHTML = html;
} else {
const table = container.querySelector('table');
if (table) table.insertAdjacentHTML('beforeend', html);
}
currentOffset += logs.length;
loadMoreBtn.style.display = data.hasMore ? '' : 'none';
totalSpan.textContent = `${data.total} total${data.hasMore ? ' (showing ' + currentOffset + ')' : ''}`;
// Toggle detail rows on click — same pattern as audit-log.js
container.querySelectorAll('.error-log-row').forEach((row) => {
if (row.dataset.wired) return;
row.dataset.wired = 'true';
row.addEventListener('click', () => {
const detail = row.nextElementSibling;
if (detail && detail.classList.contains('error-log-detail')) {
detail.style.display = detail.style.display === 'none' ? '' : 'none';
}
});
});
} catch (e) {
if (e && e.name === 'AbortError') return;
container.innerHTML = `<div class="panel-empty" style="color: var(--bad-fg);">Failed: ${escapeHtml(e.message)}</div>`;
totalSpan.textContent = '';
}
}
async function clearErrorLogs() {
if (!confirm('Clear all error logs?')) return;
async function clearLogs() {
if (!confirm('Clear the entire error log? This cannot be undone.')) return;
try {
const response = await secureFetch('/api/v1/error-logs', { method: 'DELETE' });
const data = await response.json();
const res = await secureFetch('/api/v1/error-logs', {
method: 'DELETE',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ confirm: 'CLEAR' }),
});
const data = await res.json();
if (data.success) {
// After a clear, the contexts list will be empty — re-fetch so the
// dropdown reflects reality. Load the now-empty page in parallel.
await refreshContexts();
loadLogs(false);
showNotification('✅ Error logs cleared', 'success', 3000);
loadErrorLogs();
} else {
showNotification('❌ Failed to clear logs', 'error', 3000);
showNotification('❌ ' + (data.error || 'Clear failed'), 'error', 4000);
}
} catch (error) {
showNotification(`❌ Error: ${error.message}`, 'error', 3000);
} catch (e) {
showNotification('❌ ' + e.message, 'error', 4000);
}
}
viewBtn?.addEventListener('click', () => {
modal.classList.add('show');
loadErrorLogs();
});
// Debounce text-input changes so we don't refetch on every keystroke.
let searchDebounce;
function wireFilters() {
levelSel?.addEventListener('change', () => loadLogs(false));
contextSel?.addEventListener('change', () => loadLogs(false));
searchInput?.addEventListener('input', () => {
clearTimeout(searchDebounce);
searchDebounce = setTimeout(() => loadLogs(false), 250);
});
let dateDebounce;
[sinceInput, untilInput].forEach((el) => {
el?.addEventListener('change', () => {
clearTimeout(dateDebounce);
dateDebounce = setTimeout(() => loadLogs(false), 250);
});
});
refreshBtn?.addEventListener('click', () => loadLogs(false));
loadMoreBtn?.addEventListener('click', () => loadLogs(true));
clearBtn?.addEventListener('click', clearLogs);
wireModal(modal, closeBtn);
}
refreshBtn?.addEventListener('click', loadErrorLogs);
clearBtn?.addEventListener('click', clearErrorLogs);
wireModal(modal, closeBtn);
viewBtn?.addEventListener('click', async () => {
modal?.classList.add('show');
await refreshContexts();
loadLogs(false);
});
wireFilters();
})();
+1 -1
View File
@@ -1,4 +1,4 @@
const CACHE = 'dashcaddy-shell-78eab743c2';
const CACHE = 'dashcaddy-shell-3958800b99';
const PRECACHE = [
'/',
'/index.html',