diff --git a/frontend/src/components/PrintModal/index.tsx b/frontend/src/components/PrintModal/index.tsx index 8e473c07a..855957b15 100644 --- a/frontend/src/components/PrintModal/index.tsx +++ b/frontend/src/components/PrintModal/index.tsx @@ -501,6 +501,14 @@ export function PrintModal({ )}

+ {/* Plate selection - first so users know filament requirements before selecting printers */} + + {/* Printer selection with per-printer mapping */} - {/* Plate selection */} - - {/* Warning when archive data couldn't be loaded */} {archiveDataMissing && (
diff --git a/static/assets/index-Cw5WdZhp.js b/static/assets/index-Cw4dIiLT.js similarity index 99% rename from static/assets/index-Cw5WdZhp.js rename to static/assets/index-Cw4dIiLT.js index 2b8dac6cb..16a73ee1c 100644 --- a/static/assets/index-Cw5WdZhp.js +++ b/static/assets/index-Cw4dIiLT.js @@ -8490,7 +8490,7 @@ void main() { `};class TJ extends $d{constructor(e){super({type:"LineMaterial",uniforms:vO.clone(as.line.uniforms),vertexShader:as.line.vertexShader,fragmentShader:as.line.fragmentShader,clipping:!0}),this.isLineMaterial=!0,this.setValues(e)}get color(){return this.uniforms.diffuse.value}set color(e){this.uniforms.diffuse.value=e}get worldUnits(){return"WORLD_UNITS"in this.defines}set worldUnits(e){e===!0?this.defines.WORLD_UNITS="":delete this.defines.WORLD_UNITS}get linewidth(){return this.uniforms.linewidth.value}set linewidth(e){this.uniforms.linewidth&&(this.uniforms.linewidth.value=e)}get dashed(){return"USE_DASH"in this.defines}set dashed(e){e===!0!==this.dashed&&(this.needsUpdate=!0),e===!0?this.defines.USE_DASH="":delete this.defines.USE_DASH}get dashScale(){return this.uniforms.dashScale.value}set dashScale(e){this.uniforms.dashScale.value=e}get dashSize(){return this.uniforms.dashSize.value}set dashSize(e){this.uniforms.dashSize.value=e}get dashOffset(){return this.uniforms.dashOffset.value}set dashOffset(e){this.uniforms.dashOffset.value=e}get gapSize(){return this.uniforms.gapSize.value}set gapSize(e){this.uniforms.gapSize.value=e}get opacity(){return this.uniforms.opacity.value}set opacity(e){this.uniforms&&(this.uniforms.opacity.value=e)}get resolution(){return this.uniforms.resolution.value}set resolution(e){this.uniforms.resolution.value.copy(e)}get alphaToCoverage(){return"USE_ALPHA_TO_COVERAGE"in this.defines}set alphaToCoverage(e){this.defines&&(e===!0!==this.alphaToCoverage&&(this.needsUpdate=!0),e===!0?(this.defines.USE_ALPHA_TO_COVERAGE="",this.extensions.derivatives=!0):(delete this.defines.USE_ALPHA_TO_COVERAGE,this.extensions.derivatives=!1))}}const U7=new wo,l1=new ze;class CJ extends tBe{constructor(){super(),this.isLineSegmentsGeometry=!0,this.type="LineSegmentsGeometry",this.setIndex([0,2,1,2,3,1,2,4,3,4,5,3,4,6,5,6,7,5]),this.setAttribute("position",new si([-1,2,0,1,2,0,-1,1,0,1,1,0,-1,0,0,1,0,0,-1,-1,0,1,-1,0],3)),this.setAttribute("uv",new si([-1,2,1,2,-1,1,1,1,-1,-1,1,-1,-1,-2,1,-2],2))}applyMatrix4(e){const n=this.attributes.instanceStart,r=this.attributes.instanceEnd;return n!==void 0&&(n.applyMatrix4(e),r.applyMatrix4(e),n.needsUpdate=!0),this.boundingBox!==null&&this.computeBoundingBox(),this.boundingSphere!==null&&this.computeBoundingSphere(),this}setPositions(e){let n;e instanceof Float32Array?n=e:Array.isArray(e)&&(n=new Float32Array(e));const r=new BP(n,6,1);return this.setAttribute("instanceStart",new gd(r,3,0)),this.setAttribute("instanceEnd",new gd(r,3,3)),this.computeBoundingBox(),this.computeBoundingSphere(),this}setColors(e){let n;e instanceof Float32Array?n=e:Array.isArray(e)&&(n=new Float32Array(e));const r=new BP(n,6,1);return this.setAttribute("instanceColorStart",new gd(r,3,0)),this.setAttribute("instanceColorEnd",new gd(r,3,3)),this}fromWireframeGeometry(e){return this.setPositions(e.attributes.position.array),this}fromEdgesGeometry(e){return this.setPositions(e.attributes.position.array),this}fromMesh(e){return this.fromWireframeGeometry(new Kze(e.geometry)),this}fromLineSegments(e){const n=e.geometry;return this.setPositions(n.attributes.position.array),this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new wo);const e=this.attributes.instanceStart,n=this.attributes.instanceEnd;e!==void 0&&n!==void 0&&(this.boundingBox.setFromBufferAttribute(e),U7.setFromBufferAttribute(n),this.boundingBox.union(U7))}computeBoundingSphere(){this.boundingSphere===null&&(this.boundingSphere=new Tl),this.boundingBox===null&&this.computeBoundingBox();const e=this.attributes.instanceStart,n=this.attributes.instanceEnd;if(e!==void 0&&n!==void 0){const r=this.boundingSphere.center;this.boundingBox.getCenter(r);let i=0;for(let a=0,o=e.count;aN&&oa.z>N)continue;if(sa.z>N){const L=sa.z-oa.z,K=(sa.z-N)/L;sa.lerp(oa,K)}else if(oa.z>N){const L=oa.z-sa.z,K=(oa.z-N)/L;oa.lerp(sa,K)}sa.applyMatrix4(b),oa.applyMatrix4(b),sa.multiplyScalar(1/sa.w),oa.multiplyScalar(1/oa.w),sa.x*=v.x/2,sa.y*=v.y/2,oa.x*=v.x/2,oa.y*=v.y/2,la.start.copy(sa),la.start.z=0,la.end.copy(oa),la.end.z=0;const R=la.closestPointToPointParameter(Nk,!0);la.at(R,$7);const C=oJ.lerp(sa.z,oa.z,R),P=C>=-1&&C<=1,F=Nk.distanceTo($7)<.5*Lh;if(P&&F){la.start.fromBufferAttribute(M,k),la.end.fromBufferAttribute(w,k),la.start.applyMatrix4(x),la.end.applyMatrix4(x);const L=new ze,K=new ze;ml.distanceSqToSegment(la.start,la.end,K,L),g.push({point:K,pointOnLine:L,distance:ml.origin.distanceTo(K),object:f,face:null,faceIndex:k,uv:null,uv1:null})}}})(this,i,n)))}}class yBe extends LM{constructor(e,n,r,i,a=4473924,o=8947848){a=new Wt(a),o=new Wt(o);const l=Math.round(e/n);r=Math.round(r/i)*i/2;const c=[],u=[];let d=0;for(let m=-1*(e=l*n/2);m<=e;m+=n){c.push(m,0,-1*r,m,0,r);const g=m===0?a:o;g.toArray(u,d),d+=3,g.toArray(u,d),d+=3,g.toArray(u,d),d+=3,g.toArray(u,d),d+=3}for(let m=-1*r;m<=r;m+=i){c.push(-1*e,0,m,e,0,m);const g=m===0?a:o;g.toArray(u,d),d+=3,g.toArray(u,d),d+=3,g.toArray(u,d),d+=3,g.toArray(u,d),d+=3}const f=new ja;f.setAttribute("position",new si(c,3)),f.setAttribute("color",new si(u,3)),super(f,new Ey({vertexColors:!0,toneMapped:!1}))}}function vBe(t,e,n,r){const i=(function(o,l,c){o*=.5,l*=.5,c*=.5;const u=new ja,d=[];return d.push(-o,-l,-c,-o,l,-c,-o,l,-c,o,l,-c,o,l,-c,o,-l,-c,o,-l,-c,-o,-l,-c,-o,-l,c,-o,l,c,-o,l,c,o,l,c,o,l,c,o,-l,c,o,-l,c,-o,-l,c,-o,-l,-c,-o,-l,c,-o,l,-c,-o,l,c,o,l,-c,o,l,c,o,-l,-c,o,-l,c),u.setAttribute("position",new si(d,3)),u})(t,e,n),a=new LM(i,new Yze({color:new Wt(r),dashSize:3,gapSize:1}));return a.computeLineDistances(),a}var Rb=function(){var t=0,e=document.createElement("div");function n(d){return e.appendChild(d.dom),d}function r(d){for(var f=0;f=a+1e3&&(l.update(1e3*o/(d-a),100),a=d,o=0,u)){var f=performance.memory;u.update(f.usedJSHeapSize/1048576,f.jsHeapSizeLimit/1048576)}return d},update:function(){i=this.end()},domElement:e,setMode:r}};Rb.Panel=function(t,e,n){var r=1/0,i=0,a=Math.round,o=a(window.devicePixelRatio||1),l=80*o,c=48*o,u=3*o,d=2*o,f=3*o,m=15*o,g=74*o,b=30*o,v=document.createElement("canvas");v.width=l,v.height=c,v.style.cssText="width:80px;height:48px";var x=v.getContext("2d");return x.font="bold "+9*o+"px Helvetica,Arial,sans-serif",x.textBaseline="top",x.fillStyle=n,x.fillRect(0,0,l,c),x.fillStyle=e,x.fillText(t,u,d),x.fillRect(f,m,g,b),x.fillStyle=n,x.globalAlpha=.9,x.fillRect(f,m,g,b),{dom:v,update:function(y,M){r=Math.min(r,y),i=Math.max(i,y),x.fillStyle=n,x.globalAlpha=1,x.fillRect(0,0,l,m),x.fillStyle=e,x.fillText(a(y)+" "+t+" ("+a(r)+"-"+a(i)+")",u,d),x.drawImage(v,f+o,m,g-o,b,f,m,g-o,b),x.fillRect(f+g-o,m,o,b),x.fillStyle=n,x.globalAlpha=.9,x.fillRect(f+g-o,m,o,a((1-y/M)*b))}}};var _Be=Rb;class V7{constructor(e,n){this.openFolders=[],this.watchedObject=e,this.options=n,this.gui=new yS,this.gui.title("Dev info"),this.setup()}setup(){this.loadOpenFolders(),this.options&&!this.options.renderer||this.setupRedererFolder(),this.options&&!this.options.camera||this.setupCameraFolder(),this.options&&!this.options.parser||this.setupParserFolder(),this.options&&!this.options.buildVolume||this.setupBuildVolumeFolder(),this.options&&!this.options.devHelpers||this.setupDevHelpers()}reset(){this.gui.destroy(),this.gui=new yS,this.gui.title("Dev info"),this.setup()}loadOpenFolders(){this.openFolders=JSON.parse(localStorage.getItem("dev-gui-open")||"{}").open||[]}saveOpenFolders(){this.openFolders=this.gui.foldersRecursive().filter((e=>!e._closed)).map((e=>e._title)),console.log(this.openFolders),localStorage.setItem("dev-gui-open",JSON.stringify({open:this.openFolders}))}setupRedererFolder(){const e=this.gui.addFolder("Render Info");this.openFolders.includes("Render Info")||e.close(),e.onOpenClose((()=>{this.saveOpenFolders()})),e.add(this.watchedObject.renderer.info.render,"triangles").listen(),e.add(this.watchedObject.renderer.info.render,"calls").listen(),e.add(this.watchedObject.renderer.info.render,"lines").listen(),e.add(this.watchedObject.renderer.info.render,"points").listen(),e.add(this.watchedObject.renderer.info.memory,"geometries").listen(),e.add(this.watchedObject.renderer.info.memory,"textures").listen(),e.add(this.watchedObject,"_lastRenderTime").listen()}setupCameraFolder(){const e=this.gui.addFolder("Camera");this.openFolders.includes("Camera")||e.close(),e.onOpenClose((()=>{this.saveOpenFolders()}));const n=e.addFolder("Camera position");n.add(this.watchedObject.camera.position,"x").listen(),n.add(this.watchedObject.camera.position,"y").listen(),n.add(this.watchedObject.camera.position,"z").listen();const r=e.addFolder("Camera rotation");r.add(this.watchedObject.camera.rotation,"x").listen(),r.add(this.watchedObject.camera.rotation,"y").listen(),r.add(this.watchedObject.camera.rotation,"z").listen()}setupParserFolder(){const e=this.gui.addFolder("Parser");this.openFolders.includes("Parser")||e.close(),e.onOpenClose((()=>{this.saveOpenFolders()})),e.add(this.watchedObject.parser,"curZ").listen(),e.add(this.watchedObject.parser,"maxZ").listen(),e.add(this.watchedObject.parser,"tolerance").listen(),e.add(this.watchedObject.parser.layers,"length").name("layers.count").listen(),e.add(this.watchedObject.parser.lines,"length").name("lines.count").listen()}setupBuildVolumeFolder(){const e=this.gui.addFolder("Build Volume");this.openFolders.includes("Build Volume")||e.close(),e.onOpenClose((()=>{this.saveOpenFolders()})),e.add(this.watchedObject.buildVolume,"x").min(0).max(600).listen().onChange((()=>{this.watchedObject.render()})),e.add(this.watchedObject.buildVolume,"y").min(0).max(600).listen().onChange((()=>{this.watchedObject.render()})),e.add(this.watchedObject.buildVolume,"z").min(0).max(600).listen().onChange((()=>{this.watchedObject.render()}))}setupDevHelpers(){const e=this.gui.addFolder("Dev Helpers");this.openFolders.includes("Dev Helpers")||e.close(),e.onOpenClose((()=>{this.saveOpenFolders()})),e.add(this.watchedObject,"_wireframe").listen().onChange((()=>{this.watchedObject.render()})),e.add(this.watchedObject,"render").listen(),e.add(this.watchedObject,"clear").listen()}}class wBe extends ja{constructor(e=[new ze],n=.6,r=.2,i=8){super(),this.type="ExtrusionGeometry",this.parameters={points:e,lineWidth:n,lineHeight:r,radialSegments:i,closed:!1};const a=new ze,o=new ze,l=new tn,c=[],u=[],d=[],f=[];function m(g){const[b,v,x]=(function(y){const M=e[y],w=new ze,A=new ze,N=new ze,k=new ze;w.copy(M).sub(e[y-1]||M).normalize().add((e[y+1]||M).clone().sub(M).normalize()).normalize();let T=Number.MAX_VALUE;const R=Math.abs(w.x),C=Math.abs(w.y),P=Math.abs(w.z);return R<=T&&(T=R,A.set(1,0,0)),C<=T&&(T=C,A.set(0,1,0)),P<=T&&A.set(0,0,1),k.crossVectors(w,A).normalize(),A.crossVectors(w,k),N.crossVectors(w,A),[M,A,N]})(g);for(let y=0;y<=i;y++){const M=y/i*Math.PI*2,w=Math.sin(M),A=-Math.cos(M);o.x=A*v.x+w*x.x,o.y=A*v.y+w*x.y,o.z=A*v.z+w*x.z,o.normalize(),u.push(o.x,o.y,o.z),a.x=b.x+n*o.x*.5,a.y=b.y+n*o.y*.5,a.z=b.z+r*o.z*.5,c.push(a.x,a.y,a.z)}}(function(){for(let g=0;gthis.animate())),this.controls.update(),this.renderer.render(this.scene,this.camera),(e=this.stats)===null||e===void 0||e.update()}processGCode(e){this.parser.parseGCode(e),this.render()}initScene(){for(;this.scene.children.length>0;)this.scene.remove(this.scene.children[0]);for(;this.disposables.length>0;){const e=this.disposables.pop();e&&e.dispose()}if(this.debug&&this.buildVolume){const e=new rBe(Math.max(this.buildVolume.x/2,this.buildVolume.y/2)+20);this.scene.add(e)}if(this.buildVolume&&this.drawBuildVolume(),this.renderTubes){console.warn("Volumetric rendering is experimental. It may not work as expected or change in the future.");const e=new eBe(13421772,.3*Math.PI),n=new Jze(16777215,Math.PI,void 0,.001);n.position.set(0,500,500),this.scene.add(e),this.scene.add(n)}}createGroup(e){const n=new yb;return n.name=e,n.quaternion.setFromEuler(new Sy(-Math.PI/2,0,0)),this.buildVolume?n.position.set(-this.buildVolume.x/2,0,this.buildVolume.y/2):n.position.set(-100,0,100),n}render(){const e=performance.now();this.group=this.createGroup("allLayers"),this.state=Db.initial,this.initScene();for(let n=0;n0?e:1)}))}renderFrameLoop(e){return new Promise((n=>{const r=()=>{this.renderLayerIndex>this.layers.length-1?n():(this.renderFrame(e),requestAnimationFrame(r))};r()}))}renderFrame(e){this.group=this.createGroup("layer"+this.renderLayerIndex);for(let n=0;nthis.maxLayerIndex)return;const d=this.layers[e],f={extrusion:[],travel:[],z:this.state.z,height:d.height};for(const m of d.commands)if(m.gcode!="g20"){if(m.gcode.startsWith("t")){this.doRenderExtrusion(f,e),f.extrusion=[];const g=m;this.state.t=g.toolIndex}else if(["g0","g00","g1","g01","g2","g02","g3","g03"].indexOf(m.gcode)>-1){const g=m,b={x:(n=g.params.x)!==null&&n!==void 0?n:this.state.x,y:(r=g.params.y)!==null&&r!==void 0?r:this.state.y,z:(i=g.params.z)!==null&&i!==void 0?i:this.state.z,r:(a=g.params.r)!==null&&a!==void 0?a:this.state.r,e:(o=g.params.e)!==null&&o!==void 0?o:this.state.e,i:(l=g.params.i)!==null&&l!==void 0?l:this.state.i,j:(c=g.params.j)!==null&&c!==void 0?c:this.state.j,t:this.state.t};if(e>=this.minLayerIndex){const v=((u=g.params.e)!==null&&u!==void 0?u:0)>0||this.nonTravelmoves.indexOf(m.gcode)>-1;(b.x!=this.state.x||b.y!=this.state.y||b.z!=this.state.z)&&(v&&this.renderExtrusion||!v&&this.renderTravel)&&(m.gcode=="g2"||m.gcode=="g3"||m.gcode=="g02"||m.gcode=="g03"?this.addArcSegment(f,this.state,b,v,m.gcode=="g2"||m.gcode=="g02"):this.addLineSegment(f,this.state,b,v))}this.state.x=b.x,this.state.y=b.y,this.state.z=b.z,this.beyondFirstMove||(this.beyondFirstMove=!0)}}else this.setInches();this.doRenderExtrusion(f,e)}doRenderExtrusion(e,n){var r,i;if(this.renderExtrusion){let a=this.currentToolColor;if(!this.singleLayerMode&&!this.renderTubes&&!this.disableGradient){const o=.1+.7*n/this.layers.length;a.getHSL(Tk),a=new Wt().setHSL(Tk.h,Tk.s,o)}if(n==this.layers.length-1){const o=(r=this._topLayerColor)!==null&&r!==void 0?r:a,l=(i=this._lastSegmentColor)!==null&&i!==void 0?i:o,c=e.extrusion.splice(-3),u=e.extrusion.splice(-3);this.renderTubes?(this.addTubeLine(e.extrusion,o.getHex(),e.height),this.addTubeLine([...u,...c],l.getHex(),e.height)):(this.addLine(e.extrusion,o.getHex()),this.addLine([...u,...c],l.getHex()))}else this.renderTubes?this.addTubeLine(e.extrusion,a.getHex(),e.height):this.addLine(e.extrusion,a.getHex())}this.renderTravel&&this.addLine(e.travel,this._travelColor.getHex())}setInches(){this.beyondFirstMove?console.warn("Switching units after movement is already made is discouraged and is not supported."):this.inches=!0}drawBuildVolume(){if(!this.buildVolume)return;this.scene.add(new yBe(this.buildVolume.x,10,this.buildVolume.y,10));const e=vBe(this.buildVolume.x,this.buildVolume.z,this.buildVolume.y,8947848);e.position.setY(this.buildVolume.z/2),this.scene.add(e)}clear(){this.resetState(),this.parser=new vS(this.minLayerThreshold)}resetState(){var e;this.startLayer=1,this.endLayer=1/0,this.singleLayerMode=!1,this.beyondFirstMove=!1,this.state=Db.initial,(e=this.devGui)===null||e===void 0||e.reset(),this._geometries={}}resize(){const[e,n]=[this.canvas.offsetWidth,this.canvas.offsetHeight];this.camera.aspect=e/n,this.camera.updateProjectionMatrix(),this.renderer.setPixelRatio(window.devicePixelRatio),this.renderer.setSize(e,n,!1)}addLineSegment(e,n,r,i){(i?e.extrusion:e.travel).push(n.x,n.y,n.z,r.x,r.y,r.z)}addArcSegment(e,n,r,i,a){const o=i?e.extrusion:e.travel,l=n.x,c=n.y,u=n.z,d=r.x,f=r.y,m=r.z;let g=r.r,b=r.i,v=r.j;if(g){const W=d-l,Y=f-c,q=Math.sqrt(Math.pow(W/2,2)+Math.pow(Y/2,2));g=Math.max(g,q);const Q=Math.pow(W,2)+Math.pow(Y,2),re=Math.pow(g,2)-Q/4;let ne=Math.sqrt(re/Q);(a&&g<0||!a&&g>0)&&(ne=-ne),b=W/2+Y*ne,v=Y/2-W*ne}const x=l==d&&c==f,y=l+b,M=c+v,w=Math.sqrt(b*b+v*v),A=Math.atan2(-v,-b),N=Math.atan2(f-M,d-y);let k;x?k=2*Math.PI:(k=a?A-N:N-A,k<0&&(k+=2*Math.PI));let T=w*k/1.8;this.inches&&(T*=25),T<1&&(T=1);let R=k/T;R*=a?-1:1;const C=[];C.push({x:l,y:c,z:u});const P=(u-m)/T;let F=l,L=c,K=u,D=A;for(let W=0;W0)return void this.addThickLine(e,n);const i=new ja;i.setAttribute("position",new si(e,3)),this.disposables.push(i);const a=new Ey({color:n});this.disposables.push(a);const o=new LM(i,a);(r=this.group)===null||r===void 0||r.add(o)}addTubeLine(e,n,r=.2){let i=[];const a=[];for(let o=0;o{var l;const c=new wBe(o,this.extrusionWidth,this.lineHeight||r,4);(l=this._geometries)[n]||(l[n]=[]),this._geometries[n].push(c)}))}addThickLine(e,n){var r;if(!e.length||!this.lineWidth)return;const i=new CJ;this.disposables.push(i);const a=new TJ({color:n,linewidth:this.lineWidth/(1e3*window.devicePixelRatio)});this.disposables.push(a),i.setPositions(e);const o=new bBe(i,a);(r=this.group)===null||r===void 0||r.add(o)}dispose(){this.disposables.forEach((e=>e.dispose())),this.disposables=[],this.controls.dispose(),this.renderer.dispose(),this.cancelAnimation()}cancelAnimation(){this.animationFrameId!==void 0&&cancelAnimationFrame(this.animationFrameId),this.animationFrameId=void 0}_enableDropHandler(){console.warn("Drag and drop is deprecated as a library feature. See the demo how to implement your own."),this.canvas.addEventListener("dragover",(e=>{e.stopPropagation(),e.preventDefault(),e.dataTransfer&&(e.dataTransfer.dropEffect="copy"),this.canvas.classList.add("dragging")})),this.canvas.addEventListener("dragleave",(e=>{e.stopPropagation(),e.preventDefault(),this.canvas.classList.remove("dragging")})),this.canvas.addEventListener("drop",(e=>Mk(this,void 0,void 0,(function*(){var n,r;e.stopPropagation(),e.preventDefault(),this.canvas.classList.remove("dragging");const i=((r=(n=e.dataTransfer)===null||n===void 0?void 0:n.files)!==null&&r!==void 0?r:[])[0];this.clear(),yield this._readFromStream(i.stream()),this.render()}))))}batchGeometries(){if(this._geometries)for(const e in this._geometries){const n=this.createBatchMesh(parseInt(e));for(;this._geometries[e].length>0;){const r=this._geometries[e].pop();n.addGeometry(r)}}}createBatchMesh(e){var n;const r=this._geometries[e],i=new Xze({color:e,wireframe:this._wireframe});this.disposables.push(i);const a=r.reduce(((l,c)=>3*c.attributes.position.count+l),0),o=new Wze(r.length,a,void 0,i);return this.disposables.push(o),(n=this.group)===null||n===void 0||n.add(o),o}_readFromStream(e){var n,r;return Mk(this,void 0,void 0,(function*(){const i=e.getReader();let a,o="",l=0;do{console.debug("reading from stream"),a=yield i.read(),l+=(r=(n=a.value)===null||n===void 0?void 0:n.length)!==null&&r!==void 0?r:0;const u=(c=a.value,new TextDecoder("utf-8").decode(c)),d=u.lastIndexOf(` `),f=u.slice(0,d);this.parser.parseGCode(o+f),o=u.slice(d)}while(!a.done);var c;console.debug("read from stream",l)}))}initGui(){typeof this.devMode=="boolean"&&this.devMode===!0?this.devGui=new V7(this):typeof this.devMode=="object"&&(this.devGui=new V7(this,this.devMode))}initStats(){var e;this.stats&&(typeof this.devMode=="object"&&(this.statsContainer=this.devMode.statsContainer),((e=this.statsContainer)!==null&&e!==void 0?e:document.body).appendChild(this.stats.dom),this.stats.dom.classList.add("stats"),this.initGui())}}zp.defaultExtrusionColor=new Wt("hotpink");function SBe({gcodeUrl:t,buildVolume:e={x:256,y:256,z:256},filamentColors:n,className:r=""}){const i=S.useRef(null),a=S.useRef(null),o=S.useRef(null),l=S.useRef(!1),[c,u]=S.useState(!0),[d,f]=S.useState(null),[m,g]=S.useState(!1),[b,v]=S.useState(0),[x,y]=S.useState(0),M=S.useMemo(()=>JSON.stringify(n),[n]);S.useEffect(()=>{if(!i.current||l.current)return;l.current=!0;const N=i.current,k=N.parentElement?.getBoundingClientRect();k&&(N.width=k.width,N.height=k.height);const T=n&&n.length>1,R=n?.[0]||"#00ae42",C=new zp({canvas:N,buildVolume:e,backgroundColor:1710618,extrusionColor:T?n:R,disableGradient:!0,lineHeight:.2,lineWidth:2,renderTravel:!1,renderExtrusion:!0});a.current=C,fetch(t).then(async F=>{if(!F.ok)throw F.status===404&&(await F.json().catch(()=>({}))).detail?.includes("sliced")?(g(!0),new Error("not_sliced")):new Error("Failed to load G-code");return F.text()}).then(F=>{const L=new Set,K=/^(\s*)T(\d+)(\s*;.*)?$/gim;let D;for(;(D=K.exec(F))!==null;){const ne=parseInt(D[2],10);ne<=15&&L.add(ne)}const W=new Map,Y=Array.from(L).sort((ne,U)=>ne-U);Y.forEach((ne,U)=>{W.set(ne,U%8)});const q=[];Y.forEach((ne,U)=>{const G=n?.[ne]||"#00ae42";q[U%8]=G});const Q=F.split(` `).map(ne=>{const U=ne.match(/^(\s*)T(\d+)(\s*;.*)?$/i);if(U){const G=parseInt(U[2],10);if(G>15)return`; FILTERED: ${ne.trim()}`;const te=W.get(G)??0;return`${U[1]}T${te}${U[3]||""}`}return ne}).join(` -`);q.length>0&&(C.extrusionColor=q),C.processGCode(Q);const re=C.layers?.length||0;y(re),v(re),C.render(),u(!1)}).catch(F=>{F.message!=="not_sliced"&&f(F.message),u(!1)});const P=()=>{if(N.parentElement&&a.current){const F=N.parentElement.getBoundingClientRect();N.width=F.width,N.height=F.height,a.current.resize()}};return window.addEventListener("resize",P),()=>{window.removeEventListener("resize",P),o.current&&cancelAnimationFrame(o.current),a.current&&(a.current.dispose(),a.current=null),l.current=!1}},[t,M]);const w=S.useCallback(N=>{if(!a.current)return;const k=Math.max(1,Math.min(N,x));v(k),o.current&&cancelAnimationFrame(o.current),o.current=requestAnimationFrame(()=>{a.current&&(a.current.endLayer=k,a.current.render())})},[x]),A=N=>{w(parseInt(N.target.value,10))};return s.jsxs("div",{className:`relative flex flex-col h-full ${r}`,children:[s.jsxs("div",{className:"flex-1 relative bg-bambu-dark rounded-lg overflow-hidden",children:[s.jsx("canvas",{ref:i,className:"w-full h-full"}),c&&s.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-bambu-dark/80",children:s.jsxs("div",{className:"text-center",children:[s.jsx(ft,{className:"w-8 h-8 animate-spin text-bambu-green mx-auto mb-2"}),s.jsx("p",{className:"text-bambu-gray text-sm",children:"Loading G-code..."})]})}),m&&s.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-bambu-dark/80",children:s.jsxs("div",{className:"text-center max-w-sm px-4",children:[s.jsx(Kce,{className:"w-12 h-12 text-bambu-gray mx-auto mb-3"}),s.jsx("p",{className:"text-white font-medium mb-2",children:"G-code not available"}),s.jsx("p",{className:"text-bambu-gray text-sm",children:"This file hasn't been sliced yet. G-code preview is only available after slicing in Bambu Studio or Orca Slicer."})]})}),d&&!m&&s.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-bambu-dark/80",children:s.jsx("div",{className:"text-center text-red-400",children:s.jsx("p",{className:"text-sm",children:d})})})]}),!c&&!d&&!m&&x>0&&s.jsx("div",{className:"mt-4 px-2",children:s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx(el,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}),s.jsx("button",{onClick:()=>w(b-1),disabled:b<=1,className:"p-1 rounded hover:bg-bambu-dark-tertiary disabled:opacity-30 disabled:cursor-not-allowed",children:s.jsx(mf,{className:"w-4 h-4"})}),s.jsx("input",{type:"range",min:1,max:x,value:b,onChange:A,className:"flex-1 h-2 bg-bambu-dark-tertiary rounded-lg appearance-none cursor-pointer accent-bambu-green"}),s.jsx("button",{onClick:()=>w(b+1),disabled:b>=x,className:"p-1 rounded hover:bg-bambu-dark-tertiary disabled:opacity-30 disabled:cursor-not-allowed",children:s.jsx($s,{className:"w-4 h-4"})}),s.jsxs("span",{className:"text-sm text-bambu-gray min-w-[80px] text-right",children:[b," / ",x]})]})})]})}function kJ({archiveId:t,title:e,onClose:n}){const[r,i]=S.useState(null),[a,o]=S.useState(null),[l,c]=S.useState(!0);S.useEffect(()=>{const d=f=>{f.key==="Escape"&&n()};return window.addEventListener("keydown",d),()=>window.removeEventListener("keydown",d)},[n]),S.useEffect(()=>{xe.getArchiveCapabilities(t).then(d=>{o(d),d.has_model?i("3d"):d.has_gcode&&i("gcode"),c(!1)}).catch(()=>{o({has_model:!0,has_gcode:!1,has_source:!1,build_volume:{x:256,y:256,z:256},filament_colors:[]}),i("3d"),c(!1)})},[t]);const u=()=>{const d=e||"model",f=`${window.location.origin}${xe.getArchiveForSlicer(t,d)}`;Rc(f)};return s.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-8",onClick:n,children:s.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary w-full max-w-4xl h-[80vh] flex flex-col",onClick:d=>d.stopPropagation(),children:[s.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[s.jsx("h2",{className:"text-lg font-semibold text-white truncate flex-1 mr-4",children:e}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs(Ce,{variant:"secondary",size:"sm",onClick:u,children:[s.jsx(Ir,{className:"w-4 h-4"}),"Open in Slicer"]}),s.jsx(Ce,{variant:"ghost",size:"sm",onClick:n,children:s.jsx(Ft,{className:"w-5 h-5"})})]})]}),a&&s.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary",children:[s.jsxs("button",{onClick:()=>a.has_model&&i("3d"),disabled:!a.has_model,className:`flex items-center gap-2 px-6 py-3 text-sm font-medium transition-colors ${r==="3d"?"text-bambu-green border-b-2 border-bambu-green":a.has_model?"text-bambu-gray hover:text-white":"text-bambu-gray/30 cursor-not-allowed"}`,children:[s.jsx(js,{className:"w-4 h-4"}),"3D Model",!a.has_model&&s.jsx("span",{className:"text-xs",children:"(not available)"})]}),s.jsxs("button",{onClick:()=>a.has_gcode&&i("gcode"),disabled:!a.has_gcode,className:`flex items-center gap-2 px-6 py-3 text-sm font-medium transition-colors ${r==="gcode"?"text-bambu-green border-b-2 border-bambu-green":a.has_gcode?"text-bambu-gray hover:text-white":"text-bambu-gray/30 cursor-not-allowed"}`,children:[s.jsx(wce,{className:"w-4 h-4"}),"G-code Preview",!a.has_gcode&&s.jsx("span",{className:"text-xs",children:"(not sliced)"})]})]}),s.jsx("div",{className:"flex-1 overflow-hidden p-4",children:l?s.jsx("div",{className:"w-full h-full flex items-center justify-center",children:s.jsx(ft,{className:"w-8 h-8 animate-spin text-bambu-green"})}):r==="3d"&&a?s.jsx(vOe,{url:a.has_source?xe.getSource3mfDownloadUrl(t):xe.getArchiveDownload(t),buildVolume:a.build_volume,filamentColors:a.filament_colors,className:"w-full h-full"}):r==="gcode"&&a?s.jsx(SBe,{gcodeUrl:xe.getArchiveGcode(t),filamentColors:a.filament_colors,className:"w-full h-full"}):s.jsx("div",{className:"w-full h-full flex items-center justify-center text-bambu-gray",children:"No preview available for this file"})})]})})}const G7={"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 MBe(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),a=Math.max(n,r,i)/255,o=Math.min(n,r,i)/255,l=(a+o)/2;let c=0,u=0;if(a!==o){const d=a-o;u=l>.5?d/(2-a-o):d/(a+o);const f=n/255,m=r/255,g=i/255;a===f?c=((m-g)/d+(m.85?"White":u<.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":c<345?"Pink":"Unknown"}function mg(t){const e=t.replace("#","").toLowerCase().substring(0,6);return G7[e]?G7[e]:MBe(t)}function _S(t){return t?`#${t.replace("#","").substring(0,6)}`:"#808080"}function Xi(t){return t?t.replace("#","").toLowerCase().substring(0,6):""}function Hd(t,e,n=40){const r=Xi(t),i=Xi(e);if(!r||!i||r.length<6||i.length<6)return!1;const a=parseInt(r.substring(0,2),16),o=parseInt(r.substring(2,4),16),l=parseInt(r.substring(4,6),16),c=parseInt(i.substring(0,2),16),u=parseInt(i.substring(2,4),16),d=parseInt(i.substring(4,6),16);return Math.abs(a-c)<=n&&Math.abs(o-u)<=n&&Math.abs(l-d)<=n}function jJ(t,e,n,r){const i=String.fromCharCode(65+(t>=128?t-128:t));return n?`HT-${i}`:`AMS-${i} Slot ${e+1}`}function PJ(t,e,n){return t*4+e}function EBe(t){if(!t)return"";const e=Math.floor(t/3600),n=Math.floor(t%3600/60);return e>0?`${e}h ${n}m`:`${n}m`}function NBe(){const t=new Date;return t.setMinutes(t.getMinutes()+1),t.toISOString().slice(0,16)}function W7(t){if(!t)return!1;const e=Date.now()+4320*60*60*1e3;return new Date(t).getTime()>e}function NO(t){const e=[];if(t?.ams?.forEach(n=>{const r=n.tray.length===1;n.tray.forEach(i=>{if(i.tray_type){const a=_S(i.tray_color);e.push({type:i.tray_type,color:a,colorName:mg(a),amsId:n.id,trayId:i.id,isHt:r,isExternal:!1,label:jJ(n.id,i.id,r),globalTrayId:PJ(n.id,i.id)})}})}),t?.vt_tray?.tray_type){const n=_S(t.vt_tray.tray_color);e.push({type:t.vt_tray.tray_type,color:n,colorName:mg(n),amsId:-1,trayId:0,isHt:!1,isExternal:!0,label:"External",globalTrayId:254})}return e}function q7(t,e){if(!t?.filaments||t.filaments.length===0)return;const n=NO(e);if(n.length===0)return;const r=new Set,i=t.filaments.map(l=>{const c=n.find(m=>!r.has(m.globalTrayId)&&m.type?.toUpperCase()===l.type?.toUpperCase()&&Xi(m.color)===Xi(l.color)),u=!c&&n.find(m=>!r.has(m.globalTrayId)&&m.type?.toUpperCase()===l.type?.toUpperCase()&&Hd(m.color,l.color)),d=!c&&!u&&n.find(m=>!r.has(m.globalTrayId)&&m.type?.toUpperCase()===l.type?.toUpperCase()),f=c||u||d||void 0;return f&&r.add(f.globalTrayId),{slot_id:l.slot_id,globalTrayId:f?.globalTrayId??-1}}),a=Math.max(...i.map(l=>l.slot_id||0));if(a<=0)return;const o=new Array(a).fill(-1);return i.forEach(l=>{l.slot_id&&l.slot_id>0&&(o[l.slot_id-1]=l.globalTrayId)}),o}function ABe(t){return S.useMemo(()=>{const e=[];if(t?.ams?.forEach(n=>{const r=n.tray.length===1;n.tray.forEach(i=>{if(i.tray_type){const a=_S(i.tray_color);e.push({type:i.tray_type,color:a,colorName:mg(a),amsId:n.id,trayId:i.id,isHt:r,isExternal:!1,label:jJ(n.id,i.id,r),globalTrayId:PJ(n.id,i.id)})}})}),t?.vt_tray?.tray_type){const n=_S(t.vt_tray.tray_color);e.push({type:t.vt_tray.tray_type,color:n,colorName:mg(n),amsId:-1,trayId:0,isHt:!1,isExternal:!0,label:"External",globalTrayId:254})}return e},[t])}function RJ(t,e,n){const r=ABe(e),i=S.useMemo(()=>{if(!t?.filaments||t.filaments.length===0)return[];const c=new Set(Object.values(n));return t.filaments.map(u=>{const d=u.slot_id||0;if(d>0&&n[d]!==void 0){const w=n[d],A=r.find(N=>N.globalTrayId===w);if(A){const N=A.type?.toUpperCase()===u.type?.toUpperCase(),k=Xi(A.color)===Xi(u.color)||Hd(A.color,u.color);let T;return N&&k?T="match":N?T="type_only":T="mismatch",{...u,loaded:A,hasFilament:!0,typeMatch:N,colorMatch:k,status:T,isManual:!0}}}const f=r.find(w=>!c.has(w.globalTrayId)&&w.type?.toUpperCase()===u.type?.toUpperCase()&&Xi(w.color)===Xi(u.color)),m=!f&&r.find(w=>!c.has(w.globalTrayId)&&w.type?.toUpperCase()===u.type?.toUpperCase()&&Hd(w.color,u.color)),g=!f&&!m&&r.find(w=>!c.has(w.globalTrayId)&&w.type?.toUpperCase()===u.type?.toUpperCase()),b=f||m||g||void 0;b&&c.add(b.globalTrayId);const v=!!b,x=v,y=!!f||!!m;let M;return f||m?M="match":g?M="type_only":M="mismatch",{...u,loaded:b,hasFilament:v,typeMatch:x,colorMatch:y,status:M,isManual:!1}})},[t,r,n]),a=S.useMemo(()=>{if(i.length===0)return;const c=Math.max(...i.map(d=>d.slot_id||0));if(c<=0)return;const u=new Array(c).fill(-1);return i.forEach(d=>{d.slot_id&&d.slot_id>0&&(u[d.slot_id-1]=d.loaded?.globalTrayId??-1)}),u},[i]),o=i.some(c=>c.status==="mismatch"),l=i.some(c=>c.status==="type_only");return{loadedFilaments:r,filamentComparison:i,amsMapping:a,hasTypeMismatch:o,hasColorMismatch:l}}function TBe(t,e,n){if(!t||t.length===0)return{exactMatches:0,typeOnlyMatches:0,missingTypes:0,totalSlots:0,status:"full"};let r=0,i=0,a=0;const o=new Set(Object.values(n));for(const u of t){const d=u.slot_id||0;if(d>0&&n[d]!==void 0){const v=n[d],x=e.find(y=>y.globalTrayId===v);if(x){const y=x.type?.toUpperCase()===u.type?.toUpperCase(),M=Xi(x.color)===Xi(u.color)||Hd(x.color,u.color);y&&M?r++:y?i++:a++;continue}}const f=e.find(v=>!o.has(v.globalTrayId)&&v.type?.toUpperCase()===u.type?.toUpperCase()&&Xi(v.color)===Xi(u.color)),m=f?void 0:e.find(v=>!o.has(v.globalTrayId)&&v.type?.toUpperCase()===u.type?.toUpperCase()&&Hd(v.color,u.color)),g=f||m?void 0:e.find(v=>!o.has(v.globalTrayId)&&v.type?.toUpperCase()===u.type?.toUpperCase()),b=f??m??g;b&&o.add(b.globalTrayId),f||m?r++:g?i++:a++}const l=t.length;let c="full";return a>0?c="missing":i>0&&(c="partial"),{exactMatches:r,typeOnlyMatches:i,missingTypes:a,totalSlots:l,status:c}}function CBe(t,e,n){if(!t?.filaments||t.filaments.length===0)return;const r=NO(e);if(r.length===0)return;const i=new Set(Object.values(n)),a=[];for(const c of t.filaments){const u=c.slot_id||0;if(u>0&&n[u]!==void 0){a.push({slot_id:u,globalTrayId:n[u]});continue}const d=r.find(b=>!i.has(b.globalTrayId)&&b.type?.toUpperCase()===c.type?.toUpperCase()&&Xi(b.color)===Xi(c.color)),f=d?void 0:r.find(b=>!i.has(b.globalTrayId)&&b.type?.toUpperCase()===c.type?.toUpperCase()&&Hd(b.color,c.color)),m=d||f?void 0:r.find(b=>!i.has(b.globalTrayId)&&b.type?.toUpperCase()===c.type?.toUpperCase()),g=d??f??m;g&&i.add(g.globalTrayId),a.push({slot_id:u,globalTrayId:g?.globalTrayId??-1})}const o=Math.max(...a.map(c=>c.slot_id||0));if(o<=0)return;const l=new Array(o).fill(-1);return a.forEach(c=>{c.slot_id&&c.slot_id>0&&(l[c.slot_id-1]=c.globalTrayId)}),l}const K7={useDefault:!0,manualMappings:{},autoConfigured:!1};function kBe(t,e,n,r,i,a){const o=vle({queries:t.map(b=>({queryKey:["printer-status",b],queryFn:()=>xe.getPrinterStatus(b),enabled:t.length>0,staleTime:5e3}))}),l=S.useMemo(()=>t.map((b,v)=>{const x=o[v],y=x?.data,w=e?.find(P=>P.id===b)?.name||`Printer ${b}`,A=NO(y),N=i[b]||K7,k=q7(n,y),T=N.useDefault?r:N.manualMappings,R=CBe(n,y,T),C=TBe(n?.filaments,A,T);return{printerId:b,printerName:w,status:y,isLoading:x?.isLoading??!1,loadedFilaments:A,autoMapping:k,finalMapping:R,matchStatus:C.status,exactMatches:C.exactMatches,typeOnlyMatches:C.typeOnlyMatches,missingTypes:C.missingTypes,totalSlots:C.totalSlots,config:N}}),[t,o,e,n,i,r]),c=o.some(b=>b.isLoading),u=(b,v)=>{a(x=>({...x,[b]:{...x[b]||K7,...v}}))},d=b=>{const v=l.find(M=>M.printerId===b);if(!v||!v.status||!n?.filaments)return;const x=q7(n,v.status);if(!x)return;const y={};x.forEach((M,w)=>{M!==-1&&(y[w+1]=M)}),u(b,{useDefault:!1,manualMappings:y,autoConfigured:!0})},f=()=>{for(const b of t)d(b)},m=b=>l.find(x=>x.printerId===b)?.finalMapping,g=l.every(b=>b.matchStatus!=="missing");return{printerResults:l,isLoading:c,perPrinterConfigs:i,updatePrinterConfig:u,autoConfigureAll:f,autoConfigurePrinter:d,getFinalMapping:m,allPrintersReady:g}}function jBe({printerResult:t,filamentReqs:e,onUpdateConfig:n}){const r=Yt(),[i,a]=S.useState(!1),o=(u,d)=>{if(u<=0)return;const f={...t.config.manualMappings};d===""?delete f[u]:f[u]=parseInt(d,10),n({useDefault:!1,manualMappings:f,autoConfigured:!1})},l=async()=>{a(!0);try{await xe.refreshPrinterStatus(t.printerId),await new Promise(u=>setTimeout(u,500)),await r.refetchQueries({queryKey:["printer-status",t.printerId]})}finally{a(!1)}},c=e.map(u=>{const d=u.slot_id||0,f=t.config.manualMappings[d];let m,g=!1;if(f!==void 0)m=t.loadedFilaments.find(v=>v.globalTrayId===f),g=!0;else{const v=new Set(Object.values(t.config.manualMappings)),x=t.loadedFilaments.find(w=>!v.has(w.globalTrayId)&&w.type?.toUpperCase()===u.type?.toUpperCase()&&Xi(w.color)===Xi(u.color)),y=x?void 0:t.loadedFilaments.find(w=>!v.has(w.globalTrayId)&&w.type?.toUpperCase()===u.type?.toUpperCase()&&Hd(w.color,u.color)),M=x||y?void 0:t.loadedFilaments.find(w=>!v.has(w.globalTrayId)&&w.type?.toUpperCase()===u.type?.toUpperCase());m=x??y??M}let b="mismatch";if(m){const v=m.type?.toUpperCase()===u.type?.toUpperCase(),x=Xi(m.color)===Xi(u.color)||Hd(m.color,u.color);v&&x?b="match":v&&(b="type_only")}return{req:u,loaded:m,status:b,isManual:g}});return s.jsxs("div",{className:"mt-2 bg-bambu-dark rounded-lg p-3 space-y-2",children:[s.jsxs("div",{className:"flex items-center justify-between mb-2",children:[s.jsx("span",{className:"text-xs text-bambu-gray",children:"Custom slot mapping"}),s.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:[s.jsx(vr,{className:`w-3 h-3 ${i?"animate-spin":""}`}),s.jsx("span",{children:"Re-read"})]})]}),c.map(({req:u,loaded:d,status:f,isManual:m},g)=>s.jsxs("div",{className:"grid items-center gap-2 text-xs",style:{gridTemplateColumns:"16px minmax(70px, 1fr) auto 2fr 16px"},children:[s.jsx("span",{title:`Required: ${u.type} - ${mg(u.color)}`,children:s.jsx(kj,{className:"w-3 h-3",fill:u.color,stroke:u.color})}),s.jsxs("span",{className:"text-white truncate",children:[u.type," ",s.jsxs("span",{className:"text-bambu-gray",children:["(",u.used_grams,"g)"]})]}),s.jsx("span",{className:"text-bambu-gray",children:"→"}),s.jsxs("select",{value:d?.globalTrayId??"",onChange:b=>o(u.slot_id||0,b.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 ${f==="match"?"border-bambu-green/50 text-bambu-green":f==="type_only"?"border-yellow-400/50 text-yellow-400":"border-orange-400/50 text-orange-400"} ${m?"ring-1 ring-blue-400/50":""}`,title:m?"Manually selected":"Auto-matched",children:[s.jsx("option",{value:"",className:"bg-bambu-dark text-bambu-gray",children:"-- Select slot --"}),t.loadedFilaments.map(b=>s.jsxs("option",{value:b.globalTrayId,className:"bg-bambu-dark text-white",children:[b.label,": ",b.type," (",b.colorName,")"]},b.globalTrayId))]}),f==="match"?s.jsx(fs,{className:"w-3 h-3 text-bambu-green"}):f==="type_only"?s.jsx("span",{title:"Same type, different color",children:s.jsx(Nn,{className:"w-3 h-3 text-yellow-400"})}):s.jsx("span",{title:"Filament type not loaded",children:s.jsx(Nn,{className:"w-3 h-3 text-orange-400"})})]},g))]})}function PBe({printers:t,selectedPrinterIds:e,onMultiSelect:n,isLoading:r=!1,allowMultiple:i=!1,showInactive:a=!1,printerMappingResults:o,filamentReqs:l,onAutoConfigurePrinter:c,onUpdatePrinterConfig:u}){const d=a?t:t.filter(w=>w.is_active),f=i&&e.length>1&&o&&l?.filaments&&l.filaments.length>0&&c&&u;if(r)return s.jsx("div",{className:"flex justify-center py-8",children:s.jsx(ft,{className:"w-6 h-6 text-bambu-green animate-spin"})});if(d.length===0)return s.jsxs("div",{className:"flex items-center gap-2 text-red-400 text-sm mb-4",children:[s.jsx(Ji,{className:"w-4 h-4"}),"No ",a?"":"active ","printers available"]});const m=w=>{i?e.includes(w)?n(e.filter(A=>A!==w)):n([...e,w]):n([w])},g=()=>{n(d.map(w=>w.id))},b=()=>{n([])},v=(w,A,N)=>{N.stopPropagation(),!(!c||!u)&&(A?c(w):u(w,{useDefault:!0,manualMappings:{},autoConfigured:!1}))},x=w=>e.includes(w),y=e.length,M=w=>o?.find(A=>A.printerId===w);return s.jsxs("div",{className:"space-y-2 mb-6",children:[i&&d.length>1&&s.jsxs("div",{className:"flex items-center justify-between text-xs text-bambu-gray mb-2",children:[s.jsx("span",{children:y===0?"Select printers":`${y} printer${y!==1?"s":""} selected`}),s.jsxs("div",{className:"flex gap-2",children:[y0&&s.jsx("button",{type:"button",onClick:b,className:"text-bambu-gray hover:text-white transition-colors",children:"Clear"})]})]}),d.map(w=>{const A=x(w.id),N=M(w.id),k=N&&!N.config.useDefault;return s.jsxs("div",{children:[s.jsxs("button",{type:"button",onClick:()=>m(w.id),className:`w-full flex items-center gap-3 p-3 rounded-lg border transition-colors ${A?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark hover:border-bambu-gray"} ${w.is_active?"":"opacity-60"}`,children:[s.jsx("div",{className:`p-2 rounded-lg ${A?"bg-bambu-green/20":"bg-bambu-dark-tertiary"}`,children:s.jsx(Rr,{className:`w-5 h-5 ${A?"text-bambu-green":"text-bambu-gray"}`})}),s.jsxs("div",{className:"text-left flex-1",children:[s.jsxs("p",{className:"text-white font-medium",children:[w.name,!w.is_active&&s.jsx("span",{className:"text-bambu-gray text-xs ml-2",children:"(inactive)"})]}),s.jsxs("p",{className:"text-xs text-bambu-gray",children:[w.model||"Unknown model"," • ",w.ip_address]})]}),i&&s.jsx("div",{className:`w-5 h-5 rounded border-2 flex items-center justify-center transition-colors ${A?"bg-bambu-green border-bambu-green":"border-bambu-gray/50"}`,children:A&&s.jsx(fs,{className:"w-3 h-3 text-white"})})]}),A&&f&&N&&s.jsxs("div",{className:"ml-4 mt-2 mb-3",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",onClick:T=>T.stopPropagation(),children:[s.jsx("input",{type:"checkbox",checked:k,onChange:T=>v(w.id,T.target.checked,T),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"}),s.jsx("span",{className:"text-xs text-bambu-gray",children:"Custom mapping"})]}),s.jsxs("span",{className:`text-xs ml-2 ${N.matchStatus==="full"?"text-bambu-green":N.matchStatus==="partial"?"text-yellow-400":"text-orange-400"}`,children:["(",N.exactMatches,"/",N.totalSlots," matched)"]}),N.isLoading&&s.jsx(vr,{className:"w-3 h-3 text-bambu-gray animate-spin"}),k&&s.jsxs("button",{type:"button",onClick:T=>{T.stopPropagation(),c(w.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:[s.jsx(Che,{className:"w-3 h-3"}),"Auto"]})]}),k&&s.jsx(jBe,{printerResult:N,filamentReqs:l.filaments,onUpdateConfig:T=>u(w.id,T)})]})]},w.id)}),y===0&&s.jsxs("p",{className:"text-xs text-orange-400 mt-1 flex items-center gap-1",children:[s.jsx(Ji,{className:"w-3 h-3"}),"Select at least one printer"]})]})}function RBe({plates:t,isMultiPlate:e,selectedPlate:n,onSelect:r}){return!e||t.length<=1?null:s.jsxs("div",{className:"mb-4",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[s.jsx(el,{className:"w-4 h-4 text-bambu-gray"}),s.jsx("span",{className:"text-sm text-bambu-gray",children:"Select Plate to Print"}),!n&&s.jsxs("span",{className:"text-xs text-orange-400 flex items-center gap-1",children:[s.jsx(Nn,{className:"w-3 h-3"}),"Selection required"]})]}),s.jsx("div",{className:"grid grid-cols-2 gap-2",children:t.map(i=>s.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?s.jsx("img",{src:i.thumbnail_url,alt:`Plate ${i.index}`,className:"w-10 h-10 rounded object-cover bg-bambu-dark-tertiary"}):s.jsx("div",{className:"w-10 h-10 rounded bg-bambu-dark-tertiary flex items-center justify-center",children:s.jsx(el,{className:"w-5 h-5 text-bambu-gray"})}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("p",{className:"text-sm text-white font-medium truncate",children:i.name||`Plate ${i.index}`}),s.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?` • ${EBe(i.print_time_seconds)}`:""]})]}),n===i.index&&s.jsx(fs,{className:"w-4 h-4 text-bambu-green flex-shrink-0"})]},i.index))})]})}function DBe({printerId:t,filamentReqs:e,manualMappings:n,onManualMappingChange:r,defaultExpanded:i=!1}){const a=Yt(),[o,l]=S.useState(!1),[c,u]=S.useState(i),{data:d}=lt({queryKey:["printer-status",t],queryFn:()=>xe.getPrinterStatus(t),enabled:!!t}),{loadedFilaments:f,filamentComparison:m,hasTypeMismatch:g,hasColorMismatch:b}=RJ(e,d,n);if(!(e?.filaments&&e.filaments.length>0)||!d)return null;const x=g?"#f97316":b?"#facc15":"#00ae42",y=(w,A)=>{if(w>0)if(A===""){const N={...n};delete N[w],r(N)}else r({...n,[w]:parseInt(A,10)})},M=async()=>{l(!0);try{await xe.refreshPrinterStatus(t),await new Promise(w=>setTimeout(w,500)),await a.refetchQueries({queryKey:["printer-status",t]})}finally{l(!1)}};return s.jsxs("div",{className:"mb-4",children:[s.jsxs("button",{type:"button",onClick:()=>u(!c),className:"flex items-center gap-2 text-sm text-bambu-gray hover:text-white transition-colors w-full",children:[s.jsx(kj,{className:"w-4 h-4",fill:x,stroke:"none"}),s.jsx("span",{children:"Filament Mapping"}),g?s.jsx("span",{className:"text-xs text-orange-400",children:"(Type not found)"}):b?s.jsx("span",{className:"text-xs text-yellow-400",children:"(Color mismatch)"}):s.jsx("span",{className:"text-xs text-bambu-green",children:"(Ready)"}),c?s.jsx(Qc,{className:"w-4 h-4 ml-auto"}):s.jsx(Zi,{className:"w-4 h-4 ml-auto"})]}),c&&s.jsxs("div",{className:"mt-2 bg-bambu-dark rounded-lg p-3 space-y-2",children:[s.jsxs("div",{className:"flex items-center justify-between mb-2",children:[s.jsx("span",{className:"text-xs text-bambu-gray",children:"Click to change slot assignment"}),s.jsxs("button",{type:"button",onClick:M,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:o,children:[s.jsx(vr,{className:`w-3 h-3 ${o?"animate-spin":""}`}),s.jsx("span",{children:"Re-read"})]})]}),m.map((w,A)=>s.jsxs("div",{className:"grid items-center gap-2 text-xs",style:{gridTemplateColumns:"16px minmax(70px, 1fr) auto 2fr 16px"},children:[s.jsx("span",{title:`Required: ${w.type} - ${mg(w.color)}`,children:s.jsx(kj,{className:"w-3 h-3",fill:w.color,stroke:w.color})}),s.jsxs("span",{className:"text-white truncate",children:[w.type," ",s.jsxs("span",{className:"text-bambu-gray",children:["(",w.used_grams,"g)"]})]}),s.jsx("span",{className:"text-bambu-gray",children:"→"}),s.jsxs("select",{value:w.loaded?.globalTrayId??"",onChange:N=>y(w.slot_id||0,N.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 ${w.status==="match"?"border-bambu-green/50 text-bambu-green":w.status==="type_only"?"border-yellow-400/50 text-yellow-400":"border-orange-400/50 text-orange-400"} ${w.isManual?"ring-1 ring-blue-400/50":""}`,title:w.isManual?"Manually selected":"Auto-matched",children:[s.jsx("option",{value:"",className:"bg-bambu-dark text-bambu-gray",children:"-- Select slot --"}),f.map(N=>s.jsxs("option",{value:N.globalTrayId,className:"bg-bambu-dark text-white",children:[N.label,": ",N.type," (",N.colorName,")"]},N.globalTrayId))]}),w.status==="match"?s.jsx(fs,{className:"w-3 h-3 text-bambu-green"}):w.status==="type_only"?s.jsx("span",{title:"Same type, different color",children:s.jsx(Nn,{className:"w-3 h-3 text-yellow-400"})}):s.jsx("span",{title:"Filament type not loaded",children:s.jsx(Nn,{className:"w-3 h-3 text-orange-400"})})]},A)),g&&s.jsx("p",{className:"text-xs text-orange-400 mt-2",children:"Required filament type not found in printer."})]})]})}const OBe=[{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 LBe({options:t,onChange:e,defaultExpanded:n=!1}){const[r,i]=S.useState(n),a=o=>{e({...t,[o]:!t[o]})};return s.jsxs("div",{className:"mb-4",children:[s.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:[s.jsx(j2,{className:"w-4 h-4"}),s.jsx("span",{children:"Print Options"}),r?s.jsx(Qc,{className:"w-4 h-4 ml-auto"}):s.jsx(Zi,{className:"w-4 h-4 ml-auto"})]}),r&&s.jsx("div",{className:"mt-2 bg-bambu-dark rounded-lg p-3 space-y-2",children:OBe.map(({key:o,label:l,desc:c})=>s.jsxs("label",{className:"flex items-center justify-between cursor-pointer group",children:[s.jsxs("div",{children:[s.jsx("span",{className:"text-sm text-white",children:l}),s.jsx("p",{className:"text-xs text-bambu-gray",children:c})]}),s.jsx("div",{className:`relative w-10 h-5 rounded-full transition-colors ${t[o]?"bg-bambu-green":"bg-bambu-dark-tertiary"}`,onClick:()=>a(o),children:s.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 IBe({options:t,onChange:e}){const n=r=>{e({...t,scheduleType:r})};return s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-2",children:"When to print"}),s.jsxs("div",{className:"flex gap-2",children:[s.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:()=>n("asap"),children:[s.jsx(Gn,{className:"w-4 h-4"}),"ASAP"]}),s.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:()=>n("scheduled"),children:[s.jsx(Qr,{className:"w-4 h-4"}),"Scheduled"]}),s.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:()=>n("manual"),children:[s.jsx(RW,{className:"w-4 h-4"}),"Queue Only"]})]})]}),t.scheduleType==="scheduled"&&s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Date & Time"}),s.jsx("input",{type:"datetime-local",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:t.scheduledTime,onChange:r=>e({...t,scheduledTime:r.target.value}),min:NBe(),required:!0})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"checkbox",id:"requirePrevious",checked:t.requirePreviousSuccess,onChange:r=>e({...t,requirePreviousSuccess:r.target.checked}),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),s.jsx("label",{htmlFor:"requirePrevious",className:"text-sm text-bambu-gray",children:"Only start if previous print succeeded"})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"checkbox",id:"autoOffAfter",checked:t.autoOffAfter,onChange:r=>e({...t,autoOffAfter:r.target.checked}),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),s.jsxs("label",{htmlFor:"autoOffAfter",className:"text-sm text-bambu-gray flex items-center gap-1",children:[s.jsx(cu,{className:"w-3.5 h-3.5"}),"Power off printer when done"]})]}),s.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 cp={bed_levelling:!0,flow_cali:!1,vibration_cali:!0,layer_inspect:!1,timelapse:!1},FBe={scheduleType:"asap",scheduledTime:"",requirePreviousSuccess:!1,autoOffAfter:!1};function Rf({mode:t,archiveId:e,libraryFileId:n,archiveName:r,queueItem:i,onClose:a,onSuccess:o}){const l=Yt(),{showToast:c}=tr(),u=!!n&&!e,[d,f]=S.useState(()=>t==="edit-queue-item"&&i?.printer_id?[i.printer_id]:[]),[m,g]=S.useState(()=>t==="edit-queue-item"&&i?i.plate_id:null),[b,v]=S.useState(()=>t==="edit-queue-item"&&i?{bed_levelling:i.bed_levelling??cp.bed_levelling,flow_cali:i.flow_cali??cp.flow_cali,vibration_cali:i.vibration_cali??cp.vibration_cali,layer_inspect:i.layer_inspect??cp.layer_inspect,timelapse:i.timelapse??cp.timelapse}:cp),[x,y]=S.useState(()=>{if(t==="edit-queue-item"&&i){let ve="asap";i.manual_start?ve="manual":i.scheduled_time&&!W7(i.scheduled_time)&&(ve="scheduled");let he="";return i.scheduled_time&&!W7(i.scheduled_time)&&(he=new Date(i.scheduled_time).toISOString().slice(0,16)),{scheduleType:ve,scheduledTime:he,requirePreviousSuccess:i.require_previous_success,autoOffAfter:i.auto_off_after}}return FBe}),[M,w]=S.useState(()=>{if(t==="edit-queue-item"&&i?.ams_mapping&&Array.isArray(i.ams_mapping)){const ve={};return i.ams_mapping.forEach((he,B)=>{he!==-1&&(ve[B+1]=he)}),ve}return{}}),[A,N]=S.useState({}),[k]=S.useState(()=>t==="edit-queue-item"&&i?.printer_id?[i.printer_id]:[]),[T]=S.useState(()=>t==="edit-queue-item"&&i?i.plate_id:null),[R,C]=S.useState(!1),[P,F]=S.useState({current:0,total:0}),L=d.length,K=d.length>0?d[0]:null,{data:D}=lt({queryKey:["settings"],queryFn:xe.getSettings}),{data:W,isLoading:Y}=lt({queryKey:["printers"],queryFn:xe.getPrinters}),{data:q,isError:Q}=lt({queryKey:["archive-plates",e],queryFn:()=>xe.getArchivePlates(e),enabled:!!e&&!u,retry:!1}),{data:re}=lt({queryKey:["library-file-plates",n],queryFn:()=>xe.getLibraryFilePlates(n),enabled:u&&!!n}),ne=u?re:q,{data:U,isError:G}=lt({queryKey:["archive-filaments",e,m],queryFn:()=>xe.getArchiveFilamentRequirements(e,m??void 0),enabled:!!e&&!u&&(m!==null||!ne?.is_multi_plate),retry:!1}),{data:te}=lt({queryKey:["library-file-filaments",n,m],queryFn:()=>xe.getLibraryFileFilamentRequirements(n,m??void 0),enabled:u&&!!n&&(m!==null||!ne?.is_multi_plate)}),ie=!u&&(Q||G),oe=u?te:U,{data:ce}=lt({queryKey:["printer-status",K],queryFn:()=>xe.getPrinterStatus(K),enabled:!!K}),{amsMapping:me}=RJ(oe,ce,M),Ae=kBe(d,W,oe,M,A,N);S.useEffect(()=>{ne?.plates?.length===1&&!m&&g(ne.plates[0].index)},[ne,m]),S.useEffect(()=>{if(t==="edit-queue-item")return;const ve=W?.filter(he=>he.is_active)||[];ve.length===1&&d.length===0&&f([ve[0].id])},[t,W,d.length]),S.useEffect(()=>{t==="edit-queue-item"?(JSON.stringify(d.sort())!==JSON.stringify(k.sort())||m!==T)&&(w({}),N({})):(w({}),N({}))},[t,d,m,k,T]),S.useEffect(()=>{if(!D?.per_printer_mapping_expanded||d.length<=1)return;const ve=d.filter(he=>!A[he]||A[he].useDefault);ve.length>0&&ve.forEach(he=>{Ae.autoConfigurePrinter(he)})},[D?.per_printer_mapping_expanded,d,A,Ae]),S.useEffect(()=>{const ve=he=>{he.key==="Escape"&&!R&&a()};return window.addEventListener("keydown",ve),()=>window.removeEventListener("keydown",ve)},[a,R]);const ge=ne?.is_multi_plate??!1,Ne=ne?.plates??[],Se=ht({mutationFn:ve=>xe.addToQueue(ve)}),J=ht({mutationFn:ve=>xe.updateQueueItem(i.id,ve),onSuccess:()=>{l.invalidateQueries({queryKey:["queue"]}),c("Queue item updated"),o?.(),a()},onError:ve=>{c(ve.message||"Failed to update queue item","error")}}),Ve=async ve=>{if(ve?.preventDefault(),d.length===0){c("Please select at least one printer","error");return}C(!0),F({current:0,total:d.length});const he={success:0,failed:0,errors:[]},B=le=>{if(d.length>1){const _e=A[le];if(_e&&!_e.useDefault)return Ae.getFinalMapping(le)}return me},I=le=>({printer_id:le,archive_id:u?void 0:e,library_file_id:u?n:void 0,require_previous_success:x.requirePreviousSuccess,auto_off_after:x.autoOffAfter,manual_start:x.scheduleType==="manual",ams_mapping:B(le),plate_id:m,scheduled_time:x.scheduleType==="scheduled"&&x.scheduledTime?new Date(x.scheduledTime).toISOString():void 0,...b});for(let le=0;leKe.id===_e)?.name||`Printer ${_e}`;he.errors.push(`${we}: ${Ee.message}`)}}if(C(!1),he.failed===0){const le=t==="reprint"?"sent to":t==="edit-queue-item"?"updated/queued for":"queued for";he.success===1?c(t==="edit-queue-item"?"Queue item updated":`Print ${le} printer`):c(`Print ${le} ${he.success} printers`),l.invalidateQueries({queryKey:["queue"]}),o?.(),a()}else he.success===0?c(`Failed: ${he.errors[0]}`,"error"):(c(`${he.success} succeeded, ${he.failed} failed`,"error"),l.invalidateQueries({queryKey:["queue"]}))},H=R||J.isPending,$=S.useMemo(()=>!(H||d.length===0||!u&&ge&&!m),[d.length,ge,m,H,u]),z=(()=>{const ve=d.length;return t==="reprint"?{title:u?"Print":"Re-print",icon:Rr,submitText:ve>1?`Print to ${ve} Printers`:"Print",submitIcon:Rr,loadingText:P.total>1?`Sending ${P.current}/${P.total}...`:"Sending..."}:t==="add-to-queue"?{title:"Schedule Print",icon:Qr,submitText:ve>1?`Queue to ${ve} Printers`:"Add to Queue",submitIcon:Qr,loadingText:P.total>1?`Adding ${P.current}/${P.total}...`:"Adding..."}:{title:"Edit Queue Item",icon:No,submitText:"Save",submitIcon:No,loadingText:P.total>1?`Saving ${P.current}/${P.total}...`:"Saving..."}})(),V=z.icon,Z=z.submitIcon,de=K&&(u||(ge?m!==null:!0));return s.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:R?void 0:a,children:s.jsx(wt,{className:"w-full max-w-lg max-h-[90vh] overflow-y-auto",onClick:ve=>ve.stopPropagation(),children:s.jsxs(Mt,{className:t==="reprint"?"":"p-0",children:[s.jsxs("div",{className:`flex items-center justify-between ${t==="reprint"?"mb-4":"p-4 border-b border-bambu-dark-tertiary"}`,children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(V,{className:"w-5 h-5 text-bambu-green"}),s.jsx("h2",{className:"text-lg font-semibold text-white",children:z.title})]}),s.jsx(Ce,{variant:"ghost",size:"sm",onClick:a,disabled:R,children:s.jsx(Ft,{className:"w-5 h-5"})})]}),s.jsxs("form",{onSubmit:Ve,className:t==="reprint"?"":"p-4 space-y-4",children:[s.jsx("p",{className:`text-sm text-bambu-gray ${t==="reprint"?"mb-4":""}`,children:t==="reprint"?s.jsxs(s.Fragment,{children:["Send ",s.jsx("span",{className:"text-white",children:r})," to printer(s)"]}):s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"block text-bambu-gray mb-1",children:"Print Job"}),s.jsx("span",{className:"text-white font-medium truncate block",children:r})]})}),s.jsx(PBe,{printers:W||[],selectedPrinterIds:d,onMultiSelect:f,isLoading:Y,allowMultiple:!0,showInactive:t==="edit-queue-item",printerMappingResults:Ae.printerResults,filamentReqs:oe,onAutoConfigurePrinter:Ae.autoConfigurePrinter,onUpdatePrinterConfig:Ae.updatePrinterConfig}),s.jsx(RBe,{plates:Ne,isMultiPlate:ge,selectedPlate:m,onSelect:g}),ie&&s.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:[s.jsx(Ji,{className:"w-4 h-4 text-orange-400 mt-0.5 flex-shrink-0"}),s.jsx("p",{className:"text-orange-400",children:"Archive data unavailable. The source file may have been deleted. Filament mapping is disabled."})]}),de&&!ie&&d.length===1&&s.jsx(DBe,{printerId:K,filamentReqs:oe,manualMappings:M,onManualMappingChange:w,defaultExpanded:D?.per_printer_mapping_expanded??!1}),(t==="reprint"||L>0)&&s.jsx(LBe,{options:b,onChange:v}),t!=="reprint"&&s.jsx(IBe,{options:x,onChange:y}),J.isError&&s.jsx("div",{className:"mb-4 p-3 bg-red-500/20 border border-red-500/50 rounded-lg text-sm text-red-400",children:J.error?.message||"Failed to complete operation"}),s.jsxs("div",{className:`flex gap-3 ${t==="reprint"?"":"pt-2"}`,children:[s.jsx(Ce,{type:"button",variant:"secondary",onClick:a,className:"flex-1",disabled:R,children:"Cancel"}),s.jsx(Ce,{type:"submit",disabled:!$,className:"flex-1",children:H?s.jsxs(s.Fragment,{children:[s.jsx(ft,{className:"w-4 h-4 animate-spin"}),z.loadingText]}):s.jsxs(s.Fragment,{children:[s.jsx(Z,{className:"w-4 h-4"}),z.submitText]})})]})]})]})})})}function UBe({onClose:t,initialFiles:e}){const n=Yt(),{showToast:r}=tr(),i=S.useRef(null),[a,o]=S.useState(()=>e?.filter(T=>T.name.endsWith(".3mf")).map(T=>({file:T,status:"pending"}))||[]),[l,c]=S.useState(!1),[u,d]=S.useState(),[f,m]=S.useState(null);S.useEffect(()=>{const T=R=>{R.key==="Escape"&&t()};return window.addEventListener("keydown",T),()=>window.removeEventListener("keydown",T)},[t]);const{data:g}=lt({queryKey:["printers"],queryFn:xe.getPrinters}),b=ht({mutationFn:T=>xe.uploadArchivesBulk(T,u),onSuccess:T=>{m(T),n.invalidateQueries({queryKey:["archives"]}),n.invalidateQueries({queryKey:["archiveStats"]}),o(R=>R.map(C=>{const P=T.results.find(L=>L.filename===C.file.name),F=T.errors.find(L=>L.filename===C.file.name);return P?{...C,status:"success",archiveId:P.id}:F?{...C,status:"error",error:F.error}:C})),T.failed===0?r(`${T.uploaded} file${T.uploaded!==1?"s":""} uploaded`):T.uploaded===0?r(`Failed to upload ${T.failed} file${T.failed!==1?"s":""}`,"error"):r(`${T.uploaded} uploaded, ${T.failed} failed`,"warning")},onError:()=>{o(T=>T.map(R=>({...R,status:"error",error:"Upload failed"}))),r("Upload failed","error")}}),v=S.useCallback(T=>{T.preventDefault(),c(!0)},[]),x=S.useCallback(T=>{T.preventDefault(),c(!1)},[]),y=S.useCallback(T=>{T.preventDefault(),c(!1);const R=Array.from(T.dataTransfer.files).filter(C=>C.name.endsWith(".3mf"));R.length>0&&o(C=>[...C,...R.map(P=>({file:P,status:"pending"}))])},[]),M=S.useCallback(T=>{const R=Array.from(T.target.files||[]).filter(C=>C.name.endsWith(".3mf"));R.length>0&&o(C=>[...C,...R.map(P=>({file:P,status:"pending"}))]),i.current&&(i.current.value="")},[]),w=S.useCallback(T=>{o(R=>R.filter((C,P)=>P!==T))},[]),A=()=>{if(a.length===0)return;const T=a.filter(R=>R.status==="pending");T.length!==0&&(o(R=>R.map(C=>C.status==="pending"?{...C,status:"uploading"}:C)),b.mutate(T.map(R=>R.file)))},N=a.filter(T=>T.status==="pending").length,k=b.isPending;return s.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:s.jsx(wt,{className:"w-full max-w-2xl max-h-[90vh] flex flex-col",children:s.jsxs(Mt,{className:"p-0 flex flex-col h-full",children:[s.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[s.jsx("h2",{className:"text-xl font-semibold text-white",children:"Upload 3MF Files"}),s.jsx("button",{onClick:t,className:"text-bambu-gray hover:text-white transition-colors",children:s.jsx(Ft,{className:"w-5 h-5"})})]}),s.jsx("div",{className:"p-4",children:s.jsxs("div",{className:`border-2 border-dashed rounded-lg p-8 text-center transition-colors ${l?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary hover:border-bambu-gray"}`,onDragOver:v,onDragLeave:x,onDrop:y,children:[s.jsx(bi,{className:"w-12 h-12 mx-auto mb-4 text-bambu-gray"}),s.jsx("p",{className:"text-white mb-2",children:"Drag & drop .3mf files here"}),s.jsx("p",{className:"text-bambu-gray text-sm mb-4",children:"or"}),s.jsx(Ce,{variant:"secondary",onClick:()=>i.current?.click(),disabled:k,children:"Browse Files"}),s.jsx("input",{ref:i,type:"file",accept:".3mf",multiple:!0,className:"hidden",onChange:M})]})}),s.jsxs("div",{className:"px-4 pb-4",children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-2",children:"Associate with printer (optional)"}),s.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:u||"",onChange:T=>d(T.target.value?Number(T.target.value):void 0),disabled:k,children:[s.jsx("option",{value:"",children:"No printer"}),g?.map(T=>s.jsx("option",{value:T.id,children:T.name},T.id))]})]}),a.length>0&&s.jsx("div",{className:"px-4 pb-4 max-h-60 overflow-y-auto",children:s.jsx("div",{className:"space-y-2",children:a.map((T,R)=>s.jsxs("div",{className:"flex items-center gap-3 p-3 bg-bambu-dark rounded-lg",children:[s.jsx(S2,{className:"w-5 h-5 text-bambu-gray flex-shrink-0"}),s.jsx("span",{className:"flex-1 text-white text-sm truncate",children:T.file.name}),s.jsxs("span",{className:"text-xs text-bambu-gray",children:[(T.file.size/(1024*1024)).toFixed(1)," MB"]}),T.status==="pending"&&s.jsx("button",{onClick:()=>w(R),className:"text-bambu-gray hover:text-red-400 transition-colors",disabled:k,children:s.jsx(Ft,{className:"w-4 h-4"})}),T.status==="uploading"&&s.jsx(ft,{className:"w-4 h-4 text-bambu-green animate-spin"}),T.status==="success"&&s.jsx(mr,{className:"w-4 h-4 text-bambu-green"}),T.status==="error"&&s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-xs text-red-400",children:T.error}),s.jsx(Ji,{className:"w-4 h-4 text-red-400"})]})]},`${T.file.name}-${R}`))})}),f&&s.jsx("div",{className:"px-4 pb-4",children:s.jsx("div",{className:"p-3 bg-bambu-dark rounded-lg",children:s.jsxs("p",{className:"text-sm text-white",children:[s.jsx("span",{className:"text-bambu-green",children:f.uploaded})," uploaded",f.failed>0&&s.jsxs(s.Fragment,{children:[", ",s.jsx("span",{className:"text-red-400",children:f.failed})," failed"]})]})})}),s.jsxs("div",{className:"flex gap-3 p-4 border-t border-bambu-dark-tertiary",children:[s.jsx(Ce,{variant:"secondary",onClick:t,className:"flex-1",children:f?"Close":"Cancel"}),!f&&s.jsx(Ce,{onClick:A,disabled:N===0||k,className:"flex-1",children:k?s.jsxs(s.Fragment,{children:[s.jsx(ft,{className:"w-4 h-4 animate-spin"}),"Uploading..."]}):s.jsxs(s.Fragment,{children:[s.jsx(bi,{className:"w-4 h-4"}),"Upload ",N>0&&`(${N})`]})})]})]})})})}const zBe=["Adhesion failure","Spaghetti / Detached","Layer shift","Clogged nozzle","Filament runout","Warping","Stringing","Under-extrusion","Power failure","User cancelled","Other"],BBe=[{value:"completed",label:"Completed"},{value:"failed",label:"Failed"},{value:"aborted",label:"Cancelled"},{value:"printing",label:"Printing"}];function DJ({archive:t,onClose:e,existingTags:n=[]}){S.useEffect(()=>{const oe=ce=>{ce.key==="Escape"&&e()};return window.addEventListener("keydown",oe),()=>window.removeEventListener("keydown",oe)},[e]);const r=Yt(),[i,a]=S.useState(t.print_name||""),[o,l]=S.useState(t.printer_id),[c,u]=S.useState(t.project_id??null),[d,f]=S.useState(t.notes||""),[m,g]=S.useState(t.tags||""),[b,v]=S.useState(t.failure_reason||""),[x,y]=S.useState(t.status),[M,w]=S.useState(t.quantity??1),[A,N]=S.useState(t.photos||[]),[k,T]=S.useState(!1),[R,C]=S.useState(!1),P=S.useRef(null),F=S.useRef(null),L=S.useRef(null),{data:K}=lt({queryKey:["printers"],queryFn:xe.getPrinters}),{data:D}=lt({queryKey:["projects"],queryFn:()=>xe.getProjects()}),{data:W}=lt({queryKey:["archives"],queryFn:()=>xe.getArchives(void 0,1e3,0),enabled:n.length===0}),Y=n.length>0?n:[...new Set(W?.flatMap(oe=>oe.tags?.split(",").map(ce=>ce.trim())||[]).filter(Boolean)||[])].sort(),q=m.split(",").map(oe=>oe.trim()).filter(Boolean),Q=Y.filter(oe=>!q.includes(oe)),re=oe=>{if(!q.includes(oe)){const ce=[...q,oe].join(", ");g(ce)}L.current!==null&&clearTimeout(L.current),P.current?.focus()},ne=oe=>{const ce=q.filter(me=>me!==oe).join(", ");g(ce)},U=ht({mutationFn:oe=>xe.updateArchive(t.id,oe),onSuccess:()=>{r.invalidateQueries({queryKey:["archives"]}),r.invalidateQueries({queryKey:["projects"]}),e()}}),G=async oe=>{const ce=oe.target.files?.[0];if(ce){T(!0);try{const me=await xe.uploadArchivePhoto(t.id,ce);N(me.photos),r.invalidateQueries({queryKey:["archives"]})}catch(me){console.error("Failed to upload photo:",me)}finally{T(!1),F.current&&(F.current.value="")}}},te=async oe=>{try{const ce=await xe.deleteArchivePhoto(t.id,oe);N(ce.photos||[]),r.invalidateQueries({queryKey:["archives"]})}catch(ce){console.error("Failed to delete photo:",ce)}},ie=oe=>{oe.preventDefault();const ce={print_name:i||void 0,printer_id:o,project_id:c,notes:d||void 0,tags:m||void 0,quantity:M};x!==t.status&&(ce.status=x),x==="failed"||x==="aborted"?ce.failure_reason=b||void 0:(t.status==="failed"||t.status==="aborted")&&(ce.failure_reason=null),U.mutate(ce)};return s.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:e,children:s.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:oe=>oe.stopPropagation(),children:[s.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[s.jsx("h2",{className:"text-lg font-semibold text-white",children:"Edit Archive"}),s.jsx("button",{onClick:e,className:"text-bambu-gray hover:text-white transition-colors",children:s.jsx(Ft,{className:"w-5 h-5"})})]}),s.jsxs("form",{onSubmit:ie,className:"p-6 space-y-4 overflow-y-auto flex-1",children:[s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Name"}),s.jsx("input",{type:"text",value:i,onChange:oe=>a(oe.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:"Print name"})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Printer"}),s.jsxs("select",{value:o??"",onChange:oe=>l(oe.target.value?Number(oe.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:[s.jsx("option",{value:"",children:"No printer"}),K?.map(oe=>s.jsx("option",{value:oe.id,children:oe.name},oe.id))]})]}),s.jsxs("div",{children:[s.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[s.jsx(ga,{className:"w-4 h-4 inline mr-1"}),"Project"]}),s.jsxs("select",{value:c??"",onChange:oe=>u(oe.target.value?Number(oe.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:[s.jsx("option",{value:"",children:"No project"}),D?.map(oe=>s.jsx("option",{value:oe.id,children:oe.name},oe.id))]})]}),s.jsxs("div",{children:[s.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[s.jsx(yue,{className:"w-4 h-4 inline mr-1"}),"Items Printed"]}),s.jsx("input",{type:"number",min:1,value:M,onChange:oe=>w(Math.max(1,parseInt(oe.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"}),s.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:"Number of items produced in this print job"})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Notes"}),s.jsx("textarea",{value:d,onChange:oe=>f(oe.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:"Add notes about this print..."})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Tags"}),q.length>0&&s.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:q.map(oe=>s.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 bg-bambu-dark-tertiary rounded text-sm text-white",children:[s.jsx(Kp,{className:"w-3 h-3"}),oe,s.jsx("button",{type:"button",onClick:()=>ne(oe),className:"ml-0.5 text-bambu-gray hover:text-white",children:s.jsx(Ft,{className:"w-3 h-3"})})]},oe))}),s.jsxs("div",{className:"relative",children:[s.jsx("input",{ref:P,type:"text",value:m,onChange:oe=>g(oe.target.value),onFocus:()=>{L.current!==null&&clearTimeout(L.current),C(!0)},onBlur:()=>{L.current=window.setTimeout(()=>C(!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:q.length>0?"Add more tags...":"Add tags..."}),R&&Q.length>0&&s.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:[s.jsx("div",{className:"p-2 text-xs text-bambu-gray border-b border-bambu-dark-tertiary",children:"Existing tags (click to add)"}),s.jsx("div",{className:"p-2 flex flex-wrap gap-1.5",children:Q.map(oe=>s.jsx("button",{type:"button",onClick:()=>re(oe),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:oe},oe))})]})]})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Status"}),s.jsx("select",{value:x,onChange:oe=>{y(oe.target.value),oe.target.value==="completed"&&v("")},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:BBe.map(oe=>s.jsx("option",{value:oe.value,children:oe.label},oe.value))})]}),(x==="failed"||x==="aborted")&&s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Failure Reason"}),s.jsxs("select",{value:b,onChange:oe=>v(oe.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:[s.jsx("option",{value:"",children:"Select reason..."}),zBe.map(oe=>s.jsx("option",{value:oe,children:oe},oe))]})]}),s.jsxs("div",{children:[s.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[s.jsx(Gp,{className:"w-4 h-4 inline mr-1"}),"Photos of Printed Result"]}),s.jsxs("div",{className:"flex flex-wrap gap-2 mb-2",children:[A.map(oe=>s.jsxs("div",{className:"relative group",children:[s.jsx("img",{src:xe.getArchivePhotoUrl(t.id,oe),alt:"Print result",className:"w-20 h-20 object-cover rounded-lg border border-bambu-dark-tertiary"}),s.jsx("button",{type:"button",onClick:()=>te(oe),className:"absolute -top-1 -right-1 p-1 bg-red-500 rounded-full opacity-0 group-hover:opacity-100 transition-opacity",children:s.jsx(nn,{className:"w-3 h-3 text-white"})})]},oe)),s.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:[s.jsx("input",{ref:F,type:"file",accept:"image/jpeg,image/png,image/webp",onChange:G,className:"hidden",disabled:k}),k?s.jsx(ft,{className:"w-6 h-6 text-bambu-gray animate-spin"}):s.jsx(ur,{className:"w-6 h-6 text-bambu-gray"})]})]}),s.jsx("p",{className:"text-xs text-bambu-gray",children:"Click + to add photos of your printed result"})]}),s.jsxs("div",{className:"flex gap-3 pt-2",children:[s.jsx(Ce,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:"Cancel"}),s.jsxs(Ce,{type:"submit",disabled:U.isPending,className:"flex-1",children:[s.jsx(Ds,{className:"w-4 h-4"}),U.isPending?"Saving...":"Save"]})]})]})]})})}function OJ({x:t,y:e,items:n,onClose:r}){const i=S.useRef(null),[a,o]=S.useState(null),l=S.useRef(null),[c,u]=S.useState({x:t,y:e,visible:!1}),[d,f]=S.useState(!1),[m,g]=S.useState({});S.useEffect(()=>{const x=w=>{i.current&&!i.current.contains(w.target)&&r()},y=w=>{w.key==="Escape"&&r()},M=()=>{r()};return document.addEventListener("mousedown",x),document.addEventListener("keydown",y),document.addEventListener("scroll",M,!0),()=>{document.removeEventListener("mousedown",x),document.removeEventListener("keydown",y),document.removeEventListener("scroll",M,!0),l.current&&clearTimeout(l.current)}},[r]),S.useLayoutEffect(()=>{if(i.current){i.current.style.visibility="hidden",i.current.style.display="block";const x=i.current.getBoundingClientRect(),y=window.innerWidth,M=window.innerHeight,w=8;let A=t,N=e;t+x.width>y-w&&(A=Math.max(w,y-x.width-w)),AM-w&&(N=Math.max(w,M-x.height-w)),Nk),u({x:A,y:N,visible:!0})}},[t,e]);const b=(x,y)=>{l.current&&(clearTimeout(l.current),l.current=null);const M=y.getBoundingClientRect(),w=window.innerHeight,A=300,T=w-M.top-8A;g(R=>({...R,[x]:T?"bottom":"top"})),o(x)},v=()=>{l.current=window.setTimeout(()=>{o(null)},150)};return s.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((x,y)=>{if(x.divider)return s.jsx("div",{className:"my-1 border-t border-bambu-dark-tertiary"},y);const M=x.submenu&&x.submenu.length>0;return s.jsxs("div",{className:"relative",onMouseEnter:w=>M&&b(y,w.currentTarget),onMouseLeave:()=>M&&v(),children:[s.jsxs("button",{onMouseEnter:w=>M&&b(y,w.currentTarget.parentElement),onClick:()=>{M?o(a===y?null:y):x.disabled||(x.onClick(),r())},disabled:x.disabled,className:`w-full flex items-center gap-2 px-3 py-2 text-sm text-left transition-colors ${x.disabled?"text-bambu-gray cursor-not-allowed":x.danger?"text-red-400 hover:bg-red-400/10":"text-white hover:bg-bambu-dark-tertiary"} ${M&&a===y?"bg-bambu-dark-tertiary":""}`,children:[x.icon&&s.jsx("span",{className:"w-4 h-4 flex-shrink-0 flex items-center justify-center",children:x.icon}),s.jsx("span",{className:"flex-1",children:x.label}),M&&s.jsx($s,{className:"w-4 h-4 text-bambu-gray"})]}),M&&a===y&&s.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] ${d?"right-full mr-1":"left-full ml-1"} ${m[y]==="bottom"?"bottom-0":"top-0"}`,onMouseEnter:()=>{l.current&&(clearTimeout(l.current),l.current=null)},onMouseLeave:()=>v(),children:x.submenu.map((w,A)=>s.jsxs("button",{onClick:()=>{w.disabled||(w.onClick(),r())},disabled:w.disabled,className:`w-full flex items-center gap-2 px-3 py-2 text-sm text-left transition-colors ${w.disabled?"text-bambu-gray cursor-not-allowed":w.danger?"text-red-400 hover:bg-red-400/10":"text-white hover:bg-bambu-dark-tertiary"}`,children:[w.icon&&s.jsx("span",{className:"w-4 h-4 flex-shrink-0 flex items-center justify-center",children:w.icon}),w.label]},A))})]},y)})})}function $Be({selectedIds:t,existingTags:e,onClose:n}){const r=Yt(),{showToast:i}=tr(),[a,o]=S.useState(""),[l,c]=S.useState(new Set),[u,d]=S.useState("add");S.useEffect(()=>{const v=x=>{x.key==="Escape"&&n()};return window.addEventListener("keydown",v),()=>window.removeEventListener("keydown",v)},[n]);const f=ht({mutationFn:async()=>{const v=Array.from(l);let x=0;for(const y of t)try{const M=await xe.getArchive(y),w=M.tags?M.tags.split(",").map(N=>N.trim()).filter(Boolean):[];let A;u==="add"?A=[...new Set([...w,...v])]:A=w.filter(N=>!l.has(N)),await xe.updateArchive(y,{tags:A.join(", ")}),x++}catch(M){throw console.error(`Failed to update archive ${y}:`,M),new Error(`Failed on archive ${y}: ${M instanceof Error?M.message:"Unknown error"}`)}return{count:x,mode:u,tags:v}},onSuccess:({count:v,mode:x,tags:y})=>{r.invalidateQueries({queryKey:["archives"]}),i(`${x==="add"?"Added":"Removed"} ${y.length} tag${y.length!==1?"s":""} ${x==="add"?"to":"from"} ${v} archive${v!==1?"s":""}`),n()},onError:v=>{i(v.message||"Failed to update tags","error")}}),m=v=>{c(x=>{const y=new Set(x);return y.has(v)?y.delete(v):y.add(v),y})},g=()=>{a.trim()&&!l.has(a.trim())&&(c(v=>new Set([...v,a.trim()])),o(""))},b=v=>{v.key==="Enter"&&(v.preventDefault(),g())};return s.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:s.jsx(wt,{className:"w-full max-w-md",children:s.jsxs(Mt,{className:"p-0",children:[s.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(Kp,{className:"w-5 h-5 text-bambu-green"}),s.jsx("h2",{className:"text-xl font-semibold text-white",children:u==="add"?"Add Tags":"Remove Tags"})]}),s.jsx("button",{onClick:n,className:"text-bambu-gray hover:text-white transition-colors",children:s.jsx(Ft,{className:"w-5 h-5"})})]}),s.jsxs("div",{className:"p-4 space-y-4",children:[s.jsxs("p",{className:"text-sm text-bambu-gray",children:[u==="add"?"Add":"Remove"," tags for ",t.length," selected archive",t.length!==1?"s":""]}),s.jsxs("div",{className:"flex gap-2",children:[s.jsx(Ce,{size:"sm",variant:u==="add"?"primary":"secondary",onClick:()=>d("add"),children:"Add Tags"}),s.jsx(Ce,{size:"sm",variant:u==="remove"?"primary":"secondary",onClick:()=>d("remove"),children:"Remove Tags"})]}),u==="add"&&s.jsxs("div",{className:"flex gap-2",children:[s.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:a,onChange:v=>o(v.target.value),onKeyDown:b}),s.jsx(Ce,{size:"sm",variant:"secondary",onClick:g,disabled:!a.trim(),children:s.jsx(ur,{className:"w-4 h-4"})})]}),e.length>0&&s.jsxs("div",{children:[s.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:"Existing tags:"}),s.jsx("div",{className:"flex flex-wrap gap-2",children:e.map(v=>s.jsx("button",{onClick:()=>m(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&&s.jsxs("div",{children:[s.jsxs("p",{className:"text-xs text-bambu-gray mb-2",children:["Tags to ",u==="add"?"add":"remove",":"]}),s.jsx("div",{className:"flex flex-wrap gap-2",children:Array.from(l).map(v=>s.jsxs("span",{className:`px-2 py-1 rounded text-sm flex items-center gap-1 ${u==="add"?"bg-green-500/20 text-green-400":"bg-red-500/20 text-red-400"}`,children:[v,s.jsx("button",{onClick:()=>m(v),className:"hover:opacity-70",children:s.jsx(Ft,{className:"w-3 h-3"})})]},v))})]})]}),s.jsxs("div",{className:"flex gap-3 p-4 border-t border-bambu-dark-tertiary",children:[s.jsx(Ce,{variant:"secondary",onClick:n,className:"flex-1",children:"Cancel"}),s.jsx(Ce,{onClick:()=>f.mutate(),disabled:l.size===0||f.isPending,className:"flex-1",children:f.isPending?s.jsxs(s.Fragment,{children:[s.jsx(ft,{className:"w-4 h-4 animate-spin"}),"Processing..."]}):s.jsxs(s.Fragment,{children:[s.jsx(Kp,{className:"w-4 h-4"}),u==="add"?"Add Tags":"Remove Tags"]})})]})]})})})}function HBe({selectedIds:t,onClose:e}){const n=Yt(),{showToast:r}=tr(),{data:i,isLoading:a}=lt({queryKey:["projects"],queryFn:()=>xe.getProjects()});S.useEffect(()=>{const d=f=>{f.key==="Escape"&&e()};return window.addEventListener("keydown",d),()=>window.removeEventListener("keydown",d)},[e]);const o=()=>{n.invalidateQueries({queryKey:["archives"]}),n.invalidateQueries({queryKey:["projects"]}),n.invalidateQueries({queryKey:["project"]}),n.invalidateQueries({queryKey:["project-archives"]})},l=ht({mutationFn:async d=>(await xe.addArchivesToProject(d,t),d),onSuccess:d=>{const f=i?.find(m=>m.id===d);o(),r(`Added ${t.length} archive${t.length!==1?"s":""} to "${f?.name}"`),e()},onError:()=>{r("Failed to assign project","error")}}),c=ht({mutationFn:async()=>{for(const d of t)await xe.updateArchive(d,{project_id:null});return t.length},onSuccess:d=>{o(),r(`Removed ${d} archive${d!==1?"s":""} from project`),e()},onError:()=>{r("Failed to remove from project","error")}}),u=l.isPending||c.isPending;return s.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:s.jsx(wt,{className:"w-full max-w-md max-h-[80vh] flex flex-col",children:s.jsxs(Mt,{className:"p-0 flex flex-col min-h-0",children:[s.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary shrink-0",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(ga,{className:"w-5 h-5 text-bambu-green"}),s.jsx("h2",{className:"text-xl font-semibold text-white",children:"Assign to Project"})]}),s.jsx("button",{onClick:e,className:"text-bambu-gray hover:text-white transition-colors",disabled:u,children:s.jsx(Ft,{className:"w-5 h-5"})})]}),s.jsxs("div",{className:"p-4 space-y-3 overflow-y-auto min-h-0",children:[s.jsxs("p",{className:"text-sm text-bambu-gray",children:["Assign ",t.length," selected archive",t.length!==1?"s":""," to a project"]}),a?s.jsx("div",{className:"flex items-center justify-center py-8",children:s.jsx(ft,{className:"w-6 h-6 animate-spin text-bambu-gray"})}):s.jsxs("div",{className:"space-y-2",children:[s.jsxs("button",{onClick:()=>c.mutate(),disabled:u,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:[s.jsx("div",{className:"w-8 h-8 rounded-full bg-red-500/20 flex items-center justify-center shrink-0",children:s.jsx(Wi,{className:"w-4 h-4 text-red-400"})}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("p",{className:"text-white font-medium",children:"Remove from project"}),s.jsx("p",{className:"text-sm text-bambu-gray truncate",children:"Clear project assignment"})]}),c.isPending&&s.jsx(ft,{className:"w-4 h-4 animate-spin text-bambu-gray shrink-0"})]}),i&&i.length>0&&s.jsxs("div",{className:"flex items-center gap-2 py-2",children:[s.jsx("div",{className:"flex-1 h-px bg-bambu-dark-tertiary"}),s.jsx("span",{className:"text-xs text-bambu-gray",children:"or assign to"}),s.jsx("div",{className:"flex-1 h-px bg-bambu-dark-tertiary"})]}),i?.map(d=>s.jsxs("button",{onClick:()=>l.mutate(d.id),disabled:u,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:[s.jsx("div",{className:"w-8 h-8 rounded-full flex items-center justify-center shrink-0",style:{backgroundColor:d.color?`${d.color}20`:"rgb(var(--bambu-green) / 0.2)"},children:s.jsx(ga,{className:"w-4 h-4",style:{color:d.color||"rgb(var(--bambu-green))"}})}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("p",{className:"text-white font-medium truncate",children:d.name}),s.jsxs("p",{className:"text-sm text-bambu-gray truncate",children:[d.archive_count," archive",d.archive_count!==1?"s":"",d.status&&` • ${d.status}`]})]}),l.isPending&&l.variables===d.id&&s.jsx(ft,{className:"w-4 h-4 animate-spin text-bambu-gray shrink-0"})]},d.id)),(!i||i.length===0)&&s.jsx("p",{className:"text-center text-bambu-gray py-4",children:"No projects yet. Create one from the Projects page."})]})]}),s.jsx("div",{className:"flex gap-3 p-4 border-t border-bambu-dark-tertiary shrink-0",children:s.jsx(Ce,{variant:"secondary",onClick:e,className:"flex-1",disabled:u,children:"Cancel"})})]})})})}function VBe(t,e){return new Date(t,e+1,0).getDate()}function GBe(t,e){return new Date(t,e,1).getDay()}const WBe=["January","February","March","April","May","June","July","August","September","October","November","December"],qBe=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];function KBe({archives:t,onArchiveClick:e,highlightedArchiveId:n}){const r=new Date,[i,a]=S.useState(r.getMonth()),[o,l]=S.useState(r.getFullYear()),[c,u]=S.useState(null),[d,f]=S.useState(null),m=S.useMemo(()=>{const N=new Map;return t.forEach(k=>{const T=mi(k.completed_at||k.created_at)||new Date,R=`${T.getFullYear()}-${String(T.getMonth()+1).padStart(2,"0")}-${String(T.getDate()).padStart(2,"0")}`,C=N.get(R)||[];C.push(k),N.set(R,C)}),N},[t]),g=VBe(o,i),b=GBe(o,i),v=()=>{i===0?(a(11),l(o-1)):a(i-1)},x=()=>{i===11?(a(0),l(o+1)):a(i+1)},y=()=>{a(r.getMonth()),l(r.getFullYear())},M=[];for(let N=0;N{N!==c&&f(null),u(N)};return s.jsxs("div",{className:"flex flex-col lg:flex-row gap-6",children:[s.jsxs("div",{className:"flex-1",children:[s.jsxs("div",{className:"flex items-center justify-between mb-4",children:[s.jsx("button",{onClick:v,className:"p-2 hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:s.jsx(mf,{className:"w-5 h-5 text-bambu-gray"})}),s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsxs("h2",{className:"text-lg font-semibold text-white",children:[WBe[i]," ",o]}),s.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"})]}),s.jsx("button",{onClick:x,className:"p-2 hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:s.jsx($s,{className:"w-5 h-5 text-bambu-gray"})})]}),s.jsx("div",{className:"grid grid-cols-7 gap-1 mb-1",children:qBe.map(N=>s.jsx("div",{className:"text-center text-xs text-bambu-gray py-2",children:N},N))}),s.jsx("div",{className:"grid grid-cols-7 gap-1",children:M.map((N,k)=>{if(N===null)return s.jsx("div",{className:"aspect-square"},`empty-${k}`);const T=`${o}-${String(i+1).padStart(2,"0")}-${String(N).padStart(2,"0")}`,R=m.get(T)||[],C=R.length>0,P=N===r.getDate()&&i===r.getMonth()&&o===r.getFullYear(),F=T===c,L=R.filter(D=>D.status==="completed").length,K=R.filter(D=>D.status==="failed").length;return s.jsxs("button",{onClick:()=>A(F?null:T),className:`aspect-square rounded-lg p-1 flex flex-col items-center justify-center transition-colors relative ${F?"bg-bambu-green text-white":P?"bg-bambu-green/20 text-white ring-2 ring-bambu-green":C?"bg-bambu-dark-tertiary hover:bg-bambu-dark-tertiary/70 text-white":"hover:bg-bambu-dark-tertiary/50 text-bambu-gray"}`,children:[s.jsx("span",{className:`text-sm font-medium ${P&&!F?"text-bambu-green":""}`,children:N}),C&&s.jsxs("div",{className:"absolute bottom-1 left-1/2 -translate-x-1/2 flex items-center gap-1",children:[s.jsx("div",{className:`w-2 h-2 rounded-full ${K>0&&L===0?"bg-red-400":K>0?"bg-yellow-400":"bg-green-400"}`}),s.jsx("span",{className:"text-xs font-medium",children:R.length})]})]},N)})}),s.jsx("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:s.jsxs("div",{className:"grid grid-cols-3 gap-4 text-center",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-2xl font-bold text-white",children:t.filter(N=>{const k=new Date(N.completed_at||N.created_at);return k.getMonth()===i&&k.getFullYear()===o}).length}),s.jsx("div",{className:"text-xs text-bambu-gray",children:"Prints this month"})]}),s.jsxs("div",{children:[s.jsx("div",{className:"text-2xl font-bold text-green-400",children:t.filter(N=>{const k=new Date(N.completed_at||N.created_at);return k.getMonth()===i&&k.getFullYear()===o&&N.status==="completed"}).length}),s.jsx("div",{className:"text-xs text-bambu-gray",children:"Successful"})]}),s.jsxs("div",{children:[s.jsx("div",{className:"text-2xl font-bold text-red-400",children:t.filter(N=>{const k=new Date(N.completed_at||N.created_at);return k.getMonth()===i&&k.getFullYear()===o&&N.status==="failed"}).length}),s.jsx("div",{className:"text-xs text-bambu-gray",children:"Failed"})]})]})})]}),s.jsx("div",{className:"lg:w-80 bg-bambu-dark rounded-xl p-4",children:c?s.jsxs(s.Fragment,{children:[s.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"})}),w.length>0?s.jsx("div",{className:"space-y-2 max-h-96 overflow-y-auto",children:w.map(N=>{const k=N.id===d||N.id===n;return s.jsxs("button",{onClick:()=>{f(N.id),e?.(N)},className:`w-full flex items-center gap-3 p-2 rounded-lg transition-colors text-left ${k?"":"hover:bg-bambu-dark-tertiary"}`,style:k?{outline:"4px solid #facc15",outlineOffset:"2px"}:void 0,children:[N.thumbnail_path?s.jsx("img",{src:xe.getArchiveThumbnail(N.id),alt:"",className:"w-12 h-12 rounded object-cover"}):s.jsx("div",{className:"w-12 h-12 rounded bg-bambu-dark-tertiary flex items-center justify-center",children:s.jsx("span",{className:"text-xs text-bambu-gray",children:"3MF"})}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsx("p",{className:"text-sm text-white truncate",children:N.print_name||N.filename}),s.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[s.jsx("span",{className:N.status==="failed"?"text-red-400":"text-green-400",children:N.status==="failed"?"Failed":"Completed"}),N.filament_color&&s.jsx("div",{className:"flex gap-0.5",children:N.filament_color.split(",").map((T,R)=>s.jsx("div",{className:"w-3 h-3 rounded-full border border-white/20",style:{backgroundColor:T}},R))})]})]})]},N.id)})}):s.jsx("p",{className:"text-sm text-bambu-gray",children:"No prints on this day"})]}):s.jsx("div",{className:"text-center py-8",children:s.jsx("p",{className:"text-sm text-bambu-gray",children:"Select a day to see prints"})})})]})}function LJ({archiveId:t,archiveName:e,onClose:n}){const r=xe.getArchiveQRCodeUrl(t,300);S.useEffect(()=>{const a=o=>{o.key==="Escape"&&n()};return window.addEventListener("keydown",a),()=>window.removeEventListener("keydown",a)},[n]);const i=()=>{const a=document.createElement("a");a.href=r,a.download=`${e}_qrcode.png`,a.click()};return s.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:n,children:s.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary w-full max-w-sm",onClick:a=>a.stopPropagation(),children:[s.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[s.jsx("h2",{className:"text-lg font-semibold text-white",children:"QR Code"}),s.jsx("button",{onClick:n,className:"text-bambu-gray hover:text-white transition-colors",children:s.jsx(Ft,{className:"w-5 h-5"})})]}),s.jsxs("div",{className:"p-6 flex flex-col items-center",children:[s.jsx("p",{className:"text-sm text-bambu-gray mb-4 text-center truncate max-w-full",children:e}),s.jsx("div",{className:"bg-white p-4 rounded-lg mb-4",children:s.jsx("img",{src:r,alt:"QR Code",className:"w-64 h-64"})}),s.jsx("p",{className:"text-xs text-bambu-gray mb-4 text-center",children:"Scan to open this archive"}),s.jsxs(Ce,{onClick:i,className:"w-full",children:[s.jsx(Jr,{className:"w-4 h-4"}),"Download QR Code"]})]})]})})}function IJ({archiveId:t,archiveName:e,photos:n,onClose:r,onDelete:i}){const[a,o]=S.useState(0),[l,c]=S.useState(!1);if(S.useEffect(()=>{const g=b=>{b.key==="Escape"&&r(),b.key==="ArrowLeft"&&o(v=>Math.max(0,v-1)),b.key==="ArrowRight"&&o(v=>Math.min(n.length-1,v+1))};return window.addEventListener("keydown",g),()=>window.removeEventListener("keydown",g)},[r,n.length]),S.useEffect(()=>{a>=n.length&&o(Math.max(0,n.length-1))},[n.length,a]),n.length===0)return r(),null;const u=n[a],d=xe.getArchivePhotoUrl(t,u),f=()=>{const g=document.createElement("a");g.href=d,g.download=`${e}_photo_${a+1}.jpg`,g.click()},m=()=>{i&&c(!0)};return s.jsxs("div",{className:"fixed inset-0 bg-black/90 flex items-center justify-center z-50",onClick:r,children:[s.jsxs("div",{className:"relative w-full h-full flex flex-col",onClick:g=>g.stopPropagation(),children:[s.jsxs("div",{className:"flex items-center justify-between px-6 py-4 bg-black/50",children:[s.jsxs("div",{children:[s.jsx("h2",{className:"text-lg font-semibold text-white",children:e}),s.jsxs("p",{className:"text-sm text-bambu-gray",children:["Photo ",a+1," of ",n.length]})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs(Ce,{variant:"secondary",size:"sm",onClick:f,children:[s.jsx(Jr,{className:"w-4 h-4"}),"Download"]}),i&&s.jsx(Ce,{variant:"secondary",size:"sm",onClick:m,className:"text-red-400 hover:text-red-300",children:s.jsx(nn,{className:"w-4 h-4"})}),s.jsx("button",{onClick:r,className:"p-2 text-bambu-gray hover:text-white transition-colors",children:s.jsx(Ft,{className:"w-6 h-6"})})]})]}),s.jsxs("div",{className:"flex-1 min-h-0 flex items-center justify-center p-4 relative overflow-hidden",children:[a>0&&s.jsx("button",{onClick:()=>o(g=>g-1),className:"absolute left-4 z-10 p-3 bg-black/50 hover:bg-black/70 rounded-full transition-colors",children:s.jsx(mf,{className:"w-8 h-8 text-white"})}),s.jsx("img",{src:d,alt:`Photo ${a+1}`,className:"max-w-full max-h-full object-contain rounded-lg",style:{maxHeight:"calc(100vh - 200px)"}}),ao(g=>g+1),className:"absolute right-4 z-10 p-3 bg-black/50 hover:bg-black/70 rounded-full transition-colors",children:s.jsx($s,{className:"w-8 h-8 text-white"})})]}),n.length>1&&s.jsx("div",{className:"flex justify-center gap-2 p-4 bg-black/50",children:n.map((g,b)=>s.jsx("button",{onClick:()=>o(b),className:`w-16 h-16 rounded-lg overflow-hidden border-2 transition-colors ${b===a?"border-bambu-green":"border-transparent hover:border-bambu-gray"}`,children:s.jsx("img",{src:xe.getArchivePhotoUrl(t,g),alt:`Thumbnail ${b+1}`,className:"w-full h-full object-cover"})},g))})]}),l&&s.jsx(Fn,{title:"Delete Photo",message:"Delete this photo? This cannot be undone.",confirmText:"Delete",variant:"danger",onConfirm:()=>{i?.(u),c(!1)},onCancel:()=>c(!1)})]})}function ua(t){this.content=t}ua.prototype={constructor:ua,find:function(t){for(var e=0;e>1}};ua.from=function(t){if(t instanceof ua)return t;var e=[];if(t)for(var n in t)e.push(n,t[n]);return new ua(e)};function FJ(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),a=e.child(r);if(i==a){n+=i.nodeSize;continue}if(!i.sameMarkup(a))return n;if(i.isText&&i.text!=a.text){for(let o=0;i.text[o]==a.text[o];o++)n++;return n}if(i.content.size||a.content.size){let o=FJ(i.content,a.content,n+1);if(o!=null)return o}n+=i.nodeSize}}function UJ(t,e,n,r){for(let i=t.childCount,a=e.childCount;;){if(i==0||a==0)return i==a?null:{a:n,b:r};let o=t.child(--i),l=e.child(--a),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 u=0,d=Math.min(o.text.length,l.text.length);for(;ue&&r(c,i+l,a||null,o)!==!1&&c.content.size){let d=l+1;c.nodesBetween(Math.max(0,e-d),Math.min(c.content.size,n-d),r,i+d)}l=u}}descendants(e){this.nodesBetween(0,this.size,e)}textBetween(e,n,r,i){let a="",o=!0;return this.nodesBetween(e,n,(l,c)=>{let u=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&&u||l.isTextblock)&&r&&(o?o=!1:a+=r),a+=u},0),a}append(e){if(!e.size)return this;if(!this.size)return e;let n=this.lastChild,r=e.firstChild,i=this.content.slice(),a=0;for(n.isText&&n.sameMarkup(r)&&(i[i.length-1]=n.withText(n.text+r.text),a=1);ae)for(let a=0,o=0;oe&&((on)&&(l.isText?l=l.cut(Math.max(0,e-o),Math.min(l.text.length,n-o)):l=l.cut(Math.max(0,e-o-1),Math.min(l.content.size,n-o-1))),r.push(l),i+=l.nodeSize),o=c}return new _t(r,i)}cutByIndex(e,n){return e==n?_t.empty:e==0&&n==this.content.length?this:new _t(this.content.slice(e,n))}replaceChild(e,n){let r=this.content[e];if(r==n)return this;let i=this.content.slice(),a=this.size+n.nodeSize-r.nodeSize;return i[e]=n,new _t(i,a)}addToStart(e){return new _t([e].concat(this.content),this.size+e.nodeSize)}addToEnd(e){return new _t(this.content.concat(e),this.size+e.nodeSize)}eq(e){if(this.content.length!=e.content.length)return!1;for(let n=0;nthis.size||e<0)throw new RangeError(`Position ${e} outside of fragment (${this})`);for(let n=0,r=0;;n++){let i=this.child(n),a=r+i.nodeSize;if(a>=e)return a==e?d1(n+1,a):d1(n,r);r=a}}toString(){return"<"+this.toStringInner()+">"}toStringInner(){return this.content.join(", ")}toJSON(){return this.content.length?this.content.map(e=>e.toJSON()):null}static fromJSON(e,n){if(!n)return _t.empty;if(!Array.isArray(n))throw new RangeError("Invalid input for Fragment.fromJSON");return new _t(n.map(e.nodeFromJSON))}static fromArray(e){if(!e.length)return _t.empty;let n,r=0;for(let i=0;ithis.type.rank&&(n||(n=e.slice(0,i)),n.push(this),r=!0),n&&n.push(a)}}return n||(n=e.slice()),r||n.push(this),n}removeFromSet(e){for(let n=0;nr.type.rank-i.type.rank),n}};pr.none=[];class SS extends Error{}class Rt{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=BJ(this.content,e+this.openStart,n);return r&&new Rt(r,this.openStart,this.openEnd)}removeBetween(e,n){return new Rt(zJ(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 Rt.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 Rt(_t.fromJSON(e,n.content),r,i)}static maxOpen(e,n=!0){let r=0,i=0;for(let a=e.firstChild;a&&!a.isLeaf&&(n||!a.type.spec.isolating);a=a.firstChild)r++;for(let a=e.lastChild;a&&!a.isLeaf&&(n||!a.type.spec.isolating);a=a.lastChild)i++;return new Rt(e,r,i)}}Rt.empty=new Rt(_t.empty,0,0);function zJ(t,e,n){let{index:r,offset:i}=t.findIndex(e),a=t.maybeChild(r),{index:o,offset:l}=t.findIndex(n);if(i==e||a.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,a.copy(zJ(a.content,e-i-1,n-i-1)))}function BJ(t,e,n,r){let{index:i,offset:a}=t.findIndex(e),o=t.maybeChild(i);if(a==e||o.isText)return r&&!r.canReplace(i,i,n)?null:t.cut(0,e).append(n).append(t.cut(e));let l=BJ(o.content,e-a-1,n,o);return l&&t.replaceChild(i,o.copy(l))}function XBe(t,e,n){if(n.openStart>t.depth)throw new SS("Inserted content deeper than insertion position");if(t.depth-n.openStart!=e.depth-n.openEnd)throw new SS("Inconsistent open depths");return $J(t,e,n,0)}function $J(t,e,n,r){let i=t.index(r),a=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 Ob(t,e,n,r){let i=(e||t).node(n),a=0,o=e?e.index(n):i.childCount;t&&(a=t.index(n),t.depth>n?a++:t.textOffset&&(sf(t.nodeAfter,r),a++));for(let l=a;li&&VP(t,e,i+1),o=r.depth>i&&VP(n,r,i+1),l=[];return Ob(null,t,i,l),a&&o&&e.index(i)==n.index(i)?(HJ(a,o),sf(of(a,VJ(t,e,n,r,i+1)),l)):(a&&sf(of(a,MS(t,e,i+1)),l),Ob(e,n,i,l),o&&sf(of(o,MS(n,r,i+1)),l)),Ob(r,null,i,l),new _t(l)}function MS(t,e,n){let r=[];if(Ob(null,t,n,r),t.depth>n){let i=VP(t,e,n+1);sf(of(i,MS(t,e,n+1)),r)}return Ob(e,null,n,r),new _t(r)}function YBe(t,e){let n=e.depth-t.openStart,i=e.node(n).copy(t.content);for(let a=n-1;a>=0;a--)i=e.node(a).copy(_t.from(i));return{start:i.resolveNoCache(t.openStart+n),end:i.resolveNoCache(i.content.size-t.openEnd-n)}}class C0{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 a=0;a0;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 ES(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,a=n;for(let o=e;;){let{index:l,offset:c}=o.content.findIndex(a),u=a-c;if(r.push(o,l,i+c),!u||(o=o.child(l),o.isText))break;a=u-1,i+=c+1}return new C0(n,r,a)}static resolveCached(e,n){let r=X7.get(e);if(r)for(let a=0;ae&&this.nodesBetween(e,n,a=>(r.isInSet(a.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()+")"),GJ(this.marks,e)}contentMatchAt(e){let n=this.type.contentMatch.matchFragment(this.content,0,e);if(!n)throw new Error("Called contentMatchAt on a node with invalid content");return n}canReplace(e,n,r=_t.empty,i=0,a=r.childCount){let o=this.contentMatchAt(e).matchFragment(r,i,a),l=o&&o.matchFragment(this.content,n);if(!l||!l.validEnd)return!1;for(let c=i;cn.type.name)}`);this.content.forEach(n=>n.check())}toJSON(){let e={type:this.type.name};for(let n in this.attrs){e.attrs=this.attrs;break}return this.content.size&&(e.content=this.content.toJSON()),this.marks.length&&(e.marks=this.marks.map(n=>n.toJSON())),e}static fromJSON(e,n){if(!n)throw new RangeError("Invalid input for Node.fromJSON");let r;if(n.marks){if(!Array.isArray(n.marks))throw new RangeError("Invalid mark data for Node.fromJSON");r=n.marks.map(e.markFromJSON)}if(n.type=="text"){if(typeof n.text!="string")throw new RangeError("Invalid text node in JSON");return e.text(n.text,r)}let i=_t.fromJSON(e,n.content),a=e.nodeType(n.type).create(n.attrs,i,r);return a.type.checkAttrs(a.attrs),a}};Td.prototype.text=void 0;class NS extends Td{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):GJ(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 NS(this.type,this.attrs,this.text,e)}withText(e){return e==this.text?this:new NS(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 GJ(t,e){for(let n=t.length-1;n>=0;n--)e=t[n].type.name+"("+e+")";return e}class Df{constructor(e){this.validEnd=e,this.next=[],this.wrapCache=[]}static parse(e,n){let r=new e8e(e,n);if(r.next==null)return Df.empty;let i=WJ(r);r.next&&r.err("Unexpected trailing text");let a=o8e(s8e(i));return l8e(a,r),a}matchType(e){for(let n=0;nu.createAndFill()));for(let u=0;u=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 a=i+(r.validEnd?"*":" ")+" ";for(let o=0;o"+e.indexOf(r.next[o].next);return a}).join(` +`);q.length>0&&(C.extrusionColor=q),C.processGCode(Q);const re=C.layers?.length||0;y(re),v(re),C.render(),u(!1)}).catch(F=>{F.message!=="not_sliced"&&f(F.message),u(!1)});const P=()=>{if(N.parentElement&&a.current){const F=N.parentElement.getBoundingClientRect();N.width=F.width,N.height=F.height,a.current.resize()}};return window.addEventListener("resize",P),()=>{window.removeEventListener("resize",P),o.current&&cancelAnimationFrame(o.current),a.current&&(a.current.dispose(),a.current=null),l.current=!1}},[t,M]);const w=S.useCallback(N=>{if(!a.current)return;const k=Math.max(1,Math.min(N,x));v(k),o.current&&cancelAnimationFrame(o.current),o.current=requestAnimationFrame(()=>{a.current&&(a.current.endLayer=k,a.current.render())})},[x]),A=N=>{w(parseInt(N.target.value,10))};return s.jsxs("div",{className:`relative flex flex-col h-full ${r}`,children:[s.jsxs("div",{className:"flex-1 relative bg-bambu-dark rounded-lg overflow-hidden",children:[s.jsx("canvas",{ref:i,className:"w-full h-full"}),c&&s.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-bambu-dark/80",children:s.jsxs("div",{className:"text-center",children:[s.jsx(ft,{className:"w-8 h-8 animate-spin text-bambu-green mx-auto mb-2"}),s.jsx("p",{className:"text-bambu-gray text-sm",children:"Loading G-code..."})]})}),m&&s.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-bambu-dark/80",children:s.jsxs("div",{className:"text-center max-w-sm px-4",children:[s.jsx(Kce,{className:"w-12 h-12 text-bambu-gray mx-auto mb-3"}),s.jsx("p",{className:"text-white font-medium mb-2",children:"G-code not available"}),s.jsx("p",{className:"text-bambu-gray text-sm",children:"This file hasn't been sliced yet. G-code preview is only available after slicing in Bambu Studio or Orca Slicer."})]})}),d&&!m&&s.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-bambu-dark/80",children:s.jsx("div",{className:"text-center text-red-400",children:s.jsx("p",{className:"text-sm",children:d})})})]}),!c&&!d&&!m&&x>0&&s.jsx("div",{className:"mt-4 px-2",children:s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx(el,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}),s.jsx("button",{onClick:()=>w(b-1),disabled:b<=1,className:"p-1 rounded hover:bg-bambu-dark-tertiary disabled:opacity-30 disabled:cursor-not-allowed",children:s.jsx(mf,{className:"w-4 h-4"})}),s.jsx("input",{type:"range",min:1,max:x,value:b,onChange:A,className:"flex-1 h-2 bg-bambu-dark-tertiary rounded-lg appearance-none cursor-pointer accent-bambu-green"}),s.jsx("button",{onClick:()=>w(b+1),disabled:b>=x,className:"p-1 rounded hover:bg-bambu-dark-tertiary disabled:opacity-30 disabled:cursor-not-allowed",children:s.jsx($s,{className:"w-4 h-4"})}),s.jsxs("span",{className:"text-sm text-bambu-gray min-w-[80px] text-right",children:[b," / ",x]})]})})]})}function kJ({archiveId:t,title:e,onClose:n}){const[r,i]=S.useState(null),[a,o]=S.useState(null),[l,c]=S.useState(!0);S.useEffect(()=>{const d=f=>{f.key==="Escape"&&n()};return window.addEventListener("keydown",d),()=>window.removeEventListener("keydown",d)},[n]),S.useEffect(()=>{xe.getArchiveCapabilities(t).then(d=>{o(d),d.has_model?i("3d"):d.has_gcode&&i("gcode"),c(!1)}).catch(()=>{o({has_model:!0,has_gcode:!1,has_source:!1,build_volume:{x:256,y:256,z:256},filament_colors:[]}),i("3d"),c(!1)})},[t]);const u=()=>{const d=e||"model",f=`${window.location.origin}${xe.getArchiveForSlicer(t,d)}`;Rc(f)};return s.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-8",onClick:n,children:s.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary w-full max-w-4xl h-[80vh] flex flex-col",onClick:d=>d.stopPropagation(),children:[s.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[s.jsx("h2",{className:"text-lg font-semibold text-white truncate flex-1 mr-4",children:e}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs(Ce,{variant:"secondary",size:"sm",onClick:u,children:[s.jsx(Ir,{className:"w-4 h-4"}),"Open in Slicer"]}),s.jsx(Ce,{variant:"ghost",size:"sm",onClick:n,children:s.jsx(Ft,{className:"w-5 h-5"})})]})]}),a&&s.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary",children:[s.jsxs("button",{onClick:()=>a.has_model&&i("3d"),disabled:!a.has_model,className:`flex items-center gap-2 px-6 py-3 text-sm font-medium transition-colors ${r==="3d"?"text-bambu-green border-b-2 border-bambu-green":a.has_model?"text-bambu-gray hover:text-white":"text-bambu-gray/30 cursor-not-allowed"}`,children:[s.jsx(js,{className:"w-4 h-4"}),"3D Model",!a.has_model&&s.jsx("span",{className:"text-xs",children:"(not available)"})]}),s.jsxs("button",{onClick:()=>a.has_gcode&&i("gcode"),disabled:!a.has_gcode,className:`flex items-center gap-2 px-6 py-3 text-sm font-medium transition-colors ${r==="gcode"?"text-bambu-green border-b-2 border-bambu-green":a.has_gcode?"text-bambu-gray hover:text-white":"text-bambu-gray/30 cursor-not-allowed"}`,children:[s.jsx(wce,{className:"w-4 h-4"}),"G-code Preview",!a.has_gcode&&s.jsx("span",{className:"text-xs",children:"(not sliced)"})]})]}),s.jsx("div",{className:"flex-1 overflow-hidden p-4",children:l?s.jsx("div",{className:"w-full h-full flex items-center justify-center",children:s.jsx(ft,{className:"w-8 h-8 animate-spin text-bambu-green"})}):r==="3d"&&a?s.jsx(vOe,{url:a.has_source?xe.getSource3mfDownloadUrl(t):xe.getArchiveDownload(t),buildVolume:a.build_volume,filamentColors:a.filament_colors,className:"w-full h-full"}):r==="gcode"&&a?s.jsx(SBe,{gcodeUrl:xe.getArchiveGcode(t),filamentColors:a.filament_colors,className:"w-full h-full"}):s.jsx("div",{className:"w-full h-full flex items-center justify-center text-bambu-gray",children:"No preview available for this file"})})]})})}const G7={"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 MBe(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),a=Math.max(n,r,i)/255,o=Math.min(n,r,i)/255,l=(a+o)/2;let c=0,u=0;if(a!==o){const d=a-o;u=l>.5?d/(2-a-o):d/(a+o);const f=n/255,m=r/255,g=i/255;a===f?c=((m-g)/d+(m.85?"White":u<.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":c<345?"Pink":"Unknown"}function mg(t){const e=t.replace("#","").toLowerCase().substring(0,6);return G7[e]?G7[e]:MBe(t)}function _S(t){return t?`#${t.replace("#","").substring(0,6)}`:"#808080"}function Xi(t){return t?t.replace("#","").toLowerCase().substring(0,6):""}function Hd(t,e,n=40){const r=Xi(t),i=Xi(e);if(!r||!i||r.length<6||i.length<6)return!1;const a=parseInt(r.substring(0,2),16),o=parseInt(r.substring(2,4),16),l=parseInt(r.substring(4,6),16),c=parseInt(i.substring(0,2),16),u=parseInt(i.substring(2,4),16),d=parseInt(i.substring(4,6),16);return Math.abs(a-c)<=n&&Math.abs(o-u)<=n&&Math.abs(l-d)<=n}function jJ(t,e,n,r){const i=String.fromCharCode(65+(t>=128?t-128:t));return n?`HT-${i}`:`AMS-${i} Slot ${e+1}`}function PJ(t,e,n){return t*4+e}function EBe(t){if(!t)return"";const e=Math.floor(t/3600),n=Math.floor(t%3600/60);return e>0?`${e}h ${n}m`:`${n}m`}function NBe(){const t=new Date;return t.setMinutes(t.getMinutes()+1),t.toISOString().slice(0,16)}function W7(t){if(!t)return!1;const e=Date.now()+4320*60*60*1e3;return new Date(t).getTime()>e}function NO(t){const e=[];if(t?.ams?.forEach(n=>{const r=n.tray.length===1;n.tray.forEach(i=>{if(i.tray_type){const a=_S(i.tray_color);e.push({type:i.tray_type,color:a,colorName:mg(a),amsId:n.id,trayId:i.id,isHt:r,isExternal:!1,label:jJ(n.id,i.id,r),globalTrayId:PJ(n.id,i.id)})}})}),t?.vt_tray?.tray_type){const n=_S(t.vt_tray.tray_color);e.push({type:t.vt_tray.tray_type,color:n,colorName:mg(n),amsId:-1,trayId:0,isHt:!1,isExternal:!0,label:"External",globalTrayId:254})}return e}function q7(t,e){if(!t?.filaments||t.filaments.length===0)return;const n=NO(e);if(n.length===0)return;const r=new Set,i=t.filaments.map(l=>{const c=n.find(m=>!r.has(m.globalTrayId)&&m.type?.toUpperCase()===l.type?.toUpperCase()&&Xi(m.color)===Xi(l.color)),u=!c&&n.find(m=>!r.has(m.globalTrayId)&&m.type?.toUpperCase()===l.type?.toUpperCase()&&Hd(m.color,l.color)),d=!c&&!u&&n.find(m=>!r.has(m.globalTrayId)&&m.type?.toUpperCase()===l.type?.toUpperCase()),f=c||u||d||void 0;return f&&r.add(f.globalTrayId),{slot_id:l.slot_id,globalTrayId:f?.globalTrayId??-1}}),a=Math.max(...i.map(l=>l.slot_id||0));if(a<=0)return;const o=new Array(a).fill(-1);return i.forEach(l=>{l.slot_id&&l.slot_id>0&&(o[l.slot_id-1]=l.globalTrayId)}),o}function ABe(t){return S.useMemo(()=>{const e=[];if(t?.ams?.forEach(n=>{const r=n.tray.length===1;n.tray.forEach(i=>{if(i.tray_type){const a=_S(i.tray_color);e.push({type:i.tray_type,color:a,colorName:mg(a),amsId:n.id,trayId:i.id,isHt:r,isExternal:!1,label:jJ(n.id,i.id,r),globalTrayId:PJ(n.id,i.id)})}})}),t?.vt_tray?.tray_type){const n=_S(t.vt_tray.tray_color);e.push({type:t.vt_tray.tray_type,color:n,colorName:mg(n),amsId:-1,trayId:0,isHt:!1,isExternal:!0,label:"External",globalTrayId:254})}return e},[t])}function RJ(t,e,n){const r=ABe(e),i=S.useMemo(()=>{if(!t?.filaments||t.filaments.length===0)return[];const c=new Set(Object.values(n));return t.filaments.map(u=>{const d=u.slot_id||0;if(d>0&&n[d]!==void 0){const w=n[d],A=r.find(N=>N.globalTrayId===w);if(A){const N=A.type?.toUpperCase()===u.type?.toUpperCase(),k=Xi(A.color)===Xi(u.color)||Hd(A.color,u.color);let T;return N&&k?T="match":N?T="type_only":T="mismatch",{...u,loaded:A,hasFilament:!0,typeMatch:N,colorMatch:k,status:T,isManual:!0}}}const f=r.find(w=>!c.has(w.globalTrayId)&&w.type?.toUpperCase()===u.type?.toUpperCase()&&Xi(w.color)===Xi(u.color)),m=!f&&r.find(w=>!c.has(w.globalTrayId)&&w.type?.toUpperCase()===u.type?.toUpperCase()&&Hd(w.color,u.color)),g=!f&&!m&&r.find(w=>!c.has(w.globalTrayId)&&w.type?.toUpperCase()===u.type?.toUpperCase()),b=f||m||g||void 0;b&&c.add(b.globalTrayId);const v=!!b,x=v,y=!!f||!!m;let M;return f||m?M="match":g?M="type_only":M="mismatch",{...u,loaded:b,hasFilament:v,typeMatch:x,colorMatch:y,status:M,isManual:!1}})},[t,r,n]),a=S.useMemo(()=>{if(i.length===0)return;const c=Math.max(...i.map(d=>d.slot_id||0));if(c<=0)return;const u=new Array(c).fill(-1);return i.forEach(d=>{d.slot_id&&d.slot_id>0&&(u[d.slot_id-1]=d.loaded?.globalTrayId??-1)}),u},[i]),o=i.some(c=>c.status==="mismatch"),l=i.some(c=>c.status==="type_only");return{loadedFilaments:r,filamentComparison:i,amsMapping:a,hasTypeMismatch:o,hasColorMismatch:l}}function TBe(t,e,n){if(!t||t.length===0)return{exactMatches:0,typeOnlyMatches:0,missingTypes:0,totalSlots:0,status:"full"};let r=0,i=0,a=0;const o=new Set(Object.values(n));for(const u of t){const d=u.slot_id||0;if(d>0&&n[d]!==void 0){const v=n[d],x=e.find(y=>y.globalTrayId===v);if(x){const y=x.type?.toUpperCase()===u.type?.toUpperCase(),M=Xi(x.color)===Xi(u.color)||Hd(x.color,u.color);y&&M?r++:y?i++:a++;continue}}const f=e.find(v=>!o.has(v.globalTrayId)&&v.type?.toUpperCase()===u.type?.toUpperCase()&&Xi(v.color)===Xi(u.color)),m=f?void 0:e.find(v=>!o.has(v.globalTrayId)&&v.type?.toUpperCase()===u.type?.toUpperCase()&&Hd(v.color,u.color)),g=f||m?void 0:e.find(v=>!o.has(v.globalTrayId)&&v.type?.toUpperCase()===u.type?.toUpperCase()),b=f??m??g;b&&o.add(b.globalTrayId),f||m?r++:g?i++:a++}const l=t.length;let c="full";return a>0?c="missing":i>0&&(c="partial"),{exactMatches:r,typeOnlyMatches:i,missingTypes:a,totalSlots:l,status:c}}function CBe(t,e,n){if(!t?.filaments||t.filaments.length===0)return;const r=NO(e);if(r.length===0)return;const i=new Set(Object.values(n)),a=[];for(const c of t.filaments){const u=c.slot_id||0;if(u>0&&n[u]!==void 0){a.push({slot_id:u,globalTrayId:n[u]});continue}const d=r.find(b=>!i.has(b.globalTrayId)&&b.type?.toUpperCase()===c.type?.toUpperCase()&&Xi(b.color)===Xi(c.color)),f=d?void 0:r.find(b=>!i.has(b.globalTrayId)&&b.type?.toUpperCase()===c.type?.toUpperCase()&&Hd(b.color,c.color)),m=d||f?void 0:r.find(b=>!i.has(b.globalTrayId)&&b.type?.toUpperCase()===c.type?.toUpperCase()),g=d??f??m;g&&i.add(g.globalTrayId),a.push({slot_id:u,globalTrayId:g?.globalTrayId??-1})}const o=Math.max(...a.map(c=>c.slot_id||0));if(o<=0)return;const l=new Array(o).fill(-1);return a.forEach(c=>{c.slot_id&&c.slot_id>0&&(l[c.slot_id-1]=c.globalTrayId)}),l}const K7={useDefault:!0,manualMappings:{},autoConfigured:!1};function kBe(t,e,n,r,i,a){const o=vle({queries:t.map(b=>({queryKey:["printer-status",b],queryFn:()=>xe.getPrinterStatus(b),enabled:t.length>0,staleTime:5e3}))}),l=S.useMemo(()=>t.map((b,v)=>{const x=o[v],y=x?.data,w=e?.find(P=>P.id===b)?.name||`Printer ${b}`,A=NO(y),N=i[b]||K7,k=q7(n,y),T=N.useDefault?r:N.manualMappings,R=CBe(n,y,T),C=TBe(n?.filaments,A,T);return{printerId:b,printerName:w,status:y,isLoading:x?.isLoading??!1,loadedFilaments:A,autoMapping:k,finalMapping:R,matchStatus:C.status,exactMatches:C.exactMatches,typeOnlyMatches:C.typeOnlyMatches,missingTypes:C.missingTypes,totalSlots:C.totalSlots,config:N}}),[t,o,e,n,i,r]),c=o.some(b=>b.isLoading),u=(b,v)=>{a(x=>({...x,[b]:{...x[b]||K7,...v}}))},d=b=>{const v=l.find(M=>M.printerId===b);if(!v||!v.status||!n?.filaments)return;const x=q7(n,v.status);if(!x)return;const y={};x.forEach((M,w)=>{M!==-1&&(y[w+1]=M)}),u(b,{useDefault:!1,manualMappings:y,autoConfigured:!0})},f=()=>{for(const b of t)d(b)},m=b=>l.find(x=>x.printerId===b)?.finalMapping,g=l.every(b=>b.matchStatus!=="missing");return{printerResults:l,isLoading:c,perPrinterConfigs:i,updatePrinterConfig:u,autoConfigureAll:f,autoConfigurePrinter:d,getFinalMapping:m,allPrintersReady:g}}function jBe({printerResult:t,filamentReqs:e,onUpdateConfig:n}){const r=Yt(),[i,a]=S.useState(!1),o=(u,d)=>{if(u<=0)return;const f={...t.config.manualMappings};d===""?delete f[u]:f[u]=parseInt(d,10),n({useDefault:!1,manualMappings:f,autoConfigured:!1})},l=async()=>{a(!0);try{await xe.refreshPrinterStatus(t.printerId),await new Promise(u=>setTimeout(u,500)),await r.refetchQueries({queryKey:["printer-status",t.printerId]})}finally{a(!1)}},c=e.map(u=>{const d=u.slot_id||0,f=t.config.manualMappings[d];let m,g=!1;if(f!==void 0)m=t.loadedFilaments.find(v=>v.globalTrayId===f),g=!0;else{const v=new Set(Object.values(t.config.manualMappings)),x=t.loadedFilaments.find(w=>!v.has(w.globalTrayId)&&w.type?.toUpperCase()===u.type?.toUpperCase()&&Xi(w.color)===Xi(u.color)),y=x?void 0:t.loadedFilaments.find(w=>!v.has(w.globalTrayId)&&w.type?.toUpperCase()===u.type?.toUpperCase()&&Hd(w.color,u.color)),M=x||y?void 0:t.loadedFilaments.find(w=>!v.has(w.globalTrayId)&&w.type?.toUpperCase()===u.type?.toUpperCase());m=x??y??M}let b="mismatch";if(m){const v=m.type?.toUpperCase()===u.type?.toUpperCase(),x=Xi(m.color)===Xi(u.color)||Hd(m.color,u.color);v&&x?b="match":v&&(b="type_only")}return{req:u,loaded:m,status:b,isManual:g}});return s.jsxs("div",{className:"mt-2 bg-bambu-dark rounded-lg p-3 space-y-2",children:[s.jsxs("div",{className:"flex items-center justify-between mb-2",children:[s.jsx("span",{className:"text-xs text-bambu-gray",children:"Custom slot mapping"}),s.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:[s.jsx(vr,{className:`w-3 h-3 ${i?"animate-spin":""}`}),s.jsx("span",{children:"Re-read"})]})]}),c.map(({req:u,loaded:d,status:f,isManual:m},g)=>s.jsxs("div",{className:"grid items-center gap-2 text-xs",style:{gridTemplateColumns:"16px minmax(70px, 1fr) auto 2fr 16px"},children:[s.jsx("span",{title:`Required: ${u.type} - ${mg(u.color)}`,children:s.jsx(kj,{className:"w-3 h-3",fill:u.color,stroke:u.color})}),s.jsxs("span",{className:"text-white truncate",children:[u.type," ",s.jsxs("span",{className:"text-bambu-gray",children:["(",u.used_grams,"g)"]})]}),s.jsx("span",{className:"text-bambu-gray",children:"→"}),s.jsxs("select",{value:d?.globalTrayId??"",onChange:b=>o(u.slot_id||0,b.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 ${f==="match"?"border-bambu-green/50 text-bambu-green":f==="type_only"?"border-yellow-400/50 text-yellow-400":"border-orange-400/50 text-orange-400"} ${m?"ring-1 ring-blue-400/50":""}`,title:m?"Manually selected":"Auto-matched",children:[s.jsx("option",{value:"",className:"bg-bambu-dark text-bambu-gray",children:"-- Select slot --"}),t.loadedFilaments.map(b=>s.jsxs("option",{value:b.globalTrayId,className:"bg-bambu-dark text-white",children:[b.label,": ",b.type," (",b.colorName,")"]},b.globalTrayId))]}),f==="match"?s.jsx(fs,{className:"w-3 h-3 text-bambu-green"}):f==="type_only"?s.jsx("span",{title:"Same type, different color",children:s.jsx(Nn,{className:"w-3 h-3 text-yellow-400"})}):s.jsx("span",{title:"Filament type not loaded",children:s.jsx(Nn,{className:"w-3 h-3 text-orange-400"})})]},g))]})}function PBe({printers:t,selectedPrinterIds:e,onMultiSelect:n,isLoading:r=!1,allowMultiple:i=!1,showInactive:a=!1,printerMappingResults:o,filamentReqs:l,onAutoConfigurePrinter:c,onUpdatePrinterConfig:u}){const d=a?t:t.filter(w=>w.is_active),f=i&&e.length>1&&o&&l?.filaments&&l.filaments.length>0&&c&&u;if(r)return s.jsx("div",{className:"flex justify-center py-8",children:s.jsx(ft,{className:"w-6 h-6 text-bambu-green animate-spin"})});if(d.length===0)return s.jsxs("div",{className:"flex items-center gap-2 text-red-400 text-sm mb-4",children:[s.jsx(Ji,{className:"w-4 h-4"}),"No ",a?"":"active ","printers available"]});const m=w=>{i?e.includes(w)?n(e.filter(A=>A!==w)):n([...e,w]):n([w])},g=()=>{n(d.map(w=>w.id))},b=()=>{n([])},v=(w,A,N)=>{N.stopPropagation(),!(!c||!u)&&(A?c(w):u(w,{useDefault:!0,manualMappings:{},autoConfigured:!1}))},x=w=>e.includes(w),y=e.length,M=w=>o?.find(A=>A.printerId===w);return s.jsxs("div",{className:"space-y-2 mb-6",children:[i&&d.length>1&&s.jsxs("div",{className:"flex items-center justify-between text-xs text-bambu-gray mb-2",children:[s.jsx("span",{children:y===0?"Select printers":`${y} printer${y!==1?"s":""} selected`}),s.jsxs("div",{className:"flex gap-2",children:[y0&&s.jsx("button",{type:"button",onClick:b,className:"text-bambu-gray hover:text-white transition-colors",children:"Clear"})]})]}),d.map(w=>{const A=x(w.id),N=M(w.id),k=N&&!N.config.useDefault;return s.jsxs("div",{children:[s.jsxs("button",{type:"button",onClick:()=>m(w.id),className:`w-full flex items-center gap-3 p-3 rounded-lg border transition-colors ${A?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark hover:border-bambu-gray"} ${w.is_active?"":"opacity-60"}`,children:[s.jsx("div",{className:`p-2 rounded-lg ${A?"bg-bambu-green/20":"bg-bambu-dark-tertiary"}`,children:s.jsx(Rr,{className:`w-5 h-5 ${A?"text-bambu-green":"text-bambu-gray"}`})}),s.jsxs("div",{className:"text-left flex-1",children:[s.jsxs("p",{className:"text-white font-medium",children:[w.name,!w.is_active&&s.jsx("span",{className:"text-bambu-gray text-xs ml-2",children:"(inactive)"})]}),s.jsxs("p",{className:"text-xs text-bambu-gray",children:[w.model||"Unknown model"," • ",w.ip_address]})]}),i&&s.jsx("div",{className:`w-5 h-5 rounded border-2 flex items-center justify-center transition-colors ${A?"bg-bambu-green border-bambu-green":"border-bambu-gray/50"}`,children:A&&s.jsx(fs,{className:"w-3 h-3 text-white"})})]}),A&&f&&N&&s.jsxs("div",{className:"ml-4 mt-2 mb-3",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",onClick:T=>T.stopPropagation(),children:[s.jsx("input",{type:"checkbox",checked:k,onChange:T=>v(w.id,T.target.checked,T),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"}),s.jsx("span",{className:"text-xs text-bambu-gray",children:"Custom mapping"})]}),s.jsxs("span",{className:`text-xs ml-2 ${N.matchStatus==="full"?"text-bambu-green":N.matchStatus==="partial"?"text-yellow-400":"text-orange-400"}`,children:["(",N.exactMatches,"/",N.totalSlots," matched)"]}),N.isLoading&&s.jsx(vr,{className:"w-3 h-3 text-bambu-gray animate-spin"}),k&&s.jsxs("button",{type:"button",onClick:T=>{T.stopPropagation(),c(w.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:[s.jsx(Che,{className:"w-3 h-3"}),"Auto"]})]}),k&&s.jsx(jBe,{printerResult:N,filamentReqs:l.filaments,onUpdateConfig:T=>u(w.id,T)})]})]},w.id)}),y===0&&s.jsxs("p",{className:"text-xs text-orange-400 mt-1 flex items-center gap-1",children:[s.jsx(Ji,{className:"w-3 h-3"}),"Select at least one printer"]})]})}function RBe({plates:t,isMultiPlate:e,selectedPlate:n,onSelect:r}){return!e||t.length<=1?null:s.jsxs("div",{className:"mb-4",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[s.jsx(el,{className:"w-4 h-4 text-bambu-gray"}),s.jsx("span",{className:"text-sm text-bambu-gray",children:"Select Plate to Print"}),!n&&s.jsxs("span",{className:"text-xs text-orange-400 flex items-center gap-1",children:[s.jsx(Nn,{className:"w-3 h-3"}),"Selection required"]})]}),s.jsx("div",{className:"grid grid-cols-2 gap-2",children:t.map(i=>s.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?s.jsx("img",{src:i.thumbnail_url,alt:`Plate ${i.index}`,className:"w-10 h-10 rounded object-cover bg-bambu-dark-tertiary"}):s.jsx("div",{className:"w-10 h-10 rounded bg-bambu-dark-tertiary flex items-center justify-center",children:s.jsx(el,{className:"w-5 h-5 text-bambu-gray"})}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("p",{className:"text-sm text-white font-medium truncate",children:i.name||`Plate ${i.index}`}),s.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?` • ${EBe(i.print_time_seconds)}`:""]})]}),n===i.index&&s.jsx(fs,{className:"w-4 h-4 text-bambu-green flex-shrink-0"})]},i.index))})]})}function DBe({printerId:t,filamentReqs:e,manualMappings:n,onManualMappingChange:r,defaultExpanded:i=!1}){const a=Yt(),[o,l]=S.useState(!1),[c,u]=S.useState(i),{data:d}=lt({queryKey:["printer-status",t],queryFn:()=>xe.getPrinterStatus(t),enabled:!!t}),{loadedFilaments:f,filamentComparison:m,hasTypeMismatch:g,hasColorMismatch:b}=RJ(e,d,n);if(!(e?.filaments&&e.filaments.length>0)||!d)return null;const x=g?"#f97316":b?"#facc15":"#00ae42",y=(w,A)=>{if(w>0)if(A===""){const N={...n};delete N[w],r(N)}else r({...n,[w]:parseInt(A,10)})},M=async()=>{l(!0);try{await xe.refreshPrinterStatus(t),await new Promise(w=>setTimeout(w,500)),await a.refetchQueries({queryKey:["printer-status",t]})}finally{l(!1)}};return s.jsxs("div",{className:"mb-4",children:[s.jsxs("button",{type:"button",onClick:()=>u(!c),className:"flex items-center gap-2 text-sm text-bambu-gray hover:text-white transition-colors w-full",children:[s.jsx(kj,{className:"w-4 h-4",fill:x,stroke:"none"}),s.jsx("span",{children:"Filament Mapping"}),g?s.jsx("span",{className:"text-xs text-orange-400",children:"(Type not found)"}):b?s.jsx("span",{className:"text-xs text-yellow-400",children:"(Color mismatch)"}):s.jsx("span",{className:"text-xs text-bambu-green",children:"(Ready)"}),c?s.jsx(Qc,{className:"w-4 h-4 ml-auto"}):s.jsx(Zi,{className:"w-4 h-4 ml-auto"})]}),c&&s.jsxs("div",{className:"mt-2 bg-bambu-dark rounded-lg p-3 space-y-2",children:[s.jsxs("div",{className:"flex items-center justify-between mb-2",children:[s.jsx("span",{className:"text-xs text-bambu-gray",children:"Click to change slot assignment"}),s.jsxs("button",{type:"button",onClick:M,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:o,children:[s.jsx(vr,{className:`w-3 h-3 ${o?"animate-spin":""}`}),s.jsx("span",{children:"Re-read"})]})]}),m.map((w,A)=>s.jsxs("div",{className:"grid items-center gap-2 text-xs",style:{gridTemplateColumns:"16px minmax(70px, 1fr) auto 2fr 16px"},children:[s.jsx("span",{title:`Required: ${w.type} - ${mg(w.color)}`,children:s.jsx(kj,{className:"w-3 h-3",fill:w.color,stroke:w.color})}),s.jsxs("span",{className:"text-white truncate",children:[w.type," ",s.jsxs("span",{className:"text-bambu-gray",children:["(",w.used_grams,"g)"]})]}),s.jsx("span",{className:"text-bambu-gray",children:"→"}),s.jsxs("select",{value:w.loaded?.globalTrayId??"",onChange:N=>y(w.slot_id||0,N.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 ${w.status==="match"?"border-bambu-green/50 text-bambu-green":w.status==="type_only"?"border-yellow-400/50 text-yellow-400":"border-orange-400/50 text-orange-400"} ${w.isManual?"ring-1 ring-blue-400/50":""}`,title:w.isManual?"Manually selected":"Auto-matched",children:[s.jsx("option",{value:"",className:"bg-bambu-dark text-bambu-gray",children:"-- Select slot --"}),f.map(N=>s.jsxs("option",{value:N.globalTrayId,className:"bg-bambu-dark text-white",children:[N.label,": ",N.type," (",N.colorName,")"]},N.globalTrayId))]}),w.status==="match"?s.jsx(fs,{className:"w-3 h-3 text-bambu-green"}):w.status==="type_only"?s.jsx("span",{title:"Same type, different color",children:s.jsx(Nn,{className:"w-3 h-3 text-yellow-400"})}):s.jsx("span",{title:"Filament type not loaded",children:s.jsx(Nn,{className:"w-3 h-3 text-orange-400"})})]},A)),g&&s.jsx("p",{className:"text-xs text-orange-400 mt-2",children:"Required filament type not found in printer."})]})]})}const OBe=[{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 LBe({options:t,onChange:e,defaultExpanded:n=!1}){const[r,i]=S.useState(n),a=o=>{e({...t,[o]:!t[o]})};return s.jsxs("div",{className:"mb-4",children:[s.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:[s.jsx(j2,{className:"w-4 h-4"}),s.jsx("span",{children:"Print Options"}),r?s.jsx(Qc,{className:"w-4 h-4 ml-auto"}):s.jsx(Zi,{className:"w-4 h-4 ml-auto"})]}),r&&s.jsx("div",{className:"mt-2 bg-bambu-dark rounded-lg p-3 space-y-2",children:OBe.map(({key:o,label:l,desc:c})=>s.jsxs("label",{className:"flex items-center justify-between cursor-pointer group",children:[s.jsxs("div",{children:[s.jsx("span",{className:"text-sm text-white",children:l}),s.jsx("p",{className:"text-xs text-bambu-gray",children:c})]}),s.jsx("div",{className:`relative w-10 h-5 rounded-full transition-colors ${t[o]?"bg-bambu-green":"bg-bambu-dark-tertiary"}`,onClick:()=>a(o),children:s.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 IBe({options:t,onChange:e}){const n=r=>{e({...t,scheduleType:r})};return s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-2",children:"When to print"}),s.jsxs("div",{className:"flex gap-2",children:[s.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:()=>n("asap"),children:[s.jsx(Gn,{className:"w-4 h-4"}),"ASAP"]}),s.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:()=>n("scheduled"),children:[s.jsx(Qr,{className:"w-4 h-4"}),"Scheduled"]}),s.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:()=>n("manual"),children:[s.jsx(RW,{className:"w-4 h-4"}),"Queue Only"]})]})]}),t.scheduleType==="scheduled"&&s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Date & Time"}),s.jsx("input",{type:"datetime-local",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:t.scheduledTime,onChange:r=>e({...t,scheduledTime:r.target.value}),min:NBe(),required:!0})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"checkbox",id:"requirePrevious",checked:t.requirePreviousSuccess,onChange:r=>e({...t,requirePreviousSuccess:r.target.checked}),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),s.jsx("label",{htmlFor:"requirePrevious",className:"text-sm text-bambu-gray",children:"Only start if previous print succeeded"})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"checkbox",id:"autoOffAfter",checked:t.autoOffAfter,onChange:r=>e({...t,autoOffAfter:r.target.checked}),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),s.jsxs("label",{htmlFor:"autoOffAfter",className:"text-sm text-bambu-gray flex items-center gap-1",children:[s.jsx(cu,{className:"w-3.5 h-3.5"}),"Power off printer when done"]})]}),s.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 cp={bed_levelling:!0,flow_cali:!1,vibration_cali:!0,layer_inspect:!1,timelapse:!1},FBe={scheduleType:"asap",scheduledTime:"",requirePreviousSuccess:!1,autoOffAfter:!1};function Rf({mode:t,archiveId:e,libraryFileId:n,archiveName:r,queueItem:i,onClose:a,onSuccess:o}){const l=Yt(),{showToast:c}=tr(),u=!!n&&!e,[d,f]=S.useState(()=>t==="edit-queue-item"&&i?.printer_id?[i.printer_id]:[]),[m,g]=S.useState(()=>t==="edit-queue-item"&&i?i.plate_id:null),[b,v]=S.useState(()=>t==="edit-queue-item"&&i?{bed_levelling:i.bed_levelling??cp.bed_levelling,flow_cali:i.flow_cali??cp.flow_cali,vibration_cali:i.vibration_cali??cp.vibration_cali,layer_inspect:i.layer_inspect??cp.layer_inspect,timelapse:i.timelapse??cp.timelapse}:cp),[x,y]=S.useState(()=>{if(t==="edit-queue-item"&&i){let ve="asap";i.manual_start?ve="manual":i.scheduled_time&&!W7(i.scheduled_time)&&(ve="scheduled");let he="";return i.scheduled_time&&!W7(i.scheduled_time)&&(he=new Date(i.scheduled_time).toISOString().slice(0,16)),{scheduleType:ve,scheduledTime:he,requirePreviousSuccess:i.require_previous_success,autoOffAfter:i.auto_off_after}}return FBe}),[M,w]=S.useState(()=>{if(t==="edit-queue-item"&&i?.ams_mapping&&Array.isArray(i.ams_mapping)){const ve={};return i.ams_mapping.forEach((he,B)=>{he!==-1&&(ve[B+1]=he)}),ve}return{}}),[A,N]=S.useState({}),[k]=S.useState(()=>t==="edit-queue-item"&&i?.printer_id?[i.printer_id]:[]),[T]=S.useState(()=>t==="edit-queue-item"&&i?i.plate_id:null),[R,C]=S.useState(!1),[P,F]=S.useState({current:0,total:0}),L=d.length,K=d.length>0?d[0]:null,{data:D}=lt({queryKey:["settings"],queryFn:xe.getSettings}),{data:W,isLoading:Y}=lt({queryKey:["printers"],queryFn:xe.getPrinters}),{data:q,isError:Q}=lt({queryKey:["archive-plates",e],queryFn:()=>xe.getArchivePlates(e),enabled:!!e&&!u,retry:!1}),{data:re}=lt({queryKey:["library-file-plates",n],queryFn:()=>xe.getLibraryFilePlates(n),enabled:u&&!!n}),ne=u?re:q,{data:U,isError:G}=lt({queryKey:["archive-filaments",e,m],queryFn:()=>xe.getArchiveFilamentRequirements(e,m??void 0),enabled:!!e&&!u&&(m!==null||!ne?.is_multi_plate),retry:!1}),{data:te}=lt({queryKey:["library-file-filaments",n,m],queryFn:()=>xe.getLibraryFileFilamentRequirements(n,m??void 0),enabled:u&&!!n&&(m!==null||!ne?.is_multi_plate)}),ie=!u&&(Q||G),oe=u?te:U,{data:ce}=lt({queryKey:["printer-status",K],queryFn:()=>xe.getPrinterStatus(K),enabled:!!K}),{amsMapping:me}=RJ(oe,ce,M),Ae=kBe(d,W,oe,M,A,N);S.useEffect(()=>{ne?.plates?.length===1&&!m&&g(ne.plates[0].index)},[ne,m]),S.useEffect(()=>{if(t==="edit-queue-item")return;const ve=W?.filter(he=>he.is_active)||[];ve.length===1&&d.length===0&&f([ve[0].id])},[t,W,d.length]),S.useEffect(()=>{t==="edit-queue-item"?(JSON.stringify(d.sort())!==JSON.stringify(k.sort())||m!==T)&&(w({}),N({})):(w({}),N({}))},[t,d,m,k,T]),S.useEffect(()=>{if(!D?.per_printer_mapping_expanded||d.length<=1)return;const ve=d.filter(he=>!A[he]||A[he].useDefault);ve.length>0&&ve.forEach(he=>{Ae.autoConfigurePrinter(he)})},[D?.per_printer_mapping_expanded,d,A,Ae]),S.useEffect(()=>{const ve=he=>{he.key==="Escape"&&!R&&a()};return window.addEventListener("keydown",ve),()=>window.removeEventListener("keydown",ve)},[a,R]);const ge=ne?.is_multi_plate??!1,Ne=ne?.plates??[],Se=ht({mutationFn:ve=>xe.addToQueue(ve)}),J=ht({mutationFn:ve=>xe.updateQueueItem(i.id,ve),onSuccess:()=>{l.invalidateQueries({queryKey:["queue"]}),c("Queue item updated"),o?.(),a()},onError:ve=>{c(ve.message||"Failed to update queue item","error")}}),Ve=async ve=>{if(ve?.preventDefault(),d.length===0){c("Please select at least one printer","error");return}C(!0),F({current:0,total:d.length});const he={success:0,failed:0,errors:[]},B=le=>{if(d.length>1){const _e=A[le];if(_e&&!_e.useDefault)return Ae.getFinalMapping(le)}return me},I=le=>({printer_id:le,archive_id:u?void 0:e,library_file_id:u?n:void 0,require_previous_success:x.requirePreviousSuccess,auto_off_after:x.autoOffAfter,manual_start:x.scheduleType==="manual",ams_mapping:B(le),plate_id:m,scheduled_time:x.scheduleType==="scheduled"&&x.scheduledTime?new Date(x.scheduledTime).toISOString():void 0,...b});for(let le=0;leKe.id===_e)?.name||`Printer ${_e}`;he.errors.push(`${we}: ${Ee.message}`)}}if(C(!1),he.failed===0){const le=t==="reprint"?"sent to":t==="edit-queue-item"?"updated/queued for":"queued for";he.success===1?c(t==="edit-queue-item"?"Queue item updated":`Print ${le} printer`):c(`Print ${le} ${he.success} printers`),l.invalidateQueries({queryKey:["queue"]}),o?.(),a()}else he.success===0?c(`Failed: ${he.errors[0]}`,"error"):(c(`${he.success} succeeded, ${he.failed} failed`,"error"),l.invalidateQueries({queryKey:["queue"]}))},H=R||J.isPending,$=S.useMemo(()=>!(H||d.length===0||!u&&ge&&!m),[d.length,ge,m,H,u]),z=(()=>{const ve=d.length;return t==="reprint"?{title:u?"Print":"Re-print",icon:Rr,submitText:ve>1?`Print to ${ve} Printers`:"Print",submitIcon:Rr,loadingText:P.total>1?`Sending ${P.current}/${P.total}...`:"Sending..."}:t==="add-to-queue"?{title:"Schedule Print",icon:Qr,submitText:ve>1?`Queue to ${ve} Printers`:"Add to Queue",submitIcon:Qr,loadingText:P.total>1?`Adding ${P.current}/${P.total}...`:"Adding..."}:{title:"Edit Queue Item",icon:No,submitText:"Save",submitIcon:No,loadingText:P.total>1?`Saving ${P.current}/${P.total}...`:"Saving..."}})(),V=z.icon,Z=z.submitIcon,de=K&&(u||(ge?m!==null:!0));return s.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:R?void 0:a,children:s.jsx(wt,{className:"w-full max-w-lg max-h-[90vh] overflow-y-auto",onClick:ve=>ve.stopPropagation(),children:s.jsxs(Mt,{className:t==="reprint"?"":"p-0",children:[s.jsxs("div",{className:`flex items-center justify-between ${t==="reprint"?"mb-4":"p-4 border-b border-bambu-dark-tertiary"}`,children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(V,{className:"w-5 h-5 text-bambu-green"}),s.jsx("h2",{className:"text-lg font-semibold text-white",children:z.title})]}),s.jsx(Ce,{variant:"ghost",size:"sm",onClick:a,disabled:R,children:s.jsx(Ft,{className:"w-5 h-5"})})]}),s.jsxs("form",{onSubmit:Ve,className:t==="reprint"?"":"p-4 space-y-4",children:[s.jsx("p",{className:`text-sm text-bambu-gray ${t==="reprint"?"mb-4":""}`,children:t==="reprint"?s.jsxs(s.Fragment,{children:["Send ",s.jsx("span",{className:"text-white",children:r})," to printer(s)"]}):s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"block text-bambu-gray mb-1",children:"Print Job"}),s.jsx("span",{className:"text-white font-medium truncate block",children:r})]})}),s.jsx(RBe,{plates:Ne,isMultiPlate:ge,selectedPlate:m,onSelect:g}),s.jsx(PBe,{printers:W||[],selectedPrinterIds:d,onMultiSelect:f,isLoading:Y,allowMultiple:!0,showInactive:t==="edit-queue-item",printerMappingResults:Ae.printerResults,filamentReqs:oe,onAutoConfigurePrinter:Ae.autoConfigurePrinter,onUpdatePrinterConfig:Ae.updatePrinterConfig}),ie&&s.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:[s.jsx(Ji,{className:"w-4 h-4 text-orange-400 mt-0.5 flex-shrink-0"}),s.jsx("p",{className:"text-orange-400",children:"Archive data unavailable. The source file may have been deleted. Filament mapping is disabled."})]}),de&&!ie&&d.length===1&&s.jsx(DBe,{printerId:K,filamentReqs:oe,manualMappings:M,onManualMappingChange:w,defaultExpanded:D?.per_printer_mapping_expanded??!1}),(t==="reprint"||L>0)&&s.jsx(LBe,{options:b,onChange:v}),t!=="reprint"&&s.jsx(IBe,{options:x,onChange:y}),J.isError&&s.jsx("div",{className:"mb-4 p-3 bg-red-500/20 border border-red-500/50 rounded-lg text-sm text-red-400",children:J.error?.message||"Failed to complete operation"}),s.jsxs("div",{className:`flex gap-3 ${t==="reprint"?"":"pt-2"}`,children:[s.jsx(Ce,{type:"button",variant:"secondary",onClick:a,className:"flex-1",disabled:R,children:"Cancel"}),s.jsx(Ce,{type:"submit",disabled:!$,className:"flex-1",children:H?s.jsxs(s.Fragment,{children:[s.jsx(ft,{className:"w-4 h-4 animate-spin"}),z.loadingText]}):s.jsxs(s.Fragment,{children:[s.jsx(Z,{className:"w-4 h-4"}),z.submitText]})})]})]})]})})})}function UBe({onClose:t,initialFiles:e}){const n=Yt(),{showToast:r}=tr(),i=S.useRef(null),[a,o]=S.useState(()=>e?.filter(T=>T.name.endsWith(".3mf")).map(T=>({file:T,status:"pending"}))||[]),[l,c]=S.useState(!1),[u,d]=S.useState(),[f,m]=S.useState(null);S.useEffect(()=>{const T=R=>{R.key==="Escape"&&t()};return window.addEventListener("keydown",T),()=>window.removeEventListener("keydown",T)},[t]);const{data:g}=lt({queryKey:["printers"],queryFn:xe.getPrinters}),b=ht({mutationFn:T=>xe.uploadArchivesBulk(T,u),onSuccess:T=>{m(T),n.invalidateQueries({queryKey:["archives"]}),n.invalidateQueries({queryKey:["archiveStats"]}),o(R=>R.map(C=>{const P=T.results.find(L=>L.filename===C.file.name),F=T.errors.find(L=>L.filename===C.file.name);return P?{...C,status:"success",archiveId:P.id}:F?{...C,status:"error",error:F.error}:C})),T.failed===0?r(`${T.uploaded} file${T.uploaded!==1?"s":""} uploaded`):T.uploaded===0?r(`Failed to upload ${T.failed} file${T.failed!==1?"s":""}`,"error"):r(`${T.uploaded} uploaded, ${T.failed} failed`,"warning")},onError:()=>{o(T=>T.map(R=>({...R,status:"error",error:"Upload failed"}))),r("Upload failed","error")}}),v=S.useCallback(T=>{T.preventDefault(),c(!0)},[]),x=S.useCallback(T=>{T.preventDefault(),c(!1)},[]),y=S.useCallback(T=>{T.preventDefault(),c(!1);const R=Array.from(T.dataTransfer.files).filter(C=>C.name.endsWith(".3mf"));R.length>0&&o(C=>[...C,...R.map(P=>({file:P,status:"pending"}))])},[]),M=S.useCallback(T=>{const R=Array.from(T.target.files||[]).filter(C=>C.name.endsWith(".3mf"));R.length>0&&o(C=>[...C,...R.map(P=>({file:P,status:"pending"}))]),i.current&&(i.current.value="")},[]),w=S.useCallback(T=>{o(R=>R.filter((C,P)=>P!==T))},[]),A=()=>{if(a.length===0)return;const T=a.filter(R=>R.status==="pending");T.length!==0&&(o(R=>R.map(C=>C.status==="pending"?{...C,status:"uploading"}:C)),b.mutate(T.map(R=>R.file)))},N=a.filter(T=>T.status==="pending").length,k=b.isPending;return s.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:s.jsx(wt,{className:"w-full max-w-2xl max-h-[90vh] flex flex-col",children:s.jsxs(Mt,{className:"p-0 flex flex-col h-full",children:[s.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[s.jsx("h2",{className:"text-xl font-semibold text-white",children:"Upload 3MF Files"}),s.jsx("button",{onClick:t,className:"text-bambu-gray hover:text-white transition-colors",children:s.jsx(Ft,{className:"w-5 h-5"})})]}),s.jsx("div",{className:"p-4",children:s.jsxs("div",{className:`border-2 border-dashed rounded-lg p-8 text-center transition-colors ${l?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary hover:border-bambu-gray"}`,onDragOver:v,onDragLeave:x,onDrop:y,children:[s.jsx(bi,{className:"w-12 h-12 mx-auto mb-4 text-bambu-gray"}),s.jsx("p",{className:"text-white mb-2",children:"Drag & drop .3mf files here"}),s.jsx("p",{className:"text-bambu-gray text-sm mb-4",children:"or"}),s.jsx(Ce,{variant:"secondary",onClick:()=>i.current?.click(),disabled:k,children:"Browse Files"}),s.jsx("input",{ref:i,type:"file",accept:".3mf",multiple:!0,className:"hidden",onChange:M})]})}),s.jsxs("div",{className:"px-4 pb-4",children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-2",children:"Associate with printer (optional)"}),s.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:u||"",onChange:T=>d(T.target.value?Number(T.target.value):void 0),disabled:k,children:[s.jsx("option",{value:"",children:"No printer"}),g?.map(T=>s.jsx("option",{value:T.id,children:T.name},T.id))]})]}),a.length>0&&s.jsx("div",{className:"px-4 pb-4 max-h-60 overflow-y-auto",children:s.jsx("div",{className:"space-y-2",children:a.map((T,R)=>s.jsxs("div",{className:"flex items-center gap-3 p-3 bg-bambu-dark rounded-lg",children:[s.jsx(S2,{className:"w-5 h-5 text-bambu-gray flex-shrink-0"}),s.jsx("span",{className:"flex-1 text-white text-sm truncate",children:T.file.name}),s.jsxs("span",{className:"text-xs text-bambu-gray",children:[(T.file.size/(1024*1024)).toFixed(1)," MB"]}),T.status==="pending"&&s.jsx("button",{onClick:()=>w(R),className:"text-bambu-gray hover:text-red-400 transition-colors",disabled:k,children:s.jsx(Ft,{className:"w-4 h-4"})}),T.status==="uploading"&&s.jsx(ft,{className:"w-4 h-4 text-bambu-green animate-spin"}),T.status==="success"&&s.jsx(mr,{className:"w-4 h-4 text-bambu-green"}),T.status==="error"&&s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-xs text-red-400",children:T.error}),s.jsx(Ji,{className:"w-4 h-4 text-red-400"})]})]},`${T.file.name}-${R}`))})}),f&&s.jsx("div",{className:"px-4 pb-4",children:s.jsx("div",{className:"p-3 bg-bambu-dark rounded-lg",children:s.jsxs("p",{className:"text-sm text-white",children:[s.jsx("span",{className:"text-bambu-green",children:f.uploaded})," uploaded",f.failed>0&&s.jsxs(s.Fragment,{children:[", ",s.jsx("span",{className:"text-red-400",children:f.failed})," failed"]})]})})}),s.jsxs("div",{className:"flex gap-3 p-4 border-t border-bambu-dark-tertiary",children:[s.jsx(Ce,{variant:"secondary",onClick:t,className:"flex-1",children:f?"Close":"Cancel"}),!f&&s.jsx(Ce,{onClick:A,disabled:N===0||k,className:"flex-1",children:k?s.jsxs(s.Fragment,{children:[s.jsx(ft,{className:"w-4 h-4 animate-spin"}),"Uploading..."]}):s.jsxs(s.Fragment,{children:[s.jsx(bi,{className:"w-4 h-4"}),"Upload ",N>0&&`(${N})`]})})]})]})})})}const zBe=["Adhesion failure","Spaghetti / Detached","Layer shift","Clogged nozzle","Filament runout","Warping","Stringing","Under-extrusion","Power failure","User cancelled","Other"],BBe=[{value:"completed",label:"Completed"},{value:"failed",label:"Failed"},{value:"aborted",label:"Cancelled"},{value:"printing",label:"Printing"}];function DJ({archive:t,onClose:e,existingTags:n=[]}){S.useEffect(()=>{const oe=ce=>{ce.key==="Escape"&&e()};return window.addEventListener("keydown",oe),()=>window.removeEventListener("keydown",oe)},[e]);const r=Yt(),[i,a]=S.useState(t.print_name||""),[o,l]=S.useState(t.printer_id),[c,u]=S.useState(t.project_id??null),[d,f]=S.useState(t.notes||""),[m,g]=S.useState(t.tags||""),[b,v]=S.useState(t.failure_reason||""),[x,y]=S.useState(t.status),[M,w]=S.useState(t.quantity??1),[A,N]=S.useState(t.photos||[]),[k,T]=S.useState(!1),[R,C]=S.useState(!1),P=S.useRef(null),F=S.useRef(null),L=S.useRef(null),{data:K}=lt({queryKey:["printers"],queryFn:xe.getPrinters}),{data:D}=lt({queryKey:["projects"],queryFn:()=>xe.getProjects()}),{data:W}=lt({queryKey:["archives"],queryFn:()=>xe.getArchives(void 0,1e3,0),enabled:n.length===0}),Y=n.length>0?n:[...new Set(W?.flatMap(oe=>oe.tags?.split(",").map(ce=>ce.trim())||[]).filter(Boolean)||[])].sort(),q=m.split(",").map(oe=>oe.trim()).filter(Boolean),Q=Y.filter(oe=>!q.includes(oe)),re=oe=>{if(!q.includes(oe)){const ce=[...q,oe].join(", ");g(ce)}L.current!==null&&clearTimeout(L.current),P.current?.focus()},ne=oe=>{const ce=q.filter(me=>me!==oe).join(", ");g(ce)},U=ht({mutationFn:oe=>xe.updateArchive(t.id,oe),onSuccess:()=>{r.invalidateQueries({queryKey:["archives"]}),r.invalidateQueries({queryKey:["projects"]}),e()}}),G=async oe=>{const ce=oe.target.files?.[0];if(ce){T(!0);try{const me=await xe.uploadArchivePhoto(t.id,ce);N(me.photos),r.invalidateQueries({queryKey:["archives"]})}catch(me){console.error("Failed to upload photo:",me)}finally{T(!1),F.current&&(F.current.value="")}}},te=async oe=>{try{const ce=await xe.deleteArchivePhoto(t.id,oe);N(ce.photos||[]),r.invalidateQueries({queryKey:["archives"]})}catch(ce){console.error("Failed to delete photo:",ce)}},ie=oe=>{oe.preventDefault();const ce={print_name:i||void 0,printer_id:o,project_id:c,notes:d||void 0,tags:m||void 0,quantity:M};x!==t.status&&(ce.status=x),x==="failed"||x==="aborted"?ce.failure_reason=b||void 0:(t.status==="failed"||t.status==="aborted")&&(ce.failure_reason=null),U.mutate(ce)};return s.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:e,children:s.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:oe=>oe.stopPropagation(),children:[s.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[s.jsx("h2",{className:"text-lg font-semibold text-white",children:"Edit Archive"}),s.jsx("button",{onClick:e,className:"text-bambu-gray hover:text-white transition-colors",children:s.jsx(Ft,{className:"w-5 h-5"})})]}),s.jsxs("form",{onSubmit:ie,className:"p-6 space-y-4 overflow-y-auto flex-1",children:[s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Name"}),s.jsx("input",{type:"text",value:i,onChange:oe=>a(oe.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:"Print name"})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Printer"}),s.jsxs("select",{value:o??"",onChange:oe=>l(oe.target.value?Number(oe.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:[s.jsx("option",{value:"",children:"No printer"}),K?.map(oe=>s.jsx("option",{value:oe.id,children:oe.name},oe.id))]})]}),s.jsxs("div",{children:[s.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[s.jsx(ga,{className:"w-4 h-4 inline mr-1"}),"Project"]}),s.jsxs("select",{value:c??"",onChange:oe=>u(oe.target.value?Number(oe.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:[s.jsx("option",{value:"",children:"No project"}),D?.map(oe=>s.jsx("option",{value:oe.id,children:oe.name},oe.id))]})]}),s.jsxs("div",{children:[s.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[s.jsx(yue,{className:"w-4 h-4 inline mr-1"}),"Items Printed"]}),s.jsx("input",{type:"number",min:1,value:M,onChange:oe=>w(Math.max(1,parseInt(oe.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"}),s.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:"Number of items produced in this print job"})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Notes"}),s.jsx("textarea",{value:d,onChange:oe=>f(oe.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:"Add notes about this print..."})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Tags"}),q.length>0&&s.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:q.map(oe=>s.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 bg-bambu-dark-tertiary rounded text-sm text-white",children:[s.jsx(Kp,{className:"w-3 h-3"}),oe,s.jsx("button",{type:"button",onClick:()=>ne(oe),className:"ml-0.5 text-bambu-gray hover:text-white",children:s.jsx(Ft,{className:"w-3 h-3"})})]},oe))}),s.jsxs("div",{className:"relative",children:[s.jsx("input",{ref:P,type:"text",value:m,onChange:oe=>g(oe.target.value),onFocus:()=>{L.current!==null&&clearTimeout(L.current),C(!0)},onBlur:()=>{L.current=window.setTimeout(()=>C(!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:q.length>0?"Add more tags...":"Add tags..."}),R&&Q.length>0&&s.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:[s.jsx("div",{className:"p-2 text-xs text-bambu-gray border-b border-bambu-dark-tertiary",children:"Existing tags (click to add)"}),s.jsx("div",{className:"p-2 flex flex-wrap gap-1.5",children:Q.map(oe=>s.jsx("button",{type:"button",onClick:()=>re(oe),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:oe},oe))})]})]})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Status"}),s.jsx("select",{value:x,onChange:oe=>{y(oe.target.value),oe.target.value==="completed"&&v("")},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:BBe.map(oe=>s.jsx("option",{value:oe.value,children:oe.label},oe.value))})]}),(x==="failed"||x==="aborted")&&s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Failure Reason"}),s.jsxs("select",{value:b,onChange:oe=>v(oe.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:[s.jsx("option",{value:"",children:"Select reason..."}),zBe.map(oe=>s.jsx("option",{value:oe,children:oe},oe))]})]}),s.jsxs("div",{children:[s.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[s.jsx(Gp,{className:"w-4 h-4 inline mr-1"}),"Photos of Printed Result"]}),s.jsxs("div",{className:"flex flex-wrap gap-2 mb-2",children:[A.map(oe=>s.jsxs("div",{className:"relative group",children:[s.jsx("img",{src:xe.getArchivePhotoUrl(t.id,oe),alt:"Print result",className:"w-20 h-20 object-cover rounded-lg border border-bambu-dark-tertiary"}),s.jsx("button",{type:"button",onClick:()=>te(oe),className:"absolute -top-1 -right-1 p-1 bg-red-500 rounded-full opacity-0 group-hover:opacity-100 transition-opacity",children:s.jsx(nn,{className:"w-3 h-3 text-white"})})]},oe)),s.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:[s.jsx("input",{ref:F,type:"file",accept:"image/jpeg,image/png,image/webp",onChange:G,className:"hidden",disabled:k}),k?s.jsx(ft,{className:"w-6 h-6 text-bambu-gray animate-spin"}):s.jsx(ur,{className:"w-6 h-6 text-bambu-gray"})]})]}),s.jsx("p",{className:"text-xs text-bambu-gray",children:"Click + to add photos of your printed result"})]}),s.jsxs("div",{className:"flex gap-3 pt-2",children:[s.jsx(Ce,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:"Cancel"}),s.jsxs(Ce,{type:"submit",disabled:U.isPending,className:"flex-1",children:[s.jsx(Ds,{className:"w-4 h-4"}),U.isPending?"Saving...":"Save"]})]})]})]})})}function OJ({x:t,y:e,items:n,onClose:r}){const i=S.useRef(null),[a,o]=S.useState(null),l=S.useRef(null),[c,u]=S.useState({x:t,y:e,visible:!1}),[d,f]=S.useState(!1),[m,g]=S.useState({});S.useEffect(()=>{const x=w=>{i.current&&!i.current.contains(w.target)&&r()},y=w=>{w.key==="Escape"&&r()},M=()=>{r()};return document.addEventListener("mousedown",x),document.addEventListener("keydown",y),document.addEventListener("scroll",M,!0),()=>{document.removeEventListener("mousedown",x),document.removeEventListener("keydown",y),document.removeEventListener("scroll",M,!0),l.current&&clearTimeout(l.current)}},[r]),S.useLayoutEffect(()=>{if(i.current){i.current.style.visibility="hidden",i.current.style.display="block";const x=i.current.getBoundingClientRect(),y=window.innerWidth,M=window.innerHeight,w=8;let A=t,N=e;t+x.width>y-w&&(A=Math.max(w,y-x.width-w)),AM-w&&(N=Math.max(w,M-x.height-w)),Nk),u({x:A,y:N,visible:!0})}},[t,e]);const b=(x,y)=>{l.current&&(clearTimeout(l.current),l.current=null);const M=y.getBoundingClientRect(),w=window.innerHeight,A=300,T=w-M.top-8A;g(R=>({...R,[x]:T?"bottom":"top"})),o(x)},v=()=>{l.current=window.setTimeout(()=>{o(null)},150)};return s.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((x,y)=>{if(x.divider)return s.jsx("div",{className:"my-1 border-t border-bambu-dark-tertiary"},y);const M=x.submenu&&x.submenu.length>0;return s.jsxs("div",{className:"relative",onMouseEnter:w=>M&&b(y,w.currentTarget),onMouseLeave:()=>M&&v(),children:[s.jsxs("button",{onMouseEnter:w=>M&&b(y,w.currentTarget.parentElement),onClick:()=>{M?o(a===y?null:y):x.disabled||(x.onClick(),r())},disabled:x.disabled,className:`w-full flex items-center gap-2 px-3 py-2 text-sm text-left transition-colors ${x.disabled?"text-bambu-gray cursor-not-allowed":x.danger?"text-red-400 hover:bg-red-400/10":"text-white hover:bg-bambu-dark-tertiary"} ${M&&a===y?"bg-bambu-dark-tertiary":""}`,children:[x.icon&&s.jsx("span",{className:"w-4 h-4 flex-shrink-0 flex items-center justify-center",children:x.icon}),s.jsx("span",{className:"flex-1",children:x.label}),M&&s.jsx($s,{className:"w-4 h-4 text-bambu-gray"})]}),M&&a===y&&s.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] ${d?"right-full mr-1":"left-full ml-1"} ${m[y]==="bottom"?"bottom-0":"top-0"}`,onMouseEnter:()=>{l.current&&(clearTimeout(l.current),l.current=null)},onMouseLeave:()=>v(),children:x.submenu.map((w,A)=>s.jsxs("button",{onClick:()=>{w.disabled||(w.onClick(),r())},disabled:w.disabled,className:`w-full flex items-center gap-2 px-3 py-2 text-sm text-left transition-colors ${w.disabled?"text-bambu-gray cursor-not-allowed":w.danger?"text-red-400 hover:bg-red-400/10":"text-white hover:bg-bambu-dark-tertiary"}`,children:[w.icon&&s.jsx("span",{className:"w-4 h-4 flex-shrink-0 flex items-center justify-center",children:w.icon}),w.label]},A))})]},y)})})}function $Be({selectedIds:t,existingTags:e,onClose:n}){const r=Yt(),{showToast:i}=tr(),[a,o]=S.useState(""),[l,c]=S.useState(new Set),[u,d]=S.useState("add");S.useEffect(()=>{const v=x=>{x.key==="Escape"&&n()};return window.addEventListener("keydown",v),()=>window.removeEventListener("keydown",v)},[n]);const f=ht({mutationFn:async()=>{const v=Array.from(l);let x=0;for(const y of t)try{const M=await xe.getArchive(y),w=M.tags?M.tags.split(",").map(N=>N.trim()).filter(Boolean):[];let A;u==="add"?A=[...new Set([...w,...v])]:A=w.filter(N=>!l.has(N)),await xe.updateArchive(y,{tags:A.join(", ")}),x++}catch(M){throw console.error(`Failed to update archive ${y}:`,M),new Error(`Failed on archive ${y}: ${M instanceof Error?M.message:"Unknown error"}`)}return{count:x,mode:u,tags:v}},onSuccess:({count:v,mode:x,tags:y})=>{r.invalidateQueries({queryKey:["archives"]}),i(`${x==="add"?"Added":"Removed"} ${y.length} tag${y.length!==1?"s":""} ${x==="add"?"to":"from"} ${v} archive${v!==1?"s":""}`),n()},onError:v=>{i(v.message||"Failed to update tags","error")}}),m=v=>{c(x=>{const y=new Set(x);return y.has(v)?y.delete(v):y.add(v),y})},g=()=>{a.trim()&&!l.has(a.trim())&&(c(v=>new Set([...v,a.trim()])),o(""))},b=v=>{v.key==="Enter"&&(v.preventDefault(),g())};return s.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:s.jsx(wt,{className:"w-full max-w-md",children:s.jsxs(Mt,{className:"p-0",children:[s.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(Kp,{className:"w-5 h-5 text-bambu-green"}),s.jsx("h2",{className:"text-xl font-semibold text-white",children:u==="add"?"Add Tags":"Remove Tags"})]}),s.jsx("button",{onClick:n,className:"text-bambu-gray hover:text-white transition-colors",children:s.jsx(Ft,{className:"w-5 h-5"})})]}),s.jsxs("div",{className:"p-4 space-y-4",children:[s.jsxs("p",{className:"text-sm text-bambu-gray",children:[u==="add"?"Add":"Remove"," tags for ",t.length," selected archive",t.length!==1?"s":""]}),s.jsxs("div",{className:"flex gap-2",children:[s.jsx(Ce,{size:"sm",variant:u==="add"?"primary":"secondary",onClick:()=>d("add"),children:"Add Tags"}),s.jsx(Ce,{size:"sm",variant:u==="remove"?"primary":"secondary",onClick:()=>d("remove"),children:"Remove Tags"})]}),u==="add"&&s.jsxs("div",{className:"flex gap-2",children:[s.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:a,onChange:v=>o(v.target.value),onKeyDown:b}),s.jsx(Ce,{size:"sm",variant:"secondary",onClick:g,disabled:!a.trim(),children:s.jsx(ur,{className:"w-4 h-4"})})]}),e.length>0&&s.jsxs("div",{children:[s.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:"Existing tags:"}),s.jsx("div",{className:"flex flex-wrap gap-2",children:e.map(v=>s.jsx("button",{onClick:()=>m(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&&s.jsxs("div",{children:[s.jsxs("p",{className:"text-xs text-bambu-gray mb-2",children:["Tags to ",u==="add"?"add":"remove",":"]}),s.jsx("div",{className:"flex flex-wrap gap-2",children:Array.from(l).map(v=>s.jsxs("span",{className:`px-2 py-1 rounded text-sm flex items-center gap-1 ${u==="add"?"bg-green-500/20 text-green-400":"bg-red-500/20 text-red-400"}`,children:[v,s.jsx("button",{onClick:()=>m(v),className:"hover:opacity-70",children:s.jsx(Ft,{className:"w-3 h-3"})})]},v))})]})]}),s.jsxs("div",{className:"flex gap-3 p-4 border-t border-bambu-dark-tertiary",children:[s.jsx(Ce,{variant:"secondary",onClick:n,className:"flex-1",children:"Cancel"}),s.jsx(Ce,{onClick:()=>f.mutate(),disabled:l.size===0||f.isPending,className:"flex-1",children:f.isPending?s.jsxs(s.Fragment,{children:[s.jsx(ft,{className:"w-4 h-4 animate-spin"}),"Processing..."]}):s.jsxs(s.Fragment,{children:[s.jsx(Kp,{className:"w-4 h-4"}),u==="add"?"Add Tags":"Remove Tags"]})})]})]})})})}function HBe({selectedIds:t,onClose:e}){const n=Yt(),{showToast:r}=tr(),{data:i,isLoading:a}=lt({queryKey:["projects"],queryFn:()=>xe.getProjects()});S.useEffect(()=>{const d=f=>{f.key==="Escape"&&e()};return window.addEventListener("keydown",d),()=>window.removeEventListener("keydown",d)},[e]);const o=()=>{n.invalidateQueries({queryKey:["archives"]}),n.invalidateQueries({queryKey:["projects"]}),n.invalidateQueries({queryKey:["project"]}),n.invalidateQueries({queryKey:["project-archives"]})},l=ht({mutationFn:async d=>(await xe.addArchivesToProject(d,t),d),onSuccess:d=>{const f=i?.find(m=>m.id===d);o(),r(`Added ${t.length} archive${t.length!==1?"s":""} to "${f?.name}"`),e()},onError:()=>{r("Failed to assign project","error")}}),c=ht({mutationFn:async()=>{for(const d of t)await xe.updateArchive(d,{project_id:null});return t.length},onSuccess:d=>{o(),r(`Removed ${d} archive${d!==1?"s":""} from project`),e()},onError:()=>{r("Failed to remove from project","error")}}),u=l.isPending||c.isPending;return s.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:s.jsx(wt,{className:"w-full max-w-md max-h-[80vh] flex flex-col",children:s.jsxs(Mt,{className:"p-0 flex flex-col min-h-0",children:[s.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary shrink-0",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(ga,{className:"w-5 h-5 text-bambu-green"}),s.jsx("h2",{className:"text-xl font-semibold text-white",children:"Assign to Project"})]}),s.jsx("button",{onClick:e,className:"text-bambu-gray hover:text-white transition-colors",disabled:u,children:s.jsx(Ft,{className:"w-5 h-5"})})]}),s.jsxs("div",{className:"p-4 space-y-3 overflow-y-auto min-h-0",children:[s.jsxs("p",{className:"text-sm text-bambu-gray",children:["Assign ",t.length," selected archive",t.length!==1?"s":""," to a project"]}),a?s.jsx("div",{className:"flex items-center justify-center py-8",children:s.jsx(ft,{className:"w-6 h-6 animate-spin text-bambu-gray"})}):s.jsxs("div",{className:"space-y-2",children:[s.jsxs("button",{onClick:()=>c.mutate(),disabled:u,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:[s.jsx("div",{className:"w-8 h-8 rounded-full bg-red-500/20 flex items-center justify-center shrink-0",children:s.jsx(Wi,{className:"w-4 h-4 text-red-400"})}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("p",{className:"text-white font-medium",children:"Remove from project"}),s.jsx("p",{className:"text-sm text-bambu-gray truncate",children:"Clear project assignment"})]}),c.isPending&&s.jsx(ft,{className:"w-4 h-4 animate-spin text-bambu-gray shrink-0"})]}),i&&i.length>0&&s.jsxs("div",{className:"flex items-center gap-2 py-2",children:[s.jsx("div",{className:"flex-1 h-px bg-bambu-dark-tertiary"}),s.jsx("span",{className:"text-xs text-bambu-gray",children:"or assign to"}),s.jsx("div",{className:"flex-1 h-px bg-bambu-dark-tertiary"})]}),i?.map(d=>s.jsxs("button",{onClick:()=>l.mutate(d.id),disabled:u,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:[s.jsx("div",{className:"w-8 h-8 rounded-full flex items-center justify-center shrink-0",style:{backgroundColor:d.color?`${d.color}20`:"rgb(var(--bambu-green) / 0.2)"},children:s.jsx(ga,{className:"w-4 h-4",style:{color:d.color||"rgb(var(--bambu-green))"}})}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("p",{className:"text-white font-medium truncate",children:d.name}),s.jsxs("p",{className:"text-sm text-bambu-gray truncate",children:[d.archive_count," archive",d.archive_count!==1?"s":"",d.status&&` • ${d.status}`]})]}),l.isPending&&l.variables===d.id&&s.jsx(ft,{className:"w-4 h-4 animate-spin text-bambu-gray shrink-0"})]},d.id)),(!i||i.length===0)&&s.jsx("p",{className:"text-center text-bambu-gray py-4",children:"No projects yet. Create one from the Projects page."})]})]}),s.jsx("div",{className:"flex gap-3 p-4 border-t border-bambu-dark-tertiary shrink-0",children:s.jsx(Ce,{variant:"secondary",onClick:e,className:"flex-1",disabled:u,children:"Cancel"})})]})})})}function VBe(t,e){return new Date(t,e+1,0).getDate()}function GBe(t,e){return new Date(t,e,1).getDay()}const WBe=["January","February","March","April","May","June","July","August","September","October","November","December"],qBe=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];function KBe({archives:t,onArchiveClick:e,highlightedArchiveId:n}){const r=new Date,[i,a]=S.useState(r.getMonth()),[o,l]=S.useState(r.getFullYear()),[c,u]=S.useState(null),[d,f]=S.useState(null),m=S.useMemo(()=>{const N=new Map;return t.forEach(k=>{const T=mi(k.completed_at||k.created_at)||new Date,R=`${T.getFullYear()}-${String(T.getMonth()+1).padStart(2,"0")}-${String(T.getDate()).padStart(2,"0")}`,C=N.get(R)||[];C.push(k),N.set(R,C)}),N},[t]),g=VBe(o,i),b=GBe(o,i),v=()=>{i===0?(a(11),l(o-1)):a(i-1)},x=()=>{i===11?(a(0),l(o+1)):a(i+1)},y=()=>{a(r.getMonth()),l(r.getFullYear())},M=[];for(let N=0;N{N!==c&&f(null),u(N)};return s.jsxs("div",{className:"flex flex-col lg:flex-row gap-6",children:[s.jsxs("div",{className:"flex-1",children:[s.jsxs("div",{className:"flex items-center justify-between mb-4",children:[s.jsx("button",{onClick:v,className:"p-2 hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:s.jsx(mf,{className:"w-5 h-5 text-bambu-gray"})}),s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsxs("h2",{className:"text-lg font-semibold text-white",children:[WBe[i]," ",o]}),s.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"})]}),s.jsx("button",{onClick:x,className:"p-2 hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:s.jsx($s,{className:"w-5 h-5 text-bambu-gray"})})]}),s.jsx("div",{className:"grid grid-cols-7 gap-1 mb-1",children:qBe.map(N=>s.jsx("div",{className:"text-center text-xs text-bambu-gray py-2",children:N},N))}),s.jsx("div",{className:"grid grid-cols-7 gap-1",children:M.map((N,k)=>{if(N===null)return s.jsx("div",{className:"aspect-square"},`empty-${k}`);const T=`${o}-${String(i+1).padStart(2,"0")}-${String(N).padStart(2,"0")}`,R=m.get(T)||[],C=R.length>0,P=N===r.getDate()&&i===r.getMonth()&&o===r.getFullYear(),F=T===c,L=R.filter(D=>D.status==="completed").length,K=R.filter(D=>D.status==="failed").length;return s.jsxs("button",{onClick:()=>A(F?null:T),className:`aspect-square rounded-lg p-1 flex flex-col items-center justify-center transition-colors relative ${F?"bg-bambu-green text-white":P?"bg-bambu-green/20 text-white ring-2 ring-bambu-green":C?"bg-bambu-dark-tertiary hover:bg-bambu-dark-tertiary/70 text-white":"hover:bg-bambu-dark-tertiary/50 text-bambu-gray"}`,children:[s.jsx("span",{className:`text-sm font-medium ${P&&!F?"text-bambu-green":""}`,children:N}),C&&s.jsxs("div",{className:"absolute bottom-1 left-1/2 -translate-x-1/2 flex items-center gap-1",children:[s.jsx("div",{className:`w-2 h-2 rounded-full ${K>0&&L===0?"bg-red-400":K>0?"bg-yellow-400":"bg-green-400"}`}),s.jsx("span",{className:"text-xs font-medium",children:R.length})]})]},N)})}),s.jsx("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:s.jsxs("div",{className:"grid grid-cols-3 gap-4 text-center",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-2xl font-bold text-white",children:t.filter(N=>{const k=new Date(N.completed_at||N.created_at);return k.getMonth()===i&&k.getFullYear()===o}).length}),s.jsx("div",{className:"text-xs text-bambu-gray",children:"Prints this month"})]}),s.jsxs("div",{children:[s.jsx("div",{className:"text-2xl font-bold text-green-400",children:t.filter(N=>{const k=new Date(N.completed_at||N.created_at);return k.getMonth()===i&&k.getFullYear()===o&&N.status==="completed"}).length}),s.jsx("div",{className:"text-xs text-bambu-gray",children:"Successful"})]}),s.jsxs("div",{children:[s.jsx("div",{className:"text-2xl font-bold text-red-400",children:t.filter(N=>{const k=new Date(N.completed_at||N.created_at);return k.getMonth()===i&&k.getFullYear()===o&&N.status==="failed"}).length}),s.jsx("div",{className:"text-xs text-bambu-gray",children:"Failed"})]})]})})]}),s.jsx("div",{className:"lg:w-80 bg-bambu-dark rounded-xl p-4",children:c?s.jsxs(s.Fragment,{children:[s.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"})}),w.length>0?s.jsx("div",{className:"space-y-2 max-h-96 overflow-y-auto",children:w.map(N=>{const k=N.id===d||N.id===n;return s.jsxs("button",{onClick:()=>{f(N.id),e?.(N)},className:`w-full flex items-center gap-3 p-2 rounded-lg transition-colors text-left ${k?"":"hover:bg-bambu-dark-tertiary"}`,style:k?{outline:"4px solid #facc15",outlineOffset:"2px"}:void 0,children:[N.thumbnail_path?s.jsx("img",{src:xe.getArchiveThumbnail(N.id),alt:"",className:"w-12 h-12 rounded object-cover"}):s.jsx("div",{className:"w-12 h-12 rounded bg-bambu-dark-tertiary flex items-center justify-center",children:s.jsx("span",{className:"text-xs text-bambu-gray",children:"3MF"})}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsx("p",{className:"text-sm text-white truncate",children:N.print_name||N.filename}),s.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[s.jsx("span",{className:N.status==="failed"?"text-red-400":"text-green-400",children:N.status==="failed"?"Failed":"Completed"}),N.filament_color&&s.jsx("div",{className:"flex gap-0.5",children:N.filament_color.split(",").map((T,R)=>s.jsx("div",{className:"w-3 h-3 rounded-full border border-white/20",style:{backgroundColor:T}},R))})]})]})]},N.id)})}):s.jsx("p",{className:"text-sm text-bambu-gray",children:"No prints on this day"})]}):s.jsx("div",{className:"text-center py-8",children:s.jsx("p",{className:"text-sm text-bambu-gray",children:"Select a day to see prints"})})})]})}function LJ({archiveId:t,archiveName:e,onClose:n}){const r=xe.getArchiveQRCodeUrl(t,300);S.useEffect(()=>{const a=o=>{o.key==="Escape"&&n()};return window.addEventListener("keydown",a),()=>window.removeEventListener("keydown",a)},[n]);const i=()=>{const a=document.createElement("a");a.href=r,a.download=`${e}_qrcode.png`,a.click()};return s.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:n,children:s.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary w-full max-w-sm",onClick:a=>a.stopPropagation(),children:[s.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[s.jsx("h2",{className:"text-lg font-semibold text-white",children:"QR Code"}),s.jsx("button",{onClick:n,className:"text-bambu-gray hover:text-white transition-colors",children:s.jsx(Ft,{className:"w-5 h-5"})})]}),s.jsxs("div",{className:"p-6 flex flex-col items-center",children:[s.jsx("p",{className:"text-sm text-bambu-gray mb-4 text-center truncate max-w-full",children:e}),s.jsx("div",{className:"bg-white p-4 rounded-lg mb-4",children:s.jsx("img",{src:r,alt:"QR Code",className:"w-64 h-64"})}),s.jsx("p",{className:"text-xs text-bambu-gray mb-4 text-center",children:"Scan to open this archive"}),s.jsxs(Ce,{onClick:i,className:"w-full",children:[s.jsx(Jr,{className:"w-4 h-4"}),"Download QR Code"]})]})]})})}function IJ({archiveId:t,archiveName:e,photos:n,onClose:r,onDelete:i}){const[a,o]=S.useState(0),[l,c]=S.useState(!1);if(S.useEffect(()=>{const g=b=>{b.key==="Escape"&&r(),b.key==="ArrowLeft"&&o(v=>Math.max(0,v-1)),b.key==="ArrowRight"&&o(v=>Math.min(n.length-1,v+1))};return window.addEventListener("keydown",g),()=>window.removeEventListener("keydown",g)},[r,n.length]),S.useEffect(()=>{a>=n.length&&o(Math.max(0,n.length-1))},[n.length,a]),n.length===0)return r(),null;const u=n[a],d=xe.getArchivePhotoUrl(t,u),f=()=>{const g=document.createElement("a");g.href=d,g.download=`${e}_photo_${a+1}.jpg`,g.click()},m=()=>{i&&c(!0)};return s.jsxs("div",{className:"fixed inset-0 bg-black/90 flex items-center justify-center z-50",onClick:r,children:[s.jsxs("div",{className:"relative w-full h-full flex flex-col",onClick:g=>g.stopPropagation(),children:[s.jsxs("div",{className:"flex items-center justify-between px-6 py-4 bg-black/50",children:[s.jsxs("div",{children:[s.jsx("h2",{className:"text-lg font-semibold text-white",children:e}),s.jsxs("p",{className:"text-sm text-bambu-gray",children:["Photo ",a+1," of ",n.length]})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs(Ce,{variant:"secondary",size:"sm",onClick:f,children:[s.jsx(Jr,{className:"w-4 h-4"}),"Download"]}),i&&s.jsx(Ce,{variant:"secondary",size:"sm",onClick:m,className:"text-red-400 hover:text-red-300",children:s.jsx(nn,{className:"w-4 h-4"})}),s.jsx("button",{onClick:r,className:"p-2 text-bambu-gray hover:text-white transition-colors",children:s.jsx(Ft,{className:"w-6 h-6"})})]})]}),s.jsxs("div",{className:"flex-1 min-h-0 flex items-center justify-center p-4 relative overflow-hidden",children:[a>0&&s.jsx("button",{onClick:()=>o(g=>g-1),className:"absolute left-4 z-10 p-3 bg-black/50 hover:bg-black/70 rounded-full transition-colors",children:s.jsx(mf,{className:"w-8 h-8 text-white"})}),s.jsx("img",{src:d,alt:`Photo ${a+1}`,className:"max-w-full max-h-full object-contain rounded-lg",style:{maxHeight:"calc(100vh - 200px)"}}),ao(g=>g+1),className:"absolute right-4 z-10 p-3 bg-black/50 hover:bg-black/70 rounded-full transition-colors",children:s.jsx($s,{className:"w-8 h-8 text-white"})})]}),n.length>1&&s.jsx("div",{className:"flex justify-center gap-2 p-4 bg-black/50",children:n.map((g,b)=>s.jsx("button",{onClick:()=>o(b),className:`w-16 h-16 rounded-lg overflow-hidden border-2 transition-colors ${b===a?"border-bambu-green":"border-transparent hover:border-bambu-gray"}`,children:s.jsx("img",{src:xe.getArchivePhotoUrl(t,g),alt:`Thumbnail ${b+1}`,className:"w-full h-full object-cover"})},g))})]}),l&&s.jsx(Fn,{title:"Delete Photo",message:"Delete this photo? This cannot be undone.",confirmText:"Delete",variant:"danger",onConfirm:()=>{i?.(u),c(!1)},onCancel:()=>c(!1)})]})}function ua(t){this.content=t}ua.prototype={constructor:ua,find:function(t){for(var e=0;e>1}};ua.from=function(t){if(t instanceof ua)return t;var e=[];if(t)for(var n in t)e.push(n,t[n]);return new ua(e)};function FJ(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),a=e.child(r);if(i==a){n+=i.nodeSize;continue}if(!i.sameMarkup(a))return n;if(i.isText&&i.text!=a.text){for(let o=0;i.text[o]==a.text[o];o++)n++;return n}if(i.content.size||a.content.size){let o=FJ(i.content,a.content,n+1);if(o!=null)return o}n+=i.nodeSize}}function UJ(t,e,n,r){for(let i=t.childCount,a=e.childCount;;){if(i==0||a==0)return i==a?null:{a:n,b:r};let o=t.child(--i),l=e.child(--a),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 u=0,d=Math.min(o.text.length,l.text.length);for(;ue&&r(c,i+l,a||null,o)!==!1&&c.content.size){let d=l+1;c.nodesBetween(Math.max(0,e-d),Math.min(c.content.size,n-d),r,i+d)}l=u}}descendants(e){this.nodesBetween(0,this.size,e)}textBetween(e,n,r,i){let a="",o=!0;return this.nodesBetween(e,n,(l,c)=>{let u=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&&u||l.isTextblock)&&r&&(o?o=!1:a+=r),a+=u},0),a}append(e){if(!e.size)return this;if(!this.size)return e;let n=this.lastChild,r=e.firstChild,i=this.content.slice(),a=0;for(n.isText&&n.sameMarkup(r)&&(i[i.length-1]=n.withText(n.text+r.text),a=1);ae)for(let a=0,o=0;oe&&((on)&&(l.isText?l=l.cut(Math.max(0,e-o),Math.min(l.text.length,n-o)):l=l.cut(Math.max(0,e-o-1),Math.min(l.content.size,n-o-1))),r.push(l),i+=l.nodeSize),o=c}return new _t(r,i)}cutByIndex(e,n){return e==n?_t.empty:e==0&&n==this.content.length?this:new _t(this.content.slice(e,n))}replaceChild(e,n){let r=this.content[e];if(r==n)return this;let i=this.content.slice(),a=this.size+n.nodeSize-r.nodeSize;return i[e]=n,new _t(i,a)}addToStart(e){return new _t([e].concat(this.content),this.size+e.nodeSize)}addToEnd(e){return new _t(this.content.concat(e),this.size+e.nodeSize)}eq(e){if(this.content.length!=e.content.length)return!1;for(let n=0;nthis.size||e<0)throw new RangeError(`Position ${e} outside of fragment (${this})`);for(let n=0,r=0;;n++){let i=this.child(n),a=r+i.nodeSize;if(a>=e)return a==e?d1(n+1,a):d1(n,r);r=a}}toString(){return"<"+this.toStringInner()+">"}toStringInner(){return this.content.join(", ")}toJSON(){return this.content.length?this.content.map(e=>e.toJSON()):null}static fromJSON(e,n){if(!n)return _t.empty;if(!Array.isArray(n))throw new RangeError("Invalid input for Fragment.fromJSON");return new _t(n.map(e.nodeFromJSON))}static fromArray(e){if(!e.length)return _t.empty;let n,r=0;for(let i=0;ithis.type.rank&&(n||(n=e.slice(0,i)),n.push(this),r=!0),n&&n.push(a)}}return n||(n=e.slice()),r||n.push(this),n}removeFromSet(e){for(let n=0;nr.type.rank-i.type.rank),n}};pr.none=[];class SS extends Error{}class Rt{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=BJ(this.content,e+this.openStart,n);return r&&new Rt(r,this.openStart,this.openEnd)}removeBetween(e,n){return new Rt(zJ(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 Rt.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 Rt(_t.fromJSON(e,n.content),r,i)}static maxOpen(e,n=!0){let r=0,i=0;for(let a=e.firstChild;a&&!a.isLeaf&&(n||!a.type.spec.isolating);a=a.firstChild)r++;for(let a=e.lastChild;a&&!a.isLeaf&&(n||!a.type.spec.isolating);a=a.lastChild)i++;return new Rt(e,r,i)}}Rt.empty=new Rt(_t.empty,0,0);function zJ(t,e,n){let{index:r,offset:i}=t.findIndex(e),a=t.maybeChild(r),{index:o,offset:l}=t.findIndex(n);if(i==e||a.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,a.copy(zJ(a.content,e-i-1,n-i-1)))}function BJ(t,e,n,r){let{index:i,offset:a}=t.findIndex(e),o=t.maybeChild(i);if(a==e||o.isText)return r&&!r.canReplace(i,i,n)?null:t.cut(0,e).append(n).append(t.cut(e));let l=BJ(o.content,e-a-1,n,o);return l&&t.replaceChild(i,o.copy(l))}function XBe(t,e,n){if(n.openStart>t.depth)throw new SS("Inserted content deeper than insertion position");if(t.depth-n.openStart!=e.depth-n.openEnd)throw new SS("Inconsistent open depths");return $J(t,e,n,0)}function $J(t,e,n,r){let i=t.index(r),a=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 Ob(t,e,n,r){let i=(e||t).node(n),a=0,o=e?e.index(n):i.childCount;t&&(a=t.index(n),t.depth>n?a++:t.textOffset&&(sf(t.nodeAfter,r),a++));for(let l=a;li&&VP(t,e,i+1),o=r.depth>i&&VP(n,r,i+1),l=[];return Ob(null,t,i,l),a&&o&&e.index(i)==n.index(i)?(HJ(a,o),sf(of(a,VJ(t,e,n,r,i+1)),l)):(a&&sf(of(a,MS(t,e,i+1)),l),Ob(e,n,i,l),o&&sf(of(o,MS(n,r,i+1)),l)),Ob(r,null,i,l),new _t(l)}function MS(t,e,n){let r=[];if(Ob(null,t,n,r),t.depth>n){let i=VP(t,e,n+1);sf(of(i,MS(t,e,n+1)),r)}return Ob(e,null,n,r),new _t(r)}function YBe(t,e){let n=e.depth-t.openStart,i=e.node(n).copy(t.content);for(let a=n-1;a>=0;a--)i=e.node(a).copy(_t.from(i));return{start:i.resolveNoCache(t.openStart+n),end:i.resolveNoCache(i.content.size-t.openEnd-n)}}class C0{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 a=0;a0;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 ES(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,a=n;for(let o=e;;){let{index:l,offset:c}=o.content.findIndex(a),u=a-c;if(r.push(o,l,i+c),!u||(o=o.child(l),o.isText))break;a=u-1,i+=c+1}return new C0(n,r,a)}static resolveCached(e,n){let r=X7.get(e);if(r)for(let a=0;ae&&this.nodesBetween(e,n,a=>(r.isInSet(a.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()+")"),GJ(this.marks,e)}contentMatchAt(e){let n=this.type.contentMatch.matchFragment(this.content,0,e);if(!n)throw new Error("Called contentMatchAt on a node with invalid content");return n}canReplace(e,n,r=_t.empty,i=0,a=r.childCount){let o=this.contentMatchAt(e).matchFragment(r,i,a),l=o&&o.matchFragment(this.content,n);if(!l||!l.validEnd)return!1;for(let c=i;cn.type.name)}`);this.content.forEach(n=>n.check())}toJSON(){let e={type:this.type.name};for(let n in this.attrs){e.attrs=this.attrs;break}return this.content.size&&(e.content=this.content.toJSON()),this.marks.length&&(e.marks=this.marks.map(n=>n.toJSON())),e}static fromJSON(e,n){if(!n)throw new RangeError("Invalid input for Node.fromJSON");let r;if(n.marks){if(!Array.isArray(n.marks))throw new RangeError("Invalid mark data for Node.fromJSON");r=n.marks.map(e.markFromJSON)}if(n.type=="text"){if(typeof n.text!="string")throw new RangeError("Invalid text node in JSON");return e.text(n.text,r)}let i=_t.fromJSON(e,n.content),a=e.nodeType(n.type).create(n.attrs,i,r);return a.type.checkAttrs(a.attrs),a}};Td.prototype.text=void 0;class NS extends Td{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):GJ(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 NS(this.type,this.attrs,this.text,e)}withText(e){return e==this.text?this:new NS(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 GJ(t,e){for(let n=t.length-1;n>=0;n--)e=t[n].type.name+"("+e+")";return e}class Df{constructor(e){this.validEnd=e,this.next=[],this.wrapCache=[]}static parse(e,n){let r=new e8e(e,n);if(r.next==null)return Df.empty;let i=WJ(r);r.next&&r.err("Unexpected trailing text");let a=o8e(s8e(i));return l8e(a,r),a}matchType(e){for(let n=0;nu.createAndFill()));for(let u=0;u=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 a=i+(r.validEnd?"*":" ")+" ";for(let o=0;o"+e.indexOf(r.next[o].next);return a}).join(` `)}}Df.empty=new Df(!0);class e8e{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 WJ(t){let e=[];do e.push(t8e(t));while(t.eat("|"));return e.length==1?e[0]:{type:"choice",exprs:e}}function t8e(t){let e=[];do e.push(n8e(t));while(t.next&&t.next!=")"&&t.next!="|");return e.length==1?e[0]:{type:"seq",exprs:e}}function n8e(t){let e=a8e(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=r8e(t,e);else break;return e}function Y7(t){/\D/.test(t.next)&&t.err("Expected number, got '"+t.next+"'");let e=Number(t.next);return t.pos++,e}function r8e(t,e){let n=Y7(t),r=n;return t.eat(",")&&(t.next!="}"?r=Y7(t):r=-1),t.eat("}")||t.err("Unclosed braced range"),{type:"range",min:n,max:r,expr:e}}function i8e(t,e){let n=t.nodeTypes,r=n[e];if(r)return[r];let i=[];for(let a in n){let o=n[a];o.isInGroup(e)&&i.push(o)}return i.length==0&&t.err("No node type or group '"+e+"' found"),i}function a8e(t){if(t.eat("(")){let e=WJ(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=i8e(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 s8e(t){let e=[[]];return i(a(t,0),n()),e;function n(){return e.push([])-1}function r(o,l,c){let u={term:c,to:l};return e[o].push(u),u}function i(o,l){o.forEach(c=>c.to=l)}function a(o,l){if(o.type=="choice")return o.exprs.reduce((c,u)=>c.concat(a(u,l)),[]);if(o.type=="seq")for(let c=0;;c++){let u=a(o.exprs[c],l);if(c==o.exprs.length-1)return u;i(u,l=n())}else if(o.type=="star"){let c=n();return r(l,c),i(a(o.expr,c),c),[r(c)]}else if(o.type=="plus"){let c=n();return i(a(o.expr,l),c),i(a(o.expr,c),c),[r(c)]}else{if(o.type=="opt")return[r(l)].concat(a(o.expr,l));if(o.type=="range"){let c=l;for(let u=0;u{t[o].forEach(({term:l,to:c})=>{if(!l)return;let u;for(let d=0;d{u||i.push([l,u=[]]),u.indexOf(d)==-1&&u.push(d)})})});let a=e[r.join(",")]=new Df(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:XJ(this.attrs,e)}create(e=null,n,r){if(this.isText)throw new Error("NodeType.create can't construct text nodes");return new Td(this,this.computeAttrs(e),_t.from(n),pr.setFrom(r))}createChecked(e=null,n,r){return n=_t.from(n),this.checkContent(n),new Td(this,this.computeAttrs(e),n,pr.setFrom(r))}createAndFill(e=null,n,r){if(e=this.computeAttrs(e),n=_t.from(n),n.size){let o=this.contentMatch.fillBefore(n);if(!o)return null;n=o.append(n)}let i=this.contentMatch.matchFragment(n),a=i&&i.fillBefore(_t.empty,!0);return a?new Td(this,e,n.append(a),pr.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[a]=new ZJ(a,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 a in r.text.attrs)throw new RangeError("The text node type should not have attributes");return r}};function c8e(t,e,n){let r=n.split("|");return i=>{let a=i===null?"null":typeof i;if(r.indexOf(a)<0)throw new RangeError(`Expected value of type ${r} for attribute ${e} on type ${t}, got ${a}`)}}class u8e{constructor(e,n,r){this.hasDefault=Object.prototype.hasOwnProperty.call(r,"default"),this.default=r.default,this.validate=typeof r.validate=="string"?c8e(e,n,r.validate):r.validate}get isRequired(){return!this.hasDefault}}class IM{constructor(e,n,r,i){this.name=e,this.rank=n,this.schema=r,this.spec=i,this.attrs=QJ(e,i.attrs),this.excluded=null;let a=KJ(this.attrs);this.instance=a?new pr(this,a):null}create(e=null){return!e&&this.instance?this.instance:new pr(this,XJ(this.attrs,e))}static compile(e,n){let r=Object.create(null),i=0;return e.forEach((a,o)=>r[a]=new IM(a,i++,n,o)),r}removeFromSet(e){for(var n=0;n-1}}class JJ{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=ua.from(e.nodes),n.marks=ua.from(e.marks||{}),this.nodes=Z7.compile(this.spec.nodes,this),this.marks=IM.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 a=this.nodes[i],o=a.spec.content||"",l=a.spec.marks;if(a.contentMatch=r[o]||(r[o]=Df.parse(o,this.nodes)),a.inlineContent=a.contentMatch.inlineContent,a.spec.linebreakReplacement){if(this.linebreakReplacement)throw new RangeError("Multiple linebreak nodes defined");if(!a.isInline||!a.isLeaf)throw new RangeError("Linebreak replacement nodes must be inline leaf nodes");this.linebreakReplacement=a}a.markSet=l=="_"?null:l?J7(this,l.split(" ")):l==""||!a.inlineContent?[]:null}for(let i in this.marks){let a=this.marks[i],o=a.spec.excludes;a.excluded=o==null?[a]:o==""?[]:J7(this,o.split(" "))}this.nodeFromJSON=i=>Td.fromJSON(this,i),this.markFromJSON=i=>pr.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 Z7){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 NS(r,r.defaultAttrs,e,pr.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 J7(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 d8e(t){return t.tag!=null}function h8e(t){return t.style!=null}let Lb=class WP{constructor(e,n){this.schema=e,this.rules=n,this.tags=[],this.styles=[];let r=this.matchedStyles=[];n.forEach(i=>{if(d8e(i))this.tags.push(i);else if(h8e(i)){let a=/[^=]*/.exec(i.style)[0];r.indexOf(a)<0&&r.push(a),this.styles.push(i)}}),this.normalizeLists=!this.tags.some(i=>{if(!/^(ul|ol)\b/.test(i.tag)||!i.node)return!1;let a=e.nodes[i.node];return a.contentMatch.matchType(a)})}parse(e,n={}){let r=new t9(this,n,!1);return r.addAll(e,pr.none,n.from,n.to),r.finish()}parseSlice(e,n={}){let r=new t9(this,n,!0);return r.addAll(e,pr.none,n.from,n.to),Rt.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 a=i.priority==null?50:i.priority,o=0;for(;o{r(o=n9(o)),o.mark||o.ignore||o.clearMark||(o.mark=i)})}for(let i in e.nodes){let a=e.nodes[i].spec.parseDOM;a&&a.forEach(o=>{r(o=n9(o)),o.node||o.ignore||o.mark||(o.node=i)})}return n}static fromSchema(e){return e.cached.domParser||(e.cached.domParser=new WP(e,WP.schemaRules(e)))}};const eee={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},f8e={head:!0,noscript:!0,object:!0,script:!0,style:!0,title:!0},tee={ol:!0,ul:!0},k0=1,qP=2,Ib=4;function e9(t,e,n){return e!=null?(e?k0:0)|(e==="full"?qP:0):t&&t.whitespace=="pre"?k0|qP:n&~Ib}class h1{constructor(e,n,r,i,a,o){this.type=e,this.attrs=n,this.marks=r,this.solid=i,this.options=o,this.content=[],this.activeMarks=pr.none,this.match=a||(o&Ib?null:e.contentMatch)}findWrapping(e){if(!this.match){if(!this.type)return[];let n=this.type.contentMatch.fillBefore(_t.from(e));if(n)this.match=this.type.contentMatch.matchFragment(n);else{let r=this.type.contentMatch,i;return(i=r.findWrapping(e.type))?(this.match=r,i):null}}return this.match.findWrapping(e.type)}finish(e){if(!(this.options&k0)){let r=this.content[this.content.length-1],i;if(r&&r.isText&&(i=/[ \t\r\n\u000c]+$/.exec(r.text))){let a=r;r.text.length==i[0].length?this.content.pop():this.content[this.content.length-1]=a.withText(a.text.slice(0,a.text.length-i[0].length))}}let n=_t.from(this.content);return!e&&this.match&&(n=n.append(this.match.fillBefore(_t.empty,!0))),this.type?this.type.create(this.attrs,n,this.marks):n}inlineContext(e){return this.type?this.type.inlineContent:this.content.length?this.content[0].isInline:e.parentNode&&!eee.hasOwnProperty(e.parentNode.nodeName.toLowerCase())}}class t9{constructor(e,n,r){this.parser=e,this.options=n,this.isOpen=r,this.open=0,this.localPreserveWS=!1;let i=n.topNode,a,o=e9(null,n.preserveWhitespace,0)|(r?Ib:0);i?a=new h1(i.type,i.attrs,pr.none,!0,n.topMatch||i.type.contentMatch,o):r?a=new h1(null,null,pr.none,!0,null,o):a=new h1(e.schema.topNodeType,null,pr.none,!0,null,o),this.nodes=[a],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,a=i.options&qP?"full":this.localPreserveWS||(i.options&k0)>0,{schema:o}=this.parser;if(a==="full"||i.inlineContext(e)||/[^ \t\r\n\u000c]/.test(r)){if(a)if(a==="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(u)):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 a,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&&(a=!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)}a&&this.sync(l)&&this.open--}addAll(e,n,r,i){let a=r||0;for(let o=r?e.childNodes[r]:e.firstChild,l=i==null?null:e.childNodes[i];o!=l;o=o.nextSibling,++a)this.findAtPoint(e,a),this.addDOM(o,n);this.findAtPoint(e,a)}findPlace(e,n,r){let i,a;for(let o=this.open,l=0;o>=0;o--){let c=this.nodes[o],u=c.findWrapping(e);if(u&&(!i||i.length>u.length+l)&&(i=u,a=c,!u.length))break;if(c.solid){if(r)break;l+=2}}if(!i)return null;this.sync(a);for(let o=0;o(o.type?o.type.allowsMarkType(u.type):r9(u.type,e))?(c=u.addToSet(c),!1):!0),this.nodes.push(new h1(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|=k0)}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),a=-(r?r.depth+1:0)+(i?0:1),o=(l,c)=>{for(;l>=0;l--){let u=n[l];if(u==""){if(l==n.length-1||l==0)continue;for(;c>=a;c--)if(o(l-1,c))return!0;return!1}else{let d=c>0||c==0&&i?this.nodes[c].type:r&&c>=a?r.node(c-a).type:null;if(!d||d.name!=u&&!d.isInGroup(u))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 m8e(t){for(let e=t.firstChild,n=null;e;e=e.nextSibling){let r=e.nodeType==1?e.nodeName.toLowerCase():null;r&&tee.hasOwnProperty(r)&&n?(n.appendChild(e),e=n):r=="li"?n=e:r&&(n=null)}}function p8e(t,e){return(t.matches||t.msMatchesSelector||t.webkitMatchesSelector||t.mozMatchesSelector).call(t,e)}function n9(t){let e={};for(let n in t)e[n]=t[n];return e}function r9(t,e){let n=e.schema.nodes;for(let r in n){let i=n[r];if(!i.allowsMarkType(t))continue;let a=[],o=l=>{a.push(l);for(let c=0;c{if(a.length||o.marks.length){let l=0,c=0;for(;l=0;i--){let a=this.serializeMark(e.marks[i],e.isInline,n);a&&((a.contentDOM||a.dom).appendChild(r),r=a.dom)}return r}serializeMark(e,n,r={}){let i=this.marks[e.type.name];return i&&q1(kk(r),i(e,n),null,e.attrs)}static renderSpec(e,n,r=null,i){return q1(e,n,r,i)}static fromSchema(e){return e.cached.domSerializer||(e.cached.domSerializer=new Wf(this.nodesFromSchema(e),this.marksFromSchema(e)))}static nodesFromSchema(e){let n=i9(e.nodes);return n.text||(n.text=r=>r.text),n}static marksFromSchema(e){return i9(e.marks)}}function i9(t){let e={};for(let n in t){let r=t[n].spec.toDOM;r&&(e[n]=r)}return e}function kk(t){return t.document||window.document}const a9=new WeakMap;function g8e(t){let e=a9.get(t);return e===void 0&&a9.set(t,e=x8e(t)),e}function x8e(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),u=e[1],d=1;if(u&&typeof u=="object"&&u.nodeType==null&&!Array.isArray(u)){d=2;for(let f in u)if(u[f]!=null){let m=f.indexOf(" ");m>0?c.setAttributeNS(f.slice(0,m),f.slice(m+1),u[f]):f=="style"&&c.style?c.style.cssText=u[f]:c.setAttribute(f,u[f])}}for(let f=d;fd)throw new RangeError("Content hole must be the only child of its parent node");return{dom:c,contentDOM:c}}else{let{dom:g,contentDOM:b}=q1(t,m,n,r);if(c.appendChild(g),b){if(l)throw new RangeError("Multiple content holes");l=b}}}return{dom:c,contentDOM:l}}const nee=65535,ree=Math.pow(2,16);function b8e(t,e){return t+e*ree}function s9(t){return t&nee}function y8e(t){return(t-(t&nee))/ree}const iee=1,aee=2,K1=4,see=8;class KP{constructor(e,n,r){this.pos=e,this.delInfo=n,this.recover=r}get deleted(){return(this.delInfo&see)>0}get deletedBefore(){return(this.delInfo&(iee|K1))>0}get deletedAfter(){return(this.delInfo&(aee|K1))>0}get deletedAcross(){return(this.delInfo&K1)>0}}class Rs{constructor(e,n=!1){if(this.ranges=e,this.inverted=n,!e.length&&Rs.empty)return Rs.empty}recover(e){let n=0,r=s9(e);if(!this.inverted)for(let i=0;ie)break;let u=this.ranges[l+a],d=this.ranges[l+o],f=c+u;if(e<=f){let m=u?e==c?-1:e==f?1:n:n,g=c+i+(m<0?0:d);if(r)return g;let b=e==(n<0?c:f)?null:b8e(l/3,e-c),v=e==c?aee:e==f?iee:K1;return(n<0?e!=c:e!=f)&&(v|=see),new KP(g,v,b)}i+=d-u}return r?e+i:new KP(e+i,0,null)}touches(e,n){let r=0,i=s9(n),a=this.inverted?2:1,o=this.inverted?1:2;for(let l=0;le)break;let u=this.ranges[l+a],d=c+u;if(e<=d&&l==i*3)return!0;r+=this.ranges[l+o]-u}return!1}forEach(e){let n=this.inverted?2:1,r=this.inverted?1:2;for(let i=0,a=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 j0;return e.appendMappingInverted(this),e}map(e,n=1){if(this.mirror)return this._map(e,n,!0);for(let r=this.from;ra&&c!o.isAtom||!l.type.allowsMarkType(this.mark.type)?o:o.mark(this.mark.addToSet(o.marks)),i),n.openStart,n.openEnd);return xi.fromReplace(e,this.from,this.to,a)}invert(){return new Yo(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 xd(n.pos,r.pos,this.mark)}merge(e){return e instanceof xd&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new xd(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 xd(n.from,n.to,e.markFromJSON(n.mark))}}Pa.jsonID("addMark",xd);class Yo extends Pa{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 Rt(AO(n.content,i=>i.mark(this.mark.removeFromSet(i.marks)),e),n.openStart,n.openEnd);return xi.fromReplace(e,this.from,this.to,r)}invert(){return new xd(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 Yo(n.pos,r.pos,this.mark)}merge(e){return e instanceof Yo&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new Yo(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 Yo(n.from,n.to,e.markFromJSON(n.mark))}}Pa.jsonID("removeMark",Yo);class bd extends Pa{constructor(e,n){super(),this.pos=e,this.mark=n}apply(e){let n=e.nodeAt(this.pos);if(!n)return xi.fail("No node at mark step's position");let r=n.type.create(n.attrs,null,this.mark.addToSet(n.marks));return xi.fromReplace(e,this.pos,this.pos+1,new Rt(_t.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 Yi(n.pos,r.pos,i,a,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 Yi(n.from,n.to,n.gapFrom,n.gapTo,Rt.fromJSON(e,n.slice),n.insert,!!n.structure)}}Pa.jsonID("replaceAround",Yi);function XP(t,e,n){let r=t.resolve(e),i=n-e,a=r.depth;for(;i>0&&a>0&&r.indexAfter(a)==r.node(a).childCount;)a--,i--;if(i>0){let o=r.node(a).maybeChild(r.indexAfter(a));for(;i>0;){if(!o||o.isLeaf)return!0;o=o.firstChild,i--}}return!1}function v8e(t,e,n,r){let i=[],a=[],o,l;t.doc.nodesBetween(e,n,(c,u,d)=>{if(!c.isInline)return;let f=c.marks;if(!r.isInSet(f)&&d.type.allowsMarkType(r.type)){let m=Math.max(u,e),g=Math.min(u+c.nodeSize,n),b=r.addToSet(f);for(let v=0;vt.step(c)),a.forEach(c=>t.step(c))}function _8e(t,e,n,r){let i=[],a=0;t.doc.nodesBetween(e,n,(o,l)=>{if(!o.isInline)return;a++;let c=null;if(r instanceof IM){let u=o.marks,d;for(;d=r.isInSet(u);)(c||(c=[])).push(d),u=d.removeFromSet(u)}else r?r.isInSet(o.marks)&&(c=[r]):c=o.marks;if(c&&c.length){let u=Math.min(l+o.nodeSize,n);for(let d=0;dt.step(new Yo(o.from,o.to,o.style)))}function TO(t,e,n,r=n.contentMatch,i=!0){let a=t.doc.nodeAt(e),o=[],l=e+1;for(let c=0;c=0;c--)t.step(o[c])}function w8e(t,e,n){return(e==0||t.canReplace(e,t.childCount))&&(n==t.childCount||t.canReplace(0,n))}function Wg(t){let n=t.parent.content.cutByIndex(t.startIndex,t.endIndex);for(let r=t.depth,i=0,a=0;;--r){let o=t.$from.node(r),l=t.$from.index(r)+i,c=t.$to.indexAfter(r)-a;if(rn;b--)v||r.index(b)>0?(v=!0,d=_t.from(r.node(b).copy(d)),f++):c--;let m=_t.empty,g=0;for(let b=a,v=!1;b>n;b--)v||i.after(b+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=_t.from(n[o].type.create(n[o].attrs,r))}let i=e.start,a=e.end;t.step(new Yi(i,a,i,a,new Rt(r,0,0),n.length,!0))}function A8e(t,e,n,r,i){if(!r.isTextblock)throw new RangeError("Type given to setBlockType should be a textblock");let a=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)&&T8e(t.doc,t.mapping.slice(a).map(l),r)){let u=null;if(r.schema.linebreakReplacement){let g=r.whitespace=="pre",b=!!r.contentMatch.matchType(r.schema.linebreakReplacement);g&&!b?u=!1:!g&&b&&(u=!0)}u===!1&&lee(t,o,l,a),TO(t,t.mapping.slice(a).map(l,1),r,void 0,u===null);let d=t.mapping.slice(a),f=d.map(l,1),m=d.map(l+o.nodeSize,1);return t.step(new Yi(f,m,f+1,m-1,new Rt(_t.from(r.create(c,null,o.marks)),0,0),1,!0)),u===!0&&oee(t,o,l,a),!1}})}function oee(t,e,n,r){e.forEach((i,a)=>{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+a+o.index);t.replaceWith(c,c+1,e.type.schema.linebreakReplacement.create())}}})}function lee(t,e,n,r){e.forEach((i,a)=>{if(i.type==i.type.schema.linebreakReplacement){let o=t.mapping.slice(r).map(n+1+a);t.replaceWith(o,o+1,e.type.schema.text(` diff --git a/static/index.html b/static/index.html index 3afa13723..551cb9754 100644 --- a/static/index.html +++ b/static/index.html @@ -23,7 +23,7 @@ - +