From f4f09ccc2d6635a5a435028a2af428a8d6f1cfb9 Mon Sep 17 00:00:00 2001 From: maziggy Date: Thu, 26 Feb 2026 09:13:06 +0100 Subject: [PATCH] Hide unnecessary target model selector on "Any" tab (#528) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When scheduling a print to "Any {model}", a redundant "Target Model" dropdown appeared even though the G-code is already sliced for a specific printer model. Changing it would lead to print failures. Hide the dropdown when slicedForModel is known — the tab label already communicates the target. The dropdown still appears as a fallback for legacy files without model metadata. --- CHANGELOG.md | 1 + backend/tests/conftest.py | 4 +- .../components/PrintModal/PrinterSelector.tsx | 46 ++++++++++--------- .../{index-D6vc8KCS.js => index-BXXkRrQK.js} | 2 +- static/index.html | 2 +- 5 files changed, 29 insertions(+), 26 deletions(-) rename static/assets/{index-D6vc8KCS.js => index-BXXkRrQK.js} (98%) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8bc9c0683..fa08e1352 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ All notable changes to Bambuddy will be documented in this file. ## [0.2.1] - Unreleased ### Fixed +- **Unnecessary Target Model Selector on "Any" Tab** ([#528](https://github.com/maziggy/bambuddy/issues/528)) — When scheduling a print to "Any {model}", a redundant "Target Model" dropdown appeared even though the G-code is already sliced for a specific printer model. Changing the target model would lead to print failures. The dropdown is now hidden when the sliced model is known (the tab label already shows "Any {model}"). It still appears as a fallback for legacy files without model metadata. - **"Clear Plate & Start Next" Button Shown on Printers Without Correct Filament** ([#527](https://github.com/maziggy/bambuddy/issues/527)) — When a print job was queued for "any printer" of a model (e.g., "any H2S"), the "Clear Plate & Start Next" button appeared on ALL printers of that model, including those without the required filament loaded. Clicking it on a printer without the right filament would start a print that fails. The `PrinterQueueWidget` now filters queue items by filament compatibility — it checks the printer's loaded filament types (from AMS and external spools) against the queue item's `required_filament_types` and only shows items the printer can actually print. If no compatible items exist, the widget is hidden. - **Manual Spool Weight Overwritten by AMS Auto-Sync** ([#525](https://github.com/maziggy/bambuddy/issues/525)) — When a user manually entered a spool weight (via UI or API), the value was overwritten by the automatic AMS remain% sync that runs on every MQTT update. The AMS remain% is integer-only (~10g resolution for 1kg spool) and can't match precise manual entries. Added a `weight_locked` flag that is automatically set when `weight_used` is explicitly updated via the API. Locked spools are skipped by both the automatic AMS remain% sync and the manual force-sync endpoint. The usage tracker (3MF/gcode delta tracking) is unaffected. Users can re-enable AMS sync by setting `weight_locked: false`. - **Inconsistent Print Cost on Reprints** ([#505](https://github.com/maziggy/bambuddy/issues/505)) — Reprinting the same model produced different costs each time (e.g., £0.77, £1.54, £2.03 for the same print). Three independent code paths wrote to `archive.cost` with conflicting strategies: the usage tracker summed ALL historical `SpoolUsageHistory` rows for the archive (including rows from previous reprints), and a separate `add_reprint_cost` method added yet another full print's cost on top. Removed the redundant `add_reprint_cost` path entirely and changed the usage tracker to compute cost only from the current print session's results instead of querying all historical rows. `archive.cost` now always reflects the cost of a single print. diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py index 8258d4a23..fd31c9ba7 100644 --- a/backend/tests/conftest.py +++ b/backend/tests/conftest.py @@ -51,7 +51,7 @@ def event_loop(): loop = asyncio.get_event_loop_policy().new_event_loop() yield loop # Drain pending callbacks so aiosqlite threads can finish before loop closes - loop.run_until_complete(asyncio.sleep(0.05)) + loop.run_until_complete(asyncio.sleep(0.1)) loop.close() @@ -94,7 +94,7 @@ async def test_engine(): # Allow aiosqlite's background thread to finish processing the close # response before the per-function event loop shuts down, preventing # "RuntimeError: Event loop is closed" in call_soon_threadsafe. - await asyncio.sleep(0.05) + await asyncio.sleep(0.1) @pytest.fixture diff --git a/frontend/src/components/PrintModal/PrinterSelector.tsx b/frontend/src/components/PrintModal/PrinterSelector.tsx index 03fdf8b68..2ab415038 100644 --- a/frontend/src/components/PrintModal/PrinterSelector.tsx +++ b/frontend/src/components/PrintModal/PrinterSelector.tsx @@ -389,28 +389,30 @@ export function PrinterSelector({ {/* Model selection and location filter (when in model mode) */} {assignmentMode === 'model' && modelAssignmentAvailable && (
- {/* Model selector */} -
- - -
+ {/* Model selector — only show when sliced model is unknown */} + {!slicedForModel && ( +
+ + +
+ )} {/* Location filter (only show when target model is selected and locations exist) */} {targetModel && uniqueLocations.length > 0 && onTargetLocationChange && ( diff --git a/static/assets/index-D6vc8KCS.js b/static/assets/index-BXXkRrQK.js similarity index 98% rename from static/assets/index-D6vc8KCS.js rename to static/assets/index-BXXkRrQK.js index 2805ba51e..7707a8c7c 100644 --- a/static/assets/index-D6vc8KCS.js +++ b/static/assets/index-BXXkRrQK.js @@ -8508,7 +8508,7 @@ void main() { flex items-center justify-center gap-1 px-3 py-1.5 rounded-lg text-xs font-medium transition-colors ${Wn&&T("printers:control")?Ft?"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:T("printers:control")?g(Ft?"printers.resume":"printers.pause"):g("printers.permission.noControl"),children:[Ft?a.jsx(io,{className:"w-3 h-3"}):a.jsx(KC,{className:"w-3 h-3"}),g(Ft?"printers.resume":"printers.pause")]})]})]})]})})(),(Ct?.length>0||fe.vt_tray.length>0)&&r==="expanded"&&(()=>{const gt=Ct.filter(St=>St.tray.length>1),Ft=Ct.filter(St=>St.tray.length===1),Wn=t.nozzle_count===2||fe?.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:g("printers.filaments")}),a.jsx("div",{className:"flex-1 h-px bg-bambu-dark-tertiary/30"})]}),a.jsxs("div",{className:"space-y-3",children:[gt.length>0&&a.jsx("div",{className:"grid grid-cols-2 gap-3",children:gt.map(St=>{const Cn=Ve[String(St.id)],Na=St.id>=128?St.id-128:St.id,nr=Cn!==void 0?Cn:Na,pa=nr===1,xr=nr===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("span",{className:"text-[10px] text-white font-medium",children:th(St.id,St.tray.length)}),Wn&&(pa||xr)&&a.jsx(t9,{side:pa?"L":"R"})]}),(St.humidity!=null||St.temp!=null)&&a.jsxs("div",{className:"flex items-center gap-1.5 max-[550px]:flex-col max-[550px]:items-start",children:[St.humidity!=null&&a.jsx(r9,{humidity:St.humidity,goodThreshold:s?.humidityGood,fairThreshold:s?.humidityFair,onClick:()=>se({amsId:St.id,amsLabel:th(St.id,St.tray.length),mode:"humidity"}),compact:!0}),St.temp!=null&&a.jsx(a9,{temp:St.temp,goodThreshold:s?.tempGood,fairThreshold:s?.tempFair,onClick:()=>se({amsId:St.id,amsLabel:th(St.id,St.tray.length),mode:"temperature"}),compact:!0})]})]}),a.jsx("div",{className:"grid grid-cols-4 gap-1.5",children:[0,1,2,3].map(en=>{const Un=St.tray[en]||St.tray.find(Tn=>Tn.id===en),Hi=Un?.tray_type&&Un.remain>=0,hi=!Un?.tray_type,Tl=St.id*4+en,Io=Mt===Tl,ho=Un?.tray_info_idx?ve?.[Un.tray_info_idx]:null,Ua=Ge?.[Tl],ga=Un?.tray_uuid?.toUpperCase(),Xa=ga?c?.[ga]:void 0,Ba=W2(Xa),Ha=u?.(t.id,St.id,en),cr=(()=>{const Tn=Ha?.spool;return Tn&&Tn.label_weight>0&&Tn.weight_used!=null?Math.round(Math.max(0,Tn.label_weight-Tn.weight_used)/Tn.label_weight*100):null})(),$a=Ba??cr??(Hi?Un.remain:null),Kc=Ba!==null?"spoolman":cr!==null?"inventory":Hi?"ams":void 0,Nr=Un?.tray_type?{vendor:K2(Un)?"Bambu Lab":"Generic",profile:ho?.name||Ua?.preset_name||Un.tray_sub_brands||Un.tray_type,colorName:H2(Un.tray_id_name)||$2(Un.tray_color),colorHex:Un.tray_color||null,kFactor:V2(Un.k),fillLevel:$a,trayUuid:Un.tray_uuid||null,tagUid:Un.tag_uid||null,fillSource:Kc}:null,ba=lt?.amsId===St.id&<?.slotId===en,an=a.jsxs("div",{className:`bg-bambu-dark-tertiary rounded p-1 text-center ${hi?"opacity-50":""} ${Io?"ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark":""}`,children:[a.jsx("div",{className:"w-3.5 h-3.5 rounded-full mx-auto mb-0.5 border-2",style:{backgroundColor:Un?.tray_color?`#${Un.tray_color}`:Un?.tray_type?"#333":"transparent",borderColor:hi?"#666":"rgba(255,255,255,0.1)",borderStyle:hi?"dashed":"solid"}}),a.jsx("div",{className:"text-[9px] text-white font-bold truncate",children:Un?.tray_type||"—"}),a.jsx("div",{className:"mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden",children:$a!==null&&$a>=0&&Un&&a.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${$a}%`,backgroundColor:G2($a)}})})]});return a.jsxs("div",{className:"relative group",children:[ba&&a.jsx("div",{className:"absolute inset-0 bg-bambu-dark-tertiary/80 rounded flex items-center justify-center z-20",children:a.jsx(vr,{className:"w-4 h-4 text-bambu-green animate-spin"})}),fe?.state!=="RUNNING"&&a.jsx("button",{onClick:Tn=>{Tn.stopPropagation(),Yr(pn?.amsId===St.id&&pn?.slotId===en?null:{amsId:St.id,slotId:en})},className:"absolute -top-1 -right-1 w-4 h-4 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity z-10 hover:bg-bambu-dark-tertiary",title:g("printers.slotOptions"),children:a.jsx(Th,{className:"w-2.5 h-2.5 text-bambu-gray"})}),fe?.state!=="RUNNING"&&pn?.amsId===St.id&&pn?.slotId===en&&a.jsx("div",{className:"absolute top-full left-0 mt-1 z-50 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl py-1 min-w-[120px]",children:a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-xs flex items-center gap-2 ${T("printers:ams_rfid")?"text-white hover:bg-bambu-dark-tertiary":"text-bambu-gray/50 cursor-not-allowed"}`,onClick:Tn=>{Tn.stopPropagation(),T("printers:ams_rfid")&&(It.mutate({amsId:St.id,slotId:en}),Yr(null))},disabled:ba||!T("printers:ams_rfid"),title:T("printers:ams_rfid")?void 0:g("printers.permission.noAmsRfid"),children:[a.jsx(vr,{className:`w-3 h-3 ${ba?"animate-spin":""}`}),g("printers.rfid.reread")]})}),Nr?a.jsx(U2,{data:Nr,spoolman:{enabled:o,hasUnlinkedSpools:l,linkedSpoolId:Nr.trayUuid?c?.[Nr.trayUuid.toUpperCase()]?.id:void 0,spoolmanUrl:d,onLinkSpool:o&&Nr.trayUuid?Tn=>{V({tagUid:Nr.tagUid||"",trayUuid:Tn,printerId:t.id,amsId:St.id,trayId:en})}:void 0},inventory:o?void 0:(()=>{const Tn=u?.(t.id,St.id,en);return{assignedSpool:Tn?.spool?{id:Tn.spool.id,material:Tn.spool.material,brand:Tn.spool.brand,color_name:Tn.spool.color_name,remainingWeightGrams:Math.max(0,Math.round(Tn.spool.label_weight-Tn.spool.weight_used))}:null,onAssignSpool:Nr.vendor!=="Bambu Lab"?()=>me({printerId:t.id,amsId:St.id,trayId:en,trayInfo:{type:Nr.profile,color:Nr.colorHex||"",location:`${th(St.id,St.tray.length)} Slot ${en+1}`}}):void 0,onUnassignSpool:Tn&&Nr.vendor!=="Bambu Lab"?()=>h?.(t.id,St.id,en):void 0}})(),configureSlot:{enabled:T("printers:control"),onConfigure:()=>ie({amsId:St.id,trayId:en,trayCount:St.tray.length,trayType:Un?.tray_type||void 0,trayColor:Un?.tray_color||void 0,traySubBrands:Un?.tray_sub_brands||void 0,trayInfoIdx:Un?.tray_info_idx||void 0,extruderId:Cn,caliIdx:Un?.cali_idx,savedPresetId:Ua?.preset_id})},children:an}):a.jsx(B2,{configureSlot:{enabled:T("printers:control"),onConfigure:()=>ie({amsId:St.id,trayId:en,trayCount:St.tray.length,extruderId:Cn})},children:an})]},en)})})]},St.id)})}),(Ft.length>0||fe.vt_tray.length>0)&&a.jsxs("div",{className:"grid grid-cols-4 gap-3",children:[Ft.map(St=>{const Cn=Ve[String(St.id)],Na=St.id>=128?St.id-128:St.id,nr=Cn!==void 0?Cn:Na,pa=nr===1,xr=nr===0,en=St.tray[0],Un=en?.tray_type&&en.remain>=0,Hi=!en?.tray_type,hi=f4(St.id,en?.id??0,!1),Tl=Mt===hi,Io=en?.tray_info_idx?ve?.[en.tray_info_idx]:null,ho=Ge?.[hi],Ua=en?.tray_uuid?.toUpperCase(),ga=Ua?c?.[Ua]:void 0,Xa=W2(ga),Ba=en?.id??0,Ha=u?.(t.id,St.id,Ba),cr=(()=>{const dr=Ha?.spool;return dr&&dr.label_weight>0&&dr.weight_used!=null?Math.round(Math.max(0,dr.label_weight-dr.weight_used)/dr.label_weight*100):null})(),$a=Xa??cr??(Un?en.remain:null),Kc=Xa!==null?"spoolman":cr!==null?"inventory":Un?"ams":void 0,Nr=en?.tray_type?{vendor:K2(en)?"Bambu Lab":"Generic",profile:Io?.name||ho?.preset_name||en.tray_sub_brands||en.tray_type,colorName:H2(en.tray_id_name)||$2(en.tray_color),colorHex:en.tray_color||null,kFactor:V2(en.k),fillLevel:$a,trayUuid:en.tray_uuid||null,tagUid:en.tag_uid||null,fillSource:Kc}:null,ba=en?.id??0,an=lt?.amsId===St.id&<?.slotId===ba,Tn=a.jsxs("div",{className:`bg-bambu-dark-tertiary rounded p-1 text-center ${Hi?"opacity-50":""} ${Tl?"ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark":""}`,children:[a.jsx("div",{className:"w-3.5 h-3.5 rounded-full mx-auto mb-0.5 border-2",style:{backgroundColor:en?.tray_color?`#${en.tray_color}`:en?.tray_type?"#333":"transparent",borderColor:Hi?"#666":"rgba(255,255,255,0.1)",borderStyle:Hi?"dashed":"solid"}}),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:$a!==null&&$a>=0&&a.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${$a}%`,backgroundColor:G2($a)}})})]});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("span",{className:"text-[10px] text-white font-medium",children:th(St.id,St.tray.length)}),Wn&&(pa||xr)&&a.jsx(t9,{side:pa?"L":"R"})]}),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:[an&&a.jsx("div",{className:"absolute inset-0 bg-bambu-dark-tertiary/80 rounded flex items-center justify-center z-20",children:a.jsx(vr,{className:"w-4 h-4 text-bambu-green animate-spin"})}),fe?.state!=="RUNNING"&&a.jsx("button",{onClick:dr=>{dr.stopPropagation(),Yr(pn?.amsId===St.id&&pn?.slotId===ba?null:{amsId:St.id,slotId:ba})},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:g("printers.slotOptions"),children:a.jsx(Th,{className:"w-2.5 h-2.5 text-bambu-gray"})}),fe?.state!=="RUNNING"&&pn?.amsId===St.id&&pn?.slotId===ba&&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 ${T("printers:ams_rfid")?"text-white hover:bg-bambu-dark-tertiary":"text-bambu-gray/50 cursor-not-allowed"}`,onClick:dr=>{dr.stopPropagation(),T("printers:ams_rfid")&&(It.mutate({amsId:St.id,slotId:ba}),Yr(null))},disabled:an||!T("printers:ams_rfid"),title:T("printers:ams_rfid")?void 0:g("printers.permission.noAmsRfid"),children:[a.jsx(vr,{className:`w-3 h-3 ${an?"animate-spin":""}`}),g("printers.rfid.reread")]})}),Nr?a.jsx(U2,{data:Nr,spoolman:{enabled:o,hasUnlinkedSpools:l,linkedSpoolId:Nr.trayUuid?c?.[Nr.trayUuid.toUpperCase()]?.id:void 0,spoolmanUrl:d,onLinkSpool:o&&Nr.trayUuid?dr=>{V({tagUid:Nr.tagUid||"",trayUuid:dr,printerId:t.id,amsId:St.id,trayId:ba})}:void 0},inventory:o?void 0:(()=>{const dr=u?.(t.id,St.id,ba);return{assignedSpool:dr?.spool?{id:dr.spool.id,material:dr.spool.material,brand:dr.spool.brand,color_name:dr.spool.color_name,remainingWeightGrams:Math.max(0,Math.round(dr.spool.label_weight-dr.spool.weight_used))}:null,onAssignSpool:Nr.vendor!=="Bambu Lab"?()=>me({printerId:t.id,amsId:St.id,trayId:ba,trayInfo:{type:Nr.profile,color:Nr.colorHex||"",location:th(St.id,St.tray.length)}}):void 0,onUnassignSpool:dr&&Nr.vendor!=="Bambu Lab"?()=>h?.(t.id,St.id,ba):void 0}})(),configureSlot:{enabled:T("printers:control"),onConfigure:()=>ie({amsId:St.id,trayId:ba,trayCount:St.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:Cn,caliIdx:en?.cali_idx,savedPresetId:ho?.preset_id})},children:Tn}):a.jsx(B2,{configureSlot:{enabled:T("printers:control"),onConfigure:()=>ie({amsId:St.id,trayId:ba,trayCount:St.tray.length,extruderId:Cn})},children:Tn})]}),(St.humidity!=null||St.temp!=null)&&a.jsxs("div",{className:"flex flex-col justify-center gap-1 shrink-0 max-[550px]:w-full",children:[St.temp!=null&&a.jsx(a9,{temp:St.temp,goodThreshold:s?.tempGood,fairThreshold:s?.tempFair,onClick:()=>se({amsId:St.id,amsLabel:th(St.id,St.tray.length),mode:"temperature"}),compact:!0}),St.humidity!=null&&a.jsx(r9,{humidity:St.humidity,goodThreshold:s?.humidityGood,fairThreshold:s?.humidityFair,onClick:()=>se({amsId:St.id,amsLabel:th(St.id,St.tray.length),mode:"humidity"}),compact:!0})]})]})]},St.id)}),fe.vt_tray.length>0&&a.jsxs("div",{className:`p-2.5 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary/30 ${fe.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:g("printers.external")})}),a.jsx("div",{className:`grid ${fe.vt_tray.length>1?"grid-cols-2":"grid-cols-1"} gap-1.5`,children:[...fe.vt_tray].sort((St,Cn)=>(St.id??254)-(Cn.id??254)).map(St=>{const Cn=St.id??254,Na=Wn&&Mt===254?Cn===254&&fe.active_extruder===1||Cn===255&&fe.active_extruder===0:Mt===Cn,nr=Cn-254,pa=Wn?g(Cn===254?"printers.extL":"printers.extR"):"",xr=St.tray_info_idx?ve?.[St.tray_info_idx]:null,en=Ge?.[1020+nr],Un=St.tray_uuid?.toUpperCase(),Hi=Un?c?.[Un]:void 0,hi=W2(Hi),Tl=u?.(t.id,255,nr),Io=(()=>{const cr=Tl?.spool;return cr&&cr.label_weight>0&&cr.weight_used!=null?Math.round(Math.max(0,cr.label_weight-cr.weight_used)/cr.label_weight*100):null})(),ho=St.tray_type&&St.remain>=0,Ua=hi??Io??(ho?St.remain:null),ga=hi!==null?"spoolman":Io!==null?"inventory":ho?"ams":void 0,Xa={vendor:K2(St)?"Bambu Lab":"Generic",profile:xr?.name||en?.preset_name||St.tray_sub_brands||St.tray_type||"Unknown",colorName:H2(St.tray_id_name)||$2(St.tray_color),colorHex:St.tray_color||null,kFactor:V2(St.k),fillLevel:Ua,trayUuid:St.tray_uuid||null,tagUid:St.tag_uid||null,fillSource:ga},Ba=!St.tray_type,Ha=a.jsxs("div",{className:`bg-bambu-dark-tertiary rounded p-1 text-center ${Ba?"opacity-50":""} ${Na?"ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark":""}`,children:[a.jsx("div",{className:"w-3.5 h-3.5 rounded-full mx-auto mb-0.5 border-2",style:{backgroundColor:St.tray_color?`#${St.tray_color}`:St.tray_type?"#333":"transparent",borderColor:Ba?"#666":"rgba(255,255,255,0.1)",borderStyle:Ba?"dashed":"solid"}}),a.jsx("div",{className:`text-[9px] font-bold truncate ${Ba?"text-white/40":"text-white"}`,children:St.tray_type||"—"}),a.jsx("div",{className:"mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden",children:Ua!==null&&Ua>=0&&!Ba&&a.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${Ua}%`,backgroundColor:G2(Ua)}})}),pa&&a.jsx("div",{className:"text-[7px] text-white/40 mt-0.5 truncate",children:pa})]});return a.jsx("div",{className:"relative group",children:Ba?a.jsx(B2,{configureSlot:{enabled:T("printers:control"),onConfigure:()=>ie({amsId:255,trayId:nr,trayCount:1,extruderId:Wn?Cn===254?1:0:void 0})},children:Ha}):a.jsx(U2,{data:Xa,spoolman:{enabled:o,hasUnlinkedSpools:l,linkedSpoolId:Xa.trayUuid?c?.[Xa.trayUuid.toUpperCase()]?.id:void 0,spoolmanUrl:d,onLinkSpool:o&&Xa.trayUuid?cr=>{V({tagUid:Xa.tagUid||"",trayUuid:cr,printerId:t.id,amsId:255,trayId:nr})}:void 0},inventory:o?void 0:(()=>{const cr=u?.(t.id,255,nr);return{assignedSpool:cr?.spool?{id:cr.spool.id,material:cr.spool.material,brand:cr.spool.brand,color_name:cr.spool.color_name,remainingWeightGrams:Math.max(0,Math.round(cr.spool.label_weight-cr.spool.weight_used))}:null,onAssignSpool:()=>me({printerId:t.id,amsId:255,trayId:nr,trayInfo:{type:Xa.profile,color:Xa.colorHex||"",location:pa||g("printers.external")}}),onUnassignSpool:cr?()=>h?.(t.id,255,nr):void 0}})(),configureSlot:{enabled:T("printers:control"),onConfigure:()=>ie({amsId:255,trayId:nr,trayCount:1,trayType:St.tray_type||void 0,trayColor:St.tray_color||void 0,traySubBrands:St.tray_sub_brands||void 0,trayInfoIdx:St.tray_info_idx||void 0,extruderId:Wn?Cn===254?1:0:void 0,caliIdx:St.cali_idx,savedPresetId:en?.preset_id})},children:Ha})},Cn)})})]})]})]})]})})()]}),Ue&&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(nu,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}),a.jsx("span",{className:"text-sm text-white truncate",children:Ue.name}),xt&&a.jsxs("span",{className:`text-xs px-1.5 py-0.5 rounded flex-shrink-0 ${xt.state==="ON"?"bg-bambu-green/20 text-bambu-green":xt.state==="OFF"?"bg-red-500/20 text-red-400":"bg-bambu-gray/20 text-bambu-gray"}`,children:[xt.state||"?",xt.state==="ON"&&xt.energy?.power!=null&&a.jsxs("span",{className:"text-yellow-400 ml-1.5",children:["· ",xt.energy.power,"W"]})]})]}),a.jsx("div",{className:"flex-1"}),a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsxs("button",{onClick:()=>W(!0),disabled:Se.isPending||xt?.state==="ON"||!T("smart_plugs:control"),className:`px-2 py-1 text-xs rounded transition-colors flex items-center gap-1 ${T("smart_plugs:control")?xt?.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:T("smart_plugs:control")?void 0:g("printers.permission.noSmartPlugControl"),children:[a.jsx(mu,{className:"w-3 h-3"}),"On"]}),a.jsxs("button",{onClick:()=>re(!0),disabled:Se.isPending||xt?.state==="OFF"||!T("smart_plugs:control"),className:`px-2 py-1 text-xs rounded transition-colors flex items-center gap-1 ${T("smart_plugs:control")?xt?.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:T("smart_plugs:control")?void 0:g("printers.permission.noSmartPlugControl"),children:[a.jsx(YC,{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 ${Ue.auto_off_executed?"text-bambu-green":"text-bambu-gray"}`,children:Ue.auto_off_executed?"Auto-off done":"Auto-off"}),a.jsx("button",{onClick:()=>tt.mutate(!Ue.auto_off),disabled:tt.isPending||Ue.auto_off_executed||!T("smart_plugs:control"),title:T("smart_plugs:control")?Ue.auto_off_executed?g("printers.autoOffExecuted"):g("printers.autoOffAfterPrint"):g("printers.permission.noSmartPlugControl"),className:`relative w-9 h-5 rounded-full transition-colors flex-shrink-0 ${T("smart_plugs:control")?Ue.auto_off_executed?"bg-bambu-green/50 cursor-not-allowed":Ue.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 ${Ue.auto_off||Ue.auto_off_executed?"translate-x-4":"translate-x-0"}`})})]})]}),yt&&yt.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(d0,{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:yt.map(gt=>a.jsxs("button",{onClick:()=>it.mutate(gt.id),disabled:it.isPending,title:`Run ${gt.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(io,{className:"w-2.5 h-2.5"}),gt.name]},gt.id))})]})]}),r==="expanded"&&a.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3",children:[a.jsxs("div",{className:"text-xs text-bambu-gray",children:[a.jsx("p",{children:t.ip_address}),a.jsx("p",{className:"truncate",children:t.serial_number})]}),a.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[a.jsx(Me,{variant:"secondary",size:"sm",onClick:()=>He.mutate(!fe?.chamber_light),disabled:!fe?.connected||He.isPending||!T("printers:control"),title:T("printers:control")?fe?.chamber_light?g("printers.chamberLightOff"):g("printers.chamberLightOn"):g("printers.permission.noControl"),className:fe?.chamber_light?"bg-yellow-500/20 hover:bg-yellow-500/30 border-yellow-500/30":"",children:a.jsx(lL,{on:fe?.chamber_light??!1,className:"w-4 h-4"})}),a.jsx(Me,{variant:"secondary",size:"sm",onClick:()=>{if(p==="embedded"&&x)x(t.id,t.name);else{const gt=localStorage.getItem("cameraWindowState"),Ft=gt?JSON.parse(gt):{width:640,height:400},Wn=[`width=${Ft.width}`,`height=${Ft.height}`,Ft.left!==void 0?`left=${Ft.left}`:"",Ft.top!==void 0?`top=${Ft.top}`:"","menubar=no,toolbar=no,location=no,status=no,noopener"].filter(Boolean).join(",");window.open(`/camera/${t.id}`,`camera-${t.id}`,Wn)}},disabled:!fe?.connected,title:g(p==="embedded"?"printers.openCameraOverlay":"printers.openCameraWindow"),children:a.jsx(PF,{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(Me,{variant:"secondary",size:"sm",onClick:jn,disabled:!fe?.connected||Xe.isPending||!T("printers:update"),title:T("printers:update")?t.plate_detection_enabled?g("printers.plateDetection.enabledClick"):g("printers.plateDetection.disabledClick"):g("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:Xe.isPending?a.jsx(at,{className:"w-4 h-4 animate-spin"}):a.jsx(_1,{className:"w-4 h-4"})}),a.jsx(Me,{variant:"secondary",size:"sm",onClick:Qt,disabled:!fe?.connected||L||!T("printers:update"),title:T("printers:update")?g("printers.plateDetection.manageCalibration"):g("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:L?a.jsx(at,{className:"w-3 h-3 animate-spin"}):a.jsx(Pn,{className:"w-3 h-3"})})]}),a.jsxs(Me,{variant:"secondary",size:"sm",onClick:()=>D(!0),disabled:!T("printers:files"),title:T("printers:files")?g("printers.browseFiles"):g("printers.permission.noFiles"),children:[a.jsx($b,{className:"w-4 h-4"}),"Files"]})]})]})]}),z&&a.jsx(kTe,{printerId:t.id,printerName:t.name,onClose:()=>D(!1)}),$&&a.jsx(jTe,{printerId:t.id,printerName:t.name,onClose:()=>G(!1)}),Ce&&a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onClick:()=>dn(),children:a.jsxs("div",{className:"bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl max-w-lg w-full",onClick:gt=>gt.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:[Ce.needs_calibration?a.jsx(_1,{className:"w-5 h-5 text-blue-500"}):Ce.is_empty?a.jsx(br,{className:"w-5 h-5 text-green-500"}):a.jsx(bi,{className:"w-5 h-5 text-yellow-500"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:"Build Plate Check"}),Ce.reference_count!==void 0&&Ce.max_references&&a.jsxs("span",{className:"text-xs text-bambu-gray bg-bambu-dark-tertiary px-2 py-1 rounded",children:[Ce.reference_count,"/",Ce.max_references," refs"]})]}),a.jsx("button",{onClick:()=>dn(),className:"p-1 text-bambu-gray hover:text-white rounded transition-colors",children:a.jsx(Rt,{className:"w-5 h-5"})})]}),a.jsxs("div",{className:"p-4 space-y-4",children:[Ce.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:g("printers.plateDetection.calibrationRequired")}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",dangerouslySetInnerHTML:{__html:g("printers.plateDetection.calibrationInstructions")}})]}),a.jsxs("div",{className:"text-sm text-bambu-gray space-y-2",children:[a.jsx("p",{children:g("printers.plateDetection.calibrationDescription")}),a.jsx("p",{dangerouslySetInnerHTML:{__html:g("printers.plateDetection.calibrationTip")}})]})]}):a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:`p-3 rounded-lg ${Ce.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 ${Ce.is_empty?"text-green-400":"text-yellow-400"}`,children:Ce.is_empty?g("printers.plateDetection.plateEmpty"):g("printers.plateDetection.objectsDetected")}),a.jsxs("p",{className:"text-sm text-bambu-gray mt-1",children:[g("printers.plateDetection.confidence"),": ",Math.round(Ce.confidence*100),"% | ",g("printers.plateDetection.difference"),": ",Ce.difference_percent.toFixed(1),"%"]})]}),Ce.debug_image_url&&a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-bambu-gray mb-2",children:g("printers.plateDetection.analysisPreview")}),a.jsx("img",{src:Ce.debug_image_url,alt:g("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:g("printers.plateDetection.analysisLegend")})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:Ce.message})]}),Tt&&Tt.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:g("printers.plateDetection.savedReferences",{count:Tt.references.length,max:Tt.max_references})}),a.jsx("div",{className:"grid grid-cols-5 gap-2",children:Tt.references.map(gt=>a.jsxs("div",{className:"relative group",children:[a.jsx("img",{src:ne.getPlateReferenceThumbnailUrl(t.id,gt.index),alt:gt.label||`Reference ${gt.index+1}`,className:"w-full aspect-video object-cover rounded border border-bambu-dark-tertiary"}),a.jsx("button",{onClick:()=>bn(gt.index),className:"absolute top-1 right-1 p-0.5 bg-red-500/80 rounded opacity-0 group-hover:opacity-100 transition-opacity",title:g("printers.plateDetection.deleteReference"),children:a.jsx(Rt,{className:"w-3 h-3 text-white"})}),Yt?.index===gt.index?a.jsx("input",{type:"text",value:Yt.label,onChange:Ft=>cn({...Yt,label:Ft.target.value}),onBlur:()=>$r(gt.index,Yt.label),onKeyDown:Ft=>{Ft.key==="Enter"&&$r(gt.index,Yt.label),Ft.key==="Escape"&&cn(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:g("printers.plateDetection.labelPlaceholder")}):a.jsx("p",{className:"text-xs text-bambu-gray mt-1 truncate cursor-pointer hover:text-white",onClick:()=>cn({index:gt.index,label:gt.label}),title:gt.label?g("printers.plateDetection.clickToEdit",{label:gt.label}):g("printers.plateDetection.clickToAddLabel"),children:gt.label||a.jsx("span",{className:"italic opacity-50",children:g("printers.noLabel")})}),a.jsx("p",{className:"text-[10px] text-bambu-gray/60",children:gt.timestamp?er(gt.timestamp)?.toLocaleDateString()??"":""})]},gt.index))})]}),!Ce.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:g("printers.roi.title")}),pe?a.jsxs("div",{className:"flex gap-1",children:[a.jsx(Me,{variant:"ghost",size:"sm",onClick:()=>te(null),disabled:Be,children:g("common.cancel")}),a.jsx(Me,{size:"sm",onClick:or,disabled:Be,children:Be?a.jsx(at,{className:"w-3 h-3 animate-spin"}):g("common.save")})]}):a.jsxs(Me,{variant:"ghost",size:"sm",onClick:()=>te(Ce.roi||{x:.15,y:.35,w:.7,h:.55}),children:[a.jsx(Ya,{className:"w-3 h-3 mr-1"}),g("common.edit")]})]}),pe?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:g("printers.roi.xStart")}),a.jsx("input",{type:"range",min:"0",max:"0.9",step:"0.01",value:pe.x,onChange:gt=>te({...pe,x:parseFloat(gt.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(pe.x*100),"%"]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"text-xs text-bambu-gray",children:g("printers.roi.yStart")}),a.jsx("input",{type:"range",min:"0",max:"0.9",step:"0.01",value:pe.y,onChange:gt=>te({...pe,y:parseFloat(gt.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(pe.y*100),"%"]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"text-xs text-bambu-gray",children:g("printers.width")}),a.jsx("input",{type:"range",min:"0.1",max:"1",step:"0.01",value:pe.w,onChange:gt=>te({...pe,w:parseFloat(gt.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(pe.w*100),"%"]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"text-xs text-bambu-gray",children:g("printers.height")}),a.jsx("input",{type:"range",min:"0.1",max:"1",step:"0.01",value:pe.h,onChange:gt=>te({...pe,h:parseFloat(gt.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(pe.h*100),"%"]})]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:g("printers.roi.instruction")})]}):a.jsxs("p",{className:"text-xs text-bambu-gray",children:["Current: X=",Math.round((Ce.roi?.x||.15)*100),"%, Y=",Math.round((Ce.roi?.y||.35)*100),"%, W=",Math.round((Ce.roi?.w||.7)*100),"%, H=",Math.round((Ce.roi?.h||.55)*100),"%"]})]})]}),a.jsx("div",{className:"flex justify-end gap-2 p-4 border-t border-bambu-dark-tertiary",children:Ce.needs_calibration?a.jsxs(a.Fragment,{children:[a.jsx(Me,{variant:"ghost",onClick:()=>dn(),children:g("common.cancel")}),a.jsx(Me,{onClick:()=>fn(),disabled:q,children:q?a.jsxs(a.Fragment,{children:[a.jsx(at,{className:"w-4 h-4 mr-2 animate-spin"}),"Calibrating..."]}):"Calibrate Empty Plate"})]}):a.jsxs(a.Fragment,{children:[a.jsx(Me,{variant:"ghost",onClick:()=>fn(),disabled:q,children:q?"Adding...":`Add Reference (${Tt?.references.length||0}/${Tt?.max_references||5})`}),a.jsx(Me,{onClick:()=>dn(),children:"Close"})]})})]})}),U&&Ue&&a.jsx(xn,{title:g("printers.confirm.powerOnTitle"),message:g("printers.confirm.powerOnMessage",{name:t.name}),confirmText:g("printers.confirm.powerOnButton"),variant:"default",onConfirm:()=>{Se.mutate("on"),W(!1)},onCancel:()=>W(!1)}),Y&&Ue&&a.jsx(xn,{title:g("printers.confirm.powerOffTitle"),message:fe?.state==="RUNNING"?g("printers.confirm.powerOffWarning",{name:t.name}):g("printers.confirm.powerOffMessage",{name:t.name}),confirmText:g("printers.confirm.powerOffButton"),variant:"danger",onConfirm:()=>{Se.mutate("off"),re(!1)},onCancel:()=>re(!1)}),ee&&a.jsx(xn,{title:g("printers.confirm.stopTitle"),message:g("printers.confirm.stopMessage",{name:t.name}),confirmText:g("printers.confirm.stopButton"),variant:"danger",onConfirm:()=>{We.mutate(),Z(!1)},onCancel:()=>Z(!1)}),we&&a.jsx(xn,{title:g("printers.confirm.pauseTitle"),message:g("printers.confirm.pauseMessage",{name:t.name}),confirmText:g("printers.confirm.pauseButton"),variant:"default",onConfirm:()=>{Ot.mutate(),oe(!1)},onCancel:()=>oe(!1)}),J&&a.jsx(xn,{title:g("printers.confirm.resumeTitle"),message:g("printers.confirm.resumeMessage",{name:t.name}),confirmText:g("printers.confirm.resumeButton"),variant:"default",onConfirm:()=>{be.mutate(),je(!1)},onCancel:()=>je(!1)}),a.jsx(cL,{printerId:t.id,isOpen:de,onClose:()=>le(!1)}),H&&a.jsx(LTe,{printerName:t.name,errors:fe?.hms_errors||[],onClose:()=>K(!1),printerId:t.id,hasPermission:T}),_e&&a.jsx(KHe,{isOpen:!!_e,onClose:()=>se(null),printerId:t.id,printerName:t.name,amsId:_e.amsId,amsLabel:_e.amsLabel,initialMode:_e.mode,thresholds:s}),ze&&a.jsx(YHe,{isOpen:!!ze,onClose:()=>V(null),tagUid:ze.tagUid,trayUuid:ze.trayUuid,printerId:ze.printerId,amsId:ze.amsId,trayId:ze.trayId}),X&&a.jsx(XHe,{isOpen:!!X,onClose:()=>me(null),printerId:X.printerId,amsId:X.amsId,trayId:X.trayId,trayInfo:X.trayInfo}),Q&&a.jsx(i$e,{isOpen:!!Q,onClose:()=>ie(null),printerId:t.id,slotInfo:Q,printerModel:xR(t.model)||void 0,onSuccess:()=>{y.invalidateQueries({queryKey:["slotPresets",t.id]}),y.invalidateQueries({queryKey:["printerStatus",t.id]})}}),B&&a.jsx(w$e,{printer:t,onClose:()=>O(!1)}),ue&&xe&&a.jsx(v$e,{printer:t,firmwareInfo:xe,onClose:()=>Le(!1)}),pn&&a.jsx("div",{className:"fixed inset-0 z-40",onClick:()=>Yr(null)})]})}function y$e({onClose:t,onAdd:e,existingSerials:n}){const{t:r}=Dt(),[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,h]=w.useState(""),[f,p]=w.useState(!1),[x,v]=w.useState(!1),[g,y]=w.useState([]),[_,N]=w.useState(""),[T,k]=w.useState({scanned:0,total:0});w.useEffect(()=>{dc.getInfo().then(P=>{v(P.is_docker),P.subnets.length>0&&(y(P.subnets),N(P.subnets[0]))}).catch(()=>{})},[]);const M=c.filter(P=>!n.includes(P.serial)),C=async()=>{h(""),d([]),l(!0),p(!1),k({scanned:0,total:0});try{if(x){await dc.startSubnetScan(_);const P=setInterval(async()=>{try{const E=await dc.getScanStatus();k({scanned:E.scanned,total:E.total});const B=await dc.getDiscoveredPrinters();d(B),E.running||(clearInterval(P),l(!1),p(!0))}catch(E){console.error("Failed to get scan status:",E)}},500)}else{await dc.startDiscovery(10);const P=setInterval(async()=>{try{const E=await dc.getDiscoveredPrinters();d(E)}catch(E){console.error("Failed to get discovered printers:",E)}},1e3);setTimeout(async()=>{clearInterval(P);try{await dc.stopDiscovery()}catch{}l(!1),p(!0);try{const E=await dc.getDiscoveredPrinters();d(E)}catch(E){console.error("Failed to get final discovered printers:",E)}},1e4)}}catch(P){console.error("Failed to start discovery:",P),h(P instanceof Error?P.message:r("printers.discovery.failedToStart")),l(!1),p(!0)}},j=P=>{const E=P.serial.startsWith("unknown-")?"":P.serial;s({...i,name:P.name||"",serial_number:E,ip_address:P.ip_address,model:xR(P.model)}),d([])};return w.useEffect(()=>()=>{dc.stopDiscovery().catch(()=>{}),dc.stopSubnetScan().catch(()=>{})},[]),w.useEffect(()=>{const P=E=>{E.key==="Escape"&&t()};return window.addEventListener("keydown",P),()=>window.removeEventListener("keydown",P)},[t]),a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",onClick:t,children:a.jsx(wt,{className:"w-full max-w-md",onClick:P=>P.stopPropagation(),children:a.jsxs(Nt,{children:[a.jsx("h2",{className:"text-xl font-semibold mb-4",children:r("printers.addPrinter")}),a.jsxs("div",{className:"mb-4 pb-4 border-b border-bambu-dark-tertiary",children:[x&&a.jsxs("div",{className:"mb-3",children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.discovery.subnetToScan")}),g.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:P=>N(P.target.value),disabled:o,children:g.map(P=>a.jsx("option",{value:P,children:P},P))}):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:P=>N(P.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(Me,{type:"button",variant:"secondary",onClick:C,disabled:o,className:"w-full",children:o?a.jsxs(a.Fragment,{children:[a.jsx(at,{className:"w-4 h-4 animate-spin"}),x&&T.total>0?r("printers.discovery.scanProgress",{scanned:T.scanned,total:T.total}):r("printers.discovery.scanning")]}):a.jsxs(a.Fragment,{children:[a.jsx(Mr,{className:"w-4 h-4"}),r(x?"printers.discovery.scanSubnet":"printers.discovery.discoverNetwork")]})}),u&&a.jsx("div",{className:"mt-2 text-sm text-red-400",children:u}),M.length>0&&a.jsx("div",{className:"mt-3 space-y-2 max-h-40 overflow-y-auto",children:M.map(P=>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:()=>j(P),children:[a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:"font-medium text-white text-sm truncate",children:P.name||P.serial}),a.jsxs("p",{className:"text-xs text-bambu-gray truncate",children:[xR(P.model)||r("printers.discovery.unknown")," • ",P.ip_address,P.serial.startsWith("unknown-")&&a.jsxs("span",{className:"text-yellow-500",children:[" • ",r("printers.discovery.serialRequired")]})]})]}),a.jsx(Pn,{className:"w-4 h-4 text-bambu-gray -rotate-90 flex-shrink-0 ml-2"})]},P.serial))}),o&&a.jsx("p",{className:"mt-2 text-sm text-bambu-gray text-center",children:r(x?"printers.discovery.scanningSubnet":"printers.discovery.scanningNetwork")}),f&&!o&&c.length===0&&a.jsx("p",{className:"mt-2 text-sm text-bambu-gray text-center",children:r(x?"printers.discovery.noPrintersFoundSubnet":"printers.discovery.noPrintersFoundNetwork")}),f&&!o&&c.length>0&&M.length===0&&a.jsx("p",{className:"mt-2 text-sm text-bambu-gray text-center",children:r("printers.discovery.allConfigured")})]}),a.jsxs("form",{onSubmit:P=>{P.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:P=>s({...i,name:P.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:P=>s({...i,ip_address:P.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:P=>s({...i,serial_number:P.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:P=>s({...i,access_code:P.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:P=>s({...i,model:P.target.value}),children:[a.jsx("option",{value:"",children:r("printers.modal.selectModel")}),a.jsxs("optgroup",{label:"H2 Series",children:[a.jsx("option",{value:"H2C",children:"H2C"}),a.jsx("option",{value:"H2D",children:"H2D"}),a.jsx("option",{value:"H2D Pro",children:"H2D Pro"}),a.jsx("option",{value:"H2S",children:"H2S"})]}),a.jsxs("optgroup",{label:"X1 Series",children:[a.jsx("option",{value:"X1E",children:"X1E"}),a.jsx("option",{value:"X1C",children:"X1 Carbon"}),a.jsx("option",{value:"X1",children:"X1"})]}),a.jsxs("optgroup",{label:"P Series",children:[a.jsx("option",{value:"P2S",children:"P2S"}),a.jsx("option",{value:"P1S",children:"P1S"}),a.jsx("option",{value:"P1P",children:"P1P"})]}),a.jsxs("optgroup",{label:"A1 Series",children:[a.jsx("option",{value:"A1",children:"A1"}),a.jsx("option",{value:"A1 Mini",children:"A1 Mini"})]})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.modal.locationGroup")}),a.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:i.location||"",onChange:P=>s({...i,location:P.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:P=>s({...i,auto_archive:P.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(Me,{type:"button",variant:"secondary",onClick:t,className:"flex-1",children:r("common.cancel")}),a.jsx(Me,{type:"submit",className:"flex-1",children:r("printers.addPrinter")})]})]})]})})})}function v$e({printer:t,firmwareInfo:e,onClose:n}){const{t:r}=Dt(),i=Jt(),{showToast:s}=ln(),{hasPermission:o}=Pr(),l=o("firmware:update"),[c,d]=w.useState(null),[u,h]=w.useState(!1),[f,p]=w.useState(null),{data:x,isLoading:v}=Je({queryKey:["firmwarePrepare",t.id],queryFn:()=>B_.prepareUpload(t.id),staleTime:3e4,enabled:e.update_available&&l}),g=st({mutationFn:()=>B_.startUpload(t.id),onSuccess:()=>{h(!0);const _=setInterval(async()=>{try{const N=await B_.getUploadStatus(t.id);d(N),(N.status==="complete"||N.status==="error")&&(clearInterval(_),p(null),h(!1),N.status==="complete"&&(s(r("printers.firmwareModal.uploadedToast"),"success"),i.invalidateQueries({queryKey:["firmwareUpdate",t.id]})))}catch{}},2e3);p(_)},onError:_=>{s(r("printers.firmwareModal.uploadFailed",{error:_.message}),"error"),h(!1)}});w.useEffect(()=>()=>{f&&clearInterval(f)},[f]);const y=()=>{d(null),g.mutate()};return a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",children:a.jsx(wt,{className:"w-full max-w-md mx-4",children:a.jsxs(Nt,{children:[a.jsxs("div",{className:"flex items-start gap-3 mb-4",children:[a.jsx("div",{className:`p-2 rounded-full ${e.update_available?"bg-orange-500/20":"bg-status-ok/20"}`,children:e.update_available?a.jsx(ha,{className:"w-5 h-5 text-orange-400"}):a.jsx(br,{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})]})]}),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 ${e.update_available?"text-white":"text-status-ok"}`,children:e.current_version||r("common.unknown")})]}),e.update_available&&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:e.latest_version})]}),e.release_notes&&a.jsxs("details",{className:"mt-3 text-sm",open:!e.update_available,children:[a.jsx("summary",{className:`cursor-pointer hover:underline ${e.update_available?"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:e.release_notes})]})]}),e.update_available?v?a.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray text-sm mb-4",children:[a.jsx(at,{className:"w-4 h-4 animate-spin"}),r("printers.firmwareModal.checkingPrereqs")]}):x&&!u&&!c?a.jsx("div",{className:"mb-4",children:x.can_proceed?a.jsxs("div",{className:"flex items-center gap-2 text-bambu-green text-sm",children:[a.jsx(ai,{className:"w-4 h-4"}),r("printers.firmwareModal.sdCardReady")]}):a.jsx("div",{className:"space-y-1",children:x.errors.map((_,N)=>a.jsxs("div",{className:"flex items-center gap-2 text-red-400 text-sm",children:[a.jsx(Wa,{className:"w-4 h-4 flex-shrink-0"}),_]},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(Me,{variant:"secondary",onClick:n,children:c?.status==="complete"?r("printers.firmwareModal.done"):r("common.cancel")}),x?.can_proceed&&!u&&c?.status!=="complete"&&l&&a.jsx(Me,{onClick:y,disabled:g.isPending,children:g.isPending?a.jsxs(a.Fragment,{children:[a.jsx(at,{className:"w-4 h-4 animate-spin mr-2"}),r("printers.firmwareModal.starting")]}):a.jsxs(a.Fragment,{children:[a.jsx(ha,{className:"w-4 h-4 mr-2"}),r("printers.firmwareModal.uploadFirmware")]})})]})]})})})}function w$e({printer:t,onClose:e}){const{t:n}=Dt(),r=Jt(),{showToast:i}=ln(),[s,o]=w.useState({name:t.name,ip_address:t.ip_address,access_code:"",model:t.model||"",location:t.location||"",auto_archive:t.auto_archive}),l=st({mutationFn:d=>ne.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-center justify-center z-50",onClick:e,children:a.jsx(wt,{className:"w-full max-w-md",onClick:d=>d.stopPropagation(),children:a.jsxs(Nt,{children:[a.jsx("h2",{className:"text-xl font-semibold mb-4",children:n("printers.editPrinter")}),a.jsxs("form",{onSubmit:c,className:"space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.name")}),a.jsx("input",{type:"text",required:!0,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:s.name,onChange:d=>o({...s,name:d.target.value}),placeholder:n("printers.modal.myPrinter")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.ipAddress")}),a.jsx("input",{type:"text",required:!0,pattern:"(\\d{1,3}(\\.\\d{1,3}){3}|[a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?(\\.[a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?)*)",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:s.ip_address,onChange:d=>o({...s,ip_address:d.target.value}),placeholder:"192.168.1.100 or printer.local"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.serialNumber")}),a.jsx("input",{type:"text",disabled:!0,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray cursor-not-allowed",value:t.serial_number}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:n("printers.serialCannotBeChanged")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.accessCode")}),a.jsx("input",{type:"password",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:s.access_code,onChange:d=>o({...s,access_code:d.target.value}),placeholder:n("printers.accessCodePlaceholder")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.model")}),a.jsxs("select",{className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:s.model,onChange:d=>o({...s,model:d.target.value}),children:[a.jsx("option",{value:"",children:n("printers.modal.selectModel")}),a.jsxs("optgroup",{label:"H2 Series",children:[a.jsx("option",{value:"H2C",children:"H2C"}),a.jsx("option",{value:"H2D",children:"H2D"}),a.jsx("option",{value:"H2D Pro",children:"H2D Pro"}),a.jsx("option",{value:"H2S",children:"H2S"})]}),a.jsxs("optgroup",{label:"X1 Series",children:[a.jsx("option",{value:"X1E",children:"X1E"}),a.jsx("option",{value:"X1C",children:"X1 Carbon"}),a.jsx("option",{value:"X1",children:"X1"})]}),a.jsxs("optgroup",{label:"P Series",children:[a.jsx("option",{value:"P2S",children:"P2S"}),a.jsx("option",{value:"P1S",children:"P1S"}),a.jsx("option",{value:"P1P",children:"P1P"})]}),a.jsxs("optgroup",{label:"A1 Series",children:[a.jsx("option",{value:"A1",children:"A1"}),a.jsx("option",{value:"A1 Mini",children:"A1 Mini"})]})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Location / Group"}),a.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:s.location,onChange:d=>o({...s,location:d.target.value}),placeholder:n("printers.modal.locationPlaceholder")}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:n("printers.locationHelp")})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"checkbox",id:"edit_auto_archive",checked:s.auto_archive,onChange:d=>o({...s,auto_archive:d.target.checked}),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),a.jsx("label",{htmlFor:"edit_auto_archive",className:"text-sm text-bambu-gray",children:n("printers.modal.autoArchiveLabel")})]}),a.jsxs("div",{className:"flex gap-3 pt-4",children:[a.jsx(Me,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:n("common.cancel")}),a.jsx(Me,{type:"submit",className:"flex-1",disabled:l.isPending,children:l.isPending?n("common.saving"):n("printers.modal.saveChanges")})]})]})]})})})}function S$e(t){const{data:e}=Je({queryKey:["printerStatus",t],queryFn:()=>ne.getPrinterStatus(t),refetchInterval:3e4});return!e?.connected}function _$e({printer:t,plug:e,onPowerOn:n,isPowering:r}){const i=S$e(t.id),{data:s}=Je({queryKey:["smartPlugStatus",e.id],queryFn:()=>ne.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(mu,{className:"w-3 h-3"}),r?"...":"On"]})]}):null}function N$e(){const{t}=Dt(),[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"),[h,f]=w.useState(()=>localStorage.getItem("printerSortAsc")!=="false"),[p,x]=w.useState(()=>{const le=localStorage.getItem("printerCardSize");return le?parseInt(le,10):2}),v=p===1?"compact":"expanded",g=Jt(),{showToast:y}=ln(),{hasPermission:_}=Pr(),[N,T]=w.useState(()=>{const le=localStorage.getItem("openEmbeddedCameras");if(le)try{const _e=JSON.parse(le);return new Map(_e.map(se=>[se.id,se]))}catch{return new Map}return new Map});w.useEffect(()=>{const le=Array.from(N.values());le.length>0?localStorage.setItem("openEmbeddedCameras",JSON.stringify(le)):localStorage.removeItem("openEmbeddedCameras")},[N]);const{data:k,isLoading:M}=Je({queryKey:["printers"],queryFn:ne.getPrinters}),{data:C}=Je({queryKey:["settings"],queryFn:ne.getSettings});w.useEffect(()=>{C?.camera_view_mode==="window"&&N.size>0&&T(new Map)},[C?.camera_view_mode,N.size]);const{data:j}=Je({queryKey:["smart-plugs"],queryFn:ne.getSmartPlugs}),{data:P}=Je({queryKey:["maintenanceOverview"],queryFn:ne.getMaintenanceOverview,staleTime:60*1e3}),{data:E}=Je({queryKey:["spoolman-status"],queryFn:ne.getSpoolmanStatus,staleTime:60*1e3}),B=E?.enabled&&E?.connected,{data:O}=Je({queryKey:["unlinked-spools"],queryFn:ne.getUnlinkedSpools,enabled:!!B,staleTime:30*1e3}),z=O&&O.length>0,{data:D}=Je({queryKey:["linked-spools"],queryFn:ne.getLinkedSpools,enabled:!!B,staleTime:30*1e3}),$=D?.linked,{data:G}=Je({queryKey:["spool-assignments"],queryFn:()=>ne.getAssignments(),staleTime:30*1e3}),U=st({mutationFn:({printerId:le,amsId:_e,trayId:se})=>ne.unassignSpool(le,_e,se),onSuccess:()=>{g.invalidateQueries({queryKey:["spool-assignments"]})}}),W=(le,_e,se)=>G?.find(ze=>ze.printer_id===le&&ze.ams_id===Number(_e)&&ze.tray_id===Number(se)),Y=P?.reduce((le,_e)=>(le[_e.printer_id]={due_count:_e.due_count,warning_count:_e.warning_count,total_print_hours:_e.total_print_hours},le),{})||{},re=j?.reduce((le,_e)=>(_e.printer_id&&(le[_e.printer_id]=_e),le),{})||{},H=st({mutationFn:ne.createPrinter,onSuccess:()=>{g.invalidateQueries({queryKey:["printers"]}),g.invalidateQueries({queryKey:["maintenanceOverview"]}),n(!1)},onError:le=>y(le.message||t("printers.toast.failedToAdd"),"error")}),K=st({mutationFn:le=>ne.controlSmartPlug(le,"on"),onSuccess:()=>{g.invalidateQueries({queryKey:["smart-plugs"]}),c(null)},onError:()=>{c(null)}}),ee=()=>{const le=!r;i(le),localStorage.setItem("hideDisconnectedPrinters",String(le))},Z=le=>{u(le),localStorage.setItem("printerSortBy",le)},we=()=>{const le=!h;f(le),localStorage.setItem("printerSortAsc",String(le))},oe=()=>{switch(p){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"}},J=["S","M","L","XL"],je=w.useMemo(()=>{if(!k)return[];const le=[...k];switch(d){case"name":le.sort((_e,se)=>_e.name.localeCompare(se.name));break;case"model":le.sort((_e,se)=>(_e.model||"").localeCompare(se.model||""));break;case"location":le.sort((_e,se)=>{const ze=_e.location||"",V=se.location||"";return!ze&&V?1:ze&&!V?-1:ze.localeCompare(V)||_e.name.localeCompare(se.name)});break;case"status":le.sort((_e,se)=>{const ze=g.getQueryData(["printerStatus",_e.id]),V=g.getQueryData(["printerStatus",se.id]),X=me=>me?.connected?me.state==="RUNNING"?0:1:2;return X(ze)-X(V)});break}return h||le.reverse(),le},[k,d,h,g]),de=w.useMemo(()=>{if(d!=="location")return null;const le={};return je.forEach(_e=>{const se=_e.location||"Ungrouped";le[se]||(le[se]=[]),le[se].push(_e)}),le},[d,je]);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(x$e,{printers:k})]}),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:le=>Z(le.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:we,className:"p-1.5 rounded-lg hover:bg-bambu-dark-tertiary transition-colors",title:t(h?"printers.sort.descending":"printers.sort.ascending"),children:h?a.jsx(Mf,{className:"w-4 h-4 text-bambu-gray"}):a.jsx(lb,{className:"w-4 h-4 text-bambu-gray"})})]}),a.jsx("div",{className:"flex items-center bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:J.map((le,_e)=>{const se=_e+1,ze=p===se;return a.jsx("button",{onClick:()=>{x(se),localStorage.setItem("printerCardSize",String(se))},className:`px-2 py-1.5 text-xs font-medium transition-colors ${_e===0?"rounded-l-lg":""} ${_e===J.length-1?"rounded-r-lg":""} ${ze?"bg-bambu-green text-white":"text-bambu-gray hover:bg-bambu-dark-tertiary hover:text-white"}`,title:t(le==="S"?"printers.cardSize.small":le==="M"?"printers.cardSize.medium":le==="L"?"printers.cardSize.large":"printers.cardSize.extraLarge"),children:le},le)})}),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:ee,className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),t("printers.hideOffline")]}),r&&Object.keys(re).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(mu,{className:"w-4 h-4"}),t("printers.powerOn"),a.jsx(Pn,{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")}),k?.filter(le=>re[le.id]).map(le=>a.jsx(_$e,{printer:le,plug:re[le.id],onPowerOn:_e=>{c(_e),K.mutate(_e)},isPowering:l===re[le.id]?.id},le.id)),k?.filter(le=>re[le.id]).length===0&&a.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:"No printers with smart plugs"})]})]})]}),a.jsxs(Me,{onClick:()=>n(!0),disabled:!_("printers:create"),title:_("printers:create")?void 0:t("printers.permission.noAdd"),children:[a.jsx(Xn,{className:"w-4 h-4"}),t("printers.addPrinter")]})]})]}),M?a.jsx("div",{className:"text-center py-12 text-bambu-gray",children:t("common.loading")}):k?.length===0?a.jsx(wt,{children:a.jsxs(Nt,{className:"text-center py-12",children:[a.jsx("p",{className:"text-bambu-gray mb-4",children:t("printers.noPrintersConfigured")}),a.jsxs(Me,{onClick:()=>n(!0),disabled:!_("printers:create"),title:_("printers:create")?void 0:t("printers.permission.noAdd"),children:[a.jsx(Xn,{className:"w-4 h-4"}),t("printers.addPrinter")]})]})}):de?a.jsx("div",{className:"space-y-6",children:Object.entries(de).map(([le,_e])=>a.jsxs("div",{children:[a.jsxs("h2",{className:"text-lg font-semibold text-white mb-3 flex items-center gap-2",children:[a.jsx("span",{className:"w-2 h-2 rounded-full bg-bambu-green"}),le,a.jsxs("span",{className:"text-sm font-normal text-bambu-gray",children:["(",_e.length,")"]})]}),a.jsx("div",{className:`grid gap-4 ${p>=3?"gap-6":""} ${oe()}`,children:_e.map(se=>a.jsx(s9,{printer:se,hideIfDisconnected:r,maintenanceInfo:Y[se.id],viewMode:v,cardSize:p,amsThresholds:C?{humidityGood:Number(C.ams_humidity_good)||40,humidityFair:Number(C.ams_humidity_fair)||60,tempGood:Number(C.ams_temp_good)||28,tempFair:Number(C.ams_temp_fair)||35}:void 0,spoolmanEnabled:B,hasUnlinkedSpools:z,linkedSpools:$,spoolmanUrl:E?.url,onGetAssignment:W,onUnassignSpool:(ze,V,X)=>U.mutate({printerId:ze,amsId:V,trayId:X}),timeFormat:C?.time_format||"system",cameraViewMode:C?.camera_view_mode||"window",onOpenEmbeddedCamera:(ze,V)=>T(X=>new Map(X).set(ze,{id:ze,name:V})),checkPrinterFirmware:C?.check_printer_firmware!==!1},se.id))})]},le))}):a.jsx("div",{className:`grid gap-4 ${p>=3?"gap-6":""} ${oe()}`,children:je.map(le=>a.jsx(s9,{printer:le,hideIfDisconnected:r,maintenanceInfo:Y[le.id],viewMode:v,cardSize:p,spoolmanEnabled:B,hasUnlinkedSpools:z,linkedSpools:$,spoolmanUrl:E?.url,onGetAssignment:W,onUnassignSpool:(_e,se,ze)=>U.mutate({printerId:_e,amsId:se,trayId:ze}),amsThresholds:C?{humidityGood:Number(C.ams_humidity_good)||40,humidityFair:Number(C.ams_humidity_fair)||60,tempGood:Number(C.ams_temp_good)||28,tempFair:Number(C.ams_temp_fair)||35}:void 0,timeFormat:C?.time_format||"system",cameraViewMode:C?.camera_view_mode||"window",onOpenEmbeddedCamera:(_e,se)=>T(ze=>new Map(ze).set(_e,{id:_e,name:se})),checkPrinterFirmware:C?.check_printer_firmware!==!1},le.id))}),e&&a.jsx(y$e,{onClose:()=>n(!1),onAdd:le=>H.mutate(le),existingSerials:k?.map(le=>le.serial_number)||[]}),Array.from(N.values()).map((le,_e)=>a.jsx(ETe,{printerId:le.id,printerName:le.name,viewerIndex:_e,onClose:()=>T(se=>{const ze=new Map(se);return ze.delete(le.id),ze})},le.id))]})}function C$e(){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 of(t,e="bambu_studio"){let n;e==="orcaslicer"?n=`orcaslicer://open?file=${t}`:C$e()==="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 k$e={USD:"$",EUR:"€",GBP:"£",CHF:"Fr.",JPY:"¥",CNY:"¥",CAD:"$",AUD:"$",INR:"₹",HKD:"HK$",KRW:"₩",SEK:"kr",NOK:"kr",DKK:"kr",PLN:"zł",BRL:"R$",TWD:"NT$",SGD:"S$",NZD:"NZ$",MXN:"MX$",CZK:"Kč",THB:"฿",ZAR:"R",TRY:"₺",RUB:"₽"};function rl(t){return k$e[t.toUpperCase()]||t}const A$e=[{code:"USD",label:"USD ($)"},{code:"EUR",label:"EUR (€)"},{code:"GBP",label:"GBP (£)"},{code:"CHF",label:"CHF (Fr.)"},{code:"JPY",label:"JPY (¥)"},{code:"CNY",label:"CNY (¥)"},{code:"CAD",label:"CAD ($)"},{code:"AUD",label:"AUD ($)"},{code:"INR",label:"INR (₹)"},{code:"HKD",label:"HKD (HK$)"},{code:"KRW",label:"KRW (₩)"},{code:"SEK",label:"SEK (kr)"},{code:"NOK",label:"NOK (kr)"},{code:"DKK",label:"DKK (kr)"},{code:"PLN",label:"PLN (zł)"},{code:"BRL",label:"BRL (R$)"},{code:"TWD",label:"TWD (NT$)"},{code:"SGD",label:"SGD (S$)"},{code:"NZD",label:"NZD (NZ$)"},{code:"MXN",label:"MXN (MX$)"},{code:"CZK",label:"CZK (Kč)"},{code:"THB",label:"THB (฿)"},{code:"ZAR",label:"ZAR (R)"},{code:"TRY",label:"TRY (₺)"},{code:"RUB",label:"RUB (₽)"}],o9=768;function xne(){const[t,e]=w.useState(()=>typeof window<"u"?window.innerWidth{const n=window.matchMedia(`(max-width: ${o9-1}px)`),r=i=>{e(i.matches)};return e(n.matches),n.addEventListener("change",r),()=>n.removeEventListener("change",r)},[]),t}function g4({archiveId:t,libraryFileId:e,title:n,fileType:r,onClose:i}){const{t:s}=Dt(),{data:o}=Je({queryKey:["settings"],queryFn:ne.getSettings}),l=o?.preferred_slicer||"bambu_studio",c=e!=null,[d,u]=w.useState(null),[h,f]=w.useState(null),[p,x]=w.useState(!0),[v,g]=w.useState(null),[y,_]=w.useState(!1),[N,T]=w.useState(null),[k,M]=w.useState(0),[C,j]=w.useState(!1),[P,E]=w.useState(null),[B,O]=w.useState(!1),[z,D]=w.useState(!1),$=w.useRef(null),G=w.useRef(null),U=10,W=160,Y=240,re=.35;w.useEffect(()=>{const Ce=ge=>{ge.key==="Escape"&&i()};return window.addEventListener("keydown",Ce),()=>window.removeEventListener("keydown",Ce)},[i]),w.useEffect(()=>{if(x(!0),c){const Ce=(r||"").toLowerCase(),ge=Ce==="3mf"||Ce==="stl",L=Ce==="gcode"||Ce==="3mf";f({has_model:ge,has_gcode:L,has_source:!1,build_volume:{x:256,y:256,z:256},filament_colors:[]}),u(ge?"3d":L?"gcode":null),x(!1);return}if(!t){f(null),u(null),x(!1);return}ne.getArchiveCapabilities(t).then(Ce=>{f(Ce),Ce.has_model?u("3d"):Ce.has_gcode&&u("gcode"),x(!1)}).catch(()=>{f({has_model:!0,has_gcode:!1,has_source:!1,build_volume:{x:256,y:256,z:256},filament_colors:[]}),u("3d"),x(!1)})},[t,r,c]),w.useEffect(()=>{if(_(!0),T(null),M(0),c){const Ce=(r||"").toLowerCase();if(!e||Ce!=="3mf"){g(null),_(!1);return}ne.getLibraryFilePlates(e).then(ge=>g(ge)).catch(()=>g(null)).finally(()=>_(!1));return}if(!t){g(null),_(!1);return}ne.getArchivePlates(t).then(Ce=>g(Ce)).catch(()=>g(null)).finally(()=>_(!1))},[t,r,c,e]);const H=w.useMemo(()=>v?.plates??[],[v]),K=(v?.is_multi_plate??!1)&&H.length>1,ee=C&&K,Z=N==null?null:H.find(Ce=>Ce.index===N)??null,we=Ce=>Ce.object_count??Ce.objects?.length??0,oe=H.reduce((Ce,ge)=>Ce+we(ge),0),J=Z?we(Z):oe,je=Z?s("modelViewer.plateNumber",{number:Z.index}):s("modelViewer.allPlates"),de=H.length>0,le=w.useRef(null),_e=w.useRef(null),[se,ze]=w.useState(10),[V,X]=w.useState(3),me=H.length>se,Q=Math.max(1,Math.ceil(H.length/se)),ie=me?H.slice(k*se,(k+1)*se):H;w.useEffect(()=>{if(!ee){ze(10),X(3);return}const Ce=le.current,ge=_e.current;if(!Ce||!ge)return;let L=0;const R=()=>{const pe=ge.clientWidth,Be=Math.floor(pe/210),Ie=Math.max(3,Math.min(5,Be||3));X(Te=>Te===Ie?Te:Ie);const $e=window.getComputedStyle(Ce),Re=Number.parseFloat($e.rowGap||"0"),xe=Ce.querySelector("button")?.getBoundingClientRect().height??44,Ne=ge.clientHeight,ve=Math.max(1,Math.floor((Ne+Re)/(xe+Re)))*Ie,Ge=Math.max(1,ve-1);ze(Te=>Te===Ge?Te:Ge)},q=()=>{L&&cancelAnimationFrame(L),L=requestAnimationFrame(R)};q();const ce=new ResizeObserver(q);return ce.observe(ge),ce.observe(Ce),()=>{L&&cancelAnimationFrame(L),ce.disconnect()}},[ee,H.length]),w.useEffect(()=>{if(!me){M(0);return}M(Ce=>Math.min(Ce,Q-1))},[H.length,me,Q]),w.useEffect(()=>{if(!me||N==null)return;const Ce=H.findIndex(L=>L.index===N);if(Ce<0)return;const ge=Math.floor(Ce/se);M(L=>L===ge?L:ge)},[H,se,N,me]),w.useEffect(()=>{if(!ee){E(null),D(!1);return}if(z)return;const Ce=$.current,ge=G.current;if(!Ce||!ge)return;const L=Ce.clientHeight;if(!L)return;const R=Math.max(Y,L*re),q=Math.max(W,L-U-R),ce=Math.min(ge.scrollHeight,q);E(Math.max(W,ce))},[ee,z,H.length,k,U,W,Y,re]),w.useEffect(()=>{if(!B)return;const Ce=L=>{const R=$.current;if(!R)return;const q=R.getBoundingClientRect(),ce=q.height;if(!ce)return;const pe=Math.max(Y,ce*re),te=Math.max(W,ce-U-pe),Be=Math.min(te,Math.max(W,L.clientY-q.top));E(Be)},ge=()=>{O(!1),D(!0)};return document.addEventListener("mousemove",Ce),document.addEventListener("mouseup",ge),document.body.style.cursor="row-resize",document.body.style.userSelect="none",()=>{document.removeEventListener("mousemove",Ce),document.removeEventListener("mouseup",ge),document.body.style.cursor="",document.body.style.userSelect=""}},[B,U,W,Y,re]);const ue=c?(r||"").toLowerCase()==="3mf":!0,Le=async()=>{if(!ue)return;const Ce=n||"model";try{if(c){const{token:ge}=await ne.createLibrarySlicerToken(e),L=ne.getLibrarySlicerDownloadUrl(e,ge,Ce);of(`${window.location.origin}${L}`,l)}else{const{token:ge}=await ne.createArchiveSlicerToken(t),L=ne.getArchiveSlicerDownloadUrl(t,ge,Ce);of(`${window.location.origin}${L}`,l)}}catch{if(c){const ge=`${window.location.origin}${ne.getLibraryFileDownloadUrl(e)}`;of(ge,l)}else{const ge=`${window.location.origin}${ne.getArchiveForSlicer(t,Ce)}`;of(ge,l)}}};return a.jsx("div",{className:`fixed inset-0 bg-black/70 flex items-center justify-center z-50 ${C?"p-0":"p-8"}`,onClick:i,children:a.jsxs("div",{className:`bg-bambu-dark-secondary border border-bambu-dark-tertiary w-full flex flex-col ${C?"h-full max-w-none rounded-none":"h-[80vh] max-w-4xl rounded-xl"}`,onClick:Ce=>Ce.stopPropagation(),children:[a.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-1 mr-4",children:[a.jsx("h2",{className:"text-lg font-semibold text-white truncate",children:n}),de&&a.jsxs("span",{className:"text-xs text-bambu-gray bg-bambu-dark-tertiary/70 px-2 py-1 rounded whitespace-nowrap",children:[je,": ",s("modelViewer.objectCount",{count:J})]})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs(Me,{variant:"secondary",size:"sm",onClick:Le,disabled:!ue,children:[a.jsx(Zr,{className:"w-4 h-4"}),s("modelViewer.openInSlicer")]}),a.jsx(Me,{variant:"secondary",size:"sm",onClick:()=>j(Ce=>!Ce),title:C?"Exit fullscreen":"Enter fullscreen",children:C?a.jsx(kF,{className:"w-4 h-4"}):a.jsx(GC,{className:"w-4 h-4"})}),a.jsx(Me,{variant:"ghost",size:"sm",onClick:i,children:a.jsx(Rt,{className:"w-5 h-5"})})]})]}),h&&a.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary",children:[a.jsxs("button",{onClick:()=>h.has_model&&u("3d"),disabled:!h.has_model,className:`flex items-center gap-2 px-6 py-3 text-sm font-medium transition-colors ${d==="3d"?"text-bambu-green border-b-2 border-bambu-green":h.has_model?"text-bambu-gray hover:text-white":"text-bambu-gray/30 cursor-not-allowed"}`,children:[a.jsx(ai,{className:"w-4 h-4"}),s("modelViewer.tabs.model"),!h.has_model&&a.jsxs("span",{className:"text-xs",children:["(",s("modelViewer.notAvailable"),")"]})]}),a.jsxs("button",{onClick:()=>h.has_gcode&&u("gcode"),disabled:!h.has_gcode,className:`flex items-center gap-2 px-6 py-3 text-sm font-medium transition-colors ${d==="gcode"?"text-bambu-green border-b-2 border-bambu-green":h.has_gcode?"text-bambu-gray hover:text-white":"text-bambu-gray/30 cursor-not-allowed"}`,children:[a.jsx(Dhe,{className:"w-4 h-4"}),s("modelViewer.tabs.gcode"),!h.has_gcode&&a.jsxs("span",{className:"text-xs",children:["(",s("modelViewer.notSliced"),")"]})]})]}),a.jsx("div",{className:"flex-1 overflow-hidden p-4",children:p?a.jsx("div",{className:"w-full h-full flex items-center justify-center",children:a.jsx(at,{className:"w-8 h-8 animate-spin text-bambu-green"})}):d==="3d"&&h?a.jsxs("div",{ref:$,className:`w-full h-full flex flex-col ${ee?"gap-0 min-h-0":"gap-3"}`,children:[K&&a.jsxs("div",{ref:G,style:ee&&P!=null?{height:P}:void 0,className:`rounded-lg border border-bambu-dark-tertiary bg-bambu-dark p-3 ${ee?"flex flex-col shrink-0":""}`,children:[a.jsxs("div",{className:"flex items-center gap-2 text-sm text-bambu-gray mb-2",children:[a.jsx(oi,{className:"w-4 h-4"}),s("modelViewer.plates"),y&&a.jsx(at,{className:"w-3 h-3 animate-spin"})]}),a.jsxs("div",{className:ee?"flex flex-col min-h-0 flex-1":void 0,children:[a.jsx("div",{ref:_e,className:ee?"min-h-0 overflow-hidden pr-1 flex-1":void 0,children:a.jsxs("div",{ref:le,className:ee?"grid gap-2":"grid grid-cols-2 md:grid-cols-3 gap-2",style:ee?{gridTemplateColumns:`repeat(${V}, minmax(0, 1fr))`}:void 0,children:[a.jsxs("button",{type:"button",onClick:()=>T(null),className:`flex items-center rounded-lg border text-left transition-colors ${ee?"gap-1.5 p-1.5 w-full":"gap-2 p-2"} ${N==null?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark-secondary hover:border-bambu-gray"}`,children:[a.jsx("div",{className:`rounded bg-bambu-dark-tertiary flex items-center justify-center ${ee?"w-8 h-8":"w-10 h-10"}`,children:a.jsx(oi,{className:`${ee?"w-4 h-4":"w-5 h-5"} text-bambu-gray`})}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:`${ee?"text-xs":"text-sm"} text-white font-medium truncate`,children:s("modelViewer.allPlates")}),a.jsx("p",{className:`${ee?"text-[10px]":"text-xs"} text-bambu-gray truncate`,children:s("modelViewer.plateCount",{count:H.length})})]}),N==null&&a.jsx(Jr,{className:`${ee?"w-3.5 h-3.5":"w-4 h-4"} text-bambu-green flex-shrink-0`})]}),ie.map(Ce=>a.jsxs("button",{type:"button",onClick:()=>T(Ce.index),className:`flex items-center rounded-lg border text-left transition-colors ${ee?"gap-1.5 p-1.5 w-full":"gap-2 p-2"} ${N===Ce.index?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark-secondary hover:border-bambu-gray"}`,children:[Ce.has_thumbnail&&Ce.thumbnail_url?a.jsx("img",{src:Ce.thumbnail_url,alt:`Plate ${Ce.index}`,className:`${ee?"w-8 h-8":"w-10 h-10"} rounded object-cover bg-bambu-dark-tertiary`}):a.jsx("div",{className:`rounded bg-bambu-dark-tertiary flex items-center justify-center ${ee?"w-8 h-8":"w-10 h-10"}`,children:a.jsx(oi,{className:`${ee?"w-4 h-4":"w-5 h-5"} text-bambu-gray`})}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:`${ee?"text-xs":"text-sm"} text-white font-medium truncate`,children:Ce.name||s("modelViewer.plateNumber",{number:Ce.index})}),a.jsx("p",{className:`${ee?"text-[10px]":"text-xs"} text-bambu-gray truncate`,children:s("modelViewer.objectCount",{count:Ce.object_count??Ce.objects?.length??0})})]}),N===Ce.index&&a.jsx(Jr,{className:`${ee?"w-3.5 h-3.5":"w-4 h-4"} text-bambu-green flex-shrink-0`})]},Ce.index))]})}),(Z||me)&&a.jsxs("div",{className:"mt-auto pt-3 flex items-center gap-4 text-xs text-bambu-gray overflow-x-auto",children:[Z&&a.jsxs("div",{className:"flex items-center gap-3 whitespace-nowrap",children:[a.jsx("span",{children:s("modelViewer.plateNumber",{number:Z.index})}),Z.print_time_seconds!=null&&a.jsx("span",{children:s("modelViewer.eta",{minutes:Math.round(Z.print_time_seconds/60)})}),Z.filament_used_grams!=null&&a.jsxs("span",{children:[Z.filament_used_grams.toFixed(1)," g"]}),Z.filaments.length>0&&a.jsx("span",{children:s("modelViewer.filamentCount",{count:Z.filaments.length})})]}),me&&a.jsxs("div",{className:`flex items-center gap-2 whitespace-nowrap ${Z?"ml-auto":""}`,children:[a.jsx("span",{children:s("modelViewer.pagination.pageOf",{current:k+1,total:Q})}),a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx("button",{type:"button",onClick:()=>M(Ce=>Math.max(Ce-1,0)),disabled:k===0,className:`px-2 py-1 rounded border text-xs ${k===0?"border-bambu-dark-tertiary text-bambu-gray/40 cursor-not-allowed":"border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,children:s("modelViewer.pagination.prev")}),(()=>{let ge=Math.max(0,k-Math.floor(2.5));const L=Math.min(Q,ge+5);L-ge<5&&(ge=Math.max(0,L-5));const R=Array.from({length:L-ge},(q,ce)=>ge+ce);return a.jsxs(a.Fragment,{children:[ge>0&&a.jsx("button",{type:"button",onClick:()=>M(0),className:`px-2 py-1 rounded border text-xs ${k===0?"border-bambu-green text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,children:"1"}),ge>1&&a.jsx("span",{className:"px-1",children:"…"}),R.map(q=>a.jsx("button",{type:"button",onClick:()=>M(q),className:`px-2 py-1 rounded border text-xs ${k===q?"border-bambu-green text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,children:q+1},q)),LM(Q-1),className:`px-2 py-1 rounded border text-xs ${k===Q-1?"border-bambu-green text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,children:Q})]})})(),a.jsx("button",{type:"button",onClick:()=>M(Ce=>Math.min(Ce+1,Q-1)),disabled:k>=Q-1,className:`px-2 py-1 rounded border text-xs ${k>=Q-1?"border-bambu-dark-tertiary text-bambu-gray/40 cursor-not-allowed":"border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,children:s("modelViewer.pagination.next")})]})]})]})]})]}),ee&&a.jsx("div",{role:"separator","aria-orientation":"horizontal",onMouseDown:Ce=>{Ce.preventDefault(),O(!0),D(!0)},className:`h-2 cursor-row-resize flex items-center justify-center ${B?"bg-bambu-dark-tertiary":"bg-bambu-dark-secondary/60 hover:bg-bambu-dark-tertiary"}`,children:a.jsx("div",{className:"w-12 h-1 rounded-full bg-bambu-gray/50"})}),a.jsx("div",{className:`flex-1 ${ee?"min-h-0":""}`,children:a.jsx(xX,{url:c?ne.getLibraryFileDownloadUrl(e):h.has_source?ne.getSource3mfDownloadUrl(t):ne.getArchiveDownload(t),fileType:r,buildVolume:h.build_volume,filamentColors:h.filament_colors,selectedPlateId:N,className:"w-full h-full"})})]}):d==="gcode"&&h?a.jsx(eQ,{gcodeUrl:c?ne.getLibraryFileGcodeUrl(e):ne.getArchiveGcode(t),filamentColors:h.filament_colors,className:"w-full h-full"}):a.jsx("div",{className:"w-full h-full flex items-center justify-center text-bambu-gray",children:s("modelViewer.noPreview")})})]})})}const UN={"000000":"Black","001489":"Blue","002e96":"Blue","0047bb":"Blue","00482b":"Pine Green","004ea8":"Blue","0056b8":"Cobalt Blue","0069b1":"Lake Blue","0072ce":"Blue","0078bf":"Marine Blue","0085ad":"Light Blue","0086d6":"Cyan","008bda":"Blue","009639":"Green","009bd8":"Cyan","009fa1":"Teal","00a6a0":"Green","00ae42":"Bambu Green","00b1b7":"Turquoise","00bb31":"Green","018814":"Candy Green","042f56":"Dark Blue","0a2989":"Blue","0a2ca5":"Blue","0c2340":"Navy Blue","0c3b95":"Blue",101820:"Black","147bd1":"Blue","164b35":"Green","16b08e":"Malachite Green","1d7c6a":"Oxide Green Metallic","1f79e5":"Lake Blue","2140b4":"Blue","25282a":"Black","2842ad":"Royal Blue","2d2b28":"Onyx Black Sparkle",324585:"Indigo Blue",353533:"Gray","39541a":"Forest Green","39699e":"Cobalt Blue Metallic","3b665e":"Green","3f5443":"Alpine Green Sparkle","3f8e43":"Mistletoe Green",424379:"Nebulae","43403d":"Iron Gray Metallic",482960:"Indigo Purple","483d8b":"Royal Purple Sparkle","489fdf":"Azure","4c241c":"Rosewood","4ce4a0":"Green","4d3324":"Dark Chocolate","4d5054":"Lava Gray","4dafda":"Cyan","4f3f24":"Black Walnut",515151:"Dark Gray","515a6c":"Gray",545454:"Dark Gray",565656:"Titan Gray","56b7e6":"Sky Blue",583061:"Violet Purple","5898dd":"Blue",594177:"Purple","5b492f":"Brown","5b6579":"Blue Gray","5c9748":"Matcha Green","5e43b7":"Purple","5e4b3c":"Copper","5f6367":"Titan Gray","61b0ff":"Translucent Light Blue","61bf36":"Green","61c680":"Grass Green","6667ab":"Lavender Blue","684a43":"Brown",686865:"Black","68724d":"Dark Green",688197:"Blue Gray","69398e":"Iris Purple","6e88bc":"Jeans Blue","6ee53c":"Lime Green","6f5034":"Cocoa Brown","7248bd":"Lavender","748c45":"Translucent Olive",757575:"Nardo Gray","75aed8":"Blue","77edd7":"Translucent Teal","789d4a":"Olive","792b36":"Crimson Red Sparkle","7ac0e9":"Glow Blue","7ae1bf":"Mint","7cd82b":"Lime Green","7d6556":"Dark Brown","8344b0":"Purple","847d48":"Bronze","854ce4":"Purple","8671cb":"Purple",875718:"Peanut Brown","87909a":"Silver","898d8d":"Gray","8a949e":"Gray","8e8e8e":"Translucent Gray","8e9089":"Gray","90ff1a":"Neon Green",918669:"Classic Birch",939393:"Gray",950051:"Plum","951e23":"Burgundy Red",959698:"Silver","96d8af":"Light Jade","96dcb9":"Mint","995f11":"Clay Brown","999d9d":"Gray","9b9ea0":"Ash Gray","9d2235":"Maroon Red","9d432c":"Brown","9e007e":"Purple","9ea2a2":"Gray","9f332a":"Brick Red",a1ffac:"Glow Green",a3d8e1:"Ice Blue",a6a9aa:"Silver",a8a8aa:"Gray",a8c6ee:"Baby Blue",aa6443:"Copper Brown Metallic",ad4e38:"Red Granite",adb1b2:"Gray",ae835b:"Caramel",ae96d4:"Lilac Purple",af1685:"Purple",afb1ae:"Gray",b15533:"Terracotta",b28b33:"Gold",b39b84:"Iridium Gold Metallic",b50011:"Red",b8acd6:"Lavender",b8cde9:"Ice Blue",ba9594:"Rose Gold",bb3d43:"Dark Red",bc0900:"Red",becf00:"Bright Green",c0df16:"Green",c12e1f:"Red",c2e189:"Apple Green",c3e2d6:"Light Cyan",c5ed48:"Lime",c6001a:"Red",c6c6c6:"Gray",c8102e:"Red",c8c8c8:"Silver",c98935:"Ochre Yellow",c9a381:"Translucent Brown",cbc6b8:"Bone White",cdceca:"Gray",cea629:"Classic Gold Sparkle",d02727:"Candy Red",d1d3d5:"Light Gray",d32941:"Red",d3b7a7:"Latte Brown",d6001c:"Red",d6abff:"Translucent Purple",d6cca3:"White Oak",dc3a27:"Orange",dd3c22:"Vermilion Red",de4343:"Scarlet Red",dfd1a7:"Beige",e02928:"Red",e4bd68:"Gold",e5b03d:"Gold",e83100:"Red",e8afcf:"Sakura Pink",e8dbb7:"Desert Tan",eaeae4:"White",eaeceb:"Silver",ec008c:"Magenta",ed0000:"Red",eeb1c1:"Pink",efe255:"Yellow",f0f1a8:"Clear",f17b8f:"Glow Pink",f3cfb2:"Champagne",f3e600:"Yellow",f48438:"Orange",f4a925:"Gold",f4d53f:"Yellow",f4ee2a:"Yellow",f5547c:"Hot Pink",f55a74:"Pink",f5b6cd:"Cherry Pink",f5dbab:"Mellow Yellow",f5f1dd:"White",f68b1b:"Neon Orange",f74e02:"Orange",f75403:"Orange",f7ada6:"Pink",f7d959:"Lemon Yellow",f7e6de:"Beige",f7f3f0:"White Marble",f8ff80:"Glow Yellow",f99963:"Mandarin Orange",f9c1bd:"Translucent Pink",f9dfb9:"Cream",f9ef41:"Yellow",f9f7f2:"Nature",f9f7f4:"White",fce300:"Yellow",fce900:"Yellow",fec600:"Sunflower Yellow",fedb00:"Yellow",ff4800:"Orange",ff671f:"Orange",ff6a13:"Orange",ff7f41:"Orange",ff9016:"Pumpkin Orange",ff911a:"Translucent Orange",ff9d5b:"Glow Orange",ffb549:"Sunflower Yellow",ffc72c:"Tangerine Yellow",ffce00:"Yellow",ffd00b:"Yellow",ffe133:"Yellow",fffaf2:"White",ffffff:"White"};function T$e(t){if(!t||t.length<6)return"Unknown";const e=t.replace("#",""),n=parseInt(e.substring(0,2),16),r=parseInt(e.substring(2,4),16),i=parseInt(e.substring(4,6),16),s=Math.max(n,r,i)/255,o=Math.min(n,r,i)/255,l=(s+o)/2;let c=0,d=0;if(s!==o){const u=s-o;d=l>.5?u/(2-s-o):u/(s+o);const h=n/255,f=r/255,p=i/255;s===h?c=((f-p)/u+(f.85?"White":d<.15?l<.4?"Dark Gray":l>.6?"Light Gray":"Gray":c<15||c>=345?"Red":c<45?"Orange":c<70?"Yellow":c<150?"Green":c<200?"Cyan":c<260?"Blue":c<290?"Purple":"Pink"}function vf(t){const e=t.replace("#","").toLowerCase().substring(0,6);return UN[e]?UN[e]:T$e(t)}function b4(t,e){if(t&&!/^[A-Z]\d+-[A-Z]\d+$/.test(t))return t;if(e&&e.length>=6){const n=e.substring(0,6).toLowerCase();if(UN[n])return UN[n]}return null}function sA(t){const e=[],n=t?.ams_extruder_map,r=n&&Object.keys(n).length>0;t?.ams?.forEach(i=>{const s=i.tray.length===1;i.tray.forEach(o=>{if(o.tray_type){const l=Z7(o.tray_color);e.push({type:o.tray_type,color:l,colorName:vf(l),amsId:i.id,trayId:o.id,isHt:s,isExternal:!1,label:m4(i.id,o.id,s,!1),globalTrayId:f4(i.id,o.id,!1),trayInfoIdx:o.tray_info_idx||"",extruderId:n?.[String(i.id)]})}})});for(const i of t?.vt_tray??[])if(i.tray_type){const s=Z7(i.tray_color),o=i.id??254,l=(t?.vt_tray?.length??0)>1;e.push({type:i.tray_type,color:s,colorName:vf(s),amsId:-1,trayId:o-254,isHt:!1,isExternal:!0,label:l?o===254?"Ext-L":"Ext-R":"External",globalTrayId:o,trayInfoIdx:i.tray_info_idx||"",extruderId:r?255-o:void 0})}return e}function l9(t,e){if(!t?.filaments||t.filaments.length===0)return;const n=sA(e);if(n.length===0)return;const r=new Set,i=t.filaments.map(l=>{const c=l.tray_info_idx||"";let d=n.filter(v=>!r.has(v.globalTrayId));l.nozzle_id!=null&&(d=d.filter(v=>v.extruderId===l.nozzle_id));let u,h,f,p;if(c){const v=d.filter(g=>g.trayInfoIdx===c);v.length===1?u=v[0]:v.length>1&&(h=v.find(g=>g.type?.toUpperCase()===l.type?.toUpperCase()&&Ra(g.color)===Ra(l.color)),h||(f=v.find(g=>g.type?.toUpperCase()===l.type?.toUpperCase()&&Rc(g.color,l.color))),!h&&!f&&(p=v.find(g=>g.type?.toUpperCase()===l.type?.toUpperCase())))}!u&&!h&&!f&&!p&&(h=d.find(v=>v.type?.toUpperCase()===l.type?.toUpperCase()&&Ra(v.color)===Ra(l.color)),h||(f=d.find(v=>v.type?.toUpperCase()===l.type?.toUpperCase()&&Rc(v.color,l.color))),!h&&!f&&(p=d.find(v=>v.type?.toUpperCase()===l.type?.toUpperCase())));const x=u||h||f||p||void 0;return x&&r.add(x.globalTrayId),{slot_id:l.slot_id,globalTrayId:x?.globalTrayId??-1}}),s=Math.max(...i.map(l=>l.slot_id||0));if(s<=0)return;const o=new Array(s).fill(-1);return i.forEach(l=>{l.slot_id&&l.slot_id>0&&(o[l.slot_id-1]=l.globalTrayId)}),o}function M$e(t){return w.useMemo(()=>sA(t),[t])}function yne(t,e,n){const r=M$e(e),i=w.useMemo(()=>{if(!t?.filaments||t.filaments.length===0)return[];const c=new Set(Object.values(n));return t.filaments.map(d=>{const u=d.slot_id||0;if(u>0&&n[u]!==void 0){const M=n[u],C=r.find(j=>j.globalTrayId===M);if(C){const j=C.type?.toUpperCase()===d.type?.toUpperCase(),P=Ra(C.color)===Ra(d.color)||Rc(C.color,d.color);let E;return j&&P?E="match":j?E="type_only":E="mismatch",{...d,loaded:C,hasFilament:!0,typeMatch:j,colorMatch:P,status:E,isManual:!0}}}const h=d.tray_info_idx||"";let f=r.filter(M=>!c.has(M.globalTrayId));d.nozzle_id!=null&&(f=f.filter(M=>M.extruderId===d.nozzle_id));let p,x,v,g;if(h){const M=f.filter(C=>C.trayInfoIdx===h);M.length===1?p=M[0]:M.length>1&&(x=M.find(C=>C.type?.toUpperCase()===d.type?.toUpperCase()&&Ra(C.color)===Ra(d.color)),x||(v=M.find(C=>C.type?.toUpperCase()===d.type?.toUpperCase()&&Rc(C.color,d.color))),!x&&!v&&(g=M.find(C=>C.type?.toUpperCase()===d.type?.toUpperCase())))}!p&&!x&&!v&&!g&&(x=f.find(M=>M.type?.toUpperCase()===d.type?.toUpperCase()&&Ra(M.color)===Ra(d.color)),x||(v=f.find(M=>M.type?.toUpperCase()===d.type?.toUpperCase()&&Rc(M.color,d.color))),!x&&!v&&(g=f.find(M=>M.type?.toUpperCase()===d.type?.toUpperCase())));const y=p||x||v||g||void 0;y&&c.add(y.globalTrayId);const _=!!y,N=_,T=!!p||!!x||!!v;let k;return p||x||v?k="match":g?k="type_only":k="mismatch",{...d,loaded:y,hasFilament:_,typeMatch:N,colorMatch:T,status:k,isManual:!1}})},[t,r,n]),s=w.useMemo(()=>{if(i.length===0)return;const c=Math.max(...i.map(u=>u.slot_id||0));if(c<=0)return;const d=new Array(c).fill(-1);return i.forEach(u=>{u.slot_id&&u.slot_id>0&&(d[u.slot_id-1]=u.loaded?.globalTrayId??-1)}),d},[i]),o=i.some(c=>c.status==="mismatch"),l=i.some(c=>c.status==="type_only");return{loadedFilaments:r,filamentComparison:i,amsMapping:s,hasTypeMismatch:o,hasColorMismatch:l}}function P$e(t,e,n){if(!t||t.length===0)return{exactMatches:0,typeOnlyMatches:0,missingTypes:0,totalSlots:0,status:"full"};let r=0,i=0,s=0;const o=new Set(Object.values(n));for(const d of t){const u=d.slot_id||0;if(u>0&&n[u]!==void 0){const g=n[u],y=e.find(_=>_.globalTrayId===g);if(y){const _=y.type?.toUpperCase()===d.type?.toUpperCase(),N=Ra(y.color)===Ra(d.color)||Rc(y.color,d.color);_&&N?r++:_?i++:s++;continue}}let h=e.filter(g=>!o.has(g.globalTrayId));if(d.nozzle_id!=null){const g=h.filter(y=>y.extruderId===d.nozzle_id);g.length>0&&(h=g)}const f=h.find(g=>g.type?.toUpperCase()===d.type?.toUpperCase()&&Ra(g.color)===Ra(d.color)),p=f?void 0:h.find(g=>g.type?.toUpperCase()===d.type?.toUpperCase()&&Rc(g.color,d.color)),x=f||p?void 0:h.find(g=>g.type?.toUpperCase()===d.type?.toUpperCase()),v=f??p??x;v&&o.add(v.globalTrayId),f||p?r++:x?i++:s++}const l=t.length;let c="full";return s>0?c="missing":i>0&&(c="partial"),{exactMatches:r,typeOnlyMatches:i,missingTypes:s,totalSlots:l,status:c}}function E$e(t,e,n){if(!t?.filaments||t.filaments.length===0)return;const r=sA(e);if(r.length===0)return;const i=new Set(Object.values(n)),s=[];for(const c of t.filaments){const d=c.slot_id||0;if(d>0&&n[d]!==void 0){s.push({slot_id:d,globalTrayId:n[d]});continue}let u=r.filter(v=>!i.has(v.globalTrayId));if(c.nozzle_id!=null){const v=u.filter(g=>g.extruderId===c.nozzle_id);v.length>0&&(u=v)}const h=u.find(v=>v.type?.toUpperCase()===c.type?.toUpperCase()&&Ra(v.color)===Ra(c.color)),f=h?void 0:u.find(v=>v.type?.toUpperCase()===c.type?.toUpperCase()&&Rc(v.color,c.color)),p=h||f?void 0:u.find(v=>v.type?.toUpperCase()===c.type?.toUpperCase()),x=h??f??p;x&&i.add(x.globalTrayId),s.push({slot_id:d,globalTrayId:x?.globalTrayId??-1})}const o=Math.max(...s.map(c=>c.slot_id||0));if(o<=0)return;const l=new Array(o).fill(-1);return s.forEach(c=>{c.slot_id&&c.slot_id>0&&(l[c.slot_id-1]=c.globalTrayId)}),l}const c9={useDefault:!0,manualMappings:{},autoConfigured:!1};function j$e(t,e,n,r,i,s){const o=zC({queries:t.map(x=>({queryKey:["printer-status",x],queryFn:()=>ne.getPrinterStatus(x),enabled:t.length>0,staleTime:5e3}))}),l=w.useMemo(()=>t.map((x,v)=>{const g=o[v],y=g?.data,N=e?.find(E=>E.id===x)?.name||`Printer ${x}`,T=sA(y),k=i[x]||c9,M=l9(n,y),C=k.useDefault?r:k.manualMappings,j=E$e(n,y,C),P=P$e(n?.filaments,T,C);return{printerId:x,printerName:N,status:y,isLoading:g?.isLoading??!1,loadedFilaments:T,autoMapping:M,finalMapping:j,matchStatus:P.status,exactMatches:P.exactMatches,typeOnlyMatches:P.typeOnlyMatches,missingTypes:P.missingTypes,totalSlots:P.totalSlots,config:k}}),[t,o,e,n,i,r]),c=o.some(x=>x.isLoading),d=(x,v)=>{s(g=>({...g,[x]:{...g[x]||c9,...v}}))},u=x=>{const v=l.find(_=>_.printerId===x);if(!v||!v.status||!n?.filaments)return;const g=l9(n,v.status);if(!g)return;const y={};g.forEach((_,N)=>{_!==-1&&(y[N+1]=_)}),d(x,{useDefault:!1,manualMappings:y,autoConfigured:!0})},h=()=>{for(const x of t)u(x)},f=x=>l.find(g=>g.printerId===x)?.finalMapping,p=l.every(x=>x.matchStatus!=="missing");return{printerResults:l,isLoading:c,perPrinterConfigs:i,updatePrinterConfig:d,autoConfigureAll:h,autoConfigurePrinter:u,getFinalMapping:f,allPrintersReady:p}}function D$e({printerId:t,filamentReqs:e,manualMappings:n,onManualMappingChange:r,currencySymbol:i,defaultCostPerKg:s,defaultExpanded:o=!1}){const{t:l}=Dt(),c=Jt(),[d,u]=w.useState(!1),[h,f]=w.useState(o),{data:p}=Je({queryKey:["printer-status",t],queryFn:()=>ne.getPrinterStatus(t),enabled:!!t}),{data:x}=Je({queryKey:["spool-assignments",t],queryFn:()=>ne.getAssignments(t),enabled:!!t}),{loadedFilaments:v,filamentComparison:g,hasTypeMismatch:y,hasColorMismatch:_}=yne(e,p,n),N=w.useMemo(()=>{const B=new Map;for(const O of x||[]){const z=O.ams_id===255,D=f4(O.ams_id,O.tray_id,z);B.set(D,O.spool?.cost_per_kg??null)}return B},[x]),T=w.useMemo(()=>{let B=0;for(const O of g){const z=O.loaded?.globalTrayId;if(z==null)continue;const $=N.get(z)??null??s;$>0&&(B+=O.used_grams/1e3*$)}return B},[g,N,s]),k=w.useMemo(()=>Array.from(N.values()).some(B=>B!=null&&B>0),[N]),M=e?.filaments&&e.filaments.length>0,C=e?.filaments?.some(B=>B.nozzle_id!=null)??!1;if(!M||!p)return null;const j=y?"#f97316":_?"#facc15":"#00ae42",P=(B,O)=>{if(B>0)if(O===""){const z={...n};delete z[B],r(z)}else r({...n,[B]:parseInt(O,10)})},E=async()=>{u(!0);try{await ne.refreshPrinterStatus(t),await new Promise(B=>setTimeout(B,500)),await c.refetchQueries({queryKey:["printer-status",t]})}finally{u(!1)}};return a.jsxs("div",{className:"mb-4",children:[a.jsxs("button",{type:"button",onClick:()=>f(!h),className:"flex items-center gap-2 text-sm text-bambu-gray hover:text-white transition-colors w-full",children:[a.jsx(x1,{className:"w-4 h-4",fill:j,stroke:"none"}),a.jsx("span",{children:l("printModal.filamentMapping")}),y?a.jsx("span",{className:"text-xs text-orange-400",children:"(Type not found)"}):_?a.jsx("span",{className:"text-xs text-yellow-400",children:"(Color mismatch)"}):a.jsx("span",{className:"text-xs text-bambu-green",children:"(Ready)"}),h?a.jsx(yl,{className:"w-4 h-4 ml-auto"}):a.jsx(Pn,{className:"w-4 h-4 ml-auto"})]}),h&&a.jsxs("div",{className:"mt-2 bg-bambu-dark rounded-lg p-3 space-y-2",children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsx("span",{className:"text-xs text-bambu-gray",children:"Click to change slot assignment"}),a.jsxs("button",{type:"button",onClick:E,className:"flex items-center gap-1 px-2 py-0.5 text-xs rounded border border-bambu-gray/30 hover:border-bambu-gray hover:bg-bambu-dark-tertiary transition-colors text-bambu-gray hover:text-white",disabled:d,children:[a.jsx(vr,{className:`w-3 h-3 ${d?"animate-spin":""}`}),a.jsx("span",{children:"Re-read"})]})]}),g.map((B,O)=>a.jsxs("div",{className:"grid items-center gap-2 text-xs",style:{gridTemplateColumns:"16px minmax(70px, 1fr) auto 2fr 16px"},children:[a.jsx("span",{title:`Required: ${B.type} - ${vf(B.color)}`,children:a.jsx(x1,{className:"w-3 h-3",fill:B.color,stroke:B.color})}),a.jsxs("span",{className:"text-white truncate flex items-center gap-1",children:[C&&B.nozzle_id!=null&&a.jsx("span",{className:"inline-flex items-center justify-center w-3.5 h-3.5 rounded text-[9px] font-bold leading-none bg-bambu-gray/20 text-bambu-gray shrink-0",title:B.nozzle_id===1?l("printModal.leftNozzleTooltip"):l("printModal.rightNozzleTooltip"),children:B.nozzle_id===1?l("printModal.leftNozzle"):l("printModal.rightNozzle")}),B.type," ",a.jsxs("span",{className:"text-bambu-gray",children:["(",B.used_grams,"g)"]})]}),a.jsx("span",{className:"text-bambu-gray",children:"→"}),a.jsxs("select",{value:B.loaded?.globalTrayId??"",onChange:z=>P(B.slot_id||0,z.target.value),className:`flex-1 px-2 py-1 rounded border text-xs bg-bambu-dark-secondary focus:outline-none focus:ring-1 focus:ring-bambu-green ${B.status==="match"?"border-bambu-green/50 text-bambu-green":B.status==="type_only"?"border-yellow-400/50 text-yellow-400":"border-orange-400/50 text-orange-400"} ${B.isManual?"ring-1 ring-blue-400/50":""}`,title:B.isManual?"Manually selected":"Auto-matched",children:[a.jsx("option",{value:"",className:"bg-bambu-dark text-bambu-gray",children:"-- Select slot --"}),v.filter(z=>B.nozzle_id==null||z.extruderId===B.nozzle_id).map(z=>a.jsxs("option",{value:z.globalTrayId,className:"bg-bambu-dark text-white",children:[z.label,": ",z.type," (",z.colorName,")"]},z.globalTrayId))]}),B.status==="match"?a.jsx(Jr,{className:"w-3 h-3 text-bambu-green"}):B.status==="type_only"?a.jsx("span",{title:"Same type, different color",children:a.jsx(An,{className:"w-3 h-3 text-yellow-400"})}):a.jsx("span",{title:"Filament type not loaded",children:a.jsx(An,{className:"w-3 h-3 text-orange-400"})})]},O)),a.jsxs("div",{className:"text-xs text-bambu-gray",children:[l("printModal.totalCost")," ",a.jsx("span",{className:"text-white",children:T>0||k?`${i}${T.toFixed(2)}`:"N/A"})]}),y&&a.jsx("p",{className:"text-xs text-orange-400 mt-2",children:"Required filament type not found in printer."})]})]})}function R$e({filamentReqs:t,availableFilaments:e,overrides:n,onChange:r}){const{t:i}=Dt(),s=w.useMemo(()=>{const c={};for(const d of e){const u=d.type.toUpperCase();c[u]||(c[u]=[]),c[u].push(d)}return c},[e]),o=t?.filaments;if(!o||o.length===0||e.length===0)return null;const l=(c,d)=>{if(d===""){const u={...n};delete u[c],r(u)}else{const[u,h]=d.split("|");r({...n,[c]:{type:u,color:h}})}};return a.jsxs("div",{className:"mb-4",children:[a.jsx("div",{className:"flex items-center gap-2 text-sm text-bambu-gray mb-2",children:a.jsx("span",{children:i("printModal.filamentOverride")})}),a.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:i("printModal.filamentOverrideHint")}),a.jsx("div",{className:"bg-bambu-dark rounded-lg p-3 space-y-2",children:o.map(c=>{const d=n[c.slot_id],u=!!d,h=s[c.type.toUpperCase()]||[],f=c.nozzle_id!=null?h.filter(p=>p.extruder_id==null||p.extruder_id===c.nozzle_id):h;return a.jsxs("div",{className:"grid items-center gap-2 text-xs",style:{gridTemplateColumns:"16px minmax(70px, 1fr) auto 2fr 20px"},children:[a.jsx("span",{title:`${i("printModal.originalFilament")}: ${c.type} - ${vf(c.color)}`,children:a.jsx(x1,{className:"w-3 h-3",fill:c.color,stroke:c.color})}),a.jsxs("span",{className:"text-white truncate",children:[c.type," ",a.jsxs("span",{className:"text-bambu-gray",children:["(",c.used_grams,"g)"]})]}),a.jsx("span",{className:"text-bambu-gray",children:"→"}),a.jsxs("select",{value:u?`${d.type}|${d.color}`:"",onChange:p=>l(c.slot_id,p.target.value),disabled:f.length===0,className:`flex-1 px-2 py-1 rounded border text-xs bg-bambu-dark-secondary focus:outline-none focus:ring-1 focus:ring-bambu-green ${u?"border-blue-400/50 text-blue-400":"border-bambu-gray/30 text-bambu-gray"}`,children:[a.jsxs("option",{value:"",className:"bg-bambu-dark text-bambu-gray",children:[i("printModal.originalFilament"),": ",c.type," (",vf(c.color),")"]}),f.map((p,x)=>a.jsxs("option",{value:`${p.type}|${p.color}`,className:"bg-bambu-dark text-white",children:[p.type," (",vf(p.color),")"]},`${p.type}-${p.color}-${x}`))]}),u?a.jsx("button",{type:"button",onClick:()=>l(c.slot_id,""),className:"text-bambu-gray hover:text-white transition-colors",title:i("printModal.resetToOriginal"),children:a.jsx(so,{className:"w-3 h-3"})}):a.jsx("span",{className:"w-3"})]},c.slot_id)})})]})}function F$e({plates:t,isMultiPlate:e,selectedPlate:n,onSelect:r}){return!e||t.length<=1?null:a.jsxs("div",{className:"mb-4",children:[a.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[a.jsx(oi,{className:"w-4 h-4 text-bambu-gray"}),a.jsx("span",{className:"text-sm text-bambu-gray",children:"Select Plate to Print"}),!n&&a.jsxs("span",{className:"text-xs text-orange-400 flex items-center gap-1",children:[a.jsx(An,{className:"w-3 h-3"}),"Selection required"]})]}),a.jsx("div",{className:"grid grid-cols-2 gap-2",children:t.map(i=>a.jsxs("button",{type:"button",onClick:()=>r(i.index),className:`flex items-center gap-2 p-2 rounded-lg border transition-colors text-left ${n===i.index?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark hover:border-bambu-gray"}`,children:[i.has_thumbnail&&i.thumbnail_url!=null?a.jsx("img",{src:i.thumbnail_url,alt:`Plate ${i.index}`,className:"w-10 h-10 rounded object-cover bg-bambu-dark-tertiary"}):a.jsx("div",{className:"w-10 h-10 rounded bg-bambu-dark-tertiary flex items-center justify-center",children:a.jsx(oi,{className:"w-5 h-5 text-bambu-gray"})}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:"text-sm text-white font-medium truncate",children:i.name||`Plate ${i.index}`}),a.jsxs("p",{className:"text-xs text-bambu-gray truncate",children:[i.objects.length>0?i.objects.slice(0,3).join(", ")+(i.objects.length>3?"...":""):`${i.filaments.length} filament${i.filaments.length!==1?"s":""}`,i.print_time_seconds!=null?` • ${Qs(i.print_time_seconds)}`:""]})]}),n===i.index&&a.jsx(Jr,{className:"w-4 h-4 text-bambu-green flex-shrink-0"})]},i.index))})]})}function L$e({printerResult:t,filamentReqs:e,onUpdateConfig:n}){const r=Jt(),[i,s]=w.useState(!1),o=(d,u)=>{if(d<=0)return;const h={...t.config.manualMappings};u===""?delete h[d]:h[d]=parseInt(u,10),n({useDefault:!1,manualMappings:h,autoConfigured:!1})},l=async()=>{s(!0);try{await ne.refreshPrinterStatus(t.printerId),await new Promise(d=>setTimeout(d,500)),await r.refetchQueries({queryKey:["printer-status",t.printerId]})}finally{s(!1)}},c=e.map(d=>{const u=d.slot_id||0,h=t.config.manualMappings[u];let f,p=!1;if(h!==void 0)f=t.loadedFilaments.find(v=>v.globalTrayId===h),p=!0;else{const v=new Set(Object.values(t.config.manualMappings)),g=t.loadedFilaments.find(N=>!v.has(N.globalTrayId)&&N.type?.toUpperCase()===d.type?.toUpperCase()&&Ra(N.color)===Ra(d.color)),y=g?void 0:t.loadedFilaments.find(N=>!v.has(N.globalTrayId)&&N.type?.toUpperCase()===d.type?.toUpperCase()&&Rc(N.color,d.color)),_=g||y?void 0:t.loadedFilaments.find(N=>!v.has(N.globalTrayId)&&N.type?.toUpperCase()===d.type?.toUpperCase());f=g??y??_}let x="mismatch";if(f){const v=f.type?.toUpperCase()===d.type?.toUpperCase(),g=Ra(f.color)===Ra(d.color)||Rc(f.color,d.color);v&&g?x="match":v&&(x="type_only")}return{req:d,loaded:f,status:x,isManual:p}});return a.jsxs("div",{className:"mt-2 bg-bambu-dark rounded-lg p-3 space-y-2",children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsx("span",{className:"text-xs text-bambu-gray",children:"Custom slot mapping"}),a.jsxs("button",{type:"button",onClick:l,className:"flex items-center gap-1 px-2 py-0.5 text-xs rounded border border-bambu-gray/30 hover:border-bambu-gray hover:bg-bambu-dark-tertiary transition-colors text-bambu-gray hover:text-white",disabled:i,children:[a.jsx(vr,{className:`w-3 h-3 ${i?"animate-spin":""}`}),a.jsx("span",{children:"Re-read"})]})]}),c.map(({req:d,loaded:u,status:h,isManual:f},p)=>a.jsxs("div",{className:"grid items-center gap-2 text-xs",style:{gridTemplateColumns:"16px minmax(70px, 1fr) auto 2fr 16px"},children:[a.jsx("span",{title:`Required: ${d.type} - ${vf(d.color)}`,children:a.jsx(x1,{className:"w-3 h-3",fill:d.color,stroke:d.color})}),a.jsxs("span",{className:"text-white truncate",children:[d.type," ",a.jsxs("span",{className:"text-bambu-gray",children:["(",d.used_grams,"g)"]})]}),a.jsx("span",{className:"text-bambu-gray",children:"→"}),a.jsxs("select",{value:u?.globalTrayId??"",onChange:x=>o(d.slot_id||0,x.target.value),className:`flex-1 px-2 py-1 rounded border text-xs bg-bambu-dark-secondary focus:outline-none focus:ring-1 focus:ring-bambu-green ${h==="match"?"border-bambu-green/50 text-bambu-green":h==="type_only"?"border-yellow-400/50 text-yellow-400":"border-orange-400/50 text-orange-400"} ${f?"ring-1 ring-blue-400/50":""}`,title:f?"Manually selected":"Auto-matched",children:[a.jsx("option",{value:"",className:"bg-bambu-dark text-bambu-gray",children:"-- Select slot --"}),t.loadedFilaments.map(x=>a.jsxs("option",{value:x.globalTrayId,className:"bg-bambu-dark text-white",children:[x.label,": ",x.type," (",x.colorName,")"]},x.globalTrayId))]}),h==="match"?a.jsx(Jr,{className:"w-3 h-3 text-bambu-green"}):h==="type_only"?a.jsx("span",{title:"Same type, different color",children:a.jsx(An,{className:"w-3 h-3 text-yellow-400"})}):a.jsx("span",{title:"Filament type not loaded",children:a.jsx(An,{className:"w-3 h-3 text-orange-400"})})]},p))]})}function O$e({printers:t,selectedPrinterIds:e,onMultiSelect:n,isLoading:r=!1,allowMultiple:i=!1,showInactive:s=!1,printerMappingResults:o,filamentReqs:l,onAutoConfigurePrinter:c,onUpdatePrinterConfig:d,assignmentMode:u="printer",onAssignmentModeChange:h,targetModel:f,onTargetModelChange:p,targetLocation:x,onTargetLocationChange:v,slicedForModel:g}){const[y,_]=w.useState(!1),N=s?t:t.filter(U=>U.is_active),T=w.useMemo(()=>{if(u!=="printer"||!g||y)return N;const U=N.filter(W=>W.model===g);return U.length>0?U:N},[N,u,g,y]),k=N.length-T.length,M=w.useMemo(()=>{const U=N.map(W=>W.model).filter(W=>!!W);return[...new Set(U)].sort()},[N]),C=w.useMemo(()=>{if(!f)return[];const U=N.filter(W=>W.model===f&&W.location).map(W=>W.location).filter(W=>!!W);return[...new Set(U)].sort()},[N,f]),j=h&&p&&M.length>0,P=i&&e.length>1&&o&&l?.filaments&&l.filaments.length>0&&c&&d;if(r)return a.jsx("div",{className:"flex justify-center py-8",children:a.jsx(at,{className:"w-6 h-6 text-bambu-green animate-spin"})});if(T.length===0)return a.jsxs("div",{className:"flex items-center gap-2 text-red-400 text-sm mb-4",children:[a.jsx(Wa,{className:"w-4 h-4"}),"No ",s?"":"active ","printers available"]});const E=U=>{i?e.includes(U)?n(e.filter(W=>W!==U)):n([...e,U]):n([U])},B=()=>{n(T.map(U=>U.id))},O=()=>{n([])},z=(U,W,Y)=>{Y.stopPropagation(),!(!c||!d)&&(W?c(U):d(U,{useDefault:!0,manualMappings:{},autoConfigured:!1}))},D=U=>e.includes(U),$=e.length,G=U=>o?.find(W=>W.printerId===U);return a.jsxs("div",{className:"space-y-2 mb-6",children:[j&&a.jsxs("div",{className:"flex gap-2 mb-4",children:[a.jsxs("button",{type:"button",onClick:()=>{h("printer"),p(null)},className:`flex-1 flex items-center justify-center gap-2 px-3 py-2 rounded-lg border transition-colors ${u==="printer"?"border-bambu-green bg-bambu-green/10 text-white":"border-bambu-dark-tertiary bg-bambu-dark text-bambu-gray hover:border-bambu-gray"}`,children:[a.jsx(Sr,{className:"w-4 h-4"}),a.jsx("span",{className:"text-sm",children:"Specific Printer"})]}),a.jsxs("button",{type:"button",onClick:()=>{h("model"),n([]);const U=g&&M.includes(g)?g:M[0];p(U)},className:`flex-1 flex items-center justify-center gap-2 px-3 py-2 rounded-lg border transition-colors ${u==="model"?"border-bambu-green bg-bambu-green/10 text-white":"border-bambu-dark-tertiary bg-bambu-dark text-bambu-gray hover:border-bambu-gray"}`,children:[a.jsx(mh,{className:"w-4 h-4"}),a.jsxs("span",{className:"text-sm",children:["Any ",g||"Model"]})]})]}),u==="model"&&j&&a.jsxs("div",{className:"space-y-3 mb-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Target Model"}),a.jsxs("select",{value:f||"",onChange:U=>{p(U.target.value||null),v&&v(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 text-sm",children:[a.jsx("option",{value:"",children:"Select a model..."}),M.map(U=>a.jsx("option",{value:U,children:U},U))]})]}),f&&C.length>0&&v&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Location Filter (optional)"}),a.jsxs("select",{value:x||"",onChange:U=>v(U.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 text-sm",children:[a.jsx("option",{value:"",children:"Any location"}),C.map(U=>a.jsx("option",{value:U,children:U},U))]})]}),f&&a.jsxs("p",{className:"text-xs text-bambu-gray",children:["Scheduler will assign to first available idle ",f," printer",x?` in ${x}`:""]})]}),u==="printer"&&i&&T.length>1&&a.jsxs("div",{className:"flex items-center justify-between text-xs text-bambu-gray mb-2",children:[a.jsx("span",{children:$===0?"Select printers":`${$} printer${$!==1?"s":""} selected`}),a.jsxs("div",{className:"flex gap-2",children:[$0&&a.jsx("button",{type:"button",onClick:O,className:"text-bambu-gray hover:text-white transition-colors",children:"Clear"})]})]}),u==="printer"&&T.map(U=>{const W=D(U.id),Y=G(U.id),re=Y&&!Y.config.useDefault;return a.jsxs("div",{children:[a.jsxs("button",{type:"button",onClick:()=>E(U.id),className:`w-full flex items-center gap-3 p-3 rounded-lg border transition-colors ${W?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark hover:border-bambu-gray"} ${U.is_active?"":"opacity-60"}`,children:[a.jsx("div",{className:`p-2 rounded-lg ${W?"bg-bambu-green/20":"bg-bambu-dark-tertiary"}`,children:a.jsx(Sr,{className:`w-5 h-5 ${W?"text-bambu-green":"text-bambu-gray"}`})}),a.jsxs("div",{className:"text-left flex-1",children:[a.jsxs("p",{className:"text-white font-medium",children:[U.name,!U.is_active&&a.jsx("span",{className:"text-bambu-gray text-xs ml-2",children:"(inactive)"})]}),a.jsxs("p",{className:"text-xs text-bambu-gray",children:[U.model||"Unknown model"," • ",U.ip_address]})]}),i&&a.jsx("div",{className:`w-5 h-5 rounded border-2 flex items-center justify-center transition-colors ${W?"bg-bambu-green border-bambu-green":"border-bambu-gray/50"}`,children:W&&a.jsx(Jr,{className:"w-3 h-3 text-white"})})]}),W&&P&&Y&&a.jsxs("div",{className:"ml-4 mt-2 mb-3",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",onClick:H=>H.stopPropagation(),children:[a.jsx("input",{type:"checkbox",checked:re,onChange:H=>z(U.id,H.target.checked,H),className:"w-3.5 h-3.5 rounded border-bambu-gray/30 bg-bambu-dark-secondary text-bambu-green focus:ring-bambu-green focus:ring-offset-0"}),a.jsx("span",{className:"text-xs text-bambu-gray",children:"Custom mapping"})]}),a.jsxs("span",{className:`text-xs ml-2 ${Y.matchStatus==="full"?"text-bambu-green":Y.matchStatus==="partial"?"text-yellow-400":"text-orange-400"}`,children:["(",Y.exactMatches,"/",Y.totalSlots," matched)"]}),Y.isLoading&&a.jsx(vr,{className:"w-3 h-3 text-bambu-gray animate-spin"}),re&&a.jsxs("button",{type:"button",onClick:H=>{H.stopPropagation(),c(U.id)},className:"ml-auto flex items-center gap-1 px-2 py-0.5 text-xs rounded border border-bambu-gray/30 hover:border-bambu-gray hover:bg-bambu-dark-tertiary transition-colors text-bambu-gray hover:text-white",children:[a.jsx(nge,{className:"w-3 h-3"}),"Auto"]})]}),re&&a.jsx(L$e,{printerResult:Y,filamentReqs:l.filaments,onUpdateConfig:H=>d(U.id,H)})]})]},U.id)}),u==="printer"&&k>0&&!y&&a.jsxs("button",{type:"button",onClick:()=>_(!0),className:"text-xs text-bambu-gray hover:text-white transition-colors mt-2 flex items-center gap-1",children:[a.jsx(An,{className:"w-3 h-3 text-yellow-400"}),k," other printer",k>1?"s":""," hidden (different model) —",a.jsx("span",{className:"underline",children:"show all"})]}),u==="printer"&&y&&g&&a.jsx("button",{type:"button",onClick:()=>_(!1),className:"text-xs text-bambu-gray hover:text-white transition-colors mt-2",children:a.jsxs("span",{className:"underline",children:["Show only ",g," printers"]})}),u==="printer"&&$===0&&a.jsxs("p",{className:"text-xs text-orange-400 mt-1 flex items-center gap-1",children:[a.jsx(Wa,{className:"w-3 h-3"}),"Select at least one printer"]}),u==="model"&&!f&&a.jsxs("p",{className:"text-xs text-orange-400 mt-1 flex items-center gap-1",children:[a.jsx(Wa,{className:"w-3 h-3"}),"Select a target printer model"]})]})}const I$e=[{key:"bed_levelling",label:"Bed Levelling",desc:"Auto-level bed before print"},{key:"flow_cali",label:"Flow Calibration",desc:"Calibrate extrusion flow"},{key:"vibration_cali",label:"Vibration Calibration",desc:"Reduce ringing artifacts"},{key:"layer_inspect",label:"First Layer Inspection",desc:"AI inspection of first layer"},{key:"timelapse",label:"Timelapse",desc:"Record timelapse video"}];function z$e({options:t,onChange:e,defaultExpanded:n=!1}){const[r,i]=w.useState(n),s=o=>{e({...t,[o]:!t[o]})};return a.jsxs("div",{className:"mb-4",children:[a.jsxs("button",{type:"button",onClick:()=>i(!r),className:"flex items-center gap-2 text-sm text-bambu-gray hover:text-white transition-colors w-full",children:[a.jsx(QC,{className:"w-4 h-4"}),a.jsx("span",{children:"Print Options"}),r?a.jsx(yl,{className:"w-4 h-4 ml-auto"}):a.jsx(Pn,{className:"w-4 h-4 ml-auto"})]}),r&&a.jsx("div",{className:"mt-2 bg-bambu-dark rounded-lg p-3 space-y-2",children:I$e.map(({key:o,label:l,desc:c})=>a.jsxs("label",{className:"flex items-center justify-between cursor-pointer group",children:[a.jsxs("div",{children:[a.jsx("span",{className:"text-sm text-white",children:l}),a.jsx("p",{className:"text-xs text-bambu-gray",children:c})]}),a.jsx("div",{className:`relative w-10 h-5 rounded-full transition-colors ${t[o]?"bg-bambu-green":"bg-bambu-dark-tertiary"}`,onClick:()=>s(o),children:a.jsx("div",{className:`absolute top-0.5 w-4 h-4 rounded-full bg-white transition-transform ${t[o]?"translate-x-5":"translate-x-0.5"}`})})]},o))})]})}function U$e({options:t,onChange:e,dateFormat:n="system",timeFormat:r="system",canControlPrinter:i=!0}){const[s,o]=w.useState(""),[l,c]=w.useState(""),[d,u]=w.useState(!0),[h,f]=w.useState(!0),p=w.useRef(null),x=w.useRef(!1);w.useEffect(()=>{if(t.scheduleType!=="scheduled"){x.current=!1;return}if(!x.current){x.current=!0;let k;t.scheduledTime?(k=new Date(t.scheduledTime),isNaN(k.getTime())&&(k=new Date,k.setHours(k.getHours()+1,0,0,0))):(k=new Date,k.setHours(k.getHours()+1,0,0,0),e({...t,scheduledTime:u3(k)})),o(d3(k,n)),c($B(k,r)),u(!0),f(!0)}},[t.scheduleType,t.scheduledTime,n,r,e,t]);const v=k=>{e({...t,scheduleType:k})},g=(k,M)=>{const C=Nge(k,n),j=Cge(M);u(!!C),f(!!j),C&&j&&(C.setHours(j.hours,j.minutes,0,0),C>new Date&&e({...t,scheduledTime:u3(C)}))},y=k=>{o(k),g(k,l)},_=k=>{c(k),g(s,k)},N=k=>{const M=k.target.value;if(M){const C=new Date(M);isNaN(C.getTime())||(o(d3(C,n)),c($B(C,r)),u(!0),f(!0),e({...t,scheduledTime:M}))}},T=()=>{p.current?.showPicker()};return a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-2",children:"When to print"}),a.jsxs("div",{className:"flex gap-2",children:[a.jsxs("button",{type:"button",className:`flex-1 px-2 py-2 rounded-lg border text-sm flex items-center justify-center gap-1.5 transition-colors ${t.scheduleType==="asap"?"bg-bambu-green border-bambu-green text-white":"bg-bambu-dark border-bambu-dark-tertiary text-bambu-gray hover:text-white"}`,onClick:()=>v("asap"),children:[a.jsx(Vn,{className:"w-4 h-4"}),"ASAP"]}),a.jsxs("button",{type:"button",className:`flex-1 px-2 py-2 rounded-lg border text-sm flex items-center justify-center gap-1.5 transition-colors ${t.scheduleType==="scheduled"?"bg-bambu-green border-bambu-green text-white":"bg-bambu-dark border-bambu-dark-tertiary text-bambu-gray hover:text-white"}`,onClick:()=>v("scheduled"),children:[a.jsx(sa,{className:"w-4 h-4"}),"Scheduled"]}),a.jsxs("button",{type:"button",className:`flex-1 px-2 py-2 rounded-lg border text-sm flex items-center justify-center gap-1.5 transition-colors ${t.scheduleType==="manual"?"bg-bambu-green border-bambu-green text-white":"bg-bambu-dark border-bambu-dark-tertiary text-bambu-gray hover:text-white"}`,onClick:()=>v("manual"),children:[a.jsx(bY,{className:"w-4 h-4"}),"Queue Only"]})]})]}),t.scheduleType==="scheduled"&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Date & Time"}),a.jsxs("div",{className:"flex gap-2",children:[a.jsxs("div",{className:"flex-1 relative",children:[a.jsx("input",{type:"text",className:`w-full px-3 py-2 pr-10 bg-bambu-dark border rounded-lg text-white focus:outline-none ${d?"border-bambu-dark-tertiary focus:border-bambu-green":"border-red-500"}`,value:s,onChange:k=>y(k.target.value),placeholder:Sge(n)}),a.jsx("button",{type:"button",onClick:T,className:"absolute right-2 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white",title:"Open calendar",children:a.jsx(sa,{className:"w-4 h-4"})})]}),a.jsx("div",{className:"w-32",children:a.jsx("input",{type:"text",className:`w-full px-3 py-2 bg-bambu-dark border rounded-lg text-white focus:outline-none ${h?"border-bambu-dark-tertiary focus:border-bambu-green":"border-red-500"}`,value:l,onChange:k=>_(k.target.value),placeholder:_ge(r)})})]}),a.jsx("input",{ref:p,type:"datetime-local",className:"sr-only",value:t.scheduledTime,onChange:N,tabIndex:-1}),(!d||!h)&&a.jsx("p",{className:"mt-1 text-xs text-red-400",children:"Please enter a valid date and time"})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"checkbox",id:"requirePrevious",checked:t.requirePreviousSuccess,onChange:k=>e({...t,requirePreviousSuccess:k.target.checked}),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),a.jsx("label",{htmlFor:"requirePrevious",className:"text-sm text-bambu-gray",children:"Only start if previous print succeeded"})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"checkbox",id:"autoOffAfter",checked:t.autoOffAfter,onChange:k=>e({...t,autoOffAfter:k.target.checked}),disabled:!i,className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green disabled:opacity-50"}),a.jsxs("label",{htmlFor:"autoOffAfter",className:`text-sm flex items-center gap-1 ${i?"text-bambu-gray":"text-bambu-gray/50"}`,children:[a.jsx(mu,{className:"w-3.5 h-3.5"}),"Power off printer when done"]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:t.scheduleType==="asap"?"Print will start as soon as the printer is idle.":t.scheduleType==="scheduled"?"Print will start at the scheduled time if the printer is idle. If busy, it will wait until the printer becomes available.":"Print will be staged but won't start automatically. Use the Start button to release it to the queue."})]})}const Ng={bed_levelling:!0,flow_cali:!1,vibration_cali:!0,layer_inspect:!1,timelapse:!1},B$e={scheduleType:"asap",scheduledTime:"",requirePreviousSuccess:!1,autoOffAfter:!1};function Yd({mode:t,archiveId:e,libraryFileId:n,archiveName:r,queueItem:i,onClose:s,onSuccess:o}){const{t:l}=Dt(),c=Jt(),{showToast:d}=ln(),{hasPermission:u}=Pr(),h=!!n&&!e,[f,p]=w.useState(()=>t==="edit-queue-item"&&i?.printer_id?[i.printer_id]:[]),[x,v]=w.useState(()=>t==="edit-queue-item"&&i?i.plate_id:null),[g,y]=w.useState(()=>t==="edit-queue-item"&&i?{bed_levelling:i.bed_levelling??Ng.bed_levelling,flow_cali:i.flow_cali??Ng.flow_cali,vibration_cali:i.vibration_cali??Ng.vibration_cali,layer_inspect:i.layer_inspect??Ng.layer_inspect,timelapse:i.timelapse??Ng.timelapse}:Ng),[_,N]=w.useState(()=>{if(t==="edit-queue-item"&&i){let Ee="asap";i.manual_start?Ee="manual":i.scheduled_time&&!J7(i.scheduled_time)&&(Ee="scheduled");let Ve="";if(i.scheduled_time&&!J7(i.scheduled_time)){const ot=er(i.scheduled_time)??new Date;Ve=u3(ot)}return{scheduleType:Ee,scheduledTime:Ve,requirePreviousSuccess:i.require_previous_success,autoOffAfter:i.auto_off_after}}return B$e}),[T,k]=w.useState(()=>{if(t==="edit-queue-item"&&i?.ams_mapping&&Array.isArray(i.ams_mapping)){const Ee={};return i.ams_mapping.forEach((Ve,ot)=>{Ve!==-1&&(Ee[ot+1]=Ve)}),Ee}return{}}),[M,C]=w.useState({}),[j,P]=w.useState(()=>t==="edit-queue-item"&&i?.target_model?"model":"printer"),[E,B]=w.useState(()=>t==="edit-queue-item"&&i?.target_model?i.target_model:null),[O,z]=w.useState(()=>t==="edit-queue-item"&&i?.target_location?i.target_location:null),[D,$]=w.useState(()=>{if(t==="edit-queue-item"&&i?.filament_overrides){const Ee={};for(const Ve of i.filament_overrides)Ee[Ve.slot_id]={type:Ve.type,color:Ve.color};return Ee}return{}}),[G]=w.useState(()=>t==="edit-queue-item"&&i?.printer_id?[i.printer_id]:[]),[U]=w.useState(()=>t==="edit-queue-item"&&i?i.plate_id:null),[W,Y]=w.useState(!1),[re,H]=w.useState({current:0,total:0}),[K,ee]=w.useState(new Set),Z=f.length,we=f.length>0?f[0]:null,{data:oe}=Je({queryKey:["settings"],queryFn:ne.getSettings}),J=rl(oe?.currency||"USD"),je=oe?.default_filament_cost??0,{data:de,isLoading:le}=Je({queryKey:["printers"],queryFn:ne.getPrinters}),{data:_e}=Je({queryKey:["archive",e],queryFn:()=>ne.getArchive(e),enabled:!!e&&!h}),{data:se}=Je({queryKey:["library-file",n],queryFn:()=>ne.getLibraryFile(n),enabled:h&&!!n}),ze=_e?.sliced_for_model||se?.sliced_for_model||null,{data:V,isError:X}=Je({queryKey:["archive-plates",e],queryFn:()=>ne.getArchivePlates(e),enabled:!!e&&!h,retry:!1}),{data:me}=Je({queryKey:["library-file-plates",n],queryFn:()=>ne.getLibraryFilePlates(n),enabled:h&&!!n}),Q=h?me:V,{data:ie,isError:ue}=Je({queryKey:["archive-filaments",e,x],queryFn:()=>ne.getArchiveFilamentRequirements(e,x??void 0),enabled:!!e&&!h&&(x!==null||!Q?.is_multi_plate),retry:!1}),{data:Le}=Je({queryKey:["library-file-filaments",n,x],queryFn:()=>ne.getLibraryFileFilamentRequirements(n,x??void 0),enabled:h&&!!n&&(x!==null||!Q?.is_multi_plate)}),Ce=!h&&(X||ue),ge=h?Le:ie,L=w.useMemo(()=>{if(!(x===null||!Q?.plates?.length))return Q.plates.find(Ee=>Ee.index===x)?.name||void 0},[Q,x]),{data:R}=Je({queryKey:["available-filaments",E,O],queryFn:()=>ne.getAvailableFilaments(E,O??void 0),enabled:j==="model"&&!!E}),{data:q}=Je({queryKey:["printer-status",we],queryFn:()=>ne.getPrinterStatus(we),enabled:!!we}),{amsMapping:ce}=yne(ge,q,T),pe=j$e(f,de,ge,T,M,C);w.useEffect(()=>{Q?.plates&&Q.plates.length>=1&&!x&&v(Q.plates[0].index)},[Q,x]),w.useEffect(()=>{if(t==="edit-queue-item")return;const Ee=de?.filter(Ve=>Ve.is_active)||[];Ee.length===1&&f.length===0&&p([Ee[0].id])},[t,de,f.length]),w.useEffect(()=>{t==="edit-queue-item"?(JSON.stringify(f.sort())!==JSON.stringify(G.sort())||x!==U)&&(k({}),C({}),ee(new Set)):(k({}),C({}),ee(new Set))},[t,f,x,G,U]);const[te,Be]=w.useState(E),[Ie,$e]=w.useState(x);w.useEffect(()=>{(E!==te||x!==Ie)&&(Be(E),$e(x),(t!=="edit-queue-item"||te!==null)&&$({}))},[E,x,te,Ie,t]),w.useEffect(()=>{if(!oe?.per_printer_mapping_expanded||f.length<=1)return;const Ee=f.filter(Ve=>{if(K.has(Ve))return!1;const ot=pe.printerResults.find(Ct=>Ct.printerId===Ve);return ot&&ot.status&&!ot.isLoading});Ee.length>0&&(ee(Ve=>{const ot=new Set(Ve);return Ee.forEach(Ct=>ot.add(Ct)),ot}),Ee.forEach(Ve=>{pe.autoConfigurePrinter(Ve)}))},[oe?.per_printer_mapping_expanded,f,K,pe]),w.useEffect(()=>{const Ee=Ve=>{Ve.key==="Escape"&&!W&&s()};return window.addEventListener("keydown",Ee),()=>window.removeEventListener("keydown",Ee)},[s,W]);const Re=Q?.is_multi_plate??!1,fe=Q?.plates??[],xe=st({mutationFn:Ee=>ne.addToQueue(Ee)}),Ne=st({mutationFn:Ee=>ne.updateQueueItem(i.id,Ee),onSuccess:()=>{c.invalidateQueries({queryKey:["queue"]}),d("Queue item updated"),o?.(),s()},onError:Ee=>{d(Ee.message||"Failed to update queue item","error")}}),ye=async Ee=>{if(Ee?.preventDefault(),j==="printer"&&f.length===0){d("Please select at least one printer","error");return}if(j==="model"&&!E){d("Please select a target printer model","error");return}Y(!0);const Ve=j==="model"?1:f.length;H({current:0,total:Ve});const ot={success:0,failed:0,errors:[]},Ct=Mt=>{if(f.length>1){const Ue=M[Mt];if(Ue&&!Ue.useDefault)return pe.getFinalMapping(Mt)}return ce},Lt=Object.keys(D).length>0?Object.entries(D).map(([Mt,{type:Ue,color:yt}])=>({slot_id:parseInt(Mt,10),type:Ue,color:yt})):void 0,Bt=Mt=>({printer_id:j==="printer"?Mt:null,target_model:j==="model"?E:null,target_location:j==="model"?O:null,filament_overrides:j==="model"?Lt:void 0,archive_id:h?void 0:e,library_file_id:h?n:void 0,require_previous_success:_.requirePreviousSuccess,auto_off_after:_.autoOffAfter,manual_start:_.scheduleType==="manual",ams_mapping:Mt?Ct(Mt):void 0,plate_id:x,scheduled_time:_.scheduleType==="scheduled"&&_.scheduledTime?new Date(_.scheduledTime).toISOString():void 0,...g});if(j==="model"){H({current:1,total:1});try{if(t==="reprint"){d("Model-based assignment only works with queue mode","error"),Y(!1);return}else if(t==="edit-queue-item"){const Mt={printer_id:null,target_model:E,target_location:O,filament_overrides:Lt||null,require_previous_success:_.requirePreviousSuccess,auto_off_after:_.autoOffAfter,manual_start:_.scheduleType==="manual",ams_mapping:void 0,plate_id:x,scheduled_time:_.scheduleType==="scheduled"&&_.scheduledTime?new Date(_.scheduledTime).toISOString():null,...g};await Ne.mutateAsync(Mt)}else await xe.mutateAsync(Bt(null));ot.success++}catch(Mt){ot.failed++,ot.errors.push(Mt.message)}}else for(let Mt=0;MtVt.id===Ue)?.name||`Printer ${Ue}`;ot.errors.push(`${xt}: ${yt.message}`)}}Y(!1),ot.failed===0?(t!=="reprint"&&(j==="model"?d(t==="edit-queue-item"?"Queue item updated":`Queued for any ${E}`):t==="edit-queue-item"?d("Queue item updated"):ot.success===1?d("Print queued for printer"):d(`Print queued for ${ot.success} printers`)),c.invalidateQueries({queryKey:["queue"]}),o?.(),s()):ot.success===0?d(`Failed: ${ot.errors[0]}`,"error"):(d(`${ot.success} succeeded, ${ot.failed} failed`,"error"),c.invalidateQueries({queryKey:["queue"]}))},ve=W||Ne.isPending,Ge=w.useMemo(()=>!(ve||j==="printer"&&f.length===0||j==="model"&&!E||j==="model"&&t==="reprint"||Re&&!x),[f.length,j,E,t,Re,x,ve]),nt=(()=>{const Ee=f.length;return t==="reprint"?{title:l(h?"queue.print":"queue.reprint"),icon:Sr,submitText:Ee>1?l("queue.printToPrinters",{count:Ee}):l("queue.print"),submitIcon:Sr,loadingText:re.total>1?l("queue.sendingProgress",{current:re.current,total:re.total}):l("queue.sending")}:t==="add-to-queue"?{title:l("queue.schedulePrint"),icon:sa,submitText:Ee>1?l("queue.queueToPrinters",{count:Ee}):l("queue.addToQueue"),submitIcon:sa,loadingText:re.total>1?l("queue.addingProgress",{current:re.current,total:re.total}):l("queue.adding")}:{title:l("queue.editQueueItem"),icon:Ya,submitText:l("common.save"),submitIcon:Ya,loadingText:re.total>1?l("queue.savingProgress",{current:re.current,total:re.total}):l("common.saving")}})(),De=nt.icon,Ke=nt.submitIcon,Oe=we&&(h||(Re?x!==null:!0));return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:W?void 0:s,children:a.jsx(wt,{className:"w-full max-w-lg max-h-[90vh] overflow-y-auto",onClick:Ee=>Ee.stopPropagation(),children:a.jsxs(Nt,{className:t==="reprint"?"":"p-0",children:[a.jsxs("div",{className:`flex items-center justify-between ${t==="reprint"?"mb-4":"p-4 border-b border-bambu-dark-tertiary"}`,children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(De,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:nt.title})]}),a.jsx(Me,{variant:"ghost",size:"sm",onClick:s,disabled:W,children:a.jsx(Rt,{className:"w-5 h-5"})})]}),a.jsxs("form",{onSubmit:ye,className:t==="reprint"?"":"p-4 space-y-4",children:[a.jsx("p",{className:`text-sm text-bambu-gray ${t==="reprint"?"mb-4":""}`,children:t==="reprint"?a.jsxs(a.Fragment,{children:["Send ",a.jsx("span",{className:"text-white",children:r})," to printer(s)"]}):a.jsxs(a.Fragment,{children:[a.jsx("span",{className:"block text-bambu-gray mb-1",children:"Print Job"}),a.jsx("span",{className:"text-white font-medium truncate block",children:r})]})}),a.jsx(F$e,{plates:fe,isMultiPlate:Re,selectedPlate:x,onSelect:v}),a.jsx(O$e,{printers:de||[],selectedPrinterIds:f,onMultiSelect:p,isLoading:le,allowMultiple:!0,showInactive:t==="edit-queue-item",printerMappingResults:pe.printerResults,filamentReqs:ge,onAutoConfigurePrinter:pe.autoConfigurePrinter,onUpdatePrinterConfig:pe.updatePrinterConfig,assignmentMode:t==="reprint"?"printer":j,onAssignmentModeChange:t!=="reprint"?P:void 0,targetModel:E,onTargetModelChange:t!=="reprint"?B:void 0,targetLocation:O,onTargetLocationChange:t!=="reprint"?z:void 0,slicedForModel:ze}),j==="model"&&E&&ge&&R&&R.length>0&&a.jsx(R$e,{filamentReqs:ge,availableFilaments:R,overrides:D,onChange:$}),ze&&j==="printer"&&f.length===1&&(()=>{const Ee=de?.find(Ve=>Ve.id===f[0]);return Ee&&Ee.model&&ze!==Ee.model?a.jsxs("div",{className:"p-3 mb-2 bg-yellow-500/10 border border-yellow-500/30 rounded-lg flex items-center gap-2",children:[a.jsx(An,{className:"w-4 h-4 text-yellow-400 flex-shrink-0"}),a.jsxs("span",{className:"text-sm text-yellow-400",children:["File was sliced for ",ze,", but printing on ",Ee.model]})]}):null})(),Ce&&a.jsxs("div",{className:"flex items-start gap-2 p-3 mb-2 bg-orange-500/10 border border-orange-500/30 rounded-lg text-sm",children:[a.jsx(Wa,{className:"w-4 h-4 text-orange-400 mt-0.5 flex-shrink-0"}),a.jsx("p",{className:"text-orange-400",children:"Archive data unavailable. The source file may have been deleted. Filament mapping is disabled."})]}),Oe&&!Ce&&f.length===1&&a.jsx(D$e,{printerId:we,filamentReqs:ge,manualMappings:T,onManualMappingChange:k,defaultExpanded:oe?.per_printer_mapping_expanded??!1,currencySymbol:J,defaultCostPerKg:je}),(t==="reprint"||Z>0||j==="model"&&E)&&a.jsx(z$e,{options:g,onChange:y}),t!=="reprint"&&a.jsx(U$e,{options:_,onChange:N,dateFormat:oe?.date_format||"system",timeFormat:oe?.time_format||"system",canControlPrinter:u("printers:control")}),Ne.isError&&a.jsx("div",{className:"mb-4 p-3 bg-red-500/20 border border-red-500/50 rounded-lg text-sm text-red-400",children:Ne.error?.message||"Failed to complete operation"}),a.jsxs("div",{className:`flex gap-3 ${t==="reprint"?"":"pt-2"}`,children:[a.jsx(Me,{type:"button",variant:"secondary",onClick:s,className:"flex-1",disabled:W,children:"Cancel"}),a.jsx(Me,{type:"submit",disabled:!Ge,className:"flex-1",children:ve?a.jsxs(a.Fragment,{children:[a.jsx(at,{className:"w-4 h-4 animate-spin"}),nt.loadingText]}):a.jsxs(a.Fragment,{children:[a.jsx(Ke,{className:"w-4 h-4"}),nt.submitText]})})]})]})]})})})}function H$e({onClose:t,initialFiles:e}){const{t:n}=Dt(),r=Jt(),{showToast:i}=ln(),s=w.useRef(null),[o,l]=w.useState(()=>e?.filter(k=>k.name.endsWith(".3mf")).map(k=>({file:k,status:"pending"}))||[]),[c,d]=w.useState(!1),[u,h]=w.useState(null);w.useEffect(()=>{const k=M=>{M.key==="Escape"&&t()};return window.addEventListener("keydown",k),()=>window.removeEventListener("keydown",k)},[t]);const f=st({mutationFn:k=>ne.uploadArchivesBulk(k),onSuccess:k=>{h(k),r.invalidateQueries({queryKey:["archives"]}),r.invalidateQueries({queryKey:["archiveStats"]}),l(M=>M.map(C=>{const j=k.results.find(E=>E.filename===C.file.name),P=k.errors.find(E=>E.filename===C.file.name);return j?{...C,status:"success",archiveId:j.id}:P?{...C,status:"error",error:P.error}:C})),k.failed===0?i(`${k.uploaded} file${k.uploaded!==1?"s":""} uploaded`):k.uploaded===0?i(`Failed to upload ${k.failed} file${k.failed!==1?"s":""}`,"error"):i(`${k.uploaded} uploaded, ${k.failed} failed`,"warning")},onError:()=>{l(k=>k.map(M=>({...M,status:"error",error:"Upload failed"}))),i("Upload failed","error")}}),p=w.useCallback(k=>{k.preventDefault(),d(!0)},[]),x=w.useCallback(k=>{k.preventDefault(),d(!1)},[]),v=w.useCallback(k=>{k.preventDefault(),d(!1);const M=Array.from(k.dataTransfer.files).filter(C=>C.name.endsWith(".3mf"));M.length>0&&l(C=>[...C,...M.map(j=>({file:j,status:"pending"}))])},[]),g=w.useCallback(k=>{const M=Array.from(k.target.files||[]).filter(C=>C.name.endsWith(".3mf"));M.length>0&&l(C=>[...C,...M.map(j=>({file:j,status:"pending"}))]),s.current&&(s.current.value="")},[]),y=w.useCallback(k=>{l(M=>M.filter((C,j)=>j!==k))},[]),_=()=>{if(o.length===0)return;const k=o.filter(M=>M.status==="pending");k.length!==0&&(l(M=>M.map(C=>C.status==="pending"?{...C,status:"uploading"}:C)),f.mutate(k.map(M=>M.file)))},N=o.filter(k=>k.status==="pending").length,T=f.isPending;return a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:a.jsx(wt,{className:"w-full max-w-2xl max-h-[90vh] flex flex-col",children:a.jsxs(Nt,{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(Rt,{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:p,onDragLeave:x,onDrop:v,children:[a.jsx(La,{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(Me,{variant:"secondary",onClick:()=>s.current?.click(),disabled:T,children:n("uploadModal.browseFiles")}),a.jsx("input",{ref:s,type:"file",accept:".3mf",multiple:!0,className:"hidden",onChange:g})]})}),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((k,M)=>a.jsxs("div",{className:"flex items-center gap-3 p-3 bg-bambu-dark rounded-lg",children:[a.jsx(HC,{className:"w-5 h-5 text-bambu-gray flex-shrink-0"}),a.jsx("span",{className:"flex-1 text-white text-sm truncate",children:k.file.name}),a.jsxs("span",{className:"text-xs text-bambu-gray",children:[(k.file.size/(1024*1024)).toFixed(1)," MB"]}),k.status==="pending"&&a.jsx("button",{onClick:()=>y(M),className:"text-bambu-gray hover:text-red-400 transition-colors",disabled:T,children:a.jsx(Rt,{className:"w-4 h-4"})}),k.status==="uploading"&&a.jsx(at,{className:"w-4 h-4 text-bambu-green animate-spin"}),k.status==="success"&&a.jsx(br,{className:"w-4 h-4 text-bambu-green"}),k.status==="error"&&a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-xs text-red-400",children:k.error}),a.jsx(Wa,{className:"w-4 h-4 text-red-400"})]})]},`${k.file.name}-${M}`))})}),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(Me,{variant:"secondary",onClick:t,className:"flex-1",children:n(u?"common.close":"common.cancel")}),!u&&a.jsx(Me,{onClick:_,disabled:N===0||T,className:"flex-1",children:T?a.jsxs(a.Fragment,{children:[a.jsx(at,{className:"w-4 h-4 animate-spin"}),n("uploadModal.uploading")]}):a.jsxs(a.Fragment,{children:[a.jsx(La,{className:"w-4 h-4"}),n("uploadModal.upload")," ",N>0&&`(${N})`]})})]})]})})})}const $$e=["adhesionFailure","spaghettiDetached","layerShift","cloggedNozzle","filamentRunout","warping","stringing","underExtrusion","powerFailure","userCancelled","other"],V$e=["completed","failed","aborted","printing"];function vne({archive:t,onClose:e,existingTags:n=[]}){const{t:r}=Dt();w.useEffect(()=>{const de=le=>{le.key==="Escape"&&e()};return window.addEventListener("keydown",de),()=>window.removeEventListener("keydown",de)},[e]);const i=Jt(),[s,o]=w.useState(t.print_name||""),[l,c]=w.useState(t.printer_id),[d,u]=w.useState(t.project_id??null),[h,f]=w.useState(t.notes||""),[p,x]=w.useState(t.tags||""),[v,g]=w.useState(t.failure_reason||""),[y,_]=w.useState(t.status),[N,T]=w.useState(t.quantity??1),[k,M]=w.useState(t.photos||[]),[C,j]=w.useState(t.external_url||""),[P,E]=w.useState(!1),[B,O]=w.useState(!1),z=w.useRef(null),D=w.useRef(null),$=w.useRef(null),{data:G}=Je({queryKey:["printers"],queryFn:ne.getPrinters}),{data:U}=Je({queryKey:["projects"],queryFn:()=>ne.getProjects()}),{data:W}=Je({queryKey:["tags"],queryFn:ne.getTags,enabled:n.length===0}),Y=n.length>0?n:W?.map(de=>de.name)||[],re=p.split(",").map(de=>de.trim()).filter(Boolean),H=p.includes(",")?p.substring(p.lastIndexOf(",")+1).trim().toLowerCase():p.trim().toLowerCase(),K=Y.filter(de=>!re.includes(de)&&(H===""||de.toLowerCase().includes(H))),ee=de=>{let le;if(H&&!Y.includes(H)?le=p.includes(",")?p.substring(0,p.lastIndexOf(",")).split(",").map(_e=>_e.trim()).filter(Boolean):[]:le=re,!le.includes(de)){const _e=[...le,de].join(", ");x(_e)}$.current!==null&&clearTimeout($.current),z.current?.focus()},Z=de=>{const le=re.filter(_e=>_e!==de).join(", ");x(le)},we=st({mutationFn:de=>ne.updateArchive(t.id,de),onSuccess:()=>{i.invalidateQueries({queryKey:["archives"]}),i.invalidateQueries({queryKey:["projects"]}),e()}}),oe=async de=>{const le=de.target.files?.[0];if(le){E(!0);try{const _e=await ne.uploadArchivePhoto(t.id,le);M(_e.photos),i.invalidateQueries({queryKey:["archives"]})}catch(_e){console.error("Failed to upload photo:",_e)}finally{E(!1),D.current&&(D.current.value="")}}},J=async de=>{try{const le=await ne.deleteArchivePhoto(t.id,de);M(le.photos||[]),i.invalidateQueries({queryKey:["archives"]})}catch(le){console.error("Failed to delete photo:",le)}},je=de=>{de.preventDefault();const le={print_name:s||void 0,printer_id:l,project_id:d,notes:h||void 0,tags:p||void 0,quantity:N,external_url:C||null};y!==t.status&&(le.status=y),y==="failed"||y==="aborted"?le.failure_reason=v||void 0:(t.status==="failed"||t.status==="aborted")&&(le.failure_reason=null),we.mutate(le)};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:de=>de.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(Rt,{className:"w-5 h-5"})})]}),a.jsxs("form",{onSubmit:je,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:de=>o(de.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:de=>c(de.target.value?Number(de.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")}),G?.map(de=>a.jsx("option",{value:de.id,children:de.name},de.id))]})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[a.jsx(xs,{className:"w-4 h-4 inline mr-1"}),r("editArchive.project")]}),a.jsxs("select",{value:d??"",onChange:de=>u(de.target.value?Number(de.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")}),U?.map(de=>a.jsx("option",{value:de.id,children:de.name},de.id))]})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[a.jsx(Ume,{className:"w-4 h-4 inline mr-1"}),r("editArchive.itemsPrinted")]}),a.jsx("input",{type:"number",min:1,value:N,onChange:de=>T(Math.max(1,parseInt(de.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:h,onChange:de=>f(de.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(Vb,{className:"w-4 h-4 inline mr-1"}),r("editArchive.externalLink")]}),a.jsx("input",{type:"url",value:C,onChange:de=>j(de.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(de=>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(Vh,{className:"w-3 h-3"}),de,a.jsx("button",{type:"button",onClick:()=>Z(de),className:"ml-0.5 text-bambu-gray hover:text-white",children:a.jsx(Rt,{className:"w-3 h-3"})})]},de))}),a.jsxs("div",{className:"relative",children:[a.jsx("input",{ref:z,type:"text",value:p,onChange:de=>x(de.target.value),onFocus:()=>{$.current!==null&&clearTimeout($.current),O(!0)},onBlur:()=>{$.current=window.setTimeout(()=>O(!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")}),B&&K.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:[H?r("editArchive.matchingTags",{query:H}):r("editArchive.existingTags")," ",r("editArchive.clickToAdd")]}),a.jsx("div",{className:"p-2 flex flex-wrap gap-1.5",children:K.map(de=>a.jsx("button",{type:"button",onClick:()=>ee(de),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:de},de))})]})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("editArchive.status")}),a.jsx("select",{value:y,onChange:de=>{_(de.target.value),de.target.value==="completed"&&g("")},className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:V$e.map(de=>a.jsx("option",{value:de,children:r(`editArchive.statuses.${de}`)},de))})]}),(y==="failed"||y==="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:de=>g(de.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")}),$$e.map(de=>a.jsx("option",{value:r(`editArchive.failureReasons.${de}`),children:r(`editArchive.failureReasons.${de}`)},de))]})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[a.jsx(cb,{className:"w-4 h-4 inline mr-1"}),r("editArchive.photos")]}),a.jsxs("div",{className:"flex flex-wrap gap-2 mb-2",children:[k.map(de=>a.jsxs("div",{className:"relative group",children:[a.jsx("img",{src:ne.getArchivePhotoUrl(t.id,de),alt:r("editArchive.printResult"),className:"w-20 h-20 object-cover rounded-lg border border-bambu-dark-tertiary"}),a.jsx("button",{type:"button",onClick:()=>J(de),className:"absolute -top-1 -right-1 p-1 bg-red-500 rounded-full opacity-0 group-hover:opacity-100 transition-opacity",children:a.jsx(Xt,{className:"w-3 h-3 text-white"})})]},de)),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:D,type:"file",accept:"image/jpeg,image/png,image/webp",onChange:oe,className:"hidden",disabled:P}),P?a.jsx(at,{className:"w-6 h-6 text-bambu-gray animate-spin"}):a.jsx(Xn,{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(Me,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:r("common.cancel")}),a.jsxs(Me,{type:"submit",disabled:we.isPending,className:"flex-1",children:[a.jsx(bs,{className:"w-4 h-4"}),we.isPending?r("common.saving"):r("common.save")]})]})]})]})})}function wne({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,h]=w.useState(!1),[f,p]=w.useState({});w.useEffect(()=>{const g=N=>{i.current&&!i.current.contains(N.target)&&r()},y=N=>{N.key==="Escape"&&r()},_=()=>{r()};return document.addEventListener("mousedown",g),document.addEventListener("keydown",y),document.addEventListener("scroll",_,!0),()=>{document.removeEventListener("mousedown",g),document.removeEventListener("keydown",y),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 g=i.current.getBoundingClientRect(),y=window.innerWidth,_=window.innerHeight,N=8;let T=t,k=e;t+g.width>y-N&&(T=Math.max(N,y-g.width-N)),T_-N&&(k=Math.max(N,_-g.height-N)),kM),d({x:T,y:k,visible:!0})}},[t,e]);const x=(g,y)=>{l.current&&(clearTimeout(l.current),l.current=null);const _=y.getBoundingClientRect(),N=window.innerHeight,T=300,C=N-_.top-8T;p(j=>({...j,[g]:C?"bottom":"top"})),o(g)},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((g,y)=>{if(g.divider)return a.jsx("div",{className:"my-1 border-t border-bambu-dark-tertiary"},y);const _=g.submenu&&g.submenu.length>0;return a.jsxs("div",{className:"relative",onMouseEnter:N=>_&&x(y,N.currentTarget),onMouseLeave:()=>_&&v(),children:[a.jsxs("button",{onMouseEnter:N=>_&&x(y,N.currentTarget.parentElement),onClick:()=>{_?o(s===y?null:y):g.disabled||(g.onClick(),r())},disabled:g.disabled,title:g.title,className:`w-full flex items-center gap-2 px-3 py-2 text-sm text-left transition-colors ${g.disabled?"text-bambu-gray cursor-not-allowed":g.danger?"text-red-400 hover:bg-red-400/10":"text-white hover:bg-bambu-dark-tertiary"} ${_&&s===y?"bg-bambu-dark-tertiary":""}`,children:[g.icon&&a.jsx("span",{className:"w-4 h-4 flex-shrink-0 flex items-center justify-center",children:g.icon}),a.jsx("span",{className:"flex-1",children:g.label}),_&&a.jsx(yi,{className:"w-4 h-4 text-bambu-gray"})]}),_&&s===y&&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"} ${f[y]==="bottom"?"bottom-0":"top-0"}`,onMouseEnter:()=>{l.current&&(clearTimeout(l.current),l.current=null)},onMouseLeave:()=>v(),children:g.submenu.map((N,T)=>a.jsxs("button",{onClick:()=>{N.disabled||(N.onClick(),r())},disabled:N.disabled,className:`w-full flex items-center gap-2 px-3 py-2 text-sm text-left transition-colors ${N.disabled?"text-bambu-gray cursor-not-allowed":N.danger?"text-red-400 hover:bg-red-400/10":"text-white hover:bg-bambu-dark-tertiary"}`,children:[N.icon&&a.jsx("span",{className:"w-4 h-4 flex-shrink-0 flex items-center justify-center",children:N.icon}),N.label]},T))})]},y)})})}function q$e({selectedIds:t,existingTags:e,onClose:n}){const r=Jt(),{showToast:i}=ln(),[s,o]=w.useState(""),[l,c]=w.useState(new Set),[d,u]=w.useState("add");w.useEffect(()=>{const v=g=>{g.key==="Escape"&&n()};return window.addEventListener("keydown",v),()=>window.removeEventListener("keydown",v)},[n]);const h=st({mutationFn:async()=>{const v=Array.from(l);let g=0;for(const y of t)try{const _=await ne.getArchive(y),N=_.tags?_.tags.split(",").map(k=>k.trim()).filter(Boolean):[];let T;d==="add"?T=[...new Set([...N,...v])]:T=N.filter(k=>!l.has(k)),await ne.updateArchive(y,{tags:T.join(", ")}),g++}catch(_){throw console.error(`Failed to update archive ${y}:`,_),new Error(`Failed on archive ${y}: ${_ instanceof Error?_.message:"Unknown error"}`)}return{count:g,mode:d,tags:v}},onSuccess:({count:v,mode:g,tags:y})=>{r.invalidateQueries({queryKey:["archives"]}),i(`${g==="add"?"Added":"Removed"} ${y.length} tag${y.length!==1?"s":""} ${g==="add"?"to":"from"} ${v} archive${v!==1?"s":""}`),n()},onError:v=>{i(v.message||"Failed to update tags","error")}}),f=v=>{c(g=>{const y=new Set(g);return y.has(v)?y.delete(v):y.add(v),y})},p=()=>{s.trim()&&!l.has(s.trim())&&(c(v=>new Set([...v,s.trim()])),o(""))},x=v=>{v.key==="Enter"&&(v.preventDefault(),p())};return a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:a.jsx(wt,{className:"w-full max-w-md",children:a.jsxs(Nt,{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(Vh,{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(Rt,{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(Me,{size:"sm",variant:d==="add"?"primary":"secondary",onClick:()=>u("add"),children:"Add Tags"}),a.jsx(Me,{size:"sm",variant:d==="remove"?"primary":"secondary",onClick:()=>u("remove"),children:"Remove Tags"})]}),d==="add"&&a.jsxs("div",{className:"flex gap-2",children:[a.jsx("input",{type:"text",placeholder:"Enter new tag...",className:"flex-1 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",value:s,onChange:v=>o(v.target.value),onKeyDown:x}),a.jsx(Me,{size:"sm",variant:"secondary",onClick:p,disabled:!s.trim(),children:a.jsx(Xn,{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:()=>f(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:()=>f(v),className:"hover:opacity-70",children:a.jsx(Rt,{className:"w-3 h-3"})})]},v))})]})]}),a.jsxs("div",{className:"flex gap-3 p-4 border-t border-bambu-dark-tertiary",children:[a.jsx(Me,{variant:"secondary",onClick:n,className:"flex-1",children:"Cancel"}),a.jsx(Me,{onClick:()=>h.mutate(),disabled:l.size===0||h.isPending,className:"flex-1",children:h.isPending?a.jsxs(a.Fragment,{children:[a.jsx(at,{className:"w-4 h-4 animate-spin"}),"Processing..."]}):a.jsxs(a.Fragment,{children:[a.jsx(Vh,{className:"w-4 h-4"}),d==="add"?"Add Tags":"Remove Tags"]})})]})]})})})}function G$e({selectedIds:t,onClose:e}){const n=Jt(),{showToast:r}=ln(),{data:i,isLoading:s}=Je({queryKey:["projects"],queryFn:()=>ne.getProjects()});w.useEffect(()=>{const u=h=>{h.key==="Escape"&&e()};return window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)},[e]);const o=()=>{n.invalidateQueries({queryKey:["archives"]}),n.invalidateQueries({queryKey:["projects"]}),n.invalidateQueries({queryKey:["project"]}),n.invalidateQueries({queryKey:["project-archives"]})},l=st({mutationFn:async u=>(await ne.addArchivesToProject(u,t),u),onSuccess:u=>{const h=i?.find(f=>f.id===u);o(),r(`Added ${t.length} archive${t.length!==1?"s":""} to "${h?.name}"`),e()},onError:()=>{r("Failed to assign project","error")}}),c=st({mutationFn:async()=>{for(const u of t)await ne.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(wt,{className:"w-full max-w-md max-h-[80vh] flex flex-col",children:a.jsxs(Nt,{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(xs,{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(Rt,{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(at,{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(bi,{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(at,{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(xs,{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(at,{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(Me,{variant:"secondary",onClick:e,className:"flex-1",disabled:d,children:"Cancel"})})]})})})}function W$e(t,e){return new Date(t,e+1,0).getDate()}function K$e(t,e){return new Date(t,e,1).getDay()}const Y$e=["January","February","March","April","May","June","July","August","September","October","November","December"],X$e=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];function Q$e({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,h]=w.useState(null),f=w.useMemo(()=>{const k=new Map;return t.forEach(M=>{const C=er(M.completed_at||M.created_at)||new Date,j=`${C.getFullYear()}-${String(C.getMonth()+1).padStart(2,"0")}-${String(C.getDate()).padStart(2,"0")}`,P=k.get(j)||[];P.push(M),k.set(j,P)}),k},[t]),p=W$e(o,i),x=K$e(o,i),v=()=>{i===0?(s(11),l(o-1)):s(i-1)},g=()=>{i===11?(s(0),l(o+1)):s(i+1)},y=()=>{s(r.getMonth()),l(r.getFullYear())},_=[];for(let k=0;k{k!==c&&h(null),d(k)};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(Kl,{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:[Y$e[i]," ",o]}),a.jsx("button",{onClick:y,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:g,className:"p-2 hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:a.jsx(yi,{className:"w-5 h-5 text-bambu-gray"})})]}),a.jsx("div",{className:"grid grid-cols-7 gap-1 mb-1",children:X$e.map(k=>a.jsx("div",{className:"text-center text-xs text-bambu-gray py-2",children:k},k))}),a.jsx("div",{className:"grid grid-cols-7 gap-1",children:_.map((k,M)=>{if(k===null)return a.jsx("div",{className:"aspect-square"},`empty-${M}`);const C=`${o}-${String(i+1).padStart(2,"0")}-${String(k).padStart(2,"0")}`,j=f.get(C)||[],P=j.length>0,E=k===r.getDate()&&i===r.getMonth()&&o===r.getFullYear(),B=C===c,O=j.filter(D=>D.status==="completed").length,z=j.filter(D=>D.status==="failed").length;return a.jsxs("button",{onClick:()=>T(B?null:C),className:`aspect-square rounded-lg p-1 flex flex-col items-center justify-center transition-colors relative ${B?"bg-bambu-green text-white":E?"bg-bambu-green/20 text-white ring-2 ring-bambu-green":P?"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 ${E&&!B?"text-bambu-green":""}`,children:k}),P&&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 ${z>0&&O===0?"bg-red-400":z>0?"bg-yellow-400":"bg-green-400"}`}),a.jsx("span",{className:"text-xs font-medium",children:j.length})]})]},k)})}),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(k=>{const M=er(k.completed_at||k.created_at)||new Date;return M.getMonth()===i&&M.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(k=>{const M=er(k.completed_at||k.created_at)||new Date;return M.getMonth()===i&&M.getFullYear()===o&&k.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(k=>{const M=er(k.completed_at||k.created_at)||new Date;return M.getMonth()===i&&M.getFullYear()===o&&k.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"})}),N.length>0?a.jsx("div",{className:"calendar-scroll space-y-2 max-h-96 overflow-y-auto",children:N.map(k=>{const M=k.id===u||k.id===n;return a.jsxs("button",{onClick:()=>{h(k.id),e?.(k)},className:`w-full flex items-center gap-3 p-2 rounded-lg transition-colors text-left ${M?"":"hover:bg-bambu-dark-tertiary"}`,style:M?{outline:"4px solid #facc15",outlineOffset:"2px"}:void 0,children:[k.thumbnail_path?a.jsx("img",{src:ne.getArchiveThumbnail(k.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:k.print_name||k.filename}),a.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[a.jsx("span",{className:k.status==="failed"?"text-red-400":"text-green-400",children:k.status==="failed"?"Failed":"Completed"}),k.filament_color&&a.jsx("div",{className:"flex gap-0.5",children:k.filament_color.split(",").map((C,j)=>a.jsx("div",{className:"w-3 h-3 rounded-full border border-white/20",style:{backgroundColor:C}},j))})]})]})]},k.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 Sne({archiveId:t,archiveName:e,onClose:n}){const r=ne.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(Rt,{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(Me,{onClick:i,className:"w-full",children:[a.jsx(ha,{className:"w-4 h-4"}),"Download QR Code"]})]})]})})}function _ne({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 p=x=>{x.key==="Escape"&&r(),x.key==="ArrowLeft"&&o(v=>Math.max(0,v-1)),x.key==="ArrowRight"&&o(v=>Math.min(n.length-1,v+1))};return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[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=ne.getArchivePhotoUrl(t,d),h=()=>{const p=document.createElement("a");p.href=u,p.download=`${e}_photo_${s+1}.jpg`,p.click()},f=()=>{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:p=>p.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(Me,{variant:"secondary",size:"sm",onClick:h,children:[a.jsx(ha,{className:"w-4 h-4"}),"Download"]}),i&&a.jsx(Me,{variant:"secondary",size:"sm",onClick:f,className:"text-red-400 hover:text-red-300",children:a.jsx(Xt,{className:"w-4 h-4"})}),a.jsx("button",{onClick:r,className:"p-2 text-bambu-gray hover:text-white transition-colors",children:a.jsx(Rt,{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(p=>p-1),className:"absolute left-4 z-10 p-3 bg-black/50 hover:bg-black/70 rounded-full transition-colors",children:a.jsx(Kl,{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(p=>p+1),className:"absolute right-4 z-10 p-3 bg-black/50 hover:bg-black/70 rounded-full transition-colors",children:a.jsx(yi,{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((p,x)=>a.jsx("button",{onClick:()=>o(x),className:`w-16 h-16 rounded-lg overflow-hidden border-2 transition-colors ${x===s?"border-bambu-green":"border-transparent hover:border-bambu-gray"}`,children:a.jsx("img",{src:ne.getArchivePhotoUrl(t,p),alt:`Thumbnail ${x+1}`,className:"w-full h-full object-cover"})},p))})]}),l&&a.jsx(xn,{title:"Delete Photo",message:"Delete this photo? This cannot be undone.",confirmText:"Delete",variant:"danger",onConfirm:()=>{i?.(d),c(!1)},onCancel:()=>c(!1)})]})}function Qi(t){this.content=t}Qi.prototype={constructor:Qi,find:function(t){for(var e=0;e>1}};Qi.from=function(t){if(t instanceof Qi)return t;var e=[];if(t)for(var n in t)e.push(n,t[n]);return new Qi(e)};function Nne(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=Nne(i.content,s.content,n+1);if(o!=null)return o}n+=i.nodeSize}}function Cne(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 Pt(r,i)}cutByIndex(e,n){return e==n?Pt.empty:e==0&&n==this.content.length?this:new Pt(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 Pt(i,s)}addToStart(e){return new Pt([e].concat(this.content),this.size+e.nodeSize)}addToEnd(e){return new Pt(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?w_(n+1,s):w_(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 Pt.empty;if(!Array.isArray(n))throw new RangeError("Invalid input for Fragment.fromJSON");return new Pt(n.map(e.nodeFromJSON))}static fromArray(e){if(!e.length)return Pt.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}};Gr.none=[];class HN extends Error{}class qt{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=Ane(this.content,e+this.openStart,n);return r&&new qt(r,this.openStart,this.openEnd)}removeBetween(e,n){return new qt(kne(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 qt.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 qt(Pt.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 qt(e,r,i)}}qt.empty=new qt(Pt.empty,0,0);function kne(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(kne(s.content,e-i-1,n-i-1)))}function Ane(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=Ane(o.content,e-s-1,n,o);return l&&t.replaceChild(i,o.copy(l))}function Z$e(t,e,n){if(n.openStart>t.depth)throw new HN("Inserted content deeper than insertion position");if(t.depth-n.openStart!=e.depth-n.openEnd)throw new HN("Inconsistent open depths");return Tne(t,e,n,0)}function Tne(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 Yy(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&&(wf(t.nodeAfter,r),s++));for(let l=s;li&&vR(t,e,i+1),o=r.depth>i&&vR(n,r,i+1),l=[];return Yy(null,t,i,l),s&&o&&e.index(i)==n.index(i)?(Mne(s,o),wf(Sf(s,Pne(t,e,n,r,i+1)),l)):(s&&wf(Sf(s,$N(t,e,i+1)),l),Yy(e,n,i,l),o&&wf(Sf(o,$N(n,r,i+1)),l)),Yy(r,null,i,l),new Pt(l)}function $N(t,e,n){let r=[];if(Yy(null,t,n,r),t.depth>n){let i=vR(t,e,n+1);wf(Sf(i,$N(t,e,n+1)),r)}return Yy(e,null,n,r),new Pt(r)}function J$e(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(Pt.from(i));return{start:i.resolveNoCache(t.openStart+n),end:i.resolveNoCache(i.content.size-t.openEnd-n)}}class qv{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 VN(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 qv(n,r,s)}static resolveCached(e,n){let r=d9.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()+")"),Ene(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=Pt.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=Pt.fromJSON(e,n.content),s=e.nodeType(n.type).create(n.attrs,i,r);return s.type.checkAttrs(s.attrs),s}};Uh.prototype.text=void 0;class qN extends Uh{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):Ene(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 qN(this.type,this.attrs,this.text,e)}withText(e){return e==this.text?this:new qN(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 Ene(t,e){for(let n=t.length-1;n>=0;n--)e=t[n].type.name+"("+e+")";return e}class Kf{constructor(e){this.validEnd=e,this.next=[],this.wrapCache=[]}static parse(e,n){let r=new rVe(e,n);if(r.next==null)return Kf.empty;let i=jne(r);r.next&&r.err("Unexpected trailing text");let s=dVe(cVe(i));return uVe(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(` + `,title:T("printers:control")?g(Ft?"printers.resume":"printers.pause"):g("printers.permission.noControl"),children:[Ft?a.jsx(io,{className:"w-3 h-3"}):a.jsx(KC,{className:"w-3 h-3"}),g(Ft?"printers.resume":"printers.pause")]})]})]})]})})(),(Ct?.length>0||fe.vt_tray.length>0)&&r==="expanded"&&(()=>{const gt=Ct.filter(St=>St.tray.length>1),Ft=Ct.filter(St=>St.tray.length===1),Wn=t.nozzle_count===2||fe?.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:g("printers.filaments")}),a.jsx("div",{className:"flex-1 h-px bg-bambu-dark-tertiary/30"})]}),a.jsxs("div",{className:"space-y-3",children:[gt.length>0&&a.jsx("div",{className:"grid grid-cols-2 gap-3",children:gt.map(St=>{const Cn=Ve[String(St.id)],Na=St.id>=128?St.id-128:St.id,nr=Cn!==void 0?Cn:Na,pa=nr===1,xr=nr===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("span",{className:"text-[10px] text-white font-medium",children:th(St.id,St.tray.length)}),Wn&&(pa||xr)&&a.jsx(t9,{side:pa?"L":"R"})]}),(St.humidity!=null||St.temp!=null)&&a.jsxs("div",{className:"flex items-center gap-1.5 max-[550px]:flex-col max-[550px]:items-start",children:[St.humidity!=null&&a.jsx(r9,{humidity:St.humidity,goodThreshold:s?.humidityGood,fairThreshold:s?.humidityFair,onClick:()=>se({amsId:St.id,amsLabel:th(St.id,St.tray.length),mode:"humidity"}),compact:!0}),St.temp!=null&&a.jsx(a9,{temp:St.temp,goodThreshold:s?.tempGood,fairThreshold:s?.tempFair,onClick:()=>se({amsId:St.id,amsLabel:th(St.id,St.tray.length),mode:"temperature"}),compact:!0})]})]}),a.jsx("div",{className:"grid grid-cols-4 gap-1.5",children:[0,1,2,3].map(en=>{const Un=St.tray[en]||St.tray.find(Tn=>Tn.id===en),Hi=Un?.tray_type&&Un.remain>=0,hi=!Un?.tray_type,Tl=St.id*4+en,Io=Mt===Tl,ho=Un?.tray_info_idx?ve?.[Un.tray_info_idx]:null,Ua=Ge?.[Tl],ga=Un?.tray_uuid?.toUpperCase(),Xa=ga?c?.[ga]:void 0,Ba=W2(Xa),Ha=u?.(t.id,St.id,en),cr=(()=>{const Tn=Ha?.spool;return Tn&&Tn.label_weight>0&&Tn.weight_used!=null?Math.round(Math.max(0,Tn.label_weight-Tn.weight_used)/Tn.label_weight*100):null})(),$a=Ba??cr??(Hi?Un.remain:null),Kc=Ba!==null?"spoolman":cr!==null?"inventory":Hi?"ams":void 0,Nr=Un?.tray_type?{vendor:K2(Un)?"Bambu Lab":"Generic",profile:ho?.name||Ua?.preset_name||Un.tray_sub_brands||Un.tray_type,colorName:H2(Un.tray_id_name)||$2(Un.tray_color),colorHex:Un.tray_color||null,kFactor:V2(Un.k),fillLevel:$a,trayUuid:Un.tray_uuid||null,tagUid:Un.tag_uid||null,fillSource:Kc}:null,ba=lt?.amsId===St.id&<?.slotId===en,an=a.jsxs("div",{className:`bg-bambu-dark-tertiary rounded p-1 text-center ${hi?"opacity-50":""} ${Io?"ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark":""}`,children:[a.jsx("div",{className:"w-3.5 h-3.5 rounded-full mx-auto mb-0.5 border-2",style:{backgroundColor:Un?.tray_color?`#${Un.tray_color}`:Un?.tray_type?"#333":"transparent",borderColor:hi?"#666":"rgba(255,255,255,0.1)",borderStyle:hi?"dashed":"solid"}}),a.jsx("div",{className:"text-[9px] text-white font-bold truncate",children:Un?.tray_type||"—"}),a.jsx("div",{className:"mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden",children:$a!==null&&$a>=0&&Un&&a.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${$a}%`,backgroundColor:G2($a)}})})]});return a.jsxs("div",{className:"relative group",children:[ba&&a.jsx("div",{className:"absolute inset-0 bg-bambu-dark-tertiary/80 rounded flex items-center justify-center z-20",children:a.jsx(vr,{className:"w-4 h-4 text-bambu-green animate-spin"})}),fe?.state!=="RUNNING"&&a.jsx("button",{onClick:Tn=>{Tn.stopPropagation(),Yr(pn?.amsId===St.id&&pn?.slotId===en?null:{amsId:St.id,slotId:en})},className:"absolute -top-1 -right-1 w-4 h-4 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity z-10 hover:bg-bambu-dark-tertiary",title:g("printers.slotOptions"),children:a.jsx(Th,{className:"w-2.5 h-2.5 text-bambu-gray"})}),fe?.state!=="RUNNING"&&pn?.amsId===St.id&&pn?.slotId===en&&a.jsx("div",{className:"absolute top-full left-0 mt-1 z-50 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl py-1 min-w-[120px]",children:a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-xs flex items-center gap-2 ${T("printers:ams_rfid")?"text-white hover:bg-bambu-dark-tertiary":"text-bambu-gray/50 cursor-not-allowed"}`,onClick:Tn=>{Tn.stopPropagation(),T("printers:ams_rfid")&&(It.mutate({amsId:St.id,slotId:en}),Yr(null))},disabled:ba||!T("printers:ams_rfid"),title:T("printers:ams_rfid")?void 0:g("printers.permission.noAmsRfid"),children:[a.jsx(vr,{className:`w-3 h-3 ${ba?"animate-spin":""}`}),g("printers.rfid.reread")]})}),Nr?a.jsx(U2,{data:Nr,spoolman:{enabled:o,hasUnlinkedSpools:l,linkedSpoolId:Nr.trayUuid?c?.[Nr.trayUuid.toUpperCase()]?.id:void 0,spoolmanUrl:d,onLinkSpool:o&&Nr.trayUuid?Tn=>{V({tagUid:Nr.tagUid||"",trayUuid:Tn,printerId:t.id,amsId:St.id,trayId:en})}:void 0},inventory:o?void 0:(()=>{const Tn=u?.(t.id,St.id,en);return{assignedSpool:Tn?.spool?{id:Tn.spool.id,material:Tn.spool.material,brand:Tn.spool.brand,color_name:Tn.spool.color_name,remainingWeightGrams:Math.max(0,Math.round(Tn.spool.label_weight-Tn.spool.weight_used))}:null,onAssignSpool:Nr.vendor!=="Bambu Lab"?()=>me({printerId:t.id,amsId:St.id,trayId:en,trayInfo:{type:Nr.profile,color:Nr.colorHex||"",location:`${th(St.id,St.tray.length)} Slot ${en+1}`}}):void 0,onUnassignSpool:Tn&&Nr.vendor!=="Bambu Lab"?()=>h?.(t.id,St.id,en):void 0}})(),configureSlot:{enabled:T("printers:control"),onConfigure:()=>ie({amsId:St.id,trayId:en,trayCount:St.tray.length,trayType:Un?.tray_type||void 0,trayColor:Un?.tray_color||void 0,traySubBrands:Un?.tray_sub_brands||void 0,trayInfoIdx:Un?.tray_info_idx||void 0,extruderId:Cn,caliIdx:Un?.cali_idx,savedPresetId:Ua?.preset_id})},children:an}):a.jsx(B2,{configureSlot:{enabled:T("printers:control"),onConfigure:()=>ie({amsId:St.id,trayId:en,trayCount:St.tray.length,extruderId:Cn})},children:an})]},en)})})]},St.id)})}),(Ft.length>0||fe.vt_tray.length>0)&&a.jsxs("div",{className:"grid grid-cols-4 gap-3",children:[Ft.map(St=>{const Cn=Ve[String(St.id)],Na=St.id>=128?St.id-128:St.id,nr=Cn!==void 0?Cn:Na,pa=nr===1,xr=nr===0,en=St.tray[0],Un=en?.tray_type&&en.remain>=0,Hi=!en?.tray_type,hi=f4(St.id,en?.id??0,!1),Tl=Mt===hi,Io=en?.tray_info_idx?ve?.[en.tray_info_idx]:null,ho=Ge?.[hi],Ua=en?.tray_uuid?.toUpperCase(),ga=Ua?c?.[Ua]:void 0,Xa=W2(ga),Ba=en?.id??0,Ha=u?.(t.id,St.id,Ba),cr=(()=>{const dr=Ha?.spool;return dr&&dr.label_weight>0&&dr.weight_used!=null?Math.round(Math.max(0,dr.label_weight-dr.weight_used)/dr.label_weight*100):null})(),$a=Xa??cr??(Un?en.remain:null),Kc=Xa!==null?"spoolman":cr!==null?"inventory":Un?"ams":void 0,Nr=en?.tray_type?{vendor:K2(en)?"Bambu Lab":"Generic",profile:Io?.name||ho?.preset_name||en.tray_sub_brands||en.tray_type,colorName:H2(en.tray_id_name)||$2(en.tray_color),colorHex:en.tray_color||null,kFactor:V2(en.k),fillLevel:$a,trayUuid:en.tray_uuid||null,tagUid:en.tag_uid||null,fillSource:Kc}:null,ba=en?.id??0,an=lt?.amsId===St.id&<?.slotId===ba,Tn=a.jsxs("div",{className:`bg-bambu-dark-tertiary rounded p-1 text-center ${Hi?"opacity-50":""} ${Tl?"ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark":""}`,children:[a.jsx("div",{className:"w-3.5 h-3.5 rounded-full mx-auto mb-0.5 border-2",style:{backgroundColor:en?.tray_color?`#${en.tray_color}`:en?.tray_type?"#333":"transparent",borderColor:Hi?"#666":"rgba(255,255,255,0.1)",borderStyle:Hi?"dashed":"solid"}}),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:$a!==null&&$a>=0&&a.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${$a}%`,backgroundColor:G2($a)}})})]});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("span",{className:"text-[10px] text-white font-medium",children:th(St.id,St.tray.length)}),Wn&&(pa||xr)&&a.jsx(t9,{side:pa?"L":"R"})]}),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:[an&&a.jsx("div",{className:"absolute inset-0 bg-bambu-dark-tertiary/80 rounded flex items-center justify-center z-20",children:a.jsx(vr,{className:"w-4 h-4 text-bambu-green animate-spin"})}),fe?.state!=="RUNNING"&&a.jsx("button",{onClick:dr=>{dr.stopPropagation(),Yr(pn?.amsId===St.id&&pn?.slotId===ba?null:{amsId:St.id,slotId:ba})},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:g("printers.slotOptions"),children:a.jsx(Th,{className:"w-2.5 h-2.5 text-bambu-gray"})}),fe?.state!=="RUNNING"&&pn?.amsId===St.id&&pn?.slotId===ba&&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 ${T("printers:ams_rfid")?"text-white hover:bg-bambu-dark-tertiary":"text-bambu-gray/50 cursor-not-allowed"}`,onClick:dr=>{dr.stopPropagation(),T("printers:ams_rfid")&&(It.mutate({amsId:St.id,slotId:ba}),Yr(null))},disabled:an||!T("printers:ams_rfid"),title:T("printers:ams_rfid")?void 0:g("printers.permission.noAmsRfid"),children:[a.jsx(vr,{className:`w-3 h-3 ${an?"animate-spin":""}`}),g("printers.rfid.reread")]})}),Nr?a.jsx(U2,{data:Nr,spoolman:{enabled:o,hasUnlinkedSpools:l,linkedSpoolId:Nr.trayUuid?c?.[Nr.trayUuid.toUpperCase()]?.id:void 0,spoolmanUrl:d,onLinkSpool:o&&Nr.trayUuid?dr=>{V({tagUid:Nr.tagUid||"",trayUuid:dr,printerId:t.id,amsId:St.id,trayId:ba})}:void 0},inventory:o?void 0:(()=>{const dr=u?.(t.id,St.id,ba);return{assignedSpool:dr?.spool?{id:dr.spool.id,material:dr.spool.material,brand:dr.spool.brand,color_name:dr.spool.color_name,remainingWeightGrams:Math.max(0,Math.round(dr.spool.label_weight-dr.spool.weight_used))}:null,onAssignSpool:Nr.vendor!=="Bambu Lab"?()=>me({printerId:t.id,amsId:St.id,trayId:ba,trayInfo:{type:Nr.profile,color:Nr.colorHex||"",location:th(St.id,St.tray.length)}}):void 0,onUnassignSpool:dr&&Nr.vendor!=="Bambu Lab"?()=>h?.(t.id,St.id,ba):void 0}})(),configureSlot:{enabled:T("printers:control"),onConfigure:()=>ie({amsId:St.id,trayId:ba,trayCount:St.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:Cn,caliIdx:en?.cali_idx,savedPresetId:ho?.preset_id})},children:Tn}):a.jsx(B2,{configureSlot:{enabled:T("printers:control"),onConfigure:()=>ie({amsId:St.id,trayId:ba,trayCount:St.tray.length,extruderId:Cn})},children:Tn})]}),(St.humidity!=null||St.temp!=null)&&a.jsxs("div",{className:"flex flex-col justify-center gap-1 shrink-0 max-[550px]:w-full",children:[St.temp!=null&&a.jsx(a9,{temp:St.temp,goodThreshold:s?.tempGood,fairThreshold:s?.tempFair,onClick:()=>se({amsId:St.id,amsLabel:th(St.id,St.tray.length),mode:"temperature"}),compact:!0}),St.humidity!=null&&a.jsx(r9,{humidity:St.humidity,goodThreshold:s?.humidityGood,fairThreshold:s?.humidityFair,onClick:()=>se({amsId:St.id,amsLabel:th(St.id,St.tray.length),mode:"humidity"}),compact:!0})]})]})]},St.id)}),fe.vt_tray.length>0&&a.jsxs("div",{className:`p-2.5 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary/30 ${fe.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:g("printers.external")})}),a.jsx("div",{className:`grid ${fe.vt_tray.length>1?"grid-cols-2":"grid-cols-1"} gap-1.5`,children:[...fe.vt_tray].sort((St,Cn)=>(St.id??254)-(Cn.id??254)).map(St=>{const Cn=St.id??254,Na=Wn&&Mt===254?Cn===254&&fe.active_extruder===1||Cn===255&&fe.active_extruder===0:Mt===Cn,nr=Cn-254,pa=Wn?g(Cn===254?"printers.extL":"printers.extR"):"",xr=St.tray_info_idx?ve?.[St.tray_info_idx]:null,en=Ge?.[1020+nr],Un=St.tray_uuid?.toUpperCase(),Hi=Un?c?.[Un]:void 0,hi=W2(Hi),Tl=u?.(t.id,255,nr),Io=(()=>{const cr=Tl?.spool;return cr&&cr.label_weight>0&&cr.weight_used!=null?Math.round(Math.max(0,cr.label_weight-cr.weight_used)/cr.label_weight*100):null})(),ho=St.tray_type&&St.remain>=0,Ua=hi??Io??(ho?St.remain:null),ga=hi!==null?"spoolman":Io!==null?"inventory":ho?"ams":void 0,Xa={vendor:K2(St)?"Bambu Lab":"Generic",profile:xr?.name||en?.preset_name||St.tray_sub_brands||St.tray_type||"Unknown",colorName:H2(St.tray_id_name)||$2(St.tray_color),colorHex:St.tray_color||null,kFactor:V2(St.k),fillLevel:Ua,trayUuid:St.tray_uuid||null,tagUid:St.tag_uid||null,fillSource:ga},Ba=!St.tray_type,Ha=a.jsxs("div",{className:`bg-bambu-dark-tertiary rounded p-1 text-center ${Ba?"opacity-50":""} ${Na?"ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark":""}`,children:[a.jsx("div",{className:"w-3.5 h-3.5 rounded-full mx-auto mb-0.5 border-2",style:{backgroundColor:St.tray_color?`#${St.tray_color}`:St.tray_type?"#333":"transparent",borderColor:Ba?"#666":"rgba(255,255,255,0.1)",borderStyle:Ba?"dashed":"solid"}}),a.jsx("div",{className:`text-[9px] font-bold truncate ${Ba?"text-white/40":"text-white"}`,children:St.tray_type||"—"}),a.jsx("div",{className:"mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden",children:Ua!==null&&Ua>=0&&!Ba&&a.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${Ua}%`,backgroundColor:G2(Ua)}})}),pa&&a.jsx("div",{className:"text-[7px] text-white/40 mt-0.5 truncate",children:pa})]});return a.jsx("div",{className:"relative group",children:Ba?a.jsx(B2,{configureSlot:{enabled:T("printers:control"),onConfigure:()=>ie({amsId:255,trayId:nr,trayCount:1,extruderId:Wn?Cn===254?1:0:void 0})},children:Ha}):a.jsx(U2,{data:Xa,spoolman:{enabled:o,hasUnlinkedSpools:l,linkedSpoolId:Xa.trayUuid?c?.[Xa.trayUuid.toUpperCase()]?.id:void 0,spoolmanUrl:d,onLinkSpool:o&&Xa.trayUuid?cr=>{V({tagUid:Xa.tagUid||"",trayUuid:cr,printerId:t.id,amsId:255,trayId:nr})}:void 0},inventory:o?void 0:(()=>{const cr=u?.(t.id,255,nr);return{assignedSpool:cr?.spool?{id:cr.spool.id,material:cr.spool.material,brand:cr.spool.brand,color_name:cr.spool.color_name,remainingWeightGrams:Math.max(0,Math.round(cr.spool.label_weight-cr.spool.weight_used))}:null,onAssignSpool:()=>me({printerId:t.id,amsId:255,trayId:nr,trayInfo:{type:Xa.profile,color:Xa.colorHex||"",location:pa||g("printers.external")}}),onUnassignSpool:cr?()=>h?.(t.id,255,nr):void 0}})(),configureSlot:{enabled:T("printers:control"),onConfigure:()=>ie({amsId:255,trayId:nr,trayCount:1,trayType:St.tray_type||void 0,trayColor:St.tray_color||void 0,traySubBrands:St.tray_sub_brands||void 0,trayInfoIdx:St.tray_info_idx||void 0,extruderId:Wn?Cn===254?1:0:void 0,caliIdx:St.cali_idx,savedPresetId:en?.preset_id})},children:Ha})},Cn)})})]})]})]})]})})()]}),Ue&&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(nu,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}),a.jsx("span",{className:"text-sm text-white truncate",children:Ue.name}),xt&&a.jsxs("span",{className:`text-xs px-1.5 py-0.5 rounded flex-shrink-0 ${xt.state==="ON"?"bg-bambu-green/20 text-bambu-green":xt.state==="OFF"?"bg-red-500/20 text-red-400":"bg-bambu-gray/20 text-bambu-gray"}`,children:[xt.state||"?",xt.state==="ON"&&xt.energy?.power!=null&&a.jsxs("span",{className:"text-yellow-400 ml-1.5",children:["· ",xt.energy.power,"W"]})]})]}),a.jsx("div",{className:"flex-1"}),a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsxs("button",{onClick:()=>W(!0),disabled:Se.isPending||xt?.state==="ON"||!T("smart_plugs:control"),className:`px-2 py-1 text-xs rounded transition-colors flex items-center gap-1 ${T("smart_plugs:control")?xt?.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:T("smart_plugs:control")?void 0:g("printers.permission.noSmartPlugControl"),children:[a.jsx(mu,{className:"w-3 h-3"}),"On"]}),a.jsxs("button",{onClick:()=>re(!0),disabled:Se.isPending||xt?.state==="OFF"||!T("smart_plugs:control"),className:`px-2 py-1 text-xs rounded transition-colors flex items-center gap-1 ${T("smart_plugs:control")?xt?.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:T("smart_plugs:control")?void 0:g("printers.permission.noSmartPlugControl"),children:[a.jsx(YC,{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 ${Ue.auto_off_executed?"text-bambu-green":"text-bambu-gray"}`,children:Ue.auto_off_executed?"Auto-off done":"Auto-off"}),a.jsx("button",{onClick:()=>tt.mutate(!Ue.auto_off),disabled:tt.isPending||Ue.auto_off_executed||!T("smart_plugs:control"),title:T("smart_plugs:control")?Ue.auto_off_executed?g("printers.autoOffExecuted"):g("printers.autoOffAfterPrint"):g("printers.permission.noSmartPlugControl"),className:`relative w-9 h-5 rounded-full transition-colors flex-shrink-0 ${T("smart_plugs:control")?Ue.auto_off_executed?"bg-bambu-green/50 cursor-not-allowed":Ue.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 ${Ue.auto_off||Ue.auto_off_executed?"translate-x-4":"translate-x-0"}`})})]})]}),yt&&yt.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(d0,{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:yt.map(gt=>a.jsxs("button",{onClick:()=>it.mutate(gt.id),disabled:it.isPending,title:`Run ${gt.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(io,{className:"w-2.5 h-2.5"}),gt.name]},gt.id))})]})]}),r==="expanded"&&a.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3",children:[a.jsxs("div",{className:"text-xs text-bambu-gray",children:[a.jsx("p",{children:t.ip_address}),a.jsx("p",{className:"truncate",children:t.serial_number})]}),a.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[a.jsx(Me,{variant:"secondary",size:"sm",onClick:()=>He.mutate(!fe?.chamber_light),disabled:!fe?.connected||He.isPending||!T("printers:control"),title:T("printers:control")?fe?.chamber_light?g("printers.chamberLightOff"):g("printers.chamberLightOn"):g("printers.permission.noControl"),className:fe?.chamber_light?"bg-yellow-500/20 hover:bg-yellow-500/30 border-yellow-500/30":"",children:a.jsx(lL,{on:fe?.chamber_light??!1,className:"w-4 h-4"})}),a.jsx(Me,{variant:"secondary",size:"sm",onClick:()=>{if(p==="embedded"&&x)x(t.id,t.name);else{const gt=localStorage.getItem("cameraWindowState"),Ft=gt?JSON.parse(gt):{width:640,height:400},Wn=[`width=${Ft.width}`,`height=${Ft.height}`,Ft.left!==void 0?`left=${Ft.left}`:"",Ft.top!==void 0?`top=${Ft.top}`:"","menubar=no,toolbar=no,location=no,status=no,noopener"].filter(Boolean).join(",");window.open(`/camera/${t.id}`,`camera-${t.id}`,Wn)}},disabled:!fe?.connected,title:g(p==="embedded"?"printers.openCameraOverlay":"printers.openCameraWindow"),children:a.jsx(PF,{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(Me,{variant:"secondary",size:"sm",onClick:jn,disabled:!fe?.connected||Xe.isPending||!T("printers:update"),title:T("printers:update")?t.plate_detection_enabled?g("printers.plateDetection.enabledClick"):g("printers.plateDetection.disabledClick"):g("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:Xe.isPending?a.jsx(at,{className:"w-4 h-4 animate-spin"}):a.jsx(_1,{className:"w-4 h-4"})}),a.jsx(Me,{variant:"secondary",size:"sm",onClick:Qt,disabled:!fe?.connected||L||!T("printers:update"),title:T("printers:update")?g("printers.plateDetection.manageCalibration"):g("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:L?a.jsx(at,{className:"w-3 h-3 animate-spin"}):a.jsx(Pn,{className:"w-3 h-3"})})]}),a.jsxs(Me,{variant:"secondary",size:"sm",onClick:()=>D(!0),disabled:!T("printers:files"),title:T("printers:files")?g("printers.browseFiles"):g("printers.permission.noFiles"),children:[a.jsx($b,{className:"w-4 h-4"}),"Files"]})]})]})]}),z&&a.jsx(kTe,{printerId:t.id,printerName:t.name,onClose:()=>D(!1)}),$&&a.jsx(jTe,{printerId:t.id,printerName:t.name,onClose:()=>G(!1)}),Ce&&a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onClick:()=>dn(),children:a.jsxs("div",{className:"bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl max-w-lg w-full",onClick:gt=>gt.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:[Ce.needs_calibration?a.jsx(_1,{className:"w-5 h-5 text-blue-500"}):Ce.is_empty?a.jsx(br,{className:"w-5 h-5 text-green-500"}):a.jsx(bi,{className:"w-5 h-5 text-yellow-500"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:"Build Plate Check"}),Ce.reference_count!==void 0&&Ce.max_references&&a.jsxs("span",{className:"text-xs text-bambu-gray bg-bambu-dark-tertiary px-2 py-1 rounded",children:[Ce.reference_count,"/",Ce.max_references," refs"]})]}),a.jsx("button",{onClick:()=>dn(),className:"p-1 text-bambu-gray hover:text-white rounded transition-colors",children:a.jsx(Rt,{className:"w-5 h-5"})})]}),a.jsxs("div",{className:"p-4 space-y-4",children:[Ce.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:g("printers.plateDetection.calibrationRequired")}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",dangerouslySetInnerHTML:{__html:g("printers.plateDetection.calibrationInstructions")}})]}),a.jsxs("div",{className:"text-sm text-bambu-gray space-y-2",children:[a.jsx("p",{children:g("printers.plateDetection.calibrationDescription")}),a.jsx("p",{dangerouslySetInnerHTML:{__html:g("printers.plateDetection.calibrationTip")}})]})]}):a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:`p-3 rounded-lg ${Ce.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 ${Ce.is_empty?"text-green-400":"text-yellow-400"}`,children:Ce.is_empty?g("printers.plateDetection.plateEmpty"):g("printers.plateDetection.objectsDetected")}),a.jsxs("p",{className:"text-sm text-bambu-gray mt-1",children:[g("printers.plateDetection.confidence"),": ",Math.round(Ce.confidence*100),"% | ",g("printers.plateDetection.difference"),": ",Ce.difference_percent.toFixed(1),"%"]})]}),Ce.debug_image_url&&a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-bambu-gray mb-2",children:g("printers.plateDetection.analysisPreview")}),a.jsx("img",{src:Ce.debug_image_url,alt:g("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:g("printers.plateDetection.analysisLegend")})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:Ce.message})]}),Tt&&Tt.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:g("printers.plateDetection.savedReferences",{count:Tt.references.length,max:Tt.max_references})}),a.jsx("div",{className:"grid grid-cols-5 gap-2",children:Tt.references.map(gt=>a.jsxs("div",{className:"relative group",children:[a.jsx("img",{src:ne.getPlateReferenceThumbnailUrl(t.id,gt.index),alt:gt.label||`Reference ${gt.index+1}`,className:"w-full aspect-video object-cover rounded border border-bambu-dark-tertiary"}),a.jsx("button",{onClick:()=>bn(gt.index),className:"absolute top-1 right-1 p-0.5 bg-red-500/80 rounded opacity-0 group-hover:opacity-100 transition-opacity",title:g("printers.plateDetection.deleteReference"),children:a.jsx(Rt,{className:"w-3 h-3 text-white"})}),Yt?.index===gt.index?a.jsx("input",{type:"text",value:Yt.label,onChange:Ft=>cn({...Yt,label:Ft.target.value}),onBlur:()=>$r(gt.index,Yt.label),onKeyDown:Ft=>{Ft.key==="Enter"&&$r(gt.index,Yt.label),Ft.key==="Escape"&&cn(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:g("printers.plateDetection.labelPlaceholder")}):a.jsx("p",{className:"text-xs text-bambu-gray mt-1 truncate cursor-pointer hover:text-white",onClick:()=>cn({index:gt.index,label:gt.label}),title:gt.label?g("printers.plateDetection.clickToEdit",{label:gt.label}):g("printers.plateDetection.clickToAddLabel"),children:gt.label||a.jsx("span",{className:"italic opacity-50",children:g("printers.noLabel")})}),a.jsx("p",{className:"text-[10px] text-bambu-gray/60",children:gt.timestamp?er(gt.timestamp)?.toLocaleDateString()??"":""})]},gt.index))})]}),!Ce.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:g("printers.roi.title")}),pe?a.jsxs("div",{className:"flex gap-1",children:[a.jsx(Me,{variant:"ghost",size:"sm",onClick:()=>te(null),disabled:Be,children:g("common.cancel")}),a.jsx(Me,{size:"sm",onClick:or,disabled:Be,children:Be?a.jsx(at,{className:"w-3 h-3 animate-spin"}):g("common.save")})]}):a.jsxs(Me,{variant:"ghost",size:"sm",onClick:()=>te(Ce.roi||{x:.15,y:.35,w:.7,h:.55}),children:[a.jsx(Ya,{className:"w-3 h-3 mr-1"}),g("common.edit")]})]}),pe?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:g("printers.roi.xStart")}),a.jsx("input",{type:"range",min:"0",max:"0.9",step:"0.01",value:pe.x,onChange:gt=>te({...pe,x:parseFloat(gt.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(pe.x*100),"%"]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"text-xs text-bambu-gray",children:g("printers.roi.yStart")}),a.jsx("input",{type:"range",min:"0",max:"0.9",step:"0.01",value:pe.y,onChange:gt=>te({...pe,y:parseFloat(gt.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(pe.y*100),"%"]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"text-xs text-bambu-gray",children:g("printers.width")}),a.jsx("input",{type:"range",min:"0.1",max:"1",step:"0.01",value:pe.w,onChange:gt=>te({...pe,w:parseFloat(gt.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(pe.w*100),"%"]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"text-xs text-bambu-gray",children:g("printers.height")}),a.jsx("input",{type:"range",min:"0.1",max:"1",step:"0.01",value:pe.h,onChange:gt=>te({...pe,h:parseFloat(gt.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(pe.h*100),"%"]})]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:g("printers.roi.instruction")})]}):a.jsxs("p",{className:"text-xs text-bambu-gray",children:["Current: X=",Math.round((Ce.roi?.x||.15)*100),"%, Y=",Math.round((Ce.roi?.y||.35)*100),"%, W=",Math.round((Ce.roi?.w||.7)*100),"%, H=",Math.round((Ce.roi?.h||.55)*100),"%"]})]})]}),a.jsx("div",{className:"flex justify-end gap-2 p-4 border-t border-bambu-dark-tertiary",children:Ce.needs_calibration?a.jsxs(a.Fragment,{children:[a.jsx(Me,{variant:"ghost",onClick:()=>dn(),children:g("common.cancel")}),a.jsx(Me,{onClick:()=>fn(),disabled:q,children:q?a.jsxs(a.Fragment,{children:[a.jsx(at,{className:"w-4 h-4 mr-2 animate-spin"}),"Calibrating..."]}):"Calibrate Empty Plate"})]}):a.jsxs(a.Fragment,{children:[a.jsx(Me,{variant:"ghost",onClick:()=>fn(),disabled:q,children:q?"Adding...":`Add Reference (${Tt?.references.length||0}/${Tt?.max_references||5})`}),a.jsx(Me,{onClick:()=>dn(),children:"Close"})]})})]})}),U&&Ue&&a.jsx(xn,{title:g("printers.confirm.powerOnTitle"),message:g("printers.confirm.powerOnMessage",{name:t.name}),confirmText:g("printers.confirm.powerOnButton"),variant:"default",onConfirm:()=>{Se.mutate("on"),W(!1)},onCancel:()=>W(!1)}),Y&&Ue&&a.jsx(xn,{title:g("printers.confirm.powerOffTitle"),message:fe?.state==="RUNNING"?g("printers.confirm.powerOffWarning",{name:t.name}):g("printers.confirm.powerOffMessage",{name:t.name}),confirmText:g("printers.confirm.powerOffButton"),variant:"danger",onConfirm:()=>{Se.mutate("off"),re(!1)},onCancel:()=>re(!1)}),ee&&a.jsx(xn,{title:g("printers.confirm.stopTitle"),message:g("printers.confirm.stopMessage",{name:t.name}),confirmText:g("printers.confirm.stopButton"),variant:"danger",onConfirm:()=>{We.mutate(),Z(!1)},onCancel:()=>Z(!1)}),we&&a.jsx(xn,{title:g("printers.confirm.pauseTitle"),message:g("printers.confirm.pauseMessage",{name:t.name}),confirmText:g("printers.confirm.pauseButton"),variant:"default",onConfirm:()=>{Ot.mutate(),oe(!1)},onCancel:()=>oe(!1)}),J&&a.jsx(xn,{title:g("printers.confirm.resumeTitle"),message:g("printers.confirm.resumeMessage",{name:t.name}),confirmText:g("printers.confirm.resumeButton"),variant:"default",onConfirm:()=>{be.mutate(),je(!1)},onCancel:()=>je(!1)}),a.jsx(cL,{printerId:t.id,isOpen:de,onClose:()=>le(!1)}),H&&a.jsx(LTe,{printerName:t.name,errors:fe?.hms_errors||[],onClose:()=>K(!1),printerId:t.id,hasPermission:T}),_e&&a.jsx(KHe,{isOpen:!!_e,onClose:()=>se(null),printerId:t.id,printerName:t.name,amsId:_e.amsId,amsLabel:_e.amsLabel,initialMode:_e.mode,thresholds:s}),ze&&a.jsx(YHe,{isOpen:!!ze,onClose:()=>V(null),tagUid:ze.tagUid,trayUuid:ze.trayUuid,printerId:ze.printerId,amsId:ze.amsId,trayId:ze.trayId}),X&&a.jsx(XHe,{isOpen:!!X,onClose:()=>me(null),printerId:X.printerId,amsId:X.amsId,trayId:X.trayId,trayInfo:X.trayInfo}),Q&&a.jsx(i$e,{isOpen:!!Q,onClose:()=>ie(null),printerId:t.id,slotInfo:Q,printerModel:xR(t.model)||void 0,onSuccess:()=>{y.invalidateQueries({queryKey:["slotPresets",t.id]}),y.invalidateQueries({queryKey:["printerStatus",t.id]})}}),B&&a.jsx(w$e,{printer:t,onClose:()=>O(!1)}),ue&&xe&&a.jsx(v$e,{printer:t,firmwareInfo:xe,onClose:()=>Le(!1)}),pn&&a.jsx("div",{className:"fixed inset-0 z-40",onClick:()=>Yr(null)})]})}function y$e({onClose:t,onAdd:e,existingSerials:n}){const{t:r}=Dt(),[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,h]=w.useState(""),[f,p]=w.useState(!1),[x,v]=w.useState(!1),[g,y]=w.useState([]),[_,N]=w.useState(""),[T,k]=w.useState({scanned:0,total:0});w.useEffect(()=>{dc.getInfo().then(P=>{v(P.is_docker),P.subnets.length>0&&(y(P.subnets),N(P.subnets[0]))}).catch(()=>{})},[]);const M=c.filter(P=>!n.includes(P.serial)),C=async()=>{h(""),d([]),l(!0),p(!1),k({scanned:0,total:0});try{if(x){await dc.startSubnetScan(_);const P=setInterval(async()=>{try{const E=await dc.getScanStatus();k({scanned:E.scanned,total:E.total});const B=await dc.getDiscoveredPrinters();d(B),E.running||(clearInterval(P),l(!1),p(!0))}catch(E){console.error("Failed to get scan status:",E)}},500)}else{await dc.startDiscovery(10);const P=setInterval(async()=>{try{const E=await dc.getDiscoveredPrinters();d(E)}catch(E){console.error("Failed to get discovered printers:",E)}},1e3);setTimeout(async()=>{clearInterval(P);try{await dc.stopDiscovery()}catch{}l(!1),p(!0);try{const E=await dc.getDiscoveredPrinters();d(E)}catch(E){console.error("Failed to get final discovered printers:",E)}},1e4)}}catch(P){console.error("Failed to start discovery:",P),h(P instanceof Error?P.message:r("printers.discovery.failedToStart")),l(!1),p(!0)}},j=P=>{const E=P.serial.startsWith("unknown-")?"":P.serial;s({...i,name:P.name||"",serial_number:E,ip_address:P.ip_address,model:xR(P.model)}),d([])};return w.useEffect(()=>()=>{dc.stopDiscovery().catch(()=>{}),dc.stopSubnetScan().catch(()=>{})},[]),w.useEffect(()=>{const P=E=>{E.key==="Escape"&&t()};return window.addEventListener("keydown",P),()=>window.removeEventListener("keydown",P)},[t]),a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",onClick:t,children:a.jsx(wt,{className:"w-full max-w-md",onClick:P=>P.stopPropagation(),children:a.jsxs(Nt,{children:[a.jsx("h2",{className:"text-xl font-semibold mb-4",children:r("printers.addPrinter")}),a.jsxs("div",{className:"mb-4 pb-4 border-b border-bambu-dark-tertiary",children:[x&&a.jsxs("div",{className:"mb-3",children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.discovery.subnetToScan")}),g.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:P=>N(P.target.value),disabled:o,children:g.map(P=>a.jsx("option",{value:P,children:P},P))}):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:P=>N(P.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(Me,{type:"button",variant:"secondary",onClick:C,disabled:o,className:"w-full",children:o?a.jsxs(a.Fragment,{children:[a.jsx(at,{className:"w-4 h-4 animate-spin"}),x&&T.total>0?r("printers.discovery.scanProgress",{scanned:T.scanned,total:T.total}):r("printers.discovery.scanning")]}):a.jsxs(a.Fragment,{children:[a.jsx(Mr,{className:"w-4 h-4"}),r(x?"printers.discovery.scanSubnet":"printers.discovery.discoverNetwork")]})}),u&&a.jsx("div",{className:"mt-2 text-sm text-red-400",children:u}),M.length>0&&a.jsx("div",{className:"mt-3 space-y-2 max-h-40 overflow-y-auto",children:M.map(P=>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:()=>j(P),children:[a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:"font-medium text-white text-sm truncate",children:P.name||P.serial}),a.jsxs("p",{className:"text-xs text-bambu-gray truncate",children:[xR(P.model)||r("printers.discovery.unknown")," • ",P.ip_address,P.serial.startsWith("unknown-")&&a.jsxs("span",{className:"text-yellow-500",children:[" • ",r("printers.discovery.serialRequired")]})]})]}),a.jsx(Pn,{className:"w-4 h-4 text-bambu-gray -rotate-90 flex-shrink-0 ml-2"})]},P.serial))}),o&&a.jsx("p",{className:"mt-2 text-sm text-bambu-gray text-center",children:r(x?"printers.discovery.scanningSubnet":"printers.discovery.scanningNetwork")}),f&&!o&&c.length===0&&a.jsx("p",{className:"mt-2 text-sm text-bambu-gray text-center",children:r(x?"printers.discovery.noPrintersFoundSubnet":"printers.discovery.noPrintersFoundNetwork")}),f&&!o&&c.length>0&&M.length===0&&a.jsx("p",{className:"mt-2 text-sm text-bambu-gray text-center",children:r("printers.discovery.allConfigured")})]}),a.jsxs("form",{onSubmit:P=>{P.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:P=>s({...i,name:P.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:P=>s({...i,ip_address:P.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:P=>s({...i,serial_number:P.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:P=>s({...i,access_code:P.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:P=>s({...i,model:P.target.value}),children:[a.jsx("option",{value:"",children:r("printers.modal.selectModel")}),a.jsxs("optgroup",{label:"H2 Series",children:[a.jsx("option",{value:"H2C",children:"H2C"}),a.jsx("option",{value:"H2D",children:"H2D"}),a.jsx("option",{value:"H2D Pro",children:"H2D Pro"}),a.jsx("option",{value:"H2S",children:"H2S"})]}),a.jsxs("optgroup",{label:"X1 Series",children:[a.jsx("option",{value:"X1E",children:"X1E"}),a.jsx("option",{value:"X1C",children:"X1 Carbon"}),a.jsx("option",{value:"X1",children:"X1"})]}),a.jsxs("optgroup",{label:"P Series",children:[a.jsx("option",{value:"P2S",children:"P2S"}),a.jsx("option",{value:"P1S",children:"P1S"}),a.jsx("option",{value:"P1P",children:"P1P"})]}),a.jsxs("optgroup",{label:"A1 Series",children:[a.jsx("option",{value:"A1",children:"A1"}),a.jsx("option",{value:"A1 Mini",children:"A1 Mini"})]})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.modal.locationGroup")}),a.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:i.location||"",onChange:P=>s({...i,location:P.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:P=>s({...i,auto_archive:P.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(Me,{type:"button",variant:"secondary",onClick:t,className:"flex-1",children:r("common.cancel")}),a.jsx(Me,{type:"submit",className:"flex-1",children:r("printers.addPrinter")})]})]})]})})})}function v$e({printer:t,firmwareInfo:e,onClose:n}){const{t:r}=Dt(),i=Jt(),{showToast:s}=ln(),{hasPermission:o}=Pr(),l=o("firmware:update"),[c,d]=w.useState(null),[u,h]=w.useState(!1),[f,p]=w.useState(null),{data:x,isLoading:v}=Je({queryKey:["firmwarePrepare",t.id],queryFn:()=>B_.prepareUpload(t.id),staleTime:3e4,enabled:e.update_available&&l}),g=st({mutationFn:()=>B_.startUpload(t.id),onSuccess:()=>{h(!0);const _=setInterval(async()=>{try{const N=await B_.getUploadStatus(t.id);d(N),(N.status==="complete"||N.status==="error")&&(clearInterval(_),p(null),h(!1),N.status==="complete"&&(s(r("printers.firmwareModal.uploadedToast"),"success"),i.invalidateQueries({queryKey:["firmwareUpdate",t.id]})))}catch{}},2e3);p(_)},onError:_=>{s(r("printers.firmwareModal.uploadFailed",{error:_.message}),"error"),h(!1)}});w.useEffect(()=>()=>{f&&clearInterval(f)},[f]);const y=()=>{d(null),g.mutate()};return a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",children:a.jsx(wt,{className:"w-full max-w-md mx-4",children:a.jsxs(Nt,{children:[a.jsxs("div",{className:"flex items-start gap-3 mb-4",children:[a.jsx("div",{className:`p-2 rounded-full ${e.update_available?"bg-orange-500/20":"bg-status-ok/20"}`,children:e.update_available?a.jsx(ha,{className:"w-5 h-5 text-orange-400"}):a.jsx(br,{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})]})]}),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 ${e.update_available?"text-white":"text-status-ok"}`,children:e.current_version||r("common.unknown")})]}),e.update_available&&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:e.latest_version})]}),e.release_notes&&a.jsxs("details",{className:"mt-3 text-sm",open:!e.update_available,children:[a.jsx("summary",{className:`cursor-pointer hover:underline ${e.update_available?"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:e.release_notes})]})]}),e.update_available?v?a.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray text-sm mb-4",children:[a.jsx(at,{className:"w-4 h-4 animate-spin"}),r("printers.firmwareModal.checkingPrereqs")]}):x&&!u&&!c?a.jsx("div",{className:"mb-4",children:x.can_proceed?a.jsxs("div",{className:"flex items-center gap-2 text-bambu-green text-sm",children:[a.jsx(ai,{className:"w-4 h-4"}),r("printers.firmwareModal.sdCardReady")]}):a.jsx("div",{className:"space-y-1",children:x.errors.map((_,N)=>a.jsxs("div",{className:"flex items-center gap-2 text-red-400 text-sm",children:[a.jsx(Wa,{className:"w-4 h-4 flex-shrink-0"}),_]},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(Me,{variant:"secondary",onClick:n,children:c?.status==="complete"?r("printers.firmwareModal.done"):r("common.cancel")}),x?.can_proceed&&!u&&c?.status!=="complete"&&l&&a.jsx(Me,{onClick:y,disabled:g.isPending,children:g.isPending?a.jsxs(a.Fragment,{children:[a.jsx(at,{className:"w-4 h-4 animate-spin mr-2"}),r("printers.firmwareModal.starting")]}):a.jsxs(a.Fragment,{children:[a.jsx(ha,{className:"w-4 h-4 mr-2"}),r("printers.firmwareModal.uploadFirmware")]})})]})]})})})}function w$e({printer:t,onClose:e}){const{t:n}=Dt(),r=Jt(),{showToast:i}=ln(),[s,o]=w.useState({name:t.name,ip_address:t.ip_address,access_code:"",model:t.model||"",location:t.location||"",auto_archive:t.auto_archive}),l=st({mutationFn:d=>ne.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-center justify-center z-50",onClick:e,children:a.jsx(wt,{className:"w-full max-w-md",onClick:d=>d.stopPropagation(),children:a.jsxs(Nt,{children:[a.jsx("h2",{className:"text-xl font-semibold mb-4",children:n("printers.editPrinter")}),a.jsxs("form",{onSubmit:c,className:"space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.name")}),a.jsx("input",{type:"text",required:!0,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:s.name,onChange:d=>o({...s,name:d.target.value}),placeholder:n("printers.modal.myPrinter")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.ipAddress")}),a.jsx("input",{type:"text",required:!0,pattern:"(\\d{1,3}(\\.\\d{1,3}){3}|[a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?(\\.[a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?)*)",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:s.ip_address,onChange:d=>o({...s,ip_address:d.target.value}),placeholder:"192.168.1.100 or printer.local"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.serialNumber")}),a.jsx("input",{type:"text",disabled:!0,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray cursor-not-allowed",value:t.serial_number}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:n("printers.serialCannotBeChanged")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.accessCode")}),a.jsx("input",{type:"password",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:s.access_code,onChange:d=>o({...s,access_code:d.target.value}),placeholder:n("printers.accessCodePlaceholder")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.model")}),a.jsxs("select",{className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:s.model,onChange:d=>o({...s,model:d.target.value}),children:[a.jsx("option",{value:"",children:n("printers.modal.selectModel")}),a.jsxs("optgroup",{label:"H2 Series",children:[a.jsx("option",{value:"H2C",children:"H2C"}),a.jsx("option",{value:"H2D",children:"H2D"}),a.jsx("option",{value:"H2D Pro",children:"H2D Pro"}),a.jsx("option",{value:"H2S",children:"H2S"})]}),a.jsxs("optgroup",{label:"X1 Series",children:[a.jsx("option",{value:"X1E",children:"X1E"}),a.jsx("option",{value:"X1C",children:"X1 Carbon"}),a.jsx("option",{value:"X1",children:"X1"})]}),a.jsxs("optgroup",{label:"P Series",children:[a.jsx("option",{value:"P2S",children:"P2S"}),a.jsx("option",{value:"P1S",children:"P1S"}),a.jsx("option",{value:"P1P",children:"P1P"})]}),a.jsxs("optgroup",{label:"A1 Series",children:[a.jsx("option",{value:"A1",children:"A1"}),a.jsx("option",{value:"A1 Mini",children:"A1 Mini"})]})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Location / Group"}),a.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:s.location,onChange:d=>o({...s,location:d.target.value}),placeholder:n("printers.modal.locationPlaceholder")}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:n("printers.locationHelp")})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"checkbox",id:"edit_auto_archive",checked:s.auto_archive,onChange:d=>o({...s,auto_archive:d.target.checked}),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),a.jsx("label",{htmlFor:"edit_auto_archive",className:"text-sm text-bambu-gray",children:n("printers.modal.autoArchiveLabel")})]}),a.jsxs("div",{className:"flex gap-3 pt-4",children:[a.jsx(Me,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:n("common.cancel")}),a.jsx(Me,{type:"submit",className:"flex-1",disabled:l.isPending,children:l.isPending?n("common.saving"):n("printers.modal.saveChanges")})]})]})]})})})}function S$e(t){const{data:e}=Je({queryKey:["printerStatus",t],queryFn:()=>ne.getPrinterStatus(t),refetchInterval:3e4});return!e?.connected}function _$e({printer:t,plug:e,onPowerOn:n,isPowering:r}){const i=S$e(t.id),{data:s}=Je({queryKey:["smartPlugStatus",e.id],queryFn:()=>ne.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(mu,{className:"w-3 h-3"}),r?"...":"On"]})]}):null}function N$e(){const{t}=Dt(),[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"),[h,f]=w.useState(()=>localStorage.getItem("printerSortAsc")!=="false"),[p,x]=w.useState(()=>{const le=localStorage.getItem("printerCardSize");return le?parseInt(le,10):2}),v=p===1?"compact":"expanded",g=Jt(),{showToast:y}=ln(),{hasPermission:_}=Pr(),[N,T]=w.useState(()=>{const le=localStorage.getItem("openEmbeddedCameras");if(le)try{const _e=JSON.parse(le);return new Map(_e.map(se=>[se.id,se]))}catch{return new Map}return new Map});w.useEffect(()=>{const le=Array.from(N.values());le.length>0?localStorage.setItem("openEmbeddedCameras",JSON.stringify(le)):localStorage.removeItem("openEmbeddedCameras")},[N]);const{data:k,isLoading:M}=Je({queryKey:["printers"],queryFn:ne.getPrinters}),{data:C}=Je({queryKey:["settings"],queryFn:ne.getSettings});w.useEffect(()=>{C?.camera_view_mode==="window"&&N.size>0&&T(new Map)},[C?.camera_view_mode,N.size]);const{data:j}=Je({queryKey:["smart-plugs"],queryFn:ne.getSmartPlugs}),{data:P}=Je({queryKey:["maintenanceOverview"],queryFn:ne.getMaintenanceOverview,staleTime:60*1e3}),{data:E}=Je({queryKey:["spoolman-status"],queryFn:ne.getSpoolmanStatus,staleTime:60*1e3}),B=E?.enabled&&E?.connected,{data:O}=Je({queryKey:["unlinked-spools"],queryFn:ne.getUnlinkedSpools,enabled:!!B,staleTime:30*1e3}),z=O&&O.length>0,{data:D}=Je({queryKey:["linked-spools"],queryFn:ne.getLinkedSpools,enabled:!!B,staleTime:30*1e3}),$=D?.linked,{data:G}=Je({queryKey:["spool-assignments"],queryFn:()=>ne.getAssignments(),staleTime:30*1e3}),U=st({mutationFn:({printerId:le,amsId:_e,trayId:se})=>ne.unassignSpool(le,_e,se),onSuccess:()=>{g.invalidateQueries({queryKey:["spool-assignments"]})}}),W=(le,_e,se)=>G?.find(ze=>ze.printer_id===le&&ze.ams_id===Number(_e)&&ze.tray_id===Number(se)),Y=P?.reduce((le,_e)=>(le[_e.printer_id]={due_count:_e.due_count,warning_count:_e.warning_count,total_print_hours:_e.total_print_hours},le),{})||{},re=j?.reduce((le,_e)=>(_e.printer_id&&(le[_e.printer_id]=_e),le),{})||{},H=st({mutationFn:ne.createPrinter,onSuccess:()=>{g.invalidateQueries({queryKey:["printers"]}),g.invalidateQueries({queryKey:["maintenanceOverview"]}),n(!1)},onError:le=>y(le.message||t("printers.toast.failedToAdd"),"error")}),K=st({mutationFn:le=>ne.controlSmartPlug(le,"on"),onSuccess:()=>{g.invalidateQueries({queryKey:["smart-plugs"]}),c(null)},onError:()=>{c(null)}}),ee=()=>{const le=!r;i(le),localStorage.setItem("hideDisconnectedPrinters",String(le))},Z=le=>{u(le),localStorage.setItem("printerSortBy",le)},we=()=>{const le=!h;f(le),localStorage.setItem("printerSortAsc",String(le))},oe=()=>{switch(p){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"}},J=["S","M","L","XL"],je=w.useMemo(()=>{if(!k)return[];const le=[...k];switch(d){case"name":le.sort((_e,se)=>_e.name.localeCompare(se.name));break;case"model":le.sort((_e,se)=>(_e.model||"").localeCompare(se.model||""));break;case"location":le.sort((_e,se)=>{const ze=_e.location||"",V=se.location||"";return!ze&&V?1:ze&&!V?-1:ze.localeCompare(V)||_e.name.localeCompare(se.name)});break;case"status":le.sort((_e,se)=>{const ze=g.getQueryData(["printerStatus",_e.id]),V=g.getQueryData(["printerStatus",se.id]),X=me=>me?.connected?me.state==="RUNNING"?0:1:2;return X(ze)-X(V)});break}return h||le.reverse(),le},[k,d,h,g]),de=w.useMemo(()=>{if(d!=="location")return null;const le={};return je.forEach(_e=>{const se=_e.location||"Ungrouped";le[se]||(le[se]=[]),le[se].push(_e)}),le},[d,je]);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(x$e,{printers:k})]}),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:le=>Z(le.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:we,className:"p-1.5 rounded-lg hover:bg-bambu-dark-tertiary transition-colors",title:t(h?"printers.sort.descending":"printers.sort.ascending"),children:h?a.jsx(Mf,{className:"w-4 h-4 text-bambu-gray"}):a.jsx(lb,{className:"w-4 h-4 text-bambu-gray"})})]}),a.jsx("div",{className:"flex items-center bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:J.map((le,_e)=>{const se=_e+1,ze=p===se;return a.jsx("button",{onClick:()=>{x(se),localStorage.setItem("printerCardSize",String(se))},className:`px-2 py-1.5 text-xs font-medium transition-colors ${_e===0?"rounded-l-lg":""} ${_e===J.length-1?"rounded-r-lg":""} ${ze?"bg-bambu-green text-white":"text-bambu-gray hover:bg-bambu-dark-tertiary hover:text-white"}`,title:t(le==="S"?"printers.cardSize.small":le==="M"?"printers.cardSize.medium":le==="L"?"printers.cardSize.large":"printers.cardSize.extraLarge"),children:le},le)})}),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:ee,className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),t("printers.hideOffline")]}),r&&Object.keys(re).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(mu,{className:"w-4 h-4"}),t("printers.powerOn"),a.jsx(Pn,{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")}),k?.filter(le=>re[le.id]).map(le=>a.jsx(_$e,{printer:le,plug:re[le.id],onPowerOn:_e=>{c(_e),K.mutate(_e)},isPowering:l===re[le.id]?.id},le.id)),k?.filter(le=>re[le.id]).length===0&&a.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:"No printers with smart plugs"})]})]})]}),a.jsxs(Me,{onClick:()=>n(!0),disabled:!_("printers:create"),title:_("printers:create")?void 0:t("printers.permission.noAdd"),children:[a.jsx(Xn,{className:"w-4 h-4"}),t("printers.addPrinter")]})]})]}),M?a.jsx("div",{className:"text-center py-12 text-bambu-gray",children:t("common.loading")}):k?.length===0?a.jsx(wt,{children:a.jsxs(Nt,{className:"text-center py-12",children:[a.jsx("p",{className:"text-bambu-gray mb-4",children:t("printers.noPrintersConfigured")}),a.jsxs(Me,{onClick:()=>n(!0),disabled:!_("printers:create"),title:_("printers:create")?void 0:t("printers.permission.noAdd"),children:[a.jsx(Xn,{className:"w-4 h-4"}),t("printers.addPrinter")]})]})}):de?a.jsx("div",{className:"space-y-6",children:Object.entries(de).map(([le,_e])=>a.jsxs("div",{children:[a.jsxs("h2",{className:"text-lg font-semibold text-white mb-3 flex items-center gap-2",children:[a.jsx("span",{className:"w-2 h-2 rounded-full bg-bambu-green"}),le,a.jsxs("span",{className:"text-sm font-normal text-bambu-gray",children:["(",_e.length,")"]})]}),a.jsx("div",{className:`grid gap-4 ${p>=3?"gap-6":""} ${oe()}`,children:_e.map(se=>a.jsx(s9,{printer:se,hideIfDisconnected:r,maintenanceInfo:Y[se.id],viewMode:v,cardSize:p,amsThresholds:C?{humidityGood:Number(C.ams_humidity_good)||40,humidityFair:Number(C.ams_humidity_fair)||60,tempGood:Number(C.ams_temp_good)||28,tempFair:Number(C.ams_temp_fair)||35}:void 0,spoolmanEnabled:B,hasUnlinkedSpools:z,linkedSpools:$,spoolmanUrl:E?.url,onGetAssignment:W,onUnassignSpool:(ze,V,X)=>U.mutate({printerId:ze,amsId:V,trayId:X}),timeFormat:C?.time_format||"system",cameraViewMode:C?.camera_view_mode||"window",onOpenEmbeddedCamera:(ze,V)=>T(X=>new Map(X).set(ze,{id:ze,name:V})),checkPrinterFirmware:C?.check_printer_firmware!==!1},se.id))})]},le))}):a.jsx("div",{className:`grid gap-4 ${p>=3?"gap-6":""} ${oe()}`,children:je.map(le=>a.jsx(s9,{printer:le,hideIfDisconnected:r,maintenanceInfo:Y[le.id],viewMode:v,cardSize:p,spoolmanEnabled:B,hasUnlinkedSpools:z,linkedSpools:$,spoolmanUrl:E?.url,onGetAssignment:W,onUnassignSpool:(_e,se,ze)=>U.mutate({printerId:_e,amsId:se,trayId:ze}),amsThresholds:C?{humidityGood:Number(C.ams_humidity_good)||40,humidityFair:Number(C.ams_humidity_fair)||60,tempGood:Number(C.ams_temp_good)||28,tempFair:Number(C.ams_temp_fair)||35}:void 0,timeFormat:C?.time_format||"system",cameraViewMode:C?.camera_view_mode||"window",onOpenEmbeddedCamera:(_e,se)=>T(ze=>new Map(ze).set(_e,{id:_e,name:se})),checkPrinterFirmware:C?.check_printer_firmware!==!1},le.id))}),e&&a.jsx(y$e,{onClose:()=>n(!1),onAdd:le=>H.mutate(le),existingSerials:k?.map(le=>le.serial_number)||[]}),Array.from(N.values()).map((le,_e)=>a.jsx(ETe,{printerId:le.id,printerName:le.name,viewerIndex:_e,onClose:()=>T(se=>{const ze=new Map(se);return ze.delete(le.id),ze})},le.id))]})}function C$e(){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 of(t,e="bambu_studio"){let n;e==="orcaslicer"?n=`orcaslicer://open?file=${t}`:C$e()==="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 k$e={USD:"$",EUR:"€",GBP:"£",CHF:"Fr.",JPY:"¥",CNY:"¥",CAD:"$",AUD:"$",INR:"₹",HKD:"HK$",KRW:"₩",SEK:"kr",NOK:"kr",DKK:"kr",PLN:"zł",BRL:"R$",TWD:"NT$",SGD:"S$",NZD:"NZ$",MXN:"MX$",CZK:"Kč",THB:"฿",ZAR:"R",TRY:"₺",RUB:"₽"};function rl(t){return k$e[t.toUpperCase()]||t}const A$e=[{code:"USD",label:"USD ($)"},{code:"EUR",label:"EUR (€)"},{code:"GBP",label:"GBP (£)"},{code:"CHF",label:"CHF (Fr.)"},{code:"JPY",label:"JPY (¥)"},{code:"CNY",label:"CNY (¥)"},{code:"CAD",label:"CAD ($)"},{code:"AUD",label:"AUD ($)"},{code:"INR",label:"INR (₹)"},{code:"HKD",label:"HKD (HK$)"},{code:"KRW",label:"KRW (₩)"},{code:"SEK",label:"SEK (kr)"},{code:"NOK",label:"NOK (kr)"},{code:"DKK",label:"DKK (kr)"},{code:"PLN",label:"PLN (zł)"},{code:"BRL",label:"BRL (R$)"},{code:"TWD",label:"TWD (NT$)"},{code:"SGD",label:"SGD (S$)"},{code:"NZD",label:"NZD (NZ$)"},{code:"MXN",label:"MXN (MX$)"},{code:"CZK",label:"CZK (Kč)"},{code:"THB",label:"THB (฿)"},{code:"ZAR",label:"ZAR (R)"},{code:"TRY",label:"TRY (₺)"},{code:"RUB",label:"RUB (₽)"}],o9=768;function xne(){const[t,e]=w.useState(()=>typeof window<"u"?window.innerWidth{const n=window.matchMedia(`(max-width: ${o9-1}px)`),r=i=>{e(i.matches)};return e(n.matches),n.addEventListener("change",r),()=>n.removeEventListener("change",r)},[]),t}function g4({archiveId:t,libraryFileId:e,title:n,fileType:r,onClose:i}){const{t:s}=Dt(),{data:o}=Je({queryKey:["settings"],queryFn:ne.getSettings}),l=o?.preferred_slicer||"bambu_studio",c=e!=null,[d,u]=w.useState(null),[h,f]=w.useState(null),[p,x]=w.useState(!0),[v,g]=w.useState(null),[y,_]=w.useState(!1),[N,T]=w.useState(null),[k,M]=w.useState(0),[C,j]=w.useState(!1),[P,E]=w.useState(null),[B,O]=w.useState(!1),[z,D]=w.useState(!1),$=w.useRef(null),G=w.useRef(null),U=10,W=160,Y=240,re=.35;w.useEffect(()=>{const Ce=ge=>{ge.key==="Escape"&&i()};return window.addEventListener("keydown",Ce),()=>window.removeEventListener("keydown",Ce)},[i]),w.useEffect(()=>{if(x(!0),c){const Ce=(r||"").toLowerCase(),ge=Ce==="3mf"||Ce==="stl",L=Ce==="gcode"||Ce==="3mf";f({has_model:ge,has_gcode:L,has_source:!1,build_volume:{x:256,y:256,z:256},filament_colors:[]}),u(ge?"3d":L?"gcode":null),x(!1);return}if(!t){f(null),u(null),x(!1);return}ne.getArchiveCapabilities(t).then(Ce=>{f(Ce),Ce.has_model?u("3d"):Ce.has_gcode&&u("gcode"),x(!1)}).catch(()=>{f({has_model:!0,has_gcode:!1,has_source:!1,build_volume:{x:256,y:256,z:256},filament_colors:[]}),u("3d"),x(!1)})},[t,r,c]),w.useEffect(()=>{if(_(!0),T(null),M(0),c){const Ce=(r||"").toLowerCase();if(!e||Ce!=="3mf"){g(null),_(!1);return}ne.getLibraryFilePlates(e).then(ge=>g(ge)).catch(()=>g(null)).finally(()=>_(!1));return}if(!t){g(null),_(!1);return}ne.getArchivePlates(t).then(Ce=>g(Ce)).catch(()=>g(null)).finally(()=>_(!1))},[t,r,c,e]);const H=w.useMemo(()=>v?.plates??[],[v]),K=(v?.is_multi_plate??!1)&&H.length>1,ee=C&&K,Z=N==null?null:H.find(Ce=>Ce.index===N)??null,we=Ce=>Ce.object_count??Ce.objects?.length??0,oe=H.reduce((Ce,ge)=>Ce+we(ge),0),J=Z?we(Z):oe,je=Z?s("modelViewer.plateNumber",{number:Z.index}):s("modelViewer.allPlates"),de=H.length>0,le=w.useRef(null),_e=w.useRef(null),[se,ze]=w.useState(10),[V,X]=w.useState(3),me=H.length>se,Q=Math.max(1,Math.ceil(H.length/se)),ie=me?H.slice(k*se,(k+1)*se):H;w.useEffect(()=>{if(!ee){ze(10),X(3);return}const Ce=le.current,ge=_e.current;if(!Ce||!ge)return;let L=0;const R=()=>{const pe=ge.clientWidth,Be=Math.floor(pe/210),Ie=Math.max(3,Math.min(5,Be||3));X(Te=>Te===Ie?Te:Ie);const $e=window.getComputedStyle(Ce),Re=Number.parseFloat($e.rowGap||"0"),xe=Ce.querySelector("button")?.getBoundingClientRect().height??44,Ne=ge.clientHeight,ve=Math.max(1,Math.floor((Ne+Re)/(xe+Re)))*Ie,Ge=Math.max(1,ve-1);ze(Te=>Te===Ge?Te:Ge)},q=()=>{L&&cancelAnimationFrame(L),L=requestAnimationFrame(R)};q();const ce=new ResizeObserver(q);return ce.observe(ge),ce.observe(Ce),()=>{L&&cancelAnimationFrame(L),ce.disconnect()}},[ee,H.length]),w.useEffect(()=>{if(!me){M(0);return}M(Ce=>Math.min(Ce,Q-1))},[H.length,me,Q]),w.useEffect(()=>{if(!me||N==null)return;const Ce=H.findIndex(L=>L.index===N);if(Ce<0)return;const ge=Math.floor(Ce/se);M(L=>L===ge?L:ge)},[H,se,N,me]),w.useEffect(()=>{if(!ee){E(null),D(!1);return}if(z)return;const Ce=$.current,ge=G.current;if(!Ce||!ge)return;const L=Ce.clientHeight;if(!L)return;const R=Math.max(Y,L*re),q=Math.max(W,L-U-R),ce=Math.min(ge.scrollHeight,q);E(Math.max(W,ce))},[ee,z,H.length,k,U,W,Y,re]),w.useEffect(()=>{if(!B)return;const Ce=L=>{const R=$.current;if(!R)return;const q=R.getBoundingClientRect(),ce=q.height;if(!ce)return;const pe=Math.max(Y,ce*re),te=Math.max(W,ce-U-pe),Be=Math.min(te,Math.max(W,L.clientY-q.top));E(Be)},ge=()=>{O(!1),D(!0)};return document.addEventListener("mousemove",Ce),document.addEventListener("mouseup",ge),document.body.style.cursor="row-resize",document.body.style.userSelect="none",()=>{document.removeEventListener("mousemove",Ce),document.removeEventListener("mouseup",ge),document.body.style.cursor="",document.body.style.userSelect=""}},[B,U,W,Y,re]);const ue=c?(r||"").toLowerCase()==="3mf":!0,Le=async()=>{if(!ue)return;const Ce=n||"model";try{if(c){const{token:ge}=await ne.createLibrarySlicerToken(e),L=ne.getLibrarySlicerDownloadUrl(e,ge,Ce);of(`${window.location.origin}${L}`,l)}else{const{token:ge}=await ne.createArchiveSlicerToken(t),L=ne.getArchiveSlicerDownloadUrl(t,ge,Ce);of(`${window.location.origin}${L}`,l)}}catch{if(c){const ge=`${window.location.origin}${ne.getLibraryFileDownloadUrl(e)}`;of(ge,l)}else{const ge=`${window.location.origin}${ne.getArchiveForSlicer(t,Ce)}`;of(ge,l)}}};return a.jsx("div",{className:`fixed inset-0 bg-black/70 flex items-center justify-center z-50 ${C?"p-0":"p-8"}`,onClick:i,children:a.jsxs("div",{className:`bg-bambu-dark-secondary border border-bambu-dark-tertiary w-full flex flex-col ${C?"h-full max-w-none rounded-none":"h-[80vh] max-w-4xl rounded-xl"}`,onClick:Ce=>Ce.stopPropagation(),children:[a.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-1 mr-4",children:[a.jsx("h2",{className:"text-lg font-semibold text-white truncate",children:n}),de&&a.jsxs("span",{className:"text-xs text-bambu-gray bg-bambu-dark-tertiary/70 px-2 py-1 rounded whitespace-nowrap",children:[je,": ",s("modelViewer.objectCount",{count:J})]})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs(Me,{variant:"secondary",size:"sm",onClick:Le,disabled:!ue,children:[a.jsx(Zr,{className:"w-4 h-4"}),s("modelViewer.openInSlicer")]}),a.jsx(Me,{variant:"secondary",size:"sm",onClick:()=>j(Ce=>!Ce),title:C?"Exit fullscreen":"Enter fullscreen",children:C?a.jsx(kF,{className:"w-4 h-4"}):a.jsx(GC,{className:"w-4 h-4"})}),a.jsx(Me,{variant:"ghost",size:"sm",onClick:i,children:a.jsx(Rt,{className:"w-5 h-5"})})]})]}),h&&a.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary",children:[a.jsxs("button",{onClick:()=>h.has_model&&u("3d"),disabled:!h.has_model,className:`flex items-center gap-2 px-6 py-3 text-sm font-medium transition-colors ${d==="3d"?"text-bambu-green border-b-2 border-bambu-green":h.has_model?"text-bambu-gray hover:text-white":"text-bambu-gray/30 cursor-not-allowed"}`,children:[a.jsx(ai,{className:"w-4 h-4"}),s("modelViewer.tabs.model"),!h.has_model&&a.jsxs("span",{className:"text-xs",children:["(",s("modelViewer.notAvailable"),")"]})]}),a.jsxs("button",{onClick:()=>h.has_gcode&&u("gcode"),disabled:!h.has_gcode,className:`flex items-center gap-2 px-6 py-3 text-sm font-medium transition-colors ${d==="gcode"?"text-bambu-green border-b-2 border-bambu-green":h.has_gcode?"text-bambu-gray hover:text-white":"text-bambu-gray/30 cursor-not-allowed"}`,children:[a.jsx(Dhe,{className:"w-4 h-4"}),s("modelViewer.tabs.gcode"),!h.has_gcode&&a.jsxs("span",{className:"text-xs",children:["(",s("modelViewer.notSliced"),")"]})]})]}),a.jsx("div",{className:"flex-1 overflow-hidden p-4",children:p?a.jsx("div",{className:"w-full h-full flex items-center justify-center",children:a.jsx(at,{className:"w-8 h-8 animate-spin text-bambu-green"})}):d==="3d"&&h?a.jsxs("div",{ref:$,className:`w-full h-full flex flex-col ${ee?"gap-0 min-h-0":"gap-3"}`,children:[K&&a.jsxs("div",{ref:G,style:ee&&P!=null?{height:P}:void 0,className:`rounded-lg border border-bambu-dark-tertiary bg-bambu-dark p-3 ${ee?"flex flex-col shrink-0":""}`,children:[a.jsxs("div",{className:"flex items-center gap-2 text-sm text-bambu-gray mb-2",children:[a.jsx(oi,{className:"w-4 h-4"}),s("modelViewer.plates"),y&&a.jsx(at,{className:"w-3 h-3 animate-spin"})]}),a.jsxs("div",{className:ee?"flex flex-col min-h-0 flex-1":void 0,children:[a.jsx("div",{ref:_e,className:ee?"min-h-0 overflow-hidden pr-1 flex-1":void 0,children:a.jsxs("div",{ref:le,className:ee?"grid gap-2":"grid grid-cols-2 md:grid-cols-3 gap-2",style:ee?{gridTemplateColumns:`repeat(${V}, minmax(0, 1fr))`}:void 0,children:[a.jsxs("button",{type:"button",onClick:()=>T(null),className:`flex items-center rounded-lg border text-left transition-colors ${ee?"gap-1.5 p-1.5 w-full":"gap-2 p-2"} ${N==null?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark-secondary hover:border-bambu-gray"}`,children:[a.jsx("div",{className:`rounded bg-bambu-dark-tertiary flex items-center justify-center ${ee?"w-8 h-8":"w-10 h-10"}`,children:a.jsx(oi,{className:`${ee?"w-4 h-4":"w-5 h-5"} text-bambu-gray`})}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:`${ee?"text-xs":"text-sm"} text-white font-medium truncate`,children:s("modelViewer.allPlates")}),a.jsx("p",{className:`${ee?"text-[10px]":"text-xs"} text-bambu-gray truncate`,children:s("modelViewer.plateCount",{count:H.length})})]}),N==null&&a.jsx(Jr,{className:`${ee?"w-3.5 h-3.5":"w-4 h-4"} text-bambu-green flex-shrink-0`})]}),ie.map(Ce=>a.jsxs("button",{type:"button",onClick:()=>T(Ce.index),className:`flex items-center rounded-lg border text-left transition-colors ${ee?"gap-1.5 p-1.5 w-full":"gap-2 p-2"} ${N===Ce.index?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark-secondary hover:border-bambu-gray"}`,children:[Ce.has_thumbnail&&Ce.thumbnail_url?a.jsx("img",{src:Ce.thumbnail_url,alt:`Plate ${Ce.index}`,className:`${ee?"w-8 h-8":"w-10 h-10"} rounded object-cover bg-bambu-dark-tertiary`}):a.jsx("div",{className:`rounded bg-bambu-dark-tertiary flex items-center justify-center ${ee?"w-8 h-8":"w-10 h-10"}`,children:a.jsx(oi,{className:`${ee?"w-4 h-4":"w-5 h-5"} text-bambu-gray`})}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:`${ee?"text-xs":"text-sm"} text-white font-medium truncate`,children:Ce.name||s("modelViewer.plateNumber",{number:Ce.index})}),a.jsx("p",{className:`${ee?"text-[10px]":"text-xs"} text-bambu-gray truncate`,children:s("modelViewer.objectCount",{count:Ce.object_count??Ce.objects?.length??0})})]}),N===Ce.index&&a.jsx(Jr,{className:`${ee?"w-3.5 h-3.5":"w-4 h-4"} text-bambu-green flex-shrink-0`})]},Ce.index))]})}),(Z||me)&&a.jsxs("div",{className:"mt-auto pt-3 flex items-center gap-4 text-xs text-bambu-gray overflow-x-auto",children:[Z&&a.jsxs("div",{className:"flex items-center gap-3 whitespace-nowrap",children:[a.jsx("span",{children:s("modelViewer.plateNumber",{number:Z.index})}),Z.print_time_seconds!=null&&a.jsx("span",{children:s("modelViewer.eta",{minutes:Math.round(Z.print_time_seconds/60)})}),Z.filament_used_grams!=null&&a.jsxs("span",{children:[Z.filament_used_grams.toFixed(1)," g"]}),Z.filaments.length>0&&a.jsx("span",{children:s("modelViewer.filamentCount",{count:Z.filaments.length})})]}),me&&a.jsxs("div",{className:`flex items-center gap-2 whitespace-nowrap ${Z?"ml-auto":""}`,children:[a.jsx("span",{children:s("modelViewer.pagination.pageOf",{current:k+1,total:Q})}),a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx("button",{type:"button",onClick:()=>M(Ce=>Math.max(Ce-1,0)),disabled:k===0,className:`px-2 py-1 rounded border text-xs ${k===0?"border-bambu-dark-tertiary text-bambu-gray/40 cursor-not-allowed":"border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,children:s("modelViewer.pagination.prev")}),(()=>{let ge=Math.max(0,k-Math.floor(2.5));const L=Math.min(Q,ge+5);L-ge<5&&(ge=Math.max(0,L-5));const R=Array.from({length:L-ge},(q,ce)=>ge+ce);return a.jsxs(a.Fragment,{children:[ge>0&&a.jsx("button",{type:"button",onClick:()=>M(0),className:`px-2 py-1 rounded border text-xs ${k===0?"border-bambu-green text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,children:"1"}),ge>1&&a.jsx("span",{className:"px-1",children:"…"}),R.map(q=>a.jsx("button",{type:"button",onClick:()=>M(q),className:`px-2 py-1 rounded border text-xs ${k===q?"border-bambu-green text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,children:q+1},q)),LM(Q-1),className:`px-2 py-1 rounded border text-xs ${k===Q-1?"border-bambu-green text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,children:Q})]})})(),a.jsx("button",{type:"button",onClick:()=>M(Ce=>Math.min(Ce+1,Q-1)),disabled:k>=Q-1,className:`px-2 py-1 rounded border text-xs ${k>=Q-1?"border-bambu-dark-tertiary text-bambu-gray/40 cursor-not-allowed":"border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,children:s("modelViewer.pagination.next")})]})]})]})]})]}),ee&&a.jsx("div",{role:"separator","aria-orientation":"horizontal",onMouseDown:Ce=>{Ce.preventDefault(),O(!0),D(!0)},className:`h-2 cursor-row-resize flex items-center justify-center ${B?"bg-bambu-dark-tertiary":"bg-bambu-dark-secondary/60 hover:bg-bambu-dark-tertiary"}`,children:a.jsx("div",{className:"w-12 h-1 rounded-full bg-bambu-gray/50"})}),a.jsx("div",{className:`flex-1 ${ee?"min-h-0":""}`,children:a.jsx(xX,{url:c?ne.getLibraryFileDownloadUrl(e):h.has_source?ne.getSource3mfDownloadUrl(t):ne.getArchiveDownload(t),fileType:r,buildVolume:h.build_volume,filamentColors:h.filament_colors,selectedPlateId:N,className:"w-full h-full"})})]}):d==="gcode"&&h?a.jsx(eQ,{gcodeUrl:c?ne.getLibraryFileGcodeUrl(e):ne.getArchiveGcode(t),filamentColors:h.filament_colors,className:"w-full h-full"}):a.jsx("div",{className:"w-full h-full flex items-center justify-center text-bambu-gray",children:s("modelViewer.noPreview")})})]})})}const UN={"000000":"Black","001489":"Blue","002e96":"Blue","0047bb":"Blue","00482b":"Pine Green","004ea8":"Blue","0056b8":"Cobalt Blue","0069b1":"Lake Blue","0072ce":"Blue","0078bf":"Marine Blue","0085ad":"Light Blue","0086d6":"Cyan","008bda":"Blue","009639":"Green","009bd8":"Cyan","009fa1":"Teal","00a6a0":"Green","00ae42":"Bambu Green","00b1b7":"Turquoise","00bb31":"Green","018814":"Candy Green","042f56":"Dark Blue","0a2989":"Blue","0a2ca5":"Blue","0c2340":"Navy Blue","0c3b95":"Blue",101820:"Black","147bd1":"Blue","164b35":"Green","16b08e":"Malachite Green","1d7c6a":"Oxide Green Metallic","1f79e5":"Lake Blue","2140b4":"Blue","25282a":"Black","2842ad":"Royal Blue","2d2b28":"Onyx Black Sparkle",324585:"Indigo Blue",353533:"Gray","39541a":"Forest Green","39699e":"Cobalt Blue Metallic","3b665e":"Green","3f5443":"Alpine Green Sparkle","3f8e43":"Mistletoe Green",424379:"Nebulae","43403d":"Iron Gray Metallic",482960:"Indigo Purple","483d8b":"Royal Purple Sparkle","489fdf":"Azure","4c241c":"Rosewood","4ce4a0":"Green","4d3324":"Dark Chocolate","4d5054":"Lava Gray","4dafda":"Cyan","4f3f24":"Black Walnut",515151:"Dark Gray","515a6c":"Gray",545454:"Dark Gray",565656:"Titan Gray","56b7e6":"Sky Blue",583061:"Violet Purple","5898dd":"Blue",594177:"Purple","5b492f":"Brown","5b6579":"Blue Gray","5c9748":"Matcha Green","5e43b7":"Purple","5e4b3c":"Copper","5f6367":"Titan Gray","61b0ff":"Translucent Light Blue","61bf36":"Green","61c680":"Grass Green","6667ab":"Lavender Blue","684a43":"Brown",686865:"Black","68724d":"Dark Green",688197:"Blue Gray","69398e":"Iris Purple","6e88bc":"Jeans Blue","6ee53c":"Lime Green","6f5034":"Cocoa Brown","7248bd":"Lavender","748c45":"Translucent Olive",757575:"Nardo Gray","75aed8":"Blue","77edd7":"Translucent Teal","789d4a":"Olive","792b36":"Crimson Red Sparkle","7ac0e9":"Glow Blue","7ae1bf":"Mint","7cd82b":"Lime Green","7d6556":"Dark Brown","8344b0":"Purple","847d48":"Bronze","854ce4":"Purple","8671cb":"Purple",875718:"Peanut Brown","87909a":"Silver","898d8d":"Gray","8a949e":"Gray","8e8e8e":"Translucent Gray","8e9089":"Gray","90ff1a":"Neon Green",918669:"Classic Birch",939393:"Gray",950051:"Plum","951e23":"Burgundy Red",959698:"Silver","96d8af":"Light Jade","96dcb9":"Mint","995f11":"Clay Brown","999d9d":"Gray","9b9ea0":"Ash Gray","9d2235":"Maroon Red","9d432c":"Brown","9e007e":"Purple","9ea2a2":"Gray","9f332a":"Brick Red",a1ffac:"Glow Green",a3d8e1:"Ice Blue",a6a9aa:"Silver",a8a8aa:"Gray",a8c6ee:"Baby Blue",aa6443:"Copper Brown Metallic",ad4e38:"Red Granite",adb1b2:"Gray",ae835b:"Caramel",ae96d4:"Lilac Purple",af1685:"Purple",afb1ae:"Gray",b15533:"Terracotta",b28b33:"Gold",b39b84:"Iridium Gold Metallic",b50011:"Red",b8acd6:"Lavender",b8cde9:"Ice Blue",ba9594:"Rose Gold",bb3d43:"Dark Red",bc0900:"Red",becf00:"Bright Green",c0df16:"Green",c12e1f:"Red",c2e189:"Apple Green",c3e2d6:"Light Cyan",c5ed48:"Lime",c6001a:"Red",c6c6c6:"Gray",c8102e:"Red",c8c8c8:"Silver",c98935:"Ochre Yellow",c9a381:"Translucent Brown",cbc6b8:"Bone White",cdceca:"Gray",cea629:"Classic Gold Sparkle",d02727:"Candy Red",d1d3d5:"Light Gray",d32941:"Red",d3b7a7:"Latte Brown",d6001c:"Red",d6abff:"Translucent Purple",d6cca3:"White Oak",dc3a27:"Orange",dd3c22:"Vermilion Red",de4343:"Scarlet Red",dfd1a7:"Beige",e02928:"Red",e4bd68:"Gold",e5b03d:"Gold",e83100:"Red",e8afcf:"Sakura Pink",e8dbb7:"Desert Tan",eaeae4:"White",eaeceb:"Silver",ec008c:"Magenta",ed0000:"Red",eeb1c1:"Pink",efe255:"Yellow",f0f1a8:"Clear",f17b8f:"Glow Pink",f3cfb2:"Champagne",f3e600:"Yellow",f48438:"Orange",f4a925:"Gold",f4d53f:"Yellow",f4ee2a:"Yellow",f5547c:"Hot Pink",f55a74:"Pink",f5b6cd:"Cherry Pink",f5dbab:"Mellow Yellow",f5f1dd:"White",f68b1b:"Neon Orange",f74e02:"Orange",f75403:"Orange",f7ada6:"Pink",f7d959:"Lemon Yellow",f7e6de:"Beige",f7f3f0:"White Marble",f8ff80:"Glow Yellow",f99963:"Mandarin Orange",f9c1bd:"Translucent Pink",f9dfb9:"Cream",f9ef41:"Yellow",f9f7f2:"Nature",f9f7f4:"White",fce300:"Yellow",fce900:"Yellow",fec600:"Sunflower Yellow",fedb00:"Yellow",ff4800:"Orange",ff671f:"Orange",ff6a13:"Orange",ff7f41:"Orange",ff9016:"Pumpkin Orange",ff911a:"Translucent Orange",ff9d5b:"Glow Orange",ffb549:"Sunflower Yellow",ffc72c:"Tangerine Yellow",ffce00:"Yellow",ffd00b:"Yellow",ffe133:"Yellow",fffaf2:"White",ffffff:"White"};function T$e(t){if(!t||t.length<6)return"Unknown";const e=t.replace("#",""),n=parseInt(e.substring(0,2),16),r=parseInt(e.substring(2,4),16),i=parseInt(e.substring(4,6),16),s=Math.max(n,r,i)/255,o=Math.min(n,r,i)/255,l=(s+o)/2;let c=0,d=0;if(s!==o){const u=s-o;d=l>.5?u/(2-s-o):u/(s+o);const h=n/255,f=r/255,p=i/255;s===h?c=((f-p)/u+(f.85?"White":d<.15?l<.4?"Dark Gray":l>.6?"Light Gray":"Gray":c<15||c>=345?"Red":c<45?"Orange":c<70?"Yellow":c<150?"Green":c<200?"Cyan":c<260?"Blue":c<290?"Purple":"Pink"}function vf(t){const e=t.replace("#","").toLowerCase().substring(0,6);return UN[e]?UN[e]:T$e(t)}function b4(t,e){if(t&&!/^[A-Z]\d+-[A-Z]\d+$/.test(t))return t;if(e&&e.length>=6){const n=e.substring(0,6).toLowerCase();if(UN[n])return UN[n]}return null}function sA(t){const e=[],n=t?.ams_extruder_map,r=n&&Object.keys(n).length>0;t?.ams?.forEach(i=>{const s=i.tray.length===1;i.tray.forEach(o=>{if(o.tray_type){const l=Z7(o.tray_color);e.push({type:o.tray_type,color:l,colorName:vf(l),amsId:i.id,trayId:o.id,isHt:s,isExternal:!1,label:m4(i.id,o.id,s,!1),globalTrayId:f4(i.id,o.id,!1),trayInfoIdx:o.tray_info_idx||"",extruderId:n?.[String(i.id)]})}})});for(const i of t?.vt_tray??[])if(i.tray_type){const s=Z7(i.tray_color),o=i.id??254,l=(t?.vt_tray?.length??0)>1;e.push({type:i.tray_type,color:s,colorName:vf(s),amsId:-1,trayId:o-254,isHt:!1,isExternal:!0,label:l?o===254?"Ext-L":"Ext-R":"External",globalTrayId:o,trayInfoIdx:i.tray_info_idx||"",extruderId:r?255-o:void 0})}return e}function l9(t,e){if(!t?.filaments||t.filaments.length===0)return;const n=sA(e);if(n.length===0)return;const r=new Set,i=t.filaments.map(l=>{const c=l.tray_info_idx||"";let d=n.filter(v=>!r.has(v.globalTrayId));l.nozzle_id!=null&&(d=d.filter(v=>v.extruderId===l.nozzle_id));let u,h,f,p;if(c){const v=d.filter(g=>g.trayInfoIdx===c);v.length===1?u=v[0]:v.length>1&&(h=v.find(g=>g.type?.toUpperCase()===l.type?.toUpperCase()&&Ra(g.color)===Ra(l.color)),h||(f=v.find(g=>g.type?.toUpperCase()===l.type?.toUpperCase()&&Rc(g.color,l.color))),!h&&!f&&(p=v.find(g=>g.type?.toUpperCase()===l.type?.toUpperCase())))}!u&&!h&&!f&&!p&&(h=d.find(v=>v.type?.toUpperCase()===l.type?.toUpperCase()&&Ra(v.color)===Ra(l.color)),h||(f=d.find(v=>v.type?.toUpperCase()===l.type?.toUpperCase()&&Rc(v.color,l.color))),!h&&!f&&(p=d.find(v=>v.type?.toUpperCase()===l.type?.toUpperCase())));const x=u||h||f||p||void 0;return x&&r.add(x.globalTrayId),{slot_id:l.slot_id,globalTrayId:x?.globalTrayId??-1}}),s=Math.max(...i.map(l=>l.slot_id||0));if(s<=0)return;const o=new Array(s).fill(-1);return i.forEach(l=>{l.slot_id&&l.slot_id>0&&(o[l.slot_id-1]=l.globalTrayId)}),o}function M$e(t){return w.useMemo(()=>sA(t),[t])}function yne(t,e,n){const r=M$e(e),i=w.useMemo(()=>{if(!t?.filaments||t.filaments.length===0)return[];const c=new Set(Object.values(n));return t.filaments.map(d=>{const u=d.slot_id||0;if(u>0&&n[u]!==void 0){const M=n[u],C=r.find(j=>j.globalTrayId===M);if(C){const j=C.type?.toUpperCase()===d.type?.toUpperCase(),P=Ra(C.color)===Ra(d.color)||Rc(C.color,d.color);let E;return j&&P?E="match":j?E="type_only":E="mismatch",{...d,loaded:C,hasFilament:!0,typeMatch:j,colorMatch:P,status:E,isManual:!0}}}const h=d.tray_info_idx||"";let f=r.filter(M=>!c.has(M.globalTrayId));d.nozzle_id!=null&&(f=f.filter(M=>M.extruderId===d.nozzle_id));let p,x,v,g;if(h){const M=f.filter(C=>C.trayInfoIdx===h);M.length===1?p=M[0]:M.length>1&&(x=M.find(C=>C.type?.toUpperCase()===d.type?.toUpperCase()&&Ra(C.color)===Ra(d.color)),x||(v=M.find(C=>C.type?.toUpperCase()===d.type?.toUpperCase()&&Rc(C.color,d.color))),!x&&!v&&(g=M.find(C=>C.type?.toUpperCase()===d.type?.toUpperCase())))}!p&&!x&&!v&&!g&&(x=f.find(M=>M.type?.toUpperCase()===d.type?.toUpperCase()&&Ra(M.color)===Ra(d.color)),x||(v=f.find(M=>M.type?.toUpperCase()===d.type?.toUpperCase()&&Rc(M.color,d.color))),!x&&!v&&(g=f.find(M=>M.type?.toUpperCase()===d.type?.toUpperCase())));const y=p||x||v||g||void 0;y&&c.add(y.globalTrayId);const _=!!y,N=_,T=!!p||!!x||!!v;let k;return p||x||v?k="match":g?k="type_only":k="mismatch",{...d,loaded:y,hasFilament:_,typeMatch:N,colorMatch:T,status:k,isManual:!1}})},[t,r,n]),s=w.useMemo(()=>{if(i.length===0)return;const c=Math.max(...i.map(u=>u.slot_id||0));if(c<=0)return;const d=new Array(c).fill(-1);return i.forEach(u=>{u.slot_id&&u.slot_id>0&&(d[u.slot_id-1]=u.loaded?.globalTrayId??-1)}),d},[i]),o=i.some(c=>c.status==="mismatch"),l=i.some(c=>c.status==="type_only");return{loadedFilaments:r,filamentComparison:i,amsMapping:s,hasTypeMismatch:o,hasColorMismatch:l}}function P$e(t,e,n){if(!t||t.length===0)return{exactMatches:0,typeOnlyMatches:0,missingTypes:0,totalSlots:0,status:"full"};let r=0,i=0,s=0;const o=new Set(Object.values(n));for(const d of t){const u=d.slot_id||0;if(u>0&&n[u]!==void 0){const g=n[u],y=e.find(_=>_.globalTrayId===g);if(y){const _=y.type?.toUpperCase()===d.type?.toUpperCase(),N=Ra(y.color)===Ra(d.color)||Rc(y.color,d.color);_&&N?r++:_?i++:s++;continue}}let h=e.filter(g=>!o.has(g.globalTrayId));if(d.nozzle_id!=null){const g=h.filter(y=>y.extruderId===d.nozzle_id);g.length>0&&(h=g)}const f=h.find(g=>g.type?.toUpperCase()===d.type?.toUpperCase()&&Ra(g.color)===Ra(d.color)),p=f?void 0:h.find(g=>g.type?.toUpperCase()===d.type?.toUpperCase()&&Rc(g.color,d.color)),x=f||p?void 0:h.find(g=>g.type?.toUpperCase()===d.type?.toUpperCase()),v=f??p??x;v&&o.add(v.globalTrayId),f||p?r++:x?i++:s++}const l=t.length;let c="full";return s>0?c="missing":i>0&&(c="partial"),{exactMatches:r,typeOnlyMatches:i,missingTypes:s,totalSlots:l,status:c}}function E$e(t,e,n){if(!t?.filaments||t.filaments.length===0)return;const r=sA(e);if(r.length===0)return;const i=new Set(Object.values(n)),s=[];for(const c of t.filaments){const d=c.slot_id||0;if(d>0&&n[d]!==void 0){s.push({slot_id:d,globalTrayId:n[d]});continue}let u=r.filter(v=>!i.has(v.globalTrayId));if(c.nozzle_id!=null){const v=u.filter(g=>g.extruderId===c.nozzle_id);v.length>0&&(u=v)}const h=u.find(v=>v.type?.toUpperCase()===c.type?.toUpperCase()&&Ra(v.color)===Ra(c.color)),f=h?void 0:u.find(v=>v.type?.toUpperCase()===c.type?.toUpperCase()&&Rc(v.color,c.color)),p=h||f?void 0:u.find(v=>v.type?.toUpperCase()===c.type?.toUpperCase()),x=h??f??p;x&&i.add(x.globalTrayId),s.push({slot_id:d,globalTrayId:x?.globalTrayId??-1})}const o=Math.max(...s.map(c=>c.slot_id||0));if(o<=0)return;const l=new Array(o).fill(-1);return s.forEach(c=>{c.slot_id&&c.slot_id>0&&(l[c.slot_id-1]=c.globalTrayId)}),l}const c9={useDefault:!0,manualMappings:{},autoConfigured:!1};function j$e(t,e,n,r,i,s){const o=zC({queries:t.map(x=>({queryKey:["printer-status",x],queryFn:()=>ne.getPrinterStatus(x),enabled:t.length>0,staleTime:5e3}))}),l=w.useMemo(()=>t.map((x,v)=>{const g=o[v],y=g?.data,N=e?.find(E=>E.id===x)?.name||`Printer ${x}`,T=sA(y),k=i[x]||c9,M=l9(n,y),C=k.useDefault?r:k.manualMappings,j=E$e(n,y,C),P=P$e(n?.filaments,T,C);return{printerId:x,printerName:N,status:y,isLoading:g?.isLoading??!1,loadedFilaments:T,autoMapping:M,finalMapping:j,matchStatus:P.status,exactMatches:P.exactMatches,typeOnlyMatches:P.typeOnlyMatches,missingTypes:P.missingTypes,totalSlots:P.totalSlots,config:k}}),[t,o,e,n,i,r]),c=o.some(x=>x.isLoading),d=(x,v)=>{s(g=>({...g,[x]:{...g[x]||c9,...v}}))},u=x=>{const v=l.find(_=>_.printerId===x);if(!v||!v.status||!n?.filaments)return;const g=l9(n,v.status);if(!g)return;const y={};g.forEach((_,N)=>{_!==-1&&(y[N+1]=_)}),d(x,{useDefault:!1,manualMappings:y,autoConfigured:!0})},h=()=>{for(const x of t)u(x)},f=x=>l.find(g=>g.printerId===x)?.finalMapping,p=l.every(x=>x.matchStatus!=="missing");return{printerResults:l,isLoading:c,perPrinterConfigs:i,updatePrinterConfig:d,autoConfigureAll:h,autoConfigurePrinter:u,getFinalMapping:f,allPrintersReady:p}}function D$e({printerId:t,filamentReqs:e,manualMappings:n,onManualMappingChange:r,currencySymbol:i,defaultCostPerKg:s,defaultExpanded:o=!1}){const{t:l}=Dt(),c=Jt(),[d,u]=w.useState(!1),[h,f]=w.useState(o),{data:p}=Je({queryKey:["printer-status",t],queryFn:()=>ne.getPrinterStatus(t),enabled:!!t}),{data:x}=Je({queryKey:["spool-assignments",t],queryFn:()=>ne.getAssignments(t),enabled:!!t}),{loadedFilaments:v,filamentComparison:g,hasTypeMismatch:y,hasColorMismatch:_}=yne(e,p,n),N=w.useMemo(()=>{const B=new Map;for(const O of x||[]){const z=O.ams_id===255,D=f4(O.ams_id,O.tray_id,z);B.set(D,O.spool?.cost_per_kg??null)}return B},[x]),T=w.useMemo(()=>{let B=0;for(const O of g){const z=O.loaded?.globalTrayId;if(z==null)continue;const $=N.get(z)??null??s;$>0&&(B+=O.used_grams/1e3*$)}return B},[g,N,s]),k=w.useMemo(()=>Array.from(N.values()).some(B=>B!=null&&B>0),[N]),M=e?.filaments&&e.filaments.length>0,C=e?.filaments?.some(B=>B.nozzle_id!=null)??!1;if(!M||!p)return null;const j=y?"#f97316":_?"#facc15":"#00ae42",P=(B,O)=>{if(B>0)if(O===""){const z={...n};delete z[B],r(z)}else r({...n,[B]:parseInt(O,10)})},E=async()=>{u(!0);try{await ne.refreshPrinterStatus(t),await new Promise(B=>setTimeout(B,500)),await c.refetchQueries({queryKey:["printer-status",t]})}finally{u(!1)}};return a.jsxs("div",{className:"mb-4",children:[a.jsxs("button",{type:"button",onClick:()=>f(!h),className:"flex items-center gap-2 text-sm text-bambu-gray hover:text-white transition-colors w-full",children:[a.jsx(x1,{className:"w-4 h-4",fill:j,stroke:"none"}),a.jsx("span",{children:l("printModal.filamentMapping")}),y?a.jsx("span",{className:"text-xs text-orange-400",children:"(Type not found)"}):_?a.jsx("span",{className:"text-xs text-yellow-400",children:"(Color mismatch)"}):a.jsx("span",{className:"text-xs text-bambu-green",children:"(Ready)"}),h?a.jsx(yl,{className:"w-4 h-4 ml-auto"}):a.jsx(Pn,{className:"w-4 h-4 ml-auto"})]}),h&&a.jsxs("div",{className:"mt-2 bg-bambu-dark rounded-lg p-3 space-y-2",children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsx("span",{className:"text-xs text-bambu-gray",children:"Click to change slot assignment"}),a.jsxs("button",{type:"button",onClick:E,className:"flex items-center gap-1 px-2 py-0.5 text-xs rounded border border-bambu-gray/30 hover:border-bambu-gray hover:bg-bambu-dark-tertiary transition-colors text-bambu-gray hover:text-white",disabled:d,children:[a.jsx(vr,{className:`w-3 h-3 ${d?"animate-spin":""}`}),a.jsx("span",{children:"Re-read"})]})]}),g.map((B,O)=>a.jsxs("div",{className:"grid items-center gap-2 text-xs",style:{gridTemplateColumns:"16px minmax(70px, 1fr) auto 2fr 16px"},children:[a.jsx("span",{title:`Required: ${B.type} - ${vf(B.color)}`,children:a.jsx(x1,{className:"w-3 h-3",fill:B.color,stroke:B.color})}),a.jsxs("span",{className:"text-white truncate flex items-center gap-1",children:[C&&B.nozzle_id!=null&&a.jsx("span",{className:"inline-flex items-center justify-center w-3.5 h-3.5 rounded text-[9px] font-bold leading-none bg-bambu-gray/20 text-bambu-gray shrink-0",title:B.nozzle_id===1?l("printModal.leftNozzleTooltip"):l("printModal.rightNozzleTooltip"),children:B.nozzle_id===1?l("printModal.leftNozzle"):l("printModal.rightNozzle")}),B.type," ",a.jsxs("span",{className:"text-bambu-gray",children:["(",B.used_grams,"g)"]})]}),a.jsx("span",{className:"text-bambu-gray",children:"→"}),a.jsxs("select",{value:B.loaded?.globalTrayId??"",onChange:z=>P(B.slot_id||0,z.target.value),className:`flex-1 px-2 py-1 rounded border text-xs bg-bambu-dark-secondary focus:outline-none focus:ring-1 focus:ring-bambu-green ${B.status==="match"?"border-bambu-green/50 text-bambu-green":B.status==="type_only"?"border-yellow-400/50 text-yellow-400":"border-orange-400/50 text-orange-400"} ${B.isManual?"ring-1 ring-blue-400/50":""}`,title:B.isManual?"Manually selected":"Auto-matched",children:[a.jsx("option",{value:"",className:"bg-bambu-dark text-bambu-gray",children:"-- Select slot --"}),v.filter(z=>B.nozzle_id==null||z.extruderId===B.nozzle_id).map(z=>a.jsxs("option",{value:z.globalTrayId,className:"bg-bambu-dark text-white",children:[z.label,": ",z.type," (",z.colorName,")"]},z.globalTrayId))]}),B.status==="match"?a.jsx(Jr,{className:"w-3 h-3 text-bambu-green"}):B.status==="type_only"?a.jsx("span",{title:"Same type, different color",children:a.jsx(An,{className:"w-3 h-3 text-yellow-400"})}):a.jsx("span",{title:"Filament type not loaded",children:a.jsx(An,{className:"w-3 h-3 text-orange-400"})})]},O)),a.jsxs("div",{className:"text-xs text-bambu-gray",children:[l("printModal.totalCost")," ",a.jsx("span",{className:"text-white",children:T>0||k?`${i}${T.toFixed(2)}`:"N/A"})]}),y&&a.jsx("p",{className:"text-xs text-orange-400 mt-2",children:"Required filament type not found in printer."})]})]})}function R$e({filamentReqs:t,availableFilaments:e,overrides:n,onChange:r}){const{t:i}=Dt(),s=w.useMemo(()=>{const c={};for(const d of e){const u=d.type.toUpperCase();c[u]||(c[u]=[]),c[u].push(d)}return c},[e]),o=t?.filaments;if(!o||o.length===0||e.length===0)return null;const l=(c,d)=>{if(d===""){const u={...n};delete u[c],r(u)}else{const[u,h]=d.split("|");r({...n,[c]:{type:u,color:h}})}};return a.jsxs("div",{className:"mb-4",children:[a.jsx("div",{className:"flex items-center gap-2 text-sm text-bambu-gray mb-2",children:a.jsx("span",{children:i("printModal.filamentOverride")})}),a.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:i("printModal.filamentOverrideHint")}),a.jsx("div",{className:"bg-bambu-dark rounded-lg p-3 space-y-2",children:o.map(c=>{const d=n[c.slot_id],u=!!d,h=s[c.type.toUpperCase()]||[],f=c.nozzle_id!=null?h.filter(p=>p.extruder_id==null||p.extruder_id===c.nozzle_id):h;return a.jsxs("div",{className:"grid items-center gap-2 text-xs",style:{gridTemplateColumns:"16px minmax(70px, 1fr) auto 2fr 20px"},children:[a.jsx("span",{title:`${i("printModal.originalFilament")}: ${c.type} - ${vf(c.color)}`,children:a.jsx(x1,{className:"w-3 h-3",fill:c.color,stroke:c.color})}),a.jsxs("span",{className:"text-white truncate",children:[c.type," ",a.jsxs("span",{className:"text-bambu-gray",children:["(",c.used_grams,"g)"]})]}),a.jsx("span",{className:"text-bambu-gray",children:"→"}),a.jsxs("select",{value:u?`${d.type}|${d.color}`:"",onChange:p=>l(c.slot_id,p.target.value),disabled:f.length===0,className:`flex-1 px-2 py-1 rounded border text-xs bg-bambu-dark-secondary focus:outline-none focus:ring-1 focus:ring-bambu-green ${u?"border-blue-400/50 text-blue-400":"border-bambu-gray/30 text-bambu-gray"}`,children:[a.jsxs("option",{value:"",className:"bg-bambu-dark text-bambu-gray",children:[i("printModal.originalFilament"),": ",c.type," (",vf(c.color),")"]}),f.map((p,x)=>a.jsxs("option",{value:`${p.type}|${p.color}`,className:"bg-bambu-dark text-white",children:[p.type," (",vf(p.color),")"]},`${p.type}-${p.color}-${x}`))]}),u?a.jsx("button",{type:"button",onClick:()=>l(c.slot_id,""),className:"text-bambu-gray hover:text-white transition-colors",title:i("printModal.resetToOriginal"),children:a.jsx(so,{className:"w-3 h-3"})}):a.jsx("span",{className:"w-3"})]},c.slot_id)})})]})}function F$e({plates:t,isMultiPlate:e,selectedPlate:n,onSelect:r}){return!e||t.length<=1?null:a.jsxs("div",{className:"mb-4",children:[a.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[a.jsx(oi,{className:"w-4 h-4 text-bambu-gray"}),a.jsx("span",{className:"text-sm text-bambu-gray",children:"Select Plate to Print"}),!n&&a.jsxs("span",{className:"text-xs text-orange-400 flex items-center gap-1",children:[a.jsx(An,{className:"w-3 h-3"}),"Selection required"]})]}),a.jsx("div",{className:"grid grid-cols-2 gap-2",children:t.map(i=>a.jsxs("button",{type:"button",onClick:()=>r(i.index),className:`flex items-center gap-2 p-2 rounded-lg border transition-colors text-left ${n===i.index?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark hover:border-bambu-gray"}`,children:[i.has_thumbnail&&i.thumbnail_url!=null?a.jsx("img",{src:i.thumbnail_url,alt:`Plate ${i.index}`,className:"w-10 h-10 rounded object-cover bg-bambu-dark-tertiary"}):a.jsx("div",{className:"w-10 h-10 rounded bg-bambu-dark-tertiary flex items-center justify-center",children:a.jsx(oi,{className:"w-5 h-5 text-bambu-gray"})}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:"text-sm text-white font-medium truncate",children:i.name||`Plate ${i.index}`}),a.jsxs("p",{className:"text-xs text-bambu-gray truncate",children:[i.objects.length>0?i.objects.slice(0,3).join(", ")+(i.objects.length>3?"...":""):`${i.filaments.length} filament${i.filaments.length!==1?"s":""}`,i.print_time_seconds!=null?` • ${Qs(i.print_time_seconds)}`:""]})]}),n===i.index&&a.jsx(Jr,{className:"w-4 h-4 text-bambu-green flex-shrink-0"})]},i.index))})]})}function L$e({printerResult:t,filamentReqs:e,onUpdateConfig:n}){const r=Jt(),[i,s]=w.useState(!1),o=(d,u)=>{if(d<=0)return;const h={...t.config.manualMappings};u===""?delete h[d]:h[d]=parseInt(u,10),n({useDefault:!1,manualMappings:h,autoConfigured:!1})},l=async()=>{s(!0);try{await ne.refreshPrinterStatus(t.printerId),await new Promise(d=>setTimeout(d,500)),await r.refetchQueries({queryKey:["printer-status",t.printerId]})}finally{s(!1)}},c=e.map(d=>{const u=d.slot_id||0,h=t.config.manualMappings[u];let f,p=!1;if(h!==void 0)f=t.loadedFilaments.find(v=>v.globalTrayId===h),p=!0;else{const v=new Set(Object.values(t.config.manualMappings)),g=t.loadedFilaments.find(N=>!v.has(N.globalTrayId)&&N.type?.toUpperCase()===d.type?.toUpperCase()&&Ra(N.color)===Ra(d.color)),y=g?void 0:t.loadedFilaments.find(N=>!v.has(N.globalTrayId)&&N.type?.toUpperCase()===d.type?.toUpperCase()&&Rc(N.color,d.color)),_=g||y?void 0:t.loadedFilaments.find(N=>!v.has(N.globalTrayId)&&N.type?.toUpperCase()===d.type?.toUpperCase());f=g??y??_}let x="mismatch";if(f){const v=f.type?.toUpperCase()===d.type?.toUpperCase(),g=Ra(f.color)===Ra(d.color)||Rc(f.color,d.color);v&&g?x="match":v&&(x="type_only")}return{req:d,loaded:f,status:x,isManual:p}});return a.jsxs("div",{className:"mt-2 bg-bambu-dark rounded-lg p-3 space-y-2",children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsx("span",{className:"text-xs text-bambu-gray",children:"Custom slot mapping"}),a.jsxs("button",{type:"button",onClick:l,className:"flex items-center gap-1 px-2 py-0.5 text-xs rounded border border-bambu-gray/30 hover:border-bambu-gray hover:bg-bambu-dark-tertiary transition-colors text-bambu-gray hover:text-white",disabled:i,children:[a.jsx(vr,{className:`w-3 h-3 ${i?"animate-spin":""}`}),a.jsx("span",{children:"Re-read"})]})]}),c.map(({req:d,loaded:u,status:h,isManual:f},p)=>a.jsxs("div",{className:"grid items-center gap-2 text-xs",style:{gridTemplateColumns:"16px minmax(70px, 1fr) auto 2fr 16px"},children:[a.jsx("span",{title:`Required: ${d.type} - ${vf(d.color)}`,children:a.jsx(x1,{className:"w-3 h-3",fill:d.color,stroke:d.color})}),a.jsxs("span",{className:"text-white truncate",children:[d.type," ",a.jsxs("span",{className:"text-bambu-gray",children:["(",d.used_grams,"g)"]})]}),a.jsx("span",{className:"text-bambu-gray",children:"→"}),a.jsxs("select",{value:u?.globalTrayId??"",onChange:x=>o(d.slot_id||0,x.target.value),className:`flex-1 px-2 py-1 rounded border text-xs bg-bambu-dark-secondary focus:outline-none focus:ring-1 focus:ring-bambu-green ${h==="match"?"border-bambu-green/50 text-bambu-green":h==="type_only"?"border-yellow-400/50 text-yellow-400":"border-orange-400/50 text-orange-400"} ${f?"ring-1 ring-blue-400/50":""}`,title:f?"Manually selected":"Auto-matched",children:[a.jsx("option",{value:"",className:"bg-bambu-dark text-bambu-gray",children:"-- Select slot --"}),t.loadedFilaments.map(x=>a.jsxs("option",{value:x.globalTrayId,className:"bg-bambu-dark text-white",children:[x.label,": ",x.type," (",x.colorName,")"]},x.globalTrayId))]}),h==="match"?a.jsx(Jr,{className:"w-3 h-3 text-bambu-green"}):h==="type_only"?a.jsx("span",{title:"Same type, different color",children:a.jsx(An,{className:"w-3 h-3 text-yellow-400"})}):a.jsx("span",{title:"Filament type not loaded",children:a.jsx(An,{className:"w-3 h-3 text-orange-400"})})]},p))]})}function O$e({printers:t,selectedPrinterIds:e,onMultiSelect:n,isLoading:r=!1,allowMultiple:i=!1,showInactive:s=!1,printerMappingResults:o,filamentReqs:l,onAutoConfigurePrinter:c,onUpdatePrinterConfig:d,assignmentMode:u="printer",onAssignmentModeChange:h,targetModel:f,onTargetModelChange:p,targetLocation:x,onTargetLocationChange:v,slicedForModel:g}){const[y,_]=w.useState(!1),N=s?t:t.filter(U=>U.is_active),T=w.useMemo(()=>{if(u!=="printer"||!g||y)return N;const U=N.filter(W=>W.model===g);return U.length>0?U:N},[N,u,g,y]),k=N.length-T.length,M=w.useMemo(()=>{const U=N.map(W=>W.model).filter(W=>!!W);return[...new Set(U)].sort()},[N]),C=w.useMemo(()=>{if(!f)return[];const U=N.filter(W=>W.model===f&&W.location).map(W=>W.location).filter(W=>!!W);return[...new Set(U)].sort()},[N,f]),j=h&&p&&M.length>0,P=i&&e.length>1&&o&&l?.filaments&&l.filaments.length>0&&c&&d;if(r)return a.jsx("div",{className:"flex justify-center py-8",children:a.jsx(at,{className:"w-6 h-6 text-bambu-green animate-spin"})});if(T.length===0)return a.jsxs("div",{className:"flex items-center gap-2 text-red-400 text-sm mb-4",children:[a.jsx(Wa,{className:"w-4 h-4"}),"No ",s?"":"active ","printers available"]});const E=U=>{i?e.includes(U)?n(e.filter(W=>W!==U)):n([...e,U]):n([U])},B=()=>{n(T.map(U=>U.id))},O=()=>{n([])},z=(U,W,Y)=>{Y.stopPropagation(),!(!c||!d)&&(W?c(U):d(U,{useDefault:!0,manualMappings:{},autoConfigured:!1}))},D=U=>e.includes(U),$=e.length,G=U=>o?.find(W=>W.printerId===U);return a.jsxs("div",{className:"space-y-2 mb-6",children:[j&&a.jsxs("div",{className:"flex gap-2 mb-4",children:[a.jsxs("button",{type:"button",onClick:()=>{h("printer"),p(null)},className:`flex-1 flex items-center justify-center gap-2 px-3 py-2 rounded-lg border transition-colors ${u==="printer"?"border-bambu-green bg-bambu-green/10 text-white":"border-bambu-dark-tertiary bg-bambu-dark text-bambu-gray hover:border-bambu-gray"}`,children:[a.jsx(Sr,{className:"w-4 h-4"}),a.jsx("span",{className:"text-sm",children:"Specific Printer"})]}),a.jsxs("button",{type:"button",onClick:()=>{h("model"),n([]);const U=g&&M.includes(g)?g:M[0];p(U)},className:`flex-1 flex items-center justify-center gap-2 px-3 py-2 rounded-lg border transition-colors ${u==="model"?"border-bambu-green bg-bambu-green/10 text-white":"border-bambu-dark-tertiary bg-bambu-dark text-bambu-gray hover:border-bambu-gray"}`,children:[a.jsx(mh,{className:"w-4 h-4"}),a.jsxs("span",{className:"text-sm",children:["Any ",g||"Model"]})]})]}),u==="model"&&j&&a.jsxs("div",{className:"space-y-3 mb-4",children:[!g&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Target Model"}),a.jsxs("select",{value:f||"",onChange:U=>{p(U.target.value||null),v&&v(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 text-sm",children:[a.jsx("option",{value:"",children:"Select a model..."}),M.map(U=>a.jsx("option",{value:U,children:U},U))]})]}),f&&C.length>0&&v&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Location Filter (optional)"}),a.jsxs("select",{value:x||"",onChange:U=>v(U.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 text-sm",children:[a.jsx("option",{value:"",children:"Any location"}),C.map(U=>a.jsx("option",{value:U,children:U},U))]})]}),f&&a.jsxs("p",{className:"text-xs text-bambu-gray",children:["Scheduler will assign to first available idle ",f," printer",x?` in ${x}`:""]})]}),u==="printer"&&i&&T.length>1&&a.jsxs("div",{className:"flex items-center justify-between text-xs text-bambu-gray mb-2",children:[a.jsx("span",{children:$===0?"Select printers":`${$} printer${$!==1?"s":""} selected`}),a.jsxs("div",{className:"flex gap-2",children:[$0&&a.jsx("button",{type:"button",onClick:O,className:"text-bambu-gray hover:text-white transition-colors",children:"Clear"})]})]}),u==="printer"&&T.map(U=>{const W=D(U.id),Y=G(U.id),re=Y&&!Y.config.useDefault;return a.jsxs("div",{children:[a.jsxs("button",{type:"button",onClick:()=>E(U.id),className:`w-full flex items-center gap-3 p-3 rounded-lg border transition-colors ${W?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark hover:border-bambu-gray"} ${U.is_active?"":"opacity-60"}`,children:[a.jsx("div",{className:`p-2 rounded-lg ${W?"bg-bambu-green/20":"bg-bambu-dark-tertiary"}`,children:a.jsx(Sr,{className:`w-5 h-5 ${W?"text-bambu-green":"text-bambu-gray"}`})}),a.jsxs("div",{className:"text-left flex-1",children:[a.jsxs("p",{className:"text-white font-medium",children:[U.name,!U.is_active&&a.jsx("span",{className:"text-bambu-gray text-xs ml-2",children:"(inactive)"})]}),a.jsxs("p",{className:"text-xs text-bambu-gray",children:[U.model||"Unknown model"," • ",U.ip_address]})]}),i&&a.jsx("div",{className:`w-5 h-5 rounded border-2 flex items-center justify-center transition-colors ${W?"bg-bambu-green border-bambu-green":"border-bambu-gray/50"}`,children:W&&a.jsx(Jr,{className:"w-3 h-3 text-white"})})]}),W&&P&&Y&&a.jsxs("div",{className:"ml-4 mt-2 mb-3",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",onClick:H=>H.stopPropagation(),children:[a.jsx("input",{type:"checkbox",checked:re,onChange:H=>z(U.id,H.target.checked,H),className:"w-3.5 h-3.5 rounded border-bambu-gray/30 bg-bambu-dark-secondary text-bambu-green focus:ring-bambu-green focus:ring-offset-0"}),a.jsx("span",{className:"text-xs text-bambu-gray",children:"Custom mapping"})]}),a.jsxs("span",{className:`text-xs ml-2 ${Y.matchStatus==="full"?"text-bambu-green":Y.matchStatus==="partial"?"text-yellow-400":"text-orange-400"}`,children:["(",Y.exactMatches,"/",Y.totalSlots," matched)"]}),Y.isLoading&&a.jsx(vr,{className:"w-3 h-3 text-bambu-gray animate-spin"}),re&&a.jsxs("button",{type:"button",onClick:H=>{H.stopPropagation(),c(U.id)},className:"ml-auto flex items-center gap-1 px-2 py-0.5 text-xs rounded border border-bambu-gray/30 hover:border-bambu-gray hover:bg-bambu-dark-tertiary transition-colors text-bambu-gray hover:text-white",children:[a.jsx(nge,{className:"w-3 h-3"}),"Auto"]})]}),re&&a.jsx(L$e,{printerResult:Y,filamentReqs:l.filaments,onUpdateConfig:H=>d(U.id,H)})]})]},U.id)}),u==="printer"&&k>0&&!y&&a.jsxs("button",{type:"button",onClick:()=>_(!0),className:"text-xs text-bambu-gray hover:text-white transition-colors mt-2 flex items-center gap-1",children:[a.jsx(An,{className:"w-3 h-3 text-yellow-400"}),k," other printer",k>1?"s":""," hidden (different model) —",a.jsx("span",{className:"underline",children:"show all"})]}),u==="printer"&&y&&g&&a.jsx("button",{type:"button",onClick:()=>_(!1),className:"text-xs text-bambu-gray hover:text-white transition-colors mt-2",children:a.jsxs("span",{className:"underline",children:["Show only ",g," printers"]})}),u==="printer"&&$===0&&a.jsxs("p",{className:"text-xs text-orange-400 mt-1 flex items-center gap-1",children:[a.jsx(Wa,{className:"w-3 h-3"}),"Select at least one printer"]}),u==="model"&&!f&&a.jsxs("p",{className:"text-xs text-orange-400 mt-1 flex items-center gap-1",children:[a.jsx(Wa,{className:"w-3 h-3"}),"Select a target printer model"]})]})}const I$e=[{key:"bed_levelling",label:"Bed Levelling",desc:"Auto-level bed before print"},{key:"flow_cali",label:"Flow Calibration",desc:"Calibrate extrusion flow"},{key:"vibration_cali",label:"Vibration Calibration",desc:"Reduce ringing artifacts"},{key:"layer_inspect",label:"First Layer Inspection",desc:"AI inspection of first layer"},{key:"timelapse",label:"Timelapse",desc:"Record timelapse video"}];function z$e({options:t,onChange:e,defaultExpanded:n=!1}){const[r,i]=w.useState(n),s=o=>{e({...t,[o]:!t[o]})};return a.jsxs("div",{className:"mb-4",children:[a.jsxs("button",{type:"button",onClick:()=>i(!r),className:"flex items-center gap-2 text-sm text-bambu-gray hover:text-white transition-colors w-full",children:[a.jsx(QC,{className:"w-4 h-4"}),a.jsx("span",{children:"Print Options"}),r?a.jsx(yl,{className:"w-4 h-4 ml-auto"}):a.jsx(Pn,{className:"w-4 h-4 ml-auto"})]}),r&&a.jsx("div",{className:"mt-2 bg-bambu-dark rounded-lg p-3 space-y-2",children:I$e.map(({key:o,label:l,desc:c})=>a.jsxs("label",{className:"flex items-center justify-between cursor-pointer group",children:[a.jsxs("div",{children:[a.jsx("span",{className:"text-sm text-white",children:l}),a.jsx("p",{className:"text-xs text-bambu-gray",children:c})]}),a.jsx("div",{className:`relative w-10 h-5 rounded-full transition-colors ${t[o]?"bg-bambu-green":"bg-bambu-dark-tertiary"}`,onClick:()=>s(o),children:a.jsx("div",{className:`absolute top-0.5 w-4 h-4 rounded-full bg-white transition-transform ${t[o]?"translate-x-5":"translate-x-0.5"}`})})]},o))})]})}function U$e({options:t,onChange:e,dateFormat:n="system",timeFormat:r="system",canControlPrinter:i=!0}){const[s,o]=w.useState(""),[l,c]=w.useState(""),[d,u]=w.useState(!0),[h,f]=w.useState(!0),p=w.useRef(null),x=w.useRef(!1);w.useEffect(()=>{if(t.scheduleType!=="scheduled"){x.current=!1;return}if(!x.current){x.current=!0;let k;t.scheduledTime?(k=new Date(t.scheduledTime),isNaN(k.getTime())&&(k=new Date,k.setHours(k.getHours()+1,0,0,0))):(k=new Date,k.setHours(k.getHours()+1,0,0,0),e({...t,scheduledTime:u3(k)})),o(d3(k,n)),c($B(k,r)),u(!0),f(!0)}},[t.scheduleType,t.scheduledTime,n,r,e,t]);const v=k=>{e({...t,scheduleType:k})},g=(k,M)=>{const C=Nge(k,n),j=Cge(M);u(!!C),f(!!j),C&&j&&(C.setHours(j.hours,j.minutes,0,0),C>new Date&&e({...t,scheduledTime:u3(C)}))},y=k=>{o(k),g(k,l)},_=k=>{c(k),g(s,k)},N=k=>{const M=k.target.value;if(M){const C=new Date(M);isNaN(C.getTime())||(o(d3(C,n)),c($B(C,r)),u(!0),f(!0),e({...t,scheduledTime:M}))}},T=()=>{p.current?.showPicker()};return a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-2",children:"When to print"}),a.jsxs("div",{className:"flex gap-2",children:[a.jsxs("button",{type:"button",className:`flex-1 px-2 py-2 rounded-lg border text-sm flex items-center justify-center gap-1.5 transition-colors ${t.scheduleType==="asap"?"bg-bambu-green border-bambu-green text-white":"bg-bambu-dark border-bambu-dark-tertiary text-bambu-gray hover:text-white"}`,onClick:()=>v("asap"),children:[a.jsx(Vn,{className:"w-4 h-4"}),"ASAP"]}),a.jsxs("button",{type:"button",className:`flex-1 px-2 py-2 rounded-lg border text-sm flex items-center justify-center gap-1.5 transition-colors ${t.scheduleType==="scheduled"?"bg-bambu-green border-bambu-green text-white":"bg-bambu-dark border-bambu-dark-tertiary text-bambu-gray hover:text-white"}`,onClick:()=>v("scheduled"),children:[a.jsx(sa,{className:"w-4 h-4"}),"Scheduled"]}),a.jsxs("button",{type:"button",className:`flex-1 px-2 py-2 rounded-lg border text-sm flex items-center justify-center gap-1.5 transition-colors ${t.scheduleType==="manual"?"bg-bambu-green border-bambu-green text-white":"bg-bambu-dark border-bambu-dark-tertiary text-bambu-gray hover:text-white"}`,onClick:()=>v("manual"),children:[a.jsx(bY,{className:"w-4 h-4"}),"Queue Only"]})]})]}),t.scheduleType==="scheduled"&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Date & Time"}),a.jsxs("div",{className:"flex gap-2",children:[a.jsxs("div",{className:"flex-1 relative",children:[a.jsx("input",{type:"text",className:`w-full px-3 py-2 pr-10 bg-bambu-dark border rounded-lg text-white focus:outline-none ${d?"border-bambu-dark-tertiary focus:border-bambu-green":"border-red-500"}`,value:s,onChange:k=>y(k.target.value),placeholder:Sge(n)}),a.jsx("button",{type:"button",onClick:T,className:"absolute right-2 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white",title:"Open calendar",children:a.jsx(sa,{className:"w-4 h-4"})})]}),a.jsx("div",{className:"w-32",children:a.jsx("input",{type:"text",className:`w-full px-3 py-2 bg-bambu-dark border rounded-lg text-white focus:outline-none ${h?"border-bambu-dark-tertiary focus:border-bambu-green":"border-red-500"}`,value:l,onChange:k=>_(k.target.value),placeholder:_ge(r)})})]}),a.jsx("input",{ref:p,type:"datetime-local",className:"sr-only",value:t.scheduledTime,onChange:N,tabIndex:-1}),(!d||!h)&&a.jsx("p",{className:"mt-1 text-xs text-red-400",children:"Please enter a valid date and time"})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"checkbox",id:"requirePrevious",checked:t.requirePreviousSuccess,onChange:k=>e({...t,requirePreviousSuccess:k.target.checked}),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),a.jsx("label",{htmlFor:"requirePrevious",className:"text-sm text-bambu-gray",children:"Only start if previous print succeeded"})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"checkbox",id:"autoOffAfter",checked:t.autoOffAfter,onChange:k=>e({...t,autoOffAfter:k.target.checked}),disabled:!i,className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green disabled:opacity-50"}),a.jsxs("label",{htmlFor:"autoOffAfter",className:`text-sm flex items-center gap-1 ${i?"text-bambu-gray":"text-bambu-gray/50"}`,children:[a.jsx(mu,{className:"w-3.5 h-3.5"}),"Power off printer when done"]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:t.scheduleType==="asap"?"Print will start as soon as the printer is idle.":t.scheduleType==="scheduled"?"Print will start at the scheduled time if the printer is idle. If busy, it will wait until the printer becomes available.":"Print will be staged but won't start automatically. Use the Start button to release it to the queue."})]})}const Ng={bed_levelling:!0,flow_cali:!1,vibration_cali:!0,layer_inspect:!1,timelapse:!1},B$e={scheduleType:"asap",scheduledTime:"",requirePreviousSuccess:!1,autoOffAfter:!1};function Yd({mode:t,archiveId:e,libraryFileId:n,archiveName:r,queueItem:i,onClose:s,onSuccess:o}){const{t:l}=Dt(),c=Jt(),{showToast:d}=ln(),{hasPermission:u}=Pr(),h=!!n&&!e,[f,p]=w.useState(()=>t==="edit-queue-item"&&i?.printer_id?[i.printer_id]:[]),[x,v]=w.useState(()=>t==="edit-queue-item"&&i?i.plate_id:null),[g,y]=w.useState(()=>t==="edit-queue-item"&&i?{bed_levelling:i.bed_levelling??Ng.bed_levelling,flow_cali:i.flow_cali??Ng.flow_cali,vibration_cali:i.vibration_cali??Ng.vibration_cali,layer_inspect:i.layer_inspect??Ng.layer_inspect,timelapse:i.timelapse??Ng.timelapse}:Ng),[_,N]=w.useState(()=>{if(t==="edit-queue-item"&&i){let Ee="asap";i.manual_start?Ee="manual":i.scheduled_time&&!J7(i.scheduled_time)&&(Ee="scheduled");let Ve="";if(i.scheduled_time&&!J7(i.scheduled_time)){const ot=er(i.scheduled_time)??new Date;Ve=u3(ot)}return{scheduleType:Ee,scheduledTime:Ve,requirePreviousSuccess:i.require_previous_success,autoOffAfter:i.auto_off_after}}return B$e}),[T,k]=w.useState(()=>{if(t==="edit-queue-item"&&i?.ams_mapping&&Array.isArray(i.ams_mapping)){const Ee={};return i.ams_mapping.forEach((Ve,ot)=>{Ve!==-1&&(Ee[ot+1]=Ve)}),Ee}return{}}),[M,C]=w.useState({}),[j,P]=w.useState(()=>t==="edit-queue-item"&&i?.target_model?"model":"printer"),[E,B]=w.useState(()=>t==="edit-queue-item"&&i?.target_model?i.target_model:null),[O,z]=w.useState(()=>t==="edit-queue-item"&&i?.target_location?i.target_location:null),[D,$]=w.useState(()=>{if(t==="edit-queue-item"&&i?.filament_overrides){const Ee={};for(const Ve of i.filament_overrides)Ee[Ve.slot_id]={type:Ve.type,color:Ve.color};return Ee}return{}}),[G]=w.useState(()=>t==="edit-queue-item"&&i?.printer_id?[i.printer_id]:[]),[U]=w.useState(()=>t==="edit-queue-item"&&i?i.plate_id:null),[W,Y]=w.useState(!1),[re,H]=w.useState({current:0,total:0}),[K,ee]=w.useState(new Set),Z=f.length,we=f.length>0?f[0]:null,{data:oe}=Je({queryKey:["settings"],queryFn:ne.getSettings}),J=rl(oe?.currency||"USD"),je=oe?.default_filament_cost??0,{data:de,isLoading:le}=Je({queryKey:["printers"],queryFn:ne.getPrinters}),{data:_e}=Je({queryKey:["archive",e],queryFn:()=>ne.getArchive(e),enabled:!!e&&!h}),{data:se}=Je({queryKey:["library-file",n],queryFn:()=>ne.getLibraryFile(n),enabled:h&&!!n}),ze=_e?.sliced_for_model||se?.sliced_for_model||null,{data:V,isError:X}=Je({queryKey:["archive-plates",e],queryFn:()=>ne.getArchivePlates(e),enabled:!!e&&!h,retry:!1}),{data:me}=Je({queryKey:["library-file-plates",n],queryFn:()=>ne.getLibraryFilePlates(n),enabled:h&&!!n}),Q=h?me:V,{data:ie,isError:ue}=Je({queryKey:["archive-filaments",e,x],queryFn:()=>ne.getArchiveFilamentRequirements(e,x??void 0),enabled:!!e&&!h&&(x!==null||!Q?.is_multi_plate),retry:!1}),{data:Le}=Je({queryKey:["library-file-filaments",n,x],queryFn:()=>ne.getLibraryFileFilamentRequirements(n,x??void 0),enabled:h&&!!n&&(x!==null||!Q?.is_multi_plate)}),Ce=!h&&(X||ue),ge=h?Le:ie,L=w.useMemo(()=>{if(!(x===null||!Q?.plates?.length))return Q.plates.find(Ee=>Ee.index===x)?.name||void 0},[Q,x]),{data:R}=Je({queryKey:["available-filaments",E,O],queryFn:()=>ne.getAvailableFilaments(E,O??void 0),enabled:j==="model"&&!!E}),{data:q}=Je({queryKey:["printer-status",we],queryFn:()=>ne.getPrinterStatus(we),enabled:!!we}),{amsMapping:ce}=yne(ge,q,T),pe=j$e(f,de,ge,T,M,C);w.useEffect(()=>{Q?.plates&&Q.plates.length>=1&&!x&&v(Q.plates[0].index)},[Q,x]),w.useEffect(()=>{if(t==="edit-queue-item")return;const Ee=de?.filter(Ve=>Ve.is_active)||[];Ee.length===1&&f.length===0&&p([Ee[0].id])},[t,de,f.length]),w.useEffect(()=>{t==="edit-queue-item"?(JSON.stringify(f.sort())!==JSON.stringify(G.sort())||x!==U)&&(k({}),C({}),ee(new Set)):(k({}),C({}),ee(new Set))},[t,f,x,G,U]);const[te,Be]=w.useState(E),[Ie,$e]=w.useState(x);w.useEffect(()=>{(E!==te||x!==Ie)&&(Be(E),$e(x),(t!=="edit-queue-item"||te!==null)&&$({}))},[E,x,te,Ie,t]),w.useEffect(()=>{if(!oe?.per_printer_mapping_expanded||f.length<=1)return;const Ee=f.filter(Ve=>{if(K.has(Ve))return!1;const ot=pe.printerResults.find(Ct=>Ct.printerId===Ve);return ot&&ot.status&&!ot.isLoading});Ee.length>0&&(ee(Ve=>{const ot=new Set(Ve);return Ee.forEach(Ct=>ot.add(Ct)),ot}),Ee.forEach(Ve=>{pe.autoConfigurePrinter(Ve)}))},[oe?.per_printer_mapping_expanded,f,K,pe]),w.useEffect(()=>{const Ee=Ve=>{Ve.key==="Escape"&&!W&&s()};return window.addEventListener("keydown",Ee),()=>window.removeEventListener("keydown",Ee)},[s,W]);const Re=Q?.is_multi_plate??!1,fe=Q?.plates??[],xe=st({mutationFn:Ee=>ne.addToQueue(Ee)}),Ne=st({mutationFn:Ee=>ne.updateQueueItem(i.id,Ee),onSuccess:()=>{c.invalidateQueries({queryKey:["queue"]}),d("Queue item updated"),o?.(),s()},onError:Ee=>{d(Ee.message||"Failed to update queue item","error")}}),ye=async Ee=>{if(Ee?.preventDefault(),j==="printer"&&f.length===0){d("Please select at least one printer","error");return}if(j==="model"&&!E){d("Please select a target printer model","error");return}Y(!0);const Ve=j==="model"?1:f.length;H({current:0,total:Ve});const ot={success:0,failed:0,errors:[]},Ct=Mt=>{if(f.length>1){const Ue=M[Mt];if(Ue&&!Ue.useDefault)return pe.getFinalMapping(Mt)}return ce},Lt=Object.keys(D).length>0?Object.entries(D).map(([Mt,{type:Ue,color:yt}])=>({slot_id:parseInt(Mt,10),type:Ue,color:yt})):void 0,Bt=Mt=>({printer_id:j==="printer"?Mt:null,target_model:j==="model"?E:null,target_location:j==="model"?O:null,filament_overrides:j==="model"?Lt:void 0,archive_id:h?void 0:e,library_file_id:h?n:void 0,require_previous_success:_.requirePreviousSuccess,auto_off_after:_.autoOffAfter,manual_start:_.scheduleType==="manual",ams_mapping:Mt?Ct(Mt):void 0,plate_id:x,scheduled_time:_.scheduleType==="scheduled"&&_.scheduledTime?new Date(_.scheduledTime).toISOString():void 0,...g});if(j==="model"){H({current:1,total:1});try{if(t==="reprint"){d("Model-based assignment only works with queue mode","error"),Y(!1);return}else if(t==="edit-queue-item"){const Mt={printer_id:null,target_model:E,target_location:O,filament_overrides:Lt||null,require_previous_success:_.requirePreviousSuccess,auto_off_after:_.autoOffAfter,manual_start:_.scheduleType==="manual",ams_mapping:void 0,plate_id:x,scheduled_time:_.scheduleType==="scheduled"&&_.scheduledTime?new Date(_.scheduledTime).toISOString():null,...g};await Ne.mutateAsync(Mt)}else await xe.mutateAsync(Bt(null));ot.success++}catch(Mt){ot.failed++,ot.errors.push(Mt.message)}}else for(let Mt=0;MtVt.id===Ue)?.name||`Printer ${Ue}`;ot.errors.push(`${xt}: ${yt.message}`)}}Y(!1),ot.failed===0?(t!=="reprint"&&(j==="model"?d(t==="edit-queue-item"?"Queue item updated":`Queued for any ${E}`):t==="edit-queue-item"?d("Queue item updated"):ot.success===1?d("Print queued for printer"):d(`Print queued for ${ot.success} printers`)),c.invalidateQueries({queryKey:["queue"]}),o?.(),s()):ot.success===0?d(`Failed: ${ot.errors[0]}`,"error"):(d(`${ot.success} succeeded, ${ot.failed} failed`,"error"),c.invalidateQueries({queryKey:["queue"]}))},ve=W||Ne.isPending,Ge=w.useMemo(()=>!(ve||j==="printer"&&f.length===0||j==="model"&&!E||j==="model"&&t==="reprint"||Re&&!x),[f.length,j,E,t,Re,x,ve]),nt=(()=>{const Ee=f.length;return t==="reprint"?{title:l(h?"queue.print":"queue.reprint"),icon:Sr,submitText:Ee>1?l("queue.printToPrinters",{count:Ee}):l("queue.print"),submitIcon:Sr,loadingText:re.total>1?l("queue.sendingProgress",{current:re.current,total:re.total}):l("queue.sending")}:t==="add-to-queue"?{title:l("queue.schedulePrint"),icon:sa,submitText:Ee>1?l("queue.queueToPrinters",{count:Ee}):l("queue.addToQueue"),submitIcon:sa,loadingText:re.total>1?l("queue.addingProgress",{current:re.current,total:re.total}):l("queue.adding")}:{title:l("queue.editQueueItem"),icon:Ya,submitText:l("common.save"),submitIcon:Ya,loadingText:re.total>1?l("queue.savingProgress",{current:re.current,total:re.total}):l("common.saving")}})(),De=nt.icon,Ke=nt.submitIcon,Oe=we&&(h||(Re?x!==null:!0));return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:W?void 0:s,children:a.jsx(wt,{className:"w-full max-w-lg max-h-[90vh] overflow-y-auto",onClick:Ee=>Ee.stopPropagation(),children:a.jsxs(Nt,{className:t==="reprint"?"":"p-0",children:[a.jsxs("div",{className:`flex items-center justify-between ${t==="reprint"?"mb-4":"p-4 border-b border-bambu-dark-tertiary"}`,children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(De,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:nt.title})]}),a.jsx(Me,{variant:"ghost",size:"sm",onClick:s,disabled:W,children:a.jsx(Rt,{className:"w-5 h-5"})})]}),a.jsxs("form",{onSubmit:ye,className:t==="reprint"?"":"p-4 space-y-4",children:[a.jsx("p",{className:`text-sm text-bambu-gray ${t==="reprint"?"mb-4":""}`,children:t==="reprint"?a.jsxs(a.Fragment,{children:["Send ",a.jsx("span",{className:"text-white",children:r})," to printer(s)"]}):a.jsxs(a.Fragment,{children:[a.jsx("span",{className:"block text-bambu-gray mb-1",children:"Print Job"}),a.jsx("span",{className:"text-white font-medium truncate block",children:r})]})}),a.jsx(F$e,{plates:fe,isMultiPlate:Re,selectedPlate:x,onSelect:v}),a.jsx(O$e,{printers:de||[],selectedPrinterIds:f,onMultiSelect:p,isLoading:le,allowMultiple:!0,showInactive:t==="edit-queue-item",printerMappingResults:pe.printerResults,filamentReqs:ge,onAutoConfigurePrinter:pe.autoConfigurePrinter,onUpdatePrinterConfig:pe.updatePrinterConfig,assignmentMode:t==="reprint"?"printer":j,onAssignmentModeChange:t!=="reprint"?P:void 0,targetModel:E,onTargetModelChange:t!=="reprint"?B:void 0,targetLocation:O,onTargetLocationChange:t!=="reprint"?z:void 0,slicedForModel:ze}),j==="model"&&E&&ge&&R&&R.length>0&&a.jsx(R$e,{filamentReqs:ge,availableFilaments:R,overrides:D,onChange:$}),ze&&j==="printer"&&f.length===1&&(()=>{const Ee=de?.find(Ve=>Ve.id===f[0]);return Ee&&Ee.model&&ze!==Ee.model?a.jsxs("div",{className:"p-3 mb-2 bg-yellow-500/10 border border-yellow-500/30 rounded-lg flex items-center gap-2",children:[a.jsx(An,{className:"w-4 h-4 text-yellow-400 flex-shrink-0"}),a.jsxs("span",{className:"text-sm text-yellow-400",children:["File was sliced for ",ze,", but printing on ",Ee.model]})]}):null})(),Ce&&a.jsxs("div",{className:"flex items-start gap-2 p-3 mb-2 bg-orange-500/10 border border-orange-500/30 rounded-lg text-sm",children:[a.jsx(Wa,{className:"w-4 h-4 text-orange-400 mt-0.5 flex-shrink-0"}),a.jsx("p",{className:"text-orange-400",children:"Archive data unavailable. The source file may have been deleted. Filament mapping is disabled."})]}),Oe&&!Ce&&f.length===1&&a.jsx(D$e,{printerId:we,filamentReqs:ge,manualMappings:T,onManualMappingChange:k,defaultExpanded:oe?.per_printer_mapping_expanded??!1,currencySymbol:J,defaultCostPerKg:je}),(t==="reprint"||Z>0||j==="model"&&E)&&a.jsx(z$e,{options:g,onChange:y}),t!=="reprint"&&a.jsx(U$e,{options:_,onChange:N,dateFormat:oe?.date_format||"system",timeFormat:oe?.time_format||"system",canControlPrinter:u("printers:control")}),Ne.isError&&a.jsx("div",{className:"mb-4 p-3 bg-red-500/20 border border-red-500/50 rounded-lg text-sm text-red-400",children:Ne.error?.message||"Failed to complete operation"}),a.jsxs("div",{className:`flex gap-3 ${t==="reprint"?"":"pt-2"}`,children:[a.jsx(Me,{type:"button",variant:"secondary",onClick:s,className:"flex-1",disabled:W,children:"Cancel"}),a.jsx(Me,{type:"submit",disabled:!Ge,className:"flex-1",children:ve?a.jsxs(a.Fragment,{children:[a.jsx(at,{className:"w-4 h-4 animate-spin"}),nt.loadingText]}):a.jsxs(a.Fragment,{children:[a.jsx(Ke,{className:"w-4 h-4"}),nt.submitText]})})]})]})]})})})}function H$e({onClose:t,initialFiles:e}){const{t:n}=Dt(),r=Jt(),{showToast:i}=ln(),s=w.useRef(null),[o,l]=w.useState(()=>e?.filter(k=>k.name.endsWith(".3mf")).map(k=>({file:k,status:"pending"}))||[]),[c,d]=w.useState(!1),[u,h]=w.useState(null);w.useEffect(()=>{const k=M=>{M.key==="Escape"&&t()};return window.addEventListener("keydown",k),()=>window.removeEventListener("keydown",k)},[t]);const f=st({mutationFn:k=>ne.uploadArchivesBulk(k),onSuccess:k=>{h(k),r.invalidateQueries({queryKey:["archives"]}),r.invalidateQueries({queryKey:["archiveStats"]}),l(M=>M.map(C=>{const j=k.results.find(E=>E.filename===C.file.name),P=k.errors.find(E=>E.filename===C.file.name);return j?{...C,status:"success",archiveId:j.id}:P?{...C,status:"error",error:P.error}:C})),k.failed===0?i(`${k.uploaded} file${k.uploaded!==1?"s":""} uploaded`):k.uploaded===0?i(`Failed to upload ${k.failed} file${k.failed!==1?"s":""}`,"error"):i(`${k.uploaded} uploaded, ${k.failed} failed`,"warning")},onError:()=>{l(k=>k.map(M=>({...M,status:"error",error:"Upload failed"}))),i("Upload failed","error")}}),p=w.useCallback(k=>{k.preventDefault(),d(!0)},[]),x=w.useCallback(k=>{k.preventDefault(),d(!1)},[]),v=w.useCallback(k=>{k.preventDefault(),d(!1);const M=Array.from(k.dataTransfer.files).filter(C=>C.name.endsWith(".3mf"));M.length>0&&l(C=>[...C,...M.map(j=>({file:j,status:"pending"}))])},[]),g=w.useCallback(k=>{const M=Array.from(k.target.files||[]).filter(C=>C.name.endsWith(".3mf"));M.length>0&&l(C=>[...C,...M.map(j=>({file:j,status:"pending"}))]),s.current&&(s.current.value="")},[]),y=w.useCallback(k=>{l(M=>M.filter((C,j)=>j!==k))},[]),_=()=>{if(o.length===0)return;const k=o.filter(M=>M.status==="pending");k.length!==0&&(l(M=>M.map(C=>C.status==="pending"?{...C,status:"uploading"}:C)),f.mutate(k.map(M=>M.file)))},N=o.filter(k=>k.status==="pending").length,T=f.isPending;return a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:a.jsx(wt,{className:"w-full max-w-2xl max-h-[90vh] flex flex-col",children:a.jsxs(Nt,{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(Rt,{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:p,onDragLeave:x,onDrop:v,children:[a.jsx(La,{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(Me,{variant:"secondary",onClick:()=>s.current?.click(),disabled:T,children:n("uploadModal.browseFiles")}),a.jsx("input",{ref:s,type:"file",accept:".3mf",multiple:!0,className:"hidden",onChange:g})]})}),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((k,M)=>a.jsxs("div",{className:"flex items-center gap-3 p-3 bg-bambu-dark rounded-lg",children:[a.jsx(HC,{className:"w-5 h-5 text-bambu-gray flex-shrink-0"}),a.jsx("span",{className:"flex-1 text-white text-sm truncate",children:k.file.name}),a.jsxs("span",{className:"text-xs text-bambu-gray",children:[(k.file.size/(1024*1024)).toFixed(1)," MB"]}),k.status==="pending"&&a.jsx("button",{onClick:()=>y(M),className:"text-bambu-gray hover:text-red-400 transition-colors",disabled:T,children:a.jsx(Rt,{className:"w-4 h-4"})}),k.status==="uploading"&&a.jsx(at,{className:"w-4 h-4 text-bambu-green animate-spin"}),k.status==="success"&&a.jsx(br,{className:"w-4 h-4 text-bambu-green"}),k.status==="error"&&a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-xs text-red-400",children:k.error}),a.jsx(Wa,{className:"w-4 h-4 text-red-400"})]})]},`${k.file.name}-${M}`))})}),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(Me,{variant:"secondary",onClick:t,className:"flex-1",children:n(u?"common.close":"common.cancel")}),!u&&a.jsx(Me,{onClick:_,disabled:N===0||T,className:"flex-1",children:T?a.jsxs(a.Fragment,{children:[a.jsx(at,{className:"w-4 h-4 animate-spin"}),n("uploadModal.uploading")]}):a.jsxs(a.Fragment,{children:[a.jsx(La,{className:"w-4 h-4"}),n("uploadModal.upload")," ",N>0&&`(${N})`]})})]})]})})})}const $$e=["adhesionFailure","spaghettiDetached","layerShift","cloggedNozzle","filamentRunout","warping","stringing","underExtrusion","powerFailure","userCancelled","other"],V$e=["completed","failed","aborted","printing"];function vne({archive:t,onClose:e,existingTags:n=[]}){const{t:r}=Dt();w.useEffect(()=>{const de=le=>{le.key==="Escape"&&e()};return window.addEventListener("keydown",de),()=>window.removeEventListener("keydown",de)},[e]);const i=Jt(),[s,o]=w.useState(t.print_name||""),[l,c]=w.useState(t.printer_id),[d,u]=w.useState(t.project_id??null),[h,f]=w.useState(t.notes||""),[p,x]=w.useState(t.tags||""),[v,g]=w.useState(t.failure_reason||""),[y,_]=w.useState(t.status),[N,T]=w.useState(t.quantity??1),[k,M]=w.useState(t.photos||[]),[C,j]=w.useState(t.external_url||""),[P,E]=w.useState(!1),[B,O]=w.useState(!1),z=w.useRef(null),D=w.useRef(null),$=w.useRef(null),{data:G}=Je({queryKey:["printers"],queryFn:ne.getPrinters}),{data:U}=Je({queryKey:["projects"],queryFn:()=>ne.getProjects()}),{data:W}=Je({queryKey:["tags"],queryFn:ne.getTags,enabled:n.length===0}),Y=n.length>0?n:W?.map(de=>de.name)||[],re=p.split(",").map(de=>de.trim()).filter(Boolean),H=p.includes(",")?p.substring(p.lastIndexOf(",")+1).trim().toLowerCase():p.trim().toLowerCase(),K=Y.filter(de=>!re.includes(de)&&(H===""||de.toLowerCase().includes(H))),ee=de=>{let le;if(H&&!Y.includes(H)?le=p.includes(",")?p.substring(0,p.lastIndexOf(",")).split(",").map(_e=>_e.trim()).filter(Boolean):[]:le=re,!le.includes(de)){const _e=[...le,de].join(", ");x(_e)}$.current!==null&&clearTimeout($.current),z.current?.focus()},Z=de=>{const le=re.filter(_e=>_e!==de).join(", ");x(le)},we=st({mutationFn:de=>ne.updateArchive(t.id,de),onSuccess:()=>{i.invalidateQueries({queryKey:["archives"]}),i.invalidateQueries({queryKey:["projects"]}),e()}}),oe=async de=>{const le=de.target.files?.[0];if(le){E(!0);try{const _e=await ne.uploadArchivePhoto(t.id,le);M(_e.photos),i.invalidateQueries({queryKey:["archives"]})}catch(_e){console.error("Failed to upload photo:",_e)}finally{E(!1),D.current&&(D.current.value="")}}},J=async de=>{try{const le=await ne.deleteArchivePhoto(t.id,de);M(le.photos||[]),i.invalidateQueries({queryKey:["archives"]})}catch(le){console.error("Failed to delete photo:",le)}},je=de=>{de.preventDefault();const le={print_name:s||void 0,printer_id:l,project_id:d,notes:h||void 0,tags:p||void 0,quantity:N,external_url:C||null};y!==t.status&&(le.status=y),y==="failed"||y==="aborted"?le.failure_reason=v||void 0:(t.status==="failed"||t.status==="aborted")&&(le.failure_reason=null),we.mutate(le)};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:de=>de.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(Rt,{className:"w-5 h-5"})})]}),a.jsxs("form",{onSubmit:je,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:de=>o(de.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:de=>c(de.target.value?Number(de.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")}),G?.map(de=>a.jsx("option",{value:de.id,children:de.name},de.id))]})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[a.jsx(xs,{className:"w-4 h-4 inline mr-1"}),r("editArchive.project")]}),a.jsxs("select",{value:d??"",onChange:de=>u(de.target.value?Number(de.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")}),U?.map(de=>a.jsx("option",{value:de.id,children:de.name},de.id))]})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[a.jsx(Ume,{className:"w-4 h-4 inline mr-1"}),r("editArchive.itemsPrinted")]}),a.jsx("input",{type:"number",min:1,value:N,onChange:de=>T(Math.max(1,parseInt(de.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:h,onChange:de=>f(de.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(Vb,{className:"w-4 h-4 inline mr-1"}),r("editArchive.externalLink")]}),a.jsx("input",{type:"url",value:C,onChange:de=>j(de.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(de=>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(Vh,{className:"w-3 h-3"}),de,a.jsx("button",{type:"button",onClick:()=>Z(de),className:"ml-0.5 text-bambu-gray hover:text-white",children:a.jsx(Rt,{className:"w-3 h-3"})})]},de))}),a.jsxs("div",{className:"relative",children:[a.jsx("input",{ref:z,type:"text",value:p,onChange:de=>x(de.target.value),onFocus:()=>{$.current!==null&&clearTimeout($.current),O(!0)},onBlur:()=>{$.current=window.setTimeout(()=>O(!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")}),B&&K.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:[H?r("editArchive.matchingTags",{query:H}):r("editArchive.existingTags")," ",r("editArchive.clickToAdd")]}),a.jsx("div",{className:"p-2 flex flex-wrap gap-1.5",children:K.map(de=>a.jsx("button",{type:"button",onClick:()=>ee(de),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:de},de))})]})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("editArchive.status")}),a.jsx("select",{value:y,onChange:de=>{_(de.target.value),de.target.value==="completed"&&g("")},className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:V$e.map(de=>a.jsx("option",{value:de,children:r(`editArchive.statuses.${de}`)},de))})]}),(y==="failed"||y==="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:de=>g(de.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")}),$$e.map(de=>a.jsx("option",{value:r(`editArchive.failureReasons.${de}`),children:r(`editArchive.failureReasons.${de}`)},de))]})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[a.jsx(cb,{className:"w-4 h-4 inline mr-1"}),r("editArchive.photos")]}),a.jsxs("div",{className:"flex flex-wrap gap-2 mb-2",children:[k.map(de=>a.jsxs("div",{className:"relative group",children:[a.jsx("img",{src:ne.getArchivePhotoUrl(t.id,de),alt:r("editArchive.printResult"),className:"w-20 h-20 object-cover rounded-lg border border-bambu-dark-tertiary"}),a.jsx("button",{type:"button",onClick:()=>J(de),className:"absolute -top-1 -right-1 p-1 bg-red-500 rounded-full opacity-0 group-hover:opacity-100 transition-opacity",children:a.jsx(Xt,{className:"w-3 h-3 text-white"})})]},de)),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:D,type:"file",accept:"image/jpeg,image/png,image/webp",onChange:oe,className:"hidden",disabled:P}),P?a.jsx(at,{className:"w-6 h-6 text-bambu-gray animate-spin"}):a.jsx(Xn,{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(Me,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:r("common.cancel")}),a.jsxs(Me,{type:"submit",disabled:we.isPending,className:"flex-1",children:[a.jsx(bs,{className:"w-4 h-4"}),we.isPending?r("common.saving"):r("common.save")]})]})]})]})})}function wne({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,h]=w.useState(!1),[f,p]=w.useState({});w.useEffect(()=>{const g=N=>{i.current&&!i.current.contains(N.target)&&r()},y=N=>{N.key==="Escape"&&r()},_=()=>{r()};return document.addEventListener("mousedown",g),document.addEventListener("keydown",y),document.addEventListener("scroll",_,!0),()=>{document.removeEventListener("mousedown",g),document.removeEventListener("keydown",y),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 g=i.current.getBoundingClientRect(),y=window.innerWidth,_=window.innerHeight,N=8;let T=t,k=e;t+g.width>y-N&&(T=Math.max(N,y-g.width-N)),T_-N&&(k=Math.max(N,_-g.height-N)),kM),d({x:T,y:k,visible:!0})}},[t,e]);const x=(g,y)=>{l.current&&(clearTimeout(l.current),l.current=null);const _=y.getBoundingClientRect(),N=window.innerHeight,T=300,C=N-_.top-8T;p(j=>({...j,[g]:C?"bottom":"top"})),o(g)},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((g,y)=>{if(g.divider)return a.jsx("div",{className:"my-1 border-t border-bambu-dark-tertiary"},y);const _=g.submenu&&g.submenu.length>0;return a.jsxs("div",{className:"relative",onMouseEnter:N=>_&&x(y,N.currentTarget),onMouseLeave:()=>_&&v(),children:[a.jsxs("button",{onMouseEnter:N=>_&&x(y,N.currentTarget.parentElement),onClick:()=>{_?o(s===y?null:y):g.disabled||(g.onClick(),r())},disabled:g.disabled,title:g.title,className:`w-full flex items-center gap-2 px-3 py-2 text-sm text-left transition-colors ${g.disabled?"text-bambu-gray cursor-not-allowed":g.danger?"text-red-400 hover:bg-red-400/10":"text-white hover:bg-bambu-dark-tertiary"} ${_&&s===y?"bg-bambu-dark-tertiary":""}`,children:[g.icon&&a.jsx("span",{className:"w-4 h-4 flex-shrink-0 flex items-center justify-center",children:g.icon}),a.jsx("span",{className:"flex-1",children:g.label}),_&&a.jsx(yi,{className:"w-4 h-4 text-bambu-gray"})]}),_&&s===y&&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"} ${f[y]==="bottom"?"bottom-0":"top-0"}`,onMouseEnter:()=>{l.current&&(clearTimeout(l.current),l.current=null)},onMouseLeave:()=>v(),children:g.submenu.map((N,T)=>a.jsxs("button",{onClick:()=>{N.disabled||(N.onClick(),r())},disabled:N.disabled,className:`w-full flex items-center gap-2 px-3 py-2 text-sm text-left transition-colors ${N.disabled?"text-bambu-gray cursor-not-allowed":N.danger?"text-red-400 hover:bg-red-400/10":"text-white hover:bg-bambu-dark-tertiary"}`,children:[N.icon&&a.jsx("span",{className:"w-4 h-4 flex-shrink-0 flex items-center justify-center",children:N.icon}),N.label]},T))})]},y)})})}function q$e({selectedIds:t,existingTags:e,onClose:n}){const r=Jt(),{showToast:i}=ln(),[s,o]=w.useState(""),[l,c]=w.useState(new Set),[d,u]=w.useState("add");w.useEffect(()=>{const v=g=>{g.key==="Escape"&&n()};return window.addEventListener("keydown",v),()=>window.removeEventListener("keydown",v)},[n]);const h=st({mutationFn:async()=>{const v=Array.from(l);let g=0;for(const y of t)try{const _=await ne.getArchive(y),N=_.tags?_.tags.split(",").map(k=>k.trim()).filter(Boolean):[];let T;d==="add"?T=[...new Set([...N,...v])]:T=N.filter(k=>!l.has(k)),await ne.updateArchive(y,{tags:T.join(", ")}),g++}catch(_){throw console.error(`Failed to update archive ${y}:`,_),new Error(`Failed on archive ${y}: ${_ instanceof Error?_.message:"Unknown error"}`)}return{count:g,mode:d,tags:v}},onSuccess:({count:v,mode:g,tags:y})=>{r.invalidateQueries({queryKey:["archives"]}),i(`${g==="add"?"Added":"Removed"} ${y.length} tag${y.length!==1?"s":""} ${g==="add"?"to":"from"} ${v} archive${v!==1?"s":""}`),n()},onError:v=>{i(v.message||"Failed to update tags","error")}}),f=v=>{c(g=>{const y=new Set(g);return y.has(v)?y.delete(v):y.add(v),y})},p=()=>{s.trim()&&!l.has(s.trim())&&(c(v=>new Set([...v,s.trim()])),o(""))},x=v=>{v.key==="Enter"&&(v.preventDefault(),p())};return a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:a.jsx(wt,{className:"w-full max-w-md",children:a.jsxs(Nt,{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(Vh,{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(Rt,{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(Me,{size:"sm",variant:d==="add"?"primary":"secondary",onClick:()=>u("add"),children:"Add Tags"}),a.jsx(Me,{size:"sm",variant:d==="remove"?"primary":"secondary",onClick:()=>u("remove"),children:"Remove Tags"})]}),d==="add"&&a.jsxs("div",{className:"flex gap-2",children:[a.jsx("input",{type:"text",placeholder:"Enter new tag...",className:"flex-1 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",value:s,onChange:v=>o(v.target.value),onKeyDown:x}),a.jsx(Me,{size:"sm",variant:"secondary",onClick:p,disabled:!s.trim(),children:a.jsx(Xn,{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:()=>f(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:()=>f(v),className:"hover:opacity-70",children:a.jsx(Rt,{className:"w-3 h-3"})})]},v))})]})]}),a.jsxs("div",{className:"flex gap-3 p-4 border-t border-bambu-dark-tertiary",children:[a.jsx(Me,{variant:"secondary",onClick:n,className:"flex-1",children:"Cancel"}),a.jsx(Me,{onClick:()=>h.mutate(),disabled:l.size===0||h.isPending,className:"flex-1",children:h.isPending?a.jsxs(a.Fragment,{children:[a.jsx(at,{className:"w-4 h-4 animate-spin"}),"Processing..."]}):a.jsxs(a.Fragment,{children:[a.jsx(Vh,{className:"w-4 h-4"}),d==="add"?"Add Tags":"Remove Tags"]})})]})]})})})}function G$e({selectedIds:t,onClose:e}){const n=Jt(),{showToast:r}=ln(),{data:i,isLoading:s}=Je({queryKey:["projects"],queryFn:()=>ne.getProjects()});w.useEffect(()=>{const u=h=>{h.key==="Escape"&&e()};return window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)},[e]);const o=()=>{n.invalidateQueries({queryKey:["archives"]}),n.invalidateQueries({queryKey:["projects"]}),n.invalidateQueries({queryKey:["project"]}),n.invalidateQueries({queryKey:["project-archives"]})},l=st({mutationFn:async u=>(await ne.addArchivesToProject(u,t),u),onSuccess:u=>{const h=i?.find(f=>f.id===u);o(),r(`Added ${t.length} archive${t.length!==1?"s":""} to "${h?.name}"`),e()},onError:()=>{r("Failed to assign project","error")}}),c=st({mutationFn:async()=>{for(const u of t)await ne.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(wt,{className:"w-full max-w-md max-h-[80vh] flex flex-col",children:a.jsxs(Nt,{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(xs,{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(Rt,{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(at,{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(bi,{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(at,{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(xs,{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(at,{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(Me,{variant:"secondary",onClick:e,className:"flex-1",disabled:d,children:"Cancel"})})]})})})}function W$e(t,e){return new Date(t,e+1,0).getDate()}function K$e(t,e){return new Date(t,e,1).getDay()}const Y$e=["January","February","March","April","May","June","July","August","September","October","November","December"],X$e=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];function Q$e({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,h]=w.useState(null),f=w.useMemo(()=>{const k=new Map;return t.forEach(M=>{const C=er(M.completed_at||M.created_at)||new Date,j=`${C.getFullYear()}-${String(C.getMonth()+1).padStart(2,"0")}-${String(C.getDate()).padStart(2,"0")}`,P=k.get(j)||[];P.push(M),k.set(j,P)}),k},[t]),p=W$e(o,i),x=K$e(o,i),v=()=>{i===0?(s(11),l(o-1)):s(i-1)},g=()=>{i===11?(s(0),l(o+1)):s(i+1)},y=()=>{s(r.getMonth()),l(r.getFullYear())},_=[];for(let k=0;k{k!==c&&h(null),d(k)};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(Kl,{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:[Y$e[i]," ",o]}),a.jsx("button",{onClick:y,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:g,className:"p-2 hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:a.jsx(yi,{className:"w-5 h-5 text-bambu-gray"})})]}),a.jsx("div",{className:"grid grid-cols-7 gap-1 mb-1",children:X$e.map(k=>a.jsx("div",{className:"text-center text-xs text-bambu-gray py-2",children:k},k))}),a.jsx("div",{className:"grid grid-cols-7 gap-1",children:_.map((k,M)=>{if(k===null)return a.jsx("div",{className:"aspect-square"},`empty-${M}`);const C=`${o}-${String(i+1).padStart(2,"0")}-${String(k).padStart(2,"0")}`,j=f.get(C)||[],P=j.length>0,E=k===r.getDate()&&i===r.getMonth()&&o===r.getFullYear(),B=C===c,O=j.filter(D=>D.status==="completed").length,z=j.filter(D=>D.status==="failed").length;return a.jsxs("button",{onClick:()=>T(B?null:C),className:`aspect-square rounded-lg p-1 flex flex-col items-center justify-center transition-colors relative ${B?"bg-bambu-green text-white":E?"bg-bambu-green/20 text-white ring-2 ring-bambu-green":P?"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 ${E&&!B?"text-bambu-green":""}`,children:k}),P&&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 ${z>0&&O===0?"bg-red-400":z>0?"bg-yellow-400":"bg-green-400"}`}),a.jsx("span",{className:"text-xs font-medium",children:j.length})]})]},k)})}),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(k=>{const M=er(k.completed_at||k.created_at)||new Date;return M.getMonth()===i&&M.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(k=>{const M=er(k.completed_at||k.created_at)||new Date;return M.getMonth()===i&&M.getFullYear()===o&&k.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(k=>{const M=er(k.completed_at||k.created_at)||new Date;return M.getMonth()===i&&M.getFullYear()===o&&k.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"})}),N.length>0?a.jsx("div",{className:"calendar-scroll space-y-2 max-h-96 overflow-y-auto",children:N.map(k=>{const M=k.id===u||k.id===n;return a.jsxs("button",{onClick:()=>{h(k.id),e?.(k)},className:`w-full flex items-center gap-3 p-2 rounded-lg transition-colors text-left ${M?"":"hover:bg-bambu-dark-tertiary"}`,style:M?{outline:"4px solid #facc15",outlineOffset:"2px"}:void 0,children:[k.thumbnail_path?a.jsx("img",{src:ne.getArchiveThumbnail(k.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:k.print_name||k.filename}),a.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[a.jsx("span",{className:k.status==="failed"?"text-red-400":"text-green-400",children:k.status==="failed"?"Failed":"Completed"}),k.filament_color&&a.jsx("div",{className:"flex gap-0.5",children:k.filament_color.split(",").map((C,j)=>a.jsx("div",{className:"w-3 h-3 rounded-full border border-white/20",style:{backgroundColor:C}},j))})]})]})]},k.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 Sne({archiveId:t,archiveName:e,onClose:n}){const r=ne.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(Rt,{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(Me,{onClick:i,className:"w-full",children:[a.jsx(ha,{className:"w-4 h-4"}),"Download QR Code"]})]})]})})}function _ne({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 p=x=>{x.key==="Escape"&&r(),x.key==="ArrowLeft"&&o(v=>Math.max(0,v-1)),x.key==="ArrowRight"&&o(v=>Math.min(n.length-1,v+1))};return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[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=ne.getArchivePhotoUrl(t,d),h=()=>{const p=document.createElement("a");p.href=u,p.download=`${e}_photo_${s+1}.jpg`,p.click()},f=()=>{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:p=>p.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(Me,{variant:"secondary",size:"sm",onClick:h,children:[a.jsx(ha,{className:"w-4 h-4"}),"Download"]}),i&&a.jsx(Me,{variant:"secondary",size:"sm",onClick:f,className:"text-red-400 hover:text-red-300",children:a.jsx(Xt,{className:"w-4 h-4"})}),a.jsx("button",{onClick:r,className:"p-2 text-bambu-gray hover:text-white transition-colors",children:a.jsx(Rt,{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(p=>p-1),className:"absolute left-4 z-10 p-3 bg-black/50 hover:bg-black/70 rounded-full transition-colors",children:a.jsx(Kl,{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(p=>p+1),className:"absolute right-4 z-10 p-3 bg-black/50 hover:bg-black/70 rounded-full transition-colors",children:a.jsx(yi,{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((p,x)=>a.jsx("button",{onClick:()=>o(x),className:`w-16 h-16 rounded-lg overflow-hidden border-2 transition-colors ${x===s?"border-bambu-green":"border-transparent hover:border-bambu-gray"}`,children:a.jsx("img",{src:ne.getArchivePhotoUrl(t,p),alt:`Thumbnail ${x+1}`,className:"w-full h-full object-cover"})},p))})]}),l&&a.jsx(xn,{title:"Delete Photo",message:"Delete this photo? This cannot be undone.",confirmText:"Delete",variant:"danger",onConfirm:()=>{i?.(d),c(!1)},onCancel:()=>c(!1)})]})}function Qi(t){this.content=t}Qi.prototype={constructor:Qi,find:function(t){for(var e=0;e>1}};Qi.from=function(t){if(t instanceof Qi)return t;var e=[];if(t)for(var n in t)e.push(n,t[n]);return new Qi(e)};function Nne(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=Nne(i.content,s.content,n+1);if(o!=null)return o}n+=i.nodeSize}}function Cne(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 Pt(r,i)}cutByIndex(e,n){return e==n?Pt.empty:e==0&&n==this.content.length?this:new Pt(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 Pt(i,s)}addToStart(e){return new Pt([e].concat(this.content),this.size+e.nodeSize)}addToEnd(e){return new Pt(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?w_(n+1,s):w_(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 Pt.empty;if(!Array.isArray(n))throw new RangeError("Invalid input for Fragment.fromJSON");return new Pt(n.map(e.nodeFromJSON))}static fromArray(e){if(!e.length)return Pt.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}};Gr.none=[];class HN extends Error{}class qt{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=Ane(this.content,e+this.openStart,n);return r&&new qt(r,this.openStart,this.openEnd)}removeBetween(e,n){return new qt(kne(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 qt.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 qt(Pt.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 qt(e,r,i)}}qt.empty=new qt(Pt.empty,0,0);function kne(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(kne(s.content,e-i-1,n-i-1)))}function Ane(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=Ane(o.content,e-s-1,n,o);return l&&t.replaceChild(i,o.copy(l))}function Z$e(t,e,n){if(n.openStart>t.depth)throw new HN("Inserted content deeper than insertion position");if(t.depth-n.openStart!=e.depth-n.openEnd)throw new HN("Inconsistent open depths");return Tne(t,e,n,0)}function Tne(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 Yy(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&&(wf(t.nodeAfter,r),s++));for(let l=s;li&&vR(t,e,i+1),o=r.depth>i&&vR(n,r,i+1),l=[];return Yy(null,t,i,l),s&&o&&e.index(i)==n.index(i)?(Mne(s,o),wf(Sf(s,Pne(t,e,n,r,i+1)),l)):(s&&wf(Sf(s,$N(t,e,i+1)),l),Yy(e,n,i,l),o&&wf(Sf(o,$N(n,r,i+1)),l)),Yy(r,null,i,l),new Pt(l)}function $N(t,e,n){let r=[];if(Yy(null,t,n,r),t.depth>n){let i=vR(t,e,n+1);wf(Sf(i,$N(t,e,n+1)),r)}return Yy(e,null,n,r),new Pt(r)}function J$e(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(Pt.from(i));return{start:i.resolveNoCache(t.openStart+n),end:i.resolveNoCache(i.content.size-t.openEnd-n)}}class qv{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 VN(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 qv(n,r,s)}static resolveCached(e,n){let r=d9.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()+")"),Ene(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=Pt.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=Pt.fromJSON(e,n.content),s=e.nodeType(n.type).create(n.attrs,i,r);return s.type.checkAttrs(s.attrs),s}};Uh.prototype.text=void 0;class qN extends Uh{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):Ene(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 qN(this.type,this.attrs,this.text,e)}withText(e){return e==this.text?this:new qN(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 Ene(t,e){for(let n=t.length-1;n>=0;n--)e=t[n].type.name+"("+e+")";return e}class Kf{constructor(e){this.validEnd=e,this.next=[],this.wrapCache=[]}static parse(e,n){let r=new rVe(e,n);if(r.next==null)return Kf.empty;let i=jne(r);r.next&&r.err("Unexpected trailing text");let s=dVe(cVe(i));return uVe(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(` `)}}Kf.empty=new Kf(!0);class rVe{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 jne(t){let e=[];do e.push(aVe(t));while(t.eat("|"));return e.length==1?e[0]:{type:"choice",exprs:e}}function aVe(t){let e=[];do e.push(iVe(t));while(t.next&&t.next!=")"&&t.next!="|");return e.length==1?e[0]:{type:"seq",exprs:e}}function iVe(t){let e=lVe(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=sVe(t,e);else break;return e}function u9(t){/\D/.test(t.next)&&t.err("Expected number, got '"+t.next+"'");let e=Number(t.next);return t.pos++,e}function sVe(t,e){let n=u9(t),r=n;return t.eat(",")&&(t.next!="}"?r=u9(t):r=-1),t.eat("}")||t.err("Unclosed braced range"),{type:"range",min:n,max:r,expr:e}}function oVe(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 lVe(t){if(t.eat("(")){let e=jne(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=oVe(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 cVe(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 Kf(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:Fne(this.attrs,e)}create(e=null,n,r){if(this.isText)throw new Error("NodeType.create can't construct text nodes");return new Uh(this,this.computeAttrs(e),Pt.from(n),Gr.setFrom(r))}createChecked(e=null,n,r){return n=Pt.from(n),this.checkContent(n),new Uh(this,this.computeAttrs(e),n,Gr.setFrom(r))}createAndFill(e=null,n,r){if(e=this.computeAttrs(e),n=Pt.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(Pt.empty,!0);return s?new Uh(this,e,n.append(s),Gr.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 Ine(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 hVe(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 mVe{constructor(e,n,r){this.hasDefault=Object.prototype.hasOwnProperty.call(r,"default"),this.default=r.default,this.validate=typeof r.validate=="string"?hVe(e,n,r.validate):r.validate}get isRequired(){return!this.hasDefault}}class oA{constructor(e,n,r,i){this.name=e,this.rank=n,this.schema=r,this.spec=i,this.attrs=One(e,i.attrs),this.excluded=null;let s=Rne(this.attrs);this.instance=s?new Gr(this,s):null}create(e=null){return!e&&this.instance?this.instance:new Gr(this,Fne(this.attrs,e))}static compile(e,n){let r=Object.create(null),i=0;return e.forEach((s,o)=>r[s]=new oA(s,i++,n,o)),r}removeFromSet(e){for(var n=0;n-1}}class zne{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=Qi.from(e.nodes),n.marks=Qi.from(e.marks||{}),this.nodes=m9.compile(this.spec.nodes,this),this.marks=oA.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]=Kf.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?f9(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==""?[]:f9(this,o.split(" "))}this.nodeFromJSON=i=>Uh.fromJSON(this,i),this.markFromJSON=i=>Gr.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 m9){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 qN(r,r.defaultAttrs,e,Gr.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 f9(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 fVe(t){return t.tag!=null}function pVe(t){return t.style!=null}let Xy=class SR{constructor(e,n){this.schema=e,this.rules=n,this.tags=[],this.styles=[];let r=this.matchedStyles=[];n.forEach(i=>{if(fVe(i))this.tags.push(i);else if(pVe(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 g9(this,n,!1);return r.addAll(e,Gr.none,n.from,n.to),r.finish()}parseSlice(e,n={}){let r=new g9(this,n,!0);return r.addAll(e,Gr.none,n.from,n.to),qt.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=b9(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=b9(o)),o.node||o.ignore||o.mark||(o.node=i)})}return n}static fromSchema(e){return e.cached.domParser||(e.cached.domParser=new SR(e,SR.schemaRules(e)))}};const Une={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},gVe={head:!0,noscript:!0,object:!0,script:!0,style:!0,title:!0},Bne={ol:!0,ul:!0},Gv=1,_R=2,Qy=4;function p9(t,e,n){return e!=null?(e?Gv:0)|(e==="full"?_R:0):t&&t.whitespace=="pre"?Gv|_R:n&~Qy}class S_{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=Gr.none,this.match=s||(o&Qy?null:e.contentMatch)}findWrapping(e){if(!this.match){if(!this.type)return[];let n=this.type.contentMatch.fillBefore(Pt.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&Gv)){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=Pt.from(this.content);return!e&&this.match&&(n=n.append(this.match.fillBefore(Pt.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&&!Une.hasOwnProperty(e.parentNode.nodeName.toLowerCase())}}class g9{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=p9(null,n.preserveWhitespace,0)|(r?Qy:0);i?s=new S_(i.type,i.attrs,Gr.none,!0,n.topMatch||i.type.contentMatch,o):r?s=new S_(null,null,Gr.none,!0,null,o):s=new S_(e.schema.topNodeType,null,Gr.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&_R?"full":this.localPreserveWS||(i.options&Gv)>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!c.clearMark(d)):n=n.concat(this.parser.schema.marks[c.mark].create(c.attrs)),c.consuming===!1)l=c;else break}}return n}addElementByRule(e,n,r,i){let s,o;if(n.node)if(o=this.parser.schema.nodes[n.node],o.isLeaf)this.insertNode(o.create(n.attrs),r,e.nodeName=="BR")||this.leafFallback(e,r);else{let c=this.enter(o,n.attrs||null,r,n.preserveWhitespace);c&&(s=!0,r=c)}else{let c=this.parser.schema.marks[n.mark];r=r.concat(c.create(n.attrs))}let l=this.top;if(o&&o.isLeaf)this.findInside(e);else if(i)this.addElement(e,r,i);else if(n.getContent)this.findInside(e),n.getContent(e,this.parser.schema).forEach(c=>this.insertNode(c,r,!1));else{let c=e;typeof n.contentElement=="string"?c=e.querySelector(n.contentElement):typeof n.contentElement=="function"?c=n.contentElement(e):n.contentElement&&(c=n.contentElement),this.findAround(e,c,!0),this.addAll(c,r),this.findAround(e,c,!1)}s&&this.sync(l)&&this.open--}addAll(e,n,r,i){let s=r||0;for(let o=r?e.childNodes[r]:e.firstChild,l=i==null?null:e.childNodes[i];o!=l;o=o.nextSibling,++s)this.findAtPoint(e,s),this.addDOM(o,n);this.findAtPoint(e,s)}findPlace(e,n,r){let i,s;for(let o=this.open,l=0;o>=0;o--){let c=this.nodes[o],d=c.findWrapping(e);if(d&&(!i||i.length>d.length+l)&&(i=d,s=c,!d.length))break;if(c.solid){if(r)break;l+=2}}if(!i)return null;this.sync(s);for(let o=0;o(o.type?o.type.allowsMarkType(d.type):x9(d.type,e))?(c=d.addToSet(c),!1):!0),this.nodes.push(new S_(e,n,c,i,null,l)),this.open++,r}closeExtra(e=!1){let n=this.nodes.length-1;if(n>this.open){for(;n>this.open;n--)this.nodes[n-1].content.push(this.nodes[n].finish(e));this.nodes.length=this.open+1}}finish(){return this.open=0,this.closeExtra(this.isOpen),this.nodes[0].finish(!!(this.isOpen||this.options.topOpen))}sync(e){for(let n=this.open;n>=0;n--){if(this.nodes[n]==e)return this.open=n,!0;this.localPreserveWS&&(this.nodes[n].options|=Gv)}return!1}get currentPos(){this.closeExtra();let e=0;for(let n=this.open;n>=0;n--){let r=this.nodes[n].content;for(let i=r.length-1;i>=0;i--)e+=r[i].nodeSize;n&&e++}return e}findAtPoint(e,n){if(this.find)for(let r=0;r-1)return e.split(/\s*\|\s*/).some(this.matchesContext,this);let n=e.split("/"),r=this.options.context,i=!this.isOpen&&(!r||r.parent.type==this.nodes[0].type),s=-(r?r.depth+1:0)+(i?0:1),o=(l,c)=>{for(;l>=0;l--){let d=n[l];if(d==""){if(l==n.length-1||l==0)continue;for(;c>=s;c--)if(o(l-1,c))return!0;return!1}else{let u=c>0||c==0&&i?this.nodes[c].type:r&&c>=s?r.node(c-s).type:null;if(!u||u.name!=d&&!u.isInGroup(d))return!1;c--}}return!0};return o(n.length-1,this.open)}textblockFromContext(){let e=this.options.context;if(e)for(let n=e.depth;n>=0;n--){let r=e.node(n).contentMatchAt(e.indexAfter(n)).defaultType;if(r&&r.isTextblock&&r.defaultAttrs)return r}for(let n in this.parser.schema.nodes){let r=this.parser.schema.nodes[n];if(r.isTextblock&&r.defaultAttrs)return r}}}function bVe(t){for(let e=t.firstChild,n=null;e;e=e.nextSibling){let r=e.nodeType==1?e.nodeName.toLowerCase():null;r&&Bne.hasOwnProperty(r)&&n?(n.appendChild(e),e=n):r=="li"?n=e:r&&(n=null)}}function xVe(t,e){return(t.matches||t.msMatchesSelector||t.webkitMatchesSelector||t.mozMatchesSelector).call(t,e)}function b9(t){let e={};for(let n in t)e[n]=t[n];return e}function x9(t,e){let n=e.schema.nodes;for(let r in n){let i=n[r];if(!i.allowsMarkType(t))continue;let s=[],o=l=>{s.push(l);for(let c=0;c{if(s.length||o.marks.length){let l=0,c=0;for(;l=0;i--){let s=this.serializeMark(e.marks[i],e.isInline,n);s&&((s.contentDOM||s.dom).appendChild(r),r=s.dom)}return r}serializeMark(e,n,r={}){let i=this.marks[e.type.name];return i&&i1(X2(r),i(e,n),null,e.attrs)}static renderSpec(e,n,r=null,i){return i1(e,n,r,i)}static fromSchema(e){return e.cached.domSerializer||(e.cached.domSerializer=new ip(this.nodesFromSchema(e),this.marksFromSchema(e)))}static nodesFromSchema(e){let n=y9(e.nodes);return n.text||(n.text=r=>r.text),n}static marksFromSchema(e){return y9(e.marks)}}function y9(t){let e={};for(let n in t){let r=t[n].spec.toDOM;r&&(e[n]=r)}return e}function X2(t){return t.document||window.document}const v9=new WeakMap;function yVe(t){let e=v9.get(t);return e===void 0&&v9.set(t,e=vVe(t)),e}function vVe(t){let e=null;function n(r){if(r&&typeof r=="object")if(Array.isArray(r))if(typeof r[0]=="string")e||(e=[]),e.push(r);else for(let i=0;i-1)throw new RangeError("Using an array from an attribute object as a DOM spec. This may be an attempted cross site scripting attack.");let o=i.indexOf(" ");o>0&&(n=i.slice(0,o),i=i.slice(o+1));let l,c=n?t.createElementNS(n,i):t.createElement(i),d=e[1],u=1;if(d&&typeof d=="object"&&d.nodeType==null&&!Array.isArray(d)){u=2;for(let h in d)if(d[h]!=null){let f=h.indexOf(" ");f>0?c.setAttributeNS(h.slice(0,f),h.slice(f+1),d[h]):h=="style"&&c.style?c.style.cssText=d[h]:c.setAttribute(h,d[h])}}for(let h=u;hu)throw new RangeError("Content hole must be the only child of its parent node");return{dom:c,contentDOM:c}}else{let{dom:p,contentDOM:x}=i1(t,f,n,r);if(c.appendChild(p),x){if(l)throw new RangeError("Multiple content holes");l=x}}}return{dom:c,contentDOM:l}}const Hne=65535,$ne=Math.pow(2,16);function wVe(t,e){return t+e*$ne}function w9(t){return t&Hne}function SVe(t){return(t-(t&Hne))/$ne}const Vne=1,qne=2,s1=4,Gne=8;class NR{constructor(e,n,r){this.pos=e,this.delInfo=n,this.recover=r}get deleted(){return(this.delInfo&Gne)>0}get deletedBefore(){return(this.delInfo&(Vne|s1))>0}get deletedAfter(){return(this.delInfo&(qne|s1))>0}get deletedAcross(){return(this.delInfo&s1)>0}}class To{constructor(e,n=!1){if(this.ranges=e,this.inverted=n,!e.length&&To.empty)return To.empty}recover(e){let n=0,r=w9(e);if(!this.inverted)for(let i=0;ie)break;let d=this.ranges[l+s],u=this.ranges[l+o],h=c+d;if(e<=h){let f=d?e==c?-1:e==h?1:n:n,p=c+i+(f<0?0:u);if(r)return p;let x=e==(n<0?c:h)?null:wVe(l/3,e-c),v=e==c?qne:e==h?Vne:s1;return(n<0?e!=c:e!=h)&&(v|=Gne),new NR(p,v,x)}i+=u-d}return r?e+i:new NR(e+i,0,null)}touches(e,n){let r=0,i=w9(n),s=this.inverted?2:1,o=this.inverted?1:2;for(let l=0;le)break;let d=this.ranges[l+s],u=c+d;if(e<=u&&l==i*3)return!0;r+=this.ranges[l+o]-d}return!1}forEach(e){let n=this.inverted?2:1,r=this.inverted?1:2;for(let i=0,s=0;i=0;n--){let i=e.getMirror(n);this.appendMap(e._maps[n].invert(),i!=null&&i>n?r-i-1:void 0)}}invert(){let e=new Wv;return e.appendMappingInverted(this),e}map(e,n=1){if(this.mirror)return this._map(e,n,!0);for(let r=this.from;rs&&c!o.isAtom||!l.type.allowsMarkType(this.mark.type)?o:o.mark(this.mark.addToSet(o.marks)),i),n.openStart,n.openEnd);return si.fromReplace(e,this.from,this.to,s)}invert(){return new Gl(this.from,this.to,this.mark)}map(e){let n=e.mapResult(this.from,1),r=e.mapResult(this.to,-1);return n.deleted&&r.deleted||n.pos>=r.pos?null:new Nh(n.pos,r.pos,this.mark)}merge(e){return e instanceof Nh&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new Nh(Math.min(this.from,e.from),Math.max(this.to,e.to),this.mark):null}toJSON(){return{stepType:"addMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(e,n){if(typeof n.from!="number"||typeof n.to!="number")throw new RangeError("Invalid input for AddMarkStep.fromJSON");return new Nh(n.from,n.to,e.markFromJSON(n.mark))}}_s.jsonID("addMark",Nh);class Gl extends _s{constructor(e,n,r){super(),this.from=e,this.to=n,this.mark=r}apply(e){let n=e.slice(this.from,this.to),r=new qt(x4(n.content,i=>i.mark(this.mark.removeFromSet(i.marks)),e),n.openStart,n.openEnd);return si.fromReplace(e,this.from,this.to,r)}invert(){return new Nh(this.from,this.to,this.mark)}map(e){let n=e.mapResult(this.from,1),r=e.mapResult(this.to,-1);return n.deleted&&r.deleted||n.pos>=r.pos?null:new Gl(n.pos,r.pos,this.mark)}merge(e){return e instanceof Gl&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new Gl(Math.min(this.from,e.from),Math.max(this.to,e.to),this.mark):null}toJSON(){return{stepType:"removeMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(e,n){if(typeof n.from!="number"||typeof n.to!="number")throw new RangeError("Invalid input for RemoveMarkStep.fromJSON");return new Gl(n.from,n.to,e.markFromJSON(n.mark))}}_s.jsonID("removeMark",Gl);class Ch extends _s{constructor(e,n){super(),this.pos=e,this.mark=n}apply(e){let n=e.nodeAt(this.pos);if(!n)return si.fail("No node at mark step's position");let r=n.type.create(n.attrs,null,this.mark.addToSet(n.marks));return si.fromReplace(e,this.pos,this.pos+1,new qt(Pt.from(r),0,n.isLeaf?0:1))}invert(e){let n=e.nodeAt(this.pos);if(n){let r=this.mark.addToSet(n.marks);if(r.length==n.marks.length){for(let i=0;ir.pos?null:new Ii(n.pos,r.pos,i,s,this.slice,this.insert,this.structure)}toJSON(){let e={stepType:"replaceAround",from:this.from,to:this.to,gapFrom:this.gapFrom,gapTo:this.gapTo,insert:this.insert};return this.slice.size&&(e.slice=this.slice.toJSON()),this.structure&&(e.structure=!0),e}static fromJSON(e,n){if(typeof n.from!="number"||typeof n.to!="number"||typeof n.gapFrom!="number"||typeof n.gapTo!="number"||typeof n.insert!="number")throw new RangeError("Invalid input for ReplaceAroundStep.fromJSON");return new Ii(n.from,n.to,n.gapFrom,n.gapTo,qt.fromJSON(e,n.slice),n.insert,!!n.structure)}}_s.jsonID("replaceAround",Ii);function CR(t,e,n){let r=t.resolve(e),i=n-e,s=r.depth;for(;i>0&&s>0&&r.indexAfter(s)==r.node(s).childCount;)s--,i--;if(i>0){let o=r.node(s).maybeChild(r.indexAfter(s));for(;i>0;){if(!o||o.isLeaf)return!0;o=o.firstChild,i--}}return!1}function _Ve(t,e,n,r){let i=[],s=[],o,l;t.doc.nodesBetween(e,n,(c,d,u)=>{if(!c.isInline)return;let h=c.marks;if(!r.isInSet(h)&&u.type.allowsMarkType(r.type)){let f=Math.max(d,e),p=Math.min(d+c.nodeSize,n),x=r.addToSet(h);for(let v=0;vt.step(c)),s.forEach(c=>t.step(c))}function NVe(t,e,n,r){let i=[],s=0;t.doc.nodesBetween(e,n,(o,l)=>{if(!o.isInline)return;s++;let c=null;if(r instanceof oA){let d=o.marks,u;for(;u=r.isInSet(d);)(c||(c=[])).push(u),d=u.removeFromSet(d)}else r?r.isInSet(o.marks)&&(c=[r]):c=o.marks;if(c&&c.length){let d=Math.min(l+o.nodeSize,n);for(let u=0;ut.step(new Gl(o.from,o.to,o.style)))}function y4(t,e,n,r=n.contentMatch,i=!0){let s=t.doc.nodeAt(e),o=[],l=e+1;for(let c=0;c=0;c--)t.step(o[c])}function CVe(t,e,n){return(e==0||t.canReplace(e,t.childCount))&&(n==t.childCount||t.canReplace(0,n))}function ox(t){let n=t.parent.content.cutByIndex(t.startIndex,t.endIndex);for(let r=t.depth,i=0,s=0;;--r){let o=t.$from.node(r),l=t.$from.index(r)+i,c=t.$to.indexAfter(r)-s;if(rn;x--)v||r.index(x)>0?(v=!0,u=Pt.from(r.node(x).copy(u)),h++):c--;let f=Pt.empty,p=0;for(let x=s,v=!1;x>n;x--)v||i.after(x+1)=0;o--){if(r.size){let l=n[o].type.contentMatch.matchFragment(r);if(!l||!l.validEnd)throw new RangeError("Wrapper type given to Transform.wrap does not form valid content of its parent wrapper")}r=Pt.from(n[o].type.create(n[o].attrs,r))}let i=e.start,s=e.end;t.step(new Ii(i,s,i,s,new qt(r,0,0),n.length,!0))}function PVe(t,e,n,r,i){if(!r.isTextblock)throw new RangeError("Type given to setBlockType should be a textblock");let s=t.steps.length;t.doc.nodesBetween(e,n,(o,l)=>{let c=typeof i=="function"?i(o):i;if(o.isTextblock&&!o.hasMarkup(r,c)&&EVe(t.doc,t.mapping.slice(s).map(l),r)){let d=null;if(r.schema.linebreakReplacement){let p=r.whitespace=="pre",x=!!r.contentMatch.matchType(r.schema.linebreakReplacement);p&&!x?d=!1:!p&&x&&(d=!0)}d===!1&&Kne(t,o,l,s),y4(t,t.mapping.slice(s).map(l,1),r,void 0,d===null);let u=t.mapping.slice(s),h=u.map(l,1),f=u.map(l+o.nodeSize,1);return t.step(new Ii(h,f,h+1,f-1,new qt(Pt.from(r.create(c,null,o.marks)),0,0),1,!0)),d===!0&&Wne(t,o,l,s),!1}})}function Wne(t,e,n,r){e.forEach((i,s)=>{if(i.isText){let o,l=/\r?\n|\r/g;for(;o=l.exec(i.text);){let c=t.mapping.slice(r).map(n+1+s+o.index);t.replaceWith(c,c+1,e.type.schema.linebreakReplacement.create())}}})}function Kne(t,e,n,r){e.forEach((i,s)=>{if(i.type==i.type.schema.linebreakReplacement){let o=t.mapping.slice(r).map(n+1+s);t.replaceWith(o,o+1,e.type.schema.text(` diff --git a/static/index.html b/static/index.html index 63a042446..987a81330 100644 --- a/static/index.html +++ b/static/index.html @@ -23,7 +23,7 @@ - +