From bf2b34ebcfec384f99afa2505e6273c6e1250472 Mon Sep 17 00:00:00 2001 From: maziggy Date: Tue, 12 May 2026 07:37:13 +0200 Subject: [PATCH] fix(ui): round smart-plug live wattage on printer card (#1266) Plugs reporting fractional watts (Kauf PLF12 / ESPHome via MQTT) overflowed the card width. SmartPlugCard and SwitchbarPopover already round the same field; only the printer-card badge was raw. --- CHANGELOG.md | 3 ++- frontend/src/pages/PrintersPage.tsx | 2 +- static/assets/{index-V-aY7Bt-.js => index-J0xD4Xg0.js} | 2 +- static/index.html | 2 +- 4 files changed, 5 insertions(+), 4 deletions(-) rename static/assets/{index-V-aY7Bt-.js => index-J0xD4Xg0.js} (97%) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4d2056ae1..2507fd108 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +4,8 @@ All notable changes to Bambuddy will be documented in this file. ## [0.2.5b1] - Unreleased -## [0.2.4] - 2026-05-11 +### Fixed +- **Printer card: smart-plug live wattage now rounded to whole watts** ([#1266](https://github.com/maziggy/bambuddy/issues/1266), reported by @Carter3DP) — The printer card's smart-plug status badge rendered `plugStatus.energy.power` raw, so plugs that report fractional watts (Kauf PLF12 via ESPHome / Home Assistant in the reporter's case, but any MQTT plug pushing a float can hit this) showed values like `14.123456789012` W and overflowed the card width. `SmartPlugCard` and `SwitchbarPopover` already wrapped the same field in `Math.round()`; only the printer-card badge was missing the round. Single-line fix at `frontend/src/pages/PrintersPage.tsx:4569`. ### Added - **Build-plate icon on archive cards + uniform printer/model line** ([#1253](https://github.com/maziggy/bambuddy/issues/1253), reported by @tonygauderman) — Archive cards now show an OrcaSlicer-style bed icon in the printer/model row indicating which build plate the print was sliced for (Cool / Cool SuperTack / Engineering / High Temp / Textured PEI / Smooth PEI), with the full plate name in the hover tooltip. Closes the gap where users had to remember which plate matched a re-print or open the source 3MF in a slicer just to read the bed setting. **Card row also unified:** archives with a real Bambuddy-printer association used to render as `H2D-1 GCODE …` while slicer-only uploads rendered as `Sliced for X1C GCODE …` — same line, two different shapes. Dropped the `Sliced for ` prefix so both render as a uniform ` [bed-icon] GCODE ` row, scanning the same regardless of provenance. **Backend:** new `bed_type` column on `print_archives` (idempotent `ALTER TABLE` migration; SQLite + Postgres safe), populated from `curr_bed_type` in `Metadata/slice_info.config` (per-plate metadata, the authoritative source — that's the bed type that actually got sent to the printer for the exported plate) with a fallback to `Metadata/project_settings.config`'s top-level `curr_bed_type` for older 3MF shapes. Wired through both code paths that produce archive responses: `archive_to_response()` (the hand-rolled dict converter at `archives.py:97` — easy to miss, the schema-only change is silently dropped by Pydantic since the route bypasses `from_attributes`) and the `/rescan` endpoint, so old archives can be re-parsed by the user via the existing per-archive Rescan button. Newly-ingested archives get the value automatically. **Backfill script:** `scripts/backfill_archive_bed_type.py` (with `--dry-run`) re-opens every NULL archive's 3MF on disk and populates the column — opt-in for users who want their entire history covered without waiting for natural turnover. Auto-loads `.env` from project root *before* importing backend modules (since `core/config.py:52` reads `DATABASE_URL` from `os.environ` at import time, not from `pydantic-settings` at `Settings()` time), prints the resolved DB URL with credentials redacted on every run so operators can confirm they're hitting the intended database (Postgres / SQLite — Bambuddy supports both per #1219's `DATABASE_URL` pathway), and calls `init_db()` itself before querying so the migration applies even if the script is run against a database the backend hasn't touched yet. **Frontend:** 6 OrcaSlicer-style PNGs ship in `frontend/public/img/bed/` (under `/img/` because that path was already statically mounted at `main.py:5244`; the `/bed-icons/` toplevel attempted first hit the SPA catch-all and returned `index.html` as `text/html`, which the browser then rendered nothing for). New `utils/bedType.ts` maps slicer strings (case-insensitive) to icon + human-readable label; covers Bambu Studio and OrcaSlicer's diverging spellings for the same physical plate (e.g. `Cool Plate` ↔ `PC Plate`, `Cool Plate (SuperTack)` ↔ `Supertack Plate` ↔ `Bambu Cool Plate SuperTack`). Renders on both card-grid view and list view in `ArchivesPage.tsx`. Unmapped or NULL `bed_type` simply omits the icon, so cards stay clean for archives created before this change. Note on icon mapping: `bed_pei.png` → Textured PEI, `bed_pei_cool.png` → Smooth PEI is a best-guess from the OrcaSlicer asset names — swap the two paths in `bedType.ts` if a future user reports the icons reversed for their plate. diff --git a/frontend/src/pages/PrintersPage.tsx b/frontend/src/pages/PrintersPage.tsx index 6d22a1ac2..f637ec712 100644 --- a/frontend/src/pages/PrintersPage.tsx +++ b/frontend/src/pages/PrintersPage.tsx @@ -4566,7 +4566,7 @@ function PrinterCard({ > {plugStatus.state || '?'} {plugStatus.state === 'ON' && plugStatus.energy?.power != null && ( - · {plugStatus.energy.power}W + · {Math.round(plugStatus.energy.power)}W )} )} diff --git a/static/assets/index-V-aY7Bt-.js b/static/assets/index-J0xD4Xg0.js similarity index 97% rename from static/assets/index-V-aY7Bt-.js rename to static/assets/index-J0xD4Xg0.js index 02b077ed7..e39af9d8d 100644 --- a/static/assets/index-V-aY7Bt-.js +++ b/static/assets/index-J0xD4Xg0.js @@ -8541,7 +8541,7 @@ ${l("inventory.assignProfileMismatchMessage",{spoolProfile:T.spoolProfile||l("co flex items-center justify-center gap-1 px-3 py-1.5 rounded-lg text-xs font-medium transition-colors ${an&&H("printers:control")?$t?"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:H("printers:control")?S($t?"printers.resume":"printers.pause"):S("printers.permission.noControl"),children:[$t?r.jsx(fs,{className:"w-3 h-3"}):r.jsx(AS,{className:"w-3 h-3"}),S($t?"printers.resume":"printers.pause")]})]})]})]})})(),(bd?.length>0||qe.vt_tray.length>0)&&a==="expanded"&&(()=>{const lt=bd.filter(ht=>ht.tray.length>1),$t=bd.filter(ht=>ht.tray.length===1),an=t.nozzle_count===2||qe?.temperatures?.nozzle_2!==void 0;return r.jsxs("div",{className:"mt-3",children:[r.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[r.jsx("span",{className:"text-[10px] uppercase tracking-wider text-bambu-gray font-medium",children:S("printers.filaments")}),r.jsx("div",{className:"flex-1 h-px bg-bambu-dark-tertiary/30"})]}),r.jsxs("div",{className:"space-y-3",children:[lt.length>0&&r.jsx("div",{className:"grid grid-cols-2 gap-3",children:lt.map(ht=>{const Un=Ki[String(ht.id)],kr=ht.id>=128?ht.id-128:ht.id,Hn=Un!==void 0?Un:kr,ya=Hn===1,va=Hn===0;return r.jsxs("div",{className:"p-2.5 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary/30",children:[r.jsxs("div",{className:"flex items-center justify-between mb-2",children:[r.jsxs("div",{className:"flex items-center gap-1.5",children:[r.jsx(WK,{ams:ht,printerId:t.id,label:$o(ht.id,ht.tray.length),amsLabels:Er,canEdit:H("printers:update"),onSaved:zn,children:r.jsx("span",{className:"text-[10px] text-white font-medium cursor-default select-none",children:Er?.[ht.id]||$o(ht.id,ht.tray.length)})}),an&&(ya||va)&&r.jsx(BK,{side:ya?"L":"R"})]}),(ht.humidity!=null||ht.temp!=null)&&r.jsxs("div",{className:"flex items-center gap-1.5 max-[550px]:flex-col max-[550px]:items-start",children:[ht.humidity!=null&&r.jsx(qK,{humidity:ht.humidity,goodThreshold:s?.humidityGood,fairThreshold:s?.humidityFair,onClick:()=>at({amsId:ht.id,amsLabel:$o(ht.id,ht.tray.length),mode:"humidity"}),compact:!0}),ht.temp!=null&&r.jsx($K,{temp:ht.temp,goodThreshold:s?.tempGood,fairThreshold:s?.tempFair,onClick:()=>at({amsId:ht.id,amsLabel:$o(ht.id,ht.tray.length),mode:"temperature"}),compact:!0}),qe.supports_drying&&(ht.module_type==="n3f"||ht.module_type==="n3s")&&H("printers:control")&&r.jsx("button",{disabled:!!(ht.dry_sf_reason?.length&&ht.dry_time===0),onClick:tn=>{if(ht.dry_time>0)Qr.mutate(ht.id);else if(Re===ht.id)tt(null);else{const Ca=(ht.tray.find(ul=>ul.tray_type)?.tray_type||"PLA").split(" ")[0].toUpperCase(),Qa=C[Ca]||C.PLA,Zi=ht.module_type;fe(Ca),$e(Qa[Zi]||Qa.n3f),nt(Zi==="n3s"?Qa.n3s_hours:Qa.n3f_hours),yt(!1),Xe(ht.module_type),tt(ht.id);const Bl=tn.currentTarget.getBoundingClientRect();Ht({top:Bl.bottom+4,left:Math.max(8,Bl.right-240)})}},className:`flex items-center gap-0.5 px-1 py-0.5 rounded text-[9px] transition-colors ${ht.dry_time>0?"bg-amber-500/20 text-amber-400":ht.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:ht.dry_time>0?S("printers.drying.stop"):ht.dry_sf_reason?.length?S("printers.drying.powerRequired"):S("printers.drying.start"),children:r.jsx(mm,{className:"w-3 h-3"})})]})]}),ht.dry_time>0&&r.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:[r.jsx(mm,{className:"w-3 h-3 text-amber-400 shrink-0"}),r.jsx("span",{className:"text-amber-400 font-medium",children:S("printers.drying.active")}),r.jsx("span",{className:"text-amber-300/70",children:S("printers.drying.timeRemaining",{time:ht.dry_time>=60?`${Math.floor(ht.dry_time/60)}h ${ht.dry_time%60}m`:`${ht.dry_time}m`})}),r.jsx("button",{onClick:()=>Qr.mutate(ht.id),disabled:Qr.isPending,className:"ml-auto text-amber-400 hover:text-amber-300 transition-colors disabled:opacity-50",title:S("printers.drying.stop"),children:r.jsx(Bt,{className:"w-3 h-3"})})]}),r.jsx("div",{className:"grid grid-cols-4 gap-1.5",children:[0,1,2,3].map(tn=>{const Tn=ht.tray[tn]||ht.tray.find(sn=>sn.id===tn),Ca=Tn?.tray_type&&Tn.remain>=0,Qa=!Tn?.tray_type,Zi=ht.id*4+tn,Bl=Ft===Zi,ul=Tn?.tray_info_idx?wn?.[Tn.tray_info_idx]:null,wa=bn?.[Zi],Ss=(Tn?.tray_uuid||Tn?.tag_uid||fm(t.serial_number,ht.id,tn))?.toUpperCase(),gi=Ss?l?.[Ss]:void 0,Cd=MN(gi),_s=o&&!b?f?.find(sn=>sn.printer_id===t.id&&sn.ams_id===ht.id&&sn.tray_id===tn):void 0,qr=_s?p?.find(sn=>sn.id===_s.spoolman_spool_id):void 0,Ha=qr&&(qr.label_weight??0)>0?Math.round(Math.max(0,(qr.label_weight??0)-qr.weight_used)/(qr.label_weight??1)*100):null,Ji=u?.(t.id,ht.id,tn),Fi=(()=>{const sn=Ji?.spool;return sn&&sn.label_weight>0&&sn.weight_used!=null?Math.round(Math.max(0,sn.label_weight-sn.weight_used)/sn.label_weight*100):null})(),zc=Fi===0&&Ca&&Tn.remain>0?null:Fi,ks=Cd??Ha??zc??(Ca?Tn.remain:null),dr=Cd!==null||Ha!==null?"spoolman":zc!==null?"inventory":Ca?"ams":void 0,$r=Tn?.tray_type?{vendor:Qs(Tn)?"Bambu Lab":"Generic",profile:wa?.preset_name||(qr?[qr.brand,qr.slicer_filament_name?.split("@")[0].trim()||qr.material].filter(Boolean).join(" ").trim():null)||Ji?.spool?.slicer_filament_name||ul?.name||Tn.tray_sub_brands||Tn.tray_type,colorName:yc(Tn.tray_color||""),colorHex:Tn.tray_color||null,kFactor:m3(Tn.k),fillLevel:ks,trayUuid:Tn.tray_uuid||null,tagUid:Tn.tag_uid||null,fillSource:dr}:null,Pa=Ro?.amsId===ht.id&&Ro?.slotId===tn,ju=r.jsxs("div",{className:`bg-bambu-dark-tertiary rounded p-1 text-center ${Qa?"opacity-50":""} ${Bl?"ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark":""}`,children:[r.jsx(u3,{trayColor:Tn?.tray_color,trayType:Tn?.tray_type,isEmpty:Qa,slotNumber:tn+1}),r.jsx("div",{className:"text-[9px] text-white font-bold truncate",children:Tn?.tray_type||"—"}),r.jsx("div",{className:"mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden",children:ks!==null&&ks>=0&&!Qa&&Tn&&r.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${ks}%`,backgroundColor:dy(ks)}})})]});return r.jsxs("div",{className:"relative group",children:[Pa&&r.jsx("div",{className:"absolute inset-0 bg-bambu-dark-tertiary/80 rounded flex items-center justify-center z-20",children:r.jsx(sr,{className:"w-4 h-4 text-bambu-green animate-spin"})}),qe?.state!=="RUNNING"&&r.jsx("button",{onClick:sn=>{sn.stopPropagation(),fi(Qi?.amsId===ht.id&&Qi?.slotId===tn?null:{amsId:ht.id,slotId:tn})},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:S("printers.slotOptions"),children:r.jsx(ym,{className:"w-2.5 h-2.5 text-bambu-gray"})}),qe?.state!=="RUNNING"&&Qi?.amsId===ht.id&&Qi?.slotId===tn&&r.jsxs("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:[r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-xs flex items-center gap-2 ${H("printers:ams_rfid")?"text-white hover:bg-bambu-dark-tertiary":"text-bambu-gray/50 cursor-not-allowed"}`,onClick:sn=>{sn.stopPropagation(),H("printers:ams_rfid")&&(Pu.mutate({amsId:ht.id,slotId:tn}),fi(null))},disabled:Pa||!H("printers:ams_rfid"),title:H("printers:ams_rfid")?void 0:S("printers.permission.noAmsRfid"),children:[r.jsx(sr,{className:`w-3 h-3 ${Pa?"animate-spin":""}`}),S("printers.rfid.reread")]}),r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-xs flex items-center gap-2 ${H("printers:control")?"text-white hover:bg-bambu-dark-tertiary":"text-bambu-gray/50 cursor-not-allowed"}`,onClick:sn=>{sn.stopPropagation(),H("printers:control")&&(Tu.mutate({trayId:ht.id*4+tn}),fi(null))},disabled:!H("printers:control"),title:H("printers:control")?void 0:S("printers.permission.noControl"),children:[r.jsx(K0,{className:"w-3 h-3"}),S("printers.ams.load")]}),r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-xs flex items-center gap-2 ${H("printers:control")?"text-white hover:bg-bambu-dark-tertiary":"text-bambu-gray/50 cursor-not-allowed"}`,onClick:sn=>{sn.stopPropagation(),H("printers:control")&&(_n.mutate(),fi(null))},disabled:!H("printers:control"),title:H("printers:control")?void 0:S("printers.permission.noControl"),children:[r.jsx(Jx,{className:"w-3 h-3"}),S("printers.ams.unload")]})]}),$r?r.jsx(s3,{data:$r,spoolman:{enabled:o,linkedSpoolId:(Ss?l?.[Ss]?.id:void 0)??_s?.spoolman_spool_id,spoolmanUrl:c,syncMode:d,onLinkSpool:o&&!_s&&!Ji?()=>{const sn=($r.trayUuid||$r.tagUid||fm(t.serial_number,ht.id,tn)).toUpperCase();_t({tagUid:$r.tagUid||sn,trayUuid:$r.trayUuid||"",printerId:t.id,amsId:ht.id,trayId:tn})}:void 0,onUnlinkSpool:gi?.id?()=>Ic.mutate(gi.id):void 0},inventory:(()=>{if(o){if(b)return;const pp=_s,ua=qr;return{assignedSpool:ua?{id:ua.id,material:ua.material,brand:ua.brand??null,color_name:ua.color_name??null,remainingWeightGrams:ua.label_weight?Math.max(0,Math.round(ua.label_weight-ua.weight_used)):void 0}:null,onAssignSpool:()=>De({printerId:t.id,amsId:ht.id,trayId:tn,trayInfo:{type:Tn?.tray_type||$r.profile,material:Tn?.tray_type??void 0,profile:$r.profile,color:$r.colorHex||"",location:`${$o(ht.id,ht.tray.length)} Slot ${tn+1}`}}),onUnassignSpool:ua&&!Qs(Tn)?()=>w?.(ua.id):void 0,isAssigned:!!pp||Qs(Tn)}}const sn=u?.(t.id,ht.id,tn);return{assignedSpool:sn?.spool?{id:sn.spool.id,material:sn.spool.material,brand:sn.spool.brand,color_name:sn.spool.color_name,remainingWeightGrams:Math.max(0,Math.round(sn.spool.label_weight-sn.spool.weight_used))}:null,onAssignSpool:()=>De({printerId:t.id,amsId:ht.id,trayId:tn,trayInfo:{type:Tn?.tray_type||$r.profile,material:Tn?.tray_type??void 0,profile:$r.profile,color:$r.colorHex||"",location:`${$o(ht.id,ht.tray.length)} Slot ${tn+1}`}}),onUnassignSpool:sn&&!Qs(Tn)?()=>m?.(t.id,ht.id,tn):void 0,isAssigned:!!sn||Qs(Tn)}})(),configureSlot:{enabled:H("printers:control"),onConfigure:()=>Ve({amsId:ht.id,trayId:tn,trayCount:ht.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:Un,caliIdx:Tn?.cali_idx,savedPresetId:wa?.preset_id})},children:ju}):r.jsx(o3,{configureSlot:{enabled:H("printers:control"),onConfigure:()=>Ve({amsId:ht.id,trayId:tn,trayCount:ht.tray.length,extruderId:Un})},onAssignSpool:()=>De({printerId:t.id,amsId:ht.id,trayId:tn,trayInfo:{type:"",material:void 0,profile:"",color:"",location:`${$o(ht.id,ht.tray.length)} Slot ${tn+1}`}}),children:ju})]},tn)})})]},ht.id)})}),($t.length>0||qe.vt_tray.length>0)&&r.jsxs("div",{className:"grid grid-cols-4 gap-3",children:[$t.map(ht=>{const Un=Ki[String(ht.id)],kr=ht.id>=128?ht.id-128:ht.id,Hn=Un!==void 0?Un:kr,ya=Hn===1,va=Hn===0,tn=ht.tray[0],Tn=tn?.tray_type&&tn.remain>=0,Ca=!tn?.tray_type,Qa=Xg(ht.id,tn?.id??0,!1),Zi=Ft===Qa,Bl=tn?.tray_info_idx?wn?.[tn.tray_info_idx]:null,ul=bn?.[Qa],wa=tn?.id??0,Ss=(tn?.tray_uuid||tn?.tag_uid||fm(t.serial_number,ht.id,wa))?.toUpperCase(),gi=Ss?l?.[Ss]:void 0,Cd=MN(gi),_s=u?.(t.id,ht.id,wa),qr=(()=>{const sn=_s?.spool;return sn&&sn.label_weight>0&&sn.weight_used!=null?Math.round(Math.max(0,sn.label_weight-sn.weight_used)/sn.label_weight*100):null})(),Ha=qr===0&&Tn&&tn.remain>0?null:qr,Ji=o&&!b?f?.find(sn=>sn.printer_id===t.id&&sn.ams_id===ht.id&&sn.tray_id===wa):void 0,Fi=Ji?p?.find(sn=>sn.id===Ji.spoolman_spool_id):void 0,zc=Fi&&(Fi.label_weight??0)>0?Math.round(Math.max(0,(Fi.label_weight??0)-Fi.weight_used)/(Fi.label_weight??1)*100):null,ks=Cd??zc??Ha??(Tn?tn.remain:null),dr=Cd!==null||zc!==null?"spoolman":Ha!==null?"inventory":Tn?"ams":void 0,$r=tn?.tray_type?{vendor:Qs(tn)?"Bambu Lab":"Generic",profile:ul?.preset_name||(Fi?[Fi.brand,Fi.slicer_filament_name?.split("@")[0].trim()||Fi.material].filter(Boolean).join(" ").trim():null)||_s?.spool?.slicer_filament_name||Bl?.name||tn.tray_sub_brands||tn.tray_type,colorName:yc(tn.tray_color||""),colorHex:tn.tray_color||null,kFactor:m3(tn.k),fillLevel:ks,trayUuid:tn.tray_uuid||null,tagUid:tn.tag_uid||null,fillSource:dr}:null,Pa=Ro?.amsId===ht.id&&Ro?.slotId===wa,ju=r.jsxs("div",{className:`bg-bambu-dark-tertiary rounded p-1 text-center ${Ca?"opacity-50":""} ${Zi?"ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark":""}`,children:[r.jsx(u3,{trayColor:tn?.tray_color,trayType:tn?.tray_type,isEmpty:Ca,slotNumber:1}),r.jsx("div",{className:"text-[9px] text-white font-bold truncate",children:tn?.tray_type||"—"}),r.jsx("div",{className:"mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden",children:ks!==null&&ks>=0&&!Ca&&r.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${ks}%`,backgroundColor:dy(ks)}})})]});return r.jsxs("div",{className:"p-2.5 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary/30",children:[r.jsxs("div",{className:"flex items-center gap-1 mb-2",children:[r.jsx(WK,{ams:ht,printerId:t.id,label:$o(ht.id,ht.tray.length),amsLabels:Er,canEdit:H("printers:update"),onSaved:zn,children:r.jsx("span",{className:"text-[10px] text-white font-medium cursor-default select-none",children:Er?.[ht.id]||$o(ht.id,ht.tray.length)})}),an&&(ya||va)&&r.jsx(BK,{side:ya?"L":"R"}),qe.supports_drying&&(ht.module_type==="n3f"||ht.module_type==="n3s")&&H("printers:control")&&r.jsx("div",{className:"relative ml-auto",children:r.jsx("button",{onClick:sn=>{if(ht.dry_time>0)Qr.mutate(ht.id);else if(Re===ht.id)tt(null);else{const ua=(ht.tray.find(b_=>b_.tray_type)?.tray_type||"PLA").split(" ")[0].toUpperCase(),Hl=C[ua]||C.PLA,Mu=ht.module_type;fe(ua),$e(Hl[Mu]||Hl.n3f),nt(Mu==="n3s"?Hl.n3s_hours:Hl.n3f_hours),yt(!1),Xe(ht.module_type),tt(ht.id);const yb=sn.currentTarget.getBoundingClientRect();Ht({top:yb.bottom+4,left:Math.max(8,yb.right-240)})}},className:`flex items-center gap-0.5 px-1 py-0.5 rounded text-[9px] transition-colors ${ht.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:ht.dry_time>0?S("printers.drying.stop"):S("printers.drying.start"),children:r.jsx(mm,{className:"w-3 h-3"})})})]}),ht.dry_time>0&&r.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:[r.jsx(mm,{className:"w-3 h-3 text-amber-400 shrink-0"}),r.jsx("span",{className:"text-amber-300/70 text-[8px] truncate",children:ht.dry_time>=60?`${Math.floor(ht.dry_time/60)}h ${ht.dry_time%60}m`:`${ht.dry_time}m`}),r.jsx("button",{onClick:()=>Qr.mutate(ht.id),disabled:Qr.isPending,className:"ml-auto text-amber-400 hover:text-amber-300 transition-colors disabled:opacity-50 shrink-0",title:S("printers.drying.stop"),children:r.jsx(Bt,{className:"w-3 h-3"})})]}),r.jsxs("div",{className:"flex gap-1.5 max-[550px]:flex-col max-[550px]:items-start",children:[r.jsxs("div",{className:"relative group flex-1 max-[550px]:w-full",children:[Pa&&r.jsx("div",{className:"absolute inset-0 bg-bambu-dark-tertiary/80 rounded flex items-center justify-center z-20",children:r.jsx(sr,{className:"w-4 h-4 text-bambu-green animate-spin"})}),qe?.state!=="RUNNING"&&r.jsx("button",{onClick:sn=>{sn.stopPropagation(),fi(Qi?.amsId===ht.id&&Qi?.slotId===wa?null:{amsId:ht.id,slotId:wa})},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:S("printers.slotOptions"),children:r.jsx(ym,{className:"w-2.5 h-2.5 text-bambu-gray"})}),qe?.state!=="RUNNING"&&Qi?.amsId===ht.id&&Qi?.slotId===wa&&r.jsxs("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:[r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-xs flex items-center gap-2 ${H("printers:ams_rfid")?"text-white hover:bg-bambu-dark-tertiary":"text-bambu-gray/50 cursor-not-allowed"}`,onClick:sn=>{sn.stopPropagation(),H("printers:ams_rfid")&&(Pu.mutate({amsId:ht.id,slotId:wa}),fi(null))},disabled:Pa||!H("printers:ams_rfid"),title:H("printers:ams_rfid")?void 0:S("printers.permission.noAmsRfid"),children:[r.jsx(sr,{className:`w-3 h-3 ${Pa?"animate-spin":""}`}),S("printers.rfid.reread")]}),r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-xs flex items-center gap-2 ${H("printers:control")?"text-white hover:bg-bambu-dark-tertiary":"text-bambu-gray/50 cursor-not-allowed"}`,onClick:sn=>{sn.stopPropagation(),H("printers:control")&&(Tu.mutate({trayId:ht.id*4+wa}),fi(null))},disabled:!H("printers:control"),title:H("printers:control")?void 0:S("printers.permission.noControl"),children:[r.jsx(K0,{className:"w-3 h-3"}),S("printers.ams.load")]}),r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-xs flex items-center gap-2 ${H("printers:control")?"text-white hover:bg-bambu-dark-tertiary":"text-bambu-gray/50 cursor-not-allowed"}`,onClick:sn=>{sn.stopPropagation(),H("printers:control")&&(_n.mutate(),fi(null))},disabled:!H("printers:control"),title:H("printers:control")?void 0:S("printers.permission.noControl"),children:[r.jsx(Jx,{className:"w-3 h-3"}),S("printers.ams.unload")]})]}),$r?r.jsx(s3,{data:$r,spoolman:{enabled:o,linkedSpoolId:(Ss?l?.[Ss]?.id:void 0)??Ji?.spoolman_spool_id,spoolmanUrl:c,syncMode:d,onLinkSpool:o&&!Ji&&!_s?()=>{const sn=($r.trayUuid||$r.tagUid||fm(t.serial_number,ht.id,wa)).toUpperCase();_t({tagUid:$r.tagUid||sn,trayUuid:$r.trayUuid||"",printerId:t.id,amsId:ht.id,trayId:wa})}:void 0,onUnlinkSpool:gi?.id?()=>Ic.mutate(gi.id):void 0},inventory:(()=>{if(o){if(b)return;const pp=Ji,ua=Fi;return{assignedSpool:ua?{id:ua.id,material:ua.material,brand:ua.brand??null,color_name:ua.color_name??null,remainingWeightGrams:ua.label_weight?Math.max(0,Math.round(ua.label_weight-ua.weight_used)):void 0}:null,onAssignSpool:()=>De({printerId:t.id,amsId:ht.id,trayId:wa,trayInfo:{type:tn?.tray_type||$r.profile,material:tn?.tray_type??void 0,profile:$r.profile,color:$r.colorHex||"",location:$o(ht.id,ht.tray.length)}}),onUnassignSpool:ua&&!Qs(tn)?()=>w?.(ua.id):void 0,isAssigned:!!pp||Qs(tn)}}const sn=u?.(t.id,ht.id,wa);return{assignedSpool:sn?.spool?{id:sn.spool.id,material:sn.spool.material,brand:sn.spool.brand,color_name:sn.spool.color_name,remainingWeightGrams:Math.max(0,Math.round(sn.spool.label_weight-sn.spool.weight_used))}:null,onAssignSpool:()=>De({printerId:t.id,amsId:ht.id,trayId:wa,trayInfo:{type:tn?.tray_type||$r.profile,material:tn?.tray_type??void 0,profile:$r.profile,color:$r.colorHex||"",location:$o(ht.id,ht.tray.length)}}),onUnassignSpool:sn&&!Qs(tn)?()=>m?.(t.id,ht.id,wa):void 0,isAssigned:!!sn||Qs(tn)}})(),configureSlot:{enabled:H("printers:control"),onConfigure:()=>Ve({amsId:ht.id,trayId:wa,trayCount:ht.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:Un,caliIdx:tn?.cali_idx,savedPresetId:ul?.preset_id})},children:ju}):r.jsx(o3,{configureSlot:{enabled:H("printers:control"),onConfigure:()=>Ve({amsId:ht.id,trayId:wa,trayCount:ht.tray.length,extruderId:Un})},onAssignSpool:()=>De({printerId:t.id,amsId:ht.id,trayId:wa,trayInfo:{type:"",material:void 0,profile:"",color:"",location:$o(ht.id,ht.tray.length)}}),children:ju})]}),(ht.humidity!=null||ht.temp!=null)&&r.jsxs("div",{className:"flex flex-col justify-center gap-1 shrink-0 max-[550px]:w-full",children:[ht.temp!=null&&r.jsx($K,{temp:ht.temp,goodThreshold:s?.tempGood,fairThreshold:s?.tempFair,onClick:()=>at({amsId:ht.id,amsLabel:$o(ht.id,ht.tray.length),mode:"temperature"}),compact:!0}),ht.humidity!=null&&r.jsx(qK,{humidity:ht.humidity,goodThreshold:s?.humidityGood,fairThreshold:s?.humidityFair,onClick:()=>at({amsId:ht.id,amsLabel:$o(ht.id,ht.tray.length),mode:"humidity"}),compact:!0})]})]})]},ht.id)}),qe.vt_tray.length>0&&r.jsxs("div",{className:`p-2.5 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary/30 ${qe.vt_tray.length===1?"max-w-[50%]":""}`,children:[r.jsx("div",{className:"flex items-center gap-1 mb-2",children:r.jsx("span",{className:"text-[10px] text-white font-medium",children:S("printers.external")})}),r.jsx("div",{className:`grid ${qe.vt_tray.length>1?"grid-cols-2":"grid-cols-1"} gap-1.5`,children:[...qe.vt_tray].sort((ht,Un)=>(ht.id??254)-(Un.id??254)).map(ht=>{const Un=ht.id??254,kr=an&&Ft===254?Un===254&&qe.active_extruder===1||Un===255&&qe.active_extruder===0:Ft===Un,Hn=Un-254,ya=an?S(Un===254?"printers.extL":"printers.extR"):"",va=ht.tray_info_idx?wn?.[ht.tray_info_idx]:null,tn=bn?.[1020+Hn],Tn=(ht.tray_uuid||ht.tag_uid||fm(t.serial_number,255,Hn))?.toUpperCase(),Ca=Tn?l?.[Tn]:void 0,Qa=MN(Ca),Zi=u?.(t.id,255,Hn),Bl=(()=>{const dr=Zi?.spool;return dr&&dr.label_weight>0&&dr.weight_used!=null?Math.round(Math.max(0,dr.label_weight-dr.weight_used)/dr.label_weight*100):null})(),ul=ht.tray_type&&ht.remain>=0,wa=Bl===0&&ul&&ht.remain>0?null:Bl,Ss=o&&!b?f?.find(dr=>dr.printer_id===t.id&&dr.ams_id===255&&dr.tray_id===Hn):void 0,gi=Ss?p?.find(dr=>dr.id===Ss.spoolman_spool_id):void 0,Cd=gi&&(gi.label_weight??0)>0?Math.round(Math.max(0,(gi.label_weight??0)-gi.weight_used)/(gi.label_weight??1)*100):null,_s=Qa??Cd??wa??(ul?ht.remain:null),qr=Qa!==null||Cd!==null?"spoolman":wa!==null?"inventory":ul?"ams":void 0,Ha={vendor:Qs(ht)?"Bambu Lab":"Generic",profile:tn?.preset_name||(gi?[gi.brand,gi.slicer_filament_name?.split("@")[0].trim()||gi.material].filter(Boolean).join(" ").trim():null)||Zi?.spool?.slicer_filament_name||va?.name||ht.tray_sub_brands||ht.tray_type||"Unknown",colorName:yc(ht.tray_color||""),colorHex:ht.tray_color||null,kFactor:m3(ht.k),fillLevel:_s,trayUuid:ht.tray_uuid||null,tagUid:ht.tag_uid||null,fillSource:qr},Ji=!ht.tray_type,Fi=r.jsxs("div",{className:`bg-bambu-dark-tertiary rounded p-1 text-center ${Ji?"opacity-50":""} ${kr?"ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark":""}`,children:[r.jsx(u3,{trayColor:ht.tray_color,trayType:ht.tray_type,isEmpty:Ji,slotNumber:Hn+1}),r.jsx("div",{className:`text-[9px] font-bold truncate ${Ji?"text-white/40":"text-white"}`,children:ht.tray_type||"—"}),r.jsx("div",{className:"mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden",children:_s!==null&&_s>=0&&!Ji&&r.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${_s}%`,backgroundColor:dy(_s)}})}),ya&&r.jsx("div",{className:"text-[7px] text-white/40 mt-0.5 truncate",children:ya})]}),zc=2550+Hn,ks=Qi?.amsId===255&&Qi?.slotId===zc;return r.jsxs("div",{className:"relative group",children:[qe?.state!=="RUNNING"&&r.jsx("button",{onClick:dr=>{dr.stopPropagation(),fi(ks?null:{amsId:255,slotId:zc})},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:S("printers.slotOptions"),children:r.jsx(ym,{className:"w-2.5 h-2.5 text-bambu-gray"})}),qe?.state!=="RUNNING"&&ks&&r.jsxs("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:[r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-xs flex items-center gap-2 ${H("printers:control")?"text-white hover:bg-bambu-dark-tertiary":"text-bambu-gray/50 cursor-not-allowed"}`,onClick:dr=>{dr.stopPropagation(),H("printers:control")&&(Tu.mutate({trayId:Un}),fi(null))},disabled:!H("printers:control"),title:H("printers:control")?void 0:S("printers.permission.noControl"),children:[r.jsx(K0,{className:"w-3 h-3"}),S("printers.ams.load")]}),r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-xs flex items-center gap-2 ${H("printers:control")?"text-white hover:bg-bambu-dark-tertiary":"text-bambu-gray/50 cursor-not-allowed"}`,onClick:dr=>{dr.stopPropagation(),H("printers:control")&&(_n.mutate(),fi(null))},disabled:!H("printers:control"),title:H("printers:control")?void 0:S("printers.permission.noControl"),children:[r.jsx(Jx,{className:"w-3 h-3"}),S("printers.ams.unload")]})]}),Ji?r.jsx(o3,{configureSlot:{enabled:H("printers:control"),onConfigure:()=>Ve({amsId:255,trayId:Hn,trayCount:1,extruderId:an?Un===254?1:0:void 0})},onAssignSpool:()=>De({printerId:t.id,amsId:255,trayId:Hn,trayInfo:{type:"",material:void 0,profile:"",color:"",location:`External Slot ${Hn+1}`}}),children:Fi}):r.jsx(s3,{data:Ha,spoolman:{enabled:o,linkedSpoolId:(Tn?l?.[Tn]?.id:void 0)??Ss?.spoolman_spool_id,spoolmanUrl:c,syncMode:d,onLinkSpool:o&&!Ss&&!Zi?()=>{const dr=(Ha.trayUuid||Ha.tagUid||fm(t.serial_number,255,Hn)).toUpperCase();_t({tagUid:Ha.tagUid||dr,trayUuid:Ha.trayUuid||"",printerId:t.id,amsId:255,trayId:Hn})}:void 0,onUnlinkSpool:Ca?.id?()=>Ic.mutate(Ca.id):void 0},inventory:(()=>{if(o){if(b)return;const $r=Ss,Pa=gi;return{assignedSpool:Pa?{id:Pa.id,material:Pa.material,brand:Pa.brand??null,color_name:Pa.color_name??null,remainingWeightGrams:Pa.label_weight?Math.max(0,Math.round(Pa.label_weight-Pa.weight_used)):void 0}:null,onAssignSpool:()=>De({printerId:t.id,amsId:255,trayId:Hn,trayInfo:{type:ht.tray_type||Ha.profile,material:ht.tray_type??void 0,profile:Ha.profile,color:Ha.colorHex||"",location:ya||S("printers.external")}}),onUnassignSpool:Pa&&!Qs(ht)?()=>w?.(Pa.id):void 0,isAssigned:!!$r||Qs(ht)}}const dr=u?.(t.id,255,Hn);return{assignedSpool:dr?.spool?{id:dr.spool.id,material:dr.spool.material,brand:dr.spool.brand,color_name:dr.spool.color_name,remainingWeightGrams:Math.max(0,Math.round(dr.spool.label_weight-dr.spool.weight_used))}:null,onAssignSpool:()=>De({printerId:t.id,amsId:255,trayId:Hn,trayInfo:{type:ht.tray_type||Ha.profile,material:ht.tray_type??void 0,profile:Ha.profile,color:Ha.colorHex||"",location:ya||S("printers.external")}}),onUnassignSpool:dr&&!Qs(ht)?()=>m?.(t.id,255,Hn):void 0,isAssigned:!!dr||Qs(ht)}})(),configureSlot:{enabled:H("printers:control"),onConfigure:()=>Ve({amsId:255,trayId:Hn,trayCount:1,trayType:ht.tray_type||void 0,trayColor:ht.tray_color||void 0,traySubBrands:ht.tray_sub_brands||void 0,trayInfoIdx:ht.tray_info_idx||void 0,extruderId:an?Un===254?1:0:void 0,caliIdx:ht.cali_idx,savedPresetId:tn?.preset_id})},children:Fi})]},Un)})})]})]})]})]})})()]}),cn&&a==="expanded"&&r.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[r.jsx(Nc,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}),r.jsx("span",{className:"text-sm text-white truncate",children:cn.name}),Gt&&r.jsxs("span",{className:`text-xs px-1.5 py-0.5 rounded flex-shrink-0 ${Gt.state==="ON"?"bg-bambu-green/20 text-bambu-green":Gt.state==="OFF"?"bg-red-500/20 text-red-400":"bg-bambu-gray/20 text-bambu-gray"}`,children:[Gt.state||"?",Gt.state==="ON"&&Gt.energy?.power!=null&&r.jsxs("span",{className:"text-yellow-400 ml-1.5",children:["· ",Gt.energy.power,"W"]})]})]}),r.jsx("div",{className:"flex-1"}),r.jsxs("div",{className:"flex items-center gap-1",children:[r.jsxs("button",{onClick:()=>K(!0),disabled:Do.isPending||Gt?.state==="ON"||!H("smart_plugs:control"),className:`px-2 py-1 text-xs rounded transition-colors flex items-center gap-1 ${H("smart_plugs:control")?Gt?.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:H("smart_plugs:control")?void 0:S("printers.permission.noSmartPlugControl"),children:[r.jsx(wu,{className:"w-3 h-3"}),"On"]}),r.jsxs("button",{onClick:()=>j(!0),disabled:Do.isPending||Gt?.state==="OFF"||!H("smart_plugs:control"),className:`px-2 py-1 text-xs rounded transition-colors flex items-center gap-1 ${H("smart_plugs:control")?Gt?.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:H("smart_plugs:control")?void 0:S("printers.permission.noSmartPlugControl"),children:[r.jsx(jS,{className:"w-3 h-3"}),"Off"]})]}),r.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[r.jsx("span",{className:`text-xs hidden sm:inline ${cn.auto_off_executed?"text-bambu-green":"text-bambu-gray"}`,children:cn.auto_off_executed?"Auto-off done":"Auto-off"}),r.jsx("button",{onClick:()=>ol.mutate(!cn.auto_off),disabled:ol.isPending||cn.auto_off_executed||!H("smart_plugs:control"),title:H("smart_plugs:control")?cn.auto_off_executed?S("printers.autoOffExecuted"):S("printers.autoOffAfterPrint"):S("printers.permission.noSmartPlugControl"),className:`relative w-9 h-5 rounded-full transition-colors flex-shrink-0 ${H("smart_plugs:control")?cn.auto_off_executed?"bg-bambu-green/50 cursor-not-allowed":cn.auto_off?"bg-bambu-green":"bg-bambu-dark-tertiary":"bg-bambu-dark-tertiary/50 cursor-not-allowed"}`,children:r.jsx("span",{className:`absolute top-[2px] left-[2px] w-4 h-4 bg-white rounded-full transition-transform ${cn.auto_off||cn.auto_off_executed?"translate-x-4":"translate-x-0"}`})})]})]}),hr&&hr.length>0&&r.jsxs("div",{className:"flex items-center gap-2 mt-2 pt-2 border-t border-bambu-dark-tertiary/50",children:[r.jsx(NS,{className:"w-3.5 h-3.5 text-blue-400 flex-shrink-0"}),r.jsx("span",{className:"text-xs text-bambu-gray",children:"HA:"}),r.jsx("div",{className:"flex flex-wrap gap-1",children:hr.map(lt=>{const $t=lt.ha_entity_id?.startsWith("script.");return r.jsxs("button",{onClick:()=>{$t?ll.mutate({id:lt.id,action:"on"}):X(lt)},disabled:ll.isPending,title:`${$t?"Run":"Toggle"} ${lt.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:[r.jsx(fs,{className:"w-2.5 h-2.5"}),lt.name]},lt.id)})})]})]}),a==="expanded"&&r.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary flex items-center justify-end gap-2 flex-wrap",children:[r.jsx(Me,{variant:"secondary",size:"sm",onClick:()=>wd.mutate(!qe?.chamber_light),disabled:!qe?.connected||wd.isPending||!H("printers:control"),title:H("printers:control")?qe?.chamber_light?S("printers.chamberLightOff"):S("printers.chamberLightOn"):S("printers.permission.noControl"),className:qe?.chamber_light?"!border-yellow-500 !text-yellow-400 hover:!bg-yellow-500/20":"",children:r.jsx(e4,{on:qe?.chamber_light??!1,className:`w-4 h-4 ${qe?.chamber_light?"text-yellow-400":""}`})}),r.jsx(Me,{variant:"secondary",size:"sm",onClick:()=>{if(x==="embedded"&&_)_(t.id,t.name);else{const lt=localStorage.getItem("cameraWindowState"),$t=lt?JSON.parse(lt):{width:640,height:400},an=[`width=${$t.width}`,`height=${$t.height}`,$t.left!==void 0?`left=${$t.left}`:"",$t.top!==void 0?`top=${$t.top}`:"","menubar=no,toolbar=no,location=no,status=no"].filter(Boolean).join(",");window.open(`/camera/${t.id}`,`camera-${t.id}`,an)}},disabled:!qe?.connected||!H("camera:view"),title:H("camera:view")?S(x==="embedded"?"printers.openCameraOverlay":"printers.openCameraWindow"):S("printers.permission.noCamera"),children:r.jsx(aC,{className:"w-4 h-4"})}),r.jsxs("div",{className:`inline-flex rounded-md ${t.plate_detection_enabled?"ring-1 ring-green-500":""}`,children:[r.jsx(Me,{variant:"secondary",size:"sm",onClick:ff,disabled:!qe?.connected||po.isPending||!H("printers:update"),title:H("printers:update")?t.plate_detection_enabled?S("printers.plateDetection.enabledClick"):S("printers.plateDetection.disabledClick"):S("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:po.isPending?r.jsx(ut,{className:"w-4 h-4 animate-spin"}):r.jsx(nC,{className:"w-4 h-4"})}),r.jsx(Me,{variant:"secondary",size:"sm",onClick:bb,disabled:!qe?.connected||Fe||!H("printers:update"),title:H("printers:update")?S("printers.plateDetection.manageCalibration"):S("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:Fe?r.jsx(ut,{className:"w-3 h-3 animate-spin"}):r.jsx(Rn,{className:"w-3 h-3"})})]}),r.jsxs(Me,{variant:"secondary",size:"sm",onClick:()=>pe(!0),disabled:!jr||!H("printers:files"),title:H("printers:files")?S("printers.browseFiles"):S("printers.permission.noFiles"),children:[r.jsx(ob,{className:"w-4 h-4"}),S("printers.files")]}),jr&&qe?.state!=="RUNNING"&&qe?.state!=="PAUSE"&&r.jsxs(Me,{size:"sm",onClick:()=>_e(!0),disabled:!H("printers:control"),title:H("printers:control")?S("common.print"):S("printers.permission.noControl"),className:"!bg-bambu-green hover:!bg-bambu-green/80 !text-white",children:[r.jsx(pr,{className:"w-4 h-4"}),S("common.print")]})]})]}),ae&&r.jsx(qEe,{printerId:t.id,printerName:t.name,onClose:()=>pe(!1)}),ze&&r.jsx(Oie,{folderId:null,onClose:()=>_e(!1),onUploadComplete:()=>{},autoUpload:!0,accept:".gcode,.3mf",validateFile:lt=>{const $t=lt.name.toLowerCase();if(!$t.endsWith(".gcode")&&!$t.includes(".gcode."))return S("printers.dropNotPrintable","Only .gcode and .gcode.3mf files can be printed")},onFileUploaded:lt=>{const $t=lt.metadata?.sliced_for_model,an=rw(t.model);if($t&&an&&$t.toLowerCase()!==an.toLowerCase())return se.deleteLibraryFile(lt.id).catch(()=>{}),S("printers.incompatibleFile","This file was sliced for {{slicedFor}}, but this printer is a {{printerModel}}",{slicedFor:$t,printerModel:an});st({id:lt.id,filename:lt.filename})}}),rt&&r.jsx(wc,{mode:"reprint",libraryFileId:rt.id,archiveName:rt.filename,initialSelectedPrinterIds:[t.id],onClose:()=>st(null),onSuccess:()=>st(null),cleanupLibraryAfterDispatch:!0}),ye&&r.jsx(YEe,{printerId:t.id,printerName:t.name,onClose:()=>Te(!1)}),Oe&&r.jsx(C7e,{printer:t,status:qe,totalPrintHours:n?.total_print_hours,onClose:Ke}),dt&&r.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onClick:()=>Ul(),children:r.jsxs("div",{className:"bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl max-w-lg w-full",onClick:lt=>lt.stopPropagation(),children:[r.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[dt.needs_calibration?r.jsx(nC,{className:"w-5 h-5 text-blue-500"}):dt.is_empty?r.jsx(wr,{className:"w-5 h-5 text-green-500"}):r.jsx(Da,{className:"w-5 h-5 text-yellow-500"}),r.jsx("h2",{className:"text-lg font-semibold text-white",children:"Build Plate Check"}),dt.reference_count!==void 0&&dt.max_references&&r.jsxs("span",{className:"text-xs text-bambu-gray bg-bambu-dark-tertiary px-2 py-1 rounded",children:[dt.reference_count,"/",dt.max_references," refs"]})]}),r.jsx("button",{onClick:()=>Ul(),className:"p-1 text-bambu-gray hover:text-white rounded transition-colors",children:r.jsx(Bt,{className:"w-5 h-5"})})]}),r.jsxs("div",{className:"p-4 space-y-4",children:[dt.needs_calibration?r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"p-3 rounded-lg bg-blue-500/20 border border-blue-500/50",children:[r.jsx("p",{className:"font-medium text-blue-400",children:S("printers.plateDetection.calibrationRequired")}),r.jsx("p",{className:"text-sm text-bambu-gray mt-1",dangerouslySetInnerHTML:{__html:S("printers.plateDetection.calibrationInstructions")}})]}),r.jsxs("div",{className:"text-sm text-bambu-gray space-y-2",children:[r.jsx("p",{children:S("printers.plateDetection.calibrationDescription")}),r.jsx("p",{dangerouslySetInnerHTML:{__html:S("printers.plateDetection.calibrationTip")}})]})]}):r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:`p-3 rounded-lg ${dt.is_empty?"bg-green-500/20 border border-green-500/50":"bg-yellow-500/20 border border-yellow-500/50"}`,children:[r.jsx("p",{className:`font-medium ${dt.is_empty?"text-green-400":"text-yellow-400"}`,children:dt.is_empty?S("printers.plateDetection.plateEmpty"):S("printers.plateDetection.objectsDetected")}),r.jsxs("p",{className:"text-sm text-bambu-gray mt-1",children:[S("printers.plateDetection.confidence"),": ",Math.round(dt.confidence*100),"% | ",S("printers.plateDetection.difference"),": ",dt.difference_percent.toFixed(1),"%"]})]}),dt.debug_image_url&&r.jsxs("div",{children:[r.jsx("p",{className:"text-sm text-bambu-gray mb-2",children:S("printers.plateDetection.analysisPreview")}),r.jsx("img",{src:dt.debug_image_url,alt:S("printers.plateDetection.analysisPreview"),className:"w-full rounded-lg border border-bambu-dark-tertiary"}),r.jsx("p",{className:"text-xs text-bambu-gray mt-2",children:S("printers.plateDetection.analysisLegend")})]}),r.jsx("p",{className:"text-xs text-bambu-gray",children:dt.message})]}),Lo&&Lo.references.length>0&&r.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[r.jsx("p",{className:"text-sm font-medium text-white mb-2",children:S("printers.plateDetection.savedReferences",{count:Lo.references.length,max:Lo.max_references})}),r.jsx("div",{className:"grid grid-cols-5 gap-2",children:Lo.references.map(lt=>r.jsxs("div",{className:"relative group",children:[r.jsx("img",{src:se.getPlateReferenceThumbnailUrl(t.id,lt.index),alt:lt.label||`Reference ${lt.index+1}`,className:"w-full aspect-video object-cover rounded border border-bambu-dark-tertiary"}),r.jsx("button",{onClick:()=>hv(lt.index),className:"absolute top-1 right-1 p-0.5 bg-red-500/80 rounded opacity-0 group-hover:opacity-100 transition-opacity",title:S("printers.plateDetection.deleteReference"),children:r.jsx(Bt,{className:"w-3 h-3 text-white"})}),_d?.index===lt.index?r.jsx("input",{type:"text",value:_d.label,onChange:$t=>kd({..._d,label:$t.target.value}),onBlur:()=>xb(lt.index,_d.label),onKeyDown:$t=>{$t.key==="Enter"&&xb(lt.index,_d.label),$t.key==="Escape"&&kd(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:S("printers.plateDetection.labelPlaceholder")}):r.jsx("p",{className:"text-xs text-bambu-gray mt-1 truncate cursor-pointer hover:text-white",onClick:()=>kd({index:lt.index,label:lt.label}),title:lt.label?S("printers.plateDetection.clickToEdit",{label:lt.label}):S("printers.plateDetection.clickToAddLabel"),children:lt.label||r.jsx("span",{className:"italic opacity-50",children:S("printers.noLabel")})}),r.jsx("p",{className:"text-[10px] text-bambu-gray/60",children:lt.timestamp?Xn(lt.timestamp)?.toLocaleDateString()??"":""})]},lt.index))})]}),!dt.needs_calibration&&r.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center justify-between mb-2",children:[r.jsx("p",{className:"text-sm font-medium text-white",children:S("printers.roi.title")}),ft?r.jsxs("div",{className:"flex gap-1",children:[r.jsx(Me,{variant:"ghost",size:"sm",onClick:()=>et(null),disabled:jt,children:S("common.cancel")}),r.jsx(Me,{size:"sm",onClick:bf,disabled:jt,children:jt?r.jsx(ut,{className:"w-3 h-3 animate-spin"}):S("common.save")})]}):r.jsxs(Me,{variant:"ghost",size:"sm",onClick:()=>et(dt.roi||{x:.15,y:.35,w:.7,h:.55}),children:[r.jsx(oi,{className:"w-3 h-3 mr-1"}),S("common.edit")]})]}),ft?r.jsxs("div",{className:"space-y-3 bg-bambu-dark-tertiary/50 p-3 rounded-lg",children:[r.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[r.jsxs("div",{children:[r.jsx("label",{className:"text-xs text-bambu-gray",children:S("printers.roi.xStart")}),r.jsx("input",{type:"range",min:"0",max:"0.9",step:"0.01",value:ft.x,onChange:lt=>et({...ft,x:parseFloat(lt.target.value)}),className:"w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"}),r.jsxs("span",{className:"text-xs text-bambu-gray",children:[Math.round(ft.x*100),"%"]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"text-xs text-bambu-gray",children:S("printers.roi.yStart")}),r.jsx("input",{type:"range",min:"0",max:"0.9",step:"0.01",value:ft.y,onChange:lt=>et({...ft,y:parseFloat(lt.target.value)}),className:"w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"}),r.jsxs("span",{className:"text-xs text-bambu-gray",children:[Math.round(ft.y*100),"%"]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"text-xs text-bambu-gray",children:S("printers.width")}),r.jsx("input",{type:"range",min:"0.1",max:"1",step:"0.01",value:ft.w,onChange:lt=>et({...ft,w:parseFloat(lt.target.value)}),className:"w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"}),r.jsxs("span",{className:"text-xs text-bambu-gray",children:[Math.round(ft.w*100),"%"]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"text-xs text-bambu-gray",children:S("printers.height")}),r.jsx("input",{type:"range",min:"0.1",max:"1",step:"0.01",value:ft.h,onChange:lt=>et({...ft,h:parseFloat(lt.target.value)}),className:"w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"}),r.jsxs("span",{className:"text-xs text-bambu-gray",children:[Math.round(ft.h*100),"%"]})]})]}),r.jsx("p",{className:"text-xs text-bambu-gray",children:S("printers.roi.instruction")})]}):r.jsxs("p",{className:"text-xs text-bambu-gray",children:["Current: X=",Math.round((dt.roi?.x||.15)*100),"%, Y=",Math.round((dt.roi?.y||.35)*100),"%, W=",Math.round((dt.roi?.w||.7)*100),"%, H=",Math.round((dt.roi?.h||.55)*100),"%"]})]})]}),r.jsx("div",{className:"flex justify-end gap-2 p-4 border-t border-bambu-dark-tertiary",children:dt.needs_calibration?r.jsxs(r.Fragment,{children:[r.jsx(Me,{variant:"ghost",onClick:()=>Ul(),children:S("common.cancel")}),r.jsx(Me,{onClick:()=>gf(),disabled:Ze,children:Ze?r.jsxs(r.Fragment,{children:[r.jsx(ut,{className:"w-4 h-4 mr-2 animate-spin"}),"Calibrating..."]}):"Calibrate Empty Plate"})]}):r.jsxs(r.Fragment,{children:[r.jsx(Me,{variant:"ghost",onClick:()=>gf(),disabled:Ze,children:Ze?"Adding...":`Add Reference (${Lo?.references.length||0}/${Lo?.max_references||5})`}),r.jsx(Me,{onClick:()=>Ul(),children:"Close"})]})})]})}),$&&cn&&r.jsx(vn,{title:S("printers.confirm.powerOnTitle"),message:S("printers.confirm.powerOnMessage",{name:t.name}),confirmText:S("printers.confirm.powerOnButton"),variant:"default",onConfirm:()=>{Do.mutate("on"),K(!1)},onCancel:()=>K(!1)}),D&&cn&&r.jsx(vn,{title:S("printers.confirm.powerOffTitle"),message:qe?.state==="RUNNING"?S("printers.confirm.powerOffWarning",{name:t.name}):S("printers.confirm.powerOffMessage",{name:t.name}),confirmText:S("printers.confirm.powerOffButton"),variant:"danger",onConfirm:()=>{Do.mutate("off"),j(!1)},onCancel:()=>j(!1)}),B&&r.jsx(vn,{title:S("printers.confirm.haToggleTitle",{name:B.name}),message:qe?.state==="RUNNING"?S("printers.confirm.haToggleWarning",{name:t.name,entity:B.ha_entity_id||B.name}):S("printers.confirm.haToggleMessage",{entity:B.ha_entity_id||B.name}),confirmText:S("printers.confirm.haToggleButton"),variant:qe?.state==="RUNNING"?"danger":"default",onConfirm:()=>{ll.mutate({id:B.id,action:"toggle"}),X(null)},onCancel:()=>X(null)}),U&&r.jsx(vn,{title:S("printers.confirm.stopTitle"),message:S("printers.confirm.stopMessage",{name:t.name}),confirmText:S("printers.confirm.stopButton"),variant:"danger",onConfirm:()=>{cl.mutate(),G(!1)},onCancel:()=>G(!1)}),Y&&r.jsx(vn,{title:S("printers.confirm.pauseTitle"),message:S("printers.confirm.pauseMessage",{name:t.name}),confirmText:S("printers.confirm.pauseButton"),variant:"default",onConfirm:()=>{vd.mutate(),Q(!1)},onCancel:()=>Q(!1)}),Ne&&r.jsx(vn,{title:S("printers.confirm.resumeTitle"),message:S("printers.confirm.resumeMessage",{name:t.name}),confirmText:S("printers.confirm.resumeButton"),variant:"default",onConfirm:()=>{dp.mutate(),ve(!1)},onCancel:()=>ve(!1)}),xe&&r.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/70 p-4",children:r.jsxs("div",{className:"bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl w-full max-w-sm p-5",children:[r.jsxs("div",{className:"flex items-start gap-3 mb-4",children:[r.jsx(Nn,{className:"w-5 h-5 text-yellow-400 flex-shrink-0 mt-0.5"}),r.jsxs("div",{children:[r.jsx("h3",{className:"text-sm font-semibold text-white mb-1",children:S("printers.bedJog.notHomedTitle")}),r.jsx("p",{className:"text-xs text-bambu-gray leading-relaxed",children:S("printers.bedJog.notHomedMessage")})]})]}),r.jsxs("div",{className:"flex flex-col gap-2",children:[r.jsx("button",{onClick:()=>{pf.mutate("all"),we(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:S("printers.bedJog.homeZ")}),r.jsx("button",{onClick:()=>{const lt=xe.distance;try{sessionStorage.setItem(`bambuddy.bedJog.warned.${t.id}`,"1")}catch{}mf.mutate({distance:lt,force:!0}),we(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:S("printers.bedJog.moveAnyway")}),r.jsx("button",{onClick:()=>we(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:S("common.cancel")})]})]})}),r.jsx(t4,{printerId:t.id,isOpen:be,onClose:()=>Ee(!1)}),O&&r.jsx(Vve,{printerName:t.name,errors:qe?.hms_errors||[],onClose:()=>ie(!1),printerId:t.id,hasPermission:H}),pt&&r.jsx(a7e,{isOpen:!!pt,onClose:()=>at(null),printerId:t.id,printerName:t.name,amsId:pt.amsId,amsLabel:pt.amsLabel,initialMode:pt.mode,thresholds:s}),vt&&r.jsx(Rie,{isOpen:!!vt,onClose:()=>_t(null),tagUid:vt.tagUid,trayUuid:vt.trayUuid,printerId:vt.printerId,amsId:vt.amsId,trayId:vt.trayId}),Dt&&r.jsx(Lie,{isOpen:!!Dt,onClose:()=>De(null),printerId:Dt.printerId,amsId:Dt.amsId,trayId:Dt.trayId,trayInfo:Dt.trayInfo,spoolmanEnabled:!!o}),je&&r.jsx(Iie,{isOpen:!!je,onClose:()=>Ve(null),printerId:t.id,slotInfo:je,printerModel:rw(t.model)||void 0,onSuccess:()=>{M.invalidateQueries({queryKey:["slotPresets",t.id]}),M.invalidateQueries({queryKey:["printerStatus",t.id]})}}),ue&&r.jsx(B7e,{printer:t,onClose:()=>W(!1)}),Je&&Ge&&r.jsx(U7e,{printer:t,firmwareInfo:Ge,onClose:()=>Le(!1)}),Qi&&r.jsx("div",{className:"fixed inset-0 z-40",onClick:()=>fi(null)}),Re!==null&&ot&&(()=>{const lt=Ce==="n3s"?85:65,$t=35,an=lt+10;return r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"fixed inset-0 z-[100]",onClick:()=>tt(null)}),r.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:ot.top,left:ot.left},onClick:ht=>ht.stopPropagation(),children:[r.jsxs("div",{className:"flex items-center gap-2 px-3 py-2.5 border-b border-bambu-dark-tertiary",children:[r.jsx(mm,{className:"w-3.5 h-3.5 text-amber-400"}),r.jsx("span",{className:"text-xs text-white font-medium",children:S("printers.drying.start")})]}),r.jsxs("div",{className:"px-3 py-2.5 space-y-2.5",children:[r.jsxs("div",{children:[r.jsx("label",{className:"text-[10px] text-bambu-gray mb-1 block",children:S("printers.filaments")}),r.jsx("select",{value:Ue,onChange:ht=>{const Un=ht.target.value;fe(Un);const kr=C[Un];kr&&($e(kr[Ce==="n3s"?"n3s":"n3f"]),nt(Ce==="n3s"?kr.n3s_hours:kr.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(C).map(ht=>r.jsx("option",{value:ht,children:ht},ht))})]}),r.jsxs("div",{children:[r.jsxs("div",{className:"flex items-center justify-between mb-1",children:[r.jsx("label",{className:"text-[10px] text-bambu-gray",children:S("printers.drying.temperature")}),r.jsxs("div",{className:"flex items-center gap-1",children:[r.jsx("input",{type:"number",min:45,max:lt,value:Ae,onChange:ht=>$e(Math.min(lt,Math.max(45,Number(ht.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"}),r.jsx("span",{className:"text-[10px] text-bambu-gray",children:"°C"})]})]}),r.jsx("input",{type:"range",min:$t,max:an,value:Ae,onChange:ht=>$e(Math.min(lt,Math.max(45,Number(ht.target.value)))),className:"w-full h-1 accent-amber-500 cursor-pointer"}),r.jsxs("div",{className:"flex justify-between text-[9px] text-bambu-gray/50 mt-0.5",children:[r.jsx("span",{children:"45°C"}),r.jsxs("span",{children:[lt,"°C"]})]})]}),r.jsxs("div",{children:[r.jsxs("div",{className:"flex items-center justify-between mb-1",children:[r.jsx("label",{className:"text-[10px] text-bambu-gray",children:S("printers.drying.duration")}),r.jsxs("div",{className:"flex items-center gap-1",children:[r.jsx("input",{type:"number",min:1,max:24,value:Be,onChange:ht=>nt(Math.min(24,Math.max(1,Number(ht.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"}),r.jsx("span",{className:"text-[10px] text-bambu-gray",children:S("printers.drying.hours")})]})]}),r.jsx("input",{type:"range",min:1,max:24,value:Be,onChange:ht=>nt(Number(ht.target.value)),className:"w-full h-1 accent-amber-500 cursor-pointer"}),r.jsxs("div",{className:"flex justify-between text-[9px] text-bambu-gray/50 mt-0.5",children:[r.jsx("span",{children:"1h"}),r.jsx("span",{children:"24h"})]})]}),r.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[r.jsx("input",{type:"checkbox",checked:gt,onChange:ht=>yt(ht.target.checked),className:"w-3.5 h-3.5 accent-amber-500 rounded cursor-pointer"}),r.jsx("span",{className:"text-[11px] text-bambu-gray",children:S("printers.drying.rotateTray")})]})]}),r.jsx("div",{className:"px-3 pb-3",children:r.jsx("button",{onClick:()=>{Re!==null&&cp.mutate({amsId:Re,temp:Ae,duration:Be,filament:Ue,rotateTray:gt})},disabled:cp.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:cp.isPending?S("printers.drying.startingDrying"):S("printers.drying.start")})})]})]})})()]})}function z7e({onClose:t,onAdd:e,existingSerials:n}){const{t:a}=kt(),[i,s]=v.useState({name:"",serial_number:"",ip_address:"",access_code:"",model:"",location:"",auto_archive:!0}),[o,l]=v.useState(!1),[c,d]=v.useState([]),[u,m]=v.useState(""),[p,f]=v.useState(!1),[b,w]=v.useState(!1),[g,x]=v.useState([]),[_,N]=v.useState(""),[C,P]=v.useState({scanned:0,total:0});v.useEffect(()=>{Md.getInfo().then(S=>{w(S.is_docker),S.subnets.length>0&&(x(S.subnets),N(S.subnets[0]))}).catch(()=>{})},[]);const T=c.filter(S=>!n.includes(S.serial)),A=async()=>{m(""),d([]),l(!0),f(!1),P({scanned:0,total:0});try{if(b){await Md.startSubnetScan(_);const S=setInterval(async()=>{try{const M=await Md.getScanStatus();P({scanned:M.scanned,total:M.total});const z=await Md.getDiscoveredPrinters();d(z),M.running||(clearInterval(S),l(!1),f(!0))}catch(M){console.error("Failed to get scan status:",M)}},500)}else{await Md.startDiscovery(10);const S=setInterval(async()=>{try{const M=await Md.getDiscoveredPrinters();d(M)}catch(M){console.error("Failed to get discovered printers:",M)}},1e3);setTimeout(async()=>{clearInterval(S);try{await Md.stopDiscovery()}catch{}l(!1),f(!0);try{const M=await Md.getDiscoveredPrinters();d(M)}catch(M){console.error("Failed to get final discovered printers:",M)}},1e4)}}catch(S){console.error("Failed to start discovery:",S),m(S instanceof Error?S.message:a("printers.discovery.failedToStart")),l(!1),f(!0)}},F=S=>{const M=S.serial.startsWith("unknown-")?"":S.serial;s({...i,name:S.name||"",serial_number:M,ip_address:S.ip_address,model:rw(S.model)}),d([])};return v.useEffect(()=>()=>{Md.stopDiscovery().catch(()=>{}),Md.stopSubnetScan().catch(()=>{})},[]),v.useEffect(()=>{const S=M=>{M.key==="Escape"&&t()};return window.addEventListener("keydown",S),()=>window.removeEventListener("keydown",S)},[t]),r.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:r.jsx(Ct,{className:"w-full max-w-md my-auto max-h-[calc(100vh-2rem)] overflow-y-auto",onClick:S=>S.stopPropagation(),children:r.jsxs(At,{children:[r.jsx("h2",{className:"text-xl font-semibold mb-4",children:a("printers.addPrinter")}),r.jsxs("div",{className:"mb-4 pb-4 border-b border-bambu-dark-tertiary",children:[b&&r.jsxs("div",{className:"mb-3",children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("printers.discovery.subnetToScan")}),g.length>0?r.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:S=>N(S.target.value),disabled:o,children:g.map(S=>r.jsx("option",{value:S,children:S},S))}):r.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:S=>N(S.target.value),placeholder:"192.168.1.0/24",disabled:o}),r.jsx("p",{className:"mt-1 text-xs text-bambu-gray",children:a("printers.discovery.dockerNote")})]}),r.jsx(Me,{type:"button",variant:"secondary",onClick:A,disabled:o,className:"w-full",children:o?r.jsxs(r.Fragment,{children:[r.jsx(ut,{className:"w-4 h-4 animate-spin"}),b&&C.total>0?a("printers.discovery.scanProgress",{scanned:C.scanned,total:C.total}):a("printers.discovery.scanning")]}):r.jsxs(r.Fragment,{children:[r.jsx(Sr,{className:"w-4 h-4"}),a(b?"printers.discovery.scanSubnet":"printers.discovery.discoverNetwork")]})}),u&&r.jsx("div",{className:"mt-2 text-sm text-red-400",children:u}),T.length>0&&r.jsx("div",{className:"mt-3 space-y-2 max-h-40 overflow-y-auto",children:T.map(S=>r.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(S),children:[r.jsxs("div",{className:"min-w-0 flex-1",children:[r.jsx("p",{className:"font-medium text-white text-sm truncate",children:S.name||S.serial}),r.jsxs("p",{className:"text-xs text-bambu-gray truncate",children:[rw(S.model)||a("printers.discovery.unknown")," • ",S.ip_address,S.serial.startsWith("unknown-")&&r.jsxs("span",{className:"text-yellow-500",children:[" • ",a("printers.discovery.serialRequired")]})]})]}),r.jsx(Rn,{className:"w-4 h-4 text-bambu-gray -rotate-90 flex-shrink-0 ml-2"})]},S.serial))}),o&&r.jsx("p",{className:"mt-2 text-sm text-bambu-gray text-center",children:a(b?"printers.discovery.scanningSubnet":"printers.discovery.scanningNetwork")}),p&&!o&&c.length===0&&r.jsx("p",{className:"mt-2 text-sm text-bambu-gray text-center",children:a(b?"printers.discovery.noPrintersFoundSubnet":"printers.discovery.noPrintersFoundNetwork")}),p&&!o&&c.length>0&&T.length===0&&r.jsx("p",{className:"mt-2 text-sm text-bambu-gray text-center",children:a("printers.discovery.allConfigured")})]}),r.jsxs("form",{onSubmit:S=>{S.preventDefault(),e(i)},className:"space-y-4",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("printers.name")}),r.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:S=>s({...i,name:S.target.value}),placeholder:a("printers.modal.myPrinter")})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("printers.ipAddress")}),r.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:S=>s({...i,ip_address:S.target.value}),placeholder:"192.168.1.100 or printer.local"})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("printers.serialNumber")}),r.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:S=>s({...i,serial_number:S.target.value}),placeholder:"01P00A000000000"})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("printers.accessCode")}),r.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:S=>s({...i,access_code:S.target.value}),placeholder:a("printers.modal.fromPrinterSettings")})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("printers.modal.modelOptional")}),r.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:S=>s({...i,model:S.target.value}),children:[r.jsx("option",{value:"",children:a("printers.modal.selectModel")}),r.jsxs("optgroup",{label:"H2 Series",children:[r.jsx("option",{value:"H2C",children:"H2C"}),r.jsx("option",{value:"H2D",children:"H2D"}),r.jsx("option",{value:"H2D Pro",children:"H2D Pro"}),r.jsx("option",{value:"H2S",children:"H2S"})]}),r.jsx("optgroup",{label:"X2 Series",children:r.jsx("option",{value:"X2D",children:"X2D"})}),r.jsxs("optgroup",{label:"X1 Series",children:[r.jsx("option",{value:"X1E",children:"X1E"}),r.jsx("option",{value:"X1C",children:"X1 Carbon"}),r.jsx("option",{value:"X1",children:"X1"})]}),r.jsxs("optgroup",{label:"P Series",children:[r.jsx("option",{value:"P2S",children:"P2S"}),r.jsx("option",{value:"P1S",children:"P1S"}),r.jsx("option",{value:"P1P",children:"P1P"})]}),r.jsxs("optgroup",{label:"A1 Series",children:[r.jsx("option",{value:"A1",children:"A1"}),r.jsx("option",{value:"A1 Mini",children:"A1 Mini"})]})]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("printers.modal.locationGroup")}),r.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:S=>s({...i,location:S.target.value}),placeholder:a("printers.modal.locationPlaceholder")}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:a("printers.locationHelp")})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("input",{type:"checkbox",id:"auto_archive",checked:i.auto_archive,onChange:S=>s({...i,auto_archive:S.target.checked}),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),r.jsx("label",{htmlFor:"auto_archive",className:"text-sm text-bambu-gray",children:a("printers.modal.autoArchiveLabel")})]}),r.jsxs("div",{className:"flex gap-3 pt-4",children:[r.jsx(Me,{type:"button",variant:"secondary",onClick:t,className:"flex-1",children:a("common.cancel")}),r.jsx(Me,{type:"submit",className:"flex-1",children:a("printers.addPrinter")})]})]})]})})})}function U7e({printer:t,firmwareInfo:e,onClose:n}){const{t:a}=kt(),i=en(),{showToast:s}=rn(),{hasPermission:o}=cr(),l=o("firmware:update"),[c,d]=v.useState(null),[u,m]=v.useState(!1),[p,f]=v.useState(null),[b,w]=v.useState(e.update_available?e.latest_version:null),{data:g,isLoading:x}=We({queryKey:["firmwarePrepare",t.id,b],queryFn:()=>fN.prepareUpload(t.id,b??void 0),staleTime:3e4,enabled:!!b&&l&&!u}),_=it({mutationFn:()=>fN.startUpload(t.id,b??void 0),onSuccess:()=>{m(!0);const C=setInterval(async()=>{try{const P=await fN.getUploadStatus(t.id);d(P),(P.status==="complete"||P.status==="error")&&(clearInterval(C),f(null),m(!1),P.status==="complete"&&(s(a("printers.firmwareModal.uploadedToast"),"success"),i.invalidateQueries({queryKey:["firmwareUpdate",t.id]})))}catch{}},2e3);f(C)},onError:C=>{s(a("printers.firmwareModal.uploadFailed",{error:C.message}),"error"),m(!1)}});v.useEffect(()=>()=>{p&&clearInterval(p)},[p]);const N=()=>{d(null),_.mutate()};return r.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",children:r.jsx(Ct,{className:"w-full max-w-md mx-4",children:r.jsxs(At,{children:[r.jsxs("div",{className:"flex items-start gap-3 mb-4",children:[r.jsx("div",{className:`p-2 rounded-full ${e.update_available?"bg-orange-500/20":"bg-status-ok/20"}`,children:e.update_available?r.jsx(Yr,{className:"w-5 h-5 text-orange-400"}):r.jsx(wr,{className:"w-5 h-5 text-status-ok"})}),r.jsxs("div",{className:"flex-1",children:[r.jsx("h3",{className:"text-lg font-semibold text-white",children:e.update_available?a("printers.firmwareModal.title"):a("printers.firmwareModal.titleUpToDate")}),r.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:t.name})]})]}),(()=>{const C=b?e.available_versions?.find(F=>F.version===b):null,P=b??e.latest_version,T=C?.release_notes??e.release_notes,A=!!P&&P!==e.current_version;return r.jsxs("div",{className:"bg-bambu-dark rounded-lg p-3 mb-4",children:[r.jsxs("div",{className:"flex justify-between items-center text-sm",children:[r.jsx("span",{className:"text-bambu-gray",children:a("printers.firmwareModal.currentVersion")}),r.jsx("span",{className:`font-mono ${A?"text-white":"text-status-ok"}`,children:e.current_version||a("common.unknown")})]}),A&&r.jsxs("div",{className:"flex justify-between items-center text-sm mt-1",children:[r.jsx("span",{className:"text-bambu-gray",children:a("printers.firmwareModal.latestVersion")}),r.jsx("span",{className:"text-orange-400 font-mono",children:P})]}),T&&r.jsxs("details",{className:"mt-3 text-sm",open:!A,children:[r.jsx("summary",{className:`cursor-pointer hover:underline ${A?"text-orange-400":"text-status-ok"}`,children:a("printers.firmwareModal.releaseNotes")}),r.jsx("div",{className:"mt-2 text-bambu-gray text-xs max-h-40 overflow-y-auto whitespace-pre-wrap",children:T})]},P??"none")]})})(),e.available_versions&&e.available_versions.length>0&&!u&&c?.status!=="complete"&&r.jsxs("div",{className:"mb-4",children:[r.jsx("div",{className:"text-xs text-bambu-gray mb-2",children:a("printers.firmwareModal.availableVersions")}),r.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(C=>{const P=e.current_version===C.version,T=b===C.version,A=e.current_version?Hve(C.version,e.current_version):0,F=P?a("printers.firmwareModal.currentBadge"):A>0?a("printers.firmwareModal.newerBadge"):a("printers.firmwareModal.olderBadge"),S=P?"text-bambu-gray":A>0?"text-orange-400":"text-blue-400";return r.jsxs("button",{type:"button",disabled:!C.file_available||!l||P,onClick:()=>w(C.version),className:`w-full text-left px-3 py-2 text-sm flex items-center justify-between gap-2 transition-colors ${T?"bg-orange-500/10":"hover:bg-bambu-dark"} ${!C.file_available||!l||P?"opacity-60 cursor-not-allowed":"cursor-pointer"}`,children:[r.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[r.jsx("span",{className:"font-mono text-white",children:C.version}),r.jsx("span",{className:`text-xs ${S}`,children:F})]}),r.jsx("span",{className:`text-xs px-2 py-0.5 rounded-full ${P?"bg-blue-500/15 text-blue-400 border border-blue-500/30":C.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:P?a("printers.firmwareModal.installed"):C.file_available?a("printers.firmwareModal.usable"):a("printers.firmwareModal.unavailable")})]},C.version)})})]}),b?x?r.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray text-sm mb-4",children:[r.jsx(ut,{className:"w-4 h-4 animate-spin"}),a("printers.firmwareModal.checkingPrereqs")]}):g&&!u&&!c?r.jsx("div",{className:"mb-4",children:g.can_proceed?r.jsxs("div",{className:"flex items-center gap-2 text-bambu-green text-sm",children:[r.jsx(Ni,{className:"w-4 h-4"}),a("printers.firmwareModal.sdCardReady")]}):r.jsx("div",{className:"space-y-1",children:g.errors.map((C,P)=>r.jsxs("div",{className:"flex items-center gap-2 text-red-400 text-sm",children:[r.jsx($a,{className:"w-4 h-4 flex-shrink-0"}),C]},P))})}):null:null,(u||c)&&c&&r.jsxs("div",{className:"mb-4",children:[r.jsxs("div",{className:"flex items-center justify-between text-sm mb-1",children:[r.jsx("span",{className:"text-bambu-gray capitalize",children:c.status}),r.jsxs("span",{className:"text-white",children:[c.progress,"%"]})]}),r.jsx("div",{className:"w-full bg-bambu-dark-tertiary rounded-full h-2",children:r.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}%`}})}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:c.message}),c.error&&r.jsx("p",{className:"text-xs text-red-400 mt-1",children:c.error})]}),c?.status==="complete"&&r.jsxs("div",{className:"bg-bambu-green/10 border border-bambu-green/30 rounded-lg p-3 mb-4",children:[r.jsx("p",{className:"text-sm text-bambu-green font-medium mb-2",children:a("printers.firmwareModal.uploadedSuccess")}),r.jsx("p",{className:"text-xs text-bambu-gray",children:a("printers.firmwareModal.applyInstructions")}),r.jsxs("ol",{className:"text-xs text-bambu-gray mt-1 list-decimal list-inside space-y-1",children:[r.jsx("li",{dangerouslySetInnerHTML:{__html:a("printers.firmwareModal.step1")}}),r.jsx("li",{dangerouslySetInnerHTML:{__html:a("printers.firmwareModal.step2")}}),r.jsx("li",{dangerouslySetInnerHTML:{__html:a("printers.firmwareModal.step3")}}),r.jsx("li",{children:a("printers.firmwareModal.step4")})]})]}),r.jsxs("div",{className:"flex gap-2 justify-end",children:[r.jsx(Me,{variant:"secondary",onClick:n,children:c?.status==="complete"?a("printers.firmwareModal.done"):a("common.cancel")}),g?.can_proceed&&!u&&c?.status!=="complete"&&l&&r.jsx(Me,{onClick:N,disabled:_.isPending,children:_.isPending?r.jsxs(r.Fragment,{children:[r.jsx(ut,{className:"w-4 h-4 animate-spin mr-2"}),a("printers.firmwareModal.starting")]}):r.jsxs(r.Fragment,{children:[r.jsx(Yr,{className:"w-4 h-4 mr-2"}),a("printers.firmwareModal.uploadFirmware")]})})]})]})})})}function B7e({printer:t,onClose:e}){const{t:n}=kt(),a=en(),{showToast:i}=rn(),[s,o]=v.useState({name:t.name,ip_address:t.ip_address,access_code:"",model:t.model||"",location:t.location||"",auto_archive:t.auto_archive}),l=it({mutationFn:d=>se.updatePrinter(t.id,d),onSuccess:()=>{a.invalidateQueries({queryKey:["printers"]}),a.invalidateQueries({queryKey:["printerStatus",t.id]}),e()},onError:d=>i(d.message||n("printers.toast.failedToUpdate"),"error")});v.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 r.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:r.jsx(Ct,{className:"w-full max-w-md my-auto max-h-[calc(100vh-2rem)] overflow-y-auto",onClick:d=>d.stopPropagation(),children:r.jsxs(At,{children:[r.jsx("h2",{className:"text-xl font-semibold mb-4",children:n("printers.editPrinter")}),r.jsxs("form",{onSubmit:c,className:"space-y-4",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.name")}),r.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")})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.ipAddress")}),r.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"})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.serialNumber")}),r.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}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:n("printers.serialCannotBeChanged")})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.accessCode")}),r.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")})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.model")}),r.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:[r.jsx("option",{value:"",children:n("printers.modal.selectModel")}),r.jsxs("optgroup",{label:"H2 Series",children:[r.jsx("option",{value:"H2C",children:"H2C"}),r.jsx("option",{value:"H2D",children:"H2D"}),r.jsx("option",{value:"H2D Pro",children:"H2D Pro"}),r.jsx("option",{value:"H2S",children:"H2S"})]}),r.jsx("optgroup",{label:"X2 Series",children:r.jsx("option",{value:"X2D",children:"X2D"})}),r.jsxs("optgroup",{label:"X1 Series",children:[r.jsx("option",{value:"X1E",children:"X1E"}),r.jsx("option",{value:"X1C",children:"X1 Carbon"}),r.jsx("option",{value:"X1",children:"X1"})]}),r.jsxs("optgroup",{label:"P Series",children:[r.jsx("option",{value:"P2S",children:"P2S"}),r.jsx("option",{value:"P1S",children:"P1S"}),r.jsx("option",{value:"P1P",children:"P1P"})]}),r.jsxs("optgroup",{label:"A1 Series",children:[r.jsx("option",{value:"A1",children:"A1"}),r.jsx("option",{value:"A1 Mini",children:"A1 Mini"})]})]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Location / Group"}),r.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")}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:n("printers.locationHelp")})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.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"}),r.jsx("label",{htmlFor:"edit_auto_archive",className:"text-sm text-bambu-gray",children:n("printers.modal.autoArchiveLabel")})]}),r.jsxs("div",{className:"flex gap-3 pt-4",children:[r.jsx(Me,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:n("common.cancel")}),r.jsx(Me,{type:"submit",className:"flex-1",disabled:l.isPending,children:l.isPending?n("common.saving"):n("printers.modal.saveChanges")})]})]})]})})})}function H7e(t){const{data:e}=We({queryKey:["printerStatus",t],queryFn:()=>se.getPrinterStatus(t),refetchInterval:3e4});return!e?.connected}function q7e({printer:t,plug:e,onPowerOn:n,isPowering:a}){const i=H7e(t.id),{data:s}=We({queryKey:["smartPlugStatus",e.id],queryFn:()=>se.getSmartPlugStatus(e.id),refetchInterval:1e4});return i?r.jsxs("div",{className:"flex items-center justify-between px-3 py-2 hover:bg-gray-100 dark:hover:bg-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[r.jsx("span",{className:"text-sm text-gray-900 dark:text-white truncate",children:t.name}),s&&r.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||"?"})]}),r.jsxs("button",{onClick:()=>n(e.id),disabled:a||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:[r.jsx(wu,{className:"w-3 h-3"}),a?"...":"On"]})]}):null}function $7e(){const{t}=kt(),[e,n]=v.useState(!1),[a,i]=v.useState(()=>localStorage.getItem("hideDisconnectedPrinters")==="true"),[s,o]=v.useState(!1),[l,c]=v.useState(null),[d,u]=v.useState(()=>localStorage.getItem("printerSortBy")||"name"),[m,p]=v.useState(()=>localStorage.getItem("printerSortAsc")!=="false"),[f,b]=v.useState(()=>{const pt=localStorage.getItem("printerCardSize");return pt?parseInt(pt,10):2}),w=f===1?"compact":"expanded",[g,x]=v.useState(""),[_,N]=v.useState("all"),[C,P]=v.useState("all"),[T,A]=v.useState(0),[F,S]=v.useState(()=>{try{const pt=localStorage.getItem("printerCollapsedSections");return pt?JSON.parse(pt):{}}catch{return{}}}),M=en(),{showToast:z}=rn(),{hasPermission:I}=cr(),[H,L]=v.useState(()=>{const pt=localStorage.getItem("openEmbeddedCameras");if(pt)try{const at=JSON.parse(pt);return new Map(at.map(vt=>[vt.id,vt]))}catch{return new Map}return new Map});v.useEffect(()=>{const pt=Array.from(H.values());pt.length>0?localStorage.setItem("openEmbeddedCameras",JSON.stringify(pt)):localStorage.removeItem("openEmbeddedCameras")},[H]);const{data:Z,isLoading:re}=We({queryKey:["printers"],queryFn:se.getPrinters}),{data:J}=We({queryKey:["settings"],queryFn:se.getSettings}),de=v.useMemo(()=>{if(J?.drying_presets)try{const pt=JSON.parse(J.drying_presets);if(typeof pt=="object"&&pt!==null&&Object.keys(pt).length>0)return{...aI,...pt}}catch{}return aI},[J?.drying_presets]);v.useEffect(()=>{J?.camera_view_mode==="window"&&H.size>0&&L(new Map)},[J?.camera_view_mode,H.size]);const{data:me}=We({queryKey:["smart-plugs"],queryFn:se.getSmartPlugs}),{data:ue}=We({queryKey:["maintenanceOverview"],queryFn:se.getMaintenanceOverview,staleTime:60*1e3}),{data:W}=We({queryKey:["spoolman-status"],queryFn:se.getSpoolmanStatus,staleTime:60*1e3}),ae=W?.enabled&&W?.connected,{data:pe}=We({queryKey:["spoolman-settings"],queryFn:se.getSpoolmanSettings,enabled:!!ae,staleTime:60*1e3}),ye=pe?.spoolman_sync_mode,{data:Te}=We({queryKey:["unlinked-spools"],queryFn:se.getUnlinkedSpools,enabled:!!ae,staleTime:30*1e3}),$=Te&&Te.length>0,{data:K}=We({queryKey:["linked-spools"],queryFn:se.getLinkedSpools,enabled:!!ae,staleTime:30*1e3}),D=K?.linked,{data:j}=We({queryKey:["spool-assignments"],queryFn:()=>se.getAssignments(),enabled:I("inventory:view_assignments"),staleTime:30*1e3}),B=it({mutationFn:({printerId:pt,amsId:at,trayId:vt})=>se.unassignSpool(pt,at,vt),onSuccess:()=>{M.invalidateQueries({queryKey:["spool-assignments"]})}}),{data:X,isLoading:O}=We({queryKey:["spoolman-inventory-spools"],queryFn:()=>se.getSpoolmanInventorySpools(!1),enabled:!!ae,staleTime:30*1e3}),{data:ie,isLoading:U}=We({queryKey:["spoolman-slot-assignments"],queryFn:()=>se.getSpoolmanSlotAssignments(),enabled:!!ae,staleTime:30*1e3}),G=it({mutationFn:pt=>se.unassignSpoolmanSlot(pt),onSuccess:()=>{M.invalidateQueries({queryKey:["spoolman-inventory-spools"]}),M.invalidateQueries({queryKey:["spoolman-slot-assignments"]})}}),Y=(pt,at,vt)=>j?.find(_t=>_t.printer_id===pt&&_t.ams_id===Number(at)&&_t.tray_id===Number(vt)),Q=ue?.reduce((pt,at)=>(pt[at.printer_id]={due_count:at.due_count,warning_count:at.warning_count,total_print_hours:at.total_print_hours},pt),{})||{},oe=me?.reduce((pt,at)=>(at.printer_id&&(pt[at.printer_id]=at),pt),{})||{},ee=it({mutationFn:se.createPrinter,onSuccess:()=>{M.invalidateQueries({queryKey:["printers"]}),M.invalidateQueries({queryKey:["maintenanceOverview"]}),n(!1)},onError:pt=>z(pt.message||t("printers.toast.failedToAdd"),"error")}),ge=it({mutationFn:pt=>se.controlSmartPlug(pt,"on"),onSuccess:()=>{M.invalidateQueries({queryKey:["smart-plugs"]}),c(null)},onError:()=>{c(null)}}),[ce,le]=v.useState(new Set),[q,R]=v.useState(!1),[ne,xe]=v.useState(null),[we,Ne]=v.useState(!1),ve=q||ce.size>0,be=v.useCallback(pt=>{le(at=>{const vt=new Set(at);return vt.has(pt)?vt.delete(pt):vt.add(pt),vt})},[]),Ee=v.useCallback(()=>{le(new Set),R(!1)},[]);v.useEffect(()=>{const pt=at=>{at.key==="Escape"&&ve&&Ee()};return window.addEventListener("keydown",pt),()=>window.removeEventListener("keydown",pt)},[ve,Ee]);const ze=v.useCallback(async pt=>{Ne(!0);const vt=Array.from(ce).filter(Ve=>{const Je=M.getQueryData(["printerStatus",Ve]);if(!Je?.connected)return!1;switch(pt){case"stop":return Je.state==="RUNNING"||Je.state==="PAUSE";case"pause":return Je.state==="RUNNING";case"resume":return Je.state==="PAUSE";case"clearPlate":return!!Je.awaiting_plate_clear;case"clearHMS":return Je.hms_errors&&Em(Je.hms_errors).length>0;default:return!1}});if(vt.length===0){z(t("printers.bulk.noneApplicable"),"error"),Ne(!1),xe(null);return}const _t={stop:se.stopPrint,pause:se.pausePrint,resume:se.resumePrint,clearPlate:se.clearPlate,clearHMS:se.clearHMSErrors}[pt],Dt=await Promise.allSettled(vt.map(Ve=>_t(Ve))),De=Dt.filter(Ve=>Ve.status==="fulfilled").length,je=Dt.filter(Ve=>Ve.status==="rejected").length;je===0?z(t("printers.bulk.success",{action:t(`printers.bulk.actions.${pt}`),count:De})):z(t("printers.bulk.partial",{succeeded:De,failed:je}),"error"),vt.forEach(Ve=>{M.invalidateQueries({queryKey:["printerStatus",Ve]})}),Ne(!1),xe(null)},[ce,M,z,t]),_e=v.useCallback(pt=>{pt==="stop"||pt==="pause"||pt==="clearPlate"?xe(pt):ze(pt)},[ze]),Oe=()=>{const pt=!a;i(pt),localStorage.setItem("hideDisconnectedPrinters",String(pt))},Ie=pt=>{u(pt),localStorage.setItem("printerSortBy",pt)},Ke=()=>{const pt=!m;p(pt),localStorage.setItem("printerSortAsc",String(pt))},rt=()=>{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"}},st=["S","M","L","XL"];v.useEffect(()=>M.getQueryCache().subscribe(at=>{at.type==="updated"&&Array.isArray(at.query.queryKey)&&at.query.queryKey[0]==="printerStatus"&&A(vt=>vt+1)}),[M]);const Re=v.useMemo(()=>{if(!Z)return[];let pt=Z;if(g.trim()){const at=g.trim().toLowerCase();pt=pt.filter(vt=>vt.name.toLowerCase().includes(at)||(vt.model||"").toLowerCase().includes(at)||(vt.location||"").toLowerCase().includes(at)||(vt.serial_number||"").toLowerCase().includes(at))}return C!=="all"&&(pt=pt.filter(at=>(at.location||"")===C)),_!=="all"&&(pt=pt.filter(at=>{const vt=M.getQueryData(["printerStatus",at.id]);if(!vt?.connected)return _==="offline";const _t=vt.hms_errors?Em(vt.hms_errors):[];switch(_){case"printing":return vt.state==="RUNNING";case"paused":return vt.state==="PAUSE";case"finished":return vt.state==="FINISH";case"error":return vt.state==="FAILED"||_t.length>0;case"idle":return vt.state!=="RUNNING"&&vt.state!=="PAUSE"&&vt.state!=="FINISH"&&vt.state!=="FAILED"&&_t.length===0;case"offline":return!1;default:return!0}})),pt},[Z,g,_,C,M,T]),tt=v.useMemo(()=>Z?[...new Set(Z.map(pt=>pt.location||"").filter(Boolean))].sort():[],[Z]),Ce=v.useMemo(()=>{const pt=[...Re];switch(d){case"name":pt.sort((at,vt)=>at.name.localeCompare(vt.name));break;case"model":pt.sort((at,vt)=>(at.model||"").localeCompare(vt.model||""));break;case"location":pt.sort((at,vt)=>{const _t=at.location||"",Dt=vt.location||"";return!_t&&Dt?1:_t&&!Dt?-1:_t.localeCompare(Dt)||at.name.localeCompare(vt.name)});break;case"status":pt.sort((at,vt)=>{const _t=M.getQueryData(["printerStatus",at.id]),Dt=M.getQueryData(["printerStatus",vt.id]),De=je=>je?.connected?(je.hms_errors?Em(je.hms_errors):[]).length>0?0:je.state==="RUNNING"?1:2:3;return De(_t)-De(Dt)});break}return m||pt.reverse(),pt},[Re,d,m,M]),Xe=v.useCallback(()=>{le(new Set(Ce.map(pt=>pt.id))),R(!0)},[Ce]),Ue=v.useCallback(pt=>{le(at=>{const vt=new Set(at);return Ce.forEach(_t=>{const Dt=M.getQueryData(["printerStatus",_t.id]);GK(Dt)===pt&&vt.add(_t.id)}),vt}),R(!0)},[Ce,M]),fe=v.useCallback(pt=>{le(at=>{const vt=new Set(at);return Ce.filter(_t=>(_t.location||"")===pt).forEach(_t=>vt.add(_t.id)),vt}),R(!0)},[Ce]),Ae=v.useCallback(pt=>{le(at=>{const vt=new Set(at);return Ce.filter(_t=>(_t.model||"Unknown")===pt).forEach(_t=>vt.add(_t.id)),vt}),R(!0)},[Ce]),$e=v.useCallback(pt=>{S(at=>{const vt={...at,[pt]:!at[pt]};try{localStorage.setItem("printerCollapsedSections",JSON.stringify(vt))}catch{}return vt})},[]),Be=v.useMemo(()=>{if(d==="name")return null;const pt={};return d==="location"?Ce.forEach(at=>{const vt=at.location||"Ungrouped";pt[vt]||(pt[vt]=[]),pt[vt].push(at)}):d==="model"?Ce.forEach(at=>{const vt=at.model||"Unknown";pt[vt]||(pt[vt]=[]),pt[vt].push(at)}):d==="status"&&Ce.forEach(at=>{const vt=M.getQueryData(["printerStatus",at.id]),_t=GK(vt);pt[_t]||(pt[_t]=[]),pt[_t].push(at)}),pt},[d,Ce,M,T]),nt=v.useRef(null),gt=v.useRef(null),yt=v.useRef(0),[ot,Ht]=v.useState(!1),Kt=v.useCallback(()=>{const pt=nt.current;if(!pt)return;const at=gt.current?.offsetWidth;at&&(yt.current=at);const Dt=yt.current>0&&pt.clientWidthDe===Dt?De:Dt)},[]),Zt=Object.keys(oe).length;v.useLayoutEffect(()=>{Kt();const pt=nt.current;if(!pt)return;if(typeof ResizeObserver>"u")return window.addEventListener("resize",Kt),()=>window.removeEventListener("resize",Kt);const at=new ResizeObserver(()=>Kt());return at.observe(pt),window.addEventListener("resize",Kt),()=>{at.disconnect(),window.removeEventListener("resize",Kt)}},[Kt,Z?.length,tt.length,a,Zt]);const Yt=(pt=!1)=>r.jsxs(r.Fragment,{children:[Z&&Z.length>0&&r.jsx(h3,{value:_,onChange:N,fullWidth:pt,options:[{value:"all",label:t("printers.filter.allStatuses")},{value:"printing",label:t("printers.status.printing")},{value:"paused",label:t("printers.status.paused")},{value:"idle",label:t("printers.status.idle")},{value:"finished",label:t("printers.status.finished")},{value:"error",label:t("printers.status.error")},{value:"offline",label:t("printers.status.offline")}]}),Z&&Z.length>0&&tt.length>0&&r.jsx(h3,{value:C,onChange:P,fullWidth:pt,options:[{value:"all",label:t("printers.filter.allLocations")},...tt.map(at=>({value:at,label:at}))]}),r.jsx("button",{type:"button",onClick:Oe,"aria-pressed":a,className:`h-8 px-2 rounded-lg border text-sm font-medium transition-colors ${pt?"w-full":""} ${a?"bg-bambu-green border-bambu-green text-white":"bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary"}`,children:t("printers.hideOffline")})]}),gn=(pt=!1)=>r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:`flex items-center gap-1 ${pt?"w-full":""}`,children:[r.jsx(h3,{value:d,onChange:Ie,fullWidth:pt,options:[{value:"name",label:t("printers.sort.name")},{value:"status",label:t("printers.sort.status")},{value:"model",label:t("printers.sort.model")},{value:"location",label:t("printers.sort.location")}]}),r.jsx("button",{onClick:Ke,className:"h-8 shrink-0 px-2 rounded-lg border bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary transition-colors flex items-center justify-center",title:t(m?"printers.sort.descending":"printers.sort.ascending"),children:m?r.jsx(Hm,{className:"w-4 h-4 text-white"}):r.jsx(Bh,{className:"w-4 h-4 text-white"})})]}),r.jsx("div",{className:`flex h-8 items-center bg-bambu-dark rounded-lg border border-bambu-dark-tertiary ${pt?"w-full":""}`,children:st.map((at,vt)=>{const _t=vt+1,Dt=f===_t;return r.jsx("button",{onClick:()=>{b(_t),localStorage.setItem("printerCardSize",String(_t))},className:`h-full px-2 text-xs font-medium transition-colors ${pt?"flex-1":""} ${vt===0?"rounded-l-lg":""} ${vt===st.length-1?"rounded-r-lg":""} ${Dt?"bg-bambu-green text-white":"text-white hover:bg-bambu-dark-tertiary"}`,title:t(at==="S"?"printers.cardSize.small":at==="M"?"printers.cardSize.medium":at==="L"?"printers.cardSize.large":"printers.cardSize.extraLarge"),children:at},at)})})]}),ln=(pt=!1)=>r.jsxs(r.Fragment,{children:[r.jsxs("button",{onClick:()=>{ve?Ee():R(!0)},className:`h-8 px-2 rounded-lg border transition-colors ${pt?"w-full justify-center gap-1.5 text-sm font-medium flex items-center":""} ${ve?"bg-bambu-green border-bambu-green text-white":"bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary"}`,title:t("printers.bulk.select"),disabled:!I("printers:control"),children:[r.jsx(bs,{className:"w-4 h-4"}),pt&&r.jsx("span",{children:t("printers.bulk.select")})]}),a&&Object.keys(oe).length>0&&r.jsxs("div",{className:`relative ${pt?"w-full":""}`,children:[r.jsxs("button",{onClick:()=>o(!s),className:`h-8 flex items-center gap-1.5 px-2 text-sm rounded-lg border transition-colors ${pt?"w-full justify-between bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary hover:text-white":"bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary"}`,children:[r.jsxs("span",{className:"flex items-center gap-1.5",children:[r.jsx(wu,{className:"w-4 h-4"}),t("printers.powerOn")]}),r.jsx(Rn,{className:`w-3 h-3 transition-transform ${s?"rotate-180":""}`})]}),s&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>o(!1)}),r.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:[r.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")}),Z?.filter(at=>oe[at.id]).map(at=>r.jsx(q7e,{printer:at,plug:oe[at.id],onPowerOn:vt=>{c(vt),ge.mutate(vt)},isPowering:l===oe[at.id]?.id},at.id)),Z?.filter(at=>oe[at.id]).length===0&&r.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:"No printers with smart plugs"})]})]})]}),r.jsxs(Me,{onClick:()=>n(!0),disabled:!I("printers:create"),title:I("printers:create")?void 0:t("printers.permission.noAdd"),className:`!h-8 !min-h-8 px-2 py-0 ${pt?"w-full":""}`,children:[r.jsx(ar,{className:"w-4 h-4"}),t("printers.addPrinter")]})]});return r.jsxs("div",{className:"p-4 md:p-8",children:[r.jsxs("div",{className:"space-y-3 mb-6",children:[r.jsxs("div",{children:[r.jsxs("h1",{className:"text-2xl font-bold text-white flex items-center gap-3",children:[r.jsx(pr,{className:"w-7 h-7 text-bambu-green"}),t("printers.title")]}),r.jsx(I7e,{printers:Z})]}),r.jsxs("div",{ref:nt,className:"relative flex items-center gap-2",children:[Z&&Z.length>0&&r.jsxs("div",{className:"relative min-w-0 flex-1",children:[r.jsx(Sr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50"}),r.jsx("input",{type:"search",name:"printer-search",autoComplete:"off","data-1p-ignore":!0,"data-lpignore":"true",value:g,onChange:pt=>x(pt.target.value),placeholder:t("printers.search"),"aria-label":t("printers.search"),className:"w-full h-8 pl-9 pr-8 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"}),g&&r.jsx("button",{type:"button","aria-label":t("common.clear"),onClick:()=>x(""),className:"absolute right-3 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white",children:r.jsx(Bt,{className:"w-4 h-4"})})]}),r.jsxs("div",{ref:gt,"aria-hidden":ot,inert:ot,className:`${ot?"absolute -left-[9999px] top-0 flex w-max pointer-events-none opacity-0":"flex"} ml-auto items-center justify-end gap-2 flex-nowrap [&>*]:shrink-0`,children:[r.jsx("div",{className:"h-6 w-px bg-bambu-dark-tertiary"}),r.jsx("div",{className:"flex items-center gap-2",children:Yt()}),r.jsx("div",{className:"h-6 w-px bg-bambu-dark-tertiary"}),r.jsx("div",{className:"flex items-center gap-2",children:gn()}),r.jsx("div",{className:"h-6 w-px bg-bambu-dark-tertiary"}),r.jsx("div",{className:"flex items-center gap-2",children:ln()})]}),ot&&r.jsxs("div",{className:"ml-auto flex items-center justify-end gap-1",children:[r.jsx(f3,{label:t("printers.toolbar.filters","Filters"),icon:r.jsx(_S,{className:"w-4 h-4"}),children:r.jsx("div",{className:"flex w-48 flex-col gap-2",children:Yt(!0)})}),r.jsx(f3,{label:t("printers.toolbar.view","View"),icon:r.jsx(xye,{className:"w-4 h-4"}),children:r.jsx("div",{className:"flex w-48 flex-col gap-2",children:gn(!0)})}),r.jsx(f3,{label:t("printers.toolbar.actions","Actions"),icon:r.jsx(qge,{className:"w-4 h-4"}),children:r.jsx("div",{className:"flex w-48 flex-col gap-2",children:ln(!0)})})]})]})]}),re?r.jsx("div",{className:"text-center py-12 text-bambu-gray",children:t("common.loading")}):Z?.length===0?r.jsx(Ct,{children:r.jsxs(At,{className:"text-center py-12",children:[r.jsx("p",{className:"text-bambu-gray mb-4",children:t("printers.noPrintersConfigured")}),r.jsxs(Me,{onClick:()=>n(!0),disabled:!I("printers:create"),title:I("printers:create")?void 0:t("printers.permission.noAdd"),children:[r.jsx(ar,{className:"w-4 h-4"}),t("printers.addPrinter")]})]})}):Ce.length===0&&(g.trim()||_!=="all"||C!=="all")?r.jsx(Ct,{children:r.jsx(At,{className:"text-center py-12",children:r.jsx("p",{className:"text-bambu-gray",children:t("printers.noSearchResults")})})}):Be?r.jsx("div",{className:"space-y-6",children:(()=>{const pt=d==="status"?O7e.filter(at=>Be[at]?.length>0):Object.keys(Be);return m?pt:[...pt].reverse()})().map(pt=>{const at=Be[pt],vt=`${d}:${pt}`,_t=!F[vt],Dt=d==="status"&&VK[pt]?.dot||"bg-bambu-green",De=d==="status"?t(VK[pt]?.labelKey||pt):pt;return r.jsx(s5,{open:_t,onToggle:()=>$e(vt),summaryClassName:"py-1",summary:r.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[r.jsx("span",{className:`w-2 h-2 rounded-full ${Dt}`}),De,r.jsxs("span",{className:"text-sm font-normal text-bambu-gray",children:["(",at.length,")"]}),ve&&r.jsx("button",{onClick:je=>{je.stopPropagation(),d==="location"?fe(pt==="Ungrouped"?"":pt):d==="status"?Ue(pt):d==="model"&&Ae(pt)},className:"text-xs text-bambu-green hover:text-bambu-green-light transition-colors ml-1",children:t("printers.bulk.selectAll")})]}),children:r.jsx("div",{className:`grid gap-4 ${f>=3?"gap-6":""} ${rt()}`,children:at.map(je=>r.jsx(KK,{printer:je,hideIfDisconnected:a,maintenanceInfo:Q[je.id],viewMode:w,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:ae,hasUnlinkedSpools:$,linkedSpools:D,spoolmanUrl:W?.url,spoolmanSyncMode:ye,onGetAssignment:Y,onUnassignSpool:(Ve,Je,Le)=>B.mutate({printerId:Ve,amsId:Je,trayId:Le}),spoolmanSpools:X,spoolmanSlotAssignments:ie,spoolmanLoading:O||U,onUnassignSpoolmanSpool:Ve=>G.mutate(Ve),timeFormat:J?.time_format||"system",cameraViewMode:J?.camera_view_mode||"window",onOpenEmbeddedCamera:(Ve,Je)=>L(Le=>new Map(Le).set(Ve,{id:Ve,name:Je})),checkPrinterFirmware:J?.check_printer_firmware!==!1,dryingPresets:de,requirePlateClear:J?.require_plate_clear===!0,selectionMode:ve,isSelected:ce.has(je.id),onToggleSelect:be},je.id))})},pt)})}):r.jsx("div",{className:`grid gap-4 ${f>=3?"gap-6":""} ${rt()}`,children:Ce.map(pt=>r.jsx(KK,{printer:pt,hideIfDisconnected:a,maintenanceInfo:Q[pt.id],viewMode:w,cardSize:f,spoolmanEnabled:ae,hasUnlinkedSpools:$,linkedSpools:D,spoolmanUrl:W?.url,spoolmanSyncMode:ye,onGetAssignment:Y,onUnassignSpool:(at,vt,_t)=>B.mutate({printerId:at,amsId:vt,trayId:_t}),spoolmanSpools:X,spoolmanSlotAssignments:ie,spoolmanLoading:O||U,onUnassignSpoolmanSpool:at=>G.mutate(at),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:(at,vt)=>L(_t=>new Map(_t).set(at,{id:at,name:vt})),checkPrinterFirmware:J?.check_printer_firmware!==!1,dryingPresets:de,requirePlateClear:J?.require_plate_clear===!0,selectionMode:ve,isSelected:ce.has(pt.id),onToggleSelect:be},pt.id))}),e&&r.jsx(z7e,{onClose:()=>n(!1),onAdd:pt=>ee.mutate(pt),existingSerials:Z?.map(pt=>pt.serial_number)||[]}),ve&&Z&&r.jsx(Wve,{selectedIds:ce,printers:Z,onClose:Ee,onSelectAll:Xe,onSelectByLocation:fe,onSelectByState:Ue,onAction:_e,actionPending:we}),ne==="stop"&&r.jsx(vn,{title:t("printers.bulk.confirm.stopTitle",{count:ce.size}),message:t("printers.bulk.confirm.stopMessage",{count:ce.size}),confirmText:t("printers.bulk.confirm.stopButton"),variant:"danger",isLoading:we,onConfirm:()=>ze("stop"),onCancel:()=>xe(null)}),ne==="pause"&&r.jsx(vn,{title:t("printers.bulk.confirm.pauseTitle",{count:ce.size}),message:t("printers.bulk.confirm.pauseMessage",{count:ce.size}),confirmText:t("printers.bulk.confirm.pauseButton"),isLoading:we,onConfirm:()=>ze("pause"),onCancel:()=>xe(null)}),ne==="clearPlate"&&r.jsx(vn,{title:t("printers.bulk.confirm.clearPlateTitle",{count:ce.size}),message:t("printers.bulk.confirm.clearPlateMessage",{count:ce.size}),confirmText:t("printers.bulk.confirm.clearPlateButton"),isLoading:we,onConfirm:()=>ze("clearPlate"),onCancel:()=>xe(null)}),Array.from(H.values()).map((pt,at)=>r.jsx(KEe,{printerId:pt.id,printerName:pt.name,viewerIndex:at,onClose:()=>L(vt=>{const _t=new Map(vt);return _t.delete(pt.id),_t})},pt.id))]})}const Gie=v.createContext(null),V7e=1500,G7e=1e3,b3=t=>`slice-job-${t}`;function q1(t){try{return decodeURIComponent(t)}catch{return t}}function W7e(t){const e=Math.max(0,Math.floor(t));if(e<60)return`${e}s`;const n=Math.floor(e/60),a=e%60;if(n<60)return`${n}m ${a}s`;const i=Math.floor(n/60),s=n%60;return`${i}h ${s}m`}function K7e({children:t}){const{t:e}=kt(),{showToast:n,showPersistentToast:a,dismissToast:i}=rn(),s=en(),[o,l]=v.useState([]),c=v.useRef([]);c.current=o;const d=v.useRef(new Map),u=v.useRef(new Map),m=v.useRef(new Map),p=v.useCallback(w=>{const g=d.current.get(w.id);if(g==null)return;const x=(Date.now()-g)/1e3,_=u.current.get(w.id)??"pending",N=W7e(x),C=m.current.get(w.id)??null,P=C&&C.stage&&C.total_percent>0;if(_==="running"&&P){a(b3(w.id),e("slice.runningWithProgress","{{name}} — {{stage}} ({{percent}}%) — {{elapsed}}",{name:q1(w.sourceName),stage:C.stage,percent:Math.min(100,Math.max(0,Math.round(C.total_percent))),elapsed:N}),"loading");return}const T=_==="pending"?"slice.queuedToast":"slice.runningToast",A=_==="pending"?"Queued: {{name}} — {{elapsed}}":"Slicing {{name}} — {{elapsed}}";a(b3(w.id),e(T,A,{name:q1(w.sourceName),elapsed:N}),"loading")},[a,e]),f=v.useCallback((w,g,x)=>{l(_=>_.some(N=>N.id===w)?_:[..._,{id:w,kind:g,sourceName:x}]),d.current.set(w,Date.now()),u.current.set(w,"pending"),m.current.set(w,null),p({id:w,kind:g,sourceName:x})},[p]),b=v.useCallback((w,g)=>{if(l(x=>x.filter(_=>_.id!==w.id)),d.current.delete(w.id),u.current.delete(w.id),m.current.delete(w.id),i(b3(w.id)),g.status==="completed")n(e("slice.completedToast","Sliced {{name}}",{name:q1(w.sourceName)}),"success");else if(g.status==="failed"){const x=g.error_detail||e("slice.failed");n(e("slice.failedToast","Slicing {{name}} failed: {{detail}}",{name:q1(w.sourceName),detail:x}),"error")}s.invalidateQueries({queryKey:["library-files"]}),s.invalidateQueries({queryKey:["archives"]})},[i,s,n,e]);return v.useEffect(()=>{if(o.length===0)return;let w=!1;const g=setInterval(async()=>{if(w)return;const x=[...c.current];for(const _ of x)try{const N=await se.getSliceJob(_.id);u.current.set(_.id,N.status),N.progress&&m.current.set(_.id,N.progress),(N.status==="completed"||N.status==="failed")&&b(_,N)}catch{}},V7e);return()=>{w=!0,clearInterval(g)}},[o.length,b]),v.useEffect(()=>{if(o.length===0)return;const w=setInterval(()=>{for(const g of c.current)p(g)},G7e);return()=>clearInterval(w)},[o.length,p]),r.jsx(Gie.Provider,{value:{trackJob:f,activeJobs:o},children:t})}function Y7e(){const t=v.useContext(Gie);if(!t)throw new Error("useSliceJobTracker must be used inside SliceJobTrackerProvider");return t}function o5({plates:t,onSelect:e,onClose:n}){const{t:a}=kt();return r.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4",onClick:n,children:r.jsxs("div",{className:"w-full max-w-3xl max-h-[85vh] flex flex-col rounded-lg bg-bambu-dark-secondary border border-bambu-dark-tertiary/60",onClick:i=>i.stopPropagation(),children:[r.jsxs("div",{className:"flex-shrink-0 flex items-start justify-between gap-3 px-4 pt-4 pb-3 border-b border-bambu-dark-tertiary/40",children:[r.jsxs("div",{className:"min-w-0",children:[r.jsx("h3",{className:"text-white font-medium",children:a("archives.platePicker.title")}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:a("archives.platePicker.hint")})]}),r.jsx("button",{onClick:n,className:"flex-shrink-0 text-bambu-gray hover:text-white transition-colors","aria-label":a("common.close","Close"),children:r.jsx(Bt,{className:"w-5 h-5"})})]}),r.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:r.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:t.map(i=>r.jsxs("button",{type:"button",onClick:()=>e(i.index),className:"flex items-center gap-2 p-2 rounded-lg border border-bambu-dark-tertiary bg-bambu-dark hover:border-bambu-gray transition-colors text-left",children:[i.has_thumbnail&&i.thumbnail_url!=null?r.jsx("img",{src:La(i.thumbnail_url),alt:`Plate ${i.index}`,className:"w-12 h-12 rounded object-cover bg-bambu-dark-tertiary flex-shrink-0"}):r.jsx("div",{className:"w-12 h-12 rounded bg-bambu-dark-tertiary flex items-center justify-center flex-shrink-0",children:r.jsx(oa,{className:"w-5 h-5 text-bambu-gray"})}),r.jsxs("div",{className:"min-w-0 flex-1",children:[r.jsx("p",{className:"text-sm text-white font-medium truncate",children:i.name?`${a("archives.platePicker.plateLabel",{index:i.index})} — ${i.name}`:a("archives.platePicker.plateLabel",{index:i.index})}),r.jsxs("p",{className:"text-xs text-bambu-gray truncate",children:[i.objects.length>0?i.objects.slice(0,3).join(", ")+(i.objects.length>3?"…":""):i.object_count!=null&&i.object_count>0?a("archives.platePicker.objectCount",{count:i.object_count}):`${i.filaments.length} filament${i.filaments.length!==1?"s":""}`,i.print_time_seconds!=null?` • ${ds(i.print_time_seconds)}`:""]})]})]},i.index))})})]})})}const Wie=["local","cloud","standard"];function iI(t,e){for(const n of Wie){const a=t[n][e];if(a.length>0)return{source:a[0].source,id:a[0].id}}return null}const X7e={local:1.5,cloud:1,standard:.5};function Q7e(t,e){const n=e.type.trim().toUpperCase(),a=Oa(e.color);let i=null;for(const s of Wie)for(const o of t[s].filament){let l=0;const c=(o.filament_type??"").trim().toUpperCase(),d=Oa(o.filament_colour??"");n&&c&&n===c&&(l+=10),a&&d&&(d===a?l+=5:ld(o.filament_colour??"",e.color)&&(l+=2)),l+=X7e[s],(i==null||l>i.score)&&(i={ref:{source:o.source,id:o.id},score:l})}return i==null?iI(t,"filament"):i.ref}function Z7e(t){return t?`${t.source}:${t.id}`:""}function J7e(t){if(!t)return null;const e=t.indexOf(":");if(e<0)return null;const n=t.slice(0,e),a=t.slice(e+1);return n!=="cloud"&&n!=="local"&&n!=="standard"?null:{source:n,id:a}}function e9e({requestId:t,sourceName:e}){const{t:n}=kt(),{showPersistentToast:a,dismissToast:i}=rn(),[s,o]=v.useState(0),[l,c]=v.useState(null);let d=e;try{d=decodeURIComponent(e)}catch{}v.useEffect(()=>{const b=Date.now(),w=setInterval(()=>o(Math.floor((Date.now()-b)/1e3)),1e3);return()=>clearInterval(w)},[]),v.useEffect(()=>{let b=!1;const w=setInterval(async()=>{if(b)return;const g=await se.getPreviewSliceProgress(t);!b&&g&&c(g)},1e3);return()=>{b=!0,clearInterval(w)}},[t]);const u=`slice-preview-${t}`;v.useEffect(()=>{const b=l&&l.stage&&l.total_percent>0,w=t9e(s);return b?a(u,n("slice.previewWithProgress","Analyzing {{name}} — {{stage}} ({{percent}}%) — {{elapsed}}",{name:d,stage:l.stage,percent:Math.min(100,Math.max(0,Math.round(l.total_percent))),elapsed:w}),"loading"):a(u,n("slice.previewToast","Analyzing {{name}} — {{elapsed}}",{name:d,elapsed:w}),"loading"),()=>{i(u)}},[s,l,d,a,i,n,u]);const m=l?.stage,p=l?.total_percent,f=m&&typeof p=="number"&&p>0?`${m} (${Math.min(100,Math.max(0,Math.round(p)))}%)`:n("slice.analyzingPlateFilaments","Analyzing plate filaments…");return r.jsxs("div",{className:"flex flex-col gap-1 text-bambu-gray text-sm py-2",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(ut,{className:"w-4 h-4 animate-spin"}),f,r.jsxs("span",{className:"text-xs tabular-nums",children:[s,"s"]})]}),s>=5&&r.jsx("div",{className:"text-xs text-bambu-gray/70 pl-6",children:n("slice.analyzingPlateFilamentsHint","Running a preview slice to discover which AMS slots this plate uses. Cached after — re-opening is instant.")})]})}function t9e(t){const e=Math.max(0,Math.floor(t));if(e<60)return`${e}s`;const n=Math.floor(e/60),a=e%60;if(n<60)return`${n}m ${a}s`;const i=Math.floor(n/60),s=n%60;return`${i}h ${s}m`}function DA({source:t,onClose:e}){const{t:n}=kt(),{trackJob:a}=Y7e(),[i,s]=v.useState(null),[o,l]=v.useState(null),[c,d]=v.useState([]),[u,m]=v.useState(null),[p,f]=v.useState(null),[b,w]=v.useState([]),[g,x]=v.useState(null),[_,N]=v.useState(null),C=We({queryKey:["slicePlates",t.kind,t.id],queryFn:async()=>t.kind==="libraryFile"?se.getLibraryFilePlates(t.id):se.getArchivePlates(t.id),staleTime:6e4}),T=!!C.data?.is_multi_plate&&(C.data?.plates?.length??0)>1&&_==null,A=_??1,F=v.useMemo(()=>{const W=typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`;return`${t.kind}-${t.id}-p${A}-${W}`},[t.kind,t.id,A]),S=We({queryKey:["sliceFilamentReqs",t.kind,t.id,A],queryFn:async()=>t.kind==="libraryFile"?se.getLibraryFileFilamentRequirements(t.id,A,F):se.getArchiveFilamentRequirements(t.id,A,F),enabled:!T,staleTime:6e4}),M=v.useMemo(()=>{const W=S.data?.filaments??[];return W.length>0?W:[{slot_id:1,type:"",color:"",used_grams:0,used_meters:0}]},[S.data]),z=We({queryKey:["slicerPresets"],queryFn:()=>se.getSlicerPresets(),staleTime:6e4,enabled:!C.isLoading&&!T}),I=We({queryKey:["slicerBundles"],queryFn:se.listSlicerBundles,staleTime:6e4,enabled:!C.isLoading&&!T,retry:!1}),H=v.useMemo(()=>!u||!I.data?null:I.data.find(W=>W.id===u)??null,[u,I.data]),L=H!=null;v.useEffect(()=>{z.data&&(i==null&&s(iI(z.data,"printer")),o==null&&l(iI(z.data,"process")))},[z.data]),v.useEffect(()=>{if(!z.data)return;const W=z.data;d(ae=>ae.length===M.length&&ae.every(pe=>pe!=null)?ae:M.map(pe=>Q7e(W,{type:pe.type,color:pe.color})))},[z.data,M]),v.useEffect(()=>{if(!H){f(null),w([]);return}f(W=>W&&H.process.includes(W)?W:H.process[0]??null),w(W=>{if(W.length===M.length&&W.every(pe=>pe!=null))return W;const ae=H.filament[0]??null;return M.map((pe,ye)=>W[ye]??ae)})},[H,M]);const Z=it({mutationFn:async()=>{let W;if(L){if(!H||!p||b.length===0||b.some(pe=>pe==null))throw new Error(n("slice.bundleAllRequired","Bundle process and every filament slot must be picked"));W={bundle:{bundle_id:H.id,printer_name:H.printer[0]??H.printer_preset_name,process_name:p,filament_names:b},..._!=null?{plate:_}:{}}}else{if(!i||!o||c.length===0||c.some(ae=>ae==null))throw new Error(n("slice.allPresetsRequired","All presets must be selected"));W={printer_preset:i,process_preset:o,filament_preset:c[0],filament_presets:c,..._!=null?{plate:_}:{}}}return t.kind==="libraryFile"?se.sliceLibraryFile(t.id,W):se.sliceArchive(t.id,W)},onSuccess:W=>{a(W.job_id,t.kind,t.filename),e()},onError:W=>{const ae=W instanceof Error?W.message:String(W);x(ae)}}),re=C.data?.source_printer_model??null,J=L?H?.printer_preset_name.replace(/^# /,"")??null:i?z.data?.[i.source].printer.find(W=>W.id===i.id)?.name:null,de=!!re&&!!J&&!J.toLowerCase().includes(re.toLowerCase()),me=L?H!=null&&p!=null&&S.isSuccess&&b.length>0&&b.every(W=>W!=null)&&!de:i!=null&&o!=null&&S.isSuccess&&c.length>0&&c.every(W=>W!=null)&&!de,ue=Z.isPending;return T&&C.data?r.jsx(o5,{plates:C.data.plates,onSelect:W=>N(W),onClose:e}):r.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4",onClick:()=>{ue||e()},children:r.jsxs("div",{className:"w-full max-w-xl max-h-[85vh] flex flex-col rounded-lg bg-bambu-dark-secondary border border-bambu-dark-tertiary/60",onClick:W=>W.stopPropagation(),children:[r.jsxs("div",{className:"flex-shrink-0 flex items-start justify-between gap-3 px-4 pt-4 pb-3 border-b border-bambu-dark-tertiary/40",children:[r.jsxs("div",{className:"min-w-0",children:[r.jsxs("h3",{className:"text-white font-medium flex items-center gap-2",children:[r.jsx(cu,{className:"w-4 h-4"}),n("slice.title","Slice model")]}),r.jsxs("p",{className:"text-xs text-bambu-gray mt-1 truncate",title:t.filename,children:[t.filename,_!=null?` • ${n("archives.platePicker.plateLabel",{index:_})}`:""]})]}),r.jsx("button",{onClick:e,disabled:ue,className:"flex-shrink-0 text-bambu-gray hover:text-white transition-colors disabled:opacity-50","aria-label":n("common.close","Close"),children:r.jsx(Bt,{className:"w-5 h-5"})})]}),r.jsxs("div",{className:"flex-1 overflow-y-auto p-4 space-y-4",children:[(C.isLoading||z.isLoading)&&r.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray text-sm",children:[r.jsx(ut,{className:"w-4 h-4 animate-spin"}),n("slice.loadingPresets","Loading presets…")]}),z.isError&&r.jsx("div",{className:"text-sm text-red-400",role:"alert",children:n("slice.presetsLoadFailed","Failed to load presets. Open Settings → Profiles to import them, or sign in to Bambu Cloud.")}),z.data&&r.jsxs(r.Fragment,{children:[r.jsx(n9e,{status:z.data.cloud_status}),I.data&&I.data.length>0&&r.jsx(r9e,{bundles:I.data,selectedId:u,onChange:m,disabled:ue}),!L&&r.jsxs(r.Fragment,{children:[r.jsx(x3,{label:n("slice.printer","Printer profile"),slot:"printer",data:z.data,value:i,onChange:s,disabled:ue}),r.jsx(x3,{label:n("slice.process","Process profile"),slot:"process",data:z.data,value:o,onChange:l,disabled:ue})]}),L&&H&&r.jsxs(r.Fragment,{children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("slice.printer","Printer profile")}),r.jsx("div",{className:"px-3 py-2 rounded-md bg-bambu-dark/40 border border-bambu-dark-tertiary text-white text-sm",children:H.printer_preset_name})]}),r.jsx(YK,{label:n("slice.process","Process profile"),options:H.process,value:p,onChange:f,disabled:ue})]}),S.isLoading?r.jsx(e9e,{requestId:F,sourceName:t.filename}):L&&H?M.map((W,ae)=>{const pe=W.used_in_plate!==!1,ye=M.length>1?n("slice.filamentSlot",{index:ae+1,type:W.type,defaultValue:`Filament ${ae+1} (${W.type||""})`}):n("slice.filament","Filament profile"),Te=pe?ye:`${ye} ${n("slice.notUsedByPlate","— not used by this plate")}`;return r.jsx(YK,{label:Te,options:H.filament,value:b[ae]??null,onChange:$=>w(K=>{const D=K.length===M.length?[...K]:M.map((j,B)=>K[B]??null);return D[ae]=$,D}),disabled:ue||!pe,swatchColor:M.length>1?W.color:void 0},`bundle-filament-${ae}`)}):M.map((W,ae)=>{const pe=W.used_in_plate!==!1,ye=M.length>1?n("slice.filamentSlot",{index:ae+1,type:W.type,defaultValue:`Filament ${ae+1} (${W.type||""})`}):n("slice.filament","Filament profile"),Te=pe?ye:`${ye} ${n("slice.notUsedByPlate","— not used by this plate")}`;return r.jsx(x3,{label:Te,slot:"filament",data:z.data,value:c[ae]??null,onChange:$=>d(K=>{const D=K.length===M.length?[...K]:M.map((j,B)=>K[B]??null);return D[ae]=$,D}),disabled:ue||!pe,swatchColor:M.length>1?W.color:void 0},`filament-${ae}`)})]}),de&&r.jsx("div",{className:"text-sm text-amber-200 bg-amber-900/20 border border-amber-700/40 rounded p-2",role:"alert",children:n("slice.printerMismatch",{source:re,target:J,defaultValue:"This 3MF was sliced for {{source}}, but you picked {{target}}. The slicer CLI cannot re-slice a 3MF for a different printer — open the source in Bambu Studio, change the printer, and re-export."})}),g&&r.jsx("div",{className:"text-sm text-red-400 bg-red-900/20 border border-red-900/40 rounded p-2",role:"alert",children:g})]}),r.jsxs("div",{className:"flex-shrink-0 flex justify-end gap-2 px-4 py-3 border-t border-bambu-dark-tertiary/40",children:[r.jsx("button",{type:"button",onClick:e,disabled:ue,className:"px-3 py-1.5 text-sm rounded-md border border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray transition-colors disabled:opacity-50",children:n("common.cancel","Cancel")}),r.jsx("button",{type:"button",onClick:()=>{x(null),Z.mutate()},disabled:!me||ue,className:"px-3 py-1.5 text-sm rounded-md bg-bambu-green hover:bg-bambu-green/90 text-bambu-dark font-medium transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2",children:ue?r.jsxs(r.Fragment,{children:[r.jsx(ut,{className:"w-4 h-4 animate-spin"}),n("slice.enqueuing","Submitting slice job…")]}):n("slice.action","Slice")})]})]})})}function n9e({status:t}){const{t:e}=kt();if(t==="ok")return null;const n={not_authenticated:{tone:"border-bambu-dark-tertiary/40 bg-bambu-dark text-bambu-gray",icon:ib,key:"slice.cloud.notAuthenticated",fallback:"Sign in to Bambu Cloud (Settings → Profiles → Cloud) to see your cloud presets."},expired:{tone:"border-amber-700/40 bg-amber-900/20 text-amber-200",icon:zF,key:"slice.cloud.expired",fallback:"Bambu Cloud session expired — sign in again to refresh your cloud presets."},unreachable:{tone:"border-bambu-dark-tertiary/40 bg-bambu-dark text-bambu-gray",icon:zF,key:"slice.cloud.unreachable",fallback:"Bambu Cloud is unreachable right now. Local and standard presets still work."}},{tone:a,icon:i,key:s,fallback:o}=n[t];return r.jsxs("div",{className:`flex items-start gap-2 text-xs rounded-md border p-2 ${a}`,role:"status",children:[r.jsx(i,{className:"w-4 h-4 flex-shrink-0 mt-0.5"}),r.jsx("span",{children:e(s,o)})]})}function x3({label:t,slot:e,data:n,value:a,onChange:i,disabled:s,swatchColor:o}){const{t:l}=kt(),c=v.useMemo(()=>[{key:"local",tier:"local",label:"slice.tier.local",fallback:"Imported"},{key:"cloud",tier:"cloud",label:"slice.tier.cloud",fallback:"Cloud"},{key:"standard",tier:"standard",label:"slice.tier.standard",fallback:"Standard"}].map(({key:m,label:p,fallback:f})=>({tierLabel:l(p,f),entries:n[m][e]})).filter(m=>m.entries.length>0),[n,e,l]),d=c.reduce((u,m)=>u+m.entries.length,0);return r.jsxs("label",{className:"block",children:[r.jsxs("span",{className:"flex items-center gap-2 text-xs text-bambu-gray mb-1",children:[o&&r.jsx("span",{className:"inline-block w-3 h-3 rounded-full border border-bambu-dark-tertiary",style:{backgroundColor:o||"transparent"},"aria-hidden":!0}),r.jsx("span",{children:t})]}),r.jsxs("select",{value:Z7e(a),onChange:u=>i(J7e(u.target.value)),disabled:s||d===0,className:"w-full px-3 py-2 rounded-md bg-bambu-dark border border-bambu-dark-tertiary text-white text-sm focus:outline-none focus:border-bambu-gray disabled:opacity-50",children:[r.jsx("option",{value:"",children:d===0?l("slice.noPresetsForSlot","No presets available"):l("slice.selectPreset","— Select a preset —")}),c.map(u=>r.jsx("optgroup",{label:u.tierLabel,children:u.entries.map(m=>r.jsx("option",{value:`${m.source}:${m.id}`,children:m.name},`${m.source}:${m.id}`))},u.tierLabel))]})]})}function r9e({bundles:t,selectedId:e,onChange:n,disabled:a}){const{t:i}=kt();return r.jsxs("label",{className:"block",children:[r.jsxs("span",{className:"block text-sm text-bambu-gray mb-1 inline-flex items-center gap-1.5",children:[r.jsx(Br,{className:"w-3.5 h-3.5"}),i("slice.bundle","Slicer bundle")]}),r.jsxs("select",{value:e??"",onChange:s=>n(s.target.value||null),disabled:a,className:"w-full px-3 py-2 rounded-md bg-bambu-dark border border-bambu-dark-tertiary text-white text-sm focus:outline-none focus:border-bambu-gray disabled:opacity-50",children:[r.jsx("option",{value:"",children:i("slice.bundleNone","— None (pick presets individually) —")}),t.map(s=>r.jsx("option",{value:s.id,children:s.printer_preset_name},s.id))]})]})}function YK({label:t,options:e,value:n,onChange:a,disabled:i,swatchColor:s}){const{t:o}=kt();return r.jsxs("label",{className:"block",children:[r.jsxs("span",{className:"block text-sm text-bambu-gray mb-1 inline-flex items-center gap-1.5",children:[s&&r.jsx("span",{className:"inline-block w-3 h-3 rounded-sm border border-black/20",style:{backgroundColor:s||"transparent"},"aria-hidden":!0}),r.jsx("span",{children:t})]}),r.jsxs("select",{value:n??"",onChange:l=>a(l.target.value||null),disabled:i||e.length===0,className:"w-full px-3 py-2 rounded-md bg-bambu-dark border border-bambu-dark-tertiary text-white text-sm focus:outline-none focus:border-bambu-gray disabled:opacity-50",children:[r.jsx("option",{value:"",children:e.length===0?o("slice.noPresetsForSlot","No presets available"):o("slice.selectPreset","— Select a preset —")}),e.map(l=>r.jsx("option",{value:l,children:l},l))]})]})}function a9e(){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 Am(t,e="bambu_studio"){let n;const a=encodeURIComponent(t);e==="orcaslicer"?n=`orcaslicer://open?file=${a}`:a9e()==="macos"?n=`bambustudioopen://${a}`:n=`bambustudio://open?file=${a}`;const i=document.createElement("a");i.href=n,i.style.display="none",document.body.appendChild(i),i.click(),document.body.removeChild(i)}const Od="/img/bed",i9e={"cool plate":{icon:`${Od}/bed_cool.png`,label:"Cool Plate"},"pc plate":{icon:`${Od}/bed_cool.png`,label:"Cool Plate"},"cool plate (supertack)":{icon:`${Od}/bed_cool_supertack.png`,label:"Cool Plate SuperTack"},"supertack plate":{icon:`${Od}/bed_cool_supertack.png`,label:"Cool Plate SuperTack"},"bambu cool plate supertack":{icon:`${Od}/bed_cool_supertack.png`,label:"Cool Plate SuperTack"},"engineering plate":{icon:`${Od}/bed_engineering.png`,label:"Engineering Plate"},"high temp plate":{icon:`${Od}/bed_high_templ.png`,label:"High Temp Plate"},"textured pei plate":{icon:`${Od}/bed_pei.png`,label:"Textured PEI Plate"},"pei plate":{icon:`${Od}/bed_pei.png`,label:"PEI Plate"},"smooth pei plate":{icon:`${Od}/bed_pei_cool.png`,label:"Smooth PEI Plate"}};function Kie(t){return t?i9e[t.trim().toLowerCase()]??null:null}const XK=768;function Yie(){const[t,e]=v.useState(()=>typeof window<"u"?window.innerWidth{const n=window.matchMedia(`(max-width: ${XK-1}px)`),a=i=>{e(i.matches)};return e(n.matches),n.addEventListener("change",a),()=>n.removeEventListener("change",a)},[]),t}function s9e({onClose:t,initialFiles:e}){const{t:n}=kt(),a=en(),{showToast:i}=rn(),s=v.useRef(null),[o,l]=v.useState(()=>e?.filter(P=>P.name.endsWith(".3mf")).map(P=>({file:P,status:"pending"}))||[]),[c,d]=v.useState(!1),[u,m]=v.useState(null);v.useEffect(()=>{const P=T=>{T.key==="Escape"&&t()};return window.addEventListener("keydown",P),()=>window.removeEventListener("keydown",P)},[t]);const p=it({mutationFn:P=>se.uploadArchivesBulk(P),onSuccess:P=>{m(P),a.invalidateQueries({queryKey:["archives"]}),a.invalidateQueries({queryKey:["archiveStats"]}),l(T=>T.map(A=>{const F=P.results.find(M=>M.filename===A.file.name),S=P.errors.find(M=>M.filename===A.file.name);return F?{...A,status:"success",archiveId:F.id}:S?{...A,status:"error",error:S.error}:A})),P.failed===0?i(`${P.uploaded} file${P.uploaded!==1?"s":""} uploaded`):P.uploaded===0?i(`Failed to upload ${P.failed} file${P.failed!==1?"s":""}`,"error"):i(`${P.uploaded} uploaded, ${P.failed} failed`,"warning")},onError:()=>{l(P=>P.map(T=>({...T,status:"error",error:"Upload failed"}))),i("Upload failed","error")}}),f=v.useCallback(P=>{P.preventDefault(),d(!0)},[]),b=v.useCallback(P=>{P.preventDefault(),d(!1)},[]),w=v.useCallback(P=>{P.preventDefault(),d(!1);const T=Array.from(P.dataTransfer.files).filter(A=>A.name.endsWith(".3mf"));T.length>0&&l(A=>[...A,...T.map(F=>({file:F,status:"pending"}))])},[]),g=v.useCallback(P=>{const T=Array.from(P.target.files||[]).filter(A=>A.name.endsWith(".3mf"));T.length>0&&l(A=>[...A,...T.map(F=>({file:F,status:"pending"}))]),s.current&&(s.current.value="")},[]),x=v.useCallback(P=>{l(T=>T.filter((A,F)=>F!==P))},[]),_=()=>{if(o.length===0)return;const P=o.filter(T=>T.status==="pending");P.length!==0&&(l(T=>T.map(A=>A.status==="pending"?{...A,status:"uploading"}:A)),p.mutate(P.map(T=>T.file)))},N=o.filter(P=>P.status==="pending").length,C=p.isPending;return r.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:r.jsx(Ct,{className:"w-full max-w-2xl max-h-[90vh] flex flex-col",children:r.jsxs(At,{className:"p-0 flex flex-col h-full",children:[r.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[r.jsx("h2",{className:"text-xl font-semibold text-white",children:n("uploadModal.title")}),r.jsx("button",{onClick:t,className:"text-bambu-gray hover:text-white transition-colors",children:r.jsx(Bt,{className:"w-5 h-5"})})]}),r.jsx("div",{className:"p-4",children:r.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:b,onDrop:w,children:[r.jsx(ka,{className:"w-12 h-12 mx-auto mb-4 text-bambu-gray"}),r.jsx("p",{className:"text-white mb-2",children:n("uploadModal.dragDrop")}),r.jsx("p",{className:"text-bambu-gray text-sm mb-4",children:n("uploadModal.or")}),r.jsx(Me,{variant:"secondary",onClick:()=>s.current?.click(),disabled:C,children:n("uploadModal.browseFiles")}),r.jsx("input",{ref:s,type:"file",accept:".3mf",multiple:!0,className:"hidden",onChange:g})]})}),r.jsx("div",{className:"px-4 pb-4",children:r.jsx("p",{className:"text-xs text-bambu-gray",children:n("uploadModal.extractionInfo")})}),o.length>0&&r.jsx("div",{className:"px-4 pb-4 max-h-60 overflow-y-auto",children:r.jsx("div",{className:"space-y-2",children:o.map((P,T)=>r.jsxs("div",{className:"flex items-center gap-3 p-3 bg-bambu-dark rounded-lg",children:[r.jsx(ST,{className:"w-5 h-5 text-bambu-gray flex-shrink-0"}),r.jsx("span",{className:"flex-1 text-white text-sm truncate",children:P.file.name}),r.jsxs("span",{className:"text-xs text-bambu-gray",children:[(P.file.size/(1024*1024)).toFixed(1)," MB"]}),P.status==="pending"&&r.jsx("button",{onClick:()=>x(T),className:"text-bambu-gray hover:text-red-400 transition-colors",disabled:C,children:r.jsx(Bt,{className:"w-4 h-4"})}),P.status==="uploading"&&r.jsx(ut,{className:"w-4 h-4 text-bambu-green animate-spin"}),P.status==="success"&&r.jsx(wr,{className:"w-4 h-4 text-bambu-green"}),P.status==="error"&&r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:"text-xs text-red-400",children:P.error}),r.jsx($a,{className:"w-4 h-4 text-red-400"})]})]},`${P.file.name}-${T}`))})}),u&&r.jsx("div",{className:"px-4 pb-4",children:r.jsx("div",{className:"p-3 bg-bambu-dark rounded-lg",children:r.jsxs("p",{className:"text-sm text-white",children:[r.jsx("span",{className:"text-bambu-green",children:u.uploaded})," ",n("uploadModal.uploaded"),u.failed>0&&r.jsxs(r.Fragment,{children:[", ",r.jsx("span",{className:"text-red-400",children:u.failed})," ",n("uploadModal.failed")]})]})})}),r.jsxs("div",{className:"flex gap-3 p-4 border-t border-bambu-dark-tertiary",children:[r.jsx(Me,{variant:"secondary",onClick:t,className:"flex-1",children:n(u?"common.close":"common.cancel")}),!u&&r.jsx(Me,{onClick:_,disabled:N===0||C,className:"flex-1",children:C?r.jsxs(r.Fragment,{children:[r.jsx(ut,{className:"w-4 h-4 animate-spin"}),n("uploadModal.uploading")]}):r.jsxs(r.Fragment,{children:[r.jsx(ka,{className:"w-4 h-4"}),n("uploadModal.upload")," ",N>0&&`(${N})`]})})]})]})})})}const o9e=365;function l9e({onClose:t,initialDays:e}){const{t:n}=kt(),a=en(),{showToast:i}=rn(),[s,o]=v.useState(e??o9e),[l,c]=v.useState(s);v.useEffect(()=>{const w=window.setTimeout(()=>c(s),300);return()=>window.clearTimeout(w)},[s]);const d=We({queryKey:["archive-purge-preview",l],queryFn:()=>se.previewArchivePurge(l),enabled:l>=1}),u=it({mutationFn:()=>se.executeArchivePurge(s),onSuccess:w=>{i(n("archivePurge.toast.success",{count:w.deleted}),"success"),a.invalidateQueries({queryKey:["archives"]}),a.invalidateQueries({queryKey:["archive-stats"]}),t()},onError:w=>i(w.message||n("archivePurge.toast.failed"),"error")});v.useEffect(()=>{const w=g=>{g.key==="Escape"&&!u.isPending&&t()};return window.addEventListener("keydown",w),()=>window.removeEventListener("keydown",w)},[t,u.isPending]);const m=d.data,p=m?.count??0,f=m?.total_bytes??0,b=p>0&&!u.isPending;return r.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4",children:r.jsxs("div",{className:"bg-white dark:bg-gray-900 rounded-lg shadow-xl max-w-lg w-full",children:[r.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-gray-200 dark:border-gray-700",children:[r.jsxs("h2",{className:"text-lg font-semibold text-gray-900 dark:text-gray-100 flex items-center gap-2",children:[r.jsx(Jt,{className:"w-5 h-5"}),n("archivePurge.title")]}),r.jsx("button",{onClick:t,className:"text-gray-400 hover:text-gray-600 dark:hover:text-gray-200","aria-label":n("common.close"),disabled:u.isPending,children:r.jsx(Bt,{className:"w-5 h-5"})})]}),r.jsxs("div",{className:"p-4 space-y-4",children:[r.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-400",children:n("archivePurge.description")}),r.jsxs("div",{children:[r.jsx("label",{htmlFor:"archive-purge-days",className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1",children:n("archivePurge.ageLabel")}),r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("input",{id:"archive-purge-days",type:"number",min:1,max:3650,value:s,onChange:w=>o(Math.max(1,Math.min(3650,parseInt(w.target.value||"0",10)||0))),className:"w-24 rounded border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-sm px-2 py-1 text-gray-900 dark:text-gray-100"}),r.jsx("span",{className:"text-sm text-gray-600 dark:text-gray-400",children:n("archivePurge.days")})]})]}),r.jsxs("div",{className:"rounded border border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800/30 p-3",children:[r.jsx("div",{className:"text-xs font-semibold uppercase tracking-wide text-gray-600 dark:text-gray-300 mb-2",children:n("archivePurge.effectsTitle")}),r.jsxs("ul",{className:"text-xs text-gray-700 dark:text-gray-300 space-y-1 list-disc pl-4",children:[r.jsx("li",{children:n("archivePurge.effect1")}),r.jsx("li",{children:n("archivePurge.effect2")}),r.jsx("li",{children:n("archivePurge.effect3")}),r.jsx("li",{children:n("archivePurge.effect4")})]})]}),r.jsx("div",{className:"rounded border border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800/50 p-3",children:d.isLoading||d.isFetching?r.jsxs("div",{className:"flex items-center gap-2 text-sm text-gray-500 dark:text-gray-400",children:[r.jsx(ut,{className:"w-4 h-4 animate-spin"})," ",n("archivePurge.previewLoading")]}):d.isError?r.jsx("div",{className:"text-sm text-red-600 dark:text-red-400",children:d.error?.message??n("archivePurge.previewFailed")}):r.jsxs("div",{className:"text-sm text-gray-900 dark:text-gray-100",children:[r.jsx("div",{className:"font-medium",children:n("archivePurge.previewSummary",{count:p,size:cs(f)})}),m?.sample_filenames&&m.sample_filenames.length>0&&r.jsxs("ul",{className:"mt-2 text-xs text-gray-600 dark:text-gray-400 space-y-0.5 list-disc pl-4",children:[m.sample_filenames.map(w=>r.jsx("li",{className:"truncate",children:w},w)),p>m.sample_filenames.length&&r.jsx("li",{className:"list-none italic text-gray-500",children:n("archivePurge.andMore",{count:p-m.sample_filenames.length})})]})]})}),r.jsxs("div",{className:"flex gap-2 items-start text-xs text-amber-700 dark:text-amber-400 bg-amber-50 dark:bg-amber-900/20 rounded px-3 py-2",children:[r.jsx(Nn,{className:"w-4 h-4 mt-0.5 shrink-0"}),r.jsx("span",{children:n("archivePurge.warning")})]})]}),r.jsxs("div",{className:"flex justify-end gap-2 p-4 border-t border-gray-200 dark:border-gray-700",children:[r.jsx(Me,{variant:"secondary",onClick:t,disabled:u.isPending,children:n("common.cancel")}),r.jsx(Me,{variant:"danger",disabled:!b,onClick:()=>u.mutate(),children:u.isPending?r.jsxs(r.Fragment,{children:[r.jsx(ut,{className:"w-4 h-4 animate-spin mr-1"}),n("archivePurge.purging")]}):n("archivePurge.confirmCta",{count:p})})]})]})})}const c9e=["adhesionFailure","spaghettiDetached","layerShift","cloggedNozzle","filamentRunout","warping","stringing","underExtrusion","powerFailure","userCancelled","other"],d9e=["completed","failed","aborted","printing"];function Xie({archive:t,onClose:e,existingTags:n=[]}){const{t:a}=kt();v.useEffect(()=>{const j=B=>{B.key==="Escape"&&e()};return window.addEventListener("keydown",j),()=>window.removeEventListener("keydown",j)},[e]);const i=en(),[s,o]=v.useState(t.print_name||""),[l,c]=v.useState(t.printer_id),[d,u]=v.useState(t.project_id??null),[m,p]=v.useState(t.notes||""),[f,b]=v.useState(t.tags||""),[w,g]=v.useState(t.failure_reason||""),[x,_]=v.useState(t.status),[N,C]=v.useState(t.quantity??1),[P,T]=v.useState(t.photos||[]),[A,F]=v.useState(t.external_url||""),[S,M]=v.useState(!1),[z,I]=v.useState(!1),H=v.useRef(null),L=v.useRef(null),Z=v.useRef(null),{data:re}=We({queryKey:["printers"],queryFn:se.getPrinters}),{data:J}=We({queryKey:["projects"],queryFn:()=>se.getProjects(),select:j=>[...j].sort((B,X)=>B.name.localeCompare(X.name))}),{data:de}=We({queryKey:["tags"],queryFn:se.getTags,enabled:n.length===0}),me=n.length>0?n:de?.map(j=>j.name)||[],ue=f.split(",").map(j=>j.trim()).filter(Boolean),W=f.includes(",")?f.substring(f.lastIndexOf(",")+1).trim().toLowerCase():f.trim().toLowerCase(),ae=me.filter(j=>!ue.includes(j)&&(W===""||j.toLowerCase().includes(W))),pe=j=>{let B;if(W&&!me.includes(W)?B=f.includes(",")?f.substring(0,f.lastIndexOf(",")).split(",").map(X=>X.trim()).filter(Boolean):[]:B=ue,!B.includes(j)){const X=[...B,j].join(", ");b(X)}Z.current!==null&&clearTimeout(Z.current),H.current?.focus()},ye=j=>{const B=ue.filter(X=>X!==j).join(", ");b(B)},Te=it({mutationFn:j=>se.updateArchive(t.id,j),onSuccess:()=>{i.invalidateQueries({queryKey:["archives"]}),i.invalidateQueries({queryKey:["projects"]}),e()}}),$=async j=>{const B=j.target.files?.[0];if(B){M(!0);try{const X=await se.uploadArchivePhoto(t.id,B);T(X.photos),i.invalidateQueries({queryKey:["archives"]})}catch(X){console.error("Failed to upload photo:",X)}finally{M(!1),L.current&&(L.current.value="")}}},K=async j=>{try{const B=await se.deleteArchivePhoto(t.id,j);T(B.photos||[]),i.invalidateQueries({queryKey:["archives"]})}catch(B){console.error("Failed to delete photo:",B)}},D=j=>{j.preventDefault();const B={print_name:s||void 0,printer_id:l,project_id:d,notes:m||void 0,tags:f||void 0,quantity:N,external_url:A||null};x!==t.status&&(B.status=x),x==="failed"||x==="aborted"?B.failure_reason=w||void 0:(t.status==="failed"||t.status==="aborted")&&(B.failure_reason=null),Te.mutate(B)};return r.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:e,children:r.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:[r.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[r.jsx("h2",{className:"text-lg font-semibold text-white",children:a("editArchive.title")}),r.jsx("button",{onClick:e,className:"text-bambu-gray hover:text-white transition-colors",children:r.jsx(Bt,{className:"w-5 h-5"})})]}),r.jsxs("form",{onSubmit:D,className:"p-6 space-y-4 overflow-y-auto flex-1",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("editArchive.name")}),r.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:a("editArchive.namePlaceholder")})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("editArchive.printer")}),r.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:[r.jsx("option",{value:"",children:a("editArchive.noPrinter")}),re?.map(j=>r.jsx("option",{value:j.id,children:j.name},j.id))]})]}),r.jsxs("div",{children:[r.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[r.jsx(ro,{className:"w-4 h-4 inline mr-1"}),a("editArchive.project")]}),r.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:[r.jsx("option",{value:"",children:a("editArchive.noProject")}),J?.map(j=>r.jsx("option",{value:j.id,children:j.name},j.id))]})]}),r.jsxs("div",{children:[r.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[r.jsx(Ebe,{className:"w-4 h-4 inline mr-1"}),a("editArchive.itemsPrinted")]}),r.jsx("input",{type:"number",min:1,value:N,onChange:j=>C(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"}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:a("editArchive.itemsPrintedHelp")})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("editArchive.notes")}),r.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:a("editArchive.notesPlaceholder")})]}),r.jsxs("div",{children:[r.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[r.jsx(Gy,{className:"w-4 h-4 inline mr-1"}),a("editArchive.externalLink")]}),r.jsx("input",{type:"url",value:A,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/..."}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:a("editArchive.externalLinkHelp")})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("editArchive.tags")}),ue.length>0&&r.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:ue.map(j=>r.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 bg-bambu-dark-tertiary rounded text-sm text-white",children:[r.jsx($m,{className:"w-3 h-3"}),j,r.jsx("button",{type:"button",onClick:()=>ye(j),className:"ml-0.5 text-bambu-gray hover:text-white",children:r.jsx(Bt,{className:"w-3 h-3"})})]},j))}),r.jsxs("div",{className:"relative",children:[r.jsx("input",{ref:H,type:"text",value:f,onChange:j=>b(j.target.value),onFocus:()=>{Z.current!==null&&clearTimeout(Z.current),I(!0)},onBlur:()=>{Z.current=window.setTimeout(()=>I(!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:ue.length>0?a("editArchive.addMoreTags"):a("editArchive.tagsPlaceholder")}),z&&ae.length>0&&r.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:[r.jsxs("div",{className:"p-2 text-xs text-bambu-gray border-b border-bambu-dark-tertiary",children:[W?a("editArchive.matchingTags",{query:W}):a("editArchive.existingTags")," ",a("editArchive.clickToAdd")]}),r.jsx("div",{className:"p-2 flex flex-wrap gap-1.5",children:ae.map(j=>r.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))})]})]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("editArchive.status")}),r.jsx("select",{value:x,onChange:j=>{_(j.target.value),j.target.value==="completed"&&g("")},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:d9e.map(j=>r.jsx("option",{value:j,children:a(`editArchive.statuses.${j}`)},j))})]}),(x==="failed"||x==="aborted")&&r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("editArchive.failureReason")}),r.jsxs("select",{value:w,onChange:j=>g(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:[r.jsx("option",{value:"",children:a("editArchive.selectReason")}),c9e.map(j=>r.jsx("option",{value:a(`editArchive.failureReasons.${j}`),children:a(`editArchive.failureReasons.${j}`)},j))]})]}),r.jsxs("div",{children:[r.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[r.jsx(fy,{className:"w-4 h-4 inline mr-1"}),a("editArchive.photos")]}),r.jsxs("div",{className:"flex flex-wrap gap-2 mb-2",children:[P.map(j=>r.jsxs("div",{className:"relative group",children:[r.jsx("img",{src:se.getArchivePhotoUrl(t.id,j),alt:a("editArchive.printResult"),className:"w-20 h-20 object-cover rounded-lg border border-bambu-dark-tertiary"}),r.jsx("button",{type:"button",onClick:()=>K(j),className:"absolute -top-1 -right-1 p-1 bg-red-500 rounded-full opacity-0 group-hover:opacity-100 transition-opacity",children:r.jsx(Jt,{className:"w-3 h-3 text-white"})})]},j)),r.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:[r.jsx("input",{ref:L,type:"file",accept:"image/jpeg,image/png,image/webp",onChange:$,className:"hidden",disabled:S}),S?r.jsx(ut,{className:"w-6 h-6 text-bambu-gray animate-spin"}):r.jsx(ar,{className:"w-6 h-6 text-bambu-gray"})]})]}),r.jsx("p",{className:"text-xs text-bambu-gray",children:a("editArchive.photosHelp")})]}),r.jsxs("div",{className:"flex gap-3 pt-2",children:[r.jsx(Me,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:a("common.cancel")}),r.jsxs(Me,{type:"submit",disabled:Te.isPending,className:"flex-1",children:[r.jsx(us,{className:"w-4 h-4"}),Te.isPending?a("common.saving"):a("common.save")]})]})]})]})})}function u9e({items:t,searchPlaceholder:e,onClose:n,className:a,onMouseEnter:i,onMouseLeave:s}){const[o,l]=v.useState(""),c=v.useRef(null);v.useEffect(()=>{if(e){const m=window.setTimeout(()=>c.current?.focus(),0);return()=>window.clearTimeout(m)}},[e]);const d=o.trim().toLowerCase(),u=e&&d?t.filter(m=>m.label.toLowerCase().includes(d)):t;return r.jsxs("div",{className:a,onMouseEnter:i,onMouseLeave:s,children:[e&&r.jsx("div",{className:"sticky top-0 z-[1] px-2 py-1.5 bg-bambu-dark-secondary border-b border-bambu-dark-tertiary",children:r.jsxs("div",{className:"relative",children:[r.jsx(Sr,{className:"absolute left-2 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-bambu-gray pointer-events-none"}),r.jsx("input",{ref:c,type:"text",value:o,onChange:m=>l(m.target.value),onKeyDown:m=>{if(m.key==="Enter"){const p=u.find(f=>!f.disabled);p&&(p.onClick(),n())}},placeholder:e,className:"w-full pl-7 pr-2 py-1 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]})}),u.map((m,p)=>r.jsxs("button",{onClick:()=>{m.disabled||(m.onClick(),n())},disabled:m.disabled,className:`w-full flex items-center gap-2 px-3 py-2 text-sm text-left transition-colors ${m.disabled?"text-bambu-gray cursor-not-allowed":m.danger?"text-red-400 hover:bg-red-400/10":"text-white hover:bg-bambu-dark-tertiary"}`,children:[m.icon&&r.jsx("span",{className:"w-4 h-4 flex-shrink-0 flex items-center justify-center",children:m.icon}),r.jsx("span",{className:"flex-1 truncate",children:m.label})]},p)),e&&u.length===0&&r.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray text-center italic",children:"—"})]})}function Qie({x:t,y:e,items:n,onClose:a}){const i=v.useRef(null),[s,o]=v.useState(null),l=v.useRef(null),[c,d]=v.useState({x:t,y:e,visible:!1}),[u,m]=v.useState(!1),[p,f]=v.useState({});v.useEffect(()=>{const g=N=>{i.current&&!i.current.contains(N.target)&&a()},x=N=>{N.key==="Escape"&&a()},_=N=>{i.current&&i.current.contains(N.target)||a()};return document.addEventListener("mousedown",g),document.addEventListener("keydown",x),document.addEventListener("scroll",_,!0),()=>{document.removeEventListener("mousedown",g),document.removeEventListener("keydown",x),document.removeEventListener("scroll",_,!0),l.current&&clearTimeout(l.current)}},[a]),v.useLayoutEffect(()=>{if(i.current){i.current.style.visibility="hidden",i.current.style.display="block";const g=i.current.getBoundingClientRect(),x=window.innerWidth,_=window.innerHeight,N=8;let C=t,P=e;t+g.width>x-N&&(C=Math.max(N,x-g.width-N)),C_-N&&(P=Math.max(N,_-g.height-N)),PT),d({x:C,y:P,visible:!0})}},[t,e]);const b=(g,x)=>{l.current&&(clearTimeout(l.current),l.current=null);const _=x.getBoundingClientRect(),N=window.innerHeight,C=300,A=N-_.top-8C;f(F=>({...F,[g]:A?"bottom":"top"})),o(g)},w=()=>{l.current=window.setTimeout(()=>{o(null)},150)};return r.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((g,x)=>{if(g.divider)return r.jsx("div",{className:"my-1 border-t border-bambu-dark-tertiary"},x);const _=g.submenu&&g.submenu.length>0;return r.jsxs("div",{className:"relative",onMouseEnter:N=>_&&b(x,N.currentTarget),onMouseLeave:()=>_&&w(),children:[r.jsxs("button",{onMouseEnter:N=>_&&b(x,N.currentTarget.parentElement),onClick:()=>{_?o(s===x?null:x):g.disabled||(g.onClick(),a())},disabled:g.disabled,title:g.title,className:`w-full flex items-center gap-2 px-3 py-2 text-sm text-left transition-colors ${g.disabled?"text-bambu-gray cursor-not-allowed":g.danger?"text-red-400 hover:bg-red-400/10":"text-white hover:bg-bambu-dark-tertiary"} ${_&&s===x?"bg-bambu-dark-tertiary":""}`,children:[g.icon&&r.jsx("span",{className:"w-4 h-4 flex-shrink-0 flex items-center justify-center",children:g.icon}),r.jsx("span",{className:"flex-1",children:g.label}),_&&r.jsx(Va,{className:"w-4 h-4 text-bambu-gray"})]}),_&&s===x&&r.jsx(u9e,{items:g.submenu,searchPlaceholder:g.submenuSearchPlaceholder,onClose:a,className:`absolute min-w-[200px] 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[x]==="bottom"?"bottom-0":"top-0"}`,onMouseEnter:()=>{l.current&&(clearTimeout(l.current),l.current=null)},onMouseLeave:()=>w()})]},x)})})}function m9e({selectedIds:t,existingTags:e,onClose:n}){const a=en(),{showToast:i}=rn(),[s,o]=v.useState(""),[l,c]=v.useState(new Set),[d,u]=v.useState("add");v.useEffect(()=>{const w=g=>{g.key==="Escape"&&n()};return window.addEventListener("keydown",w),()=>window.removeEventListener("keydown",w)},[n]);const m=it({mutationFn:async()=>{const w=Array.from(l);let g=0;for(const x of t)try{const _=await se.getArchive(x),N=_.tags?_.tags.split(",").map(P=>P.trim()).filter(Boolean):[];let C;d==="add"?C=[...new Set([...N,...w])]:C=N.filter(P=>!l.has(P)),await se.updateArchive(x,{tags:C.join(", ")}),g++}catch(_){throw console.error(`Failed to update archive ${x}:`,_),new Error(`Failed on archive ${x}: ${_ instanceof Error?_.message:"Unknown error"}`)}return{count:g,mode:d,tags:w}},onSuccess:({count:w,mode:g,tags:x})=>{a.invalidateQueries({queryKey:["archives"]}),i(`${g==="add"?"Added":"Removed"} ${x.length} tag${x.length!==1?"s":""} ${g==="add"?"to":"from"} ${w} archive${w!==1?"s":""}`),n()},onError:w=>{i(w.message||"Failed to update tags","error")}}),p=w=>{c(g=>{const x=new Set(g);return x.has(w)?x.delete(w):x.add(w),x})},f=()=>{s.trim()&&!l.has(s.trim())&&(c(w=>new Set([...w,s.trim()])),o(""))},b=w=>{w.key==="Enter"&&(w.preventDefault(),f())};return r.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:r.jsx(Ct,{className:"w-full max-w-md",children:r.jsxs(At,{className:"p-0",children:[r.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx($m,{className:"w-5 h-5 text-bambu-green"}),r.jsx("h2",{className:"text-xl font-semibold text-white",children:d==="add"?"Add Tags":"Remove Tags"})]}),r.jsx("button",{onClick:n,className:"text-bambu-gray hover:text-white transition-colors",children:r.jsx(Bt,{className:"w-5 h-5"})})]}),r.jsxs("div",{className:"p-4 space-y-4",children:[r.jsxs("p",{className:"text-sm text-bambu-gray",children:[d==="add"?"Add":"Remove"," tags for ",t.length," selected archive",t.length!==1?"s":""]}),r.jsxs("div",{className:"flex gap-2",children:[r.jsx(Me,{size:"sm",variant:d==="add"?"primary":"secondary",onClick:()=>u("add"),children:"Add Tags"}),r.jsx(Me,{size:"sm",variant:d==="remove"?"primary":"secondary",onClick:()=>u("remove"),children:"Remove Tags"})]}),d==="add"&&r.jsxs("div",{className:"flex gap-2",children:[r.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:w=>o(w.target.value),onKeyDown:b}),r.jsx(Me,{size:"sm",variant:"secondary",onClick:f,disabled:!s.trim(),children:r.jsx(ar,{className:"w-4 h-4"})})]}),e.length>0&&r.jsxs("div",{children:[r.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:"Existing tags:"}),r.jsx("div",{className:"flex flex-wrap gap-2",children:e.map(w=>r.jsx("button",{onClick:()=>p(w),className:`px-2 py-1 rounded text-sm transition-colors ${l.has(w)?"bg-bambu-green text-white":"bg-bambu-dark-tertiary text-bambu-gray-light hover:bg-bambu-dark"}`,children:w},w))})]}),l.size>0&&r.jsxs("div",{children:[r.jsxs("p",{className:"text-xs text-bambu-gray mb-2",children:["Tags to ",d==="add"?"add":"remove",":"]}),r.jsx("div",{className:"flex flex-wrap gap-2",children:Array.from(l).map(w=>r.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:[w,r.jsx("button",{onClick:()=>p(w),className:"hover:opacity-70",children:r.jsx(Bt,{className:"w-3 h-3"})})]},w))})]})]}),r.jsxs("div",{className:"flex gap-3 p-4 border-t border-bambu-dark-tertiary",children:[r.jsx(Me,{variant:"secondary",onClick:n,className:"flex-1",children:"Cancel"}),r.jsx(Me,{onClick:()=>m.mutate(),disabled:l.size===0||m.isPending,className:"flex-1",children:m.isPending?r.jsxs(r.Fragment,{children:[r.jsx(ut,{className:"w-4 h-4 animate-spin"}),"Processing..."]}):r.jsxs(r.Fragment,{children:[r.jsx($m,{className:"w-4 h-4"}),d==="add"?"Add Tags":"Remove Tags"]})})]})]})})})}function p9e({selectedIds:t,onClose:e}){const{t:n}=kt(),a=en(),{showToast:i}=rn(),[s,o]=v.useState(""),{data:l,isLoading:c}=We({queryKey:["projects"],queryFn:()=>se.getProjects()}),d=v.useMemo(()=>l?[...l].sort((x,_)=>x.name.localeCompare(_.name)):void 0,[l]),u=s.trim().toLowerCase(),m=u?d?.filter(x=>x.name.toLowerCase().includes(u)):d,p=(d?.length??0)>5;v.useEffect(()=>{const x=_=>{_.key==="Escape"&&e()};return window.addEventListener("keydown",x),()=>window.removeEventListener("keydown",x)},[e]);const f=()=>{a.invalidateQueries({queryKey:["archives"]}),a.invalidateQueries({queryKey:["projects"]}),a.invalidateQueries({queryKey:["project"]}),a.invalidateQueries({queryKey:["project-archives"]})},b=it({mutationFn:async x=>(await se.addArchivesToProject(x,t),x),onSuccess:x=>{const _=l?.find(N=>N.id===x);f(),i(`Added ${t.length} archive${t.length!==1?"s":""} to "${_?.name}"`),e()},onError:()=>{i("Failed to assign project","error")}}),w=it({mutationFn:async()=>{for(const x of t)await se.updateArchive(x,{project_id:null});return t.length},onSuccess:x=>{f(),i(`Removed ${x} archive${x!==1?"s":""} from project`),e()},onError:()=>{i("Failed to remove from project","error")}}),g=b.isPending||w.isPending;return r.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:r.jsx(Ct,{className:"w-full max-w-md max-h-[80vh] flex flex-col",children:r.jsxs(At,{className:"p-0 flex flex-col min-h-0",children:[r.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary shrink-0",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(ro,{className:"w-5 h-5 text-bambu-green"}),r.jsx("h2",{className:"text-xl font-semibold text-white",children:"Assign to Project"})]}),r.jsx("button",{onClick:e,className:"text-bambu-gray hover:text-white transition-colors",disabled:g,children:r.jsx(Bt,{className:"w-5 h-5"})})]}),r.jsxs("div",{className:"p-4 space-y-3 overflow-y-auto min-h-0",children:[r.jsxs("p",{className:"text-sm text-bambu-gray",children:["Assign ",t.length," selected archive",t.length!==1?"s":""," to a project"]}),c?r.jsx("div",{className:"flex items-center justify-center py-8",children:r.jsx(ut,{className:"w-6 h-6 animate-spin text-bambu-gray"})}):r.jsxs("div",{className:"space-y-2",children:[r.jsxs("button",{onClick:()=>w.mutate(),disabled:g,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:[r.jsx("div",{className:"w-8 h-8 rounded-full bg-red-500/20 flex items-center justify-center shrink-0",children:r.jsx(Da,{className:"w-4 h-4 text-red-400"})}),r.jsxs("div",{className:"min-w-0 flex-1",children:[r.jsx("p",{className:"text-white font-medium",children:"Remove from project"}),r.jsx("p",{className:"text-sm text-bambu-gray truncate",children:"Clear project assignment"})]}),w.isPending&&r.jsx(ut,{className:"w-4 h-4 animate-spin text-bambu-gray shrink-0"})]}),d&&d.length>0&&r.jsxs("div",{className:"flex items-center gap-2 py-2",children:[r.jsx("div",{className:"flex-1 h-px bg-bambu-dark-tertiary"}),r.jsx("span",{className:"text-xs text-bambu-gray",children:"or assign to"}),r.jsx("div",{className:"flex-1 h-px bg-bambu-dark-tertiary"})]}),p&&r.jsxs("div",{className:"relative",children:[r.jsx(Sr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"}),r.jsx("input",{type:"text",value:s,onChange:x=>o(x.target.value),placeholder:n("archives.menu.searchProjects"),className:"w-full pl-9 pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray text-sm focus:border-bambu-green focus:outline-none"})]}),m?.map(x=>r.jsxs("button",{onClick:()=>b.mutate(x.id),disabled:g,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:[r.jsx("div",{className:"w-8 h-8 rounded-full flex items-center justify-center shrink-0",style:{backgroundColor:x.color?`${x.color}20`:"rgb(var(--bambu-green) / 0.2)"},children:r.jsx(ro,{className:"w-4 h-4",style:{color:x.color||"rgb(var(--bambu-green))"}})}),r.jsxs("div",{className:"min-w-0 flex-1",children:[r.jsx("p",{className:"text-white font-medium truncate",children:x.name}),r.jsxs("p",{className:"text-sm text-bambu-gray truncate",children:[x.archive_count," archive",x.archive_count!==1?"s":"",x.status&&` • ${x.status}`]})]}),b.isPending&&b.variables===x.id&&r.jsx(ut,{className:"w-4 h-4 animate-spin text-bambu-gray shrink-0"})]},x.id)),(!d||d.length===0)&&r.jsx("p",{className:"text-center text-bambu-gray py-4",children:"No projects yet. Create one from the Projects page."}),d&&d.length>0&&m?.length===0&&r.jsx("p",{className:"text-center text-bambu-gray text-sm py-4",children:"—"})]})]}),r.jsx("div",{className:"flex gap-3 p-4 border-t border-bambu-dark-tertiary shrink-0",children:r.jsx(Me,{variant:"secondary",onClick:e,className:"flex-1",disabled:g,children:"Cancel"})})]})})})}function h9e(t,e){return new Date(t,e+1,0).getDate()}function f9e(t,e){return new Date(t,e,1).getDay()}const g9e=["January","February","March","April","May","June","July","August","September","October","November","December"],b9e=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];function x9e({archives:t,onArchiveClick:e,highlightedArchiveId:n}){const a=new Date,[i,s]=v.useState(a.getMonth()),[o,l]=v.useState(a.getFullYear()),[c,d]=v.useState(null),[u,m]=v.useState(null),p=v.useMemo(()=>{const P=new Map;return t.forEach(T=>{const A=Xn(T.completed_at||T.created_at)||new Date,F=`${A.getFullYear()}-${String(A.getMonth()+1).padStart(2,"0")}-${String(A.getDate()).padStart(2,"0")}`,S=P.get(F)||[];S.push(T),P.set(F,S)}),P},[t]),f=h9e(o,i),b=f9e(o,i),w=()=>{i===0?(s(11),l(o-1)):s(i-1)},g=()=>{i===11?(s(0),l(o+1)):s(i+1)},x=()=>{s(a.getMonth()),l(a.getFullYear())},_=[];for(let P=0;P{P!==c&&m(null),d(P)};return r.jsxs("div",{className:"flex flex-col lg:flex-row gap-6",children:[r.jsxs("div",{className:"flex-1",children:[r.jsxs("div",{className:"flex items-center justify-between mb-4",children:[r.jsx("button",{onClick:w,className:"p-2 hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:r.jsx(el,{className:"w-5 h-5 text-bambu-gray"})}),r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsxs("h2",{className:"text-lg font-semibold text-white",children:[g9e[i]," ",o]}),r.jsx("button",{onClick:x,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"})]}),r.jsx("button",{onClick:g,className:"p-2 hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:r.jsx(Va,{className:"w-5 h-5 text-bambu-gray"})})]}),r.jsx("div",{className:"grid grid-cols-7 gap-1 mb-1",children:b9e.map(P=>r.jsx("div",{className:"text-center text-xs text-bambu-gray py-2",children:P},P))}),r.jsx("div",{className:"grid grid-cols-7 gap-1",children:_.map((P,T)=>{if(P===null)return r.jsx("div",{className:"aspect-square"},`empty-${T}`);const A=`${o}-${String(i+1).padStart(2,"0")}-${String(P).padStart(2,"0")}`,F=p.get(A)||[],S=F.length>0,M=P===a.getDate()&&i===a.getMonth()&&o===a.getFullYear(),z=A===c,I=F.filter(L=>L.status==="completed").length,H=F.filter(L=>L.status==="failed").length;return r.jsxs("button",{onClick:()=>C(z?null:A),className:`aspect-square rounded-lg p-1 flex flex-col items-center justify-center transition-colors relative ${z?"bg-bambu-green text-white":M?"bg-bambu-green/20 text-white ring-2 ring-bambu-green":S?"bg-bambu-dark-tertiary hover:bg-bambu-dark-tertiary/70 text-white":"hover:bg-bambu-dark-tertiary/50 text-bambu-gray"}`,children:[r.jsx("span",{className:`text-sm font-medium ${M&&!z?"text-bambu-green":""}`,children:P}),S&&r.jsxs("div",{className:"absolute bottom-1 left-1/2 -translate-x-1/2 flex items-center gap-1",children:[r.jsx("div",{className:`w-2 h-2 rounded-full ${H>0&&I===0?"bg-red-400":H>0?"bg-yellow-400":"bg-green-400"}`}),r.jsx("span",{className:"text-xs font-medium",children:F.length})]})]},P)})}),r.jsx("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:r.jsxs("div",{className:"grid grid-cols-3 gap-4 text-center",children:[r.jsxs("div",{children:[r.jsx("div",{className:"text-2xl font-bold text-white",children:t.filter(P=>{const T=Xn(P.completed_at||P.created_at)||new Date;return T.getMonth()===i&&T.getFullYear()===o}).length}),r.jsx("div",{className:"text-xs text-bambu-gray",children:"Prints this month"})]}),r.jsxs("div",{children:[r.jsx("div",{className:"text-2xl font-bold text-green-400",children:t.filter(P=>{const T=Xn(P.completed_at||P.created_at)||new Date;return T.getMonth()===i&&T.getFullYear()===o&&P.status==="completed"}).length}),r.jsx("div",{className:"text-xs text-bambu-gray",children:"Successful"})]}),r.jsxs("div",{children:[r.jsx("div",{className:"text-2xl font-bold text-red-400",children:t.filter(P=>{const T=Xn(P.completed_at||P.created_at)||new Date;return T.getMonth()===i&&T.getFullYear()===o&&P.status==="failed"}).length}),r.jsx("div",{className:"text-xs text-bambu-gray",children:"Failed"})]})]})})]}),r.jsx("div",{className:"lg:w-80 bg-bambu-dark rounded-xl p-4",children:c?r.jsxs(r.Fragment,{children:[r.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"})}),N.length>0?r.jsx("div",{className:"calendar-scroll space-y-2 max-h-96 overflow-y-auto",children:N.map(P=>{const T=P.id===u||P.id===n;return r.jsxs("button",{onClick:()=>{m(P.id),e?.(P)},className:`w-full flex items-center gap-3 p-2 rounded-lg transition-colors text-left ${T?"":"hover:bg-bambu-dark-tertiary"}`,style:T?{outline:"4px solid #facc15",outlineOffset:"2px"}:void 0,children:[P.thumbnail_path?r.jsx("img",{src:se.getArchiveThumbnail(P.id),alt:"",className:"w-12 h-12 rounded object-cover"}):r.jsx("div",{className:"w-12 h-12 rounded bg-bambu-dark-tertiary flex items-center justify-center",children:r.jsx("span",{className:"text-xs text-bambu-gray",children:"3MF"})}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsx("p",{className:"text-sm text-white truncate",children:P.print_name||P.filename}),r.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[r.jsx("span",{className:P.status==="failed"?"text-red-400":"text-green-400",children:P.status==="failed"?"Failed":"Completed"}),P.filament_color&&r.jsx("div",{className:"flex gap-0.5",children:P.filament_color.split(",").map((A,F)=>r.jsx("div",{className:"w-3 h-3 rounded-full border border-black/20",style:{backgroundColor:A}},F))})]})]})]},P.id)})}):r.jsx("p",{className:"text-sm text-bambu-gray",children:"No prints on this day"})]}):r.jsx("div",{className:"text-center py-8",children:r.jsx("p",{className:"text-sm text-bambu-gray",children:"Select a day to see prints"})})})]})}function Zie({archiveId:t,archiveName:e,onClose:n}){const a=se.getArchiveQRCodeUrl(t,300);v.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=a,s.download=`${e}_qrcode.png`,s.click()};return r.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:n,children:r.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary w-full max-w-sm",onClick:s=>s.stopPropagation(),children:[r.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[r.jsx("h2",{className:"text-lg font-semibold text-white",children:"QR Code"}),r.jsx("button",{onClick:n,className:"text-bambu-gray hover:text-white transition-colors",children:r.jsx(Bt,{className:"w-5 h-5"})})]}),r.jsxs("div",{className:"p-6 flex flex-col items-center",children:[r.jsx("p",{className:"text-sm text-bambu-gray mb-4 text-center truncate max-w-full",children:e}),r.jsx("div",{className:"bg-white p-4 rounded-lg mb-4",children:r.jsx("img",{src:a,alt:"QR Code",className:"w-64 h-64"})}),r.jsx("p",{className:"text-xs text-bambu-gray mb-4 text-center",children:"Scan to open this archive"}),r.jsxs(Me,{onClick:i,className:"w-full",children:[r.jsx(Yr,{className:"w-4 h-4"}),"Download QR Code"]})]})]})})}function Jie({archiveId:t,archiveName:e,photos:n,onClose:a,onDelete:i}){const[s,o]=v.useState(0),[l,c]=v.useState(!1);if(v.useEffect(()=>{const f=b=>{b.key==="Escape"&&a(),b.key==="ArrowLeft"&&o(w=>Math.max(0,w-1)),b.key==="ArrowRight"&&o(w=>Math.min(n.length-1,w+1))};return window.addEventListener("keydown",f),()=>window.removeEventListener("keydown",f)},[a,n.length]),v.useEffect(()=>{s>=n.length&&o(Math.max(0,n.length-1))},[n.length,s]),n.length===0)return a(),null;const d=n[s],u=se.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 r.jsxs("div",{className:"fixed inset-0 bg-black/90 flex items-center justify-center z-50",onClick:a,children:[r.jsxs("div",{className:"relative w-full h-full flex flex-col",onClick:f=>f.stopPropagation(),children:[r.jsxs("div",{className:"flex items-center justify-between px-6 py-4 bg-black/50",children:[r.jsxs("div",{children:[r.jsx("h2",{className:"text-lg font-semibold text-white",children:e}),r.jsxs("p",{className:"text-sm text-bambu-gray",children:["Photo ",s+1," of ",n.length]})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs(Me,{variant:"secondary",size:"sm",onClick:m,children:[r.jsx(Yr,{className:"w-4 h-4"}),"Download"]}),i&&r.jsx(Me,{variant:"secondary",size:"sm",onClick:p,className:"text-red-400 hover:text-red-300",children:r.jsx(Jt,{className:"w-4 h-4"})}),r.jsx("button",{onClick:a,className:"p-2 text-bambu-gray hover:text-white transition-colors",children:r.jsx(Bt,{className:"w-6 h-6"})})]})]}),r.jsxs("div",{className:"flex-1 min-h-0 flex items-center justify-center p-4 relative overflow-hidden",children:[s>0&&r.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:r.jsx(el,{className:"w-8 h-8 text-white"})}),r.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:r.jsx(Va,{className:"w-8 h-8 text-white"})})]}),n.length>1&&r.jsx("div",{className:"flex justify-center gap-2 p-4 bg-black/50",children:n.map((f,b)=>r.jsx("button",{onClick:()=>o(b),className:`w-16 h-16 rounded-lg overflow-hidden border-2 transition-colors ${b===s?"border-bambu-green":"border-transparent hover:border-bambu-gray"}`,children:r.jsx("img",{src:se.getArchivePhotoUrl(t,f),alt:`Thumbnail ${b+1}`,className:"w-full h-full object-cover"})},f))})]}),l&&r.jsx(vn,{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:ese,setPrototypeOf:QK,isFrozen:y9e,getPrototypeOf:v9e,getOwnPropertyDescriptor:w9e}=Object;let{freeze:To,seal:Mc,create:I0}=Object,{apply:sI,construct:oI}=typeof Reflect<"u"&&Reflect;To||(To=function(e){return e});Mc||(Mc=function(e){return e});sI||(sI=function(e,n){for(var a=arguments.length,i=new Array(a>2?a-2:0),s=2;s1?n-1:0),i=1;i1?n-1:0),i=1;i2&&arguments[2]!==void 0?arguments[2]:EN;QK&&QK(t,null);let a=e.length;for(;a--;){let i=e[a];if(typeof i=="string"){const s=n(i);s!==i&&(y9e(e)||(e[a]=s),i=s)}t[i]=!0}return t}function P9e(t){for(let e=0;e/gm),E9e=Mc(/\$\{[\w\W]*/gm),D9e=Mc(/^data-[\-\w.\u00B7-\uFFFF]+$/),F9e=Mc(/^aria-[\-\w]+$/),tse=Mc(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),R9e=Mc(/^(?:\w+script|data):/i),L9e=Mc(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),nse=Mc(/^html$/i),I9e=Mc(/^[a-z][.\w]*(-[.\w]+)+$/i);var rY=Object.freeze({__proto__:null,ARIA_ATTR:F9e,ATTR_WHITESPACE:L9e,CUSTOM_ELEMENT:I9e,DATA_ATTR:D9e,DOCTYPE_NAME:nse,ERB_EXPR:M9e,IS_ALLOWED_URI:tse,IS_SCRIPT_OR_DATA:R9e,MUSTACHE_EXPR:j9e,TMPLIT_EXPR:E9e});const k0={element:1,text:3,progressingInstruction:7,comment:8,document:9},O9e=function(){return typeof window>"u"?null:window},z9e=function(e,n){if(typeof e!="object"||typeof e.createPolicy!="function")return null;let a=null;const i="data-tt-policy-suffix";n&&n.hasAttribute(i)&&(a=n.getAttribute(i));const s="dompurify"+(a?"#"+a:"");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}},aY=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function rse(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:O9e();const e=Je=>rse(Je);if(e.version="3.4.0",e.removed=[],!t||!t.document||t.document.nodeType!==k0.document||!t.Element)return e.isSupported=!1,e;let{document:n}=t;const a=n,i=a.currentScript,{DocumentFragment:s,HTMLTemplateElement:o,Node:l,Element:c,NodeFilter:d,NamedNodeMap:u=t.NamedNodeMap||t.MozNamedAttrMap,HTMLFormElement:m,DOMParser:p,trustedTypes:f}=t,b=c.prototype,w=_0(b,"cloneNode"),g=_0(b,"remove"),x=_0(b,"nextSibling"),_=_0(b,"childNodes"),N=_0(b,"parentNode");if(typeof o=="function"){const Je=n.createElement("template");Je.content&&Je.content.ownerDocument&&(n=Je.content.ownerDocument)}let C,P="";const{implementation:T,createNodeIterator:A,createDocumentFragment:F,getElementsByTagName:S}=n,{importNode:M}=a;let z=aY();e.isSupported=typeof ese=="function"&&typeof N=="function"&&T&&T.createHTMLDocument!==void 0;const{MUSTACHE_EXPR:I,ERB_EXPR:H,TMPLIT_EXPR:L,DATA_ATTR:Z,ARIA_ATTR:re,IS_SCRIPT_OR_DATA:J,ATTR_WHITESPACE:de,CUSTOM_ELEMENT:me}=rY;let{IS_ALLOWED_URI:ue}=rY,W=null;const ae=ur({},[...JK,...w3,...S3,..._3,...eY]);let pe=null;const ye=ur({},[...tY,...k3,...nY,...$1]);let Te=Object.seal(I0(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,K=null;const D=Object.seal(I0(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let j=!0,B=!0,X=!1,O=!0,ie=!1,U=!0,G=!1,Y=!1,Q=!1,oe=!1,ee=!1,ge=!1,ce=!0,le=!1;const q="user-content-";let R=!0,ne=!1,xe={},we=null;const Ne=ur({},["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 ve=null;const be=ur({},["audio","video","img","source","image","track"]);let Ee=null;const ze=ur({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),_e="http://www.w3.org/1998/Math/MathML",Oe="http://www.w3.org/2000/svg",Ie="http://www.w3.org/1999/xhtml";let Ke=Ie,rt=!1,st=null;const Re=ur({},[_e,Oe,Ie],y3);let tt=ur({},["mi","mo","mn","ms","mtext"]),Ce=ur({},["annotation-xml"]);const Xe=ur({},["title","style","font","a","script"]);let Ue=null;const fe=["application/xhtml+xml","text/html"],Ae="text/html";let $e=null,Be=null;const nt=n.createElement("form"),gt=function(Le){return Le instanceof RegExp||Le instanceof Function},yt=function(){let Le=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(Be&&Be===Le)){if((!Le||typeof Le!="object")&&(Le={}),Le=Ud(Le),Ue=fe.indexOf(Le.PARSER_MEDIA_TYPE)===-1?Ae:Le.PARSER_MEDIA_TYPE,$e=Ue==="application/xhtml+xml"?y3:EN,W=Xc(Le,"ALLOWED_TAGS")?ur({},Le.ALLOWED_TAGS,$e):ae,pe=Xc(Le,"ALLOWED_ATTR")?ur({},Le.ALLOWED_ATTR,$e):ye,st=Xc(Le,"ALLOWED_NAMESPACES")?ur({},Le.ALLOWED_NAMESPACES,y3):Re,Ee=Xc(Le,"ADD_URI_SAFE_ATTR")?ur(Ud(ze),Le.ADD_URI_SAFE_ATTR,$e):ze,ve=Xc(Le,"ADD_DATA_URI_TAGS")?ur(Ud(be),Le.ADD_DATA_URI_TAGS,$e):be,we=Xc(Le,"FORBID_CONTENTS")?ur({},Le.FORBID_CONTENTS,$e):Ne,$=Xc(Le,"FORBID_TAGS")?ur({},Le.FORBID_TAGS,$e):Ud({}),K=Xc(Le,"FORBID_ATTR")?ur({},Le.FORBID_ATTR,$e):Ud({}),xe=Xc(Le,"USE_PROFILES")?Le.USE_PROFILES:!1,j=Le.ALLOW_ARIA_ATTR!==!1,B=Le.ALLOW_DATA_ATTR!==!1,X=Le.ALLOW_UNKNOWN_PROTOCOLS||!1,O=Le.ALLOW_SELF_CLOSE_IN_ATTR!==!1,ie=Le.SAFE_FOR_TEMPLATES||!1,U=Le.SAFE_FOR_XML!==!1,G=Le.WHOLE_DOCUMENT||!1,oe=Le.RETURN_DOM||!1,ee=Le.RETURN_DOM_FRAGMENT||!1,ge=Le.RETURN_TRUSTED_TYPE||!1,Q=Le.FORCE_BODY||!1,ce=Le.SANITIZE_DOM!==!1,le=Le.SANITIZE_NAMED_PROPS||!1,R=Le.KEEP_CONTENT!==!1,ne=Le.IN_PLACE||!1,ue=Le.ALLOWED_URI_REGEXP||tse,Ke=Le.NAMESPACE||Ie,tt=Le.MATHML_TEXT_INTEGRATION_POINTS||tt,Ce=Le.HTML_INTEGRATION_POINTS||Ce,Te=Le.CUSTOM_ELEMENT_HANDLING||I0(null),Le.CUSTOM_ELEMENT_HANDLING&>(Le.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(Te.tagNameCheck=Le.CUSTOM_ELEMENT_HANDLING.tagNameCheck),Le.CUSTOM_ELEMENT_HANDLING&>(Le.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(Te.attributeNameCheck=Le.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),Le.CUSTOM_ELEMENT_HANDLING&&typeof Le.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&(Te.allowCustomizedBuiltInElements=Le.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),ie&&(B=!1),ee&&(oe=!0),xe&&(W=ur({},eY),pe=I0(null),xe.html===!0&&(ur(W,JK),ur(pe,tY)),xe.svg===!0&&(ur(W,w3),ur(pe,k3),ur(pe,$1)),xe.svgFilters===!0&&(ur(W,S3),ur(pe,k3),ur(pe,$1)),xe.mathMl===!0&&(ur(W,_3),ur(pe,nY),ur(pe,$1))),D.tagCheck=null,D.attributeCheck=null,Le.ADD_TAGS&&(typeof Le.ADD_TAGS=="function"?D.tagCheck=Le.ADD_TAGS:(W===ae&&(W=Ud(W)),ur(W,Le.ADD_TAGS,$e))),Le.ADD_ATTR&&(typeof Le.ADD_ATTR=="function"?D.attributeCheck=Le.ADD_ATTR:(pe===ye&&(pe=Ud(pe)),ur(pe,Le.ADD_ATTR,$e))),Le.ADD_URI_SAFE_ATTR&&ur(Ee,Le.ADD_URI_SAFE_ATTR,$e),Le.FORBID_CONTENTS&&(we===Ne&&(we=Ud(we)),ur(we,Le.FORBID_CONTENTS,$e)),Le.ADD_FORBID_CONTENTS&&(we===Ne&&(we=Ud(we)),ur(we,Le.ADD_FORBID_CONTENTS,$e)),R&&(W["#text"]=!0),G&&ur(W,["html","head","body"]),W.table&&(ur(W,["tbody"]),delete $.tbody),Le.TRUSTED_TYPES_POLICY){if(typeof Le.TRUSTED_TYPES_POLICY.createHTML!="function")throw S0('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof Le.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw S0('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');C=Le.TRUSTED_TYPES_POLICY,P=C.createHTML("")}else C===void 0&&(C=z9e(f,i)),C!==null&&typeof P=="string"&&(P=C.createHTML(""));To&&To(Le),Be=Le}},ot=ur({},[...w3,...S3,...T9e]),Ht=ur({},[..._3,...A9e]),Kt=function(Le){let dt=N(Le);(!dt||!dt.tagName)&&(dt={namespaceURI:Ke,tagName:"template"});const he=EN(Le.tagName),Fe=EN(dt.tagName);return st[Le.namespaceURI]?Le.namespaceURI===Oe?dt.namespaceURI===Ie?he==="svg":dt.namespaceURI===_e?he==="svg"&&(Fe==="annotation-xml"||tt[Fe]):!!ot[he]:Le.namespaceURI===_e?dt.namespaceURI===Ie?he==="math":dt.namespaceURI===Oe?he==="math"&&Ce[Fe]:!!Ht[he]:Le.namespaceURI===Ie?dt.namespaceURI===Oe&&!Ce[Fe]||dt.namespaceURI===_e&&!tt[Fe]?!1:!Ht[he]&&(Xe[he]||!ot[he]):!!(Ue==="application/xhtml+xml"&&st[Le.namespaceURI]):!1},Zt=function(Le){w0(e.removed,{element:Le});try{N(Le).removeChild(Le)}catch{g(Le)}},Yt=function(Le,dt){try{w0(e.removed,{attribute:dt.getAttributeNode(Le),from:dt})}catch{w0(e.removed,{attribute:null,from:dt})}if(dt.removeAttribute(Le),Le==="is")if(oe||ee)try{Zt(dt)}catch{}else try{dt.setAttribute(Le,"")}catch{}},gn=function(Le){let dt=null,he=null;if(Q)Le=""+Le;else{const Ze=v3(Le,/^[\r\n\t ]+/);he=Ze&&Ze[0]}Ue==="application/xhtml+xml"&&Ke===Ie&&(Le=''+Le+"");const Fe=C?C.createHTML(Le):Le;if(Ke===Ie)try{dt=new p().parseFromString(Fe,Ue)}catch{}if(!dt||!dt.documentElement){dt=T.createDocument(Ke,"template",null);try{dt.documentElement.innerHTML=rt?P:Fe}catch{}}const Qe=dt.body||dt.documentElement;return Le&&he&&Qe.insertBefore(n.createTextNode(he),Qe.childNodes[0]||null),Ke===Ie?S.call(dt,G?"html":"body")[0]:G?dt.documentElement:Qe},ln=function(Le){return A.call(Le.ownerDocument||Le,Le,d.SHOW_ELEMENT|d.SHOW_COMMENT|d.SHOW_TEXT|d.SHOW_PROCESSING_INSTRUCTION|d.SHOW_CDATA_SECTION,null)},pt=function(Le){return Le instanceof m&&(typeof Le.nodeName!="string"||typeof Le.textContent!="string"||typeof Le.removeChild!="function"||!(Le.attributes instanceof u)||typeof Le.removeAttribute!="function"||typeof Le.setAttribute!="function"||typeof Le.namespaceURI!="string"||typeof Le.insertBefore!="function"||typeof Le.hasChildNodes!="function")},at=function(Le){return typeof l=="function"&&Le instanceof l};function vt(Je,Le,dt){v0(Je,he=>{he.call(e,Le,dt,Be)})}const _t=function(Le){let dt=null;if(vt(z.beforeSanitizeElements,Le,null),pt(Le))return Zt(Le),!0;const he=$e(Le.nodeName);if(vt(z.uponSanitizeElement,Le,{tagName:he,allowedTags:W}),U&&Le.hasChildNodes()&&!at(Le.firstElementChild)&&go(/<[/\w!]/g,Le.innerHTML)&&go(/<[/\w!]/g,Le.textContent)||U&&Le.namespaceURI===Ie&&he==="style"&&at(Le.firstElementChild)||Le.nodeType===k0.progressingInstruction||U&&Le.nodeType===k0.comment&&go(/<[/\w]/g,Le.data))return Zt(Le),!0;if($[he]||!(D.tagCheck instanceof Function&&D.tagCheck(he))&&!W[he]){if(!$[he]&&De(he)&&(Te.tagNameCheck instanceof RegExp&&go(Te.tagNameCheck,he)||Te.tagNameCheck instanceof Function&&Te.tagNameCheck(he)))return!1;if(R&&!we[he]){const Fe=N(Le)||Le.parentNode,Qe=_(Le)||Le.childNodes;if(Qe&&Fe){const Ze=Qe.length;for(let Ye=Ze-1;Ye>=0;--Ye){const ft=w(Qe[Ye],!0);ft.__removalCount=(Le.__removalCount||0)+1,Fe.insertBefore(ft,x(Le))}}}return Zt(Le),!0}return Le instanceof c&&!Kt(Le)||(he==="noscript"||he==="noembed"||he==="noframes")&&go(/<\/no(script|embed|frames)/i,Le.innerHTML)?(Zt(Le),!0):(ie&&Le.nodeType===k0.text&&(dt=Le.textContent,v0([I,H,L],Fe=>{dt=Ex(dt,Fe," ")}),Le.textContent!==dt&&(w0(e.removed,{element:Le.cloneNode()}),Le.textContent=dt)),vt(z.afterSanitizeElements,Le,null),!1)},Dt=function(Le,dt,he){if(K[dt]||ce&&(dt==="id"||dt==="name")&&(he in n||he in nt))return!1;if(!(B&&!K[dt]&&go(Z,dt))){if(!(j&&go(re,dt))){if(!(D.attributeCheck instanceof Function&&D.attributeCheck(dt,Le))){if(!pe[dt]||K[dt]){if(!(De(Le)&&(Te.tagNameCheck instanceof RegExp&&go(Te.tagNameCheck,Le)||Te.tagNameCheck instanceof Function&&Te.tagNameCheck(Le))&&(Te.attributeNameCheck instanceof RegExp&&go(Te.attributeNameCheck,dt)||Te.attributeNameCheck instanceof Function&&Te.attributeNameCheck(dt,Le))||dt==="is"&&Te.allowCustomizedBuiltInElements&&(Te.tagNameCheck instanceof RegExp&&go(Te.tagNameCheck,he)||Te.tagNameCheck instanceof Function&&Te.tagNameCheck(he))))return!1}else if(!Ee[dt]){if(!go(ue,Ex(he,de,""))){if(!((dt==="src"||dt==="xlink:href"||dt==="href")&&Le!=="script"&&k9e(he,"data:")===0&&ve[Le])){if(!(X&&!go(J,Ex(he,de,"")))){if(he)return!1}}}}}}}return!0},De=function(Le){return Le!=="annotation-xml"&&v3(Le,me)},je=function(Le){vt(z.beforeSanitizeAttributes,Le,null);const{attributes:dt}=Le;if(!dt||pt(Le))return;const he={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:pe,forceKeepAttr:void 0};let Fe=dt.length;for(;Fe--;){const Qe=dt[Fe],{name:Ze,namespaceURI:Ye,value:ft}=Qe,et=$e(Ze),jt=ft;let St=Ze==="value"?jt:N9e(jt);if(he.attrName=et,he.attrValue=St,he.keepAttr=!0,he.forceKeepAttr=void 0,vt(z.uponSanitizeAttribute,Le,he),St=he.attrValue,le&&(et==="id"||et==="name")&&(Yt(Ze,Le),St=q+St),U&&go(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,St)){Yt(Ze,Le);continue}if(et==="attributename"&&v3(St,"href")){Yt(Ze,Le);continue}if(he.forceKeepAttr)continue;if(!he.keepAttr){Yt(Ze,Le);continue}if(!O&&go(/\/>/i,St)){Yt(Ze,Le);continue}ie&&v0([I,H,L],Ot=>{St=Ex(St,Ot," ")});const Lt=$e(Le.nodeName);if(!Dt(Lt,et,St)){Yt(Ze,Le);continue}if(C&&typeof f=="object"&&typeof f.getAttributeType=="function"&&!Ye)switch(f.getAttributeType(Lt,et)){case"TrustedHTML":{St=C.createHTML(St);break}case"TrustedScriptURL":{St=C.createScriptURL(St);break}}if(St!==jt)try{Ye?Le.setAttributeNS(Ye,Ze,St):Le.setAttribute(Ze,St),pt(Le)?Zt(Le):ZK(e.removed)}catch{Yt(Ze,Le)}}vt(z.afterSanitizeAttributes,Le,null)},Ve=function(Le){let dt=null;const he=ln(Le);for(vt(z.beforeSanitizeShadowDOM,Le,null);dt=he.nextNode();)vt(z.uponSanitizeShadowNode,dt,null),_t(dt),je(dt),dt.content instanceof s&&Ve(dt.content);vt(z.afterSanitizeShadowDOM,Le,null)};return e.sanitize=function(Je){let Le=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},dt=null,he=null,Fe=null,Qe=null;if(rt=!Je,rt&&(Je=""),typeof Je!="string"&&!at(Je))if(typeof Je.toString=="function"){if(Je=Je.toString(),typeof Je!="string")throw S0("dirty is not a string, aborting")}else throw S0("toString is not a function");if(!e.isSupported)return Je;if(Y||yt(Le),e.removed=[],typeof Je=="string"&&(ne=!1),ne){if(Je.nodeName){const ft=$e(Je.nodeName);if(!W[ft]||$[ft])throw S0("root node is forbidden and cannot be sanitized in-place")}}else if(Je instanceof l)dt=gn(""),he=dt.ownerDocument.importNode(Je,!0),he.nodeType===k0.element&&he.nodeName==="BODY"||he.nodeName==="HTML"?dt=he:dt.appendChild(he);else{if(!oe&&!ie&&!G&&Je.indexOf("<")===-1)return C&&ge?C.createHTML(Je):Je;if(dt=gn(Je),!dt)return oe?null:ge?P:""}dt&&Q&&Zt(dt.firstChild);const Ze=ln(ne?Je:dt);for(;Fe=Ze.nextNode();)_t(Fe),je(Fe),Fe.content instanceof s&&Ve(Fe.content);if(ne)return Je;if(oe){if(ie){dt.normalize();let ft=dt.innerHTML;v0([I,H,L],et=>{ft=Ex(ft,et," ")}),dt.innerHTML=ft}if(ee)for(Qe=F.call(dt.ownerDocument);dt.firstChild;)Qe.appendChild(dt.firstChild);else Qe=dt;return(pe.shadowroot||pe.shadowrootmode)&&(Qe=M.call(a,Qe,!0)),Qe}let Ye=G?dt.outerHTML:dt.innerHTML;return G&&W["!doctype"]&&dt.ownerDocument&&dt.ownerDocument.doctype&&dt.ownerDocument.doctype.name&&go(nse,dt.ownerDocument.doctype.name)&&(Ye=" + `,title:H("printers:control")?S($t?"printers.resume":"printers.pause"):S("printers.permission.noControl"),children:[$t?r.jsx(fs,{className:"w-3 h-3"}):r.jsx(AS,{className:"w-3 h-3"}),S($t?"printers.resume":"printers.pause")]})]})]})]})})(),(bd?.length>0||qe.vt_tray.length>0)&&a==="expanded"&&(()=>{const lt=bd.filter(ht=>ht.tray.length>1),$t=bd.filter(ht=>ht.tray.length===1),an=t.nozzle_count===2||qe?.temperatures?.nozzle_2!==void 0;return r.jsxs("div",{className:"mt-3",children:[r.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[r.jsx("span",{className:"text-[10px] uppercase tracking-wider text-bambu-gray font-medium",children:S("printers.filaments")}),r.jsx("div",{className:"flex-1 h-px bg-bambu-dark-tertiary/30"})]}),r.jsxs("div",{className:"space-y-3",children:[lt.length>0&&r.jsx("div",{className:"grid grid-cols-2 gap-3",children:lt.map(ht=>{const Un=Ki[String(ht.id)],kr=ht.id>=128?ht.id-128:ht.id,Hn=Un!==void 0?Un:kr,ya=Hn===1,va=Hn===0;return r.jsxs("div",{className:"p-2.5 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary/30",children:[r.jsxs("div",{className:"flex items-center justify-between mb-2",children:[r.jsxs("div",{className:"flex items-center gap-1.5",children:[r.jsx(WK,{ams:ht,printerId:t.id,label:$o(ht.id,ht.tray.length),amsLabels:Er,canEdit:H("printers:update"),onSaved:zn,children:r.jsx("span",{className:"text-[10px] text-white font-medium cursor-default select-none",children:Er?.[ht.id]||$o(ht.id,ht.tray.length)})}),an&&(ya||va)&&r.jsx(BK,{side:ya?"L":"R"})]}),(ht.humidity!=null||ht.temp!=null)&&r.jsxs("div",{className:"flex items-center gap-1.5 max-[550px]:flex-col max-[550px]:items-start",children:[ht.humidity!=null&&r.jsx(qK,{humidity:ht.humidity,goodThreshold:s?.humidityGood,fairThreshold:s?.humidityFair,onClick:()=>at({amsId:ht.id,amsLabel:$o(ht.id,ht.tray.length),mode:"humidity"}),compact:!0}),ht.temp!=null&&r.jsx($K,{temp:ht.temp,goodThreshold:s?.tempGood,fairThreshold:s?.tempFair,onClick:()=>at({amsId:ht.id,amsLabel:$o(ht.id,ht.tray.length),mode:"temperature"}),compact:!0}),qe.supports_drying&&(ht.module_type==="n3f"||ht.module_type==="n3s")&&H("printers:control")&&r.jsx("button",{disabled:!!(ht.dry_sf_reason?.length&&ht.dry_time===0),onClick:tn=>{if(ht.dry_time>0)Qr.mutate(ht.id);else if(Re===ht.id)tt(null);else{const Ca=(ht.tray.find(ul=>ul.tray_type)?.tray_type||"PLA").split(" ")[0].toUpperCase(),Qa=C[Ca]||C.PLA,Zi=ht.module_type;fe(Ca),$e(Qa[Zi]||Qa.n3f),nt(Zi==="n3s"?Qa.n3s_hours:Qa.n3f_hours),yt(!1),Xe(ht.module_type),tt(ht.id);const Bl=tn.currentTarget.getBoundingClientRect();Ht({top:Bl.bottom+4,left:Math.max(8,Bl.right-240)})}},className:`flex items-center gap-0.5 px-1 py-0.5 rounded text-[9px] transition-colors ${ht.dry_time>0?"bg-amber-500/20 text-amber-400":ht.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:ht.dry_time>0?S("printers.drying.stop"):ht.dry_sf_reason?.length?S("printers.drying.powerRequired"):S("printers.drying.start"),children:r.jsx(mm,{className:"w-3 h-3"})})]})]}),ht.dry_time>0&&r.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:[r.jsx(mm,{className:"w-3 h-3 text-amber-400 shrink-0"}),r.jsx("span",{className:"text-amber-400 font-medium",children:S("printers.drying.active")}),r.jsx("span",{className:"text-amber-300/70",children:S("printers.drying.timeRemaining",{time:ht.dry_time>=60?`${Math.floor(ht.dry_time/60)}h ${ht.dry_time%60}m`:`${ht.dry_time}m`})}),r.jsx("button",{onClick:()=>Qr.mutate(ht.id),disabled:Qr.isPending,className:"ml-auto text-amber-400 hover:text-amber-300 transition-colors disabled:opacity-50",title:S("printers.drying.stop"),children:r.jsx(Bt,{className:"w-3 h-3"})})]}),r.jsx("div",{className:"grid grid-cols-4 gap-1.5",children:[0,1,2,3].map(tn=>{const Tn=ht.tray[tn]||ht.tray.find(sn=>sn.id===tn),Ca=Tn?.tray_type&&Tn.remain>=0,Qa=!Tn?.tray_type,Zi=ht.id*4+tn,Bl=Ft===Zi,ul=Tn?.tray_info_idx?wn?.[Tn.tray_info_idx]:null,wa=bn?.[Zi],Ss=(Tn?.tray_uuid||Tn?.tag_uid||fm(t.serial_number,ht.id,tn))?.toUpperCase(),gi=Ss?l?.[Ss]:void 0,Cd=MN(gi),_s=o&&!b?f?.find(sn=>sn.printer_id===t.id&&sn.ams_id===ht.id&&sn.tray_id===tn):void 0,qr=_s?p?.find(sn=>sn.id===_s.spoolman_spool_id):void 0,Ha=qr&&(qr.label_weight??0)>0?Math.round(Math.max(0,(qr.label_weight??0)-qr.weight_used)/(qr.label_weight??1)*100):null,Ji=u?.(t.id,ht.id,tn),Fi=(()=>{const sn=Ji?.spool;return sn&&sn.label_weight>0&&sn.weight_used!=null?Math.round(Math.max(0,sn.label_weight-sn.weight_used)/sn.label_weight*100):null})(),zc=Fi===0&&Ca&&Tn.remain>0?null:Fi,ks=Cd??Ha??zc??(Ca?Tn.remain:null),dr=Cd!==null||Ha!==null?"spoolman":zc!==null?"inventory":Ca?"ams":void 0,$r=Tn?.tray_type?{vendor:Qs(Tn)?"Bambu Lab":"Generic",profile:wa?.preset_name||(qr?[qr.brand,qr.slicer_filament_name?.split("@")[0].trim()||qr.material].filter(Boolean).join(" ").trim():null)||Ji?.spool?.slicer_filament_name||ul?.name||Tn.tray_sub_brands||Tn.tray_type,colorName:yc(Tn.tray_color||""),colorHex:Tn.tray_color||null,kFactor:m3(Tn.k),fillLevel:ks,trayUuid:Tn.tray_uuid||null,tagUid:Tn.tag_uid||null,fillSource:dr}:null,Pa=Ro?.amsId===ht.id&&Ro?.slotId===tn,ju=r.jsxs("div",{className:`bg-bambu-dark-tertiary rounded p-1 text-center ${Qa?"opacity-50":""} ${Bl?"ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark":""}`,children:[r.jsx(u3,{trayColor:Tn?.tray_color,trayType:Tn?.tray_type,isEmpty:Qa,slotNumber:tn+1}),r.jsx("div",{className:"text-[9px] text-white font-bold truncate",children:Tn?.tray_type||"—"}),r.jsx("div",{className:"mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden",children:ks!==null&&ks>=0&&!Qa&&Tn&&r.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${ks}%`,backgroundColor:dy(ks)}})})]});return r.jsxs("div",{className:"relative group",children:[Pa&&r.jsx("div",{className:"absolute inset-0 bg-bambu-dark-tertiary/80 rounded flex items-center justify-center z-20",children:r.jsx(sr,{className:"w-4 h-4 text-bambu-green animate-spin"})}),qe?.state!=="RUNNING"&&r.jsx("button",{onClick:sn=>{sn.stopPropagation(),fi(Qi?.amsId===ht.id&&Qi?.slotId===tn?null:{amsId:ht.id,slotId:tn})},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:S("printers.slotOptions"),children:r.jsx(ym,{className:"w-2.5 h-2.5 text-bambu-gray"})}),qe?.state!=="RUNNING"&&Qi?.amsId===ht.id&&Qi?.slotId===tn&&r.jsxs("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:[r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-xs flex items-center gap-2 ${H("printers:ams_rfid")?"text-white hover:bg-bambu-dark-tertiary":"text-bambu-gray/50 cursor-not-allowed"}`,onClick:sn=>{sn.stopPropagation(),H("printers:ams_rfid")&&(Pu.mutate({amsId:ht.id,slotId:tn}),fi(null))},disabled:Pa||!H("printers:ams_rfid"),title:H("printers:ams_rfid")?void 0:S("printers.permission.noAmsRfid"),children:[r.jsx(sr,{className:`w-3 h-3 ${Pa?"animate-spin":""}`}),S("printers.rfid.reread")]}),r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-xs flex items-center gap-2 ${H("printers:control")?"text-white hover:bg-bambu-dark-tertiary":"text-bambu-gray/50 cursor-not-allowed"}`,onClick:sn=>{sn.stopPropagation(),H("printers:control")&&(Tu.mutate({trayId:ht.id*4+tn}),fi(null))},disabled:!H("printers:control"),title:H("printers:control")?void 0:S("printers.permission.noControl"),children:[r.jsx(K0,{className:"w-3 h-3"}),S("printers.ams.load")]}),r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-xs flex items-center gap-2 ${H("printers:control")?"text-white hover:bg-bambu-dark-tertiary":"text-bambu-gray/50 cursor-not-allowed"}`,onClick:sn=>{sn.stopPropagation(),H("printers:control")&&(_n.mutate(),fi(null))},disabled:!H("printers:control"),title:H("printers:control")?void 0:S("printers.permission.noControl"),children:[r.jsx(Jx,{className:"w-3 h-3"}),S("printers.ams.unload")]})]}),$r?r.jsx(s3,{data:$r,spoolman:{enabled:o,linkedSpoolId:(Ss?l?.[Ss]?.id:void 0)??_s?.spoolman_spool_id,spoolmanUrl:c,syncMode:d,onLinkSpool:o&&!_s&&!Ji?()=>{const sn=($r.trayUuid||$r.tagUid||fm(t.serial_number,ht.id,tn)).toUpperCase();_t({tagUid:$r.tagUid||sn,trayUuid:$r.trayUuid||"",printerId:t.id,amsId:ht.id,trayId:tn})}:void 0,onUnlinkSpool:gi?.id?()=>Ic.mutate(gi.id):void 0},inventory:(()=>{if(o){if(b)return;const pp=_s,ua=qr;return{assignedSpool:ua?{id:ua.id,material:ua.material,brand:ua.brand??null,color_name:ua.color_name??null,remainingWeightGrams:ua.label_weight?Math.max(0,Math.round(ua.label_weight-ua.weight_used)):void 0}:null,onAssignSpool:()=>De({printerId:t.id,amsId:ht.id,trayId:tn,trayInfo:{type:Tn?.tray_type||$r.profile,material:Tn?.tray_type??void 0,profile:$r.profile,color:$r.colorHex||"",location:`${$o(ht.id,ht.tray.length)} Slot ${tn+1}`}}),onUnassignSpool:ua&&!Qs(Tn)?()=>w?.(ua.id):void 0,isAssigned:!!pp||Qs(Tn)}}const sn=u?.(t.id,ht.id,tn);return{assignedSpool:sn?.spool?{id:sn.spool.id,material:sn.spool.material,brand:sn.spool.brand,color_name:sn.spool.color_name,remainingWeightGrams:Math.max(0,Math.round(sn.spool.label_weight-sn.spool.weight_used))}:null,onAssignSpool:()=>De({printerId:t.id,amsId:ht.id,trayId:tn,trayInfo:{type:Tn?.tray_type||$r.profile,material:Tn?.tray_type??void 0,profile:$r.profile,color:$r.colorHex||"",location:`${$o(ht.id,ht.tray.length)} Slot ${tn+1}`}}),onUnassignSpool:sn&&!Qs(Tn)?()=>m?.(t.id,ht.id,tn):void 0,isAssigned:!!sn||Qs(Tn)}})(),configureSlot:{enabled:H("printers:control"),onConfigure:()=>Ve({amsId:ht.id,trayId:tn,trayCount:ht.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:Un,caliIdx:Tn?.cali_idx,savedPresetId:wa?.preset_id})},children:ju}):r.jsx(o3,{configureSlot:{enabled:H("printers:control"),onConfigure:()=>Ve({amsId:ht.id,trayId:tn,trayCount:ht.tray.length,extruderId:Un})},onAssignSpool:()=>De({printerId:t.id,amsId:ht.id,trayId:tn,trayInfo:{type:"",material:void 0,profile:"",color:"",location:`${$o(ht.id,ht.tray.length)} Slot ${tn+1}`}}),children:ju})]},tn)})})]},ht.id)})}),($t.length>0||qe.vt_tray.length>0)&&r.jsxs("div",{className:"grid grid-cols-4 gap-3",children:[$t.map(ht=>{const Un=Ki[String(ht.id)],kr=ht.id>=128?ht.id-128:ht.id,Hn=Un!==void 0?Un:kr,ya=Hn===1,va=Hn===0,tn=ht.tray[0],Tn=tn?.tray_type&&tn.remain>=0,Ca=!tn?.tray_type,Qa=Xg(ht.id,tn?.id??0,!1),Zi=Ft===Qa,Bl=tn?.tray_info_idx?wn?.[tn.tray_info_idx]:null,ul=bn?.[Qa],wa=tn?.id??0,Ss=(tn?.tray_uuid||tn?.tag_uid||fm(t.serial_number,ht.id,wa))?.toUpperCase(),gi=Ss?l?.[Ss]:void 0,Cd=MN(gi),_s=u?.(t.id,ht.id,wa),qr=(()=>{const sn=_s?.spool;return sn&&sn.label_weight>0&&sn.weight_used!=null?Math.round(Math.max(0,sn.label_weight-sn.weight_used)/sn.label_weight*100):null})(),Ha=qr===0&&Tn&&tn.remain>0?null:qr,Ji=o&&!b?f?.find(sn=>sn.printer_id===t.id&&sn.ams_id===ht.id&&sn.tray_id===wa):void 0,Fi=Ji?p?.find(sn=>sn.id===Ji.spoolman_spool_id):void 0,zc=Fi&&(Fi.label_weight??0)>0?Math.round(Math.max(0,(Fi.label_weight??0)-Fi.weight_used)/(Fi.label_weight??1)*100):null,ks=Cd??zc??Ha??(Tn?tn.remain:null),dr=Cd!==null||zc!==null?"spoolman":Ha!==null?"inventory":Tn?"ams":void 0,$r=tn?.tray_type?{vendor:Qs(tn)?"Bambu Lab":"Generic",profile:ul?.preset_name||(Fi?[Fi.brand,Fi.slicer_filament_name?.split("@")[0].trim()||Fi.material].filter(Boolean).join(" ").trim():null)||_s?.spool?.slicer_filament_name||Bl?.name||tn.tray_sub_brands||tn.tray_type,colorName:yc(tn.tray_color||""),colorHex:tn.tray_color||null,kFactor:m3(tn.k),fillLevel:ks,trayUuid:tn.tray_uuid||null,tagUid:tn.tag_uid||null,fillSource:dr}:null,Pa=Ro?.amsId===ht.id&&Ro?.slotId===wa,ju=r.jsxs("div",{className:`bg-bambu-dark-tertiary rounded p-1 text-center ${Ca?"opacity-50":""} ${Zi?"ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark":""}`,children:[r.jsx(u3,{trayColor:tn?.tray_color,trayType:tn?.tray_type,isEmpty:Ca,slotNumber:1}),r.jsx("div",{className:"text-[9px] text-white font-bold truncate",children:tn?.tray_type||"—"}),r.jsx("div",{className:"mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden",children:ks!==null&&ks>=0&&!Ca&&r.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${ks}%`,backgroundColor:dy(ks)}})})]});return r.jsxs("div",{className:"p-2.5 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary/30",children:[r.jsxs("div",{className:"flex items-center gap-1 mb-2",children:[r.jsx(WK,{ams:ht,printerId:t.id,label:$o(ht.id,ht.tray.length),amsLabels:Er,canEdit:H("printers:update"),onSaved:zn,children:r.jsx("span",{className:"text-[10px] text-white font-medium cursor-default select-none",children:Er?.[ht.id]||$o(ht.id,ht.tray.length)})}),an&&(ya||va)&&r.jsx(BK,{side:ya?"L":"R"}),qe.supports_drying&&(ht.module_type==="n3f"||ht.module_type==="n3s")&&H("printers:control")&&r.jsx("div",{className:"relative ml-auto",children:r.jsx("button",{onClick:sn=>{if(ht.dry_time>0)Qr.mutate(ht.id);else if(Re===ht.id)tt(null);else{const ua=(ht.tray.find(b_=>b_.tray_type)?.tray_type||"PLA").split(" ")[0].toUpperCase(),Hl=C[ua]||C.PLA,Mu=ht.module_type;fe(ua),$e(Hl[Mu]||Hl.n3f),nt(Mu==="n3s"?Hl.n3s_hours:Hl.n3f_hours),yt(!1),Xe(ht.module_type),tt(ht.id);const yb=sn.currentTarget.getBoundingClientRect();Ht({top:yb.bottom+4,left:Math.max(8,yb.right-240)})}},className:`flex items-center gap-0.5 px-1 py-0.5 rounded text-[9px] transition-colors ${ht.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:ht.dry_time>0?S("printers.drying.stop"):S("printers.drying.start"),children:r.jsx(mm,{className:"w-3 h-3"})})})]}),ht.dry_time>0&&r.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:[r.jsx(mm,{className:"w-3 h-3 text-amber-400 shrink-0"}),r.jsx("span",{className:"text-amber-300/70 text-[8px] truncate",children:ht.dry_time>=60?`${Math.floor(ht.dry_time/60)}h ${ht.dry_time%60}m`:`${ht.dry_time}m`}),r.jsx("button",{onClick:()=>Qr.mutate(ht.id),disabled:Qr.isPending,className:"ml-auto text-amber-400 hover:text-amber-300 transition-colors disabled:opacity-50 shrink-0",title:S("printers.drying.stop"),children:r.jsx(Bt,{className:"w-3 h-3"})})]}),r.jsxs("div",{className:"flex gap-1.5 max-[550px]:flex-col max-[550px]:items-start",children:[r.jsxs("div",{className:"relative group flex-1 max-[550px]:w-full",children:[Pa&&r.jsx("div",{className:"absolute inset-0 bg-bambu-dark-tertiary/80 rounded flex items-center justify-center z-20",children:r.jsx(sr,{className:"w-4 h-4 text-bambu-green animate-spin"})}),qe?.state!=="RUNNING"&&r.jsx("button",{onClick:sn=>{sn.stopPropagation(),fi(Qi?.amsId===ht.id&&Qi?.slotId===wa?null:{amsId:ht.id,slotId:wa})},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:S("printers.slotOptions"),children:r.jsx(ym,{className:"w-2.5 h-2.5 text-bambu-gray"})}),qe?.state!=="RUNNING"&&Qi?.amsId===ht.id&&Qi?.slotId===wa&&r.jsxs("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:[r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-xs flex items-center gap-2 ${H("printers:ams_rfid")?"text-white hover:bg-bambu-dark-tertiary":"text-bambu-gray/50 cursor-not-allowed"}`,onClick:sn=>{sn.stopPropagation(),H("printers:ams_rfid")&&(Pu.mutate({amsId:ht.id,slotId:wa}),fi(null))},disabled:Pa||!H("printers:ams_rfid"),title:H("printers:ams_rfid")?void 0:S("printers.permission.noAmsRfid"),children:[r.jsx(sr,{className:`w-3 h-3 ${Pa?"animate-spin":""}`}),S("printers.rfid.reread")]}),r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-xs flex items-center gap-2 ${H("printers:control")?"text-white hover:bg-bambu-dark-tertiary":"text-bambu-gray/50 cursor-not-allowed"}`,onClick:sn=>{sn.stopPropagation(),H("printers:control")&&(Tu.mutate({trayId:ht.id*4+wa}),fi(null))},disabled:!H("printers:control"),title:H("printers:control")?void 0:S("printers.permission.noControl"),children:[r.jsx(K0,{className:"w-3 h-3"}),S("printers.ams.load")]}),r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-xs flex items-center gap-2 ${H("printers:control")?"text-white hover:bg-bambu-dark-tertiary":"text-bambu-gray/50 cursor-not-allowed"}`,onClick:sn=>{sn.stopPropagation(),H("printers:control")&&(_n.mutate(),fi(null))},disabled:!H("printers:control"),title:H("printers:control")?void 0:S("printers.permission.noControl"),children:[r.jsx(Jx,{className:"w-3 h-3"}),S("printers.ams.unload")]})]}),$r?r.jsx(s3,{data:$r,spoolman:{enabled:o,linkedSpoolId:(Ss?l?.[Ss]?.id:void 0)??Ji?.spoolman_spool_id,spoolmanUrl:c,syncMode:d,onLinkSpool:o&&!Ji&&!_s?()=>{const sn=($r.trayUuid||$r.tagUid||fm(t.serial_number,ht.id,wa)).toUpperCase();_t({tagUid:$r.tagUid||sn,trayUuid:$r.trayUuid||"",printerId:t.id,amsId:ht.id,trayId:wa})}:void 0,onUnlinkSpool:gi?.id?()=>Ic.mutate(gi.id):void 0},inventory:(()=>{if(o){if(b)return;const pp=Ji,ua=Fi;return{assignedSpool:ua?{id:ua.id,material:ua.material,brand:ua.brand??null,color_name:ua.color_name??null,remainingWeightGrams:ua.label_weight?Math.max(0,Math.round(ua.label_weight-ua.weight_used)):void 0}:null,onAssignSpool:()=>De({printerId:t.id,amsId:ht.id,trayId:wa,trayInfo:{type:tn?.tray_type||$r.profile,material:tn?.tray_type??void 0,profile:$r.profile,color:$r.colorHex||"",location:$o(ht.id,ht.tray.length)}}),onUnassignSpool:ua&&!Qs(tn)?()=>w?.(ua.id):void 0,isAssigned:!!pp||Qs(tn)}}const sn=u?.(t.id,ht.id,wa);return{assignedSpool:sn?.spool?{id:sn.spool.id,material:sn.spool.material,brand:sn.spool.brand,color_name:sn.spool.color_name,remainingWeightGrams:Math.max(0,Math.round(sn.spool.label_weight-sn.spool.weight_used))}:null,onAssignSpool:()=>De({printerId:t.id,amsId:ht.id,trayId:wa,trayInfo:{type:tn?.tray_type||$r.profile,material:tn?.tray_type??void 0,profile:$r.profile,color:$r.colorHex||"",location:$o(ht.id,ht.tray.length)}}),onUnassignSpool:sn&&!Qs(tn)?()=>m?.(t.id,ht.id,wa):void 0,isAssigned:!!sn||Qs(tn)}})(),configureSlot:{enabled:H("printers:control"),onConfigure:()=>Ve({amsId:ht.id,trayId:wa,trayCount:ht.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:Un,caliIdx:tn?.cali_idx,savedPresetId:ul?.preset_id})},children:ju}):r.jsx(o3,{configureSlot:{enabled:H("printers:control"),onConfigure:()=>Ve({amsId:ht.id,trayId:wa,trayCount:ht.tray.length,extruderId:Un})},onAssignSpool:()=>De({printerId:t.id,amsId:ht.id,trayId:wa,trayInfo:{type:"",material:void 0,profile:"",color:"",location:$o(ht.id,ht.tray.length)}}),children:ju})]}),(ht.humidity!=null||ht.temp!=null)&&r.jsxs("div",{className:"flex flex-col justify-center gap-1 shrink-0 max-[550px]:w-full",children:[ht.temp!=null&&r.jsx($K,{temp:ht.temp,goodThreshold:s?.tempGood,fairThreshold:s?.tempFair,onClick:()=>at({amsId:ht.id,amsLabel:$o(ht.id,ht.tray.length),mode:"temperature"}),compact:!0}),ht.humidity!=null&&r.jsx(qK,{humidity:ht.humidity,goodThreshold:s?.humidityGood,fairThreshold:s?.humidityFair,onClick:()=>at({amsId:ht.id,amsLabel:$o(ht.id,ht.tray.length),mode:"humidity"}),compact:!0})]})]})]},ht.id)}),qe.vt_tray.length>0&&r.jsxs("div",{className:`p-2.5 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary/30 ${qe.vt_tray.length===1?"max-w-[50%]":""}`,children:[r.jsx("div",{className:"flex items-center gap-1 mb-2",children:r.jsx("span",{className:"text-[10px] text-white font-medium",children:S("printers.external")})}),r.jsx("div",{className:`grid ${qe.vt_tray.length>1?"grid-cols-2":"grid-cols-1"} gap-1.5`,children:[...qe.vt_tray].sort((ht,Un)=>(ht.id??254)-(Un.id??254)).map(ht=>{const Un=ht.id??254,kr=an&&Ft===254?Un===254&&qe.active_extruder===1||Un===255&&qe.active_extruder===0:Ft===Un,Hn=Un-254,ya=an?S(Un===254?"printers.extL":"printers.extR"):"",va=ht.tray_info_idx?wn?.[ht.tray_info_idx]:null,tn=bn?.[1020+Hn],Tn=(ht.tray_uuid||ht.tag_uid||fm(t.serial_number,255,Hn))?.toUpperCase(),Ca=Tn?l?.[Tn]:void 0,Qa=MN(Ca),Zi=u?.(t.id,255,Hn),Bl=(()=>{const dr=Zi?.spool;return dr&&dr.label_weight>0&&dr.weight_used!=null?Math.round(Math.max(0,dr.label_weight-dr.weight_used)/dr.label_weight*100):null})(),ul=ht.tray_type&&ht.remain>=0,wa=Bl===0&&ul&&ht.remain>0?null:Bl,Ss=o&&!b?f?.find(dr=>dr.printer_id===t.id&&dr.ams_id===255&&dr.tray_id===Hn):void 0,gi=Ss?p?.find(dr=>dr.id===Ss.spoolman_spool_id):void 0,Cd=gi&&(gi.label_weight??0)>0?Math.round(Math.max(0,(gi.label_weight??0)-gi.weight_used)/(gi.label_weight??1)*100):null,_s=Qa??Cd??wa??(ul?ht.remain:null),qr=Qa!==null||Cd!==null?"spoolman":wa!==null?"inventory":ul?"ams":void 0,Ha={vendor:Qs(ht)?"Bambu Lab":"Generic",profile:tn?.preset_name||(gi?[gi.brand,gi.slicer_filament_name?.split("@")[0].trim()||gi.material].filter(Boolean).join(" ").trim():null)||Zi?.spool?.slicer_filament_name||va?.name||ht.tray_sub_brands||ht.tray_type||"Unknown",colorName:yc(ht.tray_color||""),colorHex:ht.tray_color||null,kFactor:m3(ht.k),fillLevel:_s,trayUuid:ht.tray_uuid||null,tagUid:ht.tag_uid||null,fillSource:qr},Ji=!ht.tray_type,Fi=r.jsxs("div",{className:`bg-bambu-dark-tertiary rounded p-1 text-center ${Ji?"opacity-50":""} ${kr?"ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark":""}`,children:[r.jsx(u3,{trayColor:ht.tray_color,trayType:ht.tray_type,isEmpty:Ji,slotNumber:Hn+1}),r.jsx("div",{className:`text-[9px] font-bold truncate ${Ji?"text-white/40":"text-white"}`,children:ht.tray_type||"—"}),r.jsx("div",{className:"mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden",children:_s!==null&&_s>=0&&!Ji&&r.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${_s}%`,backgroundColor:dy(_s)}})}),ya&&r.jsx("div",{className:"text-[7px] text-white/40 mt-0.5 truncate",children:ya})]}),zc=2550+Hn,ks=Qi?.amsId===255&&Qi?.slotId===zc;return r.jsxs("div",{className:"relative group",children:[qe?.state!=="RUNNING"&&r.jsx("button",{onClick:dr=>{dr.stopPropagation(),fi(ks?null:{amsId:255,slotId:zc})},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:S("printers.slotOptions"),children:r.jsx(ym,{className:"w-2.5 h-2.5 text-bambu-gray"})}),qe?.state!=="RUNNING"&&ks&&r.jsxs("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:[r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-xs flex items-center gap-2 ${H("printers:control")?"text-white hover:bg-bambu-dark-tertiary":"text-bambu-gray/50 cursor-not-allowed"}`,onClick:dr=>{dr.stopPropagation(),H("printers:control")&&(Tu.mutate({trayId:Un}),fi(null))},disabled:!H("printers:control"),title:H("printers:control")?void 0:S("printers.permission.noControl"),children:[r.jsx(K0,{className:"w-3 h-3"}),S("printers.ams.load")]}),r.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-xs flex items-center gap-2 ${H("printers:control")?"text-white hover:bg-bambu-dark-tertiary":"text-bambu-gray/50 cursor-not-allowed"}`,onClick:dr=>{dr.stopPropagation(),H("printers:control")&&(_n.mutate(),fi(null))},disabled:!H("printers:control"),title:H("printers:control")?void 0:S("printers.permission.noControl"),children:[r.jsx(Jx,{className:"w-3 h-3"}),S("printers.ams.unload")]})]}),Ji?r.jsx(o3,{configureSlot:{enabled:H("printers:control"),onConfigure:()=>Ve({amsId:255,trayId:Hn,trayCount:1,extruderId:an?Un===254?1:0:void 0})},onAssignSpool:()=>De({printerId:t.id,amsId:255,trayId:Hn,trayInfo:{type:"",material:void 0,profile:"",color:"",location:`External Slot ${Hn+1}`}}),children:Fi}):r.jsx(s3,{data:Ha,spoolman:{enabled:o,linkedSpoolId:(Tn?l?.[Tn]?.id:void 0)??Ss?.spoolman_spool_id,spoolmanUrl:c,syncMode:d,onLinkSpool:o&&!Ss&&!Zi?()=>{const dr=(Ha.trayUuid||Ha.tagUid||fm(t.serial_number,255,Hn)).toUpperCase();_t({tagUid:Ha.tagUid||dr,trayUuid:Ha.trayUuid||"",printerId:t.id,amsId:255,trayId:Hn})}:void 0,onUnlinkSpool:Ca?.id?()=>Ic.mutate(Ca.id):void 0},inventory:(()=>{if(o){if(b)return;const $r=Ss,Pa=gi;return{assignedSpool:Pa?{id:Pa.id,material:Pa.material,brand:Pa.brand??null,color_name:Pa.color_name??null,remainingWeightGrams:Pa.label_weight?Math.max(0,Math.round(Pa.label_weight-Pa.weight_used)):void 0}:null,onAssignSpool:()=>De({printerId:t.id,amsId:255,trayId:Hn,trayInfo:{type:ht.tray_type||Ha.profile,material:ht.tray_type??void 0,profile:Ha.profile,color:Ha.colorHex||"",location:ya||S("printers.external")}}),onUnassignSpool:Pa&&!Qs(ht)?()=>w?.(Pa.id):void 0,isAssigned:!!$r||Qs(ht)}}const dr=u?.(t.id,255,Hn);return{assignedSpool:dr?.spool?{id:dr.spool.id,material:dr.spool.material,brand:dr.spool.brand,color_name:dr.spool.color_name,remainingWeightGrams:Math.max(0,Math.round(dr.spool.label_weight-dr.spool.weight_used))}:null,onAssignSpool:()=>De({printerId:t.id,amsId:255,trayId:Hn,trayInfo:{type:ht.tray_type||Ha.profile,material:ht.tray_type??void 0,profile:Ha.profile,color:Ha.colorHex||"",location:ya||S("printers.external")}}),onUnassignSpool:dr&&!Qs(ht)?()=>m?.(t.id,255,Hn):void 0,isAssigned:!!dr||Qs(ht)}})(),configureSlot:{enabled:H("printers:control"),onConfigure:()=>Ve({amsId:255,trayId:Hn,trayCount:1,trayType:ht.tray_type||void 0,trayColor:ht.tray_color||void 0,traySubBrands:ht.tray_sub_brands||void 0,trayInfoIdx:ht.tray_info_idx||void 0,extruderId:an?Un===254?1:0:void 0,caliIdx:ht.cali_idx,savedPresetId:tn?.preset_id})},children:Fi})]},Un)})})]})]})]})]})})()]}),cn&&a==="expanded"&&r.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[r.jsx(Nc,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}),r.jsx("span",{className:"text-sm text-white truncate",children:cn.name}),Gt&&r.jsxs("span",{className:`text-xs px-1.5 py-0.5 rounded flex-shrink-0 ${Gt.state==="ON"?"bg-bambu-green/20 text-bambu-green":Gt.state==="OFF"?"bg-red-500/20 text-red-400":"bg-bambu-gray/20 text-bambu-gray"}`,children:[Gt.state||"?",Gt.state==="ON"&&Gt.energy?.power!=null&&r.jsxs("span",{className:"text-yellow-400 ml-1.5",children:["· ",Math.round(Gt.energy.power),"W"]})]})]}),r.jsx("div",{className:"flex-1"}),r.jsxs("div",{className:"flex items-center gap-1",children:[r.jsxs("button",{onClick:()=>K(!0),disabled:Do.isPending||Gt?.state==="ON"||!H("smart_plugs:control"),className:`px-2 py-1 text-xs rounded transition-colors flex items-center gap-1 ${H("smart_plugs:control")?Gt?.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:H("smart_plugs:control")?void 0:S("printers.permission.noSmartPlugControl"),children:[r.jsx(wu,{className:"w-3 h-3"}),"On"]}),r.jsxs("button",{onClick:()=>j(!0),disabled:Do.isPending||Gt?.state==="OFF"||!H("smart_plugs:control"),className:`px-2 py-1 text-xs rounded transition-colors flex items-center gap-1 ${H("smart_plugs:control")?Gt?.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:H("smart_plugs:control")?void 0:S("printers.permission.noSmartPlugControl"),children:[r.jsx(jS,{className:"w-3 h-3"}),"Off"]})]}),r.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[r.jsx("span",{className:`text-xs hidden sm:inline ${cn.auto_off_executed?"text-bambu-green":"text-bambu-gray"}`,children:cn.auto_off_executed?"Auto-off done":"Auto-off"}),r.jsx("button",{onClick:()=>ol.mutate(!cn.auto_off),disabled:ol.isPending||cn.auto_off_executed||!H("smart_plugs:control"),title:H("smart_plugs:control")?cn.auto_off_executed?S("printers.autoOffExecuted"):S("printers.autoOffAfterPrint"):S("printers.permission.noSmartPlugControl"),className:`relative w-9 h-5 rounded-full transition-colors flex-shrink-0 ${H("smart_plugs:control")?cn.auto_off_executed?"bg-bambu-green/50 cursor-not-allowed":cn.auto_off?"bg-bambu-green":"bg-bambu-dark-tertiary":"bg-bambu-dark-tertiary/50 cursor-not-allowed"}`,children:r.jsx("span",{className:`absolute top-[2px] left-[2px] w-4 h-4 bg-white rounded-full transition-transform ${cn.auto_off||cn.auto_off_executed?"translate-x-4":"translate-x-0"}`})})]})]}),hr&&hr.length>0&&r.jsxs("div",{className:"flex items-center gap-2 mt-2 pt-2 border-t border-bambu-dark-tertiary/50",children:[r.jsx(NS,{className:"w-3.5 h-3.5 text-blue-400 flex-shrink-0"}),r.jsx("span",{className:"text-xs text-bambu-gray",children:"HA:"}),r.jsx("div",{className:"flex flex-wrap gap-1",children:hr.map(lt=>{const $t=lt.ha_entity_id?.startsWith("script.");return r.jsxs("button",{onClick:()=>{$t?ll.mutate({id:lt.id,action:"on"}):X(lt)},disabled:ll.isPending,title:`${$t?"Run":"Toggle"} ${lt.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:[r.jsx(fs,{className:"w-2.5 h-2.5"}),lt.name]},lt.id)})})]})]}),a==="expanded"&&r.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary flex items-center justify-end gap-2 flex-wrap",children:[r.jsx(Me,{variant:"secondary",size:"sm",onClick:()=>wd.mutate(!qe?.chamber_light),disabled:!qe?.connected||wd.isPending||!H("printers:control"),title:H("printers:control")?qe?.chamber_light?S("printers.chamberLightOff"):S("printers.chamberLightOn"):S("printers.permission.noControl"),className:qe?.chamber_light?"!border-yellow-500 !text-yellow-400 hover:!bg-yellow-500/20":"",children:r.jsx(e4,{on:qe?.chamber_light??!1,className:`w-4 h-4 ${qe?.chamber_light?"text-yellow-400":""}`})}),r.jsx(Me,{variant:"secondary",size:"sm",onClick:()=>{if(x==="embedded"&&_)_(t.id,t.name);else{const lt=localStorage.getItem("cameraWindowState"),$t=lt?JSON.parse(lt):{width:640,height:400},an=[`width=${$t.width}`,`height=${$t.height}`,$t.left!==void 0?`left=${$t.left}`:"",$t.top!==void 0?`top=${$t.top}`:"","menubar=no,toolbar=no,location=no,status=no"].filter(Boolean).join(",");window.open(`/camera/${t.id}`,`camera-${t.id}`,an)}},disabled:!qe?.connected||!H("camera:view"),title:H("camera:view")?S(x==="embedded"?"printers.openCameraOverlay":"printers.openCameraWindow"):S("printers.permission.noCamera"),children:r.jsx(aC,{className:"w-4 h-4"})}),r.jsxs("div",{className:`inline-flex rounded-md ${t.plate_detection_enabled?"ring-1 ring-green-500":""}`,children:[r.jsx(Me,{variant:"secondary",size:"sm",onClick:ff,disabled:!qe?.connected||po.isPending||!H("printers:update"),title:H("printers:update")?t.plate_detection_enabled?S("printers.plateDetection.enabledClick"):S("printers.plateDetection.disabledClick"):S("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:po.isPending?r.jsx(ut,{className:"w-4 h-4 animate-spin"}):r.jsx(nC,{className:"w-4 h-4"})}),r.jsx(Me,{variant:"secondary",size:"sm",onClick:bb,disabled:!qe?.connected||Fe||!H("printers:update"),title:H("printers:update")?S("printers.plateDetection.manageCalibration"):S("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:Fe?r.jsx(ut,{className:"w-3 h-3 animate-spin"}):r.jsx(Rn,{className:"w-3 h-3"})})]}),r.jsxs(Me,{variant:"secondary",size:"sm",onClick:()=>pe(!0),disabled:!jr||!H("printers:files"),title:H("printers:files")?S("printers.browseFiles"):S("printers.permission.noFiles"),children:[r.jsx(ob,{className:"w-4 h-4"}),S("printers.files")]}),jr&&qe?.state!=="RUNNING"&&qe?.state!=="PAUSE"&&r.jsxs(Me,{size:"sm",onClick:()=>_e(!0),disabled:!H("printers:control"),title:H("printers:control")?S("common.print"):S("printers.permission.noControl"),className:"!bg-bambu-green hover:!bg-bambu-green/80 !text-white",children:[r.jsx(pr,{className:"w-4 h-4"}),S("common.print")]})]})]}),ae&&r.jsx(qEe,{printerId:t.id,printerName:t.name,onClose:()=>pe(!1)}),ze&&r.jsx(Oie,{folderId:null,onClose:()=>_e(!1),onUploadComplete:()=>{},autoUpload:!0,accept:".gcode,.3mf",validateFile:lt=>{const $t=lt.name.toLowerCase();if(!$t.endsWith(".gcode")&&!$t.includes(".gcode."))return S("printers.dropNotPrintable","Only .gcode and .gcode.3mf files can be printed")},onFileUploaded:lt=>{const $t=lt.metadata?.sliced_for_model,an=rw(t.model);if($t&&an&&$t.toLowerCase()!==an.toLowerCase())return se.deleteLibraryFile(lt.id).catch(()=>{}),S("printers.incompatibleFile","This file was sliced for {{slicedFor}}, but this printer is a {{printerModel}}",{slicedFor:$t,printerModel:an});st({id:lt.id,filename:lt.filename})}}),rt&&r.jsx(wc,{mode:"reprint",libraryFileId:rt.id,archiveName:rt.filename,initialSelectedPrinterIds:[t.id],onClose:()=>st(null),onSuccess:()=>st(null),cleanupLibraryAfterDispatch:!0}),ye&&r.jsx(YEe,{printerId:t.id,printerName:t.name,onClose:()=>Te(!1)}),Oe&&r.jsx(C7e,{printer:t,status:qe,totalPrintHours:n?.total_print_hours,onClose:Ke}),dt&&r.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onClick:()=>Ul(),children:r.jsxs("div",{className:"bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl max-w-lg w-full",onClick:lt=>lt.stopPropagation(),children:[r.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[dt.needs_calibration?r.jsx(nC,{className:"w-5 h-5 text-blue-500"}):dt.is_empty?r.jsx(wr,{className:"w-5 h-5 text-green-500"}):r.jsx(Da,{className:"w-5 h-5 text-yellow-500"}),r.jsx("h2",{className:"text-lg font-semibold text-white",children:"Build Plate Check"}),dt.reference_count!==void 0&&dt.max_references&&r.jsxs("span",{className:"text-xs text-bambu-gray bg-bambu-dark-tertiary px-2 py-1 rounded",children:[dt.reference_count,"/",dt.max_references," refs"]})]}),r.jsx("button",{onClick:()=>Ul(),className:"p-1 text-bambu-gray hover:text-white rounded transition-colors",children:r.jsx(Bt,{className:"w-5 h-5"})})]}),r.jsxs("div",{className:"p-4 space-y-4",children:[dt.needs_calibration?r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"p-3 rounded-lg bg-blue-500/20 border border-blue-500/50",children:[r.jsx("p",{className:"font-medium text-blue-400",children:S("printers.plateDetection.calibrationRequired")}),r.jsx("p",{className:"text-sm text-bambu-gray mt-1",dangerouslySetInnerHTML:{__html:S("printers.plateDetection.calibrationInstructions")}})]}),r.jsxs("div",{className:"text-sm text-bambu-gray space-y-2",children:[r.jsx("p",{children:S("printers.plateDetection.calibrationDescription")}),r.jsx("p",{dangerouslySetInnerHTML:{__html:S("printers.plateDetection.calibrationTip")}})]})]}):r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:`p-3 rounded-lg ${dt.is_empty?"bg-green-500/20 border border-green-500/50":"bg-yellow-500/20 border border-yellow-500/50"}`,children:[r.jsx("p",{className:`font-medium ${dt.is_empty?"text-green-400":"text-yellow-400"}`,children:dt.is_empty?S("printers.plateDetection.plateEmpty"):S("printers.plateDetection.objectsDetected")}),r.jsxs("p",{className:"text-sm text-bambu-gray mt-1",children:[S("printers.plateDetection.confidence"),": ",Math.round(dt.confidence*100),"% | ",S("printers.plateDetection.difference"),": ",dt.difference_percent.toFixed(1),"%"]})]}),dt.debug_image_url&&r.jsxs("div",{children:[r.jsx("p",{className:"text-sm text-bambu-gray mb-2",children:S("printers.plateDetection.analysisPreview")}),r.jsx("img",{src:dt.debug_image_url,alt:S("printers.plateDetection.analysisPreview"),className:"w-full rounded-lg border border-bambu-dark-tertiary"}),r.jsx("p",{className:"text-xs text-bambu-gray mt-2",children:S("printers.plateDetection.analysisLegend")})]}),r.jsx("p",{className:"text-xs text-bambu-gray",children:dt.message})]}),Lo&&Lo.references.length>0&&r.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[r.jsx("p",{className:"text-sm font-medium text-white mb-2",children:S("printers.plateDetection.savedReferences",{count:Lo.references.length,max:Lo.max_references})}),r.jsx("div",{className:"grid grid-cols-5 gap-2",children:Lo.references.map(lt=>r.jsxs("div",{className:"relative group",children:[r.jsx("img",{src:se.getPlateReferenceThumbnailUrl(t.id,lt.index),alt:lt.label||`Reference ${lt.index+1}`,className:"w-full aspect-video object-cover rounded border border-bambu-dark-tertiary"}),r.jsx("button",{onClick:()=>hv(lt.index),className:"absolute top-1 right-1 p-0.5 bg-red-500/80 rounded opacity-0 group-hover:opacity-100 transition-opacity",title:S("printers.plateDetection.deleteReference"),children:r.jsx(Bt,{className:"w-3 h-3 text-white"})}),_d?.index===lt.index?r.jsx("input",{type:"text",value:_d.label,onChange:$t=>kd({..._d,label:$t.target.value}),onBlur:()=>xb(lt.index,_d.label),onKeyDown:$t=>{$t.key==="Enter"&&xb(lt.index,_d.label),$t.key==="Escape"&&kd(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:S("printers.plateDetection.labelPlaceholder")}):r.jsx("p",{className:"text-xs text-bambu-gray mt-1 truncate cursor-pointer hover:text-white",onClick:()=>kd({index:lt.index,label:lt.label}),title:lt.label?S("printers.plateDetection.clickToEdit",{label:lt.label}):S("printers.plateDetection.clickToAddLabel"),children:lt.label||r.jsx("span",{className:"italic opacity-50",children:S("printers.noLabel")})}),r.jsx("p",{className:"text-[10px] text-bambu-gray/60",children:lt.timestamp?Xn(lt.timestamp)?.toLocaleDateString()??"":""})]},lt.index))})]}),!dt.needs_calibration&&r.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center justify-between mb-2",children:[r.jsx("p",{className:"text-sm font-medium text-white",children:S("printers.roi.title")}),ft?r.jsxs("div",{className:"flex gap-1",children:[r.jsx(Me,{variant:"ghost",size:"sm",onClick:()=>et(null),disabled:jt,children:S("common.cancel")}),r.jsx(Me,{size:"sm",onClick:bf,disabled:jt,children:jt?r.jsx(ut,{className:"w-3 h-3 animate-spin"}):S("common.save")})]}):r.jsxs(Me,{variant:"ghost",size:"sm",onClick:()=>et(dt.roi||{x:.15,y:.35,w:.7,h:.55}),children:[r.jsx(oi,{className:"w-3 h-3 mr-1"}),S("common.edit")]})]}),ft?r.jsxs("div",{className:"space-y-3 bg-bambu-dark-tertiary/50 p-3 rounded-lg",children:[r.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[r.jsxs("div",{children:[r.jsx("label",{className:"text-xs text-bambu-gray",children:S("printers.roi.xStart")}),r.jsx("input",{type:"range",min:"0",max:"0.9",step:"0.01",value:ft.x,onChange:lt=>et({...ft,x:parseFloat(lt.target.value)}),className:"w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"}),r.jsxs("span",{className:"text-xs text-bambu-gray",children:[Math.round(ft.x*100),"%"]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"text-xs text-bambu-gray",children:S("printers.roi.yStart")}),r.jsx("input",{type:"range",min:"0",max:"0.9",step:"0.01",value:ft.y,onChange:lt=>et({...ft,y:parseFloat(lt.target.value)}),className:"w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"}),r.jsxs("span",{className:"text-xs text-bambu-gray",children:[Math.round(ft.y*100),"%"]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"text-xs text-bambu-gray",children:S("printers.width")}),r.jsx("input",{type:"range",min:"0.1",max:"1",step:"0.01",value:ft.w,onChange:lt=>et({...ft,w:parseFloat(lt.target.value)}),className:"w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"}),r.jsxs("span",{className:"text-xs text-bambu-gray",children:[Math.round(ft.w*100),"%"]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"text-xs text-bambu-gray",children:S("printers.height")}),r.jsx("input",{type:"range",min:"0.1",max:"1",step:"0.01",value:ft.h,onChange:lt=>et({...ft,h:parseFloat(lt.target.value)}),className:"w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"}),r.jsxs("span",{className:"text-xs text-bambu-gray",children:[Math.round(ft.h*100),"%"]})]})]}),r.jsx("p",{className:"text-xs text-bambu-gray",children:S("printers.roi.instruction")})]}):r.jsxs("p",{className:"text-xs text-bambu-gray",children:["Current: X=",Math.round((dt.roi?.x||.15)*100),"%, Y=",Math.round((dt.roi?.y||.35)*100),"%, W=",Math.round((dt.roi?.w||.7)*100),"%, H=",Math.round((dt.roi?.h||.55)*100),"%"]})]})]}),r.jsx("div",{className:"flex justify-end gap-2 p-4 border-t border-bambu-dark-tertiary",children:dt.needs_calibration?r.jsxs(r.Fragment,{children:[r.jsx(Me,{variant:"ghost",onClick:()=>Ul(),children:S("common.cancel")}),r.jsx(Me,{onClick:()=>gf(),disabled:Ze,children:Ze?r.jsxs(r.Fragment,{children:[r.jsx(ut,{className:"w-4 h-4 mr-2 animate-spin"}),"Calibrating..."]}):"Calibrate Empty Plate"})]}):r.jsxs(r.Fragment,{children:[r.jsx(Me,{variant:"ghost",onClick:()=>gf(),disabled:Ze,children:Ze?"Adding...":`Add Reference (${Lo?.references.length||0}/${Lo?.max_references||5})`}),r.jsx(Me,{onClick:()=>Ul(),children:"Close"})]})})]})}),$&&cn&&r.jsx(vn,{title:S("printers.confirm.powerOnTitle"),message:S("printers.confirm.powerOnMessage",{name:t.name}),confirmText:S("printers.confirm.powerOnButton"),variant:"default",onConfirm:()=>{Do.mutate("on"),K(!1)},onCancel:()=>K(!1)}),D&&cn&&r.jsx(vn,{title:S("printers.confirm.powerOffTitle"),message:qe?.state==="RUNNING"?S("printers.confirm.powerOffWarning",{name:t.name}):S("printers.confirm.powerOffMessage",{name:t.name}),confirmText:S("printers.confirm.powerOffButton"),variant:"danger",onConfirm:()=>{Do.mutate("off"),j(!1)},onCancel:()=>j(!1)}),B&&r.jsx(vn,{title:S("printers.confirm.haToggleTitle",{name:B.name}),message:qe?.state==="RUNNING"?S("printers.confirm.haToggleWarning",{name:t.name,entity:B.ha_entity_id||B.name}):S("printers.confirm.haToggleMessage",{entity:B.ha_entity_id||B.name}),confirmText:S("printers.confirm.haToggleButton"),variant:qe?.state==="RUNNING"?"danger":"default",onConfirm:()=>{ll.mutate({id:B.id,action:"toggle"}),X(null)},onCancel:()=>X(null)}),U&&r.jsx(vn,{title:S("printers.confirm.stopTitle"),message:S("printers.confirm.stopMessage",{name:t.name}),confirmText:S("printers.confirm.stopButton"),variant:"danger",onConfirm:()=>{cl.mutate(),G(!1)},onCancel:()=>G(!1)}),Y&&r.jsx(vn,{title:S("printers.confirm.pauseTitle"),message:S("printers.confirm.pauseMessage",{name:t.name}),confirmText:S("printers.confirm.pauseButton"),variant:"default",onConfirm:()=>{vd.mutate(),Q(!1)},onCancel:()=>Q(!1)}),Ne&&r.jsx(vn,{title:S("printers.confirm.resumeTitle"),message:S("printers.confirm.resumeMessage",{name:t.name}),confirmText:S("printers.confirm.resumeButton"),variant:"default",onConfirm:()=>{dp.mutate(),ve(!1)},onCancel:()=>ve(!1)}),xe&&r.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/70 p-4",children:r.jsxs("div",{className:"bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl w-full max-w-sm p-5",children:[r.jsxs("div",{className:"flex items-start gap-3 mb-4",children:[r.jsx(Nn,{className:"w-5 h-5 text-yellow-400 flex-shrink-0 mt-0.5"}),r.jsxs("div",{children:[r.jsx("h3",{className:"text-sm font-semibold text-white mb-1",children:S("printers.bedJog.notHomedTitle")}),r.jsx("p",{className:"text-xs text-bambu-gray leading-relaxed",children:S("printers.bedJog.notHomedMessage")})]})]}),r.jsxs("div",{className:"flex flex-col gap-2",children:[r.jsx("button",{onClick:()=>{pf.mutate("all"),we(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:S("printers.bedJog.homeZ")}),r.jsx("button",{onClick:()=>{const lt=xe.distance;try{sessionStorage.setItem(`bambuddy.bedJog.warned.${t.id}`,"1")}catch{}mf.mutate({distance:lt,force:!0}),we(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:S("printers.bedJog.moveAnyway")}),r.jsx("button",{onClick:()=>we(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:S("common.cancel")})]})]})}),r.jsx(t4,{printerId:t.id,isOpen:be,onClose:()=>Ee(!1)}),O&&r.jsx(Vve,{printerName:t.name,errors:qe?.hms_errors||[],onClose:()=>ie(!1),printerId:t.id,hasPermission:H}),pt&&r.jsx(a7e,{isOpen:!!pt,onClose:()=>at(null),printerId:t.id,printerName:t.name,amsId:pt.amsId,amsLabel:pt.amsLabel,initialMode:pt.mode,thresholds:s}),vt&&r.jsx(Rie,{isOpen:!!vt,onClose:()=>_t(null),tagUid:vt.tagUid,trayUuid:vt.trayUuid,printerId:vt.printerId,amsId:vt.amsId,trayId:vt.trayId}),Dt&&r.jsx(Lie,{isOpen:!!Dt,onClose:()=>De(null),printerId:Dt.printerId,amsId:Dt.amsId,trayId:Dt.trayId,trayInfo:Dt.trayInfo,spoolmanEnabled:!!o}),je&&r.jsx(Iie,{isOpen:!!je,onClose:()=>Ve(null),printerId:t.id,slotInfo:je,printerModel:rw(t.model)||void 0,onSuccess:()=>{M.invalidateQueries({queryKey:["slotPresets",t.id]}),M.invalidateQueries({queryKey:["printerStatus",t.id]})}}),ue&&r.jsx(B7e,{printer:t,onClose:()=>W(!1)}),Je&&Ge&&r.jsx(U7e,{printer:t,firmwareInfo:Ge,onClose:()=>Le(!1)}),Qi&&r.jsx("div",{className:"fixed inset-0 z-40",onClick:()=>fi(null)}),Re!==null&&ot&&(()=>{const lt=Ce==="n3s"?85:65,$t=35,an=lt+10;return r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"fixed inset-0 z-[100]",onClick:()=>tt(null)}),r.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:ot.top,left:ot.left},onClick:ht=>ht.stopPropagation(),children:[r.jsxs("div",{className:"flex items-center gap-2 px-3 py-2.5 border-b border-bambu-dark-tertiary",children:[r.jsx(mm,{className:"w-3.5 h-3.5 text-amber-400"}),r.jsx("span",{className:"text-xs text-white font-medium",children:S("printers.drying.start")})]}),r.jsxs("div",{className:"px-3 py-2.5 space-y-2.5",children:[r.jsxs("div",{children:[r.jsx("label",{className:"text-[10px] text-bambu-gray mb-1 block",children:S("printers.filaments")}),r.jsx("select",{value:Ue,onChange:ht=>{const Un=ht.target.value;fe(Un);const kr=C[Un];kr&&($e(kr[Ce==="n3s"?"n3s":"n3f"]),nt(Ce==="n3s"?kr.n3s_hours:kr.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(C).map(ht=>r.jsx("option",{value:ht,children:ht},ht))})]}),r.jsxs("div",{children:[r.jsxs("div",{className:"flex items-center justify-between mb-1",children:[r.jsx("label",{className:"text-[10px] text-bambu-gray",children:S("printers.drying.temperature")}),r.jsxs("div",{className:"flex items-center gap-1",children:[r.jsx("input",{type:"number",min:45,max:lt,value:Ae,onChange:ht=>$e(Math.min(lt,Math.max(45,Number(ht.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"}),r.jsx("span",{className:"text-[10px] text-bambu-gray",children:"°C"})]})]}),r.jsx("input",{type:"range",min:$t,max:an,value:Ae,onChange:ht=>$e(Math.min(lt,Math.max(45,Number(ht.target.value)))),className:"w-full h-1 accent-amber-500 cursor-pointer"}),r.jsxs("div",{className:"flex justify-between text-[9px] text-bambu-gray/50 mt-0.5",children:[r.jsx("span",{children:"45°C"}),r.jsxs("span",{children:[lt,"°C"]})]})]}),r.jsxs("div",{children:[r.jsxs("div",{className:"flex items-center justify-between mb-1",children:[r.jsx("label",{className:"text-[10px] text-bambu-gray",children:S("printers.drying.duration")}),r.jsxs("div",{className:"flex items-center gap-1",children:[r.jsx("input",{type:"number",min:1,max:24,value:Be,onChange:ht=>nt(Math.min(24,Math.max(1,Number(ht.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"}),r.jsx("span",{className:"text-[10px] text-bambu-gray",children:S("printers.drying.hours")})]})]}),r.jsx("input",{type:"range",min:1,max:24,value:Be,onChange:ht=>nt(Number(ht.target.value)),className:"w-full h-1 accent-amber-500 cursor-pointer"}),r.jsxs("div",{className:"flex justify-between text-[9px] text-bambu-gray/50 mt-0.5",children:[r.jsx("span",{children:"1h"}),r.jsx("span",{children:"24h"})]})]}),r.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[r.jsx("input",{type:"checkbox",checked:gt,onChange:ht=>yt(ht.target.checked),className:"w-3.5 h-3.5 accent-amber-500 rounded cursor-pointer"}),r.jsx("span",{className:"text-[11px] text-bambu-gray",children:S("printers.drying.rotateTray")})]})]}),r.jsx("div",{className:"px-3 pb-3",children:r.jsx("button",{onClick:()=>{Re!==null&&cp.mutate({amsId:Re,temp:Ae,duration:Be,filament:Ue,rotateTray:gt})},disabled:cp.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:cp.isPending?S("printers.drying.startingDrying"):S("printers.drying.start")})})]})]})})()]})}function z7e({onClose:t,onAdd:e,existingSerials:n}){const{t:a}=kt(),[i,s]=v.useState({name:"",serial_number:"",ip_address:"",access_code:"",model:"",location:"",auto_archive:!0}),[o,l]=v.useState(!1),[c,d]=v.useState([]),[u,m]=v.useState(""),[p,f]=v.useState(!1),[b,w]=v.useState(!1),[g,x]=v.useState([]),[_,N]=v.useState(""),[C,P]=v.useState({scanned:0,total:0});v.useEffect(()=>{Md.getInfo().then(S=>{w(S.is_docker),S.subnets.length>0&&(x(S.subnets),N(S.subnets[0]))}).catch(()=>{})},[]);const T=c.filter(S=>!n.includes(S.serial)),A=async()=>{m(""),d([]),l(!0),f(!1),P({scanned:0,total:0});try{if(b){await Md.startSubnetScan(_);const S=setInterval(async()=>{try{const M=await Md.getScanStatus();P({scanned:M.scanned,total:M.total});const z=await Md.getDiscoveredPrinters();d(z),M.running||(clearInterval(S),l(!1),f(!0))}catch(M){console.error("Failed to get scan status:",M)}},500)}else{await Md.startDiscovery(10);const S=setInterval(async()=>{try{const M=await Md.getDiscoveredPrinters();d(M)}catch(M){console.error("Failed to get discovered printers:",M)}},1e3);setTimeout(async()=>{clearInterval(S);try{await Md.stopDiscovery()}catch{}l(!1),f(!0);try{const M=await Md.getDiscoveredPrinters();d(M)}catch(M){console.error("Failed to get final discovered printers:",M)}},1e4)}}catch(S){console.error("Failed to start discovery:",S),m(S instanceof Error?S.message:a("printers.discovery.failedToStart")),l(!1),f(!0)}},F=S=>{const M=S.serial.startsWith("unknown-")?"":S.serial;s({...i,name:S.name||"",serial_number:M,ip_address:S.ip_address,model:rw(S.model)}),d([])};return v.useEffect(()=>()=>{Md.stopDiscovery().catch(()=>{}),Md.stopSubnetScan().catch(()=>{})},[]),v.useEffect(()=>{const S=M=>{M.key==="Escape"&&t()};return window.addEventListener("keydown",S),()=>window.removeEventListener("keydown",S)},[t]),r.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:r.jsx(Ct,{className:"w-full max-w-md my-auto max-h-[calc(100vh-2rem)] overflow-y-auto",onClick:S=>S.stopPropagation(),children:r.jsxs(At,{children:[r.jsx("h2",{className:"text-xl font-semibold mb-4",children:a("printers.addPrinter")}),r.jsxs("div",{className:"mb-4 pb-4 border-b border-bambu-dark-tertiary",children:[b&&r.jsxs("div",{className:"mb-3",children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("printers.discovery.subnetToScan")}),g.length>0?r.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:S=>N(S.target.value),disabled:o,children:g.map(S=>r.jsx("option",{value:S,children:S},S))}):r.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:S=>N(S.target.value),placeholder:"192.168.1.0/24",disabled:o}),r.jsx("p",{className:"mt-1 text-xs text-bambu-gray",children:a("printers.discovery.dockerNote")})]}),r.jsx(Me,{type:"button",variant:"secondary",onClick:A,disabled:o,className:"w-full",children:o?r.jsxs(r.Fragment,{children:[r.jsx(ut,{className:"w-4 h-4 animate-spin"}),b&&C.total>0?a("printers.discovery.scanProgress",{scanned:C.scanned,total:C.total}):a("printers.discovery.scanning")]}):r.jsxs(r.Fragment,{children:[r.jsx(Sr,{className:"w-4 h-4"}),a(b?"printers.discovery.scanSubnet":"printers.discovery.discoverNetwork")]})}),u&&r.jsx("div",{className:"mt-2 text-sm text-red-400",children:u}),T.length>0&&r.jsx("div",{className:"mt-3 space-y-2 max-h-40 overflow-y-auto",children:T.map(S=>r.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(S),children:[r.jsxs("div",{className:"min-w-0 flex-1",children:[r.jsx("p",{className:"font-medium text-white text-sm truncate",children:S.name||S.serial}),r.jsxs("p",{className:"text-xs text-bambu-gray truncate",children:[rw(S.model)||a("printers.discovery.unknown")," • ",S.ip_address,S.serial.startsWith("unknown-")&&r.jsxs("span",{className:"text-yellow-500",children:[" • ",a("printers.discovery.serialRequired")]})]})]}),r.jsx(Rn,{className:"w-4 h-4 text-bambu-gray -rotate-90 flex-shrink-0 ml-2"})]},S.serial))}),o&&r.jsx("p",{className:"mt-2 text-sm text-bambu-gray text-center",children:a(b?"printers.discovery.scanningSubnet":"printers.discovery.scanningNetwork")}),p&&!o&&c.length===0&&r.jsx("p",{className:"mt-2 text-sm text-bambu-gray text-center",children:a(b?"printers.discovery.noPrintersFoundSubnet":"printers.discovery.noPrintersFoundNetwork")}),p&&!o&&c.length>0&&T.length===0&&r.jsx("p",{className:"mt-2 text-sm text-bambu-gray text-center",children:a("printers.discovery.allConfigured")})]}),r.jsxs("form",{onSubmit:S=>{S.preventDefault(),e(i)},className:"space-y-4",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("printers.name")}),r.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:S=>s({...i,name:S.target.value}),placeholder:a("printers.modal.myPrinter")})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("printers.ipAddress")}),r.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:S=>s({...i,ip_address:S.target.value}),placeholder:"192.168.1.100 or printer.local"})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("printers.serialNumber")}),r.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:S=>s({...i,serial_number:S.target.value}),placeholder:"01P00A000000000"})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("printers.accessCode")}),r.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:S=>s({...i,access_code:S.target.value}),placeholder:a("printers.modal.fromPrinterSettings")})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("printers.modal.modelOptional")}),r.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:S=>s({...i,model:S.target.value}),children:[r.jsx("option",{value:"",children:a("printers.modal.selectModel")}),r.jsxs("optgroup",{label:"H2 Series",children:[r.jsx("option",{value:"H2C",children:"H2C"}),r.jsx("option",{value:"H2D",children:"H2D"}),r.jsx("option",{value:"H2D Pro",children:"H2D Pro"}),r.jsx("option",{value:"H2S",children:"H2S"})]}),r.jsx("optgroup",{label:"X2 Series",children:r.jsx("option",{value:"X2D",children:"X2D"})}),r.jsxs("optgroup",{label:"X1 Series",children:[r.jsx("option",{value:"X1E",children:"X1E"}),r.jsx("option",{value:"X1C",children:"X1 Carbon"}),r.jsx("option",{value:"X1",children:"X1"})]}),r.jsxs("optgroup",{label:"P Series",children:[r.jsx("option",{value:"P2S",children:"P2S"}),r.jsx("option",{value:"P1S",children:"P1S"}),r.jsx("option",{value:"P1P",children:"P1P"})]}),r.jsxs("optgroup",{label:"A1 Series",children:[r.jsx("option",{value:"A1",children:"A1"}),r.jsx("option",{value:"A1 Mini",children:"A1 Mini"})]})]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("printers.modal.locationGroup")}),r.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:S=>s({...i,location:S.target.value}),placeholder:a("printers.modal.locationPlaceholder")}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:a("printers.locationHelp")})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("input",{type:"checkbox",id:"auto_archive",checked:i.auto_archive,onChange:S=>s({...i,auto_archive:S.target.checked}),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),r.jsx("label",{htmlFor:"auto_archive",className:"text-sm text-bambu-gray",children:a("printers.modal.autoArchiveLabel")})]}),r.jsxs("div",{className:"flex gap-3 pt-4",children:[r.jsx(Me,{type:"button",variant:"secondary",onClick:t,className:"flex-1",children:a("common.cancel")}),r.jsx(Me,{type:"submit",className:"flex-1",children:a("printers.addPrinter")})]})]})]})})})}function U7e({printer:t,firmwareInfo:e,onClose:n}){const{t:a}=kt(),i=en(),{showToast:s}=rn(),{hasPermission:o}=cr(),l=o("firmware:update"),[c,d]=v.useState(null),[u,m]=v.useState(!1),[p,f]=v.useState(null),[b,w]=v.useState(e.update_available?e.latest_version:null),{data:g,isLoading:x}=We({queryKey:["firmwarePrepare",t.id,b],queryFn:()=>fN.prepareUpload(t.id,b??void 0),staleTime:3e4,enabled:!!b&&l&&!u}),_=it({mutationFn:()=>fN.startUpload(t.id,b??void 0),onSuccess:()=>{m(!0);const C=setInterval(async()=>{try{const P=await fN.getUploadStatus(t.id);d(P),(P.status==="complete"||P.status==="error")&&(clearInterval(C),f(null),m(!1),P.status==="complete"&&(s(a("printers.firmwareModal.uploadedToast"),"success"),i.invalidateQueries({queryKey:["firmwareUpdate",t.id]})))}catch{}},2e3);f(C)},onError:C=>{s(a("printers.firmwareModal.uploadFailed",{error:C.message}),"error"),m(!1)}});v.useEffect(()=>()=>{p&&clearInterval(p)},[p]);const N=()=>{d(null),_.mutate()};return r.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",children:r.jsx(Ct,{className:"w-full max-w-md mx-4",children:r.jsxs(At,{children:[r.jsxs("div",{className:"flex items-start gap-3 mb-4",children:[r.jsx("div",{className:`p-2 rounded-full ${e.update_available?"bg-orange-500/20":"bg-status-ok/20"}`,children:e.update_available?r.jsx(Yr,{className:"w-5 h-5 text-orange-400"}):r.jsx(wr,{className:"w-5 h-5 text-status-ok"})}),r.jsxs("div",{className:"flex-1",children:[r.jsx("h3",{className:"text-lg font-semibold text-white",children:e.update_available?a("printers.firmwareModal.title"):a("printers.firmwareModal.titleUpToDate")}),r.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:t.name})]})]}),(()=>{const C=b?e.available_versions?.find(F=>F.version===b):null,P=b??e.latest_version,T=C?.release_notes??e.release_notes,A=!!P&&P!==e.current_version;return r.jsxs("div",{className:"bg-bambu-dark rounded-lg p-3 mb-4",children:[r.jsxs("div",{className:"flex justify-between items-center text-sm",children:[r.jsx("span",{className:"text-bambu-gray",children:a("printers.firmwareModal.currentVersion")}),r.jsx("span",{className:`font-mono ${A?"text-white":"text-status-ok"}`,children:e.current_version||a("common.unknown")})]}),A&&r.jsxs("div",{className:"flex justify-between items-center text-sm mt-1",children:[r.jsx("span",{className:"text-bambu-gray",children:a("printers.firmwareModal.latestVersion")}),r.jsx("span",{className:"text-orange-400 font-mono",children:P})]}),T&&r.jsxs("details",{className:"mt-3 text-sm",open:!A,children:[r.jsx("summary",{className:`cursor-pointer hover:underline ${A?"text-orange-400":"text-status-ok"}`,children:a("printers.firmwareModal.releaseNotes")}),r.jsx("div",{className:"mt-2 text-bambu-gray text-xs max-h-40 overflow-y-auto whitespace-pre-wrap",children:T})]},P??"none")]})})(),e.available_versions&&e.available_versions.length>0&&!u&&c?.status!=="complete"&&r.jsxs("div",{className:"mb-4",children:[r.jsx("div",{className:"text-xs text-bambu-gray mb-2",children:a("printers.firmwareModal.availableVersions")}),r.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(C=>{const P=e.current_version===C.version,T=b===C.version,A=e.current_version?Hve(C.version,e.current_version):0,F=P?a("printers.firmwareModal.currentBadge"):A>0?a("printers.firmwareModal.newerBadge"):a("printers.firmwareModal.olderBadge"),S=P?"text-bambu-gray":A>0?"text-orange-400":"text-blue-400";return r.jsxs("button",{type:"button",disabled:!C.file_available||!l||P,onClick:()=>w(C.version),className:`w-full text-left px-3 py-2 text-sm flex items-center justify-between gap-2 transition-colors ${T?"bg-orange-500/10":"hover:bg-bambu-dark"} ${!C.file_available||!l||P?"opacity-60 cursor-not-allowed":"cursor-pointer"}`,children:[r.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[r.jsx("span",{className:"font-mono text-white",children:C.version}),r.jsx("span",{className:`text-xs ${S}`,children:F})]}),r.jsx("span",{className:`text-xs px-2 py-0.5 rounded-full ${P?"bg-blue-500/15 text-blue-400 border border-blue-500/30":C.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:P?a("printers.firmwareModal.installed"):C.file_available?a("printers.firmwareModal.usable"):a("printers.firmwareModal.unavailable")})]},C.version)})})]}),b?x?r.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray text-sm mb-4",children:[r.jsx(ut,{className:"w-4 h-4 animate-spin"}),a("printers.firmwareModal.checkingPrereqs")]}):g&&!u&&!c?r.jsx("div",{className:"mb-4",children:g.can_proceed?r.jsxs("div",{className:"flex items-center gap-2 text-bambu-green text-sm",children:[r.jsx(Ni,{className:"w-4 h-4"}),a("printers.firmwareModal.sdCardReady")]}):r.jsx("div",{className:"space-y-1",children:g.errors.map((C,P)=>r.jsxs("div",{className:"flex items-center gap-2 text-red-400 text-sm",children:[r.jsx($a,{className:"w-4 h-4 flex-shrink-0"}),C]},P))})}):null:null,(u||c)&&c&&r.jsxs("div",{className:"mb-4",children:[r.jsxs("div",{className:"flex items-center justify-between text-sm mb-1",children:[r.jsx("span",{className:"text-bambu-gray capitalize",children:c.status}),r.jsxs("span",{className:"text-white",children:[c.progress,"%"]})]}),r.jsx("div",{className:"w-full bg-bambu-dark-tertiary rounded-full h-2",children:r.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}%`}})}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:c.message}),c.error&&r.jsx("p",{className:"text-xs text-red-400 mt-1",children:c.error})]}),c?.status==="complete"&&r.jsxs("div",{className:"bg-bambu-green/10 border border-bambu-green/30 rounded-lg p-3 mb-4",children:[r.jsx("p",{className:"text-sm text-bambu-green font-medium mb-2",children:a("printers.firmwareModal.uploadedSuccess")}),r.jsx("p",{className:"text-xs text-bambu-gray",children:a("printers.firmwareModal.applyInstructions")}),r.jsxs("ol",{className:"text-xs text-bambu-gray mt-1 list-decimal list-inside space-y-1",children:[r.jsx("li",{dangerouslySetInnerHTML:{__html:a("printers.firmwareModal.step1")}}),r.jsx("li",{dangerouslySetInnerHTML:{__html:a("printers.firmwareModal.step2")}}),r.jsx("li",{dangerouslySetInnerHTML:{__html:a("printers.firmwareModal.step3")}}),r.jsx("li",{children:a("printers.firmwareModal.step4")})]})]}),r.jsxs("div",{className:"flex gap-2 justify-end",children:[r.jsx(Me,{variant:"secondary",onClick:n,children:c?.status==="complete"?a("printers.firmwareModal.done"):a("common.cancel")}),g?.can_proceed&&!u&&c?.status!=="complete"&&l&&r.jsx(Me,{onClick:N,disabled:_.isPending,children:_.isPending?r.jsxs(r.Fragment,{children:[r.jsx(ut,{className:"w-4 h-4 animate-spin mr-2"}),a("printers.firmwareModal.starting")]}):r.jsxs(r.Fragment,{children:[r.jsx(Yr,{className:"w-4 h-4 mr-2"}),a("printers.firmwareModal.uploadFirmware")]})})]})]})})})}function B7e({printer:t,onClose:e}){const{t:n}=kt(),a=en(),{showToast:i}=rn(),[s,o]=v.useState({name:t.name,ip_address:t.ip_address,access_code:"",model:t.model||"",location:t.location||"",auto_archive:t.auto_archive}),l=it({mutationFn:d=>se.updatePrinter(t.id,d),onSuccess:()=>{a.invalidateQueries({queryKey:["printers"]}),a.invalidateQueries({queryKey:["printerStatus",t.id]}),e()},onError:d=>i(d.message||n("printers.toast.failedToUpdate"),"error")});v.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 r.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:r.jsx(Ct,{className:"w-full max-w-md my-auto max-h-[calc(100vh-2rem)] overflow-y-auto",onClick:d=>d.stopPropagation(),children:r.jsxs(At,{children:[r.jsx("h2",{className:"text-xl font-semibold mb-4",children:n("printers.editPrinter")}),r.jsxs("form",{onSubmit:c,className:"space-y-4",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.name")}),r.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")})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.ipAddress")}),r.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"})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.serialNumber")}),r.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}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:n("printers.serialCannotBeChanged")})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.accessCode")}),r.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")})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.model")}),r.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:[r.jsx("option",{value:"",children:n("printers.modal.selectModel")}),r.jsxs("optgroup",{label:"H2 Series",children:[r.jsx("option",{value:"H2C",children:"H2C"}),r.jsx("option",{value:"H2D",children:"H2D"}),r.jsx("option",{value:"H2D Pro",children:"H2D Pro"}),r.jsx("option",{value:"H2S",children:"H2S"})]}),r.jsx("optgroup",{label:"X2 Series",children:r.jsx("option",{value:"X2D",children:"X2D"})}),r.jsxs("optgroup",{label:"X1 Series",children:[r.jsx("option",{value:"X1E",children:"X1E"}),r.jsx("option",{value:"X1C",children:"X1 Carbon"}),r.jsx("option",{value:"X1",children:"X1"})]}),r.jsxs("optgroup",{label:"P Series",children:[r.jsx("option",{value:"P2S",children:"P2S"}),r.jsx("option",{value:"P1S",children:"P1S"}),r.jsx("option",{value:"P1P",children:"P1P"})]}),r.jsxs("optgroup",{label:"A1 Series",children:[r.jsx("option",{value:"A1",children:"A1"}),r.jsx("option",{value:"A1 Mini",children:"A1 Mini"})]})]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Location / Group"}),r.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")}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:n("printers.locationHelp")})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.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"}),r.jsx("label",{htmlFor:"edit_auto_archive",className:"text-sm text-bambu-gray",children:n("printers.modal.autoArchiveLabel")})]}),r.jsxs("div",{className:"flex gap-3 pt-4",children:[r.jsx(Me,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:n("common.cancel")}),r.jsx(Me,{type:"submit",className:"flex-1",disabled:l.isPending,children:l.isPending?n("common.saving"):n("printers.modal.saveChanges")})]})]})]})})})}function H7e(t){const{data:e}=We({queryKey:["printerStatus",t],queryFn:()=>se.getPrinterStatus(t),refetchInterval:3e4});return!e?.connected}function q7e({printer:t,plug:e,onPowerOn:n,isPowering:a}){const i=H7e(t.id),{data:s}=We({queryKey:["smartPlugStatus",e.id],queryFn:()=>se.getSmartPlugStatus(e.id),refetchInterval:1e4});return i?r.jsxs("div",{className:"flex items-center justify-between px-3 py-2 hover:bg-gray-100 dark:hover:bg-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[r.jsx("span",{className:"text-sm text-gray-900 dark:text-white truncate",children:t.name}),s&&r.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||"?"})]}),r.jsxs("button",{onClick:()=>n(e.id),disabled:a||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:[r.jsx(wu,{className:"w-3 h-3"}),a?"...":"On"]})]}):null}function $7e(){const{t}=kt(),[e,n]=v.useState(!1),[a,i]=v.useState(()=>localStorage.getItem("hideDisconnectedPrinters")==="true"),[s,o]=v.useState(!1),[l,c]=v.useState(null),[d,u]=v.useState(()=>localStorage.getItem("printerSortBy")||"name"),[m,p]=v.useState(()=>localStorage.getItem("printerSortAsc")!=="false"),[f,b]=v.useState(()=>{const pt=localStorage.getItem("printerCardSize");return pt?parseInt(pt,10):2}),w=f===1?"compact":"expanded",[g,x]=v.useState(""),[_,N]=v.useState("all"),[C,P]=v.useState("all"),[T,A]=v.useState(0),[F,S]=v.useState(()=>{try{const pt=localStorage.getItem("printerCollapsedSections");return pt?JSON.parse(pt):{}}catch{return{}}}),M=en(),{showToast:z}=rn(),{hasPermission:I}=cr(),[H,L]=v.useState(()=>{const pt=localStorage.getItem("openEmbeddedCameras");if(pt)try{const at=JSON.parse(pt);return new Map(at.map(vt=>[vt.id,vt]))}catch{return new Map}return new Map});v.useEffect(()=>{const pt=Array.from(H.values());pt.length>0?localStorage.setItem("openEmbeddedCameras",JSON.stringify(pt)):localStorage.removeItem("openEmbeddedCameras")},[H]);const{data:Z,isLoading:re}=We({queryKey:["printers"],queryFn:se.getPrinters}),{data:J}=We({queryKey:["settings"],queryFn:se.getSettings}),de=v.useMemo(()=>{if(J?.drying_presets)try{const pt=JSON.parse(J.drying_presets);if(typeof pt=="object"&&pt!==null&&Object.keys(pt).length>0)return{...aI,...pt}}catch{}return aI},[J?.drying_presets]);v.useEffect(()=>{J?.camera_view_mode==="window"&&H.size>0&&L(new Map)},[J?.camera_view_mode,H.size]);const{data:me}=We({queryKey:["smart-plugs"],queryFn:se.getSmartPlugs}),{data:ue}=We({queryKey:["maintenanceOverview"],queryFn:se.getMaintenanceOverview,staleTime:60*1e3}),{data:W}=We({queryKey:["spoolman-status"],queryFn:se.getSpoolmanStatus,staleTime:60*1e3}),ae=W?.enabled&&W?.connected,{data:pe}=We({queryKey:["spoolman-settings"],queryFn:se.getSpoolmanSettings,enabled:!!ae,staleTime:60*1e3}),ye=pe?.spoolman_sync_mode,{data:Te}=We({queryKey:["unlinked-spools"],queryFn:se.getUnlinkedSpools,enabled:!!ae,staleTime:30*1e3}),$=Te&&Te.length>0,{data:K}=We({queryKey:["linked-spools"],queryFn:se.getLinkedSpools,enabled:!!ae,staleTime:30*1e3}),D=K?.linked,{data:j}=We({queryKey:["spool-assignments"],queryFn:()=>se.getAssignments(),enabled:I("inventory:view_assignments"),staleTime:30*1e3}),B=it({mutationFn:({printerId:pt,amsId:at,trayId:vt})=>se.unassignSpool(pt,at,vt),onSuccess:()=>{M.invalidateQueries({queryKey:["spool-assignments"]})}}),{data:X,isLoading:O}=We({queryKey:["spoolman-inventory-spools"],queryFn:()=>se.getSpoolmanInventorySpools(!1),enabled:!!ae,staleTime:30*1e3}),{data:ie,isLoading:U}=We({queryKey:["spoolman-slot-assignments"],queryFn:()=>se.getSpoolmanSlotAssignments(),enabled:!!ae,staleTime:30*1e3}),G=it({mutationFn:pt=>se.unassignSpoolmanSlot(pt),onSuccess:()=>{M.invalidateQueries({queryKey:["spoolman-inventory-spools"]}),M.invalidateQueries({queryKey:["spoolman-slot-assignments"]})}}),Y=(pt,at,vt)=>j?.find(_t=>_t.printer_id===pt&&_t.ams_id===Number(at)&&_t.tray_id===Number(vt)),Q=ue?.reduce((pt,at)=>(pt[at.printer_id]={due_count:at.due_count,warning_count:at.warning_count,total_print_hours:at.total_print_hours},pt),{})||{},oe=me?.reduce((pt,at)=>(at.printer_id&&(pt[at.printer_id]=at),pt),{})||{},ee=it({mutationFn:se.createPrinter,onSuccess:()=>{M.invalidateQueries({queryKey:["printers"]}),M.invalidateQueries({queryKey:["maintenanceOverview"]}),n(!1)},onError:pt=>z(pt.message||t("printers.toast.failedToAdd"),"error")}),ge=it({mutationFn:pt=>se.controlSmartPlug(pt,"on"),onSuccess:()=>{M.invalidateQueries({queryKey:["smart-plugs"]}),c(null)},onError:()=>{c(null)}}),[ce,le]=v.useState(new Set),[q,R]=v.useState(!1),[ne,xe]=v.useState(null),[we,Ne]=v.useState(!1),ve=q||ce.size>0,be=v.useCallback(pt=>{le(at=>{const vt=new Set(at);return vt.has(pt)?vt.delete(pt):vt.add(pt),vt})},[]),Ee=v.useCallback(()=>{le(new Set),R(!1)},[]);v.useEffect(()=>{const pt=at=>{at.key==="Escape"&&ve&&Ee()};return window.addEventListener("keydown",pt),()=>window.removeEventListener("keydown",pt)},[ve,Ee]);const ze=v.useCallback(async pt=>{Ne(!0);const vt=Array.from(ce).filter(Ve=>{const Je=M.getQueryData(["printerStatus",Ve]);if(!Je?.connected)return!1;switch(pt){case"stop":return Je.state==="RUNNING"||Je.state==="PAUSE";case"pause":return Je.state==="RUNNING";case"resume":return Je.state==="PAUSE";case"clearPlate":return!!Je.awaiting_plate_clear;case"clearHMS":return Je.hms_errors&&Em(Je.hms_errors).length>0;default:return!1}});if(vt.length===0){z(t("printers.bulk.noneApplicable"),"error"),Ne(!1),xe(null);return}const _t={stop:se.stopPrint,pause:se.pausePrint,resume:se.resumePrint,clearPlate:se.clearPlate,clearHMS:se.clearHMSErrors}[pt],Dt=await Promise.allSettled(vt.map(Ve=>_t(Ve))),De=Dt.filter(Ve=>Ve.status==="fulfilled").length,je=Dt.filter(Ve=>Ve.status==="rejected").length;je===0?z(t("printers.bulk.success",{action:t(`printers.bulk.actions.${pt}`),count:De})):z(t("printers.bulk.partial",{succeeded:De,failed:je}),"error"),vt.forEach(Ve=>{M.invalidateQueries({queryKey:["printerStatus",Ve]})}),Ne(!1),xe(null)},[ce,M,z,t]),_e=v.useCallback(pt=>{pt==="stop"||pt==="pause"||pt==="clearPlate"?xe(pt):ze(pt)},[ze]),Oe=()=>{const pt=!a;i(pt),localStorage.setItem("hideDisconnectedPrinters",String(pt))},Ie=pt=>{u(pt),localStorage.setItem("printerSortBy",pt)},Ke=()=>{const pt=!m;p(pt),localStorage.setItem("printerSortAsc",String(pt))},rt=()=>{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"}},st=["S","M","L","XL"];v.useEffect(()=>M.getQueryCache().subscribe(at=>{at.type==="updated"&&Array.isArray(at.query.queryKey)&&at.query.queryKey[0]==="printerStatus"&&A(vt=>vt+1)}),[M]);const Re=v.useMemo(()=>{if(!Z)return[];let pt=Z;if(g.trim()){const at=g.trim().toLowerCase();pt=pt.filter(vt=>vt.name.toLowerCase().includes(at)||(vt.model||"").toLowerCase().includes(at)||(vt.location||"").toLowerCase().includes(at)||(vt.serial_number||"").toLowerCase().includes(at))}return C!=="all"&&(pt=pt.filter(at=>(at.location||"")===C)),_!=="all"&&(pt=pt.filter(at=>{const vt=M.getQueryData(["printerStatus",at.id]);if(!vt?.connected)return _==="offline";const _t=vt.hms_errors?Em(vt.hms_errors):[];switch(_){case"printing":return vt.state==="RUNNING";case"paused":return vt.state==="PAUSE";case"finished":return vt.state==="FINISH";case"error":return vt.state==="FAILED"||_t.length>0;case"idle":return vt.state!=="RUNNING"&&vt.state!=="PAUSE"&&vt.state!=="FINISH"&&vt.state!=="FAILED"&&_t.length===0;case"offline":return!1;default:return!0}})),pt},[Z,g,_,C,M,T]),tt=v.useMemo(()=>Z?[...new Set(Z.map(pt=>pt.location||"").filter(Boolean))].sort():[],[Z]),Ce=v.useMemo(()=>{const pt=[...Re];switch(d){case"name":pt.sort((at,vt)=>at.name.localeCompare(vt.name));break;case"model":pt.sort((at,vt)=>(at.model||"").localeCompare(vt.model||""));break;case"location":pt.sort((at,vt)=>{const _t=at.location||"",Dt=vt.location||"";return!_t&&Dt?1:_t&&!Dt?-1:_t.localeCompare(Dt)||at.name.localeCompare(vt.name)});break;case"status":pt.sort((at,vt)=>{const _t=M.getQueryData(["printerStatus",at.id]),Dt=M.getQueryData(["printerStatus",vt.id]),De=je=>je?.connected?(je.hms_errors?Em(je.hms_errors):[]).length>0?0:je.state==="RUNNING"?1:2:3;return De(_t)-De(Dt)});break}return m||pt.reverse(),pt},[Re,d,m,M]),Xe=v.useCallback(()=>{le(new Set(Ce.map(pt=>pt.id))),R(!0)},[Ce]),Ue=v.useCallback(pt=>{le(at=>{const vt=new Set(at);return Ce.forEach(_t=>{const Dt=M.getQueryData(["printerStatus",_t.id]);GK(Dt)===pt&&vt.add(_t.id)}),vt}),R(!0)},[Ce,M]),fe=v.useCallback(pt=>{le(at=>{const vt=new Set(at);return Ce.filter(_t=>(_t.location||"")===pt).forEach(_t=>vt.add(_t.id)),vt}),R(!0)},[Ce]),Ae=v.useCallback(pt=>{le(at=>{const vt=new Set(at);return Ce.filter(_t=>(_t.model||"Unknown")===pt).forEach(_t=>vt.add(_t.id)),vt}),R(!0)},[Ce]),$e=v.useCallback(pt=>{S(at=>{const vt={...at,[pt]:!at[pt]};try{localStorage.setItem("printerCollapsedSections",JSON.stringify(vt))}catch{}return vt})},[]),Be=v.useMemo(()=>{if(d==="name")return null;const pt={};return d==="location"?Ce.forEach(at=>{const vt=at.location||"Ungrouped";pt[vt]||(pt[vt]=[]),pt[vt].push(at)}):d==="model"?Ce.forEach(at=>{const vt=at.model||"Unknown";pt[vt]||(pt[vt]=[]),pt[vt].push(at)}):d==="status"&&Ce.forEach(at=>{const vt=M.getQueryData(["printerStatus",at.id]),_t=GK(vt);pt[_t]||(pt[_t]=[]),pt[_t].push(at)}),pt},[d,Ce,M,T]),nt=v.useRef(null),gt=v.useRef(null),yt=v.useRef(0),[ot,Ht]=v.useState(!1),Kt=v.useCallback(()=>{const pt=nt.current;if(!pt)return;const at=gt.current?.offsetWidth;at&&(yt.current=at);const Dt=yt.current>0&&pt.clientWidthDe===Dt?De:Dt)},[]),Zt=Object.keys(oe).length;v.useLayoutEffect(()=>{Kt();const pt=nt.current;if(!pt)return;if(typeof ResizeObserver>"u")return window.addEventListener("resize",Kt),()=>window.removeEventListener("resize",Kt);const at=new ResizeObserver(()=>Kt());return at.observe(pt),window.addEventListener("resize",Kt),()=>{at.disconnect(),window.removeEventListener("resize",Kt)}},[Kt,Z?.length,tt.length,a,Zt]);const Yt=(pt=!1)=>r.jsxs(r.Fragment,{children:[Z&&Z.length>0&&r.jsx(h3,{value:_,onChange:N,fullWidth:pt,options:[{value:"all",label:t("printers.filter.allStatuses")},{value:"printing",label:t("printers.status.printing")},{value:"paused",label:t("printers.status.paused")},{value:"idle",label:t("printers.status.idle")},{value:"finished",label:t("printers.status.finished")},{value:"error",label:t("printers.status.error")},{value:"offline",label:t("printers.status.offline")}]}),Z&&Z.length>0&&tt.length>0&&r.jsx(h3,{value:C,onChange:P,fullWidth:pt,options:[{value:"all",label:t("printers.filter.allLocations")},...tt.map(at=>({value:at,label:at}))]}),r.jsx("button",{type:"button",onClick:Oe,"aria-pressed":a,className:`h-8 px-2 rounded-lg border text-sm font-medium transition-colors ${pt?"w-full":""} ${a?"bg-bambu-green border-bambu-green text-white":"bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary"}`,children:t("printers.hideOffline")})]}),gn=(pt=!1)=>r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:`flex items-center gap-1 ${pt?"w-full":""}`,children:[r.jsx(h3,{value:d,onChange:Ie,fullWidth:pt,options:[{value:"name",label:t("printers.sort.name")},{value:"status",label:t("printers.sort.status")},{value:"model",label:t("printers.sort.model")},{value:"location",label:t("printers.sort.location")}]}),r.jsx("button",{onClick:Ke,className:"h-8 shrink-0 px-2 rounded-lg border bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary transition-colors flex items-center justify-center",title:t(m?"printers.sort.descending":"printers.sort.ascending"),children:m?r.jsx(Hm,{className:"w-4 h-4 text-white"}):r.jsx(Bh,{className:"w-4 h-4 text-white"})})]}),r.jsx("div",{className:`flex h-8 items-center bg-bambu-dark rounded-lg border border-bambu-dark-tertiary ${pt?"w-full":""}`,children:st.map((at,vt)=>{const _t=vt+1,Dt=f===_t;return r.jsx("button",{onClick:()=>{b(_t),localStorage.setItem("printerCardSize",String(_t))},className:`h-full px-2 text-xs font-medium transition-colors ${pt?"flex-1":""} ${vt===0?"rounded-l-lg":""} ${vt===st.length-1?"rounded-r-lg":""} ${Dt?"bg-bambu-green text-white":"text-white hover:bg-bambu-dark-tertiary"}`,title:t(at==="S"?"printers.cardSize.small":at==="M"?"printers.cardSize.medium":at==="L"?"printers.cardSize.large":"printers.cardSize.extraLarge"),children:at},at)})})]}),ln=(pt=!1)=>r.jsxs(r.Fragment,{children:[r.jsxs("button",{onClick:()=>{ve?Ee():R(!0)},className:`h-8 px-2 rounded-lg border transition-colors ${pt?"w-full justify-center gap-1.5 text-sm font-medium flex items-center":""} ${ve?"bg-bambu-green border-bambu-green text-white":"bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary"}`,title:t("printers.bulk.select"),disabled:!I("printers:control"),children:[r.jsx(bs,{className:"w-4 h-4"}),pt&&r.jsx("span",{children:t("printers.bulk.select")})]}),a&&Object.keys(oe).length>0&&r.jsxs("div",{className:`relative ${pt?"w-full":""}`,children:[r.jsxs("button",{onClick:()=>o(!s),className:`h-8 flex items-center gap-1.5 px-2 text-sm rounded-lg border transition-colors ${pt?"w-full justify-between bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary hover:text-white":"bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary"}`,children:[r.jsxs("span",{className:"flex items-center gap-1.5",children:[r.jsx(wu,{className:"w-4 h-4"}),t("printers.powerOn")]}),r.jsx(Rn,{className:`w-3 h-3 transition-transform ${s?"rotate-180":""}`})]}),s&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>o(!1)}),r.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:[r.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")}),Z?.filter(at=>oe[at.id]).map(at=>r.jsx(q7e,{printer:at,plug:oe[at.id],onPowerOn:vt=>{c(vt),ge.mutate(vt)},isPowering:l===oe[at.id]?.id},at.id)),Z?.filter(at=>oe[at.id]).length===0&&r.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:"No printers with smart plugs"})]})]})]}),r.jsxs(Me,{onClick:()=>n(!0),disabled:!I("printers:create"),title:I("printers:create")?void 0:t("printers.permission.noAdd"),className:`!h-8 !min-h-8 px-2 py-0 ${pt?"w-full":""}`,children:[r.jsx(ar,{className:"w-4 h-4"}),t("printers.addPrinter")]})]});return r.jsxs("div",{className:"p-4 md:p-8",children:[r.jsxs("div",{className:"space-y-3 mb-6",children:[r.jsxs("div",{children:[r.jsxs("h1",{className:"text-2xl font-bold text-white flex items-center gap-3",children:[r.jsx(pr,{className:"w-7 h-7 text-bambu-green"}),t("printers.title")]}),r.jsx(I7e,{printers:Z})]}),r.jsxs("div",{ref:nt,className:"relative flex items-center gap-2",children:[Z&&Z.length>0&&r.jsxs("div",{className:"relative min-w-0 flex-1",children:[r.jsx(Sr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50"}),r.jsx("input",{type:"search",name:"printer-search",autoComplete:"off","data-1p-ignore":!0,"data-lpignore":"true",value:g,onChange:pt=>x(pt.target.value),placeholder:t("printers.search"),"aria-label":t("printers.search"),className:"w-full h-8 pl-9 pr-8 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"}),g&&r.jsx("button",{type:"button","aria-label":t("common.clear"),onClick:()=>x(""),className:"absolute right-3 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white",children:r.jsx(Bt,{className:"w-4 h-4"})})]}),r.jsxs("div",{ref:gt,"aria-hidden":ot,inert:ot,className:`${ot?"absolute -left-[9999px] top-0 flex w-max pointer-events-none opacity-0":"flex"} ml-auto items-center justify-end gap-2 flex-nowrap [&>*]:shrink-0`,children:[r.jsx("div",{className:"h-6 w-px bg-bambu-dark-tertiary"}),r.jsx("div",{className:"flex items-center gap-2",children:Yt()}),r.jsx("div",{className:"h-6 w-px bg-bambu-dark-tertiary"}),r.jsx("div",{className:"flex items-center gap-2",children:gn()}),r.jsx("div",{className:"h-6 w-px bg-bambu-dark-tertiary"}),r.jsx("div",{className:"flex items-center gap-2",children:ln()})]}),ot&&r.jsxs("div",{className:"ml-auto flex items-center justify-end gap-1",children:[r.jsx(f3,{label:t("printers.toolbar.filters","Filters"),icon:r.jsx(_S,{className:"w-4 h-4"}),children:r.jsx("div",{className:"flex w-48 flex-col gap-2",children:Yt(!0)})}),r.jsx(f3,{label:t("printers.toolbar.view","View"),icon:r.jsx(xye,{className:"w-4 h-4"}),children:r.jsx("div",{className:"flex w-48 flex-col gap-2",children:gn(!0)})}),r.jsx(f3,{label:t("printers.toolbar.actions","Actions"),icon:r.jsx(qge,{className:"w-4 h-4"}),children:r.jsx("div",{className:"flex w-48 flex-col gap-2",children:ln(!0)})})]})]})]}),re?r.jsx("div",{className:"text-center py-12 text-bambu-gray",children:t("common.loading")}):Z?.length===0?r.jsx(Ct,{children:r.jsxs(At,{className:"text-center py-12",children:[r.jsx("p",{className:"text-bambu-gray mb-4",children:t("printers.noPrintersConfigured")}),r.jsxs(Me,{onClick:()=>n(!0),disabled:!I("printers:create"),title:I("printers:create")?void 0:t("printers.permission.noAdd"),children:[r.jsx(ar,{className:"w-4 h-4"}),t("printers.addPrinter")]})]})}):Ce.length===0&&(g.trim()||_!=="all"||C!=="all")?r.jsx(Ct,{children:r.jsx(At,{className:"text-center py-12",children:r.jsx("p",{className:"text-bambu-gray",children:t("printers.noSearchResults")})})}):Be?r.jsx("div",{className:"space-y-6",children:(()=>{const pt=d==="status"?O7e.filter(at=>Be[at]?.length>0):Object.keys(Be);return m?pt:[...pt].reverse()})().map(pt=>{const at=Be[pt],vt=`${d}:${pt}`,_t=!F[vt],Dt=d==="status"&&VK[pt]?.dot||"bg-bambu-green",De=d==="status"?t(VK[pt]?.labelKey||pt):pt;return r.jsx(s5,{open:_t,onToggle:()=>$e(vt),summaryClassName:"py-1",summary:r.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[r.jsx("span",{className:`w-2 h-2 rounded-full ${Dt}`}),De,r.jsxs("span",{className:"text-sm font-normal text-bambu-gray",children:["(",at.length,")"]}),ve&&r.jsx("button",{onClick:je=>{je.stopPropagation(),d==="location"?fe(pt==="Ungrouped"?"":pt):d==="status"?Ue(pt):d==="model"&&Ae(pt)},className:"text-xs text-bambu-green hover:text-bambu-green-light transition-colors ml-1",children:t("printers.bulk.selectAll")})]}),children:r.jsx("div",{className:`grid gap-4 ${f>=3?"gap-6":""} ${rt()}`,children:at.map(je=>r.jsx(KK,{printer:je,hideIfDisconnected:a,maintenanceInfo:Q[je.id],viewMode:w,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:ae,hasUnlinkedSpools:$,linkedSpools:D,spoolmanUrl:W?.url,spoolmanSyncMode:ye,onGetAssignment:Y,onUnassignSpool:(Ve,Je,Le)=>B.mutate({printerId:Ve,amsId:Je,trayId:Le}),spoolmanSpools:X,spoolmanSlotAssignments:ie,spoolmanLoading:O||U,onUnassignSpoolmanSpool:Ve=>G.mutate(Ve),timeFormat:J?.time_format||"system",cameraViewMode:J?.camera_view_mode||"window",onOpenEmbeddedCamera:(Ve,Je)=>L(Le=>new Map(Le).set(Ve,{id:Ve,name:Je})),checkPrinterFirmware:J?.check_printer_firmware!==!1,dryingPresets:de,requirePlateClear:J?.require_plate_clear===!0,selectionMode:ve,isSelected:ce.has(je.id),onToggleSelect:be},je.id))})},pt)})}):r.jsx("div",{className:`grid gap-4 ${f>=3?"gap-6":""} ${rt()}`,children:Ce.map(pt=>r.jsx(KK,{printer:pt,hideIfDisconnected:a,maintenanceInfo:Q[pt.id],viewMode:w,cardSize:f,spoolmanEnabled:ae,hasUnlinkedSpools:$,linkedSpools:D,spoolmanUrl:W?.url,spoolmanSyncMode:ye,onGetAssignment:Y,onUnassignSpool:(at,vt,_t)=>B.mutate({printerId:at,amsId:vt,trayId:_t}),spoolmanSpools:X,spoolmanSlotAssignments:ie,spoolmanLoading:O||U,onUnassignSpoolmanSpool:at=>G.mutate(at),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:(at,vt)=>L(_t=>new Map(_t).set(at,{id:at,name:vt})),checkPrinterFirmware:J?.check_printer_firmware!==!1,dryingPresets:de,requirePlateClear:J?.require_plate_clear===!0,selectionMode:ve,isSelected:ce.has(pt.id),onToggleSelect:be},pt.id))}),e&&r.jsx(z7e,{onClose:()=>n(!1),onAdd:pt=>ee.mutate(pt),existingSerials:Z?.map(pt=>pt.serial_number)||[]}),ve&&Z&&r.jsx(Wve,{selectedIds:ce,printers:Z,onClose:Ee,onSelectAll:Xe,onSelectByLocation:fe,onSelectByState:Ue,onAction:_e,actionPending:we}),ne==="stop"&&r.jsx(vn,{title:t("printers.bulk.confirm.stopTitle",{count:ce.size}),message:t("printers.bulk.confirm.stopMessage",{count:ce.size}),confirmText:t("printers.bulk.confirm.stopButton"),variant:"danger",isLoading:we,onConfirm:()=>ze("stop"),onCancel:()=>xe(null)}),ne==="pause"&&r.jsx(vn,{title:t("printers.bulk.confirm.pauseTitle",{count:ce.size}),message:t("printers.bulk.confirm.pauseMessage",{count:ce.size}),confirmText:t("printers.bulk.confirm.pauseButton"),isLoading:we,onConfirm:()=>ze("pause"),onCancel:()=>xe(null)}),ne==="clearPlate"&&r.jsx(vn,{title:t("printers.bulk.confirm.clearPlateTitle",{count:ce.size}),message:t("printers.bulk.confirm.clearPlateMessage",{count:ce.size}),confirmText:t("printers.bulk.confirm.clearPlateButton"),isLoading:we,onConfirm:()=>ze("clearPlate"),onCancel:()=>xe(null)}),Array.from(H.values()).map((pt,at)=>r.jsx(KEe,{printerId:pt.id,printerName:pt.name,viewerIndex:at,onClose:()=>L(vt=>{const _t=new Map(vt);return _t.delete(pt.id),_t})},pt.id))]})}const Gie=v.createContext(null),V7e=1500,G7e=1e3,b3=t=>`slice-job-${t}`;function q1(t){try{return decodeURIComponent(t)}catch{return t}}function W7e(t){const e=Math.max(0,Math.floor(t));if(e<60)return`${e}s`;const n=Math.floor(e/60),a=e%60;if(n<60)return`${n}m ${a}s`;const i=Math.floor(n/60),s=n%60;return`${i}h ${s}m`}function K7e({children:t}){const{t:e}=kt(),{showToast:n,showPersistentToast:a,dismissToast:i}=rn(),s=en(),[o,l]=v.useState([]),c=v.useRef([]);c.current=o;const d=v.useRef(new Map),u=v.useRef(new Map),m=v.useRef(new Map),p=v.useCallback(w=>{const g=d.current.get(w.id);if(g==null)return;const x=(Date.now()-g)/1e3,_=u.current.get(w.id)??"pending",N=W7e(x),C=m.current.get(w.id)??null,P=C&&C.stage&&C.total_percent>0;if(_==="running"&&P){a(b3(w.id),e("slice.runningWithProgress","{{name}} — {{stage}} ({{percent}}%) — {{elapsed}}",{name:q1(w.sourceName),stage:C.stage,percent:Math.min(100,Math.max(0,Math.round(C.total_percent))),elapsed:N}),"loading");return}const T=_==="pending"?"slice.queuedToast":"slice.runningToast",A=_==="pending"?"Queued: {{name}} — {{elapsed}}":"Slicing {{name}} — {{elapsed}}";a(b3(w.id),e(T,A,{name:q1(w.sourceName),elapsed:N}),"loading")},[a,e]),f=v.useCallback((w,g,x)=>{l(_=>_.some(N=>N.id===w)?_:[..._,{id:w,kind:g,sourceName:x}]),d.current.set(w,Date.now()),u.current.set(w,"pending"),m.current.set(w,null),p({id:w,kind:g,sourceName:x})},[p]),b=v.useCallback((w,g)=>{if(l(x=>x.filter(_=>_.id!==w.id)),d.current.delete(w.id),u.current.delete(w.id),m.current.delete(w.id),i(b3(w.id)),g.status==="completed")n(e("slice.completedToast","Sliced {{name}}",{name:q1(w.sourceName)}),"success");else if(g.status==="failed"){const x=g.error_detail||e("slice.failed");n(e("slice.failedToast","Slicing {{name}} failed: {{detail}}",{name:q1(w.sourceName),detail:x}),"error")}s.invalidateQueries({queryKey:["library-files"]}),s.invalidateQueries({queryKey:["archives"]})},[i,s,n,e]);return v.useEffect(()=>{if(o.length===0)return;let w=!1;const g=setInterval(async()=>{if(w)return;const x=[...c.current];for(const _ of x)try{const N=await se.getSliceJob(_.id);u.current.set(_.id,N.status),N.progress&&m.current.set(_.id,N.progress),(N.status==="completed"||N.status==="failed")&&b(_,N)}catch{}},V7e);return()=>{w=!0,clearInterval(g)}},[o.length,b]),v.useEffect(()=>{if(o.length===0)return;const w=setInterval(()=>{for(const g of c.current)p(g)},G7e);return()=>clearInterval(w)},[o.length,p]),r.jsx(Gie.Provider,{value:{trackJob:f,activeJobs:o},children:t})}function Y7e(){const t=v.useContext(Gie);if(!t)throw new Error("useSliceJobTracker must be used inside SliceJobTrackerProvider");return t}function o5({plates:t,onSelect:e,onClose:n}){const{t:a}=kt();return r.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4",onClick:n,children:r.jsxs("div",{className:"w-full max-w-3xl max-h-[85vh] flex flex-col rounded-lg bg-bambu-dark-secondary border border-bambu-dark-tertiary/60",onClick:i=>i.stopPropagation(),children:[r.jsxs("div",{className:"flex-shrink-0 flex items-start justify-between gap-3 px-4 pt-4 pb-3 border-b border-bambu-dark-tertiary/40",children:[r.jsxs("div",{className:"min-w-0",children:[r.jsx("h3",{className:"text-white font-medium",children:a("archives.platePicker.title")}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:a("archives.platePicker.hint")})]}),r.jsx("button",{onClick:n,className:"flex-shrink-0 text-bambu-gray hover:text-white transition-colors","aria-label":a("common.close","Close"),children:r.jsx(Bt,{className:"w-5 h-5"})})]}),r.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:r.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:t.map(i=>r.jsxs("button",{type:"button",onClick:()=>e(i.index),className:"flex items-center gap-2 p-2 rounded-lg border border-bambu-dark-tertiary bg-bambu-dark hover:border-bambu-gray transition-colors text-left",children:[i.has_thumbnail&&i.thumbnail_url!=null?r.jsx("img",{src:La(i.thumbnail_url),alt:`Plate ${i.index}`,className:"w-12 h-12 rounded object-cover bg-bambu-dark-tertiary flex-shrink-0"}):r.jsx("div",{className:"w-12 h-12 rounded bg-bambu-dark-tertiary flex items-center justify-center flex-shrink-0",children:r.jsx(oa,{className:"w-5 h-5 text-bambu-gray"})}),r.jsxs("div",{className:"min-w-0 flex-1",children:[r.jsx("p",{className:"text-sm text-white font-medium truncate",children:i.name?`${a("archives.platePicker.plateLabel",{index:i.index})} — ${i.name}`:a("archives.platePicker.plateLabel",{index:i.index})}),r.jsxs("p",{className:"text-xs text-bambu-gray truncate",children:[i.objects.length>0?i.objects.slice(0,3).join(", ")+(i.objects.length>3?"…":""):i.object_count!=null&&i.object_count>0?a("archives.platePicker.objectCount",{count:i.object_count}):`${i.filaments.length} filament${i.filaments.length!==1?"s":""}`,i.print_time_seconds!=null?` • ${ds(i.print_time_seconds)}`:""]})]})]},i.index))})})]})})}const Wie=["local","cloud","standard"];function iI(t,e){for(const n of Wie){const a=t[n][e];if(a.length>0)return{source:a[0].source,id:a[0].id}}return null}const X7e={local:1.5,cloud:1,standard:.5};function Q7e(t,e){const n=e.type.trim().toUpperCase(),a=Oa(e.color);let i=null;for(const s of Wie)for(const o of t[s].filament){let l=0;const c=(o.filament_type??"").trim().toUpperCase(),d=Oa(o.filament_colour??"");n&&c&&n===c&&(l+=10),a&&d&&(d===a?l+=5:ld(o.filament_colour??"",e.color)&&(l+=2)),l+=X7e[s],(i==null||l>i.score)&&(i={ref:{source:o.source,id:o.id},score:l})}return i==null?iI(t,"filament"):i.ref}function Z7e(t){return t?`${t.source}:${t.id}`:""}function J7e(t){if(!t)return null;const e=t.indexOf(":");if(e<0)return null;const n=t.slice(0,e),a=t.slice(e+1);return n!=="cloud"&&n!=="local"&&n!=="standard"?null:{source:n,id:a}}function e9e({requestId:t,sourceName:e}){const{t:n}=kt(),{showPersistentToast:a,dismissToast:i}=rn(),[s,o]=v.useState(0),[l,c]=v.useState(null);let d=e;try{d=decodeURIComponent(e)}catch{}v.useEffect(()=>{const b=Date.now(),w=setInterval(()=>o(Math.floor((Date.now()-b)/1e3)),1e3);return()=>clearInterval(w)},[]),v.useEffect(()=>{let b=!1;const w=setInterval(async()=>{if(b)return;const g=await se.getPreviewSliceProgress(t);!b&&g&&c(g)},1e3);return()=>{b=!0,clearInterval(w)}},[t]);const u=`slice-preview-${t}`;v.useEffect(()=>{const b=l&&l.stage&&l.total_percent>0,w=t9e(s);return b?a(u,n("slice.previewWithProgress","Analyzing {{name}} — {{stage}} ({{percent}}%) — {{elapsed}}",{name:d,stage:l.stage,percent:Math.min(100,Math.max(0,Math.round(l.total_percent))),elapsed:w}),"loading"):a(u,n("slice.previewToast","Analyzing {{name}} — {{elapsed}}",{name:d,elapsed:w}),"loading"),()=>{i(u)}},[s,l,d,a,i,n,u]);const m=l?.stage,p=l?.total_percent,f=m&&typeof p=="number"&&p>0?`${m} (${Math.min(100,Math.max(0,Math.round(p)))}%)`:n("slice.analyzingPlateFilaments","Analyzing plate filaments…");return r.jsxs("div",{className:"flex flex-col gap-1 text-bambu-gray text-sm py-2",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(ut,{className:"w-4 h-4 animate-spin"}),f,r.jsxs("span",{className:"text-xs tabular-nums",children:[s,"s"]})]}),s>=5&&r.jsx("div",{className:"text-xs text-bambu-gray/70 pl-6",children:n("slice.analyzingPlateFilamentsHint","Running a preview slice to discover which AMS slots this plate uses. Cached after — re-opening is instant.")})]})}function t9e(t){const e=Math.max(0,Math.floor(t));if(e<60)return`${e}s`;const n=Math.floor(e/60),a=e%60;if(n<60)return`${n}m ${a}s`;const i=Math.floor(n/60),s=n%60;return`${i}h ${s}m`}function DA({source:t,onClose:e}){const{t:n}=kt(),{trackJob:a}=Y7e(),[i,s]=v.useState(null),[o,l]=v.useState(null),[c,d]=v.useState([]),[u,m]=v.useState(null),[p,f]=v.useState(null),[b,w]=v.useState([]),[g,x]=v.useState(null),[_,N]=v.useState(null),C=We({queryKey:["slicePlates",t.kind,t.id],queryFn:async()=>t.kind==="libraryFile"?se.getLibraryFilePlates(t.id):se.getArchivePlates(t.id),staleTime:6e4}),T=!!C.data?.is_multi_plate&&(C.data?.plates?.length??0)>1&&_==null,A=_??1,F=v.useMemo(()=>{const W=typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`;return`${t.kind}-${t.id}-p${A}-${W}`},[t.kind,t.id,A]),S=We({queryKey:["sliceFilamentReqs",t.kind,t.id,A],queryFn:async()=>t.kind==="libraryFile"?se.getLibraryFileFilamentRequirements(t.id,A,F):se.getArchiveFilamentRequirements(t.id,A,F),enabled:!T,staleTime:6e4}),M=v.useMemo(()=>{const W=S.data?.filaments??[];return W.length>0?W:[{slot_id:1,type:"",color:"",used_grams:0,used_meters:0}]},[S.data]),z=We({queryKey:["slicerPresets"],queryFn:()=>se.getSlicerPresets(),staleTime:6e4,enabled:!C.isLoading&&!T}),I=We({queryKey:["slicerBundles"],queryFn:se.listSlicerBundles,staleTime:6e4,enabled:!C.isLoading&&!T,retry:!1}),H=v.useMemo(()=>!u||!I.data?null:I.data.find(W=>W.id===u)??null,[u,I.data]),L=H!=null;v.useEffect(()=>{z.data&&(i==null&&s(iI(z.data,"printer")),o==null&&l(iI(z.data,"process")))},[z.data]),v.useEffect(()=>{if(!z.data)return;const W=z.data;d(ae=>ae.length===M.length&&ae.every(pe=>pe!=null)?ae:M.map(pe=>Q7e(W,{type:pe.type,color:pe.color})))},[z.data,M]),v.useEffect(()=>{if(!H){f(null),w([]);return}f(W=>W&&H.process.includes(W)?W:H.process[0]??null),w(W=>{if(W.length===M.length&&W.every(pe=>pe!=null))return W;const ae=H.filament[0]??null;return M.map((pe,ye)=>W[ye]??ae)})},[H,M]);const Z=it({mutationFn:async()=>{let W;if(L){if(!H||!p||b.length===0||b.some(pe=>pe==null))throw new Error(n("slice.bundleAllRequired","Bundle process and every filament slot must be picked"));W={bundle:{bundle_id:H.id,printer_name:H.printer[0]??H.printer_preset_name,process_name:p,filament_names:b},..._!=null?{plate:_}:{}}}else{if(!i||!o||c.length===0||c.some(ae=>ae==null))throw new Error(n("slice.allPresetsRequired","All presets must be selected"));W={printer_preset:i,process_preset:o,filament_preset:c[0],filament_presets:c,..._!=null?{plate:_}:{}}}return t.kind==="libraryFile"?se.sliceLibraryFile(t.id,W):se.sliceArchive(t.id,W)},onSuccess:W=>{a(W.job_id,t.kind,t.filename),e()},onError:W=>{const ae=W instanceof Error?W.message:String(W);x(ae)}}),re=C.data?.source_printer_model??null,J=L?H?.printer_preset_name.replace(/^# /,"")??null:i?z.data?.[i.source].printer.find(W=>W.id===i.id)?.name:null,de=!!re&&!!J&&!J.toLowerCase().includes(re.toLowerCase()),me=L?H!=null&&p!=null&&S.isSuccess&&b.length>0&&b.every(W=>W!=null)&&!de:i!=null&&o!=null&&S.isSuccess&&c.length>0&&c.every(W=>W!=null)&&!de,ue=Z.isPending;return T&&C.data?r.jsx(o5,{plates:C.data.plates,onSelect:W=>N(W),onClose:e}):r.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4",onClick:()=>{ue||e()},children:r.jsxs("div",{className:"w-full max-w-xl max-h-[85vh] flex flex-col rounded-lg bg-bambu-dark-secondary border border-bambu-dark-tertiary/60",onClick:W=>W.stopPropagation(),children:[r.jsxs("div",{className:"flex-shrink-0 flex items-start justify-between gap-3 px-4 pt-4 pb-3 border-b border-bambu-dark-tertiary/40",children:[r.jsxs("div",{className:"min-w-0",children:[r.jsxs("h3",{className:"text-white font-medium flex items-center gap-2",children:[r.jsx(cu,{className:"w-4 h-4"}),n("slice.title","Slice model")]}),r.jsxs("p",{className:"text-xs text-bambu-gray mt-1 truncate",title:t.filename,children:[t.filename,_!=null?` • ${n("archives.platePicker.plateLabel",{index:_})}`:""]})]}),r.jsx("button",{onClick:e,disabled:ue,className:"flex-shrink-0 text-bambu-gray hover:text-white transition-colors disabled:opacity-50","aria-label":n("common.close","Close"),children:r.jsx(Bt,{className:"w-5 h-5"})})]}),r.jsxs("div",{className:"flex-1 overflow-y-auto p-4 space-y-4",children:[(C.isLoading||z.isLoading)&&r.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray text-sm",children:[r.jsx(ut,{className:"w-4 h-4 animate-spin"}),n("slice.loadingPresets","Loading presets…")]}),z.isError&&r.jsx("div",{className:"text-sm text-red-400",role:"alert",children:n("slice.presetsLoadFailed","Failed to load presets. Open Settings → Profiles to import them, or sign in to Bambu Cloud.")}),z.data&&r.jsxs(r.Fragment,{children:[r.jsx(n9e,{status:z.data.cloud_status}),I.data&&I.data.length>0&&r.jsx(r9e,{bundles:I.data,selectedId:u,onChange:m,disabled:ue}),!L&&r.jsxs(r.Fragment,{children:[r.jsx(x3,{label:n("slice.printer","Printer profile"),slot:"printer",data:z.data,value:i,onChange:s,disabled:ue}),r.jsx(x3,{label:n("slice.process","Process profile"),slot:"process",data:z.data,value:o,onChange:l,disabled:ue})]}),L&&H&&r.jsxs(r.Fragment,{children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("slice.printer","Printer profile")}),r.jsx("div",{className:"px-3 py-2 rounded-md bg-bambu-dark/40 border border-bambu-dark-tertiary text-white text-sm",children:H.printer_preset_name})]}),r.jsx(YK,{label:n("slice.process","Process profile"),options:H.process,value:p,onChange:f,disabled:ue})]}),S.isLoading?r.jsx(e9e,{requestId:F,sourceName:t.filename}):L&&H?M.map((W,ae)=>{const pe=W.used_in_plate!==!1,ye=M.length>1?n("slice.filamentSlot",{index:ae+1,type:W.type,defaultValue:`Filament ${ae+1} (${W.type||""})`}):n("slice.filament","Filament profile"),Te=pe?ye:`${ye} ${n("slice.notUsedByPlate","— not used by this plate")}`;return r.jsx(YK,{label:Te,options:H.filament,value:b[ae]??null,onChange:$=>w(K=>{const D=K.length===M.length?[...K]:M.map((j,B)=>K[B]??null);return D[ae]=$,D}),disabled:ue||!pe,swatchColor:M.length>1?W.color:void 0},`bundle-filament-${ae}`)}):M.map((W,ae)=>{const pe=W.used_in_plate!==!1,ye=M.length>1?n("slice.filamentSlot",{index:ae+1,type:W.type,defaultValue:`Filament ${ae+1} (${W.type||""})`}):n("slice.filament","Filament profile"),Te=pe?ye:`${ye} ${n("slice.notUsedByPlate","— not used by this plate")}`;return r.jsx(x3,{label:Te,slot:"filament",data:z.data,value:c[ae]??null,onChange:$=>d(K=>{const D=K.length===M.length?[...K]:M.map((j,B)=>K[B]??null);return D[ae]=$,D}),disabled:ue||!pe,swatchColor:M.length>1?W.color:void 0},`filament-${ae}`)})]}),de&&r.jsx("div",{className:"text-sm text-amber-200 bg-amber-900/20 border border-amber-700/40 rounded p-2",role:"alert",children:n("slice.printerMismatch",{source:re,target:J,defaultValue:"This 3MF was sliced for {{source}}, but you picked {{target}}. The slicer CLI cannot re-slice a 3MF for a different printer — open the source in Bambu Studio, change the printer, and re-export."})}),g&&r.jsx("div",{className:"text-sm text-red-400 bg-red-900/20 border border-red-900/40 rounded p-2",role:"alert",children:g})]}),r.jsxs("div",{className:"flex-shrink-0 flex justify-end gap-2 px-4 py-3 border-t border-bambu-dark-tertiary/40",children:[r.jsx("button",{type:"button",onClick:e,disabled:ue,className:"px-3 py-1.5 text-sm rounded-md border border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray transition-colors disabled:opacity-50",children:n("common.cancel","Cancel")}),r.jsx("button",{type:"button",onClick:()=>{x(null),Z.mutate()},disabled:!me||ue,className:"px-3 py-1.5 text-sm rounded-md bg-bambu-green hover:bg-bambu-green/90 text-bambu-dark font-medium transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2",children:ue?r.jsxs(r.Fragment,{children:[r.jsx(ut,{className:"w-4 h-4 animate-spin"}),n("slice.enqueuing","Submitting slice job…")]}):n("slice.action","Slice")})]})]})})}function n9e({status:t}){const{t:e}=kt();if(t==="ok")return null;const n={not_authenticated:{tone:"border-bambu-dark-tertiary/40 bg-bambu-dark text-bambu-gray",icon:ib,key:"slice.cloud.notAuthenticated",fallback:"Sign in to Bambu Cloud (Settings → Profiles → Cloud) to see your cloud presets."},expired:{tone:"border-amber-700/40 bg-amber-900/20 text-amber-200",icon:zF,key:"slice.cloud.expired",fallback:"Bambu Cloud session expired — sign in again to refresh your cloud presets."},unreachable:{tone:"border-bambu-dark-tertiary/40 bg-bambu-dark text-bambu-gray",icon:zF,key:"slice.cloud.unreachable",fallback:"Bambu Cloud is unreachable right now. Local and standard presets still work."}},{tone:a,icon:i,key:s,fallback:o}=n[t];return r.jsxs("div",{className:`flex items-start gap-2 text-xs rounded-md border p-2 ${a}`,role:"status",children:[r.jsx(i,{className:"w-4 h-4 flex-shrink-0 mt-0.5"}),r.jsx("span",{children:e(s,o)})]})}function x3({label:t,slot:e,data:n,value:a,onChange:i,disabled:s,swatchColor:o}){const{t:l}=kt(),c=v.useMemo(()=>[{key:"local",tier:"local",label:"slice.tier.local",fallback:"Imported"},{key:"cloud",tier:"cloud",label:"slice.tier.cloud",fallback:"Cloud"},{key:"standard",tier:"standard",label:"slice.tier.standard",fallback:"Standard"}].map(({key:m,label:p,fallback:f})=>({tierLabel:l(p,f),entries:n[m][e]})).filter(m=>m.entries.length>0),[n,e,l]),d=c.reduce((u,m)=>u+m.entries.length,0);return r.jsxs("label",{className:"block",children:[r.jsxs("span",{className:"flex items-center gap-2 text-xs text-bambu-gray mb-1",children:[o&&r.jsx("span",{className:"inline-block w-3 h-3 rounded-full border border-bambu-dark-tertiary",style:{backgroundColor:o||"transparent"},"aria-hidden":!0}),r.jsx("span",{children:t})]}),r.jsxs("select",{value:Z7e(a),onChange:u=>i(J7e(u.target.value)),disabled:s||d===0,className:"w-full px-3 py-2 rounded-md bg-bambu-dark border border-bambu-dark-tertiary text-white text-sm focus:outline-none focus:border-bambu-gray disabled:opacity-50",children:[r.jsx("option",{value:"",children:d===0?l("slice.noPresetsForSlot","No presets available"):l("slice.selectPreset","— Select a preset —")}),c.map(u=>r.jsx("optgroup",{label:u.tierLabel,children:u.entries.map(m=>r.jsx("option",{value:`${m.source}:${m.id}`,children:m.name},`${m.source}:${m.id}`))},u.tierLabel))]})]})}function r9e({bundles:t,selectedId:e,onChange:n,disabled:a}){const{t:i}=kt();return r.jsxs("label",{className:"block",children:[r.jsxs("span",{className:"block text-sm text-bambu-gray mb-1 inline-flex items-center gap-1.5",children:[r.jsx(Br,{className:"w-3.5 h-3.5"}),i("slice.bundle","Slicer bundle")]}),r.jsxs("select",{value:e??"",onChange:s=>n(s.target.value||null),disabled:a,className:"w-full px-3 py-2 rounded-md bg-bambu-dark border border-bambu-dark-tertiary text-white text-sm focus:outline-none focus:border-bambu-gray disabled:opacity-50",children:[r.jsx("option",{value:"",children:i("slice.bundleNone","— None (pick presets individually) —")}),t.map(s=>r.jsx("option",{value:s.id,children:s.printer_preset_name},s.id))]})]})}function YK({label:t,options:e,value:n,onChange:a,disabled:i,swatchColor:s}){const{t:o}=kt();return r.jsxs("label",{className:"block",children:[r.jsxs("span",{className:"block text-sm text-bambu-gray mb-1 inline-flex items-center gap-1.5",children:[s&&r.jsx("span",{className:"inline-block w-3 h-3 rounded-sm border border-black/20",style:{backgroundColor:s||"transparent"},"aria-hidden":!0}),r.jsx("span",{children:t})]}),r.jsxs("select",{value:n??"",onChange:l=>a(l.target.value||null),disabled:i||e.length===0,className:"w-full px-3 py-2 rounded-md bg-bambu-dark border border-bambu-dark-tertiary text-white text-sm focus:outline-none focus:border-bambu-gray disabled:opacity-50",children:[r.jsx("option",{value:"",children:e.length===0?o("slice.noPresetsForSlot","No presets available"):o("slice.selectPreset","— Select a preset —")}),e.map(l=>r.jsx("option",{value:l,children:l},l))]})]})}function a9e(){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 Am(t,e="bambu_studio"){let n;const a=encodeURIComponent(t);e==="orcaslicer"?n=`orcaslicer://open?file=${a}`:a9e()==="macos"?n=`bambustudioopen://${a}`:n=`bambustudio://open?file=${a}`;const i=document.createElement("a");i.href=n,i.style.display="none",document.body.appendChild(i),i.click(),document.body.removeChild(i)}const Od="/img/bed",i9e={"cool plate":{icon:`${Od}/bed_cool.png`,label:"Cool Plate"},"pc plate":{icon:`${Od}/bed_cool.png`,label:"Cool Plate"},"cool plate (supertack)":{icon:`${Od}/bed_cool_supertack.png`,label:"Cool Plate SuperTack"},"supertack plate":{icon:`${Od}/bed_cool_supertack.png`,label:"Cool Plate SuperTack"},"bambu cool plate supertack":{icon:`${Od}/bed_cool_supertack.png`,label:"Cool Plate SuperTack"},"engineering plate":{icon:`${Od}/bed_engineering.png`,label:"Engineering Plate"},"high temp plate":{icon:`${Od}/bed_high_templ.png`,label:"High Temp Plate"},"textured pei plate":{icon:`${Od}/bed_pei.png`,label:"Textured PEI Plate"},"pei plate":{icon:`${Od}/bed_pei.png`,label:"PEI Plate"},"smooth pei plate":{icon:`${Od}/bed_pei_cool.png`,label:"Smooth PEI Plate"}};function Kie(t){return t?i9e[t.trim().toLowerCase()]??null:null}const XK=768;function Yie(){const[t,e]=v.useState(()=>typeof window<"u"?window.innerWidth{const n=window.matchMedia(`(max-width: ${XK-1}px)`),a=i=>{e(i.matches)};return e(n.matches),n.addEventListener("change",a),()=>n.removeEventListener("change",a)},[]),t}function s9e({onClose:t,initialFiles:e}){const{t:n}=kt(),a=en(),{showToast:i}=rn(),s=v.useRef(null),[o,l]=v.useState(()=>e?.filter(P=>P.name.endsWith(".3mf")).map(P=>({file:P,status:"pending"}))||[]),[c,d]=v.useState(!1),[u,m]=v.useState(null);v.useEffect(()=>{const P=T=>{T.key==="Escape"&&t()};return window.addEventListener("keydown",P),()=>window.removeEventListener("keydown",P)},[t]);const p=it({mutationFn:P=>se.uploadArchivesBulk(P),onSuccess:P=>{m(P),a.invalidateQueries({queryKey:["archives"]}),a.invalidateQueries({queryKey:["archiveStats"]}),l(T=>T.map(A=>{const F=P.results.find(M=>M.filename===A.file.name),S=P.errors.find(M=>M.filename===A.file.name);return F?{...A,status:"success",archiveId:F.id}:S?{...A,status:"error",error:S.error}:A})),P.failed===0?i(`${P.uploaded} file${P.uploaded!==1?"s":""} uploaded`):P.uploaded===0?i(`Failed to upload ${P.failed} file${P.failed!==1?"s":""}`,"error"):i(`${P.uploaded} uploaded, ${P.failed} failed`,"warning")},onError:()=>{l(P=>P.map(T=>({...T,status:"error",error:"Upload failed"}))),i("Upload failed","error")}}),f=v.useCallback(P=>{P.preventDefault(),d(!0)},[]),b=v.useCallback(P=>{P.preventDefault(),d(!1)},[]),w=v.useCallback(P=>{P.preventDefault(),d(!1);const T=Array.from(P.dataTransfer.files).filter(A=>A.name.endsWith(".3mf"));T.length>0&&l(A=>[...A,...T.map(F=>({file:F,status:"pending"}))])},[]),g=v.useCallback(P=>{const T=Array.from(P.target.files||[]).filter(A=>A.name.endsWith(".3mf"));T.length>0&&l(A=>[...A,...T.map(F=>({file:F,status:"pending"}))]),s.current&&(s.current.value="")},[]),x=v.useCallback(P=>{l(T=>T.filter((A,F)=>F!==P))},[]),_=()=>{if(o.length===0)return;const P=o.filter(T=>T.status==="pending");P.length!==0&&(l(T=>T.map(A=>A.status==="pending"?{...A,status:"uploading"}:A)),p.mutate(P.map(T=>T.file)))},N=o.filter(P=>P.status==="pending").length,C=p.isPending;return r.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:r.jsx(Ct,{className:"w-full max-w-2xl max-h-[90vh] flex flex-col",children:r.jsxs(At,{className:"p-0 flex flex-col h-full",children:[r.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[r.jsx("h2",{className:"text-xl font-semibold text-white",children:n("uploadModal.title")}),r.jsx("button",{onClick:t,className:"text-bambu-gray hover:text-white transition-colors",children:r.jsx(Bt,{className:"w-5 h-5"})})]}),r.jsx("div",{className:"p-4",children:r.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:b,onDrop:w,children:[r.jsx(ka,{className:"w-12 h-12 mx-auto mb-4 text-bambu-gray"}),r.jsx("p",{className:"text-white mb-2",children:n("uploadModal.dragDrop")}),r.jsx("p",{className:"text-bambu-gray text-sm mb-4",children:n("uploadModal.or")}),r.jsx(Me,{variant:"secondary",onClick:()=>s.current?.click(),disabled:C,children:n("uploadModal.browseFiles")}),r.jsx("input",{ref:s,type:"file",accept:".3mf",multiple:!0,className:"hidden",onChange:g})]})}),r.jsx("div",{className:"px-4 pb-4",children:r.jsx("p",{className:"text-xs text-bambu-gray",children:n("uploadModal.extractionInfo")})}),o.length>0&&r.jsx("div",{className:"px-4 pb-4 max-h-60 overflow-y-auto",children:r.jsx("div",{className:"space-y-2",children:o.map((P,T)=>r.jsxs("div",{className:"flex items-center gap-3 p-3 bg-bambu-dark rounded-lg",children:[r.jsx(ST,{className:"w-5 h-5 text-bambu-gray flex-shrink-0"}),r.jsx("span",{className:"flex-1 text-white text-sm truncate",children:P.file.name}),r.jsxs("span",{className:"text-xs text-bambu-gray",children:[(P.file.size/(1024*1024)).toFixed(1)," MB"]}),P.status==="pending"&&r.jsx("button",{onClick:()=>x(T),className:"text-bambu-gray hover:text-red-400 transition-colors",disabled:C,children:r.jsx(Bt,{className:"w-4 h-4"})}),P.status==="uploading"&&r.jsx(ut,{className:"w-4 h-4 text-bambu-green animate-spin"}),P.status==="success"&&r.jsx(wr,{className:"w-4 h-4 text-bambu-green"}),P.status==="error"&&r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:"text-xs text-red-400",children:P.error}),r.jsx($a,{className:"w-4 h-4 text-red-400"})]})]},`${P.file.name}-${T}`))})}),u&&r.jsx("div",{className:"px-4 pb-4",children:r.jsx("div",{className:"p-3 bg-bambu-dark rounded-lg",children:r.jsxs("p",{className:"text-sm text-white",children:[r.jsx("span",{className:"text-bambu-green",children:u.uploaded})," ",n("uploadModal.uploaded"),u.failed>0&&r.jsxs(r.Fragment,{children:[", ",r.jsx("span",{className:"text-red-400",children:u.failed})," ",n("uploadModal.failed")]})]})})}),r.jsxs("div",{className:"flex gap-3 p-4 border-t border-bambu-dark-tertiary",children:[r.jsx(Me,{variant:"secondary",onClick:t,className:"flex-1",children:n(u?"common.close":"common.cancel")}),!u&&r.jsx(Me,{onClick:_,disabled:N===0||C,className:"flex-1",children:C?r.jsxs(r.Fragment,{children:[r.jsx(ut,{className:"w-4 h-4 animate-spin"}),n("uploadModal.uploading")]}):r.jsxs(r.Fragment,{children:[r.jsx(ka,{className:"w-4 h-4"}),n("uploadModal.upload")," ",N>0&&`(${N})`]})})]})]})})})}const o9e=365;function l9e({onClose:t,initialDays:e}){const{t:n}=kt(),a=en(),{showToast:i}=rn(),[s,o]=v.useState(e??o9e),[l,c]=v.useState(s);v.useEffect(()=>{const w=window.setTimeout(()=>c(s),300);return()=>window.clearTimeout(w)},[s]);const d=We({queryKey:["archive-purge-preview",l],queryFn:()=>se.previewArchivePurge(l),enabled:l>=1}),u=it({mutationFn:()=>se.executeArchivePurge(s),onSuccess:w=>{i(n("archivePurge.toast.success",{count:w.deleted}),"success"),a.invalidateQueries({queryKey:["archives"]}),a.invalidateQueries({queryKey:["archive-stats"]}),t()},onError:w=>i(w.message||n("archivePurge.toast.failed"),"error")});v.useEffect(()=>{const w=g=>{g.key==="Escape"&&!u.isPending&&t()};return window.addEventListener("keydown",w),()=>window.removeEventListener("keydown",w)},[t,u.isPending]);const m=d.data,p=m?.count??0,f=m?.total_bytes??0,b=p>0&&!u.isPending;return r.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4",children:r.jsxs("div",{className:"bg-white dark:bg-gray-900 rounded-lg shadow-xl max-w-lg w-full",children:[r.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-gray-200 dark:border-gray-700",children:[r.jsxs("h2",{className:"text-lg font-semibold text-gray-900 dark:text-gray-100 flex items-center gap-2",children:[r.jsx(Jt,{className:"w-5 h-5"}),n("archivePurge.title")]}),r.jsx("button",{onClick:t,className:"text-gray-400 hover:text-gray-600 dark:hover:text-gray-200","aria-label":n("common.close"),disabled:u.isPending,children:r.jsx(Bt,{className:"w-5 h-5"})})]}),r.jsxs("div",{className:"p-4 space-y-4",children:[r.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-400",children:n("archivePurge.description")}),r.jsxs("div",{children:[r.jsx("label",{htmlFor:"archive-purge-days",className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1",children:n("archivePurge.ageLabel")}),r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("input",{id:"archive-purge-days",type:"number",min:1,max:3650,value:s,onChange:w=>o(Math.max(1,Math.min(3650,parseInt(w.target.value||"0",10)||0))),className:"w-24 rounded border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-sm px-2 py-1 text-gray-900 dark:text-gray-100"}),r.jsx("span",{className:"text-sm text-gray-600 dark:text-gray-400",children:n("archivePurge.days")})]})]}),r.jsxs("div",{className:"rounded border border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800/30 p-3",children:[r.jsx("div",{className:"text-xs font-semibold uppercase tracking-wide text-gray-600 dark:text-gray-300 mb-2",children:n("archivePurge.effectsTitle")}),r.jsxs("ul",{className:"text-xs text-gray-700 dark:text-gray-300 space-y-1 list-disc pl-4",children:[r.jsx("li",{children:n("archivePurge.effect1")}),r.jsx("li",{children:n("archivePurge.effect2")}),r.jsx("li",{children:n("archivePurge.effect3")}),r.jsx("li",{children:n("archivePurge.effect4")})]})]}),r.jsx("div",{className:"rounded border border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800/50 p-3",children:d.isLoading||d.isFetching?r.jsxs("div",{className:"flex items-center gap-2 text-sm text-gray-500 dark:text-gray-400",children:[r.jsx(ut,{className:"w-4 h-4 animate-spin"})," ",n("archivePurge.previewLoading")]}):d.isError?r.jsx("div",{className:"text-sm text-red-600 dark:text-red-400",children:d.error?.message??n("archivePurge.previewFailed")}):r.jsxs("div",{className:"text-sm text-gray-900 dark:text-gray-100",children:[r.jsx("div",{className:"font-medium",children:n("archivePurge.previewSummary",{count:p,size:cs(f)})}),m?.sample_filenames&&m.sample_filenames.length>0&&r.jsxs("ul",{className:"mt-2 text-xs text-gray-600 dark:text-gray-400 space-y-0.5 list-disc pl-4",children:[m.sample_filenames.map(w=>r.jsx("li",{className:"truncate",children:w},w)),p>m.sample_filenames.length&&r.jsx("li",{className:"list-none italic text-gray-500",children:n("archivePurge.andMore",{count:p-m.sample_filenames.length})})]})]})}),r.jsxs("div",{className:"flex gap-2 items-start text-xs text-amber-700 dark:text-amber-400 bg-amber-50 dark:bg-amber-900/20 rounded px-3 py-2",children:[r.jsx(Nn,{className:"w-4 h-4 mt-0.5 shrink-0"}),r.jsx("span",{children:n("archivePurge.warning")})]})]}),r.jsxs("div",{className:"flex justify-end gap-2 p-4 border-t border-gray-200 dark:border-gray-700",children:[r.jsx(Me,{variant:"secondary",onClick:t,disabled:u.isPending,children:n("common.cancel")}),r.jsx(Me,{variant:"danger",disabled:!b,onClick:()=>u.mutate(),children:u.isPending?r.jsxs(r.Fragment,{children:[r.jsx(ut,{className:"w-4 h-4 animate-spin mr-1"}),n("archivePurge.purging")]}):n("archivePurge.confirmCta",{count:p})})]})]})})}const c9e=["adhesionFailure","spaghettiDetached","layerShift","cloggedNozzle","filamentRunout","warping","stringing","underExtrusion","powerFailure","userCancelled","other"],d9e=["completed","failed","aborted","printing"];function Xie({archive:t,onClose:e,existingTags:n=[]}){const{t:a}=kt();v.useEffect(()=>{const j=B=>{B.key==="Escape"&&e()};return window.addEventListener("keydown",j),()=>window.removeEventListener("keydown",j)},[e]);const i=en(),[s,o]=v.useState(t.print_name||""),[l,c]=v.useState(t.printer_id),[d,u]=v.useState(t.project_id??null),[m,p]=v.useState(t.notes||""),[f,b]=v.useState(t.tags||""),[w,g]=v.useState(t.failure_reason||""),[x,_]=v.useState(t.status),[N,C]=v.useState(t.quantity??1),[P,T]=v.useState(t.photos||[]),[A,F]=v.useState(t.external_url||""),[S,M]=v.useState(!1),[z,I]=v.useState(!1),H=v.useRef(null),L=v.useRef(null),Z=v.useRef(null),{data:re}=We({queryKey:["printers"],queryFn:se.getPrinters}),{data:J}=We({queryKey:["projects"],queryFn:()=>se.getProjects(),select:j=>[...j].sort((B,X)=>B.name.localeCompare(X.name))}),{data:de}=We({queryKey:["tags"],queryFn:se.getTags,enabled:n.length===0}),me=n.length>0?n:de?.map(j=>j.name)||[],ue=f.split(",").map(j=>j.trim()).filter(Boolean),W=f.includes(",")?f.substring(f.lastIndexOf(",")+1).trim().toLowerCase():f.trim().toLowerCase(),ae=me.filter(j=>!ue.includes(j)&&(W===""||j.toLowerCase().includes(W))),pe=j=>{let B;if(W&&!me.includes(W)?B=f.includes(",")?f.substring(0,f.lastIndexOf(",")).split(",").map(X=>X.trim()).filter(Boolean):[]:B=ue,!B.includes(j)){const X=[...B,j].join(", ");b(X)}Z.current!==null&&clearTimeout(Z.current),H.current?.focus()},ye=j=>{const B=ue.filter(X=>X!==j).join(", ");b(B)},Te=it({mutationFn:j=>se.updateArchive(t.id,j),onSuccess:()=>{i.invalidateQueries({queryKey:["archives"]}),i.invalidateQueries({queryKey:["projects"]}),e()}}),$=async j=>{const B=j.target.files?.[0];if(B){M(!0);try{const X=await se.uploadArchivePhoto(t.id,B);T(X.photos),i.invalidateQueries({queryKey:["archives"]})}catch(X){console.error("Failed to upload photo:",X)}finally{M(!1),L.current&&(L.current.value="")}}},K=async j=>{try{const B=await se.deleteArchivePhoto(t.id,j);T(B.photos||[]),i.invalidateQueries({queryKey:["archives"]})}catch(B){console.error("Failed to delete photo:",B)}},D=j=>{j.preventDefault();const B={print_name:s||void 0,printer_id:l,project_id:d,notes:m||void 0,tags:f||void 0,quantity:N,external_url:A||null};x!==t.status&&(B.status=x),x==="failed"||x==="aborted"?B.failure_reason=w||void 0:(t.status==="failed"||t.status==="aborted")&&(B.failure_reason=null),Te.mutate(B)};return r.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:e,children:r.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:[r.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[r.jsx("h2",{className:"text-lg font-semibold text-white",children:a("editArchive.title")}),r.jsx("button",{onClick:e,className:"text-bambu-gray hover:text-white transition-colors",children:r.jsx(Bt,{className:"w-5 h-5"})})]}),r.jsxs("form",{onSubmit:D,className:"p-6 space-y-4 overflow-y-auto flex-1",children:[r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("editArchive.name")}),r.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:a("editArchive.namePlaceholder")})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("editArchive.printer")}),r.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:[r.jsx("option",{value:"",children:a("editArchive.noPrinter")}),re?.map(j=>r.jsx("option",{value:j.id,children:j.name},j.id))]})]}),r.jsxs("div",{children:[r.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[r.jsx(ro,{className:"w-4 h-4 inline mr-1"}),a("editArchive.project")]}),r.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:[r.jsx("option",{value:"",children:a("editArchive.noProject")}),J?.map(j=>r.jsx("option",{value:j.id,children:j.name},j.id))]})]}),r.jsxs("div",{children:[r.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[r.jsx(Ebe,{className:"w-4 h-4 inline mr-1"}),a("editArchive.itemsPrinted")]}),r.jsx("input",{type:"number",min:1,value:N,onChange:j=>C(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"}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:a("editArchive.itemsPrintedHelp")})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("editArchive.notes")}),r.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:a("editArchive.notesPlaceholder")})]}),r.jsxs("div",{children:[r.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[r.jsx(Gy,{className:"w-4 h-4 inline mr-1"}),a("editArchive.externalLink")]}),r.jsx("input",{type:"url",value:A,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/..."}),r.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:a("editArchive.externalLinkHelp")})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("editArchive.tags")}),ue.length>0&&r.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:ue.map(j=>r.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 bg-bambu-dark-tertiary rounded text-sm text-white",children:[r.jsx($m,{className:"w-3 h-3"}),j,r.jsx("button",{type:"button",onClick:()=>ye(j),className:"ml-0.5 text-bambu-gray hover:text-white",children:r.jsx(Bt,{className:"w-3 h-3"})})]},j))}),r.jsxs("div",{className:"relative",children:[r.jsx("input",{ref:H,type:"text",value:f,onChange:j=>b(j.target.value),onFocus:()=>{Z.current!==null&&clearTimeout(Z.current),I(!0)},onBlur:()=>{Z.current=window.setTimeout(()=>I(!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:ue.length>0?a("editArchive.addMoreTags"):a("editArchive.tagsPlaceholder")}),z&&ae.length>0&&r.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:[r.jsxs("div",{className:"p-2 text-xs text-bambu-gray border-b border-bambu-dark-tertiary",children:[W?a("editArchive.matchingTags",{query:W}):a("editArchive.existingTags")," ",a("editArchive.clickToAdd")]}),r.jsx("div",{className:"p-2 flex flex-wrap gap-1.5",children:ae.map(j=>r.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))})]})]})]}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("editArchive.status")}),r.jsx("select",{value:x,onChange:j=>{_(j.target.value),j.target.value==="completed"&&g("")},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:d9e.map(j=>r.jsx("option",{value:j,children:a(`editArchive.statuses.${j}`)},j))})]}),(x==="failed"||x==="aborted")&&r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("editArchive.failureReason")}),r.jsxs("select",{value:w,onChange:j=>g(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:[r.jsx("option",{value:"",children:a("editArchive.selectReason")}),c9e.map(j=>r.jsx("option",{value:a(`editArchive.failureReasons.${j}`),children:a(`editArchive.failureReasons.${j}`)},j))]})]}),r.jsxs("div",{children:[r.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[r.jsx(fy,{className:"w-4 h-4 inline mr-1"}),a("editArchive.photos")]}),r.jsxs("div",{className:"flex flex-wrap gap-2 mb-2",children:[P.map(j=>r.jsxs("div",{className:"relative group",children:[r.jsx("img",{src:se.getArchivePhotoUrl(t.id,j),alt:a("editArchive.printResult"),className:"w-20 h-20 object-cover rounded-lg border border-bambu-dark-tertiary"}),r.jsx("button",{type:"button",onClick:()=>K(j),className:"absolute -top-1 -right-1 p-1 bg-red-500 rounded-full opacity-0 group-hover:opacity-100 transition-opacity",children:r.jsx(Jt,{className:"w-3 h-3 text-white"})})]},j)),r.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:[r.jsx("input",{ref:L,type:"file",accept:"image/jpeg,image/png,image/webp",onChange:$,className:"hidden",disabled:S}),S?r.jsx(ut,{className:"w-6 h-6 text-bambu-gray animate-spin"}):r.jsx(ar,{className:"w-6 h-6 text-bambu-gray"})]})]}),r.jsx("p",{className:"text-xs text-bambu-gray",children:a("editArchive.photosHelp")})]}),r.jsxs("div",{className:"flex gap-3 pt-2",children:[r.jsx(Me,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:a("common.cancel")}),r.jsxs(Me,{type:"submit",disabled:Te.isPending,className:"flex-1",children:[r.jsx(us,{className:"w-4 h-4"}),Te.isPending?a("common.saving"):a("common.save")]})]})]})]})})}function u9e({items:t,searchPlaceholder:e,onClose:n,className:a,onMouseEnter:i,onMouseLeave:s}){const[o,l]=v.useState(""),c=v.useRef(null);v.useEffect(()=>{if(e){const m=window.setTimeout(()=>c.current?.focus(),0);return()=>window.clearTimeout(m)}},[e]);const d=o.trim().toLowerCase(),u=e&&d?t.filter(m=>m.label.toLowerCase().includes(d)):t;return r.jsxs("div",{className:a,onMouseEnter:i,onMouseLeave:s,children:[e&&r.jsx("div",{className:"sticky top-0 z-[1] px-2 py-1.5 bg-bambu-dark-secondary border-b border-bambu-dark-tertiary",children:r.jsxs("div",{className:"relative",children:[r.jsx(Sr,{className:"absolute left-2 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-bambu-gray pointer-events-none"}),r.jsx("input",{ref:c,type:"text",value:o,onChange:m=>l(m.target.value),onKeyDown:m=>{if(m.key==="Enter"){const p=u.find(f=>!f.disabled);p&&(p.onClick(),n())}},placeholder:e,className:"w-full pl-7 pr-2 py-1 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]})}),u.map((m,p)=>r.jsxs("button",{onClick:()=>{m.disabled||(m.onClick(),n())},disabled:m.disabled,className:`w-full flex items-center gap-2 px-3 py-2 text-sm text-left transition-colors ${m.disabled?"text-bambu-gray cursor-not-allowed":m.danger?"text-red-400 hover:bg-red-400/10":"text-white hover:bg-bambu-dark-tertiary"}`,children:[m.icon&&r.jsx("span",{className:"w-4 h-4 flex-shrink-0 flex items-center justify-center",children:m.icon}),r.jsx("span",{className:"flex-1 truncate",children:m.label})]},p)),e&&u.length===0&&r.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray text-center italic",children:"—"})]})}function Qie({x:t,y:e,items:n,onClose:a}){const i=v.useRef(null),[s,o]=v.useState(null),l=v.useRef(null),[c,d]=v.useState({x:t,y:e,visible:!1}),[u,m]=v.useState(!1),[p,f]=v.useState({});v.useEffect(()=>{const g=N=>{i.current&&!i.current.contains(N.target)&&a()},x=N=>{N.key==="Escape"&&a()},_=N=>{i.current&&i.current.contains(N.target)||a()};return document.addEventListener("mousedown",g),document.addEventListener("keydown",x),document.addEventListener("scroll",_,!0),()=>{document.removeEventListener("mousedown",g),document.removeEventListener("keydown",x),document.removeEventListener("scroll",_,!0),l.current&&clearTimeout(l.current)}},[a]),v.useLayoutEffect(()=>{if(i.current){i.current.style.visibility="hidden",i.current.style.display="block";const g=i.current.getBoundingClientRect(),x=window.innerWidth,_=window.innerHeight,N=8;let C=t,P=e;t+g.width>x-N&&(C=Math.max(N,x-g.width-N)),C_-N&&(P=Math.max(N,_-g.height-N)),PT),d({x:C,y:P,visible:!0})}},[t,e]);const b=(g,x)=>{l.current&&(clearTimeout(l.current),l.current=null);const _=x.getBoundingClientRect(),N=window.innerHeight,C=300,A=N-_.top-8C;f(F=>({...F,[g]:A?"bottom":"top"})),o(g)},w=()=>{l.current=window.setTimeout(()=>{o(null)},150)};return r.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((g,x)=>{if(g.divider)return r.jsx("div",{className:"my-1 border-t border-bambu-dark-tertiary"},x);const _=g.submenu&&g.submenu.length>0;return r.jsxs("div",{className:"relative",onMouseEnter:N=>_&&b(x,N.currentTarget),onMouseLeave:()=>_&&w(),children:[r.jsxs("button",{onMouseEnter:N=>_&&b(x,N.currentTarget.parentElement),onClick:()=>{_?o(s===x?null:x):g.disabled||(g.onClick(),a())},disabled:g.disabled,title:g.title,className:`w-full flex items-center gap-2 px-3 py-2 text-sm text-left transition-colors ${g.disabled?"text-bambu-gray cursor-not-allowed":g.danger?"text-red-400 hover:bg-red-400/10":"text-white hover:bg-bambu-dark-tertiary"} ${_&&s===x?"bg-bambu-dark-tertiary":""}`,children:[g.icon&&r.jsx("span",{className:"w-4 h-4 flex-shrink-0 flex items-center justify-center",children:g.icon}),r.jsx("span",{className:"flex-1",children:g.label}),_&&r.jsx(Va,{className:"w-4 h-4 text-bambu-gray"})]}),_&&s===x&&r.jsx(u9e,{items:g.submenu,searchPlaceholder:g.submenuSearchPlaceholder,onClose:a,className:`absolute min-w-[200px] 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[x]==="bottom"?"bottom-0":"top-0"}`,onMouseEnter:()=>{l.current&&(clearTimeout(l.current),l.current=null)},onMouseLeave:()=>w()})]},x)})})}function m9e({selectedIds:t,existingTags:e,onClose:n}){const a=en(),{showToast:i}=rn(),[s,o]=v.useState(""),[l,c]=v.useState(new Set),[d,u]=v.useState("add");v.useEffect(()=>{const w=g=>{g.key==="Escape"&&n()};return window.addEventListener("keydown",w),()=>window.removeEventListener("keydown",w)},[n]);const m=it({mutationFn:async()=>{const w=Array.from(l);let g=0;for(const x of t)try{const _=await se.getArchive(x),N=_.tags?_.tags.split(",").map(P=>P.trim()).filter(Boolean):[];let C;d==="add"?C=[...new Set([...N,...w])]:C=N.filter(P=>!l.has(P)),await se.updateArchive(x,{tags:C.join(", ")}),g++}catch(_){throw console.error(`Failed to update archive ${x}:`,_),new Error(`Failed on archive ${x}: ${_ instanceof Error?_.message:"Unknown error"}`)}return{count:g,mode:d,tags:w}},onSuccess:({count:w,mode:g,tags:x})=>{a.invalidateQueries({queryKey:["archives"]}),i(`${g==="add"?"Added":"Removed"} ${x.length} tag${x.length!==1?"s":""} ${g==="add"?"to":"from"} ${w} archive${w!==1?"s":""}`),n()},onError:w=>{i(w.message||"Failed to update tags","error")}}),p=w=>{c(g=>{const x=new Set(g);return x.has(w)?x.delete(w):x.add(w),x})},f=()=>{s.trim()&&!l.has(s.trim())&&(c(w=>new Set([...w,s.trim()])),o(""))},b=w=>{w.key==="Enter"&&(w.preventDefault(),f())};return r.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:r.jsx(Ct,{className:"w-full max-w-md",children:r.jsxs(At,{className:"p-0",children:[r.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx($m,{className:"w-5 h-5 text-bambu-green"}),r.jsx("h2",{className:"text-xl font-semibold text-white",children:d==="add"?"Add Tags":"Remove Tags"})]}),r.jsx("button",{onClick:n,className:"text-bambu-gray hover:text-white transition-colors",children:r.jsx(Bt,{className:"w-5 h-5"})})]}),r.jsxs("div",{className:"p-4 space-y-4",children:[r.jsxs("p",{className:"text-sm text-bambu-gray",children:[d==="add"?"Add":"Remove"," tags for ",t.length," selected archive",t.length!==1?"s":""]}),r.jsxs("div",{className:"flex gap-2",children:[r.jsx(Me,{size:"sm",variant:d==="add"?"primary":"secondary",onClick:()=>u("add"),children:"Add Tags"}),r.jsx(Me,{size:"sm",variant:d==="remove"?"primary":"secondary",onClick:()=>u("remove"),children:"Remove Tags"})]}),d==="add"&&r.jsxs("div",{className:"flex gap-2",children:[r.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:w=>o(w.target.value),onKeyDown:b}),r.jsx(Me,{size:"sm",variant:"secondary",onClick:f,disabled:!s.trim(),children:r.jsx(ar,{className:"w-4 h-4"})})]}),e.length>0&&r.jsxs("div",{children:[r.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:"Existing tags:"}),r.jsx("div",{className:"flex flex-wrap gap-2",children:e.map(w=>r.jsx("button",{onClick:()=>p(w),className:`px-2 py-1 rounded text-sm transition-colors ${l.has(w)?"bg-bambu-green text-white":"bg-bambu-dark-tertiary text-bambu-gray-light hover:bg-bambu-dark"}`,children:w},w))})]}),l.size>0&&r.jsxs("div",{children:[r.jsxs("p",{className:"text-xs text-bambu-gray mb-2",children:["Tags to ",d==="add"?"add":"remove",":"]}),r.jsx("div",{className:"flex flex-wrap gap-2",children:Array.from(l).map(w=>r.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:[w,r.jsx("button",{onClick:()=>p(w),className:"hover:opacity-70",children:r.jsx(Bt,{className:"w-3 h-3"})})]},w))})]})]}),r.jsxs("div",{className:"flex gap-3 p-4 border-t border-bambu-dark-tertiary",children:[r.jsx(Me,{variant:"secondary",onClick:n,className:"flex-1",children:"Cancel"}),r.jsx(Me,{onClick:()=>m.mutate(),disabled:l.size===0||m.isPending,className:"flex-1",children:m.isPending?r.jsxs(r.Fragment,{children:[r.jsx(ut,{className:"w-4 h-4 animate-spin"}),"Processing..."]}):r.jsxs(r.Fragment,{children:[r.jsx($m,{className:"w-4 h-4"}),d==="add"?"Add Tags":"Remove Tags"]})})]})]})})})}function p9e({selectedIds:t,onClose:e}){const{t:n}=kt(),a=en(),{showToast:i}=rn(),[s,o]=v.useState(""),{data:l,isLoading:c}=We({queryKey:["projects"],queryFn:()=>se.getProjects()}),d=v.useMemo(()=>l?[...l].sort((x,_)=>x.name.localeCompare(_.name)):void 0,[l]),u=s.trim().toLowerCase(),m=u?d?.filter(x=>x.name.toLowerCase().includes(u)):d,p=(d?.length??0)>5;v.useEffect(()=>{const x=_=>{_.key==="Escape"&&e()};return window.addEventListener("keydown",x),()=>window.removeEventListener("keydown",x)},[e]);const f=()=>{a.invalidateQueries({queryKey:["archives"]}),a.invalidateQueries({queryKey:["projects"]}),a.invalidateQueries({queryKey:["project"]}),a.invalidateQueries({queryKey:["project-archives"]})},b=it({mutationFn:async x=>(await se.addArchivesToProject(x,t),x),onSuccess:x=>{const _=l?.find(N=>N.id===x);f(),i(`Added ${t.length} archive${t.length!==1?"s":""} to "${_?.name}"`),e()},onError:()=>{i("Failed to assign project","error")}}),w=it({mutationFn:async()=>{for(const x of t)await se.updateArchive(x,{project_id:null});return t.length},onSuccess:x=>{f(),i(`Removed ${x} archive${x!==1?"s":""} from project`),e()},onError:()=>{i("Failed to remove from project","error")}}),g=b.isPending||w.isPending;return r.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:r.jsx(Ct,{className:"w-full max-w-md max-h-[80vh] flex flex-col",children:r.jsxs(At,{className:"p-0 flex flex-col min-h-0",children:[r.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary shrink-0",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx(ro,{className:"w-5 h-5 text-bambu-green"}),r.jsx("h2",{className:"text-xl font-semibold text-white",children:"Assign to Project"})]}),r.jsx("button",{onClick:e,className:"text-bambu-gray hover:text-white transition-colors",disabled:g,children:r.jsx(Bt,{className:"w-5 h-5"})})]}),r.jsxs("div",{className:"p-4 space-y-3 overflow-y-auto min-h-0",children:[r.jsxs("p",{className:"text-sm text-bambu-gray",children:["Assign ",t.length," selected archive",t.length!==1?"s":""," to a project"]}),c?r.jsx("div",{className:"flex items-center justify-center py-8",children:r.jsx(ut,{className:"w-6 h-6 animate-spin text-bambu-gray"})}):r.jsxs("div",{className:"space-y-2",children:[r.jsxs("button",{onClick:()=>w.mutate(),disabled:g,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:[r.jsx("div",{className:"w-8 h-8 rounded-full bg-red-500/20 flex items-center justify-center shrink-0",children:r.jsx(Da,{className:"w-4 h-4 text-red-400"})}),r.jsxs("div",{className:"min-w-0 flex-1",children:[r.jsx("p",{className:"text-white font-medium",children:"Remove from project"}),r.jsx("p",{className:"text-sm text-bambu-gray truncate",children:"Clear project assignment"})]}),w.isPending&&r.jsx(ut,{className:"w-4 h-4 animate-spin text-bambu-gray shrink-0"})]}),d&&d.length>0&&r.jsxs("div",{className:"flex items-center gap-2 py-2",children:[r.jsx("div",{className:"flex-1 h-px bg-bambu-dark-tertiary"}),r.jsx("span",{className:"text-xs text-bambu-gray",children:"or assign to"}),r.jsx("div",{className:"flex-1 h-px bg-bambu-dark-tertiary"})]}),p&&r.jsxs("div",{className:"relative",children:[r.jsx(Sr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"}),r.jsx("input",{type:"text",value:s,onChange:x=>o(x.target.value),placeholder:n("archives.menu.searchProjects"),className:"w-full pl-9 pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray text-sm focus:border-bambu-green focus:outline-none"})]}),m?.map(x=>r.jsxs("button",{onClick:()=>b.mutate(x.id),disabled:g,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:[r.jsx("div",{className:"w-8 h-8 rounded-full flex items-center justify-center shrink-0",style:{backgroundColor:x.color?`${x.color}20`:"rgb(var(--bambu-green) / 0.2)"},children:r.jsx(ro,{className:"w-4 h-4",style:{color:x.color||"rgb(var(--bambu-green))"}})}),r.jsxs("div",{className:"min-w-0 flex-1",children:[r.jsx("p",{className:"text-white font-medium truncate",children:x.name}),r.jsxs("p",{className:"text-sm text-bambu-gray truncate",children:[x.archive_count," archive",x.archive_count!==1?"s":"",x.status&&` • ${x.status}`]})]}),b.isPending&&b.variables===x.id&&r.jsx(ut,{className:"w-4 h-4 animate-spin text-bambu-gray shrink-0"})]},x.id)),(!d||d.length===0)&&r.jsx("p",{className:"text-center text-bambu-gray py-4",children:"No projects yet. Create one from the Projects page."}),d&&d.length>0&&m?.length===0&&r.jsx("p",{className:"text-center text-bambu-gray text-sm py-4",children:"—"})]})]}),r.jsx("div",{className:"flex gap-3 p-4 border-t border-bambu-dark-tertiary shrink-0",children:r.jsx(Me,{variant:"secondary",onClick:e,className:"flex-1",disabled:g,children:"Cancel"})})]})})})}function h9e(t,e){return new Date(t,e+1,0).getDate()}function f9e(t,e){return new Date(t,e,1).getDay()}const g9e=["January","February","March","April","May","June","July","August","September","October","November","December"],b9e=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];function x9e({archives:t,onArchiveClick:e,highlightedArchiveId:n}){const a=new Date,[i,s]=v.useState(a.getMonth()),[o,l]=v.useState(a.getFullYear()),[c,d]=v.useState(null),[u,m]=v.useState(null),p=v.useMemo(()=>{const P=new Map;return t.forEach(T=>{const A=Xn(T.completed_at||T.created_at)||new Date,F=`${A.getFullYear()}-${String(A.getMonth()+1).padStart(2,"0")}-${String(A.getDate()).padStart(2,"0")}`,S=P.get(F)||[];S.push(T),P.set(F,S)}),P},[t]),f=h9e(o,i),b=f9e(o,i),w=()=>{i===0?(s(11),l(o-1)):s(i-1)},g=()=>{i===11?(s(0),l(o+1)):s(i+1)},x=()=>{s(a.getMonth()),l(a.getFullYear())},_=[];for(let P=0;P{P!==c&&m(null),d(P)};return r.jsxs("div",{className:"flex flex-col lg:flex-row gap-6",children:[r.jsxs("div",{className:"flex-1",children:[r.jsxs("div",{className:"flex items-center justify-between mb-4",children:[r.jsx("button",{onClick:w,className:"p-2 hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:r.jsx(el,{className:"w-5 h-5 text-bambu-gray"})}),r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsxs("h2",{className:"text-lg font-semibold text-white",children:[g9e[i]," ",o]}),r.jsx("button",{onClick:x,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"})]}),r.jsx("button",{onClick:g,className:"p-2 hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:r.jsx(Va,{className:"w-5 h-5 text-bambu-gray"})})]}),r.jsx("div",{className:"grid grid-cols-7 gap-1 mb-1",children:b9e.map(P=>r.jsx("div",{className:"text-center text-xs text-bambu-gray py-2",children:P},P))}),r.jsx("div",{className:"grid grid-cols-7 gap-1",children:_.map((P,T)=>{if(P===null)return r.jsx("div",{className:"aspect-square"},`empty-${T}`);const A=`${o}-${String(i+1).padStart(2,"0")}-${String(P).padStart(2,"0")}`,F=p.get(A)||[],S=F.length>0,M=P===a.getDate()&&i===a.getMonth()&&o===a.getFullYear(),z=A===c,I=F.filter(L=>L.status==="completed").length,H=F.filter(L=>L.status==="failed").length;return r.jsxs("button",{onClick:()=>C(z?null:A),className:`aspect-square rounded-lg p-1 flex flex-col items-center justify-center transition-colors relative ${z?"bg-bambu-green text-white":M?"bg-bambu-green/20 text-white ring-2 ring-bambu-green":S?"bg-bambu-dark-tertiary hover:bg-bambu-dark-tertiary/70 text-white":"hover:bg-bambu-dark-tertiary/50 text-bambu-gray"}`,children:[r.jsx("span",{className:`text-sm font-medium ${M&&!z?"text-bambu-green":""}`,children:P}),S&&r.jsxs("div",{className:"absolute bottom-1 left-1/2 -translate-x-1/2 flex items-center gap-1",children:[r.jsx("div",{className:`w-2 h-2 rounded-full ${H>0&&I===0?"bg-red-400":H>0?"bg-yellow-400":"bg-green-400"}`}),r.jsx("span",{className:"text-xs font-medium",children:F.length})]})]},P)})}),r.jsx("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:r.jsxs("div",{className:"grid grid-cols-3 gap-4 text-center",children:[r.jsxs("div",{children:[r.jsx("div",{className:"text-2xl font-bold text-white",children:t.filter(P=>{const T=Xn(P.completed_at||P.created_at)||new Date;return T.getMonth()===i&&T.getFullYear()===o}).length}),r.jsx("div",{className:"text-xs text-bambu-gray",children:"Prints this month"})]}),r.jsxs("div",{children:[r.jsx("div",{className:"text-2xl font-bold text-green-400",children:t.filter(P=>{const T=Xn(P.completed_at||P.created_at)||new Date;return T.getMonth()===i&&T.getFullYear()===o&&P.status==="completed"}).length}),r.jsx("div",{className:"text-xs text-bambu-gray",children:"Successful"})]}),r.jsxs("div",{children:[r.jsx("div",{className:"text-2xl font-bold text-red-400",children:t.filter(P=>{const T=Xn(P.completed_at||P.created_at)||new Date;return T.getMonth()===i&&T.getFullYear()===o&&P.status==="failed"}).length}),r.jsx("div",{className:"text-xs text-bambu-gray",children:"Failed"})]})]})})]}),r.jsx("div",{className:"lg:w-80 bg-bambu-dark rounded-xl p-4",children:c?r.jsxs(r.Fragment,{children:[r.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"})}),N.length>0?r.jsx("div",{className:"calendar-scroll space-y-2 max-h-96 overflow-y-auto",children:N.map(P=>{const T=P.id===u||P.id===n;return r.jsxs("button",{onClick:()=>{m(P.id),e?.(P)},className:`w-full flex items-center gap-3 p-2 rounded-lg transition-colors text-left ${T?"":"hover:bg-bambu-dark-tertiary"}`,style:T?{outline:"4px solid #facc15",outlineOffset:"2px"}:void 0,children:[P.thumbnail_path?r.jsx("img",{src:se.getArchiveThumbnail(P.id),alt:"",className:"w-12 h-12 rounded object-cover"}):r.jsx("div",{className:"w-12 h-12 rounded bg-bambu-dark-tertiary flex items-center justify-center",children:r.jsx("span",{className:"text-xs text-bambu-gray",children:"3MF"})}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsx("p",{className:"text-sm text-white truncate",children:P.print_name||P.filename}),r.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[r.jsx("span",{className:P.status==="failed"?"text-red-400":"text-green-400",children:P.status==="failed"?"Failed":"Completed"}),P.filament_color&&r.jsx("div",{className:"flex gap-0.5",children:P.filament_color.split(",").map((A,F)=>r.jsx("div",{className:"w-3 h-3 rounded-full border border-black/20",style:{backgroundColor:A}},F))})]})]})]},P.id)})}):r.jsx("p",{className:"text-sm text-bambu-gray",children:"No prints on this day"})]}):r.jsx("div",{className:"text-center py-8",children:r.jsx("p",{className:"text-sm text-bambu-gray",children:"Select a day to see prints"})})})]})}function Zie({archiveId:t,archiveName:e,onClose:n}){const a=se.getArchiveQRCodeUrl(t,300);v.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=a,s.download=`${e}_qrcode.png`,s.click()};return r.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:n,children:r.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary w-full max-w-sm",onClick:s=>s.stopPropagation(),children:[r.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[r.jsx("h2",{className:"text-lg font-semibold text-white",children:"QR Code"}),r.jsx("button",{onClick:n,className:"text-bambu-gray hover:text-white transition-colors",children:r.jsx(Bt,{className:"w-5 h-5"})})]}),r.jsxs("div",{className:"p-6 flex flex-col items-center",children:[r.jsx("p",{className:"text-sm text-bambu-gray mb-4 text-center truncate max-w-full",children:e}),r.jsx("div",{className:"bg-white p-4 rounded-lg mb-4",children:r.jsx("img",{src:a,alt:"QR Code",className:"w-64 h-64"})}),r.jsx("p",{className:"text-xs text-bambu-gray mb-4 text-center",children:"Scan to open this archive"}),r.jsxs(Me,{onClick:i,className:"w-full",children:[r.jsx(Yr,{className:"w-4 h-4"}),"Download QR Code"]})]})]})})}function Jie({archiveId:t,archiveName:e,photos:n,onClose:a,onDelete:i}){const[s,o]=v.useState(0),[l,c]=v.useState(!1);if(v.useEffect(()=>{const f=b=>{b.key==="Escape"&&a(),b.key==="ArrowLeft"&&o(w=>Math.max(0,w-1)),b.key==="ArrowRight"&&o(w=>Math.min(n.length-1,w+1))};return window.addEventListener("keydown",f),()=>window.removeEventListener("keydown",f)},[a,n.length]),v.useEffect(()=>{s>=n.length&&o(Math.max(0,n.length-1))},[n.length,s]),n.length===0)return a(),null;const d=n[s],u=se.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 r.jsxs("div",{className:"fixed inset-0 bg-black/90 flex items-center justify-center z-50",onClick:a,children:[r.jsxs("div",{className:"relative w-full h-full flex flex-col",onClick:f=>f.stopPropagation(),children:[r.jsxs("div",{className:"flex items-center justify-between px-6 py-4 bg-black/50",children:[r.jsxs("div",{children:[r.jsx("h2",{className:"text-lg font-semibold text-white",children:e}),r.jsxs("p",{className:"text-sm text-bambu-gray",children:["Photo ",s+1," of ",n.length]})]}),r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsxs(Me,{variant:"secondary",size:"sm",onClick:m,children:[r.jsx(Yr,{className:"w-4 h-4"}),"Download"]}),i&&r.jsx(Me,{variant:"secondary",size:"sm",onClick:p,className:"text-red-400 hover:text-red-300",children:r.jsx(Jt,{className:"w-4 h-4"})}),r.jsx("button",{onClick:a,className:"p-2 text-bambu-gray hover:text-white transition-colors",children:r.jsx(Bt,{className:"w-6 h-6"})})]})]}),r.jsxs("div",{className:"flex-1 min-h-0 flex items-center justify-center p-4 relative overflow-hidden",children:[s>0&&r.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:r.jsx(el,{className:"w-8 h-8 text-white"})}),r.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:r.jsx(Va,{className:"w-8 h-8 text-white"})})]}),n.length>1&&r.jsx("div",{className:"flex justify-center gap-2 p-4 bg-black/50",children:n.map((f,b)=>r.jsx("button",{onClick:()=>o(b),className:`w-16 h-16 rounded-lg overflow-hidden border-2 transition-colors ${b===s?"border-bambu-green":"border-transparent hover:border-bambu-gray"}`,children:r.jsx("img",{src:se.getArchivePhotoUrl(t,f),alt:`Thumbnail ${b+1}`,className:"w-full h-full object-cover"})},f))})]}),l&&r.jsx(vn,{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:ese,setPrototypeOf:QK,isFrozen:y9e,getPrototypeOf:v9e,getOwnPropertyDescriptor:w9e}=Object;let{freeze:To,seal:Mc,create:I0}=Object,{apply:sI,construct:oI}=typeof Reflect<"u"&&Reflect;To||(To=function(e){return e});Mc||(Mc=function(e){return e});sI||(sI=function(e,n){for(var a=arguments.length,i=new Array(a>2?a-2:0),s=2;s1?n-1:0),i=1;i1?n-1:0),i=1;i2&&arguments[2]!==void 0?arguments[2]:EN;QK&&QK(t,null);let a=e.length;for(;a--;){let i=e[a];if(typeof i=="string"){const s=n(i);s!==i&&(y9e(e)||(e[a]=s),i=s)}t[i]=!0}return t}function P9e(t){for(let e=0;e/gm),E9e=Mc(/\$\{[\w\W]*/gm),D9e=Mc(/^data-[\-\w.\u00B7-\uFFFF]+$/),F9e=Mc(/^aria-[\-\w]+$/),tse=Mc(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),R9e=Mc(/^(?:\w+script|data):/i),L9e=Mc(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),nse=Mc(/^html$/i),I9e=Mc(/^[a-z][.\w]*(-[.\w]+)+$/i);var rY=Object.freeze({__proto__:null,ARIA_ATTR:F9e,ATTR_WHITESPACE:L9e,CUSTOM_ELEMENT:I9e,DATA_ATTR:D9e,DOCTYPE_NAME:nse,ERB_EXPR:M9e,IS_ALLOWED_URI:tse,IS_SCRIPT_OR_DATA:R9e,MUSTACHE_EXPR:j9e,TMPLIT_EXPR:E9e});const k0={element:1,text:3,progressingInstruction:7,comment:8,document:9},O9e=function(){return typeof window>"u"?null:window},z9e=function(e,n){if(typeof e!="object"||typeof e.createPolicy!="function")return null;let a=null;const i="data-tt-policy-suffix";n&&n.hasAttribute(i)&&(a=n.getAttribute(i));const s="dompurify"+(a?"#"+a:"");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}},aY=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function rse(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:O9e();const e=Je=>rse(Je);if(e.version="3.4.0",e.removed=[],!t||!t.document||t.document.nodeType!==k0.document||!t.Element)return e.isSupported=!1,e;let{document:n}=t;const a=n,i=a.currentScript,{DocumentFragment:s,HTMLTemplateElement:o,Node:l,Element:c,NodeFilter:d,NamedNodeMap:u=t.NamedNodeMap||t.MozNamedAttrMap,HTMLFormElement:m,DOMParser:p,trustedTypes:f}=t,b=c.prototype,w=_0(b,"cloneNode"),g=_0(b,"remove"),x=_0(b,"nextSibling"),_=_0(b,"childNodes"),N=_0(b,"parentNode");if(typeof o=="function"){const Je=n.createElement("template");Je.content&&Je.content.ownerDocument&&(n=Je.content.ownerDocument)}let C,P="";const{implementation:T,createNodeIterator:A,createDocumentFragment:F,getElementsByTagName:S}=n,{importNode:M}=a;let z=aY();e.isSupported=typeof ese=="function"&&typeof N=="function"&&T&&T.createHTMLDocument!==void 0;const{MUSTACHE_EXPR:I,ERB_EXPR:H,TMPLIT_EXPR:L,DATA_ATTR:Z,ARIA_ATTR:re,IS_SCRIPT_OR_DATA:J,ATTR_WHITESPACE:de,CUSTOM_ELEMENT:me}=rY;let{IS_ALLOWED_URI:ue}=rY,W=null;const ae=ur({},[...JK,...w3,...S3,..._3,...eY]);let pe=null;const ye=ur({},[...tY,...k3,...nY,...$1]);let Te=Object.seal(I0(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,K=null;const D=Object.seal(I0(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let j=!0,B=!0,X=!1,O=!0,ie=!1,U=!0,G=!1,Y=!1,Q=!1,oe=!1,ee=!1,ge=!1,ce=!0,le=!1;const q="user-content-";let R=!0,ne=!1,xe={},we=null;const Ne=ur({},["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 ve=null;const be=ur({},["audio","video","img","source","image","track"]);let Ee=null;const ze=ur({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),_e="http://www.w3.org/1998/Math/MathML",Oe="http://www.w3.org/2000/svg",Ie="http://www.w3.org/1999/xhtml";let Ke=Ie,rt=!1,st=null;const Re=ur({},[_e,Oe,Ie],y3);let tt=ur({},["mi","mo","mn","ms","mtext"]),Ce=ur({},["annotation-xml"]);const Xe=ur({},["title","style","font","a","script"]);let Ue=null;const fe=["application/xhtml+xml","text/html"],Ae="text/html";let $e=null,Be=null;const nt=n.createElement("form"),gt=function(Le){return Le instanceof RegExp||Le instanceof Function},yt=function(){let Le=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(Be&&Be===Le)){if((!Le||typeof Le!="object")&&(Le={}),Le=Ud(Le),Ue=fe.indexOf(Le.PARSER_MEDIA_TYPE)===-1?Ae:Le.PARSER_MEDIA_TYPE,$e=Ue==="application/xhtml+xml"?y3:EN,W=Xc(Le,"ALLOWED_TAGS")?ur({},Le.ALLOWED_TAGS,$e):ae,pe=Xc(Le,"ALLOWED_ATTR")?ur({},Le.ALLOWED_ATTR,$e):ye,st=Xc(Le,"ALLOWED_NAMESPACES")?ur({},Le.ALLOWED_NAMESPACES,y3):Re,Ee=Xc(Le,"ADD_URI_SAFE_ATTR")?ur(Ud(ze),Le.ADD_URI_SAFE_ATTR,$e):ze,ve=Xc(Le,"ADD_DATA_URI_TAGS")?ur(Ud(be),Le.ADD_DATA_URI_TAGS,$e):be,we=Xc(Le,"FORBID_CONTENTS")?ur({},Le.FORBID_CONTENTS,$e):Ne,$=Xc(Le,"FORBID_TAGS")?ur({},Le.FORBID_TAGS,$e):Ud({}),K=Xc(Le,"FORBID_ATTR")?ur({},Le.FORBID_ATTR,$e):Ud({}),xe=Xc(Le,"USE_PROFILES")?Le.USE_PROFILES:!1,j=Le.ALLOW_ARIA_ATTR!==!1,B=Le.ALLOW_DATA_ATTR!==!1,X=Le.ALLOW_UNKNOWN_PROTOCOLS||!1,O=Le.ALLOW_SELF_CLOSE_IN_ATTR!==!1,ie=Le.SAFE_FOR_TEMPLATES||!1,U=Le.SAFE_FOR_XML!==!1,G=Le.WHOLE_DOCUMENT||!1,oe=Le.RETURN_DOM||!1,ee=Le.RETURN_DOM_FRAGMENT||!1,ge=Le.RETURN_TRUSTED_TYPE||!1,Q=Le.FORCE_BODY||!1,ce=Le.SANITIZE_DOM!==!1,le=Le.SANITIZE_NAMED_PROPS||!1,R=Le.KEEP_CONTENT!==!1,ne=Le.IN_PLACE||!1,ue=Le.ALLOWED_URI_REGEXP||tse,Ke=Le.NAMESPACE||Ie,tt=Le.MATHML_TEXT_INTEGRATION_POINTS||tt,Ce=Le.HTML_INTEGRATION_POINTS||Ce,Te=Le.CUSTOM_ELEMENT_HANDLING||I0(null),Le.CUSTOM_ELEMENT_HANDLING&>(Le.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(Te.tagNameCheck=Le.CUSTOM_ELEMENT_HANDLING.tagNameCheck),Le.CUSTOM_ELEMENT_HANDLING&>(Le.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(Te.attributeNameCheck=Le.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),Le.CUSTOM_ELEMENT_HANDLING&&typeof Le.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&(Te.allowCustomizedBuiltInElements=Le.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),ie&&(B=!1),ee&&(oe=!0),xe&&(W=ur({},eY),pe=I0(null),xe.html===!0&&(ur(W,JK),ur(pe,tY)),xe.svg===!0&&(ur(W,w3),ur(pe,k3),ur(pe,$1)),xe.svgFilters===!0&&(ur(W,S3),ur(pe,k3),ur(pe,$1)),xe.mathMl===!0&&(ur(W,_3),ur(pe,nY),ur(pe,$1))),D.tagCheck=null,D.attributeCheck=null,Le.ADD_TAGS&&(typeof Le.ADD_TAGS=="function"?D.tagCheck=Le.ADD_TAGS:(W===ae&&(W=Ud(W)),ur(W,Le.ADD_TAGS,$e))),Le.ADD_ATTR&&(typeof Le.ADD_ATTR=="function"?D.attributeCheck=Le.ADD_ATTR:(pe===ye&&(pe=Ud(pe)),ur(pe,Le.ADD_ATTR,$e))),Le.ADD_URI_SAFE_ATTR&&ur(Ee,Le.ADD_URI_SAFE_ATTR,$e),Le.FORBID_CONTENTS&&(we===Ne&&(we=Ud(we)),ur(we,Le.FORBID_CONTENTS,$e)),Le.ADD_FORBID_CONTENTS&&(we===Ne&&(we=Ud(we)),ur(we,Le.ADD_FORBID_CONTENTS,$e)),R&&(W["#text"]=!0),G&&ur(W,["html","head","body"]),W.table&&(ur(W,["tbody"]),delete $.tbody),Le.TRUSTED_TYPES_POLICY){if(typeof Le.TRUSTED_TYPES_POLICY.createHTML!="function")throw S0('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof Le.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw S0('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');C=Le.TRUSTED_TYPES_POLICY,P=C.createHTML("")}else C===void 0&&(C=z9e(f,i)),C!==null&&typeof P=="string"&&(P=C.createHTML(""));To&&To(Le),Be=Le}},ot=ur({},[...w3,...S3,...T9e]),Ht=ur({},[..._3,...A9e]),Kt=function(Le){let dt=N(Le);(!dt||!dt.tagName)&&(dt={namespaceURI:Ke,tagName:"template"});const he=EN(Le.tagName),Fe=EN(dt.tagName);return st[Le.namespaceURI]?Le.namespaceURI===Oe?dt.namespaceURI===Ie?he==="svg":dt.namespaceURI===_e?he==="svg"&&(Fe==="annotation-xml"||tt[Fe]):!!ot[he]:Le.namespaceURI===_e?dt.namespaceURI===Ie?he==="math":dt.namespaceURI===Oe?he==="math"&&Ce[Fe]:!!Ht[he]:Le.namespaceURI===Ie?dt.namespaceURI===Oe&&!Ce[Fe]||dt.namespaceURI===_e&&!tt[Fe]?!1:!Ht[he]&&(Xe[he]||!ot[he]):!!(Ue==="application/xhtml+xml"&&st[Le.namespaceURI]):!1},Zt=function(Le){w0(e.removed,{element:Le});try{N(Le).removeChild(Le)}catch{g(Le)}},Yt=function(Le,dt){try{w0(e.removed,{attribute:dt.getAttributeNode(Le),from:dt})}catch{w0(e.removed,{attribute:null,from:dt})}if(dt.removeAttribute(Le),Le==="is")if(oe||ee)try{Zt(dt)}catch{}else try{dt.setAttribute(Le,"")}catch{}},gn=function(Le){let dt=null,he=null;if(Q)Le=""+Le;else{const Ze=v3(Le,/^[\r\n\t ]+/);he=Ze&&Ze[0]}Ue==="application/xhtml+xml"&&Ke===Ie&&(Le=''+Le+"");const Fe=C?C.createHTML(Le):Le;if(Ke===Ie)try{dt=new p().parseFromString(Fe,Ue)}catch{}if(!dt||!dt.documentElement){dt=T.createDocument(Ke,"template",null);try{dt.documentElement.innerHTML=rt?P:Fe}catch{}}const Qe=dt.body||dt.documentElement;return Le&&he&&Qe.insertBefore(n.createTextNode(he),Qe.childNodes[0]||null),Ke===Ie?S.call(dt,G?"html":"body")[0]:G?dt.documentElement:Qe},ln=function(Le){return A.call(Le.ownerDocument||Le,Le,d.SHOW_ELEMENT|d.SHOW_COMMENT|d.SHOW_TEXT|d.SHOW_PROCESSING_INSTRUCTION|d.SHOW_CDATA_SECTION,null)},pt=function(Le){return Le instanceof m&&(typeof Le.nodeName!="string"||typeof Le.textContent!="string"||typeof Le.removeChild!="function"||!(Le.attributes instanceof u)||typeof Le.removeAttribute!="function"||typeof Le.setAttribute!="function"||typeof Le.namespaceURI!="string"||typeof Le.insertBefore!="function"||typeof Le.hasChildNodes!="function")},at=function(Le){return typeof l=="function"&&Le instanceof l};function vt(Je,Le,dt){v0(Je,he=>{he.call(e,Le,dt,Be)})}const _t=function(Le){let dt=null;if(vt(z.beforeSanitizeElements,Le,null),pt(Le))return Zt(Le),!0;const he=$e(Le.nodeName);if(vt(z.uponSanitizeElement,Le,{tagName:he,allowedTags:W}),U&&Le.hasChildNodes()&&!at(Le.firstElementChild)&&go(/<[/\w!]/g,Le.innerHTML)&&go(/<[/\w!]/g,Le.textContent)||U&&Le.namespaceURI===Ie&&he==="style"&&at(Le.firstElementChild)||Le.nodeType===k0.progressingInstruction||U&&Le.nodeType===k0.comment&&go(/<[/\w]/g,Le.data))return Zt(Le),!0;if($[he]||!(D.tagCheck instanceof Function&&D.tagCheck(he))&&!W[he]){if(!$[he]&&De(he)&&(Te.tagNameCheck instanceof RegExp&&go(Te.tagNameCheck,he)||Te.tagNameCheck instanceof Function&&Te.tagNameCheck(he)))return!1;if(R&&!we[he]){const Fe=N(Le)||Le.parentNode,Qe=_(Le)||Le.childNodes;if(Qe&&Fe){const Ze=Qe.length;for(let Ye=Ze-1;Ye>=0;--Ye){const ft=w(Qe[Ye],!0);ft.__removalCount=(Le.__removalCount||0)+1,Fe.insertBefore(ft,x(Le))}}}return Zt(Le),!0}return Le instanceof c&&!Kt(Le)||(he==="noscript"||he==="noembed"||he==="noframes")&&go(/<\/no(script|embed|frames)/i,Le.innerHTML)?(Zt(Le),!0):(ie&&Le.nodeType===k0.text&&(dt=Le.textContent,v0([I,H,L],Fe=>{dt=Ex(dt,Fe," ")}),Le.textContent!==dt&&(w0(e.removed,{element:Le.cloneNode()}),Le.textContent=dt)),vt(z.afterSanitizeElements,Le,null),!1)},Dt=function(Le,dt,he){if(K[dt]||ce&&(dt==="id"||dt==="name")&&(he in n||he in nt))return!1;if(!(B&&!K[dt]&&go(Z,dt))){if(!(j&&go(re,dt))){if(!(D.attributeCheck instanceof Function&&D.attributeCheck(dt,Le))){if(!pe[dt]||K[dt]){if(!(De(Le)&&(Te.tagNameCheck instanceof RegExp&&go(Te.tagNameCheck,Le)||Te.tagNameCheck instanceof Function&&Te.tagNameCheck(Le))&&(Te.attributeNameCheck instanceof RegExp&&go(Te.attributeNameCheck,dt)||Te.attributeNameCheck instanceof Function&&Te.attributeNameCheck(dt,Le))||dt==="is"&&Te.allowCustomizedBuiltInElements&&(Te.tagNameCheck instanceof RegExp&&go(Te.tagNameCheck,he)||Te.tagNameCheck instanceof Function&&Te.tagNameCheck(he))))return!1}else if(!Ee[dt]){if(!go(ue,Ex(he,de,""))){if(!((dt==="src"||dt==="xlink:href"||dt==="href")&&Le!=="script"&&k9e(he,"data:")===0&&ve[Le])){if(!(X&&!go(J,Ex(he,de,"")))){if(he)return!1}}}}}}}return!0},De=function(Le){return Le!=="annotation-xml"&&v3(Le,me)},je=function(Le){vt(z.beforeSanitizeAttributes,Le,null);const{attributes:dt}=Le;if(!dt||pt(Le))return;const he={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:pe,forceKeepAttr:void 0};let Fe=dt.length;for(;Fe--;){const Qe=dt[Fe],{name:Ze,namespaceURI:Ye,value:ft}=Qe,et=$e(Ze),jt=ft;let St=Ze==="value"?jt:N9e(jt);if(he.attrName=et,he.attrValue=St,he.keepAttr=!0,he.forceKeepAttr=void 0,vt(z.uponSanitizeAttribute,Le,he),St=he.attrValue,le&&(et==="id"||et==="name")&&(Yt(Ze,Le),St=q+St),U&&go(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,St)){Yt(Ze,Le);continue}if(et==="attributename"&&v3(St,"href")){Yt(Ze,Le);continue}if(he.forceKeepAttr)continue;if(!he.keepAttr){Yt(Ze,Le);continue}if(!O&&go(/\/>/i,St)){Yt(Ze,Le);continue}ie&&v0([I,H,L],Ot=>{St=Ex(St,Ot," ")});const Lt=$e(Le.nodeName);if(!Dt(Lt,et,St)){Yt(Ze,Le);continue}if(C&&typeof f=="object"&&typeof f.getAttributeType=="function"&&!Ye)switch(f.getAttributeType(Lt,et)){case"TrustedHTML":{St=C.createHTML(St);break}case"TrustedScriptURL":{St=C.createScriptURL(St);break}}if(St!==jt)try{Ye?Le.setAttributeNS(Ye,Ze,St):Le.setAttribute(Ze,St),pt(Le)?Zt(Le):ZK(e.removed)}catch{Yt(Ze,Le)}}vt(z.afterSanitizeAttributes,Le,null)},Ve=function(Le){let dt=null;const he=ln(Le);for(vt(z.beforeSanitizeShadowDOM,Le,null);dt=he.nextNode();)vt(z.uponSanitizeShadowNode,dt,null),_t(dt),je(dt),dt.content instanceof s&&Ve(dt.content);vt(z.afterSanitizeShadowDOM,Le,null)};return e.sanitize=function(Je){let Le=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},dt=null,he=null,Fe=null,Qe=null;if(rt=!Je,rt&&(Je=""),typeof Je!="string"&&!at(Je))if(typeof Je.toString=="function"){if(Je=Je.toString(),typeof Je!="string")throw S0("dirty is not a string, aborting")}else throw S0("toString is not a function");if(!e.isSupported)return Je;if(Y||yt(Le),e.removed=[],typeof Je=="string"&&(ne=!1),ne){if(Je.nodeName){const ft=$e(Je.nodeName);if(!W[ft]||$[ft])throw S0("root node is forbidden and cannot be sanitized in-place")}}else if(Je instanceof l)dt=gn(""),he=dt.ownerDocument.importNode(Je,!0),he.nodeType===k0.element&&he.nodeName==="BODY"||he.nodeName==="HTML"?dt=he:dt.appendChild(he);else{if(!oe&&!ie&&!G&&Je.indexOf("<")===-1)return C&&ge?C.createHTML(Je):Je;if(dt=gn(Je),!dt)return oe?null:ge?P:""}dt&&Q&&Zt(dt.firstChild);const Ze=ln(ne?Je:dt);for(;Fe=Ze.nextNode();)_t(Fe),je(Fe),Fe.content instanceof s&&Ve(Fe.content);if(ne)return Je;if(oe){if(ie){dt.normalize();let ft=dt.innerHTML;v0([I,H,L],et=>{ft=Ex(ft,et," ")}),dt.innerHTML=ft}if(ee)for(Qe=F.call(dt.ownerDocument);dt.firstChild;)Qe.appendChild(dt.firstChild);else Qe=dt;return(pe.shadowroot||pe.shadowrootmode)&&(Qe=M.call(a,Qe,!0)),Qe}let Ye=G?dt.outerHTML:dt.innerHTML;return G&&W["!doctype"]&&dt.ownerDocument&&dt.ownerDocument.doctype&&dt.ownerDocument.doctype.name&&go(nse,dt.ownerDocument.doctype.name)&&(Ye=" `+Ye),ie&&v0([I,H,L],ft=>{Ye=Ex(Ye,ft," ")}),C&&ge?C.createHTML(Ye):Ye},e.setConfig=function(){let Je=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};yt(Je),Y=!0},e.clearConfig=function(){Be=null,Y=!1},e.isValidAttribute=function(Je,Le,dt){Be||yt({});const he=$e(Je),Fe=$e(Le);return Dt(he,Fe,dt)},e.addHook=function(Je,Le){typeof Le=="function"&&w0(z[Je],Le)},e.removeHook=function(Je,Le){if(Le!==void 0){const dt=S9e(z[Je],Le);return dt===-1?void 0:_9e(z[Je],dt,1)[0]}return ZK(z[Je])},e.removeHooks=function(Je){z[Je]=[]},e.removeAllHooks=function(){z=aY()},e}var l5=rse();function Ds(t){this.content=t}Ds.prototype={constructor:Ds,find:function(t){for(var e=0;e>1}};Ds.from=function(t){if(t instanceof Ds)return t;var e=[];if(t)for(var n in t)e.push(n,t[n]);return new Ds(e)};function ase(t,e,n){for(let a=0;;a++){if(a==t.childCount||a==e.childCount)return t.childCount==e.childCount?null:n;let i=t.child(a),s=e.child(a);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=ase(i.content,s.content,n+1);if(o!=null)return o}n+=i.nodeSize}}function ise(t,e,n,a){for(let i=t.childCount,s=e.childCount;;){if(i==0||s==0)return i==s?null:{a:n,b:a};let o=t.child(--i),l=e.child(--s),c=o.nodeSize;if(o==l){n-=c,a-=c;continue}if(!o.sameMarkup(l))return{a:n,b:a};if(o.isText&&o.text!=l.text){let d=0,u=Math.min(o.text.length,l.text.length);for(;de&&a(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),a,i+u)}l=d}}descendants(e){this.nodesBetween(0,this.size,e)}textBetween(e,n,a,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)&&a&&(o?o=!1:s+=a),s+=d},0),s}append(e){if(!e.size)return this;if(!this.size)return e;let n=this.lastChild,a=e.firstChild,i=this.content.slice(),s=0;for(n.isText&&n.sameMarkup(a)&&(i[i.length-1]=n.withText(n.text+a.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))),a.push(l),i+=l.nodeSize),o=c}return new Wt(a,i)}cutByIndex(e,n){return e==n?Wt.empty:e==0&&n==this.content.length?this:new Wt(this.content.slice(e,n))}replaceChild(e,n){let a=this.content[e];if(a==n)return this;let i=this.content.slice(),s=this.size+n.nodeSize-a.nodeSize;return i[e]=n,new Wt(i,s)}addToStart(e){return new Wt([e].concat(this.content),this.size+e.nodeSize)}addToEnd(e){return new Wt(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,a=0;;n++){let i=this.child(n),s=a+i.nodeSize;if(s>=e)return s==e?V1(n+1,s):V1(n,a);a=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 Wt.empty;if(!Array.isArray(n))throw new RangeError("Invalid input for Fragment.fromJSON");return new Wt(n.map(e.nodeFromJSON))}static fromArray(e){if(!e.length)return Wt.empty;let n,a=0;for(let i=0;ithis.type.rank&&(n||(n=e.slice(0,i)),n.push(this),a=!0),n&&n.push(s)}}return n||(n=e.slice()),a||n.push(this),n}removeFromSet(e){for(let n=0;na.type.rank-i.type.rank),n}};ha.none=[];class vP extends Error{}class hn{constructor(e,n,a){this.content=e,this.openStart=n,this.openEnd=a}get size(){return this.content.size-this.openStart-this.openEnd}insertAt(e,n){let a=ose(this.content,e+this.openStart,n);return a&&new hn(a,this.openStart,this.openEnd)}removeBetween(e,n){return new hn(sse(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 hn.empty;let a=n.openStart||0,i=n.openEnd||0;if(typeof a!="number"||typeof i!="number")throw new RangeError("Invalid input for Slice.fromJSON");return new hn(Wt.fromJSON(e,n.content),a,i)}static maxOpen(e,n=!0){let a=0,i=0;for(let s=e.firstChild;s&&!s.isLeaf&&(n||!s.type.spec.isolating);s=s.firstChild)a++;for(let s=e.lastChild;s&&!s.isLeaf&&(n||!s.type.spec.isolating);s=s.lastChild)i++;return new hn(e,a,i)}}hn.empty=new hn(Wt.empty,0,0);function sse(t,e,n){let{index:a,offset:i}=t.findIndex(e),s=t.maybeChild(a),{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(a!=o)throw new RangeError("Removing non-flat range");return t.replaceChild(a,s.copy(sse(s.content,e-i-1,n-i-1)))}function ose(t,e,n,a){let{index:i,offset:s}=t.findIndex(e),o=t.maybeChild(i);if(s==e||o.isText)return a&&!a.canReplace(i,i,n)?null:t.cut(0,e).append(n).append(t.cut(e));let l=ose(o.content,e-s-1,n,o);return l&&t.replaceChild(i,o.copy(l))}function U9e(t,e,n){if(n.openStart>t.depth)throw new vP("Inserted content deeper than insertion position");if(t.depth-n.openStart!=e.depth-n.openEnd)throw new vP("Inconsistent open depths");return lse(t,e,n,0)}function lse(t,e,n,a){let i=t.index(a),s=t.node(a);if(i==e.index(a)&&a=0&&t.isText&&t.sameMarkup(e[n])?e[n]=t.withText(e[n].text+t.text):e.push(t)}function aw(t,e,n,a){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&&(Sg(t.nodeAfter,a),s++));for(let l=s;li&&cI(t,e,i+1),o=a.depth>i&&cI(n,a,i+1),l=[];return aw(null,t,i,l),s&&o&&e.index(i)==n.index(i)?(cse(s,o),Sg(_g(s,dse(t,e,n,a,i+1)),l)):(s&&Sg(_g(s,wP(t,e,i+1)),l),aw(e,n,i,l),o&&Sg(_g(o,wP(n,a,i+1)),l)),aw(a,null,i,l),new Wt(l)}function wP(t,e,n){let a=[];if(aw(null,t,n,a),t.depth>n){let i=cI(t,e,n+1);Sg(_g(i,wP(t,e,n+1)),a)}return aw(e,null,n,a),new Wt(a)}function B9e(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(Wt.from(i));return{start:i.resolveNoCache(t.openStart+n),end:i.resolveNoCache(i.content.size-t.openEnd-n)}}class aS{constructor(e,n,a){this.pos=e,this.path=n,this.parentOffset=a,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 a=this.pos-this.path[this.path.length-1],i=e.child(n);return a?e.child(n).cut(a):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 a=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;a--)if(e.pos<=this.end(a)&&(!n||n(this.node(a))))return new SP(this,e,a);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 a=[],i=0,s=n;for(let o=e;;){let{index:l,offset:c}=o.content.findIndex(s),d=s-c;if(a.push(o,l,i+c),!d||(o=o.child(l),o.isText))break;s=d-1,i+=c+1}return new aS(n,a,s)}static resolveCached(e,n){let a=iY.get(e);if(a)for(let s=0;se&&this.nodesBetween(e,n,s=>(a.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()+")"),use(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,a=Wt.empty,i=0,s=a.childCount){let o=this.contentMatchAt(e).matchFragment(a,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 a;if(n.marks){if(!Array.isArray(n.marks))throw new RangeError("Invalid mark data for Node.fromJSON");a=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,a)}let i=Wt.fromJSON(e,n.content),s=e.nodeType(n.type).create(n.attrs,i,a);return s.type.checkAttrs(s.attrs),s}}cd.prototype.text=void 0;class _P extends cd{constructor(e,n,a,i){if(super(e,n,null,i),!a)throw new RangeError("Empty text nodes are not allowed");this.text=a}toString(){return this.type.spec.toDebugString?this.type.spec.toDebugString(this):use(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 _P(this.type,this.attrs,this.text,e)}withText(e){return e==this.text?this:new _P(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 use(t,e){for(let n=t.length-1;n>=0;n--)e=t[n].type.name+"("+e+")";return e}class Qg{constructor(e){this.validEnd=e,this.next=[],this.wrapCache=[]}static parse(e,n){let a=new V9e(e,n);if(a.next==null)return Qg.empty;let i=mse(a);a.next&&a.err("Unexpected trailing text");let s=Z9e(Q9e(i));return J9e(s,a),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(a){e.push(a);for(let i=0;i{let s=i+(a.validEnd?"*":" ")+" ";for(let o=0;o"+e.indexOf(a.next[o].next);return s}).join(` `)}}Qg.empty=new Qg(!0);class V9e{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 mse(t){let e=[];do e.push(G9e(t));while(t.eat("|"));return e.length==1?e[0]:{type:"choice",exprs:e}}function G9e(t){let e=[];do e.push(W9e(t));while(t.next&&t.next!=")"&&t.next!="|");return e.length==1?e[0]:{type:"seq",exprs:e}}function W9e(t){let e=X9e(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=K9e(t,e);else break;return e}function sY(t){/\D/.test(t.next)&&t.err("Expected number, got '"+t.next+"'");let e=Number(t.next);return t.pos++,e}function K9e(t,e){let n=sY(t),a=n;return t.eat(",")&&(t.next!="}"?a=sY(t):a=-1),t.eat("}")||t.err("Unclosed braced range"),{type:"range",min:n,max:a,expr:e}}function Y9e(t,e){let n=t.nodeTypes,a=n[e];if(a)return[a];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 X9e(t){if(t.eat("(")){let e=mse(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=Y9e(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 Q9e(t){let e=[[]];return i(s(t,0),n()),e;function n(){return e.push([])-1}function a(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 a(l,c),i(s(o.expr,c),c),[a(c)]}else if(o.type=="plus"){let c=n();return i(s(o.expr,l),c),i(s(o.expr,c),c),[a(c)]}else{if(o.type=="opt")return[a(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[a.join(",")]=new Qg(a.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:fse(this.attrs,e)}create(e=null,n,a){if(this.isText)throw new Error("NodeType.create can't construct text nodes");return new cd(this,this.computeAttrs(e),Wt.from(n),ha.setFrom(a))}createChecked(e=null,n,a){return n=Wt.from(n),this.checkContent(n),new cd(this,this.computeAttrs(e),n,ha.setFrom(a))}createAndFill(e=null,n,a){if(e=this.computeAttrs(e),n=Wt.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(Wt.empty,!0);return s?new cd(this,e,n.append(s),ha.setFrom(a)):null}validContent(e){let n=this.contentMatch.matchFragment(e);if(!n||!n.validEnd)return!1;for(let a=0;a-1}allowsMarks(e){if(this.markSet==null)return!0;for(let n=0;na[s]=new xse(s,n,o));let i=n.spec.topNode||"doc";if(!a[i])throw new RangeError("Schema is missing its top node type ('"+i+"')");if(!a.text)throw new RangeError("Every schema needs a 'text' type");for(let s in a.text.attrs)throw new RangeError("The text node type should not have attributes");return a}};function eWe(t,e,n){let a=n.split("|");return i=>{let s=i===null?"null":typeof i;if(a.indexOf(s)<0)throw new RangeError(`Expected value of type ${a} for attribute ${e} on type ${t}, got ${s}`)}}class tWe{constructor(e,n,a){this.hasDefault=Object.prototype.hasOwnProperty.call(a,"default"),this.default=a.default,this.validate=typeof a.validate=="string"?eWe(e,n,a.validate):a.validate}get isRequired(){return!this.hasDefault}}class FA{constructor(e,n,a,i){this.name=e,this.rank=n,this.schema=a,this.spec=i,this.attrs=bse(e,i.attrs),this.excluded=null;let s=hse(this.attrs);this.instance=s?new ha(this,s):null}create(e=null){return!e&&this.instance?this.instance:new ha(this,fse(this.attrs,e))}static compile(e,n){let a=Object.create(null),i=0;return e.forEach((s,o)=>a[s]=new FA(s,i++,n,o)),a}removeFromSet(e){for(var n=0;n-1}}class yse{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=Ds.from(e.nodes),n.marks=Ds.from(e.marks||{}),this.nodes=lY.compile(this.spec.nodes,this),this.marks=FA.compile(this.spec.marks,this);let a=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=a[o]||(a[o]=Qg.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?cY(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==""?[]:cY(this,o.split(" "))}this.nodeFromJSON=i=>cd.fromJSON(this,i),this.markFromJSON=i=>ha.fromJSON(this,i),this.topNodeType=this.nodes[this.spec.topNode||"doc"],this.cached.wrappings=Object.create(null)}node(e,n=null,a,i){if(typeof e=="string")e=this.nodeType(e);else if(e instanceof lY){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,a,i)}text(e,n){let a=this.nodes.text;return new _P(a,a.defaultAttrs,e,ha.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 cY(t,e){let n=[];for(let a=0;a-1)&&n.push(o=c)}if(!o)throw new SyntaxError("Unknown mark type: '"+e[a]+"'")}return n}function nWe(t){return t.tag!=null}function rWe(t){return t.style!=null}let iw=class dI{constructor(e,n){this.schema=e,this.rules=n,this.tags=[],this.styles=[];let a=this.matchedStyles=[];n.forEach(i=>{if(nWe(i))this.tags.push(i);else if(rWe(i)){let s=/[^=]*/.exec(i.style)[0];a.indexOf(s)<0&&a.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 a=new uY(this,n,!1);return a.addAll(e,ha.none,n.from,n.to),a.finish()}parseSlice(e,n={}){let a=new uY(this,n,!0);return a.addAll(e,ha.none,n.from,n.to),hn.maxOpen(a.finish())}matchTag(e,n,a){for(let i=a?this.tags.indexOf(a)+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 a(i){let s=i.priority==null?50:i.priority,o=0;for(;o{a(o=mY(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=>{a(o=mY(o)),o.node||o.ignore||o.mark||(o.node=i)})}return n}static fromSchema(e){return e.cached.domParser||(e.cached.domParser=new dI(e,dI.schemaRules(e)))}};const vse={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},aWe={head:!0,noscript:!0,object:!0,script:!0,style:!0,title:!0},wse={ol:!0,ul:!0},iS=1,uI=2,sw=4;function dY(t,e,n){return e!=null?(e?iS:0)|(e==="full"?uI:0):t&&t.whitespace=="pre"?iS|uI:n&~sw}class G1{constructor(e,n,a,i,s,o){this.type=e,this.attrs=n,this.marks=a,this.solid=i,this.options=o,this.content=[],this.activeMarks=ha.none,this.match=s||(o&sw?null:e.contentMatch)}findWrapping(e){if(!this.match){if(!this.type)return[];let n=this.type.contentMatch.fillBefore(Wt.from(e));if(n)this.match=this.type.contentMatch.matchFragment(n);else{let a=this.type.contentMatch,i;return(i=a.findWrapping(e.type))?(this.match=a,i):null}}return this.match.findWrapping(e.type)}finish(e){if(!(this.options&iS)){let a=this.content[this.content.length-1],i;if(a&&a.isText&&(i=/[ \t\r\n\u000c]+$/.exec(a.text))){let s=a;a.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=Wt.from(this.content);return!e&&this.match&&(n=n.append(this.match.fillBefore(Wt.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&&!vse.hasOwnProperty(e.parentNode.nodeName.toLowerCase())}}class uY{constructor(e,n,a){this.parser=e,this.options=n,this.isOpen=a,this.open=0,this.localPreserveWS=!1;let i=n.topNode,s,o=dY(null,n.preserveWhitespace,0)|(a?sw:0);i?s=new G1(i.type,i.attrs,ha.none,!0,n.topMatch||i.type.contentMatch,o):a?s=new G1(null,null,ha.none,!0,null,o):s=new G1(e.schema.topNodeType,null,ha.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 a=e.nodeValue,i=this.top,s=i.options&uI?"full":this.localPreserveWS||(i.options&iS)>0,{schema:o}=this.parser;if(s==="full"||i.inlineContext(e)||/[^ \t\r\n\u000c]/.test(a)){if(s)if(s==="full")a=a.replace(/\r\n?/g,` `);else if(o.linebreakReplacement&&/[\r\n]/.test(a)&&this.top.findWrapping(o.linebreakReplacement.create())){let l=a.split(/\r?\n|\r/);for(let c=0;c - +