0&&(i[c]=u,s=!0)}s&&(e.data.morphAttributes=i,e.data.morphTargetsRelative=this.morphTargetsRelative);const o=this.groups;o.length>0&&(e.data.groups=JSON.parse(JSON.stringify(o)));const l=this.boundingSphere;return l!==null&&(e.data.boundingSphere=l.toJSON()),e}clone(){return new this.constructor().copy(this)}copy(e){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;const n={};this.name=e.name;const r=e.index;r!==null&&this.setIndex(r.clone());const i=e.attributes;for(const d in i){const u=i[d];this.setAttribute(d,u.clone(n))}const s=e.morphAttributes;for(const d in s){const u=[],h=s[d];for(let f=0,p=h.length;f0){const i=n[r[0]];if(i!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let s=0,o=i.length;s(e.far-e.near)**2))&&(u8.copy(s).invert(),Mm.copy(e.ray).applyMatrix4(u8),!(r.boundingBox!==null&&Mm.intersectsBox(r.boundingBox)===!1)&&this._computeIntersections(e,n,Mm)))}_computeIntersections(e,n,r){let i;const s=this.geometry,o=this.material,l=s.index,c=s.attributes.position,d=s.attributes.uv,u=s.attributes.uv1,h=s.attributes.normal,f=s.groups,p=s.drawRange;if(l!==null)if(Array.isArray(o))for(let x=0,v=f.length;xn.far?null:{distance:d,point:xS.clone(),object:t}}function yS(t,e,n,r,i,s,o,l,c,d){t.getVertexPosition(l,fS),t.getVertexPosition(c,pS),t.getVertexPosition(d,gS);const u=Kbe(t,e,n,r,fS,pS,gS,m8);if(u){const h=new pt;ay.getBarycoord(m8,fS,pS,gS,h),i&&(u.uv=ay.getInterpolatedAttribute(i,l,c,d,h,new In)),s&&(u.uv1=ay.getInterpolatedAttribute(s,l,c,d,h,new In)),o&&(u.normal=ay.getInterpolatedAttribute(o,l,c,d,h,new pt),u.normal.dot(r.direction)>0&&u.normal.multiplyScalar(-1));const f={a:l,b:c,c:d,normal:new pt,materialIndex:0};ay.getNormal(fS,pS,gS,f.normal),u.face=f,u.barycoord=h}return u}let KF=class oY extends _l{constructor(e=1,n=1,r=1,i=1,s=1,o=1){super(),this.type="BoxGeometry",this.parameters={width:e,height:n,depth:r,widthSegments:i,heightSegments:s,depthSegments:o};const l=this;i=Math.floor(i),s=Math.floor(s),o=Math.floor(o);const c=[],d=[],u=[],h=[];let f=0,p=0;x("z","y","x",-1,-1,r,n,e,o,s,0),x("z","y","x",1,-1,r,n,-e,o,s,1),x("x","z","y",1,1,e,r,n,i,o,2),x("x","z","y",1,-1,e,r,-n,i,o,3),x("x","y","z",1,-1,e,n,r,i,s,4),x("x","y","z",-1,-1,e,n,-r,i,s,5),this.setIndex(c),this.setAttribute("position",new Eo(d,3)),this.setAttribute("normal",new Eo(u,3)),this.setAttribute("uv",new Eo(h,2));function x(v,g,y,_,N,A,k,P,C,E,M){const j=A/C,B=k/E,L=A/2,U=k/2,D=P/2,$=C+1,G=E+1;let z=0,W=0;const K=new pt;for(let te=0;te0?1:-1,u.push(K.x,K.y,K.z),h.push(Y/C),h.push(1-te/E),z+=1}}for(let te=0;te0||pe.vt_tray.length>0)&&r==="expanded"&&(()=>{const bt=Ft.filter(vt=>vt.tray.length>1),Ot=Ft.filter(vt=>vt.tray.length===1),vn=t.nozzle_count===2||pe?.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:[bt.length>0&&a.jsx("div",{className:"grid grid-cols-2 gap-3",children:bt.map(vt=>{const Un=ot[String(vt.id)],Zr=vt.id>=128?vt.id-128:vt.id,Zn=Un!==void 0?Un:Zr,dr=Zn===1,li=Zn===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:nh(vt.id,vt.tray.length)}),vn&&(dr||li)&&a.jsx(s9,{side:dr?"L":"R"})]}),(vt.humidity!=null||vt.temp!=null)&&a.jsxs("div",{className:"flex items-center gap-1.5 max-[550px]:flex-col max-[550px]:items-start",children:[vt.humidity!=null&&a.jsx(l9,{humidity:vt.humidity,goodThreshold:s?.humidityGood,fairThreshold:s?.humidityFair,onClick:()=>le({amsId:vt.id,amsLabel:nh(vt.id,vt.tray.length),mode:"humidity"}),compact:!0}),vt.temp!=null&&a.jsx(c9,{temp:vt.temp,goodThreshold:s?.tempGood,fairThreshold:s?.tempFair,onClick:()=>le({amsId:vt.id,amsLabel:nh(vt.id,vt.tray.length),mode:"temperature"}),compact:!0})]})]}),a.jsx("div",{className:"grid grid-cols-4 gap-1.5",children:[0,1,2,3].map(rn=>{const Pn=vt.tray[rn]||vt.tray.find($n=>$n.id===rn),Ci=Pn?.tray_type&&Pn.remain>=0,Bs=!Pn?.tray_type,zo=vt.id*4+rn,Uo=Be===zo,zi=Pn?.tray_info_idx?qe?.[Pn.tray_info_idx]:null,Dr=ke?.[zo],Hs=Pn?.tray_uuid?.toUpperCase(),Ca=Hs?c?.[Hs]:void 0,Jr=Kj(Ca),is=u?.(t.id,vt.id,rn),ur=(()=>{const $n=is?.spool;return $n&&$n.label_weight>0&&$n.weight_used!=null?Math.round(Math.max(0,$n.label_weight-$n.weight_used)/$n.label_weight*100):null})(),Ui=Jr??ur??(Ci?Pn.remain:null),jl=Jr!==null?"spoolman":ur!==null?"inventory":Ci?"ams":void 0,Cr=Pn?.tray_type?{vendor:Xj(Pn)?"Bambu Lab":"Generic",profile:zi?.name||Dr?.preset_name||Pn.tray_sub_brands||Pn.tray_type,colorName:$j(Pn.tray_id_name)||Vj(Pn.tray_color),colorHex:Pn.tray_color||null,kFactor:qj(Pn.k),fillLevel:Ui,trayUuid:Pn.tray_uuid||null,tagUid:Pn.tag_uid||null,fillSource:jl}:null,Xt=gt?.amsId===vt.id&>?.slotId===rn,ya=a.jsxs("div",{className:`bg-bambu-dark-tertiary rounded p-1 text-center ${Bs?"opacity-50":""} ${Uo?"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:Pn?.tray_color?`#${Pn.tray_color}`:Pn?.tray_type?"#333":"transparent",borderColor:Bs?"#666":"rgba(255,255,255,0.1)",borderStyle:Bs?"dashed":"solid"}}),a.jsx("div",{className:"text-[9px] text-white font-bold truncate",children:Pn?.tray_type||"—"}),a.jsx("div",{className:"mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden",children:Ui!==null&&Ui>=0&&Pn&&a.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${Ui}%`,backgroundColor:Wj(Ui)}})})]});return a.jsxs("div",{className:"relative group",children:[Xt&&a.jsx("div",{className:"absolute inset-0 bg-bambu-dark-tertiary/80 rounded flex items-center justify-center z-20",children:a.jsx(Sr,{className:"w-4 h-4 text-bambu-green animate-spin"})}),pe?.state!=="RUNNING"&&a.jsx("button",{onClick:$n=>{$n.stopPropagation(),Qn(vr?.amsId===vt.id&&vr?.slotId===rn?null:{amsId:vt.id,slotId:rn})},className:"absolute -top-1 -right-1 w-4 h-4 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity z-10 hover:bg-bambu-dark-tertiary",title:g("printers.slotOptions"),children:a.jsx(Mh,{className:"w-2.5 h-2.5 text-bambu-gray"})}),pe?.state!=="RUNNING"&&vr?.amsId===vt.id&&vr?.slotId===rn&&a.jsx("div",{className:"absolute top-full left-0 mt-1 z-50 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl py-1 min-w-[120px]",children:a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-xs flex items-center gap-2 ${A("printers:ams_rfid")?"text-white hover:bg-bambu-dark-tertiary":"text-bambu-gray/50 cursor-not-allowed"}`,onClick:$n=>{$n.stopPropagation(),A("printers:ams_rfid")&&(Pt.mutate({amsId:vt.id,slotId:rn}),Qn(null))},disabled:Xt||!A("printers:ams_rfid"),title:A("printers:ams_rfid")?void 0:g("printers.permission.noAmsRfid"),children:[a.jsx(Sr,{className:`w-3 h-3 ${Xt?"animate-spin":""}`}),g("printers.rfid.reread")]})}),Cr?a.jsx(Bj,{data:Cr,spoolman:{enabled:o,hasUnlinkedSpools:l,linkedSpoolId:Cr.trayUuid?c?.[Cr.trayUuid.toUpperCase()]?.id:void 0,spoolmanUrl:d,onLinkSpool:o&&Cr.trayUuid?$n=>{V({tagUid:Cr.tagUid||"",trayUuid:$n,printerId:t.id,amsId:vt.id,trayId:rn})}:void 0},inventory:o?void 0:(()=>{const $n=u?.(t.id,vt.id,rn);return{assignedSpool:$n?.spool?{id:$n.spool.id,material:$n.spool.material,brand:$n.spool.brand,color_name:$n.spool.color_name,remainingWeightGrams:Math.max(0,Math.round($n.spool.label_weight-$n.spool.weight_used))}:null,onAssignSpool:Cr.vendor!=="Bambu Lab"?()=>fe({printerId:t.id,amsId:vt.id,trayId:rn,trayInfo:{type:Cr.profile,color:Cr.colorHex||"",location:`${nh(vt.id,vt.tray.length)} Slot ${rn+1}`}}):void 0,onUnassignSpool:$n&&Cr.vendor!=="Bambu Lab"?()=>h?.(t.id,vt.id,rn):void 0}})(),configureSlot:{enabled:A("printers:control"),onConfigure:()=>re({amsId:vt.id,trayId:rn,trayCount:vt.tray.length,trayType:Pn?.tray_type||void 0,trayColor:Pn?.tray_color||void 0,traySubBrands:Pn?.tray_sub_brands||void 0,trayInfoIdx:Pn?.tray_info_idx||void 0,extruderId:Un,caliIdx:Pn?.cali_idx,savedPresetId:Dr?.preset_id})},children:ya}):a.jsx(Hj,{configureSlot:{enabled:A("printers:control"),onConfigure:()=>re({amsId:vt.id,trayId:rn,trayCount:vt.tray.length,extruderId:Un})},children:ya})]},rn)})})]},vt.id)})}),(Ot.length>0||pe.vt_tray.length>0)&&a.jsxs("div",{className:"grid grid-cols-4 gap-3",children:[Ot.map(vt=>{const Un=ot[String(vt.id)],Zr=vt.id>=128?vt.id-128:vt.id,Zn=Un!==void 0?Un:Zr,dr=Zn===1,li=Zn===0,rn=vt.tray[0],Pn=rn?.tray_type&&rn.remain>=0,Ci=!rn?.tray_type,Bs=BN(vt.id,rn?.id??0,!1),zo=Be===Bs,Uo=rn?.tray_info_idx?qe?.[rn.tray_info_idx]:null,zi=ke?.[Bs],Dr=rn?.tray_uuid?.toUpperCase(),Hs=Dr?c?.[Dr]:void 0,Ca=Kj(Hs),Jr=rn?.id??0,is=u?.(t.id,vt.id,Jr),ur=(()=>{const kr=is?.spool;return kr&&kr.label_weight>0&&kr.weight_used!=null?Math.round(Math.max(0,kr.label_weight-kr.weight_used)/kr.label_weight*100):null})(),Ui=Ca??ur??(Pn?rn.remain:null),jl=Ca!==null?"spoolman":ur!==null?"inventory":Pn?"ams":void 0,Cr=rn?.tray_type?{vendor:Xj(rn)?"Bambu Lab":"Generic",profile:Uo?.name||zi?.preset_name||rn.tray_sub_brands||rn.tray_type,colorName:$j(rn.tray_id_name)||Vj(rn.tray_color),colorHex:rn.tray_color||null,kFactor:qj(rn.k),fillLevel:Ui,trayUuid:rn.tray_uuid||null,tagUid:rn.tag_uid||null,fillSource:jl}:null,Xt=rn?.id??0,ya=gt?.amsId===vt.id&>?.slotId===Xt,$n=a.jsxs("div",{className:`bg-bambu-dark-tertiary rounded p-1 text-center ${Ci?"opacity-50":""} ${zo?"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:rn?.tray_color?`#${rn.tray_color}`:rn?.tray_type?"#333":"transparent",borderColor:Ci?"#666":"rgba(255,255,255,0.1)",borderStyle:Ci?"dashed":"solid"}}),a.jsx("div",{className:"text-[9px] text-white font-bold truncate",children:rn?.tray_type||"—"}),a.jsx("div",{className:"mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden",children:Ui!==null&&Ui>=0&&a.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${Ui}%`,backgroundColor:Wj(Ui)}})})]});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:nh(vt.id,vt.tray.length)}),vn&&(dr||li)&&a.jsx(s9,{side:dr?"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:[ya&&a.jsx("div",{className:"absolute inset-0 bg-bambu-dark-tertiary/80 rounded flex items-center justify-center z-20",children:a.jsx(Sr,{className:"w-4 h-4 text-bambu-green animate-spin"})}),pe?.state!=="RUNNING"&&a.jsx("button",{onClick:kr=>{kr.stopPropagation(),Qn(vr?.amsId===vt.id&&vr?.slotId===Xt?null:{amsId:vt.id,slotId:Xt})},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(Mh,{className:"w-2.5 h-2.5 text-bambu-gray"})}),pe?.state!=="RUNNING"&&vr?.amsId===vt.id&&vr?.slotId===Xt&&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 ${A("printers:ams_rfid")?"text-white hover:bg-bambu-dark-tertiary":"text-bambu-gray/50 cursor-not-allowed"}`,onClick:kr=>{kr.stopPropagation(),A("printers:ams_rfid")&&(Pt.mutate({amsId:vt.id,slotId:Xt}),Qn(null))},disabled:ya||!A("printers:ams_rfid"),title:A("printers:ams_rfid")?void 0:g("printers.permission.noAmsRfid"),children:[a.jsx(Sr,{className:`w-3 h-3 ${ya?"animate-spin":""}`}),g("printers.rfid.reread")]})}),Cr?a.jsx(Bj,{data:Cr,spoolman:{enabled:o,hasUnlinkedSpools:l,linkedSpoolId:Cr.trayUuid?c?.[Cr.trayUuid.toUpperCase()]?.id:void 0,spoolmanUrl:d,onLinkSpool:o&&Cr.trayUuid?kr=>{V({tagUid:Cr.tagUid||"",trayUuid:kr,printerId:t.id,amsId:vt.id,trayId:Xt})}:void 0},inventory:o?void 0:(()=>{const kr=u?.(t.id,vt.id,Xt);return{assignedSpool:kr?.spool?{id:kr.spool.id,material:kr.spool.material,brand:kr.spool.brand,color_name:kr.spool.color_name,remainingWeightGrams:Math.max(0,Math.round(kr.spool.label_weight-kr.spool.weight_used))}:null,onAssignSpool:Cr.vendor!=="Bambu Lab"?()=>fe({printerId:t.id,amsId:vt.id,trayId:Xt,trayInfo:{type:Cr.profile,color:Cr.colorHex||"",location:nh(vt.id,vt.tray.length)}}):void 0,onUnassignSpool:kr&&Cr.vendor!=="Bambu Lab"?()=>h?.(t.id,vt.id,Xt):void 0}})(),configureSlot:{enabled:A("printers:control"),onConfigure:()=>re({amsId:vt.id,trayId:Xt,trayCount:vt.tray.length,trayType:rn?.tray_type||void 0,trayColor:rn?.tray_color||void 0,traySubBrands:rn?.tray_sub_brands||void 0,trayInfoIdx:rn?.tray_info_idx||void 0,extruderId:Un,caliIdx:rn?.cali_idx,savedPresetId:zi?.preset_id})},children:$n}):a.jsx(Hj,{configureSlot:{enabled:A("printers:control"),onConfigure:()=>re({amsId:vt.id,trayId:Xt,trayCount:vt.tray.length,extruderId:Un})},children:$n})]}),(vt.humidity!=null||vt.temp!=null)&&a.jsxs("div",{className:"flex flex-col justify-center gap-1 shrink-0 max-[550px]:w-full",children:[vt.temp!=null&&a.jsx(c9,{temp:vt.temp,goodThreshold:s?.tempGood,fairThreshold:s?.tempFair,onClick:()=>le({amsId:vt.id,amsLabel:nh(vt.id,vt.tray.length),mode:"temperature"}),compact:!0}),vt.humidity!=null&&a.jsx(l9,{humidity:vt.humidity,goodThreshold:s?.humidityGood,fairThreshold:s?.humidityFair,onClick:()=>le({amsId:vt.id,amsLabel:nh(vt.id,vt.tray.length),mode:"humidity"}),compact:!0})]})]})]},vt.id)}),pe.vt_tray.length>0&&a.jsxs("div",{className:`p-2.5 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary/30 ${pe.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 ${pe.vt_tray.length>1?"grid-cols-2":"grid-cols-1"} gap-1.5`,children:[...pe.vt_tray].sort((vt,Un)=>(vt.id??254)-(Un.id??254)).map(vt=>{const Un=vt.id??254,Zr=vn&&Be===254?Un===254&&pe.active_extruder===1||Un===255&&pe.active_extruder===0:Be===Un,Zn=Un-254,dr=vn?g(Un===254?"printers.extL":"printers.extR"):"",li=vt.tray_info_idx?qe?.[vt.tray_info_idx]:null,rn=ke?.[1020+Zn],Pn=vt.tray_uuid?.toUpperCase(),Ci=Pn?c?.[Pn]:void 0,Bs=Kj(Ci),zo=u?.(t.id,255,Zn),Uo=(()=>{const ur=zo?.spool;return ur&&ur.label_weight>0&&ur.weight_used!=null?Math.round(Math.max(0,ur.label_weight-ur.weight_used)/ur.label_weight*100):null})(),zi=vt.tray_type&&vt.remain>=0,Dr=Bs??Uo??(zi?vt.remain:null),Hs=Bs!==null?"spoolman":Uo!==null?"inventory":zi?"ams":void 0,Ca={vendor:Xj(vt)?"Bambu Lab":"Generic",profile:li?.name||rn?.preset_name||vt.tray_sub_brands||vt.tray_type||"Unknown",colorName:$j(vt.tray_id_name)||Vj(vt.tray_color),colorHex:vt.tray_color||null,kFactor:qj(vt.k),fillLevel:Dr,trayUuid:vt.tray_uuid||null,tagUid:vt.tag_uid||null,fillSource:Hs},Jr=!vt.tray_type,is=a.jsxs("div",{className:`bg-bambu-dark-tertiary rounded p-1 text-center ${Jr?"opacity-50":""} ${Zr?"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:vt.tray_color?`#${vt.tray_color}`:vt.tray_type?"#333":"transparent",borderColor:Jr?"#666":"rgba(255,255,255,0.1)",borderStyle:Jr?"dashed":"solid"}}),a.jsx("div",{className:`text-[9px] font-bold truncate ${Jr?"text-white/40":"text-white"}`,children:vt.tray_type||"—"}),a.jsx("div",{className:"mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden",children:Dr!==null&&Dr>=0&&!Jr&&a.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${Dr}%`,backgroundColor:Wj(Dr)}})}),dr&&a.jsx("div",{className:"text-[7px] text-white/40 mt-0.5 truncate",children:dr})]});return a.jsx("div",{className:"relative group",children:Jr?a.jsx(Hj,{configureSlot:{enabled:A("printers:control"),onConfigure:()=>re({amsId:255,trayId:Zn,trayCount:1,extruderId:vn?Un===254?1:0:void 0})},children:is}):a.jsx(Bj,{data:Ca,spoolman:{enabled:o,hasUnlinkedSpools:l,linkedSpoolId:Ca.trayUuid?c?.[Ca.trayUuid.toUpperCase()]?.id:void 0,spoolmanUrl:d,onLinkSpool:o&&Ca.trayUuid?ur=>{V({tagUid:Ca.tagUid||"",trayUuid:ur,printerId:t.id,amsId:255,trayId:Zn})}:void 0},inventory:o?void 0:(()=>{const ur=u?.(t.id,255,Zn);return{assignedSpool:ur?.spool?{id:ur.spool.id,material:ur.spool.material,brand:ur.spool.brand,color_name:ur.spool.color_name,remainingWeightGrams:Math.max(0,Math.round(ur.spool.label_weight-ur.spool.weight_used))}:null,onAssignSpool:()=>fe({printerId:t.id,amsId:255,trayId:Zn,trayInfo:{type:Ca.profile,color:Ca.colorHex||"",location:dr||g("printers.external")}}),onUnassignSpool:ur?()=>h?.(t.id,255,Zn):void 0}})(),configureSlot:{enabled:A("printers:control"),onConfigure:()=>re({amsId:255,trayId:Zn,trayCount:1,trayType:vt.tray_type||void 0,trayColor:vt.tray_color||void 0,traySubBrands:vt.tray_sub_brands||void 0,trayInfoIdx:vt.tray_info_idx||void 0,extruderId:vn?Un===254?1:0:void 0,caliIdx:vt.cali_idx,savedPresetId:rn?.preset_id})},children:is})},Un)})})]})]})]})]})})()]}),mt&&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(ru,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}),a.jsx("span",{className:"text-sm text-white truncate",children:mt.name}),zt&&a.jsxs("span",{className:`text-xs px-1.5 py-0.5 rounded flex-shrink-0 ${zt.state==="ON"?"bg-bambu-green/20 text-bambu-green":zt.state==="OFF"?"bg-red-500/20 text-red-400":"bg-bambu-gray/20 text-bambu-gray"}`,children:[zt.state||"?",zt.state==="ON"&&zt.energy?.power!=null&&a.jsxs("span",{className:"text-yellow-400 ml-1.5",children:["· ",zt.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:tt.isPending||zt?.state==="ON"||!A("smart_plugs:control"),className:`px-2 py-1 text-xs rounded transition-colors flex items-center gap-1 ${A("smart_plugs:control")?zt?.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:A("smart_plugs:control")?void 0:g("printers.permission.noSmartPlugControl"),children:[a.jsx(fu,{className:"w-3 h-3"}),"On"]}),a.jsxs("button",{onClick:()=>te(!0),disabled:tt.isPending||zt?.state==="OFF"||!A("smart_plugs:control"),className:`px-2 py-1 text-xs rounded transition-colors flex items-center gap-1 ${A("smart_plugs:control")?zt?.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:A("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 ${mt.auto_off_executed?"text-bambu-green":"text-bambu-gray"}`,children:mt.auto_off_executed?"Auto-off done":"Auto-off"}),a.jsx("button",{onClick:()=>st.mutate(!mt.auto_off),disabled:st.isPending||mt.auto_off_executed||!A("smart_plugs:control"),title:A("smart_plugs:control")?mt.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 ${A("smart_plugs:control")?mt.auto_off_executed?"bg-bambu-green/50 cursor-not-allowed":mt.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 ${mt.auto_off||mt.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(dv,{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(bt=>a.jsxs("button",{onClick:()=>Ke.mutate(bt.id),disabled:Ke.isPending,title:`Run ${bt.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(oo,{className:"w-2.5 h-2.5"}),bt.name]},bt.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:()=>Qe.mutate(!pe?.chamber_light),disabled:!pe?.connected||Qe.isPending||!A("printers:control"),title:A("printers:control")?pe?.chamber_light?g("printers.chamberLightOff"):g("printers.chamberLightOn"):g("printers.permission.noControl"),className:pe?.chamber_light?"bg-yellow-500/20 hover:bg-yellow-500/30 border-yellow-500/30":"",children:a.jsx(dL,{on:pe?.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 bt=localStorage.getItem("cameraWindowState"),Ot=bt?JSON.parse(bt):{width:640,height:400},vn=[`width=${Ot.width}`,`height=${Ot.height}`,Ot.left!==void 0?`left=${Ot.left}`:"",Ot.top!==void 0?`top=${Ot.top}`:"","menubar=no,toolbar=no,location=no,status=no,noopener"].filter(Boolean).join(",");window.open(`/camera/${t.id}`,`camera-${t.id}`,vn)}},disabled:!pe?.connected,title:g(p==="embedded"?"printers.openCameraOverlay":"printers.openCameraWindow"),children:a.jsx(EF,{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:Zt,disabled:!pe?.connected||Xe.isPending||!A("printers:update"),title:A("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:fn,disabled:!pe?.connected||O||!A("printers:update"),title:A("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:O?a.jsx(at,{className:"w-3 h-3 animate-spin"}):a.jsx(Mn,{className:"w-3 h-3"})})]}),a.jsxs(Me,{variant:"secondary",size:"sm",onClick:()=>D(!0),disabled:!A("printers:files"),title:A("printers:files")?g("printers.browseFiles"):g("printers.permission.noFiles"),children:[a.jsx(Vb,{className:"w-4 h-4"}),"Files"]})]})]})]}),U&&a.jsx(LTe,{printerId:t.id,printerName:t.name,onClose:()=>D(!1)}),$&&a.jsx(HTe,{printerId:t.id,printerName:t.name,onClose:()=>G(!1)}),Pe&&a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onClick:()=>un(),children:a.jsxs("div",{className:"bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl max-w-lg w-full",onClick:bt=>bt.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:[Pe.needs_calibration?a.jsx(_1,{className:"w-5 h-5 text-blue-500"}):Pe.is_empty?a.jsx(yr,{className:"w-5 h-5 text-green-500"}):a.jsx(mi,{className:"w-5 h-5 text-yellow-500"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:"Build Plate Check"}),Pe.reference_count!==void 0&&Pe.max_references&&a.jsxs("span",{className:"text-xs text-bambu-gray bg-bambu-dark-tertiary px-2 py-1 rounded",children:[Pe.reference_count,"/",Pe.max_references," refs"]})]}),a.jsx("button",{onClick:()=>un(),className:"p-1 text-bambu-gray hover:text-white rounded transition-colors",children:a.jsx(Dt,{className:"w-5 h-5"})})]}),a.jsxs("div",{className:"p-4 space-y-4",children:[Pe.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 ${Pe.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 ${Pe.is_empty?"text-green-400":"text-yellow-400"}`,children:Pe.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(Pe.confidence*100),"% | ",g("printers.plateDetection.difference"),": ",Pe.difference_percent.toFixed(1),"%"]})]}),Pe.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:Pe.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:Pe.message})]}),tn&&tn.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:tn.references.length,max:tn.max_references})}),a.jsx("div",{className:"grid grid-cols-5 gap-2",children:tn.references.map(bt=>a.jsxs("div",{className:"relative group",children:[a.jsx("img",{src:J.getPlateReferenceThumbnailUrl(t.id,bt.index),alt:bt.label||`Reference ${bt.index+1}`,className:"w-full aspect-video object-cover rounded border border-bambu-dark-tertiary"}),a.jsx("button",{onClick:()=>lr(bt.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(Dt,{className:"w-3 h-3 text-white"})}),on?.index===bt.index?a.jsx("input",{type:"text",value:on.label,onChange:Ot=>gn({...on,label:Ot.target.value}),onBlur:()=>pn(bt.index,on.label),onKeyDown:Ot=>{Ot.key==="Enter"&&pn(bt.index,on.label),Ot.key==="Escape"&&gn(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:()=>gn({index:bt.index,label:bt.label}),title:bt.label?g("printers.plateDetection.clickToEdit",{label:bt.label}):g("printers.plateDetection.clickToAddLabel"),children:bt.label||a.jsx("span",{className:"italic opacity-50",children:g("printers.noLabel")})}),a.jsx("p",{className:"text-[10px] text-bambu-gray/60",children:bt.timestamp?tr(bt.timestamp)?.toLocaleDateString()??"":""})]},bt.index))})]}),!Pe.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")}),ge?a.jsxs("div",{className:"flex gap-1",children:[a.jsx(Me,{variant:"ghost",size:"sm",onClick:()=>ae(null),disabled:Ue,children:g("common.cancel")}),a.jsx(Me,{size:"sm",onClick:as,disabled:Ue,children:Ue?a.jsx(at,{className:"w-3 h-3 animate-spin"}):g("common.save")})]}):a.jsxs(Me,{variant:"ghost",size:"sm",onClick:()=>ae(Pe.roi||{x:.15,y:.35,w:.7,h:.55}),children:[a.jsx(Ga,{className:"w-3 h-3 mr-1"}),g("common.edit")]})]}),ge?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:ge.x,onChange:bt=>ae({...ge,x:parseFloat(bt.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(ge.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:ge.y,onChange:bt=>ae({...ge,y:parseFloat(bt.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(ge.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:ge.w,onChange:bt=>ae({...ge,w:parseFloat(bt.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(ge.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:ge.h,onChange:bt=>ae({...ge,h:parseFloat(bt.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(ge.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((Pe.roi?.x||.15)*100),"%, Y=",Math.round((Pe.roi?.y||.35)*100),"%, W=",Math.round((Pe.roi?.w||.7)*100),"%, H=",Math.round((Pe.roi?.h||.55)*100),"%"]})]})]}),a.jsx("div",{className:"flex justify-end gap-2 p-4 border-t border-bambu-dark-tertiary",children:Pe.needs_calibration?a.jsxs(a.Fragment,{children:[a.jsx(Me,{variant:"ghost",onClick:()=>un(),children:g("common.cancel")}),a.jsx(Me,{onClick:()=>Gr(),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:()=>Gr(),disabled:q,children:q?"Adding...":`Add Reference (${tn?.references.length||0}/${tn?.max_references||5})`}),a.jsx(Me,{onClick:()=>un(),children:"Close"})]})})]})}),z&&mt&&a.jsx(xn,{title:g("printers.confirm.powerOnTitle"),message:g("printers.confirm.powerOnMessage",{name:t.name}),confirmText:g("printers.confirm.powerOnButton"),variant:"default",onConfirm:()=>{tt.mutate("on"),W(!1)},onCancel:()=>W(!1)}),K&&mt&&a.jsx(xn,{title:g("printers.confirm.powerOffTitle"),message:pe?.state==="RUNNING"?g("printers.confirm.powerOffWarning",{name:t.name}):g("printers.confirm.powerOffMessage",{name:t.name}),confirmText:g("printers.confirm.powerOffButton"),variant:"danger",onConfirm:()=>{tt.mutate("off"),te(!1)},onCancel:()=>te(!1)}),Z&&a.jsx(xn,{title:g("printers.confirm.stopTitle"),message:g("printers.confirm.stopMessage",{name:t.name}),confirmText:g("printers.confirm.stopButton"),variant:"danger",onConfirm:()=>{Lt.mutate(),ee(!1)},onCancel:()=>ee(!1)}),Se&&a.jsx(xn,{title:g("printers.confirm.pauseTitle"),message:g("printers.confirm.pauseMessage",{name:t.name}),confirmText:g("printers.confirm.pauseButton"),variant:"default",onConfirm:()=>{ye.mutate(),oe(!1)},onCancel:()=>oe(!1)}),ie&&a.jsx(xn,{title:g("printers.confirm.resumeTitle"),message:g("printers.confirm.resumeMessage",{name:t.name}),confirmText:g("printers.confirm.resumeButton"),variant:"default",onConfirm:()=>{He.mutate(),me(!1)},onCancel:()=>me(!1)}),a.jsx(uL,{printerId:t.id,isOpen:se,onClose:()=>ce(!1)}),H&&a.jsx(GTe,{printerName:t.name,errors:pe?.hms_errors||[],onClose:()=>Y(!1),printerId:t.id,hasPermission:A}),Ce&&a.jsx(a$e,{isOpen:!!Ce,onClose:()=>le(null),printerId:t.id,printerName:t.name,amsId:Ce.amsId,amsLabel:Ce.amsLabel,initialMode:Ce.mode,thresholds:s}),Le&&a.jsx(i$e,{isOpen:!!Le,onClose:()=>V(null),tagUid:Le.tagUid,trayUuid:Le.trayUuid,printerId:Le.printerId,amsId:Le.amsId,trayId:Le.trayId}),X&&a.jsx(s$e,{isOpen:!!X,onClose:()=>fe(null),printerId:X.printerId,amsId:X.amsId,trayId:X.trayId,trayInfo:X.trayInfo}),Q&&a.jsx(wne,{isOpen:!!Q,onClose:()=>re(null),printerId:t.id,slotInfo:Q,printerModel:vR(t.model)||void 0,onSuccess:()=>{y.invalidateQueries({queryKey:["slotPresets",t.id]}),y.invalidateQueries({queryKey:["printerStatus",t.id]})}}),B&&a.jsx(k$e,{printer:t,onClose:()=>L(!1)}),ue&&ve&&a.jsx(C$e,{printer:t,firmwareInfo:ve,onClose:()=>Fe(!1)}),vr&&a.jsx("div",{className:"fixed inset-0 z-40",onClick:()=>Qn(null)})]})}function N$e({onClose:t,onAdd:e,existingSerials:n}){const{t:r}=Rt(),[i,s]=w.useState({name:"",serial_number:"",ip_address:"",access_code:"",model:"",location:"",auto_archive:!0}),[o,l]=w.useState(!1),[c,d]=w.useState([]),[u,h]=w.useState(""),[f,p]=w.useState(!1),[x,v]=w.useState(!1),[g,y]=w.useState([]),[_,N]=w.useState(""),[A,k]=w.useState({scanned:0,total:0});w.useEffect(()=>{hc.getInfo().then(M=>{v(M.is_docker),M.subnets.length>0&&(y(M.subnets),N(M.subnets[0]))}).catch(()=>{})},[]);const P=c.filter(M=>!n.includes(M.serial)),C=async()=>{h(""),d([]),l(!0),p(!1),k({scanned:0,total:0});try{if(x){await hc.startSubnetScan(_);const M=setInterval(async()=>{try{const j=await hc.getScanStatus();k({scanned:j.scanned,total:j.total});const B=await hc.getDiscoveredPrinters();d(B),j.running||(clearInterval(M),l(!1),p(!0))}catch(j){console.error("Failed to get scan status:",j)}},500)}else{await hc.startDiscovery(10);const M=setInterval(async()=>{try{const j=await hc.getDiscoveredPrinters();d(j)}catch(j){console.error("Failed to get discovered printers:",j)}},1e3);setTimeout(async()=>{clearInterval(M);try{await hc.stopDiscovery()}catch{}l(!1),p(!0);try{const j=await hc.getDiscoveredPrinters();d(j)}catch(j){console.error("Failed to get final discovered printers:",j)}},1e4)}}catch(M){console.error("Failed to start discovery:",M),h(M instanceof Error?M.message:r("printers.discovery.failedToStart")),l(!1),p(!0)}},E=M=>{const j=M.serial.startsWith("unknown-")?"":M.serial;s({...i,name:M.name||"",serial_number:j,ip_address:M.ip_address,model:vR(M.model)}),d([])};return w.useEffect(()=>()=>{hc.stopDiscovery().catch(()=>{}),hc.stopSubnetScan().catch(()=>{})},[]),w.useEffect(()=>{const M=j=>{j.key==="Escape"&&t()};return window.addEventListener("keydown",M),()=>window.removeEventListener("keydown",M)},[t]),a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",onClick:t,children:a.jsx(St,{className:"w-full max-w-md",onClick:M=>M.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:M=>N(M.target.value),disabled:o,children:g.map(M=>a.jsx("option",{value:M,children:M},M))}):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:M=>N(M.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&&A.total>0?r("printers.discovery.scanProgress",{scanned:A.scanned,total:A.total}):r("printers.discovery.scanning")]}):a.jsxs(a.Fragment,{children:[a.jsx(jr,{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}),P.length>0&&a.jsx("div",{className:"mt-3 space-y-2 max-h-40 overflow-y-auto",children:P.map(M=>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:()=>E(M),children:[a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:"font-medium text-white text-sm truncate",children:M.name||M.serial}),a.jsxs("p",{className:"text-xs text-bambu-gray truncate",children:[vR(M.model)||r("printers.discovery.unknown")," • ",M.ip_address,M.serial.startsWith("unknown-")&&a.jsxs("span",{className:"text-yellow-500",children:[" • ",r("printers.discovery.serialRequired")]})]})]}),a.jsx(Mn,{className:"w-4 h-4 text-bambu-gray -rotate-90 flex-shrink-0 ml-2"})]},M.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&&P.length===0&&a.jsx("p",{className:"mt-2 text-sm text-bambu-gray text-center",children:r("printers.discovery.allConfigured")})]}),a.jsxs("form",{onSubmit:M=>{M.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:M=>s({...i,name:M.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:M=>s({...i,ip_address:M.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:M=>s({...i,serial_number:M.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:M=>s({...i,access_code:M.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:M=>s({...i,model:M.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:M=>s({...i,location:M.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:M=>s({...i,auto_archive:M.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 C$e({printer:t,firmwareInfo:e,onClose:n}){const{t:r}=Rt(),i=Qt(),{showToast:s}=dn(),{hasPermission:o}=Er(),l=o("firmware:update"),[c,d]=w.useState(null),[u,h]=w.useState(!1),[f,p]=w.useState(null),{data:x,isLoading:v}=Ye({queryKey:["firmwarePrepare",t.id],queryFn:()=>B_.prepareUpload(t.id),staleTime:3e4,enabled:e.update_available&&l}),g=it({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(St,{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(ga,{className:"w-5 h-5 text-orange-400"}):a.jsx(yr,{className:"w-5 h-5 text-status-ok"})}),a.jsxs("div",{className:"flex-1",children:[a.jsx("h3",{className:"text-lg font-semibold text-white",children:e.update_available?r("printers.firmwareModal.title"):r("printers.firmwareModal.titleUpToDate")}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:t.name})]})]}),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(ei,{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(Va,{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(ga,{className:"w-4 h-4 mr-2"}),r("printers.firmwareModal.uploadFirmware")]})})]})]})})})}function k$e({printer:t,onClose:e}){const{t:n}=Rt(),r=Qt(),{showToast:i}=dn(),[s,o]=w.useState({name:t.name,ip_address:t.ip_address,access_code:"",model:t.model||"",location:t.location||"",auto_archive:t.auto_archive}),l=it({mutationFn:d=>J.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(St,{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 A$e(t){const{data:e}=Ye({queryKey:["printerStatus",t],queryFn:()=>J.getPrinterStatus(t),refetchInterval:3e4});return!e?.connected}function T$e({printer:t,plug:e,onPowerOn:n,isPowering:r}){const i=A$e(t.id),{data:s}=Ye({queryKey:["smartPlugStatus",e.id],queryFn:()=>J.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(fu,{className:"w-3 h-3"}),r?"...":"On"]})]}):null}function M$e(){const{t}=Rt(),[e,n]=w.useState(!1),[r,i]=w.useState(()=>localStorage.getItem("hideDisconnectedPrinters")==="true"),[s,o]=w.useState(!1),[l,c]=w.useState(null),[d,u]=w.useState(()=>localStorage.getItem("printerSortBy")||"name"),[h,f]=w.useState(()=>localStorage.getItem("printerSortAsc")!=="false"),[p,x]=w.useState(()=>{const ce=localStorage.getItem("printerCardSize");return ce?parseInt(ce,10):2}),v=p===1?"compact":"expanded",g=Qt(),{showToast:y}=dn(),{hasPermission:_}=Er(),[N,A]=w.useState(()=>{const ce=localStorage.getItem("openEmbeddedCameras");if(ce)try{const Ce=JSON.parse(ce);return new Map(Ce.map(le=>[le.id,le]))}catch{return new Map}return new Map});w.useEffect(()=>{const ce=Array.from(N.values());ce.length>0?localStorage.setItem("openEmbeddedCameras",JSON.stringify(ce)):localStorage.removeItem("openEmbeddedCameras")},[N]);const{data:k,isLoading:P}=Ye({queryKey:["printers"],queryFn:J.getPrinters}),{data:C}=Ye({queryKey:["settings"],queryFn:J.getSettings});w.useEffect(()=>{C?.camera_view_mode==="window"&&N.size>0&&A(new Map)},[C?.camera_view_mode,N.size]);const{data:E}=Ye({queryKey:["smart-plugs"],queryFn:J.getSmartPlugs}),{data:M}=Ye({queryKey:["maintenanceOverview"],queryFn:J.getMaintenanceOverview,staleTime:60*1e3}),{data:j}=Ye({queryKey:["spoolman-status"],queryFn:J.getSpoolmanStatus,staleTime:60*1e3}),B=j?.enabled&&j?.connected,{data:L}=Ye({queryKey:["unlinked-spools"],queryFn:J.getUnlinkedSpools,enabled:!!B,staleTime:30*1e3}),U=L&&L.length>0,{data:D}=Ye({queryKey:["linked-spools"],queryFn:J.getLinkedSpools,enabled:!!B,staleTime:30*1e3}),$=D?.linked,{data:G}=Ye({queryKey:["spool-assignments"],queryFn:()=>J.getAssignments(),staleTime:30*1e3}),z=it({mutationFn:({printerId:ce,amsId:Ce,trayId:le})=>J.unassignSpool(ce,Ce,le),onSuccess:()=>{g.invalidateQueries({queryKey:["spool-assignments"]})}}),W=(ce,Ce,le)=>G?.find(Le=>Le.printer_id===ce&&Le.ams_id===Number(Ce)&&Le.tray_id===Number(le)),K=M?.reduce((ce,Ce)=>(ce[Ce.printer_id]={due_count:Ce.due_count,warning_count:Ce.warning_count,total_print_hours:Ce.total_print_hours},ce),{})||{},te=E?.reduce((ce,Ce)=>(Ce.printer_id&&(ce[Ce.printer_id]=Ce),ce),{})||{},H=it({mutationFn:J.createPrinter,onSuccess:()=>{g.invalidateQueries({queryKey:["printers"]}),g.invalidateQueries({queryKey:["maintenanceOverview"]}),n(!1)},onError:ce=>y(ce.message||t("printers.toast.failedToAdd"),"error")}),Y=it({mutationFn:ce=>J.controlSmartPlug(ce,"on"),onSuccess:()=>{g.invalidateQueries({queryKey:["smart-plugs"]}),c(null)},onError:()=>{c(null)}}),Z=()=>{const ce=!r;i(ce),localStorage.setItem("hideDisconnectedPrinters",String(ce))},ee=ce=>{u(ce),localStorage.setItem("printerSortBy",ce)},Se=()=>{const ce=!h;f(ce),localStorage.setItem("printerSortAsc",String(ce))},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"}},ie=["S","M","L","XL"],me=w.useMemo(()=>{if(!k)return[];const ce=[...k];switch(d){case"name":ce.sort((Ce,le)=>Ce.name.localeCompare(le.name));break;case"model":ce.sort((Ce,le)=>(Ce.model||"").localeCompare(le.model||""));break;case"location":ce.sort((Ce,le)=>{const Le=Ce.location||"",V=le.location||"";return!Le&&V?1:Le&&!V?-1:Le.localeCompare(V)||Ce.name.localeCompare(le.name)});break;case"status":ce.sort((Ce,le)=>{const Le=g.getQueryData(["printerStatus",Ce.id]),V=g.getQueryData(["printerStatus",le.id]),X=fe=>fe?.connected?fe.state==="RUNNING"?0:1:2;return X(Le)-X(V)});break}return h||ce.reverse(),ce},[k,d,h,g]),se=w.useMemo(()=>{if(d!=="location")return null;const ce={};return me.forEach(Ce=>{const le=Ce.location||"Ungrouped";ce[le]||(ce[le]=[]),ce[le].push(Ce)}),ce},[d,me]);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(_$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:ce=>ee(ce.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:Se,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(cb,{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:ie.map((ce,Ce)=>{const le=Ce+1,Le=p===le;return a.jsx("button",{onClick:()=>{x(le),localStorage.setItem("printerCardSize",String(le))},className:`px-2 py-1.5 text-xs font-medium transition-colors ${Ce===0?"rounded-l-lg":""} ${Ce===ie.length-1?"rounded-r-lg":""} ${Le?"bg-bambu-green text-white":"text-bambu-gray hover:bg-bambu-dark-tertiary hover:text-white"}`,title:t(ce==="S"?"printers.cardSize.small":ce==="M"?"printers.cardSize.medium":ce==="L"?"printers.cardSize.large":"printers.cardSize.extraLarge"),children:ce},ce)})}),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:Z,className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),t("printers.hideOffline")]}),r&&Object.keys(te).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(fu,{className:"w-4 h-4"}),t("printers.powerOn"),a.jsx(Mn,{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(ce=>te[ce.id]).map(ce=>a.jsx(T$e,{printer:ce,plug:te[ce.id],onPowerOn:Ce=>{c(Ce),Y.mutate(Ce)},isPowering:l===te[ce.id]?.id},ce.id)),k?.filter(ce=>te[ce.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")]})]})]}),P?a.jsx("div",{className:"text-center py-12 text-bambu-gray",children:t("common.loading")}):k?.length===0?a.jsx(St,{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")]})]})}):se?a.jsx("div",{className:"space-y-6",children:Object.entries(se).map(([ce,Ce])=>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"}),ce,a.jsxs("span",{className:"text-sm font-normal text-bambu-gray",children:["(",Ce.length,")"]})]}),a.jsx("div",{className:`grid gap-4 ${p>=3?"gap-6":""} ${oe()}`,children:Ce.map(le=>a.jsx(u9,{printer:le,hideIfDisconnected:r,maintenanceInfo:K[le.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:U,linkedSpools:$,spoolmanUrl:j?.url,onGetAssignment:W,onUnassignSpool:(Le,V,X)=>z.mutate({printerId:Le,amsId:V,trayId:X}),timeFormat:C?.time_format||"system",cameraViewMode:C?.camera_view_mode||"window",onOpenEmbeddedCamera:(Le,V)=>A(X=>new Map(X).set(Le,{id:Le,name:V})),checkPrinterFirmware:C?.check_printer_firmware!==!1},le.id))})]},ce))}):a.jsx("div",{className:`grid gap-4 ${p>=3?"gap-6":""} ${oe()}`,children:me.map(ce=>a.jsx(u9,{printer:ce,hideIfDisconnected:r,maintenanceInfo:K[ce.id],viewMode:v,cardSize:p,spoolmanEnabled:B,hasUnlinkedSpools:U,linkedSpools:$,spoolmanUrl:j?.url,onGetAssignment:W,onUnassignSpool:(Ce,le,Le)=>z.mutate({printerId:Ce,amsId:le,trayId:Le}),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:(Ce,le)=>A(Le=>new Map(Le).set(Ce,{id:Ce,name:le})),checkPrinterFirmware:C?.check_printer_firmware!==!1},ce.id))}),e&&a.jsx(N$e,{onClose:()=>n(!1),onAdd:ce=>H.mutate(ce),existingSerials:k?.map(ce=>ce.serial_number)||[]}),Array.from(N.values()).map((ce,Ce)=>a.jsx(BTe,{printerId:ce.id,printerName:ce.name,viewerIndex:Ce,onClose:()=>A(le=>{const Le=new Map(le);return Le.delete(ce.id),Le})},ce.id))]})}function P$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}`:P$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 j$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 il(t){return j$e[t.toUpperCase()]||t}const E$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 (₽)"}],h9=768;function Cne(){const[t,e]=w.useState(()=>typeof window<"u"?window.innerWidth{const n=window.matchMedia(`(max-width: ${h9-1}px)`),r=i=>{e(i.matches)};return e(n.matches),n.addEventListener("change",r),()=>n.removeEventListener("change",r)},[]),t}function bO({archiveId:t,libraryFileId:e,title:n,fileType:r,onClose:i}){const{t:s}=Rt(),{data:o}=Ye({queryKey:["settings"],queryFn:J.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,A]=w.useState(null),[k,P]=w.useState(0),[C,E]=w.useState(!1),[M,j]=w.useState(null),[B,L]=w.useState(!1),[U,D]=w.useState(!1),$=w.useRef(null),G=w.useRef(null),z=10,W=160,K=240,te=.35;w.useEffect(()=>{const Pe=be=>{be.key==="Escape"&&i()};return window.addEventListener("keydown",Pe),()=>window.removeEventListener("keydown",Pe)},[i]),w.useEffect(()=>{if(x(!0),c){const Pe=(r||"").toLowerCase(),be=Pe==="3mf"||Pe==="stl",O=Pe==="gcode"||Pe==="3mf";f({has_model:be,has_gcode:O,has_source:!1,build_volume:{x:256,y:256,z:256},filament_colors:[]}),u(be?"3d":O?"gcode":null),x(!1);return}if(!t){f(null),u(null),x(!1);return}J.getArchiveCapabilities(t).then(Pe=>{f(Pe),Pe.has_model?u("3d"):Pe.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),A(null),P(0),c){const Pe=(r||"").toLowerCase();if(!e||Pe!=="3mf"){g(null),_(!1);return}J.getLibraryFilePlates(e).then(be=>g(be)).catch(()=>g(null)).finally(()=>_(!1));return}if(!t){g(null),_(!1);return}J.getArchivePlates(t).then(Pe=>g(Pe)).catch(()=>g(null)).finally(()=>_(!1))},[t,r,c,e]);const H=w.useMemo(()=>v?.plates??[],[v]),Y=(v?.is_multi_plate??!1)&&H.length>1,Z=C&&Y,ee=N==null?null:H.find(Pe=>Pe.index===N)??null,Se=Pe=>Pe.object_count??Pe.objects?.length??0,oe=H.reduce((Pe,be)=>Pe+Se(be),0),ie=ee?Se(ee):oe,me=ee?s("modelViewer.plateNumber",{number:ee.index}):s("modelViewer.allPlates"),se=H.length>0,ce=w.useRef(null),Ce=w.useRef(null),[le,Le]=w.useState(10),[V,X]=w.useState(3),fe=H.length>le,Q=Math.max(1,Math.ceil(H.length/le)),re=fe?H.slice(k*le,(k+1)*le):H;w.useEffect(()=>{if(!Z){Le(10),X(3);return}const Pe=ce.current,be=Ce.current;if(!Pe||!be)return;let O=0;const R=()=>{const ge=be.clientWidth,Ue=Math.floor(ge/210),ze=Math.max(3,Math.min(5,Ue||3));X(ke=>ke===ze?ke:ze);const $e=window.getComputedStyle(Pe),Re=Number.parseFloat($e.rowGap||"0"),ve=Pe.querySelector("button")?.getBoundingClientRect().height??44,Ne=be.clientHeight,we=Math.max(1,Math.floor((Ne+Re)/(ve+Re)))*ze,qe=Math.max(1,we-1);Le(ke=>ke===qe?ke:qe)},q=()=>{O&&cancelAnimationFrame(O),O=requestAnimationFrame(R)};q();const de=new ResizeObserver(q);return de.observe(be),de.observe(Pe),()=>{O&&cancelAnimationFrame(O),de.disconnect()}},[Z,H.length]),w.useEffect(()=>{if(!fe){P(0);return}P(Pe=>Math.min(Pe,Q-1))},[H.length,fe,Q]),w.useEffect(()=>{if(!fe||N==null)return;const Pe=H.findIndex(O=>O.index===N);if(Pe<0)return;const be=Math.floor(Pe/le);P(O=>O===be?O:be)},[H,le,N,fe]),w.useEffect(()=>{if(!Z){j(null),D(!1);return}if(U)return;const Pe=$.current,be=G.current;if(!Pe||!be)return;const O=Pe.clientHeight;if(!O)return;const R=Math.max(K,O*te),q=Math.max(W,O-z-R),de=Math.min(be.scrollHeight,q);j(Math.max(W,de))},[Z,U,H.length,k,z,W,K,te]),w.useEffect(()=>{if(!B)return;const Pe=O=>{const R=$.current;if(!R)return;const q=R.getBoundingClientRect(),de=q.height;if(!de)return;const ge=Math.max(K,de*te),ae=Math.max(W,de-z-ge),Ue=Math.min(ae,Math.max(W,O.clientY-q.top));j(Ue)},be=()=>{L(!1),D(!0)};return document.addEventListener("mousemove",Pe),document.addEventListener("mouseup",be),document.body.style.cursor="row-resize",document.body.style.userSelect="none",()=>{document.removeEventListener("mousemove",Pe),document.removeEventListener("mouseup",be),document.body.style.cursor="",document.body.style.userSelect=""}},[B,z,W,K,te]);const ue=c?(r||"").toLowerCase()==="3mf":!0,Fe=async()=>{if(!ue)return;const Pe=n||"model";try{if(c){const{token:be}=await J.createLibrarySlicerToken(e),O=J.getLibrarySlicerDownloadUrl(e,be,Pe);of(`${window.location.origin}${O}`,l)}else{const{token:be}=await J.createArchiveSlicerToken(t),O=J.getArchiveSlicerDownloadUrl(t,be,Pe);of(`${window.location.origin}${O}`,l)}}catch{if(c){const be=`${window.location.origin}${J.getLibraryFileDownloadUrl(e)}`;of(be,l)}else{const be=`${window.location.origin}${J.getArchiveForSlicer(t,Pe)}`;of(be,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:Pe=>Pe.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}),se&&a.jsxs("span",{className:"text-xs text-bambu-gray bg-bambu-dark-tertiary/70 px-2 py-1 rounded whitespace-nowrap",children:[me,": ",s("modelViewer.objectCount",{count:ie})]})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs(Me,{variant:"secondary",size:"sm",onClick:Fe,disabled:!ue,children:[a.jsx(na,{className:"w-4 h-4"}),s("modelViewer.openInSlicer")]}),a.jsx(Me,{variant:"secondary",size:"sm",onClick:()=>E(Pe=>!Pe),title:C?"Exit fullscreen":"Enter fullscreen",children:C?a.jsx(TF,{className:"w-4 h-4"}):a.jsx(WC,{className:"w-4 h-4"})}),a.jsx(Me,{variant:"ghost",size:"sm",onClick:i,children:a.jsx(Dt,{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(ei,{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($he,{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 ${Z?"gap-0 min-h-0":"gap-3"}`,children:[Y&&a.jsxs("div",{ref:G,style:Z&&M!=null?{height:M}:void 0,className:`rounded-lg border border-bambu-dark-tertiary bg-bambu-dark p-3 ${Z?"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(ri,{className:"w-4 h-4"}),s("modelViewer.plates"),y&&a.jsx(at,{className:"w-3 h-3 animate-spin"})]}),a.jsxs("div",{className:Z?"flex flex-col min-h-0 flex-1":void 0,children:[a.jsx("div",{ref:Ce,className:Z?"min-h-0 overflow-hidden pr-1 flex-1":void 0,children:a.jsxs("div",{ref:ce,className:Z?"grid gap-2":"grid grid-cols-2 md:grid-cols-3 gap-2",style:Z?{gridTemplateColumns:`repeat(${V}, minmax(0, 1fr))`}:void 0,children:[a.jsxs("button",{type:"button",onClick:()=>A(null),className:`flex items-center rounded-lg border text-left transition-colors ${Z?"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 ${Z?"w-8 h-8":"w-10 h-10"}`,children:a.jsx(ri,{className:`${Z?"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:`${Z?"text-xs":"text-sm"} text-white font-medium truncate`,children:s("modelViewer.allPlates")}),a.jsx("p",{className:`${Z?"text-[10px]":"text-xs"} text-bambu-gray truncate`,children:s("modelViewer.plateCount",{count:H.length})})]}),N==null&&a.jsx(Vr,{className:`${Z?"w-3.5 h-3.5":"w-4 h-4"} text-bambu-green flex-shrink-0`})]}),re.map(Pe=>a.jsxs("button",{type:"button",onClick:()=>A(Pe.index),className:`flex items-center rounded-lg border text-left transition-colors ${Z?"gap-1.5 p-1.5 w-full":"gap-2 p-2"} ${N===Pe.index?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark-secondary hover:border-bambu-gray"}`,children:[Pe.has_thumbnail&&Pe.thumbnail_url?a.jsx("img",{src:Pe.thumbnail_url,alt:`Plate ${Pe.index}`,className:`${Z?"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 ${Z?"w-8 h-8":"w-10 h-10"}`,children:a.jsx(ri,{className:`${Z?"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:`${Z?"text-xs":"text-sm"} text-white font-medium truncate`,children:Pe.name||s("modelViewer.plateNumber",{number:Pe.index})}),a.jsx("p",{className:`${Z?"text-[10px]":"text-xs"} text-bambu-gray truncate`,children:s("modelViewer.objectCount",{count:Pe.object_count??Pe.objects?.length??0})})]}),N===Pe.index&&a.jsx(Vr,{className:`${Z?"w-3.5 h-3.5":"w-4 h-4"} text-bambu-green flex-shrink-0`})]},Pe.index))]})}),(ee||fe)&&a.jsxs("div",{className:"mt-auto pt-3 flex items-center gap-4 text-xs text-bambu-gray overflow-x-auto",children:[ee&&a.jsxs("div",{className:"flex items-center gap-3 whitespace-nowrap",children:[a.jsx("span",{children:s("modelViewer.plateNumber",{number:ee.index})}),ee.print_time_seconds!=null&&a.jsx("span",{children:s("modelViewer.eta",{minutes:Math.round(ee.print_time_seconds/60)})}),ee.filament_used_grams!=null&&a.jsxs("span",{children:[ee.filament_used_grams.toFixed(1)," g"]}),ee.filaments.length>0&&a.jsx("span",{children:s("modelViewer.filamentCount",{count:ee.filaments.length})})]}),fe&&a.jsxs("div",{className:`flex items-center gap-2 whitespace-nowrap ${ee?"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:()=>P(Pe=>Math.max(Pe-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 be=Math.max(0,k-Math.floor(2.5));const O=Math.min(Q,be+5);O-be<5&&(be=Math.max(0,O-5));const R=Array.from({length:O-be},(q,de)=>be+de);return a.jsxs(a.Fragment,{children:[be>0&&a.jsx("button",{type:"button",onClick:()=>P(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"}),be>1&&a.jsx("span",{className:"px-1",children:"…"}),R.map(q=>a.jsx("button",{type:"button",onClick:()=>P(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)),OP(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:()=>P(Pe=>Math.min(Pe+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")})]})]})]})]})]}),Z&&a.jsx("div",{role:"separator","aria-orientation":"horizontal",onMouseDown:Pe=>{Pe.preventDefault(),L(!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 ${Z?"min-h-0":""}`,children:a.jsx(NY,{url:c?J.getLibraryFileDownloadUrl(e):h.has_source?J.getSource3mfDownloadUrl(t):J.getArchiveDownload(t),fileType:r,buildVolume:h.build_volume,filamentColors:h.filament_colors,selectedPlateId:N,className:"w-full h-full"})})]}):d==="gcode"&&h?a.jsx(sQ,{gcodeUrl:c?J.getLibraryFileGcodeUrl(e):J.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 HN={"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 D$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 HN[e]?HN[e]:D$e(t)}function xO(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(HN[n])return HN[n]}return null}function oA(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=r9(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:pO(i.id,o.id,s,!1),globalTrayId:BN(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=r9(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 m9(t,e){if(!t?.filaments||t.filaments.length===0)return;const n=oA(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()&&Fa(g.color)===Fa(l.color)),h||(f=v.find(g=>g.type?.toUpperCase()===l.type?.toUpperCase()&&Lc(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()&&Fa(v.color)===Fa(l.color)),h||(f=d.find(v=>v.type?.toUpperCase()===l.type?.toUpperCase()&&Lc(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 R$e(t){return w.useMemo(()=>oA(t),[t])}function kne(t,e,n){const r=R$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 P=n[u],C=r.find(E=>E.globalTrayId===P);if(C){const E=C.type?.toUpperCase()===d.type?.toUpperCase(),M=Fa(C.color)===Fa(d.color)||Lc(C.color,d.color);let j;return E&&M?j="match":E?j="type_only":j="mismatch",{...d,loaded:C,hasFilament:!0,typeMatch:E,colorMatch:M,status:j,isManual:!0}}}const h=d.tray_info_idx||"";let f=r.filter(P=>!c.has(P.globalTrayId));d.nozzle_id!=null&&(f=f.filter(P=>P.extruderId===d.nozzle_id));let p,x,v,g;if(h){const P=f.filter(C=>C.trayInfoIdx===h);P.length===1?p=P[0]:P.length>1&&(x=P.find(C=>C.type?.toUpperCase()===d.type?.toUpperCase()&&Fa(C.color)===Fa(d.color)),x||(v=P.find(C=>C.type?.toUpperCase()===d.type?.toUpperCase()&&Lc(C.color,d.color))),!x&&!v&&(g=P.find(C=>C.type?.toUpperCase()===d.type?.toUpperCase())))}!p&&!x&&!v&&!g&&(x=f.find(P=>P.type?.toUpperCase()===d.type?.toUpperCase()&&Fa(P.color)===Fa(d.color)),x||(v=f.find(P=>P.type?.toUpperCase()===d.type?.toUpperCase()&&Lc(P.color,d.color))),!x&&!v&&(g=f.find(P=>P.type?.toUpperCase()===d.type?.toUpperCase())));const y=p||x||v||g||void 0;y&&c.add(y.globalTrayId);const _=!!y,N=_,A=!!p||!!x||!!v;let k;return p||x||v?k="match":g?k="type_only":k="mismatch",{...d,loaded:y,hasFilament:_,typeMatch:N,colorMatch:A,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 F$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=Fa(y.color)===Fa(d.color)||Lc(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()&&Fa(g.color)===Fa(d.color)),p=f?void 0:h.find(g=>g.type?.toUpperCase()===d.type?.toUpperCase()&&Lc(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 L$e(t,e,n){if(!t?.filaments||t.filaments.length===0)return;const r=oA(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()&&Fa(v.color)===Fa(c.color)),f=h?void 0:u.find(v=>v.type?.toUpperCase()===c.type?.toUpperCase()&&Lc(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 f9={useDefault:!0,manualMappings:{},autoConfigured:!1};function O$e(t,e,n,r,i,s){const o=lv({queries:t.map(x=>({queryKey:["printer-status",x],queryFn:()=>J.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(j=>j.id===x)?.name||`Printer ${x}`,A=oA(y),k=i[x]||f9,P=m9(n,y),C=k.useDefault?r:k.manualMappings,E=L$e(n,y,C),M=F$e(n?.filaments,A,C);return{printerId:x,printerName:N,status:y,isLoading:g?.isLoading??!1,loadedFilaments:A,autoMapping:P,finalMapping:E,matchStatus:M.status,exactMatches:M.exactMatches,typeOnlyMatches:M.typeOnlyMatches,missingTypes:M.missingTypes,totalSlots:M.totalSlots,config:k}}),[t,o,e,n,i,r]),c=o.some(x=>x.isLoading),d=(x,v)=>{s(g=>({...g,[x]:{...g[x]||f9,...v}}))},u=x=>{const v=l.find(_=>_.printerId===x);if(!v||!v.status||!n?.filaments)return;const g=m9(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 I$e({printerId:t,filamentReqs:e,manualMappings:n,onManualMappingChange:r,currencySymbol:i,defaultCostPerKg:s,defaultExpanded:o=!1}){const{t:l}=Rt(),c=Qt(),[d,u]=w.useState(!1),[h,f]=w.useState(o),{data:p}=Ye({queryKey:["printer-status",t],queryFn:()=>J.getPrinterStatus(t),enabled:!!t}),{data:x}=Ye({queryKey:["spool-assignments",t],queryFn:()=>J.getAssignments(t),enabled:!!t}),{loadedFilaments:v,filamentComparison:g,hasTypeMismatch:y,hasColorMismatch:_}=kne(e,p,n),N=w.useMemo(()=>{const L=new Map;for(const U of x||[]){const D=U.ams_id===255,$=BN(U.ams_id,U.tray_id,D);L.set($,U.spool?.cost_per_kg??null)}return L},[x]),A=w.useMemo(()=>{const L=new Map;for(const U of x||[]){const D=U.ams_id===255,$=BN(U.ams_id,U.tray_id,D),G=U.spool;if(!G){L.set($,null);continue}L.set($,Math.max(0,Math.round((G.label_weight??0)-(G.weight_used??0))))}return L},[x]),k=w.useMemo(()=>{let L=0;for(const U of g){const D=U.loaded?.globalTrayId;if(D==null)continue;const G=N.get(D)??null??s;G>0&&(L+=U.used_grams/1e3*G)}return L},[g,N,s]),P=w.useMemo(()=>Array.from(N.values()).some(L=>L!=null&&L>0),[N]),C=e?.filaments&&e.filaments.length>0,E=e?.filaments?.some(L=>L.nozzle_id!=null)??!1;if(!C||!p)return null;const M=y?"#f97316":_?"#facc15":"#00ae42",j=(L,U)=>{if(L>0)if(U===""){const D={...n};delete D[L],r(D)}else r({...n,[L]:parseInt(U,10)})},B=async()=>{u(!0);try{await J.refreshPrinterStatus(t),await new Promise(L=>setTimeout(L,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:M,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(wl,{className:"w-4 h-4 ml-auto"}):a.jsx(Mn,{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:B,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(Sr,{className:`w-3 h-3 ${d?"animate-spin":""}`}),a.jsx("span",{children:"Re-read"})]})]}),g.map((L,U)=>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: ${L.type} - ${vf(L.color)}`,children:a.jsx(x1,{className:"w-3 h-3",fill:L.color,stroke:L.color})}),a.jsxs("span",{className:"text-white truncate flex items-center gap-1",children:[E&&L.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:L.nozzle_id===1?l("printModal.leftNozzleTooltip"):l("printModal.rightNozzleTooltip"),children:L.nozzle_id===1?l("printModal.leftNozzle"):l("printModal.rightNozzle")}),L.type," ",a.jsxs("span",{className:"text-bambu-gray",children:["(",L.used_grams,"g)"]})]}),a.jsx("span",{className:"text-bambu-gray",children:"→"}),a.jsxs("select",{value:L.loaded?.globalTrayId??"",onChange:D=>j(L.slot_id||0,D.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 ${L.status==="match"?"border-bambu-green/50 text-bambu-green":L.status==="type_only"?"border-yellow-400/50 text-yellow-400":"border-orange-400/50 text-orange-400"} ${L.isManual?"ring-1 ring-blue-400/50":""}`,title:L.isManual?"Manually selected":"Auto-matched",children:[a.jsx("option",{value:"",className:"bg-bambu-dark text-bambu-gray",children:"-- Select slot --"}),v.filter(D=>L.nozzle_id==null||D.extruderId===L.nozzle_id).map(D=>{const $=A.get(D.globalTrayId),G=$!=null?l("printModal.slotRemainingShort",{grams:$,defaultValue:` - ${$}g left`}):"";return a.jsxs("option",{value:D.globalTrayId,className:"bg-bambu-dark text-white",children:[D.label,": ",D.type," (",D.colorName,")",G]},D.globalTrayId)})]}),L.status==="match"?a.jsx(Vr,{className:"w-3 h-3 text-bambu-green"}):L.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"})})]},U)),a.jsxs("div",{className:"text-xs text-bambu-gray",children:[l("printModal.totalCost")," ",a.jsx("span",{className:"text-white",children:k>0||P?`${i}${k.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 z$e({filamentReqs:t,availableFilaments:e,overrides:n,onChange:r}){const{t:i}=Rt(),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(lo,{className:"w-3 h-3"})}):a.jsx("span",{className:"w-3"})]},c.slot_id)})})]})}function U$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(ri,{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(ri,{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?` • ${Js(i.print_time_seconds)}`:""]})]}),n===i.index&&a.jsx(Vr,{className:"w-4 h-4 text-bambu-green flex-shrink-0"})]},i.index))})]})}function B$e({printerResult:t,filamentReqs:e,onUpdateConfig:n}){const r=Qt(),[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 J.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()&&Fa(N.color)===Fa(d.color)),y=g?void 0:t.loadedFilaments.find(N=>!v.has(N.globalTrayId)&&N.type?.toUpperCase()===d.type?.toUpperCase()&&Lc(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=Fa(f.color)===Fa(d.color)||Lc(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(Sr,{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(Vr,{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 H$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(z=>z.is_active),A=w.useMemo(()=>{if(u!=="printer"||!g||y)return N;const z=N.filter(W=>W.model===g);return z.length>0?z:N},[N,u,g,y]),k=N.length-A.length,P=w.useMemo(()=>{const z=N.map(W=>W.model).filter(W=>!!W);return[...new Set(z)].sort()},[N]),C=w.useMemo(()=>{if(!f)return[];const z=N.filter(W=>W.model===f&&W.location).map(W=>W.location).filter(W=>!!W);return[...new Set(z)].sort()},[N,f]),E=h&&p&&P.length>0,M=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(A.length===0)return a.jsxs("div",{className:"flex items-center gap-2 text-red-400 text-sm mb-4",children:[a.jsx(Va,{className:"w-4 h-4"}),"No ",s?"":"active ","printers available"]});const j=z=>{i?e.includes(z)?n(e.filter(W=>W!==z)):n([...e,z]):n([z])},B=()=>{n(A.map(z=>z.id))},L=()=>{n([])},U=(z,W,K)=>{K.stopPropagation(),!(!c||!d)&&(W?c(z):d(z,{useDefault:!0,manualMappings:{},autoConfigured:!1}))},D=z=>e.includes(z),$=e.length,G=z=>o?.find(W=>W.printerId===z);return a.jsxs("div",{className:"space-y-2 mb-6",children:[E&&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(Nr,{className:"w-4 h-4"}),a.jsx("span",{className:"text-sm",children:"Specific Printer"})]}),a.jsxs("button",{type:"button",onClick:()=>{h("model"),n([]);const z=g&&P.includes(g)?g:P[0];p(z)},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(fh,{className:"w-4 h-4"}),a.jsxs("span",{className:"text-sm",children:["Any ",g||"Model"]})]})]}),u==="model"&&E&&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:z=>{p(z.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..."}),P.map(z=>a.jsx("option",{value:z,children:z},z))]})]}),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:z=>v(z.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(z=>a.jsx("option",{value:z,children:z},z))]})]}),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&&A.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:L,className:"text-bambu-gray hover:text-white transition-colors",children:"Clear"})]})]}),u==="printer"&&A.map(z=>{const W=D(z.id),K=G(z.id),te=K&&!K.config.useDefault;return a.jsxs("div",{children:[a.jsxs("button",{type:"button",onClick:()=>j(z.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"} ${z.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(Nr,{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:[z.name,!z.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:[z.model||"Unknown model"," • ",z.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(Vr,{className:"w-3 h-3 text-white"})})]}),W&&M&&K&&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:te,onChange:H=>U(z.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 ${K.matchStatus==="full"?"text-bambu-green":K.matchStatus==="partial"?"text-yellow-400":"text-orange-400"}`,children:["(",K.exactMatches,"/",K.totalSlots," matched)"]}),K.isLoading&&a.jsx(Sr,{className:"w-3 h-3 text-bambu-gray animate-spin"}),te&&a.jsxs("button",{type:"button",onClick:H=>{H.stopPropagation(),c(z.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(hge,{className:"w-3 h-3"}),"Auto"]})]}),te&&a.jsx(B$e,{printerResult:K,filamentReqs:l.filaments,onUpdateConfig:H=>d(z.id,H)})]})]},z.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(Va,{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(Va,{className:"w-3 h-3"}),"Select a target printer model"]})]})}const $$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 V$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(ZC,{className:"w-4 h-4"}),a.jsx("span",{children:"Print Options"}),r?a.jsx(wl,{className:"w-4 h-4 ml-auto"}):a.jsx(Mn,{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:$$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 q$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:m3(k)})),o(h3(k,n)),c(VB(k,r)),u(!0),f(!0)}},[t.scheduleType,t.scheduledTime,n,r,e,t]);const v=k=>{e({...t,scheduleType:k})},g=(k,P)=>{const C=Rge(k,n),E=Fge(P);u(!!C),f(!!E),C&&E&&(C.setHours(E.hours,E.minutes,0,0),C>new Date&&e({...t,scheduledTime:m3(C)}))},y=k=>{o(k),g(k,l)},_=k=>{c(k),g(s,k)},N=k=>{const P=k.target.value;if(P){const C=new Date(P);isNaN(C.getTime())||(o(h3(C,n)),c(VB(C,r)),u(!0),f(!0),e({...t,scheduledTime:P}))}},A=()=>{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(qn,{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(da,{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(_X,{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:Ege(n)}),a.jsx("button",{type:"button",onClick:A,className:"absolute right-2 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white",title:"Open calendar",children:a.jsx(da,{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:Dge(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(fu,{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},G$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}=Rt(),c=Qt(),{showToast:d}=dn(),{hasPermission:u}=Er(),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&&!a9(i.scheduled_time)&&(Ee="scheduled");let Ve="";if(i.scheduled_time&&!a9(i.scheduled_time)){const ot=tr(i.scheduled_time)??new Date;Ve=m3(ot)}return{scheduleType:Ee,scheduledTime:Ve,requirePreviousSuccess:i.require_previous_success,autoOffAfter:i.auto_off_after}}return G$e}),[A,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{}}),[P,C]=w.useState({}),[E,M]=w.useState(()=>t==="edit-queue-item"&&i?.target_model?"model":"printer"),[j,B]=w.useState(()=>t==="edit-queue-item"&&i?.target_model?i.target_model:null),[L,U]=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]:[]),[z]=w.useState(()=>t==="edit-queue-item"&&i?i.plate_id:null),[W,K]=w.useState(!1),[te,H]=w.useState({current:0,total:0}),[Y,Z]=w.useState(new Set),ee=f.length,Se=f.length>0?f[0]:null,{data:oe}=Ye({queryKey:["settings"],queryFn:J.getSettings}),ie=il(oe?.currency||"USD"),me=oe?.default_filament_cost??0,{data:se,isLoading:ce}=Ye({queryKey:["printers"],queryFn:J.getPrinters}),{data:Ce}=Ye({queryKey:["archive",e],queryFn:()=>J.getArchive(e),enabled:!!e&&!h}),{data:le}=Ye({queryKey:["library-file",n],queryFn:()=>J.getLibraryFile(n),enabled:h&&!!n}),Le=Ce?.sliced_for_model||le?.sliced_for_model||null,{data:V,isError:X}=Ye({queryKey:["archive-plates",e],queryFn:()=>J.getArchivePlates(e),enabled:!!e&&!h,retry:!1}),{data:fe}=Ye({queryKey:["library-file-plates",n],queryFn:()=>J.getLibraryFilePlates(n),enabled:h&&!!n}),Q=h?fe:V,{data:re,isError:ue}=Ye({queryKey:["archive-filaments",e,x],queryFn:()=>J.getArchiveFilamentRequirements(e,x??void 0),enabled:!!e&&!h&&(x!==null||!Q?.is_multi_plate),retry:!1}),{data:Fe}=Ye({queryKey:["library-file-filaments",n,x],queryFn:()=>J.getLibraryFileFilamentRequirements(n,x??void 0),enabled:h&&!!n&&(x!==null||!Q?.is_multi_plate)}),Pe=!h&&(X||ue),be=h?Fe:re,O=w.useMemo(()=>{if(!(x===null||!Q?.plates?.length))return Q.plates.find(Ee=>Ee.index===x)?.name||void 0},[Q,x]),{data:R}=Ye({queryKey:["available-filaments",j,L],queryFn:()=>J.getAvailableFilaments(j,L??void 0),enabled:E==="model"&&!!j}),{data:q}=Ye({queryKey:["printer-status",Se],queryFn:()=>J.getPrinterStatus(Se),enabled:!!Se}),{amsMapping:de}=kne(be,q,A),ge=O$e(f,se,be,A,P,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=se?.filter(Ve=>Ve.is_active)||[];Ee.length===1&&f.length===0&&p([Ee[0].id])},[t,se,f.length]),w.useEffect(()=>{t==="edit-queue-item"?(JSON.stringify(f.sort())!==JSON.stringify(G.sort())||x!==z)&&(k({}),C({}),Z(new Set)):(k({}),C({}),Z(new Set))},[t,f,x,G,z]);const[ae,Ue]=w.useState(j),[ze,$e]=w.useState(x);w.useEffect(()=>{(j!==ae||x!==ze)&&(Ue(j),$e(x),(t!=="edit-queue-item"||ae!==null)&&$({}))},[j,x,ae,ze,t]),w.useEffect(()=>{if(!oe?.per_printer_mapping_expanded||f.length<=1)return;const Ee=f.filter(Ve=>{if(Y.has(Ve))return!1;const ot=ge.printerResults.find(kt=>kt.printerId===Ve);return ot&&ot.status&&!ot.isLoading});Ee.length>0&&(Z(Ve=>{const ot=new Set(Ve);return Ee.forEach(kt=>ot.add(kt)),ot}),Ee.forEach(Ve=>{ge.autoConfigurePrinter(Ve)}))},[oe?.per_printer_mapping_expanded,f,Y,ge]),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,pe=Q?.plates??[],ve=it({mutationFn:Ee=>J.addToQueue(Ee)}),Ne=it({mutationFn:Ee=>J.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")}}),xe=async Ee=>{if(Ee?.preventDefault(),E==="printer"&&f.length===0){d("Please select at least one printer","error");return}if(E==="model"&&!j){d("Please select a target printer model","error");return}K(!0);const Ve=E==="model"?1:f.length;H({current:0,total:Ve});const ot={success:0,failed:0,errors:[]},kt=At=>{if(f.length>1){const Be=P[At];if(Be&&!Be.useDefault)return ge.getFinalMapping(At)}return de},Ft=Object.keys(D).length>0?Object.entries(D).map(([At,{type:Be,color:mt}])=>({slot_id:parseInt(At,10),type:Be,color:mt})):void 0,Vt=At=>({printer_id:E==="printer"?At:null,target_model:E==="model"?j:null,target_location:E==="model"?L:null,filament_overrides:E==="model"?Ft: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:At?kt(At):void 0,plate_id:x,scheduled_time:_.scheduleType==="scheduled"&&_.scheduledTime?new Date(_.scheduledTime).toISOString():void 0,...g});if(E==="model"){H({current:1,total:1});try{if(t==="reprint"){d("Model-based assignment only works with queue mode","error"),K(!1);return}else if(t==="edit-queue-item"){const At={printer_id:null,target_model:j,target_location:L,filament_overrides:Ft||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(At)}else await ve.mutateAsync(Vt(null));ot.success++}catch(At){ot.failed++,ot.errors.push(At.message)}}else for(let At=0;Atzt.id===Be)?.name||`Printer ${Be}`;ot.errors.push(`${yt}: ${mt.message}`)}}K(!1),ot.failed===0?(t!=="reprint"&&(E==="model"?d(t==="edit-queue-item"?"Queue item updated":`Queued for any ${j}`):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"]}))},we=W||Ne.isPending,qe=w.useMemo(()=>!(we||E==="printer"&&f.length===0||E==="model"&&!j||E==="model"&&t==="reprint"||Re&&!x),[f.length,E,j,t,Re,x,we]),nt=(()=>{const Ee=f.length;return t==="reprint"?{title:l(h?"queue.print":"queue.reprint"),icon:Nr,submitText:Ee>1?l("queue.printToPrinters",{count:Ee}):l("queue.print"),submitIcon:Nr,loadingText:te.total>1?l("queue.sendingProgress",{current:te.current,total:te.total}):l("queue.sending")}:t==="add-to-queue"?{title:l("queue.schedulePrint"),icon:da,submitText:Ee>1?l("queue.queueToPrinters",{count:Ee}):l("queue.addToQueue"),submitIcon:da,loadingText:te.total>1?l("queue.addingProgress",{current:te.current,total:te.total}):l("queue.adding")}:{title:l("queue.editQueueItem"),icon:Ga,submitText:l("common.save"),submitIcon:Ga,loadingText:te.total>1?l("queue.savingProgress",{current:te.current,total:te.total}):l("common.saving")}})(),De=nt.icon,We=nt.submitIcon,Oe=Se&&(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(St,{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(Dt,{className:"w-5 h-5"})})]}),a.jsxs("form",{onSubmit:xe,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(U$e,{plates:pe,isMultiPlate:Re,selectedPlate:x,onSelect:v}),a.jsx(H$e,{printers:se||[],selectedPrinterIds:f,onMultiSelect:p,isLoading:ce,allowMultiple:!0,showInactive:t==="edit-queue-item",printerMappingResults:ge.printerResults,filamentReqs:be,onAutoConfigurePrinter:ge.autoConfigurePrinter,onUpdatePrinterConfig:ge.updatePrinterConfig,assignmentMode:t==="reprint"?"printer":E,onAssignmentModeChange:t!=="reprint"?M:void 0,targetModel:j,onTargetModelChange:t!=="reprint"?B:void 0,targetLocation:L,onTargetLocationChange:t!=="reprint"?U:void 0,slicedForModel:Le}),E==="model"&&j&&be&&R&&R.length>0&&a.jsx(z$e,{filamentReqs:be,availableFilaments:R,overrides:D,onChange:$}),Le&&E==="printer"&&f.length===1&&(()=>{const Ee=se?.find(Ve=>Ve.id===f[0]);return Ee&&Ee.model&&Le!==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 ",Le,", but printing on ",Ee.model]})]}):null})(),Pe&&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(Va,{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&&!Pe&&f.length===1&&a.jsx(I$e,{printerId:Se,filamentReqs:be,manualMappings:A,onManualMappingChange:k,defaultExpanded:oe?.per_printer_mapping_expanded??!1,currencySymbol:ie,defaultCostPerKg:me}),(t==="reprint"||ee>0||E==="model"&&j)&&a.jsx(V$e,{options:g,onChange:y}),t!=="reprint"&&a.jsx(q$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:!qe,className:"flex-1",children:we?a.jsxs(a.Fragment,{children:[a.jsx(at,{className:"w-4 h-4 animate-spin"}),nt.loadingText]}):a.jsxs(a.Fragment,{children:[a.jsx(We,{className:"w-4 h-4"}),nt.submitText]})})]})]})]})})})}function W$e({onClose:t,initialFiles:e}){const{t:n}=Rt(),r=Qt(),{showToast:i}=dn(),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=P=>{P.key==="Escape"&&t()};return window.addEventListener("keydown",k),()=>window.removeEventListener("keydown",k)},[t]);const f=it({mutationFn:k=>J.uploadArchivesBulk(k),onSuccess:k=>{h(k),r.invalidateQueries({queryKey:["archives"]}),r.invalidateQueries({queryKey:["archiveStats"]}),l(P=>P.map(C=>{const E=k.results.find(j=>j.filename===C.file.name),M=k.errors.find(j=>j.filename===C.file.name);return E?{...C,status:"success",archiveId:E.id}:M?{...C,status:"error",error:M.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(P=>({...P,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 P=Array.from(k.dataTransfer.files).filter(C=>C.name.endsWith(".3mf"));P.length>0&&l(C=>[...C,...P.map(E=>({file:E,status:"pending"}))])},[]),g=w.useCallback(k=>{const P=Array.from(k.target.files||[]).filter(C=>C.name.endsWith(".3mf"));P.length>0&&l(C=>[...C,...P.map(E=>({file:E,status:"pending"}))]),s.current&&(s.current.value="")},[]),y=w.useCallback(k=>{l(P=>P.filter((C,E)=>E!==k))},[]),_=()=>{if(o.length===0)return;const k=o.filter(P=>P.status==="pending");k.length!==0&&(l(P=>P.map(C=>C.status==="pending"?{...C,status:"uploading"}:C)),f.mutate(k.map(P=>P.file)))},N=o.filter(k=>k.status==="pending").length,A=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(St,{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(Dt,{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(Oa,{className:"w-12 h-12 mx-auto mb-4 text-bambu-gray"}),a.jsx("p",{className:"text-white mb-2",children:n("uploadModal.dragDrop")}),a.jsx("p",{className:"text-bambu-gray text-sm mb-4",children:n("uploadModal.or")}),a.jsx(Me,{variant:"secondary",onClick:()=>s.current?.click(),disabled:A,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,P)=>a.jsxs("div",{className:"flex items-center gap-3 p-3 bg-bambu-dark rounded-lg",children:[a.jsx($C,{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(P),className:"text-bambu-gray hover:text-red-400 transition-colors",disabled:A,children:a.jsx(Dt,{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(yr,{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(Va,{className:"w-4 h-4 text-red-400"})]})]},`${k.file.name}-${P}`))})}),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||A,className:"flex-1",children:A?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(Oa,{className:"w-4 h-4"}),n("uploadModal.upload")," ",N>0&&`(${N})`]})})]})]})})})}const K$e=["adhesionFailure","spaghettiDetached","layerShift","cloggedNozzle","filamentRunout","warping","stringing","underExtrusion","powerFailure","userCancelled","other"],X$e=["completed","failed","aborted","printing"];function Ane({archive:t,onClose:e,existingTags:n=[]}){const{t:r}=Rt();w.useEffect(()=>{const se=ce=>{ce.key==="Escape"&&e()};return window.addEventListener("keydown",se),()=>window.removeEventListener("keydown",se)},[e]);const i=Qt(),[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,A]=w.useState(t.quantity??1),[k,P]=w.useState(t.photos||[]),[C,E]=w.useState(t.external_url||""),[M,j]=w.useState(!1),[B,L]=w.useState(!1),U=w.useRef(null),D=w.useRef(null),$=w.useRef(null),{data:G}=Ye({queryKey:["printers"],queryFn:J.getPrinters}),{data:z}=Ye({queryKey:["projects"],queryFn:()=>J.getProjects()}),{data:W}=Ye({queryKey:["tags"],queryFn:J.getTags,enabled:n.length===0}),K=n.length>0?n:W?.map(se=>se.name)||[],te=p.split(",").map(se=>se.trim()).filter(Boolean),H=p.includes(",")?p.substring(p.lastIndexOf(",")+1).trim().toLowerCase():p.trim().toLowerCase(),Y=K.filter(se=>!te.includes(se)&&(H===""||se.toLowerCase().includes(H))),Z=se=>{let ce;if(H&&!K.includes(H)?ce=p.includes(",")?p.substring(0,p.lastIndexOf(",")).split(",").map(Ce=>Ce.trim()).filter(Boolean):[]:ce=te,!ce.includes(se)){const Ce=[...ce,se].join(", ");x(Ce)}$.current!==null&&clearTimeout($.current),U.current?.focus()},ee=se=>{const ce=te.filter(Ce=>Ce!==se).join(", ");x(ce)},Se=it({mutationFn:se=>J.updateArchive(t.id,se),onSuccess:()=>{i.invalidateQueries({queryKey:["archives"]}),i.invalidateQueries({queryKey:["projects"]}),e()}}),oe=async se=>{const ce=se.target.files?.[0];if(ce){j(!0);try{const Ce=await J.uploadArchivePhoto(t.id,ce);P(Ce.photos),i.invalidateQueries({queryKey:["archives"]})}catch(Ce){console.error("Failed to upload photo:",Ce)}finally{j(!1),D.current&&(D.current.value="")}}},ie=async se=>{try{const ce=await J.deleteArchivePhoto(t.id,se);P(ce.photos||[]),i.invalidateQueries({queryKey:["archives"]})}catch(ce){console.error("Failed to delete photo:",ce)}},me=se=>{se.preventDefault();const ce={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&&(ce.status=y),y==="failed"||y==="aborted"?ce.failure_reason=v||void 0:(t.status==="failed"||t.status==="aborted")&&(ce.failure_reason=null),Se.mutate(ce)};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:se=>se.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(Dt,{className:"w-5 h-5"})})]}),a.jsxs("form",{onSubmit:me,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:se=>o(se.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:se=>c(se.target.value?Number(se.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(se=>a.jsx("option",{value:se.id,children:se.name},se.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:se=>u(se.target.value?Number(se.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")}),z?.map(se=>a.jsx("option",{value:se.id,children:se.name},se.id))]})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[a.jsx(Yme,{className:"w-4 h-4 inline mr-1"}),r("editArchive.itemsPrinted")]}),a.jsx("input",{type:"number",min:1,value:N,onChange:se=>A(Math.max(1,parseInt(se.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:se=>f(se.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(qb,{className:"w-4 h-4 inline mr-1"}),r("editArchive.externalLink")]}),a.jsx("input",{type:"url",value:C,onChange:se=>E(se.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")}),te.length>0&&a.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:te.map(se=>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(qh,{className:"w-3 h-3"}),se,a.jsx("button",{type:"button",onClick:()=>ee(se),className:"ml-0.5 text-bambu-gray hover:text-white",children:a.jsx(Dt,{className:"w-3 h-3"})})]},se))}),a.jsxs("div",{className:"relative",children:[a.jsx("input",{ref:U,type:"text",value:p,onChange:se=>x(se.target.value),onFocus:()=>{$.current!==null&&clearTimeout($.current),L(!0)},onBlur:()=>{$.current=window.setTimeout(()=>L(!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:te.length>0?r("editArchive.addMoreTags"):r("editArchive.tagsPlaceholder")}),B&&Y.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:Y.map(se=>a.jsx("button",{type:"button",onClick:()=>Z(se),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:se},se))})]})]})]}),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:se=>{_(se.target.value),se.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:X$e.map(se=>a.jsx("option",{value:se,children:r(`editArchive.statuses.${se}`)},se))})]}),(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:se=>g(se.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")}),K$e.map(se=>a.jsx("option",{value:r(`editArchive.failureReasons.${se}`),children:r(`editArchive.failureReasons.${se}`)},se))]})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[a.jsx(db,{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(se=>a.jsxs("div",{className:"relative group",children:[a.jsx("img",{src:J.getArchivePhotoUrl(t.id,se),alt:r("editArchive.printResult"),className:"w-20 h-20 object-cover rounded-lg border border-bambu-dark-tertiary"}),a.jsx("button",{type:"button",onClick:()=>ie(se),className:"absolute -top-1 -right-1 p-1 bg-red-500 rounded-full opacity-0 group-hover:opacity-100 transition-opacity",children:a.jsx(Yt,{className:"w-3 h-3 text-white"})})]},se)),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:M}),M?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:Se.isPending,className:"flex-1",children:[a.jsx(bs,{className:"w-4 h-4"}),Se.isPending?r("common.saving"):r("common.save")]})]})]})]})})}function Tne({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 A=t,k=e;t+g.width>y-N&&(A=Math.max(N,y-g.width-N)),A_-N&&(k=Math.max(N,_-g.height-N)),kP),d({x:A,y:k,visible:!0})}},[t,e]);const x=(g,y)=>{l.current&&(clearTimeout(l.current),l.current=null);const _=y.getBoundingClientRect(),N=window.innerHeight,A=300,C=N-_.top-8A;p(E=>({...E,[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(pi,{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,A)=>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]},A))})]},y)})})}function Y$e({selectedIds:t,existingTags:e,onClose:n}){const r=Qt(),{showToast:i}=dn(),[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=it({mutationFn:async()=>{const v=Array.from(l);let g=0;for(const y of t)try{const _=await J.getArchive(y),N=_.tags?_.tags.split(",").map(k=>k.trim()).filter(Boolean):[];let A;d==="add"?A=[...new Set([...N,...v])]:A=N.filter(k=>!l.has(k)),await J.updateArchive(y,{tags:A.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(St,{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(qh,{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(Dt,{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(Dt,{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(qh,{className:"w-4 h-4"}),d==="add"?"Add Tags":"Remove Tags"]})})]})]})})})}function Q$e({selectedIds:t,onClose:e}){const n=Qt(),{showToast:r}=dn(),{data:i,isLoading:s}=Ye({queryKey:["projects"],queryFn:()=>J.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=it({mutationFn:async u=>(await J.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=it({mutationFn:async()=>{for(const u of t)await J.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(St,{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(Dt,{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(mi,{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 Z$e(t,e){return new Date(t,e+1,0).getDate()}function J$e(t,e){return new Date(t,e,1).getDay()}const eVe=["January","February","March","April","May","June","July","August","September","October","November","December"],tVe=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];function nVe({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(P=>{const C=tr(P.completed_at||P.created_at)||new Date,E=`${C.getFullYear()}-${String(C.getMonth()+1).padStart(2,"0")}-${String(C.getDate()).padStart(2,"0")}`,M=k.get(E)||[];M.push(P),k.set(E,M)}),k},[t]),p=Z$e(o,i),x=J$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(Ql,{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:[eVe[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(pi,{className:"w-5 h-5 text-bambu-gray"})})]}),a.jsx("div",{className:"grid grid-cols-7 gap-1 mb-1",children:tVe.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,P)=>{if(k===null)return a.jsx("div",{className:"aspect-square"},`empty-${P}`);const C=`${o}-${String(i+1).padStart(2,"0")}-${String(k).padStart(2,"0")}`,E=f.get(C)||[],M=E.length>0,j=k===r.getDate()&&i===r.getMonth()&&o===r.getFullYear(),B=C===c,L=E.filter(D=>D.status==="completed").length,U=E.filter(D=>D.status==="failed").length;return a.jsxs("button",{onClick:()=>A(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":j?"bg-bambu-green/20 text-white ring-2 ring-bambu-green":M?"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 ${j&&!B?"text-bambu-green":""}`,children:k}),M&&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 ${U>0&&L===0?"bg-red-400":U>0?"bg-yellow-400":"bg-green-400"}`}),a.jsx("span",{className:"text-xs font-medium",children:E.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 P=tr(k.completed_at||k.created_at)||new Date;return P.getMonth()===i&&P.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 P=tr(k.completed_at||k.created_at)||new Date;return P.getMonth()===i&&P.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 P=tr(k.completed_at||k.created_at)||new Date;return P.getMonth()===i&&P.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 P=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 ${P?"":"hover:bg-bambu-dark-tertiary"}`,style:P?{outline:"4px solid #facc15",outlineOffset:"2px"}:void 0,children:[k.thumbnail_path?a.jsx("img",{src:J.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,E)=>a.jsx("div",{className:"w-3 h-3 rounded-full border border-white/20",style:{backgroundColor:C}},E))})]})]})]},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 Mne({archiveId:t,archiveName:e,onClose:n}){const r=J.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(Dt,{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(ga,{className:"w-4 h-4"}),"Download QR Code"]})]})]})})}function Pne({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=J.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(ga,{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(Yt,{className:"w-4 h-4"})}),a.jsx("button",{onClick:r,className:"p-2 text-bambu-gray hover:text-white transition-colors",children:a.jsx(Dt,{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(Ql,{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(pi,{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:J.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 Xi(t){this.content=t}Xi.prototype={constructor:Xi,find:function(t){for(var e=0;e>1}};Xi.from=function(t){if(t instanceof Xi)return t;var e=[];if(t)for(var n in t)e.push(n,t[n]);return new Xi(e)};function jne(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=jne(i.content,s.content,n+1);if(o!=null)return o}n+=i.nodeSize}}function Ene(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 Mt(r,i)}cutByIndex(e,n){return e==n?Mt.empty:e==0&&n==this.content.length?this:new Mt(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 Mt(i,s)}addToStart(e){return new Mt([e].concat(this.content),this.size+e.nodeSize)}addToEnd(e){return new Mt(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 Mt.empty;if(!Array.isArray(n))throw new RangeError("Invalid input for Fragment.fromJSON");return new Mt(n.map(e.nodeFromJSON))}static fromArray(e){if(!e.length)return Mt.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}};Xr.none=[];class VN 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=Rne(this.content,e+this.openStart,n);return r&&new qt(r,this.openStart,this.openEnd)}removeBetween(e,n){return new qt(Dne(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(Mt.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(Mt.empty,0,0);function Dne(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(Dne(s.content,e-i-1,n-i-1)))}function Rne(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=Rne(o.content,e-s-1,n,o);return l&&t.replaceChild(i,o.copy(l))}function rVe(t,e,n){if(n.openStart>t.depth)throw new VN("Inserted content deeper than insertion position");if(t.depth-n.openStart!=e.depth-n.openEnd)throw new VN("Inconsistent open depths");return Fne(t,e,n,0)}function Fne(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 Ky(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&&SR(t,e,i+1),o=r.depth>i&&SR(n,r,i+1),l=[];return Ky(null,t,i,l),s&&o&&e.index(i)==n.index(i)?(Lne(s,o),wf(Sf(s,One(t,e,n,r,i+1)),l)):(s&&wf(Sf(s,qN(t,e,i+1)),l),Ky(e,n,i,l),o&&wf(Sf(o,qN(n,r,i+1)),l)),Ky(r,null,i,l),new Mt(l)}function qN(t,e,n){let r=[];if(Ky(null,t,n,r),t.depth>n){let i=SR(t,e,n+1);wf(Sf(i,qN(t,e,n+1)),r)}return Ky(e,null,n,r),new Mt(r)}function aVe(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(Mt.from(i));return{start:i.resolveNoCache(t.openStart+n),end:i.resolveNoCache(i.content.size-t.openEnd-n)}}class V0{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 GN(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 V0(n,r,s)}static resolveCached(e,n){let r=p9.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()+")"),Ine(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=Mt.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=Mt.fromJSON(e,n.content),s=e.nodeType(n.type).create(n.attrs,i,r);return s.type.checkAttrs(s.attrs),s}};Bh.prototype.text=void 0;class WN extends Bh{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):Ine(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 WN(this.type,this.attrs,this.text,e)}withText(e){return e==this.text?this:new WN(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 Ine(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 lVe(e,n);if(r.next==null)return Kf.empty;let i=zne(r);r.next&&r.err("Unexpected trailing text");let s=pVe(fVe(i));return gVe(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:A("printers:control")?g(Ot?"printers.resume":"printers.pause"):g("printers.permission.noControl"),children:[Ot?a.jsx(oo,{className:"w-3 h-3"}):a.jsx(XC,{className:"w-3 h-3"}),g(Ot?"printers.resume":"printers.pause")]})]})]})]})})(),(Ft?.length>0||pe.vt_tray.length>0)&&r==="expanded"&&(()=>{const bt=Ft.filter(vt=>vt.tray.length>1),Ot=Ft.filter(vt=>vt.tray.length===1),vn=t.nozzle_count===2||pe?.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:[bt.length>0&&a.jsx("div",{className:"grid grid-cols-2 gap-3",children:bt.map(vt=>{const Un=ot[String(vt.id)],Zr=vt.id>=128?vt.id-128:vt.id,Zn=Un!==void 0?Un:Zr,dr=Zn===1,li=Zn===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:nh(vt.id,vt.tray.length)}),vn&&(dr||li)&&a.jsx(s9,{side:dr?"L":"R"})]}),(vt.humidity!=null||vt.temp!=null)&&a.jsxs("div",{className:"flex items-center gap-1.5 max-[550px]:flex-col max-[550px]:items-start",children:[vt.humidity!=null&&a.jsx(l9,{humidity:vt.humidity,goodThreshold:s?.humidityGood,fairThreshold:s?.humidityFair,onClick:()=>le({amsId:vt.id,amsLabel:nh(vt.id,vt.tray.length),mode:"humidity"}),compact:!0}),vt.temp!=null&&a.jsx(c9,{temp:vt.temp,goodThreshold:s?.tempGood,fairThreshold:s?.tempFair,onClick:()=>le({amsId:vt.id,amsLabel:nh(vt.id,vt.tray.length),mode:"temperature"}),compact:!0})]})]}),a.jsx("div",{className:"grid grid-cols-4 gap-1.5",children:[0,1,2,3].map(rn=>{const Pn=vt.tray[rn]||vt.tray.find($n=>$n.id===rn),Ci=Pn?.tray_type&&Pn.remain>=0,Bs=!Pn?.tray_type,zo=vt.id*4+rn,Uo=Be===zo,zi=Pn?.tray_info_idx?qe?.[Pn.tray_info_idx]:null,Dr=ke?.[zo],Hs=Pn?.tray_uuid?.toUpperCase(),Ca=Hs?c?.[Hs]:void 0,Jr=Kj(Ca),is=u?.(t.id,vt.id,rn),ur=(()=>{const $n=is?.spool;return $n&&$n.label_weight>0&&$n.weight_used!=null?Math.round(Math.max(0,$n.label_weight-$n.weight_used)/$n.label_weight*100):null})(),Ui=Jr??ur??(Ci?Pn.remain:null),jl=Jr!==null?"spoolman":ur!==null?"inventory":Ci?"ams":void 0,Cr=Pn?.tray_type?{vendor:Xj(Pn)?"Bambu Lab":"Generic",profile:zi?.name||Dr?.preset_name||Pn.tray_sub_brands||Pn.tray_type,colorName:$j(Pn.tray_id_name)||Vj(Pn.tray_color),colorHex:Pn.tray_color||null,kFactor:qj(Pn.k),fillLevel:Ui,trayUuid:Pn.tray_uuid||null,tagUid:Pn.tag_uid||null,fillSource:jl}:null,Xt=gt?.amsId===vt.id&>?.slotId===rn,ya=a.jsxs("div",{className:`bg-bambu-dark-tertiary rounded p-1 text-center ${Bs?"opacity-50":""} ${Uo?"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:Pn?.tray_color?`#${Pn.tray_color}`:Pn?.tray_type?"#333":"transparent",borderColor:Bs?"#666":"rgba(255,255,255,0.1)",borderStyle:Bs?"dashed":"solid"}}),a.jsx("div",{className:"text-[9px] text-white font-bold truncate",children:Pn?.tray_type||"—"}),a.jsx("div",{className:"mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden",children:Ui!==null&&Ui>=0&&Pn&&a.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${Ui}%`,backgroundColor:Wj(Ui)}})})]});return a.jsxs("div",{className:"relative group",children:[Xt&&a.jsx("div",{className:"absolute inset-0 bg-bambu-dark-tertiary/80 rounded flex items-center justify-center z-20",children:a.jsx(Sr,{className:"w-4 h-4 text-bambu-green animate-spin"})}),pe?.state!=="RUNNING"&&a.jsx("button",{onClick:$n=>{$n.stopPropagation(),Qn(vr?.amsId===vt.id&&vr?.slotId===rn?null:{amsId:vt.id,slotId:rn})},className:"absolute -top-1 -right-1 w-4 h-4 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity z-10 hover:bg-bambu-dark-tertiary",title:g("printers.slotOptions"),children:a.jsx(Mh,{className:"w-2.5 h-2.5 text-bambu-gray"})}),pe?.state!=="RUNNING"&&vr?.amsId===vt.id&&vr?.slotId===rn&&a.jsx("div",{className:"absolute top-full left-0 mt-1 z-50 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl py-1 min-w-[120px]",children:a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-xs flex items-center gap-2 ${A("printers:ams_rfid")?"text-white hover:bg-bambu-dark-tertiary":"text-bambu-gray/50 cursor-not-allowed"}`,onClick:$n=>{$n.stopPropagation(),A("printers:ams_rfid")&&(Pt.mutate({amsId:vt.id,slotId:rn}),Qn(null))},disabled:Xt||!A("printers:ams_rfid"),title:A("printers:ams_rfid")?void 0:g("printers.permission.noAmsRfid"),children:[a.jsx(Sr,{className:`w-3 h-3 ${Xt?"animate-spin":""}`}),g("printers.rfid.reread")]})}),Cr?a.jsx(Bj,{data:Cr,spoolman:{enabled:o,hasUnlinkedSpools:l,linkedSpoolId:Cr.trayUuid?c?.[Cr.trayUuid.toUpperCase()]?.id:void 0,spoolmanUrl:d,onLinkSpool:o&&Cr.trayUuid?$n=>{V({tagUid:Cr.tagUid||"",trayUuid:$n,printerId:t.id,amsId:vt.id,trayId:rn})}:void 0},inventory:o?void 0:(()=>{const $n=u?.(t.id,vt.id,rn);return{assignedSpool:$n?.spool?{id:$n.spool.id,material:$n.spool.material,brand:$n.spool.brand,color_name:$n.spool.color_name,remainingWeightGrams:Math.max(0,Math.round($n.spool.label_weight-$n.spool.weight_used))}:null,onAssignSpool:Cr.vendor!=="Bambu Lab"?()=>fe({printerId:t.id,amsId:vt.id,trayId:rn,trayInfo:{type:Cr.profile,color:Cr.colorHex||"",location:`${nh(vt.id,vt.tray.length)} Slot ${rn+1}`}}):void 0,onUnassignSpool:$n&&Cr.vendor!=="Bambu Lab"?()=>h?.(t.id,vt.id,rn):void 0}})(),configureSlot:{enabled:A("printers:control"),onConfigure:()=>re({amsId:vt.id,trayId:rn,trayCount:vt.tray.length,trayType:Pn?.tray_type||void 0,trayColor:Pn?.tray_color||void 0,traySubBrands:Pn?.tray_sub_brands||void 0,trayInfoIdx:Pn?.tray_info_idx||void 0,extruderId:Un,caliIdx:Pn?.cali_idx,savedPresetId:Dr?.preset_id})},children:ya}):a.jsx(Hj,{configureSlot:{enabled:A("printers:control"),onConfigure:()=>re({amsId:vt.id,trayId:rn,trayCount:vt.tray.length,extruderId:Un})},children:ya})]},rn)})})]},vt.id)})}),(Ot.length>0||pe.vt_tray.length>0)&&a.jsxs("div",{className:"grid grid-cols-4 gap-3",children:[Ot.map(vt=>{const Un=ot[String(vt.id)],Zr=vt.id>=128?vt.id-128:vt.id,Zn=Un!==void 0?Un:Zr,dr=Zn===1,li=Zn===0,rn=vt.tray[0],Pn=rn?.tray_type&&rn.remain>=0,Ci=!rn?.tray_type,Bs=BN(vt.id,rn?.id??0,!1),zo=Be===Bs,Uo=rn?.tray_info_idx?qe?.[rn.tray_info_idx]:null,zi=ke?.[Bs],Dr=rn?.tray_uuid?.toUpperCase(),Hs=Dr?c?.[Dr]:void 0,Ca=Kj(Hs),Jr=rn?.id??0,is=u?.(t.id,vt.id,Jr),ur=(()=>{const kr=is?.spool;return kr&&kr.label_weight>0&&kr.weight_used!=null?Math.round(Math.max(0,kr.label_weight-kr.weight_used)/kr.label_weight*100):null})(),Ui=Ca??ur??(Pn?rn.remain:null),jl=Ca!==null?"spoolman":ur!==null?"inventory":Pn?"ams":void 0,Cr=rn?.tray_type?{vendor:Xj(rn)?"Bambu Lab":"Generic",profile:Uo?.name||zi?.preset_name||rn.tray_sub_brands||rn.tray_type,colorName:$j(rn.tray_id_name)||Vj(rn.tray_color),colorHex:rn.tray_color||null,kFactor:qj(rn.k),fillLevel:Ui,trayUuid:rn.tray_uuid||null,tagUid:rn.tag_uid||null,fillSource:jl}:null,Xt=rn?.id??0,ya=gt?.amsId===vt.id&>?.slotId===Xt,$n=a.jsxs("div",{className:`bg-bambu-dark-tertiary rounded p-1 text-center ${Ci?"opacity-50":""} ${zo?"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:rn?.tray_color?`#${rn.tray_color}`:rn?.tray_type?"#333":"transparent",borderColor:Ci?"#666":"rgba(255,255,255,0.1)",borderStyle:Ci?"dashed":"solid"}}),a.jsx("div",{className:"text-[9px] text-white font-bold truncate",children:rn?.tray_type||"—"}),a.jsx("div",{className:"mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden",children:Ui!==null&&Ui>=0&&a.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${Ui}%`,backgroundColor:Wj(Ui)}})})]});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:nh(vt.id,vt.tray.length)}),vn&&(dr||li)&&a.jsx(s9,{side:dr?"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:[ya&&a.jsx("div",{className:"absolute inset-0 bg-bambu-dark-tertiary/80 rounded flex items-center justify-center z-20",children:a.jsx(Sr,{className:"w-4 h-4 text-bambu-green animate-spin"})}),pe?.state!=="RUNNING"&&a.jsx("button",{onClick:kr=>{kr.stopPropagation(),Qn(vr?.amsId===vt.id&&vr?.slotId===Xt?null:{amsId:vt.id,slotId:Xt})},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(Mh,{className:"w-2.5 h-2.5 text-bambu-gray"})}),pe?.state!=="RUNNING"&&vr?.amsId===vt.id&&vr?.slotId===Xt&&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 ${A("printers:ams_rfid")?"text-white hover:bg-bambu-dark-tertiary":"text-bambu-gray/50 cursor-not-allowed"}`,onClick:kr=>{kr.stopPropagation(),A("printers:ams_rfid")&&(Pt.mutate({amsId:vt.id,slotId:Xt}),Qn(null))},disabled:ya||!A("printers:ams_rfid"),title:A("printers:ams_rfid")?void 0:g("printers.permission.noAmsRfid"),children:[a.jsx(Sr,{className:`w-3 h-3 ${ya?"animate-spin":""}`}),g("printers.rfid.reread")]})}),Cr?a.jsx(Bj,{data:Cr,spoolman:{enabled:o,hasUnlinkedSpools:l,linkedSpoolId:Cr.trayUuid?c?.[Cr.trayUuid.toUpperCase()]?.id:void 0,spoolmanUrl:d,onLinkSpool:o&&Cr.trayUuid?kr=>{V({tagUid:Cr.tagUid||"",trayUuid:kr,printerId:t.id,amsId:vt.id,trayId:Xt})}:void 0},inventory:o?void 0:(()=>{const kr=u?.(t.id,vt.id,Xt);return{assignedSpool:kr?.spool?{id:kr.spool.id,material:kr.spool.material,brand:kr.spool.brand,color_name:kr.spool.color_name,remainingWeightGrams:Math.max(0,Math.round(kr.spool.label_weight-kr.spool.weight_used))}:null,onAssignSpool:Cr.vendor!=="Bambu Lab"?()=>fe({printerId:t.id,amsId:vt.id,trayId:Xt,trayInfo:{type:Cr.profile,color:Cr.colorHex||"",location:nh(vt.id,vt.tray.length)}}):void 0,onUnassignSpool:kr&&Cr.vendor!=="Bambu Lab"?()=>h?.(t.id,vt.id,Xt):void 0}})(),configureSlot:{enabled:A("printers:control"),onConfigure:()=>re({amsId:vt.id,trayId:Xt,trayCount:vt.tray.length,trayType:rn?.tray_type||void 0,trayColor:rn?.tray_color||void 0,traySubBrands:rn?.tray_sub_brands||void 0,trayInfoIdx:rn?.tray_info_idx||void 0,extruderId:Un,caliIdx:rn?.cali_idx,savedPresetId:zi?.preset_id})},children:$n}):a.jsx(Hj,{configureSlot:{enabled:A("printers:control"),onConfigure:()=>re({amsId:vt.id,trayId:Xt,trayCount:vt.tray.length,extruderId:Un})},children:$n})]}),(vt.humidity!=null||vt.temp!=null)&&a.jsxs("div",{className:"flex flex-col justify-center gap-1 shrink-0 max-[550px]:w-full",children:[vt.temp!=null&&a.jsx(c9,{temp:vt.temp,goodThreshold:s?.tempGood,fairThreshold:s?.tempFair,onClick:()=>le({amsId:vt.id,amsLabel:nh(vt.id,vt.tray.length),mode:"temperature"}),compact:!0}),vt.humidity!=null&&a.jsx(l9,{humidity:vt.humidity,goodThreshold:s?.humidityGood,fairThreshold:s?.humidityFair,onClick:()=>le({amsId:vt.id,amsLabel:nh(vt.id,vt.tray.length),mode:"humidity"}),compact:!0})]})]})]},vt.id)}),pe.vt_tray.length>0&&a.jsxs("div",{className:`p-2.5 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary/30 ${pe.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 ${pe.vt_tray.length>1?"grid-cols-2":"grid-cols-1"} gap-1.5`,children:[...pe.vt_tray].sort((vt,Un)=>(vt.id??254)-(Un.id??254)).map(vt=>{const Un=vt.id??254,Zr=vn&&Be===254?Un===254&&pe.active_extruder===1||Un===255&&pe.active_extruder===0:Be===Un,Zn=Un-254,dr=vn?g(Un===254?"printers.extL":"printers.extR"):"",li=vt.tray_info_idx?qe?.[vt.tray_info_idx]:null,rn=ke?.[1020+Zn],Pn=vt.tray_uuid?.toUpperCase(),Ci=Pn?c?.[Pn]:void 0,Bs=Kj(Ci),zo=u?.(t.id,255,Zn),Uo=(()=>{const ur=zo?.spool;return ur&&ur.label_weight>0&&ur.weight_used!=null?Math.round(Math.max(0,ur.label_weight-ur.weight_used)/ur.label_weight*100):null})(),zi=vt.tray_type&&vt.remain>=0,Dr=Bs??Uo??(zi?vt.remain:null),Hs=Bs!==null?"spoolman":Uo!==null?"inventory":zi?"ams":void 0,Ca={vendor:Xj(vt)?"Bambu Lab":"Generic",profile:li?.name||rn?.preset_name||vt.tray_sub_brands||vt.tray_type||"Unknown",colorName:$j(vt.tray_id_name)||Vj(vt.tray_color),colorHex:vt.tray_color||null,kFactor:qj(vt.k),fillLevel:Dr,trayUuid:vt.tray_uuid||null,tagUid:vt.tag_uid||null,fillSource:Hs},Jr=!vt.tray_type,is=a.jsxs("div",{className:`bg-bambu-dark-tertiary rounded p-1 text-center ${Jr?"opacity-50":""} ${Zr?"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:vt.tray_color?`#${vt.tray_color}`:vt.tray_type?"#333":"transparent",borderColor:Jr?"#666":"rgba(255,255,255,0.1)",borderStyle:Jr?"dashed":"solid"}}),a.jsx("div",{className:`text-[9px] font-bold truncate ${Jr?"text-white/40":"text-white"}`,children:vt.tray_type||"—"}),a.jsx("div",{className:"mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden",children:Dr!==null&&Dr>=0&&!Jr&&a.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${Dr}%`,backgroundColor:Wj(Dr)}})}),dr&&a.jsx("div",{className:"text-[7px] text-white/40 mt-0.5 truncate",children:dr})]});return a.jsx("div",{className:"relative group",children:Jr?a.jsx(Hj,{configureSlot:{enabled:A("printers:control"),onConfigure:()=>re({amsId:255,trayId:Zn,trayCount:1,extruderId:vn?Un===254?1:0:void 0})},children:is}):a.jsx(Bj,{data:Ca,spoolman:{enabled:o,hasUnlinkedSpools:l,linkedSpoolId:Ca.trayUuid?c?.[Ca.trayUuid.toUpperCase()]?.id:void 0,spoolmanUrl:d,onLinkSpool:o&&Ca.trayUuid?ur=>{V({tagUid:Ca.tagUid||"",trayUuid:ur,printerId:t.id,amsId:255,trayId:Zn})}:void 0},inventory:o?void 0:(()=>{const ur=u?.(t.id,255,Zn);return{assignedSpool:ur?.spool?{id:ur.spool.id,material:ur.spool.material,brand:ur.spool.brand,color_name:ur.spool.color_name,remainingWeightGrams:Math.max(0,Math.round(ur.spool.label_weight-ur.spool.weight_used))}:null,onAssignSpool:()=>fe({printerId:t.id,amsId:255,trayId:Zn,trayInfo:{type:Ca.profile,color:Ca.colorHex||"",location:dr||g("printers.external")}}),onUnassignSpool:ur?()=>h?.(t.id,255,Zn):void 0}})(),configureSlot:{enabled:A("printers:control"),onConfigure:()=>re({amsId:255,trayId:Zn,trayCount:1,trayType:vt.tray_type||void 0,trayColor:vt.tray_color||void 0,traySubBrands:vt.tray_sub_brands||void 0,trayInfoIdx:vt.tray_info_idx||void 0,extruderId:vn?Un===254?1:0:void 0,caliIdx:vt.cali_idx,savedPresetId:rn?.preset_id})},children:is})},Un)})})]})]})]})]})})()]}),mt&&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(ru,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}),a.jsx("span",{className:"text-sm text-white truncate",children:mt.name}),zt&&a.jsxs("span",{className:`text-xs px-1.5 py-0.5 rounded flex-shrink-0 ${zt.state==="ON"?"bg-bambu-green/20 text-bambu-green":zt.state==="OFF"?"bg-red-500/20 text-red-400":"bg-bambu-gray/20 text-bambu-gray"}`,children:[zt.state||"?",zt.state==="ON"&&zt.energy?.power!=null&&a.jsxs("span",{className:"text-yellow-400 ml-1.5",children:["· ",zt.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:tt.isPending||zt?.state==="ON"||!A("smart_plugs:control"),className:`px-2 py-1 text-xs rounded transition-colors flex items-center gap-1 ${A("smart_plugs:control")?zt?.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:A("smart_plugs:control")?void 0:g("printers.permission.noSmartPlugControl"),children:[a.jsx(fu,{className:"w-3 h-3"}),"On"]}),a.jsxs("button",{onClick:()=>te(!0),disabled:tt.isPending||zt?.state==="OFF"||!A("smart_plugs:control"),className:`px-2 py-1 text-xs rounded transition-colors flex items-center gap-1 ${A("smart_plugs:control")?zt?.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:A("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 ${mt.auto_off_executed?"text-bambu-green":"text-bambu-gray"}`,children:mt.auto_off_executed?"Auto-off done":"Auto-off"}),a.jsx("button",{onClick:()=>st.mutate(!mt.auto_off),disabled:st.isPending||mt.auto_off_executed||!A("smart_plugs:control"),title:A("smart_plugs:control")?mt.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 ${A("smart_plugs:control")?mt.auto_off_executed?"bg-bambu-green/50 cursor-not-allowed":mt.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 ${mt.auto_off||mt.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(dv,{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(bt=>a.jsxs("button",{onClick:()=>Ke.mutate(bt.id),disabled:Ke.isPending,title:`Run ${bt.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(oo,{className:"w-2.5 h-2.5"}),bt.name]},bt.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:()=>Qe.mutate(!pe?.chamber_light),disabled:!pe?.connected||Qe.isPending||!A("printers:control"),title:A("printers:control")?pe?.chamber_light?g("printers.chamberLightOff"):g("printers.chamberLightOn"):g("printers.permission.noControl"),className:pe?.chamber_light?"bg-yellow-500/20 hover:bg-yellow-500/30 border-yellow-500/30":"",children:a.jsx(dL,{on:pe?.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 bt=localStorage.getItem("cameraWindowState"),Ot=bt?JSON.parse(bt):{width:640,height:400},vn=[`width=${Ot.width}`,`height=${Ot.height}`,Ot.left!==void 0?`left=${Ot.left}`:"",Ot.top!==void 0?`top=${Ot.top}`:"","menubar=no,toolbar=no,location=no,status=no,noopener"].filter(Boolean).join(",");window.open(`/camera/${t.id}`,`camera-${t.id}`,vn)}},disabled:!pe?.connected||!A("camera:view"),title:A("camera:view")?g(p==="embedded"?"printers.openCameraOverlay":"printers.openCameraWindow"):g("printers.permission.noCamera"),children:a.jsx(EF,{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:Zt,disabled:!pe?.connected||Xe.isPending||!A("printers:update"),title:A("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:fn,disabled:!pe?.connected||O||!A("printers:update"),title:A("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:O?a.jsx(at,{className:"w-3 h-3 animate-spin"}):a.jsx(Mn,{className:"w-3 h-3"})})]}),a.jsxs(Me,{variant:"secondary",size:"sm",onClick:()=>D(!0),disabled:!A("printers:files"),title:A("printers:files")?g("printers.browseFiles"):g("printers.permission.noFiles"),children:[a.jsx(Vb,{className:"w-4 h-4"}),"Files"]})]})]})]}),U&&a.jsx(LTe,{printerId:t.id,printerName:t.name,onClose:()=>D(!1)}),$&&a.jsx(HTe,{printerId:t.id,printerName:t.name,onClose:()=>G(!1)}),Pe&&a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onClick:()=>un(),children:a.jsxs("div",{className:"bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl max-w-lg w-full",onClick:bt=>bt.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:[Pe.needs_calibration?a.jsx(_1,{className:"w-5 h-5 text-blue-500"}):Pe.is_empty?a.jsx(yr,{className:"w-5 h-5 text-green-500"}):a.jsx(mi,{className:"w-5 h-5 text-yellow-500"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:"Build Plate Check"}),Pe.reference_count!==void 0&&Pe.max_references&&a.jsxs("span",{className:"text-xs text-bambu-gray bg-bambu-dark-tertiary px-2 py-1 rounded",children:[Pe.reference_count,"/",Pe.max_references," refs"]})]}),a.jsx("button",{onClick:()=>un(),className:"p-1 text-bambu-gray hover:text-white rounded transition-colors",children:a.jsx(Dt,{className:"w-5 h-5"})})]}),a.jsxs("div",{className:"p-4 space-y-4",children:[Pe.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 ${Pe.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 ${Pe.is_empty?"text-green-400":"text-yellow-400"}`,children:Pe.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(Pe.confidence*100),"% | ",g("printers.plateDetection.difference"),": ",Pe.difference_percent.toFixed(1),"%"]})]}),Pe.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:Pe.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:Pe.message})]}),tn&&tn.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:tn.references.length,max:tn.max_references})}),a.jsx("div",{className:"grid grid-cols-5 gap-2",children:tn.references.map(bt=>a.jsxs("div",{className:"relative group",children:[a.jsx("img",{src:J.getPlateReferenceThumbnailUrl(t.id,bt.index),alt:bt.label||`Reference ${bt.index+1}`,className:"w-full aspect-video object-cover rounded border border-bambu-dark-tertiary"}),a.jsx("button",{onClick:()=>lr(bt.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(Dt,{className:"w-3 h-3 text-white"})}),on?.index===bt.index?a.jsx("input",{type:"text",value:on.label,onChange:Ot=>gn({...on,label:Ot.target.value}),onBlur:()=>pn(bt.index,on.label),onKeyDown:Ot=>{Ot.key==="Enter"&&pn(bt.index,on.label),Ot.key==="Escape"&&gn(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:()=>gn({index:bt.index,label:bt.label}),title:bt.label?g("printers.plateDetection.clickToEdit",{label:bt.label}):g("printers.plateDetection.clickToAddLabel"),children:bt.label||a.jsx("span",{className:"italic opacity-50",children:g("printers.noLabel")})}),a.jsx("p",{className:"text-[10px] text-bambu-gray/60",children:bt.timestamp?tr(bt.timestamp)?.toLocaleDateString()??"":""})]},bt.index))})]}),!Pe.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")}),ge?a.jsxs("div",{className:"flex gap-1",children:[a.jsx(Me,{variant:"ghost",size:"sm",onClick:()=>ae(null),disabled:Ue,children:g("common.cancel")}),a.jsx(Me,{size:"sm",onClick:as,disabled:Ue,children:Ue?a.jsx(at,{className:"w-3 h-3 animate-spin"}):g("common.save")})]}):a.jsxs(Me,{variant:"ghost",size:"sm",onClick:()=>ae(Pe.roi||{x:.15,y:.35,w:.7,h:.55}),children:[a.jsx(Ga,{className:"w-3 h-3 mr-1"}),g("common.edit")]})]}),ge?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:ge.x,onChange:bt=>ae({...ge,x:parseFloat(bt.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(ge.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:ge.y,onChange:bt=>ae({...ge,y:parseFloat(bt.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(ge.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:ge.w,onChange:bt=>ae({...ge,w:parseFloat(bt.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(ge.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:ge.h,onChange:bt=>ae({...ge,h:parseFloat(bt.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(ge.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((Pe.roi?.x||.15)*100),"%, Y=",Math.round((Pe.roi?.y||.35)*100),"%, W=",Math.round((Pe.roi?.w||.7)*100),"%, H=",Math.round((Pe.roi?.h||.55)*100),"%"]})]})]}),a.jsx("div",{className:"flex justify-end gap-2 p-4 border-t border-bambu-dark-tertiary",children:Pe.needs_calibration?a.jsxs(a.Fragment,{children:[a.jsx(Me,{variant:"ghost",onClick:()=>un(),children:g("common.cancel")}),a.jsx(Me,{onClick:()=>Gr(),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:()=>Gr(),disabled:q,children:q?"Adding...":`Add Reference (${tn?.references.length||0}/${tn?.max_references||5})`}),a.jsx(Me,{onClick:()=>un(),children:"Close"})]})})]})}),z&&mt&&a.jsx(xn,{title:g("printers.confirm.powerOnTitle"),message:g("printers.confirm.powerOnMessage",{name:t.name}),confirmText:g("printers.confirm.powerOnButton"),variant:"default",onConfirm:()=>{tt.mutate("on"),W(!1)},onCancel:()=>W(!1)}),K&&mt&&a.jsx(xn,{title:g("printers.confirm.powerOffTitle"),message:pe?.state==="RUNNING"?g("printers.confirm.powerOffWarning",{name:t.name}):g("printers.confirm.powerOffMessage",{name:t.name}),confirmText:g("printers.confirm.powerOffButton"),variant:"danger",onConfirm:()=>{tt.mutate("off"),te(!1)},onCancel:()=>te(!1)}),Z&&a.jsx(xn,{title:g("printers.confirm.stopTitle"),message:g("printers.confirm.stopMessage",{name:t.name}),confirmText:g("printers.confirm.stopButton"),variant:"danger",onConfirm:()=>{Lt.mutate(),ee(!1)},onCancel:()=>ee(!1)}),Se&&a.jsx(xn,{title:g("printers.confirm.pauseTitle"),message:g("printers.confirm.pauseMessage",{name:t.name}),confirmText:g("printers.confirm.pauseButton"),variant:"default",onConfirm:()=>{ye.mutate(),oe(!1)},onCancel:()=>oe(!1)}),ie&&a.jsx(xn,{title:g("printers.confirm.resumeTitle"),message:g("printers.confirm.resumeMessage",{name:t.name}),confirmText:g("printers.confirm.resumeButton"),variant:"default",onConfirm:()=>{He.mutate(),me(!1)},onCancel:()=>me(!1)}),a.jsx(uL,{printerId:t.id,isOpen:se,onClose:()=>ce(!1)}),H&&a.jsx(GTe,{printerName:t.name,errors:pe?.hms_errors||[],onClose:()=>Y(!1),printerId:t.id,hasPermission:A}),Ce&&a.jsx(a$e,{isOpen:!!Ce,onClose:()=>le(null),printerId:t.id,printerName:t.name,amsId:Ce.amsId,amsLabel:Ce.amsLabel,initialMode:Ce.mode,thresholds:s}),Le&&a.jsx(i$e,{isOpen:!!Le,onClose:()=>V(null),tagUid:Le.tagUid,trayUuid:Le.trayUuid,printerId:Le.printerId,amsId:Le.amsId,trayId:Le.trayId}),X&&a.jsx(s$e,{isOpen:!!X,onClose:()=>fe(null),printerId:X.printerId,amsId:X.amsId,trayId:X.trayId,trayInfo:X.trayInfo}),Q&&a.jsx(wne,{isOpen:!!Q,onClose:()=>re(null),printerId:t.id,slotInfo:Q,printerModel:vR(t.model)||void 0,onSuccess:()=>{y.invalidateQueries({queryKey:["slotPresets",t.id]}),y.invalidateQueries({queryKey:["printerStatus",t.id]})}}),B&&a.jsx(k$e,{printer:t,onClose:()=>L(!1)}),ue&&ve&&a.jsx(C$e,{printer:t,firmwareInfo:ve,onClose:()=>Fe(!1)}),vr&&a.jsx("div",{className:"fixed inset-0 z-40",onClick:()=>Qn(null)})]})}function N$e({onClose:t,onAdd:e,existingSerials:n}){const{t:r}=Rt(),[i,s]=w.useState({name:"",serial_number:"",ip_address:"",access_code:"",model:"",location:"",auto_archive:!0}),[o,l]=w.useState(!1),[c,d]=w.useState([]),[u,h]=w.useState(""),[f,p]=w.useState(!1),[x,v]=w.useState(!1),[g,y]=w.useState([]),[_,N]=w.useState(""),[A,k]=w.useState({scanned:0,total:0});w.useEffect(()=>{hc.getInfo().then(M=>{v(M.is_docker),M.subnets.length>0&&(y(M.subnets),N(M.subnets[0]))}).catch(()=>{})},[]);const P=c.filter(M=>!n.includes(M.serial)),C=async()=>{h(""),d([]),l(!0),p(!1),k({scanned:0,total:0});try{if(x){await hc.startSubnetScan(_);const M=setInterval(async()=>{try{const j=await hc.getScanStatus();k({scanned:j.scanned,total:j.total});const B=await hc.getDiscoveredPrinters();d(B),j.running||(clearInterval(M),l(!1),p(!0))}catch(j){console.error("Failed to get scan status:",j)}},500)}else{await hc.startDiscovery(10);const M=setInterval(async()=>{try{const j=await hc.getDiscoveredPrinters();d(j)}catch(j){console.error("Failed to get discovered printers:",j)}},1e3);setTimeout(async()=>{clearInterval(M);try{await hc.stopDiscovery()}catch{}l(!1),p(!0);try{const j=await hc.getDiscoveredPrinters();d(j)}catch(j){console.error("Failed to get final discovered printers:",j)}},1e4)}}catch(M){console.error("Failed to start discovery:",M),h(M instanceof Error?M.message:r("printers.discovery.failedToStart")),l(!1),p(!0)}},E=M=>{const j=M.serial.startsWith("unknown-")?"":M.serial;s({...i,name:M.name||"",serial_number:j,ip_address:M.ip_address,model:vR(M.model)}),d([])};return w.useEffect(()=>()=>{hc.stopDiscovery().catch(()=>{}),hc.stopSubnetScan().catch(()=>{})},[]),w.useEffect(()=>{const M=j=>{j.key==="Escape"&&t()};return window.addEventListener("keydown",M),()=>window.removeEventListener("keydown",M)},[t]),a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",onClick:t,children:a.jsx(St,{className:"w-full max-w-md",onClick:M=>M.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:M=>N(M.target.value),disabled:o,children:g.map(M=>a.jsx("option",{value:M,children:M},M))}):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:M=>N(M.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&&A.total>0?r("printers.discovery.scanProgress",{scanned:A.scanned,total:A.total}):r("printers.discovery.scanning")]}):a.jsxs(a.Fragment,{children:[a.jsx(jr,{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}),P.length>0&&a.jsx("div",{className:"mt-3 space-y-2 max-h-40 overflow-y-auto",children:P.map(M=>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:()=>E(M),children:[a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:"font-medium text-white text-sm truncate",children:M.name||M.serial}),a.jsxs("p",{className:"text-xs text-bambu-gray truncate",children:[vR(M.model)||r("printers.discovery.unknown")," • ",M.ip_address,M.serial.startsWith("unknown-")&&a.jsxs("span",{className:"text-yellow-500",children:[" • ",r("printers.discovery.serialRequired")]})]})]}),a.jsx(Mn,{className:"w-4 h-4 text-bambu-gray -rotate-90 flex-shrink-0 ml-2"})]},M.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&&P.length===0&&a.jsx("p",{className:"mt-2 text-sm text-bambu-gray text-center",children:r("printers.discovery.allConfigured")})]}),a.jsxs("form",{onSubmit:M=>{M.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:M=>s({...i,name:M.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:M=>s({...i,ip_address:M.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:M=>s({...i,serial_number:M.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:M=>s({...i,access_code:M.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:M=>s({...i,model:M.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:M=>s({...i,location:M.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:M=>s({...i,auto_archive:M.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 C$e({printer:t,firmwareInfo:e,onClose:n}){const{t:r}=Rt(),i=Qt(),{showToast:s}=dn(),{hasPermission:o}=Er(),l=o("firmware:update"),[c,d]=w.useState(null),[u,h]=w.useState(!1),[f,p]=w.useState(null),{data:x,isLoading:v}=Ye({queryKey:["firmwarePrepare",t.id],queryFn:()=>B_.prepareUpload(t.id),staleTime:3e4,enabled:e.update_available&&l}),g=it({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(St,{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(ga,{className:"w-5 h-5 text-orange-400"}):a.jsx(yr,{className:"w-5 h-5 text-status-ok"})}),a.jsxs("div",{className:"flex-1",children:[a.jsx("h3",{className:"text-lg font-semibold text-white",children:e.update_available?r("printers.firmwareModal.title"):r("printers.firmwareModal.titleUpToDate")}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:t.name})]})]}),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(ei,{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(Va,{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(ga,{className:"w-4 h-4 mr-2"}),r("printers.firmwareModal.uploadFirmware")]})})]})]})})})}function k$e({printer:t,onClose:e}){const{t:n}=Rt(),r=Qt(),{showToast:i}=dn(),[s,o]=w.useState({name:t.name,ip_address:t.ip_address,access_code:"",model:t.model||"",location:t.location||"",auto_archive:t.auto_archive}),l=it({mutationFn:d=>J.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(St,{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 A$e(t){const{data:e}=Ye({queryKey:["printerStatus",t],queryFn:()=>J.getPrinterStatus(t),refetchInterval:3e4});return!e?.connected}function T$e({printer:t,plug:e,onPowerOn:n,isPowering:r}){const i=A$e(t.id),{data:s}=Ye({queryKey:["smartPlugStatus",e.id],queryFn:()=>J.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(fu,{className:"w-3 h-3"}),r?"...":"On"]})]}):null}function M$e(){const{t}=Rt(),[e,n]=w.useState(!1),[r,i]=w.useState(()=>localStorage.getItem("hideDisconnectedPrinters")==="true"),[s,o]=w.useState(!1),[l,c]=w.useState(null),[d,u]=w.useState(()=>localStorage.getItem("printerSortBy")||"name"),[h,f]=w.useState(()=>localStorage.getItem("printerSortAsc")!=="false"),[p,x]=w.useState(()=>{const ce=localStorage.getItem("printerCardSize");return ce?parseInt(ce,10):2}),v=p===1?"compact":"expanded",g=Qt(),{showToast:y}=dn(),{hasPermission:_}=Er(),[N,A]=w.useState(()=>{const ce=localStorage.getItem("openEmbeddedCameras");if(ce)try{const Ce=JSON.parse(ce);return new Map(Ce.map(le=>[le.id,le]))}catch{return new Map}return new Map});w.useEffect(()=>{const ce=Array.from(N.values());ce.length>0?localStorage.setItem("openEmbeddedCameras",JSON.stringify(ce)):localStorage.removeItem("openEmbeddedCameras")},[N]);const{data:k,isLoading:P}=Ye({queryKey:["printers"],queryFn:J.getPrinters}),{data:C}=Ye({queryKey:["settings"],queryFn:J.getSettings});w.useEffect(()=>{C?.camera_view_mode==="window"&&N.size>0&&A(new Map)},[C?.camera_view_mode,N.size]);const{data:E}=Ye({queryKey:["smart-plugs"],queryFn:J.getSmartPlugs}),{data:M}=Ye({queryKey:["maintenanceOverview"],queryFn:J.getMaintenanceOverview,staleTime:60*1e3}),{data:j}=Ye({queryKey:["spoolman-status"],queryFn:J.getSpoolmanStatus,staleTime:60*1e3}),B=j?.enabled&&j?.connected,{data:L}=Ye({queryKey:["unlinked-spools"],queryFn:J.getUnlinkedSpools,enabled:!!B,staleTime:30*1e3}),U=L&&L.length>0,{data:D}=Ye({queryKey:["linked-spools"],queryFn:J.getLinkedSpools,enabled:!!B,staleTime:30*1e3}),$=D?.linked,{data:G}=Ye({queryKey:["spool-assignments"],queryFn:()=>J.getAssignments(),staleTime:30*1e3}),z=it({mutationFn:({printerId:ce,amsId:Ce,trayId:le})=>J.unassignSpool(ce,Ce,le),onSuccess:()=>{g.invalidateQueries({queryKey:["spool-assignments"]})}}),W=(ce,Ce,le)=>G?.find(Le=>Le.printer_id===ce&&Le.ams_id===Number(Ce)&&Le.tray_id===Number(le)),K=M?.reduce((ce,Ce)=>(ce[Ce.printer_id]={due_count:Ce.due_count,warning_count:Ce.warning_count,total_print_hours:Ce.total_print_hours},ce),{})||{},te=E?.reduce((ce,Ce)=>(Ce.printer_id&&(ce[Ce.printer_id]=Ce),ce),{})||{},H=it({mutationFn:J.createPrinter,onSuccess:()=>{g.invalidateQueries({queryKey:["printers"]}),g.invalidateQueries({queryKey:["maintenanceOverview"]}),n(!1)},onError:ce=>y(ce.message||t("printers.toast.failedToAdd"),"error")}),Y=it({mutationFn:ce=>J.controlSmartPlug(ce,"on"),onSuccess:()=>{g.invalidateQueries({queryKey:["smart-plugs"]}),c(null)},onError:()=>{c(null)}}),Z=()=>{const ce=!r;i(ce),localStorage.setItem("hideDisconnectedPrinters",String(ce))},ee=ce=>{u(ce),localStorage.setItem("printerSortBy",ce)},Se=()=>{const ce=!h;f(ce),localStorage.setItem("printerSortAsc",String(ce))},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"}},ie=["S","M","L","XL"],me=w.useMemo(()=>{if(!k)return[];const ce=[...k];switch(d){case"name":ce.sort((Ce,le)=>Ce.name.localeCompare(le.name));break;case"model":ce.sort((Ce,le)=>(Ce.model||"").localeCompare(le.model||""));break;case"location":ce.sort((Ce,le)=>{const Le=Ce.location||"",V=le.location||"";return!Le&&V?1:Le&&!V?-1:Le.localeCompare(V)||Ce.name.localeCompare(le.name)});break;case"status":ce.sort((Ce,le)=>{const Le=g.getQueryData(["printerStatus",Ce.id]),V=g.getQueryData(["printerStatus",le.id]),X=fe=>fe?.connected?fe.state==="RUNNING"?0:1:2;return X(Le)-X(V)});break}return h||ce.reverse(),ce},[k,d,h,g]),se=w.useMemo(()=>{if(d!=="location")return null;const ce={};return me.forEach(Ce=>{const le=Ce.location||"Ungrouped";ce[le]||(ce[le]=[]),ce[le].push(Ce)}),ce},[d,me]);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(_$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:ce=>ee(ce.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:Se,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(cb,{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:ie.map((ce,Ce)=>{const le=Ce+1,Le=p===le;return a.jsx("button",{onClick:()=>{x(le),localStorage.setItem("printerCardSize",String(le))},className:`px-2 py-1.5 text-xs font-medium transition-colors ${Ce===0?"rounded-l-lg":""} ${Ce===ie.length-1?"rounded-r-lg":""} ${Le?"bg-bambu-green text-white":"text-bambu-gray hover:bg-bambu-dark-tertiary hover:text-white"}`,title:t(ce==="S"?"printers.cardSize.small":ce==="M"?"printers.cardSize.medium":ce==="L"?"printers.cardSize.large":"printers.cardSize.extraLarge"),children:ce},ce)})}),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:Z,className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),t("printers.hideOffline")]}),r&&Object.keys(te).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(fu,{className:"w-4 h-4"}),t("printers.powerOn"),a.jsx(Mn,{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(ce=>te[ce.id]).map(ce=>a.jsx(T$e,{printer:ce,plug:te[ce.id],onPowerOn:Ce=>{c(Ce),Y.mutate(Ce)},isPowering:l===te[ce.id]?.id},ce.id)),k?.filter(ce=>te[ce.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")]})]})]}),P?a.jsx("div",{className:"text-center py-12 text-bambu-gray",children:t("common.loading")}):k?.length===0?a.jsx(St,{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")]})]})}):se?a.jsx("div",{className:"space-y-6",children:Object.entries(se).map(([ce,Ce])=>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"}),ce,a.jsxs("span",{className:"text-sm font-normal text-bambu-gray",children:["(",Ce.length,")"]})]}),a.jsx("div",{className:`grid gap-4 ${p>=3?"gap-6":""} ${oe()}`,children:Ce.map(le=>a.jsx(u9,{printer:le,hideIfDisconnected:r,maintenanceInfo:K[le.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:U,linkedSpools:$,spoolmanUrl:j?.url,onGetAssignment:W,onUnassignSpool:(Le,V,X)=>z.mutate({printerId:Le,amsId:V,trayId:X}),timeFormat:C?.time_format||"system",cameraViewMode:C?.camera_view_mode||"window",onOpenEmbeddedCamera:(Le,V)=>A(X=>new Map(X).set(Le,{id:Le,name:V})),checkPrinterFirmware:C?.check_printer_firmware!==!1},le.id))})]},ce))}):a.jsx("div",{className:`grid gap-4 ${p>=3?"gap-6":""} ${oe()}`,children:me.map(ce=>a.jsx(u9,{printer:ce,hideIfDisconnected:r,maintenanceInfo:K[ce.id],viewMode:v,cardSize:p,spoolmanEnabled:B,hasUnlinkedSpools:U,linkedSpools:$,spoolmanUrl:j?.url,onGetAssignment:W,onUnassignSpool:(Ce,le,Le)=>z.mutate({printerId:Ce,amsId:le,trayId:Le}),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:(Ce,le)=>A(Le=>new Map(Le).set(Ce,{id:Ce,name:le})),checkPrinterFirmware:C?.check_printer_firmware!==!1},ce.id))}),e&&a.jsx(N$e,{onClose:()=>n(!1),onAdd:ce=>H.mutate(ce),existingSerials:k?.map(ce=>ce.serial_number)||[]}),Array.from(N.values()).map((ce,Ce)=>a.jsx(BTe,{printerId:ce.id,printerName:ce.name,viewerIndex:Ce,onClose:()=>A(le=>{const Le=new Map(le);return Le.delete(ce.id),Le})},ce.id))]})}function P$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}`:P$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 j$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 il(t){return j$e[t.toUpperCase()]||t}const E$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 (₽)"}],h9=768;function Cne(){const[t,e]=w.useState(()=>typeof window<"u"?window.innerWidth{const n=window.matchMedia(`(max-width: ${h9-1}px)`),r=i=>{e(i.matches)};return e(n.matches),n.addEventListener("change",r),()=>n.removeEventListener("change",r)},[]),t}function bO({archiveId:t,libraryFileId:e,title:n,fileType:r,onClose:i}){const{t:s}=Rt(),{data:o}=Ye({queryKey:["settings"],queryFn:J.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,A]=w.useState(null),[k,P]=w.useState(0),[C,E]=w.useState(!1),[M,j]=w.useState(null),[B,L]=w.useState(!1),[U,D]=w.useState(!1),$=w.useRef(null),G=w.useRef(null),z=10,W=160,K=240,te=.35;w.useEffect(()=>{const Pe=be=>{be.key==="Escape"&&i()};return window.addEventListener("keydown",Pe),()=>window.removeEventListener("keydown",Pe)},[i]),w.useEffect(()=>{if(x(!0),c){const Pe=(r||"").toLowerCase(),be=Pe==="3mf"||Pe==="stl",O=Pe==="gcode"||Pe==="3mf";f({has_model:be,has_gcode:O,has_source:!1,build_volume:{x:256,y:256,z:256},filament_colors:[]}),u(be?"3d":O?"gcode":null),x(!1);return}if(!t){f(null),u(null),x(!1);return}J.getArchiveCapabilities(t).then(Pe=>{f(Pe),Pe.has_model?u("3d"):Pe.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),A(null),P(0),c){const Pe=(r||"").toLowerCase();if(!e||Pe!=="3mf"){g(null),_(!1);return}J.getLibraryFilePlates(e).then(be=>g(be)).catch(()=>g(null)).finally(()=>_(!1));return}if(!t){g(null),_(!1);return}J.getArchivePlates(t).then(Pe=>g(Pe)).catch(()=>g(null)).finally(()=>_(!1))},[t,r,c,e]);const H=w.useMemo(()=>v?.plates??[],[v]),Y=(v?.is_multi_plate??!1)&&H.length>1,Z=C&&Y,ee=N==null?null:H.find(Pe=>Pe.index===N)??null,Se=Pe=>Pe.object_count??Pe.objects?.length??0,oe=H.reduce((Pe,be)=>Pe+Se(be),0),ie=ee?Se(ee):oe,me=ee?s("modelViewer.plateNumber",{number:ee.index}):s("modelViewer.allPlates"),se=H.length>0,ce=w.useRef(null),Ce=w.useRef(null),[le,Le]=w.useState(10),[V,X]=w.useState(3),fe=H.length>le,Q=Math.max(1,Math.ceil(H.length/le)),re=fe?H.slice(k*le,(k+1)*le):H;w.useEffect(()=>{if(!Z){Le(10),X(3);return}const Pe=ce.current,be=Ce.current;if(!Pe||!be)return;let O=0;const R=()=>{const ge=be.clientWidth,Ue=Math.floor(ge/210),ze=Math.max(3,Math.min(5,Ue||3));X(ke=>ke===ze?ke:ze);const $e=window.getComputedStyle(Pe),Re=Number.parseFloat($e.rowGap||"0"),ve=Pe.querySelector("button")?.getBoundingClientRect().height??44,Ne=be.clientHeight,we=Math.max(1,Math.floor((Ne+Re)/(ve+Re)))*ze,qe=Math.max(1,we-1);Le(ke=>ke===qe?ke:qe)},q=()=>{O&&cancelAnimationFrame(O),O=requestAnimationFrame(R)};q();const de=new ResizeObserver(q);return de.observe(be),de.observe(Pe),()=>{O&&cancelAnimationFrame(O),de.disconnect()}},[Z,H.length]),w.useEffect(()=>{if(!fe){P(0);return}P(Pe=>Math.min(Pe,Q-1))},[H.length,fe,Q]),w.useEffect(()=>{if(!fe||N==null)return;const Pe=H.findIndex(O=>O.index===N);if(Pe<0)return;const be=Math.floor(Pe/le);P(O=>O===be?O:be)},[H,le,N,fe]),w.useEffect(()=>{if(!Z){j(null),D(!1);return}if(U)return;const Pe=$.current,be=G.current;if(!Pe||!be)return;const O=Pe.clientHeight;if(!O)return;const R=Math.max(K,O*te),q=Math.max(W,O-z-R),de=Math.min(be.scrollHeight,q);j(Math.max(W,de))},[Z,U,H.length,k,z,W,K,te]),w.useEffect(()=>{if(!B)return;const Pe=O=>{const R=$.current;if(!R)return;const q=R.getBoundingClientRect(),de=q.height;if(!de)return;const ge=Math.max(K,de*te),ae=Math.max(W,de-z-ge),Ue=Math.min(ae,Math.max(W,O.clientY-q.top));j(Ue)},be=()=>{L(!1),D(!0)};return document.addEventListener("mousemove",Pe),document.addEventListener("mouseup",be),document.body.style.cursor="row-resize",document.body.style.userSelect="none",()=>{document.removeEventListener("mousemove",Pe),document.removeEventListener("mouseup",be),document.body.style.cursor="",document.body.style.userSelect=""}},[B,z,W,K,te]);const ue=c?(r||"").toLowerCase()==="3mf":!0,Fe=async()=>{if(!ue)return;const Pe=n||"model";try{if(c){const{token:be}=await J.createLibrarySlicerToken(e),O=J.getLibrarySlicerDownloadUrl(e,be,Pe);of(`${window.location.origin}${O}`,l)}else{const{token:be}=await J.createArchiveSlicerToken(t),O=J.getArchiveSlicerDownloadUrl(t,be,Pe);of(`${window.location.origin}${O}`,l)}}catch{if(c){const be=`${window.location.origin}${J.getLibraryFileDownloadUrl(e)}`;of(be,l)}else{const be=`${window.location.origin}${J.getArchiveForSlicer(t,Pe)}`;of(be,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:Pe=>Pe.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}),se&&a.jsxs("span",{className:"text-xs text-bambu-gray bg-bambu-dark-tertiary/70 px-2 py-1 rounded whitespace-nowrap",children:[me,": ",s("modelViewer.objectCount",{count:ie})]})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs(Me,{variant:"secondary",size:"sm",onClick:Fe,disabled:!ue,children:[a.jsx(na,{className:"w-4 h-4"}),s("modelViewer.openInSlicer")]}),a.jsx(Me,{variant:"secondary",size:"sm",onClick:()=>E(Pe=>!Pe),title:C?"Exit fullscreen":"Enter fullscreen",children:C?a.jsx(TF,{className:"w-4 h-4"}):a.jsx(WC,{className:"w-4 h-4"})}),a.jsx(Me,{variant:"ghost",size:"sm",onClick:i,children:a.jsx(Dt,{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(ei,{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($he,{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 ${Z?"gap-0 min-h-0":"gap-3"}`,children:[Y&&a.jsxs("div",{ref:G,style:Z&&M!=null?{height:M}:void 0,className:`rounded-lg border border-bambu-dark-tertiary bg-bambu-dark p-3 ${Z?"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(ri,{className:"w-4 h-4"}),s("modelViewer.plates"),y&&a.jsx(at,{className:"w-3 h-3 animate-spin"})]}),a.jsxs("div",{className:Z?"flex flex-col min-h-0 flex-1":void 0,children:[a.jsx("div",{ref:Ce,className:Z?"min-h-0 overflow-hidden pr-1 flex-1":void 0,children:a.jsxs("div",{ref:ce,className:Z?"grid gap-2":"grid grid-cols-2 md:grid-cols-3 gap-2",style:Z?{gridTemplateColumns:`repeat(${V}, minmax(0, 1fr))`}:void 0,children:[a.jsxs("button",{type:"button",onClick:()=>A(null),className:`flex items-center rounded-lg border text-left transition-colors ${Z?"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 ${Z?"w-8 h-8":"w-10 h-10"}`,children:a.jsx(ri,{className:`${Z?"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:`${Z?"text-xs":"text-sm"} text-white font-medium truncate`,children:s("modelViewer.allPlates")}),a.jsx("p",{className:`${Z?"text-[10px]":"text-xs"} text-bambu-gray truncate`,children:s("modelViewer.plateCount",{count:H.length})})]}),N==null&&a.jsx(Vr,{className:`${Z?"w-3.5 h-3.5":"w-4 h-4"} text-bambu-green flex-shrink-0`})]}),re.map(Pe=>a.jsxs("button",{type:"button",onClick:()=>A(Pe.index),className:`flex items-center rounded-lg border text-left transition-colors ${Z?"gap-1.5 p-1.5 w-full":"gap-2 p-2"} ${N===Pe.index?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark-secondary hover:border-bambu-gray"}`,children:[Pe.has_thumbnail&&Pe.thumbnail_url?a.jsx("img",{src:Pe.thumbnail_url,alt:`Plate ${Pe.index}`,className:`${Z?"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 ${Z?"w-8 h-8":"w-10 h-10"}`,children:a.jsx(ri,{className:`${Z?"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:`${Z?"text-xs":"text-sm"} text-white font-medium truncate`,children:Pe.name||s("modelViewer.plateNumber",{number:Pe.index})}),a.jsx("p",{className:`${Z?"text-[10px]":"text-xs"} text-bambu-gray truncate`,children:s("modelViewer.objectCount",{count:Pe.object_count??Pe.objects?.length??0})})]}),N===Pe.index&&a.jsx(Vr,{className:`${Z?"w-3.5 h-3.5":"w-4 h-4"} text-bambu-green flex-shrink-0`})]},Pe.index))]})}),(ee||fe)&&a.jsxs("div",{className:"mt-auto pt-3 flex items-center gap-4 text-xs text-bambu-gray overflow-x-auto",children:[ee&&a.jsxs("div",{className:"flex items-center gap-3 whitespace-nowrap",children:[a.jsx("span",{children:s("modelViewer.plateNumber",{number:ee.index})}),ee.print_time_seconds!=null&&a.jsx("span",{children:s("modelViewer.eta",{minutes:Math.round(ee.print_time_seconds/60)})}),ee.filament_used_grams!=null&&a.jsxs("span",{children:[ee.filament_used_grams.toFixed(1)," g"]}),ee.filaments.length>0&&a.jsx("span",{children:s("modelViewer.filamentCount",{count:ee.filaments.length})})]}),fe&&a.jsxs("div",{className:`flex items-center gap-2 whitespace-nowrap ${ee?"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:()=>P(Pe=>Math.max(Pe-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 be=Math.max(0,k-Math.floor(2.5));const O=Math.min(Q,be+5);O-be<5&&(be=Math.max(0,O-5));const R=Array.from({length:O-be},(q,de)=>be+de);return a.jsxs(a.Fragment,{children:[be>0&&a.jsx("button",{type:"button",onClick:()=>P(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"}),be>1&&a.jsx("span",{className:"px-1",children:"…"}),R.map(q=>a.jsx("button",{type:"button",onClick:()=>P(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)),OP(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:()=>P(Pe=>Math.min(Pe+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")})]})]})]})]})]}),Z&&a.jsx("div",{role:"separator","aria-orientation":"horizontal",onMouseDown:Pe=>{Pe.preventDefault(),L(!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 ${Z?"min-h-0":""}`,children:a.jsx(NY,{url:c?J.getLibraryFileDownloadUrl(e):h.has_source?J.getSource3mfDownloadUrl(t):J.getArchiveDownload(t),fileType:r,buildVolume:h.build_volume,filamentColors:h.filament_colors,selectedPlateId:N,className:"w-full h-full"})})]}):d==="gcode"&&h?a.jsx(sQ,{gcodeUrl:c?J.getLibraryFileGcodeUrl(e):J.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 HN={"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 D$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 HN[e]?HN[e]:D$e(t)}function xO(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(HN[n])return HN[n]}return null}function oA(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=r9(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:pO(i.id,o.id,s,!1),globalTrayId:BN(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=r9(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 m9(t,e){if(!t?.filaments||t.filaments.length===0)return;const n=oA(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()&&Fa(g.color)===Fa(l.color)),h||(f=v.find(g=>g.type?.toUpperCase()===l.type?.toUpperCase()&&Lc(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()&&Fa(v.color)===Fa(l.color)),h||(f=d.find(v=>v.type?.toUpperCase()===l.type?.toUpperCase()&&Lc(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 R$e(t){return w.useMemo(()=>oA(t),[t])}function kne(t,e,n){const r=R$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 P=n[u],C=r.find(E=>E.globalTrayId===P);if(C){const E=C.type?.toUpperCase()===d.type?.toUpperCase(),M=Fa(C.color)===Fa(d.color)||Lc(C.color,d.color);let j;return E&&M?j="match":E?j="type_only":j="mismatch",{...d,loaded:C,hasFilament:!0,typeMatch:E,colorMatch:M,status:j,isManual:!0}}}const h=d.tray_info_idx||"";let f=r.filter(P=>!c.has(P.globalTrayId));d.nozzle_id!=null&&(f=f.filter(P=>P.extruderId===d.nozzle_id));let p,x,v,g;if(h){const P=f.filter(C=>C.trayInfoIdx===h);P.length===1?p=P[0]:P.length>1&&(x=P.find(C=>C.type?.toUpperCase()===d.type?.toUpperCase()&&Fa(C.color)===Fa(d.color)),x||(v=P.find(C=>C.type?.toUpperCase()===d.type?.toUpperCase()&&Lc(C.color,d.color))),!x&&!v&&(g=P.find(C=>C.type?.toUpperCase()===d.type?.toUpperCase())))}!p&&!x&&!v&&!g&&(x=f.find(P=>P.type?.toUpperCase()===d.type?.toUpperCase()&&Fa(P.color)===Fa(d.color)),x||(v=f.find(P=>P.type?.toUpperCase()===d.type?.toUpperCase()&&Lc(P.color,d.color))),!x&&!v&&(g=f.find(P=>P.type?.toUpperCase()===d.type?.toUpperCase())));const y=p||x||v||g||void 0;y&&c.add(y.globalTrayId);const _=!!y,N=_,A=!!p||!!x||!!v;let k;return p||x||v?k="match":g?k="type_only":k="mismatch",{...d,loaded:y,hasFilament:_,typeMatch:N,colorMatch:A,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 F$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=Fa(y.color)===Fa(d.color)||Lc(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()&&Fa(g.color)===Fa(d.color)),p=f?void 0:h.find(g=>g.type?.toUpperCase()===d.type?.toUpperCase()&&Lc(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 L$e(t,e,n){if(!t?.filaments||t.filaments.length===0)return;const r=oA(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()&&Fa(v.color)===Fa(c.color)),f=h?void 0:u.find(v=>v.type?.toUpperCase()===c.type?.toUpperCase()&&Lc(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 f9={useDefault:!0,manualMappings:{},autoConfigured:!1};function O$e(t,e,n,r,i,s){const o=lv({queries:t.map(x=>({queryKey:["printer-status",x],queryFn:()=>J.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(j=>j.id===x)?.name||`Printer ${x}`,A=oA(y),k=i[x]||f9,P=m9(n,y),C=k.useDefault?r:k.manualMappings,E=L$e(n,y,C),M=F$e(n?.filaments,A,C);return{printerId:x,printerName:N,status:y,isLoading:g?.isLoading??!1,loadedFilaments:A,autoMapping:P,finalMapping:E,matchStatus:M.status,exactMatches:M.exactMatches,typeOnlyMatches:M.typeOnlyMatches,missingTypes:M.missingTypes,totalSlots:M.totalSlots,config:k}}),[t,o,e,n,i,r]),c=o.some(x=>x.isLoading),d=(x,v)=>{s(g=>({...g,[x]:{...g[x]||f9,...v}}))},u=x=>{const v=l.find(_=>_.printerId===x);if(!v||!v.status||!n?.filaments)return;const g=m9(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 I$e({printerId:t,filamentReqs:e,manualMappings:n,onManualMappingChange:r,currencySymbol:i,defaultCostPerKg:s,defaultExpanded:o=!1}){const{t:l}=Rt(),c=Qt(),[d,u]=w.useState(!1),[h,f]=w.useState(o),{data:p}=Ye({queryKey:["printer-status",t],queryFn:()=>J.getPrinterStatus(t),enabled:!!t}),{data:x}=Ye({queryKey:["spool-assignments",t],queryFn:()=>J.getAssignments(t),enabled:!!t}),{loadedFilaments:v,filamentComparison:g,hasTypeMismatch:y,hasColorMismatch:_}=kne(e,p,n),N=w.useMemo(()=>{const L=new Map;for(const U of x||[]){const D=U.ams_id===255,$=BN(U.ams_id,U.tray_id,D);L.set($,U.spool?.cost_per_kg??null)}return L},[x]),A=w.useMemo(()=>{const L=new Map;for(const U of x||[]){const D=U.ams_id===255,$=BN(U.ams_id,U.tray_id,D),G=U.spool;if(!G){L.set($,null);continue}L.set($,Math.max(0,Math.round((G.label_weight??0)-(G.weight_used??0))))}return L},[x]),k=w.useMemo(()=>{let L=0;for(const U of g){const D=U.loaded?.globalTrayId;if(D==null)continue;const G=N.get(D)??null??s;G>0&&(L+=U.used_grams/1e3*G)}return L},[g,N,s]),P=w.useMemo(()=>Array.from(N.values()).some(L=>L!=null&&L>0),[N]),C=e?.filaments&&e.filaments.length>0,E=e?.filaments?.some(L=>L.nozzle_id!=null)??!1;if(!C||!p)return null;const M=y?"#f97316":_?"#facc15":"#00ae42",j=(L,U)=>{if(L>0)if(U===""){const D={...n};delete D[L],r(D)}else r({...n,[L]:parseInt(U,10)})},B=async()=>{u(!0);try{await J.refreshPrinterStatus(t),await new Promise(L=>setTimeout(L,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:M,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(wl,{className:"w-4 h-4 ml-auto"}):a.jsx(Mn,{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:B,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(Sr,{className:`w-3 h-3 ${d?"animate-spin":""}`}),a.jsx("span",{children:"Re-read"})]})]}),g.map((L,U)=>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: ${L.type} - ${vf(L.color)}`,children:a.jsx(x1,{className:"w-3 h-3",fill:L.color,stroke:L.color})}),a.jsxs("span",{className:"text-white truncate flex items-center gap-1",children:[E&&L.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:L.nozzle_id===1?l("printModal.leftNozzleTooltip"):l("printModal.rightNozzleTooltip"),children:L.nozzle_id===1?l("printModal.leftNozzle"):l("printModal.rightNozzle")}),L.type," ",a.jsxs("span",{className:"text-bambu-gray",children:["(",L.used_grams,"g)"]})]}),a.jsx("span",{className:"text-bambu-gray",children:"→"}),a.jsxs("select",{value:L.loaded?.globalTrayId??"",onChange:D=>j(L.slot_id||0,D.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 ${L.status==="match"?"border-bambu-green/50 text-bambu-green":L.status==="type_only"?"border-yellow-400/50 text-yellow-400":"border-orange-400/50 text-orange-400"} ${L.isManual?"ring-1 ring-blue-400/50":""}`,title:L.isManual?"Manually selected":"Auto-matched",children:[a.jsx("option",{value:"",className:"bg-bambu-dark text-bambu-gray",children:"-- Select slot --"}),v.filter(D=>L.nozzle_id==null||D.extruderId===L.nozzle_id).map(D=>{const $=A.get(D.globalTrayId),G=$!=null?l("printModal.slotRemainingShort",{grams:$,defaultValue:` - ${$}g left`}):"";return a.jsxs("option",{value:D.globalTrayId,className:"bg-bambu-dark text-white",children:[D.label,": ",D.type," (",D.colorName,")",G]},D.globalTrayId)})]}),L.status==="match"?a.jsx(Vr,{className:"w-3 h-3 text-bambu-green"}):L.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"})})]},U)),a.jsxs("div",{className:"text-xs text-bambu-gray",children:[l("printModal.totalCost")," ",a.jsx("span",{className:"text-white",children:k>0||P?`${i}${k.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 z$e({filamentReqs:t,availableFilaments:e,overrides:n,onChange:r}){const{t:i}=Rt(),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(lo,{className:"w-3 h-3"})}):a.jsx("span",{className:"w-3"})]},c.slot_id)})})]})}function U$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(ri,{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(ri,{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?` • ${Js(i.print_time_seconds)}`:""]})]}),n===i.index&&a.jsx(Vr,{className:"w-4 h-4 text-bambu-green flex-shrink-0"})]},i.index))})]})}function B$e({printerResult:t,filamentReqs:e,onUpdateConfig:n}){const r=Qt(),[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 J.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()&&Fa(N.color)===Fa(d.color)),y=g?void 0:t.loadedFilaments.find(N=>!v.has(N.globalTrayId)&&N.type?.toUpperCase()===d.type?.toUpperCase()&&Lc(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=Fa(f.color)===Fa(d.color)||Lc(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(Sr,{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(Vr,{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 H$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(z=>z.is_active),A=w.useMemo(()=>{if(u!=="printer"||!g||y)return N;const z=N.filter(W=>W.model===g);return z.length>0?z:N},[N,u,g,y]),k=N.length-A.length,P=w.useMemo(()=>{const z=N.map(W=>W.model).filter(W=>!!W);return[...new Set(z)].sort()},[N]),C=w.useMemo(()=>{if(!f)return[];const z=N.filter(W=>W.model===f&&W.location).map(W=>W.location).filter(W=>!!W);return[...new Set(z)].sort()},[N,f]),E=h&&p&&P.length>0,M=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(A.length===0)return a.jsxs("div",{className:"flex items-center gap-2 text-red-400 text-sm mb-4",children:[a.jsx(Va,{className:"w-4 h-4"}),"No ",s?"":"active ","printers available"]});const j=z=>{i?e.includes(z)?n(e.filter(W=>W!==z)):n([...e,z]):n([z])},B=()=>{n(A.map(z=>z.id))},L=()=>{n([])},U=(z,W,K)=>{K.stopPropagation(),!(!c||!d)&&(W?c(z):d(z,{useDefault:!0,manualMappings:{},autoConfigured:!1}))},D=z=>e.includes(z),$=e.length,G=z=>o?.find(W=>W.printerId===z);return a.jsxs("div",{className:"space-y-2 mb-6",children:[E&&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(Nr,{className:"w-4 h-4"}),a.jsx("span",{className:"text-sm",children:"Specific Printer"})]}),a.jsxs("button",{type:"button",onClick:()=>{h("model"),n([]);const z=g&&P.includes(g)?g:P[0];p(z)},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(fh,{className:"w-4 h-4"}),a.jsxs("span",{className:"text-sm",children:["Any ",g||"Model"]})]})]}),u==="model"&&E&&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:z=>{p(z.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..."}),P.map(z=>a.jsx("option",{value:z,children:z},z))]})]}),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:z=>v(z.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(z=>a.jsx("option",{value:z,children:z},z))]})]}),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&&A.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:L,className:"text-bambu-gray hover:text-white transition-colors",children:"Clear"})]})]}),u==="printer"&&A.map(z=>{const W=D(z.id),K=G(z.id),te=K&&!K.config.useDefault;return a.jsxs("div",{children:[a.jsxs("button",{type:"button",onClick:()=>j(z.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"} ${z.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(Nr,{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:[z.name,!z.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:[z.model||"Unknown model"," • ",z.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(Vr,{className:"w-3 h-3 text-white"})})]}),W&&M&&K&&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:te,onChange:H=>U(z.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 ${K.matchStatus==="full"?"text-bambu-green":K.matchStatus==="partial"?"text-yellow-400":"text-orange-400"}`,children:["(",K.exactMatches,"/",K.totalSlots," matched)"]}),K.isLoading&&a.jsx(Sr,{className:"w-3 h-3 text-bambu-gray animate-spin"}),te&&a.jsxs("button",{type:"button",onClick:H=>{H.stopPropagation(),c(z.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(hge,{className:"w-3 h-3"}),"Auto"]})]}),te&&a.jsx(B$e,{printerResult:K,filamentReqs:l.filaments,onUpdateConfig:H=>d(z.id,H)})]})]},z.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(Va,{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(Va,{className:"w-3 h-3"}),"Select a target printer model"]})]})}const $$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 V$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(ZC,{className:"w-4 h-4"}),a.jsx("span",{children:"Print Options"}),r?a.jsx(wl,{className:"w-4 h-4 ml-auto"}):a.jsx(Mn,{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:$$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 q$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:m3(k)})),o(h3(k,n)),c(VB(k,r)),u(!0),f(!0)}},[t.scheduleType,t.scheduledTime,n,r,e,t]);const v=k=>{e({...t,scheduleType:k})},g=(k,P)=>{const C=Rge(k,n),E=Fge(P);u(!!C),f(!!E),C&&E&&(C.setHours(E.hours,E.minutes,0,0),C>new Date&&e({...t,scheduledTime:m3(C)}))},y=k=>{o(k),g(k,l)},_=k=>{c(k),g(s,k)},N=k=>{const P=k.target.value;if(P){const C=new Date(P);isNaN(C.getTime())||(o(h3(C,n)),c(VB(C,r)),u(!0),f(!0),e({...t,scheduledTime:P}))}},A=()=>{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(qn,{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(da,{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(_X,{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:Ege(n)}),a.jsx("button",{type:"button",onClick:A,className:"absolute right-2 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white",title:"Open calendar",children:a.jsx(da,{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:Dge(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(fu,{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},G$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}=Rt(),c=Qt(),{showToast:d}=dn(),{hasPermission:u}=Er(),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&&!a9(i.scheduled_time)&&(Ee="scheduled");let Ve="";if(i.scheduled_time&&!a9(i.scheduled_time)){const ot=tr(i.scheduled_time)??new Date;Ve=m3(ot)}return{scheduleType:Ee,scheduledTime:Ve,requirePreviousSuccess:i.require_previous_success,autoOffAfter:i.auto_off_after}}return G$e}),[A,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{}}),[P,C]=w.useState({}),[E,M]=w.useState(()=>t==="edit-queue-item"&&i?.target_model?"model":"printer"),[j,B]=w.useState(()=>t==="edit-queue-item"&&i?.target_model?i.target_model:null),[L,U]=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]:[]),[z]=w.useState(()=>t==="edit-queue-item"&&i?i.plate_id:null),[W,K]=w.useState(!1),[te,H]=w.useState({current:0,total:0}),[Y,Z]=w.useState(new Set),ee=f.length,Se=f.length>0?f[0]:null,{data:oe}=Ye({queryKey:["settings"],queryFn:J.getSettings}),ie=il(oe?.currency||"USD"),me=oe?.default_filament_cost??0,{data:se,isLoading:ce}=Ye({queryKey:["printers"],queryFn:J.getPrinters}),{data:Ce}=Ye({queryKey:["archive",e],queryFn:()=>J.getArchive(e),enabled:!!e&&!h}),{data:le}=Ye({queryKey:["library-file",n],queryFn:()=>J.getLibraryFile(n),enabled:h&&!!n}),Le=Ce?.sliced_for_model||le?.sliced_for_model||null,{data:V,isError:X}=Ye({queryKey:["archive-plates",e],queryFn:()=>J.getArchivePlates(e),enabled:!!e&&!h,retry:!1}),{data:fe}=Ye({queryKey:["library-file-plates",n],queryFn:()=>J.getLibraryFilePlates(n),enabled:h&&!!n}),Q=h?fe:V,{data:re,isError:ue}=Ye({queryKey:["archive-filaments",e,x],queryFn:()=>J.getArchiveFilamentRequirements(e,x??void 0),enabled:!!e&&!h&&(x!==null||!Q?.is_multi_plate),retry:!1}),{data:Fe}=Ye({queryKey:["library-file-filaments",n,x],queryFn:()=>J.getLibraryFileFilamentRequirements(n,x??void 0),enabled:h&&!!n&&(x!==null||!Q?.is_multi_plate)}),Pe=!h&&(X||ue),be=h?Fe:re,O=w.useMemo(()=>{if(!(x===null||!Q?.plates?.length))return Q.plates.find(Ee=>Ee.index===x)?.name||void 0},[Q,x]),{data:R}=Ye({queryKey:["available-filaments",j,L],queryFn:()=>J.getAvailableFilaments(j,L??void 0),enabled:E==="model"&&!!j}),{data:q}=Ye({queryKey:["printer-status",Se],queryFn:()=>J.getPrinterStatus(Se),enabled:!!Se}),{amsMapping:de}=kne(be,q,A),ge=O$e(f,se,be,A,P,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=se?.filter(Ve=>Ve.is_active)||[];Ee.length===1&&f.length===0&&p([Ee[0].id])},[t,se,f.length]),w.useEffect(()=>{t==="edit-queue-item"?(JSON.stringify(f.sort())!==JSON.stringify(G.sort())||x!==z)&&(k({}),C({}),Z(new Set)):(k({}),C({}),Z(new Set))},[t,f,x,G,z]);const[ae,Ue]=w.useState(j),[ze,$e]=w.useState(x);w.useEffect(()=>{(j!==ae||x!==ze)&&(Ue(j),$e(x),(t!=="edit-queue-item"||ae!==null)&&$({}))},[j,x,ae,ze,t]),w.useEffect(()=>{if(!oe?.per_printer_mapping_expanded||f.length<=1)return;const Ee=f.filter(Ve=>{if(Y.has(Ve))return!1;const ot=ge.printerResults.find(kt=>kt.printerId===Ve);return ot&&ot.status&&!ot.isLoading});Ee.length>0&&(Z(Ve=>{const ot=new Set(Ve);return Ee.forEach(kt=>ot.add(kt)),ot}),Ee.forEach(Ve=>{ge.autoConfigurePrinter(Ve)}))},[oe?.per_printer_mapping_expanded,f,Y,ge]),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,pe=Q?.plates??[],ve=it({mutationFn:Ee=>J.addToQueue(Ee)}),Ne=it({mutationFn:Ee=>J.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")}}),xe=async Ee=>{if(Ee?.preventDefault(),E==="printer"&&f.length===0){d("Please select at least one printer","error");return}if(E==="model"&&!j){d("Please select a target printer model","error");return}K(!0);const Ve=E==="model"?1:f.length;H({current:0,total:Ve});const ot={success:0,failed:0,errors:[]},kt=At=>{if(f.length>1){const Be=P[At];if(Be&&!Be.useDefault)return ge.getFinalMapping(At)}return de},Ft=Object.keys(D).length>0?Object.entries(D).map(([At,{type:Be,color:mt}])=>({slot_id:parseInt(At,10),type:Be,color:mt})):void 0,Vt=At=>({printer_id:E==="printer"?At:null,target_model:E==="model"?j:null,target_location:E==="model"?L:null,filament_overrides:E==="model"?Ft: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:At?kt(At):void 0,plate_id:x,scheduled_time:_.scheduleType==="scheduled"&&_.scheduledTime?new Date(_.scheduledTime).toISOString():void 0,...g});if(E==="model"){H({current:1,total:1});try{if(t==="reprint"){d("Model-based assignment only works with queue mode","error"),K(!1);return}else if(t==="edit-queue-item"){const At={printer_id:null,target_model:j,target_location:L,filament_overrides:Ft||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(At)}else await ve.mutateAsync(Vt(null));ot.success++}catch(At){ot.failed++,ot.errors.push(At.message)}}else for(let At=0;Atzt.id===Be)?.name||`Printer ${Be}`;ot.errors.push(`${yt}: ${mt.message}`)}}K(!1),ot.failed===0?(t!=="reprint"&&(E==="model"?d(t==="edit-queue-item"?"Queue item updated":`Queued for any ${j}`):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"]}))},we=W||Ne.isPending,qe=w.useMemo(()=>!(we||E==="printer"&&f.length===0||E==="model"&&!j||E==="model"&&t==="reprint"||Re&&!x),[f.length,E,j,t,Re,x,we]),nt=(()=>{const Ee=f.length;return t==="reprint"?{title:l(h?"queue.print":"queue.reprint"),icon:Nr,submitText:Ee>1?l("queue.printToPrinters",{count:Ee}):l("queue.print"),submitIcon:Nr,loadingText:te.total>1?l("queue.sendingProgress",{current:te.current,total:te.total}):l("queue.sending")}:t==="add-to-queue"?{title:l("queue.schedulePrint"),icon:da,submitText:Ee>1?l("queue.queueToPrinters",{count:Ee}):l("queue.addToQueue"),submitIcon:da,loadingText:te.total>1?l("queue.addingProgress",{current:te.current,total:te.total}):l("queue.adding")}:{title:l("queue.editQueueItem"),icon:Ga,submitText:l("common.save"),submitIcon:Ga,loadingText:te.total>1?l("queue.savingProgress",{current:te.current,total:te.total}):l("common.saving")}})(),De=nt.icon,We=nt.submitIcon,Oe=Se&&(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(St,{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(Dt,{className:"w-5 h-5"})})]}),a.jsxs("form",{onSubmit:xe,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(U$e,{plates:pe,isMultiPlate:Re,selectedPlate:x,onSelect:v}),a.jsx(H$e,{printers:se||[],selectedPrinterIds:f,onMultiSelect:p,isLoading:ce,allowMultiple:!0,showInactive:t==="edit-queue-item",printerMappingResults:ge.printerResults,filamentReqs:be,onAutoConfigurePrinter:ge.autoConfigurePrinter,onUpdatePrinterConfig:ge.updatePrinterConfig,assignmentMode:t==="reprint"?"printer":E,onAssignmentModeChange:t!=="reprint"?M:void 0,targetModel:j,onTargetModelChange:t!=="reprint"?B:void 0,targetLocation:L,onTargetLocationChange:t!=="reprint"?U:void 0,slicedForModel:Le}),E==="model"&&j&&be&&R&&R.length>0&&a.jsx(z$e,{filamentReqs:be,availableFilaments:R,overrides:D,onChange:$}),Le&&E==="printer"&&f.length===1&&(()=>{const Ee=se?.find(Ve=>Ve.id===f[0]);return Ee&&Ee.model&&Le!==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 ",Le,", but printing on ",Ee.model]})]}):null})(),Pe&&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(Va,{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&&!Pe&&f.length===1&&a.jsx(I$e,{printerId:Se,filamentReqs:be,manualMappings:A,onManualMappingChange:k,defaultExpanded:oe?.per_printer_mapping_expanded??!1,currencySymbol:ie,defaultCostPerKg:me}),(t==="reprint"||ee>0||E==="model"&&j)&&a.jsx(V$e,{options:g,onChange:y}),t!=="reprint"&&a.jsx(q$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:!qe,className:"flex-1",children:we?a.jsxs(a.Fragment,{children:[a.jsx(at,{className:"w-4 h-4 animate-spin"}),nt.loadingText]}):a.jsxs(a.Fragment,{children:[a.jsx(We,{className:"w-4 h-4"}),nt.submitText]})})]})]})]})})})}function W$e({onClose:t,initialFiles:e}){const{t:n}=Rt(),r=Qt(),{showToast:i}=dn(),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=P=>{P.key==="Escape"&&t()};return window.addEventListener("keydown",k),()=>window.removeEventListener("keydown",k)},[t]);const f=it({mutationFn:k=>J.uploadArchivesBulk(k),onSuccess:k=>{h(k),r.invalidateQueries({queryKey:["archives"]}),r.invalidateQueries({queryKey:["archiveStats"]}),l(P=>P.map(C=>{const E=k.results.find(j=>j.filename===C.file.name),M=k.errors.find(j=>j.filename===C.file.name);return E?{...C,status:"success",archiveId:E.id}:M?{...C,status:"error",error:M.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(P=>({...P,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 P=Array.from(k.dataTransfer.files).filter(C=>C.name.endsWith(".3mf"));P.length>0&&l(C=>[...C,...P.map(E=>({file:E,status:"pending"}))])},[]),g=w.useCallback(k=>{const P=Array.from(k.target.files||[]).filter(C=>C.name.endsWith(".3mf"));P.length>0&&l(C=>[...C,...P.map(E=>({file:E,status:"pending"}))]),s.current&&(s.current.value="")},[]),y=w.useCallback(k=>{l(P=>P.filter((C,E)=>E!==k))},[]),_=()=>{if(o.length===0)return;const k=o.filter(P=>P.status==="pending");k.length!==0&&(l(P=>P.map(C=>C.status==="pending"?{...C,status:"uploading"}:C)),f.mutate(k.map(P=>P.file)))},N=o.filter(k=>k.status==="pending").length,A=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(St,{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(Dt,{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(Oa,{className:"w-12 h-12 mx-auto mb-4 text-bambu-gray"}),a.jsx("p",{className:"text-white mb-2",children:n("uploadModal.dragDrop")}),a.jsx("p",{className:"text-bambu-gray text-sm mb-4",children:n("uploadModal.or")}),a.jsx(Me,{variant:"secondary",onClick:()=>s.current?.click(),disabled:A,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,P)=>a.jsxs("div",{className:"flex items-center gap-3 p-3 bg-bambu-dark rounded-lg",children:[a.jsx($C,{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(P),className:"text-bambu-gray hover:text-red-400 transition-colors",disabled:A,children:a.jsx(Dt,{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(yr,{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(Va,{className:"w-4 h-4 text-red-400"})]})]},`${k.file.name}-${P}`))})}),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||A,className:"flex-1",children:A?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(Oa,{className:"w-4 h-4"}),n("uploadModal.upload")," ",N>0&&`(${N})`]})})]})]})})})}const K$e=["adhesionFailure","spaghettiDetached","layerShift","cloggedNozzle","filamentRunout","warping","stringing","underExtrusion","powerFailure","userCancelled","other"],X$e=["completed","failed","aborted","printing"];function Ane({archive:t,onClose:e,existingTags:n=[]}){const{t:r}=Rt();w.useEffect(()=>{const se=ce=>{ce.key==="Escape"&&e()};return window.addEventListener("keydown",se),()=>window.removeEventListener("keydown",se)},[e]);const i=Qt(),[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,A]=w.useState(t.quantity??1),[k,P]=w.useState(t.photos||[]),[C,E]=w.useState(t.external_url||""),[M,j]=w.useState(!1),[B,L]=w.useState(!1),U=w.useRef(null),D=w.useRef(null),$=w.useRef(null),{data:G}=Ye({queryKey:["printers"],queryFn:J.getPrinters}),{data:z}=Ye({queryKey:["projects"],queryFn:()=>J.getProjects()}),{data:W}=Ye({queryKey:["tags"],queryFn:J.getTags,enabled:n.length===0}),K=n.length>0?n:W?.map(se=>se.name)||[],te=p.split(",").map(se=>se.trim()).filter(Boolean),H=p.includes(",")?p.substring(p.lastIndexOf(",")+1).trim().toLowerCase():p.trim().toLowerCase(),Y=K.filter(se=>!te.includes(se)&&(H===""||se.toLowerCase().includes(H))),Z=se=>{let ce;if(H&&!K.includes(H)?ce=p.includes(",")?p.substring(0,p.lastIndexOf(",")).split(",").map(Ce=>Ce.trim()).filter(Boolean):[]:ce=te,!ce.includes(se)){const Ce=[...ce,se].join(", ");x(Ce)}$.current!==null&&clearTimeout($.current),U.current?.focus()},ee=se=>{const ce=te.filter(Ce=>Ce!==se).join(", ");x(ce)},Se=it({mutationFn:se=>J.updateArchive(t.id,se),onSuccess:()=>{i.invalidateQueries({queryKey:["archives"]}),i.invalidateQueries({queryKey:["projects"]}),e()}}),oe=async se=>{const ce=se.target.files?.[0];if(ce){j(!0);try{const Ce=await J.uploadArchivePhoto(t.id,ce);P(Ce.photos),i.invalidateQueries({queryKey:["archives"]})}catch(Ce){console.error("Failed to upload photo:",Ce)}finally{j(!1),D.current&&(D.current.value="")}}},ie=async se=>{try{const ce=await J.deleteArchivePhoto(t.id,se);P(ce.photos||[]),i.invalidateQueries({queryKey:["archives"]})}catch(ce){console.error("Failed to delete photo:",ce)}},me=se=>{se.preventDefault();const ce={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&&(ce.status=y),y==="failed"||y==="aborted"?ce.failure_reason=v||void 0:(t.status==="failed"||t.status==="aborted")&&(ce.failure_reason=null),Se.mutate(ce)};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:se=>se.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(Dt,{className:"w-5 h-5"})})]}),a.jsxs("form",{onSubmit:me,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:se=>o(se.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:se=>c(se.target.value?Number(se.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(se=>a.jsx("option",{value:se.id,children:se.name},se.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:se=>u(se.target.value?Number(se.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")}),z?.map(se=>a.jsx("option",{value:se.id,children:se.name},se.id))]})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[a.jsx(Yme,{className:"w-4 h-4 inline mr-1"}),r("editArchive.itemsPrinted")]}),a.jsx("input",{type:"number",min:1,value:N,onChange:se=>A(Math.max(1,parseInt(se.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:se=>f(se.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(qb,{className:"w-4 h-4 inline mr-1"}),r("editArchive.externalLink")]}),a.jsx("input",{type:"url",value:C,onChange:se=>E(se.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")}),te.length>0&&a.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:te.map(se=>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(qh,{className:"w-3 h-3"}),se,a.jsx("button",{type:"button",onClick:()=>ee(se),className:"ml-0.5 text-bambu-gray hover:text-white",children:a.jsx(Dt,{className:"w-3 h-3"})})]},se))}),a.jsxs("div",{className:"relative",children:[a.jsx("input",{ref:U,type:"text",value:p,onChange:se=>x(se.target.value),onFocus:()=>{$.current!==null&&clearTimeout($.current),L(!0)},onBlur:()=>{$.current=window.setTimeout(()=>L(!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:te.length>0?r("editArchive.addMoreTags"):r("editArchive.tagsPlaceholder")}),B&&Y.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:Y.map(se=>a.jsx("button",{type:"button",onClick:()=>Z(se),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:se},se))})]})]})]}),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:se=>{_(se.target.value),se.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:X$e.map(se=>a.jsx("option",{value:se,children:r(`editArchive.statuses.${se}`)},se))})]}),(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:se=>g(se.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")}),K$e.map(se=>a.jsx("option",{value:r(`editArchive.failureReasons.${se}`),children:r(`editArchive.failureReasons.${se}`)},se))]})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[a.jsx(db,{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(se=>a.jsxs("div",{className:"relative group",children:[a.jsx("img",{src:J.getArchivePhotoUrl(t.id,se),alt:r("editArchive.printResult"),className:"w-20 h-20 object-cover rounded-lg border border-bambu-dark-tertiary"}),a.jsx("button",{type:"button",onClick:()=>ie(se),className:"absolute -top-1 -right-1 p-1 bg-red-500 rounded-full opacity-0 group-hover:opacity-100 transition-opacity",children:a.jsx(Yt,{className:"w-3 h-3 text-white"})})]},se)),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:M}),M?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:Se.isPending,className:"flex-1",children:[a.jsx(bs,{className:"w-4 h-4"}),Se.isPending?r("common.saving"):r("common.save")]})]})]})]})})}function Tne({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 A=t,k=e;t+g.width>y-N&&(A=Math.max(N,y-g.width-N)),A_-N&&(k=Math.max(N,_-g.height-N)),kP),d({x:A,y:k,visible:!0})}},[t,e]);const x=(g,y)=>{l.current&&(clearTimeout(l.current),l.current=null);const _=y.getBoundingClientRect(),N=window.innerHeight,A=300,C=N-_.top-8A;p(E=>({...E,[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(pi,{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,A)=>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]},A))})]},y)})})}function Y$e({selectedIds:t,existingTags:e,onClose:n}){const r=Qt(),{showToast:i}=dn(),[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=it({mutationFn:async()=>{const v=Array.from(l);let g=0;for(const y of t)try{const _=await J.getArchive(y),N=_.tags?_.tags.split(",").map(k=>k.trim()).filter(Boolean):[];let A;d==="add"?A=[...new Set([...N,...v])]:A=N.filter(k=>!l.has(k)),await J.updateArchive(y,{tags:A.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(St,{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(qh,{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(Dt,{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(Dt,{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(qh,{className:"w-4 h-4"}),d==="add"?"Add Tags":"Remove Tags"]})})]})]})})})}function Q$e({selectedIds:t,onClose:e}){const n=Qt(),{showToast:r}=dn(),{data:i,isLoading:s}=Ye({queryKey:["projects"],queryFn:()=>J.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=it({mutationFn:async u=>(await J.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=it({mutationFn:async()=>{for(const u of t)await J.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(St,{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(Dt,{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(mi,{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 Z$e(t,e){return new Date(t,e+1,0).getDate()}function J$e(t,e){return new Date(t,e,1).getDay()}const eVe=["January","February","March","April","May","June","July","August","September","October","November","December"],tVe=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];function nVe({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(P=>{const C=tr(P.completed_at||P.created_at)||new Date,E=`${C.getFullYear()}-${String(C.getMonth()+1).padStart(2,"0")}-${String(C.getDate()).padStart(2,"0")}`,M=k.get(E)||[];M.push(P),k.set(E,M)}),k},[t]),p=Z$e(o,i),x=J$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(Ql,{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:[eVe[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(pi,{className:"w-5 h-5 text-bambu-gray"})})]}),a.jsx("div",{className:"grid grid-cols-7 gap-1 mb-1",children:tVe.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,P)=>{if(k===null)return a.jsx("div",{className:"aspect-square"},`empty-${P}`);const C=`${o}-${String(i+1).padStart(2,"0")}-${String(k).padStart(2,"0")}`,E=f.get(C)||[],M=E.length>0,j=k===r.getDate()&&i===r.getMonth()&&o===r.getFullYear(),B=C===c,L=E.filter(D=>D.status==="completed").length,U=E.filter(D=>D.status==="failed").length;return a.jsxs("button",{onClick:()=>A(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":j?"bg-bambu-green/20 text-white ring-2 ring-bambu-green":M?"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 ${j&&!B?"text-bambu-green":""}`,children:k}),M&&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 ${U>0&&L===0?"bg-red-400":U>0?"bg-yellow-400":"bg-green-400"}`}),a.jsx("span",{className:"text-xs font-medium",children:E.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 P=tr(k.completed_at||k.created_at)||new Date;return P.getMonth()===i&&P.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 P=tr(k.completed_at||k.created_at)||new Date;return P.getMonth()===i&&P.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 P=tr(k.completed_at||k.created_at)||new Date;return P.getMonth()===i&&P.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 P=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 ${P?"":"hover:bg-bambu-dark-tertiary"}`,style:P?{outline:"4px solid #facc15",outlineOffset:"2px"}:void 0,children:[k.thumbnail_path?a.jsx("img",{src:J.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,E)=>a.jsx("div",{className:"w-3 h-3 rounded-full border border-white/20",style:{backgroundColor:C}},E))})]})]})]},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 Mne({archiveId:t,archiveName:e,onClose:n}){const r=J.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(Dt,{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(ga,{className:"w-4 h-4"}),"Download QR Code"]})]})]})})}function Pne({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=J.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(ga,{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(Yt,{className:"w-4 h-4"})}),a.jsx("button",{onClick:r,className:"p-2 text-bambu-gray hover:text-white transition-colors",children:a.jsx(Dt,{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(Ql,{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(pi,{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:J.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 Xi(t){this.content=t}Xi.prototype={constructor:Xi,find:function(t){for(var e=0;e>1}};Xi.from=function(t){if(t instanceof Xi)return t;var e=[];if(t)for(var n in t)e.push(n,t[n]);return new Xi(e)};function jne(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=jne(i.content,s.content,n+1);if(o!=null)return o}n+=i.nodeSize}}function Ene(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 Mt(r,i)}cutByIndex(e,n){return e==n?Mt.empty:e==0&&n==this.content.length?this:new Mt(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 Mt(i,s)}addToStart(e){return new Mt([e].concat(this.content),this.size+e.nodeSize)}addToEnd(e){return new Mt(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 Mt.empty;if(!Array.isArray(n))throw new RangeError("Invalid input for Fragment.fromJSON");return new Mt(n.map(e.nodeFromJSON))}static fromArray(e){if(!e.length)return Mt.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}};Xr.none=[];class VN 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=Rne(this.content,e+this.openStart,n);return r&&new qt(r,this.openStart,this.openEnd)}removeBetween(e,n){return new qt(Dne(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(Mt.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(Mt.empty,0,0);function Dne(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(Dne(s.content,e-i-1,n-i-1)))}function Rne(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=Rne(o.content,e-s-1,n,o);return l&&t.replaceChild(i,o.copy(l))}function rVe(t,e,n){if(n.openStart>t.depth)throw new VN("Inserted content deeper than insertion position");if(t.depth-n.openStart!=e.depth-n.openEnd)throw new VN("Inconsistent open depths");return Fne(t,e,n,0)}function Fne(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 Ky(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&&SR(t,e,i+1),o=r.depth>i&&SR(n,r,i+1),l=[];return Ky(null,t,i,l),s&&o&&e.index(i)==n.index(i)?(Lne(s,o),wf(Sf(s,One(t,e,n,r,i+1)),l)):(s&&wf(Sf(s,qN(t,e,i+1)),l),Ky(e,n,i,l),o&&wf(Sf(o,qN(n,r,i+1)),l)),Ky(r,null,i,l),new Mt(l)}function qN(t,e,n){let r=[];if(Ky(null,t,n,r),t.depth>n){let i=SR(t,e,n+1);wf(Sf(i,qN(t,e,n+1)),r)}return Ky(e,null,n,r),new Mt(r)}function aVe(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(Mt.from(i));return{start:i.resolveNoCache(t.openStart+n),end:i.resolveNoCache(i.content.size-t.openEnd-n)}}class V0{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 GN(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 V0(n,r,s)}static resolveCached(e,n){let r=p9.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()+")"),Ine(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=Mt.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=Mt.fromJSON(e,n.content),s=e.nodeType(n.type).create(n.attrs,i,r);return s.type.checkAttrs(s.attrs),s}};Bh.prototype.text=void 0;class WN extends Bh{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):Ine(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 WN(this.type,this.attrs,this.text,e)}withText(e){return e==this.text?this:new WN(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 Ine(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 lVe(e,n);if(r.next==null)return Kf.empty;let i=zne(r);r.next&&r.err("Unexpected trailing text");let s=pVe(fVe(i));return gVe(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 lVe{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 zne(t){let e=[];do e.push(cVe(t));while(t.eat("|"));return e.length==1?e[0]:{type:"choice",exprs:e}}function cVe(t){let e=[];do e.push(dVe(t));while(t.next&&t.next!=")"&&t.next!="|");return e.length==1?e[0]:{type:"seq",exprs:e}}function dVe(t){let e=mVe(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=uVe(t,e);else break;return e}function g9(t){/\D/.test(t.next)&&t.err("Expected number, got '"+t.next+"'");let e=Number(t.next);return t.pos++,e}function uVe(t,e){let n=g9(t),r=n;return t.eat(",")&&(t.next!="}"?r=g9(t):r=-1),t.eat("}")||t.err("Unclosed braced range"),{type:"range",min:n,max:r,expr:e}}function hVe(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 mVe(t){if(t.eat("(")){let e=zne(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=hVe(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 fVe(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:Hne(this.attrs,e)}create(e=null,n,r){if(this.isText)throw new Error("NodeType.create can't construct text nodes");return new Bh(this,this.computeAttrs(e),Mt.from(n),Xr.setFrom(r))}createChecked(e=null,n,r){return n=Mt.from(n),this.checkContent(n),new Bh(this,this.computeAttrs(e),n,Xr.setFrom(r))}createAndFill(e=null,n,r){if(e=this.computeAttrs(e),n=Mt.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(Mt.empty,!0);return s?new Bh(this,e,n.append(s),Xr.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 qne(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 bVe(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 xVe{constructor(e,n,r){this.hasDefault=Object.prototype.hasOwnProperty.call(r,"default"),this.default=r.default,this.validate=typeof r.validate=="string"?bVe(e,n,r.validate):r.validate}get isRequired(){return!this.hasDefault}}class lA{constructor(e,n,r,i){this.name=e,this.rank=n,this.schema=r,this.spec=i,this.attrs=Vne(e,i.attrs),this.excluded=null;let s=Bne(this.attrs);this.instance=s?new Xr(this,s):null}create(e=null){return!e&&this.instance?this.instance:new Xr(this,Hne(this.attrs,e))}static compile(e,n){let r=Object.create(null),i=0;return e.forEach((s,o)=>r[s]=new lA(s,i++,n,o)),r}removeFromSet(e){for(var n=0;n-1}}class Gne{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=Xi.from(e.nodes),n.marks=Xi.from(e.marks||{}),this.nodes=x9.compile(this.spec.nodes,this),this.marks=lA.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?y9(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==""?[]:y9(this,o.split(" "))}this.nodeFromJSON=i=>Bh.fromJSON(this,i),this.markFromJSON=i=>Xr.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 x9){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 WN(r,r.defaultAttrs,e,Xr.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 y9(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 yVe(t){return t.tag!=null}function vVe(t){return t.style!=null}let Xy=class NR{constructor(e,n){this.schema=e,this.rules=n,this.tags=[],this.styles=[];let r=this.matchedStyles=[];n.forEach(i=>{if(yVe(i))this.tags.push(i);else if(vVe(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 w9(this,n,!1);return r.addAll(e,Xr.none,n.from,n.to),r.finish()}parseSlice(e,n={}){let r=new w9(this,n,!0);return r.addAll(e,Xr.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=S9(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=S9(o)),o.node||o.ignore||o.mark||(o.node=i)})}return n}static fromSchema(e){return e.cached.domParser||(e.cached.domParser=new NR(e,NR.schemaRules(e)))}};const Wne={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},wVe={head:!0,noscript:!0,object:!0,script:!0,style:!0,title:!0},Kne={ol:!0,ul:!0},q0=1,CR=2,Yy=4;function v9(t,e,n){return e!=null?(e?q0:0)|(e==="full"?CR:0):t&&t.whitespace=="pre"?q0|CR:n&~Yy}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=Xr.none,this.match=s||(o&Yy?null:e.contentMatch)}findWrapping(e){if(!this.match){if(!this.type)return[];let n=this.type.contentMatch.fillBefore(Mt.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&q0)){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=Mt.from(this.content);return!e&&this.match&&(n=n.append(this.match.fillBefore(Mt.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&&!Wne.hasOwnProperty(e.parentNode.nodeName.toLowerCase())}}class w9{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=v9(null,n.preserveWhitespace,0)|(r?Yy:0);i?s=new S_(i.type,i.attrs,Xr.none,!0,n.topMatch||i.type.contentMatch,o):r?s=new S_(null,null,Xr.none,!0,null,o):s=new S_(e.schema.topNodeType,null,Xr.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&CR?"full":this.localPreserveWS||(i.options&q0)>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):_9(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|=q0)}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 SVe(t){for(let e=t.firstChild,n=null;e;e=e.nextSibling){let r=e.nodeType==1?e.nodeName.toLowerCase():null;r&&Kne.hasOwnProperty(r)&&n?(n.appendChild(e),e=n):r=="li"?n=e:r&&(n=null)}}function _Ve(t,e){return(t.matches||t.msMatchesSelector||t.webkitMatchesSelector||t.mozMatchesSelector).call(t,e)}function S9(t){let e={};for(let n in t)e[n]=t[n];return e}function _9(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(Qj(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=N9(e.nodes);return n.text||(n.text=r=>r.text),n}static marksFromSchema(e){return N9(e.marks)}}function N9(t){let e={};for(let n in t){let r=t[n].spec.toDOM;r&&(e[n]=r)}return e}function Qj(t){return t.document||window.document}const C9=new WeakMap;function NVe(t){let e=C9.get(t);return e===void 0&&C9.set(t,e=CVe(t)),e}function CVe(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 Xne=65535,Yne=Math.pow(2,16);function kVe(t,e){return t+e*Yne}function k9(t){return t&Xne}function AVe(t){return(t-(t&Xne))/Yne}const Qne=1,Zne=2,s1=4,Jne=8;class kR{constructor(e,n,r){this.pos=e,this.delInfo=n,this.recover=r}get deleted(){return(this.delInfo&Jne)>0}get deletedBefore(){return(this.delInfo&(Qne|s1))>0}get deletedAfter(){return(this.delInfo&(Zne|s1))>0}get deletedAcross(){return(this.delInfo&s1)>0}}class Mo{constructor(e,n=!1){if(this.ranges=e,this.inverted=n,!e.length&&Mo.empty)return Mo.empty}recover(e){let n=0,r=k9(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:kVe(l/3,e-c),v=e==c?Zne:e==h?Qne:s1;return(n<0?e!=c:e!=h)&&(v|=Jne),new kR(p,v,x)}i+=u-d}return r?e+i:new kR(e+i,0,null)}touches(e,n){let r=0,i=k9(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 G0;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 ni.fromReplace(e,this.from,this.to,s)}invert(){return new Xl(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 Ch(n.pos,r.pos,this.mark)}merge(e){return e instanceof Ch&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new Ch(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 Ch(n.from,n.to,e.markFromJSON(n.mark))}}_s.jsonID("addMark",Ch);class Xl 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(yO(n.content,i=>i.mark(this.mark.removeFromSet(i.marks)),e),n.openStart,n.openEnd);return ni.fromReplace(e,this.from,this.to,r)}invert(){return new Ch(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 Xl(n.pos,r.pos,this.mark)}merge(e){return e instanceof Xl&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new Xl(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 Xl(n.from,n.to,e.markFromJSON(n.mark))}}_s.jsonID("removeMark",Xl);class kh extends _s{constructor(e,n){super(),this.pos=e,this.mark=n}apply(e){let n=e.nodeAt(this.pos);if(!n)return ni.fail("No node at mark step's position");let r=n.type.create(n.attrs,null,this.mark.addToSet(n.marks));return ni.fromReplace(e,this.pos,this.pos+1,new qt(Mt.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 Fi(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 Fi(n.from,n.to,n.gapFrom,n.gapTo,qt.fromJSON(e,n.slice),n.insert,!!n.structure)}}_s.jsonID("replaceAround",Fi);function AR(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 TVe(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 MVe(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 lA){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 Xl(o.from,o.to,o.style)))}function vO(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 PVe(t,e,n){return(e==0||t.canReplace(e,t.childCount))&&(n==t.childCount||t.canReplace(0,n))}function lx(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=Mt.from(r.node(x).copy(u)),h++):c--;let f=Mt.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=Mt.from(n[o].type.create(n[o].attrs,r))}let i=e.start,s=e.end;t.step(new Fi(i,s,i,s,new qt(r,0,0),n.length,!0))}function FVe(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)&&LVe(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&&tre(t,o,l,s),vO(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 Fi(h,f,h+1,f-1,new qt(Mt.from(r.create(c,null,o.marks)),0,0),1,!0)),d===!0&&ere(t,o,l,s),!1}})}function ere(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 tre(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 3abc2cd00..5d0f0b09c 100644
--- a/static/index.html
+++ b/static/index.html
@@ -23,7 +23,7 @@
-
+