(function(){injectModal("logo-modal",`<div id="logo-modal" class="weather-modal">
    <div class="weather-modal-content" style="min-width: 400px; max-width: 520px;">
      <h3>Dashboard Settings</h3>
      <p style="font-size: 0.85rem; color: var(--muted); margin: 0 0 16px;">
        Customize your dashboard's appearance and system preferences.
      </p>

      <div class="mb-16">
        <label for="dashboard-title" class="form-label-bold">Dashboard Title:</label>
        <input type="text" id="dashboard-title" placeholder="DashCaddy" maxlength="50" style="width: 100%; padding: 10px 12px; border: 1px solid var(--border); border-radius: 4px; background: var(--card-bg); color: var(--fg); font-size: 1rem;" />
        <p class="tiny-hint">Shown in browser tab and header (max 50 characters)</p>
      </div>

      <hr class="hr-divider" />

      <div class="mb-16">
        <label class="form-label-bold">Logo:</label>
        <p class="tiny-hint" style="margin-top: 2px;">Separate logos for dark and light themes, or use the same for both.</p>
      </div>

      <div style="display: flex; gap: 12px; margin-bottom: 12px;">
        <div style="flex: 1; text-align: center; padding: 16px 10px; border-radius: 8px; background: #1a1a2e; border: 1px solid rgba(255,255,255,.1);">
          <img id="logo-preview-dark" src="/assets/dashcaddy-logo-dark.png" alt="Dark theme logo" style="max-height: 60px; max-width: 100%;" />
          <p style="font-size: 0.65rem; color: #9aa6bf; margin-top: 6px;">Dark themes</p>
        </div>
        <div style="flex: 1; text-align: center; padding: 16px 10px; border-radius: 8px; background: #f0f0f0; border: 1px solid rgba(0,0,0,.1);">
          <img id="logo-preview-light" src="/assets/dashcaddy-logo-light.png" alt="Light theme logo" style="max-height: 60px; max-width: 100%;" />
          <p style="font-size: 0.65rem; color: #5f6b7a; margin-top: 6px;">Light themes</p>
        </div>
      </div>
      <p id="logo-status" style="font-size: 0.75rem; color: var(--muted); margin-bottom: 12px; text-align: center;">Using default logos</p>

      <div class="mb-16">
        <label style="display: flex; align-items: center; gap: 8px; font-size: 0.82rem; cursor: pointer; user-select: none;">
          <input type="checkbox" id="logo-same-both" /> Use same logo for both
        </label>
      </div>

      <div id="logo-dual-uploads" class="mb-16" style="display: flex; gap: 12px;">
        <div style="flex: 1;">
          <label for="logo-upload-dark" style="display: block; margin-bottom: 6px; font-size: 0.8rem;">Dark theme logo:</label>
          <input type="file" id="logo-upload-dark" accept="image/*" class="input-card-alt" style="font-size: 0.75rem;" />
        </div>
        <div style="flex: 1;">
          <label for="logo-upload-light" style="display: block; margin-bottom: 6px; font-size: 0.8rem;">Light theme logo:</label>
          <input type="file" id="logo-upload-light" accept="image/*" class="input-card-alt" style="font-size: 0.75rem;" />
        </div>
      </div>

      <div id="logo-single-upload" class="mb-16" style="display: none;">
        <label for="logo-upload-single" style="display: block; margin-bottom: 6px; font-size: 0.8rem;">Upload logo:</label>
        <input type="file" id="logo-upload-single" accept="image/*" class="input-card-alt" />
        <p class="tiny-hint">This logo will be used on all themes</p>
      </div>

      <div class="mb-16">
        <label style="display: block; margin-bottom: 8px;">Logo Position:</label>
        <div id="logo-position-btns" class="flex-row-gap">
          <button type="button" data-pos="left" class="logo-pos-btn btn-option">Left</button>
          <button type="button" data-pos="center" class="logo-pos-btn btn-option">Center</button>
          <button type="button" data-pos="right" class="logo-pos-btn btn-option">Right</button>
        </div>
      </div>

      <hr class="hr-divider" />

      <div class="mb-16">
        <label class="form-label-bold">Favicon (Browser Tab Icon):</label>
        <div id="favicon-preview-container" style="display: flex; align-items: center; gap: 12px; margin-bottom: 8px; padding: 12px; border-radius: 6px; background: var(--card-bg);">
          <img id="favicon-preview" src="/assets/dashcaddy-favicon.ico" alt="Current favicon" style="width: 32px; height: 32px; image-rendering: pixelated;" onerror="this.src='data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 32 32%22><rect fill=%22%23667%22 width=%2232%22 height=%2232%22 rx=%224%22/></svg>'" />
          <span id="favicon-status" class="text-tiny-muted">Using DashCaddy favicon</span>
        </div>
        <input type="file" id="favicon-upload" accept="image/png,image/svg+xml" class="input-card-alt" />
        <p class="tiny-hint">Upload PNG or SVG - automatically converted to ICO</p>
      </div>

      <hr class="hr-divider" />

      <div class="mb-16">
        <label for="settings-timezone" class="form-label-bold">Timezone:</label>
        <select id="settings-timezone" style="width: 100%; padding: 10px 12px; border: 1px solid var(--border); border-radius: 4px; background: var(--card-bg); color: var(--fg); font-size: 1rem;">
          <!-- Populated by JS with IANA timezones -->
        </select>
        <p class="tiny-hint">Used by all deployed containers. Changes apply to new deployments.</p>
      </div>

      <div class="weather-modal-buttons">
        <button id="logo-reset" style="background: color-mix(in srgb, #ef4444 20%, transparent); border-color: #ef4444; color: #ef4444;">Reset to Default</button>
        <button id="logo-cancel">Cancel</button>
        <button id="logo-save" class="btn-accent">Save</button>
      </div>
    </div>
  </div>`);const h=document.getElementById("logo-modal"),E=document.getElementById("logo-preview-dark"),P=document.getElementById("logo-preview-light"),w=document.getElementById("logo-status"),N=document.getElementById("logo-same-both"),O=document.getElementById("logo-dual-uploads"),z=document.getElementById("logo-single-upload"),A=document.getElementById("logo-upload-dark"),v=document.getElementById("logo-upload-light"),L=document.getElementById("logo-upload-single"),b=document.querySelector("#brand .brand-logo-dark"),M=document.querySelector("#brand .brand-logo-light"),k=document.querySelector(".top-row"),B=document.getElementById("dashboard-title"),S=DC.NAME;let T=null,j=null,H=null,R="left",x=S;N?.addEventListener("change",()=>{N.checked?(O.style.display="none",z.style.display="",T=null,j=null):(O.style.display="flex",z.style.display="none",H=null)});function D(n,e){if(!n||!n.type.startsWith("image/")){showNotification("Please select an image file","warning");return}const o=new FileReader;o.onload=a=>e(a.target.result),o.readAsDataURL(n)}A?.addEventListener("change",n=>{D(n.target.files[0],e=>{T=e,E.src=e,w.textContent="New dark logo ready to save"})}),v?.addEventListener("change",n=>{D(n.target.files[0],e=>{j=e,P.src=e,w.textContent="New light logo ready to save"})}),L?.addEventListener("change",n=>{D(n.target.files[0],e=>{H=e,E.src=e,P.src=e,w.textContent="New logo ready to save (both themes)"})});function g(n){k.setAttribute("data-logo-pos",n),document.querySelectorAll(".logo-pos-btn").forEach(e=>{e.style.background=e.dataset.pos===n?"var(--accent)":"var(--card-bg)",e.style.color=e.dataset.pos===n?"white":"var(--fg)"})}function u(n){x=n||S,document.title=x;const e=document.querySelector(".dashboard-title");e&&(e.textContent=x)}async function f(){try{const n=await fetch("/api/v1/logo");if(n.ok){const e=await n.json();e.customLogoDark&&(b.src=e.customLogoDark,E.src=e.customLogoDark),e.customLogoLight&&(M.src=e.customLogoLight,P.src=e.customLogoLight),!e.customLogoDark&&!e.customLogoLight&&e.customLogo&&(b.src=e.customLogo,M.src=e.customLogo,E.src=e.customLogo,P.src=e.customLogo),e.isDefault||(w.textContent="Using custom logo"),e.position&&(R=e.position,g(e.position)),e.dashboardTitle&&u(e.dashboardTitle)}}catch(n){console.warn("Could not load custom logo:",n.message)}}document.querySelectorAll(".logo-pos-btn").forEach(n=>{n.addEventListener("click",()=>{R=n.dataset.pos,g(R)})}),document.getElementById("brand")?.addEventListener("click",()=>{T=null,j=null,H=null,A&&(A.value=""),v&&(v.value=""),L&&(L.value=""),N&&(N.checked=!1),O.style.display="flex",z.style.display="none",E.src=b.src,P.src=M.src;const n=b.src.includes("custom-logo")||M.src.includes("custom-logo");w.textContent=n?"Using custom logo":"Using default logos",g(R),B.value=x,h.classList.add("show")}),document.getElementById("logo-save")?.addEventListener("click",async()=>{try{const n=B.value.trim()||S,e={position:R,dashboardTitle:n};N?.checked&&H?(e.dataDark=H,e.dataLight=H):(T&&(e.dataDark=T),j&&(e.dataLight=j));const o=await secureFetch("/api/v1/logo",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(o.ok){const a=await o.json(),r="?t="+Date.now();a.pathDark&&(b.src=a.pathDark+r,E.src=a.pathDark+r),a.pathLight&&(M.src=a.pathLight+r,P.src=a.pathLight+r),g(R),u(n),h.classList.remove("show")}else{const a=await o.json();showNotification("Failed to save: "+a.error,"error")}}catch(n){showNotification("Error saving: "+n.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&&(b.src="/assets/dashcaddy-logo-dark.png",M.src="/assets/dashcaddy-logo-light.png",E.src="/assets/dashcaddy-logo-dark.png",P.src="/assets/dashcaddy-logo-light.png",w.textContent="Using default logos",T=null,j=null,H=null,B.value=S,u(S),R="left",g("left")),(await secureFetch("/api/v1/favicon",{method:"DELETE"})).ok){const o=document.querySelector('link[rel="icon"]'),a=document.getElementById("favicon-preview"),r=document.getElementById("favicon-status");o&&(o.href="/assets/dashcaddy-favicon.ico?t="+Date.now()),a&&(a.src="/assets/dashcaddy-favicon.ico?t="+Date.now()),r&&(r.textContent="Using DashCaddy favicon"),i=null}}catch(n){showNotification("Error resetting branding: "+n.message,"error")}}),wireModal(h,document.getElementById("logo-cancel"));const m=document.getElementById("favicon-preview"),p=document.getElementById("favicon-status"),d=document.getElementById("favicon-upload"),c=document.querySelector('link[rel="icon"]')||document.createElement("link");let i=null;document.querySelector('link[rel="icon"]')||(c.rel="icon",c.href="/assets/dashcaddy-favicon.ico",document.head.appendChild(c));async function $(){try{const n=await fetch("/api/v1/favicon");if(n.ok){const e=await n.json();e.customFavicon&&(c.href=e.customFavicon+"?t="+Date.now(),m.src=e.customFavicon+"?t="+Date.now(),p.textContent="Using custom favicon")}}catch(n){console.warn("Could not load custom favicon:",n.message)}}d?.addEventListener("change",n=>{const e=n.target.files[0];if(!e)return;if(!e.type.match(/^image\/(png|svg\+xml)$/)){showNotification("Please select a PNG or SVG file","warning"),d.value="";return}const o=new FileReader;o.onload=a=>{i=a.target.result,m.src=i,p.textContent="New favicon ready to save"},o.readAsDataURL(e)}),document.getElementById("logo-save")?.addEventListener("click",async()=>{if(i)try{const n=await secureFetch("/api/v1/favicon",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({data:i})});if(n.ok){const e=await n.json();c.href=e.path+"?t="+Date.now(),m.src=e.path+"?t="+Date.now(),p.textContent="Using custom favicon",i=null}else{const e=await n.json();showNotification("Failed to save favicon: "+e.error,"error")}}catch(n){showNotification("Error saving favicon: "+n.message,"error")}}),$(),f();const y=document.getElementById("settings-timezone");y&&(new MutationObserver(()=>{h.classList.contains("show")&&y.options.length===0&&(async()=>{let e;try{const o=await fetch("/api/v1/config");o.ok&&(e=(await o.json()).timezone)}catch{}window.populateTimezoneSelect(y,e)})()}).observe(h,{attributes:!0,attributeFilter:["class"]}),document.getElementById("logo-save")?.addEventListener("click",async()=>{const e=y.value;if(e)try{const o=await fetch("/api/v1/config");if(!o.ok)return;const a=await o.json();a.timezone=e,a.updatedAt=new Date().toISOString(),await secureFetch("/api/v1/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)})}catch(o){console.warn("Failed to save timezone:",o.message)}}))})(),window.populateTimezoneSelect=function(h,E){const P=Intl.supportedValuesOf("timeZone"),w=E||Intl.DateTimeFormat().resolvedOptions().timeZone||"UTC";h.innerHTML="";for(const N of P){const O=document.createElement("option");O.value=N,O.textContent=N.replace(/_/g," "),N===w&&(O.selected=!0),h.appendChild(O)}},(function(){let h="homelab",E=null;async function P(){try{const D=await fetch("/api/v1/config");if(D.ok&&(E=await D.json(),E&&E.setupComplete))return document.getElementById("setup-wizard").style.display="none",!0}catch(D){console.warn("Could not fetch server config, checking localStorage fallback:",D.message)}return safeGet("dashcaddy-setup")?(document.getElementById("setup-wizard").style.display="none",!0):(document.getElementById("setup-wizard").style.display="flex",!1)}P();const w=document.getElementById("setup-timezone");w&&window.populateTimezoneSelect(w);function N(x){document.querySelectorAll(".setup-step").forEach(g=>{g.style.display="none"});const D=document.getElementById(x);D&&(D.style.display="block")}function O(){const x=document.getElementById("setup-summary-content");if(!x)return;let D='<div style="display: grid; gap: 20px;">';if(h==="homelab"){const u=document.getElementById("setup-tld")?.value?.trim()||".home",f=document.getElementById("setup-ca-name")?.value?.trim()||"",m=document.getElementById("setup-dns-ip")?.value?.trim()||"",p=document.getElementById("setup-dns-port")?.value?.trim()||DC.DEFAULTS.DNS_PORT;D+=`
        <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> ${u}</div>
            <div><strong>Certificate Authority:</strong> ${f}</div>
            <div><strong>DNS Server:</strong> ${m}:${p}</div>
            <div><strong>Example URLs:</strong> https://uptime${u}, https://nextcloud${u}</div>
          </div>
        </div>
      `}else if(h==="simple"){const u=document.getElementById("setup-simple-ip")?.value?.trim()||"localhost";D+=`
        <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> ${u}</div>
            <div><strong>SSL:</strong> None (HTTP only)</div>
            <div><strong>Example URLs:</strong> http://${u}:8080, http://${u}:3000</div>
          </div>
        </div>
      `}else if(h==="public"){const u=document.getElementById("setup-public-domain")?.value?.trim()||"",f=document.getElementById("setup-public-email")?.value?.trim()||"",m=document.querySelector('input[name="routing-mode"]:checked')?.value||"subdirectory",p=m==="subdirectory"?`https://${u}/sonarr, https://${u}/grafana`:`https://sonarr.${u}, https://grafana.${u}`;D+=`
        <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> ${u}</div>
            <div><strong>SSL:</strong> Let's Encrypt</div>
            <div><strong>Email:</strong> ${f}</div>
            <div><strong>Routing:</strong> ${m==="subdirectory"?"Subdirectory (domain.com/app)":"Subdomain (app.domain.com)"}</div>
            <div><strong>Example URLs:</strong> ${p}</div>
          </div>
        </div>
      `}const g=document.getElementById("setup-timezone")?.value||Intl.DateTimeFormat().resolvedOptions().timeZone||"UTC";D+=`
      <div style="margin-top: 8px; padding-top: 12px; border-top: 1px solid var(--border);">
        <div style="font-size: 0.95rem;"><strong>Timezone:</strong> ${g.replace(/_/g," ")}</div>
      </div>
    `,D+="</div>",x.innerHTML=D,N("setup-step-summary")}async function z(x){try{const D=await secureFetch("/api/v1/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(x)});return D.ok?(await D.json(),!0):(errorHandler.logError("[SetupWizard] Save Config",new Error(`Server returned ${D.status}`),{function:"saveConfigToServer"}),!1)}catch(D){return errorHandler.logError("[SetupWizard] Save Config",D,{function:"saveConfigToServer"}),!1}}async function A(){const x={setupComplete:!0,configurationType:h,timestamp:new Date().toISOString(),timezone:document.getElementById("setup-timezone")?.value||Intl.DateTimeFormat().resolvedOptions().timeZone||"UTC"};h==="homelab"?(x.tld=document.getElementById("setup-tld")?.value?.trim()||".home",x.caName=document.getElementById("setup-ca-name")?.value?.trim()||"",x.dns={provider:"technitium",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()||""},x.defaults={dnsType:"private",sslType:"internal",targetIP:"localhost"}):h==="simple"?(x.defaultIP=document.getElementById("setup-simple-ip")?.value?.trim()||"localhost",x.defaults={dnsType:"none",sslType:"none",targetIP:x.defaultIP}):h==="public"&&(x.domain=document.getElementById("setup-public-domain")?.value?.trim()||"",x.email=document.getElementById("setup-public-email")?.value?.trim()||"",x.routingMode=document.querySelector('input[name="routing-mode"]:checked')?.value||"subdirectory",x.defaults={dnsType:x.routingMode==="subdirectory"?"none":"public",sslType:"letsencrypt",targetIP:"localhost"});const D=await z(x);safeSet("dashcaddy-config",JSON.stringify(x)),safeSet("dashcaddy-setup","completed"),document.getElementById("setup-wizard").style.display="none";const g=h==="homelab"?"Professional Home Lab":h==="simple"?"Simple Setup":"Public Server",u=D?"server (shared across all devices)":"locally (this browser only)";showNotification(`Setup Complete! Configured for: ${g}. Settings saved to: ${u}`,"success",5e3),setTimeout(()=>location.reload(),500)}const v=document.getElementById("setup-step-1-next");v&&(v.onclick=function(x){x.preventDefault();const D=document.querySelector('input[name="config-type"]:checked');D&&(h=D.value),N(h==="homelab"?"setup-step-homelab":h==="simple"?"setup-step-simple":h==="public"?"setup-step-public":"setup-step-homelab")});const L=document.getElementById("setup-skip");L&&(L.onclick=async function(x){x.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 b=document.getElementById("setup-tld");b&&(b.oninput=function(x){const D=x.target.value||".home",g=document.getElementById("tld-preview"),u=document.getElementById("tld-preview-2");g&&(g.textContent=D),u&&(u.textContent=D)});const M=document.getElementById("setup-homelab-back");M&&(M.onclick=function(x){x.preventDefault(),N("setup-step-1")});const k=document.getElementById("setup-homelab-next");k&&(k.onclick=function(x){x.preventDefault();const D=document.getElementById("setup-tld")?.value?.trim()||"",g=document.getElementById("setup-ca-name")?.value?.trim()||"",u=document.getElementById("setup-dns-ip")?.value?.trim()||"";if(!D||!D.startsWith(".")){showNotification("Please enter a valid TLD starting with a dot (e.g., .home)","warning");return}if(!g){showNotification("Please enter a Certificate Authority name","warning");return}if(!u){showNotification("Please enter your DNS server IP address","warning");return}O()});const B=document.getElementById("setup-simple-back");B&&(B.onclick=function(x){x.preventDefault(),N("setup-step-1")});const S=document.getElementById("setup-simple-next");S&&(S.onclick=function(x){x.preventDefault(),O()}),document.querySelectorAll('input[name="routing-mode"]').forEach(function(x){x.onchange=function(){var D=document.getElementById("dns-requirement-note");D&&(D.textContent=this.value==="subdirectory"?"Only one DNS record needed (for the main domain)":"You'll need to configure DNS manually for each subdomain")}});const T=document.getElementById("setup-public-back");T&&(T.onclick=function(x){x.preventDefault(),N("setup-step-1")});const j=document.getElementById("setup-public-next");j&&(j.onclick=function(x){x.preventDefault();const D=document.getElementById("setup-public-domain")?.value?.trim()||"",g=document.getElementById("setup-public-email")?.value?.trim()||"";if(!D){showNotification("Please enter your domain name","warning");return}if(!g||!g.includes("@")){showNotification("Please enter a valid email address","warning");return}O()});const H=document.getElementById("setup-summary-back");H&&(H.onclick=function(x){x.preventDefault(),h==="homelab"?N("setup-step-homelab"):h==="simple"?N("setup-step-simple"):h==="public"&&N("setup-step-public")});const R=document.getElementById("setup-finish");R&&(R.onclick=function(x){x.preventDefault(),A()}),window.getGlobalConfig=async function(){try{const D=await fetch("/api/v1/config");if(D.ok){const g=await D.json();if(g&&g.setupComplete)return g}}catch{console.warn("Could not fetch config from server")}const x=safeGet("dashcaddy-config");return x?JSON.parse(x):{setupComplete:!1,configurationType:"homelab",tld:".home",caName:"",defaults:{dnsType:"private",sslType:"internal",targetIP:"localhost"}}},window.resetSetupWizard=async function(){if(confirm("Reset DashCaddy configuration? This will show the setup wizard again.")){try{await secureFetch("/api/v1/config",{method:"DELETE"})}catch{console.warn("Could not delete server config")}safeRemove("dashcaddy-setup"),safeRemove("dashcaddy-config"),location.reload()}}})(),(function(){const h=new ErrorHandler;injectModal("app-selector-modal",`<div id="app-selector-modal" class="weather-modal">
    <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>
      <div style="text-align: center; margin-top: 24px;">
        <button id="app-selector-cancel">Cancel</button>
      </div>
    </div>
  </div>`),injectModal("app-deploy-modal",`<div id="app-deploy-modal" class="weather-modal">
    <div class="weather-modal-content" style="min-width: 600px; max-width: 700px;">
      <h3 id="app-deploy-title">Deploy Application</h3>

      <div style="display: grid; grid-template-columns: 1fr; gap: 16px; margin-top: 16px;">
        <!-- Subdomain/Domain -->
        <div>
          <label for="deploy-subdomain" class="form-label-accent-sm">
            \u{1F310} Subdomain or Domain
          </label>
          <input type="text" id="deploy-subdomain" placeholder="uptime"
                 style="width: 100%; padding: 10px; background: var(--card-bg); color: var(--fg); border: 1px solid var(--border); border-radius: 6px; font-size: 0.95rem;" />
          <div class="form-hint-sm">
            Your app will be available at: <span id="deploy-url-preview" style="color: var(--accent); font-weight: 500;">uptime.home</span>
          </div>
          <div id="subpath-compat-warning" style="display: none; padding: 8px 12px; border-radius: 6px; background: color-mix(in srgb, #ff9800 10%, var(--card-bg)); border: 1px solid color-mix(in srgb, #ff9800 30%, transparent); margin-top: 8px; font-size: 0.85rem;"></div>
        </div>

        <!-- DNS Configuration -->
        <div>
          <label class="form-label-accent">
            \u{1F5C2}\uFE0F DNS Configuration
          </label>
          <div class="flex-col-gap">
            <label class="radio-option">
              <input type="radio" name="dns-type" value="private" checked style="margin-right: 10px;" />
              <div>
                <div class="fw-500">Private DNS (Technitium)</div>
                <div class="text-hint">Use your local DNS server with custom TLD (.sami, .home, etc.)</div>
              </div>
            </label>
            <label class="radio-option">
              <input type="radio" name="dns-type" value="public" style="margin-right: 10px;" />
              <div>
                <div class="fw-500">Public DNS</div>
                <div class="text-hint">Use a real domain (example.com) - requires DNS provider setup</div>
              </div>
            </label>
            <label class="radio-option">
              <input type="radio" name="dns-type" value="none" style="margin-right: 10px;" />
              <div>
                <div class="fw-500">No DNS (IP:Port only)</div>
                <div class="text-hint">Access via IP address and port - no domain setup</div>
              </div>
            </label>
          </div>
        </div>

        <!-- SSL Configuration -->
        <div>
          <label class="form-label-accent">
            \u{1F512} SSL/TLS Certificate
          </label>
          <div class="flex-col-gap">
            <label class="radio-option">
              <input type="radio" name="ssl-type" value="internal" checked style="margin-right: 10px;" />
              <div>
                <div class="fw-500">Internal CA</div>
                <div class="text-hint">Use Caddy's internal certificate authority (self-signed)</div>
              </div>
            </label>
            <label class="radio-option">
              <input type="radio" name="ssl-type" value="letsencrypt" style="margin-right: 10px;" />
              <div>
                <div class="fw-500">Let's Encrypt</div>
                <div class="text-hint">Free public SSL certificate (requires public domain)</div>
              </div>
            </label>
            <label class="radio-option">
              <input type="radio" name="ssl-type" value="none" style="margin-right: 10px;" />
              <div>
                <div class="fw-500">No SSL (HTTP only)</div>
                <div class="text-hint">\u26A0\uFE0F Not recommended - traffic will be unencrypted</div>
              </div>
            </label>
          </div>
        </div>

        <!-- Media Library Path (shown for media apps) -->
        <div id="media-path-section" style="display: none;">
          <label class="form-label-accent">
            \u{1F4C1} Media Library Location
          </label>
          <div style="display: flex; flex-direction: column; gap: 10px;">
            <!-- Detected mounts from existing media servers -->
            <div id="detected-mounts-container" style="display: none;">
              <div style="font-size: 0.85rem; color: var(--success); margin-bottom: 6px;">
                \u2713 Detected from existing media servers:
              </div>
              <div id="detected-mounts-list" style="display: flex; gap: 8px; flex-wrap: wrap;"></div>
            </div>

            <!-- Path input with browse button -->
            <div class="flex-row-gap">
              <input type="text" id="deploy-media-path" placeholder="/media/Movies, /media/TVShows"
                     class="input-flex" style="font-size: 0.95rem;" />
              <button type="button" id="browse-media-btn" style="padding: 10px 16px; background: var(--accent); color: white; border: none; border-radius: 6px; cursor: pointer; font-weight: 500; white-space: nowrap;">
                \u{1F4C2} Browse
              </button>
            </div>

            <div id="media-path-description" class="text-hint">
              Select folders from existing servers, browse, or type paths manually. Separate multiple with commas.
            </div>

            <!-- Selected paths display -->
            <div id="selected-media-paths" style="display: none; flex-wrap: wrap; gap: 6px;"></div>
          </div>
        </div>

        <!-- Plex Claim Token (shown only for Plex deployments) -->
        <div id="plex-claim-section" style="display: none;">
          <label class="form-label-accent">
            \u{1F511} Plex Claim Token
          </label>
          <div class="flex-row-gap">
            <input type="text" id="deploy-plex-claim" placeholder="claim-xxxxxxxxxxxxxxxxxxxx"
                   class="input-flex" style="font-size: 0.95rem;" />
            <a href="https://plex.tv/claim" target="_blank" rel="noopener noreferrer"
               style="padding: 10px 16px; background: #e5a00d; color: #000; border: none; border-radius: 6px; cursor: pointer; font-weight: 500; white-space: nowrap; text-decoration: none; display: flex; align-items: center;">
              Get Token
            </a>
          </div>
          <div style="font-size: 0.8rem; color: #e5a00d; margin-top: 4px;">
            Token expires in 4 minutes! Get it right before clicking Deploy. Leave empty to configure Plex manually later.
          </div>
        </div>

        <!-- Tailscale Security -->
        <div id="tailscale-section">
          <label class="form-label-accent">
            \u{1F510} Tailscale Security
          </label>
          <div class="flex-col-gap">
            <label class="radio-option">
              <input type="checkbox" id="deploy-tailscale-only" style="margin-right: 10px; width: 18px; height: 18px;" />
              <div>
                <div class="fw-500">Tailscale-Only Access</div>
                <div class="text-hint">Restrict this service to Tailscale users only (100.x.x.x IPs)</div>
              </div>
            </label>
            <div id="tailscale-status" style="padding: 8px 12px; background: var(--card-bg); border-radius: 6px; font-size: 0.85rem;">
              <span style="color: var(--muted);">Checking Tailscale status...</span>
            </div>
          </div>
        </div>

        <!-- Advanced Options (Collapsible) -->
        <details>
          <summary style="cursor: pointer; color: var(--accent); font-weight: 500; margin-bottom: 8px;">\u2699\uFE0F Advanced Options</summary>
          <div style="margin-top: 12px; display: grid; gap: 12px;">
            <div>
              <label for="deploy-port" style="display: block; margin-bottom: 6px;">Custom Port (optional)</label>
              <input type="number" id="deploy-port" placeholder="Leave empty for default"
                     class="form-input-card" />
            </div>
            <div>
              <label for="deploy-ip" style="display: block; margin-bottom: 6px;">Target IP Address</label>
              <input type="text" id="deploy-ip" value="localhost"
                     class="form-input-card" />
              <div class="form-hint-sm">
                Use 'localhost' for same-host containers, or specific IP for remote services
              </div>
            </div>
            <div id="volume-mounts-section" style="display: none;">
              <label class="form-label-accent-sm">\u{1F4C2} Volume Mounts</label>
              <div style="font-size: 0.8rem; color: var(--muted); margin-bottom: 8px;">
                Customize where container data is stored on the host. Media volumes are configured above.
              </div>
              <div id="volume-mounts-list" style="display: grid; gap: 8px;"></div>
            </div>
            <div style="margin-top: 12px;">
              <label class="form-label-accent-sm">\u2699\uFE0F Resource Limits</label>
              <div style="font-size: 0.8rem; color: var(--muted); margin-bottom: 8px;">
                Optional CPU and memory constraints. Leave at 0 for unlimited.
              </div>
              <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px;">
                <div>
                  <label for="deploy-cpu-limit" style="display: block; font-size: 0.78rem; color: var(--muted); margin-bottom: 4px;">CPU Cores</label>
                  <input type="number" id="deploy-cpu-limit" value="0" min="0" max="64" step="0.25" class="form-input-card" style="width: 100%;" placeholder="0 = unlimited" />
                </div>
                <div>
                  <label for="deploy-memory-limit" style="display: block; font-size: 0.78rem; color: var(--muted); margin-bottom: 4px;">Memory (MB)</label>
                  <input type="number" id="deploy-memory-limit" value="0" min="0" max="131072" step="64" class="form-input-card" style="width: 100%;" placeholder="0 = unlimited" />
                </div>
              </div>
            </div>
          </div>
        </details>
      </div>

      <div class="weather-modal-buttons" style="margin-top: 24px;">
        <button id="app-deploy-cancel">Cancel</button>
        <button id="app-deploy-confirm" class="btn-accent">
          \u{1F680} Deploy
        </button>
      </div>
    </div>
  </div>`);const E="custom-apps";let P=null,w=null;const N=document.getElementById("app-selector-modal"),O=document.getElementById("app-selector-grid");async function z(){try{const c=await(await fetch("/api/v1/apps/templates")).json();if(c.success)return P=c.templates,w=c.categories,!0}catch(d){h.logError("[AppSelector] Fetch Templates",d,{function:"fetchApiTemplates"})}return!1}async function A(d){try{return await(await fetch(`/api/v1/apps/ports/${d}/check`)).json()}catch(c){return h.logError("[AppSelector] Check Port",c,{function:"checkPortAvailability"}),{available:!0}}}async function v(d){try{const i=await(await fetch(`/api/v1/apps/ports/${d}/suggest`)).json();if(i.success)return i.suggestedPort}catch(c){h.logError("[AppSelector] Get Suggested Port",c,{function:"getSuggestedPort"})}return d}async function L(){if(O.innerHTML='<div style="text-align: center; padding: 40px; color: var(--muted);">Loading app templates...</div>',!P&&!await z()){O.innerHTML='<div style="text-align: center; padding: 40px; color: var(--error);">Failed to load app templates. Please try again.</div>';return}O.innerHTML="";const d={};for(const[i,$]of Object.entries(P)){const y=$.category||"Other";d[y]||(d[y]=[]),d[y].push({id:i,...$})}const c=w?Object.keys(w):Object.keys(d).sort();for(const i of c){const $=d[i];if(!$||$.length===0)continue;$.sort((e,o)=>(o.popularity||0)-(e.popularity||0));const y=document.createElement("div");y.className="app-category-header";const n=w?.[i]||{};y.innerHTML=`${escapeHtml(n.icon||"")} ${escapeHtml(i)}`,n.color&&(y.style.borderBottomColor=n.color),O.appendChild(y),$.forEach(e=>{const o=document.createElement("div");o.className="app-option";const a=e.isDashboardWidget,r=a&&safeGet("widget-"+e.id+"-enabled")!=="false",t=a?`<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>`:"",s=!a&&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>`:"";o.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>
          ${t}${s}
        `,a?o.onclick=()=>b(e,o):o.onclick=()=>M(e),O.appendChild(o)})}window.renderRecipeCards&&await window.renderRecipeCards(O)}function b(d,c){const i="widget-"+d.id+"-enabled",y=!(safeGet(i)!=="false");safeSet(i,String(y));const n=d.widgetSelector;if(n){const o=document.querySelector(n);o&&(o.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(`${d.name} widget ${y?"enabled":"disabled"}`,"success",2e3)}async function M(d){const c=document.getElementById("app-deploy-modal"),i=document.getElementById("app-deploy-title"),$=document.getElementById("deploy-subdomain"),y=document.getElementById("deploy-url-preview"),n=document.getElementById("deploy-ip"),e=document.getElementById("deploy-port"),o=document.getElementById("deploy-tailscale-only"),a=document.getElementById("tailscale-status");try{const W=await(await secureFetch("/api/v1/apps/check-existing",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({appId:d.id})})).json();if(W.success&&W.exists){const V=W.container;confirm(`Found existing ${d.name} container:

Container: ${V.name}
Status: ${V.status}
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.`)&&(d._useExisting=!0,d._existingContainer=V)}}catch{}i.textContent=`Deploy ${d.name}`;const r=d.subdomain||d.id.replace(/-/g,"");$.value=r;const t=document.getElementById("subpath-compat-warning");if(t)if(SITE.routingMode==="subdirectory"){const _=d.subpathSupport||"strip";_==="none"?(t.style.display="block",t.innerHTML='<span style="color: #ff9800;">&#9888; <strong>'+d.name+"</strong> does not support subdirectory mode. It may not work correctly at a subpath.</span>"):_==="strip"?(t.style.display="block",t.innerHTML='<span style="color: var(--muted);">&#9432; '+d.name+" has unverified subdirectory support. It may require additional configuration.</span>"):t.style.display="none"}else t.style.display="none";const s=SITE.defaults.dnsType||(SITE.configurationType==="public"?"public":"private"),l=SITE.defaults.sslType||(SITE.configurationType==="public"?"letsencrypt":"internal"),C=document.querySelector(`input[name="dns-type"][value="${s}"]`),I=document.querySelector(`input[name="ssl-type"][value="${l}"]`);C?C.checked=!0:document.querySelector('input[name="dns-type"][value="private"]').checked=!0,I?I.checked=!0:document.querySelector('input[name="ssl-type"][value="internal"]').checked=!0,n.value=SITE.defaults.targetIP||"localhost",o.checked=!1;const F=document.querySelector("#app-deploy-modal .flex-col-gap")?.closest("div"),q=document.querySelector("#app-deploy-modal details"),U=q?.querySelector("div");if(q&&U&&(SITE.configurationType==="public"||SITE.configurationType==="homelab")){const _=document.querySelectorAll('#app-deploy-modal input[name="dns-type"]')[0]?.closest("div.flex-col-gap")?.parentElement,W=document.querySelectorAll('#app-deploy-modal input[name="ssl-type"]')[0]?.closest("div.flex-col-gap")?.parentElement;_&&!_.dataset.moved&&(U.appendChild(_),_.dataset.moved="1"),W&&!W.dataset.moved&&(U.appendChild(W),W.dataset.moved="1")}const G=document.getElementById("media-path-section"),J=document.getElementById("deploy-media-path"),X=document.getElementById("media-path-description");if(d.mediaMount){G.style.display="block",J.value="",J.placeholder="/media/Movies, /media/TVShows or click Browse";const _=document.getElementById("detected-mounts-container"),W=document.getElementById("detected-mounts-list");try{const K=await(await fetch("/api/v1/media/detected-mounts")).json();if(K.success&&K.mounts.length>0){_.style.display="block",W.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 le=te.includes(ee.hostPath);Z.style.cssText=`padding: 8px 14px; font-size: 0.85rem; background: color-mix(in srgb, var(--success) ${le?"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 de=J.value.split(",").map(ce=>ce.trim()).filter(ce=>ce),pe=de.indexOf(ee.hostPath);pe>=0?(de.splice(pe,1),Z.style.background="color-mix(in srgb, var(--success) 15%, var(--card-bg))"):(de.push(ee.hostPath),Z.style.background="color-mix(in srgb, var(--success) 40%, var(--card-bg))"),J.value=de.join(", ")},W.appendChild(Z)})}else _.style.display="none"}catch{_.style.display="none"}document.getElementById("browse-media-btn").onclick=()=>{openFolderBrowser(J)}}else G.style.display="none",J.value="",document.getElementById("detected-mounts-container").style.display="none";const Q=document.getElementById("plex-claim-section");Q&&(d.id==="plex"||d.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="",d.docker?.volumes?.length){const _=d.mediaMount?.containerPath,W=d.docker.volumes.filter(V=>!V.includes("{{MEDIA_PATH}}")&&!(_&&V.endsWith(":"+_)));W.length>0?(ne.style.display="block",W.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 le=Z.querySelector(".vol-host-path");openFolderBrowser(le)}})):ne.style.display="none"}else ne.style.display="none";const se=d.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 _=e.value||se;Y.innerHTML='<span style="color: var(--muted);">Checking port...</span>';const W=await A(_);if(W.available)Y.innerHTML=`<span style="color: #4caf50;">Port ${escapeHtml(String(_))} is available</span>`;else{const V=await v(se);Y.innerHTML=`
          <span style="color: #e74c3c;">Port ${escapeHtml(_)} in use by ${escapeHtml(W.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 W=await(await fetch("/api/v1/tailscale/status")).json();W.success&&W.installed&&W.connected?a.innerHTML=`
          <span style="color: #4caf50;">Connected</span>
          <span style="color: var(--muted); margin-left: 8px;">${W.self?.hostname} (${W.self?.ip})</span>
          <span style="color: var(--muted); margin-left: 8px;">| ${W.deviceCount} devices</span>
        `:W.installed?a.innerHTML='<span style="color: #ff9800;">Not connected</span>':(a.innerHTML='<span style="color: var(--muted);">Not available</span>',o.disabled=!0)}catch{a.innerHTML='<span style="color: var(--muted);">Could not check status</span>'}function ae(){const _=$.value||"subdomain",W=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}/${_}`;else if(W==="private")K=`${V==="none"?"http":"https"}://${buildDomain(_)}`;else if(W==="public"){const te=V==="none"?"http":"https",ee=SITE.domain||_;K=SITE.domain?`${te}://${_}.${SITE.domain}`:`${te}://${_}`}else{const te=e.value||d.defaultPort||DC.DEFAULTS.SERVICE_PORT;K=`http://${n.value}:${te}`}y.textContent=K}$.oninput=ae,n.oninput=ae,e.oninput=ae,document.querySelectorAll('input[name="dns-type"]').forEach(_=>{_.onchange=ae}),document.querySelectorAll('input[name="ssl-type"]').forEach(_=>{_.onchange=ae}),ae(),N.classList.remove("show"),c.classList.add("show"),c.dataset.appTemplate=JSON.stringify(d)}async function k(d){const c=d.appTemplate,i=safeGetJSON(E,[]),$=c._useExisting&&c._existingContainer,y=i.find(n=>n.id===d.subdomain);if(!(y&&!$&&!confirm(`An app with subdomain "${d.subdomain}" already exists. Redeploy?`))){if(y){const n=i.indexOf(y);i.splice(n,1),safeSet(E,JSON.stringify(i))}if($)d.port=c._existingContainer.primaryPort;else{const n=d.port||c.defaultPort||8080;showNotification(`Checking port ${n} availability...`,"info",0);const e=await A(n);if(!e.available){const o=await v(c.defaultPort||8080);if(confirm(`Port ${n} is already in use by ${e.conflict?.usedBy||"another container"}.

Would you like to use port ${o} instead?`))d.port=o;else{showNotification("Deployment cancelled - port conflict","error",5e3);return}}}showNotification($?`Configuring ${c.name} with existing container...`:`Deploying ${c.name}...`,"info",0);try{const n={appId:c.id,config:{subdomain:d.subdomain,ip:d.ip,createDns:d.dnsType==="private",port:d.port||c.defaultPort||null,sslType:d.sslType,dnsType:d.dnsType,tailscaleOnly:d.tailscaleOnly||!1,mediaPath:d.mediaPath||null,plexClaimToken:d.plexClaimToken||null,customVolumes:d.customVolumes||null}};$&&(n.config.useExisting=!0,n.config.existingContainerId=c._existingContainer.id,n.config.existingPort=c._existingContainer.primaryPort,!d.port&&c._existingContainer.primaryPort&&(n.config.port=c._existingContainer.primaryPort));const o=await(await secureFetch("/api/v1/apps/deploy",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)})).json();if(o.success){const a={id:d.subdomain,name:c.name,logo:`/assets/${c.id}.png`,containerId:o.containerId,url:o.url,ip:d.ip,appTemplate:c.id,tailscaleOnly:d.tailscaleOnly||!1};i.push(a),safeSet(E,JSON.stringify(i)),window.APPS&&!window.APPS.some(t=>t.id===c.id)&&(window.APPS.push(a),typeof window.buildGrid=="function"&&window.buildGrid(),typeof window.refreshAll=="function"&&setTimeout(()=>window.refreshAll(),500));let r=o.usedExisting?`${c.name} configured with existing container!
URL: ${o.url}`:`${c.name} deployed successfully!
URL: ${o.url}`;o.warning&&(r+=`

\u26A0 Warning: ${o.warning}`),showNotification(r,"success",8e3),delete c._useExisting,delete c._existingContainer,o.url&&o.url.startsWith("https://")&&B(o.url,c.name),o.setupInstructions&&o.setupInstructions.length>0&&setTimeout(()=>{const t=o.setupInstructions.join(`
`);showNotification(`Setup Instructions for ${c.name}: ${t}`,"info",1e4)},1e3)}else throw new Error(o.error||"Deployment failed")}catch(n){h.logError("[AppSelector] Deployment",n,{function:"deploy"}),showNotification(`Failed to deploy ${c.name}: ${n.message}`,"error",8e3)}}}async function B(d,c){showNotification(`\u23F3 Generating SSL certificate for ${c}...`,"warning",6e4);let i=0;const $=12,y=async()=>{i++;try{const n=await fetch(d,{method:"HEAD",mode:"no-cors"});return showNotification(`\u2705 ${c} is ready! SSL certificate generated.`,"success",5e3),!0}catch{return i<$?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(E,[]).forEach(c=>{window.APPS.some(i=>i.id===c.id)||window.APPS.push(c)})}document.getElementById("add-service-btn")?.addEventListener("click",()=>{L(),N.classList.add("show")}),wireModal(N,document.getElementById("app-selector-cancel"));const T=document.getElementById("app-deploy-modal");document.getElementById("app-deploy-cancel")?.addEventListener("click",()=>{T.classList.remove("show")}),document.getElementById("app-deploy-confirm")?.addEventListener("click",()=>{const d=JSON.parse(T.dataset.appTemplate),c=document.getElementById("deploy-media-path").value.trim(),i=[];document.querySelectorAll("#volume-mounts-list .vol-host-path").forEach(y=>{i.push({hostPath:y.value.trim(),containerPath:y.dataset.containerPath})});const $={appTemplate:d,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:i.length>0?i:null,resources:{cpus:parseFloat(document.getElementById("deploy-cpu-limit").value)||0,memory:parseFloat(document.getElementById("deploy-memory-limit").value)||0}};if(!$.subdomain){showNotification("Please enter a subdomain or domain name","warning");return}if(d.mediaMount?.required&&!c){showNotification("Please enter a media library path for this application","warning");return}T.classList.remove("show"),k($)}),wireModal(T);const j=document.getElementById("folder-browser-modal"),H=document.getElementById("folder-browser-path"),R=document.getElementById("folder-browser-list"),x=document.getElementById("folder-browser-selected"),D=document.getElementById("folder-browser-selected-list");let g="",u=[],f=null;window.openFolderBrowser=function(d){f=d,u=d.value.split(",").map(c=>c.trim()).filter(c=>c),g="",p(),m(""),j.classList.add("show")};async function m(d){H.textContent=d||"Select a drive...",R.innerHTML='<div style="padding: 20px; text-align: center; color: var(--muted);">Loading...</div>';try{const i=await(await fetch(`/api/v1/browse/directories?path=${encodeURIComponent(d)}`)).json();if(!i.success){R.innerHTML=`<div style="padding: 20px; text-align: center; color: var(--error);">Error: ${escapeHtml(i.error)}</div>`;return}g=i.path||"",H.textContent=g||"Select a drive...";let $="";i.parent&&i.parent!==i.path&&($+=`<div class="folder-item" data-path="${escapeHtml(i.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>`),i.items.length===0&&!i.parent?$+='<div style="padding: 20px; text-align: center; color: var(--muted);">No browseable drives configured. Check your docker-compose.yml volume mounts.</div>':i.items.length===0?$+='<div style="padding: 20px; text-align: center; color: var(--muted);">No subfolders found</div>':i.items.forEach(y=>{const n=y.type==="drive"?"\u{1F4BE}":"\u{1F4C1}",e=u.includes(y.path),o=e?"background: color-mix(in srgb, var(--success) 20%, transparent);":"";$+=`<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; ${o}">
            <span style="font-size: 1.2rem;">${n}</span>
            <span style="flex: 1;">${escapeHtml(y.name)}</span>
            ${e?'<span style="color: var(--success);">\u2713</span>':""}
          </div>`}),R.innerHTML=$,R.querySelectorAll(".folder-item").forEach(y=>{y.addEventListener("click",()=>{m(y.dataset.path)}),y.addEventListener("mouseenter",()=>{y.style.background="var(--card-bg)"}),y.addEventListener("mouseleave",()=>{const n=u.includes(y.dataset.path);y.style.background=n?"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 p(){if(u.length===0){x.style.display="none";return}x.style.display="block",D.innerHTML=u.map(d=>`
      <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(d)}
        <button type="button" onclick="removeSelectedFolder('${escapeHtml(d)}')" style="background: none; border: none; cursor: pointer; color: var(--error); font-size: 1rem; padding: 0;">\xD7</button>
      </span>
    `).join("")}window.removeSelectedFolder=function(d){u=u.filter(c=>c!==d),p(),m(g)},document.getElementById("folder-browser-select-current").addEventListener("click",()=>{g&&!u.includes(g)&&(u.push(g),p(),m(g))}),wireModal(j,document.getElementById("folder-browser-cancel")),document.getElementById("folder-browser-done").addEventListener("click",()=>{f&&(f.value=u.join(", ")),j.classList.remove("show")}),S()})(),(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>

      <!-- Step indicator -->
      <div id="recipe-steps" style="display: flex; gap: 4px; margin: 16px 0 24px;">
        <div class="recipe-step active" data-step="1"><span>1</span> Components</div>
        <div class="recipe-step" data-step="2"><span>2</span> Configuration</div>
        <div class="recipe-step" data-step="3"><span>3</span> Review</div>
        <div class="recipe-step" data-step="4"><span>4</span> Progress</div>
      </div>

      <!-- Step 1: Component Selection -->
      <div id="recipe-step-1" class="recipe-step-panel">
        <label class="form-label-accent-sm">Select Components:</label>
        <div id="recipe-component-list" style="display: grid; gap: 10px; margin-top: 8px;"></div>
      </div>

      <!-- Step 2: Shared Configuration -->
      <div id="recipe-step-2" class="recipe-step-panel" style="display:none;">
        <div style="display: grid; gap: 16px;">
          <!-- Shared volumes -->
          <div id="recipe-volumes-section" style="display:none;">
            <label class="form-label-accent-sm">Shared Volumes:</label>
            <div id="recipe-volume-list" style="display: grid; gap: 10px; margin-top: 8px;"></div>
          </div>

          <!-- Timezone -->
          <div>
            <label class="form-label-accent-sm">Timezone:</label>
            <input type="text" id="recipe-timezone" value="UTC" placeholder="e.g. America/New_York"
              style="width: 100%; padding: 8px 12px; background: var(--card-bg); color: var(--fg); border: 1px solid var(--border); border-radius: 6px;" />
          </div>

          <!-- Target IP -->
          <div>
            <label class="form-label-accent-sm">Target IP Address:</label>
            <input type="text" id="recipe-ip" value="host.docker.internal" placeholder="localhost or IP"
              style="width: 100%; padding: 8px 12px; background: var(--card-bg); color: var(--fg); border: 1px solid var(--border); border-radius: 6px;" />
            <div class="form-hint-sm">IP where containers expose ports</div>
          </div>

          <!-- Tailscale -->
          <label class="checkbox-label">
            <input type="checkbox" id="recipe-tailscale" />
            <span>Restrict to Tailscale network only</span>
          </label>
        </div>
      </div>

      <!-- Step 3: Review -->
      <div id="recipe-step-3" class="recipe-step-panel" style="display:none;">
        <div id="recipe-review-content" style="font-size: 0.9rem; line-height: 1.7;"></div>
      </div>

      <!-- Step 4: Progress -->
      <div id="recipe-step-4" class="recipe-step-panel" style="display:none;">
        <div id="recipe-progress-list" style="display: grid; gap: 8px;"></div>
        <div id="recipe-deploy-result" style="margin-top: 16px; display:none;"></div>
      </div>

      <div class="weather-modal-buttons" style="margin-top: 20px;">
        <button id="recipe-cancel">Cancel</button>
        <button id="recipe-prev" class="btn-accent" style="display:none;">Back</button>
        <button id="recipe-next" class="btn-accent-solid">Next</button>
      </div>
    </div>
  </div>`);let h=null,E=null,P=null,w=1,N=!1;const O=document.getElementById("recipe-deploy-modal"),z=document.getElementById("recipe-cancel"),A=document.getElementById("recipe-prev"),v=document.getElementById("recipe-next");wireModal(O,z);async function L(){try{const g=await fetch("/api/v1/recipes/templates"),u=await g.json();if(u.success)return h=u.templates,E=u.categories,!0;if(g.status===403)return N=!1,!1}catch(g){console.warn("Failed to fetch recipe templates:",g.message)}return!1}async function b(){try{N=(await(await fetch("/api/v1/license/feature/recipes")).json()).available}catch{N=!1}return N}window.renderRecipeCards=async function(g){await b();let u;if(N&&h?u=h:u=M(),!u||u.length===0)return;const f=document.createElement("div");f.className="app-category-header",f.innerHTML="\u{1F9EA} Recipes",f.style.borderBottomColor="#8e44ad",g.appendChild(f);const m=Array.isArray(u)?u:Object.values(u);m.sort((p,d)=>(d.popularity||0)-(p.popularity||0));for(const p of m){const d=document.createElement("div");d.className="app-option",d.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;">${p.componentCount||p.components?.length||"?"} apps</div>`,i=N?"":'<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>';d.innerHTML=`
        ${i}
        <div class="app-option-icon">${escapeHtml(p.icon||"\u{1F9EA}")}</div>
        <div class="app-option-name">${escapeHtml(p.name)}</div>
        <div class="app-option-desc">${escapeHtml(p.description||"")}</div>
        ${c}
      `,d.onclick=()=>{if(!N){showNotification("Recipes require a DashCaddy Premium license. Click the License button to activate.","warning",5e3),window.openLicenseModal&&window.openLicenseModal();return}k(p)},g.appendChild(d)}};function M(){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(g){P=g,w=1;const u=document.getElementById("app-selector-modal");u&&u.classList.remove("show"),document.getElementById("recipe-deploy-title").textContent=`Deploy ${g.name}`,B(),S(),O.classList.add("show")}function B(){document.querySelectorAll("#recipe-steps .recipe-step").forEach(g=>{const u=parseInt(g.dataset.step);g.classList.toggle("active",u===w),g.classList.toggle("completed",u<w)});for(let g=1;g<=4;g++){const u=document.getElementById(`recipe-step-${g}`);u&&(u.style.display=g===w?"":"none")}A.style.display=w>1&&w<4?"":"none",w===4?(v.style.display="none",z.textContent="Close"):w===3?(v.textContent="\u{1F680} Deploy",v.style.display="",z.textContent="Cancel"):(v.textContent="Next",v.style.display="",z.textContent="Cancel")}function S(){const g=document.getElementById("recipe-component-list");g.innerHTML="";const u=P.components||[];for(const f of u){const m=document.createElement("div");m.style.cssText="display: flex; align-items: center; gap: 12px; padding: 12px; border-radius: 8px; background: var(--card-bg); border: 1px solid var(--border);";const p=f.required,d=f.internal;m.innerHTML=`
        <input type="checkbox" ${p?"checked disabled":"checked"} data-component-id="${f.id}"
          style="width: 18px; height: 18px; accent-color: var(--accent);" />
        <div style="flex: 1;">
          <div style="font-weight: 600; font-size: 0.9rem;">${escapeHtml(f.role||f.id)}</div>
          <div style="font-size: 0.78rem; color: var(--muted);">
            ${f.templateRef?escapeHtml(f.templateRef):"Built-in"}
            ${p?'<span style="color: var(--accent); margin-left: 6px;">Required</span>':'<span style="color: var(--muted); margin-left: 6px;">Optional</span>'}
            ${d?'<span style="color: var(--muted); margin-left: 6px;">(Internal)</span>':""}
          </div>
          ${f.note?`<div style="font-size: 0.75rem; color: var(--warn-fg); margin-top: 4px;">\u26A0 ${escapeHtml(f.note)}</div>`:""}
        </div>
      `,g.appendChild(m)}}function T(){const g=document.getElementById("recipe-volumes-section"),u=document.getElementById("recipe-volume-list"),f=P.sharedVolumes;if(f&&Object.keys(f).length>0){g.style.display="",u.innerHTML="";for(const[m,p]of Object.entries(f)){const d=document.createElement("div");d.style.cssText="display: grid; gap: 4px;",d.innerHTML=`
          <label style="font-weight: 500; font-size: 0.85rem;">${escapeHtml(p.label||m)}</label>
          <input type="text" data-volume-key="${m}" value="${escapeHtml(p.defaultPath||"")}"
            placeholder="${escapeHtml(p.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(p.description||"")}</div>
        `,u.appendChild(d)}}else g.style.display="none"}function j(){const g=document.getElementById("recipe-review-content"),u=H(),f=document.querySelectorAll("#recipe-volume-list input[data-volume-key]"),m={};f.forEach(i=>{m[i.dataset.volumeKey]=i.value});const p=document.getElementById("recipe-timezone").value||"UTC",d=document.getElementById("recipe-ip").value||"host.docker.internal",c=document.getElementById("recipe-tailscale").checked;g.innerHTML=`
      <div style="font-weight: 600; font-size: 1rem; margin-bottom: 12px;">${escapeHtml(P.name)}</div>
      <div style="color: var(--muted); margin-bottom: 16px;">${escapeHtml(P.description||"")}</div>

      <div style="margin-bottom: 12px;">
        <strong>Components (${u.length}):</strong>
        <div style="display: grid; gap: 4px; margin-top: 6px;">
          ${u.map(i=>`<div style="padding: 4px 0; font-size: 0.85rem;">
            \u2022 <strong>${escapeHtml(i.role||i.id)}</strong> ${i.internal?'<span style="color:var(--muted)">(internal)</span>':""}
          </div>`).join("")}
        </div>
      </div>

      ${Object.keys(m).length>0?`<div style="margin-bottom: 12px;">
        <strong>Volumes:</strong>
        ${Object.entries(m).map(([i,$])=>`<div style="font-size: 0.85rem; font-family: monospace; color: var(--muted);">${i}: ${escapeHtml($)}</div>`).join("")}
      </div>`:""}

      <div style="font-size: 0.85rem; color: var(--muted);">
        Timezone: ${escapeHtml(p)} &bull; IP: ${escapeHtml(d)} ${c?"&bull; Tailscale only":""}
      </div>

      ${P.network?`<div style="font-size: 0.85rem; color: var(--muted); margin-top: 4px;">Docker network: <code>${escapeHtml(P.network.name)}</code></div>`:""}
    `}function H(){const g=document.querySelectorAll("#recipe-component-list input[data-component-id]"),u=new Set;g.forEach(m=>{m.checked&&u.add(m.dataset.componentId)});const f=P.components||[];return f.filter(m=>m.required).forEach(m=>u.add(m.id)),f.filter(m=>u.has(m.id))}async function R(){const g=document.getElementById("recipe-progress-list"),u=document.getElementById("recipe-deploy-result");u.style.display="none",g.innerHTML="";const f=H();for(const c of f){const i=document.createElement("div");i.id=`recipe-progress-${c.id}`,i.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;",i.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>
      `,g.appendChild(i)}const m=document.querySelectorAll("#recipe-volume-list input[data-volume-key]"),p={};m.forEach(c=>{p[c.dataset.volumeKey]=c.value});const d={selectedComponents:f.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:p},componentOverrides:{}};for(const c of f)x(c.id,"deploying","Deploying...");try{const i=await(await secureFetch("/api/v1/recipes/deploy",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({recipeId:P.id,config:d})})).json();if(i.success){for(const $ of i.deployed||[])x($.id,"success",$.url?`Running \u2192 ${$.url}`:"Running");for(const $ of i.errors||[])x($.componentId,"error",$.error);u.style.display="",u.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(i.message||"Deployed!")}</div>
            ${i.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;">${i.setupInstructions.map($=>`<li>${escapeHtml($)}</li>`).join("")}</ul>
            </div>`:""}
          </div>
        `,showNotification(`${P.name} recipe deployed successfully!`,"success",5e3),window.loadServices&&window.loadServices()}else u.style.display="",u.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(i.error||"Unknown error")}
        </div>`,showNotification(`Recipe deployment failed: ${i.error}`,"error",5e3)}catch(c){u.style.display="",u.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 x(g,u,f){const m=document.getElementById(`recipe-progress-${g}`);if(!m)return;const p=m.querySelector(".recipe-progress-icon"),d=m.querySelector(".recipe-progress-status");u==="deploying"?(p.textContent="\u23F3",d.style.color="var(--accent)"):u==="success"?(p.textContent="\u2705",d.style.color="var(--ok-fg)"):u==="error"&&(p.textContent="\u274C",d.style.color="var(--bad-fg)"),d.textContent=f}v.addEventListener("click",()=>{if(w===3){w=4,B(),R();return}w<3&&(w++,B(),w===2&&T(),w===3&&j())}),A.addEventListener("click",()=>{w>1&&w<4&&(w--,B())}),window.groupRecipeCards=function(){const g=document.querySelectorAll(".service-card[data-recipe-id]");if(g.length===0)return;const u={};g.forEach(f=>{const m=f.dataset.recipeId;u[m]||(u[m]=[]),u[m].push(f)});for(const[f,m]of Object.entries(u))m.length<2||m.forEach((p,d)=>{if(p.style.borderLeft="3px solid rgba(142,68,173,0.5)",d===0){let c=p.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=f.replace(/-/g," "),p.style.position="relative",p.appendChild(c))}})},window.manageRecipe=async function(g,u){const f=`/api/v1/recipes/${g}/${u}`,m=u==="remove"?"DELETE":"POST",p=u==="remove"?`/api/v1/recipes/${g}`:f;if(!(u==="remove"&&!confirm(`Remove the entire ${g} recipe? This will delete all containers and configuration.`)))try{const c=await(await secureFetch(p,{method:m})).json();c.success?(showNotification(`Recipe ${u}: ${c.results?.filter(i=>i.status!=="failed").length||0} components processed`,"success",4e3),window.loadServices&&window.loadServices()):showNotification(`Recipe ${u} failed: ${c.error}`,"error",5e3)}catch(d){showNotification(`Network error: ${d.message}`,"error",5e3)}};const D=document.createElement("style");D.textContent=`
    .recipe-step {
      flex: 1;
      text-align: center;
      padding: 8px 4px;
      font-size: 0.78rem;
      color: var(--muted);
      border-bottom: 2px solid var(--border);
      transition: all 0.2s;
    }
    .recipe-step span {
      display: inline-flex;
      align-items: center;
      justify-content: center;
      width: 20px;
      height: 20px;
      border-radius: 50%;
      background: var(--border);
      color: var(--muted);
      font-size: 0.7rem;
      font-weight: 700;
      margin-right: 4px;
    }
    .recipe-step.active {
      color: var(--accent);
      border-bottom-color: var(--accent);
    }
    .recipe-step.active span {
      background: var(--accent);
      color: #fff;
    }
    .recipe-step.completed {
      color: var(--ok-fg);
      border-bottom-color: var(--ok-fg);
    }
    .recipe-step.completed span {
      background: var(--ok-fg);
      color: #fff;
    }
    .recipe-step-panel {
      min-height: 180px;
    }
  `,document.head.appendChild(D),b()})(),(function(){document.getElementById("reload-caddy-top")?.addEventListener("click",async()=>{const h=document.getElementById("reload-caddy-top"),E=h.textContent;try{h.textContent="\u23F3 Reloading...",h.disabled=!0;const P=await secureFetch("/api/v1/caddy/reload",{method:"POST",headers:{"Content-Type":"application/json"}}),w=await P.json();if(P.ok&&w.success)h.textContent="\u2705 Reloaded!",setTimeout(()=>{h.textContent=E,h.disabled=!1},2e3);else throw new Error(w.error||"Reload failed")}catch(P){h.textContent="\u274C Failed",showNotification(`Failed to reload Caddy: ${P.message}`,"error"),setTimeout(()=>{h.textContent=E,h.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 h=document.getElementById("error-log-modal"),E=document.getElementById("error-log-content"),P=document.getElementById("view-error-logs"),w=document.getElementById("error-log-refresh"),N=document.getElementById("error-log-clear"),O=document.getElementById("error-log-close");async function z(){E.innerHTML='<div class="logs-loading">Loading error logs...</div>';try{const L=await(await fetch("/api/v1/error-logs")).json();L.success&&L.logs?L.logs.length===0?E.innerHTML='<div style="padding: 20px; text-align: center; color: var(--muted);">\u2705 No errors logged! Everything is working smoothly.</div>':E.innerHTML=L.logs.map(b=>`
              <div class="log-entry error">
                <span class="log-timestamp">${new Date(b.timestamp).toLocaleString()}</span>
                <span class="log-level">ERROR</span>
                <div class="log-message">
                  <strong>${escapeHtml(b.context)}</strong>: ${escapeHtml(b.error)}
                  ${b.details?`<br><small style="opacity: 0.7;">${escapeHtml(b.details)}</small>`:""}
                </div>
              </div>
            `).join(""):E.innerHTML='<div style="padding: 20px; color: var(--bad-fg);">\u274C Failed to load error logs</div>'}catch(v){E.innerHTML=`<div style="padding: 20px; color: var(--bad-fg);">\u274C Error loading logs: ${escapeHtml(v.message)}</div>`}}async function A(){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)}}P?.addEventListener("click",()=>{h.classList.add("show"),z()}),w?.addEventListener("click",z),N?.addEventListener("click",A),wireModal(h,O)})(),(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>
          <h3 style="margin: 0;">\u{1F4DC} Container Logs</h3>
          <p class="modal-subtitle" style="margin: 4px 0 0 0; font-size: 0.85rem; opacity: 0.7;">View and stream Docker container logs</p>
        </div>
        <div class="logs-controls" style="display: flex; gap: 8px; align-items: center;">
          <select id="cl-container-select" style="padding: 6px 10px; border: 1px solid var(--border); border-radius: 6px; background: var(--bg); color: var(--fg); min-width: 200px;">
            <option value="">Select a container...</option>
          </select>
          <input type="text" id="cl-log-search" placeholder="Search logs..." style="padding: 6px 10px; border: 1px solid var(--border); border-radius: 6px; background: var(--bg); color: var(--fg); width: 150px;" />
          <select id="cl-log-tail" style="padding: 6px 10px; border: 1px solid var(--border); border-radius: 6px; background: var(--bg); color: var(--fg);">
            <option value="50">Last 50 lines</option>
            <option value="100" selected>Last 100 lines</option>
            <option value="500">Last 500 lines</option>
            <option value="1000">Last 1000 lines</option>
            <option value="all">All logs</option>
          </select>
          <button id="cl-refresh" class="btn-accent-solid" style="padding: 6px 14px; font-size: 0.85rem;">\u{1F504} Refresh</button>
          <button id="cl-stream" class="btn-accent-solid" style="padding: 6px 14px; font-size: 0.85rem;">\u25B6 Stream</button>
          <button id="cl-download" style="padding: 6px 14px; font-size: 0.85rem;">\u{1F4BE} Download</button>
          <button id="cl-clear-search" style="padding: 6px 10px; font-size: 0.85rem;" title="Clear search">\u2715</button>
          <button id="cl-close" class="close-btn" style="padding: 6px 10px;">\u2715</button>
        </div>
      </div>
      
      <div id="cl-container-info" style="display: flex; gap: 16px; margin-bottom: 12px; padding: 8px 12px; background: var(--bg-secondary, var(--bg)); border-radius: 6px; font-size: 0.82rem;">
        <span><strong>Image:</strong> <span id="cl-image">-</span></span>
        <span><strong>Status:</strong> <span id="cl-status">-</span></span>
        <span><strong>Created:</strong> <span id="cl-created">-</span></span>
      </div>
      
      <div id="cl-log-content" class="logs-content scroll-container" style="flex: 1; min-height: 0; background: #1a1a1a; border-radius: 6px; padding: 12px; font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace; font-size: 0.78rem; overflow: auto;">
        <div class="logs-loading" style="color: var(--muted); text-align: center; padding: 40px;">Select a container to view logs</div>
      </div>
      
      <div id="cl-stream-status" style="display: none; padding: 8px 12px; background: var(--ok-bg, #1a3a1a); color: var(--ok-fg, #4ade80); border-radius: 6px; margin-top: 8px; font-size: 0.82rem;">
        <span id="cl-stream-indicator">\u{1F534}</span> <span id="cl-stream-text">Disconnected</span>
      </div>
      
      <div class="weather-modal-buttons modal-footer-bar" style="margin-top: 12px; padding-top: 12px; border-top: 1px solid var(--border);">
        <div style="display: flex; gap: 8px; font-size: 0.78rem; color: var(--muted);">
          <span id="cl-line-count">0 lines</span>
          <span>|</span>
          <span id="cl-filter-count">0 filtered</span>
        </div>
        <button id="cl-close-btn" class="btn-secondary">Close</button>
      </div>
    </div>
  </div>`);const h=document.getElementById("container-logs-modal"),E=document.getElementById("cl-container-select"),P=document.getElementById("cl-log-content"),w=document.getElementById("cl-log-search"),N=document.getElementById("cl-log-tail"),O=document.getElementById("cl-refresh"),z=document.getElementById("cl-stream"),A=document.getElementById("cl-download"),v=document.getElementById("cl-clear-search"),L=document.getElementById("cl-close"),b=document.getElementById("cl-close-btn"),M=document.getElementById("cl-stream-status"),k=document.getElementById("cl-stream-indicator"),B=document.getElementById("cl-stream-text"),S=document.getElementById("cl-line-count"),T=document.getElementById("cl-filter-count"),j=document.getElementById("cl-image"),H=document.getElementById("cl-status"),R=document.getElementById("cl-created");let x=null,D=[],g=[],u=null,f=!1,m=null;function p(s){if(!s)return"-";const l=new Date(s);return isNaN(l.getTime())?s:l.toLocaleString()}function d(s){if(!s)return"";const l=document.createElement("div");return l.textContent=s,l.innerHTML}function c(s,l){const C=s.stream==="stderr"?"log-stderr":"log-stdout",I=s.stream==="stderr"?"\u26A0\uFE0F":"\u{1F4E4}";return`
      <div class="log-entry ${C}" 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"};">${I}</span>
        <span class="log-text" style="flex: 1; white-space: pre-wrap; word-break: break-all; color: #e5e5e5;">${d(s.text)}</span>
      </div>
    `}function i(s,l=""){if(!s||s.length===0){P.innerHTML='<div class="logs-loading" style="color: var(--muted); text-align: center; padding: 40px;">No logs available</div>',S.textContent="0 lines",T.textContent="0 filtered";return}if(D=s,g=l?s.filter(C=>C.text&&C.text.toLowerCase().includes(l.toLowerCase())):s,S.textContent=`${s.length} lines`,T.textContent=l?`${g.length} of ${s.length} shown`:`${s.length} shown`,g.length===0){P.innerHTML=`<div class="logs-loading" style="color: var(--muted); text-align: center; padding: 40px;">No logs match "${d(l)}"</div>`;return}P.innerHTML=g.map((C,I)=>c(C,I)).join(""),P.scrollTop=P.scrollHeight}async function $(){try{const l=(await getJSON("/api/v1/logs/containers")).containers||[],C=E.value;E.innerHTML='<option value="">Select a container...</option>',l.forEach(I=>{const F=document.createElement("option");F.value=I.id,F.textContent=`${I.name} (${I.image.split(":")[0]}) - ${I.status}`,F.dataset.name=I.name,F.dataset.image=I.image,F.dataset.status=I.status,F.dataset.created=I.created,E.appendChild(F)}),C&&E.querySelector(`option[value="${C}"]`)&&(E.value=C,y(C))}catch(s){console.error("Failed to load containers:",s)}}function y(s){const l=E.querySelector(`option[value="${s}"]`);l&&(j.textContent=l.dataset.image||"-",H.textContent=l.dataset.status||"-",H.style.color=l.dataset.status==="running"?"var(--ok-fg, #4ade80)":"var(--bad-fg, #ef4444)",R.textContent=p(l.dataset.created))}async function n(){const s=E.value;if(!s){P.innerHTML='<div class="logs-loading" style="color: var(--muted); text-align: center; padding: 40px;">Select a container to view logs</div>';return}o(),x=s,y(s);const l=N.value,C=w.value.trim();P.innerHTML='<div class="logs-loading" style="color: var(--muted); text-align: center; padding: 40px;">Loading logs...</div>';try{const I=`/api/v1/logs/container/${s}${l!=="all"?`?tail=${l}`:""}`,F=await getJSON(I);F.logs&&F.logs.length>0?i(F.logs,C):(P.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",T.textContent="0 filtered")}catch(I){P.innerHTML=`<div class="logs-loading" style="color: var(--bad-fg, #ef4444); text-align: center; padding: 40px;">Error loading logs: ${d(I.message)}</div>`}}function e(){const s=E.value;if(!s)return;o(),f=!0,z.textContent="\u23F9 Stop",M.style.display="flex",k.textContent="\u{1F7E2}",B.textContent="Connecting...";const l=`/api/v1/logs/stream/${s}`;u=new EventSource(l),u.onopen=()=>{k.textContent="\u{1F7E2}",B.textContent="Connected - streaming logs"},u.onmessage=C=>{try{const I=JSON.parse(C.data);if(I.error){k.textContent="\u{1F534}",B.textContent=`Error: ${I.error}`;return}D.push(I),g.push(I),S.textContent=`${D.length} lines`,T.textContent=`${g.length} shown`;const F=w.value.trim();if(!F||I.text&&I.text.toLowerCase().includes(F.toLowerCase())){const q=document.createElement("div");q.innerHTML=c(I,g.length-1);const U=q.firstElementChild;U.style.background="#1a3a1a",P.appendChild(U),P.scrollTop=P.scrollHeight}}catch(I){console.error("Error parsing log:",I)}},u.onerror=()=>{k.textContent="\u{1F534}",B.textContent="Disconnected",f=!1,z.textContent="\u25B6 Stream"},h._eventSource=u}function o(){u&&(u.close(),u=null),h._eventSource&&(h._eventSource.close(),h._eventSource=null),f=!1,z.textContent="\u25B6 Stream",M.style.display="none"}function a(){if(!D||D.length===0){showNotification("No logs to download","error");return}const s=E.querySelector(`option[value="${x}"]`)?.dataset.name||x,l=new Date().toISOString().replace(/[:.]/g,"-"),C=`${s}-logs-${l}.txt`,I=D.map(G=>{const J=G.timestamp||"",X=G.stream==="stderr"?"[ERR]":"[OUT]";return`${J?J+" ":""}${X} ${G.text}`}).join(`
`),F=new Blob([I],{type:"text/plain"}),q=URL.createObjectURL(F),U=document.createElement("a");U.href=q,U.download=C,document.body.appendChild(U),U.click(),document.body.removeChild(U),URL.revokeObjectURL(q),showNotification(`Downloaded ${D.length} log lines`,"success")}E?.addEventListener("change",()=>{n()}),N?.addEventListener("change",()=>{n()}),O?.addEventListener("click",()=>{n()}),z?.addEventListener("click",()=>{f?o():e()}),A?.addEventListener("click",()=>{a()}),v?.addEventListener("click",()=>{w.value="",i(D,"")}),w?.addEventListener("input",()=>{clearTimeout(m),m=setTimeout(()=>{i(D,w.value.trim())},300)}),w?.addEventListener("keydown",s=>{s.key==="Escape"&&(w.value="",i(D,""))}),document.getElementById("view-container-logs")?.addEventListener("click",()=>{h.classList.add("show"),$()});function t(){o(),h.classList.remove("show")}L?.addEventListener("click",t),b?.addEventListener("click",t),document.addEventListener("keydown",s=>{s.key==="Escape"&&h.classList.contains("show")&&t()}),h.addEventListener("click",s=>{s.target===h&&t()}),window.openContainerLogsModal=function(s,l){h.classList.add("show"),$().then(()=>{const C=Array.from(E.options).find(I=>I.value===s||I.dataset.name===l);C?(E.value=C.value,y(C.value),n()):s?(x=s,j.textContent=l||s,H.textContent="-",R.textContent="-",n()):P.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">
        Create and manage Docker container checkpoints for instant state recovery.
      </p>

      <div id="snapshot-container-select-wrapper" style="margin-bottom: 16px;">
        <label style="font-size: 0.85rem; color: var(--muted);">Select Container:</label>
        <select id="snapshot-container-select" style="width: 100%; padding: 8px 12px; margin-top: 4px; background: var(--bg); border: 1px solid var(--border); border-radius: 6px; color: var(--fg); font-size: 0.9rem;">
          <option value="">-- Select a container --</option>
        </select>
      </div>

      <div id="snapshot-details" style="display: none; margin-bottom: 16px; padding: 12px; border: 1px solid var(--border); border-radius: 8px; background: var(--card-hover);">
        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 8px; font-size: 0.85rem;">
          <div><span style="color: var(--muted);">Image:</span> <span id="snapshot-image"></span></div>
          <div><span style="color: var(--muted);">Status:</span> <span id="snapshot-status"></span></div>
          <div><span style="color: var(--muted);">Created:</span> <span id="snapshot-created"></span></div>
          <div><span style="color: var(--muted);">Container ID:</span> <span id="snapshot-id" style="font-family: monospace;"></span></div>
        </div>
      </div>

      <div class="panel-tabs" style="margin-bottom: 12px;">
        <button class="panel-tab active" data-panel="snapshot-create">Create Snapshot</button>
        <button class="panel-tab" data-panel="snapshot-list">Manage Snapshots</button>
      </div>

      <div id="snapshot-create" class="panel-section active">
        <div style="margin-bottom: 12px;">
          <label style="font-size: 0.85rem; color: var(--muted);">Snapshot Name:</label>
          <input type="text" id="snapshot-name" placeholder="e.g., before-update-2024" 
            style="width: 100%; padding: 8px 12px; margin-top: 4px; background: var(--bg); border: 1px solid var(--border); border-radius: 6px; color: var(--fg); font-size: 0.9rem; box-sizing: border-box;" />
        </div>
        <div style="margin-bottom: 12px;">
          <label class="checkbox-label" style="font-size: 0.85rem;">
            <input type="checkbox" id="snapshot-leave-running" checked />
            Leave container running after checkpoint (resume without restart)
          </label>
        </div>
        <button id="snapshot-create-btn" class="btn-accent-solid" style="width: 100%;">\u{1F4BE} Create Snapshot</button>
        <div id="snapshot-create-status" style="margin-top: 12px; text-align: center; font-size: 0.85rem;"></div>
      </div>

      <div id="snapshot-list" class="panel-section" style="display: none;">
        <div id="snapshot-list-container" class="scroll-container" style="max-height: 300px;">
          <div class="panel-empty"><span class="empty-icon">\u{1F4BE}</span>Select a container to view its snapshots</div>
        </div>
      </div>

      <div class="weather-modal-buttons modal-footer-bar">
        <button id="snapshot-close">Close</button>
      </div>
    </div>
  </div>`);const h=document.getElementById("snapshot-modal"),E=document.getElementById("snapshot-btn"),P=document.getElementById("snapshot-close"),w=document.getElementById("snapshot-container-select"),N=document.getElementById("snapshot-details"),O=document.getElementById("snapshot-create-btn"),z=document.getElementById("snapshot-create-status");let A=null;async function v(){try{const S=await(await fetch("/api/v1/containers")).json();if(!S.success||!S.containers)return;w.innerHTML='<option value="">-- Select a container --</option>';for(const T of S.containers){const j=document.createElement("option");j.value=T.id,j.textContent=`${T.name||T.id} (${T.image||"unknown"})`,j.dataset.name=T.name,j.dataset.image=T.image,j.dataset.status=T.status,j.dataset.created=T.created,w.appendChild(j)}}catch(B){console.error("Failed to load containers:",B)}}function L(B){if(!B||!B.value){N.style.display="none",A=null;return}A=B.value,document.getElementById("snapshot-image").textContent=B.dataset.image||"-",document.getElementById("snapshot-status").textContent=B.dataset.status||"-",document.getElementById("snapshot-created").textContent=B.dataset.created?new Date(B.dataset.created*1e3).toLocaleString():"-",document.getElementById("snapshot-id").textContent=B.value.substring(0,12),N.style.display=""}async function b(){if(!A){z.textContent="Please select a container first",z.style.color="var(--bad-fg)";return}const B=document.getElementById("snapshot-name").value.trim();if(!B){z.textContent="Please enter a snapshot name",z.style.color="var(--bad-fg)";return}const S=document.getElementById("snapshot-leave-running").checked;O.disabled=!0,O.textContent="Creating...",z.textContent="";try{const j=await(await fetch(`/api/v1/containers/${encodeURIComponent(A)}/checkpoint`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:B,leaveRunning:S})})).json();j.success?(z.textContent=`\u2713 Snapshot "${B}" 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(T){z.textContent=`\u2717 Error: ${T.message}`,z.style.color="var(--bad-fg)"}finally{O.disabled=!1,O.textContent="\u{1F4BE} Create Snapshot"}}function M(){h.classList.add("show"),v()}function k(){h.classList.remove("show"),N.style.display="none",A=null,w.selectedIndex=0}E?.addEventListener("click",M),P?.addEventListener("click",k),wireModal(h,P),w?.addEventListener("change",B=>{const S=w.options[w.selectedIndex];L(S)}),O?.addEventListener("click",b),h?.querySelectorAll(".panel-tab").forEach(B=>{B.addEventListener("click",()=>{h.querySelectorAll(".panel-tab").forEach(S=>S.classList.remove("active")),h.querySelectorAll(".panel-section").forEach(S=>S.classList.remove("active")),B.classList.add("active"),h.querySelector(`#${B.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;">
        Auto-discover and connect your entire media stack.
      </p>

      <!-- Phase 1: Detection -->
      <div id="smart-phase-detect">
        <div style="text-align: center; padding: 20px;">
          <span class="brand-spinner" style="margin-bottom: 12px; display: inline-block;"></span>
          <div style="color: var(--muted); font-size: 0.9rem;">Scanning for services...</div>
        </div>
        <div id="smart-detect-results" style="display: none;"></div>
      </div>

      <!-- Phase 2: Credential Input (only for services needing keys) -->
      <div id="smart-phase-credentials" style="display: none;">
        <h4 class="heading-accent-section">Enter Missing API Keys</h4>
        <div id="smart-credential-inputs"></div>

        <!-- Connection Options -->
        <div style="margin-top: 16px; padding: 12px; background: var(--card-base); border-radius: 8px; border: 1px solid var(--border);">
          <h4 style="margin: 0 0 10px; font-size: 0.85rem; color: var(--accent);">Connection Options</h4>
          <label class="option-label">
            <input type="checkbox" id="smart-opt-seerr" checked class="checkbox-sm" />
            Configure Seerr with Radarr + Sonarr
          </label>
          <label class="option-label">
            <input type="checkbox" id="smart-opt-plex" checked class="checkbox-sm" />
            Connect Plex to Seerr
          </label>
          <label class="option-label">
            <input type="checkbox" id="smart-opt-prowlarr" checked class="checkbox-sm" />
            Connect Prowlarr to Radarr + Sonarr
          </label>
          <label style="display: flex; align-items: center; gap: 8px; cursor: pointer; font-size: 0.85rem;">
            <input type="checkbox" id="smart-opt-save" checked class="checkbox-sm" />
            Save API keys for one-click reconnect
          </label>
        </div>

        <button id="smart-connect-btn" style="width: 100%; margin-top: 16px; padding: 12px; background: linear-gradient(135deg, #e74c3c 0%, #9b59b6 100%); border: none; color: white; font-weight: 600; font-size: 1rem; border-radius: 8px; cursor: pointer;">
          Smart Connect
        </button>
      </div>

      <!-- Phase 3: Connection Progress -->
      <div id="smart-phase-progress" style="display: none;">
        <h4 class="heading-accent-section">Connecting Everything...</h4>
        <div id="smart-progress-steps" style="display: flex; flex-direction: column; gap: 6px;"></div>
      </div>

      <!-- Phase 4: Results -->
      <div id="smart-phase-results" style="display: none;">
        <div id="smart-results-content"></div>
        <div id="smart-plex-libraries" style="display: none; margin-top: 12px;"></div>
        <div style="display: flex; gap: 8px; margin-top: 16px;">
          <button id="smart-retry-btn" style="display: none; flex: 1; padding: 10px; background: #f39c12; border: none; color: white; font-weight: 500; border-radius: 8px; cursor: pointer;">
            Retry Failed Steps
          </button>
          <a id="smart-open-seerr" href="#" target="_blank" rel="noopener noreferrer"
             style="flex: 1; padding: 10px; background: var(--accent); color: white; border: none; border-radius: 8px; cursor: pointer; font-weight: 500; text-decoration: none; text-align: center;">
            Open Seerr
          </a>
        </div>
      </div>

      <!-- Help Text -->
      <div style="font-size: 0.75rem; color: var(--muted); margin-top: 12px; padding: 10px; background: color-mix(in srgb, var(--accent) 5%, transparent); border-radius: 6px;">
        <strong>Where to find API keys:</strong><br>
        Radarr/Sonarr/Prowlarr: Settings -> General -> Security -> API Key
      </div>

      <!-- Close Button -->
      <div class="weather-modal-buttons modal-footer-bar">
        <button id="arr-setup-cancel">Close</button>
      </div>
    </div>
  </div>`);const h=document.getElementById("arr-setup-modal"),E=document.getElementById("arr-setup-btn"),P=document.getElementById("arr-setup-cancel"),w=document.getElementById("smart-connect-btn"),N=document.getElementById("smart-phase-detect"),O=document.getElementById("smart-phase-credentials"),z=document.getElementById("smart-phase-progress"),A=document.getElementById("smart-phase-results"),v=document.getElementById("smart-detect-results"),L=document.getElementById("smart-credential-inputs"),b=document.getElementById("smart-progress-steps"),M=document.getElementById("smart-results-content"),k=document.getElementById("smart-plex-libraries"),B=document.getElementById("smart-retry-btn");let S=null;const T={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(m){N.style.display=m==="detect"?"block":"none",O.style.display=m==="credentials"?"block":"none",z.style.display=m==="progress"?"block":"none",A.style.display=m==="results"?"block":"none"}function R(m){const p={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"}},d=p[m]||p.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, ${d.bg} 20%, transparent); color: ${d.bg};">${d.icon} ${d.text}</span>`}async function x(){H("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 p='<div style="display: flex; flex-direction: column; gap: 8px;">';for(const[c,i]of Object.entries(S.services)){const $=T[c]||"\u{1F4E6}",y=j[c]||c,n=i.source?`<span style="font-size: 0.7rem; color: var(--muted); padding: 1px 6px; background: var(--card-bg); border-radius: 3px;">${escapeHtml(i.source)}</span>`:"",e=i.version?`<span style="font-size: 0.7rem; color: var(--muted);">v${escapeHtml(i.version)}</span>`:"",o=(i.hasApiKey||i.hasToken)&&i.status==="connected"?'<span style="font-size: 0.7rem; color: var(--ok-fg);">Key saved</span>':"";p+=`<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;">${$}</span>
          <div style="flex: 1;">
            <div style="font-weight: 500; font-size: 0.9rem;">${y}</div>
            <div style="display: flex; gap: 6px; align-items: center; flex-wrap: wrap;">
              ${n} ${e} ${o}
            </div>
          </div>
          ${R(i.status)}
        </div>`}p+="</div>";const d=S.summary;p+=`<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(d.fullyConnected))}/${escapeHtml(String(d.totalDetected+(5-d.totalDetected)))} services detected &middot;
        ${escapeHtml(String(d.fullyConnected))} connected${d.needsApiKey>0?` &middot; <strong>${escapeHtml(String(d.needsApiKey))} needs API key</strong>`:""}
      </div>`,v.innerHTML=p,v.style.display="block",D(S),setTimeout(()=>{H("credentials")},800)}catch(m){v.innerHTML=`<div style="padding: 12px; color: var(--bad-fg);">Error: ${escapeHtml(m.message)}</div>`,v.style.display="block"}}function D(m){let p="";const d=m.services,c=["radarr","sonarr","prowlarr"];for(const y of c){const n=d[y];if(!n||n.status==="not_found"&&!n.url)continue;const e=T[y],o=j[y],a=n.status==="connected";p+=`<div style="margin-bottom: 10px; padding: 12px; background: var(--card-base); border-radius: 8px; border: 1px solid ${a?"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;">${o}</span>
          <span id="smart-${y}-status" style="margin-left: auto; font-size: 0.75rem;">
            ${a?'<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(n.url||"")}" placeholder="https://seedbox.com/${y}/"
                   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="${a?"(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 i=d.plex;if(i){const y=i.status==="connected";p+=`<div style="padding: 10px 12px; background: var(--card-base); border-radius: 8px; border: 1px solid ${y?"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>
          ${R(i.status)}
          <span style="margin-left: auto; font-size: 0.75rem; color: var(--muted);">${escapeHtml(i.source||"")}</span>
        </div>
      </div>`}const $=d.seerr;if($){const y=$.status==="connected";let n="";if($.configuredServices){const e=$.configuredServices;n=`<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>`}p+=`<div style="padding: 10px 12px; background: var(--card-base); border-radius: 8px; border: 1px solid ${y?"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>
          ${R($.status)}
        </div>
        ${n}
      </div>`}L.innerHTML=p}window.smartTestConnection=async function(m){const p=document.getElementById(`smart-${m}-url`),d=document.getElementById(`smart-${m}-key`),c=document.getElementById(`smart-${m}-status`),i=p?.value.trim(),$=d?.value.trim();if(!i||!$){c.innerHTML='<span style="color: var(--bad-fg);">Enter URL and API key</span>';return}c.innerHTML='<span class="brand-spinner"></span>';try{const n=await(await secureFetch("/api/v1/arr/test-connection",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({service:m,url:i,apiKey:$})})).json();n.success?c.innerHTML=`<span style="color: var(--ok-fg);">&#10003; ${escapeHtml(n.appName||"Connected")} v${escapeHtml(n.version||"")}</span>`:c.innerHTML=`<span style="color: var(--bad-fg);">&#10007; ${escapeHtml(n.error)}</span>`}catch(y){c.innerHTML=`<span style="color: var(--bad-fg);">&#10007; ${escapeHtml(y.message)}</span>`}};async function g(){H("progress"),b.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 m={};for(const d of["radarr","sonarr","prowlarr"]){const c=document.getElementById(`smart-${d}-url`)?.value.trim(),i=document.getElementById(`smart-${d}-key`)?.value.trim();i&&c?m[d]={apiKey:i,url:c}:i&&(m[d]={apiKey:i})}const p={services:Object.keys(m).length>0?m: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(p)})).json();let i="";for(const $ of c.steps||[]){const y=$.status==="success"?'<span style="color: var(--ok-fg);">&#10003;</span>':'<span style="color: var(--bad-fg);">&#10007;</span>',n=$.status==="success"?"var(--muted)":"var(--bad-fg)";i+=`<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($.step)}</span>
          <span style="margin-left: auto; font-size: 0.75rem; color: ${n};">${escapeHtml($.details||"")}</span>
        </div>`}b.innerHTML=i,setTimeout(()=>u(c),500)}catch(d){b.innerHTML=`<div style="padding: 12px; color: var(--bad-fg);">Connection error: ${escapeHtml(d.message)}</div>`}}function u(m){H("results");const p=m.summary||{},d=p.failed===0&&p.succeeded>0,c=d?"var(--ok-fg)":"#f39c12",i=d?"&#10003;":"&#9888;",$=d?"All Connected!":`${escapeHtml(String(p.succeeded))}/${escapeHtml(String(p.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};">${i}</div>
      <div style="font-size: 1.1rem; font-weight: 600; color: ${c};">${$}</div>
      <div style="font-size: 0.85rem; color: var(--muted); margin-top: 4px;">${escapeHtml(String(p.succeeded))} succeeded, ${escapeHtml(String(p.failed))} failed</div>
    </div>`;y+='<div style="display: flex; flex-direction: column; gap: 4px;">';for(const n of m.steps||[]){const e=n.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;">
        ${e} ${escapeHtml(n.step)} <span style="margin-left: auto; color: var(--muted); font-size: 0.75rem;">${escapeHtml(n.details||"")}</span>
      </div>`}y+="</div>",M.innerHTML=y,B.style.display=p.failed>0?"block":"none",m.steps?.some(n=>n.step.includes("Plex")&&n.status==="success")&&f()}async function f(){try{const p=await(await fetch("/api/v1/plex/libraries")).json();if(p.success&&p.libraries?.length>0){let d=`<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(p.serverName)} Libraries</h4>
          <div style="display: flex; flex-wrap: wrap; gap: 8px;">`;for(const c of p.libraries){const i=c.type==="movie"?"\u{1F3AC}":c.type==="show"?"\u{1F4FA}":"\u{1F3B5}";d+=`<div style="padding: 8px 12px; background: var(--card-bg); border-radius: 6px; font-size: 0.85rem;">
            ${i} <strong>${escapeHtml(c.title)}</strong>
            <span style="color: var(--muted); font-size: 0.75rem;">${escapeHtml(String(c.count))} items</span>
          </div>`}d+="</div></div>",k.innerHTML=d,k.style.display="block"}}catch{}}E?.addEventListener("click",()=>{h.classList.add("show"),k.style.display="none",x()}),wireModal(h,P),w?.addEventListener("click",g),B?.addEventListener("click",g)})(),(function(){const h=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>

      <!-- Master Toggle -->
      <div class="accent-info-box">
        <label style="display: flex; align-items: center; gap: 10px; cursor: pointer;">
          <input type="checkbox" id="notifications-enabled" />
          <div>
            <span style="font-weight: 600; color: var(--accent);">Enable Notifications</span>
            <div class="text-tiny-muted">Receive alerts when containers go up/down</div>
          </div>
        </label>
      </div>

      <!-- Providers Section -->
      <h4 class="section-heading">Notification Providers</h4>

      <!-- Discord -->
      <div class="notification-provider provider-card">
        <div class="provider-header">
          <label class="checkbox-label">
            <input type="checkbox" id="discord-enabled" />
            <span class="fw-500">Discord</span>
          </label>
          <button id="discord-test" class="test-btn btn-xs">Test</button>
        </div>
        <div id="discord-config" style="display: none;">
          <label class="field-label-sm">Webhook URL:</label>
          <input type="text" id="discord-webhook" placeholder="https://discord.com/api/v1/webhooks/..." style="width: 100%;" />
        </div>
      </div>

      <!-- Telegram -->
      <div class="notification-provider provider-card">
        <div class="provider-header">
          <label class="checkbox-label">
            <input type="checkbox" id="telegram-enabled" />
            <span class="fw-500">Telegram</span>
          </label>
          <button id="telegram-test" class="test-btn btn-xs">Test</button>
        </div>
        <div id="telegram-config" style="display: none;">
          <div class="grid-2col">
            <div>
              <label class="field-label-sm">Bot Token:</label>
              <input type="text" id="telegram-bot-token" placeholder="123456:ABC..." />
            </div>
            <div>
              <label class="field-label-sm">Chat ID:</label>
              <input type="text" id="telegram-chat-id" placeholder="-1001234567890" />
            </div>
          </div>
        </div>
      </div>

      <!-- ntfy.sh -->
      <div class="notification-provider provider-card">
        <div class="provider-header">
          <label class="checkbox-label">
            <input type="checkbox" id="ntfy-enabled" />
            <span class="fw-500">ntfy.sh</span>
          </label>
          <button id="ntfy-test" class="test-btn btn-xs">Test</button>
        </div>
        <div id="ntfy-config" style="display: none;">
          <div style="display: grid; grid-template-columns: 2fr 1fr; gap: 8px;">
            <div>
              <label class="field-label-sm">Server URL:</label>
              <input type="text" id="ntfy-server" placeholder="https://ntfy.sh" value="https://ntfy.sh" />
            </div>
            <div>
              <label class="field-label-sm">Topic:</label>
              <input type="text" id="ntfy-topic" placeholder="dashcaddy-alerts" />
            </div>
          </div>
        </div>
      </div>

      <!-- Email -->
      <div class="notification-provider provider-card">
        <div class="provider-header">
          <label class="checkbox-label">
            <input type="checkbox" id="email-enabled" />
            <span class="fw-500">Email (SMTP)</span>
          </label>
          <button id="email-test" class="test-btn btn-xs">Test</button>
        </div>
        <div id="email-config" style="display: none;">
          <div style="display: grid; grid-template-columns: 2fr 1fr; gap: 8px; margin-bottom: 8px;">
            <div>
              <label class="field-label-sm">SMTP Host:</label>
              <input type="text" id="email-host" placeholder="smtp.gmail.com" />
            </div>
            <div>
              <label class="field-label-sm">Port:</label>
              <input type="number" id="email-port" value="587" placeholder="587" />
            </div>
          </div>
          <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 8px; margin-bottom: 8px;">
            <div>
              <label class="field-label-sm">Username:</label>
              <input type="text" id="email-user" placeholder="user@gmail.com" />
            </div>
            <div>
              <label class="field-label-sm">Password:</label>
              <input type="password" id="email-pass" placeholder="app password" />
            </div>
          </div>
          <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 8px;">
            <div>
              <label class="field-label-sm">From:</label>
              <input type="text" id="email-from" placeholder="DashCaddy &lt;noreply@example.com&gt;" />
            </div>
            <div>
              <label class="field-label-sm">To:</label>
              <input type="text" id="email-to" placeholder="admin@example.com" />
            </div>
          </div>
          <label style="display: flex; align-items: center; gap: 6px; margin-top: 8px; font-size: 0.8rem;">
            <input type="checkbox" id="email-secure" /> Use TLS (port 465)
          </label>
        </div>
      </div>

      <!-- Health Check Settings -->
      <h4 class="section-heading">Health Monitoring</h4>
      <div style="padding: 12px; background: var(--card-base); border-radius: 8px; border: 1px solid var(--border);">
        <label style="display: flex; align-items: center; gap: 10px; cursor: pointer; margin-bottom: 10px;">
          <input type="checkbox" id="health-check-enabled" />
          <div>
            <span class="fw-500">Enable Health Monitoring</span>
            <div class="text-tiny-muted">Periodically check container status</div>
          </div>
        </label>
        <div id="health-check-config" style="display: flex; align-items: center; gap: 10px;">
          <label class="field-label-sm">Check interval:</label>
          <select id="health-check-interval" style="width: auto;">
            <option value="1">1 minute</option>
            <option value="5" selected>5 minutes</option>
            <option value="15">15 minutes</option>
            <option value="30">30 minutes</option>
            <option value="60">1 hour</option>
          </select>
          <button id="health-check-now" style="padding: 4px 10px; font-size: 0.75rem; margin-left: auto;">Check Now</button>
        </div>
        <div id="health-check-status" style="font-size: 0.75rem; color: var(--muted); margin-top: 8px;">
          Last check: Never
        </div>
      </div>

      <!-- Event Types -->
      <h4 class="section-heading">Events to Notify</h4>
      <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 6px; padding: 12px; background: var(--card-base); border-radius: 8px; border: 1px solid var(--border);">
        <label class="checkbox-label-sm">
          <input type="checkbox" id="event-container-down" checked /> Container Down
        </label>
        <label class="checkbox-label-sm">
          <input type="checkbox" id="event-container-up" checked /> Container Recovered
        </label>
        <label class="checkbox-label-sm">
          <input type="checkbox" id="event-deploy-success" checked /> Deployment Success
        </label>
        <label class="checkbox-label-sm">
          <input type="checkbox" id="event-deploy-failed" checked /> Deployment Failed
        </label>
        <label class="checkbox-label-sm" style="grid-column: 1 / -1;">
          <input type="checkbox" id="event-resource-alert" checked /> Resource Alerts
        </label>
      </div>

      <!-- History -->
      <h4 class="section-heading">Notification History</h4>
      <div id="notification-history" style="max-height: 150px; overflow-y: auto; padding: 8px; background: var(--card-base); border-radius: 8px; border: 1px solid var(--border); font-size: 0.8rem;">
        <div style="color: var(--muted); text-align: center; padding: 20px;">No notifications yet</div>
      </div>
      <div id="last-notification-sent" style="font-size: 0.75rem; color: var(--muted); text-align: center; margin-top: 6px;"></div>

      <!-- Buttons -->
      <div class="weather-modal-buttons modal-footer-bar">
        <button id="notifications-send-test" class="btn-secondary" style="margin-right: auto;">Send Test</button>
        <button id="notifications-cancel">Cancel</button>
        <button id="notifications-save" class="btn-accent">Save Settings</button>
      </div>
    </div>
  </div>`);const E=document.getElementById("notifications-modal"),P=document.getElementById("manage-notifications"),w=document.getElementById("notifications-save"),N=document.getElementById("notifications-cancel");["discord","telegram","ntfy","email"].forEach(k=>{const B=document.getElementById(`${k}-enabled`),S=document.getElementById(`${k}-config`);B?.addEventListener("change",()=>{S.style.display=B.checked?"block":"none"})});const O=document.getElementById("health-check-enabled"),z=document.getElementById("health-check-config");O?.addEventListener("change",()=>{z.style.opacity=O.checked?"1":"0.5"});async function A(){try{const B=await(await fetch("/api/v1/notifications/config")).json();if(B.success){const S=B.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){h.logError("[Notifications] Load Config",k,{function:"loadConfig"})}}async function v(){try{const B=await(await fetch("/api/v1/notifications/history?limit=10")).json(),S=document.getElementById("notification-history");B.success&&B.history?.length>0?S.innerHTML=B.history.map(T=>{const j=new Date(T.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)"}[T.type]||"var(--muted)"}">${T.type==="success"?"\u2713":T.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(T.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){h.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}},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),E.classList.remove("show")):showNotification(`Failed to save: ${S.error}`,"error",3e3)}catch(k){showNotification(`Error: ${k.message}`,"error",3e3)}}async function b(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(B){showNotification(`Error: ${B.message}`,"error",3e3)}}document.getElementById("discord-test")?.addEventListener("click",()=>b("discord")),document.getElementById("telegram-test")?.addEventListener("click",()=>b("telegram")),document.getElementById("ntfy-test")?.addEventListener("click",()=>b("ntfy")),document.getElementById("email-test")?.addEventListener("click",()=>b("email")),document.getElementById("health-check-now")?.addEventListener("click",async()=>{try{const B=await(await secureFetch("/api/v1/notifications/health-check",{method:"POST"})).json();B.success&&(document.getElementById("health-check-status").textContent=`Last check: ${new Date(B.lastCheck).toLocaleString()} (${B.containersMonitored} containers)`,showNotification("Health check completed","success",2e3))}catch(k){showNotification(`Error: ${k.message}`,"error",3e3)}}),P?.addEventListener("click",()=>{E.classList.add("show"),A(),v()}),w?.addEventListener("click",L),document.getElementById("notifications-send-test")?.addEventListener("click",async()=>{const k=document.getElementById("notifications-send-test"),B=k.textContent;k.textContent="Sending...",k.disabled=!0;try{const T=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();T.success?(showNotification("Test notification sent!","success",3e3),M()):showNotification(`Test failed: ${T.results?.map(j=>`${j.provider}: ${j.error||"ok"}`).join(", ")}`,"error",5e3)}catch(S){showNotification(`Error: ${S.message}`,"error",3e3)}finally{k.textContent=B,k.disabled=!1}});async function M(){try{const B=await(await fetch("/api/v1/notifications/status")).json();if(B.success&&B.lastSent){const S=document.getElementById("last-notification-sent");S&&(S.textContent=`Last sent: ${new Date(B.lastSent).toLocaleString()}`)}}catch{}}wireModal(E,N)})(),(function(){document.addEventListener("click",h=>{const E=h.target.closest(".panel-tab");if(!E)return;const P=E.dataset.panel;if(!P)return;const w=E.closest(".panel-tabs"),N=w.closest(".weather-modal-content");w.querySelectorAll(".panel-tab").forEach(z=>z.classList.remove("active")),E.classList.add("active"),N.querySelectorAll(".panel-section").forEach(z=>z.classList.remove("active"));const O=N.querySelector("#"+P);O&&O.classList.add("active")})})(),(function(){var h=["dashcaddy_site_config","dashcaddy_onboarding","dashcaddy-encryption-key","dashcaddy-setup","dashcaddy-config","theme","user-themes","custom-theme","custom-apps","custom-services","toolbar-sections","weather-location","weather-zip","weather-geo","weather-unit","clock-style","clock-chimes","clock-chime-volume"];function E(){for(var e={},o=0;o<h.length;o++){var a=h[o],r=safeGet(a);r!=null&&(e[a]=r)}try{for(var t=0;t<localStorage.length;t++){var s=localStorage.key(t);/^widget-.+-enabled$/.test(s)&&(e[s]=localStorage.getItem(s))}}catch{}return e}function P(e){if(!e||typeof e!="object")return 0;var o=0;for(var a in e)e.hasOwnProperty(a)&&(safeSet(a,e[a]),o++);return o}function w(e){return e.version&&!e.files&&e.services}function N(e){var o={};e.customServices&&(o["custom-services"]=JSON.stringify(e.customServices)),e.customApps&&(o["custom-apps"]=JSON.stringify(e.customApps)),e.weatherZip&&(o["weather-zip"]=e.weatherZip),e.theme&&(o.theme=e.theme),e.userThemes&&Object.keys(e.userThemes).length&&(o["user-themes"]=JSON.stringify(e.userThemes)),P(o),e.services&&Array.isArray(e.services)&&secureFetch("/api/v1/services",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(e.services)}).catch(function(){}),e.userThemes&&Object.keys(e.userThemes).forEach(function(a){var r=e.userThemes[a],t={};(window.THEME_PROPS||[]).forEach(function(s){r[s]&&(t[s]=r[s])}),secureFetch("/api/v1/themes/"+a,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:r.name||a,colors:t})}).catch(function(){})})}injectModal("backup-modal",`<div id="backup-modal" class="weather-modal">
    <div class="weather-modal-content" style="min-width: 550px; max-width: 650px;">
      <h3>\u{1F4BE} Backup & Restore</h3>
      <p class="modal-subtitle">
        Full backup of your entire DashCaddy setup \u2014 server config, credentials, themes, and browser preferences in one file.
      </p>

      <!-- Tab bar -->
      <div class="panel-tabs">
        <button class="panel-tab active" data-panel="backup-manual">Manual</button>
        <button class="panel-tab" data-panel="backup-schedules-tab">Schedules</button>
        <button class="panel-tab" data-panel="backup-disk-tab">Backups on Disk</button>
        <button class="panel-tab" data-panel="backup-pointintime-tab">Point-in-Time</button>
        <button class="panel-tab" data-panel="backup-history-tab">History</button>
      </div>

      <!-- Tab: Manual -->
      <div id="backup-manual" class="panel-section active">
        <!-- Export Section -->
        <div style="margin-bottom: 20px; padding: 16px; background: linear-gradient(135deg, color-mix(in srgb, #27ae60 15%, transparent), color-mix(in srgb, #2ecc71 10%, transparent)); border-radius: 10px; border: 1px solid #27ae60;">
          <h4 style="margin: 0 0 8px; color: #2ecc71; font-size: 0.95rem;">\u{1F4E4} Export Backup</h4>
          <p style="font-size: 0.8rem; color: var(--muted); margin: 0 0 12px;">
            Downloads everything \u2014 services, Caddyfile, credentials, encryption key, themes, and all browser preferences.
          </p>
          <button id="backup-export-btn" style="width: 100%; padding: 10px; background: linear-gradient(135deg, #27ae60 0%, #2ecc71 100%); border: none; color: white; font-weight: 600; border-radius: 8px; cursor: pointer;">
            \u2B07\uFE0F Download Full Backup
          </button>
        </div>

        <!-- Import Section -->
        <div style="padding: 16px; background: linear-gradient(135deg, color-mix(in srgb, #3498db 15%, transparent), color-mix(in srgb, #2980b9 10%, transparent)); border-radius: 10px; border: 1px solid #3498db;">
          <h4 style="margin: 0 0 8px; color: #3498db; font-size: 0.95rem;">\u{1F4E5} Restore Backup</h4>
          <p style="font-size: 0.8rem; color: var(--muted); margin: 0 0 12px;">
            Upload a backup file to restore your entire configuration \u2014 drag and drop ready.
          </p>
          <input type="file" id="backup-file-input" accept=".json" style="display: none;" />
          <button id="backup-select-file" style="width: 100%; padding: 10px; background: linear-gradient(135deg, #3498db 0%, #2980b9 100%); border: none; color: white; font-weight: 600; border-radius: 8px; cursor: pointer;">
            \u{1F4C1} Select Backup File
          </button>
          <div id="backup-file-name" style="display: none; margin-top: 8px; padding: 8px; background: var(--card-base); border-radius: 6px; font-size: 0.85rem;"></div>
        </div>

        <!-- Preview Section (shown after file selected) -->
        <div id="backup-preview" style="display: none; margin-top: 16px; padding: 16px; background: var(--card-base); border-radius: 10px; border: 1px solid var(--border);">
          <h4 style="margin: 0 0 12px; font-size: 0.9rem;">\u{1F4CB} Backup Contents</h4>
          <div id="backup-preview-content" style="font-size: 0.85rem;"></div>
          <div style="margin-top: 12px; padding-top: 12px; border-top: 1px solid var(--border);">
            <label class="checkbox-label" style="font-size: 0.85rem;">
              <input type="checkbox" id="backup-reload-caddy" checked />
              Reload Caddy after restore
            </label>
          </div>
          <button id="backup-do-restore-btn" style="width: 100%; margin-top: 12px; padding: 10px; background: linear-gradient(135deg, #e74c3c 0%, #c0392b 100%); border: none; color: white; font-weight: 600; border-radius: 8px; cursor: pointer;">
            \u26A1 Restore Everything
          </button>
        </div>

        <!-- Result Message -->
        <div id="backup-result" style="display: none; margin-top: 16px; padding: 12px; border-radius: 8px;"></div>
      </div>

      <!-- Tab: Schedules (Premium) -->
      <div id="backup-schedules-tab" class="panel-section">
        <div id="backup-schedules-container">
          <div class="panel-empty">
            <span class="empty-icon">\u23F0</span>
            <span class="brand-spinner"></span> Loading schedules...
          </div>
        </div>
      </div>

      <!-- Tab: Backups on Disk -->
      <div id="backup-disk-tab" class="panel-section">
        <div id="backup-disk-container">
          <div class="panel-empty">
            <span class="empty-icon">\u{1F4BE}</span>
            <span class="brand-spinner"></span> Loading backup files...
          </div>
        </div>
      </div>

      <!-- Tab: Point-in-Time Restore -->
      <div id="backup-pointintime-tab" class="panel-section">
        <div id="pointintime-container">
          <div class="panel-empty">
            <span class="empty-icon">\u23EA</span>
            <span class="brand-spinner"></span> Loading...
          </div>
        </div>
      </div>

      <!-- Tab: Backup History -->
      <div id="backup-history-tab" class="panel-section">
        <div id="backup-history-container" style="max-height: 400px; overflow-y: auto;">
          <div class="panel-empty">
            <span class="empty-icon">\u{1F4CB}</span>
            <span class="brand-spinner"></span> Loading backup history...
          </div>
        </div>
      </div>

      <!-- Close Button -->
      <div class="weather-modal-buttons modal-footer-bar">
        <button id="backup-cancel">Close</button>
      </div>
    </div>
  </div>`);var O=document.getElementById("backup-modal"),z=document.getElementById("backup-restore-btn"),A=document.getElementById("backup-cancel"),v=document.getElementById("backup-export-btn"),L=document.getElementById("backup-select-file"),b=document.getElementById("backup-file-input"),M=document.getElementById("backup-file-name"),k=document.getElementById("backup-preview"),B=document.getElementById("backup-preview-content"),S=document.getElementById("backup-do-restore-btn"),T=document.getElementById("backup-result"),j=document.getElementById("backup-schedules-container"),H=document.getElementById("backup-history-container"),R=document.getElementById("backup-disk-container"),x=document.getElementById("pointintime-container"),D=null;z?.addEventListener("click",function(){O.classList.add("show"),T&&(T.style.display="none"),k&&(k.style.display="none"),M&&(M.style.display="none"),D=null}),wireModal(O,A),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"),o=await e.json();o.browserState=E();var a=new Blob([JSON.stringify(o,null,2)],{type:"application/json"}),r=URL.createObjectURL(a),t=document.createElement("a");t.href=r,t.download="dashcaddy-backup-"+new Date().toISOString().split("T")[0]+".json",document.body.appendChild(t),t.click(),document.body.removeChild(t),URL.revokeObjectURL(r);var s=Object.keys(o.browserState).length,l=o.themes?Object.keys(o.themes).length:0;T.innerHTML="\u2705 Full backup downloaded \u2014 server config + "+s+" browser settings"+(l?" + "+l+" themes":""),T.style.display="block",T.style.background="color-mix(in srgb, var(--ok-fg) 15%, transparent)",T.style.border="1px solid var(--ok-fg)"}catch(C){T.innerHTML="\u274C Export failed: "+escapeHtml(C.message),T.style.display="block",T.style.background="color-mix(in srgb, var(--bad-fg) 15%, transparent)",T.style.border="1px solid var(--bad-fg)"}v.disabled=!1,v.innerHTML="\u2B07\uFE0F Download Full Backup"}),L?.addEventListener("click",function(){b.click()}),b?.addEventListener("change",async function(e){var o=e.target.files[0];if(o){M.textContent="\u{1F4C4} "+o.name,M.style.display="block",T.style.display="none";try{var a=await o.text(),r=JSON.parse(a);if(w(r)){D=r;var t='<div style="margin-bottom: 8px; color: var(--muted); font-size: 0.8rem;">Legacy format (v'+escapeHtml(r.version)+")</div>";t+='<div style="display: flex; flex-wrap: wrap; gap: 6px;">',r.services?.length&&(t+='<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&&(t+='<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&&(t+='<span style="padding: 4px 8px; background: var(--base); border-radius: 4px; font-size: 0.8rem;">\u{1F3A8} Theme: '+escapeHtml(r.theme)+"</span>"),r.userThemes&&(t+='<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>"),t+="</div>",B.innerHTML=t,k.style.display="block";return}var s=await secureFetch("/api/v1/backup/preview",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)}),l=await s.json();if(l.success){D=r;var t='<div style="margin-bottom: 8px; color: var(--muted); font-size: 0.8rem;">Exported: '+new Date(r.exportedAt).toLocaleString()+" (v"+escapeHtml(r.version)+")</div>";t+='<div style="margin-bottom: 6px; font-size: 0.75rem; color: var(--muted); text-transform: uppercase; letter-spacing: 0.5px;">Server Config</div>',t+='<div style="display: flex; flex-wrap: wrap; gap: 6px; margin-bottom: 10px;">';for(var C in l.preview.files){var I=l.preview.files[C],F=I.action==="create"?"\u{1F195}":"\u{1F4DD}";t+='<span style="padding: 4px 8px; background: var(--base); border-radius: 4px; font-size: 0.8rem;">'+F+" "+escapeHtml(I.description)+"</span>"}t+="</div>",l.preview.serviceCount&&(t+='<div style="font-size: 0.8rem; color: var(--accent); margin-bottom: 6px;">'+l.preview.serviceCount+" services</div>"),l.preview.themeCount&&(t+='<div style="font-size: 0.8rem; color: var(--accent); margin-bottom: 6px;">\u{1F3A8} '+l.preview.themeCount+" custom themes</div>"),l.preview.browserStateCount&&(t+='<div style="margin-top: 6px; font-size: 0.75rem; color: var(--muted); text-transform: uppercase; letter-spacing: 0.5px;">Browser Preferences</div>',t+='<div style="font-size: 0.8rem; color: var(--accent);">\u{1F5A5}\uFE0F '+l.preview.browserStateCount+" saved settings (theme, weather, clock, widgets, etc.)</div>"),B.innerHTML=t,k.style.display="block"}else T.innerHTML="\u26A0\uFE0F Invalid backup file: "+escapeHtml(l.error),T.style.display="block",T.style.background="color-mix(in srgb, #f39c12 15%, transparent)",T.style.border="1px solid #f39c12",k.style.display="none"}catch(q){T.innerHTML="\u274C Could not read file: "+escapeHtml(q.message),T.style.display="block",T.style.background="color-mix(in srgb, var(--bad-fg) 15%, transparent)",T.style.border="1px solid var(--bad-fg)",k.style.display="none"}}}),S?.addEventListener("click",async function(){if(D&&confirm("This will overwrite your current configuration and browser preferences. Continue?")){S.disabled=!0,S.innerHTML='<span class="brand-spinner"></span> Restoring...';try{if(w(D)){N(D),T.innerHTML="\u2705 Legacy backup restored \u2014 browser settings and services imported.",T.style.background="color-mix(in srgb, var(--ok-fg) 15%, transparent)",T.style.border="1px solid var(--ok-fg)",T.style.display="block",setTimeout(function(){location.reload()},2e3),S.disabled=!1,S.innerHTML="\u26A1 Restore Everything";return}var e=document.getElementById("backup-reload-caddy")?.checked??!0,o=await secureFetch("/api/v1/backup/restore",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({backup:D,options:{reloadCaddy:e}})}),a=await o.json(),r=0;if(D.browserState&&(r=P(D.browserState)),a.success){var t="\u2705 "+a.message;r>0&&(t+='<br><small style="color: var(--muted);">'+r+" browser settings restored</small>"),a.results.caddyReloaded&&(t+='<br><small style="color: var(--muted);">Caddy configuration reloaded</small>'),T.innerHTML=t,T.style.background="color-mix(in srgb, var(--ok-fg) 15%, transparent)",T.style.border="1px solid var(--ok-fg)",setTimeout(function(){location.reload()},2e3)}else T.innerHTML="\u26A0\uFE0F "+escapeHtml(a.message),r>0&&(T.innerHTML+='<br><small style="color: var(--muted);">'+r+" browser settings were restored</small>"),a.results?.errors?.length>0&&(T.innerHTML+="<br><small>"+a.results.errors.map(function(s){return escapeHtml(s.file)+": "+escapeHtml(s.error)}).join(", ")+"</small>"),T.style.background="color-mix(in srgb, #f39c12 15%, transparent)",T.style.border="1px solid #f39c12";T.style.display="block"}catch(s){T.innerHTML="\u274C Restore failed: "+escapeHtml(s.message),T.style.display="block",T.style.background="color-mix(in srgb, var(--bad-fg) 15%, transparent)",T.style.border="1px solid var(--bad-fg)"}S.disabled=!1,S.innerHTML="\u26A1 Restore Everything"}});async function g(){if(j){j.innerHTML='<div class="panel-empty"><span class="brand-spinner"></span> Loading...</div>';try{var e=await fetch("/api/v1/backups/schedule"),o=await e.json();if(o.premiumRequired){j.innerHTML=`<div class="panel-empty" style="padding: 24px; text-align: center;"><div style="font-size: 2rem; margin-bottom: 12px;">\u2B50</div><div style="font-weight: 600; margin-bottom: 8px;">Premium Feature</div><div style="font-size: 0.85rem; color: var(--muted);">Auto-backup scheduling requires a DashCaddy Premium subscription.</div><button onclick="showNotification('Upgrade to Premium to enable auto-backups!', 'info'); scrollToSection('license');" style="margin-top: 16px; padding: 8px 20px; background: linear-gradient(135deg, #f39c12, #e67e22); border: none; color: white; border-radius: 8px; cursor: pointer; font-weight: 600;">Upgrade to Premium</button></div>`;return}if(!o.success)throw new Error(o.error||"Failed to load schedules");var a=o.schedules||[];if(a.length===0){j.innerHTML='<div class="panel-empty"><span class="empty-icon">\u23F0</span><div>No backup schedules configured</div><div style="font-size: 0.8rem; color: var(--muted); margin-top: 4px;">Select apps below to enable auto-backup</div></div>';return}for(var r='<div style="display: flex; flex-direction: column; gap: 8px;">',t=0;t<a.length;t++){var s=a[t],l=s.nextRun?new Date(s.nextRun).toLocaleString():"Not scheduled",C=s.lastRun?new Date(s.lastRun).toLocaleString():"Never";r+='<div style="padding: 12px 14px; background: var(--card-base); border-radius: 8px; border: 1px solid var(--border);"><div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px;">  <div style="font-weight: 600; font-size: 0.9rem;">'+escapeHtml(s.appId)+'</div>  <label class="toggle-switch" style="display: flex; align-items: center; gap: 6px;">    <input type="checkbox" class="schedule-toggle" data-appid="'+escapeHtml(s.appId)+'"'+(s.enabled?" checked":"")+' />    <span style="font-size: 0.75rem; color: var(--muted);">'+(s.enabled?"ON":"OFF")+'</span>  </label></div><div style="display: grid; grid-template-columns: 1fr 1fr; gap: 8px; font-size: 0.8rem; margin-bottom: 10px;">  <div><span style="color: var(--muted);">Schedule:</span> <select class="schedule-select" data-appid="'+escapeHtml(s.appId)+'" style="background: var(--base); border: 1px solid var(--border); border-radius: 4px; padding: 2px 6px;">    <option value="hourly"'+(s.schedule==="hourly"?" selected":"")+'>Hourly</option>    <option value="daily"'+(s.schedule==="daily"?" selected":"")+'>Daily</option>    <option value="weekly"'+(s.schedule==="weekly"?" selected":"")+'>Weekly</option>    <option value="monthly"'+(s.schedule==="monthly"?" selected":"")+'>Monthly</option>  </select></div>  <div><span style="color: var(--muted);">Keep last:</span> <input type="number" class="retention-input" data-appid="'+escapeHtml(s.appId)+'" value="'+(s.retention?.keep||7)+'" min="1" max="100" style="width: 50px; background: var(--base); border: 1px solid var(--border); border-radius: 4px; padding: 2px 6px;" /></div></div><div style="font-size: 0.75rem; color: var(--muted); margin-bottom: 10px;">  <div>Next run: '+escapeHtml(l)+"</div>  <div>Last run: "+escapeHtml(C)+'</div></div><div style="display: flex; gap: 6px;">  <button class="schedule-run-now" data-appid="'+escapeHtml(s.appId)+'" style="padding: 5px 12px; font-size: 0.8rem; background: color-mix(in srgb, var(--ok-fg) 20%, transparent); border: 1px solid var(--ok-fg); color: var(--ok-fg); border-radius: 6px; cursor: pointer;">\u25B6\uFE0F Run Now</button>  <button class="schedule-delete" data-appid="'+escapeHtml(s.appId)+'" style="padding: 5px 12px; font-size: 0.8rem; background: transparent; border: 1px solid var(--bad-fg); color: var(--bad-fg); border-radius: 6px; cursor: pointer;">\u{1F5D1}\uFE0F Remove</button></div></div>'}r+="</div>",r+='<div style="margin-top: 16px; padding: 16px; background: color-mix(in srgb, var(--accent) 5%, transparent); border-radius: 10px; border: 1px dashed var(--border);"><h4 style="margin: 0 0 12px; font-size: 0.85rem; color: var(--muted);">\u2795 Add New Schedule</h4><div style="display: flex; gap: 8px; flex-wrap: wrap;">  <input type="text" id="new-schedule-appid" placeholder="App ID (e.g., plex, sonarr)" style="flex: 1; min-width: 150px; padding: 8px; border-radius: 6px; border: 1px solid var(--border); background: var(--base);" />  <select id="new-schedule-interval" style="padding: 8px; border-radius: 6px; border: 1px solid var(--border); background: var(--base);">    <option value="hourly">Hourly</option>    <option value="daily" selected>Daily</option>    <option value="weekly">Weekly</option>    <option value="monthly">Monthly</option>    <option value="6h">Every 6 hours</option>    <option value="30m">Every 30 minutes</option>  </select>  <input type="number" id="new-schedule-retention" value="7" min="1" max="100" placeholder="Keep" style="width: 70px; padding: 8px; border-radius: 6px; border: 1px solid var(--border); background: var(--base);" />  <button id="add-schedule-btn" style="padding: 8px 16px; background: var(--accent); border: none; color: white; border-radius: 6px; cursor: pointer; font-weight: 500;">Add Schedule</button></div></div>',j.innerHTML=r,j.querySelectorAll(".schedule-toggle").forEach(function(I){I.addEventListener("change",function(){u(I.dataset.appid,{enabled:I.checked})})}),j.querySelectorAll(".schedule-select").forEach(function(I){I.addEventListener("change",function(){u(I.dataset.appid,{schedule:I.value})})}),j.querySelectorAll(".retention-input").forEach(function(I){I.addEventListener("change",function(){u(I.dataset.appid,{retention:{keep:parseInt(I.value)||7}})})}),j.querySelectorAll(".schedule-run-now").forEach(function(I){I.addEventListener("click",function(){f(I.dataset.appid)})}),j.querySelectorAll(".schedule-delete").forEach(function(I){I.addEventListener("click",function(){m(I.dataset.appid)})}),document.getElementById("add-schedule-btn")?.addEventListener("click",p)}catch(I){j.innerHTML='<div class="panel-empty" style="color: var(--bad-fg);">Failed to load: '+escapeHtml(I.message)+"</div>"}}}async function u(e,o){try{var a=await secureFetch("/api/v1/backups/schedule",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({appId:e,...o})}),r=await a.json();r.success?showNotification("Schedule updated for "+e,"success"):(showNotification("Update failed: "+(r.error||"Unknown"),"error"),g())}catch(t){showNotification("Error: "+t.message,"error")}}async function f(e){try{var o=await secureFetch("/api/v1/backups/backup/"+encodeURIComponent(e),{method:"POST",headers:{"Content-Type":"application/json"}}),a=await o.json();a.success?showNotification("Backup started for "+e+"!","success"):showNotification("Backup failed: "+(a.error||"Unknown"),"error")}catch(r){showNotification("Error: "+r.message,"error")}}async function m(e){if(confirm("Remove backup schedule for "+e+"?"))try{var o=await secureFetch("/api/v1/backups/schedule/"+encodeURIComponent(e),{method:"DELETE"}),a=await o.json();a.success?(showNotification("Schedule removed for "+e,"success"),g()):showNotification("Delete failed: "+(a.error||"Unknown"),"error")}catch(r){showNotification("Error: "+r.message,"error")}}async function p(){var e=document.getElementById("new-schedule-appid")?.value?.trim(),o=document.getElementById("new-schedule-interval")?.value||"daily",a=parseInt(document.getElementById("new-schedule-retention")?.value)||7;if(!e){showNotification("Please enter an App ID","warning");return}try{var r=await secureFetch("/api/v1/backups/schedule",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({appId:e,schedule:o,retention:{keep:a},enabled:!0})}),t=await r.json();if(t.success){showNotification("Schedule created for "+e,"success"),g();var s=document.getElementById("new-schedule-appid");s&&(s.value="")}else showNotification("Failed: "+(t.error||"Unknown"),"error")}catch(l){showNotification("Error: "+l.message,"error")}}async function d(){if(R){R.innerHTML='<div class="panel-empty"><span class="brand-spinner"></span> Loading...</div>';try{var e=await fetch("/api/v1/backups/files"),o=await e.json();if(!o.success)throw new Error(o.error||"Failed to load");var a=o.files||[];if(a.length===0){R.innerHTML='<div class="panel-empty"><span class="empty-icon">\u{1F4BE}</span><div>No backup files on disk</div><div style="font-size: 0.8rem; color: var(--muted); margin-top: 4px;">Run a backup to create backup files</div></div>';return}for(var r={},t=0;t<a.length;t++){var s=a[t],l=s.appId||"unknown";r[l]||(r[l]=[]),r[l].push(s)}var C='<div style="font-size: 0.75rem; color: var(--muted); margin-bottom: 12px;">'+a.length+" backup file(s) across "+Object.keys(r).length+" app(s)</div>";C+='<div style="display: flex; flex-direction: column; gap: 12px;">';for(var I=Object.keys(r).sort(),F=0;F<I.length;F++){var l=I[F],q=r[l];C+='<div style="background: var(--card-base); border-radius: 8px; border: 1px solid var(--border); overflow: hidden;"><div style="padding: 8px 12px; background: color-mix(in srgb, var(--accent) 8%, transparent); border-bottom: 1px solid var(--border); font-weight: 600; font-size: 0.85rem;">'+escapeHtml(l)+' <span style="font-weight: normal; color: var(--muted); font-size: 0.75rem;">('+q.length+" backup(s))</span></div>";for(var U=0;U<q.length;U++){var s=q[U],G=new Date(s.timestamp).toLocaleString();C+='<div style="padding: 10px 12px; border-bottom: 1px solid var(--border);"><div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 4px;">  <div style="font-weight: 500; font-size: 0.85rem;">'+escapeHtml(s.name)+'</div>  <div style="font-size: 0.75rem; color: var(--muted);">'+s.sizeFormatted+'</div></div><div style="font-size: 0.75rem; color: var(--muted); margin-bottom: 8px;">'+G+'</div><div style="display: flex; gap: 6px;">  <button class="disk-compare-btn" data-appid="'+escapeHtml(l)+'" data-filename="'+escapeHtml(s.name)+'" style="padding: 3px 8px; font-size: 0.75rem; background: transparent; border: 1px solid var(--accent); color: var(--accent); border-radius: 5px; cursor: pointer;">Compare</button>  <button class="disk-restore-btn" data-appid="'+escapeHtml(l)+'" data-filename="'+escapeHtml(s.name)+'" style="padding: 3px 8px; font-size: 0.75rem; background: linear-gradient(135deg, var(--ok-fg), #27ae60); border: none; color: white; border-radius: 5px; cursor: pointer; font-weight: 500;">Restore</button></div></div>'}C+="</div>"}C+="</div>",R.innerHTML=C,R.querySelectorAll(".disk-compare-btn").forEach(function(J){J.addEventListener("click",function(){y(J.dataset.appid,J.dataset.filename)})}),R.querySelectorAll(".disk-restore-btn").forEach(function(J){J.addEventListener("click",function(){n(J.dataset.appid,J.dataset.filename)})})}catch(J){R.innerHTML='<div class="panel-empty" style="color: var(--bad-fg);">Failed: '+escapeHtml(J.message)+"</div>"}}}async function c(){if(H){H.innerHTML='<div class="panel-empty"><span class="brand-spinner"></span> Loading...</div>';try{var e=await fetch("/api/v1/backups/history?limit=50"),o=await e.json();if(!o.success||!o.history?.length){H.innerHTML='<div class="panel-empty"><span class="empty-icon">\u{1F4CB}</span> No backup history yet</div>';return}for(var a='<div style="display: flex; flex-direction: column; gap: 6px;">',r=0;r<o.history.length;r++){var t=o.history[r],s=t.size?(t.size/1024/1024).toFixed(2):"?";a+='<div style="padding: 10px 12px; background: var(--card-base); border-radius: 6px; border: 1px solid var(--border); font-size: 0.85rem;">',a+='  <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 4px;">',a+='    <span style="font-weight: 500;">'+escapeHtml(t.name||"backup")+"</span>",a+='    <div style="display: flex; align-items: center; gap: 8px;">',a+='      <span class="status-badge '+(t.status==="success"?"success":"down")+'">'+escapeHtml(t.status)+"</span>",t.status==="success"&&(a+='      <button class="backup-restore-btn" data-backup-id="'+escapeHtml(t.id)+'" style="padding: 3px 8px; font-size: 0.75rem;">Restore</button>'),a+="    </div>",a+="  </div>",a+='  <div style="font-size: 0.75rem; color: var(--muted);">',a+="    "+new Date(t.timestamp).toLocaleString()+" | "+s+" MB | "+(t.duration?(t.duration/1e3).toFixed(1)+"s":"--"),t.encrypted&&(a+=" | \u{1F512}"),a+="  </div>",a+="</div>"}a+="</div>",H.innerHTML=a,H.querySelectorAll(".backup-restore-btn").forEach(function(l){l.addEventListener("click",function(){window.__restoreServerBackup(l.dataset.backupId)})})}catch(l){H.innerHTML='<div class="panel-empty" style="color: var(--bad-fg);">Failed: '+escapeHtml(l.message)+"</div>"}}}window.__restoreServerBackup=async function(e){if(confirm("Restore from this server backup? This will overwrite current configuration."))try{var o=await secureFetch("/api/v1/backups/restore/"+e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({restoreServices:!0,restoreConfig:!0})}),a=await o.json();a.success?(showNotification("Restore completed successfully!","success"),location.reload()):showNotification("Restore failed: "+(a.error||"Unknown error"),"error")}catch(r){showNotification("Restore error: "+r.message,"error")}},document.querySelector('[data-panel="backup-schedules-tab"]')?.addEventListener("click",g),document.querySelector('[data-panel="backup-disk-tab"]')?.addEventListener("click",d),document.querySelector('[data-panel="backup-pointintime-tab"]')?.addEventListener("click",i),document.querySelector('[data-panel="backup-history-tab"]')?.addEventListener("click",c);async function i(){if(x){try{var e=await fetch("/api/v1/license/status"),o=await e.json();if(o.tier!=="premium"){x.innerHTML=`<div class="panel-empty" style="padding: 24px; text-align: center;"><div style="font-size: 2rem; margin-bottom: 12px;">\u2B50</div><div style="font-weight: 600; margin-bottom: 8px;">Premium Feature</div><div style="font-size: 0.85rem; color: var(--muted);">Point-in-time restore requires DashCaddy Premium with auto-backup enabled.</div><button onclick="showNotification('Upgrade to Premium for point-in-time restore!', 'info'); scrollToSection('license');" style="margin-top: 16px; padding: 8px 20px; background: linear-gradient(135deg, #f39c12, #e67e22); border: none; color: white; border-radius: 8px; cursor: pointer; font-weight: 600;">Upgrade to Premium</button></div>`;return}}catch{}x.innerHTML='<div class="panel-empty"><span class="brand-spinner"></span> Loading...</div>';try{var a=await fetch("/api/v1/services"),r=await a.json(),t=r.services||[];if(t.length===0){x.innerHTML='<div class="panel-empty"><span class="empty-icon">\u{1F4E6}</span> No apps deployed yet</div>';return}for(var s='<div style="padding: 8px 0 12px;"><div style="display: flex; gap: 8px; align-items: center; margin-bottom: 12px;">  <label style="font-size: 0.85rem; color: var(--muted); white-space: nowrap;">App:</label>  <select id="pit-app-select" style="flex: 1; padding: 8px; border-radius: 6px; border: 1px solid var(--border); background: var(--base); max-width: 240px;">',l=0;l<t.length;l++)s+='<option value="'+escapeHtml(t[l].id||t[l].name||"")+'">'+escapeHtml(t[l].name||t[l].id||"")+"</option>";s+='</select>  <button id="pit-load-btn" style="padding: 8px 16px; background: var(--accent); border: none; color: white; border-radius: 6px; cursor: pointer; font-weight: 500;">Load Backups</button></div><div id="pit-backups-list" style="max-height: 320px; overflow-y: auto;"></div></div>',x.innerHTML=s,document.getElementById("pit-load-btn")?.addEventListener("click",function(){var C=document.getElementById("pit-app-select")?.value;C&&$(C)})}catch(C){x.innerHTML='<div class="panel-empty" style="color: var(--bad-fg);">Failed: '+escapeHtml(C.message)+"</div>"}}}async function $(e){var o=document.getElementById("pit-backups-list");if(o){o.innerHTML='<div style="padding: 20px; text-align: center;"><span class="brand-spinner"></span> Loading backups...</div>';try{var a=await fetch("/api/v1/backups/files/"+encodeURIComponent(e)),r=await a.json();if(!r.success||!r.files||r.files.length===0){o.innerHTML='<div class="panel-empty"><span class="empty-icon">\u{1F4BE}</span> No backup files for '+escapeHtml(e)+"</div>";return}for(var t='<div style="font-size: 0.75rem; color: var(--muted); margin-bottom: 8px;">'+r.files.length+' backup(s)</div><div style="display: flex; flex-direction: column; gap: 6px;">',s=0;s<r.files.length;s++){var l=r.files[s],C=new Date(l.timestamp).toLocaleString();t+='<div style="padding: 10px 12px; background: var(--card-base); border-radius: 8px; border: 1px solid var(--border);"><div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 4px;">  <div style="font-weight: 500; font-size: 0.85rem;">'+escapeHtml(l.name)+'</div>  <div style="font-size: 0.75rem; color: var(--muted);">'+l.sizeFormatted+'</div></div><div style="font-size: 0.75rem; color: var(--muted); margin-bottom: 8px;">'+C+'</div><div style="display: flex; gap: 6px;">  <button class="pit-compare-btn" data-appid="'+escapeHtml(e)+'" data-filename="'+escapeHtml(l.name)+'" style="padding: 4px 10px; font-size: 0.75rem; background: transparent; border: 1px solid var(--accent); color: var(--accent); border-radius: 5px; cursor: pointer;">Compare</button>  <button class="pit-restore-btn" data-appid="'+escapeHtml(e)+'" data-filename="'+escapeHtml(l.name)+'" style="padding: 4px 10px; font-size: 0.75rem; background: linear-gradient(135deg, var(--ok-fg), #27ae60); border: none; color: white; border-radius: 5px; cursor: pointer; font-weight: 500;">Restore</button></div></div>'}t+="</div>",o.innerHTML=t,o.querySelectorAll(".pit-compare-btn").forEach(function(I){I.addEventListener("click",function(){y(I.dataset.appid,I.dataset.filename)})}),o.querySelectorAll(".pit-restore-btn").forEach(function(I){I.addEventListener("click",function(){n(I.dataset.appid,I.dataset.filename)})})}catch(I){o.innerHTML='<div class="panel-empty" style="color: var(--bad-fg);">Failed: '+escapeHtml(I.message)+"</div>"}}}async function y(e,o){try{var a=await secureFetch("/api/v1/backups/compare/"+encodeURIComponent(o),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({})}),r=await a.json();if(!r.success){showNotification("Compare failed: "+(r.error||"Unknown"),"error");return}var t=r.diff,s='<div style="position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.5); z-index: 10000; display: flex; align-items: center; justify-content: center;" id="compare-overlay"><div style="background: var(--base); border-radius: 12px; max-width: 600px; width: 90%; max-height: 80vh; overflow: auto; padding: 20px; border: 1px solid var(--border);"><h4 style="margin: 0 0 16px;">\u{1F4CA} Compare: '+escapeHtml(o)+'</h4><div style="font-size: 0.8rem; color: var(--muted); margin-bottom: 16px;">Size: '+(t.sizeFormatted||"?")+" | Created: "+new Date(t.timestamp).toLocaleString()+"</div>";if(t.services){var l=t.services.hasChanges?"\u{1F534}":"\u{1F7E2}";s+='<div style="margin-bottom: 12px; padding: 10px; background: var(--card-base); border-radius: 6px; border: 1px solid var(--border);"><div style="font-weight: 600; font-size: 0.85rem; margin-bottom: 4px;">'+l+' Services (backup vs current)</div><div style="font-size: 0.8rem; color: var(--muted);">Backup: '+t.services.backupCount+" services | Current: "+t.services.currentCount+" services</div>",t.services.hasChanges&&(s+='<div style="margin-top: 6px; font-size: 0.8rem; color: #f39c12;">Services differ \u2014 restoring will replace current configuration</div>'),s+="</div>"}if(t.config){var C=t.config.hasChanges?"\u{1F534}":"\u{1F7E2}";s+='<div style="margin-bottom: 12px; padding: 10px; background: var(--card-base); border-radius: 6px; border: 1px solid var(--border);"><div style="font-weight: 600; font-size: 0.85rem; margin-bottom: 4px;">'+C+" Configuration</div>",t.config.hasChanges?s+='<div style="font-size: 0.8rem; color: #f39c12;">Configuration differs \u2014 restoring will replace current settings</div>':s+='<div style="font-size: 0.8rem; color: var(--ok-fg);">No changes</div>',s+="</div>"}s+='<button id="compare-close-btn" style="padding: 8px 20px; background: var(--accent); border: none; color: white; border-radius: 6px; cursor: pointer; font-weight: 500;">Close</button></div></div>',document.body.insertAdjacentHTML("beforeend",s),document.getElementById("compare-close-btn")?.addEventListener("click",function(){document.getElementById("compare-overlay")?.remove()}),document.getElementById("compare-overlay")?.addEventListener("click",function(I){I.target===this&&this.remove()})}catch(I){showNotification("Compare error: "+I.message,"error")}}async function n(e,o){if(confirm("Restore "+o+" for "+e+`?

This will replace current configuration, credentials, and data. Containers will be restarted.`))try{var a=await secureFetch("/api/v1/apps/"+encodeURIComponent(e)+"/revert/"+encodeURIComponent(o),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({restartContainers:!0})}),r=await a.json();r.success?(showNotification(e+" restored to "+o,"success"),setTimeout(function(){location.reload()},1500)):showNotification("Restore failed: "+(r.error||"Unknown"),"error")}catch(t){showNotification("Restore error: "+t.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">
        Real-time and historical CPU, memory, network, and disk usage for containers.
      </p>

      <!-- Tab bar -->
      <div class="panel-tabs">
        <button class="panel-tab active" data-panel="stats-live">Live Stats</button>
        <button class="panel-tab" data-panel="stats-aggregated">24h Summary</button>
        <button class="panel-tab" data-panel="stats-history">History</button>
        <button class="panel-tab" data-panel="stats-alerts">Alerts</button>
      </div>

      <!-- Tab: Live Stats -->
      <div id="stats-live" class="panel-section active">
        <div id="stats-container" class="scroll-container">
          <div style="text-align: center; padding: 40px; color: var(--muted);">
            <span class="brand-spinner"></span> Loading container stats...
          </div>
        </div>
      </div>

      <!-- Tab: 24h Aggregated Summary -->
      <div id="stats-aggregated" class="panel-section">
        <div id="stats-aggregated-container" class="scroll-container">
          <div class="panel-empty">
            <span class="empty-icon">\u{1F4C8}</span>
            Loading 24-hour aggregated metrics...
          </div>
        </div>
      </div>

      <!-- Tab: Long-term History -->
      <div id="stats-history" class="panel-section">
        <div style="display: flex; gap: 8px; align-items: center; margin-bottom: 12px; flex-wrap: wrap;">
          <label style="font-size: 0.85rem; color: var(--muted);">Container:</label>
          <select id="stats-history-container" style="padding: 4px 8px; background: var(--card-base); border: 1px solid var(--border); color: var(--fg); border-radius: 4px; font-size: 0.85rem; flex: 1; min-width: 180px;"></select>
          <div id="stats-history-range-buttons" style="display: flex; gap: 4px;">
            <button class="stats-range-btn active" data-range="1h">1h</button>
            <button class="stats-range-btn" data-range="24h">24h</button>
            <button class="stats-range-btn" data-range="7d">7d</button>
            <button class="stats-range-btn" data-range="30d">30d</button>
            <button class="stats-range-btn" data-range="1y">1y</button>
          </div>
        </div>
        <div id="stats-history-container-area" class="scroll-container">
          <div class="panel-empty">
            <span class="empty-icon">\u{1F4CA}</span>
            Choose a container and time range to view history.
          </div>
        </div>
      </div>

      <!-- Tab: Alert Configuration -->
      <div id="stats-alerts" class="panel-section">
        <div id="stats-alerts-container" class="scroll-container">
          <div class="panel-empty">
            <span class="empty-icon">\u{1F514}</span>
            Loading alert configurations...
          </div>
        </div>
      </div>

      <!-- Auto-refresh toggle (bottom bar) -->
      <div class="panel-bottom-bar">
        <label class="checkbox-label" style="font-size: 0.85rem;">
          <input type="checkbox" id="stats-auto-refresh" checked />
          Auto-refresh every 5s
        </label>
        <button id="stats-refresh-btn" class="btn-sm">\u{1F504} Refresh Now</button>
        <span id="stats-last-update" class="text-auto-right"></span>
      </div>

      <!-- Close Button -->
      <div class="weather-modal-buttons modal-footer-bar">
        <button id="stats-cancel">Close</button>
      </div>
    </div>
  </div>`);const h=document.getElementById("stats-modal"),E=document.getElementById("container-stats-btn"),P=document.getElementById("stats-cancel"),w=document.getElementById("stats-refresh-btn"),N=document.getElementById("stats-auto-refresh"),O=document.getElementById("stats-container"),z=document.getElementById("stats-aggregated-container"),A=document.getElementById("stats-alerts-container"),v=document.getElementById("stats-last-update");let L=null,b=null;function M(i){if(i===0||!i)return"0 B";const $=1024,y=["B","KB","MB","GB"],n=Math.floor(Math.log(i)/Math.log($));return parseFloat((i/Math.pow($,n)).toFixed(1))+" "+y[n]}function k(i){return i<30?"#2ecc71":i<70?"#f39c12":"#e74c3c"}function B(i){return i<50?"#2ecc71":i<80?"#f39c12":"#e74c3c"}async function S(){try{let i=null,$=!1;try{const e=await(await fetch("/api/v1/monitoring/stats")).json();e.success&&e.stats&&(i=e.stats,$=!0,b=e.stats)}catch{}if(!$){const e=await(await fetch("/api/v1/stats/containers")).json();if(e.success&&e.stats){i={};for(const o of e.stats)i[o.name]={name:o.name,current:{cpu:o.cpu,memory:{percent:o.memory.percent,usage:o.memory.used,limit:o.memory.limit,usageMB:Math.round(o.memory.used/1048576),limitMB:Math.round(o.memory.limit/1048576)},network:{rxBytes:o.network.rx,txBytes:o.network.tx,rxMB:(o.network.rx/1048576).toFixed(1),txMB:(o.network.tx/1048576).toFixed(1)},disk:{readMB:0,writeMB:0}},status:o.status};b=i}}if(!i||Object.keys(i).length===0){O.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[n,e]of Object.entries(i)){const o=e.current||e,a=o.cpu?.percent||0,r=o.memory?.percent||0,t=k(a),s=B(r),l=o.memory?.usage||o.memory?.used||0,C=o.memory?.limit||0,I=o.network?.rxBytes||o.network?.rx||0,F=o.network?.txBytes||o.network?.tx||0,q=e.aggregated;y+=`
          <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||n}</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;">
              <div>
                <div style="font-size: 0.7rem; color: var(--muted); margin-bottom: 4px;">CPU</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(a,100)}%; background: ${t}; border-radius: 3px; transition: width 0.3s;"></div>
                  </div>
                  <span style="font-size: 0.8rem; font-weight: 500; color: ${t}; min-width: 45px; text-align: right;">${a.toFixed(1)}%</span>
                </div>
              </div>
              <div>
                <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(r,100)}%; background: ${s}; 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;">${r.toFixed(1)}%</span>
                </div>
                <div style="font-size: 0.65rem; color: var(--muted); margin-top: 2px;">${M(l)} / ${M(C)}</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 ${M(I)}</span>
                  <span style="color: var(--muted); margin: 0 4px;">/</span>
                  <span style="color: #e74c3c;">\u2191 ${M(F)}</span>
                </div>
              </div>
            </div>
          </div>`}y+="</div>",O.innerHTML=y,v.textContent="Updated: "+new Date().toLocaleTimeString()}catch(i){O.innerHTML=`<div style="text-align: center; padding: 40px; color: var(--bad-fg);">\u274C Failed to load stats: ${escapeHtml(i.message)}</div>`}}async function T(){if(!z)return;const i=b;if(!i||Object.keys(i).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 $='<div style="display: flex; flex-direction: column; gap: 12px;">';for(const[y,n]of Object.entries(i)){const e=n.aggregated;e&&($+=`<div style="padding: 12px; background: var(--card-base); border-radius: 8px; border: 1px solid var(--border);">
        <div style="font-weight: 600; margin-bottom: 10px;">${n.name||y}</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>
          <div class="stat-mini-card"><span class="stat-val">${e.memory?.avg?.toFixed(1)||0}%</span><span class="stat-lbl">Avg Mem</span></div>
          <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>`)}$+="</div>",z.innerHTML=$}async function j(){if(!A)return;A.innerHTML='<div class="panel-empty"><span class="brand-spinner"></span> Loading alerts...</div>';const i=b;if(!i||Object.keys(i).length===0){A.innerHTML='<div class="panel-empty"><span class="empty-icon">\u{1F514}</span>No containers found. Open the Live Stats tab first.</div>';return}let $=!1;try{$=(await(await fetch("/api/v1/license/feature/resource-alerts")).json()).available}catch{$=!1}let y=[];try{const s=await(await fetch("/api/v1/monitoring/alerts?limit=50")).json();s.success&&(y=s.history||[])}catch{}let n={};try{const s=await(await fetch("/api/v1/monitoring/alerts/config")).json();s.success&&(n=s.configs||{})}catch{}const o=Object.entries(i).map(([t,s])=>{const l=n[t]||{cpuThreshold:80,memoryThreshold:90,diskIOThreshold:50,autoRestart:!1,enabled:!1};return`
        <tr data-container="${t}">
          <td style="font-weight: 600; padding: 8px;">${s.name||t}</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;" ${$?"":"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;" ${$?"":"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;" ${$?"":"disabled"} /></td>
          <td style="padding: 4px 8px;"><input type="checkbox" class="alert-autorestart" ${l.autoRestart?"checked":""} ${$?"":"disabled"} /></td>
          <td style="padding: 4px 8px;">
            <button class="alert-test-btn btn-xs" data-container="${t}" data-name="${s.name||t}" 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(""),a=y.map(t=>{const s=new Date(t.timestamp).toLocaleString(),l=t.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-weight: 500;">${t.containerName||t.containerId}</td>
          <td style="padding: 6px 8px; text-transform: capitalize;">${t.metric||t.type}</td>
          <td style="padding: 6px 8px;">${typeof t.value=="number"?t.value.toFixed(1):t.value}${t.metric==="disk"?" MB/s":"%"}</td>
          <td style="padding: 6px 8px; text-align: center;">${l}</td>
          <td style="padding: 6px 8px; font-size: 0.75rem; color: ${t.autoRestartTriggered?"#f39c12":"var(--muted)"};">${t.autoRestartTriggered?"\u21BB":""}</td>
        </tr>
      `}).join(""),r=$?`
      <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>
          <a href="#" id="go-to-notifications" style="font-size: 0.8rem; color: var(--accent); text-decoration: none;">Configure notifications \u2192</a>
        </div>
        <div style="overflow-x: auto;">
          <table style="width: 100%; border-collapse: collapse; font-size: 0.85rem;">
            <thead>
              <tr style="border-bottom: 1px solid var(--border);">
                <th style="text-align: left; padding: 6px 8px; color: var(--muted);">Container</th>
                <th style="text-align: left; padding: 6px 8px; color: var(--muted);">CPU %</th>
                <th style="text-align: left; padding: 6px 8px; color: var(--muted);">Mem %</th>
                <th style="text-align: left; padding: 6px 8px; color: var(--muted);">Disk I/O MB/s</th>
                <th style="text-align: center; padding: 6px 8px; color: var(--muted);">Auto-Restart</th>
                <th style="padding: 6px 8px;"></th>
              </tr>
            </thead>
            <tbody>${o}</tbody>
          </table>
        </div>
        <div style="margin-top: 12px; display: flex; justify-content: flex-end;">
          <button id="save-all-alerts" style="padding: 6px 16px; font-size: 0.85rem; background: var(--accent); color: var(--base); border: none; border-radius: 4px; cursor: pointer; font-weight: 600;">Save All</button>
        </div>
      </div>
    `:`
      <div style="margin-bottom: 20px; padding: 12px; background: rgba(241,196,15,0.1); border: 1px solid rgba(241,196,15,0.3); border-radius: 8px; text-align: center;">
        <span style="color: #f1c40f; font-weight: 600; font-size: 0.85rem;">\u2B50 Premium Feature</span>
        <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>
    `;A.innerHTML=`
      ${r}
      <div>
        <h4 style="margin: 0 0 10px; font-size: 0.9rem;">\u{1F4CB} Recent Alerts</h4>
        ${a?`
          <div style="overflow-x: auto;">
            <table style="width: 100%; border-collapse: collapse; font-size: 0.8rem;">
              <thead>
                <tr style="border-bottom: 1px solid var(--border);">
                  <th style="text-align: left; padding: 6px 8px; color: var(--muted);">Time</th>
                  <th style="text-align: left; padding: 6px 8px; color: var(--muted);">Container</th>
                  <th style="text-align: left; padding: 6px 8px; color: var(--muted);">Metric</th>
                  <th style="text-align: left; padding: 6px 8px; color: var(--muted);">Value</th>
                  <th style="text-align: center; padding: 6px 8px; color: var(--muted);">\u2713?</th>
                  <th style="padding: 6px 8px;"></th>
                </tr>
              </thead>
              <tbody>${a}</tbody>
            </table>
          </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 t={};document.querySelectorAll("#stats-alerts-container tr[data-container]").forEach(s=>{const l=s.dataset.container;t[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:t})})).json(),C=document.getElementById("save-all-alerts");C.textContent=l.success?"\u2705 Saved":"\u274C Failed",setTimeout(()=>{C.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",t=>{t.preventDefault(),h.classList.remove("show"),R(),document.getElementById("manage-notifications")?.click()}),document.querySelectorAll(".alert-test-btn").forEach(t=>{t.addEventListener("click",async()=>{const s=t.textContent;t.textContent="...";try{await secureFetch(`/api/v1/monitoring/alerts/${t.dataset.container}/test`,{method:"POST"}),t.textContent="\u2705",showNotification("Test alert sent for "+t.dataset.name,"success",3e3)}catch{t.textContent="\u274C"}setTimeout(()=>{t.textContent=s},2e3)})}),document.getElementById("upgrade-for-alerts")?.addEventListener("click",()=>{h.classList.remove("show"),R(),typeof openLicenseModal=="function"&&openLicenseModal()})}function H(){L&&clearInterval(L),N?.checked&&(L=setInterval(S,DC.POLL.STATS))}function R(){L&&(clearInterval(L),L=null)}E?.addEventListener("click",()=>{h.classList.add("show"),S(),H()}),P?.addEventListener("click",()=>{h.classList.remove("show"),R()}),h?.addEventListener("click",i=>{i.target===h&&(h.classList.remove("show"),R())}),w?.addEventListener("click",S),N?.addEventListener("change",()=>{N.checked?H():R()}),document.querySelector('[data-panel="stats-aggregated"]')?.addEventListener("click",T),document.querySelector('[data-panel="stats-alerts"]')?.addEventListener("click",j);const x=document.getElementById("stats-history-container"),D=document.getElementById("stats-history-container-area"),g=document.querySelectorAll(".stats-range-btn");let u="1h";function f(i){switch(i){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 m(i){return i==="raw"?"live (10s samples)":i==="hourly"?"hourly average":i==="daily"?"daily average":i}function p(i,$,y,n,e){if(!i||i.length===0)return`<div style="text-align: center; color: var(--muted); padding: 20px;">No data for ${escapeHtml(n)}</div>`;const o=i.map($).filter(G=>G!=null);if(o.length===0)return`<div style="text-align: center; color: var(--muted); padding: 20px;">No data for ${escapeHtml(n)}</div>`;const a=Math.max(...o,1),r=Math.min(...o,0),t=a-r||1,s=600,l=80,C=4,I=(s-C*2)/Math.max(o.length-1,1),F=o.map((G,J)=>{const X=C+J*I,Q=l-C-(G-r)/t*(l-C*2);return`${X.toFixed(1)},${Q.toFixed(1)}`}).join(" "),q=o[o.length-1],U=o.reduce((G,J)=>G+J,0)/o.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(n)}</span>
          <span style="font-size: 0.75rem; color: var(--muted);">last ${q.toFixed(1)}${e} \xB7 avg ${U.toFixed(1)}${e} \xB7 max ${a.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="${F}" />
        </svg>
      </div>
    `}function d(){if(!x)return;const i=b||{},$=x.value,y=Object.entries(i);if(y.length===0){x.innerHTML='<option value="">No containers</option>';return}x.innerHTML=y.map(([n,e])=>`<option value="${escapeHtml(n)}">${escapeHtml(e.name||n)}</option>`).join(""),$&&i[$]&&(x.value=$)}async function c(){if(!D||!x)return;const i=x.value;if(!i){D.innerHTML='<div class="panel-empty"><span class="empty-icon">\u{1F4CA}</span>No container selected.</div>';return}const $=Date.now(),y=$-f(u);D.innerHTML='<div class="panel-empty"><span class="brand-spinner"></span> Loading history...</div>';try{const e=await(await fetch(`/api/v1/monitoring/history/${encodeURIComponent(i)}?startTime=${y}&endTime=${$}`)).json();if(!e.success)throw new Error(e.error||"Failed to load history");const o=e.samples||[],a=e.tier||"raw";if(o.length===0){D.innerHTML=`<div class="panel-empty"><span class="empty-icon">\u{1F4CA}</span>No data for the last ${u}. Tier: ${m(a)}.</div>`;return}const r=a==="raw",t=r?F=>F.cpu?.percent:F=>F.cpu?.avg,s=r?F=>F.memory?.percent:F=>F.memory?.avgPercent,l=r?F=>F.network?.rxMB||0:F=>F.network?.rxMB||0,C=r?F=>F.network?.txMB||0:F=>F.network?.txMB||0;let I=`
        <div style="font-size: 0.75rem; color: var(--muted); margin-bottom: 8px;">
          ${o.length} samples \xB7 ${escapeHtml(m(a))} \xB7 ${new Date(y).toLocaleString()} \u2192 ${new Date($).toLocaleString()}
        </div>
      `;I+=p(o,t,"#2ecc71","CPU","%"),I+=p(o,s,"#3498db","Memory","%"),I+=p(o,l,"#9b59b6","Network RX"," MB"),I+=p(o,C,"#e67e22","Network TX"," MB"),D.innerHTML=I}catch(n){D.innerHTML=`<div class="panel-empty"><span class="empty-icon">\u26A0\uFE0F</span>Failed to load history: ${escapeHtml(n.message)}</div>`}}g.forEach(i=>{i.addEventListener("click",()=>{g.forEach($=>$.classList.remove("active")),i.classList.add("active"),u=i.dataset.range,c()})}),x?.addEventListener("change",c),document.querySelector('[data-panel="stats-history"]')?.addEventListener("click",()=>{d(),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">
        Service uptime tracking, SLA monitoring, and incident management.
      </p>

      <div class="panel-tabs">
        <button class="panel-tab active" data-panel="health-status">Status</button>
        <button class="panel-tab" data-panel="health-incidents">Incidents</button>
        <button class="panel-tab" data-panel="health-config">Configure</button>
      </div>

      <!-- Tab: Status -->
      <div id="health-status" class="panel-section active">
        <div id="health-status-container" class="scroll-container">
          <div class="panel-empty"><span class="brand-spinner"></span> Loading health status...</div>
        </div>
      </div>

      <!-- Tab: Incidents -->
      <div id="health-incidents" class="panel-section">
        <div id="health-incidents-container" class="scroll-container">
          <div class="panel-empty"><span class="empty-icon">\u{1F6A8}</span> Loading incidents...</div>
        </div>
      </div>

      <!-- Tab: Configure -->
      <div id="health-config" class="panel-section">
        <div id="health-config-container" class="scroll-container">
          <div class="panel-empty"><span class="empty-icon">\u2699\uFE0F</span> Loading configuration...</div>
        </div>

        <!-- Add/Edit Health Check Form -->
        <div id="health-config-form" style="display: none; margin-top: 16px; padding: 16px; border: 1px solid var(--border); border-radius: var(--radius); background: var(--card-base);">
          <h4 id="health-form-title" style="margin: 0 0 12px;">Add Health Check</h4>
          <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 12px;">
            <div>
              <label class="text-muted-sm">Service ID</label>
              <input type="text" id="health-form-id" placeholder="e.g. plex" class="form-input" />
            </div>
            <div>
              <label class="text-muted-sm">Display Name</label>
              <input type="text" id="health-form-name" placeholder="e.g. Plex Media Server" class="form-input" />
            </div>
            <div style="grid-column: span 2;">
              <label class="text-muted-sm">URL</label>
              <input type="text" id="health-form-url" placeholder="https://plex.home" class="form-input" />
            </div>
            <div>
              <label class="text-muted-sm">Timeout (ms)</label>
              <input type="number" id="health-form-timeout" value="10000" class="form-input" />
            </div>
            <div>
              <label class="text-muted-sm">Expected Status Codes</label>
              <input type="text" id="health-form-codes" value="200" placeholder="200, 301, 302" class="form-input" />
            </div>
            <div>
              <label class="text-muted-sm">SLA Target (%)</label>
              <input type="number" id="health-form-sla" value="99.9" step="0.1" class="form-input" />
            </div>
            <div>
              <label class="text-muted-sm">Slow Response Threshold (ms)</label>
              <input type="number" id="health-form-slow" value="5000" class="form-input" />
            </div>
          </div>
          <div style="margin-top: 12px; display: flex; gap: 8px; justify-content: flex-end;">
            <button id="health-form-cancel">Cancel</button>
            <button id="health-form-save" class="btn-accent-solid">Save</button>
          </div>
        </div>

        <div style="margin-top: 12px;">
          <button id="health-add-btn" class="btn-accent-solid">+ Add Health Check</button>
        </div>
      </div>

      <div class="panel-bottom-bar">
        <button id="health-refresh-btn" class="btn-sm">\u{1F504} Refresh</button>
        <span id="health-last-update" class="text-auto-right"></span>
      </div>

      <div class="weather-modal-buttons modal-footer-bar">
        <button id="health-cancel">Close</button>
      </div>
    </div>
  </div>`);const h=document.getElementById("health-modal"),E=document.getElementById("health-check-btn"),P=document.getElementById("health-cancel"),w=document.getElementById("health-refresh-btn"),N=document.getElementById("health-status-container"),O=document.getElementById("health-incidents-container"),z=document.getElementById("health-config-container"),A=document.getElementById("health-last-update"),v=document.getElementById("health-add-btn"),L=document.getElementById("health-config-form"),b=document.getElementById("health-form-title"),M=document.getElementById("health-form-cancel"),k=document.getElementById("health-form-save");let B=null;function S(g){return g>=99.9?"var(--ok-fg)":g>=95?"#f39c12":"var(--bad-fg)"}function T(g){const u={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: ${u[g]||"var(--muted)"}20; color: ${u[g]||"var(--muted)"};">${g}</span>`}async function j(){try{const u=await(await fetch("/api/v1/health-checks/status")).json();if(!u.success||!u.status||Object.keys(u.status).length===0){N.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 f=Object.values(u.status);let m='<table style="width: 100%; border-collapse: collapse; font-size: 0.85rem;">';m+='<tr style="border-bottom: 1px solid var(--border); color: var(--muted); text-align: left;">',m+='<th style="padding: 8px;">Service</th><th style="padding: 8px;">Status</th>',m+='<th style="padding: 8px;">Uptime 24h</th><th style="padding: 8px;">Uptime 7d</th>',m+='<th style="padding: 8px;">Avg Response</th><th style="padding: 8px;">Last Check</th></tr>';for(const p of f){const d=p.status==="up",c=d?"var(--dot-ok)":"var(--dot-bad)",i=p.uptime?.["24h"]??"-",$=p.uptime?.["7d"]??"-",y=p.avgResponseTime!=null?Math.round(p.avgResponseTime)+"ms":"-",n=p.timestamp?timeAgo(p.timestamp):"-";m+=`<tr style="border-bottom: 1px solid var(--border); cursor: pointer;" data-health-id="${escapeHtml(p.serviceId)}">`,m+=`<td style="padding: 8px; font-weight: 500;">${escapeHtml(p.name||p.serviceId)}</td>`,m+=`<td style="padding: 8px;"><span style="display: inline-block; width: 8px; height: 8px; border-radius: 50%; background: ${c}; margin-right: 6px;"></span>${d?"Up":"Down"}</td>`,m+=`<td style="padding: 8px; color: ${typeof i=="number"?S(i):"var(--muted)"};">${typeof i=="number"?i.toFixed(1)+"%":i}</td>`,m+=`<td style="padding: 8px; color: ${typeof $=="number"?S($):"var(--muted)"};">${typeof $=="number"?$.toFixed(1)+"%":$}</td>`,m+=`<td style="padding: 8px;">${y}</td>`,m+=`<td style="padding: 8px; color: var(--muted);">${n}</td>`,m+="</tr>",m+=`<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 details...</div></td></tr>`}m+="</table>",N.innerHTML=m,A.textContent="Updated "+new Date().toLocaleTimeString(),N.querySelectorAll("tr[data-health-id]").forEach(p=>{p.addEventListener("click",async()=>{const d=p.dataset.healthId,c=document.getElementById("health-detail-"+d);if(c){if(c.style.display!=="none"){c.style.display="none";return}c.style.display="";try{const $=await(await fetch(`/api/v1/health-checks/${d}/stats?hours=24`)).json();if($.success&&$.stats){const y=$.stats,n=y.responseTime||{};c.querySelector("td").innerHTML=`
                <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>${y.totalChecks||0}</strong></div>
                  <div><span style="color: var(--muted);">Uptime</span><br><strong style="color: ${S(y.uptime||0)};">${(y.uptime||0).toFixed(2)}%</strong></div>
                  <div><span style="color: var(--muted);">Avg Response</span><br><strong>${Math.round(n.avg||0)}ms</strong></div>
                  <div><span style="color: var(--muted);">P95 / P99</span><br><strong>${Math.round(n.p95||0)}ms / ${Math.round(n.p99||0)}ms</strong></div>
                  <div><span style="color: var(--muted);">Min Response</span><br><strong>${Math.round(n.min||0)}ms</strong></div>
                  <div><span style="color: var(--muted);">Max Response</span><br><strong>${Math.round(n.max||0)}ms</strong></div>
                  <div><span style="color: var(--muted);">Up Checks</span><br><strong style="color: var(--ok-fg);">${y.upChecks||0}</strong></div>
                  <div><span style="color: var(--muted);">Down Checks</span><br><strong style="color: var(--bad-fg);">${y.downChecks||0}</strong></div>
                </div>`}else c.querySelector("td").innerHTML='<div class="panel-empty">No detailed stats available for this period.</div>'}catch(i){c.querySelector("td").innerHTML=`<div class="panel-empty" style="color: var(--bad-fg);">Failed: ${escapeHtml(i.message)}</div>`}}})})}catch(g){N.innerHTML=`<div class="panel-empty" style="color: var(--bad-fg);">Failed to load health status: ${escapeHtml(g.message)}</div>`}}async function H(){try{const[g,u]=await Promise.all([fetch("/api/v1/health-checks/incidents"),fetch("/api/v1/health-checks/incidents/history?limit=50")]),f=await g.json(),m=await u.json();let p="";const d=f.success&&f.incidents?f.incidents:[];if(d.length>0){p+='<div style="margin-bottom: 16px;"><h4 style="color: var(--bad-fg); margin: 0 0 8px;">Open Incidents ('+d.length+")</h4>";for(const i of d)p+=`<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(i.serviceId)}</span>
              <span>${T(i.severity)}</span>
            </div>
            <div style="font-size: 0.82rem; color: var(--muted); margin-top: 4px;">${escapeHtml(i.message)}</div>
            <div style="font-size: 0.75rem; color: var(--muted); margin-top: 4px;">Started ${timeAgo(i.createdAt)} \xB7 ${i.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 c=m.success&&m.history?m.history:[];if(c.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 i of c){const $=i.status==="resolved",y=$&&i.duration?i.duration<6e4?Math.round(i.duration/1e3)+"s":Math.round(i.duration/6e4)+"m":"-";p+='<tr style="border-bottom: 1px solid var(--border);">',p+=`<td style="padding: 6px;">${escapeHtml(i.serviceId)}</td>`,p+=`<td style="padding: 6px;">${escapeHtml(i.type)}</td>`,p+=`<td style="padding: 6px;">${T(i.severity)}</td>`,p+=`<td style="padding: 6px;"><span style="color: ${$?"var(--ok-fg)":"var(--bad-fg)"};">${i.status}</span></td>`,p+=`<td style="padding: 6px;">${y}</td>`,p+=`<td style="padding: 6px; color: var(--muted);">${timeAgo(i.createdAt)}</td>`,p+="</tr>"}p+="</table>"}O.innerHTML=p||'<div class="panel-empty"><span class="empty-icon">\u{1F6A8}</span>No incidents recorded yet.</div>'}catch(g){O.innerHTML=`<div class="panel-empty" style="color: var(--bad-fg);">Failed: ${escapeHtml(g.message)}</div>`}}async function R(){try{const u=await(await fetch("/api/v1/health-checks/status")).json(),f=u.success&&u.status?Object.values(u.status):[];if(f.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 m='<table style="width: 100%; border-collapse: collapse; font-size: 0.85rem;">';m+='<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 f){const d=p.status==="up";m+='<tr style="border-bottom: 1px solid var(--border);">',m+=`<td style="padding: 8px; font-weight: 500;">${escapeHtml(p.name||p.serviceId)}</td>`,m+=`<td style="padding: 8px; color: ${d?"var(--ok-fg)":"var(--bad-fg)"};">${d?"Up":"Down"}</td>`,m+=`<td style="padding: 8px;">${p.sla?.target?p.sla.target+"%":"-"}</td>`,m+='<td style="padding: 8px; text-align: right;">',m+=`<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>`,m+=`<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>`,m+="</td></tr>"}m+="</table>",z.innerHTML=m}catch(g){z.innerHTML=`<div class="panel-empty" style="color: var(--bad-fg);">Failed: ${escapeHtml(g.message)}</div>`}}function x(g,u,f,m,p,d,c){B=g||null,b.textContent=g?"Edit Health Check":"Add Health Check",document.getElementById("health-form-id").value=g||"",document.getElementById("health-form-id").disabled=!!g,document.getElementById("health-form-name").value=u||"",document.getElementById("health-form-url").value=f||"",document.getElementById("health-form-timeout").value=m||1e4,document.getElementById("health-form-codes").value=p||"200",document.getElementById("health-form-sla").value=d||99.9,document.getElementById("health-form-slow").value=c||5e3,L.style.display="",v.style.display="none"}function D(){L.style.display="none",v.style.display="",B=null}v?.addEventListener("click",()=>x("","","",1e4,"200",99.9,5e3)),M?.addEventListener("click",D),k?.addEventListener("click",async()=>{const g=B||document.getElementById("health-form-id").value.trim();if(!g)return showNotification("Service ID is required","warning");const u=document.getElementById("health-form-url").value.trim();if(!u)return showNotification("URL is required","warning");const f=document.getElementById("health-form-codes").value.split(",").map(p=>parseInt(p.trim())).filter(Boolean),m={name:document.getElementById("health-form-name").value.trim()||g,url:u,timeout:parseInt(document.getElementById("health-form-timeout").value)||1e4,expectedStatusCodes:f.length?f:[200],sla:{target:parseFloat(document.getElementById("health-form-sla").value)||99.9},slowResponseThreshold:parseInt(document.getElementById("health-form-slow").value)||5e3};try{k.textContent="Saving...",k.disabled=!0;const d=await(await secureFetch(`/api/v1/health-checks/${encodeURIComponent(g)}/configure`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(m)})).json();if(!d.success)throw new Error(d.error||"Save failed");D(),R(),j()}catch(p){showNotification("Error: "+p.message,"error")}finally{k.textContent="Save",k.disabled=!1}}),document.addEventListener("health-edit",async g=>{const u=g.detail;x(u,"","",1e4,"200",99.9,5e3)}),document.addEventListener("health-delete",async g=>{const u=g.detail;if(confirm(`Delete health check for "${u}"?`))try{const m=await(await secureFetch(`/api/v1/health-checks/${encodeURIComponent(u)}/configure`,{method:"DELETE"})).json();if(!m.success)throw new Error(m.error);R(),j()}catch(f){showNotification("Error: "+f.message,"error")}}),E?.addEventListener("click",()=>{h?.classList.add("show"),j()}),wireModal(h,P),w?.addEventListener("click",j),document.querySelector('[data-panel="health-incidents"]')?.addEventListener("click",H),document.querySelector('[data-panel="health-config"]')?.addEventListener("click",R)})(),(function(){injectModal("updates-modal",`<div id="updates-modal" class="weather-modal">
    <div class="weather-modal-content" style="min-width: 750px; max-width: 950px;">
      <h3>\u2B06\uFE0F Update Management</h3>
      <p class="modal-subtitle">
        Check for container image updates, apply them, and manage rollbacks.
      </p>

      <div class="panel-tabs">
        <button class="panel-tab active" data-panel="updates-available">Available</button>
        <button class="panel-tab" data-panel="updates-history">History</button>
        <button class="panel-tab" data-panel="updates-auto">Auto-Update</button>
        <button class="panel-tab" data-panel="updates-dashcaddy" id="updates-dashcaddy-tab">DashCaddy</button>
      </div>

      <!-- Tab: Available Updates -->
      <div id="updates-available" class="panel-section active">
        <div style="margin-bottom: 12px; display: flex; gap: 8px; align-items: center;">
          <button id="updates-check-btn" class="btn-accent-solid">\u{1F50D} Check for Updates</button>
          <button id="updates-update-all-btn" style="display: none; padding: 6px 14px; font-size: 0.82rem; background: #f97316; color: #fff; border: 1px solid #f97316; border-radius: 6px; cursor: pointer;">\u2B06\uFE0F Update All</button>
          <span id="updates-count-badge" style="display: none; padding: 4px 10px; border-radius: 12px; font-size: 0.78rem; font-weight: 600; background: var(--accent); color: var(--bg);"></span>
        </div>
        <div id="updates-available-container" style="max-height: 450px; overflow-y: auto;">
          <div class="panel-empty"><span class="empty-icon">\u{1F4E6}</span> Click "Check for Updates" to scan containers.</div>
        </div>
      </div>

      <!-- Tab: History -->
      <div id="updates-history" class="panel-section">
        <div id="updates-history-container" class="scroll-container">
          <div class="panel-empty"><span class="brand-spinner"></span> Loading update history...</div>
        </div>
      </div>

      <!-- Tab: Auto-Update -->
      <div id="updates-auto" class="panel-section">
        <div id="updates-auto-container" class="scroll-container">
          <div class="panel-empty"><span class="empty-icon">\u{1F916}</span> Loading auto-update configuration...</div>
        </div>
      </div>

      <!-- Tab: DashCaddy Self-Update -->
      <div id="updates-dashcaddy" class="panel-section">
        <div id="dashcaddy-version-info" style="display: flex; align-items: center; gap: 16px; margin-bottom: 16px; padding: 12px; border-radius: 8px; background: var(--bg);">
          <div style="flex: 1;">
            <div style="font-weight: 600; font-size: 1rem;">DashCaddy</div>
            <div id="dashcaddy-current-version" style="color: var(--muted); font-size: 0.85rem;">Loading...</div>
          </div>
          <div id="dashcaddy-update-badge" style="display: none; padding: 4px 12px; border-radius: 12px; font-size: 0.78rem; font-weight: 600; background: var(--accent); color: var(--bg);">Update available</div>
        </div>
        <div id="dashcaddy-update-details" style="display: none; margin-bottom: 16px; padding: 12px; border-radius: 8px; border: 1px solid var(--border);">
          <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px;">
            <span style="font-weight: 600;">New version: <span id="dashcaddy-new-version"></span></span>
            <button id="dashcaddy-apply-btn" class="btn-accent-solid" style="padding: 6px 16px; font-size: 0.85rem;">Update Now</button>
          </div>
          <div id="dashcaddy-changelog" style="font-size: 0.8rem; color: var(--muted); max-height: 120px; overflow-y: auto; white-space: pre-wrap; font-family: var(--font-mono); line-height: 1.5;"></div>
        </div>
        <div id="dashcaddy-status-bar" style="display: none; margin-bottom: 16px; padding: 10px 12px; border-radius: 8px; font-size: 0.85rem;"></div>
        <div style="margin-bottom: 12px;">
          <button id="dashcaddy-check-btn" style="padding: 6px 14px; font-size: 0.82rem;">Check for Updates</button>
          <button id="dashcaddy-rollback-btn" style="padding: 6px 14px; font-size: 0.82rem; margin-left: 6px;">Rollback</button>
        </div>
        <div id="dashcaddy-history-container" style="max-height: 250px; overflow-y: auto;">
          <div class="panel-empty"><span class="empty-icon">\u{1F4E6}</span>No self-update history.</div>
        </div>
      </div>

      <div class="panel-bottom-bar">
        <span id="updates-last-check" class="text-auto-right"></span>
      </div>

      <div class="weather-modal-buttons modal-footer-bar">
        <button id="updates-cancel">Close</button>
      </div>
    </div>
  </div>`);const h=document.getElementById("updates-modal"),E=document.getElementById("updates-btn"),P=document.getElementById("updates-cancel"),w=document.getElementById("updates-check-btn"),N=document.getElementById("updates-available-container"),O=document.getElementById("updates-history-container"),z=document.getElementById("updates-auto-container"),A=document.getElementById("updates-last-check");async function v(){try{const n=await(await fetch("/api/v1/updates/available")).json();if(!n.success)throw new Error(n.error);const e=n.updates||[];if(e.length===0){N.innerHTML='<div class="panel-empty"><span class="empty-icon">\u2705</span>All containers are up to date.</div>',A.textContent="",document.getElementById("updates-update-all-btn").style.display="none",document.getElementById("updates-count-badge").style.display="none",window._pendingUpdates=[];return}let o='<table style="width: 100%; border-collapse: collapse; font-size: 0.85rem;">';o+='<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 t of e){const s=(()=>{const l=window.APPS||[];for(const C of l)if(C.containerId===t.containerId||C.name===t.containerName||C.id===t.containerName)return C.id;return t.containerName})();o+=`<tr data-app-id="${escapeHtml(s)}" style="border-bottom: 1px solid var(--border);">`,o+=`<td style="padding: 8px; font-weight: 500;">${escapeHtml(t.containerName)}</td>`,o+=`<td style="padding: 8px; color: var(--muted);">${escapeHtml(t.imageName)}</td>`,o+=`<td style="padding: 8px;"><code style="font-size: 0.78rem; background: var(--bg); padding: 2px 6px; border-radius: 4px;">${escapeHtml(t.currentDigest)}</code></td>`,o+=`<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(t.latestDigest)}</code></td>`,o+='<td style="padding: 8px; text-align: right;">',o+=`<button class="update-now-btn" data-id="${escapeHtml(t.containerId)}" data-name="${escapeHtml(t.containerName)}" style="padding: 4px 10px; font-size: 0.78rem; background: var(--accent); color: var(--bg); border-color: var(--accent); margin-right: 4px;">Update</button>`,o+=`<button class="rollback-btn" data-id="${escapeHtml(t.containerId)}" data-name="${escapeHtml(t.containerName)}" style="padding: 4px 10px; font-size: 0.78rem;">Rollback</button>`,o+="</td></tr>"}o+="</table>",N.innerHTML=o,A.textContent=e.length+" update(s) available";const a=document.getElementById("updates-count-badge"),r=document.getElementById("updates-update-all-btn");a&&(a.textContent=e.length+" pending",a.style.display=""),r&&e.length>0&&(r.style.display=""),window._pendingUpdates=e,N.querySelectorAll(".update-now-btn").forEach(t=>{t.addEventListener("click",async()=>{const s=t.dataset.id,l=t.dataset.name;if(confirm(`Update "${l}" to the latest version? The container will restart.`)){t.textContent="Updating...",t.disabled=!0;try{const I=await(await secureFetch(`/api/v1/updates/update/${encodeURIComponent(s)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({autoRollback:!0})})).json();if(I.success)t.textContent="Done!",t.style.background="var(--ok-fg)",setTimeout(()=>v(),2e3);else throw new Error(I.error||"Update failed")}catch(C){t.textContent="Failed",t.style.color="var(--bad-fg)",showNotification("Update error: "+C.message,"error"),setTimeout(()=>{t.textContent="Update",t.disabled=!1,t.style.color="",t.style.background=""},3e3)}}})}),N.querySelectorAll(".rollback-btn").forEach(t=>{t.addEventListener("click",async()=>{const s=t.dataset.id,l=t.dataset.name;if(confirm(`Rollback "${l}" to its previous version?`)){t.textContent="Rolling back...",t.disabled=!0;try{const I=await(await secureFetch(`/api/v1/updates/rollback/${encodeURIComponent(s)}`,{method:"POST"})).json();if(I.success)t.textContent="Rolled back!",setTimeout(()=>v(),2e3);else throw new Error(I.error||"Rollback failed")}catch(C){t.textContent="Failed",showNotification("Rollback error: "+C.message,"error"),setTimeout(()=>{t.textContent="Rollback",t.disabled=!1},3e3)}}})})}catch(y){N.innerHTML=`<div class="panel-empty" style="color: var(--bad-fg);">Failed: ${escapeHtml(y.message)}</div>`}}async function L(){const y=window._pendingUpdates||[];if(!y.length)return;const n=document.getElementById("updates-update-all-btn");if(!confirm(`Update all ${y.length} containers? Each will restart.`))return;n.textContent="\u23F3 Updating...",n.disabled=!0;let e=0,o=0;for(const a of y)try{(await(await secureFetch(`/api/v1/updates/update/${encodeURIComponent(a.containerId)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({autoRollback:!0})})).json()).success?e++:o++}catch{o++}n.textContent="\u2705 Done",showNotification(`Update all: ${e} succeeded, ${o} failed.`,e>0&&o===0?"success":"error"),setTimeout(()=>{n.textContent="\u2B06\uFE0F Update All",n.disabled=!1,v()},3e3)}document.getElementById("updates-update-all-btn")?.addEventListener("click",L);async function b(){w.textContent="\u{1F50D} Checking...",w.disabled=!0;try{const n=await(await secureFetch("/api/v1/updates/check",{method:"POST"})).json();if(!n.success)throw new Error(n.error);w.textContent="\u2705 Done!",await v()}catch(y){w.textContent="\u274C Failed",showNotification("Check error: "+y.message,"error")}setTimeout(()=>{w.textContent="\u{1F50D} Check for Updates",w.disabled=!1},3e3)}async function M(){try{O.innerHTML='<div class="panel-empty"><span class="brand-spinner"></span> Loading...</div>';const n=await(await fetch("/api/v1/updates/history?limit=50")).json(),e=n.success&&n.history?n.history:[];if(e.length===0){O.innerHTML='<div class="panel-empty"><span class="empty-icon">\u{1F4CB}</span>No update history yet.</div>';return}let o='<table style="width: 100%; border-collapse: collapse; font-size: 0.82rem;">';o+='<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;">Container</th><th style="padding: 6px; text-align: left;">Image</th><th style="padding: 6px; text-align: left;">Duration</th><th style="padding: 6px; text-align: left;">Status</th></tr>';for(const a of e){const r=a.status==="success",t=a.duration?a.duration<1e3?a.duration+"ms":Math.round(a.duration/1e3)+"s":"-";o+='<tr style="border-bottom: 1px solid var(--border);">',o+=`<td style="padding: 6px; color: var(--muted);">${timeAgo(a.timestamp)}</td>`,o+=`<td style="padding: 6px; font-weight: 500;">${escapeHtml(a.containerName)}</td>`,o+=`<td style="padding: 6px; color: var(--muted);">${escapeHtml(a.imageName)}</td>`,o+=`<td style="padding: 6px;">${t}</td>`,o+=`<td style="padding: 6px;"><span style="color: ${r?"var(--ok-fg)":"var(--bad-fg)"};">${r?"\u2713 success":"\u2717 failed"}</span></td>`,o+="</tr>",!r&&a.error&&(o+=`<tr><td colspan="5" style="padding: 4px 6px 8px; font-size: 0.78rem; color: var(--bad-fg);">${escapeHtml(a.error)}</td></tr>`)}o+="</table>",O.innerHTML=o}catch(y){O.innerHTML=`<div class="panel-empty" style="color: var(--bad-fg);">Failed: ${escapeHtml(y.message)}</div>`}}async function k(){try{z.innerHTML='<div class="panel-empty"><span class="brand-spinner"></span> Loading...</div>';const[y,n]=await Promise.all([fetch("/api/v1/stats/containers"),fetch("/api/v1/updates/auto-update")]),e=await y.json(),o=await n.json(),a=e.success&&e.stats?e.stats:[],r=o.success&&o.config?o.config:{};if(a.length===0){z.innerHTML='<div class="panel-empty"><span class="empty-icon">\u{1F916}</span>No running containers found.</div>';return}let t='<div style="margin-bottom: 12px; font-size: 0.8rem; color: var(--muted);">Auto-updates run during maintenance window (default 2AM-4AM). Daily = every day, Weekly = Sundays, Monthly = 1st of month.</div>';t+='<table style="width: 100%; border-collapse: collapse; font-size: 0.85rem;">',t+='<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;">Schedule</th><th style="padding: 8px; text-align: left;">Window</th><th style="padding: 8px; text-align: left;">Rollback</th><th style="padding: 8px; text-align: left;">Last Run</th><th style="padding: 8px; text-align: right;">Actions</th></tr>';for(const s of a){const l=s.name||s.Names?.[0]?.replace(/^\//,"")||s.Id?.substring(0,12),C=s.containerId||s.Id,I=r[C]||{},F=I.enabled?I.schedule||"weekly":"",q=I.autoRollback!==!1,U=I.maintenanceWindow||"",G=I.lastAutoUpdate?timeAgo(I.lastAutoUpdate):"Never";t+=`<tr style="border-bottom: 1px solid var(--border);" data-container-id="${escapeHtml(C)}">`,t+=`<td style="padding: 8px; font-weight: 500;">${escapeHtml(l)}</td>`,t+=`<td style="padding: 8px;">
          <select class="auto-schedule" data-id="${escapeHtml(C)}" style="padding: 4px 8px; border-radius: 4px; border: 1px solid var(--border); background: var(--bg); color: var(--fg); font-size: 0.82rem;">
            <option value=""${F?"":" selected"}>Disabled</option>
            <option value="daily"${F==="daily"?" selected":""}>Daily</option>
            <option value="weekly"${F==="weekly"?" selected":""}>Weekly</option>
            <option value="monthly"${F==="monthly"?" selected":""}>Monthly</option>
          </select></td>`,t+=`<td style="padding: 8px;"><input type="text" class="auto-window" data-id="${escapeHtml(C)}" value="${escapeHtml(U)}" 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>`,t+=`<td style="padding: 8px;"><input type="checkbox" class="auto-rollback" data-id="${escapeHtml(C)}"${q?" checked":""} /></td>`,t+=`<td style="padding: 8px; font-size: 0.78rem; color: var(--muted);">${G}</td>`,t+=`<td style="padding: 8px; text-align: right;"><button class="save-auto-btn" data-id="${escapeHtml(C)}" data-name="${escapeHtml(l)}" style="padding: 4px 10px; font-size: 0.78rem;">Save</button></td>`,t+="</tr>"}t+="</table>",z.innerHTML=t,z.querySelectorAll(".save-auto-btn").forEach(s=>{s.addEventListener("click",async()=>{const l=s.dataset.id,C=s.closest("tr"),I=C.querySelector(".auto-schedule").value,F=C.querySelector(".auto-rollback").checked,q=C.querySelector(".auto-window").value.trim();s.textContent="Saving...",s.disabled=!0;try{const G=await(await secureFetch(`/api/v1/updates/auto-update/${encodeURIComponent(l)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({enabled:!!I,schedule:I||"weekly",autoRollback:F,maintenanceWindow:q||void 0})})).json();if(G.success)s.textContent="\u2713 Saved";else throw new Error(G.error)}catch(U){s.textContent="\u2717 Error",showNotification("Save error: "+U.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 B=document.getElementById("dashcaddy-current-version"),S=document.getElementById("dashcaddy-update-badge"),T=document.getElementById("dashcaddy-update-details"),j=document.getElementById("dashcaddy-new-version"),H=document.getElementById("dashcaddy-changelog"),R=document.getElementById("dashcaddy-apply-btn"),x=document.getElementById("dashcaddy-check-btn"),D=document.getElementById("dashcaddy-rollback-btn"),g=document.getElementById("dashcaddy-status-bar"),u=document.getElementById("dashcaddy-history-container");let f=null;function m(y,n){g&&(g.style.display="block",g.style.background=n==="error"?"var(--bad-bg)":n==="success"?"var(--ok-bg)":"var(--bg)",g.style.color=n==="error"?"var(--bad-fg)":n==="success"?"var(--ok-fg)":"var(--fg)",g.textContent=y)}async function p(){try{const n=await(await fetch("/api/v1/system/version")).json();if(n.success){const e=n.commit&&n.commit!=="unknown"?n.commit:null;B.textContent="v"+n.version+(e?" ("+e.substring(0,7)+")":"")}}catch{B.textContent="Unable to fetch version"}}async function d(y){y||(x.textContent="Checking...",x.disabled=!0);try{const e=await(await fetch("/api/v1/system/update-check")).json();if(f=e,e.success&&e.available&&e.remote){S.style.display="",T.style.display="",j.textContent="v"+e.remote.version,H.textContent=e.remote.changelog||"No changelog available.";const o=document.getElementById("updates-btn");if(o&&!o.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);",o.style.position="relative",o.appendChild(r)}const a=document.getElementById("updates-dashcaddy-tab");if(a&&!a.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;",a.appendChild(r)}}else S.style.display="none",T.style.display="none",await p(),y||m("You are running the latest version.","success");y||(x.textContent="Check for Updates",x.disabled=!1)}catch(n){y||(m("Failed to check: "+n.message,"error"),x.textContent="Check for Updates",x.disabled=!1)}}async function c(){if(!confirm("Apply DashCaddy update? The API container will restart."))return!1;R.textContent="Updating...",R.disabled=!0,m("Downloading and applying update...","info");try{const n=await(await secureFetch("/api/v1/system/update-apply",{method:"POST"})).json();if(n.success)return m("Update initiated: v"+(n.fromVersion||"?")+" \u2192 v"+(n.toVersion||"?")+". The container will restart shortly.","success"),R.textContent="Applied!",document.querySelectorAll(".update-dot").forEach(e=>e.remove()),!0;throw new Error(n.error||"Update failed")}catch(y){throw m("Update failed: "+y.message,"error"),R.textContent="Update Now",R.disabled=!1,y}}async function i(){try{const n=await(await fetch("/api/v1/system/update-history")).json(),e=n.success&&n.history?n.history:[];if(e.length===0){u.innerHTML='<div class="panel-empty"><span class="empty-icon">\u{1F4E6}</span>No self-update history.</div>';return}let o='<table style="width: 100%; border-collapse: collapse; font-size: 0.82rem;">';o+='<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;">Version</th><th style="padding: 6px; text-align: left;">From</th><th style="padding: 6px; text-align: left;">Status</th></tr>';for(const a of e){const r=a.status==="success"?"\u2713 success":a.status==="pending"?"\u23F3 pending":a.status==="partial"?"\u26A0 partial":"\u2717 "+a.status,t=a.status==="success"?"var(--ok-fg)":a.status==="pending"?"var(--muted)":"var(--bad-fg)";o+='<tr style="border-bottom: 1px solid var(--border);">',o+='<td style="padding: 6px; color: var(--muted);">'+timeAgo(a.timestamp)+"</td>",o+='<td style="padding: 6px; font-weight: 500;">v'+escapeHtml(a.version)+(a.rollback?" (rollback)":"")+"</td>",o+='<td style="padding: 6px; color: var(--muted);">v'+escapeHtml(a.fromVersion||"?")+"</td>",o+='<td style="padding: 6px;"><span style="color: '+t+';">'+r+"</span></td>",o+="</tr>",a.error&&(o+='<tr><td colspan="4" style="padding: 4px 6px 8px; font-size: 0.78rem; color: var(--bad-fg);">'+escapeHtml(a.error)+"</td></tr>"),a.note&&(o+='<tr><td colspan="4" style="padding: 4px 6px 8px; font-size: 0.78rem; color: var(--muted);">'+escapeHtml(a.note)+"</td></tr>")}o+="</table>",u.innerHTML=o}catch(y){u.innerHTML='<div class="panel-empty" style="color: var(--bad-fg);">Failed: '+escapeHtml(y.message)+"</div>"}}async function $(){try{const n=await(await fetch("/api/v1/system/rollback-versions")).json(),e=n.success&&n.versions?n.versions:[];if(e.length===0){showNotification("No rollback versions available.","info");return}const o=prompt(`Available rollback versions:
`+e.join(`
`)+`

Enter version to rollback to:`);if(!o)return;if(!e.includes(o)){showNotification("Invalid version: "+o,"error");return}if(!confirm("Rollback DashCaddy to v"+o+"? The container will restart."))return;m("Rolling back to v"+o+"...","info");const r=await(await secureFetch("/api/v1/system/rollback",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({version:o})})).json();if(r.success)m("Rollback to v"+o+" initiated. Container will restart.","success");else throw new Error(r.error||"Rollback failed")}catch(y){m("Rollback failed: "+y.message,"error")}}x?.addEventListener("click",()=>d(!1)),R?.addEventListener("click",()=>c().catch(()=>{})),D?.addEventListener("click",$),w?.addEventListener("click",b),E?.addEventListener("click",()=>{h?.classList.add("show"),v()}),wireModal(h,P),window.openUpdateModal=function(y){h?.classList.add("show"),v().then(()=>{if(!y)return;const n=N.querySelector(`[data-app-id="${y}"]`);n&&(n.scrollIntoView({behavior:"smooth",block:"center"}),n.style.background="rgba(249,115,22,0.15)",setTimeout(()=>{n.style.background=""},3e3))})},document.querySelector('[data-panel="updates-history"]')?.addEventListener("click",M),document.querySelector('[data-panel="updates-auto"]')?.addEventListener("click",k),document.querySelector('[data-panel="updates-dashcaddy"]')?.addEventListener("click",()=>{p(),i(),f||d(!0)}),window.dcApplyUpdate=c,window.dcCheckForUpdate=d,setTimeout(()=>d(!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>

      <div class="panel-tabs">
        <button class="panel-tab active" data-panel="dr-volumes">Volumes</button>
        <button class="panel-tab" data-panel="dr-networks">Networks</button>
        <button class="panel-tab" data-panel="dr-disk">Disk Usage</button>
      </div>

      <!-- Volumes -->
      <div id="dr-volumes" class="panel-section active">
        <div style="display: flex; gap: 8px; margin-bottom: 12px;">
          <input type="text" id="dr-vol-name" placeholder="Volume name" style="flex: 1; padding: 6px 10px; border: 1px solid var(--border); border-radius: 6px; background: var(--bg); color: var(--fg);" />
          <button id="dr-vol-create" class="btn-accent-solid" style="padding: 6px 14px; font-size: 0.82rem;">Create</button>
        </div>
        <div id="dr-vol-list" class="scroll-container" style="max-height: 400px;">
          <div class="panel-empty"><span class="brand-spinner"></span> Loading...</div>
        </div>
      </div>

      <!-- Networks -->
      <div id="dr-networks" class="panel-section">
        <div style="display: flex; gap: 8px; margin-bottom: 12px;">
          <input type="text" id="dr-net-name" placeholder="Network name" style="flex: 1; padding: 6px 10px; border: 1px solid var(--border); border-radius: 6px; background: var(--bg); color: var(--fg);" />
          <select id="dr-net-driver" style="padding: 6px 10px; border: 1px solid var(--border); border-radius: 6px; background: var(--bg); color: var(--fg);">
            <option value="bridge">bridge</option>
            <option value="overlay">overlay</option>
            <option value="host">host</option>
          </select>
          <button id="dr-net-create" class="btn-accent-solid" style="padding: 6px 14px; font-size: 0.82rem;">Create</button>
        </div>
        <div id="dr-net-list" class="scroll-container" style="max-height: 400px;">
          <div class="panel-empty"><span class="brand-spinner"></span> Loading...</div>
        </div>
      </div>

      <!-- Disk Usage -->
      <div id="dr-disk" class="panel-section">
        <div id="dr-disk-content">
          <div class="panel-empty"><span class="brand-spinner"></span> Loading...</div>
        </div>
      </div>

      <div class="weather-modal-buttons modal-footer-bar">
        <button id="dr-close">Close</button>
      </div>
    </div>
  </div>`);const h=document.getElementById("docker-resources-modal"),E=document.getElementById("docker-resources-btn"),P=document.getElementById("dr-close");function w(A){if(!A||A===0)return"0 B";const v=["B","KB","MB","GB","TB"],L=Math.floor(Math.log(Math.abs(A))/Math.log(1024));return(A/Math.pow(1024,L)).toFixed(1)+" "+v[L]}async function N(){const A=document.getElementById("dr-vol-list");try{const L=(await getJSON("/api/v1/docker/volumes")).volumes||[];if(L.length===0){A.innerHTML='<div class="panel-empty"><span class="empty-icon">\u{1F4E6}</span>No volumes found.</div>';return}let b='<table style="width: 100%; border-collapse: collapse; font-size: 0.82rem;">';b+='<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 M of L){const k=M.name==="buildkit"||M.name.length===64;b+='<tr style="border-bottom: 1px solid var(--border);">',b+=`<td style="padding: 6px; font-weight: 500; max-width: 300px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;" title="${escapeHtml(M.name)}">${escapeHtml(M.name.length>40?M.name.substring(0,37)+"...":M.name)}</td>`,b+=`<td style="padding: 6px; text-align: center; color: var(--muted);">${escapeHtml(M.driver)}</td>`,b+=`<td style="padding: 6px; text-align: center; color: var(--muted);">${escapeHtml(M.scope)}</td>`,b+='<td style="padding: 6px; text-align: right;">',k||(b+=`<button class="dr-vol-del" data-name="${escapeHtml(M.name)}" style="padding: 3px 8px; font-size: 0.75rem; color: var(--bad-fg);">Delete</button>`),b+="</td></tr>"}b+="</table>",A.innerHTML=b,A.querySelectorAll(".dr-vol-del").forEach(M=>{M.addEventListener("click",async()=>{if(confirm(`Delete volume "${M.dataset.name}"? Data will be lost.`)){M.textContent="...",M.disabled=!0;try{await deleteAPI(`/api/v1/docker/volumes/${encodeURIComponent(M.dataset.name)}?force=true`),N()}catch(k){showNotification("Delete failed: "+k.message,"error"),M.textContent="Delete",M.disabled=!1}}})})}catch(v){A.innerHTML=`<div class="panel-empty" style="color: var(--bad-fg);">Failed: ${escapeHtml(v.message)}</div>`}}document.getElementById("dr-vol-create")?.addEventListener("click",async()=>{const A=document.getElementById("dr-vol-name"),v=A.value.trim();if(!v){showNotification("Enter a volume name","warning");return}try{await postJSON("/api/v1/docker/volumes",{name:v}),A.value="",showNotification(`Volume "${v}" created`,"success"),N()}catch(L){showNotification("Create failed: "+L.message,"error")}});async function O(){const A=document.getElementById("dr-net-list");try{const L=(await getJSON("/api/v1/docker/networks")).networks||[];if(L.length===0){A.innerHTML='<div class="panel-empty"><span class="empty-icon">\u{1F310}</span>No networks found.</div>';return}let b='<table style="width: 100%; border-collapse: collapse; font-size: 0.82rem;">';b+='<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 M of L){const k=["bridge","host","none"].includes(M.name);b+='<tr style="border-bottom: 1px solid var(--border);">',b+=`<td style="padding: 6px; font-weight: 500;">${escapeHtml(M.name)}</td>`,b+=`<td style="padding: 6px; text-align: center; color: var(--muted);">${escapeHtml(M.driver)}</td>`,b+=`<td style="padding: 6px; text-align: center; color: var(--muted);">${escapeHtml(M.scope)}</td>`,b+=`<td style="padding: 6px; text-align: center;">${M.containers}</td>`,b+='<td style="padding: 6px; text-align: right;">',k||(b+=`<button class="dr-net-del" data-id="${escapeHtml(M.id)}" data-name="${escapeHtml(M.name)}" style="padding: 3px 8px; font-size: 0.75rem; color: var(--bad-fg);">Delete</button>`),b+="</td></tr>"}b+="</table>",A.innerHTML=b,A.querySelectorAll(".dr-net-del").forEach(M=>{M.addEventListener("click",async()=>{if(confirm(`Delete network "${M.dataset.name}"?`)){M.textContent="...",M.disabled=!0;try{await deleteAPI(`/api/v1/docker/networks/${encodeURIComponent(M.dataset.id)}`),O()}catch(k){showNotification("Delete failed: "+k.message,"error"),M.textContent="Delete",M.disabled=!1}}})})}catch(v){A.innerHTML=`<div class="panel-empty" style="color: var(--bad-fg);">Failed: ${escapeHtml(v.message)}</div>`}}document.getElementById("dr-net-create")?.addEventListener("click",async()=>{const A=document.getElementById("dr-net-name"),v=document.getElementById("dr-net-driver"),L=A.value.trim();if(!L){showNotification("Enter a network name","warning");return}try{await postJSON("/api/v1/docker/networks",{name:L,driver:v.value}),A.value="",showNotification(`Network "${L}" created`,"success"),O()}catch(b){showNotification("Create failed: "+b.message,"error")}});async function z(){const A=document.getElementById("dr-disk-content");try{const v=await getJSON("/api/v1/docker/disk-usage"),L=[{label:"Images",icon:"\u{1F4C0}",count:v.images.count,size:v.images.size,reclaimable:v.images.reclaimable},{label:"Containers",icon:"\u{1F4E6}",count:v.containers.count,size:v.containers.size,extra:`${v.containers.running} running`},{label:"Volumes",icon:"\u{1F4BE}",count:v.volumes.count,size:v.volumes.size,reclaimable:v.volumes.reclaimable},{label:"Build Cache",icon:"\u{1F527}",count:v.buildCache.count,size:v.buildCache.size,reclaimable:v.buildCache.reclaimable}];let b=`<div style="font-size: 1.1rem; font-weight: 600; margin-bottom: 16px;">Total: ${w(v.totalSize)}</div>`;b+='<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 12px;">';for(const M of L)b+='<div style="padding: 14px; background: var(--bg); border-radius: 8px; border: 1px solid var(--border);">',b+=`<div style="font-weight: 600; margin-bottom: 6px;">${M.icon} ${M.label} <span style="color: var(--muted); font-weight: 400; font-size: 0.82rem;">(${M.count})</span></div>`,b+=`<div style="font-size: 1.1rem; font-weight: 600; color: var(--accent);">${w(M.size)}</div>`,M.reclaimable>0&&(b+=`<div style="font-size: 0.78rem; color: var(--muted);">Reclaimable: ${w(M.reclaimable)}</div>`),M.extra&&(b+=`<div style="font-size: 0.78rem; color: var(--muted);">${M.extra}</div>`),b+="</div>";b+="</div>",A.innerHTML=b}catch(v){A.innerHTML=`<div class="panel-empty" style="color: var(--bad-fg);">Failed: ${escapeHtml(v.message)}</div>`}}E?.addEventListener("click",()=>{h?.classList.add("show"),N()}),wireModal(h,P),document.querySelector('[data-panel="dr-networks"]')?.addEventListener("click",O),document.querySelector('[data-panel="dr-disk"]')?.addEventListener("click",z)})(),(function(){injectModal("compose-import-modal",`<div id="compose-import-modal" class="weather-modal">
    <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>

      <!-- Step 1: Paste YAML -->
      <div id="compose-step-paste">
        <div style="margin-bottom: 12px;">
          <label class="form-label-accent-sm">Stack Name</label>
          <input type="text" id="compose-stack-name" placeholder="my-stack" value="" style="width: 100%; padding: 8px 10px; border: 1px solid var(--border); border-radius: 6px; background: var(--bg); color: var(--fg);" />
        </div>
        <div style="margin-bottom: 12px;">
          <label class="form-label-accent-sm">docker-compose.yml</label>
          <textarea id="compose-yaml" rows="14" placeholder="version: '3'&#10;services:&#10;  web:&#10;    image: nginx:latest&#10;    ports:&#10;      - '8080:80'" style="width: 100%; padding: 10px; font-family: monospace; font-size: 0.82rem; border: 1px solid var(--border); border-radius: 6px; background: var(--bg); color: var(--fg); resize: vertical;"></textarea>
          <div style="margin-top: 6px;">
            <label style="display: inline-flex; align-items: center; gap: 6px; cursor: pointer; font-size: 0.82rem; color: var(--muted);">
              <input type="file" id="compose-file-upload" accept=".yml,.yaml" style="display: none;" />
              <span style="text-decoration: underline;">or upload a file</span>
            </label>
          </div>
        </div>
        <div class="weather-modal-buttons modal-footer-bar">
          <button id="compose-parse-btn" class="btn-accent-solid" style="padding: 8px 20px;">Parse & Preview</button>
          <button id="compose-cancel">Cancel</button>
        </div>
      </div>

      <!-- Step 2: Preview -->
      <div id="compose-step-preview" style="display: none;">
        <div id="compose-preview-content"></div>
        <div class="weather-modal-buttons modal-footer-bar" style="margin-top: 16px;">
          <button id="compose-deploy-btn" class="btn-accent-solid" style="padding: 8px 20px;">Deploy All</button>
          <button id="compose-back-btn">Back</button>
        </div>
      </div>

      <!-- Step 3: Progress -->
      <div id="compose-step-progress" style="display: none;">
        <div id="compose-progress-content"></div>
      </div>
    </div>
  </div>`);const h=document.getElementById("compose-import-modal"),E=document.getElementById("compose-import-btn"),P=document.getElementById("compose-cancel");wireModal(h,P);let w=null;function N(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"}E?.addEventListener("click",()=>{N("paste"),w=null,document.getElementById("compose-yaml").value="",document.getElementById("compose-stack-name").value="",h?.classList.add("show")}),document.getElementById("compose-file-upload")?.addEventListener("change",z=>{const A=z.target.files[0];if(!A)return;const v=new FileReader;v.onload=()=>{document.getElementById("compose-yaml").value=v.result},v.readAsText(A)}),document.getElementById("compose-parse-btn")?.addEventListener("click",async()=>{const z=document.getElementById("compose-yaml").value.trim(),A=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"),L=v.textContent;v.textContent="Parsing...",v.disabled=!0;try{const b=await postJSON("/api/v1/apps/import-compose",{yaml:z,stackName:A});w=b,w.stackName=A,O(b),N("preview")}catch(b){showNotification("Parse failed: "+b.message,"error")}finally{v.textContent=L,v.disabled=!1}});function O(z){const A=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(L=>`<code>${escapeHtml(L)}</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(L=>`<code>${escapeHtml(L)}</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 L of z.services){const b=L.skip?"var(--bad-fg)":"var(--border)";if(v+=`<div style="padding: 10px 14px; border: 1px solid ${b}; border-radius: 8px; margin-bottom: 8px; background: var(--bg);">`,v+=`<div style="font-weight: 600; font-size: 0.9rem;">${escapeHtml(L.name)}`,L.skip&&(v+=` <span style="color: var(--bad-fg); font-weight: 400; font-size: 0.78rem;">\u2014 skipped: ${escapeHtml(L.reason)}</span>`),v+="</div>",!L.skip&&(v+=`<div style="font-size: 0.8rem; color: var(--muted); margin-top: 4px;">Image: <code>${escapeHtml(L.image)}</code></div>`,L.ports?.length&&(v+=`<div style="font-size: 0.8rem; color: var(--muted);">Ports: ${L.ports.map(M=>`${M.host}:${M.container}`).join(", ")}</div>`),L.volumes?.length&&(v+=`<div style="font-size: 0.8rem; color: var(--muted);">Volumes: ${L.volumes.length}</div>`),Object.keys(L.environment||{}).length&&(v+=`<div style="font-size: 0.8rem; color: var(--muted);">Env vars: ${Object.keys(L.environment).length}</div>`),L.envFileWarning&&(v+=`<div style="font-size: 0.78rem; color: var(--bad-fg);">\u26A0 ${escapeHtml(L.envFileWarning)}</div>`),L.resources?.cpus||L.resources?.memory)){const M=[];L.resources.cpus&&M.push(`CPU: ${L.resources.cpus}`),L.resources.memory&&M.push(`Mem: ${L.resources.memory}MB`),v+=`<div style="font-size: 0.8rem; color: var(--muted);">Limits: ${M.join(", ")}</div>`}v+="</div>"}v+="</div>",A.innerHTML=v}document.getElementById("compose-back-btn")?.addEventListener("click",()=>N("paste")),document.getElementById("compose-deploy-btn")?.addEventListener("click",async()=>{if(!w)return;const z=document.getElementById("compose-deploy-btn");z.textContent="Deploying...",z.disabled=!0,N("progress");const A=document.getElementById("compose-progress-content");A.innerHTML='<div class="panel-empty"><span class="brand-spinner"></span> Deploying services...</div>';try{const v=await postJSON("/api/v1/apps/deploy-compose",{services:w.services,networks:w.networks,stackName:w.stackName});let L=`<div style="font-weight: 600; margin-bottom: 12px;">Stack "${escapeHtml(v.stackName)}" \u2014 Deployment Complete</div>`;L+='<div class="scroll-container" style="max-height: 350px;">';for(const b of v.results){const M=b.status==="deployed"||b.status==="created"?"\u2705":b.status==="exists"?"\u26A1":b.status==="skipped"?"\u23ED":"\u274C";L+='<div style="padding: 8px 12px; border-bottom: 1px solid var(--border); font-size: 0.85rem;">',L+=`${M} <strong>${escapeHtml(b.name)}</strong> (${b.type}) \u2014 ${escapeHtml(b.status)}`,b.error&&(L+=` <span style="color: var(--bad-fg);">${escapeHtml(b.error)}</span>`),b.subdomain&&(L+=` \u2192 <code>${escapeHtml(b.subdomain)}</code>`),b.reason&&(L+=` <span style="color: var(--muted);">(${escapeHtml(b.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>',A.innerHTML=L,document.getElementById("compose-done-btn")?.addEventListener("click",()=>{h?.classList.remove("show"),typeof window.loadServices=="function"&&window.loadServices().then(()=>{typeof window.buildGrid=="function"&&window.buildGrid()})}),showNotification(`Stack "${v.stackName}" deployed`,"success")}catch(v){A.innerHTML=`<div class="panel-empty" style="color: var(--bad-fg);">Deployment failed: ${escapeHtml(v.message)}</div>
        <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",()=>N("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>
      <div id="exec-terminal" style="height: 420px; border-radius: 6px; overflow: hidden; background: #1e1e1e;"></div>
      <div class="weather-modal-buttons modal-footer-bar" style="margin-top: 8px; padding-bottom: 12px;">
        <button id="exec-close">Close</button>
      </div>
    </div>
  </div>`);const h=document.getElementById("exec-modal"),E=document.getElementById("exec-terminal"),P=document.getElementById("exec-close");let w=null,N=null,O=null;function z(){if(N){try{N.close()}catch{}N=null}if(w){try{w.dispose()}catch{}w=null}O=null,E.innerHTML=""}function A(v,L){if(z(),document.getElementById("exec-title").textContent=`Terminal \u2014 ${L||v}`,h?.classList.add("show"),typeof Terminal>"u"){E.innerHTML='<div style="color: #f44; padding: 20px; font-family: monospace;">xterm.js not loaded</div>';return}w=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"&&(O=new FitAddon.FitAddon,w.loadAddon(O)),w.open(E),O&&setTimeout(()=>O.fit(),50);const b=location.protocol==="https:"?"wss:":"ws:";N=new WebSocket(`${b}//${location.host}/ws/exec/${encodeURIComponent(v)}`),N.binaryType="arraybuffer",N.onopen=()=>{if(w.writeln("\x1B[32mConnecting...\x1B[0m"),O){const k=O.proposeDimensions();k&&N.send(JSON.stringify({type:"resize",cols:k.cols,rows:k.rows}))}},N.onmessage=k=>{if(typeof k.data=="string"){try{const B=JSON.parse(k.data);if(B.type==="connected"){w.writeln(`\x1B[32mConnected (${B.shell})\x1B[0m\r
`);return}if(B.type==="error"){w.writeln(`\x1B[31mError: ${B.message}\x1B[0m`);return}if(B.type==="exit"){w.writeln(`\r
\x1B[33mSession ended.\x1B[0m`);return}}catch{}w.write(k.data)}else w.write(new Uint8Array(k.data))},N.onclose=()=>{w&&w.writeln(`\r
\x1B[33mDisconnected.\x1B[0m`)},N.onerror=()=>{w&&w.writeln(`\r
\x1B[31mConnection error.\x1B[0m`)},w.onData(k=>{N&&N.readyState===WebSocket.OPEN&&N.send(k)}),w.onResize(({cols:k,rows:B})=>{N&&N.readyState===WebSocket.OPEN&&N.send(JSON.stringify({type:"resize",cols:k,rows:B}))});const M=()=>{O&&O.fit()};window.addEventListener("resize",M),h._resizeHandler=M}P?.addEventListener("click",()=>{z(),h._resizeHandler&&window.removeEventListener("resize",h._resizeHandler),h?.classList.remove("show")}),h?.addEventListener("click",v=>{v.target===h&&(z(),h._resizeHandler&&window.removeEventListener("resize",h._resizeHandler),h?.classList.remove("show"))}),window.openExecModal=A})(),(function(){injectModal("audit-modal",`<div id="audit-modal" class="weather-modal">
    <div class="weather-modal-content" style="min-width: 850px; max-width: 1050px;">
      <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>
        <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="service">Services</option>
          <option value="container">Containers</option>
          <option value="caddy">Caddy</option>
          <option value="dns">DNS</option>
          <option value="backup">Backups</option>
          <option value="config">Config</option>
          <option value="auth">Auth</option>
        </select>
        <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>
      </div>

      <div id="audit-log-container" class="scroll-container">
        <div class="panel-empty"><span class="brand-spinner"></span> Loading audit log...</div>
      </div>

      <div style="margin-top: 12px; text-align: center;">
        <button id="audit-load-more" style="display: none; padding: 6px 16px; font-size: 0.8rem;">Load More</button>
      </div>

      <div class="weather-modal-buttons modal-footer-bar">
        <button id="audit-cancel">Close</button>
      </div>
    </div>
  </div>`);const h=document.getElementById("audit-modal"),E=document.getElementById("audit-log-btn"),P=document.getElementById("audit-cancel"),w=document.getElementById("audit-refresh-btn"),N=document.getElementById("audit-clear-btn"),O=document.getElementById("audit-filter"),z=document.getElementById("audit-log-container"),A=document.getElementById("audit-load-more");let v=0;const L=50;async function b(M){try{M||(v=0,z.innerHTML='<div class="panel-empty"><span class="brand-spinner"></span> Loading...</div>');const k=O.value;let B=`/api/v1/audit-logs?limit=${L}&offset=${v}`;k&&(B+=`&action=${encodeURIComponent(k)}`);const T=await(await fetch(B)).json(),j=T.success&&T.entries?T.entries:[];if(j.length===0&&!M){z.innerHTML='<div class="panel-empty"><span class="empty-icon">\u{1F4DC}</span>No audit log entries yet. Actions will be logged automatically.</div>',A.style.display="none";return}let H="";M||(H='<table style="width: 100%; border-collapse: collapse; font-size: 0.82rem;">',H+='<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 R of j){const x=R.outcome==="success";H+='<tr style="border-bottom: 1px solid var(--border); cursor: pointer;" class="audit-row">',H+=`<td style="padding: 6px; color: var(--muted);">${timeAgo(R.timestamp)}</td>`,H+=`<td style="padding: 6px; font-family: monospace; font-size: 0.78rem;">${escapeHtml(R.ip||"-")}</td>`,H+=`<td style="padding: 6px; font-weight: 500;">${escapeHtml(R.action||"-")}</td>`,H+=`<td style="padding: 6px;">${escapeHtml(R.resource||"-")}</td>`,H+=`<td style="padding: 6px;"><span style="color: ${x?"var(--ok-fg)":"var(--bad-fg)"};">${x?"\u2713":"\u2717"}</span></td>`,H+="</tr>",R.details&&Object.keys(R.details).length>0&&(H+=`<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(R.details,null,2))}</pre></td></tr>`)}if(!M)H+="</table>",z.innerHTML=H;else{const R=z.querySelector("table");R&&R.insertAdjacentHTML("beforeend",H)}v+=j.length,A.style.display=j.length>=L?"":"none",z.querySelectorAll(".audit-row").forEach(R=>{R.dataset.wired||(R.dataset.wired="true",R.addEventListener("click",()=>{const x=R.nextElementSibling;x&&x.classList.contains("audit-detail")&&(x.style.display=x.style.display==="none"?"":"none")}))})}catch(k){z.innerHTML=`<div class="panel-empty" style="color: var(--bad-fg);">Failed: ${escapeHtml(k.message)}</div>`}}E?.addEventListener("click",()=>{h?.classList.add("show"),b(!1)}),wireModal(h,P),w?.addEventListener("click",()=>b(!1)),O?.addEventListener("change",()=>b(!1)),A?.addEventListener("click",()=>b(!0)),N?.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?b(!1):showNotification("Error: "+(k.error||"Clear failed"),"error")}catch(M){showNotification("Error: "+M.message,"error")}})})(),(function(){const h=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>
    <div style="margin-top: 14px; padding-top: 12px; border-top: 1px solid var(--border);">
      <label style="display: block; margin-bottom: 8px; font-weight: 600; color: var(--fg);">Units</label>
      <div style="display: flex; gap: 8px;">
        <label class="weather-unit-option"><input type="radio" name="weather-unit-radio" value="imperial"><span class="weather-unit-card">&deg;F / mph</span></label>
        <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 E="weather-location",P="weather-zip",w="weather-geo",N="weather-unit";!safeGet(E)&&safeGet(P)&&safeSet(E,safeGet(P));function O(){return safeGet(N)||"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 A={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"},L=["N","NNE","NE","ENE","E","ESE","SE","SSE","S","SSW","SW","WSW","W","WNW","NW","NNW"];function b(H){return L[Math.round(H/22.5)%16]}async function M(H){const R=safeGet(w);if(R)try{const f=JSON.parse(R);if(f.query===H)return f}catch{}const x=await fetch(`https://geocoding-api.open-meteo.com/v1/search?name=${encodeURIComponent(H)}&count=1&language=en&format=json`);if(!x.ok)throw new Error("Geocoding failed");const D=await x.json();if(!D.results||!D.results.length)throw new Error("Location not found");const g=D.results[0],u={query:H,lat:g.latitude,lon:g.longitude,city:g.name,state:g.admin1||"",country:g.country||"",countryCode:g.country_code||""};return safeSet(w,JSON.stringify(u)),u}function k(H){return H.countryCode==="US"&&H.state?`${H.city}, ${H.state}`:H.country?`${H.city}, ${H.country}`:H.city}async function B(H){try{const R=await M(H),x=O(),D=x==="metric"?"celsius":"fahrenheit",g=x==="metric"?"kmh":"mph",u=`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=${D}&wind_speed_unit=${g}`,f=await fetch(u);if(!f.ok)throw new Error("Weather fetch failed");const p=(await f.json()).current,d=p.weather_code;return{temp:Math.round(p.temperature_2m),condition:A[d]||"Unknown",icon:v[d]||"\u{1F324}\uFE0F",locationStr:k(R),windSpeed:Math.round(p.wind_speed_10m),windDir:b(p.wind_direction_10m),unit:x}}catch(R){return console.warn("Weather fetch failed:",R),null}}async function S(){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(E);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 x=await B(R);if(x){const D=x.unit==="metric"?"\xB0C":"\xB0F",g=x.unit==="metric"?"km/h":"mph";H.location.textContent=x.locationStr,H.temp.textContent=`${x.temp}${D}`,H.condition.textContent=x.condition,H.wind.textContent=`Wind: ${x.windSpeed} ${g} ${x.windDir}`,H.icon.innerHTML=`<span class="weather-emoji">${escapeHtml(x.icon)}</span>`}}catch(x){h.logError("[Weather] Update Error",x,{function:"updateWeather"}),H.location.textContent="Weather Error",H.temp.textContent="Error",H.condition.textContent="Failed to load",H.wind.textContent="--"}}const T=document.getElementById("weather-modal"),j=document.getElementById("weather-location-input");document.getElementById("weather-settings")?.addEventListener("click",()=>{j.value=safeGet(E)||"";const H=O(),R=T.querySelector(`input[name="weather-unit-radio"][value="${H}"]`);R&&(R.checked=!0),T.classList.add("show"),j.focus()}),document.getElementById("weather-cancel")?.addEventListener("click",()=>{T.classList.remove("show")}),document.getElementById("weather-save")?.addEventListener("click",()=>{const H=j.value.trim();if(H){safeGet(E)!==H&&safeSet(w,""),safeSet(E,H);const x=T.querySelector('input[name="weather-unit-radio"]:checked'),D=x?x.value:"imperial",g=O();safeSet(N,D),g!==D&&safeSet(w,""),T.classList.remove("show"),S()}else showNotification("Please enter a location (e.g., Hamburg, London, 90210)","warning")}),wireModal(T),document.addEventListener("keydown",H=>{H.key==="Escape"&&T.classList.contains("show")&&T.classList.remove("show")}),S(),setInterval(S,DC.POLL.WEATHER)})(),(function(){const h=document.getElementById("clock-widget"),E=document.getElementById("clock-render");if(!h||!E)return;const P=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],w=["January","February","March","April","May","June","July","August","September","October","November","December"],N=["XII","I","II","III","IV","V","VI","VII","VIII","IX","X","XI"];let O=safeGet("clock-style")||"default",z=-1,A=!1,v="",L="",b=null,M=null;function k(n){if(A||safeGet("clock-chimes")!=="true")return;A=!0;const e=parseInt(safeGet("clock-chime-volume")||"50",10)/100;let o=0;function a(){if(o>=n){A=!1;return}const r=new Audio("/assets/sounds/church-bell.mp3");r.volume=e,r.play().catch(()=>{}),o++,o<n?setTimeout(a,2500):setTimeout(()=>{A=!1},2500)}a()}function B(n){return P[n.getDay()]+", "+w[n.getMonth()]+" "+n.getDate()+", "+n.getFullYear()}function S(){L="",b=null}function T(){return L!=="digital"&&(E.innerHTML='<div class="clock-time"><span class="clock-main"></span><span class="clock-seconds"></span><span class="clock-ampm"></span></div><div class="clock-date"></div>',b={main:E.querySelector(".clock-main"),seconds:E.querySelector(".clock-seconds"),ampm:E.querySelector(".clock-ampm"),date:E.querySelector(".clock-date")},L="digital"),b}function j(n){const e=n.getHours(),o=n.getMinutes(),a=n.getSeconds(),r=e>=12?"PM":"AM",t=e%12||12,s=T();s.main.textContent=`${t}:${String(o).padStart(2,"0")}`,s.seconds.textContent=`:${String(a).padStart(2,"0")}`,s.ampm.textContent=r,s.date.textContent=B(n)}function H(n,e){const o=n.getHours(),a=n.getMinutes(),r=n.getSeconds(),t=o>=12?"PM":"AM",s=o%12||12,l=T();l.main.textContent=`${String(s).padStart(2,"0")}:${String(a).padStart(2,"0")}`,l.seconds.textContent=`:${String(r).padStart(2,"0")}`,l.ampm.textContent=t,l.date.textContent=B(n)}function R(n){const e=n.getHours(),o=n.getMinutes(),a=n.getSeconds(),r=e>=12?"PM":"AM",t=e%12||12,s=String(t).padStart(2," ")+String(o).padStart(2,"0")+String(a).padStart(2,"0");let l='<div class="flip-clock-row">';if(l+=x(s[0],0),l+=x(s[1],1),l+='<span class="flip-colon">:</span>',l+=x(s[2],2),l+=x(s[3],3),l+='<span class="flip-colon">:</span>',l+=x(s[4],4),l+=x(s[5],5),l+=`<span class="flip-ampm">${r}</span>`,l+="</div>",l+=`<div class="clock-date">${B(n)}</div>`,E.innerHTML=l,L="flip",v){for(let C=0;C<6;C++)if(s[C]!==v[C]){const I=E.querySelector(`.flip-card[data-idx="${C}"]`);I&&I.classList.add("flipping")}}v=s}function x(n,e){const o=n===" "?"":n;return`<div class="flip-card" data-idx="${e}"><div class="flip-top">${o}</div><div class="flip-bottom">${o}</div></div>`}function D(n){const e=n.getHours(),o=n.getMinutes(),a=n.getSeconds(),r=e%12||12,t=e>=12?"PM":"AM",s=[Math.floor(r/10),r%10,Math.floor(o/10),o%10,Math.floor(a/10),a%10];let l='<div class="binary-clock">';l+='<div class="binary-labels"><span>H</span><span>H</span><span>M</span><span>M</span><span>S</span><span>S</span></div>';for(let C=3;C>=0;C--){l+='<div class="binary-row">';for(let I=0;I<6;I++){const F=s[I]>>C&1;l+=`<div class="binary-dot ${F?"on":""}"></div>`}l+="</div>"}l+='<div class="binary-values">';for(let C=0;C<6;C++)l+=`<span>${s[C]}</span>`;l+="</div>",l+=`<div class="binary-ampm">${t}</div>`,l+="</div>",l+=`<div class="clock-date">${B(n)}</div>`,E.innerHTML=l,L="binary"}function g(n,e){const o=n.getHours(),a=n.getMinutes(),r=n.getSeconds(),t=120,s=t/2,l=t/2,C=r/60*360-90,I=(a+r/60)/60*360-90,F=(o%12+a/60)/12*360-90;let q="";for(let X=1;X<=12;X++){const Q=X/12*2*Math.PI-Math.PI/2,ne=47,oe=s+ne*Math.cos(Q),se=l+ne*Math.sin(Q),Y=e?N[X%12]:X;q+=`<text x="${oe}" y="${se}" text-anchor="middle" dominant-baseline="central" fill="var(--fg)" font-size="${e?"7":"9"}" font-weight="600" font-family="'Sami Grotesk',sans-serif">${Y}</text>`}let U="";for(let X=0;X<60;X++){const Q=X/60*2*Math.PI-Math.PI/2,ne=56,oe=X%5===0?52:54,se=s+oe*Math.cos(Q),Y=l+oe*Math.sin(Q),ie=s+ne*Math.cos(Q),re=l+ne*Math.sin(Q),ae=X%5===0?1.5:.5;U+=`<line x1="${se}" y1="${Y}" x2="${ie}" y2="${re}" stroke="var(--muted)" stroke-width="${ae}" stroke-linecap="round"/>`}const G=`<svg class="analog-clock-svg" viewBox="0 0 ${t} ${t}" width="${t}" height="${t}">
      <circle cx="${s}" cy="${l}" r="58" fill="none" stroke="var(--border)" stroke-width="2"/>
      ${U}
      ${q}
      <line x1="${s}" y1="${l}" x2="${s+28*Math.cos(F*Math.PI/180)}" y2="${l+28*Math.sin(F*Math.PI/180)}" stroke="var(--fg)" stroke-width="3" stroke-linecap="round"/>
      <line x1="${s}" y1="${l}" x2="${s+38*Math.cos(I*Math.PI/180)}" y2="${l+38*Math.sin(I*Math.PI/180)}" stroke="var(--fg)" stroke-width="2" stroke-linecap="round"/>
      <line x1="${s}" y1="${l}" x2="${s+42*Math.cos(C*Math.PI/180)}" y2="${l+42*Math.sin(C*Math.PI/180)}" stroke="#e74c3c" stroke-width="1" stroke-linecap="round"/>
      <circle cx="${s}" cy="${l}" r="3" fill="var(--fg)"/>
    </svg>`,J=n.getHours()>=12?"PM":"AM";E.innerHTML=`<div class="analog-clock-wrap">${G}<div class="analog-info"><span class="analog-digital">${n.getHours()%12||12}:${String(a).padStart(2,"0")} ${J}</span><span class="analog-date-sm">${B(n)}</span></div></div>`,L="analog"}function u(){const n=new Date,e=n.getHours()%12||12,o=n.getMinutes(),a=n.getSeconds(),r="clock-widget"+(O!=="default"?" "+O:"");switch(h.className!==r&&(h.className=r),O){case"lcd":H(n);break;case"lcd-blue":H(n);break;case"lcd-amber":H(n);break;case"lcd-retro":H(n);break;case"lcd-taxi":H(n);break;case"flip":R(n);break;case"binary":D(n);break;case"analog":g(n,!1);break;case"roman":g(n,!0);break;default:j(n)}o===0&&a===0&&e!==z&&(z=e,k(e)),o!==0&&(z=-1)}function f(){clearTimeout(M);const n=document.hidden?6e4:1e3,e=n-Date.now()%n+25;M=setTimeout(()=>{u(),f()},e)}document.addEventListener("visibilitychange",()=>{v="",S(),u(),f()}),u(),f();const m=[{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 p='<div class="clock-style-grid">';m.forEach(n=>{p+=`<label class="clock-style-option">
      <input type="radio" name="clock-style-radio" value="${n.id}">
      <span class="clock-style-card"><span class="clock-style-icon">${n.icon}</span><span class="clock-style-label">${n.label}</span></span>
    </label>`}),p+="</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>
        ${p}
      </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);">
          <input type="checkbox" id="clock-chimes-toggle"> Hourly church bell chimes
        </label>
        <div style="font-size: 0.78rem; color: var(--muted); margin-top: 4px; margin-left: 24px;">
          Strikes the number of the hour (e.g., 3 bells at 3:00)
        </div>
      </div>
      <div style="margin-bottom: 16px;" id="clock-volume-section">
        <label style="display: block; margin-bottom: 6px; font-weight: 600; color: var(--fg);">Volume</label>
        <div style="display: flex; align-items: center; gap: 10px;">
          <span style="font-size: 0.85rem;">\u{1F508}</span>
          <input type="range" id="clock-chime-volume" min="0" max="100" value="50" style="flex: 1; accent-color: var(--ok-fg);">
          <span style="font-size: 0.85rem;">\u{1F50A}</span>
          <button id="clock-chime-test" style="padding: 4px 10px; font-size: 0.78rem; border-radius: 4px; cursor: pointer;">Test</button>
        </div>
      </div>
      <div class="weather-modal-buttons">
        <button id="clock-settings-cancel">Cancel</button>
        <button id="clock-settings-save">Save</button>
      </div>
    </div>
  </div>`);const d=document.getElementById("clock-settings-modal"),c=document.getElementById("clock-chimes-toggle"),i=document.getElementById("clock-chime-volume"),$=document.getElementById("clock-volume-section");function y(){const n=safeGet("clock-style")||"default",e=d.querySelector(`input[value="${n}"]`);e&&(e.checked=!0),c.checked=safeGet("clock-chimes")==="true",i.value=safeGet("clock-chime-volume")||"50",$.style.opacity=c.checked?"1":"0.4"}c?.addEventListener("change",()=>{$.style.opacity=c.checked?"1":"0.4"}),document.getElementById("clock-settings")?.addEventListener("click",()=>{y(),d.classList.add("show")}),document.getElementById("clock-chime-test")?.addEventListener("click",()=>{const n=parseInt(i.value,10)/100,e=new Audio("/assets/sounds/church-bell.mp3");e.volume=n,e.play().catch(()=>{})}),document.getElementById("clock-settings-save")?.addEventListener("click",()=>{const n=d.querySelector('input[name="clock-style-radio"]:checked'),e=n?n.value:"default";safeSet("clock-style",e),safeSet("clock-chimes",String(c.checked)),safeSet("clock-chime-volume",i.value),O=e,v="",S(),u(),f(),d.classList.remove("show"),showNotification("Clock settings saved","success",2e3)}),document.getElementById("clock-settings-cancel")?.addEventListener("click",()=>{d.classList.remove("show")}),wireModal(d),d?.querySelectorAll('input[name="clock-style-radio"]').forEach(n=>{n.addEventListener("change",()=>{O=n.value,v="",S(),u()})})})(),(function(){async function h(){try{const A=await(await fetch("/api/v1/health-checks/status")).json();if(!A.success||!A.status)return;for(const[v,L]of Object.entries(A.status)){const b=document.getElementById("uptime-"+v),M=document.getElementById("uptime-bar-"+v);if(!b)continue;const k=L.uptime?.["24h"];if(k!=null){const B=k.toFixed(1);b.textContent=`${B}% uptime`,b.className="uptime-chip",k>=99.9?b.classList.add("excellent"):k>=99?b.classList.add("good"):k>=95?b.classList.add("degraded"):b.classList.add("poor"),M&&(M.style.width=B+"%")}}}catch{console.warn("[Card Badges] Health check API unavailable")}}let E;try{E=new Set(JSON.parse(safeSessionGet("dismissed-updates")||"[]"))}catch{E=new Set}let P=[];async function w(z){try{const v=await(await fetch("/api/v1/updates/available")).json();if(!v.success)return;document.querySelectorAll(".update-available-badge").forEach(b=>b.classList.remove("visible"));const L=v.updates||[];if(P=L,z&&L.length>0){const b=window._lastKnownUpdateCount||0;b>0&&L.length>b&&showNotification(`${L.length} container update(s) available \u2014 click Update Management to review.`,"info"),window._lastKnownUpdateCount=L.length}if(!L.length)return;for(const b of L){const M=window.APPS||[];for(const k of M)if(k.containerId===b.containerId||k.id===b.containerName||k.name===b.containerName){if(E.has(k.id))break;const B=document.getElementById("update-badge-"+k.id),S=document.getElementById("update-btn-"+k.id);B&&(B.classList.add("visible"),B.title="Update available \u2014 click to open Update Management.",B.style.cursor="pointer",B.onclick=T=>{T.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 N(){setTimeout(()=>{h(),w()},5e3),setInterval(()=>{h(),w(!0)},6e4)}const O=window.refreshAll;O&&(window.refreshAll=async function(){try{await O(),setTimeout(h,1e3)}catch(z){console.warn("[Card Badges] Error in refreshAll hook:",z.message)}}),N()})(),(function(){var h=null,E=null,P={},w={dark:"Dark",light:"Light",blue:"Blue",black:"Black",nord:"Nord",dracula:"Dracula","solarized-dark":"Solarized Dark","solarized-light":"Solarized Light",taxi:"Taxi",ocean:"Ocean"},N=[["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"]],O=document.getElementById("theme");if(!O)return;var z=document.getElementById("theme-label");function A(a){if(w[a])return w[a];var r=safeGetJSON(window.USER_THEMES_KEY,{});return r[a]&&r[a].name||a}function v(){z&&(z.textContent=A(window.getActiveTheme()))}O.addEventListener("click",function(){var a=window.THEMES.slice(),r=window.getActiveTheme(),t=a.indexOf(r),s=a[(t+1)%a.length];window.applyTheme(s),v()}),v();function L(){var a={base:"Base Colors",accent:"Accent",status:"Status",advanced:"Advanced (auto-derived)"},r={};N.forEach(function(s){r[s[2]]||(r[s[2]]=[]),r[s[2]].push(s)});var t="";return Object.keys(a).forEach(function(s){s==="advanced"?(t+='<div id="theme-builder-advanced-toggle" class="theme-builder-advanced-toggle" style="margin:12px 0 4px;cursor:pointer;color:var(--accent);font-size:.85rem;user-select:none;">Show advanced colors &#9660;</div>',t+='<div id="theme-builder-advanced" class="theme-builder-section" style="display:none;">'):t+='<div class="theme-builder-section">',t+='<div class="theme-builder-section-title">'+a[s]+"</div>",(r[s]||[]).forEach(function(l){t+='<div class="theme-builder-row"><span class="theme-builder-label">'+l[1]+'</span><input type="color" class="theme-builder-color" data-prop="'+l[0]+'"'+(s==="advanced"?' data-advanced="1"':"")+' value="#000000" /><span class="theme-builder-hex" data-hex="'+l[0]+'">#000000</span></div>'}),t+="</div>"}),t}function b(){return window.THEMES.map(function(a){return'<option value="'+a+'">'+A(a)+"</option>"}).join("")}var M='<div id="theme-builder-modal" class="weather-modal"><div class="weather-modal-content" style="min-width:420px;max-width:560px;"><h3>Theme Builder</h3><div id="theme-builder-existing" style="margin-bottom:16px;display:none;"><label style="font-size:.85rem;color:var(--muted);margin-right:8px;">Edit:</label><select id="theme-builder-edit-select" style="padding:6px 10px;background:var(--card-bg);color:var(--fg);border:1px solid var(--border);border-radius:6px;font-size:.85rem;margin-right:8px;"><option value="">\u2014 New Theme \u2014</option></select><button id="theme-builder-delete" style="padding:4px 10px;background:color-mix(in srgb,var(--bad-fg) 15%,transparent);border:1px solid var(--bad-fg);color:var(--bad-fg);border-radius:6px;font-size:.8rem;cursor:pointer;">Delete</button></div><div style="margin-bottom:16px;"><label style="font-size:.85rem;color:var(--muted);margin-right:8px;">Name:</label><input type="text" id="theme-builder-name" maxlength="20" placeholder="My Theme" style="padding:6px 10px;background:var(--card-bg);color:var(--fg);border:1px solid var(--border);border-radius:6px;font-size:.85rem;width:140px;" /></div><div style="margin-bottom:16px;display:flex;align-items:center;"><label style="font-size:.85rem;color:var(--muted);margin-right:8px;cursor:pointer;" for="theme-builder-lightbg"><input type="checkbox" id="theme-builder-lightbg" style="margin-right:6px;cursor:pointer;vertical-align:middle;" />Light background (use dark logo)</label></div><div style="margin-bottom:16px;"><label style="font-size:.85rem;color:var(--muted);margin-right:8px;">Start from:</label><select id="theme-builder-start" style="padding:6px 10px;background:var(--card-bg);color:var(--fg);border:1px solid var(--border);border-radius:6px;font-size:.85rem;">'+b()+'</select></div><div class="theme-builder-preview" id="theme-builder-preview"><div class="theme-builder-card" id="theme-preview-card"><div class="preview-title">Sample Card</div><div class="preview-muted">Secondary text preview</div><div class="preview-badges"><span class="preview-badge" id="preview-badge-ok">ON</span><span class="preview-badge" id="preview-badge-bad">OFF</span></div><div class="preview-dots"><span><span class="preview-dot" id="preview-dot-ok"></span> Online</span><span><span class="preview-dot" id="preview-dot-bad"></span> Offline</span></div><button class="preview-btn" id="preview-accent-btn">Accent Button</button></div></div>'+L()+'<div class="weather-modal-buttons"><button id="theme-builder-cancel">Cancel</button><button id="theme-builder-import" style="margin-left:auto;" title="Import theme from JSON file">Import</button><button id="theme-builder-export" title="Export theme as JSON file">Export</button><button id="theme-builder-save" class="btn-accent">Save Theme</button></div></div></div>';injectModal("theme-builder-modal",M);var k=document.getElementById("theme-builder-modal"),B=document.getElementById("theme-builder-start"),S=document.getElementById("theme-builder-name"),T=document.getElementById("theme-builder-edit-select"),j=document.getElementById("theme-builder-existing"),H=document.getElementById("theme-builder-lightbg"),R=k.querySelectorAll(".theme-builder-color"),x=document.getElementById("theme-builder-advanced"),D=document.getElementById("theme-builder-advanced-toggle"),g=document.getElementById("theme-builder-export"),u=!1;D.addEventListener("click",function(){u=!u,x.style.display=u?"":"none",D.innerHTML=u?"Hide advanced colors &#9650;":"Show advanced colors &#9660;"});function f(){var a={};return R.forEach(function(r){a[r.dataset.prop]=r.value}),a["card-bg"]=a["card-base"],a}function m(){var a={};return R.forEach(function(r){r.dataset.advanced||(a[r.dataset.prop]=r.value)}),a["card-bg"]=a["card-base"],H.checked&&(a.lightBg=!0),a}function p(){var a=m(),r=window.deriveExtendedColors?window.deriveExtendedColors(a):{};R.forEach(function(t){if(t.dataset.advanced&&!P[t.dataset.prop]){var s=r[t.dataset.prop]||"#333333";t.value=s;var l=k.querySelector('[data-hex="'+t.dataset.prop+'"]');l&&(l.textContent=s.toUpperCase())}})}function d(a){var r=window.THEME_COLORS[a];r&&(P={},R.forEach(function(t){var s=r[t.dataset.prop]||"#000000";(s.startsWith("rgba")||s.startsWith("color-mix"))&&(s="#333333"),t.value=s;var l=k.querySelector('[data-hex="'+t.dataset.prop+'"]');l&&(l.textContent=s.toUpperCase())}),H.checked=!!r.lightBg,i())}function c(a){var r=safeGetJSON(window.USER_THEMES_KEY,{}),t=r[a];t&&(P={},R.forEach(function(s){var l=t[s.dataset.prop]||"#000000";s.value=l;var C=k.querySelector('[data-hex="'+s.dataset.prop+'"]');C&&(C.textContent=l.toUpperCase()),s.dataset.advanced&&t[s.dataset.prop]&&(P[s.dataset.prop]=!0)}),S.value=t.name||"",H.checked=!!t.lightBg,p(),i())}function i(){var a=f(),r=document.getElementById("theme-builder-preview"),t=document.getElementById("theme-preview-card"),s=t.querySelector(".preview-title"),l=t.querySelector(".preview-muted"),C=document.getElementById("preview-badge-ok"),I=document.getElementById("preview-badge-bad"),F=document.getElementById("preview-dot-ok"),q=document.getElementById("preview-dot-bad"),U=document.getElementById("preview-accent-btn"),G=t.querySelector(".preview-dots");r.style.background=a.bg,t.style.background=a["card-base"],t.style.borderColor=a.border,s.style.color=a.fg,l.style.color=a.muted,C.style.background=a["ok-bg"],C.style.color=a["ok-fg"],I.style.background=a["bad-bg"],I.style.color=a["bad-fg"],F.style.background=a["dot-ok"],q.style.background=a["dot-bad"],G.style.color=a.fg,U.style.background=a.accent,U.style.color=a.bg}function $(a){var r=window.deriveExtendedColors?window.deriveExtendedColors(a):{};window.THEME_PROPS.forEach(function(t){var s=a[t]||r[t];s&&document.documentElement.style.setProperty("--"+t,s)})}R.forEach(function(a){a.addEventListener("input",function(){var r=k.querySelector('[data-hex="'+a.dataset.prop+'"]');r&&(r.textContent=a.value.toUpperCase()),a.dataset.advanced?P[a.dataset.prop]=!0:p(),i(),$(f())})}),H.addEventListener("change",function(){p(),i(),$(f())}),B.addEventListener("change",function(){P={},d(B.value),$(f())});function y(){var a=safeGetJSON(window.USER_THEMES_KEY,{}),r=Object.keys(a);T.innerHTML='<option value="">\u2014 New Theme \u2014</option>',r.forEach(function(t){var s=document.createElement("option");s.value=t,s.textContent=a[t].name||t,T.appendChild(s)}),j.style.display=r.length?"":"none"}function n(){B.innerHTML=b()}T.addEventListener("change",function(){var a=this.value;a?(E=a,c(a),$(f())):(E=null,P={},S.value="",B.value=window.getActiveTheme(),d(B.value)),g.style.display=E?"":"none"});function e(){h=window.getActiveTheme(),E=null,P={},u=!1,x.style.display="none",D.innerHTML="Show advanced colors &#9660;",y(),n();var a=safeGetJSON(window.USER_THEMES_KEY,{});a[h]?(T.value=h,E=h,c(h)):(T.value="",S.value="",B.value=h,d(h)),g.style.display=E?"":"none",k.classList.add("show")}var o=document.getElementById("theme-customize-btn");o&&o.addEventListener("click",function(){e()}),document.getElementById("theme-builder-save").addEventListener("click",function(){var a=f(),r=S.value.trim();if(!r){showNotification("Please enter a theme name","warning",3e3),S.focus();return}var t=safeGetJSON(window.USER_THEMES_KEY,{}),s,l=null;if(E){s=E;var C=window.slugifyThemeName(r,E);if(C!==E){l=E,delete t[E];var I=window.THEMES.indexOf(E);I!==-1&&window.THEMES.splice(I,1),delete window.THEME_COLORS[E],s=C}}else s=window.slugifyThemeName(r);var F={name:r};H.checked&&(F.lightBg=!0),window.THEME_PROPS.forEach(function(U){a[U]&&(F[U]=a[U])}),t[s]=F,safeSet(window.USER_THEMES_KEY,JSON.stringify(t)),window.clearCustomProperties(),window.injectUserThemeStyles(),window.applyTheme(s),k.classList.remove("show"),v();var q={};window.THEME_PROPS.forEach(function(U){a[U]&&(q[U]=a[U])}),l&&secureFetch("/api/v1/themes/"+l,{method:"DELETE"}).catch(function(){}),secureFetch("/api/v1/themes/"+s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:r,colors:q,lightBg:H.checked})}).then(function(){showNotification(r+" theme saved","success",3e3)}).catch(function(){showNotification(r+" theme saved locally (server sync failed)","warning",3e3)})}),document.getElementById("theme-builder-cancel").addEventListener("click",function(){k.classList.remove("show"),window.clearCustomProperties(),h&&window.applyTheme(h)}),document.getElementById("theme-builder-delete").addEventListener("click",function(){if(E){var a=safeGetJSON(window.USER_THEMES_KEY,{}),r=a[E]?a[E].name:E;if(confirm('Delete "'+r+'" theme?')){var t=E;delete a[t],safeSet(window.USER_THEMES_KEY,JSON.stringify(a));var s=window.THEMES.indexOf(t);s!==-1&&window.THEMES.splice(s,1),delete window.THEME_COLORS[t],window.clearCustomProperties(),window.injectUserThemeStyles();var l=h&&h!==t?h:"dark";window.applyTheme(l),E=null,k.classList.remove("show"),v(),secureFetch("/api/v1/themes/"+t,{method:"DELETE"}).then(function(){showNotification(r+" theme deleted","success",3e3)}).catch(function(){showNotification(r+" theme deleted locally (server sync failed)","warning",3e3)})}}}),document.getElementById("theme-builder-export").addEventListener("click",function(){if(!E){showNotification("Save the theme first, then export","warning",3e3);return}var a=safeGetJSON(window.USER_THEMES_KEY,{}),r=a[E];if(r){var t={_dashcaddy_theme:!0,version:"1.0",exportDate:new Date().toISOString(),slug:E,name:r.name,lightBg:r.lightBg||!1,colors:{}};window.THEME_PROPS.forEach(function(I){r[I]&&(t.colors[I]=r[I])});var s=new Blob([JSON.stringify(t,null,2)],{type:"application/json"}),l=URL.createObjectURL(s),C=document.createElement("a");C.href=l,C.download=E+"-theme.json",document.body.appendChild(C),C.click(),document.body.removeChild(C),URL.revokeObjectURL(l),showNotification("Theme exported as "+E+"-theme.json","success",3e3)}}),document.getElementById("theme-builder-import").addEventListener("click",function(){var a=document.createElement("input");a.type="file",a.accept=".json",a.onchange=function(r){var t=r.target.files[0];if(t){var s=new FileReader;s.onload=function(l){try{var C=JSON.parse(l.target.result),I,F,q;if(C._dashcaddy_theme&&C.colors)I=C.name||"Imported",F=C.colors,q=C.lightBg||!1;else if(C.name&&(C.bg||C["card-base"]))I=C.name,F={},window.THEME_PROPS.forEach(function(U){C[U]&&(F[U]=C[U])}),q=C.lightBg||!1;else throw new Error("Not a valid DashCaddy theme file");S.value=I,H.checked=!!q,E=null,T.value="",P={},R.forEach(function(U){var G=F[U.dataset.prop]||"#000000";U.value=G;var J=k.querySelector('[data-hex="'+U.dataset.prop+'"]');J&&(J.textContent=G.toUpperCase()),U.dataset.advanced&&F[U.dataset.prop]&&(P[U.dataset.prop]=!0)}),p(),i(),$(f()),g.style.display="none",showNotification('"'+I+'" loaded into builder. Click Save to keep it.',"success",5e3)}catch(U){showNotification("Import failed: "+U.message,"error",5e3)}},s.readAsText(t)}},a.click()}),wireModal(k),k.addEventListener("click",function(a){a.target===k&&(window.clearCustomProperties(),h&&window.applyTheme(h))})})(),(function(){injectModal("license-modal",`<div id="license-modal" class="weather-modal">
    <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;">
        Activate a license code to unlock premium features.
      </p>

      <div id="license-status-section" style="margin-bottom: 16px;">
        <div id="license-badge" style="display: inline-flex; align-items: center; gap: 6px; padding: 6px 14px; border-radius: 20px; font-size: 0.85rem; font-weight: 600; margin-bottom: 12px;">
          <span id="license-badge-icon"></span>
          <span id="license-badge-text"></span>
        </div>
        <div id="license-details" style="font-size: 0.85rem; color: var(--muted); line-height: 1.6;"></div>
      </div>

      <div id="license-activate-section">
        <label class="form-label-bold">License Code:</label>
        <input type="text" id="license-code-input" placeholder="DC-XXXXX-XXXXX-XXXXX-XXXXX-XXXXX"
          maxlength="35" spellcheck="false" autocomplete="off"
          style="width: 100%; padding: 10px 12px; border: 1px solid var(--border); border-radius: 4px; background: var(--card-bg); color: var(--fg); font-size: 1rem; font-family: monospace; letter-spacing: 1px;" />
        <p class="tiny-hint">Enter your license code to activate premium features</p>
      </div>

      <div id="license-features" style="margin-top: 16px;">
        <label class="form-label-bold" style="margin-bottom: 8px; display: block;">Premium Features:</label>
        <div id="license-feature-list" style="display: grid; gap: 8px;"></div>
      </div>

      <div id="license-error" style="display: none; margin-top: 12px; padding: 10px; border-radius: 4px; background: rgba(231,76,60,0.15); color: var(--bad-fg); font-size: 0.85rem;"></div>
      <div id="license-success" style="display: none; margin-top: 12px; padding: 10px; border-radius: 4px; background: rgba(46,204,113,0.15); color: var(--ok-fg); font-size: 0.85rem;"></div>

      <div class="weather-modal-buttons" style="margin-top: 16px;">
        <button id="license-cancel">Close</button>
        <button id="license-deactivate" class="btn-accent" style="display: none; background: var(--bad-bg); border-color: var(--bad-fg); color: var(--bad-fg);">Deactivate</button>
        <button id="license-activate" class="btn-accent">Activate</button>
      </div>
    </div>
  </div>`);const h=document.getElementById("license-modal"),E=document.getElementById("license-code-input"),P=document.getElementById("license-activate"),w=document.getElementById("license-deactivate"),N=document.getElementById("license-error"),O=document.getElementById("license-success"),z=document.getElementById("license-badge-icon"),A=document.getElementById("license-badge-text"),v=document.getElementById("license-badge"),L=document.getElementById("license-details"),b=document.getElementById("license-feature-list"),M=document.getElementById("license-activate-section");let k=null;function B(){N.style.display="none",O.style.display="none"}function S(f){B(),N.textContent=f,N.style.display="block"}function T(f){B(),O.textContent=f,O.style.display="block"}function j(f){if(k=f,f.active){v.style.background="rgba(46,204,113,0.15)",v.style.color="var(--ok-fg)",z.textContent="\u2605",A.textContent="Premium Active";const d=f.lifetime?"<div>License: <strong>LIFETIME</strong></div>":`<div>Expires: <strong>${new Date(f.expiresAt).toLocaleDateString()}</strong> (${f.daysRemaining} days remaining)</div>`;L.innerHTML=`
        <div>Code: <code style="font-family: monospace;">${f.code||"***"}</code></div>
        ${d}
      `,M.style.display="none",P.style.display="none",w.style.display=""}else v.style.background="rgba(149,165,166,0.15)",v.style.color="var(--muted)",z.textContent="\u2606",A.textContent=f.expired?"License Expired":"Free Tier",L.innerHTML=f.expired?"<div>Your license has expired. Enter a new code to renew.</div>":"<div>Enter a license code to unlock premium features.</div>",M.style.display="",P.style.display="",w.style.display="none";const m=f.premiumFeatures||{},p=new Set(f.features||[]);b.innerHTML=Object.entries(m).map(([d,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;">${p.has(d)?"\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 H(){try{const m=await(await fetch("/api/v1/license/status")).json();m.success&&(j(m.license),D(m.license))}catch(f){console.warn("Failed to load license status:",f.message)}}async function R(){const f=E.value.trim();if(!f){S("Please enter a license code.");return}B(),P.disabled=!0,P.textContent="Activating...";try{const p=await(await secureFetch("/api/v1/license/activate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:f})})).json();p.success?(T(p.message),E.value="",j(p.license),showNotification("License activated! Premium features unlocked.","success",5e3),D(p.license)):S(p.error||"Activation failed")}catch(m){S("Network error: "+m.message)}finally{P.disabled=!1,P.textContent="Activate"}}async function x(){if(confirm("Deactivate your license? You can reuse the code on another machine.")){w.disabled=!0,w.textContent="Deactivating...";try{const m=await(await secureFetch("/api/v1/license/deactivate",{method:"POST"})).json();m.success?(T(m.message),await H(),showNotification("License deactivated.","info",3e3),D({active:!1})):S(m.error||"Deactivation failed")}catch(f){S("Network error: "+f.message)}finally{w.disabled=!1,w.textContent="Deactivate"}}}function D(f){const m=document.getElementById("license-status-topbar"),p=document.getElementById("license-topbar-icon"),d=document.getElementById("license-topbar-text"),c=document.getElementById("license-topbar-time");if(m)if(m.className="license-status-topbar "+(f.active?"premium":"free"),f.active)if(p.textContent="\u2605",d.textContent="PREMIUM",f.lifetime)c.textContent="\xB7 LIFETIME";else{const i=f.daysRemaining;c.textContent=i!=null?"\xB7 "+i+"d remaining":""}else p.textContent="\u2606",d.textContent=f.expired?"EXPIRED":"FREE TIER",c.textContent=""}function g(){B(),H(),h.classList.add("show")}E.addEventListener("input",function(){let f=this.value.toUpperCase().replace(/[^A-Z0-9-]/g,"");if(f.length>this._prevLength&&(f=f.replace(/-/g,""),f.length>2&&!f.startsWith("DC")&&(f="DC"+f),f.startsWith("DC")&&f.length>2)){const m=["DC"],p=f.substring(2);for(let d=0;d<p.length;d+=5)m.push(p.substring(d,d+5));f=m.join("-")}this._prevLength=f.length,this.value=f}),P.addEventListener("click",R),w.addEventListener("click",x),E.addEventListener("keydown",f=>{f.key==="Enter"&&R()}),wireModal(h,document.getElementById("license-cancel"));const u=document.getElementById("license-status-topbar");u&&u.addEventListener("click",()=>window.openLicenseModal&&window.openLicenseModal()),window.openLicenseModal=g,window.checkPremiumFeature=async function(f){try{return(await(await fetch(`/api/v1/license/feature/${f}`)).json()).available}catch{return!1}},H().then(f=>{k&&D(k)})})();
