From 5cd366ceac4761fdcd7363302fdb439a118a6040 Mon Sep 17 00:00:00 2001 From: maziggy Date: Tue, 16 Dec 2025 10:26:30 +0100 Subject: [PATCH] Fix browser tab crash on print completion (debounced invalidations) When a print completes, multiple WebSocket messages are sent rapidly (print_complete, archive_updated, etc.). Each was immediately invalidating the archives query, causing a cascade of rapid re-renders that crashed the browser tab. Added debounced query invalidation to useWebSocket.ts: - Multiple invalidation requests within 100ms are coalesced into one - Uses requestAnimationFrame to avoid blocking the main thread - Properly cleans up timeouts on unmount --- frontend/src/hooks/useWebSocket.ts | 49 ++++++++++++++---- static/._.DS_Store | Bin 4096 -> 0 bytes .../{index-CFaicAOR.js => index-AT42oZVR.js} | 4 +- static/index.html | 2 +- 4 files changed, 43 insertions(+), 12 deletions(-) delete mode 100644 static/._.DS_Store rename static/assets/{index-CFaicAOR.js => index-AT42oZVR.js} (98%) diff --git a/frontend/src/hooks/useWebSocket.ts b/frontend/src/hooks/useWebSocket.ts index c46867672..4094a77c0 100644 --- a/frontend/src/hooks/useWebSocket.ts +++ b/frontend/src/hooks/useWebSocket.ts @@ -13,6 +13,10 @@ export function useWebSocket() { const queryClient = useQueryClient(); const [isConnected, setIsConnected] = useState(false); + // Debounce invalidations to prevent rapid re-render cascades + const pendingInvalidations = useRef>(new Set()); + const invalidationTimeoutRef = useRef(null); + const connect = useCallback(() => { if (wsRef.current?.readyState === WebSocket.OPEN) { return; @@ -68,6 +72,30 @@ export function useWebSocket() { wsRef.current = ws; }, []); + // Debounced invalidation helper - coalesces multiple rapid invalidations + const debouncedInvalidate = useCallback((queryKey: string) => { + pendingInvalidations.current.add(queryKey); + + // Clear existing timeout + if (invalidationTimeoutRef.current) { + clearTimeout(invalidationTimeoutRef.current); + } + + // Schedule invalidation after a short delay (100ms) + invalidationTimeoutRef.current = window.setTimeout(() => { + const keys = Array.from(pendingInvalidations.current); + pendingInvalidations.current.clear(); + invalidationTimeoutRef.current = null; + + // Use requestAnimationFrame to avoid blocking the main thread + requestAnimationFrame(() => { + keys.forEach((key) => { + queryClient.invalidateQueries({ queryKey: [key] }); + }); + }); + }, 100); + }, [queryClient]); + const handleMessage = useCallback((message: WebSocketMessage) => { switch (message.type) { case 'printer_status': @@ -91,27 +119,27 @@ export function useWebSocket() { break; case 'print_complete': - // Invalidate archives to refresh the list - queryClient.invalidateQueries({ queryKey: ['archives'] }); - queryClient.invalidateQueries({ queryKey: ['archiveStats'] }); + // Invalidate archives to refresh the list (debounced) + debouncedInvalidate('archives'); + debouncedInvalidate('archiveStats'); break; case 'archive_created': - // Invalidate archives to show new archive - queryClient.invalidateQueries({ queryKey: ['archives'] }); - queryClient.invalidateQueries({ queryKey: ['archiveStats'] }); + // Invalidate archives to show new archive (debounced) + debouncedInvalidate('archives'); + debouncedInvalidate('archiveStats'); break; case 'archive_updated': - // Invalidate archives to refresh (e.g., timelapse attached) - queryClient.invalidateQueries({ queryKey: ['archives'] }); + // Invalidate archives to refresh (debounced) + debouncedInvalidate('archives'); break; case 'pong': // Keepalive response, ignore break; } - }, [queryClient]); + }, [queryClient, debouncedInvalidate]); useEffect(() => { connect(); @@ -120,6 +148,9 @@ export function useWebSocket() { if (reconnectTimeoutRef.current) { clearTimeout(reconnectTimeoutRef.current); } + if (invalidationTimeoutRef.current) { + clearTimeout(invalidationTimeoutRef.current); + } if (wsRef.current) { wsRef.current.close(); } diff --git a/static/._.DS_Store b/static/._.DS_Store deleted file mode 100644 index 28c42fb20a1f27e695fb64323501fc6476578b13..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 4096 zcmZQz6=P>$Vqox1Ojhs@R)|o50+1L3ClDJkFz{^v(m+1nBL)UWIhYCu0iY;W;207T z1d#ygV5q>VXjE`C1V%$(Gz3ONU^E0qLtr!nMnhmU1V%$(Gz3ONU^E1%90H6$^FSC3 zT&&qi.z>T)continue;if(Wi.z>T){const O=Wi.z-qi.z,q=(Wi.z-T)/O;Wi.lerp(qi,q)}else if(qi.z>T){const O=qi.z-Wi.z,q=(qi.z-T)/O;qi.lerp(Wi,q)}Wi.applyMatrix4(x),qi.applyMatrix4(x),Wi.multiplyScalar(1/Wi.w),qi.multiplyScalar(1/qi.w),Wi.x*=v.x/2,Wi.y*=v.y/2,qi.x*=v.x/2,qi.y*=v.y/2,Ki.start.copy(Wi),Ki.start.z=0,Ki.end.copy(qi),Ki.end.z=0;const I=Ki.closestPointToPointParameter(NN,!0);Ki.at(I,TV);const C=OZ.lerp(Wi.z,qi.z,I),D=C>=-1&&C<=1,F=NN.distanceTo(TV)<.5*uh;if(D&&F){Ki.start.fromBufferAttribute(M,k),Ki.end.fromBufferAttribute(S,k),Ki.start.applyMatrix4(y),Ki.end.applyMatrix4(y);const O=new De,q=new De;Zo.distanceSqToSegment(Ki.start,Ki.end,q,O),m.push({point:q,pointOnLine:O,distance:Zo.origin.distanceTo(q),object:f,face:null,faceIndex:k,uv:null,uv1:null})}}})(this,i,n)))}}class sUe extends WM{constructor(e,n,r,i,a=4473924,s=8947848){a=new $t(a),s=new $t(s);const o=Math.round(e/n);r=Math.round(r/i)*i/2;const c=[],u=[];let d=0;for(let g=-1*(e=o*n/2);g<=e;g+=n){c.push(g,0,-1*r,g,0,r);const m=g===0?a:s;m.toArray(u,d),d+=3,m.toArray(u,d),d+=3,m.toArray(u,d),d+=3,m.toArray(u,d),d+=3}for(let g=-1*r;g<=r;g+=i){c.push(-1*e,0,g,e,0,g);const m=g===0?a:s;m.toArray(u,d),d+=3,m.toArray(u,d),d+=3,m.toArray(u,d),d+=3,m.toArray(u,d),d+=3}const f=new ga;f.setAttribute("position",new Br(c,3)),f.setAttribute("color",new Br(u,3)),super(f,new Xb({vertexColors:!0,toneMapped:!1}))}}function oUe(t,e,n,r){const i=(function(s,o,c){s*=.5,o*=.5,c*=.5;const u=new ga,d=[];return d.push(-s,-o,-c,-s,o,-c,-s,o,-c,s,o,-c,s,o,-c,s,-o,-c,s,-o,-c,-s,-o,-c,-s,-o,c,-s,o,c,-s,o,c,s,o,c,s,o,c,s,-o,c,s,-o,c,-s,-o,c,-s,-o,-c,-s,-o,c,-s,o,-c,-s,o,c,s,o,-c,s,o,c,s,-o,-c,s,-o,c),u.setAttribute("position",new Br(d,3)),u})(t,e,n),a=new WM(i,new IFe({color:new $t(r),dashSize:3,gapSize:1}));return a.computeLineDistances(),a}var Zx=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&&(o.update(1e3*s/(d-a),100),a=d,s=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}};Zx.Panel=function(t,e,n){var r=1/0,i=0,a=Math.round,s=a(window.devicePixelRatio||1),o=80*s,c=48*s,u=3*s,d=2*s,f=3*s,g=15*s,m=74*s,x=30*s,v=document.createElement("canvas");v.width=o,v.height=c,v.style.cssText="width:80px;height:48px";var y=v.getContext("2d");return y.font="bold "+9*s+"px Helvetica,Arial,sans-serif",y.textBaseline="top",y.fillStyle=n,y.fillRect(0,0,o,c),y.fillStyle=e,y.fillText(t,u,d),y.fillRect(f,g,m,x),y.fillStyle=n,y.globalAlpha=.9,y.fillRect(f,g,m,x),{dom:v,update:function(b,M){r=Math.min(r,b),i=Math.max(i,b),y.fillStyle=n,y.globalAlpha=1,y.fillRect(0,0,o,g),y.fillStyle=e,y.fillText(a(b)+" "+t+" ("+a(r)+"-"+a(i)+")",u,d),y.drawImage(v,f+s,g,m-s,x,f,g,m-s,x),y.fillRect(f+m-s,g,s,x),y.fillStyle=n,y.globalAlpha=.9,y.fillRect(f+m-s,g,s,a((1-b/M)*x))}}};var lUe=Zx;class NV{constructor(e,n){this.openFolders=[],this.watchedObject=e,this.options=n,this.gui=new Uw,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 Uw,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 cUe extends ga{constructor(e=[new De],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 De,s=new De,o=new Zt,c=[],u=[],d=[],f=[];function g(m){const[x,v,y]=(function(b){const M=e[b],S=new De,A=new De,T=new De,k=new De;S.copy(M).sub(e[b-1]||M).normalize().add((e[b+1]||M).clone().sub(M).normalize()).normalize();let N=Number.MAX_VALUE;const I=Math.abs(S.x),C=Math.abs(S.y),D=Math.abs(S.z);return I<=N&&(N=I,A.set(1,0,0)),C<=N&&(N=C,A.set(0,1,0)),D<=N&&A.set(0,0,1),k.crossVectors(S,A).normalize(),A.crossVectors(S,k),T.crossVectors(S,A),[M,A,T]})(m);for(let b=0;b<=i;b++){const M=b/i*Math.PI*2,S=Math.sin(M),A=-Math.cos(M);s.x=A*v.x+S*y.x,s.y=A*v.y+S*y.y,s.z=A*v.z+S*y.z,s.normalize(),u.push(s.x,s.y,s.z),a.x=x.x+n*s.x*.5,a.y=x.y+n*s.y*.5,a.z=x.z+r*s.z*.5,c.push(a.x,a.y,a.z)}}(function(){for(let m=0;mthis.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 VFe(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 BFe(13421772,.3*Math.PI),n=new zFe(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 Ux;return n.name=e,n.quaternion.setFromEuler(new qb(-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=Qx.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 g of d.commands)if(g.gcode!="g20"){if(g.gcode.startsWith("t")){this.doRenderExtrusion(f,e),f.extrusion=[];const m=g;this.state.t=m.toolIndex}else if(["g0","g00","g1","g01","g2","g02","g3","g03"].indexOf(g.gcode)>-1){const m=g,x={x:(n=m.params.x)!==null&&n!==void 0?n:this.state.x,y:(r=m.params.y)!==null&&r!==void 0?r:this.state.y,z:(i=m.params.z)!==null&&i!==void 0?i:this.state.z,r:(a=m.params.r)!==null&&a!==void 0?a:this.state.r,e:(s=m.params.e)!==null&&s!==void 0?s:this.state.e,i:(o=m.params.i)!==null&&o!==void 0?o:this.state.i,j:(c=m.params.j)!==null&&c!==void 0?c:this.state.j,t:this.state.t};if(e>=this.minLayerIndex){const v=((u=m.params.e)!==null&&u!==void 0?u:0)>0||this.nonTravelmoves.indexOf(g.gcode)>-1;(x.x!=this.state.x||x.y!=this.state.y||x.z!=this.state.z)&&(v&&this.renderExtrusion||!v&&this.renderTravel)&&(g.gcode=="g2"||g.gcode=="g3"||g.gcode=="g02"||g.gcode=="g03"?this.addArcSegment(f,this.state,x,v,g.gcode=="g2"||g.gcode=="g02"):this.addLineSegment(f,this.state,x,v))}this.state.x=x.x,this.state.y=x.y,this.state.z=x.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 s=.1+.7*n/this.layers.length;a.getHSL(PN),a=new $t().setHSL(PN.h,PN.s,s)}if(n==this.layers.length-1){const s=(r=this._topLayerColor)!==null&&r!==void 0?r:a,o=(i=this._lastSegmentColor)!==null&&i!==void 0?i:s,c=e.extrusion.splice(-3),u=e.extrusion.splice(-3);this.renderTubes?(this.addTubeLine(e.extrusion,s.getHex(),e.height),this.addTubeLine([...u,...c],o.getHex(),e.height)):(this.addLine(e.extrusion,s.getHex()),this.addLine([...u,...c],o.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 sUe(this.buildVolume.x,10,this.buildVolume.y,10));const e=oUe(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 zw(this.minLayerThreshold)}resetState(){var e;this.startLayer=1,this.endLayer=1/0,this.singleLayerMode=!1,this.beyondFirstMove=!1,this.state=Qx.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 s=i?e.extrusion:e.travel,o=n.x,c=n.y,u=n.z,d=r.x,f=r.y,g=r.z;let m=r.r,x=r.i,v=r.j;if(m){const W=d-o,K=f-c,G=Math.sqrt(Math.pow(W/2,2)+Math.pow(K/2,2));m=Math.max(m,G);const ee=Math.pow(W,2)+Math.pow(K,2),Z=Math.pow(m,2)-ee/4;let Q=Math.sqrt(Z/ee);(a&&m<0||!a&&m>0)&&(Q=-Q),x=W/2+K*Q,v=K/2-W*Q}const y=o==d&&c==f,b=o+x,M=c+v,S=Math.sqrt(x*x+v*v),A=Math.atan2(-v,-x),T=Math.atan2(f-M,d-b);let k;y?k=2*Math.PI:(k=a?A-T:T-A,k<0&&(k+=2*Math.PI));let N=S*k/1.8;this.inches&&(N*=25),N<1&&(N=1);let I=k/N;I*=a?-1:1;const C=[];C.push({x:o,y:c,z:u});const D=(u-g)/N;let F=o,O=c,q=u,R=A;for(let W=0;W0)return void this.addThickLine(e,n);const i=new ga;i.setAttribute("position",new Br(e,3)),this.disposables.push(i);const a=new Xb({color:n});this.disposables.push(a);const s=new WM(i,a);(r=this.group)===null||r===void 0||r.add(s)}addTubeLine(e,n,r=.2){let i=[];const a=[];for(let s=0;s{var o;const c=new cUe(s,this.extrusionWidth,this.lineHeight||r,4);(o=this._geometries)[n]||(o[n]=[]),this._geometries[n].push(c)}))}addThickLine(e,n){var r;if(!e.length||!this.lineWidth)return;const i=new rQ;this.disposables.push(i);const a=new nQ({color:n,linewidth:this.lineWidth/(1e3*window.devicePixelRatio)});this.disposables.push(a),i.setPositions(e);const s=new aUe(i,a);(r=this.group)===null||r===void 0||r.add(s)}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=>TN(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 LFe({color:e,wireframe:this._wireframe});this.disposables.push(i);const a=r.reduce(((o,c)=>3*c.attributes.position.count+o),0),s=new DFe(r.length,a,void 0,i);return this.disposables.push(s),(n=this.group)===null||n===void 0||n.add(s),s}_readFromStream(e){var n,r;return TN(this,void 0,void 0,(function*(){const i=e.getReader();let a,s="",o=0;do{console.debug("reading from stream"),a=yield i.read(),o+=(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(s+f),s=u.slice(d)}while(!a.done);var c;console.debug("read from stream",o)}))}initGui(){typeof this.devMode=="boolean"&&this.devMode===!0?this.devGui=new NV(this):typeof this.devMode=="object"&&(this.devGui=new NV(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())}}lm.defaultExtrusionColor=new $t("hotpink");const uUe=function(t){return new lm(t)};function dUe({gcodeUrl:t,buildVolume:e={x:256,y:256,z:256},className:n=""}){const r=E.useRef(null),i=E.useRef(null),[a,s]=E.useState(!0),[o,c]=E.useState(null),[u,d]=E.useState(!1),[f,g]=E.useState(0),[m,x]=E.useState(0);E.useEffect(()=>{if(!r.current)return;const b=r.current,M=uUe({canvas:b,buildVolume:e,backgroundColor:1710618,travelColor:4473924,extrusionColor:44610,topLayerColor:65370,lastSegmentColor:16777215,lineWidth:2,renderTravel:!1,renderExtrusion:!0});i.current=M,s(!0),c(null),d(!1),fetch(t).then(async A=>{if(!A.ok)throw A.status===404&&(await A.json().catch(()=>({}))).detail?.includes("sliced")?(d(!0),new Error("not_sliced")):new Error("Failed to load G-code");return A.text()}).then(A=>{M.processGCode(A);const T=M.layers?.length||0;x(T),g(T),M.render(),s(!1)}).catch(A=>{c(A.message),s(!1)});const S=()=>{if(b.parentElement){const A=b.parentElement.getBoundingClientRect();b.width=A.width,b.height=A.height,M.resize()}};return S(),window.addEventListener("resize",S),()=>{window.removeEventListener("resize",S),M.dispose()}},[t,e]);const v=b=>{if(!i.current)return;const M=Math.max(1,Math.min(b,m));g(M),i.current.render()},y=b=>{v(parseInt(b.target.value,10))};return l.jsxs("div",{className:`relative flex flex-col h-full ${n}`,children:[l.jsxs("div",{className:"flex-1 relative bg-bambu-dark rounded-lg overflow-hidden",children:[l.jsx("canvas",{ref:r,className:"w-full h-full"}),a&&l.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-bambu-dark/80",children:l.jsxs("div",{className:"text-center",children:[l.jsx(At,{className:"w-8 h-8 animate-spin text-bambu-green mx-auto mb-2"}),l.jsx("p",{className:"text-bambu-gray text-sm",children:"Loading G-code..."})]})}),u&&l.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-bambu-dark/80",children:l.jsxs("div",{className:"text-center max-w-sm px-4",children:[l.jsx(ale,{className:"w-12 h-12 text-bambu-gray mx-auto mb-3"}),l.jsx("p",{className:"text-white font-medium mb-2",children:"G-code not available"}),l.jsx("p",{className:"text-bambu-gray text-sm",children:"This file hasn't been sliced yet. G-code preview is only available after slicing the model in Bambu Studio or Orca Slicer."})]})}),o&&!u&&l.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-bambu-dark/80",children:l.jsx("div",{className:"text-center text-red-400",children:l.jsx("p",{className:"text-sm",children:o})})})]}),!a&&!o&&!u&&m>0&&l.jsx("div",{className:"mt-4 px-2",children:l.jsxs("div",{className:"flex items-center gap-3",children:[l.jsx($h,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}),l.jsx("button",{onClick:()=>v(f-1),disabled:f<=1,className:"p-1 rounded hover:bg-bambu-dark-tertiary disabled:opacity-30 disabled:cursor-not-allowed",children:l.jsx(Bh,{className:"w-4 h-4"})}),l.jsx("input",{type:"range",min:1,max:m,value:f,onChange:y,className:"flex-1 h-2 bg-bambu-dark-tertiary rounded-lg appearance-none cursor-pointer accent-bambu-green"}),l.jsx("button",{onClick:()=>v(f+1),disabled:f>=m,className:"p-1 rounded hover:bg-bambu-dark-tertiary disabled:opacity-30 disabled:cursor-not-allowed",children:l.jsx(df,{className:"w-4 h-4"})}),l.jsxs("span",{className:"text-sm text-bambu-gray min-w-[80px] text-right",children:[f," / ",m]})]})})]})}function hUe({archiveId:t,title:e,onClose:n}){const[r,i]=E.useState(null),[a,s]=E.useState(null),[o,c]=E.useState(!0);E.useEffect(()=>{const d=f=>{f.key==="Escape"&&n()};return window.addEventListener("keydown",d),()=>window.removeEventListener("keydown",d)},[n]),E.useEffect(()=>{ke.getArchiveCapabilities(t).then(d=>{s(d),d.has_model?i("3d"):d.has_gcode&&i("gcode"),c(!1)}).catch(()=>{s({has_model:!0,has_gcode:!1,build_volume:{x:256,y:256,z:256}}),i("3d"),c(!1)})},[t]);const u=()=>{const d=e||"model",f=`${window.location.origin}${ke.getArchiveForSlicer(t,d)}`;window.location.href=`bambustudioopen://${encodeURIComponent(f)}`};return l.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-8",onClick:n,children:l.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:[l.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[l.jsx("h2",{className:"text-lg font-semibold text-white truncate flex-1 mr-4",children:e}),l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsxs(Le,{variant:"secondary",size:"sm",onClick:u,children:[l.jsx(As,{className:"w-4 h-4"}),"Open in Slicer"]}),l.jsx(Le,{variant:"ghost",size:"sm",onClick:n,children:l.jsx(Wt,{className:"w-5 h-5"})})]})]}),a&&l.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary",children:[l.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:[l.jsx(fm,{className:"w-4 h-4"}),"3D Model",!a.has_model&&l.jsx("span",{className:"text-xs",children:"(not available)"})]}),l.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:[l.jsx(Doe,{className:"w-4 h-4"}),"G-code Preview",!a.has_gcode&&l.jsx("span",{className:"text-xs",children:"(not sliced)"})]})]}),l.jsx("div",{className:"flex-1 overflow-hidden p-4",children:o?l.jsx("div",{className:"w-full h-full flex items-center justify-center",children:l.jsx(At,{className:"w-8 h-8 animate-spin text-bambu-green"})}):r==="3d"&&a?l.jsx(oje,{url:ke.getArchiveDownload(t),buildVolume:a.build_volume,className:"w-full h-full"}):r==="gcode"&&a?l.jsx(dUe,{gcodeUrl:ke.getArchiveGcode(t),buildVolume:a.build_volume,className:"w-full h-full"}):l.jsx("div",{className:"w-full h-full flex items-center justify-center text-bambu-gray",children:"No preview available for this file"})})]})})}function fUe({archiveId:t,archiveName:e,onClose:n,onSuccess:r}){const[i,a]=E.useState(null);E.useEffect(()=>{const d=f=>{f.key==="Escape"&&n()};return window.addEventListener("keydown",d),()=>window.removeEventListener("keydown",d)},[n]);const{data:s,isLoading:o}=vt({queryKey:["printers"],queryFn:ke.getPrinters}),c=wt({mutationFn:()=>{if(!i)throw new Error("No printer selected");return ke.reprintArchive(t,i)},onSuccess:()=>{r(),n()}}),u=s?.filter(d=>d.is_active)||[];return l.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-8",children:l.jsx(Nt,{className:"w-full max-w-md",children:l.jsxs(Rt,{children:[l.jsxs("div",{className:"flex items-center justify-between mb-4",children:[l.jsx("h2",{className:"text-lg font-semibold text-white",children:"Re-print"}),l.jsx(Le,{variant:"ghost",size:"sm",onClick:n,children:l.jsx(Wt,{className:"w-5 h-5"})})]}),l.jsxs("p",{className:"text-sm text-bambu-gray mb-4",children:["Send ",l.jsx("span",{className:"text-white",children:e})," to a printer"]}),o?l.jsx("div",{className:"flex justify-center py-8",children:l.jsx(At,{className:"w-6 h-6 text-bambu-green animate-spin"})}):u.length===0?l.jsx("div",{className:"text-center py-8 text-bambu-gray",children:"No active printers available"}):l.jsx("div",{className:"space-y-2 mb-6",children:u.map(d=>l.jsxs("button",{onClick:()=>a(d.id),className:`w-full flex items-center gap-3 p-3 rounded-lg border transition-colors ${i===d.id?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark hover:border-bambu-gray"}`,children:[l.jsx("div",{className:`p-2 rounded-lg ${i===d.id?"bg-bambu-green/20":"bg-bambu-dark-tertiary"}`,children:l.jsx(Ts,{className:`w-5 h-5 ${i===d.id?"text-bambu-green":"text-bambu-gray"}`})}),l.jsxs("div",{className:"text-left",children:[l.jsx("p",{className:"text-white font-medium",children:d.name}),l.jsxs("p",{className:"text-xs text-bambu-gray",children:[d.model||"Unknown model"," • ",d.ip_address]})]})]},d.id))}),c.isError&&l.jsx("div",{className:"mb-4 p-3 bg-red-500/20 border border-red-500/50 rounded-lg text-sm text-red-400",children:c.error.message||"Failed to start print"}),l.jsxs("div",{className:"flex gap-3",children:[l.jsx(Le,{variant:"secondary",onClick:n,className:"flex-1",children:"Cancel"}),l.jsx(Le,{onClick:()=>c.mutate(),disabled:!i||c.isPending,className:"flex-1",children:c.isPending?l.jsxs(l.Fragment,{children:[l.jsx(At,{className:"w-4 h-4 animate-spin"}),"Sending..."]}):l.jsxs(l.Fragment,{children:[l.jsx(Ts,{className:"w-4 h-4"}),"Print"]})})]})]})})})}function pUe({onClose:t,initialFiles:e}){const n=En(),{showToast:r}=ai(),i=E.useRef(null),[a,s]=E.useState(()=>e?.filter(N=>N.name.endsWith(".3mf")).map(N=>({file:N,status:"pending"}))||[]),[o,c]=E.useState(!1),[u,d]=E.useState(),[f,g]=E.useState(null);E.useEffect(()=>{const N=I=>{I.key==="Escape"&&t()};return window.addEventListener("keydown",N),()=>window.removeEventListener("keydown",N)},[t]);const{data:m}=vt({queryKey:["printers"],queryFn:ke.getPrinters}),x=wt({mutationFn:N=>ke.uploadArchivesBulk(N,u),onSuccess:N=>{g(N),n.invalidateQueries({queryKey:["archives"]}),n.invalidateQueries({queryKey:["archiveStats"]}),s(I=>I.map(C=>{const D=N.results.find(O=>O.filename===C.file.name),F=N.errors.find(O=>O.filename===C.file.name);return D?{...C,status:"success",archiveId:D.id}:F?{...C,status:"error",error:F.error}:C})),N.failed===0?r(`${N.uploaded} file${N.uploaded!==1?"s":""} uploaded`):N.uploaded===0?r(`Failed to upload ${N.failed} file${N.failed!==1?"s":""}`,"error"):r(`${N.uploaded} uploaded, ${N.failed} failed`,"warning")},onError:()=>{s(N=>N.map(I=>({...I,status:"error",error:"Upload failed"}))),r("Upload failed","error")}}),v=E.useCallback(N=>{N.preventDefault(),c(!0)},[]),y=E.useCallback(N=>{N.preventDefault(),c(!1)},[]),b=E.useCallback(N=>{N.preventDefault(),c(!1);const I=Array.from(N.dataTransfer.files).filter(C=>C.name.endsWith(".3mf"));I.length>0&&s(C=>[...C,...I.map(D=>({file:D,status:"pending"}))])},[]),M=E.useCallback(N=>{const I=Array.from(N.target.files||[]).filter(C=>C.name.endsWith(".3mf"));I.length>0&&s(C=>[...C,...I.map(D=>({file:D,status:"pending"}))]),i.current&&(i.current.value="")},[]),S=E.useCallback(N=>{s(I=>I.filter((C,D)=>D!==N))},[]),A=()=>{if(a.length===0)return;const N=a.filter(I=>I.status==="pending");N.length!==0&&(s(I=>I.map(C=>C.status==="pending"?{...C,status:"uploading"}:C)),x.mutate(N.map(I=>I.file)))},T=a.filter(N=>N.status==="pending").length,k=x.isPending;return l.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:l.jsx(Nt,{className:"w-full max-w-2xl max-h-[90vh] flex flex-col",children:l.jsxs(Rt,{className:"p-0 flex flex-col h-full",children:[l.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[l.jsx("h2",{className:"text-xl font-semibold text-white",children:"Upload 3MF Files"}),l.jsx("button",{onClick:t,className:"text-bambu-gray hover:text-white transition-colors",children:l.jsx(Wt,{className:"w-5 h-5"})})]}),l.jsx("div",{className:"p-4",children:l.jsxs("div",{className:`border-2 border-dashed rounded-lg p-8 text-center transition-colors ${o?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary hover:border-bambu-gray"}`,onDragOver:v,onDragLeave:y,onDrop:b,children:[l.jsx(vs,{className:"w-12 h-12 mx-auto mb-4 text-bambu-gray"}),l.jsx("p",{className:"text-white mb-2",children:"Drag & drop .3mf files here"}),l.jsx("p",{className:"text-bambu-gray text-sm mb-4",children:"or"}),l.jsx(Le,{variant:"secondary",onClick:()=>i.current?.click(),disabled:k,children:"Browse Files"}),l.jsx("input",{ref:i,type:"file",accept:".3mf",multiple:!0,className:"hidden",onChange:M})]})}),l.jsxs("div",{className:"px-4 pb-4",children:[l.jsx("label",{className:"block text-sm text-bambu-gray mb-2",children:"Associate with printer (optional)"}),l.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:N=>d(N.target.value?Number(N.target.value):void 0),disabled:k,children:[l.jsx("option",{value:"",children:"No printer"}),m?.map(N=>l.jsx("option",{value:N.id,children:N.name},N.id))]})]}),a.length>0&&l.jsx("div",{className:"px-4 pb-4 max-h-60 overflow-y-auto",children:l.jsx("div",{className:"space-y-2",children:a.map((N,I)=>l.jsxs("div",{className:"flex items-center gap-3 p-3 bg-bambu-dark rounded-lg",children:[l.jsx(oG,{className:"w-5 h-5 text-bambu-gray flex-shrink-0"}),l.jsx("span",{className:"flex-1 text-white text-sm truncate",children:N.file.name}),l.jsxs("span",{className:"text-xs text-bambu-gray",children:[(N.file.size/(1024*1024)).toFixed(1)," MB"]}),N.status==="pending"&&l.jsx("button",{onClick:()=>S(I),className:"text-bambu-gray hover:text-red-400 transition-colors",disabled:k,children:l.jsx(Wt,{className:"w-4 h-4"})}),N.status==="uploading"&&l.jsx(At,{className:"w-4 h-4 text-bambu-green animate-spin"}),N.status==="success"&&l.jsx(fi,{className:"w-4 h-4 text-bambu-green"}),N.status==="error"&&l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("span",{className:"text-xs text-red-400",children:N.error}),l.jsx(lo,{className:"w-4 h-4 text-red-400"})]})]},`${N.file.name}-${I}`))})}),f&&l.jsx("div",{className:"px-4 pb-4",children:l.jsx("div",{className:"p-3 bg-bambu-dark rounded-lg",children:l.jsxs("p",{className:"text-sm text-white",children:[l.jsx("span",{className:"text-bambu-green",children:f.uploaded})," uploaded",f.failed>0&&l.jsxs(l.Fragment,{children:[", ",l.jsx("span",{className:"text-red-400",children:f.failed})," failed"]})]})})}),l.jsxs("div",{className:"flex gap-3 p-4 border-t border-bambu-dark-tertiary",children:[l.jsx(Le,{variant:"secondary",onClick:t,className:"flex-1",children:f?"Close":"Cancel"}),!f&&l.jsx(Le,{onClick:A,disabled:T===0||k,className:"flex-1",children:k?l.jsxs(l.Fragment,{children:[l.jsx(At,{className:"w-4 h-4 animate-spin"}),"Uploading..."]}):l.jsxs(l.Fragment,{children:[l.jsx(vs,{className:"w-4 h-4"}),"Upload ",T>0&&`(${T})`]})})]})]})})})}const mUe=["Adhesion failure","Spaghetti / Detached","Layer shift","Clogged nozzle","Filament runout","Warping","Stringing","Under-extrusion","Power failure","User cancelled","Other"],gUe=[{value:"completed",label:"Completed"},{value:"failed",label:"Failed"},{value:"aborted",label:"Cancelled"},{value:"printing",label:"Printing"}];function xUe({archive:t,onClose:e,existingTags:n=[]}){E.useEffect(()=>{const X=te=>{te.key==="Escape"&&e()};return window.addEventListener("keydown",X),()=>window.removeEventListener("keydown",X)},[e]);const r=En(),[i,a]=E.useState(t.print_name||""),[s,o]=E.useState(t.printer_id),[c,u]=E.useState(t.project_id??null),[d,f]=E.useState(t.notes||""),[g,m]=E.useState(t.tags||""),[x,v]=E.useState(t.failure_reason||""),[y,b]=E.useState(t.status),[M,S]=E.useState(t.photos||[]),[A,T]=E.useState(!1),[k,N]=E.useState(!1),I=E.useRef(null),C=E.useRef(null),D=E.useRef(null),{data:F}=vt({queryKey:["printers"],queryFn:ke.getPrinters}),{data:O}=vt({queryKey:["projects"],queryFn:()=>ke.getProjects()}),{data:q}=vt({queryKey:["archives"],queryFn:()=>ke.getArchives(void 0,1e3,0),enabled:n.length===0}),R=n.length>0?n:[...new Set(q?.flatMap(X=>X.tags?.split(",").map(te=>te.trim())||[]).filter(Boolean)||[])].sort(),W=g.split(",").map(X=>X.trim()).filter(Boolean),K=R.filter(X=>!W.includes(X)),G=X=>{if(!W.includes(X)){const te=[...W,X].join(", ");m(te)}D.current!==null&&clearTimeout(D.current),I.current?.focus()},ee=X=>{const te=W.filter(fe=>fe!==X).join(", ");m(te)},Z=wt({mutationFn:X=>ke.updateArchive(t.id,X),onSuccess:()=>{r.invalidateQueries({queryKey:["archives"]}),r.invalidateQueries({queryKey:["projects"]}),e()}}),Q=async X=>{const te=X.target.files?.[0];if(te){T(!0);try{const fe=await ke.uploadArchivePhoto(t.id,te);S(fe.photos),r.invalidateQueries({queryKey:["archives"]})}catch(fe){console.error("Failed to upload photo:",fe)}finally{T(!1),C.current&&(C.current.value="")}}},U=async X=>{try{const te=await ke.deleteArchivePhoto(t.id,X);S(te.photos||[]),r.invalidateQueries({queryKey:["archives"]})}catch(te){console.error("Failed to delete photo:",te)}},$=X=>{X.preventDefault();const te={print_name:i||void 0,printer_id:s,project_id:c,notes:d||void 0,tags:g||void 0};y!==t.status&&(te.status=y),y==="failed"||y==="aborted"?te.failure_reason=x||void 0:(t.status==="failed"||t.status==="aborted")&&(te.failure_reason=null),Z.mutate(te)};return l.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:e,children:l.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:X=>X.stopPropagation(),children:[l.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[l.jsx("h2",{className:"text-lg font-semibold text-white",children:"Edit Archive"}),l.jsx("button",{onClick:e,className:"text-bambu-gray hover:text-white transition-colors",children:l.jsx(Wt,{className:"w-5 h-5"})})]}),l.jsxs("form",{onSubmit:$,className:"p-6 space-y-4 overflow-y-auto flex-1",children:[l.jsxs("div",{children:[l.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Name"}),l.jsx("input",{type:"text",value:i,onChange:X=>a(X.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"})]}),l.jsxs("div",{children:[l.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Printer"}),l.jsxs("select",{value:s??"",onChange:X=>o(X.target.value?Number(X.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:[l.jsx("option",{value:"",children:"No printer"}),F?.map(X=>l.jsx("option",{value:X.id,children:X.name},X.id))]})]}),l.jsxs("div",{children:[l.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[l.jsx(qu,{className:"w-4 h-4 inline mr-1"}),"Project"]}),l.jsxs("select",{value:c??"",onChange:X=>u(X.target.value?Number(X.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:[l.jsx("option",{value:"",children:"No project"}),O?.map(X=>l.jsx("option",{value:X.id,children:X.name},X.id))]})]}),l.jsxs("div",{children:[l.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Notes"}),l.jsx("textarea",{value:d,onChange:X=>f(X.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..."})]}),l.jsxs("div",{children:[l.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Tags"}),W.length>0&&l.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:W.map(X=>l.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 bg-bambu-dark-tertiary rounded text-sm text-white",children:[l.jsx(E0,{className:"w-3 h-3"}),X,l.jsx("button",{type:"button",onClick:()=>ee(X),className:"ml-0.5 text-bambu-gray hover:text-white",children:l.jsx(Wt,{className:"w-3 h-3"})})]},X))}),l.jsxs("div",{className:"relative",children:[l.jsx("input",{ref:I,type:"text",value:g,onChange:X=>m(X.target.value),onFocus:()=>{D.current!==null&&clearTimeout(D.current),N(!0)},onBlur:()=>{D.current=window.setTimeout(()=>N(!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:W.length>0?"Add more tags...":"Add tags..."}),k&&K.length>0&&l.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:[l.jsx("div",{className:"p-2 text-xs text-bambu-gray border-b border-bambu-dark-tertiary",children:"Existing tags (click to add)"}),l.jsx("div",{className:"p-2 flex flex-wrap gap-1.5",children:K.map(X=>l.jsx("button",{type:"button",onClick:()=>G(X),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:X},X))})]})]})]}),l.jsxs("div",{children:[l.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Status"}),l.jsx("select",{value:y,onChange:X=>{b(X.target.value),X.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:gUe.map(X=>l.jsx("option",{value:X.value,children:X.label},X.value))})]}),(y==="failed"||y==="aborted")&&l.jsxs("div",{children:[l.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Failure Reason"}),l.jsxs("select",{value:x,onChange:X=>v(X.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:[l.jsx("option",{value:"",children:"Select reason..."}),mUe.map(X=>l.jsx("option",{value:X,children:X},X))]})]}),l.jsxs("div",{children:[l.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[l.jsx(b0,{className:"w-4 h-4 inline mr-1"}),"Photos of Printed Result"]}),l.jsxs("div",{className:"flex flex-wrap gap-2 mb-2",children:[M.map(X=>l.jsxs("div",{className:"relative group",children:[l.jsx("img",{src:ke.getArchivePhotoUrl(t.id,X),alt:"Print result",className:"w-20 h-20 object-cover rounded-lg border border-bambu-dark-tertiary"}),l.jsx("button",{type:"button",onClick:()=>U(X),className:"absolute -top-1 -right-1 p-1 bg-red-500 rounded-full opacity-0 group-hover:opacity-100 transition-opacity",children:l.jsx(Rn,{className:"w-3 h-3 text-white"})})]},X)),l.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:[l.jsx("input",{ref:C,type:"file",accept:"image/jpeg,image/png,image/webp",onChange:Q,className:"hidden",disabled:A}),A?l.jsx(At,{className:"w-6 h-6 text-bambu-gray animate-spin"}):l.jsx(pr,{className:"w-6 h-6 text-bambu-gray"})]})]}),l.jsx("p",{className:"text-xs text-bambu-gray",children:"Click + to add photos of your printed result"})]}),l.jsxs("div",{className:"flex gap-3 pt-2",children:[l.jsx(Le,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:"Cancel"}),l.jsxs(Le,{type:"submit",disabled:Z.isPending,className:"flex-1",children:[l.jsx(Ro,{className:"w-4 h-4"}),Z.isPending?"Saving...":"Save"]})]})]})]})})}function bUe({x:t,y:e,items:n,onClose:r}){const i=E.useRef(null),[a,s]=E.useState(null),o=E.useRef(null),[c,u]=E.useState({x:t,y:e,visible:!1}),[d,f]=E.useState(!1);E.useEffect(()=>{const x=b=>{i.current&&!i.current.contains(b.target)&&r()},v=b=>{b.key==="Escape"&&r()},y=()=>{r()};return document.addEventListener("mousedown",x),document.addEventListener("keydown",v),document.addEventListener("scroll",y,!0),()=>{document.removeEventListener("mousedown",x),document.removeEventListener("keydown",v),document.removeEventListener("scroll",y,!0),o.current&&clearTimeout(o.current)}},[r]),E.useLayoutEffect(()=>{if(i.current){i.current.style.visibility="hidden",i.current.style.display="block";const x=i.current.getBoundingClientRect(),v=window.innerWidth,y=window.innerHeight,b=8;let M=t,S=e;t+x.width>v-b&&(M=Math.max(b,v-x.width-b)),My-b&&(S=Math.max(b,y-x.height-b)),SA),u({x:M,y:S,visible:!0})}},[t,e]);const g=x=>{o.current&&(clearTimeout(o.current),o.current=null),s(x)},m=()=>{o.current=window.setTimeout(()=>{s(null)},150)};return l.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,v)=>{if(x.divider)return l.jsx("div",{className:"my-1 border-t border-bambu-dark-tertiary"},v);const y=x.submenu&&x.submenu.length>0;return l.jsxs("div",{className:"relative",onMouseEnter:()=>y&&g(v),onMouseLeave:()=>y&&m(),children:[l.jsxs("button",{onClick:()=>{y?s(a===v?null:v):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"} ${y&&a===v?"bg-bambu-dark-tertiary":""}`,children:[x.icon&&l.jsx("span",{className:"w-4 h-4 flex-shrink-0 flex items-center justify-center",children:x.icon}),l.jsx("span",{className:"flex-1",children:x.label}),y&&l.jsx(df,{className:"w-4 h-4 text-bambu-gray"})]}),y&&a===v&&l.jsx("div",{className:`absolute top-0 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"}`,onMouseEnter:()=>{o.current&&(clearTimeout(o.current),o.current=null)},onMouseLeave:()=>m(),children:x.submenu.map((b,M)=>l.jsxs("button",{onClick:()=>{b.disabled||(b.onClick(),r())},disabled:b.disabled,className:`w-full flex items-center gap-2 px-3 py-2 text-sm text-left transition-colors ${b.disabled?"text-bambu-gray cursor-not-allowed":b.danger?"text-red-400 hover:bg-red-400/10":"text-white hover:bg-bambu-dark-tertiary"}`,children:[b.icon&&l.jsx("span",{className:"w-4 h-4 flex-shrink-0 flex items-center justify-center",children:b.icon}),b.label]},M))})]},v)})})}function yUe({selectedIds:t,existingTags:e,onClose:n}){const r=En(),{showToast:i}=ai(),[a,s]=E.useState(""),[o,c]=E.useState(new Set),[u,d]=E.useState("add");E.useEffect(()=>{const v=y=>{y.key==="Escape"&&n()};return window.addEventListener("keydown",v),()=>window.removeEventListener("keydown",v)},[n]);const f=wt({mutationFn:async()=>{const v=Array.from(o);let y=0;for(const b of t)try{const M=await ke.getArchive(b),S=M.tags?M.tags.split(",").map(T=>T.trim()).filter(Boolean):[];let A;u==="add"?A=[...new Set([...S,...v])]:A=S.filter(T=>!o.has(T)),await ke.updateArchive(b,{tags:A.join(", ")}),y++}catch(M){throw console.error(`Failed to update archive ${b}:`,M),new Error(`Failed on archive ${b}: ${M instanceof Error?M.message:"Unknown error"}`)}return{count:y,mode:u,tags:v}},onSuccess:({count:v,mode:y,tags:b})=>{r.invalidateQueries({queryKey:["archives"]}),i(`${y==="add"?"Added":"Removed"} ${b.length} tag${b.length!==1?"s":""} ${y==="add"?"to":"from"} ${v} archive${v!==1?"s":""}`),n()},onError:v=>{i(v.message||"Failed to update tags","error")}}),g=v=>{c(y=>{const b=new Set(y);return b.has(v)?b.delete(v):b.add(v),b})},m=()=>{a.trim()&&!o.has(a.trim())&&(c(v=>new Set([...v,a.trim()])),s(""))},x=v=>{v.key==="Enter"&&(v.preventDefault(),m())};return l.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:l.jsx(Nt,{className:"w-full max-w-md",children:l.jsxs(Rt,{className:"p-0",children:[l.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx(E0,{className:"w-5 h-5 text-bambu-green"}),l.jsx("h2",{className:"text-xl font-semibold text-white",children:u==="add"?"Add Tags":"Remove Tags"})]}),l.jsx("button",{onClick:n,className:"text-bambu-gray hover:text-white transition-colors",children:l.jsx(Wt,{className:"w-5 h-5"})})]}),l.jsxs("div",{className:"p-4 space-y-4",children:[l.jsxs("p",{className:"text-sm text-bambu-gray",children:[u==="add"?"Add":"Remove"," tags for ",t.length," selected archive",t.length!==1?"s":""]}),l.jsxs("div",{className:"flex gap-2",children:[l.jsx(Le,{size:"sm",variant:u==="add"?"primary":"secondary",onClick:()=>d("add"),children:"Add Tags"}),l.jsx(Le,{size:"sm",variant:u==="remove"?"primary":"secondary",onClick:()=>d("remove"),children:"Remove Tags"})]}),u==="add"&&l.jsxs("div",{className:"flex gap-2",children:[l.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=>s(v.target.value),onKeyDown:x}),l.jsx(Le,{size:"sm",variant:"secondary",onClick:m,disabled:!a.trim(),children:l.jsx(pr,{className:"w-4 h-4"})})]}),e.length>0&&l.jsxs("div",{children:[l.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:"Existing tags:"}),l.jsx("div",{className:"flex flex-wrap gap-2",children:e.map(v=>l.jsx("button",{onClick:()=>g(v),className:`px-2 py-1 rounded text-sm transition-colors ${o.has(v)?"bg-bambu-green text-white":"bg-bambu-dark-tertiary text-bambu-gray-light hover:bg-bambu-dark"}`,children:v},v))})]}),o.size>0&&l.jsxs("div",{children:[l.jsxs("p",{className:"text-xs text-bambu-gray mb-2",children:["Tags to ",u==="add"?"add":"remove",":"]}),l.jsx("div",{className:"flex flex-wrap gap-2",children:Array.from(o).map(v=>l.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,l.jsx("button",{onClick:()=>g(v),className:"hover:opacity-70",children:l.jsx(Wt,{className:"w-3 h-3"})})]},v))})]})]}),l.jsxs("div",{className:"flex gap-3 p-4 border-t border-bambu-dark-tertiary",children:[l.jsx(Le,{variant:"secondary",onClick:n,className:"flex-1",children:"Cancel"}),l.jsx(Le,{onClick:()=>f.mutate(),disabled:o.size===0||f.isPending,className:"flex-1",children:f.isPending?l.jsxs(l.Fragment,{children:[l.jsx(At,{className:"w-4 h-4 animate-spin"}),"Processing..."]}):l.jsxs(l.Fragment,{children:[l.jsx(E0,{className:"w-4 h-4"}),u==="add"?"Add Tags":"Remove Tags"]})})]})]})})})}function vUe(t,e){return new Date(t,e+1,0).getDate()}function _Ue(t,e){return new Date(t,e,1).getDay()}const wUe=["January","February","March","April","May","June","July","August","September","October","November","December"],SUe=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];function MUe({archives:t,onArchiveClick:e}){const n=new Date,[r,i]=E.useState(n.getMonth()),[a,s]=E.useState(n.getFullYear()),[o,c]=E.useState(null),u=E.useMemo(()=>{const b=new Map;return t.forEach(M=>{const S=new Date(M.completed_at||M.created_at),A=`${S.getFullYear()}-${String(S.getMonth()+1).padStart(2,"0")}-${String(S.getDate()).padStart(2,"0")}`,T=b.get(A)||[];T.push(M),b.set(A,T)}),b},[t]),d=vUe(a,r),f=_Ue(a,r),g=()=>{r===0?(i(11),s(a-1)):i(r-1)},m=()=>{r===11?(i(0),s(a+1)):i(r+1)},x=()=>{i(n.getMonth()),s(n.getFullYear())},v=[];for(let b=0;bl.jsx("div",{className:"text-center text-xs text-bambu-gray py-2",children:b},b))}),l.jsx("div",{className:"grid grid-cols-7 gap-1",children:v.map((b,M)=>{if(b===null)return l.jsx("div",{className:"aspect-square"},`empty-${M}`);const S=`${a}-${String(r+1).padStart(2,"0")}-${String(b).padStart(2,"0")}`,A=u.get(S)||[],T=A.length>0,k=b===n.getDate()&&r===n.getMonth()&&a===n.getFullYear(),N=S===o,I=A.filter(D=>D.status==="completed").length,C=A.filter(D=>D.status==="failed").length;return l.jsxs("button",{onClick:()=>c(N?null:S),className:`aspect-square rounded-lg p-1 flex flex-col items-center justify-center transition-colors relative ${N?"bg-bambu-green text-white":k?"bg-bambu-green/20 text-white ring-2 ring-bambu-green":T?"bg-bambu-dark-tertiary hover:bg-bambu-dark-tertiary/70 text-white":"hover:bg-bambu-dark-tertiary/50 text-bambu-gray"}`,children:[l.jsx("span",{className:`text-sm font-medium ${k&&!N?"text-bambu-green":""}`,children:b}),T&&l.jsxs("div",{className:"absolute bottom-1 left-1/2 -translate-x-1/2 flex items-center gap-1",children:[l.jsx("div",{className:`w-2 h-2 rounded-full ${C>0&&I===0?"bg-red-400":C>0?"bg-yellow-400":"bg-green-400"}`}),l.jsx("span",{className:"text-xs font-medium",children:A.length})]})]},b)})}),l.jsx("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:l.jsxs("div",{className:"grid grid-cols-3 gap-4 text-center",children:[l.jsxs("div",{children:[l.jsx("div",{className:"text-2xl font-bold text-white",children:t.filter(b=>{const M=new Date(b.completed_at||b.created_at);return M.getMonth()===r&&M.getFullYear()===a}).length}),l.jsx("div",{className:"text-xs text-bambu-gray",children:"Prints this month"})]}),l.jsxs("div",{children:[l.jsx("div",{className:"text-2xl font-bold text-green-400",children:t.filter(b=>{const M=new Date(b.completed_at||b.created_at);return M.getMonth()===r&&M.getFullYear()===a&&b.status==="completed"}).length}),l.jsx("div",{className:"text-xs text-bambu-gray",children:"Successful"})]}),l.jsxs("div",{children:[l.jsx("div",{className:"text-2xl font-bold text-red-400",children:t.filter(b=>{const M=new Date(b.completed_at||b.created_at);return M.getMonth()===r&&M.getFullYear()===a&&b.status==="failed"}).length}),l.jsx("div",{className:"text-xs text-bambu-gray",children:"Failed"})]})]})})]}),l.jsx("div",{className:"lg:w-80 bg-bambu-dark rounded-xl p-4",children:o?l.jsxs(l.Fragment,{children:[l.jsx("h3",{className:"text-sm font-medium text-bambu-gray mb-3",children:new Date(o+"T12:00:00").toLocaleDateString("en-US",{weekday:"long",month:"long",day:"numeric",year:"numeric"})}),y.length>0?l.jsx("div",{className:"space-y-2 max-h-96 overflow-y-auto",children:y.map(b=>l.jsxs("button",{onClick:()=>e?.(b),className:"w-full flex items-center gap-3 p-2 rounded-lg hover:bg-bambu-dark-tertiary transition-colors text-left",children:[b.thumbnail_path?l.jsx("img",{src:ke.getArchiveThumbnail(b.id),alt:"",className:"w-12 h-12 rounded object-cover"}):l.jsx("div",{className:"w-12 h-12 rounded bg-bambu-dark-tertiary flex items-center justify-center",children:l.jsx("span",{className:"text-xs text-bambu-gray",children:"3MF"})}),l.jsxs("div",{className:"flex-1 min-w-0",children:[l.jsx("p",{className:"text-sm text-white truncate",children:b.print_name||b.filename}),l.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[l.jsx("span",{className:b.status==="failed"?"text-red-400":"text-green-400",children:b.status==="failed"?"Failed":"Completed"}),b.filament_color&&l.jsx("div",{className:"flex gap-0.5",children:b.filament_color.split(",").map((M,S)=>l.jsx("div",{className:"w-3 h-3 rounded-full border border-white/20",style:{backgroundColor:M}},S))})]})]})]},b.id))}):l.jsx("p",{className:"text-sm text-bambu-gray",children:"No prints on this day"})]}):l.jsx("div",{className:"text-center py-8",children:l.jsx("p",{className:"text-sm text-bambu-gray",children:"Select a day to see prints"})})})]})}function EUe({archiveId:t,archiveName:e,onClose:n}){const r=ke.getArchiveQRCodeUrl(t,300);E.useEffect(()=>{const a=s=>{s.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 l.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:n,children:l.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary w-full max-w-sm",onClick:a=>a.stopPropagation(),children:[l.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[l.jsx("h2",{className:"text-lg font-semibold text-white",children:"QR Code"}),l.jsx("button",{onClick:n,className:"text-bambu-gray hover:text-white transition-colors",children:l.jsx(Wt,{className:"w-5 h-5"})})]}),l.jsxs("div",{className:"p-6 flex flex-col items-center",children:[l.jsx("p",{className:"text-sm text-bambu-gray mb-4 text-center truncate max-w-full",children:e}),l.jsx("div",{className:"bg-white p-4 rounded-lg mb-4",children:l.jsx("img",{src:r,alt:"QR Code",className:"w-64 h-64"})}),l.jsx("p",{className:"text-xs text-bambu-gray mb-4 text-center",children:"Scan to open this archive"}),l.jsxs(Le,{onClick:i,className:"w-full",children:[l.jsx(Es,{className:"w-4 h-4"}),"Download QR Code"]})]})]})})}function AUe({archiveId:t,archiveName:e,photos:n,onClose:r,onDelete:i}){const[a,s]=E.useState(0),[o,c]=E.useState(!1);if(E.useEffect(()=>{const m=x=>{x.key==="Escape"&&r(),x.key==="ArrowLeft"&&s(v=>Math.max(0,v-1)),x.key==="ArrowRight"&&s(v=>Math.min(n.length-1,v+1))};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)},[r,n.length]),E.useEffect(()=>{a>=n.length&&s(Math.max(0,n.length-1))},[n.length,a]),n.length===0)return r(),null;const u=n[a],d=ke.getArchivePhotoUrl(t,u),f=()=>{const m=document.createElement("a");m.href=d,m.download=`${e}_photo_${a+1}.jpg`,m.click()},g=()=>{i&&c(!0)};return l.jsxs("div",{className:"fixed inset-0 bg-black/90 flex items-center justify-center z-50",onClick:r,children:[l.jsxs("div",{className:"relative w-full h-full flex flex-col",onClick:m=>m.stopPropagation(),children:[l.jsxs("div",{className:"flex items-center justify-between px-6 py-4 bg-black/50",children:[l.jsxs("div",{children:[l.jsx("h2",{className:"text-lg font-semibold text-white",children:e}),l.jsxs("p",{className:"text-sm text-bambu-gray",children:["Photo ",a+1," of ",n.length]})]}),l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsxs(Le,{variant:"secondary",size:"sm",onClick:f,children:[l.jsx(Es,{className:"w-4 h-4"}),"Download"]}),i&&l.jsx(Le,{variant:"secondary",size:"sm",onClick:g,className:"text-red-400 hover:text-red-300",children:l.jsx(Rn,{className:"w-4 h-4"})}),l.jsx("button",{onClick:r,className:"p-2 text-bambu-gray hover:text-white transition-colors",children:l.jsx(Wt,{className:"w-6 h-6"})})]})]}),l.jsxs("div",{className:"flex-1 min-h-0 flex items-center justify-center p-4 relative overflow-hidden",children:[a>0&&l.jsx("button",{onClick:()=>s(m=>m-1),className:"absolute left-4 z-10 p-3 bg-black/50 hover:bg-black/70 rounded-full transition-colors",children:l.jsx(Bh,{className:"w-8 h-8 text-white"})}),l.jsx("img",{src:d,alt:`Photo ${a+1}`,className:"max-w-full max-h-full object-contain rounded-lg",style:{maxHeight:"calc(100vh - 200px)"}}),as(m=>m+1),className:"absolute right-4 z-10 p-3 bg-black/50 hover:bg-black/70 rounded-full transition-colors",children:l.jsx(df,{className:"w-8 h-8 text-white"})})]}),n.length>1&&l.jsx("div",{className:"flex justify-center gap-2 p-4 bg-black/50",children:n.map((m,x)=>l.jsx("button",{onClick:()=>s(x),className:`w-16 h-16 rounded-lg overflow-hidden border-2 transition-colors ${x===a?"border-bambu-green":"border-transparent hover:border-bambu-gray"}`,children:l.jsx("img",{src:ke.getArchivePhotoUrl(t,m),alt:`Thumbnail ${x+1}`,className:"w-full h-full object-cover"})},m))})]}),o&&l.jsx(Qr,{title:"Delete Photo",message:"Delete this photo? This cannot be undone.",confirmText:"Delete",variant:"danger",onConfirm:()=>{i?.(u),c(!1)},onCancel:()=>c(!1)})]})}function Yi(t){this.content=t}Yi.prototype={constructor:Yi,find:function(t){for(var e=0;e>1}};Yi.from=function(t){if(t instanceof Yi)return t;var e=[];if(t)for(var n in t)e.push(n,t[n]);return new Yi(e)};function iQ(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 s=0;i.text[s]==a.text[s];s++)n++;return n}if(i.content.size||a.content.size){let s=iQ(i.content,a.content,n+1);if(s!=null)return s}n+=i.nodeSize}}function aQ(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 s=t.child(--i),o=e.child(--a),c=s.nodeSize;if(s==o){n-=c,r-=c;continue}if(!s.sameMarkup(o))return{a:n,b:r};if(s.isText&&s.text!=o.text){let u=0,d=Math.min(s.text.length,o.text.length);for(;ue&&r(c,i+o,a||null,s)!==!1&&c.content.size){let d=o+1;c.nodesBetween(Math.max(0,e-d),Math.min(c.content.size,n-d),r,i+d)}o=u}}descendants(e){this.nodesBetween(0,this.size,e)}textBetween(e,n,r,i){let a="",s=!0;return this.nodesBetween(e,n,(o,c)=>{let u=o.isText?o.text.slice(Math.max(e,c)-c,n-c):o.isLeaf?i?typeof i=="function"?i(o):i:o.type.spec.leafText?o.type.spec.leafText(o):"":"";o.isBlock&&(o.isLeaf&&u||o.isTextblock)&&r&&(s?s=!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,s=0;se&&((sn)&&(o.isText?o=o.cut(Math.max(0,e-s),Math.min(o.text.length,n-s)):o=o.cut(Math.max(0,e-s-1),Math.min(o.content.size,n-s-1))),r.push(o),i+=o.nodeSize),s=c}return new pt(r,i)}cutByIndex(e,n){return e==n?pt.empty:e==0&&n==this.content.length?this:new pt(this.content.slice(e,n))}replaceChild(e,n){let r=this.content[e];if(r==n)return this;let i=this.content.slice(),a=this.size+n.nodeSize-r.nodeSize;return i[e]=n,new pt(i,a)}addToStart(e){return new pt([e].concat(this.content),this.size+e.nodeSize)}addToEnd(e){return new pt(this.content.concat(e),this.size+e.nodeSize)}eq(e){if(this.content.length!=e.content.length)return!1;for(let n=0;nthis.size||e<0)throw new RangeError(`Position ${e} outside of fragment (${this})`);for(let n=0,r=0;;n++){let i=this.child(n),a=r+i.nodeSize;if(a>=e)return a==e?O_(n+1,a):O_(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 pt.empty;if(!Array.isArray(n))throw new RangeError("Invalid input for Fragment.fromJSON");return new pt(n.map(e.nodeFromJSON))}static fromArray(e){if(!e.length)return pt.empty;let n,r=0;for(let i=0;ithis.type.rank&&(n||(n=e.slice(0,i)),n.push(this),r=!0),n&&n.push(a)}}return n||(n=e.slice()),r||n.push(this),n}removeFromSet(e){for(let n=0;nr.type.rank-i.type.rank),n}};tr.none=[];class Hw extends Error{}class kt{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=oQ(this.content,e+this.openStart,n);return r&&new kt(r,this.openStart,this.openEnd)}removeBetween(e,n){return new kt(sQ(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 kt.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 kt(pt.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 kt(e,r,i)}}kt.empty=new kt(pt.empty,0,0);function sQ(t,e,n){let{index:r,offset:i}=t.findIndex(e),a=t.maybeChild(r),{index:s,offset:o}=t.findIndex(n);if(i==e||a.isText){if(o!=n&&!t.child(s).isText)throw new RangeError("Removing non-flat range");return t.cut(0,e).append(t.cut(n))}if(r!=s)throw new RangeError("Removing non-flat range");return t.replaceChild(r,a.copy(sQ(a.content,e-i-1,n-i-1)))}function oQ(t,e,n,r){let{index:i,offset:a}=t.findIndex(e),s=t.maybeChild(i);if(a==e||s.isText)return r&&!r.canReplace(i,i,n)?null:t.cut(0,e).append(n).append(t.cut(e));let o=oQ(s.content,e-a-1,n,s);return o&&t.replaceChild(i,s.copy(o))}function TUe(t,e,n){if(n.openStart>t.depth)throw new Hw("Inserted content deeper than insertion position");if(t.depth-n.openStart!=e.depth-n.openEnd)throw new Hw("Inconsistent open depths");return lQ(t,e,n,0)}function lQ(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 Jx(t,e,n,r){let i=(e||t).node(n),a=0,s=e?e.index(n):i.childCount;t&&(a=t.index(n),t.depth>n?a++:t.textOffset&&(Rh(t.nodeAfter,r),a++));for(let o=a;oi&&BP(t,e,i+1),s=r.depth>i&&BP(n,r,i+1),o=[];return Jx(null,t,i,o),a&&s&&e.index(i)==n.index(i)?(cQ(a,s),Rh(Dh(a,uQ(t,e,n,r,i+1)),o)):(a&&Rh(Dh(a,$w(t,e,i+1)),o),Jx(e,n,i,o),s&&Rh(Dh(s,$w(n,r,i+1)),o)),Jx(r,null,i,o),new pt(o)}function $w(t,e,n){let r=[];if(Jx(null,t,n,r),t.depth>n){let i=BP(t,e,n+1);Rh(Dh(i,$w(t,e,n+1)),r)}return Jx(e,null,n,r),new pt(r)}function CUe(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(pt.from(i));return{start:i.resolveNoCache(t.openStart+n),end:i.resolveNoCache(i.content.size-t.openEnd-n)}}class J0{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 Vw(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 s=e;;){let{index:o,offset:c}=s.content.findIndex(a),u=a-c;if(r.push(s,o,i+c),!u||(s=s.child(o),s.isText))break;a=u-1,i+=c+1}return new J0(n,r,a)}static resolveCached(e,n){let r=kV.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()+")"),dQ(this.marks,e)}contentMatchAt(e){let n=this.type.contentMatch.matchFragment(this.content,0,e);if(!n)throw new Error("Called contentMatchAt on a node with invalid content");return n}canReplace(e,n,r=pt.empty,i=0,a=r.childCount){let s=this.contentMatchAt(e).matchFragment(r,i,a),o=s&&s.matchFragment(this.content,n);if(!o||!o.validEnd)return!1;for(let c=i;cn.type.name)}`);this.content.forEach(n=>n.check())}toJSON(){let e={type:this.type.name};for(let n in this.attrs){e.attrs=this.attrs;break}return this.content.size&&(e.content=this.content.toJSON()),this.marks.length&&(e.marks=this.marks.map(n=>n.toJSON())),e}static fromJSON(e,n){if(!n)throw new RangeError("Invalid input for Node.fromJSON");let r;if(n.marks){if(!Array.isArray(n.marks))throw new RangeError("Invalid mark data for Node.fromJSON");r=n.marks.map(e.markFromJSON)}if(n.type=="text"){if(typeof n.text!="string")throw new RangeError("Invalid text node in JSON");return e.text(n.text,r)}let i=pt.fromJSON(e,n.content),a=e.nodeType(n.type).create(n.attrs,i,r);return a.type.checkAttrs(a.attrs),a}};Ju.prototype.text=void 0;class Gw extends Ju{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):dQ(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 Gw(this.type,this.attrs,this.text,e)}withText(e){return e==this.text?this:new Gw(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 dQ(t,e){for(let n=t.length-1;n>=0;n--)e=t[n].type.name+"("+e+")";return e}class af{constructor(e){this.validEnd=e,this.next=[],this.wrapCache=[]}static parse(e,n){let r=new RUe(e,n);if(r.next==null)return af.empty;let i=hQ(r);r.next&&r.err("Unexpected trailing text");let a=UUe(FUe(i));return zUe(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 s=0;s"+e.indexOf(r.next[s].next);return a}).join(` +`),f=u.slice(0,d);this.parser.parseGCode(s+f),s=u.slice(d)}while(!a.done);var c;console.debug("read from stream",o)}))}initGui(){typeof this.devMode=="boolean"&&this.devMode===!0?this.devGui=new NV(this):typeof this.devMode=="object"&&(this.devGui=new NV(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())}}lm.defaultExtrusionColor=new $t("hotpink");const uUe=function(t){return new lm(t)};function dUe({gcodeUrl:t,buildVolume:e={x:256,y:256,z:256},className:n=""}){const r=E.useRef(null),i=E.useRef(null),[a,s]=E.useState(!0),[o,c]=E.useState(null),[u,d]=E.useState(!1),[f,g]=E.useState(0),[m,x]=E.useState(0);E.useEffect(()=>{if(!r.current)return;const b=r.current,M=uUe({canvas:b,buildVolume:e,backgroundColor:1710618,travelColor:4473924,extrusionColor:44610,topLayerColor:65370,lastSegmentColor:16777215,lineWidth:2,renderTravel:!1,renderExtrusion:!0});i.current=M,s(!0),c(null),d(!1),fetch(t).then(async A=>{if(!A.ok)throw A.status===404&&(await A.json().catch(()=>({}))).detail?.includes("sliced")?(d(!0),new Error("not_sliced")):new Error("Failed to load G-code");return A.text()}).then(A=>{M.processGCode(A);const T=M.layers?.length||0;x(T),g(T),M.render(),s(!1)}).catch(A=>{c(A.message),s(!1)});const S=()=>{if(b.parentElement){const A=b.parentElement.getBoundingClientRect();b.width=A.width,b.height=A.height,M.resize()}};return S(),window.addEventListener("resize",S),()=>{window.removeEventListener("resize",S),M.dispose()}},[t,e]);const v=b=>{if(!i.current)return;const M=Math.max(1,Math.min(b,m));g(M),i.current.render()},y=b=>{v(parseInt(b.target.value,10))};return l.jsxs("div",{className:`relative flex flex-col h-full ${n}`,children:[l.jsxs("div",{className:"flex-1 relative bg-bambu-dark rounded-lg overflow-hidden",children:[l.jsx("canvas",{ref:r,className:"w-full h-full"}),a&&l.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-bambu-dark/80",children:l.jsxs("div",{className:"text-center",children:[l.jsx(At,{className:"w-8 h-8 animate-spin text-bambu-green mx-auto mb-2"}),l.jsx("p",{className:"text-bambu-gray text-sm",children:"Loading G-code..."})]})}),u&&l.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-bambu-dark/80",children:l.jsxs("div",{className:"text-center max-w-sm px-4",children:[l.jsx(ale,{className:"w-12 h-12 text-bambu-gray mx-auto mb-3"}),l.jsx("p",{className:"text-white font-medium mb-2",children:"G-code not available"}),l.jsx("p",{className:"text-bambu-gray text-sm",children:"This file hasn't been sliced yet. G-code preview is only available after slicing the model in Bambu Studio or Orca Slicer."})]})}),o&&!u&&l.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-bambu-dark/80",children:l.jsx("div",{className:"text-center text-red-400",children:l.jsx("p",{className:"text-sm",children:o})})})]}),!a&&!o&&!u&&m>0&&l.jsx("div",{className:"mt-4 px-2",children:l.jsxs("div",{className:"flex items-center gap-3",children:[l.jsx($h,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}),l.jsx("button",{onClick:()=>v(f-1),disabled:f<=1,className:"p-1 rounded hover:bg-bambu-dark-tertiary disabled:opacity-30 disabled:cursor-not-allowed",children:l.jsx(Bh,{className:"w-4 h-4"})}),l.jsx("input",{type:"range",min:1,max:m,value:f,onChange:y,className:"flex-1 h-2 bg-bambu-dark-tertiary rounded-lg appearance-none cursor-pointer accent-bambu-green"}),l.jsx("button",{onClick:()=>v(f+1),disabled:f>=m,className:"p-1 rounded hover:bg-bambu-dark-tertiary disabled:opacity-30 disabled:cursor-not-allowed",children:l.jsx(df,{className:"w-4 h-4"})}),l.jsxs("span",{className:"text-sm text-bambu-gray min-w-[80px] text-right",children:[f," / ",m]})]})})]})}function hUe({archiveId:t,title:e,onClose:n}){const[r,i]=E.useState(null),[a,s]=E.useState(null),[o,c]=E.useState(!0);E.useEffect(()=>{const d=f=>{f.key==="Escape"&&n()};return window.addEventListener("keydown",d),()=>window.removeEventListener("keydown",d)},[n]),E.useEffect(()=>{ke.getArchiveCapabilities(t).then(d=>{s(d),d.has_model?i("3d"):d.has_gcode&&i("gcode"),c(!1)}).catch(()=>{s({has_model:!0,has_gcode:!1,build_volume:{x:256,y:256,z:256}}),i("3d"),c(!1)})},[t]);const u=()=>{const d=e||"model",f=`${window.location.origin}${ke.getArchiveForSlicer(t,d)}`;window.location.href=`bambustudioopen://${encodeURIComponent(f)}`};return l.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-8",onClick:n,children:l.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:[l.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[l.jsx("h2",{className:"text-lg font-semibold text-white truncate flex-1 mr-4",children:e}),l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsxs(Le,{variant:"secondary",size:"sm",onClick:u,children:[l.jsx(As,{className:"w-4 h-4"}),"Open in Slicer"]}),l.jsx(Le,{variant:"ghost",size:"sm",onClick:n,children:l.jsx(Wt,{className:"w-5 h-5"})})]})]}),a&&l.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary",children:[l.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:[l.jsx(fm,{className:"w-4 h-4"}),"3D Model",!a.has_model&&l.jsx("span",{className:"text-xs",children:"(not available)"})]}),l.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:[l.jsx(Doe,{className:"w-4 h-4"}),"G-code Preview",!a.has_gcode&&l.jsx("span",{className:"text-xs",children:"(not sliced)"})]})]}),l.jsx("div",{className:"flex-1 overflow-hidden p-4",children:o?l.jsx("div",{className:"w-full h-full flex items-center justify-center",children:l.jsx(At,{className:"w-8 h-8 animate-spin text-bambu-green"})}):r==="3d"&&a?l.jsx(oje,{url:ke.getArchiveDownload(t),buildVolume:a.build_volume,className:"w-full h-full"}):r==="gcode"&&a?l.jsx(dUe,{gcodeUrl:ke.getArchiveGcode(t),buildVolume:a.build_volume,className:"w-full h-full"}):l.jsx("div",{className:"w-full h-full flex items-center justify-center text-bambu-gray",children:"No preview available for this file"})})]})})}function fUe({archiveId:t,archiveName:e,onClose:n,onSuccess:r}){const[i,a]=E.useState(null);E.useEffect(()=>{const d=f=>{f.key==="Escape"&&n()};return window.addEventListener("keydown",d),()=>window.removeEventListener("keydown",d)},[n]);const{data:s,isLoading:o}=vt({queryKey:["printers"],queryFn:ke.getPrinters}),c=wt({mutationFn:()=>{if(!i)throw new Error("No printer selected");return ke.reprintArchive(t,i)},onSuccess:()=>{r(),n()}}),u=s?.filter(d=>d.is_active)||[];return l.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-8",children:l.jsx(Nt,{className:"w-full max-w-md",children:l.jsxs(Rt,{children:[l.jsxs("div",{className:"flex items-center justify-between mb-4",children:[l.jsx("h2",{className:"text-lg font-semibold text-white",children:"Re-print"}),l.jsx(Le,{variant:"ghost",size:"sm",onClick:n,children:l.jsx(Wt,{className:"w-5 h-5"})})]}),l.jsxs("p",{className:"text-sm text-bambu-gray mb-4",children:["Send ",l.jsx("span",{className:"text-white",children:e})," to a printer"]}),o?l.jsx("div",{className:"flex justify-center py-8",children:l.jsx(At,{className:"w-6 h-6 text-bambu-green animate-spin"})}):u.length===0?l.jsx("div",{className:"text-center py-8 text-bambu-gray",children:"No active printers available"}):l.jsx("div",{className:"space-y-2 mb-6",children:u.map(d=>l.jsxs("button",{onClick:()=>a(d.id),className:`w-full flex items-center gap-3 p-3 rounded-lg border transition-colors ${i===d.id?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark hover:border-bambu-gray"}`,children:[l.jsx("div",{className:`p-2 rounded-lg ${i===d.id?"bg-bambu-green/20":"bg-bambu-dark-tertiary"}`,children:l.jsx(Ts,{className:`w-5 h-5 ${i===d.id?"text-bambu-green":"text-bambu-gray"}`})}),l.jsxs("div",{className:"text-left",children:[l.jsx("p",{className:"text-white font-medium",children:d.name}),l.jsxs("p",{className:"text-xs text-bambu-gray",children:[d.model||"Unknown model"," • ",d.ip_address]})]})]},d.id))}),c.isError&&l.jsx("div",{className:"mb-4 p-3 bg-red-500/20 border border-red-500/50 rounded-lg text-sm text-red-400",children:c.error.message||"Failed to start print"}),l.jsxs("div",{className:"flex gap-3",children:[l.jsx(Le,{variant:"secondary",onClick:n,className:"flex-1",children:"Cancel"}),l.jsx(Le,{onClick:()=>c.mutate(),disabled:!i||c.isPending,className:"flex-1",children:c.isPending?l.jsxs(l.Fragment,{children:[l.jsx(At,{className:"w-4 h-4 animate-spin"}),"Sending..."]}):l.jsxs(l.Fragment,{children:[l.jsx(Ts,{className:"w-4 h-4"}),"Print"]})})]})]})})})}function pUe({onClose:t,initialFiles:e}){const n=En(),{showToast:r}=ai(),i=E.useRef(null),[a,s]=E.useState(()=>e?.filter(N=>N.name.endsWith(".3mf")).map(N=>({file:N,status:"pending"}))||[]),[o,c]=E.useState(!1),[u,d]=E.useState(),[f,g]=E.useState(null);E.useEffect(()=>{const N=I=>{I.key==="Escape"&&t()};return window.addEventListener("keydown",N),()=>window.removeEventListener("keydown",N)},[t]);const{data:m}=vt({queryKey:["printers"],queryFn:ke.getPrinters}),x=wt({mutationFn:N=>ke.uploadArchivesBulk(N,u),onSuccess:N=>{g(N),n.invalidateQueries({queryKey:["archives"]}),n.invalidateQueries({queryKey:["archiveStats"]}),s(I=>I.map(C=>{const D=N.results.find(O=>O.filename===C.file.name),F=N.errors.find(O=>O.filename===C.file.name);return D?{...C,status:"success",archiveId:D.id}:F?{...C,status:"error",error:F.error}:C})),N.failed===0?r(`${N.uploaded} file${N.uploaded!==1?"s":""} uploaded`):N.uploaded===0?r(`Failed to upload ${N.failed} file${N.failed!==1?"s":""}`,"error"):r(`${N.uploaded} uploaded, ${N.failed} failed`,"warning")},onError:()=>{s(N=>N.map(I=>({...I,status:"error",error:"Upload failed"}))),r("Upload failed","error")}}),v=E.useCallback(N=>{N.preventDefault(),c(!0)},[]),y=E.useCallback(N=>{N.preventDefault(),c(!1)},[]),b=E.useCallback(N=>{N.preventDefault(),c(!1);const I=Array.from(N.dataTransfer.files).filter(C=>C.name.endsWith(".3mf"));I.length>0&&s(C=>[...C,...I.map(D=>({file:D,status:"pending"}))])},[]),M=E.useCallback(N=>{const I=Array.from(N.target.files||[]).filter(C=>C.name.endsWith(".3mf"));I.length>0&&s(C=>[...C,...I.map(D=>({file:D,status:"pending"}))]),i.current&&(i.current.value="")},[]),S=E.useCallback(N=>{s(I=>I.filter((C,D)=>D!==N))},[]),A=()=>{if(a.length===0)return;const N=a.filter(I=>I.status==="pending");N.length!==0&&(s(I=>I.map(C=>C.status==="pending"?{...C,status:"uploading"}:C)),x.mutate(N.map(I=>I.file)))},T=a.filter(N=>N.status==="pending").length,k=x.isPending;return l.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:l.jsx(Nt,{className:"w-full max-w-2xl max-h-[90vh] flex flex-col",children:l.jsxs(Rt,{className:"p-0 flex flex-col h-full",children:[l.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[l.jsx("h2",{className:"text-xl font-semibold text-white",children:"Upload 3MF Files"}),l.jsx("button",{onClick:t,className:"text-bambu-gray hover:text-white transition-colors",children:l.jsx(Wt,{className:"w-5 h-5"})})]}),l.jsx("div",{className:"p-4",children:l.jsxs("div",{className:`border-2 border-dashed rounded-lg p-8 text-center transition-colors ${o?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary hover:border-bambu-gray"}`,onDragOver:v,onDragLeave:y,onDrop:b,children:[l.jsx(vs,{className:"w-12 h-12 mx-auto mb-4 text-bambu-gray"}),l.jsx("p",{className:"text-white mb-2",children:"Drag & drop .3mf files here"}),l.jsx("p",{className:"text-bambu-gray text-sm mb-4",children:"or"}),l.jsx(Le,{variant:"secondary",onClick:()=>i.current?.click(),disabled:k,children:"Browse Files"}),l.jsx("input",{ref:i,type:"file",accept:".3mf",multiple:!0,className:"hidden",onChange:M})]})}),l.jsxs("div",{className:"px-4 pb-4",children:[l.jsx("label",{className:"block text-sm text-bambu-gray mb-2",children:"Associate with printer (optional)"}),l.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:N=>d(N.target.value?Number(N.target.value):void 0),disabled:k,children:[l.jsx("option",{value:"",children:"No printer"}),m?.map(N=>l.jsx("option",{value:N.id,children:N.name},N.id))]})]}),a.length>0&&l.jsx("div",{className:"px-4 pb-4 max-h-60 overflow-y-auto",children:l.jsx("div",{className:"space-y-2",children:a.map((N,I)=>l.jsxs("div",{className:"flex items-center gap-3 p-3 bg-bambu-dark rounded-lg",children:[l.jsx(oG,{className:"w-5 h-5 text-bambu-gray flex-shrink-0"}),l.jsx("span",{className:"flex-1 text-white text-sm truncate",children:N.file.name}),l.jsxs("span",{className:"text-xs text-bambu-gray",children:[(N.file.size/(1024*1024)).toFixed(1)," MB"]}),N.status==="pending"&&l.jsx("button",{onClick:()=>S(I),className:"text-bambu-gray hover:text-red-400 transition-colors",disabled:k,children:l.jsx(Wt,{className:"w-4 h-4"})}),N.status==="uploading"&&l.jsx(At,{className:"w-4 h-4 text-bambu-green animate-spin"}),N.status==="success"&&l.jsx(fi,{className:"w-4 h-4 text-bambu-green"}),N.status==="error"&&l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("span",{className:"text-xs text-red-400",children:N.error}),l.jsx(lo,{className:"w-4 h-4 text-red-400"})]})]},`${N.file.name}-${I}`))})}),f&&l.jsx("div",{className:"px-4 pb-4",children:l.jsx("div",{className:"p-3 bg-bambu-dark rounded-lg",children:l.jsxs("p",{className:"text-sm text-white",children:[l.jsx("span",{className:"text-bambu-green",children:f.uploaded})," uploaded",f.failed>0&&l.jsxs(l.Fragment,{children:[", ",l.jsx("span",{className:"text-red-400",children:f.failed})," failed"]})]})})}),l.jsxs("div",{className:"flex gap-3 p-4 border-t border-bambu-dark-tertiary",children:[l.jsx(Le,{variant:"secondary",onClick:t,className:"flex-1",children:f?"Close":"Cancel"}),!f&&l.jsx(Le,{onClick:A,disabled:T===0||k,className:"flex-1",children:k?l.jsxs(l.Fragment,{children:[l.jsx(At,{className:"w-4 h-4 animate-spin"}),"Uploading..."]}):l.jsxs(l.Fragment,{children:[l.jsx(vs,{className:"w-4 h-4"}),"Upload ",T>0&&`(${T})`]})})]})]})})})}const mUe=["Adhesion failure","Spaghetti / Detached","Layer shift","Clogged nozzle","Filament runout","Warping","Stringing","Under-extrusion","Power failure","User cancelled","Other"],gUe=[{value:"completed",label:"Completed"},{value:"failed",label:"Failed"},{value:"aborted",label:"Cancelled"},{value:"printing",label:"Printing"}];function xUe({archive:t,onClose:e,existingTags:n=[]}){E.useEffect(()=>{const X=te=>{te.key==="Escape"&&e()};return window.addEventListener("keydown",X),()=>window.removeEventListener("keydown",X)},[e]);const r=En(),[i,a]=E.useState(t.print_name||""),[s,o]=E.useState(t.printer_id),[c,u]=E.useState(t.project_id??null),[d,f]=E.useState(t.notes||""),[g,m]=E.useState(t.tags||""),[x,v]=E.useState(t.failure_reason||""),[y,b]=E.useState(t.status),[M,S]=E.useState(t.photos||[]),[A,T]=E.useState(!1),[k,N]=E.useState(!1),I=E.useRef(null),C=E.useRef(null),D=E.useRef(null),{data:F}=vt({queryKey:["printers"],queryFn:ke.getPrinters}),{data:O}=vt({queryKey:["projects"],queryFn:()=>ke.getProjects()}),{data:q}=vt({queryKey:["archives"],queryFn:()=>ke.getArchives(void 0,1e3,0),enabled:n.length===0}),R=n.length>0?n:[...new Set(q?.flatMap(X=>X.tags?.split(",").map(te=>te.trim())||[]).filter(Boolean)||[])].sort(),W=g.split(",").map(X=>X.trim()).filter(Boolean),K=R.filter(X=>!W.includes(X)),G=X=>{if(!W.includes(X)){const te=[...W,X].join(", ");m(te)}D.current!==null&&clearTimeout(D.current),I.current?.focus()},ee=X=>{const te=W.filter(fe=>fe!==X).join(", ");m(te)},Z=wt({mutationFn:X=>ke.updateArchive(t.id,X),onSuccess:()=>{r.invalidateQueries({queryKey:["archives"]}),r.invalidateQueries({queryKey:["projects"]}),e()}}),Q=async X=>{const te=X.target.files?.[0];if(te){T(!0);try{const fe=await ke.uploadArchivePhoto(t.id,te);S(fe.photos),r.invalidateQueries({queryKey:["archives"]})}catch(fe){console.error("Failed to upload photo:",fe)}finally{T(!1),C.current&&(C.current.value="")}}},U=async X=>{try{const te=await ke.deleteArchivePhoto(t.id,X);S(te.photos||[]),r.invalidateQueries({queryKey:["archives"]})}catch(te){console.error("Failed to delete photo:",te)}},$=X=>{X.preventDefault();const te={print_name:i||void 0,printer_id:s,project_id:c,notes:d||void 0,tags:g||void 0};y!==t.status&&(te.status=y),y==="failed"||y==="aborted"?te.failure_reason=x||void 0:(t.status==="failed"||t.status==="aborted")&&(te.failure_reason=null),Z.mutate(te)};return l.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:e,children:l.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:X=>X.stopPropagation(),children:[l.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[l.jsx("h2",{className:"text-lg font-semibold text-white",children:"Edit Archive"}),l.jsx("button",{onClick:e,className:"text-bambu-gray hover:text-white transition-colors",children:l.jsx(Wt,{className:"w-5 h-5"})})]}),l.jsxs("form",{onSubmit:$,className:"p-6 space-y-4 overflow-y-auto flex-1",children:[l.jsxs("div",{children:[l.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Name"}),l.jsx("input",{type:"text",value:i,onChange:X=>a(X.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"})]}),l.jsxs("div",{children:[l.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Printer"}),l.jsxs("select",{value:s??"",onChange:X=>o(X.target.value?Number(X.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:[l.jsx("option",{value:"",children:"No printer"}),F?.map(X=>l.jsx("option",{value:X.id,children:X.name},X.id))]})]}),l.jsxs("div",{children:[l.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[l.jsx(qu,{className:"w-4 h-4 inline mr-1"}),"Project"]}),l.jsxs("select",{value:c??"",onChange:X=>u(X.target.value?Number(X.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:[l.jsx("option",{value:"",children:"No project"}),O?.map(X=>l.jsx("option",{value:X.id,children:X.name},X.id))]})]}),l.jsxs("div",{children:[l.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Notes"}),l.jsx("textarea",{value:d,onChange:X=>f(X.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..."})]}),l.jsxs("div",{children:[l.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Tags"}),W.length>0&&l.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:W.map(X=>l.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 bg-bambu-dark-tertiary rounded text-sm text-white",children:[l.jsx(E0,{className:"w-3 h-3"}),X,l.jsx("button",{type:"button",onClick:()=>ee(X),className:"ml-0.5 text-bambu-gray hover:text-white",children:l.jsx(Wt,{className:"w-3 h-3"})})]},X))}),l.jsxs("div",{className:"relative",children:[l.jsx("input",{ref:I,type:"text",value:g,onChange:X=>m(X.target.value),onFocus:()=>{D.current!==null&&clearTimeout(D.current),N(!0)},onBlur:()=>{D.current=window.setTimeout(()=>N(!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:W.length>0?"Add more tags...":"Add tags..."}),k&&K.length>0&&l.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:[l.jsx("div",{className:"p-2 text-xs text-bambu-gray border-b border-bambu-dark-tertiary",children:"Existing tags (click to add)"}),l.jsx("div",{className:"p-2 flex flex-wrap gap-1.5",children:K.map(X=>l.jsx("button",{type:"button",onClick:()=>G(X),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:X},X))})]})]})]}),l.jsxs("div",{children:[l.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Status"}),l.jsx("select",{value:y,onChange:X=>{b(X.target.value),X.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:gUe.map(X=>l.jsx("option",{value:X.value,children:X.label},X.value))})]}),(y==="failed"||y==="aborted")&&l.jsxs("div",{children:[l.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Failure Reason"}),l.jsxs("select",{value:x,onChange:X=>v(X.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:[l.jsx("option",{value:"",children:"Select reason..."}),mUe.map(X=>l.jsx("option",{value:X,children:X},X))]})]}),l.jsxs("div",{children:[l.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[l.jsx(b0,{className:"w-4 h-4 inline mr-1"}),"Photos of Printed Result"]}),l.jsxs("div",{className:"flex flex-wrap gap-2 mb-2",children:[M.map(X=>l.jsxs("div",{className:"relative group",children:[l.jsx("img",{src:ke.getArchivePhotoUrl(t.id,X),alt:"Print result",className:"w-20 h-20 object-cover rounded-lg border border-bambu-dark-tertiary"}),l.jsx("button",{type:"button",onClick:()=>U(X),className:"absolute -top-1 -right-1 p-1 bg-red-500 rounded-full opacity-0 group-hover:opacity-100 transition-opacity",children:l.jsx(Rn,{className:"w-3 h-3 text-white"})})]},X)),l.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:[l.jsx("input",{ref:C,type:"file",accept:"image/jpeg,image/png,image/webp",onChange:Q,className:"hidden",disabled:A}),A?l.jsx(At,{className:"w-6 h-6 text-bambu-gray animate-spin"}):l.jsx(pr,{className:"w-6 h-6 text-bambu-gray"})]})]}),l.jsx("p",{className:"text-xs text-bambu-gray",children:"Click + to add photos of your printed result"})]}),l.jsxs("div",{className:"flex gap-3 pt-2",children:[l.jsx(Le,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:"Cancel"}),l.jsxs(Le,{type:"submit",disabled:Z.isPending,className:"flex-1",children:[l.jsx(Ro,{className:"w-4 h-4"}),Z.isPending?"Saving...":"Save"]})]})]})]})})}function bUe({x:t,y:e,items:n,onClose:r}){const i=E.useRef(null),[a,s]=E.useState(null),o=E.useRef(null),[c,u]=E.useState({x:t,y:e,visible:!1}),[d,f]=E.useState(!1);E.useEffect(()=>{const x=b=>{i.current&&!i.current.contains(b.target)&&r()},v=b=>{b.key==="Escape"&&r()},y=()=>{r()};return document.addEventListener("mousedown",x),document.addEventListener("keydown",v),document.addEventListener("scroll",y,!0),()=>{document.removeEventListener("mousedown",x),document.removeEventListener("keydown",v),document.removeEventListener("scroll",y,!0),o.current&&clearTimeout(o.current)}},[r]),E.useLayoutEffect(()=>{if(i.current){i.current.style.visibility="hidden",i.current.style.display="block";const x=i.current.getBoundingClientRect(),v=window.innerWidth,y=window.innerHeight,b=8;let M=t,S=e;t+x.width>v-b&&(M=Math.max(b,v-x.width-b)),My-b&&(S=Math.max(b,y-x.height-b)),SA),u({x:M,y:S,visible:!0})}},[t,e]);const g=x=>{o.current&&(clearTimeout(o.current),o.current=null),s(x)},m=()=>{o.current=window.setTimeout(()=>{s(null)},150)};return l.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,v)=>{if(x.divider)return l.jsx("div",{className:"my-1 border-t border-bambu-dark-tertiary"},v);const y=x.submenu&&x.submenu.length>0;return l.jsxs("div",{className:"relative",onMouseEnter:()=>y&&g(v),onMouseLeave:()=>y&&m(),children:[l.jsxs("button",{onMouseEnter:()=>y&&g(v),onClick:()=>{y?s(a===v?null:v):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"} ${y&&a===v?"bg-bambu-dark-tertiary":""}`,children:[x.icon&&l.jsx("span",{className:"w-4 h-4 flex-shrink-0 flex items-center justify-center",children:x.icon}),l.jsx("span",{className:"flex-1",children:x.label}),y&&l.jsx(df,{className:"w-4 h-4 text-bambu-gray"})]}),y&&a===v&&l.jsx("div",{className:`absolute top-0 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"}`,onMouseEnter:()=>{o.current&&(clearTimeout(o.current),o.current=null)},onMouseLeave:()=>m(),children:x.submenu.map((b,M)=>l.jsxs("button",{onClick:()=>{b.disabled||(b.onClick(),r())},disabled:b.disabled,className:`w-full flex items-center gap-2 px-3 py-2 text-sm text-left transition-colors ${b.disabled?"text-bambu-gray cursor-not-allowed":b.danger?"text-red-400 hover:bg-red-400/10":"text-white hover:bg-bambu-dark-tertiary"}`,children:[b.icon&&l.jsx("span",{className:"w-4 h-4 flex-shrink-0 flex items-center justify-center",children:b.icon}),b.label]},M))})]},v)})})}function yUe({selectedIds:t,existingTags:e,onClose:n}){const r=En(),{showToast:i}=ai(),[a,s]=E.useState(""),[o,c]=E.useState(new Set),[u,d]=E.useState("add");E.useEffect(()=>{const v=y=>{y.key==="Escape"&&n()};return window.addEventListener("keydown",v),()=>window.removeEventListener("keydown",v)},[n]);const f=wt({mutationFn:async()=>{const v=Array.from(o);let y=0;for(const b of t)try{const M=await ke.getArchive(b),S=M.tags?M.tags.split(",").map(T=>T.trim()).filter(Boolean):[];let A;u==="add"?A=[...new Set([...S,...v])]:A=S.filter(T=>!o.has(T)),await ke.updateArchive(b,{tags:A.join(", ")}),y++}catch(M){throw console.error(`Failed to update archive ${b}:`,M),new Error(`Failed on archive ${b}: ${M instanceof Error?M.message:"Unknown error"}`)}return{count:y,mode:u,tags:v}},onSuccess:({count:v,mode:y,tags:b})=>{r.invalidateQueries({queryKey:["archives"]}),i(`${y==="add"?"Added":"Removed"} ${b.length} tag${b.length!==1?"s":""} ${y==="add"?"to":"from"} ${v} archive${v!==1?"s":""}`),n()},onError:v=>{i(v.message||"Failed to update tags","error")}}),g=v=>{c(y=>{const b=new Set(y);return b.has(v)?b.delete(v):b.add(v),b})},m=()=>{a.trim()&&!o.has(a.trim())&&(c(v=>new Set([...v,a.trim()])),s(""))},x=v=>{v.key==="Enter"&&(v.preventDefault(),m())};return l.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:l.jsx(Nt,{className:"w-full max-w-md",children:l.jsxs(Rt,{className:"p-0",children:[l.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx(E0,{className:"w-5 h-5 text-bambu-green"}),l.jsx("h2",{className:"text-xl font-semibold text-white",children:u==="add"?"Add Tags":"Remove Tags"})]}),l.jsx("button",{onClick:n,className:"text-bambu-gray hover:text-white transition-colors",children:l.jsx(Wt,{className:"w-5 h-5"})})]}),l.jsxs("div",{className:"p-4 space-y-4",children:[l.jsxs("p",{className:"text-sm text-bambu-gray",children:[u==="add"?"Add":"Remove"," tags for ",t.length," selected archive",t.length!==1?"s":""]}),l.jsxs("div",{className:"flex gap-2",children:[l.jsx(Le,{size:"sm",variant:u==="add"?"primary":"secondary",onClick:()=>d("add"),children:"Add Tags"}),l.jsx(Le,{size:"sm",variant:u==="remove"?"primary":"secondary",onClick:()=>d("remove"),children:"Remove Tags"})]}),u==="add"&&l.jsxs("div",{className:"flex gap-2",children:[l.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=>s(v.target.value),onKeyDown:x}),l.jsx(Le,{size:"sm",variant:"secondary",onClick:m,disabled:!a.trim(),children:l.jsx(pr,{className:"w-4 h-4"})})]}),e.length>0&&l.jsxs("div",{children:[l.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:"Existing tags:"}),l.jsx("div",{className:"flex flex-wrap gap-2",children:e.map(v=>l.jsx("button",{onClick:()=>g(v),className:`px-2 py-1 rounded text-sm transition-colors ${o.has(v)?"bg-bambu-green text-white":"bg-bambu-dark-tertiary text-bambu-gray-light hover:bg-bambu-dark"}`,children:v},v))})]}),o.size>0&&l.jsxs("div",{children:[l.jsxs("p",{className:"text-xs text-bambu-gray mb-2",children:["Tags to ",u==="add"?"add":"remove",":"]}),l.jsx("div",{className:"flex flex-wrap gap-2",children:Array.from(o).map(v=>l.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,l.jsx("button",{onClick:()=>g(v),className:"hover:opacity-70",children:l.jsx(Wt,{className:"w-3 h-3"})})]},v))})]})]}),l.jsxs("div",{className:"flex gap-3 p-4 border-t border-bambu-dark-tertiary",children:[l.jsx(Le,{variant:"secondary",onClick:n,className:"flex-1",children:"Cancel"}),l.jsx(Le,{onClick:()=>f.mutate(),disabled:o.size===0||f.isPending,className:"flex-1",children:f.isPending?l.jsxs(l.Fragment,{children:[l.jsx(At,{className:"w-4 h-4 animate-spin"}),"Processing..."]}):l.jsxs(l.Fragment,{children:[l.jsx(E0,{className:"w-4 h-4"}),u==="add"?"Add Tags":"Remove Tags"]})})]})]})})})}function vUe(t,e){return new Date(t,e+1,0).getDate()}function _Ue(t,e){return new Date(t,e,1).getDay()}const wUe=["January","February","March","April","May","June","July","August","September","October","November","December"],SUe=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];function MUe({archives:t,onArchiveClick:e}){const n=new Date,[r,i]=E.useState(n.getMonth()),[a,s]=E.useState(n.getFullYear()),[o,c]=E.useState(null),u=E.useMemo(()=>{const b=new Map;return t.forEach(M=>{const S=new Date(M.completed_at||M.created_at),A=`${S.getFullYear()}-${String(S.getMonth()+1).padStart(2,"0")}-${String(S.getDate()).padStart(2,"0")}`,T=b.get(A)||[];T.push(M),b.set(A,T)}),b},[t]),d=vUe(a,r),f=_Ue(a,r),g=()=>{r===0?(i(11),s(a-1)):i(r-1)},m=()=>{r===11?(i(0),s(a+1)):i(r+1)},x=()=>{i(n.getMonth()),s(n.getFullYear())},v=[];for(let b=0;bl.jsx("div",{className:"text-center text-xs text-bambu-gray py-2",children:b},b))}),l.jsx("div",{className:"grid grid-cols-7 gap-1",children:v.map((b,M)=>{if(b===null)return l.jsx("div",{className:"aspect-square"},`empty-${M}`);const S=`${a}-${String(r+1).padStart(2,"0")}-${String(b).padStart(2,"0")}`,A=u.get(S)||[],T=A.length>0,k=b===n.getDate()&&r===n.getMonth()&&a===n.getFullYear(),N=S===o,I=A.filter(D=>D.status==="completed").length,C=A.filter(D=>D.status==="failed").length;return l.jsxs("button",{onClick:()=>c(N?null:S),className:`aspect-square rounded-lg p-1 flex flex-col items-center justify-center transition-colors relative ${N?"bg-bambu-green text-white":k?"bg-bambu-green/20 text-white ring-2 ring-bambu-green":T?"bg-bambu-dark-tertiary hover:bg-bambu-dark-tertiary/70 text-white":"hover:bg-bambu-dark-tertiary/50 text-bambu-gray"}`,children:[l.jsx("span",{className:`text-sm font-medium ${k&&!N?"text-bambu-green":""}`,children:b}),T&&l.jsxs("div",{className:"absolute bottom-1 left-1/2 -translate-x-1/2 flex items-center gap-1",children:[l.jsx("div",{className:`w-2 h-2 rounded-full ${C>0&&I===0?"bg-red-400":C>0?"bg-yellow-400":"bg-green-400"}`}),l.jsx("span",{className:"text-xs font-medium",children:A.length})]})]},b)})}),l.jsx("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:l.jsxs("div",{className:"grid grid-cols-3 gap-4 text-center",children:[l.jsxs("div",{children:[l.jsx("div",{className:"text-2xl font-bold text-white",children:t.filter(b=>{const M=new Date(b.completed_at||b.created_at);return M.getMonth()===r&&M.getFullYear()===a}).length}),l.jsx("div",{className:"text-xs text-bambu-gray",children:"Prints this month"})]}),l.jsxs("div",{children:[l.jsx("div",{className:"text-2xl font-bold text-green-400",children:t.filter(b=>{const M=new Date(b.completed_at||b.created_at);return M.getMonth()===r&&M.getFullYear()===a&&b.status==="completed"}).length}),l.jsx("div",{className:"text-xs text-bambu-gray",children:"Successful"})]}),l.jsxs("div",{children:[l.jsx("div",{className:"text-2xl font-bold text-red-400",children:t.filter(b=>{const M=new Date(b.completed_at||b.created_at);return M.getMonth()===r&&M.getFullYear()===a&&b.status==="failed"}).length}),l.jsx("div",{className:"text-xs text-bambu-gray",children:"Failed"})]})]})})]}),l.jsx("div",{className:"lg:w-80 bg-bambu-dark rounded-xl p-4",children:o?l.jsxs(l.Fragment,{children:[l.jsx("h3",{className:"text-sm font-medium text-bambu-gray mb-3",children:new Date(o+"T12:00:00").toLocaleDateString("en-US",{weekday:"long",month:"long",day:"numeric",year:"numeric"})}),y.length>0?l.jsx("div",{className:"space-y-2 max-h-96 overflow-y-auto",children:y.map(b=>l.jsxs("button",{onClick:()=>e?.(b),className:"w-full flex items-center gap-3 p-2 rounded-lg hover:bg-bambu-dark-tertiary transition-colors text-left",children:[b.thumbnail_path?l.jsx("img",{src:ke.getArchiveThumbnail(b.id),alt:"",className:"w-12 h-12 rounded object-cover"}):l.jsx("div",{className:"w-12 h-12 rounded bg-bambu-dark-tertiary flex items-center justify-center",children:l.jsx("span",{className:"text-xs text-bambu-gray",children:"3MF"})}),l.jsxs("div",{className:"flex-1 min-w-0",children:[l.jsx("p",{className:"text-sm text-white truncate",children:b.print_name||b.filename}),l.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[l.jsx("span",{className:b.status==="failed"?"text-red-400":"text-green-400",children:b.status==="failed"?"Failed":"Completed"}),b.filament_color&&l.jsx("div",{className:"flex gap-0.5",children:b.filament_color.split(",").map((M,S)=>l.jsx("div",{className:"w-3 h-3 rounded-full border border-white/20",style:{backgroundColor:M}},S))})]})]})]},b.id))}):l.jsx("p",{className:"text-sm text-bambu-gray",children:"No prints on this day"})]}):l.jsx("div",{className:"text-center py-8",children:l.jsx("p",{className:"text-sm text-bambu-gray",children:"Select a day to see prints"})})})]})}function EUe({archiveId:t,archiveName:e,onClose:n}){const r=ke.getArchiveQRCodeUrl(t,300);E.useEffect(()=>{const a=s=>{s.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 l.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:n,children:l.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary w-full max-w-sm",onClick:a=>a.stopPropagation(),children:[l.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[l.jsx("h2",{className:"text-lg font-semibold text-white",children:"QR Code"}),l.jsx("button",{onClick:n,className:"text-bambu-gray hover:text-white transition-colors",children:l.jsx(Wt,{className:"w-5 h-5"})})]}),l.jsxs("div",{className:"p-6 flex flex-col items-center",children:[l.jsx("p",{className:"text-sm text-bambu-gray mb-4 text-center truncate max-w-full",children:e}),l.jsx("div",{className:"bg-white p-4 rounded-lg mb-4",children:l.jsx("img",{src:r,alt:"QR Code",className:"w-64 h-64"})}),l.jsx("p",{className:"text-xs text-bambu-gray mb-4 text-center",children:"Scan to open this archive"}),l.jsxs(Le,{onClick:i,className:"w-full",children:[l.jsx(Es,{className:"w-4 h-4"}),"Download QR Code"]})]})]})})}function AUe({archiveId:t,archiveName:e,photos:n,onClose:r,onDelete:i}){const[a,s]=E.useState(0),[o,c]=E.useState(!1);if(E.useEffect(()=>{const m=x=>{x.key==="Escape"&&r(),x.key==="ArrowLeft"&&s(v=>Math.max(0,v-1)),x.key==="ArrowRight"&&s(v=>Math.min(n.length-1,v+1))};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)},[r,n.length]),E.useEffect(()=>{a>=n.length&&s(Math.max(0,n.length-1))},[n.length,a]),n.length===0)return r(),null;const u=n[a],d=ke.getArchivePhotoUrl(t,u),f=()=>{const m=document.createElement("a");m.href=d,m.download=`${e}_photo_${a+1}.jpg`,m.click()},g=()=>{i&&c(!0)};return l.jsxs("div",{className:"fixed inset-0 bg-black/90 flex items-center justify-center z-50",onClick:r,children:[l.jsxs("div",{className:"relative w-full h-full flex flex-col",onClick:m=>m.stopPropagation(),children:[l.jsxs("div",{className:"flex items-center justify-between px-6 py-4 bg-black/50",children:[l.jsxs("div",{children:[l.jsx("h2",{className:"text-lg font-semibold text-white",children:e}),l.jsxs("p",{className:"text-sm text-bambu-gray",children:["Photo ",a+1," of ",n.length]})]}),l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsxs(Le,{variant:"secondary",size:"sm",onClick:f,children:[l.jsx(Es,{className:"w-4 h-4"}),"Download"]}),i&&l.jsx(Le,{variant:"secondary",size:"sm",onClick:g,className:"text-red-400 hover:text-red-300",children:l.jsx(Rn,{className:"w-4 h-4"})}),l.jsx("button",{onClick:r,className:"p-2 text-bambu-gray hover:text-white transition-colors",children:l.jsx(Wt,{className:"w-6 h-6"})})]})]}),l.jsxs("div",{className:"flex-1 min-h-0 flex items-center justify-center p-4 relative overflow-hidden",children:[a>0&&l.jsx("button",{onClick:()=>s(m=>m-1),className:"absolute left-4 z-10 p-3 bg-black/50 hover:bg-black/70 rounded-full transition-colors",children:l.jsx(Bh,{className:"w-8 h-8 text-white"})}),l.jsx("img",{src:d,alt:`Photo ${a+1}`,className:"max-w-full max-h-full object-contain rounded-lg",style:{maxHeight:"calc(100vh - 200px)"}}),as(m=>m+1),className:"absolute right-4 z-10 p-3 bg-black/50 hover:bg-black/70 rounded-full transition-colors",children:l.jsx(df,{className:"w-8 h-8 text-white"})})]}),n.length>1&&l.jsx("div",{className:"flex justify-center gap-2 p-4 bg-black/50",children:n.map((m,x)=>l.jsx("button",{onClick:()=>s(x),className:`w-16 h-16 rounded-lg overflow-hidden border-2 transition-colors ${x===a?"border-bambu-green":"border-transparent hover:border-bambu-gray"}`,children:l.jsx("img",{src:ke.getArchivePhotoUrl(t,m),alt:`Thumbnail ${x+1}`,className:"w-full h-full object-cover"})},m))})]}),o&&l.jsx(Qr,{title:"Delete Photo",message:"Delete this photo? This cannot be undone.",confirmText:"Delete",variant:"danger",onConfirm:()=>{i?.(u),c(!1)},onCancel:()=>c(!1)})]})}function Yi(t){this.content=t}Yi.prototype={constructor:Yi,find:function(t){for(var e=0;e>1}};Yi.from=function(t){if(t instanceof Yi)return t;var e=[];if(t)for(var n in t)e.push(n,t[n]);return new Yi(e)};function iQ(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 s=0;i.text[s]==a.text[s];s++)n++;return n}if(i.content.size||a.content.size){let s=iQ(i.content,a.content,n+1);if(s!=null)return s}n+=i.nodeSize}}function aQ(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 s=t.child(--i),o=e.child(--a),c=s.nodeSize;if(s==o){n-=c,r-=c;continue}if(!s.sameMarkup(o))return{a:n,b:r};if(s.isText&&s.text!=o.text){let u=0,d=Math.min(s.text.length,o.text.length);for(;ue&&r(c,i+o,a||null,s)!==!1&&c.content.size){let d=o+1;c.nodesBetween(Math.max(0,e-d),Math.min(c.content.size,n-d),r,i+d)}o=u}}descendants(e){this.nodesBetween(0,this.size,e)}textBetween(e,n,r,i){let a="",s=!0;return this.nodesBetween(e,n,(o,c)=>{let u=o.isText?o.text.slice(Math.max(e,c)-c,n-c):o.isLeaf?i?typeof i=="function"?i(o):i:o.type.spec.leafText?o.type.spec.leafText(o):"":"";o.isBlock&&(o.isLeaf&&u||o.isTextblock)&&r&&(s?s=!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,s=0;se&&((sn)&&(o.isText?o=o.cut(Math.max(0,e-s),Math.min(o.text.length,n-s)):o=o.cut(Math.max(0,e-s-1),Math.min(o.content.size,n-s-1))),r.push(o),i+=o.nodeSize),s=c}return new pt(r,i)}cutByIndex(e,n){return e==n?pt.empty:e==0&&n==this.content.length?this:new pt(this.content.slice(e,n))}replaceChild(e,n){let r=this.content[e];if(r==n)return this;let i=this.content.slice(),a=this.size+n.nodeSize-r.nodeSize;return i[e]=n,new pt(i,a)}addToStart(e){return new pt([e].concat(this.content),this.size+e.nodeSize)}addToEnd(e){return new pt(this.content.concat(e),this.size+e.nodeSize)}eq(e){if(this.content.length!=e.content.length)return!1;for(let n=0;nthis.size||e<0)throw new RangeError(`Position ${e} outside of fragment (${this})`);for(let n=0,r=0;;n++){let i=this.child(n),a=r+i.nodeSize;if(a>=e)return a==e?O_(n+1,a):O_(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 pt.empty;if(!Array.isArray(n))throw new RangeError("Invalid input for Fragment.fromJSON");return new pt(n.map(e.nodeFromJSON))}static fromArray(e){if(!e.length)return pt.empty;let n,r=0;for(let i=0;ithis.type.rank&&(n||(n=e.slice(0,i)),n.push(this),r=!0),n&&n.push(a)}}return n||(n=e.slice()),r||n.push(this),n}removeFromSet(e){for(let n=0;nr.type.rank-i.type.rank),n}};tr.none=[];class Hw extends Error{}class kt{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=oQ(this.content,e+this.openStart,n);return r&&new kt(r,this.openStart,this.openEnd)}removeBetween(e,n){return new kt(sQ(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 kt.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 kt(pt.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 kt(e,r,i)}}kt.empty=new kt(pt.empty,0,0);function sQ(t,e,n){let{index:r,offset:i}=t.findIndex(e),a=t.maybeChild(r),{index:s,offset:o}=t.findIndex(n);if(i==e||a.isText){if(o!=n&&!t.child(s).isText)throw new RangeError("Removing non-flat range");return t.cut(0,e).append(t.cut(n))}if(r!=s)throw new RangeError("Removing non-flat range");return t.replaceChild(r,a.copy(sQ(a.content,e-i-1,n-i-1)))}function oQ(t,e,n,r){let{index:i,offset:a}=t.findIndex(e),s=t.maybeChild(i);if(a==e||s.isText)return r&&!r.canReplace(i,i,n)?null:t.cut(0,e).append(n).append(t.cut(e));let o=oQ(s.content,e-a-1,n,s);return o&&t.replaceChild(i,s.copy(o))}function TUe(t,e,n){if(n.openStart>t.depth)throw new Hw("Inserted content deeper than insertion position");if(t.depth-n.openStart!=e.depth-n.openEnd)throw new Hw("Inconsistent open depths");return lQ(t,e,n,0)}function lQ(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 Jx(t,e,n,r){let i=(e||t).node(n),a=0,s=e?e.index(n):i.childCount;t&&(a=t.index(n),t.depth>n?a++:t.textOffset&&(Rh(t.nodeAfter,r),a++));for(let o=a;oi&&BP(t,e,i+1),s=r.depth>i&&BP(n,r,i+1),o=[];return Jx(null,t,i,o),a&&s&&e.index(i)==n.index(i)?(cQ(a,s),Rh(Dh(a,uQ(t,e,n,r,i+1)),o)):(a&&Rh(Dh(a,$w(t,e,i+1)),o),Jx(e,n,i,o),s&&Rh(Dh(s,$w(n,r,i+1)),o)),Jx(r,null,i,o),new pt(o)}function $w(t,e,n){let r=[];if(Jx(null,t,n,r),t.depth>n){let i=BP(t,e,n+1);Rh(Dh(i,$w(t,e,n+1)),r)}return Jx(e,null,n,r),new pt(r)}function CUe(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(pt.from(i));return{start:i.resolveNoCache(t.openStart+n),end:i.resolveNoCache(i.content.size-t.openEnd-n)}}class J0{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 Vw(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 s=e;;){let{index:o,offset:c}=s.content.findIndex(a),u=a-c;if(r.push(s,o,i+c),!u||(s=s.child(o),s.isText))break;a=u-1,i+=c+1}return new J0(n,r,a)}static resolveCached(e,n){let r=kV.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()+")"),dQ(this.marks,e)}contentMatchAt(e){let n=this.type.contentMatch.matchFragment(this.content,0,e);if(!n)throw new Error("Called contentMatchAt on a node with invalid content");return n}canReplace(e,n,r=pt.empty,i=0,a=r.childCount){let s=this.contentMatchAt(e).matchFragment(r,i,a),o=s&&s.matchFragment(this.content,n);if(!o||!o.validEnd)return!1;for(let c=i;cn.type.name)}`);this.content.forEach(n=>n.check())}toJSON(){let e={type:this.type.name};for(let n in this.attrs){e.attrs=this.attrs;break}return this.content.size&&(e.content=this.content.toJSON()),this.marks.length&&(e.marks=this.marks.map(n=>n.toJSON())),e}static fromJSON(e,n){if(!n)throw new RangeError("Invalid input for Node.fromJSON");let r;if(n.marks){if(!Array.isArray(n.marks))throw new RangeError("Invalid mark data for Node.fromJSON");r=n.marks.map(e.markFromJSON)}if(n.type=="text"){if(typeof n.text!="string")throw new RangeError("Invalid text node in JSON");return e.text(n.text,r)}let i=pt.fromJSON(e,n.content),a=e.nodeType(n.type).create(n.attrs,i,r);return a.type.checkAttrs(a.attrs),a}};Ju.prototype.text=void 0;class Gw extends Ju{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):dQ(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 Gw(this.type,this.attrs,this.text,e)}withText(e){return e==this.text?this:new Gw(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 dQ(t,e){for(let n=t.length-1;n>=0;n--)e=t[n].type.name+"("+e+")";return e}class af{constructor(e){this.validEnd=e,this.next=[],this.wrapCache=[]}static parse(e,n){let r=new RUe(e,n);if(r.next==null)return af.empty;let i=hQ(r);r.next&&r.err("Unexpected trailing text");let a=UUe(FUe(i));return zUe(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 s=0;s"+e.indexOf(r.next[s].next);return a}).join(` `)}}af.empty=new af(!0);class RUe{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 hQ(t){let e=[];do e.push(DUe(t));while(t.eat("|"));return e.length==1?e[0]:{type:"choice",exprs:e}}function DUe(t){let e=[];do e.push(jUe(t));while(t.next&&t.next!=")"&&t.next!="|");return e.length==1?e[0]:{type:"seq",exprs:e}}function jUe(t){let e=IUe(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=OUe(t,e);else break;return e}function PV(t){/\D/.test(t.next)&&t.err("Expected number, got '"+t.next+"'");let e=Number(t.next);return t.pos++,e}function OUe(t,e){let n=PV(t),r=n;return t.eat(",")&&(t.next!="}"?r=PV(t):r=-1),t.eat("}")||t.err("Unclosed braced range"),{type:"range",min:n,max:r,expr:e}}function LUe(t,e){let n=t.nodeTypes,r=n[e];if(r)return[r];let i=[];for(let a in n){let s=n[a];s.isInGroup(e)&&i.push(s)}return i.length==0&&t.err("No node type or group '"+e+"' found"),i}function IUe(t){if(t.eat("(")){let e=hQ(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=LUe(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 FUe(t){let e=[[]];return i(a(t,0),n()),e;function n(){return e.push([])-1}function r(s,o,c){let u={term:c,to:o};return e[s].push(u),u}function i(s,o){s.forEach(c=>c.to=o)}function a(s,o){if(s.type=="choice")return s.exprs.reduce((c,u)=>c.concat(a(u,o)),[]);if(s.type=="seq")for(let c=0;;c++){let u=a(s.exprs[c],o);if(c==s.exprs.length-1)return u;i(u,o=n())}else if(s.type=="star"){let c=n();return r(o,c),i(a(s.expr,c),c),[r(c)]}else if(s.type=="plus"){let c=n();return i(a(s.expr,o),c),i(a(s.expr,c),c),[r(c)]}else{if(s.type=="opt")return[r(o)].concat(a(s.expr,o));if(s.type=="range"){let c=o;for(let u=0;u{t[s].forEach(({term:o,to:c})=>{if(!o)return;let u;for(let d=0;d{u||i.push([o,u=[]]),u.indexOf(d)==-1&&u.push(d)})})});let a=e[r.join(",")]=new af(r.indexOf(t.length-1)>-1);for(let s=0;s-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:mQ(this.attrs,e)}create(e=null,n,r){if(this.isText)throw new Error("NodeType.create can't construct text nodes");return new Ju(this,this.computeAttrs(e),pt.from(n),tr.setFrom(r))}createChecked(e=null,n,r){return n=pt.from(n),this.checkContent(n),new Ju(this,this.computeAttrs(e),n,tr.setFrom(r))}createAndFill(e=null,n,r){if(e=this.computeAttrs(e),n=pt.from(n),n.size){let s=this.contentMatch.fillBefore(n);if(!s)return null;n=s.append(n)}let i=this.contentMatch.matchFragment(n),a=i&&i.fillBefore(pt.empty,!0);return a?new Ju(this,e,n.append(a),tr.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 bQ(a,n,s));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 BUe(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 HUe{constructor(e,n,r){this.hasDefault=Object.prototype.hasOwnProperty.call(r,"default"),this.default=r.default,this.validate=typeof r.validate=="string"?BUe(e,n,r.validate):r.validate}get isRequired(){return!this.hasDefault}}class qM{constructor(e,n,r,i){this.name=e,this.rank=n,this.schema=r,this.spec=i,this.attrs=xQ(e,i.attrs),this.excluded=null;let a=pQ(this.attrs);this.instance=a?new tr(this,a):null}create(e=null){return!e&&this.instance?this.instance:new tr(this,mQ(this.attrs,e))}static compile(e,n){let r=Object.create(null),i=0;return e.forEach((a,s)=>r[a]=new qM(a,i++,n,s)),r}removeFromSet(e){for(var n=0;n-1}}class yQ{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=Yi.from(e.nodes),n.marks=Yi.from(e.marks||{}),this.nodes=DV.compile(this.spec.nodes,this),this.marks=qM.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],s=a.spec.content||"",o=a.spec.marks;if(a.contentMatch=r[s]||(r[s]=af.parse(s,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=o=="_"?null:o?jV(this,o.split(" ")):o==""||!a.inlineContent?[]:null}for(let i in this.marks){let a=this.marks[i],s=a.spec.excludes;a.excluded=s==null?[a]:s==""?[]:jV(this,s.split(" "))}this.nodeFromJSON=i=>Ju.fromJSON(this,i),this.markFromJSON=i=>tr.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 DV){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 Gw(r,r.defaultAttrs,e,tr.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 jV(t,e){let n=[];for(let r=0;r-1)&&n.push(s=c)}if(!s)throw new SyntaxError("Unknown mark type: '"+e[r]+"'")}return n}function $Ue(t){return t.tag!=null}function VUe(t){return t.style!=null}let e0=class $P{constructor(e,n){this.schema=e,this.rules=n,this.tags=[],this.styles=[];let r=this.matchedStyles=[];n.forEach(i=>{if($Ue(i))this.tags.push(i);else if(VUe(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 LV(this,n,!1);return r.addAll(e,tr.none,n.from,n.to),r.finish()}parseSlice(e,n={}){let r=new LV(this,n,!0);return r.addAll(e,tr.none,n.from,n.to),kt.maxOpen(r.finish())}matchTag(e,n,r){for(let i=r?this.tags.indexOf(r)+1:0;ie.length&&(o.charCodeAt(e.length)!=61||o.slice(e.length+1)!=n))){if(s.getAttrs){let c=s.getAttrs(n);if(c===!1)continue;s.attrs=c||void 0}return s}}}static schemaRules(e){let n=[];function r(i){let a=i.priority==null?50:i.priority,s=0;for(;s{r(s=IV(s)),s.mark||s.ignore||s.clearMark||(s.mark=i)})}for(let i in e.nodes){let a=e.nodes[i].spec.parseDOM;a&&a.forEach(s=>{r(s=IV(s)),s.node||s.ignore||s.mark||(s.node=i)})}return n}static fromSchema(e){return e.cached.domParser||(e.cached.domParser=new $P(e,$P.schemaRules(e)))}};const vQ={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},GUe={head:!0,noscript:!0,object:!0,script:!0,style:!0,title:!0},_Q={ol:!0,ul:!0},eb=1,VP=2,t0=4;function OV(t,e,n){return e!=null?(e?eb:0)|(e==="full"?VP:0):t&&t.whitespace=="pre"?eb|VP:n&~t0}class L_{constructor(e,n,r,i,a,s){this.type=e,this.attrs=n,this.marks=r,this.solid=i,this.options=s,this.content=[],this.activeMarks=tr.none,this.match=a||(s&t0?null:e.contentMatch)}findWrapping(e){if(!this.match){if(!this.type)return[];let n=this.type.contentMatch.fillBefore(pt.from(e));if(n)this.match=this.type.contentMatch.matchFragment(n);else{let r=this.type.contentMatch,i;return(i=r.findWrapping(e.type))?(this.match=r,i):null}}return this.match.findWrapping(e.type)}finish(e){if(!(this.options&eb)){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=pt.from(this.content);return!e&&this.match&&(n=n.append(this.match.fillBefore(pt.empty,!0))),this.type?this.type.create(this.attrs,n,this.marks):n}inlineContext(e){return this.type?this.type.inlineContent:this.content.length?this.content[0].isInline:e.parentNode&&!vQ.hasOwnProperty(e.parentNode.nodeName.toLowerCase())}}class LV{constructor(e,n,r){this.parser=e,this.options=n,this.isOpen=r,this.open=0,this.localPreserveWS=!1;let i=n.topNode,a,s=OV(null,n.preserveWhitespace,0)|(r?t0:0);i?a=new L_(i.type,i.attrs,tr.none,!0,n.topMatch||i.type.contentMatch,s):r?a=new L_(null,null,tr.none,!0,null,s):a=new L_(e.schema.topNodeType,null,tr.none,!0,null,s),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&VP?"full":this.localPreserveWS||(i.options&eb)>0,{schema:s}=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(s.linebreakReplacement&&/[\r\n]/.test(r)&&this.top.findWrapping(s.linebreakReplacement.create())){let o=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)o=c;else break}}return n}addElementByRule(e,n,r,i){let a,s;if(n.node)if(s=this.parser.schema.nodes[n.node],s.isLeaf)this.insertNode(s.create(n.attrs),r,e.nodeName=="BR")||this.leafFallback(e,r);else{let c=this.enter(s,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 o=this.top;if(s&&s.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(o)&&this.open--}addAll(e,n,r,i){let a=r||0;for(let s=r?e.childNodes[r]:e.firstChild,o=i==null?null:e.childNodes[i];s!=o;s=s.nextSibling,++a)this.findAtPoint(e,a),this.addDOM(s,n);this.findAtPoint(e,a)}findPlace(e,n,r){let i,a;for(let s=this.open,o=0;s>=0;s--){let c=this.nodes[s],u=c.findWrapping(e);if(u&&(!i||i.length>u.length+o)&&(i=u,a=c,!u.length))break;if(c.solid){if(r)break;o+=2}}if(!i)return null;this.sync(a);for(let s=0;s(s.type?s.type.allowsMarkType(u.type):FV(u.type,e))?(c=u.addToSet(c),!1):!0),this.nodes.push(new L_(e,n,c,i,null,o)),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|=eb)}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),s=(o,c)=>{for(;o>=0;o--){let u=n[o];if(u==""){if(o==n.length-1||o==0)continue;for(;c>=a;c--)if(s(o-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 s(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 WUe(t){for(let e=t.firstChild,n=null;e;e=e.nextSibling){let r=e.nodeType==1?e.nodeName.toLowerCase():null;r&&_Q.hasOwnProperty(r)&&n?(n.appendChild(e),e=n):r=="li"?n=e:r&&(n=null)}}function qUe(t,e){return(t.matches||t.msMatchesSelector||t.webkitMatchesSelector||t.mozMatchesSelector).call(t,e)}function IV(t){let e={};for(let n in t)e[n]=t[n];return e}function FV(t,e){let n=e.schema.nodes;for(let r in n){let i=n[r];if(!i.allowsMarkType(t))continue;let a=[],s=o=>{a.push(o);for(let c=0;c{if(a.length||s.marks.length){let o=0,c=0;for(;o=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&&m1(DN(r),i(e,n),null,e.attrs)}static renderSpec(e,n,r=null,i){return m1(e,n,r,i)}static fromSchema(e){return e.cached.domSerializer||(e.cached.domSerializer=new xf(this.nodesFromSchema(e),this.marksFromSchema(e)))}static nodesFromSchema(e){let n=UV(e.nodes);return n.text||(n.text=r=>r.text),n}static marksFromSchema(e){return UV(e.marks)}}function UV(t){let e={};for(let n in t){let r=t[n].spec.toDOM;r&&(e[n]=r)}return e}function DN(t){return t.document||window.document}const zV=new WeakMap;function KUe(t){let e=zV.get(t);return e===void 0&&zV.set(t,e=XUe(t)),e}function XUe(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 s=i.indexOf(" ");s>0&&(n=i.slice(0,s),i=i.slice(s+1));let o,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 g=f.indexOf(" ");g>0?c.setAttributeNS(f.slice(0,g),f.slice(g+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:m,contentDOM:x}=m1(t,g,n,r);if(c.appendChild(m),x){if(o)throw new RangeError("Multiple content holes");o=x}}}return{dom:c,contentDOM:o}}const wQ=65535,SQ=Math.pow(2,16);function YUe(t,e){return t+e*SQ}function BV(t){return t&wQ}function ZUe(t){return(t-(t&wQ))/SQ}const MQ=1,EQ=2,g1=4,AQ=8;class GP{constructor(e,n,r){this.pos=e,this.delInfo=n,this.recover=r}get deleted(){return(this.delInfo&AQ)>0}get deletedBefore(){return(this.delInfo&(MQ|g1))>0}get deletedAfter(){return(this.delInfo&(EQ|g1))>0}get deletedAcross(){return(this.delInfo&g1)>0}}class bs{constructor(e,n=!1){if(this.ranges=e,this.inverted=n,!e.length&&bs.empty)return bs.empty}recover(e){let n=0,r=BV(e);if(!this.inverted)for(let i=0;ie)break;let u=this.ranges[o+a],d=this.ranges[o+s],f=c+u;if(e<=f){let g=u?e==c?-1:e==f?1:n:n,m=c+i+(g<0?0:d);if(r)return m;let x=e==(n<0?c:f)?null:YUe(o/3,e-c),v=e==c?EQ:e==f?MQ:g1;return(n<0?e!=c:e!=f)&&(v|=AQ),new GP(m,v,x)}i+=d-u}return r?e+i:new GP(e+i,0,null)}touches(e,n){let r=0,i=BV(n),a=this.inverted?2:1,s=this.inverted?1:2;for(let o=0;oe)break;let u=this.ranges[o+a],d=c+u;if(e<=d&&o==i*3)return!0;r+=this.ranges[o+s]-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 tb;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!s.isAtom||!o.type.allowsMarkType(this.mark.type)?s:s.mark(this.mark.addToSet(s.marks)),i),n.openStart,n.openEnd);return ei.fromReplace(e,this.from,this.to,a)}invert(){return new Oo(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 $u(n.pos,r.pos,this.mark)}merge(e){return e instanceof $u&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new $u(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 $u(n.from,n.to,e.markFromJSON(n.mark))}}xa.jsonID("addMark",$u);class Oo extends xa{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 kt(SO(n.content,i=>i.mark(this.mark.removeFromSet(i.marks)),e),n.openStart,n.openEnd);return ei.fromReplace(e,this.from,this.to,r)}invert(){return new $u(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 Oo(n.pos,r.pos,this.mark)}merge(e){return e instanceof Oo&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new Oo(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 Oo(n.from,n.to,e.markFromJSON(n.mark))}}xa.jsonID("removeMark",Oo);class Vu extends xa{constructor(e,n){super(),this.pos=e,this.mark=n}apply(e){let n=e.nodeAt(this.pos);if(!n)return ei.fail("No node at mark step's position");let r=n.type.create(n.attrs,null,this.mark.addToSet(n.marks));return ei.fromReplace(e,this.pos,this.pos+1,new kt(pt.from(r),0,n.isLeaf?0:1))}invert(e){let n=e.nodeAt(this.pos);if(n){let r=this.mark.addToSet(n.marks);if(r.length==n.marks.length){for(let i=0;ir.pos?null:new Ii(n.pos,r.pos,i,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 Ii(n.from,n.to,n.gapFrom,n.gapTo,kt.fromJSON(e,n.slice),n.insert,!!n.structure)}}xa.jsonID("replaceAround",Ii);function WP(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 s=r.node(a).maybeChild(r.indexAfter(a));for(;i>0;){if(!s||s.isLeaf)return!0;s=s.firstChild,i--}}return!1}function QUe(t,e,n,r){let i=[],a=[],s,o;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 g=Math.max(u,e),m=Math.min(u+c.nodeSize,n),x=r.addToSet(f);for(let v=0;vt.step(c)),a.forEach(c=>t.step(c))}function JUe(t,e,n,r){let i=[],a=0;t.doc.nodesBetween(e,n,(s,o)=>{if(!s.isInline)return;a++;let c=null;if(r instanceof qM){let u=s.marks,d;for(;d=r.isInSet(u);)(c||(c=[])).push(d),u=d.removeFromSet(u)}else r?r.isInSet(s.marks)&&(c=[r]):c=s.marks;if(c&&c.length){let u=Math.min(o+s.nodeSize,n);for(let d=0;dt.step(new Oo(s.from,s.to,s.style)))}function MO(t,e,n,r=n.contentMatch,i=!0){let a=t.doc.nodeAt(e),s=[],o=e+1;for(let c=0;c=0;c--)t.step(s[c])}function eze(t,e,n){return(e==0||t.canReplace(e,t.childCount))&&(n==t.childCount||t.canReplace(0,n))}function hg(t){let n=t.parent.content.cutByIndex(t.startIndex,t.endIndex);for(let r=t.depth,i=0,a=0;;--r){let s=t.$from.node(r),o=t.$from.index(r)+i,c=t.$to.indexAfter(r)-a;if(rn;x--)v||r.index(x)>0?(v=!0,d=pt.from(r.node(x).copy(d)),f++):c--;let g=pt.empty,m=0;for(let x=a,v=!1;x>n;x--)v||i.after(x+1)=0;s--){if(r.size){let o=n[s].type.contentMatch.matchFragment(r);if(!o||!o.validEnd)throw new RangeError("Wrapper type given to Transform.wrap does not form valid content of its parent wrapper")}r=pt.from(n[s].type.create(n[s].attrs,r))}let i=e.start,a=e.end;t.step(new Ii(i,a,i,a,new kt(r,0,0),n.length,!0))}function aze(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,(s,o)=>{let c=typeof i=="function"?i(s):i;if(s.isTextblock&&!s.hasMarkup(r,c)&&sze(t.doc,t.mapping.slice(a).map(o),r)){let u=null;if(r.schema.linebreakReplacement){let m=r.whitespace=="pre",x=!!r.contentMatch.matchType(r.schema.linebreakReplacement);m&&!x?u=!1:!m&&x&&(u=!0)}u===!1&&CQ(t,s,o,a),MO(t,t.mapping.slice(a).map(o,1),r,void 0,u===null);let d=t.mapping.slice(a),f=d.map(o,1),g=d.map(o+s.nodeSize,1);return t.step(new Ii(f,g,f+1,g-1,new kt(pt.from(r.create(c,null,s.marks)),0,0),1,!0)),u===!0&&TQ(t,s,o,a),!1}})}function TQ(t,e,n,r){e.forEach((i,a)=>{if(i.isText){let s,o=/\r?\n|\r/g;for(;s=o.exec(i.text);){let c=t.mapping.slice(r).map(n+1+a+s.index);t.replaceWith(c,c+1,e.type.schema.linebreakReplacement.create())}}})}function CQ(t,e,n,r){e.forEach((i,a)=>{if(i.type==i.type.schema.linebreakReplacement){let s=t.mapping.slice(r).map(n+1+a);t.replaceWith(s,s+1,e.type.schema.text(` @@ -8608,4 +8608,4 @@ Accuracy: ${t.time_accuracy.toFixed(0)}%`:t.actual_time_seconds?`Actual: ${Px(t. `+n+"]";if(typeof t=="object"){const r=Object.entries(t);return r.length===0?"{}":`{ `+r.map(([a,s])=>n+" "+JSON.stringify(a)+": "+ER(s,e+1)).join(`, `)+` -`+n+"}"}return String(t)}function yGe({setting:t,onClose:e,onDeleted:n,onDuplicate:r,onEdit:i}){const{showToast:a}=ai(),s=En(),[o,c]=E.useState(!1),{data:u,isLoading:d}=vt({queryKey:["cloudSettingDetail",t.setting_id],queryFn:()=>ke.getCloudSettingDetail(t.setting_id)}),f=wt({mutationFn:()=>ke.deleteCloudSetting(t.setting_id),onSuccess:()=>{a("Preset deleted"),s.invalidateQueries({queryKey:["cloudSettings"]}),n()},onError:x=>a(x.message,"error")}),g=hb(t.setting_id),m=xL(t.name,u?.setting?.inherits);return l.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:l.jsx(Nt,{className:"w-full max-w-3xl max-h-[90vh] flex flex-col overflow-hidden",children:l.jsxs(Rt,{className:"p-0 flex flex-col min-h-0 flex-1",children:[l.jsxs("div",{className:"flex-shrink-0 flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[l.jsxs("div",{className:"flex-1 min-w-0",children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("h2",{className:"text-xl font-semibold text-white truncate",children:t.name}),g&&l.jsx("span",{className:"px-2 py-0.5 text-xs font-medium bg-bambu-green/20 text-bambu-green rounded-full",children:"Editable"})]}),l.jsxs("div",{className:"flex items-center gap-2 mt-1 text-sm text-bambu-gray",children:[l.jsxs("span",{className:"capitalize",children:[t.type," preset"]}),m.printer&&l.jsxs(l.Fragment,{children:[l.jsx("span",{children:"•"}),l.jsx("span",{children:m.printer})]})]})]}),l.jsx("button",{onClick:e,className:"p-2 text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:l.jsx(Wt,{className:"w-5 h-5"})})]}),l.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto p-4",children:d?l.jsx("div",{className:"flex items-center justify-center py-16",children:l.jsx(At,{className:"w-8 h-8 text-bambu-green animate-spin"})}):u?l.jsx("pre",{className:"text-xs text-bambu-gray font-mono whitespace-pre-wrap break-all bg-bambu-dark p-4 rounded-lg border border-bambu-dark-tertiary overflow-x-auto max-w-full",children:ER(u)}):l.jsx("div",{className:"text-center py-16 text-bambu-gray",children:"Failed to load preset details"})}),o?l.jsxs("div",{className:"flex-shrink-0 p-4 border-t border-bambu-dark-tertiary bg-red-500/5",children:[l.jsxs("div",{className:"flex items-center gap-2 mb-3 text-red-400",children:[l.jsx(ti,{className:"w-5 h-5"}),l.jsx("span",{className:"font-medium",children:"Delete this preset?"})]}),l.jsxs("p",{className:"text-sm text-bambu-gray mb-4",children:['This will permanently delete "',t.name,'" from Bambu Cloud. This cannot be undone.']}),l.jsxs("div",{className:"flex gap-2",children:[l.jsx(Le,{variant:"secondary",onClick:()=>c(!1),disabled:f.isPending,className:"flex-1",children:"Cancel"}),l.jsxs(Le,{variant:"danger",onClick:()=>f.mutate(),disabled:f.isPending,className:"flex-1",children:[f.isPending?l.jsx(At,{className:"w-4 h-4 animate-spin"}):l.jsx(Rn,{className:"w-4 h-4"}),"Delete"]})]})]}):l.jsx("div",{className:"flex-shrink-0 p-4 border-t border-bambu-dark-tertiary",children:l.jsxs("div",{className:"flex gap-2",children:[l.jsx(Le,{variant:"secondary",onClick:e,className:"flex-1",children:"Close"}),l.jsxs(Le,{variant:"secondary",onClick:r,children:[l.jsx(Hh,{className:"w-4 h-4"}),"Duplicate"]}),g&&l.jsxs(l.Fragment,{children:[l.jsxs(Le,{variant:"secondary",onClick:i,disabled:d||!u,children:[l.jsx(rd,{className:"w-4 h-4"}),"Edit"]}),l.jsx(Le,{variant:"danger",onClick:()=>c(!0),children:l.jsx(Rn,{className:"w-4 h-4"})})]})]})})]})})})}function mte(){try{const t=localStorage.getItem("bambusy_preset_templates");return t?JSON.parse(t):[]}catch{return[]}}function gte(t){localStorage.setItem("bambusy_preset_templates",JSON.stringify(t))}function vGe({onClose:t,onApply:e}){const{showToast:n}=ai(),[r,i]=E.useState(mte),[a,s]=E.useState("all"),[o,c]=E.useState(null),[u,d]=E.useState(""),[f,g]=E.useState(""),[m,x]=E.useState("{}"),[v,y]=E.useState(null),[b,M]=E.useState(null),S=a==="all"?r:r.filter(O=>O.type===a),A=O=>{i(O),gte(O)},T=O=>{const q=r.filter(R=>R.id!==O);A(q),M(null),n("Template deleted")},k=O=>{c(O.id),d(O.name),g(O.description),x(JSON.stringify(O.settings,null,2)),y(null)},N=()=>{if(!(!o||!u.trim()))try{const O=JSON.parse(m),q=r.map(R=>R.id===o?{...R,name:u.trim(),description:f.trim(),settings:O}:R);A(q),c(null),n("Template updated")}catch(O){y(O.message)}},I=()=>{c(null),d(""),g(""),x("{}"),y(null)},C=O=>{const q=r.map(R=>R.id===O?{...R,showInModal:!R.showInModal}:R);A(q)},D={filament:{label:"Filament",icon:IR,color:"text-amber-400"},print:{label:"Process",icon:HS,color:"text-blue-400"},printer:{label:"Printer",icon:Ts,color:"text-purple-400"}},F=b?r.find(O=>O.id===b):null;return E.useEffect(()=>{const O=q=>{q.key==="Escape"&&(b?M(null):o?I():t())};return window.addEventListener("keydown",O),()=>window.removeEventListener("keydown",O)},[b,o,t]),l.jsxs("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:[F&&l.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-60",children:l.jsx(Nt,{className:"w-full max-w-md",children:l.jsxs(Rt,{className:"p-6",children:[l.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[l.jsx("div",{className:"p-2 bg-red-500/20 rounded-lg",children:l.jsx(ti,{className:"w-6 h-6 text-red-400"})}),l.jsxs("div",{children:[l.jsx("h3",{className:"text-lg font-semibold text-white",children:"Delete Template"}),l.jsx("p",{className:"text-sm text-bambu-gray",children:"This action cannot be undone"})]})]}),l.jsxs("p",{className:"text-white mb-6",children:['Are you sure you want to delete "',l.jsx("span",{className:"font-medium",children:F.name}),'"?']}),l.jsxs("div",{className:"flex gap-2",children:[l.jsx(Le,{variant:"secondary",onClick:()=>M(null),className:"flex-1",children:"Cancel"}),l.jsxs(Le,{onClick:()=>T(b),className:"flex-1 bg-red-500 hover:bg-red-600",children:[l.jsx(Rn,{className:"w-4 h-4"}),"Delete"]})]})]})})}),l.jsx(Nt,{className:"w-full max-w-2xl max-h-[80vh] flex flex-col",children:l.jsxs(Rt,{className:"p-0 flex flex-col h-full",children:[l.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[l.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[l.jsx(M0,{className:"w-5 h-5 text-amber-400"}),"Quick Templates"]}),l.jsx("button",{onClick:t,className:"text-bambu-gray hover:text-white",children:l.jsx(Wt,{className:"w-5 h-5"})})]}),l.jsxs("div",{className:"flex items-center gap-2 p-4 border-b border-bambu-dark-tertiary",children:[l.jsx("span",{className:"text-sm text-bambu-gray",children:"Type:"}),["all","filament","print","printer"].map(O=>l.jsx("button",{onClick:()=>s(O),className:`px-3 py-1 text-sm rounded-lg transition-colors ${a===O?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:O==="all"?"All":D[O].label},O))]}),l.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:S.length===0?l.jsxs("div",{className:"text-center py-12 text-bambu-gray",children:[l.jsx(M0,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),l.jsx("p",{children:"No templates yet"}),l.jsx("p",{className:"text-sm mt-1",children:"Create templates from the preset editor"})]}):l.jsx("div",{className:"space-y-2",children:S.map(O=>{const q=D[O.type],R=q.icon;return o===O.id?l.jsxs("div",{className:"p-4 bg-bambu-dark rounded-lg border border-bambu-green",children:[l.jsxs("div",{className:"grid grid-cols-2 gap-3 mb-3",children:[l.jsx("input",{type:"text",value:u,onChange:W=>d(W.target.value),placeholder:"Template name",className:"px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none",autoFocus:!0}),l.jsx("input",{type:"text",value:f,onChange:W=>g(W.target.value),placeholder:"Description",className:"px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none"})]}),l.jsxs("div",{className:"mb-3",children:[l.jsx("label",{className:"text-xs text-bambu-gray mb-1 block",children:"Settings (JSON)"}),l.jsx("textarea",{value:m,onChange:W=>{x(W.target.value),y(null)},rows:6,className:`w-full px-3 py-2 bg-bambu-dark-secondary border rounded text-white text-sm font-mono focus:outline-none ${v?"border-red-500":"border-bambu-dark-tertiary focus:border-bambu-green"}`}),v&&l.jsx("p",{className:"text-xs text-red-400 mt-1",children:v})]}),l.jsxs("div",{className:"flex gap-2",children:[l.jsxs(Le,{size:"sm",onClick:N,disabled:!u.trim(),children:[l.jsx(Ro,{className:"w-4 h-4"}),"Save"]}),l.jsx(Le,{size:"sm",variant:"secondary",onClick:I,children:"Cancel"})]})]},O.id):l.jsxs("div",{className:"flex items-center gap-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary hover:border-bambu-gray-dark transition-colors",children:[l.jsx(R,{className:`w-5 h-5 ${q.color} flex-shrink-0`}),l.jsxs("div",{className:"flex-1 min-w-0",children:[l.jsx("p",{className:"text-sm font-medium text-white",children:O.name}),l.jsx("p",{className:"text-xs text-bambu-gray truncate",children:O.description})]}),l.jsxs("span",{className:"text-xs text-bambu-gray-dark px-2 py-1 bg-bambu-dark-secondary rounded",children:[Object.keys(O.settings).length," fields"]}),l.jsx("button",{onClick:()=>C(O.id),className:`p-1 transition-colors ${O.showInModal?"text-bambu-green hover:text-bambu-green/70":"text-bambu-gray hover:text-white"}`,title:O.showInModal?"Shown in modals":"Hidden in modals",children:O.showInModal?l.jsx(mm,{className:"w-4 h-4"}):l.jsx(FR,{className:"w-4 h-4"})}),l.jsx("button",{onClick:()=>e(O),className:"px-3 py-1 text-xs bg-bambu-green/20 text-bambu-green rounded hover:bg-bambu-green/30 transition-colors",children:"Apply"}),l.jsx("button",{onClick:()=>k(O),className:"p-1 text-bambu-gray hover:text-white",title:"Edit",children:l.jsx(rd,{className:"w-4 h-4"})}),l.jsx("button",{onClick:()=>M(O.id),className:"p-1 text-bambu-gray hover:text-red-400",title:"Delete",children:l.jsx(Rn,{className:"w-4 h-4"})})]},O.id)})})})]})})]})}function xte({onClose:t,leftPreset:e,rightPreset:n,leftLabel:r,rightLabel:i}){const[a,s]=E.useState("changes"),[o,c]=E.useState(""),u=E.useMemo(()=>{const m=new Set([...Object.keys(e),...Object.keys(n)]),x=[];for(const v of m){if(v==="inherits"||v==="version")continue;const y=e[v],b=n[v],M=v in e,S=v in n;let A;!M&&S?A="added":M&&!S?A="removed":JSON.stringify(y)!==JSON.stringify(b)?A="changed":A="same",x.push({key:v,left:y,right:b,status:A})}return x.sort((v,y)=>{const b={changed:0,added:1,removed:2,same:3};return b[v.status]!==b[y.status]?b[v.status]-b[y.status]:v.key.localeCompare(y.key)})},[e,n]),d=E.useMemo(()=>{let m=[...u];if(a==="changes"&&(m=m.filter(x=>x.status!=="same")),o){const x=o.toLowerCase();m=m.filter(v=>v.key.toLowerCase().includes(x)||String(v.left).toLowerCase().includes(x)||String(v.right).toLowerCase().includes(x))}return m},[u,a,o]),f=E.useMemo(()=>({added:u.filter(m=>m.status==="added").length,removed:u.filter(m=>m.status==="removed").length,changed:u.filter(m=>m.status==="changed").length,same:u.filter(m=>m.status==="same").length}),[u]),g=m=>{if(m===void 0)return"—";if(m===null)return"null";if(Array.isArray(m))return m.length===0?"[]":m.length===1?String(m[0]):m.join(", ");if(typeof m=="object")return JSON.stringify(m);const x=String(m);if(x.includes("\\n")||x.length>100){const v=x.split("\\n").length;if(v>1)return`[${v} lines of G-code/script]`;if(x.length>100)return x.substring(0,100)+"…"}return x};return E.useEffect(()=>{const m=x=>{x.key==="Escape"&&t()};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)},[t]),l.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:l.jsx(Nt,{className:"w-full max-w-4xl max-h-[85vh] flex flex-col overflow-hidden",children:l.jsxs(Rt,{className:"p-0 flex flex-col min-h-0 flex-1",children:[l.jsxs("div",{className:"flex-shrink-0 flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[l.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[l.jsx(Qp,{className:"w-5 h-5 text-blue-400"}),"Compare Presets"]}),l.jsx("button",{onClick:t,className:"text-bambu-gray hover:text-white",children:l.jsx(Wt,{className:"w-5 h-5"})})]}),l.jsxs("div",{className:"flex-shrink-0 grid grid-cols-2 gap-4 p-4 border-b border-bambu-dark-tertiary bg-bambu-dark",children:[l.jsxs("div",{className:"text-center",children:[l.jsx("span",{className:"text-sm text-bambu-gray",children:"Left:"}),l.jsx("p",{className:"text-white font-medium truncate",children:r})]}),l.jsxs("div",{className:"text-center",children:[l.jsx("span",{className:"text-sm text-bambu-gray",children:"Right:"}),l.jsx("p",{className:"text-white font-medium truncate",children:i})]})]}),l.jsxs("div",{className:"flex-shrink-0 flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[l.jsxs("div",{className:"flex items-center gap-4 text-sm",children:[l.jsxs("span",{className:"flex items-center gap-1 text-green-400",children:[l.jsx(pr,{className:"w-3.5 h-3.5"}),f.added," added"]}),l.jsxs("span",{className:"flex items-center gap-1 text-red-400",children:[l.jsx(Rk,{className:"w-3.5 h-3.5"}),f.removed," removed"]}),l.jsxs("span",{className:"flex items-center gap-1 text-amber-400",children:[l.jsx(Tk,{className:"w-3.5 h-3.5"}),f.changed," changed"]}),l.jsxs("span",{className:"flex items-center gap-1 text-bambu-gray",children:[l.jsx(RA,{className:"w-3.5 h-3.5"}),f.same," same"]})]}),l.jsxs("div",{className:"flex items-center gap-3",children:[l.jsxs("div",{className:"relative",children:[l.jsx(id,{className:"absolute left-2 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),l.jsx("input",{type:"text",value:o,onChange:m=>c(m.target.value),placeholder:"Search fields...",className:"pl-8 pr-3 py-1.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none w-48"})]}),f.same>0&&l.jsxs("div",{className:"flex rounded overflow-hidden border border-bambu-dark-tertiary",children:[l.jsx("button",{onClick:()=>s("changes"),className:`px-3 py-1.5 text-sm transition-colors ${a==="changes"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:"Changes"}),l.jsx("button",{onClick:()=>s("all"),className:`px-3 py-1.5 text-sm transition-colors ${a==="all"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:"All"})]})]})]}),l.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:d.length===0?l.jsxs("div",{className:"text-center py-12 text-bambu-gray",children:[l.jsx(RA,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),l.jsx("p",{children:a==="changes"?"No differences found":"No fields match the search"})]}):l.jsxs("table",{className:"w-full",children:[l.jsx("thead",{className:"sticky top-0 bg-bambu-dark-secondary",children:l.jsxs("tr",{className:"text-sm text-bambu-gray border-b border-bambu-dark-tertiary",children:[l.jsx("th",{className:"text-left p-3 w-1/3",children:"Field"}),l.jsx("th",{className:"text-left p-3 w-1/3",children:r}),l.jsx("th",{className:"text-left p-3 w-1/3",children:i})]})}),l.jsx("tbody",{children:d.map(m=>{const x={added:"bg-green-500/10",removed:"bg-red-500/10",changed:"bg-amber-500/10",same:""}[m.status],v={added:l.jsx(pr,{className:"w-3.5 h-3.5 text-green-400"}),removed:l.jsx(Rk,{className:"w-3.5 h-3.5 text-red-400"}),changed:l.jsx(Tk,{className:"w-3.5 h-3.5 text-amber-400"}),same:l.jsx(RA,{className:"w-3.5 h-3.5 text-bambu-gray-dark"})}[m.status];return l.jsxs("tr",{className:`border-b border-bambu-dark-tertiary ${x}`,children:[l.jsx("td",{className:"p-3",children:l.jsxs("div",{className:"flex items-center gap-2",children:[v,l.jsx("span",{className:"text-sm text-white font-mono",children:m.key})]})}),l.jsx("td",{className:"p-3",children:l.jsx("span",{className:`text-sm font-mono break-all ${m.status==="removed"?"text-red-300":m.status==="changed"?"text-white":"text-bambu-gray"}`,children:g(m.left)})}),l.jsx("td",{className:"p-3",children:l.jsx("span",{className:`text-sm font-mono break-all ${m.status==="added"?"text-green-300":m.status==="changed"?"text-white":"text-bambu-gray"}`,children:g(m.right)})})]},m.key)})})]})})]})})})}function _Ge({onClose:t,initialData:e,allPresets:n}){const{showToast:r}=ai(),i=En(),a=!!e?.setting_id,[s,o]=E.useState("common"),[c,u]=E.useState(e?.type||"filament"),[d,f]=E.useState(e?.name?a?e.name:`${e.name} (Copy)`:""),[g,m]=E.useState(e?.base_id||""),[x,v]=E.useState(""),[y,b]=E.useState(e?.setting||{inherits:""}),[M,S]=E.useState(JSON.stringify(e?.setting||{inherits:""},null,2)),[A,T]=E.useState(null),[k,N]=E.useState(""),[I,C]=E.useState(!1),[D,F]=E.useState(""),[O,q]=E.useState(!1),[R,W]=E.useState(mte),[K,G]=E.useState(!1),[ee,Z]=E.useState(""),[Q,U]=E.useState(""),[$,X]=E.useState(!0),[te,fe]=E.useState(null),[pe,xe]=E.useState(!1),Ne=E.useMemo(()=>({filament:n.filament,print:n.process,printer:n.printer})[c]||[],[n,c]),ie=E.useMemo(()=>Ne.filter(oe=>hb(oe.setting_id)),[Ne]),{data:be}=vt({queryKey:["cloudFields",c],queryFn:()=>ke.getCloudFields(c==="print"?"process":c),staleTime:1e3*60*60}),{data:je}=vt({queryKey:["allPresetDetails",c,ie.map(oe=>oe.setting_id).join(",")],queryFn:async()=>{const oe={};for(let He=0;He{try{const Ye=await ke.getCloudSettingDetail(de.setting_id);return{id:de.setting_id,detail:Ye}}catch{return null}}))).forEach(de=>{de&&(oe[de.id]=de.detail)})}return oe},enabled:ie.length>0,staleTime:1e3*60*10}),{data:he,isLoading:ht}=vt({queryKey:["cloudSettingDetail",g],queryFn:()=>ke.getCloudSettingDetail(g),enabled:!!g});E.useEffect(()=>{s!=="json"&&S(JSON.stringify(y,null,2))},[y,s]);const H=E.useMemo(()=>({filament:n.filament,print:n.process,printer:n.printer}[c]||[]).filter(Je=>!hb(Je.setting_id)).sort((Je,He)=>Je.name.localeCompare(He.name)),[n,c]);E.useEffect(()=>{if(!g)return;const oe=H.find(Je=>Je.setting_id===g);oe&&(v(oe.name),a||(b({inherits:oe.name}),S(JSON.stringify({inherits:oe.name},null,2))))},[g,H,a]);const B=E.useMemo(()=>{const oe=be?.fields||[],Je=new Set(oe.map(de=>de.key)),He=new Set,Ke=new Set(["inherits","updated_time","compatible_printers","compatible_prints"]);je&&Object.values(je).forEach(de=>{de?.setting&&Object.keys(de.setting).forEach(Ye=>{!Je.has(Ye)&&!Ke.has(Ye)&&He.add(Ye)})}),Object.keys(y).forEach(de=>{!Je.has(de)&&!Ke.has(de)&&He.add(de)});const ct=Array.from(He).sort().map(de=>({key:de,label:de.replace(/_/g," ").replace(/\b\w/g,Ye=>Ye.toUpperCase()),type:"text",category:"discovered",description:"Discovered from presets"}));return[...oe,...ct]},[be,je,y]),re=B.filter(oe=>oe.label.toLowerCase().includes(k.toLowerCase())||oe.key.toLowerCase().includes(k.toLowerCase())),V=()=>{if(D.trim()){const oe=D.trim().toLowerCase().replace(/\s+/g,"_");J(oe,""),F(""),q(!1),r(`Field "${oe}" added`)}},J=(oe,Je)=>{b(He=>{const Ke={...He};return Je===""||Je===void 0?delete Ke[oe]:Ke[oe]=Je,Ke})},se=oe=>{b(Je=>({...Je,...oe.settings})),fe(oe.name),r("Template applied")},Ae=()=>{if(!ee.trim())return;const oe={...y};if(delete oe.inherits,Object.keys(oe).length===0){r("No overrides to save","error");return}const Je={id:Date.now().toString(),name:ee.trim(),description:Q.trim()||"Custom template",type:c,settings:oe,showInModal:$},He=[...R,Je];W(He),gte(He),G(!1),Z(""),U(""),X(!0),r("Template saved")},Pe=E.useMemo(()=>R.filter(oe=>oe.type===c&&oe.showInModal),[c,R]),Se=oe=>{S(oe);try{const Je=JSON.parse(oe);b(Je),T(null)}catch(Je){T(Je.message)}},z=oe=>{oe.preventDefault(),C(!1);const Je=oe.dataTransfer.files[0];if(Je&&Je.name.endsWith(".json")){const He=new FileReader;He.onload=Ke=>{try{const ct=Ke.target?.result,de=JSON.parse(ct),Ye=de.setting||de;b(ge=>({...ge,...Ye})),S(JSON.stringify({...y,...Ye},null,2)),r("File imported successfully")}catch{r("Invalid JSON file","error")}},He.readAsText(Je)}},L=wt({mutationFn:()=>{const oe={...y},Je=c==="filament"?"filament_settings_id":c==="print"?"print_settings_id":"printer_settings_id";oe[Je]=`"${d}"`;const He={type:c,name:d,base_id:g,setting:oe};return ke.createCloudSetting(He)},onSuccess:async()=>{r("Preset created successfully"),await i.refetchQueries({queryKey:["cloudSettings"]}),t()},onError:oe=>r(oe.message,"error")}),ne=wt({mutationFn:()=>{if(!e?.setting_id)throw new Error("No setting ID for update");return ke.updateCloudSetting(e.setting_id,{name:d,setting:y})},onSuccess:async()=>{r("Preset updated successfully"),i.removeQueries({queryKey:["cloudSettingDetail"]}),await i.refetchQueries({queryKey:["cloudSettings"]}),t()},onError:oe=>r(oe.message,"error")}),ve=a?ne:L,we=he?.setting?.inherits,ye=we?H.find(oe=>oe.name===we):void 0,{data:nt}=vt({queryKey:["cloudSettingDetail",ye?.setting_id],queryFn:()=>ke.getCloudSettingDetail(ye.setting_id),enabled:!!ye?.setting_id}),Be=E.useMemo(()=>{const oe=nt?.setting||{},Je=he?.setting||{},He=g&&je?.[g]?.setting?je[g].setting:{};return{...oe,...Je,...He}},[g,he,nt,je]),ue=oe=>{if(oe==null)return"";if(Array.isArray(oe)){const Je=[...new Set(oe.map(He=>String(He)))];return Je.length===1?Je[0]:oe.join(", ")}return String(oe)},Ve=oe=>{const Je=y[oe.key],He=Be[oe.key],Ke=ue(He),ct=ht?"Loading...":Ke||"",de="w-full px-3 py-1.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none";if(oe.type==="boolean"){const Ye=Je==="1"||Je===void 0&&He==="1";return l.jsx("button",{type:"button",onClick:()=>J(oe.key,Je==="1"?"0":"1"),className:`w-8 h-5 rounded-full transition-colors ${Ye?"bg-bambu-green":"bg-bambu-dark-tertiary"}`,children:l.jsx("div",{className:`w-4 h-4 rounded-full bg-white shadow transition-transform ${Ye?"translate-x-3.5":"translate-x-0.5"}`})})}return oe.type==="select"?l.jsxs("select",{value:Je||"",onChange:Ye=>J(oe.key,Ye.target.value),className:de,children:[l.jsx("option",{value:"",children:ct}),oe.options?.map(Ye=>l.jsx("option",{value:Ye.value,children:Ye.label},Ye.value))]}):l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("input",{type:oe.type==="number"?"number":"text",value:Je!==void 0?String(Je):"",onChange:Ye=>J(oe.key,Ye.target.value),step:oe.step,min:oe.min,max:oe.max,placeholder:ct,className:de}),oe.unit&&l.jsx("span",{className:"text-xs text-bambu-gray whitespace-nowrap",children:oe.unit})]})},Fe=E.useMemo(()=>he?.setting?he.setting:{},[he]);return l.jsxs("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onDragOver:oe=>{oe.preventDefault(),C(!0)},onDragLeave:()=>C(!1),onDrop:z,children:[pe&&g&&l.jsx(xte,{onClose:()=>xe(!1),leftPreset:Fe,rightPreset:y,leftLabel:`Base: ${x||g}`,rightLabel:`Current: ${d||"New Preset"}`}),l.jsx(Nt,{className:"w-full max-w-6xl max-h-[90vh] flex flex-col",children:l.jsxs(Rt,{className:"p-0 flex flex-col h-full",children:[l.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[l.jsxs("div",{children:[l.jsx("h2",{className:"text-xl font-semibold text-white",children:a?"Edit Preset":e?"Duplicate Preset":"Create New Preset"}),l.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:"Customize settings for your new preset"})]}),l.jsxs("div",{className:"flex items-center gap-2",children:[g&&l.jsxs("button",{onClick:()=>xe(!0),className:"flex items-center gap-2 px-3 py-2 text-sm text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary rounded-lg transition-colors",title:"Compare with base preset",children:[l.jsx(Qp,{className:"w-4 h-4"}),"Compare"]}),l.jsx("button",{onClick:t,className:"p-2 text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:l.jsx(Wt,{className:"w-5 h-5"})})]})]}),I&&l.jsx("div",{className:"absolute inset-0 bg-bambu-green/10 border-2 border-dashed border-bambu-green rounded-lg flex items-center justify-center z-10",children:l.jsxs("div",{className:"text-center",children:[l.jsx(vs,{className:"w-12 h-12 text-bambu-green mx-auto mb-2"}),l.jsx("p",{className:"text-bambu-green font-medium",children:"Drop JSON file to import"})]})}),l.jsxs("div",{className:"p-4 border-b border-bambu-dark-tertiary space-y-3",children:[l.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[l.jsxs("div",{children:[l.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Type"}),l.jsxs("select",{value:c,onChange:oe=>{u(oe.target.value),m("")},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:[l.jsx("option",{value:"filament",children:"Filament"}),l.jsx("option",{value:"print",children:"Process"}),l.jsx("option",{value:"printer",children:"Printer"})]})]}),l.jsxs("div",{children:[l.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Base Preset"}),l.jsxs("select",{value:g,onChange:oe=>m(oe.target.value),className:"w-full 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",children:[l.jsx("option",{value:"",children:"Select base preset..."}),H.map(oe=>l.jsx("option",{value:oe.setting_id,children:oe.name},oe.setting_id))]})]}),l.jsxs("div",{children:[l.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Preset Name"}),l.jsx("input",{type:"text",value:d,onChange:oe=>f(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:"My Custom Preset"})]})]}),x&&l.jsx("div",{className:"text-xs text-bambu-gray",children:l.jsxs("p",{className:"flex items-center gap-1",children:[l.jsx(zh,{className:"w-3 h-3 text-bambu-green"}),"Inherits from: ",l.jsx("span",{className:"text-white",children:x}),ht&&l.jsx(At,{className:"w-3 h-3 animate-spin ml-1"})]})})]}),l.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary",children:[l.jsxs("button",{onClick:()=>o("common"),className:`flex items-center gap-2 px-4 py-3 text-sm font-medium transition-colors border-b-2 -mb-px ${s==="common"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-white border-transparent"}`,children:[l.jsx(ZF,{className:"w-4 h-4"}),"Common"]}),l.jsxs("button",{onClick:()=>o("fields"),className:`flex items-center gap-2 px-4 py-3 text-sm font-medium transition-colors border-b-2 -mb-px ${s==="fields"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-white border-transparent"}`,children:[l.jsx(HR,{className:"w-4 h-4"}),"All Fields"]}),l.jsxs("button",{onClick:()=>o("json"),className:`flex items-center gap-2 px-4 py-3 text-sm font-medium transition-colors border-b-2 -mb-px ${s==="json"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-white border-transparent"}`,children:[l.jsx(iG,{className:"w-4 h-4"}),"JSON",A&&l.jsx(lo,{className:"w-3 h-3 text-red-400"})]}),l.jsx("div",{className:"flex-1"}),l.jsxs("button",{onClick:()=>{const oe={name:d,type:c,base_id:g,setting:y},Je=new Blob([JSON.stringify(oe,null,2)],{type:"application/json"}),He=URL.createObjectURL(Je),Ke=document.createElement("a");Ke.href=He,Ke.download=`${d||"preset"}.json`,document.body.appendChild(Ke),Ke.click(),document.body.removeChild(Ke),URL.revokeObjectURL(He),r("Preset exported")},className:"flex items-center gap-2 px-4 py-3 text-sm text-bambu-gray hover:text-white transition-colors",title:"Export current settings to JSON file",children:[l.jsx(Es,{className:"w-4 h-4"}),"Export"]}),l.jsxs("button",{onClick:()=>document.getElementById("file-import")?.click(),className:"flex items-center gap-2 px-4 py-3 text-sm text-bambu-gray hover:text-white transition-colors",title:"Import settings from JSON file",children:[l.jsx(vs,{className:"w-4 h-4"}),"Import"]}),l.jsx("input",{id:"file-import",type:"file",accept:".json",className:"hidden",onChange:oe=>{const Je=oe.target.files?.[0];if(Je){const He=new FileReader;He.onload=Ke=>{try{const ct=JSON.parse(Ke.target?.result),de=ct.setting||ct;b(Ye=>({...Ye,...de})),r("File imported")}catch{r("Invalid JSON","error")}},He.readAsText(Je)}}})]}),l.jsxs("div",{className:"flex-1 overflow-y-auto p-4",children:[s==="common"&&l.jsxs("div",{className:"space-y-6",children:[l.jsxs("div",{children:[l.jsxs("div",{className:"flex items-center justify-between mb-3",children:[l.jsxs("h3",{className:"text-sm font-medium text-white flex items-center gap-2",children:[l.jsx(M0,{className:"w-4 h-4 text-amber-400"}),"Quick Templates"]}),Object.keys(y).filter(oe=>oe!=="inherits").length>0&&l.jsxs("button",{onClick:()=>G(!K),className:"text-xs text-bambu-gray hover:text-white flex items-center gap-1 transition-colors",children:[l.jsx(Ro,{className:"w-3 h-3"}),"Save as template"]})]}),K&&l.jsxs("div",{className:"mb-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[l.jsxs("div",{className:"grid grid-cols-2 gap-2 mb-2",children:[l.jsx("input",{type:"text",value:ee,onChange:oe=>Z(oe.target.value),placeholder:"Template name",className:"px-3 py-1.5 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none",autoFocus:!0}),l.jsx("input",{type:"text",value:Q,onChange:oe=>U(oe.target.value),placeholder:"Description (optional)",className:"px-3 py-1.5 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none"})]}),l.jsxs("div",{className:"flex items-center justify-between",children:[l.jsxs("div",{className:"flex gap-2",children:[l.jsxs(Le,{size:"sm",onClick:Ae,disabled:!ee.trim(),children:[l.jsx(Ro,{className:"w-3 h-3"}),"Save"]}),l.jsx(Le,{size:"sm",variant:"secondary",onClick:()=>G(!1),children:"Cancel"})]}),l.jsxs("button",{onClick:()=>X(!$),className:`flex items-center gap-1.5 text-xs transition-colors ${$?"text-bambu-green":"text-bambu-gray hover:text-white"}`,children:[$?l.jsx(mm,{className:"w-3.5 h-3.5"}):l.jsx(FR,{className:"w-3.5 h-3.5"}),$?"Show in modals":"Hidden in modals"]})]})]}),te&&l.jsxs("div",{className:"mb-3 px-3 py-2 bg-bambu-green/10 border border-bambu-green/30 rounded-lg flex items-center gap-2",children:[l.jsx(zh,{className:"w-4 h-4 text-bambu-green"}),l.jsxs("span",{className:"text-sm text-bambu-green",children:["Template applied: ",l.jsx("span",{className:"font-medium",children:te})]}),l.jsx("button",{onClick:()=>fe(null),className:"ml-auto text-bambu-green/70 hover:text-bambu-green",children:l.jsx(Wt,{className:"w-4 h-4"})})]}),l.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[Pe.map(oe=>l.jsxs("button",{onClick:()=>se(oe),className:"p-3 text-left bg-bambu-dark border border-bambu-dark-tertiary rounded-lg hover:border-bambu-gray-dark transition-colors",children:[l.jsx("p",{className:"text-sm font-medium text-white",children:oe.name}),l.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:oe.description})]},oe.id)),Pe.length===0&&l.jsx("p",{className:"col-span-3 text-center text-bambu-gray text-sm py-4",children:"No templates selected. Use the Templates button to enable templates for quick access."})]}),l.jsx("p",{className:"text-xs text-bambu-gray-dark mt-2 text-center",children:"Manage templates via the Templates button on the main page"})]}),l.jsxs("div",{children:[l.jsx("h3",{className:"text-sm font-medium text-white mb-3",children:"Common Settings"}),l.jsx("div",{className:"grid grid-cols-2 gap-x-6 gap-y-3",children:B.slice(0,10).map(oe=>l.jsxs("div",{className:"flex items-center justify-between gap-4",children:[l.jsx("label",{className:"text-sm text-bambu-gray flex-shrink-0",children:oe.label}),l.jsx("div",{className:"w-48",children:Ve(oe)})]},oe.key))})]}),Object.keys(y).length>1&&l.jsxs("div",{children:[l.jsx("h3",{className:"text-sm font-medium text-white mb-3",children:"Current Overrides"}),l.jsx("div",{className:"flex flex-wrap gap-2",children:Object.entries(y).filter(([oe])=>oe!=="inherits").map(([oe,Je])=>l.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-1 bg-bambu-green/10 text-bambu-green text-xs rounded",children:[oe,": ",String(Je).slice(0,20),l.jsx("button",{onClick:()=>J(oe,void 0),className:"hover:text-white",children:l.jsx(Wt,{className:"w-3 h-3"})})]},oe))})]})]}),s==="fields"&&l.jsxs("div",{className:"grid grid-cols-2 gap-6",style:{height:"400px"},children:[l.jsxs("div",{className:"flex flex-col h-full overflow-hidden",children:[l.jsxs("div",{className:"flex items-center justify-between mb-3 flex-shrink-0",children:[l.jsx("h3",{className:"text-sm font-medium text-white",children:"Available Fields"}),l.jsx("span",{className:"text-xs text-bambu-gray",children:je?`${B.length} fields`:"Loading..."})]}),l.jsxs("div",{className:"relative mb-3 flex-shrink-0",children:[l.jsx(id,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),l.jsx("input",{type:"text",value:k,onChange:oe=>N(oe.target.value),placeholder:"Search fields...",className:"w-full pl-10 pr-4 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder-bambu-gray-dark focus:border-bambu-green focus:outline-none"})]}),l.jsxs("div",{className:"flex-1 overflow-y-auto space-y-1 pr-2 min-h-0",children:[re.filter(oe=>!(oe.key in y)).map(oe=>{const Je=Be[oe.key],He=ue(Je);return l.jsxs("div",{onClick:()=>{b(Ke=>({...Ke,[oe.key]:He||""}))},className:"flex items-center justify-between gap-2 p-2 rounded-lg hover:bg-bambu-dark-tertiary transition-colors cursor-pointer group",children:[l.jsxs("div",{className:"min-w-0 flex-1",children:[l.jsx("p",{className:"text-sm text-white truncate",children:oe.label}),l.jsx("p",{className:"text-xs text-bambu-gray-dark truncate",children:oe.key})]}),l.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[He&&l.jsxs("span",{className:"text-xs text-bambu-gray bg-bambu-dark px-2 py-0.5 rounded max-w-32 truncate",title:He,children:[He.slice(0,20),He.length>20?"...":""]}),l.jsx("div",{className:"w-6 h-6 flex items-center justify-center rounded bg-bambu-dark-tertiary group-hover:bg-bambu-green/20 transition-colors",children:l.jsx(pr,{className:"w-4 h-4 text-bambu-gray group-hover:text-bambu-green transition-colors"})})]})]},oe.key)}),re.filter(oe=>!(oe.key in y)).length===0&&l.jsx("p",{className:"text-center text-bambu-gray py-4 text-sm",children:k?"No matching fields":"All fields added"})]}),l.jsx("div",{className:"pt-3 mt-3 border-t border-bambu-dark-tertiary flex-shrink-0",children:O?l.jsxs("div",{className:"flex gap-2",children:[l.jsx("input",{type:"text",value:D,onChange:oe=>F(oe.target.value),onKeyDown:oe=>oe.key==="Enter"&&V(),placeholder:"custom_field_name",className:"flex-1 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white font-mono text-sm placeholder-bambu-gray-dark focus:border-bambu-green focus:outline-none",autoFocus:!0}),l.jsx(Le,{size:"sm",onClick:V,disabled:!D.trim(),children:l.jsx(pr,{className:"w-4 h-4"})}),l.jsx(Le,{size:"sm",variant:"secondary",onClick:()=>{q(!1),F("")},children:l.jsx(Wt,{className:"w-4 h-4"})})]}):l.jsxs("button",{onClick:()=>q(!0),className:"w-full flex items-center justify-center gap-2 p-2 text-sm text-bambu-gray hover:text-white border border-dashed border-bambu-dark-tertiary hover:border-bambu-gray-dark rounded-lg transition-colors",children:[l.jsx(pr,{className:"w-4 h-4"}),"Add custom field"]})})]}),l.jsxs("div",{className:"flex flex-col h-full overflow-hidden",children:[l.jsxs("div",{className:"flex items-center justify-between mb-3 flex-shrink-0",children:[l.jsx("h3",{className:"text-sm font-medium text-white",children:"Your Overrides"}),l.jsxs("span",{className:"text-xs text-bambu-gray",children:[Object.keys(y).filter(oe=>oe!=="inherits").length," fields"]})]}),l.jsxs("div",{className:"flex-1 overflow-y-auto space-y-2 pr-2 min-h-0",children:[Object.entries(y).filter(([oe])=>oe!=="inherits").map(([oe,Je])=>{const He=B.find(Ke=>Ke.key===oe);return l.jsxs("div",{className:"p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[l.jsxs("div",{className:"flex items-center justify-between mb-2",children:[l.jsxs("div",{children:[l.jsx("p",{className:"text-sm font-medium text-white",children:He?.label||oe}),l.jsx("p",{className:"text-xs text-bambu-gray-dark",children:oe})]}),l.jsx("button",{onClick:()=>J(oe,void 0),className:"p-1 text-bambu-gray hover:text-red-400 transition-colors",children:l.jsx(Wt,{className:"w-4 h-4"})})]}),He?Ve(He):l.jsx("input",{type:"text",value:String(Je),onChange:Ke=>J(oe,Ke.target.value),className:"w-full px-3 py-1.5 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none"})]},oe)}),Object.keys(y).filter(oe=>oe!=="inherits").length===0&&l.jsxs("div",{className:"text-center py-8 text-bambu-gray",children:[l.jsx(ZF,{className:"w-8 h-8 mx-auto mb-2 opacity-50"}),l.jsx("p",{className:"text-sm",children:"No overrides yet"}),l.jsx("p",{className:"text-xs mt-1",children:"Click fields on the left to add them"})]})]}),Object.keys(y).filter(oe=>oe!=="inherits").length>0&&l.jsx("div",{className:"pt-3 mt-3 border-t border-bambu-dark-tertiary flex-shrink-0",children:l.jsxs("button",{onClick:()=>{G(!0),o("common")},className:"w-full flex items-center justify-center gap-2 p-2 text-sm text-bambu-gray hover:text-white border border-dashed border-bambu-dark-tertiary hover:border-bambu-gray-dark rounded-lg transition-colors",children:[l.jsx(Ro,{className:"w-4 h-4"}),"Save as template"]})})]})]}),s==="json"&&l.jsxs("div",{className:"space-y-2",children:[A&&l.jsxs("div",{className:"flex items-center gap-2 text-red-400 text-sm",children:[l.jsx(lo,{className:"w-4 h-4"}),A]}),l.jsx("textarea",{value:M,onChange:oe=>Se(oe.target.value),className:`w-full h-80 px-3 py-2 bg-bambu-dark border rounded-lg text-white text-xs font-mono focus:outline-none resize-none ${A?"border-red-500 focus:border-red-500":"border-bambu-dark-tertiary focus:border-bambu-green"}`,spellCheck:!1}),l.jsx("p",{className:"text-xs text-bambu-gray",children:"Tip: Drag & drop a .json file anywhere on this modal to import settings"})]})]}),l.jsxs("div",{className:"p-4 border-t border-bambu-dark-tertiary flex gap-2",children:[l.jsx(Le,{variant:"secondary",onClick:t,className:"flex-1",children:"Cancel"}),l.jsxs(Le,{onClick:()=>ve.mutate(),disabled:ve.isPending||!d.trim()||!a&&!g||!!A,className:"flex-1",children:[ve.isPending?l.jsx(At,{className:"w-4 h-4 animate-spin"}):a?l.jsx(Ro,{className:"w-4 h-4"}):l.jsx(pr,{className:"w-4 h-4"}),a?"Save":e?"Duplicate":"Create"]})]})]})})]})}function wGe({settings:t,lastSyncTime:e,onRefresh:n,isRefreshing:r,printers:i}){const[a,s]=E.useState(""),[o,c]=E.useState("all"),[u,d]=E.useState("all"),[f,g]=E.useState("all"),[m,x]=E.useState("all"),[v,y]=E.useState("all"),[b,M]=E.useState("all"),[S,A]=E.useState(null),[T,k]=E.useState(!1),[N,I]=E.useState(!1),[C,D]=E.useState(null),[F,O]=E.useState(null),[q,R]=E.useState(null),[W,K]=E.useState(!1),[G,ee]=E.useState([null,null]),[Z,Q]=E.useState(!1),[U,$]=E.useState(null),X=En(),te=E.useMemo(()=>[...t.filament.map(re=>({...re,type:"filament"})),...t.printer.map(re=>({...re,type:"printer"})),...t.process.map(re=>({...re,type:"process"}))].map(re=>({...re,meta:xL(re.name)})),[t]),fe=E.useMemo(()=>{const B=new Set,re=new Set,V=new Set;return te.forEach(J=>{J.meta.nozzle&&B.add(J.meta.nozzle),J.meta.filamentType&&re.add(J.meta.filamentType),J.meta.layerHeight&&V.add(J.meta.layerHeight)}),{printers:i.map(J=>({id:J.id.toString(),name:J.name})),nozzles:Array.from(B).sort((J,se)=>parseFloat(J)-parseFloat(se)),filaments:Array.from(re).sort(),layerHeights:Array.from(V).sort((J,se)=>parseFloat(J)-parseFloat(se))}},[te,i]),pe=E.useMemo(()=>f==="all"?null:i.find(re=>re.id.toString()===f)?.model||null,[f,i]),xe=E.useMemo(()=>te.filter(B=>o==="all"||B.type===o).filter(B=>{if(u==="all")return!0;const re=hb(B.setting_id);return u==="custom"?re:!re}).filter(B=>{if(f==="all"||!pe)return!0;const re=B.meta.printer?.toLowerCase()||"",V=pe.toLowerCase();return re.includes(V)||V.includes(re)}).filter(B=>m==="all"||B.meta.nozzle===m).filter(B=>v==="all"||B.meta.filamentType===v).filter(B=>b==="all"||B.meta.layerHeight===b).filter(B=>a===""||B.name.toLowerCase().includes(a.toLowerCase())).sort((B,re)=>B.name.localeCompare(re.name)),[te,o,u,f,pe,m,v,b,a]),Ne=B=>{if(W){const re=G[0]?.setting_id===B.setting_id,V=G[1]?.setting_id===B.setting_id;if(re)ee([G[1],null]);else if(V)ee([G[0],null]);else if(!G[0])ee([B,null]);else if(G[1]){if(G[0].type!==B.type)return;ee([G[0],B])}else{if(G[0].type!==B.type)return;ee([G[0],B])}}else A(B)},ie=B=>{if(G[0]?.setting_id===B.setting_id)return 0;if(G[1]?.setting_id===B.setting_id)return 1},be=async B=>{try{const re=await ke.getCloudSettingDetail(B.setting_id),V=B.type==="process"?"print":B.type;D({type:V,name:B.name,base_id:re.base_id||"GFSA00",setting:re.setting||{}}),A(null)}catch(re){console.error("Failed to fetch preset details for duplication:",re)}},je=async B=>{try{X.removeQueries({queryKey:["cloudSettingDetail",B.setting_id]});const re=await ke.getCloudSettingDetail(B.setting_id),V=B.type==="process"?"print":B.type;O({type:V,name:B.name,base_id:re.base_id||"GFSA00",setting:re.setting||{},setting_id:B.setting_id}),A(null)}catch(re){console.error("Failed to fetch preset details for editing:",re)}},he=()=>{c("all"),d("all"),g("all"),x("all"),y("all"),M("all"),s("")},ht=o!=="all"||u!=="all"||f!=="all"||m!=="all"||v!=="all"||b!=="all"||a!=="",H=t.filament.length+t.printer.length+t.process.length;return l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"space-y-4 mb-6",children:[l.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[l.jsxs("div",{className:"relative flex-1",children:[l.jsx(id,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),l.jsx("input",{type:"text",value:a,onChange:B=>s(B.target.value),placeholder:"Search presets...",className:"w-full pl-10 pr-4 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray-dark focus:border-bambu-green focus:outline-none"})]}),l.jsxs("div",{className:"flex gap-2",children:[l.jsxs(Le,{variant:W?"primary":"secondary",onClick:()=>{W?(K(!1),ee([null,null])):K(!0)},children:[l.jsx(Qp,{className:"w-4 h-4"}),W?"Cancel":"Compare"]}),l.jsxs(Le,{variant:"secondary",onClick:()=>I(!0),children:[l.jsx(M0,{className:"w-4 h-4"}),"Templates"]}),l.jsxs(Le,{variant:"secondary",onClick:n,disabled:r,children:[l.jsx(Ta,{className:`w-4 h-4 ${r?"animate-spin":""}`}),"Refresh"]}),l.jsxs(Le,{onClick:()=>k(!0),children:[l.jsx(pr,{className:"w-4 h-4"}),"New Preset"]})]})]}),l.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[l.jsx(UR,{className:"w-4 h-4 text-bambu-gray"}),l.jsx(Lp,{label:"Type",value:o,options:[{value:"all",label:"All",count:H},{value:"filament",label:"Filament",count:t.filament.length},{value:"printer",label:"Printer",count:t.printer.length},{value:"process",label:"Process",count:t.process.length}],onChange:B=>c(B)}),l.jsx(Lp,{label:"Owner",value:u,options:[{value:"all",label:"All"},{value:"custom",label:"My Presets"},{value:"builtin",label:"Built-in"}],onChange:B=>d(B)}),fe.printers.length>0&&l.jsx(Lp,{label:"Printer",value:f,options:[{value:"all",label:"All"},...fe.printers.map(B=>({value:B.id,label:B.name}))],onChange:g}),fe.nozzles.length>0&&l.jsx(Lp,{label:"Nozzle",value:m,options:[{value:"all",label:"All"},...fe.nozzles.map(B=>({value:B,label:B}))],onChange:x}),fe.filaments.length>0&&(o==="all"||o==="filament")&&l.jsx(Lp,{label:"Filament",value:v,options:[{value:"all",label:"All"},...fe.filaments.map(B=>({value:B,label:B}))],onChange:y}),fe.layerHeights.length>0&&(o==="all"||o==="process")&&l.jsx(Lp,{label:"Layer",value:b,options:[{value:"all",label:"All"},...fe.layerHeights.map(B=>({value:B,label:B}))],onChange:M}),ht&&l.jsx("button",{onClick:he,className:"px-3 py-2 text-sm text-bambu-gray hover:text-white transition-colors",children:"Clear filters"})]})]}),W&&l.jsx("div",{className:"mb-4 p-3 bg-blue-500/10 border border-blue-500/30 rounded-lg",children:l.jsxs("div",{className:"flex items-center justify-between",children:[l.jsxs("div",{className:"flex items-center gap-4",children:[l.jsx(Qp,{className:"w-5 h-5 text-blue-400"}),l.jsx("span",{className:"text-white font-medium",children:"Compare Mode"}),l.jsx("span",{className:"text-bambu-gray",children:G[0]?`Select another ${G[0].type} preset`:"Click two presets of the same type to compare"})]}),l.jsxs("div",{className:"flex items-center gap-3",children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("span",{className:`px-2 py-1 text-sm rounded truncate max-w-[200px] ${G[0]?"bg-blue-500/30 text-blue-700 dark:text-blue-300":"bg-bambu-dark text-bambu-gray"}`,children:G[0]?G[0].name:"1. Select first"}),l.jsx(Tk,{className:"w-4 h-4 text-bambu-gray"}),l.jsx("span",{className:`px-2 py-1 text-sm rounded truncate max-w-[200px] ${G[1]?"bg-blue-500/30 text-blue-700 dark:text-blue-300":"bg-bambu-dark text-bambu-gray"}`,children:G[1]?G[1].name:"2. Select second"})]}),G[0]&&G[1]&&l.jsxs(Le,{size:"sm",onClick:async()=>{try{const[B,re]=await Promise.all([ke.getCloudSettingDetail(G[0].setting_id),ke.getCloudSettingDetail(G[1].setting_id)]);$([B.setting||{},re.setting||{}]),Q(!0)}catch{}},children:[l.jsx(Qp,{className:"w-4 h-4"}),"Compare Now"]})]})]})}),l.jsxs("div",{className:"flex flex-wrap items-center gap-4 mb-4 text-sm text-bambu-gray",children:[e&&l.jsxs("div",{className:"flex items-center gap-1",children:[l.jsx(_r,{className:"w-3 h-3"}),"Last synced: ",gGe(e.toISOString())]}),l.jsxs("span",{children:["Showing ",xe.length," of ",H," presets"]}),l.jsxs("div",{className:"flex items-center gap-1",children:[l.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-bambu-green"}),l.jsx("span",{children:"= My preset (editable)"})]})]}),xe.length===0?l.jsxs("div",{className:"text-center py-16",children:[l.jsx($h,{className:"w-12 h-12 text-bambu-gray-dark mx-auto mb-4"}),l.jsx("p",{className:"text-bambu-gray",children:"No presets found"}),ht&&l.jsx("button",{onClick:he,className:"mt-2 text-sm text-bambu-green hover:text-bambu-green-light",children:"Clear filters"})]}):l.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-6",children:[l.jsxs("div",{children:[l.jsxs("div",{className:"flex items-center gap-2 mb-3 px-1",children:[l.jsx(IR,{className:"w-4 h-4 text-amber-400"}),l.jsx("h3",{className:"text-sm font-medium text-bambu-gray",children:"Filament"}),l.jsxs("span",{className:"text-xs text-bambu-gray-dark",children:["(",xe.filter(B=>B.type==="filament").length,")"]})]}),l.jsxs("div",{className:"space-y-1 max-h-[calc(100vh-320px)] overflow-y-auto pr-1",children:[xe.filter(B=>B.type==="filament").map(B=>l.jsx(fk,{setting:B,onClick:()=>Ne(B),onDuplicate:()=>be(B),compareMode:W,isCompareSelected:ie(B)!==void 0,compareIndex:ie(B),compareDisabled:W&&!!G[0]&&G[0].type!==B.type},B.setting_id)),xe.filter(B=>B.type==="filament").length===0&&l.jsx("p",{className:"text-xs text-bambu-gray-dark px-3 py-2",children:"No filament presets"})]})]}),l.jsxs("div",{children:[l.jsxs("div",{className:"flex items-center gap-2 mb-3 px-1",children:[l.jsx(HS,{className:"w-4 h-4 text-blue-400"}),l.jsx("h3",{className:"text-sm font-medium text-bambu-gray",children:"Process"}),l.jsxs("span",{className:"text-xs text-bambu-gray-dark",children:["(",xe.filter(B=>B.type==="process").length,")"]})]}),l.jsxs("div",{className:"space-y-1 max-h-[calc(100vh-320px)] overflow-y-auto pr-1",children:[xe.filter(B=>B.type==="process").map(B=>l.jsx(fk,{setting:B,onClick:()=>Ne(B),onDuplicate:()=>be(B),compareMode:W,isCompareSelected:ie(B)!==void 0,compareIndex:ie(B),compareDisabled:W&&!!G[0]&&G[0].type!==B.type},B.setting_id)),xe.filter(B=>B.type==="process").length===0&&l.jsx("p",{className:"text-xs text-bambu-gray-dark px-3 py-2",children:"No process presets"})]})]}),l.jsxs("div",{children:[l.jsxs("div",{className:"flex items-center gap-2 mb-3 px-1",children:[l.jsx(Ts,{className:"w-4 h-4 text-purple-400"}),l.jsx("h3",{className:"text-sm font-medium text-bambu-gray",children:"Printer"}),l.jsxs("span",{className:"text-xs text-bambu-gray-dark",children:["(",xe.filter(B=>B.type==="printer").length,")"]})]}),l.jsxs("div",{className:"space-y-1 max-h-[calc(100vh-320px)] overflow-y-auto pr-1",children:[xe.filter(B=>B.type==="printer").map(B=>l.jsx(fk,{setting:B,onClick:()=>Ne(B),onDuplicate:()=>be(B),compareMode:W,isCompareSelected:ie(B)!==void 0,compareIndex:ie(B),compareDisabled:W&&!!G[0]&&G[0].type!==B.type},B.setting_id)),xe.filter(B=>B.type==="printer").length===0&&l.jsx("p",{className:"text-xs text-bambu-gray-dark px-3 py-2",children:"No printer presets"})]})]})]}),S&&l.jsx(yGe,{setting:S,onClose:()=>A(null),onDeleted:()=>A(null),onDuplicate:()=>be(S),onEdit:()=>je(S)}),(T||C||F||q)&&l.jsx(_Ge,{onClose:()=>{k(!1),D(null),O(null),R(null)},initialData:F||C||(q?{type:q.type,name:"",base_id:"",setting:q.setting}:void 0),allPresets:t}),N&&l.jsx(vGe,{onClose:()=>I(!1),onApply:B=>{R({type:B.type,setting:B.settings}),I(!1)}}),Z&&U&&G[0]&&G[1]&&l.jsx(xte,{onClose:()=>{Q(!1),$(null)},leftPreset:U[0],rightPreset:U[1],leftLabel:G[0].name,rightLabel:G[1].name})]})}function SGe(){const t=En(),{showToast:e}=ai(),[n,r]=E.useState("cloud"),[i,a]=E.useState(),{data:s,isLoading:o}=vt({queryKey:["cloudStatus"],queryFn:ke.getCloudStatus}),{data:c=[]}=vt({queryKey:["printers"],queryFn:ke.getPrinters}),{data:u,isLoading:d,refetch:f,dataUpdatedAt:g}=vt({queryKey:["cloudSettings"],queryFn:()=>ke.getCloudSettings(),enabled:!!s?.is_authenticated,retry:!1,staleTime:1e3*60*5});E.useEffect(()=>{g&&a(new Date(g))},[g]);const m=wt({mutationFn:ke.cloudLogout,onSuccess:()=>{t.invalidateQueries({queryKey:["cloudStatus"]}),t.removeQueries({queryKey:["cloudSettings"]}),e("Logged out")}}),x=()=>{t.invalidateQueries({queryKey:["cloudStatus"]})};return o?l.jsx("div",{className:"p-4 md:p-8 flex items-center justify-center min-h-[400px]",children:l.jsx(At,{className:"w-8 h-8 text-bambu-green animate-spin"})}):l.jsxs("div",{className:"p-6 lg:p-8",children:[l.jsxs("div",{className:"mb-6",children:[l.jsx("h1",{className:"text-2xl font-bold text-white",children:"Profiles"}),l.jsx("p",{className:"text-bambu-gray",children:"Manage your slicer presets and pressure advance calibrations"})]}),l.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary mb-6",children:[l.jsxs("button",{onClick:()=>r("cloud"),className:`flex items-center gap-2 px-4 py-3 text-sm font-medium transition-colors border-b-2 -mb-px ${n==="cloud"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-white border-transparent"}`,children:[l.jsx(US,{className:"w-4 h-4"}),"Cloud Profiles"]}),l.jsxs("button",{onClick:()=>r("kprofiles"),className:`flex items-center gap-2 px-4 py-3 text-sm font-medium transition-colors border-b-2 -mb-px ${n==="kprofiles"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-white border-transparent"}`,children:[l.jsx(zR,{className:"w-4 h-4"}),"K-Profiles"]})]}),n==="cloud"&&l.jsxs(l.Fragment,{children:[s?.is_authenticated&&l.jsxs("div",{className:"flex items-center justify-between p-3 mb-6 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[l.jsxs("div",{className:"flex items-center gap-3",children:[l.jsx("div",{className:"w-2 h-2 rounded-full bg-bambu-green animate-pulse"}),l.jsxs("span",{className:"text-sm text-bambu-gray",children:["Connected as ",l.jsx("span",{className:"text-white",children:s.email})]})]}),l.jsxs(Le,{variant:"secondary",size:"sm",onClick:()=>m.mutate(),disabled:m.isPending,children:[l.jsx(Zle,{className:"w-4 h-4"}),"Logout"]})]}),s?.is_authenticated?d?l.jsx("div",{className:"flex items-center justify-center py-16",children:l.jsx(At,{className:"w-8 h-8 text-bambu-green animate-spin"})}):u?l.jsx(wGe,{settings:u,lastSyncTime:i,onRefresh:()=>f(),isRefreshing:d,printers:c}):l.jsxs("div",{className:"text-center py-16",children:[l.jsx("p",{className:"text-bambu-gray mb-4",children:"Failed to load profiles"}),l.jsx(Le,{onClick:()=>f(),children:"Retry"})]}):l.jsx(xGe,{onSuccess:x})]}),n==="kprofiles"&&l.jsx(mGe,{}),l.jsx(bGe,{})]})}const Vx={Droplet:IR,Flame:dle,Ruler:Fce,Sparkles:M0,Square:gm,Cable:loe,Wrench:ad,Calendar:Zr,Timer:Uu,Cog:Foe,Fan:ele,Zap:bm,Wind:Oue,Thermometer:Sh,Layers:$h,Box:fm,Target:fG,RefreshCw:Ta,Settings:WR,Filter:UR,CircleDot:Aoe};function f0(t){return t&&Vx[t]||ad}function Ip(t,e){return e==="days"?t<1?"Today":t===1?"1 day":t<7?`${Math.round(t)} days`:t<30?`${Math.round(t/7)} weeks`:`${Math.round(t/30)} months`:t<1?`${Math.round(t*60)}m`:t<10?`${t.toFixed(1)}h`:`${Math.round(t)}h`}function pk(t,e){return e==="days"?t===1?"1 day":t===7?"1 week":t===14?"2 weeks":t===30?"1 month":t===60?"2 months":t===90?"3 months":t===180?"6 months":t===365?"1 year":`${t} days`:`${t}h`}function MGe({item:t,onPerform:e,onToggle:n}){const r=f0(t.maintenance_type_icon),i=t.interval_type||"hours",s=(()=>{if(i==="days"){const f=t.days_since_maintenance??0;return Math.max(0,Math.min(100,f/t.interval_hours*100))}return Math.max(0,Math.min(100,(t.interval_hours-t.hours_until_due)/t.interval_hours*100))})(),o=()=>t.enabled?t.is_due?"text-red-400":t.is_warning?"text-amber-400":"text-bambu-green":"text-bambu-gray",c=()=>t.enabled?t.is_due?"bg-red-500":t.is_warning?"bg-amber-500":"bg-bambu-green":"bg-bambu-gray/30",u=()=>t.enabled?t.is_due?"bg-red-500/5 border-red-500/20":t.is_warning?"bg-amber-500/5 border-amber-500/20":"bg-bambu-dark-secondary border-bambu-dark-tertiary":"bg-bambu-dark-secondary/50",d=()=>{if(!t.enabled)return"Disabled";if(i==="days"){const f=t.days_until_due??0;return t.is_due?`Overdue by ${Ip(Math.abs(f),"days")}`:t.is_warning?`Due in ${Ip(f,"days")}`:`${Ip(f,"days")} left`}else return t.is_due?`Overdue by ${Ip(Math.abs(t.hours_until_due),"hours")}`:t.is_warning?`Due in ${Ip(t.hours_until_due,"hours")}`:`${Ip(t.hours_until_due,"hours")} left`};return l.jsx("div",{className:`rounded-xl border p-4 transition-all ${u()}`,children:l.jsxs("div",{className:"flex items-start gap-3",children:[l.jsxs("div",{className:`relative p-2.5 rounded-lg ${t.is_due?"bg-red-500/20":t.is_warning?"bg-amber-500/20":t.enabled?"bg-bambu-dark":"bg-bambu-dark/50"}`,children:[l.jsx(r,{className:`w-5 h-5 ${o()}`}),t.enabled&&(t.is_due||t.is_warning)&&l.jsx("span",{className:`absolute -top-1 -right-1 w-2.5 h-2.5 rounded-full ${t.is_due?"bg-red-500":"bg-amber-500"} animate-pulse`})]}),l.jsxs("div",{className:"flex-1 min-w-0",children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("h3",{className:`font-medium truncate ${t.enabled?"text-white":"text-bambu-gray"}`,children:t.maintenance_type_name}),i==="days"&&l.jsx("span",{title:"Time-based interval",children:l.jsx(Zr,{className:"w-3.5 h-3.5 text-bambu-gray shrink-0"})})]}),l.jsx("div",{className:"mt-2 mb-1.5",children:l.jsx("div",{className:"w-full h-1.5 bg-bambu-dark rounded-full overflow-hidden",children:l.jsx("div",{className:`h-full rounded-full transition-all duration-500 ${c()}`,style:{width:`${s}%`}})})}),l.jsxs("div",{className:`text-xs flex items-center gap-1 ${o()}`,children:[t.is_due&&l.jsx(ti,{className:"w-3 h-3"}),t.is_warning&&!t.is_due&&l.jsx(_r,{className:"w-3 h-3"}),!t.is_due&&!t.is_warning&&t.enabled&&l.jsx(zh,{className:"w-3 h-3"}),d()]})]}),l.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[l.jsx(Pn,{checked:t.enabled,onChange:f=>n(t.id,f)}),l.jsxs(Le,{size:"sm",variant:t.is_due?"primary":"secondary",onClick:()=>e(t.id),disabled:!t.enabled,className:"!px-3",children:[l.jsx(Xm,{className:"w-3.5 h-3.5"}),"Reset"]})]})]})})}function EGe({overview:t,onPerform:e,onToggle:n,onSetHours:r}){const[i,a]=E.useState(!0),[s,o]=E.useState(!1),[c,u]=E.useState(t.total_print_hours.toFixed(1)),d=[...t.maintenance_items].sort((m,x)=>m.is_due&&!x.is_due?-1:!m.is_due&&x.is_due?1:m.is_warning&&!x.is_warning?-1:!m.is_warning&&x.is_warning?1:m.maintenance_type_id-x.maintenance_type_id),f=d.find(m=>m.enabled&&(m.is_due||m.is_warning)),g=()=>{const m=parseFloat(c);!isNaN(m)&&m>=0&&(r(t.printer_id,m),o(!1))};return l.jsxs(Nt,{className:"overflow-hidden",children:[l.jsxs("div",{className:"p-5",children:[l.jsxs("div",{className:"flex items-center justify-between",children:[l.jsxs("div",{className:"flex items-center gap-4",children:[l.jsx("h2",{className:"text-xl font-semibold text-white",children:t.printer_name}),l.jsxs("div",{className:"flex items-center gap-2",children:[t.due_count>0&&l.jsxs("span",{className:"px-2.5 py-1 bg-red-500/20 text-red-400 text-xs font-medium rounded-full flex items-center gap-1.5",children:[l.jsx(ti,{className:"w-3 h-3"}),t.due_count," overdue"]}),t.warning_count>0&&l.jsxs("span",{className:"px-2.5 py-1 bg-amber-500/20 text-amber-400 text-xs font-medium rounded-full flex items-center gap-1.5",children:[l.jsx(_r,{className:"w-3 h-3"}),t.warning_count," due soon"]}),t.due_count===0&&t.warning_count===0&&l.jsxs("span",{className:"px-2.5 py-1 bg-bambu-green/20 text-bambu-green text-xs font-medium rounded-full flex items-center gap-1.5",children:[l.jsx(zh,{className:"w-3 h-3"}),"All good"]})]})]}),l.jsxs("button",{onClick:()=>a(!i),className:"flex items-center gap-1.5 px-3 py-1.5 text-sm text-bambu-gray hover:text-white hover:bg-bambu-dark rounded-lg transition-colors",children:[i?l.jsx(FS,{className:"w-4 h-4"}):l.jsx(uf,{className:"w-4 h-4"}),i?"Collapse":"Expand"]})]}),l.jsxs("div",{className:"flex items-center gap-6 mt-4",children:[l.jsxs("div",{className:"flex items-center gap-3",children:[l.jsx("div",{className:"p-2 bg-bambu-dark/50 rounded-lg",children:l.jsx(Uu,{className:"w-4 h-4 text-bambu-gray"})}),s?l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("input",{type:"number",value:c,onChange:m=>u(m.target.value),onKeyDown:m=>{m.key==="Enter"&&g(),m.key==="Escape"&&o(!1)},className:"w-24 px-2 py-1 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-sm",min:"0",step:"1",autoFocus:!0}),l.jsx("span",{className:"text-xs text-bambu-gray",children:"hours"}),l.jsx(Le,{size:"sm",onClick:g,children:"Save"}),l.jsx(Le,{size:"sm",variant:"secondary",onClick:()=>o(!1),children:"Cancel"})]}):l.jsxs("button",{onClick:()=>{u(Math.round(t.total_print_hours).toString()),o(!0)},className:"group",children:[l.jsxs("div",{className:"text-sm font-medium text-white group-hover:text-bambu-green transition-colors flex items-center gap-1",children:[Math.floor(t.total_print_hours)," hours",l.jsx(S0,{className:"w-3 h-3 text-bambu-gray group-hover:text-bambu-green"})]}),l.jsx("div",{className:"text-xs text-bambu-gray",children:"Total print time"})]})]}),l.jsx("div",{className:"w-px h-10 bg-bambu-dark-tertiary"}),f&&l.jsxs("div",{className:"flex items-center gap-3",children:[l.jsx("div",{className:`p-2 rounded-lg ${f.is_due?"bg-red-500/20":"bg-amber-500/20"}`,children:(()=>{const m=f0(f.maintenance_type_icon);return l.jsx(m,{className:`w-4 h-4 ${f.is_due?"text-red-400":"text-amber-400"}`})})()}),l.jsxs("div",{children:[l.jsx("div",{className:`text-sm font-medium ${f.is_due?"text-red-400":"text-amber-400"}`,children:f.maintenance_type_name}),l.jsx("div",{className:`text-xs ${f.is_due?"text-red-400/70":"text-amber-400/70"}`,children:f.is_due?"Overdue":"Due soon"})]})]})]})]}),i&&l.jsx(Rt,{className:"pt-0 border-t border-bambu-dark-tertiary",children:l.jsx("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-3 pt-4",children:d.map(m=>l.jsx(MGe,{item:m,onPerform:e,onToggle:n},m.id))})})]})}function AGe({overview:t,types:e,onUpdateInterval:n,onAddType:r,onUpdateType:i,onDeleteType:a}){const[s,o]=E.useState(null),[c,u]=E.useState(""),[d,f]=E.useState("hours"),[g,m]=E.useState(!1),[x,v]=E.useState(""),[y,b]=E.useState("100"),[M,S]=E.useState("hours"),[A,T]=E.useState("Wrench"),[k,N]=E.useState(null),[I,C]=E.useState(""),[D,F]=E.useState(""),[O,q]=E.useState("hours"),[R,W]=E.useState("Wrench"),K=X=>{N(X),C(X.name),F(X.default_interval_hours.toString()),q(X.interval_type||"hours"),W(X.icon||"Wrench")},G=()=>{k&&I.trim()&&parseFloat(D)>0&&(i(k.id,{name:I.trim(),default_interval_hours:parseFloat(D),interval_type:O,icon:R}),N(null))},ee=(X,te,fe)=>{const pe=parseFloat(c);if(!isNaN(pe)&&pe>0){const xe=Math.abs(pe-te)<.01?null:pe;n(X,{custom_interval_hours:xe,custom_interval_type:d!==fe?d:null})}o(null)},Z=X=>{X.preventDefault(),x.trim()&&parseFloat(y)>0&&(r({name:x.trim(),default_interval_hours:parseFloat(y),interval_type:M,icon:A}),v(""),b("100"),S("hours"),m(!1))},Q=t?.map(X=>({printerId:X.printer_id,printerName:X.printer_name,items:X.maintenance_items.sort((te,fe)=>te.maintenance_type_id-fe.maintenance_type_id)})).sort((X,te)=>X.printerName.localeCompare(te.printerName))||[],U=e.filter(X=>X.is_system),$=e.filter(X=>!X.is_system);return l.jsxs("div",{className:"space-y-8",children:[l.jsxs("div",{children:[l.jsxs("div",{className:"flex items-center justify-between mb-4",children:[l.jsxs("div",{children:[l.jsx("h2",{className:"text-lg font-semibold text-white",children:"Maintenance Types"}),l.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:"System types and your custom maintenance tasks"})]}),l.jsxs(Le,{onClick:()=>m(!g),children:[l.jsx(pr,{className:"w-4 h-4"}),"Add Custom Type"]})]}),g&&l.jsx(Nt,{className:"mb-6",children:l.jsx(Rt,{className:"py-4",children:l.jsxs("form",{onSubmit:Z,children:[l.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4",children:[l.jsxs("div",{className:"lg:col-span-2",children:[l.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:"Name"}),l.jsx("input",{type:"text",value:x,onChange:X=>v(X.target.value),className:"w-full 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",placeholder:"e.g., Replace HEPA Filter",autoFocus:!0})]}),l.jsxs("div",{children:[l.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:"Interval Type"}),l.jsxs("select",{value:M,onChange:X=>{S(X.target.value),X.target.value==="days"?b("30"):b("100")},className:"w-full 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",children:[l.jsx("option",{value:"hours",children:"Print Hours"}),l.jsx("option",{value:"days",children:"Calendar Days"})]})]}),l.jsxs("div",{children:[l.jsxs("label",{className:"block text-xs text-bambu-gray mb-1.5",children:["Interval (",M==="days"?"days":"hours",")"]}),l.jsx("input",{type:"number",value:y,onChange:X=>b(X.target.value),className:"w-full 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",min:"1"})]})]}),l.jsxs("div",{className:"mt-4 flex items-end justify-between",children:[l.jsxs("div",{children:[l.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:"Icon"}),l.jsx("div",{className:"flex gap-1",children:Object.keys(Vx).map(X=>{const te=Vx[X];return l.jsx("button",{type:"button",onClick:()=>T(X),className:`p-2 rounded-lg transition-colors ${A===X?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary"}`,children:l.jsx(te,{className:"w-4 h-4"})},X)})})]}),l.jsxs("div",{className:"flex gap-2",children:[l.jsx(Le,{type:"button",variant:"secondary",onClick:()=>m(!1),children:"Cancel"}),l.jsx(Le,{type:"submit",disabled:!x.trim(),children:"Add Type"})]})]})]})})}),l.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3",children:[U.map(X=>{const te=f0(X.icon),fe=X.interval_type||"hours";return l.jsx("div",{className:"bg-bambu-dark-secondary rounded-xl p-4 border border-bambu-dark-tertiary",children:l.jsxs("div",{className:"flex items-center gap-3",children:[l.jsx("div",{className:"p-2.5 bg-bambu-dark rounded-lg",children:l.jsx(te,{className:"w-5 h-5 text-bambu-gray"})}),l.jsxs("div",{className:"flex-1 min-w-0",children:[l.jsx("div",{className:"text-sm font-medium text-white truncate",children:X.name}),l.jsxs("div",{className:"text-xs text-bambu-gray mt-0.5 flex items-center gap-1",children:[fe==="days"?l.jsx(Zr,{className:"w-3 h-3"}):l.jsx(Uu,{className:"w-3 h-3"}),pk(X.default_interval_hours,fe)]})]})]})},X.id)}),$.map(X=>{const te=f0(X.icon),fe=X.interval_type||"hours";return k?.id===X.id?l.jsx("div",{className:"bg-bambu-dark-secondary rounded-xl p-4 border border-bambu-green",children:l.jsxs("div",{className:"space-y-3",children:[l.jsx("input",{type:"text",value:I,onChange:xe=>C(xe.target.value),className:"w-full 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",placeholder:"Name",autoFocus:!0}),l.jsxs("div",{className:"flex gap-2",children:[l.jsxs("select",{value:O,onChange:xe=>q(xe.target.value),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",children:[l.jsx("option",{value:"hours",children:"Print Hours"}),l.jsx("option",{value:"days",children:"Calendar Days"})]}),l.jsx("input",{type:"number",value:D,onChange:xe=>F(xe.target.value),className:"w-24 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",min:"1"})]}),l.jsx("div",{className:"flex flex-wrap gap-1",children:Object.keys(Vx).map(xe=>{const Ne=Vx[xe];return l.jsx("button",{type:"button",onClick:()=>W(xe),className:`p-1.5 rounded transition-colors ${R===xe?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:l.jsx(Ne,{className:"w-3.5 h-3.5"})},xe)})}),l.jsxs("div",{className:"flex gap-2",children:[l.jsx(Le,{size:"sm",onClick:G,disabled:!I.trim(),children:"Save"}),l.jsx(Le,{size:"sm",variant:"secondary",onClick:()=>N(null),children:"Cancel"})]})]})},X.id):l.jsx("div",{className:"bg-bambu-dark-secondary rounded-xl p-4 border border-bambu-green/30",children:l.jsxs("div",{className:"flex items-center gap-3",children:[l.jsx("div",{className:"p-2.5 bg-bambu-green/20 rounded-lg",children:l.jsx(te,{className:"w-5 h-5 text-bambu-green"})}),l.jsxs("div",{className:"flex-1 min-w-0",children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("span",{className:"text-sm font-medium text-white truncate",children:X.name}),l.jsx("span",{className:"px-1.5 py-0.5 bg-bambu-green/20 text-bambu-green text-[10px] font-medium rounded",children:"Custom"})]}),l.jsxs("div",{className:"text-xs text-bambu-gray mt-0.5 flex items-center gap-1",children:[fe==="days"?l.jsx(Zr,{className:"w-3 h-3"}):l.jsx(Uu,{className:"w-3 h-3"}),pk(X.default_interval_hours,fe)]})]}),l.jsx("button",{onClick:()=>K(X),className:"p-2 rounded-lg hover:bg-bambu-dark text-bambu-gray hover:text-white transition-colors",children:l.jsx(S0,{className:"w-4 h-4"})}),l.jsx("button",{onClick:()=>{confirm(`Delete "${X.name}"?`)&&a(X.id)},className:"p-2 rounded-lg hover:bg-bambu-dark text-bambu-gray hover:text-red-400 transition-colors",children:l.jsx(Rn,{className:"w-4 h-4"})})]})},X.id)})]})]}),Q.length>0&&l.jsxs("div",{children:[l.jsxs("div",{className:"mb-4",children:[l.jsx("h2",{className:"text-lg font-semibold text-white",children:"Interval Overrides"}),l.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:"Customize intervals for specific printers"})]}),l.jsx("div",{className:"space-y-4",children:Q.map(X=>l.jsx(Nt,{children:l.jsxs(Rt,{className:"py-4",children:[l.jsx("h3",{className:"text-sm font-medium text-white mb-3",children:X.printerName}),l.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-2",children:X.items.map(te=>{const fe=f0(te.maintenance_type_icon),pe=e.find(je=>je.id===te.maintenance_type_id),xe=pe?.default_interval_hours||te.interval_hours,Ne=pe?.interval_type||"hours",ie=te.interval_type||"hours",be=s===te.id;return l.jsxs("div",{className:"flex items-center gap-2 p-2.5 bg-bambu-dark rounded-lg",children:[l.jsx(fe,{className:"w-4 h-4 text-bambu-gray shrink-0"}),l.jsx("span",{className:"text-xs text-bambu-gray flex-1 truncate",children:te.maintenance_type_name}),be?l.jsxs("div",{className:"flex items-center gap-1",children:[d==="days"?l.jsx(Zr,{className:"w-3.5 h-3.5 text-bambu-gray shrink-0"}):l.jsx(Uu,{className:"w-3.5 h-3.5 text-bambu-gray shrink-0"}),l.jsxs("select",{value:d,onChange:je=>f(je.target.value),className:"px-1.5 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-xs",children:[l.jsx("option",{value:"hours",children:"Print Hours"}),l.jsx("option",{value:"days",children:"Calendar Days"})]}),l.jsx("input",{type:"number",value:c,onChange:je=>u(je.target.value),onKeyDown:je=>{je.key==="Enter"&&ee(te.id,xe,Ne),je.key==="Escape"&&o(null)},className:"w-16 px-2 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-xs",min:"1"}),l.jsx(Le,{size:"sm",onClick:()=>ee(te.id,xe,Ne),children:"OK"})]}):l.jsxs("button",{onClick:()=>{o(te.id),u(te.interval_hours.toString()),f(ie)},className:"px-2 py-1 bg-bambu-dark-tertiary hover:bg-bambu-dark-secondary border border-bambu-dark-tertiary hover:border-bambu-green rounded text-xs font-medium text-white transition-colors flex items-center gap-1",children:[ie==="days"?l.jsx(Zr,{className:"w-3 h-3"}):l.jsx(Uu,{className:"w-3 h-3"}),pk(te.interval_hours,ie),l.jsx(S0,{className:"w-3 h-3 text-bambu-gray"})]})]},te.id)})})]})},X.printerId))})]}),Q.length===0&&l.jsx(Nt,{children:l.jsxs(Rt,{className:"text-center py-12",children:[l.jsx(_r,{className:"w-12 h-12 mx-auto mb-4 text-bambu-gray/30"}),l.jsx("p",{className:"text-bambu-gray",children:"No printers configured"}),l.jsx("p",{className:"text-sm text-bambu-gray/70 mt-1",children:"Add printers to configure maintenance intervals"})]})})]})}function TGe(){const t=En(),{showToast:e}=ai(),[n,r]=E.useState("status"),{data:i,isLoading:a}=vt({queryKey:["maintenanceOverview"],queryFn:ke.getMaintenanceOverview}),{data:s}=vt({queryKey:["maintenanceTypes"],queryFn:ke.getMaintenanceTypes}),o=wt({mutationFn:({id:M,notes:S})=>ke.performMaintenance(M,S),onSuccess:()=>{t.invalidateQueries({queryKey:["maintenanceOverview"]}),t.invalidateQueries({queryKey:["maintenanceSummary"]}),e("Maintenance marked as complete")},onError:M=>{e(M.message,"error")}}),c=wt({mutationFn:({id:M,data:S})=>ke.updateMaintenanceItem(M,S),onSuccess:()=>{t.invalidateQueries({queryKey:["maintenanceOverview"]})},onError:M=>{e(M.message,"error")}}),u=wt({mutationFn:ke.createMaintenanceType,onSuccess:()=>{t.invalidateQueries({queryKey:["maintenanceTypes"]}),t.invalidateQueries({queryKey:["maintenanceOverview"]}),e("Maintenance type added")},onError:M=>{e(M.message,"error")}}),d=wt({mutationFn:({id:M,data:S})=>ke.updateMaintenanceType(M,S),onSuccess:()=>{t.invalidateQueries({queryKey:["maintenanceTypes"]}),t.invalidateQueries({queryKey:["maintenanceOverview"]}),e("Maintenance type updated")},onError:M=>{e(M.message,"error")}}),f=wt({mutationFn:ke.deleteMaintenanceType,onSuccess:()=>{t.invalidateQueries({queryKey:["maintenanceTypes"]}),t.invalidateQueries({queryKey:["maintenanceOverview"]}),e("Maintenance type deleted")},onError:M=>{e(M.message,"error")}}),g=wt({mutationFn:({printerId:M,hours:S})=>ke.setPrinterHours(M,S),onSuccess:()=>{t.invalidateQueries({queryKey:["maintenanceOverview"]}),t.invalidateQueries({queryKey:["maintenanceSummary"]}),e("Print hours updated")},onError:M=>{e(M.message,"error")}}),m=M=>{o.mutate({id:M})},x=(M,S)=>{c.mutate({id:M,data:{enabled:S}})},v=(M,S)=>{g.mutate({printerId:M,hours:S})};if(a)return l.jsx("div",{className:"p-4 md:p-8 flex justify-center",children:l.jsx(At,{className:"w-8 h-8 text-bambu-green animate-spin"})});const y=i?.reduce((M,S)=>M+S.due_count,0)||0,b=i?.reduce((M,S)=>M+S.warning_count,0)||0;return l.jsxs("div",{className:"p-4 md:p-8",children:[l.jsxs("div",{className:"mb-6",children:[l.jsx("h1",{className:"text-2xl font-bold text-white",children:"Maintenance"}),l.jsx("p",{className:"text-bambu-gray text-sm mt-1",children:n==="status"?l.jsxs(l.Fragment,{children:[y>0&&l.jsxs("span",{className:"text-red-400",children:[y," task",y!==1?"s":""," overdue"]}),y>0&&b>0&&" · ",b>0&&l.jsxs("span",{className:"text-amber-400",children:[b," due soon"]}),y===0&&b===0&&l.jsx("span",{className:"text-bambu-green",children:"All maintenance up to date"})]}):"Configure maintenance types and intervals"})]}),l.jsxs("div",{className:"flex gap-1 mb-6 border-b border-bambu-dark-tertiary",children:[l.jsx("button",{onClick:()=>r("status"),className:`px-4 py-2 text-sm font-medium border-b-2 -mb-px transition-colors ${n==="status"?"text-bambu-green border-bambu-green":"text-bambu-gray border-transparent hover:text-white"}`,children:"Status"}),l.jsx("button",{onClick:()=>r("settings"),className:`px-4 py-2 text-sm font-medium border-b-2 -mb-px transition-colors ${n==="settings"?"text-bambu-green border-bambu-green":"text-bambu-gray border-transparent hover:text-white"}`,children:"Settings"})]}),n==="status"?l.jsx("div",{className:"space-y-6",children:i&&i.length>0?[...i].sort((M,S)=>{const A=M.due_count*10+M.warning_count,T=S.due_count*10+S.warning_count;return A!==T?T-A:M.printer_name.localeCompare(S.printer_name)}).map(M=>l.jsx(EGe,{overview:M,onPerform:m,onToggle:x,onSetHours:v},M.printer_id)):l.jsx(Nt,{children:l.jsxs(Rt,{className:"text-center py-16",children:[l.jsx(ad,{className:"w-16 h-16 mx-auto mb-4 text-bambu-gray/30"}),l.jsx("p",{className:"text-lg font-medium text-white mb-2",children:"No printers configured"}),l.jsx("p",{className:"text-bambu-gray",children:"Add printers to start tracking maintenance"})]})})}):l.jsx(AGe,{overview:i,types:s||[],onUpdateInterval:(M,S)=>c.mutate({id:M,data:S}),onAddType:M=>u.mutate(M),onUpdateType:(M,S)=>d.mutate({id:M,data:S}),onDeleteType:M=>f.mutate(M)})]})}const g9=["#ef4444","#f97316","#eab308","#22c55e","#06b6d4","#3b82f6","#8b5cf6","#ec4899","#6b7280"];function CGe({project:t,onClose:e,onSave:n,isLoading:r}){const[i,a]=E.useState(t?.name||""),[s,o]=E.useState(t?.description||""),[c,u]=E.useState(t?.color||g9[0]),[d,f]=E.useState(t?.target_count?.toString()||""),[g,m]=E.useState(t?.status||"active"),x=v=>{v.preventDefault(),n({name:i.trim(),description:s.trim()||void 0,color:c,target_count:d?parseInt(d,10):void 0,...t&&{status:g}})};return l.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:l.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-md border border-bambu-dark-tertiary",children:[l.jsx("div",{className:"p-4 border-b border-bambu-dark-tertiary",children:l.jsx("h2",{className:"text-lg font-semibold text-white",children:t?"Edit Project":"New Project"})}),l.jsxs("form",{onSubmit:x,className:"p-4 space-y-4",children:[l.jsxs("div",{children:[l.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:"Name"}),l.jsx("input",{type:"text",value:i,onChange:v=>a(v.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:"e.g., Voron 2.4 Build",required:!0})]}),l.jsxs("div",{children:[l.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:"Description"}),l.jsx("textarea",{value:s,onChange:v=>o(v.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green resize-none",placeholder:"Optional description...",rows:2})]}),l.jsxs("div",{children:[l.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:"Color"}),l.jsx("div",{className:"flex gap-2 flex-wrap",children:g9.map(v=>l.jsx("button",{type:"button",onClick:()=>u(v),className:`w-8 h-8 rounded-full transition-transform ${c===v?"ring-2 ring-white ring-offset-2 ring-offset-bambu-dark-secondary scale-110":""}`,style:{backgroundColor:v}},v))})]}),l.jsxs("div",{children:[l.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:"Target Print Count (optional)"}),l.jsx("input",{type:"number",value:d,onChange:v=>f(v.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:"e.g., 50 parts to print",min:"1"})]}),t&&l.jsxs("div",{children:[l.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:"Status"}),l.jsxs("select",{value:g,onChange:v=>m(v.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white focus:outline-none focus:border-bambu-green",children:[l.jsx("option",{value:"active",children:"Active"}),l.jsx("option",{value:"completed",children:"Completed"}),l.jsx("option",{value:"archived",children:"Archived"})]})]}),l.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[l.jsx(Le,{type:"button",variant:"secondary",onClick:e,children:"Cancel"}),l.jsx(Le,{type:"submit",disabled:!i.trim()||r,children:r?l.jsx(At,{className:"w-4 h-4 animate-spin"}):t?"Save":"Create"})]})]})]})})}function NGe({project:t,onClick:e,onEdit:n,onDelete:r}){const i=t.progress_percent??0,a=t.status==="completed",s=t.status==="archived";return l.jsx(Nt,{className:"hover:border-bambu-gray/30 transition-colors cursor-pointer",onClick:e,children:l.jsxs(Rt,{className:"p-4",children:[l.jsxs("div",{className:"flex items-start justify-between mb-3",children:[l.jsxs("div",{className:"flex items-center gap-3",children:[l.jsx("div",{className:"w-3 h-3 rounded-full flex-shrink-0",style:{backgroundColor:t.color||"#6b7280"}}),l.jsxs("div",{children:[l.jsx("h3",{className:"font-medium text-white",children:t.name}),t.description&&l.jsx("p",{className:"text-sm text-bambu-gray/70 mt-0.5 line-clamp-1",children:t.description})]})]}),l.jsxs("div",{className:"flex items-center gap-1",onClick:o=>o.stopPropagation(),children:[a&&l.jsx("span",{className:"text-xs bg-bambu-green/20 text-bambu-green px-2 py-0.5 rounded",children:"Completed"}),s&&l.jsx("span",{className:"text-xs bg-bambu-gray/20 text-bambu-gray px-2 py-0.5 rounded",children:"Archived"}),l.jsx(Le,{variant:"ghost",size:"sm",onClick:n,className:"p-1",children:l.jsx(S0,{className:"w-4 h-4"})}),l.jsx(Le,{variant:"ghost",size:"sm",onClick:r,className:"p-1 text-red-400 hover:text-red-300",children:l.jsx(Rn,{className:"w-4 h-4"})})]})]}),t.target_count&&l.jsxs("div",{className:"mb-3",children:[l.jsxs("div",{className:"flex justify-between text-xs text-bambu-gray mb-1",children:[l.jsxs("span",{children:[t.archive_count," / ",t.target_count," prints"]}),l.jsxs("span",{children:[i.toFixed(0),"%"]})]}),l.jsx("div",{className:"h-2 bg-bambu-dark rounded-full overflow-hidden",children:l.jsx("div",{className:"h-full transition-all duration-300",style:{width:`${Math.min(i,100)}%`,backgroundColor:i>=100?"#22c55e":t.color||"#6b7280"}})})]}),t.archives&&t.archives.length>0&&l.jsx("div",{className:"mb-3",children:l.jsxs("div",{className:"flex gap-2",children:[t.archives.slice(0,5).map(o=>l.jsxs("a",{href:`/archives?search=${encodeURIComponent(o.print_name||"")}`,onClick:c=>c.stopPropagation(),className:"relative w-14 h-14 rounded-lg bg-bambu-dark flex-shrink-0 overflow-hidden border border-bambu-dark-tertiary hover:border-bambu-green transition-colors",title:o.print_name||"Unknown",children:[o.thumbnail_path?l.jsx("img",{src:`/api/v1/archives/${o.id}/thumbnail`,alt:o.print_name||"",className:"w-full h-full object-cover"}):l.jsx("div",{className:"w-full h-full flex items-center justify-center text-bambu-gray",children:l.jsx(w0,{className:"w-6 h-6"})}),o.status==="failed"&&l.jsx("div",{className:"absolute inset-0 bg-red-500/40 flex items-center justify-center",children:l.jsx("span",{className:"text-white text-xs font-bold",children:"✗"})})]},o.id)),t.archive_count>5&&l.jsxs("div",{className:"w-14 h-14 rounded-lg bg-bambu-dark flex-shrink-0 flex items-center justify-center text-sm text-bambu-gray border border-bambu-dark-tertiary",children:["+",t.archive_count-5]})]})}),l.jsxs("div",{className:"flex items-center gap-4 text-sm text-bambu-gray",children:[l.jsxs("div",{className:"flex items-center gap-1",title:"Archives",children:[l.jsx(_h,{className:"w-4 h-4"}),l.jsx("span",{children:t.archive_count})]}),l.jsxs("div",{className:"flex items-center gap-1",title:"Queued",children:[l.jsx(Wle,{className:"w-4 h-4"}),l.jsx("span",{children:t.queue_count})]})]})]})})}function kGe(){const t=En(),{showToast:e}=ai(),[n,r]=E.useState(!1),[i,a]=E.useState(),[s,o]=E.useState("active"),[c,u]=E.useState(null),{data:d,isLoading:f}=vt({queryKey:["projects",s==="all"?void 0:s],queryFn:()=>ke.getProjects(s==="all"?void 0:s)}),g=wt({mutationFn:A=>ke.createProject(A),onSuccess:()=>{t.invalidateQueries({queryKey:["projects"]}),r(!1),e("Project created","success")},onError:A=>{e(A.message,"error")}}),m=wt({mutationFn:({id:A,data:T})=>ke.updateProject(A,T),onSuccess:()=>{t.invalidateQueries({queryKey:["projects"]}),r(!1),a(void 0),e("Project updated","success")},onError:A=>{e(A.message,"error")}}),x=wt({mutationFn:A=>ke.deleteProject(A),onSuccess:()=>{t.invalidateQueries({queryKey:["projects"]}),u(null),e("Project deleted","success")},onError:A=>{e(A.message,"error")}}),v=A=>{i?m.mutate({id:i.id,data:A}):g.mutate(A)},y=A=>{a(A),r(!0)},b=A=>{y(A)},M=A=>{u(A)},S=()=>{c!==null&&x.mutate(c)};return l.jsxs("div",{className:"space-y-6",children:[l.jsxs("div",{className:"flex items-center justify-between",children:[l.jsxs("div",{className:"flex items-center gap-3",children:[l.jsx(qu,{className:"w-6 h-6 text-bambu-green"}),l.jsx("h1",{className:"text-2xl font-bold text-white",children:"Projects"})]}),l.jsxs(Le,{onClick:()=>r(!0),children:[l.jsx(pr,{className:"w-4 h-4 mr-2"}),"New Project"]})]}),l.jsx("div",{className:"flex gap-2",children:["active","completed","archived","all"].map(A=>l.jsx("button",{onClick:()=>o(A),className:`px-3 py-1.5 text-sm rounded-lg transition-colors ${s===A?"bg-bambu-green text-white":"bg-bambu-card text-bambu-gray hover:bg-bambu-gray/20"}`,children:A.charAt(0).toUpperCase()+A.slice(1)},A))}),f?l.jsx("div",{className:"flex items-center justify-center py-12",children:l.jsx(At,{className:"w-8 h-8 animate-spin text-bambu-green"})}):d?.length===0?l.jsx(Nt,{children:l.jsxs(Rt,{className:"py-12 text-center",children:[l.jsx(qu,{className:"w-12 h-12 text-bambu-gray/50 mx-auto mb-4"}),l.jsx("p",{className:"text-bambu-gray",children:"No projects found"}),l.jsx("p",{className:"text-bambu-gray/70 text-sm mt-1",children:"Create a project to group related prints together"})]})}):l.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:d?.map(A=>l.jsx(NGe,{project:A,onClick:()=>b(A),onEdit:()=>y(A),onDelete:()=>M(A.id)},A.id))}),c!==null&&l.jsx(Qr,{title:"Delete Project",message:"Are you sure you want to delete this project? Archives and queue items will be unlinked but not deleted.",confirmText:"Delete Project",variant:"danger",onConfirm:S,onCancel:()=>u(null)}),n&&l.jsx(CGe,{project:i,onClose:()=>{r(!1),a(void 0)},onSave:v,isLoading:g.isPending||m.isPending})]})}function PGe(){const{printerId:t}=F9(),e=parseInt(t||"0",10),[n,r]=E.useState("stream"),[i,a]=E.useState(!1),[s,o]=E.useState(!0),[c,u]=E.useState(Date.now()),[d,f]=E.useState(!1),[g,m]=E.useState(!1),x=E.useRef(null),v=E.useRef(null),{data:y}=vt({queryKey:["printer",e],queryFn:()=>ke.getPrinter(e),enabled:e>0});E.useEffect(()=>(y&&(document.title=`${y.name} - Camera`),()=>{document.title="Bambuddy"}),[y]),E.useEffect(()=>{const C=`/api/v1/printers/${e}/camera/stop`,D=()=>{e>0&&navigator.sendBeacon(C)},F=()=>{document.visibilityState==="hidden"&&e>0&&navigator.sendBeacon(C)};return window.addEventListener("beforeunload",D),document.addEventListener("visibilitychange",F),()=>{window.removeEventListener("beforeunload",D),document.removeEventListener("visibilitychange",F),x.current&&(x.current.src=""),e>0&&navigator.sendBeacon(C)}},[e]),E.useEffect(()=>{if(s&&!d){const D=setTimeout(()=>{o(!1)},n==="stream"?3e3:2e4);return()=>clearTimeout(D)}},[n,s,c,d]),E.useEffect(()=>{const C=()=>{m(!!document.fullscreenElement)};return document.addEventListener("fullscreenchange",C),()=>document.removeEventListener("fullscreenchange",C)},[]);const b=()=>{a(!0),o(!1)},M=()=>{o(!1),a(!1)},S=()=>{e>0&&fetch(`/api/v1/printers/${e}/camera/stop`).catch(()=>{})},A=C=>{n===C||d||(f(!0),o(!0),a(!1),x.current&&(x.current.src=""),n==="stream"&&S(),setTimeout(()=>{r(C),u(Date.now()),f(!1)},100))},T=()=>{d||(f(!0),o(!0),a(!1),x.current&&(x.current.src=""),n==="stream"&&S(),setTimeout(()=>{u(Date.now()),f(!1)},100))},k=()=>{v.current&&(document.fullscreenElement?document.exitFullscreen():v.current.requestFullscreen())},N=d?"":n==="stream"?`/api/v1/printers/${e}/camera/stream?fps=10&t=${c}`:`/api/v1/printers/${e}/camera/snapshot?t=${c}`,I=s||d;return e?l.jsxs("div",{ref:v,className:"min-h-screen bg-black flex flex-col",children:[l.jsxs("div",{className:"flex items-center justify-between px-4 py-2 bg-bambu-dark-secondary border-b border-bambu-dark-tertiary",children:[l.jsxs("h1",{className:"text-sm font-medium text-white flex items-center gap-2",children:[l.jsx(b0,{className:"w-4 h-4"}),y?.name||`Printer ${e}`]}),l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsxs("div",{className:"flex bg-bambu-dark rounded p-0.5",children:[l.jsx("button",{onClick:()=>A("stream"),disabled:I,className:`px-3 py-1 text-xs rounded transition-colors ${n==="stream"?"bg-bambu-green text-white":"text-bambu-gray hover:text-white disabled:opacity-50"}`,children:"Live"}),l.jsx("button",{onClick:()=>A("snapshot"),disabled:I,className:`px-3 py-1 text-xs rounded transition-colors ${n==="snapshot"?"bg-bambu-green text-white":"text-bambu-gray hover:text-white disabled:opacity-50"}`,children:"Snapshot"})]}),l.jsx("button",{onClick:T,disabled:I,className:"p-1.5 hover:bg-bambu-dark-tertiary rounded disabled:opacity-50",title:n==="stream"?"Restart stream":"Refresh snapshot",children:l.jsx(Ta,{className:`w-4 h-4 text-bambu-gray ${I?"animate-spin":""}`})}),l.jsx("button",{onClick:k,className:"p-1.5 hover:bg-bambu-dark-tertiary rounded",title:g?"Exit fullscreen":"Fullscreen",children:g?l.jsx(fce,{className:"w-4 h-4 text-bambu-gray"}):l.jsx(ace,{className:"w-4 h-4 text-bambu-gray"})})]})]}),l.jsx("div",{className:"flex-1 flex items-center justify-center p-2",children:l.jsxs("div",{className:"relative w-full h-full flex items-center justify-center",children:[(s||d)&&l.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/50 z-10",children:l.jsxs("div",{className:"text-center",children:[l.jsx(Ta,{className:"w-8 h-8 text-bambu-gray animate-spin mx-auto mb-2"}),l.jsx("p",{className:"text-sm text-bambu-gray",children:n==="stream"?"Connecting to camera...":"Capturing snapshot..."})]})}),i&&l.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black z-10",children:l.jsxs("div",{className:"text-center p-4",children:[l.jsx(ti,{className:"w-12 h-12 text-orange-400 mx-auto mb-3"}),l.jsx("p",{className:"text-white mb-2",children:"Camera unavailable"}),l.jsx("p",{className:"text-xs text-bambu-gray mb-4 max-w-md",children:"Make sure the printer is powered on and connected."}),l.jsx("button",{onClick:T,className:"px-4 py-2 bg-bambu-green text-white rounded hover:bg-bambu-green/80 transition-colors",children:"Retry"})]})}),l.jsx("img",{ref:x,src:N,alt:"Camera stream",className:"max-w-full max-h-full object-contain",onError:N?b:void 0,onLoad:N?M:void 0},c)]})})]}):l.jsx("div",{className:"min-h-screen bg-black flex items-center justify-center",children:l.jsx("p",{className:"text-white",children:"Invalid printer ID"})})}function RGe(){const{id:t}=F9(),{theme:e}=xb(),{data:n,isLoading:r,error:i}=vt({queryKey:["external-link",t],queryFn:()=>ke.getExternalLink(Number(t)),enabled:!!t});return r?l.jsx("div",{className:"flex items-center justify-center h-full",children:l.jsx(At,{className:"w-8 h-8 text-bambu-green animate-spin"})}):i||!n?l.jsxs("div",{className:"flex flex-col items-center justify-center h-full gap-4 text-bambu-gray",children:[l.jsx(ti,{className:"w-12 h-12"}),l.jsx("p",{children:"Link not found"})]}):l.jsx("iframe",{src:n.url,className:"h-full w-full border-0",style:{colorScheme:e},title:n.name,sandbox:"allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox"})}function Fr({icon:t,label:e,value:n,subValue:r,color:i="text-bambu-green"}){return l.jsxs("div",{className:"flex items-start gap-3 p-4 bg-bambu-dark rounded-lg",children:[l.jsx("div",{className:`p-2 rounded-lg bg-bambu-dark-tertiary ${i}`,children:l.jsx(t,{className:"w-5 h-5"})}),l.jsxs("div",{className:"flex-1 min-w-0",children:[l.jsx("p",{className:"text-sm text-bambu-gray",children:e}),l.jsx("p",{className:"text-lg font-semibold text-white truncate",children:n}),r&&l.jsx("p",{className:"text-xs text-bambu-gray mt-0.5",children:r})]})]})}function x9({percent:t,color:e="bg-bambu-green"}){return l.jsx("div",{className:"w-full h-2 bg-bambu-dark rounded-full overflow-hidden",children:l.jsx("div",{className:`h-full ${e} transition-all duration-300`,style:{width:`${Math.min(100,t)}%`}})})}function eh({title:t,icon:e,children:n}){return l.jsxs(Nt,{className:"p-6",children:[l.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[l.jsx(e,{className:"w-5 h-5 text-bambu-green"}),l.jsx("h2",{className:"text-lg font-semibold text-white",children:t})]}),n]})}function DGe(){const{t}=Gm(),{data:e,isLoading:n,refetch:r,isFetching:i}=vt({queryKey:["systemInfo"],queryFn:ke.getSystemInfo,refetchInterval:3e4});if(n)return l.jsx("div",{className:"flex items-center justify-center h-64",children:l.jsx(At,{className:"w-8 h-8 text-bambu-green animate-spin"})});if(!e)return l.jsx("div",{className:"p-6 text-center text-bambu-gray",children:t("system.failedToLoad","Failed to load system information")});const a=e.storage.disk_percent_used>90?"bg-red-500":e.storage.disk_percent_used>75?"bg-yellow-500":"bg-bambu-green",s=e.memory.percent_used>90?"bg-red-500":e.memory.percent_used>75?"bg-yellow-500":"bg-bambu-green";return l.jsxs("div",{className:"p-6 space-y-6",children:[l.jsxs("div",{className:"flex items-center justify-between",children:[l.jsxs("div",{children:[l.jsx("h1",{className:"text-2xl font-bold text-white",children:t("system.title","System Information")}),l.jsx("p",{className:"text-bambu-gray mt-1",children:t("system.subtitle","Monitor system resources and database statistics")})]}),l.jsxs("button",{onClick:()=>r(),disabled:i,className:"flex items-center gap-2 px-4 py-2 bg-bambu-dark-secondary hover:bg-bambu-dark-tertiary rounded-lg transition-colors disabled:opacity-50",children:[l.jsx(Ta,{className:`w-4 h-4 ${i?"animate-spin":""}`}),t("common.refresh","Refresh")]})]}),l.jsx(eh,{title:t("system.application","Application"),icon:th,children:l.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[l.jsx(Fr,{icon:th,label:t("system.version","Version"),value:`v${e.app.version}`}),l.jsx(Fr,{icon:_r,label:t("system.uptime","System Uptime"),value:e.system.uptime_formatted}),l.jsx(Fr,{icon:th,label:t("system.hostname","Hostname"),value:e.system.hostname})]})}),l.jsxs(eh,{title:t("system.database","Database"),icon:pm,children:[l.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4 mb-4",children:[l.jsx(Fr,{icon:_h,label:t("system.totalArchives","Total Archives"),value:e.database.archives}),l.jsx(Fr,{icon:Moe,label:t("system.completed","Completed"),value:e.database.archives_completed,color:"text-green-500"}),l.jsx(Fr,{icon:gs,label:t("system.failed","Failed"),value:e.database.archives_failed,color:"text-red-500"}),l.jsx(Fr,{icon:At,label:t("system.printing","Printing"),value:e.database.archives_printing,color:"text-yellow-500"})]}),l.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[l.jsx(Fr,{icon:Ts,label:t("system.printers","Printers"),value:e.database.printers}),l.jsx(Fr,{icon:dG,label:t("system.filaments","Filaments"),value:e.database.filaments}),l.jsx(Fr,{icon:qu,label:t("system.projects","Projects"),value:e.database.projects}),l.jsx(Fr,{icon:Jp,label:t("system.smartPlugs","Smart Plugs"),value:e.database.smart_plugs})]}),l.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4 mt-4",children:[l.jsx(Fr,{icon:_r,label:t("system.totalPrintTime","Total Print Time"),value:e.database.total_print_time_formatted}),l.jsx(Fr,{icon:_h,label:t("system.totalFilament","Total Filament Used"),value:`${e.database.total_filament_kg} kg`,subValue:`${e.database.total_filament_grams.toLocaleString()} g`})]})]}),l.jsxs(eh,{title:t("system.connectedPrinters","Connected Printers"),icon:Ts,children:[l.jsxs("div",{className:"flex items-center gap-4 mb-4",children:[l.jsx("div",{className:"text-3xl font-bold text-bambu-green",children:e.printers.connected}),l.jsx("div",{className:"text-bambu-gray",children:t("system.ofTotal","of {{total}} printers connected",{total:e.printers.total})})]}),e.printers.connected_list.length>0?l.jsx("div",{className:"space-y-2",children:e.printers.connected_list.map(o=>l.jsxs("div",{className:"flex items-center justify-between p-3 bg-bambu-dark rounded-lg",children:[l.jsxs("div",{className:"flex items-center gap-3",children:[l.jsx("div",{className:"w-2 h-2 rounded-full bg-bambu-green"}),l.jsx("span",{className:"font-medium text-white",children:o.name})]}),l.jsxs("div",{className:"flex items-center gap-4 text-sm text-bambu-gray",children:[l.jsx("span",{children:o.model}),l.jsx("span",{className:`px-2 py-0.5 rounded ${o.state==="RUNNING"?"bg-bambu-green/20 text-bambu-green":o.state==="IDLE"?"bg-blue-500/20 text-blue-400":"bg-bambu-dark-tertiary"}`,children:o.state})]})]},o.id))}):l.jsx("p",{className:"text-bambu-gray",children:t("system.noPrintersConnected","No printers connected")})]}),l.jsx(eh,{title:t("system.storage","Storage"),icon:BR,children:l.jsxs("div",{className:"space-y-4",children:[l.jsxs("div",{children:[l.jsxs("div",{className:"flex justify-between text-sm mb-1",children:[l.jsx("span",{className:"text-bambu-gray",children:t("system.diskUsage","Disk Usage")}),l.jsxs("span",{className:"text-white",children:[e.storage.disk_used_formatted," / ",e.storage.disk_total_formatted]})]}),l.jsx(x9,{percent:e.storage.disk_percent_used,color:a}),l.jsxs("p",{className:"text-xs text-bambu-gray mt-1",children:[e.storage.disk_free_formatted," ",t("system.free","free")," (",(100-e.storage.disk_percent_used).toFixed(1),"%)"]})]}),l.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[l.jsx(Fr,{icon:_h,label:t("system.archiveStorage","Archive Storage"),value:e.storage.archive_size_formatted}),l.jsx(Fr,{icon:pm,label:t("system.databaseSize","Database Size"),value:e.storage.database_size_formatted})]})]})}),l.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[l.jsx(eh,{title:t("system.memory","Memory"),icon:oce,children:l.jsx("div",{className:"space-y-4",children:l.jsxs("div",{children:[l.jsxs("div",{className:"flex justify-between text-sm mb-1",children:[l.jsx("span",{className:"text-bambu-gray",children:t("system.memoryUsage","Memory Usage")}),l.jsxs("span",{className:"text-white",children:[e.memory.used_formatted," / ",e.memory.total_formatted]})]}),l.jsx(x9,{percent:e.memory.percent_used,color:s}),l.jsxs("p",{className:"text-xs text-bambu-gray mt-1",children:[e.memory.available_formatted," ",t("system.available","available")]})]})})}),l.jsx(eh,{title:t("system.cpu","CPU"),icon:gv,children:l.jsx("div",{className:"space-y-4",children:l.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[l.jsx(Fr,{icon:gv,label:t("system.cores","Cores"),value:e.cpu.count,subValue:`${e.cpu.count_logical} logical`}),l.jsx(Fr,{icon:gv,label:t("system.usage","Usage"),value:`${e.cpu.percent}%`})]})})})]}),l.jsx(eh,{title:t("system.systemDetails","System Details"),icon:th,children:l.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[l.jsx(Fr,{icon:th,label:t("system.os","Operating System"),value:e.system.platform,subValue:e.system.platform_release}),l.jsx(Fr,{icon:gv,label:t("system.architecture","Architecture"),value:e.system.architecture}),l.jsx(Fr,{icon:th,label:t("system.python","Python"),value:e.system.python_version}),l.jsx(Fr,{icon:_r,label:t("system.bootTime","Boot Time"),value:new Date(e.system.boot_time).toLocaleString()})]})})]})}function jGe(){const t=E.useRef(null),e=E.useRef(null),n=En(),[r,i]=E.useState(!1),a=E.useCallback(()=>{if(t.current?.readyState===WebSocket.OPEN)return;const u=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/api/v1/ws`,d=new WebSocket(u);let f=null;d.onopen=()=>{console.log("[WebSocket] Connected"),i(!0),f=window.setInterval(()=>{d.readyState===WebSocket.OPEN&&d.send(JSON.stringify({type:"ping"}))},3e4)},d.onmessage=g=>{try{const m=JSON.parse(g.data);s(m)}catch{}},d.onclose=g=>{console.log("[WebSocket] Closed",g.code,g.reason),f&&(clearInterval(f),f=null),i(!1),t.current=null,e.current=window.setTimeout(()=>{a()},3e3)},d.onerror=g=>{console.error("[WebSocket] Error",g),d.close()},t.current=d},[]),s=E.useCallback(c=>{switch(c.type){case"printer_status":c.printer_id!==void 0&&n.setQueryData(["printerStatus",c.printer_id],u=>{const d={...u,...c.data};return d.wifi_signal==null&&u?.wifi_signal!=null&&(d.wifi_signal=u.wifi_signal),d});break;case"print_complete":n.invalidateQueries({queryKey:["archives"]}),n.invalidateQueries({queryKey:["archiveStats"]});break;case"archive_created":n.invalidateQueries({queryKey:["archives"]}),n.invalidateQueries({queryKey:["archiveStats"]});break;case"archive_updated":n.invalidateQueries({queryKey:["archives"]});break}},[n]);E.useEffect(()=>(a(),()=>{e.current&&clearTimeout(e.current),t.current&&t.current.close()}),[a]);const o=E.useCallback(c=>{t.current?.readyState===WebSocket.OPEN&&t.current.send(JSON.stringify(c))},[]);return{isConnected:r,sendMessage:o}}const OGe=new Nse({defaultOptions:{queries:{staleTime:1e3*60,retry:1}}});function LGe({children:t}){return jGe(),l.jsx(l.Fragment,{children:t})}function IGe(){return l.jsx($ue,{children:l.jsx(Jue,{children:l.jsx(kse,{client:OGe,children:l.jsx(LGe,{children:l.jsx(Zae,{children:l.jsxs(Cae,{children:[l.jsx(fs,{path:"/camera/:printerId",element:l.jsx(PGe,{})}),l.jsxs(fs,{path:"/",element:l.jsx(Yue,{}),children:[l.jsx(fs,{index:!0,element:l.jsx(wCe,{})}),l.jsx(fs,{path:"archives",element:l.jsx(XVe,{})}),l.jsx(fs,{path:"queue",element:l.jsx(j9e,{})}),l.jsx(fs,{path:"stats",element:l.jsx(K9e,{})}),l.jsx(fs,{path:"profiles",element:l.jsx(SGe,{})}),l.jsx(fs,{path:"maintenance",element:l.jsx(TGe,{})}),l.jsx(fs,{path:"projects",element:l.jsx(kGe,{})}),l.jsx(fs,{path:"settings",element:l.jsx(hGe,{})}),l.jsx(fs,{path:"system",element:l.jsx(DGe,{})}),l.jsx(fs,{path:"external/:id",element:l.jsx(RGe,{})})]})]})})})})})})}Rre.createRoot(document.getElementById("root")).render(l.jsx(E.StrictMode,{children:l.jsx(IGe,{})})); +`+n+"}"}return String(t)}function yGe({setting:t,onClose:e,onDeleted:n,onDuplicate:r,onEdit:i}){const{showToast:a}=ai(),s=En(),[o,c]=E.useState(!1),{data:u,isLoading:d}=vt({queryKey:["cloudSettingDetail",t.setting_id],queryFn:()=>ke.getCloudSettingDetail(t.setting_id)}),f=wt({mutationFn:()=>ke.deleteCloudSetting(t.setting_id),onSuccess:()=>{a("Preset deleted"),s.invalidateQueries({queryKey:["cloudSettings"]}),n()},onError:x=>a(x.message,"error")}),g=hb(t.setting_id),m=xL(t.name,u?.setting?.inherits);return l.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:l.jsx(Nt,{className:"w-full max-w-3xl max-h-[90vh] flex flex-col overflow-hidden",children:l.jsxs(Rt,{className:"p-0 flex flex-col min-h-0 flex-1",children:[l.jsxs("div",{className:"flex-shrink-0 flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[l.jsxs("div",{className:"flex-1 min-w-0",children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("h2",{className:"text-xl font-semibold text-white truncate",children:t.name}),g&&l.jsx("span",{className:"px-2 py-0.5 text-xs font-medium bg-bambu-green/20 text-bambu-green rounded-full",children:"Editable"})]}),l.jsxs("div",{className:"flex items-center gap-2 mt-1 text-sm text-bambu-gray",children:[l.jsxs("span",{className:"capitalize",children:[t.type," preset"]}),m.printer&&l.jsxs(l.Fragment,{children:[l.jsx("span",{children:"•"}),l.jsx("span",{children:m.printer})]})]})]}),l.jsx("button",{onClick:e,className:"p-2 text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:l.jsx(Wt,{className:"w-5 h-5"})})]}),l.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto p-4",children:d?l.jsx("div",{className:"flex items-center justify-center py-16",children:l.jsx(At,{className:"w-8 h-8 text-bambu-green animate-spin"})}):u?l.jsx("pre",{className:"text-xs text-bambu-gray font-mono whitespace-pre-wrap break-all bg-bambu-dark p-4 rounded-lg border border-bambu-dark-tertiary overflow-x-auto max-w-full",children:ER(u)}):l.jsx("div",{className:"text-center py-16 text-bambu-gray",children:"Failed to load preset details"})}),o?l.jsxs("div",{className:"flex-shrink-0 p-4 border-t border-bambu-dark-tertiary bg-red-500/5",children:[l.jsxs("div",{className:"flex items-center gap-2 mb-3 text-red-400",children:[l.jsx(ti,{className:"w-5 h-5"}),l.jsx("span",{className:"font-medium",children:"Delete this preset?"})]}),l.jsxs("p",{className:"text-sm text-bambu-gray mb-4",children:['This will permanently delete "',t.name,'" from Bambu Cloud. This cannot be undone.']}),l.jsxs("div",{className:"flex gap-2",children:[l.jsx(Le,{variant:"secondary",onClick:()=>c(!1),disabled:f.isPending,className:"flex-1",children:"Cancel"}),l.jsxs(Le,{variant:"danger",onClick:()=>f.mutate(),disabled:f.isPending,className:"flex-1",children:[f.isPending?l.jsx(At,{className:"w-4 h-4 animate-spin"}):l.jsx(Rn,{className:"w-4 h-4"}),"Delete"]})]})]}):l.jsx("div",{className:"flex-shrink-0 p-4 border-t border-bambu-dark-tertiary",children:l.jsxs("div",{className:"flex gap-2",children:[l.jsx(Le,{variant:"secondary",onClick:e,className:"flex-1",children:"Close"}),l.jsxs(Le,{variant:"secondary",onClick:r,children:[l.jsx(Hh,{className:"w-4 h-4"}),"Duplicate"]}),g&&l.jsxs(l.Fragment,{children:[l.jsxs(Le,{variant:"secondary",onClick:i,disabled:d||!u,children:[l.jsx(rd,{className:"w-4 h-4"}),"Edit"]}),l.jsx(Le,{variant:"danger",onClick:()=>c(!0),children:l.jsx(Rn,{className:"w-4 h-4"})})]})]})})]})})})}function mte(){try{const t=localStorage.getItem("bambusy_preset_templates");return t?JSON.parse(t):[]}catch{return[]}}function gte(t){localStorage.setItem("bambusy_preset_templates",JSON.stringify(t))}function vGe({onClose:t,onApply:e}){const{showToast:n}=ai(),[r,i]=E.useState(mte),[a,s]=E.useState("all"),[o,c]=E.useState(null),[u,d]=E.useState(""),[f,g]=E.useState(""),[m,x]=E.useState("{}"),[v,y]=E.useState(null),[b,M]=E.useState(null),S=a==="all"?r:r.filter(O=>O.type===a),A=O=>{i(O),gte(O)},T=O=>{const q=r.filter(R=>R.id!==O);A(q),M(null),n("Template deleted")},k=O=>{c(O.id),d(O.name),g(O.description),x(JSON.stringify(O.settings,null,2)),y(null)},N=()=>{if(!(!o||!u.trim()))try{const O=JSON.parse(m),q=r.map(R=>R.id===o?{...R,name:u.trim(),description:f.trim(),settings:O}:R);A(q),c(null),n("Template updated")}catch(O){y(O.message)}},I=()=>{c(null),d(""),g(""),x("{}"),y(null)},C=O=>{const q=r.map(R=>R.id===O?{...R,showInModal:!R.showInModal}:R);A(q)},D={filament:{label:"Filament",icon:IR,color:"text-amber-400"},print:{label:"Process",icon:HS,color:"text-blue-400"},printer:{label:"Printer",icon:Ts,color:"text-purple-400"}},F=b?r.find(O=>O.id===b):null;return E.useEffect(()=>{const O=q=>{q.key==="Escape"&&(b?M(null):o?I():t())};return window.addEventListener("keydown",O),()=>window.removeEventListener("keydown",O)},[b,o,t]),l.jsxs("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:[F&&l.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-60",children:l.jsx(Nt,{className:"w-full max-w-md",children:l.jsxs(Rt,{className:"p-6",children:[l.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[l.jsx("div",{className:"p-2 bg-red-500/20 rounded-lg",children:l.jsx(ti,{className:"w-6 h-6 text-red-400"})}),l.jsxs("div",{children:[l.jsx("h3",{className:"text-lg font-semibold text-white",children:"Delete Template"}),l.jsx("p",{className:"text-sm text-bambu-gray",children:"This action cannot be undone"})]})]}),l.jsxs("p",{className:"text-white mb-6",children:['Are you sure you want to delete "',l.jsx("span",{className:"font-medium",children:F.name}),'"?']}),l.jsxs("div",{className:"flex gap-2",children:[l.jsx(Le,{variant:"secondary",onClick:()=>M(null),className:"flex-1",children:"Cancel"}),l.jsxs(Le,{onClick:()=>T(b),className:"flex-1 bg-red-500 hover:bg-red-600",children:[l.jsx(Rn,{className:"w-4 h-4"}),"Delete"]})]})]})})}),l.jsx(Nt,{className:"w-full max-w-2xl max-h-[80vh] flex flex-col",children:l.jsxs(Rt,{className:"p-0 flex flex-col h-full",children:[l.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[l.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[l.jsx(M0,{className:"w-5 h-5 text-amber-400"}),"Quick Templates"]}),l.jsx("button",{onClick:t,className:"text-bambu-gray hover:text-white",children:l.jsx(Wt,{className:"w-5 h-5"})})]}),l.jsxs("div",{className:"flex items-center gap-2 p-4 border-b border-bambu-dark-tertiary",children:[l.jsx("span",{className:"text-sm text-bambu-gray",children:"Type:"}),["all","filament","print","printer"].map(O=>l.jsx("button",{onClick:()=>s(O),className:`px-3 py-1 text-sm rounded-lg transition-colors ${a===O?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:O==="all"?"All":D[O].label},O))]}),l.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:S.length===0?l.jsxs("div",{className:"text-center py-12 text-bambu-gray",children:[l.jsx(M0,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),l.jsx("p",{children:"No templates yet"}),l.jsx("p",{className:"text-sm mt-1",children:"Create templates from the preset editor"})]}):l.jsx("div",{className:"space-y-2",children:S.map(O=>{const q=D[O.type],R=q.icon;return o===O.id?l.jsxs("div",{className:"p-4 bg-bambu-dark rounded-lg border border-bambu-green",children:[l.jsxs("div",{className:"grid grid-cols-2 gap-3 mb-3",children:[l.jsx("input",{type:"text",value:u,onChange:W=>d(W.target.value),placeholder:"Template name",className:"px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none",autoFocus:!0}),l.jsx("input",{type:"text",value:f,onChange:W=>g(W.target.value),placeholder:"Description",className:"px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none"})]}),l.jsxs("div",{className:"mb-3",children:[l.jsx("label",{className:"text-xs text-bambu-gray mb-1 block",children:"Settings (JSON)"}),l.jsx("textarea",{value:m,onChange:W=>{x(W.target.value),y(null)},rows:6,className:`w-full px-3 py-2 bg-bambu-dark-secondary border rounded text-white text-sm font-mono focus:outline-none ${v?"border-red-500":"border-bambu-dark-tertiary focus:border-bambu-green"}`}),v&&l.jsx("p",{className:"text-xs text-red-400 mt-1",children:v})]}),l.jsxs("div",{className:"flex gap-2",children:[l.jsxs(Le,{size:"sm",onClick:N,disabled:!u.trim(),children:[l.jsx(Ro,{className:"w-4 h-4"}),"Save"]}),l.jsx(Le,{size:"sm",variant:"secondary",onClick:I,children:"Cancel"})]})]},O.id):l.jsxs("div",{className:"flex items-center gap-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary hover:border-bambu-gray-dark transition-colors",children:[l.jsx(R,{className:`w-5 h-5 ${q.color} flex-shrink-0`}),l.jsxs("div",{className:"flex-1 min-w-0",children:[l.jsx("p",{className:"text-sm font-medium text-white",children:O.name}),l.jsx("p",{className:"text-xs text-bambu-gray truncate",children:O.description})]}),l.jsxs("span",{className:"text-xs text-bambu-gray-dark px-2 py-1 bg-bambu-dark-secondary rounded",children:[Object.keys(O.settings).length," fields"]}),l.jsx("button",{onClick:()=>C(O.id),className:`p-1 transition-colors ${O.showInModal?"text-bambu-green hover:text-bambu-green/70":"text-bambu-gray hover:text-white"}`,title:O.showInModal?"Shown in modals":"Hidden in modals",children:O.showInModal?l.jsx(mm,{className:"w-4 h-4"}):l.jsx(FR,{className:"w-4 h-4"})}),l.jsx("button",{onClick:()=>e(O),className:"px-3 py-1 text-xs bg-bambu-green/20 text-bambu-green rounded hover:bg-bambu-green/30 transition-colors",children:"Apply"}),l.jsx("button",{onClick:()=>k(O),className:"p-1 text-bambu-gray hover:text-white",title:"Edit",children:l.jsx(rd,{className:"w-4 h-4"})}),l.jsx("button",{onClick:()=>M(O.id),className:"p-1 text-bambu-gray hover:text-red-400",title:"Delete",children:l.jsx(Rn,{className:"w-4 h-4"})})]},O.id)})})})]})})]})}function xte({onClose:t,leftPreset:e,rightPreset:n,leftLabel:r,rightLabel:i}){const[a,s]=E.useState("changes"),[o,c]=E.useState(""),u=E.useMemo(()=>{const m=new Set([...Object.keys(e),...Object.keys(n)]),x=[];for(const v of m){if(v==="inherits"||v==="version")continue;const y=e[v],b=n[v],M=v in e,S=v in n;let A;!M&&S?A="added":M&&!S?A="removed":JSON.stringify(y)!==JSON.stringify(b)?A="changed":A="same",x.push({key:v,left:y,right:b,status:A})}return x.sort((v,y)=>{const b={changed:0,added:1,removed:2,same:3};return b[v.status]!==b[y.status]?b[v.status]-b[y.status]:v.key.localeCompare(y.key)})},[e,n]),d=E.useMemo(()=>{let m=[...u];if(a==="changes"&&(m=m.filter(x=>x.status!=="same")),o){const x=o.toLowerCase();m=m.filter(v=>v.key.toLowerCase().includes(x)||String(v.left).toLowerCase().includes(x)||String(v.right).toLowerCase().includes(x))}return m},[u,a,o]),f=E.useMemo(()=>({added:u.filter(m=>m.status==="added").length,removed:u.filter(m=>m.status==="removed").length,changed:u.filter(m=>m.status==="changed").length,same:u.filter(m=>m.status==="same").length}),[u]),g=m=>{if(m===void 0)return"—";if(m===null)return"null";if(Array.isArray(m))return m.length===0?"[]":m.length===1?String(m[0]):m.join(", ");if(typeof m=="object")return JSON.stringify(m);const x=String(m);if(x.includes("\\n")||x.length>100){const v=x.split("\\n").length;if(v>1)return`[${v} lines of G-code/script]`;if(x.length>100)return x.substring(0,100)+"…"}return x};return E.useEffect(()=>{const m=x=>{x.key==="Escape"&&t()};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)},[t]),l.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:l.jsx(Nt,{className:"w-full max-w-4xl max-h-[85vh] flex flex-col overflow-hidden",children:l.jsxs(Rt,{className:"p-0 flex flex-col min-h-0 flex-1",children:[l.jsxs("div",{className:"flex-shrink-0 flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[l.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[l.jsx(Qp,{className:"w-5 h-5 text-blue-400"}),"Compare Presets"]}),l.jsx("button",{onClick:t,className:"text-bambu-gray hover:text-white",children:l.jsx(Wt,{className:"w-5 h-5"})})]}),l.jsxs("div",{className:"flex-shrink-0 grid grid-cols-2 gap-4 p-4 border-b border-bambu-dark-tertiary bg-bambu-dark",children:[l.jsxs("div",{className:"text-center",children:[l.jsx("span",{className:"text-sm text-bambu-gray",children:"Left:"}),l.jsx("p",{className:"text-white font-medium truncate",children:r})]}),l.jsxs("div",{className:"text-center",children:[l.jsx("span",{className:"text-sm text-bambu-gray",children:"Right:"}),l.jsx("p",{className:"text-white font-medium truncate",children:i})]})]}),l.jsxs("div",{className:"flex-shrink-0 flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[l.jsxs("div",{className:"flex items-center gap-4 text-sm",children:[l.jsxs("span",{className:"flex items-center gap-1 text-green-400",children:[l.jsx(pr,{className:"w-3.5 h-3.5"}),f.added," added"]}),l.jsxs("span",{className:"flex items-center gap-1 text-red-400",children:[l.jsx(Rk,{className:"w-3.5 h-3.5"}),f.removed," removed"]}),l.jsxs("span",{className:"flex items-center gap-1 text-amber-400",children:[l.jsx(Tk,{className:"w-3.5 h-3.5"}),f.changed," changed"]}),l.jsxs("span",{className:"flex items-center gap-1 text-bambu-gray",children:[l.jsx(RA,{className:"w-3.5 h-3.5"}),f.same," same"]})]}),l.jsxs("div",{className:"flex items-center gap-3",children:[l.jsxs("div",{className:"relative",children:[l.jsx(id,{className:"absolute left-2 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),l.jsx("input",{type:"text",value:o,onChange:m=>c(m.target.value),placeholder:"Search fields...",className:"pl-8 pr-3 py-1.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none w-48"})]}),f.same>0&&l.jsxs("div",{className:"flex rounded overflow-hidden border border-bambu-dark-tertiary",children:[l.jsx("button",{onClick:()=>s("changes"),className:`px-3 py-1.5 text-sm transition-colors ${a==="changes"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:"Changes"}),l.jsx("button",{onClick:()=>s("all"),className:`px-3 py-1.5 text-sm transition-colors ${a==="all"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:"All"})]})]})]}),l.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:d.length===0?l.jsxs("div",{className:"text-center py-12 text-bambu-gray",children:[l.jsx(RA,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),l.jsx("p",{children:a==="changes"?"No differences found":"No fields match the search"})]}):l.jsxs("table",{className:"w-full",children:[l.jsx("thead",{className:"sticky top-0 bg-bambu-dark-secondary",children:l.jsxs("tr",{className:"text-sm text-bambu-gray border-b border-bambu-dark-tertiary",children:[l.jsx("th",{className:"text-left p-3 w-1/3",children:"Field"}),l.jsx("th",{className:"text-left p-3 w-1/3",children:r}),l.jsx("th",{className:"text-left p-3 w-1/3",children:i})]})}),l.jsx("tbody",{children:d.map(m=>{const x={added:"bg-green-500/10",removed:"bg-red-500/10",changed:"bg-amber-500/10",same:""}[m.status],v={added:l.jsx(pr,{className:"w-3.5 h-3.5 text-green-400"}),removed:l.jsx(Rk,{className:"w-3.5 h-3.5 text-red-400"}),changed:l.jsx(Tk,{className:"w-3.5 h-3.5 text-amber-400"}),same:l.jsx(RA,{className:"w-3.5 h-3.5 text-bambu-gray-dark"})}[m.status];return l.jsxs("tr",{className:`border-b border-bambu-dark-tertiary ${x}`,children:[l.jsx("td",{className:"p-3",children:l.jsxs("div",{className:"flex items-center gap-2",children:[v,l.jsx("span",{className:"text-sm text-white font-mono",children:m.key})]})}),l.jsx("td",{className:"p-3",children:l.jsx("span",{className:`text-sm font-mono break-all ${m.status==="removed"?"text-red-300":m.status==="changed"?"text-white":"text-bambu-gray"}`,children:g(m.left)})}),l.jsx("td",{className:"p-3",children:l.jsx("span",{className:`text-sm font-mono break-all ${m.status==="added"?"text-green-300":m.status==="changed"?"text-white":"text-bambu-gray"}`,children:g(m.right)})})]},m.key)})})]})})]})})})}function _Ge({onClose:t,initialData:e,allPresets:n}){const{showToast:r}=ai(),i=En(),a=!!e?.setting_id,[s,o]=E.useState("common"),[c,u]=E.useState(e?.type||"filament"),[d,f]=E.useState(e?.name?a?e.name:`${e.name} (Copy)`:""),[g,m]=E.useState(e?.base_id||""),[x,v]=E.useState(""),[y,b]=E.useState(e?.setting||{inherits:""}),[M,S]=E.useState(JSON.stringify(e?.setting||{inherits:""},null,2)),[A,T]=E.useState(null),[k,N]=E.useState(""),[I,C]=E.useState(!1),[D,F]=E.useState(""),[O,q]=E.useState(!1),[R,W]=E.useState(mte),[K,G]=E.useState(!1),[ee,Z]=E.useState(""),[Q,U]=E.useState(""),[$,X]=E.useState(!0),[te,fe]=E.useState(null),[pe,xe]=E.useState(!1),Ne=E.useMemo(()=>({filament:n.filament,print:n.process,printer:n.printer})[c]||[],[n,c]),ie=E.useMemo(()=>Ne.filter(oe=>hb(oe.setting_id)),[Ne]),{data:be}=vt({queryKey:["cloudFields",c],queryFn:()=>ke.getCloudFields(c==="print"?"process":c),staleTime:1e3*60*60}),{data:je}=vt({queryKey:["allPresetDetails",c,ie.map(oe=>oe.setting_id).join(",")],queryFn:async()=>{const oe={};for(let He=0;He{try{const Ye=await ke.getCloudSettingDetail(de.setting_id);return{id:de.setting_id,detail:Ye}}catch{return null}}))).forEach(de=>{de&&(oe[de.id]=de.detail)})}return oe},enabled:ie.length>0,staleTime:1e3*60*10}),{data:he,isLoading:ht}=vt({queryKey:["cloudSettingDetail",g],queryFn:()=>ke.getCloudSettingDetail(g),enabled:!!g});E.useEffect(()=>{s!=="json"&&S(JSON.stringify(y,null,2))},[y,s]);const H=E.useMemo(()=>({filament:n.filament,print:n.process,printer:n.printer}[c]||[]).filter(Je=>!hb(Je.setting_id)).sort((Je,He)=>Je.name.localeCompare(He.name)),[n,c]);E.useEffect(()=>{if(!g)return;const oe=H.find(Je=>Je.setting_id===g);oe&&(v(oe.name),a||(b({inherits:oe.name}),S(JSON.stringify({inherits:oe.name},null,2))))},[g,H,a]);const B=E.useMemo(()=>{const oe=be?.fields||[],Je=new Set(oe.map(de=>de.key)),He=new Set,Ke=new Set(["inherits","updated_time","compatible_printers","compatible_prints"]);je&&Object.values(je).forEach(de=>{de?.setting&&Object.keys(de.setting).forEach(Ye=>{!Je.has(Ye)&&!Ke.has(Ye)&&He.add(Ye)})}),Object.keys(y).forEach(de=>{!Je.has(de)&&!Ke.has(de)&&He.add(de)});const ct=Array.from(He).sort().map(de=>({key:de,label:de.replace(/_/g," ").replace(/\b\w/g,Ye=>Ye.toUpperCase()),type:"text",category:"discovered",description:"Discovered from presets"}));return[...oe,...ct]},[be,je,y]),re=B.filter(oe=>oe.label.toLowerCase().includes(k.toLowerCase())||oe.key.toLowerCase().includes(k.toLowerCase())),V=()=>{if(D.trim()){const oe=D.trim().toLowerCase().replace(/\s+/g,"_");J(oe,""),F(""),q(!1),r(`Field "${oe}" added`)}},J=(oe,Je)=>{b(He=>{const Ke={...He};return Je===""||Je===void 0?delete Ke[oe]:Ke[oe]=Je,Ke})},se=oe=>{b(Je=>({...Je,...oe.settings})),fe(oe.name),r("Template applied")},Ae=()=>{if(!ee.trim())return;const oe={...y};if(delete oe.inherits,Object.keys(oe).length===0){r("No overrides to save","error");return}const Je={id:Date.now().toString(),name:ee.trim(),description:Q.trim()||"Custom template",type:c,settings:oe,showInModal:$},He=[...R,Je];W(He),gte(He),G(!1),Z(""),U(""),X(!0),r("Template saved")},Pe=E.useMemo(()=>R.filter(oe=>oe.type===c&&oe.showInModal),[c,R]),Se=oe=>{S(oe);try{const Je=JSON.parse(oe);b(Je),T(null)}catch(Je){T(Je.message)}},z=oe=>{oe.preventDefault(),C(!1);const Je=oe.dataTransfer.files[0];if(Je&&Je.name.endsWith(".json")){const He=new FileReader;He.onload=Ke=>{try{const ct=Ke.target?.result,de=JSON.parse(ct),Ye=de.setting||de;b(ge=>({...ge,...Ye})),S(JSON.stringify({...y,...Ye},null,2)),r("File imported successfully")}catch{r("Invalid JSON file","error")}},He.readAsText(Je)}},L=wt({mutationFn:()=>{const oe={...y},Je=c==="filament"?"filament_settings_id":c==="print"?"print_settings_id":"printer_settings_id";oe[Je]=`"${d}"`;const He={type:c,name:d,base_id:g,setting:oe};return ke.createCloudSetting(He)},onSuccess:async()=>{r("Preset created successfully"),await i.refetchQueries({queryKey:["cloudSettings"]}),t()},onError:oe=>r(oe.message,"error")}),ne=wt({mutationFn:()=>{if(!e?.setting_id)throw new Error("No setting ID for update");return ke.updateCloudSetting(e.setting_id,{name:d,setting:y})},onSuccess:async()=>{r("Preset updated successfully"),i.removeQueries({queryKey:["cloudSettingDetail"]}),await i.refetchQueries({queryKey:["cloudSettings"]}),t()},onError:oe=>r(oe.message,"error")}),ve=a?ne:L,we=he?.setting?.inherits,ye=we?H.find(oe=>oe.name===we):void 0,{data:nt}=vt({queryKey:["cloudSettingDetail",ye?.setting_id],queryFn:()=>ke.getCloudSettingDetail(ye.setting_id),enabled:!!ye?.setting_id}),Be=E.useMemo(()=>{const oe=nt?.setting||{},Je=he?.setting||{},He=g&&je?.[g]?.setting?je[g].setting:{};return{...oe,...Je,...He}},[g,he,nt,je]),ue=oe=>{if(oe==null)return"";if(Array.isArray(oe)){const Je=[...new Set(oe.map(He=>String(He)))];return Je.length===1?Je[0]:oe.join(", ")}return String(oe)},Ve=oe=>{const Je=y[oe.key],He=Be[oe.key],Ke=ue(He),ct=ht?"Loading...":Ke||"",de="w-full px-3 py-1.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none";if(oe.type==="boolean"){const Ye=Je==="1"||Je===void 0&&He==="1";return l.jsx("button",{type:"button",onClick:()=>J(oe.key,Je==="1"?"0":"1"),className:`w-8 h-5 rounded-full transition-colors ${Ye?"bg-bambu-green":"bg-bambu-dark-tertiary"}`,children:l.jsx("div",{className:`w-4 h-4 rounded-full bg-white shadow transition-transform ${Ye?"translate-x-3.5":"translate-x-0.5"}`})})}return oe.type==="select"?l.jsxs("select",{value:Je||"",onChange:Ye=>J(oe.key,Ye.target.value),className:de,children:[l.jsx("option",{value:"",children:ct}),oe.options?.map(Ye=>l.jsx("option",{value:Ye.value,children:Ye.label},Ye.value))]}):l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("input",{type:oe.type==="number"?"number":"text",value:Je!==void 0?String(Je):"",onChange:Ye=>J(oe.key,Ye.target.value),step:oe.step,min:oe.min,max:oe.max,placeholder:ct,className:de}),oe.unit&&l.jsx("span",{className:"text-xs text-bambu-gray whitespace-nowrap",children:oe.unit})]})},Fe=E.useMemo(()=>he?.setting?he.setting:{},[he]);return l.jsxs("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onDragOver:oe=>{oe.preventDefault(),C(!0)},onDragLeave:()=>C(!1),onDrop:z,children:[pe&&g&&l.jsx(xte,{onClose:()=>xe(!1),leftPreset:Fe,rightPreset:y,leftLabel:`Base: ${x||g}`,rightLabel:`Current: ${d||"New Preset"}`}),l.jsx(Nt,{className:"w-full max-w-6xl max-h-[90vh] flex flex-col",children:l.jsxs(Rt,{className:"p-0 flex flex-col h-full",children:[l.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[l.jsxs("div",{children:[l.jsx("h2",{className:"text-xl font-semibold text-white",children:a?"Edit Preset":e?"Duplicate Preset":"Create New Preset"}),l.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:"Customize settings for your new preset"})]}),l.jsxs("div",{className:"flex items-center gap-2",children:[g&&l.jsxs("button",{onClick:()=>xe(!0),className:"flex items-center gap-2 px-3 py-2 text-sm text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary rounded-lg transition-colors",title:"Compare with base preset",children:[l.jsx(Qp,{className:"w-4 h-4"}),"Compare"]}),l.jsx("button",{onClick:t,className:"p-2 text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:l.jsx(Wt,{className:"w-5 h-5"})})]})]}),I&&l.jsx("div",{className:"absolute inset-0 bg-bambu-green/10 border-2 border-dashed border-bambu-green rounded-lg flex items-center justify-center z-10",children:l.jsxs("div",{className:"text-center",children:[l.jsx(vs,{className:"w-12 h-12 text-bambu-green mx-auto mb-2"}),l.jsx("p",{className:"text-bambu-green font-medium",children:"Drop JSON file to import"})]})}),l.jsxs("div",{className:"p-4 border-b border-bambu-dark-tertiary space-y-3",children:[l.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[l.jsxs("div",{children:[l.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Type"}),l.jsxs("select",{value:c,onChange:oe=>{u(oe.target.value),m("")},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:[l.jsx("option",{value:"filament",children:"Filament"}),l.jsx("option",{value:"print",children:"Process"}),l.jsx("option",{value:"printer",children:"Printer"})]})]}),l.jsxs("div",{children:[l.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Base Preset"}),l.jsxs("select",{value:g,onChange:oe=>m(oe.target.value),className:"w-full 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",children:[l.jsx("option",{value:"",children:"Select base preset..."}),H.map(oe=>l.jsx("option",{value:oe.setting_id,children:oe.name},oe.setting_id))]})]}),l.jsxs("div",{children:[l.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Preset Name"}),l.jsx("input",{type:"text",value:d,onChange:oe=>f(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:"My Custom Preset"})]})]}),x&&l.jsx("div",{className:"text-xs text-bambu-gray",children:l.jsxs("p",{className:"flex items-center gap-1",children:[l.jsx(zh,{className:"w-3 h-3 text-bambu-green"}),"Inherits from: ",l.jsx("span",{className:"text-white",children:x}),ht&&l.jsx(At,{className:"w-3 h-3 animate-spin ml-1"})]})})]}),l.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary",children:[l.jsxs("button",{onClick:()=>o("common"),className:`flex items-center gap-2 px-4 py-3 text-sm font-medium transition-colors border-b-2 -mb-px ${s==="common"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-white border-transparent"}`,children:[l.jsx(ZF,{className:"w-4 h-4"}),"Common"]}),l.jsxs("button",{onClick:()=>o("fields"),className:`flex items-center gap-2 px-4 py-3 text-sm font-medium transition-colors border-b-2 -mb-px ${s==="fields"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-white border-transparent"}`,children:[l.jsx(HR,{className:"w-4 h-4"}),"All Fields"]}),l.jsxs("button",{onClick:()=>o("json"),className:`flex items-center gap-2 px-4 py-3 text-sm font-medium transition-colors border-b-2 -mb-px ${s==="json"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-white border-transparent"}`,children:[l.jsx(iG,{className:"w-4 h-4"}),"JSON",A&&l.jsx(lo,{className:"w-3 h-3 text-red-400"})]}),l.jsx("div",{className:"flex-1"}),l.jsxs("button",{onClick:()=>{const oe={name:d,type:c,base_id:g,setting:y},Je=new Blob([JSON.stringify(oe,null,2)],{type:"application/json"}),He=URL.createObjectURL(Je),Ke=document.createElement("a");Ke.href=He,Ke.download=`${d||"preset"}.json`,document.body.appendChild(Ke),Ke.click(),document.body.removeChild(Ke),URL.revokeObjectURL(He),r("Preset exported")},className:"flex items-center gap-2 px-4 py-3 text-sm text-bambu-gray hover:text-white transition-colors",title:"Export current settings to JSON file",children:[l.jsx(Es,{className:"w-4 h-4"}),"Export"]}),l.jsxs("button",{onClick:()=>document.getElementById("file-import")?.click(),className:"flex items-center gap-2 px-4 py-3 text-sm text-bambu-gray hover:text-white transition-colors",title:"Import settings from JSON file",children:[l.jsx(vs,{className:"w-4 h-4"}),"Import"]}),l.jsx("input",{id:"file-import",type:"file",accept:".json",className:"hidden",onChange:oe=>{const Je=oe.target.files?.[0];if(Je){const He=new FileReader;He.onload=Ke=>{try{const ct=JSON.parse(Ke.target?.result),de=ct.setting||ct;b(Ye=>({...Ye,...de})),r("File imported")}catch{r("Invalid JSON","error")}},He.readAsText(Je)}}})]}),l.jsxs("div",{className:"flex-1 overflow-y-auto p-4",children:[s==="common"&&l.jsxs("div",{className:"space-y-6",children:[l.jsxs("div",{children:[l.jsxs("div",{className:"flex items-center justify-between mb-3",children:[l.jsxs("h3",{className:"text-sm font-medium text-white flex items-center gap-2",children:[l.jsx(M0,{className:"w-4 h-4 text-amber-400"}),"Quick Templates"]}),Object.keys(y).filter(oe=>oe!=="inherits").length>0&&l.jsxs("button",{onClick:()=>G(!K),className:"text-xs text-bambu-gray hover:text-white flex items-center gap-1 transition-colors",children:[l.jsx(Ro,{className:"w-3 h-3"}),"Save as template"]})]}),K&&l.jsxs("div",{className:"mb-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[l.jsxs("div",{className:"grid grid-cols-2 gap-2 mb-2",children:[l.jsx("input",{type:"text",value:ee,onChange:oe=>Z(oe.target.value),placeholder:"Template name",className:"px-3 py-1.5 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none",autoFocus:!0}),l.jsx("input",{type:"text",value:Q,onChange:oe=>U(oe.target.value),placeholder:"Description (optional)",className:"px-3 py-1.5 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none"})]}),l.jsxs("div",{className:"flex items-center justify-between",children:[l.jsxs("div",{className:"flex gap-2",children:[l.jsxs(Le,{size:"sm",onClick:Ae,disabled:!ee.trim(),children:[l.jsx(Ro,{className:"w-3 h-3"}),"Save"]}),l.jsx(Le,{size:"sm",variant:"secondary",onClick:()=>G(!1),children:"Cancel"})]}),l.jsxs("button",{onClick:()=>X(!$),className:`flex items-center gap-1.5 text-xs transition-colors ${$?"text-bambu-green":"text-bambu-gray hover:text-white"}`,children:[$?l.jsx(mm,{className:"w-3.5 h-3.5"}):l.jsx(FR,{className:"w-3.5 h-3.5"}),$?"Show in modals":"Hidden in modals"]})]})]}),te&&l.jsxs("div",{className:"mb-3 px-3 py-2 bg-bambu-green/10 border border-bambu-green/30 rounded-lg flex items-center gap-2",children:[l.jsx(zh,{className:"w-4 h-4 text-bambu-green"}),l.jsxs("span",{className:"text-sm text-bambu-green",children:["Template applied: ",l.jsx("span",{className:"font-medium",children:te})]}),l.jsx("button",{onClick:()=>fe(null),className:"ml-auto text-bambu-green/70 hover:text-bambu-green",children:l.jsx(Wt,{className:"w-4 h-4"})})]}),l.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[Pe.map(oe=>l.jsxs("button",{onClick:()=>se(oe),className:"p-3 text-left bg-bambu-dark border border-bambu-dark-tertiary rounded-lg hover:border-bambu-gray-dark transition-colors",children:[l.jsx("p",{className:"text-sm font-medium text-white",children:oe.name}),l.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:oe.description})]},oe.id)),Pe.length===0&&l.jsx("p",{className:"col-span-3 text-center text-bambu-gray text-sm py-4",children:"No templates selected. Use the Templates button to enable templates for quick access."})]}),l.jsx("p",{className:"text-xs text-bambu-gray-dark mt-2 text-center",children:"Manage templates via the Templates button on the main page"})]}),l.jsxs("div",{children:[l.jsx("h3",{className:"text-sm font-medium text-white mb-3",children:"Common Settings"}),l.jsx("div",{className:"grid grid-cols-2 gap-x-6 gap-y-3",children:B.slice(0,10).map(oe=>l.jsxs("div",{className:"flex items-center justify-between gap-4",children:[l.jsx("label",{className:"text-sm text-bambu-gray flex-shrink-0",children:oe.label}),l.jsx("div",{className:"w-48",children:Ve(oe)})]},oe.key))})]}),Object.keys(y).length>1&&l.jsxs("div",{children:[l.jsx("h3",{className:"text-sm font-medium text-white mb-3",children:"Current Overrides"}),l.jsx("div",{className:"flex flex-wrap gap-2",children:Object.entries(y).filter(([oe])=>oe!=="inherits").map(([oe,Je])=>l.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-1 bg-bambu-green/10 text-bambu-green text-xs rounded",children:[oe,": ",String(Je).slice(0,20),l.jsx("button",{onClick:()=>J(oe,void 0),className:"hover:text-white",children:l.jsx(Wt,{className:"w-3 h-3"})})]},oe))})]})]}),s==="fields"&&l.jsxs("div",{className:"grid grid-cols-2 gap-6",style:{height:"400px"},children:[l.jsxs("div",{className:"flex flex-col h-full overflow-hidden",children:[l.jsxs("div",{className:"flex items-center justify-between mb-3 flex-shrink-0",children:[l.jsx("h3",{className:"text-sm font-medium text-white",children:"Available Fields"}),l.jsx("span",{className:"text-xs text-bambu-gray",children:je?`${B.length} fields`:"Loading..."})]}),l.jsxs("div",{className:"relative mb-3 flex-shrink-0",children:[l.jsx(id,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),l.jsx("input",{type:"text",value:k,onChange:oe=>N(oe.target.value),placeholder:"Search fields...",className:"w-full pl-10 pr-4 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder-bambu-gray-dark focus:border-bambu-green focus:outline-none"})]}),l.jsxs("div",{className:"flex-1 overflow-y-auto space-y-1 pr-2 min-h-0",children:[re.filter(oe=>!(oe.key in y)).map(oe=>{const Je=Be[oe.key],He=ue(Je);return l.jsxs("div",{onClick:()=>{b(Ke=>({...Ke,[oe.key]:He||""}))},className:"flex items-center justify-between gap-2 p-2 rounded-lg hover:bg-bambu-dark-tertiary transition-colors cursor-pointer group",children:[l.jsxs("div",{className:"min-w-0 flex-1",children:[l.jsx("p",{className:"text-sm text-white truncate",children:oe.label}),l.jsx("p",{className:"text-xs text-bambu-gray-dark truncate",children:oe.key})]}),l.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[He&&l.jsxs("span",{className:"text-xs text-bambu-gray bg-bambu-dark px-2 py-0.5 rounded max-w-32 truncate",title:He,children:[He.slice(0,20),He.length>20?"...":""]}),l.jsx("div",{className:"w-6 h-6 flex items-center justify-center rounded bg-bambu-dark-tertiary group-hover:bg-bambu-green/20 transition-colors",children:l.jsx(pr,{className:"w-4 h-4 text-bambu-gray group-hover:text-bambu-green transition-colors"})})]})]},oe.key)}),re.filter(oe=>!(oe.key in y)).length===0&&l.jsx("p",{className:"text-center text-bambu-gray py-4 text-sm",children:k?"No matching fields":"All fields added"})]}),l.jsx("div",{className:"pt-3 mt-3 border-t border-bambu-dark-tertiary flex-shrink-0",children:O?l.jsxs("div",{className:"flex gap-2",children:[l.jsx("input",{type:"text",value:D,onChange:oe=>F(oe.target.value),onKeyDown:oe=>oe.key==="Enter"&&V(),placeholder:"custom_field_name",className:"flex-1 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white font-mono text-sm placeholder-bambu-gray-dark focus:border-bambu-green focus:outline-none",autoFocus:!0}),l.jsx(Le,{size:"sm",onClick:V,disabled:!D.trim(),children:l.jsx(pr,{className:"w-4 h-4"})}),l.jsx(Le,{size:"sm",variant:"secondary",onClick:()=>{q(!1),F("")},children:l.jsx(Wt,{className:"w-4 h-4"})})]}):l.jsxs("button",{onClick:()=>q(!0),className:"w-full flex items-center justify-center gap-2 p-2 text-sm text-bambu-gray hover:text-white border border-dashed border-bambu-dark-tertiary hover:border-bambu-gray-dark rounded-lg transition-colors",children:[l.jsx(pr,{className:"w-4 h-4"}),"Add custom field"]})})]}),l.jsxs("div",{className:"flex flex-col h-full overflow-hidden",children:[l.jsxs("div",{className:"flex items-center justify-between mb-3 flex-shrink-0",children:[l.jsx("h3",{className:"text-sm font-medium text-white",children:"Your Overrides"}),l.jsxs("span",{className:"text-xs text-bambu-gray",children:[Object.keys(y).filter(oe=>oe!=="inherits").length," fields"]})]}),l.jsxs("div",{className:"flex-1 overflow-y-auto space-y-2 pr-2 min-h-0",children:[Object.entries(y).filter(([oe])=>oe!=="inherits").map(([oe,Je])=>{const He=B.find(Ke=>Ke.key===oe);return l.jsxs("div",{className:"p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[l.jsxs("div",{className:"flex items-center justify-between mb-2",children:[l.jsxs("div",{children:[l.jsx("p",{className:"text-sm font-medium text-white",children:He?.label||oe}),l.jsx("p",{className:"text-xs text-bambu-gray-dark",children:oe})]}),l.jsx("button",{onClick:()=>J(oe,void 0),className:"p-1 text-bambu-gray hover:text-red-400 transition-colors",children:l.jsx(Wt,{className:"w-4 h-4"})})]}),He?Ve(He):l.jsx("input",{type:"text",value:String(Je),onChange:Ke=>J(oe,Ke.target.value),className:"w-full px-3 py-1.5 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none"})]},oe)}),Object.keys(y).filter(oe=>oe!=="inherits").length===0&&l.jsxs("div",{className:"text-center py-8 text-bambu-gray",children:[l.jsx(ZF,{className:"w-8 h-8 mx-auto mb-2 opacity-50"}),l.jsx("p",{className:"text-sm",children:"No overrides yet"}),l.jsx("p",{className:"text-xs mt-1",children:"Click fields on the left to add them"})]})]}),Object.keys(y).filter(oe=>oe!=="inherits").length>0&&l.jsx("div",{className:"pt-3 mt-3 border-t border-bambu-dark-tertiary flex-shrink-0",children:l.jsxs("button",{onClick:()=>{G(!0),o("common")},className:"w-full flex items-center justify-center gap-2 p-2 text-sm text-bambu-gray hover:text-white border border-dashed border-bambu-dark-tertiary hover:border-bambu-gray-dark rounded-lg transition-colors",children:[l.jsx(Ro,{className:"w-4 h-4"}),"Save as template"]})})]})]}),s==="json"&&l.jsxs("div",{className:"space-y-2",children:[A&&l.jsxs("div",{className:"flex items-center gap-2 text-red-400 text-sm",children:[l.jsx(lo,{className:"w-4 h-4"}),A]}),l.jsx("textarea",{value:M,onChange:oe=>Se(oe.target.value),className:`w-full h-80 px-3 py-2 bg-bambu-dark border rounded-lg text-white text-xs font-mono focus:outline-none resize-none ${A?"border-red-500 focus:border-red-500":"border-bambu-dark-tertiary focus:border-bambu-green"}`,spellCheck:!1}),l.jsx("p",{className:"text-xs text-bambu-gray",children:"Tip: Drag & drop a .json file anywhere on this modal to import settings"})]})]}),l.jsxs("div",{className:"p-4 border-t border-bambu-dark-tertiary flex gap-2",children:[l.jsx(Le,{variant:"secondary",onClick:t,className:"flex-1",children:"Cancel"}),l.jsxs(Le,{onClick:()=>ve.mutate(),disabled:ve.isPending||!d.trim()||!a&&!g||!!A,className:"flex-1",children:[ve.isPending?l.jsx(At,{className:"w-4 h-4 animate-spin"}):a?l.jsx(Ro,{className:"w-4 h-4"}):l.jsx(pr,{className:"w-4 h-4"}),a?"Save":e?"Duplicate":"Create"]})]})]})})]})}function wGe({settings:t,lastSyncTime:e,onRefresh:n,isRefreshing:r,printers:i}){const[a,s]=E.useState(""),[o,c]=E.useState("all"),[u,d]=E.useState("all"),[f,g]=E.useState("all"),[m,x]=E.useState("all"),[v,y]=E.useState("all"),[b,M]=E.useState("all"),[S,A]=E.useState(null),[T,k]=E.useState(!1),[N,I]=E.useState(!1),[C,D]=E.useState(null),[F,O]=E.useState(null),[q,R]=E.useState(null),[W,K]=E.useState(!1),[G,ee]=E.useState([null,null]),[Z,Q]=E.useState(!1),[U,$]=E.useState(null),X=En(),te=E.useMemo(()=>[...t.filament.map(re=>({...re,type:"filament"})),...t.printer.map(re=>({...re,type:"printer"})),...t.process.map(re=>({...re,type:"process"}))].map(re=>({...re,meta:xL(re.name)})),[t]),fe=E.useMemo(()=>{const B=new Set,re=new Set,V=new Set;return te.forEach(J=>{J.meta.nozzle&&B.add(J.meta.nozzle),J.meta.filamentType&&re.add(J.meta.filamentType),J.meta.layerHeight&&V.add(J.meta.layerHeight)}),{printers:i.map(J=>({id:J.id.toString(),name:J.name})),nozzles:Array.from(B).sort((J,se)=>parseFloat(J)-parseFloat(se)),filaments:Array.from(re).sort(),layerHeights:Array.from(V).sort((J,se)=>parseFloat(J)-parseFloat(se))}},[te,i]),pe=E.useMemo(()=>f==="all"?null:i.find(re=>re.id.toString()===f)?.model||null,[f,i]),xe=E.useMemo(()=>te.filter(B=>o==="all"||B.type===o).filter(B=>{if(u==="all")return!0;const re=hb(B.setting_id);return u==="custom"?re:!re}).filter(B=>{if(f==="all"||!pe)return!0;const re=B.meta.printer?.toLowerCase()||"",V=pe.toLowerCase();return re.includes(V)||V.includes(re)}).filter(B=>m==="all"||B.meta.nozzle===m).filter(B=>v==="all"||B.meta.filamentType===v).filter(B=>b==="all"||B.meta.layerHeight===b).filter(B=>a===""||B.name.toLowerCase().includes(a.toLowerCase())).sort((B,re)=>B.name.localeCompare(re.name)),[te,o,u,f,pe,m,v,b,a]),Ne=B=>{if(W){const re=G[0]?.setting_id===B.setting_id,V=G[1]?.setting_id===B.setting_id;if(re)ee([G[1],null]);else if(V)ee([G[0],null]);else if(!G[0])ee([B,null]);else if(G[1]){if(G[0].type!==B.type)return;ee([G[0],B])}else{if(G[0].type!==B.type)return;ee([G[0],B])}}else A(B)},ie=B=>{if(G[0]?.setting_id===B.setting_id)return 0;if(G[1]?.setting_id===B.setting_id)return 1},be=async B=>{try{const re=await ke.getCloudSettingDetail(B.setting_id),V=B.type==="process"?"print":B.type;D({type:V,name:B.name,base_id:re.base_id||"GFSA00",setting:re.setting||{}}),A(null)}catch(re){console.error("Failed to fetch preset details for duplication:",re)}},je=async B=>{try{X.removeQueries({queryKey:["cloudSettingDetail",B.setting_id]});const re=await ke.getCloudSettingDetail(B.setting_id),V=B.type==="process"?"print":B.type;O({type:V,name:B.name,base_id:re.base_id||"GFSA00",setting:re.setting||{},setting_id:B.setting_id}),A(null)}catch(re){console.error("Failed to fetch preset details for editing:",re)}},he=()=>{c("all"),d("all"),g("all"),x("all"),y("all"),M("all"),s("")},ht=o!=="all"||u!=="all"||f!=="all"||m!=="all"||v!=="all"||b!=="all"||a!=="",H=t.filament.length+t.printer.length+t.process.length;return l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"space-y-4 mb-6",children:[l.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[l.jsxs("div",{className:"relative flex-1",children:[l.jsx(id,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),l.jsx("input",{type:"text",value:a,onChange:B=>s(B.target.value),placeholder:"Search presets...",className:"w-full pl-10 pr-4 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray-dark focus:border-bambu-green focus:outline-none"})]}),l.jsxs("div",{className:"flex gap-2",children:[l.jsxs(Le,{variant:W?"primary":"secondary",onClick:()=>{W?(K(!1),ee([null,null])):K(!0)},children:[l.jsx(Qp,{className:"w-4 h-4"}),W?"Cancel":"Compare"]}),l.jsxs(Le,{variant:"secondary",onClick:()=>I(!0),children:[l.jsx(M0,{className:"w-4 h-4"}),"Templates"]}),l.jsxs(Le,{variant:"secondary",onClick:n,disabled:r,children:[l.jsx(Ta,{className:`w-4 h-4 ${r?"animate-spin":""}`}),"Refresh"]}),l.jsxs(Le,{onClick:()=>k(!0),children:[l.jsx(pr,{className:"w-4 h-4"}),"New Preset"]})]})]}),l.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[l.jsx(UR,{className:"w-4 h-4 text-bambu-gray"}),l.jsx(Lp,{label:"Type",value:o,options:[{value:"all",label:"All",count:H},{value:"filament",label:"Filament",count:t.filament.length},{value:"printer",label:"Printer",count:t.printer.length},{value:"process",label:"Process",count:t.process.length}],onChange:B=>c(B)}),l.jsx(Lp,{label:"Owner",value:u,options:[{value:"all",label:"All"},{value:"custom",label:"My Presets"},{value:"builtin",label:"Built-in"}],onChange:B=>d(B)}),fe.printers.length>0&&l.jsx(Lp,{label:"Printer",value:f,options:[{value:"all",label:"All"},...fe.printers.map(B=>({value:B.id,label:B.name}))],onChange:g}),fe.nozzles.length>0&&l.jsx(Lp,{label:"Nozzle",value:m,options:[{value:"all",label:"All"},...fe.nozzles.map(B=>({value:B,label:B}))],onChange:x}),fe.filaments.length>0&&(o==="all"||o==="filament")&&l.jsx(Lp,{label:"Filament",value:v,options:[{value:"all",label:"All"},...fe.filaments.map(B=>({value:B,label:B}))],onChange:y}),fe.layerHeights.length>0&&(o==="all"||o==="process")&&l.jsx(Lp,{label:"Layer",value:b,options:[{value:"all",label:"All"},...fe.layerHeights.map(B=>({value:B,label:B}))],onChange:M}),ht&&l.jsx("button",{onClick:he,className:"px-3 py-2 text-sm text-bambu-gray hover:text-white transition-colors",children:"Clear filters"})]})]}),W&&l.jsx("div",{className:"mb-4 p-3 bg-blue-500/10 border border-blue-500/30 rounded-lg",children:l.jsxs("div",{className:"flex items-center justify-between",children:[l.jsxs("div",{className:"flex items-center gap-4",children:[l.jsx(Qp,{className:"w-5 h-5 text-blue-400"}),l.jsx("span",{className:"text-white font-medium",children:"Compare Mode"}),l.jsx("span",{className:"text-bambu-gray",children:G[0]?`Select another ${G[0].type} preset`:"Click two presets of the same type to compare"})]}),l.jsxs("div",{className:"flex items-center gap-3",children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("span",{className:`px-2 py-1 text-sm rounded truncate max-w-[200px] ${G[0]?"bg-blue-500/30 text-blue-700 dark:text-blue-300":"bg-bambu-dark text-bambu-gray"}`,children:G[0]?G[0].name:"1. Select first"}),l.jsx(Tk,{className:"w-4 h-4 text-bambu-gray"}),l.jsx("span",{className:`px-2 py-1 text-sm rounded truncate max-w-[200px] ${G[1]?"bg-blue-500/30 text-blue-700 dark:text-blue-300":"bg-bambu-dark text-bambu-gray"}`,children:G[1]?G[1].name:"2. Select second"})]}),G[0]&&G[1]&&l.jsxs(Le,{size:"sm",onClick:async()=>{try{const[B,re]=await Promise.all([ke.getCloudSettingDetail(G[0].setting_id),ke.getCloudSettingDetail(G[1].setting_id)]);$([B.setting||{},re.setting||{}]),Q(!0)}catch{}},children:[l.jsx(Qp,{className:"w-4 h-4"}),"Compare Now"]})]})]})}),l.jsxs("div",{className:"flex flex-wrap items-center gap-4 mb-4 text-sm text-bambu-gray",children:[e&&l.jsxs("div",{className:"flex items-center gap-1",children:[l.jsx(_r,{className:"w-3 h-3"}),"Last synced: ",gGe(e.toISOString())]}),l.jsxs("span",{children:["Showing ",xe.length," of ",H," presets"]}),l.jsxs("div",{className:"flex items-center gap-1",children:[l.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-bambu-green"}),l.jsx("span",{children:"= My preset (editable)"})]})]}),xe.length===0?l.jsxs("div",{className:"text-center py-16",children:[l.jsx($h,{className:"w-12 h-12 text-bambu-gray-dark mx-auto mb-4"}),l.jsx("p",{className:"text-bambu-gray",children:"No presets found"}),ht&&l.jsx("button",{onClick:he,className:"mt-2 text-sm text-bambu-green hover:text-bambu-green-light",children:"Clear filters"})]}):l.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-6",children:[l.jsxs("div",{children:[l.jsxs("div",{className:"flex items-center gap-2 mb-3 px-1",children:[l.jsx(IR,{className:"w-4 h-4 text-amber-400"}),l.jsx("h3",{className:"text-sm font-medium text-bambu-gray",children:"Filament"}),l.jsxs("span",{className:"text-xs text-bambu-gray-dark",children:["(",xe.filter(B=>B.type==="filament").length,")"]})]}),l.jsxs("div",{className:"space-y-1 max-h-[calc(100vh-320px)] overflow-y-auto pr-1",children:[xe.filter(B=>B.type==="filament").map(B=>l.jsx(fk,{setting:B,onClick:()=>Ne(B),onDuplicate:()=>be(B),compareMode:W,isCompareSelected:ie(B)!==void 0,compareIndex:ie(B),compareDisabled:W&&!!G[0]&&G[0].type!==B.type},B.setting_id)),xe.filter(B=>B.type==="filament").length===0&&l.jsx("p",{className:"text-xs text-bambu-gray-dark px-3 py-2",children:"No filament presets"})]})]}),l.jsxs("div",{children:[l.jsxs("div",{className:"flex items-center gap-2 mb-3 px-1",children:[l.jsx(HS,{className:"w-4 h-4 text-blue-400"}),l.jsx("h3",{className:"text-sm font-medium text-bambu-gray",children:"Process"}),l.jsxs("span",{className:"text-xs text-bambu-gray-dark",children:["(",xe.filter(B=>B.type==="process").length,")"]})]}),l.jsxs("div",{className:"space-y-1 max-h-[calc(100vh-320px)] overflow-y-auto pr-1",children:[xe.filter(B=>B.type==="process").map(B=>l.jsx(fk,{setting:B,onClick:()=>Ne(B),onDuplicate:()=>be(B),compareMode:W,isCompareSelected:ie(B)!==void 0,compareIndex:ie(B),compareDisabled:W&&!!G[0]&&G[0].type!==B.type},B.setting_id)),xe.filter(B=>B.type==="process").length===0&&l.jsx("p",{className:"text-xs text-bambu-gray-dark px-3 py-2",children:"No process presets"})]})]}),l.jsxs("div",{children:[l.jsxs("div",{className:"flex items-center gap-2 mb-3 px-1",children:[l.jsx(Ts,{className:"w-4 h-4 text-purple-400"}),l.jsx("h3",{className:"text-sm font-medium text-bambu-gray",children:"Printer"}),l.jsxs("span",{className:"text-xs text-bambu-gray-dark",children:["(",xe.filter(B=>B.type==="printer").length,")"]})]}),l.jsxs("div",{className:"space-y-1 max-h-[calc(100vh-320px)] overflow-y-auto pr-1",children:[xe.filter(B=>B.type==="printer").map(B=>l.jsx(fk,{setting:B,onClick:()=>Ne(B),onDuplicate:()=>be(B),compareMode:W,isCompareSelected:ie(B)!==void 0,compareIndex:ie(B),compareDisabled:W&&!!G[0]&&G[0].type!==B.type},B.setting_id)),xe.filter(B=>B.type==="printer").length===0&&l.jsx("p",{className:"text-xs text-bambu-gray-dark px-3 py-2",children:"No printer presets"})]})]})]}),S&&l.jsx(yGe,{setting:S,onClose:()=>A(null),onDeleted:()=>A(null),onDuplicate:()=>be(S),onEdit:()=>je(S)}),(T||C||F||q)&&l.jsx(_Ge,{onClose:()=>{k(!1),D(null),O(null),R(null)},initialData:F||C||(q?{type:q.type,name:"",base_id:"",setting:q.setting}:void 0),allPresets:t}),N&&l.jsx(vGe,{onClose:()=>I(!1),onApply:B=>{R({type:B.type,setting:B.settings}),I(!1)}}),Z&&U&&G[0]&&G[1]&&l.jsx(xte,{onClose:()=>{Q(!1),$(null)},leftPreset:U[0],rightPreset:U[1],leftLabel:G[0].name,rightLabel:G[1].name})]})}function SGe(){const t=En(),{showToast:e}=ai(),[n,r]=E.useState("cloud"),[i,a]=E.useState(),{data:s,isLoading:o}=vt({queryKey:["cloudStatus"],queryFn:ke.getCloudStatus}),{data:c=[]}=vt({queryKey:["printers"],queryFn:ke.getPrinters}),{data:u,isLoading:d,refetch:f,dataUpdatedAt:g}=vt({queryKey:["cloudSettings"],queryFn:()=>ke.getCloudSettings(),enabled:!!s?.is_authenticated,retry:!1,staleTime:1e3*60*5});E.useEffect(()=>{g&&a(new Date(g))},[g]);const m=wt({mutationFn:ke.cloudLogout,onSuccess:()=>{t.invalidateQueries({queryKey:["cloudStatus"]}),t.removeQueries({queryKey:["cloudSettings"]}),e("Logged out")}}),x=()=>{t.invalidateQueries({queryKey:["cloudStatus"]})};return o?l.jsx("div",{className:"p-4 md:p-8 flex items-center justify-center min-h-[400px]",children:l.jsx(At,{className:"w-8 h-8 text-bambu-green animate-spin"})}):l.jsxs("div",{className:"p-6 lg:p-8",children:[l.jsxs("div",{className:"mb-6",children:[l.jsx("h1",{className:"text-2xl font-bold text-white",children:"Profiles"}),l.jsx("p",{className:"text-bambu-gray",children:"Manage your slicer presets and pressure advance calibrations"})]}),l.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary mb-6",children:[l.jsxs("button",{onClick:()=>r("cloud"),className:`flex items-center gap-2 px-4 py-3 text-sm font-medium transition-colors border-b-2 -mb-px ${n==="cloud"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-white border-transparent"}`,children:[l.jsx(US,{className:"w-4 h-4"}),"Cloud Profiles"]}),l.jsxs("button",{onClick:()=>r("kprofiles"),className:`flex items-center gap-2 px-4 py-3 text-sm font-medium transition-colors border-b-2 -mb-px ${n==="kprofiles"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-white border-transparent"}`,children:[l.jsx(zR,{className:"w-4 h-4"}),"K-Profiles"]})]}),n==="cloud"&&l.jsxs(l.Fragment,{children:[s?.is_authenticated&&l.jsxs("div",{className:"flex items-center justify-between p-3 mb-6 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[l.jsxs("div",{className:"flex items-center gap-3",children:[l.jsx("div",{className:"w-2 h-2 rounded-full bg-bambu-green animate-pulse"}),l.jsxs("span",{className:"text-sm text-bambu-gray",children:["Connected as ",l.jsx("span",{className:"text-white",children:s.email})]})]}),l.jsxs(Le,{variant:"secondary",size:"sm",onClick:()=>m.mutate(),disabled:m.isPending,children:[l.jsx(Zle,{className:"w-4 h-4"}),"Logout"]})]}),s?.is_authenticated?d?l.jsx("div",{className:"flex items-center justify-center py-16",children:l.jsx(At,{className:"w-8 h-8 text-bambu-green animate-spin"})}):u?l.jsx(wGe,{settings:u,lastSyncTime:i,onRefresh:()=>f(),isRefreshing:d,printers:c}):l.jsxs("div",{className:"text-center py-16",children:[l.jsx("p",{className:"text-bambu-gray mb-4",children:"Failed to load profiles"}),l.jsx(Le,{onClick:()=>f(),children:"Retry"})]}):l.jsx(xGe,{onSuccess:x})]}),n==="kprofiles"&&l.jsx(mGe,{}),l.jsx(bGe,{})]})}const Vx={Droplet:IR,Flame:dle,Ruler:Fce,Sparkles:M0,Square:gm,Cable:loe,Wrench:ad,Calendar:Zr,Timer:Uu,Cog:Foe,Fan:ele,Zap:bm,Wind:Oue,Thermometer:Sh,Layers:$h,Box:fm,Target:fG,RefreshCw:Ta,Settings:WR,Filter:UR,CircleDot:Aoe};function f0(t){return t&&Vx[t]||ad}function Ip(t,e){return e==="days"?t<1?"Today":t===1?"1 day":t<7?`${Math.round(t)} days`:t<30?`${Math.round(t/7)} weeks`:`${Math.round(t/30)} months`:t<1?`${Math.round(t*60)}m`:t<10?`${t.toFixed(1)}h`:`${Math.round(t)}h`}function pk(t,e){return e==="days"?t===1?"1 day":t===7?"1 week":t===14?"2 weeks":t===30?"1 month":t===60?"2 months":t===90?"3 months":t===180?"6 months":t===365?"1 year":`${t} days`:`${t}h`}function MGe({item:t,onPerform:e,onToggle:n}){const r=f0(t.maintenance_type_icon),i=t.interval_type||"hours",s=(()=>{if(i==="days"){const f=t.days_since_maintenance??0;return Math.max(0,Math.min(100,f/t.interval_hours*100))}return Math.max(0,Math.min(100,(t.interval_hours-t.hours_until_due)/t.interval_hours*100))})(),o=()=>t.enabled?t.is_due?"text-red-400":t.is_warning?"text-amber-400":"text-bambu-green":"text-bambu-gray",c=()=>t.enabled?t.is_due?"bg-red-500":t.is_warning?"bg-amber-500":"bg-bambu-green":"bg-bambu-gray/30",u=()=>t.enabled?t.is_due?"bg-red-500/5 border-red-500/20":t.is_warning?"bg-amber-500/5 border-amber-500/20":"bg-bambu-dark-secondary border-bambu-dark-tertiary":"bg-bambu-dark-secondary/50",d=()=>{if(!t.enabled)return"Disabled";if(i==="days"){const f=t.days_until_due??0;return t.is_due?`Overdue by ${Ip(Math.abs(f),"days")}`:t.is_warning?`Due in ${Ip(f,"days")}`:`${Ip(f,"days")} left`}else return t.is_due?`Overdue by ${Ip(Math.abs(t.hours_until_due),"hours")}`:t.is_warning?`Due in ${Ip(t.hours_until_due,"hours")}`:`${Ip(t.hours_until_due,"hours")} left`};return l.jsx("div",{className:`rounded-xl border p-4 transition-all ${u()}`,children:l.jsxs("div",{className:"flex items-start gap-3",children:[l.jsxs("div",{className:`relative p-2.5 rounded-lg ${t.is_due?"bg-red-500/20":t.is_warning?"bg-amber-500/20":t.enabled?"bg-bambu-dark":"bg-bambu-dark/50"}`,children:[l.jsx(r,{className:`w-5 h-5 ${o()}`}),t.enabled&&(t.is_due||t.is_warning)&&l.jsx("span",{className:`absolute -top-1 -right-1 w-2.5 h-2.5 rounded-full ${t.is_due?"bg-red-500":"bg-amber-500"} animate-pulse`})]}),l.jsxs("div",{className:"flex-1 min-w-0",children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("h3",{className:`font-medium truncate ${t.enabled?"text-white":"text-bambu-gray"}`,children:t.maintenance_type_name}),i==="days"&&l.jsx("span",{title:"Time-based interval",children:l.jsx(Zr,{className:"w-3.5 h-3.5 text-bambu-gray shrink-0"})})]}),l.jsx("div",{className:"mt-2 mb-1.5",children:l.jsx("div",{className:"w-full h-1.5 bg-bambu-dark rounded-full overflow-hidden",children:l.jsx("div",{className:`h-full rounded-full transition-all duration-500 ${c()}`,style:{width:`${s}%`}})})}),l.jsxs("div",{className:`text-xs flex items-center gap-1 ${o()}`,children:[t.is_due&&l.jsx(ti,{className:"w-3 h-3"}),t.is_warning&&!t.is_due&&l.jsx(_r,{className:"w-3 h-3"}),!t.is_due&&!t.is_warning&&t.enabled&&l.jsx(zh,{className:"w-3 h-3"}),d()]})]}),l.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[l.jsx(Pn,{checked:t.enabled,onChange:f=>n(t.id,f)}),l.jsxs(Le,{size:"sm",variant:t.is_due?"primary":"secondary",onClick:()=>e(t.id),disabled:!t.enabled,className:"!px-3",children:[l.jsx(Xm,{className:"w-3.5 h-3.5"}),"Reset"]})]})]})})}function EGe({overview:t,onPerform:e,onToggle:n,onSetHours:r}){const[i,a]=E.useState(!0),[s,o]=E.useState(!1),[c,u]=E.useState(t.total_print_hours.toFixed(1)),d=[...t.maintenance_items].sort((m,x)=>m.is_due&&!x.is_due?-1:!m.is_due&&x.is_due?1:m.is_warning&&!x.is_warning?-1:!m.is_warning&&x.is_warning?1:m.maintenance_type_id-x.maintenance_type_id),f=d.find(m=>m.enabled&&(m.is_due||m.is_warning)),g=()=>{const m=parseFloat(c);!isNaN(m)&&m>=0&&(r(t.printer_id,m),o(!1))};return l.jsxs(Nt,{className:"overflow-hidden",children:[l.jsxs("div",{className:"p-5",children:[l.jsxs("div",{className:"flex items-center justify-between",children:[l.jsxs("div",{className:"flex items-center gap-4",children:[l.jsx("h2",{className:"text-xl font-semibold text-white",children:t.printer_name}),l.jsxs("div",{className:"flex items-center gap-2",children:[t.due_count>0&&l.jsxs("span",{className:"px-2.5 py-1 bg-red-500/20 text-red-400 text-xs font-medium rounded-full flex items-center gap-1.5",children:[l.jsx(ti,{className:"w-3 h-3"}),t.due_count," overdue"]}),t.warning_count>0&&l.jsxs("span",{className:"px-2.5 py-1 bg-amber-500/20 text-amber-400 text-xs font-medium rounded-full flex items-center gap-1.5",children:[l.jsx(_r,{className:"w-3 h-3"}),t.warning_count," due soon"]}),t.due_count===0&&t.warning_count===0&&l.jsxs("span",{className:"px-2.5 py-1 bg-bambu-green/20 text-bambu-green text-xs font-medium rounded-full flex items-center gap-1.5",children:[l.jsx(zh,{className:"w-3 h-3"}),"All good"]})]})]}),l.jsxs("button",{onClick:()=>a(!i),className:"flex items-center gap-1.5 px-3 py-1.5 text-sm text-bambu-gray hover:text-white hover:bg-bambu-dark rounded-lg transition-colors",children:[i?l.jsx(FS,{className:"w-4 h-4"}):l.jsx(uf,{className:"w-4 h-4"}),i?"Collapse":"Expand"]})]}),l.jsxs("div",{className:"flex items-center gap-6 mt-4",children:[l.jsxs("div",{className:"flex items-center gap-3",children:[l.jsx("div",{className:"p-2 bg-bambu-dark/50 rounded-lg",children:l.jsx(Uu,{className:"w-4 h-4 text-bambu-gray"})}),s?l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("input",{type:"number",value:c,onChange:m=>u(m.target.value),onKeyDown:m=>{m.key==="Enter"&&g(),m.key==="Escape"&&o(!1)},className:"w-24 px-2 py-1 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-sm",min:"0",step:"1",autoFocus:!0}),l.jsx("span",{className:"text-xs text-bambu-gray",children:"hours"}),l.jsx(Le,{size:"sm",onClick:g,children:"Save"}),l.jsx(Le,{size:"sm",variant:"secondary",onClick:()=>o(!1),children:"Cancel"})]}):l.jsxs("button",{onClick:()=>{u(Math.round(t.total_print_hours).toString()),o(!0)},className:"group",children:[l.jsxs("div",{className:"text-sm font-medium text-white group-hover:text-bambu-green transition-colors flex items-center gap-1",children:[Math.floor(t.total_print_hours)," hours",l.jsx(S0,{className:"w-3 h-3 text-bambu-gray group-hover:text-bambu-green"})]}),l.jsx("div",{className:"text-xs text-bambu-gray",children:"Total print time"})]})]}),l.jsx("div",{className:"w-px h-10 bg-bambu-dark-tertiary"}),f&&l.jsxs("div",{className:"flex items-center gap-3",children:[l.jsx("div",{className:`p-2 rounded-lg ${f.is_due?"bg-red-500/20":"bg-amber-500/20"}`,children:(()=>{const m=f0(f.maintenance_type_icon);return l.jsx(m,{className:`w-4 h-4 ${f.is_due?"text-red-400":"text-amber-400"}`})})()}),l.jsxs("div",{children:[l.jsx("div",{className:`text-sm font-medium ${f.is_due?"text-red-400":"text-amber-400"}`,children:f.maintenance_type_name}),l.jsx("div",{className:`text-xs ${f.is_due?"text-red-400/70":"text-amber-400/70"}`,children:f.is_due?"Overdue":"Due soon"})]})]})]})]}),i&&l.jsx(Rt,{className:"pt-0 border-t border-bambu-dark-tertiary",children:l.jsx("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-3 pt-4",children:d.map(m=>l.jsx(MGe,{item:m,onPerform:e,onToggle:n},m.id))})})]})}function AGe({overview:t,types:e,onUpdateInterval:n,onAddType:r,onUpdateType:i,onDeleteType:a}){const[s,o]=E.useState(null),[c,u]=E.useState(""),[d,f]=E.useState("hours"),[g,m]=E.useState(!1),[x,v]=E.useState(""),[y,b]=E.useState("100"),[M,S]=E.useState("hours"),[A,T]=E.useState("Wrench"),[k,N]=E.useState(null),[I,C]=E.useState(""),[D,F]=E.useState(""),[O,q]=E.useState("hours"),[R,W]=E.useState("Wrench"),K=X=>{N(X),C(X.name),F(X.default_interval_hours.toString()),q(X.interval_type||"hours"),W(X.icon||"Wrench")},G=()=>{k&&I.trim()&&parseFloat(D)>0&&(i(k.id,{name:I.trim(),default_interval_hours:parseFloat(D),interval_type:O,icon:R}),N(null))},ee=(X,te,fe)=>{const pe=parseFloat(c);if(!isNaN(pe)&&pe>0){const xe=Math.abs(pe-te)<.01?null:pe;n(X,{custom_interval_hours:xe,custom_interval_type:d!==fe?d:null})}o(null)},Z=X=>{X.preventDefault(),x.trim()&&parseFloat(y)>0&&(r({name:x.trim(),default_interval_hours:parseFloat(y),interval_type:M,icon:A}),v(""),b("100"),S("hours"),m(!1))},Q=t?.map(X=>({printerId:X.printer_id,printerName:X.printer_name,items:X.maintenance_items.sort((te,fe)=>te.maintenance_type_id-fe.maintenance_type_id)})).sort((X,te)=>X.printerName.localeCompare(te.printerName))||[],U=e.filter(X=>X.is_system),$=e.filter(X=>!X.is_system);return l.jsxs("div",{className:"space-y-8",children:[l.jsxs("div",{children:[l.jsxs("div",{className:"flex items-center justify-between mb-4",children:[l.jsxs("div",{children:[l.jsx("h2",{className:"text-lg font-semibold text-white",children:"Maintenance Types"}),l.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:"System types and your custom maintenance tasks"})]}),l.jsxs(Le,{onClick:()=>m(!g),children:[l.jsx(pr,{className:"w-4 h-4"}),"Add Custom Type"]})]}),g&&l.jsx(Nt,{className:"mb-6",children:l.jsx(Rt,{className:"py-4",children:l.jsxs("form",{onSubmit:Z,children:[l.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4",children:[l.jsxs("div",{className:"lg:col-span-2",children:[l.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:"Name"}),l.jsx("input",{type:"text",value:x,onChange:X=>v(X.target.value),className:"w-full 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",placeholder:"e.g., Replace HEPA Filter",autoFocus:!0})]}),l.jsxs("div",{children:[l.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:"Interval Type"}),l.jsxs("select",{value:M,onChange:X=>{S(X.target.value),X.target.value==="days"?b("30"):b("100")},className:"w-full 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",children:[l.jsx("option",{value:"hours",children:"Print Hours"}),l.jsx("option",{value:"days",children:"Calendar Days"})]})]}),l.jsxs("div",{children:[l.jsxs("label",{className:"block text-xs text-bambu-gray mb-1.5",children:["Interval (",M==="days"?"days":"hours",")"]}),l.jsx("input",{type:"number",value:y,onChange:X=>b(X.target.value),className:"w-full 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",min:"1"})]})]}),l.jsxs("div",{className:"mt-4 flex items-end justify-between",children:[l.jsxs("div",{children:[l.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:"Icon"}),l.jsx("div",{className:"flex gap-1",children:Object.keys(Vx).map(X=>{const te=Vx[X];return l.jsx("button",{type:"button",onClick:()=>T(X),className:`p-2 rounded-lg transition-colors ${A===X?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary"}`,children:l.jsx(te,{className:"w-4 h-4"})},X)})})]}),l.jsxs("div",{className:"flex gap-2",children:[l.jsx(Le,{type:"button",variant:"secondary",onClick:()=>m(!1),children:"Cancel"}),l.jsx(Le,{type:"submit",disabled:!x.trim(),children:"Add Type"})]})]})]})})}),l.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3",children:[U.map(X=>{const te=f0(X.icon),fe=X.interval_type||"hours";return l.jsx("div",{className:"bg-bambu-dark-secondary rounded-xl p-4 border border-bambu-dark-tertiary",children:l.jsxs("div",{className:"flex items-center gap-3",children:[l.jsx("div",{className:"p-2.5 bg-bambu-dark rounded-lg",children:l.jsx(te,{className:"w-5 h-5 text-bambu-gray"})}),l.jsxs("div",{className:"flex-1 min-w-0",children:[l.jsx("div",{className:"text-sm font-medium text-white truncate",children:X.name}),l.jsxs("div",{className:"text-xs text-bambu-gray mt-0.5 flex items-center gap-1",children:[fe==="days"?l.jsx(Zr,{className:"w-3 h-3"}):l.jsx(Uu,{className:"w-3 h-3"}),pk(X.default_interval_hours,fe)]})]})]})},X.id)}),$.map(X=>{const te=f0(X.icon),fe=X.interval_type||"hours";return k?.id===X.id?l.jsx("div",{className:"bg-bambu-dark-secondary rounded-xl p-4 border border-bambu-green",children:l.jsxs("div",{className:"space-y-3",children:[l.jsx("input",{type:"text",value:I,onChange:xe=>C(xe.target.value),className:"w-full 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",placeholder:"Name",autoFocus:!0}),l.jsxs("div",{className:"flex gap-2",children:[l.jsxs("select",{value:O,onChange:xe=>q(xe.target.value),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",children:[l.jsx("option",{value:"hours",children:"Print Hours"}),l.jsx("option",{value:"days",children:"Calendar Days"})]}),l.jsx("input",{type:"number",value:D,onChange:xe=>F(xe.target.value),className:"w-24 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",min:"1"})]}),l.jsx("div",{className:"flex flex-wrap gap-1",children:Object.keys(Vx).map(xe=>{const Ne=Vx[xe];return l.jsx("button",{type:"button",onClick:()=>W(xe),className:`p-1.5 rounded transition-colors ${R===xe?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:l.jsx(Ne,{className:"w-3.5 h-3.5"})},xe)})}),l.jsxs("div",{className:"flex gap-2",children:[l.jsx(Le,{size:"sm",onClick:G,disabled:!I.trim(),children:"Save"}),l.jsx(Le,{size:"sm",variant:"secondary",onClick:()=>N(null),children:"Cancel"})]})]})},X.id):l.jsx("div",{className:"bg-bambu-dark-secondary rounded-xl p-4 border border-bambu-green/30",children:l.jsxs("div",{className:"flex items-center gap-3",children:[l.jsx("div",{className:"p-2.5 bg-bambu-green/20 rounded-lg",children:l.jsx(te,{className:"w-5 h-5 text-bambu-green"})}),l.jsxs("div",{className:"flex-1 min-w-0",children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("span",{className:"text-sm font-medium text-white truncate",children:X.name}),l.jsx("span",{className:"px-1.5 py-0.5 bg-bambu-green/20 text-bambu-green text-[10px] font-medium rounded",children:"Custom"})]}),l.jsxs("div",{className:"text-xs text-bambu-gray mt-0.5 flex items-center gap-1",children:[fe==="days"?l.jsx(Zr,{className:"w-3 h-3"}):l.jsx(Uu,{className:"w-3 h-3"}),pk(X.default_interval_hours,fe)]})]}),l.jsx("button",{onClick:()=>K(X),className:"p-2 rounded-lg hover:bg-bambu-dark text-bambu-gray hover:text-white transition-colors",children:l.jsx(S0,{className:"w-4 h-4"})}),l.jsx("button",{onClick:()=>{confirm(`Delete "${X.name}"?`)&&a(X.id)},className:"p-2 rounded-lg hover:bg-bambu-dark text-bambu-gray hover:text-red-400 transition-colors",children:l.jsx(Rn,{className:"w-4 h-4"})})]})},X.id)})]})]}),Q.length>0&&l.jsxs("div",{children:[l.jsxs("div",{className:"mb-4",children:[l.jsx("h2",{className:"text-lg font-semibold text-white",children:"Interval Overrides"}),l.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:"Customize intervals for specific printers"})]}),l.jsx("div",{className:"space-y-4",children:Q.map(X=>l.jsx(Nt,{children:l.jsxs(Rt,{className:"py-4",children:[l.jsx("h3",{className:"text-sm font-medium text-white mb-3",children:X.printerName}),l.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-2",children:X.items.map(te=>{const fe=f0(te.maintenance_type_icon),pe=e.find(je=>je.id===te.maintenance_type_id),xe=pe?.default_interval_hours||te.interval_hours,Ne=pe?.interval_type||"hours",ie=te.interval_type||"hours",be=s===te.id;return l.jsxs("div",{className:"flex items-center gap-2 p-2.5 bg-bambu-dark rounded-lg",children:[l.jsx(fe,{className:"w-4 h-4 text-bambu-gray shrink-0"}),l.jsx("span",{className:"text-xs text-bambu-gray flex-1 truncate",children:te.maintenance_type_name}),be?l.jsxs("div",{className:"flex items-center gap-1",children:[d==="days"?l.jsx(Zr,{className:"w-3.5 h-3.5 text-bambu-gray shrink-0"}):l.jsx(Uu,{className:"w-3.5 h-3.5 text-bambu-gray shrink-0"}),l.jsxs("select",{value:d,onChange:je=>f(je.target.value),className:"px-1.5 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-xs",children:[l.jsx("option",{value:"hours",children:"Print Hours"}),l.jsx("option",{value:"days",children:"Calendar Days"})]}),l.jsx("input",{type:"number",value:c,onChange:je=>u(je.target.value),onKeyDown:je=>{je.key==="Enter"&&ee(te.id,xe,Ne),je.key==="Escape"&&o(null)},className:"w-16 px-2 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-xs",min:"1"}),l.jsx(Le,{size:"sm",onClick:()=>ee(te.id,xe,Ne),children:"OK"})]}):l.jsxs("button",{onClick:()=>{o(te.id),u(te.interval_hours.toString()),f(ie)},className:"px-2 py-1 bg-bambu-dark-tertiary hover:bg-bambu-dark-secondary border border-bambu-dark-tertiary hover:border-bambu-green rounded text-xs font-medium text-white transition-colors flex items-center gap-1",children:[ie==="days"?l.jsx(Zr,{className:"w-3 h-3"}):l.jsx(Uu,{className:"w-3 h-3"}),pk(te.interval_hours,ie),l.jsx(S0,{className:"w-3 h-3 text-bambu-gray"})]})]},te.id)})})]})},X.printerId))})]}),Q.length===0&&l.jsx(Nt,{children:l.jsxs(Rt,{className:"text-center py-12",children:[l.jsx(_r,{className:"w-12 h-12 mx-auto mb-4 text-bambu-gray/30"}),l.jsx("p",{className:"text-bambu-gray",children:"No printers configured"}),l.jsx("p",{className:"text-sm text-bambu-gray/70 mt-1",children:"Add printers to configure maintenance intervals"})]})})]})}function TGe(){const t=En(),{showToast:e}=ai(),[n,r]=E.useState("status"),{data:i,isLoading:a}=vt({queryKey:["maintenanceOverview"],queryFn:ke.getMaintenanceOverview}),{data:s}=vt({queryKey:["maintenanceTypes"],queryFn:ke.getMaintenanceTypes}),o=wt({mutationFn:({id:M,notes:S})=>ke.performMaintenance(M,S),onSuccess:()=>{t.invalidateQueries({queryKey:["maintenanceOverview"]}),t.invalidateQueries({queryKey:["maintenanceSummary"]}),e("Maintenance marked as complete")},onError:M=>{e(M.message,"error")}}),c=wt({mutationFn:({id:M,data:S})=>ke.updateMaintenanceItem(M,S),onSuccess:()=>{t.invalidateQueries({queryKey:["maintenanceOverview"]})},onError:M=>{e(M.message,"error")}}),u=wt({mutationFn:ke.createMaintenanceType,onSuccess:()=>{t.invalidateQueries({queryKey:["maintenanceTypes"]}),t.invalidateQueries({queryKey:["maintenanceOverview"]}),e("Maintenance type added")},onError:M=>{e(M.message,"error")}}),d=wt({mutationFn:({id:M,data:S})=>ke.updateMaintenanceType(M,S),onSuccess:()=>{t.invalidateQueries({queryKey:["maintenanceTypes"]}),t.invalidateQueries({queryKey:["maintenanceOverview"]}),e("Maintenance type updated")},onError:M=>{e(M.message,"error")}}),f=wt({mutationFn:ke.deleteMaintenanceType,onSuccess:()=>{t.invalidateQueries({queryKey:["maintenanceTypes"]}),t.invalidateQueries({queryKey:["maintenanceOverview"]}),e("Maintenance type deleted")},onError:M=>{e(M.message,"error")}}),g=wt({mutationFn:({printerId:M,hours:S})=>ke.setPrinterHours(M,S),onSuccess:()=>{t.invalidateQueries({queryKey:["maintenanceOverview"]}),t.invalidateQueries({queryKey:["maintenanceSummary"]}),e("Print hours updated")},onError:M=>{e(M.message,"error")}}),m=M=>{o.mutate({id:M})},x=(M,S)=>{c.mutate({id:M,data:{enabled:S}})},v=(M,S)=>{g.mutate({printerId:M,hours:S})};if(a)return l.jsx("div",{className:"p-4 md:p-8 flex justify-center",children:l.jsx(At,{className:"w-8 h-8 text-bambu-green animate-spin"})});const y=i?.reduce((M,S)=>M+S.due_count,0)||0,b=i?.reduce((M,S)=>M+S.warning_count,0)||0;return l.jsxs("div",{className:"p-4 md:p-8",children:[l.jsxs("div",{className:"mb-6",children:[l.jsx("h1",{className:"text-2xl font-bold text-white",children:"Maintenance"}),l.jsx("p",{className:"text-bambu-gray text-sm mt-1",children:n==="status"?l.jsxs(l.Fragment,{children:[y>0&&l.jsxs("span",{className:"text-red-400",children:[y," task",y!==1?"s":""," overdue"]}),y>0&&b>0&&" · ",b>0&&l.jsxs("span",{className:"text-amber-400",children:[b," due soon"]}),y===0&&b===0&&l.jsx("span",{className:"text-bambu-green",children:"All maintenance up to date"})]}):"Configure maintenance types and intervals"})]}),l.jsxs("div",{className:"flex gap-1 mb-6 border-b border-bambu-dark-tertiary",children:[l.jsx("button",{onClick:()=>r("status"),className:`px-4 py-2 text-sm font-medium border-b-2 -mb-px transition-colors ${n==="status"?"text-bambu-green border-bambu-green":"text-bambu-gray border-transparent hover:text-white"}`,children:"Status"}),l.jsx("button",{onClick:()=>r("settings"),className:`px-4 py-2 text-sm font-medium border-b-2 -mb-px transition-colors ${n==="settings"?"text-bambu-green border-bambu-green":"text-bambu-gray border-transparent hover:text-white"}`,children:"Settings"})]}),n==="status"?l.jsx("div",{className:"space-y-6",children:i&&i.length>0?[...i].sort((M,S)=>{const A=M.due_count*10+M.warning_count,T=S.due_count*10+S.warning_count;return A!==T?T-A:M.printer_name.localeCompare(S.printer_name)}).map(M=>l.jsx(EGe,{overview:M,onPerform:m,onToggle:x,onSetHours:v},M.printer_id)):l.jsx(Nt,{children:l.jsxs(Rt,{className:"text-center py-16",children:[l.jsx(ad,{className:"w-16 h-16 mx-auto mb-4 text-bambu-gray/30"}),l.jsx("p",{className:"text-lg font-medium text-white mb-2",children:"No printers configured"}),l.jsx("p",{className:"text-bambu-gray",children:"Add printers to start tracking maintenance"})]})})}):l.jsx(AGe,{overview:i,types:s||[],onUpdateInterval:(M,S)=>c.mutate({id:M,data:S}),onAddType:M=>u.mutate(M),onUpdateType:(M,S)=>d.mutate({id:M,data:S}),onDeleteType:M=>f.mutate(M)})]})}const g9=["#ef4444","#f97316","#eab308","#22c55e","#06b6d4","#3b82f6","#8b5cf6","#ec4899","#6b7280"];function CGe({project:t,onClose:e,onSave:n,isLoading:r}){const[i,a]=E.useState(t?.name||""),[s,o]=E.useState(t?.description||""),[c,u]=E.useState(t?.color||g9[0]),[d,f]=E.useState(t?.target_count?.toString()||""),[g,m]=E.useState(t?.status||"active"),x=v=>{v.preventDefault(),n({name:i.trim(),description:s.trim()||void 0,color:c,target_count:d?parseInt(d,10):void 0,...t&&{status:g}})};return l.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:l.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-md border border-bambu-dark-tertiary",children:[l.jsx("div",{className:"p-4 border-b border-bambu-dark-tertiary",children:l.jsx("h2",{className:"text-lg font-semibold text-white",children:t?"Edit Project":"New Project"})}),l.jsxs("form",{onSubmit:x,className:"p-4 space-y-4",children:[l.jsxs("div",{children:[l.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:"Name"}),l.jsx("input",{type:"text",value:i,onChange:v=>a(v.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:"e.g., Voron 2.4 Build",required:!0})]}),l.jsxs("div",{children:[l.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:"Description"}),l.jsx("textarea",{value:s,onChange:v=>o(v.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green resize-none",placeholder:"Optional description...",rows:2})]}),l.jsxs("div",{children:[l.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:"Color"}),l.jsx("div",{className:"flex gap-2 flex-wrap",children:g9.map(v=>l.jsx("button",{type:"button",onClick:()=>u(v),className:`w-8 h-8 rounded-full transition-transform ${c===v?"ring-2 ring-white ring-offset-2 ring-offset-bambu-dark-secondary scale-110":""}`,style:{backgroundColor:v}},v))})]}),l.jsxs("div",{children:[l.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:"Target Print Count (optional)"}),l.jsx("input",{type:"number",value:d,onChange:v=>f(v.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:"e.g., 50 parts to print",min:"1"})]}),t&&l.jsxs("div",{children:[l.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:"Status"}),l.jsxs("select",{value:g,onChange:v=>m(v.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white focus:outline-none focus:border-bambu-green",children:[l.jsx("option",{value:"active",children:"Active"}),l.jsx("option",{value:"completed",children:"Completed"}),l.jsx("option",{value:"archived",children:"Archived"})]})]}),l.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[l.jsx(Le,{type:"button",variant:"secondary",onClick:e,children:"Cancel"}),l.jsx(Le,{type:"submit",disabled:!i.trim()||r,children:r?l.jsx(At,{className:"w-4 h-4 animate-spin"}):t?"Save":"Create"})]})]})]})})}function NGe({project:t,onClick:e,onEdit:n,onDelete:r}){const i=t.progress_percent??0,a=t.status==="completed",s=t.status==="archived";return l.jsx(Nt,{className:"hover:border-bambu-gray/30 transition-colors cursor-pointer",onClick:e,children:l.jsxs(Rt,{className:"p-4",children:[l.jsxs("div",{className:"flex items-start justify-between mb-3",children:[l.jsxs("div",{className:"flex items-center gap-3",children:[l.jsx("div",{className:"w-3 h-3 rounded-full flex-shrink-0",style:{backgroundColor:t.color||"#6b7280"}}),l.jsxs("div",{children:[l.jsx("h3",{className:"font-medium text-white",children:t.name}),t.description&&l.jsx("p",{className:"text-sm text-bambu-gray/70 mt-0.5 line-clamp-1",children:t.description})]})]}),l.jsxs("div",{className:"flex items-center gap-1",onClick:o=>o.stopPropagation(),children:[a&&l.jsx("span",{className:"text-xs bg-bambu-green/20 text-bambu-green px-2 py-0.5 rounded",children:"Completed"}),s&&l.jsx("span",{className:"text-xs bg-bambu-gray/20 text-bambu-gray px-2 py-0.5 rounded",children:"Archived"}),l.jsx(Le,{variant:"ghost",size:"sm",onClick:n,className:"p-1",children:l.jsx(S0,{className:"w-4 h-4"})}),l.jsx(Le,{variant:"ghost",size:"sm",onClick:r,className:"p-1 text-red-400 hover:text-red-300",children:l.jsx(Rn,{className:"w-4 h-4"})})]})]}),t.target_count&&l.jsxs("div",{className:"mb-3",children:[l.jsxs("div",{className:"flex justify-between text-xs text-bambu-gray mb-1",children:[l.jsxs("span",{children:[t.archive_count," / ",t.target_count," prints"]}),l.jsxs("span",{children:[i.toFixed(0),"%"]})]}),l.jsx("div",{className:"h-2 bg-bambu-dark rounded-full overflow-hidden",children:l.jsx("div",{className:"h-full transition-all duration-300",style:{width:`${Math.min(i,100)}%`,backgroundColor:i>=100?"#22c55e":t.color||"#6b7280"}})})]}),t.archives&&t.archives.length>0&&l.jsx("div",{className:"mb-3",children:l.jsxs("div",{className:"flex gap-2",children:[t.archives.slice(0,5).map(o=>l.jsxs("a",{href:`/archives?search=${encodeURIComponent(o.print_name||"")}`,onClick:c=>c.stopPropagation(),className:"relative w-14 h-14 rounded-lg bg-bambu-dark flex-shrink-0 overflow-hidden border border-bambu-dark-tertiary hover:border-bambu-green transition-colors",title:o.print_name||"Unknown",children:[o.thumbnail_path?l.jsx("img",{src:`/api/v1/archives/${o.id}/thumbnail`,alt:o.print_name||"",className:"w-full h-full object-cover"}):l.jsx("div",{className:"w-full h-full flex items-center justify-center text-bambu-gray",children:l.jsx(w0,{className:"w-6 h-6"})}),o.status==="failed"&&l.jsx("div",{className:"absolute inset-0 bg-red-500/40 flex items-center justify-center",children:l.jsx("span",{className:"text-white text-xs font-bold",children:"✗"})})]},o.id)),t.archive_count>5&&l.jsxs("div",{className:"w-14 h-14 rounded-lg bg-bambu-dark flex-shrink-0 flex items-center justify-center text-sm text-bambu-gray border border-bambu-dark-tertiary",children:["+",t.archive_count-5]})]})}),l.jsxs("div",{className:"flex items-center gap-4 text-sm text-bambu-gray",children:[l.jsxs("div",{className:"flex items-center gap-1",title:"Archives",children:[l.jsx(_h,{className:"w-4 h-4"}),l.jsx("span",{children:t.archive_count})]}),l.jsxs("div",{className:"flex items-center gap-1",title:"Queued",children:[l.jsx(Wle,{className:"w-4 h-4"}),l.jsx("span",{children:t.queue_count})]})]})]})})}function kGe(){const t=En(),{showToast:e}=ai(),[n,r]=E.useState(!1),[i,a]=E.useState(),[s,o]=E.useState("active"),[c,u]=E.useState(null),{data:d,isLoading:f}=vt({queryKey:["projects",s==="all"?void 0:s],queryFn:()=>ke.getProjects(s==="all"?void 0:s)}),g=wt({mutationFn:A=>ke.createProject(A),onSuccess:()=>{t.invalidateQueries({queryKey:["projects"]}),r(!1),e("Project created","success")},onError:A=>{e(A.message,"error")}}),m=wt({mutationFn:({id:A,data:T})=>ke.updateProject(A,T),onSuccess:()=>{t.invalidateQueries({queryKey:["projects"]}),r(!1),a(void 0),e("Project updated","success")},onError:A=>{e(A.message,"error")}}),x=wt({mutationFn:A=>ke.deleteProject(A),onSuccess:()=>{t.invalidateQueries({queryKey:["projects"]}),u(null),e("Project deleted","success")},onError:A=>{e(A.message,"error")}}),v=A=>{i?m.mutate({id:i.id,data:A}):g.mutate(A)},y=A=>{a(A),r(!0)},b=A=>{y(A)},M=A=>{u(A)},S=()=>{c!==null&&x.mutate(c)};return l.jsxs("div",{className:"space-y-6",children:[l.jsxs("div",{className:"flex items-center justify-between",children:[l.jsxs("div",{className:"flex items-center gap-3",children:[l.jsx(qu,{className:"w-6 h-6 text-bambu-green"}),l.jsx("h1",{className:"text-2xl font-bold text-white",children:"Projects"})]}),l.jsxs(Le,{onClick:()=>r(!0),children:[l.jsx(pr,{className:"w-4 h-4 mr-2"}),"New Project"]})]}),l.jsx("div",{className:"flex gap-2",children:["active","completed","archived","all"].map(A=>l.jsx("button",{onClick:()=>o(A),className:`px-3 py-1.5 text-sm rounded-lg transition-colors ${s===A?"bg-bambu-green text-white":"bg-bambu-card text-bambu-gray hover:bg-bambu-gray/20"}`,children:A.charAt(0).toUpperCase()+A.slice(1)},A))}),f?l.jsx("div",{className:"flex items-center justify-center py-12",children:l.jsx(At,{className:"w-8 h-8 animate-spin text-bambu-green"})}):d?.length===0?l.jsx(Nt,{children:l.jsxs(Rt,{className:"py-12 text-center",children:[l.jsx(qu,{className:"w-12 h-12 text-bambu-gray/50 mx-auto mb-4"}),l.jsx("p",{className:"text-bambu-gray",children:"No projects found"}),l.jsx("p",{className:"text-bambu-gray/70 text-sm mt-1",children:"Create a project to group related prints together"})]})}):l.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:d?.map(A=>l.jsx(NGe,{project:A,onClick:()=>b(A),onEdit:()=>y(A),onDelete:()=>M(A.id)},A.id))}),c!==null&&l.jsx(Qr,{title:"Delete Project",message:"Are you sure you want to delete this project? Archives and queue items will be unlinked but not deleted.",confirmText:"Delete Project",variant:"danger",onConfirm:S,onCancel:()=>u(null)}),n&&l.jsx(CGe,{project:i,onClose:()=>{r(!1),a(void 0)},onSave:v,isLoading:g.isPending||m.isPending})]})}function PGe(){const{printerId:t}=F9(),e=parseInt(t||"0",10),[n,r]=E.useState("stream"),[i,a]=E.useState(!1),[s,o]=E.useState(!0),[c,u]=E.useState(Date.now()),[d,f]=E.useState(!1),[g,m]=E.useState(!1),x=E.useRef(null),v=E.useRef(null),{data:y}=vt({queryKey:["printer",e],queryFn:()=>ke.getPrinter(e),enabled:e>0});E.useEffect(()=>(y&&(document.title=`${y.name} - Camera`),()=>{document.title="Bambuddy"}),[y]),E.useEffect(()=>{const C=`/api/v1/printers/${e}/camera/stop`,D=()=>{e>0&&navigator.sendBeacon(C)},F=()=>{document.visibilityState==="hidden"&&e>0&&navigator.sendBeacon(C)};return window.addEventListener("beforeunload",D),document.addEventListener("visibilitychange",F),()=>{window.removeEventListener("beforeunload",D),document.removeEventListener("visibilitychange",F),x.current&&(x.current.src=""),e>0&&navigator.sendBeacon(C)}},[e]),E.useEffect(()=>{if(s&&!d){const D=setTimeout(()=>{o(!1)},n==="stream"?3e3:2e4);return()=>clearTimeout(D)}},[n,s,c,d]),E.useEffect(()=>{const C=()=>{m(!!document.fullscreenElement)};return document.addEventListener("fullscreenchange",C),()=>document.removeEventListener("fullscreenchange",C)},[]);const b=()=>{a(!0),o(!1)},M=()=>{o(!1),a(!1)},S=()=>{e>0&&fetch(`/api/v1/printers/${e}/camera/stop`).catch(()=>{})},A=C=>{n===C||d||(f(!0),o(!0),a(!1),x.current&&(x.current.src=""),n==="stream"&&S(),setTimeout(()=>{r(C),u(Date.now()),f(!1)},100))},T=()=>{d||(f(!0),o(!0),a(!1),x.current&&(x.current.src=""),n==="stream"&&S(),setTimeout(()=>{u(Date.now()),f(!1)},100))},k=()=>{v.current&&(document.fullscreenElement?document.exitFullscreen():v.current.requestFullscreen())},N=d?"":n==="stream"?`/api/v1/printers/${e}/camera/stream?fps=10&t=${c}`:`/api/v1/printers/${e}/camera/snapshot?t=${c}`,I=s||d;return e?l.jsxs("div",{ref:v,className:"min-h-screen bg-black flex flex-col",children:[l.jsxs("div",{className:"flex items-center justify-between px-4 py-2 bg-bambu-dark-secondary border-b border-bambu-dark-tertiary",children:[l.jsxs("h1",{className:"text-sm font-medium text-white flex items-center gap-2",children:[l.jsx(b0,{className:"w-4 h-4"}),y?.name||`Printer ${e}`]}),l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsxs("div",{className:"flex bg-bambu-dark rounded p-0.5",children:[l.jsx("button",{onClick:()=>A("stream"),disabled:I,className:`px-3 py-1 text-xs rounded transition-colors ${n==="stream"?"bg-bambu-green text-white":"text-bambu-gray hover:text-white disabled:opacity-50"}`,children:"Live"}),l.jsx("button",{onClick:()=>A("snapshot"),disabled:I,className:`px-3 py-1 text-xs rounded transition-colors ${n==="snapshot"?"bg-bambu-green text-white":"text-bambu-gray hover:text-white disabled:opacity-50"}`,children:"Snapshot"})]}),l.jsx("button",{onClick:T,disabled:I,className:"p-1.5 hover:bg-bambu-dark-tertiary rounded disabled:opacity-50",title:n==="stream"?"Restart stream":"Refresh snapshot",children:l.jsx(Ta,{className:`w-4 h-4 text-bambu-gray ${I?"animate-spin":""}`})}),l.jsx("button",{onClick:k,className:"p-1.5 hover:bg-bambu-dark-tertiary rounded",title:g?"Exit fullscreen":"Fullscreen",children:g?l.jsx(fce,{className:"w-4 h-4 text-bambu-gray"}):l.jsx(ace,{className:"w-4 h-4 text-bambu-gray"})})]})]}),l.jsx("div",{className:"flex-1 flex items-center justify-center p-2",children:l.jsxs("div",{className:"relative w-full h-full flex items-center justify-center",children:[(s||d)&&l.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/50 z-10",children:l.jsxs("div",{className:"text-center",children:[l.jsx(Ta,{className:"w-8 h-8 text-bambu-gray animate-spin mx-auto mb-2"}),l.jsx("p",{className:"text-sm text-bambu-gray",children:n==="stream"?"Connecting to camera...":"Capturing snapshot..."})]})}),i&&l.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black z-10",children:l.jsxs("div",{className:"text-center p-4",children:[l.jsx(ti,{className:"w-12 h-12 text-orange-400 mx-auto mb-3"}),l.jsx("p",{className:"text-white mb-2",children:"Camera unavailable"}),l.jsx("p",{className:"text-xs text-bambu-gray mb-4 max-w-md",children:"Make sure the printer is powered on and connected."}),l.jsx("button",{onClick:T,className:"px-4 py-2 bg-bambu-green text-white rounded hover:bg-bambu-green/80 transition-colors",children:"Retry"})]})}),l.jsx("img",{ref:x,src:N,alt:"Camera stream",className:"max-w-full max-h-full object-contain",onError:N?b:void 0,onLoad:N?M:void 0},c)]})})]}):l.jsx("div",{className:"min-h-screen bg-black flex items-center justify-center",children:l.jsx("p",{className:"text-white",children:"Invalid printer ID"})})}function RGe(){const{id:t}=F9(),{theme:e}=xb(),{data:n,isLoading:r,error:i}=vt({queryKey:["external-link",t],queryFn:()=>ke.getExternalLink(Number(t)),enabled:!!t});return r?l.jsx("div",{className:"flex items-center justify-center h-full",children:l.jsx(At,{className:"w-8 h-8 text-bambu-green animate-spin"})}):i||!n?l.jsxs("div",{className:"flex flex-col items-center justify-center h-full gap-4 text-bambu-gray",children:[l.jsx(ti,{className:"w-12 h-12"}),l.jsx("p",{children:"Link not found"})]}):l.jsx("iframe",{src:n.url,className:"h-full w-full border-0",style:{colorScheme:e},title:n.name,sandbox:"allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox"})}function Fr({icon:t,label:e,value:n,subValue:r,color:i="text-bambu-green"}){return l.jsxs("div",{className:"flex items-start gap-3 p-4 bg-bambu-dark rounded-lg",children:[l.jsx("div",{className:`p-2 rounded-lg bg-bambu-dark-tertiary ${i}`,children:l.jsx(t,{className:"w-5 h-5"})}),l.jsxs("div",{className:"flex-1 min-w-0",children:[l.jsx("p",{className:"text-sm text-bambu-gray",children:e}),l.jsx("p",{className:"text-lg font-semibold text-white truncate",children:n}),r&&l.jsx("p",{className:"text-xs text-bambu-gray mt-0.5",children:r})]})]})}function x9({percent:t,color:e="bg-bambu-green"}){return l.jsx("div",{className:"w-full h-2 bg-bambu-dark rounded-full overflow-hidden",children:l.jsx("div",{className:`h-full ${e} transition-all duration-300`,style:{width:`${Math.min(100,t)}%`}})})}function eh({title:t,icon:e,children:n}){return l.jsxs(Nt,{className:"p-6",children:[l.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[l.jsx(e,{className:"w-5 h-5 text-bambu-green"}),l.jsx("h2",{className:"text-lg font-semibold text-white",children:t})]}),n]})}function DGe(){const{t}=Gm(),{data:e,isLoading:n,refetch:r,isFetching:i}=vt({queryKey:["systemInfo"],queryFn:ke.getSystemInfo,refetchInterval:3e4});if(n)return l.jsx("div",{className:"flex items-center justify-center h-64",children:l.jsx(At,{className:"w-8 h-8 text-bambu-green animate-spin"})});if(!e)return l.jsx("div",{className:"p-6 text-center text-bambu-gray",children:t("system.failedToLoad","Failed to load system information")});const a=e.storage.disk_percent_used>90?"bg-red-500":e.storage.disk_percent_used>75?"bg-yellow-500":"bg-bambu-green",s=e.memory.percent_used>90?"bg-red-500":e.memory.percent_used>75?"bg-yellow-500":"bg-bambu-green";return l.jsxs("div",{className:"p-6 space-y-6",children:[l.jsxs("div",{className:"flex items-center justify-between",children:[l.jsxs("div",{children:[l.jsx("h1",{className:"text-2xl font-bold text-white",children:t("system.title","System Information")}),l.jsx("p",{className:"text-bambu-gray mt-1",children:t("system.subtitle","Monitor system resources and database statistics")})]}),l.jsxs("button",{onClick:()=>r(),disabled:i,className:"flex items-center gap-2 px-4 py-2 bg-bambu-dark-secondary hover:bg-bambu-dark-tertiary rounded-lg transition-colors disabled:opacity-50",children:[l.jsx(Ta,{className:`w-4 h-4 ${i?"animate-spin":""}`}),t("common.refresh","Refresh")]})]}),l.jsx(eh,{title:t("system.application","Application"),icon:th,children:l.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[l.jsx(Fr,{icon:th,label:t("system.version","Version"),value:`v${e.app.version}`}),l.jsx(Fr,{icon:_r,label:t("system.uptime","System Uptime"),value:e.system.uptime_formatted}),l.jsx(Fr,{icon:th,label:t("system.hostname","Hostname"),value:e.system.hostname})]})}),l.jsxs(eh,{title:t("system.database","Database"),icon:pm,children:[l.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4 mb-4",children:[l.jsx(Fr,{icon:_h,label:t("system.totalArchives","Total Archives"),value:e.database.archives}),l.jsx(Fr,{icon:Moe,label:t("system.completed","Completed"),value:e.database.archives_completed,color:"text-green-500"}),l.jsx(Fr,{icon:gs,label:t("system.failed","Failed"),value:e.database.archives_failed,color:"text-red-500"}),l.jsx(Fr,{icon:At,label:t("system.printing","Printing"),value:e.database.archives_printing,color:"text-yellow-500"})]}),l.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[l.jsx(Fr,{icon:Ts,label:t("system.printers","Printers"),value:e.database.printers}),l.jsx(Fr,{icon:dG,label:t("system.filaments","Filaments"),value:e.database.filaments}),l.jsx(Fr,{icon:qu,label:t("system.projects","Projects"),value:e.database.projects}),l.jsx(Fr,{icon:Jp,label:t("system.smartPlugs","Smart Plugs"),value:e.database.smart_plugs})]}),l.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4 mt-4",children:[l.jsx(Fr,{icon:_r,label:t("system.totalPrintTime","Total Print Time"),value:e.database.total_print_time_formatted}),l.jsx(Fr,{icon:_h,label:t("system.totalFilament","Total Filament Used"),value:`${e.database.total_filament_kg} kg`,subValue:`${e.database.total_filament_grams.toLocaleString()} g`})]})]}),l.jsxs(eh,{title:t("system.connectedPrinters","Connected Printers"),icon:Ts,children:[l.jsxs("div",{className:"flex items-center gap-4 mb-4",children:[l.jsx("div",{className:"text-3xl font-bold text-bambu-green",children:e.printers.connected}),l.jsx("div",{className:"text-bambu-gray",children:t("system.ofTotal","of {{total}} printers connected",{total:e.printers.total})})]}),e.printers.connected_list.length>0?l.jsx("div",{className:"space-y-2",children:e.printers.connected_list.map(o=>l.jsxs("div",{className:"flex items-center justify-between p-3 bg-bambu-dark rounded-lg",children:[l.jsxs("div",{className:"flex items-center gap-3",children:[l.jsx("div",{className:"w-2 h-2 rounded-full bg-bambu-green"}),l.jsx("span",{className:"font-medium text-white",children:o.name})]}),l.jsxs("div",{className:"flex items-center gap-4 text-sm text-bambu-gray",children:[l.jsx("span",{children:o.model}),l.jsx("span",{className:`px-2 py-0.5 rounded ${o.state==="RUNNING"?"bg-bambu-green/20 text-bambu-green":o.state==="IDLE"?"bg-blue-500/20 text-blue-400":"bg-bambu-dark-tertiary"}`,children:o.state})]})]},o.id))}):l.jsx("p",{className:"text-bambu-gray",children:t("system.noPrintersConnected","No printers connected")})]}),l.jsx(eh,{title:t("system.storage","Storage"),icon:BR,children:l.jsxs("div",{className:"space-y-4",children:[l.jsxs("div",{children:[l.jsxs("div",{className:"flex justify-between text-sm mb-1",children:[l.jsx("span",{className:"text-bambu-gray",children:t("system.diskUsage","Disk Usage")}),l.jsxs("span",{className:"text-white",children:[e.storage.disk_used_formatted," / ",e.storage.disk_total_formatted]})]}),l.jsx(x9,{percent:e.storage.disk_percent_used,color:a}),l.jsxs("p",{className:"text-xs text-bambu-gray mt-1",children:[e.storage.disk_free_formatted," ",t("system.free","free")," (",(100-e.storage.disk_percent_used).toFixed(1),"%)"]})]}),l.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[l.jsx(Fr,{icon:_h,label:t("system.archiveStorage","Archive Storage"),value:e.storage.archive_size_formatted}),l.jsx(Fr,{icon:pm,label:t("system.databaseSize","Database Size"),value:e.storage.database_size_formatted})]})]})}),l.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[l.jsx(eh,{title:t("system.memory","Memory"),icon:oce,children:l.jsx("div",{className:"space-y-4",children:l.jsxs("div",{children:[l.jsxs("div",{className:"flex justify-between text-sm mb-1",children:[l.jsx("span",{className:"text-bambu-gray",children:t("system.memoryUsage","Memory Usage")}),l.jsxs("span",{className:"text-white",children:[e.memory.used_formatted," / ",e.memory.total_formatted]})]}),l.jsx(x9,{percent:e.memory.percent_used,color:s}),l.jsxs("p",{className:"text-xs text-bambu-gray mt-1",children:[e.memory.available_formatted," ",t("system.available","available")]})]})})}),l.jsx(eh,{title:t("system.cpu","CPU"),icon:gv,children:l.jsx("div",{className:"space-y-4",children:l.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[l.jsx(Fr,{icon:gv,label:t("system.cores","Cores"),value:e.cpu.count,subValue:`${e.cpu.count_logical} logical`}),l.jsx(Fr,{icon:gv,label:t("system.usage","Usage"),value:`${e.cpu.percent}%`})]})})})]}),l.jsx(eh,{title:t("system.systemDetails","System Details"),icon:th,children:l.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[l.jsx(Fr,{icon:th,label:t("system.os","Operating System"),value:e.system.platform,subValue:e.system.platform_release}),l.jsx(Fr,{icon:gv,label:t("system.architecture","Architecture"),value:e.system.architecture}),l.jsx(Fr,{icon:th,label:t("system.python","Python"),value:e.system.python_version}),l.jsx(Fr,{icon:_r,label:t("system.bootTime","Boot Time"),value:new Date(e.system.boot_time).toLocaleString()})]})})]})}function jGe(){const t=E.useRef(null),e=E.useRef(null),n=En(),[r,i]=E.useState(!1),a=E.useRef(new Set),s=E.useRef(null),o=E.useCallback(()=>{if(t.current?.readyState===WebSocket.OPEN)return;const g=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/api/v1/ws`,m=new WebSocket(g);let x=null;m.onopen=()=>{console.log("[WebSocket] Connected"),i(!0),x=window.setInterval(()=>{m.readyState===WebSocket.OPEN&&m.send(JSON.stringify({type:"ping"}))},3e4)},m.onmessage=v=>{try{const y=JSON.parse(v.data);u(y)}catch{}},m.onclose=v=>{console.log("[WebSocket] Closed",v.code,v.reason),x&&(clearInterval(x),x=null),i(!1),t.current=null,e.current=window.setTimeout(()=>{o()},3e3)},m.onerror=v=>{console.error("[WebSocket] Error",v),m.close()},t.current=m},[]),c=E.useCallback(f=>{a.current.add(f),s.current&&clearTimeout(s.current),s.current=window.setTimeout(()=>{const g=Array.from(a.current);a.current.clear(),s.current=null,requestAnimationFrame(()=>{g.forEach(m=>{n.invalidateQueries({queryKey:[m]})})})},100)},[n]),u=E.useCallback(f=>{switch(f.type){case"printer_status":f.printer_id!==void 0&&n.setQueryData(["printerStatus",f.printer_id],g=>{const m={...g,...f.data};return m.wifi_signal==null&&g?.wifi_signal!=null&&(m.wifi_signal=g.wifi_signal),m});break;case"print_complete":c("archives"),c("archiveStats");break;case"archive_created":c("archives"),c("archiveStats");break;case"archive_updated":c("archives");break}},[n,c]);E.useEffect(()=>(o(),()=>{e.current&&clearTimeout(e.current),s.current&&clearTimeout(s.current),t.current&&t.current.close()}),[o]);const d=E.useCallback(f=>{t.current?.readyState===WebSocket.OPEN&&t.current.send(JSON.stringify(f))},[]);return{isConnected:r,sendMessage:d}}const OGe=new Nse({defaultOptions:{queries:{staleTime:1e3*60,retry:1}}});function LGe({children:t}){return jGe(),l.jsx(l.Fragment,{children:t})}function IGe(){return l.jsx($ue,{children:l.jsx(Jue,{children:l.jsx(kse,{client:OGe,children:l.jsx(LGe,{children:l.jsx(Zae,{children:l.jsxs(Cae,{children:[l.jsx(fs,{path:"/camera/:printerId",element:l.jsx(PGe,{})}),l.jsxs(fs,{path:"/",element:l.jsx(Yue,{}),children:[l.jsx(fs,{index:!0,element:l.jsx(wCe,{})}),l.jsx(fs,{path:"archives",element:l.jsx(XVe,{})}),l.jsx(fs,{path:"queue",element:l.jsx(j9e,{})}),l.jsx(fs,{path:"stats",element:l.jsx(K9e,{})}),l.jsx(fs,{path:"profiles",element:l.jsx(SGe,{})}),l.jsx(fs,{path:"maintenance",element:l.jsx(TGe,{})}),l.jsx(fs,{path:"projects",element:l.jsx(kGe,{})}),l.jsx(fs,{path:"settings",element:l.jsx(hGe,{})}),l.jsx(fs,{path:"system",element:l.jsx(DGe,{})}),l.jsx(fs,{path:"external/:id",element:l.jsx(RGe,{})})]})]})})})})})})}Rre.createRoot(document.getElementById("root")).render(l.jsx(E.StrictMode,{children:l.jsx(IGe,{})})); diff --git a/static/index.html b/static/index.html index b4e0c922e..49f6a3be7 100644 --- a/static/index.html +++ b/static/index.html @@ -23,7 +23,7 @@ - +