From 76b997fc8a3c75e5bed1ea75106e00bd7cc7ecf8 Mon Sep 17 00:00:00 2001 From: maziggy Date: Thu, 23 Apr 2026 10:03:44 +0200 Subject: [PATCH] fix(slicer): encode file URL in protocol-handler scheme on Windows/Linux MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit "Open in Slicer" emitted `orcaslicer://open?file=` and `bambustudio://open?file=` by plain string concatenation, relying on a stale comment that claimed the browser preserves URLs in the query string. That ignores the slicer's own `url_decode()` on the received query (BS post_init → url_decode + split_str; OrcaSlicer Downloader regex + url_decode), so any already-percent-encoded character — most commonly `%20` from filenames with spaces — decoded to a literal space and the slicer's subsequent HTTP GET returned 0 bytes or 404. All three URL forms now use `encodeURIComponent()` (matching what the macOS `bambustudioopen://` branch was already doing, which is why the bug didn't surface on macOS). Corrected the file-level comment to document the actual invariant. Regression test in slicer.test.ts feeds the exact issue reproduction URL and asserts `%2520` appears in the generated href. --- CHANGELOG.md | 1 + frontend/src/__tests__/utils/slicer.test.ts | 17 +++++++++------ frontend/src/utils/slicer.ts | 21 ++++++++++--------- .../{index-B2bhLHKc.js => index-DbCeLLRM.js} | 2 +- static/index.html | 2 +- 5 files changed, 25 insertions(+), 18 deletions(-) rename static/assets/{index-B2bhLHKc.js => index-DbCeLLRM.js} (98%) diff --git a/CHANGELOG.md b/CHANGELOG.md index abb7c4cbd..229e65086 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,7 @@ All notable changes to Bambuddy will be documented in this file. - **Setup: re-enabling auth could 422 on a password the form no longer needs** — after disabling authentication and re-enabling it (common when switching between local auth and LDAP, or recovering from a bad config), the setup form still sends `admin_password` in the body even though the backend route ignores it when an admin user already exists. The `SetupRequest` Pydantic schema enforced password complexity (uppercase + lowercase + digit + special char) unconditionally, so any existing password that predated the complexity rule — or a legitimate LDAP-mode placeholder — triggered `422 Value error, Password must contain at least one special character` before the route body could decide to ignore the field. Complexity validation has moved out of the schema and into the route body, scoped to the branch that actually creates a new local admin. Re-enabling auth with an existing admin (or any LDAP user) now accepts whatever the form sends; fresh first-time setup still rejects weak passwords with a clear 400. Two regression tests added in `test_auth_api.py`: weak password rejected at setup when creating the first admin, weak/placeholder password accepted when an admin already exists. - **Queue: batch (quantity>1) double-dispatched onto the same printer** — scheduling an ASAP print with `quantity > 1` could end up with two queue items in `'printing'` status for the same printer, surfaced in the logs as `BUG: Multiple queue items in 'printing' status for printer N`. The scheduler's in-memory `busy_printers` set was seeded empty each tick and only populated after `_start_print` succeeded in the current iteration, so on the next tick (30 s later) `_is_printer_idle()` read the printer's live MQTT state — which on H2D / P1 series lags several seconds behind the print command and still reported `IDLE` / `FINISH` — and dispatched the second batch item onto the already-running printer. `check_queue()` now queries `PrintQueueItem` for `status='printing'` rows and seeds `busy_printers` with their printer IDs before iterating pending items, so any printer with an outstanding dispatched job is excluded regardless of what MQTT currently reports. Regression covered in `test_phantom_print_hardening.py` (`TestBusyPrinterSeedingFromPrintingItems`): seeding query returns printers with `'printing'` rows only, returns empty when none exist, and end-to-end `check_queue()` does not call `_start_print` for a pending item whose printer already has a `'printing'` row even when `_is_printer_idle()` is forced `True`. - **Queue: active-item progress bar flashed 100% before dropping to 0%** — immediately after a queue item was dispatched, the per-item progress bar on the Queue page showed 100% (or whatever the prior print's final `mc_percent` was) for the few seconds between dispatch and the printer's MQTT state transitioning to `RUNNING`. Frontend `QueuePage.tsx` read `status.progress` directly from the printer's live MQTT snapshot, which carries over the last reported value from the previous print until the new one starts ticking. The progress bar, remaining time, ETA, and layer counter are now gated on `status.state` being `RUNNING` or `PAUSE`; in any other state (including `FINISH` from the prior print, `IDLE`, or `PREPARE` while heating) the bar renders at 0% with no stale ETA/layer values. +- **"Open in Slicer" fails on Windows / Linux for any filename containing spaces or special characters** ([#1059](https://github.com/maziggy/bambuddy/issues/1059)) — clicking "Open in Slicer" from the File Manager or Archives page produced one of three symptoms depending on the file: `.3mf` files opened Bambu Studio / OrcaSlicer but the app showed "Importing to Bambu Studio failed. Please download the file and open it manually" (the file on disk was 0 bytes); `.stl` files greyed the button out; `.step` couldn't be previewed at all. The protocol-handler URL emitted by `frontend/src/utils/slicer.ts` for OrcaSlicer (`orcaslicer://open?file=`) and Windows/Linux Bambu Studio (`bambustudio://open?file=`) was built by plain string concatenation with no `encodeURIComponent()` — the macOS `bambustudioopen://` branch was already encoding correctly, which is why macOS users didn't see this. A stale comment block in the file claimed the browser preserves the URL in the query string so no encoding is needed; that's true for the browser-to-OS handoff but ignores that the slicer itself calls `url_decode()` on the received query (BS `post_init()` calls `url_decode` then `split_str`; OrcaSlicer's Downloader regex-extracts then `url_decode`). Any already-percent-encoded character in the download URL — most commonly `%20` from filenames with spaces, which Bambuddy's archive paths produce naturally — decoded to a literal space and the slicer's subsequent HTTP GET came back 0 bytes or 404. All three URL forms now `encodeURIComponent()` the file URL, so the slicer sees the correctly-encoded URL after its own `url_decode`. The comment block is corrected to document the actual invariant. Regression test in `slicer.test.ts` feeds the exact issue reproduction URL (`Toothpick%20Launcher%20Print-in-Place.3mf`) and asserts `%2520` appears in the generated `orcaslicer://` href — so any future refactor that drops the encoding fails CI. Thanks to @jsapede for the double-encoding diagnosis and @AllanonBrooks and @lunaticds for the original reports. ## [0.2.3.2] - 2020-04-22 diff --git a/frontend/src/__tests__/utils/slicer.test.ts b/frontend/src/__tests__/utils/slicer.test.ts index 94016e366..1a7d96dfe 100644 --- a/frontend/src/__tests__/utils/slicer.test.ts +++ b/frontend/src/__tests__/utils/slicer.test.ts @@ -51,7 +51,7 @@ describe('slicer utility', () => { expect(appendSpy).toHaveBeenCalled(); expect(createdLink.href).toContain('bambustudio://open?file='); - expect(createdLink.href).toContain('http://localhost:8000/file.3mf'); + expect(createdLink.href).toContain(encodeURIComponent('http://localhost:8000/file.3mf')); expect(clickSpy).toHaveBeenCalled(); expect(removeSpy).toHaveBeenCalled(); }); @@ -78,15 +78,20 @@ describe('slicer utility', () => { expect(createdLink.href).toContain('open?file='); }); - it('does not encode the file URL for orcaslicer', () => { + it('encodes filenames with spaces so the slicer receives %20 after url_decode (issue #1059)', () => { vi.spyOn(navigator, 'userAgent', 'get').mockReturnValue('Mozilla/5.0 (Windows NT 10.0)'); - const url = 'http://localhost:8000/api/v1/archives/1/file/My Model.3mf'; + // A download URL that already contains percent-encoded spaces — this is how + // Bambuddy emits archive paths (the filename in the URL is URL-path-encoded). + const url = 'http://localhost:8000/api/v1/archives/1/dl/TOKEN/Toothpick%20Launcher%20Print-in-Place.3mf'; openInSlicer(url, 'orcaslicer'); - // The href should contain the raw URL (browser may normalize it but it should not be double-encoded) + // Each %20 in the input must become %2520 in the href so that after the + // slicer's own url_decode() it comes back as %20 (preserving the original + // URL). Without this, the slicer would decode %20 → literal space and its + // subsequent HTTP fetch would fail. expect(createdLink.href).toContain('orcaslicer://open?file='); - // Should NOT contain %253A (double-encoded colon) - expect(createdLink.href).not.toContain('%253A'); + expect(createdLink.href).toContain('Toothpick%2520Launcher%2520Print-in-Place.3mf'); + expect(createdLink.href).not.toContain('Toothpick%20Launcher'); }); it('defaults to bambu_studio when no slicer specified', () => { diff --git a/frontend/src/utils/slicer.ts b/frontend/src/utils/slicer.ts index c2f21ebb5..a30d7a68c 100644 --- a/frontend/src/utils/slicer.ts +++ b/frontend/src/utils/slicer.ts @@ -15,9 +15,13 @@ * - (orcaslicer|bambustudio|...)://open?file= * - bambustudioopen:// * - * Key insight: Using ?file= query format, the browser's URL parser preserves - * http:// in the query string without any encoding. Only the macOS-specific - * bambustudioopen:// format needs encodeURIComponent (BS calls url_decode). + * Key insight: every form needs encodeURIComponent on the file URL, because + * the slicer calls url_decode() on the received query (post_init calls + * url_decode then split_str; MacOpenURL strips the prefix then url_decode; + * OrcaSlicer's Downloader regex-extracts then url_decode). Without encoding, + * any already-percent-encoded character in the download URL (most commonly + * %20 in filenames with spaces) decodes to a literal space and the slicer's + * subsequent HTTP fetch fails with a 0-byte body or 404. See issue #1059. */ export type SlicerType = 'bambu_studio' | 'orcaslicer'; @@ -51,22 +55,19 @@ export function detectPlatform(): Platform { export function openInSlicer(downloadUrl: string, slicer: SlicerType = 'bambu_studio'): void { let url: string; + const encoded = encodeURIComponent(downloadUrl); if (slicer === 'orcaslicer') { - // OrcaSlicer: ?file= query format — http:// preserved in query string - url = `orcaslicer://open?file=${downloadUrl}`; + url = `orcaslicer://open?file=${encoded}`; } else { const platform = detectPlatform(); if (platform === 'macos') { // macOS only: bambustudioopen scheme via MacOpenURL() callback. - // Must encode because bare http:// in authority gets mangled by browser. - // BS calls url_decode() after stripping "bambustudioopen://" prefix. - url = `bambustudioopen://${encodeURIComponent(downloadUrl)}`; + url = `bambustudioopen://${encoded}`; } else { // Windows/Linux: bambustudio://open?file= via post_init() CLI args. - // The ?file= query format preserves http:// without encoding. // IMPORTANT: On Linux, BS only handles "bambustudio://open" prefix — // it does NOT process "bambustudioopen://" (that's macOS-only). - url = `bambustudio://open?file=${downloadUrl}`; + url = `bambustudio://open?file=${encoded}`; } } diff --git a/static/assets/index-B2bhLHKc.js b/static/assets/index-DbCeLLRM.js similarity index 98% rename from static/assets/index-B2bhLHKc.js rename to static/assets/index-DbCeLLRM.js index 33b6b9afa..dba2e6e0d 100644 --- a/static/assets/index-B2bhLHKc.js +++ b/static/assets/index-DbCeLLRM.js @@ -8541,7 +8541,7 @@ ${o("inventory.assignProfileMismatchMessage",{spoolProfile:C.spoolProfile||o("co flex items-center justify-center gap-1 px-3 py-1.5 rounded-lg text-xs font-medium transition-colors ${Jt&&k("printers:control")?Ht?"bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30":"bg-yellow-500/20 text-yellow-400 hover:bg-yellow-500/30":"bg-bambu-dark text-bambu-gray/50 cursor-not-allowed"} - `,title:k("printers:control")?N(Ht?"printers.resume":"printers.pause"):N("printers.permission.noControl"),children:[Ht?a.jsx(ns,{className:"w-3 h-3"}):a.jsx(rS,{className:"w-3 h-3"}),N(Ht?"printers.resume":"printers.pause")]})]})]})]})})(),(ma?.length>0||Ue.vt_tray.length>0)&&r==="expanded"&&(()=>{const lt=ma.filter(ct=>ct.tray.length>1),Ht=ma.filter(ct=>ct.tray.length===1),Jt=t.nozzle_count===2||Ue?.temperatures?.nozzle_2!==void 0;return a.jsxs("div",{className:"mt-3",children:[a.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[a.jsx("span",{className:"text-[10px] uppercase tracking-wider text-bambu-gray font-medium",children:N("printers.filaments")}),a.jsx("div",{className:"flex-1 h-px bg-bambu-dark-tertiary/30"})]}),a.jsxs("div",{className:"space-y-3",children:[lt.length>0&&a.jsx("div",{className:"grid grid-cols-2 gap-3",children:lt.map(ct=>{const Un=Ha[String(ct.id)],Tr=ct.id>=128?ct.id-128:ct.id,ar=Un!==void 0?Un:Tr,Lr=ar===1,Da=ar===0;return a.jsxs("div",{className:"p-2.5 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary/30",children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsxs("div",{className:"flex items-center gap-1.5",children:[a.jsx(uK,{ams:ct,printerId:t.id,label:Ul(ct.id,ct.tray.length),amsLabels:Nn,canEdit:k("printers:update"),onSaved:bn,children:a.jsx("span",{className:"text-[10px] text-white font-medium cursor-default select-none",children:Nn?.[ct.id]||Ul(ct.id,ct.tray.length)})}),Jt&&(Lr||Da)&&a.jsx(iK,{side:Lr?"L":"R"})]}),(ct.humidity!=null||ct.temp!=null)&&a.jsxs("div",{className:"flex items-center gap-1.5 max-[550px]:flex-col max-[550px]:items-start",children:[ct.humidity!=null&&a.jsx(oK,{humidity:ct.humidity,goodThreshold:s?.humidityGood,fairThreshold:s?.humidityFair,onClick:()=>Zt({amsId:ct.id,amsLabel:Ul(ct.id,ct.tray.length),mode:"humidity"}),compact:!0}),ct.temp!=null&&a.jsx(lK,{temp:ct.temp,goodThreshold:s?.tempGood,fairThreshold:s?.tempFair,onClick:()=>Zt({amsId:ct.id,amsLabel:Ul(ct.id,ct.tray.length),mode:"temperature"}),compact:!0}),Ue.supports_drying&&(ct.module_type==="n3f"||ct.module_type==="n3s")&&k("printers:control")&&a.jsx("button",{disabled:!!(ct.dry_sf_reason?.length&&ct.dry_time===0),onClick:rn=>{if(ct.dry_time>0)Ts.mutate(ct.id);else if(Me===ct.id)Oe(null);else{const Na=(ct.tray.find(Cl=>Cl.tray_type)?.tray_type||"PLA").split(" ")[0].toUpperCase(),ai=b[Na]||b.PLA,mi=ct.module_type;tt(Na),ze(ai[mi]||ai.n3f),qe(mi==="n3s"?ai.n3s_hours:ai.n3f_hours),de(!1),$e(ct.module_type),Oe(ct.id);const Ys=rn.currentTarget.getBoundingClientRect();Be({top:Ys.bottom+4,left:Math.max(8,Ys.right-240)})}},className:`flex items-center gap-0.5 px-1 py-0.5 rounded text-[9px] transition-colors ${ct.dry_time>0?"bg-amber-500/20 text-amber-400":ct.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:ct.dry_time>0?N("printers.drying.stop"):ct.dry_sf_reason?.length?N("printers.drying.powerRequired"):N("printers.drying.start"),children:a.jsx(Hu,{className:"w-3 h-3"})})]})]}),ct.dry_time>0&&a.jsxs("div",{className:"flex items-center gap-2 px-2 py-1 mb-1 bg-amber-500/10 border border-amber-500/20 rounded text-[9px]",children:[a.jsx(Hu,{className:"w-3 h-3 text-amber-400 shrink-0"}),a.jsx("span",{className:"text-amber-400 font-medium",children:N("printers.drying.active")}),a.jsx("span",{className:"text-amber-300/70",children:N("printers.drying.timeRemaining",{time:ct.dry_time>=60?`${Math.floor(ct.dry_time/60)}h ${ct.dry_time%60}m`:`${ct.dry_time}m`})}),a.jsx("button",{onClick:()=>Ts.mutate(ct.id),disabled:Ts.isPending,className:"ml-auto text-amber-400 hover:text-amber-300 transition-colors disabled:opacity-50",title:N("printers.drying.stop"),children:a.jsx(Bt,{className:"w-3 h-3"})})]}),a.jsx("div",{className:"grid grid-cols-4 gap-1.5",children:[0,1,2,3].map(rn=>{const En=ct.tray[rn]||ct.tray.find(zn=>zn.id===rn),Na=En?.tray_type&&En.remain>=0,ai=!En?.tray_type,mi=ct.id*4+rn,Ys=Br===mi,Cl=En?.tray_info_idx?St?.[En.tray_info_idx]:null,ha=Pt?.[mi],Hi=(En?.tray_uuid||En?.tag_uid||Vu(t.serial_number,ct.id,rn))?.toUpperCase(),Pl=Hi?l?.[Hi]:void 0,qi=tN(Pl),Qs=u?.(t.id,ct.id,rn),Pc=(()=>{const zn=Qs?.spool;return zn&&zn.label_weight>0&&zn.weight_used!=null?Math.round(Math.max(0,zn.label_weight-zn.weight_used)/zn.label_weight*100):null})(),pa=Pc===0&&Na&&En.remain>0?null:Pc,ko=qi??pa??(Na?En.remain:null),Gy=qi!==null?"spoolman":pa!==null?"inventory":Na?"ams":void 0,ya=En?.tray_type?{vendor:ID(En)?"Bambu Lab":"Generic",profile:ha?.preset_name||Cl?.name||Qs?.spool?.slicer_filament_name||En.tray_sub_brands||En.tray_type,colorName:rc(En.tray_color||""),colorHex:En.tray_color||null,kFactor:LD(En.k),fillLevel:ko,trayUuid:En.tray_uuid||null,tagUid:En.tag_uid||null,fillSource:Gy}:null,ou=Yo?.amsId===ct.id&&Yo?.slotId===rn,$p=a.jsxs("div",{className:`bg-bambu-dark-tertiary rounded p-1 text-center ${ai?"opacity-50":""} ${Ys?"ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark":""}`,children:[a.jsx(RD,{trayColor:En?.tray_color,trayType:En?.tray_type,isEmpty:ai,slotNumber:rn+1}),a.jsx("div",{className:"text-[9px] text-white font-bold truncate",children:En?.tray_type||"—"}),a.jsx("div",{className:"mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden",children:ko!==null&&ko>=0&&!ai&&En&&a.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${ko}%`,backgroundColor:Ox(ko)}})})]});return a.jsxs("div",{className:"relative group",children:[ou&&a.jsx("div",{className:"absolute inset-0 bg-bambu-dark-tertiary/80 rounded flex items-center justify-center z-20",children:a.jsx(lr,{className:"w-4 h-4 text-bambu-green animate-spin"})}),Ue?.state!=="RUNNING"&&a.jsx("button",{onClick:zn=>{zn.stopPropagation(),_n(Sn?.amsId===ct.id&&Sn?.slotId===rn?null:{amsId:ct.id,slotId:rn})},className:"absolute -top-1 -right-1 w-4 h-4 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity z-10 hover:bg-bambu-dark-tertiary",title:N("printers.slotOptions"),children:a.jsx(Jh,{className:"w-2.5 h-2.5 text-bambu-gray"})}),Ue?.state!=="RUNNING"&&Sn?.amsId===ct.id&&Sn?.slotId===rn&&a.jsx("div",{className:"absolute top-full left-0 mt-1 z-50 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl py-1 min-w-[120px]",children:a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-xs flex items-center gap-2 ${k("printers:ams_rfid")?"text-white hover:bg-bambu-dark-tertiary":"text-bambu-gray/50 cursor-not-allowed"}`,onClick:zn=>{zn.stopPropagation(),k("printers:ams_rfid")&&(xn.mutate({amsId:ct.id,slotId:rn}),_n(null))},disabled:ou||!k("printers:ams_rfid"),title:k("printers:ams_rfid")?void 0:N("printers.permission.noAmsRfid"),children:[a.jsx(lr,{className:`w-3 h-3 ${ou?"animate-spin":""}`}),N("printers.rfid.reread")]})}),ya?a.jsx(jD,{data:ya,spoolman:{enabled:o,linkedSpoolId:Hi?l?.[Hi]?.id:void 0,spoolmanUrl:c,syncMode:d,onLinkSpool:o?()=>{const zn=(ya.trayUuid||ya.tagUid||Vu(t.serial_number,ct.id,rn)).toUpperCase();Xt({tagUid:ya.tagUid||zn,trayUuid:ya.trayUuid||"",printerId:t.id,amsId:ct.id,trayId:rn})}:void 0,onUnlinkSpool:Pl?.id?()=>Ps.mutate(Pl.id):void 0},inventory:o?void 0:(()=>{const zn=u?.(t.id,ct.id,rn);return{assignedSpool:zn?.spool?{id:zn.spool.id,material:zn.spool.material,brand:zn.spool.brand,color_name:zn.spool.color_name,remainingWeightGrams:Math.max(0,Math.round(zn.spool.label_weight-zn.spool.weight_used))}:null,onAssignSpool:ya.vendor!=="Bambu Lab"?()=>vn({printerId:t.id,amsId:ct.id,trayId:rn,trayInfo:{type:En?.tray_type||ya.profile,material:En?.tray_type??void 0,profile:ya.profile,color:ya.colorHex||"",location:`${Ul(ct.id,ct.tray.length)} Slot ${rn+1}`}}):void 0,onUnassignSpool:zn&&ya.vendor!=="Bambu Lab"?()=>m?.(t.id,ct.id,rn):void 0}})(),configureSlot:{enabled:k("printers:control"),onConfigure:()=>at({amsId:ct.id,trayId:rn,trayCount:ct.tray.length,trayType:En?.tray_type||void 0,trayColor:En?.tray_color||void 0,traySubBrands:En?.tray_sub_brands||void 0,trayInfoIdx:En?.tray_info_idx||void 0,extruderId:Un,caliIdx:En?.cali_idx,savedPresetId:ha?.preset_id})},children:$p}):a.jsx(MD,{configureSlot:{enabled:k("printers:control"),onConfigure:()=>at({amsId:ct.id,trayId:rn,trayCount:ct.tray.length,extruderId:Un})},inventory:o?void 0:{onAssignSpool:()=>vn({printerId:t.id,amsId:ct.id,trayId:rn,trayInfo:{type:"",color:"",location:`${Ul(ct.id,ct.tray.length)} Slot ${rn+1}`}})},children:$p})]},rn)})})]},ct.id)})}),(Ht.length>0||Ue.vt_tray.length>0)&&a.jsxs("div",{className:"grid grid-cols-4 gap-3",children:[Ht.map(ct=>{const Un=Ha[String(ct.id)],Tr=ct.id>=128?ct.id-128:ct.id,ar=Un!==void 0?Un:Tr,Lr=ar===1,Da=ar===0,rn=ct.tray[0],En=rn?.tray_type&&rn.remain>=0,Na=!rn?.tray_type,ai=Ag(ct.id,rn?.id??0,!1),mi=Br===ai,Ys=rn?.tray_info_idx?St?.[rn.tray_info_idx]:null,Cl=Pt?.[ai],ha=rn?.id??0,Hi=(rn?.tray_uuid||rn?.tag_uid||Vu(t.serial_number,ct.id,ha))?.toUpperCase(),Pl=Hi?l?.[Hi]:void 0,qi=tN(Pl),Qs=u?.(t.id,ct.id,ha),Pc=(()=>{const zn=Qs?.spool;return zn&&zn.label_weight>0&&zn.weight_used!=null?Math.round(Math.max(0,zn.label_weight-zn.weight_used)/zn.label_weight*100):null})(),pa=Pc===0&&En&&rn.remain>0?null:Pc,ko=qi??pa??(En?rn.remain:null),Gy=qi!==null?"spoolman":pa!==null?"inventory":En?"ams":void 0,ya=rn?.tray_type?{vendor:ID(rn)?"Bambu Lab":"Generic",profile:Cl?.preset_name||Ys?.name||Qs?.spool?.slicer_filament_name||rn.tray_sub_brands||rn.tray_type,colorName:rc(rn.tray_color||""),colorHex:rn.tray_color||null,kFactor:LD(rn.k),fillLevel:ko,trayUuid:rn.tray_uuid||null,tagUid:rn.tag_uid||null,fillSource:Gy}:null,ou=Yo?.amsId===ct.id&&Yo?.slotId===ha,$p=a.jsxs("div",{className:`bg-bambu-dark-tertiary rounded p-1 text-center ${Na?"opacity-50":""} ${mi?"ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark":""}`,children:[a.jsx(RD,{trayColor:rn?.tray_color,trayType:rn?.tray_type,isEmpty:Na,slotNumber:1}),a.jsx("div",{className:"text-[9px] text-white font-bold truncate",children:rn?.tray_type||"—"}),a.jsx("div",{className:"mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden",children:ko!==null&&ko>=0&&!Na&&a.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${ko}%`,backgroundColor:Ox(ko)}})})]});return a.jsxs("div",{className:"p-2.5 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary/30",children:[a.jsxs("div",{className:"flex items-center gap-1 mb-2",children:[a.jsx(uK,{ams:ct,printerId:t.id,label:Ul(ct.id,ct.tray.length),amsLabels:Nn,canEdit:k("printers:update"),onSaved:bn,children:a.jsx("span",{className:"text-[10px] text-white font-medium cursor-default select-none",children:Nn?.[ct.id]||Ul(ct.id,ct.tray.length)})}),Jt&&(Lr||Da)&&a.jsx(iK,{side:Lr?"L":"R"}),Ue.supports_drying&&(ct.module_type==="n3f"||ct.module_type==="n3s")&&k("printers:control")&&a.jsx("div",{className:"relative ml-auto",children:a.jsx("button",{onClick:zn=>{if(ct.dry_time>0)Ts.mutate(ct.id);else if(Me===ct.id)Oe(null);else{const Um=(ct.tray.find($S=>$S.tray_type)?.tray_type||"PLA").split(" ")[0].toUpperCase(),Vp=b[Um]||b.PLA,Wy=ct.module_type;tt(Um),ze(Vp[Wy]||Vp.n3f),qe(Wy==="n3s"?Vp.n3s_hours:Vp.n3f_hours),de(!1),$e(ct.module_type),Oe(ct.id);const Ky=zn.currentTarget.getBoundingClientRect();Be({top:Ky.bottom+4,left:Math.max(8,Ky.right-240)})}},className:`flex items-center gap-0.5 px-1 py-0.5 rounded text-[9px] transition-colors ${ct.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:ct.dry_time>0?N("printers.drying.stop"):N("printers.drying.start"),children:a.jsx(Hu,{className:"w-3 h-3"})})})]}),ct.dry_time>0&&a.jsxs("div",{className:"flex items-center gap-1.5 px-2 py-1 mb-1 bg-amber-500/10 border border-amber-500/20 rounded text-[9px] whitespace-nowrap overflow-hidden",children:[a.jsx(Hu,{className:"w-3 h-3 text-amber-400 shrink-0"}),a.jsx("span",{className:"text-amber-300/70 text-[8px] truncate",children:ct.dry_time>=60?`${Math.floor(ct.dry_time/60)}h ${ct.dry_time%60}m`:`${ct.dry_time}m`}),a.jsx("button",{onClick:()=>Ts.mutate(ct.id),disabled:Ts.isPending,className:"ml-auto text-amber-400 hover:text-amber-300 transition-colors disabled:opacity-50 shrink-0",title:N("printers.drying.stop"),children:a.jsx(Bt,{className:"w-3 h-3"})})]}),a.jsxs("div",{className:"flex gap-1.5 max-[550px]:flex-col max-[550px]:items-start",children:[a.jsxs("div",{className:"relative group flex-1 max-[550px]:w-full",children:[ou&&a.jsx("div",{className:"absolute inset-0 bg-bambu-dark-tertiary/80 rounded flex items-center justify-center z-20",children:a.jsx(lr,{className:"w-4 h-4 text-bambu-green animate-spin"})}),Ue?.state!=="RUNNING"&&a.jsx("button",{onClick:zn=>{zn.stopPropagation(),_n(Sn?.amsId===ct.id&&Sn?.slotId===ha?null:{amsId:ct.id,slotId:ha})},className:"absolute -top-1 -right-1 w-4 h-4 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity z-10 hover:bg-bambu-dark-tertiary",title:N("printers.slotOptions"),children:a.jsx(Jh,{className:"w-2.5 h-2.5 text-bambu-gray"})}),Ue?.state!=="RUNNING"&&Sn?.amsId===ct.id&&Sn?.slotId===ha&&a.jsx("div",{className:"absolute top-full left-0 mt-1 z-50 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl py-1 min-w-[120px]",children:a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-xs flex items-center gap-2 ${k("printers:ams_rfid")?"text-white hover:bg-bambu-dark-tertiary":"text-bambu-gray/50 cursor-not-allowed"}`,onClick:zn=>{zn.stopPropagation(),k("printers:ams_rfid")&&(xn.mutate({amsId:ct.id,slotId:ha}),_n(null))},disabled:ou||!k("printers:ams_rfid"),title:k("printers:ams_rfid")?void 0:N("printers.permission.noAmsRfid"),children:[a.jsx(lr,{className:`w-3 h-3 ${ou?"animate-spin":""}`}),N("printers.rfid.reread")]})}),ya?a.jsx(jD,{data:ya,spoolman:{enabled:o,linkedSpoolId:Hi?l?.[Hi]?.id:void 0,spoolmanUrl:c,syncMode:d,onLinkSpool:o?()=>{const zn=(ya.trayUuid||ya.tagUid||Vu(t.serial_number,ct.id,ha)).toUpperCase();Xt({tagUid:ya.tagUid||zn,trayUuid:ya.trayUuid||"",printerId:t.id,amsId:ct.id,trayId:ha})}:void 0,onUnlinkSpool:Pl?.id?()=>Ps.mutate(Pl.id):void 0},inventory:o?void 0:(()=>{const zn=u?.(t.id,ct.id,ha);return{assignedSpool:zn?.spool?{id:zn.spool.id,material:zn.spool.material,brand:zn.spool.brand,color_name:zn.spool.color_name,remainingWeightGrams:Math.max(0,Math.round(zn.spool.label_weight-zn.spool.weight_used))}:null,onAssignSpool:ya.vendor!=="Bambu Lab"?()=>vn({printerId:t.id,amsId:ct.id,trayId:ha,trayInfo:{type:rn?.tray_type||ya.profile,material:rn?.tray_type??void 0,profile:ya.profile,color:ya.colorHex||"",location:Ul(ct.id,ct.tray.length)}}):void 0,onUnassignSpool:zn&&ya.vendor!=="Bambu Lab"?()=>m?.(t.id,ct.id,ha):void 0}})(),configureSlot:{enabled:k("printers:control"),onConfigure:()=>at({amsId:ct.id,trayId:ha,trayCount:ct.tray.length,trayType:rn?.tray_type||void 0,trayColor:rn?.tray_color||void 0,traySubBrands:rn?.tray_sub_brands||void 0,trayInfoIdx:rn?.tray_info_idx||void 0,extruderId:Un,caliIdx:rn?.cali_idx,savedPresetId:Cl?.preset_id})},children:$p}):a.jsx(MD,{configureSlot:{enabled:k("printers:control"),onConfigure:()=>at({amsId:ct.id,trayId:ha,trayCount:ct.tray.length,extruderId:Un})},inventory:o?void 0:{onAssignSpool:()=>vn({printerId:t.id,amsId:ct.id,trayId:ha,trayInfo:{type:"",color:"",location:Ul(ct.id,ct.tray.length)}})},children:$p})]}),(ct.humidity!=null||ct.temp!=null)&&a.jsxs("div",{className:"flex flex-col justify-center gap-1 shrink-0 max-[550px]:w-full",children:[ct.temp!=null&&a.jsx(lK,{temp:ct.temp,goodThreshold:s?.tempGood,fairThreshold:s?.tempFair,onClick:()=>Zt({amsId:ct.id,amsLabel:Ul(ct.id,ct.tray.length),mode:"temperature"}),compact:!0}),ct.humidity!=null&&a.jsx(oK,{humidity:ct.humidity,goodThreshold:s?.humidityGood,fairThreshold:s?.humidityFair,onClick:()=>Zt({amsId:ct.id,amsLabel:Ul(ct.id,ct.tray.length),mode:"humidity"}),compact:!0})]})]})]},ct.id)}),Ue.vt_tray.length>0&&a.jsxs("div",{className:`p-2.5 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary/30 ${Ue.vt_tray.length===1?"max-w-[50%]":""}`,children:[a.jsx("div",{className:"flex items-center gap-1 mb-2",children:a.jsx("span",{className:"text-[10px] text-white font-medium",children:N("printers.external")})}),a.jsx("div",{className:`grid ${Ue.vt_tray.length>1?"grid-cols-2":"grid-cols-1"} gap-1.5`,children:[...Ue.vt_tray].sort((ct,Un)=>(ct.id??254)-(Un.id??254)).map(ct=>{const Un=ct.id??254,Tr=Jt&&Br===254?Un===254&&Ue.active_extruder===1||Un===255&&Ue.active_extruder===0:Br===Un,ar=Un-254,Lr=Jt?N(Un===254?"printers.extL":"printers.extR"):"",Da=ct.tray_info_idx?St?.[ct.tray_info_idx]:null,rn=Pt?.[1020+ar],En=(ct.tray_uuid||ct.tag_uid||Vu(t.serial_number,255,ar))?.toUpperCase(),Na=En?l?.[En]:void 0,ai=tN(Na),mi=u?.(t.id,255,ar),Ys=(()=>{const pa=mi?.spool;return pa&&pa.label_weight>0&&pa.weight_used!=null?Math.round(Math.max(0,pa.label_weight-pa.weight_used)/pa.label_weight*100):null})(),Cl=ct.tray_type&&ct.remain>=0,ha=Ys===0&&Cl&&ct.remain>0?null:Ys,Hi=ai??ha??(Cl?ct.remain:null),Pl=ai!==null?"spoolman":ha!==null?"inventory":Cl?"ams":void 0,qi={vendor:ID(ct)?"Bambu Lab":"Generic",profile:rn?.preset_name||Da?.name||mi?.spool?.slicer_filament_name||ct.tray_sub_brands||ct.tray_type||"Unknown",colorName:rc(ct.tray_color||""),colorHex:ct.tray_color||null,kFactor:LD(ct.k),fillLevel:Hi,trayUuid:ct.tray_uuid||null,tagUid:ct.tag_uid||null,fillSource:Pl},Qs=!ct.tray_type,Pc=a.jsxs("div",{className:`bg-bambu-dark-tertiary rounded p-1 text-center ${Qs?"opacity-50":""} ${Tr?"ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark":""}`,children:[a.jsx(RD,{trayColor:ct.tray_color,trayType:ct.tray_type,isEmpty:Qs,slotNumber:ar+1}),a.jsx("div",{className:`text-[9px] font-bold truncate ${Qs?"text-white/40":"text-white"}`,children:ct.tray_type||"—"}),a.jsx("div",{className:"mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden",children:Hi!==null&&Hi>=0&&!Qs&&a.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${Hi}%`,backgroundColor:Ox(Hi)}})}),Lr&&a.jsx("div",{className:"text-[7px] text-white/40 mt-0.5 truncate",children:Lr})]});return a.jsx("div",{className:"relative group",children:Qs?a.jsx(MD,{configureSlot:{enabled:k("printers:control"),onConfigure:()=>at({amsId:255,trayId:ar,trayCount:1,extruderId:Jt?Un===254?1:0:void 0})},inventory:o?void 0:{onAssignSpool:()=>vn({printerId:t.id,amsId:255,trayId:ar,trayInfo:{type:"",color:"",location:Lr||N("printers.external")}})},children:Pc}):a.jsx(jD,{data:qi,spoolman:{enabled:o,linkedSpoolId:En?l?.[En]?.id:void 0,spoolmanUrl:c,syncMode:d,onLinkSpool:o?()=>{const pa=(qi.trayUuid||qi.tagUid||Vu(t.serial_number,255,ar)).toUpperCase();Xt({tagUid:qi.tagUid||pa,trayUuid:qi.trayUuid||"",printerId:t.id,amsId:255,trayId:ar})}:void 0,onUnlinkSpool:Na?.id?()=>Ps.mutate(Na.id):void 0},inventory:o?void 0:(()=>{const pa=u?.(t.id,255,ar);return{assignedSpool:pa?.spool?{id:pa.spool.id,material:pa.spool.material,brand:pa.spool.brand,color_name:pa.spool.color_name,remainingWeightGrams:Math.max(0,Math.round(pa.spool.label_weight-pa.spool.weight_used))}:null,onAssignSpool:()=>vn({printerId:t.id,amsId:255,trayId:ar,trayInfo:{type:ct.tray_type||qi.profile,material:ct.tray_type??void 0,profile:qi.profile,color:qi.colorHex||"",location:Lr||N("printers.external")}}),onUnassignSpool:pa?()=>m?.(t.id,255,ar):void 0}})(),configureSlot:{enabled:k("printers:control"),onConfigure:()=>at({amsId:255,trayId:ar,trayCount:1,trayType:ct.tray_type||void 0,trayColor:ct.tray_color||void 0,traySubBrands:ct.tray_sub_brands||void 0,trayInfoIdx:ct.tray_info_idx||void 0,extruderId:Jt?Un===254?1:0:void 0,caliIdx:ct.cali_idx,savedPresetId:rn?.preset_id})},children:Pc})},Un)})})]})]})]})]})})()]}),cr&&r==="expanded"&&a.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[a.jsx(dc,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}),a.jsx("span",{className:"text-sm text-white truncate",children:cr.name}),Ui&&a.jsxs("span",{className:`text-xs px-1.5 py-0.5 rounded flex-shrink-0 ${Ui.state==="ON"?"bg-bambu-green/20 text-bambu-green":Ui.state==="OFF"?"bg-red-500/20 text-red-400":"bg-bambu-gray/20 text-bambu-gray"}`,children:[Ui.state||"?",Ui.state==="ON"&&Ui.energy?.power!=null&&a.jsxs("span",{className:"text-yellow-400 ml-1.5",children:["· ",Ui.energy.power,"W"]})]})]}),a.jsx("div",{className:"flex-1"}),a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsxs("button",{onClick:()=>pe(!0),disabled:Wo.isPending||Ui?.state==="ON"||!k("smart_plugs:control"),className:`px-2 py-1 text-xs rounded transition-colors flex items-center gap-1 ${k("smart_plugs:control")?Ui?.state==="ON"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary":"bg-bambu-dark text-bambu-gray/50 cursor-not-allowed"}`,title:k("smart_plugs:control")?void 0:N("printers.permission.noSmartPlugControl"),children:[a.jsx(Yd,{className:"w-3 h-3"}),"On"]}),a.jsxs("button",{onClick:()=>Ne(!0),disabled:Wo.isPending||Ui?.state==="OFF"||!k("smart_plugs:control"),className:`px-2 py-1 text-xs rounded transition-colors flex items-center gap-1 ${k("smart_plugs:control")?Ui?.state==="OFF"?"bg-red-500/30 text-red-400":"bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary":"bg-bambu-dark text-bambu-gray/50 cursor-not-allowed"}`,title:k("smart_plugs:control")?void 0:N("printers.permission.noSmartPlugControl"),children:[a.jsx(aS,{className:"w-3 h-3"}),"Off"]})]}),a.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[a.jsx("span",{className:`text-xs hidden sm:inline ${cr.auto_off_executed?"text-bambu-green":"text-bambu-gray"}`,children:cr.auto_off_executed?"Auto-off done":"Auto-off"}),a.jsx("button",{onClick:()=>So.mutate(!cr.auto_off),disabled:So.isPending||cr.auto_off_executed||!k("smart_plugs:control"),title:k("smart_plugs:control")?cr.auto_off_executed?N("printers.autoOffExecuted"):N("printers.autoOffAfterPrint"):N("printers.permission.noSmartPlugControl"),className:`relative w-9 h-5 rounded-full transition-colors flex-shrink-0 ${k("smart_plugs:control")?cr.auto_off_executed?"bg-bambu-green/50 cursor-not-allowed":cr.auto_off?"bg-bambu-green":"bg-bambu-dark-tertiary":"bg-bambu-dark-tertiary/50 cursor-not-allowed"}`,children:a.jsx("span",{className:`absolute top-[2px] left-[2px] w-4 h-4 bg-white rounded-full transition-transform ${cr.auto_off||cr.auto_off_executed?"translate-x-4":"translate-x-0"}`})})]})]}),Ci&&Ci.length>0&&a.jsxs("div",{className:"flex items-center gap-2 mt-2 pt-2 border-t border-bambu-dark-tertiary/50",children:[a.jsx(Jw,{className:"w-3.5 h-3.5 text-blue-400 flex-shrink-0"}),a.jsx("span",{className:"text-xs text-bambu-gray",children:"HA:"}),a.jsx("div",{className:"flex flex-wrap gap-1",children:Ci.map(lt=>{const Ht=lt.ha_entity_id?.startsWith("script.");return a.jsxs("button",{onClick:()=>_c.mutate({id:lt.id,action:Ht?"on":"toggle"}),disabled:_c.isPending,title:`${Ht?"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:[a.jsx(ns,{className:"w-2.5 h-2.5"}),lt.name]},lt.id)})})]})]}),r==="expanded"&&a.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary flex items-center justify-end gap-2 flex-wrap",children:[a.jsx(De,{variant:"secondary",size:"sm",onClick:()=>au.mutate(!Ue?.chamber_light),disabled:!Ue?.connected||au.isPending||!k("printers:control"),title:k("printers:control")?Ue?.chamber_light?N("printers.chamberLightOff"):N("printers.chamberLightOn"):N("printers.permission.noControl"),className:Ue?.chamber_light?"!border-yellow-500 !text-yellow-400 hover:!bg-yellow-500/20":"",children:a.jsx(xI,{on:Ue?.chamber_light??!1,className:`w-4 h-4 ${Ue?.chamber_light?"text-yellow-400":""}`})}),a.jsx(De,{variant:"secondary",size:"sm",onClick:()=>{if(f==="embedded"&&y)y(t.id,t.name);else{const lt=localStorage.getItem("cameraWindowState"),Ht=lt?JSON.parse(lt):{width:640,height:400},Jt=[`width=${Ht.width}`,`height=${Ht.height}`,Ht.left!==void 0?`left=${Ht.left}`:"",Ht.top!==void 0?`top=${Ht.top}`:"","menubar=no,toolbar=no,location=no,status=no"].filter(Boolean).join(",");window.open(`/camera/${t.id}`,`camera-${t.id}`,Jt)}},disabled:!Ue?.connected||!k("camera:view"),title:k("camera:view")?N(f==="embedded"?"printers.openCameraOverlay":"printers.openCameraWindow"):N("printers.permission.noCamera"),children:a.jsx(OO,{className:"w-4 h-4"})}),a.jsxs("div",{className:`inline-flex rounded-md ${t.plate_detection_enabled?"ring-1 ring-green-500":""}`,children:[a.jsx(De,{variant:"secondary",size:"sm",onClick:qy,disabled:!Ue?.connected||_o.isPending||!k("printers:update"),title:k("printers:update")?t.plate_detection_enabled?N("printers.plateDetection.enabledClick"):N("printers.plateDetection.disabledClick"):N("printers.plateDetection.noPermission"),className:`!rounded-r-none !border-r-0 ${t.plate_detection_enabled?"!border-green-500 !text-green-400 hover:!bg-green-500/20":""}`,children:_o.isPending?a.jsx(ft,{className:"w-4 h-4 animate-spin"}):a.jsx(NN,{className:"w-4 h-4"})}),a.jsx(De,{variant:"secondary",size:"sm",onClick:Hp,disabled:!Ue?.connected||mt||!k("printers:update"),title:k("printers:update")?N("printers.plateDetection.manageCalibration"):N("printers.plateDetection.noPermission"),className:`!rounded-l-none !px-1.5 ${t.plate_detection_enabled?"!border-green-500 !text-green-400 hover:!bg-green-500/20":""}`,children:mt?a.jsx(ft,{className:"w-3 h-3 animate-spin"}):a.jsx(On,{className:"w-3 h-3"})})]}),a.jsxs(De,{variant:"secondary",size:"sm",onClick:()=>ge(!0),disabled:!Nr||!k("printers:files"),title:k("printers:files")?N("printers.browseFiles"):N("printers.permission.noFiles"),children:[a.jsx(Ig,{className:"w-4 h-4"}),N("printers.files")]}),Nr&&Ue?.state!=="RUNNING"&&Ue?.state!=="PAUSE"&&a.jsxs(De,{size:"sm",onClick:()=>ve(!0),disabled:!k("printers:control"),title:k("printers:control")?N("common.print"):N("printers.permission.noControl"),className:"!bg-bambu-green hover:!bg-bambu-green/80 !text-white",children:[a.jsx(Dr,{className:"w-4 h-4"}),N("common.print")]})]})]}),oe&&a.jsx(HMe,{printerId:t.id,printerName:t.name,onClose:()=>ge(!1)}),Se&&a.jsx(Xae,{folderId:null,onClose:()=>ve(!1),onUploadComplete:()=>{},autoUpload:!0,accept:".gcode,.3mf",validateFile:lt=>{const Ht=lt.name.toLowerCase();if(!Ht.endsWith(".gcode")&&!Ht.includes(".gcode."))return N("printers.dropNotPrintable","Only .gcode and .gcode.3mf files can be printed")},onFileUploaded:lt=>{const Ht=lt.metadata?.sliced_for_model,Jt=O0(t.model);if(Ht&&Jt&&Ht.toLowerCase()!==Jt.toLowerCase())return me.deleteLibraryFile(lt.id).catch(()=>{}),N("printers.incompatibleFile","This file was sliced for {{slicedFor}}, but this printer is a {{printerModel}}",{slicedFor:Ht,printerModel:Jt});Fe({id:lt.id,filename:lt.filename})}}),Ce&&a.jsx(ic,{mode:"reprint",libraryFileId:Ce.id,archiveName:Ce.filename,initialSelectedPrinterIds:[t.id],onClose:()=>Fe(null),onSuccess:()=>Fe(null),cleanupLibraryAfterDispatch:!0}),re&&a.jsx(KMe,{printerId:t.id,printerName:t.name,onClose:()=>W(!1)}),Ae&&a.jsx(N7e,{printer:t,status:Ue,totalPrintHours:n?.total_print_hours,onClose:he}),At&&a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onClick:()=>ld(),children:a.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:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[At.needs_calibration?a.jsx(NN,{className:"w-5 h-5 text-blue-500"}):At.is_empty?a.jsx(yr,{className:"w-5 h-5 text-green-500"}):a.jsx(Ma,{className:"w-5 h-5 text-yellow-500"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:"Build Plate Check"}),At.reference_count!==void 0&&At.max_references&&a.jsxs("span",{className:"text-xs text-bambu-gray bg-bambu-dark-tertiary px-2 py-1 rounded",children:[At.reference_count,"/",At.max_references," refs"]})]}),a.jsx("button",{onClick:()=>ld(),className:"p-1 text-bambu-gray hover:text-white rounded transition-colors",children:a.jsx(Bt,{className:"w-5 h-5"})})]}),a.jsxs("div",{className:"p-4 space-y-4",children:[At.needs_calibration?a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"p-3 rounded-lg bg-blue-500/20 border border-blue-500/50",children:[a.jsx("p",{className:"font-medium text-blue-400",children:N("printers.plateDetection.calibrationRequired")}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",dangerouslySetInnerHTML:{__html:N("printers.plateDetection.calibrationInstructions")}})]}),a.jsxs("div",{className:"text-sm text-bambu-gray space-y-2",children:[a.jsx("p",{children:N("printers.plateDetection.calibrationDescription")}),a.jsx("p",{dangerouslySetInnerHTML:{__html:N("printers.plateDetection.calibrationTip")}})]})]}):a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:`p-3 rounded-lg ${At.is_empty?"bg-green-500/20 border border-green-500/50":"bg-yellow-500/20 border border-yellow-500/50"}`,children:[a.jsx("p",{className:`font-medium ${At.is_empty?"text-green-400":"text-yellow-400"}`,children:At.is_empty?N("printers.plateDetection.plateEmpty"):N("printers.plateDetection.objectsDetected")}),a.jsxs("p",{className:"text-sm text-bambu-gray mt-1",children:[N("printers.plateDetection.confidence"),": ",Math.round(At.confidence*100),"% | ",N("printers.plateDetection.difference"),": ",At.difference_percent.toFixed(1),"%"]})]}),At.debug_image_url&&a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-bambu-gray mb-2",children:N("printers.plateDetection.analysisPreview")}),a.jsx("img",{src:At.debug_image_url,alt:N("printers.plateDetection.analysisPreview"),className:"w-full rounded-lg border border-bambu-dark-tertiary"}),a.jsx("p",{className:"text-xs text-bambu-gray mt-2",children:N("printers.plateDetection.analysisLegend")})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:At.message})]}),kc&&kc.references.length>0&&a.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[a.jsx("p",{className:"text-sm font-medium text-white mb-2",children:N("printers.plateDetection.savedReferences",{count:kc.references.length,max:kc.max_references})}),a.jsx("div",{className:"grid grid-cols-5 gap-2",children:kc.references.map(lt=>a.jsxs("div",{className:"relative group",children:[a.jsx("img",{src:me.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"}),a.jsx("button",{onClick:()=>$y(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:N("printers.plateDetection.deleteReference"),children:a.jsx(Bt,{className:"w-3 h-3 text-white"})}),od?.index===lt.index?a.jsx("input",{type:"text",value:od.label,onChange:Ht=>Nc({...od,label:Ht.target.value}),onBlur:()=>Im(lt.index,od.label),onKeyDown:Ht=>{Ht.key==="Enter"&&Im(lt.index,od.label),Ht.key==="Escape"&&Nc(null)},className:"w-full mt-1 px-1 py-0.5 text-xs bg-bambu-dark-tertiary border border-bambu-green rounded text-white",autoFocus:!0,placeholder:N("printers.plateDetection.labelPlaceholder")}):a.jsx("p",{className:"text-xs text-bambu-gray mt-1 truncate cursor-pointer hover:text-white",onClick:()=>Nc({index:lt.index,label:lt.label}),title:lt.label?N("printers.plateDetection.clickToEdit",{label:lt.label}):N("printers.plateDetection.clickToAddLabel"),children:lt.label||a.jsx("span",{className:"italic opacity-50",children:N("printers.noLabel")})}),a.jsx("p",{className:"text-[10px] text-bambu-gray/60",children:lt.timestamp?Zn(lt.timestamp)?.toLocaleDateString()??"":""})]},lt.index))})]}),!At.needs_calibration&&a.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsx("p",{className:"text-sm font-medium text-white",children:N("printers.roi.title")}),ot?a.jsxs("div",{className:"flex gap-1",children:[a.jsx(De,{variant:"ghost",size:"sm",onClick:()=>Te(null),disabled:Ge,children:N("common.cancel")}),a.jsx(De,{size:"sm",onClick:_e,disabled:Ge,children:Ge?a.jsx(ft,{className:"w-3 h-3 animate-spin"}):N("common.save")})]}):a.jsxs(De,{variant:"ghost",size:"sm",onClick:()=>Te(At.roi||{x:.15,y:.35,w:.7,h:.55}),children:[a.jsx(ci,{className:"w-3 h-3 mr-1"}),N("common.edit")]})]}),ot?a.jsxs("div",{className:"space-y-3 bg-bambu-dark-tertiary/50 p-3 rounded-lg",children:[a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"text-xs text-bambu-gray",children:N("printers.roi.xStart")}),a.jsx("input",{type:"range",min:"0",max:"0.9",step:"0.01",value:ot.x,onChange:lt=>Te({...ot,x:parseFloat(lt.target.value)}),className:"w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"}),a.jsxs("span",{className:"text-xs text-bambu-gray",children:[Math.round(ot.x*100),"%"]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"text-xs text-bambu-gray",children:N("printers.roi.yStart")}),a.jsx("input",{type:"range",min:"0",max:"0.9",step:"0.01",value:ot.y,onChange:lt=>Te({...ot,y:parseFloat(lt.target.value)}),className:"w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"}),a.jsxs("span",{className:"text-xs text-bambu-gray",children:[Math.round(ot.y*100),"%"]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"text-xs text-bambu-gray",children:N("printers.width")}),a.jsx("input",{type:"range",min:"0.1",max:"1",step:"0.01",value:ot.w,onChange:lt=>Te({...ot,w:parseFloat(lt.target.value)}),className:"w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"}),a.jsxs("span",{className:"text-xs text-bambu-gray",children:[Math.round(ot.w*100),"%"]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"text-xs text-bambu-gray",children:N("printers.height")}),a.jsx("input",{type:"range",min:"0.1",max:"1",step:"0.01",value:ot.h,onChange:lt=>Te({...ot,h:parseFloat(lt.target.value)}),className:"w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"}),a.jsxs("span",{className:"text-xs text-bambu-gray",children:[Math.round(ot.h*100),"%"]})]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:N("printers.roi.instruction")})]}):a.jsxs("p",{className:"text-xs text-bambu-gray",children:["Current: X=",Math.round((At.roi?.x||.15)*100),"%, Y=",Math.round((At.roi?.y||.35)*100),"%, W=",Math.round((At.roi?.w||.7)*100),"%, H=",Math.round((At.roi?.h||.55)*100),"%"]})]})]}),a.jsx("div",{className:"flex justify-end gap-2 p-4 border-t border-bambu-dark-tertiary",children:At.needs_calibration?a.jsxs(a.Fragment,{children:[a.jsx(De,{variant:"ghost",onClick:()=>ld(),children:N("common.cancel")}),a.jsx(De,{onClick:()=>Cc(),disabled:nt,children:nt?a.jsxs(a.Fragment,{children:[a.jsx(ft,{className:"w-4 h-4 mr-2 animate-spin"}),"Calibrating..."]}):"Calibrate Empty Plate"})]}):a.jsxs(a.Fragment,{children:[a.jsx(De,{variant:"ghost",onClick:()=>Cc(),disabled:nt,children:nt?"Adding...":`Add Reference (${kc?.references.length||0}/${kc?.max_references||5})`}),a.jsx(De,{onClick:()=>ld(),children:"Close"})]})})]})}),ne&&cr&&a.jsx(yn,{title:N("printers.confirm.powerOnTitle"),message:N("printers.confirm.powerOnMessage",{name:t.name}),confirmText:N("printers.confirm.powerOnButton"),variant:"default",onConfirm:()=>{Wo.mutate("on"),pe(!1)},onCancel:()=>pe(!1)}),xe&&cr&&a.jsx(yn,{title:N("printers.confirm.powerOffTitle"),message:Ue?.state==="RUNNING"?N("printers.confirm.powerOffWarning",{name:t.name}):N("printers.confirm.powerOffMessage",{name:t.name}),confirmText:N("printers.confirm.powerOffButton"),variant:"danger",onConfirm:()=>{Wo.mutate("off"),Ne(!1)},onCancel:()=>Ne(!1)}),E&&a.jsx(yn,{title:N("printers.confirm.stopTitle"),message:N("printers.confirm.stopMessage",{name:t.name}),confirmText:N("printers.confirm.stopButton"),variant:"danger",onConfirm:()=>{ru.mutate(),j(!1)},onCancel:()=>j(!1)}),O&&a.jsx(yn,{title:N("printers.confirm.pauseTitle"),message:N("printers.confirm.pauseMessage",{name:t.name}),confirmText:N("printers.confirm.pauseButton"),variant:"default",onConfirm:()=>{zp.mutate(),K(!1)},onCancel:()=>K(!1)}),le&&a.jsx(yn,{title:N("printers.confirm.resumeTitle"),message:N("printers.confirm.resumeMessage",{name:t.name}),confirmText:N("printers.confirm.resumeButton"),variant:"default",onConfirm:()=>{di.mutate(),B(!1)},onCancel:()=>B(!1)}),be&&a.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/70 p-4",children:a.jsxs("div",{className:"bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl w-full max-w-sm p-5",children:[a.jsxs("div",{className:"flex items-start gap-3 mb-4",children:[a.jsx(Dn,{className:"w-5 h-5 text-yellow-400 flex-shrink-0 mt-0.5"}),a.jsxs("div",{children:[a.jsx("h3",{className:"text-sm font-semibold text-white mb-1",children:N("printers.bedJog.notHomedTitle")}),a.jsx("p",{className:"text-xs text-bambu-gray leading-relaxed",children:N("printers.bedJog.notHomedMessage")})]})]}),a.jsxs("div",{className:"flex flex-col gap-2",children:[a.jsx("button",{onClick:()=>{iu.mutate("all"),fe(null)},className:"w-full px-3 py-2 rounded-lg text-xs font-medium bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30 transition-colors",children:N("printers.bedJog.homeZ")}),a.jsx("button",{onClick:()=>{const lt=be.distance;try{sessionStorage.setItem(`bambuddy.bedJog.warned.${t.id}`,"1")}catch{}Ko.mutate({distance:lt,force:!0}),fe(null)},className:"w-full px-3 py-2 rounded-lg text-xs font-medium bg-yellow-500/20 text-yellow-400 hover:bg-yellow-500/30 transition-colors",children:N("printers.bedJog.moveAnyway")}),a.jsx("button",{onClick:()=>fe(null),className:"w-full px-3 py-2 rounded-lg text-xs font-medium bg-bambu-dark text-bambu-gray hover:bg-bambu-dark-tertiary transition-colors",children:N("common.cancel")})]})]})}),a.jsx(yI,{printerId:t.id,isOpen:R,onClose:()=>ae(!1)}),q&&a.jsx($ye,{printerName:t.name,errors:Ue?.hms_errors||[],onClose:()=>Y(!1),printerId:t.id,hasPermission:k}),Wt&&a.jsx(a7e,{isOpen:!!Wt,onClose:()=>Zt(null),printerId:t.id,printerName:t.name,amsId:Wt.amsId,amsLabel:Wt.amsLabel,initialMode:Wt.mode,thresholds:s}),Kt&&a.jsx(Gae,{isOpen:!!Kt,onClose:()=>Xt(null),tagUid:Kt.tagUid,trayUuid:Kt.trayUuid,printerId:Kt.printerId,amsId:Kt.amsId,trayId:Kt.trayId}),ln&&a.jsx(Wae,{isOpen:!!ln,onClose:()=>vn(null),printerId:ln.printerId,amsId:ln.amsId,trayId:ln.trayId,trayInfo:ln.trayInfo}),Ke&&a.jsx(Kae,{isOpen:!!Ke,onClose:()=>at(null),printerId:t.id,slotInfo:Ke,printerModel:O0(t.model)||void 0,onSuccess:()=>{A.invalidateQueries({queryKey:["slotPresets",t.id]}),A.invalidateQueries({queryKey:["printerStatus",t.id]})}}),ie&&a.jsx(z7e,{printer:t,onClose:()=>J(!1)}),Lt&&et&&a.jsx(I7e,{printer:t,firmwareInfo:et,onClose:()=>Et(!1)}),Sn&&a.jsx("div",{className:"fixed inset-0 z-40",onClick:()=>_n(null)}),Me!==null&&ye&&(()=>{const lt=Re==="n3s"?85:65,Ht=35,Jt=lt+10;return a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"fixed inset-0 z-[100]",onClick:()=>Oe(null)}),a.jsxs("div",{className:"fixed z-[101] w-[240px] bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl overflow-hidden",style:{top:ye.top,left:ye.left},onClick:ct=>ct.stopPropagation(),children:[a.jsxs("div",{className:"flex items-center gap-2 px-3 py-2.5 border-b border-bambu-dark-tertiary",children:[a.jsx(Hu,{className:"w-3.5 h-3.5 text-amber-400"}),a.jsx("span",{className:"text-xs text-white font-medium",children:N("printers.drying.start")})]}),a.jsxs("div",{className:"px-3 py-2.5 space-y-2.5",children:[a.jsxs("div",{children:[a.jsx("label",{className:"text-[10px] text-bambu-gray mb-1 block",children:N("printers.filaments")}),a.jsx("select",{value:Xe,onChange:ct=>{const Un=ct.target.value;tt(Un);const Tr=b[Un];Tr&&(ze(Tr[Re==="n3s"?"n3s":"n3f"]),qe(Re==="n3s"?Tr.n3s_hours:Tr.n3f_hours))},className:"w-full px-2 py-1.5 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-xs focus:outline-none focus:border-amber-500/50",children:Object.keys(b).map(ct=>a.jsx("option",{value:ct,children:ct},ct))})]}),a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center justify-between mb-1",children:[a.jsx("label",{className:"text-[10px] text-bambu-gray",children:N("printers.drying.temperature")}),a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx("input",{type:"number",min:45,max:lt,value:we,onChange:ct=>ze(Math.min(lt,Math.max(45,Number(ct.target.value)||45))),className:"w-12 px-1 py-0.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-[11px] text-center focus:outline-none focus:border-amber-500/50 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"}),a.jsx("span",{className:"text-[10px] text-bambu-gray",children:"°C"})]})]}),a.jsx("input",{type:"range",min:Ht,max:Jt,value:we,onChange:ct=>ze(Math.min(lt,Math.max(45,Number(ct.target.value)))),className:"w-full h-1 accent-amber-500 cursor-pointer"}),a.jsxs("div",{className:"flex justify-between text-[9px] text-bambu-gray/50 mt-0.5",children:[a.jsx("span",{children:"45°C"}),a.jsxs("span",{children:[lt,"°C"]})]})]}),a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center justify-between mb-1",children:[a.jsx("label",{className:"text-[10px] text-bambu-gray",children:N("printers.drying.duration")}),a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx("input",{type:"number",min:1,max:24,value:ce,onChange:ct=>qe(Math.min(24,Math.max(1,Number(ct.target.value)||1))),className:"w-10 px-1 py-0.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-[11px] text-center focus:outline-none focus:border-amber-500/50 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"}),a.jsx("span",{className:"text-[10px] text-bambu-gray",children:N("printers.drying.hours")})]})]}),a.jsx("input",{type:"range",min:1,max:24,value:ce,onChange:ct=>qe(Number(ct.target.value)),className:"w-full h-1 accent-amber-500 cursor-pointer"}),a.jsxs("div",{className:"flex justify-between text-[9px] text-bambu-gray/50 mt-0.5",children:[a.jsx("span",{children:"1h"}),a.jsx("span",{children:"24h"})]})]}),a.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:Pe,onChange:ct=>de(ct.target.checked),className:"w-3.5 h-3.5 accent-amber-500 rounded cursor-pointer"}),a.jsx("span",{className:"text-[11px] text-bambu-gray",children:N("printers.drying.rotateTray")})]})]}),a.jsx("div",{className:"px-3 pb-3",children:a.jsx("button",{onClick:()=>{Me!==null&&wo.mutate({amsId:Me,temp:we,duration:ce,filament:Xe,rotateTray:Pe})},disabled:wo.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:wo.isPending?N("printers.drying.startingDrying"):N("printers.drying.start")})})]})]})})()]})}function O7e({onClose:t,onAdd:e,existingSerials:n}){const{t:r}=Ft(),[i,s]=w.useState({name:"",serial_number:"",ip_address:"",access_code:"",model:"",location:"",auto_archive:!0}),[o,l]=w.useState(!1),[c,d]=w.useState([]),[u,m]=w.useState(""),[p,f]=w.useState(!1),[y,v]=w.useState(!1),[b,g]=w.useState([]),[_,C]=w.useState(""),[P,N]=w.useState({scanned:0,total:0});w.useEffect(()=>{hd.getInfo().then(k=>{v(k.is_docker),k.subnets.length>0&&(g(k.subnets),C(k.subnets[0]))}).catch(()=>{})},[]);const A=c.filter(k=>!n.includes(k.serial)),T=async()=>{m(""),d([]),l(!0),f(!1),N({scanned:0,total:0});try{if(y){await hd.startSubnetScan(_);const k=setInterval(async()=>{try{const D=await hd.getScanStatus();N({scanned:D.scanned,total:D.total});const H=await hd.getDiscoveredPrinters();d(H),D.running||(clearInterval(k),l(!1),f(!0))}catch(D){console.error("Failed to get scan status:",D)}},500)}else{await hd.startDiscovery(10);const k=setInterval(async()=>{try{const D=await hd.getDiscoveredPrinters();d(D)}catch(D){console.error("Failed to get discovered printers:",D)}},1e3);setTimeout(async()=>{clearInterval(k);try{await hd.stopDiscovery()}catch{}l(!1),f(!0);try{const D=await hd.getDiscoveredPrinters();d(D)}catch(D){console.error("Failed to get final discovered printers:",D)}},1e4)}}catch(k){console.error("Failed to start discovery:",k),m(k instanceof Error?k.message:r("printers.discovery.failedToStart")),l(!1),f(!0)}},F=k=>{const D=k.serial.startsWith("unknown-")?"":k.serial;s({...i,name:k.name||"",serial_number:D,ip_address:k.ip_address,model:O0(k.model)}),d([])};return w.useEffect(()=>()=>{hd.stopDiscovery().catch(()=>{}),hd.stopSubnetScan().catch(()=>{})},[]),w.useEffect(()=>{const k=D=>{D.key==="Escape"&&t()};return window.addEventListener("keydown",k),()=>window.removeEventListener("keydown",k)},[t]),a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-start sm:items-center justify-center z-50 p-4 overflow-y-auto",onClick:t,children:a.jsx(Tt,{className:"w-full max-w-md my-auto max-h-[calc(100vh-2rem)] overflow-y-auto",onClick:k=>k.stopPropagation(),children:a.jsxs(Mt,{children:[a.jsx("h2",{className:"text-xl font-semibold mb-4",children:r("printers.addPrinter")}),a.jsxs("div",{className:"mb-4 pb-4 border-b border-bambu-dark-tertiary",children:[y&&a.jsxs("div",{className:"mb-3",children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.discovery.subnetToScan")}),b.length>0?a.jsx("select",{className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none text-sm",value:_,onChange:k=>C(k.target.value),disabled:o,children:b.map(k=>a.jsx("option",{value:k,children:k},k))}):a.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none text-sm",value:_,onChange:k=>C(k.target.value),placeholder:"192.168.1.0/24",disabled:o}),a.jsx("p",{className:"mt-1 text-xs text-bambu-gray",children:r("printers.discovery.dockerNote")})]}),a.jsx(De,{type:"button",variant:"secondary",onClick:T,disabled:o,className:"w-full",children:o?a.jsxs(a.Fragment,{children:[a.jsx(ft,{className:"w-4 h-4 animate-spin"}),y&&P.total>0?r("printers.discovery.scanProgress",{scanned:P.scanned,total:P.total}):r("printers.discovery.scanning")]}):a.jsxs(a.Fragment,{children:[a.jsx(Pr,{className:"w-4 h-4"}),r(y?"printers.discovery.scanSubnet":"printers.discovery.discoverNetwork")]})}),u&&a.jsx("div",{className:"mt-2 text-sm text-red-400",children:u}),A.length>0&&a.jsx("div",{className:"mt-3 space-y-2 max-h-40 overflow-y-auto",children:A.map(k=>a.jsxs("div",{className:"flex items-center justify-between p-2 bg-bambu-dark rounded-lg hover:bg-bambu-dark-secondary cursor-pointer transition-colors",onClick:()=>F(k),children:[a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:"font-medium text-white text-sm truncate",children:k.name||k.serial}),a.jsxs("p",{className:"text-xs text-bambu-gray truncate",children:[O0(k.model)||r("printers.discovery.unknown")," • ",k.ip_address,k.serial.startsWith("unknown-")&&a.jsxs("span",{className:"text-yellow-500",children:[" • ",r("printers.discovery.serialRequired")]})]})]}),a.jsx(On,{className:"w-4 h-4 text-bambu-gray -rotate-90 flex-shrink-0 ml-2"})]},k.serial))}),o&&a.jsx("p",{className:"mt-2 text-sm text-bambu-gray text-center",children:r(y?"printers.discovery.scanningSubnet":"printers.discovery.scanningNetwork")}),p&&!o&&c.length===0&&a.jsx("p",{className:"mt-2 text-sm text-bambu-gray text-center",children:r(y?"printers.discovery.noPrintersFoundSubnet":"printers.discovery.noPrintersFoundNetwork")}),p&&!o&&c.length>0&&A.length===0&&a.jsx("p",{className:"mt-2 text-sm text-bambu-gray text-center",children:r("printers.discovery.allConfigured")})]}),a.jsxs("form",{onSubmit:k=>{k.preventDefault(),e(i)},className:"space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.name")}),a.jsx("input",{type:"text",required:!0,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:i.name,onChange:k=>s({...i,name:k.target.value}),placeholder:r("printers.modal.myPrinter")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.ipAddress")}),a.jsx("input",{type:"text",required:!0,pattern:"(\\d{1,3}(\\.\\d{1,3}){3}|[a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?(\\.[a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?)*)",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:i.ip_address,onChange:k=>s({...i,ip_address:k.target.value}),placeholder:"192.168.1.100 or printer.local"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.serialNumber")}),a.jsx("input",{type:"text",required:!0,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:i.serial_number,onChange:k=>s({...i,serial_number:k.target.value}),placeholder:"01P00A000000000"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.accessCode")}),a.jsx("input",{type:"password",required:!0,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:i.access_code,onChange:k=>s({...i,access_code:k.target.value}),placeholder:r("printers.modal.fromPrinterSettings")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.modal.modelOptional")}),a.jsxs("select",{className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:i.model||"",onChange:k=>s({...i,model:k.target.value}),children:[a.jsx("option",{value:"",children:r("printers.modal.selectModel")}),a.jsxs("optgroup",{label:"H2 Series",children:[a.jsx("option",{value:"H2C",children:"H2C"}),a.jsx("option",{value:"H2D",children:"H2D"}),a.jsx("option",{value:"H2D Pro",children:"H2D Pro"}),a.jsx("option",{value:"H2S",children:"H2S"})]}),a.jsx("optgroup",{label:"X2 Series",children:a.jsx("option",{value:"X2D",children:"X2D"})}),a.jsxs("optgroup",{label:"X1 Series",children:[a.jsx("option",{value:"X1E",children:"X1E"}),a.jsx("option",{value:"X1C",children:"X1 Carbon"}),a.jsx("option",{value:"X1",children:"X1"})]}),a.jsxs("optgroup",{label:"P Series",children:[a.jsx("option",{value:"P2S",children:"P2S"}),a.jsx("option",{value:"P1S",children:"P1S"}),a.jsx("option",{value:"P1P",children:"P1P"})]}),a.jsxs("optgroup",{label:"A1 Series",children:[a.jsx("option",{value:"A1",children:"A1"}),a.jsx("option",{value:"A1 Mini",children:"A1 Mini"})]})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.modal.locationGroup")}),a.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:i.location||"",onChange:k=>s({...i,location:k.target.value}),placeholder:r("printers.modal.locationPlaceholder")}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:r("printers.locationHelp")})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"checkbox",id:"auto_archive",checked:i.auto_archive,onChange:k=>s({...i,auto_archive:k.target.checked}),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),a.jsx("label",{htmlFor:"auto_archive",className:"text-sm text-bambu-gray",children:r("printers.modal.autoArchiveLabel")})]}),a.jsxs("div",{className:"flex gap-3 pt-4",children:[a.jsx(De,{type:"button",variant:"secondary",onClick:t,className:"flex-1",children:r("common.cancel")}),a.jsx(De,{type:"submit",className:"flex-1",children:r("printers.addPrinter")})]})]})]})})})}function I7e({printer:t,firmwareInfo:e,onClose:n}){const{t:r}=Ft(),i=nn(),{showToast:s}=hn(),{hasPermission:o}=kr(),l=o("firmware:update"),[c,d]=w.useState(null),[u,m]=w.useState(!1),[p,f]=w.useState(null),[y,v]=w.useState(e.update_available?e.latest_version:null),{data:b,isLoading:g}=Ye({queryKey:["firmwarePrepare",t.id,y],queryFn:()=>zk.prepareUpload(t.id,y??void 0),staleTime:3e4,enabled:!!y&&l&&!u}),_=it({mutationFn:()=>zk.startUpload(t.id,y??void 0),onSuccess:()=>{m(!0);const P=setInterval(async()=>{try{const N=await zk.getUploadStatus(t.id);d(N),(N.status==="complete"||N.status==="error")&&(clearInterval(P),f(null),m(!1),N.status==="complete"&&(s(r("printers.firmwareModal.uploadedToast"),"success"),i.invalidateQueries({queryKey:["firmwareUpdate",t.id]})))}catch{}},2e3);f(P)},onError:P=>{s(r("printers.firmwareModal.uploadFailed",{error:P.message}),"error"),m(!1)}});w.useEffect(()=>()=>{p&&clearInterval(p)},[p]);const C=()=>{d(null),_.mutate()};return a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",children:a.jsx(Tt,{className:"w-full max-w-md mx-4",children:a.jsxs(Mt,{children:[a.jsxs("div",{className:"flex items-start gap-3 mb-4",children:[a.jsx("div",{className:`p-2 rounded-full ${e.update_available?"bg-orange-500/20":"bg-status-ok/20"}`,children:e.update_available?a.jsx(ga,{className:"w-5 h-5 text-orange-400"}):a.jsx(yr,{className:"w-5 h-5 text-status-ok"})}),a.jsxs("div",{className:"flex-1",children:[a.jsx("h3",{className:"text-lg font-semibold text-white",children:e.update_available?r("printers.firmwareModal.title"):r("printers.firmwareModal.titleUpToDate")}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:t.name})]})]}),(()=>{const P=y?e.available_versions?.find(F=>F.version===y):null,N=y??e.latest_version,A=P?.release_notes??e.release_notes,T=!!N&&N!==e.current_version;return a.jsxs("div",{className:"bg-bambu-dark rounded-lg p-3 mb-4",children:[a.jsxs("div",{className:"flex justify-between items-center text-sm",children:[a.jsx("span",{className:"text-bambu-gray",children:r("printers.firmwareModal.currentVersion")}),a.jsx("span",{className:`font-mono ${T?"text-white":"text-status-ok"}`,children:e.current_version||r("common.unknown")})]}),T&&a.jsxs("div",{className:"flex justify-between items-center text-sm mt-1",children:[a.jsx("span",{className:"text-bambu-gray",children:r("printers.firmwareModal.latestVersion")}),a.jsx("span",{className:"text-orange-400 font-mono",children:N})]}),A&&a.jsxs("details",{className:"mt-3 text-sm",open:!T,children:[a.jsx("summary",{className:`cursor-pointer hover:underline ${T?"text-orange-400":"text-status-ok"}`,children:r("printers.firmwareModal.releaseNotes")}),a.jsx("div",{className:"mt-2 text-bambu-gray text-xs max-h-40 overflow-y-auto whitespace-pre-wrap",children:A})]},N??"none")]})})(),e.available_versions&&e.available_versions.length>0&&!u&&c?.status!=="complete"&&a.jsxs("div",{className:"mb-4",children:[a.jsx("div",{className:"text-xs text-bambu-gray mb-2",children:r("printers.firmwareModal.availableVersions")}),a.jsx("div",{className:"max-h-56 overflow-y-auto border border-bambu-dark-tertiary rounded-lg divide-y divide-bambu-dark-tertiary",children:e.available_versions.map(P=>{const N=e.current_version===P.version,A=y===P.version,T=e.current_version?Bye(P.version,e.current_version):0,F=N?r("printers.firmwareModal.currentBadge"):T>0?r("printers.firmwareModal.newerBadge"):r("printers.firmwareModal.olderBadge"),k=N?"text-bambu-gray":T>0?"text-orange-400":"text-blue-400";return a.jsxs("button",{type:"button",disabled:!P.file_available||!l||N,onClick:()=>v(P.version),className:`w-full text-left px-3 py-2 text-sm flex items-center justify-between gap-2 transition-colors ${A?"bg-orange-500/10":"hover:bg-bambu-dark"} ${!P.file_available||!l||N?"opacity-60 cursor-not-allowed":"cursor-pointer"}`,children:[a.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[a.jsx("span",{className:"font-mono text-white",children:P.version}),a.jsx("span",{className:`text-xs ${k}`,children:F})]}),a.jsx("span",{className:`text-xs px-2 py-0.5 rounded-full ${N?"bg-blue-500/15 text-blue-400 border border-blue-500/30":P.file_available?"bg-bambu-green/15 text-bambu-green border border-bambu-green/30":"bg-bambu-gray/10 text-bambu-gray border border-bambu-gray/30"}`,children:N?r("printers.firmwareModal.installed"):P.file_available?r("printers.firmwareModal.usable"):r("printers.firmwareModal.unavailable")})]},P.version)})})]}),y?g?a.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray text-sm mb-4",children:[a.jsx(ft,{className:"w-4 h-4 animate-spin"}),r("printers.firmwareModal.checkingPrereqs")]}):b&&!u&&!c?a.jsx("div",{className:"mb-4",children:b.can_proceed?a.jsxs("div",{className:"flex items-center gap-2 text-bambu-green text-sm",children:[a.jsx(vi,{className:"w-4 h-4"}),r("printers.firmwareModal.sdCardReady")]}):a.jsx("div",{className:"space-y-1",children:b.errors.map((P,N)=>a.jsxs("div",{className:"flex items-center gap-2 text-red-400 text-sm",children:[a.jsx(ei,{className:"w-4 h-4 flex-shrink-0"}),P]},N))})}):null:null,(u||c)&&c&&a.jsxs("div",{className:"mb-4",children:[a.jsxs("div",{className:"flex items-center justify-between text-sm mb-1",children:[a.jsx("span",{className:"text-bambu-gray capitalize",children:c.status}),a.jsxs("span",{className:"text-white",children:[c.progress,"%"]})]}),a.jsx("div",{className:"w-full bg-bambu-dark-tertiary rounded-full h-2",children:a.jsx("div",{className:`h-2 rounded-full transition-all ${c.status==="error"?"bg-status-error":c.status==="complete"?"bg-status-ok":"bg-orange-500"} ${c.status==="uploading"?"animate-pulse":""}`,style:{width:`${c.progress}%`}})}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:c.message}),c.error&&a.jsx("p",{className:"text-xs text-red-400 mt-1",children:c.error})]}),c?.status==="complete"&&a.jsxs("div",{className:"bg-bambu-green/10 border border-bambu-green/30 rounded-lg p-3 mb-4",children:[a.jsx("p",{className:"text-sm text-bambu-green font-medium mb-2",children:r("printers.firmwareModal.uploadedSuccess")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:r("printers.firmwareModal.applyInstructions")}),a.jsxs("ol",{className:"text-xs text-bambu-gray mt-1 list-decimal list-inside space-y-1",children:[a.jsx("li",{dangerouslySetInnerHTML:{__html:r("printers.firmwareModal.step1")}}),a.jsx("li",{dangerouslySetInnerHTML:{__html:r("printers.firmwareModal.step2")}}),a.jsx("li",{dangerouslySetInnerHTML:{__html:r("printers.firmwareModal.step3")}}),a.jsx("li",{children:r("printers.firmwareModal.step4")})]})]}),a.jsxs("div",{className:"flex gap-2 justify-end",children:[a.jsx(De,{variant:"secondary",onClick:n,children:c?.status==="complete"?r("printers.firmwareModal.done"):r("common.cancel")}),b?.can_proceed&&!u&&c?.status!=="complete"&&l&&a.jsx(De,{onClick:C,disabled:_.isPending,children:_.isPending?a.jsxs(a.Fragment,{children:[a.jsx(ft,{className:"w-4 h-4 animate-spin mr-2"}),r("printers.firmwareModal.starting")]}):a.jsxs(a.Fragment,{children:[a.jsx(ga,{className:"w-4 h-4 mr-2"}),r("printers.firmwareModal.uploadFirmware")]})})]})]})})})}function z7e({printer:t,onClose:e}){const{t:n}=Ft(),r=nn(),{showToast:i}=hn(),[s,o]=w.useState({name:t.name,ip_address:t.ip_address,access_code:"",model:t.model||"",location:t.location||"",auto_archive:t.auto_archive}),l=it({mutationFn:d=>me.updatePrinter(t.id,d),onSuccess:()=>{r.invalidateQueries({queryKey:["printers"]}),r.invalidateQueries({queryKey:["printerStatus",t.id]}),e()},onError:d=>i(d.message||n("printers.toast.failedToUpdate"),"error")});w.useEffect(()=>{const d=u=>{u.key==="Escape"&&e()};return window.addEventListener("keydown",d),()=>window.removeEventListener("keydown",d)},[e]);const c=d=>{d.preventDefault();const u={name:s.name,ip_address:s.ip_address,model:s.model||void 0,location:s.location||void 0,auto_archive:s.auto_archive};s.access_code&&(u.access_code=s.access_code),l.mutate(u)};return a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-start sm:items-center justify-center z-50 p-4 overflow-y-auto",onClick:e,children:a.jsx(Tt,{className:"w-full max-w-md my-auto max-h-[calc(100vh-2rem)] overflow-y-auto",onClick:d=>d.stopPropagation(),children:a.jsxs(Mt,{children:[a.jsx("h2",{className:"text-xl font-semibold mb-4",children:n("printers.editPrinter")}),a.jsxs("form",{onSubmit:c,className:"space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.name")}),a.jsx("input",{type:"text",required:!0,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:s.name,onChange:d=>o({...s,name:d.target.value}),placeholder:n("printers.modal.myPrinter")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.ipAddress")}),a.jsx("input",{type:"text",required:!0,pattern:"(\\d{1,3}(\\.\\d{1,3}){3}|[a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?(\\.[a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?)*)",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:s.ip_address,onChange:d=>o({...s,ip_address:d.target.value}),placeholder:"192.168.1.100 or printer.local"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.serialNumber")}),a.jsx("input",{type:"text",disabled:!0,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray cursor-not-allowed",value:t.serial_number}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:n("printers.serialCannotBeChanged")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.accessCode")}),a.jsx("input",{type:"password",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:s.access_code,onChange:d=>o({...s,access_code:d.target.value}),placeholder:n("printers.accessCodePlaceholder")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.model")}),a.jsxs("select",{className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:s.model,onChange:d=>o({...s,model:d.target.value}),children:[a.jsx("option",{value:"",children:n("printers.modal.selectModel")}),a.jsxs("optgroup",{label:"H2 Series",children:[a.jsx("option",{value:"H2C",children:"H2C"}),a.jsx("option",{value:"H2D",children:"H2D"}),a.jsx("option",{value:"H2D Pro",children:"H2D Pro"}),a.jsx("option",{value:"H2S",children:"H2S"})]}),a.jsx("optgroup",{label:"X2 Series",children:a.jsx("option",{value:"X2D",children:"X2D"})}),a.jsxs("optgroup",{label:"X1 Series",children:[a.jsx("option",{value:"X1E",children:"X1E"}),a.jsx("option",{value:"X1C",children:"X1 Carbon"}),a.jsx("option",{value:"X1",children:"X1"})]}),a.jsxs("optgroup",{label:"P Series",children:[a.jsx("option",{value:"P2S",children:"P2S"}),a.jsx("option",{value:"P1S",children:"P1S"}),a.jsx("option",{value:"P1P",children:"P1P"})]}),a.jsxs("optgroup",{label:"A1 Series",children:[a.jsx("option",{value:"A1",children:"A1"}),a.jsx("option",{value:"A1 Mini",children:"A1 Mini"})]})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Location / Group"}),a.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:s.location,onChange:d=>o({...s,location:d.target.value}),placeholder:n("printers.modal.locationPlaceholder")}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:n("printers.locationHelp")})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"checkbox",id:"edit_auto_archive",checked:s.auto_archive,onChange:d=>o({...s,auto_archive:d.target.checked}),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),a.jsx("label",{htmlFor:"edit_auto_archive",className:"text-sm text-bambu-gray",children:n("printers.modal.autoArchiveLabel")})]}),a.jsxs("div",{className:"flex gap-3 pt-4",children:[a.jsx(De,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:n("common.cancel")}),a.jsx(De,{type:"submit",className:"flex-1",disabled:l.isPending,children:l.isPending?n("common.saving"):n("printers.modal.saveChanges")})]})]})]})})})}function U7e(t){const{data:e}=Ye({queryKey:["printerStatus",t],queryFn:()=>me.getPrinterStatus(t),refetchInterval:3e4});return!e?.connected}function B7e({printer:t,plug:e,onPowerOn:n,isPowering:r}){const i=U7e(t.id),{data:s}=Ye({queryKey:["smartPlugStatus",e.id],queryFn:()=>me.getSmartPlugStatus(e.id),refetchInterval:1e4});return i?a.jsxs("div",{className:"flex items-center justify-between px-3 py-2 hover:bg-gray-100 dark:hover:bg-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[a.jsx("span",{className:"text-sm text-gray-900 dark:text-white truncate",children:t.name}),s&&a.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded ${s.state==="ON"?"bg-bambu-green/20 text-bambu-green":"bg-red-500/20 text-red-400"}`,children:s.state||"?"})]}),a.jsxs("button",{onClick:()=>n(e.id),disabled:r||s?.state==="ON",className:`px-2 py-1 text-xs rounded transition-colors flex items-center gap-1 ${s?.state==="ON"?"bg-bambu-green/20 text-bambu-green cursor-default":"bg-bambu-green/20 text-bambu-green hover:bg-bambu-green hover:text-white"}`,children:[a.jsx(Yd,{className:"w-3 h-3"}),r?"...":"On"]})]}):null}function H7e(){const{t}=Ft(),[e,n]=w.useState(!1),[r,i]=w.useState(()=>localStorage.getItem("hideDisconnectedPrinters")==="true"),[s,o]=w.useState(!1),[l,c]=w.useState(null),[d,u]=w.useState(()=>localStorage.getItem("printerSortBy")||"name"),[m,p]=w.useState(()=>localStorage.getItem("printerSortAsc")!=="false"),[f,y]=w.useState(()=>{const Pe=localStorage.getItem("printerCardSize");return Pe?parseInt(Pe,10):2}),v=f===1?"compact":"expanded",[b,g]=w.useState(""),[_,C]=w.useState("all"),[P,N]=w.useState("all"),[A,T]=w.useState(0),[F,k]=w.useState(()=>{try{const Pe=localStorage.getItem("printerCollapsedSections");return Pe?JSON.parse(Pe):{}}catch{return{}}}),D=nn(),{showToast:H}=hn(),{hasPermission:z}=kr(),[Q,L]=w.useState(()=>{const Pe=localStorage.getItem("openEmbeddedCameras");if(Pe)try{const de=JSON.parse(Pe);return new Map(de.map(ye=>[ye.id,ye]))}catch{return new Map}return new Map});w.useEffect(()=>{const Pe=Array.from(Q.values());Pe.length>0?localStorage.setItem("openEmbeddedCameras",JSON.stringify(Pe)):localStorage.removeItem("openEmbeddedCameras")},[Q]);const{data:te,isLoading:ie}=Ye({queryKey:["printers"],queryFn:me.getPrinters}),{data:J}=Ye({queryKey:["settings"],queryFn:me.getSettings}),oe=w.useMemo(()=>{if(J?.drying_presets)try{const Pe=JSON.parse(J.drying_presets);if(typeof Pe=="object"&&Pe!==null&&Object.keys(Pe).length>0)return{...wL,...Pe}}catch{}return wL},[J?.drying_presets]);w.useEffect(()=>{J?.camera_view_mode==="window"&&Q.size>0&&L(new Map)},[J?.camera_view_mode,Q.size]);const{data:ge}=Ye({queryKey:["smart-plugs"],queryFn:me.getSmartPlugs}),{data:re}=Ye({queryKey:["maintenanceOverview"],queryFn:me.getMaintenanceOverview,staleTime:60*1e3}),{data:W}=Ye({queryKey:["spoolman-status"],queryFn:me.getSpoolmanStatus,staleTime:60*1e3}),ne=W?.enabled&&W?.connected,{data:pe}=Ye({queryKey:["spoolman-settings"],queryFn:me.getSpoolmanSettings,enabled:!!ne,staleTime:60*1e3}),xe=pe?.spoolman_sync_mode,{data:Ne}=Ye({queryKey:["unlinked-spools"],queryFn:me.getUnlinkedSpools,enabled:!!ne,staleTime:30*1e3}),q=Ne&&Ne.length>0,{data:Y}=Ye({queryKey:["linked-spools"],queryFn:me.getLinkedSpools,enabled:!!ne,staleTime:30*1e3}),E=Y?.linked,{data:j}=Ye({queryKey:["spool-assignments"],queryFn:()=>me.getAssignments(),enabled:z("inventory:view_assignments"),staleTime:30*1e3}),O=it({mutationFn:({printerId:Pe,amsId:de,trayId:ye})=>me.unassignSpool(Pe,de,ye),onSuccess:()=>{D.invalidateQueries({queryKey:["spool-assignments"]})}}),K=(Pe,de,ye)=>j?.find(Be=>Be.printer_id===Pe&&Be.ams_id===Number(de)&&Be.tray_id===Number(ye)),U=re?.reduce((Pe,de)=>(Pe[de.printer_id]={due_count:de.due_count,warning_count:de.warning_count,total_print_hours:de.total_print_hours},Pe),{})||{},ue=ge?.reduce((Pe,de)=>(de.printer_id&&(Pe[de.printer_id]=de),Pe),{})||{},I=it({mutationFn:me.createPrinter,onSuccess:()=>{D.invalidateQueries({queryKey:["printers"]}),D.invalidateQueries({queryKey:["maintenanceOverview"]}),n(!1)},onError:Pe=>H(Pe.message||t("printers.toast.failedToAdd"),"error")}),G=it({mutationFn:Pe=>me.controlSmartPlug(Pe,"on"),onSuccess:()=>{D.invalidateQueries({queryKey:["smart-plugs"]}),c(null)},onError:()=>{c(null)}}),[X,V]=w.useState(new Set),[ee,se]=w.useState(!1),[be,fe]=w.useState(null),[le,B]=w.useState(!1),R=ee||X.size>0,ae=w.useCallback(Pe=>{V(de=>{const ye=new Set(de);return ye.has(Pe)?ye.delete(Pe):ye.add(Pe),ye})},[]),Se=w.useCallback(()=>{V(new Set),se(!1)},[]);w.useEffect(()=>{const Pe=de=>{de.key==="Escape"&&R&&Se()};return window.addEventListener("keydown",Pe),()=>window.removeEventListener("keydown",Pe)},[R,Se]);const ve=w.useCallback(async Pe=>{B(!0);const ye=Array.from(X).filter(gt=>{const Ut=D.getQueryData(["printerStatus",gt]);if(!Ut?.connected)return!1;switch(Pe){case"stop":return Ut.state==="RUNNING"||Ut.state==="PAUSE";case"pause":return Ut.state==="RUNNING";case"resume":return Ut.state==="PAUSE";case"clearPlate":return!!Ut.awaiting_plate_clear;case"clearHMS":return Ut.hms_errors&&om(Ut.hms_errors).length>0;default:return!1}});if(ye.length===0){H(t("printers.bulk.noneApplicable"),"error"),B(!1),fe(null);return}const Be={stop:me.stopPrint,pause:me.pausePrint,resume:me.resumePrint,clearPlate:me.clearPlate,clearHMS:me.clearHMSErrors}[Pe],Qe=await Promise.allSettled(ye.map(gt=>Be(gt))),ht=Qe.filter(gt=>gt.status==="fulfilled").length,xt=Qe.filter(gt=>gt.status==="rejected").length;xt===0?H(t("printers.bulk.success",{action:t(`printers.bulk.actions.${Pe}`),count:ht})):H(t("printers.bulk.partial",{succeeded:ht,failed:xt}),"error"),ye.forEach(gt=>{D.invalidateQueries({queryKey:["printerStatus",gt]})}),B(!1),fe(null)},[X,D,H,t]),Ae=w.useCallback(Pe=>{Pe==="stop"||Pe==="pause"||Pe==="clearPlate"?fe(Pe):ve(Pe)},[ve]),je=()=>{const Pe=!r;i(Pe),localStorage.setItem("hideDisconnectedPrinters",String(Pe))},he=Pe=>{u(Pe),localStorage.setItem("printerSortBy",Pe)},Ce=()=>{const Pe=!m;p(Pe),localStorage.setItem("printerSortAsc",String(Pe))},Fe=()=>{switch(f){case 1:return"grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5";case 2:return"grid-cols-1 md:grid-cols-2 xl:grid-cols-3";case 3:return"grid-cols-1 lg:grid-cols-2";case 4:return"grid-cols-1";default:return"grid-cols-1 md:grid-cols-2 xl:grid-cols-3"}},Me=["S","M","L","XL"];w.useEffect(()=>D.getQueryCache().subscribe(de=>{de.type==="updated"&&Array.isArray(de.query.queryKey)&&de.query.queryKey[0]==="printerStatus"&&T(ye=>ye+1)}),[D]);const Oe=w.useMemo(()=>{if(!te)return[];let Pe=te;if(b.trim()){const de=b.trim().toLowerCase();Pe=Pe.filter(ye=>ye.name.toLowerCase().includes(de)||(ye.model||"").toLowerCase().includes(de)||(ye.location||"").toLowerCase().includes(de)||(ye.serial_number||"").toLowerCase().includes(de))}return P!=="all"&&(Pe=Pe.filter(de=>(de.location||"")===P)),_!=="all"&&(Pe=Pe.filter(de=>{const ye=D.getQueryData(["printerStatus",de.id]);if(!ye?.connected)return _==="offline";const Be=ye.hms_errors?om(ye.hms_errors):[];switch(_){case"printing":return ye.state==="RUNNING";case"paused":return ye.state==="PAUSE";case"finished":return ye.state==="FINISH";case"error":return ye.state==="FAILED"||Be.length>0;case"idle":return ye.state!=="RUNNING"&&ye.state!=="PAUSE"&&ye.state!=="FINISH"&&ye.state!=="FAILED"&&Be.length===0;case"offline":return!1;default:return!0}})),Pe},[te,b,_,P,D,A]),Re=w.useMemo(()=>te?[...new Set(te.map(Pe=>Pe.location||"").filter(Boolean))].sort():[],[te]),$e=w.useMemo(()=>{const Pe=[...Oe];switch(d){case"name":Pe.sort((de,ye)=>de.name.localeCompare(ye.name));break;case"model":Pe.sort((de,ye)=>(de.model||"").localeCompare(ye.model||""));break;case"location":Pe.sort((de,ye)=>{const Be=de.location||"",Qe=ye.location||"";return!Be&&Qe?1:Be&&!Qe?-1:Be.localeCompare(Qe)||de.name.localeCompare(ye.name)});break;case"status":Pe.sort((de,ye)=>{const Be=D.getQueryData(["printerStatus",de.id]),Qe=D.getQueryData(["printerStatus",ye.id]),ht=xt=>xt?.connected?(xt.hms_errors?om(xt.hms_errors):[]).length>0?0:xt.state==="RUNNING"?1:2:3;return ht(Be)-ht(Qe)});break}return m||Pe.reverse(),Pe},[Oe,d,m,D]),Xe=w.useCallback(()=>{V(new Set($e.map(Pe=>Pe.id))),se(!0)},[$e]),tt=w.useCallback(Pe=>{V(de=>{const ye=new Set(de);return $e.forEach(Be=>{const Qe=D.getQueryData(["printerStatus",Be.id]);dK(Qe)===Pe&&ye.add(Be.id)}),ye}),se(!0)},[$e,D]),we=w.useCallback(Pe=>{V(de=>{const ye=new Set(de);return $e.filter(Be=>(Be.location||"")===Pe).forEach(Be=>ye.add(Be.id)),ye}),se(!0)},[$e]),ze=w.useCallback(Pe=>{V(de=>{const ye=new Set(de);return $e.filter(Be=>(Be.model||"Unknown")===Pe).forEach(Be=>ye.add(Be.id)),ye}),se(!0)},[$e]),ce=w.useCallback(Pe=>{k(de=>{const ye={...de,[Pe]:!de[Pe]};try{localStorage.setItem("printerCollapsedSections",JSON.stringify(ye))}catch{}return ye})},[]),qe=w.useMemo(()=>{if(d==="name")return null;const Pe={};return d==="location"?$e.forEach(de=>{const ye=de.location||"Ungrouped";Pe[ye]||(Pe[ye]=[]),Pe[ye].push(de)}):d==="model"?$e.forEach(de=>{const ye=de.model||"Unknown";Pe[ye]||(Pe[ye]=[]),Pe[ye].push(de)}):d==="status"&&$e.forEach(de=>{const ye=D.getQueryData(["printerStatus",de.id]),Be=dK(ye);Pe[Be]||(Pe[Be]=[]),Pe[Be].push(de)}),Pe},[d,$e,D,A]);return a.jsxs("div",{className:"p-4 md:p-8",children:[a.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-6",children:[a.jsxs("div",{children:[a.jsx("h1",{className:"text-2xl font-bold text-white",children:t("printers.title")}),a.jsx(R7e,{printers:te}),te&&te.length>0&&a.jsxs("div",{className:"relative w-full sm:max-w-sm mt-3",children:[a.jsx(Pr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50"}),a.jsx("input",{type:"search",name:"printer-search",autoComplete:"off","data-1p-ignore":!0,"data-lpignore":"true",value:b,onChange:Pe=>g(Pe.target.value),placeholder:t("printers.search"),"aria-label":t("printers.search"),className:"w-full pl-10 pr-8 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green"}),b&&a.jsx("button",{type:"button","aria-label":t("common.clear"),onClick:()=>g(""),className:"absolute right-3 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white",children:a.jsx(Bt,{className:"w-4 h-4"})})]})]}),a.jsxs("div",{className:"flex items-center gap-2 sm:gap-3 flex-wrap",children:[a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsxs("select",{value:d,onChange:Pe=>he(Pe.target.value),className:"text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg px-2 py-1.5 text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"name",children:t("printers.sort.name")}),a.jsx("option",{value:"status",children:t("printers.sort.status")}),a.jsx("option",{value:"model",children:t("printers.sort.model")}),a.jsx("option",{value:"location",children:t("printers.sort.location")})]}),a.jsx("button",{onClick:Ce,className:"p-1.5 rounded-lg hover:bg-bambu-dark-tertiary transition-colors",title:t(m?"printers.sort.descending":"printers.sort.ascending"),children:m?a.jsx(fp,{className:"w-4 h-4 text-bambu-gray"}):a.jsx(cg,{className:"w-4 h-4 text-bambu-gray"})})]}),te&&te.length>0&&a.jsxs("select",{value:_,onChange:Pe=>C(Pe.target.value),className:"text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg px-2 py-1.5 text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"all",children:t("printers.filter.allStatuses")}),a.jsx("option",{value:"printing",children:t("printers.status.printing")}),a.jsx("option",{value:"paused",children:t("printers.status.paused")}),a.jsx("option",{value:"idle",children:t("printers.status.idle")}),a.jsx("option",{value:"finished",children:t("printers.status.finished")}),a.jsx("option",{value:"error",children:t("printers.status.error")}),a.jsx("option",{value:"offline",children:t("printers.status.offline")})]}),te&&te.length>0&&Re.length>0&&a.jsxs("select",{value:P,onChange:Pe=>N(Pe.target.value),className:"text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg px-2 py-1.5 text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"all",children:t("printers.filter.allLocations")}),Re.map(Pe=>a.jsx("option",{value:Pe,children:Pe},Pe))]}),a.jsx("div",{className:"flex items-center bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:Me.map((Pe,de)=>{const ye=de+1,Be=f===ye;return a.jsx("button",{onClick:()=>{y(ye),localStorage.setItem("printerCardSize",String(ye))},className:`px-2 py-1.5 text-xs font-medium transition-colors ${de===0?"rounded-l-lg":""} ${de===Me.length-1?"rounded-r-lg":""} ${Be?"bg-bambu-green text-white":"text-bambu-gray hover:bg-bambu-dark-tertiary hover:text-white"}`,title:t(Pe==="S"?"printers.cardSize.small":Pe==="M"?"printers.cardSize.medium":Pe==="L"?"printers.cardSize.large":"printers.cardSize.extraLarge"),children:Pe},Pe)})}),a.jsx("button",{onClick:()=>{R?Se():se(!0)},className:`p-1.5 rounded-lg transition-colors ${R?"bg-bambu-green text-white":"hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white"}`,title:t("printers.bulk.select"),disabled:!z("printers:control"),children:a.jsx(Ns,{className:"w-4 h-4"})}),a.jsx("div",{className:"w-px h-6 bg-bambu-dark-tertiary"}),a.jsxs("label",{className:"flex items-center gap-2 text-sm text-bambu-gray cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:r,onChange:je,className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),t("printers.hideOffline")]}),r&&Object.keys(ue).length>0&&a.jsxs("div",{className:"relative",children:[a.jsxs("button",{onClick:()=>o(!s),className:"flex items-center gap-1.5 px-3 py-1.5 text-sm bg-white dark:bg-bambu-dark-secondary border border-gray-200 dark:border-bambu-dark-tertiary rounded-lg text-gray-600 dark:text-bambu-gray hover:text-gray-900 dark:hover:text-white hover:border-bambu-green transition-colors",children:[a.jsx(Yd,{className:"w-4 h-4"}),t("printers.powerOn"),a.jsx(On,{className:`w-3 h-3 transition-transform ${s?"rotate-180":""}`})]}),s&&a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>o(!1)}),a.jsxs("div",{className:"absolute right-0 mt-2 w-56 bg-white dark:bg-bambu-dark-secondary border border-gray-200 dark:border-bambu-dark-tertiary rounded-lg shadow-lg z-20 py-1",children:[a.jsx("div",{className:"px-3 py-2 text-xs text-gray-500 dark:text-bambu-gray border-b border-gray-200 dark:border-bambu-dark-tertiary",children:t("printers.offlinePrintersWithPlugs")}),te?.filter(Pe=>ue[Pe.id]).map(Pe=>a.jsx(B7e,{printer:Pe,plug:ue[Pe.id],onPowerOn:de=>{c(de),G.mutate(de)},isPowering:l===ue[Pe.id]?.id},Pe.id)),te?.filter(Pe=>ue[Pe.id]).length===0&&a.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:"No printers with smart plugs"})]})]})]}),a.jsxs(De,{onClick:()=>n(!0),disabled:!z("printers:create"),title:z("printers:create")?void 0:t("printers.permission.noAdd"),children:[a.jsx(sr,{className:"w-4 h-4"}),t("printers.addPrinter")]})]})]}),ie?a.jsx("div",{className:"text-center py-12 text-bambu-gray",children:t("common.loading")}):te?.length===0?a.jsx(Tt,{children:a.jsxs(Mt,{className:"text-center py-12",children:[a.jsx("p",{className:"text-bambu-gray mb-4",children:t("printers.noPrintersConfigured")}),a.jsxs(De,{onClick:()=>n(!0),disabled:!z("printers:create"),title:z("printers:create")?void 0:t("printers.permission.noAdd"),children:[a.jsx(sr,{className:"w-4 h-4"}),t("printers.addPrinter")]})]})}):$e.length===0&&(b.trim()||_!=="all"||P!=="all")?a.jsx(Tt,{children:a.jsx(Mt,{className:"text-center py-12",children:a.jsx("p",{className:"text-bambu-gray",children:t("printers.noSearchResults")})})}):qe?a.jsx("div",{className:"space-y-6",children:(()=>{const Pe=d==="status"?L7e.filter(de=>qe[de]?.length>0):Object.keys(qe);return m?Pe:[...Pe].reverse()})().map(Pe=>{const de=qe[Pe],ye=`${d}:${Pe}`,Be=!F[ye],Qe=d==="status"&&cK[Pe]?.dot||"bg-bambu-green",ht=d==="status"?t(cK[Pe]?.labelKey||Pe):Pe;return a.jsx(Sz,{open:Be,onToggle:()=>ce(ye),summaryClassName:"py-1",summary:a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx("span",{className:`w-2 h-2 rounded-full ${Qe}`}),ht,a.jsxs("span",{className:"text-sm font-normal text-bambu-gray",children:["(",de.length,")"]}),R&&a.jsx("button",{onClick:xt=>{xt.stopPropagation(),d==="location"?we(Pe==="Ungrouped"?"":Pe):d==="status"?tt(Pe):d==="model"&&ze(Pe)},className:"text-xs text-bambu-green hover:text-bambu-green-light transition-colors ml-1",children:t("printers.bulk.selectAll")})]}),children:a.jsx("div",{className:`grid gap-4 ${f>=3?"gap-6":""} ${Fe()}`,children:de.map(xt=>a.jsx(mK,{printer:xt,hideIfDisconnected:r,maintenanceInfo:U[xt.id],viewMode:v,cardSize:f,amsThresholds:J?{humidityGood:Number(J.ams_humidity_good)||40,humidityFair:Number(J.ams_humidity_fair)||60,tempGood:Number(J.ams_temp_good)||28,tempFair:Number(J.ams_temp_fair)||35}:void 0,spoolmanEnabled:ne,hasUnlinkedSpools:q,linkedSpools:E,spoolmanUrl:W?.url,spoolmanSyncMode:xe,onGetAssignment:K,onUnassignSpool:(gt,Ut,Wt)=>O.mutate({printerId:gt,amsId:Ut,trayId:Wt}),timeFormat:J?.time_format||"system",cameraViewMode:J?.camera_view_mode||"window",onOpenEmbeddedCamera:(gt,Ut)=>L(Wt=>new Map(Wt).set(gt,{id:gt,name:Ut})),checkPrinterFirmware:J?.check_printer_firmware!==!1,dryingPresets:oe,requirePlateClear:J?.require_plate_clear===!0,selectionMode:R,isSelected:X.has(xt.id),onToggleSelect:ae},xt.id))})},Pe)})}):a.jsx("div",{className:`grid gap-4 ${f>=3?"gap-6":""} ${Fe()}`,children:$e.map(Pe=>a.jsx(mK,{printer:Pe,hideIfDisconnected:r,maintenanceInfo:U[Pe.id],viewMode:v,cardSize:f,spoolmanEnabled:ne,hasUnlinkedSpools:q,linkedSpools:E,spoolmanUrl:W?.url,spoolmanSyncMode:xe,onGetAssignment:K,onUnassignSpool:(de,ye,Be)=>O.mutate({printerId:de,amsId:ye,trayId:Be}),amsThresholds:J?{humidityGood:Number(J.ams_humidity_good)||40,humidityFair:Number(J.ams_humidity_fair)||60,tempGood:Number(J.ams_temp_good)||28,tempFair:Number(J.ams_temp_fair)||35}:void 0,timeFormat:J?.time_format||"system",cameraViewMode:J?.camera_view_mode||"window",onOpenEmbeddedCamera:(de,ye)=>L(Be=>new Map(Be).set(de,{id:de,name:ye})),checkPrinterFirmware:J?.check_printer_firmware!==!1,dryingPresets:oe,requirePlateClear:J?.require_plate_clear===!0,selectionMode:R,isSelected:X.has(Pe.id),onToggleSelect:ae},Pe.id))}),e&&a.jsx(O7e,{onClose:()=>n(!1),onAdd:Pe=>I.mutate(Pe),existingSerials:te?.map(Pe=>Pe.serial_number)||[]}),R&&te&&a.jsx(Gye,{selectedIds:X,printers:te,onClose:Se,onSelectAll:Xe,onSelectByLocation:we,onSelectByState:tt,onAction:Ae,actionPending:le}),be==="stop"&&a.jsx(yn,{title:t("printers.bulk.confirm.stopTitle",{count:X.size}),message:t("printers.bulk.confirm.stopMessage",{count:X.size}),confirmText:t("printers.bulk.confirm.stopButton"),variant:"danger",isLoading:le,onConfirm:()=>ve("stop"),onCancel:()=>fe(null)}),be==="pause"&&a.jsx(yn,{title:t("printers.bulk.confirm.pauseTitle",{count:X.size}),message:t("printers.bulk.confirm.pauseMessage",{count:X.size}),confirmText:t("printers.bulk.confirm.pauseButton"),isLoading:le,onConfirm:()=>ve("pause"),onCancel:()=>fe(null)}),be==="clearPlate"&&a.jsx(yn,{title:t("printers.bulk.confirm.clearPlateTitle",{count:X.size}),message:t("printers.bulk.confirm.clearPlateMessage",{count:X.size}),confirmText:t("printers.bulk.confirm.clearPlateButton"),isLoading:le,onConfirm:()=>ve("clearPlate"),onCancel:()=>fe(null)}),Array.from(Q.values()).map((Pe,de)=>a.jsx(WMe,{printerId:Pe.id,printerName:Pe.name,viewerIndex:de,onClose:()=>L(ye=>{const Be=new Map(ye);return Be.delete(Pe.id),Be})},Pe.id))]})}function q7e(){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 qf(t,e="bambu_studio"){let n;e==="orcaslicer"?n=`orcaslicer://open?file=${t}`:q7e()==="macos"?n=`bambustudioopen://${encodeURIComponent(t)}`:n=`bambustudio://open?file=${t}`;const r=document.createElement("a");r.href=n,r.style.display="none",document.body.appendChild(r),r.click(),document.body.removeChild(r)}const hK=768;function rie(){const[t,e]=w.useState(()=>typeof window<"u"?window.innerWidth{const n=window.matchMedia(`(max-width: ${hK-1}px)`),r=i=>{e(i.matches)};return e(n.matches),n.addEventListener("change",r),()=>n.removeEventListener("change",r)},[]),t}function $7e({onClose:t,initialFiles:e}){const{t:n}=Ft(),r=nn(),{showToast:i}=hn(),s=w.useRef(null),[o,l]=w.useState(()=>e?.filter(N=>N.name.endsWith(".3mf")).map(N=>({file:N,status:"pending"}))||[]),[c,d]=w.useState(!1),[u,m]=w.useState(null);w.useEffect(()=>{const N=A=>{A.key==="Escape"&&t()};return window.addEventListener("keydown",N),()=>window.removeEventListener("keydown",N)},[t]);const p=it({mutationFn:N=>me.uploadArchivesBulk(N),onSuccess:N=>{m(N),r.invalidateQueries({queryKey:["archives"]}),r.invalidateQueries({queryKey:["archiveStats"]}),l(A=>A.map(T=>{const F=N.results.find(D=>D.filename===T.file.name),k=N.errors.find(D=>D.filename===T.file.name);return F?{...T,status:"success",archiveId:F.id}:k?{...T,status:"error",error:k.error}:T})),N.failed===0?i(`${N.uploaded} file${N.uploaded!==1?"s":""} uploaded`):N.uploaded===0?i(`Failed to upload ${N.failed} file${N.failed!==1?"s":""}`,"error"):i(`${N.uploaded} uploaded, ${N.failed} failed`,"warning")},onError:()=>{l(N=>N.map(A=>({...A,status:"error",error:"Upload failed"}))),i("Upload failed","error")}}),f=w.useCallback(N=>{N.preventDefault(),d(!0)},[]),y=w.useCallback(N=>{N.preventDefault(),d(!1)},[]),v=w.useCallback(N=>{N.preventDefault(),d(!1);const A=Array.from(N.dataTransfer.files).filter(T=>T.name.endsWith(".3mf"));A.length>0&&l(T=>[...T,...A.map(F=>({file:F,status:"pending"}))])},[]),b=w.useCallback(N=>{const A=Array.from(N.target.files||[]).filter(T=>T.name.endsWith(".3mf"));A.length>0&&l(T=>[...T,...A.map(F=>({file:F,status:"pending"}))]),s.current&&(s.current.value="")},[]),g=w.useCallback(N=>{l(A=>A.filter((T,F)=>F!==N))},[]),_=()=>{if(o.length===0)return;const N=o.filter(A=>A.status==="pending");N.length!==0&&(l(A=>A.map(T=>T.status==="pending"?{...T,status:"uploading"}:T)),p.mutate(N.map(A=>A.file)))},C=o.filter(N=>N.status==="pending").length,P=p.isPending;return a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:a.jsx(Tt,{className:"w-full max-w-2xl max-h-[90vh] flex flex-col",children:a.jsxs(Mt,{className:"p-0 flex flex-col h-full",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsx("h2",{className:"text-xl font-semibold text-white",children:n("uploadModal.title")}),a.jsx("button",{onClick:t,className:"text-bambu-gray hover:text-white transition-colors",children:a.jsx(Bt,{className:"w-5 h-5"})})]}),a.jsx("div",{className:"p-4",children:a.jsxs("div",{className:`border-2 border-dashed rounded-lg p-8 text-center transition-colors ${c?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary hover:border-bambu-gray"}`,onDragOver:f,onDragLeave:y,onDrop:v,children:[a.jsx(Oa,{className:"w-12 h-12 mx-auto mb-4 text-bambu-gray"}),a.jsx("p",{className:"text-white mb-2",children:n("uploadModal.dragDrop")}),a.jsx("p",{className:"text-bambu-gray text-sm mb-4",children:n("uploadModal.or")}),a.jsx(De,{variant:"secondary",onClick:()=>s.current?.click(),disabled:P,children:n("uploadModal.browseFiles")}),a.jsx("input",{ref:s,type:"file",accept:".3mf",multiple:!0,className:"hidden",onChange:b})]})}),a.jsx("div",{className:"px-4 pb-4",children:a.jsx("p",{className:"text-xs text-bambu-gray",children:n("uploadModal.extractionInfo")})}),o.length>0&&a.jsx("div",{className:"px-4 pb-4 max-h-60 overflow-y-auto",children:a.jsx("div",{className:"space-y-2",children:o.map((N,A)=>a.jsxs("div",{className:"flex items-center gap-3 p-3 bg-bambu-dark rounded-lg",children:[a.jsx(qP,{className:"w-5 h-5 text-bambu-gray flex-shrink-0"}),a.jsx("span",{className:"flex-1 text-white text-sm truncate",children:N.file.name}),a.jsxs("span",{className:"text-xs text-bambu-gray",children:[(N.file.size/(1024*1024)).toFixed(1)," MB"]}),N.status==="pending"&&a.jsx("button",{onClick:()=>g(A),className:"text-bambu-gray hover:text-red-400 transition-colors",disabled:P,children:a.jsx(Bt,{className:"w-4 h-4"})}),N.status==="uploading"&&a.jsx(ft,{className:"w-4 h-4 text-bambu-green animate-spin"}),N.status==="success"&&a.jsx(yr,{className:"w-4 h-4 text-bambu-green"}),N.status==="error"&&a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-xs text-red-400",children:N.error}),a.jsx(ei,{className:"w-4 h-4 text-red-400"})]})]},`${N.file.name}-${A}`))})}),u&&a.jsx("div",{className:"px-4 pb-4",children:a.jsx("div",{className:"p-3 bg-bambu-dark rounded-lg",children:a.jsxs("p",{className:"text-sm text-white",children:[a.jsx("span",{className:"text-bambu-green",children:u.uploaded})," ",n("uploadModal.uploaded"),u.failed>0&&a.jsxs(a.Fragment,{children:[", ",a.jsx("span",{className:"text-red-400",children:u.failed})," ",n("uploadModal.failed")]})]})})}),a.jsxs("div",{className:"flex gap-3 p-4 border-t border-bambu-dark-tertiary",children:[a.jsx(De,{variant:"secondary",onClick:t,className:"flex-1",children:n(u?"common.close":"common.cancel")}),!u&&a.jsx(De,{onClick:_,disabled:C===0||P,className:"flex-1",children:P?a.jsxs(a.Fragment,{children:[a.jsx(ft,{className:"w-4 h-4 animate-spin"}),n("uploadModal.uploading")]}):a.jsxs(a.Fragment,{children:[a.jsx(Oa,{className:"w-4 h-4"}),n("uploadModal.upload")," ",C>0&&`(${C})`]})})]})]})})})}const V7e=["adhesionFailure","spaghettiDetached","layerShift","cloggedNozzle","filamentRunout","warping","stringing","underExtrusion","powerFailure","userCancelled","other"],G7e=["completed","failed","aborted","printing"];function aie({archive:t,onClose:e,existingTags:n=[]}){const{t:r}=Ft();w.useEffect(()=>{const j=O=>{O.key==="Escape"&&e()};return window.addEventListener("keydown",j),()=>window.removeEventListener("keydown",j)},[e]);const i=nn(),[s,o]=w.useState(t.print_name||""),[l,c]=w.useState(t.printer_id),[d,u]=w.useState(t.project_id??null),[m,p]=w.useState(t.notes||""),[f,y]=w.useState(t.tags||""),[v,b]=w.useState(t.failure_reason||""),[g,_]=w.useState(t.status),[C,P]=w.useState(t.quantity??1),[N,A]=w.useState(t.photos||[]),[T,F]=w.useState(t.external_url||""),[k,D]=w.useState(!1),[H,z]=w.useState(!1),Q=w.useRef(null),L=w.useRef(null),te=w.useRef(null),{data:ie}=Ye({queryKey:["printers"],queryFn:me.getPrinters}),{data:J}=Ye({queryKey:["projects"],queryFn:()=>me.getProjects()}),{data:oe}=Ye({queryKey:["tags"],queryFn:me.getTags,enabled:n.length===0}),ge=n.length>0?n:oe?.map(j=>j.name)||[],re=f.split(",").map(j=>j.trim()).filter(Boolean),W=f.includes(",")?f.substring(f.lastIndexOf(",")+1).trim().toLowerCase():f.trim().toLowerCase(),ne=ge.filter(j=>!re.includes(j)&&(W===""||j.toLowerCase().includes(W))),pe=j=>{let O;if(W&&!ge.includes(W)?O=f.includes(",")?f.substring(0,f.lastIndexOf(",")).split(",").map(K=>K.trim()).filter(Boolean):[]:O=re,!O.includes(j)){const K=[...O,j].join(", ");y(K)}te.current!==null&&clearTimeout(te.current),Q.current?.focus()},xe=j=>{const O=re.filter(K=>K!==j).join(", ");y(O)},Ne=it({mutationFn:j=>me.updateArchive(t.id,j),onSuccess:()=>{i.invalidateQueries({queryKey:["archives"]}),i.invalidateQueries({queryKey:["projects"]}),e()}}),q=async j=>{const O=j.target.files?.[0];if(O){D(!0);try{const K=await me.uploadArchivePhoto(t.id,O);A(K.photos),i.invalidateQueries({queryKey:["archives"]})}catch(K){console.error("Failed to upload photo:",K)}finally{D(!1),L.current&&(L.current.value="")}}},Y=async j=>{try{const O=await me.deleteArchivePhoto(t.id,j);A(O.photos||[]),i.invalidateQueries({queryKey:["archives"]})}catch(O){console.error("Failed to delete photo:",O)}},E=j=>{j.preventDefault();const O={print_name:s||void 0,printer_id:l,project_id:d,notes:m||void 0,tags:f||void 0,quantity:C,external_url:T||null};g!==t.status&&(O.status=g),g==="failed"||g==="aborted"?O.failure_reason=v||void 0:(t.status==="failed"||t.status==="aborted")&&(O.failure_reason=null),Ne.mutate(O)};return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:e,children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary w-full max-w-md max-h-[90vh] flex flex-col",onClick:j=>j.stopPropagation(),children:[a.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[a.jsx("h2",{className:"text-lg font-semibold text-white",children:r("editArchive.title")}),a.jsx("button",{onClick:e,className:"text-bambu-gray hover:text-white transition-colors",children:a.jsx(Bt,{className:"w-5 h-5"})})]}),a.jsxs("form",{onSubmit:E,className:"p-6 space-y-4 overflow-y-auto flex-1",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("editArchive.name")}),a.jsx("input",{type:"text",value:s,onChange:j=>o(j.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",placeholder:r("editArchive.namePlaceholder")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("editArchive.printer")}),a.jsxs("select",{value:l??"",onChange:j=>c(j.target.value?Number(j.target.value):null),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"",children:r("editArchive.noPrinter")}),ie?.map(j=>a.jsx("option",{value:j.id,children:j.name},j.id))]})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[a.jsx(Bs,{className:"w-4 h-4 inline mr-1"}),r("editArchive.project")]}),a.jsxs("select",{value:d??"",onChange:j=>u(j.target.value?Number(j.target.value):null),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"",children:r("editArchive.noProject")}),J?.map(j=>a.jsx("option",{value:j.id,children:j.name},j.id))]})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[a.jsx(Lge,{className:"w-4 h-4 inline mr-1"}),r("editArchive.itemsPrinted")]}),a.jsx("input",{type:"number",min:1,value:C,onChange:j=>P(Math.max(1,parseInt(j.target.value)||1)),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",placeholder:"1"}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:r("editArchive.itemsPrintedHelp")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("editArchive.notes")}),a.jsx("textarea",{value:m,onChange:j=>p(j.target.value),rows:3,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none resize-none",placeholder:r("editArchive.notesPlaceholder")})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[a.jsx(Sy,{className:"w-4 h-4 inline mr-1"}),r("editArchive.externalLink")]}),a.jsx("input",{type:"url",value:T,onChange:j=>F(j.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",placeholder:"https://printables.com/model/..."}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:r("editArchive.externalLinkHelp")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("editArchive.tags")}),re.length>0&&a.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:re.map(j=>a.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 bg-bambu-dark-tertiary rounded text-sm text-white",children:[a.jsx(xm,{className:"w-3 h-3"}),j,a.jsx("button",{type:"button",onClick:()=>xe(j),className:"ml-0.5 text-bambu-gray hover:text-white",children:a.jsx(Bt,{className:"w-3 h-3"})})]},j))}),a.jsxs("div",{className:"relative",children:[a.jsx("input",{ref:Q,type:"text",value:f,onChange:j=>y(j.target.value),onFocus:()=>{te.current!==null&&clearTimeout(te.current),z(!0)},onBlur:()=>{te.current=window.setTimeout(()=>z(!1),200)},className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",placeholder:re.length>0?r("editArchive.addMoreTags"):r("editArchive.tagsPlaceholder")}),H&&ne.length>0&&a.jsxs("div",{className:"absolute top-full left-0 right-0 mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg z-10 max-h-40 overflow-y-auto",children:[a.jsxs("div",{className:"p-2 text-xs text-bambu-gray border-b border-bambu-dark-tertiary",children:[W?r("editArchive.matchingTags",{query:W}):r("editArchive.existingTags")," ",r("editArchive.clickToAdd")]}),a.jsx("div",{className:"p-2 flex flex-wrap gap-1.5",children:ne.map(j=>a.jsx("button",{type:"button",onClick:()=>pe(j),className:"px-2 py-0.5 bg-bambu-dark-tertiary hover:bg-bambu-green/20 rounded text-sm text-bambu-gray hover:text-white transition-colors",children:j},j))})]})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("editArchive.status")}),a.jsx("select",{value:g,onChange:j=>{_(j.target.value),j.target.value==="completed"&&b("")},className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:G7e.map(j=>a.jsx("option",{value:j,children:r(`editArchive.statuses.${j}`)},j))})]}),(g==="failed"||g==="aborted")&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("editArchive.failureReason")}),a.jsxs("select",{value:v,onChange:j=>b(j.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"",children:r("editArchive.selectReason")}),V7e.map(j=>a.jsx("option",{value:r(`editArchive.failureReasons.${j}`),children:r(`editArchive.failureReasons.${j}`)},j))]})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[a.jsx(qx,{className:"w-4 h-4 inline mr-1"}),r("editArchive.photos")]}),a.jsxs("div",{className:"flex flex-wrap gap-2 mb-2",children:[N.map(j=>a.jsxs("div",{className:"relative group",children:[a.jsx("img",{src:me.getArchivePhotoUrl(t.id,j),alt:r("editArchive.printResult"),className:"w-20 h-20 object-cover rounded-lg border border-bambu-dark-tertiary"}),a.jsx("button",{type:"button",onClick:()=>Y(j),className:"absolute -top-1 -right-1 p-1 bg-red-500 rounded-full opacity-0 group-hover:opacity-100 transition-opacity",children:a.jsx(en,{className:"w-3 h-3 text-white"})})]},j)),a.jsxs("label",{className:"w-20 h-20 flex items-center justify-center border-2 border-dashed border-bambu-dark-tertiary rounded-lg cursor-pointer hover:border-bambu-green transition-colors",children:[a.jsx("input",{ref:L,type:"file",accept:"image/jpeg,image/png,image/webp",onChange:q,className:"hidden",disabled:k}),k?a.jsx(ft,{className:"w-6 h-6 text-bambu-gray animate-spin"}):a.jsx(sr,{className:"w-6 h-6 text-bambu-gray"})]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:r("editArchive.photosHelp")})]}),a.jsxs("div",{className:"flex gap-3 pt-2",children:[a.jsx(De,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:r("common.cancel")}),a.jsxs(De,{type:"submit",disabled:Ne.isPending,className:"flex-1",children:[a.jsx(_s,{className:"w-4 h-4"}),Ne.isPending?r("common.saving"):r("common.save")]})]})]})]})})}function iie({x:t,y:e,items:n,onClose:r}){const i=w.useRef(null),[s,o]=w.useState(null),l=w.useRef(null),[c,d]=w.useState({x:t,y:e,visible:!1}),[u,m]=w.useState(!1),[p,f]=w.useState({});w.useEffect(()=>{const b=C=>{i.current&&!i.current.contains(C.target)&&r()},g=C=>{C.key==="Escape"&&r()},_=()=>{r()};return document.addEventListener("mousedown",b),document.addEventListener("keydown",g),document.addEventListener("scroll",_,!0),()=>{document.removeEventListener("mousedown",b),document.removeEventListener("keydown",g),document.removeEventListener("scroll",_,!0),l.current&&clearTimeout(l.current)}},[r]),w.useLayoutEffect(()=>{if(i.current){i.current.style.visibility="hidden",i.current.style.display="block";const b=i.current.getBoundingClientRect(),g=window.innerWidth,_=window.innerHeight,C=8;let P=t,N=e;t+b.width>g-C&&(P=Math.max(C,g-b.width-C)),P_-C&&(N=Math.max(C,_-b.height-C)),NA),d({x:P,y:N,visible:!0})}},[t,e]);const y=(b,g)=>{l.current&&(clearTimeout(l.current),l.current=null);const _=g.getBoundingClientRect(),C=window.innerHeight,P=300,T=C-_.top-8P;f(F=>({...F,[b]:T?"bottom":"top"})),o(b)},v=()=>{l.current=window.setTimeout(()=>{o(null)},150)};return a.jsx("div",{ref:i,className:"fixed z-50 min-w-[180px] max-w-[280px] bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl py-1",style:{left:c.x,top:c.y,visibility:c.visible?"visible":"hidden"},children:n.map((b,g)=>{if(b.divider)return a.jsx("div",{className:"my-1 border-t border-bambu-dark-tertiary"},g);const _=b.submenu&&b.submenu.length>0;return a.jsxs("div",{className:"relative",onMouseEnter:C=>_&&y(g,C.currentTarget),onMouseLeave:()=>_&&v(),children:[a.jsxs("button",{onMouseEnter:C=>_&&y(g,C.currentTarget.parentElement),onClick:()=>{_?o(s===g?null:g):b.disabled||(b.onClick(),r())},disabled:b.disabled,title:b.title,className:`w-full flex items-center gap-2 px-3 py-2 text-sm text-left transition-colors ${b.disabled?"text-bambu-gray cursor-not-allowed":b.danger?"text-red-400 hover:bg-red-400/10":"text-white hover:bg-bambu-dark-tertiary"} ${_&&s===g?"bg-bambu-dark-tertiary":""}`,children:[b.icon&&a.jsx("span",{className:"w-4 h-4 flex-shrink-0 flex items-center justify-center",children:b.icon}),a.jsx("span",{className:"flex-1",children:b.label}),_&&a.jsx(ti,{className:"w-4 h-4 text-bambu-gray"})]}),_&&s===g&&a.jsx("div",{className:`absolute min-w-[160px] bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl py-1 overflow-hidden max-h-[300px] overflow-y-auto z-[60] ${u?"right-full mr-1":"left-full ml-1"} ${p[g]==="bottom"?"bottom-0":"top-0"}`,onMouseEnter:()=>{l.current&&(clearTimeout(l.current),l.current=null)},onMouseLeave:()=>v(),children:b.submenu.map((C,P)=>a.jsxs("button",{onClick:()=>{C.disabled||(C.onClick(),r())},disabled:C.disabled,className:`w-full flex items-center gap-2 px-3 py-2 text-sm text-left transition-colors ${C.disabled?"text-bambu-gray cursor-not-allowed":C.danger?"text-red-400 hover:bg-red-400/10":"text-white hover:bg-bambu-dark-tertiary"}`,children:[C.icon&&a.jsx("span",{className:"w-4 h-4 flex-shrink-0 flex items-center justify-center",children:C.icon}),C.label]},P))})]},g)})})}function W7e({selectedIds:t,existingTags:e,onClose:n}){const r=nn(),{showToast:i}=hn(),[s,o]=w.useState(""),[l,c]=w.useState(new Set),[d,u]=w.useState("add");w.useEffect(()=>{const v=b=>{b.key==="Escape"&&n()};return window.addEventListener("keydown",v),()=>window.removeEventListener("keydown",v)},[n]);const m=it({mutationFn:async()=>{const v=Array.from(l);let b=0;for(const g of t)try{const _=await me.getArchive(g),C=_.tags?_.tags.split(",").map(N=>N.trim()).filter(Boolean):[];let P;d==="add"?P=[...new Set([...C,...v])]:P=C.filter(N=>!l.has(N)),await me.updateArchive(g,{tags:P.join(", ")}),b++}catch(_){throw console.error(`Failed to update archive ${g}:`,_),new Error(`Failed on archive ${g}: ${_ instanceof Error?_.message:"Unknown error"}`)}return{count:b,mode:d,tags:v}},onSuccess:({count:v,mode:b,tags:g})=>{r.invalidateQueries({queryKey:["archives"]}),i(`${b==="add"?"Added":"Removed"} ${g.length} tag${g.length!==1?"s":""} ${b==="add"?"to":"from"} ${v} archive${v!==1?"s":""}`),n()},onError:v=>{i(v.message||"Failed to update tags","error")}}),p=v=>{c(b=>{const g=new Set(b);return g.has(v)?g.delete(v):g.add(v),g})},f=()=>{s.trim()&&!l.has(s.trim())&&(c(v=>new Set([...v,s.trim()])),o(""))},y=v=>{v.key==="Enter"&&(v.preventDefault(),f())};return a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:a.jsx(Tt,{className:"w-full max-w-md",children:a.jsxs(Mt,{className:"p-0",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(xm,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-xl font-semibold text-white",children:d==="add"?"Add Tags":"Remove Tags"})]}),a.jsx("button",{onClick:n,className:"text-bambu-gray hover:text-white transition-colors",children:a.jsx(Bt,{className:"w-5 h-5"})})]}),a.jsxs("div",{className:"p-4 space-y-4",children:[a.jsxs("p",{className:"text-sm text-bambu-gray",children:[d==="add"?"Add":"Remove"," tags for ",t.length," selected archive",t.length!==1?"s":""]}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx(De,{size:"sm",variant:d==="add"?"primary":"secondary",onClick:()=>u("add"),children:"Add Tags"}),a.jsx(De,{size:"sm",variant:d==="remove"?"primary":"secondary",onClick:()=>u("remove"),children:"Remove Tags"})]}),d==="add"&&a.jsxs("div",{className:"flex gap-2",children:[a.jsx("input",{type:"text",placeholder:"Enter new tag...",className:"flex-1 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",value:s,onChange:v=>o(v.target.value),onKeyDown:y}),a.jsx(De,{size:"sm",variant:"secondary",onClick:f,disabled:!s.trim(),children:a.jsx(sr,{className:"w-4 h-4"})})]}),e.length>0&&a.jsxs("div",{children:[a.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:"Existing tags:"}),a.jsx("div",{className:"flex flex-wrap gap-2",children:e.map(v=>a.jsx("button",{onClick:()=>p(v),className:`px-2 py-1 rounded text-sm transition-colors ${l.has(v)?"bg-bambu-green text-white":"bg-bambu-dark-tertiary text-bambu-gray-light hover:bg-bambu-dark"}`,children:v},v))})]}),l.size>0&&a.jsxs("div",{children:[a.jsxs("p",{className:"text-xs text-bambu-gray mb-2",children:["Tags to ",d==="add"?"add":"remove",":"]}),a.jsx("div",{className:"flex flex-wrap gap-2",children:Array.from(l).map(v=>a.jsxs("span",{className:`px-2 py-1 rounded text-sm flex items-center gap-1 ${d==="add"?"bg-green-500/20 text-green-400":"bg-red-500/20 text-red-400"}`,children:[v,a.jsx("button",{onClick:()=>p(v),className:"hover:opacity-70",children:a.jsx(Bt,{className:"w-3 h-3"})})]},v))})]})]}),a.jsxs("div",{className:"flex gap-3 p-4 border-t border-bambu-dark-tertiary",children:[a.jsx(De,{variant:"secondary",onClick:n,className:"flex-1",children:"Cancel"}),a.jsx(De,{onClick:()=>m.mutate(),disabled:l.size===0||m.isPending,className:"flex-1",children:m.isPending?a.jsxs(a.Fragment,{children:[a.jsx(ft,{className:"w-4 h-4 animate-spin"}),"Processing..."]}):a.jsxs(a.Fragment,{children:[a.jsx(xm,{className:"w-4 h-4"}),d==="add"?"Add Tags":"Remove Tags"]})})]})]})})})}function K7e({selectedIds:t,onClose:e}){const n=nn(),{showToast:r}=hn(),{data:i,isLoading:s}=Ye({queryKey:["projects"],queryFn:()=>me.getProjects()});w.useEffect(()=>{const u=m=>{m.key==="Escape"&&e()};return window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)},[e]);const o=()=>{n.invalidateQueries({queryKey:["archives"]}),n.invalidateQueries({queryKey:["projects"]}),n.invalidateQueries({queryKey:["project"]}),n.invalidateQueries({queryKey:["project-archives"]})},l=it({mutationFn:async u=>(await me.addArchivesToProject(u,t),u),onSuccess:u=>{const m=i?.find(p=>p.id===u);o(),r(`Added ${t.length} archive${t.length!==1?"s":""} to "${m?.name}"`),e()},onError:()=>{r("Failed to assign project","error")}}),c=it({mutationFn:async()=>{for(const u of t)await me.updateArchive(u,{project_id:null});return t.length},onSuccess:u=>{o(),r(`Removed ${u} archive${u!==1?"s":""} from project`),e()},onError:()=>{r("Failed to remove from project","error")}}),d=l.isPending||c.isPending;return a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:a.jsx(Tt,{className:"w-full max-w-md max-h-[80vh] flex flex-col",children:a.jsxs(Mt,{className:"p-0 flex flex-col min-h-0",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary shrink-0",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Bs,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-xl font-semibold text-white",children:"Assign to Project"})]}),a.jsx("button",{onClick:e,className:"text-bambu-gray hover:text-white transition-colors",disabled:d,children:a.jsx(Bt,{className:"w-5 h-5"})})]}),a.jsxs("div",{className:"p-4 space-y-3 overflow-y-auto min-h-0",children:[a.jsxs("p",{className:"text-sm text-bambu-gray",children:["Assign ",t.length," selected archive",t.length!==1?"s":""," to a project"]}),s?a.jsx("div",{className:"flex items-center justify-center py-8",children:a.jsx(ft,{className:"w-6 h-6 animate-spin text-bambu-gray"})}):a.jsxs("div",{className:"space-y-2",children:[a.jsxs("button",{onClick:()=>c.mutate(),disabled:d,className:"w-full flex items-center gap-3 p-3 rounded-lg bg-bambu-dark hover:bg-bambu-dark-tertiary border border-bambu-dark-tertiary transition-colors text-left disabled:opacity-50",children:[a.jsx("div",{className:"w-8 h-8 rounded-full bg-red-500/20 flex items-center justify-center shrink-0",children:a.jsx(Ma,{className:"w-4 h-4 text-red-400"})}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:"text-white font-medium",children:"Remove from project"}),a.jsx("p",{className:"text-sm text-bambu-gray truncate",children:"Clear project assignment"})]}),c.isPending&&a.jsx(ft,{className:"w-4 h-4 animate-spin text-bambu-gray shrink-0"})]}),i&&i.length>0&&a.jsxs("div",{className:"flex items-center gap-2 py-2",children:[a.jsx("div",{className:"flex-1 h-px bg-bambu-dark-tertiary"}),a.jsx("span",{className:"text-xs text-bambu-gray",children:"or assign to"}),a.jsx("div",{className:"flex-1 h-px bg-bambu-dark-tertiary"})]}),i?.map(u=>a.jsxs("button",{onClick:()=>l.mutate(u.id),disabled:d,className:"w-full flex items-center gap-3 p-3 rounded-lg bg-bambu-dark hover:bg-bambu-dark-tertiary border border-bambu-dark-tertiary transition-colors text-left disabled:opacity-50",children:[a.jsx("div",{className:"w-8 h-8 rounded-full flex items-center justify-center shrink-0",style:{backgroundColor:u.color?`${u.color}20`:"rgb(var(--bambu-green) / 0.2)"},children:a.jsx(Bs,{className:"w-4 h-4",style:{color:u.color||"rgb(var(--bambu-green))"}})}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:"text-white font-medium truncate",children:u.name}),a.jsxs("p",{className:"text-sm text-bambu-gray truncate",children:[u.archive_count," archive",u.archive_count!==1?"s":"",u.status&&` • ${u.status}`]})]}),l.isPending&&l.variables===u.id&&a.jsx(ft,{className:"w-4 h-4 animate-spin text-bambu-gray shrink-0"})]},u.id)),(!i||i.length===0)&&a.jsx("p",{className:"text-center text-bambu-gray py-4",children:"No projects yet. Create one from the Projects page."})]})]}),a.jsx("div",{className:"flex gap-3 p-4 border-t border-bambu-dark-tertiary shrink-0",children:a.jsx(De,{variant:"secondary",onClick:e,className:"flex-1",disabled:d,children:"Cancel"})})]})})})}function X7e(t,e){return new Date(t,e+1,0).getDate()}function Y7e(t,e){return new Date(t,e,1).getDay()}const Q7e=["January","February","March","April","May","June","July","August","September","October","November","December"],Z7e=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];function J7e({archives:t,onArchiveClick:e,highlightedArchiveId:n}){const r=new Date,[i,s]=w.useState(r.getMonth()),[o,l]=w.useState(r.getFullYear()),[c,d]=w.useState(null),[u,m]=w.useState(null),p=w.useMemo(()=>{const N=new Map;return t.forEach(A=>{const T=Zn(A.completed_at||A.created_at)||new Date,F=`${T.getFullYear()}-${String(T.getMonth()+1).padStart(2,"0")}-${String(T.getDate()).padStart(2,"0")}`,k=N.get(F)||[];k.push(A),N.set(F,k)}),N},[t]),f=X7e(o,i),y=Y7e(o,i),v=()=>{i===0?(s(11),l(o-1)):s(i-1)},b=()=>{i===11?(s(0),l(o+1)):s(i+1)},g=()=>{s(r.getMonth()),l(r.getFullYear())},_=[];for(let N=0;N{N!==c&&m(null),d(N)};return a.jsxs("div",{className:"flex flex-col lg:flex-row gap-6",children:[a.jsxs("div",{className:"flex-1",children:[a.jsxs("div",{className:"flex items-center justify-between mb-4",children:[a.jsx("button",{onClick:v,className:"p-2 hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:a.jsx(xl,{className:"w-5 h-5 text-bambu-gray"})}),a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white",children:[Q7e[i]," ",o]}),a.jsx("button",{onClick:g,className:"px-2 py-1 text-xs bg-bambu-dark-tertiary hover:bg-bambu-green/20 text-bambu-gray hover:text-white rounded transition-colors",children:"Today"})]}),a.jsx("button",{onClick:b,className:"p-2 hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:a.jsx(ti,{className:"w-5 h-5 text-bambu-gray"})})]}),a.jsx("div",{className:"grid grid-cols-7 gap-1 mb-1",children:Z7e.map(N=>a.jsx("div",{className:"text-center text-xs text-bambu-gray py-2",children:N},N))}),a.jsx("div",{className:"grid grid-cols-7 gap-1",children:_.map((N,A)=>{if(N===null)return a.jsx("div",{className:"aspect-square"},`empty-${A}`);const T=`${o}-${String(i+1).padStart(2,"0")}-${String(N).padStart(2,"0")}`,F=p.get(T)||[],k=F.length>0,D=N===r.getDate()&&i===r.getMonth()&&o===r.getFullYear(),H=T===c,z=F.filter(L=>L.status==="completed").length,Q=F.filter(L=>L.status==="failed").length;return a.jsxs("button",{onClick:()=>P(H?null:T),className:`aspect-square rounded-lg p-1 flex flex-col items-center justify-center transition-colors relative ${H?"bg-bambu-green text-white":D?"bg-bambu-green/20 text-white ring-2 ring-bambu-green":k?"bg-bambu-dark-tertiary hover:bg-bambu-dark-tertiary/70 text-white":"hover:bg-bambu-dark-tertiary/50 text-bambu-gray"}`,children:[a.jsx("span",{className:`text-sm font-medium ${D&&!H?"text-bambu-green":""}`,children:N}),k&&a.jsxs("div",{className:"absolute bottom-1 left-1/2 -translate-x-1/2 flex items-center gap-1",children:[a.jsx("div",{className:`w-2 h-2 rounded-full ${Q>0&&z===0?"bg-red-400":Q>0?"bg-yellow-400":"bg-green-400"}`}),a.jsx("span",{className:"text-xs font-medium",children:F.length})]})]},N)})}),a.jsx("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:a.jsxs("div",{className:"grid grid-cols-3 gap-4 text-center",children:[a.jsxs("div",{children:[a.jsx("div",{className:"text-2xl font-bold text-white",children:t.filter(N=>{const A=Zn(N.completed_at||N.created_at)||new Date;return A.getMonth()===i&&A.getFullYear()===o}).length}),a.jsx("div",{className:"text-xs text-bambu-gray",children:"Prints this month"})]}),a.jsxs("div",{children:[a.jsx("div",{className:"text-2xl font-bold text-green-400",children:t.filter(N=>{const A=Zn(N.completed_at||N.created_at)||new Date;return A.getMonth()===i&&A.getFullYear()===o&&N.status==="completed"}).length}),a.jsx("div",{className:"text-xs text-bambu-gray",children:"Successful"})]}),a.jsxs("div",{children:[a.jsx("div",{className:"text-2xl font-bold text-red-400",children:t.filter(N=>{const A=Zn(N.completed_at||N.created_at)||new Date;return A.getMonth()===i&&A.getFullYear()===o&&N.status==="failed"}).length}),a.jsx("div",{className:"text-xs text-bambu-gray",children:"Failed"})]})]})})]}),a.jsx("div",{className:"lg:w-80 bg-bambu-dark rounded-xl p-4",children:c?a.jsxs(a.Fragment,{children:[a.jsx("h3",{className:"text-sm font-medium text-bambu-gray mb-3",children:new Date(c+"T12:00:00").toLocaleDateString("en-US",{weekday:"long",month:"long",day:"numeric",year:"numeric"})}),C.length>0?a.jsx("div",{className:"calendar-scroll space-y-2 max-h-96 overflow-y-auto",children:C.map(N=>{const A=N.id===u||N.id===n;return a.jsxs("button",{onClick:()=>{m(N.id),e?.(N)},className:`w-full flex items-center gap-3 p-2 rounded-lg transition-colors text-left ${A?"":"hover:bg-bambu-dark-tertiary"}`,style:A?{outline:"4px solid #facc15",outlineOffset:"2px"}:void 0,children:[N.thumbnail_path?a.jsx("img",{src:me.getArchiveThumbnail(N.id),alt:"",className:"w-12 h-12 rounded object-cover"}):a.jsx("div",{className:"w-12 h-12 rounded bg-bambu-dark-tertiary flex items-center justify-center",children:a.jsx("span",{className:"text-xs text-bambu-gray",children:"3MF"})}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("p",{className:"text-sm text-white truncate",children:N.print_name||N.filename}),a.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[a.jsx("span",{className:N.status==="failed"?"text-red-400":"text-green-400",children:N.status==="failed"?"Failed":"Completed"}),N.filament_color&&a.jsx("div",{className:"flex gap-0.5",children:N.filament_color.split(",").map((T,F)=>a.jsx("div",{className:"w-3 h-3 rounded-full border border-black/20",style:{backgroundColor:T}},F))})]})]})]},N.id)})}):a.jsx("p",{className:"text-sm text-bambu-gray",children:"No prints on this day"})]}):a.jsx("div",{className:"text-center py-8",children:a.jsx("p",{className:"text-sm text-bambu-gray",children:"Select a day to see prints"})})})]})}function sie({archiveId:t,archiveName:e,onClose:n}){const r=me.getArchiveQRCodeUrl(t,300);w.useEffect(()=>{const s=o=>{o.key==="Escape"&&n()};return window.addEventListener("keydown",s),()=>window.removeEventListener("keydown",s)},[n]);const i=()=>{const s=document.createElement("a");s.href=r,s.download=`${e}_qrcode.png`,s.click()};return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:n,children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary w-full max-w-sm",onClick:s=>s.stopPropagation(),children:[a.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[a.jsx("h2",{className:"text-lg font-semibold text-white",children:"QR Code"}),a.jsx("button",{onClick:n,className:"text-bambu-gray hover:text-white transition-colors",children:a.jsx(Bt,{className:"w-5 h-5"})})]}),a.jsxs("div",{className:"p-6 flex flex-col items-center",children:[a.jsx("p",{className:"text-sm text-bambu-gray mb-4 text-center truncate max-w-full",children:e}),a.jsx("div",{className:"bg-white p-4 rounded-lg mb-4",children:a.jsx("img",{src:r,alt:"QR Code",className:"w-64 h-64"})}),a.jsx("p",{className:"text-xs text-bambu-gray mb-4 text-center",children:"Scan to open this archive"}),a.jsxs(De,{onClick:i,className:"w-full",children:[a.jsx(ga,{className:"w-4 h-4"}),"Download QR Code"]})]})]})})}function oie({archiveId:t,archiveName:e,photos:n,onClose:r,onDelete:i}){const[s,o]=w.useState(0),[l,c]=w.useState(!1);if(w.useEffect(()=>{const f=y=>{y.key==="Escape"&&r(),y.key==="ArrowLeft"&&o(v=>Math.max(0,v-1)),y.key==="ArrowRight"&&o(v=>Math.min(n.length-1,v+1))};return window.addEventListener("keydown",f),()=>window.removeEventListener("keydown",f)},[r,n.length]),w.useEffect(()=>{s>=n.length&&o(Math.max(0,n.length-1))},[n.length,s]),n.length===0)return r(),null;const d=n[s],u=me.getArchivePhotoUrl(t,d),m=()=>{const f=document.createElement("a");f.href=u,f.download=`${e}_photo_${s+1}.jpg`,f.click()},p=()=>{i&&c(!0)};return a.jsxs("div",{className:"fixed inset-0 bg-black/90 flex items-center justify-center z-50",onClick:r,children:[a.jsxs("div",{className:"relative w-full h-full flex flex-col",onClick:f=>f.stopPropagation(),children:[a.jsxs("div",{className:"flex items-center justify-between px-6 py-4 bg-black/50",children:[a.jsxs("div",{children:[a.jsx("h2",{className:"text-lg font-semibold text-white",children:e}),a.jsxs("p",{className:"text-sm text-bambu-gray",children:["Photo ",s+1," of ",n.length]})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs(De,{variant:"secondary",size:"sm",onClick:m,children:[a.jsx(ga,{className:"w-4 h-4"}),"Download"]}),i&&a.jsx(De,{variant:"secondary",size:"sm",onClick:p,className:"text-red-400 hover:text-red-300",children:a.jsx(en,{className:"w-4 h-4"})}),a.jsx("button",{onClick:r,className:"p-2 text-bambu-gray hover:text-white transition-colors",children:a.jsx(Bt,{className:"w-6 h-6"})})]})]}),a.jsxs("div",{className:"flex-1 min-h-0 flex items-center justify-center p-4 relative overflow-hidden",children:[s>0&&a.jsx("button",{onClick:()=>o(f=>f-1),className:"absolute left-4 z-10 p-3 bg-black/50 hover:bg-black/70 rounded-full transition-colors",children:a.jsx(xl,{className:"w-8 h-8 text-white"})}),a.jsx("img",{src:u,alt:`Photo ${s+1}`,className:"max-w-full max-h-full object-contain rounded-lg",style:{maxHeight:"calc(100vh - 200px)"}}),so(f=>f+1),className:"absolute right-4 z-10 p-3 bg-black/50 hover:bg-black/70 rounded-full transition-colors",children:a.jsx(ti,{className:"w-8 h-8 text-white"})})]}),n.length>1&&a.jsx("div",{className:"flex justify-center gap-2 p-4 bg-black/50",children:n.map((f,y)=>a.jsx("button",{onClick:()=>o(y),className:`w-16 h-16 rounded-lg overflow-hidden border-2 transition-colors ${y===s?"border-bambu-green":"border-transparent hover:border-bambu-gray"}`,children:a.jsx("img",{src:me.getArchivePhotoUrl(t,f),alt:`Thumbnail ${y+1}`,className:"w-full h-full object-cover"})},f))})]}),l&&a.jsx(yn,{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:lie,setPrototypeOf:pK,isFrozen:eGe,getPrototypeOf:tGe,getOwnPropertyDescriptor:nGe}=Object;let{freeze:fo,seal:gc,create:y0}=Object,{apply:SL,construct:_L}=typeof Reflect<"u"&&Reflect;fo||(fo=function(e){return e});gc||(gc=function(e){return e});SL||(SL=function(e,n){for(var r=arguments.length,i=new Array(r>2?r-2:0),s=2;s1?n-1:0),i=1;i1?n-1:0),i=1;i2&&arguments[2]!==void 0?arguments[2]:nN;pK&&pK(t,null);let r=e.length;for(;r--;){let i=e[r];if(typeof i=="string"){const s=n(i);s!==i&&(eGe(e)||(e[r]=s),i=s)}t[i]=!0}return t}function lGe(t){for(let e=0;e/gm),hGe=gc(/\$\{[\w\W]*/gm),pGe=gc(/^data-[\-\w.\u00B7-\uFFFF]+$/),fGe=gc(/^aria-[\-\w]+$/),cie=gc(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),gGe=gc(/^(?:\w+script|data):/i),bGe=gc(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),die=gc(/^html$/i),xGe=gc(/^[a-z][.\w]*(-[.\w]+)+$/i);var vK=Object.freeze({__proto__:null,ARIA_ATTR:fGe,ATTR_WHITESPACE:bGe,CUSTOM_ELEMENT:xGe,DATA_ATTR:pGe,DOCTYPE_NAME:die,ERB_EXPR:mGe,IS_ALLOWED_URI:cie,IS_SCRIPT_OR_DATA:gGe,MUSTACHE_EXPR:uGe,TMPLIT_EXPR:hGe});const i0={element:1,text:3,progressingInstruction:7,comment:8,document:9},yGe=function(){return typeof window>"u"?null:window},vGe=function(e,n){if(typeof e!="object"||typeof e.createPolicy!="function")return null;let r=null;const i="data-tt-policy-suffix";n&&n.hasAttribute(i)&&(r=n.getAttribute(i));const s="dompurify"+(r?"#"+r:"");try{return e.createPolicy(s,{createHTML(o){return o},createScriptURL(o){return o}})}catch{return console.warn("TrustedTypes policy "+s+" could not be created."),null}},wK=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function uie(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:yGe();const e=nt=>uie(nt);if(e.version="3.4.0",e.removed=[],!t||!t.document||t.document.nodeType!==i0.document||!t.Element)return e.isSupported=!1,e;let{document:n}=t;const r=n,i=r.currentScript,{DocumentFragment:s,HTMLTemplateElement:o,Node:l,Element:c,NodeFilter:d,NamedNodeMap:u=t.NamedNodeMap||t.MozNamedAttrMap,HTMLFormElement:m,DOMParser:p,trustedTypes:f}=t,y=c.prototype,v=a0(y,"cloneNode"),b=a0(y,"remove"),g=a0(y,"nextSibling"),_=a0(y,"childNodes"),C=a0(y,"parentNode");if(typeof o=="function"){const nt=n.createElement("template");nt.content&&nt.content.ownerDocument&&(n=nt.content.ownerDocument)}let P,N="";const{implementation:A,createNodeIterator:T,createDocumentFragment:F,getElementsByTagName:k}=n,{importNode:D}=r;let H=wK();e.isSupported=typeof lie=="function"&&typeof C=="function"&&A&&A.createHTMLDocument!==void 0;const{MUSTACHE_EXPR:z,ERB_EXPR:Q,TMPLIT_EXPR:L,DATA_ATTR:te,ARIA_ATTR:ie,IS_SCRIPT_OR_DATA:J,ATTR_WHITESPACE:oe,CUSTOM_ELEMENT:ge}=vK;let{IS_ALLOWED_URI:re}=vK,W=null;const ne=ur({},[...gK,...HD,...qD,...$D,...bK]);let pe=null;const xe=ur({},[...xK,...VD,...yK,...gk]);let Ne=Object.seal(y0(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}})),q=null,Y=null;const E=Object.seal(y0(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let j=!0,O=!0,K=!1,U=!0,ue=!1,I=!0,G=!1,X=!1,V=!1,ee=!1,se=!1,be=!1,fe=!0,le=!1;const B="user-content-";let R=!0,ae=!1,Se={},ve=null;const Ae=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 je=null;const he=ur({},["audio","video","img","source","image","track"]);let Ce=null;const Fe=ur({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),Me="http://www.w3.org/1998/Math/MathML",Oe="http://www.w3.org/2000/svg",Re="http://www.w3.org/1999/xhtml";let $e=Re,Xe=!1,tt=null;const we=ur({},[Me,Oe,Re],UD);let ze=ur({},["mi","mo","mn","ms","mtext"]),ce=ur({},["annotation-xml"]);const qe=ur({},["title","style","font","a","script"]);let Pe=null;const de=["application/xhtml+xml","text/html"],ye="text/html";let Be=null,Qe=null;const ht=n.createElement("form"),xt=function(Ie){return Ie instanceof RegExp||Ie instanceof Function},gt=function(){let Ie=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(Qe&&Qe===Ie)){if((!Ie||typeof Ie!="object")&&(Ie={}),Ie=vd(Ie),Pe=de.indexOf(Ie.PARSER_MEDIA_TYPE)===-1?ye:Ie.PARSER_MEDIA_TYPE,Be=Pe==="application/xhtml+xml"?UD:nN,W=Ic(Ie,"ALLOWED_TAGS")?ur({},Ie.ALLOWED_TAGS,Be):ne,pe=Ic(Ie,"ALLOWED_ATTR")?ur({},Ie.ALLOWED_ATTR,Be):xe,tt=Ic(Ie,"ALLOWED_NAMESPACES")?ur({},Ie.ALLOWED_NAMESPACES,UD):we,Ce=Ic(Ie,"ADD_URI_SAFE_ATTR")?ur(vd(Fe),Ie.ADD_URI_SAFE_ATTR,Be):Fe,je=Ic(Ie,"ADD_DATA_URI_TAGS")?ur(vd(he),Ie.ADD_DATA_URI_TAGS,Be):he,ve=Ic(Ie,"FORBID_CONTENTS")?ur({},Ie.FORBID_CONTENTS,Be):Ae,q=Ic(Ie,"FORBID_TAGS")?ur({},Ie.FORBID_TAGS,Be):vd({}),Y=Ic(Ie,"FORBID_ATTR")?ur({},Ie.FORBID_ATTR,Be):vd({}),Se=Ic(Ie,"USE_PROFILES")?Ie.USE_PROFILES:!1,j=Ie.ALLOW_ARIA_ATTR!==!1,O=Ie.ALLOW_DATA_ATTR!==!1,K=Ie.ALLOW_UNKNOWN_PROTOCOLS||!1,U=Ie.ALLOW_SELF_CLOSE_IN_ATTR!==!1,ue=Ie.SAFE_FOR_TEMPLATES||!1,I=Ie.SAFE_FOR_XML!==!1,G=Ie.WHOLE_DOCUMENT||!1,ee=Ie.RETURN_DOM||!1,se=Ie.RETURN_DOM_FRAGMENT||!1,be=Ie.RETURN_TRUSTED_TYPE||!1,V=Ie.FORCE_BODY||!1,fe=Ie.SANITIZE_DOM!==!1,le=Ie.SANITIZE_NAMED_PROPS||!1,R=Ie.KEEP_CONTENT!==!1,ae=Ie.IN_PLACE||!1,re=Ie.ALLOWED_URI_REGEXP||cie,$e=Ie.NAMESPACE||Re,ze=Ie.MATHML_TEXT_INTEGRATION_POINTS||ze,ce=Ie.HTML_INTEGRATION_POINTS||ce,Ne=Ie.CUSTOM_ELEMENT_HANDLING||y0(null),Ie.CUSTOM_ELEMENT_HANDLING&&xt(Ie.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(Ne.tagNameCheck=Ie.CUSTOM_ELEMENT_HANDLING.tagNameCheck),Ie.CUSTOM_ELEMENT_HANDLING&&xt(Ie.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(Ne.attributeNameCheck=Ie.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),Ie.CUSTOM_ELEMENT_HANDLING&&typeof Ie.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&(Ne.allowCustomizedBuiltInElements=Ie.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),ue&&(O=!1),se&&(ee=!0),Se&&(W=ur({},bK),pe=y0(null),Se.html===!0&&(ur(W,gK),ur(pe,xK)),Se.svg===!0&&(ur(W,HD),ur(pe,VD),ur(pe,gk)),Se.svgFilters===!0&&(ur(W,qD),ur(pe,VD),ur(pe,gk)),Se.mathMl===!0&&(ur(W,$D),ur(pe,yK),ur(pe,gk))),E.tagCheck=null,E.attributeCheck=null,Ie.ADD_TAGS&&(typeof Ie.ADD_TAGS=="function"?E.tagCheck=Ie.ADD_TAGS:(W===ne&&(W=vd(W)),ur(W,Ie.ADD_TAGS,Be))),Ie.ADD_ATTR&&(typeof Ie.ADD_ATTR=="function"?E.attributeCheck=Ie.ADD_ATTR:(pe===xe&&(pe=vd(pe)),ur(pe,Ie.ADD_ATTR,Be))),Ie.ADD_URI_SAFE_ATTR&&ur(Ce,Ie.ADD_URI_SAFE_ATTR,Be),Ie.FORBID_CONTENTS&&(ve===Ae&&(ve=vd(ve)),ur(ve,Ie.FORBID_CONTENTS,Be)),Ie.ADD_FORBID_CONTENTS&&(ve===Ae&&(ve=vd(ve)),ur(ve,Ie.ADD_FORBID_CONTENTS,Be)),R&&(W["#text"]=!0),G&&ur(W,["html","head","body"]),W.table&&(ur(W,["tbody"]),delete q.tbody),Ie.TRUSTED_TYPES_POLICY){if(typeof Ie.TRUSTED_TYPES_POLICY.createHTML!="function")throw r0('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof Ie.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw r0('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');P=Ie.TRUSTED_TYPES_POLICY,N=P.createHTML("")}else P===void 0&&(P=vGe(f,i)),P!==null&&typeof N=="string"&&(N=P.createHTML(""));fo&&fo(Ie),Qe=Ie}},Ut=ur({},[...HD,...qD,...cGe]),Wt=ur({},[...$D,...dGe]),Zt=function(Ie){let ot=C(Ie);(!ot||!ot.tagName)&&(ot={namespaceURI:$e,tagName:"template"});const Te=nN(Ie.tagName),Ge=nN(ot.tagName);return tt[Ie.namespaceURI]?Ie.namespaceURI===Oe?ot.namespaceURI===Re?Te==="svg":ot.namespaceURI===Me?Te==="svg"&&(Ge==="annotation-xml"||ze[Ge]):!!Ut[Te]:Ie.namespaceURI===Me?ot.namespaceURI===Re?Te==="math":ot.namespaceURI===Oe?Te==="math"&&ce[Ge]:!!Wt[Te]:Ie.namespaceURI===Re?ot.namespaceURI===Oe&&!ce[Ge]||ot.namespaceURI===Me&&!ze[Ge]?!1:!Wt[Te]&&(qe[Te]||!Ut[Te]):!!(Pe==="application/xhtml+xml"&&tt[Ie.namespaceURI]):!1},Kt=function(Ie){n0(e.removed,{element:Ie});try{C(Ie).removeChild(Ie)}catch{b(Ie)}},Xt=function(Ie,ot){try{n0(e.removed,{attribute:ot.getAttributeNode(Ie),from:ot})}catch{n0(e.removed,{attribute:null,from:ot})}if(ot.removeAttribute(Ie),Ie==="is")if(ee||se)try{Kt(ot)}catch{}else try{ot.setAttribute(Ie,"")}catch{}},ln=function(Ie){let ot=null,Te=null;if(V)Ie=""+Ie;else{const Je=BD(Ie,/^[\r\n\t ]+/);Te=Je&&Je[0]}Pe==="application/xhtml+xml"&&$e===Re&&(Ie=''+Ie+"");const Ge=P?P.createHTML(Ie):Ie;if($e===Re)try{ot=new p().parseFromString(Ge,Pe)}catch{}if(!ot||!ot.documentElement){ot=A.createDocument($e,"template",null);try{ot.documentElement.innerHTML=Xe?N:Ge}catch{}}const Ze=ot.body||ot.documentElement;return Ie&&Te&&Ze.insertBefore(n.createTextNode(Te),Ze.childNodes[0]||null),$e===Re?k.call(ot,G?"html":"body")[0]:G?ot.documentElement:Ze},vn=function(Ie){return T.call(Ie.ownerDocument||Ie,Ie,d.SHOW_ELEMENT|d.SHOW_COMMENT|d.SHOW_TEXT|d.SHOW_PROCESSING_INSTRUCTION|d.SHOW_CDATA_SECTION,null)},Ke=function(Ie){return Ie instanceof m&&(typeof Ie.nodeName!="string"||typeof Ie.textContent!="string"||typeof Ie.removeChild!="function"||!(Ie.attributes instanceof u)||typeof Ie.removeAttribute!="function"||typeof Ie.setAttribute!="function"||typeof Ie.namespaceURI!="string"||typeof Ie.insertBefore!="function"||typeof Ie.hasChildNodes!="function")},at=function(Ie){return typeof l=="function"&&Ie instanceof l};function Lt(nt,Ie,ot){t0(nt,Te=>{Te.call(e,Ie,ot,Qe)})}const Et=function(Ie){let ot=null;if(Lt(H.beforeSanitizeElements,Ie,null),Ke(Ie))return Kt(Ie),!0;const Te=Be(Ie.nodeName);if(Lt(H.uponSanitizeElement,Ie,{tagName:Te,allowedTags:W}),I&&Ie.hasChildNodes()&&!at(Ie.firstElementChild)&&eo(/<[/\w!]/g,Ie.innerHTML)&&eo(/<[/\w!]/g,Ie.textContent)||I&&Ie.namespaceURI===Re&&Te==="style"&&at(Ie.firstElementChild)||Ie.nodeType===i0.progressingInstruction||I&&Ie.nodeType===i0.comment&&eo(/<[/\w]/g,Ie.data))return Kt(Ie),!0;if(q[Te]||!(E.tagCheck instanceof Function&&E.tagCheck(Te))&&!W[Te]){if(!q[Te]&&Le(Te)&&(Ne.tagNameCheck instanceof RegExp&&eo(Ne.tagNameCheck,Te)||Ne.tagNameCheck instanceof Function&&Ne.tagNameCheck(Te)))return!1;if(R&&!ve[Te]){const Ge=C(Ie)||Ie.parentNode,Ze=_(Ie)||Ie.childNodes;if(Ze&&Ge){const Je=Ze.length;for(let We=Je-1;We>=0;--We){const Ue=v(Ze[We],!0);Ue.__removalCount=(Ie.__removalCount||0)+1,Ge.insertBefore(Ue,g(Ie))}}}return Kt(Ie),!0}return Ie instanceof c&&!Zt(Ie)||(Te==="noscript"||Te==="noembed"||Te==="noframes")&&eo(/<\/no(script|embed|frames)/i,Ie.innerHTML)?(Kt(Ie),!0):(ue&&Ie.nodeType===i0.text&&(ot=Ie.textContent,t0([z,Q,L],Ge=>{ot=sx(ot,Ge," ")}),Ie.textContent!==ot&&(n0(e.removed,{element:Ie.cloneNode()}),Ie.textContent=ot)),Lt(H.afterSanitizeElements,Ie,null),!1)},At=function(Ie,ot,Te){if(Y[ot]||fe&&(ot==="id"||ot==="name")&&(Te in n||Te in ht))return!1;if(!(O&&!Y[ot]&&eo(te,ot))){if(!(j&&eo(ie,ot))){if(!(E.attributeCheck instanceof Function&&E.attributeCheck(ot,Ie))){if(!pe[ot]||Y[ot]){if(!(Le(Ie)&&(Ne.tagNameCheck instanceof RegExp&&eo(Ne.tagNameCheck,Ie)||Ne.tagNameCheck instanceof Function&&Ne.tagNameCheck(Ie))&&(Ne.attributeNameCheck instanceof RegExp&&eo(Ne.attributeNameCheck,ot)||Ne.attributeNameCheck instanceof Function&&Ne.attributeNameCheck(ot,Ie))||ot==="is"&&Ne.allowCustomizedBuiltInElements&&(Ne.tagNameCheck instanceof RegExp&&eo(Ne.tagNameCheck,Te)||Ne.tagNameCheck instanceof Function&&Ne.tagNameCheck(Te))))return!1}else if(!Ce[ot]){if(!eo(re,sx(Te,oe,""))){if(!((ot==="src"||ot==="xlink:href"||ot==="href")&&Ie!=="script"&&iGe(Te,"data:")===0&&je[Ie])){if(!(K&&!eo(J,sx(Te,oe,"")))){if(Te)return!1}}}}}}}return!0},Le=function(Ie){return Ie!=="annotation-xml"&&BD(Ie,ge)},mt=function(Ie){Lt(H.beforeSanitizeAttributes,Ie,null);const{attributes:ot}=Ie;if(!ot||Ke(Ie))return;const Te={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:pe,forceKeepAttr:void 0};let Ge=ot.length;for(;Ge--;){const Ze=ot[Ge],{name:Je,namespaceURI:We,value:Ue}=Ze,et=Be(Je),jt=Ue;let yt=Je==="value"?jt:sGe(jt);if(Te.attrName=et,Te.attrValue=yt,Te.keepAttr=!0,Te.forceKeepAttr=void 0,Lt(H.uponSanitizeAttribute,Ie,Te),yt=Te.attrValue,le&&(et==="id"||et==="name")&&(Xt(Je,Ie),yt=B+yt),I&&eo(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,yt)){Xt(Je,Ie);continue}if(et==="attributename"&&BD(yt,"href")){Xt(Je,Ie);continue}if(Te.forceKeepAttr)continue;if(!Te.keepAttr){Xt(Je,Ie);continue}if(!U&&eo(/\/>/i,yt)){Xt(Je,Ie);continue}ue&&t0([z,Q,L],St=>{yt=sx(yt,St," ")});const Ve=Be(Ie.nodeName);if(!At(Ve,et,yt)){Xt(Je,Ie);continue}if(P&&typeof f=="object"&&typeof f.getAttributeType=="function"&&!We)switch(f.getAttributeType(Ve,et)){case"TrustedHTML":{yt=P.createHTML(yt);break}case"TrustedScriptURL":{yt=P.createScriptURL(yt);break}}if(yt!==jt)try{We?Ie.setAttributeNS(We,Je,yt):Ie.setAttribute(Je,yt),Ke(Ie)?Kt(Ie):fK(e.removed)}catch{Xt(Je,Ie)}}Lt(H.afterSanitizeAttributes,Ie,null)},pt=function(Ie){let ot=null;const Te=vn(Ie);for(Lt(H.beforeSanitizeShadowDOM,Ie,null);ot=Te.nextNode();)Lt(H.uponSanitizeShadowNode,ot,null),Et(ot),mt(ot),ot.content instanceof s&&pt(ot.content);Lt(H.afterSanitizeShadowDOM,Ie,null)};return e.sanitize=function(nt){let Ie=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},ot=null,Te=null,Ge=null,Ze=null;if(Xe=!nt,Xe&&(nt=""),typeof nt!="string"&&!at(nt))if(typeof nt.toString=="function"){if(nt=nt.toString(),typeof nt!="string")throw r0("dirty is not a string, aborting")}else throw r0("toString is not a function");if(!e.isSupported)return nt;if(X||gt(Ie),e.removed=[],typeof nt=="string"&&(ae=!1),ae){if(nt.nodeName){const Ue=Be(nt.nodeName);if(!W[Ue]||q[Ue])throw r0("root node is forbidden and cannot be sanitized in-place")}}else if(nt instanceof l)ot=ln(""),Te=ot.ownerDocument.importNode(nt,!0),Te.nodeType===i0.element&&Te.nodeName==="BODY"||Te.nodeName==="HTML"?ot=Te:ot.appendChild(Te);else{if(!ee&&!ue&&!G&&nt.indexOf("<")===-1)return P&&be?P.createHTML(nt):nt;if(ot=ln(nt),!ot)return ee?null:be?N:""}ot&&V&&Kt(ot.firstChild);const Je=vn(ae?nt:ot);for(;Ge=Je.nextNode();)Et(Ge),mt(Ge),Ge.content instanceof s&&pt(Ge.content);if(ae)return nt;if(ee){if(ue){ot.normalize();let Ue=ot.innerHTML;t0([z,Q,L],et=>{Ue=sx(Ue,et," ")}),ot.innerHTML=Ue}if(se)for(Ze=F.call(ot.ownerDocument);ot.firstChild;)Ze.appendChild(ot.firstChild);else Ze=ot;return(pe.shadowroot||pe.shadowrootmode)&&(Ze=D.call(r,Ze,!0)),Ze}let We=G?ot.outerHTML:ot.innerHTML;return G&&W["!doctype"]&&ot.ownerDocument&&ot.ownerDocument.doctype&&ot.ownerDocument.doctype.name&&eo(die,ot.ownerDocument.doctype.name)&&(We=" + `,title:k("printers:control")?N(Ht?"printers.resume":"printers.pause"):N("printers.permission.noControl"),children:[Ht?a.jsx(ns,{className:"w-3 h-3"}):a.jsx(rS,{className:"w-3 h-3"}),N(Ht?"printers.resume":"printers.pause")]})]})]})]})})(),(ma?.length>0||Ue.vt_tray.length>0)&&r==="expanded"&&(()=>{const lt=ma.filter(ct=>ct.tray.length>1),Ht=ma.filter(ct=>ct.tray.length===1),Jt=t.nozzle_count===2||Ue?.temperatures?.nozzle_2!==void 0;return a.jsxs("div",{className:"mt-3",children:[a.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[a.jsx("span",{className:"text-[10px] uppercase tracking-wider text-bambu-gray font-medium",children:N("printers.filaments")}),a.jsx("div",{className:"flex-1 h-px bg-bambu-dark-tertiary/30"})]}),a.jsxs("div",{className:"space-y-3",children:[lt.length>0&&a.jsx("div",{className:"grid grid-cols-2 gap-3",children:lt.map(ct=>{const Un=Ha[String(ct.id)],Tr=ct.id>=128?ct.id-128:ct.id,ar=Un!==void 0?Un:Tr,Lr=ar===1,Da=ar===0;return a.jsxs("div",{className:"p-2.5 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary/30",children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsxs("div",{className:"flex items-center gap-1.5",children:[a.jsx(uK,{ams:ct,printerId:t.id,label:Ul(ct.id,ct.tray.length),amsLabels:Nn,canEdit:k("printers:update"),onSaved:bn,children:a.jsx("span",{className:"text-[10px] text-white font-medium cursor-default select-none",children:Nn?.[ct.id]||Ul(ct.id,ct.tray.length)})}),Jt&&(Lr||Da)&&a.jsx(iK,{side:Lr?"L":"R"})]}),(ct.humidity!=null||ct.temp!=null)&&a.jsxs("div",{className:"flex items-center gap-1.5 max-[550px]:flex-col max-[550px]:items-start",children:[ct.humidity!=null&&a.jsx(oK,{humidity:ct.humidity,goodThreshold:s?.humidityGood,fairThreshold:s?.humidityFair,onClick:()=>Zt({amsId:ct.id,amsLabel:Ul(ct.id,ct.tray.length),mode:"humidity"}),compact:!0}),ct.temp!=null&&a.jsx(lK,{temp:ct.temp,goodThreshold:s?.tempGood,fairThreshold:s?.tempFair,onClick:()=>Zt({amsId:ct.id,amsLabel:Ul(ct.id,ct.tray.length),mode:"temperature"}),compact:!0}),Ue.supports_drying&&(ct.module_type==="n3f"||ct.module_type==="n3s")&&k("printers:control")&&a.jsx("button",{disabled:!!(ct.dry_sf_reason?.length&&ct.dry_time===0),onClick:rn=>{if(ct.dry_time>0)Ts.mutate(ct.id);else if(Me===ct.id)Oe(null);else{const Na=(ct.tray.find(Cl=>Cl.tray_type)?.tray_type||"PLA").split(" ")[0].toUpperCase(),ai=b[Na]||b.PLA,mi=ct.module_type;tt(Na),ze(ai[mi]||ai.n3f),qe(mi==="n3s"?ai.n3s_hours:ai.n3f_hours),de(!1),$e(ct.module_type),Oe(ct.id);const Ys=rn.currentTarget.getBoundingClientRect();Be({top:Ys.bottom+4,left:Math.max(8,Ys.right-240)})}},className:`flex items-center gap-0.5 px-1 py-0.5 rounded text-[9px] transition-colors ${ct.dry_time>0?"bg-amber-500/20 text-amber-400":ct.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:ct.dry_time>0?N("printers.drying.stop"):ct.dry_sf_reason?.length?N("printers.drying.powerRequired"):N("printers.drying.start"),children:a.jsx(Hu,{className:"w-3 h-3"})})]})]}),ct.dry_time>0&&a.jsxs("div",{className:"flex items-center gap-2 px-2 py-1 mb-1 bg-amber-500/10 border border-amber-500/20 rounded text-[9px]",children:[a.jsx(Hu,{className:"w-3 h-3 text-amber-400 shrink-0"}),a.jsx("span",{className:"text-amber-400 font-medium",children:N("printers.drying.active")}),a.jsx("span",{className:"text-amber-300/70",children:N("printers.drying.timeRemaining",{time:ct.dry_time>=60?`${Math.floor(ct.dry_time/60)}h ${ct.dry_time%60}m`:`${ct.dry_time}m`})}),a.jsx("button",{onClick:()=>Ts.mutate(ct.id),disabled:Ts.isPending,className:"ml-auto text-amber-400 hover:text-amber-300 transition-colors disabled:opacity-50",title:N("printers.drying.stop"),children:a.jsx(Bt,{className:"w-3 h-3"})})]}),a.jsx("div",{className:"grid grid-cols-4 gap-1.5",children:[0,1,2,3].map(rn=>{const En=ct.tray[rn]||ct.tray.find(zn=>zn.id===rn),Na=En?.tray_type&&En.remain>=0,ai=!En?.tray_type,mi=ct.id*4+rn,Ys=Br===mi,Cl=En?.tray_info_idx?St?.[En.tray_info_idx]:null,ha=Pt?.[mi],Hi=(En?.tray_uuid||En?.tag_uid||Vu(t.serial_number,ct.id,rn))?.toUpperCase(),Pl=Hi?l?.[Hi]:void 0,qi=tN(Pl),Qs=u?.(t.id,ct.id,rn),Pc=(()=>{const zn=Qs?.spool;return zn&&zn.label_weight>0&&zn.weight_used!=null?Math.round(Math.max(0,zn.label_weight-zn.weight_used)/zn.label_weight*100):null})(),pa=Pc===0&&Na&&En.remain>0?null:Pc,ko=qi??pa??(Na?En.remain:null),Gy=qi!==null?"spoolman":pa!==null?"inventory":Na?"ams":void 0,ya=En?.tray_type?{vendor:ID(En)?"Bambu Lab":"Generic",profile:ha?.preset_name||Cl?.name||Qs?.spool?.slicer_filament_name||En.tray_sub_brands||En.tray_type,colorName:rc(En.tray_color||""),colorHex:En.tray_color||null,kFactor:LD(En.k),fillLevel:ko,trayUuid:En.tray_uuid||null,tagUid:En.tag_uid||null,fillSource:Gy}:null,ou=Yo?.amsId===ct.id&&Yo?.slotId===rn,$p=a.jsxs("div",{className:`bg-bambu-dark-tertiary rounded p-1 text-center ${ai?"opacity-50":""} ${Ys?"ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark":""}`,children:[a.jsx(RD,{trayColor:En?.tray_color,trayType:En?.tray_type,isEmpty:ai,slotNumber:rn+1}),a.jsx("div",{className:"text-[9px] text-white font-bold truncate",children:En?.tray_type||"—"}),a.jsx("div",{className:"mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden",children:ko!==null&&ko>=0&&!ai&&En&&a.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${ko}%`,backgroundColor:Ox(ko)}})})]});return a.jsxs("div",{className:"relative group",children:[ou&&a.jsx("div",{className:"absolute inset-0 bg-bambu-dark-tertiary/80 rounded flex items-center justify-center z-20",children:a.jsx(lr,{className:"w-4 h-4 text-bambu-green animate-spin"})}),Ue?.state!=="RUNNING"&&a.jsx("button",{onClick:zn=>{zn.stopPropagation(),_n(Sn?.amsId===ct.id&&Sn?.slotId===rn?null:{amsId:ct.id,slotId:rn})},className:"absolute -top-1 -right-1 w-4 h-4 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity z-10 hover:bg-bambu-dark-tertiary",title:N("printers.slotOptions"),children:a.jsx(Jh,{className:"w-2.5 h-2.5 text-bambu-gray"})}),Ue?.state!=="RUNNING"&&Sn?.amsId===ct.id&&Sn?.slotId===rn&&a.jsx("div",{className:"absolute top-full left-0 mt-1 z-50 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl py-1 min-w-[120px]",children:a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-xs flex items-center gap-2 ${k("printers:ams_rfid")?"text-white hover:bg-bambu-dark-tertiary":"text-bambu-gray/50 cursor-not-allowed"}`,onClick:zn=>{zn.stopPropagation(),k("printers:ams_rfid")&&(xn.mutate({amsId:ct.id,slotId:rn}),_n(null))},disabled:ou||!k("printers:ams_rfid"),title:k("printers:ams_rfid")?void 0:N("printers.permission.noAmsRfid"),children:[a.jsx(lr,{className:`w-3 h-3 ${ou?"animate-spin":""}`}),N("printers.rfid.reread")]})}),ya?a.jsx(jD,{data:ya,spoolman:{enabled:o,linkedSpoolId:Hi?l?.[Hi]?.id:void 0,spoolmanUrl:c,syncMode:d,onLinkSpool:o?()=>{const zn=(ya.trayUuid||ya.tagUid||Vu(t.serial_number,ct.id,rn)).toUpperCase();Xt({tagUid:ya.tagUid||zn,trayUuid:ya.trayUuid||"",printerId:t.id,amsId:ct.id,trayId:rn})}:void 0,onUnlinkSpool:Pl?.id?()=>Ps.mutate(Pl.id):void 0},inventory:o?void 0:(()=>{const zn=u?.(t.id,ct.id,rn);return{assignedSpool:zn?.spool?{id:zn.spool.id,material:zn.spool.material,brand:zn.spool.brand,color_name:zn.spool.color_name,remainingWeightGrams:Math.max(0,Math.round(zn.spool.label_weight-zn.spool.weight_used))}:null,onAssignSpool:ya.vendor!=="Bambu Lab"?()=>vn({printerId:t.id,amsId:ct.id,trayId:rn,trayInfo:{type:En?.tray_type||ya.profile,material:En?.tray_type??void 0,profile:ya.profile,color:ya.colorHex||"",location:`${Ul(ct.id,ct.tray.length)} Slot ${rn+1}`}}):void 0,onUnassignSpool:zn&&ya.vendor!=="Bambu Lab"?()=>m?.(t.id,ct.id,rn):void 0}})(),configureSlot:{enabled:k("printers:control"),onConfigure:()=>at({amsId:ct.id,trayId:rn,trayCount:ct.tray.length,trayType:En?.tray_type||void 0,trayColor:En?.tray_color||void 0,traySubBrands:En?.tray_sub_brands||void 0,trayInfoIdx:En?.tray_info_idx||void 0,extruderId:Un,caliIdx:En?.cali_idx,savedPresetId:ha?.preset_id})},children:$p}):a.jsx(MD,{configureSlot:{enabled:k("printers:control"),onConfigure:()=>at({amsId:ct.id,trayId:rn,trayCount:ct.tray.length,extruderId:Un})},inventory:o?void 0:{onAssignSpool:()=>vn({printerId:t.id,amsId:ct.id,trayId:rn,trayInfo:{type:"",color:"",location:`${Ul(ct.id,ct.tray.length)} Slot ${rn+1}`}})},children:$p})]},rn)})})]},ct.id)})}),(Ht.length>0||Ue.vt_tray.length>0)&&a.jsxs("div",{className:"grid grid-cols-4 gap-3",children:[Ht.map(ct=>{const Un=Ha[String(ct.id)],Tr=ct.id>=128?ct.id-128:ct.id,ar=Un!==void 0?Un:Tr,Lr=ar===1,Da=ar===0,rn=ct.tray[0],En=rn?.tray_type&&rn.remain>=0,Na=!rn?.tray_type,ai=Ag(ct.id,rn?.id??0,!1),mi=Br===ai,Ys=rn?.tray_info_idx?St?.[rn.tray_info_idx]:null,Cl=Pt?.[ai],ha=rn?.id??0,Hi=(rn?.tray_uuid||rn?.tag_uid||Vu(t.serial_number,ct.id,ha))?.toUpperCase(),Pl=Hi?l?.[Hi]:void 0,qi=tN(Pl),Qs=u?.(t.id,ct.id,ha),Pc=(()=>{const zn=Qs?.spool;return zn&&zn.label_weight>0&&zn.weight_used!=null?Math.round(Math.max(0,zn.label_weight-zn.weight_used)/zn.label_weight*100):null})(),pa=Pc===0&&En&&rn.remain>0?null:Pc,ko=qi??pa??(En?rn.remain:null),Gy=qi!==null?"spoolman":pa!==null?"inventory":En?"ams":void 0,ya=rn?.tray_type?{vendor:ID(rn)?"Bambu Lab":"Generic",profile:Cl?.preset_name||Ys?.name||Qs?.spool?.slicer_filament_name||rn.tray_sub_brands||rn.tray_type,colorName:rc(rn.tray_color||""),colorHex:rn.tray_color||null,kFactor:LD(rn.k),fillLevel:ko,trayUuid:rn.tray_uuid||null,tagUid:rn.tag_uid||null,fillSource:Gy}:null,ou=Yo?.amsId===ct.id&&Yo?.slotId===ha,$p=a.jsxs("div",{className:`bg-bambu-dark-tertiary rounded p-1 text-center ${Na?"opacity-50":""} ${mi?"ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark":""}`,children:[a.jsx(RD,{trayColor:rn?.tray_color,trayType:rn?.tray_type,isEmpty:Na,slotNumber:1}),a.jsx("div",{className:"text-[9px] text-white font-bold truncate",children:rn?.tray_type||"—"}),a.jsx("div",{className:"mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden",children:ko!==null&&ko>=0&&!Na&&a.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${ko}%`,backgroundColor:Ox(ko)}})})]});return a.jsxs("div",{className:"p-2.5 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary/30",children:[a.jsxs("div",{className:"flex items-center gap-1 mb-2",children:[a.jsx(uK,{ams:ct,printerId:t.id,label:Ul(ct.id,ct.tray.length),amsLabels:Nn,canEdit:k("printers:update"),onSaved:bn,children:a.jsx("span",{className:"text-[10px] text-white font-medium cursor-default select-none",children:Nn?.[ct.id]||Ul(ct.id,ct.tray.length)})}),Jt&&(Lr||Da)&&a.jsx(iK,{side:Lr?"L":"R"}),Ue.supports_drying&&(ct.module_type==="n3f"||ct.module_type==="n3s")&&k("printers:control")&&a.jsx("div",{className:"relative ml-auto",children:a.jsx("button",{onClick:zn=>{if(ct.dry_time>0)Ts.mutate(ct.id);else if(Me===ct.id)Oe(null);else{const Um=(ct.tray.find($S=>$S.tray_type)?.tray_type||"PLA").split(" ")[0].toUpperCase(),Vp=b[Um]||b.PLA,Wy=ct.module_type;tt(Um),ze(Vp[Wy]||Vp.n3f),qe(Wy==="n3s"?Vp.n3s_hours:Vp.n3f_hours),de(!1),$e(ct.module_type),Oe(ct.id);const Ky=zn.currentTarget.getBoundingClientRect();Be({top:Ky.bottom+4,left:Math.max(8,Ky.right-240)})}},className:`flex items-center gap-0.5 px-1 py-0.5 rounded text-[9px] transition-colors ${ct.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:ct.dry_time>0?N("printers.drying.stop"):N("printers.drying.start"),children:a.jsx(Hu,{className:"w-3 h-3"})})})]}),ct.dry_time>0&&a.jsxs("div",{className:"flex items-center gap-1.5 px-2 py-1 mb-1 bg-amber-500/10 border border-amber-500/20 rounded text-[9px] whitespace-nowrap overflow-hidden",children:[a.jsx(Hu,{className:"w-3 h-3 text-amber-400 shrink-0"}),a.jsx("span",{className:"text-amber-300/70 text-[8px] truncate",children:ct.dry_time>=60?`${Math.floor(ct.dry_time/60)}h ${ct.dry_time%60}m`:`${ct.dry_time}m`}),a.jsx("button",{onClick:()=>Ts.mutate(ct.id),disabled:Ts.isPending,className:"ml-auto text-amber-400 hover:text-amber-300 transition-colors disabled:opacity-50 shrink-0",title:N("printers.drying.stop"),children:a.jsx(Bt,{className:"w-3 h-3"})})]}),a.jsxs("div",{className:"flex gap-1.5 max-[550px]:flex-col max-[550px]:items-start",children:[a.jsxs("div",{className:"relative group flex-1 max-[550px]:w-full",children:[ou&&a.jsx("div",{className:"absolute inset-0 bg-bambu-dark-tertiary/80 rounded flex items-center justify-center z-20",children:a.jsx(lr,{className:"w-4 h-4 text-bambu-green animate-spin"})}),Ue?.state!=="RUNNING"&&a.jsx("button",{onClick:zn=>{zn.stopPropagation(),_n(Sn?.amsId===ct.id&&Sn?.slotId===ha?null:{amsId:ct.id,slotId:ha})},className:"absolute -top-1 -right-1 w-4 h-4 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity z-10 hover:bg-bambu-dark-tertiary",title:N("printers.slotOptions"),children:a.jsx(Jh,{className:"w-2.5 h-2.5 text-bambu-gray"})}),Ue?.state!=="RUNNING"&&Sn?.amsId===ct.id&&Sn?.slotId===ha&&a.jsx("div",{className:"absolute top-full left-0 mt-1 z-50 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl py-1 min-w-[120px]",children:a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-xs flex items-center gap-2 ${k("printers:ams_rfid")?"text-white hover:bg-bambu-dark-tertiary":"text-bambu-gray/50 cursor-not-allowed"}`,onClick:zn=>{zn.stopPropagation(),k("printers:ams_rfid")&&(xn.mutate({amsId:ct.id,slotId:ha}),_n(null))},disabled:ou||!k("printers:ams_rfid"),title:k("printers:ams_rfid")?void 0:N("printers.permission.noAmsRfid"),children:[a.jsx(lr,{className:`w-3 h-3 ${ou?"animate-spin":""}`}),N("printers.rfid.reread")]})}),ya?a.jsx(jD,{data:ya,spoolman:{enabled:o,linkedSpoolId:Hi?l?.[Hi]?.id:void 0,spoolmanUrl:c,syncMode:d,onLinkSpool:o?()=>{const zn=(ya.trayUuid||ya.tagUid||Vu(t.serial_number,ct.id,ha)).toUpperCase();Xt({tagUid:ya.tagUid||zn,trayUuid:ya.trayUuid||"",printerId:t.id,amsId:ct.id,trayId:ha})}:void 0,onUnlinkSpool:Pl?.id?()=>Ps.mutate(Pl.id):void 0},inventory:o?void 0:(()=>{const zn=u?.(t.id,ct.id,ha);return{assignedSpool:zn?.spool?{id:zn.spool.id,material:zn.spool.material,brand:zn.spool.brand,color_name:zn.spool.color_name,remainingWeightGrams:Math.max(0,Math.round(zn.spool.label_weight-zn.spool.weight_used))}:null,onAssignSpool:ya.vendor!=="Bambu Lab"?()=>vn({printerId:t.id,amsId:ct.id,trayId:ha,trayInfo:{type:rn?.tray_type||ya.profile,material:rn?.tray_type??void 0,profile:ya.profile,color:ya.colorHex||"",location:Ul(ct.id,ct.tray.length)}}):void 0,onUnassignSpool:zn&&ya.vendor!=="Bambu Lab"?()=>m?.(t.id,ct.id,ha):void 0}})(),configureSlot:{enabled:k("printers:control"),onConfigure:()=>at({amsId:ct.id,trayId:ha,trayCount:ct.tray.length,trayType:rn?.tray_type||void 0,trayColor:rn?.tray_color||void 0,traySubBrands:rn?.tray_sub_brands||void 0,trayInfoIdx:rn?.tray_info_idx||void 0,extruderId:Un,caliIdx:rn?.cali_idx,savedPresetId:Cl?.preset_id})},children:$p}):a.jsx(MD,{configureSlot:{enabled:k("printers:control"),onConfigure:()=>at({amsId:ct.id,trayId:ha,trayCount:ct.tray.length,extruderId:Un})},inventory:o?void 0:{onAssignSpool:()=>vn({printerId:t.id,amsId:ct.id,trayId:ha,trayInfo:{type:"",color:"",location:Ul(ct.id,ct.tray.length)}})},children:$p})]}),(ct.humidity!=null||ct.temp!=null)&&a.jsxs("div",{className:"flex flex-col justify-center gap-1 shrink-0 max-[550px]:w-full",children:[ct.temp!=null&&a.jsx(lK,{temp:ct.temp,goodThreshold:s?.tempGood,fairThreshold:s?.tempFair,onClick:()=>Zt({amsId:ct.id,amsLabel:Ul(ct.id,ct.tray.length),mode:"temperature"}),compact:!0}),ct.humidity!=null&&a.jsx(oK,{humidity:ct.humidity,goodThreshold:s?.humidityGood,fairThreshold:s?.humidityFair,onClick:()=>Zt({amsId:ct.id,amsLabel:Ul(ct.id,ct.tray.length),mode:"humidity"}),compact:!0})]})]})]},ct.id)}),Ue.vt_tray.length>0&&a.jsxs("div",{className:`p-2.5 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary/30 ${Ue.vt_tray.length===1?"max-w-[50%]":""}`,children:[a.jsx("div",{className:"flex items-center gap-1 mb-2",children:a.jsx("span",{className:"text-[10px] text-white font-medium",children:N("printers.external")})}),a.jsx("div",{className:`grid ${Ue.vt_tray.length>1?"grid-cols-2":"grid-cols-1"} gap-1.5`,children:[...Ue.vt_tray].sort((ct,Un)=>(ct.id??254)-(Un.id??254)).map(ct=>{const Un=ct.id??254,Tr=Jt&&Br===254?Un===254&&Ue.active_extruder===1||Un===255&&Ue.active_extruder===0:Br===Un,ar=Un-254,Lr=Jt?N(Un===254?"printers.extL":"printers.extR"):"",Da=ct.tray_info_idx?St?.[ct.tray_info_idx]:null,rn=Pt?.[1020+ar],En=(ct.tray_uuid||ct.tag_uid||Vu(t.serial_number,255,ar))?.toUpperCase(),Na=En?l?.[En]:void 0,ai=tN(Na),mi=u?.(t.id,255,ar),Ys=(()=>{const pa=mi?.spool;return pa&&pa.label_weight>0&&pa.weight_used!=null?Math.round(Math.max(0,pa.label_weight-pa.weight_used)/pa.label_weight*100):null})(),Cl=ct.tray_type&&ct.remain>=0,ha=Ys===0&&Cl&&ct.remain>0?null:Ys,Hi=ai??ha??(Cl?ct.remain:null),Pl=ai!==null?"spoolman":ha!==null?"inventory":Cl?"ams":void 0,qi={vendor:ID(ct)?"Bambu Lab":"Generic",profile:rn?.preset_name||Da?.name||mi?.spool?.slicer_filament_name||ct.tray_sub_brands||ct.tray_type||"Unknown",colorName:rc(ct.tray_color||""),colorHex:ct.tray_color||null,kFactor:LD(ct.k),fillLevel:Hi,trayUuid:ct.tray_uuid||null,tagUid:ct.tag_uid||null,fillSource:Pl},Qs=!ct.tray_type,Pc=a.jsxs("div",{className:`bg-bambu-dark-tertiary rounded p-1 text-center ${Qs?"opacity-50":""} ${Tr?"ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark":""}`,children:[a.jsx(RD,{trayColor:ct.tray_color,trayType:ct.tray_type,isEmpty:Qs,slotNumber:ar+1}),a.jsx("div",{className:`text-[9px] font-bold truncate ${Qs?"text-white/40":"text-white"}`,children:ct.tray_type||"—"}),a.jsx("div",{className:"mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden",children:Hi!==null&&Hi>=0&&!Qs&&a.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${Hi}%`,backgroundColor:Ox(Hi)}})}),Lr&&a.jsx("div",{className:"text-[7px] text-white/40 mt-0.5 truncate",children:Lr})]});return a.jsx("div",{className:"relative group",children:Qs?a.jsx(MD,{configureSlot:{enabled:k("printers:control"),onConfigure:()=>at({amsId:255,trayId:ar,trayCount:1,extruderId:Jt?Un===254?1:0:void 0})},inventory:o?void 0:{onAssignSpool:()=>vn({printerId:t.id,amsId:255,trayId:ar,trayInfo:{type:"",color:"",location:Lr||N("printers.external")}})},children:Pc}):a.jsx(jD,{data:qi,spoolman:{enabled:o,linkedSpoolId:En?l?.[En]?.id:void 0,spoolmanUrl:c,syncMode:d,onLinkSpool:o?()=>{const pa=(qi.trayUuid||qi.tagUid||Vu(t.serial_number,255,ar)).toUpperCase();Xt({tagUid:qi.tagUid||pa,trayUuid:qi.trayUuid||"",printerId:t.id,amsId:255,trayId:ar})}:void 0,onUnlinkSpool:Na?.id?()=>Ps.mutate(Na.id):void 0},inventory:o?void 0:(()=>{const pa=u?.(t.id,255,ar);return{assignedSpool:pa?.spool?{id:pa.spool.id,material:pa.spool.material,brand:pa.spool.brand,color_name:pa.spool.color_name,remainingWeightGrams:Math.max(0,Math.round(pa.spool.label_weight-pa.spool.weight_used))}:null,onAssignSpool:()=>vn({printerId:t.id,amsId:255,trayId:ar,trayInfo:{type:ct.tray_type||qi.profile,material:ct.tray_type??void 0,profile:qi.profile,color:qi.colorHex||"",location:Lr||N("printers.external")}}),onUnassignSpool:pa?()=>m?.(t.id,255,ar):void 0}})(),configureSlot:{enabled:k("printers:control"),onConfigure:()=>at({amsId:255,trayId:ar,trayCount:1,trayType:ct.tray_type||void 0,trayColor:ct.tray_color||void 0,traySubBrands:ct.tray_sub_brands||void 0,trayInfoIdx:ct.tray_info_idx||void 0,extruderId:Jt?Un===254?1:0:void 0,caliIdx:ct.cali_idx,savedPresetId:rn?.preset_id})},children:Pc})},Un)})})]})]})]})]})})()]}),cr&&r==="expanded"&&a.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[a.jsx(dc,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}),a.jsx("span",{className:"text-sm text-white truncate",children:cr.name}),Ui&&a.jsxs("span",{className:`text-xs px-1.5 py-0.5 rounded flex-shrink-0 ${Ui.state==="ON"?"bg-bambu-green/20 text-bambu-green":Ui.state==="OFF"?"bg-red-500/20 text-red-400":"bg-bambu-gray/20 text-bambu-gray"}`,children:[Ui.state||"?",Ui.state==="ON"&&Ui.energy?.power!=null&&a.jsxs("span",{className:"text-yellow-400 ml-1.5",children:["· ",Ui.energy.power,"W"]})]})]}),a.jsx("div",{className:"flex-1"}),a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsxs("button",{onClick:()=>pe(!0),disabled:Wo.isPending||Ui?.state==="ON"||!k("smart_plugs:control"),className:`px-2 py-1 text-xs rounded transition-colors flex items-center gap-1 ${k("smart_plugs:control")?Ui?.state==="ON"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary":"bg-bambu-dark text-bambu-gray/50 cursor-not-allowed"}`,title:k("smart_plugs:control")?void 0:N("printers.permission.noSmartPlugControl"),children:[a.jsx(Yd,{className:"w-3 h-3"}),"On"]}),a.jsxs("button",{onClick:()=>Ne(!0),disabled:Wo.isPending||Ui?.state==="OFF"||!k("smart_plugs:control"),className:`px-2 py-1 text-xs rounded transition-colors flex items-center gap-1 ${k("smart_plugs:control")?Ui?.state==="OFF"?"bg-red-500/30 text-red-400":"bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary":"bg-bambu-dark text-bambu-gray/50 cursor-not-allowed"}`,title:k("smart_plugs:control")?void 0:N("printers.permission.noSmartPlugControl"),children:[a.jsx(aS,{className:"w-3 h-3"}),"Off"]})]}),a.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[a.jsx("span",{className:`text-xs hidden sm:inline ${cr.auto_off_executed?"text-bambu-green":"text-bambu-gray"}`,children:cr.auto_off_executed?"Auto-off done":"Auto-off"}),a.jsx("button",{onClick:()=>So.mutate(!cr.auto_off),disabled:So.isPending||cr.auto_off_executed||!k("smart_plugs:control"),title:k("smart_plugs:control")?cr.auto_off_executed?N("printers.autoOffExecuted"):N("printers.autoOffAfterPrint"):N("printers.permission.noSmartPlugControl"),className:`relative w-9 h-5 rounded-full transition-colors flex-shrink-0 ${k("smart_plugs:control")?cr.auto_off_executed?"bg-bambu-green/50 cursor-not-allowed":cr.auto_off?"bg-bambu-green":"bg-bambu-dark-tertiary":"bg-bambu-dark-tertiary/50 cursor-not-allowed"}`,children:a.jsx("span",{className:`absolute top-[2px] left-[2px] w-4 h-4 bg-white rounded-full transition-transform ${cr.auto_off||cr.auto_off_executed?"translate-x-4":"translate-x-0"}`})})]})]}),Ci&&Ci.length>0&&a.jsxs("div",{className:"flex items-center gap-2 mt-2 pt-2 border-t border-bambu-dark-tertiary/50",children:[a.jsx(Jw,{className:"w-3.5 h-3.5 text-blue-400 flex-shrink-0"}),a.jsx("span",{className:"text-xs text-bambu-gray",children:"HA:"}),a.jsx("div",{className:"flex flex-wrap gap-1",children:Ci.map(lt=>{const Ht=lt.ha_entity_id?.startsWith("script.");return a.jsxs("button",{onClick:()=>_c.mutate({id:lt.id,action:Ht?"on":"toggle"}),disabled:_c.isPending,title:`${Ht?"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:[a.jsx(ns,{className:"w-2.5 h-2.5"}),lt.name]},lt.id)})})]})]}),r==="expanded"&&a.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary flex items-center justify-end gap-2 flex-wrap",children:[a.jsx(De,{variant:"secondary",size:"sm",onClick:()=>au.mutate(!Ue?.chamber_light),disabled:!Ue?.connected||au.isPending||!k("printers:control"),title:k("printers:control")?Ue?.chamber_light?N("printers.chamberLightOff"):N("printers.chamberLightOn"):N("printers.permission.noControl"),className:Ue?.chamber_light?"!border-yellow-500 !text-yellow-400 hover:!bg-yellow-500/20":"",children:a.jsx(xI,{on:Ue?.chamber_light??!1,className:`w-4 h-4 ${Ue?.chamber_light?"text-yellow-400":""}`})}),a.jsx(De,{variant:"secondary",size:"sm",onClick:()=>{if(f==="embedded"&&y)y(t.id,t.name);else{const lt=localStorage.getItem("cameraWindowState"),Ht=lt?JSON.parse(lt):{width:640,height:400},Jt=[`width=${Ht.width}`,`height=${Ht.height}`,Ht.left!==void 0?`left=${Ht.left}`:"",Ht.top!==void 0?`top=${Ht.top}`:"","menubar=no,toolbar=no,location=no,status=no"].filter(Boolean).join(",");window.open(`/camera/${t.id}`,`camera-${t.id}`,Jt)}},disabled:!Ue?.connected||!k("camera:view"),title:k("camera:view")?N(f==="embedded"?"printers.openCameraOverlay":"printers.openCameraWindow"):N("printers.permission.noCamera"),children:a.jsx(OO,{className:"w-4 h-4"})}),a.jsxs("div",{className:`inline-flex rounded-md ${t.plate_detection_enabled?"ring-1 ring-green-500":""}`,children:[a.jsx(De,{variant:"secondary",size:"sm",onClick:qy,disabled:!Ue?.connected||_o.isPending||!k("printers:update"),title:k("printers:update")?t.plate_detection_enabled?N("printers.plateDetection.enabledClick"):N("printers.plateDetection.disabledClick"):N("printers.plateDetection.noPermission"),className:`!rounded-r-none !border-r-0 ${t.plate_detection_enabled?"!border-green-500 !text-green-400 hover:!bg-green-500/20":""}`,children:_o.isPending?a.jsx(ft,{className:"w-4 h-4 animate-spin"}):a.jsx(NN,{className:"w-4 h-4"})}),a.jsx(De,{variant:"secondary",size:"sm",onClick:Hp,disabled:!Ue?.connected||mt||!k("printers:update"),title:k("printers:update")?N("printers.plateDetection.manageCalibration"):N("printers.plateDetection.noPermission"),className:`!rounded-l-none !px-1.5 ${t.plate_detection_enabled?"!border-green-500 !text-green-400 hover:!bg-green-500/20":""}`,children:mt?a.jsx(ft,{className:"w-3 h-3 animate-spin"}):a.jsx(On,{className:"w-3 h-3"})})]}),a.jsxs(De,{variant:"secondary",size:"sm",onClick:()=>ge(!0),disabled:!Nr||!k("printers:files"),title:k("printers:files")?N("printers.browseFiles"):N("printers.permission.noFiles"),children:[a.jsx(Ig,{className:"w-4 h-4"}),N("printers.files")]}),Nr&&Ue?.state!=="RUNNING"&&Ue?.state!=="PAUSE"&&a.jsxs(De,{size:"sm",onClick:()=>ve(!0),disabled:!k("printers:control"),title:k("printers:control")?N("common.print"):N("printers.permission.noControl"),className:"!bg-bambu-green hover:!bg-bambu-green/80 !text-white",children:[a.jsx(Dr,{className:"w-4 h-4"}),N("common.print")]})]})]}),oe&&a.jsx(HMe,{printerId:t.id,printerName:t.name,onClose:()=>ge(!1)}),Se&&a.jsx(Xae,{folderId:null,onClose:()=>ve(!1),onUploadComplete:()=>{},autoUpload:!0,accept:".gcode,.3mf",validateFile:lt=>{const Ht=lt.name.toLowerCase();if(!Ht.endsWith(".gcode")&&!Ht.includes(".gcode."))return N("printers.dropNotPrintable","Only .gcode and .gcode.3mf files can be printed")},onFileUploaded:lt=>{const Ht=lt.metadata?.sliced_for_model,Jt=O0(t.model);if(Ht&&Jt&&Ht.toLowerCase()!==Jt.toLowerCase())return me.deleteLibraryFile(lt.id).catch(()=>{}),N("printers.incompatibleFile","This file was sliced for {{slicedFor}}, but this printer is a {{printerModel}}",{slicedFor:Ht,printerModel:Jt});Fe({id:lt.id,filename:lt.filename})}}),Ce&&a.jsx(ic,{mode:"reprint",libraryFileId:Ce.id,archiveName:Ce.filename,initialSelectedPrinterIds:[t.id],onClose:()=>Fe(null),onSuccess:()=>Fe(null),cleanupLibraryAfterDispatch:!0}),re&&a.jsx(KMe,{printerId:t.id,printerName:t.name,onClose:()=>W(!1)}),Ae&&a.jsx(N7e,{printer:t,status:Ue,totalPrintHours:n?.total_print_hours,onClose:he}),At&&a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onClick:()=>ld(),children:a.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:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[At.needs_calibration?a.jsx(NN,{className:"w-5 h-5 text-blue-500"}):At.is_empty?a.jsx(yr,{className:"w-5 h-5 text-green-500"}):a.jsx(Ma,{className:"w-5 h-5 text-yellow-500"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:"Build Plate Check"}),At.reference_count!==void 0&&At.max_references&&a.jsxs("span",{className:"text-xs text-bambu-gray bg-bambu-dark-tertiary px-2 py-1 rounded",children:[At.reference_count,"/",At.max_references," refs"]})]}),a.jsx("button",{onClick:()=>ld(),className:"p-1 text-bambu-gray hover:text-white rounded transition-colors",children:a.jsx(Bt,{className:"w-5 h-5"})})]}),a.jsxs("div",{className:"p-4 space-y-4",children:[At.needs_calibration?a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"p-3 rounded-lg bg-blue-500/20 border border-blue-500/50",children:[a.jsx("p",{className:"font-medium text-blue-400",children:N("printers.plateDetection.calibrationRequired")}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",dangerouslySetInnerHTML:{__html:N("printers.plateDetection.calibrationInstructions")}})]}),a.jsxs("div",{className:"text-sm text-bambu-gray space-y-2",children:[a.jsx("p",{children:N("printers.plateDetection.calibrationDescription")}),a.jsx("p",{dangerouslySetInnerHTML:{__html:N("printers.plateDetection.calibrationTip")}})]})]}):a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:`p-3 rounded-lg ${At.is_empty?"bg-green-500/20 border border-green-500/50":"bg-yellow-500/20 border border-yellow-500/50"}`,children:[a.jsx("p",{className:`font-medium ${At.is_empty?"text-green-400":"text-yellow-400"}`,children:At.is_empty?N("printers.plateDetection.plateEmpty"):N("printers.plateDetection.objectsDetected")}),a.jsxs("p",{className:"text-sm text-bambu-gray mt-1",children:[N("printers.plateDetection.confidence"),": ",Math.round(At.confidence*100),"% | ",N("printers.plateDetection.difference"),": ",At.difference_percent.toFixed(1),"%"]})]}),At.debug_image_url&&a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-bambu-gray mb-2",children:N("printers.plateDetection.analysisPreview")}),a.jsx("img",{src:At.debug_image_url,alt:N("printers.plateDetection.analysisPreview"),className:"w-full rounded-lg border border-bambu-dark-tertiary"}),a.jsx("p",{className:"text-xs text-bambu-gray mt-2",children:N("printers.plateDetection.analysisLegend")})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:At.message})]}),kc&&kc.references.length>0&&a.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[a.jsx("p",{className:"text-sm font-medium text-white mb-2",children:N("printers.plateDetection.savedReferences",{count:kc.references.length,max:kc.max_references})}),a.jsx("div",{className:"grid grid-cols-5 gap-2",children:kc.references.map(lt=>a.jsxs("div",{className:"relative group",children:[a.jsx("img",{src:me.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"}),a.jsx("button",{onClick:()=>$y(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:N("printers.plateDetection.deleteReference"),children:a.jsx(Bt,{className:"w-3 h-3 text-white"})}),od?.index===lt.index?a.jsx("input",{type:"text",value:od.label,onChange:Ht=>Nc({...od,label:Ht.target.value}),onBlur:()=>Im(lt.index,od.label),onKeyDown:Ht=>{Ht.key==="Enter"&&Im(lt.index,od.label),Ht.key==="Escape"&&Nc(null)},className:"w-full mt-1 px-1 py-0.5 text-xs bg-bambu-dark-tertiary border border-bambu-green rounded text-white",autoFocus:!0,placeholder:N("printers.plateDetection.labelPlaceholder")}):a.jsx("p",{className:"text-xs text-bambu-gray mt-1 truncate cursor-pointer hover:text-white",onClick:()=>Nc({index:lt.index,label:lt.label}),title:lt.label?N("printers.plateDetection.clickToEdit",{label:lt.label}):N("printers.plateDetection.clickToAddLabel"),children:lt.label||a.jsx("span",{className:"italic opacity-50",children:N("printers.noLabel")})}),a.jsx("p",{className:"text-[10px] text-bambu-gray/60",children:lt.timestamp?Zn(lt.timestamp)?.toLocaleDateString()??"":""})]},lt.index))})]}),!At.needs_calibration&&a.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsx("p",{className:"text-sm font-medium text-white",children:N("printers.roi.title")}),ot?a.jsxs("div",{className:"flex gap-1",children:[a.jsx(De,{variant:"ghost",size:"sm",onClick:()=>Te(null),disabled:Ge,children:N("common.cancel")}),a.jsx(De,{size:"sm",onClick:_e,disabled:Ge,children:Ge?a.jsx(ft,{className:"w-3 h-3 animate-spin"}):N("common.save")})]}):a.jsxs(De,{variant:"ghost",size:"sm",onClick:()=>Te(At.roi||{x:.15,y:.35,w:.7,h:.55}),children:[a.jsx(ci,{className:"w-3 h-3 mr-1"}),N("common.edit")]})]}),ot?a.jsxs("div",{className:"space-y-3 bg-bambu-dark-tertiary/50 p-3 rounded-lg",children:[a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"text-xs text-bambu-gray",children:N("printers.roi.xStart")}),a.jsx("input",{type:"range",min:"0",max:"0.9",step:"0.01",value:ot.x,onChange:lt=>Te({...ot,x:parseFloat(lt.target.value)}),className:"w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"}),a.jsxs("span",{className:"text-xs text-bambu-gray",children:[Math.round(ot.x*100),"%"]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"text-xs text-bambu-gray",children:N("printers.roi.yStart")}),a.jsx("input",{type:"range",min:"0",max:"0.9",step:"0.01",value:ot.y,onChange:lt=>Te({...ot,y:parseFloat(lt.target.value)}),className:"w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"}),a.jsxs("span",{className:"text-xs text-bambu-gray",children:[Math.round(ot.y*100),"%"]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"text-xs text-bambu-gray",children:N("printers.width")}),a.jsx("input",{type:"range",min:"0.1",max:"1",step:"0.01",value:ot.w,onChange:lt=>Te({...ot,w:parseFloat(lt.target.value)}),className:"w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"}),a.jsxs("span",{className:"text-xs text-bambu-gray",children:[Math.round(ot.w*100),"%"]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"text-xs text-bambu-gray",children:N("printers.height")}),a.jsx("input",{type:"range",min:"0.1",max:"1",step:"0.01",value:ot.h,onChange:lt=>Te({...ot,h:parseFloat(lt.target.value)}),className:"w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"}),a.jsxs("span",{className:"text-xs text-bambu-gray",children:[Math.round(ot.h*100),"%"]})]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:N("printers.roi.instruction")})]}):a.jsxs("p",{className:"text-xs text-bambu-gray",children:["Current: X=",Math.round((At.roi?.x||.15)*100),"%, Y=",Math.round((At.roi?.y||.35)*100),"%, W=",Math.round((At.roi?.w||.7)*100),"%, H=",Math.round((At.roi?.h||.55)*100),"%"]})]})]}),a.jsx("div",{className:"flex justify-end gap-2 p-4 border-t border-bambu-dark-tertiary",children:At.needs_calibration?a.jsxs(a.Fragment,{children:[a.jsx(De,{variant:"ghost",onClick:()=>ld(),children:N("common.cancel")}),a.jsx(De,{onClick:()=>Cc(),disabled:nt,children:nt?a.jsxs(a.Fragment,{children:[a.jsx(ft,{className:"w-4 h-4 mr-2 animate-spin"}),"Calibrating..."]}):"Calibrate Empty Plate"})]}):a.jsxs(a.Fragment,{children:[a.jsx(De,{variant:"ghost",onClick:()=>Cc(),disabled:nt,children:nt?"Adding...":`Add Reference (${kc?.references.length||0}/${kc?.max_references||5})`}),a.jsx(De,{onClick:()=>ld(),children:"Close"})]})})]})}),ne&&cr&&a.jsx(yn,{title:N("printers.confirm.powerOnTitle"),message:N("printers.confirm.powerOnMessage",{name:t.name}),confirmText:N("printers.confirm.powerOnButton"),variant:"default",onConfirm:()=>{Wo.mutate("on"),pe(!1)},onCancel:()=>pe(!1)}),xe&&cr&&a.jsx(yn,{title:N("printers.confirm.powerOffTitle"),message:Ue?.state==="RUNNING"?N("printers.confirm.powerOffWarning",{name:t.name}):N("printers.confirm.powerOffMessage",{name:t.name}),confirmText:N("printers.confirm.powerOffButton"),variant:"danger",onConfirm:()=>{Wo.mutate("off"),Ne(!1)},onCancel:()=>Ne(!1)}),E&&a.jsx(yn,{title:N("printers.confirm.stopTitle"),message:N("printers.confirm.stopMessage",{name:t.name}),confirmText:N("printers.confirm.stopButton"),variant:"danger",onConfirm:()=>{ru.mutate(),j(!1)},onCancel:()=>j(!1)}),O&&a.jsx(yn,{title:N("printers.confirm.pauseTitle"),message:N("printers.confirm.pauseMessage",{name:t.name}),confirmText:N("printers.confirm.pauseButton"),variant:"default",onConfirm:()=>{zp.mutate(),K(!1)},onCancel:()=>K(!1)}),le&&a.jsx(yn,{title:N("printers.confirm.resumeTitle"),message:N("printers.confirm.resumeMessage",{name:t.name}),confirmText:N("printers.confirm.resumeButton"),variant:"default",onConfirm:()=>{di.mutate(),B(!1)},onCancel:()=>B(!1)}),be&&a.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/70 p-4",children:a.jsxs("div",{className:"bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl w-full max-w-sm p-5",children:[a.jsxs("div",{className:"flex items-start gap-3 mb-4",children:[a.jsx(Dn,{className:"w-5 h-5 text-yellow-400 flex-shrink-0 mt-0.5"}),a.jsxs("div",{children:[a.jsx("h3",{className:"text-sm font-semibold text-white mb-1",children:N("printers.bedJog.notHomedTitle")}),a.jsx("p",{className:"text-xs text-bambu-gray leading-relaxed",children:N("printers.bedJog.notHomedMessage")})]})]}),a.jsxs("div",{className:"flex flex-col gap-2",children:[a.jsx("button",{onClick:()=>{iu.mutate("all"),fe(null)},className:"w-full px-3 py-2 rounded-lg text-xs font-medium bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30 transition-colors",children:N("printers.bedJog.homeZ")}),a.jsx("button",{onClick:()=>{const lt=be.distance;try{sessionStorage.setItem(`bambuddy.bedJog.warned.${t.id}`,"1")}catch{}Ko.mutate({distance:lt,force:!0}),fe(null)},className:"w-full px-3 py-2 rounded-lg text-xs font-medium bg-yellow-500/20 text-yellow-400 hover:bg-yellow-500/30 transition-colors",children:N("printers.bedJog.moveAnyway")}),a.jsx("button",{onClick:()=>fe(null),className:"w-full px-3 py-2 rounded-lg text-xs font-medium bg-bambu-dark text-bambu-gray hover:bg-bambu-dark-tertiary transition-colors",children:N("common.cancel")})]})]})}),a.jsx(yI,{printerId:t.id,isOpen:R,onClose:()=>ae(!1)}),q&&a.jsx($ye,{printerName:t.name,errors:Ue?.hms_errors||[],onClose:()=>Y(!1),printerId:t.id,hasPermission:k}),Wt&&a.jsx(a7e,{isOpen:!!Wt,onClose:()=>Zt(null),printerId:t.id,printerName:t.name,amsId:Wt.amsId,amsLabel:Wt.amsLabel,initialMode:Wt.mode,thresholds:s}),Kt&&a.jsx(Gae,{isOpen:!!Kt,onClose:()=>Xt(null),tagUid:Kt.tagUid,trayUuid:Kt.trayUuid,printerId:Kt.printerId,amsId:Kt.amsId,trayId:Kt.trayId}),ln&&a.jsx(Wae,{isOpen:!!ln,onClose:()=>vn(null),printerId:ln.printerId,amsId:ln.amsId,trayId:ln.trayId,trayInfo:ln.trayInfo}),Ke&&a.jsx(Kae,{isOpen:!!Ke,onClose:()=>at(null),printerId:t.id,slotInfo:Ke,printerModel:O0(t.model)||void 0,onSuccess:()=>{A.invalidateQueries({queryKey:["slotPresets",t.id]}),A.invalidateQueries({queryKey:["printerStatus",t.id]})}}),ie&&a.jsx(z7e,{printer:t,onClose:()=>J(!1)}),Lt&&et&&a.jsx(I7e,{printer:t,firmwareInfo:et,onClose:()=>Et(!1)}),Sn&&a.jsx("div",{className:"fixed inset-0 z-40",onClick:()=>_n(null)}),Me!==null&&ye&&(()=>{const lt=Re==="n3s"?85:65,Ht=35,Jt=lt+10;return a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"fixed inset-0 z-[100]",onClick:()=>Oe(null)}),a.jsxs("div",{className:"fixed z-[101] w-[240px] bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl overflow-hidden",style:{top:ye.top,left:ye.left},onClick:ct=>ct.stopPropagation(),children:[a.jsxs("div",{className:"flex items-center gap-2 px-3 py-2.5 border-b border-bambu-dark-tertiary",children:[a.jsx(Hu,{className:"w-3.5 h-3.5 text-amber-400"}),a.jsx("span",{className:"text-xs text-white font-medium",children:N("printers.drying.start")})]}),a.jsxs("div",{className:"px-3 py-2.5 space-y-2.5",children:[a.jsxs("div",{children:[a.jsx("label",{className:"text-[10px] text-bambu-gray mb-1 block",children:N("printers.filaments")}),a.jsx("select",{value:Xe,onChange:ct=>{const Un=ct.target.value;tt(Un);const Tr=b[Un];Tr&&(ze(Tr[Re==="n3s"?"n3s":"n3f"]),qe(Re==="n3s"?Tr.n3s_hours:Tr.n3f_hours))},className:"w-full px-2 py-1.5 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-xs focus:outline-none focus:border-amber-500/50",children:Object.keys(b).map(ct=>a.jsx("option",{value:ct,children:ct},ct))})]}),a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center justify-between mb-1",children:[a.jsx("label",{className:"text-[10px] text-bambu-gray",children:N("printers.drying.temperature")}),a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx("input",{type:"number",min:45,max:lt,value:we,onChange:ct=>ze(Math.min(lt,Math.max(45,Number(ct.target.value)||45))),className:"w-12 px-1 py-0.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-[11px] text-center focus:outline-none focus:border-amber-500/50 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"}),a.jsx("span",{className:"text-[10px] text-bambu-gray",children:"°C"})]})]}),a.jsx("input",{type:"range",min:Ht,max:Jt,value:we,onChange:ct=>ze(Math.min(lt,Math.max(45,Number(ct.target.value)))),className:"w-full h-1 accent-amber-500 cursor-pointer"}),a.jsxs("div",{className:"flex justify-between text-[9px] text-bambu-gray/50 mt-0.5",children:[a.jsx("span",{children:"45°C"}),a.jsxs("span",{children:[lt,"°C"]})]})]}),a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center justify-between mb-1",children:[a.jsx("label",{className:"text-[10px] text-bambu-gray",children:N("printers.drying.duration")}),a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx("input",{type:"number",min:1,max:24,value:ce,onChange:ct=>qe(Math.min(24,Math.max(1,Number(ct.target.value)||1))),className:"w-10 px-1 py-0.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-[11px] text-center focus:outline-none focus:border-amber-500/50 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"}),a.jsx("span",{className:"text-[10px] text-bambu-gray",children:N("printers.drying.hours")})]})]}),a.jsx("input",{type:"range",min:1,max:24,value:ce,onChange:ct=>qe(Number(ct.target.value)),className:"w-full h-1 accent-amber-500 cursor-pointer"}),a.jsxs("div",{className:"flex justify-between text-[9px] text-bambu-gray/50 mt-0.5",children:[a.jsx("span",{children:"1h"}),a.jsx("span",{children:"24h"})]})]}),a.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:Pe,onChange:ct=>de(ct.target.checked),className:"w-3.5 h-3.5 accent-amber-500 rounded cursor-pointer"}),a.jsx("span",{className:"text-[11px] text-bambu-gray",children:N("printers.drying.rotateTray")})]})]}),a.jsx("div",{className:"px-3 pb-3",children:a.jsx("button",{onClick:()=>{Me!==null&&wo.mutate({amsId:Me,temp:we,duration:ce,filament:Xe,rotateTray:Pe})},disabled:wo.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:wo.isPending?N("printers.drying.startingDrying"):N("printers.drying.start")})})]})]})})()]})}function O7e({onClose:t,onAdd:e,existingSerials:n}){const{t:r}=Ft(),[i,s]=w.useState({name:"",serial_number:"",ip_address:"",access_code:"",model:"",location:"",auto_archive:!0}),[o,l]=w.useState(!1),[c,d]=w.useState([]),[u,m]=w.useState(""),[p,f]=w.useState(!1),[y,v]=w.useState(!1),[b,g]=w.useState([]),[_,C]=w.useState(""),[P,N]=w.useState({scanned:0,total:0});w.useEffect(()=>{hd.getInfo().then(k=>{v(k.is_docker),k.subnets.length>0&&(g(k.subnets),C(k.subnets[0]))}).catch(()=>{})},[]);const A=c.filter(k=>!n.includes(k.serial)),T=async()=>{m(""),d([]),l(!0),f(!1),N({scanned:0,total:0});try{if(y){await hd.startSubnetScan(_);const k=setInterval(async()=>{try{const D=await hd.getScanStatus();N({scanned:D.scanned,total:D.total});const H=await hd.getDiscoveredPrinters();d(H),D.running||(clearInterval(k),l(!1),f(!0))}catch(D){console.error("Failed to get scan status:",D)}},500)}else{await hd.startDiscovery(10);const k=setInterval(async()=>{try{const D=await hd.getDiscoveredPrinters();d(D)}catch(D){console.error("Failed to get discovered printers:",D)}},1e3);setTimeout(async()=>{clearInterval(k);try{await hd.stopDiscovery()}catch{}l(!1),f(!0);try{const D=await hd.getDiscoveredPrinters();d(D)}catch(D){console.error("Failed to get final discovered printers:",D)}},1e4)}}catch(k){console.error("Failed to start discovery:",k),m(k instanceof Error?k.message:r("printers.discovery.failedToStart")),l(!1),f(!0)}},F=k=>{const D=k.serial.startsWith("unknown-")?"":k.serial;s({...i,name:k.name||"",serial_number:D,ip_address:k.ip_address,model:O0(k.model)}),d([])};return w.useEffect(()=>()=>{hd.stopDiscovery().catch(()=>{}),hd.stopSubnetScan().catch(()=>{})},[]),w.useEffect(()=>{const k=D=>{D.key==="Escape"&&t()};return window.addEventListener("keydown",k),()=>window.removeEventListener("keydown",k)},[t]),a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-start sm:items-center justify-center z-50 p-4 overflow-y-auto",onClick:t,children:a.jsx(Tt,{className:"w-full max-w-md my-auto max-h-[calc(100vh-2rem)] overflow-y-auto",onClick:k=>k.stopPropagation(),children:a.jsxs(Mt,{children:[a.jsx("h2",{className:"text-xl font-semibold mb-4",children:r("printers.addPrinter")}),a.jsxs("div",{className:"mb-4 pb-4 border-b border-bambu-dark-tertiary",children:[y&&a.jsxs("div",{className:"mb-3",children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.discovery.subnetToScan")}),b.length>0?a.jsx("select",{className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none text-sm",value:_,onChange:k=>C(k.target.value),disabled:o,children:b.map(k=>a.jsx("option",{value:k,children:k},k))}):a.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none text-sm",value:_,onChange:k=>C(k.target.value),placeholder:"192.168.1.0/24",disabled:o}),a.jsx("p",{className:"mt-1 text-xs text-bambu-gray",children:r("printers.discovery.dockerNote")})]}),a.jsx(De,{type:"button",variant:"secondary",onClick:T,disabled:o,className:"w-full",children:o?a.jsxs(a.Fragment,{children:[a.jsx(ft,{className:"w-4 h-4 animate-spin"}),y&&P.total>0?r("printers.discovery.scanProgress",{scanned:P.scanned,total:P.total}):r("printers.discovery.scanning")]}):a.jsxs(a.Fragment,{children:[a.jsx(Pr,{className:"w-4 h-4"}),r(y?"printers.discovery.scanSubnet":"printers.discovery.discoverNetwork")]})}),u&&a.jsx("div",{className:"mt-2 text-sm text-red-400",children:u}),A.length>0&&a.jsx("div",{className:"mt-3 space-y-2 max-h-40 overflow-y-auto",children:A.map(k=>a.jsxs("div",{className:"flex items-center justify-between p-2 bg-bambu-dark rounded-lg hover:bg-bambu-dark-secondary cursor-pointer transition-colors",onClick:()=>F(k),children:[a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:"font-medium text-white text-sm truncate",children:k.name||k.serial}),a.jsxs("p",{className:"text-xs text-bambu-gray truncate",children:[O0(k.model)||r("printers.discovery.unknown")," • ",k.ip_address,k.serial.startsWith("unknown-")&&a.jsxs("span",{className:"text-yellow-500",children:[" • ",r("printers.discovery.serialRequired")]})]})]}),a.jsx(On,{className:"w-4 h-4 text-bambu-gray -rotate-90 flex-shrink-0 ml-2"})]},k.serial))}),o&&a.jsx("p",{className:"mt-2 text-sm text-bambu-gray text-center",children:r(y?"printers.discovery.scanningSubnet":"printers.discovery.scanningNetwork")}),p&&!o&&c.length===0&&a.jsx("p",{className:"mt-2 text-sm text-bambu-gray text-center",children:r(y?"printers.discovery.noPrintersFoundSubnet":"printers.discovery.noPrintersFoundNetwork")}),p&&!o&&c.length>0&&A.length===0&&a.jsx("p",{className:"mt-2 text-sm text-bambu-gray text-center",children:r("printers.discovery.allConfigured")})]}),a.jsxs("form",{onSubmit:k=>{k.preventDefault(),e(i)},className:"space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.name")}),a.jsx("input",{type:"text",required:!0,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:i.name,onChange:k=>s({...i,name:k.target.value}),placeholder:r("printers.modal.myPrinter")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.ipAddress")}),a.jsx("input",{type:"text",required:!0,pattern:"(\\d{1,3}(\\.\\d{1,3}){3}|[a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?(\\.[a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?)*)",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:i.ip_address,onChange:k=>s({...i,ip_address:k.target.value}),placeholder:"192.168.1.100 or printer.local"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.serialNumber")}),a.jsx("input",{type:"text",required:!0,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:i.serial_number,onChange:k=>s({...i,serial_number:k.target.value}),placeholder:"01P00A000000000"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.accessCode")}),a.jsx("input",{type:"password",required:!0,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:i.access_code,onChange:k=>s({...i,access_code:k.target.value}),placeholder:r("printers.modal.fromPrinterSettings")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.modal.modelOptional")}),a.jsxs("select",{className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:i.model||"",onChange:k=>s({...i,model:k.target.value}),children:[a.jsx("option",{value:"",children:r("printers.modal.selectModel")}),a.jsxs("optgroup",{label:"H2 Series",children:[a.jsx("option",{value:"H2C",children:"H2C"}),a.jsx("option",{value:"H2D",children:"H2D"}),a.jsx("option",{value:"H2D Pro",children:"H2D Pro"}),a.jsx("option",{value:"H2S",children:"H2S"})]}),a.jsx("optgroup",{label:"X2 Series",children:a.jsx("option",{value:"X2D",children:"X2D"})}),a.jsxs("optgroup",{label:"X1 Series",children:[a.jsx("option",{value:"X1E",children:"X1E"}),a.jsx("option",{value:"X1C",children:"X1 Carbon"}),a.jsx("option",{value:"X1",children:"X1"})]}),a.jsxs("optgroup",{label:"P Series",children:[a.jsx("option",{value:"P2S",children:"P2S"}),a.jsx("option",{value:"P1S",children:"P1S"}),a.jsx("option",{value:"P1P",children:"P1P"})]}),a.jsxs("optgroup",{label:"A1 Series",children:[a.jsx("option",{value:"A1",children:"A1"}),a.jsx("option",{value:"A1 Mini",children:"A1 Mini"})]})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.modal.locationGroup")}),a.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:i.location||"",onChange:k=>s({...i,location:k.target.value}),placeholder:r("printers.modal.locationPlaceholder")}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:r("printers.locationHelp")})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"checkbox",id:"auto_archive",checked:i.auto_archive,onChange:k=>s({...i,auto_archive:k.target.checked}),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),a.jsx("label",{htmlFor:"auto_archive",className:"text-sm text-bambu-gray",children:r("printers.modal.autoArchiveLabel")})]}),a.jsxs("div",{className:"flex gap-3 pt-4",children:[a.jsx(De,{type:"button",variant:"secondary",onClick:t,className:"flex-1",children:r("common.cancel")}),a.jsx(De,{type:"submit",className:"flex-1",children:r("printers.addPrinter")})]})]})]})})})}function I7e({printer:t,firmwareInfo:e,onClose:n}){const{t:r}=Ft(),i=nn(),{showToast:s}=hn(),{hasPermission:o}=kr(),l=o("firmware:update"),[c,d]=w.useState(null),[u,m]=w.useState(!1),[p,f]=w.useState(null),[y,v]=w.useState(e.update_available?e.latest_version:null),{data:b,isLoading:g}=Ye({queryKey:["firmwarePrepare",t.id,y],queryFn:()=>zk.prepareUpload(t.id,y??void 0),staleTime:3e4,enabled:!!y&&l&&!u}),_=it({mutationFn:()=>zk.startUpload(t.id,y??void 0),onSuccess:()=>{m(!0);const P=setInterval(async()=>{try{const N=await zk.getUploadStatus(t.id);d(N),(N.status==="complete"||N.status==="error")&&(clearInterval(P),f(null),m(!1),N.status==="complete"&&(s(r("printers.firmwareModal.uploadedToast"),"success"),i.invalidateQueries({queryKey:["firmwareUpdate",t.id]})))}catch{}},2e3);f(P)},onError:P=>{s(r("printers.firmwareModal.uploadFailed",{error:P.message}),"error"),m(!1)}});w.useEffect(()=>()=>{p&&clearInterval(p)},[p]);const C=()=>{d(null),_.mutate()};return a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",children:a.jsx(Tt,{className:"w-full max-w-md mx-4",children:a.jsxs(Mt,{children:[a.jsxs("div",{className:"flex items-start gap-3 mb-4",children:[a.jsx("div",{className:`p-2 rounded-full ${e.update_available?"bg-orange-500/20":"bg-status-ok/20"}`,children:e.update_available?a.jsx(ga,{className:"w-5 h-5 text-orange-400"}):a.jsx(yr,{className:"w-5 h-5 text-status-ok"})}),a.jsxs("div",{className:"flex-1",children:[a.jsx("h3",{className:"text-lg font-semibold text-white",children:e.update_available?r("printers.firmwareModal.title"):r("printers.firmwareModal.titleUpToDate")}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:t.name})]})]}),(()=>{const P=y?e.available_versions?.find(F=>F.version===y):null,N=y??e.latest_version,A=P?.release_notes??e.release_notes,T=!!N&&N!==e.current_version;return a.jsxs("div",{className:"bg-bambu-dark rounded-lg p-3 mb-4",children:[a.jsxs("div",{className:"flex justify-between items-center text-sm",children:[a.jsx("span",{className:"text-bambu-gray",children:r("printers.firmwareModal.currentVersion")}),a.jsx("span",{className:`font-mono ${T?"text-white":"text-status-ok"}`,children:e.current_version||r("common.unknown")})]}),T&&a.jsxs("div",{className:"flex justify-between items-center text-sm mt-1",children:[a.jsx("span",{className:"text-bambu-gray",children:r("printers.firmwareModal.latestVersion")}),a.jsx("span",{className:"text-orange-400 font-mono",children:N})]}),A&&a.jsxs("details",{className:"mt-3 text-sm",open:!T,children:[a.jsx("summary",{className:`cursor-pointer hover:underline ${T?"text-orange-400":"text-status-ok"}`,children:r("printers.firmwareModal.releaseNotes")}),a.jsx("div",{className:"mt-2 text-bambu-gray text-xs max-h-40 overflow-y-auto whitespace-pre-wrap",children:A})]},N??"none")]})})(),e.available_versions&&e.available_versions.length>0&&!u&&c?.status!=="complete"&&a.jsxs("div",{className:"mb-4",children:[a.jsx("div",{className:"text-xs text-bambu-gray mb-2",children:r("printers.firmwareModal.availableVersions")}),a.jsx("div",{className:"max-h-56 overflow-y-auto border border-bambu-dark-tertiary rounded-lg divide-y divide-bambu-dark-tertiary",children:e.available_versions.map(P=>{const N=e.current_version===P.version,A=y===P.version,T=e.current_version?Bye(P.version,e.current_version):0,F=N?r("printers.firmwareModal.currentBadge"):T>0?r("printers.firmwareModal.newerBadge"):r("printers.firmwareModal.olderBadge"),k=N?"text-bambu-gray":T>0?"text-orange-400":"text-blue-400";return a.jsxs("button",{type:"button",disabled:!P.file_available||!l||N,onClick:()=>v(P.version),className:`w-full text-left px-3 py-2 text-sm flex items-center justify-between gap-2 transition-colors ${A?"bg-orange-500/10":"hover:bg-bambu-dark"} ${!P.file_available||!l||N?"opacity-60 cursor-not-allowed":"cursor-pointer"}`,children:[a.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[a.jsx("span",{className:"font-mono text-white",children:P.version}),a.jsx("span",{className:`text-xs ${k}`,children:F})]}),a.jsx("span",{className:`text-xs px-2 py-0.5 rounded-full ${N?"bg-blue-500/15 text-blue-400 border border-blue-500/30":P.file_available?"bg-bambu-green/15 text-bambu-green border border-bambu-green/30":"bg-bambu-gray/10 text-bambu-gray border border-bambu-gray/30"}`,children:N?r("printers.firmwareModal.installed"):P.file_available?r("printers.firmwareModal.usable"):r("printers.firmwareModal.unavailable")})]},P.version)})})]}),y?g?a.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray text-sm mb-4",children:[a.jsx(ft,{className:"w-4 h-4 animate-spin"}),r("printers.firmwareModal.checkingPrereqs")]}):b&&!u&&!c?a.jsx("div",{className:"mb-4",children:b.can_proceed?a.jsxs("div",{className:"flex items-center gap-2 text-bambu-green text-sm",children:[a.jsx(vi,{className:"w-4 h-4"}),r("printers.firmwareModal.sdCardReady")]}):a.jsx("div",{className:"space-y-1",children:b.errors.map((P,N)=>a.jsxs("div",{className:"flex items-center gap-2 text-red-400 text-sm",children:[a.jsx(ei,{className:"w-4 h-4 flex-shrink-0"}),P]},N))})}):null:null,(u||c)&&c&&a.jsxs("div",{className:"mb-4",children:[a.jsxs("div",{className:"flex items-center justify-between text-sm mb-1",children:[a.jsx("span",{className:"text-bambu-gray capitalize",children:c.status}),a.jsxs("span",{className:"text-white",children:[c.progress,"%"]})]}),a.jsx("div",{className:"w-full bg-bambu-dark-tertiary rounded-full h-2",children:a.jsx("div",{className:`h-2 rounded-full transition-all ${c.status==="error"?"bg-status-error":c.status==="complete"?"bg-status-ok":"bg-orange-500"} ${c.status==="uploading"?"animate-pulse":""}`,style:{width:`${c.progress}%`}})}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:c.message}),c.error&&a.jsx("p",{className:"text-xs text-red-400 mt-1",children:c.error})]}),c?.status==="complete"&&a.jsxs("div",{className:"bg-bambu-green/10 border border-bambu-green/30 rounded-lg p-3 mb-4",children:[a.jsx("p",{className:"text-sm text-bambu-green font-medium mb-2",children:r("printers.firmwareModal.uploadedSuccess")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:r("printers.firmwareModal.applyInstructions")}),a.jsxs("ol",{className:"text-xs text-bambu-gray mt-1 list-decimal list-inside space-y-1",children:[a.jsx("li",{dangerouslySetInnerHTML:{__html:r("printers.firmwareModal.step1")}}),a.jsx("li",{dangerouslySetInnerHTML:{__html:r("printers.firmwareModal.step2")}}),a.jsx("li",{dangerouslySetInnerHTML:{__html:r("printers.firmwareModal.step3")}}),a.jsx("li",{children:r("printers.firmwareModal.step4")})]})]}),a.jsxs("div",{className:"flex gap-2 justify-end",children:[a.jsx(De,{variant:"secondary",onClick:n,children:c?.status==="complete"?r("printers.firmwareModal.done"):r("common.cancel")}),b?.can_proceed&&!u&&c?.status!=="complete"&&l&&a.jsx(De,{onClick:C,disabled:_.isPending,children:_.isPending?a.jsxs(a.Fragment,{children:[a.jsx(ft,{className:"w-4 h-4 animate-spin mr-2"}),r("printers.firmwareModal.starting")]}):a.jsxs(a.Fragment,{children:[a.jsx(ga,{className:"w-4 h-4 mr-2"}),r("printers.firmwareModal.uploadFirmware")]})})]})]})})})}function z7e({printer:t,onClose:e}){const{t:n}=Ft(),r=nn(),{showToast:i}=hn(),[s,o]=w.useState({name:t.name,ip_address:t.ip_address,access_code:"",model:t.model||"",location:t.location||"",auto_archive:t.auto_archive}),l=it({mutationFn:d=>me.updatePrinter(t.id,d),onSuccess:()=>{r.invalidateQueries({queryKey:["printers"]}),r.invalidateQueries({queryKey:["printerStatus",t.id]}),e()},onError:d=>i(d.message||n("printers.toast.failedToUpdate"),"error")});w.useEffect(()=>{const d=u=>{u.key==="Escape"&&e()};return window.addEventListener("keydown",d),()=>window.removeEventListener("keydown",d)},[e]);const c=d=>{d.preventDefault();const u={name:s.name,ip_address:s.ip_address,model:s.model||void 0,location:s.location||void 0,auto_archive:s.auto_archive};s.access_code&&(u.access_code=s.access_code),l.mutate(u)};return a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-start sm:items-center justify-center z-50 p-4 overflow-y-auto",onClick:e,children:a.jsx(Tt,{className:"w-full max-w-md my-auto max-h-[calc(100vh-2rem)] overflow-y-auto",onClick:d=>d.stopPropagation(),children:a.jsxs(Mt,{children:[a.jsx("h2",{className:"text-xl font-semibold mb-4",children:n("printers.editPrinter")}),a.jsxs("form",{onSubmit:c,className:"space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.name")}),a.jsx("input",{type:"text",required:!0,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:s.name,onChange:d=>o({...s,name:d.target.value}),placeholder:n("printers.modal.myPrinter")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.ipAddress")}),a.jsx("input",{type:"text",required:!0,pattern:"(\\d{1,3}(\\.\\d{1,3}){3}|[a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?(\\.[a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?)*)",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:s.ip_address,onChange:d=>o({...s,ip_address:d.target.value}),placeholder:"192.168.1.100 or printer.local"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.serialNumber")}),a.jsx("input",{type:"text",disabled:!0,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray cursor-not-allowed",value:t.serial_number}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:n("printers.serialCannotBeChanged")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.accessCode")}),a.jsx("input",{type:"password",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:s.access_code,onChange:d=>o({...s,access_code:d.target.value}),placeholder:n("printers.accessCodePlaceholder")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.model")}),a.jsxs("select",{className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:s.model,onChange:d=>o({...s,model:d.target.value}),children:[a.jsx("option",{value:"",children:n("printers.modal.selectModel")}),a.jsxs("optgroup",{label:"H2 Series",children:[a.jsx("option",{value:"H2C",children:"H2C"}),a.jsx("option",{value:"H2D",children:"H2D"}),a.jsx("option",{value:"H2D Pro",children:"H2D Pro"}),a.jsx("option",{value:"H2S",children:"H2S"})]}),a.jsx("optgroup",{label:"X2 Series",children:a.jsx("option",{value:"X2D",children:"X2D"})}),a.jsxs("optgroup",{label:"X1 Series",children:[a.jsx("option",{value:"X1E",children:"X1E"}),a.jsx("option",{value:"X1C",children:"X1 Carbon"}),a.jsx("option",{value:"X1",children:"X1"})]}),a.jsxs("optgroup",{label:"P Series",children:[a.jsx("option",{value:"P2S",children:"P2S"}),a.jsx("option",{value:"P1S",children:"P1S"}),a.jsx("option",{value:"P1P",children:"P1P"})]}),a.jsxs("optgroup",{label:"A1 Series",children:[a.jsx("option",{value:"A1",children:"A1"}),a.jsx("option",{value:"A1 Mini",children:"A1 Mini"})]})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Location / Group"}),a.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:s.location,onChange:d=>o({...s,location:d.target.value}),placeholder:n("printers.modal.locationPlaceholder")}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:n("printers.locationHelp")})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"checkbox",id:"edit_auto_archive",checked:s.auto_archive,onChange:d=>o({...s,auto_archive:d.target.checked}),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),a.jsx("label",{htmlFor:"edit_auto_archive",className:"text-sm text-bambu-gray",children:n("printers.modal.autoArchiveLabel")})]}),a.jsxs("div",{className:"flex gap-3 pt-4",children:[a.jsx(De,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:n("common.cancel")}),a.jsx(De,{type:"submit",className:"flex-1",disabled:l.isPending,children:l.isPending?n("common.saving"):n("printers.modal.saveChanges")})]})]})]})})})}function U7e(t){const{data:e}=Ye({queryKey:["printerStatus",t],queryFn:()=>me.getPrinterStatus(t),refetchInterval:3e4});return!e?.connected}function B7e({printer:t,plug:e,onPowerOn:n,isPowering:r}){const i=U7e(t.id),{data:s}=Ye({queryKey:["smartPlugStatus",e.id],queryFn:()=>me.getSmartPlugStatus(e.id),refetchInterval:1e4});return i?a.jsxs("div",{className:"flex items-center justify-between px-3 py-2 hover:bg-gray-100 dark:hover:bg-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[a.jsx("span",{className:"text-sm text-gray-900 dark:text-white truncate",children:t.name}),s&&a.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded ${s.state==="ON"?"bg-bambu-green/20 text-bambu-green":"bg-red-500/20 text-red-400"}`,children:s.state||"?"})]}),a.jsxs("button",{onClick:()=>n(e.id),disabled:r||s?.state==="ON",className:`px-2 py-1 text-xs rounded transition-colors flex items-center gap-1 ${s?.state==="ON"?"bg-bambu-green/20 text-bambu-green cursor-default":"bg-bambu-green/20 text-bambu-green hover:bg-bambu-green hover:text-white"}`,children:[a.jsx(Yd,{className:"w-3 h-3"}),r?"...":"On"]})]}):null}function H7e(){const{t}=Ft(),[e,n]=w.useState(!1),[r,i]=w.useState(()=>localStorage.getItem("hideDisconnectedPrinters")==="true"),[s,o]=w.useState(!1),[l,c]=w.useState(null),[d,u]=w.useState(()=>localStorage.getItem("printerSortBy")||"name"),[m,p]=w.useState(()=>localStorage.getItem("printerSortAsc")!=="false"),[f,y]=w.useState(()=>{const Pe=localStorage.getItem("printerCardSize");return Pe?parseInt(Pe,10):2}),v=f===1?"compact":"expanded",[b,g]=w.useState(""),[_,C]=w.useState("all"),[P,N]=w.useState("all"),[A,T]=w.useState(0),[F,k]=w.useState(()=>{try{const Pe=localStorage.getItem("printerCollapsedSections");return Pe?JSON.parse(Pe):{}}catch{return{}}}),D=nn(),{showToast:H}=hn(),{hasPermission:z}=kr(),[Q,L]=w.useState(()=>{const Pe=localStorage.getItem("openEmbeddedCameras");if(Pe)try{const de=JSON.parse(Pe);return new Map(de.map(ye=>[ye.id,ye]))}catch{return new Map}return new Map});w.useEffect(()=>{const Pe=Array.from(Q.values());Pe.length>0?localStorage.setItem("openEmbeddedCameras",JSON.stringify(Pe)):localStorage.removeItem("openEmbeddedCameras")},[Q]);const{data:te,isLoading:ie}=Ye({queryKey:["printers"],queryFn:me.getPrinters}),{data:J}=Ye({queryKey:["settings"],queryFn:me.getSettings}),oe=w.useMemo(()=>{if(J?.drying_presets)try{const Pe=JSON.parse(J.drying_presets);if(typeof Pe=="object"&&Pe!==null&&Object.keys(Pe).length>0)return{...wL,...Pe}}catch{}return wL},[J?.drying_presets]);w.useEffect(()=>{J?.camera_view_mode==="window"&&Q.size>0&&L(new Map)},[J?.camera_view_mode,Q.size]);const{data:ge}=Ye({queryKey:["smart-plugs"],queryFn:me.getSmartPlugs}),{data:re}=Ye({queryKey:["maintenanceOverview"],queryFn:me.getMaintenanceOverview,staleTime:60*1e3}),{data:W}=Ye({queryKey:["spoolman-status"],queryFn:me.getSpoolmanStatus,staleTime:60*1e3}),ne=W?.enabled&&W?.connected,{data:pe}=Ye({queryKey:["spoolman-settings"],queryFn:me.getSpoolmanSettings,enabled:!!ne,staleTime:60*1e3}),xe=pe?.spoolman_sync_mode,{data:Ne}=Ye({queryKey:["unlinked-spools"],queryFn:me.getUnlinkedSpools,enabled:!!ne,staleTime:30*1e3}),q=Ne&&Ne.length>0,{data:Y}=Ye({queryKey:["linked-spools"],queryFn:me.getLinkedSpools,enabled:!!ne,staleTime:30*1e3}),E=Y?.linked,{data:j}=Ye({queryKey:["spool-assignments"],queryFn:()=>me.getAssignments(),enabled:z("inventory:view_assignments"),staleTime:30*1e3}),O=it({mutationFn:({printerId:Pe,amsId:de,trayId:ye})=>me.unassignSpool(Pe,de,ye),onSuccess:()=>{D.invalidateQueries({queryKey:["spool-assignments"]})}}),K=(Pe,de,ye)=>j?.find(Be=>Be.printer_id===Pe&&Be.ams_id===Number(de)&&Be.tray_id===Number(ye)),U=re?.reduce((Pe,de)=>(Pe[de.printer_id]={due_count:de.due_count,warning_count:de.warning_count,total_print_hours:de.total_print_hours},Pe),{})||{},ue=ge?.reduce((Pe,de)=>(de.printer_id&&(Pe[de.printer_id]=de),Pe),{})||{},I=it({mutationFn:me.createPrinter,onSuccess:()=>{D.invalidateQueries({queryKey:["printers"]}),D.invalidateQueries({queryKey:["maintenanceOverview"]}),n(!1)},onError:Pe=>H(Pe.message||t("printers.toast.failedToAdd"),"error")}),G=it({mutationFn:Pe=>me.controlSmartPlug(Pe,"on"),onSuccess:()=>{D.invalidateQueries({queryKey:["smart-plugs"]}),c(null)},onError:()=>{c(null)}}),[X,V]=w.useState(new Set),[ee,se]=w.useState(!1),[be,fe]=w.useState(null),[le,B]=w.useState(!1),R=ee||X.size>0,ae=w.useCallback(Pe=>{V(de=>{const ye=new Set(de);return ye.has(Pe)?ye.delete(Pe):ye.add(Pe),ye})},[]),Se=w.useCallback(()=>{V(new Set),se(!1)},[]);w.useEffect(()=>{const Pe=de=>{de.key==="Escape"&&R&&Se()};return window.addEventListener("keydown",Pe),()=>window.removeEventListener("keydown",Pe)},[R,Se]);const ve=w.useCallback(async Pe=>{B(!0);const ye=Array.from(X).filter(gt=>{const Ut=D.getQueryData(["printerStatus",gt]);if(!Ut?.connected)return!1;switch(Pe){case"stop":return Ut.state==="RUNNING"||Ut.state==="PAUSE";case"pause":return Ut.state==="RUNNING";case"resume":return Ut.state==="PAUSE";case"clearPlate":return!!Ut.awaiting_plate_clear;case"clearHMS":return Ut.hms_errors&&om(Ut.hms_errors).length>0;default:return!1}});if(ye.length===0){H(t("printers.bulk.noneApplicable"),"error"),B(!1),fe(null);return}const Be={stop:me.stopPrint,pause:me.pausePrint,resume:me.resumePrint,clearPlate:me.clearPlate,clearHMS:me.clearHMSErrors}[Pe],Qe=await Promise.allSettled(ye.map(gt=>Be(gt))),ht=Qe.filter(gt=>gt.status==="fulfilled").length,xt=Qe.filter(gt=>gt.status==="rejected").length;xt===0?H(t("printers.bulk.success",{action:t(`printers.bulk.actions.${Pe}`),count:ht})):H(t("printers.bulk.partial",{succeeded:ht,failed:xt}),"error"),ye.forEach(gt=>{D.invalidateQueries({queryKey:["printerStatus",gt]})}),B(!1),fe(null)},[X,D,H,t]),Ae=w.useCallback(Pe=>{Pe==="stop"||Pe==="pause"||Pe==="clearPlate"?fe(Pe):ve(Pe)},[ve]),je=()=>{const Pe=!r;i(Pe),localStorage.setItem("hideDisconnectedPrinters",String(Pe))},he=Pe=>{u(Pe),localStorage.setItem("printerSortBy",Pe)},Ce=()=>{const Pe=!m;p(Pe),localStorage.setItem("printerSortAsc",String(Pe))},Fe=()=>{switch(f){case 1:return"grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5";case 2:return"grid-cols-1 md:grid-cols-2 xl:grid-cols-3";case 3:return"grid-cols-1 lg:grid-cols-2";case 4:return"grid-cols-1";default:return"grid-cols-1 md:grid-cols-2 xl:grid-cols-3"}},Me=["S","M","L","XL"];w.useEffect(()=>D.getQueryCache().subscribe(de=>{de.type==="updated"&&Array.isArray(de.query.queryKey)&&de.query.queryKey[0]==="printerStatus"&&T(ye=>ye+1)}),[D]);const Oe=w.useMemo(()=>{if(!te)return[];let Pe=te;if(b.trim()){const de=b.trim().toLowerCase();Pe=Pe.filter(ye=>ye.name.toLowerCase().includes(de)||(ye.model||"").toLowerCase().includes(de)||(ye.location||"").toLowerCase().includes(de)||(ye.serial_number||"").toLowerCase().includes(de))}return P!=="all"&&(Pe=Pe.filter(de=>(de.location||"")===P)),_!=="all"&&(Pe=Pe.filter(de=>{const ye=D.getQueryData(["printerStatus",de.id]);if(!ye?.connected)return _==="offline";const Be=ye.hms_errors?om(ye.hms_errors):[];switch(_){case"printing":return ye.state==="RUNNING";case"paused":return ye.state==="PAUSE";case"finished":return ye.state==="FINISH";case"error":return ye.state==="FAILED"||Be.length>0;case"idle":return ye.state!=="RUNNING"&&ye.state!=="PAUSE"&&ye.state!=="FINISH"&&ye.state!=="FAILED"&&Be.length===0;case"offline":return!1;default:return!0}})),Pe},[te,b,_,P,D,A]),Re=w.useMemo(()=>te?[...new Set(te.map(Pe=>Pe.location||"").filter(Boolean))].sort():[],[te]),$e=w.useMemo(()=>{const Pe=[...Oe];switch(d){case"name":Pe.sort((de,ye)=>de.name.localeCompare(ye.name));break;case"model":Pe.sort((de,ye)=>(de.model||"").localeCompare(ye.model||""));break;case"location":Pe.sort((de,ye)=>{const Be=de.location||"",Qe=ye.location||"";return!Be&&Qe?1:Be&&!Qe?-1:Be.localeCompare(Qe)||de.name.localeCompare(ye.name)});break;case"status":Pe.sort((de,ye)=>{const Be=D.getQueryData(["printerStatus",de.id]),Qe=D.getQueryData(["printerStatus",ye.id]),ht=xt=>xt?.connected?(xt.hms_errors?om(xt.hms_errors):[]).length>0?0:xt.state==="RUNNING"?1:2:3;return ht(Be)-ht(Qe)});break}return m||Pe.reverse(),Pe},[Oe,d,m,D]),Xe=w.useCallback(()=>{V(new Set($e.map(Pe=>Pe.id))),se(!0)},[$e]),tt=w.useCallback(Pe=>{V(de=>{const ye=new Set(de);return $e.forEach(Be=>{const Qe=D.getQueryData(["printerStatus",Be.id]);dK(Qe)===Pe&&ye.add(Be.id)}),ye}),se(!0)},[$e,D]),we=w.useCallback(Pe=>{V(de=>{const ye=new Set(de);return $e.filter(Be=>(Be.location||"")===Pe).forEach(Be=>ye.add(Be.id)),ye}),se(!0)},[$e]),ze=w.useCallback(Pe=>{V(de=>{const ye=new Set(de);return $e.filter(Be=>(Be.model||"Unknown")===Pe).forEach(Be=>ye.add(Be.id)),ye}),se(!0)},[$e]),ce=w.useCallback(Pe=>{k(de=>{const ye={...de,[Pe]:!de[Pe]};try{localStorage.setItem("printerCollapsedSections",JSON.stringify(ye))}catch{}return ye})},[]),qe=w.useMemo(()=>{if(d==="name")return null;const Pe={};return d==="location"?$e.forEach(de=>{const ye=de.location||"Ungrouped";Pe[ye]||(Pe[ye]=[]),Pe[ye].push(de)}):d==="model"?$e.forEach(de=>{const ye=de.model||"Unknown";Pe[ye]||(Pe[ye]=[]),Pe[ye].push(de)}):d==="status"&&$e.forEach(de=>{const ye=D.getQueryData(["printerStatus",de.id]),Be=dK(ye);Pe[Be]||(Pe[Be]=[]),Pe[Be].push(de)}),Pe},[d,$e,D,A]);return a.jsxs("div",{className:"p-4 md:p-8",children:[a.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-6",children:[a.jsxs("div",{children:[a.jsx("h1",{className:"text-2xl font-bold text-white",children:t("printers.title")}),a.jsx(R7e,{printers:te}),te&&te.length>0&&a.jsxs("div",{className:"relative w-full sm:max-w-sm mt-3",children:[a.jsx(Pr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50"}),a.jsx("input",{type:"search",name:"printer-search",autoComplete:"off","data-1p-ignore":!0,"data-lpignore":"true",value:b,onChange:Pe=>g(Pe.target.value),placeholder:t("printers.search"),"aria-label":t("printers.search"),className:"w-full pl-10 pr-8 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green"}),b&&a.jsx("button",{type:"button","aria-label":t("common.clear"),onClick:()=>g(""),className:"absolute right-3 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white",children:a.jsx(Bt,{className:"w-4 h-4"})})]})]}),a.jsxs("div",{className:"flex items-center gap-2 sm:gap-3 flex-wrap",children:[a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsxs("select",{value:d,onChange:Pe=>he(Pe.target.value),className:"text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg px-2 py-1.5 text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"name",children:t("printers.sort.name")}),a.jsx("option",{value:"status",children:t("printers.sort.status")}),a.jsx("option",{value:"model",children:t("printers.sort.model")}),a.jsx("option",{value:"location",children:t("printers.sort.location")})]}),a.jsx("button",{onClick:Ce,className:"p-1.5 rounded-lg hover:bg-bambu-dark-tertiary transition-colors",title:t(m?"printers.sort.descending":"printers.sort.ascending"),children:m?a.jsx(fp,{className:"w-4 h-4 text-bambu-gray"}):a.jsx(cg,{className:"w-4 h-4 text-bambu-gray"})})]}),te&&te.length>0&&a.jsxs("select",{value:_,onChange:Pe=>C(Pe.target.value),className:"text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg px-2 py-1.5 text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"all",children:t("printers.filter.allStatuses")}),a.jsx("option",{value:"printing",children:t("printers.status.printing")}),a.jsx("option",{value:"paused",children:t("printers.status.paused")}),a.jsx("option",{value:"idle",children:t("printers.status.idle")}),a.jsx("option",{value:"finished",children:t("printers.status.finished")}),a.jsx("option",{value:"error",children:t("printers.status.error")}),a.jsx("option",{value:"offline",children:t("printers.status.offline")})]}),te&&te.length>0&&Re.length>0&&a.jsxs("select",{value:P,onChange:Pe=>N(Pe.target.value),className:"text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg px-2 py-1.5 text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"all",children:t("printers.filter.allLocations")}),Re.map(Pe=>a.jsx("option",{value:Pe,children:Pe},Pe))]}),a.jsx("div",{className:"flex items-center bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:Me.map((Pe,de)=>{const ye=de+1,Be=f===ye;return a.jsx("button",{onClick:()=>{y(ye),localStorage.setItem("printerCardSize",String(ye))},className:`px-2 py-1.5 text-xs font-medium transition-colors ${de===0?"rounded-l-lg":""} ${de===Me.length-1?"rounded-r-lg":""} ${Be?"bg-bambu-green text-white":"text-bambu-gray hover:bg-bambu-dark-tertiary hover:text-white"}`,title:t(Pe==="S"?"printers.cardSize.small":Pe==="M"?"printers.cardSize.medium":Pe==="L"?"printers.cardSize.large":"printers.cardSize.extraLarge"),children:Pe},Pe)})}),a.jsx("button",{onClick:()=>{R?Se():se(!0)},className:`p-1.5 rounded-lg transition-colors ${R?"bg-bambu-green text-white":"hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white"}`,title:t("printers.bulk.select"),disabled:!z("printers:control"),children:a.jsx(Ns,{className:"w-4 h-4"})}),a.jsx("div",{className:"w-px h-6 bg-bambu-dark-tertiary"}),a.jsxs("label",{className:"flex items-center gap-2 text-sm text-bambu-gray cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:r,onChange:je,className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),t("printers.hideOffline")]}),r&&Object.keys(ue).length>0&&a.jsxs("div",{className:"relative",children:[a.jsxs("button",{onClick:()=>o(!s),className:"flex items-center gap-1.5 px-3 py-1.5 text-sm bg-white dark:bg-bambu-dark-secondary border border-gray-200 dark:border-bambu-dark-tertiary rounded-lg text-gray-600 dark:text-bambu-gray hover:text-gray-900 dark:hover:text-white hover:border-bambu-green transition-colors",children:[a.jsx(Yd,{className:"w-4 h-4"}),t("printers.powerOn"),a.jsx(On,{className:`w-3 h-3 transition-transform ${s?"rotate-180":""}`})]}),s&&a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>o(!1)}),a.jsxs("div",{className:"absolute right-0 mt-2 w-56 bg-white dark:bg-bambu-dark-secondary border border-gray-200 dark:border-bambu-dark-tertiary rounded-lg shadow-lg z-20 py-1",children:[a.jsx("div",{className:"px-3 py-2 text-xs text-gray-500 dark:text-bambu-gray border-b border-gray-200 dark:border-bambu-dark-tertiary",children:t("printers.offlinePrintersWithPlugs")}),te?.filter(Pe=>ue[Pe.id]).map(Pe=>a.jsx(B7e,{printer:Pe,plug:ue[Pe.id],onPowerOn:de=>{c(de),G.mutate(de)},isPowering:l===ue[Pe.id]?.id},Pe.id)),te?.filter(Pe=>ue[Pe.id]).length===0&&a.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:"No printers with smart plugs"})]})]})]}),a.jsxs(De,{onClick:()=>n(!0),disabled:!z("printers:create"),title:z("printers:create")?void 0:t("printers.permission.noAdd"),children:[a.jsx(sr,{className:"w-4 h-4"}),t("printers.addPrinter")]})]})]}),ie?a.jsx("div",{className:"text-center py-12 text-bambu-gray",children:t("common.loading")}):te?.length===0?a.jsx(Tt,{children:a.jsxs(Mt,{className:"text-center py-12",children:[a.jsx("p",{className:"text-bambu-gray mb-4",children:t("printers.noPrintersConfigured")}),a.jsxs(De,{onClick:()=>n(!0),disabled:!z("printers:create"),title:z("printers:create")?void 0:t("printers.permission.noAdd"),children:[a.jsx(sr,{className:"w-4 h-4"}),t("printers.addPrinter")]})]})}):$e.length===0&&(b.trim()||_!=="all"||P!=="all")?a.jsx(Tt,{children:a.jsx(Mt,{className:"text-center py-12",children:a.jsx("p",{className:"text-bambu-gray",children:t("printers.noSearchResults")})})}):qe?a.jsx("div",{className:"space-y-6",children:(()=>{const Pe=d==="status"?L7e.filter(de=>qe[de]?.length>0):Object.keys(qe);return m?Pe:[...Pe].reverse()})().map(Pe=>{const de=qe[Pe],ye=`${d}:${Pe}`,Be=!F[ye],Qe=d==="status"&&cK[Pe]?.dot||"bg-bambu-green",ht=d==="status"?t(cK[Pe]?.labelKey||Pe):Pe;return a.jsx(Sz,{open:Be,onToggle:()=>ce(ye),summaryClassName:"py-1",summary:a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx("span",{className:`w-2 h-2 rounded-full ${Qe}`}),ht,a.jsxs("span",{className:"text-sm font-normal text-bambu-gray",children:["(",de.length,")"]}),R&&a.jsx("button",{onClick:xt=>{xt.stopPropagation(),d==="location"?we(Pe==="Ungrouped"?"":Pe):d==="status"?tt(Pe):d==="model"&&ze(Pe)},className:"text-xs text-bambu-green hover:text-bambu-green-light transition-colors ml-1",children:t("printers.bulk.selectAll")})]}),children:a.jsx("div",{className:`grid gap-4 ${f>=3?"gap-6":""} ${Fe()}`,children:de.map(xt=>a.jsx(mK,{printer:xt,hideIfDisconnected:r,maintenanceInfo:U[xt.id],viewMode:v,cardSize:f,amsThresholds:J?{humidityGood:Number(J.ams_humidity_good)||40,humidityFair:Number(J.ams_humidity_fair)||60,tempGood:Number(J.ams_temp_good)||28,tempFair:Number(J.ams_temp_fair)||35}:void 0,spoolmanEnabled:ne,hasUnlinkedSpools:q,linkedSpools:E,spoolmanUrl:W?.url,spoolmanSyncMode:xe,onGetAssignment:K,onUnassignSpool:(gt,Ut,Wt)=>O.mutate({printerId:gt,amsId:Ut,trayId:Wt}),timeFormat:J?.time_format||"system",cameraViewMode:J?.camera_view_mode||"window",onOpenEmbeddedCamera:(gt,Ut)=>L(Wt=>new Map(Wt).set(gt,{id:gt,name:Ut})),checkPrinterFirmware:J?.check_printer_firmware!==!1,dryingPresets:oe,requirePlateClear:J?.require_plate_clear===!0,selectionMode:R,isSelected:X.has(xt.id),onToggleSelect:ae},xt.id))})},Pe)})}):a.jsx("div",{className:`grid gap-4 ${f>=3?"gap-6":""} ${Fe()}`,children:$e.map(Pe=>a.jsx(mK,{printer:Pe,hideIfDisconnected:r,maintenanceInfo:U[Pe.id],viewMode:v,cardSize:f,spoolmanEnabled:ne,hasUnlinkedSpools:q,linkedSpools:E,spoolmanUrl:W?.url,spoolmanSyncMode:xe,onGetAssignment:K,onUnassignSpool:(de,ye,Be)=>O.mutate({printerId:de,amsId:ye,trayId:Be}),amsThresholds:J?{humidityGood:Number(J.ams_humidity_good)||40,humidityFair:Number(J.ams_humidity_fair)||60,tempGood:Number(J.ams_temp_good)||28,tempFair:Number(J.ams_temp_fair)||35}:void 0,timeFormat:J?.time_format||"system",cameraViewMode:J?.camera_view_mode||"window",onOpenEmbeddedCamera:(de,ye)=>L(Be=>new Map(Be).set(de,{id:de,name:ye})),checkPrinterFirmware:J?.check_printer_firmware!==!1,dryingPresets:oe,requirePlateClear:J?.require_plate_clear===!0,selectionMode:R,isSelected:X.has(Pe.id),onToggleSelect:ae},Pe.id))}),e&&a.jsx(O7e,{onClose:()=>n(!1),onAdd:Pe=>I.mutate(Pe),existingSerials:te?.map(Pe=>Pe.serial_number)||[]}),R&&te&&a.jsx(Gye,{selectedIds:X,printers:te,onClose:Se,onSelectAll:Xe,onSelectByLocation:we,onSelectByState:tt,onAction:Ae,actionPending:le}),be==="stop"&&a.jsx(yn,{title:t("printers.bulk.confirm.stopTitle",{count:X.size}),message:t("printers.bulk.confirm.stopMessage",{count:X.size}),confirmText:t("printers.bulk.confirm.stopButton"),variant:"danger",isLoading:le,onConfirm:()=>ve("stop"),onCancel:()=>fe(null)}),be==="pause"&&a.jsx(yn,{title:t("printers.bulk.confirm.pauseTitle",{count:X.size}),message:t("printers.bulk.confirm.pauseMessage",{count:X.size}),confirmText:t("printers.bulk.confirm.pauseButton"),isLoading:le,onConfirm:()=>ve("pause"),onCancel:()=>fe(null)}),be==="clearPlate"&&a.jsx(yn,{title:t("printers.bulk.confirm.clearPlateTitle",{count:X.size}),message:t("printers.bulk.confirm.clearPlateMessage",{count:X.size}),confirmText:t("printers.bulk.confirm.clearPlateButton"),isLoading:le,onConfirm:()=>ve("clearPlate"),onCancel:()=>fe(null)}),Array.from(Q.values()).map((Pe,de)=>a.jsx(WMe,{printerId:Pe.id,printerName:Pe.name,viewerIndex:de,onClose:()=>L(ye=>{const Be=new Map(ye);return Be.delete(Pe.id),Be})},Pe.id))]})}function q7e(){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 qf(t,e="bambu_studio"){let n;const r=encodeURIComponent(t);e==="orcaslicer"?n=`orcaslicer://open?file=${r}`:q7e()==="macos"?n=`bambustudioopen://${r}`:n=`bambustudio://open?file=${r}`;const i=document.createElement("a");i.href=n,i.style.display="none",document.body.appendChild(i),i.click(),document.body.removeChild(i)}const hK=768;function rie(){const[t,e]=w.useState(()=>typeof window<"u"?window.innerWidth{const n=window.matchMedia(`(max-width: ${hK-1}px)`),r=i=>{e(i.matches)};return e(n.matches),n.addEventListener("change",r),()=>n.removeEventListener("change",r)},[]),t}function $7e({onClose:t,initialFiles:e}){const{t:n}=Ft(),r=nn(),{showToast:i}=hn(),s=w.useRef(null),[o,l]=w.useState(()=>e?.filter(N=>N.name.endsWith(".3mf")).map(N=>({file:N,status:"pending"}))||[]),[c,d]=w.useState(!1),[u,m]=w.useState(null);w.useEffect(()=>{const N=A=>{A.key==="Escape"&&t()};return window.addEventListener("keydown",N),()=>window.removeEventListener("keydown",N)},[t]);const p=it({mutationFn:N=>me.uploadArchivesBulk(N),onSuccess:N=>{m(N),r.invalidateQueries({queryKey:["archives"]}),r.invalidateQueries({queryKey:["archiveStats"]}),l(A=>A.map(T=>{const F=N.results.find(D=>D.filename===T.file.name),k=N.errors.find(D=>D.filename===T.file.name);return F?{...T,status:"success",archiveId:F.id}:k?{...T,status:"error",error:k.error}:T})),N.failed===0?i(`${N.uploaded} file${N.uploaded!==1?"s":""} uploaded`):N.uploaded===0?i(`Failed to upload ${N.failed} file${N.failed!==1?"s":""}`,"error"):i(`${N.uploaded} uploaded, ${N.failed} failed`,"warning")},onError:()=>{l(N=>N.map(A=>({...A,status:"error",error:"Upload failed"}))),i("Upload failed","error")}}),f=w.useCallback(N=>{N.preventDefault(),d(!0)},[]),y=w.useCallback(N=>{N.preventDefault(),d(!1)},[]),v=w.useCallback(N=>{N.preventDefault(),d(!1);const A=Array.from(N.dataTransfer.files).filter(T=>T.name.endsWith(".3mf"));A.length>0&&l(T=>[...T,...A.map(F=>({file:F,status:"pending"}))])},[]),b=w.useCallback(N=>{const A=Array.from(N.target.files||[]).filter(T=>T.name.endsWith(".3mf"));A.length>0&&l(T=>[...T,...A.map(F=>({file:F,status:"pending"}))]),s.current&&(s.current.value="")},[]),g=w.useCallback(N=>{l(A=>A.filter((T,F)=>F!==N))},[]),_=()=>{if(o.length===0)return;const N=o.filter(A=>A.status==="pending");N.length!==0&&(l(A=>A.map(T=>T.status==="pending"?{...T,status:"uploading"}:T)),p.mutate(N.map(A=>A.file)))},C=o.filter(N=>N.status==="pending").length,P=p.isPending;return a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:a.jsx(Tt,{className:"w-full max-w-2xl max-h-[90vh] flex flex-col",children:a.jsxs(Mt,{className:"p-0 flex flex-col h-full",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsx("h2",{className:"text-xl font-semibold text-white",children:n("uploadModal.title")}),a.jsx("button",{onClick:t,className:"text-bambu-gray hover:text-white transition-colors",children:a.jsx(Bt,{className:"w-5 h-5"})})]}),a.jsx("div",{className:"p-4",children:a.jsxs("div",{className:`border-2 border-dashed rounded-lg p-8 text-center transition-colors ${c?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary hover:border-bambu-gray"}`,onDragOver:f,onDragLeave:y,onDrop:v,children:[a.jsx(Oa,{className:"w-12 h-12 mx-auto mb-4 text-bambu-gray"}),a.jsx("p",{className:"text-white mb-2",children:n("uploadModal.dragDrop")}),a.jsx("p",{className:"text-bambu-gray text-sm mb-4",children:n("uploadModal.or")}),a.jsx(De,{variant:"secondary",onClick:()=>s.current?.click(),disabled:P,children:n("uploadModal.browseFiles")}),a.jsx("input",{ref:s,type:"file",accept:".3mf",multiple:!0,className:"hidden",onChange:b})]})}),a.jsx("div",{className:"px-4 pb-4",children:a.jsx("p",{className:"text-xs text-bambu-gray",children:n("uploadModal.extractionInfo")})}),o.length>0&&a.jsx("div",{className:"px-4 pb-4 max-h-60 overflow-y-auto",children:a.jsx("div",{className:"space-y-2",children:o.map((N,A)=>a.jsxs("div",{className:"flex items-center gap-3 p-3 bg-bambu-dark rounded-lg",children:[a.jsx(qP,{className:"w-5 h-5 text-bambu-gray flex-shrink-0"}),a.jsx("span",{className:"flex-1 text-white text-sm truncate",children:N.file.name}),a.jsxs("span",{className:"text-xs text-bambu-gray",children:[(N.file.size/(1024*1024)).toFixed(1)," MB"]}),N.status==="pending"&&a.jsx("button",{onClick:()=>g(A),className:"text-bambu-gray hover:text-red-400 transition-colors",disabled:P,children:a.jsx(Bt,{className:"w-4 h-4"})}),N.status==="uploading"&&a.jsx(ft,{className:"w-4 h-4 text-bambu-green animate-spin"}),N.status==="success"&&a.jsx(yr,{className:"w-4 h-4 text-bambu-green"}),N.status==="error"&&a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-xs text-red-400",children:N.error}),a.jsx(ei,{className:"w-4 h-4 text-red-400"})]})]},`${N.file.name}-${A}`))})}),u&&a.jsx("div",{className:"px-4 pb-4",children:a.jsx("div",{className:"p-3 bg-bambu-dark rounded-lg",children:a.jsxs("p",{className:"text-sm text-white",children:[a.jsx("span",{className:"text-bambu-green",children:u.uploaded})," ",n("uploadModal.uploaded"),u.failed>0&&a.jsxs(a.Fragment,{children:[", ",a.jsx("span",{className:"text-red-400",children:u.failed})," ",n("uploadModal.failed")]})]})})}),a.jsxs("div",{className:"flex gap-3 p-4 border-t border-bambu-dark-tertiary",children:[a.jsx(De,{variant:"secondary",onClick:t,className:"flex-1",children:n(u?"common.close":"common.cancel")}),!u&&a.jsx(De,{onClick:_,disabled:C===0||P,className:"flex-1",children:P?a.jsxs(a.Fragment,{children:[a.jsx(ft,{className:"w-4 h-4 animate-spin"}),n("uploadModal.uploading")]}):a.jsxs(a.Fragment,{children:[a.jsx(Oa,{className:"w-4 h-4"}),n("uploadModal.upload")," ",C>0&&`(${C})`]})})]})]})})})}const V7e=["adhesionFailure","spaghettiDetached","layerShift","cloggedNozzle","filamentRunout","warping","stringing","underExtrusion","powerFailure","userCancelled","other"],G7e=["completed","failed","aborted","printing"];function aie({archive:t,onClose:e,existingTags:n=[]}){const{t:r}=Ft();w.useEffect(()=>{const j=O=>{O.key==="Escape"&&e()};return window.addEventListener("keydown",j),()=>window.removeEventListener("keydown",j)},[e]);const i=nn(),[s,o]=w.useState(t.print_name||""),[l,c]=w.useState(t.printer_id),[d,u]=w.useState(t.project_id??null),[m,p]=w.useState(t.notes||""),[f,y]=w.useState(t.tags||""),[v,b]=w.useState(t.failure_reason||""),[g,_]=w.useState(t.status),[C,P]=w.useState(t.quantity??1),[N,A]=w.useState(t.photos||[]),[T,F]=w.useState(t.external_url||""),[k,D]=w.useState(!1),[H,z]=w.useState(!1),Q=w.useRef(null),L=w.useRef(null),te=w.useRef(null),{data:ie}=Ye({queryKey:["printers"],queryFn:me.getPrinters}),{data:J}=Ye({queryKey:["projects"],queryFn:()=>me.getProjects()}),{data:oe}=Ye({queryKey:["tags"],queryFn:me.getTags,enabled:n.length===0}),ge=n.length>0?n:oe?.map(j=>j.name)||[],re=f.split(",").map(j=>j.trim()).filter(Boolean),W=f.includes(",")?f.substring(f.lastIndexOf(",")+1).trim().toLowerCase():f.trim().toLowerCase(),ne=ge.filter(j=>!re.includes(j)&&(W===""||j.toLowerCase().includes(W))),pe=j=>{let O;if(W&&!ge.includes(W)?O=f.includes(",")?f.substring(0,f.lastIndexOf(",")).split(",").map(K=>K.trim()).filter(Boolean):[]:O=re,!O.includes(j)){const K=[...O,j].join(", ");y(K)}te.current!==null&&clearTimeout(te.current),Q.current?.focus()},xe=j=>{const O=re.filter(K=>K!==j).join(", ");y(O)},Ne=it({mutationFn:j=>me.updateArchive(t.id,j),onSuccess:()=>{i.invalidateQueries({queryKey:["archives"]}),i.invalidateQueries({queryKey:["projects"]}),e()}}),q=async j=>{const O=j.target.files?.[0];if(O){D(!0);try{const K=await me.uploadArchivePhoto(t.id,O);A(K.photos),i.invalidateQueries({queryKey:["archives"]})}catch(K){console.error("Failed to upload photo:",K)}finally{D(!1),L.current&&(L.current.value="")}}},Y=async j=>{try{const O=await me.deleteArchivePhoto(t.id,j);A(O.photos||[]),i.invalidateQueries({queryKey:["archives"]})}catch(O){console.error("Failed to delete photo:",O)}},E=j=>{j.preventDefault();const O={print_name:s||void 0,printer_id:l,project_id:d,notes:m||void 0,tags:f||void 0,quantity:C,external_url:T||null};g!==t.status&&(O.status=g),g==="failed"||g==="aborted"?O.failure_reason=v||void 0:(t.status==="failed"||t.status==="aborted")&&(O.failure_reason=null),Ne.mutate(O)};return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:e,children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary w-full max-w-md max-h-[90vh] flex flex-col",onClick:j=>j.stopPropagation(),children:[a.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[a.jsx("h2",{className:"text-lg font-semibold text-white",children:r("editArchive.title")}),a.jsx("button",{onClick:e,className:"text-bambu-gray hover:text-white transition-colors",children:a.jsx(Bt,{className:"w-5 h-5"})})]}),a.jsxs("form",{onSubmit:E,className:"p-6 space-y-4 overflow-y-auto flex-1",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("editArchive.name")}),a.jsx("input",{type:"text",value:s,onChange:j=>o(j.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",placeholder:r("editArchive.namePlaceholder")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("editArchive.printer")}),a.jsxs("select",{value:l??"",onChange:j=>c(j.target.value?Number(j.target.value):null),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"",children:r("editArchive.noPrinter")}),ie?.map(j=>a.jsx("option",{value:j.id,children:j.name},j.id))]})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[a.jsx(Bs,{className:"w-4 h-4 inline mr-1"}),r("editArchive.project")]}),a.jsxs("select",{value:d??"",onChange:j=>u(j.target.value?Number(j.target.value):null),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"",children:r("editArchive.noProject")}),J?.map(j=>a.jsx("option",{value:j.id,children:j.name},j.id))]})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[a.jsx(Lge,{className:"w-4 h-4 inline mr-1"}),r("editArchive.itemsPrinted")]}),a.jsx("input",{type:"number",min:1,value:C,onChange:j=>P(Math.max(1,parseInt(j.target.value)||1)),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",placeholder:"1"}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:r("editArchive.itemsPrintedHelp")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("editArchive.notes")}),a.jsx("textarea",{value:m,onChange:j=>p(j.target.value),rows:3,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none resize-none",placeholder:r("editArchive.notesPlaceholder")})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[a.jsx(Sy,{className:"w-4 h-4 inline mr-1"}),r("editArchive.externalLink")]}),a.jsx("input",{type:"url",value:T,onChange:j=>F(j.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",placeholder:"https://printables.com/model/..."}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:r("editArchive.externalLinkHelp")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("editArchive.tags")}),re.length>0&&a.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:re.map(j=>a.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 bg-bambu-dark-tertiary rounded text-sm text-white",children:[a.jsx(xm,{className:"w-3 h-3"}),j,a.jsx("button",{type:"button",onClick:()=>xe(j),className:"ml-0.5 text-bambu-gray hover:text-white",children:a.jsx(Bt,{className:"w-3 h-3"})})]},j))}),a.jsxs("div",{className:"relative",children:[a.jsx("input",{ref:Q,type:"text",value:f,onChange:j=>y(j.target.value),onFocus:()=>{te.current!==null&&clearTimeout(te.current),z(!0)},onBlur:()=>{te.current=window.setTimeout(()=>z(!1),200)},className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",placeholder:re.length>0?r("editArchive.addMoreTags"):r("editArchive.tagsPlaceholder")}),H&&ne.length>0&&a.jsxs("div",{className:"absolute top-full left-0 right-0 mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg z-10 max-h-40 overflow-y-auto",children:[a.jsxs("div",{className:"p-2 text-xs text-bambu-gray border-b border-bambu-dark-tertiary",children:[W?r("editArchive.matchingTags",{query:W}):r("editArchive.existingTags")," ",r("editArchive.clickToAdd")]}),a.jsx("div",{className:"p-2 flex flex-wrap gap-1.5",children:ne.map(j=>a.jsx("button",{type:"button",onClick:()=>pe(j),className:"px-2 py-0.5 bg-bambu-dark-tertiary hover:bg-bambu-green/20 rounded text-sm text-bambu-gray hover:text-white transition-colors",children:j},j))})]})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("editArchive.status")}),a.jsx("select",{value:g,onChange:j=>{_(j.target.value),j.target.value==="completed"&&b("")},className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:G7e.map(j=>a.jsx("option",{value:j,children:r(`editArchive.statuses.${j}`)},j))})]}),(g==="failed"||g==="aborted")&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("editArchive.failureReason")}),a.jsxs("select",{value:v,onChange:j=>b(j.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"",children:r("editArchive.selectReason")}),V7e.map(j=>a.jsx("option",{value:r(`editArchive.failureReasons.${j}`),children:r(`editArchive.failureReasons.${j}`)},j))]})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[a.jsx(qx,{className:"w-4 h-4 inline mr-1"}),r("editArchive.photos")]}),a.jsxs("div",{className:"flex flex-wrap gap-2 mb-2",children:[N.map(j=>a.jsxs("div",{className:"relative group",children:[a.jsx("img",{src:me.getArchivePhotoUrl(t.id,j),alt:r("editArchive.printResult"),className:"w-20 h-20 object-cover rounded-lg border border-bambu-dark-tertiary"}),a.jsx("button",{type:"button",onClick:()=>Y(j),className:"absolute -top-1 -right-1 p-1 bg-red-500 rounded-full opacity-0 group-hover:opacity-100 transition-opacity",children:a.jsx(en,{className:"w-3 h-3 text-white"})})]},j)),a.jsxs("label",{className:"w-20 h-20 flex items-center justify-center border-2 border-dashed border-bambu-dark-tertiary rounded-lg cursor-pointer hover:border-bambu-green transition-colors",children:[a.jsx("input",{ref:L,type:"file",accept:"image/jpeg,image/png,image/webp",onChange:q,className:"hidden",disabled:k}),k?a.jsx(ft,{className:"w-6 h-6 text-bambu-gray animate-spin"}):a.jsx(sr,{className:"w-6 h-6 text-bambu-gray"})]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:r("editArchive.photosHelp")})]}),a.jsxs("div",{className:"flex gap-3 pt-2",children:[a.jsx(De,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:r("common.cancel")}),a.jsxs(De,{type:"submit",disabled:Ne.isPending,className:"flex-1",children:[a.jsx(_s,{className:"w-4 h-4"}),Ne.isPending?r("common.saving"):r("common.save")]})]})]})]})})}function iie({x:t,y:e,items:n,onClose:r}){const i=w.useRef(null),[s,o]=w.useState(null),l=w.useRef(null),[c,d]=w.useState({x:t,y:e,visible:!1}),[u,m]=w.useState(!1),[p,f]=w.useState({});w.useEffect(()=>{const b=C=>{i.current&&!i.current.contains(C.target)&&r()},g=C=>{C.key==="Escape"&&r()},_=()=>{r()};return document.addEventListener("mousedown",b),document.addEventListener("keydown",g),document.addEventListener("scroll",_,!0),()=>{document.removeEventListener("mousedown",b),document.removeEventListener("keydown",g),document.removeEventListener("scroll",_,!0),l.current&&clearTimeout(l.current)}},[r]),w.useLayoutEffect(()=>{if(i.current){i.current.style.visibility="hidden",i.current.style.display="block";const b=i.current.getBoundingClientRect(),g=window.innerWidth,_=window.innerHeight,C=8;let P=t,N=e;t+b.width>g-C&&(P=Math.max(C,g-b.width-C)),P_-C&&(N=Math.max(C,_-b.height-C)),NA),d({x:P,y:N,visible:!0})}},[t,e]);const y=(b,g)=>{l.current&&(clearTimeout(l.current),l.current=null);const _=g.getBoundingClientRect(),C=window.innerHeight,P=300,T=C-_.top-8P;f(F=>({...F,[b]:T?"bottom":"top"})),o(b)},v=()=>{l.current=window.setTimeout(()=>{o(null)},150)};return a.jsx("div",{ref:i,className:"fixed z-50 min-w-[180px] max-w-[280px] bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl py-1",style:{left:c.x,top:c.y,visibility:c.visible?"visible":"hidden"},children:n.map((b,g)=>{if(b.divider)return a.jsx("div",{className:"my-1 border-t border-bambu-dark-tertiary"},g);const _=b.submenu&&b.submenu.length>0;return a.jsxs("div",{className:"relative",onMouseEnter:C=>_&&y(g,C.currentTarget),onMouseLeave:()=>_&&v(),children:[a.jsxs("button",{onMouseEnter:C=>_&&y(g,C.currentTarget.parentElement),onClick:()=>{_?o(s===g?null:g):b.disabled||(b.onClick(),r())},disabled:b.disabled,title:b.title,className:`w-full flex items-center gap-2 px-3 py-2 text-sm text-left transition-colors ${b.disabled?"text-bambu-gray cursor-not-allowed":b.danger?"text-red-400 hover:bg-red-400/10":"text-white hover:bg-bambu-dark-tertiary"} ${_&&s===g?"bg-bambu-dark-tertiary":""}`,children:[b.icon&&a.jsx("span",{className:"w-4 h-4 flex-shrink-0 flex items-center justify-center",children:b.icon}),a.jsx("span",{className:"flex-1",children:b.label}),_&&a.jsx(ti,{className:"w-4 h-4 text-bambu-gray"})]}),_&&s===g&&a.jsx("div",{className:`absolute min-w-[160px] bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl py-1 overflow-hidden max-h-[300px] overflow-y-auto z-[60] ${u?"right-full mr-1":"left-full ml-1"} ${p[g]==="bottom"?"bottom-0":"top-0"}`,onMouseEnter:()=>{l.current&&(clearTimeout(l.current),l.current=null)},onMouseLeave:()=>v(),children:b.submenu.map((C,P)=>a.jsxs("button",{onClick:()=>{C.disabled||(C.onClick(),r())},disabled:C.disabled,className:`w-full flex items-center gap-2 px-3 py-2 text-sm text-left transition-colors ${C.disabled?"text-bambu-gray cursor-not-allowed":C.danger?"text-red-400 hover:bg-red-400/10":"text-white hover:bg-bambu-dark-tertiary"}`,children:[C.icon&&a.jsx("span",{className:"w-4 h-4 flex-shrink-0 flex items-center justify-center",children:C.icon}),C.label]},P))})]},g)})})}function W7e({selectedIds:t,existingTags:e,onClose:n}){const r=nn(),{showToast:i}=hn(),[s,o]=w.useState(""),[l,c]=w.useState(new Set),[d,u]=w.useState("add");w.useEffect(()=>{const v=b=>{b.key==="Escape"&&n()};return window.addEventListener("keydown",v),()=>window.removeEventListener("keydown",v)},[n]);const m=it({mutationFn:async()=>{const v=Array.from(l);let b=0;for(const g of t)try{const _=await me.getArchive(g),C=_.tags?_.tags.split(",").map(N=>N.trim()).filter(Boolean):[];let P;d==="add"?P=[...new Set([...C,...v])]:P=C.filter(N=>!l.has(N)),await me.updateArchive(g,{tags:P.join(", ")}),b++}catch(_){throw console.error(`Failed to update archive ${g}:`,_),new Error(`Failed on archive ${g}: ${_ instanceof Error?_.message:"Unknown error"}`)}return{count:b,mode:d,tags:v}},onSuccess:({count:v,mode:b,tags:g})=>{r.invalidateQueries({queryKey:["archives"]}),i(`${b==="add"?"Added":"Removed"} ${g.length} tag${g.length!==1?"s":""} ${b==="add"?"to":"from"} ${v} archive${v!==1?"s":""}`),n()},onError:v=>{i(v.message||"Failed to update tags","error")}}),p=v=>{c(b=>{const g=new Set(b);return g.has(v)?g.delete(v):g.add(v),g})},f=()=>{s.trim()&&!l.has(s.trim())&&(c(v=>new Set([...v,s.trim()])),o(""))},y=v=>{v.key==="Enter"&&(v.preventDefault(),f())};return a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:a.jsx(Tt,{className:"w-full max-w-md",children:a.jsxs(Mt,{className:"p-0",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(xm,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-xl font-semibold text-white",children:d==="add"?"Add Tags":"Remove Tags"})]}),a.jsx("button",{onClick:n,className:"text-bambu-gray hover:text-white transition-colors",children:a.jsx(Bt,{className:"w-5 h-5"})})]}),a.jsxs("div",{className:"p-4 space-y-4",children:[a.jsxs("p",{className:"text-sm text-bambu-gray",children:[d==="add"?"Add":"Remove"," tags for ",t.length," selected archive",t.length!==1?"s":""]}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx(De,{size:"sm",variant:d==="add"?"primary":"secondary",onClick:()=>u("add"),children:"Add Tags"}),a.jsx(De,{size:"sm",variant:d==="remove"?"primary":"secondary",onClick:()=>u("remove"),children:"Remove Tags"})]}),d==="add"&&a.jsxs("div",{className:"flex gap-2",children:[a.jsx("input",{type:"text",placeholder:"Enter new tag...",className:"flex-1 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",value:s,onChange:v=>o(v.target.value),onKeyDown:y}),a.jsx(De,{size:"sm",variant:"secondary",onClick:f,disabled:!s.trim(),children:a.jsx(sr,{className:"w-4 h-4"})})]}),e.length>0&&a.jsxs("div",{children:[a.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:"Existing tags:"}),a.jsx("div",{className:"flex flex-wrap gap-2",children:e.map(v=>a.jsx("button",{onClick:()=>p(v),className:`px-2 py-1 rounded text-sm transition-colors ${l.has(v)?"bg-bambu-green text-white":"bg-bambu-dark-tertiary text-bambu-gray-light hover:bg-bambu-dark"}`,children:v},v))})]}),l.size>0&&a.jsxs("div",{children:[a.jsxs("p",{className:"text-xs text-bambu-gray mb-2",children:["Tags to ",d==="add"?"add":"remove",":"]}),a.jsx("div",{className:"flex flex-wrap gap-2",children:Array.from(l).map(v=>a.jsxs("span",{className:`px-2 py-1 rounded text-sm flex items-center gap-1 ${d==="add"?"bg-green-500/20 text-green-400":"bg-red-500/20 text-red-400"}`,children:[v,a.jsx("button",{onClick:()=>p(v),className:"hover:opacity-70",children:a.jsx(Bt,{className:"w-3 h-3"})})]},v))})]})]}),a.jsxs("div",{className:"flex gap-3 p-4 border-t border-bambu-dark-tertiary",children:[a.jsx(De,{variant:"secondary",onClick:n,className:"flex-1",children:"Cancel"}),a.jsx(De,{onClick:()=>m.mutate(),disabled:l.size===0||m.isPending,className:"flex-1",children:m.isPending?a.jsxs(a.Fragment,{children:[a.jsx(ft,{className:"w-4 h-4 animate-spin"}),"Processing..."]}):a.jsxs(a.Fragment,{children:[a.jsx(xm,{className:"w-4 h-4"}),d==="add"?"Add Tags":"Remove Tags"]})})]})]})})})}function K7e({selectedIds:t,onClose:e}){const n=nn(),{showToast:r}=hn(),{data:i,isLoading:s}=Ye({queryKey:["projects"],queryFn:()=>me.getProjects()});w.useEffect(()=>{const u=m=>{m.key==="Escape"&&e()};return window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)},[e]);const o=()=>{n.invalidateQueries({queryKey:["archives"]}),n.invalidateQueries({queryKey:["projects"]}),n.invalidateQueries({queryKey:["project"]}),n.invalidateQueries({queryKey:["project-archives"]})},l=it({mutationFn:async u=>(await me.addArchivesToProject(u,t),u),onSuccess:u=>{const m=i?.find(p=>p.id===u);o(),r(`Added ${t.length} archive${t.length!==1?"s":""} to "${m?.name}"`),e()},onError:()=>{r("Failed to assign project","error")}}),c=it({mutationFn:async()=>{for(const u of t)await me.updateArchive(u,{project_id:null});return t.length},onSuccess:u=>{o(),r(`Removed ${u} archive${u!==1?"s":""} from project`),e()},onError:()=>{r("Failed to remove from project","error")}}),d=l.isPending||c.isPending;return a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:a.jsx(Tt,{className:"w-full max-w-md max-h-[80vh] flex flex-col",children:a.jsxs(Mt,{className:"p-0 flex flex-col min-h-0",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary shrink-0",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Bs,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-xl font-semibold text-white",children:"Assign to Project"})]}),a.jsx("button",{onClick:e,className:"text-bambu-gray hover:text-white transition-colors",disabled:d,children:a.jsx(Bt,{className:"w-5 h-5"})})]}),a.jsxs("div",{className:"p-4 space-y-3 overflow-y-auto min-h-0",children:[a.jsxs("p",{className:"text-sm text-bambu-gray",children:["Assign ",t.length," selected archive",t.length!==1?"s":""," to a project"]}),s?a.jsx("div",{className:"flex items-center justify-center py-8",children:a.jsx(ft,{className:"w-6 h-6 animate-spin text-bambu-gray"})}):a.jsxs("div",{className:"space-y-2",children:[a.jsxs("button",{onClick:()=>c.mutate(),disabled:d,className:"w-full flex items-center gap-3 p-3 rounded-lg bg-bambu-dark hover:bg-bambu-dark-tertiary border border-bambu-dark-tertiary transition-colors text-left disabled:opacity-50",children:[a.jsx("div",{className:"w-8 h-8 rounded-full bg-red-500/20 flex items-center justify-center shrink-0",children:a.jsx(Ma,{className:"w-4 h-4 text-red-400"})}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:"text-white font-medium",children:"Remove from project"}),a.jsx("p",{className:"text-sm text-bambu-gray truncate",children:"Clear project assignment"})]}),c.isPending&&a.jsx(ft,{className:"w-4 h-4 animate-spin text-bambu-gray shrink-0"})]}),i&&i.length>0&&a.jsxs("div",{className:"flex items-center gap-2 py-2",children:[a.jsx("div",{className:"flex-1 h-px bg-bambu-dark-tertiary"}),a.jsx("span",{className:"text-xs text-bambu-gray",children:"or assign to"}),a.jsx("div",{className:"flex-1 h-px bg-bambu-dark-tertiary"})]}),i?.map(u=>a.jsxs("button",{onClick:()=>l.mutate(u.id),disabled:d,className:"w-full flex items-center gap-3 p-3 rounded-lg bg-bambu-dark hover:bg-bambu-dark-tertiary border border-bambu-dark-tertiary transition-colors text-left disabled:opacity-50",children:[a.jsx("div",{className:"w-8 h-8 rounded-full flex items-center justify-center shrink-0",style:{backgroundColor:u.color?`${u.color}20`:"rgb(var(--bambu-green) / 0.2)"},children:a.jsx(Bs,{className:"w-4 h-4",style:{color:u.color||"rgb(var(--bambu-green))"}})}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:"text-white font-medium truncate",children:u.name}),a.jsxs("p",{className:"text-sm text-bambu-gray truncate",children:[u.archive_count," archive",u.archive_count!==1?"s":"",u.status&&` • ${u.status}`]})]}),l.isPending&&l.variables===u.id&&a.jsx(ft,{className:"w-4 h-4 animate-spin text-bambu-gray shrink-0"})]},u.id)),(!i||i.length===0)&&a.jsx("p",{className:"text-center text-bambu-gray py-4",children:"No projects yet. Create one from the Projects page."})]})]}),a.jsx("div",{className:"flex gap-3 p-4 border-t border-bambu-dark-tertiary shrink-0",children:a.jsx(De,{variant:"secondary",onClick:e,className:"flex-1",disabled:d,children:"Cancel"})})]})})})}function X7e(t,e){return new Date(t,e+1,0).getDate()}function Y7e(t,e){return new Date(t,e,1).getDay()}const Q7e=["January","February","March","April","May","June","July","August","September","October","November","December"],Z7e=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];function J7e({archives:t,onArchiveClick:e,highlightedArchiveId:n}){const r=new Date,[i,s]=w.useState(r.getMonth()),[o,l]=w.useState(r.getFullYear()),[c,d]=w.useState(null),[u,m]=w.useState(null),p=w.useMemo(()=>{const N=new Map;return t.forEach(A=>{const T=Zn(A.completed_at||A.created_at)||new Date,F=`${T.getFullYear()}-${String(T.getMonth()+1).padStart(2,"0")}-${String(T.getDate()).padStart(2,"0")}`,k=N.get(F)||[];k.push(A),N.set(F,k)}),N},[t]),f=X7e(o,i),y=Y7e(o,i),v=()=>{i===0?(s(11),l(o-1)):s(i-1)},b=()=>{i===11?(s(0),l(o+1)):s(i+1)},g=()=>{s(r.getMonth()),l(r.getFullYear())},_=[];for(let N=0;N{N!==c&&m(null),d(N)};return a.jsxs("div",{className:"flex flex-col lg:flex-row gap-6",children:[a.jsxs("div",{className:"flex-1",children:[a.jsxs("div",{className:"flex items-center justify-between mb-4",children:[a.jsx("button",{onClick:v,className:"p-2 hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:a.jsx(xl,{className:"w-5 h-5 text-bambu-gray"})}),a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white",children:[Q7e[i]," ",o]}),a.jsx("button",{onClick:g,className:"px-2 py-1 text-xs bg-bambu-dark-tertiary hover:bg-bambu-green/20 text-bambu-gray hover:text-white rounded transition-colors",children:"Today"})]}),a.jsx("button",{onClick:b,className:"p-2 hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:a.jsx(ti,{className:"w-5 h-5 text-bambu-gray"})})]}),a.jsx("div",{className:"grid grid-cols-7 gap-1 mb-1",children:Z7e.map(N=>a.jsx("div",{className:"text-center text-xs text-bambu-gray py-2",children:N},N))}),a.jsx("div",{className:"grid grid-cols-7 gap-1",children:_.map((N,A)=>{if(N===null)return a.jsx("div",{className:"aspect-square"},`empty-${A}`);const T=`${o}-${String(i+1).padStart(2,"0")}-${String(N).padStart(2,"0")}`,F=p.get(T)||[],k=F.length>0,D=N===r.getDate()&&i===r.getMonth()&&o===r.getFullYear(),H=T===c,z=F.filter(L=>L.status==="completed").length,Q=F.filter(L=>L.status==="failed").length;return a.jsxs("button",{onClick:()=>P(H?null:T),className:`aspect-square rounded-lg p-1 flex flex-col items-center justify-center transition-colors relative ${H?"bg-bambu-green text-white":D?"bg-bambu-green/20 text-white ring-2 ring-bambu-green":k?"bg-bambu-dark-tertiary hover:bg-bambu-dark-tertiary/70 text-white":"hover:bg-bambu-dark-tertiary/50 text-bambu-gray"}`,children:[a.jsx("span",{className:`text-sm font-medium ${D&&!H?"text-bambu-green":""}`,children:N}),k&&a.jsxs("div",{className:"absolute bottom-1 left-1/2 -translate-x-1/2 flex items-center gap-1",children:[a.jsx("div",{className:`w-2 h-2 rounded-full ${Q>0&&z===0?"bg-red-400":Q>0?"bg-yellow-400":"bg-green-400"}`}),a.jsx("span",{className:"text-xs font-medium",children:F.length})]})]},N)})}),a.jsx("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:a.jsxs("div",{className:"grid grid-cols-3 gap-4 text-center",children:[a.jsxs("div",{children:[a.jsx("div",{className:"text-2xl font-bold text-white",children:t.filter(N=>{const A=Zn(N.completed_at||N.created_at)||new Date;return A.getMonth()===i&&A.getFullYear()===o}).length}),a.jsx("div",{className:"text-xs text-bambu-gray",children:"Prints this month"})]}),a.jsxs("div",{children:[a.jsx("div",{className:"text-2xl font-bold text-green-400",children:t.filter(N=>{const A=Zn(N.completed_at||N.created_at)||new Date;return A.getMonth()===i&&A.getFullYear()===o&&N.status==="completed"}).length}),a.jsx("div",{className:"text-xs text-bambu-gray",children:"Successful"})]}),a.jsxs("div",{children:[a.jsx("div",{className:"text-2xl font-bold text-red-400",children:t.filter(N=>{const A=Zn(N.completed_at||N.created_at)||new Date;return A.getMonth()===i&&A.getFullYear()===o&&N.status==="failed"}).length}),a.jsx("div",{className:"text-xs text-bambu-gray",children:"Failed"})]})]})})]}),a.jsx("div",{className:"lg:w-80 bg-bambu-dark rounded-xl p-4",children:c?a.jsxs(a.Fragment,{children:[a.jsx("h3",{className:"text-sm font-medium text-bambu-gray mb-3",children:new Date(c+"T12:00:00").toLocaleDateString("en-US",{weekday:"long",month:"long",day:"numeric",year:"numeric"})}),C.length>0?a.jsx("div",{className:"calendar-scroll space-y-2 max-h-96 overflow-y-auto",children:C.map(N=>{const A=N.id===u||N.id===n;return a.jsxs("button",{onClick:()=>{m(N.id),e?.(N)},className:`w-full flex items-center gap-3 p-2 rounded-lg transition-colors text-left ${A?"":"hover:bg-bambu-dark-tertiary"}`,style:A?{outline:"4px solid #facc15",outlineOffset:"2px"}:void 0,children:[N.thumbnail_path?a.jsx("img",{src:me.getArchiveThumbnail(N.id),alt:"",className:"w-12 h-12 rounded object-cover"}):a.jsx("div",{className:"w-12 h-12 rounded bg-bambu-dark-tertiary flex items-center justify-center",children:a.jsx("span",{className:"text-xs text-bambu-gray",children:"3MF"})}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("p",{className:"text-sm text-white truncate",children:N.print_name||N.filename}),a.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[a.jsx("span",{className:N.status==="failed"?"text-red-400":"text-green-400",children:N.status==="failed"?"Failed":"Completed"}),N.filament_color&&a.jsx("div",{className:"flex gap-0.5",children:N.filament_color.split(",").map((T,F)=>a.jsx("div",{className:"w-3 h-3 rounded-full border border-black/20",style:{backgroundColor:T}},F))})]})]})]},N.id)})}):a.jsx("p",{className:"text-sm text-bambu-gray",children:"No prints on this day"})]}):a.jsx("div",{className:"text-center py-8",children:a.jsx("p",{className:"text-sm text-bambu-gray",children:"Select a day to see prints"})})})]})}function sie({archiveId:t,archiveName:e,onClose:n}){const r=me.getArchiveQRCodeUrl(t,300);w.useEffect(()=>{const s=o=>{o.key==="Escape"&&n()};return window.addEventListener("keydown",s),()=>window.removeEventListener("keydown",s)},[n]);const i=()=>{const s=document.createElement("a");s.href=r,s.download=`${e}_qrcode.png`,s.click()};return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:n,children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary w-full max-w-sm",onClick:s=>s.stopPropagation(),children:[a.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[a.jsx("h2",{className:"text-lg font-semibold text-white",children:"QR Code"}),a.jsx("button",{onClick:n,className:"text-bambu-gray hover:text-white transition-colors",children:a.jsx(Bt,{className:"w-5 h-5"})})]}),a.jsxs("div",{className:"p-6 flex flex-col items-center",children:[a.jsx("p",{className:"text-sm text-bambu-gray mb-4 text-center truncate max-w-full",children:e}),a.jsx("div",{className:"bg-white p-4 rounded-lg mb-4",children:a.jsx("img",{src:r,alt:"QR Code",className:"w-64 h-64"})}),a.jsx("p",{className:"text-xs text-bambu-gray mb-4 text-center",children:"Scan to open this archive"}),a.jsxs(De,{onClick:i,className:"w-full",children:[a.jsx(ga,{className:"w-4 h-4"}),"Download QR Code"]})]})]})})}function oie({archiveId:t,archiveName:e,photos:n,onClose:r,onDelete:i}){const[s,o]=w.useState(0),[l,c]=w.useState(!1);if(w.useEffect(()=>{const f=y=>{y.key==="Escape"&&r(),y.key==="ArrowLeft"&&o(v=>Math.max(0,v-1)),y.key==="ArrowRight"&&o(v=>Math.min(n.length-1,v+1))};return window.addEventListener("keydown",f),()=>window.removeEventListener("keydown",f)},[r,n.length]),w.useEffect(()=>{s>=n.length&&o(Math.max(0,n.length-1))},[n.length,s]),n.length===0)return r(),null;const d=n[s],u=me.getArchivePhotoUrl(t,d),m=()=>{const f=document.createElement("a");f.href=u,f.download=`${e}_photo_${s+1}.jpg`,f.click()},p=()=>{i&&c(!0)};return a.jsxs("div",{className:"fixed inset-0 bg-black/90 flex items-center justify-center z-50",onClick:r,children:[a.jsxs("div",{className:"relative w-full h-full flex flex-col",onClick:f=>f.stopPropagation(),children:[a.jsxs("div",{className:"flex items-center justify-between px-6 py-4 bg-black/50",children:[a.jsxs("div",{children:[a.jsx("h2",{className:"text-lg font-semibold text-white",children:e}),a.jsxs("p",{className:"text-sm text-bambu-gray",children:["Photo ",s+1," of ",n.length]})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs(De,{variant:"secondary",size:"sm",onClick:m,children:[a.jsx(ga,{className:"w-4 h-4"}),"Download"]}),i&&a.jsx(De,{variant:"secondary",size:"sm",onClick:p,className:"text-red-400 hover:text-red-300",children:a.jsx(en,{className:"w-4 h-4"})}),a.jsx("button",{onClick:r,className:"p-2 text-bambu-gray hover:text-white transition-colors",children:a.jsx(Bt,{className:"w-6 h-6"})})]})]}),a.jsxs("div",{className:"flex-1 min-h-0 flex items-center justify-center p-4 relative overflow-hidden",children:[s>0&&a.jsx("button",{onClick:()=>o(f=>f-1),className:"absolute left-4 z-10 p-3 bg-black/50 hover:bg-black/70 rounded-full transition-colors",children:a.jsx(xl,{className:"w-8 h-8 text-white"})}),a.jsx("img",{src:u,alt:`Photo ${s+1}`,className:"max-w-full max-h-full object-contain rounded-lg",style:{maxHeight:"calc(100vh - 200px)"}}),so(f=>f+1),className:"absolute right-4 z-10 p-3 bg-black/50 hover:bg-black/70 rounded-full transition-colors",children:a.jsx(ti,{className:"w-8 h-8 text-white"})})]}),n.length>1&&a.jsx("div",{className:"flex justify-center gap-2 p-4 bg-black/50",children:n.map((f,y)=>a.jsx("button",{onClick:()=>o(y),className:`w-16 h-16 rounded-lg overflow-hidden border-2 transition-colors ${y===s?"border-bambu-green":"border-transparent hover:border-bambu-gray"}`,children:a.jsx("img",{src:me.getArchivePhotoUrl(t,f),alt:`Thumbnail ${y+1}`,className:"w-full h-full object-cover"})},f))})]}),l&&a.jsx(yn,{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:lie,setPrototypeOf:pK,isFrozen:eGe,getPrototypeOf:tGe,getOwnPropertyDescriptor:nGe}=Object;let{freeze:fo,seal:gc,create:y0}=Object,{apply:SL,construct:_L}=typeof Reflect<"u"&&Reflect;fo||(fo=function(e){return e});gc||(gc=function(e){return e});SL||(SL=function(e,n){for(var r=arguments.length,i=new Array(r>2?r-2:0),s=2;s1?n-1:0),i=1;i1?n-1:0),i=1;i2&&arguments[2]!==void 0?arguments[2]:nN;pK&&pK(t,null);let r=e.length;for(;r--;){let i=e[r];if(typeof i=="string"){const s=n(i);s!==i&&(eGe(e)||(e[r]=s),i=s)}t[i]=!0}return t}function lGe(t){for(let e=0;e/gm),hGe=gc(/\$\{[\w\W]*/gm),pGe=gc(/^data-[\-\w.\u00B7-\uFFFF]+$/),fGe=gc(/^aria-[\-\w]+$/),cie=gc(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),gGe=gc(/^(?:\w+script|data):/i),bGe=gc(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),die=gc(/^html$/i),xGe=gc(/^[a-z][.\w]*(-[.\w]+)+$/i);var vK=Object.freeze({__proto__:null,ARIA_ATTR:fGe,ATTR_WHITESPACE:bGe,CUSTOM_ELEMENT:xGe,DATA_ATTR:pGe,DOCTYPE_NAME:die,ERB_EXPR:mGe,IS_ALLOWED_URI:cie,IS_SCRIPT_OR_DATA:gGe,MUSTACHE_EXPR:uGe,TMPLIT_EXPR:hGe});const i0={element:1,text:3,progressingInstruction:7,comment:8,document:9},yGe=function(){return typeof window>"u"?null:window},vGe=function(e,n){if(typeof e!="object"||typeof e.createPolicy!="function")return null;let r=null;const i="data-tt-policy-suffix";n&&n.hasAttribute(i)&&(r=n.getAttribute(i));const s="dompurify"+(r?"#"+r:"");try{return e.createPolicy(s,{createHTML(o){return o},createScriptURL(o){return o}})}catch{return console.warn("TrustedTypes policy "+s+" could not be created."),null}},wK=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function uie(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:yGe();const e=nt=>uie(nt);if(e.version="3.4.0",e.removed=[],!t||!t.document||t.document.nodeType!==i0.document||!t.Element)return e.isSupported=!1,e;let{document:n}=t;const r=n,i=r.currentScript,{DocumentFragment:s,HTMLTemplateElement:o,Node:l,Element:c,NodeFilter:d,NamedNodeMap:u=t.NamedNodeMap||t.MozNamedAttrMap,HTMLFormElement:m,DOMParser:p,trustedTypes:f}=t,y=c.prototype,v=a0(y,"cloneNode"),b=a0(y,"remove"),g=a0(y,"nextSibling"),_=a0(y,"childNodes"),C=a0(y,"parentNode");if(typeof o=="function"){const nt=n.createElement("template");nt.content&&nt.content.ownerDocument&&(n=nt.content.ownerDocument)}let P,N="";const{implementation:A,createNodeIterator:T,createDocumentFragment:F,getElementsByTagName:k}=n,{importNode:D}=r;let H=wK();e.isSupported=typeof lie=="function"&&typeof C=="function"&&A&&A.createHTMLDocument!==void 0;const{MUSTACHE_EXPR:z,ERB_EXPR:Q,TMPLIT_EXPR:L,DATA_ATTR:te,ARIA_ATTR:ie,IS_SCRIPT_OR_DATA:J,ATTR_WHITESPACE:oe,CUSTOM_ELEMENT:ge}=vK;let{IS_ALLOWED_URI:re}=vK,W=null;const ne=ur({},[...gK,...HD,...qD,...$D,...bK]);let pe=null;const xe=ur({},[...xK,...VD,...yK,...gk]);let Ne=Object.seal(y0(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}})),q=null,Y=null;const E=Object.seal(y0(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let j=!0,O=!0,K=!1,U=!0,ue=!1,I=!0,G=!1,X=!1,V=!1,ee=!1,se=!1,be=!1,fe=!0,le=!1;const B="user-content-";let R=!0,ae=!1,Se={},ve=null;const Ae=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 je=null;const he=ur({},["audio","video","img","source","image","track"]);let Ce=null;const Fe=ur({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),Me="http://www.w3.org/1998/Math/MathML",Oe="http://www.w3.org/2000/svg",Re="http://www.w3.org/1999/xhtml";let $e=Re,Xe=!1,tt=null;const we=ur({},[Me,Oe,Re],UD);let ze=ur({},["mi","mo","mn","ms","mtext"]),ce=ur({},["annotation-xml"]);const qe=ur({},["title","style","font","a","script"]);let Pe=null;const de=["application/xhtml+xml","text/html"],ye="text/html";let Be=null,Qe=null;const ht=n.createElement("form"),xt=function(Ie){return Ie instanceof RegExp||Ie instanceof Function},gt=function(){let Ie=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(Qe&&Qe===Ie)){if((!Ie||typeof Ie!="object")&&(Ie={}),Ie=vd(Ie),Pe=de.indexOf(Ie.PARSER_MEDIA_TYPE)===-1?ye:Ie.PARSER_MEDIA_TYPE,Be=Pe==="application/xhtml+xml"?UD:nN,W=Ic(Ie,"ALLOWED_TAGS")?ur({},Ie.ALLOWED_TAGS,Be):ne,pe=Ic(Ie,"ALLOWED_ATTR")?ur({},Ie.ALLOWED_ATTR,Be):xe,tt=Ic(Ie,"ALLOWED_NAMESPACES")?ur({},Ie.ALLOWED_NAMESPACES,UD):we,Ce=Ic(Ie,"ADD_URI_SAFE_ATTR")?ur(vd(Fe),Ie.ADD_URI_SAFE_ATTR,Be):Fe,je=Ic(Ie,"ADD_DATA_URI_TAGS")?ur(vd(he),Ie.ADD_DATA_URI_TAGS,Be):he,ve=Ic(Ie,"FORBID_CONTENTS")?ur({},Ie.FORBID_CONTENTS,Be):Ae,q=Ic(Ie,"FORBID_TAGS")?ur({},Ie.FORBID_TAGS,Be):vd({}),Y=Ic(Ie,"FORBID_ATTR")?ur({},Ie.FORBID_ATTR,Be):vd({}),Se=Ic(Ie,"USE_PROFILES")?Ie.USE_PROFILES:!1,j=Ie.ALLOW_ARIA_ATTR!==!1,O=Ie.ALLOW_DATA_ATTR!==!1,K=Ie.ALLOW_UNKNOWN_PROTOCOLS||!1,U=Ie.ALLOW_SELF_CLOSE_IN_ATTR!==!1,ue=Ie.SAFE_FOR_TEMPLATES||!1,I=Ie.SAFE_FOR_XML!==!1,G=Ie.WHOLE_DOCUMENT||!1,ee=Ie.RETURN_DOM||!1,se=Ie.RETURN_DOM_FRAGMENT||!1,be=Ie.RETURN_TRUSTED_TYPE||!1,V=Ie.FORCE_BODY||!1,fe=Ie.SANITIZE_DOM!==!1,le=Ie.SANITIZE_NAMED_PROPS||!1,R=Ie.KEEP_CONTENT!==!1,ae=Ie.IN_PLACE||!1,re=Ie.ALLOWED_URI_REGEXP||cie,$e=Ie.NAMESPACE||Re,ze=Ie.MATHML_TEXT_INTEGRATION_POINTS||ze,ce=Ie.HTML_INTEGRATION_POINTS||ce,Ne=Ie.CUSTOM_ELEMENT_HANDLING||y0(null),Ie.CUSTOM_ELEMENT_HANDLING&&xt(Ie.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(Ne.tagNameCheck=Ie.CUSTOM_ELEMENT_HANDLING.tagNameCheck),Ie.CUSTOM_ELEMENT_HANDLING&&xt(Ie.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(Ne.attributeNameCheck=Ie.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),Ie.CUSTOM_ELEMENT_HANDLING&&typeof Ie.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&(Ne.allowCustomizedBuiltInElements=Ie.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),ue&&(O=!1),se&&(ee=!0),Se&&(W=ur({},bK),pe=y0(null),Se.html===!0&&(ur(W,gK),ur(pe,xK)),Se.svg===!0&&(ur(W,HD),ur(pe,VD),ur(pe,gk)),Se.svgFilters===!0&&(ur(W,qD),ur(pe,VD),ur(pe,gk)),Se.mathMl===!0&&(ur(W,$D),ur(pe,yK),ur(pe,gk))),E.tagCheck=null,E.attributeCheck=null,Ie.ADD_TAGS&&(typeof Ie.ADD_TAGS=="function"?E.tagCheck=Ie.ADD_TAGS:(W===ne&&(W=vd(W)),ur(W,Ie.ADD_TAGS,Be))),Ie.ADD_ATTR&&(typeof Ie.ADD_ATTR=="function"?E.attributeCheck=Ie.ADD_ATTR:(pe===xe&&(pe=vd(pe)),ur(pe,Ie.ADD_ATTR,Be))),Ie.ADD_URI_SAFE_ATTR&&ur(Ce,Ie.ADD_URI_SAFE_ATTR,Be),Ie.FORBID_CONTENTS&&(ve===Ae&&(ve=vd(ve)),ur(ve,Ie.FORBID_CONTENTS,Be)),Ie.ADD_FORBID_CONTENTS&&(ve===Ae&&(ve=vd(ve)),ur(ve,Ie.ADD_FORBID_CONTENTS,Be)),R&&(W["#text"]=!0),G&&ur(W,["html","head","body"]),W.table&&(ur(W,["tbody"]),delete q.tbody),Ie.TRUSTED_TYPES_POLICY){if(typeof Ie.TRUSTED_TYPES_POLICY.createHTML!="function")throw r0('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof Ie.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw r0('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');P=Ie.TRUSTED_TYPES_POLICY,N=P.createHTML("")}else P===void 0&&(P=vGe(f,i)),P!==null&&typeof N=="string"&&(N=P.createHTML(""));fo&&fo(Ie),Qe=Ie}},Ut=ur({},[...HD,...qD,...cGe]),Wt=ur({},[...$D,...dGe]),Zt=function(Ie){let ot=C(Ie);(!ot||!ot.tagName)&&(ot={namespaceURI:$e,tagName:"template"});const Te=nN(Ie.tagName),Ge=nN(ot.tagName);return tt[Ie.namespaceURI]?Ie.namespaceURI===Oe?ot.namespaceURI===Re?Te==="svg":ot.namespaceURI===Me?Te==="svg"&&(Ge==="annotation-xml"||ze[Ge]):!!Ut[Te]:Ie.namespaceURI===Me?ot.namespaceURI===Re?Te==="math":ot.namespaceURI===Oe?Te==="math"&&ce[Ge]:!!Wt[Te]:Ie.namespaceURI===Re?ot.namespaceURI===Oe&&!ce[Ge]||ot.namespaceURI===Me&&!ze[Ge]?!1:!Wt[Te]&&(qe[Te]||!Ut[Te]):!!(Pe==="application/xhtml+xml"&&tt[Ie.namespaceURI]):!1},Kt=function(Ie){n0(e.removed,{element:Ie});try{C(Ie).removeChild(Ie)}catch{b(Ie)}},Xt=function(Ie,ot){try{n0(e.removed,{attribute:ot.getAttributeNode(Ie),from:ot})}catch{n0(e.removed,{attribute:null,from:ot})}if(ot.removeAttribute(Ie),Ie==="is")if(ee||se)try{Kt(ot)}catch{}else try{ot.setAttribute(Ie,"")}catch{}},ln=function(Ie){let ot=null,Te=null;if(V)Ie=""+Ie;else{const Je=BD(Ie,/^[\r\n\t ]+/);Te=Je&&Je[0]}Pe==="application/xhtml+xml"&&$e===Re&&(Ie=''+Ie+"");const Ge=P?P.createHTML(Ie):Ie;if($e===Re)try{ot=new p().parseFromString(Ge,Pe)}catch{}if(!ot||!ot.documentElement){ot=A.createDocument($e,"template",null);try{ot.documentElement.innerHTML=Xe?N:Ge}catch{}}const Ze=ot.body||ot.documentElement;return Ie&&Te&&Ze.insertBefore(n.createTextNode(Te),Ze.childNodes[0]||null),$e===Re?k.call(ot,G?"html":"body")[0]:G?ot.documentElement:Ze},vn=function(Ie){return T.call(Ie.ownerDocument||Ie,Ie,d.SHOW_ELEMENT|d.SHOW_COMMENT|d.SHOW_TEXT|d.SHOW_PROCESSING_INSTRUCTION|d.SHOW_CDATA_SECTION,null)},Ke=function(Ie){return Ie instanceof m&&(typeof Ie.nodeName!="string"||typeof Ie.textContent!="string"||typeof Ie.removeChild!="function"||!(Ie.attributes instanceof u)||typeof Ie.removeAttribute!="function"||typeof Ie.setAttribute!="function"||typeof Ie.namespaceURI!="string"||typeof Ie.insertBefore!="function"||typeof Ie.hasChildNodes!="function")},at=function(Ie){return typeof l=="function"&&Ie instanceof l};function Lt(nt,Ie,ot){t0(nt,Te=>{Te.call(e,Ie,ot,Qe)})}const Et=function(Ie){let ot=null;if(Lt(H.beforeSanitizeElements,Ie,null),Ke(Ie))return Kt(Ie),!0;const Te=Be(Ie.nodeName);if(Lt(H.uponSanitizeElement,Ie,{tagName:Te,allowedTags:W}),I&&Ie.hasChildNodes()&&!at(Ie.firstElementChild)&&eo(/<[/\w!]/g,Ie.innerHTML)&&eo(/<[/\w!]/g,Ie.textContent)||I&&Ie.namespaceURI===Re&&Te==="style"&&at(Ie.firstElementChild)||Ie.nodeType===i0.progressingInstruction||I&&Ie.nodeType===i0.comment&&eo(/<[/\w]/g,Ie.data))return Kt(Ie),!0;if(q[Te]||!(E.tagCheck instanceof Function&&E.tagCheck(Te))&&!W[Te]){if(!q[Te]&&Le(Te)&&(Ne.tagNameCheck instanceof RegExp&&eo(Ne.tagNameCheck,Te)||Ne.tagNameCheck instanceof Function&&Ne.tagNameCheck(Te)))return!1;if(R&&!ve[Te]){const Ge=C(Ie)||Ie.parentNode,Ze=_(Ie)||Ie.childNodes;if(Ze&&Ge){const Je=Ze.length;for(let We=Je-1;We>=0;--We){const Ue=v(Ze[We],!0);Ue.__removalCount=(Ie.__removalCount||0)+1,Ge.insertBefore(Ue,g(Ie))}}}return Kt(Ie),!0}return Ie instanceof c&&!Zt(Ie)||(Te==="noscript"||Te==="noembed"||Te==="noframes")&&eo(/<\/no(script|embed|frames)/i,Ie.innerHTML)?(Kt(Ie),!0):(ue&&Ie.nodeType===i0.text&&(ot=Ie.textContent,t0([z,Q,L],Ge=>{ot=sx(ot,Ge," ")}),Ie.textContent!==ot&&(n0(e.removed,{element:Ie.cloneNode()}),Ie.textContent=ot)),Lt(H.afterSanitizeElements,Ie,null),!1)},At=function(Ie,ot,Te){if(Y[ot]||fe&&(ot==="id"||ot==="name")&&(Te in n||Te in ht))return!1;if(!(O&&!Y[ot]&&eo(te,ot))){if(!(j&&eo(ie,ot))){if(!(E.attributeCheck instanceof Function&&E.attributeCheck(ot,Ie))){if(!pe[ot]||Y[ot]){if(!(Le(Ie)&&(Ne.tagNameCheck instanceof RegExp&&eo(Ne.tagNameCheck,Ie)||Ne.tagNameCheck instanceof Function&&Ne.tagNameCheck(Ie))&&(Ne.attributeNameCheck instanceof RegExp&&eo(Ne.attributeNameCheck,ot)||Ne.attributeNameCheck instanceof Function&&Ne.attributeNameCheck(ot,Ie))||ot==="is"&&Ne.allowCustomizedBuiltInElements&&(Ne.tagNameCheck instanceof RegExp&&eo(Ne.tagNameCheck,Te)||Ne.tagNameCheck instanceof Function&&Ne.tagNameCheck(Te))))return!1}else if(!Ce[ot]){if(!eo(re,sx(Te,oe,""))){if(!((ot==="src"||ot==="xlink:href"||ot==="href")&&Ie!=="script"&&iGe(Te,"data:")===0&&je[Ie])){if(!(K&&!eo(J,sx(Te,oe,"")))){if(Te)return!1}}}}}}}return!0},Le=function(Ie){return Ie!=="annotation-xml"&&BD(Ie,ge)},mt=function(Ie){Lt(H.beforeSanitizeAttributes,Ie,null);const{attributes:ot}=Ie;if(!ot||Ke(Ie))return;const Te={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:pe,forceKeepAttr:void 0};let Ge=ot.length;for(;Ge--;){const Ze=ot[Ge],{name:Je,namespaceURI:We,value:Ue}=Ze,et=Be(Je),jt=Ue;let yt=Je==="value"?jt:sGe(jt);if(Te.attrName=et,Te.attrValue=yt,Te.keepAttr=!0,Te.forceKeepAttr=void 0,Lt(H.uponSanitizeAttribute,Ie,Te),yt=Te.attrValue,le&&(et==="id"||et==="name")&&(Xt(Je,Ie),yt=B+yt),I&&eo(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,yt)){Xt(Je,Ie);continue}if(et==="attributename"&&BD(yt,"href")){Xt(Je,Ie);continue}if(Te.forceKeepAttr)continue;if(!Te.keepAttr){Xt(Je,Ie);continue}if(!U&&eo(/\/>/i,yt)){Xt(Je,Ie);continue}ue&&t0([z,Q,L],St=>{yt=sx(yt,St," ")});const Ve=Be(Ie.nodeName);if(!At(Ve,et,yt)){Xt(Je,Ie);continue}if(P&&typeof f=="object"&&typeof f.getAttributeType=="function"&&!We)switch(f.getAttributeType(Ve,et)){case"TrustedHTML":{yt=P.createHTML(yt);break}case"TrustedScriptURL":{yt=P.createScriptURL(yt);break}}if(yt!==jt)try{We?Ie.setAttributeNS(We,Je,yt):Ie.setAttribute(Je,yt),Ke(Ie)?Kt(Ie):fK(e.removed)}catch{Xt(Je,Ie)}}Lt(H.afterSanitizeAttributes,Ie,null)},pt=function(Ie){let ot=null;const Te=vn(Ie);for(Lt(H.beforeSanitizeShadowDOM,Ie,null);ot=Te.nextNode();)Lt(H.uponSanitizeShadowNode,ot,null),Et(ot),mt(ot),ot.content instanceof s&&pt(ot.content);Lt(H.afterSanitizeShadowDOM,Ie,null)};return e.sanitize=function(nt){let Ie=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},ot=null,Te=null,Ge=null,Ze=null;if(Xe=!nt,Xe&&(nt=""),typeof nt!="string"&&!at(nt))if(typeof nt.toString=="function"){if(nt=nt.toString(),typeof nt!="string")throw r0("dirty is not a string, aborting")}else throw r0("toString is not a function");if(!e.isSupported)return nt;if(X||gt(Ie),e.removed=[],typeof nt=="string"&&(ae=!1),ae){if(nt.nodeName){const Ue=Be(nt.nodeName);if(!W[Ue]||q[Ue])throw r0("root node is forbidden and cannot be sanitized in-place")}}else if(nt instanceof l)ot=ln(""),Te=ot.ownerDocument.importNode(nt,!0),Te.nodeType===i0.element&&Te.nodeName==="BODY"||Te.nodeName==="HTML"?ot=Te:ot.appendChild(Te);else{if(!ee&&!ue&&!G&&nt.indexOf("<")===-1)return P&&be?P.createHTML(nt):nt;if(ot=ln(nt),!ot)return ee?null:be?N:""}ot&&V&&Kt(ot.firstChild);const Je=vn(ae?nt:ot);for(;Ge=Je.nextNode();)Et(Ge),mt(Ge),Ge.content instanceof s&&pt(Ge.content);if(ae)return nt;if(ee){if(ue){ot.normalize();let Ue=ot.innerHTML;t0([z,Q,L],et=>{Ue=sx(Ue,et," ")}),ot.innerHTML=Ue}if(se)for(Ze=F.call(ot.ownerDocument);ot.firstChild;)Ze.appendChild(ot.firstChild);else Ze=ot;return(pe.shadowroot||pe.shadowrootmode)&&(Ze=D.call(r,Ze,!0)),Ze}let We=G?ot.outerHTML:ot.innerHTML;return G&&W["!doctype"]&&ot.ownerDocument&&ot.ownerDocument.doctype&&ot.ownerDocument.doctype.name&&eo(die,ot.ownerDocument.doctype.name)&&(We=" `+We),ue&&t0([z,Q,L],Ue=>{We=sx(We,Ue," ")}),P&&be?P.createHTML(We):We},e.setConfig=function(){let nt=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};gt(nt),X=!0},e.clearConfig=function(){Qe=null,X=!1},e.isValidAttribute=function(nt,Ie,ot){Qe||gt({});const Te=Be(nt),Ge=Be(Ie);return At(Te,Ge,ot)},e.addHook=function(nt,Ie){typeof Ie=="function"&&n0(H[nt],Ie)},e.removeHook=function(nt,Ie){if(Ie!==void 0){const ot=rGe(H[nt],Ie);return ot===-1?void 0:aGe(H[nt],ot,1)[0]}return fK(H[nt])},e.removeHooks=function(nt){H[nt]=[]},e.removeAllHooks=function(){H=wK()},e}var mie=uie();function fs(t){this.content=t}fs.prototype={constructor:fs,find:function(t){for(var e=0;e>1}};fs.from=function(t){if(t instanceof fs)return t;var e=[];if(t)for(var n in t)e.push(n,t[n]);return new fs(e)};function hie(t,e,n){for(let r=0;;r++){if(r==t.childCount||r==e.childCount)return t.childCount==e.childCount?null:n;let i=t.child(r),s=e.child(r);if(i==s){n+=i.nodeSize;continue}if(!i.sameMarkup(s))return n;if(i.isText&&i.text!=s.text){for(let o=0;i.text[o]==s.text[o];o++)n++;return n}if(i.content.size||s.content.size){let o=hie(i.content,s.content,n+1);if(o!=null)return o}n+=i.nodeSize}}function pie(t,e,n,r){for(let i=t.childCount,s=e.childCount;;){if(i==0||s==0)return i==s?null:{a:n,b:r};let o=t.child(--i),l=e.child(--s),c=o.nodeSize;if(o==l){n-=c,r-=c;continue}if(!o.sameMarkup(l))return{a:n,b:r};if(o.isText&&o.text!=l.text){let d=0,u=Math.min(o.text.length,l.text.length);for(;de&&r(c,i+l,s||null,o)!==!1&&c.content.size){let u=l+1;c.nodesBetween(Math.max(0,e-u),Math.min(c.content.size,n-u),r,i+u)}l=d}}descendants(e){this.nodesBetween(0,this.size,e)}textBetween(e,n,r,i){let s="",o=!0;return this.nodesBetween(e,n,(l,c)=>{let d=l.isText?l.text.slice(Math.max(e,c)-c,n-c):l.isLeaf?i?typeof i=="function"?i(l):i:l.type.spec.leafText?l.type.spec.leafText(l):"":"";l.isBlock&&(l.isLeaf&&d||l.isTextblock)&&r&&(o?o=!1:s+=r),s+=d},0),s}append(e){if(!e.size)return this;if(!this.size)return e;let n=this.lastChild,r=e.firstChild,i=this.content.slice(),s=0;for(n.isText&&n.sameMarkup(r)&&(i[i.length-1]=n.withText(n.text+r.text),s=1);se)for(let s=0,o=0;oe&&((on)&&(l.isText?l=l.cut(Math.max(0,e-o),Math.min(l.text.length,n-o)):l=l.cut(Math.max(0,e-o-1),Math.min(l.content.size,n-o-1))),r.push(l),i+=l.nodeSize),o=c}return new Vt(r,i)}cutByIndex(e,n){return e==n?Vt.empty:e==0&&n==this.content.length?this:new Vt(this.content.slice(e,n))}replaceChild(e,n){let r=this.content[e];if(r==n)return this;let i=this.content.slice(),s=this.size+n.nodeSize-r.nodeSize;return i[e]=n,new Vt(i,s)}addToStart(e){return new Vt([e].concat(this.content),this.size+e.nodeSize)}addToEnd(e){return new Vt(this.content.concat(e),this.size+e.nodeSize)}eq(e){if(this.content.length!=e.content.length)return!1;for(let n=0;nthis.size||e<0)throw new RangeError(`Position ${e} outside of fragment (${this})`);for(let n=0,r=0;;n++){let i=this.child(n),s=r+i.nodeSize;if(s>=e)return s==e?bk(n+1,s):bk(n,r);r=s}}toString(){return"<"+this.toStringInner()+">"}toStringInner(){return this.content.join(", ")}toJSON(){return this.content.length?this.content.map(e=>e.toJSON()):null}static fromJSON(e,n){if(!n)return Vt.empty;if(!Array.isArray(n))throw new RangeError("Invalid input for Fragment.fromJSON");return new Vt(n.map(e.nodeFromJSON))}static fromArray(e){if(!e.length)return Vt.empty;let n,r=0;for(let i=0;ithis.type.rank&&(n||(n=e.slice(0,i)),n.push(this),r=!0),n&&n.push(s)}}return n||(n=e.slice()),r||n.push(this),n}removeFromSet(e){for(let n=0;nr.type.rank-i.type.rank),n}};oa.none=[];class HC extends Error{}class an{constructor(e,n,r){this.content=e,this.openStart=n,this.openEnd=r}get size(){return this.content.size-this.openStart-this.openEnd}insertAt(e,n){let r=gie(this.content,e+this.openStart,n);return r&&new an(r,this.openStart,this.openEnd)}removeBetween(e,n){return new an(fie(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 an.empty;let r=n.openStart||0,i=n.openEnd||0;if(typeof r!="number"||typeof i!="number")throw new RangeError("Invalid input for Slice.fromJSON");return new an(Vt.fromJSON(e,n.content),r,i)}static maxOpen(e,n=!0){let r=0,i=0;for(let s=e.firstChild;s&&!s.isLeaf&&(n||!s.type.spec.isolating);s=s.firstChild)r++;for(let s=e.lastChild;s&&!s.isLeaf&&(n||!s.type.spec.isolating);s=s.lastChild)i++;return new an(e,r,i)}}an.empty=new an(Vt.empty,0,0);function fie(t,e,n){let{index:r,offset:i}=t.findIndex(e),s=t.maybeChild(r),{index:o,offset:l}=t.findIndex(n);if(i==e||s.isText){if(l!=n&&!t.child(o).isText)throw new RangeError("Removing non-flat range");return t.cut(0,e).append(t.cut(n))}if(r!=o)throw new RangeError("Removing non-flat range");return t.replaceChild(r,s.copy(fie(s.content,e-i-1,n-i-1)))}function gie(t,e,n,r){let{index:i,offset:s}=t.findIndex(e),o=t.maybeChild(i);if(s==e||o.isText)return r&&!r.canReplace(i,i,n)?null:t.cut(0,e).append(n).append(t.cut(e));let l=gie(o.content,e-s-1,n,o);return l&&t.replaceChild(i,o.copy(l))}function wGe(t,e,n){if(n.openStart>t.depth)throw new HC("Inserted content deeper than insertion position");if(t.depth-n.openStart!=e.depth-n.openEnd)throw new HC("Inconsistent open depths");return bie(t,e,n,0)}function bie(t,e,n,r){let i=t.index(r),s=t.node(r);if(i==e.index(r)&&r=0&&t.isText&&t.sameMarkup(e[n])?e[n]=t.withText(e[n].text+t.text):e.push(t)}function I0(t,e,n,r){let i=(e||t).node(n),s=0,o=e?e.index(n):i.childCount;t&&(s=t.index(n),t.depth>n?s++:t.textOffset&&(tg(t.nodeAfter,r),s++));for(let l=s;li&&NL(t,e,i+1),o=r.depth>i&&NL(n,r,i+1),l=[];return I0(null,t,i,l),s&&o&&e.index(i)==n.index(i)?(xie(s,o),tg(ng(s,yie(t,e,n,r,i+1)),l)):(s&&tg(ng(s,qC(t,e,i+1)),l),I0(e,n,i,l),o&&tg(ng(o,qC(n,r,i+1)),l)),I0(r,null,i,l),new Vt(l)}function qC(t,e,n){let r=[];if(I0(null,t,n,r),t.depth>n){let i=NL(t,e,n+1);tg(ng(i,qC(t,e,n+1)),r)}return I0(e,null,n,r),new Vt(r)}function SGe(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(Vt.from(i));return{start:i.resolveNoCache(t.openStart+n),end:i.resolveNoCache(i.content.size-t.openEnd-n)}}class Fw{constructor(e,n,r){this.pos=e,this.path=n,this.parentOffset=r,this.depth=n.length/3-1}resolveDepth(e){return e==null?this.depth:e<0?this.depth+e:e}get parent(){return this.node(this.depth)}get doc(){return this.node(0)}node(e){return this.path[this.resolveDepth(e)*3]}index(e){return this.path[this.resolveDepth(e)*3+1]}indexAfter(e){return e=this.resolveDepth(e),this.index(e)+(e==this.depth&&!this.textOffset?0:1)}start(e){return e=this.resolveDepth(e),e==0?0:this.path[e*3-1]+1}end(e){return e=this.resolveDepth(e),this.start(e)+this.node(e).content.size}before(e){if(e=this.resolveDepth(e),!e)throw new RangeError("There is no position before the top-level node");return e==this.depth+1?this.pos:this.path[e*3-1]}after(e){if(e=this.resolveDepth(e),!e)throw new RangeError("There is no position after the top-level node");return e==this.depth+1?this.pos:this.path[e*3-1]+this.path[e*3].nodeSize}get textOffset(){return this.pos-this.path[this.path.length-1]}get nodeAfter(){let e=this.parent,n=this.index(this.depth);if(n==e.childCount)return null;let r=this.pos-this.path[this.path.length-1],i=e.child(n);return r?e.child(n).cut(r):i}get nodeBefore(){let e=this.index(this.depth),n=this.pos-this.path[this.path.length-1];return n?this.parent.child(e).cut(0,n):e==0?null:this.parent.child(e-1)}posAtIndex(e,n){n=this.resolveDepth(n);let r=this.path[n*3],i=n==0?0:this.path[n*3-1]+1;for(let s=0;s0;n--)if(this.start(n)<=e&&this.end(n)>=e)return n;return 0}blockRange(e=this,n){if(e.pos=0;r--)if(e.pos<=this.end(r)&&(!n||n(this.node(r))))return new $C(this,e,r);return null}sameParent(e){return this.pos-this.parentOffset==e.pos-e.parentOffset}max(e){return e.pos>this.pos?e:this}min(e){return e.pos=0&&n<=e.content.size))throw new RangeError("Position "+n+" out of range");let r=[],i=0,s=n;for(let o=e;;){let{index:l,offset:c}=o.content.findIndex(s),d=s-c;if(r.push(o,l,i+c),!d||(o=o.child(l),o.isText))break;s=d-1,i+=c+1}return new Fw(n,r,s)}static resolveCached(e,n){let r=SK.get(e);if(r)for(let s=0;se&&this.nodesBetween(e,n,s=>(r.isInSet(s.marks)&&(i=!0),!i)),i}get isBlock(){return this.type.isBlock}get isTextblock(){return this.type.isTextblock}get inlineContent(){return this.type.inlineContent}get isInline(){return this.type.isInline}get isText(){return this.type.isText}get isLeaf(){return this.type.isLeaf}get isAtom(){return this.type.isAtom}toString(){if(this.type.spec.toDebugString)return this.type.spec.toDebugString(this);let e=this.type.name;return this.content.size&&(e+="("+this.content.toStringInner()+")"),vie(this.marks,e)}contentMatchAt(e){let n=this.type.contentMatch.matchFragment(this.content,0,e);if(!n)throw new Error("Called contentMatchAt on a node with invalid content");return n}canReplace(e,n,r=Vt.empty,i=0,s=r.childCount){let o=this.contentMatchAt(e).matchFragment(r,i,s),l=o&&o.matchFragment(this.content,n);if(!l||!l.validEnd)return!1;for(let c=i;cn.type.name)}`);this.content.forEach(n=>n.check())}toJSON(){let e={type:this.type.name};for(let n in this.attrs){e.attrs=this.attrs;break}return this.content.size&&(e.content=this.content.toJSON()),this.marks.length&&(e.marks=this.marks.map(n=>n.toJSON())),e}static fromJSON(e,n){if(!n)throw new RangeError("Invalid input for Node.fromJSON");let r;if(n.marks){if(!Array.isArray(n.marks))throw new RangeError("Invalid mark data for Node.fromJSON");r=n.marks.map(e.markFromJSON)}if(n.type=="text"){if(typeof n.text!="string")throw new RangeError("Invalid text node in JSON");return e.text(n.text,r)}let i=Vt.fromJSON(e,n.content),s=e.nodeType(n.type).create(n.attrs,i,r);return s.type.checkAttrs(s.attrs),s}}Yc.prototype.text=void 0;class VC extends Yc{constructor(e,n,r,i){if(super(e,n,null,i),!r)throw new RangeError("Empty text nodes are not allowed");this.text=r}toString(){return this.type.spec.toDebugString?this.type.spec.toDebugString(this):vie(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 VC(this.type,this.attrs,this.text,e)}withText(e){return e==this.text?this:new VC(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 vie(t,e){for(let n=t.length-1;n>=0;n--)e=t[n].type.name+"("+e+")";return e}class jg{constructor(e){this.validEnd=e,this.next=[],this.wrapCache=[]}static parse(e,n){let r=new CGe(e,n);if(r.next==null)return jg.empty;let i=wie(r);r.next&&r.err("Unexpected trailing text");let s=DGe(EGe(i));return FGe(s,r),s}matchType(e){for(let n=0;nd.createAndFill()));for(let d=0;d=this.next.length)throw new RangeError(`There's no ${e}th edge in this content match`);return this.next[e]}toString(){let e=[];function n(r){e.push(r);for(let i=0;i{let s=i+(r.validEnd?"*":" ")+" ";for(let o=0;o"+e.indexOf(r.next[o].next);return s}).join(` `)}}jg.empty=new jg(!0);class CGe{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 wie(t){let e=[];do e.push(PGe(t));while(t.eat("|"));return e.length==1?e[0]:{type:"choice",exprs:e}}function PGe(t){let e=[];do e.push(TGe(t));while(t.next&&t.next!=")"&&t.next!="|");return e.length==1?e[0]:{type:"seq",exprs:e}}function TGe(t){let e=MGe(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=AGe(t,e);else break;return e}function _K(t){/\D/.test(t.next)&&t.err("Expected number, got '"+t.next+"'");let e=Number(t.next);return t.pos++,e}function AGe(t,e){let n=_K(t),r=n;return t.eat(",")&&(t.next!="}"?r=_K(t):r=-1),t.eat("}")||t.err("Unclosed braced range"),{type:"range",min:n,max:r,expr:e}}function jGe(t,e){let n=t.nodeTypes,r=n[e];if(r)return[r];let i=[];for(let s in n){let o=n[s];o.isInGroup(e)&&i.push(o)}return i.length==0&&t.err("No node type or group '"+e+"' found"),i}function MGe(t){if(t.eat("(")){let e=wie(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=jGe(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 EGe(t){let e=[[]];return i(s(t,0),n()),e;function n(){return e.push([])-1}function r(o,l,c){let d={term:c,to:l};return e[o].push(d),d}function i(o,l){o.forEach(c=>c.to=l)}function s(o,l){if(o.type=="choice")return o.exprs.reduce((c,d)=>c.concat(s(d,l)),[]);if(o.type=="seq")for(let c=0;;c++){let d=s(o.exprs[c],l);if(c==o.exprs.length-1)return d;i(d,l=n())}else if(o.type=="star"){let c=n();return r(l,c),i(s(o.expr,c),c),[r(c)]}else if(o.type=="plus"){let c=n();return i(s(o.expr,l),c),i(s(o.expr,c),c),[r(c)]}else{if(o.type=="opt")return[r(l)].concat(s(o.expr,l));if(o.type=="range"){let c=l;for(let d=0;d{t[o].forEach(({term:l,to:c})=>{if(!l)return;let d;for(let u=0;u{d||i.push([l,d=[]]),d.indexOf(u)==-1&&d.push(u)})})});let s=e[r.join(",")]=new jg(r.indexOf(t.length-1)>-1);for(let o=0;o-1}get whitespace(){return this.spec.whitespace||(this.spec.code?"pre":"normal")}hasRequiredAttrs(){for(let e in this.attrs)if(this.attrs[e].isRequired)return!0;return!1}compatibleContent(e){return this==e||this.contentMatch.compatible(e.contentMatch)}computeAttrs(e){return!e&&this.defaultAttrs?this.defaultAttrs:kie(this.attrs,e)}create(e=null,n,r){if(this.isText)throw new Error("NodeType.create can't construct text nodes");return new Yc(this,this.computeAttrs(e),Vt.from(n),oa.setFrom(r))}createChecked(e=null,n,r){return n=Vt.from(n),this.checkContent(n),new Yc(this,this.computeAttrs(e),n,oa.setFrom(r))}createAndFill(e=null,n,r){if(e=this.computeAttrs(e),n=Vt.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(Vt.empty,!0);return s?new Yc(this,e,n.append(s),oa.setFrom(r)):null}validContent(e){let n=this.contentMatch.matchFragment(e);if(!n||!n.validEnd)return!1;for(let r=0;r-1}allowsMarks(e){if(this.markSet==null)return!0;for(let n=0;nr[s]=new Pie(s,n,o));let i=n.spec.topNode||"doc";if(!r[i])throw new RangeError("Schema is missing its top node type ('"+i+"')");if(!r.text)throw new RangeError("Every schema needs a 'text' type");for(let s in r.text.attrs)throw new RangeError("The text node type should not have attributes");return r}};function RGe(t,e,n){let r=n.split("|");return i=>{let s=i===null?"null":typeof i;if(r.indexOf(s)<0)throw new RangeError(`Expected value of type ${r} for attribute ${e} on type ${t}, got ${s}`)}}class LGe{constructor(e,n,r){this.hasDefault=Object.prototype.hasOwnProperty.call(r,"default"),this.default=r.default,this.validate=typeof r.validate=="string"?RGe(e,n,r.validate):r.validate}get isRequired(){return!this.hasDefault}}class eA{constructor(e,n,r,i){this.name=e,this.rank=n,this.schema=r,this.spec=i,this.attrs=Cie(e,i.attrs),this.excluded=null;let s=_ie(this.attrs);this.instance=s?new oa(this,s):null}create(e=null){return!e&&this.instance?this.instance:new oa(this,kie(this.attrs,e))}static compile(e,n){let r=Object.create(null),i=0;return e.forEach((s,o)=>r[s]=new eA(s,i++,n,o)),r}removeFromSet(e){for(var n=0;n-1}}class Tie{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=fs.from(e.nodes),n.marks=fs.from(e.marks||{}),this.nodes=NK.compile(this.spec.nodes,this),this.marks=eA.compile(this.spec.marks,this);let r=Object.create(null);for(let i in this.nodes){if(i in this.marks)throw new RangeError(i+" can not be both a node and a mark");let s=this.nodes[i],o=s.spec.content||"",l=s.spec.marks;if(s.contentMatch=r[o]||(r[o]=jg.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?CK(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==""?[]:CK(this,o.split(" "))}this.nodeFromJSON=i=>Yc.fromJSON(this,i),this.markFromJSON=i=>oa.fromJSON(this,i),this.topNodeType=this.nodes[this.spec.topNode||"doc"],this.cached.wrappings=Object.create(null)}node(e,n=null,r,i){if(typeof e=="string")e=this.nodeType(e);else if(e instanceof NK){if(e.schema!=this)throw new RangeError("Node type from different schema used ("+e.name+")")}else throw new RangeError("Invalid node type: "+e);return e.createChecked(n,r,i)}text(e,n){let r=this.nodes.text;return new VC(r,r.defaultAttrs,e,oa.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 CK(t,e){let n=[];for(let r=0;r-1)&&n.push(o=c)}if(!o)throw new SyntaxError("Unknown mark type: '"+e[r]+"'")}return n}function OGe(t){return t.tag!=null}function IGe(t){return t.style!=null}let z0=class CL{constructor(e,n){this.schema=e,this.rules=n,this.tags=[],this.styles=[];let r=this.matchedStyles=[];n.forEach(i=>{if(OGe(i))this.tags.push(i);else if(IGe(i)){let s=/[^=]*/.exec(i.style)[0];r.indexOf(s)<0&&r.push(s),this.styles.push(i)}}),this.normalizeLists=!this.tags.some(i=>{if(!/^(ul|ol)\b/.test(i.tag)||!i.node)return!1;let s=e.nodes[i.node];return s.contentMatch.matchType(s)})}parse(e,n={}){let r=new TK(this,n,!1);return r.addAll(e,oa.none,n.from,n.to),r.finish()}parseSlice(e,n={}){let r=new TK(this,n,!0);return r.addAll(e,oa.none,n.from,n.to),an.maxOpen(r.finish())}matchTag(e,n,r){for(let i=r?this.tags.indexOf(r)+1:0;ie.length&&(l.charCodeAt(e.length)!=61||l.slice(e.length+1)!=n))){if(o.getAttrs){let c=o.getAttrs(n);if(c===!1)continue;o.attrs=c||void 0}return o}}}static schemaRules(e){let n=[];function r(i){let s=i.priority==null?50:i.priority,o=0;for(;o{r(o=AK(o)),o.mark||o.ignore||o.clearMark||(o.mark=i)})}for(let i in e.nodes){let s=e.nodes[i].spec.parseDOM;s&&s.forEach(o=>{r(o=AK(o)),o.node||o.ignore||o.mark||(o.node=i)})}return n}static fromSchema(e){return e.cached.domParser||(e.cached.domParser=new CL(e,CL.schemaRules(e)))}};const Aie={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},zGe={head:!0,noscript:!0,object:!0,script:!0,style:!0,title:!0},jie={ol:!0,ul:!0},Rw=1,PL=2,U0=4;function PK(t,e,n){return e!=null?(e?Rw:0)|(e==="full"?PL:0):t&&t.whitespace=="pre"?Rw|PL:n&~U0}class xk{constructor(e,n,r,i,s,o){this.type=e,this.attrs=n,this.marks=r,this.solid=i,this.options=o,this.content=[],this.activeMarks=oa.none,this.match=s||(o&U0?null:e.contentMatch)}findWrapping(e){if(!this.match){if(!this.type)return[];let n=this.type.contentMatch.fillBefore(Vt.from(e));if(n)this.match=this.type.contentMatch.matchFragment(n);else{let r=this.type.contentMatch,i;return(i=r.findWrapping(e.type))?(this.match=r,i):null}}return this.match.findWrapping(e.type)}finish(e){if(!(this.options&Rw)){let r=this.content[this.content.length-1],i;if(r&&r.isText&&(i=/[ \t\r\n\u000c]+$/.exec(r.text))){let s=r;r.text.length==i[0].length?this.content.pop():this.content[this.content.length-1]=s.withText(s.text.slice(0,s.text.length-i[0].length))}}let n=Vt.from(this.content);return!e&&this.match&&(n=n.append(this.match.fillBefore(Vt.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&&!Aie.hasOwnProperty(e.parentNode.nodeName.toLowerCase())}}class TK{constructor(e,n,r){this.parser=e,this.options=n,this.isOpen=r,this.open=0,this.localPreserveWS=!1;let i=n.topNode,s,o=PK(null,n.preserveWhitespace,0)|(r?U0:0);i?s=new xk(i.type,i.attrs,oa.none,!0,n.topMatch||i.type.contentMatch,o):r?s=new xk(null,null,oa.none,!0,null,o):s=new xk(e.schema.topNodeType,null,oa.none,!0,null,o),this.nodes=[s],this.find=n.findPositions,this.needsBlock=!1}get top(){return this.nodes[this.open]}addDOM(e,n){e.nodeType==3?this.addTextNode(e,n):e.nodeType==1&&this.addElement(e,n)}addTextNode(e,n){let r=e.nodeValue,i=this.top,s=i.options&PL?"full":this.localPreserveWS||(i.options&Rw)>0,{schema:o}=this.parser;if(s==="full"||i.inlineContext(e)||/[^ \t\r\n\u000c]/.test(r)){if(s)if(s==="full")r=r.replace(/\r\n?/g,` `);else if(o.linebreakReplacement&&/[\r\n]/.test(r)&&this.top.findWrapping(o.linebreakReplacement.create())){let l=r.split(/\r?\n|\r/);for(let c=0;c - +