diff --git a/frontend/src/pages/spoolbuddy/SpoolBuddyAmsPage.tsx b/frontend/src/pages/spoolbuddy/SpoolBuddyAmsPage.tsx index 277326803..ab5f8d50d 100644 --- a/frontend/src/pages/spoolbuddy/SpoolBuddyAmsPage.tsx +++ b/frontend/src/pages/spoolbuddy/SpoolBuddyAmsPage.tsx @@ -678,20 +678,8 @@ export function SpoolBuddyAmsPage() { - {/* Inventory: Assign / Unassign */} - {!spoolmanEnabled && ( - - )} - {!spoolmanEnabled && assignment && ( + {/* Inventory: Assign or Unassign */} + {!spoolmanEnabled && (assignment ? ( - )} - - {/* Spoolman: Link / Unlink */} - {spoolmanEnabled && ( + ) : ( - )} - {spoolmanEnabled && linked?.id && ( + ))} + + {/* Spoolman: Link or Unlink */} + {spoolmanEnabled && (linked?.id ? ( - )} + ) : ( + + ))} diff --git a/static/assets/index-Dh0_3dIz.js b/static/assets/index-BsSJ-PqL.js similarity index 99% rename from static/assets/index-Dh0_3dIz.js rename to static/assets/index-BsSJ-PqL.js index 63659dd73..4e44fcc04 100644 --- a/static/assets/index-Dh0_3dIz.js +++ b/static/assets/index-BsSJ-PqL.js @@ -8726,5 +8726,5 @@ Difference: ${l}g (mismatch!)`;return i.jsxs("div",{className:`flex items-center In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)})()}function f(V,J){if(V){if(typeof V=="string")return y(V,J);var D={}.toString.call(V).slice(8,-1);return D==="Object"&&V.constructor&&(D=V.constructor.name),D==="Map"||D==="Set"?Array.from(V):D==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(D)?y(V,J):void 0}}function y(V,J){(J==null||J>V.length)&&(J=V.length);for(var D=0,E=Array(J);D"u"||"remove"in Element.prototype||(Element.prototype.remove=function(){this.parentNode&&this.parentNode.removeChild(this)}),typeof self<"u"&&"document"in self&&((!("classList"in document.createElement("_"))||document.createElementNS&&!("classList"in document.createElementNS("http://www.w3.org/2000/svg","g")))&&(function(V){if("Element"in V){var J="classList",D="prototype",E=V.Element[D],U=Object,W=String[D].trim||function(){return this.replace(/^\s+|\s+$/g,"")},B=Array[D].indexOf||function(oe){for(var he=0,fe=this.length;he2&&arguments[2]!==void 0&&arguments[2]?Object.assign({},this.getDefaultDiplay(),U):U||this.getDefaultDiplay())[E]||E}},{key:"getUpdatedInput",value:function(E,U,W){var B=arguments.length>3&&arguments[3]!==void 0?arguments[3]:W,ie=arguments.length>4&&arguments[4]!==void 0&&arguments[4],O=this.getOptions(),$=[W,B,ie],Y=U;return(E==="{bksp}"||E==="{backspace}")&&Y.length>0?Y=this.removeAt.apply(this,[Y].concat($)):(E==="{delete}"||E==="{forwarddelete}")&&Y.length>0?Y=this.removeForwardsAt.apply(this,[Y].concat($)):E==="{space}"?Y=this.addStringAt.apply(this,[Y," "].concat($)):E!=="{tab}"||typeof O.tabCharOnTab=="boolean"&&O.tabCharOnTab===!1?E!=="{enter}"&&E!=="{numpadenter}"||!O.newLineOnEnter?E.includes("numpad")&&Number.isInteger(Number(E[E.length-2]))?Y=this.addStringAt.apply(this,[Y,E[E.length-2]].concat($)):E==="{numpaddivide}"?Y=this.addStringAt.apply(this,[Y,"/"].concat($)):E==="{numpadmultiply}"?Y=this.addStringAt.apply(this,[Y,"*"].concat($)):E==="{numpadsubtract}"?Y=this.addStringAt.apply(this,[Y,"-"].concat($)):E==="{numpadadd}"?Y=this.addStringAt.apply(this,[Y,"+"].concat($)):E==="{numpaddecimal}"?Y=this.addStringAt.apply(this,[Y,"."].concat($)):E==="{"||E==="}"?Y=this.addStringAt.apply(this,[Y,E].concat($)):E.includes("{")||E.includes("}")||(Y=this.addStringAt.apply(this,[Y,E].concat($))):Y=this.addStringAt.apply(this,[Y,` `].concat($)):Y=this.addStringAt.apply(this,[Y," "].concat($)),O.debug&&console.log("Input will be: "+Y),Y}},{key:"updateCaretPos",value:function(E){var U=arguments.length>1&&arguments[1]!==void 0&&arguments[1],W=this.updateCaretPosAction(E,U);this.dispatch((function(B){B.setCaretPosition(W)}))}},{key:"updateCaretPosAction",value:function(E){var U=arguments.length>1&&arguments[1]!==void 0&&arguments[1],W=this.getOptions(),B=this.getCaretPosition();return B!=null&&(U?B>0&&(B-=E):B+=E),W.debug&&console.log("Caret at:",B),B}},{key:"addStringAt",value:function(E,U){var W,B=arguments.length>2&&arguments[2]!==void 0?arguments[2]:E.length,ie=arguments.length>3&&arguments[3]!==void 0?arguments[3]:E.length,O=arguments.length>4&&arguments[4]!==void 0&&arguments[4];return B||B===0?(W=[E.slice(0,B),U,E.slice(ie)].join(""),this.isMaxLengthReached()||O&&this.updateCaretPos(U.length)):W=E+U,W}},{key:"removeAt",value:function(E){var U,W=arguments.length>1&&arguments[1]!==void 0?arguments[1]:E.length,B=arguments.length>2&&arguments[2]!==void 0?arguments[2]:E.length,ie=arguments.length>3&&arguments[3]!==void 0&&arguments[3];if(W===0&&B===0)return E;if(W===B){var O=/([\uD800-\uDBFF][\uDC00-\uDFFF])/g;W&&W>=0?E.substring(W-2,W).match(O)?(U=E.substr(0,W-2)+E.substr(W),ie&&this.updateCaretPos(2,!0)):(U=E.substr(0,W-1)+E.substr(W),ie&&this.updateCaretPos(1,!0)):E.slice(-2).match(O)?(U=E.slice(0,-2),ie&&this.updateCaretPos(2,!0)):(U=E.slice(0,-1),ie&&this.updateCaretPos(1,!0))}else U=E.slice(0,W)+E.slice(B),ie&&this.dispatch((function($){$.setCaretPosition(W)}));return U}},{key:"removeForwardsAt",value:function(E){var U,W=arguments.length>1&&arguments[1]!==void 0?arguments[1]:E.length,B=arguments.length>2&&arguments[2]!==void 0?arguments[2]:E.length,ie=arguments.length>3&&arguments[3]!==void 0&&arguments[3];return E!=null&&E.length&&W!==null?(W===B?U=E.substring(W,W+2).match(/([\uD800-\uDBFF][\uDC00-\uDFFF])/g)?E.substr(0,W)+E.substr(W+2):E.substr(0,W)+E.substr(W+1):(U=E.slice(0,W)+E.slice(B),ie&&this.dispatch((function(O){O.setCaretPosition(W)}))),U):E}},{key:"handleMaxLength",value:function(E,U){var W=this.getOptions(),B=W.maxLength,ie=E[W.inputName||"default"],O=U.length-1>=B;if(U.length<=ie.length)return!1;if(Number.isInteger(B))return W.debug&&console.log("maxLength (num) reached:",O),O?(this.maxLengthReached=!0,!0):(this.maxLengthReached=!1,!1);if(v(B)==="object"){var $=U.length-1>=B[W.inputName||"default"];return W.debug&&console.log("maxLength (obj) reached:",$),$?(this.maxLengthReached=!0,!0):(this.maxLengthReached=!1,!1)}}},{key:"isMaxLengthReached",value:function(){return!!this.maxLengthReached}},{key:"isTouchDevice",value:function(){return"ontouchstart"in window||navigator.maxTouchPoints}},{key:"pointerEventsSupported",value:function(){return!!window.PointerEvent}},{key:"camelCase",value:function(E){return E?E.toLowerCase().trim().split(/[.\-_\s]/g).reduce((function(U,W){return W.length?U+W[0].toUpperCase()+W.slice(1):U})):""}},{key:"chunkArray",value:function(E,U){return p(Array(Math.ceil(E.length/U))).map((function(W,B){return E.slice(U*B,U+U*B)}))}},{key:"escapeRegex",value:function(E){return E.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&")}},{key:"getRtlOffset",value:function(E,U){var W=E,B=U.indexOf("‫");return B=O.length?{done:!0}:{done:!1,value:O[q++]}},e:function(re){throw re},f:te}}throw new TypeError(`Invalid attempt to iterate non-iterable instance. In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var oe,he=!0,fe=!1;return{s:function(){Y=Y.call(O)},n:function(){var re=Y.next();return he=re.done,re},e:function(re){fe=!0,oe=re},f:function(){try{he||Y.return==null||Y.return()}finally{if(fe)throw oe}}}})(Object.getOwnPropertyNames(E.prototype));try{for(B.s();!(W=B.n()).done;){var ie=W.value;ie==="constructor"||ie==="bindMethods"||(U[ie]=U[ie].bind(U))}}catch(O){B.e(O)}finally{B.f()}}}],J&&b(V.prototype,J),D&&b(V,D),Object.defineProperty(V,"prototype",{writable:!1}),V;var V,J,D})();g(k,"noop",(function(){}));var C=k;function N(V){return N=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(J){return typeof J}:function(J){return J&&typeof Symbol=="function"&&J.constructor===Symbol&&J!==Symbol.prototype?"symbol":typeof J},N(V)}function P(V,J){for(var D=0;D1?(U=W)===null||U===void 0?void 0:U.toLowerCase():W}},{key:"keyCodeToKey",value:function(E){return{8:"Backspace",9:"Tab",13:"Enter",16:"Shift",17:"Ctrl",18:"Alt",19:"Pause",20:"CapsLock",27:"Esc",32:"Space",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",45:"Insert",46:"Delete",48:"0",49:"1",50:"2",51:"3",52:"4",53:"5",54:"6",55:"7",56:"8",57:"9",65:"A",66:"B",67:"C",68:"D",69:"E",70:"F",71:"G",72:"H",73:"I",74:"J",75:"K",76:"L",77:"M",78:"N",79:"O",80:"P",81:"Q",82:"R",83:"S",84:"T",85:"U",86:"V",87:"W",88:"X",89:"Y",90:"Z",91:"Meta",96:"Numpad0",97:"Numpad1",98:"Numpad2",99:"Numpad3",100:"Numpad4",101:"Numpad5",102:"Numpad6",103:"Numpad7",104:"Numpad8",105:"Numpad9",106:"NumpadMultiply",107:"NumpadAdd",109:"NumpadSubtract",110:"NumpadDecimal",111:"NumpadDivide",112:"F1",113:"F2",114:"F3",115:"F4",116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"NumLock",145:"ScrollLock",186:";",187:"=",188:",",189:"-",190:".",191:"/",192:"`",219:"[",220:"\\",221:"]",222:"'"}[E]||""}}],J&&P(V.prototype,J),D&&P(V,D),Object.defineProperty(V,"prototype",{writable:!1}),V;var V,J,D})();function F(V){return F=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(J){return typeof J}:function(J){return J&&typeof Symbol=="function"&&J.constructor===Symbol&&J!==Symbol.prototype?"symbol":typeof J},F(V)}function G(V,J){for(var D=0;D0&&arguments[0]!==void 0?arguments[0]:we();return Y(R,me)},q.appendChild(ve)}));var te=O>0,oe=document.createElement("div");oe.classList.add("hg-candidate-box-prev"),te&&oe.classList.add("hg-candidate-box-btn-active");var he=function(){te&&W.renderPage({candidateListPages:B,targetElement:ie,pageIndex:O-1,nbPages:$,onItemSelected:Y})};this.options.useTouchEvents?oe.ontouchstart=he:oe.onclick=he,this.candidateBoxElement.appendChild(oe),this.candidateBoxElement.appendChild(q);var fe=O<$-1,re=document.createElement("div");re.classList.add("hg-candidate-box-next"),fe&&re.classList.add("hg-candidate-box-btn-active");var L=function(){fe&&W.renderPage({candidateListPages:B,targetElement:ie,pageIndex:O+1,nbPages:$,onItemSelected:Y})};this.options.useTouchEvents?re.ontouchstart=L:re.onclick=L,this.candidateBoxElement.appendChild(re),ie.prepend(this.candidateBoxElement)}}],J&&G(V.prototype,J),D&&G(V,D),Object.defineProperty(V,"prototype",{writable:!1}),V;var V,J,D})(),ee=I;function ae(V){return(function(J){if(Array.isArray(J))return X(J)})(V)||(function(J){if(typeof Symbol<"u"&&J[Symbol.iterator]!=null||J["@@iterator"]!=null)return Array.from(J)})(V)||(function(J,D){if(J){if(typeof J=="string")return X(J,D);var E={}.toString.call(J).slice(8,-1);return E==="Object"&&J.constructor&&(E=J.constructor.name),E==="Map"||E==="Set"?Array.from(J):E==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(E)?X(J,D):void 0}})(V)||(function(){throw new TypeError(`Invalid attempt to spread non-iterable instance. -In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)})()}function X(V,J){(J==null||J>V.length)&&(J=V.length);for(var D=0,E=Array(J);D1&&arguments[1]!==void 0?arguments[1]:E;this.caretPosition=E,this.caretPositionEnd=U}},{key:"getInputCandidates",value:function(E){var U=this,W=this.options,B=W.layoutCandidates,ie=W.layoutCandidatesCaseSensitiveMatch;if(!B||ce(B)!=="object")return{};var O=Object.keys(B).filter((function(q){var te=E.substring(0,U.getCaretPositionEnd()||0)||E,oe=new RegExp("".concat(U.utilities.escapeRegex(q),"$"),ie?"g":"gi");return!!ae(te.matchAll(oe)).length}));if(O.length>1){var $=O.sort((function(q,te){return te.length-q.length}))[0];return{candidateKey:$,candidateValue:B[$]}}if(O.length){var Y=O[0];return{candidateKey:Y,candidateValue:B[Y]}}return{}}},{key:"showCandidatesBox",value:function(E,U,W){var B=this;this.candidateBox&&this.candidateBox.show({candidateValue:U,targetElement:W,onSelect:function(ie,O){var $=B.options,Y=$.layoutCandidatesCaseSensitiveMatch,q=$.disableCandidateNormalization,te=$.enableLayoutCandidatesKeyPress,oe=ie;q||(oe=ie.normalize("NFD")),typeof B.options.beforeInputUpdate=="function"&&B.options.beforeInputUpdate(B);var he=B.getInput(B.options.inputName,!0),fe=B.getCaretPositionEnd()||0,re=he.substring(0,fe||0)||he,L=new RegExp("".concat(B.utilities.escapeRegex(E),"$"),Y?"g":"gi"),R=re.replace(L,oe),ne=he.replace(re,R),ve=R.length-re.length,we=(fe||he.length)+ve;we<0&&(we=0),B.setInput(ne,B.options.inputName,!0),B.setCaretPosition(we),te&&typeof B.options.onKeyPress=="function"&&B.options.onKeyPress(ie,O),typeof B.options.onChange=="function"&&B.options.onChange(B.getInput(B.options.inputName,!0),O),typeof B.options.onChangeAll=="function"&&B.options.onChangeAll(B.getAllInputs(),O)}})}},{key:"handleButtonClicked",value:function(E,U){var W=this.options,B=W.inputName,ie=B===void 0?this.defaultName:B,O=W.debug;if(E!=="{//}"){this.input[ie]||(this.input[ie]=""),typeof this.options.beforeInputUpdate=="function"&&this.options.beforeInputUpdate(this);var $=this.utilities.getUpdatedInput(E,this.input[ie],this.caretPosition,this.caretPositionEnd);if(this.utilities.isStandardButton(E)&&this.activeInputElement&&this.input[ie]&&this.input[ie]===$&&this.caretPosition===0&&this.caretPositionEnd===$.length)return this.setInput("",this.options.inputName,!0),this.setCaretPosition(0),this.activeInputElement.value="",this.activeInputElement.setSelectionRange(0,0),void this.handleButtonClicked(E,U);if(typeof this.options.onKeyPress=="function"&&this.options.onKeyPress(E,U),this.input[ie]!==$&&(!this.options.inputPattern||this.options.inputPattern&&this.inputPatternIsValid($))){if(this.options.maxLength&&this.utilities.handleMaxLength(this.input,$))return;var Y=this.utilities.getUpdatedInput(E,this.input[ie],this.caretPosition,this.caretPositionEnd,!0);if(this.setInput(Y,this.options.inputName,!0),O&&console.log("Input changed:",this.getAllInputs()),this.options.debug&&console.log("Caret at: ",this.getCaretPosition(),this.getCaretPositionEnd(),"(".concat(this.keyboardDOMClass,")"),U?.type),this.options.syncInstanceInputs&&this.syncInstanceInputs(),typeof this.options.onChange=="function"&&this.options.onChange(this.getInput(this.options.inputName,!0),U),typeof this.options.onChangeAll=="function"&&this.options.onChangeAll(this.getAllInputs(),U),U!=null&&U.target&&this.options.enableLayoutCandidates){var q,te=this.getInputCandidates($),oe=te.candidateKey,he=te.candidateValue;oe&&he?this.showCandidatesBox(oe,he,this.keyboardDOM):(q=this.candidateBox)===null||q===void 0||q.destroy()}}this.caretPositionEnd&&this.caretPosition!==this.caretPositionEnd&&(this.setCaretPosition(this.caretPositionEnd,this.caretPositionEnd),this.activeInputElement&&this.activeInputElement.setSelectionRange(this.caretPositionEnd,this.caretPositionEnd),this.options.debug&&console.log("Caret position aligned",this.caretPosition)),O&&console.log("Key pressed:",E)}}},{key:"getMouseHold",value:function(){return this.isMouseHold}},{key:"setMouseHold",value:function(E){this.options.syncInstanceInputs?this.dispatch((function(U){U.isMouseHold=E})):this.isMouseHold=E}},{key:"handleButtonMouseDown",value:function(E,U){var W=this;U&&(this.options.preventMouseDownDefault&&U.preventDefault(),this.options.stopMouseDownPropagation&&U.stopPropagation(),U.target.classList.add(this.activeButtonClass)),this.holdInteractionTimeout&&clearTimeout(this.holdInteractionTimeout),this.holdTimeout&&clearTimeout(this.holdTimeout),this.setMouseHold(!0),this.options.disableButtonHold||(this.holdTimeout=window.setTimeout((function(){(W.getMouseHold()&&(!E.includes("{")&&!E.includes("}")||E==="{delete}"||E==="{backspace}"||E==="{bksp}"||E==="{space}"||E==="{tab}")||E==="{arrowright}"||E==="{arrowleft}"||E==="{arrowup}"||E==="{arrowdown}")&&(W.options.debug&&console.log("Button held:",E),W.handleButtonHold(E)),clearTimeout(W.holdTimeout)}),500))}},{key:"handleButtonMouseUp",value:function(E,U){var W=this;U&&(this.options.preventMouseUpDefault&&U.preventDefault&&U.preventDefault(),this.options.stopMouseUpPropagation&&U.stopPropagation&&U.stopPropagation(),!(U.target===this.keyboardDOM||U.target&&this.keyboardDOM.contains(U.target)||this.candidateBox&&this.candidateBox.candidateBoxElement&&(U.target===this.candidateBox.candidateBoxElement||U.target&&this.candidateBox.candidateBoxElement.contains(U.target)))&&this.candidateBox&&this.candidateBox.destroy()),this.recurseButtons((function(B){B.classList.remove(W.activeButtonClass)})),this.setMouseHold(!1),this.holdInteractionTimeout&&clearTimeout(this.holdInteractionTimeout),E&&typeof this.options.onKeyReleased=="function"&&this.options.onKeyReleased(E,U)}},{key:"handleKeyboardContainerMouseDown",value:function(E){this.options.preventMouseDownDefault&&E.preventDefault()}},{key:"handleButtonHold",value:function(E){var U=this;this.holdInteractionTimeout&&clearTimeout(this.holdInteractionTimeout),this.holdInteractionTimeout=window.setTimeout((function(){U.getMouseHold()?(U.handleButtonClicked(E),U.handleButtonHold(E)):clearTimeout(U.holdInteractionTimeout)}),100)}},{key:"syncInstanceInputs",value:function(){var E=this;this.dispatch((function(U){U.replaceInput(E.input),U.setCaretPosition(E.caretPosition,E.caretPositionEnd)}))}},{key:"clearInput",value:function(){var E=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.options.inputName||this.defaultName;this.input[E]="",this.setCaretPosition(0),this.options.syncInstanceInputs&&this.syncInstanceInputs()}},{key:"getInput",value:function(){var E=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.options.inputName||this.defaultName,U=arguments.length>1&&arguments[1]!==void 0&&arguments[1];return this.options.syncInstanceInputs&&!U&&this.syncInstanceInputs(),this.options.rtl?"‫"+this.input[E].replace("‫","").replace("‬","")+"‬":this.input[E]}},{key:"getAllInputs",value:function(){var E=this,U={};return Object.keys(this.input).forEach((function(W){U[W]=E.getInput(W,!0)})),U}},{key:"setInput",value:function(E){var U=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.options.inputName||this.defaultName,W=arguments.length>2?arguments[2]:void 0;this.input[U]=E,!W&&this.options.syncInstanceInputs&&this.syncInstanceInputs()}},{key:"replaceInput",value:function(E){this.input=E}},{key:"setOptions",value:function(){var E=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},U=this.changedOptions(E);this.options=Object.assign(this.options,E),U.length&&(this.options.debug&&console.log("changedOptions",U),this.onSetOptions(U),this.render())}},{key:"changedOptions",value:function(E){var U=this;return Object.keys(E).filter((function(W){return JSON.stringify(E[W])!==JSON.stringify(U.options[W])}))}},{key:"onSetOptions",value:function(){var E=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];E.includes("layoutName")&&this.candidateBox&&this.candidateBox.destroy(),(E.includes("layoutCandidatesPageSize")||E.includes("layoutCandidates"))&&this.candidateBox&&(this.candidateBox.destroy(),this.candidateBox=new ee({utilities:this.utilities,options:this.options}))}},{key:"resetRows",value:function(){this.keyboardRowsDOM&&this.keyboardRowsDOM.remove(),this.keyboardDOM.className=this.keyboardDOMClass,this.keyboardDOM.setAttribute("data-skInstance",this.currentInstanceName),this.buttonElements={}}},{key:"dispatch",value:function(E){if(!window.SimpleKeyboardInstances)throw console.warn("SimpleKeyboardInstances is not defined. Dispatch cannot be called."),new Error("INSTANCES_VAR_ERROR");return Object.keys(window.SimpleKeyboardInstances).forEach((function(U){E(window.SimpleKeyboardInstances[U],U)}))}},{key:"addButtonTheme",value:function(E,U){var W=this;U&&E&&(E.split(" ").forEach((function(B){U.split(" ").forEach((function(ie){W.options.buttonTheme||(W.options.buttonTheme=[]);var O=!1;W.options.buttonTheme.map((function($){if($!=null&&$.class.split(" ").includes(ie)){O=!0;var Y=$.buttons.split(" ");Y.includes(B)||(O=!0,Y.push(B),$.buttons=Y.join(" "))}return $})),O||W.options.buttonTheme.push({class:ie,buttons:E})}))})),this.render())}},{key:"removeButtonTheme",value:function(E,U){var W=this;if(!E&&!U)return this.options.buttonTheme=[],void this.render();E&&Array.isArray(this.options.buttonTheme)&&this.options.buttonTheme.length&&(E.split(" ").forEach((function(B){var ie;(ie=W.options)===null||ie===void 0||(ie=ie.buttonTheme)===null||ie===void 0||ie.map((function(O,$){if(O&&U&&U.includes(O.class)||!U){var Y,q,te=(Y=O)===null||Y===void 0?void 0:Y.buttons.split(" ").filter((function(oe){return oe!==B}));O&&te!=null&&te.length?O.buttons=te.join(" "):((q=W.options.buttonTheme)===null||q===void 0||q.splice($,1),O=null)}return O}))})),this.render())}},{key:"getButtonElement",value:function(E){var U,W=this.buttonElements[E];return W&&(U=W.length>1?W:W[0]),U}},{key:"inputPatternIsValid",value:function(E){var U,W=this.options.inputPattern;if((U=W instanceof RegExp?W:W[this.options.inputName||this.defaultName])&&E){var B=U.test(E);return this.options.debug&&console.log('inputPattern ("'.concat(U,'"): ').concat(B?"passed":"did not pass!")),B}return!0}},{key:"setEventListeners",value:function(){if(this.isFirstKeyboardInstance||!this.allKeyboardInstances){this.options.debug&&console.log("Caret handling started (".concat(this.keyboardDOMClass,")"));var E=this.options.physicalKeyboardHighlightPreventDefault,U=E!==void 0&&E;document.addEventListener("keyup",this.handleKeyUp,U),document.addEventListener("keydown",this.handleKeyDown,U),document.addEventListener("mouseup",this.handleMouseUp),document.addEventListener("touchend",this.handleTouchEnd),this.options.updateCaretOnSelectionChange&&document.addEventListener("selectionchange",this.handleSelectionChange),document.addEventListener("select",this.handleSelect)}}},{key:"handleKeyUp",value:function(E){this.caretEventHandler(E),this.options.physicalKeyboardHighlight&&this.physicalKeyboard.handleHighlightKeyUp(E)}},{key:"handleKeyDown",value:function(E){this.options.physicalKeyboardHighlight&&this.physicalKeyboard.handleHighlightKeyDown(E)}},{key:"handleMouseUp",value:function(E){this.caretEventHandler(E)}},{key:"handleTouchEnd",value:function(E){this.caretEventHandler(E)}},{key:"handleSelect",value:function(E){this.caretEventHandler(E)}},{key:"handleSelectionChange",value:function(E){navigator.userAgent.includes("Firefox")||this.caretEventHandler(E)}},{key:"caretEventHandler",value:function(E){var U,W=this;E.target.tagName&&(U=E.target.tagName.toLowerCase()),this.dispatch((function(B){var ie=E.target===B.keyboardDOM||E.target&&B.keyboardDOM.contains(E.target);if(W.options.syncInstanceInputs&&Array.isArray(E.path)&&(ie=E.path.some((function(Y){var q;return Y==null||(q=Y.hasAttribute)===null||q===void 0?void 0:q.call(Y,"data-skInstance")}))),(U==="textarea"||U==="input"&&["text","search","url","tel","password"].includes(E.target.type))&&!B.options.disableCaretPositioning){var O=E.target.selectionStart,$=E.target.selectionEnd;B.options.rtl&&(O=B.utilities.getRtlOffset(O,B.getInput()),$=B.utilities.getRtlOffset($,B.getInput())),B.setCaretPosition(O,$),B.activeInputElement=E.target,B.options.debug&&console.log("Caret at: ",B.getCaretPosition(),B.getCaretPositionEnd(),E&&E.target.tagName.toLowerCase(),"(".concat(B.keyboardDOMClass,")"),E?.type)}else!B.options.disableCaretPositioning&&ie||E?.type==="selectionchange"||(B.setCaretPosition(null),B.activeInputElement=null,B.options.debug&&console.log('Caret position reset due to "'.concat(E?.type,'" event'),E))}))}},{key:"recurseButtons",value:function(E){var U=this;E&&Object.keys(this.buttonElements).forEach((function(W){return U.buttonElements[W].forEach(E)}))}},{key:"destroy",value:function(){this.options.debug&&console.log("Destroying simple-keyboard instance: ".concat(this.currentInstanceName));var E=this.options.physicalKeyboardHighlightPreventDefault,U=E!==void 0&&E;document.removeEventListener("keyup",this.handleKeyUp,U),document.removeEventListener("keydown",this.handleKeyDown,U),document.removeEventListener("mouseup",this.handleMouseUp),document.removeEventListener("touchend",this.handleTouchEnd),document.removeEventListener("select",this.handleSelect),this.options.updateCaretOnSelectionChange&&document.removeEventListener("selectionchange",this.handleSelectionChange),document.onpointerup=null,document.ontouchend=null,document.ontouchcancel=null,document.onmouseup=null,this.recurseButtons((function(W){W&&(W.onpointerdown=null,W.onpointerup=null,W.onpointercancel=null,W.ontouchstart=null,W.ontouchend=null,W.ontouchcancel=null,W.onclick=null,W.onmousedown=null,W.onmouseup=null,W.remove(),W=null)})),this.keyboardDOM.onpointerdown=null,this.keyboardDOM.ontouchstart=null,this.keyboardDOM.onmousedown=null,this.resetRows(),this.candidateBox&&(this.candidateBox.destroy(),this.candidateBox=null),this.activeInputElement=null,this.keyboardDOM.removeAttribute("data-skInstance"),this.keyboardDOM.innerHTML="",window.SimpleKeyboardInstances[this.currentInstanceName]=null,delete window.SimpleKeyboardInstances[this.currentInstanceName],this.initialized=!1}},{key:"getButtonThemeClasses",value:function(E){var U=this.options.buttonTheme,W=[];return Array.isArray(U)&&U.forEach((function(B){if(B&&B.class&&typeof B.class=="string"&&B.buttons&&typeof B.buttons=="string"){var ie=B.class.split(" ");B.buttons.split(" ").includes(E)&&(W=[].concat(ae(W),ae(ie)))}else console.warn('Incorrect "buttonTheme". Please check the documentation.',B)})),W}},{key:"setDOMButtonAttributes",value:function(E,U){var W=this.options.buttonAttributes;Array.isArray(W)&&W.forEach((function(B){B.attribute&&typeof B.attribute=="string"&&B.value&&typeof B.value=="string"?B.buttons&&typeof B.buttons=="string"?B.buttons.split(" ").includes(E)&&U(B.attribute,B.value):U(B.attribute,B.value):console.warn('Incorrect "buttonAttributes". Please check the documentation.',B)}))}},{key:"onTouchDeviceDetected",value:function(){this.processAutoTouchEvents(),this.disableContextualWindow()}},{key:"disableContextualWindow",value:function(){window.oncontextmenu=function(E){var U;if((U=E.target.classList)!==null&&U!==void 0&&U.contains("hg-button"))return E.preventDefault(),E.stopPropagation(),!1}}},{key:"processAutoTouchEvents",value:function(){this.options.autoUseTouchEvents&&(this.options.useTouchEvents=!0,this.options.debug&&console.log("autoUseTouchEvents: Touch device detected, useTouchEvents enabled."))}},{key:"onInit",value:function(){this.options.debug&&console.log("".concat(this.keyboardDOMClass," Initialized")),this.setEventListeners(),typeof this.options.onInit=="function"&&this.options.onInit(this)}},{key:"beforeFirstRender",value:function(){this.utilities.isTouchDevice()&&this.onTouchDeviceDetected(),typeof this.options.beforeFirstRender=="function"&&this.options.beforeFirstRender(this),this.isFirstKeyboardInstance&&this.utilities.pointerEventsSupported()&&!this.options.useTouchEvents&&!this.options.useMouseEvents&&this.options.debug&&console.log("Using PointerEvents as it is supported by this browser"),this.options.useTouchEvents&&this.options.debug&&console.log("useTouchEvents has been enabled. Only touch events will be used.")}},{key:"beforeRender",value:function(){typeof this.options.beforeRender=="function"&&this.options.beforeRender(this)}},{key:"onRender",value:function(){typeof this.options.onRender=="function"&&this.options.onRender(this)}},{key:"onModulesLoaded",value:function(){typeof this.options.onModulesLoaded=="function"&&this.options.onModulesLoaded(this)}},{key:"loadModules",value:function(){var E=this;Array.isArray(this.options.modules)&&(this.options.modules.forEach((function(U){var W=E.utilities.isConstructor(U)?new U(E):U(E);W.init&&W.init(E)})),this.keyboardPluginClasses="modules-loaded",this.render(),this.onModulesLoaded())}},{key:"getModuleProp",value:function(E,U){return!!this.modules[E]&&this.modules[E][U]}},{key:"getModulesList",value:function(){return Object.keys(this.modules)}},{key:"parseRowDOMContainers",value:function(E,U,W,B){var ie=this,O=Array.from(E.children),$=0;return O.length&&W.forEach((function(Y,q){var te=B[q];if(!(te&&te>Y))return!1;var oe=Y-$,he=te-$,fe=document.createElement("div");fe.className+="hg-button-container";var re="".concat(ie.options.layoutName,"-r").concat(U,"c").concat(q);fe.setAttribute("data-skUID",re);var L=O.splice(oe,he-oe+1);$+=he-oe,L.forEach((function(R){return fe.appendChild(R)})),O.splice(oe,0,fe),E.innerHTML="",O.forEach((function(R){return E.appendChild(R)})),ie.options.debug&&console.log("rowDOMContainer",L,oe,he,$+1)})),E}},{key:"render",value:function(){var E=this;this.resetRows(),this.initialized||this.beforeFirstRender(),this.beforeRender();var U="hg-layout-".concat(this.options.layoutName),W=this.options.layout||{default:["` 1 2 3 4 5 6 7 8 9 0 - = {bksp}","{tab} q w e r t y u i o p [ ] \\","{lock} a s d f g h j k l ; ' {enter}","{shift} z x c v b n m , . / {shift}",".com @ {space}"],shift:["~ ! @ # $ % ^ & * ( ) _ + {bksp}","{tab} Q W E R T Y U I O P { } |",'{lock} A S D F G H J K L : " {enter}',"{shift} Z X C V B N M < > ? {shift}",".com @ {space}"]},B=this.options.useTouchEvents||!1,ie=B?"hg-touch-events":"",O=this.options.useMouseEvents||!1,$=this.options.disableRowButtonContainers;this.keyboardDOM.className=this.getKeyboardClassString(this.options.theme,U,this.keyboardPluginClasses,ie),this.keyboardDOM.setAttribute("data-skInstance",this.currentInstanceName),this.keyboardRowsDOM=document.createElement("div"),this.keyboardRowsDOM.className="hg-rows",W[this.options.layoutName||this.defaultName].forEach((function(Y,q){var te=Y.split(" ");E.options.excludeFromLayout&&E.options.excludeFromLayout[E.options.layoutName||E.defaultName]&&(te=te.filter((function(re){return E.options.excludeFromLayout&&!E.options.excludeFromLayout[E.options.layoutName||E.defaultName].includes(re)})));var oe=document.createElement("div");oe.className+="hg-row";var he=[],fe=[];te.forEach((function(re,L){var R,ne=!$&&typeof re=="string"&&re.length>1&&re.indexOf("[")===0,ve=!$&&typeof re=="string"&&re.length>1&&re.indexOf("]")===re.length-1;ne&&(he.push(L),re=re.replace(/\[/g,"")),ve&&(fe.push(L),re=re.replace(/\]/g,""));var we=E.utilities.getButtonClass(re),me=E.utilities.getButtonDisplayName(re,E.options.display,E.options.mergeDisplay),Me=E.options.useButtonTag?"button":"div",xe=document.createElement(Me);xe.className+="hg-button ".concat(we),(R=xe.classList).add.apply(R,ae(E.getButtonThemeClasses(re))),E.setDOMButtonAttributes(re,(function(Oe,_e){xe.setAttribute(Oe,_e)})),E.activeButtonClass="hg-activeButton",!E.utilities.pointerEventsSupported()||B||O?B?(xe.ontouchstart=function(Oe){E.handleButtonClicked(re,Oe),E.handleButtonMouseDown(re,Oe)},xe.ontouchend=function(Oe){E.handleButtonMouseUp(re,Oe)},xe.ontouchcancel=function(Oe){E.handleButtonMouseUp(re,Oe)}):(xe.onclick=function(Oe){E.setMouseHold(!1),typeof E.options.onKeyReleased=="function"||E.options.useMouseEvents&&E.options.clickOnMouseDown||E.handleButtonClicked(re,Oe)},xe.onmousedown=function(Oe){(typeof E.options.onKeyReleased=="function"||E.options.useMouseEvents&&E.options.clickOnMouseDown)&&!E.isMouseHold&&E.handleButtonClicked(re,Oe),E.handleButtonMouseDown(re,Oe)},xe.onmouseup=function(Oe){E.handleButtonMouseUp(re,Oe)}):(xe.onpointerdown=function(Oe){E.handleButtonClicked(re,Oe),E.handleButtonMouseDown(re,Oe)},xe.onpointerup=function(Oe){E.handleButtonMouseUp(re,Oe)},xe.onpointercancel=function(Oe){E.handleButtonMouseUp(re,Oe)}),xe.setAttribute("data-skBtn",re);var je="".concat(E.options.layoutName,"-r").concat(q,"b").concat(L);xe.setAttribute("data-skBtnUID",je);var He=document.createElement("span");He.innerHTML=me,xe.appendChild(He),E.buttonElements[re]||(E.buttonElements[re]=[]),E.buttonElements[re].push(xe),oe.appendChild(xe)})),oe=E.parseRowDOMContainers(oe,q,he,fe),E.keyboardRowsDOM.appendChild(oe)})),this.keyboardDOM.appendChild(this.keyboardRowsDOM),this.onRender(),this.initialized||(this.initialized=!0,!this.utilities.pointerEventsSupported()||B||O?B?(document.ontouchend=function(Y){return E.handleButtonMouseUp(void 0,Y)},document.ontouchcancel=function(Y){return E.handleButtonMouseUp(void 0,Y)},this.keyboardDOM.ontouchstart=function(Y){return E.handleKeyboardContainerMouseDown(Y)}):B||(document.onmouseup=function(Y){return E.handleButtonMouseUp(void 0,Y)},this.keyboardDOM.onmousedown=function(Y){return E.handleKeyboardContainerMouseDown(Y)}):(document.onpointerup=function(Y){return E.handleButtonMouseUp(void 0,Y)},this.keyboardDOM.onpointerdown=function(Y){return E.handleKeyboardContainerMouseDown(Y)}),this.onInit())}}],J&&pe(V.prototype,J),D&&pe(V,D),Object.defineProperty(V,"prototype",{writable:!1}),V;var V,J,D})(),ge=de,Te=ge;return m})()},442:function(l){l.exports=n}},a={};function s(l){var c=a[l];if(c!==void 0)return c.exports;var d=a[l]={exports:{}};return r[l].call(d.exports,d,d.exports,s),d.exports}s.n=function(l){var c=l&&l.__esModule?function(){return l.default}:function(){return l};return s.d(c,{a:c}),c},s.d=function(l,c){for(var d in c)s.o(c,d)&&!s.o(l,d)&&Object.defineProperty(l,d,{enumerable:!0,get:c[d]})},s.o=function(l,c){return Object.prototype.hasOwnProperty.call(l,c)},s.r=function(l){typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(l,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(l,"__esModule",{value:!0})};var o={};return(function(){s.r(o),s.d(o,{KeyboardReact:function(){return v},default:function(){return b}}),s(981);var l=s(442),c=s(548),d=s.n(c);function u(g){return u=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(_){return typeof _}:function(_){return _&&typeof Symbol=="function"&&_.constructor===Symbol&&_!==Symbol.prototype?"symbol":typeof _},u(g)}function m(g,_){var k=Object.keys(g);if(Object.getOwnPropertySymbols){var C=Object.getOwnPropertySymbols(g);_&&(C=C.filter((function(N){return Object.getOwnPropertyDescriptor(g,N).enumerable}))),k.push.apply(k,C)}return k}function p(g){for(var _=1;_{if(a.current)return;const v=y.target;if(!v.closest('[data-vkb="false"]')){if(v instanceof HTMLInputElement){if(!Fnt.has(v.type))return}else if(!(v instanceof HTMLTextAreaElement))return;l.current=v,e(!0),o("default"),c.current?.setInput?.(l.current.value),setTimeout(()=>{v.scrollIntoView({behavior:"smooth",block:"center"})},100)}},[]),m=w.useCallback(()=>{setTimeout(()=>{const y=document.activeElement;y&&(d.current?.contains(y)||y===l.current)||(e(!1),l.current=null)},150)},[]);w.useEffect(()=>(document.addEventListener("focusin",u),document.addEventListener("focusout",m),()=>{document.removeEventListener("focusin",u),document.removeEventListener("focusout",m)}),[u,m]);const p=w.useCallback(()=>{a.current=!0,r(!0),l.current?.blur(),l.current=null,setTimeout(()=>{e(!1),r(!1),a.current=!1},400)},[]),f=w.useCallback(y=>{const v=l.current;if(v){if(y==="{shift}"){o(b=>b==="default"?"shift":"default");return}if(y==="{lock}"){o(b=>b==="default"?"shift":"default");return}if(y==="{close}"){p();return}y==="{bksp}"?i3(v,v.value.slice(0,-1)):y==="{space}"?i3(v,v.value+" "):(i3(v,v.value+y),s==="shift"&&o("default")),v.focus(),c.current?.setInput?.(v.value)}},[s,p]);return t?i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"fixed inset-0 z-[9998] bg-transparent",onMouseDown:y=>{y.preventDefault(),y.stopPropagation(),n||p()},onTouchStart:y=>{y.preventDefault(),y.stopPropagation(),n||p()},onClick:y=>{y.preventDefault(),y.stopPropagation()}}),!n&&i.jsx("div",{ref:d,className:"fixed bottom-0 left-0 right-0 z-[9999]",onMouseDown:y=>y.preventDefault(),onTouchStart:y=>{y.target.closest(".hg-button")||y.preventDefault()},children:i.jsx(Dnt,{keyboardRef:y=>{c.current=y},layoutName:s,onKeyPress:f,theme:"simple-keyboard vkb-theme",layout:{default:["1 2 3 4 5 6 7 8 9 0 {bksp}","q w e r t y u i o p","{lock} a s d f g h j k l","{shift} z x c v b n m . @","{space} {close}"],shift:["! @ # $ % ^ & * ( ) {bksp}","Q W E R T Y U I O P","{lock} A S D F G H J K L","{shift} Z X C V B N M , _","{space} {close}"]},display:{"{bksp}":"⌫","{close}":"✕ Close","{shift}":"⇧","{lock}":"⇪","{space}":" "}})})]}):null}function Lnt(){const[t,e]=w.useState(null),[n,r]=w.useState(null),[a,s]=w.useState(!1),[o,l]=w.useState(100),[c,d]=w.useState(0),u=w.useRef(Date.now()),{i18n:m}=jt(),p=Pnt(),{data:f}=et({queryKey:["settings"],queryFn:be.getSettings});w.useEffect(()=>{f?.language&&f.language!==m.language&&m.changeLanguage(f.language)},[f?.language,m]);const{data:y=[]}=et({queryKey:["spoolbuddy-devices"],queryFn:()=>zi.getDevices(),refetchInterval:3e4}),v=y[0],b=p.deviceOnline||!!v?.online,g=w.useMemo(()=>({...p,deviceOnline:b}),[p,b]),_=w.useRef(!1);w.useEffect(()=>{v&&!_.current&&(l(v.display_brightness),d(v.display_blank_timeout),_.current=!0)},[v]),w.useEffect(()=>{const P=document.documentElement,T=P.classList.contains("dark");return P.classList.add("dark"),()=>{T||P.classList.remove("dark")}},[]);const{data:k}=et({queryKey:["spoolbuddy-update-check",v?.device_id],queryFn:()=>v?zi.checkDaemonUpdate(v.device_id):Promise.resolve(null),enabled:!!v,refetchInterval:300*1e3,staleTime:0});w.useEffect(()=>{b?k?.update_available&&k.latest_version?r({type:"info",message:`Update available: v${k.latest_version}`}):r(null):r({type:"warning",message:"SpoolBuddy device disconnected"})},[b,k?.update_available,k?.latest_version]);const C=w.useCallback(()=>{u.current=Date.now(),s(!1)},[]);w.useEffect(()=>(window.addEventListener("pointerdown",C),window.addEventListener("keydown",C),()=>{window.removeEventListener("pointerdown",C),window.removeEventListener("keydown",C)}),[C]),w.useEffect(()=>{if(c<=0)return;const P=setInterval(()=>{Date.now()-u.current>=c*1e3&&s(!0)},1e3);return()=>clearInterval(P)},[c]);const N=o<100?{filter:`brightness(${o/100})`}:void 0;return i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"w-screen h-screen bg-bambu-dark text-white flex flex-col overflow-hidden",style:N,children:[i.jsx(_nt,{selectedPrinterId:t,onPrinterChange:e,deviceOnline:b}),i.jsx("main",{className:"flex-1 overflow-y-auto",children:i.jsx(kX,{context:{selectedPrinterId:t,setSelectedPrinterId:e,sbState:g,setAlert:r,displayBrightness:o,setDisplayBrightness:l,displayBlankTimeout:c,setDisplayBlankTimeout:d}})}),i.jsx(Cnt,{alert:n}),i.jsx(Nnt,{}),i.jsx(Rnt,{})]}),a&&i.jsx("div",{className:"fixed inset-0 bg-black z-[9999]",onPointerDown:P=>{P.stopPropagation(),C()}})]})}function F5({color:t,isEmpty:e,size:n=32}){return e?i.jsx("div",{className:"rounded-full border-2 border-dashed border-zinc-500 flex items-center justify-center",style:{width:n,height:n},children:i.jsx("div",{className:"w-2 h-2 rounded-full bg-zinc-600"})}):i.jsxs("svg",{width:n,height:n,viewBox:"0 0 32 32",children:[i.jsx("circle",{cx:"16",cy:"16",r:"14",fill:t,stroke:"white",strokeWidth:"1.5",strokeOpacity:"0.7"}),i.jsx("circle",{cx:"16",cy:"16",r:"11",fill:t,style:{filter:"brightness(0.85)"}})]})}const Ont="spoolbuddy-default-core-weight";function gle(){try{const t=localStorage.getItem(Ont);if(t){const e=parseInt(t,10);if(e>=0&&e<=500)return e}}catch{}return 250}function Int({spool:t,scaleWeight:e,onClose:n,onSyncWeight:r,onAssignToAms:a}){const{t:s}=jt(),[o,l]=w.useState(!1),[c,d]=w.useState(!1),u=t.rgba?`#${t.rgba.slice(0,6)}`:"#808080",m=t.core_weight&&t.core_weight>0?t.core_weight:gle(),p=e!==null?Math.round(Math.max(0,e)):null,f=p!==null?Math.round(Math.max(0,p-m)):null,y=Math.round(t.label_weight||1e3),v=f!==null?Math.min(100,Math.round(f/y*100)):null,b=v!==null?v>50?"#22c55e":v>20?"#eab308":"#ef4444":"#808080",_=Math.max(0,(t.label_weight||0)-(t.weight_used||0))+m,k=p!==null?p-_:null,C=k!==null?Math.abs(k)<=50:null,N=async()=>{if(e!==null){l(!0);try{await zi.updateSpoolWeight(t.id,Math.round(e)),d(!0),r?.(),setTimeout(()=>d(!1),3e3)}catch(P){console.error("Failed to sync weight:",P)}finally{l(!1)}}};return i.jsxs("div",{className:"flex flex-col items-center space-y-4 max-w-md",children:[i.jsxs("div",{className:"flex items-start gap-5",children:[i.jsxs("div",{className:"relative shrink-0",children:[i.jsx(F5,{color:u,isEmpty:!1,size:100}),v!==null&&i.jsxs("div",{className:"absolute -bottom-2 -right-2 px-2 py-0.5 rounded-full text-xs font-bold text-white shadow-lg",style:{backgroundColor:b},children:[v,"%"]})]}),i.jsxs("div",{className:"flex-1 min-w-0 pt-1",children:[i.jsx("h3",{className:"text-lg font-semibold text-zinc-100",children:t.color_name||"Unknown color"}),i.jsxs("p",{className:"text-sm text-zinc-400",children:[t.brand," • ",t.material,t.subtype&&` ${t.subtype}`]}),f!==null&&i.jsxs("div",{className:"mt-3",children:[i.jsxs("div",{className:"flex items-baseline gap-2",children:[i.jsxs("span",{className:"text-3xl font-bold font-mono text-zinc-100",children:[f,"g"]}),i.jsxs("span",{className:"text-sm text-zinc-500",children:["/ ",y,"g"]})]}),i.jsx("p",{className:"text-xs text-zinc-500 mt-0.5",children:s("spoolbuddy.spool.remaining","Remaining")}),i.jsx("div",{className:"mt-2 max-w-xs",children:i.jsx("div",{className:"h-2 bg-zinc-700 rounded-full overflow-hidden",children:i.jsx("div",{className:"h-full rounded-full transition-all duration-500",style:{width:`${v}%`,backgroundColor:b}})})})]})]})]}),i.jsxs("div",{className:"grid grid-cols-2 gap-x-6 gap-y-2 text-sm bg-zinc-800 rounded-lg p-4 w-full",children:[i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-zinc-500",children:s("spoolbuddy.dashboard.grossWeight","Gross weight")}),i.jsx("span",{className:"font-mono text-zinc-300",children:p!==null?`${p}g`:"—"})]}),i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-zinc-500",children:s("spoolbuddy.spool.coreWeight","Core")}),i.jsxs("span",{className:"font-mono text-zinc-300",children:[m,"g"]})]}),i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-zinc-500",children:s("spoolbuddy.dashboard.spoolSize","Spool size")}),i.jsxs("span",{className:"font-mono text-zinc-300",children:[y,"g"]})]}),i.jsxs("div",{className:"flex justify-between items-center",children:[i.jsx("span",{className:"text-zinc-500",children:s("spoolbuddy.spool.scaleWeight","Scale")}),p!==null?i.jsxs("span",{className:`flex items-center gap-1 font-mono ${C?"text-green-500":"text-yellow-500"}`,children:[p,"g",C?i.jsx(Zr,{className:"w-3.5 h-3.5"}):i.jsxs(i.Fragment,{children:[i.jsx(jn,{className:"w-3.5 h-3.5"}),i.jsx("button",{onClick:N,className:"p-1 hover:bg-green-500/20 rounded transition-colors text-green-500",title:s("spoolbuddy.dashboard.syncWeight","Sync Weight"),children:i.jsx(vr,{className:"w-4 h-4"})})]})]}):i.jsx("span",{className:"text-zinc-500",children:"—"})]}),i.jsxs("div",{className:"flex justify-between items-center",children:[i.jsx("span",{className:"text-zinc-500",children:s("spoolbuddy.dashboard.tagId","Tag")}),i.jsx("span",{className:"font-mono text-xs text-zinc-400 truncate max-w-[120px]",title:t.tag_uid||"",children:t.tag_uid?t.tag_uid.slice(-8):"—"})]})]}),i.jsxs("div",{className:"flex gap-2 justify-center",children:[a&&i.jsx("button",{onClick:a,className:"px-5 py-2.5 rounded-lg text-sm font-medium bg-green-600 text-white hover:bg-green-700 transition-colors min-h-[44px]",children:s("spoolbuddy.modal.assignToAms","Assign to AMS")}),i.jsx("button",{onClick:N,disabled:e===null||o,className:`px-5 py-2.5 rounded-lg text-sm font-medium transition-colors min-h-[44px] ${c?"bg-green-600/20 text-green-400":a?"bg-zinc-700 text-zinc-300 hover:bg-zinc-600 disabled:opacity-40 disabled:cursor-not-allowed":"bg-green-600 text-white hover:bg-green-700 disabled:opacity-40 disabled:cursor-not-allowed"}`,children:o?"...":c?s("spoolbuddy.dashboard.weightSynced","Synced!"):s("spoolbuddy.dashboard.syncWeight","Sync Weight")}),n&&i.jsx("button",{onClick:n,className:"px-5 py-2.5 rounded-lg text-sm font-medium bg-zinc-700 text-zinc-300 hover:bg-zinc-600 transition-colors min-h-[44px]",children:s("spoolbuddy.dashboard.close","Close")})]})]})}function znt({tagUid:t,scaleWeight:e,coreWeight:n,onLinkSpool:r,onAddToInventory:a,onClose:s}){const{t:o}=jt(),l=n??gle(),c=e!==null?Math.round(Math.max(0,e)):null,d=c!==null?Math.round(Math.max(0,c-l)):null;return i.jsxs("div",{className:"flex flex-col items-center text-center space-y-5",children:[i.jsx("div",{className:"w-20 h-20 rounded-2xl bg-green-500/15 flex items-center justify-center",children:i.jsx("svg",{className:"w-10 h-10 text-green-500",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M7 7h.01M7 3h5c.512 0 1.024.195 1.414.586l7 7a2 2 0 010 2.828l-7 7a2 2 0 01-2.828 0l-7-7A2 2 0 013 12V7a4 4 0 014-4z"})})}),i.jsxs("div",{children:[i.jsx("h3",{className:"text-lg font-semibold text-zinc-100",children:o("spoolbuddy.dashboard.newTag","New Tag Detected")}),i.jsx("p",{className:"text-sm text-zinc-500 font-mono mt-1",children:t})]}),c!==null&&i.jsxs("div",{className:"text-sm text-zinc-400",children:[i.jsxs("span",{className:"font-mono font-semibold",children:[c,"g"]})," ",o("spoolbuddy.dashboard.onScale","on scale"),d!==null&&d>0&&i.jsxs("span",{className:"text-zinc-500",children:[" • ~",d,"g filament"]})]}),i.jsxs("div",{className:"flex flex-wrap gap-2 justify-center",children:[a&&i.jsx("button",{onClick:a,className:"px-5 py-2.5 rounded-lg text-sm font-medium bg-green-600 text-white hover:bg-green-700 transition-colors min-h-[44px]",children:o("spoolbuddy.modal.addToInventory","Add to Inventory")}),r&&i.jsxs("button",{onClick:r,className:"px-5 py-2.5 rounded-lg text-sm font-medium bg-zinc-700 text-zinc-300 hover:bg-zinc-600 transition-colors min-h-[44px]",children:[i.jsx("svg",{className:"w-4 h-4 inline-block mr-1.5 -mt-0.5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M13.828 10.172a4 4 0 00-5.656 0l-4 4a4 4 0 105.656 5.656l1.102-1.101m-.758-4.899a4 4 0 005.656 0l4-4a4 4 0 00-5.656-5.656l-1.1 1.1"})}),o("spoolbuddy.dashboard.linkSpool","Link to Spool")]}),s&&i.jsx("button",{onClick:s,className:"px-5 py-2.5 rounded-lg text-sm font-medium bg-zinc-700 text-zinc-300 hover:bg-zinc-600 transition-colors min-h-[44px]",children:o("spoolbuddy.dashboard.close","Close")})]})]})}function Unt(t){return t?`#${t.slice(0,6)}`:"#808080"}function ble(t){return!t.tray_type||t.tray_type===""}function Bnt(t){return t<=3?`AMS ${String.fromCharCode(65+t)}`:t>=128&&t<=135?`AMS HT ${String.fromCharCode(65+t-128)}`:`AMS ${t}`}function Hnt({className:t}){return i.jsx("svg",{className:t,viewBox:"0 0 36 54",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:i.jsx("path",{d:"M17.8131 0.00538C18.4463 -0.15091 20.3648 3.14642 20.8264 3.84781C25.4187 10.816 35.3089 26.9368 35.9383 34.8694C37.4182 53.5822 11.882 61.3357 2.53721 45.3789C-1.73471 38.0791 0.016 32.2049 3.178 25.0232C6.99221 16.3662 12.6411 7.90372 17.8131 0.00538ZM18.3738 7.24807L17.5881 7.48441C14.4452 12.9431 10.917 18.2341 8.19369 23.9368C4.6808 31.29 1.18317 38.5479 7.69403 45.5657C17.3058 55.9228 34.9847 46.8808 31.4604 32.8681C29.2558 24.0969 22.4207 15.2913 18.3776 7.24807H18.3738Z",fill:"#C3C2C1"})})}function $nt({className:t}){return i.jsxs("svg",{className:t,viewBox:"0 0 35 53",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[i.jsx("path",{d:"M17.3165 0.0038C17.932 -0.14959 19.7971 3.08645 20.2458 3.77481C24.7103 10.6135 34.3251 26.4346 34.937 34.2198C36.3757 52.5848 11.5505 60.1942 2.46584 44.534C-1.68714 37.3735 0.0148 31.6085 3.08879 24.5603C6.79681 16.0605 12.2884 7.75907 17.3165 0.0038ZM17.8615 7.11561L17.0977 7.34755C14.0423 12.7048 10.6124 17.8974 7.96483 23.4941C4.54975 30.7107 1.14949 37.8337 7.47908 44.721C16.8233 54.8856 34.01 46.0117 30.5838 32.2595C28.4405 23.6512 21.7957 15.0093 17.8652 7.11561H17.8615Z",fill:"#C3C2C1"}),i.jsx("path",{d:"M5.03547 30.112C9.64453 30.4936 11.632 35.7985 16.4154 35.791C19.6339 35.7873 20.2161 33.2283 22.3853 31.6197C31.6776 24.7286 33.5835 37.4894 27.9881 44.4254C18.1878 56.5653 -1.16063 44.6013 5.03917 30.1158L5.03547 30.112Z",fill:"#1F8FEB"})]})}function qnt({className:t}){return i.jsxs("svg",{className:t,viewBox:"0 0 36 54",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[i.jsx("path",{d:"M17.9625 4.48059L4.77216 26.3154L2.08228 40.2175L10.0224 50.8414H23.1594L33.3246 42.1693V30.2455L17.9625 4.48059Z",fill:"#1F8FEB"}),i.jsx("path",{d:"M17.7948 0.00538C18.4273 -0.15091 20.3438 3.14642 20.8048 3.84781C25.3921 10.816 35.2715 26.9368 35.9001 34.8694C37.3784 53.5822 11.8702 61.3357 2.53562 45.3789C-1.73163 38.0829 0.0134 32.2087 3.1757 25.027C6.98574 16.3662 12.6284 7.90372 17.7948 0.00538ZM18.3549 7.24807L17.57 7.48441C14.4306 12.9431 10.9063 18.2341 8.1859 23.9368C4.67686 31.29 1.18305 38.5479 7.68679 45.5657C17.2881 55.9228 34.9476 46.8808 31.4271 32.8681C29.2249 24.0969 22.3974 15.2913 18.3587 7.24807H18.3549Z",fill:"#C3C2C1"})]})}function Vnt({className:t}){return i.jsxs("svg",{className:t,viewBox:"0 0 12 20",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[i.jsx("path",{d:"M6 0.5C4.6 0.5 3.5 1.6 3.5 3V12.1C2.6 12.8 2 13.9 2 15C2 17.2 3.8 19 6 19C8.2 19 10 17.2 10 15C10 13.9 9.4 12.8 8.5 12.1V3C8.5 1.6 7.4 0.5 6 0.5Z",stroke:"#C3C2C1",strokeWidth:"1",fill:"none"}),i.jsx("circle",{cx:"6",cy:"15",r:"2.5",stroke:"#C3C2C1",strokeWidth:"1",fill:"none"})]})}function Gnt({className:t}){return i.jsxs("svg",{className:t,viewBox:"0 0 12 20",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[i.jsx("rect",{x:"4.5",y:"8",width:"3",height:"4.5",fill:"#d4a017",rx:"0.5"}),i.jsx("circle",{cx:"6",cy:"15",r:"2",fill:"#d4a017"}),i.jsx("path",{d:"M6 0.5C4.6 0.5 3.5 1.6 3.5 3V12.1C2.6 12.8 2 13.9 2 15C2 17.2 3.8 19 6 19C8.2 19 10 17.2 10 15C10 13.9 9.4 12.8 8.5 12.1V3C8.5 1.6 7.4 0.5 6 0.5Z",stroke:"#C3C2C1",strokeWidth:"1",fill:"none"})]})}function Wnt({className:t}){return i.jsxs("svg",{className:t,viewBox:"0 0 12 20",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[i.jsx("rect",{x:"4.5",y:"3",width:"3",height:"9.5",fill:"#c62828",rx:"0.5"}),i.jsx("circle",{cx:"6",cy:"15",r:"2",fill:"#c62828"}),i.jsx("path",{d:"M6 0.5C4.6 0.5 3.5 1.6 3.5 3V12.1C2.6 12.8 2 13.9 2 15C2 17.2 3.8 19 6 19C8.2 19 10 17.2 10 15C10 13.9 9.4 12.8 8.5 12.1V3C8.5 1.6 7.4 0.5 6 0.5Z",stroke:"#C3C2C1",strokeWidth:"1",fill:"none"})]})}function xle({humidity:t,goodThreshold:e=40,fairThreshold:n=60}){let r,a;return t<=e?(r="#22a352",a=Hnt):t<=n?(r="#d4a017",a=$nt):(r="#c62828",a=qnt),i.jsxs("div",{className:"flex items-center gap-0.5",children:[i.jsx(a,{className:"w-3 h-3.5"}),i.jsxs("span",{className:"font-medium tabular-nums text-xs",style:{color:r},children:[t,"%"]})]})}function yle({temp:t,goodThreshold:e=28,fairThreshold:n=35}){let r,a;return t<=e?(r="#22a352",a=Vnt):t<=n?(r="#d4a017",a=Gnt):(r="#c62828",a=Wnt),i.jsxs("div",{className:"flex items-center gap-0.5",children:[i.jsx(a,{className:"w-3 h-3.5"}),i.jsxs("span",{className:"font-medium tabular-nums text-xs",style:{color:r},children:[t,"°C"]})]})}function R5({side:t}){return i.jsx("span",{className:"inline-flex items-center justify-center w-4 h-4 text-[9px] font-bold rounded",style:{backgroundColor:"#1a4d2e",color:"#00ae42"},children:t})}function Knt({tray:t,slotIndex:e,isActive:n,fillOverride:r,spoolmanFill:a,onClick:s}){const o=ble(t),l=Unt(t.tray_color),c=t.remain!==null&&t.remain!==void 0&&t.remain>=0?t.remain:null,d=r===0&&c!==null&&c>0?null:r,u=a??d??c;return i.jsxs("div",{className:`relative flex flex-col items-center p-2.5 rounded-lg transition-all ${n?"ring-2 ring-bambu-green":""} ${s?"cursor-pointer hover:bg-white/5":""}`,onClick:s,children:[i.jsxs("div",{className:"relative w-16 h-16 mb-1",children:[o?i.jsx("div",{className:"w-full h-full rounded-full border-2 border-dashed border-gray-500 flex items-center justify-center",children:i.jsx("div",{className:"w-3 h-3 rounded-full bg-gray-600"})}):i.jsxs("svg",{viewBox:"0 0 56 56",className:"w-full h-full",children:[i.jsx("circle",{cx:"28",cy:"28",r:"26",fill:l}),i.jsx("circle",{cx:"28",cy:"28",r:"20",fill:l,style:{filter:"brightness(0.85)"}}),i.jsx("ellipse",{cx:"20",cy:"20",rx:"6",ry:"4",fill:"white",opacity:"0.3"}),i.jsx("circle",{cx:"28",cy:"28",r:"8",fill:"#2d2d2d"}),i.jsx("circle",{cx:"28",cy:"28",r:"5",fill:"#1a1a1a"})]}),n&&i.jsx("div",{className:"absolute -bottom-1 left-1/2 -translate-x-1/2 w-2.5 h-2.5 bg-bambu-green rounded-full"})]}),i.jsx("span",{className:"text-sm text-white/70 truncate max-w-full",children:o?"Empty":t.tray_type||"Unknown"}),!o&&u!==null&&u>=0&&i.jsx("div",{className:"w-full h-1 bg-bambu-dark-tertiary rounded-full overflow-hidden mt-1",children:i.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${u}%`,backgroundColor:sx(u)}})}),i.jsx("span",{className:"absolute top-1 right-1 text-xs text-white/30",children:e+1})]})}function vle({unit:t,activeSlot:e,onConfigureSlot:n,isDualNozzle:r,nozzleSide:a,thresholds:s,fillOverrides:o,spoolmanFillOverrides:l}){const c=t.tray||[],d=t.is_ams_ht,u=d?1:4;return i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg p-3",children:[i.jsxs("div",{className:"flex items-center justify-between mb-2",children:[i.jsxs("div",{className:"flex items-center gap-1.5",children:[i.jsx("span",{className:"text-white font-medium text-base",children:Bnt(t.id)}),r&&a&&i.jsx(R5,{side:a})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[t.temp!=null&&i.jsx(yle,{temp:t.temp,goodThreshold:s?.tempGood,fairThreshold:s?.tempFair}),t.humidity!=null&&i.jsx(xle,{humidity:t.humidity,goodThreshold:s?.humidityGood,fairThreshold:s?.humidityFair})]})]}),i.jsx("div",{className:`grid ${d?"grid-cols-1 max-w-[100px] mx-auto":"grid-cols-4"} gap-2`,children:Array.from({length:u}).map((m,p)=>{const f=c[p]||{id:p,tray_color:null,tray_type:"",tray_sub_brands:null,tray_id_name:null,tray_info_idx:null,remain:-1,k:null,cali_idx:null,tag_uid:null,tray_uuid:null,nozzle_temp_min:null,nozzle_temp_max:null};return i.jsx(Knt,{tray:f,slotIndex:p,isActive:e===p,fillOverride:o?.[`${t.id}-${p}`]??null,spoolmanFill:l?.[`${t.id}-${p}`]??null,onClick:n?()=>n(t.id,p,ble(f)?null:f):void 0},p)})})]})}function Ynt(t){return t<=3?`AMS ${String.fromCharCode(65+t)}`:t>=128&&t<=135?`AMS HT ${String.fromCharCode(65+t-128)}`:`AMS ${t}`}function WY(t){return!t.tray_type||t.tray_type===""}function Xnt(t){return t?`#${t.slice(0,6)}`:"#808080"}function Qnt({isOpen:t,onClose:e,spool:n,printerId:r}){const{t:a}=jt(),s=cn(),[o,l]=w.useState(null),[c,d]=w.useState(null);w.useEffect(()=>{t&&(l(null),d(null))},[t]);const u=w.useCallback(ee=>{ee.key==="Escape"&&e()},[e]);w.useEffect(()=>(t&&document.addEventListener("keydown",u),()=>document.removeEventListener("keydown",u)),[t,u]);const{data:m}=et({queryKey:["printerStatus",r],queryFn:()=>be.getPrinterStatus(r),enabled:t&&r!==null,refetchInterval:5e3}),{data:p}=et({queryKey:["printer",r],queryFn:()=>be.getPrinter(r),enabled:t&&r!==null}),{data:f}=et({queryKey:["settings"],queryFn:()=>be.getSettings(),enabled:t,staleTime:300*1e3}),{data:y}=et({queryKey:["spool-assignments",r],queryFn:()=>be.getAssignments(r),enabled:t&&r!==null,staleTime:30*1e3}),v=w.useMemo(()=>{const ee={};if(!y)return ee;for(const ae of y){const X=ae.spool;if(X&&X.label_weight>0&&X.weight_used!=null){const ce=Math.round(Math.max(0,X.label_weight-X.weight_used)/X.label_weight*100);ee[`${ae.ams_id}-${ae.tray_id}`]=ce}}return ee},[y]),b=f?{humidityGood:Number(f.ams_humidity_good)||40,humidityFair:Number(f.ams_humidity_fair)||60,tempGood:Number(f.ams_temp_good)||28,tempFair:Number(f.ams_temp_fair)||35}:void 0,g=m?.connected??!1,_=w.useMemo(()=>m?.ams??[],[m?.ams]),k=w.useMemo(()=>_.filter(ee=>!ee.is_ams_ht),[_]),C=w.useMemo(()=>_.filter(ee=>ee.is_ams_ht),[_]),N=w.useMemo(()=>[...m?.vt_tray??[]].sort((ee,ae)=>(ee.id??254)-(ae.id??254)),[m?.vt_tray]),P=p?.nozzle_count===2||m?.temperatures?.nozzle_2!==void 0,T=w.useRef({});w.useEffect(()=>{m?.ams_extruder_map&&Object.keys(m.ams_extruder_map).length>0&&(T.current=m.ams_extruder_map)},[m?.ams_extruder_map]);const j=m?.ams_extruder_map&&Object.keys(m.ams_extruder_map).length>0?m.ams_extruder_map:T.current,A=w.useCallback(ee=>{if(!P)return null;const ae=j[String(ee)],X=ee>=128?ee-128:ee;return(ae!==void 0?ae:X)===1?"L":"R"},[P,j]),F=pt({mutationFn:async({amsId:ee,trayId:ae})=>{if(!r)throw new Error("No printer selected");await be.assignSpool({spool_id:n.id,printer_id:r,ams_id:ee,tray_id:ae})},onSuccess:()=>{d("success"),l(a("spoolbuddy.modal.assignSuccess","Assigned!")),s.invalidateQueries({queryKey:["slotPresets"]}),setTimeout(()=>e(),1500)},onError:ee=>{d("error"),l(ee instanceof Error?ee.message:a("spoolbuddy.modal.assignError","Failed to assign spool."))}}),G=F.isPending,z=w.useCallback((ee,ae)=>{G||(d("info"),l(a("spoolbuddy.modal.assigning","Configuring slot...")),F.mutate({amsId:ee,trayId:ae}))},[G,F,a]),Z=w.useMemo(()=>{const ee=[];for(const ae of C){const X=ae.tray?.[0]||{id:0,tray_color:null,tray_type:"",tray_sub_brands:null,tray_id_name:null,tray_info_idx:null,remain:-1,k:null,cali_idx:null,tag_uid:null,tray_uuid:null,nozzle_temp_min:null,nozzle_temp_max:null},ce=v[`${ae.id}-0`]??null,ue=X.remain!=null&&X.remain>=0?X.remain:null,pe=ce===0&&ue!==null&&ue>0?null:ce;ee.push({key:`ht-${ae.id}`,label:Ynt(ae.id),amsId:ae.id,trayId:0,tray:X,isEmpty:WY(X),nozzleSide:A(ae.id),effectiveFill:pe??ue})}for(const ae of N){const X=ae.id??254,ce=X-254,ue=v[`255-${ce}`]??null,pe=ae.remain!=null&&ae.remain>=0?ae.remain:null,K=ue===0&&pe!==null&&pe>0?null:ue;ee.push({key:`ext-${X}`,label:P?X===254?a("printers.extL","Ext-L"):a("printers.extR","Ext-R"):a("printers.ext","Ext"),amsId:255,trayId:ce,tray:ae,isEmpty:WY(ae),nozzleSide:P?X===254?"L":"R":null,effectiveFill:K??pe})}return ee},[C,N,P,a,A,v]);if(!t)return null;const I=n.rgba?`#${n.rgba.slice(0,6)}`:"#808080";return i.jsxs("div",{className:"fixed inset-0 z-[60] bg-bambu-dark flex flex-col",children:[i.jsxs("div",{className:"flex items-center justify-between px-5 py-3 border-b border-zinc-800 shrink-0",children:[i.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[i.jsx("div",{className:"w-7 h-7 rounded-full shrink-0",style:{backgroundColor:I}}),i.jsx("div",{className:"min-w-0",children:i.jsxs("h2",{className:"text-sm font-semibold text-zinc-100 truncate",children:[a("spoolbuddy.modal.assignToAmsTitle","Assign to AMS"),i.jsxs("span",{className:"font-normal text-zinc-500 ml-2",children:[n.color_name||"Unknown"," • ",n.brand," ",n.material,n.subtype&&` ${n.subtype}`]})]})})]}),i.jsx("button",{onClick:e,disabled:G,className:"p-2 rounded-lg text-zinc-500 hover:text-zinc-300 hover:bg-zinc-800 transition-colors shrink-0 disabled:opacity-50",children:i.jsx(qt,{className:"w-5 h-5"})})]}),o&&i.jsxs("div",{className:`mx-5 mt-3 p-3 rounded-lg flex items-center gap-3 border shrink-0 ${c==="info"?"bg-blue-500/10 border-blue-500/40":c==="success"?"bg-green-500/10 border-green-500/40":"bg-red-500/10 border-red-500/40"}`,children:[c==="info"&&i.jsx(ft,{className:"w-4 h-4 text-blue-400 animate-spin shrink-0"}),c==="success"&&i.jsx(pr,{className:"w-4 h-4 text-green-400 shrink-0"}),c==="error"&&i.jsx(Wi,{className:"w-4 h-4 text-red-400 shrink-0"}),i.jsx("span",{className:`text-sm ${c==="info"?"text-blue-300":c==="success"?"text-green-300":"text-red-300"}`,children:o})]}),i.jsx("div",{className:"flex-1 flex flex-col gap-3 p-4 min-h-0",children:!g&&r?i.jsx("div",{className:"flex-1 flex items-center justify-center",children:i.jsx("div",{className:"text-center text-white/50",children:i.jsx("p",{className:"text-lg mb-2",children:a("spoolbuddy.ams.printerDisconnected","Printer disconnected")})})}):_.length===0&&N.length===0?i.jsx("div",{className:"flex-1 flex items-center justify-center",children:i.jsxs("div",{className:"text-center text-white/50",children:[i.jsx(Ki,{className:"w-12 h-12 mx-auto mb-3 opacity-50"}),i.jsx("p",{className:"text-lg mb-2",children:a("spoolbuddy.ams.noData","No AMS detected")}),i.jsx("p",{className:"text-sm",children:a("spoolbuddy.ams.connectAms","Connect an AMS to see filament slots")})]})}):i.jsxs(i.Fragment,{children:[k.length>0&&i.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3 flex-1 min-h-0",children:k.map(ee=>i.jsx(vle,{unit:ee,activeSlot:null,onConfigureSlot:(ae,X)=>z(ee.id,X),isDualNozzle:P,nozzleSide:A(ee.id),thresholds:b,fillOverrides:v},ee.id))}),Z.length>0&&i.jsx("div",{className:"flex gap-2 shrink-0",children:Z.map(({key:ee,label:ae,amsId:X,trayId:ce,tray:ue,isEmpty:pe,nozzleSide:K,effectiveFill:se})=>{const de=Xnt(ue.tray_color);return i.jsxs("div",{onClick:()=>z(X,ce),className:`bg-bambu-dark-secondary rounded-lg px-3 py-2 cursor-pointer hover:bg-bambu-dark-secondary/80 transition-all flex items-center gap-2 ${G?"opacity-50 pointer-events-none":""}`,children:[i.jsx("div",{className:"relative w-10 h-10 shrink-0",children:pe?i.jsx("div",{className:"w-full h-full rounded-full border-2 border-dashed border-gray-500 flex items-center justify-center",children:i.jsx("div",{className:"w-1.5 h-1.5 rounded-full bg-gray-600"})}):i.jsxs("svg",{viewBox:"0 0 56 56",className:"w-full h-full",children:[i.jsx("circle",{cx:"28",cy:"28",r:"26",fill:de}),i.jsx("circle",{cx:"28",cy:"28",r:"20",fill:de,style:{filter:"brightness(0.85)"}}),i.jsx("ellipse",{cx:"20",cy:"20",rx:"6",ry:"4",fill:"white",opacity:"0.3"}),i.jsx("circle",{cx:"28",cy:"28",r:"8",fill:"#2d2d2d"}),i.jsx("circle",{cx:"28",cy:"28",r:"5",fill:"#1a1a1a"})]})}),i.jsxs("div",{className:"min-w-0",children:[i.jsxs("div",{className:"flex items-center gap-1",children:[i.jsx("span",{className:"text-xs text-white/50 font-medium",children:ae}),K&&i.jsx(R5,{side:K})]}),i.jsx("div",{className:"text-sm text-white/80 truncate",children:pe?"Empty":ue.tray_type||"?"})]}),!pe&&se!=null&&se>=0&&i.jsx("div",{className:"w-1.5 h-8 bg-bambu-dark-tertiary rounded-full overflow-hidden shrink-0 flex flex-col-reverse",children:i.jsx("div",{className:"w-full rounded-full",style:{height:`${se}%`,backgroundColor:sx(se)}})})]},ee)})})]})}),i.jsx("div",{className:"flex justify-end gap-3 px-5 py-3 border-t border-zinc-800 shrink-0",children:i.jsx("button",{onClick:e,disabled:G,className:"px-5 py-2.5 rounded-lg text-sm font-medium bg-zinc-800 text-zinc-300 hover:bg-zinc-700 transition-colors min-h-[44px] disabled:opacity-50",children:c==="success"?a("spoolbuddy.dashboard.close","Close"):a("spoolbuddy.modal.cancel","Cancel")})})]})}function Znt({isOpen:t,onClose:e,tagId:n,untaggedSpools:r,onLink:a}){const{t:s}=jt(),[o,l]=w.useState(null),c=w.useCallback(()=>{l(null),e()},[e]),d=w.useCallback(m=>{m.key==="Escape"&&c()},[c]);if(w.useEffect(()=>(t&&(document.addEventListener("keydown",d),document.body.style.overflow="hidden"),()=>{document.removeEventListener("keydown",d),document.body.style.overflow=""}),[t,d]),!t)return null;const u=()=>{o&&(a(o),l(null))};return i.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/70 animate-fade-in",onClick:c,children:i.jsxs("div",{className:"bg-zinc-800 rounded-xl shadow-2xl w-full max-w-lg mx-4 animate-slide-up",onClick:m=>m.stopPropagation(),children:[i.jsxs("div",{className:"flex items-center justify-between px-5 py-4 border-b border-zinc-700",children:[i.jsxs("div",{children:[i.jsx("h2",{className:"text-base font-semibold text-zinc-100",children:s("spoolbuddy.dashboard.linkTagTitle","Link Tag to Spool")}),i.jsx("p",{className:"text-sm text-zinc-500 font-mono",children:n})]}),i.jsx("button",{onClick:c,className:"p-2 rounded-lg text-zinc-500 hover:text-zinc-300 hover:bg-zinc-700 transition-colors",children:i.jsx(qt,{className:"w-5 h-5"})})]}),i.jsxs("div",{className:"px-5 py-4 space-y-3 max-h-[400px] overflow-y-auto",children:[i.jsx("p",{className:"text-sm text-zinc-400",children:s("spoolbuddy.dashboard.selectSpool","Select a spool to link this tag to:")}),r.length===0?i.jsx("div",{className:"text-center py-8 text-zinc-500",children:s("spoolbuddy.dashboard.noUntagged","No spools without tags found")}):i.jsx("div",{className:"space-y-2",children:r.map(m=>i.jsxs("button",{type:"button",onClick:()=>l(m),className:`w-full flex items-center gap-3 p-3 rounded-lg border-2 transition-all text-left ${o?.id===m.id?"border-green-500 bg-green-500/10":"border-zinc-700 hover:border-green-500/50 hover:bg-zinc-700/50"}`,children:[i.jsx(F5,{color:m.rgba?`#${m.rgba.slice(0,6)}`:"#808080",isEmpty:!1,size:40}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsx("div",{className:"font-medium text-zinc-100 truncate",children:m.color_name||"Unknown color"}),i.jsxs("div",{className:"text-sm text-zinc-400 truncate",children:[m.brand," • ",m.material,m.subtype&&` ${m.subtype}`]})]}),i.jsxs("div",{className:"text-sm font-mono text-zinc-500",children:[Math.max(0,m.label_weight-m.weight_used),"g"]})]},m.id))})]}),i.jsxs("div",{className:"flex justify-end gap-2 px-5 py-4 border-t border-zinc-700",children:[i.jsx("button",{onClick:c,className:"px-4 py-2.5 rounded-lg text-sm font-medium bg-zinc-700 text-zinc-300 hover:bg-zinc-600 transition-colors min-h-[44px]",children:s("common.cancel","Cancel")}),i.jsx("button",{onClick:u,disabled:!o,className:"px-4 py-2.5 rounded-lg text-sm font-medium bg-green-600 text-white hover:bg-green-700 disabled:opacity-40 disabled:cursor-not-allowed transition-colors min-h-[44px]",children:s("spoolbuddy.dashboard.linkTag","Link Tag")})]})]})})}const KY=["#00AE42","#FF6B35","#3B82F6","#EF4444","#A855F7","#FBBF24","#14B8A6","#EC4899","#F97316","#22C55E"];function YY(t){return t?t.replace(/[^0-9a-f]/gi,"").toUpperCase():""}function Jnt(t,e){const n=YY(t),r=YY(e);return!n||!r?!1:n===r?!0:n.endsWith(r)||r.endsWith(n)}function ert(){const{t}=jt(),[e,n]=w.useState(0);w.useEffect(()=>{const a=setInterval(()=>{n(s=>(s+1)%KY.length)},2e3);return()=>clearInterval(a)},[]);const r=KY[e];return i.jsxs("div",{className:"flex flex-col items-center text-center",children:[i.jsxs("div",{className:"relative mb-6 flex items-center justify-center",style:{width:160,height:160},children:[i.jsx("div",{className:"absolute w-24 h-24 rounded-full border-2 border-green-500/30 animate-ping",style:{animationDuration:"2.5s"}}),i.jsx("div",{className:"absolute w-32 h-32 rounded-full border border-green-500/20 animate-ping",style:{animationDuration:"2.5s",animationDelay:"0.4s"}}),i.jsx("div",{className:"absolute w-40 h-40 rounded-full border border-green-500/10 animate-ping",style:{animationDuration:"2.5s",animationDelay:"0.8s"}}),i.jsxs("div",{className:"relative",children:[i.jsx("div",{className:"absolute -inset-4 rounded-full blur-2xl opacity-30 transition-colors duration-1000",style:{backgroundColor:r}}),i.jsx("div",{className:"transition-all duration-1000",children:i.jsx(F5,{color:r,isEmpty:!1,size:100})})]})]}),i.jsxs("div",{className:"space-y-2",children:[i.jsx("p",{className:"text-xl font-medium text-zinc-300",children:t("spoolbuddy.dashboard.readyToScan","Ready to scan")}),i.jsx("p",{className:"text-sm text-zinc-500",children:t("spoolbuddy.dashboard.idleMessage","Place a spool on the scale to identify it")})]}),i.jsxs("div",{className:"mt-6 flex items-center gap-2 text-sm text-zinc-600",children:[i.jsx("svg",{className:"w-4 h-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),i.jsx("span",{children:t("spoolbuddy.dashboard.nfcHint","NFC tag will be read automatically")})]})]})}function trt(){const{t}=jt();return i.jsxs("div",{className:"flex flex-col items-center text-center",children:[i.jsx("div",{className:"relative mb-6 flex items-center justify-center",style:{width:160,height:160},children:i.jsx("div",{className:"w-24 h-24 rounded-full bg-zinc-800 flex items-center justify-center",children:i.jsx("svg",{className:"w-12 h-12 text-zinc-600",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"1.5",d:"M18.364 5.636a9 9 0 010 12.728m0 0l-12.728-12.728m12.728 12.728L5.636 5.636m12.728 0a9 9 0 00-12.728 0m0 12.728a9 9 0 010-12.728"})})})}),i.jsxs("div",{className:"space-y-2",children:[i.jsx("p",{className:"text-lg font-medium text-zinc-500",children:t("spoolbuddy.status.deviceOffline","Device Offline")}),i.jsx("p",{className:"text-sm text-zinc-600",children:t("spoolbuddy.status.connectDisplay","Connect the SpoolBuddy display to scan spools")})]}),i.jsxs("div",{className:"mt-6 flex items-center gap-2 text-xs text-zinc-600",children:[i.jsx("svg",{className:"w-4 h-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M8.111 16.404a5.5 5.5 0 017.778 0M12 20h.01m-7.08-7.071c3.904-3.905 10.236-3.905 14.14 0M1.394 9.393c5.857-5.857 15.355-5.857 21.213 0"})}),i.jsx("span",{children:t("spoolbuddy.status.waitingConnection","Waiting for device connection...")})]})]})}function nrt(){const{sbState:t,selectedPrinterId:e}=fw(),{t:n}=jt(),{data:r=[],refetch:a}=et({queryKey:["inventory-spools"],queryFn:()=>be.getSpools(!1)}),{data:s=[]}=et({queryKey:["printers"],queryFn:()=>be.getPrinters()}),o=ig({queries:s.map(K=>({queryKey:["printerStatus",K.id],queryFn:()=>be.getPrinterStatus(K.id),refetchInterval:1e4}))}),[l,c]=w.useState(null),[d,u]=w.useState(null),[m,p]=w.useState(null),[f,y]=w.useState(!1),[v,b]=w.useState(!1),[g,_]=w.useState(!1),[k,C]=w.useState(!1),N=t.matchedSpool?.tag_uid??t.unknownTagUid??null,P=t.weight,T=t.weightStable,j=w.useRef(null);P===null?j.current=null:(j.current===null||Math.abs(P-j.current)>=3||T)&&(j.current=P);const F=j.current,G=w.useMemo(()=>{if(t.matchedSpool?.id){const K=r.find(se=>se.id===t.matchedSpool?.id);if(K)return K}return l?r.find(K=>Jnt(K.tag_uid,l))??null:null},[l,t.matchedSpool,r]),z=w.useMemo(()=>r.filter(K=>!K.tag_uid&&!K.archived_at),[r]);w.useEffect(()=>{if(N){const K=m===N;(l!==null&&l!==N||!K&&l!==N)&&(c(N),u(null),p(null)),!K&&P!==null&&T&&u(Math.round(Math.max(0,P)))}else m&&(c(null),p(null),u(null))},[N,P,T,l,m]);const Z=()=>{p(l)},I=async K=>{if(l)try{await be.linkTagToSpool(K.id,{tag_uid:l,tag_type:"generic",data_origin:"nfc_link"}),y(!1),a()}catch(se){console.error("Failed to link tag:",se)}},ee=async()=>{if(l){C(!0);try{const K=X??d;await be.createSpool({material:"PLA",subtype:null,color_name:null,rgba:null,brand:null,label_weight:1e3,core_weight:250,core_weight_catalog_id:null,weight_used:0,slicer_filament:null,slicer_filament_name:null,nozzle_temp_min:null,nozzle_temp_max:null,note:null,added_full:null,last_used:null,encode_time:null,tag_uid:l,tray_uuid:null,data_origin:"spoolbuddy",tag_type:"generic",cost_per_kg:null,last_scale_weight:K,last_weighed_at:K!==null?new Date().toISOString():null}),_(!1),a()}catch(K){console.error("Failed to quick-add spool:",K)}finally{C(!1)}}},X=P!==null&&(N===l||N===null&&l!==null)?P:null,ce=r.length,ue=new Set(r.map(K=>K.material)).size,pe=new Set(r.filter(K=>K.brand).map(K=>K.brand)).size;return i.jsxs("div",{className:"h-full flex flex-col p-4",children:[i.jsxs("div",{className:"flex items-center gap-6 px-4 py-1.5 bg-zinc-800/50 rounded-xl border border-zinc-700/50 mb-3 shrink-0",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"text-xl font-bold text-zinc-100",children:ce}),i.jsx("span",{className:"text-sm text-zinc-500",children:n("spoolbuddy.inventory.spools","Spools")})]}),i.jsx("div",{className:"w-px h-5 bg-zinc-700"}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"text-xl font-bold text-zinc-100",children:ue}),i.jsx("span",{className:"text-sm text-zinc-500",children:n("spoolbuddy.spool.material","Materials")})]}),i.jsx("div",{className:"w-px h-5 bg-zinc-700"}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"text-xl font-bold text-zinc-100",children:pe}),i.jsx("span",{className:"text-sm text-zinc-500",children:n("spoolbuddy.spool.brand","Brands")})]})]}),i.jsxs("div",{className:"flex-1 flex gap-4 min-h-0",children:[i.jsxs("div",{className:"w-5/12 flex flex-col min-h-0",children:[i.jsxs("div",{className:"border border-dashed border-zinc-700/50 rounded-xl p-4",children:[i.jsx("h2",{className:"text-sm font-semibold text-zinc-400 uppercase tracking-wide mb-3",children:n("spoolbuddy.dashboard.device","Device")}),i.jsxs("div",{className:"space-y-2.5",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:`w-2.5 h-2.5 rounded-full ${t.deviceOnline?"bg-green-500 animate-pulse":"bg-red-500"}`}),i.jsx("span",{className:"text-base text-zinc-400",children:t.deviceOnline?n("spoolbuddy.status.online","Online"):n("spoolbuddy.status.offline","Disconnected")})]}),i.jsxs("div",{className:"flex items-center justify-between p-3 bg-zinc-800/50 rounded-lg",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("svg",{className:`w-4 h-4 ${t.deviceOnline?"text-green-500":"text-zinc-500"}`,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M3 6l3 1m0 0l-3 9a5.002 5.002 0 006.001 0M6 7l3 9M6 7l6-2m6 2l3-1m-3 1l-3 9a5.002 5.002 0 006.001 0M18 7l3 9m-3-9l-6-2m0-2v2m0 16V5m0 16H9m3 0h3"})}),i.jsx("span",{className:"text-sm text-zinc-500",children:n("spoolbuddy.spool.scaleWeight","Scale")})]}),i.jsx("span",{className:"text-lg font-mono font-semibold text-zinc-100",children:F!==null?`${Math.abs(F)<=20?0:Math.round(Math.max(0,F))}g`:"—"})]}),i.jsxs("div",{className:"flex items-center justify-between p-3 bg-zinc-800/50 rounded-lg",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("svg",{className:`w-4 h-4 ${t.deviceOnline?"text-green-500":"text-zinc-500"}`,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M7 7h.01M7 3h5c.512 0 1.024.195 1.414.586l7 7a2 2 0 010 2.828l-7 7a2 2 0 01-2.828 0l-7-7A2 2 0 013 12V7a4 4 0 014-4z"})}),i.jsx("span",{className:"text-sm text-zinc-500",children:"NFC"})]}),i.jsx("span",{className:`text-sm font-medium ${N?"text-green-500":"text-zinc-500"}`,children:N?n("spoolbuddy.dashboard.tagDetected","Tag detected"):n("spoolbuddy.dashboard.noTag","No tag")})]})]})]}),s.length>0&&i.jsxs("div",{className:"mt-3 border border-dashed border-zinc-700/50 rounded-xl p-4",children:[i.jsx("h2",{className:"text-sm font-semibold text-zinc-400 uppercase tracking-wide mb-2.5",children:n("spoolbuddy.dashboard.printers","Printers")}),i.jsx("div",{className:"flex flex-wrap gap-2 overflow-hidden",children:s.map((K,se)=>{const de=o[se]?.data?.connected??!1;return i.jsxs("div",{className:"flex items-center gap-1.5 px-2.5 py-1 bg-zinc-800/50 rounded-lg",title:`${K.name} — ${de?"Online":"Offline"}`,children:[i.jsx("div",{className:`w-2 h-2 rounded-full shrink-0 ${de?"bg-green-500":"bg-zinc-600"}`}),i.jsx("span",{className:"text-xs text-zinc-400 truncate max-w-[100px]",children:K.name})]},K.id)})})]})]}),i.jsx("div",{className:"w-7/12 min-h-0",children:i.jsxs("div",{className:"border border-dashed border-zinc-700/50 rounded-xl p-6 h-full flex flex-col",children:[i.jsx("h2",{className:"text-sm font-semibold text-zinc-400 uppercase tracking-wide mb-4 shrink-0",children:n("spoolbuddy.dashboard.currentSpool","Current Spool")}),i.jsx("div",{className:"flex-1 flex items-center justify-center min-h-0",children:t.deviceOnline?(G||t.matchedSpool)&&l&&m!==l?i.jsx(Int,{spool:{id:G?.id??t.matchedSpool.id,tag_uid:l,material:G?.material??t.matchedSpool.material,subtype:G?.subtype??t.matchedSpool.subtype,color_name:G?.color_name??t.matchedSpool.color_name,rgba:G?.rgba??t.matchedSpool.rgba,brand:G?.brand??t.matchedSpool.brand,label_weight:G?.label_weight??t.matchedSpool.label_weight,core_weight:G?.core_weight??t.matchedSpool.core_weight,weight_used:G?.weight_used??t.matchedSpool.weight_used},scaleWeight:X??d,onSyncWeight:()=>a(),onAssignToAms:()=>b(!0),onClose:Z}):N&&l&&!G&&!t.matchedSpool&&m!==l?i.jsx(znt,{tagUid:l,scaleWeight:X??d,onLinkSpool:z.length>0?()=>y(!0):void 0,onAddToInventory:()=>_(!0),onClose:Z}):i.jsx(ert,{}):i.jsx(trt,{})})]})})]}),G&&l&&i.jsx(Qnt,{isOpen:v,onClose:()=>b(!1),spool:G,printerId:e}),l&&i.jsx(Znt,{isOpen:f,onClose:()=>y(!1),tagId:l,untaggedSpools:z,onLink:I}),g&&l&&i.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60",children:i.jsxs("div",{className:"bg-zinc-800 rounded-2xl p-6 mx-4 max-w-sm w-full border border-zinc-700",children:[i.jsx("h3",{className:"text-lg font-semibold text-zinc-100 mb-3",children:n("spoolbuddy.modal.addToInventory","Add to Inventory")}),i.jsxs("div",{className:"flex gap-2.5 p-3 bg-amber-500/10 border border-amber-500/20 rounded-lg mb-4",children:[i.jsx("svg",{className:"w-5 h-5 text-amber-500 shrink-0 mt-0.5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),i.jsx("p",{className:"text-sm text-amber-200/80",children:n("spoolbuddy.modal.quickAddHint",'For best results, add the spool in the Bambuddy web interface first (with material, color, brand), then use "Link to Spool" here to assign the NFC tag.')})]}),i.jsx("p",{className:"text-sm text-zinc-400 mb-1",children:n("spoolbuddy.modal.quickAddDesc","This will create a basic PLA spool entry with this NFC tag. You can edit the details later in Bambuddy.")}),i.jsx("p",{className:"text-xs text-zinc-500 font-mono mb-5",children:l}),i.jsxs("div",{className:"flex gap-3",children:[i.jsx("button",{onClick:()=>_(!1),className:"flex-1 px-4 py-2.5 rounded-lg text-sm font-medium bg-zinc-700 text-zinc-300 hover:bg-zinc-600 transition-colors min-h-[44px]",children:n("common.cancel","Cancel")}),i.jsx("button",{onClick:ee,disabled:k,className:"flex-1 px-4 py-2.5 rounded-lg text-sm font-medium bg-green-600 text-white hover:bg-green-700 disabled:opacity-50 transition-colors min-h-[44px]",children:k?n("common.saving","Saving..."):n("spoolbuddy.modal.addAnyway","Add Anyway")})]})]})})]})}function a3(t){return t<=3?`AMS ${String.fromCharCode(65+t)}`:t>=128&&t<=135?`AMS HT ${String.fromCharCode(65+t-128)}`:`AMS ${t}`}function rrt(t){return t?{O1D:"H2D",O1E:"H2D Pro",O2D:"H2D Pro",O1C:"H2C",O1C2:"H2C",O1S:"H2S","BL-P001":"X1C","BL-P002":"X1","BL-P003":"X1E",C11:"P1S",C12:"P1P",C13:"P2S",N2S:"A1",N1:"A1 Mini",X1C:"X1C",X1:"X1",X1E:"X1E",P1S:"P1S",P1P:"P1P",P2S:"P2S",A1:"A1","A1 Mini":"A1 Mini",H2D:"H2D","H2D Pro":"H2D Pro",H2C:"H2C",H2S:"H2S"}[t]||t:""}function zp(t){return!t.tray_type||t.tray_type===""}function irt(t){return t?`#${t.slice(0,6)}`:"#808080"}function art(){const{selectedPrinterId:t,setAlert:e}=fw(),{t:n}=jt(),r=cn(),{showToast:a}=pn(),{data:s}=et({queryKey:["printerStatus",t],queryFn:()=>be.getPrinterStatus(t),enabled:t!==null,staleTime:30*1e3}),{data:o}=et({queryKey:["printer",t],queryFn:()=>be.getPrinter(t),enabled:t!==null,staleTime:60*1e3}),{data:l}=et({queryKey:["slotPresets",t],queryFn:()=>be.getSlotPresets(t),enabled:t!==null,staleTime:120*1e3}),{data:c}=et({queryKey:["settings"],queryFn:()=>be.getSettings(),staleTime:300*1e3}),{data:d}=et({queryKey:["spoolman-status"],queryFn:be.getSpoolmanStatus,staleTime:60*1e3}),u=d?.enabled&&d?.connected,{data:m}=et({queryKey:["linked-spools"],queryFn:be.getLinkedSpools,enabled:!!u,staleTime:30*1e3}),p=m?.linked,{data:f}=et({queryKey:["spool-assignments",t],queryFn:()=>be.getAssignments(t),enabled:t!==null,staleTime:30*1e3}),y=w.useMemo(()=>{const Y={};if(!f)return Y;for(const q of f){const te=q.spool;if(te&&te.label_weight>0&&te.weight_used!=null){const oe=Math.round(Math.max(0,te.label_weight-te.weight_used)/te.label_weight*100);Y[`${q.ams_id}-${q.tray_id}`]=oe}}return Y},[f]),v=o?.serial_number??"",b=w.useCallback((Y,q,te)=>{if(!p||!v)return null;const oe=(te?.tray_uuid||te?.tag_uid||wu(v,Y,q))?.toUpperCase(),he=oe?p[oe]:void 0;return yk(he)},[p,v]),g=s?.connected??!1,_=w.useRef([]);w.useEffect(()=>{s?.ams&&s.ams.length>0&&(_.current=s.ams)},[s?.ams]);const k=w.useMemo(()=>{const Y=s?.ams;return Y&&Y.length>0?Y:_.current??[]},[s?.ams]),C=w.useMemo(()=>k.filter(Y=>!Y.is_ams_ht),[k]),N=w.useMemo(()=>k.filter(Y=>Y.is_ams_ht),[k]),P=w.useMemo(()=>{const Y={};if(!p||!v)return Y;for(const q of C)for(let te=0;te<(q.tray?.length??0);te++){const oe=q.tray[te],he=b(q.id,te,zp(oe)?null:oe);he!==null&&(Y[`${q.id}-${te}`]=he)}return Y},[p,v,C,b]),T=w.useRef(void 0),j=s?.tray_now;j!==void 0&&j!==255?T.current=j:j===255&&(T.current=void 0);const A=j!==void 0&&j!==255?j:T.current,F=o?.nozzle_count===2||s?.temperatures?.nozzle_2!==void 0,G=w.useMemo(()=>[...s?.vt_tray??[]].sort((Y,q)=>(Y.id??254)-(q.id??254)),[s?.vt_tray]),z=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,Z=w.useRef({});w.useEffect(()=>{s?.ams_extruder_map&&Object.keys(s.ams_extruder_map).length>0&&(Z.current=s.ams_extruder_map)},[s?.ams_extruder_map]);const I=s?.ams_extruder_map&&Object.keys(s.ams_extruder_map).length>0?s.ams_extruder_map:Z.current,ee=w.useCallback(Y=>{if(!F)return null;const q=I[String(Y)],te=Y>=128?Y-128:Y;return(q!==void 0?q:te)===1?"L":"R"},[F,I]),[ae,X]=w.useState(null),[ce,ue]=w.useState(null),[pe,K]=w.useState(null),[se,de]=w.useState(null),ge=w.useCallback((Y,q)=>f?.find(te=>te.ams_id===Number(Y)&&te.tray_id===Number(q)),[f]),Te=w.useCallback((Y,q,te)=>{if(!p||!v)return;const oe=(te?.tray_uuid||te?.tag_uid||wu(v,Y,q))?.toUpperCase();return oe?p[oe]:void 0},[p,v]),V=pt({mutationFn:({printerId:Y,amsId:q,trayId:te})=>be.unassignSpool(Y,q,te),onSuccess:()=>{r.invalidateQueries({queryKey:["spool-assignments",t]}),a(n("inventory.unassignSuccess","Spool unassigned"),"success"),ue(null)}}),J=pt({mutationFn:Y=>be.unlinkSpool(Y),onSuccess:Y=>{a(n("spoolman.unlinkSuccess")||Y?.message,"success"),r.invalidateQueries({queryKey:["linked-spools"]}),r.invalidateQueries({queryKey:["unlinked-spools"]}),ue(null)},onError:Y=>{a(Y.message||n("spoolman.unlinkFailed"),"error")}}),D=w.useCallback(Y=>A===void 0?null:Y<=3&&Math.floor(A/4)===Y?A%4:Y>=128&&Y<=135&&A===Dx(Y,0,!1)?0:null,[A]),E=w.useCallback((Y,q,te)=>{const oe=Y>=128?(Y-128)*4+q+64:Y*4+q,he=l?.[oe],fe=I[String(Y)],re=Y>=128?Y-128:Y,L=fe!==void 0?fe:re,R={amsId:Y,trayId:q,trayCount:te&&Y>=128?1:4,tray:te,trayType:te?.tray_type||void 0,trayColor:te?.tray_color||void 0,traySubBrands:te?.tray_sub_brands||void 0,trayInfoIdx:te?.tray_info_idx||void 0,extruderId:F?L:void 0,caliIdx:te?.cali_idx,savedPresetId:he?.preset_id,location:`${a3(Y)} Slot ${q+1}`};ue(R)},[l,I,F]),U=w.useCallback(Y=>{const q=Y.id??254,te=q-254,oe=l?.[1020+te],he={amsId:255,trayId:te,trayCount:1,tray:zp(Y)?null:Y,trayType:Y.tray_type||void 0,trayColor:Y.tray_color||void 0,traySubBrands:Y.tray_sub_brands||void 0,trayInfoIdx:Y.tray_info_idx||void 0,extruderId:F?q===254?1:0:void 0,caliIdx:Y.cali_idx,savedPresetId:oe?.preset_id,location:F?q===254?"Ext-L":"Ext-R":"External"};ue(he)},[l,F]),W=w.useCallback(()=>{if(!ce)return;const{tray:Y,location:q,...te}=ce;ue(null),X(te)},[ce]),B=w.useCallback(()=>{if(!ce||!t)return;const{amsId:Y,trayId:q,trayType:te,trayColor:oe,location:he}=ce;ue(null),K({printerId:t,amsId:Y,trayId:q,trayInfo:{type:te||"",material:te,color:oe?.slice(0,6)||"",location:he}})},[ce,t]),ie=w.useCallback(()=>{if(!ce||!t)return;const{amsId:Y,trayId:q,tray:te}=ce,oe=(te?.tray_uuid||te?.tag_uid||wu(v,Y,q))?.toUpperCase()||"";ue(null),de({tagUid:te?.tag_uid||oe,trayUuid:te?.tray_uuid||"",printerId:t,amsId:Y,trayId:q})},[ce,t,v]),O=w.useCallback(()=>{if(!ce||!t)return;const{amsId:Y,trayId:q}=ce;V.mutate({printerId:t,amsId:Y,trayId:q})},[ce,t,V]);w.useEffect(()=>{if(!g&&t){e({type:"warning",message:n("spoolbuddy.ams.printerDisconnected","Printer disconnected")});return}for(const Y of k)for(const q of Y.tray||[])if(q.remain!==null&&q.remain>=0&&q.remain<15&&q.tray_type){e({type:"warning",message:`Low Filament: ${q.tray_type} (${a3(Y.id)}) - ${q.remain}% remaining`});return}e(null)},[k,g,t,e,n]);const $=w.useMemo(()=>{const Y=[];for(const q of N){const te=q.tray?.[0]||{id:0,tray_color:null,tray_type:"",tray_sub_brands:null,tray_id_name:null,tray_info_idx:null,remain:-1,k:null,cali_idx:null,tag_uid:null,tray_uuid:null,nozzle_temp_min:null,nozzle_temp_max:null},oe=b(q.id,0,zp(te)?null:te),he=y[`${q.id}-0`]??null,fe=te.remain!=null&&te.remain>=0?te.remain:null,re=he===0&&fe!==null&&fe>0?null:he;Y.push({key:`ht-${q.id}`,label:a3(q.id),tray:te,isEmpty:zp(te),isActive:D(q.id)===0,temp:q.temp,humidity:q.humidity,nozzleSide:ee(q.id),effectiveFill:oe??re??fe,onClick:()=>E(q.id,0,zp(te)?null:te)})}for(const q of G){const te=q.id??254,oe=F&&A===254?te===254&&s?.active_extruder===1||te===255&&s?.active_extruder===0:A===te,he=te-254,fe=b(255,he,zp(q)?null:q),re=y[`255-${he}`]??null,L=q.remain!=null&&q.remain>=0?q.remain:null,R=re===0&&L!==null&&L>0?null:re;Y.push({key:`ext-${te}`,label:F?te===254?n("printers.extL","Ext-L"):n("printers.extR","Ext-R"):n("printers.ext","Ext"),tray:q,isEmpty:zp(q),isActive:oe,nozzleSide:null,effectiveFill:fe??R??L,onClick:()=>U(q)})}return Y},[N,G,F,A,s?.active_extruder,n,D,ee,E,U,y,b]);return i.jsxs("div",{className:"h-full flex flex-col p-4",children:[i.jsx("div",{className:"flex-1 min-h-0",children:t?g?k.length===0&&G.length===0?i.jsx("div",{className:"flex-1 flex items-center justify-center h-full",children:i.jsxs("div",{className:"text-center text-white/50",children:[i.jsx(Ki,{className:"w-12 h-12 mx-auto mb-3 opacity-50"}),i.jsx("p",{className:"text-lg mb-2",children:n("spoolbuddy.ams.noData","No AMS detected")}),i.jsx("p",{className:"text-sm",children:n("spoolbuddy.ams.connectAms","Connect an AMS to see filament slots")})]})}):i.jsxs("div",{className:"flex flex-col gap-3 h-full",children:[i.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:C.map(Y=>i.jsx(vle,{unit:Y,activeSlot:D(Y.id),onConfigureSlot:E,isDualNozzle:F,nozzleSide:ee(Y.id),thresholds:z,fillOverrides:y,spoolmanFillOverrides:P},Y.id))}),$.length>0&&i.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:$.map(({key:Y,label:q,tray:te,isEmpty:oe,isActive:he,temp:fe,humidity:re,nozzleSide:L,effectiveFill:R,onClick:ne})=>{const ve=irt(te.tray_color);return i.jsxs("div",{className:`bg-bambu-dark-secondary rounded-lg px-3 py-2 cursor-pointer hover:bg-bambu-dark-secondary/80 transition-all flex items-center gap-3 ${he?"ring-2 ring-bambu-green":""}`,onClick:ne,children:[i.jsxs("div",{className:"relative w-10 h-10 flex-shrink-0",children:[oe?i.jsx("div",{className:"w-full h-full rounded-full border-2 border-dashed border-gray-500 flex items-center justify-center",children:i.jsx("div",{className:"w-1.5 h-1.5 rounded-full bg-gray-600"})}):i.jsxs("svg",{viewBox:"0 0 56 56",className:"w-full h-full",children:[i.jsx("circle",{cx:"28",cy:"28",r:"26",fill:ve}),i.jsx("circle",{cx:"28",cy:"28",r:"20",fill:ve,style:{filter:"brightness(0.85)"}}),i.jsx("ellipse",{cx:"20",cy:"20",rx:"6",ry:"4",fill:"white",opacity:"0.3"}),i.jsx("circle",{cx:"28",cy:"28",r:"8",fill:"#2d2d2d"}),i.jsx("circle",{cx:"28",cy:"28",r:"5",fill:"#1a1a1a"})]}),he&&i.jsx("div",{className:"absolute -bottom-0.5 left-1/2 -translate-x-1/2 w-1.5 h-1.5 bg-bambu-green rounded-full"})]}),i.jsxs("div",{className:"min-w-0",children:[i.jsxs("div",{className:"flex items-center gap-1",children:[i.jsx("span",{className:"text-xs text-white/50 font-medium truncate",children:q}),L&&i.jsx(R5,{side:L})]}),i.jsx("div",{className:"text-sm text-white/80 truncate",children:oe?"Empty":te.tray_type||"?"}),(fe!=null||re!=null)&&i.jsxs("div",{className:"flex items-center gap-1.5",children:[fe!=null&&i.jsx(yle,{temp:fe,goodThreshold:z?.tempGood,fairThreshold:z?.tempFair}),re!=null&&i.jsx(xle,{humidity:re,goodThreshold:z?.humidityGood,fairThreshold:z?.humidityFair})]})]}),!oe&&R!=null&&R>=0&&i.jsx("div",{className:"w-1.5 h-8 bg-bambu-dark-tertiary rounded-full overflow-hidden flex-shrink-0 flex flex-col-reverse",children:i.jsx("div",{className:"w-full rounded-full",style:{height:`${R}%`,backgroundColor:sx(R)}})})]},Y)})})]}):i.jsx("div",{className:"flex-1 flex items-center justify-center h-full",children:i.jsx("div",{className:"text-center text-white/50",children:i.jsx("p",{className:"text-lg mb-2",children:n("spoolbuddy.ams.printerDisconnected","Printer disconnected")})})}):i.jsx("div",{className:"flex-1 flex items-center justify-center h-full",children:i.jsxs("div",{className:"text-center text-white/50",children:[i.jsx("p",{className:"text-lg mb-2",children:n("spoolbuddy.ams.noPrinter","No printer selected")}),i.jsx("p",{className:"text-sm",children:n("spoolbuddy.ams.selectPrinter","Select a printer from the top bar")})]})})}),ae&&t&&i.jsx(oie,{isOpen:!!ae,onClose:()=>X(null),printerId:t,slotInfo:ae,printerModel:rrt(o?.model??null)||void 0,fullScreen:!0,onSuccess:()=>{r.invalidateQueries({queryKey:["slotPresets",t]}),r.invalidateQueries({queryKey:["printerStatus",t]})}}),ce&&t&&(()=>{const Y=ge(ce.amsId,ce.trayId),q=Te(ce.amsId,ce.trayId,ce.tray);return i.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[i.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:()=>ue(null)}),i.jsxs("div",{className:"relative w-full max-w-sm mx-4 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl",children:[i.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[ce.trayColor&&i.jsx("span",{className:"w-4 h-4 rounded-full border border-black/20",style:{backgroundColor:`#${ce.trayColor.slice(0,6)}`}}),i.jsx("h2",{className:"text-lg font-semibold text-white",children:ce.location}),ce.traySubBrands&&i.jsxs("span",{className:"text-sm text-bambu-gray",children:["(",ce.traySubBrands,")"]})]}),i.jsx("button",{onClick:()=>ue(null),className:"p-1 text-bambu-gray hover:text-white rounded transition-colors",children:i.jsx(qt,{className:"w-5 h-5"})})]}),i.jsxs("div",{className:"p-4 space-y-2",children:[!u&&Y?.spool&&i.jsxs("div",{className:"p-2.5 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary mb-3",children:[i.jsx("p",{className:"text-xs text-bambu-gray mb-1",children:n("inventory.assignedSpool","Assigned spool")}),i.jsxs("div",{className:"flex items-center gap-2",children:[Y.spool.rgba&&i.jsx("span",{className:"w-3 h-3 rounded-full border border-black/20 flex-shrink-0",style:{backgroundColor:`#${Y.spool.rgba.substring(0,6)}`}}),i.jsxs("span",{className:"text-sm text-white",children:[Y.spool.brand?`${Y.spool.brand} `:"",Y.spool.material,Y.spool.color_name?` - ${Y.spool.color_name}`:""]})]})]}),u&&q&&i.jsxs("div",{className:"p-2.5 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary mb-3",children:[i.jsx("p",{className:"text-xs text-bambu-gray mb-1",children:n("spoolman.linkedSpool","Linked spool")}),i.jsx("div",{className:"flex items-center gap-2",children:i.jsxs("span",{className:"text-sm text-white",children:["Spoolman #",q.id,q.remaining_weight!=null?` (${Math.round(q.remaining_weight)}g)`:""]})})]}),i.jsxs("button",{onClick:W,className:"w-full flex items-center gap-3 p-3 rounded-lg bg-bambu-dark border border-bambu-dark-tertiary hover:border-bambu-blue transition-colors text-left",children:[i.jsx(yd,{className:"w-5 h-5 text-bambu-blue flex-shrink-0"}),i.jsxs("div",{children:[i.jsx("p",{className:"text-white font-medium",children:n("configureAmsSlot.title")}),i.jsx("p",{className:"text-xs text-bambu-gray",children:n("spoolbuddy.ams.configureDesc","Set filament preset, K-profile, and color")})]})]}),!u&&i.jsxs("button",{onClick:B,className:"w-full flex items-center gap-3 p-3 rounded-lg bg-bambu-dark border border-bambu-dark-tertiary hover:border-bambu-green transition-colors text-left",children:[i.jsx(Ii,{className:"w-5 h-5 text-bambu-green flex-shrink-0"}),i.jsxs("div",{children:[i.jsx("p",{className:"text-white font-medium",children:n("inventory.assignSpool")}),i.jsx("p",{className:"text-xs text-bambu-gray",children:n("spoolbuddy.ams.assignDesc","Track a spool from your inventory")})]})]}),!u&&Y&&i.jsxs("button",{onClick:O,disabled:V.isPending,className:"w-full flex items-center gap-3 p-3 rounded-lg bg-bambu-dark border border-bambu-dark-tertiary hover:border-amber-500 transition-colors text-left",children:[i.jsx(Df,{className:"w-5 h-5 text-amber-400 flex-shrink-0"}),i.jsxs("div",{children:[i.jsx("p",{className:"text-amber-400 font-medium",children:n("inventory.unassignSpool","Unassign")}),i.jsx("p",{className:"text-xs text-bambu-gray",children:n("spoolbuddy.ams.unassignDesc","Remove inventory spool from this slot")})]})]}),u&&i.jsxs("button",{onClick:ie,className:"w-full flex items-center gap-3 p-3 rounded-lg bg-bambu-dark border border-bambu-dark-tertiary hover:border-bambu-green transition-colors text-left",children:[i.jsx(Fu,{className:"w-5 h-5 text-bambu-green flex-shrink-0"}),i.jsxs("div",{children:[i.jsx("p",{className:"text-white font-medium",children:n("spoolman.linkToSpoolman")}),i.jsx("p",{className:"text-xs text-bambu-gray",children:n("spoolbuddy.ams.linkDesc","Link a Spoolman spool to this slot")})]})]}),u&&q?.id&&i.jsxs("button",{onClick:()=>J.mutate(q.id),disabled:J.isPending,className:"w-full flex items-center gap-3 p-3 rounded-lg bg-bambu-dark border border-bambu-dark-tertiary hover:border-amber-500 transition-colors text-left",children:[i.jsx(Df,{className:"w-5 h-5 text-amber-400 flex-shrink-0"}),i.jsxs("div",{children:[i.jsx("p",{className:"text-amber-400 font-medium",children:n("spoolman.unlinkSpool")}),i.jsx("p",{className:"text-xs text-bambu-gray",children:n("spoolbuddy.ams.unlinkDesc","Remove Spoolman link from this slot")})]})]})]})]})]})})(),pe&&i.jsx(sie,{isOpen:!!pe,onClose:()=>{K(null),r.invalidateQueries({queryKey:["spool-assignments",t]})},printerId:pe.printerId,amsId:pe.amsId,trayId:pe.trayId,trayInfo:pe.trayInfo}),se&&i.jsx(aie,{isOpen:!!se,onClose:()=>de(null),tagUid:se.tagUid,trayUuid:se.trayUuid,printerId:se.printerId,amsId:se.amsId,trayId:se.trayId})]})}function wle({type:t,deviceId:e,onClose:n}){const{t:r}=jt(),[a,s]=w.useState(!1),[o,l]=w.useState(""),[c,d]=w.useState(""),[u,m]=w.useState(!1);w.useEffect(()=>{const y=v=>{v.key==="Escape"&&!a&&n()};return window.addEventListener("keydown",y),()=>window.removeEventListener("keydown",y)},[a,n]);const p=w.useCallback(async()=>{s(!0),l(""),d(""),m(!0);try{l(r("spoolbuddy.diagnostic.queuing",`Queuing diagnostic on device... +In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)})()}function X(V,J){(J==null||J>V.length)&&(J=V.length);for(var D=0,E=Array(J);D1&&arguments[1]!==void 0?arguments[1]:E;this.caretPosition=E,this.caretPositionEnd=U}},{key:"getInputCandidates",value:function(E){var U=this,W=this.options,B=W.layoutCandidates,ie=W.layoutCandidatesCaseSensitiveMatch;if(!B||ce(B)!=="object")return{};var O=Object.keys(B).filter((function(q){var te=E.substring(0,U.getCaretPositionEnd()||0)||E,oe=new RegExp("".concat(U.utilities.escapeRegex(q),"$"),ie?"g":"gi");return!!ae(te.matchAll(oe)).length}));if(O.length>1){var $=O.sort((function(q,te){return te.length-q.length}))[0];return{candidateKey:$,candidateValue:B[$]}}if(O.length){var Y=O[0];return{candidateKey:Y,candidateValue:B[Y]}}return{}}},{key:"showCandidatesBox",value:function(E,U,W){var B=this;this.candidateBox&&this.candidateBox.show({candidateValue:U,targetElement:W,onSelect:function(ie,O){var $=B.options,Y=$.layoutCandidatesCaseSensitiveMatch,q=$.disableCandidateNormalization,te=$.enableLayoutCandidatesKeyPress,oe=ie;q||(oe=ie.normalize("NFD")),typeof B.options.beforeInputUpdate=="function"&&B.options.beforeInputUpdate(B);var he=B.getInput(B.options.inputName,!0),fe=B.getCaretPositionEnd()||0,re=he.substring(0,fe||0)||he,L=new RegExp("".concat(B.utilities.escapeRegex(E),"$"),Y?"g":"gi"),R=re.replace(L,oe),ne=he.replace(re,R),ve=R.length-re.length,we=(fe||he.length)+ve;we<0&&(we=0),B.setInput(ne,B.options.inputName,!0),B.setCaretPosition(we),te&&typeof B.options.onKeyPress=="function"&&B.options.onKeyPress(ie,O),typeof B.options.onChange=="function"&&B.options.onChange(B.getInput(B.options.inputName,!0),O),typeof B.options.onChangeAll=="function"&&B.options.onChangeAll(B.getAllInputs(),O)}})}},{key:"handleButtonClicked",value:function(E,U){var W=this.options,B=W.inputName,ie=B===void 0?this.defaultName:B,O=W.debug;if(E!=="{//}"){this.input[ie]||(this.input[ie]=""),typeof this.options.beforeInputUpdate=="function"&&this.options.beforeInputUpdate(this);var $=this.utilities.getUpdatedInput(E,this.input[ie],this.caretPosition,this.caretPositionEnd);if(this.utilities.isStandardButton(E)&&this.activeInputElement&&this.input[ie]&&this.input[ie]===$&&this.caretPosition===0&&this.caretPositionEnd===$.length)return this.setInput("",this.options.inputName,!0),this.setCaretPosition(0),this.activeInputElement.value="",this.activeInputElement.setSelectionRange(0,0),void this.handleButtonClicked(E,U);if(typeof this.options.onKeyPress=="function"&&this.options.onKeyPress(E,U),this.input[ie]!==$&&(!this.options.inputPattern||this.options.inputPattern&&this.inputPatternIsValid($))){if(this.options.maxLength&&this.utilities.handleMaxLength(this.input,$))return;var Y=this.utilities.getUpdatedInput(E,this.input[ie],this.caretPosition,this.caretPositionEnd,!0);if(this.setInput(Y,this.options.inputName,!0),O&&console.log("Input changed:",this.getAllInputs()),this.options.debug&&console.log("Caret at: ",this.getCaretPosition(),this.getCaretPositionEnd(),"(".concat(this.keyboardDOMClass,")"),U?.type),this.options.syncInstanceInputs&&this.syncInstanceInputs(),typeof this.options.onChange=="function"&&this.options.onChange(this.getInput(this.options.inputName,!0),U),typeof this.options.onChangeAll=="function"&&this.options.onChangeAll(this.getAllInputs(),U),U!=null&&U.target&&this.options.enableLayoutCandidates){var q,te=this.getInputCandidates($),oe=te.candidateKey,he=te.candidateValue;oe&&he?this.showCandidatesBox(oe,he,this.keyboardDOM):(q=this.candidateBox)===null||q===void 0||q.destroy()}}this.caretPositionEnd&&this.caretPosition!==this.caretPositionEnd&&(this.setCaretPosition(this.caretPositionEnd,this.caretPositionEnd),this.activeInputElement&&this.activeInputElement.setSelectionRange(this.caretPositionEnd,this.caretPositionEnd),this.options.debug&&console.log("Caret position aligned",this.caretPosition)),O&&console.log("Key pressed:",E)}}},{key:"getMouseHold",value:function(){return this.isMouseHold}},{key:"setMouseHold",value:function(E){this.options.syncInstanceInputs?this.dispatch((function(U){U.isMouseHold=E})):this.isMouseHold=E}},{key:"handleButtonMouseDown",value:function(E,U){var W=this;U&&(this.options.preventMouseDownDefault&&U.preventDefault(),this.options.stopMouseDownPropagation&&U.stopPropagation(),U.target.classList.add(this.activeButtonClass)),this.holdInteractionTimeout&&clearTimeout(this.holdInteractionTimeout),this.holdTimeout&&clearTimeout(this.holdTimeout),this.setMouseHold(!0),this.options.disableButtonHold||(this.holdTimeout=window.setTimeout((function(){(W.getMouseHold()&&(!E.includes("{")&&!E.includes("}")||E==="{delete}"||E==="{backspace}"||E==="{bksp}"||E==="{space}"||E==="{tab}")||E==="{arrowright}"||E==="{arrowleft}"||E==="{arrowup}"||E==="{arrowdown}")&&(W.options.debug&&console.log("Button held:",E),W.handleButtonHold(E)),clearTimeout(W.holdTimeout)}),500))}},{key:"handleButtonMouseUp",value:function(E,U){var W=this;U&&(this.options.preventMouseUpDefault&&U.preventDefault&&U.preventDefault(),this.options.stopMouseUpPropagation&&U.stopPropagation&&U.stopPropagation(),!(U.target===this.keyboardDOM||U.target&&this.keyboardDOM.contains(U.target)||this.candidateBox&&this.candidateBox.candidateBoxElement&&(U.target===this.candidateBox.candidateBoxElement||U.target&&this.candidateBox.candidateBoxElement.contains(U.target)))&&this.candidateBox&&this.candidateBox.destroy()),this.recurseButtons((function(B){B.classList.remove(W.activeButtonClass)})),this.setMouseHold(!1),this.holdInteractionTimeout&&clearTimeout(this.holdInteractionTimeout),E&&typeof this.options.onKeyReleased=="function"&&this.options.onKeyReleased(E,U)}},{key:"handleKeyboardContainerMouseDown",value:function(E){this.options.preventMouseDownDefault&&E.preventDefault()}},{key:"handleButtonHold",value:function(E){var U=this;this.holdInteractionTimeout&&clearTimeout(this.holdInteractionTimeout),this.holdInteractionTimeout=window.setTimeout((function(){U.getMouseHold()?(U.handleButtonClicked(E),U.handleButtonHold(E)):clearTimeout(U.holdInteractionTimeout)}),100)}},{key:"syncInstanceInputs",value:function(){var E=this;this.dispatch((function(U){U.replaceInput(E.input),U.setCaretPosition(E.caretPosition,E.caretPositionEnd)}))}},{key:"clearInput",value:function(){var E=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.options.inputName||this.defaultName;this.input[E]="",this.setCaretPosition(0),this.options.syncInstanceInputs&&this.syncInstanceInputs()}},{key:"getInput",value:function(){var E=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.options.inputName||this.defaultName,U=arguments.length>1&&arguments[1]!==void 0&&arguments[1];return this.options.syncInstanceInputs&&!U&&this.syncInstanceInputs(),this.options.rtl?"‫"+this.input[E].replace("‫","").replace("‬","")+"‬":this.input[E]}},{key:"getAllInputs",value:function(){var E=this,U={};return Object.keys(this.input).forEach((function(W){U[W]=E.getInput(W,!0)})),U}},{key:"setInput",value:function(E){var U=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.options.inputName||this.defaultName,W=arguments.length>2?arguments[2]:void 0;this.input[U]=E,!W&&this.options.syncInstanceInputs&&this.syncInstanceInputs()}},{key:"replaceInput",value:function(E){this.input=E}},{key:"setOptions",value:function(){var E=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},U=this.changedOptions(E);this.options=Object.assign(this.options,E),U.length&&(this.options.debug&&console.log("changedOptions",U),this.onSetOptions(U),this.render())}},{key:"changedOptions",value:function(E){var U=this;return Object.keys(E).filter((function(W){return JSON.stringify(E[W])!==JSON.stringify(U.options[W])}))}},{key:"onSetOptions",value:function(){var E=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];E.includes("layoutName")&&this.candidateBox&&this.candidateBox.destroy(),(E.includes("layoutCandidatesPageSize")||E.includes("layoutCandidates"))&&this.candidateBox&&(this.candidateBox.destroy(),this.candidateBox=new ee({utilities:this.utilities,options:this.options}))}},{key:"resetRows",value:function(){this.keyboardRowsDOM&&this.keyboardRowsDOM.remove(),this.keyboardDOM.className=this.keyboardDOMClass,this.keyboardDOM.setAttribute("data-skInstance",this.currentInstanceName),this.buttonElements={}}},{key:"dispatch",value:function(E){if(!window.SimpleKeyboardInstances)throw console.warn("SimpleKeyboardInstances is not defined. Dispatch cannot be called."),new Error("INSTANCES_VAR_ERROR");return Object.keys(window.SimpleKeyboardInstances).forEach((function(U){E(window.SimpleKeyboardInstances[U],U)}))}},{key:"addButtonTheme",value:function(E,U){var W=this;U&&E&&(E.split(" ").forEach((function(B){U.split(" ").forEach((function(ie){W.options.buttonTheme||(W.options.buttonTheme=[]);var O=!1;W.options.buttonTheme.map((function($){if($!=null&&$.class.split(" ").includes(ie)){O=!0;var Y=$.buttons.split(" ");Y.includes(B)||(O=!0,Y.push(B),$.buttons=Y.join(" "))}return $})),O||W.options.buttonTheme.push({class:ie,buttons:E})}))})),this.render())}},{key:"removeButtonTheme",value:function(E,U){var W=this;if(!E&&!U)return this.options.buttonTheme=[],void this.render();E&&Array.isArray(this.options.buttonTheme)&&this.options.buttonTheme.length&&(E.split(" ").forEach((function(B){var ie;(ie=W.options)===null||ie===void 0||(ie=ie.buttonTheme)===null||ie===void 0||ie.map((function(O,$){if(O&&U&&U.includes(O.class)||!U){var Y,q,te=(Y=O)===null||Y===void 0?void 0:Y.buttons.split(" ").filter((function(oe){return oe!==B}));O&&te!=null&&te.length?O.buttons=te.join(" "):((q=W.options.buttonTheme)===null||q===void 0||q.splice($,1),O=null)}return O}))})),this.render())}},{key:"getButtonElement",value:function(E){var U,W=this.buttonElements[E];return W&&(U=W.length>1?W:W[0]),U}},{key:"inputPatternIsValid",value:function(E){var U,W=this.options.inputPattern;if((U=W instanceof RegExp?W:W[this.options.inputName||this.defaultName])&&E){var B=U.test(E);return this.options.debug&&console.log('inputPattern ("'.concat(U,'"): ').concat(B?"passed":"did not pass!")),B}return!0}},{key:"setEventListeners",value:function(){if(this.isFirstKeyboardInstance||!this.allKeyboardInstances){this.options.debug&&console.log("Caret handling started (".concat(this.keyboardDOMClass,")"));var E=this.options.physicalKeyboardHighlightPreventDefault,U=E!==void 0&&E;document.addEventListener("keyup",this.handleKeyUp,U),document.addEventListener("keydown",this.handleKeyDown,U),document.addEventListener("mouseup",this.handleMouseUp),document.addEventListener("touchend",this.handleTouchEnd),this.options.updateCaretOnSelectionChange&&document.addEventListener("selectionchange",this.handleSelectionChange),document.addEventListener("select",this.handleSelect)}}},{key:"handleKeyUp",value:function(E){this.caretEventHandler(E),this.options.physicalKeyboardHighlight&&this.physicalKeyboard.handleHighlightKeyUp(E)}},{key:"handleKeyDown",value:function(E){this.options.physicalKeyboardHighlight&&this.physicalKeyboard.handleHighlightKeyDown(E)}},{key:"handleMouseUp",value:function(E){this.caretEventHandler(E)}},{key:"handleTouchEnd",value:function(E){this.caretEventHandler(E)}},{key:"handleSelect",value:function(E){this.caretEventHandler(E)}},{key:"handleSelectionChange",value:function(E){navigator.userAgent.includes("Firefox")||this.caretEventHandler(E)}},{key:"caretEventHandler",value:function(E){var U,W=this;E.target.tagName&&(U=E.target.tagName.toLowerCase()),this.dispatch((function(B){var ie=E.target===B.keyboardDOM||E.target&&B.keyboardDOM.contains(E.target);if(W.options.syncInstanceInputs&&Array.isArray(E.path)&&(ie=E.path.some((function(Y){var q;return Y==null||(q=Y.hasAttribute)===null||q===void 0?void 0:q.call(Y,"data-skInstance")}))),(U==="textarea"||U==="input"&&["text","search","url","tel","password"].includes(E.target.type))&&!B.options.disableCaretPositioning){var O=E.target.selectionStart,$=E.target.selectionEnd;B.options.rtl&&(O=B.utilities.getRtlOffset(O,B.getInput()),$=B.utilities.getRtlOffset($,B.getInput())),B.setCaretPosition(O,$),B.activeInputElement=E.target,B.options.debug&&console.log("Caret at: ",B.getCaretPosition(),B.getCaretPositionEnd(),E&&E.target.tagName.toLowerCase(),"(".concat(B.keyboardDOMClass,")"),E?.type)}else!B.options.disableCaretPositioning&&ie||E?.type==="selectionchange"||(B.setCaretPosition(null),B.activeInputElement=null,B.options.debug&&console.log('Caret position reset due to "'.concat(E?.type,'" event'),E))}))}},{key:"recurseButtons",value:function(E){var U=this;E&&Object.keys(this.buttonElements).forEach((function(W){return U.buttonElements[W].forEach(E)}))}},{key:"destroy",value:function(){this.options.debug&&console.log("Destroying simple-keyboard instance: ".concat(this.currentInstanceName));var E=this.options.physicalKeyboardHighlightPreventDefault,U=E!==void 0&&E;document.removeEventListener("keyup",this.handleKeyUp,U),document.removeEventListener("keydown",this.handleKeyDown,U),document.removeEventListener("mouseup",this.handleMouseUp),document.removeEventListener("touchend",this.handleTouchEnd),document.removeEventListener("select",this.handleSelect),this.options.updateCaretOnSelectionChange&&document.removeEventListener("selectionchange",this.handleSelectionChange),document.onpointerup=null,document.ontouchend=null,document.ontouchcancel=null,document.onmouseup=null,this.recurseButtons((function(W){W&&(W.onpointerdown=null,W.onpointerup=null,W.onpointercancel=null,W.ontouchstart=null,W.ontouchend=null,W.ontouchcancel=null,W.onclick=null,W.onmousedown=null,W.onmouseup=null,W.remove(),W=null)})),this.keyboardDOM.onpointerdown=null,this.keyboardDOM.ontouchstart=null,this.keyboardDOM.onmousedown=null,this.resetRows(),this.candidateBox&&(this.candidateBox.destroy(),this.candidateBox=null),this.activeInputElement=null,this.keyboardDOM.removeAttribute("data-skInstance"),this.keyboardDOM.innerHTML="",window.SimpleKeyboardInstances[this.currentInstanceName]=null,delete window.SimpleKeyboardInstances[this.currentInstanceName],this.initialized=!1}},{key:"getButtonThemeClasses",value:function(E){var U=this.options.buttonTheme,W=[];return Array.isArray(U)&&U.forEach((function(B){if(B&&B.class&&typeof B.class=="string"&&B.buttons&&typeof B.buttons=="string"){var ie=B.class.split(" ");B.buttons.split(" ").includes(E)&&(W=[].concat(ae(W),ae(ie)))}else console.warn('Incorrect "buttonTheme". Please check the documentation.',B)})),W}},{key:"setDOMButtonAttributes",value:function(E,U){var W=this.options.buttonAttributes;Array.isArray(W)&&W.forEach((function(B){B.attribute&&typeof B.attribute=="string"&&B.value&&typeof B.value=="string"?B.buttons&&typeof B.buttons=="string"?B.buttons.split(" ").includes(E)&&U(B.attribute,B.value):U(B.attribute,B.value):console.warn('Incorrect "buttonAttributes". Please check the documentation.',B)}))}},{key:"onTouchDeviceDetected",value:function(){this.processAutoTouchEvents(),this.disableContextualWindow()}},{key:"disableContextualWindow",value:function(){window.oncontextmenu=function(E){var U;if((U=E.target.classList)!==null&&U!==void 0&&U.contains("hg-button"))return E.preventDefault(),E.stopPropagation(),!1}}},{key:"processAutoTouchEvents",value:function(){this.options.autoUseTouchEvents&&(this.options.useTouchEvents=!0,this.options.debug&&console.log("autoUseTouchEvents: Touch device detected, useTouchEvents enabled."))}},{key:"onInit",value:function(){this.options.debug&&console.log("".concat(this.keyboardDOMClass," Initialized")),this.setEventListeners(),typeof this.options.onInit=="function"&&this.options.onInit(this)}},{key:"beforeFirstRender",value:function(){this.utilities.isTouchDevice()&&this.onTouchDeviceDetected(),typeof this.options.beforeFirstRender=="function"&&this.options.beforeFirstRender(this),this.isFirstKeyboardInstance&&this.utilities.pointerEventsSupported()&&!this.options.useTouchEvents&&!this.options.useMouseEvents&&this.options.debug&&console.log("Using PointerEvents as it is supported by this browser"),this.options.useTouchEvents&&this.options.debug&&console.log("useTouchEvents has been enabled. Only touch events will be used.")}},{key:"beforeRender",value:function(){typeof this.options.beforeRender=="function"&&this.options.beforeRender(this)}},{key:"onRender",value:function(){typeof this.options.onRender=="function"&&this.options.onRender(this)}},{key:"onModulesLoaded",value:function(){typeof this.options.onModulesLoaded=="function"&&this.options.onModulesLoaded(this)}},{key:"loadModules",value:function(){var E=this;Array.isArray(this.options.modules)&&(this.options.modules.forEach((function(U){var W=E.utilities.isConstructor(U)?new U(E):U(E);W.init&&W.init(E)})),this.keyboardPluginClasses="modules-loaded",this.render(),this.onModulesLoaded())}},{key:"getModuleProp",value:function(E,U){return!!this.modules[E]&&this.modules[E][U]}},{key:"getModulesList",value:function(){return Object.keys(this.modules)}},{key:"parseRowDOMContainers",value:function(E,U,W,B){var ie=this,O=Array.from(E.children),$=0;return O.length&&W.forEach((function(Y,q){var te=B[q];if(!(te&&te>Y))return!1;var oe=Y-$,he=te-$,fe=document.createElement("div");fe.className+="hg-button-container";var re="".concat(ie.options.layoutName,"-r").concat(U,"c").concat(q);fe.setAttribute("data-skUID",re);var L=O.splice(oe,he-oe+1);$+=he-oe,L.forEach((function(R){return fe.appendChild(R)})),O.splice(oe,0,fe),E.innerHTML="",O.forEach((function(R){return E.appendChild(R)})),ie.options.debug&&console.log("rowDOMContainer",L,oe,he,$+1)})),E}},{key:"render",value:function(){var E=this;this.resetRows(),this.initialized||this.beforeFirstRender(),this.beforeRender();var U="hg-layout-".concat(this.options.layoutName),W=this.options.layout||{default:["` 1 2 3 4 5 6 7 8 9 0 - = {bksp}","{tab} q w e r t y u i o p [ ] \\","{lock} a s d f g h j k l ; ' {enter}","{shift} z x c v b n m , . / {shift}",".com @ {space}"],shift:["~ ! @ # $ % ^ & * ( ) _ + {bksp}","{tab} Q W E R T Y U I O P { } |",'{lock} A S D F G H J K L : " {enter}',"{shift} Z X C V B N M < > ? {shift}",".com @ {space}"]},B=this.options.useTouchEvents||!1,ie=B?"hg-touch-events":"",O=this.options.useMouseEvents||!1,$=this.options.disableRowButtonContainers;this.keyboardDOM.className=this.getKeyboardClassString(this.options.theme,U,this.keyboardPluginClasses,ie),this.keyboardDOM.setAttribute("data-skInstance",this.currentInstanceName),this.keyboardRowsDOM=document.createElement("div"),this.keyboardRowsDOM.className="hg-rows",W[this.options.layoutName||this.defaultName].forEach((function(Y,q){var te=Y.split(" ");E.options.excludeFromLayout&&E.options.excludeFromLayout[E.options.layoutName||E.defaultName]&&(te=te.filter((function(re){return E.options.excludeFromLayout&&!E.options.excludeFromLayout[E.options.layoutName||E.defaultName].includes(re)})));var oe=document.createElement("div");oe.className+="hg-row";var he=[],fe=[];te.forEach((function(re,L){var R,ne=!$&&typeof re=="string"&&re.length>1&&re.indexOf("[")===0,ve=!$&&typeof re=="string"&&re.length>1&&re.indexOf("]")===re.length-1;ne&&(he.push(L),re=re.replace(/\[/g,"")),ve&&(fe.push(L),re=re.replace(/\]/g,""));var we=E.utilities.getButtonClass(re),me=E.utilities.getButtonDisplayName(re,E.options.display,E.options.mergeDisplay),Me=E.options.useButtonTag?"button":"div",xe=document.createElement(Me);xe.className+="hg-button ".concat(we),(R=xe.classList).add.apply(R,ae(E.getButtonThemeClasses(re))),E.setDOMButtonAttributes(re,(function(Oe,_e){xe.setAttribute(Oe,_e)})),E.activeButtonClass="hg-activeButton",!E.utilities.pointerEventsSupported()||B||O?B?(xe.ontouchstart=function(Oe){E.handleButtonClicked(re,Oe),E.handleButtonMouseDown(re,Oe)},xe.ontouchend=function(Oe){E.handleButtonMouseUp(re,Oe)},xe.ontouchcancel=function(Oe){E.handleButtonMouseUp(re,Oe)}):(xe.onclick=function(Oe){E.setMouseHold(!1),typeof E.options.onKeyReleased=="function"||E.options.useMouseEvents&&E.options.clickOnMouseDown||E.handleButtonClicked(re,Oe)},xe.onmousedown=function(Oe){(typeof E.options.onKeyReleased=="function"||E.options.useMouseEvents&&E.options.clickOnMouseDown)&&!E.isMouseHold&&E.handleButtonClicked(re,Oe),E.handleButtonMouseDown(re,Oe)},xe.onmouseup=function(Oe){E.handleButtonMouseUp(re,Oe)}):(xe.onpointerdown=function(Oe){E.handleButtonClicked(re,Oe),E.handleButtonMouseDown(re,Oe)},xe.onpointerup=function(Oe){E.handleButtonMouseUp(re,Oe)},xe.onpointercancel=function(Oe){E.handleButtonMouseUp(re,Oe)}),xe.setAttribute("data-skBtn",re);var je="".concat(E.options.layoutName,"-r").concat(q,"b").concat(L);xe.setAttribute("data-skBtnUID",je);var He=document.createElement("span");He.innerHTML=me,xe.appendChild(He),E.buttonElements[re]||(E.buttonElements[re]=[]),E.buttonElements[re].push(xe),oe.appendChild(xe)})),oe=E.parseRowDOMContainers(oe,q,he,fe),E.keyboardRowsDOM.appendChild(oe)})),this.keyboardDOM.appendChild(this.keyboardRowsDOM),this.onRender(),this.initialized||(this.initialized=!0,!this.utilities.pointerEventsSupported()||B||O?B?(document.ontouchend=function(Y){return E.handleButtonMouseUp(void 0,Y)},document.ontouchcancel=function(Y){return E.handleButtonMouseUp(void 0,Y)},this.keyboardDOM.ontouchstart=function(Y){return E.handleKeyboardContainerMouseDown(Y)}):B||(document.onmouseup=function(Y){return E.handleButtonMouseUp(void 0,Y)},this.keyboardDOM.onmousedown=function(Y){return E.handleKeyboardContainerMouseDown(Y)}):(document.onpointerup=function(Y){return E.handleButtonMouseUp(void 0,Y)},this.keyboardDOM.onpointerdown=function(Y){return E.handleKeyboardContainerMouseDown(Y)}),this.onInit())}}],J&&pe(V.prototype,J),D&&pe(V,D),Object.defineProperty(V,"prototype",{writable:!1}),V;var V,J,D})(),ge=de,Te=ge;return m})()},442:function(l){l.exports=n}},a={};function s(l){var c=a[l];if(c!==void 0)return c.exports;var d=a[l]={exports:{}};return r[l].call(d.exports,d,d.exports,s),d.exports}s.n=function(l){var c=l&&l.__esModule?function(){return l.default}:function(){return l};return s.d(c,{a:c}),c},s.d=function(l,c){for(var d in c)s.o(c,d)&&!s.o(l,d)&&Object.defineProperty(l,d,{enumerable:!0,get:c[d]})},s.o=function(l,c){return Object.prototype.hasOwnProperty.call(l,c)},s.r=function(l){typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(l,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(l,"__esModule",{value:!0})};var o={};return(function(){s.r(o),s.d(o,{KeyboardReact:function(){return v},default:function(){return b}}),s(981);var l=s(442),c=s(548),d=s.n(c);function u(g){return u=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(_){return typeof _}:function(_){return _&&typeof Symbol=="function"&&_.constructor===Symbol&&_!==Symbol.prototype?"symbol":typeof _},u(g)}function m(g,_){var k=Object.keys(g);if(Object.getOwnPropertySymbols){var C=Object.getOwnPropertySymbols(g);_&&(C=C.filter((function(N){return Object.getOwnPropertyDescriptor(g,N).enumerable}))),k.push.apply(k,C)}return k}function p(g){for(var _=1;_{if(a.current)return;const v=y.target;if(!v.closest('[data-vkb="false"]')){if(v instanceof HTMLInputElement){if(!Fnt.has(v.type))return}else if(!(v instanceof HTMLTextAreaElement))return;l.current=v,e(!0),o("default"),c.current?.setInput?.(l.current.value),setTimeout(()=>{v.scrollIntoView({behavior:"smooth",block:"center"})},100)}},[]),m=w.useCallback(()=>{setTimeout(()=>{const y=document.activeElement;y&&(d.current?.contains(y)||y===l.current)||(e(!1),l.current=null)},150)},[]);w.useEffect(()=>(document.addEventListener("focusin",u),document.addEventListener("focusout",m),()=>{document.removeEventListener("focusin",u),document.removeEventListener("focusout",m)}),[u,m]);const p=w.useCallback(()=>{a.current=!0,r(!0),l.current?.blur(),l.current=null,setTimeout(()=>{e(!1),r(!1),a.current=!1},400)},[]),f=w.useCallback(y=>{const v=l.current;if(v){if(y==="{shift}"){o(b=>b==="default"?"shift":"default");return}if(y==="{lock}"){o(b=>b==="default"?"shift":"default");return}if(y==="{close}"){p();return}y==="{bksp}"?i3(v,v.value.slice(0,-1)):y==="{space}"?i3(v,v.value+" "):(i3(v,v.value+y),s==="shift"&&o("default")),v.focus(),c.current?.setInput?.(v.value)}},[s,p]);return t?i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"fixed inset-0 z-[9998] bg-transparent",onMouseDown:y=>{y.preventDefault(),y.stopPropagation(),n||p()},onTouchStart:y=>{y.preventDefault(),y.stopPropagation(),n||p()},onClick:y=>{y.preventDefault(),y.stopPropagation()}}),!n&&i.jsx("div",{ref:d,className:"fixed bottom-0 left-0 right-0 z-[9999]",onMouseDown:y=>y.preventDefault(),onTouchStart:y=>{y.target.closest(".hg-button")||y.preventDefault()},children:i.jsx(Dnt,{keyboardRef:y=>{c.current=y},layoutName:s,onKeyPress:f,theme:"simple-keyboard vkb-theme",layout:{default:["1 2 3 4 5 6 7 8 9 0 {bksp}","q w e r t y u i o p","{lock} a s d f g h j k l","{shift} z x c v b n m . @","{space} {close}"],shift:["! @ # $ % ^ & * ( ) {bksp}","Q W E R T Y U I O P","{lock} A S D F G H J K L","{shift} Z X C V B N M , _","{space} {close}"]},display:{"{bksp}":"⌫","{close}":"✕ Close","{shift}":"⇧","{lock}":"⇪","{space}":" "}})})]}):null}function Lnt(){const[t,e]=w.useState(null),[n,r]=w.useState(null),[a,s]=w.useState(!1),[o,l]=w.useState(100),[c,d]=w.useState(0),u=w.useRef(Date.now()),{i18n:m}=jt(),p=Pnt(),{data:f}=et({queryKey:["settings"],queryFn:be.getSettings});w.useEffect(()=>{f?.language&&f.language!==m.language&&m.changeLanguage(f.language)},[f?.language,m]);const{data:y=[]}=et({queryKey:["spoolbuddy-devices"],queryFn:()=>zi.getDevices(),refetchInterval:3e4}),v=y[0],b=p.deviceOnline||!!v?.online,g=w.useMemo(()=>({...p,deviceOnline:b}),[p,b]),_=w.useRef(!1);w.useEffect(()=>{v&&!_.current&&(l(v.display_brightness),d(v.display_blank_timeout),_.current=!0)},[v]),w.useEffect(()=>{const P=document.documentElement,T=P.classList.contains("dark");return P.classList.add("dark"),()=>{T||P.classList.remove("dark")}},[]);const{data:k}=et({queryKey:["spoolbuddy-update-check",v?.device_id],queryFn:()=>v?zi.checkDaemonUpdate(v.device_id):Promise.resolve(null),enabled:!!v,refetchInterval:300*1e3,staleTime:0});w.useEffect(()=>{b?k?.update_available&&k.latest_version?r({type:"info",message:`Update available: v${k.latest_version}`}):r(null):r({type:"warning",message:"SpoolBuddy device disconnected"})},[b,k?.update_available,k?.latest_version]);const C=w.useCallback(()=>{u.current=Date.now(),s(!1)},[]);w.useEffect(()=>(window.addEventListener("pointerdown",C),window.addEventListener("keydown",C),()=>{window.removeEventListener("pointerdown",C),window.removeEventListener("keydown",C)}),[C]),w.useEffect(()=>{if(c<=0)return;const P=setInterval(()=>{Date.now()-u.current>=c*1e3&&s(!0)},1e3);return()=>clearInterval(P)},[c]);const N=o<100?{filter:`brightness(${o/100})`}:void 0;return i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"w-screen h-screen bg-bambu-dark text-white flex flex-col overflow-hidden",style:N,children:[i.jsx(_nt,{selectedPrinterId:t,onPrinterChange:e,deviceOnline:b}),i.jsx("main",{className:"flex-1 overflow-y-auto",children:i.jsx(kX,{context:{selectedPrinterId:t,setSelectedPrinterId:e,sbState:g,setAlert:r,displayBrightness:o,setDisplayBrightness:l,displayBlankTimeout:c,setDisplayBlankTimeout:d}})}),i.jsx(Cnt,{alert:n}),i.jsx(Nnt,{}),i.jsx(Rnt,{})]}),a&&i.jsx("div",{className:"fixed inset-0 bg-black z-[9999]",onPointerDown:P=>{P.stopPropagation(),C()}})]})}function F5({color:t,isEmpty:e,size:n=32}){return e?i.jsx("div",{className:"rounded-full border-2 border-dashed border-zinc-500 flex items-center justify-center",style:{width:n,height:n},children:i.jsx("div",{className:"w-2 h-2 rounded-full bg-zinc-600"})}):i.jsxs("svg",{width:n,height:n,viewBox:"0 0 32 32",children:[i.jsx("circle",{cx:"16",cy:"16",r:"14",fill:t,stroke:"white",strokeWidth:"1.5",strokeOpacity:"0.7"}),i.jsx("circle",{cx:"16",cy:"16",r:"11",fill:t,style:{filter:"brightness(0.85)"}})]})}const Ont="spoolbuddy-default-core-weight";function gle(){try{const t=localStorage.getItem(Ont);if(t){const e=parseInt(t,10);if(e>=0&&e<=500)return e}}catch{}return 250}function Int({spool:t,scaleWeight:e,onClose:n,onSyncWeight:r,onAssignToAms:a}){const{t:s}=jt(),[o,l]=w.useState(!1),[c,d]=w.useState(!1),u=t.rgba?`#${t.rgba.slice(0,6)}`:"#808080",m=t.core_weight&&t.core_weight>0?t.core_weight:gle(),p=e!==null?Math.round(Math.max(0,e)):null,f=p!==null?Math.round(Math.max(0,p-m)):null,y=Math.round(t.label_weight||1e3),v=f!==null?Math.min(100,Math.round(f/y*100)):null,b=v!==null?v>50?"#22c55e":v>20?"#eab308":"#ef4444":"#808080",_=Math.max(0,(t.label_weight||0)-(t.weight_used||0))+m,k=p!==null?p-_:null,C=k!==null?Math.abs(k)<=50:null,N=async()=>{if(e!==null){l(!0);try{await zi.updateSpoolWeight(t.id,Math.round(e)),d(!0),r?.(),setTimeout(()=>d(!1),3e3)}catch(P){console.error("Failed to sync weight:",P)}finally{l(!1)}}};return i.jsxs("div",{className:"flex flex-col items-center space-y-4 max-w-md",children:[i.jsxs("div",{className:"flex items-start gap-5",children:[i.jsxs("div",{className:"relative shrink-0",children:[i.jsx(F5,{color:u,isEmpty:!1,size:100}),v!==null&&i.jsxs("div",{className:"absolute -bottom-2 -right-2 px-2 py-0.5 rounded-full text-xs font-bold text-white shadow-lg",style:{backgroundColor:b},children:[v,"%"]})]}),i.jsxs("div",{className:"flex-1 min-w-0 pt-1",children:[i.jsx("h3",{className:"text-lg font-semibold text-zinc-100",children:t.color_name||"Unknown color"}),i.jsxs("p",{className:"text-sm text-zinc-400",children:[t.brand," • ",t.material,t.subtype&&` ${t.subtype}`]}),f!==null&&i.jsxs("div",{className:"mt-3",children:[i.jsxs("div",{className:"flex items-baseline gap-2",children:[i.jsxs("span",{className:"text-3xl font-bold font-mono text-zinc-100",children:[f,"g"]}),i.jsxs("span",{className:"text-sm text-zinc-500",children:["/ ",y,"g"]})]}),i.jsx("p",{className:"text-xs text-zinc-500 mt-0.5",children:s("spoolbuddy.spool.remaining","Remaining")}),i.jsx("div",{className:"mt-2 max-w-xs",children:i.jsx("div",{className:"h-2 bg-zinc-700 rounded-full overflow-hidden",children:i.jsx("div",{className:"h-full rounded-full transition-all duration-500",style:{width:`${v}%`,backgroundColor:b}})})})]})]})]}),i.jsxs("div",{className:"grid grid-cols-2 gap-x-6 gap-y-2 text-sm bg-zinc-800 rounded-lg p-4 w-full",children:[i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-zinc-500",children:s("spoolbuddy.dashboard.grossWeight","Gross weight")}),i.jsx("span",{className:"font-mono text-zinc-300",children:p!==null?`${p}g`:"—"})]}),i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-zinc-500",children:s("spoolbuddy.spool.coreWeight","Core")}),i.jsxs("span",{className:"font-mono text-zinc-300",children:[m,"g"]})]}),i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-zinc-500",children:s("spoolbuddy.dashboard.spoolSize","Spool size")}),i.jsxs("span",{className:"font-mono text-zinc-300",children:[y,"g"]})]}),i.jsxs("div",{className:"flex justify-between items-center",children:[i.jsx("span",{className:"text-zinc-500",children:s("spoolbuddy.spool.scaleWeight","Scale")}),p!==null?i.jsxs("span",{className:`flex items-center gap-1 font-mono ${C?"text-green-500":"text-yellow-500"}`,children:[p,"g",C?i.jsx(Zr,{className:"w-3.5 h-3.5"}):i.jsxs(i.Fragment,{children:[i.jsx(jn,{className:"w-3.5 h-3.5"}),i.jsx("button",{onClick:N,className:"p-1 hover:bg-green-500/20 rounded transition-colors text-green-500",title:s("spoolbuddy.dashboard.syncWeight","Sync Weight"),children:i.jsx(vr,{className:"w-4 h-4"})})]})]}):i.jsx("span",{className:"text-zinc-500",children:"—"})]}),i.jsxs("div",{className:"flex justify-between items-center",children:[i.jsx("span",{className:"text-zinc-500",children:s("spoolbuddy.dashboard.tagId","Tag")}),i.jsx("span",{className:"font-mono text-xs text-zinc-400 truncate max-w-[120px]",title:t.tag_uid||"",children:t.tag_uid?t.tag_uid.slice(-8):"—"})]})]}),i.jsxs("div",{className:"flex gap-2 justify-center",children:[a&&i.jsx("button",{onClick:a,className:"px-5 py-2.5 rounded-lg text-sm font-medium bg-green-600 text-white hover:bg-green-700 transition-colors min-h-[44px]",children:s("spoolbuddy.modal.assignToAms","Assign to AMS")}),i.jsx("button",{onClick:N,disabled:e===null||o,className:`px-5 py-2.5 rounded-lg text-sm font-medium transition-colors min-h-[44px] ${c?"bg-green-600/20 text-green-400":a?"bg-zinc-700 text-zinc-300 hover:bg-zinc-600 disabled:opacity-40 disabled:cursor-not-allowed":"bg-green-600 text-white hover:bg-green-700 disabled:opacity-40 disabled:cursor-not-allowed"}`,children:o?"...":c?s("spoolbuddy.dashboard.weightSynced","Synced!"):s("spoolbuddy.dashboard.syncWeight","Sync Weight")}),n&&i.jsx("button",{onClick:n,className:"px-5 py-2.5 rounded-lg text-sm font-medium bg-zinc-700 text-zinc-300 hover:bg-zinc-600 transition-colors min-h-[44px]",children:s("spoolbuddy.dashboard.close","Close")})]})]})}function znt({tagUid:t,scaleWeight:e,coreWeight:n,onLinkSpool:r,onAddToInventory:a,onClose:s}){const{t:o}=jt(),l=n??gle(),c=e!==null?Math.round(Math.max(0,e)):null,d=c!==null?Math.round(Math.max(0,c-l)):null;return i.jsxs("div",{className:"flex flex-col items-center text-center space-y-5",children:[i.jsx("div",{className:"w-20 h-20 rounded-2xl bg-green-500/15 flex items-center justify-center",children:i.jsx("svg",{className:"w-10 h-10 text-green-500",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M7 7h.01M7 3h5c.512 0 1.024.195 1.414.586l7 7a2 2 0 010 2.828l-7 7a2 2 0 01-2.828 0l-7-7A2 2 0 013 12V7a4 4 0 014-4z"})})}),i.jsxs("div",{children:[i.jsx("h3",{className:"text-lg font-semibold text-zinc-100",children:o("spoolbuddy.dashboard.newTag","New Tag Detected")}),i.jsx("p",{className:"text-sm text-zinc-500 font-mono mt-1",children:t})]}),c!==null&&i.jsxs("div",{className:"text-sm text-zinc-400",children:[i.jsxs("span",{className:"font-mono font-semibold",children:[c,"g"]})," ",o("spoolbuddy.dashboard.onScale","on scale"),d!==null&&d>0&&i.jsxs("span",{className:"text-zinc-500",children:[" • ~",d,"g filament"]})]}),i.jsxs("div",{className:"flex flex-wrap gap-2 justify-center",children:[a&&i.jsx("button",{onClick:a,className:"px-5 py-2.5 rounded-lg text-sm font-medium bg-green-600 text-white hover:bg-green-700 transition-colors min-h-[44px]",children:o("spoolbuddy.modal.addToInventory","Add to Inventory")}),r&&i.jsxs("button",{onClick:r,className:"px-5 py-2.5 rounded-lg text-sm font-medium bg-zinc-700 text-zinc-300 hover:bg-zinc-600 transition-colors min-h-[44px]",children:[i.jsx("svg",{className:"w-4 h-4 inline-block mr-1.5 -mt-0.5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M13.828 10.172a4 4 0 00-5.656 0l-4 4a4 4 0 105.656 5.656l1.102-1.101m-.758-4.899a4 4 0 005.656 0l4-4a4 4 0 00-5.656-5.656l-1.1 1.1"})}),o("spoolbuddy.dashboard.linkSpool","Link to Spool")]}),s&&i.jsx("button",{onClick:s,className:"px-5 py-2.5 rounded-lg text-sm font-medium bg-zinc-700 text-zinc-300 hover:bg-zinc-600 transition-colors min-h-[44px]",children:o("spoolbuddy.dashboard.close","Close")})]})]})}function Unt(t){return t?`#${t.slice(0,6)}`:"#808080"}function ble(t){return!t.tray_type||t.tray_type===""}function Bnt(t){return t<=3?`AMS ${String.fromCharCode(65+t)}`:t>=128&&t<=135?`AMS HT ${String.fromCharCode(65+t-128)}`:`AMS ${t}`}function Hnt({className:t}){return i.jsx("svg",{className:t,viewBox:"0 0 36 54",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:i.jsx("path",{d:"M17.8131 0.00538C18.4463 -0.15091 20.3648 3.14642 20.8264 3.84781C25.4187 10.816 35.3089 26.9368 35.9383 34.8694C37.4182 53.5822 11.882 61.3357 2.53721 45.3789C-1.73471 38.0791 0.016 32.2049 3.178 25.0232C6.99221 16.3662 12.6411 7.90372 17.8131 0.00538ZM18.3738 7.24807L17.5881 7.48441C14.4452 12.9431 10.917 18.2341 8.19369 23.9368C4.6808 31.29 1.18317 38.5479 7.69403 45.5657C17.3058 55.9228 34.9847 46.8808 31.4604 32.8681C29.2558 24.0969 22.4207 15.2913 18.3776 7.24807H18.3738Z",fill:"#C3C2C1"})})}function $nt({className:t}){return i.jsxs("svg",{className:t,viewBox:"0 0 35 53",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[i.jsx("path",{d:"M17.3165 0.0038C17.932 -0.14959 19.7971 3.08645 20.2458 3.77481C24.7103 10.6135 34.3251 26.4346 34.937 34.2198C36.3757 52.5848 11.5505 60.1942 2.46584 44.534C-1.68714 37.3735 0.0148 31.6085 3.08879 24.5603C6.79681 16.0605 12.2884 7.75907 17.3165 0.0038ZM17.8615 7.11561L17.0977 7.34755C14.0423 12.7048 10.6124 17.8974 7.96483 23.4941C4.54975 30.7107 1.14949 37.8337 7.47908 44.721C16.8233 54.8856 34.01 46.0117 30.5838 32.2595C28.4405 23.6512 21.7957 15.0093 17.8652 7.11561H17.8615Z",fill:"#C3C2C1"}),i.jsx("path",{d:"M5.03547 30.112C9.64453 30.4936 11.632 35.7985 16.4154 35.791C19.6339 35.7873 20.2161 33.2283 22.3853 31.6197C31.6776 24.7286 33.5835 37.4894 27.9881 44.4254C18.1878 56.5653 -1.16063 44.6013 5.03917 30.1158L5.03547 30.112Z",fill:"#1F8FEB"})]})}function qnt({className:t}){return i.jsxs("svg",{className:t,viewBox:"0 0 36 54",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[i.jsx("path",{d:"M17.9625 4.48059L4.77216 26.3154L2.08228 40.2175L10.0224 50.8414H23.1594L33.3246 42.1693V30.2455L17.9625 4.48059Z",fill:"#1F8FEB"}),i.jsx("path",{d:"M17.7948 0.00538C18.4273 -0.15091 20.3438 3.14642 20.8048 3.84781C25.3921 10.816 35.2715 26.9368 35.9001 34.8694C37.3784 53.5822 11.8702 61.3357 2.53562 45.3789C-1.73163 38.0829 0.0134 32.2087 3.1757 25.027C6.98574 16.3662 12.6284 7.90372 17.7948 0.00538ZM18.3549 7.24807L17.57 7.48441C14.4306 12.9431 10.9063 18.2341 8.1859 23.9368C4.67686 31.29 1.18305 38.5479 7.68679 45.5657C17.2881 55.9228 34.9476 46.8808 31.4271 32.8681C29.2249 24.0969 22.3974 15.2913 18.3587 7.24807H18.3549Z",fill:"#C3C2C1"})]})}function Vnt({className:t}){return i.jsxs("svg",{className:t,viewBox:"0 0 12 20",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[i.jsx("path",{d:"M6 0.5C4.6 0.5 3.5 1.6 3.5 3V12.1C2.6 12.8 2 13.9 2 15C2 17.2 3.8 19 6 19C8.2 19 10 17.2 10 15C10 13.9 9.4 12.8 8.5 12.1V3C8.5 1.6 7.4 0.5 6 0.5Z",stroke:"#C3C2C1",strokeWidth:"1",fill:"none"}),i.jsx("circle",{cx:"6",cy:"15",r:"2.5",stroke:"#C3C2C1",strokeWidth:"1",fill:"none"})]})}function Gnt({className:t}){return i.jsxs("svg",{className:t,viewBox:"0 0 12 20",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[i.jsx("rect",{x:"4.5",y:"8",width:"3",height:"4.5",fill:"#d4a017",rx:"0.5"}),i.jsx("circle",{cx:"6",cy:"15",r:"2",fill:"#d4a017"}),i.jsx("path",{d:"M6 0.5C4.6 0.5 3.5 1.6 3.5 3V12.1C2.6 12.8 2 13.9 2 15C2 17.2 3.8 19 6 19C8.2 19 10 17.2 10 15C10 13.9 9.4 12.8 8.5 12.1V3C8.5 1.6 7.4 0.5 6 0.5Z",stroke:"#C3C2C1",strokeWidth:"1",fill:"none"})]})}function Wnt({className:t}){return i.jsxs("svg",{className:t,viewBox:"0 0 12 20",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[i.jsx("rect",{x:"4.5",y:"3",width:"3",height:"9.5",fill:"#c62828",rx:"0.5"}),i.jsx("circle",{cx:"6",cy:"15",r:"2",fill:"#c62828"}),i.jsx("path",{d:"M6 0.5C4.6 0.5 3.5 1.6 3.5 3V12.1C2.6 12.8 2 13.9 2 15C2 17.2 3.8 19 6 19C8.2 19 10 17.2 10 15C10 13.9 9.4 12.8 8.5 12.1V3C8.5 1.6 7.4 0.5 6 0.5Z",stroke:"#C3C2C1",strokeWidth:"1",fill:"none"})]})}function xle({humidity:t,goodThreshold:e=40,fairThreshold:n=60}){let r,a;return t<=e?(r="#22a352",a=Hnt):t<=n?(r="#d4a017",a=$nt):(r="#c62828",a=qnt),i.jsxs("div",{className:"flex items-center gap-0.5",children:[i.jsx(a,{className:"w-3 h-3.5"}),i.jsxs("span",{className:"font-medium tabular-nums text-xs",style:{color:r},children:[t,"%"]})]})}function yle({temp:t,goodThreshold:e=28,fairThreshold:n=35}){let r,a;return t<=e?(r="#22a352",a=Vnt):t<=n?(r="#d4a017",a=Gnt):(r="#c62828",a=Wnt),i.jsxs("div",{className:"flex items-center gap-0.5",children:[i.jsx(a,{className:"w-3 h-3.5"}),i.jsxs("span",{className:"font-medium tabular-nums text-xs",style:{color:r},children:[t,"°C"]})]})}function R5({side:t}){return i.jsx("span",{className:"inline-flex items-center justify-center w-4 h-4 text-[9px] font-bold rounded",style:{backgroundColor:"#1a4d2e",color:"#00ae42"},children:t})}function Knt({tray:t,slotIndex:e,isActive:n,fillOverride:r,spoolmanFill:a,onClick:s}){const o=ble(t),l=Unt(t.tray_color),c=t.remain!==null&&t.remain!==void 0&&t.remain>=0?t.remain:null,d=r===0&&c!==null&&c>0?null:r,u=a??d??c;return i.jsxs("div",{className:`relative flex flex-col items-center p-2.5 rounded-lg transition-all ${n?"ring-2 ring-bambu-green":""} ${s?"cursor-pointer hover:bg-white/5":""}`,onClick:s,children:[i.jsxs("div",{className:"relative w-16 h-16 mb-1",children:[o?i.jsx("div",{className:"w-full h-full rounded-full border-2 border-dashed border-gray-500 flex items-center justify-center",children:i.jsx("div",{className:"w-3 h-3 rounded-full bg-gray-600"})}):i.jsxs("svg",{viewBox:"0 0 56 56",className:"w-full h-full",children:[i.jsx("circle",{cx:"28",cy:"28",r:"26",fill:l}),i.jsx("circle",{cx:"28",cy:"28",r:"20",fill:l,style:{filter:"brightness(0.85)"}}),i.jsx("ellipse",{cx:"20",cy:"20",rx:"6",ry:"4",fill:"white",opacity:"0.3"}),i.jsx("circle",{cx:"28",cy:"28",r:"8",fill:"#2d2d2d"}),i.jsx("circle",{cx:"28",cy:"28",r:"5",fill:"#1a1a1a"})]}),n&&i.jsx("div",{className:"absolute -bottom-1 left-1/2 -translate-x-1/2 w-2.5 h-2.5 bg-bambu-green rounded-full"})]}),i.jsx("span",{className:"text-sm text-white/70 truncate max-w-full",children:o?"Empty":t.tray_type||"Unknown"}),!o&&u!==null&&u>=0&&i.jsx("div",{className:"w-full h-1 bg-bambu-dark-tertiary rounded-full overflow-hidden mt-1",children:i.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${u}%`,backgroundColor:sx(u)}})}),i.jsx("span",{className:"absolute top-1 right-1 text-xs text-white/30",children:e+1})]})}function vle({unit:t,activeSlot:e,onConfigureSlot:n,isDualNozzle:r,nozzleSide:a,thresholds:s,fillOverrides:o,spoolmanFillOverrides:l}){const c=t.tray||[],d=t.is_ams_ht,u=d?1:4;return i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg p-3",children:[i.jsxs("div",{className:"flex items-center justify-between mb-2",children:[i.jsxs("div",{className:"flex items-center gap-1.5",children:[i.jsx("span",{className:"text-white font-medium text-base",children:Bnt(t.id)}),r&&a&&i.jsx(R5,{side:a})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[t.temp!=null&&i.jsx(yle,{temp:t.temp,goodThreshold:s?.tempGood,fairThreshold:s?.tempFair}),t.humidity!=null&&i.jsx(xle,{humidity:t.humidity,goodThreshold:s?.humidityGood,fairThreshold:s?.humidityFair})]})]}),i.jsx("div",{className:`grid ${d?"grid-cols-1 max-w-[100px] mx-auto":"grid-cols-4"} gap-2`,children:Array.from({length:u}).map((m,p)=>{const f=c[p]||{id:p,tray_color:null,tray_type:"",tray_sub_brands:null,tray_id_name:null,tray_info_idx:null,remain:-1,k:null,cali_idx:null,tag_uid:null,tray_uuid:null,nozzle_temp_min:null,nozzle_temp_max:null};return i.jsx(Knt,{tray:f,slotIndex:p,isActive:e===p,fillOverride:o?.[`${t.id}-${p}`]??null,spoolmanFill:l?.[`${t.id}-${p}`]??null,onClick:n?()=>n(t.id,p,ble(f)?null:f):void 0},p)})})]})}function Ynt(t){return t<=3?`AMS ${String.fromCharCode(65+t)}`:t>=128&&t<=135?`AMS HT ${String.fromCharCode(65+t-128)}`:`AMS ${t}`}function WY(t){return!t.tray_type||t.tray_type===""}function Xnt(t){return t?`#${t.slice(0,6)}`:"#808080"}function Qnt({isOpen:t,onClose:e,spool:n,printerId:r}){const{t:a}=jt(),s=cn(),[o,l]=w.useState(null),[c,d]=w.useState(null);w.useEffect(()=>{t&&(l(null),d(null))},[t]);const u=w.useCallback(ee=>{ee.key==="Escape"&&e()},[e]);w.useEffect(()=>(t&&document.addEventListener("keydown",u),()=>document.removeEventListener("keydown",u)),[t,u]);const{data:m}=et({queryKey:["printerStatus",r],queryFn:()=>be.getPrinterStatus(r),enabled:t&&r!==null,refetchInterval:5e3}),{data:p}=et({queryKey:["printer",r],queryFn:()=>be.getPrinter(r),enabled:t&&r!==null}),{data:f}=et({queryKey:["settings"],queryFn:()=>be.getSettings(),enabled:t,staleTime:300*1e3}),{data:y}=et({queryKey:["spool-assignments",r],queryFn:()=>be.getAssignments(r),enabled:t&&r!==null,staleTime:30*1e3}),v=w.useMemo(()=>{const ee={};if(!y)return ee;for(const ae of y){const X=ae.spool;if(X&&X.label_weight>0&&X.weight_used!=null){const ce=Math.round(Math.max(0,X.label_weight-X.weight_used)/X.label_weight*100);ee[`${ae.ams_id}-${ae.tray_id}`]=ce}}return ee},[y]),b=f?{humidityGood:Number(f.ams_humidity_good)||40,humidityFair:Number(f.ams_humidity_fair)||60,tempGood:Number(f.ams_temp_good)||28,tempFair:Number(f.ams_temp_fair)||35}:void 0,g=m?.connected??!1,_=w.useMemo(()=>m?.ams??[],[m?.ams]),k=w.useMemo(()=>_.filter(ee=>!ee.is_ams_ht),[_]),C=w.useMemo(()=>_.filter(ee=>ee.is_ams_ht),[_]),N=w.useMemo(()=>[...m?.vt_tray??[]].sort((ee,ae)=>(ee.id??254)-(ae.id??254)),[m?.vt_tray]),P=p?.nozzle_count===2||m?.temperatures?.nozzle_2!==void 0,T=w.useRef({});w.useEffect(()=>{m?.ams_extruder_map&&Object.keys(m.ams_extruder_map).length>0&&(T.current=m.ams_extruder_map)},[m?.ams_extruder_map]);const j=m?.ams_extruder_map&&Object.keys(m.ams_extruder_map).length>0?m.ams_extruder_map:T.current,A=w.useCallback(ee=>{if(!P)return null;const ae=j[String(ee)],X=ee>=128?ee-128:ee;return(ae!==void 0?ae:X)===1?"L":"R"},[P,j]),F=pt({mutationFn:async({amsId:ee,trayId:ae})=>{if(!r)throw new Error("No printer selected");await be.assignSpool({spool_id:n.id,printer_id:r,ams_id:ee,tray_id:ae})},onSuccess:()=>{d("success"),l(a("spoolbuddy.modal.assignSuccess","Assigned!")),s.invalidateQueries({queryKey:["slotPresets"]}),setTimeout(()=>e(),1500)},onError:ee=>{d("error"),l(ee instanceof Error?ee.message:a("spoolbuddy.modal.assignError","Failed to assign spool."))}}),G=F.isPending,z=w.useCallback((ee,ae)=>{G||(d("info"),l(a("spoolbuddy.modal.assigning","Configuring slot...")),F.mutate({amsId:ee,trayId:ae}))},[G,F,a]),Z=w.useMemo(()=>{const ee=[];for(const ae of C){const X=ae.tray?.[0]||{id:0,tray_color:null,tray_type:"",tray_sub_brands:null,tray_id_name:null,tray_info_idx:null,remain:-1,k:null,cali_idx:null,tag_uid:null,tray_uuid:null,nozzle_temp_min:null,nozzle_temp_max:null},ce=v[`${ae.id}-0`]??null,ue=X.remain!=null&&X.remain>=0?X.remain:null,pe=ce===0&&ue!==null&&ue>0?null:ce;ee.push({key:`ht-${ae.id}`,label:Ynt(ae.id),amsId:ae.id,trayId:0,tray:X,isEmpty:WY(X),nozzleSide:A(ae.id),effectiveFill:pe??ue})}for(const ae of N){const X=ae.id??254,ce=X-254,ue=v[`255-${ce}`]??null,pe=ae.remain!=null&&ae.remain>=0?ae.remain:null,K=ue===0&&pe!==null&&pe>0?null:ue;ee.push({key:`ext-${X}`,label:P?X===254?a("printers.extL","Ext-L"):a("printers.extR","Ext-R"):a("printers.ext","Ext"),amsId:255,trayId:ce,tray:ae,isEmpty:WY(ae),nozzleSide:P?X===254?"L":"R":null,effectiveFill:K??pe})}return ee},[C,N,P,a,A,v]);if(!t)return null;const I=n.rgba?`#${n.rgba.slice(0,6)}`:"#808080";return i.jsxs("div",{className:"fixed inset-0 z-[60] bg-bambu-dark flex flex-col",children:[i.jsxs("div",{className:"flex items-center justify-between px-5 py-3 border-b border-zinc-800 shrink-0",children:[i.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[i.jsx("div",{className:"w-7 h-7 rounded-full shrink-0",style:{backgroundColor:I}}),i.jsx("div",{className:"min-w-0",children:i.jsxs("h2",{className:"text-sm font-semibold text-zinc-100 truncate",children:[a("spoolbuddy.modal.assignToAmsTitle","Assign to AMS"),i.jsxs("span",{className:"font-normal text-zinc-500 ml-2",children:[n.color_name||"Unknown"," • ",n.brand," ",n.material,n.subtype&&` ${n.subtype}`]})]})})]}),i.jsx("button",{onClick:e,disabled:G,className:"p-2 rounded-lg text-zinc-500 hover:text-zinc-300 hover:bg-zinc-800 transition-colors shrink-0 disabled:opacity-50",children:i.jsx(qt,{className:"w-5 h-5"})})]}),o&&i.jsxs("div",{className:`mx-5 mt-3 p-3 rounded-lg flex items-center gap-3 border shrink-0 ${c==="info"?"bg-blue-500/10 border-blue-500/40":c==="success"?"bg-green-500/10 border-green-500/40":"bg-red-500/10 border-red-500/40"}`,children:[c==="info"&&i.jsx(ft,{className:"w-4 h-4 text-blue-400 animate-spin shrink-0"}),c==="success"&&i.jsx(pr,{className:"w-4 h-4 text-green-400 shrink-0"}),c==="error"&&i.jsx(Wi,{className:"w-4 h-4 text-red-400 shrink-0"}),i.jsx("span",{className:`text-sm ${c==="info"?"text-blue-300":c==="success"?"text-green-300":"text-red-300"}`,children:o})]}),i.jsx("div",{className:"flex-1 flex flex-col gap-3 p-4 min-h-0",children:!g&&r?i.jsx("div",{className:"flex-1 flex items-center justify-center",children:i.jsx("div",{className:"text-center text-white/50",children:i.jsx("p",{className:"text-lg mb-2",children:a("spoolbuddy.ams.printerDisconnected","Printer disconnected")})})}):_.length===0&&N.length===0?i.jsx("div",{className:"flex-1 flex items-center justify-center",children:i.jsxs("div",{className:"text-center text-white/50",children:[i.jsx(Ki,{className:"w-12 h-12 mx-auto mb-3 opacity-50"}),i.jsx("p",{className:"text-lg mb-2",children:a("spoolbuddy.ams.noData","No AMS detected")}),i.jsx("p",{className:"text-sm",children:a("spoolbuddy.ams.connectAms","Connect an AMS to see filament slots")})]})}):i.jsxs(i.Fragment,{children:[k.length>0&&i.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3 flex-1 min-h-0",children:k.map(ee=>i.jsx(vle,{unit:ee,activeSlot:null,onConfigureSlot:(ae,X)=>z(ee.id,X),isDualNozzle:P,nozzleSide:A(ee.id),thresholds:b,fillOverrides:v},ee.id))}),Z.length>0&&i.jsx("div",{className:"flex gap-2 shrink-0",children:Z.map(({key:ee,label:ae,amsId:X,trayId:ce,tray:ue,isEmpty:pe,nozzleSide:K,effectiveFill:se})=>{const de=Xnt(ue.tray_color);return i.jsxs("div",{onClick:()=>z(X,ce),className:`bg-bambu-dark-secondary rounded-lg px-3 py-2 cursor-pointer hover:bg-bambu-dark-secondary/80 transition-all flex items-center gap-2 ${G?"opacity-50 pointer-events-none":""}`,children:[i.jsx("div",{className:"relative w-10 h-10 shrink-0",children:pe?i.jsx("div",{className:"w-full h-full rounded-full border-2 border-dashed border-gray-500 flex items-center justify-center",children:i.jsx("div",{className:"w-1.5 h-1.5 rounded-full bg-gray-600"})}):i.jsxs("svg",{viewBox:"0 0 56 56",className:"w-full h-full",children:[i.jsx("circle",{cx:"28",cy:"28",r:"26",fill:de}),i.jsx("circle",{cx:"28",cy:"28",r:"20",fill:de,style:{filter:"brightness(0.85)"}}),i.jsx("ellipse",{cx:"20",cy:"20",rx:"6",ry:"4",fill:"white",opacity:"0.3"}),i.jsx("circle",{cx:"28",cy:"28",r:"8",fill:"#2d2d2d"}),i.jsx("circle",{cx:"28",cy:"28",r:"5",fill:"#1a1a1a"})]})}),i.jsxs("div",{className:"min-w-0",children:[i.jsxs("div",{className:"flex items-center gap-1",children:[i.jsx("span",{className:"text-xs text-white/50 font-medium",children:ae}),K&&i.jsx(R5,{side:K})]}),i.jsx("div",{className:"text-sm text-white/80 truncate",children:pe?"Empty":ue.tray_type||"?"})]}),!pe&&se!=null&&se>=0&&i.jsx("div",{className:"w-1.5 h-8 bg-bambu-dark-tertiary rounded-full overflow-hidden shrink-0 flex flex-col-reverse",children:i.jsx("div",{className:"w-full rounded-full",style:{height:`${se}%`,backgroundColor:sx(se)}})})]},ee)})})]})}),i.jsx("div",{className:"flex justify-end gap-3 px-5 py-3 border-t border-zinc-800 shrink-0",children:i.jsx("button",{onClick:e,disabled:G,className:"px-5 py-2.5 rounded-lg text-sm font-medium bg-zinc-800 text-zinc-300 hover:bg-zinc-700 transition-colors min-h-[44px] disabled:opacity-50",children:c==="success"?a("spoolbuddy.dashboard.close","Close"):a("spoolbuddy.modal.cancel","Cancel")})})]})}function Znt({isOpen:t,onClose:e,tagId:n,untaggedSpools:r,onLink:a}){const{t:s}=jt(),[o,l]=w.useState(null),c=w.useCallback(()=>{l(null),e()},[e]),d=w.useCallback(m=>{m.key==="Escape"&&c()},[c]);if(w.useEffect(()=>(t&&(document.addEventListener("keydown",d),document.body.style.overflow="hidden"),()=>{document.removeEventListener("keydown",d),document.body.style.overflow=""}),[t,d]),!t)return null;const u=()=>{o&&(a(o),l(null))};return i.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/70 animate-fade-in",onClick:c,children:i.jsxs("div",{className:"bg-zinc-800 rounded-xl shadow-2xl w-full max-w-lg mx-4 animate-slide-up",onClick:m=>m.stopPropagation(),children:[i.jsxs("div",{className:"flex items-center justify-between px-5 py-4 border-b border-zinc-700",children:[i.jsxs("div",{children:[i.jsx("h2",{className:"text-base font-semibold text-zinc-100",children:s("spoolbuddy.dashboard.linkTagTitle","Link Tag to Spool")}),i.jsx("p",{className:"text-sm text-zinc-500 font-mono",children:n})]}),i.jsx("button",{onClick:c,className:"p-2 rounded-lg text-zinc-500 hover:text-zinc-300 hover:bg-zinc-700 transition-colors",children:i.jsx(qt,{className:"w-5 h-5"})})]}),i.jsxs("div",{className:"px-5 py-4 space-y-3 max-h-[400px] overflow-y-auto",children:[i.jsx("p",{className:"text-sm text-zinc-400",children:s("spoolbuddy.dashboard.selectSpool","Select a spool to link this tag to:")}),r.length===0?i.jsx("div",{className:"text-center py-8 text-zinc-500",children:s("spoolbuddy.dashboard.noUntagged","No spools without tags found")}):i.jsx("div",{className:"space-y-2",children:r.map(m=>i.jsxs("button",{type:"button",onClick:()=>l(m),className:`w-full flex items-center gap-3 p-3 rounded-lg border-2 transition-all text-left ${o?.id===m.id?"border-green-500 bg-green-500/10":"border-zinc-700 hover:border-green-500/50 hover:bg-zinc-700/50"}`,children:[i.jsx(F5,{color:m.rgba?`#${m.rgba.slice(0,6)}`:"#808080",isEmpty:!1,size:40}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsx("div",{className:"font-medium text-zinc-100 truncate",children:m.color_name||"Unknown color"}),i.jsxs("div",{className:"text-sm text-zinc-400 truncate",children:[m.brand," • ",m.material,m.subtype&&` ${m.subtype}`]})]}),i.jsxs("div",{className:"text-sm font-mono text-zinc-500",children:[Math.max(0,m.label_weight-m.weight_used),"g"]})]},m.id))})]}),i.jsxs("div",{className:"flex justify-end gap-2 px-5 py-4 border-t border-zinc-700",children:[i.jsx("button",{onClick:c,className:"px-4 py-2.5 rounded-lg text-sm font-medium bg-zinc-700 text-zinc-300 hover:bg-zinc-600 transition-colors min-h-[44px]",children:s("common.cancel","Cancel")}),i.jsx("button",{onClick:u,disabled:!o,className:"px-4 py-2.5 rounded-lg text-sm font-medium bg-green-600 text-white hover:bg-green-700 disabled:opacity-40 disabled:cursor-not-allowed transition-colors min-h-[44px]",children:s("spoolbuddy.dashboard.linkTag","Link Tag")})]})]})})}const KY=["#00AE42","#FF6B35","#3B82F6","#EF4444","#A855F7","#FBBF24","#14B8A6","#EC4899","#F97316","#22C55E"];function YY(t){return t?t.replace(/[^0-9a-f]/gi,"").toUpperCase():""}function Jnt(t,e){const n=YY(t),r=YY(e);return!n||!r?!1:n===r?!0:n.endsWith(r)||r.endsWith(n)}function ert(){const{t}=jt(),[e,n]=w.useState(0);w.useEffect(()=>{const a=setInterval(()=>{n(s=>(s+1)%KY.length)},2e3);return()=>clearInterval(a)},[]);const r=KY[e];return i.jsxs("div",{className:"flex flex-col items-center text-center",children:[i.jsxs("div",{className:"relative mb-6 flex items-center justify-center",style:{width:160,height:160},children:[i.jsx("div",{className:"absolute w-24 h-24 rounded-full border-2 border-green-500/30 animate-ping",style:{animationDuration:"2.5s"}}),i.jsx("div",{className:"absolute w-32 h-32 rounded-full border border-green-500/20 animate-ping",style:{animationDuration:"2.5s",animationDelay:"0.4s"}}),i.jsx("div",{className:"absolute w-40 h-40 rounded-full border border-green-500/10 animate-ping",style:{animationDuration:"2.5s",animationDelay:"0.8s"}}),i.jsxs("div",{className:"relative",children:[i.jsx("div",{className:"absolute -inset-4 rounded-full blur-2xl opacity-30 transition-colors duration-1000",style:{backgroundColor:r}}),i.jsx("div",{className:"transition-all duration-1000",children:i.jsx(F5,{color:r,isEmpty:!1,size:100})})]})]}),i.jsxs("div",{className:"space-y-2",children:[i.jsx("p",{className:"text-xl font-medium text-zinc-300",children:t("spoolbuddy.dashboard.readyToScan","Ready to scan")}),i.jsx("p",{className:"text-sm text-zinc-500",children:t("spoolbuddy.dashboard.idleMessage","Place a spool on the scale to identify it")})]}),i.jsxs("div",{className:"mt-6 flex items-center gap-2 text-sm text-zinc-600",children:[i.jsx("svg",{className:"w-4 h-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),i.jsx("span",{children:t("spoolbuddy.dashboard.nfcHint","NFC tag will be read automatically")})]})]})}function trt(){const{t}=jt();return i.jsxs("div",{className:"flex flex-col items-center text-center",children:[i.jsx("div",{className:"relative mb-6 flex items-center justify-center",style:{width:160,height:160},children:i.jsx("div",{className:"w-24 h-24 rounded-full bg-zinc-800 flex items-center justify-center",children:i.jsx("svg",{className:"w-12 h-12 text-zinc-600",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"1.5",d:"M18.364 5.636a9 9 0 010 12.728m0 0l-12.728-12.728m12.728 12.728L5.636 5.636m12.728 0a9 9 0 00-12.728 0m0 12.728a9 9 0 010-12.728"})})})}),i.jsxs("div",{className:"space-y-2",children:[i.jsx("p",{className:"text-lg font-medium text-zinc-500",children:t("spoolbuddy.status.deviceOffline","Device Offline")}),i.jsx("p",{className:"text-sm text-zinc-600",children:t("spoolbuddy.status.connectDisplay","Connect the SpoolBuddy display to scan spools")})]}),i.jsxs("div",{className:"mt-6 flex items-center gap-2 text-xs text-zinc-600",children:[i.jsx("svg",{className:"w-4 h-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M8.111 16.404a5.5 5.5 0 017.778 0M12 20h.01m-7.08-7.071c3.904-3.905 10.236-3.905 14.14 0M1.394 9.393c5.857-5.857 15.355-5.857 21.213 0"})}),i.jsx("span",{children:t("spoolbuddy.status.waitingConnection","Waiting for device connection...")})]})]})}function nrt(){const{sbState:t,selectedPrinterId:e}=fw(),{t:n}=jt(),{data:r=[],refetch:a}=et({queryKey:["inventory-spools"],queryFn:()=>be.getSpools(!1)}),{data:s=[]}=et({queryKey:["printers"],queryFn:()=>be.getPrinters()}),o=ig({queries:s.map(K=>({queryKey:["printerStatus",K.id],queryFn:()=>be.getPrinterStatus(K.id),refetchInterval:1e4}))}),[l,c]=w.useState(null),[d,u]=w.useState(null),[m,p]=w.useState(null),[f,y]=w.useState(!1),[v,b]=w.useState(!1),[g,_]=w.useState(!1),[k,C]=w.useState(!1),N=t.matchedSpool?.tag_uid??t.unknownTagUid??null,P=t.weight,T=t.weightStable,j=w.useRef(null);P===null?j.current=null:(j.current===null||Math.abs(P-j.current)>=3||T)&&(j.current=P);const F=j.current,G=w.useMemo(()=>{if(t.matchedSpool?.id){const K=r.find(se=>se.id===t.matchedSpool?.id);if(K)return K}return l?r.find(K=>Jnt(K.tag_uid,l))??null:null},[l,t.matchedSpool,r]),z=w.useMemo(()=>r.filter(K=>!K.tag_uid&&!K.archived_at),[r]);w.useEffect(()=>{if(N){const K=m===N;(l!==null&&l!==N||!K&&l!==N)&&(c(N),u(null),p(null)),!K&&P!==null&&T&&u(Math.round(Math.max(0,P)))}else m&&(c(null),p(null),u(null))},[N,P,T,l,m]);const Z=()=>{p(l)},I=async K=>{if(l)try{await be.linkTagToSpool(K.id,{tag_uid:l,tag_type:"generic",data_origin:"nfc_link"}),y(!1),a()}catch(se){console.error("Failed to link tag:",se)}},ee=async()=>{if(l){C(!0);try{const K=X??d;await be.createSpool({material:"PLA",subtype:null,color_name:null,rgba:null,brand:null,label_weight:1e3,core_weight:250,core_weight_catalog_id:null,weight_used:0,slicer_filament:null,slicer_filament_name:null,nozzle_temp_min:null,nozzle_temp_max:null,note:null,added_full:null,last_used:null,encode_time:null,tag_uid:l,tray_uuid:null,data_origin:"spoolbuddy",tag_type:"generic",cost_per_kg:null,last_scale_weight:K,last_weighed_at:K!==null?new Date().toISOString():null}),_(!1),a()}catch(K){console.error("Failed to quick-add spool:",K)}finally{C(!1)}}},X=P!==null&&(N===l||N===null&&l!==null)?P:null,ce=r.length,ue=new Set(r.map(K=>K.material)).size,pe=new Set(r.filter(K=>K.brand).map(K=>K.brand)).size;return i.jsxs("div",{className:"h-full flex flex-col p-4",children:[i.jsxs("div",{className:"flex items-center gap-6 px-4 py-1.5 bg-zinc-800/50 rounded-xl border border-zinc-700/50 mb-3 shrink-0",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"text-xl font-bold text-zinc-100",children:ce}),i.jsx("span",{className:"text-sm text-zinc-500",children:n("spoolbuddy.inventory.spools","Spools")})]}),i.jsx("div",{className:"w-px h-5 bg-zinc-700"}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"text-xl font-bold text-zinc-100",children:ue}),i.jsx("span",{className:"text-sm text-zinc-500",children:n("spoolbuddy.spool.material","Materials")})]}),i.jsx("div",{className:"w-px h-5 bg-zinc-700"}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"text-xl font-bold text-zinc-100",children:pe}),i.jsx("span",{className:"text-sm text-zinc-500",children:n("spoolbuddy.spool.brand","Brands")})]})]}),i.jsxs("div",{className:"flex-1 flex gap-4 min-h-0",children:[i.jsxs("div",{className:"w-5/12 flex flex-col min-h-0",children:[i.jsxs("div",{className:"border border-dashed border-zinc-700/50 rounded-xl p-4",children:[i.jsx("h2",{className:"text-sm font-semibold text-zinc-400 uppercase tracking-wide mb-3",children:n("spoolbuddy.dashboard.device","Device")}),i.jsxs("div",{className:"space-y-2.5",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:`w-2.5 h-2.5 rounded-full ${t.deviceOnline?"bg-green-500 animate-pulse":"bg-red-500"}`}),i.jsx("span",{className:"text-base text-zinc-400",children:t.deviceOnline?n("spoolbuddy.status.online","Online"):n("spoolbuddy.status.offline","Disconnected")})]}),i.jsxs("div",{className:"flex items-center justify-between p-3 bg-zinc-800/50 rounded-lg",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("svg",{className:`w-4 h-4 ${t.deviceOnline?"text-green-500":"text-zinc-500"}`,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M3 6l3 1m0 0l-3 9a5.002 5.002 0 006.001 0M6 7l3 9M6 7l6-2m6 2l3-1m-3 1l-3 9a5.002 5.002 0 006.001 0M18 7l3 9m-3-9l-6-2m0-2v2m0 16V5m0 16H9m3 0h3"})}),i.jsx("span",{className:"text-sm text-zinc-500",children:n("spoolbuddy.spool.scaleWeight","Scale")})]}),i.jsx("span",{className:"text-lg font-mono font-semibold text-zinc-100",children:F!==null?`${Math.abs(F)<=20?0:Math.round(Math.max(0,F))}g`:"—"})]}),i.jsxs("div",{className:"flex items-center justify-between p-3 bg-zinc-800/50 rounded-lg",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("svg",{className:`w-4 h-4 ${t.deviceOnline?"text-green-500":"text-zinc-500"}`,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M7 7h.01M7 3h5c.512 0 1.024.195 1.414.586l7 7a2 2 0 010 2.828l-7 7a2 2 0 01-2.828 0l-7-7A2 2 0 013 12V7a4 4 0 014-4z"})}),i.jsx("span",{className:"text-sm text-zinc-500",children:"NFC"})]}),i.jsx("span",{className:`text-sm font-medium ${N?"text-green-500":"text-zinc-500"}`,children:N?n("spoolbuddy.dashboard.tagDetected","Tag detected"):n("spoolbuddy.dashboard.noTag","No tag")})]})]})]}),s.length>0&&i.jsxs("div",{className:"mt-3 border border-dashed border-zinc-700/50 rounded-xl p-4",children:[i.jsx("h2",{className:"text-sm font-semibold text-zinc-400 uppercase tracking-wide mb-2.5",children:n("spoolbuddy.dashboard.printers","Printers")}),i.jsx("div",{className:"flex flex-wrap gap-2 overflow-hidden",children:s.map((K,se)=>{const de=o[se]?.data?.connected??!1;return i.jsxs("div",{className:"flex items-center gap-1.5 px-2.5 py-1 bg-zinc-800/50 rounded-lg",title:`${K.name} — ${de?"Online":"Offline"}`,children:[i.jsx("div",{className:`w-2 h-2 rounded-full shrink-0 ${de?"bg-green-500":"bg-zinc-600"}`}),i.jsx("span",{className:"text-xs text-zinc-400 truncate max-w-[100px]",children:K.name})]},K.id)})})]})]}),i.jsx("div",{className:"w-7/12 min-h-0",children:i.jsxs("div",{className:"border border-dashed border-zinc-700/50 rounded-xl p-6 h-full flex flex-col",children:[i.jsx("h2",{className:"text-sm font-semibold text-zinc-400 uppercase tracking-wide mb-4 shrink-0",children:n("spoolbuddy.dashboard.currentSpool","Current Spool")}),i.jsx("div",{className:"flex-1 flex items-center justify-center min-h-0",children:t.deviceOnline?(G||t.matchedSpool)&&l&&m!==l?i.jsx(Int,{spool:{id:G?.id??t.matchedSpool.id,tag_uid:l,material:G?.material??t.matchedSpool.material,subtype:G?.subtype??t.matchedSpool.subtype,color_name:G?.color_name??t.matchedSpool.color_name,rgba:G?.rgba??t.matchedSpool.rgba,brand:G?.brand??t.matchedSpool.brand,label_weight:G?.label_weight??t.matchedSpool.label_weight,core_weight:G?.core_weight??t.matchedSpool.core_weight,weight_used:G?.weight_used??t.matchedSpool.weight_used},scaleWeight:X??d,onSyncWeight:()=>a(),onAssignToAms:()=>b(!0),onClose:Z}):N&&l&&!G&&!t.matchedSpool&&m!==l?i.jsx(znt,{tagUid:l,scaleWeight:X??d,onLinkSpool:z.length>0?()=>y(!0):void 0,onAddToInventory:()=>_(!0),onClose:Z}):i.jsx(ert,{}):i.jsx(trt,{})})]})})]}),G&&l&&i.jsx(Qnt,{isOpen:v,onClose:()=>b(!1),spool:G,printerId:e}),l&&i.jsx(Znt,{isOpen:f,onClose:()=>y(!1),tagId:l,untaggedSpools:z,onLink:I}),g&&l&&i.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60",children:i.jsxs("div",{className:"bg-zinc-800 rounded-2xl p-6 mx-4 max-w-sm w-full border border-zinc-700",children:[i.jsx("h3",{className:"text-lg font-semibold text-zinc-100 mb-3",children:n("spoolbuddy.modal.addToInventory","Add to Inventory")}),i.jsxs("div",{className:"flex gap-2.5 p-3 bg-amber-500/10 border border-amber-500/20 rounded-lg mb-4",children:[i.jsx("svg",{className:"w-5 h-5 text-amber-500 shrink-0 mt-0.5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),i.jsx("p",{className:"text-sm text-amber-200/80",children:n("spoolbuddy.modal.quickAddHint",'For best results, add the spool in the Bambuddy web interface first (with material, color, brand), then use "Link to Spool" here to assign the NFC tag.')})]}),i.jsx("p",{className:"text-sm text-zinc-400 mb-1",children:n("spoolbuddy.modal.quickAddDesc","This will create a basic PLA spool entry with this NFC tag. You can edit the details later in Bambuddy.")}),i.jsx("p",{className:"text-xs text-zinc-500 font-mono mb-5",children:l}),i.jsxs("div",{className:"flex gap-3",children:[i.jsx("button",{onClick:()=>_(!1),className:"flex-1 px-4 py-2.5 rounded-lg text-sm font-medium bg-zinc-700 text-zinc-300 hover:bg-zinc-600 transition-colors min-h-[44px]",children:n("common.cancel","Cancel")}),i.jsx("button",{onClick:ee,disabled:k,className:"flex-1 px-4 py-2.5 rounded-lg text-sm font-medium bg-green-600 text-white hover:bg-green-700 disabled:opacity-50 transition-colors min-h-[44px]",children:k?n("common.saving","Saving..."):n("spoolbuddy.modal.addAnyway","Add Anyway")})]})]})})]})}function a3(t){return t<=3?`AMS ${String.fromCharCode(65+t)}`:t>=128&&t<=135?`AMS HT ${String.fromCharCode(65+t-128)}`:`AMS ${t}`}function rrt(t){return t?{O1D:"H2D",O1E:"H2D Pro",O2D:"H2D Pro",O1C:"H2C",O1C2:"H2C",O1S:"H2S","BL-P001":"X1C","BL-P002":"X1","BL-P003":"X1E",C11:"P1S",C12:"P1P",C13:"P2S",N2S:"A1",N1:"A1 Mini",X1C:"X1C",X1:"X1",X1E:"X1E",P1S:"P1S",P1P:"P1P",P2S:"P2S",A1:"A1","A1 Mini":"A1 Mini",H2D:"H2D","H2D Pro":"H2D Pro",H2C:"H2C",H2S:"H2S"}[t]||t:""}function zp(t){return!t.tray_type||t.tray_type===""}function irt(t){return t?`#${t.slice(0,6)}`:"#808080"}function art(){const{selectedPrinterId:t,setAlert:e}=fw(),{t:n}=jt(),r=cn(),{showToast:a}=pn(),{data:s}=et({queryKey:["printerStatus",t],queryFn:()=>be.getPrinterStatus(t),enabled:t!==null,staleTime:30*1e3}),{data:o}=et({queryKey:["printer",t],queryFn:()=>be.getPrinter(t),enabled:t!==null,staleTime:60*1e3}),{data:l}=et({queryKey:["slotPresets",t],queryFn:()=>be.getSlotPresets(t),enabled:t!==null,staleTime:120*1e3}),{data:c}=et({queryKey:["settings"],queryFn:()=>be.getSettings(),staleTime:300*1e3}),{data:d}=et({queryKey:["spoolman-status"],queryFn:be.getSpoolmanStatus,staleTime:60*1e3}),u=d?.enabled&&d?.connected,{data:m}=et({queryKey:["linked-spools"],queryFn:be.getLinkedSpools,enabled:!!u,staleTime:30*1e3}),p=m?.linked,{data:f}=et({queryKey:["spool-assignments",t],queryFn:()=>be.getAssignments(t),enabled:t!==null,staleTime:30*1e3}),y=w.useMemo(()=>{const Y={};if(!f)return Y;for(const q of f){const te=q.spool;if(te&&te.label_weight>0&&te.weight_used!=null){const oe=Math.round(Math.max(0,te.label_weight-te.weight_used)/te.label_weight*100);Y[`${q.ams_id}-${q.tray_id}`]=oe}}return Y},[f]),v=o?.serial_number??"",b=w.useCallback((Y,q,te)=>{if(!p||!v)return null;const oe=(te?.tray_uuid||te?.tag_uid||wu(v,Y,q))?.toUpperCase(),he=oe?p[oe]:void 0;return yk(he)},[p,v]),g=s?.connected??!1,_=w.useRef([]);w.useEffect(()=>{s?.ams&&s.ams.length>0&&(_.current=s.ams)},[s?.ams]);const k=w.useMemo(()=>{const Y=s?.ams;return Y&&Y.length>0?Y:_.current??[]},[s?.ams]),C=w.useMemo(()=>k.filter(Y=>!Y.is_ams_ht),[k]),N=w.useMemo(()=>k.filter(Y=>Y.is_ams_ht),[k]),P=w.useMemo(()=>{const Y={};if(!p||!v)return Y;for(const q of C)for(let te=0;te<(q.tray?.length??0);te++){const oe=q.tray[te],he=b(q.id,te,zp(oe)?null:oe);he!==null&&(Y[`${q.id}-${te}`]=he)}return Y},[p,v,C,b]),T=w.useRef(void 0),j=s?.tray_now;j!==void 0&&j!==255?T.current=j:j===255&&(T.current=void 0);const A=j!==void 0&&j!==255?j:T.current,F=o?.nozzle_count===2||s?.temperatures?.nozzle_2!==void 0,G=w.useMemo(()=>[...s?.vt_tray??[]].sort((Y,q)=>(Y.id??254)-(q.id??254)),[s?.vt_tray]),z=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,Z=w.useRef({});w.useEffect(()=>{s?.ams_extruder_map&&Object.keys(s.ams_extruder_map).length>0&&(Z.current=s.ams_extruder_map)},[s?.ams_extruder_map]);const I=s?.ams_extruder_map&&Object.keys(s.ams_extruder_map).length>0?s.ams_extruder_map:Z.current,ee=w.useCallback(Y=>{if(!F)return null;const q=I[String(Y)],te=Y>=128?Y-128:Y;return(q!==void 0?q:te)===1?"L":"R"},[F,I]),[ae,X]=w.useState(null),[ce,ue]=w.useState(null),[pe,K]=w.useState(null),[se,de]=w.useState(null),ge=w.useCallback((Y,q)=>f?.find(te=>te.ams_id===Number(Y)&&te.tray_id===Number(q)),[f]),Te=w.useCallback((Y,q,te)=>{if(!p||!v)return;const oe=(te?.tray_uuid||te?.tag_uid||wu(v,Y,q))?.toUpperCase();return oe?p[oe]:void 0},[p,v]),V=pt({mutationFn:({printerId:Y,amsId:q,trayId:te})=>be.unassignSpool(Y,q,te),onSuccess:()=>{r.invalidateQueries({queryKey:["spool-assignments",t]}),a(n("inventory.unassignSuccess","Spool unassigned"),"success"),ue(null)}}),J=pt({mutationFn:Y=>be.unlinkSpool(Y),onSuccess:Y=>{a(n("spoolman.unlinkSuccess")||Y?.message,"success"),r.invalidateQueries({queryKey:["linked-spools"]}),r.invalidateQueries({queryKey:["unlinked-spools"]}),ue(null)},onError:Y=>{a(Y.message||n("spoolman.unlinkFailed"),"error")}}),D=w.useCallback(Y=>A===void 0?null:Y<=3&&Math.floor(A/4)===Y?A%4:Y>=128&&Y<=135&&A===Dx(Y,0,!1)?0:null,[A]),E=w.useCallback((Y,q,te)=>{const oe=Y>=128?(Y-128)*4+q+64:Y*4+q,he=l?.[oe],fe=I[String(Y)],re=Y>=128?Y-128:Y,L=fe!==void 0?fe:re,R={amsId:Y,trayId:q,trayCount:te&&Y>=128?1:4,tray:te,trayType:te?.tray_type||void 0,trayColor:te?.tray_color||void 0,traySubBrands:te?.tray_sub_brands||void 0,trayInfoIdx:te?.tray_info_idx||void 0,extruderId:F?L:void 0,caliIdx:te?.cali_idx,savedPresetId:he?.preset_id,location:`${a3(Y)} Slot ${q+1}`};ue(R)},[l,I,F]),U=w.useCallback(Y=>{const q=Y.id??254,te=q-254,oe=l?.[1020+te],he={amsId:255,trayId:te,trayCount:1,tray:zp(Y)?null:Y,trayType:Y.tray_type||void 0,trayColor:Y.tray_color||void 0,traySubBrands:Y.tray_sub_brands||void 0,trayInfoIdx:Y.tray_info_idx||void 0,extruderId:F?q===254?1:0:void 0,caliIdx:Y.cali_idx,savedPresetId:oe?.preset_id,location:F?q===254?"Ext-L":"Ext-R":"External"};ue(he)},[l,F]),W=w.useCallback(()=>{if(!ce)return;const{tray:Y,location:q,...te}=ce;ue(null),X(te)},[ce]),B=w.useCallback(()=>{if(!ce||!t)return;const{amsId:Y,trayId:q,trayType:te,trayColor:oe,location:he}=ce;ue(null),K({printerId:t,amsId:Y,trayId:q,trayInfo:{type:te||"",material:te,color:oe?.slice(0,6)||"",location:he}})},[ce,t]),ie=w.useCallback(()=>{if(!ce||!t)return;const{amsId:Y,trayId:q,tray:te}=ce,oe=(te?.tray_uuid||te?.tag_uid||wu(v,Y,q))?.toUpperCase()||"";ue(null),de({tagUid:te?.tag_uid||oe,trayUuid:te?.tray_uuid||"",printerId:t,amsId:Y,trayId:q})},[ce,t,v]),O=w.useCallback(()=>{if(!ce||!t)return;const{amsId:Y,trayId:q}=ce;V.mutate({printerId:t,amsId:Y,trayId:q})},[ce,t,V]);w.useEffect(()=>{if(!g&&t){e({type:"warning",message:n("spoolbuddy.ams.printerDisconnected","Printer disconnected")});return}for(const Y of k)for(const q of Y.tray||[])if(q.remain!==null&&q.remain>=0&&q.remain<15&&q.tray_type){e({type:"warning",message:`Low Filament: ${q.tray_type} (${a3(Y.id)}) - ${q.remain}% remaining`});return}e(null)},[k,g,t,e,n]);const $=w.useMemo(()=>{const Y=[];for(const q of N){const te=q.tray?.[0]||{id:0,tray_color:null,tray_type:"",tray_sub_brands:null,tray_id_name:null,tray_info_idx:null,remain:-1,k:null,cali_idx:null,tag_uid:null,tray_uuid:null,nozzle_temp_min:null,nozzle_temp_max:null},oe=b(q.id,0,zp(te)?null:te),he=y[`${q.id}-0`]??null,fe=te.remain!=null&&te.remain>=0?te.remain:null,re=he===0&&fe!==null&&fe>0?null:he;Y.push({key:`ht-${q.id}`,label:a3(q.id),tray:te,isEmpty:zp(te),isActive:D(q.id)===0,temp:q.temp,humidity:q.humidity,nozzleSide:ee(q.id),effectiveFill:oe??re??fe,onClick:()=>E(q.id,0,zp(te)?null:te)})}for(const q of G){const te=q.id??254,oe=F&&A===254?te===254&&s?.active_extruder===1||te===255&&s?.active_extruder===0:A===te,he=te-254,fe=b(255,he,zp(q)?null:q),re=y[`255-${he}`]??null,L=q.remain!=null&&q.remain>=0?q.remain:null,R=re===0&&L!==null&&L>0?null:re;Y.push({key:`ext-${te}`,label:F?te===254?n("printers.extL","Ext-L"):n("printers.extR","Ext-R"):n("printers.ext","Ext"),tray:q,isEmpty:zp(q),isActive:oe,nozzleSide:null,effectiveFill:fe??R??L,onClick:()=>U(q)})}return Y},[N,G,F,A,s?.active_extruder,n,D,ee,E,U,y,b]);return i.jsxs("div",{className:"h-full flex flex-col p-4",children:[i.jsx("div",{className:"flex-1 min-h-0",children:t?g?k.length===0&&G.length===0?i.jsx("div",{className:"flex-1 flex items-center justify-center h-full",children:i.jsxs("div",{className:"text-center text-white/50",children:[i.jsx(Ki,{className:"w-12 h-12 mx-auto mb-3 opacity-50"}),i.jsx("p",{className:"text-lg mb-2",children:n("spoolbuddy.ams.noData","No AMS detected")}),i.jsx("p",{className:"text-sm",children:n("spoolbuddy.ams.connectAms","Connect an AMS to see filament slots")})]})}):i.jsxs("div",{className:"flex flex-col gap-3 h-full",children:[i.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:C.map(Y=>i.jsx(vle,{unit:Y,activeSlot:D(Y.id),onConfigureSlot:E,isDualNozzle:F,nozzleSide:ee(Y.id),thresholds:z,fillOverrides:y,spoolmanFillOverrides:P},Y.id))}),$.length>0&&i.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:$.map(({key:Y,label:q,tray:te,isEmpty:oe,isActive:he,temp:fe,humidity:re,nozzleSide:L,effectiveFill:R,onClick:ne})=>{const ve=irt(te.tray_color);return i.jsxs("div",{className:`bg-bambu-dark-secondary rounded-lg px-3 py-2 cursor-pointer hover:bg-bambu-dark-secondary/80 transition-all flex items-center gap-3 ${he?"ring-2 ring-bambu-green":""}`,onClick:ne,children:[i.jsxs("div",{className:"relative w-10 h-10 flex-shrink-0",children:[oe?i.jsx("div",{className:"w-full h-full rounded-full border-2 border-dashed border-gray-500 flex items-center justify-center",children:i.jsx("div",{className:"w-1.5 h-1.5 rounded-full bg-gray-600"})}):i.jsxs("svg",{viewBox:"0 0 56 56",className:"w-full h-full",children:[i.jsx("circle",{cx:"28",cy:"28",r:"26",fill:ve}),i.jsx("circle",{cx:"28",cy:"28",r:"20",fill:ve,style:{filter:"brightness(0.85)"}}),i.jsx("ellipse",{cx:"20",cy:"20",rx:"6",ry:"4",fill:"white",opacity:"0.3"}),i.jsx("circle",{cx:"28",cy:"28",r:"8",fill:"#2d2d2d"}),i.jsx("circle",{cx:"28",cy:"28",r:"5",fill:"#1a1a1a"})]}),he&&i.jsx("div",{className:"absolute -bottom-0.5 left-1/2 -translate-x-1/2 w-1.5 h-1.5 bg-bambu-green rounded-full"})]}),i.jsxs("div",{className:"min-w-0",children:[i.jsxs("div",{className:"flex items-center gap-1",children:[i.jsx("span",{className:"text-xs text-white/50 font-medium truncate",children:q}),L&&i.jsx(R5,{side:L})]}),i.jsx("div",{className:"text-sm text-white/80 truncate",children:oe?"Empty":te.tray_type||"?"}),(fe!=null||re!=null)&&i.jsxs("div",{className:"flex items-center gap-1.5",children:[fe!=null&&i.jsx(yle,{temp:fe,goodThreshold:z?.tempGood,fairThreshold:z?.tempFair}),re!=null&&i.jsx(xle,{humidity:re,goodThreshold:z?.humidityGood,fairThreshold:z?.humidityFair})]})]}),!oe&&R!=null&&R>=0&&i.jsx("div",{className:"w-1.5 h-8 bg-bambu-dark-tertiary rounded-full overflow-hidden flex-shrink-0 flex flex-col-reverse",children:i.jsx("div",{className:"w-full rounded-full",style:{height:`${R}%`,backgroundColor:sx(R)}})})]},Y)})})]}):i.jsx("div",{className:"flex-1 flex items-center justify-center h-full",children:i.jsx("div",{className:"text-center text-white/50",children:i.jsx("p",{className:"text-lg mb-2",children:n("spoolbuddy.ams.printerDisconnected","Printer disconnected")})})}):i.jsx("div",{className:"flex-1 flex items-center justify-center h-full",children:i.jsxs("div",{className:"text-center text-white/50",children:[i.jsx("p",{className:"text-lg mb-2",children:n("spoolbuddy.ams.noPrinter","No printer selected")}),i.jsx("p",{className:"text-sm",children:n("spoolbuddy.ams.selectPrinter","Select a printer from the top bar")})]})})}),ae&&t&&i.jsx(oie,{isOpen:!!ae,onClose:()=>X(null),printerId:t,slotInfo:ae,printerModel:rrt(o?.model??null)||void 0,fullScreen:!0,onSuccess:()=>{r.invalidateQueries({queryKey:["slotPresets",t]}),r.invalidateQueries({queryKey:["printerStatus",t]})}}),ce&&t&&(()=>{const Y=ge(ce.amsId,ce.trayId),q=Te(ce.amsId,ce.trayId,ce.tray);return i.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[i.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:()=>ue(null)}),i.jsxs("div",{className:"relative w-full max-w-sm mx-4 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl",children:[i.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[ce.trayColor&&i.jsx("span",{className:"w-4 h-4 rounded-full border border-black/20",style:{backgroundColor:`#${ce.trayColor.slice(0,6)}`}}),i.jsx("h2",{className:"text-lg font-semibold text-white",children:ce.location}),ce.traySubBrands&&i.jsxs("span",{className:"text-sm text-bambu-gray",children:["(",ce.traySubBrands,")"]})]}),i.jsx("button",{onClick:()=>ue(null),className:"p-1 text-bambu-gray hover:text-white rounded transition-colors",children:i.jsx(qt,{className:"w-5 h-5"})})]}),i.jsxs("div",{className:"p-4 space-y-2",children:[!u&&Y?.spool&&i.jsxs("div",{className:"p-2.5 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary mb-3",children:[i.jsx("p",{className:"text-xs text-bambu-gray mb-1",children:n("inventory.assignedSpool","Assigned spool")}),i.jsxs("div",{className:"flex items-center gap-2",children:[Y.spool.rgba&&i.jsx("span",{className:"w-3 h-3 rounded-full border border-black/20 flex-shrink-0",style:{backgroundColor:`#${Y.spool.rgba.substring(0,6)}`}}),i.jsxs("span",{className:"text-sm text-white",children:[Y.spool.brand?`${Y.spool.brand} `:"",Y.spool.material,Y.spool.color_name?` - ${Y.spool.color_name}`:""]})]})]}),u&&q&&i.jsxs("div",{className:"p-2.5 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary mb-3",children:[i.jsx("p",{className:"text-xs text-bambu-gray mb-1",children:n("spoolman.linkedSpool","Linked spool")}),i.jsx("div",{className:"flex items-center gap-2",children:i.jsxs("span",{className:"text-sm text-white",children:["Spoolman #",q.id,q.remaining_weight!=null?` (${Math.round(q.remaining_weight)}g)`:""]})})]}),i.jsxs("button",{onClick:W,className:"w-full flex items-center gap-3 p-3 rounded-lg bg-bambu-dark border border-bambu-dark-tertiary hover:border-bambu-blue transition-colors text-left",children:[i.jsx(yd,{className:"w-5 h-5 text-bambu-blue flex-shrink-0"}),i.jsxs("div",{children:[i.jsx("p",{className:"text-white font-medium",children:n("configureAmsSlot.title")}),i.jsx("p",{className:"text-xs text-bambu-gray",children:n("spoolbuddy.ams.configureDesc","Set filament preset, K-profile, and color")})]})]}),!u&&(Y?i.jsxs("button",{onClick:O,disabled:V.isPending,className:"w-full flex items-center gap-3 p-3 rounded-lg bg-bambu-dark border border-bambu-dark-tertiary hover:border-amber-500 transition-colors text-left",children:[i.jsx(Df,{className:"w-5 h-5 text-amber-400 flex-shrink-0"}),i.jsxs("div",{children:[i.jsx("p",{className:"text-amber-400 font-medium",children:n("inventory.unassignSpool","Unassign")}),i.jsx("p",{className:"text-xs text-bambu-gray",children:n("spoolbuddy.ams.unassignDesc","Remove inventory spool from this slot")})]})]}):i.jsxs("button",{onClick:B,className:"w-full flex items-center gap-3 p-3 rounded-lg bg-bambu-dark border border-bambu-dark-tertiary hover:border-bambu-green transition-colors text-left",children:[i.jsx(Ii,{className:"w-5 h-5 text-bambu-green flex-shrink-0"}),i.jsxs("div",{children:[i.jsx("p",{className:"text-white font-medium",children:n("inventory.assignSpool")}),i.jsx("p",{className:"text-xs text-bambu-gray",children:n("spoolbuddy.ams.assignDesc","Track a spool from your inventory")})]})]})),u&&(q?.id?i.jsxs("button",{onClick:()=>J.mutate(q.id),disabled:J.isPending,className:"w-full flex items-center gap-3 p-3 rounded-lg bg-bambu-dark border border-bambu-dark-tertiary hover:border-amber-500 transition-colors text-left",children:[i.jsx(Df,{className:"w-5 h-5 text-amber-400 flex-shrink-0"}),i.jsxs("div",{children:[i.jsx("p",{className:"text-amber-400 font-medium",children:n("spoolman.unlinkSpool")}),i.jsx("p",{className:"text-xs text-bambu-gray",children:n("spoolbuddy.ams.unlinkDesc","Remove Spoolman link from this slot")})]})]}):i.jsxs("button",{onClick:ie,className:"w-full flex items-center gap-3 p-3 rounded-lg bg-bambu-dark border border-bambu-dark-tertiary hover:border-bambu-green transition-colors text-left",children:[i.jsx(Fu,{className:"w-5 h-5 text-bambu-green flex-shrink-0"}),i.jsxs("div",{children:[i.jsx("p",{className:"text-white font-medium",children:n("spoolman.linkToSpoolman")}),i.jsx("p",{className:"text-xs text-bambu-gray",children:n("spoolbuddy.ams.linkDesc","Link a Spoolman spool to this slot")})]})]}))]})]})]})})(),pe&&i.jsx(sie,{isOpen:!!pe,onClose:()=>{K(null),r.invalidateQueries({queryKey:["spool-assignments",t]})},printerId:pe.printerId,amsId:pe.amsId,trayId:pe.trayId,trayInfo:pe.trayInfo}),se&&i.jsx(aie,{isOpen:!!se,onClose:()=>de(null),tagUid:se.tagUid,trayUuid:se.trayUuid,printerId:se.printerId,amsId:se.amsId,trayId:se.trayId})]})}function wle({type:t,deviceId:e,onClose:n}){const{t:r}=jt(),[a,s]=w.useState(!1),[o,l]=w.useState(""),[c,d]=w.useState(""),[u,m]=w.useState(!1);w.useEffect(()=>{const y=v=>{v.key==="Escape"&&!a&&n()};return window.addEventListener("keydown",y),()=>window.removeEventListener("keydown",y)},[a,n]);const p=w.useCallback(async()=>{s(!0),l(""),d(""),m(!0);try{l(r("spoolbuddy.diagnostic.queuing",`Queuing diagnostic on device... `)),await zi.queueDiagnostics(e,t);let y=null;const v=60;let b=0;for(;bsetTimeout(g,500));try{y=await zi.getDiagnosticResult(e,t);break}catch{b++,b%4===0&&l(g=>g+".")}}if(!y)throw new Error("Diagnostic timed out - device did not report results");l(y.output),y.success||d(`Exit code: ${y.exit_code}`)}catch(y){d(y instanceof Error?y.message:"Unknown error"),l("")}finally{s(!1)}},[t,e,r]),f=t==="scale"?r("spoolbuddy.diagnostic.scaleTitle","Scale Diagnostic"):t==="read_tag"?r("spoolbuddy.diagnostic.readTagTitle","Read Tag Diagnostic"):r("spoolbuddy.diagnostic.nfcTitle","NFC Reader Diagnostic");return i.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/70 animate-fade-in",onClick:n,children:i.jsxs("div",{className:"bg-zinc-800 rounded-lg shadow-xl w-full max-w-2xl mx-4 max-h-[80vh] flex flex-col animate-slide-up",onClick:y=>y.stopPropagation(),children:[i.jsxs("div",{className:"flex justify-between items-center p-4 border-b border-zinc-700",children:[i.jsx("h2",{className:"text-lg font-semibold text-white",children:f}),i.jsx("button",{onClick:n,className:"text-zinc-400 hover:text-white transition-colors","aria-label":"Close",children:i.jsx(qt,{size:20})})]}),i.jsx("div",{className:"flex-1 overflow-auto p-4 bg-black/50 font-mono text-sm",children:a?i.jsxs("div",{className:"flex items-center gap-2 text-green-400",children:[i.jsx("div",{className:"animate-spin w-4 h-4 border-2 border-green-400 border-t-transparent rounded-full"}),i.jsx("span",{children:r("spoolbuddy.diagnostic.running","Running diagnostic on device...")})]}):o?i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"text-green-400 whitespace-pre-wrap break-words",children:o}),c&&i.jsxs("div",{className:"text-red-400 mt-2",children:["❌ ",c]})]}):u?i.jsx("div",{children:c?i.jsxs("div",{className:"text-red-400",children:["ERROR: ",c]}):i.jsx("span",{className:"text-green-400",children:r("spoolbuddy.diagnostic.completed","Diagnostic completed successfully.")})}):i.jsxs("div",{className:"text-zinc-500",children:[r("spoolbuddy.diagnostic.clickStart",'Click "Run Diagnostic" to start the hardware diagnostic on')," ",e,"."]})}),i.jsxs("div",{className:"flex gap-2 p-4 border-t border-zinc-700 bg-zinc-800",children:[i.jsx("button",{onClick:p,disabled:a,className:"flex-1 flex items-center justify-center gap-2 bg-green-600 hover:bg-green-700 disabled:bg-gray-600 disabled:cursor-not-allowed px-4 py-2 rounded font-semibold text-white transition-colors",children:a?i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"animate-spin w-4 h-4 border-2 border-white border-t-transparent rounded-full"}),r("spoolbuddy.diagnostic.runningBtn","Running...")]}):u?i.jsxs(i.Fragment,{children:[i.jsx(Yge,{size:16}),r("spoolbuddy.diagnostic.runAgain","Run Again")]}):i.jsxs(i.Fragment,{children:[i.jsx(Ks,{size:16}),r("spoolbuddy.diagnostic.runBtn","Run Diagnostic")]})}),i.jsx("button",{onClick:n,className:"px-4 py-2 rounded bg-zinc-700 hover:bg-zinc-600 text-white font-semibold transition-colors",children:r("spoolbuddy.diagnostic.close","Close")})]})]})})}function srt(t){if(t<60)return`${t}s`;if(t<3600)return`${Math.floor(t/60)}m`;const e=Math.floor(t/3600),n=Math.floor(t%3600/60);return`${e}h ${n}m`}function ort(t){if(!t)return"-";try{const e=new Date(t);return e.toLocaleDateString(void 0,{month:"short",day:"numeric"})+" "+e.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"})}catch{return"-"}}const lrt=[{label:"Off",value:0},{label:"1m",value:60},{label:"2m",value:120},{label:"5m",value:300},{label:"10m",value:600},{label:"30m",value:1800}];function crt({device:t}){const{t:e}=jt(),[n,r]=w.useState(null),[a,s]=w.useState(""),[o,l]=w.useState(""),[c,d]=w.useState(!1),[u,m]=w.useState(null);w.useEffect(()=>{!a&&t.backend_url&&s(t.backend_url)},[t.backend_url,a]);const p=async()=>{if(!a.trim()){m({type:"error",text:e("spoolbuddy.settings.systemFieldsRequired","Backend URL is required.")});return}d(!0),m(null);try{await zi.updateSystemConfig(t.device_id,a.trim(),o.trim()||void 0),m({type:"ok",text:e("spoolbuddy.settings.systemQueued","Config queued.")})}catch(f){m({type:"error",text:f instanceof Error?f.message:e("common.error","Error")})}finally{d(!1)}};return i.jsxs("div",{className:"space-y-2",children:[i.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[i.jsxs("div",{className:"bg-zinc-800 rounded-lg p-3",children:[i.jsx("h3",{className:"text-sm font-semibold text-zinc-300 mb-2",children:e("spoolbuddy.settings.nfcReader","NFC Reader")}),i.jsxs("div",{className:"space-y-1.5 text-xs",children:[i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-zinc-500",children:e("spoolbuddy.settings.type","Type")}),i.jsx("span",{className:"text-zinc-300 font-mono",children:t.nfc_reader_type||"N/A"})]}),i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-zinc-500",children:e("spoolbuddy.settings.connection","Connection")}),i.jsx("span",{className:"text-zinc-300 font-mono",children:t.nfc_connection||"N/A"})]}),i.jsxs("div",{className:"flex justify-between items-center",children:[i.jsx("span",{className:"text-zinc-500",children:e("spoolbuddy.status.status","Status")}),i.jsxs("div",{className:"flex items-center gap-1.5",children:[i.jsx("div",{className:`w-2 h-2 rounded-full ${t.nfc_ok?"bg-green-500":t.nfc_reader_type?"bg-red-500":"bg-zinc-600"}`}),i.jsx("span",{className:t.nfc_ok?"text-green-400":t.nfc_reader_type?"text-red-400":"text-zinc-500",children:t.nfc_ok?e("spoolbuddy.status.nfcReady","Ready"):t.nfc_reader_type?e("common.error","Error"):e("spoolbuddy.settings.notConnected","N/A")})]})]})]})]}),i.jsxs("div",{className:"bg-zinc-800 rounded-lg p-3",children:[i.jsx("h3",{className:"text-sm font-semibold text-zinc-300 mb-2",children:e("spoolbuddy.settings.deviceInfo","Device Info")}),i.jsxs("div",{className:"space-y-1.5 text-xs",children:[i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-zinc-500",children:e("spoolbuddy.settings.hostname","Host")}),i.jsx("span",{className:"text-zinc-300 truncate ml-2",children:t.hostname})]}),i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-zinc-500",children:"IP"}),i.jsx("span",{className:"text-zinc-300",children:t.ip_address})]}),i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-zinc-500",children:e("spoolbuddy.settings.uptime","Uptime")}),i.jsx("span",{className:"text-zinc-300",children:srt(t.uptime_s)})]}),i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-zinc-500",children:"ID"}),i.jsx("span",{className:"text-zinc-400 font-mono truncate ml-2",children:t.device_id})]})]})]})]}),i.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[i.jsxs("div",{className:"bg-zinc-800 rounded-lg p-3 space-y-2",children:[i.jsx("h3",{className:"text-sm font-semibold text-zinc-300",children:e("spoolbuddy.settings.systemConfig","Backend & Auth")}),i.jsx("input",{value:a,onChange:f=>s(f.target.value),placeholder:"http://192.168.1.100:5000",className:"w-full px-2 py-1.5 rounded bg-zinc-900 border border-zinc-700 text-zinc-100 text-xs"}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx("input",{type:"password",value:o,onChange:f=>l(f.target.value),placeholder:e("spoolbuddy.settings.apiTokenPlaceholder","API token"),className:"flex-1 px-2 py-1.5 rounded bg-zinc-900 border border-zinc-700 text-zinc-100 text-xs"}),i.jsx("button",{onClick:p,disabled:c,className:"px-3 py-1.5 rounded bg-green-700 hover:bg-green-600 disabled:bg-zinc-700 text-xs font-medium text-zinc-100",children:e("spoolbuddy.settings.saveConfig","Save")})]}),u&&i.jsx("div",{className:`text-xs ${u.type==="ok"?"text-green-400":"text-red-400"}`,children:u.text})]}),i.jsxs("div",{className:"bg-zinc-800 rounded-lg p-3 flex flex-col gap-2",children:[i.jsxs("button",{onClick:()=>r("nfc"),className:"flex-1 bg-blue-700 hover:bg-blue-600 transition-colors rounded-lg p-2 flex items-center gap-2",children:[i.jsx(cQ,{className:"w-4 h-4 text-blue-300 shrink-0"}),i.jsx("span",{className:"text-xs font-medium text-blue-100",children:e("spoolbuddy.settings.nfcDiagnostic","NFC Diagnostic")})]}),i.jsxs("button",{onClick:()=>r("scale"),className:"flex-1 bg-yellow-700 hover:bg-yellow-600 transition-colors rounded-lg p-2 flex items-center gap-2",children:[i.jsx(Wl,{className:"w-4 h-4 text-yellow-300 shrink-0"}),i.jsx("span",{className:"text-xs font-medium text-yellow-100",children:e("spoolbuddy.settings.scaleDiagnostic","Scale Diagnostic")})]}),i.jsxs("button",{onClick:()=>r("read_tag"),className:"flex-1 bg-emerald-700 hover:bg-emerald-600 transition-colors rounded-lg p-2 flex items-center gap-2",children:[i.jsx(Ss,{className:"w-4 h-4 text-emerald-300 shrink-0"}),i.jsx("span",{className:"text-xs font-medium text-emerald-100",children:e("spoolbuddy.settings.readTagDiagnostic","Read Tag")})]})]})]}),n&&t&&i.jsx(wle,{type:n,deviceId:t.device_id,onClose:()=>r(null)})]})}function drt({device:t,onBrightnessChange:e,onBlankTimeoutChange:n}){const{t:r}=jt(),[a,s]=w.useState(t.display_brightness),[o,l]=w.useState(t.display_blank_timeout),[c,d]=w.useState(!1),u=w.useRef(void 0),m=w.useRef(void 0);w.useEffect(()=>{s(t.display_brightness),l(t.display_blank_timeout)},[t.display_brightness,t.display_blank_timeout]);const p=w.useCallback(()=>{d(!0),m.current&&clearTimeout(m.current),m.current=setTimeout(()=>d(!1),1500)},[]),f=w.useCallback((b,g)=>{u.current&&clearTimeout(u.current),u.current=setTimeout(()=>{zi.updateDisplay(t.device_id,b,g).then(()=>p()).catch(_=>console.error("Failed to update display:",_))},300)},[t.device_id,p]),y=b=>{s(b),e(b),f(b,o)},v=b=>{l(b),n(b),f(a,b)};return i.jsxs("div",{className:"space-y-4",children:[i.jsxs("div",{className:"bg-zinc-800 rounded-lg p-4",children:[i.jsxs("div",{className:"flex items-center justify-between mb-3",children:[i.jsx("h3",{className:"text-sm font-semibold text-zinc-300",children:r("spoolbuddy.settings.brightness","Brightness")}),c&&i.jsxs("span",{className:"text-xs text-green-400 flex items-center gap-1 animate-pulse",children:[i.jsx("svg",{className:"w-3 h-3",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:3,children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M5 13l4 4L19 7"})}),r("spoolbuddy.settings.saved","Saved")]})]}),i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("svg",{className:"w-4 h-4 text-zinc-500 flex-shrink-0",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 3v1m0 16v1m9-9h-1M4 12H3m15.364 6.364l-.707-.707M6.343 6.343l-.707-.707m12.728 0l-.707.707M6.343 17.657l-.707.707M16 12a4 4 0 11-8 0 4 4 0 018 0z"})}),i.jsx("input",{type:"range",min:0,max:100,value:a,onChange:b=>y(parseInt(b.target.value)),className:"flex-1 h-2 bg-zinc-700 rounded-lg appearance-none cursor-pointer accent-green-500"}),i.jsxs("span",{className:"text-sm font-mono text-zinc-400 w-10 text-right",children:[a,"%"]})]}),!t.has_backlight&&i.jsx("p",{className:"text-xs text-zinc-600 mt-2",children:r("spoolbuddy.settings.noBacklight","No DSI backlight detected. Brightness control requires a DSI display.")})]}),i.jsxs("div",{className:"bg-zinc-800 rounded-lg p-4",children:[i.jsx("h3",{className:"text-sm font-semibold text-zinc-300 mb-1",children:r("spoolbuddy.settings.screenBlank","Screen Blank Timeout")}),i.jsx("p",{className:"text-xs text-zinc-500 mb-3",children:r("spoolbuddy.settings.screenBlankDesc","Screen turns off after inactivity. Touch to wake.")}),i.jsx("div",{className:"grid grid-cols-3 gap-2",children:lrt.map(b=>i.jsx("button",{onClick:()=>v(b.value),className:`px-3 py-2 rounded-lg text-sm font-medium transition-colors min-h-[40px] ${o===b.value?"bg-green-600 text-white":"bg-zinc-700 text-zinc-300 hover:bg-zinc-600"}`,children:b.label},b.value))})]}),i.jsx("p",{className:"text-xs text-zinc-600 text-center",children:r("spoolbuddy.settings.displayNote","Brightness is applied as a software filter.")})]})}function urt({step:t,labels:e}){return i.jsxs("div",{className:"flex flex-col items-center w-16 shrink-0 pt-1",children:[i.jsx("div",{className:`flex items-center justify-center w-7 h-7 rounded-full text-xs font-bold ${t==="tare"?"bg-green-600 text-white":"bg-green-600/20 text-green-400"}`,children:t==="weight"?i.jsx("svg",{className:"w-3.5 h-3.5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:3,children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M5 13l4 4L19 7"})}):"1"}),i.jsx("span",{className:`text-[10px] mt-0.5 ${t==="tare"?"text-green-400 font-medium":"text-green-400/60"}`,children:e.tare}),i.jsx("div",{className:`w-px h-5 my-1 ${t==="weight"?"bg-green-600/40":"bg-zinc-700"}`}),i.jsx("div",{className:`flex items-center justify-center w-7 h-7 rounded-full text-xs font-bold ${t==="weight"?"bg-green-600 text-white":"bg-zinc-700 text-zinc-500"}`,children:"2"}),i.jsx("span",{className:`text-[10px] mt-0.5 ${t==="weight"?"text-green-400 font-medium":"text-zinc-600"}`,children:e.weight})]})}function mrt({device:t,weight:e,weightStable:n,rawAdc:r}){const{t:a}=jt(),[s,o]=w.useState("idle"),[l,c]=w.useState("500"),[d,u]=w.useState(null),[m,p]=w.useState(!1),[f,y]=w.useState(null),v=_=>{_==="backspace"?c(k=>k.slice(0,-1)||""):_==="."&&!l.includes(".")?c(k=>k+"."):_>="0"&&_<="9"&&c(k=>k==="0"?_:k+_)},b=async()=>{p(!0),y(null);try{await zi.tare(t.device_id),y({type:"ok",msg:a("spoolbuddy.settings.tareSet","Tare command sent. Waiting for device...")})}catch{y({type:"error",msg:a("spoolbuddy.settings.tareFailed","Failed to send tare command")})}finally{p(!1)}},g=async()=>{if(s==="tare"){p(!0),y(null);try{u(r),await zi.tare(t.device_id),y({type:"ok",msg:a("spoolbuddy.settings.zeroSet","Zero point set. Place known weight on scale.")}),o("weight")}catch{y({type:"error",msg:a("spoolbuddy.settings.tareFailed","Failed to send tare command")})}finally{p(!1)}}else if(s==="weight"){const _=parseFloat(l);if(r===null||!_||_<=0)return;p(!0),y(null);try{await zi.setCalibrationFactor(t.device_id,_,r,d??void 0),y({type:"ok",msg:a("spoolbuddy.settings.calibrationDone","Calibration complete!")}),o("idle")}catch{y({type:"error",msg:a("spoolbuddy.settings.calibrationFailed","Calibration failed")})}finally{p(!1)}}};return s==="idle"?i.jsxs("div",{className:"flex flex-col h-full",children:[i.jsxs("div",{className:"bg-zinc-800 rounded-lg p-3 mb-3",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("div",{className:`w-2 h-2 rounded-full ${n?"bg-green-500":"bg-amber-500 animate-pulse"}`}),i.jsx("span",{className:"text-lg font-mono text-zinc-200",children:e!==null?`${e.toFixed(1)} g`:"-- g"})]}),i.jsxs("div",{className:"text-xs text-zinc-500 text-right",children:[i.jsxs("span",{children:[a("spoolbuddy.settings.tareOffset","Tare"),": ",t.tare_offset]}),i.jsx("span",{className:"mx-1.5",children:"·"}),i.jsxs("span",{children:[a("spoolbuddy.settings.calFactor","Factor"),": ",t.calibration_factor.toFixed(2)]})]})]}),t.last_calibrated_at&&i.jsxs("div",{className:"text-xs text-zinc-600 mt-1",children:[a("spoolbuddy.settings.lastCalibrated","Last calibrated"),": ",ort(t.last_calibrated_at)]})]}),f&&i.jsx("div",{className:`rounded-lg px-3 py-2 mb-3 text-sm ${f.type==="ok"?"bg-green-900/30 text-green-300 border border-green-800":"bg-red-900/30 text-red-300 border border-red-800"}`,children:f.msg}),i.jsxs("div",{className:"flex gap-2",children:[i.jsxs("button",{onClick:b,disabled:m,className:"flex-1 px-4 py-2.5 rounded-lg text-sm font-medium bg-zinc-700 text-zinc-200 hover:bg-zinc-600 disabled:opacity-40 transition-colors min-h-[44px] flex items-center justify-center gap-2",children:[m&&i.jsxs("svg",{className:"w-4 h-4 animate-spin",viewBox:"0 0 24 24",fill:"none",children:[i.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),i.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"})]}),a("spoolbuddy.weight.tare","Tare")]}),i.jsx("button",{onClick:()=>{o("tare"),y(null)},className:"flex-1 px-4 py-2.5 rounded-lg text-sm font-medium bg-green-600 text-white hover:bg-green-700 transition-colors min-h-[44px]",children:a("spoolbuddy.weight.calibrate","Calibrate")})]})]}):i.jsxs("div",{className:"flex gap-3",children:[i.jsx(urt,{step:s,labels:{tare:a("spoolbuddy.weight.tare","Tare"),weight:a("spoolbuddy.settings.knownWeight","Known weight")}}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsxs("div",{className:"flex items-center gap-2 bg-zinc-800 rounded-lg px-3 py-1.5 mb-1.5",children:[i.jsx("div",{className:`w-2 h-2 rounded-full shrink-0 ${n?"bg-green-500":"bg-amber-500 animate-pulse"}`}),i.jsx("span",{className:"text-sm font-mono text-zinc-200",children:e!==null?`${e.toFixed(1)} g`:"-- g"}),i.jsx("span",{className:`text-xs ml-auto ${n?"text-green-400":"text-amber-400"}`,children:n?a("spoolbuddy.settings.stable","Stable"):a("spoolbuddy.settings.settling","Settling...")})]}),f&&i.jsx("div",{className:`rounded-lg px-3 py-1.5 mb-1.5 text-xs ${f.type==="ok"?"bg-green-900/30 text-green-300 border border-green-800":"bg-red-900/30 text-red-300 border border-red-800"}`,children:f.msg}),s==="tare"?i.jsx("p",{className:"text-sm text-zinc-300 mb-3",children:a("spoolbuddy.settings.calStep1","Remove all items from the scale and press Set Zero.")}):i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[i.jsx("span",{className:"text-xs text-zinc-400 shrink-0",children:a("spoolbuddy.settings.knownWeight","Known weight")}),i.jsxs("div",{className:"flex-1 bg-zinc-900 border border-zinc-600 rounded px-3 py-1 text-right text-lg font-mono text-zinc-100",children:[l||"0",i.jsx("span",{className:"text-zinc-500 ml-1",children:"g"})]})]}),i.jsx("div",{className:"grid grid-cols-4 gap-1 mb-1.5",children:["7","8","9","backspace","4","5","6",".","1","2","3","0"].map(_=>i.jsx("button",{onClick:()=>v(_),className:`rounded text-lg font-medium transition-colors h-[48px] active:scale-95 ${_==="backspace"?"bg-zinc-700 text-zinc-300 hover:bg-zinc-600":"bg-zinc-800 text-zinc-100 hover:bg-zinc-700 border border-zinc-700"}`,children:_==="backspace"?"⌫":_},_))})]}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx("button",{onClick:()=>{o("idle"),y(null)},className:"flex-1 px-4 py-2 rounded-lg text-sm bg-zinc-700 text-zinc-300 hover:bg-zinc-600 transition-colors h-[40px]",children:a("common.cancel","Cancel")}),i.jsxs("button",{onClick:g,disabled:m,className:"flex-1 px-4 py-2 rounded-lg text-sm font-medium bg-green-600 text-white hover:bg-green-700 disabled:opacity-40 transition-colors h-[40px] flex items-center justify-center gap-2",children:[m&&i.jsxs("svg",{className:"w-4 h-4 animate-spin",viewBox:"0 0 24 24",fill:"none",children:[i.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),i.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"})]}),s==="tare"?a("spoolbuddy.settings.setZero","Set Zero"):a("spoolbuddy.settings.calibrateNow","Calibrate")]})]})]})]})}function hrt({device:t}){const{t:e}=jt(),[n,r]=w.useState(null),[a,s]=w.useState(null),[o,l]=w.useState(!1),[c,d]=w.useState(!1),u=t.update_status==="pending"||t.update_status==="updating";w.useEffect(()=>{u&&n==="applying"&&r(null)},[u,n]),w.useEffect(()=>{const k=()=>{u&&setTimeout(()=>window.location.reload(),1e3)};return window.addEventListener("spoolbuddy-online",k),()=>window.removeEventListener("spoolbuddy-online",k)},[u]);const{data:m,refetch:p}=et({queryKey:["spoolbuddy-update-check",t.device_id],queryFn:()=>zi.checkDaemonUpdate(t.device_id),staleTime:0}),{data:f}=et({queryKey:["spoolbuddy-ssh-key"],queryFn:()=>zi.getSSHPublicKey(),enabled:o,staleTime:1/0}),y=async()=>{r("checking"),s(null);try{await p()}finally{r(null)}},v=async()=>{r("applying"),s(null);try{await zi.triggerUpdate(t.device_id)}catch(k){s(k instanceof Error?k.message:"Failed to trigger update"),r(null)}},b=n!=null||u,g=()=>{f?.public_key&&(navigator.clipboard.writeText(f.public_key),d(!0),setTimeout(()=>d(!1),2e3))},_=t.firmware_version||(m?.current_version&&m.current_version!=="0.0.0"?m.current_version:null);return i.jsxs("div",{className:"space-y-3",children:[i.jsxs("div",{className:"bg-zinc-800 rounded-lg p-3 space-y-3",children:[i.jsxs("div",{className:"flex justify-between items-center text-sm",children:[i.jsx("span",{className:"text-zinc-500",children:e("spoolbuddy.settings.currentVersion","Current Version")}),i.jsx("span",{className:"text-zinc-200 font-mono",children:_||i.jsx("span",{className:"text-zinc-500 italic text-xs",children:e("spoolbuddy.settings.versionPending","Waiting for daemon...")})})]}),b?i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs("svg",{className:"w-4 h-4 animate-spin text-green-400 flex-shrink-0",viewBox:"0 0 24 24",fill:"none",children:[i.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),i.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"})]}),i.jsx("span",{className:"text-green-300 text-xs",children:n==="checking"?e("spoolbuddy.settings.checking","Checking for updates..."):t.update_message||e("spoolbuddy.settings.updateWaiting","Updating...")})]}):t.update_status==="error"?i.jsx("p",{className:"text-xs text-red-300",children:t.update_message||e("spoolbuddy.settings.updateFailed","Update failed")}):a?i.jsx("p",{className:"text-xs text-red-300",children:a}):m?.update_available?i.jsxs("p",{className:"text-xs text-green-300",children:[e("spoolbuddy.settings.updateAvailable","Update available"),": ",_," → ",m.latest_version]}):null,!b&&(m?.update_available?i.jsx("button",{onClick:v,disabled:!t.online,className:"w-full px-3 py-2 rounded-lg text-sm font-medium bg-green-600 text-white hover:bg-green-700 disabled:opacity-40 transition-colors",children:t.online?e("spoolbuddy.settings.applyUpdate","Apply Update"):e("spoolbuddy.settings.deviceOffline","Device Offline")}):i.jsxs("div",{className:"flex gap-2",children:[i.jsx("button",{onClick:y,className:"flex-1 px-3 py-2 rounded-lg text-xs font-medium bg-zinc-700 text-zinc-300 hover:bg-zinc-600 transition-colors",children:e("spoolbuddy.settings.checkUpdates","Check for Updates")}),i.jsx("button",{onClick:v,disabled:!t.online,className:"px-3 py-2 rounded-lg text-xs font-medium bg-zinc-700 text-zinc-400 hover:bg-zinc-600 hover:text-zinc-200 disabled:opacity-40 transition-colors",children:e("spoolbuddy.settings.forceUpdate","Force Update")})]}))]}),i.jsxs("div",{className:"bg-zinc-800 rounded-lg p-3",children:[i.jsxs("button",{onClick:()=>l(!o),className:"w-full flex justify-between items-center text-xs",children:[i.jsx("span",{className:"font-medium text-zinc-400",children:e("spoolbuddy.settings.sshSetup","SSH Setup")}),i.jsx("svg",{className:`w-3 h-3 text-zinc-500 transition-transform ${o?"rotate-180":""}`,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M19 9l-7 7-7-7"})})]}),o&&i.jsxs("div",{className:"mt-2 space-y-2",children:[i.jsx("p",{className:"text-xs text-zinc-500",children:e("spoolbuddy.settings.sshDescription","SSH key is deployed automatically. For manual setup, add this key to ~/.ssh/authorized_keys on the device.")}),f?.public_key?i.jsxs("div",{className:"relative",children:[i.jsx("pre",{className:"bg-zinc-900 rounded p-2 text-[10px] text-zinc-400 font-mono break-all whitespace-pre-wrap",children:f.public_key}),i.jsx("button",{onClick:g,className:"absolute top-1 right-1 px-1.5 py-0.5 rounded text-[10px] bg-zinc-700 text-zinc-300 hover:bg-zinc-600 transition-colors",children:c?e("common.copied","Copied!"):e("common.copy","Copy")})]}):i.jsx("span",{className:"text-[10px] text-zinc-500 italic",children:e("spoolbuddy.settings.sshKeyLoading","Loading...")})]})]})]})}function prt(){const{sbState:t,setDisplayBrightness:e,setDisplayBlankTimeout:n}=fw(),{t:r}=jt(),[a,s]=w.useState("device"),{data:o=[]}=et({queryKey:["spoolbuddy-devices"],queryFn:()=>zi.getDevices(),refetchInterval:1e4}),l=t.deviceId?o.find(d=>d.device_id===t.deviceId)??o[0]:o[0],c=[{id:"device",label:r("spoolbuddy.settings.tabDevice","Device")},{id:"display",label:r("spoolbuddy.settings.tabDisplay","Display")},{id:"scale",label:r("spoolbuddy.settings.tabScale","Scale")},{id:"updates",label:r("spoolbuddy.settings.tabUpdates","Updates")}];return i.jsxs("div",{className:"h-full flex flex-col p-4",children:[i.jsx("h1",{className:"text-xl font-semibold text-zinc-100 mb-3",children:r("spoolbuddy.nav.settings","Settings")}),i.jsx("div",{className:"flex gap-1 bg-zinc-800/50 rounded-lg p-1 mb-4",children:c.map(d=>i.jsx("button",{onClick:()=>s(d.id),className:`flex-1 px-2 py-2 rounded-md text-sm font-medium transition-colors min-h-[36px] ${a===d.id?"bg-zinc-700 text-zinc-100":"text-zinc-500 hover:text-zinc-300"}`,children:d.label},d.id))}),i.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:l?i.jsxs(i.Fragment,{children:[a==="device"&&i.jsx(crt,{device:l}),a==="display"&&i.jsx(drt,{device:l,onBrightnessChange:e,onBlankTimeoutChange:n}),a==="scale"&&i.jsx(mrt,{device:l,weight:t.weight,weightStable:t.weightStable,rawAdc:t.rawAdc}),a==="updates"&&i.jsx(hrt,{device:l})]}):i.jsx("div",{className:"flex items-center justify-center h-32",children:i.jsx("div",{className:"text-center text-zinc-500",children:i.jsx("p",{className:"text-sm",children:r("spoolbuddy.settings.noDevice","No SpoolBuddy device found")})})})})]})}function frt({device:t,weight:e,weightStable:n,rawAdc:r}){const{t:a}=jt(),[s,o]=w.useState(!1),[l,c]=w.useState("idle"),[d,u]=w.useState("500"),[m,p]=w.useState(null),[f,y]=w.useState(!1),v=k=>{k==="backspace"?u(C=>C.slice(0,-1)||""):k==="."&&!d.includes(".")?u(C=>C+"."):k>="0"&&k<="9"&&u(C=>C==="0"?k:C+k)},b=async()=>{y(!0);try{await zi.tare(t.device_id)}catch(k){console.error("Failed to tare:",k)}finally{y(!1)}},g=()=>{c("tare")},_=async()=>{if(l==="tare"){o(!0);try{p(r),await zi.tare(t.device_id),c("weight")}catch(k){console.error("Failed to tare:",k)}finally{o(!1)}}else if(l==="weight"){const k=parseFloat(d);if(r===null||!k||k<=0)return;o(!0);try{await zi.setCalibrationFactor(t.device_id,k,r,m??void 0),c("idle")}catch(C){console.error("Failed to calibrate:",C)}finally{o(!1)}}};return i.jsxs("div",{className:"space-y-4",children:[i.jsxs("div",{className:"bg-zinc-800 rounded-lg p-4",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("span",{className:"text-sm text-zinc-400",children:a("spoolbuddy.settings.currentWeight","Current weight")}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("div",{className:`w-2 h-2 rounded-full ${n?"bg-green-500":"bg-amber-500 animate-pulse"}`}),i.jsx("span",{className:"text-lg font-mono text-zinc-200",children:e!==null?`${e.toFixed(1)} g`:"-- g"})]})]}),i.jsxs("div",{className:"grid grid-cols-2 gap-4 mt-3 text-xs",children:[i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-zinc-500",children:a("spoolbuddy.settings.tareOffset","Tare offset")}),i.jsx("span",{className:"text-zinc-400 font-mono",children:t.tare_offset})]}),i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-zinc-500",children:a("spoolbuddy.settings.calFactor","Cal. factor")}),i.jsx("span",{className:"text-zinc-400 font-mono",children:t.calibration_factor.toFixed(2)})]})]})]}),l==="idle"?i.jsxs("div",{className:"flex gap-2",children:[i.jsx("button",{onClick:b,disabled:f,className:"flex-1 px-4 py-2.5 rounded-lg text-sm font-medium bg-zinc-700 text-zinc-200 hover:bg-zinc-600 disabled:opacity-40 transition-colors min-h-[44px]",children:f?"...":a("spoolbuddy.weight.tare","Tare")}),i.jsx("button",{onClick:g,className:"flex-1 px-4 py-2.5 rounded-lg text-sm font-medium bg-green-600 text-white hover:bg-green-700 transition-colors min-h-[44px]",children:a("spoolbuddy.weight.calibrate","Calibrate")})]}):i.jsxs("div",{className:"bg-zinc-800 border border-zinc-700 rounded-lg p-3 space-y-2",children:[i.jsx("div",{className:"text-sm font-medium text-zinc-200",children:l==="tare"?a("spoolbuddy.settings.calStep1","Step 1: Remove all items from the scale"):a("spoolbuddy.settings.calStep2","Step 2: Place known weight on scale")}),l==="weight"&&i.jsxs("div",{className:"space-y-1.5",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"text-xs text-zinc-400",children:a("spoolbuddy.settings.knownWeight","Known weight (g)")}),i.jsxs("div",{className:"flex-1 bg-zinc-900 border border-zinc-600 rounded px-3 py-1.5 text-right text-base font-mono text-zinc-100",children:[d||"0",i.jsx("span",{className:"text-zinc-500 ml-1",children:"g"})]})]}),i.jsx("div",{className:"grid grid-cols-4 gap-1",children:["7","8","9","backspace","4","5","6",".","1","2","3","0"].map(k=>i.jsx("button",{onClick:()=>v(k),className:`py-2 rounded text-sm font-medium transition-colors min-h-[36px] ${k==="backspace"?"bg-zinc-700 text-zinc-300 hover:bg-zinc-600":"bg-zinc-800 text-zinc-100 hover:bg-zinc-700 border border-zinc-700"}`,children:k==="backspace"?"⌫":k},k))})]}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx("button",{onClick:()=>c("idle"),className:"flex-1 px-4 py-2 rounded-lg text-sm bg-zinc-700 text-zinc-300 hover:bg-zinc-600 transition-colors min-h-[40px]",children:a("common.cancel","Cancel")}),i.jsx("button",{onClick:_,disabled:s,className:"flex-1 px-4 py-2 rounded-lg text-sm font-medium bg-green-600 text-white hover:bg-green-700 disabled:opacity-40 transition-colors min-h-[40px]",children:s?"...":l==="tare"?a("spoolbuddy.settings.setZero","Set Zero"):a("spoolbuddy.settings.calibrateNow","Calibrate")})]})]})]})}function grt(){const{sbState:t}=fw(),{t:e}=jt(),n=ol(),{data:r=[]}=et({queryKey:["spoolbuddy-devices"],queryFn:()=>zi.getDevices(),refetchInterval:1e4}),a=t.deviceId?r.find(s=>s.device_id===t.deviceId)??r[0]:r[0];return i.jsxs("div",{className:"h-full flex flex-col p-4",children:[i.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[i.jsx("button",{onClick:()=>n("/spoolbuddy/settings"),className:"p-1.5 rounded-lg text-zinc-400 hover:text-zinc-200 hover:bg-zinc-800 transition-colors",children:i.jsx("svg",{className:"w-5 h-5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M15 19l-7-7 7-7"})})}),i.jsx("h1",{className:"text-xl font-semibold text-zinc-100",children:e("spoolbuddy.settings.scaleCalibration","Scale Calibration")})]}),i.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:a?i.jsx(frt,{device:a,weight:t.weight,weightStable:t.weightStable,rawAdc:t.rawAdc}):i.jsx("div",{className:"flex items-center justify-center h-32",children:i.jsx("div",{className:"text-center text-zinc-500",children:i.jsx("p",{className:"text-sm",children:e("spoolbuddy.settings.noDevice","No SpoolBuddy device found")})})})})]})}const brt=["PLA","PETG","ABS","ASA","TPU","PA","PC","PVA","HIPS"];function xrt(){const{t}=jt(),{sbState:e}=fw(),[n,r]=w.useState("existing"),[a,s]=w.useState(null),[o,l]=w.useState(""),[c,d]=w.useState("idle"),[u,m]=w.useState(""),[p,f]=w.useState(!1),[y,v]=w.useState(!1),[b,g]=w.useState(null),[_,k]=w.useState(null),{data:C=[],refetch:N}=et({queryKey:["inventory-spools"],queryFn:()=>be.getSpools(!1),refetchInterval:1e4}),{data:P=[]}=et({queryKey:["spoolbuddy-devices"],queryFn:()=>zi.getDevices(),refetchInterval:5e3}),{data:T}=et({queryKey:["settings"],queryFn:be.getSettings}),j=P[0],A=e.deviceOnline,F=go(T?.currency||"USD"),G=w.useMemo(()=>{let ge;if(n==="existing")ge=C.filter(Te=>!Te.tag_uid&&!Te.archived_at);else if(n==="replace")ge=C.filter(Te=>(Te.tag_uid||Te.tray_uuid)&&!Te.archived_at);else return[];if(o){const Te=o.toLowerCase();ge=ge.filter(V=>V.material?.toLowerCase().includes(Te)||V.color_name?.toLowerCase().includes(Te)||V.brand?.toLowerCase().includes(Te)||V.subtype?.toLowerCase().includes(Te))}return ge},[C,n,o]),z=w.useCallback(ge=>{const Te=ge.detail;(Te.sak??Te.data?.sak)===0&&(v(!0),g(Te.tag_uid??Te.data?.tag_uid??null))},[]),Z=w.useCallback(ge=>{const Te=ge.detail;v(!0),g(Te.tag_uid??Te.data?.tag_uid??null)},[]),I=w.useCallback(()=>{v(!1),g(null)},[]),ee=w.useCallback(ge=>{const Te=ge.detail;(Te.spool_id===a?.id||Te.data?.spool_id===a?.id)&&(d("success"),m(t("spoolbuddy.writeTag.writeSuccess","Tag written successfully!")),N(),setTimeout(()=>{d("idle"),s(null),m("")},5e3))},[a,t,N]),ae=w.useCallback(ge=>{const Te=ge.detail;(Te.spool_id===a?.id||Te.data?.spool_id===a?.id)&&(d("error"),m(Te.message??Te.data?.message??t("spoolbuddy.writeTag.writeFailed","Write failed")))},[a,t]);w.useEffect(()=>(window.addEventListener("spoolbuddy-unknown-tag",z),window.addEventListener("spoolbuddy-tag-matched",Z),window.addEventListener("spoolbuddy-tag-removed",I),window.addEventListener("spoolbuddy-tag-written",ee),window.addEventListener("spoolbuddy-tag-write-failed",ae),()=>{window.removeEventListener("spoolbuddy-unknown-tag",z),window.removeEventListener("spoolbuddy-tag-matched",Z),window.removeEventListener("spoolbuddy-tag-removed",I),window.removeEventListener("spoolbuddy-tag-written",ee),window.removeEventListener("spoolbuddy-tag-write-failed",ae)}),[z,Z,I,ee,ae]),w.useEffect(()=>{s(null),d("idle"),m(""),l("")},[n]);const X=async()=>{if(!(!a||!j)){d("writing"),m(t("spoolbuddy.writeTag.waiting","Waiting for SpoolBuddy..."));try{await zi.writeTag(j.device_id,a.id)}catch{d("error"),m(t("spoolbuddy.writeTag.queueFailed","Failed to queue write command"))}}},ce=async()=>{if(j){try{await zi.cancelWrite(j.device_id)}catch{}d("idle"),m("")}},ue=async()=>{if(!(!a||!XY(a))){f(!0),d("idle"),m("");try{await be.linkTagToSpool(a.id,{tag_uid:"",tray_uuid:"",data_origin:"manual"}),await N(),s(null),d("success"),m(t("spoolbuddy.writeTag.untagSuccess","Tag removed from spool")),setTimeout(()=>{d("idle"),m("")},2500)}catch{d("error"),m(t("spoolbuddy.writeTag.untagFailed","Failed to remove tag from spool"))}finally{f(!1)}}},pe=w.useCallback(ge=>{s(ge),d("idle"),m(""),N()},[N]),K=a&&A&&c!=="writing"&&c!=="success",se=w.useCallback(()=>{k("nfc")},[]),de=w.useCallback(()=>{k("scale")},[]);return i.jsxs("div",{className:"flex flex-col h-full",children:[_&&i.jsx(wle,{type:_,onClose:()=>k(null),deviceId:j?.device_id||""}),i.jsx("div",{className:"flex border-b border-bambu-dark-tertiary shrink-0",children:[{key:"existing",label:t("spoolbuddy.writeTag.tabExisting","Existing Spool")},{key:"new",label:t("spoolbuddy.writeTag.tabNew","New Spool")},{key:"replace",label:t("spoolbuddy.writeTag.tabReplace","Replace Tag")}].map(ge=>i.jsx("button",{onClick:()=>r(ge.key),className:`flex-1 py-3 text-sm font-medium transition-colors ${n===ge.key?"text-bambu-green border-b-2 border-bambu-green bg-bambu-dark":"text-zinc-400 hover:text-zinc-200 hover:bg-bambu-dark-tertiary"}`,children:ge.label},ge.key))}),i.jsxs("div",{className:"flex flex-1 overflow-hidden",children:[i.jsx("div",{className:"flex-1 flex flex-col overflow-hidden border-r border-bambu-dark-tertiary",children:n==="new"?i.jsx(vrt,{currencySymbol:F,onCreated:pe,selectedSpool:a,t}):i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"p-3 shrink-0",children:i.jsx("input",{type:"text",value:o,onChange:ge=>l(ge.target.value),placeholder:t("spoolbuddy.writeTag.searchPlaceholder","Search by material, color, brand..."),className:"w-full px-3 py-2 bg-bambu-dark-tertiary border border-bambu-dark-tertiary rounded text-sm text-white placeholder-zinc-500 focus:outline-none focus:border-bambu-green"})}),i.jsx("div",{className:"flex-1 overflow-y-auto px-3 pb-3 space-y-2",children:G.length===0?i.jsx("div",{className:"text-center text-zinc-500 py-8 text-sm",children:n==="existing"?t("spoolbuddy.writeTag.noUntaggedSpools","No spools without tags"):t("spoolbuddy.writeTag.noTaggedSpools","No spools with tags")}):G.map(ge=>i.jsx(yrt,{spool:ge,selected:a?.id===ge.id,showTag:n==="replace",onClick:()=>{s(ge),d("idle"),m("")}},ge.id))})]})}),i.jsx("div",{className:"w-[340px] flex flex-col items-center justify-center p-6 shrink-0",children:i.jsx(wrt,{writeStatus:c,writeMessage:u,selectedSpool:a,tagOnReader:y,tagUid:b,deviceOnline:A,canWrite:!!K,isReplace:n==="replace",canUntag:n==="replace"&&!!a&&XY(a),untagging:p,onWrite:X,onUntag:ue,onCancel:ce,onRetry:()=>{d("idle"),m("")},onOpenNfcDiagnostics:se,onOpenScaleDiagnostics:de,t})})]})]})}function XY(t){return!!(t.tag_uid||t.tray_uuid)}function yrt({spool:t,selected:e,showTag:n,onClick:r}){const a=t.rgba?`#${t.rgba.slice(0,6)}`:"#666",s=Math.max(0,t.label_weight-t.weight_used),o=t.label_weight>0?Math.round(s/t.label_weight*100):0;return i.jsxs("button",{onClick:r,className:`w-full flex items-center gap-3 p-3 rounded-lg text-left transition-colors ${e?"bg-bambu-green/15 border border-bambu-green/50":"bg-bambu-dark-secondary hover:bg-bambu-dark-tertiary border border-transparent"}`,children:[i.jsx("div",{className:"w-8 h-8 rounded-full shrink-0 border border-white/10",style:{backgroundColor:a}}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsx("div",{className:"flex items-center gap-2",children:i.jsxs("span",{className:"text-sm font-medium text-white truncate",children:[t.brand?`${t.brand} `:"",t.material,t.subtype?` ${t.subtype}`:""]})}),i.jsxs("div",{className:"flex items-center gap-2 text-xs text-zinc-400",children:[t.color_name&&i.jsx("span",{children:t.color_name}),i.jsxs("span",{children:[s,"g / ",t.label_weight,"g (",o,"%)"]})]}),n&&t.tag_uid&&i.jsx("div",{className:"text-xs text-zinc-500 mt-0.5 font-mono",children:t.tag_uid})]}),e&&i.jsx("svg",{className:"w-5 h-5 text-bambu-green shrink-0",fill:"currentColor",viewBox:"0 0 20 20",children:i.jsx("path",{fillRule:"evenodd",d:"M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z",clipRule:"evenodd"})})]})}function vrt({currencySymbol:t,onCreated:e,selectedSpool:n,t:r}){const[a,s]=w.useState("simple"),[o,l]=w.useState("filament"),[c,d]=w.useState(AL),[u,m]=w.useState({}),[p,f]=w.useState(!1),[y,v]=w.useState(1),[b,g]=w.useState(!1),[_,k]=w.useState(null),[C,N]=w.useState(!1),[P,T]=w.useState(!1),[j,A]=w.useState([]),[F,G]=w.useState([]),[z,Z]=w.useState([]),[I,ee]=w.useState([]),[ae,X]=w.useState(""),[ce,ue]=w.useState([]),[pe,K]=w.useState([]),[se,de]=w.useState(new Set),[ge,Te]=w.useState(new Set);w.useEffect(()=>{ue(lle())},[]),w.useEffect(()=>{(async()=>{if(a==="full"){T(!0);try{const fe=await be.getCloudStatus();if(N(fe.is_authenticated),fe.is_authenticated){const re=await be.getFilamentPresets();A(re)}}catch{N(!1)}finally{T(!1)}be.getSpoolCatalog().then(Z).catch(()=>{}),be.getColorCatalog().then(ee).catch(()=>{}),be.getLocalPresets().then(fe=>G(fe.filament)).catch(()=>{});try{const fe=await be.getPrinters(),re=await Promise.all(fe.map(R=>be.getPrinterStatus(R.id).catch(()=>null))),L=[];for(let R=0;R({cali_idx:xe.slot_id,filament_id:xe.filament_id,setting_id:xe.setting_id||"",name:xe.name,k_value:parseFloat(xe.k_value)||0,n_coef:parseFloat(xe.n_coef)||0,extruder_id:xe.extruder_id,nozzle_diameter:xe.nozzle_diameter}))}catch{}L.push({printer:{...ne,connected:we},calibrations:me})}K(L)}catch{}}})()},[a]),w.useEffect(()=>{pe.length>0&&Te(new Set(pe.map(he=>String(he.printer.id))))},[pe]);const V=w.useMemo(()=>sle(j,new Set,F),[j,F]),J=w.useMemo(()=>ole(c.slicer_filament,V),[c.slicer_filament,V]),D=w.useMemo(()=>{const he=ale(j,F),fe=I.map(re=>re.manufacturer?.trim()).filter(re=>!!re);return Array.from(new Set([...he,...fe])).sort((re,L)=>re.localeCompare(L))},[j,F,I]),E=w.useMemo(()=>{const he=I.map(fe=>fe.material?.trim()).filter(fe=>!!fe);return Array.from(new Set([...nle,...he])).sort((fe,re)=>fe.localeCompare(re))},[I]),U=w.useMemo(()=>{const he=[];for(const fe of I){const re=fe.manufacturer?.trim(),L=fe.material?.trim();re&&L&&he.push({brand:re,material:L})}for(const fe of j){const re=Qh(fe.name);re.brand&&re.material&&he.push({brand:re.brand,material:re.material})}for(const fe of F){const re=Qh(fe.name),L=fe.filament_vendor?.trim()||re.brand,R=re.material;L&&R&&he.push({brand:L,material:R})}return he},[j,I,F]),W=w.useMemo(()=>{const he=new Map;for(const fe of U){const re=fe.brand.toLowerCase(),L=fe.material.toLowerCase();he.has(re)||he.set(re,new Set),he.get(re).add(L)}return he},[U]),B=w.useMemo(()=>{const he=new Map;for(const fe of U){const re=fe.brand.toLowerCase(),L=fe.material.toLowerCase();he.has(L)||he.set(L,new Set),he.get(L).add(re)}return he},[U]),ie=w.useMemo(()=>{if(!c.material)return D;const he=c.material.toLowerCase(),fe=B.get(he);return!fe||fe.size===0?D:D.filter(re=>fe.has(re.toLowerCase()))},[D,c.material,B]),O=w.useMemo(()=>{if(!c.brand)return E;const he=c.brand.toLowerCase(),fe=W.get(he);return!fe||fe.size===0?E:E.filter(re=>fe.has(re.toLowerCase()))},[E,c.brand,W]),$=(he,fe)=>{d(re=>({...re,[he]:fe})),u[he]&&m(re=>({...re,[he]:void 0}))},Y=he=>{ue(fe=>cle(he,fe))},q=async he=>{if(se.size===0){try{await be.saveSpoolKProfiles(he,[])}catch{}return}const fe=[];for(const re of se){const[L,R,ne]=re.split(":"),ve=parseInt(L),we=parseInt(R),me=ne==="null"?0:parseInt(ne),Me=pe.find(xe=>xe.printer.id===ve);if(Me){const xe=Me.calibrations.find(je=>je.cali_idx===we);xe&&fe.push({printer_id:ve,extruder:me,nozzle_diameter:xe.nozzle_diameter||"0.4",k_value:xe.k_value,name:xe.name||null,cali_idx:xe.cali_idx,setting_id:xe.setting_id||null})}}fe.length>0&&await be.saveSpoolKProfiles(he,fe)},te=async()=>{k(null);const he=tle(c,a==="simple"?!0:p);if(!he.isValid){m(he.errors),l("filament");return}const fe=J?.displayName||ae||null,re={material:c.material,subtype:c.subtype||null,brand:c.brand||null,color_name:c.color_name||null,rgba:c.rgba||null,label_weight:c.label_weight,core_weight:c.core_weight,core_weight_catalog_id:c.core_weight_catalog_id,weight_used:c.weight_used,slicer_filament:c.slicer_filament||null,slicer_filament_name:fe,nozzle_temp_min:null,nozzle_temp_max:null,note:c.note||null,cost_per_kg:c.cost_per_kg,added_full:null,last_used:null,encode_time:null,tag_uid:null,tray_uuid:null,data_origin:null,tag_type:null,last_scale_weight:null,last_weighed_at:null};g(!0);try{if(y>1){const L=await be.bulkCreateSpools(re,y);for(const R of L)await q(R.id);L.length>0&&e(L[0])}else{const L=await be.createSpool(re);await q(L.id),e(L)}}catch{k(r("spoolbuddy.writeTag.createFailed","Failed to create spool"))}finally{g(!1)}},oe=`#${(c.rgba||"808080FF").slice(0,6)}`;return i.jsxs("div",{className:"p-3 space-y-3 overflow-y-auto h-full",children:[i.jsxs("div",{className:"flex items-center justify-between px-2 py-2 bg-bambu-dark-secondary rounded-lg border border-bambu-dark-tertiary",children:[i.jsx("span",{className:"text-sm text-zinc-200",children:r("spoolbuddy.writeTag.viewMode","View")}),i.jsxs("div",{className:"flex rounded-lg overflow-hidden border border-bambu-dark-tertiary",children:[i.jsx("button",{type:"button",onClick:()=>s("simple"),className:`px-3 py-1.5 text-xs font-medium ${a==="simple"?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark text-zinc-400"}`,children:r("spoolbuddy.writeTag.simpleView","Simple")}),i.jsx("button",{type:"button",onClick:()=>s("full"),className:`px-3 py-1.5 text-xs font-medium ${a==="full"?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark text-zinc-400"}`,children:r("spoolbuddy.writeTag.fullView","Full")})]})]}),a==="simple"?n?i.jsxs("div",{className:"flex flex-col items-center justify-center h-full p-6 text-center bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg",children:[i.jsx("div",{className:"w-12 h-12 rounded-full mb-4 border border-white/10",style:{backgroundColor:n.rgba?`#${n.rgba.slice(0,6)}`:"#666"}}),i.jsxs("p",{className:"text-white font-medium",children:[n.brand?`${n.brand} `:"",n.material]}),n.color_name&&i.jsx("p",{className:"text-zinc-400 text-sm",children:n.color_name}),i.jsxs("p",{className:"text-zinc-500 text-xs mt-1",children:[n.label_weight,"g"]}),i.jsx("p",{className:"text-bambu-green text-sm mt-4",children:r("spoolbuddy.writeTag.spoolCreated","Spool created! Ready to write.")})]}):i.jsxs("div",{className:"p-4 space-y-4 overflow-y-auto bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-xs text-zinc-400 mb-1",children:r("spoolbuddy.writeTag.material","Material")}),i.jsx("select",{value:c.material,onChange:he=>$("material",he.target.value),className:"w-full px-3 py-2 bg-bambu-dark-tertiary border border-bambu-dark-tertiary rounded text-sm text-white focus:outline-none focus:border-bambu-green",children:brt.map(he=>i.jsx("option",{value:he,children:he},he))})]}),i.jsxs("div",{className:"flex gap-3",children:[i.jsxs("div",{className:"flex-1",children:[i.jsx("label",{className:"block text-xs text-zinc-400 mb-1",children:r("spoolbuddy.writeTag.colorName","Color Name")}),i.jsx("input",{type:"text",value:c.color_name,onChange:he=>$("color_name",he.target.value),placeholder:"Jade White",className:"w-full px-3 py-2 bg-bambu-dark-tertiary border border-bambu-dark-tertiary rounded text-sm text-white placeholder-zinc-500 focus:outline-none focus:border-bambu-green"})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-xs text-zinc-400 mb-1",children:r("spoolbuddy.writeTag.color","Color")}),i.jsx("input",{type:"color",value:oe,onChange:he=>$("rgba",he.target.value.replace("#","").toUpperCase()+"FF"),className:"w-10 h-9 bg-transparent border border-bambu-dark-tertiary rounded cursor-pointer"})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-xs text-zinc-400 mb-1",children:r("spoolbuddy.writeTag.brand","Brand")}),i.jsx("input",{type:"text",value:c.brand,onChange:he=>$("brand",he.target.value),placeholder:"Polymaker",className:"w-full px-3 py-2 bg-bambu-dark-tertiary border border-bambu-dark-tertiary rounded text-sm text-white placeholder-zinc-500 focus:outline-none focus:border-bambu-green"})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-xs text-zinc-400 mb-1",children:r("spoolbuddy.writeTag.weight","Weight (g)")}),i.jsx("input",{type:"number",value:c.label_weight,onChange:he=>$("label_weight",parseInt(he.target.value)||0),min:0,max:1e4,className:"w-full px-3 py-2 bg-bambu-dark-tertiary border border-bambu-dark-tertiary rounded text-sm text-white focus:outline-none focus:border-bambu-green"})]}),i.jsx("button",{onClick:te,disabled:b||!c.material,className:"w-full py-2.5 bg-bambu-green hover:bg-bambu-green/80 disabled:opacity-50 disabled:cursor-not-allowed text-white text-sm font-medium rounded transition-colors",children:b?r("spoolbuddy.writeTag.creating","Creating..."):r("spoolbuddy.writeTag.createSpool","Create Spool")})]}):i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"flex items-center justify-between px-2 py-2 bg-bambu-dark-secondary rounded-lg border border-bambu-dark-tertiary",children:[i.jsx("span",{className:"text-sm text-zinc-200",children:r("inventory.quickAdd","Quick Add")}),i.jsx("button",{type:"button",onClick:()=>f(he=>!he),className:`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${p?"bg-bambu-green":"bg-bambu-dark-tertiary"}`,children:i.jsx("span",{className:`inline-block h-4.5 w-4.5 rounded-full bg-white transition-transform ${p?"translate-x-6":"translate-x-1"}`})})]}),i.jsxs("div",{className:"flex border border-bambu-dark-tertiary rounded-lg overflow-hidden",children:[i.jsx("button",{onClick:()=>l("filament"),className:`flex-1 py-2.5 text-sm font-medium ${o==="filament"?"bg-bambu-green/15 text-bambu-green":"bg-bambu-dark-secondary text-zinc-400"}`,children:r("inventory.filamentInfoTab","Filament")}),!p&&i.jsx("button",{onClick:()=>l("pa-profile"),className:`flex-1 py-2.5 text-sm font-medium ${o==="pa-profile"?"bg-bambu-green/15 text-bambu-green":"bg-bambu-dark-secondary text-zinc-400"}`,children:r("inventory.paProfileTab","PA Profile")})]}),i.jsx("div",{className:"bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg p-3",children:o==="filament"?i.jsxs("div",{className:"space-y-4",children:[i.jsx(dle,{formData:c,updateField:$,cloudAuthenticated:C,loadingCloudPresets:P,presetInputValue:ae,setPresetInputValue:X,selectedPresetOption:J,filamentOptions:V,availableBrands:ie,availableMaterials:O,quickAdd:p,quantity:y,onQuantityChange:v,errors:u}),i.jsx(ule,{formData:c,updateField:$,recentColors:ce,onColorUsed:Y,catalogColors:I}),i.jsx(mle,{formData:c,updateField:$,spoolCatalog:z,currencySymbol:t})]}):i.jsx(hle,{formData:c,updateField:$,printersWithCalibrations:pe,selectedProfiles:se,setSelectedProfiles:de,expandedPrinters:ge,setExpandedPrinters:Te})})]}),_&&i.jsx("div",{className:"text-sm text-red-400 bg-red-900/20 border border-red-900/40 rounded-lg px-3 py-2",children:_}),a==="full"&&i.jsx("button",{onClick:te,disabled:b,className:"w-full py-3 bg-bambu-green hover:bg-bambu-green/80 disabled:opacity-50 disabled:cursor-not-allowed text-white text-sm font-medium rounded transition-colors",children:b?r("spoolbuddy.writeTag.creating","Creating..."):r("spoolbuddy.writeTag.createSpool","Create Spool")}),a==="full"&&n&&i.jsxs("div",{className:"flex flex-col items-center justify-center p-4 text-center bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg",children:[i.jsx("div",{className:"w-12 h-12 rounded-full mb-4 border border-white/10",style:{backgroundColor:n.rgba?`#${n.rgba.slice(0,6)}`:"#666"}}),i.jsxs("p",{className:"text-white font-medium",children:[n.brand?`${n.brand} `:"",n.material]}),n.color_name&&i.jsx("p",{className:"text-zinc-400 text-sm",children:n.color_name}),i.jsxs("p",{className:"text-zinc-500 text-xs mt-1",children:[n.label_weight,"g"]}),i.jsx("p",{className:"text-bambu-green text-sm mt-4",children:r("spoolbuddy.writeTag.spoolCreated","Spool created! Ready to write.")})]})]})}function wrt({writeStatus:t,writeMessage:e,selectedSpool:n,tagOnReader:r,tagUid:a,deviceOnline:s,canWrite:o,isReplace:l,canUntag:c,untagging:d,onWrite:u,onUntag:m,onCancel:p,onRetry:f,onOpenNfcDiagnostics:y,onOpenScaleDiagnostics:v,t:b}){if(t==="success")return i.jsxs("div",{className:"flex flex-col items-center text-center space-y-4",children:[i.jsx("div",{className:"w-16 h-16 rounded-full bg-green-500/20 flex items-center justify-center",children:i.jsx("svg",{className:"w-8 h-8 text-green-400",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 13l4 4L19 7"})})}),i.jsx("p",{className:"text-green-400 font-medium",children:e}),n&&i.jsxs("p",{className:"text-zinc-400 text-sm",children:[n.brand?`${n.brand} `:"",n.material,n.color_name?` - ${n.color_name}`:""]})]});if(t==="error")return i.jsxs("div",{className:"flex flex-col items-center text-center space-y-4",children:[i.jsx("div",{className:"w-16 h-16 rounded-full bg-red-500/20 flex items-center justify-center",children:i.jsx("svg",{className:"w-8 h-8 text-red-400",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})}),i.jsx("p",{className:"text-red-400 font-medium",children:e}),i.jsx("button",{onClick:f,className:"px-4 py-2 bg-bambu-dark-tertiary hover:bg-bambu-dark-secondary text-white text-sm rounded transition-colors",children:b("spoolbuddy.writeTag.tryAgain","Try Again")})]});if(t==="writing")return i.jsxs("div",{className:"flex flex-col items-center text-center space-y-4",children:[i.jsxs("div",{className:"relative w-16 h-16",children:[i.jsx("div",{className:"absolute inset-0 rounded-full border-2 border-bambu-green/30 animate-ping"}),i.jsx("div",{className:"absolute inset-2 rounded-full border-2 border-bambu-green/50 animate-pulse"}),i.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:i.jsx(jv,{className:"w-8 h-8 text-bambu-green"})})]}),i.jsx("p",{className:"text-bambu-green font-medium",children:b("spoolbuddy.writeTag.writing","Writing tag...")}),i.jsx("p",{className:"text-zinc-500 text-xs",children:e}),i.jsx("button",{onClick:p,className:"px-4 py-2 bg-bambu-dark-tertiary hover:bg-bambu-dark-secondary text-zinc-400 text-sm rounded transition-colors",children:b("spoolbuddy.writeTag.cancel","Cancel")})]});if(!s)return i.jsxs("div",{className:"flex flex-col items-center text-center space-y-3",children:[i.jsx(jv,{className:"w-12 h-12 text-zinc-600"}),i.jsx("p",{className:"text-zinc-500 text-sm",children:b("spoolbuddy.writeTag.deviceOffline","SpoolBuddy is offline")})]});if(!n)return i.jsxs("div",{className:"flex flex-col items-center text-center space-y-3",children:[i.jsx(jv,{className:"w-12 h-12 text-zinc-600"}),i.jsx("p",{className:"text-zinc-400 text-sm",children:b("spoolbuddy.writeTag.selectSpool","Select a spool, then place a blank NTAG on the reader")})]});const g=n.rgba?`#${n.rgba.slice(0,6)}`:"#666";return i.jsxs("div",{className:"flex flex-col items-center text-center space-y-4 w-full",children:[i.jsx("div",{className:"relative w-16 h-16",children:r?i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"absolute inset-0 rounded-full bg-bambu-green/10"}),i.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:i.jsx(jv,{className:"w-8 h-8 text-bambu-green"})})]}):i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"absolute inset-0 rounded-full border-2 border-zinc-600 animate-pulse"}),i.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:i.jsx(jv,{className:"w-8 h-8 text-zinc-500"})})]})}),r?i.jsxs("div",{className:"space-y-1",children:[i.jsx("p",{className:"text-bambu-green text-sm font-medium",children:b("spoolbuddy.writeTag.tagReady","Tag detected — ready to write")}),a&&i.jsx("p",{className:"text-zinc-500 text-xs font-mono",children:a})]}):i.jsx("p",{className:"text-zinc-400 text-sm",children:b("spoolbuddy.writeTag.placeTag","Place an NTAG on the reader")}),i.jsxs("div",{className:"w-full bg-bambu-dark-secondary rounded-lg p-3 space-y-2",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:"w-8 h-8 rounded-full border border-white/10 shrink-0",style:{backgroundColor:g}}),i.jsxs("div",{className:"text-left min-w-0",children:[i.jsxs("p",{className:"text-white text-sm font-medium truncate",children:[n.brand?`${n.brand} `:"",n.material]}),n.color_name&&i.jsx("p",{className:"text-zinc-400 text-xs",children:n.color_name})]})]}),i.jsxs("div",{className:"text-xs text-zinc-500",children:[n.label_weight,"g"]})]}),l&&n.tag_uid&&i.jsx("p",{className:"text-yellow-500/80 text-xs",children:b("spoolbuddy.writeTag.replaceWarning","Old tag will be unlinked. New tag will replace it.")}),i.jsx("button",{onClick:u,disabled:!o,className:"w-full py-3 bg-bambu-green hover:bg-bambu-green/80 disabled:opacity-40 disabled:cursor-not-allowed text-white font-medium rounded-lg transition-colors text-sm",children:l?b("spoolbuddy.writeTag.replaceTag","Replace Tag"):b("spoolbuddy.writeTag.writeTag","Write Tag")}),l&&c&&i.jsx("button",{onClick:m,disabled:d,className:"w-full py-2.5 bg-bambu-dark-tertiary hover:bg-bambu-dark-secondary disabled:opacity-40 disabled:cursor-not-allowed text-zinc-200 rounded-lg transition-colors text-sm",children:d?b("spoolbuddy.writeTag.untagging","Removing tag..."):b("spoolbuddy.writeTag.untagSpool","Untag Selected Spool")}),i.jsxs("div",{className:"w-full flex gap-2 pt-2",children:[i.jsx("button",{onClick:y,className:"flex-1 py-2 px-2 bg-bambu-dark-tertiary hover:bg-bambu-dark-secondary text-zinc-300 text-xs rounded transition-colors",children:b("spoolbuddy.writeTag.nfcDiagnostics","NFC Diag")}),i.jsx("button",{onClick:v,className:"flex-1 py-2 px-2 bg-bambu-dark-tertiary hover:bg-bambu-dark-secondary text-zinc-300 text-xs rounded transition-colors",children:b("spoolbuddy.writeTag.scaleDiagnostics","Scale Diag")})]})]})}function jv({className:t}){return i.jsxs("svg",{className:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:1.5,children:[i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M8.288 15.038a5.25 5.25 0 017.424 0M5.106 11.856c3.807-3.808 9.98-3.808 13.788 0M1.924 8.674c5.565-5.565 14.587-5.565 20.152 0"}),i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12.53 18.22l-.53.53-.53-.53a.75.75 0 011.06 0z"})]})}const Srt=new ghe({defaultOptions:{queries:{staleTime:1e3*60,retry:1}}});function QY({children:t}){return Snt(),i.jsx(i.Fragment,{children:t})}function ZY({children:t}){const{authEnabled:e,loading:n,user:r}=Ar();return n?i.jsx("div",{className:"min-h-screen flex items-center justify-center",children:"Loading..."}):e&&!r?i.jsx(dx,{to:"/login",replace:!0}):i.jsx(i.Fragment,{children:t})}function s3({children:t}){const{authEnabled:e,loading:n,user:r,isAdmin:a}=Ar();return n?i.jsx("div",{className:"min-h-screen flex items-center justify-center",children:"Loading..."}):e?r?a?i.jsx(i.Fragment,{children:t}):i.jsx(dx,{to:"/",replace:!0}):i.jsx(dx,{to:"/login",replace:!0}):i.jsx(i.Fragment,{children:t})}function _rt({children:t}){const{authEnabled:e,loading:n}=Ar();return n?i.jsx("div",{className:"min-h-screen flex items-center justify-center",children:"Loading..."}):e?i.jsx(dx,{to:"/login",replace:!0}):i.jsx(i.Fragment,{children:t})}function krt(){return i.jsx(uxe,{children:i.jsx(yxe,{children:i.jsx(bhe,{client:Srt,children:i.jsx(bxe,{children:i.jsx(Lme,{children:i.jsxs(ume,{children:[i.jsx(Nr,{path:"/setup",element:i.jsx(_rt,{children:i.jsx(vnt,{})})}),i.jsx(Nr,{path:"/login",element:i.jsx(ynt,{})}),i.jsx(Nr,{path:"/camera/:printerId",element:i.jsx(Htt,{})}),i.jsx(Nr,{path:"/overlay/:printerId",element:i.jsx(Gtt,{})}),i.jsxs(Nr,{element:i.jsx(ZY,{children:i.jsx(QY,{children:i.jsx(Lnt,{})})}),children:[i.jsx(Nr,{path:"spoolbuddy",element:i.jsx(nrt,{})}),i.jsx(Nr,{path:"spoolbuddy/ams",element:i.jsx(art,{})}),i.jsx(Nr,{path:"spoolbuddy/write-tag",element:i.jsx(xrt,{})}),i.jsx(Nr,{path:"spoolbuddy/settings",element:i.jsx(prt,{})}),i.jsx(Nr,{path:"spoolbuddy/calibration",element:i.jsx(grt,{})})]}),i.jsxs(Nr,{element:i.jsx(ZY,{children:i.jsx(QY,{children:i.jsx(Dxe,{})})}),children:[i.jsx(Nr,{index:!0,element:i.jsx(DVe,{})}),i.jsx(Nr,{path:"archives",element:i.jsx(NZe,{})}),i.jsx(Nr,{path:"queue",element:i.jsx(det,{})}),i.jsx(Nr,{path:"stats",element:i.jsx(Pet,{})}),i.jsx(Nr,{path:"profiles",element:i.jsx(ytt,{})}),i.jsx(Nr,{path:"maintenance",element:i.jsx(ktt,{})}),i.jsx(Nr,{path:"projects",element:i.jsx(Ctt,{})}),i.jsx(Nr,{path:"projects/:id",element:i.jsx(Ett,{})}),i.jsx(Nr,{path:"inventory",element:i.jsx(unt,{})}),i.jsx(Nr,{path:"files",element:i.jsx(Itt,{})}),i.jsx(Nr,{path:"settings",element:i.jsx(s3,{children:i.jsx(att,{})})}),i.jsx(Nr,{path:"groups/new",element:i.jsx(s3,{children:i.jsx(zY,{})})}),i.jsx(Nr,{path:"groups/:id/edit",element:i.jsx(s3,{children:i.jsx(zY,{})})}),i.jsx(Nr,{path:"users",element:i.jsx(dx,{to:"/settings?tab=users",replace:!0})}),i.jsx(Nr,{path:"groups",element:i.jsx(dx,{to:"/settings?tab=users",replace:!0})}),i.jsx(Nr,{path:"system",element:i.jsx(xnt,{})}),i.jsx(Nr,{path:"notifications",element:i.jsx(wnt,{})}),i.jsx(Nr,{path:"external/:id",element:i.jsx(Wtt,{})})]})]})})})})})})}sde.createRoot(document.getElementById("root")).render(i.jsx(w.StrictMode,{children:i.jsx(krt,{})})); diff --git a/static/index.html b/static/index.html index 204733e80..c38a46fc7 100644 --- a/static/index.html +++ b/static/index.html @@ -23,7 +23,7 @@ - +