From c6aba212784810c7ac49b595e1e868a5a2a0a09c Mon Sep 17 00:00:00 2001 From: maziggy Date: Fri, 17 Apr 2026 08:50:49 +0200 Subject: [PATCH] fix(printer): add X2D to add/edit printer model dropdowns (#988) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Both the Add Printer and Edit Printer modals had hardcoded model lists missing the X2D — manual printer setup had no way to select the new model. Auto-discovery via SSDP and virtual printer model selection (dynamic from backend) were unaffected. --- CHANGELOG.md | 2 +- frontend/src/pages/PrintersPage.tsx | 6 ++++++ static/assets/{index-Bre7b40i.js => index-DEBOSiPG.js} | 2 +- static/index.html | 2 +- 4 files changed, 9 insertions(+), 3 deletions(-) rename static/assets/{index-Bre7b40i.js => index-DEBOSiPG.js} (98%) diff --git a/CHANGELOG.md b/CHANGELOG.md index c0aaaa6b4..60d67f8a4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,7 +26,7 @@ All notable changes to Bambuddy will be documented in this file. - **Dependency Updates for Published Advisories** — Bumped two dependencies flagged by vulnerability scanners. `python-multipart` 0.0.22 → 0.0.26 closes CVE-2026-40347 (GHSA-mj87-hwqh-73pj), a denial-of-service triggered by large preamble or epilogue data around a multipart boundary — the 0.0.26 release now skips the preamble before the first boundary and silently discards the epilogue after the closing one. Bambuddy uses `python-multipart` transitively through FastAPI/Starlette for form and file-upload parsing, so any authenticated endpoint accepting `multipart/form-data` (e.g. backup restore, project thumbnail upload) was exposed. `dompurify` 3.3.3 → 3.4.0 picks up the fix for GHSA-39q2-94rc-95cp (the function-form `ADD_TAGS` could bypass `FORBID_TAGS`); Bambuddy's two call sites (`ProjectDetailPage`, `ProjectPageModal`) only use array-form `ALLOWED_TAGS`/`ALLOWED_ATTR`, so the specific bypass was not reachable, but the bump still hardens the sanitizer against future misconfiguration and clears the audit warning. ### Fixed -- **Bambu Lab X2D Support** ([#988](https://github.com/maziggy/bambuddy/issues/988)) — The newly released X2D (dual-nozzle, enclosed, hardened steel rod gantry, AMS 2 Pro compatible) identifies itself as internal model code `N6` via SSDP/MQTT, and serials begin with `20P9`. Because neither the code nor the prefix existed in any of Bambuddy's model tables, multiple paths silently fell back to wrong defaults: the camera service routed to the chamber-image protocol on port 6000 (which the X2D doesn't speak) instead of RTSP on port 322 — the reporter saw `Chamber image: data is not a valid JPEG` spam and no stream; the K-profile edit/delete path conditioned its in-place `cali_idx` write on the H2D serial prefix `094` and would therefore have treated X2D as a single-nozzle printer even though its dual-extruder layout matches H2D; the firmware-update check logged `Unknown printer model: N6`; and the virtual-printer model registry had no way to emulate X2D. Added the `N6 → X2D` mapping across every registry (`PRINTER_MODEL_ID_MAP`, `PRINTER_MODEL_MAP`, `ETHERNET_MODELS`, `STEEL_ROD_MODELS`, `CHAMBER_TEMP_SUPPORTED_MODELS`, firmware-check API keys and wiki path, virtual-printer SSDP product names and serial prefix, DB migration `vp_model_fixes`), extended `supports_rtsp()` to match `X2` display names and the `N6` internal code (camera now goes to port 322), expanded the dual-nozzle serial prefix check in `kprofiles.py` and the K-profile delete command in `bambu_mqtt.py` to also accept `20P9` so the H2D-style `cali_idx` in-place edit path runs on X2D, added X2D to the `is_h2d` model-family gate that selects the integer-format `timelapse`/`bed_leveling`/`flow_cali`/`vibration_cali`/`layer_inspect` fields in the MQTT print command, and added X2D to the frontend's door-badge and airduct-mode whitelists, `mapModelCode` lookups on both the Printers page and Spoolbuddy AMS page, and the MaintenancePage wiki-URL resolver (X2D inherits P2S's steel-rod lubrication, belt-tension, nozzle cold-pull and PTFE wiki pages, since its hardware is closer to P2S than to H2). Credit to @krautech for the report and the debug bundle, and to @legend813 for the initial PR (#989) that seeded most of the registry changes — the classification was corrected (X2D uses hardened steel rods like P2S, not carbon rods) and the dual-nozzle/K-profile gaps were added on top. +- **Bambu Lab X2D Support** ([#988](https://github.com/maziggy/bambuddy/issues/988)) — Added X2D to the Add Printer and Edit Printer model dropdowns (both were missing the new model, so manual printer setup had no X2D option — auto-discovery via SSDP was unaffected). The newly released X2D (dual-nozzle, enclosed, hardened steel rod gantry, AMS 2 Pro compatible) identifies itself as internal model code `N6` via SSDP/MQTT, and serials begin with `20P9`. Because neither the code nor the prefix existed in any of Bambuddy's model tables, multiple paths silently fell back to wrong defaults: the camera service routed to the chamber-image protocol on port 6000 (which the X2D doesn't speak) instead of RTSP on port 322 — the reporter saw `Chamber image: data is not a valid JPEG` spam and no stream; the K-profile edit/delete path conditioned its in-place `cali_idx` write on the H2D serial prefix `094` and would therefore have treated X2D as a single-nozzle printer even though its dual-extruder layout matches H2D; the firmware-update check logged `Unknown printer model: N6`; and the virtual-printer model registry had no way to emulate X2D. Added the `N6 → X2D` mapping across every registry (`PRINTER_MODEL_ID_MAP`, `PRINTER_MODEL_MAP`, `ETHERNET_MODELS`, `STEEL_ROD_MODELS`, `CHAMBER_TEMP_SUPPORTED_MODELS`, firmware-check API keys and wiki path, virtual-printer SSDP product names and serial prefix, DB migration `vp_model_fixes`), extended `supports_rtsp()` to match `X2` display names and the `N6` internal code (camera now goes to port 322), expanded the dual-nozzle serial prefix check in `kprofiles.py` and the K-profile delete command in `bambu_mqtt.py` to also accept `20P9` so the H2D-style `cali_idx` in-place edit path runs on X2D, added X2D to the `is_h2d` model-family gate that selects the integer-format `timelapse`/`bed_leveling`/`flow_cali`/`vibration_cali`/`layer_inspect` fields in the MQTT print command, and added X2D to the frontend's door-badge and airduct-mode whitelists, `mapModelCode` lookups on both the Printers page and Spoolbuddy AMS page, and the MaintenancePage wiki-URL resolver (X2D inherits P2S's steel-rod lubrication, belt-tension, nozzle cold-pull and PTFE wiki pages, since its hardware is closer to P2S than to H2). Credit to @krautech for the report and the debug bundle, and to @legend813 for the initial PR (#989) that seeded most of the registry changes — the classification was corrected (X2D uses hardened steel rods like P2S, not carbon rods) and the dual-nozzle/K-profile gaps were added on top. - **Print Speed Icon Not Updating Live When Changed on Printer** ([#993](https://github.com/maziggy/bambuddy/issues/993)) — Changing the print speed mode from the printer's own panel (instead of from Bambuddy) did not update the speed icon on the Printers page card; the new value only appeared after a full page reload. The MQTT parser was already tracking `spd_lvl` and updating `state.speed_level` correctly, but the WebSocket serializer (`printer_state_to_dict`) was missing the field — so live status pushes never carried `speed_level`, and the frontend's merge-over-old-cache update left the icon stuck on its previous value. The REST `/status` endpoint used on initial page load already included it, which is why reloads worked. Added `speed_level` to the WebSocket payload. Thanks to @chesterakl for reporting. - **Camera Popup Shows "Valid camera stream token required" With Auth Enabled** ([#979](https://github.com/maziggy/bambuddy/issues/979)) — When Camera View Mode was set to "Window" and authentication was enabled, clicking the camera button opened a popup that immediately failed with `"Valid camera stream token required"`, while the embedded overlay kept working. Two root causes: (1) `window.open(...)` passed `noopener` in the popup features, which severed the opener link and prevented the browser from copying sessionStorage (where the auth token lives) into the popup — so the new window booted unauthenticated and the `POST /printers/camera/stream-token` fetch returned 401, leaving the `` src without the required `?token=` query param; (2) even once the token arrived, `CameraPage` computed its URL from the module-level stream-token cache on render and never re-rendered when the cache was updated in a `useEffect`, so the first paint locked in a tokenless URL that the backend kept rejecting. Fixed by dropping `noopener` from the camera popup features (same-origin, trusted window) so sessionStorage is inherited, subscribing `CameraPage` to the `camera-stream-token` React Query so it re-renders the moment the token resolves, and appending the token directly from the reactive query value instead of the effect-synced module cache — the `` src stays empty until the token is ready, so no tokenless request ever leaves the popup. Embedded-overlay mode was unaffected. Thanks to @VREmma for the reproducer. - **Obico ML API Got 401 When Fetching Snapshot with Auth Enabled** ([#172](https://github.com/maziggy/bambuddy/issues/172)) — The Obico failure-detection service handed the ML API container a snapshot URL (`/api/v1/printers/{id}/camera/snapshot`) for it to `GET` directly, but when Bambuddy authentication was enabled the endpoint returned 401 and the ML API surfaced "Failed to get image" (visible as a 400 from the ML API back to Bambuddy). The detection service now appends a short-lived camera-stream token to the snapshot URL — the same token scheme already used by ``-based camera consumers, which the snapshot endpoint already accepts. The token is cached on the service and refreshed before its 60-minute expiry, so no extra per-call DB churn. When auth is disabled the token is simply ignored. Thanks to @fblix for reporting. diff --git a/frontend/src/pages/PrintersPage.tsx b/frontend/src/pages/PrintersPage.tsx index 39ba690ec..bfdfa9cbb 100644 --- a/frontend/src/pages/PrintersPage.tsx +++ b/frontend/src/pages/PrintersPage.tsx @@ -5271,6 +5271,9 @@ function AddPrinterModal({ + + + @@ -5725,6 +5728,9 @@ function EditPrinterModal({ + + + diff --git a/static/assets/index-Bre7b40i.js b/static/assets/index-DEBOSiPG.js similarity index 98% rename from static/assets/index-Bre7b40i.js rename to static/assets/index-DEBOSiPG.js index ac142fbb5..1d022bca8 100644 --- a/static/assets/index-Bre7b40i.js +++ b/static/assets/index-DEBOSiPG.js @@ -8538,7 +8538,7 @@ ${o("inventory.assignProfileMismatchMessage",{spoolProfile:C.spoolProfile||o("co flex items-center justify-center gap-1 px-3 py-1.5 rounded-lg text-xs font-medium transition-colors ${Kt&&k("printers:control")?Tt?"bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30":"bg-yellow-500/20 text-yellow-400 hover:bg-yellow-500/30":"bg-bambu-dark text-bambu-gray/50 cursor-not-allowed"} - `,title:k("printers:control")?N(Tt?"printers.resume":"printers.pause"):N("printers.permission.noControl"),children:[Tt?a.jsx(Gi,{className:"w-3 h-3"}):a.jsx(Xw,{className:"w-3 h-3"}),N(Tt?"printers.resume":"printers.pause")]})]})]})]})})(),(En?.length>0||Ue.vt_tray.length>0)&&r==="expanded"&&(()=>{const tt=En.filter(it=>it.tray.length>1),Tt=En.filter(it=>it.tray.length===1),Kt=t.nozzle_count===2||Ue?.temperatures?.nozzle_2!==void 0;return a.jsxs("div",{className:"mt-3",children:[a.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[a.jsx("span",{className:"text-[10px] uppercase tracking-wider text-bambu-gray font-medium",children:N("printers.filaments")}),a.jsx("div",{className:"flex-1 h-px bg-bambu-dark-tertiary/30"})]}),a.jsxs("div",{className:"space-y-3",children:[tt.length>0&&a.jsx("div",{className:"grid grid-cols-2 gap-3",children:tt.map(it=>{const nn=hr[String(it.id)],gr=it.id>=128?it.id-128:it.id,Kn=nn!==void 0?nn:gr,ua=Kn===1,ga=Kn===0;return a.jsxs("div",{className:"p-2.5 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary/30",children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsxs("div",{className:"flex items-center gap-1.5",children:[a.jsx(lK,{ams:it,printerId:t.id,label:Rl(it.id,it.tray.length),amsLabels:Gt,canEdit:k("printers:update"),onSaved:ln,children:a.jsx("span",{className:"text-[10px] text-white font-medium cursor-default select-none",children:Gt?.[it.id]||Rl(it.id,it.tray.length)})}),Kt&&(ua||ga)&&a.jsx(nK,{side:ua?"L":"R"})]}),(it.humidity!=null||it.temp!=null)&&a.jsxs("div",{className:"flex items-center gap-1.5 max-[550px]:flex-col max-[550px]:items-start",children:[it.humidity!=null&&a.jsx(aK,{humidity:it.humidity,goodThreshold:s?.humidityGood,fairThreshold:s?.humidityFair,onClick:()=>rn({amsId:it.id,amsLabel:Rl(it.id,it.tray.length),mode:"humidity"}),compact:!0}),it.temp!=null&&a.jsx(iK,{temp:it.temp,goodThreshold:s?.tempGood,fairThreshold:s?.tempFair,onClick:()=>rn({amsId:it.id,amsLabel:Rl(it.id,it.tray.length),mode:"temperature"}),compact:!0}),Ue.supports_drying&&(it.module_type==="n3f"||it.module_type==="n3s")&&k("printers:control")&&a.jsx("button",{disabled:!!(it.dry_sf_reason?.length&&it.dry_time===0),onClick:en=>{if(it.dry_time>0)fa.mutate(it.id);else if(Me===it.id)Fe(null);else{const Sa=(it.tray.find(Ho=>Ho.tray_type)?.tray_type||"PLA").split(" ")[0].toUpperCase(),Ja=b[Sa]||b.PLA,Yi=it.module_type;nt(Sa),ze(Ja[Yi]||Ja.n3f),Ve(Yi==="n3s"?Ja.n3s_hours:Ja.n3f_hours),ue(!1),qe(it.module_type),Fe(it.id);const Sl=en.currentTarget.getBoundingClientRect();Be({top:Sl.bottom+4,left:Math.max(8,Sl.right-240)})}},className:`flex items-center gap-0.5 px-1 py-0.5 rounded text-[9px] transition-colors ${it.dry_time>0?"bg-amber-500/20 text-amber-400":it.dry_sf_reason?.length?"bg-bambu-dark-tertiary/30 text-bambu-gray/50 cursor-not-allowed":"bg-bambu-dark-tertiary/50 text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary"}`,title:it.dry_time>0?N("printers.drying.stop"):it.dry_sf_reason?.length?N("printers.drying.powerRequired"):N("printers.drying.start"),children:a.jsx(Lu,{className:"w-3 h-3"})})]})]}),it.dry_time>0&&a.jsxs("div",{className:"flex items-center gap-2 px-2 py-1 mb-1 bg-amber-500/10 border border-amber-500/20 rounded text-[9px]",children:[a.jsx(Lu,{className:"w-3 h-3 text-amber-400 shrink-0"}),a.jsx("span",{className:"text-amber-400 font-medium",children:N("printers.drying.active")}),a.jsx("span",{className:"text-amber-300/70",children:N("printers.drying.timeRemaining",{time:it.dry_time>=60?`${Math.floor(it.dry_time/60)}h ${it.dry_time%60}m`:`${it.dry_time}m`})}),a.jsx("button",{onClick:()=>fa.mutate(it.id),disabled:fa.isPending,className:"ml-auto text-amber-400 hover:text-amber-300 transition-colors disabled:opacity-50",title:N("printers.drying.stop"),children:a.jsx(Ht,{className:"w-3 h-3"})})]}),a.jsx("div",{className:"grid grid-cols-4 gap-1.5",children:[0,1,2,3].map(en=>{const Tn=it.tray[en]||it.tray.find(Fn=>Fn.id===en),Sa=Tn?.tray_type&&Tn.remain>=0,Ja=!Tn?.tray_type,Yi=it.id*4+en,Sl=na===Yi,Ho=Tn?.tray_info_idx?vt?.[Tn.tray_info_idx]:null,qr=Et?.[Yi],Qi=(Tn?.tray_uuid||Tn?.tag_uid||zu(t.serial_number,it.id,en))?.toUpperCase(),vc=Qi?l?.[Qi]:void 0,Ss=Xk(vc),bo=u?.(t.id,it.id,en),wc=(()=>{const Fn=bo?.spool;return Fn&&Fn.label_weight>0&&Fn.weight_used!=null?Math.round(Math.max(0,Fn.label_weight-Fn.weight_used)/Fn.label_weight*100):null})(),Or=wc===0&&Sa&&Tn.remain>0?null:wc,Zi=Ss??Or??(Sa?Tn.remain:null),Oy=Ss!==null?"spoolman":Or!==null?"inventory":Sa?"ams":void 0,$r=Tn?.tray_type?{vendor:MD(Tn)?"Bambu Lab":"Generic",profile:qr?.preset_name||Ho?.name||bo?.spool?.slicer_filament_name||Tn.tray_sub_brands||Tn.tray_type,colorName:Zl(Tn.tray_color||""),colorHex:Tn.tray_color||null,kFactor:AD(Tn.k),fillLevel:Zi,trayUuid:Tn.tray_uuid||null,tagUid:Tn.tag_uid||null,fillSource:Oy}:null,id=ws?.amsId===it.id&&ws?.slotId===en,Dm=a.jsxs("div",{className:`bg-bambu-dark-tertiary rounded p-1 text-center ${Ja?"opacity-50":""} ${Sl?"ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark":""}`,children:[a.jsx(TD,{trayColor:Tn?.tray_color,trayType:Tn?.tray_type,isEmpty:Ja,slotNumber:en+1}),a.jsx("div",{className:"text-[9px] text-white font-bold truncate",children:Tn?.tray_type||"—"}),a.jsx("div",{className:"mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden",children:Zi!==null&&Zi>=0&&!Ja&&Tn&&a.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${Zi}%`,backgroundColor:Tx(Zi)}})})]});return a.jsxs("div",{className:"relative group",children:[id&&a.jsx("div",{className:"absolute inset-0 bg-bambu-dark-tertiary/80 rounded flex items-center justify-center z-20",children:a.jsx(or,{className:"w-4 h-4 text-bambu-green animate-spin"})}),Ue?.state!=="RUNNING"&&a.jsx("button",{onClick:Fn=>{Fn.stopPropagation(),tu(go?.amsId===it.id&&go?.slotId===en?null:{amsId:it.id,slotId:en})},className:"absolute -top-1 -right-1 w-4 h-4 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity z-10 hover:bg-bambu-dark-tertiary",title:N("printers.slotOptions"),children:a.jsx(Gh,{className:"w-2.5 h-2.5 text-bambu-gray"})}),Ue?.state!=="RUNNING"&&go?.amsId===it.id&&go?.slotId===en&&a.jsx("div",{className:"absolute top-full left-0 mt-1 z-50 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl py-1 min-w-[120px]",children:a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-xs flex items-center gap-2 ${k("printers:ams_rfid")?"text-white hover:bg-bambu-dark-tertiary":"text-bambu-gray/50 cursor-not-allowed"}`,onClick:Fn=>{Fn.stopPropagation(),k("printers:ams_rfid")&&(nd.mutate({amsId:it.id,slotId:en}),tu(null))},disabled:id||!k("printers:ams_rfid"),title:k("printers:ams_rfid")?void 0:N("printers.permission.noAmsRfid"),children:[a.jsx(or,{className:`w-3 h-3 ${id?"animate-spin":""}`}),N("printers.rfid.reread")]})}),$r?a.jsx(kD,{data:$r,spoolman:{enabled:o,linkedSpoolId:Qi?l?.[Qi]?.id:void 0,spoolmanUrl:c,syncMode:d,onLinkSpool:o?()=>{const Fn=($r.trayUuid||$r.tagUid||zu(t.serial_number,it.id,en)).toUpperCase();Jt({tagUid:$r.tagUid||Fn,trayUuid:$r.trayUuid||"",printerId:t.id,amsId:it.id,trayId:en})}:void 0,onUnlinkSpool:vc?.id?()=>Uo.mutate(vc.id):void 0},inventory:o?void 0:(()=>{const Fn=u?.(t.id,it.id,en);return{assignedSpool:Fn?.spool?{id:Fn.spool.id,material:Fn.spool.material,brand:Fn.spool.brand,color_name:Fn.spool.color_name,remainingWeightGrams:Math.max(0,Math.round(Fn.spool.label_weight-Fn.spool.weight_used))}:null,onAssignSpool:$r.vendor!=="Bambu Lab"?()=>Ft({printerId:t.id,amsId:it.id,trayId:en,trayInfo:{type:Tn?.tray_type||$r.profile,material:Tn?.tray_type??void 0,profile:$r.profile,color:$r.colorHex||"",location:`${Rl(it.id,it.tray.length)} Slot ${en+1}`}}):void 0,onUnassignSpool:Fn&&$r.vendor!=="Bambu Lab"?()=>m?.(t.id,it.id,en):void 0}})(),configureSlot:{enabled:k("printers:control"),onConfigure:()=>Nt({amsId:it.id,trayId:en,trayCount:it.tray.length,trayType:Tn?.tray_type||void 0,trayColor:Tn?.tray_color||void 0,traySubBrands:Tn?.tray_sub_brands||void 0,trayInfoIdx:Tn?.tray_info_idx||void 0,extruderId:nn,caliIdx:Tn?.cali_idx,savedPresetId:qr?.preset_id})},children:Dm}):a.jsx(ND,{configureSlot:Tn?.state===10?{enabled:k("printers:control"),onConfigure:()=>Nt({amsId:it.id,trayId:en,trayCount:it.tray.length,extruderId:nn})}:void 0,inventory:Tn?.state===10&&!o?{onAssignSpool:()=>Ft({printerId:t.id,amsId:it.id,trayId:en,trayInfo:{type:"",color:"",location:`${Rl(it.id,it.tray.length)} Slot ${en+1}`}})}:void 0,children:Dm})]},en)})})]},it.id)})}),(Tt.length>0||Ue.vt_tray.length>0)&&a.jsxs("div",{className:"grid grid-cols-4 gap-3",children:[Tt.map(it=>{const nn=hr[String(it.id)],gr=it.id>=128?it.id-128:it.id,Kn=nn!==void 0?nn:gr,ua=Kn===1,ga=Kn===0,en=it.tray[0],Tn=en?.tray_type&&en.remain>=0,Sa=!en?.tray_type,Ja=Jx(it.id,en?.id??0,!1),Yi=na===Ja,Sl=en?.tray_info_idx?vt?.[en.tray_info_idx]:null,Ho=Et?.[Ja],qr=en?.id??0,Qi=(en?.tray_uuid||en?.tag_uid||zu(t.serial_number,it.id,qr))?.toUpperCase(),vc=Qi?l?.[Qi]:void 0,Ss=Xk(vc),bo=u?.(t.id,it.id,qr),wc=(()=>{const Fn=bo?.spool;return Fn&&Fn.label_weight>0&&Fn.weight_used!=null?Math.round(Math.max(0,Fn.label_weight-Fn.weight_used)/Fn.label_weight*100):null})(),Or=wc===0&&Tn&&en.remain>0?null:wc,Zi=Ss??Or??(Tn?en.remain:null),Oy=Ss!==null?"spoolman":Or!==null?"inventory":Tn?"ams":void 0,$r=en?.tray_type?{vendor:MD(en)?"Bambu Lab":"Generic",profile:Ho?.preset_name||Sl?.name||bo?.spool?.slicer_filament_name||en.tray_sub_brands||en.tray_type,colorName:Zl(en.tray_color||""),colorHex:en.tray_color||null,kFactor:AD(en.k),fillLevel:Zi,trayUuid:en.tray_uuid||null,tagUid:en.tag_uid||null,fillSource:Oy}:null,id=ws?.amsId===it.id&&ws?.slotId===qr,Dm=a.jsxs("div",{className:`bg-bambu-dark-tertiary rounded p-1 text-center ${Sa?"opacity-50":""} ${Yi?"ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark":""}`,children:[a.jsx(TD,{trayColor:en?.tray_color,trayType:en?.tray_type,isEmpty:Sa,slotNumber:1}),a.jsx("div",{className:"text-[9px] text-white font-bold truncate",children:en?.tray_type||"—"}),a.jsx("div",{className:"mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden",children:Zi!==null&&Zi>=0&&!Sa&&a.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${Zi}%`,backgroundColor:Tx(Zi)}})})]});return a.jsxs("div",{className:"p-2.5 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary/30",children:[a.jsxs("div",{className:"flex items-center gap-1 mb-2",children:[a.jsx(lK,{ams:it,printerId:t.id,label:Rl(it.id,it.tray.length),amsLabels:Gt,canEdit:k("printers:update"),onSaved:ln,children:a.jsx("span",{className:"text-[10px] text-white font-medium cursor-default select-none",children:Gt?.[it.id]||Rl(it.id,it.tray.length)})}),Kt&&(ua||ga)&&a.jsx(nK,{side:ua?"L":"R"}),Ue.supports_drying&&(it.module_type==="n3f"||it.module_type==="n3s")&&k("printers:control")&&a.jsx("div",{className:"relative ml-auto",children:a.jsx("button",{onClick:Fn=>{if(it.dry_time>0)fa.mutate(it.id);else if(Me===it.id)Fe(null);else{const Iy=(it.tray.find(bA=>bA.tray_type)?.tray_type||"PLA").split(" ")[0].toUpperCase(),Fp=b[Iy]||b.PLA,zy=it.module_type;nt(Iy),ze(Fp[zy]||Fp.n3f),Ve(zy==="n3s"?Fp.n3s_hours:Fp.n3f_hours),ue(!1),qe(it.module_type),Fe(it.id);const OS=Fn.currentTarget.getBoundingClientRect();Be({top:OS.bottom+4,left:Math.max(8,OS.right-240)})}},className:`flex items-center gap-0.5 px-1 py-0.5 rounded text-[9px] transition-colors ${it.dry_time>0?"bg-amber-500/20 text-amber-400":"bg-bambu-dark-tertiary/50 text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary"}`,title:it.dry_time>0?N("printers.drying.stop"):N("printers.drying.start"),children:a.jsx(Lu,{className:"w-3 h-3"})})})]}),it.dry_time>0&&a.jsxs("div",{className:"flex items-center gap-1.5 px-2 py-1 mb-1 bg-amber-500/10 border border-amber-500/20 rounded text-[9px] whitespace-nowrap overflow-hidden",children:[a.jsx(Lu,{className:"w-3 h-3 text-amber-400 shrink-0"}),a.jsx("span",{className:"text-amber-300/70 text-[8px] truncate",children:it.dry_time>=60?`${Math.floor(it.dry_time/60)}h ${it.dry_time%60}m`:`${it.dry_time}m`}),a.jsx("button",{onClick:()=>fa.mutate(it.id),disabled:fa.isPending,className:"ml-auto text-amber-400 hover:text-amber-300 transition-colors disabled:opacity-50 shrink-0",title:N("printers.drying.stop"),children:a.jsx(Ht,{className:"w-3 h-3"})})]}),a.jsxs("div",{className:"flex gap-1.5 max-[550px]:flex-col max-[550px]:items-start",children:[a.jsxs("div",{className:"relative group flex-1 max-[550px]:w-full",children:[id&&a.jsx("div",{className:"absolute inset-0 bg-bambu-dark-tertiary/80 rounded flex items-center justify-center z-20",children:a.jsx(or,{className:"w-4 h-4 text-bambu-green animate-spin"})}),Ue?.state!=="RUNNING"&&a.jsx("button",{onClick:Fn=>{Fn.stopPropagation(),tu(go?.amsId===it.id&&go?.slotId===qr?null:{amsId:it.id,slotId:qr})},className:"absolute -top-1 -right-1 w-4 h-4 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity z-10 hover:bg-bambu-dark-tertiary",title:N("printers.slotOptions"),children:a.jsx(Gh,{className:"w-2.5 h-2.5 text-bambu-gray"})}),Ue?.state!=="RUNNING"&&go?.amsId===it.id&&go?.slotId===qr&&a.jsx("div",{className:"absolute top-full left-0 mt-1 z-50 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl py-1 min-w-[120px]",children:a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-xs flex items-center gap-2 ${k("printers:ams_rfid")?"text-white hover:bg-bambu-dark-tertiary":"text-bambu-gray/50 cursor-not-allowed"}`,onClick:Fn=>{Fn.stopPropagation(),k("printers:ams_rfid")&&(nd.mutate({amsId:it.id,slotId:qr}),tu(null))},disabled:id||!k("printers:ams_rfid"),title:k("printers:ams_rfid")?void 0:N("printers.permission.noAmsRfid"),children:[a.jsx(or,{className:`w-3 h-3 ${id?"animate-spin":""}`}),N("printers.rfid.reread")]})}),$r?a.jsx(kD,{data:$r,spoolman:{enabled:o,linkedSpoolId:Qi?l?.[Qi]?.id:void 0,spoolmanUrl:c,syncMode:d,onLinkSpool:o?()=>{const Fn=($r.trayUuid||$r.tagUid||zu(t.serial_number,it.id,qr)).toUpperCase();Jt({tagUid:$r.tagUid||Fn,trayUuid:$r.trayUuid||"",printerId:t.id,amsId:it.id,trayId:qr})}:void 0,onUnlinkSpool:vc?.id?()=>Uo.mutate(vc.id):void 0},inventory:o?void 0:(()=>{const Fn=u?.(t.id,it.id,qr);return{assignedSpool:Fn?.spool?{id:Fn.spool.id,material:Fn.spool.material,brand:Fn.spool.brand,color_name:Fn.spool.color_name,remainingWeightGrams:Math.max(0,Math.round(Fn.spool.label_weight-Fn.spool.weight_used))}:null,onAssignSpool:$r.vendor!=="Bambu Lab"?()=>Ft({printerId:t.id,amsId:it.id,trayId:qr,trayInfo:{type:en?.tray_type||$r.profile,material:en?.tray_type??void 0,profile:$r.profile,color:$r.colorHex||"",location:Rl(it.id,it.tray.length)}}):void 0,onUnassignSpool:Fn&&$r.vendor!=="Bambu Lab"?()=>m?.(t.id,it.id,qr):void 0}})(),configureSlot:{enabled:k("printers:control"),onConfigure:()=>Nt({amsId:it.id,trayId:qr,trayCount:it.tray.length,trayType:en?.tray_type||void 0,trayColor:en?.tray_color||void 0,traySubBrands:en?.tray_sub_brands||void 0,trayInfoIdx:en?.tray_info_idx||void 0,extruderId:nn,caliIdx:en?.cali_idx,savedPresetId:Ho?.preset_id})},children:Dm}):a.jsx(ND,{configureSlot:en?.state===10?{enabled:k("printers:control"),onConfigure:()=>Nt({amsId:it.id,trayId:qr,trayCount:it.tray.length,extruderId:nn})}:void 0,inventory:en?.state===10&&!o?{onAssignSpool:()=>Ft({printerId:t.id,amsId:it.id,trayId:qr,trayInfo:{type:"",color:"",location:Rl(it.id,it.tray.length)}})}:void 0,children:Dm})]}),(it.humidity!=null||it.temp!=null)&&a.jsxs("div",{className:"flex flex-col justify-center gap-1 shrink-0 max-[550px]:w-full",children:[it.temp!=null&&a.jsx(iK,{temp:it.temp,goodThreshold:s?.tempGood,fairThreshold:s?.tempFair,onClick:()=>rn({amsId:it.id,amsLabel:Rl(it.id,it.tray.length),mode:"temperature"}),compact:!0}),it.humidity!=null&&a.jsx(aK,{humidity:it.humidity,goodThreshold:s?.humidityGood,fairThreshold:s?.humidityFair,onClick:()=>rn({amsId:it.id,amsLabel:Rl(it.id,it.tray.length),mode:"humidity"}),compact:!0})]})]})]},it.id)}),Ue.vt_tray.length>0&&a.jsxs("div",{className:`p-2.5 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary/30 ${Ue.vt_tray.length===1?"max-w-[50%]":""}`,children:[a.jsx("div",{className:"flex items-center gap-1 mb-2",children:a.jsx("span",{className:"text-[10px] text-white font-medium",children:N("printers.external")})}),a.jsx("div",{className:`grid ${Ue.vt_tray.length>1?"grid-cols-2":"grid-cols-1"} gap-1.5`,children:[...Ue.vt_tray].sort((it,nn)=>(it.id??254)-(nn.id??254)).map(it=>{const nn=it.id??254,gr=Kt&&na===254?nn===254&&Ue.active_extruder===1||nn===255&&Ue.active_extruder===0:na===nn,Kn=nn-254,ua=Kt?N(nn===254?"printers.extL":"printers.extR"):"",ga=it.tray_info_idx?vt?.[it.tray_info_idx]:null,en=Et?.[1020+Kn],Tn=(it.tray_uuid||it.tag_uid||zu(t.serial_number,255,Kn))?.toUpperCase(),Sa=Tn?l?.[Tn]:void 0,Ja=Xk(Sa),Yi=u?.(t.id,255,Kn),Sl=(()=>{const Or=Yi?.spool;return Or&&Or.label_weight>0&&Or.weight_used!=null?Math.round(Math.max(0,Or.label_weight-Or.weight_used)/Or.label_weight*100):null})(),Ho=it.tray_type&&it.remain>=0,qr=Sl===0&&Ho&&it.remain>0?null:Sl,Qi=Ja??qr??(Ho?it.remain:null),vc=Ja!==null?"spoolman":qr!==null?"inventory":Ho?"ams":void 0,Ss={vendor:MD(it)?"Bambu Lab":"Generic",profile:en?.preset_name||ga?.name||Yi?.spool?.slicer_filament_name||it.tray_sub_brands||it.tray_type||"Unknown",colorName:Zl(it.tray_color||""),colorHex:it.tray_color||null,kFactor:AD(it.k),fillLevel:Qi,trayUuid:it.tray_uuid||null,tagUid:it.tag_uid||null,fillSource:vc},bo=!it.tray_type,wc=a.jsxs("div",{className:`bg-bambu-dark-tertiary rounded p-1 text-center ${bo?"opacity-50":""} ${gr?"ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark":""}`,children:[a.jsx(TD,{trayColor:it.tray_color,trayType:it.tray_type,isEmpty:bo,slotNumber:Kn+1}),a.jsx("div",{className:`text-[9px] font-bold truncate ${bo?"text-white/40":"text-white"}`,children:it.tray_type||"—"}),a.jsx("div",{className:"mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden",children:Qi!==null&&Qi>=0&&!bo&&a.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${Qi}%`,backgroundColor:Tx(Qi)}})}),ua&&a.jsx("div",{className:"text-[7px] text-white/40 mt-0.5 truncate",children:ua})]});return a.jsx("div",{className:"relative group",children:bo?a.jsx(ND,{configureSlot:{enabled:k("printers:control"),onConfigure:()=>Nt({amsId:255,trayId:Kn,trayCount:1,extruderId:Kt?nn===254?1:0:void 0})},inventory:o?void 0:{onAssignSpool:()=>Ft({printerId:t.id,amsId:255,trayId:Kn,trayInfo:{type:"",color:"",location:ua||N("printers.external")}})},children:wc}):a.jsx(kD,{data:Ss,spoolman:{enabled:o,linkedSpoolId:Tn?l?.[Tn]?.id:void 0,spoolmanUrl:c,syncMode:d,onLinkSpool:o?()=>{const Or=(Ss.trayUuid||Ss.tagUid||zu(t.serial_number,255,Kn)).toUpperCase();Jt({tagUid:Ss.tagUid||Or,trayUuid:Ss.trayUuid||"",printerId:t.id,amsId:255,trayId:Kn})}:void 0,onUnlinkSpool:Sa?.id?()=>Uo.mutate(Sa.id):void 0},inventory:o?void 0:(()=>{const Or=u?.(t.id,255,Kn);return{assignedSpool:Or?.spool?{id:Or.spool.id,material:Or.spool.material,brand:Or.spool.brand,color_name:Or.spool.color_name,remainingWeightGrams:Math.max(0,Math.round(Or.spool.label_weight-Or.spool.weight_used))}:null,onAssignSpool:()=>Ft({printerId:t.id,amsId:255,trayId:Kn,trayInfo:{type:it.tray_type||Ss.profile,material:it.tray_type??void 0,profile:Ss.profile,color:Ss.colorHex||"",location:ua||N("printers.external")}}),onUnassignSpool:Or?()=>m?.(t.id,255,Kn):void 0}})(),configureSlot:{enabled:k("printers:control"),onConfigure:()=>Nt({amsId:255,trayId:Kn,trayCount:1,trayType:it.tray_type||void 0,trayColor:it.tray_color||void 0,traySubBrands:it.tray_sub_brands||void 0,trayInfoIdx:it.tray_info_idx||void 0,extruderId:Kt?nn===254?1:0:void 0,caliIdx:it.cali_idx,savedPresetId:en?.preset_id})},children:wc})},nn)})})]})]})]})]})})()]}),Bn&&r==="expanded"&&a.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[a.jsx(ic,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}),a.jsx("span",{className:"text-sm text-white truncate",children:Bn.name}),pr&&a.jsxs("span",{className:`text-xs px-1.5 py-0.5 rounded flex-shrink-0 ${pr.state==="ON"?"bg-bambu-green/20 text-bambu-green":pr.state==="OFF"?"bg-red-500/20 text-red-400":"bg-bambu-gray/20 text-bambu-gray"}`,children:[pr.state||"?",pr.state==="ON"&&pr.energy?.power!=null&&a.jsxs("span",{className:"text-yellow-400 ml-1.5",children:["· ",pr.energy.power,"W"]})]})]}),a.jsx("div",{className:"flex-1"}),a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsxs("button",{onClick:()=>pe(!0),disabled:Zc.isPending||pr?.state==="ON"||!k("smart_plugs:control"),className:`px-2 py-1 text-xs rounded transition-colors flex items-center gap-1 ${k("smart_plugs:control")?pr?.state==="ON"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary":"bg-bambu-dark text-bambu-gray/50 cursor-not-allowed"}`,title:k("smart_plugs:control")?void 0:N("printers.permission.noSmartPlugControl"),children:[a.jsx(Wd,{className:"w-3 h-3"}),"On"]}),a.jsxs("button",{onClick:()=>Ce(!0),disabled:Zc.isPending||pr?.state==="OFF"||!k("smart_plugs:control"),className:`px-2 py-1 text-xs rounded transition-colors flex items-center gap-1 ${k("smart_plugs:control")?pr?.state==="OFF"?"bg-red-500/30 text-red-400":"bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary":"bg-bambu-dark text-bambu-gray/50 cursor-not-allowed"}`,title:k("smart_plugs:control")?void 0:N("printers.permission.noSmartPlugControl"),children:[a.jsx(Yw,{className:"w-3 h-3"}),"Off"]})]}),a.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[a.jsx("span",{className:`text-xs hidden sm:inline ${Bn.auto_off_executed?"text-bambu-green":"text-bambu-gray"}`,children:Bn.auto_off_executed?"Auto-off done":"Auto-off"}),a.jsx("button",{onClick:()=>Mm.mutate(!Bn.auto_off),disabled:Mm.isPending||Bn.auto_off_executed||!k("smart_plugs:control"),title:k("smart_plugs:control")?Bn.auto_off_executed?N("printers.autoOffExecuted"):N("printers.autoOffAfterPrint"):N("printers.permission.noSmartPlugControl"),className:`relative w-9 h-5 rounded-full transition-colors flex-shrink-0 ${k("smart_plugs:control")?Bn.auto_off_executed?"bg-bambu-green/50 cursor-not-allowed":Bn.auto_off?"bg-bambu-green":"bg-bambu-dark-tertiary":"bg-bambu-dark-tertiary/50 cursor-not-allowed"}`,children:a.jsx("span",{className:`absolute top-[2px] left-[2px] w-4 h-4 bg-white rounded-full transition-transform ${Bn.auto_off||Bn.auto_off_executed?"translate-x-4":"translate-x-0"}`})})]})]}),ra&&ra.length>0&&a.jsxs("div",{className:"flex items-center gap-2 mt-2 pt-2 border-t border-bambu-dark-tertiary/50",children:[a.jsx(Vw,{className:"w-3.5 h-3.5 text-blue-400 flex-shrink-0"}),a.jsx("span",{className:"text-xs text-bambu-gray",children:"HA:"}),a.jsx("div",{className:"flex flex-wrap gap-1",children:ra.map(tt=>{const Tt=tt.ha_entity_id?.startsWith("script.");return a.jsxs("button",{onClick:()=>Jc.mutate({id:tt.id,action:Tt?"on":"toggle"}),disabled:Jc.isPending,title:`${Tt?"Run":"Toggle"} ${tt.ha_entity_id}`,className:"px-2 py-0.5 text-xs bg-blue-500/20 text-blue-400 hover:bg-blue-500/30 rounded transition-colors flex items-center gap-1",children:[a.jsx(Gi,{className:"w-2.5 h-2.5"}),tt.name]},tt.id)})})]})]}),r==="expanded"&&a.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary flex items-center justify-end gap-2 flex-wrap",children:[a.jsx(De,{variant:"secondary",size:"sm",onClick:()=>Bo.mutate(!Ue?.chamber_light),disabled:!Ue?.connected||Bo.isPending||!k("printers:control"),title:k("printers:control")?Ue?.chamber_light?N("printers.chamberLightOff"):N("printers.chamberLightOn"):N("printers.permission.noControl"),className:Ue?.chamber_light?"!border-yellow-500 !text-yellow-400 hover:!bg-yellow-500/20":"",children:a.jsx(uI,{on:Ue?.chamber_light??!1,className:`w-4 h-4 ${Ue?.chamber_light?"text-yellow-400":""}`})}),a.jsx(De,{variant:"secondary",size:"sm",onClick:()=>{if(f==="embedded"&&x)x(t.id,t.name);else{const tt=localStorage.getItem("cameraWindowState"),Tt=tt?JSON.parse(tt):{width:640,height:400},Kt=[`width=${Tt.width}`,`height=${Tt.height}`,Tt.left!==void 0?`left=${Tt.left}`:"",Tt.top!==void 0?`top=${Tt.top}`:"","menubar=no,toolbar=no,location=no,status=no"].filter(Boolean).join(",");window.open(`/camera/${t.id}`,`camera-${t.id}`,Kt)}},disabled:!Ue?.connected||!k("camera:view"),title:k("camera:view")?N(f==="embedded"?"printers.openCameraOverlay":"printers.openCameraWindow"):N("printers.permission.noCamera"),children:a.jsx(jO,{className:"w-4 h-4"})}),a.jsxs("div",{className:`inline-flex rounded-md ${t.plate_detection_enabled?"ring-1 ring-green-500":""}`,children:[a.jsx(De,{variant:"secondary",size:"sm",onClick:Fg,disabled:!Ue?.connected||gc.isPending||!k("printers:update"),title:k("printers:update")?t.plate_detection_enabled?N("printers.plateDetection.enabledClick"):N("printers.plateDetection.disabledClick"):N("printers.plateDetection.noPermission"),className:`!rounded-r-none !border-r-0 ${t.plate_detection_enabled?"!border-green-500 !text-green-400 hover:!bg-green-500/20":""}`,children:gc.isPending?a.jsx(ht,{className:"w-4 h-4 animate-spin"}):a.jsx(yN,{className:"w-4 h-4"})}),a.jsx(De,{variant:"secondary",size:"sm",onClick:eu,disabled:!Ue?.connected||ct||!k("printers:update"),title:k("printers:update")?N("printers.plateDetection.manageCalibration"):N("printers.plateDetection.noPermission"),className:`!rounded-l-none !px-1.5 ${t.plate_detection_enabled?"!border-green-500 !text-green-400 hover:!bg-green-500/20":""}`,children:ct?a.jsx(ht,{className:"w-3 h-3 animate-spin"}):a.jsx(In,{className:"w-3 h-3"})})]}),a.jsxs(De,{variant:"secondary",size:"sm",onClick:()=>oe(!0),disabled:!bn||!k("printers:files"),title:k("printers:files")?N("printers.browseFiles"):N("printers.permission.noFiles"),children:[a.jsx(Cg,{className:"w-4 h-4"}),N("printers.files")]}),bn&&Ue?.state!=="RUNNING"&&Ue?.state!=="PAUSE"&&a.jsxs(De,{size:"sm",onClick:()=>Se(!0),disabled:!k("printers:control"),title:k("printers:control")?N("common.print"):N("printers.permission.noControl"),className:"!bg-bambu-green hover:!bg-bambu-green/80 !text-white",children:[a.jsx(Ar,{className:"w-4 h-4"}),N("common.print")]})]})]}),ce&&a.jsx(BMe,{printerId:t.id,printerName:t.name,onClose:()=>oe(!1)}),_e&&a.jsx(Gae,{folderId:null,onClose:()=>Se(!1),onUploadComplete:()=>{},autoUpload:!0,accept:".gcode,.3mf",validateFile:tt=>{const Tt=tt.name.toLowerCase();if(!Tt.endsWith(".gcode")&&!Tt.includes(".gcode."))return N("printers.dropNotPrintable","Only .gcode and .gcode.3mf files can be printed")},onFileUploaded:tt=>{const Tt=tt.metadata?.sliced_for_model,Kt=A0(t.model);if(Tt&&Kt&&Tt.toLowerCase()!==Kt.toLowerCase())return he.deleteLibraryFile(tt.id).catch(()=>{}),N("printers.incompatibleFile","This file was sliced for {{slicedFor}}, but this printer is a {{printerModel}}",{slicedFor:Tt,printerModel:Kt});Le({id:tt.id,filename:tt.filename})}}),Ae&&a.jsx(ec,{mode:"reprint",libraryFileId:Ae.id,archiveName:Ae.filename,initialSelectedPrinterIds:[t.id],onClose:()=>Le(null),onSuccess:()=>Le(null)}),le&&a.jsx(WMe,{printerId:t.id,printerName:t.name,onClose:()=>W(!1)}),ye&&a.jsx(k7e,{printer:t,status:Ue,totalPrintHours:n?.total_print_hours,onClose:xe}),It&&a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onClick:()=>yc(),children:a.jsxs("div",{className:"bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl max-w-lg w-full",onClick:tt=>tt.stopPropagation(),children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[It.needs_calibration?a.jsx(yN,{className:"w-5 h-5 text-blue-500"}):It.is_empty?a.jsx(yr,{className:"w-5 h-5 text-green-500"}):a.jsx(Ta,{className:"w-5 h-5 text-yellow-500"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:"Build Plate Check"}),It.reference_count!==void 0&&It.max_references&&a.jsxs("span",{className:"text-xs text-bambu-gray bg-bambu-dark-tertiary px-2 py-1 rounded",children:[It.reference_count,"/",It.max_references," refs"]})]}),a.jsx("button",{onClick:()=>yc(),className:"p-1 text-bambu-gray hover:text-white rounded transition-colors",children:a.jsx(Ht,{className:"w-5 h-5"})})]}),a.jsxs("div",{className:"p-4 space-y-4",children:[It.needs_calibration?a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"p-3 rounded-lg bg-blue-500/20 border border-blue-500/50",children:[a.jsx("p",{className:"font-medium text-blue-400",children:N("printers.plateDetection.calibrationRequired")}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",dangerouslySetInnerHTML:{__html:N("printers.plateDetection.calibrationInstructions")}})]}),a.jsxs("div",{className:"text-sm text-bambu-gray space-y-2",children:[a.jsx("p",{children:N("printers.plateDetection.calibrationDescription")}),a.jsx("p",{dangerouslySetInnerHTML:{__html:N("printers.plateDetection.calibrationTip")}})]})]}):a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:`p-3 rounded-lg ${It.is_empty?"bg-green-500/20 border border-green-500/50":"bg-yellow-500/20 border border-yellow-500/50"}`,children:[a.jsx("p",{className:`font-medium ${It.is_empty?"text-green-400":"text-yellow-400"}`,children:It.is_empty?N("printers.plateDetection.plateEmpty"):N("printers.plateDetection.objectsDetected")}),a.jsxs("p",{className:"text-sm text-bambu-gray mt-1",children:[N("printers.plateDetection.confidence"),": ",Math.round(It.confidence*100),"% | ",N("printers.plateDetection.difference"),": ",It.difference_percent.toFixed(1),"%"]})]}),It.debug_image_url&&a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-bambu-gray mb-2",children:N("printers.plateDetection.analysisPreview")}),a.jsx("img",{src:It.debug_image_url,alt:N("printers.plateDetection.analysisPreview"),className:"w-full rounded-lg border border-bambu-dark-tertiary"}),a.jsx("p",{className:"text-xs text-bambu-gray mt-2",children:N("printers.plateDetection.analysisLegend")})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:It.message})]}),Xi&&Xi.references.length>0&&a.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[a.jsx("p",{className:"text-sm font-medium text-white mb-2",children:N("printers.plateDetection.savedReferences",{count:Xi.references.length,max:Xi.max_references})}),a.jsx("div",{className:"grid grid-cols-5 gap-2",children:Xi.references.map(tt=>a.jsxs("div",{className:"relative group",children:[a.jsx("img",{src:he.getPlateReferenceThumbnailUrl(t.id,tt.index),alt:tt.label||`Reference ${tt.index+1}`,className:"w-full aspect-video object-cover rounded border border-bambu-dark-tertiary"}),a.jsx("button",{onClick:()=>Ep(tt.index),className:"absolute top-1 right-1 p-0.5 bg-red-500/80 rounded opacity-0 group-hover:opacity-100 transition-opacity",title:N("printers.plateDetection.deleteReference"),children:a.jsx(Ht,{className:"w-3 h-3 text-white"})}),po?.index===tt.index?a.jsx("input",{type:"text",value:po.label,onChange:Tt=>bc({...po,label:Tt.target.value}),onBlur:()=>Rg(tt.index,po.label),onKeyDown:Tt=>{Tt.key==="Enter"&&Rg(tt.index,po.label),Tt.key==="Escape"&&bc(null)},className:"w-full mt-1 px-1 py-0.5 text-xs bg-bambu-dark-tertiary border border-bambu-green rounded text-white",autoFocus:!0,placeholder:N("printers.plateDetection.labelPlaceholder")}):a.jsx("p",{className:"text-xs text-bambu-gray mt-1 truncate cursor-pointer hover:text-white",onClick:()=>bc({index:tt.index,label:tt.label}),title:tt.label?N("printers.plateDetection.clickToEdit",{label:tt.label}):N("printers.plateDetection.clickToAddLabel"),children:tt.label||a.jsx("span",{className:"italic opacity-50",children:N("printers.noLabel")})}),a.jsx("p",{className:"text-[10px] text-bambu-gray/60",children:tt.timestamp?Zn(tt.timestamp)?.toLocaleDateString()??"":""})]},tt.index))})]}),!It.needs_calibration&&a.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsx("p",{className:"text-sm font-medium text-white",children:N("printers.roi.title")}),lt?a.jsxs("div",{className:"flex gap-1",children:[a.jsx(De,{variant:"ghost",size:"sm",onClick:()=>Pe(null),disabled:Ge,children:N("common.cancel")}),a.jsx(De,{size:"sm",onClick:Lg,disabled:Ge,children:Ge?a.jsx(ht,{className:"w-3 h-3 animate-spin"}):N("common.save")})]}):a.jsxs(De,{variant:"ghost",size:"sm",onClick:()=>Pe(It.roi||{x:.15,y:.35,w:.7,h:.55}),children:[a.jsx(ii,{className:"w-3 h-3 mr-1"}),N("common.edit")]})]}),lt?a.jsxs("div",{className:"space-y-3 bg-bambu-dark-tertiary/50 p-3 rounded-lg",children:[a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"text-xs text-bambu-gray",children:N("printers.roi.xStart")}),a.jsx("input",{type:"range",min:"0",max:"0.9",step:"0.01",value:lt.x,onChange:tt=>Pe({...lt,x:parseFloat(tt.target.value)}),className:"w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"}),a.jsxs("span",{className:"text-xs text-bambu-gray",children:[Math.round(lt.x*100),"%"]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"text-xs text-bambu-gray",children:N("printers.roi.yStart")}),a.jsx("input",{type:"range",min:"0",max:"0.9",step:"0.01",value:lt.y,onChange:tt=>Pe({...lt,y:parseFloat(tt.target.value)}),className:"w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"}),a.jsxs("span",{className:"text-xs text-bambu-gray",children:[Math.round(lt.y*100),"%"]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"text-xs text-bambu-gray",children:N("printers.width")}),a.jsx("input",{type:"range",min:"0.1",max:"1",step:"0.01",value:lt.w,onChange:tt=>Pe({...lt,w:parseFloat(tt.target.value)}),className:"w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"}),a.jsxs("span",{className:"text-xs text-bambu-gray",children:[Math.round(lt.w*100),"%"]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"text-xs text-bambu-gray",children:N("printers.height")}),a.jsx("input",{type:"range",min:"0.1",max:"1",step:"0.01",value:lt.h,onChange:tt=>Pe({...lt,h:parseFloat(tt.target.value)}),className:"w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"}),a.jsxs("span",{className:"text-xs text-bambu-gray",children:[Math.round(lt.h*100),"%"]})]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:N("printers.roi.instruction")})]}):a.jsxs("p",{className:"text-xs text-bambu-gray",children:["Current: X=",Math.round((It.roi?.x||.15)*100),"%, Y=",Math.round((It.roi?.y||.35)*100),"%, W=",Math.round((It.roi?.w||.7)*100),"%, H=",Math.round((It.roi?.h||.55)*100),"%"]})]})]}),a.jsx("div",{className:"flex justify-end gap-2 p-4 border-t border-bambu-dark-tertiary",children:It.needs_calibration?a.jsxs(a.Fragment,{children:[a.jsx(De,{variant:"ghost",onClick:()=>yc(),children:N("common.cancel")}),a.jsx(De,{onClick:()=>vn(),disabled:at,children:at?a.jsxs(a.Fragment,{children:[a.jsx(ht,{className:"w-4 h-4 mr-2 animate-spin"}),"Calibrating..."]}):"Calibrate Empty Plate"})]}):a.jsxs(a.Fragment,{children:[a.jsx(De,{variant:"ghost",onClick:()=>vn(),disabled:at,children:at?"Adding...":`Add Reference (${Xi?.references.length||0}/${Xi?.max_references||5})`}),a.jsx(De,{onClick:()=>yc(),children:"Close"})]})})]})}),ne&&Bn&&a.jsx(wn,{title:N("printers.confirm.powerOnTitle"),message:N("printers.confirm.powerOnMessage",{name:t.name}),confirmText:N("printers.confirm.powerOnButton"),variant:"default",onConfirm:()=>{Zc.mutate("on"),pe(!1)},onCancel:()=>pe(!1)}),be&&Bn&&a.jsx(wn,{title:N("printers.confirm.powerOffTitle"),message:Ue?.state==="RUNNING"?N("printers.confirm.powerOffWarning",{name:t.name}):N("printers.confirm.powerOffMessage",{name:t.name}),confirmText:N("printers.confirm.powerOffButton"),variant:"danger",onConfirm:()=>{Zc.mutate("off"),Ce(!1)},onCancel:()=>Ce(!1)}),E&&a.jsx(wn,{title:N("printers.confirm.stopTitle"),message:N("printers.confirm.stopMessage",{name:t.name}),confirmText:N("printers.confirm.stopButton"),variant:"danger",onConfirm:()=>{Bs.mutate(),j(!1)},onCancel:()=>j(!1)}),O&&a.jsx(wn,{title:N("printers.confirm.pauseTitle"),message:N("printers.confirm.pauseMessage",{name:t.name}),confirmText:N("printers.confirm.pauseButton"),variant:"default",onConfirm:()=>{Em.mutate(),K(!1)},onCancel:()=>K(!1)}),de&&a.jsx(wn,{title:N("printers.confirm.resumeTitle"),message:N("printers.confirm.resumeMessage",{name:t.name}),confirmText:N("printers.confirm.resumeButton"),variant:"default",onConfirm:()=>{Hs.mutate(),U(!1)},onCancel:()=>U(!1)}),ge&&a.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/70 p-4",children:a.jsxs("div",{className:"bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl w-full max-w-sm p-5",children:[a.jsxs("div",{className:"flex items-start gap-3 mb-4",children:[a.jsx(Dn,{className:"w-5 h-5 text-yellow-400 flex-shrink-0 mt-0.5"}),a.jsxs("div",{children:[a.jsx("h3",{className:"text-sm font-semibold text-white mb-1",children:N("printers.bedJog.notHomedTitle")}),a.jsx("p",{className:"text-xs text-bambu-gray leading-relaxed",children:N("printers.bedJog.notHomedMessage")})]})]}),a.jsxs("div",{className:"flex flex-col gap-2",children:[a.jsx("button",{onClick:()=>{td.mutate("z"),fe(null)},className:"w-full px-3 py-2 rounded-lg text-xs font-medium bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30 transition-colors",children:N("printers.bedJog.homeZ")}),a.jsx("button",{onClick:()=>{const tt=ge.distance;try{sessionStorage.setItem(`bambuddy.bedJog.warned.${t.id}`,"1")}catch{}mo.mutate({distance:tt,force:!0}),fe(null)},className:"w-full px-3 py-2 rounded-lg text-xs font-medium bg-yellow-500/20 text-yellow-400 hover:bg-yellow-500/30 transition-colors",children:N("printers.bedJog.moveAnyway")}),a.jsx("button",{onClick:()=>fe(null),className:"w-full px-3 py-2 rounded-lg text-xs font-medium bg-bambu-dark text-bambu-gray hover:bg-bambu-dark-tertiary transition-colors",children:N("common.cancel")})]})]})}),a.jsx(mI,{printerId:t.id,isOpen:R,onClose:()=>re(!1)}),$&&a.jsx(qye,{printerName:t.name,errors:Ue?.hms_errors||[],onClose:()=>Y(!1),printerId:t.id,hasPermission:k}),Yt&&a.jsx(r7e,{isOpen:!!Yt,onClose:()=>rn(null),printerId:t.id,printerName:t.name,amsId:Yt.amsId,amsLabel:Yt.amsLabel,initialMode:Yt.mode,thresholds:s}),Vt&&a.jsx(qae,{isOpen:!!Vt,onClose:()=>Jt(null),tagUid:Vt.tagUid,trayUuid:Vt.trayUuid,printerId:Vt.printerId,amsId:Vt.amsId,trayId:Vt.trayId}),We&&a.jsx($ae,{isOpen:!!We,onClose:()=>Ft(null),printerId:We.printerId,amsId:We.amsId,trayId:We.trayId,trayInfo:We.trayInfo}),Qt&&a.jsx(Vae,{isOpen:!!Qt,onClose:()=>Nt(null),printerId:t.id,slotInfo:Qt,printerModel:A0(t.model)||void 0,onSuccess:()=>{A.invalidateQueries({queryKey:["slotPresets",t.id]}),A.invalidateQueries({queryKey:["printerStatus",t.id]})}}),ie&&a.jsx(I7e,{printer:t,onClose:()=>J(!1)}),bt&&Je&&a.jsx(O7e,{printer:t,firmwareInfo:Je,onClose:()=>Wt(!1)}),go&&a.jsx("div",{className:"fixed inset-0 z-40",onClick:()=>tu(null)}),Me!==null&&ve&&(()=>{const tt=Re==="n3s"?85:65,Tt=35,Kt=tt+10;return a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"fixed inset-0 z-[100]",onClick:()=>Fe(null)}),a.jsxs("div",{className:"fixed z-[101] w-[240px] bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl overflow-hidden",style:{top:ve.top,left:ve.left},onClick:it=>it.stopPropagation(),children:[a.jsxs("div",{className:"flex items-center gap-2 px-3 py-2.5 border-b border-bambu-dark-tertiary",children:[a.jsx(Lu,{className:"w-3.5 h-3.5 text-amber-400"}),a.jsx("span",{className:"text-xs text-white font-medium",children:N("printers.drying.start")})]}),a.jsxs("div",{className:"px-3 py-2.5 space-y-2.5",children:[a.jsxs("div",{children:[a.jsx("label",{className:"text-[10px] text-bambu-gray mb-1 block",children:N("printers.filaments")}),a.jsx("select",{value:Ye,onChange:it=>{const nn=it.target.value;nt(nn);const gr=b[nn];gr&&(ze(gr[Re==="n3s"?"n3s":"n3f"]),Ve(Re==="n3s"?gr.n3s_hours:gr.n3f_hours))},className:"w-full px-2 py-1.5 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-xs focus:outline-none focus:border-amber-500/50",children:Object.keys(b).map(it=>a.jsx("option",{value:it,children:it},it))})]}),a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center justify-between mb-1",children:[a.jsx("label",{className:"text-[10px] text-bambu-gray",children:N("printers.drying.temperature")}),a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx("input",{type:"number",min:45,max:tt,value:ae,onChange:it=>ze(Math.min(tt,Math.max(45,Number(it.target.value)||45))),className:"w-12 px-1 py-0.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-[11px] text-center focus:outline-none focus:border-amber-500/50 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"}),a.jsx("span",{className:"text-[10px] text-bambu-gray",children:"°C"})]})]}),a.jsx("input",{type:"range",min:Tt,max:Kt,value:ae,onChange:it=>ze(Math.min(tt,Math.max(45,Number(it.target.value)))),className:"w-full h-1 accent-amber-500 cursor-pointer"}),a.jsxs("div",{className:"flex justify-between text-[9px] text-bambu-gray/50 mt-0.5",children:[a.jsx("span",{children:"45°C"}),a.jsxs("span",{children:[tt,"°C"]})]})]}),a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center justify-between mb-1",children:[a.jsx("label",{className:"text-[10px] text-bambu-gray",children:N("printers.drying.duration")}),a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx("input",{type:"number",min:1,max:24,value:we,onChange:it=>Ve(Math.min(24,Math.max(1,Number(it.target.value)||1))),className:"w-10 px-1 py-0.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-[11px] text-center focus:outline-none focus:border-amber-500/50 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"}),a.jsx("span",{className:"text-[10px] text-bambu-gray",children:N("printers.drying.hours")})]})]}),a.jsx("input",{type:"range",min:1,max:24,value:we,onChange:it=>Ve(Number(it.target.value)),className:"w-full h-1 accent-amber-500 cursor-pointer"}),a.jsxs("div",{className:"flex justify-between text-[9px] text-bambu-gray/50 mt-0.5",children:[a.jsx("span",{children:"1h"}),a.jsx("span",{children:"24h"})]})]}),a.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:je,onChange:it=>ue(it.target.checked),className:"w-3.5 h-3.5 accent-amber-500 rounded cursor-pointer"}),a.jsx("span",{className:"text-[11px] text-bambu-gray",children:N("printers.drying.rotateTray")})]})]}),a.jsx("div",{className:"px-3 pb-3",children:a.jsx("button",{onClick:()=>{Me!==null&&xl.mutate({amsId:Me,temp:ae,duration:we,filament:Ye,rotateTray:je})},disabled:xl.isPending,className:"w-full py-1.5 bg-amber-500 hover:bg-amber-400 text-white text-xs font-medium rounded-lg transition-colors disabled:opacity-50",children:xl.isPending?N("printers.drying.startingDrying"):N("printers.drying.start")})})]})]})})()]})}function L7e({onClose:t,onAdd:e,existingSerials:n}){const{t:r}=Rt(),[i,s]=w.useState({name:"",serial_number:"",ip_address:"",access_code:"",model:"",location:"",auto_archive:!0}),[o,l]=w.useState(!1),[c,d]=w.useState([]),[u,m]=w.useState(""),[p,f]=w.useState(!1),[x,v]=w.useState(!1),[b,g]=w.useState([]),[_,C]=w.useState(""),[P,N]=w.useState({scanned:0,total:0});w.useEffect(()=>{dd.getInfo().then(k=>{v(k.is_docker),k.subnets.length>0&&(g(k.subnets),C(k.subnets[0]))}).catch(()=>{})},[]);const A=c.filter(k=>!n.includes(k.serial)),T=async()=>{m(""),d([]),l(!0),f(!1),N({scanned:0,total:0});try{if(x){await dd.startSubnetScan(_);const k=setInterval(async()=>{try{const D=await dd.getScanStatus();N({scanned:D.scanned,total:D.total});const H=await dd.getDiscoveredPrinters();d(H),D.running||(clearInterval(k),l(!1),f(!0))}catch(D){console.error("Failed to get scan status:",D)}},500)}else{await dd.startDiscovery(10);const k=setInterval(async()=>{try{const D=await dd.getDiscoveredPrinters();d(D)}catch(D){console.error("Failed to get discovered printers:",D)}},1e3);setTimeout(async()=>{clearInterval(k);try{await dd.stopDiscovery()}catch{}l(!1),f(!0);try{const D=await dd.getDiscoveredPrinters();d(D)}catch(D){console.error("Failed to get final discovered printers:",D)}},1e4)}}catch(k){console.error("Failed to start discovery:",k),m(k instanceof Error?k.message:r("printers.discovery.failedToStart")),l(!1),f(!0)}},F=k=>{const D=k.serial.startsWith("unknown-")?"":k.serial;s({...i,name:k.name||"",serial_number:D,ip_address:k.ip_address,model:A0(k.model)}),d([])};return w.useEffect(()=>()=>{dd.stopDiscovery().catch(()=>{}),dd.stopSubnetScan().catch(()=>{})},[]),w.useEffect(()=>{const k=D=>{D.key==="Escape"&&t()};return window.addEventListener("keydown",k),()=>window.removeEventListener("keydown",k)},[t]),a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-start sm:items-center justify-center z-50 p-4 overflow-y-auto",onClick:t,children:a.jsx(At,{className:"w-full max-w-md my-auto max-h-[calc(100vh-2rem)] overflow-y-auto",onClick:k=>k.stopPropagation(),children:a.jsxs(Mt,{children:[a.jsx("h2",{className:"text-xl font-semibold mb-4",children:r("printers.addPrinter")}),a.jsxs("div",{className:"mb-4 pb-4 border-b border-bambu-dark-tertiary",children:[x&&a.jsxs("div",{className:"mb-3",children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.discovery.subnetToScan")}),b.length>0?a.jsx("select",{className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none text-sm",value:_,onChange:k=>C(k.target.value),disabled:o,children:b.map(k=>a.jsx("option",{value:k,children:k},k))}):a.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none text-sm",value:_,onChange:k=>C(k.target.value),placeholder:"192.168.1.0/24",disabled:o}),a.jsx("p",{className:"mt-1 text-xs text-bambu-gray",children:r("printers.discovery.dockerNote")})]}),a.jsx(De,{type:"button",variant:"secondary",onClick:T,disabled:o,className:"w-full",children:o?a.jsxs(a.Fragment,{children:[a.jsx(ht,{className:"w-4 h-4 animate-spin"}),x&&P.total>0?r("printers.discovery.scanProgress",{scanned:P.scanned,total:P.total}):r("printers.discovery.scanning")]}):a.jsxs(a.Fragment,{children:[a.jsx(Nr,{className:"w-4 h-4"}),r(x?"printers.discovery.scanSubnet":"printers.discovery.discoverNetwork")]})}),u&&a.jsx("div",{className:"mt-2 text-sm text-red-400",children:u}),A.length>0&&a.jsx("div",{className:"mt-3 space-y-2 max-h-40 overflow-y-auto",children:A.map(k=>a.jsxs("div",{className:"flex items-center justify-between p-2 bg-bambu-dark rounded-lg hover:bg-bambu-dark-secondary cursor-pointer transition-colors",onClick:()=>F(k),children:[a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:"font-medium text-white text-sm truncate",children:k.name||k.serial}),a.jsxs("p",{className:"text-xs text-bambu-gray truncate",children:[A0(k.model)||r("printers.discovery.unknown")," • ",k.ip_address,k.serial.startsWith("unknown-")&&a.jsxs("span",{className:"text-yellow-500",children:[" • ",r("printers.discovery.serialRequired")]})]})]}),a.jsx(In,{className:"w-4 h-4 text-bambu-gray -rotate-90 flex-shrink-0 ml-2"})]},k.serial))}),o&&a.jsx("p",{className:"mt-2 text-sm text-bambu-gray text-center",children:r(x?"printers.discovery.scanningSubnet":"printers.discovery.scanningNetwork")}),p&&!o&&c.length===0&&a.jsx("p",{className:"mt-2 text-sm text-bambu-gray text-center",children:r(x?"printers.discovery.noPrintersFoundSubnet":"printers.discovery.noPrintersFoundNetwork")}),p&&!o&&c.length>0&&A.length===0&&a.jsx("p",{className:"mt-2 text-sm text-bambu-gray text-center",children:r("printers.discovery.allConfigured")})]}),a.jsxs("form",{onSubmit:k=>{k.preventDefault(),e(i)},className:"space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.name")}),a.jsx("input",{type:"text",required:!0,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:i.name,onChange:k=>s({...i,name:k.target.value}),placeholder:r("printers.modal.myPrinter")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.ipAddress")}),a.jsx("input",{type:"text",required:!0,pattern:"(\\d{1,3}(\\.\\d{1,3}){3}|[a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?(\\.[a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?)*)",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:i.ip_address,onChange:k=>s({...i,ip_address:k.target.value}),placeholder:"192.168.1.100 or printer.local"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.serialNumber")}),a.jsx("input",{type:"text",required:!0,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:i.serial_number,onChange:k=>s({...i,serial_number:k.target.value}),placeholder:"01P00A000000000"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.accessCode")}),a.jsx("input",{type:"password",required:!0,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:i.access_code,onChange:k=>s({...i,access_code:k.target.value}),placeholder:r("printers.modal.fromPrinterSettings")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.modal.modelOptional")}),a.jsxs("select",{className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:i.model||"",onChange:k=>s({...i,model:k.target.value}),children:[a.jsx("option",{value:"",children:r("printers.modal.selectModel")}),a.jsxs("optgroup",{label:"H2 Series",children:[a.jsx("option",{value:"H2C",children:"H2C"}),a.jsx("option",{value:"H2D",children:"H2D"}),a.jsx("option",{value:"H2D Pro",children:"H2D Pro"}),a.jsx("option",{value:"H2S",children:"H2S"})]}),a.jsxs("optgroup",{label:"X1 Series",children:[a.jsx("option",{value:"X1E",children:"X1E"}),a.jsx("option",{value:"X1C",children:"X1 Carbon"}),a.jsx("option",{value:"X1",children:"X1"})]}),a.jsxs("optgroup",{label:"P Series",children:[a.jsx("option",{value:"P2S",children:"P2S"}),a.jsx("option",{value:"P1S",children:"P1S"}),a.jsx("option",{value:"P1P",children:"P1P"})]}),a.jsxs("optgroup",{label:"A1 Series",children:[a.jsx("option",{value:"A1",children:"A1"}),a.jsx("option",{value:"A1 Mini",children:"A1 Mini"})]})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.modal.locationGroup")}),a.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:i.location||"",onChange:k=>s({...i,location:k.target.value}),placeholder:r("printers.modal.locationPlaceholder")}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:r("printers.locationHelp")})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"checkbox",id:"auto_archive",checked:i.auto_archive,onChange:k=>s({...i,auto_archive:k.target.checked}),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),a.jsx("label",{htmlFor:"auto_archive",className:"text-sm text-bambu-gray",children:r("printers.modal.autoArchiveLabel")})]}),a.jsxs("div",{className:"flex gap-3 pt-4",children:[a.jsx(De,{type:"button",variant:"secondary",onClick:t,className:"flex-1",children:r("common.cancel")}),a.jsx(De,{type:"submit",className:"flex-1",children:r("printers.addPrinter")})]})]})]})})})}function O7e({printer:t,firmwareInfo:e,onClose:n}){const{t:r}=Rt(),i=on(),{showToast:s}=fn(),{hasPermission:o}=Sr(),l=o("firmware:update"),[c,d]=w.useState(null),[u,m]=w.useState(!1),[p,f]=w.useState(null),[x,v]=w.useState(e.update_available?e.latest_version:null),{data:b,isLoading:g}=Qe({queryKey:["firmwarePrepare",t.id,x],queryFn:()=>Dk.prepareUpload(t.id,x??void 0),staleTime:3e4,enabled:!!x&&l&&!u}),_=st({mutationFn:()=>Dk.startUpload(t.id,x??void 0),onSuccess:()=>{m(!0);const P=setInterval(async()=>{try{const N=await Dk.getUploadStatus(t.id);d(N),(N.status==="complete"||N.status==="error")&&(clearInterval(P),f(null),m(!1),N.status==="complete"&&(s(r("printers.firmwareModal.uploadedToast"),"success"),i.invalidateQueries({queryKey:["firmwareUpdate",t.id]})))}catch{}},2e3);f(P)},onError:P=>{s(r("printers.firmwareModal.uploadFailed",{error:P.message}),"error"),m(!1)}});w.useEffect(()=>()=>{p&&clearInterval(p)},[p]);const C=()=>{d(null),_.mutate()};return a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",children:a.jsx(At,{className:"w-full max-w-md mx-4",children:a.jsxs(Mt,{children:[a.jsxs("div",{className:"flex items-start gap-3 mb-4",children:[a.jsx("div",{className:`p-2 rounded-full ${e.update_available?"bg-orange-500/20":"bg-status-ok/20"}`,children:e.update_available?a.jsx(ha,{className:"w-5 h-5 text-orange-400"}):a.jsx(yr,{className:"w-5 h-5 text-status-ok"})}),a.jsxs("div",{className:"flex-1",children:[a.jsx("h3",{className:"text-lg font-semibold text-white",children:e.update_available?r("printers.firmwareModal.title"):r("printers.firmwareModal.titleUpToDate")}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:t.name})]})]}),(()=>{const P=x?e.available_versions?.find(F=>F.version===x):null,N=x??e.latest_version,A=P?.release_notes??e.release_notes,T=!!N&&N!==e.current_version;return a.jsxs("div",{className:"bg-bambu-dark rounded-lg p-3 mb-4",children:[a.jsxs("div",{className:"flex justify-between items-center text-sm",children:[a.jsx("span",{className:"text-bambu-gray",children:r("printers.firmwareModal.currentVersion")}),a.jsx("span",{className:`font-mono ${T?"text-white":"text-status-ok"}`,children:e.current_version||r("common.unknown")})]}),T&&a.jsxs("div",{className:"flex justify-between items-center text-sm mt-1",children:[a.jsx("span",{className:"text-bambu-gray",children:r("printers.firmwareModal.latestVersion")}),a.jsx("span",{className:"text-orange-400 font-mono",children:N})]}),A&&a.jsxs("details",{className:"mt-3 text-sm",open:!T,children:[a.jsx("summary",{className:`cursor-pointer hover:underline ${T?"text-orange-400":"text-status-ok"}`,children:r("printers.firmwareModal.releaseNotes")}),a.jsx("div",{className:"mt-2 text-bambu-gray text-xs max-h-40 overflow-y-auto whitespace-pre-wrap",children:A})]},N??"none")]})})(),e.available_versions&&e.available_versions.length>0&&!u&&c?.status!=="complete"&&a.jsxs("div",{className:"mb-4",children:[a.jsx("div",{className:"text-xs text-bambu-gray mb-2",children:r("printers.firmwareModal.availableVersions")}),a.jsx("div",{className:"max-h-56 overflow-y-auto border border-bambu-dark-tertiary rounded-lg divide-y divide-bambu-dark-tertiary",children:e.available_versions.map(P=>{const N=e.current_version===P.version,A=x===P.version,T=e.current_version?Uye(P.version,e.current_version):0,F=N?r("printers.firmwareModal.currentBadge"):T>0?r("printers.firmwareModal.newerBadge"):r("printers.firmwareModal.olderBadge"),k=N?"text-bambu-gray":T>0?"text-orange-400":"text-blue-400";return a.jsxs("button",{type:"button",disabled:!P.file_available||!l||N,onClick:()=>v(P.version),className:`w-full text-left px-3 py-2 text-sm flex items-center justify-between gap-2 transition-colors ${A?"bg-orange-500/10":"hover:bg-bambu-dark"} ${!P.file_available||!l||N?"opacity-60 cursor-not-allowed":"cursor-pointer"}`,children:[a.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[a.jsx("span",{className:"font-mono text-white",children:P.version}),a.jsx("span",{className:`text-xs ${k}`,children:F})]}),a.jsx("span",{className:`text-xs px-2 py-0.5 rounded-full ${N?"bg-blue-500/15 text-blue-400 border border-blue-500/30":P.file_available?"bg-bambu-green/15 text-bambu-green border border-bambu-green/30":"bg-bambu-gray/10 text-bambu-gray border border-bambu-gray/30"}`,children:N?r("printers.firmwareModal.installed"):P.file_available?r("printers.firmwareModal.usable"):r("printers.firmwareModal.unavailable")})]},P.version)})})]}),x?g?a.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray text-sm mb-4",children:[a.jsx(ht,{className:"w-4 h-4 animate-spin"}),r("printers.firmwareModal.checkingPrereqs")]}):b&&!u&&!c?a.jsx("div",{className:"mb-4",children:b.can_proceed?a.jsxs("div",{className:"flex items-center gap-2 text-bambu-green text-sm",children:[a.jsx(hi,{className:"w-4 h-4"}),r("printers.firmwareModal.sdCardReady")]}):a.jsx("div",{className:"space-y-1",children:b.errors.map((P,N)=>a.jsxs("div",{className:"flex items-center gap-2 text-red-400 text-sm",children:[a.jsx(Ka,{className:"w-4 h-4 flex-shrink-0"}),P]},N))})}):null:null,(u||c)&&c&&a.jsxs("div",{className:"mb-4",children:[a.jsxs("div",{className:"flex items-center justify-between text-sm mb-1",children:[a.jsx("span",{className:"text-bambu-gray capitalize",children:c.status}),a.jsxs("span",{className:"text-white",children:[c.progress,"%"]})]}),a.jsx("div",{className:"w-full bg-bambu-dark-tertiary rounded-full h-2",children:a.jsx("div",{className:`h-2 rounded-full transition-all ${c.status==="error"?"bg-status-error":c.status==="complete"?"bg-status-ok":"bg-orange-500"} ${c.status==="uploading"?"animate-pulse":""}`,style:{width:`${c.progress}%`}})}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:c.message}),c.error&&a.jsx("p",{className:"text-xs text-red-400 mt-1",children:c.error})]}),c?.status==="complete"&&a.jsxs("div",{className:"bg-bambu-green/10 border border-bambu-green/30 rounded-lg p-3 mb-4",children:[a.jsx("p",{className:"text-sm text-bambu-green font-medium mb-2",children:r("printers.firmwareModal.uploadedSuccess")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:r("printers.firmwareModal.applyInstructions")}),a.jsxs("ol",{className:"text-xs text-bambu-gray mt-1 list-decimal list-inside space-y-1",children:[a.jsx("li",{dangerouslySetInnerHTML:{__html:r("printers.firmwareModal.step1")}}),a.jsx("li",{dangerouslySetInnerHTML:{__html:r("printers.firmwareModal.step2")}}),a.jsx("li",{dangerouslySetInnerHTML:{__html:r("printers.firmwareModal.step3")}}),a.jsx("li",{children:r("printers.firmwareModal.step4")})]})]}),a.jsxs("div",{className:"flex gap-2 justify-end",children:[a.jsx(De,{variant:"secondary",onClick:n,children:c?.status==="complete"?r("printers.firmwareModal.done"):r("common.cancel")}),b?.can_proceed&&!u&&c?.status!=="complete"&&l&&a.jsx(De,{onClick:C,disabled:_.isPending,children:_.isPending?a.jsxs(a.Fragment,{children:[a.jsx(ht,{className:"w-4 h-4 animate-spin mr-2"}),r("printers.firmwareModal.starting")]}):a.jsxs(a.Fragment,{children:[a.jsx(ha,{className:"w-4 h-4 mr-2"}),r("printers.firmwareModal.uploadFirmware")]})})]})]})})})}function I7e({printer:t,onClose:e}){const{t:n}=Rt(),r=on(),{showToast:i}=fn(),[s,o]=w.useState({name:t.name,ip_address:t.ip_address,access_code:"",model:t.model||"",location:t.location||"",auto_archive:t.auto_archive}),l=st({mutationFn:d=>he.updatePrinter(t.id,d),onSuccess:()=>{r.invalidateQueries({queryKey:["printers"]}),r.invalidateQueries({queryKey:["printerStatus",t.id]}),e()},onError:d=>i(d.message||n("printers.toast.failedToUpdate"),"error")});w.useEffect(()=>{const d=u=>{u.key==="Escape"&&e()};return window.addEventListener("keydown",d),()=>window.removeEventListener("keydown",d)},[e]);const c=d=>{d.preventDefault();const u={name:s.name,ip_address:s.ip_address,model:s.model||void 0,location:s.location||void 0,auto_archive:s.auto_archive};s.access_code&&(u.access_code=s.access_code),l.mutate(u)};return a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-start sm:items-center justify-center z-50 p-4 overflow-y-auto",onClick:e,children:a.jsx(At,{className:"w-full max-w-md my-auto max-h-[calc(100vh-2rem)] overflow-y-auto",onClick:d=>d.stopPropagation(),children:a.jsxs(Mt,{children:[a.jsx("h2",{className:"text-xl font-semibold mb-4",children:n("printers.editPrinter")}),a.jsxs("form",{onSubmit:c,className:"space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.name")}),a.jsx("input",{type:"text",required:!0,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:s.name,onChange:d=>o({...s,name:d.target.value}),placeholder:n("printers.modal.myPrinter")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.ipAddress")}),a.jsx("input",{type:"text",required:!0,pattern:"(\\d{1,3}(\\.\\d{1,3}){3}|[a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?(\\.[a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?)*)",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:s.ip_address,onChange:d=>o({...s,ip_address:d.target.value}),placeholder:"192.168.1.100 or printer.local"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.serialNumber")}),a.jsx("input",{type:"text",disabled:!0,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray cursor-not-allowed",value:t.serial_number}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:n("printers.serialCannotBeChanged")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.accessCode")}),a.jsx("input",{type:"password",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:s.access_code,onChange:d=>o({...s,access_code:d.target.value}),placeholder:n("printers.accessCodePlaceholder")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.model")}),a.jsxs("select",{className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:s.model,onChange:d=>o({...s,model:d.target.value}),children:[a.jsx("option",{value:"",children:n("printers.modal.selectModel")}),a.jsxs("optgroup",{label:"H2 Series",children:[a.jsx("option",{value:"H2C",children:"H2C"}),a.jsx("option",{value:"H2D",children:"H2D"}),a.jsx("option",{value:"H2D Pro",children:"H2D Pro"}),a.jsx("option",{value:"H2S",children:"H2S"})]}),a.jsxs("optgroup",{label:"X1 Series",children:[a.jsx("option",{value:"X1E",children:"X1E"}),a.jsx("option",{value:"X1C",children:"X1 Carbon"}),a.jsx("option",{value:"X1",children:"X1"})]}),a.jsxs("optgroup",{label:"P Series",children:[a.jsx("option",{value:"P2S",children:"P2S"}),a.jsx("option",{value:"P1S",children:"P1S"}),a.jsx("option",{value:"P1P",children:"P1P"})]}),a.jsxs("optgroup",{label:"A1 Series",children:[a.jsx("option",{value:"A1",children:"A1"}),a.jsx("option",{value:"A1 Mini",children:"A1 Mini"})]})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Location / Group"}),a.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:s.location,onChange:d=>o({...s,location:d.target.value}),placeholder:n("printers.modal.locationPlaceholder")}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:n("printers.locationHelp")})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"checkbox",id:"edit_auto_archive",checked:s.auto_archive,onChange:d=>o({...s,auto_archive:d.target.checked}),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),a.jsx("label",{htmlFor:"edit_auto_archive",className:"text-sm text-bambu-gray",children:n("printers.modal.autoArchiveLabel")})]}),a.jsxs("div",{className:"flex gap-3 pt-4",children:[a.jsx(De,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:n("common.cancel")}),a.jsx(De,{type:"submit",className:"flex-1",disabled:l.isPending,children:l.isPending?n("common.saving"):n("printers.modal.saveChanges")})]})]})]})})})}function z7e(t){const{data:e}=Qe({queryKey:["printerStatus",t],queryFn:()=>he.getPrinterStatus(t),refetchInterval:3e4});return!e?.connected}function U7e({printer:t,plug:e,onPowerOn:n,isPowering:r}){const i=z7e(t.id),{data:s}=Qe({queryKey:["smartPlugStatus",e.id],queryFn:()=>he.getSmartPlugStatus(e.id),refetchInterval:1e4});return i?a.jsxs("div",{className:"flex items-center justify-between px-3 py-2 hover:bg-gray-100 dark:hover:bg-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[a.jsx("span",{className:"text-sm text-gray-900 dark:text-white truncate",children:t.name}),s&&a.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded ${s.state==="ON"?"bg-bambu-green/20 text-bambu-green":"bg-red-500/20 text-red-400"}`,children:s.state||"?"})]}),a.jsxs("button",{onClick:()=>n(e.id),disabled:r||s?.state==="ON",className:`px-2 py-1 text-xs rounded transition-colors flex items-center gap-1 ${s?.state==="ON"?"bg-bambu-green/20 text-bambu-green cursor-default":"bg-bambu-green/20 text-bambu-green hover:bg-bambu-green hover:text-white"}`,children:[a.jsx(Wd,{className:"w-3 h-3"}),r?"...":"On"]})]}):null}function B7e(){const{t}=Rt(),[e,n]=w.useState(!1),[r,i]=w.useState(()=>localStorage.getItem("hideDisconnectedPrinters")==="true"),[s,o]=w.useState(!1),[l,c]=w.useState(null),[d,u]=w.useState(()=>localStorage.getItem("printerSortBy")||"name"),[m,p]=w.useState(()=>localStorage.getItem("printerSortAsc")!=="false"),[f,x]=w.useState(()=>{const je=localStorage.getItem("printerCardSize");return je?parseInt(je,10):2}),v=f===1?"compact":"expanded",[b,g]=w.useState(""),[_,C]=w.useState("all"),[P,N]=w.useState("all"),[A,T]=w.useState(0),[F,k]=w.useState(()=>{try{const je=localStorage.getItem("printerCollapsedSections");return je?JSON.parse(je):{}}catch{return{}}}),D=on(),{showToast:H}=fn(),{hasPermission:z}=Sr(),[X,L]=w.useState(()=>{const je=localStorage.getItem("openEmbeddedCameras");if(je)try{const ue=JSON.parse(je);return new Map(ue.map(ve=>[ve.id,ve]))}catch{return new Map}return new Map});w.useEffect(()=>{const je=Array.from(X.values());je.length>0?localStorage.setItem("openEmbeddedCameras",JSON.stringify(je)):localStorage.removeItem("openEmbeddedCameras")},[X]);const{data:te,isLoading:ie}=Qe({queryKey:["printers"],queryFn:he.getPrinters}),{data:J}=Qe({queryKey:["settings"],queryFn:he.getSettings}),ce=w.useMemo(()=>{if(J?.drying_presets)try{const je=JSON.parse(J.drying_presets);if(typeof je=="object"&&je!==null&&Object.keys(je).length>0)return{...pL,...je}}catch{}return pL},[J?.drying_presets]);w.useEffect(()=>{J?.camera_view_mode==="window"&&X.size>0&&L(new Map)},[J?.camera_view_mode,X.size]);const{data:oe}=Qe({queryKey:["smart-plugs"],queryFn:he.getSmartPlugs}),{data:le}=Qe({queryKey:["maintenanceOverview"],queryFn:he.getMaintenanceOverview,staleTime:60*1e3}),{data:W}=Qe({queryKey:["spoolman-status"],queryFn:he.getSpoolmanStatus,staleTime:60*1e3}),ne=W?.enabled&&W?.connected,{data:pe}=Qe({queryKey:["spoolman-settings"],queryFn:he.getSpoolmanSettings,enabled:!!ne,staleTime:60*1e3}),be=pe?.spoolman_sync_mode,{data:Ce}=Qe({queryKey:["unlinked-spools"],queryFn:he.getUnlinkedSpools,enabled:!!ne,staleTime:30*1e3}),$=Ce&&Ce.length>0,{data:Y}=Qe({queryKey:["linked-spools"],queryFn:he.getLinkedSpools,enabled:!!ne,staleTime:30*1e3}),E=Y?.linked,{data:j}=Qe({queryKey:["spool-assignments"],queryFn:()=>he.getAssignments(),enabled:z("inventory:view_assignments"),staleTime:30*1e3}),O=st({mutationFn:({printerId:je,amsId:ue,trayId:ve})=>he.unassignSpool(je,ue,ve),onSuccess:()=>{D.invalidateQueries({queryKey:["spool-assignments"]})}}),K=(je,ue,ve)=>j?.find(Be=>Be.printer_id===je&&Be.ams_id===Number(ue)&&Be.tray_id===Number(ve)),B=le?.reduce((je,ue)=>(je[ue.printer_id]={due_count:ue.due_count,warning_count:ue.warning_count,total_print_hours:ue.total_print_hours},je),{})||{},me=oe?.reduce((je,ue)=>(ue.printer_id&&(je[ue.printer_id]=ue),je),{})||{},I=st({mutationFn:he.createPrinter,onSuccess:()=>{D.invalidateQueries({queryKey:["printers"]}),D.invalidateQueries({queryKey:["maintenanceOverview"]}),n(!1)},onError:je=>H(je.message||t("printers.toast.failedToAdd"),"error")}),V=st({mutationFn:je=>he.controlSmartPlug(je,"on"),onSuccess:()=>{D.invalidateQueries({queryKey:["smart-plugs"]}),c(null)},onError:()=>{c(null)}}),[Q,G]=w.useState(new Set),[ee,se]=w.useState(!1),[ge,fe]=w.useState(null),[de,U]=w.useState(!1),R=ee||Q.size>0,re=w.useCallback(je=>{G(ue=>{const ve=new Set(ue);return ve.has(je)?ve.delete(je):ve.add(je),ve})},[]),_e=w.useCallback(()=>{G(new Set),se(!1)},[]);w.useEffect(()=>{const je=ue=>{ue.key==="Escape"&&R&&_e()};return window.addEventListener("keydown",je),()=>window.removeEventListener("keydown",je)},[R,_e]);const Se=w.useCallback(async je=>{U(!0);const ve=Array.from(Q).filter(xt=>{const Bt=D.getQueryData(["printerStatus",xt]);if(!Bt?.connected)return!1;switch(je){case"stop":return Bt.state==="RUNNING"||Bt.state==="PAUSE";case"pause":return Bt.state==="RUNNING";case"resume":return Bt.state==="PAUSE";case"clearPlate":return!!Bt.awaiting_plate_clear;case"clearHMS":return Bt.hms_errors&&tm(Bt.hms_errors).length>0;default:return!1}});if(ve.length===0){H(t("printers.bulk.noneApplicable"),"error"),U(!1),fe(null);return}const Be={stop:he.stopPrint,pause:he.pausePrint,resume:he.resumePrint,clearPlate:he.clearPlate,clearHMS:he.clearHMSErrors}[je],Ze=await Promise.allSettled(ve.map(xt=>Be(xt))),mt=Ze.filter(xt=>xt.status==="fulfilled").length,gt=Ze.filter(xt=>xt.status==="rejected").length;gt===0?H(t("printers.bulk.success",{action:t(`printers.bulk.actions.${je}`),count:mt})):H(t("printers.bulk.partial",{succeeded:mt,failed:gt}),"error"),ve.forEach(xt=>{D.invalidateQueries({queryKey:["printerStatus",xt]})}),U(!1),fe(null)},[Q,D,H,t]),ye=w.useCallback(je=>{je==="stop"||je==="pause"||je==="clearPlate"?fe(je):Se(je)},[Se]),Te=()=>{const je=!r;i(je),localStorage.setItem("hideDisconnectedPrinters",String(je))},xe=je=>{u(je),localStorage.setItem("printerSortBy",je)},Ae=()=>{const je=!m;p(je),localStorage.setItem("printerSortAsc",String(je))},Le=()=>{switch(f){case 1:return"grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5";case 2:return"grid-cols-1 md:grid-cols-2 xl:grid-cols-3";case 3:return"grid-cols-1 lg:grid-cols-2";case 4:return"grid-cols-1";default:return"grid-cols-1 md:grid-cols-2 xl:grid-cols-3"}},Me=["S","M","L","XL"];w.useEffect(()=>D.getQueryCache().subscribe(ue=>{ue.type==="updated"&&Array.isArray(ue.query.queryKey)&&ue.query.queryKey[0]==="printerStatus"&&T(ve=>ve+1)}),[D]);const Fe=w.useMemo(()=>{if(!te)return[];let je=te;if(b.trim()){const ue=b.trim().toLowerCase();je=je.filter(ve=>ve.name.toLowerCase().includes(ue)||(ve.model||"").toLowerCase().includes(ue)||(ve.location||"").toLowerCase().includes(ue)||(ve.serial_number||"").toLowerCase().includes(ue))}return P!=="all"&&(je=je.filter(ue=>(ue.location||"")===P)),_!=="all"&&(je=je.filter(ue=>{const ve=D.getQueryData(["printerStatus",ue.id]);if(!ve?.connected)return _==="offline";const Be=ve.hms_errors?tm(ve.hms_errors):[];switch(_){case"printing":return ve.state==="RUNNING";case"paused":return ve.state==="PAUSE";case"finished":return ve.state==="FINISH";case"error":return ve.state==="FAILED"||Be.length>0;case"idle":return ve.state!=="RUNNING"&&ve.state!=="PAUSE"&&ve.state!=="FINISH"&&ve.state!=="FAILED"&&Be.length===0;case"offline":return!1;default:return!0}})),je},[te,b,_,P,D,A]),Re=w.useMemo(()=>te?[...new Set(te.map(je=>je.location||"").filter(Boolean))].sort():[],[te]),qe=w.useMemo(()=>{const je=[...Fe];switch(d){case"name":je.sort((ue,ve)=>ue.name.localeCompare(ve.name));break;case"model":je.sort((ue,ve)=>(ue.model||"").localeCompare(ve.model||""));break;case"location":je.sort((ue,ve)=>{const Be=ue.location||"",Ze=ve.location||"";return!Be&&Ze?1:Be&&!Ze?-1:Be.localeCompare(Ze)||ue.name.localeCompare(ve.name)});break;case"status":je.sort((ue,ve)=>{const Be=D.getQueryData(["printerStatus",ue.id]),Ze=D.getQueryData(["printerStatus",ve.id]),mt=gt=>gt?.connected?(gt.hms_errors?tm(gt.hms_errors):[]).length>0?0:gt.state==="RUNNING"?1:2:3;return mt(Be)-mt(Ze)});break}return m||je.reverse(),je},[Fe,d,m,D]),Ye=w.useCallback(()=>{G(new Set(qe.map(je=>je.id))),se(!0)},[qe]),nt=w.useCallback(je=>{G(ue=>{const ve=new Set(ue);return qe.forEach(Be=>{const Ze=D.getQueryData(["printerStatus",Be.id]);oK(Ze)===je&&ve.add(Be.id)}),ve}),se(!0)},[qe,D]),ae=w.useCallback(je=>{G(ue=>{const ve=new Set(ue);return qe.filter(Be=>(Be.location||"")===je).forEach(Be=>ve.add(Be.id)),ve}),se(!0)},[qe]),ze=w.useCallback(je=>{G(ue=>{const ve=new Set(ue);return qe.filter(Be=>(Be.model||"Unknown")===je).forEach(Be=>ve.add(Be.id)),ve}),se(!0)},[qe]),we=w.useCallback(je=>{k(ue=>{const ve={...ue,[je]:!ue[je]};try{localStorage.setItem("printerCollapsedSections",JSON.stringify(ve))}catch{}return ve})},[]),Ve=w.useMemo(()=>{if(d==="name")return null;const je={};return d==="location"?qe.forEach(ue=>{const ve=ue.location||"Ungrouped";je[ve]||(je[ve]=[]),je[ve].push(ue)}):d==="model"?qe.forEach(ue=>{const ve=ue.model||"Unknown";je[ve]||(je[ve]=[]),je[ve].push(ue)}):d==="status"&&qe.forEach(ue=>{const ve=D.getQueryData(["printerStatus",ue.id]),Be=oK(ve);je[Be]||(je[Be]=[]),je[Be].push(ue)}),je},[d,qe,D,A]);return a.jsxs("div",{className:"p-4 md:p-8",children:[a.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-6",children:[a.jsxs("div",{children:[a.jsx("h1",{className:"text-2xl font-bold text-white",children:t("printers.title")}),a.jsx(F7e,{printers:te}),te&&te.length>0&&a.jsxs("div",{className:"relative w-full sm:max-w-sm mt-3",children:[a.jsx(Nr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50"}),a.jsx("input",{type:"text",value:b,onChange:je=>g(je.target.value),placeholder:t("printers.search"),"aria-label":t("printers.search"),className:"w-full pl-10 pr-8 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green"}),b&&a.jsx("button",{type:"button","aria-label":t("common.clear"),onClick:()=>g(""),className:"absolute right-3 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white",children:a.jsx(Ht,{className:"w-4 h-4"})})]})]}),a.jsxs("div",{className:"flex items-center gap-2 sm:gap-3 flex-wrap",children:[a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsxs("select",{value:d,onChange:je=>xe(je.target.value),className:"text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg px-2 py-1.5 text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"name",children:t("printers.sort.name")}),a.jsx("option",{value:"status",children:t("printers.sort.status")}),a.jsx("option",{value:"model",children:t("printers.sort.model")}),a.jsx("option",{value:"location",children:t("printers.sort.location")})]}),a.jsx("button",{onClick:Ae,className:"p-1.5 rounded-lg hover:bg-bambu-dark-tertiary transition-colors",title:t(m?"printers.sort.descending":"printers.sort.ascending"),children:m?a.jsx(lp,{className:"w-4 h-4 text-bambu-gray"}):a.jsx(Zf,{className:"w-4 h-4 text-bambu-gray"})})]}),te&&te.length>0&&a.jsxs("select",{value:_,onChange:je=>C(je.target.value),className:"text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg px-2 py-1.5 text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"all",children:t("printers.filter.allStatuses")}),a.jsx("option",{value:"printing",children:t("printers.status.printing")}),a.jsx("option",{value:"paused",children:t("printers.status.paused")}),a.jsx("option",{value:"idle",children:t("printers.status.idle")}),a.jsx("option",{value:"finished",children:t("printers.status.finished")}),a.jsx("option",{value:"error",children:t("printers.status.error")}),a.jsx("option",{value:"offline",children:t("printers.status.offline")})]}),te&&te.length>0&&Re.length>0&&a.jsxs("select",{value:P,onChange:je=>N(je.target.value),className:"text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg px-2 py-1.5 text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"all",children:t("printers.filter.allLocations")}),Re.map(je=>a.jsx("option",{value:je,children:je},je))]}),a.jsx("div",{className:"flex items-center bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:Me.map((je,ue)=>{const ve=ue+1,Be=f===ve;return a.jsx("button",{onClick:()=>{x(ve),localStorage.setItem("printerCardSize",String(ve))},className:`px-2 py-1.5 text-xs font-medium transition-colors ${ue===0?"rounded-l-lg":""} ${ue===Me.length-1?"rounded-r-lg":""} ${Be?"bg-bambu-green text-white":"text-bambu-gray hover:bg-bambu-dark-tertiary hover:text-white"}`,title:t(je==="S"?"printers.cardSize.small":je==="M"?"printers.cardSize.medium":je==="L"?"printers.cardSize.large":"printers.cardSize.extraLarge"),children:je},je)})}),a.jsx("button",{onClick:()=>{R?_e():se(!0)},className:`p-1.5 rounded-lg transition-colors ${R?"bg-bambu-green text-white":"hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white"}`,title:t("printers.bulk.select"),disabled:!z("printers:control"),children:a.jsx(ys,{className:"w-4 h-4"})}),a.jsx("div",{className:"w-px h-6 bg-bambu-dark-tertiary"}),a.jsxs("label",{className:"flex items-center gap-2 text-sm text-bambu-gray cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:r,onChange:Te,className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),t("printers.hideOffline")]}),r&&Object.keys(me).length>0&&a.jsxs("div",{className:"relative",children:[a.jsxs("button",{onClick:()=>o(!s),className:"flex items-center gap-1.5 px-3 py-1.5 text-sm bg-white dark:bg-bambu-dark-secondary border border-gray-200 dark:border-bambu-dark-tertiary rounded-lg text-gray-600 dark:text-bambu-gray hover:text-gray-900 dark:hover:text-white hover:border-bambu-green transition-colors",children:[a.jsx(Wd,{className:"w-4 h-4"}),t("printers.powerOn"),a.jsx(In,{className:`w-3 h-3 transition-transform ${s?"rotate-180":""}`})]}),s&&a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>o(!1)}),a.jsxs("div",{className:"absolute right-0 mt-2 w-56 bg-white dark:bg-bambu-dark-secondary border border-gray-200 dark:border-bambu-dark-tertiary rounded-lg shadow-lg z-20 py-1",children:[a.jsx("div",{className:"px-3 py-2 text-xs text-gray-500 dark:text-bambu-gray border-b border-gray-200 dark:border-bambu-dark-tertiary",children:t("printers.offlinePrintersWithPlugs")}),te?.filter(je=>me[je.id]).map(je=>a.jsx(U7e,{printer:je,plug:me[je.id],onPowerOn:ue=>{c(ue),V.mutate(ue)},isPowering:l===me[je.id]?.id},je.id)),te?.filter(je=>me[je.id]).length===0&&a.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:"No printers with smart plugs"})]})]})]}),a.jsxs(De,{onClick:()=>n(!0),disabled:!z("printers:create"),title:z("printers:create")?void 0:t("printers.permission.noAdd"),children:[a.jsx(ir,{className:"w-4 h-4"}),t("printers.addPrinter")]})]})]}),ie?a.jsx("div",{className:"text-center py-12 text-bambu-gray",children:t("common.loading")}):te?.length===0?a.jsx(At,{children:a.jsxs(Mt,{className:"text-center py-12",children:[a.jsx("p",{className:"text-bambu-gray mb-4",children:t("printers.noPrintersConfigured")}),a.jsxs(De,{onClick:()=>n(!0),disabled:!z("printers:create"),title:z("printers:create")?void 0:t("printers.permission.noAdd"),children:[a.jsx(ir,{className:"w-4 h-4"}),t("printers.addPrinter")]})]})}):qe.length===0&&(b.trim()||_!=="all"||P!=="all")?a.jsx(At,{children:a.jsx(Mt,{className:"text-center py-12",children:a.jsx("p",{className:"text-bambu-gray",children:t("printers.noSearchResults")})})}):Ve?a.jsx("div",{className:"space-y-6",children:(()=>{const je=d==="status"?R7e.filter(ue=>Ve[ue]?.length>0):Object.keys(Ve);return m?je:[...je].reverse()})().map(je=>{const ue=Ve[je],ve=`${d}:${je}`,Be=!F[ve],Ze=d==="status"&&sK[je]?.dot||"bg-bambu-green",mt=d==="status"?t(sK[je]?.labelKey||je):je;return a.jsx(fz,{open:Be,onToggle:()=>we(ve),summaryClassName:"py-1",summary:a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx("span",{className:`w-2 h-2 rounded-full ${Ze}`}),mt,a.jsxs("span",{className:"text-sm font-normal text-bambu-gray",children:["(",ue.length,")"]}),R&&a.jsx("button",{onClick:gt=>{gt.stopPropagation(),d==="location"?ae(je==="Ungrouped"?"":je):d==="status"?nt(je):d==="model"&&ze(je)},className:"text-xs text-bambu-green hover:text-bambu-green-light transition-colors ml-1",children:t("printers.bulk.selectAll")})]}),children:a.jsx("div",{className:`grid gap-4 ${f>=3?"gap-6":""} ${Le()}`,children:ue.map(gt=>a.jsx(cK,{printer:gt,hideIfDisconnected:r,maintenanceInfo:B[gt.id],viewMode:v,cardSize:f,amsThresholds:J?{humidityGood:Number(J.ams_humidity_good)||40,humidityFair:Number(J.ams_humidity_fair)||60,tempGood:Number(J.ams_temp_good)||28,tempFair:Number(J.ams_temp_fair)||35}:void 0,spoolmanEnabled:ne,hasUnlinkedSpools:$,linkedSpools:E,spoolmanUrl:W?.url,spoolmanSyncMode:be,onGetAssignment:K,onUnassignSpool:(xt,Bt,Yt)=>O.mutate({printerId:xt,amsId:Bt,trayId:Yt}),timeFormat:J?.time_format||"system",cameraViewMode:J?.camera_view_mode||"window",onOpenEmbeddedCamera:(xt,Bt)=>L(Yt=>new Map(Yt).set(xt,{id:xt,name:Bt})),checkPrinterFirmware:J?.check_printer_firmware!==!1,dryingPresets:ce,requirePlateClear:J?.require_plate_clear===!0,selectionMode:R,isSelected:Q.has(gt.id),onToggleSelect:re},gt.id))})},je)})}):a.jsx("div",{className:`grid gap-4 ${f>=3?"gap-6":""} ${Le()}`,children:qe.map(je=>a.jsx(cK,{printer:je,hideIfDisconnected:r,maintenanceInfo:B[je.id],viewMode:v,cardSize:f,spoolmanEnabled:ne,hasUnlinkedSpools:$,linkedSpools:E,spoolmanUrl:W?.url,spoolmanSyncMode:be,onGetAssignment:K,onUnassignSpool:(ue,ve,Be)=>O.mutate({printerId:ue,amsId:ve,trayId:Be}),amsThresholds:J?{humidityGood:Number(J.ams_humidity_good)||40,humidityFair:Number(J.ams_humidity_fair)||60,tempGood:Number(J.ams_temp_good)||28,tempFair:Number(J.ams_temp_fair)||35}:void 0,timeFormat:J?.time_format||"system",cameraViewMode:J?.camera_view_mode||"window",onOpenEmbeddedCamera:(ue,ve)=>L(Be=>new Map(Be).set(ue,{id:ue,name:ve})),checkPrinterFirmware:J?.check_printer_firmware!==!1,dryingPresets:ce,requirePlateClear:J?.require_plate_clear===!0,selectionMode:R,isSelected:Q.has(je.id),onToggleSelect:re},je.id))}),e&&a.jsx(L7e,{onClose:()=>n(!1),onAdd:je=>I.mutate(je),existingSerials:te?.map(je=>je.serial_number)||[]}),R&&te&&a.jsx(Vye,{selectedIds:Q,printers:te,onClose:_e,onSelectAll:Ye,onSelectByLocation:ae,onSelectByState:nt,onAction:ye,actionPending:de}),ge==="stop"&&a.jsx(wn,{title:t("printers.bulk.confirm.stopTitle",{count:Q.size}),message:t("printers.bulk.confirm.stopMessage",{count:Q.size}),confirmText:t("printers.bulk.confirm.stopButton"),variant:"danger",isLoading:de,onConfirm:()=>Se("stop"),onCancel:()=>fe(null)}),ge==="pause"&&a.jsx(wn,{title:t("printers.bulk.confirm.pauseTitle",{count:Q.size}),message:t("printers.bulk.confirm.pauseMessage",{count:Q.size}),confirmText:t("printers.bulk.confirm.pauseButton"),isLoading:de,onConfirm:()=>Se("pause"),onCancel:()=>fe(null)}),ge==="clearPlate"&&a.jsx(wn,{title:t("printers.bulk.confirm.clearPlateTitle",{count:Q.size}),message:t("printers.bulk.confirm.clearPlateMessage",{count:Q.size}),confirmText:t("printers.bulk.confirm.clearPlateButton"),isLoading:de,onConfirm:()=>Se("clearPlate"),onCancel:()=>fe(null)}),Array.from(X.values()).map((je,ue)=>a.jsx(GMe,{printerId:je.id,printerName:je.name,viewerIndex:ue,onClose:()=>L(ve=>{const Be=new Map(ve);return Be.delete(je.id),Be})},je.id))]})}function H7e(){const t=navigator.userAgent.toLowerCase(),e=navigator.platform?.toLowerCase()||"";return t.includes("win")||e.includes("win")?"windows":t.includes("mac")||e.includes("mac")?"macos":t.includes("linux")||e.includes("linux")?"linux":"unknown"}function Ef(t,e="bambu_studio"){let n;e==="orcaslicer"?n=`orcaslicer://open?file=${t}`:H7e()==="macos"?n=`bambustudioopen://${encodeURIComponent(t)}`:n=`bambustudio://open?file=${t}`;const r=document.createElement("a");r.href=n,r.style.display="none",document.body.appendChild(r),r.click(),document.body.removeChild(r)}const dK=768;function eie(){const[t,e]=w.useState(()=>typeof window<"u"?window.innerWidth{const n=window.matchMedia(`(max-width: ${dK-1}px)`),r=i=>{e(i.matches)};return e(n.matches),n.addEventListener("change",r),()=>n.removeEventListener("change",r)},[]),t}function gz({archiveId:t,libraryFileId:e,title:n,fileType:r,onClose:i}){const{t:s}=Rt(),{data:o}=Qe({queryKey:["settings"],queryFn:he.getSettings}),l=o?.preferred_slicer||"bambu_studio",c=e!=null,[d,u]=w.useState(null),[m,p]=w.useState(null),[f,x]=w.useState(!0),[v,b]=w.useState(null),[g,_]=w.useState(!1),[C,P]=w.useState(null),[N,A]=w.useState(0),[T,F]=w.useState(!1),[k,D]=w.useState(null),[H,z]=w.useState(!1),[X,L]=w.useState(!1),te=w.useRef(null),ie=w.useRef(null),J=10,ce=160,oe=240,le=.35;w.useEffect(()=>{const fe=de=>{de.key==="Escape"&&i()};return window.addEventListener("keydown",fe),()=>window.removeEventListener("keydown",fe)},[i]),w.useEffect(()=>{if(x(!0),c){const fe=(r||"").toLowerCase(),de=fe==="3mf"||fe==="stl",U=fe==="gcode"||fe==="3mf";p({has_model:de,has_gcode:U,has_source:!1,build_volume:{x:256,y:256,z:256},filament_colors:[]}),u(de?"3d":U?"gcode":null),x(!1);return}if(!t){p(null),u(null),x(!1);return}he.getArchiveCapabilities(t).then(fe=>{p(fe),fe.has_model?u("3d"):fe.has_gcode&&u("gcode"),x(!1)}).catch(()=>{p({has_model:!0,has_gcode:!1,has_source:!1,build_volume:{x:256,y:256,z:256},filament_colors:[]}),u("3d"),x(!1)})},[t,r,c]),w.useEffect(()=>{if(_(!0),P(null),A(0),c){const fe=(r||"").toLowerCase();if(!e||fe!=="3mf"){b(null),_(!1);return}he.getLibraryFilePlates(e).then(de=>b(de)).catch(()=>b(null)).finally(()=>_(!1));return}if(!t){b(null),_(!1);return}he.getArchivePlates(t).then(fe=>b(fe)).catch(()=>b(null)).finally(()=>_(!1))},[t,r,c,e]);const W=w.useMemo(()=>v?.plates??[],[v]),ne=(v?.is_multi_plate??!1)&&W.length>1,pe=T&&ne,be=C==null?null:W.find(fe=>fe.index===C)??null,Ce=fe=>fe.object_count??fe.objects?.length??0,$=W.reduce((fe,de)=>fe+Ce(de),0),Y=be?Ce(be):$,E=be?s("modelViewer.plateNumber",{number:be.index}):s("modelViewer.allPlates"),j=W.length>0,O=w.useRef(null),K=w.useRef(null),[B,me]=w.useState(10),[I,V]=w.useState(3),Q=W.length>B,G=Math.max(1,Math.ceil(W.length/B)),ee=Q?W.slice(N*B,(N+1)*B):W;w.useEffect(()=>{if(!pe){me(10),V(3);return}const fe=O.current,de=K.current;if(!fe||!de)return;let U=0;const R=()=>{const Se=de.clientWidth,Te=Math.floor(Se/210),xe=Math.max(3,Math.min(5,Te||3));V(ae=>ae===xe?ae:xe);const Ae=window.getComputedStyle(fe),Le=Number.parseFloat(Ae.rowGap||"0"),Fe=fe.querySelector("button")?.getBoundingClientRect().height??44,Re=de.clientHeight,Ye=Math.max(1,Math.floor((Re+Le)/(Fe+Le)))*xe,nt=Math.max(1,Ye-1);me(ae=>ae===nt?ae:nt)},re=()=>{U&&cancelAnimationFrame(U),U=requestAnimationFrame(R)};re();const _e=new ResizeObserver(re);return _e.observe(de),_e.observe(fe),()=>{U&&cancelAnimationFrame(U),_e.disconnect()}},[pe,W.length]),w.useEffect(()=>{if(!Q){A(0);return}A(fe=>Math.min(fe,G-1))},[W.length,Q,G]),w.useEffect(()=>{if(!Q||C==null)return;const fe=W.findIndex(U=>U.index===C);if(fe<0)return;const de=Math.floor(fe/B);A(U=>U===de?U:de)},[W,B,C,Q]),w.useEffect(()=>{if(!pe){D(null),L(!1);return}if(X)return;const fe=te.current,de=ie.current;if(!fe||!de)return;const U=fe.clientHeight;if(!U)return;const R=Math.max(oe,U*le),re=Math.max(ce,U-J-R),_e=Math.min(de.scrollHeight,re);D(Math.max(ce,_e))},[pe,X,W.length,N,J,ce,oe,le]),w.useEffect(()=>{if(!H)return;const fe=U=>{const R=te.current;if(!R)return;const re=R.getBoundingClientRect(),_e=re.height;if(!_e)return;const Se=Math.max(oe,_e*le),ye=Math.max(ce,_e-J-Se),Te=Math.min(ye,Math.max(ce,U.clientY-re.top));D(Te)},de=()=>{z(!1),L(!0)};return document.addEventListener("mousemove",fe),document.addEventListener("mouseup",de),document.body.style.cursor="row-resize",document.body.style.userSelect="none",()=>{document.removeEventListener("mousemove",fe),document.removeEventListener("mouseup",de),document.body.style.cursor="",document.body.style.userSelect=""}},[H,J,ce,oe,le]);const se=c?(r||"").toLowerCase()==="3mf":!0,ge=async()=>{if(!se)return;const fe=n||"model";try{if(c){const{token:de}=await he.createLibrarySlicerToken(e),U=he.getLibrarySlicerDownloadUrl(e,de,fe);Ef(`${window.location.origin}${U}`,l)}else{const{token:de}=await he.createArchiveSlicerToken(t),U=he.getArchiveSlicerDownloadUrl(t,de,fe);Ef(`${window.location.origin}${U}`,l)}}catch{if(c){const de=`${window.location.origin}${he.getLibraryFileDownloadUrl(e)}`;Ef(de,l)}else{const de=`${window.location.origin}${he.getArchiveForSlicer(t,fe)}`;Ef(de,l)}}};return a.jsx("div",{className:`fixed inset-0 bg-black/70 flex items-center justify-center z-50 ${T?"p-0":"p-8"}`,onClick:i,children:a.jsxs("div",{className:`bg-bambu-dark-secondary border border-bambu-dark-tertiary w-full flex flex-col ${T?"h-full max-w-none rounded-none":"h-[80vh] max-w-4xl rounded-xl"}`,onClick:fe=>fe.stopPropagation(),children:[a.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-1 mr-4",children:[a.jsx("h2",{className:"text-lg font-semibold text-white truncate",children:n}),j&&a.jsxs("span",{className:"text-xs text-bambu-gray bg-bambu-dark-tertiary/70 px-2 py-1 rounded whitespace-nowrap",children:[E,": ",s("modelViewer.objectCount",{count:Y})]})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs(De,{variant:"secondary",size:"sm",onClick:ge,disabled:!se,children:[a.jsx(oa,{className:"w-4 h-4"}),s("modelViewer.openInSlicer")]}),a.jsx(De,{variant:"secondary",size:"sm",onClick:()=>F(fe=>!fe),title:T?"Exit fullscreen":"Enter fullscreen",children:T?a.jsx(CO,{className:"w-4 h-4"}):a.jsx(zP,{className:"w-4 h-4"})}),a.jsx(De,{variant:"ghost",size:"sm",onClick:i,children:a.jsx(Ht,{className:"w-5 h-5"})})]})]}),m&&a.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary",children:[a.jsxs("button",{onClick:()=>m.has_model&&u("3d"),disabled:!m.has_model,className:`flex items-center gap-2 px-6 py-3 text-sm font-medium transition-colors ${d==="3d"?"text-bambu-green border-b-2 border-bambu-green":m.has_model?"text-bambu-gray hover:text-white":"text-bambu-gray/30 cursor-not-allowed"}`,children:[a.jsx(hi,{className:"w-4 h-4"}),s("modelViewer.tabs.model"),!m.has_model&&a.jsxs("span",{className:"text-xs",children:["(",s("modelViewer.notAvailable"),")"]})]}),a.jsxs("button",{onClick:()=>m.has_gcode&&u("gcode"),disabled:!m.has_gcode,className:`flex items-center gap-2 px-6 py-3 text-sm font-medium transition-colors ${d==="gcode"?"text-bambu-green border-b-2 border-bambu-green":m.has_gcode?"text-bambu-gray hover:text-white":"text-bambu-gray/30 cursor-not-allowed"}`,children:[a.jsx(yfe,{className:"w-4 h-4"}),s("modelViewer.tabs.gcode"),!m.has_gcode&&a.jsxs("span",{className:"text-xs",children:["(",s("modelViewer.notSliced"),")"]})]})]}),a.jsx("div",{className:"flex-1 overflow-hidden p-4",children:f?a.jsx("div",{className:"w-full h-full flex items-center justify-center",children:a.jsx(ht,{className:"w-8 h-8 animate-spin text-bambu-green"})}):d==="3d"&&m?a.jsxs("div",{ref:te,className:`w-full h-full flex flex-col ${pe?"gap-0 min-h-0":"gap-3"}`,children:[ne&&a.jsxs("div",{ref:ie,style:pe&&k!=null?{height:k}:void 0,className:`rounded-lg border border-bambu-dark-tertiary bg-bambu-dark p-3 ${pe?"flex flex-col shrink-0":""}`,children:[a.jsxs("div",{className:"flex items-center gap-2 text-sm text-bambu-gray mb-2",children:[a.jsx(ca,{className:"w-4 h-4"}),s("modelViewer.plates"),g&&a.jsx(ht,{className:"w-3 h-3 animate-spin"})]}),a.jsxs("div",{className:pe?"flex flex-col min-h-0 flex-1":void 0,children:[a.jsx("div",{ref:K,className:pe?"min-h-0 overflow-hidden pr-1 flex-1":void 0,children:a.jsxs("div",{ref:O,className:pe?"grid gap-2":"grid grid-cols-2 md:grid-cols-3 gap-2",style:pe?{gridTemplateColumns:`repeat(${I}, minmax(0, 1fr))`}:void 0,children:[a.jsxs("button",{type:"button",onClick:()=>P(null),className:`flex items-center rounded-lg border text-left transition-colors ${pe?"gap-1.5 p-1.5 w-full":"gap-2 p-2"} ${C==null?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark-secondary hover:border-bambu-gray"}`,children:[a.jsx("div",{className:`rounded bg-bambu-dark-tertiary flex items-center justify-center ${pe?"w-8 h-8":"w-10 h-10"}`,children:a.jsx(ca,{className:`${pe?"w-4 h-4":"w-5 h-5"} text-bambu-gray`})}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:`${pe?"text-xs":"text-sm"} text-white font-medium truncate`,children:s("modelViewer.allPlates")}),a.jsx("p",{className:`${pe?"text-[10px]":"text-xs"} text-bambu-gray truncate`,children:s("modelViewer.plateCount",{count:W.length})})]}),C==null&&a.jsx(Lr,{className:`${pe?"w-3.5 h-3.5":"w-4 h-4"} text-bambu-green flex-shrink-0`})]}),ee.map(fe=>a.jsxs("button",{type:"button",onClick:()=>P(fe.index),className:`flex items-center rounded-lg border text-left transition-colors ${pe?"gap-1.5 p-1.5 w-full":"gap-2 p-2"} ${C===fe.index?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark-secondary hover:border-bambu-gray"}`,children:[fe.has_thumbnail&&fe.thumbnail_url?a.jsx("img",{src:fe.thumbnail_url,alt:`Plate ${fe.index}`,className:`${pe?"w-8 h-8":"w-10 h-10"} rounded object-cover bg-bambu-dark-tertiary`}):a.jsx("div",{className:`rounded bg-bambu-dark-tertiary flex items-center justify-center ${pe?"w-8 h-8":"w-10 h-10"}`,children:a.jsx(ca,{className:`${pe?"w-4 h-4":"w-5 h-5"} text-bambu-gray`})}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:`${pe?"text-xs":"text-sm"} text-white font-medium truncate`,children:fe.name||s("modelViewer.plateNumber",{number:fe.index})}),a.jsx("p",{className:`${pe?"text-[10px]":"text-xs"} text-bambu-gray truncate`,children:s("modelViewer.objectCount",{count:fe.object_count??fe.objects?.length??0})})]}),C===fe.index&&a.jsx(Lr,{className:`${pe?"w-3.5 h-3.5":"w-4 h-4"} text-bambu-green flex-shrink-0`})]},fe.index))]})}),(be||Q)&&a.jsxs("div",{className:"mt-auto pt-3 flex items-center gap-4 text-xs text-bambu-gray overflow-x-auto",children:[be&&a.jsxs("div",{className:"flex items-center gap-3 whitespace-nowrap",children:[a.jsx("span",{children:s("modelViewer.plateNumber",{number:be.index})}),be.print_time_seconds!=null&&a.jsx("span",{children:s("modelViewer.eta",{minutes:Math.round(be.print_time_seconds/60)})}),be.filament_used_grams!=null&&a.jsxs("span",{children:[be.filament_used_grams.toFixed(1)," g"]}),be.filaments.length>0&&a.jsx("span",{children:s("modelViewer.filamentCount",{count:be.filaments.length})})]}),Q&&a.jsxs("div",{className:`flex items-center gap-2 whitespace-nowrap ${be?"ml-auto":""}`,children:[a.jsx("span",{children:s("modelViewer.pagination.pageOf",{current:N+1,total:G})}),a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx("button",{type:"button",onClick:()=>A(fe=>Math.max(fe-1,0)),disabled:N===0,className:`px-2 py-1 rounded border text-xs ${N===0?"border-bambu-dark-tertiary text-bambu-gray/40 cursor-not-allowed":"border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,children:s("modelViewer.pagination.prev")}),(()=>{let de=Math.max(0,N-Math.floor(2.5));const U=Math.min(G,de+5);U-de<5&&(de=Math.max(0,U-5));const R=Array.from({length:U-de},(re,_e)=>de+_e);return a.jsxs(a.Fragment,{children:[de>0&&a.jsx("button",{type:"button",onClick:()=>A(0),className:`px-2 py-1 rounded border text-xs ${N===0?"border-bambu-green text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,children:"1"}),de>1&&a.jsx("span",{className:"px-1",children:"…"}),R.map(re=>a.jsx("button",{type:"button",onClick:()=>A(re),className:`px-2 py-1 rounded border text-xs ${N===re?"border-bambu-green text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,children:re+1},re)),UA(G-1),className:`px-2 py-1 rounded border text-xs ${N===G-1?"border-bambu-green text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,children:G})]})})(),a.jsx("button",{type:"button",onClick:()=>A(fe=>Math.min(fe+1,G-1)),disabled:N>=G-1,className:`px-2 py-1 rounded border text-xs ${N>=G-1?"border-bambu-dark-tertiary text-bambu-gray/40 cursor-not-allowed":"border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,children:s("modelViewer.pagination.next")})]})]})]})]})]}),pe&&a.jsx("div",{role:"separator","aria-orientation":"horizontal",onMouseDown:fe=>{fe.preventDefault(),z(!0),L(!0)},className:`h-2 cursor-row-resize flex items-center justify-center ${H?"bg-bambu-dark-tertiary":"bg-bambu-dark-secondary/60 hover:bg-bambu-dark-tertiary"}`,children:a.jsx("div",{className:"w-12 h-1 rounded-full bg-bambu-gray/50"})}),a.jsx("div",{className:`flex-1 ${pe?"min-h-0":""}`,children:a.jsx($Z,{url:c?he.getLibraryFileDownloadUrl(e):m.has_source?he.getSource3mfDownloadUrl(t):he.getArchiveDownload(t),fileType:r,buildVolume:m.build_volume,filamentColors:m.filament_colors,selectedPlateId:C,className:"w-full h-full"})})]}):d==="gcode"&&m?a.jsx(CJ,{gcodeUrl:c?he.getLibraryFileGcodeUrl(e):he.getArchiveGcode(t),filamentColors:m.filament_colors,className:"w-full h-full"}):a.jsx("div",{className:"w-full h-full flex items-center justify-center text-bambu-gray",children:s("modelViewer.noPreview")})})]})})}function q7e({onClose:t,initialFiles:e}){const{t:n}=Rt(),r=on(),{showToast:i}=fn(),s=w.useRef(null),[o,l]=w.useState(()=>e?.filter(N=>N.name.endsWith(".3mf")).map(N=>({file:N,status:"pending"}))||[]),[c,d]=w.useState(!1),[u,m]=w.useState(null);w.useEffect(()=>{const N=A=>{A.key==="Escape"&&t()};return window.addEventListener("keydown",N),()=>window.removeEventListener("keydown",N)},[t]);const p=st({mutationFn:N=>he.uploadArchivesBulk(N),onSuccess:N=>{m(N),r.invalidateQueries({queryKey:["archives"]}),r.invalidateQueries({queryKey:["archiveStats"]}),l(A=>A.map(T=>{const F=N.results.find(D=>D.filename===T.file.name),k=N.errors.find(D=>D.filename===T.file.name);return F?{...T,status:"success",archiveId:F.id}:k?{...T,status:"error",error:k.error}:T})),N.failed===0?i(`${N.uploaded} file${N.uploaded!==1?"s":""} uploaded`):N.uploaded===0?i(`Failed to upload ${N.failed} file${N.failed!==1?"s":""}`,"error"):i(`${N.uploaded} uploaded, ${N.failed} failed`,"warning")},onError:()=>{l(N=>N.map(A=>({...A,status:"error",error:"Upload failed"}))),i("Upload failed","error")}}),f=w.useCallback(N=>{N.preventDefault(),d(!0)},[]),x=w.useCallback(N=>{N.preventDefault(),d(!1)},[]),v=w.useCallback(N=>{N.preventDefault(),d(!1);const A=Array.from(N.dataTransfer.files).filter(T=>T.name.endsWith(".3mf"));A.length>0&&l(T=>[...T,...A.map(F=>({file:F,status:"pending"}))])},[]),b=w.useCallback(N=>{const A=Array.from(N.target.files||[]).filter(T=>T.name.endsWith(".3mf"));A.length>0&&l(T=>[...T,...A.map(F=>({file:F,status:"pending"}))]),s.current&&(s.current.value="")},[]),g=w.useCallback(N=>{l(A=>A.filter((T,F)=>F!==N))},[]),_=()=>{if(o.length===0)return;const N=o.filter(A=>A.status==="pending");N.length!==0&&(l(A=>A.map(T=>T.status==="pending"?{...T,status:"uploading"}:T)),p.mutate(N.map(A=>A.file)))},C=o.filter(N=>N.status==="pending").length,P=p.isPending;return a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:a.jsx(At,{className:"w-full max-w-2xl max-h-[90vh] flex flex-col",children:a.jsxs(Mt,{className:"p-0 flex flex-col h-full",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsx("h2",{className:"text-xl font-semibold text-white",children:n("uploadModal.title")}),a.jsx("button",{onClick:t,className:"text-bambu-gray hover:text-white transition-colors",children:a.jsx(Ht,{className:"w-5 h-5"})})]}),a.jsx("div",{className:"p-4",children:a.jsxs("div",{className:`border-2 border-dashed rounded-lg p-8 text-center transition-colors ${c?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary hover:border-bambu-gray"}`,onDragOver:f,onDragLeave:x,onDrop:v,children:[a.jsx(Da,{className:"w-12 h-12 mx-auto mb-4 text-bambu-gray"}),a.jsx("p",{className:"text-white mb-2",children:n("uploadModal.dragDrop")}),a.jsx("p",{className:"text-bambu-gray text-sm mb-4",children:n("uploadModal.or")}),a.jsx(De,{variant:"secondary",onClick:()=>s.current?.click(),disabled:P,children:n("uploadModal.browseFiles")}),a.jsx("input",{ref:s,type:"file",accept:".3mf",multiple:!0,className:"hidden",onChange:b})]})}),a.jsx("div",{className:"px-4 pb-4",children:a.jsx("p",{className:"text-xs text-bambu-gray",children:n("uploadModal.extractionInfo")})}),o.length>0&&a.jsx("div",{className:"px-4 pb-4 max-h-60 overflow-y-auto",children:a.jsx("div",{className:"space-y-2",children:o.map((N,A)=>a.jsxs("div",{className:"flex items-center gap-3 p-3 bg-bambu-dark rounded-lg",children:[a.jsx(OP,{className:"w-5 h-5 text-bambu-gray flex-shrink-0"}),a.jsx("span",{className:"flex-1 text-white text-sm truncate",children:N.file.name}),a.jsxs("span",{className:"text-xs text-bambu-gray",children:[(N.file.size/(1024*1024)).toFixed(1)," MB"]}),N.status==="pending"&&a.jsx("button",{onClick:()=>g(A),className:"text-bambu-gray hover:text-red-400 transition-colors",disabled:P,children:a.jsx(Ht,{className:"w-4 h-4"})}),N.status==="uploading"&&a.jsx(ht,{className:"w-4 h-4 text-bambu-green animate-spin"}),N.status==="success"&&a.jsx(yr,{className:"w-4 h-4 text-bambu-green"}),N.status==="error"&&a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-xs text-red-400",children:N.error}),a.jsx(Ka,{className:"w-4 h-4 text-red-400"})]})]},`${N.file.name}-${A}`))})}),u&&a.jsx("div",{className:"px-4 pb-4",children:a.jsx("div",{className:"p-3 bg-bambu-dark rounded-lg",children:a.jsxs("p",{className:"text-sm text-white",children:[a.jsx("span",{className:"text-bambu-green",children:u.uploaded})," ",n("uploadModal.uploaded"),u.failed>0&&a.jsxs(a.Fragment,{children:[", ",a.jsx("span",{className:"text-red-400",children:u.failed})," ",n("uploadModal.failed")]})]})})}),a.jsxs("div",{className:"flex gap-3 p-4 border-t border-bambu-dark-tertiary",children:[a.jsx(De,{variant:"secondary",onClick:t,className:"flex-1",children:n(u?"common.close":"common.cancel")}),!u&&a.jsx(De,{onClick:_,disabled:C===0||P,className:"flex-1",children:P?a.jsxs(a.Fragment,{children:[a.jsx(ht,{className:"w-4 h-4 animate-spin"}),n("uploadModal.uploading")]}):a.jsxs(a.Fragment,{children:[a.jsx(Da,{className:"w-4 h-4"}),n("uploadModal.upload")," ",C>0&&`(${C})`]})})]})]})})})}const $7e=["adhesionFailure","spaghettiDetached","layerShift","cloggedNozzle","filamentRunout","warping","stringing","underExtrusion","powerFailure","userCancelled","other"],V7e=["completed","failed","aborted","printing"];function tie({archive:t,onClose:e,existingTags:n=[]}){const{t:r}=Rt();w.useEffect(()=>{const j=O=>{O.key==="Escape"&&e()};return window.addEventListener("keydown",j),()=>window.removeEventListener("keydown",j)},[e]);const i=on(),[s,o]=w.useState(t.print_name||""),[l,c]=w.useState(t.printer_id),[d,u]=w.useState(t.project_id??null),[m,p]=w.useState(t.notes||""),[f,x]=w.useState(t.tags||""),[v,b]=w.useState(t.failure_reason||""),[g,_]=w.useState(t.status),[C,P]=w.useState(t.quantity??1),[N,A]=w.useState(t.photos||[]),[T,F]=w.useState(t.external_url||""),[k,D]=w.useState(!1),[H,z]=w.useState(!1),X=w.useRef(null),L=w.useRef(null),te=w.useRef(null),{data:ie}=Qe({queryKey:["printers"],queryFn:he.getPrinters}),{data:J}=Qe({queryKey:["projects"],queryFn:()=>he.getProjects()}),{data:ce}=Qe({queryKey:["tags"],queryFn:he.getTags,enabled:n.length===0}),oe=n.length>0?n:ce?.map(j=>j.name)||[],le=f.split(",").map(j=>j.trim()).filter(Boolean),W=f.includes(",")?f.substring(f.lastIndexOf(",")+1).trim().toLowerCase():f.trim().toLowerCase(),ne=oe.filter(j=>!le.includes(j)&&(W===""||j.toLowerCase().includes(W))),pe=j=>{let O;if(W&&!oe.includes(W)?O=f.includes(",")?f.substring(0,f.lastIndexOf(",")).split(",").map(K=>K.trim()).filter(Boolean):[]:O=le,!O.includes(j)){const K=[...O,j].join(", ");x(K)}te.current!==null&&clearTimeout(te.current),X.current?.focus()},be=j=>{const O=le.filter(K=>K!==j).join(", ");x(O)},Ce=st({mutationFn:j=>he.updateArchive(t.id,j),onSuccess:()=>{i.invalidateQueries({queryKey:["archives"]}),i.invalidateQueries({queryKey:["projects"]}),e()}}),$=async j=>{const O=j.target.files?.[0];if(O){D(!0);try{const K=await he.uploadArchivePhoto(t.id,O);A(K.photos),i.invalidateQueries({queryKey:["archives"]})}catch(K){console.error("Failed to upload photo:",K)}finally{D(!1),L.current&&(L.current.value="")}}},Y=async j=>{try{const O=await he.deleteArchivePhoto(t.id,j);A(O.photos||[]),i.invalidateQueries({queryKey:["archives"]})}catch(O){console.error("Failed to delete photo:",O)}},E=j=>{j.preventDefault();const O={print_name:s||void 0,printer_id:l,project_id:d,notes:m||void 0,tags:f||void 0,quantity:C,external_url:T||null};g!==t.status&&(O.status=g),g==="failed"||g==="aborted"?O.failure_reason=v||void 0:(t.status==="failed"||t.status==="aborted")&&(O.failure_reason=null),Ce.mutate(O)};return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:e,children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary w-full max-w-md max-h-[90vh] flex flex-col",onClick:j=>j.stopPropagation(),children:[a.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[a.jsx("h2",{className:"text-lg font-semibold text-white",children:r("editArchive.title")}),a.jsx("button",{onClick:e,className:"text-bambu-gray hover:text-white transition-colors",children:a.jsx(Ht,{className:"w-5 h-5"})})]}),a.jsxs("form",{onSubmit:E,className:"p-6 space-y-4 overflow-y-auto flex-1",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("editArchive.name")}),a.jsx("input",{type:"text",value:s,onChange:j=>o(j.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",placeholder:r("editArchive.namePlaceholder")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("editArchive.printer")}),a.jsxs("select",{value:l??"",onChange:j=>c(j.target.value?Number(j.target.value):null),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"",children:r("editArchive.noPrinter")}),ie?.map(j=>a.jsx("option",{value:j.id,children:j.name},j.id))]})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[a.jsx(Fs,{className:"w-4 h-4 inline mr-1"}),r("editArchive.project")]}),a.jsxs("select",{value:d??"",onChange:j=>u(j.target.value?Number(j.target.value):null),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"",children:r("editArchive.noProject")}),J?.map(j=>a.jsx("option",{value:j.id,children:j.name},j.id))]})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[a.jsx(Rge,{className:"w-4 h-4 inline mr-1"}),r("editArchive.itemsPrinted")]}),a.jsx("input",{type:"number",min:1,value:C,onChange:j=>P(Math.max(1,parseInt(j.target.value)||1)),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",placeholder:"1"}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:r("editArchive.itemsPrintedHelp")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("editArchive.notes")}),a.jsx("textarea",{value:m,onChange:j=>p(j.target.value),rows:3,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none resize-none",placeholder:r("editArchive.notesPlaceholder")})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[a.jsx(py,{className:"w-4 h-4 inline mr-1"}),r("editArchive.externalLink")]}),a.jsx("input",{type:"url",value:T,onChange:j=>F(j.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",placeholder:"https://printables.com/model/..."}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:r("editArchive.externalLinkHelp")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("editArchive.tags")}),le.length>0&&a.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:le.map(j=>a.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 bg-bambu-dark-tertiary rounded text-sm text-white",children:[a.jsx(mm,{className:"w-3 h-3"}),j,a.jsx("button",{type:"button",onClick:()=>be(j),className:"ml-0.5 text-bambu-gray hover:text-white",children:a.jsx(Ht,{className:"w-3 h-3"})})]},j))}),a.jsxs("div",{className:"relative",children:[a.jsx("input",{ref:X,type:"text",value:f,onChange:j=>x(j.target.value),onFocus:()=>{te.current!==null&&clearTimeout(te.current),z(!0)},onBlur:()=>{te.current=window.setTimeout(()=>z(!1),200)},className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",placeholder:le.length>0?r("editArchive.addMoreTags"):r("editArchive.tagsPlaceholder")}),H&&ne.length>0&&a.jsxs("div",{className:"absolute top-full left-0 right-0 mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg z-10 max-h-40 overflow-y-auto",children:[a.jsxs("div",{className:"p-2 text-xs text-bambu-gray border-b border-bambu-dark-tertiary",children:[W?r("editArchive.matchingTags",{query:W}):r("editArchive.existingTags")," ",r("editArchive.clickToAdd")]}),a.jsx("div",{className:"p-2 flex flex-wrap gap-1.5",children:ne.map(j=>a.jsx("button",{type:"button",onClick:()=>pe(j),className:"px-2 py-0.5 bg-bambu-dark-tertiary hover:bg-bambu-green/20 rounded text-sm text-bambu-gray hover:text-white transition-colors",children:j},j))})]})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("editArchive.status")}),a.jsx("select",{value:g,onChange:j=>{_(j.target.value),j.target.value==="completed"&&b("")},className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:V7e.map(j=>a.jsx("option",{value:j,children:r(`editArchive.statuses.${j}`)},j))})]}),(g==="failed"||g==="aborted")&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("editArchive.failureReason")}),a.jsxs("select",{value:v,onChange:j=>b(j.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"",children:r("editArchive.selectReason")}),$7e.map(j=>a.jsx("option",{value:r(`editArchive.failureReasons.${j}`),children:r(`editArchive.failureReasons.${j}`)},j))]})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[a.jsx(Fx,{className:"w-4 h-4 inline mr-1"}),r("editArchive.photos")]}),a.jsxs("div",{className:"flex flex-wrap gap-2 mb-2",children:[N.map(j=>a.jsxs("div",{className:"relative group",children:[a.jsx("img",{src:he.getArchivePhotoUrl(t.id,j),alt:r("editArchive.printResult"),className:"w-20 h-20 object-cover rounded-lg border border-bambu-dark-tertiary"}),a.jsx("button",{type:"button",onClick:()=>Y(j),className:"absolute -top-1 -right-1 p-1 bg-red-500 rounded-full opacity-0 group-hover:opacity-100 transition-opacity",children:a.jsx(an,{className:"w-3 h-3 text-white"})})]},j)),a.jsxs("label",{className:"w-20 h-20 flex items-center justify-center border-2 border-dashed border-bambu-dark-tertiary rounded-lg cursor-pointer hover:border-bambu-green transition-colors",children:[a.jsx("input",{ref:L,type:"file",accept:"image/jpeg,image/png,image/webp",onChange:$,className:"hidden",disabled:k}),k?a.jsx(ht,{className:"w-6 h-6 text-bambu-gray animate-spin"}):a.jsx(ir,{className:"w-6 h-6 text-bambu-gray"})]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:r("editArchive.photosHelp")})]}),a.jsxs("div",{className:"flex gap-3 pt-2",children:[a.jsx(De,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:r("common.cancel")}),a.jsxs(De,{type:"submit",disabled:Ce.isPending,className:"flex-1",children:[a.jsx(bs,{className:"w-4 h-4"}),Ce.isPending?r("common.saving"):r("common.save")]})]})]})]})})}function nie({x:t,y:e,items:n,onClose:r}){const i=w.useRef(null),[s,o]=w.useState(null),l=w.useRef(null),[c,d]=w.useState({x:t,y:e,visible:!1}),[u,m]=w.useState(!1),[p,f]=w.useState({});w.useEffect(()=>{const b=C=>{i.current&&!i.current.contains(C.target)&&r()},g=C=>{C.key==="Escape"&&r()},_=()=>{r()};return document.addEventListener("mousedown",b),document.addEventListener("keydown",g),document.addEventListener("scroll",_,!0),()=>{document.removeEventListener("mousedown",b),document.removeEventListener("keydown",g),document.removeEventListener("scroll",_,!0),l.current&&clearTimeout(l.current)}},[r]),w.useLayoutEffect(()=>{if(i.current){i.current.style.visibility="hidden",i.current.style.display="block";const b=i.current.getBoundingClientRect(),g=window.innerWidth,_=window.innerHeight,C=8;let P=t,N=e;t+b.width>g-C&&(P=Math.max(C,g-b.width-C)),P_-C&&(N=Math.max(C,_-b.height-C)),NA),d({x:P,y:N,visible:!0})}},[t,e]);const x=(b,g)=>{l.current&&(clearTimeout(l.current),l.current=null);const _=g.getBoundingClientRect(),C=window.innerHeight,P=300,T=C-_.top-8P;f(F=>({...F,[b]:T?"bottom":"top"})),o(b)},v=()=>{l.current=window.setTimeout(()=>{o(null)},150)};return a.jsx("div",{ref:i,className:"fixed z-50 min-w-[180px] max-w-[280px] bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl py-1",style:{left:c.x,top:c.y,visibility:c.visible?"visible":"hidden"},children:n.map((b,g)=>{if(b.divider)return a.jsx("div",{className:"my-1 border-t border-bambu-dark-tertiary"},g);const _=b.submenu&&b.submenu.length>0;return a.jsxs("div",{className:"relative",onMouseEnter:C=>_&&x(g,C.currentTarget),onMouseLeave:()=>_&&v(),children:[a.jsxs("button",{onMouseEnter:C=>_&&x(g,C.currentTarget.parentElement),onClick:()=>{_?o(s===g?null:g):b.disabled||(b.onClick(),r())},disabled:b.disabled,title:b.title,className:`w-full flex items-center gap-2 px-3 py-2 text-sm text-left transition-colors ${b.disabled?"text-bambu-gray cursor-not-allowed":b.danger?"text-red-400 hover:bg-red-400/10":"text-white hover:bg-bambu-dark-tertiary"} ${_&&s===g?"bg-bambu-dark-tertiary":""}`,children:[b.icon&&a.jsx("span",{className:"w-4 h-4 flex-shrink-0 flex items-center justify-center",children:b.icon}),a.jsx("span",{className:"flex-1",children:b.label}),_&&a.jsx(Xa,{className:"w-4 h-4 text-bambu-gray"})]}),_&&s===g&&a.jsx("div",{className:`absolute min-w-[160px] bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl py-1 overflow-hidden max-h-[300px] overflow-y-auto z-[60] ${u?"right-full mr-1":"left-full ml-1"} ${p[g]==="bottom"?"bottom-0":"top-0"}`,onMouseEnter:()=>{l.current&&(clearTimeout(l.current),l.current=null)},onMouseLeave:()=>v(),children:b.submenu.map((C,P)=>a.jsxs("button",{onClick:()=>{C.disabled||(C.onClick(),r())},disabled:C.disabled,className:`w-full flex items-center gap-2 px-3 py-2 text-sm text-left transition-colors ${C.disabled?"text-bambu-gray cursor-not-allowed":C.danger?"text-red-400 hover:bg-red-400/10":"text-white hover:bg-bambu-dark-tertiary"}`,children:[C.icon&&a.jsx("span",{className:"w-4 h-4 flex-shrink-0 flex items-center justify-center",children:C.icon}),C.label]},P))})]},g)})})}function G7e({selectedIds:t,existingTags:e,onClose:n}){const r=on(),{showToast:i}=fn(),[s,o]=w.useState(""),[l,c]=w.useState(new Set),[d,u]=w.useState("add");w.useEffect(()=>{const v=b=>{b.key==="Escape"&&n()};return window.addEventListener("keydown",v),()=>window.removeEventListener("keydown",v)},[n]);const m=st({mutationFn:async()=>{const v=Array.from(l);let b=0;for(const g of t)try{const _=await he.getArchive(g),C=_.tags?_.tags.split(",").map(N=>N.trim()).filter(Boolean):[];let P;d==="add"?P=[...new Set([...C,...v])]:P=C.filter(N=>!l.has(N)),await he.updateArchive(g,{tags:P.join(", ")}),b++}catch(_){throw console.error(`Failed to update archive ${g}:`,_),new Error(`Failed on archive ${g}: ${_ instanceof Error?_.message:"Unknown error"}`)}return{count:b,mode:d,tags:v}},onSuccess:({count:v,mode:b,tags:g})=>{r.invalidateQueries({queryKey:["archives"]}),i(`${b==="add"?"Added":"Removed"} ${g.length} tag${g.length!==1?"s":""} ${b==="add"?"to":"from"} ${v} archive${v!==1?"s":""}`),n()},onError:v=>{i(v.message||"Failed to update tags","error")}}),p=v=>{c(b=>{const g=new Set(b);return g.has(v)?g.delete(v):g.add(v),g})},f=()=>{s.trim()&&!l.has(s.trim())&&(c(v=>new Set([...v,s.trim()])),o(""))},x=v=>{v.key==="Enter"&&(v.preventDefault(),f())};return a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:a.jsx(At,{className:"w-full max-w-md",children:a.jsxs(Mt,{className:"p-0",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(mm,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-xl font-semibold text-white",children:d==="add"?"Add Tags":"Remove Tags"})]}),a.jsx("button",{onClick:n,className:"text-bambu-gray hover:text-white transition-colors",children:a.jsx(Ht,{className:"w-5 h-5"})})]}),a.jsxs("div",{className:"p-4 space-y-4",children:[a.jsxs("p",{className:"text-sm text-bambu-gray",children:[d==="add"?"Add":"Remove"," tags for ",t.length," selected archive",t.length!==1?"s":""]}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx(De,{size:"sm",variant:d==="add"?"primary":"secondary",onClick:()=>u("add"),children:"Add Tags"}),a.jsx(De,{size:"sm",variant:d==="remove"?"primary":"secondary",onClick:()=>u("remove"),children:"Remove Tags"})]}),d==="add"&&a.jsxs("div",{className:"flex gap-2",children:[a.jsx("input",{type:"text",placeholder:"Enter new tag...",className:"flex-1 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",value:s,onChange:v=>o(v.target.value),onKeyDown:x}),a.jsx(De,{size:"sm",variant:"secondary",onClick:f,disabled:!s.trim(),children:a.jsx(ir,{className:"w-4 h-4"})})]}),e.length>0&&a.jsxs("div",{children:[a.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:"Existing tags:"}),a.jsx("div",{className:"flex flex-wrap gap-2",children:e.map(v=>a.jsx("button",{onClick:()=>p(v),className:`px-2 py-1 rounded text-sm transition-colors ${l.has(v)?"bg-bambu-green text-white":"bg-bambu-dark-tertiary text-bambu-gray-light hover:bg-bambu-dark"}`,children:v},v))})]}),l.size>0&&a.jsxs("div",{children:[a.jsxs("p",{className:"text-xs text-bambu-gray mb-2",children:["Tags to ",d==="add"?"add":"remove",":"]}),a.jsx("div",{className:"flex flex-wrap gap-2",children:Array.from(l).map(v=>a.jsxs("span",{className:`px-2 py-1 rounded text-sm flex items-center gap-1 ${d==="add"?"bg-green-500/20 text-green-400":"bg-red-500/20 text-red-400"}`,children:[v,a.jsx("button",{onClick:()=>p(v),className:"hover:opacity-70",children:a.jsx(Ht,{className:"w-3 h-3"})})]},v))})]})]}),a.jsxs("div",{className:"flex gap-3 p-4 border-t border-bambu-dark-tertiary",children:[a.jsx(De,{variant:"secondary",onClick:n,className:"flex-1",children:"Cancel"}),a.jsx(De,{onClick:()=>m.mutate(),disabled:l.size===0||m.isPending,className:"flex-1",children:m.isPending?a.jsxs(a.Fragment,{children:[a.jsx(ht,{className:"w-4 h-4 animate-spin"}),"Processing..."]}):a.jsxs(a.Fragment,{children:[a.jsx(mm,{className:"w-4 h-4"}),d==="add"?"Add Tags":"Remove Tags"]})})]})]})})})}function W7e({selectedIds:t,onClose:e}){const n=on(),{showToast:r}=fn(),{data:i,isLoading:s}=Qe({queryKey:["projects"],queryFn:()=>he.getProjects()});w.useEffect(()=>{const u=m=>{m.key==="Escape"&&e()};return window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)},[e]);const o=()=>{n.invalidateQueries({queryKey:["archives"]}),n.invalidateQueries({queryKey:["projects"]}),n.invalidateQueries({queryKey:["project"]}),n.invalidateQueries({queryKey:["project-archives"]})},l=st({mutationFn:async u=>(await he.addArchivesToProject(u,t),u),onSuccess:u=>{const m=i?.find(p=>p.id===u);o(),r(`Added ${t.length} archive${t.length!==1?"s":""} to "${m?.name}"`),e()},onError:()=>{r("Failed to assign project","error")}}),c=st({mutationFn:async()=>{for(const u of t)await he.updateArchive(u,{project_id:null});return t.length},onSuccess:u=>{o(),r(`Removed ${u} archive${u!==1?"s":""} from project`),e()},onError:()=>{r("Failed to remove from project","error")}}),d=l.isPending||c.isPending;return a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:a.jsx(At,{className:"w-full max-w-md max-h-[80vh] flex flex-col",children:a.jsxs(Mt,{className:"p-0 flex flex-col min-h-0",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary shrink-0",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Fs,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-xl font-semibold text-white",children:"Assign to Project"})]}),a.jsx("button",{onClick:e,className:"text-bambu-gray hover:text-white transition-colors",disabled:d,children:a.jsx(Ht,{className:"w-5 h-5"})})]}),a.jsxs("div",{className:"p-4 space-y-3 overflow-y-auto min-h-0",children:[a.jsxs("p",{className:"text-sm text-bambu-gray",children:["Assign ",t.length," selected archive",t.length!==1?"s":""," to a project"]}),s?a.jsx("div",{className:"flex items-center justify-center py-8",children:a.jsx(ht,{className:"w-6 h-6 animate-spin text-bambu-gray"})}):a.jsxs("div",{className:"space-y-2",children:[a.jsxs("button",{onClick:()=>c.mutate(),disabled:d,className:"w-full flex items-center gap-3 p-3 rounded-lg bg-bambu-dark hover:bg-bambu-dark-tertiary border border-bambu-dark-tertiary transition-colors text-left disabled:opacity-50",children:[a.jsx("div",{className:"w-8 h-8 rounded-full bg-red-500/20 flex items-center justify-center shrink-0",children:a.jsx(Ta,{className:"w-4 h-4 text-red-400"})}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:"text-white font-medium",children:"Remove from project"}),a.jsx("p",{className:"text-sm text-bambu-gray truncate",children:"Clear project assignment"})]}),c.isPending&&a.jsx(ht,{className:"w-4 h-4 animate-spin text-bambu-gray shrink-0"})]}),i&&i.length>0&&a.jsxs("div",{className:"flex items-center gap-2 py-2",children:[a.jsx("div",{className:"flex-1 h-px bg-bambu-dark-tertiary"}),a.jsx("span",{className:"text-xs text-bambu-gray",children:"or assign to"}),a.jsx("div",{className:"flex-1 h-px bg-bambu-dark-tertiary"})]}),i?.map(u=>a.jsxs("button",{onClick:()=>l.mutate(u.id),disabled:d,className:"w-full flex items-center gap-3 p-3 rounded-lg bg-bambu-dark hover:bg-bambu-dark-tertiary border border-bambu-dark-tertiary transition-colors text-left disabled:opacity-50",children:[a.jsx("div",{className:"w-8 h-8 rounded-full flex items-center justify-center shrink-0",style:{backgroundColor:u.color?`${u.color}20`:"rgb(var(--bambu-green) / 0.2)"},children:a.jsx(Fs,{className:"w-4 h-4",style:{color:u.color||"rgb(var(--bambu-green))"}})}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:"text-white font-medium truncate",children:u.name}),a.jsxs("p",{className:"text-sm text-bambu-gray truncate",children:[u.archive_count," archive",u.archive_count!==1?"s":"",u.status&&` • ${u.status}`]})]}),l.isPending&&l.variables===u.id&&a.jsx(ht,{className:"w-4 h-4 animate-spin text-bambu-gray shrink-0"})]},u.id)),(!i||i.length===0)&&a.jsx("p",{className:"text-center text-bambu-gray py-4",children:"No projects yet. Create one from the Projects page."})]})]}),a.jsx("div",{className:"flex gap-3 p-4 border-t border-bambu-dark-tertiary shrink-0",children:a.jsx(De,{variant:"secondary",onClick:e,className:"flex-1",disabled:d,children:"Cancel"})})]})})})}function K7e(t,e){return new Date(t,e+1,0).getDate()}function X7e(t,e){return new Date(t,e,1).getDay()}const Y7e=["January","February","March","April","May","June","July","August","September","October","November","December"],Q7e=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];function Z7e({archives:t,onArchiveClick:e,highlightedArchiveId:n}){const r=new Date,[i,s]=w.useState(r.getMonth()),[o,l]=w.useState(r.getFullYear()),[c,d]=w.useState(null),[u,m]=w.useState(null),p=w.useMemo(()=>{const N=new Map;return t.forEach(A=>{const T=Zn(A.completed_at||A.created_at)||new Date,F=`${T.getFullYear()}-${String(T.getMonth()+1).padStart(2,"0")}-${String(T.getDate()).padStart(2,"0")}`,k=N.get(F)||[];k.push(A),N.set(F,k)}),N},[t]),f=K7e(o,i),x=X7e(o,i),v=()=>{i===0?(s(11),l(o-1)):s(i-1)},b=()=>{i===11?(s(0),l(o+1)):s(i+1)},g=()=>{s(r.getMonth()),l(r.getFullYear())},_=[];for(let N=0;N{N!==c&&m(null),d(N)};return a.jsxs("div",{className:"flex flex-col lg:flex-row gap-6",children:[a.jsxs("div",{className:"flex-1",children:[a.jsxs("div",{className:"flex items-center justify-between mb-4",children:[a.jsx("button",{onClick:v,className:"p-2 hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:a.jsx(ml,{className:"w-5 h-5 text-bambu-gray"})}),a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white",children:[Y7e[i]," ",o]}),a.jsx("button",{onClick:g,className:"px-2 py-1 text-xs bg-bambu-dark-tertiary hover:bg-bambu-green/20 text-bambu-gray hover:text-white rounded transition-colors",children:"Today"})]}),a.jsx("button",{onClick:b,className:"p-2 hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:a.jsx(Xa,{className:"w-5 h-5 text-bambu-gray"})})]}),a.jsx("div",{className:"grid grid-cols-7 gap-1 mb-1",children:Q7e.map(N=>a.jsx("div",{className:"text-center text-xs text-bambu-gray py-2",children:N},N))}),a.jsx("div",{className:"grid grid-cols-7 gap-1",children:_.map((N,A)=>{if(N===null)return a.jsx("div",{className:"aspect-square"},`empty-${A}`);const T=`${o}-${String(i+1).padStart(2,"0")}-${String(N).padStart(2,"0")}`,F=p.get(T)||[],k=F.length>0,D=N===r.getDate()&&i===r.getMonth()&&o===r.getFullYear(),H=T===c,z=F.filter(L=>L.status==="completed").length,X=F.filter(L=>L.status==="failed").length;return a.jsxs("button",{onClick:()=>P(H?null:T),className:`aspect-square rounded-lg p-1 flex flex-col items-center justify-center transition-colors relative ${H?"bg-bambu-green text-white":D?"bg-bambu-green/20 text-white ring-2 ring-bambu-green":k?"bg-bambu-dark-tertiary hover:bg-bambu-dark-tertiary/70 text-white":"hover:bg-bambu-dark-tertiary/50 text-bambu-gray"}`,children:[a.jsx("span",{className:`text-sm font-medium ${D&&!H?"text-bambu-green":""}`,children:N}),k&&a.jsxs("div",{className:"absolute bottom-1 left-1/2 -translate-x-1/2 flex items-center gap-1",children:[a.jsx("div",{className:`w-2 h-2 rounded-full ${X>0&&z===0?"bg-red-400":X>0?"bg-yellow-400":"bg-green-400"}`}),a.jsx("span",{className:"text-xs font-medium",children:F.length})]})]},N)})}),a.jsx("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:a.jsxs("div",{className:"grid grid-cols-3 gap-4 text-center",children:[a.jsxs("div",{children:[a.jsx("div",{className:"text-2xl font-bold text-white",children:t.filter(N=>{const A=Zn(N.completed_at||N.created_at)||new Date;return A.getMonth()===i&&A.getFullYear()===o}).length}),a.jsx("div",{className:"text-xs text-bambu-gray",children:"Prints this month"})]}),a.jsxs("div",{children:[a.jsx("div",{className:"text-2xl font-bold text-green-400",children:t.filter(N=>{const A=Zn(N.completed_at||N.created_at)||new Date;return A.getMonth()===i&&A.getFullYear()===o&&N.status==="completed"}).length}),a.jsx("div",{className:"text-xs text-bambu-gray",children:"Successful"})]}),a.jsxs("div",{children:[a.jsx("div",{className:"text-2xl font-bold text-red-400",children:t.filter(N=>{const A=Zn(N.completed_at||N.created_at)||new Date;return A.getMonth()===i&&A.getFullYear()===o&&N.status==="failed"}).length}),a.jsx("div",{className:"text-xs text-bambu-gray",children:"Failed"})]})]})})]}),a.jsx("div",{className:"lg:w-80 bg-bambu-dark rounded-xl p-4",children:c?a.jsxs(a.Fragment,{children:[a.jsx("h3",{className:"text-sm font-medium text-bambu-gray mb-3",children:new Date(c+"T12:00:00").toLocaleDateString("en-US",{weekday:"long",month:"long",day:"numeric",year:"numeric"})}),C.length>0?a.jsx("div",{className:"calendar-scroll space-y-2 max-h-96 overflow-y-auto",children:C.map(N=>{const A=N.id===u||N.id===n;return a.jsxs("button",{onClick:()=>{m(N.id),e?.(N)},className:`w-full flex items-center gap-3 p-2 rounded-lg transition-colors text-left ${A?"":"hover:bg-bambu-dark-tertiary"}`,style:A?{outline:"4px solid #facc15",outlineOffset:"2px"}:void 0,children:[N.thumbnail_path?a.jsx("img",{src:he.getArchiveThumbnail(N.id),alt:"",className:"w-12 h-12 rounded object-cover"}):a.jsx("div",{className:"w-12 h-12 rounded bg-bambu-dark-tertiary flex items-center justify-center",children:a.jsx("span",{className:"text-xs text-bambu-gray",children:"3MF"})}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("p",{className:"text-sm text-white truncate",children:N.print_name||N.filename}),a.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[a.jsx("span",{className:N.status==="failed"?"text-red-400":"text-green-400",children:N.status==="failed"?"Failed":"Completed"}),N.filament_color&&a.jsx("div",{className:"flex gap-0.5",children:N.filament_color.split(",").map((T,F)=>a.jsx("div",{className:"w-3 h-3 rounded-full border border-black/20",style:{backgroundColor:T}},F))})]})]})]},N.id)})}):a.jsx("p",{className:"text-sm text-bambu-gray",children:"No prints on this day"})]}):a.jsx("div",{className:"text-center py-8",children:a.jsx("p",{className:"text-sm text-bambu-gray",children:"Select a day to see prints"})})})]})}function rie({archiveId:t,archiveName:e,onClose:n}){const r=he.getArchiveQRCodeUrl(t,300);w.useEffect(()=>{const s=o=>{o.key==="Escape"&&n()};return window.addEventListener("keydown",s),()=>window.removeEventListener("keydown",s)},[n]);const i=()=>{const s=document.createElement("a");s.href=r,s.download=`${e}_qrcode.png`,s.click()};return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:n,children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary w-full max-w-sm",onClick:s=>s.stopPropagation(),children:[a.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[a.jsx("h2",{className:"text-lg font-semibold text-white",children:"QR Code"}),a.jsx("button",{onClick:n,className:"text-bambu-gray hover:text-white transition-colors",children:a.jsx(Ht,{className:"w-5 h-5"})})]}),a.jsxs("div",{className:"p-6 flex flex-col items-center",children:[a.jsx("p",{className:"text-sm text-bambu-gray mb-4 text-center truncate max-w-full",children:e}),a.jsx("div",{className:"bg-white p-4 rounded-lg mb-4",children:a.jsx("img",{src:r,alt:"QR Code",className:"w-64 h-64"})}),a.jsx("p",{className:"text-xs text-bambu-gray mb-4 text-center",children:"Scan to open this archive"}),a.jsxs(De,{onClick:i,className:"w-full",children:[a.jsx(ha,{className:"w-4 h-4"}),"Download QR Code"]})]})]})})}function aie({archiveId:t,archiveName:e,photos:n,onClose:r,onDelete:i}){const[s,o]=w.useState(0),[l,c]=w.useState(!1);if(w.useEffect(()=>{const f=x=>{x.key==="Escape"&&r(),x.key==="ArrowLeft"&&o(v=>Math.max(0,v-1)),x.key==="ArrowRight"&&o(v=>Math.min(n.length-1,v+1))};return window.addEventListener("keydown",f),()=>window.removeEventListener("keydown",f)},[r,n.length]),w.useEffect(()=>{s>=n.length&&o(Math.max(0,n.length-1))},[n.length,s]),n.length===0)return r(),null;const d=n[s],u=he.getArchivePhotoUrl(t,d),m=()=>{const f=document.createElement("a");f.href=u,f.download=`${e}_photo_${s+1}.jpg`,f.click()},p=()=>{i&&c(!0)};return a.jsxs("div",{className:"fixed inset-0 bg-black/90 flex items-center justify-center z-50",onClick:r,children:[a.jsxs("div",{className:"relative w-full h-full flex flex-col",onClick:f=>f.stopPropagation(),children:[a.jsxs("div",{className:"flex items-center justify-between px-6 py-4 bg-black/50",children:[a.jsxs("div",{children:[a.jsx("h2",{className:"text-lg font-semibold text-white",children:e}),a.jsxs("p",{className:"text-sm text-bambu-gray",children:["Photo ",s+1," of ",n.length]})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs(De,{variant:"secondary",size:"sm",onClick:m,children:[a.jsx(ha,{className:"w-4 h-4"}),"Download"]}),i&&a.jsx(De,{variant:"secondary",size:"sm",onClick:p,className:"text-red-400 hover:text-red-300",children:a.jsx(an,{className:"w-4 h-4"})}),a.jsx("button",{onClick:r,className:"p-2 text-bambu-gray hover:text-white transition-colors",children:a.jsx(Ht,{className:"w-6 h-6"})})]})]}),a.jsxs("div",{className:"flex-1 min-h-0 flex items-center justify-center p-4 relative overflow-hidden",children:[s>0&&a.jsx("button",{onClick:()=>o(f=>f-1),className:"absolute left-4 z-10 p-3 bg-black/50 hover:bg-black/70 rounded-full transition-colors",children:a.jsx(ml,{className:"w-8 h-8 text-white"})}),a.jsx("img",{src:u,alt:`Photo ${s+1}`,className:"max-w-full max-h-full object-contain rounded-lg",style:{maxHeight:"calc(100vh - 200px)"}}),so(f=>f+1),className:"absolute right-4 z-10 p-3 bg-black/50 hover:bg-black/70 rounded-full transition-colors",children:a.jsx(Xa,{className:"w-8 h-8 text-white"})})]}),n.length>1&&a.jsx("div",{className:"flex justify-center gap-2 p-4 bg-black/50",children:n.map((f,x)=>a.jsx("button",{onClick:()=>o(x),className:`w-16 h-16 rounded-lg overflow-hidden border-2 transition-colors ${x===s?"border-bambu-green":"border-transparent hover:border-bambu-gray"}`,children:a.jsx("img",{src:he.getArchivePhotoUrl(t,f),alt:`Thumbnail ${x+1}`,className:"w-full h-full object-cover"})},f))})]}),l&&a.jsx(wn,{title:"Delete Photo",message:"Delete this photo? This cannot be undone.",confirmText:"Delete",variant:"danger",onConfirm:()=>{i?.(d),c(!1)},onCancel:()=>c(!1)})]})}const{entries:iie,setPrototypeOf:uK,isFrozen:J7e,getPrototypeOf:eGe,getOwnPropertyDescriptor:tGe}=Object;let{freeze:so,seal:uc,create:u0}=Object,{apply:fL,construct:gL}=typeof Reflect<"u"&&Reflect;so||(so=function(e){return e});uc||(uc=function(e){return e});fL||(fL=function(e,n){for(var r=arguments.length,i=new Array(r>2?r-2:0),s=2;s1?n-1:0),i=1;i1?n-1:0),i=1;i2&&arguments[2]!==void 0?arguments[2]:Yk;uK&&uK(t,null);let r=e.length;for(;r--;){let i=e[r];if(typeof i=="string"){const s=n(i);s!==i&&(J7e(e)||(e[r]=s),i=s)}t[i]=!0}return t}function oGe(t){for(let e=0;e/gm),mGe=uc(/\$\{[\w\W]*/gm),hGe=uc(/^data-[\-\w.\u00B7-\uFFFF]+$/),pGe=uc(/^aria-[\-\w]+$/),sie=uc(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),fGe=uc(/^(?:\w+script|data):/i),gGe=uc(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),oie=uc(/^html$/i),bGe=uc(/^[a-z][.\w]*(-[.\w]+)+$/i);var bK=Object.freeze({__proto__:null,ARIA_ATTR:pGe,ATTR_WHITESPACE:gGe,CUSTOM_ELEMENT:bGe,DATA_ATTR:hGe,DOCTYPE_NAME:oie,ERB_EXPR:uGe,IS_ALLOWED_URI:sie,IS_SCRIPT_OR_DATA:fGe,MUSTACHE_EXPR:dGe,TMPLIT_EXPR:mGe});const Qv={element:1,text:3,progressingInstruction:7,comment:8,document:9},xGe=function(){return typeof window>"u"?null:window},yGe=function(e,n){if(typeof e!="object"||typeof e.createPolicy!="function")return null;let r=null;const i="data-tt-policy-suffix";n&&n.hasAttribute(i)&&(r=n.getAttribute(i));const s="dompurify"+(r?"#"+r:"");try{return e.createPolicy(s,{createHTML(o){return o},createScriptURL(o){return o}})}catch{return console.warn("TrustedTypes policy "+s+" could not be created."),null}},xK=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function lie(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:xGe();const e=at=>lie(at);if(e.version="3.4.0",e.removed=[],!t||!t.document||t.document.nodeType!==Qv.document||!t.Element)return e.isSupported=!1,e;let{document:n}=t;const r=n,i=r.currentScript,{DocumentFragment:s,HTMLTemplateElement:o,Node:l,Element:c,NodeFilter:d,NamedNodeMap:u=t.NamedNodeMap||t.MozNamedAttrMap,HTMLFormElement:m,DOMParser:p,trustedTypes:f}=t,x=c.prototype,v=Yv(x,"cloneNode"),b=Yv(x,"remove"),g=Yv(x,"nextSibling"),_=Yv(x,"childNodes"),C=Yv(x,"parentNode");if(typeof o=="function"){const at=n.createElement("template");at.content&&at.content.ownerDocument&&(n=at.content.ownerDocument)}let P,N="";const{implementation:A,createNodeIterator:T,createDocumentFragment:F,getElementsByTagName:k}=n,{importNode:D}=r;let H=xK();e.isSupported=typeof iie=="function"&&typeof C=="function"&&A&&A.createHTMLDocument!==void 0;const{MUSTACHE_EXPR:z,ERB_EXPR:X,TMPLIT_EXPR:L,DATA_ATTR:te,ARIA_ATTR:ie,IS_SCRIPT_OR_DATA:J,ATTR_WHITESPACE:ce,CUSTOM_ELEMENT:oe}=bK;let{IS_ALLOWED_URI:le}=bK,W=null;const ne=lr({},[...hK,...RD,...LD,...OD,...pK]);let pe=null;const be=lr({},[...fK,...ID,...gK,...dk]);let Ce=Object.seal(u0(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),$=null,Y=null;const E=Object.seal(u0(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let j=!0,O=!0,K=!1,B=!0,me=!1,I=!0,V=!1,Q=!1,G=!1,ee=!1,se=!1,ge=!1,fe=!0,de=!1;const U="user-content-";let R=!0,re=!1,_e={},Se=null;const ye=lr({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]);let Te=null;const xe=lr({},["audio","video","img","source","image","track"]);let Ae=null;const Le=lr({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),Me="http://www.w3.org/1998/Math/MathML",Fe="http://www.w3.org/2000/svg",Re="http://www.w3.org/1999/xhtml";let qe=Re,Ye=!1,nt=null;const ae=lr({},[Me,Fe,Re],DD);let ze=lr({},["mi","mo","mn","ms","mtext"]),we=lr({},["annotation-xml"]);const Ve=lr({},["title","style","font","a","script"]);let je=null;const ue=["application/xhtml+xml","text/html"],ve="text/html";let Be=null,Ze=null;const mt=n.createElement("form"),gt=function(Oe){return Oe instanceof RegExp||Oe instanceof Function},xt=function(){let Oe=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(Ze&&Ze===Oe)){if((!Oe||typeof Oe!="object")&&(Oe={}),Oe=bd(Oe),je=ue.indexOf(Oe.PARSER_MEDIA_TYPE)===-1?ve:Oe.PARSER_MEDIA_TYPE,Be=je==="application/xhtml+xml"?DD:Yk,W=Ec(Oe,"ALLOWED_TAGS")?lr({},Oe.ALLOWED_TAGS,Be):ne,pe=Ec(Oe,"ALLOWED_ATTR")?lr({},Oe.ALLOWED_ATTR,Be):be,nt=Ec(Oe,"ALLOWED_NAMESPACES")?lr({},Oe.ALLOWED_NAMESPACES,DD):ae,Ae=Ec(Oe,"ADD_URI_SAFE_ATTR")?lr(bd(Le),Oe.ADD_URI_SAFE_ATTR,Be):Le,Te=Ec(Oe,"ADD_DATA_URI_TAGS")?lr(bd(xe),Oe.ADD_DATA_URI_TAGS,Be):xe,Se=Ec(Oe,"FORBID_CONTENTS")?lr({},Oe.FORBID_CONTENTS,Be):ye,$=Ec(Oe,"FORBID_TAGS")?lr({},Oe.FORBID_TAGS,Be):bd({}),Y=Ec(Oe,"FORBID_ATTR")?lr({},Oe.FORBID_ATTR,Be):bd({}),_e=Ec(Oe,"USE_PROFILES")?Oe.USE_PROFILES:!1,j=Oe.ALLOW_ARIA_ATTR!==!1,O=Oe.ALLOW_DATA_ATTR!==!1,K=Oe.ALLOW_UNKNOWN_PROTOCOLS||!1,B=Oe.ALLOW_SELF_CLOSE_IN_ATTR!==!1,me=Oe.SAFE_FOR_TEMPLATES||!1,I=Oe.SAFE_FOR_XML!==!1,V=Oe.WHOLE_DOCUMENT||!1,ee=Oe.RETURN_DOM||!1,se=Oe.RETURN_DOM_FRAGMENT||!1,ge=Oe.RETURN_TRUSTED_TYPE||!1,G=Oe.FORCE_BODY||!1,fe=Oe.SANITIZE_DOM!==!1,de=Oe.SANITIZE_NAMED_PROPS||!1,R=Oe.KEEP_CONTENT!==!1,re=Oe.IN_PLACE||!1,le=Oe.ALLOWED_URI_REGEXP||sie,qe=Oe.NAMESPACE||Re,ze=Oe.MATHML_TEXT_INTEGRATION_POINTS||ze,we=Oe.HTML_INTEGRATION_POINTS||we,Ce=Oe.CUSTOM_ELEMENT_HANDLING||u0(null),Oe.CUSTOM_ELEMENT_HANDLING&>(Oe.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(Ce.tagNameCheck=Oe.CUSTOM_ELEMENT_HANDLING.tagNameCheck),Oe.CUSTOM_ELEMENT_HANDLING&>(Oe.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(Ce.attributeNameCheck=Oe.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),Oe.CUSTOM_ELEMENT_HANDLING&&typeof Oe.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&(Ce.allowCustomizedBuiltInElements=Oe.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),me&&(O=!1),se&&(ee=!0),_e&&(W=lr({},pK),pe=u0(null),_e.html===!0&&(lr(W,hK),lr(pe,fK)),_e.svg===!0&&(lr(W,RD),lr(pe,ID),lr(pe,dk)),_e.svgFilters===!0&&(lr(W,LD),lr(pe,ID),lr(pe,dk)),_e.mathMl===!0&&(lr(W,OD),lr(pe,gK),lr(pe,dk))),E.tagCheck=null,E.attributeCheck=null,Oe.ADD_TAGS&&(typeof Oe.ADD_TAGS=="function"?E.tagCheck=Oe.ADD_TAGS:(W===ne&&(W=bd(W)),lr(W,Oe.ADD_TAGS,Be))),Oe.ADD_ATTR&&(typeof Oe.ADD_ATTR=="function"?E.attributeCheck=Oe.ADD_ATTR:(pe===be&&(pe=bd(pe)),lr(pe,Oe.ADD_ATTR,Be))),Oe.ADD_URI_SAFE_ATTR&&lr(Ae,Oe.ADD_URI_SAFE_ATTR,Be),Oe.FORBID_CONTENTS&&(Se===ye&&(Se=bd(Se)),lr(Se,Oe.FORBID_CONTENTS,Be)),Oe.ADD_FORBID_CONTENTS&&(Se===ye&&(Se=bd(Se)),lr(Se,Oe.ADD_FORBID_CONTENTS,Be)),R&&(W["#text"]=!0),V&&lr(W,["html","head","body"]),W.table&&(lr(W,["tbody"]),delete $.tbody),Oe.TRUSTED_TYPES_POLICY){if(typeof Oe.TRUSTED_TYPES_POLICY.createHTML!="function")throw Xv('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof Oe.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw Xv('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');P=Oe.TRUSTED_TYPES_POLICY,N=P.createHTML("")}else P===void 0&&(P=yGe(f,i)),P!==null&&typeof N=="string"&&(N=P.createHTML(""));so&&so(Oe),Ze=Oe}},Bt=lr({},[...RD,...LD,...lGe]),Yt=lr({},[...OD,...cGe]),rn=function(Oe){let lt=C(Oe);(!lt||!lt.tagName)&&(lt={namespaceURI:qe,tagName:"template"});const Pe=Yk(Oe.tagName),Ge=Yk(lt.tagName);return nt[Oe.namespaceURI]?Oe.namespaceURI===Fe?lt.namespaceURI===Re?Pe==="svg":lt.namespaceURI===Me?Pe==="svg"&&(Ge==="annotation-xml"||ze[Ge]):!!Bt[Pe]:Oe.namespaceURI===Me?lt.namespaceURI===Re?Pe==="math":lt.namespaceURI===Fe?Pe==="math"&&we[Ge]:!!Yt[Pe]:Oe.namespaceURI===Re?lt.namespaceURI===Fe&&!we[Ge]||lt.namespaceURI===Me&&!ze[Ge]?!1:!Yt[Pe]&&(Ve[Pe]||!Bt[Pe]):!!(je==="application/xhtml+xml"&&nt[Oe.namespaceURI]):!1},Vt=function(Oe){Kv(e.removed,{element:Oe});try{C(Oe).removeChild(Oe)}catch{b(Oe)}},Jt=function(Oe,lt){try{Kv(e.removed,{attribute:lt.getAttributeNode(Oe),from:lt})}catch{Kv(e.removed,{attribute:null,from:lt})}if(lt.removeAttribute(Oe),Oe==="is")if(ee||se)try{Vt(lt)}catch{}else try{lt.setAttribute(Oe,"")}catch{}},We=function(Oe){let lt=null,Pe=null;if(G)Oe=""+Oe;else{const Ke=FD(Oe,/^[\r\n\t ]+/);Pe=Ke&&Ke[0]}je==="application/xhtml+xml"&&qe===Re&&(Oe=''+Oe+"");const Ge=P?P.createHTML(Oe):Oe;if(qe===Re)try{lt=new p().parseFromString(Ge,je)}catch{}if(!lt||!lt.documentElement){lt=A.createDocument(qe,"template",null);try{lt.documentElement.innerHTML=Ye?N:Ge}catch{}}const et=lt.body||lt.documentElement;return Oe&&Pe&&et.insertBefore(n.createTextNode(Pe),et.childNodes[0]||null),qe===Re?k.call(lt,V?"html":"body")[0]:V?lt.documentElement:et},Ft=function(Oe){return T.call(Oe.ownerDocument||Oe,Oe,d.SHOW_ELEMENT|d.SHOW_COMMENT|d.SHOW_TEXT|d.SHOW_PROCESSING_INSTRUCTION|d.SHOW_CDATA_SECTION,null)},Qt=function(Oe){return Oe instanceof m&&(typeof Oe.nodeName!="string"||typeof Oe.textContent!="string"||typeof Oe.removeChild!="function"||!(Oe.attributes instanceof u)||typeof Oe.removeAttribute!="function"||typeof Oe.setAttribute!="function"||typeof Oe.namespaceURI!="string"||typeof Oe.insertBefore!="function"||typeof Oe.hasChildNodes!="function")},Nt=function(Oe){return typeof l=="function"&&Oe instanceof l};function bt(at,Oe,lt){Wv(at,Pe=>{Pe.call(e,Oe,lt,Ze)})}const Wt=function(Oe){let lt=null;if(bt(H.beforeSanitizeElements,Oe,null),Qt(Oe))return Vt(Oe),!0;const Pe=Be(Oe.nodeName);if(bt(H.uponSanitizeElement,Oe,{tagName:Pe,allowedTags:W}),I&&Oe.hasChildNodes()&&!Nt(Oe.firstElementChild)&&Gs(/<[/\w!]/g,Oe.innerHTML)&&Gs(/<[/\w!]/g,Oe.textContent)||I&&Oe.namespaceURI===Re&&Pe==="style"&&Nt(Oe.firstElementChild)||Oe.nodeType===Qv.progressingInstruction||I&&Oe.nodeType===Qv.comment&&Gs(/<[/\w]/g,Oe.data))return Vt(Oe),!0;if($[Pe]||!(E.tagCheck instanceof Function&&E.tagCheck(Pe))&&!W[Pe]){if(!$[Pe]&&Ie(Pe)&&(Ce.tagNameCheck instanceof RegExp&&Gs(Ce.tagNameCheck,Pe)||Ce.tagNameCheck instanceof Function&&Ce.tagNameCheck(Pe)))return!1;if(R&&!Se[Pe]){const Ge=C(Oe)||Oe.parentNode,et=_(Oe)||Oe.childNodes;if(et&&Ge){const Ke=et.length;for(let Xe=Ke-1;Xe>=0;--Xe){const Ue=v(et[Xe],!0);Ue.__removalCount=(Oe.__removalCount||0)+1,Ge.insertBefore(Ue,g(Oe))}}}return Vt(Oe),!0}return Oe instanceof c&&!rn(Oe)||(Pe==="noscript"||Pe==="noembed"||Pe==="noframes")&&Gs(/<\/no(script|embed|frames)/i,Oe.innerHTML)?(Vt(Oe),!0):(me&&Oe.nodeType===Qv.text&&(lt=Oe.textContent,Wv([z,X,L],Ge=>{lt=Qb(lt,Ge," ")}),Oe.textContent!==lt&&(Kv(e.removed,{element:Oe.cloneNode()}),Oe.textContent=lt)),bt(H.afterSanitizeElements,Oe,null),!1)},It=function(Oe,lt,Pe){if(Y[lt]||fe&&(lt==="id"||lt==="name")&&(Pe in n||Pe in mt))return!1;if(!(O&&!Y[lt]&&Gs(te,lt))){if(!(j&&Gs(ie,lt))){if(!(E.attributeCheck instanceof Function&&E.attributeCheck(lt,Oe))){if(!pe[lt]||Y[lt]){if(!(Ie(Oe)&&(Ce.tagNameCheck instanceof RegExp&&Gs(Ce.tagNameCheck,Oe)||Ce.tagNameCheck instanceof Function&&Ce.tagNameCheck(Oe))&&(Ce.attributeNameCheck instanceof RegExp&&Gs(Ce.attributeNameCheck,lt)||Ce.attributeNameCheck instanceof Function&&Ce.attributeNameCheck(lt,Oe))||lt==="is"&&Ce.allowCustomizedBuiltInElements&&(Ce.tagNameCheck instanceof RegExp&&Gs(Ce.tagNameCheck,Pe)||Ce.tagNameCheck instanceof Function&&Ce.tagNameCheck(Pe))))return!1}else if(!Ae[lt]){if(!Gs(le,Qb(Pe,ce,""))){if(!((lt==="src"||lt==="xlink:href"||lt==="href")&&Oe!=="script"&&aGe(Pe,"data:")===0&&Te[Oe])){if(!(K&&!Gs(J,Qb(Pe,ce,"")))){if(Pe)return!1}}}}}}}return!0},Ie=function(Oe){return Oe!=="annotation-xml"&&FD(Oe,oe)},ct=function(Oe){bt(H.beforeSanitizeAttributes,Oe,null);const{attributes:lt}=Oe;if(!lt||Qt(Oe))return;const Pe={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:pe,forceKeepAttr:void 0};let Ge=lt.length;for(;Ge--;){const et=lt[Ge],{name:Ke,namespaceURI:Xe,value:Ue}=et,Je=Be(Ke),jt=Ue;let yt=Ke==="value"?jt:iGe(jt);if(Pe.attrName=Je,Pe.attrValue=yt,Pe.keepAttr=!0,Pe.forceKeepAttr=void 0,bt(H.uponSanitizeAttribute,Oe,Pe),yt=Pe.attrValue,de&&(Je==="id"||Je==="name")&&(Jt(Ke,Oe),yt=U+yt),I&&Gs(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,yt)){Jt(Ke,Oe);continue}if(Je==="attributename"&&FD(yt,"href")){Jt(Ke,Oe);continue}if(Pe.forceKeepAttr)continue;if(!Pe.keepAttr){Jt(Ke,Oe);continue}if(!B&&Gs(/\/>/i,yt)){Jt(Ke,Oe);continue}me&&Wv([z,X,L],vt=>{yt=Qb(yt,vt," ")});const $e=Be(Oe.nodeName);if(!It($e,Je,yt)){Jt(Ke,Oe);continue}if(P&&typeof f=="object"&&typeof f.getAttributeType=="function"&&!Xe)switch(f.getAttributeType($e,Je)){case"TrustedHTML":{yt=P.createHTML(yt);break}case"TrustedScriptURL":{yt=P.createScriptURL(yt);break}}if(yt!==jt)try{Xe?Oe.setAttributeNS(Xe,Ke,yt):Oe.setAttribute(Ke,yt),Qt(Oe)?Vt(Oe):mK(e.removed)}catch{Jt(Ke,Oe)}}bt(H.afterSanitizeAttributes,Oe,null)},pt=function(Oe){let lt=null;const Pe=Ft(Oe);for(bt(H.beforeSanitizeShadowDOM,Oe,null);lt=Pe.nextNode();)bt(H.uponSanitizeShadowNode,lt,null),Wt(lt),ct(lt),lt.content instanceof s&&pt(lt.content);bt(H.afterSanitizeShadowDOM,Oe,null)};return e.sanitize=function(at){let Oe=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},lt=null,Pe=null,Ge=null,et=null;if(Ye=!at,Ye&&(at=""),typeof at!="string"&&!Nt(at))if(typeof at.toString=="function"){if(at=at.toString(),typeof at!="string")throw Xv("dirty is not a string, aborting")}else throw Xv("toString is not a function");if(!e.isSupported)return at;if(Q||xt(Oe),e.removed=[],typeof at=="string"&&(re=!1),re){if(at.nodeName){const Ue=Be(at.nodeName);if(!W[Ue]||$[Ue])throw Xv("root node is forbidden and cannot be sanitized in-place")}}else if(at instanceof l)lt=We(""),Pe=lt.ownerDocument.importNode(at,!0),Pe.nodeType===Qv.element&&Pe.nodeName==="BODY"||Pe.nodeName==="HTML"?lt=Pe:lt.appendChild(Pe);else{if(!ee&&!me&&!V&&at.indexOf("<")===-1)return P&&ge?P.createHTML(at):at;if(lt=We(at),!lt)return ee?null:ge?N:""}lt&&G&&Vt(lt.firstChild);const Ke=Ft(re?at:lt);for(;Ge=Ke.nextNode();)Wt(Ge),ct(Ge),Ge.content instanceof s&&pt(Ge.content);if(re)return at;if(ee){if(me){lt.normalize();let Ue=lt.innerHTML;Wv([z,X,L],Je=>{Ue=Qb(Ue,Je," ")}),lt.innerHTML=Ue}if(se)for(et=F.call(lt.ownerDocument);lt.firstChild;)et.appendChild(lt.firstChild);else et=lt;return(pe.shadowroot||pe.shadowrootmode)&&(et=D.call(r,et,!0)),et}let Xe=V?lt.outerHTML:lt.innerHTML;return V&&W["!doctype"]&<.ownerDocument&<.ownerDocument.doctype&<.ownerDocument.doctype.name&&Gs(oie,lt.ownerDocument.doctype.name)&&(Xe=" + `,title:k("printers:control")?N(Tt?"printers.resume":"printers.pause"):N("printers.permission.noControl"),children:[Tt?a.jsx(Gi,{className:"w-3 h-3"}):a.jsx(Xw,{className:"w-3 h-3"}),N(Tt?"printers.resume":"printers.pause")]})]})]})]})})(),(En?.length>0||Ue.vt_tray.length>0)&&r==="expanded"&&(()=>{const tt=En.filter(it=>it.tray.length>1),Tt=En.filter(it=>it.tray.length===1),Kt=t.nozzle_count===2||Ue?.temperatures?.nozzle_2!==void 0;return a.jsxs("div",{className:"mt-3",children:[a.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[a.jsx("span",{className:"text-[10px] uppercase tracking-wider text-bambu-gray font-medium",children:N("printers.filaments")}),a.jsx("div",{className:"flex-1 h-px bg-bambu-dark-tertiary/30"})]}),a.jsxs("div",{className:"space-y-3",children:[tt.length>0&&a.jsx("div",{className:"grid grid-cols-2 gap-3",children:tt.map(it=>{const nn=hr[String(it.id)],gr=it.id>=128?it.id-128:it.id,Kn=nn!==void 0?nn:gr,ua=Kn===1,ga=Kn===0;return a.jsxs("div",{className:"p-2.5 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary/30",children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsxs("div",{className:"flex items-center gap-1.5",children:[a.jsx(lK,{ams:it,printerId:t.id,label:Rl(it.id,it.tray.length),amsLabels:Gt,canEdit:k("printers:update"),onSaved:ln,children:a.jsx("span",{className:"text-[10px] text-white font-medium cursor-default select-none",children:Gt?.[it.id]||Rl(it.id,it.tray.length)})}),Kt&&(ua||ga)&&a.jsx(nK,{side:ua?"L":"R"})]}),(it.humidity!=null||it.temp!=null)&&a.jsxs("div",{className:"flex items-center gap-1.5 max-[550px]:flex-col max-[550px]:items-start",children:[it.humidity!=null&&a.jsx(aK,{humidity:it.humidity,goodThreshold:s?.humidityGood,fairThreshold:s?.humidityFair,onClick:()=>rn({amsId:it.id,amsLabel:Rl(it.id,it.tray.length),mode:"humidity"}),compact:!0}),it.temp!=null&&a.jsx(iK,{temp:it.temp,goodThreshold:s?.tempGood,fairThreshold:s?.tempFair,onClick:()=>rn({amsId:it.id,amsLabel:Rl(it.id,it.tray.length),mode:"temperature"}),compact:!0}),Ue.supports_drying&&(it.module_type==="n3f"||it.module_type==="n3s")&&k("printers:control")&&a.jsx("button",{disabled:!!(it.dry_sf_reason?.length&&it.dry_time===0),onClick:en=>{if(it.dry_time>0)fa.mutate(it.id);else if(Me===it.id)Fe(null);else{const Sa=(it.tray.find(Ho=>Ho.tray_type)?.tray_type||"PLA").split(" ")[0].toUpperCase(),Ja=b[Sa]||b.PLA,Yi=it.module_type;nt(Sa),ze(Ja[Yi]||Ja.n3f),Ve(Yi==="n3s"?Ja.n3s_hours:Ja.n3f_hours),ue(!1),qe(it.module_type),Fe(it.id);const Sl=en.currentTarget.getBoundingClientRect();Be({top:Sl.bottom+4,left:Math.max(8,Sl.right-240)})}},className:`flex items-center gap-0.5 px-1 py-0.5 rounded text-[9px] transition-colors ${it.dry_time>0?"bg-amber-500/20 text-amber-400":it.dry_sf_reason?.length?"bg-bambu-dark-tertiary/30 text-bambu-gray/50 cursor-not-allowed":"bg-bambu-dark-tertiary/50 text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary"}`,title:it.dry_time>0?N("printers.drying.stop"):it.dry_sf_reason?.length?N("printers.drying.powerRequired"):N("printers.drying.start"),children:a.jsx(Lu,{className:"w-3 h-3"})})]})]}),it.dry_time>0&&a.jsxs("div",{className:"flex items-center gap-2 px-2 py-1 mb-1 bg-amber-500/10 border border-amber-500/20 rounded text-[9px]",children:[a.jsx(Lu,{className:"w-3 h-3 text-amber-400 shrink-0"}),a.jsx("span",{className:"text-amber-400 font-medium",children:N("printers.drying.active")}),a.jsx("span",{className:"text-amber-300/70",children:N("printers.drying.timeRemaining",{time:it.dry_time>=60?`${Math.floor(it.dry_time/60)}h ${it.dry_time%60}m`:`${it.dry_time}m`})}),a.jsx("button",{onClick:()=>fa.mutate(it.id),disabled:fa.isPending,className:"ml-auto text-amber-400 hover:text-amber-300 transition-colors disabled:opacity-50",title:N("printers.drying.stop"),children:a.jsx(Ht,{className:"w-3 h-3"})})]}),a.jsx("div",{className:"grid grid-cols-4 gap-1.5",children:[0,1,2,3].map(en=>{const Tn=it.tray[en]||it.tray.find(Fn=>Fn.id===en),Sa=Tn?.tray_type&&Tn.remain>=0,Ja=!Tn?.tray_type,Yi=it.id*4+en,Sl=na===Yi,Ho=Tn?.tray_info_idx?vt?.[Tn.tray_info_idx]:null,qr=Et?.[Yi],Qi=(Tn?.tray_uuid||Tn?.tag_uid||zu(t.serial_number,it.id,en))?.toUpperCase(),vc=Qi?l?.[Qi]:void 0,Ss=Xk(vc),bo=u?.(t.id,it.id,en),wc=(()=>{const Fn=bo?.spool;return Fn&&Fn.label_weight>0&&Fn.weight_used!=null?Math.round(Math.max(0,Fn.label_weight-Fn.weight_used)/Fn.label_weight*100):null})(),Or=wc===0&&Sa&&Tn.remain>0?null:wc,Zi=Ss??Or??(Sa?Tn.remain:null),Oy=Ss!==null?"spoolman":Or!==null?"inventory":Sa?"ams":void 0,$r=Tn?.tray_type?{vendor:MD(Tn)?"Bambu Lab":"Generic",profile:qr?.preset_name||Ho?.name||bo?.spool?.slicer_filament_name||Tn.tray_sub_brands||Tn.tray_type,colorName:Zl(Tn.tray_color||""),colorHex:Tn.tray_color||null,kFactor:AD(Tn.k),fillLevel:Zi,trayUuid:Tn.tray_uuid||null,tagUid:Tn.tag_uid||null,fillSource:Oy}:null,id=ws?.amsId===it.id&&ws?.slotId===en,Dm=a.jsxs("div",{className:`bg-bambu-dark-tertiary rounded p-1 text-center ${Ja?"opacity-50":""} ${Sl?"ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark":""}`,children:[a.jsx(TD,{trayColor:Tn?.tray_color,trayType:Tn?.tray_type,isEmpty:Ja,slotNumber:en+1}),a.jsx("div",{className:"text-[9px] text-white font-bold truncate",children:Tn?.tray_type||"—"}),a.jsx("div",{className:"mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden",children:Zi!==null&&Zi>=0&&!Ja&&Tn&&a.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${Zi}%`,backgroundColor:Tx(Zi)}})})]});return a.jsxs("div",{className:"relative group",children:[id&&a.jsx("div",{className:"absolute inset-0 bg-bambu-dark-tertiary/80 rounded flex items-center justify-center z-20",children:a.jsx(or,{className:"w-4 h-4 text-bambu-green animate-spin"})}),Ue?.state!=="RUNNING"&&a.jsx("button",{onClick:Fn=>{Fn.stopPropagation(),tu(go?.amsId===it.id&&go?.slotId===en?null:{amsId:it.id,slotId:en})},className:"absolute -top-1 -right-1 w-4 h-4 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity z-10 hover:bg-bambu-dark-tertiary",title:N("printers.slotOptions"),children:a.jsx(Gh,{className:"w-2.5 h-2.5 text-bambu-gray"})}),Ue?.state!=="RUNNING"&&go?.amsId===it.id&&go?.slotId===en&&a.jsx("div",{className:"absolute top-full left-0 mt-1 z-50 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl py-1 min-w-[120px]",children:a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-xs flex items-center gap-2 ${k("printers:ams_rfid")?"text-white hover:bg-bambu-dark-tertiary":"text-bambu-gray/50 cursor-not-allowed"}`,onClick:Fn=>{Fn.stopPropagation(),k("printers:ams_rfid")&&(nd.mutate({amsId:it.id,slotId:en}),tu(null))},disabled:id||!k("printers:ams_rfid"),title:k("printers:ams_rfid")?void 0:N("printers.permission.noAmsRfid"),children:[a.jsx(or,{className:`w-3 h-3 ${id?"animate-spin":""}`}),N("printers.rfid.reread")]})}),$r?a.jsx(kD,{data:$r,spoolman:{enabled:o,linkedSpoolId:Qi?l?.[Qi]?.id:void 0,spoolmanUrl:c,syncMode:d,onLinkSpool:o?()=>{const Fn=($r.trayUuid||$r.tagUid||zu(t.serial_number,it.id,en)).toUpperCase();Jt({tagUid:$r.tagUid||Fn,trayUuid:$r.trayUuid||"",printerId:t.id,amsId:it.id,trayId:en})}:void 0,onUnlinkSpool:vc?.id?()=>Uo.mutate(vc.id):void 0},inventory:o?void 0:(()=>{const Fn=u?.(t.id,it.id,en);return{assignedSpool:Fn?.spool?{id:Fn.spool.id,material:Fn.spool.material,brand:Fn.spool.brand,color_name:Fn.spool.color_name,remainingWeightGrams:Math.max(0,Math.round(Fn.spool.label_weight-Fn.spool.weight_used))}:null,onAssignSpool:$r.vendor!=="Bambu Lab"?()=>Ft({printerId:t.id,amsId:it.id,trayId:en,trayInfo:{type:Tn?.tray_type||$r.profile,material:Tn?.tray_type??void 0,profile:$r.profile,color:$r.colorHex||"",location:`${Rl(it.id,it.tray.length)} Slot ${en+1}`}}):void 0,onUnassignSpool:Fn&&$r.vendor!=="Bambu Lab"?()=>m?.(t.id,it.id,en):void 0}})(),configureSlot:{enabled:k("printers:control"),onConfigure:()=>Nt({amsId:it.id,trayId:en,trayCount:it.tray.length,trayType:Tn?.tray_type||void 0,trayColor:Tn?.tray_color||void 0,traySubBrands:Tn?.tray_sub_brands||void 0,trayInfoIdx:Tn?.tray_info_idx||void 0,extruderId:nn,caliIdx:Tn?.cali_idx,savedPresetId:qr?.preset_id})},children:Dm}):a.jsx(ND,{configureSlot:Tn?.state===10?{enabled:k("printers:control"),onConfigure:()=>Nt({amsId:it.id,trayId:en,trayCount:it.tray.length,extruderId:nn})}:void 0,inventory:Tn?.state===10&&!o?{onAssignSpool:()=>Ft({printerId:t.id,amsId:it.id,trayId:en,trayInfo:{type:"",color:"",location:`${Rl(it.id,it.tray.length)} Slot ${en+1}`}})}:void 0,children:Dm})]},en)})})]},it.id)})}),(Tt.length>0||Ue.vt_tray.length>0)&&a.jsxs("div",{className:"grid grid-cols-4 gap-3",children:[Tt.map(it=>{const nn=hr[String(it.id)],gr=it.id>=128?it.id-128:it.id,Kn=nn!==void 0?nn:gr,ua=Kn===1,ga=Kn===0,en=it.tray[0],Tn=en?.tray_type&&en.remain>=0,Sa=!en?.tray_type,Ja=Jx(it.id,en?.id??0,!1),Yi=na===Ja,Sl=en?.tray_info_idx?vt?.[en.tray_info_idx]:null,Ho=Et?.[Ja],qr=en?.id??0,Qi=(en?.tray_uuid||en?.tag_uid||zu(t.serial_number,it.id,qr))?.toUpperCase(),vc=Qi?l?.[Qi]:void 0,Ss=Xk(vc),bo=u?.(t.id,it.id,qr),wc=(()=>{const Fn=bo?.spool;return Fn&&Fn.label_weight>0&&Fn.weight_used!=null?Math.round(Math.max(0,Fn.label_weight-Fn.weight_used)/Fn.label_weight*100):null})(),Or=wc===0&&Tn&&en.remain>0?null:wc,Zi=Ss??Or??(Tn?en.remain:null),Oy=Ss!==null?"spoolman":Or!==null?"inventory":Tn?"ams":void 0,$r=en?.tray_type?{vendor:MD(en)?"Bambu Lab":"Generic",profile:Ho?.preset_name||Sl?.name||bo?.spool?.slicer_filament_name||en.tray_sub_brands||en.tray_type,colorName:Zl(en.tray_color||""),colorHex:en.tray_color||null,kFactor:AD(en.k),fillLevel:Zi,trayUuid:en.tray_uuid||null,tagUid:en.tag_uid||null,fillSource:Oy}:null,id=ws?.amsId===it.id&&ws?.slotId===qr,Dm=a.jsxs("div",{className:`bg-bambu-dark-tertiary rounded p-1 text-center ${Sa?"opacity-50":""} ${Yi?"ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark":""}`,children:[a.jsx(TD,{trayColor:en?.tray_color,trayType:en?.tray_type,isEmpty:Sa,slotNumber:1}),a.jsx("div",{className:"text-[9px] text-white font-bold truncate",children:en?.tray_type||"—"}),a.jsx("div",{className:"mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden",children:Zi!==null&&Zi>=0&&!Sa&&a.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${Zi}%`,backgroundColor:Tx(Zi)}})})]});return a.jsxs("div",{className:"p-2.5 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary/30",children:[a.jsxs("div",{className:"flex items-center gap-1 mb-2",children:[a.jsx(lK,{ams:it,printerId:t.id,label:Rl(it.id,it.tray.length),amsLabels:Gt,canEdit:k("printers:update"),onSaved:ln,children:a.jsx("span",{className:"text-[10px] text-white font-medium cursor-default select-none",children:Gt?.[it.id]||Rl(it.id,it.tray.length)})}),Kt&&(ua||ga)&&a.jsx(nK,{side:ua?"L":"R"}),Ue.supports_drying&&(it.module_type==="n3f"||it.module_type==="n3s")&&k("printers:control")&&a.jsx("div",{className:"relative ml-auto",children:a.jsx("button",{onClick:Fn=>{if(it.dry_time>0)fa.mutate(it.id);else if(Me===it.id)Fe(null);else{const Iy=(it.tray.find(bA=>bA.tray_type)?.tray_type||"PLA").split(" ")[0].toUpperCase(),Fp=b[Iy]||b.PLA,zy=it.module_type;nt(Iy),ze(Fp[zy]||Fp.n3f),Ve(zy==="n3s"?Fp.n3s_hours:Fp.n3f_hours),ue(!1),qe(it.module_type),Fe(it.id);const OS=Fn.currentTarget.getBoundingClientRect();Be({top:OS.bottom+4,left:Math.max(8,OS.right-240)})}},className:`flex items-center gap-0.5 px-1 py-0.5 rounded text-[9px] transition-colors ${it.dry_time>0?"bg-amber-500/20 text-amber-400":"bg-bambu-dark-tertiary/50 text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary"}`,title:it.dry_time>0?N("printers.drying.stop"):N("printers.drying.start"),children:a.jsx(Lu,{className:"w-3 h-3"})})})]}),it.dry_time>0&&a.jsxs("div",{className:"flex items-center gap-1.5 px-2 py-1 mb-1 bg-amber-500/10 border border-amber-500/20 rounded text-[9px] whitespace-nowrap overflow-hidden",children:[a.jsx(Lu,{className:"w-3 h-3 text-amber-400 shrink-0"}),a.jsx("span",{className:"text-amber-300/70 text-[8px] truncate",children:it.dry_time>=60?`${Math.floor(it.dry_time/60)}h ${it.dry_time%60}m`:`${it.dry_time}m`}),a.jsx("button",{onClick:()=>fa.mutate(it.id),disabled:fa.isPending,className:"ml-auto text-amber-400 hover:text-amber-300 transition-colors disabled:opacity-50 shrink-0",title:N("printers.drying.stop"),children:a.jsx(Ht,{className:"w-3 h-3"})})]}),a.jsxs("div",{className:"flex gap-1.5 max-[550px]:flex-col max-[550px]:items-start",children:[a.jsxs("div",{className:"relative group flex-1 max-[550px]:w-full",children:[id&&a.jsx("div",{className:"absolute inset-0 bg-bambu-dark-tertiary/80 rounded flex items-center justify-center z-20",children:a.jsx(or,{className:"w-4 h-4 text-bambu-green animate-spin"})}),Ue?.state!=="RUNNING"&&a.jsx("button",{onClick:Fn=>{Fn.stopPropagation(),tu(go?.amsId===it.id&&go?.slotId===qr?null:{amsId:it.id,slotId:qr})},className:"absolute -top-1 -right-1 w-4 h-4 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity z-10 hover:bg-bambu-dark-tertiary",title:N("printers.slotOptions"),children:a.jsx(Gh,{className:"w-2.5 h-2.5 text-bambu-gray"})}),Ue?.state!=="RUNNING"&&go?.amsId===it.id&&go?.slotId===qr&&a.jsx("div",{className:"absolute top-full left-0 mt-1 z-50 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl py-1 min-w-[120px]",children:a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-xs flex items-center gap-2 ${k("printers:ams_rfid")?"text-white hover:bg-bambu-dark-tertiary":"text-bambu-gray/50 cursor-not-allowed"}`,onClick:Fn=>{Fn.stopPropagation(),k("printers:ams_rfid")&&(nd.mutate({amsId:it.id,slotId:qr}),tu(null))},disabled:id||!k("printers:ams_rfid"),title:k("printers:ams_rfid")?void 0:N("printers.permission.noAmsRfid"),children:[a.jsx(or,{className:`w-3 h-3 ${id?"animate-spin":""}`}),N("printers.rfid.reread")]})}),$r?a.jsx(kD,{data:$r,spoolman:{enabled:o,linkedSpoolId:Qi?l?.[Qi]?.id:void 0,spoolmanUrl:c,syncMode:d,onLinkSpool:o?()=>{const Fn=($r.trayUuid||$r.tagUid||zu(t.serial_number,it.id,qr)).toUpperCase();Jt({tagUid:$r.tagUid||Fn,trayUuid:$r.trayUuid||"",printerId:t.id,amsId:it.id,trayId:qr})}:void 0,onUnlinkSpool:vc?.id?()=>Uo.mutate(vc.id):void 0},inventory:o?void 0:(()=>{const Fn=u?.(t.id,it.id,qr);return{assignedSpool:Fn?.spool?{id:Fn.spool.id,material:Fn.spool.material,brand:Fn.spool.brand,color_name:Fn.spool.color_name,remainingWeightGrams:Math.max(0,Math.round(Fn.spool.label_weight-Fn.spool.weight_used))}:null,onAssignSpool:$r.vendor!=="Bambu Lab"?()=>Ft({printerId:t.id,amsId:it.id,trayId:qr,trayInfo:{type:en?.tray_type||$r.profile,material:en?.tray_type??void 0,profile:$r.profile,color:$r.colorHex||"",location:Rl(it.id,it.tray.length)}}):void 0,onUnassignSpool:Fn&&$r.vendor!=="Bambu Lab"?()=>m?.(t.id,it.id,qr):void 0}})(),configureSlot:{enabled:k("printers:control"),onConfigure:()=>Nt({amsId:it.id,trayId:qr,trayCount:it.tray.length,trayType:en?.tray_type||void 0,trayColor:en?.tray_color||void 0,traySubBrands:en?.tray_sub_brands||void 0,trayInfoIdx:en?.tray_info_idx||void 0,extruderId:nn,caliIdx:en?.cali_idx,savedPresetId:Ho?.preset_id})},children:Dm}):a.jsx(ND,{configureSlot:en?.state===10?{enabled:k("printers:control"),onConfigure:()=>Nt({amsId:it.id,trayId:qr,trayCount:it.tray.length,extruderId:nn})}:void 0,inventory:en?.state===10&&!o?{onAssignSpool:()=>Ft({printerId:t.id,amsId:it.id,trayId:qr,trayInfo:{type:"",color:"",location:Rl(it.id,it.tray.length)}})}:void 0,children:Dm})]}),(it.humidity!=null||it.temp!=null)&&a.jsxs("div",{className:"flex flex-col justify-center gap-1 shrink-0 max-[550px]:w-full",children:[it.temp!=null&&a.jsx(iK,{temp:it.temp,goodThreshold:s?.tempGood,fairThreshold:s?.tempFair,onClick:()=>rn({amsId:it.id,amsLabel:Rl(it.id,it.tray.length),mode:"temperature"}),compact:!0}),it.humidity!=null&&a.jsx(aK,{humidity:it.humidity,goodThreshold:s?.humidityGood,fairThreshold:s?.humidityFair,onClick:()=>rn({amsId:it.id,amsLabel:Rl(it.id,it.tray.length),mode:"humidity"}),compact:!0})]})]})]},it.id)}),Ue.vt_tray.length>0&&a.jsxs("div",{className:`p-2.5 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary/30 ${Ue.vt_tray.length===1?"max-w-[50%]":""}`,children:[a.jsx("div",{className:"flex items-center gap-1 mb-2",children:a.jsx("span",{className:"text-[10px] text-white font-medium",children:N("printers.external")})}),a.jsx("div",{className:`grid ${Ue.vt_tray.length>1?"grid-cols-2":"grid-cols-1"} gap-1.5`,children:[...Ue.vt_tray].sort((it,nn)=>(it.id??254)-(nn.id??254)).map(it=>{const nn=it.id??254,gr=Kt&&na===254?nn===254&&Ue.active_extruder===1||nn===255&&Ue.active_extruder===0:na===nn,Kn=nn-254,ua=Kt?N(nn===254?"printers.extL":"printers.extR"):"",ga=it.tray_info_idx?vt?.[it.tray_info_idx]:null,en=Et?.[1020+Kn],Tn=(it.tray_uuid||it.tag_uid||zu(t.serial_number,255,Kn))?.toUpperCase(),Sa=Tn?l?.[Tn]:void 0,Ja=Xk(Sa),Yi=u?.(t.id,255,Kn),Sl=(()=>{const Or=Yi?.spool;return Or&&Or.label_weight>0&&Or.weight_used!=null?Math.round(Math.max(0,Or.label_weight-Or.weight_used)/Or.label_weight*100):null})(),Ho=it.tray_type&&it.remain>=0,qr=Sl===0&&Ho&&it.remain>0?null:Sl,Qi=Ja??qr??(Ho?it.remain:null),vc=Ja!==null?"spoolman":qr!==null?"inventory":Ho?"ams":void 0,Ss={vendor:MD(it)?"Bambu Lab":"Generic",profile:en?.preset_name||ga?.name||Yi?.spool?.slicer_filament_name||it.tray_sub_brands||it.tray_type||"Unknown",colorName:Zl(it.tray_color||""),colorHex:it.tray_color||null,kFactor:AD(it.k),fillLevel:Qi,trayUuid:it.tray_uuid||null,tagUid:it.tag_uid||null,fillSource:vc},bo=!it.tray_type,wc=a.jsxs("div",{className:`bg-bambu-dark-tertiary rounded p-1 text-center ${bo?"opacity-50":""} ${gr?"ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark":""}`,children:[a.jsx(TD,{trayColor:it.tray_color,trayType:it.tray_type,isEmpty:bo,slotNumber:Kn+1}),a.jsx("div",{className:`text-[9px] font-bold truncate ${bo?"text-white/40":"text-white"}`,children:it.tray_type||"—"}),a.jsx("div",{className:"mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden",children:Qi!==null&&Qi>=0&&!bo&&a.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${Qi}%`,backgroundColor:Tx(Qi)}})}),ua&&a.jsx("div",{className:"text-[7px] text-white/40 mt-0.5 truncate",children:ua})]});return a.jsx("div",{className:"relative group",children:bo?a.jsx(ND,{configureSlot:{enabled:k("printers:control"),onConfigure:()=>Nt({amsId:255,trayId:Kn,trayCount:1,extruderId:Kt?nn===254?1:0:void 0})},inventory:o?void 0:{onAssignSpool:()=>Ft({printerId:t.id,amsId:255,trayId:Kn,trayInfo:{type:"",color:"",location:ua||N("printers.external")}})},children:wc}):a.jsx(kD,{data:Ss,spoolman:{enabled:o,linkedSpoolId:Tn?l?.[Tn]?.id:void 0,spoolmanUrl:c,syncMode:d,onLinkSpool:o?()=>{const Or=(Ss.trayUuid||Ss.tagUid||zu(t.serial_number,255,Kn)).toUpperCase();Jt({tagUid:Ss.tagUid||Or,trayUuid:Ss.trayUuid||"",printerId:t.id,amsId:255,trayId:Kn})}:void 0,onUnlinkSpool:Sa?.id?()=>Uo.mutate(Sa.id):void 0},inventory:o?void 0:(()=>{const Or=u?.(t.id,255,Kn);return{assignedSpool:Or?.spool?{id:Or.spool.id,material:Or.spool.material,brand:Or.spool.brand,color_name:Or.spool.color_name,remainingWeightGrams:Math.max(0,Math.round(Or.spool.label_weight-Or.spool.weight_used))}:null,onAssignSpool:()=>Ft({printerId:t.id,amsId:255,trayId:Kn,trayInfo:{type:it.tray_type||Ss.profile,material:it.tray_type??void 0,profile:Ss.profile,color:Ss.colorHex||"",location:ua||N("printers.external")}}),onUnassignSpool:Or?()=>m?.(t.id,255,Kn):void 0}})(),configureSlot:{enabled:k("printers:control"),onConfigure:()=>Nt({amsId:255,trayId:Kn,trayCount:1,trayType:it.tray_type||void 0,trayColor:it.tray_color||void 0,traySubBrands:it.tray_sub_brands||void 0,trayInfoIdx:it.tray_info_idx||void 0,extruderId:Kt?nn===254?1:0:void 0,caliIdx:it.cali_idx,savedPresetId:en?.preset_id})},children:wc})},nn)})})]})]})]})]})})()]}),Bn&&r==="expanded"&&a.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[a.jsx(ic,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}),a.jsx("span",{className:"text-sm text-white truncate",children:Bn.name}),pr&&a.jsxs("span",{className:`text-xs px-1.5 py-0.5 rounded flex-shrink-0 ${pr.state==="ON"?"bg-bambu-green/20 text-bambu-green":pr.state==="OFF"?"bg-red-500/20 text-red-400":"bg-bambu-gray/20 text-bambu-gray"}`,children:[pr.state||"?",pr.state==="ON"&&pr.energy?.power!=null&&a.jsxs("span",{className:"text-yellow-400 ml-1.5",children:["· ",pr.energy.power,"W"]})]})]}),a.jsx("div",{className:"flex-1"}),a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsxs("button",{onClick:()=>pe(!0),disabled:Zc.isPending||pr?.state==="ON"||!k("smart_plugs:control"),className:`px-2 py-1 text-xs rounded transition-colors flex items-center gap-1 ${k("smart_plugs:control")?pr?.state==="ON"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary":"bg-bambu-dark text-bambu-gray/50 cursor-not-allowed"}`,title:k("smart_plugs:control")?void 0:N("printers.permission.noSmartPlugControl"),children:[a.jsx(Wd,{className:"w-3 h-3"}),"On"]}),a.jsxs("button",{onClick:()=>Ce(!0),disabled:Zc.isPending||pr?.state==="OFF"||!k("smart_plugs:control"),className:`px-2 py-1 text-xs rounded transition-colors flex items-center gap-1 ${k("smart_plugs:control")?pr?.state==="OFF"?"bg-red-500/30 text-red-400":"bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary":"bg-bambu-dark text-bambu-gray/50 cursor-not-allowed"}`,title:k("smart_plugs:control")?void 0:N("printers.permission.noSmartPlugControl"),children:[a.jsx(Yw,{className:"w-3 h-3"}),"Off"]})]}),a.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[a.jsx("span",{className:`text-xs hidden sm:inline ${Bn.auto_off_executed?"text-bambu-green":"text-bambu-gray"}`,children:Bn.auto_off_executed?"Auto-off done":"Auto-off"}),a.jsx("button",{onClick:()=>Mm.mutate(!Bn.auto_off),disabled:Mm.isPending||Bn.auto_off_executed||!k("smart_plugs:control"),title:k("smart_plugs:control")?Bn.auto_off_executed?N("printers.autoOffExecuted"):N("printers.autoOffAfterPrint"):N("printers.permission.noSmartPlugControl"),className:`relative w-9 h-5 rounded-full transition-colors flex-shrink-0 ${k("smart_plugs:control")?Bn.auto_off_executed?"bg-bambu-green/50 cursor-not-allowed":Bn.auto_off?"bg-bambu-green":"bg-bambu-dark-tertiary":"bg-bambu-dark-tertiary/50 cursor-not-allowed"}`,children:a.jsx("span",{className:`absolute top-[2px] left-[2px] w-4 h-4 bg-white rounded-full transition-transform ${Bn.auto_off||Bn.auto_off_executed?"translate-x-4":"translate-x-0"}`})})]})]}),ra&&ra.length>0&&a.jsxs("div",{className:"flex items-center gap-2 mt-2 pt-2 border-t border-bambu-dark-tertiary/50",children:[a.jsx(Vw,{className:"w-3.5 h-3.5 text-blue-400 flex-shrink-0"}),a.jsx("span",{className:"text-xs text-bambu-gray",children:"HA:"}),a.jsx("div",{className:"flex flex-wrap gap-1",children:ra.map(tt=>{const Tt=tt.ha_entity_id?.startsWith("script.");return a.jsxs("button",{onClick:()=>Jc.mutate({id:tt.id,action:Tt?"on":"toggle"}),disabled:Jc.isPending,title:`${Tt?"Run":"Toggle"} ${tt.ha_entity_id}`,className:"px-2 py-0.5 text-xs bg-blue-500/20 text-blue-400 hover:bg-blue-500/30 rounded transition-colors flex items-center gap-1",children:[a.jsx(Gi,{className:"w-2.5 h-2.5"}),tt.name]},tt.id)})})]})]}),r==="expanded"&&a.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary flex items-center justify-end gap-2 flex-wrap",children:[a.jsx(De,{variant:"secondary",size:"sm",onClick:()=>Bo.mutate(!Ue?.chamber_light),disabled:!Ue?.connected||Bo.isPending||!k("printers:control"),title:k("printers:control")?Ue?.chamber_light?N("printers.chamberLightOff"):N("printers.chamberLightOn"):N("printers.permission.noControl"),className:Ue?.chamber_light?"!border-yellow-500 !text-yellow-400 hover:!bg-yellow-500/20":"",children:a.jsx(uI,{on:Ue?.chamber_light??!1,className:`w-4 h-4 ${Ue?.chamber_light?"text-yellow-400":""}`})}),a.jsx(De,{variant:"secondary",size:"sm",onClick:()=>{if(f==="embedded"&&x)x(t.id,t.name);else{const tt=localStorage.getItem("cameraWindowState"),Tt=tt?JSON.parse(tt):{width:640,height:400},Kt=[`width=${Tt.width}`,`height=${Tt.height}`,Tt.left!==void 0?`left=${Tt.left}`:"",Tt.top!==void 0?`top=${Tt.top}`:"","menubar=no,toolbar=no,location=no,status=no"].filter(Boolean).join(",");window.open(`/camera/${t.id}`,`camera-${t.id}`,Kt)}},disabled:!Ue?.connected||!k("camera:view"),title:k("camera:view")?N(f==="embedded"?"printers.openCameraOverlay":"printers.openCameraWindow"):N("printers.permission.noCamera"),children:a.jsx(jO,{className:"w-4 h-4"})}),a.jsxs("div",{className:`inline-flex rounded-md ${t.plate_detection_enabled?"ring-1 ring-green-500":""}`,children:[a.jsx(De,{variant:"secondary",size:"sm",onClick:Fg,disabled:!Ue?.connected||gc.isPending||!k("printers:update"),title:k("printers:update")?t.plate_detection_enabled?N("printers.plateDetection.enabledClick"):N("printers.plateDetection.disabledClick"):N("printers.plateDetection.noPermission"),className:`!rounded-r-none !border-r-0 ${t.plate_detection_enabled?"!border-green-500 !text-green-400 hover:!bg-green-500/20":""}`,children:gc.isPending?a.jsx(ht,{className:"w-4 h-4 animate-spin"}):a.jsx(yN,{className:"w-4 h-4"})}),a.jsx(De,{variant:"secondary",size:"sm",onClick:eu,disabled:!Ue?.connected||ct||!k("printers:update"),title:k("printers:update")?N("printers.plateDetection.manageCalibration"):N("printers.plateDetection.noPermission"),className:`!rounded-l-none !px-1.5 ${t.plate_detection_enabled?"!border-green-500 !text-green-400 hover:!bg-green-500/20":""}`,children:ct?a.jsx(ht,{className:"w-3 h-3 animate-spin"}):a.jsx(In,{className:"w-3 h-3"})})]}),a.jsxs(De,{variant:"secondary",size:"sm",onClick:()=>oe(!0),disabled:!bn||!k("printers:files"),title:k("printers:files")?N("printers.browseFiles"):N("printers.permission.noFiles"),children:[a.jsx(Cg,{className:"w-4 h-4"}),N("printers.files")]}),bn&&Ue?.state!=="RUNNING"&&Ue?.state!=="PAUSE"&&a.jsxs(De,{size:"sm",onClick:()=>Se(!0),disabled:!k("printers:control"),title:k("printers:control")?N("common.print"):N("printers.permission.noControl"),className:"!bg-bambu-green hover:!bg-bambu-green/80 !text-white",children:[a.jsx(Ar,{className:"w-4 h-4"}),N("common.print")]})]})]}),ce&&a.jsx(BMe,{printerId:t.id,printerName:t.name,onClose:()=>oe(!1)}),_e&&a.jsx(Gae,{folderId:null,onClose:()=>Se(!1),onUploadComplete:()=>{},autoUpload:!0,accept:".gcode,.3mf",validateFile:tt=>{const Tt=tt.name.toLowerCase();if(!Tt.endsWith(".gcode")&&!Tt.includes(".gcode."))return N("printers.dropNotPrintable","Only .gcode and .gcode.3mf files can be printed")},onFileUploaded:tt=>{const Tt=tt.metadata?.sliced_for_model,Kt=A0(t.model);if(Tt&&Kt&&Tt.toLowerCase()!==Kt.toLowerCase())return he.deleteLibraryFile(tt.id).catch(()=>{}),N("printers.incompatibleFile","This file was sliced for {{slicedFor}}, but this printer is a {{printerModel}}",{slicedFor:Tt,printerModel:Kt});Le({id:tt.id,filename:tt.filename})}}),Ae&&a.jsx(ec,{mode:"reprint",libraryFileId:Ae.id,archiveName:Ae.filename,initialSelectedPrinterIds:[t.id],onClose:()=>Le(null),onSuccess:()=>Le(null)}),le&&a.jsx(WMe,{printerId:t.id,printerName:t.name,onClose:()=>W(!1)}),ye&&a.jsx(k7e,{printer:t,status:Ue,totalPrintHours:n?.total_print_hours,onClose:xe}),It&&a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onClick:()=>yc(),children:a.jsxs("div",{className:"bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl max-w-lg w-full",onClick:tt=>tt.stopPropagation(),children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[It.needs_calibration?a.jsx(yN,{className:"w-5 h-5 text-blue-500"}):It.is_empty?a.jsx(yr,{className:"w-5 h-5 text-green-500"}):a.jsx(Ta,{className:"w-5 h-5 text-yellow-500"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:"Build Plate Check"}),It.reference_count!==void 0&&It.max_references&&a.jsxs("span",{className:"text-xs text-bambu-gray bg-bambu-dark-tertiary px-2 py-1 rounded",children:[It.reference_count,"/",It.max_references," refs"]})]}),a.jsx("button",{onClick:()=>yc(),className:"p-1 text-bambu-gray hover:text-white rounded transition-colors",children:a.jsx(Ht,{className:"w-5 h-5"})})]}),a.jsxs("div",{className:"p-4 space-y-4",children:[It.needs_calibration?a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"p-3 rounded-lg bg-blue-500/20 border border-blue-500/50",children:[a.jsx("p",{className:"font-medium text-blue-400",children:N("printers.plateDetection.calibrationRequired")}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",dangerouslySetInnerHTML:{__html:N("printers.plateDetection.calibrationInstructions")}})]}),a.jsxs("div",{className:"text-sm text-bambu-gray space-y-2",children:[a.jsx("p",{children:N("printers.plateDetection.calibrationDescription")}),a.jsx("p",{dangerouslySetInnerHTML:{__html:N("printers.plateDetection.calibrationTip")}})]})]}):a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:`p-3 rounded-lg ${It.is_empty?"bg-green-500/20 border border-green-500/50":"bg-yellow-500/20 border border-yellow-500/50"}`,children:[a.jsx("p",{className:`font-medium ${It.is_empty?"text-green-400":"text-yellow-400"}`,children:It.is_empty?N("printers.plateDetection.plateEmpty"):N("printers.plateDetection.objectsDetected")}),a.jsxs("p",{className:"text-sm text-bambu-gray mt-1",children:[N("printers.plateDetection.confidence"),": ",Math.round(It.confidence*100),"% | ",N("printers.plateDetection.difference"),": ",It.difference_percent.toFixed(1),"%"]})]}),It.debug_image_url&&a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-bambu-gray mb-2",children:N("printers.plateDetection.analysisPreview")}),a.jsx("img",{src:It.debug_image_url,alt:N("printers.plateDetection.analysisPreview"),className:"w-full rounded-lg border border-bambu-dark-tertiary"}),a.jsx("p",{className:"text-xs text-bambu-gray mt-2",children:N("printers.plateDetection.analysisLegend")})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:It.message})]}),Xi&&Xi.references.length>0&&a.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[a.jsx("p",{className:"text-sm font-medium text-white mb-2",children:N("printers.plateDetection.savedReferences",{count:Xi.references.length,max:Xi.max_references})}),a.jsx("div",{className:"grid grid-cols-5 gap-2",children:Xi.references.map(tt=>a.jsxs("div",{className:"relative group",children:[a.jsx("img",{src:he.getPlateReferenceThumbnailUrl(t.id,tt.index),alt:tt.label||`Reference ${tt.index+1}`,className:"w-full aspect-video object-cover rounded border border-bambu-dark-tertiary"}),a.jsx("button",{onClick:()=>Ep(tt.index),className:"absolute top-1 right-1 p-0.5 bg-red-500/80 rounded opacity-0 group-hover:opacity-100 transition-opacity",title:N("printers.plateDetection.deleteReference"),children:a.jsx(Ht,{className:"w-3 h-3 text-white"})}),po?.index===tt.index?a.jsx("input",{type:"text",value:po.label,onChange:Tt=>bc({...po,label:Tt.target.value}),onBlur:()=>Rg(tt.index,po.label),onKeyDown:Tt=>{Tt.key==="Enter"&&Rg(tt.index,po.label),Tt.key==="Escape"&&bc(null)},className:"w-full mt-1 px-1 py-0.5 text-xs bg-bambu-dark-tertiary border border-bambu-green rounded text-white",autoFocus:!0,placeholder:N("printers.plateDetection.labelPlaceholder")}):a.jsx("p",{className:"text-xs text-bambu-gray mt-1 truncate cursor-pointer hover:text-white",onClick:()=>bc({index:tt.index,label:tt.label}),title:tt.label?N("printers.plateDetection.clickToEdit",{label:tt.label}):N("printers.plateDetection.clickToAddLabel"),children:tt.label||a.jsx("span",{className:"italic opacity-50",children:N("printers.noLabel")})}),a.jsx("p",{className:"text-[10px] text-bambu-gray/60",children:tt.timestamp?Zn(tt.timestamp)?.toLocaleDateString()??"":""})]},tt.index))})]}),!It.needs_calibration&&a.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsx("p",{className:"text-sm font-medium text-white",children:N("printers.roi.title")}),lt?a.jsxs("div",{className:"flex gap-1",children:[a.jsx(De,{variant:"ghost",size:"sm",onClick:()=>Pe(null),disabled:Ge,children:N("common.cancel")}),a.jsx(De,{size:"sm",onClick:Lg,disabled:Ge,children:Ge?a.jsx(ht,{className:"w-3 h-3 animate-spin"}):N("common.save")})]}):a.jsxs(De,{variant:"ghost",size:"sm",onClick:()=>Pe(It.roi||{x:.15,y:.35,w:.7,h:.55}),children:[a.jsx(ii,{className:"w-3 h-3 mr-1"}),N("common.edit")]})]}),lt?a.jsxs("div",{className:"space-y-3 bg-bambu-dark-tertiary/50 p-3 rounded-lg",children:[a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"text-xs text-bambu-gray",children:N("printers.roi.xStart")}),a.jsx("input",{type:"range",min:"0",max:"0.9",step:"0.01",value:lt.x,onChange:tt=>Pe({...lt,x:parseFloat(tt.target.value)}),className:"w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"}),a.jsxs("span",{className:"text-xs text-bambu-gray",children:[Math.round(lt.x*100),"%"]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"text-xs text-bambu-gray",children:N("printers.roi.yStart")}),a.jsx("input",{type:"range",min:"0",max:"0.9",step:"0.01",value:lt.y,onChange:tt=>Pe({...lt,y:parseFloat(tt.target.value)}),className:"w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"}),a.jsxs("span",{className:"text-xs text-bambu-gray",children:[Math.round(lt.y*100),"%"]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"text-xs text-bambu-gray",children:N("printers.width")}),a.jsx("input",{type:"range",min:"0.1",max:"1",step:"0.01",value:lt.w,onChange:tt=>Pe({...lt,w:parseFloat(tt.target.value)}),className:"w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"}),a.jsxs("span",{className:"text-xs text-bambu-gray",children:[Math.round(lt.w*100),"%"]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"text-xs text-bambu-gray",children:N("printers.height")}),a.jsx("input",{type:"range",min:"0.1",max:"1",step:"0.01",value:lt.h,onChange:tt=>Pe({...lt,h:parseFloat(tt.target.value)}),className:"w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"}),a.jsxs("span",{className:"text-xs text-bambu-gray",children:[Math.round(lt.h*100),"%"]})]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:N("printers.roi.instruction")})]}):a.jsxs("p",{className:"text-xs text-bambu-gray",children:["Current: X=",Math.round((It.roi?.x||.15)*100),"%, Y=",Math.round((It.roi?.y||.35)*100),"%, W=",Math.round((It.roi?.w||.7)*100),"%, H=",Math.round((It.roi?.h||.55)*100),"%"]})]})]}),a.jsx("div",{className:"flex justify-end gap-2 p-4 border-t border-bambu-dark-tertiary",children:It.needs_calibration?a.jsxs(a.Fragment,{children:[a.jsx(De,{variant:"ghost",onClick:()=>yc(),children:N("common.cancel")}),a.jsx(De,{onClick:()=>vn(),disabled:at,children:at?a.jsxs(a.Fragment,{children:[a.jsx(ht,{className:"w-4 h-4 mr-2 animate-spin"}),"Calibrating..."]}):"Calibrate Empty Plate"})]}):a.jsxs(a.Fragment,{children:[a.jsx(De,{variant:"ghost",onClick:()=>vn(),disabled:at,children:at?"Adding...":`Add Reference (${Xi?.references.length||0}/${Xi?.max_references||5})`}),a.jsx(De,{onClick:()=>yc(),children:"Close"})]})})]})}),ne&&Bn&&a.jsx(wn,{title:N("printers.confirm.powerOnTitle"),message:N("printers.confirm.powerOnMessage",{name:t.name}),confirmText:N("printers.confirm.powerOnButton"),variant:"default",onConfirm:()=>{Zc.mutate("on"),pe(!1)},onCancel:()=>pe(!1)}),be&&Bn&&a.jsx(wn,{title:N("printers.confirm.powerOffTitle"),message:Ue?.state==="RUNNING"?N("printers.confirm.powerOffWarning",{name:t.name}):N("printers.confirm.powerOffMessage",{name:t.name}),confirmText:N("printers.confirm.powerOffButton"),variant:"danger",onConfirm:()=>{Zc.mutate("off"),Ce(!1)},onCancel:()=>Ce(!1)}),E&&a.jsx(wn,{title:N("printers.confirm.stopTitle"),message:N("printers.confirm.stopMessage",{name:t.name}),confirmText:N("printers.confirm.stopButton"),variant:"danger",onConfirm:()=>{Bs.mutate(),j(!1)},onCancel:()=>j(!1)}),O&&a.jsx(wn,{title:N("printers.confirm.pauseTitle"),message:N("printers.confirm.pauseMessage",{name:t.name}),confirmText:N("printers.confirm.pauseButton"),variant:"default",onConfirm:()=>{Em.mutate(),K(!1)},onCancel:()=>K(!1)}),de&&a.jsx(wn,{title:N("printers.confirm.resumeTitle"),message:N("printers.confirm.resumeMessage",{name:t.name}),confirmText:N("printers.confirm.resumeButton"),variant:"default",onConfirm:()=>{Hs.mutate(),U(!1)},onCancel:()=>U(!1)}),ge&&a.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/70 p-4",children:a.jsxs("div",{className:"bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl w-full max-w-sm p-5",children:[a.jsxs("div",{className:"flex items-start gap-3 mb-4",children:[a.jsx(Dn,{className:"w-5 h-5 text-yellow-400 flex-shrink-0 mt-0.5"}),a.jsxs("div",{children:[a.jsx("h3",{className:"text-sm font-semibold text-white mb-1",children:N("printers.bedJog.notHomedTitle")}),a.jsx("p",{className:"text-xs text-bambu-gray leading-relaxed",children:N("printers.bedJog.notHomedMessage")})]})]}),a.jsxs("div",{className:"flex flex-col gap-2",children:[a.jsx("button",{onClick:()=>{td.mutate("z"),fe(null)},className:"w-full px-3 py-2 rounded-lg text-xs font-medium bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30 transition-colors",children:N("printers.bedJog.homeZ")}),a.jsx("button",{onClick:()=>{const tt=ge.distance;try{sessionStorage.setItem(`bambuddy.bedJog.warned.${t.id}`,"1")}catch{}mo.mutate({distance:tt,force:!0}),fe(null)},className:"w-full px-3 py-2 rounded-lg text-xs font-medium bg-yellow-500/20 text-yellow-400 hover:bg-yellow-500/30 transition-colors",children:N("printers.bedJog.moveAnyway")}),a.jsx("button",{onClick:()=>fe(null),className:"w-full px-3 py-2 rounded-lg text-xs font-medium bg-bambu-dark text-bambu-gray hover:bg-bambu-dark-tertiary transition-colors",children:N("common.cancel")})]})]})}),a.jsx(mI,{printerId:t.id,isOpen:R,onClose:()=>re(!1)}),$&&a.jsx(qye,{printerName:t.name,errors:Ue?.hms_errors||[],onClose:()=>Y(!1),printerId:t.id,hasPermission:k}),Yt&&a.jsx(r7e,{isOpen:!!Yt,onClose:()=>rn(null),printerId:t.id,printerName:t.name,amsId:Yt.amsId,amsLabel:Yt.amsLabel,initialMode:Yt.mode,thresholds:s}),Vt&&a.jsx(qae,{isOpen:!!Vt,onClose:()=>Jt(null),tagUid:Vt.tagUid,trayUuid:Vt.trayUuid,printerId:Vt.printerId,amsId:Vt.amsId,trayId:Vt.trayId}),We&&a.jsx($ae,{isOpen:!!We,onClose:()=>Ft(null),printerId:We.printerId,amsId:We.amsId,trayId:We.trayId,trayInfo:We.trayInfo}),Qt&&a.jsx(Vae,{isOpen:!!Qt,onClose:()=>Nt(null),printerId:t.id,slotInfo:Qt,printerModel:A0(t.model)||void 0,onSuccess:()=>{A.invalidateQueries({queryKey:["slotPresets",t.id]}),A.invalidateQueries({queryKey:["printerStatus",t.id]})}}),ie&&a.jsx(I7e,{printer:t,onClose:()=>J(!1)}),bt&&Je&&a.jsx(O7e,{printer:t,firmwareInfo:Je,onClose:()=>Wt(!1)}),go&&a.jsx("div",{className:"fixed inset-0 z-40",onClick:()=>tu(null)}),Me!==null&&ve&&(()=>{const tt=Re==="n3s"?85:65,Tt=35,Kt=tt+10;return a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"fixed inset-0 z-[100]",onClick:()=>Fe(null)}),a.jsxs("div",{className:"fixed z-[101] w-[240px] bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl overflow-hidden",style:{top:ve.top,left:ve.left},onClick:it=>it.stopPropagation(),children:[a.jsxs("div",{className:"flex items-center gap-2 px-3 py-2.5 border-b border-bambu-dark-tertiary",children:[a.jsx(Lu,{className:"w-3.5 h-3.5 text-amber-400"}),a.jsx("span",{className:"text-xs text-white font-medium",children:N("printers.drying.start")})]}),a.jsxs("div",{className:"px-3 py-2.5 space-y-2.5",children:[a.jsxs("div",{children:[a.jsx("label",{className:"text-[10px] text-bambu-gray mb-1 block",children:N("printers.filaments")}),a.jsx("select",{value:Ye,onChange:it=>{const nn=it.target.value;nt(nn);const gr=b[nn];gr&&(ze(gr[Re==="n3s"?"n3s":"n3f"]),Ve(Re==="n3s"?gr.n3s_hours:gr.n3f_hours))},className:"w-full px-2 py-1.5 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-xs focus:outline-none focus:border-amber-500/50",children:Object.keys(b).map(it=>a.jsx("option",{value:it,children:it},it))})]}),a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center justify-between mb-1",children:[a.jsx("label",{className:"text-[10px] text-bambu-gray",children:N("printers.drying.temperature")}),a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx("input",{type:"number",min:45,max:tt,value:ae,onChange:it=>ze(Math.min(tt,Math.max(45,Number(it.target.value)||45))),className:"w-12 px-1 py-0.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-[11px] text-center focus:outline-none focus:border-amber-500/50 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"}),a.jsx("span",{className:"text-[10px] text-bambu-gray",children:"°C"})]})]}),a.jsx("input",{type:"range",min:Tt,max:Kt,value:ae,onChange:it=>ze(Math.min(tt,Math.max(45,Number(it.target.value)))),className:"w-full h-1 accent-amber-500 cursor-pointer"}),a.jsxs("div",{className:"flex justify-between text-[9px] text-bambu-gray/50 mt-0.5",children:[a.jsx("span",{children:"45°C"}),a.jsxs("span",{children:[tt,"°C"]})]})]}),a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center justify-between mb-1",children:[a.jsx("label",{className:"text-[10px] text-bambu-gray",children:N("printers.drying.duration")}),a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx("input",{type:"number",min:1,max:24,value:we,onChange:it=>Ve(Math.min(24,Math.max(1,Number(it.target.value)||1))),className:"w-10 px-1 py-0.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-[11px] text-center focus:outline-none focus:border-amber-500/50 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"}),a.jsx("span",{className:"text-[10px] text-bambu-gray",children:N("printers.drying.hours")})]})]}),a.jsx("input",{type:"range",min:1,max:24,value:we,onChange:it=>Ve(Number(it.target.value)),className:"w-full h-1 accent-amber-500 cursor-pointer"}),a.jsxs("div",{className:"flex justify-between text-[9px] text-bambu-gray/50 mt-0.5",children:[a.jsx("span",{children:"1h"}),a.jsx("span",{children:"24h"})]})]}),a.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:je,onChange:it=>ue(it.target.checked),className:"w-3.5 h-3.5 accent-amber-500 rounded cursor-pointer"}),a.jsx("span",{className:"text-[11px] text-bambu-gray",children:N("printers.drying.rotateTray")})]})]}),a.jsx("div",{className:"px-3 pb-3",children:a.jsx("button",{onClick:()=>{Me!==null&&xl.mutate({amsId:Me,temp:ae,duration:we,filament:Ye,rotateTray:je})},disabled:xl.isPending,className:"w-full py-1.5 bg-amber-500 hover:bg-amber-400 text-white text-xs font-medium rounded-lg transition-colors disabled:opacity-50",children:xl.isPending?N("printers.drying.startingDrying"):N("printers.drying.start")})})]})]})})()]})}function L7e({onClose:t,onAdd:e,existingSerials:n}){const{t:r}=Rt(),[i,s]=w.useState({name:"",serial_number:"",ip_address:"",access_code:"",model:"",location:"",auto_archive:!0}),[o,l]=w.useState(!1),[c,d]=w.useState([]),[u,m]=w.useState(""),[p,f]=w.useState(!1),[x,v]=w.useState(!1),[b,g]=w.useState([]),[_,C]=w.useState(""),[P,N]=w.useState({scanned:0,total:0});w.useEffect(()=>{dd.getInfo().then(k=>{v(k.is_docker),k.subnets.length>0&&(g(k.subnets),C(k.subnets[0]))}).catch(()=>{})},[]);const A=c.filter(k=>!n.includes(k.serial)),T=async()=>{m(""),d([]),l(!0),f(!1),N({scanned:0,total:0});try{if(x){await dd.startSubnetScan(_);const k=setInterval(async()=>{try{const D=await dd.getScanStatus();N({scanned:D.scanned,total:D.total});const H=await dd.getDiscoveredPrinters();d(H),D.running||(clearInterval(k),l(!1),f(!0))}catch(D){console.error("Failed to get scan status:",D)}},500)}else{await dd.startDiscovery(10);const k=setInterval(async()=>{try{const D=await dd.getDiscoveredPrinters();d(D)}catch(D){console.error("Failed to get discovered printers:",D)}},1e3);setTimeout(async()=>{clearInterval(k);try{await dd.stopDiscovery()}catch{}l(!1),f(!0);try{const D=await dd.getDiscoveredPrinters();d(D)}catch(D){console.error("Failed to get final discovered printers:",D)}},1e4)}}catch(k){console.error("Failed to start discovery:",k),m(k instanceof Error?k.message:r("printers.discovery.failedToStart")),l(!1),f(!0)}},F=k=>{const D=k.serial.startsWith("unknown-")?"":k.serial;s({...i,name:k.name||"",serial_number:D,ip_address:k.ip_address,model:A0(k.model)}),d([])};return w.useEffect(()=>()=>{dd.stopDiscovery().catch(()=>{}),dd.stopSubnetScan().catch(()=>{})},[]),w.useEffect(()=>{const k=D=>{D.key==="Escape"&&t()};return window.addEventListener("keydown",k),()=>window.removeEventListener("keydown",k)},[t]),a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-start sm:items-center justify-center z-50 p-4 overflow-y-auto",onClick:t,children:a.jsx(At,{className:"w-full max-w-md my-auto max-h-[calc(100vh-2rem)] overflow-y-auto",onClick:k=>k.stopPropagation(),children:a.jsxs(Mt,{children:[a.jsx("h2",{className:"text-xl font-semibold mb-4",children:r("printers.addPrinter")}),a.jsxs("div",{className:"mb-4 pb-4 border-b border-bambu-dark-tertiary",children:[x&&a.jsxs("div",{className:"mb-3",children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.discovery.subnetToScan")}),b.length>0?a.jsx("select",{className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none text-sm",value:_,onChange:k=>C(k.target.value),disabled:o,children:b.map(k=>a.jsx("option",{value:k,children:k},k))}):a.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none text-sm",value:_,onChange:k=>C(k.target.value),placeholder:"192.168.1.0/24",disabled:o}),a.jsx("p",{className:"mt-1 text-xs text-bambu-gray",children:r("printers.discovery.dockerNote")})]}),a.jsx(De,{type:"button",variant:"secondary",onClick:T,disabled:o,className:"w-full",children:o?a.jsxs(a.Fragment,{children:[a.jsx(ht,{className:"w-4 h-4 animate-spin"}),x&&P.total>0?r("printers.discovery.scanProgress",{scanned:P.scanned,total:P.total}):r("printers.discovery.scanning")]}):a.jsxs(a.Fragment,{children:[a.jsx(Nr,{className:"w-4 h-4"}),r(x?"printers.discovery.scanSubnet":"printers.discovery.discoverNetwork")]})}),u&&a.jsx("div",{className:"mt-2 text-sm text-red-400",children:u}),A.length>0&&a.jsx("div",{className:"mt-3 space-y-2 max-h-40 overflow-y-auto",children:A.map(k=>a.jsxs("div",{className:"flex items-center justify-between p-2 bg-bambu-dark rounded-lg hover:bg-bambu-dark-secondary cursor-pointer transition-colors",onClick:()=>F(k),children:[a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:"font-medium text-white text-sm truncate",children:k.name||k.serial}),a.jsxs("p",{className:"text-xs text-bambu-gray truncate",children:[A0(k.model)||r("printers.discovery.unknown")," • ",k.ip_address,k.serial.startsWith("unknown-")&&a.jsxs("span",{className:"text-yellow-500",children:[" • ",r("printers.discovery.serialRequired")]})]})]}),a.jsx(In,{className:"w-4 h-4 text-bambu-gray -rotate-90 flex-shrink-0 ml-2"})]},k.serial))}),o&&a.jsx("p",{className:"mt-2 text-sm text-bambu-gray text-center",children:r(x?"printers.discovery.scanningSubnet":"printers.discovery.scanningNetwork")}),p&&!o&&c.length===0&&a.jsx("p",{className:"mt-2 text-sm text-bambu-gray text-center",children:r(x?"printers.discovery.noPrintersFoundSubnet":"printers.discovery.noPrintersFoundNetwork")}),p&&!o&&c.length>0&&A.length===0&&a.jsx("p",{className:"mt-2 text-sm text-bambu-gray text-center",children:r("printers.discovery.allConfigured")})]}),a.jsxs("form",{onSubmit:k=>{k.preventDefault(),e(i)},className:"space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.name")}),a.jsx("input",{type:"text",required:!0,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:i.name,onChange:k=>s({...i,name:k.target.value}),placeholder:r("printers.modal.myPrinter")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.ipAddress")}),a.jsx("input",{type:"text",required:!0,pattern:"(\\d{1,3}(\\.\\d{1,3}){3}|[a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?(\\.[a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?)*)",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:i.ip_address,onChange:k=>s({...i,ip_address:k.target.value}),placeholder:"192.168.1.100 or printer.local"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.serialNumber")}),a.jsx("input",{type:"text",required:!0,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:i.serial_number,onChange:k=>s({...i,serial_number:k.target.value}),placeholder:"01P00A000000000"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.accessCode")}),a.jsx("input",{type:"password",required:!0,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:i.access_code,onChange:k=>s({...i,access_code:k.target.value}),placeholder:r("printers.modal.fromPrinterSettings")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.modal.modelOptional")}),a.jsxs("select",{className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:i.model||"",onChange:k=>s({...i,model:k.target.value}),children:[a.jsx("option",{value:"",children:r("printers.modal.selectModel")}),a.jsxs("optgroup",{label:"H2 Series",children:[a.jsx("option",{value:"H2C",children:"H2C"}),a.jsx("option",{value:"H2D",children:"H2D"}),a.jsx("option",{value:"H2D Pro",children:"H2D Pro"}),a.jsx("option",{value:"H2S",children:"H2S"})]}),a.jsx("optgroup",{label:"X2 Series",children:a.jsx("option",{value:"X2D",children:"X2D"})}),a.jsxs("optgroup",{label:"X1 Series",children:[a.jsx("option",{value:"X1E",children:"X1E"}),a.jsx("option",{value:"X1C",children:"X1 Carbon"}),a.jsx("option",{value:"X1",children:"X1"})]}),a.jsxs("optgroup",{label:"P Series",children:[a.jsx("option",{value:"P2S",children:"P2S"}),a.jsx("option",{value:"P1S",children:"P1S"}),a.jsx("option",{value:"P1P",children:"P1P"})]}),a.jsxs("optgroup",{label:"A1 Series",children:[a.jsx("option",{value:"A1",children:"A1"}),a.jsx("option",{value:"A1 Mini",children:"A1 Mini"})]})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.modal.locationGroup")}),a.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:i.location||"",onChange:k=>s({...i,location:k.target.value}),placeholder:r("printers.modal.locationPlaceholder")}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:r("printers.locationHelp")})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"checkbox",id:"auto_archive",checked:i.auto_archive,onChange:k=>s({...i,auto_archive:k.target.checked}),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),a.jsx("label",{htmlFor:"auto_archive",className:"text-sm text-bambu-gray",children:r("printers.modal.autoArchiveLabel")})]}),a.jsxs("div",{className:"flex gap-3 pt-4",children:[a.jsx(De,{type:"button",variant:"secondary",onClick:t,className:"flex-1",children:r("common.cancel")}),a.jsx(De,{type:"submit",className:"flex-1",children:r("printers.addPrinter")})]})]})]})})})}function O7e({printer:t,firmwareInfo:e,onClose:n}){const{t:r}=Rt(),i=on(),{showToast:s}=fn(),{hasPermission:o}=Sr(),l=o("firmware:update"),[c,d]=w.useState(null),[u,m]=w.useState(!1),[p,f]=w.useState(null),[x,v]=w.useState(e.update_available?e.latest_version:null),{data:b,isLoading:g}=Qe({queryKey:["firmwarePrepare",t.id,x],queryFn:()=>Dk.prepareUpload(t.id,x??void 0),staleTime:3e4,enabled:!!x&&l&&!u}),_=st({mutationFn:()=>Dk.startUpload(t.id,x??void 0),onSuccess:()=>{m(!0);const P=setInterval(async()=>{try{const N=await Dk.getUploadStatus(t.id);d(N),(N.status==="complete"||N.status==="error")&&(clearInterval(P),f(null),m(!1),N.status==="complete"&&(s(r("printers.firmwareModal.uploadedToast"),"success"),i.invalidateQueries({queryKey:["firmwareUpdate",t.id]})))}catch{}},2e3);f(P)},onError:P=>{s(r("printers.firmwareModal.uploadFailed",{error:P.message}),"error"),m(!1)}});w.useEffect(()=>()=>{p&&clearInterval(p)},[p]);const C=()=>{d(null),_.mutate()};return a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",children:a.jsx(At,{className:"w-full max-w-md mx-4",children:a.jsxs(Mt,{children:[a.jsxs("div",{className:"flex items-start gap-3 mb-4",children:[a.jsx("div",{className:`p-2 rounded-full ${e.update_available?"bg-orange-500/20":"bg-status-ok/20"}`,children:e.update_available?a.jsx(ha,{className:"w-5 h-5 text-orange-400"}):a.jsx(yr,{className:"w-5 h-5 text-status-ok"})}),a.jsxs("div",{className:"flex-1",children:[a.jsx("h3",{className:"text-lg font-semibold text-white",children:e.update_available?r("printers.firmwareModal.title"):r("printers.firmwareModal.titleUpToDate")}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:t.name})]})]}),(()=>{const P=x?e.available_versions?.find(F=>F.version===x):null,N=x??e.latest_version,A=P?.release_notes??e.release_notes,T=!!N&&N!==e.current_version;return a.jsxs("div",{className:"bg-bambu-dark rounded-lg p-3 mb-4",children:[a.jsxs("div",{className:"flex justify-between items-center text-sm",children:[a.jsx("span",{className:"text-bambu-gray",children:r("printers.firmwareModal.currentVersion")}),a.jsx("span",{className:`font-mono ${T?"text-white":"text-status-ok"}`,children:e.current_version||r("common.unknown")})]}),T&&a.jsxs("div",{className:"flex justify-between items-center text-sm mt-1",children:[a.jsx("span",{className:"text-bambu-gray",children:r("printers.firmwareModal.latestVersion")}),a.jsx("span",{className:"text-orange-400 font-mono",children:N})]}),A&&a.jsxs("details",{className:"mt-3 text-sm",open:!T,children:[a.jsx("summary",{className:`cursor-pointer hover:underline ${T?"text-orange-400":"text-status-ok"}`,children:r("printers.firmwareModal.releaseNotes")}),a.jsx("div",{className:"mt-2 text-bambu-gray text-xs max-h-40 overflow-y-auto whitespace-pre-wrap",children:A})]},N??"none")]})})(),e.available_versions&&e.available_versions.length>0&&!u&&c?.status!=="complete"&&a.jsxs("div",{className:"mb-4",children:[a.jsx("div",{className:"text-xs text-bambu-gray mb-2",children:r("printers.firmwareModal.availableVersions")}),a.jsx("div",{className:"max-h-56 overflow-y-auto border border-bambu-dark-tertiary rounded-lg divide-y divide-bambu-dark-tertiary",children:e.available_versions.map(P=>{const N=e.current_version===P.version,A=x===P.version,T=e.current_version?Uye(P.version,e.current_version):0,F=N?r("printers.firmwareModal.currentBadge"):T>0?r("printers.firmwareModal.newerBadge"):r("printers.firmwareModal.olderBadge"),k=N?"text-bambu-gray":T>0?"text-orange-400":"text-blue-400";return a.jsxs("button",{type:"button",disabled:!P.file_available||!l||N,onClick:()=>v(P.version),className:`w-full text-left px-3 py-2 text-sm flex items-center justify-between gap-2 transition-colors ${A?"bg-orange-500/10":"hover:bg-bambu-dark"} ${!P.file_available||!l||N?"opacity-60 cursor-not-allowed":"cursor-pointer"}`,children:[a.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[a.jsx("span",{className:"font-mono text-white",children:P.version}),a.jsx("span",{className:`text-xs ${k}`,children:F})]}),a.jsx("span",{className:`text-xs px-2 py-0.5 rounded-full ${N?"bg-blue-500/15 text-blue-400 border border-blue-500/30":P.file_available?"bg-bambu-green/15 text-bambu-green border border-bambu-green/30":"bg-bambu-gray/10 text-bambu-gray border border-bambu-gray/30"}`,children:N?r("printers.firmwareModal.installed"):P.file_available?r("printers.firmwareModal.usable"):r("printers.firmwareModal.unavailable")})]},P.version)})})]}),x?g?a.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray text-sm mb-4",children:[a.jsx(ht,{className:"w-4 h-4 animate-spin"}),r("printers.firmwareModal.checkingPrereqs")]}):b&&!u&&!c?a.jsx("div",{className:"mb-4",children:b.can_proceed?a.jsxs("div",{className:"flex items-center gap-2 text-bambu-green text-sm",children:[a.jsx(hi,{className:"w-4 h-4"}),r("printers.firmwareModal.sdCardReady")]}):a.jsx("div",{className:"space-y-1",children:b.errors.map((P,N)=>a.jsxs("div",{className:"flex items-center gap-2 text-red-400 text-sm",children:[a.jsx(Ka,{className:"w-4 h-4 flex-shrink-0"}),P]},N))})}):null:null,(u||c)&&c&&a.jsxs("div",{className:"mb-4",children:[a.jsxs("div",{className:"flex items-center justify-between text-sm mb-1",children:[a.jsx("span",{className:"text-bambu-gray capitalize",children:c.status}),a.jsxs("span",{className:"text-white",children:[c.progress,"%"]})]}),a.jsx("div",{className:"w-full bg-bambu-dark-tertiary rounded-full h-2",children:a.jsx("div",{className:`h-2 rounded-full transition-all ${c.status==="error"?"bg-status-error":c.status==="complete"?"bg-status-ok":"bg-orange-500"} ${c.status==="uploading"?"animate-pulse":""}`,style:{width:`${c.progress}%`}})}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:c.message}),c.error&&a.jsx("p",{className:"text-xs text-red-400 mt-1",children:c.error})]}),c?.status==="complete"&&a.jsxs("div",{className:"bg-bambu-green/10 border border-bambu-green/30 rounded-lg p-3 mb-4",children:[a.jsx("p",{className:"text-sm text-bambu-green font-medium mb-2",children:r("printers.firmwareModal.uploadedSuccess")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:r("printers.firmwareModal.applyInstructions")}),a.jsxs("ol",{className:"text-xs text-bambu-gray mt-1 list-decimal list-inside space-y-1",children:[a.jsx("li",{dangerouslySetInnerHTML:{__html:r("printers.firmwareModal.step1")}}),a.jsx("li",{dangerouslySetInnerHTML:{__html:r("printers.firmwareModal.step2")}}),a.jsx("li",{dangerouslySetInnerHTML:{__html:r("printers.firmwareModal.step3")}}),a.jsx("li",{children:r("printers.firmwareModal.step4")})]})]}),a.jsxs("div",{className:"flex gap-2 justify-end",children:[a.jsx(De,{variant:"secondary",onClick:n,children:c?.status==="complete"?r("printers.firmwareModal.done"):r("common.cancel")}),b?.can_proceed&&!u&&c?.status!=="complete"&&l&&a.jsx(De,{onClick:C,disabled:_.isPending,children:_.isPending?a.jsxs(a.Fragment,{children:[a.jsx(ht,{className:"w-4 h-4 animate-spin mr-2"}),r("printers.firmwareModal.starting")]}):a.jsxs(a.Fragment,{children:[a.jsx(ha,{className:"w-4 h-4 mr-2"}),r("printers.firmwareModal.uploadFirmware")]})})]})]})})})}function I7e({printer:t,onClose:e}){const{t:n}=Rt(),r=on(),{showToast:i}=fn(),[s,o]=w.useState({name:t.name,ip_address:t.ip_address,access_code:"",model:t.model||"",location:t.location||"",auto_archive:t.auto_archive}),l=st({mutationFn:d=>he.updatePrinter(t.id,d),onSuccess:()=>{r.invalidateQueries({queryKey:["printers"]}),r.invalidateQueries({queryKey:["printerStatus",t.id]}),e()},onError:d=>i(d.message||n("printers.toast.failedToUpdate"),"error")});w.useEffect(()=>{const d=u=>{u.key==="Escape"&&e()};return window.addEventListener("keydown",d),()=>window.removeEventListener("keydown",d)},[e]);const c=d=>{d.preventDefault();const u={name:s.name,ip_address:s.ip_address,model:s.model||void 0,location:s.location||void 0,auto_archive:s.auto_archive};s.access_code&&(u.access_code=s.access_code),l.mutate(u)};return a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-start sm:items-center justify-center z-50 p-4 overflow-y-auto",onClick:e,children:a.jsx(At,{className:"w-full max-w-md my-auto max-h-[calc(100vh-2rem)] overflow-y-auto",onClick:d=>d.stopPropagation(),children:a.jsxs(Mt,{children:[a.jsx("h2",{className:"text-xl font-semibold mb-4",children:n("printers.editPrinter")}),a.jsxs("form",{onSubmit:c,className:"space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.name")}),a.jsx("input",{type:"text",required:!0,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:s.name,onChange:d=>o({...s,name:d.target.value}),placeholder:n("printers.modal.myPrinter")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.ipAddress")}),a.jsx("input",{type:"text",required:!0,pattern:"(\\d{1,3}(\\.\\d{1,3}){3}|[a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?(\\.[a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?)*)",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:s.ip_address,onChange:d=>o({...s,ip_address:d.target.value}),placeholder:"192.168.1.100 or printer.local"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.serialNumber")}),a.jsx("input",{type:"text",disabled:!0,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray cursor-not-allowed",value:t.serial_number}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:n("printers.serialCannotBeChanged")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.accessCode")}),a.jsx("input",{type:"password",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:s.access_code,onChange:d=>o({...s,access_code:d.target.value}),placeholder:n("printers.accessCodePlaceholder")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.model")}),a.jsxs("select",{className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:s.model,onChange:d=>o({...s,model:d.target.value}),children:[a.jsx("option",{value:"",children:n("printers.modal.selectModel")}),a.jsxs("optgroup",{label:"H2 Series",children:[a.jsx("option",{value:"H2C",children:"H2C"}),a.jsx("option",{value:"H2D",children:"H2D"}),a.jsx("option",{value:"H2D Pro",children:"H2D Pro"}),a.jsx("option",{value:"H2S",children:"H2S"})]}),a.jsx("optgroup",{label:"X2 Series",children:a.jsx("option",{value:"X2D",children:"X2D"})}),a.jsxs("optgroup",{label:"X1 Series",children:[a.jsx("option",{value:"X1E",children:"X1E"}),a.jsx("option",{value:"X1C",children:"X1 Carbon"}),a.jsx("option",{value:"X1",children:"X1"})]}),a.jsxs("optgroup",{label:"P Series",children:[a.jsx("option",{value:"P2S",children:"P2S"}),a.jsx("option",{value:"P1S",children:"P1S"}),a.jsx("option",{value:"P1P",children:"P1P"})]}),a.jsxs("optgroup",{label:"A1 Series",children:[a.jsx("option",{value:"A1",children:"A1"}),a.jsx("option",{value:"A1 Mini",children:"A1 Mini"})]})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Location / Group"}),a.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:s.location,onChange:d=>o({...s,location:d.target.value}),placeholder:n("printers.modal.locationPlaceholder")}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:n("printers.locationHelp")})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"checkbox",id:"edit_auto_archive",checked:s.auto_archive,onChange:d=>o({...s,auto_archive:d.target.checked}),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),a.jsx("label",{htmlFor:"edit_auto_archive",className:"text-sm text-bambu-gray",children:n("printers.modal.autoArchiveLabel")})]}),a.jsxs("div",{className:"flex gap-3 pt-4",children:[a.jsx(De,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:n("common.cancel")}),a.jsx(De,{type:"submit",className:"flex-1",disabled:l.isPending,children:l.isPending?n("common.saving"):n("printers.modal.saveChanges")})]})]})]})})})}function z7e(t){const{data:e}=Qe({queryKey:["printerStatus",t],queryFn:()=>he.getPrinterStatus(t),refetchInterval:3e4});return!e?.connected}function U7e({printer:t,plug:e,onPowerOn:n,isPowering:r}){const i=z7e(t.id),{data:s}=Qe({queryKey:["smartPlugStatus",e.id],queryFn:()=>he.getSmartPlugStatus(e.id),refetchInterval:1e4});return i?a.jsxs("div",{className:"flex items-center justify-between px-3 py-2 hover:bg-gray-100 dark:hover:bg-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[a.jsx("span",{className:"text-sm text-gray-900 dark:text-white truncate",children:t.name}),s&&a.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded ${s.state==="ON"?"bg-bambu-green/20 text-bambu-green":"bg-red-500/20 text-red-400"}`,children:s.state||"?"})]}),a.jsxs("button",{onClick:()=>n(e.id),disabled:r||s?.state==="ON",className:`px-2 py-1 text-xs rounded transition-colors flex items-center gap-1 ${s?.state==="ON"?"bg-bambu-green/20 text-bambu-green cursor-default":"bg-bambu-green/20 text-bambu-green hover:bg-bambu-green hover:text-white"}`,children:[a.jsx(Wd,{className:"w-3 h-3"}),r?"...":"On"]})]}):null}function B7e(){const{t}=Rt(),[e,n]=w.useState(!1),[r,i]=w.useState(()=>localStorage.getItem("hideDisconnectedPrinters")==="true"),[s,o]=w.useState(!1),[l,c]=w.useState(null),[d,u]=w.useState(()=>localStorage.getItem("printerSortBy")||"name"),[m,p]=w.useState(()=>localStorage.getItem("printerSortAsc")!=="false"),[f,x]=w.useState(()=>{const je=localStorage.getItem("printerCardSize");return je?parseInt(je,10):2}),v=f===1?"compact":"expanded",[b,g]=w.useState(""),[_,C]=w.useState("all"),[P,N]=w.useState("all"),[A,T]=w.useState(0),[F,k]=w.useState(()=>{try{const je=localStorage.getItem("printerCollapsedSections");return je?JSON.parse(je):{}}catch{return{}}}),D=on(),{showToast:H}=fn(),{hasPermission:z}=Sr(),[X,L]=w.useState(()=>{const je=localStorage.getItem("openEmbeddedCameras");if(je)try{const ue=JSON.parse(je);return new Map(ue.map(ve=>[ve.id,ve]))}catch{return new Map}return new Map});w.useEffect(()=>{const je=Array.from(X.values());je.length>0?localStorage.setItem("openEmbeddedCameras",JSON.stringify(je)):localStorage.removeItem("openEmbeddedCameras")},[X]);const{data:te,isLoading:ie}=Qe({queryKey:["printers"],queryFn:he.getPrinters}),{data:J}=Qe({queryKey:["settings"],queryFn:he.getSettings}),ce=w.useMemo(()=>{if(J?.drying_presets)try{const je=JSON.parse(J.drying_presets);if(typeof je=="object"&&je!==null&&Object.keys(je).length>0)return{...pL,...je}}catch{}return pL},[J?.drying_presets]);w.useEffect(()=>{J?.camera_view_mode==="window"&&X.size>0&&L(new Map)},[J?.camera_view_mode,X.size]);const{data:oe}=Qe({queryKey:["smart-plugs"],queryFn:he.getSmartPlugs}),{data:le}=Qe({queryKey:["maintenanceOverview"],queryFn:he.getMaintenanceOverview,staleTime:60*1e3}),{data:W}=Qe({queryKey:["spoolman-status"],queryFn:he.getSpoolmanStatus,staleTime:60*1e3}),ne=W?.enabled&&W?.connected,{data:pe}=Qe({queryKey:["spoolman-settings"],queryFn:he.getSpoolmanSettings,enabled:!!ne,staleTime:60*1e3}),be=pe?.spoolman_sync_mode,{data:Ce}=Qe({queryKey:["unlinked-spools"],queryFn:he.getUnlinkedSpools,enabled:!!ne,staleTime:30*1e3}),$=Ce&&Ce.length>0,{data:Y}=Qe({queryKey:["linked-spools"],queryFn:he.getLinkedSpools,enabled:!!ne,staleTime:30*1e3}),E=Y?.linked,{data:j}=Qe({queryKey:["spool-assignments"],queryFn:()=>he.getAssignments(),enabled:z("inventory:view_assignments"),staleTime:30*1e3}),O=st({mutationFn:({printerId:je,amsId:ue,trayId:ve})=>he.unassignSpool(je,ue,ve),onSuccess:()=>{D.invalidateQueries({queryKey:["spool-assignments"]})}}),K=(je,ue,ve)=>j?.find(Be=>Be.printer_id===je&&Be.ams_id===Number(ue)&&Be.tray_id===Number(ve)),B=le?.reduce((je,ue)=>(je[ue.printer_id]={due_count:ue.due_count,warning_count:ue.warning_count,total_print_hours:ue.total_print_hours},je),{})||{},me=oe?.reduce((je,ue)=>(ue.printer_id&&(je[ue.printer_id]=ue),je),{})||{},I=st({mutationFn:he.createPrinter,onSuccess:()=>{D.invalidateQueries({queryKey:["printers"]}),D.invalidateQueries({queryKey:["maintenanceOverview"]}),n(!1)},onError:je=>H(je.message||t("printers.toast.failedToAdd"),"error")}),V=st({mutationFn:je=>he.controlSmartPlug(je,"on"),onSuccess:()=>{D.invalidateQueries({queryKey:["smart-plugs"]}),c(null)},onError:()=>{c(null)}}),[Q,G]=w.useState(new Set),[ee,se]=w.useState(!1),[ge,fe]=w.useState(null),[de,U]=w.useState(!1),R=ee||Q.size>0,re=w.useCallback(je=>{G(ue=>{const ve=new Set(ue);return ve.has(je)?ve.delete(je):ve.add(je),ve})},[]),_e=w.useCallback(()=>{G(new Set),se(!1)},[]);w.useEffect(()=>{const je=ue=>{ue.key==="Escape"&&R&&_e()};return window.addEventListener("keydown",je),()=>window.removeEventListener("keydown",je)},[R,_e]);const Se=w.useCallback(async je=>{U(!0);const ve=Array.from(Q).filter(xt=>{const Bt=D.getQueryData(["printerStatus",xt]);if(!Bt?.connected)return!1;switch(je){case"stop":return Bt.state==="RUNNING"||Bt.state==="PAUSE";case"pause":return Bt.state==="RUNNING";case"resume":return Bt.state==="PAUSE";case"clearPlate":return!!Bt.awaiting_plate_clear;case"clearHMS":return Bt.hms_errors&&tm(Bt.hms_errors).length>0;default:return!1}});if(ve.length===0){H(t("printers.bulk.noneApplicable"),"error"),U(!1),fe(null);return}const Be={stop:he.stopPrint,pause:he.pausePrint,resume:he.resumePrint,clearPlate:he.clearPlate,clearHMS:he.clearHMSErrors}[je],Ze=await Promise.allSettled(ve.map(xt=>Be(xt))),mt=Ze.filter(xt=>xt.status==="fulfilled").length,gt=Ze.filter(xt=>xt.status==="rejected").length;gt===0?H(t("printers.bulk.success",{action:t(`printers.bulk.actions.${je}`),count:mt})):H(t("printers.bulk.partial",{succeeded:mt,failed:gt}),"error"),ve.forEach(xt=>{D.invalidateQueries({queryKey:["printerStatus",xt]})}),U(!1),fe(null)},[Q,D,H,t]),ye=w.useCallback(je=>{je==="stop"||je==="pause"||je==="clearPlate"?fe(je):Se(je)},[Se]),Te=()=>{const je=!r;i(je),localStorage.setItem("hideDisconnectedPrinters",String(je))},xe=je=>{u(je),localStorage.setItem("printerSortBy",je)},Ae=()=>{const je=!m;p(je),localStorage.setItem("printerSortAsc",String(je))},Le=()=>{switch(f){case 1:return"grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5";case 2:return"grid-cols-1 md:grid-cols-2 xl:grid-cols-3";case 3:return"grid-cols-1 lg:grid-cols-2";case 4:return"grid-cols-1";default:return"grid-cols-1 md:grid-cols-2 xl:grid-cols-3"}},Me=["S","M","L","XL"];w.useEffect(()=>D.getQueryCache().subscribe(ue=>{ue.type==="updated"&&Array.isArray(ue.query.queryKey)&&ue.query.queryKey[0]==="printerStatus"&&T(ve=>ve+1)}),[D]);const Fe=w.useMemo(()=>{if(!te)return[];let je=te;if(b.trim()){const ue=b.trim().toLowerCase();je=je.filter(ve=>ve.name.toLowerCase().includes(ue)||(ve.model||"").toLowerCase().includes(ue)||(ve.location||"").toLowerCase().includes(ue)||(ve.serial_number||"").toLowerCase().includes(ue))}return P!=="all"&&(je=je.filter(ue=>(ue.location||"")===P)),_!=="all"&&(je=je.filter(ue=>{const ve=D.getQueryData(["printerStatus",ue.id]);if(!ve?.connected)return _==="offline";const Be=ve.hms_errors?tm(ve.hms_errors):[];switch(_){case"printing":return ve.state==="RUNNING";case"paused":return ve.state==="PAUSE";case"finished":return ve.state==="FINISH";case"error":return ve.state==="FAILED"||Be.length>0;case"idle":return ve.state!=="RUNNING"&&ve.state!=="PAUSE"&&ve.state!=="FINISH"&&ve.state!=="FAILED"&&Be.length===0;case"offline":return!1;default:return!0}})),je},[te,b,_,P,D,A]),Re=w.useMemo(()=>te?[...new Set(te.map(je=>je.location||"").filter(Boolean))].sort():[],[te]),qe=w.useMemo(()=>{const je=[...Fe];switch(d){case"name":je.sort((ue,ve)=>ue.name.localeCompare(ve.name));break;case"model":je.sort((ue,ve)=>(ue.model||"").localeCompare(ve.model||""));break;case"location":je.sort((ue,ve)=>{const Be=ue.location||"",Ze=ve.location||"";return!Be&&Ze?1:Be&&!Ze?-1:Be.localeCompare(Ze)||ue.name.localeCompare(ve.name)});break;case"status":je.sort((ue,ve)=>{const Be=D.getQueryData(["printerStatus",ue.id]),Ze=D.getQueryData(["printerStatus",ve.id]),mt=gt=>gt?.connected?(gt.hms_errors?tm(gt.hms_errors):[]).length>0?0:gt.state==="RUNNING"?1:2:3;return mt(Be)-mt(Ze)});break}return m||je.reverse(),je},[Fe,d,m,D]),Ye=w.useCallback(()=>{G(new Set(qe.map(je=>je.id))),se(!0)},[qe]),nt=w.useCallback(je=>{G(ue=>{const ve=new Set(ue);return qe.forEach(Be=>{const Ze=D.getQueryData(["printerStatus",Be.id]);oK(Ze)===je&&ve.add(Be.id)}),ve}),se(!0)},[qe,D]),ae=w.useCallback(je=>{G(ue=>{const ve=new Set(ue);return qe.filter(Be=>(Be.location||"")===je).forEach(Be=>ve.add(Be.id)),ve}),se(!0)},[qe]),ze=w.useCallback(je=>{G(ue=>{const ve=new Set(ue);return qe.filter(Be=>(Be.model||"Unknown")===je).forEach(Be=>ve.add(Be.id)),ve}),se(!0)},[qe]),we=w.useCallback(je=>{k(ue=>{const ve={...ue,[je]:!ue[je]};try{localStorage.setItem("printerCollapsedSections",JSON.stringify(ve))}catch{}return ve})},[]),Ve=w.useMemo(()=>{if(d==="name")return null;const je={};return d==="location"?qe.forEach(ue=>{const ve=ue.location||"Ungrouped";je[ve]||(je[ve]=[]),je[ve].push(ue)}):d==="model"?qe.forEach(ue=>{const ve=ue.model||"Unknown";je[ve]||(je[ve]=[]),je[ve].push(ue)}):d==="status"&&qe.forEach(ue=>{const ve=D.getQueryData(["printerStatus",ue.id]),Be=oK(ve);je[Be]||(je[Be]=[]),je[Be].push(ue)}),je},[d,qe,D,A]);return a.jsxs("div",{className:"p-4 md:p-8",children:[a.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-6",children:[a.jsxs("div",{children:[a.jsx("h1",{className:"text-2xl font-bold text-white",children:t("printers.title")}),a.jsx(F7e,{printers:te}),te&&te.length>0&&a.jsxs("div",{className:"relative w-full sm:max-w-sm mt-3",children:[a.jsx(Nr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50"}),a.jsx("input",{type:"text",value:b,onChange:je=>g(je.target.value),placeholder:t("printers.search"),"aria-label":t("printers.search"),className:"w-full pl-10 pr-8 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green"}),b&&a.jsx("button",{type:"button","aria-label":t("common.clear"),onClick:()=>g(""),className:"absolute right-3 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white",children:a.jsx(Ht,{className:"w-4 h-4"})})]})]}),a.jsxs("div",{className:"flex items-center gap-2 sm:gap-3 flex-wrap",children:[a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsxs("select",{value:d,onChange:je=>xe(je.target.value),className:"text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg px-2 py-1.5 text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"name",children:t("printers.sort.name")}),a.jsx("option",{value:"status",children:t("printers.sort.status")}),a.jsx("option",{value:"model",children:t("printers.sort.model")}),a.jsx("option",{value:"location",children:t("printers.sort.location")})]}),a.jsx("button",{onClick:Ae,className:"p-1.5 rounded-lg hover:bg-bambu-dark-tertiary transition-colors",title:t(m?"printers.sort.descending":"printers.sort.ascending"),children:m?a.jsx(lp,{className:"w-4 h-4 text-bambu-gray"}):a.jsx(Zf,{className:"w-4 h-4 text-bambu-gray"})})]}),te&&te.length>0&&a.jsxs("select",{value:_,onChange:je=>C(je.target.value),className:"text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg px-2 py-1.5 text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"all",children:t("printers.filter.allStatuses")}),a.jsx("option",{value:"printing",children:t("printers.status.printing")}),a.jsx("option",{value:"paused",children:t("printers.status.paused")}),a.jsx("option",{value:"idle",children:t("printers.status.idle")}),a.jsx("option",{value:"finished",children:t("printers.status.finished")}),a.jsx("option",{value:"error",children:t("printers.status.error")}),a.jsx("option",{value:"offline",children:t("printers.status.offline")})]}),te&&te.length>0&&Re.length>0&&a.jsxs("select",{value:P,onChange:je=>N(je.target.value),className:"text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg px-2 py-1.5 text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"all",children:t("printers.filter.allLocations")}),Re.map(je=>a.jsx("option",{value:je,children:je},je))]}),a.jsx("div",{className:"flex items-center bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:Me.map((je,ue)=>{const ve=ue+1,Be=f===ve;return a.jsx("button",{onClick:()=>{x(ve),localStorage.setItem("printerCardSize",String(ve))},className:`px-2 py-1.5 text-xs font-medium transition-colors ${ue===0?"rounded-l-lg":""} ${ue===Me.length-1?"rounded-r-lg":""} ${Be?"bg-bambu-green text-white":"text-bambu-gray hover:bg-bambu-dark-tertiary hover:text-white"}`,title:t(je==="S"?"printers.cardSize.small":je==="M"?"printers.cardSize.medium":je==="L"?"printers.cardSize.large":"printers.cardSize.extraLarge"),children:je},je)})}),a.jsx("button",{onClick:()=>{R?_e():se(!0)},className:`p-1.5 rounded-lg transition-colors ${R?"bg-bambu-green text-white":"hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white"}`,title:t("printers.bulk.select"),disabled:!z("printers:control"),children:a.jsx(ys,{className:"w-4 h-4"})}),a.jsx("div",{className:"w-px h-6 bg-bambu-dark-tertiary"}),a.jsxs("label",{className:"flex items-center gap-2 text-sm text-bambu-gray cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:r,onChange:Te,className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),t("printers.hideOffline")]}),r&&Object.keys(me).length>0&&a.jsxs("div",{className:"relative",children:[a.jsxs("button",{onClick:()=>o(!s),className:"flex items-center gap-1.5 px-3 py-1.5 text-sm bg-white dark:bg-bambu-dark-secondary border border-gray-200 dark:border-bambu-dark-tertiary rounded-lg text-gray-600 dark:text-bambu-gray hover:text-gray-900 dark:hover:text-white hover:border-bambu-green transition-colors",children:[a.jsx(Wd,{className:"w-4 h-4"}),t("printers.powerOn"),a.jsx(In,{className:`w-3 h-3 transition-transform ${s?"rotate-180":""}`})]}),s&&a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>o(!1)}),a.jsxs("div",{className:"absolute right-0 mt-2 w-56 bg-white dark:bg-bambu-dark-secondary border border-gray-200 dark:border-bambu-dark-tertiary rounded-lg shadow-lg z-20 py-1",children:[a.jsx("div",{className:"px-3 py-2 text-xs text-gray-500 dark:text-bambu-gray border-b border-gray-200 dark:border-bambu-dark-tertiary",children:t("printers.offlinePrintersWithPlugs")}),te?.filter(je=>me[je.id]).map(je=>a.jsx(U7e,{printer:je,plug:me[je.id],onPowerOn:ue=>{c(ue),V.mutate(ue)},isPowering:l===me[je.id]?.id},je.id)),te?.filter(je=>me[je.id]).length===0&&a.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:"No printers with smart plugs"})]})]})]}),a.jsxs(De,{onClick:()=>n(!0),disabled:!z("printers:create"),title:z("printers:create")?void 0:t("printers.permission.noAdd"),children:[a.jsx(ir,{className:"w-4 h-4"}),t("printers.addPrinter")]})]})]}),ie?a.jsx("div",{className:"text-center py-12 text-bambu-gray",children:t("common.loading")}):te?.length===0?a.jsx(At,{children:a.jsxs(Mt,{className:"text-center py-12",children:[a.jsx("p",{className:"text-bambu-gray mb-4",children:t("printers.noPrintersConfigured")}),a.jsxs(De,{onClick:()=>n(!0),disabled:!z("printers:create"),title:z("printers:create")?void 0:t("printers.permission.noAdd"),children:[a.jsx(ir,{className:"w-4 h-4"}),t("printers.addPrinter")]})]})}):qe.length===0&&(b.trim()||_!=="all"||P!=="all")?a.jsx(At,{children:a.jsx(Mt,{className:"text-center py-12",children:a.jsx("p",{className:"text-bambu-gray",children:t("printers.noSearchResults")})})}):Ve?a.jsx("div",{className:"space-y-6",children:(()=>{const je=d==="status"?R7e.filter(ue=>Ve[ue]?.length>0):Object.keys(Ve);return m?je:[...je].reverse()})().map(je=>{const ue=Ve[je],ve=`${d}:${je}`,Be=!F[ve],Ze=d==="status"&&sK[je]?.dot||"bg-bambu-green",mt=d==="status"?t(sK[je]?.labelKey||je):je;return a.jsx(fz,{open:Be,onToggle:()=>we(ve),summaryClassName:"py-1",summary:a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx("span",{className:`w-2 h-2 rounded-full ${Ze}`}),mt,a.jsxs("span",{className:"text-sm font-normal text-bambu-gray",children:["(",ue.length,")"]}),R&&a.jsx("button",{onClick:gt=>{gt.stopPropagation(),d==="location"?ae(je==="Ungrouped"?"":je):d==="status"?nt(je):d==="model"&&ze(je)},className:"text-xs text-bambu-green hover:text-bambu-green-light transition-colors ml-1",children:t("printers.bulk.selectAll")})]}),children:a.jsx("div",{className:`grid gap-4 ${f>=3?"gap-6":""} ${Le()}`,children:ue.map(gt=>a.jsx(cK,{printer:gt,hideIfDisconnected:r,maintenanceInfo:B[gt.id],viewMode:v,cardSize:f,amsThresholds:J?{humidityGood:Number(J.ams_humidity_good)||40,humidityFair:Number(J.ams_humidity_fair)||60,tempGood:Number(J.ams_temp_good)||28,tempFair:Number(J.ams_temp_fair)||35}:void 0,spoolmanEnabled:ne,hasUnlinkedSpools:$,linkedSpools:E,spoolmanUrl:W?.url,spoolmanSyncMode:be,onGetAssignment:K,onUnassignSpool:(xt,Bt,Yt)=>O.mutate({printerId:xt,amsId:Bt,trayId:Yt}),timeFormat:J?.time_format||"system",cameraViewMode:J?.camera_view_mode||"window",onOpenEmbeddedCamera:(xt,Bt)=>L(Yt=>new Map(Yt).set(xt,{id:xt,name:Bt})),checkPrinterFirmware:J?.check_printer_firmware!==!1,dryingPresets:ce,requirePlateClear:J?.require_plate_clear===!0,selectionMode:R,isSelected:Q.has(gt.id),onToggleSelect:re},gt.id))})},je)})}):a.jsx("div",{className:`grid gap-4 ${f>=3?"gap-6":""} ${Le()}`,children:qe.map(je=>a.jsx(cK,{printer:je,hideIfDisconnected:r,maintenanceInfo:B[je.id],viewMode:v,cardSize:f,spoolmanEnabled:ne,hasUnlinkedSpools:$,linkedSpools:E,spoolmanUrl:W?.url,spoolmanSyncMode:be,onGetAssignment:K,onUnassignSpool:(ue,ve,Be)=>O.mutate({printerId:ue,amsId:ve,trayId:Be}),amsThresholds:J?{humidityGood:Number(J.ams_humidity_good)||40,humidityFair:Number(J.ams_humidity_fair)||60,tempGood:Number(J.ams_temp_good)||28,tempFair:Number(J.ams_temp_fair)||35}:void 0,timeFormat:J?.time_format||"system",cameraViewMode:J?.camera_view_mode||"window",onOpenEmbeddedCamera:(ue,ve)=>L(Be=>new Map(Be).set(ue,{id:ue,name:ve})),checkPrinterFirmware:J?.check_printer_firmware!==!1,dryingPresets:ce,requirePlateClear:J?.require_plate_clear===!0,selectionMode:R,isSelected:Q.has(je.id),onToggleSelect:re},je.id))}),e&&a.jsx(L7e,{onClose:()=>n(!1),onAdd:je=>I.mutate(je),existingSerials:te?.map(je=>je.serial_number)||[]}),R&&te&&a.jsx(Vye,{selectedIds:Q,printers:te,onClose:_e,onSelectAll:Ye,onSelectByLocation:ae,onSelectByState:nt,onAction:ye,actionPending:de}),ge==="stop"&&a.jsx(wn,{title:t("printers.bulk.confirm.stopTitle",{count:Q.size}),message:t("printers.bulk.confirm.stopMessage",{count:Q.size}),confirmText:t("printers.bulk.confirm.stopButton"),variant:"danger",isLoading:de,onConfirm:()=>Se("stop"),onCancel:()=>fe(null)}),ge==="pause"&&a.jsx(wn,{title:t("printers.bulk.confirm.pauseTitle",{count:Q.size}),message:t("printers.bulk.confirm.pauseMessage",{count:Q.size}),confirmText:t("printers.bulk.confirm.pauseButton"),isLoading:de,onConfirm:()=>Se("pause"),onCancel:()=>fe(null)}),ge==="clearPlate"&&a.jsx(wn,{title:t("printers.bulk.confirm.clearPlateTitle",{count:Q.size}),message:t("printers.bulk.confirm.clearPlateMessage",{count:Q.size}),confirmText:t("printers.bulk.confirm.clearPlateButton"),isLoading:de,onConfirm:()=>Se("clearPlate"),onCancel:()=>fe(null)}),Array.from(X.values()).map((je,ue)=>a.jsx(GMe,{printerId:je.id,printerName:je.name,viewerIndex:ue,onClose:()=>L(ve=>{const Be=new Map(ve);return Be.delete(je.id),Be})},je.id))]})}function H7e(){const t=navigator.userAgent.toLowerCase(),e=navigator.platform?.toLowerCase()||"";return t.includes("win")||e.includes("win")?"windows":t.includes("mac")||e.includes("mac")?"macos":t.includes("linux")||e.includes("linux")?"linux":"unknown"}function Ef(t,e="bambu_studio"){let n;e==="orcaslicer"?n=`orcaslicer://open?file=${t}`:H7e()==="macos"?n=`bambustudioopen://${encodeURIComponent(t)}`:n=`bambustudio://open?file=${t}`;const r=document.createElement("a");r.href=n,r.style.display="none",document.body.appendChild(r),r.click(),document.body.removeChild(r)}const dK=768;function eie(){const[t,e]=w.useState(()=>typeof window<"u"?window.innerWidth{const n=window.matchMedia(`(max-width: ${dK-1}px)`),r=i=>{e(i.matches)};return e(n.matches),n.addEventListener("change",r),()=>n.removeEventListener("change",r)},[]),t}function gz({archiveId:t,libraryFileId:e,title:n,fileType:r,onClose:i}){const{t:s}=Rt(),{data:o}=Qe({queryKey:["settings"],queryFn:he.getSettings}),l=o?.preferred_slicer||"bambu_studio",c=e!=null,[d,u]=w.useState(null),[m,p]=w.useState(null),[f,x]=w.useState(!0),[v,b]=w.useState(null),[g,_]=w.useState(!1),[C,P]=w.useState(null),[N,A]=w.useState(0),[T,F]=w.useState(!1),[k,D]=w.useState(null),[H,z]=w.useState(!1),[X,L]=w.useState(!1),te=w.useRef(null),ie=w.useRef(null),J=10,ce=160,oe=240,le=.35;w.useEffect(()=>{const fe=de=>{de.key==="Escape"&&i()};return window.addEventListener("keydown",fe),()=>window.removeEventListener("keydown",fe)},[i]),w.useEffect(()=>{if(x(!0),c){const fe=(r||"").toLowerCase(),de=fe==="3mf"||fe==="stl",U=fe==="gcode"||fe==="3mf";p({has_model:de,has_gcode:U,has_source:!1,build_volume:{x:256,y:256,z:256},filament_colors:[]}),u(de?"3d":U?"gcode":null),x(!1);return}if(!t){p(null),u(null),x(!1);return}he.getArchiveCapabilities(t).then(fe=>{p(fe),fe.has_model?u("3d"):fe.has_gcode&&u("gcode"),x(!1)}).catch(()=>{p({has_model:!0,has_gcode:!1,has_source:!1,build_volume:{x:256,y:256,z:256},filament_colors:[]}),u("3d"),x(!1)})},[t,r,c]),w.useEffect(()=>{if(_(!0),P(null),A(0),c){const fe=(r||"").toLowerCase();if(!e||fe!=="3mf"){b(null),_(!1);return}he.getLibraryFilePlates(e).then(de=>b(de)).catch(()=>b(null)).finally(()=>_(!1));return}if(!t){b(null),_(!1);return}he.getArchivePlates(t).then(fe=>b(fe)).catch(()=>b(null)).finally(()=>_(!1))},[t,r,c,e]);const W=w.useMemo(()=>v?.plates??[],[v]),ne=(v?.is_multi_plate??!1)&&W.length>1,pe=T&&ne,be=C==null?null:W.find(fe=>fe.index===C)??null,Ce=fe=>fe.object_count??fe.objects?.length??0,$=W.reduce((fe,de)=>fe+Ce(de),0),Y=be?Ce(be):$,E=be?s("modelViewer.plateNumber",{number:be.index}):s("modelViewer.allPlates"),j=W.length>0,O=w.useRef(null),K=w.useRef(null),[B,me]=w.useState(10),[I,V]=w.useState(3),Q=W.length>B,G=Math.max(1,Math.ceil(W.length/B)),ee=Q?W.slice(N*B,(N+1)*B):W;w.useEffect(()=>{if(!pe){me(10),V(3);return}const fe=O.current,de=K.current;if(!fe||!de)return;let U=0;const R=()=>{const Se=de.clientWidth,Te=Math.floor(Se/210),xe=Math.max(3,Math.min(5,Te||3));V(ae=>ae===xe?ae:xe);const Ae=window.getComputedStyle(fe),Le=Number.parseFloat(Ae.rowGap||"0"),Fe=fe.querySelector("button")?.getBoundingClientRect().height??44,Re=de.clientHeight,Ye=Math.max(1,Math.floor((Re+Le)/(Fe+Le)))*xe,nt=Math.max(1,Ye-1);me(ae=>ae===nt?ae:nt)},re=()=>{U&&cancelAnimationFrame(U),U=requestAnimationFrame(R)};re();const _e=new ResizeObserver(re);return _e.observe(de),_e.observe(fe),()=>{U&&cancelAnimationFrame(U),_e.disconnect()}},[pe,W.length]),w.useEffect(()=>{if(!Q){A(0);return}A(fe=>Math.min(fe,G-1))},[W.length,Q,G]),w.useEffect(()=>{if(!Q||C==null)return;const fe=W.findIndex(U=>U.index===C);if(fe<0)return;const de=Math.floor(fe/B);A(U=>U===de?U:de)},[W,B,C,Q]),w.useEffect(()=>{if(!pe){D(null),L(!1);return}if(X)return;const fe=te.current,de=ie.current;if(!fe||!de)return;const U=fe.clientHeight;if(!U)return;const R=Math.max(oe,U*le),re=Math.max(ce,U-J-R),_e=Math.min(de.scrollHeight,re);D(Math.max(ce,_e))},[pe,X,W.length,N,J,ce,oe,le]),w.useEffect(()=>{if(!H)return;const fe=U=>{const R=te.current;if(!R)return;const re=R.getBoundingClientRect(),_e=re.height;if(!_e)return;const Se=Math.max(oe,_e*le),ye=Math.max(ce,_e-J-Se),Te=Math.min(ye,Math.max(ce,U.clientY-re.top));D(Te)},de=()=>{z(!1),L(!0)};return document.addEventListener("mousemove",fe),document.addEventListener("mouseup",de),document.body.style.cursor="row-resize",document.body.style.userSelect="none",()=>{document.removeEventListener("mousemove",fe),document.removeEventListener("mouseup",de),document.body.style.cursor="",document.body.style.userSelect=""}},[H,J,ce,oe,le]);const se=c?(r||"").toLowerCase()==="3mf":!0,ge=async()=>{if(!se)return;const fe=n||"model";try{if(c){const{token:de}=await he.createLibrarySlicerToken(e),U=he.getLibrarySlicerDownloadUrl(e,de,fe);Ef(`${window.location.origin}${U}`,l)}else{const{token:de}=await he.createArchiveSlicerToken(t),U=he.getArchiveSlicerDownloadUrl(t,de,fe);Ef(`${window.location.origin}${U}`,l)}}catch{if(c){const de=`${window.location.origin}${he.getLibraryFileDownloadUrl(e)}`;Ef(de,l)}else{const de=`${window.location.origin}${he.getArchiveForSlicer(t,fe)}`;Ef(de,l)}}};return a.jsx("div",{className:`fixed inset-0 bg-black/70 flex items-center justify-center z-50 ${T?"p-0":"p-8"}`,onClick:i,children:a.jsxs("div",{className:`bg-bambu-dark-secondary border border-bambu-dark-tertiary w-full flex flex-col ${T?"h-full max-w-none rounded-none":"h-[80vh] max-w-4xl rounded-xl"}`,onClick:fe=>fe.stopPropagation(),children:[a.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-1 mr-4",children:[a.jsx("h2",{className:"text-lg font-semibold text-white truncate",children:n}),j&&a.jsxs("span",{className:"text-xs text-bambu-gray bg-bambu-dark-tertiary/70 px-2 py-1 rounded whitespace-nowrap",children:[E,": ",s("modelViewer.objectCount",{count:Y})]})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs(De,{variant:"secondary",size:"sm",onClick:ge,disabled:!se,children:[a.jsx(oa,{className:"w-4 h-4"}),s("modelViewer.openInSlicer")]}),a.jsx(De,{variant:"secondary",size:"sm",onClick:()=>F(fe=>!fe),title:T?"Exit fullscreen":"Enter fullscreen",children:T?a.jsx(CO,{className:"w-4 h-4"}):a.jsx(zP,{className:"w-4 h-4"})}),a.jsx(De,{variant:"ghost",size:"sm",onClick:i,children:a.jsx(Ht,{className:"w-5 h-5"})})]})]}),m&&a.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary",children:[a.jsxs("button",{onClick:()=>m.has_model&&u("3d"),disabled:!m.has_model,className:`flex items-center gap-2 px-6 py-3 text-sm font-medium transition-colors ${d==="3d"?"text-bambu-green border-b-2 border-bambu-green":m.has_model?"text-bambu-gray hover:text-white":"text-bambu-gray/30 cursor-not-allowed"}`,children:[a.jsx(hi,{className:"w-4 h-4"}),s("modelViewer.tabs.model"),!m.has_model&&a.jsxs("span",{className:"text-xs",children:["(",s("modelViewer.notAvailable"),")"]})]}),a.jsxs("button",{onClick:()=>m.has_gcode&&u("gcode"),disabled:!m.has_gcode,className:`flex items-center gap-2 px-6 py-3 text-sm font-medium transition-colors ${d==="gcode"?"text-bambu-green border-b-2 border-bambu-green":m.has_gcode?"text-bambu-gray hover:text-white":"text-bambu-gray/30 cursor-not-allowed"}`,children:[a.jsx(yfe,{className:"w-4 h-4"}),s("modelViewer.tabs.gcode"),!m.has_gcode&&a.jsxs("span",{className:"text-xs",children:["(",s("modelViewer.notSliced"),")"]})]})]}),a.jsx("div",{className:"flex-1 overflow-hidden p-4",children:f?a.jsx("div",{className:"w-full h-full flex items-center justify-center",children:a.jsx(ht,{className:"w-8 h-8 animate-spin text-bambu-green"})}):d==="3d"&&m?a.jsxs("div",{ref:te,className:`w-full h-full flex flex-col ${pe?"gap-0 min-h-0":"gap-3"}`,children:[ne&&a.jsxs("div",{ref:ie,style:pe&&k!=null?{height:k}:void 0,className:`rounded-lg border border-bambu-dark-tertiary bg-bambu-dark p-3 ${pe?"flex flex-col shrink-0":""}`,children:[a.jsxs("div",{className:"flex items-center gap-2 text-sm text-bambu-gray mb-2",children:[a.jsx(ca,{className:"w-4 h-4"}),s("modelViewer.plates"),g&&a.jsx(ht,{className:"w-3 h-3 animate-spin"})]}),a.jsxs("div",{className:pe?"flex flex-col min-h-0 flex-1":void 0,children:[a.jsx("div",{ref:K,className:pe?"min-h-0 overflow-hidden pr-1 flex-1":void 0,children:a.jsxs("div",{ref:O,className:pe?"grid gap-2":"grid grid-cols-2 md:grid-cols-3 gap-2",style:pe?{gridTemplateColumns:`repeat(${I}, minmax(0, 1fr))`}:void 0,children:[a.jsxs("button",{type:"button",onClick:()=>P(null),className:`flex items-center rounded-lg border text-left transition-colors ${pe?"gap-1.5 p-1.5 w-full":"gap-2 p-2"} ${C==null?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark-secondary hover:border-bambu-gray"}`,children:[a.jsx("div",{className:`rounded bg-bambu-dark-tertiary flex items-center justify-center ${pe?"w-8 h-8":"w-10 h-10"}`,children:a.jsx(ca,{className:`${pe?"w-4 h-4":"w-5 h-5"} text-bambu-gray`})}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:`${pe?"text-xs":"text-sm"} text-white font-medium truncate`,children:s("modelViewer.allPlates")}),a.jsx("p",{className:`${pe?"text-[10px]":"text-xs"} text-bambu-gray truncate`,children:s("modelViewer.plateCount",{count:W.length})})]}),C==null&&a.jsx(Lr,{className:`${pe?"w-3.5 h-3.5":"w-4 h-4"} text-bambu-green flex-shrink-0`})]}),ee.map(fe=>a.jsxs("button",{type:"button",onClick:()=>P(fe.index),className:`flex items-center rounded-lg border text-left transition-colors ${pe?"gap-1.5 p-1.5 w-full":"gap-2 p-2"} ${C===fe.index?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark-secondary hover:border-bambu-gray"}`,children:[fe.has_thumbnail&&fe.thumbnail_url?a.jsx("img",{src:fe.thumbnail_url,alt:`Plate ${fe.index}`,className:`${pe?"w-8 h-8":"w-10 h-10"} rounded object-cover bg-bambu-dark-tertiary`}):a.jsx("div",{className:`rounded bg-bambu-dark-tertiary flex items-center justify-center ${pe?"w-8 h-8":"w-10 h-10"}`,children:a.jsx(ca,{className:`${pe?"w-4 h-4":"w-5 h-5"} text-bambu-gray`})}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:`${pe?"text-xs":"text-sm"} text-white font-medium truncate`,children:fe.name||s("modelViewer.plateNumber",{number:fe.index})}),a.jsx("p",{className:`${pe?"text-[10px]":"text-xs"} text-bambu-gray truncate`,children:s("modelViewer.objectCount",{count:fe.object_count??fe.objects?.length??0})})]}),C===fe.index&&a.jsx(Lr,{className:`${pe?"w-3.5 h-3.5":"w-4 h-4"} text-bambu-green flex-shrink-0`})]},fe.index))]})}),(be||Q)&&a.jsxs("div",{className:"mt-auto pt-3 flex items-center gap-4 text-xs text-bambu-gray overflow-x-auto",children:[be&&a.jsxs("div",{className:"flex items-center gap-3 whitespace-nowrap",children:[a.jsx("span",{children:s("modelViewer.plateNumber",{number:be.index})}),be.print_time_seconds!=null&&a.jsx("span",{children:s("modelViewer.eta",{minutes:Math.round(be.print_time_seconds/60)})}),be.filament_used_grams!=null&&a.jsxs("span",{children:[be.filament_used_grams.toFixed(1)," g"]}),be.filaments.length>0&&a.jsx("span",{children:s("modelViewer.filamentCount",{count:be.filaments.length})})]}),Q&&a.jsxs("div",{className:`flex items-center gap-2 whitespace-nowrap ${be?"ml-auto":""}`,children:[a.jsx("span",{children:s("modelViewer.pagination.pageOf",{current:N+1,total:G})}),a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx("button",{type:"button",onClick:()=>A(fe=>Math.max(fe-1,0)),disabled:N===0,className:`px-2 py-1 rounded border text-xs ${N===0?"border-bambu-dark-tertiary text-bambu-gray/40 cursor-not-allowed":"border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,children:s("modelViewer.pagination.prev")}),(()=>{let de=Math.max(0,N-Math.floor(2.5));const U=Math.min(G,de+5);U-de<5&&(de=Math.max(0,U-5));const R=Array.from({length:U-de},(re,_e)=>de+_e);return a.jsxs(a.Fragment,{children:[de>0&&a.jsx("button",{type:"button",onClick:()=>A(0),className:`px-2 py-1 rounded border text-xs ${N===0?"border-bambu-green text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,children:"1"}),de>1&&a.jsx("span",{className:"px-1",children:"…"}),R.map(re=>a.jsx("button",{type:"button",onClick:()=>A(re),className:`px-2 py-1 rounded border text-xs ${N===re?"border-bambu-green text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,children:re+1},re)),UA(G-1),className:`px-2 py-1 rounded border text-xs ${N===G-1?"border-bambu-green text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,children:G})]})})(),a.jsx("button",{type:"button",onClick:()=>A(fe=>Math.min(fe+1,G-1)),disabled:N>=G-1,className:`px-2 py-1 rounded border text-xs ${N>=G-1?"border-bambu-dark-tertiary text-bambu-gray/40 cursor-not-allowed":"border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,children:s("modelViewer.pagination.next")})]})]})]})]})]}),pe&&a.jsx("div",{role:"separator","aria-orientation":"horizontal",onMouseDown:fe=>{fe.preventDefault(),z(!0),L(!0)},className:`h-2 cursor-row-resize flex items-center justify-center ${H?"bg-bambu-dark-tertiary":"bg-bambu-dark-secondary/60 hover:bg-bambu-dark-tertiary"}`,children:a.jsx("div",{className:"w-12 h-1 rounded-full bg-bambu-gray/50"})}),a.jsx("div",{className:`flex-1 ${pe?"min-h-0":""}`,children:a.jsx($Z,{url:c?he.getLibraryFileDownloadUrl(e):m.has_source?he.getSource3mfDownloadUrl(t):he.getArchiveDownload(t),fileType:r,buildVolume:m.build_volume,filamentColors:m.filament_colors,selectedPlateId:C,className:"w-full h-full"})})]}):d==="gcode"&&m?a.jsx(CJ,{gcodeUrl:c?he.getLibraryFileGcodeUrl(e):he.getArchiveGcode(t),filamentColors:m.filament_colors,className:"w-full h-full"}):a.jsx("div",{className:"w-full h-full flex items-center justify-center text-bambu-gray",children:s("modelViewer.noPreview")})})]})})}function q7e({onClose:t,initialFiles:e}){const{t:n}=Rt(),r=on(),{showToast:i}=fn(),s=w.useRef(null),[o,l]=w.useState(()=>e?.filter(N=>N.name.endsWith(".3mf")).map(N=>({file:N,status:"pending"}))||[]),[c,d]=w.useState(!1),[u,m]=w.useState(null);w.useEffect(()=>{const N=A=>{A.key==="Escape"&&t()};return window.addEventListener("keydown",N),()=>window.removeEventListener("keydown",N)},[t]);const p=st({mutationFn:N=>he.uploadArchivesBulk(N),onSuccess:N=>{m(N),r.invalidateQueries({queryKey:["archives"]}),r.invalidateQueries({queryKey:["archiveStats"]}),l(A=>A.map(T=>{const F=N.results.find(D=>D.filename===T.file.name),k=N.errors.find(D=>D.filename===T.file.name);return F?{...T,status:"success",archiveId:F.id}:k?{...T,status:"error",error:k.error}:T})),N.failed===0?i(`${N.uploaded} file${N.uploaded!==1?"s":""} uploaded`):N.uploaded===0?i(`Failed to upload ${N.failed} file${N.failed!==1?"s":""}`,"error"):i(`${N.uploaded} uploaded, ${N.failed} failed`,"warning")},onError:()=>{l(N=>N.map(A=>({...A,status:"error",error:"Upload failed"}))),i("Upload failed","error")}}),f=w.useCallback(N=>{N.preventDefault(),d(!0)},[]),x=w.useCallback(N=>{N.preventDefault(),d(!1)},[]),v=w.useCallback(N=>{N.preventDefault(),d(!1);const A=Array.from(N.dataTransfer.files).filter(T=>T.name.endsWith(".3mf"));A.length>0&&l(T=>[...T,...A.map(F=>({file:F,status:"pending"}))])},[]),b=w.useCallback(N=>{const A=Array.from(N.target.files||[]).filter(T=>T.name.endsWith(".3mf"));A.length>0&&l(T=>[...T,...A.map(F=>({file:F,status:"pending"}))]),s.current&&(s.current.value="")},[]),g=w.useCallback(N=>{l(A=>A.filter((T,F)=>F!==N))},[]),_=()=>{if(o.length===0)return;const N=o.filter(A=>A.status==="pending");N.length!==0&&(l(A=>A.map(T=>T.status==="pending"?{...T,status:"uploading"}:T)),p.mutate(N.map(A=>A.file)))},C=o.filter(N=>N.status==="pending").length,P=p.isPending;return a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:a.jsx(At,{className:"w-full max-w-2xl max-h-[90vh] flex flex-col",children:a.jsxs(Mt,{className:"p-0 flex flex-col h-full",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsx("h2",{className:"text-xl font-semibold text-white",children:n("uploadModal.title")}),a.jsx("button",{onClick:t,className:"text-bambu-gray hover:text-white transition-colors",children:a.jsx(Ht,{className:"w-5 h-5"})})]}),a.jsx("div",{className:"p-4",children:a.jsxs("div",{className:`border-2 border-dashed rounded-lg p-8 text-center transition-colors ${c?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary hover:border-bambu-gray"}`,onDragOver:f,onDragLeave:x,onDrop:v,children:[a.jsx(Da,{className:"w-12 h-12 mx-auto mb-4 text-bambu-gray"}),a.jsx("p",{className:"text-white mb-2",children:n("uploadModal.dragDrop")}),a.jsx("p",{className:"text-bambu-gray text-sm mb-4",children:n("uploadModal.or")}),a.jsx(De,{variant:"secondary",onClick:()=>s.current?.click(),disabled:P,children:n("uploadModal.browseFiles")}),a.jsx("input",{ref:s,type:"file",accept:".3mf",multiple:!0,className:"hidden",onChange:b})]})}),a.jsx("div",{className:"px-4 pb-4",children:a.jsx("p",{className:"text-xs text-bambu-gray",children:n("uploadModal.extractionInfo")})}),o.length>0&&a.jsx("div",{className:"px-4 pb-4 max-h-60 overflow-y-auto",children:a.jsx("div",{className:"space-y-2",children:o.map((N,A)=>a.jsxs("div",{className:"flex items-center gap-3 p-3 bg-bambu-dark rounded-lg",children:[a.jsx(OP,{className:"w-5 h-5 text-bambu-gray flex-shrink-0"}),a.jsx("span",{className:"flex-1 text-white text-sm truncate",children:N.file.name}),a.jsxs("span",{className:"text-xs text-bambu-gray",children:[(N.file.size/(1024*1024)).toFixed(1)," MB"]}),N.status==="pending"&&a.jsx("button",{onClick:()=>g(A),className:"text-bambu-gray hover:text-red-400 transition-colors",disabled:P,children:a.jsx(Ht,{className:"w-4 h-4"})}),N.status==="uploading"&&a.jsx(ht,{className:"w-4 h-4 text-bambu-green animate-spin"}),N.status==="success"&&a.jsx(yr,{className:"w-4 h-4 text-bambu-green"}),N.status==="error"&&a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-xs text-red-400",children:N.error}),a.jsx(Ka,{className:"w-4 h-4 text-red-400"})]})]},`${N.file.name}-${A}`))})}),u&&a.jsx("div",{className:"px-4 pb-4",children:a.jsx("div",{className:"p-3 bg-bambu-dark rounded-lg",children:a.jsxs("p",{className:"text-sm text-white",children:[a.jsx("span",{className:"text-bambu-green",children:u.uploaded})," ",n("uploadModal.uploaded"),u.failed>0&&a.jsxs(a.Fragment,{children:[", ",a.jsx("span",{className:"text-red-400",children:u.failed})," ",n("uploadModal.failed")]})]})})}),a.jsxs("div",{className:"flex gap-3 p-4 border-t border-bambu-dark-tertiary",children:[a.jsx(De,{variant:"secondary",onClick:t,className:"flex-1",children:n(u?"common.close":"common.cancel")}),!u&&a.jsx(De,{onClick:_,disabled:C===0||P,className:"flex-1",children:P?a.jsxs(a.Fragment,{children:[a.jsx(ht,{className:"w-4 h-4 animate-spin"}),n("uploadModal.uploading")]}):a.jsxs(a.Fragment,{children:[a.jsx(Da,{className:"w-4 h-4"}),n("uploadModal.upload")," ",C>0&&`(${C})`]})})]})]})})})}const $7e=["adhesionFailure","spaghettiDetached","layerShift","cloggedNozzle","filamentRunout","warping","stringing","underExtrusion","powerFailure","userCancelled","other"],V7e=["completed","failed","aborted","printing"];function tie({archive:t,onClose:e,existingTags:n=[]}){const{t:r}=Rt();w.useEffect(()=>{const j=O=>{O.key==="Escape"&&e()};return window.addEventListener("keydown",j),()=>window.removeEventListener("keydown",j)},[e]);const i=on(),[s,o]=w.useState(t.print_name||""),[l,c]=w.useState(t.printer_id),[d,u]=w.useState(t.project_id??null),[m,p]=w.useState(t.notes||""),[f,x]=w.useState(t.tags||""),[v,b]=w.useState(t.failure_reason||""),[g,_]=w.useState(t.status),[C,P]=w.useState(t.quantity??1),[N,A]=w.useState(t.photos||[]),[T,F]=w.useState(t.external_url||""),[k,D]=w.useState(!1),[H,z]=w.useState(!1),X=w.useRef(null),L=w.useRef(null),te=w.useRef(null),{data:ie}=Qe({queryKey:["printers"],queryFn:he.getPrinters}),{data:J}=Qe({queryKey:["projects"],queryFn:()=>he.getProjects()}),{data:ce}=Qe({queryKey:["tags"],queryFn:he.getTags,enabled:n.length===0}),oe=n.length>0?n:ce?.map(j=>j.name)||[],le=f.split(",").map(j=>j.trim()).filter(Boolean),W=f.includes(",")?f.substring(f.lastIndexOf(",")+1).trim().toLowerCase():f.trim().toLowerCase(),ne=oe.filter(j=>!le.includes(j)&&(W===""||j.toLowerCase().includes(W))),pe=j=>{let O;if(W&&!oe.includes(W)?O=f.includes(",")?f.substring(0,f.lastIndexOf(",")).split(",").map(K=>K.trim()).filter(Boolean):[]:O=le,!O.includes(j)){const K=[...O,j].join(", ");x(K)}te.current!==null&&clearTimeout(te.current),X.current?.focus()},be=j=>{const O=le.filter(K=>K!==j).join(", ");x(O)},Ce=st({mutationFn:j=>he.updateArchive(t.id,j),onSuccess:()=>{i.invalidateQueries({queryKey:["archives"]}),i.invalidateQueries({queryKey:["projects"]}),e()}}),$=async j=>{const O=j.target.files?.[0];if(O){D(!0);try{const K=await he.uploadArchivePhoto(t.id,O);A(K.photos),i.invalidateQueries({queryKey:["archives"]})}catch(K){console.error("Failed to upload photo:",K)}finally{D(!1),L.current&&(L.current.value="")}}},Y=async j=>{try{const O=await he.deleteArchivePhoto(t.id,j);A(O.photos||[]),i.invalidateQueries({queryKey:["archives"]})}catch(O){console.error("Failed to delete photo:",O)}},E=j=>{j.preventDefault();const O={print_name:s||void 0,printer_id:l,project_id:d,notes:m||void 0,tags:f||void 0,quantity:C,external_url:T||null};g!==t.status&&(O.status=g),g==="failed"||g==="aborted"?O.failure_reason=v||void 0:(t.status==="failed"||t.status==="aborted")&&(O.failure_reason=null),Ce.mutate(O)};return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:e,children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary w-full max-w-md max-h-[90vh] flex flex-col",onClick:j=>j.stopPropagation(),children:[a.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[a.jsx("h2",{className:"text-lg font-semibold text-white",children:r("editArchive.title")}),a.jsx("button",{onClick:e,className:"text-bambu-gray hover:text-white transition-colors",children:a.jsx(Ht,{className:"w-5 h-5"})})]}),a.jsxs("form",{onSubmit:E,className:"p-6 space-y-4 overflow-y-auto flex-1",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("editArchive.name")}),a.jsx("input",{type:"text",value:s,onChange:j=>o(j.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",placeholder:r("editArchive.namePlaceholder")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("editArchive.printer")}),a.jsxs("select",{value:l??"",onChange:j=>c(j.target.value?Number(j.target.value):null),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"",children:r("editArchive.noPrinter")}),ie?.map(j=>a.jsx("option",{value:j.id,children:j.name},j.id))]})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[a.jsx(Fs,{className:"w-4 h-4 inline mr-1"}),r("editArchive.project")]}),a.jsxs("select",{value:d??"",onChange:j=>u(j.target.value?Number(j.target.value):null),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"",children:r("editArchive.noProject")}),J?.map(j=>a.jsx("option",{value:j.id,children:j.name},j.id))]})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[a.jsx(Rge,{className:"w-4 h-4 inline mr-1"}),r("editArchive.itemsPrinted")]}),a.jsx("input",{type:"number",min:1,value:C,onChange:j=>P(Math.max(1,parseInt(j.target.value)||1)),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",placeholder:"1"}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:r("editArchive.itemsPrintedHelp")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("editArchive.notes")}),a.jsx("textarea",{value:m,onChange:j=>p(j.target.value),rows:3,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none resize-none",placeholder:r("editArchive.notesPlaceholder")})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[a.jsx(py,{className:"w-4 h-4 inline mr-1"}),r("editArchive.externalLink")]}),a.jsx("input",{type:"url",value:T,onChange:j=>F(j.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",placeholder:"https://printables.com/model/..."}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:r("editArchive.externalLinkHelp")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("editArchive.tags")}),le.length>0&&a.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:le.map(j=>a.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 bg-bambu-dark-tertiary rounded text-sm text-white",children:[a.jsx(mm,{className:"w-3 h-3"}),j,a.jsx("button",{type:"button",onClick:()=>be(j),className:"ml-0.5 text-bambu-gray hover:text-white",children:a.jsx(Ht,{className:"w-3 h-3"})})]},j))}),a.jsxs("div",{className:"relative",children:[a.jsx("input",{ref:X,type:"text",value:f,onChange:j=>x(j.target.value),onFocus:()=>{te.current!==null&&clearTimeout(te.current),z(!0)},onBlur:()=>{te.current=window.setTimeout(()=>z(!1),200)},className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",placeholder:le.length>0?r("editArchive.addMoreTags"):r("editArchive.tagsPlaceholder")}),H&&ne.length>0&&a.jsxs("div",{className:"absolute top-full left-0 right-0 mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg z-10 max-h-40 overflow-y-auto",children:[a.jsxs("div",{className:"p-2 text-xs text-bambu-gray border-b border-bambu-dark-tertiary",children:[W?r("editArchive.matchingTags",{query:W}):r("editArchive.existingTags")," ",r("editArchive.clickToAdd")]}),a.jsx("div",{className:"p-2 flex flex-wrap gap-1.5",children:ne.map(j=>a.jsx("button",{type:"button",onClick:()=>pe(j),className:"px-2 py-0.5 bg-bambu-dark-tertiary hover:bg-bambu-green/20 rounded text-sm text-bambu-gray hover:text-white transition-colors",children:j},j))})]})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("editArchive.status")}),a.jsx("select",{value:g,onChange:j=>{_(j.target.value),j.target.value==="completed"&&b("")},className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:V7e.map(j=>a.jsx("option",{value:j,children:r(`editArchive.statuses.${j}`)},j))})]}),(g==="failed"||g==="aborted")&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("editArchive.failureReason")}),a.jsxs("select",{value:v,onChange:j=>b(j.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"",children:r("editArchive.selectReason")}),$7e.map(j=>a.jsx("option",{value:r(`editArchive.failureReasons.${j}`),children:r(`editArchive.failureReasons.${j}`)},j))]})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[a.jsx(Fx,{className:"w-4 h-4 inline mr-1"}),r("editArchive.photos")]}),a.jsxs("div",{className:"flex flex-wrap gap-2 mb-2",children:[N.map(j=>a.jsxs("div",{className:"relative group",children:[a.jsx("img",{src:he.getArchivePhotoUrl(t.id,j),alt:r("editArchive.printResult"),className:"w-20 h-20 object-cover rounded-lg border border-bambu-dark-tertiary"}),a.jsx("button",{type:"button",onClick:()=>Y(j),className:"absolute -top-1 -right-1 p-1 bg-red-500 rounded-full opacity-0 group-hover:opacity-100 transition-opacity",children:a.jsx(an,{className:"w-3 h-3 text-white"})})]},j)),a.jsxs("label",{className:"w-20 h-20 flex items-center justify-center border-2 border-dashed border-bambu-dark-tertiary rounded-lg cursor-pointer hover:border-bambu-green transition-colors",children:[a.jsx("input",{ref:L,type:"file",accept:"image/jpeg,image/png,image/webp",onChange:$,className:"hidden",disabled:k}),k?a.jsx(ht,{className:"w-6 h-6 text-bambu-gray animate-spin"}):a.jsx(ir,{className:"w-6 h-6 text-bambu-gray"})]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:r("editArchive.photosHelp")})]}),a.jsxs("div",{className:"flex gap-3 pt-2",children:[a.jsx(De,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:r("common.cancel")}),a.jsxs(De,{type:"submit",disabled:Ce.isPending,className:"flex-1",children:[a.jsx(bs,{className:"w-4 h-4"}),Ce.isPending?r("common.saving"):r("common.save")]})]})]})]})})}function nie({x:t,y:e,items:n,onClose:r}){const i=w.useRef(null),[s,o]=w.useState(null),l=w.useRef(null),[c,d]=w.useState({x:t,y:e,visible:!1}),[u,m]=w.useState(!1),[p,f]=w.useState({});w.useEffect(()=>{const b=C=>{i.current&&!i.current.contains(C.target)&&r()},g=C=>{C.key==="Escape"&&r()},_=()=>{r()};return document.addEventListener("mousedown",b),document.addEventListener("keydown",g),document.addEventListener("scroll",_,!0),()=>{document.removeEventListener("mousedown",b),document.removeEventListener("keydown",g),document.removeEventListener("scroll",_,!0),l.current&&clearTimeout(l.current)}},[r]),w.useLayoutEffect(()=>{if(i.current){i.current.style.visibility="hidden",i.current.style.display="block";const b=i.current.getBoundingClientRect(),g=window.innerWidth,_=window.innerHeight,C=8;let P=t,N=e;t+b.width>g-C&&(P=Math.max(C,g-b.width-C)),P_-C&&(N=Math.max(C,_-b.height-C)),NA),d({x:P,y:N,visible:!0})}},[t,e]);const x=(b,g)=>{l.current&&(clearTimeout(l.current),l.current=null);const _=g.getBoundingClientRect(),C=window.innerHeight,P=300,T=C-_.top-8P;f(F=>({...F,[b]:T?"bottom":"top"})),o(b)},v=()=>{l.current=window.setTimeout(()=>{o(null)},150)};return a.jsx("div",{ref:i,className:"fixed z-50 min-w-[180px] max-w-[280px] bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl py-1",style:{left:c.x,top:c.y,visibility:c.visible?"visible":"hidden"},children:n.map((b,g)=>{if(b.divider)return a.jsx("div",{className:"my-1 border-t border-bambu-dark-tertiary"},g);const _=b.submenu&&b.submenu.length>0;return a.jsxs("div",{className:"relative",onMouseEnter:C=>_&&x(g,C.currentTarget),onMouseLeave:()=>_&&v(),children:[a.jsxs("button",{onMouseEnter:C=>_&&x(g,C.currentTarget.parentElement),onClick:()=>{_?o(s===g?null:g):b.disabled||(b.onClick(),r())},disabled:b.disabled,title:b.title,className:`w-full flex items-center gap-2 px-3 py-2 text-sm text-left transition-colors ${b.disabled?"text-bambu-gray cursor-not-allowed":b.danger?"text-red-400 hover:bg-red-400/10":"text-white hover:bg-bambu-dark-tertiary"} ${_&&s===g?"bg-bambu-dark-tertiary":""}`,children:[b.icon&&a.jsx("span",{className:"w-4 h-4 flex-shrink-0 flex items-center justify-center",children:b.icon}),a.jsx("span",{className:"flex-1",children:b.label}),_&&a.jsx(Xa,{className:"w-4 h-4 text-bambu-gray"})]}),_&&s===g&&a.jsx("div",{className:`absolute min-w-[160px] bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl py-1 overflow-hidden max-h-[300px] overflow-y-auto z-[60] ${u?"right-full mr-1":"left-full ml-1"} ${p[g]==="bottom"?"bottom-0":"top-0"}`,onMouseEnter:()=>{l.current&&(clearTimeout(l.current),l.current=null)},onMouseLeave:()=>v(),children:b.submenu.map((C,P)=>a.jsxs("button",{onClick:()=>{C.disabled||(C.onClick(),r())},disabled:C.disabled,className:`w-full flex items-center gap-2 px-3 py-2 text-sm text-left transition-colors ${C.disabled?"text-bambu-gray cursor-not-allowed":C.danger?"text-red-400 hover:bg-red-400/10":"text-white hover:bg-bambu-dark-tertiary"}`,children:[C.icon&&a.jsx("span",{className:"w-4 h-4 flex-shrink-0 flex items-center justify-center",children:C.icon}),C.label]},P))})]},g)})})}function G7e({selectedIds:t,existingTags:e,onClose:n}){const r=on(),{showToast:i}=fn(),[s,o]=w.useState(""),[l,c]=w.useState(new Set),[d,u]=w.useState("add");w.useEffect(()=>{const v=b=>{b.key==="Escape"&&n()};return window.addEventListener("keydown",v),()=>window.removeEventListener("keydown",v)},[n]);const m=st({mutationFn:async()=>{const v=Array.from(l);let b=0;for(const g of t)try{const _=await he.getArchive(g),C=_.tags?_.tags.split(",").map(N=>N.trim()).filter(Boolean):[];let P;d==="add"?P=[...new Set([...C,...v])]:P=C.filter(N=>!l.has(N)),await he.updateArchive(g,{tags:P.join(", ")}),b++}catch(_){throw console.error(`Failed to update archive ${g}:`,_),new Error(`Failed on archive ${g}: ${_ instanceof Error?_.message:"Unknown error"}`)}return{count:b,mode:d,tags:v}},onSuccess:({count:v,mode:b,tags:g})=>{r.invalidateQueries({queryKey:["archives"]}),i(`${b==="add"?"Added":"Removed"} ${g.length} tag${g.length!==1?"s":""} ${b==="add"?"to":"from"} ${v} archive${v!==1?"s":""}`),n()},onError:v=>{i(v.message||"Failed to update tags","error")}}),p=v=>{c(b=>{const g=new Set(b);return g.has(v)?g.delete(v):g.add(v),g})},f=()=>{s.trim()&&!l.has(s.trim())&&(c(v=>new Set([...v,s.trim()])),o(""))},x=v=>{v.key==="Enter"&&(v.preventDefault(),f())};return a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:a.jsx(At,{className:"w-full max-w-md",children:a.jsxs(Mt,{className:"p-0",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(mm,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-xl font-semibold text-white",children:d==="add"?"Add Tags":"Remove Tags"})]}),a.jsx("button",{onClick:n,className:"text-bambu-gray hover:text-white transition-colors",children:a.jsx(Ht,{className:"w-5 h-5"})})]}),a.jsxs("div",{className:"p-4 space-y-4",children:[a.jsxs("p",{className:"text-sm text-bambu-gray",children:[d==="add"?"Add":"Remove"," tags for ",t.length," selected archive",t.length!==1?"s":""]}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx(De,{size:"sm",variant:d==="add"?"primary":"secondary",onClick:()=>u("add"),children:"Add Tags"}),a.jsx(De,{size:"sm",variant:d==="remove"?"primary":"secondary",onClick:()=>u("remove"),children:"Remove Tags"})]}),d==="add"&&a.jsxs("div",{className:"flex gap-2",children:[a.jsx("input",{type:"text",placeholder:"Enter new tag...",className:"flex-1 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",value:s,onChange:v=>o(v.target.value),onKeyDown:x}),a.jsx(De,{size:"sm",variant:"secondary",onClick:f,disabled:!s.trim(),children:a.jsx(ir,{className:"w-4 h-4"})})]}),e.length>0&&a.jsxs("div",{children:[a.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:"Existing tags:"}),a.jsx("div",{className:"flex flex-wrap gap-2",children:e.map(v=>a.jsx("button",{onClick:()=>p(v),className:`px-2 py-1 rounded text-sm transition-colors ${l.has(v)?"bg-bambu-green text-white":"bg-bambu-dark-tertiary text-bambu-gray-light hover:bg-bambu-dark"}`,children:v},v))})]}),l.size>0&&a.jsxs("div",{children:[a.jsxs("p",{className:"text-xs text-bambu-gray mb-2",children:["Tags to ",d==="add"?"add":"remove",":"]}),a.jsx("div",{className:"flex flex-wrap gap-2",children:Array.from(l).map(v=>a.jsxs("span",{className:`px-2 py-1 rounded text-sm flex items-center gap-1 ${d==="add"?"bg-green-500/20 text-green-400":"bg-red-500/20 text-red-400"}`,children:[v,a.jsx("button",{onClick:()=>p(v),className:"hover:opacity-70",children:a.jsx(Ht,{className:"w-3 h-3"})})]},v))})]})]}),a.jsxs("div",{className:"flex gap-3 p-4 border-t border-bambu-dark-tertiary",children:[a.jsx(De,{variant:"secondary",onClick:n,className:"flex-1",children:"Cancel"}),a.jsx(De,{onClick:()=>m.mutate(),disabled:l.size===0||m.isPending,className:"flex-1",children:m.isPending?a.jsxs(a.Fragment,{children:[a.jsx(ht,{className:"w-4 h-4 animate-spin"}),"Processing..."]}):a.jsxs(a.Fragment,{children:[a.jsx(mm,{className:"w-4 h-4"}),d==="add"?"Add Tags":"Remove Tags"]})})]})]})})})}function W7e({selectedIds:t,onClose:e}){const n=on(),{showToast:r}=fn(),{data:i,isLoading:s}=Qe({queryKey:["projects"],queryFn:()=>he.getProjects()});w.useEffect(()=>{const u=m=>{m.key==="Escape"&&e()};return window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)},[e]);const o=()=>{n.invalidateQueries({queryKey:["archives"]}),n.invalidateQueries({queryKey:["projects"]}),n.invalidateQueries({queryKey:["project"]}),n.invalidateQueries({queryKey:["project-archives"]})},l=st({mutationFn:async u=>(await he.addArchivesToProject(u,t),u),onSuccess:u=>{const m=i?.find(p=>p.id===u);o(),r(`Added ${t.length} archive${t.length!==1?"s":""} to "${m?.name}"`),e()},onError:()=>{r("Failed to assign project","error")}}),c=st({mutationFn:async()=>{for(const u of t)await he.updateArchive(u,{project_id:null});return t.length},onSuccess:u=>{o(),r(`Removed ${u} archive${u!==1?"s":""} from project`),e()},onError:()=>{r("Failed to remove from project","error")}}),d=l.isPending||c.isPending;return a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:a.jsx(At,{className:"w-full max-w-md max-h-[80vh] flex flex-col",children:a.jsxs(Mt,{className:"p-0 flex flex-col min-h-0",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary shrink-0",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Fs,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-xl font-semibold text-white",children:"Assign to Project"})]}),a.jsx("button",{onClick:e,className:"text-bambu-gray hover:text-white transition-colors",disabled:d,children:a.jsx(Ht,{className:"w-5 h-5"})})]}),a.jsxs("div",{className:"p-4 space-y-3 overflow-y-auto min-h-0",children:[a.jsxs("p",{className:"text-sm text-bambu-gray",children:["Assign ",t.length," selected archive",t.length!==1?"s":""," to a project"]}),s?a.jsx("div",{className:"flex items-center justify-center py-8",children:a.jsx(ht,{className:"w-6 h-6 animate-spin text-bambu-gray"})}):a.jsxs("div",{className:"space-y-2",children:[a.jsxs("button",{onClick:()=>c.mutate(),disabled:d,className:"w-full flex items-center gap-3 p-3 rounded-lg bg-bambu-dark hover:bg-bambu-dark-tertiary border border-bambu-dark-tertiary transition-colors text-left disabled:opacity-50",children:[a.jsx("div",{className:"w-8 h-8 rounded-full bg-red-500/20 flex items-center justify-center shrink-0",children:a.jsx(Ta,{className:"w-4 h-4 text-red-400"})}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:"text-white font-medium",children:"Remove from project"}),a.jsx("p",{className:"text-sm text-bambu-gray truncate",children:"Clear project assignment"})]}),c.isPending&&a.jsx(ht,{className:"w-4 h-4 animate-spin text-bambu-gray shrink-0"})]}),i&&i.length>0&&a.jsxs("div",{className:"flex items-center gap-2 py-2",children:[a.jsx("div",{className:"flex-1 h-px bg-bambu-dark-tertiary"}),a.jsx("span",{className:"text-xs text-bambu-gray",children:"or assign to"}),a.jsx("div",{className:"flex-1 h-px bg-bambu-dark-tertiary"})]}),i?.map(u=>a.jsxs("button",{onClick:()=>l.mutate(u.id),disabled:d,className:"w-full flex items-center gap-3 p-3 rounded-lg bg-bambu-dark hover:bg-bambu-dark-tertiary border border-bambu-dark-tertiary transition-colors text-left disabled:opacity-50",children:[a.jsx("div",{className:"w-8 h-8 rounded-full flex items-center justify-center shrink-0",style:{backgroundColor:u.color?`${u.color}20`:"rgb(var(--bambu-green) / 0.2)"},children:a.jsx(Fs,{className:"w-4 h-4",style:{color:u.color||"rgb(var(--bambu-green))"}})}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:"text-white font-medium truncate",children:u.name}),a.jsxs("p",{className:"text-sm text-bambu-gray truncate",children:[u.archive_count," archive",u.archive_count!==1?"s":"",u.status&&` • ${u.status}`]})]}),l.isPending&&l.variables===u.id&&a.jsx(ht,{className:"w-4 h-4 animate-spin text-bambu-gray shrink-0"})]},u.id)),(!i||i.length===0)&&a.jsx("p",{className:"text-center text-bambu-gray py-4",children:"No projects yet. Create one from the Projects page."})]})]}),a.jsx("div",{className:"flex gap-3 p-4 border-t border-bambu-dark-tertiary shrink-0",children:a.jsx(De,{variant:"secondary",onClick:e,className:"flex-1",disabled:d,children:"Cancel"})})]})})})}function K7e(t,e){return new Date(t,e+1,0).getDate()}function X7e(t,e){return new Date(t,e,1).getDay()}const Y7e=["January","February","March","April","May","June","July","August","September","October","November","December"],Q7e=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];function Z7e({archives:t,onArchiveClick:e,highlightedArchiveId:n}){const r=new Date,[i,s]=w.useState(r.getMonth()),[o,l]=w.useState(r.getFullYear()),[c,d]=w.useState(null),[u,m]=w.useState(null),p=w.useMemo(()=>{const N=new Map;return t.forEach(A=>{const T=Zn(A.completed_at||A.created_at)||new Date,F=`${T.getFullYear()}-${String(T.getMonth()+1).padStart(2,"0")}-${String(T.getDate()).padStart(2,"0")}`,k=N.get(F)||[];k.push(A),N.set(F,k)}),N},[t]),f=K7e(o,i),x=X7e(o,i),v=()=>{i===0?(s(11),l(o-1)):s(i-1)},b=()=>{i===11?(s(0),l(o+1)):s(i+1)},g=()=>{s(r.getMonth()),l(r.getFullYear())},_=[];for(let N=0;N{N!==c&&m(null),d(N)};return a.jsxs("div",{className:"flex flex-col lg:flex-row gap-6",children:[a.jsxs("div",{className:"flex-1",children:[a.jsxs("div",{className:"flex items-center justify-between mb-4",children:[a.jsx("button",{onClick:v,className:"p-2 hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:a.jsx(ml,{className:"w-5 h-5 text-bambu-gray"})}),a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white",children:[Y7e[i]," ",o]}),a.jsx("button",{onClick:g,className:"px-2 py-1 text-xs bg-bambu-dark-tertiary hover:bg-bambu-green/20 text-bambu-gray hover:text-white rounded transition-colors",children:"Today"})]}),a.jsx("button",{onClick:b,className:"p-2 hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:a.jsx(Xa,{className:"w-5 h-5 text-bambu-gray"})})]}),a.jsx("div",{className:"grid grid-cols-7 gap-1 mb-1",children:Q7e.map(N=>a.jsx("div",{className:"text-center text-xs text-bambu-gray py-2",children:N},N))}),a.jsx("div",{className:"grid grid-cols-7 gap-1",children:_.map((N,A)=>{if(N===null)return a.jsx("div",{className:"aspect-square"},`empty-${A}`);const T=`${o}-${String(i+1).padStart(2,"0")}-${String(N).padStart(2,"0")}`,F=p.get(T)||[],k=F.length>0,D=N===r.getDate()&&i===r.getMonth()&&o===r.getFullYear(),H=T===c,z=F.filter(L=>L.status==="completed").length,X=F.filter(L=>L.status==="failed").length;return a.jsxs("button",{onClick:()=>P(H?null:T),className:`aspect-square rounded-lg p-1 flex flex-col items-center justify-center transition-colors relative ${H?"bg-bambu-green text-white":D?"bg-bambu-green/20 text-white ring-2 ring-bambu-green":k?"bg-bambu-dark-tertiary hover:bg-bambu-dark-tertiary/70 text-white":"hover:bg-bambu-dark-tertiary/50 text-bambu-gray"}`,children:[a.jsx("span",{className:`text-sm font-medium ${D&&!H?"text-bambu-green":""}`,children:N}),k&&a.jsxs("div",{className:"absolute bottom-1 left-1/2 -translate-x-1/2 flex items-center gap-1",children:[a.jsx("div",{className:`w-2 h-2 rounded-full ${X>0&&z===0?"bg-red-400":X>0?"bg-yellow-400":"bg-green-400"}`}),a.jsx("span",{className:"text-xs font-medium",children:F.length})]})]},N)})}),a.jsx("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:a.jsxs("div",{className:"grid grid-cols-3 gap-4 text-center",children:[a.jsxs("div",{children:[a.jsx("div",{className:"text-2xl font-bold text-white",children:t.filter(N=>{const A=Zn(N.completed_at||N.created_at)||new Date;return A.getMonth()===i&&A.getFullYear()===o}).length}),a.jsx("div",{className:"text-xs text-bambu-gray",children:"Prints this month"})]}),a.jsxs("div",{children:[a.jsx("div",{className:"text-2xl font-bold text-green-400",children:t.filter(N=>{const A=Zn(N.completed_at||N.created_at)||new Date;return A.getMonth()===i&&A.getFullYear()===o&&N.status==="completed"}).length}),a.jsx("div",{className:"text-xs text-bambu-gray",children:"Successful"})]}),a.jsxs("div",{children:[a.jsx("div",{className:"text-2xl font-bold text-red-400",children:t.filter(N=>{const A=Zn(N.completed_at||N.created_at)||new Date;return A.getMonth()===i&&A.getFullYear()===o&&N.status==="failed"}).length}),a.jsx("div",{className:"text-xs text-bambu-gray",children:"Failed"})]})]})})]}),a.jsx("div",{className:"lg:w-80 bg-bambu-dark rounded-xl p-4",children:c?a.jsxs(a.Fragment,{children:[a.jsx("h3",{className:"text-sm font-medium text-bambu-gray mb-3",children:new Date(c+"T12:00:00").toLocaleDateString("en-US",{weekday:"long",month:"long",day:"numeric",year:"numeric"})}),C.length>0?a.jsx("div",{className:"calendar-scroll space-y-2 max-h-96 overflow-y-auto",children:C.map(N=>{const A=N.id===u||N.id===n;return a.jsxs("button",{onClick:()=>{m(N.id),e?.(N)},className:`w-full flex items-center gap-3 p-2 rounded-lg transition-colors text-left ${A?"":"hover:bg-bambu-dark-tertiary"}`,style:A?{outline:"4px solid #facc15",outlineOffset:"2px"}:void 0,children:[N.thumbnail_path?a.jsx("img",{src:he.getArchiveThumbnail(N.id),alt:"",className:"w-12 h-12 rounded object-cover"}):a.jsx("div",{className:"w-12 h-12 rounded bg-bambu-dark-tertiary flex items-center justify-center",children:a.jsx("span",{className:"text-xs text-bambu-gray",children:"3MF"})}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("p",{className:"text-sm text-white truncate",children:N.print_name||N.filename}),a.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[a.jsx("span",{className:N.status==="failed"?"text-red-400":"text-green-400",children:N.status==="failed"?"Failed":"Completed"}),N.filament_color&&a.jsx("div",{className:"flex gap-0.5",children:N.filament_color.split(",").map((T,F)=>a.jsx("div",{className:"w-3 h-3 rounded-full border border-black/20",style:{backgroundColor:T}},F))})]})]})]},N.id)})}):a.jsx("p",{className:"text-sm text-bambu-gray",children:"No prints on this day"})]}):a.jsx("div",{className:"text-center py-8",children:a.jsx("p",{className:"text-sm text-bambu-gray",children:"Select a day to see prints"})})})]})}function rie({archiveId:t,archiveName:e,onClose:n}){const r=he.getArchiveQRCodeUrl(t,300);w.useEffect(()=>{const s=o=>{o.key==="Escape"&&n()};return window.addEventListener("keydown",s),()=>window.removeEventListener("keydown",s)},[n]);const i=()=>{const s=document.createElement("a");s.href=r,s.download=`${e}_qrcode.png`,s.click()};return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:n,children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary w-full max-w-sm",onClick:s=>s.stopPropagation(),children:[a.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[a.jsx("h2",{className:"text-lg font-semibold text-white",children:"QR Code"}),a.jsx("button",{onClick:n,className:"text-bambu-gray hover:text-white transition-colors",children:a.jsx(Ht,{className:"w-5 h-5"})})]}),a.jsxs("div",{className:"p-6 flex flex-col items-center",children:[a.jsx("p",{className:"text-sm text-bambu-gray mb-4 text-center truncate max-w-full",children:e}),a.jsx("div",{className:"bg-white p-4 rounded-lg mb-4",children:a.jsx("img",{src:r,alt:"QR Code",className:"w-64 h-64"})}),a.jsx("p",{className:"text-xs text-bambu-gray mb-4 text-center",children:"Scan to open this archive"}),a.jsxs(De,{onClick:i,className:"w-full",children:[a.jsx(ha,{className:"w-4 h-4"}),"Download QR Code"]})]})]})})}function aie({archiveId:t,archiveName:e,photos:n,onClose:r,onDelete:i}){const[s,o]=w.useState(0),[l,c]=w.useState(!1);if(w.useEffect(()=>{const f=x=>{x.key==="Escape"&&r(),x.key==="ArrowLeft"&&o(v=>Math.max(0,v-1)),x.key==="ArrowRight"&&o(v=>Math.min(n.length-1,v+1))};return window.addEventListener("keydown",f),()=>window.removeEventListener("keydown",f)},[r,n.length]),w.useEffect(()=>{s>=n.length&&o(Math.max(0,n.length-1))},[n.length,s]),n.length===0)return r(),null;const d=n[s],u=he.getArchivePhotoUrl(t,d),m=()=>{const f=document.createElement("a");f.href=u,f.download=`${e}_photo_${s+1}.jpg`,f.click()},p=()=>{i&&c(!0)};return a.jsxs("div",{className:"fixed inset-0 bg-black/90 flex items-center justify-center z-50",onClick:r,children:[a.jsxs("div",{className:"relative w-full h-full flex flex-col",onClick:f=>f.stopPropagation(),children:[a.jsxs("div",{className:"flex items-center justify-between px-6 py-4 bg-black/50",children:[a.jsxs("div",{children:[a.jsx("h2",{className:"text-lg font-semibold text-white",children:e}),a.jsxs("p",{className:"text-sm text-bambu-gray",children:["Photo ",s+1," of ",n.length]})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs(De,{variant:"secondary",size:"sm",onClick:m,children:[a.jsx(ha,{className:"w-4 h-4"}),"Download"]}),i&&a.jsx(De,{variant:"secondary",size:"sm",onClick:p,className:"text-red-400 hover:text-red-300",children:a.jsx(an,{className:"w-4 h-4"})}),a.jsx("button",{onClick:r,className:"p-2 text-bambu-gray hover:text-white transition-colors",children:a.jsx(Ht,{className:"w-6 h-6"})})]})]}),a.jsxs("div",{className:"flex-1 min-h-0 flex items-center justify-center p-4 relative overflow-hidden",children:[s>0&&a.jsx("button",{onClick:()=>o(f=>f-1),className:"absolute left-4 z-10 p-3 bg-black/50 hover:bg-black/70 rounded-full transition-colors",children:a.jsx(ml,{className:"w-8 h-8 text-white"})}),a.jsx("img",{src:u,alt:`Photo ${s+1}`,className:"max-w-full max-h-full object-contain rounded-lg",style:{maxHeight:"calc(100vh - 200px)"}}),so(f=>f+1),className:"absolute right-4 z-10 p-3 bg-black/50 hover:bg-black/70 rounded-full transition-colors",children:a.jsx(Xa,{className:"w-8 h-8 text-white"})})]}),n.length>1&&a.jsx("div",{className:"flex justify-center gap-2 p-4 bg-black/50",children:n.map((f,x)=>a.jsx("button",{onClick:()=>o(x),className:`w-16 h-16 rounded-lg overflow-hidden border-2 transition-colors ${x===s?"border-bambu-green":"border-transparent hover:border-bambu-gray"}`,children:a.jsx("img",{src:he.getArchivePhotoUrl(t,f),alt:`Thumbnail ${x+1}`,className:"w-full h-full object-cover"})},f))})]}),l&&a.jsx(wn,{title:"Delete Photo",message:"Delete this photo? This cannot be undone.",confirmText:"Delete",variant:"danger",onConfirm:()=>{i?.(d),c(!1)},onCancel:()=>c(!1)})]})}const{entries:iie,setPrototypeOf:uK,isFrozen:J7e,getPrototypeOf:eGe,getOwnPropertyDescriptor:tGe}=Object;let{freeze:so,seal:uc,create:u0}=Object,{apply:fL,construct:gL}=typeof Reflect<"u"&&Reflect;so||(so=function(e){return e});uc||(uc=function(e){return e});fL||(fL=function(e,n){for(var r=arguments.length,i=new Array(r>2?r-2:0),s=2;s1?n-1:0),i=1;i1?n-1:0),i=1;i2&&arguments[2]!==void 0?arguments[2]:Yk;uK&&uK(t,null);let r=e.length;for(;r--;){let i=e[r];if(typeof i=="string"){const s=n(i);s!==i&&(J7e(e)||(e[r]=s),i=s)}t[i]=!0}return t}function oGe(t){for(let e=0;e/gm),mGe=uc(/\$\{[\w\W]*/gm),hGe=uc(/^data-[\-\w.\u00B7-\uFFFF]+$/),pGe=uc(/^aria-[\-\w]+$/),sie=uc(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),fGe=uc(/^(?:\w+script|data):/i),gGe=uc(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),oie=uc(/^html$/i),bGe=uc(/^[a-z][.\w]*(-[.\w]+)+$/i);var bK=Object.freeze({__proto__:null,ARIA_ATTR:pGe,ATTR_WHITESPACE:gGe,CUSTOM_ELEMENT:bGe,DATA_ATTR:hGe,DOCTYPE_NAME:oie,ERB_EXPR:uGe,IS_ALLOWED_URI:sie,IS_SCRIPT_OR_DATA:fGe,MUSTACHE_EXPR:dGe,TMPLIT_EXPR:mGe});const Qv={element:1,text:3,progressingInstruction:7,comment:8,document:9},xGe=function(){return typeof window>"u"?null:window},yGe=function(e,n){if(typeof e!="object"||typeof e.createPolicy!="function")return null;let r=null;const i="data-tt-policy-suffix";n&&n.hasAttribute(i)&&(r=n.getAttribute(i));const s="dompurify"+(r?"#"+r:"");try{return e.createPolicy(s,{createHTML(o){return o},createScriptURL(o){return o}})}catch{return console.warn("TrustedTypes policy "+s+" could not be created."),null}},xK=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function lie(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:xGe();const e=at=>lie(at);if(e.version="3.4.0",e.removed=[],!t||!t.document||t.document.nodeType!==Qv.document||!t.Element)return e.isSupported=!1,e;let{document:n}=t;const r=n,i=r.currentScript,{DocumentFragment:s,HTMLTemplateElement:o,Node:l,Element:c,NodeFilter:d,NamedNodeMap:u=t.NamedNodeMap||t.MozNamedAttrMap,HTMLFormElement:m,DOMParser:p,trustedTypes:f}=t,x=c.prototype,v=Yv(x,"cloneNode"),b=Yv(x,"remove"),g=Yv(x,"nextSibling"),_=Yv(x,"childNodes"),C=Yv(x,"parentNode");if(typeof o=="function"){const at=n.createElement("template");at.content&&at.content.ownerDocument&&(n=at.content.ownerDocument)}let P,N="";const{implementation:A,createNodeIterator:T,createDocumentFragment:F,getElementsByTagName:k}=n,{importNode:D}=r;let H=xK();e.isSupported=typeof iie=="function"&&typeof C=="function"&&A&&A.createHTMLDocument!==void 0;const{MUSTACHE_EXPR:z,ERB_EXPR:X,TMPLIT_EXPR:L,DATA_ATTR:te,ARIA_ATTR:ie,IS_SCRIPT_OR_DATA:J,ATTR_WHITESPACE:ce,CUSTOM_ELEMENT:oe}=bK;let{IS_ALLOWED_URI:le}=bK,W=null;const ne=lr({},[...hK,...RD,...LD,...OD,...pK]);let pe=null;const be=lr({},[...fK,...ID,...gK,...dk]);let Ce=Object.seal(u0(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),$=null,Y=null;const E=Object.seal(u0(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let j=!0,O=!0,K=!1,B=!0,me=!1,I=!0,V=!1,Q=!1,G=!1,ee=!1,se=!1,ge=!1,fe=!0,de=!1;const U="user-content-";let R=!0,re=!1,_e={},Se=null;const ye=lr({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]);let Te=null;const xe=lr({},["audio","video","img","source","image","track"]);let Ae=null;const Le=lr({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),Me="http://www.w3.org/1998/Math/MathML",Fe="http://www.w3.org/2000/svg",Re="http://www.w3.org/1999/xhtml";let qe=Re,Ye=!1,nt=null;const ae=lr({},[Me,Fe,Re],DD);let ze=lr({},["mi","mo","mn","ms","mtext"]),we=lr({},["annotation-xml"]);const Ve=lr({},["title","style","font","a","script"]);let je=null;const ue=["application/xhtml+xml","text/html"],ve="text/html";let Be=null,Ze=null;const mt=n.createElement("form"),gt=function(Oe){return Oe instanceof RegExp||Oe instanceof Function},xt=function(){let Oe=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(Ze&&Ze===Oe)){if((!Oe||typeof Oe!="object")&&(Oe={}),Oe=bd(Oe),je=ue.indexOf(Oe.PARSER_MEDIA_TYPE)===-1?ve:Oe.PARSER_MEDIA_TYPE,Be=je==="application/xhtml+xml"?DD:Yk,W=Ec(Oe,"ALLOWED_TAGS")?lr({},Oe.ALLOWED_TAGS,Be):ne,pe=Ec(Oe,"ALLOWED_ATTR")?lr({},Oe.ALLOWED_ATTR,Be):be,nt=Ec(Oe,"ALLOWED_NAMESPACES")?lr({},Oe.ALLOWED_NAMESPACES,DD):ae,Ae=Ec(Oe,"ADD_URI_SAFE_ATTR")?lr(bd(Le),Oe.ADD_URI_SAFE_ATTR,Be):Le,Te=Ec(Oe,"ADD_DATA_URI_TAGS")?lr(bd(xe),Oe.ADD_DATA_URI_TAGS,Be):xe,Se=Ec(Oe,"FORBID_CONTENTS")?lr({},Oe.FORBID_CONTENTS,Be):ye,$=Ec(Oe,"FORBID_TAGS")?lr({},Oe.FORBID_TAGS,Be):bd({}),Y=Ec(Oe,"FORBID_ATTR")?lr({},Oe.FORBID_ATTR,Be):bd({}),_e=Ec(Oe,"USE_PROFILES")?Oe.USE_PROFILES:!1,j=Oe.ALLOW_ARIA_ATTR!==!1,O=Oe.ALLOW_DATA_ATTR!==!1,K=Oe.ALLOW_UNKNOWN_PROTOCOLS||!1,B=Oe.ALLOW_SELF_CLOSE_IN_ATTR!==!1,me=Oe.SAFE_FOR_TEMPLATES||!1,I=Oe.SAFE_FOR_XML!==!1,V=Oe.WHOLE_DOCUMENT||!1,ee=Oe.RETURN_DOM||!1,se=Oe.RETURN_DOM_FRAGMENT||!1,ge=Oe.RETURN_TRUSTED_TYPE||!1,G=Oe.FORCE_BODY||!1,fe=Oe.SANITIZE_DOM!==!1,de=Oe.SANITIZE_NAMED_PROPS||!1,R=Oe.KEEP_CONTENT!==!1,re=Oe.IN_PLACE||!1,le=Oe.ALLOWED_URI_REGEXP||sie,qe=Oe.NAMESPACE||Re,ze=Oe.MATHML_TEXT_INTEGRATION_POINTS||ze,we=Oe.HTML_INTEGRATION_POINTS||we,Ce=Oe.CUSTOM_ELEMENT_HANDLING||u0(null),Oe.CUSTOM_ELEMENT_HANDLING&>(Oe.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(Ce.tagNameCheck=Oe.CUSTOM_ELEMENT_HANDLING.tagNameCheck),Oe.CUSTOM_ELEMENT_HANDLING&>(Oe.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(Ce.attributeNameCheck=Oe.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),Oe.CUSTOM_ELEMENT_HANDLING&&typeof Oe.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&(Ce.allowCustomizedBuiltInElements=Oe.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),me&&(O=!1),se&&(ee=!0),_e&&(W=lr({},pK),pe=u0(null),_e.html===!0&&(lr(W,hK),lr(pe,fK)),_e.svg===!0&&(lr(W,RD),lr(pe,ID),lr(pe,dk)),_e.svgFilters===!0&&(lr(W,LD),lr(pe,ID),lr(pe,dk)),_e.mathMl===!0&&(lr(W,OD),lr(pe,gK),lr(pe,dk))),E.tagCheck=null,E.attributeCheck=null,Oe.ADD_TAGS&&(typeof Oe.ADD_TAGS=="function"?E.tagCheck=Oe.ADD_TAGS:(W===ne&&(W=bd(W)),lr(W,Oe.ADD_TAGS,Be))),Oe.ADD_ATTR&&(typeof Oe.ADD_ATTR=="function"?E.attributeCheck=Oe.ADD_ATTR:(pe===be&&(pe=bd(pe)),lr(pe,Oe.ADD_ATTR,Be))),Oe.ADD_URI_SAFE_ATTR&&lr(Ae,Oe.ADD_URI_SAFE_ATTR,Be),Oe.FORBID_CONTENTS&&(Se===ye&&(Se=bd(Se)),lr(Se,Oe.FORBID_CONTENTS,Be)),Oe.ADD_FORBID_CONTENTS&&(Se===ye&&(Se=bd(Se)),lr(Se,Oe.ADD_FORBID_CONTENTS,Be)),R&&(W["#text"]=!0),V&&lr(W,["html","head","body"]),W.table&&(lr(W,["tbody"]),delete $.tbody),Oe.TRUSTED_TYPES_POLICY){if(typeof Oe.TRUSTED_TYPES_POLICY.createHTML!="function")throw Xv('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof Oe.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw Xv('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');P=Oe.TRUSTED_TYPES_POLICY,N=P.createHTML("")}else P===void 0&&(P=yGe(f,i)),P!==null&&typeof N=="string"&&(N=P.createHTML(""));so&&so(Oe),Ze=Oe}},Bt=lr({},[...RD,...LD,...lGe]),Yt=lr({},[...OD,...cGe]),rn=function(Oe){let lt=C(Oe);(!lt||!lt.tagName)&&(lt={namespaceURI:qe,tagName:"template"});const Pe=Yk(Oe.tagName),Ge=Yk(lt.tagName);return nt[Oe.namespaceURI]?Oe.namespaceURI===Fe?lt.namespaceURI===Re?Pe==="svg":lt.namespaceURI===Me?Pe==="svg"&&(Ge==="annotation-xml"||ze[Ge]):!!Bt[Pe]:Oe.namespaceURI===Me?lt.namespaceURI===Re?Pe==="math":lt.namespaceURI===Fe?Pe==="math"&&we[Ge]:!!Yt[Pe]:Oe.namespaceURI===Re?lt.namespaceURI===Fe&&!we[Ge]||lt.namespaceURI===Me&&!ze[Ge]?!1:!Yt[Pe]&&(Ve[Pe]||!Bt[Pe]):!!(je==="application/xhtml+xml"&&nt[Oe.namespaceURI]):!1},Vt=function(Oe){Kv(e.removed,{element:Oe});try{C(Oe).removeChild(Oe)}catch{b(Oe)}},Jt=function(Oe,lt){try{Kv(e.removed,{attribute:lt.getAttributeNode(Oe),from:lt})}catch{Kv(e.removed,{attribute:null,from:lt})}if(lt.removeAttribute(Oe),Oe==="is")if(ee||se)try{Vt(lt)}catch{}else try{lt.setAttribute(Oe,"")}catch{}},We=function(Oe){let lt=null,Pe=null;if(G)Oe=""+Oe;else{const Ke=FD(Oe,/^[\r\n\t ]+/);Pe=Ke&&Ke[0]}je==="application/xhtml+xml"&&qe===Re&&(Oe=''+Oe+"");const Ge=P?P.createHTML(Oe):Oe;if(qe===Re)try{lt=new p().parseFromString(Ge,je)}catch{}if(!lt||!lt.documentElement){lt=A.createDocument(qe,"template",null);try{lt.documentElement.innerHTML=Ye?N:Ge}catch{}}const et=lt.body||lt.documentElement;return Oe&&Pe&&et.insertBefore(n.createTextNode(Pe),et.childNodes[0]||null),qe===Re?k.call(lt,V?"html":"body")[0]:V?lt.documentElement:et},Ft=function(Oe){return T.call(Oe.ownerDocument||Oe,Oe,d.SHOW_ELEMENT|d.SHOW_COMMENT|d.SHOW_TEXT|d.SHOW_PROCESSING_INSTRUCTION|d.SHOW_CDATA_SECTION,null)},Qt=function(Oe){return Oe instanceof m&&(typeof Oe.nodeName!="string"||typeof Oe.textContent!="string"||typeof Oe.removeChild!="function"||!(Oe.attributes instanceof u)||typeof Oe.removeAttribute!="function"||typeof Oe.setAttribute!="function"||typeof Oe.namespaceURI!="string"||typeof Oe.insertBefore!="function"||typeof Oe.hasChildNodes!="function")},Nt=function(Oe){return typeof l=="function"&&Oe instanceof l};function bt(at,Oe,lt){Wv(at,Pe=>{Pe.call(e,Oe,lt,Ze)})}const Wt=function(Oe){let lt=null;if(bt(H.beforeSanitizeElements,Oe,null),Qt(Oe))return Vt(Oe),!0;const Pe=Be(Oe.nodeName);if(bt(H.uponSanitizeElement,Oe,{tagName:Pe,allowedTags:W}),I&&Oe.hasChildNodes()&&!Nt(Oe.firstElementChild)&&Gs(/<[/\w!]/g,Oe.innerHTML)&&Gs(/<[/\w!]/g,Oe.textContent)||I&&Oe.namespaceURI===Re&&Pe==="style"&&Nt(Oe.firstElementChild)||Oe.nodeType===Qv.progressingInstruction||I&&Oe.nodeType===Qv.comment&&Gs(/<[/\w]/g,Oe.data))return Vt(Oe),!0;if($[Pe]||!(E.tagCheck instanceof Function&&E.tagCheck(Pe))&&!W[Pe]){if(!$[Pe]&&Ie(Pe)&&(Ce.tagNameCheck instanceof RegExp&&Gs(Ce.tagNameCheck,Pe)||Ce.tagNameCheck instanceof Function&&Ce.tagNameCheck(Pe)))return!1;if(R&&!Se[Pe]){const Ge=C(Oe)||Oe.parentNode,et=_(Oe)||Oe.childNodes;if(et&&Ge){const Ke=et.length;for(let Xe=Ke-1;Xe>=0;--Xe){const Ue=v(et[Xe],!0);Ue.__removalCount=(Oe.__removalCount||0)+1,Ge.insertBefore(Ue,g(Oe))}}}return Vt(Oe),!0}return Oe instanceof c&&!rn(Oe)||(Pe==="noscript"||Pe==="noembed"||Pe==="noframes")&&Gs(/<\/no(script|embed|frames)/i,Oe.innerHTML)?(Vt(Oe),!0):(me&&Oe.nodeType===Qv.text&&(lt=Oe.textContent,Wv([z,X,L],Ge=>{lt=Qb(lt,Ge," ")}),Oe.textContent!==lt&&(Kv(e.removed,{element:Oe.cloneNode()}),Oe.textContent=lt)),bt(H.afterSanitizeElements,Oe,null),!1)},It=function(Oe,lt,Pe){if(Y[lt]||fe&&(lt==="id"||lt==="name")&&(Pe in n||Pe in mt))return!1;if(!(O&&!Y[lt]&&Gs(te,lt))){if(!(j&&Gs(ie,lt))){if(!(E.attributeCheck instanceof Function&&E.attributeCheck(lt,Oe))){if(!pe[lt]||Y[lt]){if(!(Ie(Oe)&&(Ce.tagNameCheck instanceof RegExp&&Gs(Ce.tagNameCheck,Oe)||Ce.tagNameCheck instanceof Function&&Ce.tagNameCheck(Oe))&&(Ce.attributeNameCheck instanceof RegExp&&Gs(Ce.attributeNameCheck,lt)||Ce.attributeNameCheck instanceof Function&&Ce.attributeNameCheck(lt,Oe))||lt==="is"&&Ce.allowCustomizedBuiltInElements&&(Ce.tagNameCheck instanceof RegExp&&Gs(Ce.tagNameCheck,Pe)||Ce.tagNameCheck instanceof Function&&Ce.tagNameCheck(Pe))))return!1}else if(!Ae[lt]){if(!Gs(le,Qb(Pe,ce,""))){if(!((lt==="src"||lt==="xlink:href"||lt==="href")&&Oe!=="script"&&aGe(Pe,"data:")===0&&Te[Oe])){if(!(K&&!Gs(J,Qb(Pe,ce,"")))){if(Pe)return!1}}}}}}}return!0},Ie=function(Oe){return Oe!=="annotation-xml"&&FD(Oe,oe)},ct=function(Oe){bt(H.beforeSanitizeAttributes,Oe,null);const{attributes:lt}=Oe;if(!lt||Qt(Oe))return;const Pe={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:pe,forceKeepAttr:void 0};let Ge=lt.length;for(;Ge--;){const et=lt[Ge],{name:Ke,namespaceURI:Xe,value:Ue}=et,Je=Be(Ke),jt=Ue;let yt=Ke==="value"?jt:iGe(jt);if(Pe.attrName=Je,Pe.attrValue=yt,Pe.keepAttr=!0,Pe.forceKeepAttr=void 0,bt(H.uponSanitizeAttribute,Oe,Pe),yt=Pe.attrValue,de&&(Je==="id"||Je==="name")&&(Jt(Ke,Oe),yt=U+yt),I&&Gs(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,yt)){Jt(Ke,Oe);continue}if(Je==="attributename"&&FD(yt,"href")){Jt(Ke,Oe);continue}if(Pe.forceKeepAttr)continue;if(!Pe.keepAttr){Jt(Ke,Oe);continue}if(!B&&Gs(/\/>/i,yt)){Jt(Ke,Oe);continue}me&&Wv([z,X,L],vt=>{yt=Qb(yt,vt," ")});const $e=Be(Oe.nodeName);if(!It($e,Je,yt)){Jt(Ke,Oe);continue}if(P&&typeof f=="object"&&typeof f.getAttributeType=="function"&&!Xe)switch(f.getAttributeType($e,Je)){case"TrustedHTML":{yt=P.createHTML(yt);break}case"TrustedScriptURL":{yt=P.createScriptURL(yt);break}}if(yt!==jt)try{Xe?Oe.setAttributeNS(Xe,Ke,yt):Oe.setAttribute(Ke,yt),Qt(Oe)?Vt(Oe):mK(e.removed)}catch{Jt(Ke,Oe)}}bt(H.afterSanitizeAttributes,Oe,null)},pt=function(Oe){let lt=null;const Pe=Ft(Oe);for(bt(H.beforeSanitizeShadowDOM,Oe,null);lt=Pe.nextNode();)bt(H.uponSanitizeShadowNode,lt,null),Wt(lt),ct(lt),lt.content instanceof s&&pt(lt.content);bt(H.afterSanitizeShadowDOM,Oe,null)};return e.sanitize=function(at){let Oe=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},lt=null,Pe=null,Ge=null,et=null;if(Ye=!at,Ye&&(at=""),typeof at!="string"&&!Nt(at))if(typeof at.toString=="function"){if(at=at.toString(),typeof at!="string")throw Xv("dirty is not a string, aborting")}else throw Xv("toString is not a function");if(!e.isSupported)return at;if(Q||xt(Oe),e.removed=[],typeof at=="string"&&(re=!1),re){if(at.nodeName){const Ue=Be(at.nodeName);if(!W[Ue]||$[Ue])throw Xv("root node is forbidden and cannot be sanitized in-place")}}else if(at instanceof l)lt=We(""),Pe=lt.ownerDocument.importNode(at,!0),Pe.nodeType===Qv.element&&Pe.nodeName==="BODY"||Pe.nodeName==="HTML"?lt=Pe:lt.appendChild(Pe);else{if(!ee&&!me&&!V&&at.indexOf("<")===-1)return P&&ge?P.createHTML(at):at;if(lt=We(at),!lt)return ee?null:ge?N:""}lt&&G&&Vt(lt.firstChild);const Ke=Ft(re?at:lt);for(;Ge=Ke.nextNode();)Wt(Ge),ct(Ge),Ge.content instanceof s&&pt(Ge.content);if(re)return at;if(ee){if(me){lt.normalize();let Ue=lt.innerHTML;Wv([z,X,L],Je=>{Ue=Qb(Ue,Je," ")}),lt.innerHTML=Ue}if(se)for(et=F.call(lt.ownerDocument);lt.firstChild;)et.appendChild(lt.firstChild);else et=lt;return(pe.shadowroot||pe.shadowrootmode)&&(et=D.call(r,et,!0)),et}let Xe=V?lt.outerHTML:lt.innerHTML;return V&&W["!doctype"]&<.ownerDocument&<.ownerDocument.doctype&<.ownerDocument.doctype.name&&Gs(oie,lt.ownerDocument.doctype.name)&&(Xe=" `+Xe),me&&Wv([z,X,L],Ue=>{Xe=Qb(Xe,Ue," ")}),P&&ge?P.createHTML(Xe):Xe},e.setConfig=function(){let at=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};xt(at),Q=!0},e.clearConfig=function(){Ze=null,Q=!1},e.isValidAttribute=function(at,Oe,lt){Ze||xt({});const Pe=Be(at),Ge=Be(Oe);return It(Pe,Ge,lt)},e.addHook=function(at,Oe){typeof Oe=="function"&&Kv(H[at],Oe)},e.removeHook=function(at,Oe){if(Oe!==void 0){const lt=nGe(H[at],Oe);return lt===-1?void 0:rGe(H[at],lt,1)[0]}return mK(H[at])},e.removeHooks=function(at){H[at]=[]},e.removeAllHooks=function(){H=xK()},e}var cie=lie();function ls(t){this.content=t}ls.prototype={constructor:ls,find:function(t){for(var e=0;e>1}};ls.from=function(t){if(t instanceof ls)return t;var e=[];if(t)for(var n in t)e.push(n,t[n]);return new ls(e)};function die(t,e,n){for(let r=0;;r++){if(r==t.childCount||r==e.childCount)return t.childCount==e.childCount?null:n;let i=t.child(r),s=e.child(r);if(i==s){n+=i.nodeSize;continue}if(!i.sameMarkup(s))return n;if(i.isText&&i.text!=s.text){for(let o=0;i.text[o]==s.text[o];o++)n++;return n}if(i.content.size||s.content.size){let o=die(i.content,s.content,n+1);if(o!=null)return o}n+=i.nodeSize}}function uie(t,e,n,r){for(let i=t.childCount,s=e.childCount;;){if(i==0||s==0)return i==s?null:{a:n,b:r};let o=t.child(--i),l=e.child(--s),c=o.nodeSize;if(o==l){n-=c,r-=c;continue}if(!o.sameMarkup(l))return{a:n,b:r};if(o.isText&&o.text!=l.text){let d=0,u=Math.min(o.text.length,l.text.length);for(;de&&r(c,i+l,s||null,o)!==!1&&c.content.size){let u=l+1;c.nodesBetween(Math.max(0,e-u),Math.min(c.content.size,n-u),r,i+u)}l=d}}descendants(e){this.nodesBetween(0,this.size,e)}textBetween(e,n,r,i){let s="",o=!0;return this.nodesBetween(e,n,(l,c)=>{let d=l.isText?l.text.slice(Math.max(e,c)-c,n-c):l.isLeaf?i?typeof i=="function"?i(l):i:l.type.spec.leafText?l.type.spec.leafText(l):"":"";l.isBlock&&(l.isLeaf&&d||l.isTextblock)&&r&&(o?o=!1:s+=r),s+=d},0),s}append(e){if(!e.size)return this;if(!this.size)return e;let n=this.lastChild,r=e.firstChild,i=this.content.slice(),s=0;for(n.isText&&n.sameMarkup(r)&&(i[i.length-1]=n.withText(n.text+r.text),s=1);se)for(let s=0,o=0;oe&&((on)&&(l.isText?l=l.cut(Math.max(0,e-o),Math.min(l.text.length,n-o)):l=l.cut(Math.max(0,e-o-1),Math.min(l.content.size,n-o-1))),r.push(l),i+=l.nodeSize),o=c}return new $t(r,i)}cutByIndex(e,n){return e==n?$t.empty:e==0&&n==this.content.length?this:new $t(this.content.slice(e,n))}replaceChild(e,n){let r=this.content[e];if(r==n)return this;let i=this.content.slice(),s=this.size+n.nodeSize-r.nodeSize;return i[e]=n,new $t(i,s)}addToStart(e){return new $t([e].concat(this.content),this.size+e.nodeSize)}addToEnd(e){return new $t(this.content.concat(e),this.size+e.nodeSize)}eq(e){if(this.content.length!=e.content.length)return!1;for(let n=0;nthis.size||e<0)throw new RangeError(`Position ${e} outside of fragment (${this})`);for(let n=0,r=0;;n++){let i=this.child(n),s=r+i.nodeSize;if(s>=e)return s==e?uk(n+1,s):uk(n,r);r=s}}toString(){return"<"+this.toStringInner()+">"}toStringInner(){return this.content.join(", ")}toJSON(){return this.content.length?this.content.map(e=>e.toJSON()):null}static fromJSON(e,n){if(!n)return $t.empty;if(!Array.isArray(n))throw new RangeError("Invalid input for Fragment.fromJSON");return new $t(n.map(e.nodeFromJSON))}static fromArray(e){if(!e.length)return $t.empty;let n,r=0;for(let i=0;ithis.type.rank&&(n||(n=e.slice(0,i)),n.push(this),r=!0),n&&n.push(s)}}return n||(n=e.slice()),r||n.push(this),n}removeFromSet(e){for(let n=0;nr.type.rank-i.type.rank),n}};sa.none=[];class LC extends Error{}class cn{constructor(e,n,r){this.content=e,this.openStart=n,this.openEnd=r}get size(){return this.content.size-this.openStart-this.openEnd}insertAt(e,n){let r=hie(this.content,e+this.openStart,n);return r&&new cn(r,this.openStart,this.openEnd)}removeBetween(e,n){return new cn(mie(this.content,e+this.openStart,n+this.openStart),this.openStart,this.openEnd)}eq(e){return this.content.eq(e.content)&&this.openStart==e.openStart&&this.openEnd==e.openEnd}toString(){return this.content+"("+this.openStart+","+this.openEnd+")"}toJSON(){if(!this.content.size)return null;let e={content:this.content.toJSON()};return this.openStart>0&&(e.openStart=this.openStart),this.openEnd>0&&(e.openEnd=this.openEnd),e}static fromJSON(e,n){if(!n)return cn.empty;let r=n.openStart||0,i=n.openEnd||0;if(typeof r!="number"||typeof i!="number")throw new RangeError("Invalid input for Slice.fromJSON");return new cn($t.fromJSON(e,n.content),r,i)}static maxOpen(e,n=!0){let r=0,i=0;for(let s=e.firstChild;s&&!s.isLeaf&&(n||!s.type.spec.isolating);s=s.firstChild)r++;for(let s=e.lastChild;s&&!s.isLeaf&&(n||!s.type.spec.isolating);s=s.lastChild)i++;return new cn(e,r,i)}}cn.empty=new cn($t.empty,0,0);function mie(t,e,n){let{index:r,offset:i}=t.findIndex(e),s=t.maybeChild(r),{index:o,offset:l}=t.findIndex(n);if(i==e||s.isText){if(l!=n&&!t.child(o).isText)throw new RangeError("Removing non-flat range");return t.cut(0,e).append(t.cut(n))}if(r!=o)throw new RangeError("Removing non-flat range");return t.replaceChild(r,s.copy(mie(s.content,e-i-1,n-i-1)))}function hie(t,e,n,r){let{index:i,offset:s}=t.findIndex(e),o=t.maybeChild(i);if(s==e||o.isText)return r&&!r.canReplace(i,i,n)?null:t.cut(0,e).append(n).append(t.cut(e));let l=hie(o.content,e-s-1,n,o);return l&&t.replaceChild(i,o.copy(l))}function vGe(t,e,n){if(n.openStart>t.depth)throw new LC("Inserted content deeper than insertion position");if(t.depth-n.openStart!=e.depth-n.openEnd)throw new LC("Inconsistent open depths");return pie(t,e,n,0)}function pie(t,e,n,r){let i=t.index(r),s=t.node(r);if(i==e.index(r)&&r=0&&t.isText&&t.sameMarkup(e[n])?e[n]=t.withText(e[n].text+t.text):e.push(t)}function j0(t,e,n,r){let i=(e||t).node(n),s=0,o=e?e.index(n):i.childCount;t&&(s=t.index(n),t.depth>n?s++:t.textOffset&&($f(t.nodeAfter,r),s++));for(let l=s;li&&xL(t,e,i+1),o=r.depth>i&&xL(n,r,i+1),l=[];return j0(null,t,i,l),s&&o&&e.index(i)==n.index(i)?(fie(s,o),$f(Vf(s,gie(t,e,n,r,i+1)),l)):(s&&$f(Vf(s,OC(t,e,i+1)),l),j0(e,n,i,l),o&&$f(Vf(o,OC(n,r,i+1)),l)),j0(r,null,i,l),new $t(l)}function OC(t,e,n){let r=[];if(j0(null,t,n,r),t.depth>n){let i=xL(t,e,n+1);$f(Vf(i,OC(t,e,n+1)),r)}return j0(e,null,n,r),new $t(r)}function wGe(t,e){let n=e.depth-t.openStart,i=e.node(n).copy(t.content);for(let s=n-1;s>=0;s--)i=e.node(s).copy($t.from(i));return{start:i.resolveNoCache(t.openStart+n),end:i.resolveNoCache(i.content.size-t.openEnd-n)}}class Cw{constructor(e,n,r){this.pos=e,this.path=n,this.parentOffset=r,this.depth=n.length/3-1}resolveDepth(e){return e==null?this.depth:e<0?this.depth+e:e}get parent(){return this.node(this.depth)}get doc(){return this.node(0)}node(e){return this.path[this.resolveDepth(e)*3]}index(e){return this.path[this.resolveDepth(e)*3+1]}indexAfter(e){return e=this.resolveDepth(e),this.index(e)+(e==this.depth&&!this.textOffset?0:1)}start(e){return e=this.resolveDepth(e),e==0?0:this.path[e*3-1]+1}end(e){return e=this.resolveDepth(e),this.start(e)+this.node(e).content.size}before(e){if(e=this.resolveDepth(e),!e)throw new RangeError("There is no position before the top-level node");return e==this.depth+1?this.pos:this.path[e*3-1]}after(e){if(e=this.resolveDepth(e),!e)throw new RangeError("There is no position after the top-level node");return e==this.depth+1?this.pos:this.path[e*3-1]+this.path[e*3].nodeSize}get textOffset(){return this.pos-this.path[this.path.length-1]}get nodeAfter(){let e=this.parent,n=this.index(this.depth);if(n==e.childCount)return null;let r=this.pos-this.path[this.path.length-1],i=e.child(n);return r?e.child(n).cut(r):i}get nodeBefore(){let e=this.index(this.depth),n=this.pos-this.path[this.path.length-1];return n?this.parent.child(e).cut(0,n):e==0?null:this.parent.child(e-1)}posAtIndex(e,n){n=this.resolveDepth(n);let r=this.path[n*3],i=n==0?0:this.path[n*3-1]+1;for(let s=0;s0;n--)if(this.start(n)<=e&&this.end(n)>=e)return n;return 0}blockRange(e=this,n){if(e.pos=0;r--)if(e.pos<=this.end(r)&&(!n||n(this.node(r))))return new IC(this,e,r);return null}sameParent(e){return this.pos-this.parentOffset==e.pos-e.parentOffset}max(e){return e.pos>this.pos?e:this}min(e){return e.pos=0&&n<=e.content.size))throw new RangeError("Position "+n+" out of range");let r=[],i=0,s=n;for(let o=e;;){let{index:l,offset:c}=o.content.findIndex(s),d=s-c;if(r.push(o,l,i+c),!d||(o=o.child(l),o.isText))break;s=d-1,i+=c+1}return new Cw(n,r,s)}static resolveCached(e,n){let r=yK.get(e);if(r)for(let s=0;se&&this.nodesBetween(e,n,s=>(r.isInSet(s.marks)&&(i=!0),!i)),i}get isBlock(){return this.type.isBlock}get isTextblock(){return this.type.isTextblock}get inlineContent(){return this.type.inlineContent}get isInline(){return this.type.isInline}get isText(){return this.type.isText}get isLeaf(){return this.type.isLeaf}get isAtom(){return this.type.isAtom}toString(){if(this.type.spec.toDebugString)return this.type.spec.toDebugString(this);let e=this.type.name;return this.content.size&&(e+="("+this.content.toStringInner()+")"),bie(this.marks,e)}contentMatchAt(e){let n=this.type.contentMatch.matchFragment(this.content,0,e);if(!n)throw new Error("Called contentMatchAt on a node with invalid content");return n}canReplace(e,n,r=$t.empty,i=0,s=r.childCount){let o=this.contentMatchAt(e).matchFragment(r,i,s),l=o&&o.matchFragment(this.content,n);if(!l||!l.validEnd)return!1;for(let c=i;cn.type.name)}`);this.content.forEach(n=>n.check())}toJSON(){let e={type:this.type.name};for(let n in this.attrs){e.attrs=this.attrs;break}return this.content.size&&(e.content=this.content.toJSON()),this.marks.length&&(e.marks=this.marks.map(n=>n.toJSON())),e}static fromJSON(e,n){if(!n)throw new RangeError("Invalid input for Node.fromJSON");let r;if(n.marks){if(!Array.isArray(n.marks))throw new RangeError("Invalid mark data for Node.fromJSON");r=n.marks.map(e.markFromJSON)}if(n.type=="text"){if(typeof n.text!="string")throw new RangeError("Invalid text node in JSON");return e.text(n.text,r)}let i=$t.fromJSON(e,n.content),s=e.nodeType(n.type).create(n.attrs,i,r);return s.type.checkAttrs(s.attrs),s}}qc.prototype.text=void 0;class zC extends qc{constructor(e,n,r,i){if(super(e,n,null,i),!r)throw new RangeError("Empty text nodes are not allowed");this.text=r}toString(){return this.type.spec.toDebugString?this.type.spec.toDebugString(this):bie(this.marks,JSON.stringify(this.text))}get textContent(){return this.text}textBetween(e,n){return this.text.slice(e,n)}get nodeSize(){return this.text.length}mark(e){return e==this.marks?this:new zC(this.type,this.attrs,this.text,e)}withText(e){return e==this.text?this:new zC(this.type,this.attrs,e,this.marks)}cut(e=0,n=this.text.length){return e==0&&n==this.text.length?this:this.withText(this.text.slice(e,n))}eq(e){return this.sameMarkup(e)&&this.text==e.text}toJSON(){let e=super.toJSON();return e.text=this.text,e}}function bie(t,e){for(let n=t.length-1;n>=0;n--)e=t[n].type.name+"("+e+")";return e}class xg{constructor(e){this.validEnd=e,this.next=[],this.wrapCache=[]}static parse(e,n){let r=new NGe(e,n);if(r.next==null)return xg.empty;let i=xie(r);r.next&&r.err("Unexpected trailing text");let s=EGe(MGe(i));return DGe(s,r),s}matchType(e){for(let n=0;nd.createAndFill()));for(let d=0;d=this.next.length)throw new RangeError(`There's no ${e}th edge in this content match`);return this.next[e]}toString(){let e=[];function n(r){e.push(r);for(let i=0;i{let s=i+(r.validEnd?"*":" ")+" ";for(let o=0;o"+e.indexOf(r.next[o].next);return s}).join(` `)}}xg.empty=new xg(!0);class NGe{constructor(e,n){this.string=e,this.nodeTypes=n,this.inline=null,this.pos=0,this.tokens=e.split(/\s*(?=\b|\W|$)/),this.tokens[this.tokens.length-1]==""&&this.tokens.pop(),this.tokens[0]==""&&this.tokens.shift()}get next(){return this.tokens[this.pos]}eat(e){return this.next==e&&(this.pos++||!0)}err(e){throw new SyntaxError(e+" (in content expression '"+this.string+"')")}}function xie(t){let e=[];do e.push(CGe(t));while(t.eat("|"));return e.length==1?e[0]:{type:"choice",exprs:e}}function CGe(t){let e=[];do e.push(PGe(t));while(t.next&&t.next!=")"&&t.next!="|");return e.length==1?e[0]:{type:"seq",exprs:e}}function PGe(t){let e=jGe(t);for(;;)if(t.eat("+"))e={type:"plus",expr:e};else if(t.eat("*"))e={type:"star",expr:e};else if(t.eat("?"))e={type:"opt",expr:e};else if(t.eat("{"))e=TGe(t,e);else break;return e}function vK(t){/\D/.test(t.next)&&t.err("Expected number, got '"+t.next+"'");let e=Number(t.next);return t.pos++,e}function TGe(t,e){let n=vK(t),r=n;return t.eat(",")&&(t.next!="}"?r=vK(t):r=-1),t.eat("}")||t.err("Unclosed braced range"),{type:"range",min:n,max:r,expr:e}}function AGe(t,e){let n=t.nodeTypes,r=n[e];if(r)return[r];let i=[];for(let s in n){let o=n[s];o.isInGroup(e)&&i.push(o)}return i.length==0&&t.err("No node type or group '"+e+"' found"),i}function jGe(t){if(t.eat("(")){let e=xie(t);return t.eat(")")||t.err("Missing closing paren"),e}else if(/\W/.test(t.next))t.err("Unexpected token '"+t.next+"'");else{let e=AGe(t,t.next).map(n=>(t.inline==null?t.inline=n.isInline:t.inline!=n.isInline&&t.err("Mixing inline and block content"),{type:"name",value:n}));return t.pos++,e.length==1?e[0]:{type:"choice",exprs:e}}}function MGe(t){let e=[[]];return i(s(t,0),n()),e;function n(){return e.push([])-1}function r(o,l,c){let d={term:c,to:l};return e[o].push(d),d}function i(o,l){o.forEach(c=>c.to=l)}function s(o,l){if(o.type=="choice")return o.exprs.reduce((c,d)=>c.concat(s(d,l)),[]);if(o.type=="seq")for(let c=0;;c++){let d=s(o.exprs[c],l);if(c==o.exprs.length-1)return d;i(d,l=n())}else if(o.type=="star"){let c=n();return r(l,c),i(s(o.expr,c),c),[r(c)]}else if(o.type=="plus"){let c=n();return i(s(o.expr,l),c),i(s(o.expr,c),c),[r(c)]}else{if(o.type=="opt")return[r(l)].concat(s(o.expr,l));if(o.type=="range"){let c=l;for(let d=0;d{t[o].forEach(({term:l,to:c})=>{if(!l)return;let d;for(let u=0;u{d||i.push([l,d=[]]),d.indexOf(u)==-1&&d.push(u)})})});let s=e[r.join(",")]=new xg(r.indexOf(t.length-1)>-1);for(let o=0;o-1}get whitespace(){return this.spec.whitespace||(this.spec.code?"pre":"normal")}hasRequiredAttrs(){for(let e in this.attrs)if(this.attrs[e].isRequired)return!0;return!1}compatibleContent(e){return this==e||this.contentMatch.compatible(e.contentMatch)}computeAttrs(e){return!e&&this.defaultAttrs?this.defaultAttrs:wie(this.attrs,e)}create(e=null,n,r){if(this.isText)throw new Error("NodeType.create can't construct text nodes");return new qc(this,this.computeAttrs(e),$t.from(n),sa.setFrom(r))}createChecked(e=null,n,r){return n=$t.from(n),this.checkContent(n),new qc(this,this.computeAttrs(e),n,sa.setFrom(r))}createAndFill(e=null,n,r){if(e=this.computeAttrs(e),n=$t.from(n),n.size){let o=this.contentMatch.fillBefore(n);if(!o)return null;n=o.append(n)}let i=this.contentMatch.matchFragment(n),s=i&&i.fillBefore($t.empty,!0);return s?new qc(this,e,n.append(s),sa.setFrom(r)):null}validContent(e){let n=this.contentMatch.matchFragment(e);if(!n||!n.validEnd)return!1;for(let r=0;r-1}allowsMarks(e){if(this.markSet==null)return!0;for(let n=0;nr[s]=new kie(s,n,o));let i=n.spec.topNode||"doc";if(!r[i])throw new RangeError("Schema is missing its top node type ('"+i+"')");if(!r.text)throw new RangeError("Every schema needs a 'text' type");for(let s in r.text.attrs)throw new RangeError("The text node type should not have attributes");return r}};function FGe(t,e,n){let r=n.split("|");return i=>{let s=i===null?"null":typeof i;if(r.indexOf(s)<0)throw new RangeError(`Expected value of type ${r} for attribute ${e} on type ${t}, got ${s}`)}}class RGe{constructor(e,n,r){this.hasDefault=Object.prototype.hasOwnProperty.call(r,"default"),this.default=r.default,this.validate=typeof r.validate=="string"?FGe(e,n,r.validate):r.validate}get isRequired(){return!this.hasDefault}}class KT{constructor(e,n,r,i){this.name=e,this.rank=n,this.schema=r,this.spec=i,this.attrs=_ie(e,i.attrs),this.excluded=null;let s=vie(this.attrs);this.instance=s?new sa(this,s):null}create(e=null){return!e&&this.instance?this.instance:new sa(this,wie(this.attrs,e))}static compile(e,n){let r=Object.create(null),i=0;return e.forEach((s,o)=>r[s]=new KT(s,i++,n,o)),r}removeFromSet(e){for(var n=0;n-1}}class Nie{constructor(e){this.linebreakReplacement=null,this.cached=Object.create(null);let n=this.spec={};for(let i in e)n[i]=e[i];n.nodes=ls.from(e.nodes),n.marks=ls.from(e.marks||{}),this.nodes=SK.compile(this.spec.nodes,this),this.marks=KT.compile(this.spec.marks,this);let r=Object.create(null);for(let i in this.nodes){if(i in this.marks)throw new RangeError(i+" can not be both a node and a mark");let s=this.nodes[i],o=s.spec.content||"",l=s.spec.marks;if(s.contentMatch=r[o]||(r[o]=xg.parse(o,this.nodes)),s.inlineContent=s.contentMatch.inlineContent,s.spec.linebreakReplacement){if(this.linebreakReplacement)throw new RangeError("Multiple linebreak nodes defined");if(!s.isInline||!s.isLeaf)throw new RangeError("Linebreak replacement nodes must be inline leaf nodes");this.linebreakReplacement=s}s.markSet=l=="_"?null:l?_K(this,l.split(" ")):l==""||!s.inlineContent?[]:null}for(let i in this.marks){let s=this.marks[i],o=s.spec.excludes;s.excluded=o==null?[s]:o==""?[]:_K(this,o.split(" "))}this.nodeFromJSON=i=>qc.fromJSON(this,i),this.markFromJSON=i=>sa.fromJSON(this,i),this.topNodeType=this.nodes[this.spec.topNode||"doc"],this.cached.wrappings=Object.create(null)}node(e,n=null,r,i){if(typeof e=="string")e=this.nodeType(e);else if(e instanceof SK){if(e.schema!=this)throw new RangeError("Node type from different schema used ("+e.name+")")}else throw new RangeError("Invalid node type: "+e);return e.createChecked(n,r,i)}text(e,n){let r=this.nodes.text;return new zC(r,r.defaultAttrs,e,sa.setFrom(n))}mark(e,n){return typeof e=="string"&&(e=this.marks[e]),e.create(n)}nodeType(e){let n=this.nodes[e];if(!n)throw new RangeError("Unknown node type: "+e);return n}}function _K(t,e){let n=[];for(let r=0;r-1)&&n.push(o=c)}if(!o)throw new SyntaxError("Unknown mark type: '"+e[r]+"'")}return n}function LGe(t){return t.tag!=null}function OGe(t){return t.style!=null}let M0=class yL{constructor(e,n){this.schema=e,this.rules=n,this.tags=[],this.styles=[];let r=this.matchedStyles=[];n.forEach(i=>{if(LGe(i))this.tags.push(i);else if(OGe(i)){let s=/[^=]*/.exec(i.style)[0];r.indexOf(s)<0&&r.push(s),this.styles.push(i)}}),this.normalizeLists=!this.tags.some(i=>{if(!/^(ul|ol)\b/.test(i.tag)||!i.node)return!1;let s=e.nodes[i.node];return s.contentMatch.matchType(s)})}parse(e,n={}){let r=new NK(this,n,!1);return r.addAll(e,sa.none,n.from,n.to),r.finish()}parseSlice(e,n={}){let r=new NK(this,n,!0);return r.addAll(e,sa.none,n.from,n.to),cn.maxOpen(r.finish())}matchTag(e,n,r){for(let i=r?this.tags.indexOf(r)+1:0;ie.length&&(l.charCodeAt(e.length)!=61||l.slice(e.length+1)!=n))){if(o.getAttrs){let c=o.getAttrs(n);if(c===!1)continue;o.attrs=c||void 0}return o}}}static schemaRules(e){let n=[];function r(i){let s=i.priority==null?50:i.priority,o=0;for(;o{r(o=CK(o)),o.mark||o.ignore||o.clearMark||(o.mark=i)})}for(let i in e.nodes){let s=e.nodes[i].spec.parseDOM;s&&s.forEach(o=>{r(o=CK(o)),o.node||o.ignore||o.mark||(o.node=i)})}return n}static fromSchema(e){return e.cached.domParser||(e.cached.domParser=new yL(e,yL.schemaRules(e)))}};const Cie={address:!0,article:!0,aside:!0,blockquote:!0,canvas:!0,dd:!0,div:!0,dl:!0,fieldset:!0,figcaption:!0,figure:!0,footer:!0,form:!0,h1:!0,h2:!0,h3:!0,h4:!0,h5:!0,h6:!0,header:!0,hgroup:!0,hr:!0,li:!0,noscript:!0,ol:!0,output:!0,p:!0,pre:!0,section:!0,table:!0,tfoot:!0,ul:!0},IGe={head:!0,noscript:!0,object:!0,script:!0,style:!0,title:!0},Pie={ol:!0,ul:!0},Pw=1,vL=2,E0=4;function kK(t,e,n){return e!=null?(e?Pw:0)|(e==="full"?vL:0):t&&t.whitespace=="pre"?Pw|vL:n&~E0}class mk{constructor(e,n,r,i,s,o){this.type=e,this.attrs=n,this.marks=r,this.solid=i,this.options=o,this.content=[],this.activeMarks=sa.none,this.match=s||(o&E0?null:e.contentMatch)}findWrapping(e){if(!this.match){if(!this.type)return[];let n=this.type.contentMatch.fillBefore($t.from(e));if(n)this.match=this.type.contentMatch.matchFragment(n);else{let r=this.type.contentMatch,i;return(i=r.findWrapping(e.type))?(this.match=r,i):null}}return this.match.findWrapping(e.type)}finish(e){if(!(this.options&Pw)){let r=this.content[this.content.length-1],i;if(r&&r.isText&&(i=/[ \t\r\n\u000c]+$/.exec(r.text))){let s=r;r.text.length==i[0].length?this.content.pop():this.content[this.content.length-1]=s.withText(s.text.slice(0,s.text.length-i[0].length))}}let n=$t.from(this.content);return!e&&this.match&&(n=n.append(this.match.fillBefore($t.empty,!0))),this.type?this.type.create(this.attrs,n,this.marks):n}inlineContext(e){return this.type?this.type.inlineContent:this.content.length?this.content[0].isInline:e.parentNode&&!Cie.hasOwnProperty(e.parentNode.nodeName.toLowerCase())}}class NK{constructor(e,n,r){this.parser=e,this.options=n,this.isOpen=r,this.open=0,this.localPreserveWS=!1;let i=n.topNode,s,o=kK(null,n.preserveWhitespace,0)|(r?E0:0);i?s=new mk(i.type,i.attrs,sa.none,!0,n.topMatch||i.type.contentMatch,o):r?s=new mk(null,null,sa.none,!0,null,o):s=new mk(e.schema.topNodeType,null,sa.none,!0,null,o),this.nodes=[s],this.find=n.findPositions,this.needsBlock=!1}get top(){return this.nodes[this.open]}addDOM(e,n){e.nodeType==3?this.addTextNode(e,n):e.nodeType==1&&this.addElement(e,n)}addTextNode(e,n){let r=e.nodeValue,i=this.top,s=i.options&vL?"full":this.localPreserveWS||(i.options&Pw)>0,{schema:o}=this.parser;if(s==="full"||i.inlineContext(e)||/[^ \t\r\n\u000c]/.test(r)){if(s)if(s==="full")r=r.replace(/\r\n?/g,` `);else if(o.linebreakReplacement&&/[\r\n]/.test(r)&&this.top.findWrapping(o.linebreakReplacement.create())){let l=r.split(/\r?\n|\r/);for(let c=0;c - +