1||c==0||v.content.size)&&(h=g,u.push(ire(v.mark(f.allowedMarks(v.marks)),d==1?c:0,d==l.childCount?p:-1)))}let x=d==l.childCount;x||(p=-1),this.placed=Ry(this.placed,n,Mt.from(u)),this.frontier[n].match=h,x&&p<0&&r&&r.type==this.frontier[this.depth].type&&this.frontier.length>1&&this.closeFrontierNode();for(let v=0,g=l;v1&&i==this.$to.end(--r);)++i;return i}findCloseLevel(e){e:for(let n=Math.min(this.depth,e.depth);n>=0;n--){let{match:r,type:i}=this.frontier[n],s=n=0;l--){let{match:c,type:d}=this.frontier[l],u=ej(e,l,d,c,!0);if(!u||u.childCount)continue e}return{depth:n,fit:o,move:s?e.doc.resolve(e.after(n+1)):e}}}}close(e){let n=this.findCloseLevel(e);if(!n)return null;for(;this.depth>n.depth;)this.closeFrontierNode();n.fit.childCount&&(this.placed=Ry(this.placed,n.depth,n.fit)),e=n.move;for(let r=n.depth+1;r<=e.depth;r++){let i=e.node(r),s=i.type.contentMatch.fillBefore(i.content,!0,e.index(r));this.openFrontierNode(i.type,i.attrs,s)}return e}openFrontierNode(e,n=null,r){let i=this.frontier[this.depth];i.match=i.match.matchType(e),this.placed=Ry(this.placed,this.depth,Mt.from(e.create(n,r))),this.frontier.push({type:e,match:e.contentMatch})}closeFrontierNode(){let n=this.frontier.pop().match.fillBefore(Mt.empty,!0);n.childCount&&(this.placed=Ry(this.placed,this.frontier.length,n))}}function Dy(t,e,n){return e==0?t.cutByIndex(n,t.childCount):t.replaceChild(0,t.firstChild.copy(Dy(t.firstChild.content,e-1,n)))}function Ry(t,e,n){return e==0?t.append(n):t.replaceChild(t.childCount-1,t.lastChild.copy(Ry(t.lastChild.content,e-1,n)))}function JE(t,e){for(let n=0;n1&&(r=r.replaceChild(0,ire(r.firstChild,e-1,r.childCount==1?n-1:0))),e>0&&(r=t.type.contentMatch.fillBefore(r).append(r),n<=0&&(r=r.append(t.type.contentMatch.matchFragment(r).fillBefore(Mt.empty,!0)))),t.copy(r)}function ej(t,e,n,r,i){let s=t.node(e),o=i?t.indexAfter(e):t.index(e);if(o==s.childCount&&!n.compatibleContent(s.type))return null;let l=r.fillBefore(s.content,!0,o);return l&&!VVe(n,s.content,o)?l:null}function VVe(t,e,n){for(let r=n;r0;f--,p--){let x=i.node(f).type.spec;if(x.defining||x.definingAsContext||x.isolating)break;o.indexOf(f)>-1?l=f:i.before(f)==p&&o.splice(1,0,-f)}let c=o.indexOf(l),d=[],u=r.openStart;for(let f=r.content,p=0;;p++){let x=f.firstChild;if(d.push(x),p==r.openStart)break;f=x.content}for(let f=u-1;f>=0;f--){let p=d[f],x=qVe(p.type);if(x&&!p.sameMarkup(i.node(Math.abs(l)-1)))u=f;else if(x||!p.type.isTextblock)break}for(let f=r.openStart;f>=0;f--){let p=(f+u+1)%(r.openStart+1),x=d[p];if(x)for(let v=0;v=0&&(t.replace(e,n,r),!(t.steps.length>h));f--){let p=o[f];p<0||(e=i.before(p),n=s.after(p))}}function sre(t,e,n,r,i){if(er){let s=i.contentMatchAt(0),o=s.fillBefore(t).append(t);t=o.append(s.matchFragment(o).fillBefore(Mt.empty,!0))}return t}function WVe(t,e,n,r){if(!r.isInline&&e==n&&t.doc.resolve(e).parent.content.size){let i=HVe(t.doc,e,r.type);i!=null&&(e=n=i)}t.replaceRange(e,n,new qt(Mt.from(r),0,0))}function KVe(t,e,n){let r=t.doc.resolve(e),i=t.doc.resolve(n),s=ore(r,i);for(let o=0;o0&&(c||r.node(l-1).canReplace(r.index(l-1),i.indexAfter(l-1))))return t.delete(r.before(l),i.after(l))}for(let o=1;o<=r.depth&&o<=i.depth;o++)if(e-r.start(o)==r.depth-o&&n>r.end(o)&&i.end(o)-n!=i.depth-o&&r.start(o-1)==i.start(o-1)&&r.node(o-1).canReplace(r.index(o-1),i.index(o-1)))return t.delete(r.before(o),n);t.delete(e,n)}function ore(t,e){let n=[],r=Math.min(t.depth,e.depth);for(let i=r;i>=0;i--){let s=t.start(i);if(se.pos+(e.depth-i)||t.node(i).type.spec.isolating||e.node(i).type.spec.isolating)break;(s==e.start(i)||i==t.depth&&i==e.depth&&t.parent.inlineContent&&e.parent.inlineContent&&i&&e.start(i-1)==s-1)&&n.push(i)}return n}class ib extends _s{constructor(e,n,r){super(),this.pos=e,this.attr=n,this.value=r}apply(e){let n=e.nodeAt(this.pos);if(!n)return ni.fail("No node at attribute step's position");let r=Object.create(null);for(let s in n.attrs)r[s]=n.attrs[s];r[this.attr]=this.value;let i=n.type.create(r,null,n.marks);return ni.fromReplace(e,this.pos,this.pos+1,new qt(Mt.from(i),0,n.isLeaf?0:1))}getMap(){return Mo.empty}invert(e){return new ib(this.pos,this.attr,e.nodeAt(this.pos).attrs[this.attr])}map(e){let n=e.mapResult(this.pos,1);return n.deletedAfter?null:new ib(n.pos,this.attr,this.value)}toJSON(){return{stepType:"attr",pos:this.pos,attr:this.attr,value:this.value}}static fromJSON(e,n){if(typeof n.pos!="number"||typeof n.attr!="string")throw new RangeError("Invalid input for AttrStep.fromJSON");return new ib(n.pos,n.attr,n.value)}}_s.jsonID("attr",ib);class W0 extends _s{constructor(e,n){super(),this.attr=e,this.value=n}apply(e){let n=Object.create(null);for(let i in e.attrs)n[i]=e.attrs[i];n[this.attr]=this.value;let r=e.type.create(n,e.content,e.marks);return ni.ok(r)}getMap(){return Mo.empty}invert(e){return new W0(this.attr,e.attrs[this.attr])}map(e){return this}toJSON(){return{stepType:"docAttr",attr:this.attr,value:this.value}}static fromJSON(e,n){if(typeof n.attr!="string")throw new RangeError("Invalid input for DocAttrStep.fromJSON");return new W0(n.attr,n.value)}}_s.jsonID("docAttr",W0);let Pb=class extends Error{};Pb=function t(e){let n=Error.call(this,e);return n.__proto__=t.prototype,n};Pb.prototype=Object.create(Error.prototype);Pb.prototype.constructor=Pb;Pb.prototype.name="TransformError";class lre{constructor(e){this.doc=e,this.steps=[],this.docs=[],this.mapping=new G0}get before(){return this.docs.length?this.docs[0]:this.doc}step(e){let n=this.maybeStep(e);if(n.failed)throw new Pb(n.failed);return this}maybeStep(e){let n=e.apply(this.doc);return n.failed||this.addStep(e,n.doc),n}get docChanged(){return this.steps.length>0}changedRange(){let e=1e9,n=-1e9;for(let r=0;r{e=Math.min(e,l),n=Math.max(n,c)})}return e==1e9?null:{from:e,to:n}}addStep(e,n){this.docs.push(this.doc),this.steps.push(e),this.mapping.appendMap(e.getMap()),this.doc=n}replace(e,n=e,r=qt.empty){let i=dA(this.doc,e,n,r);return i&&this.step(i),this}replaceWith(e,n,r){return this.replace(e,n,new qt(Mt.from(r),0,0))}delete(e,n){return this.replace(e,n,qt.empty)}insert(e,n){return this.replaceWith(e,e,n)}replaceRange(e,n,r){return GVe(this,e,n,r),this}replaceRangeWith(e,n,r){return WVe(this,e,n,r),this}deleteRange(e,n){return KVe(this,e,n),this}lift(e,n){return jVe(this,e,n),this}join(e,n=1){return BVe(this,e,n),this}wrap(e,n){return FVe(this,e,n),this}setBlockType(e,n=e,r,i=null){return LVe(this,e,n,r,i),this}setNodeMarkup(e,n,r=null,i){return IVe(this,e,n,r,i),this}setNodeAttribute(e,n,r){return this.step(new ib(e,n,r)),this}setDocAttribute(e,n){return this.step(new W0(e,n)),this}addNodeMark(e,n){return this.step(new kh(e,n)),this}removeNodeMark(e,n){let r=this.doc.nodeAt(e);if(!r)throw new RangeError("No node at position "+e);if(n instanceof Kr)n.isInSet(r.marks)&&this.step(new Xf(e,n));else{let i=r.marks,s,o=[];for(;s=n.isInSet(i);)o.push(new Xf(e,s)),i=s.removeFromSet(i);for(let l=o.length-1;l>=0;l--)this.step(o[l])}return this}split(e,n=1,r){return zVe(this,e,n,r),this}addMark(e,n,r){return MVe(this,e,n,r),this}removeMark(e,n,r){return PVe(this,e,n,r),this}clearIncompatible(e,n,r){return vO(this,e,n,r),this}}const tj=Object.create(null);class zn{constructor(e,n,r){this.$anchor=e,this.$head=n,this.ranges=r||[new XVe(e.min(n),e.max(n))]}get anchor(){return this.$anchor.pos}get head(){return this.$head.pos}get from(){return this.$from.pos}get to(){return this.$to.pos}get $from(){return this.ranges[0].$from}get $to(){return this.ranges[0].$to}get empty(){let e=this.ranges;for(let n=0;n=0;s--){let o=n<0?Rg(e.node(0),e.node(s),e.before(s+1),e.index(s),n,r):Rg(e.node(0),e.node(s),e.after(s+1),e.index(s)+1,n,r);if(o)return o}return null}static near(e,n=1){return this.findFrom(e,n)||this.findFrom(e,-n)||new Fo(e.node(0))}static atStart(e){return Rg(e,e,0,0,1)||new Fo(e)}static atEnd(e){return Rg(e,e,e.content.size,e.childCount,-1)||new Fo(e)}static fromJSON(e,n){if(!n||!n.type)throw new RangeError("Invalid input for Selection.fromJSON");let r=tj[n.type];if(!r)throw new RangeError(`No selection type ${n.type} defined`);return r.fromJSON(e,n)}static jsonID(e,n){if(e in tj)throw new RangeError("Duplicate use of selection JSON ID "+e);return tj[e]=n,n.prototype.jsonID=e,n}getBookmark(){return _n.between(this.$anchor,this.$head).getBookmark()}}zn.prototype.visible=!0;class XVe{constructor(e,n){this.$from=e,this.$to=n}}let T9=!1;function M9(t){!T9&&!t.parent.inlineContent&&(T9=!0,console.warn("TextSelection endpoint not pointing into a node with inline content ("+t.parent.type.name+")"))}class _n extends zn{constructor(e,n=e){M9(e),M9(n),super(e,n)}get $cursor(){return this.$anchor.pos==this.$head.pos?this.$head:null}map(e,n){let r=e.resolve(n.map(this.head));if(!r.parent.inlineContent)return zn.near(r);let i=e.resolve(n.map(this.anchor));return new _n(i.parent.inlineContent?i:r,r)}replace(e,n=qt.empty){if(super.replace(e,n),n==qt.empty){let r=this.$from.marksAcross(this.$to);r&&e.ensureMarks(r)}}eq(e){return e instanceof _n&&e.anchor==this.anchor&&e.head==this.head}getBookmark(){return new uA(this.anchor,this.head)}toJSON(){return{type:"text",anchor:this.anchor,head:this.head}}static fromJSON(e,n){if(typeof n.anchor!="number"||typeof n.head!="number")throw new RangeError("Invalid input for TextSelection.fromJSON");return new _n(e.resolve(n.anchor),e.resolve(n.head))}static create(e,n,r=n){let i=e.resolve(n);return new this(i,r==n?i:e.resolve(r))}static between(e,n,r){let i=e.pos-n.pos;if((!r||i)&&(r=i>=0?1:-1),!n.parent.inlineContent){let s=zn.findFrom(n,r,!0)||zn.findFrom(n,-r,!0);if(s)n=s.$head;else return zn.near(n,r)}return e.parent.inlineContent||(i==0?e=n:(e=(zn.findFrom(e,-r,!0)||zn.findFrom(e,r,!0)).$anchor,e.pos0?0:1);i>0?o=0;o+=i){let l=e.child(o);if(l.isAtom){if(!s&&cn.isSelectable(l))return cn.create(t,n-(i<0?l.nodeSize:0))}else{let c=Rg(t,l,n+i,i<0?l.childCount:0,i,s);if(c)return c}n+=l.nodeSize*i}return null}function P9(t,e,n){let r=t.steps.length-1;if(r{o==null&&(o=u)}),t.setSelection(zn.near(t.doc.resolve(o),n))}const E9=1,__=2,j9=4;class QVe extends lre{constructor(e){super(e.doc),this.curSelectionFor=0,this.updated=0,this.meta=Object.create(null),this.time=Date.now(),this.curSelection=e.selection,this.storedMarks=e.storedMarks}get selection(){return this.curSelectionFor0}setStoredMarks(e){return this.storedMarks=e,this.updated|=__,this}ensureMarks(e){return Kr.sameSet(this.storedMarks||this.selection.$from.marks(),e)||this.setStoredMarks(e),this}addStoredMark(e){return this.ensureMarks(e.addToSet(this.storedMarks||this.selection.$head.marks()))}removeStoredMark(e){return this.ensureMarks(e.removeFromSet(this.storedMarks||this.selection.$head.marks()))}get storedMarksSet(){return(this.updated&__)>0}addStep(e,n){super.addStep(e,n),this.updated=this.updated&~__,this.storedMarks=null}setTime(e){return this.time=e,this}replaceSelection(e){return this.selection.replace(this,e),this}replaceSelectionWith(e,n=!0){let r=this.selection;return n&&(e=e.mark(this.storedMarks||(r.empty?r.$from.marks():r.$from.marksAcross(r.$to)||Kr.none))),r.replaceWith(this,e),this}deleteSelection(){return this.selection.replace(this),this}insertText(e,n,r){let i=this.doc.type.schema;if(n==null)return e?this.replaceSelectionWith(i.text(e),!0):this.deleteSelection();{if(r==null&&(r=n),!e)return this.deleteRange(n,r);let s=this.storedMarks;if(!s){let o=this.doc.resolve(n);s=r==n?o.marks():o.marksAcross(this.doc.resolve(r))}return this.replaceRangeWith(n,r,i.text(e,s)),!this.selection.empty&&this.selection.to==n+e.length&&this.setSelection(zn.near(this.selection.$to)),this}}setMeta(e,n){return this.meta[typeof e=="string"?e:e.key]=n,this}getMeta(e){return this.meta[typeof e=="string"?e:e.key]}get isGeneric(){for(let e in this.meta)return!1;return!0}scrollIntoView(){return this.updated|=j9,this}get scrolledIntoView(){return(this.updated&j9)>0}}function D9(t,e){return!e||!t?t:t.bind(e)}class Fy{constructor(e,n,r){this.name=e,this.init=D9(n.init,r),this.apply=D9(n.apply,r)}}const ZVe=[new Fy("doc",{init(t){return t.doc||t.schema.topNodeType.createAndFill()},apply(t){return t.doc}}),new Fy("selection",{init(t,e){return t.selection||zn.atStart(e.doc)},apply(t){return t.selection}}),new Fy("storedMarks",{init(t){return t.storedMarks||null},apply(t,e,n,r){return r.selection.$cursor?t.storedMarks:null}}),new Fy("scrollToSelection",{init(){return 0},apply(t,e){return t.scrolledIntoView?e+1:e}})];class nj{constructor(e,n){this.schema=e,this.plugins=[],this.pluginsByKey=Object.create(null),this.fields=ZVe.slice(),n&&n.forEach(r=>{if(this.pluginsByKey[r.key])throw new RangeError("Adding different instances of a keyed plugin ("+r.key+")");this.plugins.push(r),this.pluginsByKey[r.key]=r,r.spec.state&&this.fields.push(new Fy(r.key,r.spec.state,r))})}}class Vg{constructor(e){this.config=e}get schema(){return this.config.schema}get plugins(){return this.config.plugins}apply(e){return this.applyTransaction(e).state}filterTransaction(e,n=-1){for(let r=0;rr.toJSON())),e&&typeof e=="object")for(let r in e){if(r=="doc"||r=="selection")throw new RangeError("The JSON fields `doc` and `selection` are reserved");let i=e[r],s=i.spec.state;s&&s.toJSON&&(n[r]=s.toJSON.call(i,this[i.key]))}return n}static fromJSON(e,n,r){if(!n)throw new RangeError("Invalid input for EditorState.fromJSON");if(!e.schema)throw new RangeError("Required config field 'schema' missing");let i=new nj(e.schema,e.plugins),s=new Vg(i);return i.fields.forEach(o=>{if(o.name=="doc")s.doc=Bh.fromJSON(e.schema,n.doc);else if(o.name=="selection")s.selection=zn.fromJSON(s.doc,n.selection);else if(o.name=="storedMarks")n.storedMarks&&(s.storedMarks=n.storedMarks.map(e.schema.markFromJSON));else{if(r)for(let l in r){let c=r[l],d=c.spec.state;if(c.key==o.name&&d&&d.fromJSON&&Object.prototype.hasOwnProperty.call(n,l)){s[o.name]=d.fromJSON.call(c,e,n[l],s);return}}s[o.name]=o.init(e,s)}}),s}}function cre(t,e,n){for(let r in t){let i=t[r];i instanceof Function?i=i.bind(e):r=="handleDOMEvents"&&(i=cre(i,e,{})),n[r]=i}return n}class Na{constructor(e){this.spec=e,this.props={},e.props&&cre(e.props,this,this.props),this.key=e.key?e.key.key:dre("plugin")}getState(e){return e[this.key]}}const rj=Object.create(null);function dre(t){return t in rj?t+"$"+ ++rj[t]:(rj[t]=0,t+"$")}class Ni{constructor(e="key"){this.key=dre(e)}get(e){return e.config.pluginsByKey[this.key]}getState(e){return e[this.key]}}const _O=(t,e)=>t.selection.empty?!1:(e&&e(t.tr.deleteSelection().scrollIntoView()),!0);function ure(t,e){let{$cursor:n}=t.selection;return!n||(e?!e.endOfTextblock("backward",t):n.parentOffset>0)?null:n}const hre=(t,e,n)=>{let r=ure(t,n);if(!r)return!1;let i=NO(r);if(!i){let o=r.blockRange(),l=o&&lx(o);return l==null?!1:(e&&e(t.tr.lift(o,l).scrollIntoView()),!0)}let s=i.nodeBefore;if(wre(t,i,e,-1))return!0;if(r.parent.content.size==0&&(Eb(s,"end")||cn.isSelectable(s)))for(let o=r.depth;;o--){let l=dA(t.doc,r.before(o),r.after(o),qt.empty);if(l&&l.slice.size1)break}return s.isAtom&&i.depth==r.depth-1?(e&&e(t.tr.delete(i.pos-s.nodeSize,i.pos).scrollIntoView()),!0):!1},JVe=(t,e,n)=>{let r=ure(t,n);if(!r)return!1;let i=NO(r);return i?mre(t,i,e):!1},eqe=(t,e,n)=>{let r=pre(t,n);if(!r)return!1;let i=CO(r);return i?mre(t,i,e):!1};function mre(t,e,n){let r=e.nodeBefore,i=r,s=e.pos-1;for(;!i.isTextblock;s--){if(i.type.spec.isolating)return!1;let u=i.lastChild;if(!u)return!1;i=u}let o=e.nodeAfter,l=o,c=e.pos+1;for(;!l.isTextblock;c++){if(l.type.spec.isolating)return!1;let u=l.firstChild;if(!u)return!1;l=u}let d=dA(t.doc,s,c,qt.empty);if(!d||d.from!=s||d instanceof Di&&d.slice.size>=c-s)return!1;if(n){let u=t.tr.step(d);u.setSelection(_n.create(u.doc,s)),n(u.scrollIntoView())}return!0}function Eb(t,e,n=!1){for(let r=t;r;r=e=="start"?r.firstChild:r.lastChild){if(r.isTextblock)return!0;if(n&&r.childCount!=1)return!1}return!1}const fre=(t,e,n)=>{let{$head:r,empty:i}=t.selection,s=r;if(!i)return!1;if(r.parent.isTextblock){if(n?!n.endOfTextblock("backward",t):r.parentOffset>0)return!1;s=NO(r)}let o=s&&s.nodeBefore;return!o||!cn.isSelectable(o)?!1:(e&&e(t.tr.setSelection(cn.create(t.doc,s.pos-o.nodeSize)).scrollIntoView()),!0)};function NO(t){if(!t.parent.type.spec.isolating)for(let e=t.depth-1;e>=0;e--){if(t.index(e)>0)return t.doc.resolve(t.before(e+1));if(t.node(e).type.spec.isolating)break}return null}function pre(t,e){let{$cursor:n}=t.selection;return!n||(e?!e.endOfTextblock("forward",t):n.parentOffset{let r=pre(t,n);if(!r)return!1;let i=CO(r);if(!i)return!1;let s=i.nodeAfter;if(wre(t,i,e,1))return!0;if(r.parent.content.size==0&&(Eb(s,"start")||cn.isSelectable(s))){let o=dA(t.doc,r.before(),r.after(),qt.empty);if(o&&o.slice.size{let{$head:r,empty:i}=t.selection,s=r;if(!i)return!1;if(r.parent.isTextblock){if(n?!n.endOfTextblock("forward",t):r.parentOffset=0;e--){let n=t.node(e);if(t.index(e)+1{let n=t.selection,r=n instanceof cn,i;if(r){if(n.node.isTextblock||!lm(t.doc,n.from))return!1;i=n.from}else if(i=cA(t.doc,n.from,-1),i==null)return!1;if(e){let s=t.tr.join(i);r&&s.setSelection(cn.create(s.doc,i-t.doc.resolve(i).nodeBefore.nodeSize)),e(s.scrollIntoView())}return!0},nqe=(t,e)=>{let n=t.selection,r;if(n instanceof cn){if(n.node.isTextblock||!lm(t.doc,n.to))return!1;r=n.to}else if(r=cA(t.doc,n.to,1),r==null)return!1;return e&&e(t.tr.join(r).scrollIntoView()),!0},rqe=(t,e)=>{let{$from:n,$to:r}=t.selection,i=n.blockRange(r),s=i&&lx(i);return s==null?!1:(e&&e(t.tr.lift(i,s).scrollIntoView()),!0)},xre=(t,e)=>{let{$head:n,$anchor:r}=t.selection;return!n.parent.type.spec.code||!n.sameParent(r)?!1:(e&&e(t.tr.insertText(`
`).scrollIntoView()),!0)};function kO(t){for(let e=0;e{let{$head:n,$anchor:r}=t.selection;if(!n.parent.type.spec.code||!n.sameParent(r))return!1;let i=n.node(-1),s=n.indexAfter(-1),o=kO(i.contentMatchAt(s));if(!o||!i.canReplaceWith(s,s,o))return!1;if(e){let l=n.after(),c=t.tr.replaceWith(l,l,o.createAndFill());c.setSelection(zn.near(c.doc.resolve(l),1)),e(c.scrollIntoView())}return!0},yre=(t,e)=>{let n=t.selection,{$from:r,$to:i}=n;if(n instanceof Fo||r.parent.inlineContent||i.parent.inlineContent)return!1;let s=kO(i.parent.contentMatchAt(i.indexAfter()));if(!s||!s.isTextblock)return!1;if(e){let o=(!r.parentOffset&&i.index(){let{$cursor:n}=t.selection;if(!n||n.parent.content.size)return!1;if(n.depth>1&&n.after()!=n.end(-1)){let s=n.before();if(Qd(t.doc,s))return e&&e(t.tr.split(s).scrollIntoView()),!0}let r=n.blockRange(),i=r&&lx(r);return i==null?!1:(e&&e(t.tr.lift(r,i).scrollIntoView()),!0)};function iqe(t){return(e,n)=>{let{$from:r,$to:i}=e.selection;if(e.selection instanceof cn&&e.selection.node.isBlock)return!r.parentOffset||!Qd(e.doc,r.pos)?!1:(n&&n(e.tr.split(r.pos).scrollIntoView()),!0);if(!r.depth)return!1;let s=[],o,l,c=!1,d=!1;for(let p=r.depth;;p--)if(r.node(p).isBlock){c=r.end(p)==r.pos+(r.depth-p),d=r.start(p)==r.pos-(r.depth-p),l=kO(r.node(p-1).contentMatchAt(r.indexAfter(p-1))),s.unshift(c&&l?{type:l}:null),o=p;break}else{if(p==1)return!1;s.unshift(null)}let u=e.tr;(e.selection instanceof _n||e.selection instanceof Fo)&&u.deleteSelection();let h=u.mapping.map(r.pos),f=Qd(u.doc,h,s.length,s);if(f||(s[0]=l?{type:l}:null,f=Qd(u.doc,h,s.length,s)),!f)return!1;if(u.split(h,s.length,s),!c&&d&&r.node(o).type!=l){let p=u.mapping.map(r.before(o)),x=u.doc.resolve(p);l&&r.node(o-1).canReplaceWith(x.index(),x.index()+1,l)&&u.setNodeMarkup(u.mapping.map(r.before(o)),l)}return n&&n(u.scrollIntoView()),!0}}const sqe=iqe(),oqe=(t,e)=>{let{$from:n,to:r}=t.selection,i,s=n.sharedDepth(r);return s==0?!1:(i=n.before(s),e&&e(t.tr.setSelection(cn.create(t.doc,i))),!0)};function lqe(t,e,n){let r=e.nodeBefore,i=e.nodeAfter,s=e.index();return!r||!i||!r.type.compatibleContent(i.type)?!1:!r.content.size&&e.parent.canReplace(s-1,s)?(n&&n(t.tr.delete(e.pos-r.nodeSize,e.pos).scrollIntoView()),!0):!e.parent.canReplace(s,s+1)||!(i.isTextblock||lm(t.doc,e.pos))?!1:(n&&n(t.tr.join(e.pos).scrollIntoView()),!0)}function wre(t,e,n,r){let i=e.nodeBefore,s=e.nodeAfter,o,l,c=i.type.spec.isolating||s.type.spec.isolating;if(!c&&lqe(t,e,n))return!0;let d=!c&&e.parent.canReplace(e.index(),e.index()+1);if(d&&(o=(l=i.contentMatchAt(i.childCount)).findWrapping(s.type))&&l.matchType(o[0]||s.type).validEnd){if(n){let p=e.pos+s.nodeSize,x=Mt.empty;for(let y=o.length-1;y>=0;y--)x=Mt.from(o[y].create(null,x));x=Mt.from(i.copy(x));let v=t.tr.step(new Fi(e.pos-1,p,e.pos,p,new qt(x,1,0),o.length,!0)),g=v.doc.resolve(p+2*o.length);g.nodeAfter&&g.nodeAfter.type==i.type&&lm(v.doc,g.pos)&&v.join(g.pos),n(v.scrollIntoView())}return!0}let u=s.type.spec.isolating||r>0&&c?null:zn.findFrom(e,1),h=u&&u.$from.blockRange(u.$to),f=h&&lx(h);if(f!=null&&f>=e.depth)return n&&n(t.tr.lift(h,f).scrollIntoView()),!0;if(d&&Eb(s,"start",!0)&&Eb(i,"end")){let p=i,x=[];for(;x.push(p),!p.isTextblock;)p=p.lastChild;let v=s,g=1;for(;!v.isTextblock;v=v.firstChild)g++;if(p.canReplace(p.childCount,p.childCount,v.content)){if(n){let y=Mt.empty;for(let N=x.length-1;N>=0;N--)y=Mt.from(x[N].copy(y));let _=t.tr.step(new Fi(e.pos-x.length,e.pos+s.nodeSize,e.pos+g,e.pos+s.nodeSize-g,new qt(y,x.length,0),0,!0));n(_.scrollIntoView())}return!0}}return!1}function Sre(t){return function(e,n){let r=e.selection,i=t<0?r.$from:r.$to,s=i.depth;for(;i.node(s).isInline;){if(!s)return!1;s--}return i.node(s).isTextblock?(n&&n(e.tr.setSelection(_n.create(e.doc,t<0?i.start(s):i.end(s)))),!0):!1}}const cqe=Sre(-1),dqe=Sre(1);function uqe(t,e=null){return function(n,r){let{$from:i,$to:s}=n.selection,o=i.blockRange(s),l=o&&wO(o,t,e);return l?(r&&r(n.tr.wrap(o,l).scrollIntoView()),!0):!1}}function R9(t,e=null){return function(n,r){let i=!1;for(let s=0;s{if(i)return!1;if(!(!c.isTextblock||c.hasMarkup(t,e)))if(c.type==t)i=!0;else{let u=n.doc.resolve(d),h=u.index();i=u.parent.canReplaceWith(h,h+1,t)}})}if(!i)return!1;if(r){let s=n.tr;for(let o=0;o=2&&e.$from.node(e.depth-1).type.compatibleContent(n)&&e.startIndex==0){if(e.$from.index(e.depth-1)==0)return!1;let c=o.resolve(e.start-2);s=new GN(c,c,e.depth),e.endIndex=0;u--)s=Mt.from(n[u].type.create(n[u].attrs,s));t.step(new Fi(e.start-(r?2:0),e.end,e.start,e.end,new qt(s,0,0),n.length,!0));let o=0;for(let u=0;uo.childCount>0&&o.firstChild.type==t);return s?n?r.node(s.depth-1).type==t?gqe(e,n,t,s):bqe(e,n,s):!0:!1}}function gqe(t,e,n,r){let i=t.tr,s=r.end,o=r.$to.end(r.depth);sv;x--)p-=i.child(x).nodeSize,r.delete(p-1,p+1);let s=r.doc.resolve(n.start),o=s.nodeAfter;if(r.mapping.map(n.end)!=n.start+s.nodeAfter.nodeSize)return!1;let l=n.startIndex==0,c=n.endIndex==i.childCount,d=s.node(-1),u=s.index(-1);if(!d.canReplace(u+(l?0:1),u+1,o.content.append(c?Mt.empty:Mt.from(i))))return!1;let h=s.pos,f=h+o.nodeSize;return r.step(new Fi(h-(l?1:0),f+(c?1:0),h+1,f-1,new qt((l?Mt.empty:Mt.from(i.copy(Mt.empty))).append(c?Mt.empty:Mt.from(i.copy(Mt.empty))),l?0:1,c?0:1),l?0:1)),e(r.scrollIntoView()),!0}function xqe(t){return function(e,n){let{$from:r,$to:i}=e.selection,s=r.blockRange(i,d=>d.childCount>0&&d.firstChild.type==t);if(!s)return!1;let o=s.startIndex;if(o==0)return!1;let l=s.parent,c=l.child(o-1);if(c.type!=t)return!1;if(n){let d=c.lastChild&&c.lastChild.type==l.type,u=Mt.from(d?t.create():null),h=new qt(Mt.from(t.create(null,Mt.from(l.type.create(null,u)))),d?3:1,0),f=s.start,p=s.end;n(e.tr.step(new Fi(f-(d?3:1),p,f,p,h,1,!0)).scrollIntoView())}return!0}}const es=function(t){for(var e=0;;e++)if(t=t.previousSibling,!t)return e},jb=function(t){let e=t.assignedSlot||t.parentNode;return e&&e.nodeType==11?e.host:e};let TR=null;const jd=function(t,e,n){let r=TR||(TR=document.createRange());return r.setEnd(t,n??t.nodeValue.length),r.setStart(t,e||0),r},yqe=function(){TR=null},Yf=function(t,e,n,r){return n&&(F9(t,e,n,r,-1)||F9(t,e,n,r,1))},vqe=/^(img|br|input|textarea|hr)$/i;function F9(t,e,n,r,i){for(var s;;){if(t==n&&e==r)return!0;if(e==(i<0?0:ml(t))){let o=t.parentNode;if(!o||o.nodeType!=1||Uv(t)||vqe.test(t.nodeName)||t.contentEditable=="false")return!1;e=es(t)+(i<0?0:1),t=o}else if(t.nodeType==1){let o=t.childNodes[e+(i<0?-1:0)];if(o.nodeType==1&&o.contentEditable=="false")if(!((s=o.pmViewDesc)===null||s===void 0)&&s.ignoreForSelection)e+=i;else return!1;else t=o,e=i<0?ml(t):0}else return!1}}function ml(t){return t.nodeType==3?t.nodeValue.length:t.childNodes.length}function wqe(t,e){for(;;){if(t.nodeType==3&&e)return t;if(t.nodeType==1&&e>0){if(t.contentEditable=="false")return null;t=t.childNodes[e-1],e=ml(t)}else if(t.parentNode&&!Uv(t))e=es(t),t=t.parentNode;else return null}}function Sqe(t,e){for(;;){if(t.nodeType==3&&e2),sl=Db||(Hc?/Mac/.test(Hc.platform):!1),Cre=Hc?/Win/.test(Hc.platform):!1,$d=/Android \d/.test(cm),Bv=!!L9&&"webkitFontSmoothing"in L9.documentElement.style,kqe=Bv?+(/\bAppleWebKit\/(\d+)/.exec(navigator.userAgent)||[0,0])[1]:0;function Aqe(t){let e=t.defaultView&&t.defaultView.visualViewport;return e?{left:0,right:e.width,top:0,bottom:e.height}:{left:0,right:t.documentElement.clientWidth,top:0,bottom:t.documentElement.clientHeight}}function Cd(t,e){return typeof t=="number"?t:t[e]}function Tqe(t){let e=t.getBoundingClientRect(),n=e.width/t.offsetWidth||1,r=e.height/t.offsetHeight||1;return{left:e.left,right:e.left+t.clientWidth*n,top:e.top,bottom:e.top+t.clientHeight*r}}function O9(t,e,n){let r=t.someProp("scrollThreshold")||0,i=t.someProp("scrollMargin")||5,s=t.dom.ownerDocument;for(let o=n||t.dom;o;){if(o.nodeType!=1){o=jb(o);continue}let l=o,c=l==s.body,d=c?Aqe(s):Tqe(l),u=0,h=0;if(e.topd.bottom-Cd(r,"bottom")&&(h=e.bottom-e.top>d.bottom-d.top?e.top+Cd(i,"top")-d.top:e.bottom-d.bottom+Cd(i,"bottom")),e.leftd.right-Cd(r,"right")&&(u=e.right-d.right+Cd(i,"right")),u||h)if(c)s.defaultView.scrollBy(u,h);else{let p=l.scrollLeft,x=l.scrollTop;h&&(l.scrollTop+=h),u&&(l.scrollLeft+=u);let v=l.scrollLeft-p,g=l.scrollTop-x;e={left:e.left-v,top:e.top-g,right:e.right-v,bottom:e.bottom-g}}let f=c?"fixed":getComputedStyle(o).position;if(/^(fixed|sticky)$/.test(f))break;o=f=="absolute"?o.offsetParent:jb(o)}}function Mqe(t){let e=t.dom.getBoundingClientRect(),n=Math.max(0,e.top),r,i;for(let s=(e.left+e.right)/2,o=n+1;o=n-20){r=l,i=c.top;break}}return{refDOM:r,refTop:i,stack:kre(t.dom)}}function kre(t){let e=[],n=t.ownerDocument;for(let r=t;r&&(e.push({dom:r,top:r.scrollTop,left:r.scrollLeft}),t!=n);r=jb(r));return e}function Pqe({refDOM:t,refTop:e,stack:n}){let r=t?t.getBoundingClientRect().top:0;Are(n,r==0?0:r-e)}function Are(t,e){for(let n=0;n=l){o=Math.max(x.bottom,o),l=Math.min(x.top,l);let v=x.left>e.left?x.left-e.left:x.right=(x.left+x.right)/2?1:0));continue}}else x.top>e.top&&!c&&x.left<=e.left&&x.right>=e.left&&(c=u,d={left:Math.max(x.left,Math.min(x.right,e.left)),top:x.top});!n&&(e.left>=x.right&&e.top>=x.top||e.left>=x.left&&e.top>=x.bottom)&&(s=h+1)}}return!n&&c&&(n=c,i=d,r=0),n&&n.nodeType==3?jqe(n,i):!n||r&&n.nodeType==1?{node:t,offset:s}:Tre(n,i)}function jqe(t,e){let n=t.nodeValue.length,r=document.createRange(),i;for(let s=0;s=(o.left+o.right)/2?1:0)};break}}return r.detach(),i||{node:t,offset:0}}function TO(t,e){return t.left>=e.left-1&&t.left<=e.right+1&&t.top>=e.top-1&&t.top<=e.bottom+1}function Dqe(t,e){let n=t.parentNode;return n&&/^li$/i.test(n.nodeName)&&e.left(o.left+o.right)/2?1:-1}return t.docView.posFromDOM(r,i,s)}function Fqe(t,e,n,r){let i=-1;for(let s=e,o=!1;s!=t.dom;){let l=t.docView.nearestDesc(s,!0),c;if(!l)return null;if(l.dom.nodeType==1&&(l.node.isBlock&&l.parent||!l.contentDOM)&&((c=l.dom.getBoundingClientRect()).width||c.height)&&(l.node.isBlock&&l.parent&&!/^T(R|BODY|HEAD|FOOT)$/.test(l.dom.nodeName)&&(!o&&c.left>r.left||c.top>r.top?i=l.posBefore:(!o&&c.right-1?i:t.docView.posFromDOM(e,n,-1)}function Mre(t,e,n){let r=t.childNodes.length;if(r&&n.tope.top&&i++}let d;Bv&&i&&r.nodeType==1&&(d=r.childNodes[i-1]).nodeType==1&&d.contentEditable=="false"&&d.getBoundingClientRect().top>=e.top&&i--,r==t.dom&&i==r.childNodes.length-1&&r.lastChild.nodeType==1&&e.top>r.lastChild.getBoundingClientRect().bottom?l=t.state.doc.content.size:(i==0||r.nodeType!=1||r.childNodes[i-1].nodeName!="BR")&&(l=Fqe(t,r,i,e))}l==null&&(l=Rqe(t,o,e));let c=t.docView.nearestDesc(o,!0);return{pos:l,inside:c?c.posAtStart-c.border:-1}}function I9(t){return t.top=0&&i==r.nodeValue.length?(c--,u=1):n<0?c--:d++,_y(ih(jd(r,c,d),u),u<0)}if(!t.state.doc.resolve(e-(s||0)).parent.inlineContent){if(s==null&&i&&(n<0||i==ml(r))){let c=r.childNodes[i-1];if(c.nodeType==1)return aj(c.getBoundingClientRect(),!1)}if(s==null&&i=0)}if(s==null&&i&&(n<0||i==ml(r))){let c=r.childNodes[i-1],d=c.nodeType==3?jd(c,ml(c)-(o?0:1)):c.nodeType==1&&(c.nodeName!="BR"||!c.nextSibling)?c:null;if(d)return _y(ih(d,1),!1)}if(s==null&&i=0)}function _y(t,e){if(t.width==0)return t;let n=e?t.left:t.right;return{top:t.top,bottom:t.bottom,left:n,right:n}}function aj(t,e){if(t.height==0)return t;let n=e?t.top:t.bottom;return{top:n,bottom:n,left:t.left,right:t.right}}function Ere(t,e,n){let r=t.state,i=t.root.activeElement;r!=e&&t.updateState(e),i!=t.dom&&t.focus();try{return n()}finally{r!=e&&t.updateState(r),i!=t.dom&&i&&i.focus()}}function Iqe(t,e,n){let r=e.selection,i=n=="up"?r.$from:r.$to;return Ere(t,e,()=>{let{node:s}=t.docView.domFromPos(i.pos,n=="up"?-1:1);for(;;){let l=t.docView.nearestDesc(s,!0);if(!l)break;if(l.node.isBlock){s=l.contentDOM||l.dom;break}s=l.dom.parentNode}let o=Pre(t,i.pos,1);for(let l=s.firstChild;l;l=l.nextSibling){let c;if(l.nodeType==1)c=l.getClientRects();else if(l.nodeType==3)c=jd(l,0,l.nodeValue.length).getClientRects();else continue;for(let d=0;du.top+1&&(n=="up"?o.top-u.top>(u.bottom-o.top)*2:u.bottom-o.bottom>(o.bottom-u.top)*2))return!1}}return!0})}const zqe=/[\u0590-\u08ac]/;function Uqe(t,e,n){let{$head:r}=e.selection;if(!r.parent.isTextblock)return!1;let i=r.parentOffset,s=!i,o=i==r.parent.content.size,l=t.domSelection();return l?!zqe.test(r.parent.textContent)||!l.modify?n=="left"||n=="backward"?s:o:Ere(t,e,()=>{let{focusNode:c,focusOffset:d,anchorNode:u,anchorOffset:h}=t.domSelectionRange(),f=l.caretBidiLevel;l.modify("move",n,"character");let p=r.depth?t.docView.domAfterPos(r.before()):t.dom,{focusNode:x,focusOffset:v}=t.domSelectionRange(),g=x&&!p.contains(x.nodeType==1?x:x.parentNode)||c==x&&d==v;try{l.collapse(u,h),c&&(c!=u||d!=h)&&l.extend&&l.extend(c,d)}catch{}return f!=null&&(l.caretBidiLevel=f),g}):r.pos==r.start()||r.pos==r.end()}let z9=null,U9=null,B9=!1;function Bqe(t,e,n){return z9==e&&U9==n?B9:(z9=e,U9=n,B9=n=="up"||n=="down"?Iqe(t,e,n):Uqe(t,e,n))}const yl=0,H9=1,lf=2,$c=3;class Hv{constructor(e,n,r,i){this.parent=e,this.children=n,this.dom=r,this.contentDOM=i,this.dirty=yl,r.pmViewDesc=this}matchesWidget(e){return!1}matchesMark(e){return!1}matchesNode(e,n,r){return!1}matchesHack(e){return!1}parseRule(){return null}stopEvent(e){return!1}get size(){let e=0;for(let n=0;nes(this.contentDOM);else if(this.contentDOM&&this.contentDOM!=this.dom&&this.dom.contains(this.contentDOM))i=e.compareDocumentPosition(this.contentDOM)&2;else if(this.dom.firstChild){if(n==0)for(let s=e;;s=s.parentNode){if(s==this.dom){i=!1;break}if(s.previousSibling)break}if(i==null&&n==e.childNodes.length)for(let s=e;;s=s.parentNode){if(s==this.dom){i=!0;break}if(s.nextSibling)break}}return i??r>0?this.posAtEnd:this.posAtStart}nearestDesc(e,n=!1){for(let r=!0,i=e;i;i=i.parentNode){let s=this.getDesc(i),o;if(s&&(!n||s.node))if(r&&(o=s.nodeDOM)&&!(o.nodeType==1?o.contains(e.nodeType==1?e:e.parentNode):o==e))r=!1;else return s}}getDesc(e){let n=e.pmViewDesc;for(let r=n;r;r=r.parent)if(r==this)return n}posFromDOM(e,n,r){for(let i=e;i;i=i.parentNode){let s=this.getDesc(i);if(s)return s.localPosFromDOM(e,n,r)}return-1}descAt(e){for(let n=0,r=0;ne||o instanceof Dre){i=e-s;break}s=l}if(i)return this.children[r].domFromPos(i-this.children[r].border,n);for(let s;r&&!(s=this.children[r-1]).size&&s instanceof jre&&s.side>=0;r--);if(n<=0){let s,o=!0;for(;s=r?this.children[r-1]:null,!(!s||s.dom.parentNode==this.contentDOM);r--,o=!1);return s&&n&&o&&!s.border&&!s.domAtom?s.domFromPos(s.size,n):{node:this.contentDOM,offset:s?es(s.dom)+1:0}}else{let s,o=!0;for(;s=r=u&&n<=d-c.border&&c.node&&c.contentDOM&&this.contentDOM.contains(c.contentDOM))return c.parseRange(e,n,u);e=o;for(let h=l;h>0;h--){let f=this.children[h-1];if(f.size&&f.dom.parentNode==this.contentDOM&&!f.emptyChildAt(1)){i=es(f.dom)+1;break}e-=f.size}i==-1&&(i=0)}if(i>-1&&(d>n||l==this.children.length-1)){n=d;for(let u=l+1;ux&&on){let x=l;l=c,c=x}let p=document.createRange();p.setEnd(c.node,c.offset),p.setStart(l.node,l.offset),d.removeAllRanges(),d.addRange(p)}}ignoreMutation(e){return!this.contentDOM&&e.type!="selection"}get contentLost(){return this.contentDOM&&this.contentDOM!=this.dom&&!this.dom.contains(this.contentDOM)}markDirty(e,n){for(let r=0,i=0;i=r:er){let l=r+s.border,c=o-s.border;if(e>=l&&n<=c){this.dirty=e==r||n==o?lf:H9,e==l&&n==c&&(s.contentLost||s.dom.parentNode!=this.contentDOM)?s.dirty=$c:s.markDirty(e-l,n-l);return}else s.dirty=s.dom==s.contentDOM&&s.dom.parentNode==this.contentDOM&&!s.children.length?lf:$c}r=o}this.dirty=lf}markParentsDirty(){let e=1;for(let n=this.parent;n;n=n.parent,e++){let r=e==1?lf:H9;n.dirty{if(!s)return i;if(s.parent)return s.parent.posBeforeChild(s)})),!n.type.spec.raw){if(o.nodeType!=1){let l=document.createElement("span");l.appendChild(o),o=l}o.contentEditable="false",o.classList.add("ProseMirror-widget")}super(e,[],o,null),this.widget=n,this.widget=n,s=this}matchesWidget(e){return this.dirty==yl&&e.type.eq(this.widget.type)}parseRule(){return{ignore:!0}}stopEvent(e){let n=this.widget.spec.stopEvent;return n?n(e):!1}ignoreMutation(e){return e.type!="selection"||this.widget.spec.ignoreSelection}destroy(){this.widget.type.destroy(this.dom),super.destroy()}get domAtom(){return!0}get ignoreForSelection(){return!!this.widget.type.spec.relaxedSide}get side(){return this.widget.type.side}}class Hqe extends Hv{constructor(e,n,r,i){super(e,[],n,null),this.textDOM=r,this.text=i}get size(){return this.text.length}localPosFromDOM(e,n){return e!=this.textDOM?this.posAtStart+(n?this.size:0):this.posAtStart+n}domFromPos(e){return{node:this.textDOM,offset:e}}ignoreMutation(e){return e.type==="characterData"&&e.target.nodeValue==e.oldValue}}class Qf extends Hv{constructor(e,n,r,i,s){super(e,[],r,i),this.mark=n,this.spec=s}static create(e,n,r,i){let s=i.nodeViews[n.type.name],o=s&&s(n,i,r);return(!o||!o.dom)&&(o=ip.renderSpec(document,n.type.spec.toDOM(n,r),null,n.attrs)),new Qf(e,n,o.dom,o.contentDOM||o.dom,o)}parseRule(){return this.dirty&$c||this.mark.type.spec.reparseInView?null:{mark:this.mark.type.name,attrs:this.mark.attrs,contentElement:this.contentDOM}}matchesMark(e){return this.dirty!=$c&&this.mark.eq(e)}markDirty(e,n){if(super.markDirty(e,n),this.dirty!=yl){let r=this.parent;for(;!r.node;)r=r.parent;r.dirty0&&(s=DR(s,0,e,r));for(let l=0;l{if(!c)return o;if(c.parent)return c.parent.posBeforeChild(c)},r,i),u=d&&d.dom,h=d&&d.contentDOM;if(n.isText){if(!u)u=document.createTextNode(n.text);else if(u.nodeType!=3)throw new RangeError("Text must be rendered as a DOM text node")}else u||({dom:u,contentDOM:h}=ip.renderSpec(document,n.type.spec.toDOM(n),null,n.attrs));!h&&!n.isText&&u.nodeName!="BR"&&(u.hasAttribute("contenteditable")||(u.contentEditable="false"),n.type.spec.draggable&&(u.draggable=!0));let f=u;return u=Lre(u,r,n),d?c=new $qe(e,n,r,i,u,h||null,f,d,s,o+1):n.isText?new mA(e,n,r,i,u,f,s):new $h(e,n,r,i,u,h||null,f,s,o+1)}parseRule(){if(this.node.type.spec.reparseInView)return null;let e={node:this.node.type.name,attrs:this.node.attrs};if(this.node.type.whitespace=="pre"&&(e.preserveWhitespace="full"),!this.contentDOM)e.getContent=()=>this.node.content;else if(!this.contentLost)e.contentElement=this.contentDOM;else{for(let n=this.children.length-1;n>=0;n--){let r=this.children[n];if(this.dom.contains(r.dom.parentNode)){e.contentElement=r.dom.parentNode;break}}e.contentElement||(e.getContent=()=>Mt.empty)}return e}matchesNode(e,n,r){return this.dirty==yl&&e.eq(this.node)&&KN(n,this.outerDeco)&&r.eq(this.innerDeco)}get size(){return this.node.nodeSize}get border(){return this.node.isLeaf?0:1}updateChildren(e,n){let r=this.node.inlineContent,i=n,s=e.composing?this.localCompositionInfo(e,n):null,o=s&&s.pos>-1?s:null,l=s&&s.pos<0,c=new qqe(this,o&&o.node,e);Kqe(this.node,this.innerDeco,(d,u,h)=>{d.spec.marks?c.syncToMarks(d.spec.marks,r,e,u):d.type.side>=0&&!h&&c.syncToMarks(u==this.node.childCount?Kr.none:this.node.child(u).marks,r,e,u),c.placeWidget(d,e,i)},(d,u,h,f)=>{c.syncToMarks(d.marks,r,e,f);let p;c.findNodeMatch(d,u,h,f)||l&&e.state.selection.from>i&&e.state.selection.to-1&&c.updateNodeAt(d,u,h,p,e)||c.updateNextNode(d,u,h,e,f,i)||c.addNode(d,u,h,e,i),i+=d.nodeSize}),c.syncToMarks([],r,e,0),this.node.isTextblock&&c.addTextblockHacks(),c.destroyRest(),(c.changed||this.dirty==lf)&&(o&&this.protectLocalComposition(e,o),Rre(this.contentDOM,this.children,e),Db&&Xqe(this.dom))}localCompositionInfo(e,n){let{from:r,to:i}=e.state.selection;if(!(e.state.selection instanceof _n)||rn+this.node.content.size)return null;let s=e.input.compositionNode;if(!s||!this.dom.contains(s.parentNode))return null;if(this.node.inlineContent){let o=s.nodeValue,l=Yqe(this.node.content,o,r-n,i-n);return l<0?null:{node:s,pos:l,text:o}}else return{node:s,pos:-1,text:""}}protectLocalComposition(e,{node:n,pos:r,text:i}){if(this.getDesc(n))return;let s=n;for(;s.parentNode!=this.contentDOM;s=s.parentNode){for(;s.previousSibling;)s.parentNode.removeChild(s.previousSibling);for(;s.nextSibling;)s.parentNode.removeChild(s.nextSibling);s.pmViewDesc&&(s.pmViewDesc=void 0)}let o=new Hqe(this,s,n,i);e.input.compositionNodes.push(o),this.children=DR(this.children,r,r+i.length,e,o)}update(e,n,r,i){return this.dirty==$c||!e.sameMarkup(this.node)?!1:(this.updateInner(e,n,r,i),!0)}updateInner(e,n,r,i){this.updateOuterDeco(n),this.node=e,this.innerDeco=r,this.contentDOM&&this.updateChildren(i,this.posAtStart),this.dirty=yl}updateOuterDeco(e){if(KN(e,this.outerDeco))return;let n=this.nodeDOM.nodeType!=1,r=this.dom;this.dom=Fre(this.dom,this.nodeDOM,jR(this.outerDeco,this.node,n),jR(e,this.node,n)),this.dom!=r&&(r.pmViewDesc=void 0,this.dom.pmViewDesc=this),this.outerDeco=e}selectNode(){this.nodeDOM.nodeType==1&&(this.nodeDOM.classList.add("ProseMirror-selectednode"),(this.contentDOM||!this.node.type.spec.draggable)&&(this.nodeDOM.draggable=!0))}deselectNode(){this.nodeDOM.nodeType==1&&(this.nodeDOM.classList.remove("ProseMirror-selectednode"),(this.contentDOM||!this.node.type.spec.draggable)&&this.nodeDOM.removeAttribute("draggable"))}get domAtom(){return this.node.isAtom}}function $9(t,e,n,r,i){Lre(r,e,t);let s=new $h(void 0,t,e,n,r,r,r,i,0);return s.contentDOM&&s.updateChildren(i,0),s}class mA extends $h{constructor(e,n,r,i,s,o,l){super(e,n,r,i,s,null,o,l,0)}parseRule(){let e=this.nodeDOM.parentNode;for(;e&&e!=this.dom&&!e.pmIsDeco;)e=e.parentNode;return{skip:e||!0}}update(e,n,r,i){return this.dirty==$c||this.dirty!=yl&&!this.inParent()||!e.sameMarkup(this.node)?!1:(this.updateOuterDeco(n),(this.dirty!=yl||e.text!=this.node.text)&&e.text!=this.nodeDOM.nodeValue&&(this.nodeDOM.nodeValue=e.text,i.trackWrites==this.nodeDOM&&(i.trackWrites=null)),this.node=e,this.dirty=yl,!0)}inParent(){let e=this.parent.contentDOM;for(let n=this.nodeDOM;n;n=n.parentNode)if(n==e)return!0;return!1}domFromPos(e){return{node:this.nodeDOM,offset:e}}localPosFromDOM(e,n,r){return e==this.nodeDOM?this.posAtStart+Math.min(n,this.node.text.length):super.localPosFromDOM(e,n,r)}ignoreMutation(e){return e.type!="characterData"&&e.type!="selection"}slice(e,n,r){let i=this.node.cut(e,n),s=document.createTextNode(i.text);return new mA(this.parent,i,this.outerDeco,this.innerDeco,s,s,r)}markDirty(e,n){super.markDirty(e,n),this.dom!=this.nodeDOM&&(e==0||n==this.nodeDOM.nodeValue.length)&&(this.dirty=$c)}get domAtom(){return!1}isText(e){return this.node.text==e}}class Dre extends Hv{parseRule(){return{ignore:!0}}matchesHack(e){return this.dirty==yl&&this.dom.nodeName==e}get domAtom(){return!0}get ignoreForCoords(){return this.dom.nodeName=="IMG"}}class $qe extends $h{constructor(e,n,r,i,s,o,l,c,d,u){super(e,n,r,i,s,o,l,d,u),this.spec=c}update(e,n,r,i){if(this.dirty==$c)return!1;if(this.spec.update&&(this.node.type==e.type||this.spec.multiType)){let s=this.spec.update(e,n,r);return s&&this.updateInner(e,n,r,i),s}else return!this.contentDOM&&!e.isLeaf?!1:super.update(e,n,r,i)}selectNode(){this.spec.selectNode?this.spec.selectNode():super.selectNode()}deselectNode(){this.spec.deselectNode?this.spec.deselectNode():super.deselectNode()}setSelection(e,n,r,i){this.spec.setSelection?this.spec.setSelection(e,n,r.root):super.setSelection(e,n,r,i)}destroy(){this.spec.destroy&&this.spec.destroy(),super.destroy()}stopEvent(e){return this.spec.stopEvent?this.spec.stopEvent(e):!1}ignoreMutation(e){return this.spec.ignoreMutation?this.spec.ignoreMutation(e):super.ignoreMutation(e)}}function Rre(t,e,n){let r=t.firstChild,i=!1;for(let s=0;s>1,l=Math.min(o,e.length);for(;s-1)c>this.index&&(this.changed=!0,this.destroyBetween(this.index,c)),this.top=this.top.children[this.index];else{let u=Qf.create(this.top,e[o],n,r);this.top.children.splice(this.index,0,u),this.top=u,this.changed=!0}this.index=0,o++}}findNodeMatch(e,n,r,i){let s=-1,o;if(i>=this.preMatch.index&&(o=this.preMatch.matches[i-this.preMatch.index]).parent==this.top&&o.matchesNode(e,n,r))s=this.top.children.indexOf(o,this.index);else for(let l=this.index,c=Math.min(this.top.children.length,l+5);l0;){let l;for(;;)if(r){let d=n.children[r-1];if(d instanceof Qf)n=d,r=d.children.length;else{l=d,r--;break}}else{if(n==e)break e;r=n.parent.children.indexOf(n),n=n.parent}let c=l.node;if(c){if(c!=t.child(i-1))break;--i,s.set(l,i),o.push(l)}}return{index:i,matched:s,matches:o.reverse()}}function Wqe(t,e){return t.type.side-e.type.side}function Kqe(t,e,n,r){let i=e.locals(t),s=0;if(i.length==0){for(let d=0;ds;)l.push(i[o++]);let x=s+f.nodeSize;if(f.isText){let g=x;o!g.inline):l.slice();r(f,v,e.forChild(s,f),p),s=x}}function Xqe(t){if(t.nodeName=="UL"||t.nodeName=="OL"){let e=t.style.cssText;t.style.cssText=e+"; list-style: square !important",window.getComputedStyle(t).listStyle,t.style.cssText=e}}function Yqe(t,e,n,r){for(let i=0,s=0;i=n){if(s>=r&&c.slice(r-e.length-l,r-l)==e)return r-e.length;let d=l=0&&d+e.length+l>=n)return l+d;if(n==r&&c.length>=r+e.length-l&&c.slice(r-l,r-l+e.length)==e)return r}}return-1}function DR(t,e,n,r,i){let s=[];for(let o=0,l=0;o=n||u<=e?s.push(c):(dn&&s.push(c.slice(n-d,c.size,r)))}return s}function MO(t,e=null){let n=t.domSelectionRange(),r=t.state.doc;if(!n.focusNode)return null;let i=t.docView.nearestDesc(n.focusNode),s=i&&i.size==0,o=t.docView.posFromDOM(n.focusNode,n.focusOffset,1);if(o<0)return null;let l=r.resolve(o),c,d;if(hA(n)){for(c=o;i&&!i.node;)i=i.parent;let h=i.node;if(i&&h.isAtom&&cn.isSelectable(h)&&i.parent&&!(h.isInline&&_qe(n.focusNode,n.focusOffset,i.dom))){let f=i.posBefore;d=new cn(o==f?l:r.resolve(f))}}else{if(n instanceof t.dom.ownerDocument.defaultView.Selection&&n.rangeCount>1){let h=o,f=o;for(let p=0;p{(n.anchorNode!=r||n.anchorOffset!=i)&&(e.removeEventListener("selectionchange",t.input.hideSelectionGuard),setTimeout(()=>{(!Ore(t)||t.state.selection.visible)&&t.dom.classList.remove("ProseMirror-hideselection")},20))})}function Zqe(t){let e=t.domSelection();if(!e)return;let n=t.cursorWrapper.dom,r=n.nodeName=="IMG";r?e.collapse(n.parentNode,es(n)+1):e.collapse(n,0),!r&&!t.state.selection.visible&&so&&Hh<=11&&(n.disabled=!0,n.disabled=!1)}function Ire(t,e){if(e instanceof cn){let n=t.docView.descAt(e.from);n!=t.lastSelectedViewDesc&&(K9(t),n&&n.selectNode(),t.lastSelectedViewDesc=n)}else K9(t)}function K9(t){t.lastSelectedViewDesc&&(t.lastSelectedViewDesc.parent&&t.lastSelectedViewDesc.deselectNode(),t.lastSelectedViewDesc=void 0)}function PO(t,e,n,r){return t.someProp("createSelectionBetween",i=>i(t,e,n))||_n.between(e,n,r)}function X9(t){return t.editable&&!t.hasFocus()?!1:zre(t)}function zre(t){let e=t.domSelectionRange();if(!e.anchorNode)return!1;try{return t.dom.contains(e.anchorNode.nodeType==3?e.anchorNode.parentNode:e.anchorNode)&&(t.editable||t.dom.contains(e.focusNode.nodeType==3?e.focusNode.parentNode:e.focusNode))}catch{return!1}}function Jqe(t){let e=t.docView.domFromPos(t.state.selection.anchor,0),n=t.domSelectionRange();return Yf(e.node,e.offset,n.anchorNode,n.anchorOffset)}function RR(t,e){let{$anchor:n,$head:r}=t.selection,i=e>0?n.max(r):n.min(r),s=i.parent.inlineContent?i.depth?t.doc.resolve(e>0?i.after():i.before()):null:i;return s&&zn.findFrom(s,e)}function dh(t,e){return t.dispatch(t.state.tr.setSelection(e).scrollIntoView()),!0}function Y9(t,e,n){let r=t.state.selection;if(r instanceof _n)if(n.indexOf("s")>-1){let{$head:i}=r,s=i.textOffset?null:e<0?i.nodeBefore:i.nodeAfter;if(!s||s.isText||!s.isLeaf)return!1;let o=t.state.doc.resolve(i.pos+s.nodeSize*(e<0?-1:1));return dh(t,new _n(r.$anchor,o))}else if(r.empty){if(t.endOfTextblock(e>0?"forward":"backward")){let i=RR(t.state,e);return i&&i instanceof cn?dh(t,i):!1}else if(!(sl&&n.indexOf("m")>-1)){let i=r.$head,s=i.textOffset?null:e<0?i.nodeBefore:i.nodeAfter,o;if(!s||s.isText)return!1;let l=e<0?i.pos-s.nodeSize:i.pos;return s.isAtom||(o=t.docView.descAt(l))&&!o.contentDOM?cn.isSelectable(s)?dh(t,new cn(e<0?t.state.doc.resolve(i.pos-s.nodeSize):i)):Bv?dh(t,new _n(t.state.doc.resolve(e<0?l:l+s.nodeSize))):!1:!1}}else return!1;else{if(r instanceof cn&&r.node.isInline)return dh(t,new _n(e>0?r.$to:r.$from));{let i=RR(t.state,e);return i?dh(t,i):!1}}}function XN(t){return t.nodeType==3?t.nodeValue.length:t.childNodes.length}function Zy(t,e){let n=t.pmViewDesc;return n&&n.size==0&&(e<0||t.nextSibling||t.nodeName!="BR")}function kg(t,e){return e<0?eGe(t):tGe(t)}function eGe(t){let e=t.domSelectionRange(),n=e.focusNode,r=e.focusOffset;if(!n)return;let i,s,o=!1;for(xl&&n.nodeType==1&&r0){if(n.nodeType!=1)break;{let l=n.childNodes[r-1];if(Zy(l,-1))i=n,s=--r;else if(l.nodeType==3)n=l,r=n.nodeValue.length;else break}}else{if(Ure(n))break;{let l=n.previousSibling;for(;l&&Zy(l,-1);)i=n.parentNode,s=es(l),l=l.previousSibling;if(l)n=l,r=XN(n);else{if(n=n.parentNode,n==t.dom)break;r=0}}}o?FR(t,n,r):i&&FR(t,i,s)}function tGe(t){let e=t.domSelectionRange(),n=e.focusNode,r=e.focusOffset;if(!n)return;let i=XN(n),s,o;for(;;)if(r{t.state==i&&Zd(t)},50)}function Q9(t,e){let n=t.state.doc.resolve(e);if(!(ns||Cre)&&n.parent.inlineContent){let i=t.coordsAtPos(e);if(e>n.start()){let s=t.coordsAtPos(e-1),o=(s.top+s.bottom)/2;if(o>i.top&&o1)return s.lefti.top&&o1)return s.left>i.left?"ltr":"rtl"}}return getComputedStyle(t.dom).direction=="rtl"?"rtl":"ltr"}function Z9(t,e,n){let r=t.state.selection;if(r instanceof _n&&!r.empty||n.indexOf("s")>-1||sl&&n.indexOf("m")>-1)return!1;let{$from:i,$to:s}=r;if(!i.parent.inlineContent||t.endOfTextblock(e<0?"up":"down")){let o=RR(t.state,e);if(o&&o instanceof cn)return dh(t,o)}if(!i.parent.inlineContent){let o=e<0?i:s,l=r instanceof Fo?zn.near(o,e):zn.findFrom(o,e);return l?dh(t,l):!1}return!1}function J9(t,e){if(!(t.state.selection instanceof _n))return!0;let{$head:n,$anchor:r,empty:i}=t.state.selection;if(!n.sameParent(r))return!0;if(!i)return!1;if(t.endOfTextblock(e>0?"forward":"backward"))return!0;let s=!n.textOffset&&(e<0?n.nodeBefore:n.nodeAfter);if(s&&!s.isText){let o=t.state.tr;return e<0?o.delete(n.pos-s.nodeSize,n.pos):o.delete(n.pos,n.pos+s.nodeSize),t.dispatch(o),!0}return!1}function eW(t,e,n){t.domObserver.stop(),e.contentEditable=n,t.domObserver.start()}function aGe(t){if(!vs||t.state.selection.$head.parentOffset>0)return!1;let{focusNode:e,focusOffset:n}=t.domSelectionRange();if(e&&e.nodeType==1&&n==0&&e.firstChild&&e.firstChild.contentEditable=="false"){let r=e.firstChild;eW(t,r,"true"),setTimeout(()=>eW(t,r,"false"),20)}return!1}function iGe(t){let e="";return t.ctrlKey&&(e+="c"),t.metaKey&&(e+="m"),t.altKey&&(e+="a"),t.shiftKey&&(e+="s"),e}function sGe(t,e){let n=e.keyCode,r=iGe(e);if(n==8||sl&&n==72&&r=="c")return J9(t,-1)||kg(t,-1);if(n==46&&!e.shiftKey||sl&&n==68&&r=="c")return J9(t,1)||kg(t,1);if(n==13||n==27)return!0;if(n==37||sl&&n==66&&r=="c"){let i=n==37?Q9(t,t.state.selection.from)=="ltr"?-1:1:-1;return Y9(t,i,r)||kg(t,i)}else if(n==39||sl&&n==70&&r=="c"){let i=n==39?Q9(t,t.state.selection.from)=="ltr"?1:-1:1;return Y9(t,i,r)||kg(t,i)}else{if(n==38||sl&&n==80&&r=="c")return Z9(t,-1,r)||kg(t,-1);if(n==40||sl&&n==78&&r=="c")return aGe(t)||Z9(t,1,r)||kg(t,1);if(r==(sl?"m":"c")&&(n==66||n==73||n==89||n==90))return!0}return!1}function EO(t,e){t.someProp("transformCopied",p=>{e=p(e,t)});let n=[],{content:r,openStart:i,openEnd:s}=e;for(;i>1&&s>1&&r.childCount==1&&r.firstChild.childCount==1;){i--,s--;let p=r.firstChild;n.push(p.type.name,p.attrs!=p.type.defaultAttrs?p.attrs:null),r=p.content}let o=t.someProp("clipboardSerializer")||ip.fromSchema(t.state.schema),l=Gre(),c=l.createElement("div");c.appendChild(o.serializeFragment(r,{document:l}));let d=c.firstChild,u,h=0;for(;d&&d.nodeType==1&&(u=qre[d.nodeName.toLowerCase()]);){for(let p=u.length-1;p>=0;p--){let x=l.createElement(u[p]);for(;c.firstChild;)x.appendChild(c.firstChild);c.appendChild(x),h++}d=c.firstChild}d&&d.nodeType==1&&d.setAttribute("data-pm-slice",`${i} ${s}${h?` -${h}`:""} ${JSON.stringify(n)}`);let f=t.someProp("clipboardTextSerializer",p=>p(e,t))||e.content.textBetween(0,e.content.size,`
+=======
+ `,title:A("printers:control")?g(Ot?"printers.resume":"printers.pause"):g("printers.permission.noControl"),children:[Ot?a.jsx(oo,{className:"w-3 h-3"}):a.jsx(XC,{className:"w-3 h-3"}),g(Ot?"printers.resume":"printers.pause")]})]})]})]})})(),(Ft?.length>0||pe.vt_tray.length>0)&&r==="expanded"&&(()=>{const bt=Ft.filter(vt=>vt.tray.length>1),Ot=Ft.filter(vt=>vt.tray.length===1),vn=t.nozzle_count===2||pe?.temperatures?.nozzle_2!==void 0;return a.jsxs("div",{className:"mt-3",children:[a.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[a.jsx("span",{className:"text-[10px] uppercase tracking-wider text-bambu-gray font-medium",children:g("printers.filaments")}),a.jsx("div",{className:"flex-1 h-px bg-bambu-dark-tertiary/30"})]}),a.jsxs("div",{className:"space-y-3",children:[bt.length>0&&a.jsx("div",{className:"grid grid-cols-2 gap-3",children:bt.map(vt=>{const Un=ot[String(vt.id)],Zr=vt.id>=128?vt.id-128:vt.id,Zn=Un!==void 0?Un:Zr,dr=Zn===1,li=Zn===0;return a.jsxs("div",{className:"p-2.5 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary/30",children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsxs("div",{className:"flex items-center gap-1.5",children:[a.jsx("span",{className:"text-[10px] text-white font-medium",children:nh(vt.id,vt.tray.length)}),vn&&(dr||li)&&a.jsx(s9,{side:dr?"L":"R"})]}),(vt.humidity!=null||vt.temp!=null)&&a.jsxs("div",{className:"flex items-center gap-1.5 max-[550px]:flex-col max-[550px]:items-start",children:[vt.humidity!=null&&a.jsx(l9,{humidity:vt.humidity,goodThreshold:s?.humidityGood,fairThreshold:s?.humidityFair,onClick:()=>le({amsId:vt.id,amsLabel:nh(vt.id,vt.tray.length),mode:"humidity"}),compact:!0}),vt.temp!=null&&a.jsx(c9,{temp:vt.temp,goodThreshold:s?.tempGood,fairThreshold:s?.tempFair,onClick:()=>le({amsId:vt.id,amsLabel:nh(vt.id,vt.tray.length),mode:"temperature"}),compact:!0})]})]}),a.jsx("div",{className:"grid grid-cols-4 gap-1.5",children:[0,1,2,3].map(rn=>{const Pn=vt.tray[rn]||vt.tray.find($n=>$n.id===rn),Ci=Pn?.tray_type&&Pn.remain>=0,Bs=!Pn?.tray_type,zo=vt.id*4+rn,Uo=Be===zo,zi=Pn?.tray_info_idx?qe?.[Pn.tray_info_idx]:null,Dr=ke?.[zo],Hs=Pn?.tray_uuid?.toUpperCase(),Ca=Hs?c?.[Hs]:void 0,Jr=Kj(Ca),is=u?.(t.id,vt.id,rn),ur=(()=>{const $n=is?.spool;return $n&&$n.label_weight>0&&$n.weight_used!=null?Math.round(Math.max(0,$n.label_weight-$n.weight_used)/$n.label_weight*100):null})(),Ui=Jr??ur??(Ci?Pn.remain:null),jl=Jr!==null?"spoolman":ur!==null?"inventory":Ci?"ams":void 0,Cr=Pn?.tray_type?{vendor:Xj(Pn)?"Bambu Lab":"Generic",profile:zi?.name||Dr?.preset_name||Pn.tray_sub_brands||Pn.tray_type,colorName:$j(Pn.tray_id_name)||Vj(Pn.tray_color),colorHex:Pn.tray_color||null,kFactor:qj(Pn.k),fillLevel:Ui,trayUuid:Pn.tray_uuid||null,tagUid:Pn.tag_uid||null,fillSource:jl}:null,Xt=gt?.amsId===vt.id&>?.slotId===rn,ya=a.jsxs("div",{className:`bg-bambu-dark-tertiary rounded p-1 text-center ${Bs?"opacity-50":""} ${Uo?"ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark":""}`,children:[a.jsx("div",{className:"w-3.5 h-3.5 rounded-full mx-auto mb-0.5 border-2",style:{backgroundColor:Pn?.tray_color?`#${Pn.tray_color}`:Pn?.tray_type?"#333":"transparent",borderColor:Bs?"#666":"rgba(255,255,255,0.1)",borderStyle:Bs?"dashed":"solid"}}),a.jsx("div",{className:"text-[9px] text-white font-bold truncate",children:Pn?.tray_type||"—"}),a.jsx("div",{className:"mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden",children:Ui!==null&&Ui>=0&&Pn&&a.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${Ui}%`,backgroundColor:Wj(Ui)}})})]});return a.jsxs("div",{className:"relative group",children:[Xt&&a.jsx("div",{className:"absolute inset-0 bg-bambu-dark-tertiary/80 rounded flex items-center justify-center z-20",children:a.jsx(Sr,{className:"w-4 h-4 text-bambu-green animate-spin"})}),pe?.state!=="RUNNING"&&a.jsx("button",{onClick:$n=>{$n.stopPropagation(),Qn(vr?.amsId===vt.id&&vr?.slotId===rn?null:{amsId:vt.id,slotId:rn})},className:"absolute -top-1 -right-1 w-4 h-4 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity z-10 hover:bg-bambu-dark-tertiary",title:g("printers.slotOptions"),children:a.jsx(Mh,{className:"w-2.5 h-2.5 text-bambu-gray"})}),pe?.state!=="RUNNING"&&vr?.amsId===vt.id&&vr?.slotId===rn&&a.jsx("div",{className:"absolute top-full left-0 mt-1 z-50 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl py-1 min-w-[120px]",children:a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-xs flex items-center gap-2 ${A("printers:ams_rfid")?"text-white hover:bg-bambu-dark-tertiary":"text-bambu-gray/50 cursor-not-allowed"}`,onClick:$n=>{$n.stopPropagation(),A("printers:ams_rfid")&&(Pt.mutate({amsId:vt.id,slotId:rn}),Qn(null))},disabled:Xt||!A("printers:ams_rfid"),title:A("printers:ams_rfid")?void 0:g("printers.permission.noAmsRfid"),children:[a.jsx(Sr,{className:`w-3 h-3 ${Xt?"animate-spin":""}`}),g("printers.rfid.reread")]})}),Cr?a.jsx(Bj,{data:Cr,spoolman:{enabled:o,hasUnlinkedSpools:l,linkedSpoolId:Cr.trayUuid?c?.[Cr.trayUuid.toUpperCase()]?.id:void 0,spoolmanUrl:d,onLinkSpool:o&&Cr.trayUuid?$n=>{V({tagUid:Cr.tagUid||"",trayUuid:$n,printerId:t.id,amsId:vt.id,trayId:rn})}:void 0},inventory:o?void 0:(()=>{const $n=u?.(t.id,vt.id,rn);return{assignedSpool:$n?.spool?{id:$n.spool.id,material:$n.spool.material,brand:$n.spool.brand,color_name:$n.spool.color_name,remainingWeightGrams:Math.max(0,Math.round($n.spool.label_weight-$n.spool.weight_used))}:null,onAssignSpool:Cr.vendor!=="Bambu Lab"?()=>fe({printerId:t.id,amsId:vt.id,trayId:rn,trayInfo:{type:Cr.profile,color:Cr.colorHex||"",location:`${nh(vt.id,vt.tray.length)} Slot ${rn+1}`}}):void 0,onUnassignSpool:$n&&Cr.vendor!=="Bambu Lab"?()=>h?.(t.id,vt.id,rn):void 0}})(),configureSlot:{enabled:A("printers:control"),onConfigure:()=>re({amsId:vt.id,trayId:rn,trayCount:vt.tray.length,trayType:Pn?.tray_type||void 0,trayColor:Pn?.tray_color||void 0,traySubBrands:Pn?.tray_sub_brands||void 0,trayInfoIdx:Pn?.tray_info_idx||void 0,extruderId:Un,caliIdx:Pn?.cali_idx,savedPresetId:Dr?.preset_id})},children:ya}):a.jsx(Hj,{configureSlot:{enabled:A("printers:control"),onConfigure:()=>re({amsId:vt.id,trayId:rn,trayCount:vt.tray.length,extruderId:Un})},children:ya})]},rn)})})]},vt.id)})}),(Ot.length>0||pe.vt_tray.length>0)&&a.jsxs("div",{className:"grid grid-cols-4 gap-3",children:[Ot.map(vt=>{const Un=ot[String(vt.id)],Zr=vt.id>=128?vt.id-128:vt.id,Zn=Un!==void 0?Un:Zr,dr=Zn===1,li=Zn===0,rn=vt.tray[0],Pn=rn?.tray_type&&rn.remain>=0,Ci=!rn?.tray_type,Bs=BN(vt.id,rn?.id??0,!1),zo=Be===Bs,Uo=rn?.tray_info_idx?qe?.[rn.tray_info_idx]:null,zi=ke?.[Bs],Dr=rn?.tray_uuid?.toUpperCase(),Hs=Dr?c?.[Dr]:void 0,Ca=Kj(Hs),Jr=rn?.id??0,is=u?.(t.id,vt.id,Jr),ur=(()=>{const kr=is?.spool;return kr&&kr.label_weight>0&&kr.weight_used!=null?Math.round(Math.max(0,kr.label_weight-kr.weight_used)/kr.label_weight*100):null})(),Ui=Ca??ur??(Pn?rn.remain:null),jl=Ca!==null?"spoolman":ur!==null?"inventory":Pn?"ams":void 0,Cr=rn?.tray_type?{vendor:Xj(rn)?"Bambu Lab":"Generic",profile:Uo?.name||zi?.preset_name||rn.tray_sub_brands||rn.tray_type,colorName:$j(rn.tray_id_name)||Vj(rn.tray_color),colorHex:rn.tray_color||null,kFactor:qj(rn.k),fillLevel:Ui,trayUuid:rn.tray_uuid||null,tagUid:rn.tag_uid||null,fillSource:jl}:null,Xt=rn?.id??0,ya=gt?.amsId===vt.id&>?.slotId===Xt,$n=a.jsxs("div",{className:`bg-bambu-dark-tertiary rounded p-1 text-center ${Ci?"opacity-50":""} ${zo?"ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark":""}`,children:[a.jsx("div",{className:"w-3.5 h-3.5 rounded-full mx-auto mb-0.5 border-2",style:{backgroundColor:rn?.tray_color?`#${rn.tray_color}`:rn?.tray_type?"#333":"transparent",borderColor:Ci?"#666":"rgba(255,255,255,0.1)",borderStyle:Ci?"dashed":"solid"}}),a.jsx("div",{className:"text-[9px] text-white font-bold truncate",children:rn?.tray_type||"—"}),a.jsx("div",{className:"mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden",children:Ui!==null&&Ui>=0&&a.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${Ui}%`,backgroundColor:Wj(Ui)}})})]});return a.jsxs("div",{className:"p-2.5 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary/30",children:[a.jsxs("div",{className:"flex items-center gap-1 mb-2",children:[a.jsx("span",{className:"text-[10px] text-white font-medium",children:nh(vt.id,vt.tray.length)}),vn&&(dr||li)&&a.jsx(s9,{side:dr?"L":"R"})]}),a.jsxs("div",{className:"flex gap-1.5 max-[550px]:flex-col max-[550px]:items-start",children:[a.jsxs("div",{className:"relative group flex-1 max-[550px]:w-full",children:[ya&&a.jsx("div",{className:"absolute inset-0 bg-bambu-dark-tertiary/80 rounded flex items-center justify-center z-20",children:a.jsx(Sr,{className:"w-4 h-4 text-bambu-green animate-spin"})}),pe?.state!=="RUNNING"&&a.jsx("button",{onClick:kr=>{kr.stopPropagation(),Qn(vr?.amsId===vt.id&&vr?.slotId===Xt?null:{amsId:vt.id,slotId:Xt})},className:"absolute -top-1 -right-1 w-4 h-4 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity z-10 hover:bg-bambu-dark-tertiary",title:g("printers.slotOptions"),children:a.jsx(Mh,{className:"w-2.5 h-2.5 text-bambu-gray"})}),pe?.state!=="RUNNING"&&vr?.amsId===vt.id&&vr?.slotId===Xt&&a.jsx("div",{className:"absolute top-full left-0 mt-1 z-50 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl py-1 min-w-[120px]",children:a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-xs flex items-center gap-2 ${A("printers:ams_rfid")?"text-white hover:bg-bambu-dark-tertiary":"text-bambu-gray/50 cursor-not-allowed"}`,onClick:kr=>{kr.stopPropagation(),A("printers:ams_rfid")&&(Pt.mutate({amsId:vt.id,slotId:Xt}),Qn(null))},disabled:ya||!A("printers:ams_rfid"),title:A("printers:ams_rfid")?void 0:g("printers.permission.noAmsRfid"),children:[a.jsx(Sr,{className:`w-3 h-3 ${ya?"animate-spin":""}`}),g("printers.rfid.reread")]})}),Cr?a.jsx(Bj,{data:Cr,spoolman:{enabled:o,hasUnlinkedSpools:l,linkedSpoolId:Cr.trayUuid?c?.[Cr.trayUuid.toUpperCase()]?.id:void 0,spoolmanUrl:d,onLinkSpool:o&&Cr.trayUuid?kr=>{V({tagUid:Cr.tagUid||"",trayUuid:kr,printerId:t.id,amsId:vt.id,trayId:Xt})}:void 0},inventory:o?void 0:(()=>{const kr=u?.(t.id,vt.id,Xt);return{assignedSpool:kr?.spool?{id:kr.spool.id,material:kr.spool.material,brand:kr.spool.brand,color_name:kr.spool.color_name,remainingWeightGrams:Math.max(0,Math.round(kr.spool.label_weight-kr.spool.weight_used))}:null,onAssignSpool:Cr.vendor!=="Bambu Lab"?()=>fe({printerId:t.id,amsId:vt.id,trayId:Xt,trayInfo:{type:Cr.profile,color:Cr.colorHex||"",location:nh(vt.id,vt.tray.length)}}):void 0,onUnassignSpool:kr&&Cr.vendor!=="Bambu Lab"?()=>h?.(t.id,vt.id,Xt):void 0}})(),configureSlot:{enabled:A("printers:control"),onConfigure:()=>re({amsId:vt.id,trayId:Xt,trayCount:vt.tray.length,trayType:rn?.tray_type||void 0,trayColor:rn?.tray_color||void 0,traySubBrands:rn?.tray_sub_brands||void 0,trayInfoIdx:rn?.tray_info_idx||void 0,extruderId:Un,caliIdx:rn?.cali_idx,savedPresetId:zi?.preset_id})},children:$n}):a.jsx(Hj,{configureSlot:{enabled:A("printers:control"),onConfigure:()=>re({amsId:vt.id,trayId:Xt,trayCount:vt.tray.length,extruderId:Un})},children:$n})]}),(vt.humidity!=null||vt.temp!=null)&&a.jsxs("div",{className:"flex flex-col justify-center gap-1 shrink-0 max-[550px]:w-full",children:[vt.temp!=null&&a.jsx(c9,{temp:vt.temp,goodThreshold:s?.tempGood,fairThreshold:s?.tempFair,onClick:()=>le({amsId:vt.id,amsLabel:nh(vt.id,vt.tray.length),mode:"temperature"}),compact:!0}),vt.humidity!=null&&a.jsx(l9,{humidity:vt.humidity,goodThreshold:s?.humidityGood,fairThreshold:s?.humidityFair,onClick:()=>le({amsId:vt.id,amsLabel:nh(vt.id,vt.tray.length),mode:"humidity"}),compact:!0})]})]})]},vt.id)}),pe.vt_tray.length>0&&a.jsxs("div",{className:`p-2.5 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary/30 ${pe.vt_tray.length===1?"max-w-[50%]":""}`,children:[a.jsx("div",{className:"flex items-center gap-1 mb-2",children:a.jsx("span",{className:"text-[10px] text-white font-medium",children:g("printers.external")})}),a.jsx("div",{className:`grid ${pe.vt_tray.length>1?"grid-cols-2":"grid-cols-1"} gap-1.5`,children:[...pe.vt_tray].sort((vt,Un)=>(vt.id??254)-(Un.id??254)).map(vt=>{const Un=vt.id??254,Zr=vn&&Be===254?Un===254&&pe.active_extruder===1||Un===255&&pe.active_extruder===0:Be===Un,Zn=Un-254,dr=vn?g(Un===254?"printers.extL":"printers.extR"):"",li=vt.tray_info_idx?qe?.[vt.tray_info_idx]:null,rn=ke?.[1020+Zn],Pn=vt.tray_uuid?.toUpperCase(),Ci=Pn?c?.[Pn]:void 0,Bs=Kj(Ci),zo=u?.(t.id,255,Zn),Uo=(()=>{const ur=zo?.spool;return ur&&ur.label_weight>0&&ur.weight_used!=null?Math.round(Math.max(0,ur.label_weight-ur.weight_used)/ur.label_weight*100):null})(),zi=vt.tray_type&&vt.remain>=0,Dr=Bs??Uo??(zi?vt.remain:null),Hs=Bs!==null?"spoolman":Uo!==null?"inventory":zi?"ams":void 0,Ca={vendor:Xj(vt)?"Bambu Lab":"Generic",profile:li?.name||rn?.preset_name||vt.tray_sub_brands||vt.tray_type||"Unknown",colorName:$j(vt.tray_id_name)||Vj(vt.tray_color),colorHex:vt.tray_color||null,kFactor:qj(vt.k),fillLevel:Dr,trayUuid:vt.tray_uuid||null,tagUid:vt.tag_uid||null,fillSource:Hs},Jr=!vt.tray_type,is=a.jsxs("div",{className:`bg-bambu-dark-tertiary rounded p-1 text-center ${Jr?"opacity-50":""} ${Zr?"ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark":""}`,children:[a.jsx("div",{className:"w-3.5 h-3.5 rounded-full mx-auto mb-0.5 border-2",style:{backgroundColor:vt.tray_color?`#${vt.tray_color}`:vt.tray_type?"#333":"transparent",borderColor:Jr?"#666":"rgba(255,255,255,0.1)",borderStyle:Jr?"dashed":"solid"}}),a.jsx("div",{className:`text-[9px] font-bold truncate ${Jr?"text-white/40":"text-white"}`,children:vt.tray_type||"—"}),a.jsx("div",{className:"mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden",children:Dr!==null&&Dr>=0&&!Jr&&a.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${Dr}%`,backgroundColor:Wj(Dr)}})}),dr&&a.jsx("div",{className:"text-[7px] text-white/40 mt-0.5 truncate",children:dr})]});return a.jsx("div",{className:"relative group",children:Jr?a.jsx(Hj,{configureSlot:{enabled:A("printers:control"),onConfigure:()=>re({amsId:255,trayId:Zn,trayCount:1,extruderId:vn?Un===254?1:0:void 0})},children:is}):a.jsx(Bj,{data:Ca,spoolman:{enabled:o,hasUnlinkedSpools:l,linkedSpoolId:Ca.trayUuid?c?.[Ca.trayUuid.toUpperCase()]?.id:void 0,spoolmanUrl:d,onLinkSpool:o&&Ca.trayUuid?ur=>{V({tagUid:Ca.tagUid||"",trayUuid:ur,printerId:t.id,amsId:255,trayId:Zn})}:void 0},inventory:o?void 0:(()=>{const ur=u?.(t.id,255,Zn);return{assignedSpool:ur?.spool?{id:ur.spool.id,material:ur.spool.material,brand:ur.spool.brand,color_name:ur.spool.color_name,remainingWeightGrams:Math.max(0,Math.round(ur.spool.label_weight-ur.spool.weight_used))}:null,onAssignSpool:()=>fe({printerId:t.id,amsId:255,trayId:Zn,trayInfo:{type:Ca.profile,color:Ca.colorHex||"",location:dr||g("printers.external")}}),onUnassignSpool:ur?()=>h?.(t.id,255,Zn):void 0}})(),configureSlot:{enabled:A("printers:control"),onConfigure:()=>re({amsId:255,trayId:Zn,trayCount:1,trayType:vt.tray_type||void 0,trayColor:vt.tray_color||void 0,traySubBrands:vt.tray_sub_brands||void 0,trayInfoIdx:vt.tray_info_idx||void 0,extruderId:vn?Un===254?1:0:void 0,caliIdx:vt.cali_idx,savedPresetId:rn?.preset_id})},children:is})},Un)})})]})]})]})]})})()]}),mt&&r==="expanded"&&a.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[a.jsx(ru,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}),a.jsx("span",{className:"text-sm text-white truncate",children:mt.name}),zt&&a.jsxs("span",{className:`text-xs px-1.5 py-0.5 rounded flex-shrink-0 ${zt.state==="ON"?"bg-bambu-green/20 text-bambu-green":zt.state==="OFF"?"bg-red-500/20 text-red-400":"bg-bambu-gray/20 text-bambu-gray"}`,children:[zt.state||"?",zt.state==="ON"&&zt.energy?.power!=null&&a.jsxs("span",{className:"text-yellow-400 ml-1.5",children:["· ",zt.energy.power,"W"]})]})]}),a.jsx("div",{className:"flex-1"}),a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsxs("button",{onClick:()=>W(!0),disabled:tt.isPending||zt?.state==="ON"||!A("smart_plugs:control"),className:`px-2 py-1 text-xs rounded transition-colors flex items-center gap-1 ${A("smart_plugs:control")?zt?.state==="ON"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary":"bg-bambu-dark text-bambu-gray/50 cursor-not-allowed"}`,title:A("smart_plugs:control")?void 0:g("printers.permission.noSmartPlugControl"),children:[a.jsx(fu,{className:"w-3 h-3"}),"On"]}),a.jsxs("button",{onClick:()=>te(!0),disabled:tt.isPending||zt?.state==="OFF"||!A("smart_plugs:control"),className:`px-2 py-1 text-xs rounded transition-colors flex items-center gap-1 ${A("smart_plugs:control")?zt?.state==="OFF"?"bg-red-500/30 text-red-400":"bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary":"bg-bambu-dark text-bambu-gray/50 cursor-not-allowed"}`,title:A("smart_plugs:control")?void 0:g("printers.permission.noSmartPlugControl"),children:[a.jsx(YC,{className:"w-3 h-3"}),"Off"]})]}),a.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[a.jsx("span",{className:`text-xs hidden sm:inline ${mt.auto_off_executed?"text-bambu-green":"text-bambu-gray"}`,children:mt.auto_off_executed?"Auto-off done":"Auto-off"}),a.jsx("button",{onClick:()=>st.mutate(!mt.auto_off),disabled:st.isPending||mt.auto_off_executed||!A("smart_plugs:control"),title:A("smart_plugs:control")?mt.auto_off_executed?g("printers.autoOffExecuted"):g("printers.autoOffAfterPrint"):g("printers.permission.noSmartPlugControl"),className:`relative w-9 h-5 rounded-full transition-colors flex-shrink-0 ${A("smart_plugs:control")?mt.auto_off_executed?"bg-bambu-green/50 cursor-not-allowed":mt.auto_off?"bg-bambu-green":"bg-bambu-dark-tertiary":"bg-bambu-dark-tertiary/50 cursor-not-allowed"}`,children:a.jsx("span",{className:`absolute top-[2px] left-[2px] w-4 h-4 bg-white rounded-full transition-transform ${mt.auto_off||mt.auto_off_executed?"translate-x-4":"translate-x-0"}`})})]})]}),yt&&yt.length>0&&a.jsxs("div",{className:"flex items-center gap-2 mt-2 pt-2 border-t border-bambu-dark-tertiary/50",children:[a.jsx(dv,{className:"w-3.5 h-3.5 text-blue-400 flex-shrink-0"}),a.jsx("span",{className:"text-xs text-bambu-gray",children:"HA:"}),a.jsx("div",{className:"flex flex-wrap gap-1",children:yt.map(bt=>a.jsxs("button",{onClick:()=>Ke.mutate(bt.id),disabled:Ke.isPending,title:`Run ${bt.ha_entity_id}`,className:"px-2 py-0.5 text-xs bg-blue-500/20 text-blue-400 hover:bg-blue-500/30 rounded transition-colors flex items-center gap-1",children:[a.jsx(oo,{className:"w-2.5 h-2.5"}),bt.name]},bt.id))})]})]}),r==="expanded"&&a.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3",children:[a.jsxs("div",{className:"text-xs text-bambu-gray",children:[a.jsx("p",{children:t.ip_address}),a.jsx("p",{className:"truncate",children:t.serial_number})]}),a.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[a.jsx(Me,{variant:"secondary",size:"sm",onClick:()=>Qe.mutate(!pe?.chamber_light),disabled:!pe?.connected||Qe.isPending||!A("printers:control"),title:A("printers:control")?pe?.chamber_light?g("printers.chamberLightOff"):g("printers.chamberLightOn"):g("printers.permission.noControl"),className:pe?.chamber_light?"bg-yellow-500/20 hover:bg-yellow-500/30 border-yellow-500/30":"",children:a.jsx(dL,{on:pe?.chamber_light??!1,className:"w-4 h-4"})}),a.jsx(Me,{variant:"secondary",size:"sm",onClick:()=>{if(p==="embedded"&&x)x(t.id,t.name);else{const bt=localStorage.getItem("cameraWindowState"),Ot=bt?JSON.parse(bt):{width:640,height:400},vn=[`width=${Ot.width}`,`height=${Ot.height}`,Ot.left!==void 0?`left=${Ot.left}`:"",Ot.top!==void 0?`top=${Ot.top}`:"","menubar=no,toolbar=no,location=no,status=no,noopener"].filter(Boolean).join(",");window.open(`/camera/${t.id}`,`camera-${t.id}`,vn)}},disabled:!pe?.connected||!A("camera:view"),title:A("camera:view")?g(p==="embedded"?"printers.openCameraOverlay":"printers.openCameraWindow"):g("printers.permission.noCamera"),children:a.jsx(EF,{className:"w-4 h-4"})}),a.jsxs("div",{className:`inline-flex rounded-md ${t.plate_detection_enabled?"ring-1 ring-green-500":""}`,children:[a.jsx(Me,{variant:"secondary",size:"sm",onClick:Zt,disabled:!pe?.connected||Xe.isPending||!A("printers:update"),title:A("printers:update")?t.plate_detection_enabled?g("printers.plateDetection.enabledClick"):g("printers.plateDetection.disabledClick"):g("printers.plateDetection.noPermission"),className:`!rounded-r-none !border-r-0 ${t.plate_detection_enabled?"!border-green-500 !text-green-400 hover:!bg-green-500/20":""}`,children:Xe.isPending?a.jsx(at,{className:"w-4 h-4 animate-spin"}):a.jsx(_1,{className:"w-4 h-4"})}),a.jsx(Me,{variant:"secondary",size:"sm",onClick:fn,disabled:!pe?.connected||O||!A("printers:update"),title:A("printers:update")?g("printers.plateDetection.manageCalibration"):g("printers.plateDetection.noPermission"),className:`!rounded-l-none !px-1.5 ${t.plate_detection_enabled?"!border-green-500 !text-green-400 hover:!bg-green-500/20":""}`,children:O?a.jsx(at,{className:"w-3 h-3 animate-spin"}):a.jsx(Mn,{className:"w-3 h-3"})})]}),a.jsxs(Me,{variant:"secondary",size:"sm",onClick:()=>D(!0),disabled:!A("printers:files"),title:A("printers:files")?g("printers.browseFiles"):g("printers.permission.noFiles"),children:[a.jsx(Vb,{className:"w-4 h-4"}),"Files"]})]})]})]}),U&&a.jsx(LTe,{printerId:t.id,printerName:t.name,onClose:()=>D(!1)}),$&&a.jsx(HTe,{printerId:t.id,printerName:t.name,onClose:()=>G(!1)}),Pe&&a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onClick:()=>un(),children:a.jsxs("div",{className:"bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl max-w-lg w-full",onClick:bt=>bt.stopPropagation(),children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[Pe.needs_calibration?a.jsx(_1,{className:"w-5 h-5 text-blue-500"}):Pe.is_empty?a.jsx(yr,{className:"w-5 h-5 text-green-500"}):a.jsx(mi,{className:"w-5 h-5 text-yellow-500"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:"Build Plate Check"}),Pe.reference_count!==void 0&&Pe.max_references&&a.jsxs("span",{className:"text-xs text-bambu-gray bg-bambu-dark-tertiary px-2 py-1 rounded",children:[Pe.reference_count,"/",Pe.max_references," refs"]})]}),a.jsx("button",{onClick:()=>un(),className:"p-1 text-bambu-gray hover:text-white rounded transition-colors",children:a.jsx(Dt,{className:"w-5 h-5"})})]}),a.jsxs("div",{className:"p-4 space-y-4",children:[Pe.needs_calibration?a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"p-3 rounded-lg bg-blue-500/20 border border-blue-500/50",children:[a.jsx("p",{className:"font-medium text-blue-400",children:g("printers.plateDetection.calibrationRequired")}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",dangerouslySetInnerHTML:{__html:g("printers.plateDetection.calibrationInstructions")}})]}),a.jsxs("div",{className:"text-sm text-bambu-gray space-y-2",children:[a.jsx("p",{children:g("printers.plateDetection.calibrationDescription")}),a.jsx("p",{dangerouslySetInnerHTML:{__html:g("printers.plateDetection.calibrationTip")}})]})]}):a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:`p-3 rounded-lg ${Pe.is_empty?"bg-green-500/20 border border-green-500/50":"bg-yellow-500/20 border border-yellow-500/50"}`,children:[a.jsx("p",{className:`font-medium ${Pe.is_empty?"text-green-400":"text-yellow-400"}`,children:Pe.is_empty?g("printers.plateDetection.plateEmpty"):g("printers.plateDetection.objectsDetected")}),a.jsxs("p",{className:"text-sm text-bambu-gray mt-1",children:[g("printers.plateDetection.confidence"),": ",Math.round(Pe.confidence*100),"% | ",g("printers.plateDetection.difference"),": ",Pe.difference_percent.toFixed(1),"%"]})]}),Pe.debug_image_url&&a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-bambu-gray mb-2",children:g("printers.plateDetection.analysisPreview")}),a.jsx("img",{src:Pe.debug_image_url,alt:g("printers.plateDetection.analysisPreview"),className:"w-full rounded-lg border border-bambu-dark-tertiary"}),a.jsx("p",{className:"text-xs text-bambu-gray mt-2",children:g("printers.plateDetection.analysisLegend")})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:Pe.message})]}),tn&&tn.references.length>0&&a.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[a.jsx("p",{className:"text-sm font-medium text-white mb-2",children:g("printers.plateDetection.savedReferences",{count:tn.references.length,max:tn.max_references})}),a.jsx("div",{className:"grid grid-cols-5 gap-2",children:tn.references.map(bt=>a.jsxs("div",{className:"relative group",children:[a.jsx("img",{src:J.getPlateReferenceThumbnailUrl(t.id,bt.index),alt:bt.label||`Reference ${bt.index+1}`,className:"w-full aspect-video object-cover rounded border border-bambu-dark-tertiary"}),a.jsx("button",{onClick:()=>lr(bt.index),className:"absolute top-1 right-1 p-0.5 bg-red-500/80 rounded opacity-0 group-hover:opacity-100 transition-opacity",title:g("printers.plateDetection.deleteReference"),children:a.jsx(Dt,{className:"w-3 h-3 text-white"})}),on?.index===bt.index?a.jsx("input",{type:"text",value:on.label,onChange:Ot=>gn({...on,label:Ot.target.value}),onBlur:()=>pn(bt.index,on.label),onKeyDown:Ot=>{Ot.key==="Enter"&&pn(bt.index,on.label),Ot.key==="Escape"&&gn(null)},className:"w-full mt-1 px-1 py-0.5 text-xs bg-bambu-dark-tertiary border border-bambu-green rounded text-white",autoFocus:!0,placeholder:g("printers.plateDetection.labelPlaceholder")}):a.jsx("p",{className:"text-xs text-bambu-gray mt-1 truncate cursor-pointer hover:text-white",onClick:()=>gn({index:bt.index,label:bt.label}),title:bt.label?g("printers.plateDetection.clickToEdit",{label:bt.label}):g("printers.plateDetection.clickToAddLabel"),children:bt.label||a.jsx("span",{className:"italic opacity-50",children:g("printers.noLabel")})}),a.jsx("p",{className:"text-[10px] text-bambu-gray/60",children:bt.timestamp?tr(bt.timestamp)?.toLocaleDateString()??"":""})]},bt.index))})]}),!Pe.needs_calibration&&a.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsx("p",{className:"text-sm font-medium text-white",children:g("printers.roi.title")}),ge?a.jsxs("div",{className:"flex gap-1",children:[a.jsx(Me,{variant:"ghost",size:"sm",onClick:()=>ae(null),disabled:Ue,children:g("common.cancel")}),a.jsx(Me,{size:"sm",onClick:as,disabled:Ue,children:Ue?a.jsx(at,{className:"w-3 h-3 animate-spin"}):g("common.save")})]}):a.jsxs(Me,{variant:"ghost",size:"sm",onClick:()=>ae(Pe.roi||{x:.15,y:.35,w:.7,h:.55}),children:[a.jsx(Ga,{className:"w-3 h-3 mr-1"}),g("common.edit")]})]}),ge?a.jsxs("div",{className:"space-y-3 bg-bambu-dark-tertiary/50 p-3 rounded-lg",children:[a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"text-xs text-bambu-gray",children:g("printers.roi.xStart")}),a.jsx("input",{type:"range",min:"0",max:"0.9",step:"0.01",value:ge.x,onChange:bt=>ae({...ge,x:parseFloat(bt.target.value)}),className:"w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"}),a.jsxs("span",{className:"text-xs text-bambu-gray",children:[Math.round(ge.x*100),"%"]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"text-xs text-bambu-gray",children:g("printers.roi.yStart")}),a.jsx("input",{type:"range",min:"0",max:"0.9",step:"0.01",value:ge.y,onChange:bt=>ae({...ge,y:parseFloat(bt.target.value)}),className:"w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"}),a.jsxs("span",{className:"text-xs text-bambu-gray",children:[Math.round(ge.y*100),"%"]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"text-xs text-bambu-gray",children:g("printers.width")}),a.jsx("input",{type:"range",min:"0.1",max:"1",step:"0.01",value:ge.w,onChange:bt=>ae({...ge,w:parseFloat(bt.target.value)}),className:"w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"}),a.jsxs("span",{className:"text-xs text-bambu-gray",children:[Math.round(ge.w*100),"%"]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"text-xs text-bambu-gray",children:g("printers.height")}),a.jsx("input",{type:"range",min:"0.1",max:"1",step:"0.01",value:ge.h,onChange:bt=>ae({...ge,h:parseFloat(bt.target.value)}),className:"w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"}),a.jsxs("span",{className:"text-xs text-bambu-gray",children:[Math.round(ge.h*100),"%"]})]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:g("printers.roi.instruction")})]}):a.jsxs("p",{className:"text-xs text-bambu-gray",children:["Current: X=",Math.round((Pe.roi?.x||.15)*100),"%, Y=",Math.round((Pe.roi?.y||.35)*100),"%, W=",Math.round((Pe.roi?.w||.7)*100),"%, H=",Math.round((Pe.roi?.h||.55)*100),"%"]})]})]}),a.jsx("div",{className:"flex justify-end gap-2 p-4 border-t border-bambu-dark-tertiary",children:Pe.needs_calibration?a.jsxs(a.Fragment,{children:[a.jsx(Me,{variant:"ghost",onClick:()=>un(),children:g("common.cancel")}),a.jsx(Me,{onClick:()=>Gr(),disabled:q,children:q?a.jsxs(a.Fragment,{children:[a.jsx(at,{className:"w-4 h-4 mr-2 animate-spin"}),"Calibrating..."]}):"Calibrate Empty Plate"})]}):a.jsxs(a.Fragment,{children:[a.jsx(Me,{variant:"ghost",onClick:()=>Gr(),disabled:q,children:q?"Adding...":`Add Reference (${tn?.references.length||0}/${tn?.max_references||5})`}),a.jsx(Me,{onClick:()=>un(),children:"Close"})]})})]})}),z&&mt&&a.jsx(xn,{title:g("printers.confirm.powerOnTitle"),message:g("printers.confirm.powerOnMessage",{name:t.name}),confirmText:g("printers.confirm.powerOnButton"),variant:"default",onConfirm:()=>{tt.mutate("on"),W(!1)},onCancel:()=>W(!1)}),K&&mt&&a.jsx(xn,{title:g("printers.confirm.powerOffTitle"),message:pe?.state==="RUNNING"?g("printers.confirm.powerOffWarning",{name:t.name}):g("printers.confirm.powerOffMessage",{name:t.name}),confirmText:g("printers.confirm.powerOffButton"),variant:"danger",onConfirm:()=>{tt.mutate("off"),te(!1)},onCancel:()=>te(!1)}),Z&&a.jsx(xn,{title:g("printers.confirm.stopTitle"),message:g("printers.confirm.stopMessage",{name:t.name}),confirmText:g("printers.confirm.stopButton"),variant:"danger",onConfirm:()=>{Lt.mutate(),ee(!1)},onCancel:()=>ee(!1)}),Se&&a.jsx(xn,{title:g("printers.confirm.pauseTitle"),message:g("printers.confirm.pauseMessage",{name:t.name}),confirmText:g("printers.confirm.pauseButton"),variant:"default",onConfirm:()=>{ye.mutate(),oe(!1)},onCancel:()=>oe(!1)}),ie&&a.jsx(xn,{title:g("printers.confirm.resumeTitle"),message:g("printers.confirm.resumeMessage",{name:t.name}),confirmText:g("printers.confirm.resumeButton"),variant:"default",onConfirm:()=>{He.mutate(),me(!1)},onCancel:()=>me(!1)}),a.jsx(uL,{printerId:t.id,isOpen:se,onClose:()=>ce(!1)}),H&&a.jsx(GTe,{printerName:t.name,errors:pe?.hms_errors||[],onClose:()=>Y(!1),printerId:t.id,hasPermission:A}),Ce&&a.jsx(a$e,{isOpen:!!Ce,onClose:()=>le(null),printerId:t.id,printerName:t.name,amsId:Ce.amsId,amsLabel:Ce.amsLabel,initialMode:Ce.mode,thresholds:s}),Le&&a.jsx(i$e,{isOpen:!!Le,onClose:()=>V(null),tagUid:Le.tagUid,trayUuid:Le.trayUuid,printerId:Le.printerId,amsId:Le.amsId,trayId:Le.trayId}),X&&a.jsx(s$e,{isOpen:!!X,onClose:()=>fe(null),printerId:X.printerId,amsId:X.amsId,trayId:X.trayId,trayInfo:X.trayInfo}),Q&&a.jsx(wne,{isOpen:!!Q,onClose:()=>re(null),printerId:t.id,slotInfo:Q,printerModel:vR(t.model)||void 0,onSuccess:()=>{y.invalidateQueries({queryKey:["slotPresets",t.id]}),y.invalidateQueries({queryKey:["printerStatus",t.id]})}}),B&&a.jsx(k$e,{printer:t,onClose:()=>L(!1)}),ue&&ve&&a.jsx(C$e,{printer:t,firmwareInfo:ve,onClose:()=>Fe(!1)}),vr&&a.jsx("div",{className:"fixed inset-0 z-40",onClick:()=>Qn(null)})]})}function N$e({onClose:t,onAdd:e,existingSerials:n}){const{t:r}=Rt(),[i,s]=w.useState({name:"",serial_number:"",ip_address:"",access_code:"",model:"",location:"",auto_archive:!0}),[o,l]=w.useState(!1),[c,d]=w.useState([]),[u,h]=w.useState(""),[f,p]=w.useState(!1),[x,v]=w.useState(!1),[g,y]=w.useState([]),[_,N]=w.useState(""),[A,k]=w.useState({scanned:0,total:0});w.useEffect(()=>{hc.getInfo().then(M=>{v(M.is_docker),M.subnets.length>0&&(y(M.subnets),N(M.subnets[0]))}).catch(()=>{})},[]);const P=c.filter(M=>!n.includes(M.serial)),C=async()=>{h(""),d([]),l(!0),p(!1),k({scanned:0,total:0});try{if(x){await hc.startSubnetScan(_);const M=setInterval(async()=>{try{const j=await hc.getScanStatus();k({scanned:j.scanned,total:j.total});const B=await hc.getDiscoveredPrinters();d(B),j.running||(clearInterval(M),l(!1),p(!0))}catch(j){console.error("Failed to get scan status:",j)}},500)}else{await hc.startDiscovery(10);const M=setInterval(async()=>{try{const j=await hc.getDiscoveredPrinters();d(j)}catch(j){console.error("Failed to get discovered printers:",j)}},1e3);setTimeout(async()=>{clearInterval(M);try{await hc.stopDiscovery()}catch{}l(!1),p(!0);try{const j=await hc.getDiscoveredPrinters();d(j)}catch(j){console.error("Failed to get final discovered printers:",j)}},1e4)}}catch(M){console.error("Failed to start discovery:",M),h(M instanceof Error?M.message:r("printers.discovery.failedToStart")),l(!1),p(!0)}},E=M=>{const j=M.serial.startsWith("unknown-")?"":M.serial;s({...i,name:M.name||"",serial_number:j,ip_address:M.ip_address,model:vR(M.model)}),d([])};return w.useEffect(()=>()=>{hc.stopDiscovery().catch(()=>{}),hc.stopSubnetScan().catch(()=>{})},[]),w.useEffect(()=>{const M=j=>{j.key==="Escape"&&t()};return window.addEventListener("keydown",M),()=>window.removeEventListener("keydown",M)},[t]),a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",onClick:t,children:a.jsx(St,{className:"w-full max-w-md",onClick:M=>M.stopPropagation(),children:a.jsxs(Nt,{children:[a.jsx("h2",{className:"text-xl font-semibold mb-4",children:r("printers.addPrinter")}),a.jsxs("div",{className:"mb-4 pb-4 border-b border-bambu-dark-tertiary",children:[x&&a.jsxs("div",{className:"mb-3",children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.discovery.subnetToScan")}),g.length>0?a.jsx("select",{className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none text-sm",value:_,onChange:M=>N(M.target.value),disabled:o,children:g.map(M=>a.jsx("option",{value:M,children:M},M))}):a.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none text-sm",value:_,onChange:M=>N(M.target.value),placeholder:"192.168.1.0/24",disabled:o}),a.jsx("p",{className:"mt-1 text-xs text-bambu-gray",children:r("printers.discovery.dockerNote")})]}),a.jsx(Me,{type:"button",variant:"secondary",onClick:C,disabled:o,className:"w-full",children:o?a.jsxs(a.Fragment,{children:[a.jsx(at,{className:"w-4 h-4 animate-spin"}),x&&A.total>0?r("printers.discovery.scanProgress",{scanned:A.scanned,total:A.total}):r("printers.discovery.scanning")]}):a.jsxs(a.Fragment,{children:[a.jsx(jr,{className:"w-4 h-4"}),r(x?"printers.discovery.scanSubnet":"printers.discovery.discoverNetwork")]})}),u&&a.jsx("div",{className:"mt-2 text-sm text-red-400",children:u}),P.length>0&&a.jsx("div",{className:"mt-3 space-y-2 max-h-40 overflow-y-auto",children:P.map(M=>a.jsxs("div",{className:"flex items-center justify-between p-2 bg-bambu-dark rounded-lg hover:bg-bambu-dark-secondary cursor-pointer transition-colors",onClick:()=>E(M),children:[a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:"font-medium text-white text-sm truncate",children:M.name||M.serial}),a.jsxs("p",{className:"text-xs text-bambu-gray truncate",children:[vR(M.model)||r("printers.discovery.unknown")," • ",M.ip_address,M.serial.startsWith("unknown-")&&a.jsxs("span",{className:"text-yellow-500",children:[" • ",r("printers.discovery.serialRequired")]})]})]}),a.jsx(Mn,{className:"w-4 h-4 text-bambu-gray -rotate-90 flex-shrink-0 ml-2"})]},M.serial))}),o&&a.jsx("p",{className:"mt-2 text-sm text-bambu-gray text-center",children:r(x?"printers.discovery.scanningSubnet":"printers.discovery.scanningNetwork")}),f&&!o&&c.length===0&&a.jsx("p",{className:"mt-2 text-sm text-bambu-gray text-center",children:r(x?"printers.discovery.noPrintersFoundSubnet":"printers.discovery.noPrintersFoundNetwork")}),f&&!o&&c.length>0&&P.length===0&&a.jsx("p",{className:"mt-2 text-sm text-bambu-gray text-center",children:r("printers.discovery.allConfigured")})]}),a.jsxs("form",{onSubmit:M=>{M.preventDefault(),e(i)},className:"space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.name")}),a.jsx("input",{type:"text",required:!0,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:i.name,onChange:M=>s({...i,name:M.target.value}),placeholder:r("printers.modal.myPrinter")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.ipAddress")}),a.jsx("input",{type:"text",required:!0,pattern:"(\\d{1,3}(\\.\\d{1,3}){3}|[a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?(\\.[a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?)*)",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:i.ip_address,onChange:M=>s({...i,ip_address:M.target.value}),placeholder:"192.168.1.100 or printer.local"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.serialNumber")}),a.jsx("input",{type:"text",required:!0,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:i.serial_number,onChange:M=>s({...i,serial_number:M.target.value}),placeholder:"01P00A000000000"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.accessCode")}),a.jsx("input",{type:"password",required:!0,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:i.access_code,onChange:M=>s({...i,access_code:M.target.value}),placeholder:r("printers.modal.fromPrinterSettings")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.modal.modelOptional")}),a.jsxs("select",{className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:i.model||"",onChange:M=>s({...i,model:M.target.value}),children:[a.jsx("option",{value:"",children:r("printers.modal.selectModel")}),a.jsxs("optgroup",{label:"H2 Series",children:[a.jsx("option",{value:"H2C",children:"H2C"}),a.jsx("option",{value:"H2D",children:"H2D"}),a.jsx("option",{value:"H2D Pro",children:"H2D Pro"}),a.jsx("option",{value:"H2S",children:"H2S"})]}),a.jsxs("optgroup",{label:"X1 Series",children:[a.jsx("option",{value:"X1E",children:"X1E"}),a.jsx("option",{value:"X1C",children:"X1 Carbon"}),a.jsx("option",{value:"X1",children:"X1"})]}),a.jsxs("optgroup",{label:"P Series",children:[a.jsx("option",{value:"P2S",children:"P2S"}),a.jsx("option",{value:"P1S",children:"P1S"}),a.jsx("option",{value:"P1P",children:"P1P"})]}),a.jsxs("optgroup",{label:"A1 Series",children:[a.jsx("option",{value:"A1",children:"A1"}),a.jsx("option",{value:"A1 Mini",children:"A1 Mini"})]})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.modal.locationGroup")}),a.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:i.location||"",onChange:M=>s({...i,location:M.target.value}),placeholder:r("printers.modal.locationPlaceholder")}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:r("printers.locationHelp")})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"checkbox",id:"auto_archive",checked:i.auto_archive,onChange:M=>s({...i,auto_archive:M.target.checked}),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),a.jsx("label",{htmlFor:"auto_archive",className:"text-sm text-bambu-gray",children:r("printers.modal.autoArchiveLabel")})]}),a.jsxs("div",{className:"flex gap-3 pt-4",children:[a.jsx(Me,{type:"button",variant:"secondary",onClick:t,className:"flex-1",children:r("common.cancel")}),a.jsx(Me,{type:"submit",className:"flex-1",children:r("printers.addPrinter")})]})]})]})})})}function C$e({printer:t,firmwareInfo:e,onClose:n}){const{t:r}=Rt(),i=Qt(),{showToast:s}=dn(),{hasPermission:o}=Er(),l=o("firmware:update"),[c,d]=w.useState(null),[u,h]=w.useState(!1),[f,p]=w.useState(null),{data:x,isLoading:v}=Ye({queryKey:["firmwarePrepare",t.id],queryFn:()=>B_.prepareUpload(t.id),staleTime:3e4,enabled:e.update_available&&l}),g=it({mutationFn:()=>B_.startUpload(t.id),onSuccess:()=>{h(!0);const _=setInterval(async()=>{try{const N=await B_.getUploadStatus(t.id);d(N),(N.status==="complete"||N.status==="error")&&(clearInterval(_),p(null),h(!1),N.status==="complete"&&(s(r("printers.firmwareModal.uploadedToast"),"success"),i.invalidateQueries({queryKey:["firmwareUpdate",t.id]})))}catch{}},2e3);p(_)},onError:_=>{s(r("printers.firmwareModal.uploadFailed",{error:_.message}),"error"),h(!1)}});w.useEffect(()=>()=>{f&&clearInterval(f)},[f]);const y=()=>{d(null),g.mutate()};return a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",children:a.jsx(St,{className:"w-full max-w-md mx-4",children:a.jsxs(Nt,{children:[a.jsxs("div",{className:"flex items-start gap-3 mb-4",children:[a.jsx("div",{className:`p-2 rounded-full ${e.update_available?"bg-orange-500/20":"bg-status-ok/20"}`,children:e.update_available?a.jsx(ga,{className:"w-5 h-5 text-orange-400"}):a.jsx(yr,{className:"w-5 h-5 text-status-ok"})}),a.jsxs("div",{className:"flex-1",children:[a.jsx("h3",{className:"text-lg font-semibold text-white",children:e.update_available?r("printers.firmwareModal.title"):r("printers.firmwareModal.titleUpToDate")}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:t.name})]})]}),a.jsxs("div",{className:"bg-bambu-dark rounded-lg p-3 mb-4",children:[a.jsxs("div",{className:"flex justify-between items-center text-sm",children:[a.jsx("span",{className:"text-bambu-gray",children:r("printers.firmwareModal.currentVersion")}),a.jsx("span",{className:`font-mono ${e.update_available?"text-white":"text-status-ok"}`,children:e.current_version||r("common.unknown")})]}),e.update_available&&a.jsxs("div",{className:"flex justify-between items-center text-sm mt-1",children:[a.jsx("span",{className:"text-bambu-gray",children:r("printers.firmwareModal.latestVersion")}),a.jsx("span",{className:"text-orange-400 font-mono",children:e.latest_version})]}),e.release_notes&&a.jsxs("details",{className:"mt-3 text-sm",open:!e.update_available,children:[a.jsx("summary",{className:`cursor-pointer hover:underline ${e.update_available?"text-orange-400":"text-status-ok"}`,children:r("printers.firmwareModal.releaseNotes")}),a.jsx("div",{className:"mt-2 text-bambu-gray text-xs max-h-40 overflow-y-auto whitespace-pre-wrap",children:e.release_notes})]})]}),e.update_available?v?a.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray text-sm mb-4",children:[a.jsx(at,{className:"w-4 h-4 animate-spin"}),r("printers.firmwareModal.checkingPrereqs")]}):x&&!u&&!c?a.jsx("div",{className:"mb-4",children:x.can_proceed?a.jsxs("div",{className:"flex items-center gap-2 text-bambu-green text-sm",children:[a.jsx(ei,{className:"w-4 h-4"}),r("printers.firmwareModal.sdCardReady")]}):a.jsx("div",{className:"space-y-1",children:x.errors.map((_,N)=>a.jsxs("div",{className:"flex items-center gap-2 text-red-400 text-sm",children:[a.jsx(Va,{className:"w-4 h-4 flex-shrink-0"}),_]},N))})}):null:null,(u||c)&&c&&a.jsxs("div",{className:"mb-4",children:[a.jsxs("div",{className:"flex items-center justify-between text-sm mb-1",children:[a.jsx("span",{className:"text-bambu-gray capitalize",children:c.status}),a.jsxs("span",{className:"text-white",children:[c.progress,"%"]})]}),a.jsx("div",{className:"w-full bg-bambu-dark-tertiary rounded-full h-2",children:a.jsx("div",{className:`h-2 rounded-full transition-all ${c.status==="error"?"bg-status-error":c.status==="complete"?"bg-status-ok":"bg-orange-500"} ${c.status==="uploading"?"animate-pulse":""}`,style:{width:`${c.progress}%`}})}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:c.message}),c.error&&a.jsx("p",{className:"text-xs text-red-400 mt-1",children:c.error})]}),c?.status==="complete"&&a.jsxs("div",{className:"bg-bambu-green/10 border border-bambu-green/30 rounded-lg p-3 mb-4",children:[a.jsx("p",{className:"text-sm text-bambu-green font-medium mb-2",children:r("printers.firmwareModal.uploadedSuccess")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:r("printers.firmwareModal.applyInstructions")}),a.jsxs("ol",{className:"text-xs text-bambu-gray mt-1 list-decimal list-inside space-y-1",children:[a.jsx("li",{dangerouslySetInnerHTML:{__html:r("printers.firmwareModal.step1")}}),a.jsx("li",{dangerouslySetInnerHTML:{__html:r("printers.firmwareModal.step2")}}),a.jsx("li",{dangerouslySetInnerHTML:{__html:r("printers.firmwareModal.step3")}}),a.jsx("li",{children:r("printers.firmwareModal.step4")})]})]}),a.jsxs("div",{className:"flex gap-2 justify-end",children:[a.jsx(Me,{variant:"secondary",onClick:n,children:c?.status==="complete"?r("printers.firmwareModal.done"):r("common.cancel")}),x?.can_proceed&&!u&&c?.status!=="complete"&&l&&a.jsx(Me,{onClick:y,disabled:g.isPending,children:g.isPending?a.jsxs(a.Fragment,{children:[a.jsx(at,{className:"w-4 h-4 animate-spin mr-2"}),r("printers.firmwareModal.starting")]}):a.jsxs(a.Fragment,{children:[a.jsx(ga,{className:"w-4 h-4 mr-2"}),r("printers.firmwareModal.uploadFirmware")]})})]})]})})})}function k$e({printer:t,onClose:e}){const{t:n}=Rt(),r=Qt(),{showToast:i}=dn(),[s,o]=w.useState({name:t.name,ip_address:t.ip_address,access_code:"",model:t.model||"",location:t.location||"",auto_archive:t.auto_archive}),l=it({mutationFn:d=>J.updatePrinter(t.id,d),onSuccess:()=>{r.invalidateQueries({queryKey:["printers"]}),r.invalidateQueries({queryKey:["printerStatus",t.id]}),e()},onError:d=>i(d.message||n("printers.toast.failedToUpdate"),"error")});w.useEffect(()=>{const d=u=>{u.key==="Escape"&&e()};return window.addEventListener("keydown",d),()=>window.removeEventListener("keydown",d)},[e]);const c=d=>{d.preventDefault();const u={name:s.name,ip_address:s.ip_address,model:s.model||void 0,location:s.location||void 0,auto_archive:s.auto_archive};s.access_code&&(u.access_code=s.access_code),l.mutate(u)};return a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",onClick:e,children:a.jsx(St,{className:"w-full max-w-md",onClick:d=>d.stopPropagation(),children:a.jsxs(Nt,{children:[a.jsx("h2",{className:"text-xl font-semibold mb-4",children:n("printers.editPrinter")}),a.jsxs("form",{onSubmit:c,className:"space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.name")}),a.jsx("input",{type:"text",required:!0,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:s.name,onChange:d=>o({...s,name:d.target.value}),placeholder:n("printers.modal.myPrinter")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.ipAddress")}),a.jsx("input",{type:"text",required:!0,pattern:"(\\d{1,3}(\\.\\d{1,3}){3}|[a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?(\\.[a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?)*)",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:s.ip_address,onChange:d=>o({...s,ip_address:d.target.value}),placeholder:"192.168.1.100 or printer.local"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.serialNumber")}),a.jsx("input",{type:"text",disabled:!0,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray cursor-not-allowed",value:t.serial_number}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:n("printers.serialCannotBeChanged")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.accessCode")}),a.jsx("input",{type:"password",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:s.access_code,onChange:d=>o({...s,access_code:d.target.value}),placeholder:n("printers.accessCodePlaceholder")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.model")}),a.jsxs("select",{className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:s.model,onChange:d=>o({...s,model:d.target.value}),children:[a.jsx("option",{value:"",children:n("printers.modal.selectModel")}),a.jsxs("optgroup",{label:"H2 Series",children:[a.jsx("option",{value:"H2C",children:"H2C"}),a.jsx("option",{value:"H2D",children:"H2D"}),a.jsx("option",{value:"H2D Pro",children:"H2D Pro"}),a.jsx("option",{value:"H2S",children:"H2S"})]}),a.jsxs("optgroup",{label:"X1 Series",children:[a.jsx("option",{value:"X1E",children:"X1E"}),a.jsx("option",{value:"X1C",children:"X1 Carbon"}),a.jsx("option",{value:"X1",children:"X1"})]}),a.jsxs("optgroup",{label:"P Series",children:[a.jsx("option",{value:"P2S",children:"P2S"}),a.jsx("option",{value:"P1S",children:"P1S"}),a.jsx("option",{value:"P1P",children:"P1P"})]}),a.jsxs("optgroup",{label:"A1 Series",children:[a.jsx("option",{value:"A1",children:"A1"}),a.jsx("option",{value:"A1 Mini",children:"A1 Mini"})]})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Location / Group"}),a.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:s.location,onChange:d=>o({...s,location:d.target.value}),placeholder:n("printers.modal.locationPlaceholder")}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:n("printers.locationHelp")})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"checkbox",id:"edit_auto_archive",checked:s.auto_archive,onChange:d=>o({...s,auto_archive:d.target.checked}),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),a.jsx("label",{htmlFor:"edit_auto_archive",className:"text-sm text-bambu-gray",children:n("printers.modal.autoArchiveLabel")})]}),a.jsxs("div",{className:"flex gap-3 pt-4",children:[a.jsx(Me,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:n("common.cancel")}),a.jsx(Me,{type:"submit",className:"flex-1",disabled:l.isPending,children:l.isPending?n("common.saving"):n("printers.modal.saveChanges")})]})]})]})})})}function A$e(t){const{data:e}=Ye({queryKey:["printerStatus",t],queryFn:()=>J.getPrinterStatus(t),refetchInterval:3e4});return!e?.connected}function T$e({printer:t,plug:e,onPowerOn:n,isPowering:r}){const i=A$e(t.id),{data:s}=Ye({queryKey:["smartPlugStatus",e.id],queryFn:()=>J.getSmartPlugStatus(e.id),refetchInterval:1e4});return i?a.jsxs("div",{className:"flex items-center justify-between px-3 py-2 hover:bg-gray-100 dark:hover:bg-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[a.jsx("span",{className:"text-sm text-gray-900 dark:text-white truncate",children:t.name}),s&&a.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded ${s.state==="ON"?"bg-bambu-green/20 text-bambu-green":"bg-red-500/20 text-red-400"}`,children:s.state||"?"})]}),a.jsxs("button",{onClick:()=>n(e.id),disabled:r||s?.state==="ON",className:`px-2 py-1 text-xs rounded transition-colors flex items-center gap-1 ${s?.state==="ON"?"bg-bambu-green/20 text-bambu-green cursor-default":"bg-bambu-green/20 text-bambu-green hover:bg-bambu-green hover:text-white"}`,children:[a.jsx(fu,{className:"w-3 h-3"}),r?"...":"On"]})]}):null}function M$e(){const{t}=Rt(),[e,n]=w.useState(!1),[r,i]=w.useState(()=>localStorage.getItem("hideDisconnectedPrinters")==="true"),[s,o]=w.useState(!1),[l,c]=w.useState(null),[d,u]=w.useState(()=>localStorage.getItem("printerSortBy")||"name"),[h,f]=w.useState(()=>localStorage.getItem("printerSortAsc")!=="false"),[p,x]=w.useState(()=>{const ce=localStorage.getItem("printerCardSize");return ce?parseInt(ce,10):2}),v=p===1?"compact":"expanded",g=Qt(),{showToast:y}=dn(),{hasPermission:_}=Er(),[N,A]=w.useState(()=>{const ce=localStorage.getItem("openEmbeddedCameras");if(ce)try{const Ce=JSON.parse(ce);return new Map(Ce.map(le=>[le.id,le]))}catch{return new Map}return new Map});w.useEffect(()=>{const ce=Array.from(N.values());ce.length>0?localStorage.setItem("openEmbeddedCameras",JSON.stringify(ce)):localStorage.removeItem("openEmbeddedCameras")},[N]);const{data:k,isLoading:P}=Ye({queryKey:["printers"],queryFn:J.getPrinters}),{data:C}=Ye({queryKey:["settings"],queryFn:J.getSettings});w.useEffect(()=>{C?.camera_view_mode==="window"&&N.size>0&&A(new Map)},[C?.camera_view_mode,N.size]);const{data:E}=Ye({queryKey:["smart-plugs"],queryFn:J.getSmartPlugs}),{data:M}=Ye({queryKey:["maintenanceOverview"],queryFn:J.getMaintenanceOverview,staleTime:60*1e3}),{data:j}=Ye({queryKey:["spoolman-status"],queryFn:J.getSpoolmanStatus,staleTime:60*1e3}),B=j?.enabled&&j?.connected,{data:L}=Ye({queryKey:["unlinked-spools"],queryFn:J.getUnlinkedSpools,enabled:!!B,staleTime:30*1e3}),U=L&&L.length>0,{data:D}=Ye({queryKey:["linked-spools"],queryFn:J.getLinkedSpools,enabled:!!B,staleTime:30*1e3}),$=D?.linked,{data:G}=Ye({queryKey:["spool-assignments"],queryFn:()=>J.getAssignments(),staleTime:30*1e3}),z=it({mutationFn:({printerId:ce,amsId:Ce,trayId:le})=>J.unassignSpool(ce,Ce,le),onSuccess:()=>{g.invalidateQueries({queryKey:["spool-assignments"]})}}),W=(ce,Ce,le)=>G?.find(Le=>Le.printer_id===ce&&Le.ams_id===Number(Ce)&&Le.tray_id===Number(le)),K=M?.reduce((ce,Ce)=>(ce[Ce.printer_id]={due_count:Ce.due_count,warning_count:Ce.warning_count,total_print_hours:Ce.total_print_hours},ce),{})||{},te=E?.reduce((ce,Ce)=>(Ce.printer_id&&(ce[Ce.printer_id]=Ce),ce),{})||{},H=it({mutationFn:J.createPrinter,onSuccess:()=>{g.invalidateQueries({queryKey:["printers"]}),g.invalidateQueries({queryKey:["maintenanceOverview"]}),n(!1)},onError:ce=>y(ce.message||t("printers.toast.failedToAdd"),"error")}),Y=it({mutationFn:ce=>J.controlSmartPlug(ce,"on"),onSuccess:()=>{g.invalidateQueries({queryKey:["smart-plugs"]}),c(null)},onError:()=>{c(null)}}),Z=()=>{const ce=!r;i(ce),localStorage.setItem("hideDisconnectedPrinters",String(ce))},ee=ce=>{u(ce),localStorage.setItem("printerSortBy",ce)},Se=()=>{const ce=!h;f(ce),localStorage.setItem("printerSortAsc",String(ce))},oe=()=>{switch(p){case 1:return"grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5";case 2:return"grid-cols-1 md:grid-cols-2 xl:grid-cols-3";case 3:return"grid-cols-1 lg:grid-cols-2";case 4:return"grid-cols-1";default:return"grid-cols-1 md:grid-cols-2 xl:grid-cols-3"}},ie=["S","M","L","XL"],me=w.useMemo(()=>{if(!k)return[];const ce=[...k];switch(d){case"name":ce.sort((Ce,le)=>Ce.name.localeCompare(le.name));break;case"model":ce.sort((Ce,le)=>(Ce.model||"").localeCompare(le.model||""));break;case"location":ce.sort((Ce,le)=>{const Le=Ce.location||"",V=le.location||"";return!Le&&V?1:Le&&!V?-1:Le.localeCompare(V)||Ce.name.localeCompare(le.name)});break;case"status":ce.sort((Ce,le)=>{const Le=g.getQueryData(["printerStatus",Ce.id]),V=g.getQueryData(["printerStatus",le.id]),X=fe=>fe?.connected?fe.state==="RUNNING"?0:1:2;return X(Le)-X(V)});break}return h||ce.reverse(),ce},[k,d,h,g]),se=w.useMemo(()=>{if(d!=="location")return null;const ce={};return me.forEach(Ce=>{const le=Ce.location||"Ungrouped";ce[le]||(ce[le]=[]),ce[le].push(Ce)}),ce},[d,me]);return a.jsxs("div",{className:"p-4 md:p-8",children:[a.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-6",children:[a.jsxs("div",{children:[a.jsx("h1",{className:"text-2xl font-bold text-white",children:t("printers.title")}),a.jsx(_$e,{printers:k})]}),a.jsxs("div",{className:"flex items-center gap-2 sm:gap-3 flex-wrap",children:[a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsxs("select",{value:d,onChange:ce=>ee(ce.target.value),className:"text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg px-2 py-1.5 text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"name",children:t("printers.sort.name")}),a.jsx("option",{value:"status",children:t("printers.sort.status")}),a.jsx("option",{value:"model",children:t("printers.sort.model")}),a.jsx("option",{value:"location",children:t("printers.sort.location")})]}),a.jsx("button",{onClick:Se,className:"p-1.5 rounded-lg hover:bg-bambu-dark-tertiary transition-colors",title:t(h?"printers.sort.descending":"printers.sort.ascending"),children:h?a.jsx(Mf,{className:"w-4 h-4 text-bambu-gray"}):a.jsx(cb,{className:"w-4 h-4 text-bambu-gray"})})]}),a.jsx("div",{className:"flex items-center bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:ie.map((ce,Ce)=>{const le=Ce+1,Le=p===le;return a.jsx("button",{onClick:()=>{x(le),localStorage.setItem("printerCardSize",String(le))},className:`px-2 py-1.5 text-xs font-medium transition-colors ${Ce===0?"rounded-l-lg":""} ${Ce===ie.length-1?"rounded-r-lg":""} ${Le?"bg-bambu-green text-white":"text-bambu-gray hover:bg-bambu-dark-tertiary hover:text-white"}`,title:t(ce==="S"?"printers.cardSize.small":ce==="M"?"printers.cardSize.medium":ce==="L"?"printers.cardSize.large":"printers.cardSize.extraLarge"),children:ce},ce)})}),a.jsx("div",{className:"w-px h-6 bg-bambu-dark-tertiary"}),a.jsxs("label",{className:"flex items-center gap-2 text-sm text-bambu-gray cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:r,onChange:Z,className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),t("printers.hideOffline")]}),r&&Object.keys(te).length>0&&a.jsxs("div",{className:"relative",children:[a.jsxs("button",{onClick:()=>o(!s),className:"flex items-center gap-1.5 px-3 py-1.5 text-sm bg-white dark:bg-bambu-dark-secondary border border-gray-200 dark:border-bambu-dark-tertiary rounded-lg text-gray-600 dark:text-bambu-gray hover:text-gray-900 dark:hover:text-white hover:border-bambu-green transition-colors",children:[a.jsx(fu,{className:"w-4 h-4"}),t("printers.powerOn"),a.jsx(Mn,{className:`w-3 h-3 transition-transform ${s?"rotate-180":""}`})]}),s&&a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>o(!1)}),a.jsxs("div",{className:"absolute right-0 mt-2 w-56 bg-white dark:bg-bambu-dark-secondary border border-gray-200 dark:border-bambu-dark-tertiary rounded-lg shadow-lg z-20 py-1",children:[a.jsx("div",{className:"px-3 py-2 text-xs text-gray-500 dark:text-bambu-gray border-b border-gray-200 dark:border-bambu-dark-tertiary",children:t("printers.offlinePrintersWithPlugs")}),k?.filter(ce=>te[ce.id]).map(ce=>a.jsx(T$e,{printer:ce,plug:te[ce.id],onPowerOn:Ce=>{c(Ce),Y.mutate(Ce)},isPowering:l===te[ce.id]?.id},ce.id)),k?.filter(ce=>te[ce.id]).length===0&&a.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:"No printers with smart plugs"})]})]})]}),a.jsxs(Me,{onClick:()=>n(!0),disabled:!_("printers:create"),title:_("printers:create")?void 0:t("printers.permission.noAdd"),children:[a.jsx(Xn,{className:"w-4 h-4"}),t("printers.addPrinter")]})]})]}),P?a.jsx("div",{className:"text-center py-12 text-bambu-gray",children:t("common.loading")}):k?.length===0?a.jsx(St,{children:a.jsxs(Nt,{className:"text-center py-12",children:[a.jsx("p",{className:"text-bambu-gray mb-4",children:t("printers.noPrintersConfigured")}),a.jsxs(Me,{onClick:()=>n(!0),disabled:!_("printers:create"),title:_("printers:create")?void 0:t("printers.permission.noAdd"),children:[a.jsx(Xn,{className:"w-4 h-4"}),t("printers.addPrinter")]})]})}):se?a.jsx("div",{className:"space-y-6",children:Object.entries(se).map(([ce,Ce])=>a.jsxs("div",{children:[a.jsxs("h2",{className:"text-lg font-semibold text-white mb-3 flex items-center gap-2",children:[a.jsx("span",{className:"w-2 h-2 rounded-full bg-bambu-green"}),ce,a.jsxs("span",{className:"text-sm font-normal text-bambu-gray",children:["(",Ce.length,")"]})]}),a.jsx("div",{className:`grid gap-4 ${p>=3?"gap-6":""} ${oe()}`,children:Ce.map(le=>a.jsx(u9,{printer:le,hideIfDisconnected:r,maintenanceInfo:K[le.id],viewMode:v,cardSize:p,amsThresholds:C?{humidityGood:Number(C.ams_humidity_good)||40,humidityFair:Number(C.ams_humidity_fair)||60,tempGood:Number(C.ams_temp_good)||28,tempFair:Number(C.ams_temp_fair)||35}:void 0,spoolmanEnabled:B,hasUnlinkedSpools:U,linkedSpools:$,spoolmanUrl:j?.url,onGetAssignment:W,onUnassignSpool:(Le,V,X)=>z.mutate({printerId:Le,amsId:V,trayId:X}),timeFormat:C?.time_format||"system",cameraViewMode:C?.camera_view_mode||"window",onOpenEmbeddedCamera:(Le,V)=>A(X=>new Map(X).set(Le,{id:Le,name:V})),checkPrinterFirmware:C?.check_printer_firmware!==!1},le.id))})]},ce))}):a.jsx("div",{className:`grid gap-4 ${p>=3?"gap-6":""} ${oe()}`,children:me.map(ce=>a.jsx(u9,{printer:ce,hideIfDisconnected:r,maintenanceInfo:K[ce.id],viewMode:v,cardSize:p,spoolmanEnabled:B,hasUnlinkedSpools:U,linkedSpools:$,spoolmanUrl:j?.url,onGetAssignment:W,onUnassignSpool:(Ce,le,Le)=>z.mutate({printerId:Ce,amsId:le,trayId:Le}),amsThresholds:C?{humidityGood:Number(C.ams_humidity_good)||40,humidityFair:Number(C.ams_humidity_fair)||60,tempGood:Number(C.ams_temp_good)||28,tempFair:Number(C.ams_temp_fair)||35}:void 0,timeFormat:C?.time_format||"system",cameraViewMode:C?.camera_view_mode||"window",onOpenEmbeddedCamera:(Ce,le)=>A(Le=>new Map(Le).set(Ce,{id:Ce,name:le})),checkPrinterFirmware:C?.check_printer_firmware!==!1},ce.id))}),e&&a.jsx(N$e,{onClose:()=>n(!1),onAdd:ce=>H.mutate(ce),existingSerials:k?.map(ce=>ce.serial_number)||[]}),Array.from(N.values()).map((ce,Ce)=>a.jsx(BTe,{printerId:ce.id,printerName:ce.name,viewerIndex:Ce,onClose:()=>A(le=>{const Le=new Map(le);return Le.delete(ce.id),Le})},ce.id))]})}function P$e(){const t=navigator.userAgent.toLowerCase(),e=navigator.platform?.toLowerCase()||"";return t.includes("win")||e.includes("win")?"windows":t.includes("mac")||e.includes("mac")?"macos":t.includes("linux")||e.includes("linux")?"linux":"unknown"}function of(t,e="bambu_studio"){let n;e==="orcaslicer"?n=`orcaslicer://open?file=${t}`:P$e()==="macos"?n=`bambustudioopen://${encodeURIComponent(t)}`:n=`bambustudio://open?file=${t}`;const r=document.createElement("a");r.href=n,r.style.display="none",document.body.appendChild(r),r.click(),document.body.removeChild(r)}const j$e={USD:"$",EUR:"€",GBP:"£",CHF:"Fr.",JPY:"¥",CNY:"¥",CAD:"$",AUD:"$",INR:"₹",HKD:"HK$",KRW:"₩",SEK:"kr",NOK:"kr",DKK:"kr",PLN:"zł",BRL:"R$",TWD:"NT$",SGD:"S$",NZD:"NZ$",MXN:"MX$",CZK:"Kč",THB:"฿",ZAR:"R",TRY:"₺",RUB:"₽"};function il(t){return j$e[t.toUpperCase()]||t}const E$e=[{code:"USD",label:"USD ($)"},{code:"EUR",label:"EUR (€)"},{code:"GBP",label:"GBP (£)"},{code:"CHF",label:"CHF (Fr.)"},{code:"JPY",label:"JPY (¥)"},{code:"CNY",label:"CNY (¥)"},{code:"CAD",label:"CAD ($)"},{code:"AUD",label:"AUD ($)"},{code:"INR",label:"INR (₹)"},{code:"HKD",label:"HKD (HK$)"},{code:"KRW",label:"KRW (₩)"},{code:"SEK",label:"SEK (kr)"},{code:"NOK",label:"NOK (kr)"},{code:"DKK",label:"DKK (kr)"},{code:"PLN",label:"PLN (zł)"},{code:"BRL",label:"BRL (R$)"},{code:"TWD",label:"TWD (NT$)"},{code:"SGD",label:"SGD (S$)"},{code:"NZD",label:"NZD (NZ$)"},{code:"MXN",label:"MXN (MX$)"},{code:"CZK",label:"CZK (Kč)"},{code:"THB",label:"THB (฿)"},{code:"ZAR",label:"ZAR (R)"},{code:"TRY",label:"TRY (₺)"},{code:"RUB",label:"RUB (₽)"}],h9=768;function Cne(){const[t,e]=w.useState(()=>typeof window<"u"?window.innerWidth{const n=window.matchMedia(`(max-width: ${h9-1}px)`),r=i=>{e(i.matches)};return e(n.matches),n.addEventListener("change",r),()=>n.removeEventListener("change",r)},[]),t}function bO({archiveId:t,libraryFileId:e,title:n,fileType:r,onClose:i}){const{t:s}=Rt(),{data:o}=Ye({queryKey:["settings"],queryFn:J.getSettings}),l=o?.preferred_slicer||"bambu_studio",c=e!=null,[d,u]=w.useState(null),[h,f]=w.useState(null),[p,x]=w.useState(!0),[v,g]=w.useState(null),[y,_]=w.useState(!1),[N,A]=w.useState(null),[k,P]=w.useState(0),[C,E]=w.useState(!1),[M,j]=w.useState(null),[B,L]=w.useState(!1),[U,D]=w.useState(!1),$=w.useRef(null),G=w.useRef(null),z=10,W=160,K=240,te=.35;w.useEffect(()=>{const Pe=be=>{be.key==="Escape"&&i()};return window.addEventListener("keydown",Pe),()=>window.removeEventListener("keydown",Pe)},[i]),w.useEffect(()=>{if(x(!0),c){const Pe=(r||"").toLowerCase(),be=Pe==="3mf"||Pe==="stl",O=Pe==="gcode"||Pe==="3mf";f({has_model:be,has_gcode:O,has_source:!1,build_volume:{x:256,y:256,z:256},filament_colors:[]}),u(be?"3d":O?"gcode":null),x(!1);return}if(!t){f(null),u(null),x(!1);return}J.getArchiveCapabilities(t).then(Pe=>{f(Pe),Pe.has_model?u("3d"):Pe.has_gcode&&u("gcode"),x(!1)}).catch(()=>{f({has_model:!0,has_gcode:!1,has_source:!1,build_volume:{x:256,y:256,z:256},filament_colors:[]}),u("3d"),x(!1)})},[t,r,c]),w.useEffect(()=>{if(_(!0),A(null),P(0),c){const Pe=(r||"").toLowerCase();if(!e||Pe!=="3mf"){g(null),_(!1);return}J.getLibraryFilePlates(e).then(be=>g(be)).catch(()=>g(null)).finally(()=>_(!1));return}if(!t){g(null),_(!1);return}J.getArchivePlates(t).then(Pe=>g(Pe)).catch(()=>g(null)).finally(()=>_(!1))},[t,r,c,e]);const H=w.useMemo(()=>v?.plates??[],[v]),Y=(v?.is_multi_plate??!1)&&H.length>1,Z=C&&Y,ee=N==null?null:H.find(Pe=>Pe.index===N)??null,Se=Pe=>Pe.object_count??Pe.objects?.length??0,oe=H.reduce((Pe,be)=>Pe+Se(be),0),ie=ee?Se(ee):oe,me=ee?s("modelViewer.plateNumber",{number:ee.index}):s("modelViewer.allPlates"),se=H.length>0,ce=w.useRef(null),Ce=w.useRef(null),[le,Le]=w.useState(10),[V,X]=w.useState(3),fe=H.length>le,Q=Math.max(1,Math.ceil(H.length/le)),re=fe?H.slice(k*le,(k+1)*le):H;w.useEffect(()=>{if(!Z){Le(10),X(3);return}const Pe=ce.current,be=Ce.current;if(!Pe||!be)return;let O=0;const R=()=>{const ge=be.clientWidth,Ue=Math.floor(ge/210),ze=Math.max(3,Math.min(5,Ue||3));X(ke=>ke===ze?ke:ze);const $e=window.getComputedStyle(Pe),Re=Number.parseFloat($e.rowGap||"0"),ve=Pe.querySelector("button")?.getBoundingClientRect().height??44,Ne=be.clientHeight,we=Math.max(1,Math.floor((Ne+Re)/(ve+Re)))*ze,qe=Math.max(1,we-1);Le(ke=>ke===qe?ke:qe)},q=()=>{O&&cancelAnimationFrame(O),O=requestAnimationFrame(R)};q();const de=new ResizeObserver(q);return de.observe(be),de.observe(Pe),()=>{O&&cancelAnimationFrame(O),de.disconnect()}},[Z,H.length]),w.useEffect(()=>{if(!fe){P(0);return}P(Pe=>Math.min(Pe,Q-1))},[H.length,fe,Q]),w.useEffect(()=>{if(!fe||N==null)return;const Pe=H.findIndex(O=>O.index===N);if(Pe<0)return;const be=Math.floor(Pe/le);P(O=>O===be?O:be)},[H,le,N,fe]),w.useEffect(()=>{if(!Z){j(null),D(!1);return}if(U)return;const Pe=$.current,be=G.current;if(!Pe||!be)return;const O=Pe.clientHeight;if(!O)return;const R=Math.max(K,O*te),q=Math.max(W,O-z-R),de=Math.min(be.scrollHeight,q);j(Math.max(W,de))},[Z,U,H.length,k,z,W,K,te]),w.useEffect(()=>{if(!B)return;const Pe=O=>{const R=$.current;if(!R)return;const q=R.getBoundingClientRect(),de=q.height;if(!de)return;const ge=Math.max(K,de*te),ae=Math.max(W,de-z-ge),Ue=Math.min(ae,Math.max(W,O.clientY-q.top));j(Ue)},be=()=>{L(!1),D(!0)};return document.addEventListener("mousemove",Pe),document.addEventListener("mouseup",be),document.body.style.cursor="row-resize",document.body.style.userSelect="none",()=>{document.removeEventListener("mousemove",Pe),document.removeEventListener("mouseup",be),document.body.style.cursor="",document.body.style.userSelect=""}},[B,z,W,K,te]);const ue=c?(r||"").toLowerCase()==="3mf":!0,Fe=async()=>{if(!ue)return;const Pe=n||"model";try{if(c){const{token:be}=await J.createLibrarySlicerToken(e),O=J.getLibrarySlicerDownloadUrl(e,be,Pe);of(`${window.location.origin}${O}`,l)}else{const{token:be}=await J.createArchiveSlicerToken(t),O=J.getArchiveSlicerDownloadUrl(t,be,Pe);of(`${window.location.origin}${O}`,l)}}catch{if(c){const be=`${window.location.origin}${J.getLibraryFileDownloadUrl(e)}`;of(be,l)}else{const be=`${window.location.origin}${J.getArchiveForSlicer(t,Pe)}`;of(be,l)}}};return a.jsx("div",{className:`fixed inset-0 bg-black/70 flex items-center justify-center z-50 ${C?"p-0":"p-8"}`,onClick:i,children:a.jsxs("div",{className:`bg-bambu-dark-secondary border border-bambu-dark-tertiary w-full flex flex-col ${C?"h-full max-w-none rounded-none":"h-[80vh] max-w-4xl rounded-xl"}`,onClick:Pe=>Pe.stopPropagation(),children:[a.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-1 mr-4",children:[a.jsx("h2",{className:"text-lg font-semibold text-white truncate",children:n}),se&&a.jsxs("span",{className:"text-xs text-bambu-gray bg-bambu-dark-tertiary/70 px-2 py-1 rounded whitespace-nowrap",children:[me,": ",s("modelViewer.objectCount",{count:ie})]})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs(Me,{variant:"secondary",size:"sm",onClick:Fe,disabled:!ue,children:[a.jsx(na,{className:"w-4 h-4"}),s("modelViewer.openInSlicer")]}),a.jsx(Me,{variant:"secondary",size:"sm",onClick:()=>E(Pe=>!Pe),title:C?"Exit fullscreen":"Enter fullscreen",children:C?a.jsx(TF,{className:"w-4 h-4"}):a.jsx(WC,{className:"w-4 h-4"})}),a.jsx(Me,{variant:"ghost",size:"sm",onClick:i,children:a.jsx(Dt,{className:"w-5 h-5"})})]})]}),h&&a.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary",children:[a.jsxs("button",{onClick:()=>h.has_model&&u("3d"),disabled:!h.has_model,className:`flex items-center gap-2 px-6 py-3 text-sm font-medium transition-colors ${d==="3d"?"text-bambu-green border-b-2 border-bambu-green":h.has_model?"text-bambu-gray hover:text-white":"text-bambu-gray/30 cursor-not-allowed"}`,children:[a.jsx(ei,{className:"w-4 h-4"}),s("modelViewer.tabs.model"),!h.has_model&&a.jsxs("span",{className:"text-xs",children:["(",s("modelViewer.notAvailable"),")"]})]}),a.jsxs("button",{onClick:()=>h.has_gcode&&u("gcode"),disabled:!h.has_gcode,className:`flex items-center gap-2 px-6 py-3 text-sm font-medium transition-colors ${d==="gcode"?"text-bambu-green border-b-2 border-bambu-green":h.has_gcode?"text-bambu-gray hover:text-white":"text-bambu-gray/30 cursor-not-allowed"}`,children:[a.jsx($he,{className:"w-4 h-4"}),s("modelViewer.tabs.gcode"),!h.has_gcode&&a.jsxs("span",{className:"text-xs",children:["(",s("modelViewer.notSliced"),")"]})]})]}),a.jsx("div",{className:"flex-1 overflow-hidden p-4",children:p?a.jsx("div",{className:"w-full h-full flex items-center justify-center",children:a.jsx(at,{className:"w-8 h-8 animate-spin text-bambu-green"})}):d==="3d"&&h?a.jsxs("div",{ref:$,className:`w-full h-full flex flex-col ${Z?"gap-0 min-h-0":"gap-3"}`,children:[Y&&a.jsxs("div",{ref:G,style:Z&&M!=null?{height:M}:void 0,className:`rounded-lg border border-bambu-dark-tertiary bg-bambu-dark p-3 ${Z?"flex flex-col shrink-0":""}`,children:[a.jsxs("div",{className:"flex items-center gap-2 text-sm text-bambu-gray mb-2",children:[a.jsx(ri,{className:"w-4 h-4"}),s("modelViewer.plates"),y&&a.jsx(at,{className:"w-3 h-3 animate-spin"})]}),a.jsxs("div",{className:Z?"flex flex-col min-h-0 flex-1":void 0,children:[a.jsx("div",{ref:Ce,className:Z?"min-h-0 overflow-hidden pr-1 flex-1":void 0,children:a.jsxs("div",{ref:ce,className:Z?"grid gap-2":"grid grid-cols-2 md:grid-cols-3 gap-2",style:Z?{gridTemplateColumns:`repeat(${V}, minmax(0, 1fr))`}:void 0,children:[a.jsxs("button",{type:"button",onClick:()=>A(null),className:`flex items-center rounded-lg border text-left transition-colors ${Z?"gap-1.5 p-1.5 w-full":"gap-2 p-2"} ${N==null?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark-secondary hover:border-bambu-gray"}`,children:[a.jsx("div",{className:`rounded bg-bambu-dark-tertiary flex items-center justify-center ${Z?"w-8 h-8":"w-10 h-10"}`,children:a.jsx(ri,{className:`${Z?"w-4 h-4":"w-5 h-5"} text-bambu-gray`})}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:`${Z?"text-xs":"text-sm"} text-white font-medium truncate`,children:s("modelViewer.allPlates")}),a.jsx("p",{className:`${Z?"text-[10px]":"text-xs"} text-bambu-gray truncate`,children:s("modelViewer.plateCount",{count:H.length})})]}),N==null&&a.jsx(Vr,{className:`${Z?"w-3.5 h-3.5":"w-4 h-4"} text-bambu-green flex-shrink-0`})]}),re.map(Pe=>a.jsxs("button",{type:"button",onClick:()=>A(Pe.index),className:`flex items-center rounded-lg border text-left transition-colors ${Z?"gap-1.5 p-1.5 w-full":"gap-2 p-2"} ${N===Pe.index?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark-secondary hover:border-bambu-gray"}`,children:[Pe.has_thumbnail&&Pe.thumbnail_url?a.jsx("img",{src:Pe.thumbnail_url,alt:`Plate ${Pe.index}`,className:`${Z?"w-8 h-8":"w-10 h-10"} rounded object-cover bg-bambu-dark-tertiary`}):a.jsx("div",{className:`rounded bg-bambu-dark-tertiary flex items-center justify-center ${Z?"w-8 h-8":"w-10 h-10"}`,children:a.jsx(ri,{className:`${Z?"w-4 h-4":"w-5 h-5"} text-bambu-gray`})}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:`${Z?"text-xs":"text-sm"} text-white font-medium truncate`,children:Pe.name||s("modelViewer.plateNumber",{number:Pe.index})}),a.jsx("p",{className:`${Z?"text-[10px]":"text-xs"} text-bambu-gray truncate`,children:s("modelViewer.objectCount",{count:Pe.object_count??Pe.objects?.length??0})})]}),N===Pe.index&&a.jsx(Vr,{className:`${Z?"w-3.5 h-3.5":"w-4 h-4"} text-bambu-green flex-shrink-0`})]},Pe.index))]})}),(ee||fe)&&a.jsxs("div",{className:"mt-auto pt-3 flex items-center gap-4 text-xs text-bambu-gray overflow-x-auto",children:[ee&&a.jsxs("div",{className:"flex items-center gap-3 whitespace-nowrap",children:[a.jsx("span",{children:s("modelViewer.plateNumber",{number:ee.index})}),ee.print_time_seconds!=null&&a.jsx("span",{children:s("modelViewer.eta",{minutes:Math.round(ee.print_time_seconds/60)})}),ee.filament_used_grams!=null&&a.jsxs("span",{children:[ee.filament_used_grams.toFixed(1)," g"]}),ee.filaments.length>0&&a.jsx("span",{children:s("modelViewer.filamentCount",{count:ee.filaments.length})})]}),fe&&a.jsxs("div",{className:`flex items-center gap-2 whitespace-nowrap ${ee?"ml-auto":""}`,children:[a.jsx("span",{children:s("modelViewer.pagination.pageOf",{current:k+1,total:Q})}),a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx("button",{type:"button",onClick:()=>P(Pe=>Math.max(Pe-1,0)),disabled:k===0,className:`px-2 py-1 rounded border text-xs ${k===0?"border-bambu-dark-tertiary text-bambu-gray/40 cursor-not-allowed":"border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,children:s("modelViewer.pagination.prev")}),(()=>{let be=Math.max(0,k-Math.floor(2.5));const O=Math.min(Q,be+5);O-be<5&&(be=Math.max(0,O-5));const R=Array.from({length:O-be},(q,de)=>be+de);return a.jsxs(a.Fragment,{children:[be>0&&a.jsx("button",{type:"button",onClick:()=>P(0),className:`px-2 py-1 rounded border text-xs ${k===0?"border-bambu-green text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,children:"1"}),be>1&&a.jsx("span",{className:"px-1",children:"…"}),R.map(q=>a.jsx("button",{type:"button",onClick:()=>P(q),className:`px-2 py-1 rounded border text-xs ${k===q?"border-bambu-green text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,children:q+1},q)),OP(Q-1),className:`px-2 py-1 rounded border text-xs ${k===Q-1?"border-bambu-green text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,children:Q})]})})(),a.jsx("button",{type:"button",onClick:()=>P(Pe=>Math.min(Pe+1,Q-1)),disabled:k>=Q-1,className:`px-2 py-1 rounded border text-xs ${k>=Q-1?"border-bambu-dark-tertiary text-bambu-gray/40 cursor-not-allowed":"border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,children:s("modelViewer.pagination.next")})]})]})]})]})]}),Z&&a.jsx("div",{role:"separator","aria-orientation":"horizontal",onMouseDown:Pe=>{Pe.preventDefault(),L(!0),D(!0)},className:`h-2 cursor-row-resize flex items-center justify-center ${B?"bg-bambu-dark-tertiary":"bg-bambu-dark-secondary/60 hover:bg-bambu-dark-tertiary"}`,children:a.jsx("div",{className:"w-12 h-1 rounded-full bg-bambu-gray/50"})}),a.jsx("div",{className:`flex-1 ${Z?"min-h-0":""}`,children:a.jsx(NY,{url:c?J.getLibraryFileDownloadUrl(e):h.has_source?J.getSource3mfDownloadUrl(t):J.getArchiveDownload(t),fileType:r,buildVolume:h.build_volume,filamentColors:h.filament_colors,selectedPlateId:N,className:"w-full h-full"})})]}):d==="gcode"&&h?a.jsx(sQ,{gcodeUrl:c?J.getLibraryFileGcodeUrl(e):J.getArchiveGcode(t),filamentColors:h.filament_colors,className:"w-full h-full"}):a.jsx("div",{className:"w-full h-full flex items-center justify-center text-bambu-gray",children:s("modelViewer.noPreview")})})]})})}const HN={"000000":"Black","001489":"Blue","002e96":"Blue","0047bb":"Blue","00482b":"Pine Green","004ea8":"Blue","0056b8":"Cobalt Blue","0069b1":"Lake Blue","0072ce":"Blue","0078bf":"Marine Blue","0085ad":"Light Blue","0086d6":"Cyan","008bda":"Blue","009639":"Green","009bd8":"Cyan","009fa1":"Teal","00a6a0":"Green","00ae42":"Bambu Green","00b1b7":"Turquoise","00bb31":"Green","018814":"Candy Green","042f56":"Dark Blue","0a2989":"Blue","0a2ca5":"Blue","0c2340":"Navy Blue","0c3b95":"Blue",101820:"Black","147bd1":"Blue","164b35":"Green","16b08e":"Malachite Green","1d7c6a":"Oxide Green Metallic","1f79e5":"Lake Blue","2140b4":"Blue","25282a":"Black","2842ad":"Royal Blue","2d2b28":"Onyx Black Sparkle",324585:"Indigo Blue",353533:"Gray","39541a":"Forest Green","39699e":"Cobalt Blue Metallic","3b665e":"Green","3f5443":"Alpine Green Sparkle","3f8e43":"Mistletoe Green",424379:"Nebulae","43403d":"Iron Gray Metallic",482960:"Indigo Purple","483d8b":"Royal Purple Sparkle","489fdf":"Azure","4c241c":"Rosewood","4ce4a0":"Green","4d3324":"Dark Chocolate","4d5054":"Lava Gray","4dafda":"Cyan","4f3f24":"Black Walnut",515151:"Dark Gray","515a6c":"Gray",545454:"Dark Gray",565656:"Titan Gray","56b7e6":"Sky Blue",583061:"Violet Purple","5898dd":"Blue",594177:"Purple","5b492f":"Brown","5b6579":"Blue Gray","5c9748":"Matcha Green","5e43b7":"Purple","5e4b3c":"Copper","5f6367":"Titan Gray","61b0ff":"Translucent Light Blue","61bf36":"Green","61c680":"Grass Green","6667ab":"Lavender Blue","684a43":"Brown",686865:"Black","68724d":"Dark Green",688197:"Blue Gray","69398e":"Iris Purple","6e88bc":"Jeans Blue","6ee53c":"Lime Green","6f5034":"Cocoa Brown","7248bd":"Lavender","748c45":"Translucent Olive",757575:"Nardo Gray","75aed8":"Blue","77edd7":"Translucent Teal","789d4a":"Olive","792b36":"Crimson Red Sparkle","7ac0e9":"Glow Blue","7ae1bf":"Mint","7cd82b":"Lime Green","7d6556":"Dark Brown","8344b0":"Purple","847d48":"Bronze","854ce4":"Purple","8671cb":"Purple",875718:"Peanut Brown","87909a":"Silver","898d8d":"Gray","8a949e":"Gray","8e8e8e":"Translucent Gray","8e9089":"Gray","90ff1a":"Neon Green",918669:"Classic Birch",939393:"Gray",950051:"Plum","951e23":"Burgundy Red",959698:"Silver","96d8af":"Light Jade","96dcb9":"Mint","995f11":"Clay Brown","999d9d":"Gray","9b9ea0":"Ash Gray","9d2235":"Maroon Red","9d432c":"Brown","9e007e":"Purple","9ea2a2":"Gray","9f332a":"Brick Red",a1ffac:"Glow Green",a3d8e1:"Ice Blue",a6a9aa:"Silver",a8a8aa:"Gray",a8c6ee:"Baby Blue",aa6443:"Copper Brown Metallic",ad4e38:"Red Granite",adb1b2:"Gray",ae835b:"Caramel",ae96d4:"Lilac Purple",af1685:"Purple",afb1ae:"Gray",b15533:"Terracotta",b28b33:"Gold",b39b84:"Iridium Gold Metallic",b50011:"Red",b8acd6:"Lavender",b8cde9:"Ice Blue",ba9594:"Rose Gold",bb3d43:"Dark Red",bc0900:"Red",becf00:"Bright Green",c0df16:"Green",c12e1f:"Red",c2e189:"Apple Green",c3e2d6:"Light Cyan",c5ed48:"Lime",c6001a:"Red",c6c6c6:"Gray",c8102e:"Red",c8c8c8:"Silver",c98935:"Ochre Yellow",c9a381:"Translucent Brown",cbc6b8:"Bone White",cdceca:"Gray",cea629:"Classic Gold Sparkle",d02727:"Candy Red",d1d3d5:"Light Gray",d32941:"Red",d3b7a7:"Latte Brown",d6001c:"Red",d6abff:"Translucent Purple",d6cca3:"White Oak",dc3a27:"Orange",dd3c22:"Vermilion Red",de4343:"Scarlet Red",dfd1a7:"Beige",e02928:"Red",e4bd68:"Gold",e5b03d:"Gold",e83100:"Red",e8afcf:"Sakura Pink",e8dbb7:"Desert Tan",eaeae4:"White",eaeceb:"Silver",ec008c:"Magenta",ed0000:"Red",eeb1c1:"Pink",efe255:"Yellow",f0f1a8:"Clear",f17b8f:"Glow Pink",f3cfb2:"Champagne",f3e600:"Yellow",f48438:"Orange",f4a925:"Gold",f4d53f:"Yellow",f4ee2a:"Yellow",f5547c:"Hot Pink",f55a74:"Pink",f5b6cd:"Cherry Pink",f5dbab:"Mellow Yellow",f5f1dd:"White",f68b1b:"Neon Orange",f74e02:"Orange",f75403:"Orange",f7ada6:"Pink",f7d959:"Lemon Yellow",f7e6de:"Beige",f7f3f0:"White Marble",f8ff80:"Glow Yellow",f99963:"Mandarin Orange",f9c1bd:"Translucent Pink",f9dfb9:"Cream",f9ef41:"Yellow",f9f7f2:"Nature",f9f7f4:"White",fce300:"Yellow",fce900:"Yellow",fec600:"Sunflower Yellow",fedb00:"Yellow",ff4800:"Orange",ff671f:"Orange",ff6a13:"Orange",ff7f41:"Orange",ff9016:"Pumpkin Orange",ff911a:"Translucent Orange",ff9d5b:"Glow Orange",ffb549:"Sunflower Yellow",ffc72c:"Tangerine Yellow",ffce00:"Yellow",ffd00b:"Yellow",ffe133:"Yellow",fffaf2:"White",ffffff:"White"};function D$e(t){if(!t||t.length<6)return"Unknown";const e=t.replace("#",""),n=parseInt(e.substring(0,2),16),r=parseInt(e.substring(2,4),16),i=parseInt(e.substring(4,6),16),s=Math.max(n,r,i)/255,o=Math.min(n,r,i)/255,l=(s+o)/2;let c=0,d=0;if(s!==o){const u=s-o;d=l>.5?u/(2-s-o):u/(s+o);const h=n/255,f=r/255,p=i/255;s===h?c=((f-p)/u+(f.85?"White":d<.15?l<.4?"Dark Gray":l>.6?"Light Gray":"Gray":c<15||c>=345?"Red":c<45?"Orange":c<70?"Yellow":c<150?"Green":c<200?"Cyan":c<260?"Blue":c<290?"Purple":"Pink"}function vf(t){const e=t.replace("#","").toLowerCase().substring(0,6);return HN[e]?HN[e]:D$e(t)}function xO(t,e){if(t&&!/^[A-Z]\d+-[A-Z]\d+$/.test(t))return t;if(e&&e.length>=6){const n=e.substring(0,6).toLowerCase();if(HN[n])return HN[n]}return null}function oA(t){const e=[],n=t?.ams_extruder_map,r=n&&Object.keys(n).length>0;t?.ams?.forEach(i=>{const s=i.tray.length===1;i.tray.forEach(o=>{if(o.tray_type){const l=r9(o.tray_color);e.push({type:o.tray_type,color:l,colorName:vf(l),amsId:i.id,trayId:o.id,isHt:s,isExternal:!1,label:pO(i.id,o.id,s,!1),globalTrayId:BN(i.id,o.id,!1),trayInfoIdx:o.tray_info_idx||"",extruderId:n?.[String(i.id)]})}})});for(const i of t?.vt_tray??[])if(i.tray_type){const s=r9(i.tray_color),o=i.id??254,l=(t?.vt_tray?.length??0)>1;e.push({type:i.tray_type,color:s,colorName:vf(s),amsId:-1,trayId:o-254,isHt:!1,isExternal:!0,label:l?o===254?"Ext-L":"Ext-R":"External",globalTrayId:o,trayInfoIdx:i.tray_info_idx||"",extruderId:r?255-o:void 0})}return e}function m9(t,e){if(!t?.filaments||t.filaments.length===0)return;const n=oA(e);if(n.length===0)return;const r=new Set,i=t.filaments.map(l=>{const c=l.tray_info_idx||"";let d=n.filter(v=>!r.has(v.globalTrayId));l.nozzle_id!=null&&(d=d.filter(v=>v.extruderId===l.nozzle_id));let u,h,f,p;if(c){const v=d.filter(g=>g.trayInfoIdx===c);v.length===1?u=v[0]:v.length>1&&(h=v.find(g=>g.type?.toUpperCase()===l.type?.toUpperCase()&&Fa(g.color)===Fa(l.color)),h||(f=v.find(g=>g.type?.toUpperCase()===l.type?.toUpperCase()&&Lc(g.color,l.color))),!h&&!f&&(p=v.find(g=>g.type?.toUpperCase()===l.type?.toUpperCase())))}!u&&!h&&!f&&!p&&(h=d.find(v=>v.type?.toUpperCase()===l.type?.toUpperCase()&&Fa(v.color)===Fa(l.color)),h||(f=d.find(v=>v.type?.toUpperCase()===l.type?.toUpperCase()&&Lc(v.color,l.color))),!h&&!f&&(p=d.find(v=>v.type?.toUpperCase()===l.type?.toUpperCase())));const x=u||h||f||p||void 0;return x&&r.add(x.globalTrayId),{slot_id:l.slot_id,globalTrayId:x?.globalTrayId??-1}}),s=Math.max(...i.map(l=>l.slot_id||0));if(s<=0)return;const o=new Array(s).fill(-1);return i.forEach(l=>{l.slot_id&&l.slot_id>0&&(o[l.slot_id-1]=l.globalTrayId)}),o}function R$e(t){return w.useMemo(()=>oA(t),[t])}function kne(t,e,n){const r=R$e(e),i=w.useMemo(()=>{if(!t?.filaments||t.filaments.length===0)return[];const c=new Set(Object.values(n));return t.filaments.map(d=>{const u=d.slot_id||0;if(u>0&&n[u]!==void 0){const P=n[u],C=r.find(E=>E.globalTrayId===P);if(C){const E=C.type?.toUpperCase()===d.type?.toUpperCase(),M=Fa(C.color)===Fa(d.color)||Lc(C.color,d.color);let j;return E&&M?j="match":E?j="type_only":j="mismatch",{...d,loaded:C,hasFilament:!0,typeMatch:E,colorMatch:M,status:j,isManual:!0}}}const h=d.tray_info_idx||"";let f=r.filter(P=>!c.has(P.globalTrayId));d.nozzle_id!=null&&(f=f.filter(P=>P.extruderId===d.nozzle_id));let p,x,v,g;if(h){const P=f.filter(C=>C.trayInfoIdx===h);P.length===1?p=P[0]:P.length>1&&(x=P.find(C=>C.type?.toUpperCase()===d.type?.toUpperCase()&&Fa(C.color)===Fa(d.color)),x||(v=P.find(C=>C.type?.toUpperCase()===d.type?.toUpperCase()&&Lc(C.color,d.color))),!x&&!v&&(g=P.find(C=>C.type?.toUpperCase()===d.type?.toUpperCase())))}!p&&!x&&!v&&!g&&(x=f.find(P=>P.type?.toUpperCase()===d.type?.toUpperCase()&&Fa(P.color)===Fa(d.color)),x||(v=f.find(P=>P.type?.toUpperCase()===d.type?.toUpperCase()&&Lc(P.color,d.color))),!x&&!v&&(g=f.find(P=>P.type?.toUpperCase()===d.type?.toUpperCase())));const y=p||x||v||g||void 0;y&&c.add(y.globalTrayId);const _=!!y,N=_,A=!!p||!!x||!!v;let k;return p||x||v?k="match":g?k="type_only":k="mismatch",{...d,loaded:y,hasFilament:_,typeMatch:N,colorMatch:A,status:k,isManual:!1}})},[t,r,n]),s=w.useMemo(()=>{if(i.length===0)return;const c=Math.max(...i.map(u=>u.slot_id||0));if(c<=0)return;const d=new Array(c).fill(-1);return i.forEach(u=>{u.slot_id&&u.slot_id>0&&(d[u.slot_id-1]=u.loaded?.globalTrayId??-1)}),d},[i]),o=i.some(c=>c.status==="mismatch"),l=i.some(c=>c.status==="type_only");return{loadedFilaments:r,filamentComparison:i,amsMapping:s,hasTypeMismatch:o,hasColorMismatch:l}}function F$e(t,e,n){if(!t||t.length===0)return{exactMatches:0,typeOnlyMatches:0,missingTypes:0,totalSlots:0,status:"full"};let r=0,i=0,s=0;const o=new Set(Object.values(n));for(const d of t){const u=d.slot_id||0;if(u>0&&n[u]!==void 0){const g=n[u],y=e.find(_=>_.globalTrayId===g);if(y){const _=y.type?.toUpperCase()===d.type?.toUpperCase(),N=Fa(y.color)===Fa(d.color)||Lc(y.color,d.color);_&&N?r++:_?i++:s++;continue}}let h=e.filter(g=>!o.has(g.globalTrayId));if(d.nozzle_id!=null){const g=h.filter(y=>y.extruderId===d.nozzle_id);g.length>0&&(h=g)}const f=h.find(g=>g.type?.toUpperCase()===d.type?.toUpperCase()&&Fa(g.color)===Fa(d.color)),p=f?void 0:h.find(g=>g.type?.toUpperCase()===d.type?.toUpperCase()&&Lc(g.color,d.color)),x=f||p?void 0:h.find(g=>g.type?.toUpperCase()===d.type?.toUpperCase()),v=f??p??x;v&&o.add(v.globalTrayId),f||p?r++:x?i++:s++}const l=t.length;let c="full";return s>0?c="missing":i>0&&(c="partial"),{exactMatches:r,typeOnlyMatches:i,missingTypes:s,totalSlots:l,status:c}}function L$e(t,e,n){if(!t?.filaments||t.filaments.length===0)return;const r=oA(e);if(r.length===0)return;const i=new Set(Object.values(n)),s=[];for(const c of t.filaments){const d=c.slot_id||0;if(d>0&&n[d]!==void 0){s.push({slot_id:d,globalTrayId:n[d]});continue}let u=r.filter(v=>!i.has(v.globalTrayId));if(c.nozzle_id!=null){const v=u.filter(g=>g.extruderId===c.nozzle_id);v.length>0&&(u=v)}const h=u.find(v=>v.type?.toUpperCase()===c.type?.toUpperCase()&&Fa(v.color)===Fa(c.color)),f=h?void 0:u.find(v=>v.type?.toUpperCase()===c.type?.toUpperCase()&&Lc(v.color,c.color)),p=h||f?void 0:u.find(v=>v.type?.toUpperCase()===c.type?.toUpperCase()),x=h??f??p;x&&i.add(x.globalTrayId),s.push({slot_id:d,globalTrayId:x?.globalTrayId??-1})}const o=Math.max(...s.map(c=>c.slot_id||0));if(o<=0)return;const l=new Array(o).fill(-1);return s.forEach(c=>{c.slot_id&&c.slot_id>0&&(l[c.slot_id-1]=c.globalTrayId)}),l}const f9={useDefault:!0,manualMappings:{},autoConfigured:!1};function O$e(t,e,n,r,i,s){const o=lv({queries:t.map(x=>({queryKey:["printer-status",x],queryFn:()=>J.getPrinterStatus(x),enabled:t.length>0,staleTime:5e3}))}),l=w.useMemo(()=>t.map((x,v)=>{const g=o[v],y=g?.data,N=e?.find(j=>j.id===x)?.name||`Printer ${x}`,A=oA(y),k=i[x]||f9,P=m9(n,y),C=k.useDefault?r:k.manualMappings,E=L$e(n,y,C),M=F$e(n?.filaments,A,C);return{printerId:x,printerName:N,status:y,isLoading:g?.isLoading??!1,loadedFilaments:A,autoMapping:P,finalMapping:E,matchStatus:M.status,exactMatches:M.exactMatches,typeOnlyMatches:M.typeOnlyMatches,missingTypes:M.missingTypes,totalSlots:M.totalSlots,config:k}}),[t,o,e,n,i,r]),c=o.some(x=>x.isLoading),d=(x,v)=>{s(g=>({...g,[x]:{...g[x]||f9,...v}}))},u=x=>{const v=l.find(_=>_.printerId===x);if(!v||!v.status||!n?.filaments)return;const g=m9(n,v.status);if(!g)return;const y={};g.forEach((_,N)=>{_!==-1&&(y[N+1]=_)}),d(x,{useDefault:!1,manualMappings:y,autoConfigured:!0})},h=()=>{for(const x of t)u(x)},f=x=>l.find(g=>g.printerId===x)?.finalMapping,p=l.every(x=>x.matchStatus!=="missing");return{printerResults:l,isLoading:c,perPrinterConfigs:i,updatePrinterConfig:d,autoConfigureAll:h,autoConfigurePrinter:u,getFinalMapping:f,allPrintersReady:p}}function I$e({printerId:t,filamentReqs:e,manualMappings:n,onManualMappingChange:r,currencySymbol:i,defaultCostPerKg:s,defaultExpanded:o=!1}){const{t:l}=Rt(),c=Qt(),[d,u]=w.useState(!1),[h,f]=w.useState(o),{data:p}=Ye({queryKey:["printer-status",t],queryFn:()=>J.getPrinterStatus(t),enabled:!!t}),{data:x}=Ye({queryKey:["spool-assignments",t],queryFn:()=>J.getAssignments(t),enabled:!!t}),{loadedFilaments:v,filamentComparison:g,hasTypeMismatch:y,hasColorMismatch:_}=kne(e,p,n),N=w.useMemo(()=>{const L=new Map;for(const U of x||[]){const D=U.ams_id===255,$=BN(U.ams_id,U.tray_id,D);L.set($,U.spool?.cost_per_kg??null)}return L},[x]),A=w.useMemo(()=>{const L=new Map;for(const U of x||[]){const D=U.ams_id===255,$=BN(U.ams_id,U.tray_id,D),G=U.spool;if(!G){L.set($,null);continue}L.set($,Math.max(0,Math.round((G.label_weight??0)-(G.weight_used??0))))}return L},[x]),k=w.useMemo(()=>{let L=0;for(const U of g){const D=U.loaded?.globalTrayId;if(D==null)continue;const G=N.get(D)??null??s;G>0&&(L+=U.used_grams/1e3*G)}return L},[g,N,s]),P=w.useMemo(()=>Array.from(N.values()).some(L=>L!=null&&L>0),[N]),C=e?.filaments&&e.filaments.length>0,E=e?.filaments?.some(L=>L.nozzle_id!=null)??!1;if(!C||!p)return null;const M=y?"#f97316":_?"#facc15":"#00ae42",j=(L,U)=>{if(L>0)if(U===""){const D={...n};delete D[L],r(D)}else r({...n,[L]:parseInt(U,10)})},B=async()=>{u(!0);try{await J.refreshPrinterStatus(t),await new Promise(L=>setTimeout(L,500)),await c.refetchQueries({queryKey:["printer-status",t]})}finally{u(!1)}};return a.jsxs("div",{className:"mb-4",children:[a.jsxs("button",{type:"button",onClick:()=>f(!h),className:"flex items-center gap-2 text-sm text-bambu-gray hover:text-white transition-colors w-full",children:[a.jsx(x1,{className:"w-4 h-4",fill:M,stroke:"none"}),a.jsx("span",{children:l("printModal.filamentMapping")}),y?a.jsx("span",{className:"text-xs text-orange-400",children:"(Type not found)"}):_?a.jsx("span",{className:"text-xs text-yellow-400",children:"(Color mismatch)"}):a.jsx("span",{className:"text-xs text-bambu-green",children:"(Ready)"}),h?a.jsx(wl,{className:"w-4 h-4 ml-auto"}):a.jsx(Mn,{className:"w-4 h-4 ml-auto"})]}),h&&a.jsxs("div",{className:"mt-2 bg-bambu-dark rounded-lg p-3 space-y-2",children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsx("span",{className:"text-xs text-bambu-gray",children:"Click to change slot assignment"}),a.jsxs("button",{type:"button",onClick:B,className:"flex items-center gap-1 px-2 py-0.5 text-xs rounded border border-bambu-gray/30 hover:border-bambu-gray hover:bg-bambu-dark-tertiary transition-colors text-bambu-gray hover:text-white",disabled:d,children:[a.jsx(Sr,{className:`w-3 h-3 ${d?"animate-spin":""}`}),a.jsx("span",{children:"Re-read"})]})]}),g.map((L,U)=>a.jsxs("div",{className:"grid items-center gap-2 text-xs",style:{gridTemplateColumns:"16px minmax(70px, 1fr) auto 2fr 16px"},children:[a.jsx("span",{title:`Required: ${L.type} - ${vf(L.color)}`,children:a.jsx(x1,{className:"w-3 h-3",fill:L.color,stroke:L.color})}),a.jsxs("span",{className:"text-white truncate flex items-center gap-1",children:[E&&L.nozzle_id!=null&&a.jsx("span",{className:"inline-flex items-center justify-center w-3.5 h-3.5 rounded text-[9px] font-bold leading-none bg-bambu-gray/20 text-bambu-gray shrink-0",title:L.nozzle_id===1?l("printModal.leftNozzleTooltip"):l("printModal.rightNozzleTooltip"),children:L.nozzle_id===1?l("printModal.leftNozzle"):l("printModal.rightNozzle")}),L.type," ",a.jsxs("span",{className:"text-bambu-gray",children:["(",L.used_grams,"g)"]})]}),a.jsx("span",{className:"text-bambu-gray",children:"→"}),a.jsxs("select",{value:L.loaded?.globalTrayId??"",onChange:D=>j(L.slot_id||0,D.target.value),className:`flex-1 px-2 py-1 rounded border text-xs bg-bambu-dark-secondary focus:outline-none focus:ring-1 focus:ring-bambu-green ${L.status==="match"?"border-bambu-green/50 text-bambu-green":L.status==="type_only"?"border-yellow-400/50 text-yellow-400":"border-orange-400/50 text-orange-400"} ${L.isManual?"ring-1 ring-blue-400/50":""}`,title:L.isManual?"Manually selected":"Auto-matched",children:[a.jsx("option",{value:"",className:"bg-bambu-dark text-bambu-gray",children:"-- Select slot --"}),v.filter(D=>L.nozzle_id==null||D.extruderId===L.nozzle_id).map(D=>{const $=A.get(D.globalTrayId),G=$!=null?l("printModal.slotRemainingShort",{grams:$,defaultValue:` - ${$}g left`}):"";return a.jsxs("option",{value:D.globalTrayId,className:"bg-bambu-dark text-white",children:[D.label,": ",D.type," (",D.colorName,")",G]},D.globalTrayId)})]}),L.status==="match"?a.jsx(Vr,{className:"w-3 h-3 text-bambu-green"}):L.status==="type_only"?a.jsx("span",{title:"Same type, different color",children:a.jsx(An,{className:"w-3 h-3 text-yellow-400"})}):a.jsx("span",{title:"Filament type not loaded",children:a.jsx(An,{className:"w-3 h-3 text-orange-400"})})]},U)),a.jsxs("div",{className:"text-xs text-bambu-gray",children:[l("printModal.totalCost")," ",a.jsx("span",{className:"text-white",children:k>0||P?`${i}${k.toFixed(2)}`:"N/A"})]}),y&&a.jsx("p",{className:"text-xs text-orange-400 mt-2",children:"Required filament type not found in printer."})]})]})}function z$e({filamentReqs:t,availableFilaments:e,overrides:n,onChange:r}){const{t:i}=Rt(),s=w.useMemo(()=>{const c={};for(const d of e){const u=d.type.toUpperCase();c[u]||(c[u]=[]),c[u].push(d)}return c},[e]),o=t?.filaments;if(!o||o.length===0||e.length===0)return null;const l=(c,d)=>{if(d===""){const u={...n};delete u[c],r(u)}else{const[u,h]=d.split("|");r({...n,[c]:{type:u,color:h}})}};return a.jsxs("div",{className:"mb-4",children:[a.jsx("div",{className:"flex items-center gap-2 text-sm text-bambu-gray mb-2",children:a.jsx("span",{children:i("printModal.filamentOverride")})}),a.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:i("printModal.filamentOverrideHint")}),a.jsx("div",{className:"bg-bambu-dark rounded-lg p-3 space-y-2",children:o.map(c=>{const d=n[c.slot_id],u=!!d,h=s[c.type.toUpperCase()]||[],f=c.nozzle_id!=null?h.filter(p=>p.extruder_id==null||p.extruder_id===c.nozzle_id):h;return a.jsxs("div",{className:"grid items-center gap-2 text-xs",style:{gridTemplateColumns:"16px minmax(70px, 1fr) auto 2fr 20px"},children:[a.jsx("span",{title:`${i("printModal.originalFilament")}: ${c.type} - ${vf(c.color)}`,children:a.jsx(x1,{className:"w-3 h-3",fill:c.color,stroke:c.color})}),a.jsxs("span",{className:"text-white truncate",children:[c.type," ",a.jsxs("span",{className:"text-bambu-gray",children:["(",c.used_grams,"g)"]})]}),a.jsx("span",{className:"text-bambu-gray",children:"→"}),a.jsxs("select",{value:u?`${d.type}|${d.color}`:"",onChange:p=>l(c.slot_id,p.target.value),disabled:f.length===0,className:`flex-1 px-2 py-1 rounded border text-xs bg-bambu-dark-secondary focus:outline-none focus:ring-1 focus:ring-bambu-green ${u?"border-blue-400/50 text-blue-400":"border-bambu-gray/30 text-bambu-gray"}`,children:[a.jsxs("option",{value:"",className:"bg-bambu-dark text-bambu-gray",children:[i("printModal.originalFilament"),": ",c.type," (",vf(c.color),")"]}),f.map((p,x)=>a.jsxs("option",{value:`${p.type}|${p.color}`,className:"bg-bambu-dark text-white",children:[p.type," (",vf(p.color),")"]},`${p.type}-${p.color}-${x}`))]}),u?a.jsx("button",{type:"button",onClick:()=>l(c.slot_id,""),className:"text-bambu-gray hover:text-white transition-colors",title:i("printModal.resetToOriginal"),children:a.jsx(lo,{className:"w-3 h-3"})}):a.jsx("span",{className:"w-3"})]},c.slot_id)})})]})}function U$e({plates:t,isMultiPlate:e,selectedPlate:n,onSelect:r}){return!e||t.length<=1?null:a.jsxs("div",{className:"mb-4",children:[a.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[a.jsx(ri,{className:"w-4 h-4 text-bambu-gray"}),a.jsx("span",{className:"text-sm text-bambu-gray",children:"Select Plate to Print"}),!n&&a.jsxs("span",{className:"text-xs text-orange-400 flex items-center gap-1",children:[a.jsx(An,{className:"w-3 h-3"}),"Selection required"]})]}),a.jsx("div",{className:"grid grid-cols-2 gap-2",children:t.map(i=>a.jsxs("button",{type:"button",onClick:()=>r(i.index),className:`flex items-center gap-2 p-2 rounded-lg border transition-colors text-left ${n===i.index?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark hover:border-bambu-gray"}`,children:[i.has_thumbnail&&i.thumbnail_url!=null?a.jsx("img",{src:i.thumbnail_url,alt:`Plate ${i.index}`,className:"w-10 h-10 rounded object-cover bg-bambu-dark-tertiary"}):a.jsx("div",{className:"w-10 h-10 rounded bg-bambu-dark-tertiary flex items-center justify-center",children:a.jsx(ri,{className:"w-5 h-5 text-bambu-gray"})}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:"text-sm text-white font-medium truncate",children:i.name||`Plate ${i.index}`}),a.jsxs("p",{className:"text-xs text-bambu-gray truncate",children:[i.objects.length>0?i.objects.slice(0,3).join(", ")+(i.objects.length>3?"...":""):`${i.filaments.length} filament${i.filaments.length!==1?"s":""}`,i.print_time_seconds!=null?` • ${Js(i.print_time_seconds)}`:""]})]}),n===i.index&&a.jsx(Vr,{className:"w-4 h-4 text-bambu-green flex-shrink-0"})]},i.index))})]})}function B$e({printerResult:t,filamentReqs:e,onUpdateConfig:n}){const r=Qt(),[i,s]=w.useState(!1),o=(d,u)=>{if(d<=0)return;const h={...t.config.manualMappings};u===""?delete h[d]:h[d]=parseInt(u,10),n({useDefault:!1,manualMappings:h,autoConfigured:!1})},l=async()=>{s(!0);try{await J.refreshPrinterStatus(t.printerId),await new Promise(d=>setTimeout(d,500)),await r.refetchQueries({queryKey:["printer-status",t.printerId]})}finally{s(!1)}},c=e.map(d=>{const u=d.slot_id||0,h=t.config.manualMappings[u];let f,p=!1;if(h!==void 0)f=t.loadedFilaments.find(v=>v.globalTrayId===h),p=!0;else{const v=new Set(Object.values(t.config.manualMappings)),g=t.loadedFilaments.find(N=>!v.has(N.globalTrayId)&&N.type?.toUpperCase()===d.type?.toUpperCase()&&Fa(N.color)===Fa(d.color)),y=g?void 0:t.loadedFilaments.find(N=>!v.has(N.globalTrayId)&&N.type?.toUpperCase()===d.type?.toUpperCase()&&Lc(N.color,d.color)),_=g||y?void 0:t.loadedFilaments.find(N=>!v.has(N.globalTrayId)&&N.type?.toUpperCase()===d.type?.toUpperCase());f=g??y??_}let x="mismatch";if(f){const v=f.type?.toUpperCase()===d.type?.toUpperCase(),g=Fa(f.color)===Fa(d.color)||Lc(f.color,d.color);v&&g?x="match":v&&(x="type_only")}return{req:d,loaded:f,status:x,isManual:p}});return a.jsxs("div",{className:"mt-2 bg-bambu-dark rounded-lg p-3 space-y-2",children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsx("span",{className:"text-xs text-bambu-gray",children:"Custom slot mapping"}),a.jsxs("button",{type:"button",onClick:l,className:"flex items-center gap-1 px-2 py-0.5 text-xs rounded border border-bambu-gray/30 hover:border-bambu-gray hover:bg-bambu-dark-tertiary transition-colors text-bambu-gray hover:text-white",disabled:i,children:[a.jsx(Sr,{className:`w-3 h-3 ${i?"animate-spin":""}`}),a.jsx("span",{children:"Re-read"})]})]}),c.map(({req:d,loaded:u,status:h,isManual:f},p)=>a.jsxs("div",{className:"grid items-center gap-2 text-xs",style:{gridTemplateColumns:"16px minmax(70px, 1fr) auto 2fr 16px"},children:[a.jsx("span",{title:`Required: ${d.type} - ${vf(d.color)}`,children:a.jsx(x1,{className:"w-3 h-3",fill:d.color,stroke:d.color})}),a.jsxs("span",{className:"text-white truncate",children:[d.type," ",a.jsxs("span",{className:"text-bambu-gray",children:["(",d.used_grams,"g)"]})]}),a.jsx("span",{className:"text-bambu-gray",children:"→"}),a.jsxs("select",{value:u?.globalTrayId??"",onChange:x=>o(d.slot_id||0,x.target.value),className:`flex-1 px-2 py-1 rounded border text-xs bg-bambu-dark-secondary focus:outline-none focus:ring-1 focus:ring-bambu-green ${h==="match"?"border-bambu-green/50 text-bambu-green":h==="type_only"?"border-yellow-400/50 text-yellow-400":"border-orange-400/50 text-orange-400"} ${f?"ring-1 ring-blue-400/50":""}`,title:f?"Manually selected":"Auto-matched",children:[a.jsx("option",{value:"",className:"bg-bambu-dark text-bambu-gray",children:"-- Select slot --"}),t.loadedFilaments.map(x=>a.jsxs("option",{value:x.globalTrayId,className:"bg-bambu-dark text-white",children:[x.label,": ",x.type," (",x.colorName,")"]},x.globalTrayId))]}),h==="match"?a.jsx(Vr,{className:"w-3 h-3 text-bambu-green"}):h==="type_only"?a.jsx("span",{title:"Same type, different color",children:a.jsx(An,{className:"w-3 h-3 text-yellow-400"})}):a.jsx("span",{title:"Filament type not loaded",children:a.jsx(An,{className:"w-3 h-3 text-orange-400"})})]},p))]})}function H$e({printers:t,selectedPrinterIds:e,onMultiSelect:n,isLoading:r=!1,allowMultiple:i=!1,showInactive:s=!1,printerMappingResults:o,filamentReqs:l,onAutoConfigurePrinter:c,onUpdatePrinterConfig:d,assignmentMode:u="printer",onAssignmentModeChange:h,targetModel:f,onTargetModelChange:p,targetLocation:x,onTargetLocationChange:v,slicedForModel:g}){const[y,_]=w.useState(!1),N=s?t:t.filter(z=>z.is_active),A=w.useMemo(()=>{if(u!=="printer"||!g||y)return N;const z=N.filter(W=>W.model===g);return z.length>0?z:N},[N,u,g,y]),k=N.length-A.length,P=w.useMemo(()=>{const z=N.map(W=>W.model).filter(W=>!!W);return[...new Set(z)].sort()},[N]),C=w.useMemo(()=>{if(!f)return[];const z=N.filter(W=>W.model===f&&W.location).map(W=>W.location).filter(W=>!!W);return[...new Set(z)].sort()},[N,f]),E=h&&p&&P.length>0,M=i&&e.length>1&&o&&l?.filaments&&l.filaments.length>0&&c&&d;if(r)return a.jsx("div",{className:"flex justify-center py-8",children:a.jsx(at,{className:"w-6 h-6 text-bambu-green animate-spin"})});if(A.length===0)return a.jsxs("div",{className:"flex items-center gap-2 text-red-400 text-sm mb-4",children:[a.jsx(Va,{className:"w-4 h-4"}),"No ",s?"":"active ","printers available"]});const j=z=>{i?e.includes(z)?n(e.filter(W=>W!==z)):n([...e,z]):n([z])},B=()=>{n(A.map(z=>z.id))},L=()=>{n([])},U=(z,W,K)=>{K.stopPropagation(),!(!c||!d)&&(W?c(z):d(z,{useDefault:!0,manualMappings:{},autoConfigured:!1}))},D=z=>e.includes(z),$=e.length,G=z=>o?.find(W=>W.printerId===z);return a.jsxs("div",{className:"space-y-2 mb-6",children:[E&&a.jsxs("div",{className:"flex gap-2 mb-4",children:[a.jsxs("button",{type:"button",onClick:()=>{h("printer"),p(null)},className:`flex-1 flex items-center justify-center gap-2 px-3 py-2 rounded-lg border transition-colors ${u==="printer"?"border-bambu-green bg-bambu-green/10 text-white":"border-bambu-dark-tertiary bg-bambu-dark text-bambu-gray hover:border-bambu-gray"}`,children:[a.jsx(Nr,{className:"w-4 h-4"}),a.jsx("span",{className:"text-sm",children:"Specific Printer"})]}),a.jsxs("button",{type:"button",onClick:()=>{h("model"),n([]);const z=g&&P.includes(g)?g:P[0];p(z)},className:`flex-1 flex items-center justify-center gap-2 px-3 py-2 rounded-lg border transition-colors ${u==="model"?"border-bambu-green bg-bambu-green/10 text-white":"border-bambu-dark-tertiary bg-bambu-dark text-bambu-gray hover:border-bambu-gray"}`,children:[a.jsx(fh,{className:"w-4 h-4"}),a.jsxs("span",{className:"text-sm",children:["Any ",g||"Model"]})]})]}),u==="model"&&E&&a.jsxs("div",{className:"space-y-3 mb-4",children:[!g&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Target Model"}),a.jsxs("select",{value:f||"",onChange:z=>{p(z.target.value||null),v&&v(null)},className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none text-sm",children:[a.jsx("option",{value:"",children:"Select a model..."}),P.map(z=>a.jsx("option",{value:z,children:z},z))]})]}),f&&C.length>0&&v&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Location Filter (optional)"}),a.jsxs("select",{value:x||"",onChange:z=>v(z.target.value||null),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none text-sm",children:[a.jsx("option",{value:"",children:"Any location"}),C.map(z=>a.jsx("option",{value:z,children:z},z))]})]}),f&&a.jsxs("p",{className:"text-xs text-bambu-gray",children:["Scheduler will assign to first available idle ",f," printer",x?` in ${x}`:""]})]}),u==="printer"&&i&&A.length>1&&a.jsxs("div",{className:"flex items-center justify-between text-xs text-bambu-gray mb-2",children:[a.jsx("span",{children:$===0?"Select printers":`${$} printer${$!==1?"s":""} selected`}),a.jsxs("div",{className:"flex gap-2",children:[$0&&a.jsx("button",{type:"button",onClick:L,className:"text-bambu-gray hover:text-white transition-colors",children:"Clear"})]})]}),u==="printer"&&A.map(z=>{const W=D(z.id),K=G(z.id),te=K&&!K.config.useDefault;return a.jsxs("div",{children:[a.jsxs("button",{type:"button",onClick:()=>j(z.id),className:`w-full flex items-center gap-3 p-3 rounded-lg border transition-colors ${W?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark hover:border-bambu-gray"} ${z.is_active?"":"opacity-60"}`,children:[a.jsx("div",{className:`p-2 rounded-lg ${W?"bg-bambu-green/20":"bg-bambu-dark-tertiary"}`,children:a.jsx(Nr,{className:`w-5 h-5 ${W?"text-bambu-green":"text-bambu-gray"}`})}),a.jsxs("div",{className:"text-left flex-1",children:[a.jsxs("p",{className:"text-white font-medium",children:[z.name,!z.is_active&&a.jsx("span",{className:"text-bambu-gray text-xs ml-2",children:"(inactive)"})]}),a.jsxs("p",{className:"text-xs text-bambu-gray",children:[z.model||"Unknown model"," • ",z.ip_address]})]}),i&&a.jsx("div",{className:`w-5 h-5 rounded border-2 flex items-center justify-center transition-colors ${W?"bg-bambu-green border-bambu-green":"border-bambu-gray/50"}`,children:W&&a.jsx(Vr,{className:"w-3 h-3 text-white"})})]}),W&&M&&K&&a.jsxs("div",{className:"ml-4 mt-2 mb-3",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",onClick:H=>H.stopPropagation(),children:[a.jsx("input",{type:"checkbox",checked:te,onChange:H=>U(z.id,H.target.checked,H),className:"w-3.5 h-3.5 rounded border-bambu-gray/30 bg-bambu-dark-secondary text-bambu-green focus:ring-bambu-green focus:ring-offset-0"}),a.jsx("span",{className:"text-xs text-bambu-gray",children:"Custom mapping"})]}),a.jsxs("span",{className:`text-xs ml-2 ${K.matchStatus==="full"?"text-bambu-green":K.matchStatus==="partial"?"text-yellow-400":"text-orange-400"}`,children:["(",K.exactMatches,"/",K.totalSlots," matched)"]}),K.isLoading&&a.jsx(Sr,{className:"w-3 h-3 text-bambu-gray animate-spin"}),te&&a.jsxs("button",{type:"button",onClick:H=>{H.stopPropagation(),c(z.id)},className:"ml-auto flex items-center gap-1 px-2 py-0.5 text-xs rounded border border-bambu-gray/30 hover:border-bambu-gray hover:bg-bambu-dark-tertiary transition-colors text-bambu-gray hover:text-white",children:[a.jsx(hge,{className:"w-3 h-3"}),"Auto"]})]}),te&&a.jsx(B$e,{printerResult:K,filamentReqs:l.filaments,onUpdateConfig:H=>d(z.id,H)})]})]},z.id)}),u==="printer"&&k>0&&!y&&a.jsxs("button",{type:"button",onClick:()=>_(!0),className:"text-xs text-bambu-gray hover:text-white transition-colors mt-2 flex items-center gap-1",children:[a.jsx(An,{className:"w-3 h-3 text-yellow-400"}),k," other printer",k>1?"s":""," hidden (different model) —",a.jsx("span",{className:"underline",children:"show all"})]}),u==="printer"&&y&&g&&a.jsx("button",{type:"button",onClick:()=>_(!1),className:"text-xs text-bambu-gray hover:text-white transition-colors mt-2",children:a.jsxs("span",{className:"underline",children:["Show only ",g," printers"]})}),u==="printer"&&$===0&&a.jsxs("p",{className:"text-xs text-orange-400 mt-1 flex items-center gap-1",children:[a.jsx(Va,{className:"w-3 h-3"}),"Select at least one printer"]}),u==="model"&&!f&&a.jsxs("p",{className:"text-xs text-orange-400 mt-1 flex items-center gap-1",children:[a.jsx(Va,{className:"w-3 h-3"}),"Select a target printer model"]})]})}const $$e=[{key:"bed_levelling",label:"Bed Levelling",desc:"Auto-level bed before print"},{key:"flow_cali",label:"Flow Calibration",desc:"Calibrate extrusion flow"},{key:"vibration_cali",label:"Vibration Calibration",desc:"Reduce ringing artifacts"},{key:"layer_inspect",label:"First Layer Inspection",desc:"AI inspection of first layer"},{key:"timelapse",label:"Timelapse",desc:"Record timelapse video"}];function V$e({options:t,onChange:e,defaultExpanded:n=!1}){const[r,i]=w.useState(n),s=o=>{e({...t,[o]:!t[o]})};return a.jsxs("div",{className:"mb-4",children:[a.jsxs("button",{type:"button",onClick:()=>i(!r),className:"flex items-center gap-2 text-sm text-bambu-gray hover:text-white transition-colors w-full",children:[a.jsx(ZC,{className:"w-4 h-4"}),a.jsx("span",{children:"Print Options"}),r?a.jsx(wl,{className:"w-4 h-4 ml-auto"}):a.jsx(Mn,{className:"w-4 h-4 ml-auto"})]}),r&&a.jsx("div",{className:"mt-2 bg-bambu-dark rounded-lg p-3 space-y-2",children:$$e.map(({key:o,label:l,desc:c})=>a.jsxs("label",{className:"flex items-center justify-between cursor-pointer group",children:[a.jsxs("div",{children:[a.jsx("span",{className:"text-sm text-white",children:l}),a.jsx("p",{className:"text-xs text-bambu-gray",children:c})]}),a.jsx("div",{className:`relative w-10 h-5 rounded-full transition-colors ${t[o]?"bg-bambu-green":"bg-bambu-dark-tertiary"}`,onClick:()=>s(o),children:a.jsx("div",{className:`absolute top-0.5 w-4 h-4 rounded-full bg-white transition-transform ${t[o]?"translate-x-5":"translate-x-0.5"}`})})]},o))})]})}function q$e({options:t,onChange:e,dateFormat:n="system",timeFormat:r="system",canControlPrinter:i=!0}){const[s,o]=w.useState(""),[l,c]=w.useState(""),[d,u]=w.useState(!0),[h,f]=w.useState(!0),p=w.useRef(null),x=w.useRef(!1);w.useEffect(()=>{if(t.scheduleType!=="scheduled"){x.current=!1;return}if(!x.current){x.current=!0;let k;t.scheduledTime?(k=new Date(t.scheduledTime),isNaN(k.getTime())&&(k=new Date,k.setHours(k.getHours()+1,0,0,0))):(k=new Date,k.setHours(k.getHours()+1,0,0,0),e({...t,scheduledTime:m3(k)})),o(h3(k,n)),c(VB(k,r)),u(!0),f(!0)}},[t.scheduleType,t.scheduledTime,n,r,e,t]);const v=k=>{e({...t,scheduleType:k})},g=(k,P)=>{const C=Rge(k,n),E=Fge(P);u(!!C),f(!!E),C&&E&&(C.setHours(E.hours,E.minutes,0,0),C>new Date&&e({...t,scheduledTime:m3(C)}))},y=k=>{o(k),g(k,l)},_=k=>{c(k),g(s,k)},N=k=>{const P=k.target.value;if(P){const C=new Date(P);isNaN(C.getTime())||(o(h3(C,n)),c(VB(C,r)),u(!0),f(!0),e({...t,scheduledTime:P}))}},A=()=>{p.current?.showPicker()};return a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-2",children:"When to print"}),a.jsxs("div",{className:"flex gap-2",children:[a.jsxs("button",{type:"button",className:`flex-1 px-2 py-2 rounded-lg border text-sm flex items-center justify-center gap-1.5 transition-colors ${t.scheduleType==="asap"?"bg-bambu-green border-bambu-green text-white":"bg-bambu-dark border-bambu-dark-tertiary text-bambu-gray hover:text-white"}`,onClick:()=>v("asap"),children:[a.jsx(qn,{className:"w-4 h-4"}),"ASAP"]}),a.jsxs("button",{type:"button",className:`flex-1 px-2 py-2 rounded-lg border text-sm flex items-center justify-center gap-1.5 transition-colors ${t.scheduleType==="scheduled"?"bg-bambu-green border-bambu-green text-white":"bg-bambu-dark border-bambu-dark-tertiary text-bambu-gray hover:text-white"}`,onClick:()=>v("scheduled"),children:[a.jsx(da,{className:"w-4 h-4"}),"Scheduled"]}),a.jsxs("button",{type:"button",className:`flex-1 px-2 py-2 rounded-lg border text-sm flex items-center justify-center gap-1.5 transition-colors ${t.scheduleType==="manual"?"bg-bambu-green border-bambu-green text-white":"bg-bambu-dark border-bambu-dark-tertiary text-bambu-gray hover:text-white"}`,onClick:()=>v("manual"),children:[a.jsx(_X,{className:"w-4 h-4"}),"Queue Only"]})]})]}),t.scheduleType==="scheduled"&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Date & Time"}),a.jsxs("div",{className:"flex gap-2",children:[a.jsxs("div",{className:"flex-1 relative",children:[a.jsx("input",{type:"text",className:`w-full px-3 py-2 pr-10 bg-bambu-dark border rounded-lg text-white focus:outline-none ${d?"border-bambu-dark-tertiary focus:border-bambu-green":"border-red-500"}`,value:s,onChange:k=>y(k.target.value),placeholder:Ege(n)}),a.jsx("button",{type:"button",onClick:A,className:"absolute right-2 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white",title:"Open calendar",children:a.jsx(da,{className:"w-4 h-4"})})]}),a.jsx("div",{className:"w-32",children:a.jsx("input",{type:"text",className:`w-full px-3 py-2 bg-bambu-dark border rounded-lg text-white focus:outline-none ${h?"border-bambu-dark-tertiary focus:border-bambu-green":"border-red-500"}`,value:l,onChange:k=>_(k.target.value),placeholder:Dge(r)})})]}),a.jsx("input",{ref:p,type:"datetime-local",className:"sr-only",value:t.scheduledTime,onChange:N,tabIndex:-1}),(!d||!h)&&a.jsx("p",{className:"mt-1 text-xs text-red-400",children:"Please enter a valid date and time"})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"checkbox",id:"requirePrevious",checked:t.requirePreviousSuccess,onChange:k=>e({...t,requirePreviousSuccess:k.target.checked}),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),a.jsx("label",{htmlFor:"requirePrevious",className:"text-sm text-bambu-gray",children:"Only start if previous print succeeded"})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"checkbox",id:"autoOffAfter",checked:t.autoOffAfter,onChange:k=>e({...t,autoOffAfter:k.target.checked}),disabled:!i,className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green disabled:opacity-50"}),a.jsxs("label",{htmlFor:"autoOffAfter",className:`text-sm flex items-center gap-1 ${i?"text-bambu-gray":"text-bambu-gray/50"}`,children:[a.jsx(fu,{className:"w-3.5 h-3.5"}),"Power off printer when done"]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:t.scheduleType==="asap"?"Print will start as soon as the printer is idle.":t.scheduleType==="scheduled"?"Print will start at the scheduled time if the printer is idle. If busy, it will wait until the printer becomes available.":"Print will be staged but won't start automatically. Use the Start button to release it to the queue."})]})}const Ng={bed_levelling:!0,flow_cali:!1,vibration_cali:!0,layer_inspect:!1,timelapse:!1},G$e={scheduleType:"asap",scheduledTime:"",requirePreviousSuccess:!1,autoOffAfter:!1};function Yd({mode:t,archiveId:e,libraryFileId:n,archiveName:r,queueItem:i,onClose:s,onSuccess:o}){const{t:l}=Rt(),c=Qt(),{showToast:d}=dn(),{hasPermission:u}=Er(),h=!!n&&!e,[f,p]=w.useState(()=>t==="edit-queue-item"&&i?.printer_id?[i.printer_id]:[]),[x,v]=w.useState(()=>t==="edit-queue-item"&&i?i.plate_id:null),[g,y]=w.useState(()=>t==="edit-queue-item"&&i?{bed_levelling:i.bed_levelling??Ng.bed_levelling,flow_cali:i.flow_cali??Ng.flow_cali,vibration_cali:i.vibration_cali??Ng.vibration_cali,layer_inspect:i.layer_inspect??Ng.layer_inspect,timelapse:i.timelapse??Ng.timelapse}:Ng),[_,N]=w.useState(()=>{if(t==="edit-queue-item"&&i){let Ee="asap";i.manual_start?Ee="manual":i.scheduled_time&&!a9(i.scheduled_time)&&(Ee="scheduled");let Ve="";if(i.scheduled_time&&!a9(i.scheduled_time)){const ot=tr(i.scheduled_time)??new Date;Ve=m3(ot)}return{scheduleType:Ee,scheduledTime:Ve,requirePreviousSuccess:i.require_previous_success,autoOffAfter:i.auto_off_after}}return G$e}),[A,k]=w.useState(()=>{if(t==="edit-queue-item"&&i?.ams_mapping&&Array.isArray(i.ams_mapping)){const Ee={};return i.ams_mapping.forEach((Ve,ot)=>{Ve!==-1&&(Ee[ot+1]=Ve)}),Ee}return{}}),[P,C]=w.useState({}),[E,M]=w.useState(()=>t==="edit-queue-item"&&i?.target_model?"model":"printer"),[j,B]=w.useState(()=>t==="edit-queue-item"&&i?.target_model?i.target_model:null),[L,U]=w.useState(()=>t==="edit-queue-item"&&i?.target_location?i.target_location:null),[D,$]=w.useState(()=>{if(t==="edit-queue-item"&&i?.filament_overrides){const Ee={};for(const Ve of i.filament_overrides)Ee[Ve.slot_id]={type:Ve.type,color:Ve.color};return Ee}return{}}),[G]=w.useState(()=>t==="edit-queue-item"&&i?.printer_id?[i.printer_id]:[]),[z]=w.useState(()=>t==="edit-queue-item"&&i?i.plate_id:null),[W,K]=w.useState(!1),[te,H]=w.useState({current:0,total:0}),[Y,Z]=w.useState(new Set),ee=f.length,Se=f.length>0?f[0]:null,{data:oe}=Ye({queryKey:["settings"],queryFn:J.getSettings}),ie=il(oe?.currency||"USD"),me=oe?.default_filament_cost??0,{data:se,isLoading:ce}=Ye({queryKey:["printers"],queryFn:J.getPrinters}),{data:Ce}=Ye({queryKey:["archive",e],queryFn:()=>J.getArchive(e),enabled:!!e&&!h}),{data:le}=Ye({queryKey:["library-file",n],queryFn:()=>J.getLibraryFile(n),enabled:h&&!!n}),Le=Ce?.sliced_for_model||le?.sliced_for_model||null,{data:V,isError:X}=Ye({queryKey:["archive-plates",e],queryFn:()=>J.getArchivePlates(e),enabled:!!e&&!h,retry:!1}),{data:fe}=Ye({queryKey:["library-file-plates",n],queryFn:()=>J.getLibraryFilePlates(n),enabled:h&&!!n}),Q=h?fe:V,{data:re,isError:ue}=Ye({queryKey:["archive-filaments",e,x],queryFn:()=>J.getArchiveFilamentRequirements(e,x??void 0),enabled:!!e&&!h&&(x!==null||!Q?.is_multi_plate),retry:!1}),{data:Fe}=Ye({queryKey:["library-file-filaments",n,x],queryFn:()=>J.getLibraryFileFilamentRequirements(n,x??void 0),enabled:h&&!!n&&(x!==null||!Q?.is_multi_plate)}),Pe=!h&&(X||ue),be=h?Fe:re,O=w.useMemo(()=>{if(!(x===null||!Q?.plates?.length))return Q.plates.find(Ee=>Ee.index===x)?.name||void 0},[Q,x]),{data:R}=Ye({queryKey:["available-filaments",j,L],queryFn:()=>J.getAvailableFilaments(j,L??void 0),enabled:E==="model"&&!!j}),{data:q}=Ye({queryKey:["printer-status",Se],queryFn:()=>J.getPrinterStatus(Se),enabled:!!Se}),{amsMapping:de}=kne(be,q,A),ge=O$e(f,se,be,A,P,C);w.useEffect(()=>{Q?.plates&&Q.plates.length>=1&&!x&&v(Q.plates[0].index)},[Q,x]),w.useEffect(()=>{if(t==="edit-queue-item")return;const Ee=se?.filter(Ve=>Ve.is_active)||[];Ee.length===1&&f.length===0&&p([Ee[0].id])},[t,se,f.length]),w.useEffect(()=>{t==="edit-queue-item"?(JSON.stringify(f.sort())!==JSON.stringify(G.sort())||x!==z)&&(k({}),C({}),Z(new Set)):(k({}),C({}),Z(new Set))},[t,f,x,G,z]);const[ae,Ue]=w.useState(j),[ze,$e]=w.useState(x);w.useEffect(()=>{(j!==ae||x!==ze)&&(Ue(j),$e(x),(t!=="edit-queue-item"||ae!==null)&&$({}))},[j,x,ae,ze,t]),w.useEffect(()=>{if(!oe?.per_printer_mapping_expanded||f.length<=1)return;const Ee=f.filter(Ve=>{if(Y.has(Ve))return!1;const ot=ge.printerResults.find(kt=>kt.printerId===Ve);return ot&&ot.status&&!ot.isLoading});Ee.length>0&&(Z(Ve=>{const ot=new Set(Ve);return Ee.forEach(kt=>ot.add(kt)),ot}),Ee.forEach(Ve=>{ge.autoConfigurePrinter(Ve)}))},[oe?.per_printer_mapping_expanded,f,Y,ge]),w.useEffect(()=>{const Ee=Ve=>{Ve.key==="Escape"&&!W&&s()};return window.addEventListener("keydown",Ee),()=>window.removeEventListener("keydown",Ee)},[s,W]);const Re=Q?.is_multi_plate??!1,pe=Q?.plates??[],ve=it({mutationFn:Ee=>J.addToQueue(Ee)}),Ne=it({mutationFn:Ee=>J.updateQueueItem(i.id,Ee),onSuccess:()=>{c.invalidateQueries({queryKey:["queue"]}),d("Queue item updated"),o?.(),s()},onError:Ee=>{d(Ee.message||"Failed to update queue item","error")}}),xe=async Ee=>{if(Ee?.preventDefault(),E==="printer"&&f.length===0){d("Please select at least one printer","error");return}if(E==="model"&&!j){d("Please select a target printer model","error");return}K(!0);const Ve=E==="model"?1:f.length;H({current:0,total:Ve});const ot={success:0,failed:0,errors:[]},kt=At=>{if(f.length>1){const Be=P[At];if(Be&&!Be.useDefault)return ge.getFinalMapping(At)}return de},Ft=Object.keys(D).length>0?Object.entries(D).map(([At,{type:Be,color:mt}])=>({slot_id:parseInt(At,10),type:Be,color:mt})):void 0,Vt=At=>({printer_id:E==="printer"?At:null,target_model:E==="model"?j:null,target_location:E==="model"?L:null,filament_overrides:E==="model"?Ft:void 0,archive_id:h?void 0:e,library_file_id:h?n:void 0,require_previous_success:_.requirePreviousSuccess,auto_off_after:_.autoOffAfter,manual_start:_.scheduleType==="manual",ams_mapping:At?kt(At):void 0,plate_id:x,scheduled_time:_.scheduleType==="scheduled"&&_.scheduledTime?new Date(_.scheduledTime).toISOString():void 0,...g});if(E==="model"){H({current:1,total:1});try{if(t==="reprint"){d("Model-based assignment only works with queue mode","error"),K(!1);return}else if(t==="edit-queue-item"){const At={printer_id:null,target_model:j,target_location:L,filament_overrides:Ft||null,require_previous_success:_.requirePreviousSuccess,auto_off_after:_.autoOffAfter,manual_start:_.scheduleType==="manual",ams_mapping:void 0,plate_id:x,scheduled_time:_.scheduleType==="scheduled"&&_.scheduledTime?new Date(_.scheduledTime).toISOString():null,...g};await Ne.mutateAsync(At)}else await ve.mutateAsync(Vt(null));ot.success++}catch(At){ot.failed++,ot.errors.push(At.message)}}else for(let At=0;Atzt.id===Be)?.name||`Printer ${Be}`;ot.errors.push(`${yt}: ${mt.message}`)}}K(!1),ot.failed===0?(t!=="reprint"&&(E==="model"?d(t==="edit-queue-item"?"Queue item updated":`Queued for any ${j}`):t==="edit-queue-item"?d("Queue item updated"):ot.success===1?d("Print queued for printer"):d(`Print queued for ${ot.success} printers`)),c.invalidateQueries({queryKey:["queue"]}),o?.(),s()):ot.success===0?d(`Failed: ${ot.errors[0]}`,"error"):(d(`${ot.success} succeeded, ${ot.failed} failed`,"error"),c.invalidateQueries({queryKey:["queue"]}))},we=W||Ne.isPending,qe=w.useMemo(()=>!(we||E==="printer"&&f.length===0||E==="model"&&!j||E==="model"&&t==="reprint"||Re&&!x),[f.length,E,j,t,Re,x,we]),nt=(()=>{const Ee=f.length;return t==="reprint"?{title:l(h?"queue.print":"queue.reprint"),icon:Nr,submitText:Ee>1?l("queue.printToPrinters",{count:Ee}):l("queue.print"),submitIcon:Nr,loadingText:te.total>1?l("queue.sendingProgress",{current:te.current,total:te.total}):l("queue.sending")}:t==="add-to-queue"?{title:l("queue.schedulePrint"),icon:da,submitText:Ee>1?l("queue.queueToPrinters",{count:Ee}):l("queue.addToQueue"),submitIcon:da,loadingText:te.total>1?l("queue.addingProgress",{current:te.current,total:te.total}):l("queue.adding")}:{title:l("queue.editQueueItem"),icon:Ga,submitText:l("common.save"),submitIcon:Ga,loadingText:te.total>1?l("queue.savingProgress",{current:te.current,total:te.total}):l("common.saving")}})(),De=nt.icon,We=nt.submitIcon,Oe=Se&&(h||(Re?x!==null:!0));return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:W?void 0:s,children:a.jsx(St,{className:"w-full max-w-lg max-h-[90vh] overflow-y-auto",onClick:Ee=>Ee.stopPropagation(),children:a.jsxs(Nt,{className:t==="reprint"?"":"p-0",children:[a.jsxs("div",{className:`flex items-center justify-between ${t==="reprint"?"mb-4":"p-4 border-b border-bambu-dark-tertiary"}`,children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(De,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:nt.title})]}),a.jsx(Me,{variant:"ghost",size:"sm",onClick:s,disabled:W,children:a.jsx(Dt,{className:"w-5 h-5"})})]}),a.jsxs("form",{onSubmit:xe,className:t==="reprint"?"":"p-4 space-y-4",children:[a.jsx("p",{className:`text-sm text-bambu-gray ${t==="reprint"?"mb-4":""}`,children:t==="reprint"?a.jsxs(a.Fragment,{children:["Send ",a.jsx("span",{className:"text-white",children:r})," to printer(s)"]}):a.jsxs(a.Fragment,{children:[a.jsx("span",{className:"block text-bambu-gray mb-1",children:"Print Job"}),a.jsx("span",{className:"text-white font-medium truncate block",children:r})]})}),a.jsx(U$e,{plates:pe,isMultiPlate:Re,selectedPlate:x,onSelect:v}),a.jsx(H$e,{printers:se||[],selectedPrinterIds:f,onMultiSelect:p,isLoading:ce,allowMultiple:!0,showInactive:t==="edit-queue-item",printerMappingResults:ge.printerResults,filamentReqs:be,onAutoConfigurePrinter:ge.autoConfigurePrinter,onUpdatePrinterConfig:ge.updatePrinterConfig,assignmentMode:t==="reprint"?"printer":E,onAssignmentModeChange:t!=="reprint"?M:void 0,targetModel:j,onTargetModelChange:t!=="reprint"?B:void 0,targetLocation:L,onTargetLocationChange:t!=="reprint"?U:void 0,slicedForModel:Le}),E==="model"&&j&&be&&R&&R.length>0&&a.jsx(z$e,{filamentReqs:be,availableFilaments:R,overrides:D,onChange:$}),Le&&E==="printer"&&f.length===1&&(()=>{const Ee=se?.find(Ve=>Ve.id===f[0]);return Ee&&Ee.model&&Le!==Ee.model?a.jsxs("div",{className:"p-3 mb-2 bg-yellow-500/10 border border-yellow-500/30 rounded-lg flex items-center gap-2",children:[a.jsx(An,{className:"w-4 h-4 text-yellow-400 flex-shrink-0"}),a.jsxs("span",{className:"text-sm text-yellow-400",children:["File was sliced for ",Le,", but printing on ",Ee.model]})]}):null})(),Pe&&a.jsxs("div",{className:"flex items-start gap-2 p-3 mb-2 bg-orange-500/10 border border-orange-500/30 rounded-lg text-sm",children:[a.jsx(Va,{className:"w-4 h-4 text-orange-400 mt-0.5 flex-shrink-0"}),a.jsx("p",{className:"text-orange-400",children:"Archive data unavailable. The source file may have been deleted. Filament mapping is disabled."})]}),Oe&&!Pe&&f.length===1&&a.jsx(I$e,{printerId:Se,filamentReqs:be,manualMappings:A,onManualMappingChange:k,defaultExpanded:oe?.per_printer_mapping_expanded??!1,currencySymbol:ie,defaultCostPerKg:me}),(t==="reprint"||ee>0||E==="model"&&j)&&a.jsx(V$e,{options:g,onChange:y}),t!=="reprint"&&a.jsx(q$e,{options:_,onChange:N,dateFormat:oe?.date_format||"system",timeFormat:oe?.time_format||"system",canControlPrinter:u("printers:control")}),Ne.isError&&a.jsx("div",{className:"mb-4 p-3 bg-red-500/20 border border-red-500/50 rounded-lg text-sm text-red-400",children:Ne.error?.message||"Failed to complete operation"}),a.jsxs("div",{className:`flex gap-3 ${t==="reprint"?"":"pt-2"}`,children:[a.jsx(Me,{type:"button",variant:"secondary",onClick:s,className:"flex-1",disabled:W,children:"Cancel"}),a.jsx(Me,{type:"submit",disabled:!qe,className:"flex-1",children:we?a.jsxs(a.Fragment,{children:[a.jsx(at,{className:"w-4 h-4 animate-spin"}),nt.loadingText]}):a.jsxs(a.Fragment,{children:[a.jsx(We,{className:"w-4 h-4"}),nt.submitText]})})]})]})]})})})}function W$e({onClose:t,initialFiles:e}){const{t:n}=Rt(),r=Qt(),{showToast:i}=dn(),s=w.useRef(null),[o,l]=w.useState(()=>e?.filter(k=>k.name.endsWith(".3mf")).map(k=>({file:k,status:"pending"}))||[]),[c,d]=w.useState(!1),[u,h]=w.useState(null);w.useEffect(()=>{const k=P=>{P.key==="Escape"&&t()};return window.addEventListener("keydown",k),()=>window.removeEventListener("keydown",k)},[t]);const f=it({mutationFn:k=>J.uploadArchivesBulk(k),onSuccess:k=>{h(k),r.invalidateQueries({queryKey:["archives"]}),r.invalidateQueries({queryKey:["archiveStats"]}),l(P=>P.map(C=>{const E=k.results.find(j=>j.filename===C.file.name),M=k.errors.find(j=>j.filename===C.file.name);return E?{...C,status:"success",archiveId:E.id}:M?{...C,status:"error",error:M.error}:C})),k.failed===0?i(`${k.uploaded} file${k.uploaded!==1?"s":""} uploaded`):k.uploaded===0?i(`Failed to upload ${k.failed} file${k.failed!==1?"s":""}`,"error"):i(`${k.uploaded} uploaded, ${k.failed} failed`,"warning")},onError:()=>{l(k=>k.map(P=>({...P,status:"error",error:"Upload failed"}))),i("Upload failed","error")}}),p=w.useCallback(k=>{k.preventDefault(),d(!0)},[]),x=w.useCallback(k=>{k.preventDefault(),d(!1)},[]),v=w.useCallback(k=>{k.preventDefault(),d(!1);const P=Array.from(k.dataTransfer.files).filter(C=>C.name.endsWith(".3mf"));P.length>0&&l(C=>[...C,...P.map(E=>({file:E,status:"pending"}))])},[]),g=w.useCallback(k=>{const P=Array.from(k.target.files||[]).filter(C=>C.name.endsWith(".3mf"));P.length>0&&l(C=>[...C,...P.map(E=>({file:E,status:"pending"}))]),s.current&&(s.current.value="")},[]),y=w.useCallback(k=>{l(P=>P.filter((C,E)=>E!==k))},[]),_=()=>{if(o.length===0)return;const k=o.filter(P=>P.status==="pending");k.length!==0&&(l(P=>P.map(C=>C.status==="pending"?{...C,status:"uploading"}:C)),f.mutate(k.map(P=>P.file)))},N=o.filter(k=>k.status==="pending").length,A=f.isPending;return a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:a.jsx(St,{className:"w-full max-w-2xl max-h-[90vh] flex flex-col",children:a.jsxs(Nt,{className:"p-0 flex flex-col h-full",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsx("h2",{className:"text-xl font-semibold text-white",children:n("uploadModal.title")}),a.jsx("button",{onClick:t,className:"text-bambu-gray hover:text-white transition-colors",children:a.jsx(Dt,{className:"w-5 h-5"})})]}),a.jsx("div",{className:"p-4",children:a.jsxs("div",{className:`border-2 border-dashed rounded-lg p-8 text-center transition-colors ${c?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary hover:border-bambu-gray"}`,onDragOver:p,onDragLeave:x,onDrop:v,children:[a.jsx(Oa,{className:"w-12 h-12 mx-auto mb-4 text-bambu-gray"}),a.jsx("p",{className:"text-white mb-2",children:n("uploadModal.dragDrop")}),a.jsx("p",{className:"text-bambu-gray text-sm mb-4",children:n("uploadModal.or")}),a.jsx(Me,{variant:"secondary",onClick:()=>s.current?.click(),disabled:A,children:n("uploadModal.browseFiles")}),a.jsx("input",{ref:s,type:"file",accept:".3mf",multiple:!0,className:"hidden",onChange:g})]})}),a.jsx("div",{className:"px-4 pb-4",children:a.jsx("p",{className:"text-xs text-bambu-gray",children:n("uploadModal.extractionInfo")})}),o.length>0&&a.jsx("div",{className:"px-4 pb-4 max-h-60 overflow-y-auto",children:a.jsx("div",{className:"space-y-2",children:o.map((k,P)=>a.jsxs("div",{className:"flex items-center gap-3 p-3 bg-bambu-dark rounded-lg",children:[a.jsx($C,{className:"w-5 h-5 text-bambu-gray flex-shrink-0"}),a.jsx("span",{className:"flex-1 text-white text-sm truncate",children:k.file.name}),a.jsxs("span",{className:"text-xs text-bambu-gray",children:[(k.file.size/(1024*1024)).toFixed(1)," MB"]}),k.status==="pending"&&a.jsx("button",{onClick:()=>y(P),className:"text-bambu-gray hover:text-red-400 transition-colors",disabled:A,children:a.jsx(Dt,{className:"w-4 h-4"})}),k.status==="uploading"&&a.jsx(at,{className:"w-4 h-4 text-bambu-green animate-spin"}),k.status==="success"&&a.jsx(yr,{className:"w-4 h-4 text-bambu-green"}),k.status==="error"&&a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-xs text-red-400",children:k.error}),a.jsx(Va,{className:"w-4 h-4 text-red-400"})]})]},`${k.file.name}-${P}`))})}),u&&a.jsx("div",{className:"px-4 pb-4",children:a.jsx("div",{className:"p-3 bg-bambu-dark rounded-lg",children:a.jsxs("p",{className:"text-sm text-white",children:[a.jsx("span",{className:"text-bambu-green",children:u.uploaded})," ",n("uploadModal.uploaded"),u.failed>0&&a.jsxs(a.Fragment,{children:[", ",a.jsx("span",{className:"text-red-400",children:u.failed})," ",n("uploadModal.failed")]})]})})}),a.jsxs("div",{className:"flex gap-3 p-4 border-t border-bambu-dark-tertiary",children:[a.jsx(Me,{variant:"secondary",onClick:t,className:"flex-1",children:n(u?"common.close":"common.cancel")}),!u&&a.jsx(Me,{onClick:_,disabled:N===0||A,className:"flex-1",children:A?a.jsxs(a.Fragment,{children:[a.jsx(at,{className:"w-4 h-4 animate-spin"}),n("uploadModal.uploading")]}):a.jsxs(a.Fragment,{children:[a.jsx(Oa,{className:"w-4 h-4"}),n("uploadModal.upload")," ",N>0&&`(${N})`]})})]})]})})})}const K$e=["adhesionFailure","spaghettiDetached","layerShift","cloggedNozzle","filamentRunout","warping","stringing","underExtrusion","powerFailure","userCancelled","other"],X$e=["completed","failed","aborted","printing"];function Ane({archive:t,onClose:e,existingTags:n=[]}){const{t:r}=Rt();w.useEffect(()=>{const se=ce=>{ce.key==="Escape"&&e()};return window.addEventListener("keydown",se),()=>window.removeEventListener("keydown",se)},[e]);const i=Qt(),[s,o]=w.useState(t.print_name||""),[l,c]=w.useState(t.printer_id),[d,u]=w.useState(t.project_id??null),[h,f]=w.useState(t.notes||""),[p,x]=w.useState(t.tags||""),[v,g]=w.useState(t.failure_reason||""),[y,_]=w.useState(t.status),[N,A]=w.useState(t.quantity??1),[k,P]=w.useState(t.photos||[]),[C,E]=w.useState(t.external_url||""),[M,j]=w.useState(!1),[B,L]=w.useState(!1),U=w.useRef(null),D=w.useRef(null),$=w.useRef(null),{data:G}=Ye({queryKey:["printers"],queryFn:J.getPrinters}),{data:z}=Ye({queryKey:["projects"],queryFn:()=>J.getProjects()}),{data:W}=Ye({queryKey:["tags"],queryFn:J.getTags,enabled:n.length===0}),K=n.length>0?n:W?.map(se=>se.name)||[],te=p.split(",").map(se=>se.trim()).filter(Boolean),H=p.includes(",")?p.substring(p.lastIndexOf(",")+1).trim().toLowerCase():p.trim().toLowerCase(),Y=K.filter(se=>!te.includes(se)&&(H===""||se.toLowerCase().includes(H))),Z=se=>{let ce;if(H&&!K.includes(H)?ce=p.includes(",")?p.substring(0,p.lastIndexOf(",")).split(",").map(Ce=>Ce.trim()).filter(Boolean):[]:ce=te,!ce.includes(se)){const Ce=[...ce,se].join(", ");x(Ce)}$.current!==null&&clearTimeout($.current),U.current?.focus()},ee=se=>{const ce=te.filter(Ce=>Ce!==se).join(", ");x(ce)},Se=it({mutationFn:se=>J.updateArchive(t.id,se),onSuccess:()=>{i.invalidateQueries({queryKey:["archives"]}),i.invalidateQueries({queryKey:["projects"]}),e()}}),oe=async se=>{const ce=se.target.files?.[0];if(ce){j(!0);try{const Ce=await J.uploadArchivePhoto(t.id,ce);P(Ce.photos),i.invalidateQueries({queryKey:["archives"]})}catch(Ce){console.error("Failed to upload photo:",Ce)}finally{j(!1),D.current&&(D.current.value="")}}},ie=async se=>{try{const ce=await J.deleteArchivePhoto(t.id,se);P(ce.photos||[]),i.invalidateQueries({queryKey:["archives"]})}catch(ce){console.error("Failed to delete photo:",ce)}},me=se=>{se.preventDefault();const ce={print_name:s||void 0,printer_id:l,project_id:d,notes:h||void 0,tags:p||void 0,quantity:N,external_url:C||null};y!==t.status&&(ce.status=y),y==="failed"||y==="aborted"?ce.failure_reason=v||void 0:(t.status==="failed"||t.status==="aborted")&&(ce.failure_reason=null),Se.mutate(ce)};return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:e,children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary w-full max-w-md max-h-[90vh] flex flex-col",onClick:se=>se.stopPropagation(),children:[a.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[a.jsx("h2",{className:"text-lg font-semibold text-white",children:r("editArchive.title")}),a.jsx("button",{onClick:e,className:"text-bambu-gray hover:text-white transition-colors",children:a.jsx(Dt,{className:"w-5 h-5"})})]}),a.jsxs("form",{onSubmit:me,className:"p-6 space-y-4 overflow-y-auto flex-1",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("editArchive.name")}),a.jsx("input",{type:"text",value:s,onChange:se=>o(se.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",placeholder:r("editArchive.namePlaceholder")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("editArchive.printer")}),a.jsxs("select",{value:l??"",onChange:se=>c(se.target.value?Number(se.target.value):null),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"",children:r("editArchive.noPrinter")}),G?.map(se=>a.jsx("option",{value:se.id,children:se.name},se.id))]})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[a.jsx(xs,{className:"w-4 h-4 inline mr-1"}),r("editArchive.project")]}),a.jsxs("select",{value:d??"",onChange:se=>u(se.target.value?Number(se.target.value):null),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"",children:r("editArchive.noProject")}),z?.map(se=>a.jsx("option",{value:se.id,children:se.name},se.id))]})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[a.jsx(Yme,{className:"w-4 h-4 inline mr-1"}),r("editArchive.itemsPrinted")]}),a.jsx("input",{type:"number",min:1,value:N,onChange:se=>A(Math.max(1,parseInt(se.target.value)||1)),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",placeholder:"1"}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:r("editArchive.itemsPrintedHelp")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("editArchive.notes")}),a.jsx("textarea",{value:h,onChange:se=>f(se.target.value),rows:3,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none resize-none",placeholder:r("editArchive.notesPlaceholder")})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[a.jsx(qb,{className:"w-4 h-4 inline mr-1"}),r("editArchive.externalLink")]}),a.jsx("input",{type:"url",value:C,onChange:se=>E(se.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",placeholder:"https://printables.com/model/..."}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:r("editArchive.externalLinkHelp")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("editArchive.tags")}),te.length>0&&a.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:te.map(se=>a.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 bg-bambu-dark-tertiary rounded text-sm text-white",children:[a.jsx(qh,{className:"w-3 h-3"}),se,a.jsx("button",{type:"button",onClick:()=>ee(se),className:"ml-0.5 text-bambu-gray hover:text-white",children:a.jsx(Dt,{className:"w-3 h-3"})})]},se))}),a.jsxs("div",{className:"relative",children:[a.jsx("input",{ref:U,type:"text",value:p,onChange:se=>x(se.target.value),onFocus:()=>{$.current!==null&&clearTimeout($.current),L(!0)},onBlur:()=>{$.current=window.setTimeout(()=>L(!1),200)},className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",placeholder:te.length>0?r("editArchive.addMoreTags"):r("editArchive.tagsPlaceholder")}),B&&Y.length>0&&a.jsxs("div",{className:"absolute top-full left-0 right-0 mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg z-10 max-h-40 overflow-y-auto",children:[a.jsxs("div",{className:"p-2 text-xs text-bambu-gray border-b border-bambu-dark-tertiary",children:[H?r("editArchive.matchingTags",{query:H}):r("editArchive.existingTags")," ",r("editArchive.clickToAdd")]}),a.jsx("div",{className:"p-2 flex flex-wrap gap-1.5",children:Y.map(se=>a.jsx("button",{type:"button",onClick:()=>Z(se),className:"px-2 py-0.5 bg-bambu-dark-tertiary hover:bg-bambu-green/20 rounded text-sm text-bambu-gray hover:text-white transition-colors",children:se},se))})]})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("editArchive.status")}),a.jsx("select",{value:y,onChange:se=>{_(se.target.value),se.target.value==="completed"&&g("")},className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:X$e.map(se=>a.jsx("option",{value:se,children:r(`editArchive.statuses.${se}`)},se))})]}),(y==="failed"||y==="aborted")&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("editArchive.failureReason")}),a.jsxs("select",{value:v,onChange:se=>g(se.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"",children:r("editArchive.selectReason")}),K$e.map(se=>a.jsx("option",{value:r(`editArchive.failureReasons.${se}`),children:r(`editArchive.failureReasons.${se}`)},se))]})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[a.jsx(db,{className:"w-4 h-4 inline mr-1"}),r("editArchive.photos")]}),a.jsxs("div",{className:"flex flex-wrap gap-2 mb-2",children:[k.map(se=>a.jsxs("div",{className:"relative group",children:[a.jsx("img",{src:J.getArchivePhotoUrl(t.id,se),alt:r("editArchive.printResult"),className:"w-20 h-20 object-cover rounded-lg border border-bambu-dark-tertiary"}),a.jsx("button",{type:"button",onClick:()=>ie(se),className:"absolute -top-1 -right-1 p-1 bg-red-500 rounded-full opacity-0 group-hover:opacity-100 transition-opacity",children:a.jsx(Yt,{className:"w-3 h-3 text-white"})})]},se)),a.jsxs("label",{className:"w-20 h-20 flex items-center justify-center border-2 border-dashed border-bambu-dark-tertiary rounded-lg cursor-pointer hover:border-bambu-green transition-colors",children:[a.jsx("input",{ref:D,type:"file",accept:"image/jpeg,image/png,image/webp",onChange:oe,className:"hidden",disabled:M}),M?a.jsx(at,{className:"w-6 h-6 text-bambu-gray animate-spin"}):a.jsx(Xn,{className:"w-6 h-6 text-bambu-gray"})]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:r("editArchive.photosHelp")})]}),a.jsxs("div",{className:"flex gap-3 pt-2",children:[a.jsx(Me,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:r("common.cancel")}),a.jsxs(Me,{type:"submit",disabled:Se.isPending,className:"flex-1",children:[a.jsx(bs,{className:"w-4 h-4"}),Se.isPending?r("common.saving"):r("common.save")]})]})]})]})})}function Tne({x:t,y:e,items:n,onClose:r}){const i=w.useRef(null),[s,o]=w.useState(null),l=w.useRef(null),[c,d]=w.useState({x:t,y:e,visible:!1}),[u,h]=w.useState(!1),[f,p]=w.useState({});w.useEffect(()=>{const g=N=>{i.current&&!i.current.contains(N.target)&&r()},y=N=>{N.key==="Escape"&&r()},_=()=>{r()};return document.addEventListener("mousedown",g),document.addEventListener("keydown",y),document.addEventListener("scroll",_,!0),()=>{document.removeEventListener("mousedown",g),document.removeEventListener("keydown",y),document.removeEventListener("scroll",_,!0),l.current&&clearTimeout(l.current)}},[r]),w.useLayoutEffect(()=>{if(i.current){i.current.style.visibility="hidden",i.current.style.display="block";const g=i.current.getBoundingClientRect(),y=window.innerWidth,_=window.innerHeight,N=8;let A=t,k=e;t+g.width>y-N&&(A=Math.max(N,y-g.width-N)),A_-N&&(k=Math.max(N,_-g.height-N)),kP),d({x:A,y:k,visible:!0})}},[t,e]);const x=(g,y)=>{l.current&&(clearTimeout(l.current),l.current=null);const _=y.getBoundingClientRect(),N=window.innerHeight,A=300,C=N-_.top-8A;p(E=>({...E,[g]:C?"bottom":"top"})),o(g)},v=()=>{l.current=window.setTimeout(()=>{o(null)},150)};return a.jsx("div",{ref:i,className:"fixed z-50 min-w-[180px] max-w-[280px] bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl py-1",style:{left:c.x,top:c.y,visibility:c.visible?"visible":"hidden"},children:n.map((g,y)=>{if(g.divider)return a.jsx("div",{className:"my-1 border-t border-bambu-dark-tertiary"},y);const _=g.submenu&&g.submenu.length>0;return a.jsxs("div",{className:"relative",onMouseEnter:N=>_&&x(y,N.currentTarget),onMouseLeave:()=>_&&v(),children:[a.jsxs("button",{onMouseEnter:N=>_&&x(y,N.currentTarget.parentElement),onClick:()=>{_?o(s===y?null:y):g.disabled||(g.onClick(),r())},disabled:g.disabled,title:g.title,className:`w-full flex items-center gap-2 px-3 py-2 text-sm text-left transition-colors ${g.disabled?"text-bambu-gray cursor-not-allowed":g.danger?"text-red-400 hover:bg-red-400/10":"text-white hover:bg-bambu-dark-tertiary"} ${_&&s===y?"bg-bambu-dark-tertiary":""}`,children:[g.icon&&a.jsx("span",{className:"w-4 h-4 flex-shrink-0 flex items-center justify-center",children:g.icon}),a.jsx("span",{className:"flex-1",children:g.label}),_&&a.jsx(pi,{className:"w-4 h-4 text-bambu-gray"})]}),_&&s===y&&a.jsx("div",{className:`absolute min-w-[160px] bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl py-1 overflow-hidden max-h-[300px] overflow-y-auto z-[60] ${u?"right-full mr-1":"left-full ml-1"} ${f[y]==="bottom"?"bottom-0":"top-0"}`,onMouseEnter:()=>{l.current&&(clearTimeout(l.current),l.current=null)},onMouseLeave:()=>v(),children:g.submenu.map((N,A)=>a.jsxs("button",{onClick:()=>{N.disabled||(N.onClick(),r())},disabled:N.disabled,className:`w-full flex items-center gap-2 px-3 py-2 text-sm text-left transition-colors ${N.disabled?"text-bambu-gray cursor-not-allowed":N.danger?"text-red-400 hover:bg-red-400/10":"text-white hover:bg-bambu-dark-tertiary"}`,children:[N.icon&&a.jsx("span",{className:"w-4 h-4 flex-shrink-0 flex items-center justify-center",children:N.icon}),N.label]},A))})]},y)})})}function Y$e({selectedIds:t,existingTags:e,onClose:n}){const r=Qt(),{showToast:i}=dn(),[s,o]=w.useState(""),[l,c]=w.useState(new Set),[d,u]=w.useState("add");w.useEffect(()=>{const v=g=>{g.key==="Escape"&&n()};return window.addEventListener("keydown",v),()=>window.removeEventListener("keydown",v)},[n]);const h=it({mutationFn:async()=>{const v=Array.from(l);let g=0;for(const y of t)try{const _=await J.getArchive(y),N=_.tags?_.tags.split(",").map(k=>k.trim()).filter(Boolean):[];let A;d==="add"?A=[...new Set([...N,...v])]:A=N.filter(k=>!l.has(k)),await J.updateArchive(y,{tags:A.join(", ")}),g++}catch(_){throw console.error(`Failed to update archive ${y}:`,_),new Error(`Failed on archive ${y}: ${_ instanceof Error?_.message:"Unknown error"}`)}return{count:g,mode:d,tags:v}},onSuccess:({count:v,mode:g,tags:y})=>{r.invalidateQueries({queryKey:["archives"]}),i(`${g==="add"?"Added":"Removed"} ${y.length} tag${y.length!==1?"s":""} ${g==="add"?"to":"from"} ${v} archive${v!==1?"s":""}`),n()},onError:v=>{i(v.message||"Failed to update tags","error")}}),f=v=>{c(g=>{const y=new Set(g);return y.has(v)?y.delete(v):y.add(v),y})},p=()=>{s.trim()&&!l.has(s.trim())&&(c(v=>new Set([...v,s.trim()])),o(""))},x=v=>{v.key==="Enter"&&(v.preventDefault(),p())};return a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:a.jsx(St,{className:"w-full max-w-md",children:a.jsxs(Nt,{className:"p-0",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(qh,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-xl font-semibold text-white",children:d==="add"?"Add Tags":"Remove Tags"})]}),a.jsx("button",{onClick:n,className:"text-bambu-gray hover:text-white transition-colors",children:a.jsx(Dt,{className:"w-5 h-5"})})]}),a.jsxs("div",{className:"p-4 space-y-4",children:[a.jsxs("p",{className:"text-sm text-bambu-gray",children:[d==="add"?"Add":"Remove"," tags for ",t.length," selected archive",t.length!==1?"s":""]}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx(Me,{size:"sm",variant:d==="add"?"primary":"secondary",onClick:()=>u("add"),children:"Add Tags"}),a.jsx(Me,{size:"sm",variant:d==="remove"?"primary":"secondary",onClick:()=>u("remove"),children:"Remove Tags"})]}),d==="add"&&a.jsxs("div",{className:"flex gap-2",children:[a.jsx("input",{type:"text",placeholder:"Enter new tag...",className:"flex-1 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",value:s,onChange:v=>o(v.target.value),onKeyDown:x}),a.jsx(Me,{size:"sm",variant:"secondary",onClick:p,disabled:!s.trim(),children:a.jsx(Xn,{className:"w-4 h-4"})})]}),e.length>0&&a.jsxs("div",{children:[a.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:"Existing tags:"}),a.jsx("div",{className:"flex flex-wrap gap-2",children:e.map(v=>a.jsx("button",{onClick:()=>f(v),className:`px-2 py-1 rounded text-sm transition-colors ${l.has(v)?"bg-bambu-green text-white":"bg-bambu-dark-tertiary text-bambu-gray-light hover:bg-bambu-dark"}`,children:v},v))})]}),l.size>0&&a.jsxs("div",{children:[a.jsxs("p",{className:"text-xs text-bambu-gray mb-2",children:["Tags to ",d==="add"?"add":"remove",":"]}),a.jsx("div",{className:"flex flex-wrap gap-2",children:Array.from(l).map(v=>a.jsxs("span",{className:`px-2 py-1 rounded text-sm flex items-center gap-1 ${d==="add"?"bg-green-500/20 text-green-400":"bg-red-500/20 text-red-400"}`,children:[v,a.jsx("button",{onClick:()=>f(v),className:"hover:opacity-70",children:a.jsx(Dt,{className:"w-3 h-3"})})]},v))})]})]}),a.jsxs("div",{className:"flex gap-3 p-4 border-t border-bambu-dark-tertiary",children:[a.jsx(Me,{variant:"secondary",onClick:n,className:"flex-1",children:"Cancel"}),a.jsx(Me,{onClick:()=>h.mutate(),disabled:l.size===0||h.isPending,className:"flex-1",children:h.isPending?a.jsxs(a.Fragment,{children:[a.jsx(at,{className:"w-4 h-4 animate-spin"}),"Processing..."]}):a.jsxs(a.Fragment,{children:[a.jsx(qh,{className:"w-4 h-4"}),d==="add"?"Add Tags":"Remove Tags"]})})]})]})})})}function Q$e({selectedIds:t,onClose:e}){const n=Qt(),{showToast:r}=dn(),{data:i,isLoading:s}=Ye({queryKey:["projects"],queryFn:()=>J.getProjects()});w.useEffect(()=>{const u=h=>{h.key==="Escape"&&e()};return window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)},[e]);const o=()=>{n.invalidateQueries({queryKey:["archives"]}),n.invalidateQueries({queryKey:["projects"]}),n.invalidateQueries({queryKey:["project"]}),n.invalidateQueries({queryKey:["project-archives"]})},l=it({mutationFn:async u=>(await J.addArchivesToProject(u,t),u),onSuccess:u=>{const h=i?.find(f=>f.id===u);o(),r(`Added ${t.length} archive${t.length!==1?"s":""} to "${h?.name}"`),e()},onError:()=>{r("Failed to assign project","error")}}),c=it({mutationFn:async()=>{for(const u of t)await J.updateArchive(u,{project_id:null});return t.length},onSuccess:u=>{o(),r(`Removed ${u} archive${u!==1?"s":""} from project`),e()},onError:()=>{r("Failed to remove from project","error")}}),d=l.isPending||c.isPending;return a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:a.jsx(St,{className:"w-full max-w-md max-h-[80vh] flex flex-col",children:a.jsxs(Nt,{className:"p-0 flex flex-col min-h-0",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary shrink-0",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(xs,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-xl font-semibold text-white",children:"Assign to Project"})]}),a.jsx("button",{onClick:e,className:"text-bambu-gray hover:text-white transition-colors",disabled:d,children:a.jsx(Dt,{className:"w-5 h-5"})})]}),a.jsxs("div",{className:"p-4 space-y-3 overflow-y-auto min-h-0",children:[a.jsxs("p",{className:"text-sm text-bambu-gray",children:["Assign ",t.length," selected archive",t.length!==1?"s":""," to a project"]}),s?a.jsx("div",{className:"flex items-center justify-center py-8",children:a.jsx(at,{className:"w-6 h-6 animate-spin text-bambu-gray"})}):a.jsxs("div",{className:"space-y-2",children:[a.jsxs("button",{onClick:()=>c.mutate(),disabled:d,className:"w-full flex items-center gap-3 p-3 rounded-lg bg-bambu-dark hover:bg-bambu-dark-tertiary border border-bambu-dark-tertiary transition-colors text-left disabled:opacity-50",children:[a.jsx("div",{className:"w-8 h-8 rounded-full bg-red-500/20 flex items-center justify-center shrink-0",children:a.jsx(mi,{className:"w-4 h-4 text-red-400"})}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:"text-white font-medium",children:"Remove from project"}),a.jsx("p",{className:"text-sm text-bambu-gray truncate",children:"Clear project assignment"})]}),c.isPending&&a.jsx(at,{className:"w-4 h-4 animate-spin text-bambu-gray shrink-0"})]}),i&&i.length>0&&a.jsxs("div",{className:"flex items-center gap-2 py-2",children:[a.jsx("div",{className:"flex-1 h-px bg-bambu-dark-tertiary"}),a.jsx("span",{className:"text-xs text-bambu-gray",children:"or assign to"}),a.jsx("div",{className:"flex-1 h-px bg-bambu-dark-tertiary"})]}),i?.map(u=>a.jsxs("button",{onClick:()=>l.mutate(u.id),disabled:d,className:"w-full flex items-center gap-3 p-3 rounded-lg bg-bambu-dark hover:bg-bambu-dark-tertiary border border-bambu-dark-tertiary transition-colors text-left disabled:opacity-50",children:[a.jsx("div",{className:"w-8 h-8 rounded-full flex items-center justify-center shrink-0",style:{backgroundColor:u.color?`${u.color}20`:"rgb(var(--bambu-green) / 0.2)"},children:a.jsx(xs,{className:"w-4 h-4",style:{color:u.color||"rgb(var(--bambu-green))"}})}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:"text-white font-medium truncate",children:u.name}),a.jsxs("p",{className:"text-sm text-bambu-gray truncate",children:[u.archive_count," archive",u.archive_count!==1?"s":"",u.status&&` • ${u.status}`]})]}),l.isPending&&l.variables===u.id&&a.jsx(at,{className:"w-4 h-4 animate-spin text-bambu-gray shrink-0"})]},u.id)),(!i||i.length===0)&&a.jsx("p",{className:"text-center text-bambu-gray py-4",children:"No projects yet. Create one from the Projects page."})]})]}),a.jsx("div",{className:"flex gap-3 p-4 border-t border-bambu-dark-tertiary shrink-0",children:a.jsx(Me,{variant:"secondary",onClick:e,className:"flex-1",disabled:d,children:"Cancel"})})]})})})}function Z$e(t,e){return new Date(t,e+1,0).getDate()}function J$e(t,e){return new Date(t,e,1).getDay()}const eVe=["January","February","March","April","May","June","July","August","September","October","November","December"],tVe=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];function nVe({archives:t,onArchiveClick:e,highlightedArchiveId:n}){const r=new Date,[i,s]=w.useState(r.getMonth()),[o,l]=w.useState(r.getFullYear()),[c,d]=w.useState(null),[u,h]=w.useState(null),f=w.useMemo(()=>{const k=new Map;return t.forEach(P=>{const C=tr(P.completed_at||P.created_at)||new Date,E=`${C.getFullYear()}-${String(C.getMonth()+1).padStart(2,"0")}-${String(C.getDate()).padStart(2,"0")}`,M=k.get(E)||[];M.push(P),k.set(E,M)}),k},[t]),p=Z$e(o,i),x=J$e(o,i),v=()=>{i===0?(s(11),l(o-1)):s(i-1)},g=()=>{i===11?(s(0),l(o+1)):s(i+1)},y=()=>{s(r.getMonth()),l(r.getFullYear())},_=[];for(let k=0;k